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 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 global 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 signature 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 resolved 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.
Returns the canonical signature.
This is only necessary when dealing with legacy transaction which did not enforce canonical S values (i.e. EIP-155. Most developers should never require this.
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-7702 authorization digest to sign.
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-4788.
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.
Discover and connect to a Provider in the Browser using the EIP-6963 discovery mechanism. If no providers are present, null is resolved.
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.
Provider info provided by the EIP-6963 discovery mechanism.
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.
The EIP-7702 authorizations (if any).
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).
Signs an authorization to be used in EIP-7702 transactions.
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 an AuthorizationRequest for authorization by populating any missing properties:
- resolves address (if an Addressable or ENS name)
- populates nonce via signer.getNonce("pending")
- populates chainId via signer.provider.getNetwork()
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.
The EIP-7702 authorizations (if any).
Any blobs to include in the transaction (see EIP-4844).
The blob versioned hashes (see EIP-4844).
The EIP-7594 BLOb Wrapper Version used for PeerDAS.
For networks that use EIP-7594, this property is required to serialize the sidecar correctly.
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-7702 authorizations (if any).
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.
Generally the Wallet and JsonRpcSigner and their sub-classes are sufficient for most developers, but this is provided to fascilitate more complex Signers.
An AbstractSigner includes most of teh functionality required to get a Signer working as expected, but requires a few Signer-specific methods be overridden.
A VoidSigner is a class designed to allow an address to be used in any API which accepts a Signer, but for which there are no credentials available to perform any actual signing.
This for example allow impersonating an account for the purpose of static calls or estimating gas, but does not allow sending transactions.
How the url was arrived at, resolving the many steps required for an avatar URL.
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.
Additional options to configure a FallbackProvider.
Creates a new FallbackProvider with providers connected to network.
If a Provider is included in providers, defaults are used for the configuration.
A configuration entry for how to use a Provider.
The statistics and state maintained for a Provider.
The protocol-defined base fee per gas in an EIP-1559 block.
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-4788.
The hash of the previous block in the blockchain. The genesis block has the parentHash of the ZeroHash.
The actual BLOb gas price that was charged. See EIP-4844.
If the transaction was directly deploying a contract, the to will be null, the data will be initcode and if successful, this will be the address of the contract deployed.
The EIP-7702 authorizations (if any).
The EIP-4844 BLOb versioned hashes.
For EIP-4844 transactions, this is the maximum fee that will be paid per BLOb.
For EIP-1559 transactions, this is the maximum fee that will be paid.
For EIP-1559 transactions, this is the maximum priority fee to allow a producer to claim.
One of the most common ways to interact with the blockchain is by a node running a JSON-RPC interface which can be connected to, based on the transport, using:
- HTTP or HTTPS - JsonRpcProvider
- WebSocket - WebSocketProvider
- IPC - IpcSocketProvider
When subscribing to the "debug" event, the Listener will receive this object as the first parameter.
Options for configuring a JsonRpcApiProvider. Much of this is targetted towards sub-classes, which often will not expose any of these options to their consumers.
polling - use the polling strategy is used immediately for events; otherwise, attempt to use filters and fall back onto polling (default: false)
staticNetwork - do not request chain ID on requests to validate the underlying chain has not changed (default: null)
This should ONLY be used if it is certain that the network cannot change, such as when using INFURA (since the URL dictates the network). If the network is assumed static and it does change, this can have tragic consequences. For example, this CANNOT be used with MetaMask, since the user can select a new network from the drop-down at any time.
batchStallTime - how long (ms) to aggregate requests into a single batch. 0 indicates batching will only encompass the current event loop. If batchMaxCount = 1, this is ignored. (default: 10)
batchMaxSize - target maximum size (bytes) to allow per batch request (default: 1Mb)
batchMaxCount - maximum number of requests to allow in a batch. If batchMaxCount = 1, then batching is disabled. (default: 100)
cacheTimeout - passed as AbstractProviderOptions.
Gets the Network this provider has committed to. On each call, the network is detected, and if it has changed, the call will reject.
Resolves once the _start has been called. This can be used in sub-classes to defer sending data until the connection has been established.
Resolves to the Signer account for address managed by the client.
If the address is a number, it is used as an index in the the accounts from listAccounts.
This can only be used on clients which manage accounts (such as Geth with imported account or MetaMask).
Requests the method with params via the JSON-RPC protocol over the underlying channel. This can be used to call methods on the backend that do not have a high-level API within the Provider API.
This method queues requests according to the batch constraints in the options, assigns the request a unique ID.
Do NOT override this method in sub-classes; instead override _send or force the options values in the call to the constructor to modify this method's behavior.
The gas price per wei for transactions prior to EIP-1559.
The maximum fee per gas for EIP-1559 transactions.
The maximum priority fee per gas for EIP-1559 transactions.
The AlchemyProvider connects to the 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.
Alchemy provides a third-party service for connecting to various blockchains over JSON-RPC.
- Ethereum Mainnet (mainnet)
- Goerli Testnet (goerli)
- Sepolia Testnet (sepolia)
- Arbitrum (arbitrum)
- Arbitrum Goerli Testnet (arbitrum-goerli)
- Arbitrum Sepolia Testnet (arbitrum-sepolia)
- Base (base)
- Base Goerlia Testnet (base-goerli)
- Base Sepolia Testnet (base-sepolia)
- Optimism (optimism)
- Optimism Goerli Testnet (optimism-goerli)
- Optimism Sepolia Testnet (optimism-sepolia)
- Polygon (matic)
- Polygon Amoy Testnet (matic-amoy)
- Polygon Mumbai Testnet (matic-mumbai)
Ankr provides a third-party service for connecting to various blockchains over JSON-RPC.
- Ethereum Mainnet (mainnet)
- Goerli Testnet (goerli)
- Sepolia Testnet (sepolia)
- Arbitrum (arbitrum)
- Base (base)
- Base Goerlia Testnet (base-goerli)
- Base Sepolia Testnet (base-sepolia)
- BNB (bnb)
- BNB Testnet (bnbt)
- Filecoin (filecoin)
- Filecoin Calibration Testnet (filecoin-calibration)
- Optimism (optimism)
- Optimism Goerli Testnet (optimism-goerli)
- Optimism Sepolia Testnet (optimism-sepolia)
- Polygon (matic)
- Polygon Mumbai Testnet (matic-mumbai)
The AnkrProvider connects to the 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.
Blockscout provides a third-party service for connecting to various blockchains over JSON-RPC.
- Ethereum Mainnet (mainnet)
- Sepolia Testnet (sepolia)
- Holesky Testnet (holesky)
- Ethereum Classic (classic)
- Arbitrum (arbitrum)
- Base (base)
- Base Sepolia Testnet (base-sepolia)
- Gnosis (xdai)
- Optimism (optimism)
- Optimism Sepolia Testnet (optimism-sepolia)
- Polygon (matic)
The BlockscoutProvider connects to the Blockscout 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.
Chainstack provides a third-party service for connecting to various blockchains over JSON-RPC.
- Ethereum Mainnet (mainnet)
- Arbitrum (arbitrum)
- BNB Smart Chain Mainnet (bnb)
- Polygon (matic)
The ChainstackProvider connects to the 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.
Etherscan provides a third-party service for connecting to various blockchains over a combination of JSON-RPC and custom API endpoints.
- Ethereum Mainnet (mainnet)
- Goerli Testnet (goerli)
- Sepolia Testnet (sepolia)
- Holesky Testnet (holesky)
- Arbitrum (arbitrum)
- Arbitrum Goerli Testnet (arbitrum-goerli)
- Base (base)
- Base Sepolia Testnet (base-sepolia)
- BNB Smart Chain Mainnet (bnb)
- BNB Smart Chain Testnet (bnbt)
- Optimism (optimism)
- Optimism Goerli Testnet (optimism-goerli)
- Polygon (matic)
- Polygon Mumbai Testnet (matic-mumbai)
- Polygon Amoy Testnet (matic-amoy)
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.
If an EtherscanPlugin is configured on the EtherscanBaseProvider_network, returns the plugin's baseUrl.
Deprecated; for Etherscan v2 the base is no longer a simply host, but instead a URL including a chainId parameter. Changing this to return a URL prefix could break some libraries, so it is left intact but will be removed in the future as it is unused.
INFURA provides a third-party service for connecting to various blockchains over JSON-RPC.
- Ethereum Mainnet (mainnet)
- Goerli Testnet (goerli)
- Sepolia Testnet (sepolia)
- Arbitrum (arbitrum)
- Arbitrum Goerli Testnet (arbitrum-goerli)
- Arbitrum Sepolia Testnet (arbitrum-sepolia)
- Base (base)
- Base Goerlia Testnet (base-goerli)
- Base Sepolia Testnet (base-sepolia)
- BNB Smart Chain Mainnet (bnb)
- BNB Smart Chain Testnet (bnbt)
- Linea (linea)
- Linea Goerli Testnet (linea-goerli)
- Linea Sepolia Testnet (linea-sepolia)
- Optimism (optimism)
- Optimism Goerli Testnet (optimism-goerli)
- Optimism Sepolia Testnet (optimism-sepolia)
- Polygon (matic)
- Polygon Amoy Testnet (matic-amoy)
- Polygon Mumbai Testnet (matic-mumbai)
The InfuraProvider connects to the INFURA JSON-RPC end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to sign up here.
The InfuraWebSocketProvider connects to the INFURA WebSocket end-points.
By default, a highly-throttled API key is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to sign up here.
Pocket Network provides a third-party service for connecting to various blockchains over JSON-RPC.
- Ethereum Mainnet (mainnet)
- Goerli Testnet (goerli)
- Polygon (matic)
- Arbitrum (arbitrum)
The PocketProvider connects to the Pocket Network 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.
QuickNode provides a third-party service for connecting to various blockchains over JSON-RPC.
- Ethereum Mainnet (mainnet)
- Goerli Testnet (goerli)
- Sepolia Testnet (sepolia)
- Holesky Testnet (holesky)
- Arbitrum (arbitrum)
- Arbitrum Goerli Testnet (arbitrum-goerli)
- Arbitrum Sepolia Testnet (arbitrum-sepolia)
- Base Mainnet (base);
- Base Goerli Testnet (base-goerli);
- Base Sepolia Testnet (base-sepolia);
- BNB Smart Chain Mainnet (bnb)
- BNB Smart Chain Testnet (bnbt)
- Optimism (optimism)
- Optimism Goerli Testnet (optimism-goerli)
- Optimism Sepolia Testnet (optimism-sepolia)
- Polygon (matic)
- Polygon Mumbai Testnet (matic-mumbai)
The QuickNodeProvider connects to the QuickNode JSON-RPC end-points.
By default, a highly-throttled API token is used, which is appropriate for quick prototypes and simple scripts. To gain access to an increased rate-limit, it is highly recommended to sign up here.
An ordered collection of AccessList entries.
A single AccessList entry of storage keys (slots) for an address.
A BLOb object that can be passed for EIP-4844 transactions.
It may have had its commitment and proof already provided or rely on an attached KzgLibrary to compute them.
A KZG Library with any of the various API configurations. As the library is still experimental and the API is not stable, depending on the version used the method names and signatures are still in flux.
This allows any of the versions to be passed into Transaction while providing a stable external API.
Returns a AccessList from any ethers-supported access-list structure.
A full-valid BLOb object for EIP-4844 transactions.
The commitment and proof should have been computed using a KZG library.
The BLObs for the Transaction, if any.
If blobs is non-null, then the seriailized will return the network formatted sidecar, otherwise it will return the standard EIP-2718 payload. The unsignedSerialized is unaffected regardless.
When setting blobs, either fully valid Blob objects may be specified (i.e. correctly padded, with correct committments and proofs) or a raw BytesLike may be provided.
If raw BytesLike are provided, the kzg property must be already set. The blob will be correctly padded and the KzgLibrary will be used to compute the committment and proof for the blob.
A BLOb is a sequence of field elements, each of which must be within the BLS field modulo, so some additional processing may be required to encode arbitrary data to ensure each 32 byte field is within the valid range.
Setting this automatically populates blobVersionedHashes, overwriting any existing values. Setting this to null does not remove the blobVersionedHashes, leaving them present.
This throws if the transaction is unsigned. For the pre-image, use unsignedSerialized.
The pre-image hash of this transaction.
This is the digest that a Signer must sign to authorize this transaction.
Returns true if this transaction is an EIP-4844 BLOB transaction.
This provides a Type Guard that the related properties are non-null.
The EIP-7702 authorizations (if any).
The blobs (if any) attached to this transaction (see EIP-4844).
The versioned hashes (see EIP-4844).
The EIP-7594 BLOb Wrapper Version used for PeerDAS.
For networks that use EIP-7594, this property is required to serialize the sidecar correctly.
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 Base58 Encoding scheme allows a numeric value to be encoded as a compact string using a radix of 58 using only alpha-numeric characters. Confusingly similar characters are omitted (i.e. "l0O").
Note that Base58 encodes a numeric value, not arbitrary bytes, since any zero-bytes on the left would get removed. To mitigate this issue most schemes that use Base58 choose specific high-order values to ensure non-zero prefixes.
Base64 encoding using 6-bit words to encode arbitrary bytes into a string using 65 printable symbols, the upper-case and lower-case alphabet, the digits 0 through 9, "+" and "/" with the "=" used for padding.
A HexString whose length is even, which ensures it is a valid representation of binary data.
Returns a DataHexString by concatenating all values within data.
Returns a DataHexString by slicing data from the start offset to the end offset.
Get a typed Uint8Array for value. If already a Uint8Array the original value is returned; if a copy is required use getBytesCopy.
Returns a DataHexString representation of data.
Returns true if value is a valid representation of arbitrary data (i.e. a valid DataHexString or a Uint8Array).
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).
Return the DataHexString result by stripping all leading * zero bytes from data.
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).
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).
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.
The Recursive-Length Prefix (RLP) encoding is used throughout Ethereum to serialize nested structures of Arrays and data.
Encodes object as an RLP-encoded DataHexString.
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
A callback that can be used with toUtf8String to analysis or recovery from invalid UTF-8 data.
Parsing UTF-8 data is done through a simple Finite-State Machine (FSM) which calls the Utf8ErrorFunc if a fault is detected.
The reason indicates where in the FSM execution the fault occurred and the offset indicates where the input failed.
The bytes represents the raw UTF-8 data that was provided and output is the current array of UTF-8 code-points, which may be updated by the Utf8ErrorFunc.
The value of the badCodepoint depends on the reason. See Utf8ErrorReason for details.
The function should return the number of bytes that should be skipped when control resumes to the FSM.
When using the UTF-8 error API the following errors can be intercepted and processed as the reason passed to the Utf8ErrorFunc.
"UNEXPECTED_CONTINUE" - a continuation byte was present where there was nothing to continue.
"BAD_PREFIX" - an invalid (non-continuation) byte to start a UTF-8 codepoint was found.
"OVERRUN" - the string is too short to process the expected codepoint length.
"MISSING_CONTINUE" - a missing continuation byte was expected but not found. The offset indicates the index the continuation byte was expected at.
"OUT_OF_RANGE" - the computed code point is outside the range for UTF-8. The badCodepoint indicates the computed codepoint, which was outside the valid UTF-8 range.
"UTF16_SURROGATE" - the UTF-8 strings contained a UTF-16 surrogate pair. The badCodepoint is the computed codepoint, which was inside the UTF-16 surrogate range.
"OVERLONG" - the string is an overlong representation. The badCodepoint indicates the computed codepoint, which has already been bounds checked.
Returns 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)
Most interactions with Ethereum requires integer values, which use the smallest magnitude unit.
For example, imagine dealing with dollars and cents. Since dollars are divisible, non-integer values are possible, such as $10.77. By using the smallest indivisible unit (i.e. cents), the value can be kept as the integer 1077.
When receiving decimal input from the user (as a decimal string), the value should be converted to an integer and when showing a user a value, the integer value should be converted to a decimal string.
This creates a clear distinction, between values to be used by code (integers) and values used for display logic to users (decimals).
The native unit in Ethereum, ether is divisible to 18 decimal places, where each individual unit is called a wei.
All errors in ethers include properties to ensure they are both human-readable (i.e. .message) and machine-readable (i.e. .code).
The isError function can be used to check the error code and provide a type guard for the properties present on that error interface.
A conditional type that transforms the ErrorCode T into its EthersError type.
All errors emitted by ethers have an ErrorCode to help identify and coalesce errors to simplify programmatic analysis.
Each ErrorCode is the code proerty of a coresponding EthersError.
"UNKNOWN_ERROR" - see UnknownError
"NOT_IMPLEMENTED" - see NotImplementedError
"UNSUPPORTED_OPERATION" - see UnsupportedOperationError
"NETWORK_ERROR" - see NetworkError
"SERVER_ERROR" - see ServerError
"TIMEOUT" - see TimeoutError
"BAD_DATA" - see BadDataError
"CANCELLED" - see CancelledError
"BUFFER_OVERRUN" - see BufferOverrunError
"NUMERIC_FAULT" - see NumericFaultError
"INVALID_ARGUMENT" - see InvalidArgumentError
"MISSING_ARGUMENT" - see MissingArgumentError
"UNEXPECTED_ARGUMENT" - see UnexpectedArgumentError
"CALL_EXCEPTION" - see CallExceptionError
"INSUFFICIENT_FUNDS" - see InsufficientFundsError
"NONCE_EXPIRED" - see NonceExpiredError
"REPLACEMENT_UNDERPRICED" - see ReplacementUnderpricedError
"TRANSACTION_REPLACED" - see TransactionReplacedError
"UNCONFIGURED_NAME" - see UnconfiguredNameError
"OFFCHAIN_FAULT" - see OffchainFaultError
"ACTION_REJECTED" - see ActionRejectedError
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.
This Error indicates an ENS name was used, but the name has not been configured.
This could indicate an ENS name is unowned or that the current address being pointed to is the ZeroAddress.
When an EventEmitterable triggers a Listener, the callback always ahas one additional argument passed, which is an EventPayload.
Fetching content from the web is environment-specific, so Ethers provides an abstraction that each environment can implement to provide this service.
On Node.js, the http and https libs are used to create a request object, register event listeners and process data and populate the FetchResponse.
In a browser, the DOM fetch is used, and the resulting Promise is waited on to retrieve the payload.
The FetchRequest is responsible for handling many common situations, such as redirects, server throttling, authentication, etc.
It also handles common gateways, such as IPFS and data URIs.
This can be used to control how throttling is handled in fetchRequest.setThrottleParams.
Represents a request for a resource using a URI.
By default, the supported schemes are HTTP, HTTPS, data:, and IPFS:.
Additional schemes can be added globally using registerGateway.
The fetch body, if any, to send as the request body. (default: null)
When setting a body, the intrinsic Content-Type is automatically set and will be used if not overridden by setting a custom header.
If body is null, the body is cleared (along with the intrinsic Content-Type).
If body is a string, the intrinsic Content-Type is set to text/plain.
If body is a Uint8Array, the intrinsic Content-Type is set to application/octet-stream.
If body is any other object, the intrinsic Content-Type is set to application/json.
This function is called to fetch content from HTTP and HTTPS URLs and is platform specific (e.g. nodejs vs browsers).
This is by default the currently registered global getUrl function, which can be changed using registerGetUrl. If this has been set, setting is to null will cause this FetchRequest (and any future clones) to revert back to using the currently registered global getUrl function.
Setting this is generally not necessary, but may be useful for developers that wish to intercept requests or to configurege a proxy or other agent.
This function is called after each response, offering an opportunity to provide client-level throttling or updating response data.
Any error thrown in this causes the send() to throw.
To schedule a retry attempt (assuming the maximum retry limit has not been reached), use [[response.throwThrottleError]].
Cancels the inflight response, causing a CANCELLED error to be rejected from the send.
Returns a new FetchRequest that represents the redirection to location.
Creates a getUrl function that fetches content from HTTP and HTTPS URLs.
The available options are dependent on the platform implementation of the default getUrl function.
This is not generally something that is needed, but is useful when trying to customize simple behaviour when fetching HTTP content.
Use the func when fetching URIs using scheme.
This method affects all requests globally.
If lockConfig has been called, no change is made and this throws.
Use getUrl when fetching URIs over HTTP and HTTPS requests.
This method affects all requests globally.
If lockConfig has been called, no change is made and this throws.
If called within a request.processFunc call, causes the request to retry as if throttled for stall milliseconds.
A description of a fixed-point arithmetic field.
When specifying the fixed format, the values override the default of a fixed128x18, which implies a signed 128-bit value with 18 decimals of precision.
The alias fixed and ufixed can be used for fixed128x18 and ufixed128x18 respectively.
When a fixed format string begins with a u, it indicates the field is unsigned, so any negative values will overflow. The first number indicates the bit-width and the second number indicates the decimal precision.
When a number is used for a fixed format, it indicates the number of decimal places, and the default width and signed-ness will be used.
The bit-width must be byte aligned and the decimals can be at most 80.
A FixedNumber represents a value over its FixedFormat arithmetic field.
A FixedNumber can be used to perform math, losslessly, on values which have decmial places.
A FixedNumber has a fixed bit-width to store values in, and stores all values internally by multiplying the value by 10 raised to the power of decimals.
If operations are performed that cause a value to grow too high (close to positive infinity) or too low (close to negative infinity), the value is said to overflow.
For example, an 8-bit signed value, with 0 decimals may only be within the range -128 to 127; so -128 - 1 will overflow and become 127. Likewise, 127 + 1 will overflow and become -127.
Many operation have a normal and unsafe variant. The normal variant will throw a NumericFaultError on any overflow, while the unsafe variant will silently allow overflow, corrupting its value value.
If operations are performed that cause a value to become too small (close to zero), the value loses precison and is said to underflow.
For example, a value with 1 decimal place may store a number as small as 0.1, but the value of 0.1 / 2 is 0.05, which cannot fit into 1 decimal place, so underflow occurs which means precision is lost and the value becomes 0.
Some operations have a normal and signalling variant. The normal variant will silently ignore underflow, while the signalling variant will thow a NumericFaultError on underflow.
The value as an integer, based on the smallest unit the decimals allow.
Creates a new FixedNumber with the big-endian representation value with format.
This will throw a NumericFaultError if value cannot fit in format due to overflow.
Creates a new FixedNumber for value with format.
This will throw a NumericFaultError if value cannot fit in format, either due to overflow or underflow (precision loss).
Creates a new FixedNumber for value divided by decimal places with format.
This will throw a NumericFaultError if value (once adjusted for decimals) cannot fit in format, either due to overflow or underflow (precision loss).
Returns a new FixedNumber with the result of this added to other. A NumericFaultError is thrown if overflow occurs.
Returns a new FixedNumber with the result of this added to other, ignoring overflow.
Returns a new FixedNumber which is the smallest integer that is greater than or equal to this.
Returns a new FixedNumber with the result of this divided by other, ignoring underflow (precision loss). A NumericFaultError is thrown if overflow occurs.
Returns a new FixedNumber with the result of this divided by other. A NumericFaultError is thrown if underflow (precision loss) occurs.
Returns a new FixedNumber with the result of this divided by other, ignoring underflow (precision loss). A NumericFaultError is thrown if overflow occurs.
Returns a new FixedNumber which is the largest integer that is less than or equal to this.
Returns a new FixedNumber with the result of this multiplied by other. A NumericFaultError is thrown if overflow occurs.
Returns a new FixedNumber with the result of this multiplied by other. A NumericFaultError is thrown if overflow occurs or if underflow (precision loss) occurs.
Returns a new FixedNumber with the result of this multiplied by other, ignoring overflow and underflow (precision loss).
Returns a new FixedNumber with the decimal component rounded up on ties at decimals places.
Returns a new FixedNumber with the result of other subtracted from this. A NumericFaultError is thrown if overflow occurs.
Returns a new FixedNumber with the result of other subtracted from this, ignoring overflow.
Return a new FixedNumber with the same value but has had its field set to format.
When interacting with Ethereum, it is necessary to use a private key authenticate actions by signing a payload.
Wallets are the simplest way to expose the concept of an Externally Owner Account (EOA) as it wraps a private key and supports high-level methods to sign common types of interaction and send transactions.
The class most developers will want to use is Wallet, which can load a private key directly or from any common wallet format.
The HDNodeWallet can be used when it is necessary to access low-level details of how an HD wallets are derived, exported or imported.
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.
The SigningKey used for signing payloads.
A Mnemonic wraps all properties required to compute BIP-39 seeds and convert between phrases and entropy.
The mnemonic phrase of 12, 15, 18, 21 or 24 words.
Use the wordlist split method to get the individual words.
Create a new Mnemonic from the entropy.
The default password is the empty string and the default wordlist is the English wordlists.
Creates a new Mnemonic for the phrase.
The default password is the empty string and the default wordlist is the English wordlists.
Returns true if phrase is a valid BIP-39 phrase.
This checks all the provided words belong to the wordlist, that the length is valid and the checksum is correct.
A Wallet manages a single private key which is used to sign transactions, messages and other common payloads.
This class is generally the main entry point for developers that wish to use a private key directly, as it can create instances from a large variety of common sources, including raw private key, BIP-39 mnemonics and encrypte JSON wallets.
Resolves to a JSON Keystore Wallet encrypted with password.
If progressCallback is specified, it will receive periodic updates as the encryption process progreses.
Returns a JSON Keystore Wallet encryped with password.
It is preferred to use the async version instead, which allows a ProgressCallback to keep the user informed.
This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial duration.
Creates a new random HDNodeWallet using the available cryptographic random source.
Creates a Wallet by decrypting the json with password.
The fromEncryptedJson method is preferred, as this method will lock up and freeze the UI during decryption, which may take some time.
Creates a HDNodeWallet for phrase.
Returns the BIP-32 path for the account at index.
This is the pattern used by wallets like Ledger.
There is also an alternate pattern used by some software.
A HDNodeVoidWallet cannot sign, but provides access to the children nodes of a BIP-32 HD wallet addresses.
The can be created by using an extended xpub key to HDNodeWallet.fromExtendedKey or by nuetering a HDNodeWallet.
Resolves to a JSON Keystore Wallet encrypted with password.
If progressCallback is specified, it will receive periodic updates as the encryption process progreses.
Returns a JSON Keystore Wallet encryped with password.
It is preferred to use the async version instead, which allows a ProgressCallback to keep the user informed.
This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial duration.
Creates a new HD Node from extendedKey.
If the extendedKey will either have a prefix or xpub or xpriv, returning a neutered HD Node (HDNodeVoidWallet) or full HD Node ([[HDNodeWallet) respectively.
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 Crowdsale Wallet 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.
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.
Returns the account details for the JSON Keystore Wallet json using password.
It is preferred to use the async version 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.
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..
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.
A Wordlist is a set of 2048 words used to encode private keys (or other binary data) that is easier for humans to write down, transcribe and dictate.
The BIP-39 standard includes several checksum bits, depending on the size of the mnemonic phrase.
A mnemonic phrase may be 12, 15, 18, 21 or 24 words long. For most purposes 12 word mnemonics should be used, as including additional words increases the difficulty and potential for mistakes and does not offer any effective improvement on security.
There are a variety of BIP-39 Wordlists for different languages, but for maximal compatibility, the English Wordlist is recommended.
The available Wordlists by their ISO 639-1 Language Code.
(i.e. cz, en, es, fr, ja, ko, it, pt, zh_cn, zh_tw)
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.
A Wordlist represents a collection of language-specific words used to encode and devoce BIP-39 encoded data by mapping words to 11-bit values and vice versa.
Creates a new Wordlist instance.
Sub-classes MUST call this if they provide their own constructor, passing in the locale string of the language.
Generally there is no need to create instances of a Wordlist, since each language-specific Wordlist creates an instance and there is no state kept internally, so they are safe to share.
An OWL format Wordlist is an encoding method that exploits the general locality of alphabetically sorted words to achieve a simple but effective means of compression.
This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages based on ASCII-7 small.
If necessary, there are tools within the generation/ folder to create the necessary data.
An OWL-A format Wordlist extends the OWL format to add an overlay onto an OWL format Wordlist to support diacritic marks.
This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages based on latin-1 small.
If necessary, there are tools within the generation/ folder to create the necessary data.
Here is a short recipe to get all the text records set for an ENS name.
It first queries all TextChanged events on the resolver, and uses a MulticallProvider to batch all the eth_call queries for each key into a single eth_call. As such, you will need to install:
When using React Native, many of the built-in cryptographic primitives can be replaced by native, substantially faster implementations.
This should be available in its own package in the future, but for now this is highly recommended, and requires installing the Quick Crypto package.
Signing content and providing the content and signature to a Contract allows on-chain validation that a signer has access to the private key of a specific address.
The ecrecover algorithm allows the public key to be determined given some message digest and the signature generated by the private key for that digest. From the public key, the address can then be computed.
How a digest is derived depends on the type of data being signed and a variety of encoding formats are employed. Each format is designed to ensure that they do not collide, so for example, a user cannot be tricked into signing a message which is actually a valid transaction.
For this reason, most APIs in Ethereum do not permit signing a raw digest, and instead require a separate API for each format type and require the related data be specified, protecting the user from accidentally authorizing an action they didn't intend.
A signed message can be any data, but it is generally recommended to use human-readable text, as this is easier for a user to verify visually.
This technique could be used, for example, to sign into a service by using the text "I am signing into ethers.org on 2023-06-04 12:57pm". The user can then see the message in MetaMask or on a Ledger Hardware Wallet and accept that they wish to sign the message which the site can then authenticate them with. By providing a timestamp the site can ensure that an older signed message cannot be used again in the future.
The format that is signed uses EIP-191 with the personal sign version code (0x45, or "E").
For those interested in the choice of this prefix, signed messages began as a Bitcoin feature, which used "\x18Bitcoin Signed Message:\n", which was a Bitcoin var-int length-prefixed string (as 0x18 is 24, the length of "Bitcoin Signed Message:\n".). When Ethereum adopted the similar feature, the relevant string was "\x19Ethereum Signed Message:\n".
In one of the most brilliant instances of technical retcon-ing, since 0x19 is invalid as the first byte of a transaction (in Recursive-Length Prefix it indicates a single byte of value 25), the initial byte \x19 has now been adopted as a prefix for some sort of signed data, where the second byte determines how to interpret that data. If the second byte is 69 (the letter "E", as in "Ethereum Signed Message:\n"), then the format is a the above prefixed message format.
So, all existing messages, tools and instances using the signed message format were already EIP-191 compliant, long before the standard existed or was even conceived and allowed for an extensible format for future formats (of which there now a few).
Anyways, the necessary JavaScript and Solidity are provided below.
The Solidity Contract has been deployed and verified on the Sepolia testnet at the address 0xf554DA5e35b2e40C09DDB481545A395da1736513.
It provides a variety of examples using various Signature encodings and formats, to recover the address for an EIP-191 signed message.
One of the biggest changes in v6 is that the BigNumber class has been replaced with the built-in ES2020 BigInt offered by modern JavaScript environments.
There is plenty of online documentation to get you started with JavaScript ES2020 BigInt. Keep in mind, just like BigNumber, a ES2020 BigInt can only operate on integers.
The FixedNumber class still exists for performing fixed-point maths.
The Contract is an ES6 Proxy, which means it can resolve method names at run-time.
In v5, in the case of an ambiguous method, it was necessary to look up a method by its canonical normalized signature. In v6 the signature does not need to be normalized and the Typed API provides a cleaner way to access the desired method.
In v5, duplicate definitions also injected warnings into the console, since there was no way to detect them at run-time.
In v5, contracts contained a series of method buckets, which then in turn had all signatures and non-ambiguous names attached to them to perform less-common operations.
In v6, the methods each have their own less-common operations attached directly to them.
In v5, the project was maintained as a large set of sub-packages managed as a monorepo.
In v6 all imports are available in the root package, and for those who wish to have finer-grained control, the pkg.exports makes certain folders available directly.
In addition to all the ethers.providers.* being moved to ethers.*, the biggest change developers need to keep in mind is that Web3Provider (which historically was used to wrap link-web3 providers) is now called BrowserProvider which is designed to wrap EIP-1193 providers, which is the standard that both modern Web3.js and injected providers offer.
The StaticJsonRpcProvider in v5 is now integrated into the v6 JsonRpcProvider directly. When connecting to a network which cannot change its network, it is much more efficient to disable the automatic safety check ethers performs.
Since the fees for Ethereum chains has become more complicated, all Fee parameters in v6 were coalesced into a single `.getFeeData` method. While `gasPrice` is no longer widely used in modern networks, when using a legacy network, it is available using that method.
The `lastBaseFeePerGas` field has been removed from the `FeeData` object in v6. This field was commonly used in v5 to calculate target gas prices by adding it to `maxPriorityFeePerGas`. In v6, this calculation is handled automatically.
The transaction helpers present in v5 were all wrapped into a Transaction class, which can handle any supported transaction format to be further processed
The Logger class has been replaced by several Error utility functions.
The checkProperties and shallowCopy have been removed in favor of using .map and Object.assign.
Pull requests are welcome, but please keep the following in mind:
- Backwards-compatibility-breaking changes will not be accepted; they may be considered for the next major version
- Security is important; adding dependencies require fairly convincing arguments as to why
- The library aims to be lean, so keep an eye on the dist/ethers.min.js file size before and after your changes (the build-clean target includes these stats)
- Keep the PR simple, readable and confined to the relevant files; see below for which files to change
- Add test cases for both expected and unexpected input
- Any new features need to be supported by me (future issues, documentation, testing, migration), so anything that is overly complicated or specific may not be accepted
- Everyone is working hard; be kind and respectful
It is always highly recommended that you open a Ethers Discussion before beginning a PR.
The documentation is an area which can always benefit from extra eyes, extra knowledge and extra examples.
Contributing to the documentation is welcome, but when making changes to documentation, please ensure that all changes are made only to:
- Updating /docs.wrm/**.wrm
- Adding links: /docs.wrm/links/*.txt
- Updating API jsdocs: /** ... */ comment blocks within /src.ts/
Generally changes to /docs.wrm/config.wrm should not be made, and if you feel it is necessary, please consider opening a Ethers Discussion first.
Similarly, when adding a new sections, a Ethers Discussion is preferred.
Currently, the documentation is built using an experimental v2 of the Flatworm documentation system, a system originally specifically made to maintain the Ethers documentation.
The new tsdocs branch has the ability to parse jsdocs from from TypeScript source files to create an API reference.
In general the only files you should ever include in a PR are:
- TypeScript source: /src.ts/**.ts
Do not include a package.json with the updated tarballHash or version, and do not include any generated files in your PR.
A bug fix must not modify anything requiring a minor version bump (see Adding Features), such as changing a method signature or altering the exports.
Contributing new features usually require a deeper understanding of the internal interactions with Ethers and its components, and generally requires a minor version bump.
When making any of the following changes, you must first open a Ethers Discussion as the minor version will need to be bumped.
- any signature change (such as adding a parameter, changing a parameter type, changing the return type)
- adding any new export; such as a class, function or constants
- adding any method to any class
- changing any exports property within the package.json
Changes of this sort should not be made without serious consideration and discussion.
The ethers library (including all dependencies) are available under the MIT License, which permits a wide variety of uses.
Copyright © Richard Moore.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.