The ethers.js library aims to be a complete and compact library for interacting with the Ethereum Blockchain and its ecosystem.
It is often used to create decentralized applications (dapps), wallets (such as MetaMask and Tally) and other tools and simple scripts that require reading and writing to the blockchain.
These docs are still under construction, and are being expanded every day.
Developers new to Ethers should be sure to read through the Getting Started section.
And the Application Programming Interface is available for drilling down into more details about the entire Application Programming Interface.
This is a very short introduction to Ethers, but covers many of the most common operations that developers require and provides a starting point for those newer to Ethereum.
Everything in Ethers is exported from its root as well as on the ethers object. There are also exports in the package.json to facilitate more fine-grained importing.
Generally this documentation will presume all exports from ethers have been imported in the code examples, but you may import the necessary objects in any way you wish.
To begin, it is useful to have a basic understanding of the types of objects available and what they are responsible for, at a high level.
A Provider is a read-only connection to the blockchain, which allows querying the blockchain state, such as account, block or transaction details, querying event logs or evaluating read-only code using call.
If you are coming from Web3.js, you are used to a Provider offering both read and write access. In Ethers, all write operations are further abstracted into another Object, the Signer.
A Signer wraps all operations that interact with an account. An account generally has a private key located somewhere, which can be used to sign a variety of types of payloads.
The private key may be located in memory (using a Wallet) or protected via some IPC layer, such as MetaMask which proxies interaction from a website to a browser plug-in, which keeps the private key out of the reach of the website and only permits interaction after requesting permission from the user and receiving authorization.
To make any state changes to the blockchain, a transaction is required, which requires a fee to be paid, where the fee covers the associated costs with executing the transaction (such as reading the disk and performing maths) and storing the updated information.
If a transaction reverts, a fee must still be paid, since the validator still had to expend resources to try running the transaction to determine that it reverted and the details of its failure are still be recorded.
Transactions include sending ether from one user to another, deploying a Contract or executing a state-changing operation against a Contract.
A Contract is a program that has been deployed to the blockchain, which includes some code and has allocated storage which it can read from and write to.
It may be read from when it is connected to a Provider or state-changing operations can be called when connected to a Signer.
Once a Transaction has been submitted to the blockchain, it is placed in the memory pool (mempool) until a validator decides to include it.
A transaction's changes are only made once it has been included in the blockchain, at which time a receipt is available, which includes details about the transaction, such as which block it was included in, the actual fee paid, gas used, all the events that it emitted and whether it was successful or reverted.
This very first thing needed to begin interacting with the blockchain is connecting to it using a Provider.
The quickest and easiest way to experiment and begin developing on Ethereum is to use MetaMask, which is a browser extension that injects objects into the window, providing:
- read-only access to the Ethereum network (a Provider)
- authenticated write access backed by a private key (a Signer)
When requesting access to the authenticated methods, such as sending a transaction or even requesting the private key address, MetaMask will show a pop-up to the user asking for permission.
If you are running your own Ethereum node (e.g. Geth) or using a custom third-party service (e.g. INFURA), you can use the JsonRpcProvider directly, which communicates using the link-jsonrpc protocol.
When using your own Ethereum node or a developer-base blockchain, such as Hardhat or Ganache, you can get access to the accounts with JsonRpcProvider-getSigner.
All units in Ethereum tend to be integer values, since dealing with decimals and floating points can lead to imprecise and non-obvious results when performing mathematic operations.
As a result, the internal units used (e.g. wei) which are suited for machine-readable purposes and maths are often very large and not easily human-readable.
For example, imagine dealing with dollars and cents; you would show values like "$2.56". In the blockchain world, we would keep all values as cents, so that would be 256 cents, internally.
So, when accepting data that a user types, it must be converted from its decimal string representation (e.g. "2.56") to its lowest-unit integer representation (e.g. 256). And when displaying a value to a user the opposite operation is necessary.
In Ethereum, one ether is equal to 10 ** 18 wei and one gwei is equal to 10 ** 9 wei, so the values get very large very quickly, so some convenience functions are provided to help convert between representations.
Once you have a Provider, you have a read-only connection to the data on the blockchain. This can be used to query the current account state, fetch historic logs, look up contract code and so on.
To write to the blockchain you require access to a private key which controls some account. In most cases, those private keys are not accessible directly to your code, and instead you make requests via a Signer, which dispatches the request to a service (such as MetaMask) which provides strictly gated access and requires feedback to the user to approve or reject operations.
A Contract is a meta-class, which means that its definition is derived at run-time, based on the ABI it is passed, which then determined what methods and properties are available on it.
Since all operations that occur on the blockchain must be encoded as binary data, we need a concise way to define how to convert between common objects (like strings and numbers) and its binary representation, as well as encode the ways to call and interpret the Contract.
For any method, event or error you wish to use, you must include a Fragment to inform Ethers how it should encode the request and decode the result.
Any methods or events that are not needed can be safely excluded.
There are several common formats available to describe an ABI. The Solidity compiler usually dumps a JSON representation but when typing an ABI by hand it is often easier (and more readable) to use the human-readable ABI, which is just the Solidity signature.
A read-only method is one which cannot change the state of the blockchain, but often provide a simple interface to get important data about a Contract.
When adding event listeners for a named event, the event parameters are destructed for the listener.
There is always one additional parameter passed to a listener, which is an EventPayload, which includes more information about the event including the filter and a method to remove that listener.
When querying within a large range of blocks, some backends may be prohibitively slow, may return an error or may truncate the results without any indication. This is at the discretion of each backend.
A private key can do a lot more than just sign a transaction to authorize it. It can also be used to sign other forms of data, which are then able to be validated for other purposes.
For example, signing a message can be used to prove ownership of an account which a website could use to authenticate a user and log them in.
When interacting with any application, whether it is on Ethereum, over the internet or within a compiled application on a computer all information is stored and sent as binary data which is just a sequence of bytes.
So every application must agree on how to encode and decode their information as a sequence of bytes.
An Application Binary Interface (ABI) provides a way to describe the encoding and decoding process, in a generic way so that a variety of types and structures of types can be defined.
For example, a string is often encoded as a UTF-8 sequence of bytes, which uses specific bits within sub-sequences to indicate emoji and other special characters. Every implementation of UTF-8 must understand and operate under the same rules so that strings work universally. In this way, UTF-8 standard is itself an ABI.
When interacting with Ethereum, a contract received a sequence of bytes as input (provided by sending a transaction or through a call) and returns a result as a sequence of bytes. So, each Contract has its own ABI that helps specify how to encode the input and how to decode the output.
It is up to the contract developer to make this ABI available. Many Contracts implement a standard (such as ERC-20), in which case the ABI for that standard can be used. Many developers choose to verify their source code on Etherscan, in which case Etherscan computes the ABI and provides it through their website (which can be fetched using the getContract method). Otherwise, beyond reverse engineering the Contract there is not a meaningful way to extract the contract ABI.
When calling a Contract on Ethereum, the input data must be encoded according to the ABI.
The first 4 bytes of the data are the method selector, which is the keccak256 hash of the normalized method signature.
Then the method parameters are encoded and concatenated to the selector.
All encoded data is made up of components padded to 32 bytes, so the length of input data will always be congruent to 4 mod 32.
The result of a successful call will be encoded values, whose components are padded to 32 bytes each as well, so the length of a result will always be congruent to 0 mod 32, on success.
The result of a reverted call will contain the error selector as the first 4 bytes, which is the keccak256 of the normalized error signature, followed by the encoded values, whose components are padded to 32 bytes each, so the length of a revert will be congruent to 4 mod 32.
The one exception to all this is that revert(false) will return a result or 0x.
When an Event is emitted from a contract, there are two places data is logged in a Log: the topics and the data.
An additional fee is paid for each topic, but this affords a topic to be indexed in a bloom filter within the block, which allows efficient filtering.
The topic hash is always the first topic in a Log, which is the keccak256 of the normalized event signature. This allows a specific event to be efficiently filtered, finding the matching events in a block.
Each additional indexed parameter (i.e. parameters marked with indexed in the signautre) are placed in the topics as well, but may be filtered to find matching values.
All non-indexed parameters are encoded and placed in the data. This is cheaper and more compact, but does not allow filtering on these values.
For example, the event Transfer(address indexed from, address indexed to, uint value) would require 3 topics, which are the topic hash, the from address and the to address and the data would contain 32 bytes, which is the padded big-endian representation of value. This allows for efficient filtering by the event (i.e. Transfer) as well as the from address and to address.
When deploying a transaction, the data provided is treated as initcode, which executes the data as normal EVM bytecode, which returns a sequence of bytes, but instead of that sequence of bytes being treated as data that result is instead the bytecode to install as the bytecode of the contract.
The bytecode produced by Solidity is designed to have all constructor parameters encoded normally and concatenated to the bytecode and provided as the data to a transaction with no to address.
The Application Binary Interface (ABI) describes how method input parameters should be encoded, their results decoded, and how to decode events and errors.
See About ABIs for more details how they are used.
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.
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.
Creates a new Result for items with each entry also accessible by its corresponding name in keys.
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.
The Interface class is a low-level class that accepts an ABI and provides all the necessary functionality to encode and decode paramaters to and results from methods, events and errors.
It also provides several convenience methods to automatically search and find matching transactions and events to parse them.
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. For example, function balanceOf(address) view returns (uint).
A Parsed JSON Fragment is a JavaScript Object desribed in the Solidity documentation.
When using the interface.parseError to automatically match an error for a call result for parsing, an ErrorDescription is returned.
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.
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.
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.
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.
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.
Encodes the tx.data for a transaction that calls the function specified (see getFunction for valid values for fragment) with the values.
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.
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.
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.
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.
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.
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.
When using the interface.parseLog to automatically match a Log to its event for parsing, a LogDescription is returned.
When using the interface.parseTransaction to automatically match a transaction data to its function for parsing, a TransactionDescription is returned.
A Typed object allows a value to have its type explicitly specified.
For example, in Solidity, the value 45 could represent a uint8 or a uint256. The value 0x1234 could represent a bytes2 or bytes.
Since JavaScript has no meaningful way to explicitly inform any APIs which what the type is, this allows transparent interoperation with Soldity.
Returns true and provides a type guard is this is a TypedBigInt.
Returns true and provides a type guard is this is a TypedString.
When sending values to or receiving values from a Contract, the data is generally encoded using the ABI standard.
The AbiCoder provides a utility to encode values to ABI data and decode values from ABI data.
Most of the time, developers should favour the Contract class, which further abstracts a lot of the finer details of ABI data.
Returns the shared singleton instance of a default AbiCoder.
Returns an ethers-compatible CallExceptionError Error for the given result data for the CallExceptionAction action against the Transaction tx.
A fragment is a single item from an ABI, which may represent any of:
- Functions
- Events
- Constructors
- Custom Errors
- Fallback or Receive functions
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.
The type of a Fragment.
When walking asynchronously a ParamType, this is called on each component.
Returns true if value is a ConstructorFragment.
Returns true if value is an ErrorFragment.
Returns true if value is an EventFragment.
Returns true if value is a FunctionFragment.
Returns true if value is a StructFragment.
A fragment for a method, event or error in a JSON ABI format.
A Type description in a JSON ABI format.
Each input and output of a Fragment is an Array of ParamType.
Returns true if this is an Array type.
This provides a type gaurd ensuring that arrayChildren and arrayLength are non-null.
Returns true if this is an Indexable type.
This provides a type gaurd ensuring that indexed is non-null.
Returns true if this is a Tuple type.
This provides a type gaurd ensuring that components is non-null.
Addresses are a fundamental part of interacting with Ethereum. They represent the gloabal identity of Externally Owned Accounts (accounts backed by a private key) and contracts.
The Ethereum Naming Service (ENS) provides an interconnected ecosystem of contracts, standards and libraries which enable looking up an address for an ENS name.
These functions help convert between various formats, validate addresses and safely resolve ENS names.
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.
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 Wisps: The Magical World of Create2.
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.
The ICAP Address format format is an early checksum format which attempts to be compatible with the banking industry IBAN format for bank accounts.
Returns true if value is an object which implements the Addressable interface.
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.
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.
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.
This can be an address, ENS name or any Addressable, such as another contract. To get the resovled address, use the getAddress method.
Return the transaction used to deploy this contract.
This is only available if this instance was returned from a ContractFactory.
A BaseContract with no type guards on its methods or events.
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.
A ContractTransactionReceipt includes the parsed logs from a TransactionReceipt.
The parsed logs for any Log which has a matching event in the Contract ABI.
A ContractTransactionResponse will return a ContractTransactionReceipt when waited on.
An EventLog contains additional properties parsed from the Log.
An EventLog contains additional properties parsed from the Log.
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.
An HMAC enables verification that a given key was used to authenticate a payload.
See: link-wiki-hmac
Return the 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.
The scrypt PBKDF 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.
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.
The EIP-2098 compact representation of the yParity and s compacted into a single bytes32.
Compute the v for a chain ID for a legacy EIP-155 transactions.
Legacy transactions which use EIP-155 hijack the v property to include the chain ID.
Compute the normalized legacy transaction v from a yParirty, a legacy transaction v or a legacy EIP-155 transaction.
Returns the 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.
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.
Utilities for common tasks involving hashing. Also see cryptographic hashing.
Computes the 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.
A simple hashing function which operates on UTF-8 strings to compute an 32-byte identifier.
This simply computes the UTF-8 bytes and computes the keccak256.
Computes the Non-Standard Packed Mode representation of values respectively to their types.
Computes the Non-Standard Packed Mode keccak256 hash of values respectively to their types.
Computes the Non-Standard Packed Mode sha256 hash of values respectively to their types.
The domain for an EIP-712 payload.
A TypedDataEncode prepares and encodes 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.
Create a new TypedDataEncoder for types.
This performs all necessary checking that types are valid and do not violate the EIP-712 structural constraints as well as computes the primaryType.
Return the fulled encoded value for the types.
Return the hash of the fully encoded value for the types.
Return the fully encoded EIP-712 value for types with domain.
Returns the JSON-encoded payload expected by nodes which implement the JSON-RPC EIP-712 method.
Return the hash of the fully encoded EIP-712 value for types with domain.
A specific field of a structured EIP-712 type.
A Provider provides a connection to the blockchain, whch can be used to query its current state, simulate execution and send transactions to update the state.
It is one of the most fundamental components of interacting with a blockchain application, and there are many ways to connect, such as over HTTP, WebSockets or injected providers such as MetaMask.
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.
The possible additional events dispatched when using the "debug" event on a BrowserProvider.
The gas cost parameters for a GasCostPlugin.
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
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 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"
The total amount of blob gas consumed by the transactions within the block. See EIP-4844.
The running total of blob gas consumed in excess of the target, prior to the block. See EIP-4844.
The hash tree root of the parent beacon block for the given execution block. See EIP-4844.
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.
Returns true if this block been mined. This provides a type guard for all properties on a MinedBlock.
A BrowserProvider is intended to wrap an injected provider which adheres to the EIP-1193 standard, which most (if not all) currently do.
The provider used for necessary state querying operations.
This can also point to the ContractRunner itself, in the case of an AbstractProvider.
The interface to an EIP-1193 provider, which is a standard used by most injected providers, which the BrowserProvider accepts and exposes the API of.
See EIP-1193 for details on this method.
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.
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)
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)
A FeeDataNetworkPlugin allows a network to provide and alternate means to specify its fee data.
For example, a network which does not support EIP-1559 may choose to use a Gas Station site to approximate the gas price.
The fee per address in the EIP-2930 access list.
The fee per storage key in the EIP-2930 access list.
The block hash of the block this log occurred in. Use the log.getBlock to get the Block.
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.
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.
The transaction hash of the transaction this log occurred in. Use the log.getTransaction to get the TransactionResponse.
An Interface to indicate a Block has been included in the blockchain. This asserts a Type Guard that necessary properties are non-null.
A NetworkPlugin provides additional functionality on a Network.
A NonceManager wraps another Signer and automatically manages the nonce, ensuring serialized and sequential nonces are used during transaction.
A PreparedTransactionRequest is identical to a TransactionRequest except all the property types are strictly enforced.
The 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.
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.
The EIP-1559 maximum total fee to pay per gas. The actual value used is protocol enforced to be the block's base fee.
The EIP-1559 maximum priority fee to pay per gas.
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, transaction count, code and state trie storage.
Simulating execution can be used to call, estimate gas and get transaction results.
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.
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.
Simulate the execution of tx. If the call reverts, it will throw a CallExceptionError which includes the revert data.
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.
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.
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.
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).
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.
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.
Prepares a {@link 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)
Signs an 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 ])).
Signs the EIP-712 typed data.
The price paid per BLOB in gas. See EIP-4844.
The block hash of the Block this transaction was included in.
The block number of the Block this transaction was included in.
The actual gas price used during execution.
Due to the complexity of EIP-1559 this value can only be caluclated after the transaction has been mined, snce the base fee is protocol-enforced.
The 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.
Any blobs to include in the transaction (see EIP-4844).
The blob versioned hashes (see EIP-4844).
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.
An external library for computing the KZG commitments and proofs necessary for EIP-4844 transactions (see EIP-4844).
This is generally null, unless you are creating BLOb transactions.
The maximum fee per blob gas (see EIP-4844).
The EIP-1559 maximum total fee to pay per gas. The actual value used is protocol enforced to be the block's base fee.
The EIP-1559 maximum priority fee to pay per gas.
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.
The EIP-2930 access list for transaction types that support it, otherwise null.
The EIP-4844 BLOb versioned hashes.
The sender of this transaction. It is implicitly computed from the transaction pre-image hash (as the digest) and the signature using ecrecover.
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.
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.
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.
The EIP-2718 transaction envelope type. This is 0 for legacy transactions types.
The value, in wei. Use formatEther to format this value as ether.
Returns true if the transaction is a Berlin (i.e. type == 1) transaction. See EIP-2930.
This provides a Type Guard that this transaction will have the null-ness for hardfork-specific properties set correctly.
Returns true if hte transaction is a Cancun (i.e. type == 3) transaction. See EIP-4844.
Returns true if the transaction is a London (i.e. type == 2) transaction. See EIP-1559.
This provides a Type Guard that this transaction will have the null-ness for hardfork-specific properties set correctly.
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.
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.
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.
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
The available providers should suffice for most developers purposes, but the AbstractProvider class has many features which enable sub-classing it for specific purposes.
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)
A normalized filter used for PerformActionRequest objects.
The AbstractProvider methods will normalize all values and pass this type to abstractProvider._perform.
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.
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.
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.
Prevent any CCIP-read operation, regardless of whether requested in a call using enableCcipRead.
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.
Returns this, to allow an AbstractProvider to implement the ContractRunner interface.
Create a new AbstractProvider connected to network, or use the various network detection capabilities to discover the Network if necessary.
Clear a timer created using the _setTimeout method.
Returns or resolves to the address for address, resolving ENS names and Addressable objects and returning if already an address.
Returns or resolves to a filter for filter, resolving any ENS names or Addressable object and returning if already a valid filter.
Returns or resolves to a transaction for request, resolving any ENS names or Addressable and returning if already a valid transaction.
If a Subscriber fails and needs to replace itself, this method may be used.
For example, this is used for providers when using the eth_getFilterChanges method, which can return null if state filters are not supported by the backend, allowing the Subscriber to swap in a PollingEventSubscriber.
Create a timer that will execute func after at least timeout (in ms). If timeout is unspecified, then func will execute in the next event loop.
Pausing the provider will pause any associated timers.
Provides the opportunity for a sub-class to wrap a block before returning it, to add additional properties or an alternate sub-class of Block.
Provides the opportunity for a sub-class to wrap a log before returning it, to add additional properties or an alternate sub-class of Log.
Provides the opportunity for a sub-class to wrap a transaction receipt before returning it, to add additional properties or an alternate sub-class of TransactionReceipt.
Provides the opportunity for a sub-class to wrap a transaction response before returning it, to add additional properties or an alternate sub-class of TransactionResponse.
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.
Creates a new FilterIdSubscriber which will used _subscribe and _emitResults to setup the subscription and provide the event to the provider.
An OnBlockSubscriber can be sub-classed, with a _poll implmentation which will be called on every new block.
A normalized transactions used for PerformActionRequest objects.
Called when the subscription should pause.
If dropWhilePaused, events that occur while paused should not be emitted resume.
A SocketSubscriber uses a socket transport to handle events and should use _emit to manage the events.