ethers
- Version 6.13.5
- Published
- 12.6 MB
- 7 dependencies
- MIT license
Install
npm i ethers
yarn add ethers
pnpm add ethers
Overview
A complete and compact Ethereum library, for dapps, wallets and any other tools.
Index
Variables
Functions
- accessListify()
- assert()
- assertArgument()
- assertArgumentCount()
- assertNormalize()
- assertPrivate()
- checkResultErrors()
- computeAddress()
- computeHmac()
- concat()
- copyRequest()
- dataLength()
- dataSlice()
- decodeBase58()
- decodeBase64()
- decodeBytes32String()
- decodeRlp()
- decryptCrowdsaleJson()
- decryptKeystoreJson()
- decryptKeystoreJsonSync()
- defineProperties()
- dnsEncode()
- encodeBase58()
- encodeBase64()
- encodeBytes32String()
- encodeRlp()
- encryptKeystoreJson()
- encryptKeystoreJsonSync()
- ensNormalize()
- formatEther()
- formatUnits()
- fromTwos()
- getAccountPath()
- getAddress()
- getBigInt()
- getBytes()
- getBytesCopy()
- getCreate2Address()
- getCreateAddress()
- getDefaultProvider()
- getIcapAddress()
- getIndexedAccountPath()
- getNumber()
- getUint()
- hashMessage()
- hexlify()
- id()
- isAddress()
- isAddressable()
- isBytesLike()
- isCallException()
- isCrowdsaleJson()
- isError()
- isHexString()
- isKeystoreJson()
- isValidName()
- keccak256()
- lock()
- makeError()
- mask()
- namehash()
- parseEther()
- parseUnits()
- pbkdf2()
- randomBytes()
- recoverAddress()
- resolveAddress()
- resolveProperties()
- ripemd160()
- scrypt()
- scryptSync()
- sha256()
- sha512()
- showThrottleMessage()
- solidityPacked()
- solidityPackedKeccak256()
- solidityPackedSha256()
- stripZerosLeft()
- toBeArray()
- toBeHex()
- toBigInt()
- toNumber()
- toQuantity()
- toTwos()
- toUtf8Bytes()
- toUtf8CodePoints()
- toUtf8String()
- uuidV4()
- verifyMessage()
- verifyTypedData()
- zeroPadBytes()
- zeroPadValue()
Classes
AbstractProvider
- addListener()
- attachPlugin()
- broadcastTransaction()
- call()
- ccipReadFetch()
- destroy()
- destroyed
- disableCcipRead
- emit()
- estimateGas()
- getAvatar()
- getBalance()
- getBlock()
- getBlockNumber()
- getCode()
- getFeeData()
- getLogs()
- getNetwork()
- getPlugin()
- getResolver()
- getStorage()
- getTransaction()
- getTransactionCount()
- getTransactionReceipt()
- getTransactionResult()
- listenerCount()
- listeners()
- lookupAddress()
- off()
- on()
- once()
- pause()
- paused
- plugins
- pollingInterval
- provider
- removeAllListeners()
- removeListener()
- resolveName()
- resume()
- waitForBlock()
- waitForTransaction()
BaseContract
- [internal]
- addListener()
- attach()
- buildClass()
- connect()
- deploymentTransaction()
- emit()
- fallback
- filters
- from()
- getAddress()
- getDeployedCode()
- getEvent()
- getFunction()
- interface
- listenerCount()
- listeners()
- off()
- on()
- once()
- queryFilter()
- queryTransaction()
- removeAllListeners()
- removeListener()
- runner
- target
- waitForDeployment()
Block
- [Symbol.iterator]()
- baseFeePerGas
- blobGasUsed
- date
- difficulty
- excessBlobGas
- extraData
- gasLimit
- gasUsed
- getPrefetchedTransaction()
- getTransaction()
- hash
- isLondon()
- isMined()
- length
- miner
- nonce
- number
- orphanedEvent()
- parentBeaconBlockRoot
- parentHash
- prefetchedTransactions
- prevRandao
- provider
- receiptsRoot
- stateRoot
- timestamp
- toJSON()
- transactions
FetchRequest
- [Symbol.iterator]()
- allowGzip
- allowInsecureAuthentication
- body
- cancel()
- clearHeaders()
- clone()
- createDataGateway()
- createGetUrlFunc()
- createIpfsGatewayFunc()
- credentials
- getGateway()
- getHeader()
- getUrlFunc
- hasBody()
- headers
- lockConfig()
- method
- preflightFunc
- processFunc
- redirect()
- registerGateway()
- registerGetUrl()
- retryFunc
- send()
- setCredentials()
- setHeader()
- setThrottleParams()
- timeout
- toString()
- url
Interface
- decodeErrorResult()
- decodeEventLog()
- decodeFunctionData()
- decodeFunctionResult()
- deploy
- encodeDeploy()
- encodeErrorResult()
- encodeEventLog()
- encodeFilterTopics()
- encodeFunctionData()
- encodeFunctionResult()
- fallback
- forEachError()
- forEachEvent()
- forEachFunction()
- format()
- formatJson()
- fragments
- from()
- getAbiCoder()
- getError()
- getEvent()
- getEventName()
- getFunction()
- getFunctionName()
- hasEvent()
- hasFunction()
- makeError()
- parseCallResult()
- parseError()
- parseLog()
- parseTransaction()
- receive
Transaction
- accessList
- blobs
- blobVersionedHashes
- chainId
- clone()
- data
- from
- from()
- fromPublicKey
- gasLimit
- gasPrice
- hash
- inferType()
- inferTypes()
- isBerlin()
- isCancun()
- isLegacy()
- isLondon()
- isSigned()
- kzg
- maxFeePerBlobGas
- maxFeePerGas
- maxPriorityFeePerGas
- nonce
- serialized
- signature
- to
- toJSON()
- type
- typeName
- unsignedHash
- unsignedSerialized
- value
TransactionResponse
- accessList
- blobVersionedHashes
- blockHash
- blockNumber
- chainId
- confirmations()
- data
- from
- gasLimit
- gasPrice
- getBlock()
- getTransaction()
- hash
- index
- isBerlin()
- isCancun()
- isLegacy()
- isLondon()
- isMined()
- maxFeePerBlobGas
- maxFeePerGas
- maxPriorityFeePerGas
- nonce
- provider
- removedEvent()
- reorderedEvent()
- replaceableTransaction()
- signature
- to
- toJSON()
- type
- value
- wait()
Typed
- address()
- array()
- arrayLength
- bool()
- bytes()
- bytes1()
- bytes10()
- bytes11()
- bytes12()
- bytes13()
- bytes14()
- bytes15()
- bytes16()
- bytes17()
- bytes18()
- bytes19()
- bytes2()
- bytes20()
- bytes21()
- bytes22()
- bytes23()
- bytes24()
- bytes25()
- bytes26()
- bytes27()
- bytes28()
- bytes29()
- bytes3()
- bytes30()
- bytes31()
- bytes32()
- bytes4()
- bytes5()
- bytes6()
- bytes7()
- bytes8()
- bytes9()
- defaultValue()
- dereference()
- format()
- from()
- int()
- int104()
- int112()
- int120()
- int128()
- int136()
- int144()
- int152()
- int16()
- int160()
- int168()
- int176()
- int184()
- int192()
- int200()
- int208()
- int216()
- int224()
- int232()
- int24()
- int240()
- int248()
- int256()
- int32()
- int40()
- int48()
- int56()
- int64()
- int72()
- int8()
- int80()
- int88()
- int96()
- isBigInt()
- isData()
- isString()
- isTyped()
- maxValue()
- minValue()
- overrides()
- string()
- tuple()
- tupleName
- type
- uint()
- uint104()
- uint112()
- uint120()
- uint128()
- uint136()
- uint144()
- uint152()
- uint16()
- uint160()
- uint168()
- uint176()
- uint184()
- uint192()
- uint200()
- uint208()
- uint216()
- uint224()
- uint232()
- uint24()
- uint240()
- uint248()
- uint256()
- uint32()
- uint40()
- uint48()
- uint56()
- uint64()
- uint72()
- uint8()
- uint80()
- uint88()
- uint96()
- value
Interfaces
Type Aliases
- AbstractProviderOptions
- AccessList
- AccessListEntry
- AccessListish
- AddressLike
- BigNumberish
- BlobLike
- BlockTag
- BrowserProviderOptions
- BytesLike
- CallExceptionAction
- CallExceptionTransaction
- CodedEthersError
- ContractEventArgs
- ContractEventName
- ContractMethodArgs
- CrowdsaleAccount
- DebugEventBrowserProvider
- EncryptOptions
- ErrorCode
- FallbackProviderOptions
- FetchGatewayFunc
- FetchGetUrlFunc
- FetchPreflightFunc
- FetchProcessFunc
- FetchRetryFunc
- FixedFormat
- FormatType
- FragmentType
- GasCostParameters
- GetUrlResponse
- InterfaceAbi
- JsonRpcApiProviderOptions
- JsonRpcError
- JsonRpcPayload
- JsonRpcResult
- KeystoreAccount
- Listener
- Networkish
- Numeric
- OrphanFilter
- ParamTypeWalkAsyncFunc
- ParamTypeWalkFunc
- PerformActionFilter
- PerformActionRequest
- PostfixOverrides
- ProgressCallback
- ProviderEvent
- RlpStructuredData
- RlpStructuredDataish
- SignatureLike
- Subscription
- TopicFilter
- UnicodeNormalizationForm
- Utf8ErrorFunc
- Utf8ErrorReason
- WebSocketCreator
Namespaces
ethers
- AbiCoder
- AbstractProvider
- AbstractProviderOptions
- AbstractProviderPlugin
- AbstractSigner
- AccessList
- AccessListEntry
- accessListify()
- AccessListish
- ActionRejectedError
- Addressable
- AddressLike
- AlchemyProvider
- AnkrProvider
- assert()
- assertArgument()
- assertArgumentCount()
- assertNormalize()
- assertPrivate()
- BadDataError
- BaseContract
- BaseContractMethod
- BaseWallet
- BigNumberish
- Blob
- BlobLike
- Block
- BlockParams
- BlockTag
- BrowserProvider
- BrowserProviderOptions
- BufferOverrunError
- BytesLike
- CallExceptionAction
- CallExceptionError
- CallExceptionTransaction
- CancelledError
- ChainstackProvider
- checkResultErrors()
- CloudflareProvider
- CodedEthersError
- computeAddress()
- computeHmac()
- concat()
- ConstantContractMethod
- ConstructorFragment
- Contract
- ContractDeployTransaction
- ContractEvent
- ContractEventArgs
- ContractEventName
- ContractEventPayload
- ContractFactory
- ContractInterface
- ContractMethod
- ContractMethodArgs
- ContractRunner
- ContractTransaction
- ContractTransactionReceipt
- ContractTransactionResponse
- ContractUnknownEventPayload
- copyRequest()
- CrowdsaleAccount
- dataLength()
- dataSlice()
- DebugEventBrowserProvider
- decodeBase58()
- decodeBase64()
- decodeBytes32String()
- decodeRlp()
- decryptCrowdsaleJson()
- decryptKeystoreJson()
- decryptKeystoreJsonSync()
- defaultPath
- DeferredTopicFilter
- defineProperties()
- dnsEncode()
- Eip1193Provider
- encodeBase58()
- encodeBase64()
- encodeBytes32String()
- encodeRlp()
- encryptKeystoreJson()
- encryptKeystoreJsonSync()
- EncryptOptions
- ensNormalize()
- EnsPlugin
- EnsResolver
- ErrorCode
- ErrorDescription
- ErrorFragment
- EtherscanPlugin
- EtherscanProvider
- EthersError
- EtherSymbol
- EventEmitterable
- EventFilter
- EventFragment
- EventLog
- EventPayload
- FallbackFragment
- FallbackProvider
- FallbackProviderOptions
- FeeData
- FeeDataNetworkPlugin
- FetchCancelSignal
- FetchGatewayFunc
- FetchGetUrlFunc
- FetchPreflightFunc
- FetchProcessFunc
- FetchRequest
- FetchResponse
- FetchRetryFunc
- FetchUrlFeeDataNetworkPlugin
- Filter
- FilterByBlockHash
- FixedFormat
- FixedNumber
- formatEther()
- FormatType
- formatUnits()
- Fragment
- FragmentType
- fromTwos()
- FunctionFragment
- GasCostParameters
- GasCostPlugin
- getAccountPath()
- getAddress()
- getBigInt()
- getBytes()
- getBytesCopy()
- getCreate2Address()
- getCreateAddress()
- getDefaultProvider()
- getIcapAddress()
- getIndexedAccountPath()
- getNumber()
- getUint()
- GetUrlResponse
- hashMessage()
- HDNodeVoidWallet
- HDNodeWallet
- hexlify()
- id()
- Indexed
- InfuraProvider
- InfuraWebSocketProvider
- InsufficientFundsError
- Interface
- InterfaceAbi
- InvalidArgumentError
- IpcSocketProvider
- isAddress()
- isAddressable()
- isBytesLike()
- isCallException()
- isCrowdsaleJson()
- isError()
- isHexString()
- isKeystoreJson()
- isValidName()
- JsonFragment
- JsonFragmentType
- JsonRpcApiProvider
- JsonRpcApiProviderOptions
- JsonRpcError
- JsonRpcPayload
- JsonRpcProvider
- JsonRpcResult
- JsonRpcSigner
- JsonRpcTransactionRequest
- keccak256()
- KeystoreAccount
- KzgLibrary
- LangEn
- Listener
- lock()
- Log
- LogDescription
- LogParams
- makeError()
- mask()
- MaxInt256
- MaxUint256
- MessagePrefix
- MinedBlock
- MinedTransactionResponse
- MinInt256
- MissingArgumentError
- Mnemonic
- MulticoinProviderPlugin
- N
- NamedFragment
- namehash()
- NameResolver
- Network
- NetworkError
- Networkish
- NetworkPlugin
- NonceExpiredError
- NonceManager
- NotImplementedError
- Numeric
- NumericFaultError
- OffchainFaultError
- OrphanFilter
- Overrides
- ParamType
- ParamTypeWalkAsyncFunc
- ParamTypeWalkFunc
- parseEther()
- parseUnits()
- pbkdf2()
- PerformActionFilter
- PerformActionRequest
- PerformActionTransaction
- PocketProvider
- PostfixOverrides
- PreparedTransactionRequest
- ProgressCallback
- Provider
- ProviderEvent
- QuickNodeProvider
- randomBytes()
- recoverAddress()
- ReplacementUnderpricedError
- resolveAddress()
- resolveProperties()
- Result
- ripemd160()
- RlpStructuredData
- RlpStructuredDataish
- scrypt()
- scryptSync()
- ServerError
- sha256()
- sha512()
- showThrottleMessage()
- Signature
- SignatureLike
- Signer
- SigningKey
- SocketBlockSubscriber
- SocketEventSubscriber
- SocketPendingSubscriber
- SocketProvider
- SocketSubscriber
- solidityPacked()
- solidityPackedKeccak256()
- solidityPackedSha256()
- stripZerosLeft()
- StructFragment
- Subscriber
- Subscription
- TimeoutError
- toBeArray()
- toBeHex()
- toBigInt()
- toNumber()
- TopicFilter
- toQuantity()
- toTwos()
- toUtf8Bytes()
- toUtf8CodePoints()
- toUtf8String()
- Transaction
- TransactionDescription
- TransactionLike
- TransactionReceipt
- TransactionReceiptParams
- TransactionReplacedError
- TransactionRequest
- TransactionResponse
- TransactionResponseParams
- Typed
- TypedDataDomain
- TypedDataEncoder
- TypedDataField
- UnconfiguredNameError
- UndecodedEventLog
- UnexpectedArgumentError
- UnicodeNormalizationForm
- UnknownError
- UnmanagedSubscriber
- UnsupportedOperationError
- Utf8ErrorFunc
- Utf8ErrorFuncs
- Utf8ErrorReason
- uuidV4()
- verifyMessage()
- verifyTypedData()
- version
- VoidSigner
- Wallet
- WebSocketCreator
- WebSocketLike
- WebSocketProvider
- WeiPerEther
- Wordlist
- WordlistOwl
- WordlistOwlA
- wordlists
- WrappedFallback
- ZeroAddress
- ZeroHash
- zeroPadBytes()
- zeroPadValue()
Variables
variable defaultPath
const defaultPath: string;
The default derivation path for Ethereum HD Nodes. (i.e. ``"m/44'/60'/0'/0/0"``)
variable EtherSymbol
const EtherSymbol: string;
A constant for the ether symbol (normalized using NFKC).
(**i.e.** ``"\u039e"``)
variable MaxInt256
const MaxInt256: BigInt;
A constant for the maximum value for an ``int256``.
(**i.e.** ``0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn``)
variable MaxUint256
const MaxUint256: BigInt;
A constant for the maximum value for a ``uint256``.
(**i.e.** ``0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn``)
variable MessagePrefix
const MessagePrefix: string;
A constant for the [[link-eip-191]] personal message prefix.
(**i.e.** ``"\x19Ethereum Signed Message:\n"``)
variable MinInt256
const MinInt256: BigInt;
A constant for the minimum value for an ``int256``.
(**i.e.** ``-8000000000000000000000000000000000000000000000000000000000000000n``)
variable N
const N: BigInt;
A constant for the order N for the secp256k1 curve.
(**i.e.** ``0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n``)
variable Utf8ErrorFuncs
const Utf8ErrorFuncs: Readonly< Record<'error' | 'ignore' | 'replace', Utf8ErrorFunc>>;
A handful of popular, built-in UTF-8 error handling strategies.
**``"error"``** - throws on ANY illegal UTF-8 sequence or non-canonical (overlong) codepoints (this is the default)
**``"ignore"``** - silently drops any illegal UTF-8 sequence and accepts non-canonical (overlong) codepoints
**``"replace"``** - replace any illegal UTF-8 sequence with the UTF-8 replacement character (i.e. ``"\ufffd"``) and accepts non-canonical (overlong) codepoints
@returns: Record<"error" | "ignore" | "replace", Utf8ErrorFunc>
variable version
const version: string;
The current version of Ethers.
variable WeiPerEther
const WeiPerEther: BigInt;
A constant for the number of wei in a single ether.
(**i.e.** ``1000000000000000000n``)
variable wordlists
const wordlists: Record<string, Wordlist>;
The available Wordlists by their [ISO 639-1 Language Code](link-wiki-iso639).
(**i.e.** [cz](LangCz), [en](LangEn), [es](LangEs), [fr](LangFr), [ja](LangJa), [ko](LangKo), [it](LangIt), [pt](LangPt), [zh_cn](LangZh), [zh_tw](LangZh))
The dist files (in the ``/dist`` folder) have had all languages except English stripped out, which reduces the library size by about 80kb. If required, they are available by importing the included ``wordlists-extra.min.js`` file.
variable ZeroAddress
const ZeroAddress: string;
A constant for the zero address.
(**i.e.** ``"0x0000000000000000000000000000000000000000"``)
variable ZeroHash
const ZeroHash: string;
A constant for the zero hash.
(**i.e.** ``"0x0000000000000000000000000000000000000000000000000000000000000000"``)
Functions
function accessListify
accessListify: (value: AccessListish) => AccessList;
Returns a [[AccessList]] from any ethers-supported access-list structure.
function assert
assert: <K extends ErrorCode, T extends CodedEthersError<K>>( check: unknown, message: string, code: K, info?: ErrorInfo<T>) => asserts check;
Throws an EthersError with %%message%%, %%code%% and additional error %%info%% when %%check%% is falsish..
See Also
[[api:makeError]]
function assertArgument
assertArgument: ( check: unknown, message: string, name: string, value: unknown) => asserts check;
A simple helper to simply ensuring provided arguments match expected constraints, throwing if not.
In TypeScript environments, the %%check%% has been asserted true, so any further code does not need additional compile-time checks.
function assertArgumentCount
assertArgumentCount: ( count: number, expectedCount: number, message?: string) => void;
function assertNormalize
assertNormalize: (form: string) => void;
Throws if the normalization %%form%% is not supported.
function assertPrivate
assertPrivate: (givenGuard: any, guard: any, className?: string) => void;
Many classes use file-scoped values to guard the constructor, making it effectively private. This facilitates that pattern by ensuring the %%givenGaurd%% matches the file-scoped %%guard%%, throwing if not, indicating the %%className%% if provided.
function checkResultErrors
checkResultErrors: ( result: Result) => Array<{ path: Array<string | number>; error: Error }>;
Returns all errors found in a [[Result]].
Since certain errors encountered when creating a [[Result]] do not impact the ability to continue parsing data, they are deferred until they are actually accessed. Hence a faulty string in an Event that is never used does not impact the program flow.
However, sometimes it may be useful to access, identify or validate correctness of a [[Result]].
@_docloc api/abi
function computeAddress
computeAddress: (key: string | SigningKey) => string;
Returns the address for the %%key%%.
The key may be any standard form of public key or a private key.
function computeHmac
computeHmac: typeof computeHmac;
Return the HMAC for %%data%% using the %%key%% key with the underlying %%algo%% used for compression.
@example: key = id("some-secret")
// Compute the HMAC computeHmac("sha256", key, "0x1337") //_result:
// To compute the HMAC of UTF-8 data, the data must be // converted to UTF-8 bytes computeHmac("sha256", key, toUtf8Bytes("Hello World")) //_result:
function concat
concat: (datas: ReadonlyArray<BytesLike>) => string;
Returns a [[DataHexString]] by concatenating all values within %%data%%.
function copyRequest
copyRequest: (req: TransactionRequest) => PreparedTransactionRequest;
Returns a copy of %%req%% with all properties coerced to their strict types.
function dataLength
dataLength: (data: BytesLike) => number;
Returns the length of %%data%%, in bytes.
function dataSlice
dataSlice: (data: BytesLike, start?: number, end?: number) => string;
Returns a [[DataHexString]] by slicing %%data%% from the %%start%% offset to the %%end%% offset.
By default %%start%% is 0 and %%end%% is the length of %%data%%.
function decodeBase58
decodeBase58: (value: string) => bigint;
Decode the Base58-encoded %%value%%.
function decodeBase64
decodeBase64: (value: string) => Uint8Array;
Decodes the base-64 encoded %%value%%.
@example: // The decoded value is always binary data... result = decodeBase64("SGVsbG8gV29ybGQhIQ==") //_result:
// ...use toUtf8String to convert it to a string. toUtf8String(result) //_result:
// Decoding binary data decodeBase64("EjQ=") //_result:
function decodeBytes32String
decodeBytes32String: (_bytes: BytesLike) => string;
Encodes the Bytes32-encoded %%bytes%% into a string.
function decodeRlp
decodeRlp: (_data: BytesLike) => RlpStructuredData;
Decodes %%data%% into the structured data it represents.
function decryptCrowdsaleJson
decryptCrowdsaleJson: ( json: string, _password: string | Uint8Array) => CrowdsaleAccount;
Before Ethereum launched, it was necessary to create a wallet format for backers to use, which would be used to receive ether as a reward for contributing to the project.
The [[link-crowdsale]] format is now obsolete, but it is still useful to support and the additional code is fairly trivial as all the primitives required are used through core portions of the library.
function decryptKeystoreJson
decryptKeystoreJson: ( json: string, _password: string | Uint8Array, progress?: ProgressCallback) => Promise<KeystoreAccount>;
Resolves to the decrypted JSON Keystore Wallet %%json%% using the %%password%%.
If provided, %%progress%% will be called periodically during the decrpytion to provide feedback, and if the function returns ``false`` will halt decryption.
The %%progressCallback%% will **always** receive ``0`` before decryption begins and ``1`` when complete.
function decryptKeystoreJsonSync
decryptKeystoreJsonSync: ( json: string, _password: string | Uint8Array) => KeystoreAccount;
Returns the account details for the JSON Keystore Wallet %%json%% using %%password%%.
It is preferred to use the [async version](decryptKeystoreJson) instead, which allows a [[ProgressCallback]] to keep the user informed as to the decryption status.
This method will block the event loop (freezing all UI) until decryption is complete, which can take quite some time, depending on the wallet paramters and platform.
function defineProperties
defineProperties: <T>( target: T, values: { [K in keyof T]?: T[K] }, types?: { [K in keyof T]?: string }) => void;
Assigns the %%values%% to %%target%% as read-only values.
It %%types%% is specified, the values are checked.
function dnsEncode
dnsEncode: (name: string, _maxLength?: number) => string;
Returns the DNS encoded %%name%%.
This is used for various parts of ENS name resolution, such as the wildcard resolution.
function encodeBase58
encodeBase58: (_value: BytesLike) => string;
Encode %%value%% as a Base58-encoded string.
function encodeBase64
encodeBase64: (data: BytesLike) => string;
Encodes %%data%% as a base-64 encoded string.
@example: // Encoding binary data as a hexstring encodeBase64("0x1234") //_result:
// Encoding binary data as a Uint8Array encodeBase64(new Uint8Array([ 0x12, 0x34 ])) //_result:
// The input MUST be data... encodeBase64("Hello World!!") //_error:
// ...use toUtf8Bytes for this. encodeBase64(toUtf8Bytes("Hello World!!")) //_result:
function encodeBytes32String
encodeBytes32String: (text: string) => string;
Encodes %%text%% as a Bytes32 string.
function encodeRlp
encodeRlp: (object: RlpStructuredDataish) => string;
Encodes %%object%% as an RLP-encoded [[DataHexString]].
function encryptKeystoreJson
encryptKeystoreJson: ( account: KeystoreAccount, password: string | Uint8Array, options?: EncryptOptions) => Promise<string>;
Resolved to the JSON Keystore Wallet for %%account%% encrypted with %%password%%.
The %%options%% can be used to tune the password-based key derivation function parameters, explicitly set the random values used and provide a [[ProgressCallback]] to receive periodic updates on the completion status..
function encryptKeystoreJsonSync
encryptKeystoreJsonSync: ( account: KeystoreAccount, password: string | Uint8Array, options?: EncryptOptions) => string;
Return the JSON Keystore Wallet for %%account%% encrypted with %%password%%.
The %%options%% can be used to tune the password-based key derivation function parameters, explicitly set the random values used. Any provided [[ProgressCallback]] is ignord.
function ensNormalize
ensNormalize: (name: string) => string;
Returns the ENS %%name%% normalized.
function formatEther
formatEther: (wei: BigNumberish) => string;
Converts %%value%% into a //decimal string// using 18 decimal places.
function formatUnits
formatUnits: (value: BigNumberish, unit?: string | Numeric) => string;
Converts %%value%% into a //decimal string//, assuming %%unit%% decimal places. The %%unit%% may be the number of decimal places or the name of a unit (e.g. ``"gwei"`` for 9 decimal places).
function fromTwos
fromTwos: (_value: BigNumberish, _width: Numeric) => bigint;
Convert %%value%% from a twos-compliment representation of %%width%% bits to its value.
If the highest bit is ``1``, the result will be negative.
function getAccountPath
getAccountPath: (_index: Numeric) => string;
Returns the [[link-bip-32]] path for the account at %%index%%.
This is the pattern used by wallets like Ledger.
There is also an [alternate pattern](getIndexedAccountPath) used by some software.
function getAddress
getAddress: (address: string) => string;
Returns a normalized and checksumed address for %%address%%. This accepts non-checksum addresses, checksum addresses and [[getIcapAddress]] formats.
The checksum in Ethereum uses the capitalization (upper-case vs lower-case) of the characters within an address to encode its checksum, which offers, on average, a checksum of 15-bits.
If %%address%% contains both upper-case and lower-case, it is assumed to already be a checksum address and its checksum is validated, and if the address fails its expected checksum an error is thrown.
If you wish the checksum of %%address%% to be ignore, it should be converted to lower-case (i.e. ``.toLowercase()``) before being passed in. This should be a very rare situation though, that you wish to bypass the safegaurds in place to protect against an address that has been incorrectly copied from another source.
@example: // Adds the checksum (via upper-casing specific letters) getAddress("0x8ba1f109551bd432803012645ac136ddd64dba72") //_result:
// Converts ICAP address and adds checksum getAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36"); //_result:
// Throws an error if an address contains mixed case, // but the checksum fails getAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72") //_error:
function getBigInt
getBigInt: (value: BigNumberish, name?: string) => bigint;
Gets a BigInt from %%value%%. If it is an invalid value for a BigInt, then an ArgumentError will be thrown for %%name%%.
function getBytes
getBytes: (value: BytesLike, name?: string) => Uint8Array;
Get a typed Uint8Array for %%value%%. If already a Uint8Array the original %%value%% is returned; if a copy is required use [[getBytesCopy]].
@see: getBytesCopy
function getBytesCopy
getBytesCopy: (value: BytesLike, name?: string) => Uint8Array;
Get a typed Uint8Array for %%value%%, creating a copy if necessary to prevent any modifications of the returned value from being reflected elsewhere.
@see: getBytes
function getCreate2Address
getCreate2Address: ( _from: string, _salt: BytesLike, _initCodeHash: BytesLike) => string;
Returns the address that would result from a ``CREATE2`` operation with the given %%from%%, %%salt%% and %%initCodeHash%%.
To compute the %%initCodeHash%% from a contract's init code, use the [[keccak256]] function.
For a quick overview and example of ``CREATE2``, see [[link-ricmoo-wisps]].
Example 1
// The address of the contract from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"
// The salt salt = id("HelloWorld")
// The hash of the initCode initCode = "0x6394198df16000526103ff60206004601c335afa6040516060f3"; initCodeHash = keccak256(initCode)
getCreate2Address(from, salt, initCodeHash) //_result:
function getCreateAddress
getCreateAddress: (tx: { from: string; nonce: BigNumberish }) => string;
Returns the address that would result from a ``CREATE`` for %%tx%%.
This can be used to compute the address a contract will be deployed to by an EOA when sending a deployment transaction (i.e. when the ``to`` address is ``null``).
This can also be used to compute the address a contract will be deployed to by a contract, by using the contract's address as the ``to`` and the contract's nonce.
Example 1
from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"; nonce = 5;
getCreateAddress({ from, nonce }); //_result:
function getDefaultProvider
getDefaultProvider: ( network?: string | Networkish | WebSocketLike, options?: any) => AbstractProvider;
Returns a default provider for %%network%%.
If %%network%% is a [[WebSocketLike]] or string that begins with ``"ws:"`` or ``"wss:"``, a [[WebSocketProvider]] is returned backed by that WebSocket or URL.
If %%network%% is a string that begins with ``"HTTP:"`` or ``"HTTPS:"``, a [[JsonRpcProvider]] is returned connected to that URL.
Otherwise, a default provider is created backed by well-known public Web3 backends (such as [[link-infura]]) using community-provided API keys.
The %%options%% allows specifying custom API keys per backend (setting an API key to ``"-"`` will omit that provider) and ``options.exclusive`` can be set to either a backend name or and array of backend names, which will whitelist **only** those backends.
Current backend strings supported are: - ``"alchemy"`` - ``"ankr"`` - ``"cloudflare"`` - ``"chainstack"`` - ``"etherscan"`` - ``"infura"`` - ``"publicPolygon"`` - ``"quicknode"``
@example: // Connect to a local Geth node provider = getDefaultProvider("http://localhost:8545/");
// Connect to Ethereum mainnet with any current and future // third-party services available provider = getDefaultProvider("mainnet");
// Connect to Polygon, but only allow Etherscan and // INFURA and use "MY_API_KEY" in calls to Etherscan. provider = getDefaultProvider("matic", { etherscan: "MY_API_KEY", exclusive: [ "etherscan", "infura" ] });
function getIcapAddress
getIcapAddress: (address: string) => string;
The [ICAP Address format](link-icap) format is an early checksum format which attempts to be compatible with the banking industry [IBAN format](link-wiki-iban) for bank accounts.
It is no longer common or a recommended format.
@example: getIcapAddress("0x8ba1f109551bd432803012645ac136ddd64dba72"); //_result:
getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36"); //_result:
// Throws an error if the ICAP checksum is wrong getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK37"); //_error:
function getIndexedAccountPath
getIndexedAccountPath: (_index: Numeric) => string;
Returns the path using an alternative pattern for deriving accounts, at %%index%%.
This derivation path uses the //index// component rather than the //account// component to derive sequential accounts.
This is the pattern used by wallets like MetaMask.
function getNumber
getNumber: (value: BigNumberish, name?: string) => number;
Gets a //number// from %%value%%. If it is an invalid value for a //number//, then an ArgumentError will be thrown for %%name%%.
function getUint
getUint: (value: BigNumberish, name?: string) => bigint;
Returns %%value%% as a bigint, validating it is valid as a bigint value and that it is positive.
function hashMessage
hashMessage: (message: Uint8Array | string) => string;
Computes the [[link-eip-191]] personal-sign message digest to sign.
This prefixes the message with [[MessagePrefix]] and the decimal length of %%message%% and computes the [[keccak256]] digest.
If %%message%% is a string, it is converted to its UTF-8 bytes first. To compute the digest of a [[DataHexString]], it must be converted to [bytes](getBytes).
@example: hashMessage("Hello World") //_result:
// Hashes the SIX (6) string characters, i.e. // [ "0", "x", "4", "2", "4", "3" ] hashMessage("0x4243") //_result:
// Hashes the TWO (2) bytes [ 0x42, 0x43 ]... hashMessage(getBytes("0x4243")) //_result:
// ...which is equal to using data hashMessage(new Uint8Array([ 0x42, 0x43 ])) //_result:
function hexlify
hexlify: (data: BytesLike) => string;
Returns a [[DataHexString]] representation of %%data%%.
function id
id: (value: string) => string;
A simple hashing function which operates on UTF-8 strings to compute an 32-byte identifier.
This simply computes the [UTF-8 bytes](toUtf8Bytes) and computes the [[keccak256]].
@example: id("hello world") //_result:
function isAddress
isAddress: (value: any) => value is string;
Returns true if %%value%% is a valid address.
@example: // Valid address isAddress("0x8ba1f109551bD432803012645Ac136ddd64DBA72") //_result:
// Valid ICAP address isAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36") //_result:
// Invalid checksum isAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBa72") //_result:
// Invalid ICAP checksum isAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72") //_result:
// Not an address (an ENS name requires a provided and an // asynchronous API to access) isAddress("ricmoo.eth") //_result:
function isAddressable
isAddressable: (value: any) => value is Addressable;
Returns true if %%value%% is an object which implements the [[Addressable]] interface.
@example: // Wallets and AbstractSigner sub-classes isAddressable(Wallet.createRandom()) //_result:
// Contracts contract = new Contract("dai.tokens.ethers.eth", [ ], provider) isAddressable(contract) //_result:
function isBytesLike
isBytesLike: (value: any) => value is BytesLike;
Returns true if %%value%% is a valid representation of arbitrary data (i.e. a valid [[DataHexString]] or a Uint8Array).
function isCallException
isCallException: (error: any) => error is CallExceptionError;
Returns true if %%error%% is a [[CallExceptionError].
function isCrowdsaleJson
isCrowdsaleJson: (json: string) => boolean;
Returns true if %%json%% is a valid JSON Crowdsale wallet.
function isError
isError: <K extends ErrorCode, T extends CodedEthersError<K>>( error: any, code: K) => error is T;
Returns true if the %%error%% matches an error thrown by ethers that matches the error %%code%%.
In TypeScript environments, this can be used to check that %%error%% matches an EthersError type, which means the expected properties will be set.
Example 1
try { // code.... } catch (e) { if (isError(e, "CALL_EXCEPTION")) { // The Type Guard has validated this object console.log(e.data); } }
See Also
[ErrorCodes](api:ErrorCode)
function isHexString
isHexString: (value: any, length?: number | boolean) => value is `0x${string}`;
Returns true if %%value%% is a valid [[HexString]].
If %%length%% is ``true`` or a //number//, it also checks that %%value%% is a valid [[DataHexString]] of %%length%% (if a //number//) bytes of data (e.g. ``0x1234`` is 2 bytes).
function isKeystoreJson
isKeystoreJson: (json: string) => boolean;
Returns true if %%json%% is a valid JSON Keystore Wallet.
function isValidName
isValidName: (name: string) => name is string;
Returns ``true`` if %%name%% is a valid ENS name.
function keccak256
keccak256: typeof keccak256;
Compute the cryptographic KECCAK256 hash of %%data%%.
The %%data%% **must** be a data representation, to compute the hash of UTF-8 data use the [[id]] function.
Returns
DataHexstring @example: keccak256("0x") //_result:
keccak256("0x1337") //_result:
keccak256(new Uint8Array([ 0x13, 0x37 ])) //_result:
// Strings are assumed to be DataHexString, otherwise it will // throw. To hash UTF-8 data, see the note above. keccak256("Hello World") //_error:
function lock
lock: () => void;
Once called, prevents any future change to the underlying cryptographic primitives using the ``.register`` feature for hooks.
function makeError
makeError: <K extends ErrorCode, T extends CodedEthersError<K>>( message: string, code: K, info?: ErrorInfo<T>) => T;
Returns a new Error configured to the format ethers emits errors, with the %%message%%, [[api:ErrorCode]] %%code%% and additional properties for the corresponding EthersError.
Each error in ethers includes the version of ethers, a machine-readable [[ErrorCode]], and depending on %%code%%, additional required properties. The error message will also include the %%message%%, ethers version, %%code%% and all additional properties, serialized.
function mask
mask: (_value: BigNumberish, _bits: Numeric) => bigint;
Mask %%value%% with a bitmask of %%bits%% ones.
function namehash
namehash: (name: string) => string;
Returns the [[link-namehash]] for %%name%%.
function parseEther
parseEther: (ether: string) => bigint;
Converts the //decimal string// %%ether%% to a BigInt, using 18 decimal places.
function parseUnits
parseUnits: (value: string, unit?: string | Numeric) => bigint;
Converts the //decimal string// %%value%% to a BigInt, assuming %%unit%% decimal places. The %%unit%% may the number of decimal places or the name of a unit (e.g. ``"gwei"`` for 9 decimal places).
function pbkdf2
pbkdf2: typeof pbkdf2;
Return the [[link-pbkdf2]] for %%keylen%% bytes for %%password%% using the %%salt%% and using %%iterations%% of %%algo%%.
This PBKDF is outdated and should not be used in new projects, but is required to decrypt older files.
@example: // The password must be converted to bytes, and it is generally // best practices to ensure the string has been normalized. Many // formats explicitly indicate the normalization form to use. password = "hello" passwordBytes = toUtf8Bytes(password, "NFKC")
salt = id("some-salt")
// Compute the PBKDF2 pbkdf2(passwordBytes, salt, 1024, 16, "sha256") //_result:
function randomBytes
randomBytes: typeof randomBytes;
Return %%length%% bytes of cryptographically secure random data.
@example: randomBytes(8) //_result:
function recoverAddress
recoverAddress: (digest: BytesLike, signature: SignatureLike) => string;
Returns the recovered address for the private key that was used to sign %%digest%% that resulted in %%signature%%.
function resolveAddress
resolveAddress: ( target: AddressLike, resolver?: null | NameResolver) => string | Promise<string>;
Resolves to an address for the %%target%%, which may be any supported address type, an [[Addressable]] or a Promise which resolves to an address.
If an ENS name is provided, but that name has not been correctly configured a [[UnconfiguredNameError]] is thrown.
@example: addr = "0x6B175474E89094C44Da98b954EedeAC495271d0F"
// Addresses are return synchronously resolveAddress(addr, provider) //_result:
// Address promises are resolved asynchronously resolveAddress(Promise.resolve(addr)) //_result:
// ENS names are resolved asynchronously resolveAddress("dai.tokens.ethers.eth", provider) //_result:
// Addressable objects are resolved asynchronously contract = new Contract(addr, [ ]) resolveAddress(contract, provider) //_result:
// Unconfigured ENS names reject resolveAddress("nothing-here.ricmoo.eth", provider) //_error:
// ENS names require a NameResolver object passed in // (notice the provider was omitted) resolveAddress("nothing-here.ricmoo.eth") //_error:
function resolveProperties
resolveProperties: <T>(value: { [P in keyof T]: T[P] | Promise<T[P]>;}) => Promise<T>;
Resolves to a new object that is a copy of %%value%%, but with all values resolved.
function ripemd160
ripemd160: typeof ripemd160;
Compute the cryptographic RIPEMD-160 hash of %%data%%.
@_docloc: api/crypto:Hash Functions
Returns
DataHexstring
@example: ripemd160("0x") //_result:
ripemd160("0x1337") //_result:
ripemd160(new Uint8Array([ 0x13, 0x37 ])) //_result:
function scrypt
scrypt: typeof scrypt;
The [[link-wiki-scrypt]] uses a memory and cpu hard method of derivation to increase the resource cost to brute-force a password for a given key.
This means this algorithm is intentionally slow, and can be tuned to become slower. As computation and memory speed improve over time, increasing the difficulty maintains the cost of an attacker.
For example, if a target time of 5 seconds is used, a legitimate user which knows their password requires only 5 seconds to unlock their account. A 6 character password has 68 billion possibilities, which would require an attacker to invest over 10,000 years of CPU time. This is of course a crude example (as password generally aren't random), but demonstrates to value of imposing large costs to decryption.
For this reason, if building a UI which involved decrypting or encrypting datsa using scrypt, it is recommended to use a [[ProgressCallback]] (as event short periods can seem lik an eternity if the UI freezes). Including the phrase //"decrypting"// in the UI can also help, assuring the user their waiting is for a good reason.
@_docloc: api/crypto:Passwords
@example: // The password must be converted to bytes, and it is generally // best practices to ensure the string has been normalized. Many // formats explicitly indicate the normalization form to use. password = "hello" passwordBytes = toUtf8Bytes(password, "NFKC")
salt = id("some-salt")
// Compute the scrypt scrypt(passwordBytes, salt, 1024, 8, 1, 16) //_result:
function scryptSync
scryptSync: typeof scryptSync;
Provides a synchronous variant of [[scrypt]].
This will completely lock up and freeze the UI in a browser and will prevent any event loop from progressing. For this reason, it is preferred to use the [async variant](scrypt).
@_docloc: api/crypto:Passwords
@example: // The password must be converted to bytes, and it is generally // best practices to ensure the string has been normalized. Many // formats explicitly indicate the normalization form to use. password = "hello" passwordBytes = toUtf8Bytes(password, "NFKC")
salt = id("some-salt")
// Compute the scrypt scryptSync(passwordBytes, salt, 1024, 8, 1, 16) //_result:
function sha256
sha256: typeof sha256;
Compute the cryptographic SHA2-256 hash of %%data%%.
@_docloc: api/crypto:Hash Functions
Returns
DataHexstring
@example: sha256("0x") //_result:
sha256("0x1337") //_result:
sha256(new Uint8Array([ 0x13, 0x37 ])) //_result:
function sha512
sha512: typeof sha512;
Compute the cryptographic SHA2-512 hash of %%data%%.
@_docloc: api/crypto:Hash Functions
Returns
DataHexstring
@example: sha512("0x") //_result:
sha512("0x1337") //_result:
sha512(new Uint8Array([ 0x13, 0x37 ])) //_result:
function showThrottleMessage
showThrottleMessage: (service: string) => void;
Displays a warning in tht console when the community resource is being used too heavily by the app, recommending the developer acquire their own credentials instead of using the community credentials.
The notification will only occur once per service.
function solidityPacked
solidityPacked: ( types: ReadonlyArray<string>, values: ReadonlyArray<any>) => string;
Computes the [[link-solc-packed]] representation of %%values%% respectively to their %%types%%.
@example: addr = "0x8ba1f109551bd432803012645ac136ddd64dba72" solidityPacked([ "address", "uint" ], [ addr, 45 ]); //_result:
function solidityPackedKeccak256
solidityPackedKeccak256: ( types: ReadonlyArray<string>, values: ReadonlyArray<any>) => string;
Computes the [[link-solc-packed]] [[keccak256]] hash of %%values%% respectively to their %%types%%.
@example: addr = "0x8ba1f109551bd432803012645ac136ddd64dba72" solidityPackedKeccak256([ "address", "uint" ], [ addr, 45 ]); //_result:
function solidityPackedSha256
solidityPackedSha256: ( types: ReadonlyArray<string>, values: ReadonlyArray<any>) => string;
Computes the [[link-solc-packed]] [[sha256]] hash of %%values%% respectively to their %%types%%.
@example: addr = "0x8ba1f109551bd432803012645ac136ddd64dba72" solidityPackedSha256([ "address", "uint" ], [ addr, 45 ]); //_result:
function stripZerosLeft
stripZerosLeft: (data: BytesLike) => string;
Return the [[DataHexString]] result by stripping all **leading** * zero bytes from %%data%%.
function toBeArray
toBeArray: (_value: BigNumberish) => Uint8Array;
Converts %%value%% to a Big Endian Uint8Array.
function toBeHex
toBeHex: (_value: BigNumberish, _width?: Numeric) => string;
Converts %%value%% to a Big Endian hexstring, optionally padded to %%width%% bytes.
function toBigInt
toBigInt: (value: BigNumberish | Uint8Array) => bigint;
function toNumber
toNumber: (value: BigNumberish | Uint8Array) => number;
Converts %%value%% to a number. If %%value%% is a Uint8Array, it is treated as Big Endian data. Throws if the value is not safe.
function toQuantity
toQuantity: (value: BytesLike | BigNumberish) => string;
Returns a [[HexString]] for %%value%% safe to use as a //Quantity//.
A //Quantity// does not have and leading 0 values unless the value is the literal value
0x0
. This is most commonly used for JSSON-RPC numeric values.
function toTwos
toTwos: (_value: BigNumberish, _width: Numeric) => bigint;
Convert %%value%% to a twos-compliment representation of %%width%% bits.
The result will always be positive.
function toUtf8Bytes
toUtf8Bytes: (str: string, form?: UnicodeNormalizationForm) => Uint8Array;
Returns the UTF-8 byte representation of %%str%%.
If %%form%% is specified, the string is normalized.
function toUtf8CodePoints
toUtf8CodePoints: ( str: string, form?: UnicodeNormalizationForm) => Array<number>;
Returns the UTF-8 code-points for %%str%%.
If %%form%% is specified, the string is normalized.
function toUtf8String
toUtf8String: (bytes: BytesLike, onError?: Utf8ErrorFunc) => string;
Returns the string represented by the UTF-8 data %%bytes%%.
When %%onError%% function is specified, it is called on UTF-8 errors allowing recovery using the [[Utf8ErrorFunc]] API. (default: [error](Utf8ErrorFuncs))
function uuidV4
uuidV4: (randomBytes: BytesLike) => string;
Returns the version 4 [[link-uuid]] for the %%randomBytes%%.
@see: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)
function verifyMessage
verifyMessage: (message: Uint8Array | string, sig: SignatureLike) => string;
Return the address of the private key that produced the signature %%sig%% during signing for %%message%%.
function verifyTypedData
verifyTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>, signature: SignatureLike) => string;
Compute the address used to sign the typed data for the %%signature%%.
function zeroPadBytes
zeroPadBytes: (data: BytesLike, length: number) => string;
Return the [[DataHexString]] of %%data%% padded on the **right** to %%length%% bytes.
If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is thrown.
This pads data the same as **bytes** are in Solidity (e.g. ``bytes16``).
function zeroPadValue
zeroPadValue: (data: BytesLike, length: number) => string;
Return the [[DataHexString]] of %%data%% padded on the **left** to %%length%% bytes.
If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is thrown.
This pads data the same as **values** are in Solidity (e.g. ``uint128``).
Classes
class AbiCoder
class AbiCoder {}
The **AbiCoder** is a low-level class responsible for encoding JavaScript values into binary data and decoding binary data into JavaScript values.
method decode
decode: ( types: ReadonlyArray<string | ParamType>, data: BytesLike, loose?: boolean) => Result;
Decode the ABI %%data%% as the %%types%% into values.
If %%loose%% decoding is enabled, then strict padding is not enforced. Some older versions of Solidity incorrectly padded event data emitted from ``external`` functions.
method defaultAbiCoder
static defaultAbiCoder: () => AbiCoder;
Returns the shared singleton instance of a default [[AbiCoder]].
On the first call, the instance is created internally.
method encode
encode: ( types: ReadonlyArray<string | ParamType>, values: ReadonlyArray<any>) => string;
Encode the %%values%% as the %%types%% into ABI data.
Returns
DataHexstring
method getBuiltinCallException
static getBuiltinCallException: ( action: CallExceptionAction, tx: { to?: null | string; from?: null | string; data?: string }, data: null | BytesLike) => CallExceptionError;
Returns an ethers-compatible [[CallExceptionError]] Error for the given result %%data%% for the [[CallExceptionAction]] %%action%% against the Transaction %%tx%%.
method getDefaultValue
getDefaultValue: (types: ReadonlyArray<string | ParamType>) => Result;
Get the default values for the given %%types%%.
For example, a ``uint`` is by default ``0`` and ``bool`` is by default ``false``.
class AbstractProvider
class AbstractProvider implements Provider {}
An **AbstractProvider** provides a base class for other sub-classes to implement the [[Provider]] API by normalizing input arguments and formatting output results as well as tracking events for consistent behaviour on an eventually-consistent network.
constructor
constructor(_network?: Networkish, options?: AbstractProviderOptions);
Create a new **AbstractProvider** connected to %%network%%, or use the various network detection capabilities to discover the [[Network]] if necessary.
property destroyed
readonly destroyed: boolean;
If this provider has been destroyed using the [[destroy]] method.
Once destroyed, all resources are reclaimed, internal event loops and timers are cleaned up and no further requests may be sent to the provider.
property disableCcipRead
disableCcipRead: boolean;
Prevent any CCIP-read operation, regardless of whether requested in a [[call]] using ``enableCcipRead``.
property paused
paused: boolean;
Whether the provider is currently paused.
A paused provider will not emit any events, and generally should not make any requests to the network, but that is up to sub-classes to manage.
Setting ``paused = true`` is identical to calling ``.pause(false)``, which will buffer any events that occur while paused until the provider is unpaused.
property plugins
readonly plugins: AbstractProviderPlugin[];
Returns all the registered plug-ins.
property pollingInterval
readonly pollingInterval: number;
property provider
readonly provider: AbstractProvider;
Returns ``this``, to allow an **AbstractProvider** to implement the [[ContractRunner]] interface.
method addListener
addListener: (event: ProviderEvent, listener: Listener) => Promise<this>;
method attachPlugin
attachPlugin: (plugin: AbstractProviderPlugin) => this;
Attach a new plug-in.
method broadcastTransaction
broadcastTransaction: (signedTx: string) => Promise<TransactionResponse>;
method call
call: (_tx: TransactionRequest) => Promise<string>;
method ccipReadFetch
ccipReadFetch: ( tx: PerformActionTransaction, calldata: string, urls: Array<string>) => Promise<null | string>;
Resolves to the data for executing the CCIP-read operations.
method destroy
destroy: () => void;
Sub-classes may use this to shutdown any sockets or release their resources and reject any pending requests.
Sub-classes **must** call ``super.destroy()``.
method emit
emit: (event: ProviderEvent, ...args: Array<any>) => Promise<boolean>;
method estimateGas
estimateGas: (_tx: TransactionRequest) => Promise<bigint>;
method getAvatar
getAvatar: (name: string) => Promise<null | string>;
method getBalance
getBalance: (address: AddressLike, blockTag?: BlockTag) => Promise<bigint>;
method getBlock
getBlock: ( block: BlockTag | string, prefetchTxs?: boolean) => Promise<null | Block>;
method getBlockNumber
getBlockNumber: () => Promise<number>;
method getCode
getCode: (address: AddressLike, blockTag?: BlockTag) => Promise<string>;
method getFeeData
getFeeData: () => Promise<FeeData>;
method getLogs
getLogs: (_filter: Filter | FilterByBlockHash) => Promise<Array<Log>>;
method getNetwork
getNetwork: () => Promise<Network>;
method getPlugin
getPlugin: <T extends AbstractProviderPlugin = AbstractProviderPlugin>( name: string) => null | T;
Get a plugin by name.
method getResolver
getResolver: (name: string) => Promise<null | EnsResolver>;
method getStorage
getStorage: ( address: AddressLike, _position: BigNumberish, blockTag?: BlockTag) => Promise<string>;
method getTransaction
getTransaction: (hash: string) => Promise<null | TransactionResponse>;
method getTransactionCount
getTransactionCount: ( address: AddressLike, blockTag?: BlockTag) => Promise<number>;
method getTransactionReceipt
getTransactionReceipt: (hash: string) => Promise<null | TransactionReceipt>;
method getTransactionResult
getTransactionResult: (hash: string) => Promise<null | string>;
method listenerCount
listenerCount: (event?: ProviderEvent) => Promise<number>;
method listeners
listeners: (event?: ProviderEvent) => Promise<Array<Listener>>;
method lookupAddress
lookupAddress: (address: string) => Promise<null | string>;
method off
off: (event: ProviderEvent, listener?: Listener) => Promise<this>;
method on
on: (event: ProviderEvent, listener: Listener) => Promise<this>;
method once
once: (event: ProviderEvent, listener: Listener) => Promise<this>;
method pause
pause: (dropWhilePaused?: boolean) => void;
Pause the provider. If %%dropWhilePaused%%, any events that occur while paused are dropped, otherwise all events will be emitted once the provider is unpaused.
method removeAllListeners
removeAllListeners: (event?: ProviderEvent) => Promise<this>;
method removeListener
removeListener: (event: ProviderEvent, listener: Listener) => Promise<this>;
method resolveName
resolveName: (name: string) => Promise<null | string>;
method resume
resume: () => void;
Resume the provider.
method waitForBlock
waitForBlock: (blockTag?: BlockTag) => Promise<Block>;
method waitForTransaction
waitForTransaction: ( hash: string, _confirms?: null | number, timeout?: null | number) => Promise<null | TransactionReceipt>;
class AbstractSigner
abstract class AbstractSigner<P extends null | Provider = null | Provider> implements Signer {}
An **AbstractSigner** includes most of teh functionality required to get a [[Signer]] working as expected, but requires a few Signer-specific methods be overridden.
constructor
constructor(provider?: Provider);
Creates a new Signer connected to %%provider%%.
property provider
readonly provider: Provider;
The provider this signer is connected to.
method call
call: (tx: TransactionRequest) => Promise<string>;
method connect
abstract connect: (provider: null | Provider) => Signer;
Returns the signer connected to %%provider%%.
This may throw, for example, a Signer connected over a Socket or to a specific instance of a node may not be transferrable.
method estimateGas
estimateGas: (tx: TransactionRequest) => Promise<bigint>;
method getAddress
abstract getAddress: () => Promise<string>;
Resolves to the Signer address.
method getNonce
getNonce: (blockTag?: BlockTag) => Promise<number>;
method populateCall
populateCall: (tx: TransactionRequest) => Promise<TransactionLike<string>>;
method populateTransaction
populateTransaction: ( tx: TransactionRequest) => Promise<TransactionLike<string>>;
method resolveName
resolveName: (name: string) => Promise<null | string>;
method sendTransaction
sendTransaction: (tx: TransactionRequest) => Promise<TransactionResponse>;
method signMessage
abstract signMessage: (message: string | Uint8Array) => Promise<string>;
method signTransaction
abstract signTransaction: (tx: TransactionRequest) => Promise<string>;
method signTypedData
abstract signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => Promise<string>;
class AlchemyProvider
class AlchemyProvider extends JsonRpcProvider implements CommunityResourcable {}
The **AlchemyProvider** connects to the [[link-alchemy]] JSON-RPC end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-alchemy-signup).
@_docloc: api/providers/thirdparty
constructor
constructor(_network?: Networkish, apiKey?: string);
property apiKey
readonly apiKey: string;
method getRequest
static getRequest: (network: Network, apiKey?: string) => FetchRequest;
method isCommunityResource
isCommunityResource: () => boolean;
class AnkrProvider
class AnkrProvider extends JsonRpcProvider implements CommunityResourcable {}
The **AnkrProvider** connects to the [[link-ankr]] JSON-RPC end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-ankr-signup).
constructor
constructor(_network?: Networkish, apiKey?: string);
Create a new **AnkrProvider**.
By default connecting to ``mainnet`` with a highly throttled API key.
property apiKey
readonly apiKey: string;
The API key for the Ankr connection.
method getRequest
static getRequest: (network: Network, apiKey?: null | string) => FetchRequest;
Returns a prepared request for connecting to %%network%% with %%apiKey%%.
method getRpcError
getRpcError: (payload: JsonRpcPayload, error: JsonRpcError) => Error;
method isCommunityResource
isCommunityResource: () => boolean;
class BaseContract
class BaseContract implements Addressable, EventEmitterable<ContractEventName> {}
constructor
constructor( target: string | Addressable, abi: InterfaceAbi | Interface, runner?: ContractRunner, _deployTx?: TransactionResponse);
Creates a new contract connected to %%target%% with the %%abi%% and optionally connected to a %%runner%% to perform operations on behalf of.
property [internal]
readonly [internal]: any;
@_ignore:
property fallback
readonly fallback: WrappedFallback;
The fallback or receive function if any.
property filters
readonly filters: Record<string, ContractEvent<any[]>>;
All the Events available on this contract.
property interface
readonly interface: Interface;
The contract Interface.
property runner
readonly runner: ContractRunner;
The connected runner. This is generally a [[Provider]] or a [[Signer]], which dictates what operations are supported.
For example, a **Contract** connected to a [[Provider]] may only execute read-only operations.
property target
readonly target: string | Addressable;
The target to connect to.
This can be an address, ENS name or any [[Addressable]], such as another contract. To get the resovled address, use the ``getAddress`` method.
method addListener
addListener: (event: ContractEventName, listener: Listener) => Promise<this>;
Alias for [on].
method attach
attach: (target: string | Addressable) => BaseContract;
Return a new Contract instance with the same ABI and runner, but a different %%target%%.
method buildClass
static buildClass: <T = ContractInterface>( abi: Interface | InterfaceAbi) => new (target: string, runner?: null | ContractRunner) => BaseContract & Omit<T, keyof BaseContract>;
Create a new Class for the %%abi%%.
method connect
connect: (runner: null | ContractRunner) => BaseContract;
Return a new Contract instance with the same target and ABI, but a different %%runner%%.
method deploymentTransaction
deploymentTransaction: () => null | ContractTransactionResponse;
Return the transaction used to deploy this contract.
This is only available if this instance was returned from a [[ContractFactory]].
method emit
emit: (event: ContractEventName, ...args: Array<any>) => Promise<boolean>;
Emit an %%event%% calling all listeners with %%args%%.
Resolves to ``true`` if any listeners were called.
method from
static from: <T = ContractInterface>( target: string, abi: Interface | InterfaceAbi, runner?: null | ContractRunner) => BaseContract & Omit<T, keyof BaseContract>;
Create a new BaseContract with a specified Interface.
method getAddress
getAddress: () => Promise<string>;
Return the resolved address of this Contract.
method getDeployedCode
getDeployedCode: () => Promise<null | string>;
Return the deployed bytecode or null if no bytecode is found.
method getEvent
getEvent: (key: string | EventFragment) => ContractEvent;
Return the event for a given name. This is useful when a contract event name conflicts with a JavaScript name such as ``prototype`` or when using a Contract programatically.
method getFunction
getFunction: < T extends ContractMethod<any[], any, any> = ContractMethod<any[], any, any>>( key: string | FunctionFragment) => T;
Return the function for a given name. This is useful when a contract method name conflicts with a JavaScript name such as ``prototype`` or when using a Contract programatically.
method listenerCount
listenerCount: (event?: ContractEventName) => Promise<number>;
Resolves to the number of listeners of %%event%% or the total number of listeners if unspecified.
method listeners
listeners: (event?: ContractEventName) => Promise<Array<Listener>>;
Resolves to the listeners subscribed to %%event%% or all listeners if unspecified.
method off
off: (event: ContractEventName, listener?: Listener) => Promise<this>;
Remove the %%listener%% from the listeners for %%event%% or remove all listeners if unspecified.
method on
on: (event: ContractEventName, listener: Listener) => Promise<this>;
Add an event %%listener%% for the %%event%%.
method once
once: (event: ContractEventName, listener: Listener) => Promise<this>;
Add an event %%listener%% for the %%event%%, but remove the listener after it is fired once.
method queryFilter
queryFilter: ( event: ContractEventName, fromBlock?: BlockTag, toBlock?: BlockTag) => Promise<Array<EventLog | Log>>;
Provide historic access to event data for %%event%% in the range %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``) inclusive.
method queryTransaction
queryTransaction: (hash: string) => Promise<Array<EventLog>>;
@_ignore:
method removeAllListeners
removeAllListeners: (event?: ContractEventName) => Promise<this>;
Remove all the listeners for %%event%% or remove all listeners if unspecified.
method removeListener
removeListener: (event: ContractEventName, listener: Listener) => Promise<this>;
Alias for [off].
method waitForDeployment
waitForDeployment: () => Promise<this>;
Resolve to this Contract once the bytecode has been deployed, or resolve immediately if already deployed.
class BaseWallet
class BaseWallet extends AbstractSigner {}
The **BaseWallet** is a stream-lined implementation of a [[Signer]] that operates with a private key.
It is preferred to use the [[Wallet]] class, as it offers additional functionality and simplifies loading a variety of JSON formats, Mnemonic Phrases, etc.
This class may be of use for those attempting to implement a minimal Signer.
constructor
constructor(privateKey: SigningKey, provider?: Provider);
Creates a new BaseWallet for %%privateKey%%, optionally connected to %%provider%%.
If %%provider%% is not specified, only offline methods can be used.
property address
readonly address: string;
The wallet address.
property privateKey
readonly privateKey: string;
The private key for this wallet.
property signingKey
readonly signingKey: SigningKey;
The [[SigningKey]] used for signing payloads.
method connect
connect: (provider: null | Provider) => BaseWallet;
method getAddress
getAddress: () => Promise<string>;
method signMessage
signMessage: (message: string | Uint8Array) => Promise<string>;
method signMessageSync
signMessageSync: (message: string | Uint8Array) => string;
Returns the signature for %%message%% signed with this wallet.
method signTransaction
signTransaction: (tx: TransactionRequest) => Promise<string>;
method signTypedData
signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => Promise<string>;
class Block
class Block implements BlockParams, Iterable<string> {}
A **Block** represents the data associated with a full block on Ethereum.
constructor
constructor(block: BlockParams, provider: Provider);
Create a new **Block** object.
This should generally not be necessary as the unless implementing a low-level library.
property baseFeePerGas
readonly baseFeePerGas: BigInt;
The base fee per gas that all transactions in this block were charged.
This adjusts after each block, depending on how congested the network is.
property blobGasUsed
readonly blobGasUsed: BigInt;
The total amount of blob gas consumed by the transactions within the block. See [[link-eip-4844]].
property date
readonly date: Date;
The [[link-js-date]] this block was included at.
property difficulty
readonly difficulty: BigInt;
The difficulty target.
On legacy networks, this is the proof-of-work target required for a block to meet the protocol rules to be included.
On modern networks, this is a random number arrived at using randao. @TODO: Find links?
property excessBlobGas
readonly excessBlobGas: BigInt;
The running total of blob gas consumed in excess of the target, prior to the block. See [[link-eip-4844]].
property extraData
readonly extraData: string;
Any extra data the validator wished to include.
property gasLimit
readonly gasLimit: BigInt;
The total gas limit for this block.
property gasUsed
readonly gasUsed: BigInt;
The total gas used in this block.
property hash
readonly hash: string;
The block hash.
This hash includes all properties, so can be safely used to identify an exact set of block properties.
property length
readonly length: number;
The number of transactions in this block.
property miner
readonly miner: string;
The miner coinbase address, wihch receives any subsidies for including this block.
property nonce
readonly nonce: string;
The nonce.
On legacy networks, this is the random number inserted which permitted the difficulty target to be reached.
property number
readonly number: number;
The block number, sometimes called the block height. This is a sequential number that is one higher than the parent block.
property parentBeaconBlockRoot
parentBeaconBlockRoot: string;
The hash tree root of the parent beacon block for the given execution block. See [[link-eip-4788]].
property parentHash
readonly parentHash: string;
The block hash of the parent block.
property prefetchedTransactions
readonly prefetchedTransactions: TransactionResponse[];
Returns the complete transactions, in the order they were executed within the block.
This is only available for blocks which prefetched transactions, by passing ``true`` to %%prefetchTxs%% into [[Provider-getBlock]].
property prevRandao
readonly prevRandao: string;
The latest RANDAO mix of the post beacon state of the previous block.
property provider
readonly provider: Provider;
The provider connected to the block used to fetch additional details if necessary.
property receiptsRoot
readonly receiptsRoot: string;
The hash of the transaction receipts trie.
property stateRoot
readonly stateRoot: string;
The root hash for the global state after applying changes in this block.
property timestamp
readonly timestamp: number;
The timestamp for this block, which is the number of seconds since epoch that this block was included.
property transactions
readonly transactions: readonly string[];
Returns the list of transaction hashes, in the order they were executed within the block.
method [Symbol.iterator]
[Symbol.iterator]: () => Iterator<string>;
method getPrefetchedTransaction
getPrefetchedTransaction: (indexOrHash: number | string) => TransactionResponse;
If a **Block** was fetched with a request to include the transactions this will allow synchronous access to those transactions.
If the transactions were not prefetched, this will throw.
method getTransaction
getTransaction: (indexOrHash: number | string) => Promise<TransactionResponse>;
Get the transaction at %%indexe%% within this block.
method isLondon
isLondon: () => this is Block & { baseFeePerGas: bigint };
Returns true if this block is an [[link-eip-2930]] block.
method isMined
isMined: () => this is MinedBlock;
Returns true if this block been mined. This provides a type guard for all properties on a [[MinedBlock]].
method orphanedEvent
orphanedEvent: () => OrphanFilter;
@_ignore:
method toJSON
toJSON: () => any;
Returns a JSON-friendly value.
class BrowserProvider
class BrowserProvider extends JsonRpcApiPollingProvider {}
A **BrowserProvider** is intended to wrap an injected provider which adheres to the [[link-eip-1193]] standard, which most (if not all) currently do.
constructor
constructor( ethereum: Eip1193Provider, network?: Networkish, _options?: BrowserProviderOptions);
Connect to the %%ethereum%% provider, optionally forcing the %%network%%.
method getRpcError
getRpcError: (payload: JsonRpcPayload, error: JsonRpcError) => Error;
method getSigner
getSigner: (address?: number | string) => Promise<JsonRpcSigner>;
method hasSigner
hasSigner: (address: number | string) => Promise<boolean>;
Resolves to ``true`` if the provider manages the %%address%%.
method send
send: (method: string, params: Array<any> | Record<string, any>) => Promise<any>;
class ChainstackProvider
class ChainstackProvider extends JsonRpcProvider implements CommunityResourcable {}
The **ChainstackProvider** connects to the [[link-chainstack]] JSON-RPC end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-chainstack).
constructor
constructor(_network?: Networkish, apiKey?: string);
Creates a new **ChainstackProvider**.
property apiKey
readonly apiKey: string;
The API key for the Chainstack connection.
method getRequest
static getRequest: (network: Network, apiKey?: null | string) => FetchRequest;
Returns a prepared request for connecting to %%network%% with %%apiKey%% and %%projectSecret%%.
method isCommunityResource
isCommunityResource: () => boolean;
class CloudflareProvider
class CloudflareProvider extends JsonRpcProvider {}
About Cloudflare...
constructor
constructor(_network?: Networkish);
class ConstructorFragment
class ConstructorFragment extends Fragment {}
A Fragment which represents a constructor.
constructor
constructor( guard: any, type: FragmentType, inputs: readonly ParamType[], payable: boolean, gas: BigInt);
property gas
readonly gas: BigInt;
The recommended gas limit for deployment or ``null``.
property payable
readonly payable: boolean;
Whether the constructor can receive an endowment.
method format
format: (format?: FormatType) => string;
Returns a string representation of this constructor as %%format%%.
method from
static from: (obj: any) => ConstructorFragment;
Returns a new **ConstructorFragment** for %%obj%%.
method isFragment
static isFragment: (value: any) => value is ConstructorFragment;
Returns ``true`` and provides a type guard if %%value%% is a **ConstructorFragment**.
class Contract
class Contract extends Contract_base {}
A [[BaseContract]] with no type guards on its methods or events.
class ContractEventPayload
class ContractEventPayload extends ContractUnknownEventPayload {}
A **ContractEventPayload** is included as the last parameter to Contract Events when the event is known.
constructor
constructor( contract: BaseContract, listener: Listener, filter: ContractEventName, fragment: EventFragment, _log: Log);
@_ignore:
property args
readonly args: Result;
The parsed arguments passed to the event by ``emit``.
property eventName
readonly eventName: string;
The event name.
property eventSignature
readonly eventSignature: string;
The event signature.
property fragment
readonly fragment: EventFragment;
The matching event.
property log
readonly log: EventLog;
The log, with parsed properties.
class ContractFactory
class ContractFactory<A extends Array<any> = Array<any>, I = BaseContract> {}
A **ContractFactory** is used to deploy a Contract to the blockchain.
constructor
constructor( abi: InterfaceAbi | Interface, bytecode: BytesLike | { object: string }, runner?: ContractRunner);
Create a new **ContractFactory** with %%abi%% and %%bytecode%%, optionally connected to %%runner%%.
The %%bytecode%% may be the ``bytecode`` property within the standard Solidity JSON output.
property bytecode
readonly bytecode: string;
The Contract deployment bytecode. Often called the initcode.
property interface
readonly interface: Interface;
The Contract Interface.
property runner
readonly runner: ContractRunner;
The ContractRunner to deploy the Contract as.
method attach
attach: ( target: string | Addressable) => BaseContract & Omit<I, keyof BaseContract>;
method connect
connect: (runner: null | ContractRunner) => ContractFactory<A, I>;
Return a new **ContractFactory** with the same ABI and bytecode, but connected to %%runner%%.
method deploy
deploy: ( ...args: ContractMethodArgs<A>) => Promise< BaseContract & { deploymentTransaction(): ContractTransactionResponse; } & Omit<I, keyof BaseContract>>;
Resolves to the Contract deployed by passing %%args%% into the constructor.
This will resolve to the Contract before it has been deployed to the network, so the [[BaseContract-waitForDeployment]] should be used before sending any transactions to it.
method fromSolidity
static fromSolidity: <A extends any[] = any[], I = ContractInterface>( output: any, runner?: ContractRunner) => ContractFactory<A, I>;
Create a new **ContractFactory** from the standard Solidity JSON output.
method getDeployTransaction
getDeployTransaction: ( ...args: ContractMethodArgs<A>) => Promise<ContractDeployTransaction>;
Resolves to the transaction to deploy the contract, passing %%args%% into the constructor.
class ContractTransactionReceipt
class ContractTransactionReceipt extends TransactionReceipt {}
A **ContractTransactionReceipt** includes the parsed logs from a [[TransactionReceipt]].
constructor
constructor(iface: Interface, provider: Provider, tx: TransactionReceipt);
@_ignore:
property logs
readonly logs: (EventLog | Log)[];
The parsed logs for any [[Log]] which has a matching event in the Contract ABI.
class ContractTransactionResponse
class ContractTransactionResponse extends TransactionResponse {}
A **ContractTransactionResponse** will return a [[ContractTransactionReceipt]] when waited on.
constructor
constructor(iface: Interface, provider: Provider, tx: TransactionResponse);
@_ignore:
method wait
wait: ( confirms?: number, timeout?: number) => Promise<null | ContractTransactionReceipt>;
Resolves once this transaction has been mined and has %%confirms%% blocks including it (default: ``1``) with an optional %%timeout%%.
This can resolve to ``null`` only if %%confirms%% is ``0`` and the transaction has not been mined, otherwise this will wait until enough confirmations have completed.
class ContractUnknownEventPayload
class ContractUnknownEventPayload extends EventPayload<ContractEventName> {}
A **ContractUnknownEventPayload** is included as the last parameter to Contract Events when the event does not match any events in the ABI.
constructor
constructor( contract: BaseContract, listener: Listener, filter: ContractEventName, log: Log);
@_event:
property log
readonly log: Log;
The log with no matching events.
method getBlock
getBlock: () => Promise<Block>;
Resolves to the block the event occured in.
method getTransaction
getTransaction: () => Promise<TransactionResponse>;
Resolves to the transaction the event occured in.
method getTransactionReceipt
getTransactionReceipt: () => Promise<TransactionReceipt>;
Resolves to the transaction receipt the event occured in.
class EnsPlugin
class EnsPlugin extends NetworkPlugin {}
An **EnsPlugin** allows a [[Network]] to specify the ENS Registry Contract address and the target network to use when using that contract.
Various testnets have their own instance of the contract to use, but in general, the mainnet instance supports multi-chain addresses and should be used.
constructor
constructor(address?: string, targetNetwork?: number);
Creates a new **EnsPlugin** connected to %%address%% on the %%targetNetwork%%. The default ENS address and mainnet is used if unspecified.
property address
readonly address: string;
The ENS Registrty Contract address.
property targetNetwork
readonly targetNetwork: number;
The chain ID that the ENS contract lives on.
method clone
clone: () => EnsPlugin;
class EnsResolver
class EnsResolver {}
A connected object to a resolved ENS name resolver, which can be used to query additional details.
constructor
constructor(provider: AbstractProvider, address: string, name: string);
property address
address: string;
The address of the resolver.
property name
name: string;
The name this resolver was resolved against.
property provider
provider: AbstractProvider;
The connected provider.
method fromName
static fromName: ( provider: AbstractProvider, name: string) => Promise<null | EnsResolver>;
Resolve to the ENS resolver for %%name%% using %%provider%% or ``null`` if unconfigured.
method getAddress
getAddress: (coinType?: number) => Promise<null | string>;
Resolves to the address for %%coinType%% or null if the provided %%coinType%% has not been configured.
method getAvatar
getAvatar: () => Promise<null | string>;
Resolves to the avatar url or ``null`` if the avatar is either unconfigured or incorrectly configured (e.g. references an NFT not owned by the address).
If diagnosing issues with configurations, the [[_getAvatar]] method may be useful.
method getContentHash
getContentHash: () => Promise<null | string>;
Rsolves to the content-hash or ``null`` if unconfigured.
method getEnsAddress
static getEnsAddress: (provider: Provider) => Promise<string>;
method getText
getText: (key: string) => Promise<null | string>;
Resolves to the EIP-634 text record for %%key%%, or ``null`` if unconfigured.
method supportsWildcard
supportsWildcard: () => Promise<boolean>;
Resolves to true if the resolver supports wildcard resolution.
class ErrorDescription
class ErrorDescription {}
When using the [[Interface-parseError]] to automatically match an error for a call result for parsing, an **ErrorDescription** is returned.
constructor
constructor(fragment: ErrorFragment, selector: string, args: Result);
@_ignore:
property args
readonly args: Result;
The arguments passed to the Error with ``revert``.
property fragment
readonly fragment: ErrorFragment;
The matching fragment.
property name
readonly name: string;
The name of the Error.
property selector
readonly selector: string;
The selector for the Error.
property signature
readonly signature: string;
The full Error signature.
class ErrorFragment
class ErrorFragment extends NamedFragment {}
A Fragment which represents a //Custom Error//.
constructor
constructor(guard: any, name: string, inputs: readonly ParamType[]);
property selector
readonly selector: string;
The Custom Error selector.
method format
format: (format?: FormatType) => string;
Returns a string representation of this fragment as %%format%%.
method from
static from: (obj: any) => ErrorFragment;
Returns a new **ErrorFragment** for %%obj%%.
method isFragment
static isFragment: (value: any) => value is ErrorFragment;
Returns ``true`` and provides a type guard if %%value%% is an **ErrorFragment**.
class EtherscanPlugin
class EtherscanPlugin extends NetworkPlugin {}
A Network can include an **EtherscanPlugin** to provide a custom base URL.
@_docloc: api/providers/thirdparty:Etherscan
constructor
constructor(baseUrl: string);
Creates a new **EtherscanProvider** which will use %%baseUrl%%.
property baseUrl
readonly baseUrl: string;
The Etherscan API base URL.
method clone
clone: () => EtherscanPlugin;
class EtherscanProvider
class EtherscanProvider extends AbstractProvider {}
The **EtherscanBaseProvider** is the super-class of [[EtherscanProvider]], which should generally be used instead.
Since the **EtherscanProvider** includes additional code for [[Contract]] access, in //rare cases// that contracts are not used, this class can reduce code size.
@_docloc: api/providers/thirdparty:Etherscan
constructor
constructor(_network?: Networkish, _apiKey?: string);
Creates a new **EtherscanBaseProvider**.
property apiKey
readonly apiKey: string;
The API key or null if using the community provided bandwidth.
property network
readonly network: Network;
The connected network.
method detectNetwork
detectNetwork: () => Promise<Network>;
method fetch
fetch: ( module: string, params: Record<string, any>, post?: boolean) => Promise<any>;
Resolves to the result of calling %%module%% with %%params%%.
If %%post%%, the request is made as a POST request.
method getBaseUrl
getBaseUrl: () => string;
Returns the base URL.
If an [[EtherscanPlugin]] is configured on the [[EtherscanBaseProvider_network]], returns the plugin's baseUrl.
method getContract
getContract: (_address: string) => Promise<null | Contract>;
Resolves to a [Contract]] for %%address%%, using the Etherscan API to retreive the Contract ABI.
method getEtherPrice
getEtherPrice: () => Promise<number>;
Resolves to the current price of ether.
This returns ``0`` on any network other than ``mainnet``.
method getNetwork
getNetwork: () => Promise<Network>;
method getPostData
getPostData: ( module: string, params: Record<string, any>) => Record<string, any>;
Returns the parameters for using POST requests.
method getPostUrl
getPostUrl: () => string;
Returns the URL for using POST requests.
method getUrl
getUrl: (module: string, params: Record<string, string>) => string;
Returns the URL for the %%module%% and %%params%%.
method isCommunityResource
isCommunityResource: () => boolean;
class EventFragment
class EventFragment extends NamedFragment {}
A Fragment which represents an Event.
constructor
constructor( guard: any, name: string, inputs: readonly ParamType[], anonymous: boolean);
property anonymous
readonly anonymous: boolean;
Whether this event is anonymous.
property topicHash
readonly topicHash: string;
The Event topic hash.
method format
format: (format?: FormatType) => string;
Returns a string representation of this event as %%format%%.
method from
static from: (obj: any) => EventFragment;
Returns a new **EventFragment** for %%obj%%.
method getTopicHash
static getTopicHash: (name: string, params?: Array<any>) => string;
Return the topic hash for an event with %%name%% and %%params%%.
method isFragment
static isFragment: (value: any) => value is EventFragment;
Returns ``true`` and provides a type guard if %%value%% is an **EventFragment**.
class EventLog
class EventLog extends Log {}
An **EventLog** contains additional properties parsed from the [[Log]].
constructor
constructor(log: Log, iface: Interface, fragment: EventFragment);
@_ignore:
property args
readonly args: Result;
The parsed arguments passed to the event by ``emit``.
property eventName
readonly eventName: string;
The name of the event.
property eventSignature
readonly eventSignature: string;
The signature of the event.
property fragment
readonly fragment: EventFragment;
The matching event.
property interface
readonly interface: Interface;
The Contract Interface.
class EventPayload
class EventPayload<T> {}
When an [[EventEmitterable]] triggers a [[Listener]], the callback always ahas one additional argument passed, which is an **EventPayload**.
constructor
constructor(emitter: EventEmitterable<T>, listener: Listener, filter: {});
Create a new **EventPayload** for %%emitter%% with the %%listener%% and for %%filter%%.
property emitter
readonly emitter: EventEmitterable<T>;
The **EventEmitterable**.
property filter
readonly filter: {};
The event filter.
method removeListener
removeListener: () => Promise<void>;
Unregister the triggered listener for future events.
class FallbackFragment
class FallbackFragment extends Fragment {}
A Fragment which represents a method.
constructor
constructor(guard: any, inputs: readonly ParamType[], payable: boolean);
property payable
readonly payable: boolean;
If the function can be sent value during invocation.
method format
format: (format?: FormatType) => string;
Returns a string representation of this fallback as %%format%%.
method from
static from: (obj: any) => FallbackFragment;
Returns a new **FallbackFragment** for %%obj%%.
method isFragment
static isFragment: (value: any) => value is FallbackFragment;
Returns ``true`` and provides a type guard if %%value%% is a **FallbackFragment**.
class FallbackProvider
class FallbackProvider extends AbstractProvider {}
A **FallbackProvider** manages several [[Providers]] providing resilience by switching between slow or misbehaving nodes, security by requiring multiple backends to aggree and performance by allowing faster backends to respond earlier.
constructor
constructor( providers: (AbstractProvider | FallbackProviderConfig)[], network?: Networkish, options?: FallbackProviderOptions);
Creates a new **FallbackProvider** with %%providers%% connected to %%network%%.
If a [[Provider]] is included in %%providers%%, defaults are used for the configuration.
property eventQuorum
readonly eventQuorum: number;
@_ignore:
property eventWorkers
readonly eventWorkers: number;
@_ignore:
property providerConfigs
readonly providerConfigs: FallbackProviderState[];
property quorum
readonly quorum: number;
The number of backends that must agree on a value before it is accpeted.
method destroy
destroy: () => Promise<void>;
class FeeData
class FeeData {}
A **FeeData** wraps all the fee-related values associated with the network.
constructor
constructor( gasPrice?: BigInt, maxFeePerGas?: BigInt, maxPriorityFeePerGas?: BigInt);
Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and %%maxPriorityFeePerGas%%.
property gasPrice
readonly gasPrice: BigInt;
The gas price for legacy networks.
property maxFeePerGas
readonly maxFeePerGas: BigInt;
The maximum fee to pay per gas.
The base fee per gas is defined by the network and based on congestion, increasing the cost during times of heavy load and lowering when less busy.
The actual fee per gas will be the base fee for the block and the priority fee, up to the max fee per gas.
This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
property maxPriorityFeePerGas
readonly maxPriorityFeePerGas: BigInt;
The additional amout to pay per gas to encourage a validator to include the transaction.
The purpose of this is to compensate the validator for the adjusted risk for including a given transaction.
This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
method toJSON
toJSON: () => any;
Returns a JSON-friendly value.
class FeeDataNetworkPlugin
class FeeDataNetworkPlugin extends NetworkPlugin {}
A **FeeDataNetworkPlugin** allows a network to provide and alternate means to specify its fee data.
For example, a network which does not support [[link-eip-1559]] may choose to use a Gas Station site to approximate the gas price.
constructor
constructor(feeDataFunc: (provider: Provider) => Promise<FeeData>);
Creates a new **FeeDataNetworkPlugin**.
property feeDataFunc
readonly feeDataFunc: (provider: Provider) => Promise<FeeData>;
The fee data function provided to the constructor.
method clone
clone: () => FeeDataNetworkPlugin;
method getFeeData
getFeeData: (provider: Provider) => Promise<FeeData>;
Resolves to the fee data.
class FetchCancelSignal
class FetchCancelSignal {}
@_ignore
constructor
constructor(request: FetchRequest);
property cancelled
readonly cancelled: boolean;
method addListener
addListener: (listener: () => void) => void;
method checkSignal
checkSignal: () => void;
class FetchRequest
class FetchRequest implements Iterable<[key: string, value: string]> {}
Represents a request for a resource using a URI.
By default, the supported schemes are ``HTTP``, ``HTTPS``, ``data:``, and ``IPFS:``.
Additional schemes can be added globally using [[registerGateway]].
@example: req = new FetchRequest("https://www.ricmoo.com") resp = await req.send() resp.body.length //_result:
constructor
constructor(url: string);
Create a new FetchRequest instance with default values.
Once created, each property may be set before issuing a ``.send()`` to make the request.
property allowGzip
allowGzip: boolean;
Enable and request gzip-encoded responses. The response will automatically be decompressed. //(default: true)//
property allowInsecureAuthentication
allowInsecureAuthentication: boolean;
Allow ``Authentication`` credentials to be sent over insecure channels. //(default: false)//
property body
body: Uint8Array;
The fetch body, if any, to send as the request body. //(default: null)//
When setting a body, the intrinsic ``Content-Type`` is automatically set and will be used if **not overridden** by setting a custom header.
If %%body%% is null, the body is cleared (along with the intrinsic ``Content-Type``).
If %%body%% is a string, the intrinsic ``Content-Type`` is set to ``text/plain``.
If %%body%% is a Uint8Array, the intrinsic ``Content-Type`` is set to ``application/octet-stream``.
If %%body%% is any other object, the intrinsic ``Content-Type`` is set to ``application/json``.
property credentials
readonly credentials: string;
The value that will be sent for the ``Authorization`` header.
To set the credentials, use the ``setCredentials`` method.
property getUrlFunc
getUrlFunc: FetchGetUrlFunc;
This function is called to fetch content from HTTP and HTTPS URLs and is platform specific (e.g. nodejs vs browsers).
This is by default the currently registered global getUrl function, which can be changed using [[registerGetUrl]]. If this has been set, setting is to ``null`` will cause this FetchRequest (and any future clones) to revert back to using the currently registered global getUrl function.
Setting this is generally not necessary, but may be useful for developers that wish to intercept requests or to configurege a proxy or other agent.
property headers
readonly headers: Record<string, string>;
The headers that will be used when requesting the URI. All keys are lower-case.
This object is a copy, so any changes will **NOT** be reflected in the ``FetchRequest``.
To set a header entry, use the ``setHeader`` method.
property method
method: string;
The HTTP method to use when requesting the URI. If no method has been explicitly set, then ``GET`` is used if the body is null and ``POST`` otherwise.
property preflightFunc
preflightFunc: FetchPreflightFunc;
This function is called prior to each request, for example during a redirection or retry in case of server throttling.
This offers an opportunity to populate headers or update content before sending a request.
property processFunc
processFunc: FetchProcessFunc;
This function is called after each response, offering an opportunity to provide client-level throttling or updating response data.
Any error thrown in this causes the ``send()`` to throw.
To schedule a retry attempt (assuming the maximum retry limit has not been reached), use [[response.throwThrottleError]].
property retryFunc
retryFunc: FetchRetryFunc;
This function is called on each retry attempt.
property timeout
timeout: number;
The timeout (in milliseconds) to wait for a complete response. //(default: 5 minutes)//
property url
url: string;
The fetch URL to request.
method [Symbol.iterator]
[Symbol.iterator]: () => Iterator<[key: string, value: string]>;
method cancel
cancel: () => void;
Cancels the inflight response, causing a ``CANCELLED`` error to be rejected from the [[send]].
method clearHeaders
clearHeaders: () => void;
Clear all headers, resetting all intrinsic headers.
method clone
clone: () => FetchRequest;
Create a new copy of this request.
method createDataGateway
static createDataGateway: () => FetchGatewayFunc;
Creates a function that can "fetch" data URIs.
Note that this is automatically done internally to support data URIs, so it is not necessary to register it.
This is not generally something that is needed, but may be useful in a wrapper to perfom custom data URI functionality.
method createGetUrlFunc
static createGetUrlFunc: (options?: Record<string, any>) => FetchGetUrlFunc;
Creates a getUrl function that fetches content from HTTP and HTTPS URLs.
The available %%options%% are dependent on the platform implementation of the default getUrl function.
This is not generally something that is needed, but is useful when trying to customize simple behaviour when fetching HTTP content.
method createIpfsGatewayFunc
static createIpfsGatewayFunc: (baseUrl: string) => FetchGatewayFunc;
Creates a function that will fetch IPFS (unvalidated) from a custom gateway baseUrl.
The default IPFS gateway used internally is ``"https://gateway.ipfs.io/ipfs/"``.
method getGateway
static getGateway: (scheme: string) => null | FetchGatewayFunc;
Get the current Gateway function for %%scheme%%.
method getHeader
getHeader: (key: string) => string;
Get the header for %%key%%, ignoring case.
method hasBody
hasBody: () => this is FetchRequest & { body: Uint8Array };
Returns true if the request has a body.
method lockConfig
static lockConfig: () => void;
Locks all static configuration for gateways and FetchGetUrlFunc registration.
method redirect
redirect: (location: string) => FetchRequest;
Returns a new [[FetchRequest]] that represents the redirection to %%location%%.
method registerGateway
static registerGateway: (scheme: string, func: FetchGatewayFunc) => void;
Use the %%func%% when fetching URIs using %%scheme%%.
This method affects all requests globally.
If [[lockConfig]] has been called, no change is made and this throws.
method registerGetUrl
static registerGetUrl: (getUrl: FetchGetUrlFunc) => void;
Use %%getUrl%% when fetching URIs over HTTP and HTTPS requests.
This method affects all requests globally.
If [[lockConfig]] has been called, no change is made and this throws.
method send
send: () => Promise<FetchResponse>;
Resolves to the response by sending the request.
method setCredentials
setCredentials: (username: string, password: string) => void;
Sets an ``Authorization`` for %%username%% with %%password%%.
method setHeader
setHeader: (key: string, value: string | number) => void;
Set the header for %%key%% to %%value%%. All values are coerced to a string.
method setThrottleParams
setThrottleParams: (params: FetchThrottleParams) => void;
Update the throttle parameters used to determine maximum attempts and exponential-backoff properties.
method toString
toString: () => string;
class FetchResponse
class FetchResponse implements Iterable<[key: string, value: string]> {}
The response for a FetchRequest.
constructor
constructor( statusCode: number, statusMessage: string, headers: Readonly<Record<string, string>>, body: Uint8Array, request?: FetchRequest);
property body
readonly body: Readonly<Uint8Array>;
The response body, or ``null`` if there was no body.
property bodyJson
readonly bodyJson: any;
The response body, decoded as JSON.
An error is thrown if the body is invalid JSON-encoded data or if there was no body.
property bodyText
readonly bodyText: string;
The response body as a UTF-8 encoded string, or the empty string (i.e. ``""``) if there was no body.
An error is thrown if the body is invalid UTF-8 data.
property headers
readonly headers: Record<string, string>;
The response headers. All keys are lower-case.
property request
readonly request: FetchRequest;
The request made for this response.
property statusCode
readonly statusCode: number;
The response status code.
property statusMessage
readonly statusMessage: string;
The response status message.
method [Symbol.iterator]
[Symbol.iterator]: () => Iterator<[key: string, value: string]>;
method assertOk
assertOk: () => void;
Throws a ``SERVER_ERROR`` if this response is not ok.
method getHeader
getHeader: (key: string) => string;
Get the header value for %%key%%, ignoring case.
method hasBody
hasBody: () => this is FetchResponse & { body: Uint8Array };
Returns true if the response has a body.
method makeServerError
makeServerError: (message?: string, error?: Error) => FetchResponse;
Return a Response with matching headers and body, but with an error status code (i.e. 599) and %%message%% with an optional %%error%%.
method ok
ok: () => boolean;
Returns true if this response was a success statusCode.
method throwThrottleError
throwThrottleError: (message?: string, stall?: number) => never;
If called within a [request.processFunc](FetchRequest-processFunc) call, causes the request to retry as if throttled for %%stall%% milliseconds.
method toString
toString: () => string;
class FetchUrlFeeDataNetworkPlugin
class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin {}
constructor
constructor( url: string, processFunc: ( f: () => Promise<FeeData>, p: Provider, r: FetchRequest ) => Promise<{ gasPrice?: null | bigint; maxFeePerGas?: null | bigint; maxPriorityFeePerGas?: null | bigint; }>);
Creates a new **FetchUrlFeeDataNetworkPlugin** which will be used when computing the fee data for the network.
property processFunc
readonly processFunc: ( f: () => Promise<FeeData>, p: Provider, r: FetchRequest) => Promise<{ gasPrice?: null | bigint; maxFeePerGas?: null | bigint; maxPriorityFeePerGas?: null | bigint;}>;
The callback to use when computing the FeeData.
property url
readonly url: string;
The URL to initialize the FetchRequest with in %%processFunc%%.
method clone
clone: () => FetchUrlFeeDataNetworkPlugin;
class FixedNumber
class FixedNumber {}
A FixedNumber represents a value over its [[FixedFormat]] arithmetic field.
A FixedNumber can be used to perform math, losslessly, on values which have decmial places.
A FixedNumber has a fixed bit-width to store values in, and stores all values internally by multiplying the value by 10 raised to the power of %%decimals%%.
If operations are performed that cause a value to grow too high (close to positive infinity) or too low (close to negative infinity), the value is said to //overflow//.
For example, an 8-bit signed value, with 0 decimals may only be within the range ``-128`` to ``127``; so ``-128 - 1`` will overflow and become ``127``. Likewise, ``127 + 1`` will overflow and become ``-127``.
Many operation have a normal and //unsafe// variant. The normal variant will throw a [[NumericFaultError]] on any overflow, while the //unsafe// variant will silently allow overflow, corrupting its value value.
If operations are performed that cause a value to become too small (close to zero), the value loses precison and is said to //underflow//.
For example, an value with 1 decimal place may store a number as small as ``0.1``, but the value of ``0.1 / 2`` is ``0.05``, which cannot fit into 1 decimal place, so underflow occurs which means precision is lost and the value becomes ``0``.
Some operations have a normal and //signalling// variant. The normal variant will silently ignore underflow, while the //signalling// variant will thow a [[NumericFaultError]] on underflow.
constructor
constructor(guard: any, value: BigInt, format: any);
property decimals
readonly decimals: number;
The number of decimal places in the fixed-point arithment field.
property format
readonly format: string;
The specific fixed-point arithmetic field for this value.
property signed
readonly signed: boolean;
If true, negative values are permitted, otherwise only positive values and zero are allowed.
property value
readonly value: BigInt;
The value as an integer, based on the smallest unit the [[decimals]] allow.
property width
readonly width: number;
The number of bits available to store the value.
method add
add: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% added to %%other%%. A [[NumericFaultError]] is thrown if overflow occurs.
method addUnsafe
addUnsafe: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% added to %%other%%, ignoring overflow.
method ceiling
ceiling: () => FixedNumber;
Returns a new [[FixedNumber]] which is the smallest **integer** that is greater than or equal to %%this%%.
The decimal component of the result will always be ``0``.
method cmp
cmp: (other: FixedNumber) => number;
Returns a comparison result between %%this%% and %%other%%.
This is suitable for use in sorting, where ``-1`` implies %%this%% is smaller, ``1`` implies %%this%% is larger and ``0`` implies both are equal.
method div
div: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% divided by %%other%%, ignoring underflow (precision loss). A [[NumericFaultError]] is thrown if overflow occurs.
method divSignal
divSignal: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% divided by %%other%%. A [[NumericFaultError]] is thrown if underflow (precision loss) occurs.
method divUnsafe
divUnsafe: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% divided by %%other%%, ignoring underflow (precision loss). A [[NumericFaultError]] is thrown if overflow occurs.
method eq
eq: (other: FixedNumber) => boolean;
Returns true if %%other%% is equal to %%this%%.
method floor
floor: () => FixedNumber;
Returns a new [[FixedNumber]] which is the largest **integer** that is less than or equal to %%this%%.
The decimal component of the result will always be ``0``.
method fromBytes
static fromBytes: (_value: BytesLike, _format?: FixedFormat) => FixedNumber;
Creates a new [[FixedNumber]] with the big-endian representation %%value%% with %%format%%.
This will throw a [[NumericFaultError]] if %%value%% cannot fit in %%format%% due to overflow.
method fromString
static fromString: (_value: string, _format?: FixedFormat) => FixedNumber;
Creates a new [[FixedNumber]] for %%value%% with %%format%%.
This will throw a [[NumericFaultError]] if %%value%% cannot fit in %%format%%, either due to overflow or underflow (precision loss).
method fromValue
static fromValue: ( _value: BigNumberish, _decimals?: Numeric, _format?: FixedFormat) => FixedNumber;
Creates a new [[FixedNumber]] for %%value%% divided by %%decimal%% places with %%format%%.
This will throw a [[NumericFaultError]] if %%value%% (once adjusted for %%decimals%%) cannot fit in %%format%%, either due to overflow or underflow (precision loss).
method gt
gt: (other: FixedNumber) => boolean;
Returns true if %%other%% is greater than to %%this%%.
method gte
gte: (other: FixedNumber) => boolean;
Returns true if %%other%% is greater than or equal to %%this%%.
method isNegative
isNegative: () => boolean;
Returns true if %%this%% is less than ``0``.
method isZero
isZero: () => boolean;
Returns true if %%this%% is equal to ``0``.
method lt
lt: (other: FixedNumber) => boolean;
Returns true if %%other%% is less than to %%this%%.
method lte
lte: (other: FixedNumber) => boolean;
Returns true if %%other%% is less than or equal to %%this%%.
method mul
mul: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% multiplied by %%other%%. A [[NumericFaultError]] is thrown if overflow occurs.
method mulSignal
mulSignal: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% multiplied by %%other%%. A [[NumericFaultError]] is thrown if overflow occurs or if underflow (precision loss) occurs.
method mulUnsafe
mulUnsafe: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% multiplied by %%other%%, ignoring overflow and underflow (precision loss).
method round
round: (decimals?: number) => FixedNumber;
Returns a new [[FixedNumber]] with the decimal component rounded up on ties at %%decimals%% places.
method sub
sub: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%other%% subtracted from %%this%%. A [[NumericFaultError]] is thrown if overflow occurs.
method subUnsafe
subUnsafe: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%other%% subtracted from %%this%%, ignoring overflow.
method toFormat
toFormat: (format: FixedFormat) => FixedNumber;
Return a new [[FixedNumber]] with the same value but has had its field set to %%format%%.
This will throw if the value cannot fit into %%format%%.
method toString
toString: () => string;
Returns the string representation of %%this%%.
method toUnsafeFloat
toUnsafeFloat: () => number;
Returns a float approximation.
Due to IEEE 754 precission (or lack thereof), this function can only return an approximation and most values will contain rounding errors.
class Fragment
abstract class Fragment {}
An abstract class to represent An individual fragment from a parse ABI.
constructor
constructor(guard: any, type: FragmentType, inputs: readonly ParamType[]);
property inputs
readonly inputs: readonly ParamType[];
The inputs for the fragment.
property type
readonly type: FragmentType;
The type of the fragment.
method format
abstract format: (format?: FormatType) => string;
Returns a string representation of this fragment as %%format%%.
method from
static from: (obj: any) => Fragment;
Creates a new **Fragment** for %%obj%%, wich can be any supported ABI frgament type.
method isConstructor
static isConstructor: (value: any) => value is ConstructorFragment;
Returns true if %%value%% is a [[ConstructorFragment]].
method isError
static isError: (value: any) => value is ErrorFragment;
Returns true if %%value%% is an [[ErrorFragment]].
method isEvent
static isEvent: (value: any) => value is EventFragment;
Returns true if %%value%% is an [[EventFragment]].
method isFunction
static isFunction: (value: any) => value is FunctionFragment;
Returns true if %%value%% is a [[FunctionFragment]].
method isStruct
static isStruct: (value: any) => value is StructFragment;
Returns true if %%value%% is a [[StructFragment]].
class FunctionFragment
class FunctionFragment extends NamedFragment {}
A Fragment which represents a method.
constructor
constructor( guard: any, name: string, stateMutability: 'payable' | 'nonpayable' | 'view' | 'pure', inputs: readonly ParamType[], outputs: readonly ParamType[], gas: BigInt);
property constant
readonly constant: boolean;
If the function is constant (e.g. ``pure`` or ``view`` functions).
property gas
readonly gas: BigInt;
The recommended gas limit to send when calling this function.
property outputs
readonly outputs: readonly ParamType[];
The returned types for the result of calling this function.
property payable
readonly payable: boolean;
If the function can be sent value during invocation.
property selector
readonly selector: string;
The Function selector.
property stateMutability
readonly stateMutability: 'payable' | 'nonpayable' | 'view' | 'pure';
The state mutability (e.g. ``payable``, ``nonpayable``, ``view`` or ``pure``)
method format
format: (format?: FormatType) => string;
Returns a string representation of this function as %%format%%.
method from
static from: (obj: any) => FunctionFragment;
Returns a new **FunctionFragment** for %%obj%%.
method getSelector
static getSelector: (name: string, params?: Array<any>) => string;
Return the selector for a function with %%name%% and %%params%%.
method isFragment
static isFragment: (value: any) => value is FunctionFragment;
Returns ``true`` and provides a type guard if %%value%% is a **FunctionFragment**.
class GasCostPlugin
class GasCostPlugin extends NetworkPlugin implements GasCostParameters {}
A **GasCostPlugin** allows a network to provide alternative values when computing the intrinsic gas required for a transaction.
constructor
constructor(effectiveBlock?: number, costs?: GasCostParameters);
Creates a new GasCostPlugin from %%effectiveBlock%% until the latest block or another GasCostPlugin supercedes that block number, with the associated %%costs%%.
property effectiveBlock
readonly effectiveBlock: number;
The block number to treat these values as valid from.
This allows a hardfork to have updated values included as well as mulutiple hardforks to be supported.
property txAccessListAddress
readonly txAccessListAddress: number;
The fee per address in the [[link-eip-2930]] access list.
property txAccessListStorageKey
readonly txAccessListStorageKey: number;
The fee per storage key in the [[link-eip-2930]] access list.
property txBase
readonly txBase: number;
The transactions base fee.
property txCreate
readonly txCreate: number;
The fee for creating a new account.
property txDataNonzero
readonly txDataNonzero: number;
The fee per non-zero-byte in the data.
property txDataZero
readonly txDataZero: number;
The fee per zero-byte in the data.
method clone
clone: () => GasCostPlugin;
class HDNodeVoidWallet
class HDNodeVoidWallet extends VoidSigner {}
A **HDNodeVoidWallet** cannot sign, but provides access to the children nodes of a [[link-bip-32]] HD wallet addresses.
The can be created by using an extended ``xpub`` key to [[HDNodeWallet_fromExtendedKey]] or by [nuetering](HDNodeWallet-neuter) a [[HDNodeWallet]].
constructor
constructor( guard: any, address: string, publicKey: string, parentFingerprint: string, chainCode: string, path: string, index: number, depth: number, provider: Provider);
property chainCode
readonly chainCode: string;
The chaincode, which is effectively a public key used to derive children.
property depth
readonly depth: number;
The depth of this wallet, which is the number of components in its path.
property extendedKey
readonly extendedKey: string;
The extended key.
This key will begin with the prefix ``xpub`` and can be used to reconstruct this neutered key to derive its children addresses.
property fingerprint
readonly fingerprint: string;
The fingerprint.
A fingerprint allows quick qay to detect parent and child nodes, but developers should be prepared to deal with collisions as it is only 4 bytes.
property index
readonly index: number;
The child index of this wallet. Values over ``2 ** 31`` indicate the node is hardened.
property parentFingerprint
readonly parentFingerprint: string;
The parent node fingerprint.
property path
readonly path: string;
The derivation path of this wallet.
Since extended keys do not provider full path details, this may be ``null``, if instantiated from a source that does not enocde it.
property publicKey
readonly publicKey: string;
The compressed public key.
method connect
connect: (provider: null | Provider) => HDNodeVoidWallet;
method deriveChild
deriveChild: (_index: Numeric) => HDNodeVoidWallet;
Return the child for %%index%%.
method derivePath
derivePath: (path: string) => HDNodeVoidWallet;
Return the signer for %%path%% from this node.
method hasPath
hasPath: () => this is { path: string };
Returns true if this wallet has a path, providing a Type Guard that the path is non-null.
class HDNodeWallet
class HDNodeWallet extends BaseWallet {}
An **HDNodeWallet** is a [[Signer]] backed by the private key derived from an HD Node using the [[link-bip-32]] stantard.
An HD Node forms a hierarchal structure with each HD Node having a private key and the ability to derive child HD Nodes, defined by a path indicating the index of each child.
constructor
constructor( guard: any, signingKey: SigningKey, parentFingerprint: string, chainCode: string, path: string, index: number, depth: number, mnemonic: Mnemonic, provider: Provider);
property chainCode
readonly chainCode: string;
The chaincode, which is effectively a public key used to derive children.
property depth
readonly depth: number;
The depth of this wallet, which is the number of components in its path.
property extendedKey
readonly extendedKey: string;
The extended key.
This key will begin with the prefix ``xpriv`` and can be used to reconstruct this HD Node to derive its children.
property fingerprint
readonly fingerprint: string;
The fingerprint.
A fingerprint allows quick qay to detect parent and child nodes, but developers should be prepared to deal with collisions as it is only 4 bytes.
property index
readonly index: number;
The child index of this wallet. Values over ``2 ** 31`` indicate the node is hardened.
property mnemonic
readonly mnemonic: Mnemonic;
The mnemonic used to create this HD Node, if available.
Sources such as extended keys do not encode the mnemonic, in which case this will be ``null``.
property parentFingerprint
readonly parentFingerprint: string;
The parent fingerprint.
property path
readonly path: string;
The derivation path of this wallet.
Since extended keys do not provide full path details, this may be ``null``, if instantiated from a source that does not encode it.
property publicKey
readonly publicKey: string;
The compressed public key.
method connect
connect: (provider: null | Provider) => HDNodeWallet;
method createRandom
static createRandom: ( password?: string, path?: string, wordlist?: Wordlist) => HDNodeWallet;
Creates a new random HDNode.
method deriveChild
deriveChild: (_index: Numeric) => HDNodeWallet;
Return the child for %%index%%.
method derivePath
derivePath: (path: string) => HDNodeWallet;
Return the HDNode for %%path%% from this node.
method encrypt
encrypt: ( password: Uint8Array | string, progressCallback?: ProgressCallback) => Promise<string>;
Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with %%password%%.
If %%progressCallback%% is specified, it will receive periodic updates as the encryption process progreses.
method encryptSync
encryptSync: (password: Uint8Array | string) => string;
Returns a [JSON Keystore Wallet](json-wallets) encryped with %%password%%.
It is preferred to use the [async version](encrypt) instead, which allows a [[ProgressCallback]] to keep the user informed.
This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial duration.
method fromExtendedKey
static fromExtendedKey: (extendedKey: string) => HDNodeWallet | HDNodeVoidWallet;
Creates a new HD Node from %%extendedKey%%.
If the %%extendedKey%% will either have a prefix or ``xpub`` or ``xpriv``, returning a neutered HD Node ([[HDNodeVoidWallet]]) or full HD Node ([[HDNodeWallet) respectively.
method fromMnemonic
static fromMnemonic: (mnemonic: Mnemonic, path?: string) => HDNodeWallet;
Create an HD Node from %%mnemonic%%.
method fromPhrase
static fromPhrase: ( phrase: string, password?: string, path?: string, wordlist?: Wordlist) => HDNodeWallet;
Creates an HD Node from a mnemonic %%phrase%%.
method fromSeed
static fromSeed: (seed: BytesLike) => HDNodeWallet;
Creates an HD Node from a %%seed%%.
method hasPath
hasPath: () => this is { path: string };
Returns true if this wallet has a path, providing a Type Guard that the path is non-null.
method neuter
neuter: () => HDNodeVoidWallet;
Returns a neutered HD Node, which removes the private details of an HD Node.
A neutered node has no private key, but can be used to derive child addresses and other public data about the HD Node.
class Indexed
class Indexed {}
An **Indexed** is used as a value when a value that does not fit within a topic (i.e. not a fixed-length, 32-byte type). It is the ``keccak256`` of the value, and used for types such as arrays, tuples, bytes and strings.
constructor
constructor(hash: string);
@_ignore:
property hash
readonly hash: string;
The ``keccak256`` of the value logged.
method isIndexed
static isIndexed: (value: any) => value is Indexed;
Returns ``true`` if %%value%% is an **Indexed**.
This provides a Type Guard for property access.
class InfuraProvider
class InfuraProvider extends JsonRpcProvider implements CommunityResourcable {}
The **InfuraProvider** connects to the [[link-infura]] JSON-RPC end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-infura-signup).
constructor
constructor(_network?: Networkish, projectId?: string, projectSecret?: string);
Creates a new **InfuraProvider**.
property projectId
readonly projectId: string;
The Project ID for the INFURA connection.
property projectSecret
readonly projectSecret: string;
The Project Secret.
If null, no authenticated requests are made. This should not be used outside of private contexts.
method getRequest
static getRequest: ( network: Network, projectId?: null | string, projectSecret?: null | string) => FetchRequest;
Returns a prepared request for connecting to %%network%% with %%projectId%% and %%projectSecret%%.
method getWebSocketProvider
static getWebSocketProvider: ( network?: Networkish, projectId?: string) => InfuraWebSocketProvider;
Creates a new **InfuraWebSocketProvider**.
method isCommunityResource
isCommunityResource: () => boolean;
class InfuraWebSocketProvider
class InfuraWebSocketProvider extends WebSocketProvider implements CommunityResourcable {}
The **InfuraWebSocketProvider** connects to the [[link-infura]] WebSocket end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-infura-signup).
constructor
constructor(network?: Networkish, projectId?: string);
Creates a new **InfuraWebSocketProvider**.
property projectId
readonly projectId: string;
The Project ID for the INFURA connection.
property projectSecret
readonly projectSecret: string;
The Project Secret.
If null, no authenticated requests are made. This should not be used outside of private contexts.
method isCommunityResource
isCommunityResource: () => boolean;
class Interface
class Interface {}
An Interface abstracts many of the low-level details for encoding and decoding the data on the blockchain.
An ABI provides information on how to encode data to send to a Contract, how to decode the results and events and how to interpret revert errors.
The ABI can be specified by [any supported format](InterfaceAbi).
constructor
constructor(fragments: InterfaceAbi);
Create a new Interface for the %%fragments%%.
property deploy
readonly deploy: ConstructorFragment;
The Contract constructor.
property fallback
readonly fallback: FallbackFragment;
The Fallback method, if any.
property fragments
readonly fragments: readonly Fragment[];
All the Contract ABI members (i.e. methods, events, errors, etc).
property receive
readonly receive: boolean;
If receiving ether is supported.
method decodeErrorResult
decodeErrorResult: (fragment: ErrorFragment | string, data: BytesLike) => Result;
Decodes the result %%data%% (e.g. from an ``eth_call``) for the specified error (see [[getError]] for valid values for %%key%%).
Most developers should prefer the [[parseCallResult]] method instead, which will automatically detect a ``CALL_EXCEPTION`` and throw the corresponding error.
method decodeEventLog
decodeEventLog: ( fragment: EventFragment | string, data: BytesLike, topics?: ReadonlyArray<string>) => Result;
method decodeFunctionData
decodeFunctionData: ( fragment: FunctionFragment | string, data: BytesLike) => Result;
Decodes the %%data%% from a transaction ``tx.data`` for the function specified (see [[getFunction]] for valid values for %%fragment%%).
Most developers should prefer the [[parseTransaction]] method instead, which will automatically detect the fragment.
method decodeFunctionResult
decodeFunctionResult: ( fragment: FunctionFragment | string, data: BytesLike) => Result;
Decodes the result %%data%% (e.g. from an ``eth_call``) for the specified function (see [[getFunction]] for valid values for %%key%%).
Most developers should prefer the [[parseCallResult]] method instead, which will automatically detect a ``CALL_EXCEPTION`` and throw the corresponding error.
method encodeDeploy
encodeDeploy: (values?: ReadonlyArray<any>) => string;
Encodes a ``tx.data`` object for deploying the Contract with the %%values%% as the constructor arguments.
method encodeErrorResult
encodeErrorResult: ( fragment: ErrorFragment | string, values?: ReadonlyArray<any>) => string;
Encodes the transaction revert data for a call result that reverted from the the Contract with the sepcified %%error%% (see [[getError]] for valid values for %%fragment%%) with the %%values%%.
This is generally not used by most developers, unless trying to mock a result from a Contract.
method encodeEventLog
encodeEventLog: ( fragment: EventFragment | string, values: ReadonlyArray<any>) => { data: string; topics: Array<string> };
method encodeFilterTopics
encodeFilterTopics: ( fragment: EventFragment | string, values: ReadonlyArray<any>) => Array<null | string | Array<string>>;
method encodeFunctionData
encodeFunctionData: ( fragment: FunctionFragment | string, values?: ReadonlyArray<any>) => string;
Encodes the ``tx.data`` for a transaction that calls the function specified (see [[getFunction]] for valid values for %%fragment%%) with the %%values%%.
method encodeFunctionResult
encodeFunctionResult: ( fragment: FunctionFragment | string, values?: ReadonlyArray<any>) => string;
Encodes the result data (e.g. from an ``eth_call``) for the specified function (see [[getFunction]] for valid values for %%fragment%%) with %%values%%.
This is generally not used by most developers, unless trying to mock a result from a Contract.
method forEachError
forEachError: (callback: (func: ErrorFragment, index: number) => void) => void;
Iterate over all errors, calling %%callback%%, sorted by their name.
method forEachEvent
forEachEvent: (callback: (func: EventFragment, index: number) => void) => void;
Iterate over all events, calling %%callback%%, sorted by their name.
method forEachFunction
forEachFunction: ( callback: (func: FunctionFragment, index: number) => void) => void;
Iterate over all functions, calling %%callback%%, sorted by their name.
method format
format: (minimal?: boolean) => Array<string>;
Returns the entire Human-Readable ABI, as an array of signatures, optionally as %%minimal%% strings, which removes parameter names and unneceesary spaces.
method formatJson
formatJson: () => string;
Return the JSON-encoded ABI. This is the format Solidiy returns.
method from
static from: (value: InterfaceAbi | Interface) => Interface;
Creates a new [[Interface]] from the ABI %%value%%.
The %%value%% may be provided as an existing [[Interface]] object, a JSON-encoded ABI or any Human-Readable ABI format.
method getAbiCoder
getAbiCoder: () => AbiCoder;
The ABI coder that will be used to encode and decode binary data.
method getError
getError: (key: string, values?: Array<any | Typed>) => null | ErrorFragment;
Get the [[ErrorFragment]] for %%key%%, which may be an error selector, error name or error signature that belongs to the ABI.
If %%values%% is provided, it will use the Typed API to handle ambiguous cases where multiple errors match by name.
If the %%key%% and %%values%% do not refine to a single error in the ABI, this will throw.
method getEvent
getEvent: (key: string, values?: Array<any | Typed>) => null | EventFragment;
Get the [[EventFragment]] for %%key%%, which may be a topic hash, event name or event signature that belongs to the ABI.
If %%values%% is provided, it will use the Typed API to handle ambiguous cases where multiple events match by name.
If the %%key%% and %%values%% do not refine to a single event in the ABI, this will throw.
method getEventName
getEventName: (key: string) => string;
Get the event name for %%key%%, which may be a topic hash, event name or event signature that belongs to the ABI.
method getFunction
getFunction: ( key: string, values?: Array<any | Typed>) => null | FunctionFragment;
Get the [[FunctionFragment]] for %%key%%, which may be a function selector, function name or function signature that belongs to the ABI.
If %%values%% is provided, it will use the Typed API to handle ambiguous cases where multiple functions match by name.
If the %%key%% and %%values%% do not refine to a single function in the ABI, this will throw.
method getFunctionName
getFunctionName: (key: string) => string;
Get the function name for %%key%%, which may be a function selector, function name or function signature that belongs to the ABI.
method hasEvent
hasEvent: (key: string) => boolean;
Returns true if %%key%% (an event topic hash, event name or event signature) is present in the ABI.
In the case of an event name, the name may be ambiguous, so accessing the [[EventFragment]] may require refinement.
method hasFunction
hasFunction: (key: string) => boolean;
Returns true if %%key%% (a function selector, function name or function signature) is present in the ABI.
In the case of a function name, the name may be ambiguous, so accessing the [[FunctionFragment]] may require refinement.
method makeError
makeError: ( _data: BytesLike, tx: CallExceptionTransaction) => CallExceptionError;
method parseCallResult
parseCallResult: (data: BytesLike) => Result;
method parseError
parseError: (data: BytesLike) => null | ErrorDescription;
Parses a revert data, finding the matching error and extracts the parameter values along with other useful error details.
If the matching error cannot be found, returns null.
method parseLog
parseLog: (log: { topics: ReadonlyArray<string>; data: string;}) => null | LogDescription;
Parses a receipt log, finding the matching event and extracts the parameter values along with other useful event details.
If the matching event cannot be found, returns null.
method parseTransaction
parseTransaction: (tx: { data: string; value?: BigNumberish;}) => null | TransactionDescription;
Parses a transaction, finding the matching function and extracts the parameter values along with other useful function details.
If the matching function cannot be found, return null.
class IpcSocketProvider
class IpcSocketProvider extends SocketProvider {}
An **IpcSocketProvider** connects over an IPC socket on the host which provides fast access to the node, but requires the node and the script run on the same machine.
constructor
constructor( path: string, network?: Networkish, options?: JsonRpcApiProviderOptions);
property socket
readonly socket: Socket;
The connected socket.
method destroy
destroy: () => void;
class JsonRpcApiProvider
abstract class JsonRpcApiProvider extends AbstractProvider {}
The JsonRpcApiProvider is an abstract class and **MUST** be sub-classed.
It provides the base for all JSON-RPC-based Provider interaction.
Sub-classing Notes: - a sub-class MUST override _send - a sub-class MUST call the
_start()
method once connected
constructor
constructor(network?: Networkish, options?: JsonRpcApiProviderOptions);
property ready
readonly ready: boolean;
Returns true only if the [[_start]] has been called.
method destroy
destroy: () => void;
method getRpcError
getRpcError: (payload: JsonRpcPayload, _error: JsonRpcError) => Error;
Returns an ethers-style Error for the given JSON-RPC error %%payload%%, coalescing the various strings and error shapes that different nodes return, coercing them into a machine-readable standardized error.
method getRpcRequest
getRpcRequest: ( req: PerformActionRequest) => null | { method: string; args: Array<any> };
Returns the request method and arguments required to perform %%req%%.
method getRpcTransaction
getRpcTransaction: (tx: TransactionRequest) => JsonRpcTransactionRequest;
Returns %%tx%% as a normalized JSON-RPC transaction request, which has all values hexlified and any numeric values converted to Quantity values.
method getSigner
getSigner: (address?: number | string) => Promise<JsonRpcSigner>;
Resolves to the [[Signer]] account for %%address%% managed by the client.
If the %%address%% is a number, it is used as an index in the the accounts from [[listAccounts]].
This can only be used on clients which manage accounts (such as Geth with imported account or MetaMask).
Throws if the account doesn't exist.
method listAccounts
listAccounts: () => Promise<Array<JsonRpcSigner>>;
method send
send: (method: string, params: Array<any> | Record<string, any>) => Promise<any>;
Requests the %%method%% with %%params%% via the JSON-RPC protocol over the underlying channel. This can be used to call methods on the backend that do not have a high-level API within the Provider API.
This method queues requests according to the batch constraints in the options, assigns the request a unique ID.
**Do NOT override** this method in sub-classes; instead override [[_send]] or force the options values in the call to the constructor to modify this method's behavior.
class JsonRpcProvider
class JsonRpcProvider extends JsonRpcApiPollingProvider {}
The JsonRpcProvider is one of the most common Providers, which performs all operations over HTTP (or HTTPS) requests.
Events are processed by polling the backend for the current block number; when it advances, all block-base events are then checked for updates.
constructor
constructor( url?: string | FetchRequest, network?: Networkish, options?: JsonRpcApiProviderOptions);
method send
send: (method: string, params: Array<any> | Record<string, any>) => Promise<any>;
class JsonRpcSigner
class JsonRpcSigner extends AbstractSigner<JsonRpcApiProvider> {}
constructor
constructor(provider: JsonRpcApiProvider, address: string);
property address
address: string;
method connect
connect: (provider: null | Provider) => Signer;
method getAddress
getAddress: () => Promise<string>;
method populateTransaction
populateTransaction: ( tx: TransactionRequest) => Promise<TransactionLike<string>>;
method sendTransaction
sendTransaction: (tx: TransactionRequest) => Promise<TransactionResponse>;
method sendUncheckedTransaction
sendUncheckedTransaction: (_tx: TransactionRequest) => Promise<string>;
method signMessage
signMessage: (_message: string | Uint8Array) => Promise<string>;
method signTransaction
signTransaction: (_tx: TransactionRequest) => Promise<string>;
method signTypedData
signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, _value: Record<string, any>) => Promise<string>;
method unlock
unlock: (password: string) => Promise<boolean>;
class LangEn
class LangEn extends WordlistOwl {}
The [[link-bip39-en]] for [mnemonic phrases](link-bip-39).
@_docloc: api/wordlists
constructor
constructor();
Creates a new instance of the English language Wordlist.
This should be unnecessary most of the time as the exported [[langEn]] should suffice.
@_ignore:
method wordlist
static wordlist: () => LangEn;
Returns a singleton instance of a ``LangEn``, creating it if this is the first time being called.
class Log
class Log implements LogParams {}
A **Log** in Ethereum represents an event that has been included in a transaction using the ``LOG*`` opcodes, which are most commonly used by Solidity's emit for announcing events.
constructor
constructor(log: LogParams, provider: Provider);
@_ignore:
property address
readonly address: string;
The address of the contract that emitted this log.
property blockHash
readonly blockHash: string;
The block hash of the block this log occurred in. Use the [[Log-getBlock]] to get the [[Block]].
property blockNumber
readonly blockNumber: number;
The block number of the block this log occurred in. It is preferred to use the [[Block-hash]] when fetching the related [[Block]], since in the case of an orphaned block, the block at that height may have changed.
property data
readonly data: string;
The data included in this log when it was emitted.
property index
readonly index: number;
The index within the block this log occurred at. This is generally not useful to developers, but can be used with the various roots to proof inclusion within a block.
property provider
readonly provider: Provider;
The provider connected to the log used to fetch additional details if necessary.
property removed
readonly removed: boolean;
If the **Log** represents a block that was removed due to an orphaned block, this will be true.
This can only happen within an orphan event listener.
property topics
readonly topics: readonly string[];
The indexed topics included in this log when it was emitted.
All topics are included in the bloom filters, so they can be efficiently filtered using the [[Provider-getLogs]] method.
property transactionHash
readonly transactionHash: string;
The transaction hash of the transaction this log occurred in. Use the [[Log-getTransaction]] to get the [[TransactionResponse]].
property transactionIndex
readonly transactionIndex: number;
The index within the transaction of this log.
method getBlock
getBlock: () => Promise<Block>;
Returns the block that this log occurred in.
method getTransaction
getTransaction: () => Promise<TransactionResponse>;
Returns the transaction that this log occurred in.
method getTransactionReceipt
getTransactionReceipt: () => Promise<TransactionReceipt>;
Returns the transaction receipt fot the transaction that this log occurred in.
method removedEvent
removedEvent: () => OrphanFilter;
@_ignore:
method toJSON
toJSON: () => any;
Returns a JSON-compatible object.
class LogDescription
class LogDescription {}
When using the [[Interface-parseLog]] to automatically match a Log to its event for parsing, a **LogDescription** is returned.
constructor
constructor(fragment: EventFragment, topic: string, args: Result);
@_ignore:
property args
readonly args: Result;
The arguments passed into the Event with ``emit``.
property fragment
readonly fragment: EventFragment;
The matching fragment for the ``topic0``.
property name
readonly name: string;
The name of the Event.
property signature
readonly signature: string;
The full Event signature.
property topic
readonly topic: string;
The topic hash for the Event.
class Mnemonic
class Mnemonic {}
A **Mnemonic** wraps all properties required to compute [[link-bip-39]] seeds and convert between phrases and entropy.
constructor
constructor( guard: any, entropy: string, phrase: string, password?: string, wordlist?: Wordlist);
property entropy
readonly entropy: string;
The underlying entropy which the mnemonic encodes.
property password
readonly password: string;
The password used for this mnemonic. If no password is used this is the empty string (i.e. ``""``) as per the specification.
property phrase
readonly phrase: string;
The mnemonic phrase of 12, 15, 18, 21 or 24 words.
Use the [[wordlist]] ``split`` method to get the individual words.
property wordlist
readonly wordlist: Wordlist;
The wordlist for this mnemonic.
method computeSeed
computeSeed: () => string;
Returns the seed for the mnemonic.
method entropyToPhrase
static entropyToPhrase: ( _entropy: BytesLike, wordlist?: null | Wordlist) => string;
Returns the phrase for %%mnemonic%%.
method fromEntropy
static fromEntropy: ( _entropy: BytesLike, password?: null | string, wordlist?: null | Wordlist) => Mnemonic;
Create a new **Mnemonic** from the %%entropy%%.
The default %%password%% is the empty string and the default wordlist is the [English wordlists](LangEn).
method fromPhrase
static fromPhrase: ( phrase: string, password?: null | string, wordlist?: null | Wordlist) => Mnemonic;
Creates a new Mnemonic for the %%phrase%%.
The default %%password%% is the empty string and the default wordlist is the [English wordlists](LangEn).
method isValidMnemonic
static isValidMnemonic: (phrase: string, wordlist?: null | Wordlist) => boolean;
Returns true if %%phrase%% is a valid [[link-bip-39]] phrase.
This checks all the provided words belong to the %%wordlist%%, that the length is valid and the checksum is correct.
method phraseToEntropy
static phraseToEntropy: (phrase: string, wordlist?: null | Wordlist) => string;
Returns the entropy for %%phrase%%.
class MulticoinProviderPlugin
abstract class MulticoinProviderPlugin implements AbstractProviderPlugin {}
A provider plugin super-class for processing multicoin address types.
constructor
constructor(name: string);
Creates a new **MulticoinProviderPluing** for %%name%%.
property name
readonly name: string;
The name.
method connect
connect: (proivder: Provider) => MulticoinProviderPlugin;
method decodeAddress
decodeAddress: (coinType: number, data: BytesLike) => Promise<string>;
Resolves to the decoded %%data%% for %%coinType%%.
method encodeAddress
encodeAddress: (coinType: number, address: string) => Promise<string>;
Resolves to the encoded %%address%% for %%coinType%%.
method supportsCoinType
supportsCoinType: (coinType: number) => boolean;
Returns ``true`` if %%coinType%% is supported by this plugin.
class NamedFragment
abstract class NamedFragment extends Fragment {}
An abstract class to represent An individual fragment which has a name from a parse ABI.
constructor
constructor( guard: any, type: FragmentType, name: string, inputs: readonly ParamType[]);
property name
readonly name: string;
The name of the fragment.
class Network
class Network {}
A **Network** provides access to a chain's properties and allows for plug-ins to extend functionality.
constructor
constructor(name: string, chainId: BigNumberish);
Creates a new **Network** for %%name%% and %%chainId%%.
property chainId
chainId: BigInt;
The network chain ID.
property name
name: string;
The network common name.
This is the canonical name, as networks migh have multiple names.
property plugins
readonly plugins: NetworkPlugin[];
Returns the list of plugins currently attached to this Network.
method attachPlugin
attachPlugin: (plugin: NetworkPlugin) => this;
Attach a new %%plugin%% to this Network. The network name must be unique, excluding any fragment.
method clone
clone: () => Network;
Create a copy of this Network.
method computeIntrinsicGas
computeIntrinsicGas: (tx: TransactionLike) => number;
Compute the intrinsic gas required for a transaction.
A GasCostPlugin can be attached to override the default values.
method from
static from: (network?: Networkish) => Network;
Returns a new Network for the %%network%% name or chainId.
method getPlugin
getPlugin: <T extends NetworkPlugin = NetworkPlugin>(name: string) => null | T;
Return the plugin, if any, matching %%name%% exactly. Plugins with fragments will not be returned unless %%name%% includes a fragment.
method getPlugins
getPlugins: <T extends NetworkPlugin = NetworkPlugin>( basename: string) => Array<T>;
Gets a list of all plugins that match %%name%%, with otr without a fragment.
method matches
matches: (other: Networkish) => boolean;
Returns true if %%other%% matches this network. Any chain ID must match, and if no chain ID is present, the name must match.
This method does not currently check for additional properties, such as ENS address or plug-in compatibility.
method register
static register: ( nameOrChainId: string | number | bigint, networkFunc: () => Network) => void;
Register %%nameOrChainId%% with a function which returns an instance of a Network representing that chain.
method toJSON
toJSON: () => any;
Returns a JSON-compatible representation of a Network.
class NetworkPlugin
class NetworkPlugin {}
A **NetworkPlugin** provides additional functionality on a [[Network]].
constructor
constructor(name: string);
Creates a new **NetworkPlugin**.
property name
readonly name: string;
The name of the plugin.
It is recommended to use reverse-domain-notation, which permits unique names with a known authority as well as hierarchal entries.
method clone
clone: () => NetworkPlugin;
Creates a copy of this plugin.
class NonceManager
class NonceManager extends AbstractSigner {}
A **NonceManager** wraps another [[Signer]] and automatically manages the nonce, ensuring serialized and sequential nonces are used during transaction.
constructor
constructor(signer: Signer);
Creates a new **NonceManager** to manage %%signer%%.
property signer
signer: Signer;
The Signer being managed.
method connect
connect: (provider: null | Provider) => NonceManager;
method getAddress
getAddress: () => Promise<string>;
method getNonce
getNonce: (blockTag?: BlockTag) => Promise<number>;
method increment
increment: () => void;
Manually increment the nonce. This may be useful when managng offline transactions.
method reset
reset: () => void;
Resets the nonce, causing the **NonceManager** to reload the current nonce from the blockchain on the next transaction.
method sendTransaction
sendTransaction: (tx: TransactionRequest) => Promise<TransactionResponse>;
method signMessage
signMessage: (message: string | Uint8Array) => Promise<string>;
method signTransaction
signTransaction: (tx: TransactionRequest) => Promise<string>;
method signTypedData
signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => Promise<string>;
class ParamType
class ParamType {}
Each input and output of a [[Fragment]] is an Array of **ParamType**.
constructor
constructor( guard: any, name: string, type: string, baseType: string, indexed: boolean, components: readonly ParamType[], arrayLength: number, arrayChildren: ParamType);
property arrayChildren
readonly arrayChildren: ParamType;
The type of each child in the array.
For non-array types this is ``null``.
property arrayLength
readonly arrayLength: number;
The array length, or ``-1`` for dynamic-lengthed arrays.
For non-array types this is ``null``.
property baseType
readonly baseType: string;
The base type (e.g. ``"address"``, ``"tuple"``, ``"array"``)
property components
readonly components: readonly ParamType[];
The components for the tuple.
For non-tuple types this is ``null``.
property indexed
readonly indexed: boolean;
True if the parameters is indexed.
For non-indexable types this is ``null``.
property name
readonly name: string;
The local name of the parameter (or ``""`` if unbound)
property type
readonly type: string;
The fully qualified type (e.g. ``"address"``, ``"tuple(address)"``, ``"uint256[3][]"``)
method format
format: (format?: FormatType) => string;
Return a string representation of this type.
For example,
``sighash" => "(uint256,address)"``
``"minimal" => "tuple(uint256,address) indexed"``
``"full" => "tuple(uint256 foo, address bar) indexed baz"``
method from
static from: (obj: any, allowIndexed?: boolean) => ParamType;
Creates a new **ParamType** for %%obj%%.
If %%allowIndexed%% then the ``indexed`` keyword is permitted, otherwise the ``indexed`` keyword will throw an error.
method isArray
isArray: () => this is ParamType & { arrayChildren: ParamType; arrayLength: number;};
Returns true if %%this%% is an Array type.
This provides a type gaurd ensuring that [[arrayChildren]] and [[arrayLength]] are non-null.
method isIndexable
isIndexable: () => this is ParamType & { indexed: boolean };
Returns true if %%this%% is an Indexable type.
This provides a type gaurd ensuring that [[indexed]] is non-null.
method isParamType
static isParamType: (value: any) => value is ParamType;
Returns true if %%value%% is a **ParamType**.
method isTuple
isTuple: () => this is ParamType & { components: ReadonlyArray<ParamType> };
Returns true if %%this%% is a Tuple type.
This provides a type gaurd ensuring that [[components]] is non-null.
method walk
walk: (value: any, process: ParamTypeWalkFunc) => any;
Walks the **ParamType** with %%value%%, calling %%process%% on each type, destructing the %%value%% recursively.
method walkAsync
walkAsync: (value: any, process: ParamTypeWalkAsyncFunc) => Promise<any>;
Walks the **ParamType** with %%value%%, asynchronously calling %%process%% on each type, destructing the %%value%% recursively.
This can be used to resolve ENS names by walking and resolving each ``"address"`` type.
class PocketProvider
class PocketProvider extends JsonRpcProvider implements CommunityResourcable {}
The **PocketProvider** connects to the [[link-pocket]] JSON-RPC end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-pocket-signup).
constructor
constructor( _network?: Networkish, applicationId?: string, applicationSecret?: string);
Create a new **PocketProvider**.
By default connecting to ``mainnet`` with a highly throttled API key.
property applicationId
readonly applicationId: string;
The Application ID for the Pocket connection.
property applicationSecret
readonly applicationSecret: string;
The Application Secret for making authenticated requests to the Pocket connection.
method getRequest
static getRequest: ( network: Network, applicationId?: null | string, applicationSecret?: null | string) => FetchRequest;
Returns a prepared request for connecting to %%network%% with %%applicationId%%.
method isCommunityResource
isCommunityResource: () => boolean;
class QuickNodeProvider
class QuickNodeProvider extends JsonRpcProvider implements CommunityResourcable {}
The **QuickNodeProvider** connects to the [[link-quicknode]] JSON-RPC end-points.
By default, a highly-throttled API token is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-quicknode).
constructor
constructor(_network?: Networkish, token?: string);
Creates a new **QuickNodeProvider**.
property token
readonly token: string;
The API token.
method getRequest
static getRequest: (network: Network, token?: null | string) => FetchRequest;
Returns a new request prepared for %%network%% and the %%token%%.
method isCommunityResource
isCommunityResource: () => boolean;
class Result
class Result extends Array<any> {}
A [[Result]] is a sub-class of Array, which allows accessing any of its values either positionally by its index or, if keys are provided by its name.
@_docloc: api/abi
constructor
constructor(...args: any[]);
method filter
filter: ( callback: (el: any, index: number, array: Result) => boolean, thisArg?: any) => Result;
@_ignore
method fromItems
static fromItems: (items: Array<any>, keys?: Array<null | string>) => Result;
Creates a new [[Result]] for %%items%% with each entry also accessible by its corresponding name in %%keys%%.
method getValue
getValue: (name: string) => any;
Returns the value for %%name%%.
Since it is possible to have a key whose name conflicts with a method on a [[Result]] or its superclass Array, or any JavaScript keyword, this ensures all named values are still accessible by name.
method map
map: <T extends unknown = any>( callback: (el: any, index: number, array: Result) => T, thisArg?: any) => Array<T>;
@_ignore
method slice
slice: (start?: number | undefined, end?: number | undefined) => Result;
@_ignore
method toArray
toArray: (deep?: boolean) => Array<any>;
Returns the Result as a normal Array. If %%deep%%, any children which are Result objects are also converted to a normal Array.
This will throw if there are any outstanding deferred errors.
method toObject
toObject: (deep?: boolean) => Record<string, any>;
Returns the Result as an Object with each name-value pair. If %%deep%%, any children which are Result objects are also converted to an Object.
This will throw if any value is unnamed, or if there are any outstanding deferred errors.
class Signature
class Signature {}
A Signature
@_docloc: api/crypto:Signing
constructor
constructor(guard: any, r: string, s: string, v: 27 | 28);
property compactSerialized
readonly compactSerialized: string;
The [[link-eip-2098]] compact representation.
property legacyChainId
readonly legacyChainId: BigInt;
The chain ID for EIP-155 legacy transactions. For non-legacy transactions, this value is ``null``.
property networkV
readonly networkV: BigInt;
The EIP-155 ``v`` for legacy transactions. For non-legacy transactions, this value is ``null``.
property r
r: string;
The ``r`` value for a signautre.
This represents the ``x`` coordinate of a "reference" or challenge point, from which the ``y`` can be computed.
property s
s: string;
The ``s`` value for a signature.
property serialized
readonly serialized: string;
The serialized representation.
property v
v: 27 | 28;
The ``v`` value for a signature.
Since a given ``x`` value for ``r`` has two possible values for its correspondin ``y``, the ``v`` indicates which of the two ``y`` values to use.
It is normalized to the values ``27`` or ``28`` for legacy purposes.
property yParity
readonly yParity: 0 | 1;
The ``yParity`` for the signature.
See ``v`` for more details on how this value is used.
property yParityAndS
readonly yParityAndS: string;
The [[link-eip-2098]] compact representation of the ``yParity`` and ``s`` compacted into a single ``bytes32``.
method clone
clone: () => Signature;
Returns a new identical [[Signature]].
method from
static from: (sig?: SignatureLike) => Signature;
Creates a new [[Signature]].
If no %%sig%% is provided, a new [[Signature]] is created with default values.
If %%sig%% is a string, it is parsed.
method getChainId
static getChainId: (v: BigNumberish) => bigint;
Compute the chain ID from the ``v`` in a legacy EIP-155 transactions.
@example: Signature.getChainId(45) //_result:
Signature.getChainId(46) //_result:
method getChainIdV
static getChainIdV: (chainId: BigNumberish, v: 27 | 28) => bigint;
Compute the ``v`` for a chain ID for a legacy EIP-155 transactions.
Legacy transactions which use [[link-eip-155]] hijack the ``v`` property to include the chain ID.
@example: Signature.getChainIdV(5, 27) //_result:
Signature.getChainIdV(5, 28) //_result:
method getNormalizedV
static getNormalizedV: (v: BigNumberish) => 27 | 28;
Compute the normalized legacy transaction ``v`` from a ``yParirty``, a legacy transaction ``v`` or a legacy [[link-eip-155]] transaction.
@example: // The values 0 and 1 imply v is actually yParity Signature.getNormalizedV(0) //_result:
// Legacy non-EIP-1559 transaction (i.e. 27 or 28) Signature.getNormalizedV(27) //_result:
// Legacy EIP-155 transaction (i.e. >= 35) Signature.getNormalizedV(46) //_result:
// Invalid values throw Signature.getNormalizedV(5) //_error:
method toJSON
toJSON: () => any;
Returns a representation that is compatible with ``JSON.stringify``.
class SigningKey
class SigningKey {}
A **SigningKey** provides high-level access to the elliptic curve cryptography (ECC) operations and key management.
constructor
constructor(privateKey: BytesLike);
Creates a new **SigningKey** for %%privateKey%%.
property compressedPublicKey
readonly compressedPublicKey: string;
The compressed public key.
This will always begin with either the prefix ``0x02`` or ``0x03`` and be 68 characters long (the ``0x`` prefix and 33 hexadecimal nibbles)
property privateKey
readonly privateKey: string;
The private key.
property publicKey
readonly publicKey: string;
The uncompressed public key.
This will always begin with the prefix ``0x04`` and be 132 characters long (the ``0x`` prefix and 130 hexadecimal nibbles).
method addPoints
static addPoints: (p0: BytesLike, p1: BytesLike, compressed?: boolean) => string;
Returns the point resulting from adding the ellipic curve points %%p0%% and %%p1%%.
This is not a common function most developers should require, but can be useful for certain privacy-specific techniques.
For example, it is used by [[HDNodeWallet]] to compute child addresses from parent public keys and chain codes.
method computePublicKey
static computePublicKey: (key: BytesLike, compressed?: boolean) => string;
Compute the public key for %%key%%, optionally %%compressed%%.
The %%key%% may be any type of key, a raw public key, a compressed/uncompressed public key or private key.
@example: sign = new SigningKey(id("some-secret"));
// Compute the uncompressed public key for a private key SigningKey.computePublicKey(sign.privateKey) //_result:
// Compute the compressed public key for a private key SigningKey.computePublicKey(sign.privateKey, true) //_result:
// Compute the uncompressed public key SigningKey.computePublicKey(sign.publicKey, false); //_result:
// Compute the Compressed a public key SigningKey.computePublicKey(sign.publicKey, true); //_result:
method computeSharedSecret
computeSharedSecret: (other: BytesLike) => string;
Returns the [[link-wiki-ecdh]] shared secret between this private key and the %%other%% key.
The %%other%% key may be any type of key, a raw public key, a compressed/uncompressed pubic key or aprivate key.
Best practice is usually to use a cryptographic hash on the returned value before using it as a symetric secret.
@example: sign1 = new SigningKey(id("some-secret-1")) sign2 = new SigningKey(id("some-secret-2"))
// Notice that privA.computeSharedSecret(pubB)... sign1.computeSharedSecret(sign2.publicKey) //_result:
// ...is equal to privB.computeSharedSecret(pubA). sign2.computeSharedSecret(sign1.publicKey) //_result:
method recoverPublicKey
static recoverPublicKey: (digest: BytesLike, signature: SignatureLike) => string;
Returns the public key for the private key which produced the %%signature%% for the given %%digest%%.
@example: key = new SigningKey(id("some-secret")) digest = id("hello world") sig = key.sign(digest)
// Notice the signer public key... key.publicKey //_result:
// ...is equal to the recovered public key SigningKey.recoverPublicKey(digest, sig) //_result:
method sign
sign: (digest: BytesLike) => Signature;
Return the signature of the signed %%digest%%.
class SocketBlockSubscriber
class SocketBlockSubscriber extends SocketSubscriber {}
A **SocketBlockSubscriber** listens for ``newHeads`` events and emits ``"block"`` events.
constructor
constructor(provider: SocketProvider);
@_ignore:
class SocketEventSubscriber
class SocketEventSubscriber extends SocketSubscriber {}
A **SocketEventSubscriber** listens for event logs.
constructor
constructor(provider: SocketProvider, filter: EventFilter);
@_ignore:
property logFilter
readonly logFilter: EventFilter;
The filter.
class SocketPendingSubscriber
class SocketPendingSubscriber extends SocketSubscriber {}
A **SocketPendingSubscriber** listens for pending transacitons and emits ``"pending"`` events.
constructor
constructor(provider: SocketProvider);
@_ignore:
class SocketProvider
class SocketProvider extends JsonRpcApiProvider {}
A **SocketProvider** is backed by a long-lived connection over a socket, which can subscribe and receive real-time messages over its communication channel.
constructor
constructor(network?: Networkish, _options?: JsonRpcApiProviderOptions);
Creates a new **SocketProvider** connected to %%network%%.
If unspecified, the network will be discovered.
class SocketSubscriber
class SocketSubscriber implements Subscriber {}
A **SocketSubscriber** uses a socket transport to handle events and should use [[_emit]] to manage the events.
constructor
constructor(provider: SocketProvider, filter: any[]);
Creates a new **SocketSubscriber** attached to %%provider%% listening to %%filter%%.
property filter
readonly filter: any[];
The filter.
method pause
pause: (dropWhilePaused?: boolean) => void;
method resume
resume: () => void;
method start
start: () => void;
method stop
stop: () => void;
class StructFragment
class StructFragment extends NamedFragment {}
A Fragment which represents a structure.
constructor
constructor(guard: any, name: string, inputs: readonly ParamType[]);
method format
format: () => string;
Returns a string representation of this struct as %%format%%.
method from
static from: (obj: any) => StructFragment;
Returns a new **StructFragment** for %%obj%%.
method isFragment
static isFragment: (value: any) => value is FunctionFragment;
Returns ``true`` and provides a type guard if %%value%% is a **StructFragment**.
class Transaction
class Transaction implements TransactionLike<string> {}
A **Transaction** describes an operation to be executed on Ethereum by an Externally Owned Account (EOA). It includes who (the [[to]] address), what (the [[data]]) and how much (the [[value]] in ether) the operation should entail.
@example: tx = new Transaction() //_result:
tx.data = "0x1234"; //_result:
constructor
constructor();
Creates a new Transaction with default values.
property accessList
accessList: AccessList;
The access list.
An access list permits discounted (but pre-paid) access to bytecode and state variable access within contract execution.
property blobs
blobs: Blob[];
The BLObs for the Transaction, if any.
If ``blobs`` is non-``null``, then the [[seriailized]] will return the network formatted sidecar, otherwise it will return the standard [[link-eip-2718]] payload. The [[unsignedSerialized]] is unaffected regardless.
When setting ``blobs``, either fully valid [[Blob]] objects may be specified (i.e. correctly padded, with correct committments and proofs) or a raw [[BytesLike]] may be provided.
If raw [[BytesLike]] are provided, the [[kzg]] property **must** be already set. The blob will be correctly padded and the [[KzgLibrary]] will be used to compute the committment and proof for the blob.
A BLOb is a sequence of field elements, each of which must be within the BLS field modulo, so some additional processing may be required to encode arbitrary data to ensure each 32 byte field is within the valid range.
Setting this automatically populates [[blobVersionedHashes]], overwriting any existing values. Setting this to ``null`` does **not** remove the [[blobVersionedHashes]], leaving them present.
property blobVersionedHashes
blobVersionedHashes: string[];
The BLOb versioned hashes for Cancun transactions.
property chainId
chainId: BigInt;
The chain ID this transaction is valid on.
property data
data: string;
The transaction data. For ``init`` transactions this is the deployment code.
property from
readonly from: string;
The sending address, if signed. Otherwise, ``null``.
property fromPublicKey
readonly fromPublicKey: string;
The public key of the sender, if signed. Otherwise, ``null``.
property gasLimit
gasLimit: BigInt;
The gas limit.
property gasPrice
gasPrice: BigInt;
The gas price.
On legacy networks this defines the fee that will be paid. On EIP-1559 networks, this should be ``null``.
property hash
readonly hash: string;
The transaction hash, if signed. Otherwise, ``null``.
property kzg
kzg: KzgLibrary;
property maxFeePerBlobGas
maxFeePerBlobGas: BigInt;
The max fee per blob gas for Cancun transactions.
property maxFeePerGas
maxFeePerGas: BigInt;
The maximum total fee per unit of gas to pay. On legacy networks this should be ``null``.
property maxPriorityFeePerGas
maxPriorityFeePerGas: BigInt;
The maximum priority fee per unit of gas to pay. On legacy networks this should be ``null``.
property nonce
nonce: number;
The transaction nonce.
property serialized
readonly serialized: string;
The serialized transaction.
This throws if the transaction is unsigned. For the pre-image, use [[unsignedSerialized]].
property signature
signature: Signature;
If signed, the signature for this transaction.
property to
to: string;
The ``to`` address for the transaction or ``null`` if the transaction is an ``init`` transaction.
property type
type: number;
The transaction type.
If null, the type will be automatically inferred based on explicit properties.
property typeName
readonly typeName: string;
The name of the transaction type.
property unsignedHash
readonly unsignedHash: string;
The pre-image hash of this transaction.
This is the digest that a [[Signer]] must sign to authorize this transaction.
property unsignedSerialized
readonly unsignedSerialized: string;
The transaction pre-image.
The hash of this is the digest which needs to be signed to authorize this transaction.
property value
value: BigInt;
The amount of ether (in wei) to send in this transactions.
method clone
clone: () => Transaction;
Create a copy of this transaciton.
method from
static from: (tx?: string | TransactionLike<string>) => Transaction;
Create a **Transaction** from a serialized transaction or a Transaction-like object.
method inferType
inferType: () => number;
Return the most "likely" type; currently the highest supported transaction type.
method inferTypes
inferTypes: () => Array<number>;
Validates the explicit properties and returns a list of compatible transaction types.
method isBerlin
isBerlin: () => this is Transaction & { type: 1; gasPrice: bigint; accessList: AccessList;};
Returns true if this transaction is berlin hardform transaction (i.e. ``type === 1``).
This provides a Type Guard that the related properties are non-null.
method isCancun
isCancun: () => this is Transaction & { type: 3; to: string; accessList: AccessList; maxFeePerGas: bigint; maxPriorityFeePerGas: bigint; maxFeePerBlobGas: bigint; blobVersionedHashes: Array<string>;};
Returns true if this transaction is an [[link-eip-4844]] BLOB transaction.
This provides a Type Guard that the related properties are non-null.
method isLegacy
isLegacy: () => this is Transaction & { type: 0; gasPrice: bigint };
Returns true if this transaction is a legacy transaction (i.e. ``type === 0``).
This provides a Type Guard that the related properties are non-null.
method isLondon
isLondon: () => this is Transaction & { type: 2; accessList: AccessList; maxFeePerGas: bigint; maxPriorityFeePerGas: bigint;};
Returns true if this transaction is london hardform transaction (i.e. ``type === 2``).
This provides a Type Guard that the related properties are non-null.
method isSigned
isSigned: () => this is Transaction & { type: number; typeName: string; from: string; signature: Signature;};
Returns true if signed.
This provides a Type Guard that properties requiring a signed transaction are non-null.
method toJSON
toJSON: () => any;
Return a JSON-friendly object.
class TransactionDescription
class TransactionDescription {}
When using the [[Interface-parseTransaction]] to automatically match a transaction data to its function for parsing, a **TransactionDescription** is returned.
constructor
constructor( fragment: FunctionFragment, selector: string, args: Result, value: BigInt);
@_ignore:
property args
readonly args: Result;
The arguments passed to the Function from the transaction ``data``.
property fragment
readonly fragment: FunctionFragment;
The matching fragment from the transaction ``data``.
property name
readonly name: string;
The name of the Function from the transaction ``data``.
property selector
readonly selector: string;
The selector for the Function from the transaction ``data``.
property signature
readonly signature: string;
The full Function signature from the transaction ``data``.
property value
readonly value: BigInt;
The ``value`` (in wei) from the transaction.
class TransactionReceipt
class TransactionReceipt implements TransactionReceiptParams, Iterable<Log> {}
A **TransactionReceipt** includes additional information about a transaction that is only available after it has been mined.
constructor
constructor(tx: TransactionReceiptParams, provider: Provider);
@_ignore:
property blobGasPrice
readonly blobGasPrice: BigInt;
The price paid per BLOB in gas. See [[link-eip-4844]].
property blobGasUsed
readonly blobGasUsed: BigInt;
The gas used for BLObs. See [[link-eip-4844]].
property blockHash
readonly blockHash: string;
The block hash of the [[Block]] this transaction was included in.
property blockNumber
readonly blockNumber: number;
The block number of the [[Block]] this transaction was included in.
property contractAddress
readonly contractAddress: string;
The address of the contract if the transaction was directly responsible for deploying one.
This is non-null **only** if the ``to`` is empty and the ``data`` was successfully executed as initcode.
property cumulativeGasUsed
readonly cumulativeGasUsed: BigInt;
The amount of gas used by all transactions within the block for this and all transactions with a lower ``index``.
This is generally not useful for developers but can be used to validate certain aspects of execution.
property fee
readonly fee: BigInt;
The total fee for this transaction, in wei.
property from
readonly from: string;
The sender of the transaction.
property gasPrice
readonly gasPrice: BigInt;
The actual gas price used during execution.
Due to the complexity of [[link-eip-1559]] this value can only be caluclated after the transaction has been mined, snce the base fee is protocol-enforced.
property gasUsed
readonly gasUsed: BigInt;
The actual amount of gas used by this transaction.
When creating a transaction, the amount of gas that will be used can only be approximated, but the sender must pay the gas fee for the entire gas limit. After the transaction, the difference is refunded.
property hash
readonly hash: string;
The transaction hash.
property index
readonly index: number;
The index of this transaction within the block transactions.
property length
readonly length: number;
@_ignore:
property logs
readonly logs: readonly Log[];
The logs for this transaction.
property logsBloom
readonly logsBloom: string;
The bloom filter bytes that represent all logs that occurred within this transaction. This is generally not useful for most developers, but can be used to validate the included logs.
property provider
readonly provider: Provider;
The provider connected to the log used to fetch additional details if necessary.
property root
readonly root: string;
The root hash of this transaction.
This is no present and was only included in pre-byzantium blocks, but could be used to validate certain parts of the receipt.
property status
readonly status: number;
The status of this transaction, indicating success (i.e. ``1``) or a revert (i.e. ``0``).
This is available in post-byzantium blocks, but some backends may backfill this value.
property to
readonly to: string;
The address the transaction was sent to.
property type
readonly type: number;
The [[link-eip-2718]] transaction type.
method [Symbol.iterator]
[Symbol.iterator]: () => Iterator<Log>;
method confirmations
confirmations: () => Promise<number>;
Resolves to the number of confirmations this transaction has.
method getBlock
getBlock: () => Promise<Block>;
Resolves to the block this transaction occurred in.
method getResult
getResult: () => Promise<string>;
Resolves to the return value of the execution of this transaction.
Support for this feature is limited, as it requires an archive node with the ``debug_`` or ``trace_`` API enabled.
method getTransaction
getTransaction: () => Promise<TransactionResponse>;
Resolves to the transaction this transaction occurred in.
method removedEvent
removedEvent: () => OrphanFilter;
@_ignore:
method reorderedEvent
reorderedEvent: (other?: TransactionResponse) => OrphanFilter;
@_ignore:
method toJSON
toJSON: () => any;
Returns a JSON-compatible representation.
class TransactionResponse
class TransactionResponse implements TransactionLike<string>, TransactionResponseParams {}
A **TransactionResponse** includes all properties about a transaction that was sent to the network, which may or may not be included in a block.
The [[TransactionResponse-isMined]] can be used to check if the transaction has been mined as well as type guard that the otherwise possibly ``null`` properties are defined.
constructor
constructor(tx: TransactionResponseParams, provider: Provider);
@_ignore:
property accessList
readonly accessList: AccessList;
The [[link-eip-2930]] access list for transaction types that support it, otherwise ``null``.
property blobVersionedHashes
readonly blobVersionedHashes: string[];
The [[link-eip-4844]] BLOb versioned hashes.
property blockHash
readonly blockHash: string;
The blockHash of the block that this transaction was included in.
This is ``null`` for pending transactions.
property blockNumber
readonly blockNumber: number;
The block number of the block that this transaction was included in.
This is ``null`` for pending transactions.
property chainId
readonly chainId: BigInt;
The chain ID.
property data
readonly data: string;
The data.
property from
readonly from: string;
The sender of this transaction. It is implicitly computed from the transaction pre-image hash (as the digest) and the [[signature]] using ecrecover.
property gasLimit
readonly gasLimit: BigInt;
The maximum units of gas this transaction can consume. If execution exceeds this, the entries transaction is reverted and the sender is charged for the full amount, despite not state changes being made.
property gasPrice
readonly gasPrice: BigInt;
The gas price can have various values, depending on the network.
In modern networks, for transactions that are included this is the //effective gas price// (the fee per gas that was actually charged), while for transactions that have not been included yet is the [[maxFeePerGas]].
For legacy transactions, or transactions on legacy networks, this is the fee that will be charged per unit of gas the transaction consumes.
property hash
readonly hash: string;
The transaction hash.
property index
readonly index: number;
The index within the block that this transaction resides at.
property maxFeePerBlobGas
readonly maxFeePerBlobGas: BigInt;
The [[link-eip-4844]] max fee per BLOb gas.
property maxFeePerGas
readonly maxFeePerGas: BigInt;
The maximum fee (per unit of gas) to allow this transaction to charge the sender.
property maxPriorityFeePerGas
readonly maxPriorityFeePerGas: BigInt;
The maximum priority fee (per unit of gas) to allow a validator to charge the sender. This is inclusive of the [[maxFeeFeePerGas]].
property nonce
readonly nonce: number;
The nonce, which is used to prevent replay attacks and offer a method to ensure transactions from a given sender are explicitly ordered.
When sending a transaction, this must be equal to the number of transactions ever sent by [[from]].
property provider
readonly provider: Provider;
The provider this is connected to, which will influence how its methods will resolve its async inspection methods.
property signature
readonly signature: Signature;
The signature.
property to
readonly to: string;
The receiver of this transaction.
If ``null``, then the transaction is an initcode transaction. This means the result of executing the [[data]] will be deployed as a new contract on chain (assuming it does not revert) and the address may be computed using [[getCreateAddress]].
property type
readonly type: number;
The [[link-eip-2718]] transaction envelope type. This is ``0`` for legacy transactions types.
property value
readonly value: BigInt;
The value, in wei. Use [[formatEther]] to format this value as ether.
method confirmations
confirmations: () => Promise<number>;
Resolve to the number of confirmations this transaction has.
method getBlock
getBlock: () => Promise<null | Block>;
Resolves to the Block that this transaction was included in.
This will return null if the transaction has not been included yet.
method getTransaction
getTransaction: () => Promise<null | TransactionResponse>;
Resolves to this transaction being re-requested from the provider. This can be used if you have an unmined transaction and wish to get an up-to-date populated instance.
method isBerlin
isBerlin: () => this is never;
Returns true if the transaction is a Berlin (i.e. ``type == 1``) transaction. See [[link-eip-2070]].
This provides a Type Guard that this transaction will have the ``null``-ness for hardfork-specific properties set correctly.
method isCancun
isCancun: () => this is TransactionResponse & { accessList: AccessList; maxFeePerGas: bigint; maxPriorityFeePerGas: bigint; maxFeePerBlobGas: bigint; blobVersionedHashes: Array<string>;};
Returns true if hte transaction is a Cancun (i.e. ``type == 3``) transaction. See [[link-eip-4844]].
method isLegacy
isLegacy: () => this is never;
Returns true if the transaction is a legacy (i.e. ``type == 0``) transaction.
This provides a Type Guard that this transaction will have the ``null``-ness for hardfork-specific properties set correctly.
method isLondon
isLondon: () => this is TransactionResponse & { accessList: AccessList; maxFeePerGas: bigint; maxPriorityFeePerGas: bigint;};
Returns true if the transaction is a London (i.e. ``type == 2``) transaction. See [[link-eip-1559]].
This provides a Type Guard that this transaction will have the ``null``-ness for hardfork-specific properties set correctly.
method isMined
isMined: () => this is MinedTransactionResponse;
Returns ``true`` if this transaction has been included.
This is effective only as of the time the TransactionResponse was instantiated. To get up-to-date information, use [[getTransaction]].
This provides a Type Guard that this transaction will have non-null property values for properties that are null for unmined transactions.
method removedEvent
removedEvent: () => OrphanFilter;
Returns a filter which can be used to listen for orphan events that evict this transaction.
method reorderedEvent
reorderedEvent: (other?: TransactionResponse) => OrphanFilter;
Returns a filter which can be used to listen for orphan events that re-order this event against %%other%%.
method replaceableTransaction
replaceableTransaction: (startBlock: number) => TransactionResponse;
Returns a new TransactionResponse instance which has the ability to detect (and throw an error) if the transaction is replaced, which will begin scanning at %%startBlock%%.
This should generally not be used by developers and is intended primarily for internal use. Setting an incorrect %%startBlock%% can have devastating performance consequences if used incorrectly.
method toJSON
toJSON: () => any;
Returns a JSON-compatible representation of this transaction.
method wait
wait: ( _confirms?: number, _timeout?: number) => Promise<null | TransactionReceipt>;
Resolves once this transaction has been mined and has %%confirms%% blocks including it (default: ``1``) with an optional %%timeout%%.
This can resolve to ``null`` only if %%confirms%% is ``0`` and the transaction has not been mined, otherwise this will wait until enough confirmations have completed.
class Typed
class Typed {}
The **Typed** class to wrap values providing explicit type information.
constructor
constructor(gaurd: any, type: string, value: any, options?: any);
@_ignore:
property arrayLength
readonly arrayLength: number;
Returns the length of the array type or ``-1`` if it is dynamic.
Throws if the type is not an array.
property tupleName
readonly tupleName: string;
Returns the tuple name, if this is a tuple. Throws otherwise.
property type
readonly type: string;
The type, as a Solidity-compatible type.
property value
readonly value: any;
The actual value.
method address
static address: (v: string | Addressable) => Typed;
Return a new ``address`` type for %%v%%.
method array
static array: (v: Array<any | Typed>, dynamic?: null | boolean) => Typed;
Return a new ``array`` type for %%v%%, allowing %%dynamic%% length.
method bool
static bool: (v: any) => Typed;
Return a new ``bool`` type for %%v%%.
method bytes
static bytes: (v: BytesLike) => Typed;
Return a new ``bytes`` type for %%v%%.
method bytes1
static bytes1: (v: BytesLike) => Typed;
Return a new ``bytes1`` type for %%v%%.
method bytes10
static bytes10: (v: BytesLike) => Typed;
Return a new ``bytes10`` type for %%v%%.
method bytes11
static bytes11: (v: BytesLike) => Typed;
Return a new ``bytes11`` type for %%v%%.
method bytes12
static bytes12: (v: BytesLike) => Typed;
Return a new ``bytes12`` type for %%v%%.
method bytes13
static bytes13: (v: BytesLike) => Typed;
Return a new ``bytes13`` type for %%v%%.
method bytes14
static bytes14: (v: BytesLike) => Typed;
Return a new ``bytes14`` type for %%v%%.
method bytes15
static bytes15: (v: BytesLike) => Typed;
Return a new ``bytes15`` type for %%v%%.
method bytes16
static bytes16: (v: BytesLike) => Typed;
Return a new ``bytes16`` type for %%v%%.
method bytes17
static bytes17: (v: BytesLike) => Typed;
Return a new ``bytes17`` type for %%v%%.
method bytes18
static bytes18: (v: BytesLike) => Typed;
Return a new ``bytes18`` type for %%v%%.
method bytes19
static bytes19: (v: BytesLike) => Typed;
Return a new ``bytes19`` type for %%v%%.
method bytes2
static bytes2: (v: BytesLike) => Typed;
Return a new ``bytes2`` type for %%v%%.
method bytes20
static bytes20: (v: BytesLike) => Typed;
Return a new ``bytes20`` type for %%v%%.
method bytes21
static bytes21: (v: BytesLike) => Typed;
Return a new ``bytes21`` type for %%v%%.
method bytes22
static bytes22: (v: BytesLike) => Typed;
Return a new ``bytes22`` type for %%v%%.
method bytes23
static bytes23: (v: BytesLike) => Typed;
Return a new ``bytes23`` type for %%v%%.
method bytes24
static bytes24: (v: BytesLike) => Typed;
Return a new ``bytes24`` type for %%v%%.
method bytes25
static bytes25: (v: BytesLike) => Typed;
Return a new ``bytes25`` type for %%v%%.
method bytes26
static bytes26: (v: BytesLike) => Typed;
Return a new ``bytes26`` type for %%v%%.
method bytes27
static bytes27: (v: BytesLike) => Typed;
Return a new ``bytes27`` type for %%v%%.
method bytes28
static bytes28: (v: BytesLike) => Typed;
Return a new ``bytes28`` type for %%v%%.
method bytes29
static bytes29: (v: BytesLike) => Typed;
Return a new ``bytes29`` type for %%v%%.
method bytes3
static bytes3: (v: BytesLike) => Typed;
Return a new ``bytes3`` type for %%v%%.
method bytes30
static bytes30: (v: BytesLike) => Typed;
Return a new ``bytes30`` type for %%v%%.
method bytes31
static bytes31: (v: BytesLike) => Typed;
Return a new ``bytes31`` type for %%v%%.
method bytes32
static bytes32: (v: BytesLike) => Typed;
Return a new ``bytes32`` type for %%v%%.
method bytes4
static bytes4: (v: BytesLike) => Typed;
Return a new ``bytes4`` type for %%v%%.
method bytes5
static bytes5: (v: BytesLike) => Typed;
Return a new ``bytes5`` type for %%v%%.
method bytes6
static bytes6: (v: BytesLike) => Typed;
Return a new ``bytes6`` type for %%v%%.
method bytes7
static bytes7: (v: BytesLike) => Typed;
Return a new ``bytes7`` type for %%v%%.
method bytes8
static bytes8: (v: BytesLike) => Typed;
Return a new ``bytes8`` type for %%v%%.
method bytes9
static bytes9: (v: BytesLike) => Typed;
Return a new ``bytes9`` type for %%v%%.
method defaultValue
defaultValue: () => string | number | bigint | Result;
The default value returned by this type.
method dereference
static dereference: <T>(value: Typed | T, type: string) => T;
If the value is a [[Typed]] instance, validates the underlying value and returns it, otherwise returns value directly.
This is useful for functions that with to accept either a [[Typed]] object or values.
method format
format: () => string;
Format the type as a Human-Readable type.
method from
static from: (type: string, value: any) => Typed;
Returns a new **Typed** of %%type%% with the %%value%%.
method int
static int: (v: BigNumberish) => Typed;
Return a new ``int256`` type for %%v%%.
method int104
static int104: (v: BigNumberish) => Typed;
Return a new ``int104`` type for %%v%%.
method int112
static int112: (v: BigNumberish) => Typed;
Return a new ``int112`` type for %%v%%.
method int120
static int120: (v: BigNumberish) => Typed;
Return a new ``int120`` type for %%v%%.
method int128
static int128: (v: BigNumberish) => Typed;
Return a new ``int128`` type for %%v%%.
method int136
static int136: (v: BigNumberish) => Typed;
Return a new ``int136`` type for %%v%%.
method int144
static int144: (v: BigNumberish) => Typed;
Return a new ``int144`` type for %%v%%.
method int152
static int152: (v: BigNumberish) => Typed;
Return a new ``int52`` type for %%v%%.
method int16
static int16: (v: BigNumberish) => Typed;
Return a new ``int16`` type for %%v%%.
method int160
static int160: (v: BigNumberish) => Typed;
Return a new ``int160`` type for %%v%%.
method int168
static int168: (v: BigNumberish) => Typed;
Return a new ``int168`` type for %%v%%.
method int176
static int176: (v: BigNumberish) => Typed;
Return a new ``int176`` type for %%v%%.
method int184
static int184: (v: BigNumberish) => Typed;
Return a new ``int184`` type for %%v%%.
method int192
static int192: (v: BigNumberish) => Typed;
Return a new ``int92`` type for %%v%%.
method int200
static int200: (v: BigNumberish) => Typed;
Return a new ``int200`` type for %%v%%.
method int208
static int208: (v: BigNumberish) => Typed;
Return a new ``int208`` type for %%v%%.
method int216
static int216: (v: BigNumberish) => Typed;
Return a new ``int216`` type for %%v%%.
method int224
static int224: (v: BigNumberish) => Typed;
Return a new ``int224`` type for %%v%%.
method int232
static int232: (v: BigNumberish) => Typed;
Return a new ``int232`` type for %%v%%.
method int24
static int24: (v: BigNumberish) => Typed;
Return a new ``int24`` type for %%v%%.
method int240
static int240: (v: BigNumberish) => Typed;
Return a new ``int240`` type for %%v%%.
method int248
static int248: (v: BigNumberish) => Typed;
Return a new ``int248`` type for %%v%%.
method int256
static int256: (v: BigNumberish) => Typed;
Return a new ``int256`` type for %%v%%.
method int32
static int32: (v: BigNumberish) => Typed;
Return a new ``int32`` type for %%v%%.
method int40
static int40: (v: BigNumberish) => Typed;
Return a new ``int40`` type for %%v%%.
method int48
static int48: (v: BigNumberish) => Typed;
Return a new ``int48`` type for %%v%%.
method int56
static int56: (v: BigNumberish) => Typed;
Return a new ``int56`` type for %%v%%.
method int64
static int64: (v: BigNumberish) => Typed;
Return a new ``int64`` type for %%v%%.
method int72
static int72: (v: BigNumberish) => Typed;
Return a new ``int72`` type for %%v%%.
method int8
static int8: (v: BigNumberish) => Typed;
Return a new ``int8`` type for %%v%%.
method int80
static int80: (v: BigNumberish) => Typed;
Return a new ``int80`` type for %%v%%.
method int88
static int88: (v: BigNumberish) => Typed;
Return a new ``int88`` type for %%v%%.
method int96
static int96: (v: BigNumberish) => Typed;
Return a new ``int96`` type for %%v%%.
method isBigInt
isBigInt: () => this is TypedBigInt;
Returns ``true`` and provides a type guard is this is a [[TypedBigInt]].
method isData
isData: () => this is TypedData;
Returns ``true`` and provides a type guard is this is a [[TypedData]].
method isString
isString: () => this is TypedString;
Returns ``true`` and provides a type guard is this is a [[TypedString]].
method isTyped
static isTyped: (value: any) => value is Typed;
Returns true only if %%value%% is a [[Typed]] instance.
method maxValue
maxValue: () => string | number | bigint;
The maximum value for numeric types.
method minValue
minValue: () => string | number | bigint;
The minimum value for numeric types.
method overrides
static overrides: (v: Record<string, any>) => Typed;
Return a new ``uint8`` type for %%v%%.
method string
static string: (v: string) => Typed;
Return a new ``string`` type for %%v%%.
method tuple
static tuple: ( v: Array<any | Typed> | Record<string, any | Typed>, name?: string) => Typed;
Return a new ``tuple`` type for %%v%%, with the optional %%name%%.
method uint
static uint: (v: BigNumberish) => Typed;
Return a new ``uint256`` type for %%v%%.
method uint104
static uint104: (v: BigNumberish) => Typed;
Return a new ``uint104`` type for %%v%%.
method uint112
static uint112: (v: BigNumberish) => Typed;
Return a new ``uint112`` type for %%v%%.
method uint120
static uint120: (v: BigNumberish) => Typed;
Return a new ``uint120`` type for %%v%%.
method uint128
static uint128: (v: BigNumberish) => Typed;
Return a new ``uint128`` type for %%v%%.
method uint136
static uint136: (v: BigNumberish) => Typed;
Return a new ``uint136`` type for %%v%%.
method uint144
static uint144: (v: BigNumberish) => Typed;
Return a new ``uint144`` type for %%v%%.
method uint152
static uint152: (v: BigNumberish) => Typed;
Return a new ``uint152`` type for %%v%%.
method uint16
static uint16: (v: BigNumberish) => Typed;
Return a new ``uint16`` type for %%v%%.
method uint160
static uint160: (v: BigNumberish) => Typed;
Return a new ``uint160`` type for %%v%%.
method uint168
static uint168: (v: BigNumberish) => Typed;
Return a new ``uint168`` type for %%v%%.
method uint176
static uint176: (v: BigNumberish) => Typed;
Return a new ``uint176`` type for %%v%%.
method uint184
static uint184: (v: BigNumberish) => Typed;
Return a new ``uint184`` type for %%v%%.
method uint192
static uint192: (v: BigNumberish) => Typed;
Return a new ``uint192`` type for %%v%%.
method uint200
static uint200: (v: BigNumberish) => Typed;
Return a new ``uint200`` type for %%v%%.
method uint208
static uint208: (v: BigNumberish) => Typed;
Return a new ``uint208`` type for %%v%%.
method uint216
static uint216: (v: BigNumberish) => Typed;
Return a new ``uint216`` type for %%v%%.
method uint224
static uint224: (v: BigNumberish) => Typed;
Return a new ``uint224`` type for %%v%%.
method uint232
static uint232: (v: BigNumberish) => Typed;
Return a new ``uint232`` type for %%v%%.
method uint24
static uint24: (v: BigNumberish) => Typed;
Return a new ``uint24`` type for %%v%%.
method uint240
static uint240: (v: BigNumberish) => Typed;
Return a new ``uint240`` type for %%v%%.
method uint248
static uint248: (v: BigNumberish) => Typed;
Return a new ``uint248`` type for %%v%%.
method uint256
static uint256: (v: BigNumberish) => Typed;
Return a new ``uint256`` type for %%v%%.
method uint32
static uint32: (v: BigNumberish) => Typed;
Return a new ``uint32`` type for %%v%%.
method uint40
static uint40: (v: BigNumberish) => Typed;
Return a new ``uint40`` type for %%v%%.
method uint48
static uint48: (v: BigNumberish) => Typed;
Return a new ``uint48`` type for %%v%%.
method uint56
static uint56: (v: BigNumberish) => Typed;
Return a new ``uint56`` type for %%v%%.
method uint64
static uint64: (v: BigNumberish) => Typed;
Return a new ``uint64`` type for %%v%%.
method uint72
static uint72: (v: BigNumberish) => Typed;
Return a new ``uint72`` type for %%v%%.
method uint8
static uint8: (v: BigNumberish) => Typed;
Return a new ``uint8`` type for %%v%%.
method uint80
static uint80: (v: BigNumberish) => Typed;
Return a new ``uint80`` type for %%v%%.
method uint88
static uint88: (v: BigNumberish) => Typed;
Return a new ``uint88`` type for %%v%%.
method uint96
static uint96: (v: BigNumberish) => Typed;
Return a new ``uint96`` type for %%v%%.
class TypedDataEncoder
class TypedDataEncoder {}
A **TypedDataEncode** prepares and encodes [[link-eip-712]] payloads for signed typed data.
This is useful for those that wish to compute various components of a typed data hash, primary types, or sub-components, but generally the higher level [[Signer-signTypedData]] is more useful.
constructor
constructor(_types: Record<string, TypedDataField[]>);
Create a new **TypedDataEncoder** for %%types%%.
This performs all necessary checking that types are valid and do not violate the [[link-eip-712]] structural constraints as well as computes the [[primaryType]].
property primaryType
readonly primaryType: string;
The primary type for the structured [[types]].
This is derived automatically from the [[types]], since no recursion is possible, once the DAG for the types is consturcted internally, the primary type must be the only remaining type with no parent nodes.
property types
readonly types: Record<string, TypedDataField[]>;
The types.
method encode
static encode: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => string;
Return the fulled encoded %%value%% for the [[types]].
Return the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%.
method encodeData
encodeData: (type: string, value: any) => string;
Return the encoded %%value%% for the %%type%%.
method encodeType
encodeType: (name: string) => string;
Return the full type for %%name%%.
method from
static from: (types: Record<string, Array<TypedDataField>>) => TypedDataEncoder;
Create a new **TypedDataEncoder** for %%types%%.
method getEncoder
getEncoder: (type: string) => (value: any) => string;
Returnthe encoder for the specific %%type%%.
method getPayload
static getPayload: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => any;
Returns the JSON-encoded payload expected by nodes which implement the JSON-RPC [[link-eip-712]] method.
method getPrimaryType
static getPrimaryType: (types: Record<string, Array<TypedDataField>>) => string;
Return the primary type for %%types%%.
method hash
static hash: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => string;
Return the hash of the fully encoded %%value%% for the [[types]].
Return the hash of the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%.
method hashDomain
static hashDomain: (domain: TypedDataDomain) => string;
Return the domain hash for %%domain%%.
method hashStruct
static hashStruct: ( name: string, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => string;
Returns the hash of %%value%% for the type of %%name%%.
Return the hashed struct for %%value%% using %%types%% and %%name%%.
method resolveNames
static resolveNames: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>, resolveName: (name: string) => Promise<string>) => Promise<{ domain: TypedDataDomain; value: any }>;
Resolves to the value from resolving all addresses in %%value%% for %%types%% and the %%domain%%.
method visit
visit: ( value: Record<string, any>, callback: (type: string, data: any) => any) => any;
Call %%calback%% for each value in %%value%%, passing the type and component within %%value%%.
This is useful for replacing addresses or other transformation that may be desired on each component, based on its type.
class UndecodedEventLog
class UndecodedEventLog extends Log {}
An **EventLog** contains additional properties parsed from the [[Log]].
constructor
constructor(log: Log, error: Error);
@_ignore:
property error
readonly error: Error;
The error encounted when trying to decode the log.
class UnmanagedSubscriber
class UnmanagedSubscriber implements Subscriber {}
An **UnmanagedSubscriber** is useful for events which do not require any additional management, such as ``"debug"`` which only requires emit in synchronous event loop triggered calls.
class VoidSigner
class VoidSigner extends AbstractSigner {}
A **VoidSigner** is a class deisgned to allow an address to be used in any API which accepts a Signer, but for which there are no credentials available to perform any actual signing.
This for example allow impersonating an account for the purpose of static calls or estimating gas, but does not allow sending transactions.
constructor
constructor(address: string, provider?: Provider);
Creates a new **VoidSigner** with %%address%% attached to %%provider%%.
property address
readonly address: string;
The signer address.
method connect
connect: (provider: null | Provider) => VoidSigner;
method getAddress
getAddress: () => Promise<string>;
method signMessage
signMessage: (message: string | Uint8Array) => Promise<string>;
method signTransaction
signTransaction: (tx: TransactionRequest) => Promise<string>;
method signTypedData
signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => Promise<string>;
class Wallet
class Wallet extends BaseWallet {}
A **Wallet** manages a single private key which is used to sign transactions, messages and other common payloads.
This class is generally the main entry point for developers that wish to use a private key directly, as it can create instances from a large variety of common sources, including raw private key, [[link-bip-39]] mnemonics and encrypte JSON wallets.
constructor
constructor(key: string | SigningKey, provider?: Provider);
Create a new wallet for the private %%key%%, optionally connected to %%provider%%.
method connect
connect: (provider: null | Provider) => Wallet;
method createRandom
static createRandom: (provider?: null | Provider) => HDNodeWallet;
Creates a new random [[HDNodeWallet]] using the available [cryptographic random source](randomBytes).
If there is no crytographic random source, this will throw.
method encrypt
encrypt: ( password: Uint8Array | string, progressCallback?: ProgressCallback) => Promise<string>;
Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with %%password%%.
If %%progressCallback%% is specified, it will receive periodic updates as the encryption process progreses.
method encryptSync
encryptSync: (password: Uint8Array | string) => string;
Returns a [JSON Keystore Wallet](json-wallets) encryped with %%password%%.
It is preferred to use the [async version](encrypt) instead, which allows a [[ProgressCallback]] to keep the user informed.
This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial duration.
method fromEncryptedJson
static fromEncryptedJson: ( json: string, password: Uint8Array | string, progress?: ProgressCallback) => Promise<HDNodeWallet | Wallet>;
Creates (asynchronously) a **Wallet** by decrypting the %%json%% with %%password%%.
If %%progress%% is provided, it is called periodically during decryption so that any UI can be updated.
method fromEncryptedJsonSync
static fromEncryptedJsonSync: ( json: string, password: Uint8Array | string) => HDNodeWallet | Wallet;
Creates a **Wallet** by decrypting the %%json%% with %%password%%.
The [[fromEncryptedJson]] method is preferred, as this method will lock up and freeze the UI during decryption, which may take some time.
method fromPhrase
static fromPhrase: (phrase: string, provider?: Provider) => HDNodeWallet;
Creates a [[HDNodeWallet]] for %%phrase%%.
class WebSocketProvider
class WebSocketProvider extends SocketProvider {}
A JSON-RPC provider which is backed by a WebSocket.
WebSockets are often preferred because they retain a live connection to a server, which permits more instant access to events.
However, this incurs higher server infrasturture costs, so additional resources may be required to host your own WebSocket nodes and many third-party services charge additional fees for WebSocket endpoints.
constructor
constructor( url: string | WebSocketLike | WebSocketCreator, network?: Networkish, options?: JsonRpcApiProviderOptions);
property websocket
readonly websocket: WebSocketLike;
method destroy
destroy: () => Promise<void>;
class Wordlist
abstract class Wordlist {}
A Wordlist represents a collection of language-specific words used to encode and devoce [[link-bip-39]] encoded data by mapping words to 11-bit values and vice versa.
constructor
constructor(locale: string);
Creates a new Wordlist instance.
Sub-classes MUST call this if they provide their own constructor, passing in the locale string of the language.
Generally there is no need to create instances of a Wordlist, since each language-specific Wordlist creates an instance and there is no state kept internally, so they are safe to share.
property locale
locale: string;
method getWord
abstract getWord: (index: number) => string;
Maps an 11-bit value into its coresponding word in the list.
Sub-classes MUST override this.
method getWordIndex
abstract getWordIndex: (word: string) => number;
Maps a word to its corresponding 11-bit value.
Sub-classes MUST override this.
method join
join: (words: Array<string>) => string;
Sub-classes may override this to provider a language-specific method for joining %%words%% into a phrase.
By default, %%words%% are joined by a single space.
method split
split: (phrase: string) => Array<string>;
Sub-classes may override this to provide a language-specific method for spliting %%phrase%% into individual words.
By default, %%phrase%% is split using any sequences of white-space as defined by regular expressions (i.e. ``/\s+/``).
class WordlistOwl
class WordlistOwl extends Wordlist {}
An OWL format Wordlist is an encoding method that exploits the general locality of alphabetically sorted words to achieve a simple but effective means of compression.
This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages based on ASCII-7 small.
If necessary, there are tools within the ``generation/`` folder to create the necessary data.
constructor
constructor(locale: string, data: string, checksum: string);
Creates a new Wordlist for %%locale%% using the OWL %%data%% and validated against the %%checksum%%.
method getWord
getWord: (index: number) => string;
method getWordIndex
getWordIndex: (word: string) => number;
class WordlistOwlA
class WordlistOwlA extends WordlistOwl {}
An OWL-A format Wordlist extends the OWL format to add an overlay onto an OWL format Wordlist to support diacritic marks.
This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages based on latin-1 small.
If necessary, there are tools within the ``generation/`` folder to create the necessary data.
constructor
constructor(locale: string, data: string, accent: string, checksum: string);
Creates a new Wordlist for %%locale%% using the OWLA %%data%% and %%accent%% data and validated against the %%checksum%%.
Interfaces
interface AbstractProviderPlugin
interface AbstractProviderPlugin {}
An **AbstractPlugin** is used to provide additional internal services to an [[AbstractProvider]] without adding backwards-incompatible changes to method signatures or other internal and complex logic.
interface ActionRejectedError
interface ActionRejectedError extends EthersError<'ACTION_REJECTED'> {}
This Error indicates a request was rejected by the user.
In most clients (such as MetaMask), when an operation requires user authorization (such as ``signer.sendTransaction``), the client presents a dialog box to the user. If the user denies the request this error is thrown.
property action
action: | 'requestAccess' | 'sendTransaction' | 'signMessage' | 'signTransaction' | 'signTypedData' | 'unknown';
The requested action.
property reason
reason: 'expired' | 'rejected' | 'pending';
The reason the action was rejected.
If there is already a pending request, some clients may indicate there is already a ``"pending"`` action. This prevents an app from spamming the user.
interface Addressable
interface Addressable {}
An interface for objects which have an address, and can resolve it asyncronously.
This allows objects such as [[Signer]] or [[Contract]] to be used most places an address can be, for example getting the [balance](Provider-getBalance).
method getAddress
getAddress: () => Promise<string>;
Get the object address.
interface BadDataError
interface BadDataError extends EthersError<'BAD_DATA'> {}
This Error indicates that a provided set of data cannot be correctly interpreted.
property value
value: any;
The data.
interface BaseContractMethod
interface BaseContractMethod< A extends Array<any> = Array<any>, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> {}
A Contract method can be called directly, or used in various ways.
property fragment
fragment: FunctionFragment;
The fragment of the Contract method. This will throw on ambiguous method names.
property name
name: string;
The name of the Contract method.
method estimateGas
estimateGas: (...args: ContractMethodArgs<A>) => Promise<bigint>;
Estimate the gas to send the contract method with %%args%%.
method getFragment
getFragment: (...args: ContractMethodArgs<A>) => FunctionFragment;
Returns the fragment constrained by %%args%%. This can be used to resolve ambiguous method names.
method populateTransaction
populateTransaction: ( ...args: ContractMethodArgs<A>) => Promise<ContractTransaction>;
Returns a populated transaction that can be used to perform the contract method with %%args%%.
method send
send: (...args: ContractMethodArgs<A>) => Promise<ContractTransactionResponse>;
Send a transaction for the contract method with %%args%%.
method staticCall
staticCall: (...args: ContractMethodArgs<A>) => Promise<R>;
Call the contract method with %%args%% and return the value.
If the return value is a single type, it will be dereferenced and returned directly, otherwise the full Result will be returned.
method staticCallResult
staticCallResult: (...args: ContractMethodArgs<A>) => Promise<Result>;
Call the contract method with %%args%% and return the Result without any dereferencing.
call signature
(...args: ContractMethodArgs<A>): Promise<D>;
interface Blob
interface Blob {}
A full-valid BLOb object for [[link-eip-4844]] transactions.
The commitment and proof should have been computed using a KZG library.
interface BlockParams
interface BlockParams {}
a **BlockParams** encodes the minimal required properties for a formatted block.
property baseFeePerGas
baseFeePerGas: null | bigint;
The protocol-defined base fee per gas in an [[link-eip-1559]] block.
property blobGasUsed
blobGasUsed?: null | bigint;
The total amount of BLOb gas consumed by transactions within the block. See [[link-eip4844].
property difficulty
difficulty: bigint;
For proof-of-work networks, the difficulty target is used to adjust the difficulty in mining to ensure a expected block rate.
property excessBlobGas
excessBlobGas?: null | bigint;
The running total of BLOb gas consumed in excess of the target prior to the block. See [[link-eip-4844]].
property extraData
extraData: string;
Additional data the miner choose to include.
property gasLimit
gasLimit: bigint;
The maximum amount of gas a block can consume.
property gasUsed
gasUsed: bigint;
The amount of gas a block consumed.
property hash
hash?: null | string;
The block hash.
property miner
miner: string;
The miner (or author) of a block.
property nonce
nonce: string;
A random sequence provided during the mining process for proof-of-work networks.
property number
number: number;
The block number.
property parentBeaconBlockRoot
parentBeaconBlockRoot?: null | string;
The hash tree root of the parent beacon block for the given execution block. See [[link-eip-4788]].
property parentHash
parentHash: string;
The hash of the previous block in the blockchain. The genesis block has the parentHash of the [[ZeroHash]].
property prevRandao
prevRandao?: null | string;
The latest RANDAO mix of the post beacon state of the previous block.
property receiptsRoot
receiptsRoot?: null | string;
The hash of the transaction receipts trie.
property stateRoot
stateRoot?: null | string;
The root hash for the global state after applying changes in this block.
property timestamp
timestamp: number;
The timestamp for this block, which is the number of seconds since epoch that this block was included.
property transactions
transactions: ReadonlyArray<string | TransactionResponseParams>;
The list of transactions in the block.
interface BufferOverrunError
interface BufferOverrunError extends EthersError<'BUFFER_OVERRUN'> {}
This Error indicates an attempt was made to read outside the bounds of protected data.
Most operations in Ethers are protected by bounds checks, to mitigate exploits when parsing data.
interface CallExceptionError
interface CallExceptionError extends EthersError<'CALL_EXCEPTION'> {}
This **Error** indicates a transaction reverted.
property action
action: CallExceptionAction;
The action being performed when the revert was encountered.
property data
data: null | string;
The revert data returned.
property invocation
invocation: null | { method: string; signature: string; args: Array<any>;};
The contract invocation details, if available.
property reason
reason: null | string;
A human-readable representation of data, if possible.
property receipt
receipt?: TransactionReceipt;
If the error occurred in a transaction that was mined (with a status of ``0``), this is the receipt.
property revert
revert: null | { signature: string; name: string; args: Array<any>;};
The built-in or custom revert error, if available
property transaction
transaction: CallExceptionTransaction;
The transaction that triggered the exception.
interface CancelledError
interface CancelledError extends EthersError<'CANCELLED'> {}
This Error indicates that the operation was cancelled by a programmatic call, for example to ``cancel()``.
interface ConstantContractMethod
interface ConstantContractMethod<A extends Array<any>, R = any> extends ContractMethod<A, R, R> {}
A pure of view method on a Contract.
interface ContractDeployTransaction
interface ContractDeployTransaction extends Omit<ContractTransaction, 'to'> {}
A deployment transaction for a contract.
interface ContractEvent
interface ContractEvent<A extends Array<any> = Array<any>> {}
property fragment
fragment: EventFragment;
The fragment of the Contract event. This will throw on ambiguous method names.
property name
name: string;
The name of the Contract event.
method getFragment
getFragment: (...args: ContractEventArgs<A>) => EventFragment;
Returns the fragment constrained by %%args%%. This can be used to resolve ambiguous event names.
call signature
(...args: ContractEventArgs<A>): DeferredTopicFilter;
interface ContractInterface
interface ContractInterface {}
A Contract with no method constraints.
index signature
[name: string]: BaseContractMethod;
interface ContractMethod
interface ContractMethod< A extends Array<any> = Array<any>, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> extends BaseContractMethod<A, R, D> {}
A contract method on a Contract.
interface ContractRunner
interface ContractRunner {}
A **ContractRunner** is a generic interface which defines an object capable of interacting with a Contract on the network.
The more operations supported, the more utility it is capable of.
The most common ContractRunners are [Providers](Provider) which enable read-only access and [Signers](Signer) which enable write-access.
property call
call?: (tx: TransactionRequest) => Promise<string>;
Required for pure, view or static calls to contracts.
property estimateGas
estimateGas?: (tx: TransactionRequest) => Promise<bigint>;
Required to estimate gas.
property provider
provider: null | Provider;
The provider used for necessary state querying operations.
This can also point to the **ContractRunner** itself, in the case of an [[AbstractProvider]].
property resolveName
resolveName?: (name: string) => Promise<null | string>;
Required to support ENS names
property sendTransaction
sendTransaction?: (tx: TransactionRequest) => Promise<TransactionResponse>;
Required for state mutating calls
interface ContractTransaction
interface ContractTransaction extends PreparedTransactionRequest {}
When populating a transaction this type is returned.
interface DeferredTopicFilter
interface DeferredTopicFilter {}
When creating a filter using the ``contract.filters``, this is returned.
property fragment
fragment: EventFragment;
method getTopicFilter
getTopicFilter: () => Promise<TopicFilter>;
interface Eip1193Provider
interface Eip1193Provider {}
The interface to an [[link-eip-1193]] provider, which is a standard used by most injected providers, which the [[BrowserProvider]] accepts and exposes the API of.
method request
request: (request: { method: string; params?: Array<any> | Record<string, any>;}) => Promise<any>;
See [[link-eip-1193]] for details on this method.
interface EthersError
interface EthersError<T extends ErrorCode = ErrorCode> extends Error {}
All errors in Ethers include properties to assist in machine-readable errors.
property code
code: ErrorCode;
The string error code.
property error
error?: Error;
Any related error.
property info
info?: Record<string, any>;
Additional info regarding the error that may be useful.
This is generally helpful mostly for human-based debugging.
property shortMessage
shortMessage: string;
A short message describing the error, with minimal additional details.
interface EventEmitterable
interface EventEmitterable<T> {}
An **EventEmitterable** behaves similar to an EventEmitter except provides async access to its methods.
An EventEmitter implements the observer pattern.
method addListener
addListener: (event: T, listener: Listener) => Promise<this>;
Alias for [[on]].
method emit
emit: (event: T, ...args: Array<any>) => Promise<boolean>;
Triggers each listener for %%event%% with the %%args%%.
method listenerCount
listenerCount: (event?: T) => Promise<number>;
Resolves to the number of listeners for %%event%%.
method listeners
listeners: (event?: T) => Promise<Array<Listener>>;
Resolves to the listeners for %%event%%.
method off
off: (event: T, listener?: Listener) => Promise<this>;
Unregister the %%listener%% for %%event%%. If %%listener%% is unspecified, all listeners are unregistered.
method on
on: (event: T, listener: Listener) => Promise<this>;
Registers a %%listener%% that is called whenever the %%event%% occurs until unregistered.
method once
once: (event: T, listener: Listener) => Promise<this>;
Registers a %%listener%% that is called the next time %%event%% occurs.
method removeAllListeners
removeAllListeners: (event?: T) => Promise<this>;
Unregister all listeners for %%event%%.
method removeListener
removeListener: (event: T, listener: Listener) => Promise<this>;
Alias for [[off]].
interface EventFilter
interface EventFilter {}
An **EventFilter** allows efficiently filtering logs (also known as events) using bloom filters included within blocks.
interface Filter
interface Filter extends EventFilter {}
A **Filter** allows searching a specific range of blocks for mathcing logs.
interface FilterByBlockHash
interface FilterByBlockHash extends EventFilter {}
A **FilterByBlockHash** allows searching a specific block for mathcing logs.
property blockHash
blockHash?: string;
The blockhash of the specific block for the filter.
interface InsufficientFundsError
interface InsufficientFundsError extends EthersError<'INSUFFICIENT_FUNDS'> {}
The sending account has insufficient funds to cover the entire transaction cost.
property transaction
transaction: TransactionRequest;
The transaction.
interface InvalidArgumentError
interface InvalidArgumentError extends EthersError<'INVALID_ARGUMENT'> {}
This Error indicates an incorrect type or value was passed to a function or method.
interface JsonFragment
interface JsonFragment {}
A fragment for a method, event or error in a [JSON ABI format](link-solc-jsonabi).
property anonymous
readonly anonymous?: boolean;
If the event is anonymous.
property constant
readonly constant?: boolean;
If the function is constant.
property gas
readonly gas?: string;
The gas limit to use when sending a transaction for this function.
property inputs
readonly inputs?: ReadonlyArray<JsonFragmentType>;
The input parameters.
property name
readonly name?: string;
The name of the error, event, function, etc.
property outputs
readonly outputs?: ReadonlyArray<JsonFragmentType>;
The output parameters.
property payable
readonly payable?: boolean;
If the function is payable.
property stateMutability
readonly stateMutability?: string;
The mutability state of the function.
property type
readonly type?: string;
The type of the fragment (e.g. ``event``, ``"function"``, etc.)
interface JsonFragmentType
interface JsonFragmentType {}
A Type description in a [JSON ABI format](link-solc-jsonabi).
property components
readonly components?: ReadonlyArray<JsonFragmentType>;
The components for a tuple.
property indexed
readonly indexed?: boolean;
If the parameter is indexed.
property internalType
readonly internalType?: string;
The internal Solidity type.
property name
readonly name?: string;
The parameter name.
property type
readonly type?: string;
The type of the parameter.
interface JsonRpcTransactionRequest
interface JsonRpcTransactionRequest {}
A **JsonRpcTransactionRequest** is formatted as needed by the JSON-RPC Ethereum API specification.
property accessList
accessList?: Array<{ address: string; storageKeys: Array<string>;}>;
The transaction access list.
property chainId
chainId?: string;
The chain ID the transaction is valid on.
property data
data?: string;
The transaction data.
property from
from?: string;
The sender address to use when signing.
property gas
gas?: string;
The maximum amount of gas to allow a transaction to consume.
In most other places in ethers, this is called ``gasLimit`` which differs from the JSON-RPC Ethereum API specification.
property gasPrice
gasPrice?: string;
The gas price per wei for transactions prior to [[link-eip-1559]].
property maxFeePerGas
maxFeePerGas?: string;
The maximum fee per gas for [[link-eip-1559]] transactions.
property maxPriorityFeePerGas
maxPriorityFeePerGas?: string;
The maximum priority fee per gas for [[link-eip-1559]] transactions.
property nonce
nonce?: string;
The nonce for the transaction.
property to
to?: string;
The target address.
property type
type?: string;
The [[link-eip-2718]] transaction type.
property value
value?: string;
The transaction value (in wei).
interface KzgLibrary
interface KzgLibrary {}
A KZG Library with the necessary functions to compute BLOb commitments and proofs.
property blobToKzgCommitment
blobToKzgCommitment: (blob: Uint8Array) => Uint8Array;
property computeBlobKzgProof
computeBlobKzgProof: (blob: Uint8Array, commitment: Uint8Array) => Uint8Array;
interface LogParams
interface LogParams {}
a **LogParams** encodes the minimal required properties for a formatted log.
property address
address: string;
The address of the contract that emitted this log.
property blockHash
blockHash: string;
The block hash of the block that included the transaction for this log.
property blockNumber
blockNumber: number;
The block number of the block that included the transaction for this log.
property data
data: string;
The data emitted with this log.
property index
index: number;
The index of this log.
property removed
removed: boolean;
Whether this log was removed due to the transaction it was included in being removed dur to an orphaned block.
property topics
topics: ReadonlyArray<string>;
The topics emitted with this log.
property transactionHash
transactionHash: string;
The transaction hash for the transaxction the log occurred in.
property transactionIndex
transactionIndex: number;
The transaction index of this log.
interface MinedBlock
interface MinedBlock extends Block {}
An Interface to indicate a [[Block]] has been included in the blockchain. This asserts a Type Guard that necessary properties are non-null.
Before a block is included, it is a //pending// block.
property date
readonly date: Date;
The block date, created from the [[timestamp]].
property hash
readonly hash: string;
The block hash.
property miner
readonly miner: string;
The miner of the block, also known as the ``author`` or block ``producer``.
property number
readonly number: number;
The block number also known as the block height.
property timestamp
readonly timestamp: number;
The block timestamp, in seconds from epoch.
interface MinedTransactionResponse
interface MinedTransactionResponse extends TransactionResponse {}
A **MinedTransactionResponse** is an interface representing a transaction which has been mined and allows for a type guard for its property values being defined.
property blockHash
blockHash: string;
The block hash this transaction occurred in.
property blockNumber
blockNumber: number;
The block number this transaction occurred in.
property date
date: Date;
The date this transaction occurred on.
interface MissingArgumentError
interface MissingArgumentError extends EthersError<'MISSING_ARGUMENT'> {}
This Error indicates there were too few arguments were provided.
property count
count: number;
The number of arguments received.
property expectedCount
expectedCount: number;
The number of arguments expected.
interface NameResolver
interface NameResolver {}
An interface for any object which can resolve an ENS name.
method resolveName
resolveName: (name: string) => Promise<null | string>;
Resolve to the address for the ENS %%name%%.
Resolves to ``null`` if the name is unconfigued. Use [[resolveAddress]] (passing this object as %%resolver%%) to throw for names that are unconfigured.
interface NetworkError
interface NetworkError extends EthersError<'NETWORK_ERROR'> {}
This Error indicates a problem connecting to a network.
property event
event: string;
The network event.
interface NonceExpiredError
interface NonceExpiredError extends EthersError<'NONCE_EXPIRED'> {}
The sending account has already used this nonce in a transaction that has been included.
property transaction
transaction: TransactionRequest;
The transaction.
interface NotImplementedError
interface NotImplementedError extends EthersError<'NOT_IMPLEMENTED'> {}
This Error is mostly used as a stub for functionality that is intended for the future, but is currently not implemented.
property operation
operation: string;
The attempted operation.
interface NumericFaultError
interface NumericFaultError extends EthersError<'NUMERIC_FAULT'> {}
This Error indicates an operation which would result in incorrect arithmetic output has occurred.
For example, trying to divide by zero or using a ``uint8`` to store a negative value.
interface OffchainFaultError
interface OffchainFaultError extends EthersError<'OFFCHAIN_FAULT'> {}
A CCIP-read exception, which cannot be recovered from or be further processed.
property reason
reason: string;
The reason the CCIP-read failed.
property transaction
transaction?: TransactionRequest;
The transaction.
interface Overrides
interface Overrides extends Omit<TransactionRequest, 'to' | 'data'> {}
The overrides for a contract transaction.
interface PerformActionTransaction
interface PerformActionTransaction extends PreparedTransactionRequest {}
A normalized transactions used for [[PerformActionRequest]] objects.
interface PreparedTransactionRequest
interface PreparedTransactionRequest {}
A **PreparedTransactionRequest** is identical to a [[TransactionRequest]] except all the property types are strictly enforced.
property accessList
accessList?: AccessList;
The [[link-eip-2930]] access list. Storage slots included in the access list are //warmed// by pre-loading them, so their initial cost to fetch is guaranteed, but then each additional access is cheaper.
property blockTag
blockTag?: BlockTag;
When using ``call`` or ``estimateGas``, this allows a specific block to be queried. Many backends do not support this and when unsupported errors are silently squelched and ``"latest"`` is used.
property chainId
chainId?: bigint;
The chain ID for the network this transaction is valid on.
property customData
customData?: any;
A custom object, which can be passed along for network-specific values.
property data
data?: string;
The transaction data.
property enableCcipRead
enableCcipRead?: boolean;
When using ``call``, this enables CCIP-read, which permits the provider to be redirected to web-based content during execution, which is then further validated by the contract.
There are potential security implications allowing CCIP-read, as it could be used to expose the IP address or user activity during the fetch to unexpected parties.
property from
from?: AddressLike;
The sender of the transaction.
property gasLimit
gasLimit?: bigint;
The maximum amount of gas to allow this transaction to consime.
property gasPrice
gasPrice?: bigint;
The gas price to use for legacy transactions or transactions on legacy networks.
Most of the time the ``max*FeePerGas`` is preferred.
property maxFeePerGas
maxFeePerGas?: bigint;
The [[link-eip-1559]] maximum total fee to pay per gas. The actual value used is protocol enforced to be the block's base fee.
property maxPriorityFeePerGas
maxPriorityFeePerGas?: bigint;
The [[link-eip-1559]] maximum priority fee to pay per gas.
property nonce
nonce?: number;
The nonce of the transaction, used to prevent replay attacks.
property to
to?: AddressLike;
The target of the transaction.
property type
type?: number;
The transaction type.
property value
value?: bigint;
The transaction value (in wei).
interface Provider
interface Provider extends ContractRunner, EventEmitterable<ProviderEvent>, NameResolver {}
A **Provider** is the primary method to interact with the read-only content on Ethereum.
It allows access to details about accounts, blocks and transactions and the ability to query event logs and simulate contract execution.
Account data includes the [balance](getBalance), [transaction count](getTransactionCount), [code](getCode) and [state trie storage](getStorage).
Simulating execution can be used to [call](call), [estimate gas](estimateGas) and [get transaction results](getTransactionResult).
The [[broadcastTransaction]] is the only method which allows updating the blockchain, but it is usually accessed by a [[Signer]], since a private key must be used to sign the transaction before it can be broadcast.
property provider
provider: this;
The provider iteself.
This is part of the necessary API for executing a contract, as it provides a common property on any [[ContractRunner]] that can be used to access the read-only portion of the runner.
method broadcastTransaction
broadcastTransaction: (signedTx: string) => Promise<TransactionResponse>;
Broadcasts the %%signedTx%% to the network, adding it to the memory pool of any node for which the transaction meets the rebroadcast requirements.
method call
call: (tx: TransactionRequest) => Promise<string>;
Simulate the execution of %%tx%%. If the call reverts, it will throw a [[CallExceptionError]] which includes the revert data.
method destroy
destroy: () => void;
Shutdown any resources this provider is using. No additional calls should be made to this provider after calling this.
method estimateGas
estimateGas: (tx: TransactionRequest) => Promise<bigint>;
Estimates the amount of gas required to execute %%tx%%.
method getBalance
getBalance: (address: AddressLike, blockTag?: BlockTag) => Promise<bigint>;
Get the account balance (in wei) of %%address%%. If %%blockTag%% is specified and the node supports archive access for that %%blockTag%%, the balance is as of that [[BlockTag]].
On nodes without archive access enabled, the %%blockTag%% may be **silently ignored** by the node, which may cause issues if relied on.
method getBlock
getBlock: ( blockHashOrBlockTag: BlockTag | string, prefetchTxs?: boolean) => Promise<null | Block>;
Resolves to the block for %%blockHashOrBlockTag%%.
If %%prefetchTxs%%, and the backend supports including transactions with block requests, all transactions will be included and the [[Block]] object will not need to make remote calls for getting transactions.
method getBlockNumber
getBlockNumber: () => Promise<number>;
Get the current block number.
method getCode
getCode: (address: AddressLike, blockTag?: BlockTag) => Promise<string>;
Get the bytecode for %%address%%.
On nodes without archive access enabled, the %%blockTag%% may be **silently ignored** by the node, which may cause issues if relied on.
method getFeeData
getFeeData: () => Promise<FeeData>;
Get the best guess at the recommended [[FeeData]].
method getLogs
getLogs: (filter: Filter | FilterByBlockHash) => Promise<Array<Log>>;
Resolves to the list of Logs that match %%filter%%
method getNetwork
getNetwork: () => Promise<Network>;
Get the connected [[Network]].
method getStorage
getStorage: ( address: AddressLike, position: BigNumberish, blockTag?: BlockTag) => Promise<string>;
Get the storage slot value for %%address%% at slot %%position%%.
On nodes without archive access enabled, the %%blockTag%% may be **silently ignored** by the node, which may cause issues if relied on.
method getTransaction
getTransaction: (hash: string) => Promise<null | TransactionResponse>;
Resolves to the transaction for %%hash%%.
If the transaction is unknown or on pruning nodes which discard old transactions this resolves to ``null``.
method getTransactionCount
getTransactionCount: ( address: AddressLike, blockTag?: BlockTag) => Promise<number>;
Get the number of transactions ever sent for %%address%%, which is used as the ``nonce`` when sending a transaction. If %%blockTag%% is specified and the node supports archive access for that %%blockTag%%, the transaction count is as of that [[BlockTag]].
On nodes without archive access enabled, the %%blockTag%% may be **silently ignored** by the node, which may cause issues if relied on.
method getTransactionReceipt
getTransactionReceipt: (hash: string) => Promise<null | TransactionReceipt>;
Resolves to the transaction receipt for %%hash%%, if mined.
If the transaction has not been mined, is unknown or on pruning nodes which discard old transactions this resolves to ``null``.
method getTransactionResult
getTransactionResult: (hash: string) => Promise<null | string>;
Resolves to the result returned by the executions of %%hash%%.
This is only supported on nodes with archive access and with the necessary debug APIs enabled.
method lookupAddress
lookupAddress: (address: string) => Promise<null | string>;
Resolves to the ENS name associated for the %%address%% or ``null`` if the //primary name// is not configured.
Users must perform additional steps to configure a //primary name//, which is not currently common.
method resolveName
resolveName: (ensName: string) => Promise<null | string>;
Resolves to the address configured for the %%ensName%% or ``null`` if unconfigured.
method waitForBlock
waitForBlock: (blockTag?: BlockTag) => Promise<Block>;
Resolves to the block at %%blockTag%% once it has been mined.
This can be useful for waiting some number of blocks by using the ``currentBlockNumber + N``.
method waitForTransaction
waitForTransaction: ( hash: string, confirms?: number, timeout?: number) => Promise<null | TransactionReceipt>;
Waits until the transaction %%hash%% is mined and has %%confirms%% confirmations.
interface ReplacementUnderpricedError
interface ReplacementUnderpricedError extends EthersError<'REPLACEMENT_UNDERPRICED'> {}
An attempt was made to replace a transaction, but with an insufficient additional fee to afford evicting the old transaction from the memory pool.
property transaction
transaction: TransactionRequest;
The transaction.
interface ServerError
interface ServerError extends EthersError<'SERVER_ERROR'> {}
This Error indicates there was a problem fetching a resource from a server.
interface Signer
interface Signer extends Addressable, ContractRunner, NameResolver {}
A Signer represents an account on the Ethereum Blockchain, and is most often backed by a private key represented by a mnemonic or residing on a Hardware Wallet.
The API remains abstract though, so that it can deal with more advanced exotic Signing entities, such as Smart Contract Wallets or Virtual Wallets (where the private key may not be known).
property provider
provider: null | Provider;
The [[Provider]] attached to this Signer (if any).
method call
call: (tx: TransactionRequest) => Promise<string>;
Evaluates the //tx// by running it against the current Blockchain state. This cannot change state and has no cost in ether, as it is effectively simulating execution.
This can be used to have the Blockchain perform computations based on its state (e.g. running a Contract's getters) or to simulate the effect of a transaction before actually performing an operation.
method connect
connect: (provider: null | Provider) => Signer;
Returns a new instance of this Signer connected to //provider// or detached from any Provider if null.
method estimateGas
estimateGas: (tx: TransactionRequest) => Promise<bigint>;
Estimates the required gas required to execute //tx// on the Blockchain. This will be the expected amount a transaction will require as its ``gasLimit`` to successfully run all the necessary computations and store the needed state that the transaction intends.
Keep in mind that this is **best efforts**, since the state of the Blockchain is in flux, which could affect transaction gas requirements.
Throws
UNPREDICTABLE_GAS_LIMIT A transaction that is believed by the node to likely fail will throw an error during gas estimation. This could indicate that it will actually fail or that the circumstances are simply too complex for the node to take into account. In these cases, a manually determined ``gasLimit`` will need to be made.
method getAddress
getAddress: () => Promise<string>;
Get the address of the Signer.
method getNonce
getNonce: (blockTag?: BlockTag) => Promise<number>;
Gets the next nonce required for this Signer to send a transaction.
Parameter blockTag
The blocktag to base the transaction count on, keep in mind many nodes do not honour this value and silently ignore it [default: ``"latest"``]
method populateCall
populateCall: (tx: TransactionRequest) => Promise<TransactionLike<string>>;
Prepares a TransactionRequest for calling: - resolves ``to`` and ``from`` addresses - if ``from`` is specified , check that it matches this Signer
Parameter tx
The call to prepare
method populateTransaction
populateTransaction: ( tx: TransactionRequest) => Promise<TransactionLike<string>>;
Prepares a TransactionRequest for sending to the network by populating any missing properties: - resolves ``to`` and ``from`` addresses - if ``from`` is specified , check that it matches this Signer - populates ``nonce`` via ``signer.getNonce("pending")`` - populates ``gasLimit`` via ``signer.estimateGas(tx)`` - populates ``chainId`` via ``signer.provider.getNetwork()`` - populates ``type`` and relevant fee data for that type (``gasPrice`` for legacy transactions, ``maxFeePerGas`` for EIP-1559, etc)
Some Signer implementations may skip populating properties that are populated downstream; for example JsonRpcSigner defers to the node to populate the nonce and fee data.
Parameter tx
The call to prepare
method resolveName
resolveName: (name: string) => Promise<null | string>;
Resolves an ENS Name to an address.
method sendTransaction
sendTransaction: (tx: TransactionRequest) => Promise<TransactionResponse>;
Sends %%tx%% to the Network. The ``signer.populateTransaction(tx)`` is called first to ensure all necessary properties for the transaction to be valid have been popualted first.
method signMessage
signMessage: (message: string | Uint8Array) => Promise<string>;
Signs an [[link-eip-191]] prefixed personal message.
If the %%message%% is a string, it is signed as UTF-8 encoded bytes. It is **not** interpretted as a [[BytesLike]]; so the string ``"0x1234"`` is signed as six characters, **not** two bytes.
To sign that example as two bytes, the Uint8Array should be used (i.e. ``new Uint8Array([ 0x12, 0x34 ])``).
method signTransaction
signTransaction: (tx: TransactionRequest) => Promise<string>;
Signs %%tx%%, returning the fully signed transaction. This does not populate any additional properties within the transaction.
method signTypedData
signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => Promise<string>;
Signs the [[link-eip-712]] typed data.
interface Subscriber
interface Subscriber {}
A **Subscriber** manages a subscription.
Only developers sub-classing [[AbstractProvider[[ will care about this, if they are modifying a low-level feature of how subscriptions operate.
property pollingInterval
pollingInterval?: number;
The frequency (in ms) to poll for events, if polling is used by the subscriber.
For non-polling subscribers, this must return ``undefined``.
method pause
pause: (dropWhilePaused?: boolean) => void;
Called when the subscription should pause.
If %%dropWhilePaused%%, events that occur while paused should not be emitted [[resume]].
method resume
resume: () => void;
Resume a paused subscriber.
method start
start: () => void;
Called initially when a subscriber is added the first time.
method stop
stop: () => void;
Called when there are no more subscribers to the event.
interface TimeoutError
interface TimeoutError extends EthersError<'TIMEOUT'> {}
This Error indicates that the timeout duration has expired and that the operation has been implicitly cancelled.
The side-effect of the operation may still occur, as this generally means a request has been sent and there has simply been no response to indicate whether it was processed or not.
interface TransactionLike
interface TransactionLike<A = string> {}
A **TransactionLike** is an object which is appropriate as a loose input for many operations which will populate missing properties of a transaction.
property accessList
accessList?: null | AccessListish;
The access list for berlin and london transactions.
property blobs
blobs?: null | Array<BlobLike>;
The blobs (if any) attached to this transaction (see [[link-eip-4844]]).
property blobVersionedHashes
blobVersionedHashes?: null | Array<string>;
The versioned hashes (see [[link-eip-4844]]).
property chainId
chainId?: null | BigNumberish;
The chain ID the transaction is valid on.
property data
data?: null | string;
The data.
property from
from?: null | A;
The sender.
property gasLimit
gasLimit?: null | BigNumberish;
The maximum amount of gas that can be used.
property gasPrice
gasPrice?: null | BigNumberish;
The gas price for legacy and berlin transactions.
property hash
hash?: null | string;
The transaction hash.
property kzg
kzg?: null | KzgLibrary;
An external library for computing the KZG commitments and proofs necessary for EIP-4844 transactions (see [[link-eip-4844]]).
This is generally ``null``, unless you are creating BLOb transactions.
property maxFeePerBlobGas
maxFeePerBlobGas?: null | BigNumberish;
The maximum fee per blob gas (see [[link-eip-4844]]).
property maxFeePerGas
maxFeePerGas?: null | BigNumberish;
The maximum total fee per gas for london transactions.
property maxPriorityFeePerGas
maxPriorityFeePerGas?: null | BigNumberish;
The maximum priority fee per gas for london transactions.
property nonce
nonce?: null | number;
The nonce.
property signature
signature?: null | SignatureLike;
The signature provided by the sender.
property to
to?: null | A;
The recipient address or ``null`` for an ``init`` transaction.
property type
type?: null | number;
The type.
property value
value?: null | BigNumberish;
The value (in wei) to send.
interface TransactionReceiptParams
interface TransactionReceiptParams {}
a **TransactionReceiptParams** encodes the minimal required properties for a formatted transaction receipt.
property blobGasPrice
blobGasPrice?: null | bigint;
The actual BLOb gas price that was charged. See [[link-eip-4844]].
property blobGasUsed
blobGasUsed?: null | bigint;
The amount of BLOb gas used. See [[link-eip-4844]].
property blockHash
blockHash: string;
The block hash of the block that included this transaction.
property blockNumber
blockNumber: number;
The block number of the block that included this transaction.
property contractAddress
contractAddress: null | string;
If the transaction was directly deploying a contract, the [[to]] will be null, the ``data`` will be initcode and if successful, this will be the address of the contract deployed.
property cumulativeGasUsed
cumulativeGasUsed: bigint;
The total amount of gas consumed during the entire block up to and including this transaction.
property effectiveGasPrice
effectiveGasPrice?: null | bigint;
The actual gas price per gas charged for this transaction.
property from
from: string;
The sender of the transaction.
property gasPrice
gasPrice?: null | bigint;
The actual gas price per gas charged for this transaction.
property gasUsed
gasUsed: bigint;
The amount of gas consumed executing this transaciton.
property hash
hash: string;
The transaction hash.
property index
index: number;
The transaction index.
property logs
logs: ReadonlyArray<LogParams>;
The logs emitted during the execution of this transaction.
property logsBloom
logsBloom: string;
The bloom filter for the logs emitted during execution of this transaction.
property root
root: null | string;
The root of this transaction in a pre-bazatium block. In post-byzantium blocks this is null.
property status
status: null | number;
The status of the transaction execution. If ``1`` then the the transaction returned success, if ``0`` then the transaction was reverted. For pre-byzantium blocks, this is usually null, but some nodes may have backfilled this data.
property to
to: null | string;
The target of the transaction. If null, the transaction was trying to deploy a transaction with the ``data`` as the initi=code.
property type
type: number;
The [[link-eip-2718]] envelope type.
interface TransactionReplacedError
interface TransactionReplacedError extends EthersError<'TRANSACTION_REPLACED'> {}
A pending transaction was replaced by another.
property cancelled
cancelled: boolean;
If the transaction was cancelled, such that the original effects of the transaction cannot be assured.
property hash
hash: string;
The hash of the replaced transaction.
property reason
reason: 'repriced' | 'cancelled' | 'replaced';
The reason the transaction was replaced.
property receipt
receipt: TransactionReceipt;
The receipt of the transaction that replace the transaction.
property replacement
replacement: TransactionResponse;
The transaction that replaced the transaction.
interface TransactionRequest
interface TransactionRequest {}
A **TransactionRequest** is a transactions with potentially various properties not defined, or with less strict types for its values.
This is used to pass to various operations, which will internally coerce any types and populate any necessary values.
property accessList
accessList?: null | AccessListish;
The [[link-eip-2930]] access list. Storage slots included in the access list are //warmed// by pre-loading them, so their initial cost to fetch is guaranteed, but then each additional access is cheaper.
property blobs
blobs?: null | Array<BlobLike>;
Any blobs to include in the transaction (see [[link-eip-4844]]).
property blobVersionedHashes
blobVersionedHashes?: null | Array<string>;
The blob versioned hashes (see [[link-eip-4844]]).
property blockTag
blockTag?: BlockTag;
When using ``call`` or ``estimateGas``, this allows a specific block to be queried. Many backends do not support this and when unsupported errors are silently squelched and ``"latest"`` is used.
property chainId
chainId?: null | BigNumberish;
The chain ID for the network this transaction is valid on.
property customData
customData?: any;
A custom object, which can be passed along for network-specific values.
property data
data?: null | string;
The transaction data.
property enableCcipRead
enableCcipRead?: boolean;
When using ``call``, this enables CCIP-read, which permits the provider to be redirected to web-based content during execution, which is then further validated by the contract.
There are potential security implications allowing CCIP-read, as it could be used to expose the IP address or user activity during the fetch to unexpected parties.
property from
from?: null | AddressLike;
The sender of the transaction.
property gasLimit
gasLimit?: null | BigNumberish;
The maximum amount of gas to allow this transaction to consume.
property gasPrice
gasPrice?: null | BigNumberish;
The gas price to use for legacy transactions or transactions on legacy networks.
Most of the time the ``max*FeePerGas`` is preferred.
property kzg
kzg?: null | KzgLibrary;
An external library for computing the KZG commitments and proofs necessary for EIP-4844 transactions (see [[link-eip-4844]]).
This is generally ``null``, unless you are creating BLOb transactions.
property maxFeePerBlobGas
maxFeePerBlobGas?: null | BigNumberish;
The maximum fee per blob gas (see [[link-eip-4844]]).
property maxFeePerGas
maxFeePerGas?: null | BigNumberish;
The [[link-eip-1559]] maximum total fee to pay per gas. The actual value used is protocol enforced to be the block's base fee.
property maxPriorityFeePerGas
maxPriorityFeePerGas?: null | BigNumberish;
The [[link-eip-1559]] maximum priority fee to pay per gas.
property nonce
nonce?: null | number;
The nonce of the transaction, used to prevent replay attacks.
property to
to?: null | AddressLike;
The target of the transaction.
property type
type?: null | number;
The transaction type.
property value
value?: null | BigNumberish;
The transaction value (in wei).
interface TransactionResponseParams
interface TransactionResponseParams {}
a **TransactionResponseParams** encodes the minimal required properties for a formatted transaction response.
property accessList
accessList: null | AccessList;
The transaction access list.
property blobVersionedHashes
blobVersionedHashes?: null | Array<string>;
The [[link-eip-4844]] BLOb versioned hashes.
property blockHash
blockHash: null | string;
The block hash of the block that included this transaction.
property blockNumber
blockNumber: null | number;
The block number of the block that included this transaction.
property chainId
chainId: bigint;
The chain ID this transaction is valid on.
property data
data: string;
The transaction data.
property from
from: string;
The sender of the transaction.
property gasLimit
gasLimit: bigint;
The maximum amount of gas this transaction is authorized to consume.
property gasPrice
gasPrice: bigint;
For legacy transactions, this is the gas price per gas to pay.
property hash
hash: string;
The transaction hash.
property index
index: number;
The transaction index.
property maxFeePerBlobGas
maxFeePerBlobGas?: null | bigint;
For [[link-eip-4844]] transactions, this is the maximum fee that will be paid per BLOb.
property maxFeePerGas
maxFeePerGas: null | bigint;
For [[link-eip-1559]] transactions, this is the maximum fee that will be paid.
property maxPriorityFeePerGas
maxPriorityFeePerGas: null | bigint;
For [[link-eip-1559]] transactions, this is the maximum priority fee to allow a producer to claim.
property nonce
nonce: number;
The nonce of the transaction, used for replay protection.
property signature
signature: Signature;
The signature of the transaction.
property to
to: null | string;
The target of the transaction. If ``null``, the ``data`` is initcode and this transaction is a deployment transaction.
property type
type: number;
The [[link-eip-2718]] transaction type.
property value
value: bigint;
The transaction value (in wei).
interface TypedDataDomain
interface TypedDataDomain {}
The domain for an [[link-eip-712]] payload.
property chainId
chainId?: null | BigNumberish;
The chain ID of the signing domain.
property name
name?: null | string;
The human-readable name of the signing domain.
property salt
salt?: null | BytesLike;
A salt used for purposes decided by the specific domain.
property verifyingContract
verifyingContract?: null | string;
The the address of the contract that will verify the signature.
property version
version?: null | string;
The major version of the signing domain.
interface TypedDataField
interface TypedDataField {}
A specific field of a structured [[link-eip-712]] type.
interface UnconfiguredNameError
interface UnconfiguredNameError extends EthersError<'UNCONFIGURED_NAME'> {}
This Error indicates an ENS name was used, but the name has not been configured.
This could indicate an ENS name is unowned or that the current address being pointed to is the [[ZeroAddress]].
property value
value: string;
The ENS name that was requested
interface UnexpectedArgumentError
interface UnexpectedArgumentError extends EthersError<'UNEXPECTED_ARGUMENT'> {}
This Error indicates too many arguments were provided.
property count
count: number;
The number of arguments received.
property expectedCount
expectedCount: number;
The number of arguments expected.
interface UnknownError
interface UnknownError extends EthersError<'UNKNOWN_ERROR'> {}
This Error is a catch-all for when there is no way for Ethers to know what the underlying problem is.
index signature
[key: string]: any;
interface UnsupportedOperationError
interface UnsupportedOperationError extends EthersError<'UNSUPPORTED_OPERATION'> {}
This Error indicates that the attempted operation is not supported.
This could range from a specific JSON-RPC end-point not supporting a feature to a specific configuration of an object prohibiting the operation.
For example, a [[Wallet]] with no connected [[Provider]] is unable to send a transaction.
property operation
operation: string;
The attempted operation.
interface WebSocketLike
interface WebSocketLike {}
A generic interface to a Websocket-like object.
property onerror
onerror: null | ((...args: Array<any>) => any);
property onmessage
onmessage: null | ((...args: Array<any>) => any);
property onopen
onopen: null | ((...args: Array<any>) => any);
property readyState
readyState: number;
method close
close: (code?: number, reason?: string) => void;
method send
send: (payload: any) => void;
interface WrappedFallback
interface WrappedFallback {}
A Fallback or Receive function on a Contract.
method estimateGas
estimateGas: (overrides?: Omit<TransactionRequest, 'to'>) => Promise<bigint>;
Estimate the gas to send a transaction to the contract fallback.
For non-receive fallback, ``data`` may be overridden.
method populateTransaction
populateTransaction: ( overrides?: Omit<TransactionRequest, 'to'>) => Promise<ContractTransaction>;
Returns a populated transaction that can be used to perform the fallback method.
For non-receive fallback, ``data`` may be overridden.
method send
send: ( overrides?: Omit<TransactionRequest, 'to'>) => Promise<ContractTransactionResponse>;
Send a transaction to the contract fallback.
For non-receive fallback, ``data`` may be overridden.
method staticCall
staticCall: (overrides?: Omit<TransactionRequest, 'to'>) => Promise<string>;
Call the contract fallback and return the result.
For non-receive fallback, ``data`` may be overridden.
call signature
( overrides?: Omit<TransactionRequest, 'to'>): Promise<ContractTransactionResponse>;
Type Aliases
type AbstractProviderOptions
type AbstractProviderOptions = { cacheTimeout?: number; pollingInterval?: number;};
Options for configuring some internal aspects of an [[AbstractProvider]].
**``cacheTimeout``** - how long to cache a low-level ``_perform`` for, based on input parameters. This reduces the number of calls to getChainId and getBlockNumber, but may break test chains which can perform operations (internally) synchronously. Use ``-1`` to disable, ``0`` will only buffer within the same event loop and any other value is in ms. (default: ``250``)
type AccessList
type AccessList = Array<AccessListEntry>;
An ordered collection of [[AccessList]] entries.
type AccessListEntry
type AccessListEntry = { address: string; storageKeys: Array<string>;};
A single [[AccessList]] entry of storage keys (slots) for an address.
type AccessListish
type AccessListish = | AccessList | Array<[string, Array<string>]> | Record<string, Array<string>>;
Any ethers-supported access list structure.
type AddressLike
type AddressLike = string | Promise<string> | Addressable;
Anything that can be used to return or resolve an address.
type BigNumberish
type BigNumberish = string | Numeric;
Any type that can be used where a big number is needed.
type BlobLike
type BlobLike = | BytesLike | { data: BytesLike; proof: BytesLike; commitment: BytesLike; };
A BLOb object that can be passed for [[link-eip-4844]] transactions.
It may have had its commitment and proof already provided or rely on an attached [[KzgLibrary]] to compute them.
type BlockTag
type BlockTag = BigNumberish | string;
A **BlockTag** specifies a specific block.
**numeric value** - specifies the block height, where the genesis block is block 0; many operations accept a negative value which indicates the block number should be deducted from the most recent block. A numeric value may be a ``number``, ``bigint``, or a decimal of hex string.
**blockhash** - specifies a specific block by its blockhash; this allows potentially orphaned blocks to be specifed, without ambiguity, but many backends do not support this for some operations.
type BrowserProviderOptions
type BrowserProviderOptions = { polling?: boolean; staticNetwork?: null | boolean | Network; cacheTimeout?: number; pollingInterval?: number;};
type BytesLike
type BytesLike = DataHexString | Uint8Array;
An object that can be used to represent binary data.
type CallExceptionAction
type CallExceptionAction = | 'call' | 'estimateGas' | 'getTransactionResult' | 'sendTransaction' | 'unknown';
The action that resulted in the call exception.
type CallExceptionTransaction
type CallExceptionTransaction = { to: null | string; from?: string; data: string;};
The related transaction that caused the error.
type CodedEthersError
type CodedEthersError<T> = T extends 'UNKNOWN_ERROR' ? UnknownError : T extends 'NOT_IMPLEMENTED' ? NotImplementedError : T extends 'UNSUPPORTED_OPERATION' ? UnsupportedOperationError : T extends 'NETWORK_ERROR' ? NetworkError : T extends 'SERVER_ERROR' ? ServerError : T extends 'TIMEOUT' ? TimeoutError : T extends 'BAD_DATA' ? BadDataError : T extends 'CANCELLED' ? CancelledError : T extends 'BUFFER_OVERRUN' ? BufferOverrunError : T extends 'NUMERIC_FAULT' ? NumericFaultError : T extends 'INVALID_ARGUMENT' ? InvalidArgumentError : T extends 'MISSING_ARGUMENT' ? MissingArgumentError : T extends 'UNEXPECTED_ARGUMENT' ? UnexpectedArgumentError : T extends 'CALL_EXCEPTION' ? CallExceptionError : T extends 'INSUFFICIENT_FUNDS' ? InsufficientFundsError : T extends 'NONCE_EXPIRED' ? NonceExpiredError : T extends 'OFFCHAIN_FAULT' ? OffchainFaultError : T extends 'REPLACEMENT_UNDERPRICED' ? ReplacementUnderpricedError : T extends 'TRANSACTION_REPLACED' ? TransactionReplacedError : T extends 'UNCONFIGURED_NAME' ? UnconfiguredNameError : T extends 'ACTION_REJECTED' ? ActionRejectedError : never;
A conditional type that transforms the [[ErrorCode]] T into its EthersError type.
@flatworm-skip-docs
type ContractEventArgs
type ContractEventArgs<A extends Array<any>> = { [I in keyof A]?: A[I] | Typed | null;};
Each argument of an event is nullable (to indicate matching //any//.
@_ignore:
type ContractEventName
type ContractEventName = string | ContractEvent | TopicFilter | DeferredTopicFilter;
The name for an event used for subscribing to Contract events.
**``string``** - An event by name. The event must be non-ambiguous. The parameters will be dereferenced when passed into the listener.
[[ContractEvent]] - A filter from the ``contract.filters``, which will pass only the EventPayload as a single parameter, which includes a ``.signature`` property that can be used to further filter the event.
[[TopicFilter]] - A filter defined using the standard Ethereum API which provides the specific topic hash or topic hashes to watch for along with any additional values to filter by. This will only pass a single parameter to the listener, the EventPayload which will include additional details to refine by, such as the event name and signature.
[[DeferredTopicFilter]] - A filter created by calling a [[ContractEvent]] with parameters, which will create a filter for a specific event signautre and dereference each parameter when calling the listener.
type ContractMethodArgs
type ContractMethodArgs<A extends Array<any>> = PostfixOverrides<{ [I in keyof A]-?: A[I] | Typed;}>;
Arguments to a Contract method can always include an additional and optional overrides parameter, and each parameter can optionally be [[Typed]].
@_ignore:
type CrowdsaleAccount
type CrowdsaleAccount = { privateKey: string; address: string;};
The data stored within a JSON Crowdsale wallet is fairly minimal.
type DebugEventBrowserProvider
type DebugEventBrowserProvider = | { action: 'sendEip1193Payload'; payload: { method: string; params: Array<any>; }; } | { action: 'receiveEip1193Result'; result: any; } | { action: 'receiveEip1193Error'; error: Error; };
The possible additional events dispatched when using the ``"debug"`` event on a [[BrowserProvider]].
type EncryptOptions
type EncryptOptions = { progressCallback?: ProgressCallback; iv?: BytesLike; entropy?: BytesLike; client?: string; salt?: BytesLike; uuid?: string; scrypt?: { N?: number; r?: number; p?: number; };};
The parameters to use when encrypting a JSON Keystore Wallet.
type ErrorCode
type ErrorCode = | 'UNKNOWN_ERROR' | 'NOT_IMPLEMENTED' | 'UNSUPPORTED_OPERATION' | 'NETWORK_ERROR' | 'SERVER_ERROR' | 'TIMEOUT' | 'BAD_DATA' | 'CANCELLED' | 'BUFFER_OVERRUN' | 'NUMERIC_FAULT' | 'INVALID_ARGUMENT' | 'MISSING_ARGUMENT' | 'UNEXPECTED_ARGUMENT' | 'VALUE_MISMATCH' | 'CALL_EXCEPTION' | 'INSUFFICIENT_FUNDS' | 'NONCE_EXPIRED' | 'REPLACEMENT_UNDERPRICED' | 'TRANSACTION_REPLACED' | 'UNCONFIGURED_NAME' | 'OFFCHAIN_FAULT' | 'ACTION_REJECTED';
All errors emitted by ethers have an **ErrorCode** to help identify and coalesce errors to simplify programmatic analysis.
Each **ErrorCode** is the %%code%% proerty of a coresponding [[EthersError]].
**Generic Errors**
**``"UNKNOWN_ERROR"``** - see [[UnknownError]]
**``"NOT_IMPLEMENTED"``** - see [[NotImplementedError]]
**``"UNSUPPORTED_OPERATION"``** - see [[UnsupportedOperationError]]
**``"NETWORK_ERROR"``** - see [[NetworkError]]
**``"SERVER_ERROR"``** - see [[ServerError]]
**``"TIMEOUT"``** - see [[TimeoutError]]
**``"BAD_DATA"``** - see [[BadDataError]]
**``"CANCELLED"``** - see [[CancelledError]]
**Operational Errors**
**``"BUFFER_OVERRUN"``** - see [[BufferOverrunError]]
**``"NUMERIC_FAULT"``** - see [[NumericFaultError]]
**Argument Errors**
**``"INVALID_ARGUMENT"``** - see [[InvalidArgumentError]]
**``"MISSING_ARGUMENT"``** - see [[MissingArgumentError]]
**``"UNEXPECTED_ARGUMENT"``** - see [[UnexpectedArgumentError]]
**``"VALUE_MISMATCH"``** - //unused//
**Blockchain Errors**
**``"CALL_EXCEPTION"``** - see [[CallExceptionError]]
**``"INSUFFICIENT_FUNDS"``** - see [[InsufficientFundsError]]
**``"NONCE_EXPIRED"``** - see [[NonceExpiredError]]
**``"REPLACEMENT_UNDERPRICED"``** - see [[ReplacementUnderpricedError]]
**``"TRANSACTION_REPLACED"``** - see [[TransactionReplacedError]]
**``"UNCONFIGURED_NAME"``** - see [[UnconfiguredNameError]]
**``"OFFCHAIN_FAULT"``** - see [[OffchainFaultError]]
**User Interaction Errors**
**``"ACTION_REJECTED"``** - see [[ActionRejectedError]]
type FallbackProviderOptions
type FallbackProviderOptions = { quorum?: number; eventQuorum?: number; eventWorkers?: number; cacheTimeout?: number; pollingInterval?: number;};
Additional options to configure a [[FallbackProvider]].
type FetchGatewayFunc
type FetchGatewayFunc = ( url: string, signal?: FetchCancelSignal) => Promise<FetchRequest | FetchResponse>;
Called on Gateway URLs.
type FetchGetUrlFunc
type FetchGetUrlFunc = ( req: FetchRequest, signal?: FetchCancelSignal) => Promise<GetUrlResponse>;
Used to perform a fetch; use this to override the underlying network fetch layer. In NodeJS, the default uses the "http" and "https" libraries and in the browser ``fetch`` is used. If you wish to use Axios, this is how you would register it.
type FetchPreflightFunc
type FetchPreflightFunc = (req: FetchRequest) => Promise<FetchRequest>;
Called before any network request, allowing updated headers (e.g. Bearer tokens), etc.
type FetchProcessFunc
type FetchProcessFunc = ( req: FetchRequest, resp: FetchResponse) => Promise<FetchResponse>;
Called on the response, allowing client-based throttling logic or post-processing.
type FetchRetryFunc
type FetchRetryFunc = ( req: FetchRequest, resp: FetchResponse, attempt: number) => Promise<boolean>;
Called prior to each retry; return true to retry, false to abort.
type FixedFormat
type FixedFormat = | number | string | { signed?: boolean; width?: number; decimals?: number; };
A description of a fixed-point arithmetic field.
When specifying the fixed format, the values override the default of a ``fixed128x18``, which implies a signed 128-bit value with 18 decimals of precision.
The alias ``fixed`` and ``ufixed`` can be used for ``fixed128x18`` and ``ufixed128x18`` respectively.
When a fixed format string begins with a ``u``, it indicates the field is unsigned, so any negative values will overflow. The first number indicates the bit-width and the second number indicates the decimal precision.
When a ``number`` is used for a fixed format, it indicates the number of decimal places, and the default width and signed-ness will be used.
The bit-width must be byte aligned and the decimals can be at most 80.
type FormatType
type FormatType = 'sighash' | 'minimal' | 'full' | 'json';
The format to serialize the output as.
**``"sighash"``** - the bare formatting, used to compute the selector or topic hash; this format cannot be reversed (as it discards ``indexed``) so cannot by used to export an [[Interface]].
**``"minimal"``** - Human-Readable ABI with minimal spacing and without names, so it is compact, but will result in Result objects that cannot be accessed by name.
**``"full"``** - Full Human-Readable ABI, with readable spacing and names intact; this is generally the recommended format.
**``"json"``** - The [JSON ABI format](link-solc-jsonabi).
type FragmentType
type FragmentType = | 'constructor' | 'error' | 'event' | 'fallback' | 'function' | 'struct';
The type of a [[Fragment]].
type GasCostParameters
type GasCostParameters = { /** * The transactions base fee. */ txBase?: number; /** * The fee for creating a new account. */ txCreate?: number; /** * The fee per zero-byte in the data. */ txDataZero?: number; /** * The fee per non-zero-byte in the data. */ txDataNonzero?: number; /** * The fee per storage key in the [[link-eip-2930]] access list. */ txAccessListStorageKey?: number; /** * The fee per address in the [[link-eip-2930]] access list. */ txAccessListAddress?: number;};
The gas cost parameters for a [[GasCostPlugin]].
type GetUrlResponse
type GetUrlResponse = { statusCode: number; statusMessage: string; headers: Record<string, string>; body: null | Uint8Array;};
An environment's implementation of ``getUrl`` must return this type.
type InterfaceAbi
type InterfaceAbi = string | ReadonlyArray<Fragment | JsonFragment | string>;
An **InterfaceAbi** may be any supported ABI format.
A string is expected to be a JSON string, which will be parsed using ``JSON.parse``. This means that the value **must** be a valid JSON string, with no stray commas, etc.
An array may contain any combination of: - Human-Readable fragments - Parsed JSON fragment - [[Fragment]] instances
A **Human-Readable Fragment** is a string which resembles a Solidity signature and is introduced in [this blog entry](link-ricmoo-humanreadableabi). For example, ``function balanceOf(address) view returns (uint)``.
A **Parsed JSON Fragment** is a JavaScript Object desribed in the [Solidity documentation](link-solc-jsonabi).
type JsonRpcApiProviderOptions
type JsonRpcApiProviderOptions = { polling?: boolean; staticNetwork?: null | boolean | Network; batchStallTime?: number; batchMaxSize?: number; batchMaxCount?: number; cacheTimeout?: number; pollingInterval?: number;};
Options for configuring a [[JsonRpcApiProvider]]. Much of this is targetted towards sub-classes, which often will not expose any of these options to their consumers.
**``polling``** - use the polling strategy is used immediately for events; otherwise, attempt to use filters and fall back onto polling (default: ``false``)
**``staticNetwork``** - do not request chain ID on requests to validate the underlying chain has not changed (default: ``null``)
This should **ONLY** be used if it is **certain** that the network cannot change, such as when using INFURA (since the URL dictates the network). If the network is assumed static and it does change, this can have tragic consequences. For example, this **CANNOT** be used with MetaMask, since the user can select a new network from the drop-down at any time.
**``batchStallTime``** - how long (ms) to aggregate requests into a single batch. ``0`` indicates batching will only encompass the current event loop. If ``batchMaxCount = 1``, this is ignored. (default: ``10``)
**``batchMaxSize``** - target maximum size (bytes) to allow per batch request (default: 1Mb)
**``batchMaxCount``** - maximum number of requests to allow in a batch. If ``batchMaxCount = 1``, then batching is disabled. (default: ``100``)
**``cacheTimeout``** - passed as [[AbstractProviderOptions]].
type JsonRpcError
type JsonRpcError = { /** * The response ID to match it to the relevant request. */ id: number; /** * The response error. */ error: { code: number; message?: string; data?: any; };};
A JSON-RPC error, which are returned on failure from a JSON-RPC server.
type JsonRpcPayload
type JsonRpcPayload = { /** * The JSON-RPC request ID. */ id: number; /** * The JSON-RPC request method. */ method: string; /** * The JSON-RPC request parameters. */ params: Array<any> | Record<string, any>; /** * A required constant in the JSON-RPC specification. */ jsonrpc: '2.0';};
A JSON-RPC payload, which are sent to a JSON-RPC server.
type JsonRpcResult
type JsonRpcResult = { /** * The response ID to match it to the relevant request. */ id: number; /** * The response result. */ result: any;};
A JSON-RPC result, which are returned on success from a JSON-RPC server.
type KeystoreAccount
type KeystoreAccount = { address: string; privateKey: string; mnemonic?: { path?: string; locale?: string; entropy: string; };};
The contents of a JSON Keystore Wallet.
type Listener
type Listener = (...args: Array<any>) => void;
A callback function called when a an event is triggered.
type Networkish
type Networkish = | Network | number | bigint | string | { name?: string; chainId?: number; ensAddress?: string; ensNetwork?: number; };
A Networkish can be used to allude to a Network, by specifing: - a [[Network]] object - a well-known (or registered) network name - a well-known (or registered) chain ID - an object with sufficient details to describe a network
type Numeric
type Numeric = number | bigint;
Any type that can be used where a numeric value is needed.
type OrphanFilter
type OrphanFilter = | { orphan: 'drop-block'; hash: string; number: number; } | { orphan: 'drop-transaction'; tx: { hash: string; blockHash: string; blockNumber: number; }; other?: { hash: string; blockHash: string; blockNumber: number; }; } | { orphan: 'reorder-transaction'; tx: { hash: string; blockHash: string; blockNumber: number; }; other?: { hash: string; blockHash: string; blockNumber: number; }; } | { orphan: 'drop-log'; log: { transactionHash: string; blockHash: string; blockNumber: number; address: string; data: string; topics: ReadonlyArray<string>; index: number; }; };
An Orphan Filter allows detecting when an orphan block has resulted in dropping a block or transaction or has resulted in transactions changing order.
Not currently fully supported.
type ParamTypeWalkAsyncFunc
type ParamTypeWalkAsyncFunc = (type: string, value: any) => any | Promise<any>;
When [walking asynchronously](ParamType-walkAsync) a [[ParamType]], this is called on each component.
type ParamTypeWalkFunc
type ParamTypeWalkFunc = (type: string, value: any) => any;
When [walking](ParamType-walk) a [[ParamType]], this is called on each component.
type PerformActionFilter
type PerformActionFilter = | { address?: string | Array<string>; topics?: Array<null | string | Array<string>>; fromBlock?: BlockTag; toBlock?: BlockTag; } | { address?: string | Array<string>; topics?: Array<null | string | Array<string>>; blockHash?: string; };
A normalized filter used for [[PerformActionRequest]] objects.
type PerformActionRequest
type PerformActionRequest = | { method: 'broadcastTransaction'; signedTransaction: string; } | { method: 'call'; transaction: PerformActionTransaction; blockTag: BlockTag; } | { method: 'chainId'; } | { method: 'estimateGas'; transaction: PerformActionTransaction; } | { method: 'getBalance'; address: string; blockTag: BlockTag; } | { method: 'getBlock'; blockTag: BlockTag; includeTransactions: boolean; } | { method: 'getBlock'; blockHash: string; includeTransactions: boolean; } | { method: 'getBlockNumber'; } | { method: 'getCode'; address: string; blockTag: BlockTag; } | { method: 'getGasPrice'; } | { method: 'getLogs'; filter: PerformActionFilter; } | { method: 'getPriorityFee'; } | { method: 'getStorage'; address: string; position: bigint; blockTag: BlockTag; } | { method: 'getTransaction'; hash: string; } | { method: 'getTransactionCount'; address: string; blockTag: BlockTag; } | { method: 'getTransactionReceipt'; hash: string; } | { method: 'getTransactionResult'; hash: string; };
The [[AbstractProvider]] methods will normalize all values and pass this type to [[AbstractProvider-_perform]].
type PostfixOverrides
type PostfixOverrides<A extends Array<any>> = A | [...A, Overrides];
Arguments to a Contract method can always include an additional and optional overrides parameter.
@_ignore:
type ProgressCallback
type ProgressCallback = (percent: number) => void;
A callback during long-running operations to update any UI or provide programatic access to the progress.
The %%percent%% is a value between ``0`` and ``1``.
@_docloc: api/crypto:Passwords
type ProviderEvent
type ProviderEvent = | string | Array<string | Array<string>> | EventFilter | OrphanFilter;
A **ProviderEvent** provides the types of events that can be subscribed to on a [[Provider]].
Each provider may include additional possible events it supports, but the most commonly supported are:
**``"block"``** - calls the listener with the current block number on each new block.
**``"error"``** - calls the listener on each async error that occurs during the event loop, with the error.
**``"debug"``** - calls the listener on debug events, which can be used to troubleshoot network errors, provider problems, etc.
**``transaction hash``** - calls the listener on each block after the transaction has been mined; generally ``.once`` is more appropriate for this event.
**``Array``** - calls the listener on each log that matches the filter.
[[EventFilter]] - calls the listener with each matching log
type RlpStructuredData
type RlpStructuredData = string | Array<RlpStructuredData>;
An RLP-encoded structure.
type RlpStructuredDataish
type RlpStructuredDataish = string | Uint8Array | Array<RlpStructuredDataish>;
An RLP-encoded structure, which allows Uint8Array.
type SignatureLike
type SignatureLike = | Signature | string | { r: string; s: string; v: BigNumberish; yParity?: 0 | 1; yParityAndS?: string; } | { r: string; yParityAndS: string; yParity?: 0 | 1; s?: string; v?: number; } | { r: string; s: string; yParity: 0 | 1; v?: BigNumberish; yParityAndS?: string; };
A SignatureLike
@_docloc: api/crypto:Signing
type Subscription
type Subscription = | { type: | 'block' | 'close' | 'debug' | 'error' | 'finalized' | 'network' | 'pending' | 'safe'; tag: string; } | { type: 'transaction'; tag: string; hash: string; } | { type: 'event'; tag: string; filter: EventFilter; } | { type: 'orphan'; tag: string; filter: OrphanFilter; };
The value passed to the [[AbstractProvider-_getSubscriber]] method.
Only developers sub-classing [[AbstractProvider[[ will care about this, if they are modifying a low-level feature of how subscriptions operate.
type TopicFilter
type TopicFilter = Array<null | string | Array<string>>;
A **TopicFilter** provides a struture to define bloom-filter queries.
Each field that is ``null`` matches **any** value, a field that is a ``string`` must match exactly that value and ``array`` is effectively an ``OR``-ed set, where any one of those values must match.
type UnicodeNormalizationForm
type UnicodeNormalizationForm = 'NFC' | 'NFD' | 'NFKC' | 'NFKD';
The stanard normalization forms.
type Utf8ErrorFunc
type Utf8ErrorFunc = ( reason: Utf8ErrorReason, offset: number, bytes: Uint8Array, output: Array<number>, badCodepoint?: number) => number;
A callback that can be used with [[toUtf8String]] to analysis or recovery from invalid UTF-8 data.
Parsing UTF-8 data is done through a simple Finite-State Machine (FSM) which calls the ``Utf8ErrorFunc`` if a fault is detected.
The %%reason%% indicates where in the FSM execution the fault occurred and the %%offset%% indicates where the input failed.
The %%bytes%% represents the raw UTF-8 data that was provided and %%output%% is the current array of UTF-8 code-points, which may be updated by the ``Utf8ErrorFunc``.
The value of the %%badCodepoint%% depends on the %%reason%%. See [[Utf8ErrorReason]] for details.
The function should return the number of bytes that should be skipped when control resumes to the FSM.
type Utf8ErrorReason
type Utf8ErrorReason = | 'UNEXPECTED_CONTINUE' | 'BAD_PREFIX' | 'OVERRUN' | 'MISSING_CONTINUE' | 'OUT_OF_RANGE' | 'UTF16_SURROGATE' | 'OVERLONG';
When using the UTF-8 error API the following errors can be intercepted and processed as the %%reason%% passed to the [[Utf8ErrorFunc]].
**``"UNEXPECTED_CONTINUE"``** - a continuation byte was present where there was nothing to continue.
**``"BAD_PREFIX"``** - an invalid (non-continuation) byte to start a UTF-8 codepoint was found.
**``"OVERRUN"``** - the string is too short to process the expected codepoint length.
**``"MISSING_CONTINUE"``** - a missing continuation byte was expected but not found. The %%offset%% indicates the index the continuation byte was expected at.
**``"OUT_OF_RANGE"``** - the computed code point is outside the range for UTF-8. The %%badCodepoint%% indicates the computed codepoint, which was outside the valid UTF-8 range.
**``"UTF16_SURROGATE"``** - the UTF-8 strings contained a UTF-16 surrogate pair. The %%badCodepoint%% is the computed codepoint, which was inside the UTF-16 surrogate range.
**``"OVERLONG"``** - the string is an overlong representation. The %%badCodepoint%% indicates the computed codepoint, which has already been bounds checked.
Returns
string
type WebSocketCreator
type WebSocketCreator = () => WebSocketLike;
A function which can be used to re-create a WebSocket connection on disconnect.
Namespaces
namespace computeHmac
namespace computeHmac {}
namespace ethers
module 'lib.commonjs/ethers.d.ts' {}
variable defaultPath
const defaultPath: string;
The default derivation path for Ethereum HD Nodes. (i.e. ``"m/44'/60'/0'/0/0"``)
variable EtherSymbol
const EtherSymbol: string;
A constant for the ether symbol (normalized using NFKC).
(**i.e.** ``"\u039e"``)
variable MaxInt256
const MaxInt256: BigInt;
A constant for the maximum value for an ``int256``.
(**i.e.** ``0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn``)
variable MaxUint256
const MaxUint256: BigInt;
A constant for the maximum value for a ``uint256``.
(**i.e.** ``0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn``)
variable MessagePrefix
const MessagePrefix: string;
A constant for the [[link-eip-191]] personal message prefix.
(**i.e.** ``"\x19Ethereum Signed Message:\n"``)
variable MinInt256
const MinInt256: BigInt;
A constant for the minimum value for an ``int256``.
(**i.e.** ``-8000000000000000000000000000000000000000000000000000000000000000n``)
variable N
const N: BigInt;
A constant for the order N for the secp256k1 curve.
(**i.e.** ``0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n``)
variable Utf8ErrorFuncs
const Utf8ErrorFuncs: Readonly< Record<'error' | 'ignore' | 'replace', Utf8ErrorFunc>>;
A handful of popular, built-in UTF-8 error handling strategies.
**``"error"``** - throws on ANY illegal UTF-8 sequence or non-canonical (overlong) codepoints (this is the default)
**``"ignore"``** - silently drops any illegal UTF-8 sequence and accepts non-canonical (overlong) codepoints
**``"replace"``** - replace any illegal UTF-8 sequence with the UTF-8 replacement character (i.e. ``"\ufffd"``) and accepts non-canonical (overlong) codepoints
@returns: Record<"error" | "ignore" | "replace", Utf8ErrorFunc>
variable version
const version: string;
The current version of Ethers.
variable WeiPerEther
const WeiPerEther: BigInt;
A constant for the number of wei in a single ether.
(**i.e.** ``1000000000000000000n``)
variable wordlists
const wordlists: Record<string, Wordlist>;
The available Wordlists by their [ISO 639-1 Language Code](link-wiki-iso639).
(**i.e.** [cz](LangCz), [en](LangEn), [es](LangEs), [fr](LangFr), [ja](LangJa), [ko](LangKo), [it](LangIt), [pt](LangPt), [zh_cn](LangZh), [zh_tw](LangZh))
The dist files (in the ``/dist`` folder) have had all languages except English stripped out, which reduces the library size by about 80kb. If required, they are available by importing the included ``wordlists-extra.min.js`` file.
variable ZeroAddress
const ZeroAddress: string;
A constant for the zero address.
(**i.e.** ``"0x0000000000000000000000000000000000000000"``)
variable ZeroHash
const ZeroHash: string;
A constant for the zero hash.
(**i.e.** ``"0x0000000000000000000000000000000000000000000000000000000000000000"``)
function accessListify
accessListify: (value: AccessListish) => AccessList;
Returns a [[AccessList]] from any ethers-supported access-list structure.
function assert
assert: <K extends ErrorCode, T extends CodedEthersError<K>>( check: unknown, message: string, code: K, info?: ErrorInfo<T>) => asserts check;
Throws an EthersError with %%message%%, %%code%% and additional error %%info%% when %%check%% is falsish..
See Also
[[api:makeError]]
function assertArgument
assertArgument: ( check: unknown, message: string, name: string, value: unknown) => asserts check;
A simple helper to simply ensuring provided arguments match expected constraints, throwing if not.
In TypeScript environments, the %%check%% has been asserted true, so any further code does not need additional compile-time checks.
function assertArgumentCount
assertArgumentCount: ( count: number, expectedCount: number, message?: string) => void;
function assertNormalize
assertNormalize: (form: string) => void;
Throws if the normalization %%form%% is not supported.
function assertPrivate
assertPrivate: (givenGuard: any, guard: any, className?: string) => void;
Many classes use file-scoped values to guard the constructor, making it effectively private. This facilitates that pattern by ensuring the %%givenGaurd%% matches the file-scoped %%guard%%, throwing if not, indicating the %%className%% if provided.
function checkResultErrors
checkResultErrors: ( result: Result) => Array<{ path: Array<string | number>; error: Error }>;
Returns all errors found in a [[Result]].
Since certain errors encountered when creating a [[Result]] do not impact the ability to continue parsing data, they are deferred until they are actually accessed. Hence a faulty string in an Event that is never used does not impact the program flow.
However, sometimes it may be useful to access, identify or validate correctness of a [[Result]].
@_docloc api/abi
function computeAddress
computeAddress: (key: string | SigningKey) => string;
Returns the address for the %%key%%.
The key may be any standard form of public key or a private key.
function computeHmac
computeHmac: typeof computeHmac;
Return the HMAC for %%data%% using the %%key%% key with the underlying %%algo%% used for compression.
@example: key = id("some-secret")
// Compute the HMAC computeHmac("sha256", key, "0x1337") //_result:
// To compute the HMAC of UTF-8 data, the data must be // converted to UTF-8 bytes computeHmac("sha256", key, toUtf8Bytes("Hello World")) //_result:
function concat
concat: (datas: ReadonlyArray<BytesLike>) => string;
Returns a [[DataHexString]] by concatenating all values within %%data%%.
function copyRequest
copyRequest: (req: TransactionRequest) => PreparedTransactionRequest;
Returns a copy of %%req%% with all properties coerced to their strict types.
function dataLength
dataLength: (data: BytesLike) => number;
Returns the length of %%data%%, in bytes.
function dataSlice
dataSlice: (data: BytesLike, start?: number, end?: number) => string;
Returns a [[DataHexString]] by slicing %%data%% from the %%start%% offset to the %%end%% offset.
By default %%start%% is 0 and %%end%% is the length of %%data%%.
function decodeBase58
decodeBase58: (value: string) => bigint;
Decode the Base58-encoded %%value%%.
function decodeBase64
decodeBase64: (value: string) => Uint8Array;
Decodes the base-64 encoded %%value%%.
@example: // The decoded value is always binary data... result = decodeBase64("SGVsbG8gV29ybGQhIQ==") //_result:
// ...use toUtf8String to convert it to a string. toUtf8String(result) //_result:
// Decoding binary data decodeBase64("EjQ=") //_result:
function decodeBytes32String
decodeBytes32String: (_bytes: BytesLike) => string;
Encodes the Bytes32-encoded %%bytes%% into a string.
function decodeRlp
decodeRlp: (_data: BytesLike) => RlpStructuredData;
Decodes %%data%% into the structured data it represents.
function decryptCrowdsaleJson
decryptCrowdsaleJson: ( json: string, _password: string | Uint8Array) => CrowdsaleAccount;
Before Ethereum launched, it was necessary to create a wallet format for backers to use, which would be used to receive ether as a reward for contributing to the project.
The [[link-crowdsale]] format is now obsolete, but it is still useful to support and the additional code is fairly trivial as all the primitives required are used through core portions of the library.
function decryptKeystoreJson
decryptKeystoreJson: ( json: string, _password: string | Uint8Array, progress?: ProgressCallback) => Promise<KeystoreAccount>;
Resolves to the decrypted JSON Keystore Wallet %%json%% using the %%password%%.
If provided, %%progress%% will be called periodically during the decrpytion to provide feedback, and if the function returns ``false`` will halt decryption.
The %%progressCallback%% will **always** receive ``0`` before decryption begins and ``1`` when complete.
function decryptKeystoreJsonSync
decryptKeystoreJsonSync: ( json: string, _password: string | Uint8Array) => KeystoreAccount;
Returns the account details for the JSON Keystore Wallet %%json%% using %%password%%.
It is preferred to use the [async version](decryptKeystoreJson) instead, which allows a [[ProgressCallback]] to keep the user informed as to the decryption status.
This method will block the event loop (freezing all UI) until decryption is complete, which can take quite some time, depending on the wallet paramters and platform.
function defineProperties
defineProperties: <T>( target: T, values: { [K in keyof T]?: T[K] }, types?: { [K in keyof T]?: string }) => void;
Assigns the %%values%% to %%target%% as read-only values.
It %%types%% is specified, the values are checked.
function dnsEncode
dnsEncode: (name: string, _maxLength?: number) => string;
Returns the DNS encoded %%name%%.
This is used for various parts of ENS name resolution, such as the wildcard resolution.
function encodeBase58
encodeBase58: (_value: BytesLike) => string;
Encode %%value%% as a Base58-encoded string.
function encodeBase64
encodeBase64: (data: BytesLike) => string;
Encodes %%data%% as a base-64 encoded string.
@example: // Encoding binary data as a hexstring encodeBase64("0x1234") //_result:
// Encoding binary data as a Uint8Array encodeBase64(new Uint8Array([ 0x12, 0x34 ])) //_result:
// The input MUST be data... encodeBase64("Hello World!!") //_error:
// ...use toUtf8Bytes for this. encodeBase64(toUtf8Bytes("Hello World!!")) //_result:
function encodeBytes32String
encodeBytes32String: (text: string) => string;
Encodes %%text%% as a Bytes32 string.
function encodeRlp
encodeRlp: (object: RlpStructuredDataish) => string;
Encodes %%object%% as an RLP-encoded [[DataHexString]].
function encryptKeystoreJson
encryptKeystoreJson: ( account: KeystoreAccount, password: string | Uint8Array, options?: EncryptOptions) => Promise<string>;
Resolved to the JSON Keystore Wallet for %%account%% encrypted with %%password%%.
The %%options%% can be used to tune the password-based key derivation function parameters, explicitly set the random values used and provide a [[ProgressCallback]] to receive periodic updates on the completion status..
function encryptKeystoreJsonSync
encryptKeystoreJsonSync: ( account: KeystoreAccount, password: string | Uint8Array, options?: EncryptOptions) => string;
Return the JSON Keystore Wallet for %%account%% encrypted with %%password%%.
The %%options%% can be used to tune the password-based key derivation function parameters, explicitly set the random values used. Any provided [[ProgressCallback]] is ignord.
function ensNormalize
ensNormalize: (name: string) => string;
Returns the ENS %%name%% normalized.
function formatEther
formatEther: (wei: BigNumberish) => string;
Converts %%value%% into a //decimal string// using 18 decimal places.
function formatUnits
formatUnits: (value: BigNumberish, unit?: string | Numeric) => string;
Converts %%value%% into a //decimal string//, assuming %%unit%% decimal places. The %%unit%% may be the number of decimal places or the name of a unit (e.g. ``"gwei"`` for 9 decimal places).
function fromTwos
fromTwos: (_value: BigNumberish, _width: Numeric) => bigint;
Convert %%value%% from a twos-compliment representation of %%width%% bits to its value.
If the highest bit is ``1``, the result will be negative.
function getAccountPath
getAccountPath: (_index: Numeric) => string;
Returns the [[link-bip-32]] path for the account at %%index%%.
This is the pattern used by wallets like Ledger.
There is also an [alternate pattern](getIndexedAccountPath) used by some software.
function getAddress
getAddress: (address: string) => string;
Returns a normalized and checksumed address for %%address%%. This accepts non-checksum addresses, checksum addresses and [[getIcapAddress]] formats.
The checksum in Ethereum uses the capitalization (upper-case vs lower-case) of the characters within an address to encode its checksum, which offers, on average, a checksum of 15-bits.
If %%address%% contains both upper-case and lower-case, it is assumed to already be a checksum address and its checksum is validated, and if the address fails its expected checksum an error is thrown.
If you wish the checksum of %%address%% to be ignore, it should be converted to lower-case (i.e. ``.toLowercase()``) before being passed in. This should be a very rare situation though, that you wish to bypass the safegaurds in place to protect against an address that has been incorrectly copied from another source.
@example: // Adds the checksum (via upper-casing specific letters) getAddress("0x8ba1f109551bd432803012645ac136ddd64dba72") //_result:
// Converts ICAP address and adds checksum getAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36"); //_result:
// Throws an error if an address contains mixed case, // but the checksum fails getAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72") //_error:
function getBigInt
getBigInt: (value: BigNumberish, name?: string) => bigint;
Gets a BigInt from %%value%%. If it is an invalid value for a BigInt, then an ArgumentError will be thrown for %%name%%.
function getBytes
getBytes: (value: BytesLike, name?: string) => Uint8Array;
Get a typed Uint8Array for %%value%%. If already a Uint8Array the original %%value%% is returned; if a copy is required use [[getBytesCopy]].
@see: getBytesCopy
function getBytesCopy
getBytesCopy: (value: BytesLike, name?: string) => Uint8Array;
Get a typed Uint8Array for %%value%%, creating a copy if necessary to prevent any modifications of the returned value from being reflected elsewhere.
@see: getBytes
function getCreate2Address
getCreate2Address: ( _from: string, _salt: BytesLike, _initCodeHash: BytesLike) => string;
Returns the address that would result from a ``CREATE2`` operation with the given %%from%%, %%salt%% and %%initCodeHash%%.
To compute the %%initCodeHash%% from a contract's init code, use the [[keccak256]] function.
For a quick overview and example of ``CREATE2``, see [[link-ricmoo-wisps]].
Example 1
// The address of the contract from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"
// The salt salt = id("HelloWorld")
// The hash of the initCode initCode = "0x6394198df16000526103ff60206004601c335afa6040516060f3"; initCodeHash = keccak256(initCode)
getCreate2Address(from, salt, initCodeHash) //_result:
function getCreateAddress
getCreateAddress: (tx: { from: string; nonce: BigNumberish }) => string;
Returns the address that would result from a ``CREATE`` for %%tx%%.
This can be used to compute the address a contract will be deployed to by an EOA when sending a deployment transaction (i.e. when the ``to`` address is ``null``).
This can also be used to compute the address a contract will be deployed to by a contract, by using the contract's address as the ``to`` and the contract's nonce.
Example 1
from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"; nonce = 5;
getCreateAddress({ from, nonce }); //_result:
function getDefaultProvider
getDefaultProvider: ( network?: string | Networkish | WebSocketLike, options?: any) => AbstractProvider;
Returns a default provider for %%network%%.
If %%network%% is a [[WebSocketLike]] or string that begins with ``"ws:"`` or ``"wss:"``, a [[WebSocketProvider]] is returned backed by that WebSocket or URL.
If %%network%% is a string that begins with ``"HTTP:"`` or ``"HTTPS:"``, a [[JsonRpcProvider]] is returned connected to that URL.
Otherwise, a default provider is created backed by well-known public Web3 backends (such as [[link-infura]]) using community-provided API keys.
The %%options%% allows specifying custom API keys per backend (setting an API key to ``"-"`` will omit that provider) and ``options.exclusive`` can be set to either a backend name or and array of backend names, which will whitelist **only** those backends.
Current backend strings supported are: - ``"alchemy"`` - ``"ankr"`` - ``"cloudflare"`` - ``"chainstack"`` - ``"etherscan"`` - ``"infura"`` - ``"publicPolygon"`` - ``"quicknode"``
@example: // Connect to a local Geth node provider = getDefaultProvider("http://localhost:8545/");
// Connect to Ethereum mainnet with any current and future // third-party services available provider = getDefaultProvider("mainnet");
// Connect to Polygon, but only allow Etherscan and // INFURA and use "MY_API_KEY" in calls to Etherscan. provider = getDefaultProvider("matic", { etherscan: "MY_API_KEY", exclusive: [ "etherscan", "infura" ] });
function getIcapAddress
getIcapAddress: (address: string) => string;
The [ICAP Address format](link-icap) format is an early checksum format which attempts to be compatible with the banking industry [IBAN format](link-wiki-iban) for bank accounts.
It is no longer common or a recommended format.
@example: getIcapAddress("0x8ba1f109551bd432803012645ac136ddd64dba72"); //_result:
getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36"); //_result:
// Throws an error if the ICAP checksum is wrong getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK37"); //_error:
function getIndexedAccountPath
getIndexedAccountPath: (_index: Numeric) => string;
Returns the path using an alternative pattern for deriving accounts, at %%index%%.
This derivation path uses the //index// component rather than the //account// component to derive sequential accounts.
This is the pattern used by wallets like MetaMask.
function getNumber
getNumber: (value: BigNumberish, name?: string) => number;
Gets a //number// from %%value%%. If it is an invalid value for a //number//, then an ArgumentError will be thrown for %%name%%.
function getUint
getUint: (value: BigNumberish, name?: string) => bigint;
Returns %%value%% as a bigint, validating it is valid as a bigint value and that it is positive.
function hashMessage
hashMessage: (message: Uint8Array | string) => string;
Computes the [[link-eip-191]] personal-sign message digest to sign.
This prefixes the message with [[MessagePrefix]] and the decimal length of %%message%% and computes the [[keccak256]] digest.
If %%message%% is a string, it is converted to its UTF-8 bytes first. To compute the digest of a [[DataHexString]], it must be converted to [bytes](getBytes).
@example: hashMessage("Hello World") //_result:
// Hashes the SIX (6) string characters, i.e. // [ "0", "x", "4", "2", "4", "3" ] hashMessage("0x4243") //_result:
// Hashes the TWO (2) bytes [ 0x42, 0x43 ]... hashMessage(getBytes("0x4243")) //_result:
// ...which is equal to using data hashMessage(new Uint8Array([ 0x42, 0x43 ])) //_result:
function hexlify
hexlify: (data: BytesLike) => string;
Returns a [[DataHexString]] representation of %%data%%.
function id
id: (value: string) => string;
A simple hashing function which operates on UTF-8 strings to compute an 32-byte identifier.
This simply computes the [UTF-8 bytes](toUtf8Bytes) and computes the [[keccak256]].
@example: id("hello world") //_result:
function isAddress
isAddress: (value: any) => value is string;
Returns true if %%value%% is a valid address.
@example: // Valid address isAddress("0x8ba1f109551bD432803012645Ac136ddd64DBA72") //_result:
// Valid ICAP address isAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36") //_result:
// Invalid checksum isAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBa72") //_result:
// Invalid ICAP checksum isAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72") //_result:
// Not an address (an ENS name requires a provided and an // asynchronous API to access) isAddress("ricmoo.eth") //_result:
function isAddressable
isAddressable: (value: any) => value is Addressable;
Returns true if %%value%% is an object which implements the [[Addressable]] interface.
@example: // Wallets and AbstractSigner sub-classes isAddressable(Wallet.createRandom()) //_result:
// Contracts contract = new Contract("dai.tokens.ethers.eth", [ ], provider) isAddressable(contract) //_result:
function isBytesLike
isBytesLike: (value: any) => value is BytesLike;
Returns true if %%value%% is a valid representation of arbitrary data (i.e. a valid [[DataHexString]] or a Uint8Array).
function isCallException
isCallException: (error: any) => error is CallExceptionError;
Returns true if %%error%% is a [[CallExceptionError].
function isCrowdsaleJson
isCrowdsaleJson: (json: string) => boolean;
Returns true if %%json%% is a valid JSON Crowdsale wallet.
function isError
isError: <K extends ErrorCode, T extends CodedEthersError<K>>( error: any, code: K) => error is T;
Returns true if the %%error%% matches an error thrown by ethers that matches the error %%code%%.
In TypeScript environments, this can be used to check that %%error%% matches an EthersError type, which means the expected properties will be set.
Example 1
try { // code.... } catch (e) { if (isError(e, "CALL_EXCEPTION")) { // The Type Guard has validated this object console.log(e.data); } }
See Also
[ErrorCodes](api:ErrorCode)
function isHexString
isHexString: (value: any, length?: number | boolean) => value is `0x${string}`;
Returns true if %%value%% is a valid [[HexString]].
If %%length%% is ``true`` or a //number//, it also checks that %%value%% is a valid [[DataHexString]] of %%length%% (if a //number//) bytes of data (e.g. ``0x1234`` is 2 bytes).
function isKeystoreJson
isKeystoreJson: (json: string) => boolean;
Returns true if %%json%% is a valid JSON Keystore Wallet.
function isValidName
isValidName: (name: string) => name is string;
Returns ``true`` if %%name%% is a valid ENS name.
function keccak256
keccak256: typeof keccak256;
Compute the cryptographic KECCAK256 hash of %%data%%.
The %%data%% **must** be a data representation, to compute the hash of UTF-8 data use the [[id]] function.
Returns
DataHexstring @example: keccak256("0x") //_result:
keccak256("0x1337") //_result:
keccak256(new Uint8Array([ 0x13, 0x37 ])) //_result:
// Strings are assumed to be DataHexString, otherwise it will // throw. To hash UTF-8 data, see the note above. keccak256("Hello World") //_error:
function lock
lock: () => void;
Once called, prevents any future change to the underlying cryptographic primitives using the ``.register`` feature for hooks.
function makeError
makeError: <K extends ErrorCode, T extends CodedEthersError<K>>( message: string, code: K, info?: ErrorInfo<T>) => T;
Returns a new Error configured to the format ethers emits errors, with the %%message%%, [[api:ErrorCode]] %%code%% and additional properties for the corresponding EthersError.
Each error in ethers includes the version of ethers, a machine-readable [[ErrorCode]], and depending on %%code%%, additional required properties. The error message will also include the %%message%%, ethers version, %%code%% and all additional properties, serialized.
function mask
mask: (_value: BigNumberish, _bits: Numeric) => bigint;
Mask %%value%% with a bitmask of %%bits%% ones.
function namehash
namehash: (name: string) => string;
Returns the [[link-namehash]] for %%name%%.
function parseEther
parseEther: (ether: string) => bigint;
Converts the //decimal string// %%ether%% to a BigInt, using 18 decimal places.
function parseUnits
parseUnits: (value: string, unit?: string | Numeric) => bigint;
Converts the //decimal string// %%value%% to a BigInt, assuming %%unit%% decimal places. The %%unit%% may the number of decimal places or the name of a unit (e.g. ``"gwei"`` for 9 decimal places).
function pbkdf2
pbkdf2: typeof pbkdf2;
Return the [[link-pbkdf2]] for %%keylen%% bytes for %%password%% using the %%salt%% and using %%iterations%% of %%algo%%.
This PBKDF is outdated and should not be used in new projects, but is required to decrypt older files.
@example: // The password must be converted to bytes, and it is generally // best practices to ensure the string has been normalized. Many // formats explicitly indicate the normalization form to use. password = "hello" passwordBytes = toUtf8Bytes(password, "NFKC")
salt = id("some-salt")
// Compute the PBKDF2 pbkdf2(passwordBytes, salt, 1024, 16, "sha256") //_result:
function randomBytes
randomBytes: typeof randomBytes;
Return %%length%% bytes of cryptographically secure random data.
@example: randomBytes(8) //_result:
function recoverAddress
recoverAddress: (digest: BytesLike, signature: SignatureLike) => string;
Returns the recovered address for the private key that was used to sign %%digest%% that resulted in %%signature%%.
function resolveAddress
resolveAddress: ( target: AddressLike, resolver?: null | NameResolver) => string | Promise<string>;
Resolves to an address for the %%target%%, which may be any supported address type, an [[Addressable]] or a Promise which resolves to an address.
If an ENS name is provided, but that name has not been correctly configured a [[UnconfiguredNameError]] is thrown.
@example: addr = "0x6B175474E89094C44Da98b954EedeAC495271d0F"
// Addresses are return synchronously resolveAddress(addr, provider) //_result:
// Address promises are resolved asynchronously resolveAddress(Promise.resolve(addr)) //_result:
// ENS names are resolved asynchronously resolveAddress("dai.tokens.ethers.eth", provider) //_result:
// Addressable objects are resolved asynchronously contract = new Contract(addr, [ ]) resolveAddress(contract, provider) //_result:
// Unconfigured ENS names reject resolveAddress("nothing-here.ricmoo.eth", provider) //_error:
// ENS names require a NameResolver object passed in // (notice the provider was omitted) resolveAddress("nothing-here.ricmoo.eth") //_error:
function resolveProperties
resolveProperties: <T>(value: { [P in keyof T]: T[P] | Promise<T[P]>;}) => Promise<T>;
Resolves to a new object that is a copy of %%value%%, but with all values resolved.
function ripemd160
ripemd160: typeof ripemd160;
Compute the cryptographic RIPEMD-160 hash of %%data%%.
@_docloc: api/crypto:Hash Functions
Returns
DataHexstring
@example: ripemd160("0x") //_result:
ripemd160("0x1337") //_result:
ripemd160(new Uint8Array([ 0x13, 0x37 ])) //_result:
function scrypt
scrypt: typeof scrypt;
The [[link-wiki-scrypt]] uses a memory and cpu hard method of derivation to increase the resource cost to brute-force a password for a given key.
This means this algorithm is intentionally slow, and can be tuned to become slower. As computation and memory speed improve over time, increasing the difficulty maintains the cost of an attacker.
For example, if a target time of 5 seconds is used, a legitimate user which knows their password requires only 5 seconds to unlock their account. A 6 character password has 68 billion possibilities, which would require an attacker to invest over 10,000 years of CPU time. This is of course a crude example (as password generally aren't random), but demonstrates to value of imposing large costs to decryption.
For this reason, if building a UI which involved decrypting or encrypting datsa using scrypt, it is recommended to use a [[ProgressCallback]] (as event short periods can seem lik an eternity if the UI freezes). Including the phrase //"decrypting"// in the UI can also help, assuring the user their waiting is for a good reason.
@_docloc: api/crypto:Passwords
@example: // The password must be converted to bytes, and it is generally // best practices to ensure the string has been normalized. Many // formats explicitly indicate the normalization form to use. password = "hello" passwordBytes = toUtf8Bytes(password, "NFKC")
salt = id("some-salt")
// Compute the scrypt scrypt(passwordBytes, salt, 1024, 8, 1, 16) //_result:
function scryptSync
scryptSync: typeof scryptSync;
Provides a synchronous variant of [[scrypt]].
This will completely lock up and freeze the UI in a browser and will prevent any event loop from progressing. For this reason, it is preferred to use the [async variant](scrypt).
@_docloc: api/crypto:Passwords
@example: // The password must be converted to bytes, and it is generally // best practices to ensure the string has been normalized. Many // formats explicitly indicate the normalization form to use. password = "hello" passwordBytes = toUtf8Bytes(password, "NFKC")
salt = id("some-salt")
// Compute the scrypt scryptSync(passwordBytes, salt, 1024, 8, 1, 16) //_result:
function sha256
sha256: typeof sha256;
Compute the cryptographic SHA2-256 hash of %%data%%.
@_docloc: api/crypto:Hash Functions
Returns
DataHexstring
@example: sha256("0x") //_result:
sha256("0x1337") //_result:
sha256(new Uint8Array([ 0x13, 0x37 ])) //_result:
function sha512
sha512: typeof sha512;
Compute the cryptographic SHA2-512 hash of %%data%%.
@_docloc: api/crypto:Hash Functions
Returns
DataHexstring
@example: sha512("0x") //_result:
sha512("0x1337") //_result:
sha512(new Uint8Array([ 0x13, 0x37 ])) //_result:
function showThrottleMessage
showThrottleMessage: (service: string) => void;
Displays a warning in tht console when the community resource is being used too heavily by the app, recommending the developer acquire their own credentials instead of using the community credentials.
The notification will only occur once per service.
function solidityPacked
solidityPacked: ( types: ReadonlyArray<string>, values: ReadonlyArray<any>) => string;
Computes the [[link-solc-packed]] representation of %%values%% respectively to their %%types%%.
@example: addr = "0x8ba1f109551bd432803012645ac136ddd64dba72" solidityPacked([ "address", "uint" ], [ addr, 45 ]); //_result:
function solidityPackedKeccak256
solidityPackedKeccak256: ( types: ReadonlyArray<string>, values: ReadonlyArray<any>) => string;
Computes the [[link-solc-packed]] [[keccak256]] hash of %%values%% respectively to their %%types%%.
@example: addr = "0x8ba1f109551bd432803012645ac136ddd64dba72" solidityPackedKeccak256([ "address", "uint" ], [ addr, 45 ]); //_result:
function solidityPackedSha256
solidityPackedSha256: ( types: ReadonlyArray<string>, values: ReadonlyArray<any>) => string;
Computes the [[link-solc-packed]] [[sha256]] hash of %%values%% respectively to their %%types%%.
@example: addr = "0x8ba1f109551bd432803012645ac136ddd64dba72" solidityPackedSha256([ "address", "uint" ], [ addr, 45 ]); //_result:
function stripZerosLeft
stripZerosLeft: (data: BytesLike) => string;
Return the [[DataHexString]] result by stripping all **leading** * zero bytes from %%data%%.
function toBeArray
toBeArray: (_value: BigNumberish) => Uint8Array;
Converts %%value%% to a Big Endian Uint8Array.
function toBeHex
toBeHex: (_value: BigNumberish, _width?: Numeric) => string;
Converts %%value%% to a Big Endian hexstring, optionally padded to %%width%% bytes.
function toBigInt
toBigInt: (value: BigNumberish | Uint8Array) => bigint;
function toNumber
toNumber: (value: BigNumberish | Uint8Array) => number;
Converts %%value%% to a number. If %%value%% is a Uint8Array, it is treated as Big Endian data. Throws if the value is not safe.
function toQuantity
toQuantity: (value: BytesLike | BigNumberish) => string;
Returns a [[HexString]] for %%value%% safe to use as a //Quantity//.
A //Quantity// does not have and leading 0 values unless the value is the literal value
0x0
. This is most commonly used for JSSON-RPC numeric values.
function toTwos
toTwos: (_value: BigNumberish, _width: Numeric) => bigint;
Convert %%value%% to a twos-compliment representation of %%width%% bits.
The result will always be positive.
function toUtf8Bytes
toUtf8Bytes: (str: string, form?: UnicodeNormalizationForm) => Uint8Array;
Returns the UTF-8 byte representation of %%str%%.
If %%form%% is specified, the string is normalized.
function toUtf8CodePoints
toUtf8CodePoints: ( str: string, form?: UnicodeNormalizationForm) => Array<number>;
Returns the UTF-8 code-points for %%str%%.
If %%form%% is specified, the string is normalized.
function toUtf8String
toUtf8String: (bytes: BytesLike, onError?: Utf8ErrorFunc) => string;
Returns the string represented by the UTF-8 data %%bytes%%.
When %%onError%% function is specified, it is called on UTF-8 errors allowing recovery using the [[Utf8ErrorFunc]] API. (default: [error](Utf8ErrorFuncs))
function uuidV4
uuidV4: (randomBytes: BytesLike) => string;
Returns the version 4 [[link-uuid]] for the %%randomBytes%%.
@see: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)
function verifyMessage
verifyMessage: (message: Uint8Array | string, sig: SignatureLike) => string;
Return the address of the private key that produced the signature %%sig%% during signing for %%message%%.
function verifyTypedData
verifyTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>, signature: SignatureLike) => string;
Compute the address used to sign the typed data for the %%signature%%.
function zeroPadBytes
zeroPadBytes: (data: BytesLike, length: number) => string;
Return the [[DataHexString]] of %%data%% padded on the **right** to %%length%% bytes.
If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is thrown.
This pads data the same as **bytes** are in Solidity (e.g. ``bytes16``).
function zeroPadValue
zeroPadValue: (data: BytesLike, length: number) => string;
Return the [[DataHexString]] of %%data%% padded on the **left** to %%length%% bytes.
If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is thrown.
This pads data the same as **values** are in Solidity (e.g. ``uint128``).
class AbiCoder
class AbiCoder {}
The **AbiCoder** is a low-level class responsible for encoding JavaScript values into binary data and decoding binary data into JavaScript values.
method decode
decode: ( types: ReadonlyArray<string | ParamType>, data: BytesLike, loose?: boolean) => Result;
Decode the ABI %%data%% as the %%types%% into values.
If %%loose%% decoding is enabled, then strict padding is not enforced. Some older versions of Solidity incorrectly padded event data emitted from ``external`` functions.
method defaultAbiCoder
static defaultAbiCoder: () => AbiCoder;
Returns the shared singleton instance of a default [[AbiCoder]].
On the first call, the instance is created internally.
method encode
encode: ( types: ReadonlyArray<string | ParamType>, values: ReadonlyArray<any>) => string;
Encode the %%values%% as the %%types%% into ABI data.
Returns
DataHexstring
method getBuiltinCallException
static getBuiltinCallException: ( action: CallExceptionAction, tx: { to?: null | string; from?: null | string; data?: string }, data: null | BytesLike) => CallExceptionError;
Returns an ethers-compatible [[CallExceptionError]] Error for the given result %%data%% for the [[CallExceptionAction]] %%action%% against the Transaction %%tx%%.
method getDefaultValue
getDefaultValue: (types: ReadonlyArray<string | ParamType>) => Result;
Get the default values for the given %%types%%.
For example, a ``uint`` is by default ``0`` and ``bool`` is by default ``false``.
class AbstractProvider
class AbstractProvider implements Provider {}
An **AbstractProvider** provides a base class for other sub-classes to implement the [[Provider]] API by normalizing input arguments and formatting output results as well as tracking events for consistent behaviour on an eventually-consistent network.
constructor
constructor(_network?: Networkish, options?: AbstractProviderOptions);
Create a new **AbstractProvider** connected to %%network%%, or use the various network detection capabilities to discover the [[Network]] if necessary.
property destroyed
readonly destroyed: boolean;
If this provider has been destroyed using the [[destroy]] method.
Once destroyed, all resources are reclaimed, internal event loops and timers are cleaned up and no further requests may be sent to the provider.
property disableCcipRead
disableCcipRead: boolean;
Prevent any CCIP-read operation, regardless of whether requested in a [[call]] using ``enableCcipRead``.
property paused
paused: boolean;
Whether the provider is currently paused.
A paused provider will not emit any events, and generally should not make any requests to the network, but that is up to sub-classes to manage.
Setting ``paused = true`` is identical to calling ``.pause(false)``, which will buffer any events that occur while paused until the provider is unpaused.
property plugins
readonly plugins: AbstractProviderPlugin[];
Returns all the registered plug-ins.
property pollingInterval
readonly pollingInterval: number;
property provider
readonly provider: AbstractProvider;
Returns ``this``, to allow an **AbstractProvider** to implement the [[ContractRunner]] interface.
method addListener
addListener: (event: ProviderEvent, listener: Listener) => Promise<this>;
method attachPlugin
attachPlugin: (plugin: AbstractProviderPlugin) => this;
Attach a new plug-in.
method broadcastTransaction
broadcastTransaction: (signedTx: string) => Promise<TransactionResponse>;
method call
call: (_tx: TransactionRequest) => Promise<string>;
method ccipReadFetch
ccipReadFetch: ( tx: PerformActionTransaction, calldata: string, urls: Array<string>) => Promise<null | string>;
Resolves to the data for executing the CCIP-read operations.
method destroy
destroy: () => void;
Sub-classes may use this to shutdown any sockets or release their resources and reject any pending requests.
Sub-classes **must** call ``super.destroy()``.
method emit
emit: (event: ProviderEvent, ...args: Array<any>) => Promise<boolean>;
method estimateGas
estimateGas: (_tx: TransactionRequest) => Promise<bigint>;
method getAvatar
getAvatar: (name: string) => Promise<null | string>;
method getBalance
getBalance: (address: AddressLike, blockTag?: BlockTag) => Promise<bigint>;
method getBlock
getBlock: ( block: BlockTag | string, prefetchTxs?: boolean) => Promise<null | Block>;
method getBlockNumber
getBlockNumber: () => Promise<number>;
method getCode
getCode: (address: AddressLike, blockTag?: BlockTag) => Promise<string>;
method getFeeData
getFeeData: () => Promise<FeeData>;
method getLogs
getLogs: (_filter: Filter | FilterByBlockHash) => Promise<Array<Log>>;
method getNetwork
getNetwork: () => Promise<Network>;
method getPlugin
getPlugin: <T extends AbstractProviderPlugin = AbstractProviderPlugin>( name: string) => null | T;
Get a plugin by name.
method getResolver
getResolver: (name: string) => Promise<null | EnsResolver>;
method getStorage
getStorage: ( address: AddressLike, _position: BigNumberish, blockTag?: BlockTag) => Promise<string>;
method getTransaction
getTransaction: (hash: string) => Promise<null | TransactionResponse>;
method getTransactionCount
getTransactionCount: ( address: AddressLike, blockTag?: BlockTag) => Promise<number>;
method getTransactionReceipt
getTransactionReceipt: (hash: string) => Promise<null | TransactionReceipt>;
method getTransactionResult
getTransactionResult: (hash: string) => Promise<null | string>;
method listenerCount
listenerCount: (event?: ProviderEvent) => Promise<number>;
method listeners
listeners: (event?: ProviderEvent) => Promise<Array<Listener>>;
method lookupAddress
lookupAddress: (address: string) => Promise<null | string>;
method off
off: (event: ProviderEvent, listener?: Listener) => Promise<this>;
method on
on: (event: ProviderEvent, listener: Listener) => Promise<this>;
method once
once: (event: ProviderEvent, listener: Listener) => Promise<this>;
method pause
pause: (dropWhilePaused?: boolean) => void;
Pause the provider. If %%dropWhilePaused%%, any events that occur while paused are dropped, otherwise all events will be emitted once the provider is unpaused.
method removeAllListeners
removeAllListeners: (event?: ProviderEvent) => Promise<this>;
method removeListener
removeListener: (event: ProviderEvent, listener: Listener) => Promise<this>;
method resolveName
resolveName: (name: string) => Promise<null | string>;
method resume
resume: () => void;
Resume the provider.
method waitForBlock
waitForBlock: (blockTag?: BlockTag) => Promise<Block>;
method waitForTransaction
waitForTransaction: ( hash: string, _confirms?: null | number, timeout?: null | number) => Promise<null | TransactionReceipt>;
class AbstractSigner
abstract class AbstractSigner<P extends null | Provider = null | Provider> implements Signer {}
An **AbstractSigner** includes most of teh functionality required to get a [[Signer]] working as expected, but requires a few Signer-specific methods be overridden.
constructor
constructor(provider?: Provider);
Creates a new Signer connected to %%provider%%.
property provider
readonly provider: Provider;
The provider this signer is connected to.
method call
call: (tx: TransactionRequest) => Promise<string>;
method connect
abstract connect: (provider: null | Provider) => Signer;
Returns the signer connected to %%provider%%.
This may throw, for example, a Signer connected over a Socket or to a specific instance of a node may not be transferrable.
method estimateGas
estimateGas: (tx: TransactionRequest) => Promise<bigint>;
method getAddress
abstract getAddress: () => Promise<string>;
Resolves to the Signer address.
method getNonce
getNonce: (blockTag?: BlockTag) => Promise<number>;
method populateCall
populateCall: (tx: TransactionRequest) => Promise<TransactionLike<string>>;
method populateTransaction
populateTransaction: ( tx: TransactionRequest) => Promise<TransactionLike<string>>;
method resolveName
resolveName: (name: string) => Promise<null | string>;
method sendTransaction
sendTransaction: (tx: TransactionRequest) => Promise<TransactionResponse>;
method signMessage
abstract signMessage: (message: string | Uint8Array) => Promise<string>;
method signTransaction
abstract signTransaction: (tx: TransactionRequest) => Promise<string>;
method signTypedData
abstract signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => Promise<string>;
class AlchemyProvider
class AlchemyProvider extends JsonRpcProvider implements CommunityResourcable {}
The **AlchemyProvider** connects to the [[link-alchemy]] JSON-RPC end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-alchemy-signup).
@_docloc: api/providers/thirdparty
constructor
constructor(_network?: Networkish, apiKey?: string);
property apiKey
readonly apiKey: string;
method getRequest
static getRequest: (network: Network, apiKey?: string) => FetchRequest;
method isCommunityResource
isCommunityResource: () => boolean;
class AnkrProvider
class AnkrProvider extends JsonRpcProvider implements CommunityResourcable {}
The **AnkrProvider** connects to the [[link-ankr]] JSON-RPC end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-ankr-signup).
constructor
constructor(_network?: Networkish, apiKey?: string);
Create a new **AnkrProvider**.
By default connecting to ``mainnet`` with a highly throttled API key.
property apiKey
readonly apiKey: string;
The API key for the Ankr connection.
method getRequest
static getRequest: (network: Network, apiKey?: null | string) => FetchRequest;
Returns a prepared request for connecting to %%network%% with %%apiKey%%.
method getRpcError
getRpcError: (payload: JsonRpcPayload, error: JsonRpcError) => Error;
method isCommunityResource
isCommunityResource: () => boolean;
class BaseContract
class BaseContract implements Addressable, EventEmitterable<ContractEventName> {}
constructor
constructor( target: string | Addressable, abi: InterfaceAbi | Interface, runner?: ContractRunner, _deployTx?: TransactionResponse);
Creates a new contract connected to %%target%% with the %%abi%% and optionally connected to a %%runner%% to perform operations on behalf of.
property [internal]
readonly [internal]: any;
@_ignore:
property fallback
readonly fallback: WrappedFallback;
The fallback or receive function if any.
property filters
readonly filters: Record<string, ContractEvent<any[]>>;
All the Events available on this contract.
property interface
readonly interface: Interface;
The contract Interface.
property runner
readonly runner: ContractRunner;
The connected runner. This is generally a [[Provider]] or a [[Signer]], which dictates what operations are supported.
For example, a **Contract** connected to a [[Provider]] may only execute read-only operations.
property target
readonly target: string | Addressable;
The target to connect to.
This can be an address, ENS name or any [[Addressable]], such as another contract. To get the resovled address, use the ``getAddress`` method.
method addListener
addListener: (event: ContractEventName, listener: Listener) => Promise<this>;
Alias for [on].
method attach
attach: (target: string | Addressable) => BaseContract;
Return a new Contract instance with the same ABI and runner, but a different %%target%%.
method buildClass
static buildClass: <T = ContractInterface>( abi: Interface | InterfaceAbi) => new (target: string, runner?: null | ContractRunner) => BaseContract & Omit<T, keyof BaseContract>;
Create a new Class for the %%abi%%.
method connect
connect: (runner: null | ContractRunner) => BaseContract;
Return a new Contract instance with the same target and ABI, but a different %%runner%%.
method deploymentTransaction
deploymentTransaction: () => null | ContractTransactionResponse;
Return the transaction used to deploy this contract.
This is only available if this instance was returned from a [[ContractFactory]].
method emit
emit: (event: ContractEventName, ...args: Array<any>) => Promise<boolean>;
Emit an %%event%% calling all listeners with %%args%%.
Resolves to ``true`` if any listeners were called.
method from
static from: <T = ContractInterface>( target: string, abi: Interface | InterfaceAbi, runner?: null | ContractRunner) => BaseContract & Omit<T, keyof BaseContract>;
Create a new BaseContract with a specified Interface.
method getAddress
getAddress: () => Promise<string>;
Return the resolved address of this Contract.
method getDeployedCode
getDeployedCode: () => Promise<null | string>;
Return the deployed bytecode or null if no bytecode is found.
method getEvent
getEvent: (key: string | EventFragment) => ContractEvent;
Return the event for a given name. This is useful when a contract event name conflicts with a JavaScript name such as ``prototype`` or when using a Contract programatically.
method getFunction
getFunction: < T extends ContractMethod<any[], any, any> = ContractMethod<any[], any, any>>( key: string | FunctionFragment) => T;
Return the function for a given name. This is useful when a contract method name conflicts with a JavaScript name such as ``prototype`` or when using a Contract programatically.
method listenerCount
listenerCount: (event?: ContractEventName) => Promise<number>;
Resolves to the number of listeners of %%event%% or the total number of listeners if unspecified.
method listeners
listeners: (event?: ContractEventName) => Promise<Array<Listener>>;
Resolves to the listeners subscribed to %%event%% or all listeners if unspecified.
method off
off: (event: ContractEventName, listener?: Listener) => Promise<this>;
Remove the %%listener%% from the listeners for %%event%% or remove all listeners if unspecified.
method on
on: (event: ContractEventName, listener: Listener) => Promise<this>;
Add an event %%listener%% for the %%event%%.
method once
once: (event: ContractEventName, listener: Listener) => Promise<this>;
Add an event %%listener%% for the %%event%%, but remove the listener after it is fired once.
method queryFilter
queryFilter: ( event: ContractEventName, fromBlock?: BlockTag, toBlock?: BlockTag) => Promise<Array<EventLog | Log>>;
Provide historic access to event data for %%event%% in the range %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``) inclusive.
method queryTransaction
queryTransaction: (hash: string) => Promise<Array<EventLog>>;
@_ignore:
method removeAllListeners
removeAllListeners: (event?: ContractEventName) => Promise<this>;
Remove all the listeners for %%event%% or remove all listeners if unspecified.
method removeListener
removeListener: (event: ContractEventName, listener: Listener) => Promise<this>;
Alias for [off].
method waitForDeployment
waitForDeployment: () => Promise<this>;
Resolve to this Contract once the bytecode has been deployed, or resolve immediately if already deployed.
class BaseWallet
class BaseWallet extends AbstractSigner {}
The **BaseWallet** is a stream-lined implementation of a [[Signer]] that operates with a private key.
It is preferred to use the [[Wallet]] class, as it offers additional functionality and simplifies loading a variety of JSON formats, Mnemonic Phrases, etc.
This class may be of use for those attempting to implement a minimal Signer.
constructor
constructor(privateKey: SigningKey, provider?: Provider);
Creates a new BaseWallet for %%privateKey%%, optionally connected to %%provider%%.
If %%provider%% is not specified, only offline methods can be used.
property address
readonly address: string;
The wallet address.
property privateKey
readonly privateKey: string;
The private key for this wallet.
property signingKey
readonly signingKey: SigningKey;
The [[SigningKey]] used for signing payloads.
method connect
connect: (provider: null | Provider) => BaseWallet;
method getAddress
getAddress: () => Promise<string>;
method signMessage
signMessage: (message: string | Uint8Array) => Promise<string>;
method signMessageSync
signMessageSync: (message: string | Uint8Array) => string;
Returns the signature for %%message%% signed with this wallet.
method signTransaction
signTransaction: (tx: TransactionRequest) => Promise<string>;
method signTypedData
signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => Promise<string>;
class Block
class Block implements BlockParams, Iterable<string> {}
A **Block** represents the data associated with a full block on Ethereum.
constructor
constructor(block: BlockParams, provider: Provider);
Create a new **Block** object.
This should generally not be necessary as the unless implementing a low-level library.
property baseFeePerGas
readonly baseFeePerGas: BigInt;
The base fee per gas that all transactions in this block were charged.
This adjusts after each block, depending on how congested the network is.
property blobGasUsed
readonly blobGasUsed: BigInt;
The total amount of blob gas consumed by the transactions within the block. See [[link-eip-4844]].
property date
readonly date: Date;
The [[link-js-date]] this block was included at.
property difficulty
readonly difficulty: BigInt;
The difficulty target.
On legacy networks, this is the proof-of-work target required for a block to meet the protocol rules to be included.
On modern networks, this is a random number arrived at using randao. @TODO: Find links?
property excessBlobGas
readonly excessBlobGas: BigInt;
The running total of blob gas consumed in excess of the target, prior to the block. See [[link-eip-4844]].
property extraData
readonly extraData: string;
Any extra data the validator wished to include.
property gasLimit
readonly gasLimit: BigInt;
The total gas limit for this block.
property gasUsed
readonly gasUsed: BigInt;
The total gas used in this block.
property hash
readonly hash: string;
The block hash.
This hash includes all properties, so can be safely used to identify an exact set of block properties.
property length
readonly length: number;
The number of transactions in this block.
property miner
readonly miner: string;
The miner coinbase address, wihch receives any subsidies for including this block.
property nonce
readonly nonce: string;
The nonce.
On legacy networks, this is the random number inserted which permitted the difficulty target to be reached.
property number
readonly number: number;
The block number, sometimes called the block height. This is a sequential number that is one higher than the parent block.
property parentBeaconBlockRoot
parentBeaconBlockRoot: string;
The hash tree root of the parent beacon block for the given execution block. See [[link-eip-4788]].
property parentHash
readonly parentHash: string;
The block hash of the parent block.
property prefetchedTransactions
readonly prefetchedTransactions: TransactionResponse[];
Returns the complete transactions, in the order they were executed within the block.
This is only available for blocks which prefetched transactions, by passing ``true`` to %%prefetchTxs%% into [[Provider-getBlock]].
property prevRandao
readonly prevRandao: string;
The latest RANDAO mix of the post beacon state of the previous block.
property provider
readonly provider: Provider;
The provider connected to the block used to fetch additional details if necessary.
property receiptsRoot
readonly receiptsRoot: string;
The hash of the transaction receipts trie.
property stateRoot
readonly stateRoot: string;
The root hash for the global state after applying changes in this block.
property timestamp
readonly timestamp: number;
The timestamp for this block, which is the number of seconds since epoch that this block was included.
property transactions
readonly transactions: readonly string[];
Returns the list of transaction hashes, in the order they were executed within the block.
method [Symbol.iterator]
[Symbol.iterator]: () => Iterator<string>;
method getPrefetchedTransaction
getPrefetchedTransaction: (indexOrHash: number | string) => TransactionResponse;
If a **Block** was fetched with a request to include the transactions this will allow synchronous access to those transactions.
If the transactions were not prefetched, this will throw.
method getTransaction
getTransaction: (indexOrHash: number | string) => Promise<TransactionResponse>;
Get the transaction at %%indexe%% within this block.
method isLondon
isLondon: () => this is Block & { baseFeePerGas: bigint };
Returns true if this block is an [[link-eip-2930]] block.
method isMined
isMined: () => this is MinedBlock;
Returns true if this block been mined. This provides a type guard for all properties on a [[MinedBlock]].
method orphanedEvent
orphanedEvent: () => OrphanFilter;
@_ignore:
method toJSON
toJSON: () => any;
Returns a JSON-friendly value.
class BrowserProvider
class BrowserProvider extends JsonRpcApiPollingProvider {}
A **BrowserProvider** is intended to wrap an injected provider which adheres to the [[link-eip-1193]] standard, which most (if not all) currently do.
constructor
constructor( ethereum: Eip1193Provider, network?: Networkish, _options?: BrowserProviderOptions);
Connect to the %%ethereum%% provider, optionally forcing the %%network%%.
method getRpcError
getRpcError: (payload: JsonRpcPayload, error: JsonRpcError) => Error;
method getSigner
getSigner: (address?: number | string) => Promise<JsonRpcSigner>;
method hasSigner
hasSigner: (address: number | string) => Promise<boolean>;
Resolves to ``true`` if the provider manages the %%address%%.
method send
send: (method: string, params: Array<any> | Record<string, any>) => Promise<any>;
class ChainstackProvider
class ChainstackProvider extends JsonRpcProvider implements CommunityResourcable {}
The **ChainstackProvider** connects to the [[link-chainstack]] JSON-RPC end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-chainstack).
constructor
constructor(_network?: Networkish, apiKey?: string);
Creates a new **ChainstackProvider**.
property apiKey
readonly apiKey: string;
The API key for the Chainstack connection.
method getRequest
static getRequest: (network: Network, apiKey?: null | string) => FetchRequest;
Returns a prepared request for connecting to %%network%% with %%apiKey%% and %%projectSecret%%.
method isCommunityResource
isCommunityResource: () => boolean;
class CloudflareProvider
class CloudflareProvider extends JsonRpcProvider {}
About Cloudflare...
constructor
constructor(_network?: Networkish);
class ConstructorFragment
class ConstructorFragment extends Fragment {}
A Fragment which represents a constructor.
constructor
constructor( guard: any, type: FragmentType, inputs: readonly ParamType[], payable: boolean, gas: BigInt);
property gas
readonly gas: BigInt;
The recommended gas limit for deployment or ``null``.
property payable
readonly payable: boolean;
Whether the constructor can receive an endowment.
method format
format: (format?: FormatType) => string;
Returns a string representation of this constructor as %%format%%.
method from
static from: (obj: any) => ConstructorFragment;
Returns a new **ConstructorFragment** for %%obj%%.
method isFragment
static isFragment: (value: any) => value is ConstructorFragment;
Returns ``true`` and provides a type guard if %%value%% is a **ConstructorFragment**.
class Contract
class Contract extends Contract_base {}
A [[BaseContract]] with no type guards on its methods or events.
class ContractEventPayload
class ContractEventPayload extends ContractUnknownEventPayload {}
A **ContractEventPayload** is included as the last parameter to Contract Events when the event is known.
constructor
constructor( contract: BaseContract, listener: Listener, filter: ContractEventName, fragment: EventFragment, _log: Log);
@_ignore:
property args
readonly args: Result;
The parsed arguments passed to the event by ``emit``.
property eventName
readonly eventName: string;
The event name.
property eventSignature
readonly eventSignature: string;
The event signature.
property fragment
readonly fragment: EventFragment;
The matching event.
property log
readonly log: EventLog;
The log, with parsed properties.
class ContractFactory
class ContractFactory<A extends Array<any> = Array<any>, I = BaseContract> {}
A **ContractFactory** is used to deploy a Contract to the blockchain.
constructor
constructor( abi: InterfaceAbi | Interface, bytecode: BytesLike | { object: string }, runner?: ContractRunner);
Create a new **ContractFactory** with %%abi%% and %%bytecode%%, optionally connected to %%runner%%.
The %%bytecode%% may be the ``bytecode`` property within the standard Solidity JSON output.
property bytecode
readonly bytecode: string;
The Contract deployment bytecode. Often called the initcode.
property interface
readonly interface: Interface;
The Contract Interface.
property runner
readonly runner: ContractRunner;
The ContractRunner to deploy the Contract as.
method attach
attach: ( target: string | Addressable) => BaseContract & Omit<I, keyof BaseContract>;
method connect
connect: (runner: null | ContractRunner) => ContractFactory<A, I>;
Return a new **ContractFactory** with the same ABI and bytecode, but connected to %%runner%%.
method deploy
deploy: ( ...args: ContractMethodArgs<A>) => Promise< BaseContract & { deploymentTransaction(): ContractTransactionResponse; } & Omit<I, keyof BaseContract>>;
Resolves to the Contract deployed by passing %%args%% into the constructor.
This will resolve to the Contract before it has been deployed to the network, so the [[BaseContract-waitForDeployment]] should be used before sending any transactions to it.
method fromSolidity
static fromSolidity: <A extends any[] = any[], I = ContractInterface>( output: any, runner?: ContractRunner) => ContractFactory<A, I>;
Create a new **ContractFactory** from the standard Solidity JSON output.
method getDeployTransaction
getDeployTransaction: ( ...args: ContractMethodArgs<A>) => Promise<ContractDeployTransaction>;
Resolves to the transaction to deploy the contract, passing %%args%% into the constructor.
class ContractTransactionReceipt
class ContractTransactionReceipt extends TransactionReceipt {}
A **ContractTransactionReceipt** includes the parsed logs from a [[TransactionReceipt]].
constructor
constructor(iface: Interface, provider: Provider, tx: TransactionReceipt);
@_ignore:
property logs
readonly logs: (EventLog | Log)[];
The parsed logs for any [[Log]] which has a matching event in the Contract ABI.
class ContractTransactionResponse
class ContractTransactionResponse extends TransactionResponse {}
A **ContractTransactionResponse** will return a [[ContractTransactionReceipt]] when waited on.
constructor
constructor(iface: Interface, provider: Provider, tx: TransactionResponse);
@_ignore:
method wait
wait: ( confirms?: number, timeout?: number) => Promise<null | ContractTransactionReceipt>;
Resolves once this transaction has been mined and has %%confirms%% blocks including it (default: ``1``) with an optional %%timeout%%.
This can resolve to ``null`` only if %%confirms%% is ``0`` and the transaction has not been mined, otherwise this will wait until enough confirmations have completed.
class ContractUnknownEventPayload
class ContractUnknownEventPayload extends EventPayload<ContractEventName> {}
A **ContractUnknownEventPayload** is included as the last parameter to Contract Events when the event does not match any events in the ABI.
constructor
constructor( contract: BaseContract, listener: Listener, filter: ContractEventName, log: Log);
@_event:
property log
readonly log: Log;
The log with no matching events.
method getBlock
getBlock: () => Promise<Block>;
Resolves to the block the event occured in.
method getTransaction
getTransaction: () => Promise<TransactionResponse>;
Resolves to the transaction the event occured in.
method getTransactionReceipt
getTransactionReceipt: () => Promise<TransactionReceipt>;
Resolves to the transaction receipt the event occured in.
class EnsPlugin
class EnsPlugin extends NetworkPlugin {}
An **EnsPlugin** allows a [[Network]] to specify the ENS Registry Contract address and the target network to use when using that contract.
Various testnets have their own instance of the contract to use, but in general, the mainnet instance supports multi-chain addresses and should be used.
constructor
constructor(address?: string, targetNetwork?: number);
Creates a new **EnsPlugin** connected to %%address%% on the %%targetNetwork%%. The default ENS address and mainnet is used if unspecified.
property address
readonly address: string;
The ENS Registrty Contract address.
property targetNetwork
readonly targetNetwork: number;
The chain ID that the ENS contract lives on.
method clone
clone: () => EnsPlugin;
class EnsResolver
class EnsResolver {}
A connected object to a resolved ENS name resolver, which can be used to query additional details.
constructor
constructor(provider: AbstractProvider, address: string, name: string);
property address
address: string;
The address of the resolver.
property name
name: string;
The name this resolver was resolved against.
property provider
provider: AbstractProvider;
The connected provider.
method fromName
static fromName: ( provider: AbstractProvider, name: string) => Promise<null | EnsResolver>;
Resolve to the ENS resolver for %%name%% using %%provider%% or ``null`` if unconfigured.
method getAddress
getAddress: (coinType?: number) => Promise<null | string>;
Resolves to the address for %%coinType%% or null if the provided %%coinType%% has not been configured.
method getAvatar
getAvatar: () => Promise<null | string>;
Resolves to the avatar url or ``null`` if the avatar is either unconfigured or incorrectly configured (e.g. references an NFT not owned by the address).
If diagnosing issues with configurations, the [[_getAvatar]] method may be useful.
method getContentHash
getContentHash: () => Promise<null | string>;
Rsolves to the content-hash or ``null`` if unconfigured.
method getEnsAddress
static getEnsAddress: (provider: Provider) => Promise<string>;
method getText
getText: (key: string) => Promise<null | string>;
Resolves to the EIP-634 text record for %%key%%, or ``null`` if unconfigured.
method supportsWildcard
supportsWildcard: () => Promise<boolean>;
Resolves to true if the resolver supports wildcard resolution.
class ErrorDescription
class ErrorDescription {}
When using the [[Interface-parseError]] to automatically match an error for a call result for parsing, an **ErrorDescription** is returned.
constructor
constructor(fragment: ErrorFragment, selector: string, args: Result);
@_ignore:
property args
readonly args: Result;
The arguments passed to the Error with ``revert``.
property fragment
readonly fragment: ErrorFragment;
The matching fragment.
property name
readonly name: string;
The name of the Error.
property selector
readonly selector: string;
The selector for the Error.
property signature
readonly signature: string;
The full Error signature.
class ErrorFragment
class ErrorFragment extends NamedFragment {}
A Fragment which represents a //Custom Error//.
constructor
constructor(guard: any, name: string, inputs: readonly ParamType[]);
property selector
readonly selector: string;
The Custom Error selector.
method format
format: (format?: FormatType) => string;
Returns a string representation of this fragment as %%format%%.
method from
static from: (obj: any) => ErrorFragment;
Returns a new **ErrorFragment** for %%obj%%.
method isFragment
static isFragment: (value: any) => value is ErrorFragment;
Returns ``true`` and provides a type guard if %%value%% is an **ErrorFragment**.
class EtherscanPlugin
class EtherscanPlugin extends NetworkPlugin {}
A Network can include an **EtherscanPlugin** to provide a custom base URL.
@_docloc: api/providers/thirdparty:Etherscan
constructor
constructor(baseUrl: string);
Creates a new **EtherscanProvider** which will use %%baseUrl%%.
property baseUrl
readonly baseUrl: string;
The Etherscan API base URL.
method clone
clone: () => EtherscanPlugin;
class EtherscanProvider
class EtherscanProvider extends AbstractProvider {}
The **EtherscanBaseProvider** is the super-class of [[EtherscanProvider]], which should generally be used instead.
Since the **EtherscanProvider** includes additional code for [[Contract]] access, in //rare cases// that contracts are not used, this class can reduce code size.
@_docloc: api/providers/thirdparty:Etherscan
constructor
constructor(_network?: Networkish, _apiKey?: string);
Creates a new **EtherscanBaseProvider**.
property apiKey
readonly apiKey: string;
The API key or null if using the community provided bandwidth.
property network
readonly network: Network;
The connected network.
method detectNetwork
detectNetwork: () => Promise<Network>;
method fetch
fetch: ( module: string, params: Record<string, any>, post?: boolean) => Promise<any>;
Resolves to the result of calling %%module%% with %%params%%.
If %%post%%, the request is made as a POST request.
method getBaseUrl
getBaseUrl: () => string;
Returns the base URL.
If an [[EtherscanPlugin]] is configured on the [[EtherscanBaseProvider_network]], returns the plugin's baseUrl.
method getContract
getContract: (_address: string) => Promise<null | Contract>;
Resolves to a [Contract]] for %%address%%, using the Etherscan API to retreive the Contract ABI.
method getEtherPrice
getEtherPrice: () => Promise<number>;
Resolves to the current price of ether.
This returns ``0`` on any network other than ``mainnet``.
method getNetwork
getNetwork: () => Promise<Network>;
method getPostData
getPostData: ( module: string, params: Record<string, any>) => Record<string, any>;
Returns the parameters for using POST requests.
method getPostUrl
getPostUrl: () => string;
Returns the URL for using POST requests.
method getUrl
getUrl: (module: string, params: Record<string, string>) => string;
Returns the URL for the %%module%% and %%params%%.
method isCommunityResource
isCommunityResource: () => boolean;
class EventFragment
class EventFragment extends NamedFragment {}
A Fragment which represents an Event.
constructor
constructor( guard: any, name: string, inputs: readonly ParamType[], anonymous: boolean);
property anonymous
readonly anonymous: boolean;
Whether this event is anonymous.
property topicHash
readonly topicHash: string;
The Event topic hash.
method format
format: (format?: FormatType) => string;
Returns a string representation of this event as %%format%%.
method from
static from: (obj: any) => EventFragment;
Returns a new **EventFragment** for %%obj%%.
method getTopicHash
static getTopicHash: (name: string, params?: Array<any>) => string;
Return the topic hash for an event with %%name%% and %%params%%.
method isFragment
static isFragment: (value: any) => value is EventFragment;
Returns ``true`` and provides a type guard if %%value%% is an **EventFragment**.
class EventLog
class EventLog extends Log {}
An **EventLog** contains additional properties parsed from the [[Log]].
constructor
constructor(log: Log, iface: Interface, fragment: EventFragment);
@_ignore:
property args
readonly args: Result;
The parsed arguments passed to the event by ``emit``.
property eventName
readonly eventName: string;
The name of the event.
property eventSignature
readonly eventSignature: string;
The signature of the event.
property fragment
readonly fragment: EventFragment;
The matching event.
property interface
readonly interface: Interface;
The Contract Interface.
class EventPayload
class EventPayload<T> {}
When an [[EventEmitterable]] triggers a [[Listener]], the callback always ahas one additional argument passed, which is an **EventPayload**.
constructor
constructor(emitter: EventEmitterable<T>, listener: Listener, filter: {});
Create a new **EventPayload** for %%emitter%% with the %%listener%% and for %%filter%%.
property emitter
readonly emitter: EventEmitterable<T>;
The **EventEmitterable**.
property filter
readonly filter: {};
The event filter.
method removeListener
removeListener: () => Promise<void>;
Unregister the triggered listener for future events.
class FallbackFragment
class FallbackFragment extends Fragment {}
A Fragment which represents a method.
constructor
constructor(guard: any, inputs: readonly ParamType[], payable: boolean);
property payable
readonly payable: boolean;
If the function can be sent value during invocation.
method format
format: (format?: FormatType) => string;
Returns a string representation of this fallback as %%format%%.
method from
static from: (obj: any) => FallbackFragment;
Returns a new **FallbackFragment** for %%obj%%.
method isFragment
static isFragment: (value: any) => value is FallbackFragment;
Returns ``true`` and provides a type guard if %%value%% is a **FallbackFragment**.
class FallbackProvider
class FallbackProvider extends AbstractProvider {}
A **FallbackProvider** manages several [[Providers]] providing resilience by switching between slow or misbehaving nodes, security by requiring multiple backends to aggree and performance by allowing faster backends to respond earlier.
constructor
constructor( providers: (AbstractProvider | FallbackProviderConfig)[], network?: Networkish, options?: FallbackProviderOptions);
Creates a new **FallbackProvider** with %%providers%% connected to %%network%%.
If a [[Provider]] is included in %%providers%%, defaults are used for the configuration.
property eventQuorum
readonly eventQuorum: number;
@_ignore:
property eventWorkers
readonly eventWorkers: number;
@_ignore:
property providerConfigs
readonly providerConfigs: FallbackProviderState[];
property quorum
readonly quorum: number;
The number of backends that must agree on a value before it is accpeted.
method destroy
destroy: () => Promise<void>;
class FeeData
class FeeData {}
A **FeeData** wraps all the fee-related values associated with the network.
constructor
constructor( gasPrice?: BigInt, maxFeePerGas?: BigInt, maxPriorityFeePerGas?: BigInt);
Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and %%maxPriorityFeePerGas%%.
property gasPrice
readonly gasPrice: BigInt;
The gas price for legacy networks.
property maxFeePerGas
readonly maxFeePerGas: BigInt;
The maximum fee to pay per gas.
The base fee per gas is defined by the network and based on congestion, increasing the cost during times of heavy load and lowering when less busy.
The actual fee per gas will be the base fee for the block and the priority fee, up to the max fee per gas.
This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
property maxPriorityFeePerGas
readonly maxPriorityFeePerGas: BigInt;
The additional amout to pay per gas to encourage a validator to include the transaction.
The purpose of this is to compensate the validator for the adjusted risk for including a given transaction.
This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
method toJSON
toJSON: () => any;
Returns a JSON-friendly value.
class FeeDataNetworkPlugin
class FeeDataNetworkPlugin extends NetworkPlugin {}
A **FeeDataNetworkPlugin** allows a network to provide and alternate means to specify its fee data.
For example, a network which does not support [[link-eip-1559]] may choose to use a Gas Station site to approximate the gas price.
constructor
constructor(feeDataFunc: (provider: Provider) => Promise<FeeData>);
Creates a new **FeeDataNetworkPlugin**.
property feeDataFunc
readonly feeDataFunc: (provider: Provider) => Promise<FeeData>;
The fee data function provided to the constructor.
method clone
clone: () => FeeDataNetworkPlugin;
method getFeeData
getFeeData: (provider: Provider) => Promise<FeeData>;
Resolves to the fee data.
class FetchCancelSignal
class FetchCancelSignal {}
@_ignore
constructor
constructor(request: FetchRequest);
property cancelled
readonly cancelled: boolean;
method addListener
addListener: (listener: () => void) => void;
method checkSignal
checkSignal: () => void;
class FetchRequest
class FetchRequest implements Iterable<[key: string, value: string]> {}
Represents a request for a resource using a URI.
By default, the supported schemes are ``HTTP``, ``HTTPS``, ``data:``, and ``IPFS:``.
Additional schemes can be added globally using [[registerGateway]].
@example: req = new FetchRequest("https://www.ricmoo.com") resp = await req.send() resp.body.length //_result:
constructor
constructor(url: string);
Create a new FetchRequest instance with default values.
Once created, each property may be set before issuing a ``.send()`` to make the request.
property allowGzip
allowGzip: boolean;
Enable and request gzip-encoded responses. The response will automatically be decompressed. //(default: true)//
property allowInsecureAuthentication
allowInsecureAuthentication: boolean;
Allow ``Authentication`` credentials to be sent over insecure channels. //(default: false)//
property body
body: Uint8Array;
The fetch body, if any, to send as the request body. //(default: null)//
When setting a body, the intrinsic ``Content-Type`` is automatically set and will be used if **not overridden** by setting a custom header.
If %%body%% is null, the body is cleared (along with the intrinsic ``Content-Type``).
If %%body%% is a string, the intrinsic ``Content-Type`` is set to ``text/plain``.
If %%body%% is a Uint8Array, the intrinsic ``Content-Type`` is set to ``application/octet-stream``.
If %%body%% is any other object, the intrinsic ``Content-Type`` is set to ``application/json``.
property credentials
readonly credentials: string;
The value that will be sent for the ``Authorization`` header.
To set the credentials, use the ``setCredentials`` method.
property getUrlFunc
getUrlFunc: FetchGetUrlFunc;
This function is called to fetch content from HTTP and HTTPS URLs and is platform specific (e.g. nodejs vs browsers).
This is by default the currently registered global getUrl function, which can be changed using [[registerGetUrl]]. If this has been set, setting is to ``null`` will cause this FetchRequest (and any future clones) to revert back to using the currently registered global getUrl function.
Setting this is generally not necessary, but may be useful for developers that wish to intercept requests or to configurege a proxy or other agent.
property headers
readonly headers: Record<string, string>;
The headers that will be used when requesting the URI. All keys are lower-case.
This object is a copy, so any changes will **NOT** be reflected in the ``FetchRequest``.
To set a header entry, use the ``setHeader`` method.
property method
method: string;
The HTTP method to use when requesting the URI. If no method has been explicitly set, then ``GET`` is used if the body is null and ``POST`` otherwise.
property preflightFunc
preflightFunc: FetchPreflightFunc;
This function is called prior to each request, for example during a redirection or retry in case of server throttling.
This offers an opportunity to populate headers or update content before sending a request.
property processFunc
processFunc: FetchProcessFunc;
This function is called after each response, offering an opportunity to provide client-level throttling or updating response data.
Any error thrown in this causes the ``send()`` to throw.
To schedule a retry attempt (assuming the maximum retry limit has not been reached), use [[response.throwThrottleError]].
property retryFunc
retryFunc: FetchRetryFunc;
This function is called on each retry attempt.
property timeout
timeout: number;
The timeout (in milliseconds) to wait for a complete response. //(default: 5 minutes)//
property url
url: string;
The fetch URL to request.
method [Symbol.iterator]
[Symbol.iterator]: () => Iterator<[key: string, value: string]>;
method cancel
cancel: () => void;
Cancels the inflight response, causing a ``CANCELLED`` error to be rejected from the [[send]].
method clearHeaders
clearHeaders: () => void;
Clear all headers, resetting all intrinsic headers.
method clone
clone: () => FetchRequest;
Create a new copy of this request.
method createDataGateway
static createDataGateway: () => FetchGatewayFunc;
Creates a function that can "fetch" data URIs.
Note that this is automatically done internally to support data URIs, so it is not necessary to register it.
This is not generally something that is needed, but may be useful in a wrapper to perfom custom data URI functionality.
method createGetUrlFunc
static createGetUrlFunc: (options?: Record<string, any>) => FetchGetUrlFunc;
Creates a getUrl function that fetches content from HTTP and HTTPS URLs.
The available %%options%% are dependent on the platform implementation of the default getUrl function.
This is not generally something that is needed, but is useful when trying to customize simple behaviour when fetching HTTP content.
method createIpfsGatewayFunc
static createIpfsGatewayFunc: (baseUrl: string) => FetchGatewayFunc;
Creates a function that will fetch IPFS (unvalidated) from a custom gateway baseUrl.
The default IPFS gateway used internally is ``"https://gateway.ipfs.io/ipfs/"``.
method getGateway
static getGateway: (scheme: string) => null | FetchGatewayFunc;
Get the current Gateway function for %%scheme%%.
method getHeader
getHeader: (key: string) => string;
Get the header for %%key%%, ignoring case.
method hasBody
hasBody: () => this is FetchRequest & { body: Uint8Array };
Returns true if the request has a body.
method lockConfig
static lockConfig: () => void;
Locks all static configuration for gateways and FetchGetUrlFunc registration.
method redirect
redirect: (location: string) => FetchRequest;
Returns a new [[FetchRequest]] that represents the redirection to %%location%%.
method registerGateway
static registerGateway: (scheme: string, func: FetchGatewayFunc) => void;
Use the %%func%% when fetching URIs using %%scheme%%.
This method affects all requests globally.
If [[lockConfig]] has been called, no change is made and this throws.
method registerGetUrl
static registerGetUrl: (getUrl: FetchGetUrlFunc) => void;
Use %%getUrl%% when fetching URIs over HTTP and HTTPS requests.
This method affects all requests globally.
If [[lockConfig]] has been called, no change is made and this throws.
method send
send: () => Promise<FetchResponse>;
Resolves to the response by sending the request.
method setCredentials
setCredentials: (username: string, password: string) => void;
Sets an ``Authorization`` for %%username%% with %%password%%.
method setHeader
setHeader: (key: string, value: string | number) => void;
Set the header for %%key%% to %%value%%. All values are coerced to a string.
method setThrottleParams
setThrottleParams: (params: FetchThrottleParams) => void;
Update the throttle parameters used to determine maximum attempts and exponential-backoff properties.
method toString
toString: () => string;
class FetchResponse
class FetchResponse implements Iterable<[key: string, value: string]> {}
The response for a FetchRequest.
constructor
constructor( statusCode: number, statusMessage: string, headers: Readonly<Record<string, string>>, body: Uint8Array, request?: FetchRequest);
property body
readonly body: Readonly<Uint8Array>;
The response body, or ``null`` if there was no body.
property bodyJson
readonly bodyJson: any;
The response body, decoded as JSON.
An error is thrown if the body is invalid JSON-encoded data or if there was no body.
property bodyText
readonly bodyText: string;
The response body as a UTF-8 encoded string, or the empty string (i.e. ``""``) if there was no body.
An error is thrown if the body is invalid UTF-8 data.
property headers
readonly headers: Record<string, string>;
The response headers. All keys are lower-case.
property request
readonly request: FetchRequest;
The request made for this response.
property statusCode
readonly statusCode: number;
The response status code.
property statusMessage
readonly statusMessage: string;
The response status message.
method [Symbol.iterator]
[Symbol.iterator]: () => Iterator<[key: string, value: string]>;
method assertOk
assertOk: () => void;
Throws a ``SERVER_ERROR`` if this response is not ok.
method getHeader
getHeader: (key: string) => string;
Get the header value for %%key%%, ignoring case.
method hasBody
hasBody: () => this is FetchResponse & { body: Uint8Array };
Returns true if the response has a body.
method makeServerError
makeServerError: (message?: string, error?: Error) => FetchResponse;
Return a Response with matching headers and body, but with an error status code (i.e. 599) and %%message%% with an optional %%error%%.
method ok
ok: () => boolean;
Returns true if this response was a success statusCode.
method throwThrottleError
throwThrottleError: (message?: string, stall?: number) => never;
If called within a [request.processFunc](FetchRequest-processFunc) call, causes the request to retry as if throttled for %%stall%% milliseconds.
method toString
toString: () => string;
class FetchUrlFeeDataNetworkPlugin
class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin {}
constructor
constructor( url: string, processFunc: ( f: () => Promise<FeeData>, p: Provider, r: FetchRequest ) => Promise<{ gasPrice?: null | bigint; maxFeePerGas?: null | bigint; maxPriorityFeePerGas?: null | bigint; }>);
Creates a new **FetchUrlFeeDataNetworkPlugin** which will be used when computing the fee data for the network.
property processFunc
readonly processFunc: ( f: () => Promise<FeeData>, p: Provider, r: FetchRequest) => Promise<{ gasPrice?: null | bigint; maxFeePerGas?: null | bigint; maxPriorityFeePerGas?: null | bigint;}>;
The callback to use when computing the FeeData.
property url
readonly url: string;
The URL to initialize the FetchRequest with in %%processFunc%%.
method clone
clone: () => FetchUrlFeeDataNetworkPlugin;
class FixedNumber
class FixedNumber {}
A FixedNumber represents a value over its [[FixedFormat]] arithmetic field.
A FixedNumber can be used to perform math, losslessly, on values which have decmial places.
A FixedNumber has a fixed bit-width to store values in, and stores all values internally by multiplying the value by 10 raised to the power of %%decimals%%.
If operations are performed that cause a value to grow too high (close to positive infinity) or too low (close to negative infinity), the value is said to //overflow//.
For example, an 8-bit signed value, with 0 decimals may only be within the range ``-128`` to ``127``; so ``-128 - 1`` will overflow and become ``127``. Likewise, ``127 + 1`` will overflow and become ``-127``.
Many operation have a normal and //unsafe// variant. The normal variant will throw a [[NumericFaultError]] on any overflow, while the //unsafe// variant will silently allow overflow, corrupting its value value.
If operations are performed that cause a value to become too small (close to zero), the value loses precison and is said to //underflow//.
For example, an value with 1 decimal place may store a number as small as ``0.1``, but the value of ``0.1 / 2`` is ``0.05``, which cannot fit into 1 decimal place, so underflow occurs which means precision is lost and the value becomes ``0``.
Some operations have a normal and //signalling// variant. The normal variant will silently ignore underflow, while the //signalling// variant will thow a [[NumericFaultError]] on underflow.
constructor
constructor(guard: any, value: BigInt, format: any);
property decimals
readonly decimals: number;
The number of decimal places in the fixed-point arithment field.
property format
readonly format: string;
The specific fixed-point arithmetic field for this value.
property signed
readonly signed: boolean;
If true, negative values are permitted, otherwise only positive values and zero are allowed.
property value
readonly value: BigInt;
The value as an integer, based on the smallest unit the [[decimals]] allow.
property width
readonly width: number;
The number of bits available to store the value.
method add
add: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% added to %%other%%. A [[NumericFaultError]] is thrown if overflow occurs.
method addUnsafe
addUnsafe: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% added to %%other%%, ignoring overflow.
method ceiling
ceiling: () => FixedNumber;
Returns a new [[FixedNumber]] which is the smallest **integer** that is greater than or equal to %%this%%.
The decimal component of the result will always be ``0``.
method cmp
cmp: (other: FixedNumber) => number;
Returns a comparison result between %%this%% and %%other%%.
This is suitable for use in sorting, where ``-1`` implies %%this%% is smaller, ``1`` implies %%this%% is larger and ``0`` implies both are equal.
method div
div: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% divided by %%other%%, ignoring underflow (precision loss). A [[NumericFaultError]] is thrown if overflow occurs.
method divSignal
divSignal: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% divided by %%other%%. A [[NumericFaultError]] is thrown if underflow (precision loss) occurs.
method divUnsafe
divUnsafe: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% divided by %%other%%, ignoring underflow (precision loss). A [[NumericFaultError]] is thrown if overflow occurs.
method eq
eq: (other: FixedNumber) => boolean;
Returns true if %%other%% is equal to %%this%%.
method floor
floor: () => FixedNumber;
Returns a new [[FixedNumber]] which is the largest **integer** that is less than or equal to %%this%%.
The decimal component of the result will always be ``0``.
method fromBytes
static fromBytes: (_value: BytesLike, _format?: FixedFormat) => FixedNumber;
Creates a new [[FixedNumber]] with the big-endian representation %%value%% with %%format%%.
This will throw a [[NumericFaultError]] if %%value%% cannot fit in %%format%% due to overflow.
method fromString
static fromString: (_value: string, _format?: FixedFormat) => FixedNumber;
Creates a new [[FixedNumber]] for %%value%% with %%format%%.
This will throw a [[NumericFaultError]] if %%value%% cannot fit in %%format%%, either due to overflow or underflow (precision loss).
method fromValue
static fromValue: ( _value: BigNumberish, _decimals?: Numeric, _format?: FixedFormat) => FixedNumber;
Creates a new [[FixedNumber]] for %%value%% divided by %%decimal%% places with %%format%%.
This will throw a [[NumericFaultError]] if %%value%% (once adjusted for %%decimals%%) cannot fit in %%format%%, either due to overflow or underflow (precision loss).
method gt
gt: (other: FixedNumber) => boolean;
Returns true if %%other%% is greater than to %%this%%.
method gte
gte: (other: FixedNumber) => boolean;
Returns true if %%other%% is greater than or equal to %%this%%.
method isNegative
isNegative: () => boolean;
Returns true if %%this%% is less than ``0``.
method isZero
isZero: () => boolean;
Returns true if %%this%% is equal to ``0``.
method lt
lt: (other: FixedNumber) => boolean;
Returns true if %%other%% is less than to %%this%%.
method lte
lte: (other: FixedNumber) => boolean;
Returns true if %%other%% is less than or equal to %%this%%.
method mul
mul: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% multiplied by %%other%%. A [[NumericFaultError]] is thrown if overflow occurs.
method mulSignal
mulSignal: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% multiplied by %%other%%. A [[NumericFaultError]] is thrown if overflow occurs or if underflow (precision loss) occurs.
method mulUnsafe
mulUnsafe: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%this%% multiplied by %%other%%, ignoring overflow and underflow (precision loss).
method round
round: (decimals?: number) => FixedNumber;
Returns a new [[FixedNumber]] with the decimal component rounded up on ties at %%decimals%% places.
method sub
sub: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%other%% subtracted from %%this%%. A [[NumericFaultError]] is thrown if overflow occurs.
method subUnsafe
subUnsafe: (other: FixedNumber) => FixedNumber;
Returns a new [[FixedNumber]] with the result of %%other%% subtracted from %%this%%, ignoring overflow.
method toFormat
toFormat: (format: FixedFormat) => FixedNumber;
Return a new [[FixedNumber]] with the same value but has had its field set to %%format%%.
This will throw if the value cannot fit into %%format%%.
method toString
toString: () => string;
Returns the string representation of %%this%%.
method toUnsafeFloat
toUnsafeFloat: () => number;
Returns a float approximation.
Due to IEEE 754 precission (or lack thereof), this function can only return an approximation and most values will contain rounding errors.
class Fragment
abstract class Fragment {}
An abstract class to represent An individual fragment from a parse ABI.
constructor
constructor(guard: any, type: FragmentType, inputs: readonly ParamType[]);
property inputs
readonly inputs: readonly ParamType[];
The inputs for the fragment.
property type
readonly type: FragmentType;
The type of the fragment.
method format
abstract format: (format?: FormatType) => string;
Returns a string representation of this fragment as %%format%%.
method from
static from: (obj: any) => Fragment;
Creates a new **Fragment** for %%obj%%, wich can be any supported ABI frgament type.
method isConstructor
static isConstructor: (value: any) => value is ConstructorFragment;
Returns true if %%value%% is a [[ConstructorFragment]].
method isError
static isError: (value: any) => value is ErrorFragment;
Returns true if %%value%% is an [[ErrorFragment]].
method isEvent
static isEvent: (value: any) => value is EventFragment;
Returns true if %%value%% is an [[EventFragment]].
method isFunction
static isFunction: (value: any) => value is FunctionFragment;
Returns true if %%value%% is a [[FunctionFragment]].
method isStruct
static isStruct: (value: any) => value is StructFragment;
Returns true if %%value%% is a [[StructFragment]].
class FunctionFragment
class FunctionFragment extends NamedFragment {}
A Fragment which represents a method.
constructor
constructor( guard: any, name: string, stateMutability: 'payable' | 'nonpayable' | 'view' | 'pure', inputs: readonly ParamType[], outputs: readonly ParamType[], gas: BigInt);
property constant
readonly constant: boolean;
If the function is constant (e.g. ``pure`` or ``view`` functions).
property gas
readonly gas: BigInt;
The recommended gas limit to send when calling this function.
property outputs
readonly outputs: readonly ParamType[];
The returned types for the result of calling this function.
property payable
readonly payable: boolean;
If the function can be sent value during invocation.
property selector
readonly selector: string;
The Function selector.
property stateMutability
readonly stateMutability: 'payable' | 'nonpayable' | 'view' | 'pure';
The state mutability (e.g. ``payable``, ``nonpayable``, ``view`` or ``pure``)
method format
format: (format?: FormatType) => string;
Returns a string representation of this function as %%format%%.
method from
static from: (obj: any) => FunctionFragment;
Returns a new **FunctionFragment** for %%obj%%.
method getSelector
static getSelector: (name: string, params?: Array<any>) => string;
Return the selector for a function with %%name%% and %%params%%.
method isFragment
static isFragment: (value: any) => value is FunctionFragment;
Returns ``true`` and provides a type guard if %%value%% is a **FunctionFragment**.
class GasCostPlugin
class GasCostPlugin extends NetworkPlugin implements GasCostParameters {}
A **GasCostPlugin** allows a network to provide alternative values when computing the intrinsic gas required for a transaction.
constructor
constructor(effectiveBlock?: number, costs?: GasCostParameters);
Creates a new GasCostPlugin from %%effectiveBlock%% until the latest block or another GasCostPlugin supercedes that block number, with the associated %%costs%%.
property effectiveBlock
readonly effectiveBlock: number;
The block number to treat these values as valid from.
This allows a hardfork to have updated values included as well as mulutiple hardforks to be supported.
property txAccessListAddress
readonly txAccessListAddress: number;
The fee per address in the [[link-eip-2930]] access list.
property txAccessListStorageKey
readonly txAccessListStorageKey: number;
The fee per storage key in the [[link-eip-2930]] access list.
property txBase
readonly txBase: number;
The transactions base fee.
property txCreate
readonly txCreate: number;
The fee for creating a new account.
property txDataNonzero
readonly txDataNonzero: number;
The fee per non-zero-byte in the data.
property txDataZero
readonly txDataZero: number;
The fee per zero-byte in the data.
method clone
clone: () => GasCostPlugin;
class HDNodeVoidWallet
class HDNodeVoidWallet extends VoidSigner {}
A **HDNodeVoidWallet** cannot sign, but provides access to the children nodes of a [[link-bip-32]] HD wallet addresses.
The can be created by using an extended ``xpub`` key to [[HDNodeWallet_fromExtendedKey]] or by [nuetering](HDNodeWallet-neuter) a [[HDNodeWallet]].
constructor
constructor( guard: any, address: string, publicKey: string, parentFingerprint: string, chainCode: string, path: string, index: number, depth: number, provider: Provider);
property chainCode
readonly chainCode: string;
The chaincode, which is effectively a public key used to derive children.
property depth
readonly depth: number;
The depth of this wallet, which is the number of components in its path.
property extendedKey
readonly extendedKey: string;
The extended key.
This key will begin with the prefix ``xpub`` and can be used to reconstruct this neutered key to derive its children addresses.
property fingerprint
readonly fingerprint: string;
The fingerprint.
A fingerprint allows quick qay to detect parent and child nodes, but developers should be prepared to deal with collisions as it is only 4 bytes.
property index
readonly index: number;
The child index of this wallet. Values over ``2 ** 31`` indicate the node is hardened.
property parentFingerprint
readonly parentFingerprint: string;
The parent node fingerprint.
property path
readonly path: string;
The derivation path of this wallet.
Since extended keys do not provider full path details, this may be ``null``, if instantiated from a source that does not enocde it.
property publicKey
readonly publicKey: string;
The compressed public key.
method connect
connect: (provider: null | Provider) => HDNodeVoidWallet;
method deriveChild
deriveChild: (_index: Numeric) => HDNodeVoidWallet;
Return the child for %%index%%.
method derivePath
derivePath: (path: string) => HDNodeVoidWallet;
Return the signer for %%path%% from this node.
method hasPath
hasPath: () => this is { path: string };
Returns true if this wallet has a path, providing a Type Guard that the path is non-null.
class HDNodeWallet
class HDNodeWallet extends BaseWallet {}
An **HDNodeWallet** is a [[Signer]] backed by the private key derived from an HD Node using the [[link-bip-32]] stantard.
An HD Node forms a hierarchal structure with each HD Node having a private key and the ability to derive child HD Nodes, defined by a path indicating the index of each child.
constructor
constructor( guard: any, signingKey: SigningKey, parentFingerprint: string, chainCode: string, path: string, index: number, depth: number, mnemonic: Mnemonic, provider: Provider);
property chainCode
readonly chainCode: string;
The chaincode, which is effectively a public key used to derive children.
property depth
readonly depth: number;
The depth of this wallet, which is the number of components in its path.
property extendedKey
readonly extendedKey: string;
The extended key.
This key will begin with the prefix ``xpriv`` and can be used to reconstruct this HD Node to derive its children.
property fingerprint
readonly fingerprint: string;
The fingerprint.
A fingerprint allows quick qay to detect parent and child nodes, but developers should be prepared to deal with collisions as it is only 4 bytes.
property index
readonly index: number;
The child index of this wallet. Values over ``2 ** 31`` indicate the node is hardened.
property mnemonic
readonly mnemonic: Mnemonic;
The mnemonic used to create this HD Node, if available.
Sources such as extended keys do not encode the mnemonic, in which case this will be ``null``.
property parentFingerprint
readonly parentFingerprint: string;
The parent fingerprint.
property path
readonly path: string;
The derivation path of this wallet.
Since extended keys do not provide full path details, this may be ``null``, if instantiated from a source that does not encode it.
property publicKey
readonly publicKey: string;
The compressed public key.
method connect
connect: (provider: null | Provider) => HDNodeWallet;
method createRandom
static createRandom: ( password?: string, path?: string, wordlist?: Wordlist) => HDNodeWallet;
Creates a new random HDNode.
method deriveChild
deriveChild: (_index: Numeric) => HDNodeWallet;
Return the child for %%index%%.
method derivePath
derivePath: (path: string) => HDNodeWallet;
Return the HDNode for %%path%% from this node.
method encrypt
encrypt: ( password: Uint8Array | string, progressCallback?: ProgressCallback) => Promise<string>;
Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with %%password%%.
If %%progressCallback%% is specified, it will receive periodic updates as the encryption process progreses.
method encryptSync
encryptSync: (password: Uint8Array | string) => string;
Returns a [JSON Keystore Wallet](json-wallets) encryped with %%password%%.
It is preferred to use the [async version](encrypt) instead, which allows a [[ProgressCallback]] to keep the user informed.
This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial duration.
method fromExtendedKey
static fromExtendedKey: (extendedKey: string) => HDNodeWallet | HDNodeVoidWallet;
Creates a new HD Node from %%extendedKey%%.
If the %%extendedKey%% will either have a prefix or ``xpub`` or ``xpriv``, returning a neutered HD Node ([[HDNodeVoidWallet]]) or full HD Node ([[HDNodeWallet) respectively.
method fromMnemonic
static fromMnemonic: (mnemonic: Mnemonic, path?: string) => HDNodeWallet;
Create an HD Node from %%mnemonic%%.
method fromPhrase
static fromPhrase: ( phrase: string, password?: string, path?: string, wordlist?: Wordlist) => HDNodeWallet;
Creates an HD Node from a mnemonic %%phrase%%.
method fromSeed
static fromSeed: (seed: BytesLike) => HDNodeWallet;
Creates an HD Node from a %%seed%%.
method hasPath
hasPath: () => this is { path: string };
Returns true if this wallet has a path, providing a Type Guard that the path is non-null.
method neuter
neuter: () => HDNodeVoidWallet;
Returns a neutered HD Node, which removes the private details of an HD Node.
A neutered node has no private key, but can be used to derive child addresses and other public data about the HD Node.
class Indexed
class Indexed {}
An **Indexed** is used as a value when a value that does not fit within a topic (i.e. not a fixed-length, 32-byte type). It is the ``keccak256`` of the value, and used for types such as arrays, tuples, bytes and strings.
constructor
constructor(hash: string);
@_ignore:
property hash
readonly hash: string;
The ``keccak256`` of the value logged.
method isIndexed
static isIndexed: (value: any) => value is Indexed;
Returns ``true`` if %%value%% is an **Indexed**.
This provides a Type Guard for property access.
class InfuraProvider
class InfuraProvider extends JsonRpcProvider implements CommunityResourcable {}
The **InfuraProvider** connects to the [[link-infura]] JSON-RPC end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-infura-signup).
constructor
constructor(_network?: Networkish, projectId?: string, projectSecret?: string);
Creates a new **InfuraProvider**.
property projectId
readonly projectId: string;
The Project ID for the INFURA connection.
property projectSecret
readonly projectSecret: string;
The Project Secret.
If null, no authenticated requests are made. This should not be used outside of private contexts.
method getRequest
static getRequest: ( network: Network, projectId?: null | string, projectSecret?: null | string) => FetchRequest;
Returns a prepared request for connecting to %%network%% with %%projectId%% and %%projectSecret%%.
method getWebSocketProvider
static getWebSocketProvider: ( network?: Networkish, projectId?: string) => InfuraWebSocketProvider;
Creates a new **InfuraWebSocketProvider**.
method isCommunityResource
isCommunityResource: () => boolean;
class InfuraWebSocketProvider
class InfuraWebSocketProvider extends WebSocketProvider implements CommunityResourcable {}
The **InfuraWebSocketProvider** connects to the [[link-infura]] WebSocket end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-infura-signup).
constructor
constructor(network?: Networkish, projectId?: string);
Creates a new **InfuraWebSocketProvider**.
property projectId
readonly projectId: string;
The Project ID for the INFURA connection.
property projectSecret
readonly projectSecret: string;
The Project Secret.
If null, no authenticated requests are made. This should not be used outside of private contexts.
method isCommunityResource
isCommunityResource: () => boolean;
class Interface
class Interface {}
An Interface abstracts many of the low-level details for encoding and decoding the data on the blockchain.
An ABI provides information on how to encode data to send to a Contract, how to decode the results and events and how to interpret revert errors.
The ABI can be specified by [any supported format](InterfaceAbi).
constructor
constructor(fragments: InterfaceAbi);
Create a new Interface for the %%fragments%%.
property deploy
readonly deploy: ConstructorFragment;
The Contract constructor.
property fallback
readonly fallback: FallbackFragment;
The Fallback method, if any.
property fragments
readonly fragments: readonly Fragment[];
All the Contract ABI members (i.e. methods, events, errors, etc).
property receive
readonly receive: boolean;
If receiving ether is supported.
method decodeErrorResult
decodeErrorResult: (fragment: ErrorFragment | string, data: BytesLike) => Result;
Decodes the result %%data%% (e.g. from an ``eth_call``) for the specified error (see [[getError]] for valid values for %%key%%).
Most developers should prefer the [[parseCallResult]] method instead, which will automatically detect a ``CALL_EXCEPTION`` and throw the corresponding error.
method decodeEventLog
decodeEventLog: ( fragment: EventFragment | string, data: BytesLike, topics?: ReadonlyArray<string>) => Result;
method decodeFunctionData
decodeFunctionData: ( fragment: FunctionFragment | string, data: BytesLike) => Result;
Decodes the %%data%% from a transaction ``tx.data`` for the function specified (see [[getFunction]] for valid values for %%fragment%%).
Most developers should prefer the [[parseTransaction]] method instead, which will automatically detect the fragment.
method decodeFunctionResult
decodeFunctionResult: ( fragment: FunctionFragment | string, data: BytesLike) => Result;
Decodes the result %%data%% (e.g. from an ``eth_call``) for the specified function (see [[getFunction]] for valid values for %%key%%).
Most developers should prefer the [[parseCallResult]] method instead, which will automatically detect a ``CALL_EXCEPTION`` and throw the corresponding error.
method encodeDeploy
encodeDeploy: (values?: ReadonlyArray<any>) => string;
Encodes a ``tx.data`` object for deploying the Contract with the %%values%% as the constructor arguments.
method encodeErrorResult
encodeErrorResult: ( fragment: ErrorFragment | string, values?: ReadonlyArray<any>) => string;
Encodes the transaction revert data for a call result that reverted from the the Contract with the sepcified %%error%% (see [[getError]] for valid values for %%fragment%%) with the %%values%%.
This is generally not used by most developers, unless trying to mock a result from a Contract.
method encodeEventLog
encodeEventLog: ( fragment: EventFragment | string, values: ReadonlyArray<any>) => { data: string; topics: Array<string> };
method encodeFilterTopics
encodeFilterTopics: ( fragment: EventFragment | string, values: ReadonlyArray<any>) => Array<null | string | Array<string>>;
method encodeFunctionData
encodeFunctionData: ( fragment: FunctionFragment | string, values?: ReadonlyArray<any>) => string;
Encodes the ``tx.data`` for a transaction that calls the function specified (see [[getFunction]] for valid values for %%fragment%%) with the %%values%%.
method encodeFunctionResult
encodeFunctionResult: ( fragment: FunctionFragment | string, values?: ReadonlyArray<any>) => string;
Encodes the result data (e.g. from an ``eth_call``) for the specified function (see [[getFunction]] for valid values for %%fragment%%) with %%values%%.
This is generally not used by most developers, unless trying to mock a result from a Contract.
method forEachError
forEachError: (callback: (func: ErrorFragment, index: number) => void) => void;
Iterate over all errors, calling %%callback%%, sorted by their name.
method forEachEvent
forEachEvent: (callback: (func: EventFragment, index: number) => void) => void;
Iterate over all events, calling %%callback%%, sorted by their name.
method forEachFunction
forEachFunction: ( callback: (func: FunctionFragment, index: number) => void) => void;
Iterate over all functions, calling %%callback%%, sorted by their name.
method format
format: (minimal?: boolean) => Array<string>;
Returns the entire Human-Readable ABI, as an array of signatures, optionally as %%minimal%% strings, which removes parameter names and unneceesary spaces.
method formatJson
formatJson: () => string;
Return the JSON-encoded ABI. This is the format Solidiy returns.
method from
static from: (value: InterfaceAbi | Interface) => Interface;
Creates a new [[Interface]] from the ABI %%value%%.
The %%value%% may be provided as an existing [[Interface]] object, a JSON-encoded ABI or any Human-Readable ABI format.
method getAbiCoder
getAbiCoder: () => AbiCoder;
The ABI coder that will be used to encode and decode binary data.
method getError
getError: (key: string, values?: Array<any | Typed>) => null | ErrorFragment;
Get the [[ErrorFragment]] for %%key%%, which may be an error selector, error name or error signature that belongs to the ABI.
If %%values%% is provided, it will use the Typed API to handle ambiguous cases where multiple errors match by name.
If the %%key%% and %%values%% do not refine to a single error in the ABI, this will throw.
method getEvent
getEvent: (key: string, values?: Array<any | Typed>) => null | EventFragment;
Get the [[EventFragment]] for %%key%%, which may be a topic hash, event name or event signature that belongs to the ABI.
If %%values%% is provided, it will use the Typed API to handle ambiguous cases where multiple events match by name.
If the %%key%% and %%values%% do not refine to a single event in the ABI, this will throw.
method getEventName
getEventName: (key: string) => string;
Get the event name for %%key%%, which may be a topic hash, event name or event signature that belongs to the ABI.
method getFunction
getFunction: ( key: string, values?: Array<any | Typed>) => null | FunctionFragment;
Get the [[FunctionFragment]] for %%key%%, which may be a function selector, function name or function signature that belongs to the ABI.
If %%values%% is provided, it will use the Typed API to handle ambiguous cases where multiple functions match by name.
If the %%key%% and %%values%% do not refine to a single function in the ABI, this will throw.
method getFunctionName
getFunctionName: (key: string) => string;
Get the function name for %%key%%, which may be a function selector, function name or function signature that belongs to the ABI.
method hasEvent
hasEvent: (key: string) => boolean;
Returns true if %%key%% (an event topic hash, event name or event signature) is present in the ABI.
In the case of an event name, the name may be ambiguous, so accessing the [[EventFragment]] may require refinement.
method hasFunction
hasFunction: (key: string) => boolean;
Returns true if %%key%% (a function selector, function name or function signature) is present in the ABI.
In the case of a function name, the name may be ambiguous, so accessing the [[FunctionFragment]] may require refinement.
method makeError
makeError: ( _data: BytesLike, tx: CallExceptionTransaction) => CallExceptionError;
method parseCallResult
parseCallResult: (data: BytesLike) => Result;
method parseError
parseError: (data: BytesLike) => null | ErrorDescription;
Parses a revert data, finding the matching error and extracts the parameter values along with other useful error details.
If the matching error cannot be found, returns null.
method parseLog
parseLog: (log: { topics: ReadonlyArray<string>; data: string;}) => null | LogDescription;
Parses a receipt log, finding the matching event and extracts the parameter values along with other useful event details.
If the matching event cannot be found, returns null.
method parseTransaction
parseTransaction: (tx: { data: string; value?: BigNumberish;}) => null | TransactionDescription;
Parses a transaction, finding the matching function and extracts the parameter values along with other useful function details.
If the matching function cannot be found, return null.
class IpcSocketProvider
class IpcSocketProvider extends SocketProvider {}
An **IpcSocketProvider** connects over an IPC socket on the host which provides fast access to the node, but requires the node and the script run on the same machine.
constructor
constructor( path: string, network?: Networkish, options?: JsonRpcApiProviderOptions);
property socket
readonly socket: Socket;
The connected socket.
method destroy
destroy: () => void;
class JsonRpcApiProvider
abstract class JsonRpcApiProvider extends AbstractProvider {}
The JsonRpcApiProvider is an abstract class and **MUST** be sub-classed.
It provides the base for all JSON-RPC-based Provider interaction.
Sub-classing Notes: - a sub-class MUST override _send - a sub-class MUST call the
_start()
method once connected
constructor
constructor(network?: Networkish, options?: JsonRpcApiProviderOptions);
property ready
readonly ready: boolean;
Returns true only if the [[_start]] has been called.
method destroy
destroy: () => void;
method getRpcError
getRpcError: (payload: JsonRpcPayload, _error: JsonRpcError) => Error;
Returns an ethers-style Error for the given JSON-RPC error %%payload%%, coalescing the various strings and error shapes that different nodes return, coercing them into a machine-readable standardized error.
method getRpcRequest
getRpcRequest: ( req: PerformActionRequest) => null | { method: string; args: Array<any> };
Returns the request method and arguments required to perform %%req%%.
method getRpcTransaction
getRpcTransaction: (tx: TransactionRequest) => JsonRpcTransactionRequest;
Returns %%tx%% as a normalized JSON-RPC transaction request, which has all values hexlified and any numeric values converted to Quantity values.
method getSigner
getSigner: (address?: number | string) => Promise<JsonRpcSigner>;
Resolves to the [[Signer]] account for %%address%% managed by the client.
If the %%address%% is a number, it is used as an index in the the accounts from [[listAccounts]].
This can only be used on clients which manage accounts (such as Geth with imported account or MetaMask).
Throws if the account doesn't exist.
method listAccounts
listAccounts: () => Promise<Array<JsonRpcSigner>>;
method send
send: (method: string, params: Array<any> | Record<string, any>) => Promise<any>;
Requests the %%method%% with %%params%% via the JSON-RPC protocol over the underlying channel. This can be used to call methods on the backend that do not have a high-level API within the Provider API.
This method queues requests according to the batch constraints in the options, assigns the request a unique ID.
**Do NOT override** this method in sub-classes; instead override [[_send]] or force the options values in the call to the constructor to modify this method's behavior.
class JsonRpcProvider
class JsonRpcProvider extends JsonRpcApiPollingProvider {}
The JsonRpcProvider is one of the most common Providers, which performs all operations over HTTP (or HTTPS) requests.
Events are processed by polling the backend for the current block number; when it advances, all block-base events are then checked for updates.
constructor
constructor( url?: string | FetchRequest, network?: Networkish, options?: JsonRpcApiProviderOptions);
method send
send: (method: string, params: Array<any> | Record<string, any>) => Promise<any>;
class JsonRpcSigner
class JsonRpcSigner extends AbstractSigner<JsonRpcApiProvider> {}
constructor
constructor(provider: JsonRpcApiProvider, address: string);
property address
address: string;
method connect
connect: (provider: null | Provider) => Signer;
method getAddress
getAddress: () => Promise<string>;
method populateTransaction
populateTransaction: ( tx: TransactionRequest) => Promise<TransactionLike<string>>;
method sendTransaction
sendTransaction: (tx: TransactionRequest) => Promise<TransactionResponse>;
method sendUncheckedTransaction
sendUncheckedTransaction: (_tx: TransactionRequest) => Promise<string>;
method signMessage
signMessage: (_message: string | Uint8Array) => Promise<string>;
method signTransaction
signTransaction: (_tx: TransactionRequest) => Promise<string>;
method signTypedData
signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, _value: Record<string, any>) => Promise<string>;
method unlock
unlock: (password: string) => Promise<boolean>;
class LangEn
class LangEn extends WordlistOwl {}
The [[link-bip39-en]] for [mnemonic phrases](link-bip-39).
@_docloc: api/wordlists
constructor
constructor();
Creates a new instance of the English language Wordlist.
This should be unnecessary most of the time as the exported [[langEn]] should suffice.
@_ignore:
method wordlist
static wordlist: () => LangEn;
Returns a singleton instance of a ``LangEn``, creating it if this is the first time being called.
class Log
class Log implements LogParams {}
A **Log** in Ethereum represents an event that has been included in a transaction using the ``LOG*`` opcodes, which are most commonly used by Solidity's emit for announcing events.
constructor
constructor(log: LogParams, provider: Provider);
@_ignore:
property address
readonly address: string;
The address of the contract that emitted this log.
property blockHash
readonly blockHash: string;
The block hash of the block this log occurred in. Use the [[Log-getBlock]] to get the [[Block]].
property blockNumber
readonly blockNumber: number;
The block number of the block this log occurred in. It is preferred to use the [[Block-hash]] when fetching the related [[Block]], since in the case of an orphaned block, the block at that height may have changed.
property data
readonly data: string;
The data included in this log when it was emitted.
property index
readonly index: number;
The index within the block this log occurred at. This is generally not useful to developers, but can be used with the various roots to proof inclusion within a block.
property provider
readonly provider: Provider;
The provider connected to the log used to fetch additional details if necessary.
property removed
readonly removed: boolean;
If the **Log** represents a block that was removed due to an orphaned block, this will be true.
This can only happen within an orphan event listener.
property topics
readonly topics: readonly string[];
The indexed topics included in this log when it was emitted.
All topics are included in the bloom filters, so they can be efficiently filtered using the [[Provider-getLogs]] method.
property transactionHash
readonly transactionHash: string;
The transaction hash of the transaction this log occurred in. Use the [[Log-getTransaction]] to get the [[TransactionResponse]].
property transactionIndex
readonly transactionIndex: number;
The index within the transaction of this log.
method getBlock
getBlock: () => Promise<Block>;
Returns the block that this log occurred in.
method getTransaction
getTransaction: () => Promise<TransactionResponse>;
Returns the transaction that this log occurred in.
method getTransactionReceipt
getTransactionReceipt: () => Promise<TransactionReceipt>;
Returns the transaction receipt fot the transaction that this log occurred in.
method removedEvent
removedEvent: () => OrphanFilter;
@_ignore:
method toJSON
toJSON: () => any;
Returns a JSON-compatible object.
class LogDescription
class LogDescription {}
When using the [[Interface-parseLog]] to automatically match a Log to its event for parsing, a **LogDescription** is returned.
constructor
constructor(fragment: EventFragment, topic: string, args: Result);
@_ignore:
property args
readonly args: Result;
The arguments passed into the Event with ``emit``.
property fragment
readonly fragment: EventFragment;
The matching fragment for the ``topic0``.
property name
readonly name: string;
The name of the Event.
property signature
readonly signature: string;
The full Event signature.
property topic
readonly topic: string;
The topic hash for the Event.
class Mnemonic
class Mnemonic {}
A **Mnemonic** wraps all properties required to compute [[link-bip-39]] seeds and convert between phrases and entropy.
constructor
constructor( guard: any, entropy: string, phrase: string, password?: string, wordlist?: Wordlist);
property entropy
readonly entropy: string;
The underlying entropy which the mnemonic encodes.
property password
readonly password: string;
The password used for this mnemonic. If no password is used this is the empty string (i.e. ``""``) as per the specification.
property phrase
readonly phrase: string;
The mnemonic phrase of 12, 15, 18, 21 or 24 words.
Use the [[wordlist]] ``split`` method to get the individual words.
property wordlist
readonly wordlist: Wordlist;
The wordlist for this mnemonic.
method computeSeed
computeSeed: () => string;
Returns the seed for the mnemonic.
method entropyToPhrase
static entropyToPhrase: ( _entropy: BytesLike, wordlist?: null | Wordlist) => string;
Returns the phrase for %%mnemonic%%.
method fromEntropy
static fromEntropy: ( _entropy: BytesLike, password?: null | string, wordlist?: null | Wordlist) => Mnemonic;
Create a new **Mnemonic** from the %%entropy%%.
The default %%password%% is the empty string and the default wordlist is the [English wordlists](LangEn).
method fromPhrase
static fromPhrase: ( phrase: string, password?: null | string, wordlist?: null | Wordlist) => Mnemonic;
Creates a new Mnemonic for the %%phrase%%.
The default %%password%% is the empty string and the default wordlist is the [English wordlists](LangEn).
method isValidMnemonic
static isValidMnemonic: (phrase: string, wordlist?: null | Wordlist) => boolean;
Returns true if %%phrase%% is a valid [[link-bip-39]] phrase.
This checks all the provided words belong to the %%wordlist%%, that the length is valid and the checksum is correct.
method phraseToEntropy
static phraseToEntropy: (phrase: string, wordlist?: null | Wordlist) => string;
Returns the entropy for %%phrase%%.
class MulticoinProviderPlugin
abstract class MulticoinProviderPlugin implements AbstractProviderPlugin {}
A provider plugin super-class for processing multicoin address types.
constructor
constructor(name: string);
Creates a new **MulticoinProviderPluing** for %%name%%.
property name
readonly name: string;
The name.
method connect
connect: (proivder: Provider) => MulticoinProviderPlugin;
method decodeAddress
decodeAddress: (coinType: number, data: BytesLike) => Promise<string>;
Resolves to the decoded %%data%% for %%coinType%%.
method encodeAddress
encodeAddress: (coinType: number, address: string) => Promise<string>;
Resolves to the encoded %%address%% for %%coinType%%.
method supportsCoinType
supportsCoinType: (coinType: number) => boolean;
Returns ``true`` if %%coinType%% is supported by this plugin.
class NamedFragment
abstract class NamedFragment extends Fragment {}
An abstract class to represent An individual fragment which has a name from a parse ABI.
constructor
constructor( guard: any, type: FragmentType, name: string, inputs: readonly ParamType[]);
property name
readonly name: string;
The name of the fragment.
class Network
class Network {}
A **Network** provides access to a chain's properties and allows for plug-ins to extend functionality.
constructor
constructor(name: string, chainId: BigNumberish);
Creates a new **Network** for %%name%% and %%chainId%%.
property chainId
chainId: BigInt;
The network chain ID.
property name
name: string;
The network common name.
This is the canonical name, as networks migh have multiple names.
property plugins
readonly plugins: NetworkPlugin[];
Returns the list of plugins currently attached to this Network.
method attachPlugin
attachPlugin: (plugin: NetworkPlugin) => this;
Attach a new %%plugin%% to this Network. The network name must be unique, excluding any fragment.
method clone
clone: () => Network;
Create a copy of this Network.
method computeIntrinsicGas
computeIntrinsicGas: (tx: TransactionLike) => number;
Compute the intrinsic gas required for a transaction.
A GasCostPlugin can be attached to override the default values.
method from
static from: (network?: Networkish) => Network;
Returns a new Network for the %%network%% name or chainId.
method getPlugin
getPlugin: <T extends NetworkPlugin = NetworkPlugin>(name: string) => null | T;
Return the plugin, if any, matching %%name%% exactly. Plugins with fragments will not be returned unless %%name%% includes a fragment.
method getPlugins
getPlugins: <T extends NetworkPlugin = NetworkPlugin>( basename: string) => Array<T>;
Gets a list of all plugins that match %%name%%, with otr without a fragment.
method matches
matches: (other: Networkish) => boolean;
Returns true if %%other%% matches this network. Any chain ID must match, and if no chain ID is present, the name must match.
This method does not currently check for additional properties, such as ENS address or plug-in compatibility.
method register
static register: ( nameOrChainId: string | number | bigint, networkFunc: () => Network) => void;
Register %%nameOrChainId%% with a function which returns an instance of a Network representing that chain.
method toJSON
toJSON: () => any;
Returns a JSON-compatible representation of a Network.
class NetworkPlugin
class NetworkPlugin {}
A **NetworkPlugin** provides additional functionality on a [[Network]].
constructor
constructor(name: string);
Creates a new **NetworkPlugin**.
property name
readonly name: string;
The name of the plugin.
It is recommended to use reverse-domain-notation, which permits unique names with a known authority as well as hierarchal entries.
method clone
clone: () => NetworkPlugin;
Creates a copy of this plugin.
class NonceManager
class NonceManager extends AbstractSigner {}
A **NonceManager** wraps another [[Signer]] and automatically manages the nonce, ensuring serialized and sequential nonces are used during transaction.
constructor
constructor(signer: Signer);
Creates a new **NonceManager** to manage %%signer%%.
property signer
signer: Signer;
The Signer being managed.
method connect
connect: (provider: null | Provider) => NonceManager;
method getAddress
getAddress: () => Promise<string>;
method getNonce
getNonce: (blockTag?: BlockTag) => Promise<number>;
method increment
increment: () => void;
Manually increment the nonce. This may be useful when managng offline transactions.
method reset
reset: () => void;
Resets the nonce, causing the **NonceManager** to reload the current nonce from the blockchain on the next transaction.
method sendTransaction
sendTransaction: (tx: TransactionRequest) => Promise<TransactionResponse>;
method signMessage
signMessage: (message: string | Uint8Array) => Promise<string>;
method signTransaction
signTransaction: (tx: TransactionRequest) => Promise<string>;
method signTypedData
signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => Promise<string>;
class ParamType
class ParamType {}
Each input and output of a [[Fragment]] is an Array of **ParamType**.
constructor
constructor( guard: any, name: string, type: string, baseType: string, indexed: boolean, components: readonly ParamType[], arrayLength: number, arrayChildren: ParamType);
property arrayChildren
readonly arrayChildren: ParamType;
The type of each child in the array.
For non-array types this is ``null``.
property arrayLength
readonly arrayLength: number;
The array length, or ``-1`` for dynamic-lengthed arrays.
For non-array types this is ``null``.
property baseType
readonly baseType: string;
The base type (e.g. ``"address"``, ``"tuple"``, ``"array"``)
property components
readonly components: readonly ParamType[];
The components for the tuple.
For non-tuple types this is ``null``.
property indexed
readonly indexed: boolean;
True if the parameters is indexed.
For non-indexable types this is ``null``.
property name
readonly name: string;
The local name of the parameter (or ``""`` if unbound)
property type
readonly type: string;
The fully qualified type (e.g. ``"address"``, ``"tuple(address)"``, ``"uint256[3][]"``)
method format
format: (format?: FormatType) => string;
Return a string representation of this type.
For example,
``sighash" => "(uint256,address)"``
``"minimal" => "tuple(uint256,address) indexed"``
``"full" => "tuple(uint256 foo, address bar) indexed baz"``
method from
static from: (obj: any, allowIndexed?: boolean) => ParamType;
Creates a new **ParamType** for %%obj%%.
If %%allowIndexed%% then the ``indexed`` keyword is permitted, otherwise the ``indexed`` keyword will throw an error.
method isArray
isArray: () => this is ParamType & { arrayChildren: ParamType; arrayLength: number;};
Returns true if %%this%% is an Array type.
This provides a type gaurd ensuring that [[arrayChildren]] and [[arrayLength]] are non-null.
method isIndexable
isIndexable: () => this is ParamType & { indexed: boolean };
Returns true if %%this%% is an Indexable type.
This provides a type gaurd ensuring that [[indexed]] is non-null.
method isParamType
static isParamType: (value: any) => value is ParamType;
Returns true if %%value%% is a **ParamType**.
method isTuple
isTuple: () => this is ParamType & { components: ReadonlyArray<ParamType> };
Returns true if %%this%% is a Tuple type.
This provides a type gaurd ensuring that [[components]] is non-null.
method walk
walk: (value: any, process: ParamTypeWalkFunc) => any;
Walks the **ParamType** with %%value%%, calling %%process%% on each type, destructing the %%value%% recursively.
method walkAsync
walkAsync: (value: any, process: ParamTypeWalkAsyncFunc) => Promise<any>;
Walks the **ParamType** with %%value%%, asynchronously calling %%process%% on each type, destructing the %%value%% recursively.
This can be used to resolve ENS names by walking and resolving each ``"address"`` type.
class PocketProvider
class PocketProvider extends JsonRpcProvider implements CommunityResourcable {}
The **PocketProvider** connects to the [[link-pocket]] JSON-RPC end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-pocket-signup).
constructor
constructor( _network?: Networkish, applicationId?: string, applicationSecret?: string);
Create a new **PocketProvider**.
By default connecting to ``mainnet`` with a highly throttled API key.
property applicationId
readonly applicationId: string;
The Application ID for the Pocket connection.
property applicationSecret
readonly applicationSecret: string;
The Application Secret for making authenticated requests to the Pocket connection.
method getRequest
static getRequest: ( network: Network, applicationId?: null | string, applicationSecret?: null | string) => FetchRequest;
Returns a prepared request for connecting to %%network%% with %%applicationId%%.
method isCommunityResource
isCommunityResource: () => boolean;
class QuickNodeProvider
class QuickNodeProvider extends JsonRpcProvider implements CommunityResourcable {}
The **QuickNodeProvider** connects to the [[link-quicknode]] JSON-RPC end-points.
By default, a highly-throttled API token is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to [sign up here](link-quicknode).
constructor
constructor(_network?: Networkish, token?: string);
Creates a new **QuickNodeProvider**.
property token
readonly token: string;
The API token.
method getRequest
static getRequest: (network: Network, token?: null | string) => FetchRequest;
Returns a new request prepared for %%network%% and the %%token%%.
method isCommunityResource
isCommunityResource: () => boolean;
class Result
class Result extends Array<any> {}
A [[Result]] is a sub-class of Array, which allows accessing any of its values either positionally by its index or, if keys are provided by its name.
@_docloc: api/abi
constructor
constructor(...args: any[]);
method filter
filter: ( callback: (el: any, index: number, array: Result) => boolean, thisArg?: any) => Result;
@_ignore
method fromItems
static fromItems: (items: Array<any>, keys?: Array<null | string>) => Result;
Creates a new [[Result]] for %%items%% with each entry also accessible by its corresponding name in %%keys%%.
method getValue
getValue: (name: string) => any;
Returns the value for %%name%%.
Since it is possible to have a key whose name conflicts with a method on a [[Result]] or its superclass Array, or any JavaScript keyword, this ensures all named values are still accessible by name.
method map
map: <T extends unknown = any>( callback: (el: any, index: number, array: Result) => T, thisArg?: any) => Array<T>;
@_ignore
method slice
slice: (start?: number | undefined, end?: number | undefined) => Result;
@_ignore
method toArray
toArray: (deep?: boolean) => Array<any>;
Returns the Result as a normal Array. If %%deep%%, any children which are Result objects are also converted to a normal Array.
This will throw if there are any outstanding deferred errors.
method toObject
toObject: (deep?: boolean) => Record<string, any>;
Returns the Result as an Object with each name-value pair. If %%deep%%, any children which are Result objects are also converted to an Object.
This will throw if any value is unnamed, or if there are any outstanding deferred errors.
class Signature
class Signature {}
A Signature
@_docloc: api/crypto:Signing
constructor
constructor(guard: any, r: string, s: string, v: 27 | 28);
property compactSerialized
readonly compactSerialized: string;
The [[link-eip-2098]] compact representation.
property legacyChainId
readonly legacyChainId: BigInt;
The chain ID for EIP-155 legacy transactions. For non-legacy transactions, this value is ``null``.
property networkV
readonly networkV: BigInt;
The EIP-155 ``v`` for legacy transactions. For non-legacy transactions, this value is ``null``.
property r
r: string;
The ``r`` value for a signautre.
This represents the ``x`` coordinate of a "reference" or challenge point, from which the ``y`` can be computed.
property s
s: string;
The ``s`` value for a signature.
property serialized
readonly serialized: string;
The serialized representation.
property v
v: 27 | 28;
The ``v`` value for a signature.
Since a given ``x`` value for ``r`` has two possible values for its correspondin ``y``, the ``v`` indicates which of the two ``y`` values to use.
It is normalized to the values ``27`` or ``28`` for legacy purposes.
property yParity
readonly yParity: 0 | 1;
The ``yParity`` for the signature.
See ``v`` for more details on how this value is used.
property yParityAndS
readonly yParityAndS: string;
The [[link-eip-2098]] compact representation of the ``yParity`` and ``s`` compacted into a single ``bytes32``.
method clone
clone: () => Signature;
Returns a new identical [[Signature]].
method from
static from: (sig?: SignatureLike) => Signature;
Creates a new [[Signature]].
If no %%sig%% is provided, a new [[Signature]] is created with default values.
If %%sig%% is a string, it is parsed.
method getChainId
static getChainId: (v: BigNumberish) => bigint;
Compute the chain ID from the ``v`` in a legacy EIP-155 transactions.
@example: Signature.getChainId(45) //_result:
Signature.getChainId(46) //_result:
method getChainIdV
static getChainIdV: (chainId: BigNumberish, v: 27 | 28) => bigint;
Compute the ``v`` for a chain ID for a legacy EIP-155 transactions.
Legacy transactions which use [[link-eip-155]] hijack the ``v`` property to include the chain ID.
@example: Signature.getChainIdV(5, 27) //_result:
Signature.getChainIdV(5, 28) //_result:
method getNormalizedV
static getNormalizedV: (v: BigNumberish) => 27 | 28;
Compute the normalized legacy transaction ``v`` from a ``yParirty``, a legacy transaction ``v`` or a legacy [[link-eip-155]] transaction.
@example: // The values 0 and 1 imply v is actually yParity Signature.getNormalizedV(0) //_result:
// Legacy non-EIP-1559 transaction (i.e. 27 or 28) Signature.getNormalizedV(27) //_result:
// Legacy EIP-155 transaction (i.e. >= 35) Signature.getNormalizedV(46) //_result:
// Invalid values throw Signature.getNormalizedV(5) //_error:
method toJSON
toJSON: () => any;
Returns a representation that is compatible with ``JSON.stringify``.
class SigningKey
class SigningKey {}
A **SigningKey** provides high-level access to the elliptic curve cryptography (ECC) operations and key management.
constructor
constructor(privateKey: BytesLike);
Creates a new **SigningKey** for %%privateKey%%.
property compressedPublicKey
readonly compressedPublicKey: string;
The compressed public key.
This will always begin with either the prefix ``0x02`` or ``0x03`` and be 68 characters long (the ``0x`` prefix and 33 hexadecimal nibbles)
property privateKey
readonly privateKey: string;
The private key.
property publicKey
readonly publicKey: string;
The uncompressed public key.
This will always begin with the prefix ``0x04`` and be 132 characters long (the ``0x`` prefix and 130 hexadecimal nibbles).
method addPoints
static addPoints: (p0: BytesLike, p1: BytesLike, compressed?: boolean) => string;
Returns the point resulting from adding the ellipic curve points %%p0%% and %%p1%%.
This is not a common function most developers should require, but can be useful for certain privacy-specific techniques.
For example, it is used by [[HDNodeWallet]] to compute child addresses from parent public keys and chain codes.
method computePublicKey
static computePublicKey: (key: BytesLike, compressed?: boolean) => string;
Compute the public key for %%key%%, optionally %%compressed%%.
The %%key%% may be any type of key, a raw public key, a compressed/uncompressed public key or private key.
@example: sign = new SigningKey(id("some-secret"));
// Compute the uncompressed public key for a private key SigningKey.computePublicKey(sign.privateKey) //_result:
// Compute the compressed public key for a private key SigningKey.computePublicKey(sign.privateKey, true) //_result:
// Compute the uncompressed public key SigningKey.computePublicKey(sign.publicKey, false); //_result:
// Compute the Compressed a public key SigningKey.computePublicKey(sign.publicKey, true); //_result:
method computeSharedSecret
computeSharedSecret: (other: BytesLike) => string;
Returns the [[link-wiki-ecdh]] shared secret between this private key and the %%other%% key.
The %%other%% key may be any type of key, a raw public key, a compressed/uncompressed pubic key or aprivate key.
Best practice is usually to use a cryptographic hash on the returned value before using it as a symetric secret.
@example: sign1 = new SigningKey(id("some-secret-1")) sign2 = new SigningKey(id("some-secret-2"))
// Notice that privA.computeSharedSecret(pubB)... sign1.computeSharedSecret(sign2.publicKey) //_result:
// ...is equal to privB.computeSharedSecret(pubA). sign2.computeSharedSecret(sign1.publicKey) //_result:
method recoverPublicKey
static recoverPublicKey: (digest: BytesLike, signature: SignatureLike) => string;
Returns the public key for the private key which produced the %%signature%% for the given %%digest%%.
@example: key = new SigningKey(id("some-secret")) digest = id("hello world") sig = key.sign(digest)
// Notice the signer public key... key.publicKey //_result:
// ...is equal to the recovered public key SigningKey.recoverPublicKey(digest, sig) //_result:
method sign
sign: (digest: BytesLike) => Signature;
Return the signature of the signed %%digest%%.
class SocketBlockSubscriber
class SocketBlockSubscriber extends SocketSubscriber {}
A **SocketBlockSubscriber** listens for ``newHeads`` events and emits ``"block"`` events.
constructor
constructor(provider: SocketProvider);
@_ignore:
class SocketEventSubscriber
class SocketEventSubscriber extends SocketSubscriber {}
A **SocketEventSubscriber** listens for event logs.
constructor
constructor(provider: SocketProvider, filter: EventFilter);
@_ignore:
property logFilter
readonly logFilter: EventFilter;
The filter.
class SocketPendingSubscriber
class SocketPendingSubscriber extends SocketSubscriber {}
A **SocketPendingSubscriber** listens for pending transacitons and emits ``"pending"`` events.
constructor
constructor(provider: SocketProvider);
@_ignore:
class SocketProvider
class SocketProvider extends JsonRpcApiProvider {}
A **SocketProvider** is backed by a long-lived connection over a socket, which can subscribe and receive real-time messages over its communication channel.
constructor
constructor(network?: Networkish, _options?: JsonRpcApiProviderOptions);
Creates a new **SocketProvider** connected to %%network%%.
If unspecified, the network will be discovered.
class SocketSubscriber
class SocketSubscriber implements Subscriber {}
A **SocketSubscriber** uses a socket transport to handle events and should use [[_emit]] to manage the events.
constructor
constructor(provider: SocketProvider, filter: any[]);
Creates a new **SocketSubscriber** attached to %%provider%% listening to %%filter%%.
property filter
readonly filter: any[];
The filter.
method pause
pause: (dropWhilePaused?: boolean) => void;
method resume
resume: () => void;
method start
start: () => void;
method stop
stop: () => void;
class StructFragment
class StructFragment extends NamedFragment {}
A Fragment which represents a structure.
constructor
constructor(guard: any, name: string, inputs: readonly ParamType[]);
method format
format: () => string;
Returns a string representation of this struct as %%format%%.
method from
static from: (obj: any) => StructFragment;
Returns a new **StructFragment** for %%obj%%.
method isFragment
static isFragment: (value: any) => value is FunctionFragment;
Returns ``true`` and provides a type guard if %%value%% is a **StructFragment**.
class Transaction
class Transaction implements TransactionLike<string> {}
A **Transaction** describes an operation to be executed on Ethereum by an Externally Owned Account (EOA). It includes who (the [[to]] address), what (the [[data]]) and how much (the [[value]] in ether) the operation should entail.
@example: tx = new Transaction() //_result:
tx.data = "0x1234"; //_result:
constructor
constructor();
Creates a new Transaction with default values.
property accessList
accessList: AccessList;
The access list.
An access list permits discounted (but pre-paid) access to bytecode and state variable access within contract execution.
property blobs
blobs: Blob[];
The BLObs for the Transaction, if any.
If ``blobs`` is non-``null``, then the [[seriailized]] will return the network formatted sidecar, otherwise it will return the standard [[link-eip-2718]] payload. The [[unsignedSerialized]] is unaffected regardless.
When setting ``blobs``, either fully valid [[Blob]] objects may be specified (i.e. correctly padded, with correct committments and proofs) or a raw [[BytesLike]] may be provided.
If raw [[BytesLike]] are provided, the [[kzg]] property **must** be already set. The blob will be correctly padded and the [[KzgLibrary]] will be used to compute the committment and proof for the blob.
A BLOb is a sequence of field elements, each of which must be within the BLS field modulo, so some additional processing may be required to encode arbitrary data to ensure each 32 byte field is within the valid range.
Setting this automatically populates [[blobVersionedHashes]], overwriting any existing values. Setting this to ``null`` does **not** remove the [[blobVersionedHashes]], leaving them present.
property blobVersionedHashes
blobVersionedHashes: string[];
The BLOb versioned hashes for Cancun transactions.
property chainId
chainId: BigInt;
The chain ID this transaction is valid on.
property data
data: string;
The transaction data. For ``init`` transactions this is the deployment code.
property from
readonly from: string;
The sending address, if signed. Otherwise, ``null``.
property fromPublicKey
readonly fromPublicKey: string;
The public key of the sender, if signed. Otherwise, ``null``.
property gasLimit
gasLimit: BigInt;
The gas limit.
property gasPrice
gasPrice: BigInt;
The gas price.
On legacy networks this defines the fee that will be paid. On EIP-1559 networks, this should be ``null``.
property hash
readonly hash: string;
The transaction hash, if signed. Otherwise, ``null``.
property kzg
kzg: KzgLibrary;
property maxFeePerBlobGas
maxFeePerBlobGas: BigInt;
The max fee per blob gas for Cancun transactions.
property maxFeePerGas
maxFeePerGas: BigInt;
The maximum total fee per unit of gas to pay. On legacy networks this should be ``null``.
property maxPriorityFeePerGas
maxPriorityFeePerGas: BigInt;
The maximum priority fee per unit of gas to pay. On legacy networks this should be ``null``.
property nonce
nonce: number;
The transaction nonce.
property serialized
readonly serialized: string;
The serialized transaction.
This throws if the transaction is unsigned. For the pre-image, use [[unsignedSerialized]].
property signature
signature: Signature;
If signed, the signature for this transaction.
property to
to: string;
The ``to`` address for the transaction or ``null`` if the transaction is an ``init`` transaction.
property type
type: number;
The transaction type.
If null, the type will be automatically inferred based on explicit properties.
property typeName
readonly typeName: string;
The name of the transaction type.
property unsignedHash
readonly unsignedHash: string;
The pre-image hash of this transaction.
This is the digest that a [[Signer]] must sign to authorize this transaction.
property unsignedSerialized
readonly unsignedSerialized: string;
The transaction pre-image.
The hash of this is the digest which needs to be signed to authorize this transaction.
property value
value: BigInt;
The amount of ether (in wei) to send in this transactions.
method clone
clone: () => Transaction;
Create a copy of this transaciton.
method from
static from: (tx?: string | TransactionLike<string>) => Transaction;
Create a **Transaction** from a serialized transaction or a Transaction-like object.
method inferType
inferType: () => number;
Return the most "likely" type; currently the highest supported transaction type.
method inferTypes
inferTypes: () => Array<number>;
Validates the explicit properties and returns a list of compatible transaction types.
method isBerlin
isBerlin: () => this is Transaction & { type: 1; gasPrice: bigint; accessList: AccessList;};
Returns true if this transaction is berlin hardform transaction (i.e. ``type === 1``).
This provides a Type Guard that the related properties are non-null.
method isCancun
isCancun: () => this is Transaction & { type: 3; to: string; accessList: AccessList; maxFeePerGas: bigint; maxPriorityFeePerGas: bigint; maxFeePerBlobGas: bigint; blobVersionedHashes: Array<string>;};
Returns true if this transaction is an [[link-eip-4844]] BLOB transaction.
This provides a Type Guard that the related properties are non-null.
method isLegacy
isLegacy: () => this is Transaction & { type: 0; gasPrice: bigint };
Returns true if this transaction is a legacy transaction (i.e. ``type === 0``).
This provides a Type Guard that the related properties are non-null.
method isLondon
isLondon: () => this is Transaction & { type: 2; accessList: AccessList; maxFeePerGas: bigint; maxPriorityFeePerGas: bigint;};
Returns true if this transaction is london hardform transaction (i.e. ``type === 2``).
This provides a Type Guard that the related properties are non-null.
method isSigned
isSigned: () => this is Transaction & { type: number; typeName: string; from: string; signature: Signature;};
Returns true if signed.
This provides a Type Guard that properties requiring a signed transaction are non-null.
method toJSON
toJSON: () => any;
Return a JSON-friendly object.
class TransactionDescription
class TransactionDescription {}
When using the [[Interface-parseTransaction]] to automatically match a transaction data to its function for parsing, a **TransactionDescription** is returned.
constructor
constructor( fragment: FunctionFragment, selector: string, args: Result, value: BigInt);
@_ignore:
property args
readonly args: Result;
The arguments passed to the Function from the transaction ``data``.
property fragment
readonly fragment: FunctionFragment;
The matching fragment from the transaction ``data``.
property name
readonly name: string;
The name of the Function from the transaction ``data``.
property selector
readonly selector: string;
The selector for the Function from the transaction ``data``.
property signature
readonly signature: string;
The full Function signature from the transaction ``data``.
property value
readonly value: BigInt;
The ``value`` (in wei) from the transaction.
class TransactionReceipt
class TransactionReceipt implements TransactionReceiptParams, Iterable<Log> {}
A **TransactionReceipt** includes additional information about a transaction that is only available after it has been mined.
constructor
constructor(tx: TransactionReceiptParams, provider: Provider);
@_ignore:
property blobGasPrice
readonly blobGasPrice: BigInt;
The price paid per BLOB in gas. See [[link-eip-4844]].
property blobGasUsed
readonly blobGasUsed: BigInt;
The gas used for BLObs. See [[link-eip-4844]].
property blockHash
readonly blockHash: string;
The block hash of the [[Block]] this transaction was included in.
property blockNumber
readonly blockNumber: number;
The block number of the [[Block]] this transaction was included in.
property contractAddress
readonly contractAddress: string;
The address of the contract if the transaction was directly responsible for deploying one.
This is non-null **only** if the ``to`` is empty and the ``data`` was successfully executed as initcode.
property cumulativeGasUsed
readonly cumulativeGasUsed: BigInt;
The amount of gas used by all transactions within the block for this and all transactions with a lower ``index``.
This is generally not useful for developers but can be used to validate certain aspects of execution.
property fee
readonly fee: BigInt;
The total fee for this transaction, in wei.
property from
readonly from: string;
The sender of the transaction.
property gasPrice
readonly gasPrice: BigInt;
The actual gas price used during execution.
Due to the complexity of [[link-eip-1559]] this value can only be caluclated after the transaction has been mined, snce the base fee is protocol-enforced.
property gasUsed
readonly gasUsed: BigInt;
The actual amount of gas used by this transaction.
When creating a transaction, the amount of gas that will be used can only be approximated, but the sender must pay the gas fee for the entire gas limit. After the transaction, the difference is refunded.
property hash
readonly hash: string;
The transaction hash.
property index
readonly index: number;
The index of this transaction within the block transactions.
property length
readonly length: number;
@_ignore:
property logs
readonly logs: readonly Log[];
The logs for this transaction.
property logsBloom
readonly logsBloom: string;
The bloom filter bytes that represent all logs that occurred within this transaction. This is generally not useful for most developers, but can be used to validate the included logs.
property provider
readonly provider: Provider;
The provider connected to the log used to fetch additional details if necessary.
property root
readonly root: string;
The root hash of this transaction.
This is no present and was only included in pre-byzantium blocks, but could be used to validate certain parts of the receipt.
property status
readonly status: number;
The status of this transaction, indicating success (i.e. ``1``) or a revert (i.e. ``0``).
This is available in post-byzantium blocks, but some backends may backfill this value.
property to
readonly to: string;
The address the transaction was sent to.
property type
readonly type: number;
The [[link-eip-2718]] transaction type.
method [Symbol.iterator]
[Symbol.iterator]: () => Iterator<Log>;
method confirmations
confirmations: () => Promise<number>;
Resolves to the number of confirmations this transaction has.
method getBlock
getBlock: () => Promise<Block>;
Resolves to the block this transaction occurred in.
method getResult
getResult: () => Promise<string>;
Resolves to the return value of the execution of this transaction.
Support for this feature is limited, as it requires an archive node with the ``debug_`` or ``trace_`` API enabled.
method getTransaction
getTransaction: () => Promise<TransactionResponse>;
Resolves to the transaction this transaction occurred in.
method removedEvent
removedEvent: () => OrphanFilter;
@_ignore:
method reorderedEvent
reorderedEvent: (other?: TransactionResponse) => OrphanFilter;
@_ignore:
method toJSON
toJSON: () => any;
Returns a JSON-compatible representation.
class TransactionResponse
class TransactionResponse implements TransactionLike<string>, TransactionResponseParams {}
A **TransactionResponse** includes all properties about a transaction that was sent to the network, which may or may not be included in a block.
The [[TransactionResponse-isMined]] can be used to check if the transaction has been mined as well as type guard that the otherwise possibly ``null`` properties are defined.
constructor
constructor(tx: TransactionResponseParams, provider: Provider);
@_ignore:
property accessList
readonly accessList: AccessList;
The [[link-eip-2930]] access list for transaction types that support it, otherwise ``null``.
property blobVersionedHashes
readonly blobVersionedHashes: string[];
The [[link-eip-4844]] BLOb versioned hashes.
property blockHash
readonly blockHash: string;
The blockHash of the block that this transaction was included in.
This is ``null`` for pending transactions.
property blockNumber
readonly blockNumber: number;
The block number of the block that this transaction was included in.
This is ``null`` for pending transactions.
property chainId
readonly chainId: BigInt;
The chain ID.
property data
readonly data: string;
The data.
property from
readonly from: string;
The sender of this transaction. It is implicitly computed from the transaction pre-image hash (as the digest) and the [[signature]] using ecrecover.
property gasLimit
readonly gasLimit: BigInt;
The maximum units of gas this transaction can consume. If execution exceeds this, the entries transaction is reverted and the sender is charged for the full amount, despite not state changes being made.
property gasPrice
readonly gasPrice: BigInt;
The gas price can have various values, depending on the network.
In modern networks, for transactions that are included this is the //effective gas price// (the fee per gas that was actually charged), while for transactions that have not been included yet is the [[maxFeePerGas]].
For legacy transactions, or transactions on legacy networks, this is the fee that will be charged per unit of gas the transaction consumes.
property hash
readonly hash: string;
The transaction hash.
property index
readonly index: number;
The index within the block that this transaction resides at.
property maxFeePerBlobGas
readonly maxFeePerBlobGas: BigInt;
The [[link-eip-4844]] max fee per BLOb gas.
property maxFeePerGas
readonly maxFeePerGas: BigInt;
The maximum fee (per unit of gas) to allow this transaction to charge the sender.
property maxPriorityFeePerGas
readonly maxPriorityFeePerGas: BigInt;
The maximum priority fee (per unit of gas) to allow a validator to charge the sender. This is inclusive of the [[maxFeeFeePerGas]].
property nonce
readonly nonce: number;
The nonce, which is used to prevent replay attacks and offer a method to ensure transactions from a given sender are explicitly ordered.
When sending a transaction, this must be equal to the number of transactions ever sent by [[from]].
property provider
readonly provider: Provider;
The provider this is connected to, which will influence how its methods will resolve its async inspection methods.
property signature
readonly signature: Signature;
The signature.
property to
readonly to: string;
The receiver of this transaction.
If ``null``, then the transaction is an initcode transaction. This means the result of executing the [[data]] will be deployed as a new contract on chain (assuming it does not revert) and the address may be computed using [[getCreateAddress]].
property type
readonly type: number;
The [[link-eip-2718]] transaction envelope type. This is ``0`` for legacy transactions types.
property value
readonly value: BigInt;
The value, in wei. Use [[formatEther]] to format this value as ether.
method confirmations
confirmations: () => Promise<number>;
Resolve to the number of confirmations this transaction has.
method getBlock
getBlock: () => Promise<null | Block>;
Resolves to the Block that this transaction was included in.
This will return null if the transaction has not been included yet.
method getTransaction
getTransaction: () => Promise<null | TransactionResponse>;
Resolves to this transaction being re-requested from the provider. This can be used if you have an unmined transaction and wish to get an up-to-date populated instance.
method isBerlin
isBerlin: () => this is never;
Returns true if the transaction is a Berlin (i.e. ``type == 1``) transaction. See [[link-eip-2070]].
This provides a Type Guard that this transaction will have the ``null``-ness for hardfork-specific properties set correctly.
method isCancun
isCancun: () => this is TransactionResponse & { accessList: AccessList; maxFeePerGas: bigint; maxPriorityFeePerGas: bigint; maxFeePerBlobGas: bigint; blobVersionedHashes: Array<string>;};
Returns true if hte transaction is a Cancun (i.e. ``type == 3``) transaction. See [[link-eip-4844]].
method isLegacy
isLegacy: () => this is never;
Returns true if the transaction is a legacy (i.e. ``type == 0``) transaction.
This provides a Type Guard that this transaction will have the ``null``-ness for hardfork-specific properties set correctly.
method isLondon
isLondon: () => this is TransactionResponse & { accessList: AccessList; maxFeePerGas: bigint; maxPriorityFeePerGas: bigint;};
Returns true if the transaction is a London (i.e. ``type == 2``) transaction. See [[link-eip-1559]].
This provides a Type Guard that this transaction will have the ``null``-ness for hardfork-specific properties set correctly.
method isMined
isMined: () => this is MinedTransactionResponse;
Returns ``true`` if this transaction has been included.
This is effective only as of the time the TransactionResponse was instantiated. To get up-to-date information, use [[getTransaction]].
This provides a Type Guard that this transaction will have non-null property values for properties that are null for unmined transactions.
method removedEvent
removedEvent: () => OrphanFilter;
Returns a filter which can be used to listen for orphan events that evict this transaction.
method reorderedEvent
reorderedEvent: (other?: TransactionResponse) => OrphanFilter;
Returns a filter which can be used to listen for orphan events that re-order this event against %%other%%.
method replaceableTransaction
replaceableTransaction: (startBlock: number) => TransactionResponse;
Returns a new TransactionResponse instance which has the ability to detect (and throw an error) if the transaction is replaced, which will begin scanning at %%startBlock%%.
This should generally not be used by developers and is intended primarily for internal use. Setting an incorrect %%startBlock%% can have devastating performance consequences if used incorrectly.
method toJSON
toJSON: () => any;
Returns a JSON-compatible representation of this transaction.
method wait
wait: ( _confirms?: number, _timeout?: number) => Promise<null | TransactionReceipt>;
Resolves once this transaction has been mined and has %%confirms%% blocks including it (default: ``1``) with an optional %%timeout%%.
This can resolve to ``null`` only if %%confirms%% is ``0`` and the transaction has not been mined, otherwise this will wait until enough confirmations have completed.
class Typed
class Typed {}
The **Typed** class to wrap values providing explicit type information.
constructor
constructor(gaurd: any, type: string, value: any, options?: any);
@_ignore:
property arrayLength
readonly arrayLength: number;
Returns the length of the array type or ``-1`` if it is dynamic.
Throws if the type is not an array.
property tupleName
readonly tupleName: string;
Returns the tuple name, if this is a tuple. Throws otherwise.
property type
readonly type: string;
The type, as a Solidity-compatible type.
property value
readonly value: any;
The actual value.
method address
static address: (v: string | Addressable) => Typed;
Return a new ``address`` type for %%v%%.
method array
static array: (v: Array<any | Typed>, dynamic?: null | boolean) => Typed;
Return a new ``array`` type for %%v%%, allowing %%dynamic%% length.
method bool
static bool: (v: any) => Typed;
Return a new ``bool`` type for %%v%%.
method bytes
static bytes: (v: BytesLike) => Typed;
Return a new ``bytes`` type for %%v%%.
method bytes1
static bytes1: (v: BytesLike) => Typed;
Return a new ``bytes1`` type for %%v%%.
method bytes10
static bytes10: (v: BytesLike) => Typed;
Return a new ``bytes10`` type for %%v%%.
method bytes11
static bytes11: (v: BytesLike) => Typed;
Return a new ``bytes11`` type for %%v%%.
method bytes12
static bytes12: (v: BytesLike) => Typed;
Return a new ``bytes12`` type for %%v%%.
method bytes13
static bytes13: (v: BytesLike) => Typed;
Return a new ``bytes13`` type for %%v%%.
method bytes14
static bytes14: (v: BytesLike) => Typed;
Return a new ``bytes14`` type for %%v%%.
method bytes15
static bytes15: (v: BytesLike) => Typed;
Return a new ``bytes15`` type for %%v%%.
method bytes16
static bytes16: (v: BytesLike) => Typed;
Return a new ``bytes16`` type for %%v%%.
method bytes17
static bytes17: (v: BytesLike) => Typed;
Return a new ``bytes17`` type for %%v%%.
method bytes18
static bytes18: (v: BytesLike) => Typed;
Return a new ``bytes18`` type for %%v%%.
method bytes19
static bytes19: (v: BytesLike) => Typed;
Return a new ``bytes19`` type for %%v%%.
method bytes2
static bytes2: (v: BytesLike) => Typed;
Return a new ``bytes2`` type for %%v%%.
method bytes20
static bytes20: (v: BytesLike) => Typed;
Return a new ``bytes20`` type for %%v%%.
method bytes21
static bytes21: (v: BytesLike) => Typed;
Return a new ``bytes21`` type for %%v%%.
method bytes22
static bytes22: (v: BytesLike) => Typed;
Return a new ``bytes22`` type for %%v%%.
method bytes23
static bytes23: (v: BytesLike) => Typed;
Return a new ``bytes23`` type for %%v%%.
method bytes24
static bytes24: (v: BytesLike) => Typed;
Return a new ``bytes24`` type for %%v%%.
method bytes25
static bytes25: (v: BytesLike) => Typed;
Return a new ``bytes25`` type for %%v%%.
method bytes26
static bytes26: (v: BytesLike) => Typed;
Return a new ``bytes26`` type for %%v%%.
method bytes27
static bytes27: (v: BytesLike) => Typed;
Return a new ``bytes27`` type for %%v%%.
method bytes28
static bytes28: (v: BytesLike) => Typed;
Return a new ``bytes28`` type for %%v%%.
method bytes29
static bytes29: (v: BytesLike) => Typed;
Return a new ``bytes29`` type for %%v%%.
method bytes3
static bytes3: (v: BytesLike) => Typed;
Return a new ``bytes3`` type for %%v%%.
method bytes30
static bytes30: (v: BytesLike) => Typed;
Return a new ``bytes30`` type for %%v%%.
method bytes31
static bytes31: (v: BytesLike) => Typed;
Return a new ``bytes31`` type for %%v%%.
method bytes32
static bytes32: (v: BytesLike) => Typed;
Return a new ``bytes32`` type for %%v%%.
method bytes4
static bytes4: (v: BytesLike) => Typed;
Return a new ``bytes4`` type for %%v%%.
method bytes5
static bytes5: (v: BytesLike) => Typed;
Return a new ``bytes5`` type for %%v%%.
method bytes6
static bytes6: (v: BytesLike) => Typed;
Return a new ``bytes6`` type for %%v%%.
method bytes7
static bytes7: (v: BytesLike) => Typed;
Return a new ``bytes7`` type for %%v%%.
method bytes8
static bytes8: (v: BytesLike) => Typed;
Return a new ``bytes8`` type for %%v%%.
method bytes9
static bytes9: (v: BytesLike) => Typed;
Return a new ``bytes9`` type for %%v%%.
method defaultValue
defaultValue: () => string | number | bigint | Result;
The default value returned by this type.
method dereference
static dereference: <T>(value: Typed | T, type: string) => T;
If the value is a [[Typed]] instance, validates the underlying value and returns it, otherwise returns value directly.
This is useful for functions that with to accept either a [[Typed]] object or values.
method format
format: () => string;
Format the type as a Human-Readable type.
method from
static from: (type: string, value: any) => Typed;
Returns a new **Typed** of %%type%% with the %%value%%.
method int
static int: (v: BigNumberish) => Typed;
Return a new ``int256`` type for %%v%%.
method int104
static int104: (v: BigNumberish) => Typed;
Return a new ``int104`` type for %%v%%.
method int112
static int112: (v: BigNumberish) => Typed;
Return a new ``int112`` type for %%v%%.
method int120
static int120: (v: BigNumberish) => Typed;
Return a new ``int120`` type for %%v%%.
method int128
static int128: (v: BigNumberish) => Typed;
Return a new ``int128`` type for %%v%%.
method int136
static int136: (v: BigNumberish) => Typed;
Return a new ``int136`` type for %%v%%.
method int144
static int144: (v: BigNumberish) => Typed;
Return a new ``int144`` type for %%v%%.
method int152
static int152: (v: BigNumberish) => Typed;
Return a new ``int52`` type for %%v%%.
method int16
static int16: (v: BigNumberish) => Typed;
Return a new ``int16`` type for %%v%%.
method int160
static int160: (v: BigNumberish) => Typed;
Return a new ``int160`` type for %%v%%.
method int168
static int168: (v: BigNumberish) => Typed;
Return a new ``int168`` type for %%v%%.
method int176
static int176: (v: BigNumberish) => Typed;
Return a new ``int176`` type for %%v%%.
method int184
static int184: (v: BigNumberish) => Typed;
Return a new ``int184`` type for %%v%%.
method int192
static int192: (v: BigNumberish) => Typed;
Return a new ``int92`` type for %%v%%.
method int200
static int200: (v: BigNumberish) => Typed;
Return a new ``int200`` type for %%v%%.
method int208
static int208: (v: BigNumberish) => Typed;
Return a new ``int208`` type for %%v%%.
method int216
static int216: (v: BigNumberish) => Typed;
Return a new ``int216`` type for %%v%%.
method int224
static int224: (v: BigNumberish) => Typed;
Return a new ``int224`` type for %%v%%.
method int232
static int232: (v: BigNumberish) => Typed;
Return a new ``int232`` type for %%v%%.
method int24
static int24: (v: BigNumberish) => Typed;
Return a new ``int24`` type for %%v%%.
method int240
static int240: (v: BigNumberish) => Typed;
Return a new ``int240`` type for %%v%%.
method int248
static int248: (v: BigNumberish) => Typed;
Return a new ``int248`` type for %%v%%.
method int256
static int256: (v: BigNumberish) => Typed;
Return a new ``int256`` type for %%v%%.
method int32
static int32: (v: BigNumberish) => Typed;
Return a new ``int32`` type for %%v%%.
method int40
static int40: (v: BigNumberish) => Typed;
Return a new ``int40`` type for %%v%%.
method int48
static int48: (v: BigNumberish) => Typed;
Return a new ``int48`` type for %%v%%.
method int56
static int56: (v: BigNumberish) => Typed;
Return a new ``int56`` type for %%v%%.
method int64
static int64: (v: BigNumberish) => Typed;
Return a new ``int64`` type for %%v%%.
method int72
static int72: (v: BigNumberish) => Typed;
Return a new ``int72`` type for %%v%%.
method int8
static int8: (v: BigNumberish) => Typed;
Return a new ``int8`` type for %%v%%.
method int80
static int80: (v: BigNumberish) => Typed;
Return a new ``int80`` type for %%v%%.
method int88
static int88: (v: BigNumberish) => Typed;
Return a new ``int88`` type for %%v%%.
method int96
static int96: (v: BigNumberish) => Typed;
Return a new ``int96`` type for %%v%%.
method isBigInt
isBigInt: () => this is TypedBigInt;
Returns ``true`` and provides a type guard is this is a [[TypedBigInt]].
method isData
isData: () => this is TypedData;
Returns ``true`` and provides a type guard is this is a [[TypedData]].
method isString
isString: () => this is TypedString;
Returns ``true`` and provides a type guard is this is a [[TypedString]].
method isTyped
static isTyped: (value: any) => value is Typed;
Returns true only if %%value%% is a [[Typed]] instance.
method maxValue
maxValue: () => string | number | bigint;
The maximum value for numeric types.
method minValue
minValue: () => string | number | bigint;
The minimum value for numeric types.
method overrides
static overrides: (v: Record<string, any>) => Typed;
Return a new ``uint8`` type for %%v%%.
method string
static string: (v: string) => Typed;
Return a new ``string`` type for %%v%%.
method tuple
static tuple: ( v: Array<any | Typed> | Record<string, any | Typed>, name?: string) => Typed;
Return a new ``tuple`` type for %%v%%, with the optional %%name%%.
method uint
static uint: (v: BigNumberish) => Typed;
Return a new ``uint256`` type for %%v%%.
method uint104
static uint104: (v: BigNumberish) => Typed;
Return a new ``uint104`` type for %%v%%.
method uint112
static uint112: (v: BigNumberish) => Typed;
Return a new ``uint112`` type for %%v%%.
method uint120
static uint120: (v: BigNumberish) => Typed;
Return a new ``uint120`` type for %%v%%.
method uint128
static uint128: (v: BigNumberish) => Typed;
Return a new ``uint128`` type for %%v%%.
method uint136
static uint136: (v: BigNumberish) => Typed;
Return a new ``uint136`` type for %%v%%.
method uint144
static uint144: (v: BigNumberish) => Typed;
Return a new ``uint144`` type for %%v%%.
method uint152
static uint152: (v: BigNumberish) => Typed;
Return a new ``uint152`` type for %%v%%.
method uint16
static uint16: (v: BigNumberish) => Typed;
Return a new ``uint16`` type for %%v%%.
method uint160
static uint160: (v: BigNumberish) => Typed;
Return a new ``uint160`` type for %%v%%.
method uint168
static uint168: (v: BigNumberish) => Typed;
Return a new ``uint168`` type for %%v%%.
method uint176
static uint176: (v: BigNumberish) => Typed;
Return a new ``uint176`` type for %%v%%.
method uint184
static uint184: (v: BigNumberish) => Typed;
Return a new ``uint184`` type for %%v%%.
method uint192
static uint192: (v: BigNumberish) => Typed;
Return a new ``uint192`` type for %%v%%.
method uint200
static uint200: (v: BigNumberish) => Typed;
Return a new ``uint200`` type for %%v%%.
method uint208
static uint208: (v: BigNumberish) => Typed;
Return a new ``uint208`` type for %%v%%.
method uint216
static uint216: (v: BigNumberish) => Typed;
Return a new ``uint216`` type for %%v%%.
method uint224
static uint224: (v: BigNumberish) => Typed;
Return a new ``uint224`` type for %%v%%.
method uint232
static uint232: (v: BigNumberish) => Typed;
Return a new ``uint232`` type for %%v%%.
method uint24
static uint24: (v: BigNumberish) => Typed;
Return a new ``uint24`` type for %%v%%.
method uint240
static uint240: (v: BigNumberish) => Typed;
Return a new ``uint240`` type for %%v%%.
method uint248
static uint248: (v: BigNumberish) => Typed;
Return a new ``uint248`` type for %%v%%.
method uint256
static uint256: (v: BigNumberish) => Typed;
Return a new ``uint256`` type for %%v%%.
method uint32
static uint32: (v: BigNumberish) => Typed;
Return a new ``uint32`` type for %%v%%.
method uint40
static uint40: (v: BigNumberish) => Typed;
Return a new ``uint40`` type for %%v%%.
method uint48
static uint48: (v: BigNumberish) => Typed;
Return a new ``uint48`` type for %%v%%.
method uint56
static uint56: (v: BigNumberish) => Typed;
Return a new ``uint56`` type for %%v%%.
method uint64
static uint64: (v: BigNumberish) => Typed;
Return a new ``uint64`` type for %%v%%.
method uint72
static uint72: (v: BigNumberish) => Typed;
Return a new ``uint72`` type for %%v%%.
method uint8
static uint8: (v: BigNumberish) => Typed;
Return a new ``uint8`` type for %%v%%.
method uint80
static uint80: (v: BigNumberish) => Typed;
Return a new ``uint80`` type for %%v%%.
method uint88
static uint88: (v: BigNumberish) => Typed;
Return a new ``uint88`` type for %%v%%.
method uint96
static uint96: (v: BigNumberish) => Typed;
Return a new ``uint96`` type for %%v%%.
class TypedDataEncoder
class TypedDataEncoder {}
A **TypedDataEncode** prepares and encodes [[link-eip-712]] payloads for signed typed data.
This is useful for those that wish to compute various components of a typed data hash, primary types, or sub-components, but generally the higher level [[Signer-signTypedData]] is more useful.
constructor
constructor(_types: Record<string, TypedDataField[]>);
Create a new **TypedDataEncoder** for %%types%%.
This performs all necessary checking that types are valid and do not violate the [[link-eip-712]] structural constraints as well as computes the [[primaryType]].
property primaryType
readonly primaryType: string;
The primary type for the structured [[types]].
This is derived automatically from the [[types]], since no recursion is possible, once the DAG for the types is consturcted internally, the primary type must be the only remaining type with no parent nodes.
property types
readonly types: Record<string, TypedDataField[]>;
The types.
method encode
static encode: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => string;
Return the fulled encoded %%value%% for the [[types]].
Return the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%.
method encodeData
encodeData: (type: string, value: any) => string;
Return the encoded %%value%% for the %%type%%.
method encodeType
encodeType: (name: string) => string;
Return the full type for %%name%%.
method from
static from: (types: Record<string, Array<TypedDataField>>) => TypedDataEncoder;
Create a new **TypedDataEncoder** for %%types%%.
method getEncoder
getEncoder: (type: string) => (value: any) => string;
Returnthe encoder for the specific %%type%%.
method getPayload
static getPayload: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => any;
Returns the JSON-encoded payload expected by nodes which implement the JSON-RPC [[link-eip-712]] method.
method getPrimaryType
static getPrimaryType: (types: Record<string, Array<TypedDataField>>) => string;
Return the primary type for %%types%%.
method hash
static hash: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => string;
Return the hash of the fully encoded %%value%% for the [[types]].
Return the hash of the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%.
method hashDomain
static hashDomain: (domain: TypedDataDomain) => string;
Return the domain hash for %%domain%%.
method hashStruct
static hashStruct: ( name: string, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => string;
Returns the hash of %%value%% for the type of %%name%%.
Return the hashed struct for %%value%% using %%types%% and %%name%%.
method resolveNames
static resolveNames: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>, resolveName: (name: string) => Promise<string>) => Promise<{ domain: TypedDataDomain; value: any }>;
Resolves to the value from resolving all addresses in %%value%% for %%types%% and the %%domain%%.
method visit
visit: ( value: Record<string, any>, callback: (type: string, data: any) => any) => any;
Call %%calback%% for each value in %%value%%, passing the type and component within %%value%%.
This is useful for replacing addresses or other transformation that may be desired on each component, based on its type.
class UndecodedEventLog
class UndecodedEventLog extends Log {}
An **EventLog** contains additional properties parsed from the [[Log]].
constructor
constructor(log: Log, error: Error);
@_ignore:
property error
readonly error: Error;
The error encounted when trying to decode the log.
class UnmanagedSubscriber
class UnmanagedSubscriber implements Subscriber {}
An **UnmanagedSubscriber** is useful for events which do not require any additional management, such as ``"debug"`` which only requires emit in synchronous event loop triggered calls.
class VoidSigner
class VoidSigner extends AbstractSigner {}
A **VoidSigner** is a class deisgned to allow an address to be used in any API which accepts a Signer, but for which there are no credentials available to perform any actual signing.
This for example allow impersonating an account for the purpose of static calls or estimating gas, but does not allow sending transactions.
constructor
constructor(address: string, provider?: Provider);
Creates a new **VoidSigner** with %%address%% attached to %%provider%%.
property address
readonly address: string;
The signer address.
method connect
connect: (provider: null | Provider) => VoidSigner;
method getAddress
getAddress: () => Promise<string>;
method signMessage
signMessage: (message: string | Uint8Array) => Promise<string>;
method signTransaction
signTransaction: (tx: TransactionRequest) => Promise<string>;
method signTypedData
signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => Promise<string>;
class Wallet
class Wallet extends BaseWallet {}
A **Wallet** manages a single private key which is used to sign transactions, messages and other common payloads.
This class is generally the main entry point for developers that wish to use a private key directly, as it can create instances from a large variety of common sources, including raw private key, [[link-bip-39]] mnemonics and encrypte JSON wallets.
constructor
constructor(key: string | SigningKey, provider?: Provider);
Create a new wallet for the private %%key%%, optionally connected to %%provider%%.
method connect
connect: (provider: null | Provider) => Wallet;
method createRandom
static createRandom: (provider?: null | Provider) => HDNodeWallet;
Creates a new random [[HDNodeWallet]] using the available [cryptographic random source](randomBytes).
If there is no crytographic random source, this will throw.
method encrypt
encrypt: ( password: Uint8Array | string, progressCallback?: ProgressCallback) => Promise<string>;
Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with %%password%%.
If %%progressCallback%% is specified, it will receive periodic updates as the encryption process progreses.
method encryptSync
encryptSync: (password: Uint8Array | string) => string;
Returns a [JSON Keystore Wallet](json-wallets) encryped with %%password%%.
It is preferred to use the [async version](encrypt) instead, which allows a [[ProgressCallback]] to keep the user informed.
This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial duration.
method fromEncryptedJson
static fromEncryptedJson: ( json: string, password: Uint8Array | string, progress?: ProgressCallback) => Promise<HDNodeWallet | Wallet>;
Creates (asynchronously) a **Wallet** by decrypting the %%json%% with %%password%%.
If %%progress%% is provided, it is called periodically during decryption so that any UI can be updated.
method fromEncryptedJsonSync
static fromEncryptedJsonSync: ( json: string, password: Uint8Array | string) => HDNodeWallet | Wallet;
Creates a **Wallet** by decrypting the %%json%% with %%password%%.
The [[fromEncryptedJson]] method is preferred, as this method will lock up and freeze the UI during decryption, which may take some time.
method fromPhrase
static fromPhrase: (phrase: string, provider?: Provider) => HDNodeWallet;
Creates a [[HDNodeWallet]] for %%phrase%%.
class WebSocketProvider
class WebSocketProvider extends SocketProvider {}
A JSON-RPC provider which is backed by a WebSocket.
WebSockets are often preferred because they retain a live connection to a server, which permits more instant access to events.
However, this incurs higher server infrasturture costs, so additional resources may be required to host your own WebSocket nodes and many third-party services charge additional fees for WebSocket endpoints.
constructor
constructor( url: string | WebSocketLike | WebSocketCreator, network?: Networkish, options?: JsonRpcApiProviderOptions);
property websocket
readonly websocket: WebSocketLike;
method destroy
destroy: () => Promise<void>;
class Wordlist
abstract class Wordlist {}
A Wordlist represents a collection of language-specific words used to encode and devoce [[link-bip-39]] encoded data by mapping words to 11-bit values and vice versa.
constructor
constructor(locale: string);
Creates a new Wordlist instance.
Sub-classes MUST call this if they provide their own constructor, passing in the locale string of the language.
Generally there is no need to create instances of a Wordlist, since each language-specific Wordlist creates an instance and there is no state kept internally, so they are safe to share.
property locale
locale: string;
method getWord
abstract getWord: (index: number) => string;
Maps an 11-bit value into its coresponding word in the list.
Sub-classes MUST override this.
method getWordIndex
abstract getWordIndex: (word: string) => number;
Maps a word to its corresponding 11-bit value.
Sub-classes MUST override this.
method join
join: (words: Array<string>) => string;
Sub-classes may override this to provider a language-specific method for joining %%words%% into a phrase.
By default, %%words%% are joined by a single space.
method split
split: (phrase: string) => Array<string>;
Sub-classes may override this to provide a language-specific method for spliting %%phrase%% into individual words.
By default, %%phrase%% is split using any sequences of white-space as defined by regular expressions (i.e. ``/\s+/``).
class WordlistOwl
class WordlistOwl extends Wordlist {}
An OWL format Wordlist is an encoding method that exploits the general locality of alphabetically sorted words to achieve a simple but effective means of compression.
This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages based on ASCII-7 small.
If necessary, there are tools within the ``generation/`` folder to create the necessary data.
constructor
constructor(locale: string, data: string, checksum: string);
Creates a new Wordlist for %%locale%% using the OWL %%data%% and validated against the %%checksum%%.
method getWord
getWord: (index: number) => string;
method getWordIndex
getWordIndex: (word: string) => number;
class WordlistOwlA
class WordlistOwlA extends WordlistOwl {}
An OWL-A format Wordlist extends the OWL format to add an overlay onto an OWL format Wordlist to support diacritic marks.
This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages based on latin-1 small.
If necessary, there are tools within the ``generation/`` folder to create the necessary data.
constructor
constructor(locale: string, data: string, accent: string, checksum: string);
Creates a new Wordlist for %%locale%% using the OWLA %%data%% and %%accent%% data and validated against the %%checksum%%.
interface AbstractProviderPlugin
interface AbstractProviderPlugin {}
An **AbstractPlugin** is used to provide additional internal services to an [[AbstractProvider]] without adding backwards-incompatible changes to method signatures or other internal and complex logic.
interface ActionRejectedError
interface ActionRejectedError extends EthersError<'ACTION_REJECTED'> {}
This Error indicates a request was rejected by the user.
In most clients (such as MetaMask), when an operation requires user authorization (such as ``signer.sendTransaction``), the client presents a dialog box to the user. If the user denies the request this error is thrown.
property action
action: | 'requestAccess' | 'sendTransaction' | 'signMessage' | 'signTransaction' | 'signTypedData' | 'unknown';
The requested action.
property reason
reason: 'expired' | 'rejected' | 'pending';
The reason the action was rejected.
If there is already a pending request, some clients may indicate there is already a ``"pending"`` action. This prevents an app from spamming the user.
interface Addressable
interface Addressable {}
An interface for objects which have an address, and can resolve it asyncronously.
This allows objects such as [[Signer]] or [[Contract]] to be used most places an address can be, for example getting the [balance](Provider-getBalance).
method getAddress
getAddress: () => Promise<string>;
Get the object address.
interface BadDataError
interface BadDataError extends EthersError<'BAD_DATA'> {}
This Error indicates that a provided set of data cannot be correctly interpreted.
property value
value: any;
The data.
interface BaseContractMethod
interface BaseContractMethod< A extends Array<any> = Array<any>, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> {}
A Contract method can be called directly, or used in various ways.
property fragment
fragment: FunctionFragment;
The fragment of the Contract method. This will throw on ambiguous method names.
property name
name: string;
The name of the Contract method.
method estimateGas
estimateGas: (...args: ContractMethodArgs<A>) => Promise<bigint>;
Estimate the gas to send the contract method with %%args%%.
method getFragment
getFragment: (...args: ContractMethodArgs<A>) => FunctionFragment;
Returns the fragment constrained by %%args%%. This can be used to resolve ambiguous method names.
method populateTransaction
populateTransaction: ( ...args: ContractMethodArgs<A>) => Promise<ContractTransaction>;
Returns a populated transaction that can be used to perform the contract method with %%args%%.
method send
send: (...args: ContractMethodArgs<A>) => Promise<ContractTransactionResponse>;
Send a transaction for the contract method with %%args%%.
method staticCall
staticCall: (...args: ContractMethodArgs<A>) => Promise<R>;
Call the contract method with %%args%% and return the value.
If the return value is a single type, it will be dereferenced and returned directly, otherwise the full Result will be returned.
method staticCallResult
staticCallResult: (...args: ContractMethodArgs<A>) => Promise<Result>;
Call the contract method with %%args%% and return the Result without any dereferencing.
call signature
(...args: ContractMethodArgs<A>): Promise<D>;
interface Blob
interface Blob {}
A full-valid BLOb object for [[link-eip-4844]] transactions.
The commitment and proof should have been computed using a KZG library.
interface BlockParams
interface BlockParams {}
a **BlockParams** encodes the minimal required properties for a formatted block.
property baseFeePerGas
baseFeePerGas: null | bigint;
The protocol-defined base fee per gas in an [[link-eip-1559]] block.
property blobGasUsed
blobGasUsed?: null | bigint;
The total amount of BLOb gas consumed by transactions within the block. See [[link-eip4844].
property difficulty
difficulty: bigint;
For proof-of-work networks, the difficulty target is used to adjust the difficulty in mining to ensure a expected block rate.
property excessBlobGas
excessBlobGas?: null | bigint;
The running total of BLOb gas consumed in excess of the target prior to the block. See [[link-eip-4844]].
property extraData
extraData: string;
Additional data the miner choose to include.
property gasLimit
gasLimit: bigint;
The maximum amount of gas a block can consume.
property gasUsed
gasUsed: bigint;
The amount of gas a block consumed.
property hash
hash?: null | string;
The block hash.
property miner
miner: string;
The miner (or author) of a block.
property nonce
nonce: string;
A random sequence provided during the mining process for proof-of-work networks.
property number
number: number;
The block number.
property parentBeaconBlockRoot
parentBeaconBlockRoot?: null | string;
The hash tree root of the parent beacon block for the given execution block. See [[link-eip-4788]].
property parentHash
parentHash: string;
The hash of the previous block in the blockchain. The genesis block has the parentHash of the [[ZeroHash]].
property prevRandao
prevRandao?: null | string;
The latest RANDAO mix of the post beacon state of the previous block.
property receiptsRoot
receiptsRoot?: null | string;
The hash of the transaction receipts trie.
property stateRoot
stateRoot?: null | string;
The root hash for the global state after applying changes in this block.
property timestamp
timestamp: number;
The timestamp for this block, which is the number of seconds since epoch that this block was included.
property transactions
transactions: ReadonlyArray<string | TransactionResponseParams>;
The list of transactions in the block.
interface BufferOverrunError
interface BufferOverrunError extends EthersError<'BUFFER_OVERRUN'> {}
This Error indicates an attempt was made to read outside the bounds of protected data.
Most operations in Ethers are protected by bounds checks, to mitigate exploits when parsing data.
interface CallExceptionError
interface CallExceptionError extends EthersError<'CALL_EXCEPTION'> {}
This **Error** indicates a transaction reverted.
property action
action: CallExceptionAction;
The action being performed when the revert was encountered.
property data
data: null | string;
The revert data returned.
property invocation
invocation: null | { method: string; signature: string; args: Array<any>;};
The contract invocation details, if available.
property reason
reason: null | string;
A human-readable representation of data, if possible.
property receipt
receipt?: TransactionReceipt;
If the error occurred in a transaction that was mined (with a status of ``0``), this is the receipt.
property revert
revert: null | { signature: string; name: string; args: Array<any>;};
The built-in or custom revert error, if available
property transaction
transaction: CallExceptionTransaction;
The transaction that triggered the exception.
interface CancelledError
interface CancelledError extends EthersError<'CANCELLED'> {}
This Error indicates that the operation was cancelled by a programmatic call, for example to ``cancel()``.
interface ConstantContractMethod
interface ConstantContractMethod<A extends Array<any>, R = any> extends ContractMethod<A, R, R> {}
A pure of view method on a Contract.
interface ContractDeployTransaction
interface ContractDeployTransaction extends Omit<ContractTransaction, 'to'> {}
A deployment transaction for a contract.
interface ContractEvent
interface ContractEvent<A extends Array<any> = Array<any>> {}
property fragment
fragment: EventFragment;
The fragment of the Contract event. This will throw on ambiguous method names.
property name
name: string;
The name of the Contract event.
method getFragment
getFragment: (...args: ContractEventArgs<A>) => EventFragment;
Returns the fragment constrained by %%args%%. This can be used to resolve ambiguous event names.
call signature
(...args: ContractEventArgs<A>): DeferredTopicFilter;
interface ContractInterface
interface ContractInterface {}
A Contract with no method constraints.
index signature
[name: string]: BaseContractMethod;
interface ContractMethod
interface ContractMethod< A extends Array<any> = Array<any>, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> extends BaseContractMethod<A, R, D> {}
A contract method on a Contract.
interface ContractRunner
interface ContractRunner {}
A **ContractRunner** is a generic interface which defines an object capable of interacting with a Contract on the network.
The more operations supported, the more utility it is capable of.
The most common ContractRunners are [Providers](Provider) which enable read-only access and [Signers](Signer) which enable write-access.
property call
call?: (tx: TransactionRequest) => Promise<string>;
Required for pure, view or static calls to contracts.
property estimateGas
estimateGas?: (tx: TransactionRequest) => Promise<bigint>;
Required to estimate gas.
property provider
provider: null | Provider;
The provider used for necessary state querying operations.
This can also point to the **ContractRunner** itself, in the case of an [[AbstractProvider]].
property resolveName
resolveName?: (name: string) => Promise<null | string>;
Required to support ENS names
property sendTransaction
sendTransaction?: (tx: TransactionRequest) => Promise<TransactionResponse>;
Required for state mutating calls
interface ContractTransaction
interface ContractTransaction extends PreparedTransactionRequest {}
When populating a transaction this type is returned.
interface DeferredTopicFilter
interface DeferredTopicFilter {}
When creating a filter using the ``contract.filters``, this is returned.
property fragment
fragment: EventFragment;
method getTopicFilter
getTopicFilter: () => Promise<TopicFilter>;
interface Eip1193Provider
interface Eip1193Provider {}
The interface to an [[link-eip-1193]] provider, which is a standard used by most injected providers, which the [[BrowserProvider]] accepts and exposes the API of.
method request
request: (request: { method: string; params?: Array<any> | Record<string, any>;}) => Promise<any>;
See [[link-eip-1193]] for details on this method.
interface EthersError
interface EthersError<T extends ErrorCode = ErrorCode> extends Error {}
All errors in Ethers include properties to assist in machine-readable errors.
property code
code: ErrorCode;
The string error code.
property error
error?: Error;
Any related error.
property info
info?: Record<string, any>;
Additional info regarding the error that may be useful.
This is generally helpful mostly for human-based debugging.
property shortMessage
shortMessage: string;
A short message describing the error, with minimal additional details.
interface EventEmitterable
interface EventEmitterable<T> {}
An **EventEmitterable** behaves similar to an EventEmitter except provides async access to its methods.
An EventEmitter implements the observer pattern.
method addListener
addListener: (event: T, listener: Listener) => Promise<this>;
Alias for [[on]].
method emit
emit: (event: T, ...args: Array<any>) => Promise<boolean>;
Triggers each listener for %%event%% with the %%args%%.
method listenerCount
listenerCount: (event?: T) => Promise<number>;
Resolves to the number of listeners for %%event%%.
method listeners
listeners: (event?: T) => Promise<Array<Listener>>;
Resolves to the listeners for %%event%%.
method off
off: (event: T, listener?: Listener) => Promise<this>;
Unregister the %%listener%% for %%event%%. If %%listener%% is unspecified, all listeners are unregistered.
method on
on: (event: T, listener: Listener) => Promise<this>;
Registers a %%listener%% that is called whenever the %%event%% occurs until unregistered.
method once
once: (event: T, listener: Listener) => Promise<this>;
Registers a %%listener%% that is called the next time %%event%% occurs.
method removeAllListeners
removeAllListeners: (event?: T) => Promise<this>;
Unregister all listeners for %%event%%.
method removeListener
removeListener: (event: T, listener: Listener) => Promise<this>;
Alias for [[off]].
interface EventFilter
interface EventFilter {}
An **EventFilter** allows efficiently filtering logs (also known as events) using bloom filters included within blocks.
interface Filter
interface Filter extends EventFilter {}
A **Filter** allows searching a specific range of blocks for mathcing logs.
interface FilterByBlockHash
interface FilterByBlockHash extends EventFilter {}
A **FilterByBlockHash** allows searching a specific block for mathcing logs.
property blockHash
blockHash?: string;
The blockhash of the specific block for the filter.
interface InsufficientFundsError
interface InsufficientFundsError extends EthersError<'INSUFFICIENT_FUNDS'> {}
The sending account has insufficient funds to cover the entire transaction cost.
property transaction
transaction: TransactionRequest;
The transaction.
interface InvalidArgumentError
interface InvalidArgumentError extends EthersError<'INVALID_ARGUMENT'> {}
This Error indicates an incorrect type or value was passed to a function or method.
interface JsonFragment
interface JsonFragment {}
A fragment for a method, event or error in a [JSON ABI format](link-solc-jsonabi).
property anonymous
readonly anonymous?: boolean;
If the event is anonymous.
property constant
readonly constant?: boolean;
If the function is constant.
property gas
readonly gas?: string;
The gas limit to use when sending a transaction for this function.
property inputs
readonly inputs?: ReadonlyArray<JsonFragmentType>;
The input parameters.
property name
readonly name?: string;
The name of the error, event, function, etc.
property outputs
readonly outputs?: ReadonlyArray<JsonFragmentType>;
The output parameters.
property payable
readonly payable?: boolean;
If the function is payable.
property stateMutability
readonly stateMutability?: string;
The mutability state of the function.
property type
readonly type?: string;
The type of the fragment (e.g. ``event``, ``"function"``, etc.)
interface JsonFragmentType
interface JsonFragmentType {}
A Type description in a [JSON ABI format](link-solc-jsonabi).
property components
readonly components?: ReadonlyArray<JsonFragmentType>;
The components for a tuple.
property indexed
readonly indexed?: boolean;
If the parameter is indexed.
property internalType
readonly internalType?: string;
The internal Solidity type.
property name
readonly name?: string;
The parameter name.
property type
readonly type?: string;
The type of the parameter.
interface JsonRpcTransactionRequest
interface JsonRpcTransactionRequest {}
A **JsonRpcTransactionRequest** is formatted as needed by the JSON-RPC Ethereum API specification.
property accessList
accessList?: Array<{ address: string; storageKeys: Array<string>;}>;
The transaction access list.
property chainId
chainId?: string;
The chain ID the transaction is valid on.
property data
data?: string;
The transaction data.
property from
from?: string;
The sender address to use when signing.
property gas
gas?: string;
The maximum amount of gas to allow a transaction to consume.
In most other places in ethers, this is called ``gasLimit`` which differs from the JSON-RPC Ethereum API specification.
property gasPrice
gasPrice?: string;
The gas price per wei for transactions prior to [[link-eip-1559]].
property maxFeePerGas
maxFeePerGas?: string;
The maximum fee per gas for [[link-eip-1559]] transactions.
property maxPriorityFeePerGas
maxPriorityFeePerGas?: string;
The maximum priority fee per gas for [[link-eip-1559]] transactions.
property nonce
nonce?: string;
The nonce for the transaction.
property to
to?: string;
The target address.
property type
type?: string;
The [[link-eip-2718]] transaction type.
property value
value?: string;
The transaction value (in wei).
interface KzgLibrary
interface KzgLibrary {}
A KZG Library with the necessary functions to compute BLOb commitments and proofs.
property blobToKzgCommitment
blobToKzgCommitment: (blob: Uint8Array) => Uint8Array;
property computeBlobKzgProof
computeBlobKzgProof: (blob: Uint8Array, commitment: Uint8Array) => Uint8Array;
interface LogParams
interface LogParams {}
a **LogParams** encodes the minimal required properties for a formatted log.
property address
address: string;
The address of the contract that emitted this log.
property blockHash
blockHash: string;
The block hash of the block that included the transaction for this log.
property blockNumber
blockNumber: number;
The block number of the block that included the transaction for this log.
property data
data: string;
The data emitted with this log.
property index
index: number;
The index of this log.
property removed
removed: boolean;
Whether this log was removed due to the transaction it was included in being removed dur to an orphaned block.
property topics
topics: ReadonlyArray<string>;
The topics emitted with this log.
property transactionHash
transactionHash: string;
The transaction hash for the transaxction the log occurred in.
property transactionIndex
transactionIndex: number;
The transaction index of this log.
interface MinedBlock
interface MinedBlock extends Block {}
An Interface to indicate a [[Block]] has been included in the blockchain. This asserts a Type Guard that necessary properties are non-null.
Before a block is included, it is a //pending// block.
property date
readonly date: Date;
The block date, created from the [[timestamp]].
property hash
readonly hash: string;
The block hash.
property miner
readonly miner: string;
The miner of the block, also known as the ``author`` or block ``producer``.
property number
readonly number: number;
The block number also known as the block height.
property timestamp
readonly timestamp: number;
The block timestamp, in seconds from epoch.
interface MinedTransactionResponse
interface MinedTransactionResponse extends TransactionResponse {}
A **MinedTransactionResponse** is an interface representing a transaction which has been mined and allows for a type guard for its property values being defined.
property blockHash
blockHash: string;
The block hash this transaction occurred in.
property blockNumber
blockNumber: number;
The block number this transaction occurred in.
property date
date: Date;
The date this transaction occurred on.
interface MissingArgumentError
interface MissingArgumentError extends EthersError<'MISSING_ARGUMENT'> {}
This Error indicates there were too few arguments were provided.
property count
count: number;
The number of arguments received.
property expectedCount
expectedCount: number;
The number of arguments expected.
interface NameResolver
interface NameResolver {}
An interface for any object which can resolve an ENS name.
method resolveName
resolveName: (name: string) => Promise<null | string>;
Resolve to the address for the ENS %%name%%.
Resolves to ``null`` if the name is unconfigued. Use [[resolveAddress]] (passing this object as %%resolver%%) to throw for names that are unconfigured.
interface NetworkError
interface NetworkError extends EthersError<'NETWORK_ERROR'> {}
This Error indicates a problem connecting to a network.
property event
event: string;
The network event.
interface NonceExpiredError
interface NonceExpiredError extends EthersError<'NONCE_EXPIRED'> {}
The sending account has already used this nonce in a transaction that has been included.
property transaction
transaction: TransactionRequest;
The transaction.
interface NotImplementedError
interface NotImplementedError extends EthersError<'NOT_IMPLEMENTED'> {}
This Error is mostly used as a stub for functionality that is intended for the future, but is currently not implemented.
property operation
operation: string;
The attempted operation.
interface NumericFaultError
interface NumericFaultError extends EthersError<'NUMERIC_FAULT'> {}
This Error indicates an operation which would result in incorrect arithmetic output has occurred.
For example, trying to divide by zero or using a ``uint8`` to store a negative value.
interface OffchainFaultError
interface OffchainFaultError extends EthersError<'OFFCHAIN_FAULT'> {}
A CCIP-read exception, which cannot be recovered from or be further processed.
property reason
reason: string;
The reason the CCIP-read failed.
property transaction
transaction?: TransactionRequest;
The transaction.
interface Overrides
interface Overrides extends Omit<TransactionRequest, 'to' | 'data'> {}
The overrides for a contract transaction.
interface PerformActionTransaction
interface PerformActionTransaction extends PreparedTransactionRequest {}
A normalized transactions used for [[PerformActionRequest]] objects.
interface PreparedTransactionRequest
interface PreparedTransactionRequest {}
A **PreparedTransactionRequest** is identical to a [[TransactionRequest]] except all the property types are strictly enforced.
property accessList
accessList?: AccessList;
The [[link-eip-2930]] access list. Storage slots included in the access list are //warmed// by pre-loading them, so their initial cost to fetch is guaranteed, but then each additional access is cheaper.
property blockTag
blockTag?: BlockTag;
When using ``call`` or ``estimateGas``, this allows a specific block to be queried. Many backends do not support this and when unsupported errors are silently squelched and ``"latest"`` is used.
property chainId
chainId?: bigint;
The chain ID for the network this transaction is valid on.
property customData
customData?: any;
A custom object, which can be passed along for network-specific values.
property data
data?: string;
The transaction data.
property enableCcipRead
enableCcipRead?: boolean;
When using ``call``, this enables CCIP-read, which permits the provider to be redirected to web-based content during execution, which is then further validated by the contract.
There are potential security implications allowing CCIP-read, as it could be used to expose the IP address or user activity during the fetch to unexpected parties.
property from
from?: AddressLike;
The sender of the transaction.
property gasLimit
gasLimit?: bigint;
The maximum amount of gas to allow this transaction to consime.
property gasPrice
gasPrice?: bigint;
The gas price to use for legacy transactions or transactions on legacy networks.
Most of the time the ``max*FeePerGas`` is preferred.
property maxFeePerGas
maxFeePerGas?: bigint;
The [[link-eip-1559]] maximum total fee to pay per gas. The actual value used is protocol enforced to be the block's base fee.
property maxPriorityFeePerGas
maxPriorityFeePerGas?: bigint;
The [[link-eip-1559]] maximum priority fee to pay per gas.
property nonce
nonce?: number;
The nonce of the transaction, used to prevent replay attacks.
property to
to?: AddressLike;
The target of the transaction.
property type
type?: number;
The transaction type.
property value
value?: bigint;
The transaction value (in wei).
interface Provider
interface Provider extends ContractRunner, EventEmitterable<ProviderEvent>, NameResolver {}
A **Provider** is the primary method to interact with the read-only content on Ethereum.
It allows access to details about accounts, blocks and transactions and the ability to query event logs and simulate contract execution.
Account data includes the [balance](getBalance), [transaction count](getTransactionCount), [code](getCode) and [state trie storage](getStorage).
Simulating execution can be used to [call](call), [estimate gas](estimateGas) and [get transaction results](getTransactionResult).
The [[broadcastTransaction]] is the only method which allows updating the blockchain, but it is usually accessed by a [[Signer]], since a private key must be used to sign the transaction before it can be broadcast.
property provider
provider: this;
The provider iteself.
This is part of the necessary API for executing a contract, as it provides a common property on any [[ContractRunner]] that can be used to access the read-only portion of the runner.
method broadcastTransaction
broadcastTransaction: (signedTx: string) => Promise<TransactionResponse>;
Broadcasts the %%signedTx%% to the network, adding it to the memory pool of any node for which the transaction meets the rebroadcast requirements.
method call
call: (tx: TransactionRequest) => Promise<string>;
Simulate the execution of %%tx%%. If the call reverts, it will throw a [[CallExceptionError]] which includes the revert data.
method destroy
destroy: () => void;
Shutdown any resources this provider is using. No additional calls should be made to this provider after calling this.
method estimateGas
estimateGas: (tx: TransactionRequest) => Promise<bigint>;
Estimates the amount of gas required to execute %%tx%%.
method getBalance
getBalance: (address: AddressLike, blockTag?: BlockTag) => Promise<bigint>;
Get the account balance (in wei) of %%address%%. If %%blockTag%% is specified and the node supports archive access for that %%blockTag%%, the balance is as of that [[BlockTag]].
On nodes without archive access enabled, the %%blockTag%% may be **silently ignored** by the node, which may cause issues if relied on.
method getBlock
getBlock: ( blockHashOrBlockTag: BlockTag | string, prefetchTxs?: boolean) => Promise<null | Block>;
Resolves to the block for %%blockHashOrBlockTag%%.
If %%prefetchTxs%%, and the backend supports including transactions with block requests, all transactions will be included and the [[Block]] object will not need to make remote calls for getting transactions.
method getBlockNumber
getBlockNumber: () => Promise<number>;
Get the current block number.
method getCode
getCode: (address: AddressLike, blockTag?: BlockTag) => Promise<string>;
Get the bytecode for %%address%%.
On nodes without archive access enabled, the %%blockTag%% may be **silently ignored** by the node, which may cause issues if relied on.
method getFeeData
getFeeData: () => Promise<FeeData>;
Get the best guess at the recommended [[FeeData]].
method getLogs
getLogs: (filter: Filter | FilterByBlockHash) => Promise<Array<Log>>;
Resolves to the list of Logs that match %%filter%%
method getNetwork
getNetwork: () => Promise<Network>;
Get the connected [[Network]].
method getStorage
getStorage: ( address: AddressLike, position: BigNumberish, blockTag?: BlockTag) => Promise<string>;
Get the storage slot value for %%address%% at slot %%position%%.
On nodes without archive access enabled, the %%blockTag%% may be **silently ignored** by the node, which may cause issues if relied on.
method getTransaction
getTransaction: (hash: string) => Promise<null | TransactionResponse>;
Resolves to the transaction for %%hash%%.
If the transaction is unknown or on pruning nodes which discard old transactions this resolves to ``null``.
method getTransactionCount
getTransactionCount: ( address: AddressLike, blockTag?: BlockTag) => Promise<number>;
Get the number of transactions ever sent for %%address%%, which is used as the ``nonce`` when sending a transaction. If %%blockTag%% is specified and the node supports archive access for that %%blockTag%%, the transaction count is as of that [[BlockTag]].
On nodes without archive access enabled, the %%blockTag%% may be **silently ignored** by the node, which may cause issues if relied on.
method getTransactionReceipt
getTransactionReceipt: (hash: string) => Promise<null | TransactionReceipt>;
Resolves to the transaction receipt for %%hash%%, if mined.
If the transaction has not been mined, is unknown or on pruning nodes which discard old transactions this resolves to ``null``.
method getTransactionResult
getTransactionResult: (hash: string) => Promise<null | string>;
Resolves to the result returned by the executions of %%hash%%.
This is only supported on nodes with archive access and with the necessary debug APIs enabled.
method lookupAddress
lookupAddress: (address: string) => Promise<null | string>;
Resolves to the ENS name associated for the %%address%% or ``null`` if the //primary name// is not configured.
Users must perform additional steps to configure a //primary name//, which is not currently common.
method resolveName
resolveName: (ensName: string) => Promise<null | string>;
Resolves to the address configured for the %%ensName%% or ``null`` if unconfigured.
method waitForBlock
waitForBlock: (blockTag?: BlockTag) => Promise<Block>;
Resolves to the block at %%blockTag%% once it has been mined.
This can be useful for waiting some number of blocks by using the ``currentBlockNumber + N``.
method waitForTransaction
waitForTransaction: ( hash: string, confirms?: number, timeout?: number) => Promise<null | TransactionReceipt>;
Waits until the transaction %%hash%% is mined and has %%confirms%% confirmations.
interface ReplacementUnderpricedError
interface ReplacementUnderpricedError extends EthersError<'REPLACEMENT_UNDERPRICED'> {}
An attempt was made to replace a transaction, but with an insufficient additional fee to afford evicting the old transaction from the memory pool.
property transaction
transaction: TransactionRequest;
The transaction.
interface ServerError
interface ServerError extends EthersError<'SERVER_ERROR'> {}
This Error indicates there was a problem fetching a resource from a server.
interface Signer
interface Signer extends Addressable, ContractRunner, NameResolver {}
A Signer represents an account on the Ethereum Blockchain, and is most often backed by a private key represented by a mnemonic or residing on a Hardware Wallet.
The API remains abstract though, so that it can deal with more advanced exotic Signing entities, such as Smart Contract Wallets or Virtual Wallets (where the private key may not be known).
property provider
provider: null | Provider;
The [[Provider]] attached to this Signer (if any).
method call
call: (tx: TransactionRequest) => Promise<string>;
Evaluates the //tx// by running it against the current Blockchain state. This cannot change state and has no cost in ether, as it is effectively simulating execution.
This can be used to have the Blockchain perform computations based on its state (e.g. running a Contract's getters) or to simulate the effect of a transaction before actually performing an operation.
method connect
connect: (provider: null | Provider) => Signer;
Returns a new instance of this Signer connected to //provider// or detached from any Provider if null.
method estimateGas
estimateGas: (tx: TransactionRequest) => Promise<bigint>;
Estimates the required gas required to execute //tx// on the Blockchain. This will be the expected amount a transaction will require as its ``gasLimit`` to successfully run all the necessary computations and store the needed state that the transaction intends.
Keep in mind that this is **best efforts**, since the state of the Blockchain is in flux, which could affect transaction gas requirements.
Throws
UNPREDICTABLE_GAS_LIMIT A transaction that is believed by the node to likely fail will throw an error during gas estimation. This could indicate that it will actually fail or that the circumstances are simply too complex for the node to take into account. In these cases, a manually determined ``gasLimit`` will need to be made.
method getAddress
getAddress: () => Promise<string>;
Get the address of the Signer.
method getNonce
getNonce: (blockTag?: BlockTag) => Promise<number>;
Gets the next nonce required for this Signer to send a transaction.
Parameter blockTag
The blocktag to base the transaction count on, keep in mind many nodes do not honour this value and silently ignore it [default: ``"latest"``]
method populateCall
populateCall: (tx: TransactionRequest) => Promise<TransactionLike<string>>;
Prepares a TransactionRequest for calling: - resolves ``to`` and ``from`` addresses - if ``from`` is specified , check that it matches this Signer
Parameter tx
The call to prepare
method populateTransaction
populateTransaction: ( tx: TransactionRequest) => Promise<TransactionLike<string>>;
Prepares a TransactionRequest for sending to the network by populating any missing properties: - resolves ``to`` and ``from`` addresses - if ``from`` is specified , check that it matches this Signer - populates ``nonce`` via ``signer.getNonce("pending")`` - populates ``gasLimit`` via ``signer.estimateGas(tx)`` - populates ``chainId`` via ``signer.provider.getNetwork()`` - populates ``type`` and relevant fee data for that type (``gasPrice`` for legacy transactions, ``maxFeePerGas`` for EIP-1559, etc)
Some Signer implementations may skip populating properties that are populated downstream; for example JsonRpcSigner defers to the node to populate the nonce and fee data.
Parameter tx
The call to prepare
method resolveName
resolveName: (name: string) => Promise<null | string>;
Resolves an ENS Name to an address.
method sendTransaction
sendTransaction: (tx: TransactionRequest) => Promise<TransactionResponse>;
Sends %%tx%% to the Network. The ``signer.populateTransaction(tx)`` is called first to ensure all necessary properties for the transaction to be valid have been popualted first.
method signMessage
signMessage: (message: string | Uint8Array) => Promise<string>;
Signs an [[link-eip-191]] prefixed personal message.
If the %%message%% is a string, it is signed as UTF-8 encoded bytes. It is **not** interpretted as a [[BytesLike]]; so the string ``"0x1234"`` is signed as six characters, **not** two bytes.
To sign that example as two bytes, the Uint8Array should be used (i.e. ``new Uint8Array([ 0x12, 0x34 ])``).
method signTransaction
signTransaction: (tx: TransactionRequest) => Promise<string>;
Signs %%tx%%, returning the fully signed transaction. This does not populate any additional properties within the transaction.
method signTypedData
signTypedData: ( domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>) => Promise<string>;
Signs the [[link-eip-712]] typed data.
interface Subscriber
interface Subscriber {}
A **Subscriber** manages a subscription.
Only developers sub-classing [[AbstractProvider[[ will care about this, if they are modifying a low-level feature of how subscriptions operate.
property pollingInterval
pollingInterval?: number;
The frequency (in ms) to poll for events, if polling is used by the subscriber.
For non-polling subscribers, this must return ``undefined``.
method pause
pause: (dropWhilePaused?: boolean) => void;
Called when the subscription should pause.
If %%dropWhilePaused%%, events that occur while paused should not be emitted [[resume]].
method resume
resume: () => void;
Resume a paused subscriber.
method start
start: () => void;
Called initially when a subscriber is added the first time.
method stop
stop: () => void;
Called when there are no more subscribers to the event.
interface TimeoutError
interface TimeoutError extends EthersError<'TIMEOUT'> {}
This Error indicates that the timeout duration has expired and that the operation has been implicitly cancelled.
The side-effect of the operation may still occur, as this generally means a request has been sent and there has simply been no response to indicate whether it was processed or not.
interface TransactionLike
interface TransactionLike<A = string> {}
A **TransactionLike** is an object which is appropriate as a loose input for many operations which will populate missing properties of a transaction.
property accessList
accessList?: null | AccessListish;
The access list for berlin and london transactions.
property blobs
blobs?: null | Array<BlobLike>;
The blobs (if any) attached to this transaction (see [[link-eip-4844]]).
property blobVersionedHashes
blobVersionedHashes?: null | Array<string>;
The versioned hashes (see [[link-eip-4844]]).
property chainId
chainId?: null | BigNumberish;
The chain ID the transaction is valid on.
property data
data?: null | string;
The data.
property from
from?: null | A;
The sender.
property gasLimit
gasLimit?: null | BigNumberish;
The maximum amount of gas that can be used.
property gasPrice
gasPrice?: null | BigNumberish;
The gas price for legacy and berlin transactions.
property hash
hash?: null | string;
The transaction hash.
property kzg
kzg?: null | KzgLibrary;
An external library for computing the KZG commitments and proofs necessary for EIP-4844 transactions (see [[link-eip-4844]]).
This is generally ``null``, unless you are creating BLOb transactions.
property maxFeePerBlobGas
maxFeePerBlobGas?: null | BigNumberish;
The maximum fee per blob gas (see [[link-eip-4844]]).
property maxFeePerGas
maxFeePerGas?: null | BigNumberish;
The maximum total fee per gas for london transactions.
property maxPriorityFeePerGas
maxPriorityFeePerGas?: null | BigNumberish;
The maximum priority fee per gas for london transactions.
property nonce
nonce?: null | number;
The nonce.
property signature
signature?: null | SignatureLike;
The signature provided by the sender.
property to
to?: null | A;
The recipient address or ``null`` for an ``init`` transaction.
property type
type?: null | number;
The type.
property value
value?: null | BigNumberish;
The value (in wei) to send.
interface TransactionReceiptParams
interface TransactionReceiptParams {}
a **TransactionReceiptParams** encodes the minimal required properties for a formatted transaction receipt.
property blobGasPrice
blobGasPrice?: null | bigint;
The actual BLOb gas price that was charged. See [[link-eip-4844]].
property blobGasUsed
blobGasUsed?: null | bigint;
The amount of BLOb gas used. See [[link-eip-4844]].
property blockHash
blockHash: string;
The block hash of the block that included this transaction.
property blockNumber
blockNumber: number;
The block number of the block that included this transaction.
property contractAddress
contractAddress: null | string;
If the transaction was directly deploying a contract, the [[to]] will be null, the ``data`` will be initcode and if successful, this will be the address of the contract deployed.
property cumulativeGasUsed
cumulativeGasUsed: bigint;
The total amount of gas consumed during the entire block up to and including this transaction.
property effectiveGasPrice
effectiveGasPrice?: null | bigint;
The actual gas price per gas charged for this transaction.
property from
from: string;
The sender of the transaction.
property gasPrice
gasPrice?: null | bigint;
The actual gas price per gas charged for this transaction.
property gasUsed
gasUsed: bigint;
The amount of gas consumed executing this transaciton.
property hash
hash: string;
The transaction hash.
property index
index: number;
The transaction index.
property logs
logs: ReadonlyArray<LogParams>;
The logs emitted during the execution of this transaction.
property logsBloom
logsBloom: string;
The bloom filter for the logs emitted during execution of this transaction.
property root
root: null | string;
The root of this transaction in a pre-bazatium block. In post-byzantium blocks this is null.
property status
status: null | number;
The status of the transaction execution. If ``1`` then the the transaction returned success, if ``0`` then the transaction was reverted. For pre-byzantium blocks, this is usually null, but some nodes may have backfilled this data.
property to
to: null | string;
The target of the transaction. If null, the transaction was trying to deploy a transaction with the ``data`` as the initi=code.
property type
type: number;
The [[link-eip-2718]] envelope type.
interface TransactionReplacedError
interface TransactionReplacedError extends EthersError<'TRANSACTION_REPLACED'> {}
A pending transaction was replaced by another.
property cancelled
cancelled: boolean;
If the transaction was cancelled, such that the original effects of the transaction cannot be assured.
property hash
hash: string;
The hash of the replaced transaction.
property reason
reason: 'repriced' | 'cancelled' | 'replaced';
The reason the transaction was replaced.
property receipt
receipt: TransactionReceipt;
The receipt of the transaction that replace the transaction.
property replacement
replacement: TransactionResponse;
The transaction that replaced the transaction.
interface TransactionRequest
interface TransactionRequest {}
A **TransactionRequest** is a transactions with potentially various properties not defined, or with less strict types for its values.
This is used to pass to various operations, which will internally coerce any types and populate any necessary values.
property accessList
accessList?: null | AccessListish;
The [[link-eip-2930]] access list. Storage slots included in the access list are //warmed// by pre-loading them, so their initial cost to fetch is guaranteed, but then each additional access is cheaper.
property blobs
blobs?: null | Array<BlobLike>;
Any blobs to include in the transaction (see [[link-eip-4844]]).
property blobVersionedHashes
blobVersionedHashes?: null | Array<string>;
The blob versioned hashes (see [[link-eip-4844]]).
property blockTag
blockTag?: BlockTag;
When using ``call`` or ``estimateGas``, this allows a specific block to be queried. Many backends do not support this and when unsupported errors are silently squelched and ``"latest"`` is used.
property chainId
chainId?: null | BigNumberish;
The chain ID for the network this transaction is valid on.
property customData
customData?: any;
A custom object, which can be passed along for network-specific values.
property data
data?: null | string;
The transaction data.
property enableCcipRead
enableCcipRead?: boolean;
When using ``call``, this enables CCIP-read, which permits the provider to be redirected to web-based content during execution, which is then further validated by the contract.
There are potential security implications allowing CCIP-read, as it could be used to expose the IP address or user activity during the fetch to unexpected parties.
property from
from?: null | AddressLike;
The sender of the transaction.
property gasLimit
gasLimit?: null | BigNumberish;
The maximum amount of gas to allow this transaction to consume.
property gasPrice
gasPrice?: null | BigNumberish;
The gas price to use for legacy transactions or transactions on legacy networks.
Most of the time the ``max*FeePerGas`` is preferred.
property kzg
kzg?: null | KzgLibrary;
An external library for computing the KZG commitments and proofs necessary for EIP-4844 transactions (see [[link-eip-4844]]).
This is generally ``null``, unless you are creating BLOb transactions.
property maxFeePerBlobGas
maxFeePerBlobGas?: null | BigNumberish;
The maximum fee per blob gas (see [[link-eip-4844]]).
property maxFeePerGas
maxFeePerGas?: null | BigNumberish;
The [[link-eip-1559]] maximum total fee to pay per gas. The actual value used is protocol enforced to be the block's base fee.
property maxPriorityFeePerGas
maxPriorityFeePerGas?: null | BigNumberish;
The [[link-eip-1559]] maximum priority fee to pay per gas.
property nonce
nonce?: null | number;
The nonce of the transaction, used to prevent replay attacks.
property to
to?: null | AddressLike;
The target of the transaction.
property type
type?: null | number;
The transaction type.
property value
value?: null | BigNumberish;
The transaction value (in wei).
interface TransactionResponseParams
interface TransactionResponseParams {}
a **TransactionResponseParams** encodes the minimal required properties for a formatted transaction response.
property accessList
accessList: null | AccessList;
The transaction access list.
property blobVersionedHashes
blobVersionedHashes?: null | Array<string>;
The [[link-eip-4844]] BLOb versioned hashes.
property blockHash
blockHash: null | string;
The block hash of the block that included this transaction.
property blockNumber
blockNumber: null | number;
The block number of the block that included this transaction.
property chainId
chainId: bigint;
The chain ID this transaction is valid on.
property data
data: string;
The transaction data.
property from
from: string;
The sender of the transaction.
property gasLimit
gasLimit: bigint;
The maximum amount of gas this transaction is authorized to consume.
property gasPrice
gasPrice: bigint;
For legacy transactions, this is the gas price per gas to pay.
property hash
hash: string;
The transaction hash.
property index
index: number;
The transaction index.
property maxFeePerBlobGas
maxFeePerBlobGas?: null | bigint;
For [[link-eip-4844]] transactions, this is the maximum fee that will be paid per BLOb.
property maxFeePerGas
maxFeePerGas: null | bigint;
For [[link-eip-1559]] transactions, this is the maximum fee that will be paid.
property maxPriorityFeePerGas
maxPriorityFeePerGas: null | bigint;
For [[link-eip-1559]] transactions, this is the maximum priority fee to allow a producer to claim.
property nonce
nonce: number;
The nonce of the transaction, used for replay protection.
property signature
signature: Signature;
The signature of the transaction.
property to
to: null | string;
The target of the transaction. If ``null``, the ``data`` is initcode and this transaction is a deployment transaction.
property type
type: number;
The [[link-eip-2718]] transaction type.
property value
value: bigint;
The transaction value (in wei).
interface TypedDataDomain
interface TypedDataDomain {}
The domain for an [[link-eip-712]] payload.
property chainId
chainId?: null | BigNumberish;
The chain ID of the signing domain.
property name
name?: null | string;
The human-readable name of the signing domain.
property salt
salt?: null | BytesLike;
A salt used for purposes decided by the specific domain.
property verifyingContract
verifyingContract?: null | string;
The the address of the contract that will verify the signature.
property version
version?: null | string;
The major version of the signing domain.
interface TypedDataField
interface TypedDataField {}
A specific field of a structured [[link-eip-712]] type.
interface UnconfiguredNameError
interface UnconfiguredNameError extends EthersError<'UNCONFIGURED_NAME'> {}
This Error indicates an ENS name was used, but the name has not been configured.
This could indicate an ENS name is unowned or that the current address being pointed to is the [[ZeroAddress]].
property value
value: string;
The ENS name that was requested
interface UnexpectedArgumentError
interface UnexpectedArgumentError extends EthersError<'UNEXPECTED_ARGUMENT'> {}
This Error indicates too many arguments were provided.
property count
count: number;
The number of arguments received.
property expectedCount
expectedCount: number;
The number of arguments expected.
interface UnknownError
interface UnknownError extends EthersError<'UNKNOWN_ERROR'> {}
This Error is a catch-all for when there is no way for Ethers to know what the underlying problem is.
index signature
[key: string]: any;
interface UnsupportedOperationError
interface UnsupportedOperationError extends EthersError<'UNSUPPORTED_OPERATION'> {}
This Error indicates that the attempted operation is not supported.
This could range from a specific JSON-RPC end-point not supporting a feature to a specific configuration of an object prohibiting the operation.
For example, a [[Wallet]] with no connected [[Provider]] is unable to send a transaction.
property operation
operation: string;
The attempted operation.
interface WebSocketLike
interface WebSocketLike {}
A generic interface to a Websocket-like object.
property onerror
onerror: null | ((...args: Array<any>) => any);
property onmessage
onmessage: null | ((...args: Array<any>) => any);
property onopen
onopen: null | ((...args: Array<any>) => any);
property readyState
readyState: number;
method close
close: (code?: number, reason?: string) => void;
method send
send: (payload: any) => void;
interface WrappedFallback
interface WrappedFallback {}
A Fallback or Receive function on a Contract.
method estimateGas
estimateGas: (overrides?: Omit<TransactionRequest, 'to'>) => Promise<bigint>;
Estimate the gas to send a transaction to the contract fallback.
For non-receive fallback, ``data`` may be overridden.
method populateTransaction
populateTransaction: ( overrides?: Omit<TransactionRequest, 'to'>) => Promise<ContractTransaction>;
Returns a populated transaction that can be used to perform the fallback method.
For non-receive fallback, ``data`` may be overridden.
method send
send: ( overrides?: Omit<TransactionRequest, 'to'>) => Promise<ContractTransactionResponse>;
Send a transaction to the contract fallback.
For non-receive fallback, ``data`` may be overridden.
method staticCall
staticCall: (overrides?: Omit<TransactionRequest, 'to'>) => Promise<string>;
Call the contract fallback and return the result.
For non-receive fallback, ``data`` may be overridden.
call signature
( overrides?: Omit<TransactionRequest, 'to'>): Promise<ContractTransactionResponse>;
type AbstractProviderOptions
type AbstractProviderOptions = { cacheTimeout?: number; pollingInterval?: number;};
Options for configuring some internal aspects of an [[AbstractProvider]].
**``cacheTimeout``** - how long to cache a low-level ``_perform`` for, based on input parameters. This reduces the number of calls to getChainId and getBlockNumber, but may break test chains which can perform operations (internally) synchronously. Use ``-1`` to disable, ``0`` will only buffer within the same event loop and any other value is in ms. (default: ``250``)
type AccessList
type AccessList = Array<AccessListEntry>;
An ordered collection of [[AccessList]] entries.
type AccessListEntry
type AccessListEntry = { address: string; storageKeys: Array<string>;};
A single [[AccessList]] entry of storage keys (slots) for an address.
type AccessListish
type AccessListish = | AccessList | Array<[string, Array<string>]> | Record<string, Array<string>>;
Any ethers-supported access list structure.
type AddressLike
type AddressLike = string | Promise<string> | Addressable;
Anything that can be used to return or resolve an address.
type BigNumberish
type BigNumberish = string | Numeric;
Any type that can be used where a big number is needed.
type BlobLike
type BlobLike = | BytesLike | { data: BytesLike; proof: BytesLike; commitment: BytesLike; };
A BLOb object that can be passed for [[link-eip-4844]] transactions.
It may have had its commitment and proof already provided or rely on an attached [[KzgLibrary]] to compute them.
type BlockTag
type BlockTag = BigNumberish | string;
A **BlockTag** specifies a specific block.
**numeric value** - specifies the block height, where the genesis block is block 0; many operations accept a negative value which indicates the block number should be deducted from the most recent block. A numeric value may be a ``number``, ``bigint``, or a decimal of hex string.
**blockhash** - specifies a specific block by its blockhash; this allows potentially orphaned blocks to be specifed, without ambiguity, but many backends do not support this for some operations.
type BrowserProviderOptions
type BrowserProviderOptions = { polling?: boolean; staticNetwork?: null | boolean | Network; cacheTimeout?: number; pollingInterval?: number;};
type BytesLike
type BytesLike = DataHexString | Uint8Array;
An object that can be used to represent binary data.
type CallExceptionAction
type CallExceptionAction = | 'call' | 'estimateGas' | 'getTransactionResult' | 'sendTransaction' | 'unknown';
The action that resulted in the call exception.
type CallExceptionTransaction
type CallExceptionTransaction = { to: null | string; from?: string; data: string;};
The related transaction that caused the error.
type CodedEthersError
type CodedEthersError<T> = T extends 'UNKNOWN_ERROR' ? UnknownError : T extends 'NOT_IMPLEMENTED' ? NotImplementedError : T extends 'UNSUPPORTED_OPERATION' ? UnsupportedOperationError : T extends 'NETWORK_ERROR' ? NetworkError : T extends 'SERVER_ERROR' ? ServerError : T extends 'TIMEOUT' ? TimeoutError : T extends 'BAD_DATA' ? BadDataError : T extends 'CANCELLED' ? CancelledError : T extends 'BUFFER_OVERRUN' ? BufferOverrunError : T extends 'NUMERIC_FAULT' ? NumericFaultError : T extends 'INVALID_ARGUMENT' ? InvalidArgumentError : T extends 'MISSING_ARGUMENT' ? MissingArgumentError : T extends 'UNEXPECTED_ARGUMENT' ? UnexpectedArgumentError : T extends 'CALL_EXCEPTION' ? CallExceptionError : T extends 'INSUFFICIENT_FUNDS' ? InsufficientFundsError : T extends 'NONCE_EXPIRED' ? NonceExpiredError : T extends 'OFFCHAIN_FAULT' ? OffchainFaultError : T extends 'REPLACEMENT_UNDERPRICED' ? ReplacementUnderpricedError : T extends 'TRANSACTION_REPLACED' ? TransactionReplacedError : T extends 'UNCONFIGURED_NAME' ? UnconfiguredNameError : T extends 'ACTION_REJECTED' ? ActionRejectedError : never;
A conditional type that transforms the [[ErrorCode]] T into its EthersError type.
@flatworm-skip-docs
type ContractEventArgs
type ContractEventArgs<A extends Array<any>> = { [I in keyof A]?: A[I] | Typed | null;};
Each argument of an event is nullable (to indicate matching //any//.
@_ignore:
type ContractEventName
type ContractEventName = string | ContractEvent | TopicFilter | DeferredTopicFilter;
The name for an event used for subscribing to Contract events.
**``string``** - An event by name. The event must be non-ambiguous. The parameters will be dereferenced when passed into the listener.
[[ContractEvent]] - A filter from the ``contract.filters``, which will pass only the EventPayload as a single parameter, which includes a ``.signature`` property that can be used to further filter the event.
[[TopicFilter]] - A filter defined using the standard Ethereum API which provides the specific topic hash or topic hashes to watch for along with any additional values to filter by. This will only pass a single parameter to the listener, the EventPayload which will include additional details to refine by, such as the event name and signature.
[[DeferredTopicFilter]] - A filter created by calling a [[ContractEvent]] with parameters, which will create a filter for a specific event signautre and dereference each parameter when calling the listener.
type ContractMethodArgs
type ContractMethodArgs<A extends Array<any>> = PostfixOverrides<{ [I in keyof A]-?: A[I] | Typed;}>;
Arguments to a Contract method can always include an additional and optional overrides parameter, and each parameter can optionally be [[Typed]].
@_ignore:
type CrowdsaleAccount
type CrowdsaleAccount = { privateKey: string; address: string;};
The data stored within a JSON Crowdsale wallet is fairly minimal.
type DebugEventBrowserProvider
type DebugEventBrowserProvider = | { action: 'sendEip1193Payload'; payload: { method: string; params: Array<any>; }; } | { action: 'receiveEip1193Result'; result: any; } | { action: 'receiveEip1193Error'; error: Error; };
The possible additional events dispatched when using the ``"debug"`` event on a [[BrowserProvider]].
type EncryptOptions
type EncryptOptions = { progressCallback?: ProgressCallback; iv?: BytesLike; entropy?: BytesLike; client?: string; salt?: BytesLike; uuid?: string; scrypt?: { N?: number; r?: number; p?: number; };};
The parameters to use when encrypting a JSON Keystore Wallet.
type ErrorCode
type ErrorCode = | 'UNKNOWN_ERROR' | 'NOT_IMPLEMENTED' | 'UNSUPPORTED_OPERATION' | 'NETWORK_ERROR' | 'SERVER_ERROR' | 'TIMEOUT' | 'BAD_DATA' | 'CANCELLED' | 'BUFFER_OVERRUN' | 'NUMERIC_FAULT' | 'INVALID_ARGUMENT' | 'MISSING_ARGUMENT' | 'UNEXPECTED_ARGUMENT' | 'VALUE_MISMATCH' | 'CALL_EXCEPTION' | 'INSUFFICIENT_FUNDS' | 'NONCE_EXPIRED' | 'REPLACEMENT_UNDERPRICED' | 'TRANSACTION_REPLACED' | 'UNCONFIGURED_NAME' | 'OFFCHAIN_FAULT' | 'ACTION_REJECTED';
All errors emitted by ethers have an **ErrorCode** to help identify and coalesce errors to simplify programmatic analysis.
Each **ErrorCode** is the %%code%% proerty of a coresponding [[EthersError]].
**Generic Errors**
**``"UNKNOWN_ERROR"``** - see [[UnknownError]]
**``"NOT_IMPLEMENTED"``** - see [[NotImplementedError]]
**``"UNSUPPORTED_OPERATION"``** - see [[UnsupportedOperationError]]
**``"NETWORK_ERROR"``** - see [[NetworkError]]
**``"SERVER_ERROR"``** - see [[ServerError]]
**``"TIMEOUT"``** - see [[TimeoutError]]
**``"BAD_DATA"``** - see [[BadDataError]]
**``"CANCELLED"``** - see [[CancelledError]]
**Operational Errors**
**``"BUFFER_OVERRUN"``** - see [[BufferOverrunError]]
**``"NUMERIC_FAULT"``** - see [[NumericFaultError]]
**Argument Errors**
**``"INVALID_ARGUMENT"``** - see [[InvalidArgumentError]]
**``"MISSING_ARGUMENT"``** - see [[MissingArgumentError]]
**``"UNEXPECTED_ARGUMENT"``** - see [[UnexpectedArgumentError]]
**``"VALUE_MISMATCH"``** - //unused//
**Blockchain Errors**
**``"CALL_EXCEPTION"``** - see [[CallExceptionError]]
**``"INSUFFICIENT_FUNDS"``** - see [[InsufficientFundsError]]
**``"NONCE_EXPIRED"``** - see [[NonceExpiredError]]
**``"REPLACEMENT_UNDERPRICED"``** - see [[ReplacementUnderpricedError]]
**``"TRANSACTION_REPLACED"``** - see [[TransactionReplacedError]]
**``"UNCONFIGURED_NAME"``** - see [[UnconfiguredNameError]]
**``"OFFCHAIN_FAULT"``** - see [[OffchainFaultError]]
**User Interaction Errors**
**``"ACTION_REJECTED"``** - see [[ActionRejectedError]]
type FallbackProviderOptions
type FallbackProviderOptions = { quorum?: number; eventQuorum?: number; eventWorkers?: number; cacheTimeout?: number; pollingInterval?: number;};
Additional options to configure a [[FallbackProvider]].
type FetchGatewayFunc
type FetchGatewayFunc = ( url: string, signal?: FetchCancelSignal) => Promise<FetchRequest | FetchResponse>;
Called on Gateway URLs.
type FetchGetUrlFunc
type FetchGetUrlFunc = ( req: FetchRequest, signal?: FetchCancelSignal) => Promise<GetUrlResponse>;
Used to perform a fetch; use this to override the underlying network fetch layer. In NodeJS, the default uses the "http" and "https" libraries and in the browser ``fetch`` is used. If you wish to use Axios, this is how you would register it.
type FetchPreflightFunc
type FetchPreflightFunc = (req: FetchRequest) => Promise<FetchRequest>;
Called before any network request, allowing updated headers (e.g. Bearer tokens), etc.
type FetchProcessFunc
type FetchProcessFunc = ( req: FetchRequest, resp: FetchResponse) => Promise<FetchResponse>;
Called on the response, allowing client-based throttling logic or post-processing.
type FetchRetryFunc
type FetchRetryFunc = ( req: FetchRequest, resp: FetchResponse, attempt: number) => Promise<boolean>;
Called prior to each retry; return true to retry, false to abort.
type FixedFormat
type FixedFormat = | number | string | { signed?: boolean; width?: number; decimals?: number; };
A description of a fixed-point arithmetic field.
When specifying the fixed format, the values override the default of a ``fixed128x18``, which implies a signed 128-bit value with 18 decimals of precision.
The alias ``fixed`` and ``ufixed`` can be used for ``fixed128x18`` and ``ufixed128x18`` respectively.
When a fixed format string begins with a ``u``, it indicates the field is unsigned, so any negative values will overflow. The first number indicates the bit-width and the second number indicates the decimal precision.
When a ``number`` is used for a fixed format, it indicates the number of decimal places, and the default width and signed-ness will be used.
The bit-width must be byte aligned and the decimals can be at most 80.
type FormatType
type FormatType = 'sighash' | 'minimal' | 'full' | 'json';
The format to serialize the output as.
**``"sighash"``** - the bare formatting, used to compute the selector or topic hash; this format cannot be reversed (as it discards ``indexed``) so cannot by used to export an [[Interface]].
**``"minimal"``** - Human-Readable ABI with minimal spacing and without names, so it is compact, but will result in Result objects that cannot be accessed by name.
**``"full"``** - Full Human-Readable ABI, with readable spacing and names intact; this is generally the recommended format.
**``"json"``** - The [JSON ABI format](link-solc-jsonabi).
type FragmentType
type FragmentType = | 'constructor' | 'error' | 'event' | 'fallback' | 'function' | 'struct';
The type of a [[Fragment]].
type GasCostParameters
type GasCostParameters = { /** * The transactions base fee. */ txBase?: number; /** * The fee for creating a new account. */ txCreate?: number; /** * The fee per zero-byte in the data. */ txDataZero?: number; /** * The fee per non-zero-byte in the data. */ txDataNonzero?: number; /** * The fee per storage key in the [[link-eip-2930]] access list. */ txAccessListStorageKey?: number; /** * The fee per address in the [[link-eip-2930]] access list. */ txAccessListAddress?: number;};
The gas cost parameters for a [[GasCostPlugin]].
type GetUrlResponse
type GetUrlResponse = { statusCode: number; statusMessage: string; headers: Record<string, string>; body: null | Uint8Array;};
An environment's implementation of ``getUrl`` must return this type.
type InterfaceAbi
type InterfaceAbi = string | ReadonlyArray<Fragment | JsonFragment | string>;
An **InterfaceAbi** may be any supported ABI format.
A string is expected to be a JSON string, which will be parsed using ``JSON.parse``. This means that the value **must** be a valid JSON string, with no stray commas, etc.
An array may contain any combination of: - Human-Readable fragments - Parsed JSON fragment - [[Fragment]] instances
A **Human-Readable Fragment** is a string which resembles a Solidity signature and is introduced in [this blog entry](link-ricmoo-humanreadableabi). For example, ``function balanceOf(address) view returns (uint)``.
A **Parsed JSON Fragment** is a JavaScript Object desribed in the [Solidity documentation](link-solc-jsonabi).
type JsonRpcApiProviderOptions
type JsonRpcApiProviderOptions = { polling?: boolean; staticNetwork?: null | boolean | Network; batchStallTime?: number; batchMaxSize?: number; batchMaxCount?: number; cacheTimeout?: number; pollingInterval?: number;};
Options for configuring a [[JsonRpcApiProvider]]. Much of this is targetted towards sub-classes, which often will not expose any of these options to their consumers.
**``polling``** - use the polling strategy is used immediately for events; otherwise, attempt to use filters and fall back onto polling (default: ``false``)
**``staticNetwork``** - do not request chain ID on requests to validate the underlying chain has not changed (default: ``null``)
This should **ONLY** be used if it is **certain** that the network cannot change, such as when using INFURA (since the URL dictates the network). If the network is assumed static and it does change, this can have tragic consequences. For example, this **CANNOT** be used with MetaMask, since the user can select a new network from the drop-down at any time.
**``batchStallTime``** - how long (ms) to aggregate requests into a single batch. ``0`` indicates batching will only encompass the current event loop. If ``batchMaxCount = 1``, this is ignored. (default: ``10``)
**``batchMaxSize``** - target maximum size (bytes) to allow per batch request (default: 1Mb)
**``batchMaxCount``** - maximum number of requests to allow in a batch. If ``batchMaxCount = 1``, then batching is disabled. (default: ``100``)
**``cacheTimeout``** - passed as [[AbstractProviderOptions]].
type JsonRpcError
type JsonRpcError = { /** * The response ID to match it to the relevant request. */ id: number; /** * The response error. */ error: { code: number; message?: string; data?: any; };};
A JSON-RPC error, which are returned on failure from a JSON-RPC server.
type JsonRpcPayload
type JsonRpcPayload = { /** * The JSON-RPC request ID. */ id: number; /** * The JSON-RPC request method. */ method: string; /** * The JSON-RPC request parameters. */ params: Array<any> | Record<string, any>; /** * A required constant in the JSON-RPC specification. */ jsonrpc: '2.0';};
A JSON-RPC payload, which are sent to a JSON-RPC server.
type JsonRpcResult
type JsonRpcResult = { /** * The response ID to match it to the relevant request. */ id: number; /** * The response result. */ result: any;};
A JSON-RPC result, which are returned on success from a JSON-RPC server.
type KeystoreAccount
type KeystoreAccount = { address: string; privateKey: string; mnemonic?: { path?: string; locale?: string; entropy: string; };};
The contents of a JSON Keystore Wallet.
type Listener
type Listener = (...args: Array<any>) => void;
A callback function called when a an event is triggered.
type Networkish
type Networkish = | Network | number | bigint | string | { name?: string; chainId?: number; ensAddress?: string; ensNetwork?: number; };
A Networkish can be used to allude to a Network, by specifing: - a [[Network]] object - a well-known (or registered) network name - a well-known (or registered) chain ID - an object with sufficient details to describe a network
type Numeric
type Numeric = number | bigint;
Any type that can be used where a numeric value is needed.
type OrphanFilter
type OrphanFilter = | { orphan: 'drop-block'; hash: string; number: number; } | { orphan: 'drop-transaction'; tx: { hash: string; blockHash: string; blockNumber: number; }; other?: { hash: string; blockHash: string; blockNumber: number; }; } | { orphan: 'reorder-transaction'; tx: { hash: string; blockHash: string; blockNumber: number; }; other?: { hash: string; blockHash: string; blockNumber: number; }; } | { orphan: 'drop-log'; log: { transactionHash: string; blockHash: string; blockNumber: number; address: string; data: string; topics: ReadonlyArray<string>; index: number; }; };
An Orphan Filter allows detecting when an orphan block has resulted in dropping a block or transaction or has resulted in transactions changing order.
Not currently fully supported.
type ParamTypeWalkAsyncFunc
type ParamTypeWalkAsyncFunc = (type: string, value: any) => any | Promise<any>;
When [walking asynchronously](ParamType-walkAsync) a [[ParamType]], this is called on each component.
type ParamTypeWalkFunc
type ParamTypeWalkFunc = (type: string, value: any) => any;
When [walking](ParamType-walk) a [[ParamType]], this is called on each component.
type PerformActionFilter
type PerformActionFilter = | { address?: string | Array<string>; topics?: Array<null | string | Array<string>>; fromBlock?: BlockTag; toBlock?: BlockTag; } | { address?: string | Array<string>; topics?: Array<null | string | Array<string>>; blockHash?: string; };
A normalized filter used for [[PerformActionRequest]] objects.
type PerformActionRequest
type PerformActionRequest = | { method: 'broadcastTransaction'; signedTransaction: string; } | { method: 'call'; transaction: PerformActionTransaction; blockTag: BlockTag; } | { method: 'chainId'; } | { method: 'estimateGas'; transaction: PerformActionTransaction; } | { method: 'getBalance'; address: string; blockTag: BlockTag; } | { method: 'getBlock'; blockTag: BlockTag; includeTransactions: boolean; } | { method: 'getBlock'; blockHash: string; includeTransactions: boolean; } | { method: 'getBlockNumber'; } | { method: 'getCode'; address: string; blockTag: BlockTag; } | { method: 'getGasPrice'; } | { method: 'getLogs'; filter: PerformActionFilter; } | { method: 'getPriorityFee'; } | { method: 'getStorage'; address: string; position: bigint; blockTag: BlockTag; } | { method: 'getTransaction'; hash: string; } | { method: 'getTransactionCount'; address: string; blockTag: BlockTag; } | { method: 'getTransactionReceipt'; hash: string; } | { method: 'getTransactionResult'; hash: string; };
The [[AbstractProvider]] methods will normalize all values and pass this type to [[AbstractProvider-_perform]].
type PostfixOverrides
type PostfixOverrides<A extends Array<any>> = A | [...A, Overrides];
Arguments to a Contract method can always include an additional and optional overrides parameter.
@_ignore:
type ProgressCallback
type ProgressCallback = (percent: number) => void;
A callback during long-running operations to update any UI or provide programatic access to the progress.
The %%percent%% is a value between ``0`` and ``1``.
@_docloc: api/crypto:Passwords
type ProviderEvent
type ProviderEvent = | string | Array<string | Array<string>> | EventFilter | OrphanFilter;
A **ProviderEvent** provides the types of events that can be subscribed to on a [[Provider]].
Each provider may include additional possible events it supports, but the most commonly supported are:
**``"block"``** - calls the listener with the current block number on each new block.
**``"error"``** - calls the listener on each async error that occurs during the event loop, with the error.
**``"debug"``** - calls the listener on debug events, which can be used to troubleshoot network errors, provider problems, etc.
**``transaction hash``** - calls the listener on each block after the transaction has been mined; generally ``.once`` is more appropriate for this event.
**``Array``** - calls the listener on each log that matches the filter.
[[EventFilter]] - calls the listener with each matching log
type RlpStructuredData
type RlpStructuredData = string | Array<RlpStructuredData>;
An RLP-encoded structure.
type RlpStructuredDataish
type RlpStructuredDataish = string | Uint8Array | Array<RlpStructuredDataish>;
An RLP-encoded structure, which allows Uint8Array.
type SignatureLike
type SignatureLike = | Signature | string | { r: string; s: string; v: BigNumberish; yParity?: 0 | 1; yParityAndS?: string; } | { r: string; yParityAndS: string; yParity?: 0 | 1; s?: string; v?: number; } | { r: string; s: string; yParity: 0 | 1; v?: BigNumberish; yParityAndS?: string; };
A SignatureLike
@_docloc: api/crypto:Signing
type Subscription
type Subscription = | { type: | 'block' | 'close' | 'debug' | 'error' | 'finalized' | 'network' | 'pending' | 'safe'; tag: string; } | { type: 'transaction'; tag: string; hash: string; } | { type: 'event'; tag: string; filter: EventFilter; } | { type: 'orphan'; tag: string; filter: OrphanFilter; };
The value passed to the [[AbstractProvider-_getSubscriber]] method.
Only developers sub-classing [[AbstractProvider[[ will care about this, if they are modifying a low-level feature of how subscriptions operate.
type TopicFilter
type TopicFilter = Array<null | string | Array<string>>;
A **TopicFilter** provides a struture to define bloom-filter queries.
Each field that is ``null`` matches **any** value, a field that is a ``string`` must match exactly that value and ``array`` is effectively an ``OR``-ed set, where any one of those values must match.
type UnicodeNormalizationForm
type UnicodeNormalizationForm = 'NFC' | 'NFD' | 'NFKC' | 'NFKD';
The stanard normalization forms.
type Utf8ErrorFunc
type Utf8ErrorFunc = ( reason: Utf8ErrorReason, offset: number, bytes: Uint8Array, output: Array<number>, badCodepoint?: number) => number;
A callback that can be used with [[toUtf8String]] to analysis or recovery from invalid UTF-8 data.
Parsing UTF-8 data is done through a simple Finite-State Machine (FSM) which calls the ``Utf8ErrorFunc`` if a fault is detected.
The %%reason%% indicates where in the FSM execution the fault occurred and the %%offset%% indicates where the input failed.
The %%bytes%% represents the raw UTF-8 data that was provided and %%output%% is the current array of UTF-8 code-points, which may be updated by the ``Utf8ErrorFunc``.
The value of the %%badCodepoint%% depends on the %%reason%%. See [[Utf8ErrorReason]] for details.
The function should return the number of bytes that should be skipped when control resumes to the FSM.
type Utf8ErrorReason
type Utf8ErrorReason = | 'UNEXPECTED_CONTINUE' | 'BAD_PREFIX' | 'OVERRUN' | 'MISSING_CONTINUE' | 'OUT_OF_RANGE' | 'UTF16_SURROGATE' | 'OVERLONG';
When using the UTF-8 error API the following errors can be intercepted and processed as the %%reason%% passed to the [[Utf8ErrorFunc]].
**``"UNEXPECTED_CONTINUE"``** - a continuation byte was present where there was nothing to continue.
**``"BAD_PREFIX"``** - an invalid (non-continuation) byte to start a UTF-8 codepoint was found.
**``"OVERRUN"``** - the string is too short to process the expected codepoint length.
**``"MISSING_CONTINUE"``** - a missing continuation byte was expected but not found. The %%offset%% indicates the index the continuation byte was expected at.
**``"OUT_OF_RANGE"``** - the computed code point is outside the range for UTF-8. The %%badCodepoint%% indicates the computed codepoint, which was outside the valid UTF-8 range.
**``"UTF16_SURROGATE"``** - the UTF-8 strings contained a UTF-16 surrogate pair. The %%badCodepoint%% is the computed codepoint, which was inside the UTF-16 surrogate range.
**``"OVERLONG"``** - the string is an overlong representation. The %%badCodepoint%% indicates the computed codepoint, which has already been bounds checked.
Returns
string
type WebSocketCreator
type WebSocketCreator = () => WebSocketLike;
A function which can be used to re-create a WebSocket connection on disconnect.
namespace ethers.computeHmac
namespace ethers.computeHmac {}
namespace ethers.keccak256
namespace ethers.keccak256 {}
namespace ethers.pbkdf2
namespace ethers.pbkdf2 {}
namespace ethers.randomBytes
namespace ethers.randomBytes {}
namespace ethers.ripemd160
namespace ethers.ripemd160 {}
namespace ethers.scrypt
namespace ethers.scrypt {}
namespace ethers.scryptSync
namespace ethers.scryptSync {}
namespace ethers.sha256
namespace ethers.sha256 {}
namespace ethers.sha512
namespace ethers.sha512 {}
namespace keccak256
namespace keccak256 {}
namespace pbkdf2
namespace pbkdf2 {}
namespace randomBytes
namespace randomBytes {}
namespace ripemd160
namespace ripemd160 {}
namespace scrypt
namespace scrypt {}
namespace scryptSync
namespace scryptSync {}
namespace sha256
namespace sha256 {}
namespace sha512
namespace sha512 {}
namespace ws
module 'ws' {}
class WebSocket
class WebSocket {}
constructor
constructor(...args: any[]);
property onerror
onerror: (...args: Array<any>) => any;
property onmessage
onmessage: (...args: Array<any>) => any;
property onopen
onopen: (...args: Array<any>) => any;
property readyState
readyState: number;
method close
close: (code?: number, reason?: string) => void;
method send
send: (payload: any) => void;
Package Files (93)
- lib.commonjs/_version.d.ts
- lib.commonjs/abi/abi-coder.d.ts
- lib.commonjs/abi/bytes32.d.ts
- lib.commonjs/abi/coders/abstract-coder.d.ts
- lib.commonjs/abi/fragments.d.ts
- lib.commonjs/abi/interface.d.ts
- lib.commonjs/abi/typed.d.ts
- lib.commonjs/address/address.d.ts
- lib.commonjs/address/checks.d.ts
- lib.commonjs/address/contract-address.d.ts
- lib.commonjs/address/index.d.ts
- lib.commonjs/constants/addresses.d.ts
- lib.commonjs/constants/hashes.d.ts
- lib.commonjs/constants/numbers.d.ts
- lib.commonjs/constants/strings.d.ts
- lib.commonjs/contract/contract.d.ts
- lib.commonjs/contract/factory.d.ts
- lib.commonjs/contract/types.d.ts
- lib.commonjs/contract/wrappers.d.ts
- lib.commonjs/crypto/hmac.d.ts
- lib.commonjs/crypto/index.d.ts
- lib.commonjs/crypto/keccak.d.ts
- lib.commonjs/crypto/pbkdf2.d.ts
- lib.commonjs/crypto/random.d.ts
- lib.commonjs/crypto/ripemd160.d.ts
- lib.commonjs/crypto/scrypt.d.ts
- lib.commonjs/crypto/sha2.d.ts
- lib.commonjs/crypto/signature.d.ts
- lib.commonjs/crypto/signing-key.d.ts
- lib.commonjs/ethers.d.ts
- lib.commonjs/hash/id.d.ts
- lib.commonjs/hash/message.d.ts
- lib.commonjs/hash/namehash.d.ts
- lib.commonjs/hash/solidity.d.ts
- lib.commonjs/hash/typed-data.d.ts
- lib.commonjs/index.d.ts
- lib.commonjs/providers/abstract-provider.d.ts
- lib.commonjs/providers/abstract-signer.d.ts
- lib.commonjs/providers/community.d.ts
- lib.commonjs/providers/contracts.d.ts
- lib.commonjs/providers/default-provider.d.ts
- lib.commonjs/providers/ens-resolver.d.ts
- lib.commonjs/providers/formatting.d.ts
- lib.commonjs/providers/network.d.ts
- lib.commonjs/providers/plugins-network.d.ts
- lib.commonjs/providers/provider-alchemy.d.ts
- lib.commonjs/providers/provider-ankr.d.ts
- lib.commonjs/providers/provider-browser.d.ts
- lib.commonjs/providers/provider-chainstack.d.ts
- lib.commonjs/providers/provider-cloudflare.d.ts
- lib.commonjs/providers/provider-etherscan.d.ts
- lib.commonjs/providers/provider-fallback.d.ts
- lib.commonjs/providers/provider-infura.d.ts
- lib.commonjs/providers/provider-ipcsocket.d.ts
- lib.commonjs/providers/provider-jsonrpc.d.ts
- lib.commonjs/providers/provider-pocket.d.ts
- lib.commonjs/providers/provider-quicknode.d.ts
- lib.commonjs/providers/provider-socket.d.ts
- lib.commonjs/providers/provider-websocket.d.ts
- lib.commonjs/providers/provider.d.ts
- lib.commonjs/providers/signer-noncemanager.d.ts
- lib.commonjs/providers/signer.d.ts
- lib.commonjs/transaction/accesslist.d.ts
- lib.commonjs/transaction/address.d.ts
- lib.commonjs/transaction/index.d.ts
- lib.commonjs/transaction/transaction.d.ts
- lib.commonjs/utils/base58.d.ts
- lib.commonjs/utils/base64.d.ts
- lib.commonjs/utils/data.d.ts
- lib.commonjs/utils/errors.d.ts
- lib.commonjs/utils/events.d.ts
- lib.commonjs/utils/fetch.d.ts
- lib.commonjs/utils/fixednumber.d.ts
- lib.commonjs/utils/maths.d.ts
- lib.commonjs/utils/properties.d.ts
- lib.commonjs/utils/rlp-decode.d.ts
- lib.commonjs/utils/rlp-encode.d.ts
- lib.commonjs/utils/rlp.d.ts
- lib.commonjs/utils/units.d.ts
- lib.commonjs/utils/utf8.d.ts
- lib.commonjs/utils/uuid.d.ts
- lib.commonjs/wallet/base-wallet.d.ts
- lib.commonjs/wallet/hdwallet.d.ts
- lib.commonjs/wallet/json-crowdsale.d.ts
- lib.commonjs/wallet/json-keystore.d.ts
- lib.commonjs/wallet/mnemonic.d.ts
- lib.commonjs/wallet/wallet.d.ts
- lib.commonjs/wordlists/lang-en.d.ts
- lib.commonjs/wordlists/wordlist-owl.d.ts
- lib.commonjs/wordlists/wordlist-owla.d.ts
- lib.commonjs/wordlists/wordlist.d.ts
- lib.commonjs/wordlists/wordlists.d.ts
- src.ts/thirdparty.d.ts
Dependencies (7)
Dev Dependencies (9)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/ethers
.
- Markdown[](https://www.jsdocs.io/package/ethers)
- HTML<a href="https://www.jsdocs.io/package/ethers"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 26710 ms. - Missing or incorrect documentation? Open an issue for this package.