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**.