Documentation

This documentation is for Ethers v5.

For Ethers v6, see the v6 documentation.

What is Ethers?

The ethers.js library aims to be a complete and compact library for interacting with the Ethereum Blockchain and its ecosystem. It was originally designed for use with ethers.io and has since expanded into a more general-purpose library.

Features

Developer Documentation

Getting Started
Ethereum Basics
Provider API Keys
Application Programming Interface
Command Line Interfaces
Cookbook
Migration Guide
Testing
Contributing and Hacking
Other Resources
Flatworm Docs
License and Copyright

Legacy Documentation

This section will be kept up to date, linking to documentation of older versions of the library.

Getting Started

Installing

Ethers' various Classes and Functions are available to import manually from sub-packages under the @ethersproject organization but for most projects, the umbrella package is the easiest way to get started.

/home/ricmoo> npm install --save ethers

Importing

Node.js

node.js require
const { ethers } = require("ethers");
ES6 or TypeScript
import { ethers } from "ethers";

Web Browser

It is generally better practice (for security reasons) to copy the ethers library to your own webserver and serve it yourself.

For quick demos or prototyping though, you can load it in your Web Applications from our CDN.

ES6 in the Browser
<script type="module"> import { ethers } from "https://cdn.ethers.io/lib/ethers-5.2.esm.min.js"; // Your code here... </script>
ES3 (UMD) in the Browser
<script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js" type="application/javascript"></script>

Common Terminology

This section needs work...

ProviderA Provider (in ethers) is a class which provides an abstraction for a connection to the Ethereum Network. It provides read-only access to the Blockchain and its status. 
SignerA Signer is a class which (usually) in some way directly or indirectly has access to a private key, which can sign messages and transactions to authorize the network to charge your account ether to perform operations. 
ContractA Contract is an abstraction which represents a connection to a specific contract on the Ethereum Network, so that applications can use it like a normal JavaScript object. 
Common Terms 

Connecting to Ethereum: MetaMask

The quickest and easiest way to experiment and begin developing on Ethereum is to use MetaMask, which is a browser extension that provides:

Connecting to MetaMask
// A Web3Provider wraps a standard Web3 provider, which is // what MetaMask injects as window.ethereum into each page const provider = new ethers.providers.Web3Provider(window.ethereum) // MetaMask requires requesting permission to connect users accounts await provider.send("eth_requestAccounts", []); // The MetaMask plugin also allows signing transactions to // send ether and pay to change state within the blockchain. // For this, you need the account signer... const signer = provider.getSigner()

Connecting to Ethereum: RPC

The JSON-RPC API is another popular method for interacting with Ethereum and is available in all major Ethereum node implementations (e.g. Geth and Parity) as well as many third-party web services (e.g. INFURA). It typically provides:

Connecting to an RPC client
// If you don't specify a //url//, Ethers connects to the default // (i.e. ``http:/\/localhost:8545``) const provider = new ethers.providers.JsonRpcProvider(); // The provider also allows signing transactions to // send ether and pay to change state within the blockchain. // For this, we need the account signer... const signer = provider.getSigner()

Querying the Blockchain

Once you have a Provider, you have a read-only connection to the blockchain, which you can use to query the current state, fetch historic logs, look up deployed code and so on.

Basic Queries
// Look up the current block number await provider.getBlockNumber() // 16987688 // Get the balance of an account (by address or ENS name, if supported by network) balance = await provider.getBalance("ethers.eth") // { BigNumber: "182334002436162568" } // Often you need to format the output to something more user-friendly, // such as in ether (instead of wei) ethers.utils.formatEther(balance) // '0.182334002436162568' // If a user enters a string in an input field, you may need // to convert it from ether (as a string) to wei (as a BigNumber) ethers.utils.parseEther("1.0") // { BigNumber: "1000000000000000000" }

Writing to the Blockchain

Sending Ether
// Send 1 ether to an ens name. const tx = signer.sendTransaction({ to: "ricmoo.firefly.eth", value: ethers.utils.parseEther("1.0") });

Contracts

A Contract is an abstraction of program code which lives on the Ethereum blockchain.

The Contract object makes it easier to use an on-chain Contract as a normal JavaScript object, with the methods mapped to encoding and decoding data for you.

If you are familiar with Databases, this is similar to an Object Relational Mapper (ORM).

In order to communicate with the Contract on-chain, this class needs to know what methods are available and how to encode and decode the data, which is what the Application Binary Interface (ABI) provides.

This class is a meta-class, which means its methods are constructed at runtime, and when you pass in the ABI to the constructor it uses it to determine which methods to add.

While an on-chain Contract may have many methods available, you can safely ignore any methods you don't need or use, providing a smaller subset of the ABI to the contract.

An ABI often comes from the Solidity or Vyper compiler, but you can use the Human-Readable ABI in code, which the following examples use.

Connecting to the DAI Contract
// You can also use an ENS name for the contract address const daiAddress = "dai.tokens.ethers.eth"; // The ERC-20 Contract ABI, which is a common contract interface // for tokens (this is the Human-Readable ABI format) const daiAbi = [ // Some details about the token "function name() view returns (string)", "function symbol() view returns (string)", // Get the account balance "function balanceOf(address) view returns (uint)", // Send some of your tokens to someone else "function transfer(address to, uint amount)", // An event triggered whenever anyone transfers to someone else "event Transfer(address indexed from, address indexed to, uint amount)" ]; // The Contract object const daiContract = new ethers.Contract(daiAddress, daiAbi, provider);

Read-Only Methods

Querying the DAI Contract
// Get the ERC-20 token name await daiContract.name() // 'Dai Stablecoin' // Get the ERC-20 token symbol (for tickers and UIs) await daiContract.symbol() // 'DAI' // Get the balance of an address balance = await daiContract.balanceOf("ricmoo.firefly.eth") // { BigNumber: "19862540059122458201631" } // Format the DAI for displaying to the user ethers.utils.formatUnits(balance, 18) // '19862.540059122458201631'

State Changing Methods

Sending DAI
// The DAI Contract is currently connected to the Provider, // which is read-only. You need to connect to a Signer, so // that you can pay to send state-changing transactions. const daiWithSigner = contract.connect(signer); // Each DAI has 18 decimal places const dai = ethers.utils.parseUnits("1.0", 18); // Send 1 DAI to "ricmoo.firefly.eth" tx = daiWithSigner.transfer("ricmoo.firefly.eth", dai);

Listening to Events

Listening to Events
// Receive an event when ANY transfer occurs daiContract.on("Transfer", (from, to, amount, event) => { console.log(`${ from } sent ${ formatEther(amount) } to ${ to}`); // The event object contains the verbatim log data, the // EventFragment and functions to fetch the block, // transaction and receipt and event functions }); // A filter for when a specific address receives tokens myAddress = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"; filter = daiContract.filters.Transfer(null, myAddress) // { // address: 'dai.tokens.ethers.eth', // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // null, // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72' // ] // } // Receive an event when that filter occurs daiContract.on(filter, (from, to, amount, event) => { // The to will always be "address" console.log(`I got ${ formatEther(amount) } from ${ from }.`); });

Query Historic Events

Filtering Historic Events
// Get the address of the Signer myAddress = await signer.getAddress() // '0x8ba1f109551bD432803012645Ac136ddd64DBA72' // Filter for all token transfers from me filterFrom = daiContract.filters.Transfer(myAddress, null); // { // address: 'dai.tokens.ethers.eth', // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72' // ] // } // Filter for all token transfers to me filterTo = daiContract.filters.Transfer(null, myAddress); // { // address: 'dai.tokens.ethers.eth', // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // null, // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72' // ] // } // List all transfers sent from me in a specific block range await daiContract.queryFilter(filterFrom, 9843470, 9843480) // [ // { // address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // args: [ // '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // '0x8B3765eDA5207fB21690874B722ae276B96260E0', // { BigNumber: "4750000000000000000" }, // amount: { BigNumber: "4750000000000000000" }, // from: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // to: '0x8B3765eDA5207fB21690874B722ae276B96260E0' // ], // blockHash: '0x8462eb2fbcef5aa4861266f59ad5f47b9aa6525d767d713920fdbdfb6b0c0b78', // blockNumber: 9843476, // data: '0x00000000000000000000000000000000000000000000000041eb63d55b1b0000', // decode: [Function (anonymous)], // event: 'Transfer', // eventSignature: 'Transfer(address,address,uint256)', // getBlock: [Function (anonymous)], // getTransaction: [Function (anonymous)], // getTransactionReceipt: [Function (anonymous)], // logIndex: 69, // removeListener: [Function (anonymous)], // removed: false, // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72', // '0x0000000000000000000000008b3765eda5207fb21690874b722ae276b96260e0' // ], // transactionHash: '0x1be23554545030e1ce47391a41098a46ff426382ed740db62d63d7676ff6fcf1', // transactionIndex: 81 // }, // { // address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // args: [ // '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // '0x00De4B13153673BCAE2616b67bf822500d325Fc3', // { BigNumber: "250000000000000000" }, // amount: { BigNumber: "250000000000000000" }, // from: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // to: '0x00De4B13153673BCAE2616b67bf822500d325Fc3' // ], // blockHash: '0x8462eb2fbcef5aa4861266f59ad5f47b9aa6525d767d713920fdbdfb6b0c0b78', // blockNumber: 9843476, // data: '0x00000000000000000000000000000000000000000000000003782dace9d90000', // decode: [Function (anonymous)], // event: 'Transfer', // eventSignature: 'Transfer(address,address,uint256)', // getBlock: [Function (anonymous)], // getTransaction: [Function (anonymous)], // getTransactionReceipt: [Function (anonymous)], // logIndex: 70, // removeListener: [Function (anonymous)], // removed: false, // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72', // '0x00000000000000000000000000de4b13153673bcae2616b67bf822500d325fc3' // ], // transactionHash: '0x1be23554545030e1ce47391a41098a46ff426382ed740db62d63d7676ff6fcf1', // transactionIndex: 81 // } // ] // // The following have had the results omitted due to the // number of entries; but they provide some useful examples // // List all transfers sent in the last 10,000 blocks await daiContract.queryFilter(filterFrom, -10000) // List all transfers ever sent to me await daiContract.queryFilter(filterTo)

Signing Messages

Signing Messages
// To sign a simple string, which are used for // logging into a service, such as CryptoKitties, // pass the string in. signature = await signer.signMessage("Hello World"); // '0x550a28a0fab4e30de31ed651851bb2908ff4dd1b7c6a5cdcf62a8e2accbec1d53e27a6081538759a971d0c71d35ab571eda1e3a565da9948ac83361aa28566e21c' // // A common case is also signing a hash, which is 32 // bytes. It is important to note, that to sign binary // data it MUST be an Array (or TypedArray) // // This string is 66 characters long message = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" // This array representation is 32 bytes long messageBytes = ethers.utils.arrayify(message); // Uint8Array [ 221, 242, 82, 173, 27, 226, 200, 155, 105, 194, 176, 104, 252, 55, 141, 170, 149, 43, 167, 241, 99, 196, 161, 22, 40, 245, 90, 77, 245, 35, 179, 239 ] // To sign a hash, you most often want to sign the bytes signature = await signer.signMessage(messageBytes) // '0x471250f1080eb2686c3cdc94491eb52e56e45a69225f3ca82b72e5c2ad7195ff3146ce8ec2445d8593dface9526a180e9df35ac043135f40fe8cdd64278bdd591c'

Ethereum Basics

This is a brief overview of some aspects of Ethereum and blockchains which developers can make use of or should be aware of.

This section is sparse at the moment, but will be expanded as time goes on.

Events
Gas
Security
Best Practices

Events

Logs and Filtering

Logs and filtering are used quite often in blockchain applications, since they allow for efficient queries of indexed data and provide lower-cost data storage when the data is not required to be accessed on-chain.

These can be used in conjunction with the Provider Events API and with the Contract Events API.

The Contract Events API also provides higher-level methods to compute and query this data, which should be preferred over the lower-level filter.

Filters

When a Contract creates a log, it can include up to 4 pieces of data to be indexed by. The indexed data is hashed and included in a Bloom Filter, which is a data structure that allows for efficient filtering.

So, a filter may correspondingly have up to 4 topic-sets, where each topic-set refers to a condition that must match the indexed log topic in that position (i.e. each condition is AND-ed together).

If a topic-set is null, a log topic in that position is not filtered at all and any value matches.

If a topic-set is a single topic, a log topic in that position must match that topic.

If a topic-set is an array of topics, a log topic in that position must match any one of the topics (i.e. the topic in this position are OR-ed).

This may sound complicated at first, but is more easily understood with some examples.

Topic-SetsMatching Logs 
[ A ]topic[0] = A 
[ A, null ] 
[ null, B ]topic[1] = B 
[ null, [ B ] ] 
[ null, [ B ], null ] 
[ A, B ](topic[0] = A) AND (topic[1] = B) 
[ A, [ B ] ] 
[ A, [ B ], null ] 
[ [ A, B ] ](topic[0] = A) OR (topic[0] = B) 
[ [ A, B ], null ] 
[ [ A, B ], [ C, D ] ][ (topic[0] = A) OR (topic[0] = B) ] AND [ (topic[1] = C) OR (topic[1] = D) ] 
Example Log Matching 
ERC-20 Transfer Filter Examples
// Short example of manually creating filters for an ERC-20 // Transfer event. // // Most users should generally use the Contract API to // compute filters, as it is much simpler, but this is // provided as an illustration for those curious. See // below for examples of the equivalent Contract API. // ERC-20: // Transfer(address indexed src, address indexed dst, uint val) // // -------------------^ // ----------------------------------------^ // // Notice that only *src* and *dst* are *indexed*, so ONLY they // qualify for filtering. // // Also, note that in Solidity an Event uses the first topic to // identify the Event name; for Transfer this will be: // id("Transfer(address,address,uint256)") // // Other Notes: // - A topic must be 32 bytes; so shorter types must be padded // List all token transfers *from* myAddress filter = { address: tokenAddress, topics: [ utils.id("Transfer(address,address,uint256)"), hexZeroPad(myAddress, 32) ] }; // List all token transfers *to* myAddress: filter = { address: tokenAddress, topics: [ utils.id("Transfer(address,address,uint256)"), null, hexZeroPad(myAddress, 32) ] }; // List all token transfers *to* myAddress or myOtherAddress: filter = { address: tokenAddress, topics: [ utils.id("Transfer(address,address,uint256)"), null, [ hexZeroPad(myAddress, 32), hexZeroPad(myOtherAddress, 32), ] ] };

To simplify life, ..., explain here, the contract API

ERC-20 Contract Filter Examples
abi = [ "event Transfer(address indexed src, address indexed dst, uint val)" ]; contract = new Contract(tokenAddress, abi, provider); // List all token transfers *from* myAddress contract.filters.Transfer(myAddress) // { // address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72' // ] // } // List all token transfers *to* myAddress: contract.filters.Transfer(null, myAddress) // { // address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // null, // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72' // ] // } // List all token transfers *from* myAddress *to* otherAddress: contract.filters.Transfer(myAddress, otherAddress) // { // address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72', // '0x000000000000000000000000ea517d5a070e6705cc5467858681ed953d285eb9' // ] // } // List all token transfers *to* myAddress OR otherAddress: contract.filters.Transfer(null, [ myAddress, otherAddress ]) // { // address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // null, // [ // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72', // '0x000000000000000000000000ea517d5a070e6705cc5467858681ed953d285eb9' // ] // ] // }

Solidity Topics

This is a quick (and non-comprehensive) overview of how events are computed in Solidity.

This is likely out of the scope for most developers, but may be interesting to those who want to learn a bit more about the underlying technology.

Solidity provides two types of events, anonymous and non-anonymous. The default is non-anonymous, and most developers will not need to worry about anonymous events.

For non-anonymous events, up to 3 topics may be indexed (instead of 4), since the first topic is reserved to specify the event signature. This allows non-anonymous events to always be filtered by their event signature.

This topic hash is always in the first slot of the indexed data, and is computed by normalizing the Event signature and taking the keccak256 hash of it.

For anonymous events, up to 4 topics may be indexed, and there is no signature topic hash, so the events cannot be filtered by the event signature.

Each additional indexed property is processed depending on whether its length is fixed or dynamic.

For fixed length types (e.g. uint, bytes5), all of which are internally exactly 32 bytes (shorter types are padded with zeros; numeric values are padded on the left, data values padded on the right), these are included directly by their actual value, 32 bytes of data.

For dynamic types (e.g. string, uint256[]) , the value is hashed using keccak256 and this hash is used.

Because dynamic types are hashed, there are important consequences in parsing events that should be kept in mind. Mainly that the original value is lost in the event. So, it is possible to tell is a topic is equal to a given string, but if they do not match, there is no way to determine what the value was.

If a developer requires that a string value is required to be both able to be filtered and also able to be read, the value must be included in the signature twice, once indexed and once non-indexed (e.g. someEvent(string indexed searchBy, string clearText)).

For a more detailed description, please refer to the Solidity Event Documentation.

Other Things? TODO

Explain what happens to strings and bytes, how to filter and retain the value

Gas

Explain attack vectors

Gas Price

The gas price is used somewhat like a bid, indicating an amount you are willing to pay (per unit of execution) to have your transaction processed.

Gas Limit

Security

While security should be a concern for all developers, in the blockchain space developers must be additionally conscious of many areas which can be exploited.

Once a problem has an economic incentives to exploit it, there is a much larger risk and with blockchain apps it can become quite valuable to attack.

In addition to many of the other security issues app developers may have to worry about, there are a few additional vectors that JavaScript developers should be aware of.

Side-Channel Attacks

A Side-Channel Attack occurs when something orthogonal to the implementation of the algorithm used can be exploited to learn more about secure or private information.

Released Data (Strings, Uint8Arrays, Buffers)

In JavaScript, memory may not be securely allocated, or more importantly securely released.

Historically, new Buffer(16) would re-use old memory that had been released. This would mean that code running later, may have access to data that was discarded.

As an example of the dangers, imagine if you had used a Buffer to store a private key, signed data and then returned from the function, allowing the Buffer to be de-allocated. A future function may be able to request a new Buffer, which would still have that left-over private key, which it could then use to steal the funds from that account.

There are also many debugging tools and systems designed to assist developers inspect the memory contents of JavaScript programs. In these cases, any private key or mnemonic sitting in memory may be visible to other users on the system, or malicious scripts.

Timing Attack

Timing attacks allow a malicious user or script to determine private data through analysing how long an operation requires to execute.

In JavaScript, Garbage Collection occurs periodically when the system determines it is required. Each JavaScript implementation is different, with a variety of strategies and and abilities.

Most Garbage Collection requires "stopping the world", or pausing all code being executed while it runs. This adds a large delay to any code that was currently running.

This can be exploited by attackers to "condition cause a delay". They will set up a scenario where the system is on the edge of needing to garbage collect, and call your code with two paths, a simple path and complex path. The simple path won't stir things up enough to cause a garbage collection, while the complex one will. By timing how long the code took to execute, they now know whether garbage collection occured and therefore whether the simple or complex path was taken.

Advanced timing attacks are very difficult to mitigate in any garbage-collection-based language. Most libraries where this matters will hopefully mitigate this for you as much as possible, but it is still good to be aware of.

General Concerns

Key Derivation Functions

This is not specific to Ethereum, but is a useful technique to understand and has some implications on User Experience.

Many people are concerned that encrypting and decrypting an Ethereum wallet is quite slow and can take quite some time. It is important to understand this is intentional and provides much stronger security.

The algorithm usually used for this process is scrypt, which is a memory and CPU intensive algorithm which computes a key (fixed-length pseudo-random series of bytes) for a given password.

Why does it take so long?

The goal is to use as much CPU and memory as possible during this algorithm, so that a single computer can only compute a very small number of results for some fixed amount of time. To scale up an attack, the attacker requires additional computers, increasing the cost to brute-force attack to guess the password.

For example, if a user knows their correct password, this process may take 10 seconds for them to unlock their own wallet and proceed.

But since an attacker does not know the password, they must guess; and each guess also requires 10 seconds. So, if they wish to try guessing 1 million passwords, their computer would be completely tied up for 10 million seconds, or around 115 days.

Without using an algorithm like this, a user would be able to log in instantly, however, 1 million passwords would only take a few seconds to attempt. Even secure passwords would likely be broken within a short period of time. There is no way the algorithm can be faster for a legitimate user without also being faster for an attacker.

Mitigating the User Experience

Rather than reducing the security (see below), a better practice is to make the user feel better about waiting. The Ethers encryption and decryption API allows the developer to incorporate a progress bar, by passing in a progress callback which will be periodically called with a number between 0 and 1 indication percent completion.

In general a progress bar makes the experience feel faster, as well as more comfortable since there is a clear indication how much (relative) time is remaining. Additionally, using language like "decrypting..." in a progress bar makes a user feel like their time is not being needlessly wasted.

Work-Arounds (not recommended)

There are ways to reduce the time required to decrypt an Ethereum JSON Wallet, but please keep in mind that doing so discards nearly all security on that wallet.

The scrypt algorithm is designed to be tuned. The main purpose of this is to increase the difficulty as time goes on and computers get faster, but it can also be tuned down in situations where the security is less important.

// Our wallet object const wallet = Wallet.createRandom(); // The password to encrypt with const password = "password123"; // WARNING: Doing this substantially reduces the security // of the wallet. This is highly NOT recommended. // We override the default scrypt.N value, which is used // to indicate the difficulty to crack this wallet. const json = wallet.encrypt(password, { scrypt: { // The number must be a power of 2 (default: 131072) N: 64 } });

Best Practices

Network Changes

Handling a change in the network (e.g. Görli vs Mainnet) is incredibly complex and a slight failure can at best make your application seem confusing and at worst cause the loss of funds, leak private data or misrepresent what an action performed.

Luckily, standard users should likely never change their networks unless tricked to do so or they make a mistake.

This is a problem you mainly need to worry about for developers, and most developers should understand the vast array of issues surrounding a network change during application operation and will understand the page reloading (which is already the default behaviour in many clients).

So, the best practice when a network change occurs is to simply refresh the page. This should cause all your UI components to reset to a known-safe state, including any banners and warnings to your users if they are on an unsupported network.

This can be accomplished by using the following function:

Automatically Refresh on Network Change
// Force page refreshes on network changes { // The "any" network will allow spontaneous network changes const provider = new ethers.providers.Web3Provider(window.ethereum, "any"); provider.on("network", (newNetwork, oldNetwork) => { // When a Provider makes its initial connection, it emits a "network" // event with a null oldNetwork along with the newNetwork. So, if the // oldNetwork exists, it represents a changing network if (oldNetwork) { window.location.reload(); } }); }

Provider API Keys

( TL; DR – sign up for your own API keys with the links below to improve your application performance )

When using a Provider backed by an API service (such as Alchemy, Etherscan or INFURA), the service requires an API key, which allows each service to track individual projects and their usage and permissions.

The ethers library offers default API keys for each service, so that each Provider works out-of-the-box.

These API keys are provided as a community resource by the backend services for low-traffic projects and for early prototyping.

Since these API keys are shared by all users (that have not acquired their own API key), they are aggressively throttled which means retries occur more frequently and the responses are slower.

It is highly recommended that you sign up for a free API key from each service for their free tier, which (depending on the service) includes many advantages:

Etherscan(see the EtherscanProvider)

Etherscan is an Ethereum block explorer, which is possibly the most useful developer tool for building and debugging Ethereum applications.

They offer an extensive collection of API endpoints which provide all the operations required to interact with the Ethereum Blockchain.

Sign up for a free API key on Etherscan

Benefits:

Networks:

homestead, goerli, sepolia, matic. maticmum, arbitrum, arbitrum-goerli, optimism and optimism-goerli.

INFURA(see the InfuraProvider)

The INFURA service has been around for quite some time and is very robust and reliable and highly recommended.

They offer a standard JSON-RPC interface and a WebSocket interface, which makes interaction with standard tools versatile, simple and straightforward.

Sign up for a free Project ID on INFURA

Benefits:

Networks:

homestead, goerli, sepolia, matic. maticmum, arbitrum, arbitrum-goerli, optimism and optimism-goerli.

Alchemy(see the AlchemyProvider)

The Alchemy service has been around a few years and is also very robust and reliable.

They offer a standard JSON-RPC interface and a WebSocket interface, as well as a collection of advanced APIs for interacting with tokens and to assist with debugging.

Sign up for a free API key on Alchemy

Benefits:

Networks:

homestead, goerli, matic. maticmum, arbitrum, arbitrum-goerli, optimism and optimism-goerli.

Pocket Gateway(see the PocketProvider)

They offer a standard JSON-RPC interface using either a load-balanced network or non-load-balanced fleet.

Sign up for a free API key on Pocket

Benefits:

Networks:

homestead

Ankr(see the AnkrProvider)

They offer a standard JSON-RPC interface and have fairly high capacity without the need for an API key early on in the development cycle.

See their free tier features on Ankr

Benefits:

Networks:

homestead, matic and arbitrum

Creating a Default Provider

The default provider connects to multiple backends and verifies their results internally, making it simple to have a high level of trust in third-party services.

A second optional parameter allows API keys to be specified to each Provider created internally and any API key omitted will fallback onto using the default API key for that service.

It is highly recommended that you provide an API for each service, to maximize your applications performance.

If the API key "-" is used, the corresponding Provider will be omitted.

Passing API Keys into getDefaultProvider
// Use the mainnet const network = "homestead"; // Specify your own API keys // Each is optional, and if you omit it the default // API key for that service will be used. const provider = ethers.getDefaultProvider(network, { etherscan: YOUR_ETHERSCAN_API_KEY, infura: YOUR_INFURA_PROJECT_ID, // Or if using a project secret: // infura: { // projectId: YOUR_INFURA_PROJECT_ID, // projectSecret: YOUR_INFURA_PROJECT_SECRET, // }, alchemy: YOUR_ALCHEMY_API_KEY, pocket: YOUR_POCKET_APPLICATION_KEY // Or if using an application secret key: // pocket: { // applicationId: , // applicationSecretKey: // }, ankr: YOUR_ANKR_API_KEY });

Application Programming Interface

An Application Programming Interface (API) is the formal specification of the library.

Providers
Signers
Contract Interaction
Utilities
Other Libraries
Experimental

Providers

A Provider is an abstraction of a connection to the Ethereum network, providing a concise, consistent interface to standard Ethereum node functionality.

The ethers.js library provides several options which should cover the vast majority of use-cases, but also includes the necessary functions and classes for sub-classing if a more custom configuration is necessary.

Most users should use the Default Provider.

Default Provider

The default provider is the safest, easiest way to begin developing on Ethereum, and it is also robust enough for use in production.

It creates a FallbackProvider connected to as many backend services as possible. When a request is made, it is sent to multiple backends simultaneously. As responses from each backend are returned, they are checked that they agree. Once a quorum has been reached (i.e. enough of the backends agree), the response is provided to your application.

This ensures that if a backend has become out-of-sync, or if it has been compromised that its responses are dropped in favor of responses that match the majority.

ethers.getDefaultProvider( [ network , [ options ] ] ) Provider

Returns a new Provider, backed by multiple services, connected to network. If no network is provided, homestead (i.e. mainnet) is used.

The network may also be a URL to connect to, such as http://localhost:8545 or wss://example.com.

The options is an object, with the following properties:

PropertyDescription 
alchemyAlchemy API Token 
etherscanEtherscan API Token 
infuraINFURA Project ID or { projectId, projectSecret } 
pocketPocket Network Application ID or { applicationId, applicationSecretKey } 
quorumThe number of backends that must agree (default: 2 for mainnet, 1 for testnets) 
Option Properties 
Note: API Keys

It is highly recommended for production services to acquire and specify an API Key for each service.

The default API Keys used by ethers are shared across all users, so services may throttle all services that are using the default API Keys during periods of load without realizing it.

Many services also have monitoring and usage metrics, which are only available if an API Key is specified. This allows tracking how many requests are being sent and which methods are being used the most.

Some services also provide additional paid features, which are only available when specifying an API Key.

Networks

There are several official common Ethereum networks as well as custom networks and other compatible projects.

Any API that accept a Networkish can be passed a common name (such as "mainnet" or "goerli") or chain ID to use that network definition or may specify custom parameters.

ethers.providers.getNetwork( aNetworkish ) Network

Returns the full Network for the given standard aNetworkish Networkish.

This is useful for functions and classes which wish to accept Networkish as an input parameter.

// By Chain Name getNetwork("homestead"); // { // chainId: 1, // ensAddress: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', // name: 'homestead' // } // By Chain ID getNetwork(1); // { // chainId: 1, // ensAddress: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', // name: 'homestead' // }

Custom ENS Contract

One common reason to specify custom properties for a Network is to override the address of the root ENS registry, either on a common network to intercept the ENS Methods or to specify the ENS registry on a dev network (on most dev networks you must deploy the ENS contracts manually).

Example: Override the ENS registry
const network = { name: "dev", chainId: 1337, ensAddress: customEnsAddress };

Provider Documentation

Provider
JsonRpcProvider
API Providers
Other Providers
Types

Provider

A Provider in ethers is a read-only abstraction to access the blockchain data.

Coming from Web3.js?

If you are coming from Web3.js, this is one of the biggest differences you will encounter using ethers.

The ethers library creates a strong division between the operation a Provider can perform and those of a Signer, which Web3.js lumps together.

This separation of concerns and a stricted subset of Provider operations allows for a larger variety of backends, a more consistent API and ensures other libraries to operate without being able to rely on any underlying assumption.

Accounts Methods

provider.getBalance( address [ , blockTag = latest ] ) Promise< BigNumber >

Returns the balance of address as of the blockTag block height.

await provider.getBalance("ricmoo.eth"); // { BigNumber: "37426320346873870455" }
provider.getCode( address [ , blockTag = latest ] ) Promise< string< DataHexString > >

Returns the contract code of address as of the blockTag block height. If there is no contract currently deployed, the result is 0x.

await provider.getCode("registrar.firefly.eth"); // '0x606060405236156100885763ffffffff60e060020a60003504166369fe0e2d81146100fa578063704b6c021461010f57806379502c551461012d578063bed866f614610179578063c37067fa1461019e578063c66485b2146101ab578063d80528ae146101c9578063ddca3f43146101f7578063f2c298be14610219578063f3fef3a314610269575b6100f85b6000808052600760209081527f6d5257204ebe7d88fd91ae87941cb2dd9d8062b64ae5a2bd2d28ec40b9fbf6df80543490810190915560408051918252517fdb7750418f9fa390aaf85d881770065aa4adbe46343bcff4ae573754c829d9af929181900390910190a25b565b005b341561010257fe5b6100f860043561028a565b005b341561011757fe5b6100f8600160a060020a03600435166102ec565b005b341561013557fe5b61013d610558565b60408051600160a060020a0396871681526020810195909552928516848401526060840191909152909216608082015290519081900360a00190f35b341561018157fe5b61018c600435610580565b60408051918252519081900360200190f35b6100f8600435610595565b005b34156101b357fe5b6100f8600160a060020a03600435166105e6565b005b34156101d157fe5b6101d9610676565b60408051938452602084019290925282820152519081900360600190f35b34156101ff57fe5b61018c61068d565b60408051918252519081900360200190f35b6100f8600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284375094965061069495505050505050565b005b341561027157fe5b6100f8600160a060020a0360043516602435610ab2565b005b60025433600160a060020a039081169116146102a65760006000fd5b600454604080519182526020820183905280517f854231545a00e13c316c82155f2b8610d638e9ff6ebc4930676f84a5af08a49a9281900390910190a160048190555b50565b60025433600160a060020a039081169116146103085760006000fd5b60025460408051600160a060020a039283168152918316602083015280517fbadc9a52979e89f78b7c58309537410c5e51d0f63a0a455efe8d61d2b474e6989281900390910190a16002805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a038381169190911790915560008054604080516020908101849052815160e060020a6302571be30281527f91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e26004820152915192909416936302571be39360248084019492938390030190829087803b15156103e957fe5b60325a03f115156103f657fe5b50505060405180519050600160a060020a0316631e83409a826000604051602001526040518263ffffffff1660e060020a0281526004018082600160a060020a0316600160a060020a03168152602001915050602060405180830381600087803b151561045f57fe5b60325a03f1151561046c57fe5b50506040805160008054600354602093840183905284517f0178b8bf00000000000000000000000000000000000000000000000000000000815260048101919091529351600160a060020a039091169450630178b8bf9360248082019493918390030190829087803b15156104dd57fe5b60325a03f115156104ea57fe5b505060408051805160035460025460e860020a62d5fa2b0284526004840191909152600160a060020a03908116602484015292519216925063d5fa2b0091604480830192600092919082900301818387803b151561054457fe5b60325a03f1151561055157fe5b5050505b50565b600054600354600254600454600154600160a060020a039485169492831692165b9091929394565b6000818152600760205260409020545b919050565b6000818152600760209081526040918290208054349081019091558251908152915183927fdb7750418f9fa390aaf85d881770065aa4adbe46343bcff4ae573754c829d9af92908290030190a25b50565b60025433600160a060020a039081169116146106025760006000fd5b60015460408051600160a060020a039283168152918316602083015280517f279875333405c968e401e3bc4e71d5f8e48728c90f4e8180ce28f74efb5669209281900390910190a16001805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0383161790555b50565b600654600554600160a060020a033016315b909192565b6004545b90565b80516001820190600080808060048510806106af5750601485115b156106ba5760006000fd5b600093505b8484101561072a57855160ff16925060618310806106e05750607a8360ff16115b80156106fc575060308360ff1610806106fc575060398360ff16115b5b801561070d57508260ff16602d14155b156107185760006000fd5b6001909501945b6001909301926106bf565b60045434101561073a5760006000fd5b866040518082805190602001908083835b6020831061076a5780518252601f19909201916020918201910161074b565b51815160209384036101000a60001901801990921691161790526040805192909401829003822060035483528282018190528451928390038501832060008054948401819052865160e060020a6302571be3028152600481018390529651929a509098509650600160a060020a0390921694506302571be393602480820194509192919082900301818787803b15156107ff57fe5b60325a03f1151561080c57fe5b505060405151600160a060020a031691909114905061082b5760006000fd5b60008054600354604080517f06ab5923000000000000000000000000000000000000000000000000000000008152600481019290925260248201869052600160a060020a03308116604484015290519216926306ab59239260648084019382900301818387803b151561089a57fe5b60325a03f115156108a757fe5b505060008054600154604080517f1896f70a00000000000000000000000000000000000000000000000000000000815260048101879052600160a060020a0392831660248201529051919092169350631896f70a9260448084019391929182900301818387803b151561091657fe5b60325a03f1151561092357fe5b50506001546040805160e860020a62d5fa2b02815260048101859052600160a060020a033381166024830152915191909216925063d5fa2b009160448082019260009290919082900301818387803b151561097a57fe5b60325a03f1151561098757fe5b505060008054604080517f5b0fc9c300000000000000000000000000000000000000000000000000000000815260048101869052600160a060020a0333811660248301529151919092169350635b0fc9c39260448084019391929182900301818387803b15156109f357fe5b60325a03f11515610a0057fe5b505060058054349081019091556006805460010190556000838152600760209081526040918290208054840190558151600160a060020a03331681529081019290925280518493507f179ef3319e6587f6efd3157b34c8b357141528074bcb03f9903589876168fa149281900390910190a260408051348152905182917fdb7750418f9fa390aaf85d881770065aa4adbe46343bcff4ae573754c829d9af919081900360200190a25b50505050505050565b60025433600160a060020a03908116911614610ace5760006000fd5b604051600160a060020a0383169082156108fc029083906000818181858888f193505050501515610aff5760006000fd5b60408051600160a060020a03841681526020810183905281517fac375770417e1cb46c89436efcf586a74d0298fee9838f66a38d40c65959ffda929181900390910190a15b50505600a165627a7a723058205c3628c01dc80233f51979d91a76cec2a25d84e86c9838d34672734ca2232b640029'
provider.getStorageAt( addr , pos [ , blockTag = latest ] ) Promise< string< DataHexString > >

Returns the Bytes32 value of the position pos at address addr, as of the blockTag.

await provider.getStorageAt("registrar.firefly.eth", 0) // '0x000000000000000000000000314159265dd8dbb310642f98f50c066173c1259b'
provider.getTransactionCount( address [ , blockTag = latest ] ) Promise< number >

Returns the number of transactions address has ever sent, as of blockTag. This value is required to be the nonce for the next transaction from address sent to the network.

await provider.getTransactionCount("ricmoo.eth"); // 47

Blocks Methods

provider.getBlock( block ) Promise< Block >

Get the block from the network, where the result.transactions is a list of transaction hashes.

await provider.getBlock(100004) // { // _difficulty: { BigNumber: "3849295379889" }, // difficulty: 3849295379889, // extraData: '0x476574682f76312e302e312d39383130306634372f6c696e75782f676f312e34', // gasLimit: { BigNumber: "3141592" }, // gasUsed: { BigNumber: "21000" }, // hash: '0xf93283571ae16dcecbe1816adc126954a739350cd1523a1559eabeae155fbb63', // miner: '0x909755D480A27911cB7EeeB5edB918fae50883c0', // nonce: '0x1a455280001cc3f8', // number: 100004, // parentHash: '0x73d88d376f6b4d232d70dc950d9515fad3b5aa241937e362fdbfd74d1c901781', // timestamp: 1439799168, // transactions: [ // '0x6f12399cc2cb42bed5b267899b08a847552e8c42a64f5eb128c1bcbd1974fb0c' // ] // }
provider.getBlockWithTransactions( block ) Promise< BlockWithTransactions >

Get the block from the network, where the result.transactions is an Array of TransactionResponse objects.

await provider.getBlockWithTransactions(100004) // { // _difficulty: { BigNumber: "3849295379889" }, // difficulty: 3849295379889, // extraData: '0x476574682f76312e302e312d39383130306634372f6c696e75782f676f312e34', // gasLimit: { BigNumber: "3141592" }, // gasUsed: { BigNumber: "21000" }, // hash: '0xf93283571ae16dcecbe1816adc126954a739350cd1523a1559eabeae155fbb63', // miner: '0x909755D480A27911cB7EeeB5edB918fae50883c0', // nonce: '0x1a455280001cc3f8', // number: 100004, // parentHash: '0x73d88d376f6b4d232d70dc950d9515fad3b5aa241937e362fdbfd74d1c901781', // timestamp: 1439799168, // transactions: [ // { // accessList: null, // blockHash: '0xf93283571ae16dcecbe1816adc126954a739350cd1523a1559eabeae155fbb63', // blockNumber: 100004, // chainId: 0, // confirmations: 16887683, // creates: null, // data: '0x', // from: '0xcf00A85f3826941e7A25BFcF9Aac575d40410852', // gasLimit: { BigNumber: "90000" }, // gasPrice: { BigNumber: "54588778004" }, // hash: '0x6f12399cc2cb42bed5b267899b08a847552e8c42a64f5eb128c1bcbd1974fb0c', // nonce: 25, // r: '0xb23adc880d3735e4389698dddc953fb02f1fa9b57e84d3510a2a4b3597ac2486', // s: '0x4e856f95c4e2828933246fb4765a5bfd2ca5959840643bef0e80b4e3a243d064', // to: '0xD9666150A9dA92d9108198a4072970805a8B3428', // transactionIndex: 0, // type: 0, // v: 27, // value: { BigNumber: "5000000000000000000" }, // wait: [Function (anonymous)] // } // ] // }

Ethereum Naming Service (ENS) Methods

The Ethereum Naming Service (ENS) allows a short and easy-to-remember ENS Name to be attached to any set of keys and values.

One of the most common uses for this is to use a simple name to refer to an Ethereum Address.

In the ethers API, nearly anywhere that accepts an address, an ENS name may be used instead, which can simplify code and make reading and debugging much simpler.

The provider offers some basic operations to help resolve and work with ENS names.

provider.getAvatar( name ) Promise< string >

Returns the URL for the avatar associated to the ENS name, or null if no avatar was configured.

provider.getResolver( name ) Promise< EnsResolver >

Returns an EnsResolver instance which can be used to further inquire about specific entries for an ENS name.

// See below (Resolver) for examples of using this object const resolver = await provider.getResolver("ricmoo.eth");
provider.lookupAddress( address ) Promise< string >

Performs a reverse lookup of the address in ENS using the Reverse Registrar. If the name does not exist, or the forward lookup does not match, null is returned.

An ENS name requries additional configuration to setup a reverse record, they are not automatically set up.

await provider.lookupAddress("0x5555763613a12D8F3e73be831DFf8598089d3dCa"); // 'ricmoo.eth'
provider.resolveName( name ) Promise< string< Address > >

Looks up the address of name. If the name is not owned, or does not have a Resolver configured, or the Resolver does not have an address configured, null is returned.

await provider.resolveName("ricmoo.eth"); // '0x5555763613a12D8F3e73be831DFf8598089d3dCa'

EnsResolver

resolver.name string

The name of this resolver.

resolver.address string< Address >

The address of the Resolver.

resolver.getAddress( [ cointType = 60 ] ) Promise< string >

Returns a Promise which resolves to the EIP-2304 multicoin address stored for the coinType. By default an Ethereum Address (coinType = 60) will be returned.

// By default, looks up the Ethereum address // (this will match provider.resolveName) await resolver.getAddress(); // '0x5555763613a12D8F3e73be831DFf8598089d3dCa' // Specify the coinType for other coin addresses (0 = Bitcoin) await resolver.getAddress(0); // '1RicMooMWxqKczuRCa5D2dnJaUEn9ZJyn'
resolver.getAvatar( ) Promise< AvatarInfo >

Returns an object the provides the URL of the avatar and the linkage representing each stage in the avatar resolution.

If there is no avatar found (or the owner of any NFT does not match the name owner), null is returned.

The AvatarInfo has the properties:

  • info.linkage - An array of info on each step resolving the avatar
  • info.url - The URL of the avatar

resolver.getContentHash( ) Promise< string >

Returns a Promise which resolves to any stored EIP-1577 content hash.

await resolver.getContentHash(); // 'ipfs://QmdTPkMMBWQvL8t7yXogo7jq5pAcWg8J7RkLrDsWZHT82y'
resolver.getText( key ) Promise< string >

Returns a Promise which resolves to any stored EIP-634 text entry for key.

await resolver.getText("email"); // 'me@ricmoo.com' await resolver.getText("url"); // 'https://www.ricmoo.com/' await resolver.getText("com.twitter"); // '@ricmoo'

Logs Methods

provider.getLogs( filter ) Promise< Array< Log > >

Returns the Array of Log matching the filter.

Keep in mind that many backends will discard old events, and that requests which are too broad may get dropped as they require too many resources to execute the query.

Network Status Methods

provider.getNetwork( ) Promise< Network >

Returns the Network this Provider is connected to.

await provider.getNetwork() // { // chainId: 1, // ensAddress: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', // name: 'homestead' // }
provider.getBlockNumber( ) Promise< number >

Returns the block number (or height) of the most recently mined block.

await provider.getBlockNumber() // 16987688
provider.getGasPrice( ) Promise< BigNumber >

Returns a best guess of the Gas Price to use in a transaction.

// The gas price (in wei)... gasPrice = await provider.getGasPrice() // { BigNumber: "23238878592" } // ...often this gas price is easier to understand or // display to the user in gwei utils.formatUnits(gasPrice, "gwei") // '23.238878592'
provider.getFeeData( ) Promise< FeeData >

Returns the current recommended FeeData to use in a transaction.

For an EIP-1559 transaction, the maxFeePerGas and maxPriorityFeePerGas should be used.

For legacy transactions and networks which do not support EIP-1559, the gasPrice should be used.

// The gas price (in wei)... feeData = await provider.getFeeData() // { // gasPrice: { BigNumber: "23238878592" }, // lastBaseFeePerGas: { BigNumber: "23169890320" }, // maxFeePerGas: { BigNumber: "47839780640" }, // maxPriorityFeePerGas: { BigNumber: "1500000000" } // } // ...often these values are easier to understand or // display to the user in gwei utils.formatUnits(feeData.maxFeePerGas, "gwei") // '47.83978064'
provider.ready Promise< Network >

Returns a Promise which will stall until the network has heen established, ignoring errors due to the target node not being active yet.

This can be used for testing or attaching scripts to wait until the node is up and running smoothly.

Transactions Methods

provider.call( transaction [ , blockTag = latest ] ) Promise< string< DataHexString > >

Returns the result of executing the transaction, using call. A call does not require any ether, but cannot change any state. This is useful for calling getters on Contracts.

await provider.call({ // ENS public resolver address to: "0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41", // `function addr(namehash("ricmoo.eth")) view returns (address)` data: "0x3b3b57debf074faa138b72c65adbdcfb329847e4f2c04bde7f7dd7fcad5a52d2f395a558" }); // '0x0000000000000000000000005555763613a12d8f3e73be831dff8598089d3dca'
provider.estimateGas( transaction ) Promise< BigNumber >

Returns an estimate of the amount of gas that would be required to submit transaction to the network.

An estimate may not be accurate since there could be another transaction on the network that was not accounted for, but after being mined affected relevant state.

await provider.estimateGas({ // Wrapped ETH address to: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // `function deposit() payable` data: "0xd0e30db0", // 1 ether value: parseEther("1.0") }); // { BigNumber: "27938" }
provider.getTransaction( hash ) Promise< TransactionResponse >

Returns the transaction with hash or null if the transaction is unknown.

If a transaction has not been mined, this method will search the transaction pool. Various backends may have more restrictive transaction pool access (e.g. if the gas price is too low or the transaction was only recently sent and not yet indexed) in which case this method may also return null.

await provider.getTransaction("0x5b73e239c55d790e3c9c3bbb84092652db01bb8dbf49ccc9e4a318470419d9a0"); // { // accessList: null, // blockHash: '0x8a179bc6cb299f936c4fd614995e62d597ec6108b579c23034fb220967ceaa94', // blockNumber: 12598244, // chainId: 1, // confirmations: 4389445, // creates: '0x733aF852514e910E2f8af40d61E00530377889E9', // data: '0x608060405234801561001057600080fd5b5060405161062438038061062483398101604081905261002f916100cd565b60405163c47f002760e01b815260206004820152600d60248201526c0daead8e8d2c6c2d8d85ccae8d609b1b60448201526001600160a01b0382169063c47f002790606401602060405180830381600087803b15801561008e57600080fd5b505af11580156100a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100c691906100fb565b5050610113565b6000602082840312156100de578081fd5b81516001600160a01b03811681146100f4578182fd5b9392505050565b60006020828403121561010c578081fd5b5051919050565b610502806101226000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c80634c0770b914610030575b600080fd5b61004361003e366004610309565b61005b565b60405161005293929190610389565b60405180910390f35b600060608085841461006c57600080fd5b8567ffffffffffffffff81111561009357634e487b7160e01b600052604160045260246000fd5b6040519080825280602002602001820160405280156100bc578160200160208202803683370190505b5091508567ffffffffffffffff8111156100e657634e487b7160e01b600052604160045260246000fd5b60405190808252806020026020018201604052801561011957816020015b60608152602001906001900390816101045790505b50905060005b86811015610235576101cd8a8a8a8a8581811061014c57634e487b7160e01b600052603260045260246000fd5b905060200201602081019061016191906102db565b89898681811061018157634e487b7160e01b600052603260045260246000fd5b90506020028101906101939190610460565b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061024592505050565b8483815181106101ed57634e487b7160e01b600052603260045260246000fd5b6020026020010184848151811061021457634e487b7160e01b600052603260045260246000fd5b6020908102919091010191909152528061022d816104a5565b91505061011f565b5043925096509650969350505050565b6000606060405190506000815260208101604052600080845160208601878afa9150843d101561028857603f3d01601f191681016040523d81523d6000602083013e5b94509492505050565b60008083601f8401126102a2578182fd5b50813567ffffffffffffffff8111156102b9578182fd5b6020830191508360208260051b85010111156102d457600080fd5b9250929050565b6000602082840312156102ec578081fd5b81356001600160a01b0381168114610302578182fd5b9392505050565b60008060008060008060808789031215610321578182fd5b8635955060208701359450604087013567ffffffffffffffff80821115610346578384fd5b6103528a838b01610291565b9096509450606089013591508082111561036a578384fd5b5061037789828a01610291565b979a9699509497509295939492505050565b60006060820185835260206060818501528186518084526080860191508288019350845b818110156103c9578451835293830193918301916001016103ad565b5050848103604086015285518082528282019350600581901b82018301838801865b8381101561045057601f1980868503018852825180518086528a5b81811015610421578281018a01518782018b01528901610406565b81811115610431578b8a83890101525b5098880198601f019091169390930186019250908501906001016103eb565b50909a9950505050505050505050565b6000808335601e19843603018112610476578283fd5b83018035915067ffffffffffffffff821115610490578283fd5b6020019150368190038213156102d457600080fd5b60006000198214156104c557634e487b7160e01b81526011600452602481fd5b506001019056fea264697066735822122083b5dc25b3c9256aa4244eddaf9e4b5fccd09a45ec4e0174f2c900de7144602d64736f6c63430008040033000000000000000000000000084b1c3c81545d370f3634392de611caabff8148', // from: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // gasLimit: { BigNumber: "443560" }, // gasPrice: { BigNumber: "10100000000" }, // hash: '0x5b73e239c55d790e3c9c3bbb84092652db01bb8dbf49ccc9e4a318470419d9a0', // nonce: 745, // r: '0xaf2b969de6dfb234fb8843f47a029636abb1ef52f26bb8bb615bbabcf23808e9', // s: '0x3dd61cd8df015e0af5689a249dd3224ee71f2b04917b7b4c14f7e68bb3a4ec17', // to: null, // transactionIndex: 315, // type: 0, // v: 38, // value: { BigNumber: "0" }, // wait: [Function (anonymous)] // }
provider.getTransactionReceipt( hash ) Promise< TransactionReceipt >

Returns the transaction receipt for hash or null if the transaction has not been mined.

To stall until the transaction has been mined, consider the waitForTransaction method below.

await provider.getTransactionReceipt("0x5b73e239c55d790e3c9c3bbb84092652db01bb8dbf49ccc9e4a318470419d9a0"); // { // blockHash: '0x8a179bc6cb299f936c4fd614995e62d597ec6108b579c23034fb220967ceaa94', // blockNumber: 12598244, // byzantium: true, // confirmations: 4389445, // contractAddress: '0x733aF852514e910E2f8af40d61E00530377889E9', // cumulativeGasUsed: { BigNumber: "12102324" }, // effectiveGasPrice: { BigNumber: "10100000000" }, // from: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // gasUsed: { BigNumber: "443560" }, // logs: [ // { // address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', // blockHash: '0x8a179bc6cb299f936c4fd614995e62d597ec6108b579c23034fb220967ceaa94', // blockNumber: 12598244, // data: '0x000000000000000000000000084b1c3c81545d370f3634392de611caabff8148', // logIndex: 160, // topics: [ // '0xce0457fe73731f824cc272376169235128c118b49d344817417c6d108d155e82', // '0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2', // '0x4774f6d3b3d08b5ec00115f0e2fddb92604b39e52b0dc908c6f8fcb7aa5d2a9a' // ], // transactionHash: '0x5b73e239c55d790e3c9c3bbb84092652db01bb8dbf49ccc9e4a318470419d9a0', // transactionIndex: 315 // }, // { // address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', // blockHash: '0x8a179bc6cb299f936c4fd614995e62d597ec6108b579c23034fb220967ceaa94', // blockNumber: 12598244, // data: '0x000000000000000000000000a2c122be93b0074270ebee7f6b7292c7deb45047', // logIndex: 161, // topics: [ // '0x335721b01866dc23fbee8b6b2c7b1e14d6f05c28cd35a2c934239f94095602a0', // '0x790fdce97f7b2b1c4c5a709fb6a49bf878feffcaa85ed0245f6dff09abcefda7' // ], // transactionHash: '0x5b73e239c55d790e3c9c3bbb84092652db01bb8dbf49ccc9e4a318470419d9a0', // transactionIndex: 315 // } // ], // logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000004000000000000010000000000000020000000000000000000040000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000040000000000000000100004000000000000008000040000000000000000000000000000000000005000000000041000000000000000000000000000000000000000000000000100000000000000001000000000000000000000', // status: 1, // to: null, // transactionHash: '0x5b73e239c55d790e3c9c3bbb84092652db01bb8dbf49ccc9e4a318470419d9a0', // transactionIndex: 315, // type: 0 // }
provider.sendTransaction( transaction ) Promise< TransactionResponse >

Submits transaction to the network to be mined. The transaction must be signed, and be valid (i.e. the nonce is correct and the account has sufficient balance to pay for the transaction).

const signedTx = "0x02f8758301e240048459682f008459682f0e825208945555763613a12d8f3e73be831dff8598089d3dca882b992b75cbeb600080c001a0ee36e3db4e4b3b437a1bae6a5f919c68f94d85d1dd189274b493912bf57fd013a02bbced1de4b62ba732fb67ddb75e6ac941c12069d1644a9b729a036f781b36de"; await provider.sendTransaction(signedTx); // { // accessList: [], // chainId: 123456, // confirmations: 0, // data: '0x', // from: '0x46E0726Ef145d92DEA66D38797CF51901701926e', // gasLimit: { BigNumber: "21000" }, // gasPrice: null, // hash: '0x6cedbc19675c30c4a1604e40d2d5a4b801c4de57e6d2315a5b19328a61913257', // maxFeePerGas: { BigNumber: "1500000014" }, // maxPriorityFeePerGas: { BigNumber: "1500000000" }, // nonce: 4, // r: '0xee36e3db4e4b3b437a1bae6a5f919c68f94d85d1dd189274b493912bf57fd013', // s: '0x2bbced1de4b62ba732fb67ddb75e6ac941c12069d1644a9b729a036f781b36de', // to: '0x5555763613a12D8F3e73be831DFf8598089d3dCa', // type: 2, // v: 1, // value: { BigNumber: "3141590000000000000" }, // wait: [Function (anonymous)] // }
provider.waitForTransaction( hash [ , confirms = 1 [ , timeout ] ] ) Promise< TxReceipt >

Returns a Promise which will not resolve until transactionHash is mined.

If confirms is 0, this method is non-blocking and if the transaction has not been mined returns null. Otherwise, this method will block until the transaction has confirms blocks mined on top of the block in which is was mined.

Event Emitter Methods

The EventEmitter API allows applications to use an Observer Pattern to register callbacks for when various events occur.

This closely follows the Event Emitter provided by other JavaScript libraries with the exception that event names support some more complex objects, not only strings. The objects are normalized internally.

provider.on( eventName , listener ) this

Add a listener to be triggered for each eventName event.

provider.once( eventName , listener ) this

Add a listener to be triggered for only the next eventName event, at which time it will be removed.

provider.emit( eventName , ...args ) boolean

Notify all listeners of the eventName event, passing args to each listener. This is generally only used internally.

provider.off( eventName [ , listener ] ) this

Remove a listener for the eventName event. If no listener is provided, all listeners for eventName are removed.

provider.removeAllListeners( [ eventName ] ) this

Remove all the listeners for the eventName events. If no eventName is provided, all events are removed.

provider.listenerCount( [ eventName ] ) number

Returns the number of listeners for the eventName events. If no eventName is provided, the total number of listeners is returned.

provider.listeners( eventName ) Array< Listener >

Returns the list of Listeners for the eventName events.

Events

Any of the following may be used as the eventName in the above methods.

Log Filter

A filter is an object, representing a contract log Filter, which has the optional properties address (the source contract) and topics (a topic-set to match).

If address is unspecified, the filter matches any contract address.

See EventFilters for more information on filtering events.

Topic-Set Filter

The value of a Topic-Set Filter is a array of Topic-Sets.

This event is identical to a Log Filter with the address omitted (i.e. from any contract).

See EventFilters for more information on filtering events.

Transaction Filter

The value of a Transaction Filter is any transaction hash.

This event is emitted on every block that is part of a chain that includes the given mined transaction. It is much more common that the once method is used than the on method.

In addition to transaction and filter events, there are several named events.

Event NameArgumentsDescription 
"block"blockNumberemitted when a new block is mined 
"error"erroremitted on any error 
"pending"pendingTransactionemitted when a new transaction enters the memory pool; only certain providers offer this event and may require running your own node for reliable results 
"willPoll"pollIdemitted prior to a polling loop is about to begin; (very rarely used by most developers) 
"poll"pollId, blockNumberemitted during each poll cycle after `blockNumber` is updated (if changed) and before any other events (if any) are emitted during the poll loop; (very rarely used by most developers) 
"didPoll"pollIdemitted after all events from a polling loop are emitted; (very rarely used by most developers) 
"debug"provider dependenteach Provider may use this to emit useful debugging information and the format is up to the developer; (very rarely used by most developers) 
Named Provider Events 
Events Example
provider.on("block", (blockNumber) => { // Emitted on every block change }) provider.once(txHash, (transaction) => { // Emitted when the transaction has been mined }) // This filter could also be generated with the Contract or // Interface API. If address is not specified, any address // matches and if topics is not specified, any log matches filter = { address: "dai.tokens.ethers.eth", topics: [ utils.id("Transfer(address,address,uint256)") ] } provider.on(filter, (log, event) => { // Emitted whenever a DAI token transfer occurs }) // Notice this is an array of topic-sets and is identical to // using a filter with no address (i.e. match any address) topicSets = [ utils.id("Transfer(address,address,uint256)"), null, [ hexZeroPad(myAddress, 32), hexZeroPad(myOtherAddress, 32) ] ] provider.on(topicSets, (log) => { // Emitted any token is sent TO either address }) provider.on("pending", (tx) => { // Emitted when any new pending transaction is noticed }); provider.on("error", (tx) => { // Emitted when any error occurs });

Inspection Methods

Provider.isProvider( object ) boolean

Returns true if and only if object is a Provider.

BaseProvider inherits Provider

Most Providers available in ethers are sub-classes of BaseProvider, which simplifies sub-classes, as it handles much of the event operations, such as polling and formatting.

provider.polling boolean

Indicates if the Provider is currently polling. If there are no events to poll for or polling has been explicitly disabled, this will be false.

provider.pollingInterval number

The frequency at which the provider polls.

JsonRpcProvider inherits BaseProvider

The JSON-RPC API is a popular method for interacting with Ethereum and is available in all major Ethereum node implementations (e.g. Geth and Parity) as well as many third-party web services (e.g. INFURA)

new ethers.providers.JsonRpcProvider( [ urlOrConnectionInfo [ , networkish ] ] )

Connect to a JSON-RPC HTTP API using the URL or ConnectionInfo urlOrConnectionInfo connected to the networkish network.

If urlOrConnectionInfo is not specified, the default (i.e. http://localhost:8545) is used and if no network is specified, it will be determined automatically by querying the node using eth_chainId and falling back on eth_networkId.

Note: Connecting to a Local Node

Each node implementation is slightly different and may require specific command-line flags, configuration or settings in their UI to enable JSON-RPC, unlock accounts or expose specific APIs. Please consult their documentation.

jsonRpcProvider.connection ConnectionInfo

The fully formed ConnectionInfo the Provider is connected to.

jsonRpcProvider.getSigner( [ addressOrIndex ] ) JsonRpcSigner

Returns a JsonRpcSigner which is managed by this Ethereum node, at addressOrIndex. If no addressOrIndex is provided, the first account (account #0) is used.

jsonRpcProvider.getUncheckedSigner( [ addressOrIndex ] ) JsonRpcUncheckedSigner
jsonRpcProvider.listAccounts( ) Promise< Array< string > >

Returns a list of all account addresses managed by this provider.

jsonRpcProvider.send( method , params ) Promise< any >

Allows sending raw messages to the provider.

This can be used for backend-specific calls, such as for debugging or specific account management.

JsonRpcSigner inherits Signer

A JsonRpcSigner is a simple Signer which is backed by a connected JsonRpcProvider.

signer.provider JsonRpcProvider

The provider this signer was established from.

signer.connectUnchecked( ) JsonRpcUncheckedSigner

Returns a new Signer object which does not perform additional checks when sending a transaction. See getUncheckedSigner for more details.

signer.sendUncheckedTransaction( transaction ) Promise< string< DataHexString< 32 > > >

Sends the transaction and returns a Promise which resolves to the opaque transaction hash.

signer.unlock( password ) Promise< boolean >

Request the node unlock the account (if locked) using password.

JsonRpcUncheckedSigner inherits Signer

The JSON-RPC API only provides a transaction hash as the response when a transaction is sent, but the ethers Provider requires populating all details of a transaction before returning it. For example, the gas price and gas limit may be adjusted by the node or the nonce automatically included, in which case the opaque transaction hash has discarded this.

To remedy this, the JsonRpcSigner immediately queries the provider for the details using the returned transaction hash to populate the TransactionResponse object.

Some backends do not respond immediately and instead defer releasing the details of a transaction it was responsible for signing until it is mined.

The UncheckedSigner does not populate any additional information and will immediately return the result as a mock TransactionResponse-like object, with most of the properties set to null, but allows access to the transaction hash quickly, if that is all that is required.

StaticJsonRpcProvider inherits JsonRpcProvider

An ethers Provider will execute frequent getNetwork calls to ensure the network calls and network being communicated with are consistent.

In the case of a client like MetaMask, this is desired as the network may be changed by the user at any time, in such cases the cost of checking the chainId is local and therefore cheap.

However, there are also many times where it is known the network cannot change, such as when connecting to an INFURA endpoint, in which case, the StaticJsonRpcProvider can be used which will indefinitely cache the chain ID, which can reduce network traffic and reduce round-trip queries for the chain ID.

This Provider should only be used when it is known the network cannot change.

Node-Specific Methods

Many methods are less common or specific to certain Ethereum Node implementations (e.g. Parity vs Geth. These include account and admin management, debugging, deeper block and transaction exploration and other services (such as Swarm and Whisper).

The jsonRpcProvider.send method can be used to access these.

API Providers

There are many services which offer a web API for accessing the Ethereum Blockchain. These Providers allow connecting to them, which simplifies development, since you do not need to run your own instance or cluster of Ethereum nodes.

However, this reliance on third-party services can reduce resilience, security and increase the amount of required trust. To mitigate these issues, it is recommended you use a Default Provider.

EtherscanProvider inherits BaseProvider

The EtherscanProvider is backed by a combination of the various Etherscan APIs.

new ethers.providers.EtherscanProvider( [ network = "homestead" , [ apiKey ] ] )

Create a new EtherscanProvider connected to network with the optional apiKey.

The network may be specified as a string for a common network name, a number for a common chain ID or a [Network Object]provider-(network).

If no apiKey is provided, a shared API key will be used, which may result in reduced performance and throttled requests. It is highly recommended for production, you register with Etherscan for your own API key.

Note: Default API keys

If no apiKey is provided, a shared API key will be used, which may result in reduced performance and throttled requests.

It is highly recommended for production, you register with Etherscan for your own API key.

Supported Networks

  • homestead - Homestead (Mainnet)
  • goerli - Görli (clique testnet)
  • sepolia - Sepolia (proof-of-authority testnet)
  • arbitrum - Arbitrum Optimistic L2
  • arbitrum-goerli - Arbitrum Optimistic L2 testnet
  • matic - Polgon mainnet
  • maticmum - Polgon testnet
  • optimism - Optimism Optimistic L2
  • optimism-goerli - Optimism Optimistic L2 testnet

Etherscan Examples
// Connect to mainnet (homestead) provider = new EtherscanProvider(); // Connect to goerli testnet (these are equivalent) provider = new EtherscanProvider("goerli"); provider = new EtherscanProvider(5); network = ethers.providers.getNetwork("goerli"); // { // chainId: 5, // ensAddress: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', // name: 'goerli' // } provider = new EtherscanProvider(network); // Connect to mainnet (homestead) with an API key provider = new EtherscanProvider(null, apiKey); provider = new EtherscanProvider("homestead", apiKey);
provider.getHistory( address ) Array< History >

@TODO... Explain

InfuraProvider inherits UrlJsonRpcProvider

The InfuraProvider is backed by the popular INFURA Ethereum service.

new ethers.providers.InfuraProvider( [ network = "homestead" , [ apiKey ] ] )

Create a new InfuraProvider connected to network with the optional apiKey.

The network may be specified as a string for a common network name, a number for a common chain ID or a [Network Object]provider-(network).

The apiKey can be a string Project ID or an object with the properties projectId and projectSecret to specify a Project Secret which can be used on non-public sources (like on a server) to further secure your API access and quotas.

InfuraProvider.getWebSocketProvider( [ network [ , apiKey ] ] ) WebSocketProvider

Create a new WebSocketProvider using the INFURA web-socket endpoint to connect to network with the optional apiKey.

The network and apiKey are specified the same as the constructor.

Note: Default API keys

If no apiKey is provided, a shared API key will be used, which may result in reduced performance and throttled requests.

It is highly recommended for production, you register with INFURA for your own API key.

Supported Networks

  • homestead - Homestead (Mainnet)
  • goerli - Görli (clique testnet)
  • sepolia - Sepolia (proof-of-authority testnet)
  • arbitrum - Arbitrum Optimistic L2
  • arbitrum-goerli - Arbitrum Optimistic L2 testnet
  • matic - Polgon mainnet
  • maticmum - Polgon testnet
  • optimism - Optimism Optimistic L2
  • optimism-goerli - Optimism Optimistic L2 testnet

INFURA Examples
// Connect to mainnet (homestead) provider = new InfuraProvider(); // Connect to the goerli testnet // (see EtherscanProvider above for other network examples) provider = new InfuraProvider("goerli"); // Connect to mainnet with a Project ID (these are equivalent) provider = new InfuraProvider(null, projectId); provider = new InfuraProvider("homestead", projectId); // Connect to mainnet with a Project ID and Project Secret provider = new InfuraProvider("homestead", { projectId: projectId, projectSecret: projectSecret }); // Connect to the INFURA WebSocket endpoints with a WebSocketProvider provider = InfuraProvider.getWebSocketProvider()

AlchemyProvider inherits UrlJsonRpcProvider

The AlchemyProvider is backed by Alchemy.

new ethers.providers.AlchemyProvider( [ network = "homestead" , [ apiKey ] ] )

Create a new AlchemyProvider connected to network with the optional apiKey.

The network may be specified as a string for a common network name, a number for a common chain ID or a Network Object.

Note: Default API keys

If no apiKey is provided, a shared API key will be used, which may result in reduced performance and throttled requests.

It is highly recommended for production, you register with Alchemy for your own API key.

Supported Networks

  • homestead - Homestead (Mainnet)
  • goerli - Görli (clique testnet)
  • arbitrum - Arbitrum Optimistic L2
  • arbitrum-goerli - Arbitrum Optimistic L2 testnet
  • matic - Polgon mainnet
  • maticmum - Polgon testnet
  • optimism - Optimism Optimistic L2
  • optimism-goerli - Optimism Optimistic L2 testnet

Alchemy Examples
// Connect to mainnet (homestead) provider = new AlchemyProvider(); // Connect to the goerli testnet // (see EtherscanProvider above for other network examples) provider = new AlchemyProvider("goerli"); // Connect to mainnet with an API key (these are equivalent) provider = new AlchemyProvider(null, apiKey); provider = new AlchemyProvider("homestead", apiKey); // Connect to the Alchemy WebSocket endpoints with a WebSocketProvider provider = AlchemyProvider.getWebSocketProvider()

CloudflareProvider inherits UrlJsonRpcProvider

The CloudflareProvider is backed by the Cloudflare Ethereum Gateway.

new ethers.providers.CloudflareProvider( )

Create a new CloudflareProvider connected to mainnet (i.e. "homestead").

Supported Networks

  • homestead - Homestead (Mainnet)

Cloudflare Examples
// Connect to mainnet (homestead) provider = new CloudflareProvider();

PocketProvider inherits UrlJsonRpcProvider

The PocketProvider is backed by Pocket.

new ethers.providers.PocketProvider( [ network = "homestead" , [ apiKey ] ] )

Create a new PocketProvider connected to network with the optional apiKey.

The network may be specified as a string for a common network name, a number for a common chain ID or a Network Object.

Note: Default API keys

If no apiKey is provided, a shared API key will be used, which may result in reduced performance and throttled requests.

It is highly recommended for production, you register with Pocket for your own API key.

Supported Networks

  • homestead - Homestead (Mainnet)
  • goerli - Görli (clique testnet)
  • matic - Polgon mainnet
  • maticmum - Polgon testnet

Pocket Examples
// Connect to mainnet (homestead) provider = new PocketProvider(); // Connect to the goerli testnet // (see EtherscanProvider above for other network examples) provider = new PocketProvider("goerli"); // Connect to mainnet with an Application ID (these are equivalent) provider = new PocketProvider(null, applicationId); provider = new PocketProvider("homestead", applicationId); // Connect to mainnet with an application ID, application secret // and specify whether to use the load balances provider = new PocketProvider("homestead", { applicationId: applicationId, applicationSecretKey: applicationSecretKey, loadBalancer: loadBalancer // true or false });

AnkrProvider inherits UrlJsonRpcProvider

The AnkrProvider is backed by Ankr.

new ethers.providers.AnkrProvider( [ network = "homestead" , [ apiKey ] ] )

Create a new AnkrProvider connected to network with the optional apiKey.

The network may be specified as a string for a common network name, a number for a common chain ID or a Network Object.

Note: Default API keys

If no apiKey is provided, a shared API key will be used, which may result in reduced performance and throttled requests.

It is highly recommended for production, you register with Ankr for your own API key.

Supported Networks

  • homestead - Homestead (Mainnet)
  • matic - Polygon
  • arbitrum - Arbitrum (L2; optimistic roll-up)

Ankr Examples
// Connect to mainnet (homestead) provider = new AnkrProvider(); // Connect to polygont // (see EtherscanProvider above for other network examples) provider = new AnkrProvider("matic"); // Connect to mainnet with an API Key (these are equivalent) provider = new AnkrProvider(null, apiKey); provider = new AnkrProvider("homestead", apiKey);

Other Providers

FallbackProvider inherits BaseProvider

The FallbackProvider is the most advanced Provider available in ethers.

It uses a quorum and connects to multiple Providers as backends, each configured with a priority and a weight .

When a request is made, the request is dispatched to multiple backends, randomly chosen (lower-value priority backends are always selected first) and the results from each are compared against the others. Only once the quorum has been reached will that result be accepted and returned to the caller.

By default the quorum requires 50% (rounded up) of the backends to agree. The weight can be used to give a backend Provider more influence.

new ethers.providers.FallbackProvider( providers [ , quorum ] )

Creates a new instance of a FallbackProvider connected to providers. If quorum is not specified, half of the total sum of the provider weights is used.

The providers can be either an array of Provider or FallbackProviderConfig. If a Provider is provided, the defaults are a priority of 1 and a weight of 1.

provider.providerConfigs Array< FallbackProviderConfig >

The list of Provider Configurations that describe the backends.

provider.quorum number

The quorum the backend responses must agree upon before a result will be resolved. By default this is half the sum of the weights.

FallbackProviderConfig

fallbackProviderConfig.provider Provider

The provider for this configuration.

fallbackProviderConfig.priority number

The priority used for the provider. Lower-value priorities are favoured over higher-value priorities. If multiple providers share the same priority, they are chosen at random.

fallbackProviderConfig.stallTimeout number

The timeout (in ms) after which another Provider will be attempted. This does not affect the current Provider; if it returns a result it is counted as part of the quorum.

Lower values will result in more network traffic, but may reduce the response time of requests.

fallbackProviderConfig.weight number

The weight a response from this provider provides. This can be used if a given Provider is more trusted, for example.

IpcProvider inherits JsonRpcProvider

The IpcProvider allows the JSON-RPC API to be used over a local filename on the file system, exposed by Geth, Parity and other nodes.

This is only available in node.js (as it requires file system access, and may have additional complications due to file permissions. See any related notes on the documentation for the actual node implementation websites.

ipcProvider.path string

The path this Provider is connected to.

JsonRpcBatchProvider inherits JsonRpcProvider

The JsonRpcBatchProvider operated identically to any other Provider, except the calls are implicly batched during an event-loop and sent using the JSON-RPC batch protocol to the backend.

This results in fewer connections and fewer requests, which may result in lower costs or faster responses, depending on your use case.

Keep in mind some backends may not support batched requests.

UrlJsonRpcProvider inherits JsonRpcProvider

This class is intended to be sub-classed and not used directly. It simplifies creating a Provider where a normal JsonRpcProvider would suffice, with a little extra effort needed to generate the JSON-RPC URL.

new ethers.providers.UrlJsonRpcProvider( [ network [ , apiKey ] ] )

Sub-classes do not need to override this. Instead they should override the static method getUrl and optionally getApiKey.

urlJsonRpcProvider.apiKey any

The value of the apiKey that was returned from InheritedClass.getApiKey.

InheritingClass.getApiKey( apiKey ) any

This function should examine the apiKey to ensure it is valid and return a (possible modified) value to use in getUrl.

InheritingClass.getUrl( network , apiKey ) string

The URL to use for the JsonRpcProvider instance.

Web3Provider inherits JsonRpcProvider

The Web3Provider is meant to ease moving from a web3.js based application to ethers by wrapping an existing Web3-compatible (such as a Web3HttpProvider, Web3IpcProvider or Web3WsProvider) and exposing it as an ethers.js Provider which can then be used with the rest of the library.

This may also be used to wrap a standard EIP-1193 Provider.

new ethers.providers.Web3Provider( externalProvider [ , network ] )

Create a new Web3Provider, which wraps an EIP-1193 Provider or Web3Provider-compatible Provider.

web3Provider.provider Web3CompatibleProvider

The provider used to create this instance.

ExternalProvider

An ExternalProvider can be either one for the above mentioned Web3 Providers (or otherwise compatible) or an EIP-1193 provider.

An ExternalProvider must offer one of the following signatures, and the first matching is used:

externalProvider.request( request ) Promise< any >

This follows the EIP-1193 API signature.

The request should be a standard JSON-RPC payload, which should at a minimum specify the method and params.

The result should be the actual result, which differs from the Web3.js response, which is a wrapped JSON-RPC response.

externalProvider.sendAsync( request , callback ) void

This follows the Web3.js Provider Signature.

The request should be a standard JSON-RPC payload, which should at a minimum specify the method and params.

The callback should use the error-first calling semantics, so (error, result) where the result is a JSON-RPC wrapped result.

externalProvider.send( request , callback ) void

This is identical to sendAsync. Historically, this used a synchronous web request, but no current browsers support this, so its use this way was deprecated quite a long time ago

WebSocketProvider inherits JsonRpcProvider

The WebSocketProvider connects to a JSON-RPC WebSocket-compatible backend which allows for a persistent connection, multiplexing requests and pub-sub events for a more immediate event dispatching.

The WebSocket API is newer, and if running your own infrastructure, note that WebSockets are much more intensive on your server resources, as they must manage and maintain the state for each client. For this reason, many services may also charge additional fees for using their WebSocket endpoints.

new ethers.providers.WebSocketProvider( [ url [ , network ] ] )

Returns a new WebSocketProvider connected to url as the network.

If url is unspecified, the default "ws://localhost:8546" will be used. If network is unspecified, it will be queried from the network.

Types

BlockTag

A BlockTag specifies a specific block location in the Blockchain.

Networkish

A Networkish may be any of the following:

Network

A Network represents an Ethereum network.

network.name string

The human-readable name of the network, such as homestead. If the network name is unknown, this will be "unknown".

network.chainId number

The Chain ID of the network.

network.ensAddress string< Address >

The address at which the ENS registry is deployed on this network.

FeeData

A FeeData object encapsulates the necessary fee data required to send a transaction, based on the best available recommendations.

feeData.gasPrice BigNumber

The gasPrice to use for legacy transactions or networks which do not support EIP-1559.

feeData.maxFeePerGas BigNumber

The maxFeePerGas to use for a transaction. This is based on the most recent block's baseFee.

feeData.maxPriorityFeePerGas BigNumber

The maxPriorityFeePerGas to use for a transaction. This accounts for the uncle risk and for the majority of current MEV risk.

Block

block.hash string< DataHexString< 32 > >

The hash of this block.

block.parentHash string< DataHexString< 32 > >

The hash of the previous block.

block.number number

The height (number) of this block.

block.timestamp number

The timestamp of this block.

block.nonce string< DataHexString >

The nonce used as part of the proof-of-work to mine this block.

This property is generally of little interest to developers.

block.difficulty number

The difficulty target required to be met by the miner of the block.

Recently the difficulty frequently exceeds the size that a JavaScript number can safely store (53-bits), so in that case this property may be null. It is recommended to use the `_difficulty` property below, which will always return a value, but as a BigNumber.

This property is generally of little interest to developers.

block._difficulty BigNumber

The difficulty target required to be met by the miner of the block, as a BigNumber.

Recently the difficulty frequently exceeds the size that a JavaScript number can safely store (53-bits), so this property was added to safely encode the value for applications that require it.

This property is generally of little interest to developers.

block.gasLimit BigNumber

The maximum amount of gas that this block was permitted to use. This is a value that can be voted up or voted down by miners and is used to automatically adjust the bandwidth requirements of the network.

This property is generally of little interest to developers.

block.gasUsed BigNumber

The total amount of gas used by all transactions in this block.

block.miner string

The coinbase address of this block, which indicates the address the miner that mined this block would like the subsidy reward to go to.

block.extraData string

This is extra data a miner may choose to include when mining a block.

This property is generally of little interest to developers.

Block (with transaction hashes)

Often only the hashes of the transactions included in a block are needed, so by default a block only contains this information, as it is substantially less data.

block.transactions Array< string< DataHexString< 32 > > >

A list of the transactions hashes for each transaction this block includes.

BlockWithTransactions inherits Block

If all transactions for a block are needed, this object instead includes the full details on each transaction.

block.transactions Array< TransactionResponse >

A list of the transactions this block includes.

Events and Logs

EventFilter

filter.address string< Address >

The address to filter by, or null to match any address.

filter.topics Array< string< Data< 32 > > | Array< string< Data< 32 > > > >

The topics to filter by or null to match any topics.

Each entry represents an AND condition that must match, or may be null to match anything. If a given entry is an Array, then that entry is treated as an OR for any value in the entry.

See Filters for more details and examples on specifying complex filters.

Filter inherits EventFilter

filter.fromBlock BlockTag

The starting block (inclusive) to search for logs matching the filter criteria.

filter.toBlock BlockTag

The end block (inclusive) to search for logs matching the filter criteria.

FilterByBlockHash inherits EventFilter

filter.blockHash string< DataHexString< 32 > >

The specific block (by its block hash) to search for logs matching the filter criteria.

Log

log.blockNumber number

The block height (number) of the block including the transaction of this log.

log.blockHash string< DataHexString< 32 > >

The block hash of the block including the transaction of this log.

log.removed boolean

During a re-org, if a transaction is orphaned, this will be set to true to indicate the Log entry has been removed; it will likely be emitted again in the near future when another block is mined with the transaction that triggered this log, but keep in mind the values may change.

log.address string< Address >

The address of the contract that generated this log.

log.data string< DataHexString >

The data included in this log.

log.topics Array< string< DataHexString< 32 > > >

The list of topics (indexed properties) for this log.

log.transactionHash string< DataHexString< 32 > >

The transaction hash of the transaction of this log.

log.transactionIndex number

The index of the transaction in the block of the transaction of this log.

log.logIndex number

The index of this log across all logs in the entire block.

Transactions

TransactionRequest

A transaction request describes a transaction that is to be sent to the network or otherwise processed.

All fields are optional and may be a promise which resolves to the required type.

transactionRequest.to string | Promise< string >

The address (or ENS name) this transaction it to.

transactionRequest.from string< Address > | Promise< string< Address > >

The address this transaction is from.

transactionRequest.nonce number | Promise< number >

The nonce for this transaction. This should be set to the number of transactions ever sent from this address.

transactionRequest.data DataHexString | Promise< DataHexString >

The transaction data.

transactionRequest.value BigNumber | Promise< BigNumber >

The amount (in wei) this transaction is sending.

transactionRequest.gasLimit BigNumber | Promise< BigNumber >

The maximum amount of gas this transaction is permitted to use.

If left unspecified, ethers will use estimateGas to determine the value to use. For transactions with unpredicatable gas estimates, this may be required to specify explicitly.

transactionRequest.gasPrice BigNumber | Promise< BigNumber >

The price (in wei) per unit of gas this transaction will pay.

This may not be specified for transactions with type set to 1 or 2, or if maxFeePerGas or maxPriorityFeePerGas is given.

transactionRequest.maxFeePerGas BigNumber | Promise< BigNumber >

The maximum price (in wei) per unit of gas this transaction will pay for the combined EIP-1559 block's base fee and this transaction's priority fee.

Most developers should leave this unspecified and use the default value that ethers determines from the network.

This may not be specified for transactions with type set to 0 or if gasPrice is specified..

transactionRequest.maxPriorityFeePerGas BigNumber | Promise< BigNumber >

The price (in wei) per unit of gas this transaction will allow in addition to the EIP-1559 block's base fee to bribe miners into giving this transaction priority. This is included in the maxFeePerGas, so this will not affect the total maximum cost set with maxFeePerGas.

Most developers should leave this unspecified and use the default value that ethers determines from the network.

This may not be specified for transactions with type set to 0 or if gasPrice is specified.

transactionRequest.chainId number | Promise< number >

The chain ID this transaction is authorized on, as specified by EIP-155.

If the chain ID is 0 will disable EIP-155 and the transaction will be valid on any network. This can be dangerous and care should be taken, since it allows transactions to be replayed on networks that were possibly not intended. Intentionally-replayable transactions are also disabled by default on recent versions of Geth and require configuration to enable.

transactionRequest.type null | number

The EIP-2718 type of this transaction envelope, or null for to use the network default. To force using a lagacy transaction without an envelope, use type 0.

transactionRequest.accessList AccessListish

The AccessList to include; only available for EIP-2930 and EIP-1559 transactions.

TransactionResponse inherits Transaction

A TransactionResponse includes all properties of a Transaction as well as several properties that are useful once it has been mined.

transaction.blockNumber number

The number ("height") of the block this transaction was mined in. If the block has not been mined, this is null.

transaction.blockHash string< DataHexString< 32 > >

The hash of the block this transaction was mined in. If the block has not been mined, this is null.

transaction.timestamp number

The timestamp of the block this transaction was mined in. If the block has not been mined, this is null.

transaction.confirmations number

The number of blocks that have been mined (including the initial block) since this transaction was mined.

transaction.raw string< DataHexString >

The serialized transaction. This may be null as some backends do not populate it. If this is required, it can be computed from a TransactionResponse object using this cookbook recipe.

transaction.wait( [ confirms = 1 ] ) Promise< TransactionReceipt >

Resolves to the TransactionReceipt once the transaction has been included in the chain for confirms blocks. If confirms is 0, and the transaction has not been mined, null is returned.

If the transaction execution failed (i.e. the receipt status is 0), a CALL_EXCEPTION error will be rejected with the following properties:

  • error.transaction - the original transaction
  • error.transactionHash - the hash of the transaction
  • error.receipt - the actual receipt, with the status of 0

If the transaction is replaced by another transaction, a TRANSACTION_REPLACED error will be rejected with the following properties:

  • error.hash - the hash of the original transaction which was replaced
  • error.reason - a string reason; one of "repriced", "cancelled" or "replaced"
  • error.cancelled - a boolean; a "repriced" transaction is not considered cancelled, but "cancelled" and "replaced" are
  • error.replacement - the replacement transaction (a TransactionResponse)
  • error.receipt - the receipt of the replacement transaction (a TransactionReceipt)

Transactions are replaced when the user uses an option in their client to send a new transaction from the same account with the original nonce. This is usually to speed up a transaction or to cancel one, by bribing miners with additional fees to prefer the new transaction over the original one.

transactionRequest.type number

The EIP-2718 type of this transaction. If the transaction is a legacy transaction without an envelope, it will have the type 0.

transactionRequest.accessList AccessList

The AccessList included, or null for transaction types which do not support access lists.

TransactionReceipt

receipt.to string< Address >

The address this transaction is to. This is null if the transaction was an init transaction, used to deploy a contract.

receipt.from string< Address >

The address this transaction is from.

receipt.contractAddress string< Address >

If this transaction has a null to address, it is an init transaction used to deploy a contract, in which case this is the address created by that contract.

To compute a contract address, the getContractAddress utility function can also be used with a TransactionResponse object, which requires the transaction nonce and the address of the sender.

receipt.transactionIndex number

The index of this transaction in the list of transactions included in the block this transaction was mined in.

receipt.type number

The EIP-2718 type of this transaction. If the transaction is a legacy transaction without an envelope, it will have the type 0.

receipt.root string

The intermediate state root of a receipt.

Only transactions included in blocks before the Byzantium Hard Fork have this property, as it was replaced by the status property.

The property is generally of little use to developers. At the time it could be used to verify a state transition with a fraud-proof only considering the single transaction; without it the full block must be considered.

receipt.gasUsed BigNumber

The amount of gas actually used by this transaction.

receipt.effectiveGasPrice BigNumber

The effective gas price the transaction was charged at.

Prior to EIP-1559 or on chains that do not support it, this value will simply be equal to the transaction gasPrice.

On EIP-1559 chains, this is equal to the block baseFee for the block that the transaction was included in, plus the transaction maxPriorityFeePerGas clamped to the transaction maxFeePerGas.

receipt.logsBloom string< DataHexString >

A bloom-filter, which includes all the addresses and topics included in any log in this transaction.

receipt.blockHash string< DataHexString< 32 > >

The block hash of the block that this transaction was included in.

receipt.transactionHash string< DataHexString< 32 > >

The transaction hash of this transaction.

receipt.logs Array< Log >

All the logs emitted by this transaction.

receipt.blockNumber number

The block height (number) of the block that this transaction was included in.

receipt.confirmations number

The number of blocks that have been mined since this transaction, including the actual block it was mined in.

receipt.cumulativeGasUsed BigNumber

For the block this transaction was included in, this is the sum of the gas used by each transaction in the ordered list of transactions up to (and including) this transaction.

This is generally of little interest to developers.

receipt.byzantium boolean

This is true if the block is in a post-Byzantium Hard Fork block.

receipt.status number

The status of a transaction is 1 is successful or 0 if it was reverted. Only transactions included in blocks post-Byzantium Hard Fork have this property.

Access Lists

An Access List is optional an includes a list of addresses and storage slots for that address which should be warmed or pre-fetched for use within the execution of this transaction. A warmed value has an additional upfront cost to access, but is discounted throughout the code execution for reading and writing.

AccessListish

A looser description of an AccessList, which will be converted internally using accessListify.

It may be any of:

When using the object form (the last option), the addresses and storage slots will be sorted. If an explicit order for the access list is required, one of the other forms must be used. Most developers do not require explicit order.

equivalent to the AccessList example below
// Option 1: // AccessList // see below // Option 2: // Array< [ Address, Array<Bytes32> ] > accessList = [ [ "0x0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", [ "0x0000000000000000000000000000000000000000000000000000000000000004", "0x0bcad17ecf260d6506c6b97768bdc2acfb6694445d27ffd3f9c1cfbee4a9bd6d" ] ], [ "0x5FfC014343cd971B7eb70732021E26C35B744cc4", [ "0x0000000000000000000000000000000000000000000000000000000000000001" ] ] ]; // Option 3: // Record<Address, Array<Bytes32>> accessList = { "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e": [ "0x0000000000000000000000000000000000000000000000000000000000000004", "0x0bcad17ecf260d6506c6b97768bdc2acfb6694445d27ffd3f9c1cfbee4a9bd6d" ], "0x5FfC014343cd971B7eb70732021E26C35B744cc4": [ "0x0000000000000000000000000000000000000000000000000000000000000001" ] };

AccessList

An EIP-2930 transaction allows an optional AccessList which causes a transaction to warm (i.e. pre-cache) another addresses state and the specified storage keys.

This incurs an increased intrinsic cost for the transaction, but provides discounts for storage and state access throughout the execution of the transaction.

example access list
// Array of objects with the form: // { // address: Address, // storageKey: Array< DataHexString< 32 > > // } accessList = [ { address: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", storageKeys: [ "0x0000000000000000000000000000000000000000000000000000000000000004", "0x0bcad17ecf260d6506c6b97768bdc2acfb6694445d27ffd3f9c1cfbee4a9bd6d" ] }, { address: "0x5FfC014343cd971B7eb70732021E26C35B744cc4", storageKeys: [ "0x0000000000000000000000000000000000000000000000000000000000000001" ] } ];

Signers

A Signer in ethers is an abstraction of an Ethereum Account, which can be used to sign messages and transactions and send signed transactions to the Ethereum Network to execute state changing operations.

The available operations depend largely on the sub-class used.

For example, a Signer from MetaMask can send transactions and sign messages but cannot sign a transaction (without broadcasting it).

The most common Signers you will encounter are:

Signer

The Signer class is abstract and cannot be directly instantiated.

Instead use one of the concrete sub-classes, such as the Wallet, VoidSigner or JsonRpcSigner.

signer.connect( provider ) Signer

Sub-classes must implement this, however they may simply throw an error if changing providers is not supported.

signer.getAddress( ) Promise< string< Address > >

Returns a Promise that resolves to the account address.

This is a Promise so that a Signer can be designed around an asynchronous source, such as hardware wallets.

Sub-classes must implement this.

Signer.isSigner( object ) boolean

Returns true if and only if object is a Signer.

Blockchain Methods

signer.getBalance( [ blockTag = "latest" ] ) Promise< BigNumber >

Returns the balance of this wallet at blockTag.

signer.getChainId( ) Promise< number >

Returns the chain ID this wallet is connected to.

signer.getGasPrice( ) Promise< BigNumber >

Returns the current gas price.

signer.getTransactionCount( [ blockTag = "latest" ] ) Promise< number >

Returns the number of transactions this account has ever sent. This is the value required to be included in transactions as the nonce.

signer.call( transactionRequest ) Promise< string< DataHexString > >

Returns the result of calling using the transactionRequest, with this account address being used as the from field.

signer.estimateGas( transactionRequest ) Promise< BigNumber >

Returns the result of estimating the cost to send the transactionRequest, with this account address being used as the from field.

signer.resolveName( ensName ) Promise< string< Address > >

Returns the address associated with the ensName.

Signing

signer.signMessage( message ) Promise< string< RawSignature > >

This returns a Promise which resolves to the Raw Signature of message.

A signed message is prefixd with "\x19Ethereum Signed Message:\n" and the length of the message, using the hashMessage method, so that it is EIP-191 compliant. If recovering the address in Solidity, this prefix will be required to create a matching hash.

Sub-classes must implement this, however they may throw if signing a message is not supported, such as in a Contract-based Wallet or Meta-Transaction-based Wallet.

Note

If message is a string, it is treated as a string and converted to its representation in UTF8 bytes.

If and only if a message is a Bytes will it be treated as binary data.

For example, the string "0x1234" is 6 characters long (and in this case 6 bytes long). This is not equivalent to the array [ 0x12, 0x34 ], which is 2 bytes long.

A common case is to sign a hash. In this case, if the hash is a string, it must be converted to an array first, using the arrayify utility function.

signer.signTransaction( transactionRequest ) Promise< string< DataHexString > >

Returns a Promise which resolves to the signed transaction of the transactionRequest. This method does not populate any missing fields.

Sub-classes must implement this, however they may throw if signing a transaction is not supported, which is common for security reasons in many clients.

signer.sendTransaction( transactionRequest ) Promise< TransactionResponse >

This method populates the transactionRequest with missing fields, using populateTransaction and returns a Promise which resolves to the transaction.

Sub-classes must implement this, however they may throw if sending a transaction is not supported, such as the VoidSigner or if the Wallet is offline and not connected to a Provider.

signer._signTypedData( domain , types , value ) Promise< string< RawSignature > >

Signs the typed data value with types data structure for domain using the EIP-712 specification.

Experimental feature (this method name will change)

This is still an experimental feature. If using it, please specify the exact version of ethers you are using (e.g. spcify "5.0.18", not "^5.0.18") as the method name will be renamed from _signTypedData to signTypedData once it has been used in the field a bit.

Typed Data Example
// All properties on a domain are optional const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC' }; // The named list of all type definitions const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' } ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' } ] }; // The data to sign const value = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826' }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB' }, contents: 'Hello, Bob!' }; signature = await signer._signTypedData(domain, types, value); // '0x463b9c9971d1a144507d2e905f4e98becd159139421a4bb8d3c9c2ed04eb401057dd0698d504fd6ca48829a3c8a7a98c1c961eae617096cb54264bbdd082e13d1c'

Sub-Classes

It is very important that all important properties of a Signer are immutable. Since Ethereum is very asynchronous and deals with critical data (such as ether and other potentially valuable crypto assets), keeping properties such as the provider and address static throughout the life-cycle of the Signer helps prevent serious issues and many other classes and libraries make this assumption.

A sub-class must extend Signer and must call super().

signer.checkTransaction( transactionRequest ) TransactionRequest

This is generally not required to be overridden, but may be needed to provide custom behaviour in sub-classes.

This should return a copy of the transactionRequest, with any properties needed by call, estimateGas and populateTransaction (which is used by sendTransaction). It should also throw an error if any unknown key is specified.

The default implementation checks only if valid TransactionRequest properties exist and adds from to the transaction if it does not exist.

If there is a from field it must be verified to be equal to the Signer's address.

signer.populateTransaction( transactionRequest ) Promise< TransactionRequest >

This is generally not required to be overridden, but may be needed to provide custom behaviour in sub-classes.

This should return a copy of transactionRequest, follow the same procedure as checkTransaction and fill in any properties required for sending a transaction. The result should have all promises resolved; if needed the resolveProperties utility function can be used for this.

The default implementation calls checkTransaction and resolves to if it is an ENS name, adds gasPrice, nonce, gasLimit and chainId based on the related operations on Signer.

Wallet inherits ExternallyOwnedAccount and Signer

The Wallet class inherits Signer and can sign transactions and messages using a private key as a standard Externally Owned Account (EOA).

new ethers.Wallet( privateKey [ , provider ] )

Create a new Wallet instance for privateKey and optionally connected to the provider.

ethers.Wallet.createRandom( [ options = {} ] ) Wallet

Returns a new Wallet with a random private key, generated from cryptographically secure entropy sources. If the current environment does not have a secure entropy source, an error is thrown.

Wallets created using this method will have a mnemonic.

ethers.Wallet.fromEncryptedJson( json , password [ , progress ] ) Promise< Wallet >

Create an instance by decrypting an encrypted JSON wallet.

If progress is provided it will be called during decryption with a value between 0 and 1 indicating the progress towards completion.

ethers.Wallet.fromEncryptedJsonSync( json , password ) Wallet

Create an instance from an encrypted JSON wallet.

This operation will operate synchronously which will lock up the user interface, possibly for a non-trivial duration. Most applications should use the asynchronous fromEncryptedJson instead.

ethers.Wallet.fromMnemonic( mnemonic [ , path , [ wordlist ] ] ) Wallet

Create an instance from a mnemonic phrase.

If path is not specified, the Ethereum default path is used (i.e. m/44'/60'/0'/0/0).

If wordlist is not specified, the English Wordlist is used.

Properties

wallet.address string< Address >

The address for the account this Wallet represents.

wallet.provider Provider

The provider this wallet is connected to, which will be used for any Blockchain Methods methods. This can be null.

Note

A Wallet instance is immutable, so if you wish to change the Provider, you may use the connect method to create a new instance connected to the desired provider.

wallet.publicKey string< DataHexString< 65 > >

The uncompressed public key for this Wallet represents.

Methods

wallet.encrypt( password , [ options = {} , [ progress ] ] ) Promise< string >

Encrypt the wallet using password returning a Promise which resolves to a JSON wallet.

If progress is provided it will be called during decryption with a value between 0 and 1 indicating the progress towards completion.

Wallet Examples
// Create a wallet instance from a mnemonic... mnemonic = "announce room limb pattern dry unit scale effort smooth jazz weasel alcohol" walletMnemonic = Wallet.fromMnemonic(mnemonic) // ...or from a private key walletPrivateKey = new Wallet(walletMnemonic.privateKey) walletMnemonic.address === walletPrivateKey.address // true // The address as a Promise per the Signer API await walletMnemonic.getAddress() // '0x71CB05EE1b1F506fF321Da3dac38f25c0c9ce6E1' // A Wallet address is also available synchronously walletMnemonic.address // '0x71CB05EE1b1F506fF321Da3dac38f25c0c9ce6E1' // The internal cryptographic components walletMnemonic.privateKey // '0x1da6847600b0ee25e9ad9a52abbd786dd2502fa4005dd5af9310b7cc7a3b25db' walletMnemonic.publicKey // '0x04b9e72dfd423bcf95b3801ac93f4392be5ff22143f9980eb78b3a860c4843bfd04829ae61cdba4b3b1978ac5fc64f5cc2f4350e35a108a9c9a92a81200a60cd64' // The wallet mnemonic walletMnemonic.mnemonic // { // locale: 'en', // path: "m/44'/60'/0'/0/0", // phrase: 'announce room limb pattern dry unit scale effort smooth jazz weasel alcohol' // } // Note: A wallet created with a private key does not // have a mnemonic (the derivation prevents it) walletPrivateKey.mnemonic // null // Signing a message await walletMnemonic.signMessage("Hello World") // '0x14280e5885a19f60e536de50097e96e3738c7acae4e9e62d67272d794b8127d31c03d9cd59781d4ee31fb4e1b893bd9b020ec67dfa65cfb51e2bdadbb1de26d91c' tx = { to: "0x8ba1f109551bD432803012645Ac136ddd64DBA72", value: utils.parseEther("1.0") } // Signing a transaction await walletMnemonic.signTransaction(tx) // '0xf865808080948ba1f109551bd432803012645ac136ddd64dba72880de0b6b3a7640000801ca0918e294306d177ab7bd664f5e141436563854ebe0a3e523b9690b4922bbb52b8a01181612cec9c431c4257a79b8c9f0c980a2c49bb5a0e6ac52949163eeb565dfc' // The connect method returns a new instance of the // Wallet connected to a provider wallet = walletMnemonic.connect(provider) // Querying the network await wallet.getBalance(); // { BigNumber: "6846" } await wallet.getTransactionCount(); // 3 // Sending ether await wallet.sendTransaction(tx) // { // accessList: [], // chainId: 123456, // confirmations: 0, // data: '0x', // from: '0x46E0726Ef145d92DEA66D38797CF51901701926e', // gasLimit: { BigNumber: "21000" }, // gasPrice: null, // hash: '0x1c4913f6e06a8b48443dbe3169acb6701b558ed6d3b478723eb6b137d2418792', // maxFeePerGas: { BigNumber: "1500000014" }, // maxPriorityFeePerGas: { BigNumber: "1500000000" }, // nonce: 5, // r: '0xb58e9234bf734f5bab14634ca21e35c3fa163562930d782424e78120cfcc9b8f', // s: '0x690c4b1c3d2b6e519340b2f0f3fc80ccea47e3c2a077f9771aaa2e1d7552aa24', // to: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // type: 2, // v: 0, // value: { BigNumber: "1000000000000000000" }, // wait: [Function (anonymous)] // }

VoidSigner inherits Signer

A VoidSigner is a simple Signer which cannot sign.

It is useful as a read-only signer, when an API requires a Signer as a parameter, but it is known only read-only operations will be carried.

For example, the call operation will automatically have the provided address passed along during the execution.

new ethers.VoidSigner( address [ , provider ] ) VoidSigner

Create a new instance of a VoidSigner for address.

voidSigner.address string< Address >

The address of this VoidSigner.

VoidSigner Pre-flight Example
address = "0x8ba1f109551bD432803012645Ac136ddd64DBA72" signer = new ethers.VoidSigner(address, provider) // The DAI token contract abi = [ "function balanceOf(address) view returns (uint)", "function transfer(address, uint) returns (bool)" ] contract = new ethers.Contract("dai.tokens.ethers.eth", abi, signer) // Get the number of tokens for this account tokens = await contract.balanceOf(signer.getAddress()) // { BigNumber: "19862540059122458201631" } // // Pre-flight (check for revert) on DAI from the signer // // Note: We do not have the private key at this point, this // simply allows us to check what would happen if we // did. This can be useful to check before prompting // a request in the UI // // This will pass since the token balance is available await contract.callStatic.transfer("donations.ethers.eth", tokens) // true // This will fail since it is greater than the token balance await contract.callStatic.transfer("donations.ethers.eth", tokens.add(1)) // [Error: call revert exception; VM Exception while processing transaction: reverted with reason string "Dai/insufficient-balance" [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ]] { // address: 'dai.tokens.ethers.eth', // args: [ // 'donations.ethers.eth', // { BigNumber: "19862540059122458201632" } // ], // code: 'CALL_EXCEPTION', // data: '0x08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000184461692f696e73756666696369656e742d62616c616e63650000000000000000', // errorArgs: [ // 'Dai/insufficient-balance' // ], // errorName: 'Error', // errorSignature: 'Error(string)', // method: 'transfer(address,uint256)', // reason: 'Dai/insufficient-balance', // transaction: { // data: '0xa9059cbb000000000000000000000000643aa0a61eadcc9cc202d1915d942d35d005400c000000000000000000000000000000000000000000000434c01dc386406c8e20', // from: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // to: '0x6B175474E89094C44Da98b954EedeAC495271d0F' // } // }

ExternallyOwnedAccount

This is an interface which contains a minimal set of properties required for Externally Owned Accounts which can have certain operations performed, such as encoding as a JSON wallet.

eoa.address string< Address >

The Address of this EOA.

eoa.privateKey string< DataHexString< 32 > >

The privateKey of this EOA

eoa.mnemonic Mnemonic

Optional. The account HD mnemonic, if it has one and can be determined. Some sources do not encode the mnemonic, such as HD extended keys.

Contract Interaction

A Contract object is an abstraction of a contract (EVM bytecode) deployed on the Ethereum network. It allows for a simple way to serialize calls and transactions to an on-chain contract and deserialize their results and emitted logs.

A ContractFactory is an abstraction of a contract's bytecode and facilitates deploying a contract.

Contract
ContractFactory
Example: ERC-20 Contract

Contract

A Contract is an abstraction of code that has been deployed to the blockchain.

A Contract may be sent transactions, which will trigger its code to be run with the input of the transaction data.

Creating Instances

new ethers.Contract( address , abi , signerOrProvider )
contract.attach( addressOrName ) Contract

Returns a new instance of the Contract attached to a new address. This is useful if there are multiple similar or identical copies of a Contract on the network and you wish to interact with each of them.

contract.connect( providerOrSigner ) Contract

Returns a new instance of the Contract, but connected to providerOrSigner.

By passing in a Provider, this will return a downgraded Contract which only has read-only access (i.e. constant calls).

By passing in a Signer. this will return a Contract which will act on behalf of that signer.

Properties

contract.address string< Address >

This is the address (or ENS name) the contract was constructed with.

contract.resolvedAddress string< Address >

This is a promise that will resolve to the address the Contract object is attached to. If an Address was provided to the constructor, it will be equal to this; if an ENS name was provided, this will be the resolved address.

contract.deployTransaction TransactionResponse

If the Contract object is the result of a ContractFactory deployment, this is the transaction which was used to deploy the contract.

contract.interface Interface

This is the ABI as an Interface.

contract.provider Provider

If a provider was provided to the constructor, this is that provider. If a signer was provided that had a Provider, this is that provider.

contract.signer Signer

If a signer was provided to the constructor, this is that signer.

Methods

contract.deployed( ) Promise< Contract >
Contract.isIndexed( value ) boolean

Events

contract.queryFilter( event [ , fromBlockOrBlockHash [ , toBlock ] ) Promise< Array< Event > >

Return Events that match the event.

contract.listenerCount( [ event ] ) number

Return the number of listeners that are subscribed to event. If no event is provided, returns the total count of all events.

contract.listeners( event ) Array< Listener >

Return a list of listeners that are subscribed to event.

contract.off( event , listener ) this

Unsubscribe listener to event.

contract.on( event , listener ) this

Subscribe to event calling listener when the event occurs.

contract.once( event , listener ) this

Subscribe once to event calling listener when the event occurs.

contract.removeAllListeners( [ event ] ) this

Unsubscribe all listeners for event. If no event is provided, all events are unsubscribed.

Meta-Class

A Meta-Class is a Class which has any of its properties determined at run-time. The Contract object uses a Contract's ABI to determine what methods are available, so the following sections describe the generic ways to interact with the properties added at run-time during the Contract constructor.

Read-Only Methods (constant)

A constant method (denoted by pure or view in Solidity) is read-only and evaluates a small amount of EVM code against the current blockchain state and can be computed by asking a single node, which can return a result. It is therefore free and does not require any ether, but cannot make changes to the blockchain state..

contract.METHOD_NAME( ...args [ , overrides ] ) Promise< any >

The type of the result depends on the ABI. If the method returns a single value, it will be returned directly, otherwise a Result object will be returned with each parameter available positionally and if the parameter is named, it will also be available by its name.

For values that have a simple meaning in JavaScript, the types are fairly straightforward; strings and booleans are returned as JavaScript strings and booleans.

For numbers, if the type is in the JavaScript safe range (i.e. less than 53 bits, such as an int24 or uint48) a normal JavaScript number is used. Otherwise a BigNumber is returned.

For bytes (both fixed length and dynamic), a DataHexString is returned.

If the call reverts (or runs out of gas), a CALL_EXCEPTION will be thrown which will include:

  • error.address - the contract address
  • error.args - the arguments passed into the method
  • error.transaction - the transaction

The overrides object for a read-only method may include any of:

  • overrides.from - the msg.sender (or CALLER) to use during the execution of the code
  • overrides.value - the msg.value (or CALLVALUE) to use during the execution of the code
  • overrides.gasPrice - the price to pay per gas (theoretically); since there is no transaction, there is not going to be any fee charged, but the EVM still requires a value to report to tx.gasprice (or GASPRICE); most developers will not require this
  • overrides.gasLimit - the amount of gas (theoretically) to allow a node to use during the execution of the code; since there is no transaction, there is not going to be any fee charged, but the EVM still processes gas metering so calls like gasleft (or GAS) report meaningful values
  • overrides.blockTag - a block tag to simulate the execution at, which can be used for hypothetical historic analysis; note that many backends do not support this, or may require paid plans to access as the node database storage and processing requirements are much higher

contract.functions.METHOD_NAME( ...args [ , overrides ] ) Promise< Result >

The result will always be a Result, even if there is only a single return value type.

This simplifies frameworks which wish to use the Contract object, since they do not need to inspect the return types to unwrap simplified functions.

Another use for this method is for error recovery. For example, if a function result is an invalid UTF-8 string, the normal call using the above meta-class function will throw an exception. This allows using the Result access error to access the low-level bytes and reason for the error allowing an alternate UTF-8 error strategy to be used.

Most developers should not require this.

The overrides are identical to the read-only operations above.

Write Methods (non-constant)

A non-constant method requires a transaction to be signed and requires payment in the form of a fee to be paid to a miner. This transaction will be verified by every node on the entire network as well by the miner who will compute the new state of the blockchain after executing it against the current state.

It cannot return a result. If a result is required, it should be logged using a Solidity event (or EVM log), which can then be queried from the transaction receipt.

contract.METHOD_NAME( ...args [ , overrides ] ) Promise< TransactionResponse >

Returns a TransactionResponse for the transaction after it is sent to the network. This requires the Contract has a signer.

The overrides object for write methods may include any of:

  • overrides.gasPrice - the price to pay per gas
  • overrides.gasLimit - the limit on the amount of gas to allow the transaction to consume; any unused gas is returned at the gasPrice
  • overrides.value - the amount of ether (in wei) to forward with the call
  • overrides.nonce - the nonce to use for the Signer

If the wait() method on the returned TransactionResponse is called, there will be additional properties on the receipt:

  • receipt.events - an array of the logs, with additional properties (if the ABI included a description for the events)
  • receipt.events[n].args - the parsed arguments
  • receipt.events[n].decode - a method that can be used to parse the log topics and data (this was used to compute args)
  • receipt.events[n].event - the name of the event
  • receipt.events[n].eventSignature - the full signature of the event
  • receipt.removeListener() - a method to remove the listener that trigger this event
  • receipt.getBlock() - a method to return the Block this event occurred in
  • receipt.getTransaction() - a method to return the Transaction this event occurred in
  • receipt.getTransactionReceipt() - a method to return the Transaction Receipt this event occurred in

Write Methods Analysis

There are several options to analyze properties and results of a write method without actually executing it.

contract.estimateGas.METHOD_NAME( ...args [ , overrides ] ) Promise< BigNumber >

Returns the estimate units of gas that would be required to execute the METHOD_NAME with args and overrides.

The overrides are identical to the overrides above for read-only or write methods, depending on the type of call of METHOD_NAME.

contract.populateTransaction.METHOD_NAME( ...args [ , overrides ] ) Promise< UnsignedTx >

Returns an UnsignedTransaction which represents the transaction that would need to be signed and submitted to the network to execute METHOD_NAME with args and overrides.

The overrides are identical to the overrides above for read-only or write methods, depending on the type of call of METHOD_NAME.

contract.callStatic.METHOD_NAME( ...args [ , overrides ] ) Promise< any >

Rather than executing the state-change of a transaction, it is possible to ask a node to pretend that a call is not state-changing and return the result.

This does not actually change any state, but is free. This in some cases can be used to determine if a transaction will fail or succeed.

This otherwise functions the same as a Read-Only Method.

The overrides are identical to the read-only operations above.

Event Filters

An event filter is made up of topics, which are values logged in a Bloom Filter, allowing efficient searching for entries which match a filter.

contract.filters.EVENT_NAME( ...args ) Filter

Return a filter for EVENT_NAME, optionally filtering by additional constraints.

Only indexed event parameters may be filtered. If a parameter is null (or not provided) then any value in that field matches.

ContractFactory

To deploy a Contract, additional information is needed that is not available on a Contract object itself.

Mainly, the bytecode (more specifically the initcode) of a contract is required.

The Contract Factory sends a special type of transaction, an initcode transaction (i.e. the to field is null, and the data field is the initcode) where the initcode will be evaluated and the result becomes the new code to be deployed as a new contract.

Creating Instances

new ethers.ContractFactory( interface , bytecode [ , signer ] )

Creates a new instance of a ContractFactory for the contract described by the interface and bytecode initcode.

ContractFactory.fromSolidity( compilerOutput [ , signer ] ) ContractFactory

Consumes the output of the Solidity compiler, extracting the ABI and bytecode from it, allowing for the various formats the solc compiler has emitted over its life.

contractFactory.connect( signer ) ContractFactory

Returns a new instance of the ContractFactory with the same interface and bytecode, but with a different signer.

Properties

contractFactory.interface Interface

The Contract interface.

contractFactory.bytecode string< DataHexString >

The bytecode (i.e. initcode) that this ContractFactory will use to deploy the Contract.

contractFactory.signer Signer

The Signer (if any) this ContractFactory will use to deploy instances of the Contract to the Blockchain.

Methods

contractFactory.attach( address ) Contract

Return an instance of a Contract attached to address. This is the same as using the Contract constructor with address and this the interface and signerOrProvider passed in when creating the ContractFactory.

contractFactory.getDeployTransaction( ...args [ , overrides ] ) UnsignedTransaction

Returns the unsigned transaction which would deploy this Contract with args passed to the Contract's constructor.

If the optional overrides is specified, they can be used to override the endowment value, transaction nonce, gasLimit or gasPrice.

contractFactory.deploy( ...args [ , overrides ] ) Promise< Contract >

Uses the signer to deploy the Contract with args passed into the constructor and returns a Contract which is attached to the address where this contract will be deployed once the transaction is mined.

The transaction can be found at contract.deployTransaction, and no interactions should be made until the transaction is mined.

If the optional overrides is specified, they can be used to override the endowment value, transaction nonce, gasLimit or gasPrice.

Deploying a Contract
// If your contract constructor requires parameters, the ABI // must include the constructor const abi = [ "constructor(address owner, uint256 initialValue)", "function value() view returns (uint)" ]; // The factory we use for deploying contracts factory = new ContractFactory(abi, bytecode, signer) // Deploy an instance of the contract contract = await factory.deploy("ricmoo.eth", 42); // The address is available immediately, but the contract // is NOT deployed yet contract.address // '0x00777F1b1439BDc7Ad1d4905A38Ec9f5400e0e26' // The transaction that the signer sent to deploy contract.deployTransaction // { // accessList: [], // chainId: 123456, // confirmations: 0, // data: '0x608060405234801561001057600080fd5b5060405161012e38038061012e8339818101604052604081101561003357600080fd5b81019080805190602001909291908051906020019092919050505081600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508060008190555050506088806100a66000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80633fa4f24514602d575b600080fd5b60336049565b6040518082815260200191505060405180910390f35b6000805490509056fea2646970667358221220926465385af0e8706644e1ff3db7161af699dc063beaadd55405f2ccd6478d7564736f6c634300070400330000000000000000000000005555763613a12d8f3e73be831dff8598089d3dca000000000000000000000000000000000000000000000000000000000000002a', // from: '0x46E0726Ef145d92DEA66D38797CF51901701926e', // gasLimit: { BigNumber: "129862" }, // gasPrice: null, // hash: '0x293aeb5aaa782c45d56aa13e67c8dabe5a34726c68539302401c15a1699074fa', // maxFeePerGas: { BigNumber: "1500000014" }, // maxPriorityFeePerGas: { BigNumber: "1500000000" }, // nonce: 0, // r: '0x6708733f3523a5efc1a5bee891a3020c1d0a622f03ccaa437763241550d93ac7', // s: '0x3065f4437666753b4216bf8518e5c6221d0cf8f86b57857ac268c128a5c2d53c', // to: null, // type: 2, // v: 0, // value: { BigNumber: "0" }, // wait: [Function (anonymous)] // } // Wait until the transaction is mined (i.e. contract is deployed) // - returns the receipt // - throws on failure (the reciept is on the error) await contract.deployTransaction.wait() // { // blockHash: '0x14b2744b8a923827c35827aa47c99942be21c94da4fe2e03451a662e3bd0dbe6', // blockNumber: 60328, // byzantium: true, // confirmations: 1, // contractAddress: '0x00777F1b1439BDc7Ad1d4905A38Ec9f5400e0e26', // cumulativeGasUsed: { BigNumber: "129862" }, // effectiveGasPrice: { BigNumber: "1500000007" }, // events: [], // from: '0x46E0726Ef145d92DEA66D38797CF51901701926e', // gasUsed: { BigNumber: "129862" }, // logs: [], // logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', // status: 1, // to: null, // transactionHash: '0x293aeb5aaa782c45d56aa13e67c8dabe5a34726c68539302401c15a1699074fa', // transactionIndex: 0, // type: 2 // } // Now the contract is safe to interact with await contract.value() // { BigNumber: "42" }

Example: ERC-20 Contract

The concept of Meta-Classes is somewhat confusing, so we will go over a short example.

A meta-class is a class which is defined at run-time. A Contract is specified by an Application Binary Interface (ABI), which describes the methods and events it has. This description is passed to the Contract object at run-time, and it creates a new Class, adding all the methods defined in the ABI at run-time.

Deploying a Contract

Most often, any contract you will need to interact with will already be deployed to the blockchain, but for this example will will first deploy the contract.

new ethers.ContractFactory( abi , bytecode , signer )

Create a new ContractFactory which can deploy a contract to the blockchain.

const bytecode = "0x608060405234801561001057600080fd5b506040516103bc3803806103bc83398101604081905261002f9161007c565b60405181815233906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a333600090815260208190526040902055610094565b60006020828403121561008d578081fd5b5051919050565b610319806100a36000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c8063313ce5671461005157806370a082311461006557806395d89b411461009c578063a9059cbb146100c5575b600080fd5b604051601281526020015b60405180910390f35b61008e610073366004610201565b6001600160a01b031660009081526020819052604090205490565b60405190815260200161005c565b604080518082018252600781526626bcaa37b5b2b760c91b6020820152905161005c919061024b565b6100d86100d3366004610222565b6100e8565b604051901515815260200161005c565b3360009081526020819052604081205482111561014b5760405162461bcd60e51b815260206004820152601a60248201527f696e73756666696369656e7420746f6b656e2062616c616e6365000000000000604482015260640160405180910390fd5b336000908152602081905260408120805484929061016a9084906102b6565b90915550506001600160a01b0383166000908152602081905260408120805484929061019790849061029e565b90915550506040518281526001600160a01b0384169033907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a350600192915050565b80356001600160a01b03811681146101fc57600080fd5b919050565b600060208284031215610212578081fd5b61021b826101e5565b9392505050565b60008060408385031215610234578081fd5b61023d836101e5565b946020939093013593505050565b6000602080835283518082850152825b818110156102775785810183015185820160400152820161025b565b818111156102885783604083870101525b50601f01601f1916929092016040019392505050565b600082198211156102b1576102b16102cd565b500190565b6000828210156102c8576102c86102cd565b500390565b634e487b7160e01b600052601160045260246000fdfea2646970667358221220d80384ce584e101c5b92e4ee9b7871262285070dbcd2d71f99601f0f4fcecd2364736f6c63430008040033"; // A Human-Readable ABI; we only need to specify relevant fragments, // in the case of deployment this means the constructor const abi = [ "constructor(uint totalSupply)" ]; const factory = new ethers.ContractFactory(abi, bytecode, signer) // Deploy, setting total supply to 100 tokens (assigned to the deployer) const contract = await factory.deploy(parseUnits("100")); // The contract is not currentl live on the network yet, however // its address is ready for us contract.address // '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674' // Wait until the contract has been deployed before interacting // with it; returns the receipt for the deployemnt transaction await contract.deployTransaction.wait(); // { // blockHash: '0xe0628e513348591aaf653ff88ac043d9da2a5755cf12060be5532b2ffea4eab3', // blockNumber: 60329, // byzantium: true, // confirmations: 1, // contractAddress: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // cumulativeGasUsed: { BigNumber: "250842" }, // effectiveGasPrice: { BigNumber: "1500000007" }, // events: [ // { // address: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // blockHash: '0xe0628e513348591aaf653ff88ac043d9da2a5755cf12060be5532b2ffea4eab3', // blockNumber: 60329, // data: '0x0000000000000000000000000000000000000000000000056bc75e2d63100000', // getBlock: [Function (anonymous)], // getTransaction: [Function (anonymous)], // getTransactionReceipt: [Function (anonymous)], // logIndex: 0, // removeListener: [Function (anonymous)], // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x0000000000000000000000000000000000000000000000000000000000000000', // '0x00000000000000000000000046e0726ef145d92dea66d38797cf51901701926e' // ], // transactionHash: '0xa3b258b2a091ef197ccc7ec269e3b4b3eaa421041c5a6db31ee751ebc403bccb', // transactionIndex: 0 // } // ], // from: '0x46E0726Ef145d92DEA66D38797CF51901701926e', // gasUsed: { BigNumber: "250842" }, // logs: [ // { // address: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // blockHash: '0xe0628e513348591aaf653ff88ac043d9da2a5755cf12060be5532b2ffea4eab3', // blockNumber: 60329, // data: '0x0000000000000000000000000000000000000000000000056bc75e2d63100000', // logIndex: 0, // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x0000000000000000000000000000000000000000000000000000000000000000', // '0x00000000000000000000000046e0726ef145d92dea66d38797cf51901701926e' // ], // transactionHash: '0xa3b258b2a091ef197ccc7ec269e3b4b3eaa421041c5a6db31ee751ebc403bccb', // transactionIndex: 0 // } // ], // logsBloom: '0x00000000000000000000000000000004000000000000000000000000000040000000000000000000000000000000000000000000000000000000020000000000000000000000000000000008000000000000001000000000000000000000000000000000020000000000000000000800000000000000000000000010000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010002000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000', // status: 1, // to: null, // transactionHash: '0xa3b258b2a091ef197ccc7ec269e3b4b3eaa421041c5a6db31ee751ebc403bccb', // transactionIndex: 0, // type: 2 // }

Connecting to a Contract

ERC20Contract inherits Contract

new ethers.Contract( address , abi , providerOrSigner )

Creating a new instance of a Contract connects to an existing contract by specifying its address on the blockchain, its abi (used to populate the class' methods) a providerOrSigner.

If a Provider is given, the contract has only read-only access, while a Signer offers access to state manipulating methods.

// A Human-Readable ABI; for interacting with the contract, we // must include any fragment we wish to use const abi = [ // Read-Only Functions "function balanceOf(address owner) view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)", // Authenticated Functions "function transfer(address to, uint amount) returns (bool)", // Events "event Transfer(address indexed from, address indexed to, uint amount)" ]; // This can be an address or an ENS name const address = "0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674"; // Read-Only; By connecting to a Provider, allows: // - Any constant function // - Querying Filters // - Populating Unsigned Transactions for non-constant methods // - Estimating Gas for non-constant (as an anonymous sender) // - Static Calling non-constant methods (as anonymous sender) const erc20 = new ethers.Contract(address, abi, provider); // Read-Write; By connecting to a Signer, allows: // - Everything from Read-Only (except as Signer, not anonymous) // - Sending transactions for non-constant functions const erc20_rw = new ethers.Contract(address, abi, signer);

Properties(inheritted from Contract)

erc20.address string< Address >

This is the address (or ENS name) the contract was constructed with.

erc20.resolvedAddress string< Address >

This is a promise that will resolve to the address the Contract object is attached to. If an Address was provided to the constructor, it will be equal to this; if an ENS name was provided, this will be the resolved address.

erc20.deployTransaction TransactionResponse

If the Contract object is the result of a ContractFactory deployment, this is the transaction which was used to deploy the contract.

erc20.interface Interface

This is the ABI as an Interface.

erc20.provider Provider

If a provider was provided to the constructor, this is that provider. If a signer was provided that had a Provider, this is that provider.

erc20.signer Signer

If a signer was provided to the constructor, this is that signer.

Methods(inheritted from Contract)

erc20.attach( addressOrName ) Contract

Returns a new instance of the Contract attached to a new address. This is useful if there are multiple similar or identical copies of a Contract on the network and you wish to interact with each of them.

erc20.connect( providerOrSigner ) Contract

Returns a new instance of the Contract, but connected to providerOrSigner.

By passing in a Provider, this will return a downgraded Contract which only has read-only access (i.e. constant calls).

By passing in a Signer. this will return a Contract which will act on behalf of that signer.

erc20.deployed( ) Promise< Contract >
Contract.isIndexed( value ) boolean

Events(inheritted from Contract)

See Meta-Class Filters for examples using events.

erc20.queryFilter( event [ , fromBlockOrBlockHash [ , toBlock ] ) Promise< Array< Event > >

Return Events that match the event.

erc20.listenerCount( [ event ] ) number

Return the number of listeners that are subscribed to event. If no event is provided, returns the total count of all events.

erc20.listeners( event ) Array< Listener >

Return a list of listeners that are subscribed to event.

erc20.off( event , listener ) this

Unsubscribe listener to event.

erc20.on( event , listener ) this

Subscribe to event calling listener when the event occurs.

erc20.once( event , listener ) this

Subscribe once to event calling listener when the event occurs.

erc20.removeAllListeners( [ event ] ) this

Unsubscribe all listeners for event. If no event is provided, all events are unsubscribed.

Meta-Class Methods(added at Runtime)

Since the Contract is a Meta-Class, the methods available here depend on the ABI which was passed into the Contract.

erc20.decimals( [ overrides ] ) Promise< number >

Returns the number of decimal places used by this ERC-20 token. This can be used with parseUnits when taking input from the user or [formatUnits](utils-formatunits] when displaying the token amounts in the UI.

await erc20.decimals(); // 18
erc20.balanceOf( owner [ , overrides ] ) Promise< BigNumber >

Returns the balance of owner for this ERC-20 token.

await erc20.balanceOf(signer.getAddress()) // { BigNumber: "100000000000000000000" }
erc20.symbol( [ overrides ] ) Promise< string >

Returns the symbol of the token.

await erc20.symbol(); // 'MyToken'
erc20_rw.transfer( target , amount [ , overrides ] ) Promise< TransactionResponse >

Transfers amount tokens to target from the current signer. The return value (a boolean) is inaccessible during a write operation using a transaction. Other techniques (such as events) are required if this value is required. On-chain contracts calling the transfer function have access to this result, which is why it is possible.

// Before... formatUnits(await erc20_rw.balanceOf(signer.getAddress())); // '100.0' // Transfer 1.23 tokens to the ENS name "ricmoo.eth" tx = await erc20_rw.transfer("ricmoo.eth", parseUnits("1.23")); // { // accessList: [], // chainId: 123456, // confirmations: 0, // data: '0xa9059cbb0000000000000000000000005555763613a12d8f3e73be831dff8598089d3dca0000000000000000000000000000000000000000000000001111d67bb1bb0000', // from: '0x46E0726Ef145d92DEA66D38797CF51901701926e', // gasLimit: { BigNumber: "51558" }, // gasPrice: null, // hash: '0xafdc1f7ec14e2e05a39826c134c9157e0011fc784aef623df3fdf9b9d29f3ac8', // maxFeePerGas: { BigNumber: "1500000014" }, // maxPriorityFeePerGas: { BigNumber: "1500000000" }, // nonce: 2, // r: '0xd5f1784f0eeb12ef38eb38f1040232f61cc52e017b53ef8685a7a07e47f3144b', // s: '0x5a63103e4b49eae8d372f474857a58612c53fa996b331b9c98611df14191f529', // to: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // type: 2, // v: 1, // value: { BigNumber: "0" }, // wait: [Function (anonymous)] // } // Wait for the transaction to be mined... await tx.wait(); // { // blockHash: '0x9340a9c7efafbb4ad9a6ebda62e3311ec5fc40ddcc733632938a988c8c62b885', // blockNumber: 60330, // byzantium: true, // confirmations: 1, // contractAddress: null, // cumulativeGasUsed: { BigNumber: "51558" }, // effectiveGasPrice: { BigNumber: "1500000007" }, // events: [ // { // address: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // args: [ // '0x46E0726Ef145d92DEA66D38797CF51901701926e', // '0x5555763613a12D8F3e73be831DFf8598089d3dCa', // { BigNumber: "1230000000000000000" }, // amount: { BigNumber: "1230000000000000000" }, // from: '0x46E0726Ef145d92DEA66D38797CF51901701926e', // to: '0x5555763613a12D8F3e73be831DFf8598089d3dCa' // ], // blockHash: '0x9340a9c7efafbb4ad9a6ebda62e3311ec5fc40ddcc733632938a988c8c62b885', // blockNumber: 60330, // data: '0x0000000000000000000000000000000000000000000000001111d67bb1bb0000', // decode: [Function (anonymous)], // event: 'Transfer', // eventSignature: 'Transfer(address,address,uint256)', // getBlock: [Function (anonymous)], // getTransaction: [Function (anonymous)], // getTransactionReceipt: [Function (anonymous)], // logIndex: 0, // removeListener: [Function (anonymous)], // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x00000000000000000000000046e0726ef145d92dea66d38797cf51901701926e', // '0x0000000000000000000000005555763613a12d8f3e73be831dff8598089d3dca' // ], // transactionHash: '0xafdc1f7ec14e2e05a39826c134c9157e0011fc784aef623df3fdf9b9d29f3ac8', // transactionIndex: 0 // } // ], // from: '0x46E0726Ef145d92DEA66D38797CF51901701926e', // gasUsed: { BigNumber: "51558" }, // logs: [ // { // address: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // blockHash: '0x9340a9c7efafbb4ad9a6ebda62e3311ec5fc40ddcc733632938a988c8c62b885', // blockNumber: 60330, // data: '0x0000000000000000000000000000000000000000000000001111d67bb1bb0000', // logIndex: 0, // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x00000000000000000000000046e0726ef145d92dea66d38797cf51901701926e', // '0x0000000000000000000000005555763613a12d8f3e73be831dff8598089d3dca' // ], // transactionHash: '0xafdc1f7ec14e2e05a39826c134c9157e0011fc784aef623df3fdf9b9d29f3ac8', // transactionIndex: 0 // } // ], // logsBloom: '0x00000000000000000800000000000004000000000000000000000000000040000000000000000000000000000000000000000000000000000000020000000000000000000000000000000008000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010002000000000000000000000000000000000000000000000000000000000000000000000001000000000200000000000000000000000000000000000000', // status: 1, // to: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // transactionHash: '0xafdc1f7ec14e2e05a39826c134c9157e0011fc784aef623df3fdf9b9d29f3ac8', // transactionIndex: 0, // type: 2 // } // After! formatUnits(await erc20_rw.balanceOf(signer.getAddress())); // '98.77' formatUnits(await erc20_rw.balanceOf("ricmoo.eth")); // '1.23'
erc20.callStatic.transfer( target , amount [ , overrides ] ) Promise< boolean >

Performs a dry-run of transferring amount tokens to target from the current signer, without actually signing or sending a transaction.

This can be used to preflight check that a transaction will be successful.

// The signer has enough tokens to send, so true is returned await erc20_rw.callStatic.transfer("ricmoo.eth", parseUnits("1.23")); // true // A random address does not have enough tokens to // send, in which case the contract throws an error erc20_random = erc20_rw.connect(randomWallet); await erc20_random.callStatic.transfer("ricmoo.eth", parseUnits("1.23")); // [Error: call revert exception; VM Exception while processing transaction: reverted with reason string "insufficient token balance" [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ]] { // address: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // args: [ // 'ricmoo.eth', // { BigNumber: "1230000000000000000" } // ], // code: 'CALL_EXCEPTION', // data: '0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001a696e73756666696369656e7420746f6b656e2062616c616e6365000000000000', // errorArgs: [ // 'insufficient token balance' // ], // errorName: 'Error', // errorSignature: 'Error(string)', // method: 'transfer(address,uint256)', // reason: 'insufficient token balance', // transaction: { // data: '0xa9059cbb0000000000000000000000005555763613a12d8f3e73be831dff8598089d3dca0000000000000000000000000000000000000000000000001111d67bb1bb0000', // from: '0x8b6b9C2CE3468B30Fde7Ca10e54aC5F0bA2456e0', // to: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674' // } // }
erc20.estimateGas.transfer( target , amount [ , overrides ] ) Promise< BigNumber >

Returns an estimate for how many units of gas would be required to transfer amount tokens to target.

await erc20_rw.estimateGas.transfer("ricmoo.eth", parseUnits("1.23")); // { BigNumber: "34458" }
erc20.populateTransaction.transfer( target , amount [ , overrides ] ) Promise< UnsignedTx >

Returns an UnsignedTransaction which could be signed and submitted to the network to transaction amount tokens to target.

await erc20_rw.populateTransaction.transfer("ricmoo.eth", parseUnits("1.23")); // { // data: '0xa9059cbb0000000000000000000000005555763613a12d8f3e73be831dff8598089d3dca0000000000000000000000000000000000000000000000001111d67bb1bb0000', // from: '0x46E0726Ef145d92DEA66D38797CF51901701926e', // to: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674' // }
Note on Estimating and Static Calling

When you perform a static call, the current state is taken into account as best as Ethereum can determine. There are many cases where this can provide false positives and false negatives. The eventually consistent model of the blockchain also means there are certain consistency modes that cannot be known until an actual transaction is attempted.

Meta-Class Filters(added at Runtime)

Since the Contract is a Meta-Class, the methods available here depend on the ABI which was passed into the Contract.

erc20.filters.Transfer( [ fromAddress [ , toAddress ] ] ) Filter

Returns a new Filter which can be used to query or to subscribe/unsubscribe to events.

If fromAddress is null or not provided, then any from address matches. If toAddress is null or not provided, then any to address matches.

query filter *from* events
filterFrom = erc20.filters.Transfer(signer.address); // { // address: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x00000000000000000000000046e0726ef145d92dea66d38797cf51901701926e' // ] // } // Search for transfers *from* me in the last 10 blocks logsFrom = await erc20.queryFilter(filterFrom, -10, "latest"); // [ // { // address: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // args: [ // '0x46E0726Ef145d92DEA66D38797CF51901701926e', // '0x5555763613a12D8F3e73be831DFf8598089d3dCa', // { BigNumber: "1230000000000000000" }, // amount: { BigNumber: "1230000000000000000" }, // from: '0x46E0726Ef145d92DEA66D38797CF51901701926e', // to: '0x5555763613a12D8F3e73be831DFf8598089d3dCa' // ], // blockHash: '0x9340a9c7efafbb4ad9a6ebda62e3311ec5fc40ddcc733632938a988c8c62b885', // blockNumber: 60330, // data: '0x0000000000000000000000000000000000000000000000001111d67bb1bb0000', // decode: [Function (anonymous)], // event: 'Transfer', // eventSignature: 'Transfer(address,address,uint256)', // getBlock: [Function (anonymous)], // getTransaction: [Function (anonymous)], // getTransactionReceipt: [Function (anonymous)], // logIndex: 0, // removeListener: [Function (anonymous)], // removed: false, // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x00000000000000000000000046e0726ef145d92dea66d38797cf51901701926e', // '0x0000000000000000000000005555763613a12d8f3e73be831dff8598089d3dca' // ], // transactionHash: '0xafdc1f7ec14e2e05a39826c134c9157e0011fc784aef623df3fdf9b9d29f3ac8', // transactionIndex: 0 // } // ] // Note that the args providees the details of the event, each // parameters is available positionally, and since our ABI // included parameter names also by name logsFrom[0].args // [ // '0x46E0726Ef145d92DEA66D38797CF51901701926e', // '0x5555763613a12D8F3e73be831DFf8598089d3dCa', // { BigNumber: "1230000000000000000" }, // amount: { BigNumber: "1230000000000000000" }, // from: '0x46E0726Ef145d92DEA66D38797CF51901701926e', // to: '0x5555763613a12D8F3e73be831DFf8598089d3dCa' // ]
query filter with *to* events
filterTo = erc20.filters.Transfer(null, signer.address); // { // address: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // null, // '0x00000000000000000000000046e0726ef145d92dea66d38797cf51901701926e' // ] // } // Search for transfers *to* me in the last 10 blocks // Note: the contract transferred totalSupply tokens to us // when it was deployed in its constructor logsTo = await erc20.queryFilter(filterTo, -10, "latest"); // [ // { // address: '0x70ff5c5B1Ad0533eAA5489e0D5Ea01485d530674', // args: [ // '0x0000000000000000000000000000000000000000', // '0x46E0726Ef145d92DEA66D38797CF51901701926e', // { BigNumber: "100000000000000000000" }, // amount: { BigNumber: "100000000000000000000" }, // from: '0x0000000000000000000000000000000000000000', // to: '0x46E0726Ef145d92DEA66D38797CF51901701926e' // ], // blockHash: '0xe0628e513348591aaf653ff88ac043d9da2a5755cf12060be5532b2ffea4eab3', // blockNumber: 60329, // data: '0x0000000000000000000000000000000000000000000000056bc75e2d63100000', // decode: [Function (anonymous)], // event: 'Transfer', // eventSignature: 'Transfer(address,address,uint256)', // getBlock: [Function (anonymous)], // getTransaction: [Function (anonymous)], // getTransactionReceipt: [Function (anonymous)], // logIndex: 0, // removeListener: [Function (anonymous)], // removed: false, // topics: [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x0000000000000000000000000000000000000000000000000000000000000000', // '0x00000000000000000000000046e0726ef145d92dea66d38797cf51901701926e' // ], // transactionHash: '0xa3b258b2a091ef197ccc7ec269e3b4b3eaa421041c5a6db31ee751ebc403bccb', // transactionIndex: 0 // } // ] // Note that the args providees the details of the event, each // parameters is available positionally, and since our ABI // included parameter names also by name logsTo[0].args // [ // '0x0000000000000000000000000000000000000000', // '0x46E0726Ef145d92DEA66D38797CF51901701926e', // { BigNumber: "100000000000000000000" }, // amount: { BigNumber: "100000000000000000000" }, // from: '0x0000000000000000000000000000000000000000', // to: '0x46E0726Ef145d92DEA66D38797CF51901701926e' // ]
listen for events
// Listen to incoming events from signer: erc20.on(filterFrom, (from, to, amount, event) => { // The `from` will always be the signer address }); // Listen to incoming events to signer: erc20.on(filterTo, (from, to, amount, event) => { // The `to` will always be the signer address }); // Listen to all Transfer events: erc20.on("Transfer", (from, to, amount, event) => { // ... });

Utilities

These utilities are used extensively within the library, but are also quite useful for application developers.

Application Binary Interface
Addresses
BigNumber
Byte Manipulation
Constants
Display Logic and Input
Encoding Utilities
FixedNumber
Hashing Algorithms
HD Wallet
Logging
Property Utilities
Signing Key
Strings
Transactions
Web Utilities
Wordlists

Application Binary Interface

An Application Binary Interface (ABI) is a collection of Fragments which specify how to interact with various components of a Contract.

An Interface helps organize Fragments by type as well as provides the functionality required to encode, decode and work with each component.

Most developers will not require this low-level access to encoding and decoding the binary data on the network and will most likely use a Contract which provides a more convenient interface. Some framework, tool developers or developers using advanced techniques may find these classes and utilities useful.

AbiCoder
ABI Formats
Fragments
Interface

AbiCoder

The AbiCoder is a collection of Coders which can be used to encode and decode the binary data formats used to interoperate between the EVM and higher level libraries.

Most developers will never need to use this class directly, since the Interface class greatly simplifies these operations.

Creating Instance

For the most part, there should never be a need to manually create an instance of an AbiCoder, since one is created with the default coercion function when the library is loaded which can be used universally.

This is likely only needed by those with specific needs to override how values are coerced after they are decoded from their binary format.

new ethers.utils.AbiCoder( [ coerceFunc ] )

Create a new AbiCoder instance, which will call the coerceFunc on every decode, where the result of the call will be used in the Result.

The function signature is `(type, value)`, where the type is the string describing the type and the value is the processed value from the underlying Coder.

If the callback throws, the Result will contain a property that when accessed will throw, allowing for higher level libraries to recover from data errors.

ethers.utils.defaultAbiCoder AbiCoder

An AbiCoder created when the library is imported which is used by the Interface.

Coding Methods

abiCoder.encode( types , values ) string< DataHexString >

Encode the array values according to the array of types, each of which may be a string or a ParamType.

// Encoding simple types abiCoder.encode([ "uint", "string" ], [ 1234, "Hello World" ]); // '0x00000000000000000000000000000000000000000000000000000000000004d20000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000' // Encoding with arrays types abiCoder.encode([ "uint[]", "string" ], [ [ 1234, 5678 ] , "Hello World" ]); // '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000004d2000000000000000000000000000000000000000000000000000000000000162e000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000' // Encoding complex structs (using positional properties) abiCoder.encode( [ "uint", "tuple(uint256, string)" ], [ 1234, [ 5678, "Hello World" ] ] ); // '0x00000000000000000000000000000000000000000000000000000000000004d20000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000162e0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000' // Encoding complex structs (using keyword properties) abiCoder.encode( [ "uint a", "tuple(uint256 b, string c) d" ], [ 1234, { b: 5678, c: "Hello World" } ] ); // '0x00000000000000000000000000000000000000000000000000000000000004d20000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000162e0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000'
abiCoder.decode( types , data ) Result

Decode the data according to the array of types, each of which may be a string or ParamType.

// Decoding simple types data = "0x00000000000000000000000000000000000000000000000000000000000004d20000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000"; abiCoder.decode([ "uint", "string" ], data); // [ // { BigNumber: "1234" }, // 'Hello World' // ] // Decoding with arrays types data = "0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000004d2000000000000000000000000000000000000000000000000000000000000162e000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000"; abiCoder.decode([ "uint[]", "string" ], data); // [ // [ // { BigNumber: "1234" }, // { BigNumber: "5678" } // ], // 'Hello World' // ] // Decoding complex structs; unnamed parameters allows ONLY // positional access to values data = "0x00000000000000000000000000000000000000000000000000000000000004d20000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000162e0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000"; abiCoder.decode([ "uint", "tuple(uint256, string)" ], data); // [ // { BigNumber: "1234" }, // [ // { BigNumber: "5678" }, // 'Hello World' // ] // ] // Decoding complex structs; named parameters allows positional // or keyword access to values abiCoder.decode([ "uint a", "tuple(uint256 b, string c) d" ], data); // [ // { BigNumber: "1234" }, // [ // { BigNumber: "5678" }, // 'Hello World', // b: { BigNumber: "5678" }, // c: 'Hello World' // ], // a: { BigNumber: "1234" }, // d: [ // { BigNumber: "5678" }, // 'Hello World', // b: { BigNumber: "5678" }, // c: 'Hello World' // ] // ]

ABI Formats

There are several formats available to specify an ABI for a Smart Contract, which specifies to the under-lying library what methods, events and errors exist so that encoding and decoding the data from and to the network can be handled by the library.

The supports ABI types are:

Human-Readable ABI

The Human-Readable ABI was introduced early by ethers, which allows for a Solidity signatures to be used to describe each method, event and error.

It is important to note that a Solidity signature fully describes all the properties the ABI requires:

This allows for a simple format which is both machine-readable (since the parser is a machine) and human-readable (at least developer-readable), as well as simple for humans to type and inline into code, which improves code readability. The Human-Readable ABI is also considerably smaller, which helps reduce code size.

A Human-Readable ABI is simple an array of strings, where each string is the Solidity signature.

Signatures may be minimally specified (i.e. names of inputs and outputs may be omitted) or fully specified (i.e. with all property names) and whitespace is ignored.

Several modifiers available in Solidity are dropped internally, as they are not required for the ABI and used old by Solidity's semantic checking system, such as input parameter data location like "calldata" and "memory". As such, they can be safely dropped in the ABI as well.

Human-Readable ABI Example
const humanReadableAbi = [ // Simple types "constructor(string symbol, string name)", "function transferFrom(address from, address to, uint value)", "function balanceOf(address owner) view returns (uint balance)", "event Transfer(address indexed from, address indexed to, address value)", "error InsufficientBalance(account owner, uint balance)", // Some examples with the struct type, we use the tuple keyword: // (note: the tuple keyword is optional, simply using additional // parentheses accomplishes the same thing) // struct Person { // string name; // uint16 age; // } "function addPerson(tuple(string name, uint16 age) person)", "function addPeople(tuple(string name, uint16 age)[] person)", "function getPerson(uint id) view returns (tuple(string name, uint16 age))", "event PersonAdded(uint indexed id, tuple(string name, uint16 age) person)" ];

Solidity JSON ABI

The Solidity JSON ABI is a standard format that many tools export, including the Solidity compiler. For the full specification, see the Solidity compiler documentation.

Various versions include slightly different keys and values. For example, early compilers included only a boolean "constant" to indicate mutability, while newer versions include a string "mutabilityState", which encompasses several older properties.

When creating an instance of a Fragment using a JSON ABI, it will automatically infer all legacy properties for new-age ABIs and for legacy ABIs will infer the new-age properties. All properties will be populated, so it will match the equivalent created using a Human-Readable ABI fragment.

The same ABI as JSON ABI
const jsonAbi = `[ { "type": "constructor", "payable": false, "inputs": [ { "type": "string", "name": "symbol" }, { "type": "string", "name": "name" } ] }, { "type": "function", "name": "transferFrom", "constant": false, "payable": false, "inputs": [ { "type": "address", "name": "from" }, { "type": "address", "name": "to" }, { "type": "uint256", "name": "value" } ], "outputs": [ ] }, { "type": "function", "name": "balanceOf", "constant":true, "stateMutability": "view", "payable":false, "inputs": [ { "type": "address", "name": "owner"} ], "outputs": [ { "type": "uint256"} ] }, { "type": "event", "anonymous": false, "name": "Transfer", "inputs": [ { "type": "address", "name": "from", "indexed":true}, { "type": "address", "name": "to", "indexed":true}, { "type": "address", "name": "value"} ] }, { "type": "error", "name": "InsufficientBalance", "inputs": [ { "type": "account", "name": "owner"}, { "type": "uint256", "name": "balance"} ] }, { "type": "function", "name": "addPerson", "constant": false, "payable": false, "inputs": [ { "type": "tuple", "name": "person", "components": [ { "type": "string", "name": "name" }, { "type": "uint16", "name": "age" } ] } ], "outputs": [] }, { "type": "function", "name": "addPeople", "constant": false, "payable": false, "inputs": [ { "type": "tuple[]", "name": "person", "components": [ { "type": "string", "name": "name" }, { "type": "uint16", "name": "age" } ] } ], "outputs": [] }, { "type": "function", "name": "getPerson", "constant": true, "stateMutability": "view", "payable": false, "inputs": [ { "type": "uint256", "name": "id" } ], "outputs": [ { "type": "tuple", "components": [ { "type": "string", "name": "name" }, { "type": "uint16", "name": "age" } ] } ] }, { "type": "event", "anonymous": false, "name": "PersonAdded", "inputs": [ { "type": "uint256", "name": "id", "indexed": true }, { "type": "tuple", "name": "person", "components": [ { "type": "string", "name": "name", "indexed": false }, { "type": "uint16", "name": "age", "indexed": false } ] } ] } ]`;

Solidity Object ABI

The output from parsing (using JSON.parse) a Solidity JSON ABI is also fully compatible with the Interface class and each method, event and error from that object are compatible with the Fragment class.

Some developers may prefer this as it allows access to the ABI properties as normal JavaScript objects, and closely matches the JSON ABI that those familiar with the Solidity ABI will recognize.

Converting Between Formats

The Fragment object makes it simple to reformat a single method, event or error, however most developers will be interested in converting an entire ABI.

For production code it is recommended to inline the Human-Readable ABI as it makes it easy to see at a glance which methods, events and errors are available. It is also highly recommend to strip out unused parts of the ABI (such as admin methods) to further reduce code size.

Converting to Full Human-Readable ABI
// Using the "full" format will ensure the Result objects // have named properties, which improves code readability const iface = new Interface(jsonAbi); iface.format(FormatTypes.full); // [ // 'constructor(string symbol, string name)', // 'function transferFrom(address from, address to, uint256 value)', // 'function balanceOf(address owner) view returns (uint256)', // 'event Transfer(address indexed from, address indexed to, address value)', // 'error InsufficientBalance(account owner, uint256 balance)', // 'function addPerson(tuple(string name, uint16 age) person)', // 'function addPeople(tuple(string name, uint16 age)[] person)', // 'function getPerson(uint256 id) view returns (tuple(string name, uint16 age))', // 'event PersonAdded(uint256 indexed id, tuple(string name, uint16 age) person)' // ]
Converting to Minimal Human-Readable ABI
// Using the "minimal" format will save a small amount of // space, but is generally not worth it as named properties // on Results will not be available const iface = new Interface(jsonAbi); iface.format(FormatTypes.minimal); // [ // 'constructor(string,string)', // 'function transferFrom(address,address,uint256)', // 'function balanceOf(address) view returns (uint256)', // 'event Transfer(address indexed,address indexed,address)', // 'error InsufficientBalance(account,uint256)', // 'function addPerson(tuple(string,uint16))', // 'function addPeople(tuple(string,uint16)[])', // 'function getPerson(uint256) view returns (tuple(string,uint16))', // 'event PersonAdded(uint256 indexed,tuple(string,uint16))' // ]
Converting to JSON ABI
// Sometimes you may need to export a Human-Readable ABI to // JSON for tools that do not have Human-Readable support // For compactness, the JSON is kept with minimal white-space const iface = new Interface(humanReadableAbi); jsonAbi = iface.format(FormatTypes.json); // '[{"type":"constructor","payable":false,"inputs":[{"type":"string","name":"symbol"},{"type":"string","name":"name"}]},{"type":"function","name":"transferFrom","constant":false,"payable":false,"inputs":[{"type":"address","name":"from"},{"type":"address","name":"to"},{"type":"uint256","name":"value"}],"outputs":[]},{"type":"function","name":"balanceOf","constant":true,"stateMutability":"view","payable":false,"inputs":[{"type":"address","name":"owner"}],"outputs":[{"type":"uint256","name":"balance"}]},{"type":"event","anonymous":false,"name":"Transfer","inputs":[{"type":"address","name":"from","indexed":true},{"type":"address","name":"to","indexed":true},{"type":"address","name":"value"}]},{"type":"error","name":"InsufficientBalance","inputs":[{"type":"account","name":"owner"},{"type":"uint256","name":"balance"}]},{"type":"function","name":"addPerson","constant":false,"payable":false,"inputs":[{"type":"tuple","name":"person","components":[{"type":"string","name":"name"},{"type":"uint16","name":"age"}]}],"outputs":[]},{"type":"function","name":"addPeople","constant":false,"payable":false,"inputs":[{"type":"tuple[]","name":"person","components":[{"type":"string","name":"name"},{"type":"uint16","name":"age"}]}],"outputs":[]},{"type":"function","name":"getPerson","constant":true,"stateMutability":"view","payable":false,"inputs":[{"type":"uint256","name":"id"}],"outputs":[{"type":"tuple","components":[{"type":"string","name":"name"},{"type":"uint16","name":"age"}]}]},{"type":"event","anonymous":false,"name":"PersonAdded","inputs":[{"type":"uint256","name":"id","indexed":true},{"type":"tuple","name":"person","components":[{"type":"string","name":"name","indexed":false},{"type":"uint16","name":"age","indexed":false}]}]}]' // However it is easy to use JSON.parse and JSON.stringify // with formatting parameters to assist with readability JSON.stringify(JSON.parse(jsonAbi), null, 2); // `[ // { // "type": "constructor", // "payable": false, // "inputs": [ // { // "type": "string", // "name": "symbol" // }, // { // "type": "string", // "name": "name" // } // ] // }, // { // "type": "function", // "name": "transferFrom", // "constant": false, // "payable": false, // "inputs": [ // { // "type": "address", // "name": "from" // }, // { // "type": "address", // "name": "to" // }, // { // "type": "uint256", // "name": "value" // } // ], // "outputs": [] // }, // { // "type": "function", // "name": "balanceOf", // "constant": true, // "stateMutability": "view", // "payable": false, // "inputs": [ // { // "type": "address", // "name": "owner" // } // ], // "outputs": [ // { // "type": "uint256", // "name": "balance" // } // ] // }, // { // "type": "event", // "anonymous": false, // "name": "Transfer", // "inputs": [ // { // "type": "address", // "name": "from", // "indexed": true // }, // { // "type": "address", // "name": "to", // "indexed": true // }, // { // "type": "address", // "name": "value" // } // ] // }, // { // "type": "error", // "name": "InsufficientBalance", // "inputs": [ // { // "type": "account", // "name": "owner" // }, // { // "type": "uint256", // "name": "balance" // } // ] // }, // { // "type": "function", // "name": "addPerson", // "constant": false, // "payable": false, // "inputs": [ // { // "type": "tuple", // "name": "person", // "components": [ // { // "type": "string", // "name": "name" // }, // { // "type": "uint16", // "name": "age" // } // ] // } // ], // "outputs": [] // }, // { // "type": "function", // "name": "addPeople", // "constant": false, // "payable": false, // "inputs": [ // { // "type": "tuple[]", // "name": "person", // "components": [ // { // "type": "string", // "name": "name" // }, // { // "type": "uint16", // "name": "age" // } // ] // } // ], // "outputs": [] // }, // { // "type": "function", // "name": "getPerson", // "constant": true, // "stateMutability": "view", // "payable": false, // "inputs": [ // { // "type": "uint256", // "name": "id" // } // ], // "outputs": [ // { // "type": "tuple", // "components": [ // { // "type": "string", // "name": "name" // }, // { // "type": "uint16", // "name": "age" // } // ] // } // ] // }, // { // "type": "event", // "anonymous": false, // "name": "PersonAdded", // "inputs": [ // { // "type": "uint256", // "name": "id", // "indexed": true // }, // { // "type": "tuple", // "name": "person", // "components": [ // { // "type": "string", // "name": "name", // "indexed": false // }, // { // "type": "uint16", // "name": "age", // "indexed": false // } // ] // } // ] // } // ]`

Fragments

Explain an ABI.

Formats

JSON String ABI (Solidity Output JSON)

The JSON ABI Format is the format that is output from the Solidity compiler.

A JSON serialized object is always a string, which represents an Array of Objects, where each Object has various properties describing the Fragment of the ABI.

The deserialized JSON string (which is a normal JavaScript Object) may also be passed into any function which accepts a JSON String ABI.

Human-Readable ABI

The Human-Readable ABI was introduced by ethers in this article and has since gained wider adoption.

The ABI is described by using an array of strings, where each string is the Solidity signature of the constructor, function, event or error.

When parsing a fragment, all inferred properties will be injected (e.g. a payable method will have its constant proeprty set to false).

Tuples can be specified by using the tuple(...) syntax or with bare (additional) parenthesis, (...).

Example Human-Readable ABI
const ABI = [ // Constructor "constructor(address ens)", // Constant functions (pure or view) "function balanceOf(address owner) view returns (uint)", // State-mutating functions (payable or non-payable) "function mint(uint amount) payable", "function transfer(address to, uint amount) returns (bool)", // Events "event Transfer(address indexed from, address indexed to, uint amount)", // Errors "error InsufficientFunds(address from, uint balance)", ]

Output Formats

Each Fragment and ParamType may be output using its format method.

ethers.utils.FormatTypes.full string

This is a full human-readable string, including all parameter names, any optional modifiers (e.g. indexed, public, etc) and white-space to aid in human readability.

ethers.utils.FormatTypes.minimal string

This is similar to full, except with no unnecessary whitespace or parameter names. This is useful for storing a minimal string which can still fully reconstruct the original Fragment using Fragment&thinsp;.&thinsp;from.

ethers.utils.FormatTypes.json string

This returns a JavaScript Object which is safe to call JSON.stringify on to create a JSON string.

ethers.utils.FormatTypes.sighash string

This is a minimal output format, which is used by Solidity when computing a signature hash or an event topic hash.

Note

The sighash format is insufficient to re-create the original Fragment, since it discards modifiers such as indexed, anonymous, stateMutability, etc.

It is only useful for computing the selector for a Fragment, and cannot be used to format an Interface.

Fragment

An ABI is a collection of Fragments, where each fragment specifies:

Properties

fragment.name string

This is the name of the Event or Function. This will be null for a ConstructorFragment.

fragment.type string

This is a string which indicates the type of the Fragment. This will be one of:

  • constructor
  • event
  • function

fragment.inputs Array< ParamType >

This is an array of each ParamType for the input parameters to the Constructor, Event of Function.

Methods

fragment.format( [ format = sighash ] ) string

Creates a string representation of the Fragment using the available output formats.

ethers.utils.Fragment.from( objectOrString ) Fragment

Creates a new Fragment sub-class from any compatible objectOrString.

ethers.utils.Fragment.isFragment( object ) boolean

Returns true if object is a Fragment.

ConstructorFragment inherits Fragment

Properties

fragment.gas BigNumber

This is the gas limit that should be used during deployment. It may be null.

fragment.payable boolean

This is whether the constructor may receive ether during deployment as an endowment (i.e. msg.value != 0).

fragment.stateMutability string

This is the state mutability of the constructor. It can be any of:

  • nonpayable
  • payable

Methods

ethers.utils.ConstructorFragment.from( objectOrString ) ConstructorFragment

Creates a new ConstructorFragment from any compatible objectOrString.

ethers.utils.ConstructorFragment.isConstructorFragment( object ) boolean

Returns true if object is a ConstructorFragment.

ErrorFragment inherits Fragment

Methods

ethers.utils.ErrorFragment.from( objectOrString ) ErrorFragment

Creates a new ErrorFragment from any compatible objectOrString.

ethers.utils.ErrorFragment.isErrorFragment( object ) boolean

Returns true if object is an ErrorFragment.

EventFragment inherits Fragment

Properties

fragment.anonymous boolean

This is whether the event is anonymous. An anonymous Event does not inject its topic hash as topic0 when creating a log.

Methods

ethers.utils.EventFragment.from( objectOrString ) EventFragment

Creates a new EventFragment from any compatible objectOrString.

ethers.utils.EventFragment.isEventFragment( object ) boolean

Returns true if object is an EventFragment.

FunctionFragment inherits ConstructorFragment

Properties

fragment.constant boolean

This is whether the function is constant (i.e. does not change state). This is true if the state mutability is pure or view.

fragment.stateMutability string

This is the state mutability of the constructor. It can be any of:

  • nonpayable
  • payable
  • pure
  • view

fragment.outputs Array< ParamType >

A list of the Function output parameters.

Methods

ethers.utils.FunctionFragment.from( objectOrString ) FunctionFragment

Creates a new FunctionFragment from any compatible objectOrString.

ethers.utils.FunctionFragment.isFunctionFragment( object ) boolean

Returns true if object is a FunctionFragment.

ParamType

The following examples will represent the Solidity parameter:

string foobar

Properties

paramType.name string

The local parameter name. This may be null for unnamed parameters. For example, the parameter definition string foobar would be foobar.

paramType.type string

The full type of the parameter, including tuple and array symbols. This may be null for unnamed parameters. For the above example, this would be foobar.

paramType.baseType string

The base type of the parameter. For primitive types (e.g. address, uint256, etc) this is equal to type. For arrays, it will be the string array and for a tuple, it will be the string tuple.

paramType.indexed boolean

Whether the parameter has been marked as indexed. This only applies to parameters which are part of an EventFragment.

paramType.arrayChildren ParamType

The type of children of the array. This is null for any parameter which is not an array.

paramType.arrayLength number

The length of the array, or -1 for dynamic-length arrays. This is null for parameters which are not arrays.

paramType.components Array< ParamType >

The components of a tuple. This is null for non-tuple parameters.

Methods

paramType.format( [ outputType = sighash ] )

Creates a string representation of the Fragment using the available output formats.

ethers.utils.ParamType.from( objectOrString ) ParamType

Creates a new ParamType from any compatible objectOrString.

ethers.utils.ParamType.isParamType( object ) boolean

Returns true if object is a ParamType.

Interface

The Interface Class abstracts the encoding and decoding required to interact with contracts on the Ethereum network.

Many of the standards organically evolved along side the Solidity language, which other languages have adopted to remain compatible with existing deployed contracts.

The EVM itself does not understand what the ABI is. It is simply an agreed upon set of formats to encode various types of data which each contract can expect so they can interoperate with each other.

Creating Instances

new ethers.utils.Interface( abi )

Create a new Interface from a JSON string or object representing abi.

The abi may be a JSON string or the parsed Object (using JSON.parse) which is emitted by the Solidity compiler (or compatible languages).

The abi may also be a Human-Readable Abi, which is a format the Ethers created to simplify manually typing the ABI into the source and so that a Contract ABI can also be referenced easily within the same source file.

Creating an Interface instance
// This interface is used for the below examples const iface = new Interface([ // Constructor "constructor(string symbol, string name)", // State mutating method "function transferFrom(address from, address to, uint amount)", // State mutating method, which is payable "function mint(uint amount) payable", // Constant method (i.e. "view" or "pure") "function balanceOf(address owner) view returns (uint)", // An Event "event Transfer(address indexed from, address indexed to, uint256 amount)", // A Custom Solidity Error "error AccountLocked(address owner, uint256 balance)", // Examples with structured types "function addUser(tuple(string name, address addr) user) returns (uint id)", "function addUsers(tuple(string name, address addr)[] user) returns (uint[] id)", "function getUser(uint id) view returns (tuple(string name, address addr) user)" ]);

Properties

interface.fragments Array< Fragment >

All the Fragments in the interface.

interface.errors Array< ErrorFragment >

All the Error Fragments in the interface.

interface.events Array< EventFragment >

All the Event Fragments in the interface.

interface.functions Array< FunctionFragment >

All the Function Fragments in the interface.

interface.deploy ConstructorFragment

The Constructor Fragments for the interface.

Formatting

interface.format( [ format ] ) string | Array< string >

Return the formatted Interface. If the format type is json a single string is returned, otherwise an Array of the human-readable strings is returned.

const FormatTypes = ethers.utils.FormatTypes; iface.format(FormatTypes.json) // '[{"type":"constructor","payable":false,"inputs":[{"type":"string","name":"symbol"},{"type":"string","name":"name"}]},{"type":"function","name":"transferFrom","constant":false,"payable":false,"inputs":[{"type":"address","name":"from"},{"type":"address","name":"to"},{"type":"uint256","name":"amount"}],"outputs":[]},{"type":"function","name":"mint","constant":false,"stateMutability":"payable","payable":true,"inputs":[{"type":"uint256","name":"amount"}],"outputs":[]},{"type":"function","name":"balanceOf","constant":true,"stateMutability":"view","payable":false,"inputs":[{"type":"address","name":"owner"}],"outputs":[{"type":"uint256"}]},{"type":"event","anonymous":false,"name":"Transfer","inputs":[{"type":"address","name":"from","indexed":true},{"type":"address","name":"to","indexed":true},{"type":"uint256","name":"amount"}]},{"type":"error","name":"AccountLocked","inputs":[{"type":"address","name":"owner"},{"type":"uint256","name":"balance"}]},{"type":"function","name":"addUser","constant":false,"payable":false,"inputs":[{"type":"tuple","name":"user","components":[{"type":"string","name":"name"},{"type":"address","name":"addr"}]}],"outputs":[{"type":"uint256","name":"id"}]},{"type":"function","name":"addUsers","constant":false,"payable":false,"inputs":[{"type":"tuple[]","name":"user","components":[{"type":"string","name":"name"},{"type":"address","name":"addr"}]}],"outputs":[{"type":"uint256[]","name":"id"}]},{"type":"function","name":"getUser","constant":true,"stateMutability":"view","payable":false,"inputs":[{"type":"uint256","name":"id"}],"outputs":[{"type":"tuple","name":"user","components":[{"type":"string","name":"name"},{"type":"address","name":"addr"}]}]}]' iface.format(FormatTypes.full) // [ // 'constructor(string symbol, string name)', // 'function transferFrom(address from, address to, uint256 amount)', // 'function mint(uint256 amount) payable', // 'function balanceOf(address owner) view returns (uint256)', // 'event Transfer(address indexed from, address indexed to, uint256 amount)', // 'error AccountLocked(address owner, uint256 balance)', // 'function addUser(tuple(string name, address addr) user) returns (uint256 id)', // 'function addUsers(tuple(string name, address addr)[] user) returns (uint256[] id)', // 'function getUser(uint256 id) view returns (tuple(string name, address addr) user)' // ] iface.format(FormatTypes.minimal) // [ // 'constructor(string,string)', // 'function transferFrom(address,address,uint256)', // 'function mint(uint256) payable', // 'function balanceOf(address) view returns (uint256)', // 'event Transfer(address indexed,address indexed,uint256)', // 'error AccountLocked(address,uint256)', // 'function addUser(tuple(string,address)) returns (uint256)', // 'function addUsers(tuple(string,address)[]) returns (uint256[])', // 'function getUser(uint256) view returns (tuple(string,address))' // ]

Fragment Access

interface.getFunction( fragment ) FunctionFragment

Returns the FunctionFragment for fragment (see Specifying Fragments).

// By method signature, which is normalized so whitespace // and superfluous attributes are ignored iface.getFunction("transferFrom(address, address, uint256)"); // By name; this ONLY works if the method is non-ambiguous iface.getFunction("transferFrom"); // By method selector iface.getFunction("0x23b872dd"); // Throws if the method does not exist iface.getFunction("doesNotExist()"); // [Error: no matching function] { // argument: 'signature', // code: 'INVALID_ARGUMENT', // reason: 'no matching function', // value: 'doesNotExist()' // }
interface.getError( fragment ) ErrorFragment

Returns the ErrorFragment for fragment (see Specifying Fragments).

// By error signature, which is normalized so whitespace // and superfluous attributes are ignored iface.getError("AccountLocked(address, uint256)"); // By name; this ONLY works if the error is non-ambiguous iface.getError("AccountLocked"); // By error selector iface.getError("0xf7c3865a"); // Throws if the error does not exist iface.getError("DoesNotExist()"); // [Error: no matching error] { // argument: 'signature', // code: 'INVALID_ARGUMENT', // reason: 'no matching error', // value: 'DoesNotExist()' // }
interface.getEvent( fragment ) EventFragment

Returns the EventFragment for fragment (see Specifying Fragments).

// By event signature, which is normalized so whitespace // and superfluous attributes are ignored iface.getEvent("Transfer(address, address, uint256)"); // By name; this ONLY works if the event is non-ambiguous iface.getEvent("Transfer"); // By event topic hash iface.getEvent("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); // Throws if the event does not exist iface.getEvent("DoesNotExist()"); // [Error: no matching event] { // argument: 'signature', // code: 'INVALID_ARGUMENT', // reason: 'no matching event', // value: 'DoesNotExist()' // }

Signature and Topic Hashes

interface.getSighash( fragment ) string< DataHexString< 4 > >

Return the sighash (or Function Selector) for fragment (see Specifying Fragments).

iface.getSighash("balanceOf"); // '0x70a08231' iface.getSighash("balanceOf(address)"); // '0x70a08231' const fragment = iface.getFunction("balanceOf") iface.getSighash(fragment); // '0x70a08231'
interface.getEventTopic( fragment ) string< DataHexString< 32 > >

Return the topic hash for fragment (see Specifying Fragments).

iface.getEventTopic("Transfer"); // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' iface.getEventTopic("Transfer(address, address, uint)"); // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' const fragment = iface.getEvent("Transfer") iface.getEventTopic(fragment); // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'

Encoding Data

interface.encodeDeploy( [ values ] ) string< DataHexString >

Return the encoded deployment data, which can be concatenated to the deployment bytecode of a contract to pass values into the contract constructor.

// The data that should be appended to the bytecode to pass // parameters to the constructor during deployment iface.encodeDeploy([ "SYM", "Some Name" ]) // '0x00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000353594d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009536f6d65204e616d650000000000000000000000000000000000000000000000'
interface.encodeErrorResult( fragment [ , values ] ) string< DataHexString >

Returns the encoded error result, which would normally be the response from a reverted call for fragment (see Specifying Fragments) for the given values.

Most developers will not need this method, but may be useful for authors of a mock blockchain.

// Encoding result data (like is returned by eth_call during a revert) iface.encodeErrorResult("AccountLocked", [ "0x8ba1f109551bD432803012645Ac136ddd64DBA72", parseEther("1.0") ]); // '0xf7c3865a0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000000de0b6b3a7640000'
interface.encodeFilterTopics( fragment , values ) Array< topic | Array< topic > >

Returns the encoded topic filter, which can be passed to getLogs for fragment (see Specifying Fragments) for the given values.

Each topic is a 32 byte (64 nibble) DataHexString.

// Filter that matches all Transfer events iface.encodeFilterTopics("Transfer", []) // [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' // ] // Filter that matches the sender iface.encodeFilterTopics("Transfer", [ "0x8ba1f109551bD432803012645Ac136ddd64DBA72" ]) // [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72' // ] // Filter that matches the receiver iface.encodeFilterTopics("Transfer", [ null, "0x8ba1f109551bD432803012645Ac136ddd64DBA72" ]) // [ // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', // null, // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72' // ]
interface.encodeFunctionData( fragment [ , values ] ) string< DataHexString >

Returns the encoded data, which can be used as the data for a transaction for fragment (see Specifying Fragments) for the given values.

// Encoding data for the tx.data of a call or transaction iface.encodeFunctionData("transferFrom", [ "0x8ba1f109551bD432803012645Ac136ddd64DBA72", "0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C", parseEther("1.0") ]) // '0x23b872dd0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c0000000000000000000000000000000000000000000000000de0b6b3a7640000' // Encoding structured data (using positional Array) user = [ "Richard Moore", "0x8ba1f109551bD432803012645Ac136ddd64DBA72" ]; iface.encodeFunctionData("addUser", [ user ]); // '0x43967833000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000400000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72000000000000000000000000000000000000000000000000000000000000000d52696368617264204d6f6f726500000000000000000000000000000000000000' // Encoding structured data, using objects. Only available // if paramters are named. user = { name: "Richard Moore", addr: "0x8ba1f109551bD432803012645Ac136ddd64DBA72" }; iface.encodeFunctionData("addUser", [ user ]); // '0x43967833000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000400000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72000000000000000000000000000000000000000000000000000000000000000d52696368617264204d6f6f726500000000000000000000000000000000000000'
interface.encodeFunctionResult( fragment [ , values ] ) string< DataHexString >

Returns the encoded result, which would normally be the response from a call for fragment (see Specifying Fragments) for the given values.

Most developers will not need this method, but may be useful for authors of a mock blockchain.

// Encoding result data (like is returned by eth_call) iface.encodeFunctionResult("balanceOf", [ "0x8ba1f109551bD432803012645Ac136ddd64DBA72" ]) // '0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72'

Decoding Data

interface.decodeErrorResult( fragment , data ) Result

Returns the decoded values from the result of a call during a revert for fragment (see Specifying Fragments) for the given data.

Most developers won't need this, as the decodeFunctionResult will automatically decode errors if the data represents a revert.

// Decoding result data (e.g. from an eth_call) errorData = "0xf7c3865a0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000000de0b6b3a7640000"; iface.decodeErrorResult("AccountLocked", errorData) // [ // '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // { BigNumber: "1000000000000000000" }, // balance: { BigNumber: "1000000000000000000" }, // owner: '0x8ba1f109551bD432803012645Ac136ddd64DBA72' // ]
interface.decodeEventLog( fragment , data [ , topics ] ) Result

Returns the decoded event values from an event log for fragment (see Specifying Fragments) for the given data with the optional topics.

If topics is not specified, placeholders will be inserted into the result.

Most developers will find the parsing methods more convenient for decoding event data, as they will automatically detect the matching event.

// Decoding log data and topics (the entries in a receipt) const data = "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000"; const topics = [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72", "0x000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c" ]; iface.decodeEventLog("Transfer", data, topics); // [ // '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C', // { BigNumber: "1000000000000000000" }, // amount: { BigNumber: "1000000000000000000" }, // from: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // to: '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C' // ]
interface.decodeFunctionData( fragment , data ) Result

Returns the decoded values from transaction data for fragment (see Specifying Fragments) for the given data.

Most developers will not need this method, but may be useful for debugging or inspecting transactions.

Most developers will also find the parsing methods more convenient for decoding transation data, as they will automatically detect the matching function.

// Decoding function data (the value of tx.data) const txData = "0x23b872dd0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c0000000000000000000000000000000000000000000000000de0b6b3a7640000"; iface.decodeFunctionData("transferFrom", txData); // [ // '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C', // { BigNumber: "1000000000000000000" }, // amount: { BigNumber: "1000000000000000000" }, // from: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // to: '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C' // ]
interface.decodeFunctionResult( fragment , data ) Result

Returns the decoded values from the result of a call for fragment (see Specifying Fragments) for the given data.

// Decoding result data (e.g. from an eth_call) resultData = "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000"; iface.decodeFunctionResult("balanceOf", resultData) // [ // { BigNumber: "1000000000000000000" } // ] // Decoding result data which was caused by a revert // Throws a CALL_EXCEPTION, with extra details errorData = "0xf7c3865a0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000000de0b6b3a7640000"; iface.decodeFunctionResult("balanceOf", errorData) // [Error: call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ]] { // code: 'CALL_EXCEPTION', // data: '0xf7c3865a0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000000de0b6b3a7640000', // errorArgs: [ // '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // { BigNumber: "1000000000000000000" }, // balance: { BigNumber: "1000000000000000000" }, // owner: '0x8ba1f109551bD432803012645Ac136ddd64DBA72' // ], // errorName: 'AccountLocked', // errorSignature: 'AccountLocked(address,uint256)', // method: 'balanceOf(address)', // reason: null // } // Decoding structured data returns a Result object, which // will include all values positionally and if the ABI // included names, values will additionally be available // by their name. resultData = "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000400000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72000000000000000000000000000000000000000000000000000000000000000d52696368617264204d6f6f726500000000000000000000000000000000000000"; result = iface.decodeFunctionResult("getUser", resultData); // [ // [ // 'Richard Moore', // '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // addr: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // name: 'Richard Moore' // ], // user: [ // 'Richard Moore', // '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // addr: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // name: 'Richard Moore' // ] // ] // Access positionally: // The 0th output parameter, the 0th proerty of the structure result[0][0]; // 'Richard Moore' // Access by name: (only avilable because parameters were named) result.user.name // 'Richard Moore'

Parsing

The functions are generally the most useful for most developers. They will automatically search the ABI for a matching Event or Function and decode the components as a fully specified description.

interface.parseError( data ) ErrorDescription

Search for the error that matches the error selector in data and parse out the details.

const data = "0xf7c3865a0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000000de0b6b3a7640000"; iface.parseError(data); // ErrorDescription { // args: [ // '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // { BigNumber: "1000000000000000000" }, // balance: { BigNumber: "1000000000000000000" }, // owner: '0x8ba1f109551bD432803012645Ac136ddd64DBA72' // ], // errorFragment: [class ErrorFragment], // name: 'AccountLocked', // sighash: '0xf7c3865a', // signature: 'AccountLocked(address,uint256)' // }
interface.parseLog( log ) LogDescription

Search the event that matches the log topic hash and parse the values the log represents.

const data = "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000"; const topics = [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72", "0x000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c" ]; iface.parseLog({ data, topics }); // LogDescription { // args: [ // '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C', // { BigNumber: "1000000000000000000" }, // amount: { BigNumber: "1000000000000000000" }, // from: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // to: '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C' // ], // eventFragment: [class EventFragment], // name: 'Transfer', // signature: 'Transfer(address,address,uint256)', // topic: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' // }
interface.parseTransaction( transaction ) TransactionDescription

Search for the function that matches the transaction data sighash and parse the transaction properties.

const data = "0x23b872dd0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba72000000000000000000000000ab7c8803962c0f2f5bbbe3fa8bf41cd82aa1923c0000000000000000000000000000000000000000000000000de0b6b3a7640000"; const value = parseEther("1.0"); iface.parseTransaction({ data, value }); // TransactionDescription { // args: [ // '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C', // { BigNumber: "1000000000000000000" }, // amount: { BigNumber: "1000000000000000000" }, // from: '0x8ba1f109551bD432803012645Ac136ddd64DBA72', // to: '0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C' // ], // functionFragment: [class FunctionFragment], // name: 'transferFrom', // sighash: '0x23b872dd', // signature: 'transferFrom(address,address,uint256)', // value: { BigNumber: "1000000000000000000" } // }

Types

Result inherits Array<any>

A Result is an array, so each value can be accessed as a positional argument.

Additionally, if values are named, the identical object as its positional value can be accessed by its name.

The name length is however reserved as it is part of the Array, so any named value for this key is renamed to _length. If there is a name collision, only the first is available by its key.

ErrorDescription

errorDescription.args Result

The values of the input parameters of the error.

errorDescription.errorFragment ErrorFragment

The ErrorFragment which matches the selector in the data.

errorDescription.name string

The error name. (e.g. AccountLocked)

errorDescription.signature string

The error signature. (e.g. AccountLocked(address,uint256))

errorDescription.sighash string

The selector of the error.

LogDescription

logDescription.args Result

The values of the input parameters of the event.

logDescription.eventFragment EventFragment

The EventFragment which matches the topic in the Log.

logDescription.name string

The event name. (e.g. Transfer)

logDescription.signature string

The event signature. (e.g. Transfer(address,address,uint256))

logDescription.topic string

The topic hash.

TransactionDescription

transactionDescription.args Result

The decoded values from the transaction data which were passed as the input parameters.

transactionDescription.functionFragment FunctionFragment

The FunctionFragment which matches the sighash in the transaction data.

transactionDescription.name string

The name of the function. (e.g. transfer)

transactionDescription.sighash string

The sighash (or function selector) that matched the transaction data.

transactionDescription.signature string

The signature of the function. (e.g. transfer(address,uint256))

transactionDescription.value BigNumber

The value from the transaction.

Specifying Fragments

When specifying a fragment to any of the functions in an Interface, any of the following may be used:

Addresses

Explain addresses,formats and checksumming here.

Also see: constants.AddressZero

Address Formats

Address

An Address is a DataHexString of 20 bytes (40 nibbles), with optional mixed case.

If the case is mixed, it is a Checksum Address, which uses a specific pattern of uppercase and lowercase letters within a given address to reduce the risk of errors introduced from typing an address or cut and paste issues.

All functions that return an Address will return a Checksum Address.

ICAP Address

The ICAP Address Format was an early attempt to introduce a checksum into Ethereum addresses using the popular banking industry's IBAN format with the country code specified as XE.

Due to the way IBAN encodes address, only addresses that fit into 30 base-36 characters are actually compatible, so the format was adapted to support 31 base-36 characters which is large enough for a full Ethereum address, however the preferred method was to select a private key whose address has a 0 as the first byte, which allows the address to be formatted as a fully compatibly standard IBAN address with 30 base-36 characters.

In general this format is no longer widely supported anymore, however any function that accepts an address can receive an ICAP address, and it will be converted internally.

To convert an address into the ICAP format, see getIcapAddress.

Converting and Verifying

ethers.utils.getAddress( address ) string< Address >

Returns address as a Checksum Address.

If address is an invalid 40-nibble HexString or if it contains mixed case and the checksum is invalid, an INVALID_ARGUMENT Error is thrown.

The value of address may be any supported address format.

// Injects the checksum (via upper-casing specific letters) getAddress("0x8ba1f109551bd432803012645ac136ddd64dba72"); // '0x8ba1f109551bD432803012645Ac136ddd64DBA72' // Converts and injects the checksum getAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36"); // '0x8ba1f109551bD432803012645Ac136ddd64DBA72' // Throws if a checksummed address is provided, but a // letter is the wrong case // ------------v (should be lower-case) getAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72") // [Error: bad address checksum] { // argument: 'address', // code: 'INVALID_ARGUMENT', // reason: 'bad address checksum', // value: '0x8Ba1f109551bD432803012645Ac136ddd64DBA72' // } // Throws if the ICAP/IBAN checksum fails getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK37"); // Error: getIcapAddress is not defined // Throws if the address is invalid, in general getIcapAddress("I like turtles!"); // Error: getIcapAddress is not defined
ethers.utils.getIcapAddress( address ) string< IcapAddress >

Returns address as an ICAP address. Supports the same restrictions as getAddress.

getIcapAddress("0x8ba1f109551bd432803012645ac136ddd64dba72"); // 'XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36' getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36"); // 'XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36'
ethers.utils.isAddress( address ) boolean

Returns true if address is valid (in any supported format).

isAddress("0x8ba1f109551bd432803012645ac136ddd64dba72"); // true isAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36"); // true isAddress("I like turtles."); // false

Derivation

ethers.utils.computeAddress( publicOrPrivateKey ) string< Address >

Returns the address for publicOrPrivateKey. A public key may be compressed or uncompressed, and a private key will be converted automatically to a public key for the derivation.

// Private Key computeAddress("0xb976778317b23a1385ec2d483eda6904d9319135b89f1d8eee9f6d2593e2665d"); // '0x0Ac1dF02185025F65202660F8167210A80dD5086' // Public Key (compressed) computeAddress("0x0376698beebe8ee5c74d8cc50ab84ac301ee8f10af6f28d0ffd6adf4d6d3b9b762"); // '0x0Ac1dF02185025F65202660F8167210A80dD5086' // Public Key (uncompressed) computeAddress("0x0476698beebe8ee5c74d8cc50ab84ac301ee8f10af6f28d0ffd6adf4d6d3b9b762d46ca56d3dad2ce13213a6f42278dabbb53259f2d92681ea6a0b98197a719be3"); // '0x0Ac1dF02185025F65202660F8167210A80dD5086'
ethers.utils.recoverAddress( digest , signature ) string< Address >

Use ECDSA Public Key Recovery to determine the address that signed digest to which generated signature.

const digest = "0x7c5ea36004851c764c44143b1dcb59679b11c9a68e5f41497f6cf3d480715331"; // Using an expanded Signature recoverAddress(digest, { r: "0x528459e4aec8934dc2ee94c4f3265cf6ce00d47cf42bb106afda3642c72e25eb", s: "0x42544137118256121502784e5a6425e6183ca964421ecd577db6c66ba9bccdcf", v: 27 }); // '0x0Ac1dF02185025F65202660F8167210A80dD5086' // Using a flat Signature const signature = "0x528459e4aec8934dc2ee94c4f3265cf6ce00d47cf42bb106afda3642c72e25eb42544137118256121502784e5a6425e6183ca964421ecd577db6c66ba9bccdcf1b"; recoverAddress(digest, signature); // '0x0Ac1dF02185025F65202660F8167210A80dD5086'

Contracts Addresses

ethers.utils.getContractAddress( transaction ) string< Address >

Returns the contract address that would result if transaction was used to deploy a contract.

const from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"; const nonce = 5; getContractAddress({ from, nonce }); // '0x082B6aC9e47d7D83ea3FaBbD1eC7DAba9D687b36'
ethers.utils.getCreate2Address( from , salt , initCodeHash ) string< Address >

Returns the contract address that would result from the given CREATE2 call.

const from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"; const salt = "0x7c5ea36004851c764c44143b1dcb59679b11c9a68e5f41497f6cf3d480715331"; const initCode = "0x6394198df16000526103ff60206004601c335afa6040516060f3"; const initCodeHash = keccak256(initCode); getCreate2Address(from, salt, initCodeHash); // '0x533ae9d683B10C02EbDb05471642F85230071FC3'

BigNumber

Many operations in Ethereum operate on numbers which are outside the range of safe values to use in JavaScript.

A BigNumber is an object which safely allows mathematical operations on numbers of any magnitude.

Most operations which need to return a value will return a BigNumber and parameters which accept values will generally accept them.

Types

BigNumberish

Many functions and methods in this library take in values which can be non-ambiguously and safely converted to a BigNumber. These values can be specified as:

string

A HexString or a decimal string, either of which may be negative.

BytesLike

A BytesLike Object, such as an Array or Uint8Array.

BigNumber

An existing BigNumber instance.

number

A number that is within the safe range for JavaScript numbers.

BigInt

A JavaScript BigInt object, on environments that support BigInt.

Creating Instances

The constructor of BigNumber cannot be called directly. Instead, Use the static BigNumber.from.

ethers.BigNumber.from( aBigNumberish ) BigNumber

Returns an instance of a BigNumber for aBigNumberish.

Examples:

// From a decimal string... BigNumber.from("42") // { BigNumber: "42" } // From a HexString... BigNumber.from("0x2a") // { BigNumber: "42" } // From a negative HexString... BigNumber.from("-0x2a") // { BigNumber: "-42" } // From an Array (or Uint8Array)... BigNumber.from([ 42 ]) // { BigNumber: "42" } // From an existing BigNumber... let one1 = constants.One; let one2 = BigNumber.from(one1) one2 // { BigNumber: "1" } // ...which returns the same instance one1 === one2 // true // From a (safe) number... BigNumber.from(42) // { BigNumber: "42" } // From a ES2015 BigInt... (only on platforms with BigInt support) BigNumber.from(42n) // { BigNumber: "42" } // Numbers outside the safe range fail: BigNumber.from(Number.MAX_SAFE_INTEGER); // [Error: overflow [ See: https://links.ethers.org/v5-errors-NUMERIC_FAULT-overflow ]] { // code: 'NUMERIC_FAULT', // fault: 'overflow', // operation: 'BigNumber.from', // reason: 'overflow', // value: 9007199254740991 // }

Methods

The BigNumber class is immutable, so no operations can change the value it represents.

Math Operations

bigNumber.add( otherValue ) BigNumber

Returns a BigNumber with the value of BigNumber + otherValue.

bigNumber.sub( otherValue ) BigNumber

Returns a BigNumber with the value of BigNumber - otherValue.

bigNumber.mul( otherValue ) BigNumber

Returns a BigNumber with the value of BigNumber × otherValue.

bigNumber.div( divisor ) BigNumber

Returns a BigNumber with the value of BigNumber ÷ divisor.

bigNumber.mod( divisor ) BigNumber

Returns a BigNumber with the value of the remainder of BigNumber ÷ divisor.

bigNumber.pow( exponent ) BigNumber

Returns a BigNumber with the value of BigNumber to the power of exponent.

bigNumber.abs( ) BigNumber

Returns a BigNumber with the absolute value of BigNumber.

bigNumber.mask( bitcount ) BigNumber

Returns a BigNumber with the value of BigNumber with bits beyond the bitcount least significant bits set to zero.

Two's Complement

Two's Complement is an elegant method used to encode and decode fixed-width signed values while efficiently preserving mathematical operations. Most users will not need to interact with these.

bigNumber.fromTwos( bitwidth ) BigNumber

Returns a BigNumber with the value of BigNumber converted from twos-complement with bitwidth.

bigNumber.toTwos( bitwidth ) BigNumber

Returns a BigNumber with the value of BigNumber converted to twos-complement with bitwidth.

Comparison and Equivalence

bigNumber.eq( otherValue ) boolean

Returns true if and only if the value of BigNumber is equal to otherValue.

bigNumber.lt( otherValue ) boolean

Returns true if and only if the value of BigNumber < otherValue.

bigNumber.lte( otherValue ) boolean

Returns true if and only if the value of BigNumber otherValue.

bigNumber.gt( otherValue ) boolean

Returns true if and only if the value of BigNumber > otherValue.

bigNumber.gte( otherValue ) boolean

Returns true if and only if the value of BigNumber otherValue.

bigNumber.isZero( ) boolean

Returns true if and only if the value of BigNumber is zero.

Conversion

bigNumber.toBigInt( ) bigint

Returns the value of BigNumber as a JavaScript BigInt value, on platforms which support them.

bigNumber.toNumber( ) number

Returns the value of BigNumber as a JavaScript value.

This will throw an error if the value is greater than or equal to Number.MAX_SAFE_INTEGER or less than or equal to Number.MIN_SAFE_INTEGER.

bigNumber.toString( ) string

Returns the value of BigNumber as a base-10 string.

bigNumber.toHexString( ) string< DataHexString >

Returns the value of BigNumber as a base-16, 0x-prefixed DataHexString.

Inspection

ethers.BigNumber.isBigNumber( object ) boolean

Returns true if and only if the object is a BigNumber object.

Examples

let a = BigNumber.from(42); let b = BigNumber.from("91"); a.mul(b); // { BigNumber: "3822" }

Notes

This section is a for a couple of questions that come up frequently.

Why can't I just use numbers?

The first problem many encounter when dealing with Ethereum is the concept of numbers. Most common currencies are broken down with very little granularity. For example, there are only 100 cents in a single dollar. However, there are 1018 wei in a single ether.

JavaScript uses IEEE 754 double-precision binary floating point numbers to represent numeric values. As a result, there are holes in the integer set after 9,007,199,254,740,991; which is problematic for Ethereum because that is only around 0.009 ether (in wei), which means any value over that will begin to experience rounding errors.

To demonstrate how this may be an issue in your code, consider:

(Number.MAX_SAFE_INTEGER + 2 - 2) == (Number.MAX_SAFE_INTEGER) // false

To remedy this, all numbers (which can be large) are stored and manipulated as Big Numbers.

The functions parseEther( etherString ) and formatEther( wei ) can be used to convert between string representations, which are displayed to or entered by the user and Big Number representations which can have mathematical operations handled safely.

Why not BigNumber.js, BN.js, BigDecimal, etc?

Everyone has their own favourite Big Number library, and once someone has chosen one, it becomes part of their identity, like their editor, vi vs emacs. There are over 100 Big Number libraries on npm.

One of the biggest differences between the Ethers BigNumber object and other libraries is that it is immutable, which is very important when dealing with the asynchronous nature of the blockchain.

Capturing the value is not safe in async functions, so immutability protects us from easy to make mistakes, which is not possible on the low-level library's objects which supports myriad in-place operations.

Second, the Ethers BigNumber provides all the functionality required internally and should generally be sufficient for most developers while not exposing some of the more advanced and rare functionality. So it will be easier to swap out the underlying library without impacting consumers.

For example, if BN.js was exposed, someone may use the greatest-common-denominator functions, which would then be functionality the replacing library should also provide to ensure anyone depending on that functionality is not broken.

Why BN.js??

The reason why BN.js is used internally as the big number is because that is the library used by elliptic.

Therefore it must be included regardless, so we leverage that library rather than adding another Big Number library, which would mean two different libraries offering the same functionality.

This has saved about 85kb (80% of this library size) of library size over other libraries which include separate Big Number libraries for various purposes.

Allow us to set a global Big Number library?

Another comment that comes up frequently is the desire to specify a global user-defined Big Number library, which all functions would return.

This becomes problematic since your code may live along side other libraries or code that use Ethers. In fact, even Ethers uses a lot of the public functions internally.

If you, for example, used a library that used a.plus(b) instead of a.add(b), this would break Ethers when it tries to compute fees internally, and other libraries likely have similar logic.

But, the BigNumber prototype is exposed, so you can always add a toMyCustomBigNumber() method to all BigNumber's globally which is safe.

Byte Manipulation

While there are many high-level APIs for interacting with Ethereum, such as Contracts and Providers, a lot of the low level access requires byte manipulation operations.

Many of these operations are used internally, but can also be used to help normalize binary data representations from the output of various functions and methods.

Types

Bytes

A Bytes is any object which is an Array or TypedArray with each value in the valid byte range (i.e. between 0 and 255 inclusive), or is an Object with a length property where each indexed property is in the valid byte range.

BytesLike

A BytesLike can be either a Bytes or a DataHexString.

DataHexString

A DataHexstring is identical to a HexString except that it has an even number of nibbles, and therefore is a valid representation of binary data as a string.

HexString

A Hexstring is a string which has a 0x prefix followed by any number of nibbles (i.e. case-insensitive hexadecimal characters, 0-9 and a-f).

Signature

Raw Signature inherits string<DataHexString<65>>

A Raw Signature is a common Signature format where the r, s and v are concatenated into a 65 byte (130 nibble) DataHexString.

SignatureLike

A SignatureLike is similar to a Signature, except redundant properties may be omitted or it may be a Raw Signature.

For example, if _vs is specified, s and v may be omitted. Likewise, if recoveryParam is provided, v may be omitted (as in these cases the missing values can be computed).

Inspection

ethers.utils.isBytes( object ) boolean

Returns true if and only if object is a valid Bytes.

ethers.utils.isBytesLike( object ) boolean

Returns true if and only if object is a Bytes or DataHexString.

ethers.utils.isHexString( object , [ length ] ) boolean

Returns true if and only if object is a valid hex string. If length is specified and object is not a valid DataHexString of length bytes, an InvalidArgument error is thrown.

Converting between Arrays and Hexstrings

ethers.utils.arrayify( DataHexStringOrArrayish [ , options ] ) Uint8Array

Converts DataHexStringOrArrayish to a Uint8Array.

ethers.utils.hexlify( hexstringOrArrayish ) string< DataHexString >

Converts hexstringOrArrayish to a DataHexString.

ethers.utils.hexValue( aBigNumberish ) string< HexString >

Converts aBigNumberish to a HexString, with no unnecessary leading zeros.

Examples
// Convert a hexstring to a Uint8Array arrayify("0x1234") // Uint8Array [ 18, 52 ] // Convert an Array to a hexstring hexlify([1, 2, 3, 4]) // '0x01020304' // Convert an Object to a hexstring hexlify({ length: 2, "0": 1, "1": 2 }) // '0x0102' // Convert an Array to a hexstring hexlify([ 1 ]) // '0x01' // Convert a number to a stripped hex value hexValue(1) // '0x1' // Convert an Array to a stripped hex value hexValue([ 1, 2 ]) // '0x102'

Array Manipulation

ethers.utils.concat( arrayOfBytesLike ) Uint8Array

Concatenates all the BytesLike in arrayOfBytesLike into a single Uint8Array.

ethers.utils.stripZeros( aBytesLike ) Uint8Array

Returns a Uint8Array with all leading 0 bytes of aBtyesLike removed.

ethers.utils.zeroPad( aBytesLike , length ) Uint8Array

Returns a Uint8Array of the data in aBytesLike with 0 bytes prepended to length bytes long.

If aBytesLike is already longer than length bytes long, an InvalidArgument error will be thrown.

Hexstring Manipulation

ethers.utils.hexConcat( arrayOfBytesLike ) string< DataHexString >

Concatenates all the BytesLike in arrayOfBytesLike into a single DataHexString

ethers.utils.hexDataLength( aBytesLike ) string< DataHexString >

Returns the length (in bytes) of aBytesLike.

ethers.utils.hexDataSlice( aBytesLike , offset [ , endOffset ] ) string< DataHexString >

Returns a DataHexString representation of a slice of aBytesLike, from offset (in bytes) to endOffset (in bytes). If endOffset is omitted, the length of aBytesLike is used.

ethers.utils.hexStripZeros( aBytesLike ) string< HexString >

Returns a HexString representation of aBytesLike with all leading zeros removed.

ethers.utils.hexZeroPad( aBytesLike , length ) string< DataHexString >

Returns a DataHexString representation of aBytesLike padded to length bytes.

If aBytesLike is already longer than length bytes long, an InvalidArgument error will be thrown.

Signature Conversion

ethers.utils.joinSignature( aSignatureLike ) string< RawSignature >

Return the raw-format of aSignaturelike, which is 65 bytes (130 nibbles) long, concatenating the r, s and (normalized) v of a Signature.

ethers.utils.splitSignature( aSignatureLikeOrBytesLike ) Signature

Return the full expanded-format of aSignaturelike or a raw-format DataHexString. Any missing properties will be computed.

Random Bytes

ethers.utils.randomBytes( length ) Uint8Array

Return a new Uint8Array of length random bytes.

ethers.utils.shuffled( array ) Array< any >

Return a copy of array shuffled using Fisher-Yates Shuffle.

Examples
utils.randomBytes(8) // Uint8Array [ 24, 54, 56, 23, 136, 185, 75, 104 ] const data = [ 1, 2, 3, 4, 5, 6, 7 ]; // Returns a new Array utils.shuffled(data); // [ // 3, // 4, // 1, // 6, // 2, // 5, // 7 // ] // The Original is unscathed... data // [ // 1, // 2, // 3, // 4, // 5, // 6, // 7 // ]

Constants

The ethers.constants Object contains commonly used values.

Bytes

ethers.constants.AddressZero string< Address >

The Address Zero, which is 20 bytes (40 nibbles) of zero.

ethers.constants.HashZero string< DataHexString< 32 > >

The Hash Zero, which is 32 bytes (64 nibbles) of zero.

Strings

ethers.constants.EtherSymbol string

The Ether symbol, Ξ.

BigNumber

ethers.constants.NegativeOne BigNumber

The BigNumber value representing "-1".

ethers.constants.Zero BigNumber

The BigNumber value representing "0".

ethers.constants.One BigNumber

The BigNumber value representing "1".

ethers.constants.Two BigNumber

The BigNumber value representing "2".

ethers.constants.WeiPerEther BigNumber

The BigNumber value representing "1000000000000000000", which is the number of Wei per Ether.

ethers.constants.MaxUint256 BigNumber

The BigNumber value representing the maximum uint256 value.

Display Logic and Input

When creating an Application, it is useful to convert between user-friendly strings (usually displaying ether) and the machine-readable values that contracts and maths depend on (usually in wei).

For example, a Wallet may specify the balance in ether, and gas prices in gwei for the User Interface, but when sending a transaction, both must be specified in wei.

The parseUnits will parse a string representing ether, such as 1.1 into a BigNumber in wei, and is useful when a user types in a value, such as sending 1.1 ether.

The formatUnits will format a BigNumberish into a string, which is useful when displaying a balance.

Units

Decimal Count

A Unit can be specified as a number, which indicates the number of decimal places that should be used.

Examples:

Named Units

There are also several common Named Units, in which case their name (as a string) may be used.

NameDecimals 
wei0 
kwei3 
mwei6 
gwei9 
szabo12 
finney15 
ether18 

Functions

Formatting

ethers.utils.commify( value ) string

Returns a string with value grouped by 3 digits, separated by ,.

commify("-1000.3000"); // '-1,000.3'

Conversion

ethers.utils.formatUnits( value [ , unit = "ether" ] ) string

Returns a string representation of value formatted with unit digits (if it is a number) or to the unit specified (if a string).

const oneGwei = BigNumber.from("1000000000"); const oneEther = BigNumber.from("1000000000000000000"); formatUnits(oneGwei, 0); // '1000000000' formatUnits(oneGwei, "gwei"); // '1.0' formatUnits(oneGwei, 9); // '1.0' formatUnits(oneEther); // '1.0' formatUnits(oneEther, 18); // '1.0'
ethers.utils.formatEther( value ) string

The equivalent to calling formatUnits(value, "ether").

const value = BigNumber.from("1000000000000000000"); formatEther(value); // '1.0'
ethers.utils.parseUnits( value [ , unit = "ether" ] ) BigNumber

Returns a BigNumber representation of value, parsed with unit digits (if it is a number) or from the unit specified (if a string).

parseUnits("1.0"); // { BigNumber: "1000000000000000000" } parseUnits("1.0", "ether"); // { BigNumber: "1000000000000000000" } parseUnits("1.0", 18); // { BigNumber: "1000000000000000000" } parseUnits("121.0", "gwei"); // { BigNumber: "121000000000" } parseUnits("121.0", 9); // { BigNumber: "121000000000" }
ethers.utils.parseEther( value ) BigNumber

The equivalent to calling parseUnits(value, "ether").

parseEther("1.0"); // { BigNumber: "1000000000000000000" } parseEther("-0.5"); // { BigNumber: "-500000000000000000" }

Encoding Utilities

Base58

ethers.utils.base58.decode( textData ) Uint8Array

Return a typed Uint8Array representation of textData decoded using base-58 encoding.

base58.decode("TzMhH"); // Uint8Array [ 18, 52, 86, 120 ]
ethers.utils.base58.encode( aBytesLike ) string

Return aBytesLike encoded as a string using the base-58 encoding.

base58.encode("0x12345678"); // 'TzMhH' base58.encode([ 0x12, 0x34, 0x56, 0x78 ]); // 'TzMhH'

Base64

ethers.utils.base64.decode( textData ) Uint8Array

Return a typed Uint8Array representation of textData decoded using base-64 encoding.

base64.decode("EjQ="); // Uint8Array [ 18, 52 ]
ethers.utils.base64.encode( aBytesLike ) string

Return aBytesLike encoded as a string using the base-64 encoding.

base64.encode("0x1234"); // 'EjQ=' base64.encode([ 0x12, 0x34 ]); // 'EjQ='

Recursive-Length Prefix

The Recursive Length Prefix encoding is used throughout Ethereum to serialize nested structures of Arrays and data.

ethers.utils.RLP.encode( dataObject ) string< DataHexString >

Encode a structured Data Object into its RLP-encoded representation.

RLP.encode("0x12345678"); // '0x8412345678' RLP.encode([ "0x12345678" ]); // '0xc58412345678' RLP.encode([ new Uint8Array([ 0x12, 0x34, 0x56, 0x78 ]) ]); // '0xc58412345678' RLP.encode([ [ "0x42", [ "0x43" ] ], "0x12345678", [ ] ]); // '0xcac342c1438412345678c0' RLP.encode([ ]); // '0xc0'
ethers.utils.RLP.decode( aBytesLike ) DataObject

Decode an RLP-encoded aBytesLike into its structured Data Object.

All Data components will be returned as a DataHexString.

RLP.decode("0x8412345678"); // '0x12345678' RLP.decode("0xcac342c1438412345678c0"); // [ // [ // '0x42', // [ // '0x43' // ] // ], // '0x12345678', // [] // ] RLP.decode("0xc0"); // []

Data Object

A Data Object is a recursive structure which is used to serialize many internal structures in Ethereum. Each Data Object can either be:

Examples

  • "0x1234"
  • [ "0x1234", [ "0xdead", "0xbeef" ], [ ] ]

FixedNumber

A FixedNumber is a fixed-width (in bits) number with an internal base-10 divisor, which allows it to represent a decimal fractional component.

Creating Instances

The FixedNumber constructor cannot be called directly. There are several static methods for creating a FixedNumber.

FixedNumber.from( value [ , format = "fixed" ] ) FixedNumber

Returns an instance of a FixedNumber for value as a format.

FixedNumber.fromBytes( aBytesLike [ , format = "fixed" ] ) FixedNumber

Returns an instance of a FixedNumber for value as a format.

FixedNumber.fromString( value [ , format = "fixed" ] ) FixedNumber

Returns an instance of a FixedNumber for value as a format. The value must not contain more decimals than the format permits.

FixedNumber.fromValue( value [ , decimals = 0 [ , format = "fixed" ] ] ) FixedNumber

Returns an instance of a FixedNumber for value with decimals as a format.

Properties

fixednumber.format

The FixedFormat of fixednumber.

Methods

Math Operations

fixednumber.addUnsafe( otherValue ) FixedNumber

Returns a new FixedNumber with the value of fixedvalue + otherValue.

fixednumber.subUnsafe( otherValue ) FixedNumber

Returns a new FixedNumber with the value of fixedvalue - otherValue.

fixednumber.mulUnsafe( otherValue ) FixedNumber

Returns a new FixedNumber with the value of fixedvalue × otherValue.

fixednumber.divUnsafe( otherValue ) FixedNumber

Returns a new FixedNumber with the value of fixedvalue ÷ otherValue.

fixednumber.round( [ decimals = 0 ] ) FixedNumber

Returns a new FixedNumber with the value of fixedvalue rounded to decimals.

Comparison and Equivalence

FixedNumber.isZero( ) boolean

Returns true if and only if the value of FixedNumber is zero.

Conversion

fixednumber.toFormat( format ) FixedNumber

Returns a new FixedNumber with the value of fixedvalue with format.

fixednumber.toHexString( ) string

Returns a HexString representation of fixednumber.

fixednumber.toString( ) string

Returns a string representation of fixednumber.

fixednumber.toUnsafeFloat( ) float

Returns a floating-point JavaScript number value of fixednumber. Due to rounding in JavaScript numbers, the value is only approximate.

Inspection

FixedNumber.isFixedNumber( value ) boolean

Returns true if and only if value is a FixedNumber.

FixedFormat

A FixedFormat is a simple object which represents a decimal (base-10) Fixed-Point data representation. Usually using this class directly is unnecessary, as passing in a Format Strings directly into the FixedNumber will automatically create this.

Format Strings

A format string is composed of three components, including signed-ness, bit-width and number of decimals.

A signed format string begins with fixed, which an unsigned format string begins with ufixed, followed by the width (in bits) and the number of decimals.

The width must be congruent to 0 mod 8 (i.e. (width % 8) == 0) and no larger than 256 bits and the number of decimals must be no larger than 80.

For example:

Creating Instances

FixedFormat.from( value = "fixed128x18" ) FixedFormat

Returns a new instance of a FixedFormat defined by value. Any valid Format Strings may be passed in as well as any object which has any of signed, width and decimals defined, including a FixedFormat object.

Properties

fixedFormat.signed boolean

The signed-ness of fixedFormat, true if negative values are supported.

fixedFormat.width number

The width (in bits) of fixedFormat.

fixedFormat.decimals number

The number of decimal points of fixedFormat.

fixedFormat.name string

The name of the fixedFormat, which can be used to recreate the format and is the string that the Solidity language uses to represent this format.

"fixed"

A shorthand for fixed128x18.

Hashing Algorithms

There are many hashing algorithms used throughout the blockchain space as well as some more complex usages which require utilities to facilitate these common operations.

Cryptographic Hash Functions

The Cryptographic Hash Functions are a specific family of hash functions.

ethers.utils.id( text ) string< DataHexString< 32 > >

The Ethereum Identity function computes the KECCAK256 hash of the text bytes.

ethers.utils.keccak256( aBytesLike ) string< DataHexString< 32 > >

Returns the KECCAK256 digest aBytesLike.

ethers.utils.ripemd160( aBytesLike ) string< DataHexString< 20 > >

Returns the RIPEMD-160 digest of aBytesLike.

ethers.utils.sha256( aBytesLike ) string< DataHexString< 32 > >

Returns the SHA2-256 digest of aBytesLike.

ethers.utils.sha512( aBytesLike ) string< DataHexString< 64 > >

Returns the SHA2-512 digest of aBytesLike.

KECCAK256
utils.keccak256([ 0x12, 0x34 ]) // '0x56570de287d73cd1cb6092bb8fdee6173974955fdef345ae579ee9f475ea7432' utils.keccak256("0x") // '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' utils.keccak256("0x1234") // '0x56570de287d73cd1cb6092bb8fdee6173974955fdef345ae579ee9f475ea7432' // The value MUST be data, such as: // - an Array of numbers // - a data hex string (e.g. "0x1234") // - a Uint8Array // Do NOT use UTF-8 strings that are not a DataHexstring utils.keccak256("hello world") // [Error: invalid arrayify value] { // argument: 'value', // code: 'INVALID_ARGUMENT', // reason: 'invalid arrayify value', // value: 'hello world' // } // If needed, convert strings to bytes first: utils.keccak256(utils.toUtf8Bytes("hello world")) // '0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad' // Or equivalently use the identity function: utils.id("hello world") // '0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad' // Keep in mind that the string "0x1234" represents TWO // bytes (i.e. [ 0x12, 0x34 ]. If you wish to compute the // hash of the 6 characters "0x1234", convert it to UTF-8 // bytes first using utils.toUtf8Bytes. // Consider the following examples: // Hash of TWO (2) bytes: utils.keccak256("0x1234") // '0x56570de287d73cd1cb6092bb8fdee6173974955fdef345ae579ee9f475ea7432' // Hash of TWO (2) bytes: (same result) utils.keccak256([ 0x12, 0x34 ]) // '0x56570de287d73cd1cb6092bb8fdee6173974955fdef345ae579ee9f475ea7432' bytes = utils.toUtf8Bytes("0x1234") // Uint8Array [ 48, 120, 49, 50, 51, 52 ] // Hash of SIX (6) characters (different than above) utils.keccak256(bytes) // '0x1ac7d1b81b7ba1025b36ccb86723da6ee5a87259f1c2fd5abe69d3200b512ec8' // Hash of SIX (6) characters (same result) utils.id("0x1234") // '0x1ac7d1b81b7ba1025b36ccb86723da6ee5a87259f1c2fd5abe69d3200b512ec8'
RIPEMD160
utils.ripemd160("0x") // '0x9c1185a5c5e9fc54612808977ee8f548b2258d31' utils.ripemd160("0x1234") // '0xc39867e393cb061b837240862d9ad318c176a96d'
SHA-2
utils.sha256("0x") // '0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' utils.sha256("0x1234") // '0x3a103a4e5729ad68c02a678ae39accfbc0ae208096437401b7ceab63cca0622f' utils.sha512("0x") // '0xcf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e' utils.sha512("0x1234") // '0x4c54886c9821195522d88ff4705c3e0c686b921054421e6ea598739c29c26e1ee75419aaceec94dd2e3c0dbb82ecf895c9f61215f375de6d800d9b99d3d4b816'

HMAC

ethers.utils.computeHmac( algorithm , key , data ) string< DataHexString >

Returns the HMAC of data with key using the Algorithm algorithm.

HMAC Supported Algorithms

ethers.utils.SupportedAlgorithm.sha256 string

Use the SHA2-256 hash algorithm.

ethers.utils.SupportedAlgorithm.sha512 string

Use the SHA2-512 hash algorithm.

HMAC
const key = "0x0102" const data = "0x1234" utils.computeHmac("sha256", key, data) // '0x7553df81c628815cf569696cad13a37c606c5058df13d9dff4fee2cf5e9b5779'

Hashing Helpers

ethers.utils.hashMessage( message ) string< DataHexString< 32 > >

Computes the EIP-191 personal message digest of message. Personal messages are converted to UTF-8 bytes and prefixed with \x19Ethereum Signed Message: and the length of message.

Hashing Messages
// Hashing a string message utils.hashMessage("Hello World") // '0xa1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2' // Hashing binary data (also "Hello World", but as bytes) utils.hashMessage( [ 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 ]) // '0xa1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2' // NOTE: It is important to understand how strings and binary // data is handled differently. A string is ALWAYS processed // as the bytes of the string, so a hexstring MUST be // converted to an ArrayLike object first. // Hashing a hex string is the same as hashing a STRING // Note: this is the hash of the 4 characters [ '0', 'x', '4', '2' ] utils.hashMessage("0x42") // '0xf0d544d6e4a96e1c08adc3efabe2fcb9ec5e28db1ad6c33ace880ba354ab0fce' // Hashing the binary data // Note: this is the hash of the 1 byte [ 0x42 ] utils.hashMessage([ 0x42 ]) // '0xd18c12b87124f9ceb7e1d3a5d06a5ac92ecab15931417e8d1558d9a263f99d63' // Hashing the binary data // Note: similarly, this is the hash of the 1 byte [ 0x42 ] utils.hashMessage(utils.arrayify("0x42")) // '0xd18c12b87124f9ceb7e1d3a5d06a5ac92ecab15931417e8d1558d9a263f99d63'
ethers.utils.namehash( name ) string< DataHexString< 32 > >

Returns the ENS Namehash of name.

Namehash
utils.namehash("") // '0x0000000000000000000000000000000000000000000000000000000000000000' utils.namehash("eth") // '0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae' utils.namehash("ricmoo.firefly.eth") // '0x0bcad17ecf260d6506c6b97768bdc2acfb6694445d27ffd3f9c1cfbee4a9bd6d' utils.namehash("ricmoo.xyz") // '0x7d56aa46358ba2f8b77d8e05bcabdd2358370dcf34e87810f8cea77ecb3fc57d'

Typed Data Encoder

The TypedDataEncoder is used to compute the various encoded data required for EIP-712 signed data.

Signed data requires a domain, list of structures and their members and the data itself.

The domain is an object with values for any of the standard domain properties.

The types is an object with each property being the name of a structure, mapping to an array of field descriptions. It should not include the EIP712Domain property unless it is required as a child structure of another.

Experimental Feature (this exported class name will change)

This is still an experimental feature. If using it, please specify the exact version of ethers you are using (e.g. spcify "5.0.18", not "^5.0.18") as the exported class name will be renamed from _TypedDataEncoder to TypedDataEncoder once it has been used in the field a bit.

ethers.utils._TypedDataEncoder.from( types ) [TypedDataEncoder]

Creates a new TypedDataEncoder for types. This object is a fairly low-level object that most developers should not require using instances directly.

Most developers will find the static class methods below the most useful.

TypedDataEncoder.encode( domain , types , values ) string

Encodes the Returns the hashed EIP-712 domain.

TypedDataEncoder.getPayload( domain , types , value ) any

Returns the standard payload used by various JSON-RPC eth_signTypedData* calls.

All domain values and entries in value are normalized and the types are verified.

TypedDataEncoder.getPrimaryType( types ) string

Constructs a directed acyclic graph of the types and returns the root type, which can be used as the primaryType for EIP-712 payloads.

TypedDataEncoder.hash( domain , types , values ) string< DataHexString< 32 > >

Returns the computed EIP-712 hash.

TypedDataEncoder.hashDomain( domain ) string< DataHexString< 32 > >

Returns the hashed EIP-712 domain.

TypedDataEncoder.resolveNames( domain , types , value , resolveName ) Promise< any >

Returns a copy of value, where any leaf value with a type of address will have been recursively replacedwith the value of calling resolveName with that value.

Typed Data Example
domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC' }; // The named list of all type definitions types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' } ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' } ] }; // The data to sign value = { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826' }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB' }, contents: 'Hello, Bob!' }; TypedDataEncoder.encode(domain, types, value) // '0x1901f2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090fc52c0ee5d84264471806290a3f2c4cecfc5490626bf912d01f240d7a274b371e' TypedDataEncoder.getPayload(domain, types, value) // { // domain: { // chainId: '1', // name: 'Ether Mail', // verifyingContract: '0xcccccccccccccccccccccccccccccccccccccccc', // version: '1' // }, // message: { // contents: 'Hello, Bob!', // from: { // name: 'Cow', // wallet: '0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826' // }, // to: { // name: 'Bob', // wallet: '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' // } // }, // primaryType: 'Mail', // types: { // EIP712Domain: [ // { // name: 'name', // type: 'string' // }, // { // name: 'version', // type: 'string' // }, // { // name: 'chainId', // type: 'uint256' // }, // { // name: 'verifyingContract', // type: 'address' // } // ], // Mail: [ // { // name: 'from', // type: 'Person' // }, // { // name: 'to', // type: 'Person' // }, // { // name: 'contents', // type: 'string' // } // ], // Person: [ // { // name: 'name', // type: 'string' // }, // { // name: 'wallet', // type: 'address' // } // ] // } // } TypedDataEncoder.getPrimaryType(types) // 'Mail' TypedDataEncoder.hash(domain, types, value) // '0xbe609aee343fb3c4b28e1df9e632fca64fcfaede20f02e86244efddf30957bd2' TypedDataEncoder.hashDomain(domain) // '0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f'

Solidity Hashing Algorithms

When using the Solidity abi.encodePacked(...) function, a non-standard tightly packed version of encoding is used. These functions implement the tightly packing algorithm.

ethers.utils.solidityPack( types , values ) string< DataHexString >

Returns the non-standard encoded values packed according to their respective type in types.

ethers.utils.solidityKeccak256( types , values ) string< DataHexString< 32 > >

Returns the KECCAK256 of the non-standard encoded values packed according to their respective type in types.

ethers.utils.soliditySha256( types , values ) string< DataHexString< 32 > >

Returns the SHA2-256 of the non-standard encoded values packed according to their respective type in types.

Solidity Hashing
utils.solidityPack([ "int16", "uint48" ], [ -1, 12 ]) // '0xffff00000000000c' utils.solidityPack([ "string", "uint8" ], [ "Hello", 3 ]) // '0x48656c6c6f03' utils.solidityKeccak256([ "int16", "uint48" ], [ -1, 12 ]) // '0x81da7abb5c9c7515f57dab2fc946f01217ab52f3bd8958bc36bd55894451a93c' utils.soliditySha256([ "int16", "uint48" ], [ -1, 12 ]) // '0xa5580fb602f6e2ba9c588011dc4e6c2335e0f5d970dc45869db8f217efc6911a' // As a short example of the non-distinguished nature of // Solidity tight-packing (which is why it is inappropriate // for many things from a security point of view), consider // the following examples are all equal, despite representing // very different values and layouts. utils.solidityPack([ "string", "string" ], [ "hello", "world01" ]) // '0x68656c6c6f776f726c643031' utils.solidityPack([ "string", "string" ], [ "helloworld", "01" ]) // '0x68656c6c6f776f726c643031' utils.solidityPack([ "string", "string", "uint16" ], [ "hell", "oworld", 0x3031 ]) // '0x68656c6c6f776f726c643031' utils.solidityPack([ "uint96" ], [ "32309054545061485574011236401" ]) // '0x68656c6c6f776f726c643031'

HD Wallet

The Hierarchal Deterministic (HD) Wallet was a standard created for Bitcoin, but lends itself well to a wide variety of Blockchains which rely on secp256k1 private keys.

For a more detailed technical understanding:

Types

Constants

ethers.utils.defaultPath "m/44'/60'/0'/0/0"

The default path for Ethereum in an HD Wallet

Mnemonic

mnemonic.phrase string

The mnemonic phrase for this mnemonic. It is 12, 15, 18, 21 or 24 words long and separated by the whitespace specified by the locale.

mnemonic.path string

The HD path for this mnemonic.

mnemonic.locale string

The language of the wordlist this mnemonic is using.

HDNode

Creating Instances

ethers.HDNode.fromMnemonic( phrase [ , password [ , wordlist ] ] ) HDNode

Return the HDNode for phrase with the optional password and wordlist.

ethers.HDNode.fromSeed( aBytesLike ) HDNode

Return the HDNode for the seed aBytesLike.

ethers.HDNode.fromExtendedKey( extendedKey ) HDNode

Return the HDNode for the extendedKey. If extendedKey was neutered, the HDNode will only be able to compute addresses and not private keys.

Properties

hdNode.privateKey string< DataHexString< 32 > >

The private key for this HDNode.

hdNode.publicKey string< DataHexString< 33 > >

The (compresses) public key for this HDNode.

hdNode.fingerprint string< DataHexString< 4 > >

The fingerprint is meant as an index to quickly match parent and children nodes together, however collisions may occur and software should verify matching nodes.

Most developers will not need to use this.

hdNode.parentFingerprint string< DataHexString< 4 > >

The fingerprint of the parent node. See fingerprint for more details.

Most developers will not need to use this.

hdNode.address string< Address >

The address of this HDNode.

hdNode.mnemonic Mnemonic

The mnemonic of this HDNode, if known.

hdNode.path string

The path of this HDNode, if known. If the mnemonic is also known, this will match mnemonic.path.

hdNode.chainCode string< DataHexString< 32 > >

The chain code is used as a non-secret private key which is then used with EC-multiply to provide the ability to derive addresses without the private key of child non-hardened nodes.

Most developers will not need to use this.

hdNode.index number

The index of this HDNode. This will match the last component of the path.

Most developers will not need to use this.

hdNode.depth number

The depth of this HDNode. This will match the number of components (less one, the m/) of the path.

Most developers will not need to use this.

hdNode.extendedKey string

A serialized string representation of this HDNode. Not all properties are included in the serialization, such as the mnemonic and path, so serializing and deserializing (using the fromExtendedKey class method) will result in reduced information.

Methods

hdNode.neuter( ) HDNode

Return a new instance of hdNode with its private key removed but all other properties preserved. This ensures that the key can not leak the private key of itself or any derived children, but may still be used to compute the addresses of itself and any non-hardened children.

hdNode.derivePath( path ) HDNode

Return a new HDNode which is the child of hdNode found by deriving path.

Other Functions

ethers.utils.mnemonicToSeed( phrase [ , password ] ) string< DataHexString< 64 > >

Convert a mnemonic phrase to a seed, according to BIP-39.

ethers.utils.mnemonicToEntropy( phrase [ , wordlist ] ) string< DataHexString >

Convert a mnemonic phrase to its entropy, according to BIP-39.

ethers.utils.isValidMnemonic( phrase [ , wordlist ] ) boolean

Returns true if phrase is a valid mnemonic phrase, by testing the checksum.

Logging

These are just a few simple logging utilities provided to simplify and standardize the error facilities across the Ethers library.

The Logger library has zero dependencies and is intentionally very light so it can be easily included in each library.

The Censorship functionality relies on one instance of the Ethers library being included. In large bundled packages or when npm link is used, this may not be the case. If you require this functionality, ensure that your bundling is configured properly.

Logger

new ethers.utils.Logger( version )

Create a new logger which will include version in all errors thrown.

Logger.globalLogger( ) Logger

Returns the singleton global logger.

Logging Output

logger.debug( ...args ) void

Log debugging information.

logger.info( ...args ) void

Log generic information.

logger.warn( ...args ) void

Log warnings.

Errors

These functions honor the current Censorship and help create a standard error model for detecting and processing errors within Ethers.

logger.makeError( message [ , code = UNKNOWN_ERROR [ , params ] ] ) Error

Create an Error object with message and an optional code and additional params set. This is useful when an error is needed to be rejected instead of thrown.

logger.throwError( message [ , code = UNKNOWN_ERROR [ , params ] ] ) never

Throw an Error with message and an optional code and additional params set.

logger.throwArgumentError( message , name , value ) never

Throw an INVALID_ARGUMENT Error with name and value.

Usage Validation

There can be used to ensure various properties and actions are safe.

logger.checkAbstract( target , kind ) void

If target is kind, throws a UNSUPPORTED_OPERATION error otherwise performs the same operations as checkNew.

This is useful for ensuring abstract classes are not being instantiated.

logger.checkArgumentCount( count , expectedCount [ , message ) void

If count is not equal to expectedCount, throws a MISSING_ARGUMENT or UNEXPECTED_ARGUMENT error.

logger.checkNew( target , kind ) void

If target is not a valid this or target value, throw a MISSING_NEW error. This is useful to ensure callers of a Class are using new.

logger.checkNormalize( message ) void

Check that the environment has a correctly functioning String.normalize. If not, a UNSUPPORTED_OPERATION error is thrown.

logger.checkSafeUint53( value [ , message ] ) void

If value is not safe as a JavaScript number, throws a NUMERIC_FAULT error.

Censorship

Logger.setCensorship( censor [ , permanent = false ] ) void

Set error censorship, optionally preventing errors from being uncensored.

In production applications, this prevents any error from leaking information by masking the message and values of errors.

This can impact debugging, making it substantially more difficult.

Logger.setLogLevel( logLevel ) void

Set the log level, to suppress logging output below a particular log level.

Errors

Every error in Ethers has a code value, which is a string that will match one of the following error codes.

Generic Error Codes

Logger.errors.NOT_IMPLEMENTED

The operation is not implemented. This may occur when calling a method on a sub-class that has not fully implemented its abstract superclass.

Logger.errors.SERVER_ERROR

There was an error communicating with a server.

This may occur for a number of reasons, for example:

  • a CORS issue; this is quite often the problem and also the hardest to diagnose and fix, so it is very beneficial to familiarize yourself with CORS; some backends allow you configure your CORS, such as the geth command-line or conifguration files or the INFURA and Alchemy dashboards by specifing allowed Origins, methods, etc.
  • an SSL issue; for example, if you are trying to connect to a local node via HTTP but are serving the content from a secure HTTPS website
  • a link issue; a firewall is preventing the traffic from reaching the server
  • a server issue; the server is down, or is returning 500 error codes
  • a backend DDoS mitigation proxy; for example, Etherscan operates behind a Cloudflare proxy, which will block traffic if the request is sent via specific User Agents or the client fingerprint is detected as a bot in some cases

Logger.errors.TIMEOUT

A timeout occurred.

Logger.errors.UNKNOWN_ERROR

A generic unknown error.

Logger.errors.UNSUPPORTED_OPERATION

The operation is not supported.

This can happen for a variety reasons, for example:

Safety Error Codes

Logger.errors.BUFFER_OVERRUN

The amount of data needed is more than the amount of data required, which would cause the data buffer to read past its end.

This can occur if a contract erroneously returns invalid ABI-encoded data or RLP data is malformed.

Logger.errors.NUMERIC_FAULT

There was an invalid operation done on numeric values.

Common cases of this occur when there is overflow, arithmetic underflow in fixed numeric types or division by zero.

Usage Error Codes

Logger.errors.INVALID_ARGUMENT

The type or value of an argument is invalid. This will generally also include the name and value of the argument. Any function which accepts sensitive data (such as a private key) will include the string "[[REDACTED]]" instead of the value passed in.

Logger.errors.MISSING_ARGUMENT

An expected parameter was not specified.

Logger.errors.MISSING_NEW

An object is a Class, but is not being called with new.

Logger.errors.UNEXPECTED_ARGUMENT

Too many parameters we passed into a function.

Ethereum Error Codes

Logger.errors.CALL_EXCEPTION

An attempt to call a blockchain contract (getter) resulted in a revert or other error, such as insufficient gas (out-of-gas) or an invalid opcode. This can also occur during gas estimation or if waiting for a TransactionReceipt which failed during execution.

Consult the contract to determine the cause, such as a failed condition in a require statement. The reason property may provide more context for the cause of this error.

Logger.errors.INSUFFICIENT_FUNDS

The account is attempting to make a transaction which costs more than is available.

A sending account must have enough ether to pay for the value, the gas limit (at the gas price) as well as the intrinsic cost of data. The intrinsic cost of data is 4 gas for each zero byte and 68 gas for each non-zero byte, as well as 35000 gas if a transaction contains no to property and is therefore expected to create a new account.

Logger.errors.NETWORK_ERROR

An Ethereum network validation error, such as an invalid chain ID.

Logger.errors.NONCE_EXPIRED

The nonce being specified has already been used in a mined transaction.

Logger.errors.REPLACEMENT_UNDERPRICED

When replacing a transaction, by using a nonce which has already been sent to the network, but which has not been mined yet the new transaction must specify a higher gas price.

This error occurs when the gas price is insufficient to bribe the transaction pool to prefer the new transaction over the old one. Generally, the new gas price should be about 50% + 1 wei more, so if a gas price of 10 gwei was used, the replacement should be 15.000000001 gwei. This is not enforced by the protocol, as it deals with unmined transactions, and can be configured by each node, however to ensure a transaction is propagated to a miner it is best practice to follow the defaults most nodes have enabled.

Logger.errors.TRANSACTION_REPLACED

When a transaction has been replaced by the user, by broadcasting a new transaction with the same nonce as an existing in-flight (unmined) transaction in the mempool, this error will occur while waiting if the transaction being waited for has become invalidated by that other transaction.

This can happen for several reasons, but most commonly because the user has increased the gas price (which changes the transaction hash) to "speed up" a transaction or if a user has "cancelled" the transaction in their client. In either case this is usually accomplished by bribing the miners with a higher gas priced transaction.

This error will have the additional properties, cancelled, hash, reason, receipt and replacement.

See the TransactionResponse for the wait method for more details.

Logger.errors.UNPREDICTABLE_GAS_LIMIT

When estimating the required amount of gas for a transaction, a node is queried for its best guess.

If a node is unable (or unwilling) to predict the cost, this error occurs.

The best remedy for this situation is to specify a gas limit in the transaction manually.

This error can also indicate that the transaction is expected to fail regardless, if for example an account with no tokens is attempting to send a token.

Log Levels

Logger.levels.DEBUG

Log all output, including debugging information.

Logger.levels.INFO

Only log output for informational, warnings and errors.

Logger.levels.WARNING

Only log output for warnings and errors.

Logger.levels.ERROR

Only log output for errors.

Logger.levels.OFF

Do not output any logs.

Property Utilities

This is a collection of utility functions used for handling properties in a platform-safe way.

The next major version of ethers will no longer be compatible with ES3, so many of these will be removed in favor of the built-in options available in ES2015 and above.

ethers.utils.checkProperties( object , check ) void

Checks that object only contains properties included in check, and throws INVALID_ARGUMENT if not.

ethers.utils.deepCopy( anObject ) any

Creates a recursive copy of anObject. Frozen (i.e. and other known immutable) objects are copied by reference.

ethers.utils.defineReadOnly( anObject , name , value ) void

Uses the Object.defineProperty method to set a read-only property on an object.

ethers.utils.getStatic( aConstructor , key ) any

Recursively check for a static method key on an inheritance chain from aConstructor to all ancestors.

This is used to mimic behaviour in other languages where this in a static method will also search ancestors.

ethers.utils.resolveProperties( anObject ) Promise< any >

Retruns a Promise which resolves all child values on anObject.

ethers.utils.shallowCopy( anObject ) any

Returns a shallow copy of anObject. This is the same as using Object.assign({ }, anObject).

Signing Key

new ethers.utils.SigningKey( privateKey )

Create a new SigningKey for privateKey.

signingKey.privateKey string< DataHexString< 32 > >

The private key for this Signing Key.

signingKey.publicKey string< DataHexString< 65 > >

The uncompressed public key for this Signing Key. It will always be 65 bytes (130 nibbles) and begins with 0x04.

signingKey.compressedPublicKey string< DataHexString< 33 > >

The compressed public key for this Signing Key. It will always be 33 bytes (66 nibbles) and begins with either 0x02 or 0x03.

signingKey.signDigest( digest ) Signature

Sign the digest and return the signature.

signingKey.computeSharedSecret( otherKey ) string< DataHexString< 32 > >

Compute the ECDH shared secret with otherKey. The otherKey may be either a public key or a private key, but generally will be a public key from another party.

It is best practice that each party computes the hash of this before using it as a symmetric key.

SigningKey.isSigningKey( anObject ) boolean

Returns true if anObject is a SigningKey.

Other Functions

ethers.utils.verifyMessage( message , signature ) string< Address >

Returns the address that signed message producing signature. The signature may have a non-canonical v (i.e. does not need to be 27 or 28), in which case it will be normalized to compute the `recoveryParam` which will then be used to compute the address; this allows systems which use the v to encode additional data (such as EIP-155) to be used since the v parameter is still completely non-ambiguous.

ethers.utils.verifyTypedData( domain , types , value , signature ) string< Address >

Returns the address that signed the EIP-712 value for the domain and types to produce the signature.

ethers.utils.recoverPublicKey( digest , signature ) string< DataHexString< 65 > >

Returns the uncompressed public key (i.e. the first byte will be 0x04) of the private key that was used to sign digest which gave the signature.

ethers.utils.computePublicKey( key [ , compressed = false ] ) string< DataHexString >

Computes the public key of key, optionally compressing it. The key can be any form of public key (compressed or uncompressed) or a private key.

Strings

A String is a representation of a human-readable input of output, which are often taken for granted.

When dealing with blockchains, properly handling human-readable and human-provided data is important to prevent loss of funds, assets, incorrect permissions, etc.

Bytes32String

A string in Solidity is length prefixed with its 256-bit (32 byte) length, which means that even short strings require 2 words (64 bytes) of storage.

In many cases, we deal with short strings, so instead of prefixing the string with its length, we can null-terminate it and fit it in a single word (32 bytes). Since we need only a single byte for the null termination, we can store strings up to 31 bytes long in a word.

Note

Strings that are 31 bytes long may contain fewer than 31 characters, since UTF-8 requires multiple bytes to encode international characters.

ethers.utils.parseBytes32String( aBytesLike ) string

Returns the decoded string represented by the Bytes32 encoded data.

ethers.utils.formatBytes32String( text ) string< DataHexString< 32 > >

Returns a bytes32 string representation of text. If the length of text exceeds 31 bytes, it will throw an error.

UTF-8 Strings

ethers.utils.toUtf8Bytes( text [ , form = current ] ) Uint8Array

Returns the UTF-8 bytes of text, optionally normalizing it using the UnicodeNormalizationForm form.

ethers.utils.toUtf8CodePoints( text [ , form = current ] ) Array< number >

Returns the Array of codepoints of text, optionally normalized using the UnicodeNormalizationForm form.

Note

This function correctly splits each user-perceived character into its codepoint, accounting for surrogate pairs. This should not be confused with string.split(""), which destroys surrogate pairs, splitting between each UTF-16 codeunit instead.

ethers.utils.toUtf8String( aBytesLike [ , onError = error ] ) string

Returns the string represented by the UTF-8 bytes of aBytesLike.

The onError is a Custom UTF-8 Error function and if not specified it defaults to the error function, which throws an error on any UTF-8 error.

UnicodeNormalizationForm

There are several commonly used forms when normalizing UTF-8 data, which allow strings to be compared or hashed in a stable way.

ethers.utils.UnicodeNormalizationForm.current

Maintain the current normalization form.

ethers.utils.UnicodeNormalizationForm.NFC

The Composed Normalization Form. This form uses single codepoints which represent the fully composed character.

For example, the é is a single codepoint, 0x00e9.

ethers.utils.UnicodeNormalizationForm.NFD

The Decomposed Normalization Form. This form uses multiple codepoints (when necessary) to compose a character.

For example, the é is made up of two codepoints, "0x0065" (which is the letter "e") and "0x0301" which is a special diacritic UTF-8 codepoint which indicates the previous character should have an acute accent.

ethers.utils.UnicodeNormalizationForm.NFKC

The Composed Normalization Form with Canonical Equivalence. The Canonical representation folds characters which have the same syntactic representation but different semantic meaning.

For example, the Roman Numeral I, which has a UTF-8 codepoint "0x2160", is folded into the capital letter I, "0x0049".

ethers.utils.UnicodeNormalizationForm.NFKD

The Decomposed Normalization Form with Canonical Equivalence. See NFKC for more an example.

Note

Only certain specified characters are folded in Canonical Equivalence, and thus it should not be considered a method to achieve any level of security from homoglyph attacks.

Custom UTF-8 Error Handling

When converting a string to its codepoints, there is the possibility of invalid byte sequences. Since certain situations may need specific ways to handle UTF-8 errors, a custom error handling function can be used, which has the signature:

errorFunction( reason , offset , bytes , output [ , badCodepoint ] ) number

The reason is one of the UTF-8 Error Reasons, offset is the index into bytes where the error was first encountered, output is the list of codepoints already processed (and may be modified) and in certain Error Reasons, the badCodepoint indicates the currently computed codepoint, but which would be rejected because its value is invalid.

This function should return the number of bytes to skip past keeping in mind the value at offset will already be consumed.

UTF-8 Error Reasons

ethers.utils.Utf8ErrorReason.BAD_PREFIX

A byte was encountered which is invalid to begin a UTF-8 byte sequence with.

ethers.utils.Utf8ErrorReason.MISSING_CONTINUE

A UTF-8 sequence was begun, but did not have enough continuation bytes for the sequence. For this error the ofset is the index at which a continuation byte was expected.

ethers.utils.Utf8ErrorReason.OUT_OF_RANGE

The computed codepoint is outside the range for valid UTF-8 codepoints (i.e. the codepoint is greater than 0x10ffff). This reason will pass the computed badCountpoint into the custom error function.

ethers.utils.Utf8ErrorReason.OVERLONG

Due to the way UTF-8 allows variable length byte sequences to be used, it is possible to have multiple representations of the same character, which means overlong sequences allow for a non-distinguished string to be formed, which can impact security as multiple strings that are otherwise equal can have different hashes.

Generally, overlong sequences are an attempt to circumvent some part of security, but in rare cases may be produced by lazy libraries or used to encode the null terminating character in a way that is safe to include in a char*.

This reason will pass the computed badCountpoint into the custom error function, which is actually a valid codepoint, just one that was arrived at through unsafe methods.

ethers.utils.Utf8ErrorReason.OVERRUN

The string does not have enough characters remaining for the length of this sequence.

ethers.utils.Utf8ErrorReason.UNEXPECTED_CONTINUE

This error is similar to BAD_PREFIX, since a continuation byte cannot begin a valid sequence, but many may wish to process this differently. However, most developers would want to trap this and perform the same operation as a BAD_PREFIX.

ethers.utils.Utf8ErrorReason.UTF16_SURROGATE

The computed codepoint represents a value reserved for UTF-16 surrogate pairs. This reason will pass the computed surrogate half badCountpoint into the custom error function.

Provided UTF-8 Error Handling Functions

There are already several functions available for the most common situations.

ethers.utils.Utf8ErrorFuncs.error

The will throw an error on any error with a UTF-8 sequence, including invalid prefix bytes, overlong sequences, UTF-16 surrogate pairs.

ethers.utils.Utf8ErrorFuncs.ignore

This will drop all invalid sequences (by consuming invalid prefix bytes and any following continuation bytes) from the final string as well as permit overlong sequences to be converted to their equivalent string.

ethers.utils.Utf8ErrorFuncs.replace

This will replace all invalid sequences (by consuming invalid prefix bytes and any following continuation bytes) with the UTF-8 Replacement Character, (i.e. U+FFFD).

Transactions

Types

UnsignedTransaction

An unsigned transaction represents a transaction that has not been signed and its values are flexible as long as they are not ambiguous.

unsignedTransaction.to string< Address >

The address this transaction is to.

unsignedTransaction.nonce number

The nonce of this transaction.

unsignedTransaction.gasLimit BigNumberish

The gas limit for this transaction.

unsignedTransaction.gasPrice BigNumberish

The gas price for this transaction.

unsignedTransaction.maxFeePerGas BigNumberish

The maximum fee per unit of gas for this transaction.

unsignedTransaction.maxPriorityFeePerGas BigNumberish

The maximum priority fee per unit of gas for this transaction.

unsignedTransaction.data BytesLike

The data for this transaction.

unsignedTransaction.value BigNumberish

The value (in wei) for this transaction.

unsignedTransaction.chainId number

The chain ID for this transaction. If the chain ID is 0 or null, then EIP-155 is disabled and legacy signing is used, unless overridden in a signature.

Transaction

A generic object to represent a transaction.

transaction.hash string< DataHexString< 32 > >

The transaction hash, which can be used as an identifier for transaction. This is the keccak256 of the serialized RLP encoded representation of transaction.

transaction.to string< Address >

The address transaction is to.

transaction.from string< Address >

The address transaction is from.

transaction.nonce number

The nonce for transaction. Each transaction sent to the network from an account includes this, which ensures the order and non-replayability of a transaction. This must be equal to the current number of transactions ever sent to the network by the from address.

transaction.gasLimit BigNumber

The gas limit for transaction. An account must have enough ether to cover the gas (at the specified gasPrice). Any unused gas is refunded at the end of the transaction, and if there is insufficient gas to complete execution, the effects of the transaction are reverted, but the gas is fully consumed and an out-of-gas error occurs.

transaction.gasPrice null | BigNumber

The price (in wei) per unit of gas for transaction.

For EIP-1559 transactions, this will be null.

transaction.maxFeePerGas BigNumber

The maximum price (in wei) per unit of gas for transaction.

For transactions that are not EIP-1559 transactions, this will be null.

transaction.maxPriorityFeePerGas BigNumber

The priority fee price (in wei) per unit of gas for transaction.

For transactions that are not EIP-1559 transactions, this will be null.

transaction.data BytesLike

The data for transaction. In a contract this is the call data.

transaction.value BigNumber

The value (in wei) for transaction.

transaction.chainId number

The chain ID for transaction. This is used as part of EIP-155 to prevent replay attacks on different networks.

For example, if a transaction was made on goerli with an account also used on homestead, it would be possible for a transaction signed on goerli to be executed on homestead, which is likely unintended.

There are situations where replay may be desired, however these are very rare and it is almost always recommended to specify the chain ID.

transaction.r string< DataHexString< 32 > >

The r portion of the elliptic curve signatures for transaction. This is more accurately, the x coordinate of the point r (from which the y can be computed, along with v).

transaction.s string< DataHexString< 32 > >

The s portion of the elliptic curve signatures for transaction.

transaction.v number

The v portion of the elliptic curve signatures for transaction. This is used to refine which of the two possible points a given x-coordinate can have, and in EIP-155 is additionally used to encode the chain ID into the serialized transaction.

Functions

ethers.utils.accessListify( anAcceslistish ) AccessList

Normalizes the AccessListish anAccessListish into an AccessList.

This is useful for other utility functions which wish to remain flexible as to the input parameter for access lists, such as when creating a Signer which needs to manipulate a possibly typed transaction envelope.

ethers.utils.parseTransaction( aBytesLike ) Transaction

Parses the transaction properties from a serialized transaction.

ethers.utils.serializeTransaction( tx [ , signature ] ) string< DataHexString >

Computes the serialized transaction, optionally serialized with the a signature. If signature is not present, the unsigned serialized transaction is returned, which can be used to compute the hash necessary to sign.

This function uses EIP-155 if a chainId is provided, otherwise legacy serialization is used. It is highly recommended to always specify a chainId.

If signature includes a chain ID (explicitly or implicitly by using an EIP-155 v or _vs) it will be used to compute the chain ID.

If there is a mismatch between the chain ID of transaction and signature an error is thrown.

Web Utilities

ethers.utils.fetchJson( urlOrConnectionInfo [ , json [ , processFunc ] ] ) Promise< any >

Fetch and parse the JSON content from urlOrConnectionInfo, with the optional body json and optionally processing the result with processFun before returning it.

ethers.utils.poll( pollFunc [ , options ] ) Promise< any >

Repeatedly call pollFunc using the PollOptions until it returns a value other than undefined.

ConnectionInfo

connection.url string

The URL to connect to.

connection.user string

The username to use for Basic Authentication. The default is null (i.e. do not use basic authentication)

connection.password string

The password to use for Basic Authentication. The default is null (i.e. do not use basic authentication)

connection.allowInsecureAuthentication boolean

Allow Basic Authentication over non-secure HTTP. The default is false.

connection.timeout number

How long to wait (in ms) before rejecting with a timeout error. (default: 120000).

connection.headers {[key:string]:string}

Additional headers to include in the connection.

connection.skipFetchSetup boolean

Normally a connection will specify the default values for a connection such as CORS-behavior and caching policy, to ensure compatibility across platforms. On some services, such as Cloudflare Workers, specifying any value (inclluding the default values) will cause failure. Setting this to true will prevent any values being passed to the underlying API.

connection.errorPassThrough boolean

If false, any server error is thrown as a SERVER_ERROR, otherwise a the processFunc is called with response including the error status intact. (default: false)

connection.allowGzip boolean

Allow Gzip responses. (default: false)

connection.throttleLimit boolean

How many times to retry in the event of a 429 status code.

connection.throttleSlotInterval boolean

The exponential back-off slot delay (i.e. omega), creating a staggered, increasing random delay on retries.

connection.throttleCallback boolean

Callback that allows application level hints to retry (within the throttleLimit) or quick fail.

PollOptions

options.timeout number

The amount of time (in ms) allowed to elapse before triggering a timeout error.

options.floor number

The minimum time limit to allow for Exponential Backoff.

The default is 0s.

options.ceiling number

The maximum time limit to allow for Exponential Backoff.

The default is 10s.

options.interval number

The interval used during Exponential Backoff calculation.

The default is 250ms.

options.retryLimit number

The number of times to retry in the event of an error or undefined is returned.

options.onceBlock Provider

If this is specified, the polling will wait on new blocks from provider before attempting the pollFunc again.

options.oncePoll Provider

If this is specified, the polling will occur on each poll cycle of provider before attempting the pollFunc again.

Wordlists

Wordlist

wordlist.locale string

The locale for this wordlist.

wordlist.getWord( index ) string

Returns the word at index.

wordlist.getWordIndex( word ) number

Returns the index of word within the wordlist.

wordlist.split( mnemonic ) Array< string >

Returns the mnemonic split into each individual word, according to a locale's valid whitespace character set.

wordlist.join( words ) string

Returns the mnemonic by joining words together using the whitespace that is standard for the locale.

Wordlist.check( wordlists ) string< DataHexString< 32 > >

Checks that all words map both directions correctly and return the hash of the lists. Sub-classes should use this to validate the wordlist is correct against the official wordlist hash.

Wordlist.register( wordlist [ , name ] ) void

Register a wordlist with the list of wordlists, optionally overriding the registered name.

Languages

The official wordlists available at `ethers.wordlists`. In the browser, only the english language is available by default; to include the others (which increases the size of the library), see the dist files in the `ethers` package.

ethers.wordlists.cz Wordlist

The Czech Wordlist.

ethers.wordlists.en Wordlist

The English Wordlist.

ethers.wordlists.es Wordlist

The Spanish Wordlist.

ethers.wordlists.fr Wordlist

The French Wordlist.

ethers.wordlists.it Wordlist

The Italian Wordlist.

ethers.wordlists.ja Wordlist

The Japanese Wordlist.

ethers.wordlists.ko Wordlist

The Korean Wordlist.

ethers.wordlists.zh_cn Wordlist

The Simplified Chinese Wordlist.

ethers.wordlists.zh_tw Wordlist

The Traditional Chinese Wordlist.

Other Libraries

Now that ethers is more modular, it is possible to have additional ancillary packages, which are not part of the core but optionally add functionality only needed in certain situations.

Assembly
Hardware Wallets

Assembly

This module should still be considered fairly experimental.

Ethers ASM Dialect
Utilities
Abstract Syntax Tree

Ethers ASM Dialect

This provides a quick, high-level overview of the Ethers ASM Dialect for EVM, which is defined by the Ethers ASM Dialect Grammar

Once a program is compiled by a higher level language into ASM (assembly), or hand-coded directly in ASM, it needs to be assembled into bytecode.

The assembly process performs a very small set of operations and is intentionally simple and closely related to the underlying EVM bytecode.

Operations include embedding programs within programs (for example the deployment bootstrap has the runtime embedded in it) and computing the necessary offsets for jump operations.

The Command-Line Assembler can be used to assemble an Ethers ASM Dialect file or to disassemble bytecode into its human-readable (ish) opcodes and literals.

Opcodes

An Opcode may be provided in either a functional or instructional syntax. For Opcodes that require parameters, the functional syntax is recommended and the instructional syntax will raise a warning.

@TODO: Examples

Labels

A Label is a position in the program which can be jumped to. A JUMPDEST is automatically added to this point in the assembled output.

@TODO: Examples

Literals

A Literal puts data on the stack when executed using a PUSH operation.

A Literal can be provided using a DataHexString or a decimal byte value.

@TODO: examples

Comments

To enter a comment in the Ethers ASM Dialect, any text following a semi-colon (i.e. ;) is ignored by the assembler.

Scopes

A common case in Ethereum is to have one program embedded in another.

The most common use of this is embedding a Contract runtime bytecode within a deployment bytecode, which can be used as init code.

When deploying a program to Ethereum, an init transaction is used. An init transaction has a null to address and contains bytecode in the data. This data bytecode is a program, that when executed returns some other bytecode as a result, this result is the bytecode to be installed.

Therefore it is important that embedded code uses jumps relative to itself, not the entire program it is embedded in, which also means that a jump can only target its own scope, no parent or child scopes. This is enforced by the assembler.

A scope may access the offset of any child Data Segment or child Scopes (with respect to itself) and may access the length of any Data Segment or Scopes anywhere in the program.

Every program in the Ethers ASM Dialect has a top-level scope named _.

Data Segment

A Data Segment allows arbitrary data to be embedded into a program, which can be useful for lookup tables or deploy-time constants.

An empty Data Segment can also be used when a labelled location is required, but without the JUMPDEST which a Labels adds.

@TODO: Example

Links

A Link allows access to a Scopes, Data Segment or Labels.

To access the byte offset of a labelled item, use $foobar.

For a Labels, the target must be directly reachable within this scope. For a Data Segment or a Scopes, it can be inside the same scope or any child scope.

For a Data Segment or a Labels, there is an additional type of Link, which provides the length of the data or bytecode respectively. A Length Link is accessed by #foobar and is pushed on the stack as a literal.

Stack Placeholders

@TODO: exampl

Evaluation and Execution

Utilities

Assembler

The assembler utilities allow parsing and assembling an Ethers ASM Dialect source file.

asm.parse( code ) Node

Parse an ethers-format assembly file and return the Abstract Syntax Tree.

asm.assemble( node ) string< DataHexString >

Performs assembly of the Abstract Syntax Tree node and return the resulting bytecode representation.

Disassembler

The Disassembler utilities make it easy to convert bytecode into an object which can easily be examined for program structure.

asm.disassemble( bytecode ) Bytecode

Returns an array of Operations given bytecode.

asm.formatBytecode( operations ) string

Create a formatted output of an array of Operation.

Bytecode inherits Array<Operation>

Each array index represents an operation, collapsing multi-byte operations (i.e. PUSH) into a single operation.

bytecode.getOperation( offset ) Operation

Get the operation at a given offset into the bytecode. This ensures that the byte at offset is an operation and not data contained within a PUSH, in which case null it returned.

Operation

An Operation is a single command from a disassembled bytecode stream.

operation.opcode Opcode

The opcode for this Operation.

operation.offset number

The offset into the bytecode for this Operation.

operation.pushValue string< DataHexString >

If the opcode is a PUSH, this is the value of that push

Opcode

asm.Opcode.from( valueOrMnemonic ) Opcode

Create a new instance of an Opcode for a given numeric value (e.g. 0x60 is PUSH1) or mnemonic string (e.g. "PUSH1").

Properties

opcode.value number

The value (bytecode as a number) of this opcode.

opcode.mnemonic string

The mnemonic string of this opcode.

opcode.delta number

The number of items this opcode will consume from the stack.

opcode.alpha number

The number of items this opcode will push onto the stack.

opcode.doc string

A short description of what this opcode does.

opcode.isMemory( ) "read" | "write" | "full"

Returns true if the opcode accesses memory.

opcode.isStatic( ) boolean

Returns true if the opcode cannot change state.

opcode.isJump( ) boolean

Returns true if the opcode is a jumper operation.

opcode.isPush( ) number

Returns 0 if the opcode is not a PUSH*, or the number of bytes this opcode will push if it is.

Abstract Syntax Tree

Parsing a file using the Ethers ASM Dialect will generate an Abstract Syntax Tree. The root node will always be a ScopeNode whose name is _.

To parse a file into an Abstract Syntax tree, use the parse function.

Types

Location

offset number

The offset into the source code to the start of this node.

length number

The length of characters in the source code to the end of this node.

source string

The source code of this node.

Nodes

@TODO: Place a diagram here showing the hierarchy

Node

node.tag string

A unique tag for this node for the lifetime of the process.

node.location Location

The source code and location within the source code that this node represents.

ValueNode inherits Node

A ValueNode is a node which may manipulate the stack.

LiteralNode inherits ValueNode

literalNode.value string

The literal value of this node, which may be a DataHexString or string of a decimal number.

literalNode.verbatim boolean

This is true in a DataNode context, since in that case the value should be taken verbatim and no PUSH operation should be added, otherwise false.

PopNode inherits ValueNode

A PopNode is used to store a place-holder for an implicit pop from the stack. It represents the code for an implicit place-holder (i.e. $$) or an explicit place-holder (e.g. $1), which indicates the expected stack position to consume.

literalNode.index number

The index this PopNode is representing. For an implicit place-holder this is 0.

LinkNode inherits ValueNode

A LinkNode represents a link to another Node's data, for example $foo or #bar.

linkNode.label string

The name of the target node.

linkNode.type "offset" | "length"

Whether this node is for an offset or a length value of the target node.

OpcodeNode inherits ValueNode

opcodeNode.opcode Opcode

The opcode for this Node.

opcodeNode.operands Array< ValueNode >

A list of all operands passed into this Node.

EvaluationNode inherits ValueNode

An EvaluationNode is used to execute code and insert the results but does not generate any output assembly, using the {{! code here }} syntax.

literalNode.verbatim boolean

This is true in a DataNode context, since in that case the value should be taken verbatim and no PUSH operation should be added, otherwise false.

evaluationNode.script string

The code to evaluate and produce the result to use as a literal.

ExecutionNode inherits Node

An ExecutionNode is used to execute code but does not generate any output assembly, using the {{! code here }} syntax.

evaluationNode.script string

The code to execute. Any result is ignored.

LabelledNode inherits Node

A LabelledNode is used for any Node that has a name, and can therefore be targeted by a LinkNode.

labelledNode.name string

The name of this node.

LabelNode inherits LabelledNode

A LabelNode is used as a place to JUMP to by referencing it name, using @myLabel:. A JUMPDEST is automatically inserted at the bytecode offset.

DataNode inherits LabelledNode

A DataNode allows for data to be inserted directly into the output assembly, using @myData[ ... ]. The data is padded if needed to ensure values that would otherwise be regarded as a PUSH value does not impact anything past the data.

dataNode.data Array< ValueNode >

The child nodes, which each represent a verbatim piece of data in insert.

ScopeNode inherits LabelledNode

A ScopeNode allows a new frame of reference that all LinkNode's will use when resolving offset locations, using @myScope{ ... }.

scopeNode.statements Array< Node >

The list of child nodes for this scope.

Hardware Wallets

LedgerSigner inherits Signer

The Ledger Hardware Wallets are a fairly popular brand.

Importing in ES6 or TypeScript
import { LedgerSigner } from "@ethersproject/hardware-wallets";

API

new LedgerSigner( [ provider [ , type [ , path ] ] ] ) LedgerSigner

Connects to a Ledger Hardware Wallet. The type if left unspecified is determined by the environment; in node the default is "hid" and in the browser "u2f" is the default. The default Ethereum path is used if path is left unspecified.

Experimental

The Experimental package is used for features that are not ready to be included in the base library. The API should not be considered stable and does not follow semver versioning, so applications requiring it should specify the exact version needed.

These features are not available in the core ethers package, so to use them you must install the @ethersproject/experimental package and import them from that.

BrainWallet inherits Wallet

Ethers removed support for BrainWallets in v4, since they are unsafe and many can be easily guessed, allowing attackers to steal the funds. This class is offered to ensure older systems which used brain wallets can still recover their funds and assets.

BrainWallet.generate( username , password [ , progressCallback ] ) BrainWallet

Generates a brain wallet, with a slightly improved experience, in which the generated wallet has a mnemonic.

BrainWallet.generateLegacy( username , password [ , progressCallback ] ) BrainWallet

Generate a brain wallet which is compatible with the ethers v3 and earlier.

Importing
// Node const { BrainWallet } = require("@ethersproject/experimental"); // ESM/TypeScript import { BrainWallet } from "@ethersproject/experimental";

EIP1193Bridge inherits EventEmitter

The EIP1193Bridge allows a normal Ethers Signer and Provider to be exposed in as a standard EIP-1193 Provider, which may be useful when interacting with other libraries.

Importing
// Node const { Eip1193Bridge } = require("@ethersproject/experimental"); // ESM/TypeScript import { Eip1193Bridge } from "@ethersproject/experimental";

NonceManager inherits Signer

The NonceManager is designed to manage the nonce for a Signer, automatically increasing it as it sends transactions.

Currently the NonceManager does not handle re-broadcast. If you attempt to send a lot of transactions to the network on a node that does not control that account, the transaction pool may drop your transactions.

In the future, it'd be nice if the NonceManager remembered transactions and watched for them on the network, rebroadcasting transactions that appear to have been dropped.

Another future feature will be some sort of failure mode. For example, often a transaction is dependent on another transaction being mined first.

new NonceManager( signer )

Create a new NonceManager.

nonceManager.signer Signer

The signer whose nonce is being managed.

nonceManager.provider Provider

The provider associated with the signer.

nonceManager.setTransactionCount( count ) void

Set the current transaction count (nonce) for the signer.

This may be useful in interacting with the signer outside of using this class.

nonceManager.incrementTransactionCount( [ count = 1 ] ) void

Bump the current transaction count (nonce) by count.

This may be useful in interacting with the signer outside of using this class.

Importing
// Node const { NonceManager } = require("@ethersproject/experimental"); // ESM/TypeScript import { NonceManager } from "@ethersproject/experimental";

Command Line Interfaces

Sandbox Utility
Assembler
Ethereum Naming Service
TypeScript
Making Your Own

Sandbox Utility

The sandbox utility provides a simple way to use the most common ethers utilities required during learning, debugging and managing interactions with the Ethereum network.

If no command is given, it will enter a REPL interface with many of the ethers utilities already exposed.

Help

Usage: ethers [ COMMAND ] [ ARGS ] [ OPTIONS ] COMMANDS (default: sandbox) sandbox Run a REPL VM environment with ethers init FILENAME Create a new JSON wallet [ --force ] Overwrite any existing files fund TARGET Fund TARGET with testnet ether info [ TARGET ... ] Dump info for accounts, addresses and ENS names send TARGET ETHER Send ETHER ether to TARGET form accounts[0] [ --allow-zero ] Allow sending to the address zero [ --data DATA ] Include data in the transaction sweep TARGET Send all ether from accounts[0] to TARGET sign-message MESSAGE Sign a MESSAGE with accounts[0] [ --hex ] The message content is hex encoded eval CODE Run CODE in a VM with ethers run FILENAME Run FILENAME in a VM with ethers wait HASH Wait for a transaction HASH to be mined wrap-ether VALUE Deposit VALUE into Wrapped Ether (WETH) unwrap-ether VALUE Withdraw VALUE from Wrapped Ether (WETH) send-token TOKEN ADDRESS VALUE Send VALUE tokens (at TOKEN) to ADDRESS compile FILENAME Compiles a Solidity contract [ --no-optimize ] Do not optimize the compiled output [ --warnings ] Error on any warning deploy FILENAME Compile and deploy a Solidity contract [ --no-optimize ] Do not optimize the compiled output [ --contract NAME ] Specify the contract to deploy ACCOUNT OPTIONS --account FILENAME Load from a file (JSON, RAW or mnemonic) --account RAW_KEY Use a private key (insecure *) --account 'MNEMONIC' Use a mnemonic (insecure *) --account - Use secure entry for a raw key or mnemonic --account-void ADDRESS Use an address as a void signer --account-void ENS_NAME Add the resolved address as a void signer --account-rpc ADDRESS Add the address from a JSON-RPC provider --account-rpc INDEX Add the index from a JSON-RPC provider --mnemonic-password Prompt for a password for mnemonics --xxx-mnemonic-password Prompt for a (experimental) hard password PROVIDER OPTIONS (default: all + homestead) --alchemy Include Alchemy --etherscan Include Etherscan --infura Include INFURA --nodesmith Include nodesmith --rpc URL Include a custom JSON-RPC --offline Dump signed transactions (no send) --network NETWORK Network to connect to (default: homestead) TRANSACTION OPTIONS (default: query network) --gasPrice GWEI Default gas price for transactions(in wei) --gasLimit GAS Default gas limit for transactions --nonce NONCE Initial nonce for the first transaction --yes Always accept Signing and Sending OTHER OPTIONS --wait Wait until transactions are mined --debug Show stack traces for errors --help Show this usage and exit --version Show this version and exit (*) By including mnemonics or private keys on the command line they are possibly readable by other users on your system and may get stored in your bash history file. This is NOT recommended.

Examples

Creating New Wallets
/home/ethers> ethers init wallet.json Creating a new JSON Wallet - wallet.json Keep this password and file SAFE!! If lost or forgotten it CANNOT be recovered, by ANYone, EVER. Choose a password: ****** Confirm password: ****** Encrypting... 100% New account address: 0x485bcC23ae2E5038ec7ec9b8DCB2A6A6291cC003 Saved: wallet.json # If you are planning to try out the Goerli testnet... /home/ethers> ethers --network goerli fund 0x485bcC23ae2E5038ec7ec9b8DCB2A6A6291cC003 Transaction Hash: 0x8dc55b8f8dc8076acded97f9e3ed7d6162460c0221e2769806006b6d7d1156e0
Sending Ether and Tokens
# Sending ether /home/ricmoo> ethers --account wallet.json send ricmoo.firefly.eth 0.123 Password (wallet.json): ****** Decrypting... 100% Transaction: To: 0x8ba1f109551bD432803012645Ac136ddd64DBA72 From: 0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C Value: 0.123 ether Nonce: 96 Data: 0x Gas Limit: 21000 Gas Price: 1.2 gwei Chain ID: 1 Network: homestead Send Transaction? (y/N/a) y Response: Hash: 0xc4adf8b379033d7ab679d199aa35e6ceee9a802ca5ab0656af067e911c4a589a # Sending a token (SAI) # NOTE: the contract address could be used instead but # popular token contract addresses are also managed # by ethers /home/ricmoo> ethers --account wallet.json send-token sai.tokens.ethers.eth ricmoo.firefly.eth 1.0 Sending Tokens: To: 0x8ba1f109551bD432803012645Ac136ddd64DBA72 Token Contract: 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359 Value: 1.0 Password (wallet.json): ****** Decrypting... 100% Transaction: To: 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359 From: 0xaB7C8803962c0f2F5BBBe3FA8bf41cd82AA1923C Value: 0.0 ether Nonce: 95 Data: 0xa9059cbb0000000000000000000000008ba1f109551bd432803012645ac136ddd64dba720000000000000000000000000000000000000000000000000de0b6b3a7640000 Gas Limit: 37538 Gas Price: 1.0 gwei Chain ID: 1 Network: homestead Send Transaction? (y/N/a) y Response: Hash: 0xd609ecb7e3b5e8d36fd781dffceede3975ece6774b6322ea56cf1e4d0a17e3a1
Signing Messages
/home/ethers> ethers --account wallet.json sign-message 'Hello World' Password (wallet.json): ****** Decrypting... 100% Message: Message: "Hello World" Message (hex): 0x48656c6c6f20576f726c64 Sign Message? (y/N/a) y Signature Flat: 0xca3f0b32a22a5ab97ca8be7e4a36b1e81d565c6822465d769f4faa4aa24539fb122ee5649c8a37c9f5fc8446593674159e3a7b039997cd6ee697a24b787b1a161b r: 0xca3f0b32a22a5ab97ca8be7e4a36b1e81d565c6822465d769f4faa4aa24539fb s: 0x122ee5649c8a37c9f5fc8446593674159e3a7b039997cd6ee697a24b787b1a16 vs: 0x122ee5649c8a37c9f5fc8446593674159e3a7b039997cd6ee697a24b787b1a16 v: 27 recid: 0

Scripting

The eval command can be used to execute simple one-line scripts from the command line to be passed into other commands or stored in script environment variables.

Get the formatted balance of an account
/home/ethers> ethers --network goerli \ --account wallet.json \ eval \ 'accounts[0].getBalance().then(b => formatEther(b))' 3.141592653589793238
Get the current block number
/home/ethers> ethers --network goerli \ eval "provider.getBlockNumber()" 5761009
Convert a Solidity signature to JSON
/home/ethers> ethers eval 'utils.Fragment.from( "function balanceOf(address) view returns (uint)" ).format("json")' | json_pp { "inputs" : [ { "type" : "address", "name" : "owner" } ], "type" : "function", "payble" : false, "stateMutability" : "view", "ouputs" : [ { "type" : "uint256" } ], "name" : "balanceOf", "constant" : true }
Compute a topic hash
/home/ricmoo> ethers eval 'id("Transfer(address,address,uint256)")' 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
Create a random mnemonic
/home/ricmoo> ethers eval 'Wallet.createRandom().mnemonic' useful pond inch knock ritual matrix giggle attend dilemma convince coach amazing

Using Mnemonics (with a password)

All mnemonic phrases have a password, but the default is to use the empty string (i.e. "") as the password. If you have a password on your mnemonic, the --mnemonic-password will prompt for the password to use to decrypt the account.

/home/ricmoo> ethers --account mnemonic.txt --mnemonic-password Password (mnemonic): ****** network: homestead (chainId: 1) homestead> accounts[0].getAddress() <Promise id=0 resolved> '0x6d3F723EC1B73141AA4aC248c3ab34A5a1DAD776' homestead>

Using Mnemonics (with experimental memory-hard passwords)

The --xxx-mnemonic-password is similar to the --mnemonic-password options, which uses a password to decrypt the account for a mnemonic, however it passes the password through the scrypt password-based key derivation function first, which is intentionally slow and makes a brute-force attack far more difficult.

/home/ricmoo> ethers --account mnemonic.txt --xxx-mnemonic-password Password (mnemonic; experimental - hard): ****** Decrypting... 100% network: homestead (chainId: 1) homestead> accounts[0].getAddress() <Promise id=0 resolved> '0x56FC8792cC17971C19bEC4Ced978beEA44711EeD' homestead>
Note

This is still an experimental feature (hence the xxx).

Assembler

The assembler Command-Line utility allows you to assemble the Ethers ASM Dialect into deployable EVM bytecode and disassemble EVM bytecode into human-readable mnemonics.

Help

Usage: ethers-asm [ FILENAME ] [ OPTIONS ] OPTIONS --define KEY=VALUE provide assembler defines --disassemble Disassemble input bytecode --ignore-warnings Ignore warnings --pic generate position independent code --target LABEL output LABEL bytecode (default: _) OTHER OPTIONS --debug Show stack traces for errors --help Show this usage and exit --version Show this version and exit

Example Input Files

SimpleStore.asm
; SimpleStore (uint) ; Set the initial value of 42 sstore(0, 42) ; Init code to deploy myContract codecopy(0, $myContract, #myContract) return(0, #myContract) @myContract { ; Non-payable jumpi($error, callvalue) ; Get the Sighash shr({{= 256 - 32 }}, calldataload(0)) ; getValue() dup1 {{= sighash("getValue()") }} jumpi($getValue, eq) ; setValue(uint) dup1 {{= sighash("setValue(uint)") }} jumpi($setValue, eq) ; No matching signature @error: revert(0, 0) @getValue: mstore(0, sload(0)) return (0, 32) @setValue: ; Make sure we have exactly a uint jumpi($error, iszero(eq(calldatasize, 36))) ; Store the value sstore(0, calldataload(4)) return (0, 0) ; There is no *need* for the PUSH32, it just makes ; decompiled code look nicer @checksum[ {{= (defines.checksum ? concat([ Opcode.from("PUSH32"), id(myContract.source) ]): "0x") }} ] }
SimpleStore.bin
0x602a6000556044601160003960446000f334601e5760003560e01c8063209652 0x5514602457806355241077146030575b60006000fd5b60005460005260206000 0xf35b6024361415601e5760043560005560006000f3
Note: Bytecode File Syntax

A bin file may be made up of multiple blocks of bytecode, each may optionally begin with a 0x prefix, all of which must be of even length (since bytes are required, with 2 nibbles per byte)

All whitespace is ignored.

Assembler Examples

The assembler converts an Ethers ASM Dialect into bytecode by running multiple passes of an assemble stage, each pass more closely approximating the final result.

This allows small portions of the bytecode to be massaged and tweaked until the bytecode stabilizes. This allows for more compact jump destinations and for code to include more advanced meta-programming techniques.

/home/ethers> ethers-asm SimpleStore.asm 0x602a6000556044601160003960446000f334601e5760003560e01c80632096525514602457806355241077146030575b60006000fd5b60005460005260206000f35b6024361415601e5760043560005560006000f3 # Piping in ASM source code /home/ethers> cat SimpleStore.asm | ethers-asm # Same as above # Setting a define which the ASM file checks and adds a checksum /home/ethers> ethers-asm --define checksum SimpleStore.asm 0x602a6000556065601160003960656000f334601e5760003560e01c80632096525514602457806355241077146030575b60006000fd5b60005460005260206000f35b6024361415601e5760043560005560006000f37f10358310d664c9aeb4bf4ce7a10a6a03176bd23194c8ccbd3160a6dac90774d6

Options

--define KEY=VALUE or --define FLAG

This allows key/value pairs (where the value is a string) and flags (which the value is true) to be passed along to the assembler, which can be accessed in Scripting Blocks, such as {{= defined.someKey }}.

--ignore-warnings

By default any warning will be treated like an error. This enabled by-passing warnings.

--pic

When a program is assembled, the labels are usually given as an absolute byte position, which can be jumped to for loops and control flow. This means that a program must be installed at a specific location.

Byt specifying the Position Independent Code flag, code will be generated in a way such that all offsets are relative, allowing the program to be moved without any impact to its logic.

This does incur an additional gas cost of 8 gas per offset access though.

--target LABEL

All programs have a root scope named _ which is by default assembled. This option allows another labelled target (either a Scopes or a Data Segment to be assembled instead. The entire program is still assembled per usual, so this only impacts which part of the program is output.

Disassembler Examples

A disassembled program shows offsets and mnemonics for the given bytecode. This format may change in the future to be more human-readable.

/home/ethers> ethers-asm --disassemble SimpleStore.bin 0000 : 0x2a ; #1 0002 : 0x00 ; #1 0004 : SSTORE 0005 : 0x44 ; #1 0007 : 0x11 ; #1 0009 : 0x00 ; #1 000b : CODECOPY 000c : 0x44 ; #1 000e : 0x00 ; #1 0010 : RETURN 0011 : CALLVALUE 0012 : 0x1e ; #1 0014 : JUMPI 0015 : 0x00 ; #1 0017 : CALLDATALOAD 0018 : 0xe0 ; #1 001a : SHR 001b : DUP1 001c : 0x20965255 ; #4 0021 : EQ 0022 : 0x24 ; #1 0024 : JUMPI 0025 : DUP1 0026 : 0x55241077 ; #4 002b : EQ 002c : 0x30 ; #1 002e : JUMPI 002f*: JUMPDEST 0030 : 0x00 ; #1 0032 : 0x00 ; #1 0034 : REVERT 0035*: JUMPDEST 0036 : 0x00 ; #1 0038 : SLOAD 0039 : 0x00 ; #1 003b : MSTORE 003c : 0x20 ; #1 003e : 0x00 ; #1 0040 : RETURN 0041*: JUMPDEST 0042 : 0x24 ; #1 0044 : CALLDATASIZE 0045 : EQ 0046 : ISZERO 0047 : 0x1e ; #1 0049 : JUMPI 004a : 0x04 ; #1 004c : CALLDATALOAD 004d : 0x00 ; #1 004f : SSTORE 0050 : 0x00 ; #1 0052 : 0x00 ; #1 0054 : RETURN /home/ethers> cat SimpleStore.bin | ethers-asm --disassemble # Same as above

Ethereum Naming Service

Help

Usage: ethers-ens COMMAND [ ARGS ] [ OPTIONS ] COMMANDS lookup [ NAME | ADDRESS [ ... ] ] Lookup a name or address commit NAME Submit a pre-commitment [ --duration DAYS ] Register duration (default: 365 days) [ --salt SALT ] SALT to blind the commit with [ --secret SECRET ] Use id(SECRET) as the salt [ --owner OWNER ] The target owner (default: current account) reveal NAME Reveal a previous pre-commitment [ --duration DAYS ] Register duration (default: 365 days) [ --salt SALT ] SALT to blind the commit with [ --secret SECRET ] Use id(SECRET) as the salt [ --owner OWNER ] The target owner (default: current account) set-controller NAME Set the controller (default: current account) [ --address ADDRESS ] Specify another address set-subnode NAME Set a subnode owner (default: current account) [ --address ADDRESS ] Specify another address set-resolver NAME Set the resolver (default: resolver.eth) [ --address ADDRESS ] Specify another address set-addr NAME Set the addr record (default: current account) [ --address ADDRESS ] Specify another address set-text NAME KEY VALUE Set a text record set-email NAME EMAIL Set the email text record set-website NAME URL Set the website text record set-content NAME HASH Set the IPFS Content Hash migrate-registrar NAME Migrate from the Legacy to the Permanent Registrar transfer NAME NEW_OWNER Transfer registrant ownership reclaim NAME Reset the controller by the registrant [ --address ADDRESS ] Specify another address ACCOUNT OPTIONS --account FILENAME Load from a file (JSON, RAW or mnemonic) --account RAW_KEY Use a private key (insecure *) --account 'MNEMONIC' Use a mnemonic (insecure *) --account - Use secure entry for a raw key or mnemonic --account-void ADDRESS Use an address as a void signer --account-void ENS_NAME Add the resolved address as a void signer --account-rpc ADDRESS Add the address from a JSON-RPC provider --account-rpc INDEX Add the index from a JSON-RPC provider --mnemonic-password Prompt for a password for mnemonics --xxx-mnemonic-password Prompt for a (experimental) hard password PROVIDER OPTIONS (default: all + homestead) --alchemy Include Alchemy --etherscan Include Etherscan --infura Include INFURA --nodesmith Include nodesmith --rpc URL Include a custom JSON-RPC --offline Dump signed transactions (no send) --network NETWORK Network to connect to (default: homestead) TRANSACTION OPTIONS (default: query network) --gasPrice GWEI Default gas price for transactions(in wei) --gasLimit GAS Default gas limit for transactions --nonce NONCE Initial nonce for the first transaction --yes Always accept Signing and Sending OTHER OPTIONS --wait Wait until transactions are mined --debug Show stack traces for errors --help Show this usage and exit --version Show this version and exit (*) By including mnemonics or private keys on the command line they are possibly readable by other users on your system and may get stored in your bash history file. This is NOT recommended.

Examples

TODO examples

TypeScript

Help

Usage: ethers-ts FILENAME [ ... ] [ OPTIONS ] OPTIONS --output FILENAME Write the output to FILENAME (default: stdout) --force Overwrite files if they already exist --no-optimize Do not run the solc optimizer --no-bytecode Do not include bytecode and Factory methods OTHER OPTIONS --debug Show stack traces for errors --help Show this usage and exit --version Show this version and exit (*) By including mnemonics or private keys on the command line they are possibly readable by other users on your system and may get stored in your bash history file. This is NOT recommended.

Examples

TODO

Making Your Own

The cli library is meant to make it easy to create command line utilities of your own.

CLI

A CLI handles parsing all the command-line flags, options and arguments and instantiates a Plugin to process the command.

A CLI may support multiple Plugin's in which case the first argument is used to determine which to run (or if no arguments, the default plugin will be selected) or may be designed to be standalone, in which case exactly one Plugin will be used and no command argument is allowed.

addPlugin( command , pluginClass ) void

Add a plugin class for the command. After all options and flags have been consumed, the first argument will be consumed and the associated plugin class will be instantiated and run.

setPlugin( pluginClass ) void

Set a dedicated Plugin class which will handle all input. This may not be used in conjunction with addPlugin and will not automatically accept a command from the arguments.

showUsage( [ message = "" [ , status = 0 ] ] ) never

Shows the usage help screen for the CLI and terminates.

run( args ) Promise< void >

Usually the value of args passed in will be process.argv.slice(2).

Plugin

Each Plugin manages each command of a CLI and is executed in phases.

If the usage (i.e. help) of a CLI is requested, the static methods getHelp and getOptionHelp are used to generate the help screen.

Otherwise, a plugin is instantiated and the prepareOptions is called. Each plugin must call super.prepareOptions, otherwise the basic options are not yet processed. During this time a Plugin should consume all the flags and options it understands, since any left over flags or options will cause the CLI to bail and issue an unknown option error. This should throw if a value for a given option is invalid or some combination of options and flags is not allowed.

Once the prepareOptions is complete (the returned promise is resolved), the prepareArguments is called. This should validate the number of arguments expected and throw an error if there are too many or too few arguments or if any arguments do not make sense.

Once the prepareArguments is complete (the returned promise is resolved), the run is called.

plugin.network Network

The network this plugin is running for.

plugin.provider Provider

The provider for this plugin is running for.

plugin.accounts Array< Signer >

The accounts passed into the plugin using --account, --account-rpc and --account-void which this plugin can use.

plugin.gasLimit BigNumber

The gas limit this plugin should use. This is null if unspecified.

plugin.gasPrice BigNumber

The gas price this plugin should use. This is null if unspecified.

plugin.nonce number

The initial nonce for the account this plugin should use.

Methods

plugin.prepareOptions( argParser [ , verifyOnly = false ] ) Promise< void >
plugin.prepareArgs( args ) Promise< void >
plugin.run( ) Promise< void >
plugin.getAddress( addressOrName [ , message = "" , [ allowZero = false ] ] ) Promise< string >

A plugin should use this method to resolve an address. If the resolved address is the zero address and allowZero is not true, an error is raised.

plugin.dump( header , info ) void

Dumps the contents of info to the console with a header in a nicely formatted style. In the future, plugins may support a JSON output format which will automatically work with this method.

plugin.throwUsageError( [ message = "" ] ) never

Stops execution of the plugin and shows the help screen of the plugin with the optional message.

plugin.throwError( message ) never

Stops execution of the plugin and shows message.

Static Methods

Plugin.getHelp Help

Each subclass should implement this static method which is used to generate the help screen.

Plugin.getOptionHelp Array< Help >

Each subclass should implement this static method if it supports additional options which is used to generate the help screen.

ArgParser

The ArgParser is used to parse a command line into flags, options and arguments.

/home/ethers> ethers --account wallet.json --yes send ricmoo.eth 1.0 # An Option ----------^ ^ ^ # - name = "account" | | # - value = "wallet.json" | | # A Flag -----------------------------------+ | # - name = "yes" | # - value = true | # Arguments ------------------------------------+ # - count = 3 # - [ "send", "ricmoo.eth", "1.0" ]

Flags are simple binary options (such as the --yes), which are true if present otherwise false.

Options require a single parameter follow them on the command line (such as --account wallet.json, which has the name account and the value wallet.json)

Arguments are all other values on the command line, and are not accessed through the ArgParser directly.

When a CLI is run, an ArgParser is used to validate the command line by using prepareOptions, which consumes all flags and options leaving only the arguments behind, which are then passed into prepareArgs.

argParser.consumeFlag( name ) boolean

Remove the flag name and return true if it is present.

argParser.consumeMultiOptions( names ) Array< {name:string,value:string} >

Remove all options which match any name in the Array of names with their values returning the list (in order) of values.

argParser.consumeOption( name ) string

Remove the option with its value for name and return the value. This will throw a UsageError if the option is included multiple times.

argParser.consumeOptions( name ) Array< string >

Remove all options with their values for name and return the list (in order) of values.

Cookbook

A collection (that will grow over time) of common, simple snippets of code that are in general useful.

React Native (and ilk)
Transactions

React Native (and ilk)

The React Native framework has become quite popular and has many popular forks, such as Expo.

React Native is based on JavaScriptCore (part of WebKit) and does not use Node.js or the common Web and DOM APIs. As such, there are many operations missing that a normal web environment or Node.js instance would provide.

For this reason, there is a Shims module provided to fill in the holes.

Installing

To use ethers in React Native, you must either provide shims for the needed missing functionality, or use the ethers.js shim.

It is HIGHLY RECOMMENDED you check out the security section below for instructions on installing packages which can affect the security of your application.

After installing packages, you may need to restart your packager and company.

Installing
/home/ricmoo/my-react-project> npm install @ethersproject/shims --save
Importing
// Pull in the shims (BEFORE importing ethers) import "@ethersproject/shims" // Import the ethers library import { ethers } from "ethers";

Security

The React Native environment does not contain a secure random source, which is used when computing random private keys. This could result in private keys that others could possibly guess, allowing funds to be stolen and assets manipulated.

For this reason, it is HIGHLY RECOMMENDED to also install the React Native get-random-values, which must be included before the shims. If it worked correctly you should not receive any warning in the console regarding missing secure random sources.

Importing with Secure Random Sources
// Import the crypto getRandomValues shim (**BEFORE** the shims) import "react-native-get-random-values" // Import the the ethers shims (**BEFORE** ethers) import "@ethersproject/shims" // Import the ethers library import { ethers } from "ethers";

Transactions

Compute the raw transaction

function getRawTransaction(tx) { function addKey(accum, key) { if (tx[key]) { accum[key] = tx[key]; } return accum; } // Extract the relevant parts of the transaction and signature const txFields = "accessList chainId data gasPrice gasLimit maxFeePerGas maxPriorityFeePerGas nonce to type value".split(" "); const sigFields = "v r s".split(" "); // Seriailze the signed transaction const raw = utils.serializeTransaction(txFields.reduce(addKey, { }), sigFields.reduce(addKey, { })); // Double check things went well if (utils.keccak256(raw) !== tx.hash) { throw new Error("serializing failed!"); } return raw; }

Migration Guide

Here are some migration guides when upgrading from older versions of Ethers or other libraries.

Migration: From Web3.js
Migration: From Ethers v4

Migration: From Web3.js

This migration guide focuses on migrating web3.js version 1.2.9 to ethers.js v5.

Providers

In ethers, a provider provides an abstraction for a connection to the Ethereum Network. It can be used to issue read only queries and send signed state changing transactions to the Ethereum Network.

Connecting to Ethereum

// web3 var Web3 = require('web3'); var web3 = new Web3('http://localhost:8545'); // ethers var ethers = require('ethers'); const url = "http://127.0.0.1:8545"; const provider = new ethers.providers.JsonRpcProvider(url);

Connecting to Ethereum: Metamask

// web3 const web3 = new Web3(Web3.givenProvider); // ethers const provider = new ethers.providers.Web3Provider(window.ethereum);

Signers

In ethers, a signer is an abstraction of an Ethereum Account. It can be used to sign messages and transactions and send signed transactions to the Ethereum Network.

In web3, an account can be used to sign messages and transactions.

Creating signer

// web3 const account = web3.eth.accounts.create(); // ethers (create random new account) const signer = ethers.Wallet.createRandom(); // ethers (connect to JSON-RPC accounts) const signer = provider.getSigner();

Signing a message

// web3 (using a private key) signature = web3.eth.accounts.sign('Some data', privateKey) // web3 (using a JSON-RPC account) // @TODO // ethers signature = await signer.signMessage('Some data')

Contracts

A contract object is an abstraction of a smart contract on the Ethereum Network. It allows for easy interaction with the smart contract.

Deploying a Contract

// web3 const contract = new web3.eth.Contract(abi); contract.deploy({ data: bytecode, arguments: ["my string"] }) .send({ from: "0x12598d2Fd88B420ED571beFDA8dD112624B5E730", gas: 150000, gasPrice: "30000000000000" }), function(error, transactionHash){ ... }) .then(function(newContract){ console.log('new contract', newContract.options.address) }); // ethers const signer = provider.getSigner(); const factory = new ethers.ContractFactory(abi, bytecode, signer); const contract = await factory.deploy("hello world"); console.log('contract address', contract.address); // wait for contract creation transaction to be mined await contract.deployTransaction.wait();

Interacting with a Contract

// web3 const contract = new web3.eth.Contract(abi, contractAddress); // read only query contract.methods.getValue().call(); // state changing operation contract.methods.changeValue(42).send({from: ....}) .on('receipt', function(){ ... }); // ethers // pass a provider when initiating a contract for read only queries const contract = new ethers.Contract(contractAddress, abi, provider); const value = await contract.getValue(); // pass a signer to create a contract instance for state changing operations const contract = new ethers.Contract(contractAddress, abi, signer); const tx = await contract.changeValue(33); // wait for the transaction to be mined const receipt = await tx.wait();

Overloaded Functions

Overloaded functions are functions that have the same name but different parameter types.

In ethers, the syntax to call an overloaded contract function is different from the non-overloaded function. This section shows the differences between web3 and ethers when calling overloaded functions.

See issue #407 for more details.

// web3 message = await contract.methods.getMessage('nice').call(); // ethers const abi = [ "function getMessage(string) public view returns (string)", "function getMessage() public view returns (string)" ] const contract = new ethers.Contract(address, abi, signer); // for ambiguous functions (two functions with the same // name), the signature must also be specified message = await contract['getMessage(string)']('nice');

Numbers

BigNumber

Convert to BigNumber:

// web3 web3.utils.toBN('123456'); // ethers (from a number; must be within safe range) ethers.BigNumber.from(123456) // ethers (from base-10 string) ethers.BigNumber.from("123456") // ethers (from hex string) ethers.BigNumber.from("0x1e240")

Utilities

Hash

Computing Keccak256 hash of a UTF-8 string in web3 and ethers:

// web3 web3.utils.sha3('hello world'); web3.utils.keccak256('hello world'); // ethers (hash of a string) ethers.utils.id('hello world') // ethers (hash of binary data) ethers.utils.keccak256('0x4242')

Migration: From Ethers v4

This document only covers the features present in v4 which have changed in some important way in v5.

It does not cover all the new additional features that have been added and mainly aims to help those updating their older scripts and applications to retain functional parity.

If you encounter any missing changes, please let me know and I'll update this guide.

BigNumber

Namespace

Since BigNumber is used quite frequently, it has been moved to the top level of the umbrella package.

// v4 ethers.utils.BigNumber ethers.utils.BigNumberish // v5 ethers.BigNumber ethers.BigNumberish

Creating Instances

The bigNumberify method was always preferred over the constructor since it could short-circuit an object instantiation for [[BigNumber] objects (since they are immutable). This has been moved to a static from class method.

// v4 new ethers.utils.BigNumber(someValue) ethers.utils.bigNumberify(someValue); // v5 // - Constructor is private // - Removed `bigNumberify` ethers.BigNumber.from(someValue)

Contracts

ENS Name Resolution

The name of the resolved address has changed. If the address passed into the constructor was an ENS name, the address will be resolved before any calls are made to the contract.

The name of the property where the resolved address has changed from addressPromise to resolvedAddress.

Resolved ENS Names
// v4 contract.addressPromise // v5 contract.resolvedAddress

Gas Estimation

The only difference in gas estimation is that the bucket has changed its name from estimate to estimateGas.

Gas Estimation
// v4 contract.estimate.transfer(toAddress, amount) // v5 contract.estimateGas.transfer(toAddress, amount)

Functions

In a contract in ethers, there is a functions bucket, which exposes all the methods of a contract.

All these functions are available on the root contract itself as well and historically there was no difference between contact.foo and contract.functions.foo. The original reason for the functions bucket was to help when there were method names that collided with other buckets, which is rare.

In v5, the functions bucket is now intended to help with frameworks and for the new error recovery API, so most users should use the methods on the root contract.

The main difference will occur when a contract method only returns a single item. The root method will dereference this automatically while the functions bucket will preserve it as an Result.

If a method returns multiple items, there is no difference.

This helps when creating a framework, since the result will always be known to have the same number of components as the Fragment outputs, without having to handle the special case of a single return value.

Functions Bucket
const abi = [ // Returns a single value "function single() view returns (uint8)", // Returns two values "function double() view returns (uint8, uint8)", ]; // v4 await contract.single() // 123 await contract.functions.single() // 123 // v5 (notice the change in the .function variant) await contract.single() // 123 await contract.functions.single() // [ 123 ] // v4 await contract.double() // [ 123, 5 ] await contract.functions.double() // [ 123, 5 ] // v5 (no difference from v4) await contract.double() // [ 123, 5 ] await contract.functions.double() // [ 123, 5 ]

Errors

Namespace

All errors now belong to the Logger class and the related functions have been moved to Logger instances, which can include a per-package version string.

Global error functions have been moved to Logger class methods.

// v4 ethers.errors.UNKNOWN_ERROR ethers.errors.* errors.setCensorship(censorship, permanent) errors.setLogLevel(logLevel) errors.checkArgumentCount(count, expectedCount, suffix) errors.checkNew(self, kind) errors.checkNormalize() errors.throwError(message, code, params) errors.warn(...) errors.info(...) // v5 ethers.utils.Logger.errors.UNKNOWN_ERROR ethers.utils.Logger.errors.* Logger.setCensorship(censorship, permanent) Logger.setLogLevel(logLevel) const logger = new ethers.utils.Logger(version); logger.checkArgumentCount(count, expectedCount, suffix) logger.checkNew(self, kind) logger.checkNormalize() logger.throwError(message, code, params) logger.warn(...) logger.info(...)

Interface

The Interface object has undergone the most dramatic changes.

It is no longer a meta-class and now has methods that simplify handling contract interface operations without the need for object inspection and special edge cases.

Functions

// v4 (example: "transfer(address to, uint amount)") interface.functions.transfer.encode(to, amount) interface.functions.transfer.decode(callData) // v5 interface.encodeFunctionData("transfer", [ to, amount ]) interface.decodeFunctionResult("transfer", data) // Or you can use any compatible signature or Fragment objects. // Notice that signature normalization is performed for you, // e.g. "uint" and "uint256" will be automatically converted interface.encodeFunctionData("transfer(address,uint)", [ to, amount ]) interface.decodeFunctionResult("transfer(address to, uint256 amount)", data)

Events

// v4 (example: Transfer(address indexed, address indexed, uint256) interface.events.Transfer.encodeTopics(values) interface.events.Transfer.decode(data, topics) // v5 interface.encodeFilterTopics("Transfer", values) interface.decodeEventLog("Transfer", data, topics)

Inspection

Interrogating properties about a function or event can now (mostly) be done directly on the Fragment object.

// v4 interface.functions.transfer.name interface.functions.transfer.inputs interface.functions.transfer.outputs interface.functions.transfer.payable interface.functions.transfer.gas // v5 const functionFragment = interface.getFunction("transfer") functionFragment.name functionFragment.inputs functionFragment.outputs functionFragment.payable functionFragment.gas // v4; type is "call" or "transaction" interface.functions.transfer.type // v5; constant is true (i.e. "call") or false (i.e. "transaction") functionFragment.constant // v4 interface.events.Transfer.anonymous interface.events.Transfer.inputs interface.events.Transfer.name // v5 const eventFragment = interface.getEvent("Transfer"); eventFragment.anonymous eventFragment.inputs eventFragment.name // v4 const functionSig = interface.functions.transfer.signature const sighash = interface.functions.transfer.sighash const eventSig = interface.events.Transfer.signature const topic = interface.events.Transfer.topic // v5 const functionSig = functionFragment.format() const sighash = interface.getSighash(functionFragment) const eventSig = eventFragment.format() const topic = interface.getTopic(eventFragment)

Wallet

Mnemonic Phrases

The mnemonic phrase and related properties have been merged into a single mnemonic object, which also now includes the locale.

// v4 wallet.mnemonic wallet.path // v5 // - Mnemonic phrase and path are a Mnemonic object // - Note: wallet.mnemonic is null if there is no mnemonic wallet.mnemonic.phrase wallet.mnemonic.path

Testing

Testing is a critical part of any library which wishes to remain secure, safe and reliable.

Ethers currently has over 23k tests among its test suites, which are all made available for other projects to use as simple exported GZIP-JSON files.

The tests are run on every check-in and the results can been seen on the GitHub CI Action.

We also strive to constantly add new test cases, especially when issues arise to ensure the issue is present prior to the fix, corrected after the fix and included to prevent future changes from causing a regression.

A large number of the test cases were created procedurally by using known correct implementations from various sources (such as Geth) and written in different languages and verified with multiple libraries.

For example, the ABI test suites were generated by procedurally generating a list of types, for each type choosing a random (valid) value, which then was converted into a Solidity source file, compiled using solc and deployed to a running Parity node and executed, with its outputs being captured. Similar to the how many of the hashing, event and selector test cases were created.

Supported Platforms

While web technologies move quite fast, especially in the Web3 universe, we try to keep ethers as accessible as possible.

Currently ethers should work on almost any ES3 or better environment and tests are run against:

If there is an environment you feel has been overlooked or have suggestions, please feel free to reach out by opening an issue on Github.

We would like to add a test build for Expo and React as those developers often seem to encounter pain points when using ethers, so if you have experience or ideas on this, bug us.

The next Major version (probably summer 2021) will likely drop support for node 8.x and will require ES2015 for Proxy.

Certain features in JavaScript are also avoided, such as look-behind tokens in regular expressions, since these have caused conflicts (at import time) with certain JavaScript environments such as Otto.

Basically, the moral of the story is "be inclusive and don't drop people needlessly".

Test Suites

The test suites are available as gzipped JSON files in the @ethersproject/testcases, which makes it easy to install and import (both GZIP and JSON are quite easy to consume from most languages). Each test suite also has its schema available in this package.

FilenameTest Cases 
accounts.json.gzPrivate Keys and addresses in checksum and ICAP formats 
contract-events.json.gzCompiled Solidity, ABI interfaces, input types/values with the output types/values for emitted events; all tests were executed against real Ethereum nodes 
contract-interface.json.gzCompiled Solidity, ABI interfaces, input types/values with the output types/values, encoded and decoded binary data and normalized values for function calls executed against real Ethereum nodes. 
contract-interface-abi2.json.gzIdentical to contract-interface, except with emphasis on the ABIv2 coder which supports nested dynami types and structured data 
contract-signatures.json.gzContract signatures and matching selectors 
hashes.json.gzData and respective hashes against a variety of hash functions 
hdnode.json.gzHDNodes (BIP-32) with mnemonics, entropy, seed and computed nodes with pathes and addresses 
namehash.json.gzENS names along with computed [namehashes](link-namehash 
nameprep.json.gzIDNA and Nameprep representations including official vectors 
rlp-coder.json.gzRecursive-Length Prefix (RLP) data and encodings 
solidity-hashes.json.gzHashes based on the Solidity non-standard packed form 
transactions.json.gzSigned and unsigned transactions with their serialized formats including both with and without EIP-155 replay protection 
units.json.gzValues converted between various units 
wallets.json.gzKeystore JSON format wallets, passwords and decrypted values 
wordlists.json.gzFully decompressed BIP-39 official wordlists 
Test Suites 

Test Suite API

There are also convenience functions for those developing directly in TypeScript.

testcases.loadTests( tag ) Array< TestCase >

Load all the given testcases for the tag.

A tag is the string in the above list of test case names not including any extension (e.g. "solidity-hashes")

testcases.TestCase.TEST_NAME

Most testcases have its schema available as a TypeScript type to make testing each property easier.

Deterministic Random Numbers (DRNG)

When creating test cases, often we want want random data from the perspective we do not case what values are used, however we want the values to be consistent across runs. Otherwise it becomes difficult to reproduce an issue.

In each of the following the seed is used to control the random value returned. Be sure to tweak the seed properly, for example on each iteration change the value and in recursive functions, concatenate to the seed.

testcases.randomBytes( seed , lower [ , upper ] ) Uint8Array

Return at least lower random bytes, up to upper (exclusive) if specified, given seed. If upper is omitted, exactly /lower bytes are returned.

testcases.randomHexString( seed , lower [ , upper ] ) string< DataHexString >

Identical to randomBytes, except returns the value as a DataHexString instead of a Uint8Array.

testcases.randomNumber( seed , lower , upper ) number

Returns a random number of at least lower and less than upper given seed.

Schemas

This section is still a work in progress, but will outline some of the more nuanced aspects of the test cases and their values.

There will likely be an overhaul of the test cases in the next major version, to make code coverage testing more straightforward and to collapse some of the redundancy.

For example, there is no longer a need to separate the ABI and ABIv2 test case and the accounts and transactions suites can be merged into one large collection.

Accounts

Basic account information using a private key and computing various address forms.

Tests were verified against [EthereumJS](https://github.com/ethereumjs) and custom scripts created to directly interact with Geth and cpp implementations.

See: accounts.json.gz

PropertyMeaning 
nameThe testcase name 
privateKeyThe private key 
addressThe address (lowercase) 
checksumAddressThe address with checksum-adjusted case 
icapAddressThe ICAP address 
Properties 
Example
{ "name": "random-1023", "address": "0x53bff74b9af2e3853f758a8d2bd61cd115d27782", "privateKey": "0x8ab0e165c2ea461b01cdd49aec882d179dccdbdb5c85c3f9c94c448aa65c5ace", "checksumAddress": "0x53bFf74b9Af2E3853f758A8D2Bd61CD115d27782", "icapAddress": "XE709S6NUSJR6SXQERCMYENAYYOZ2Y91M6A" }

Contract Interface

Procedurally generated test cases to test ABI coding.

Example
{ "name": "random-1999", "source": "contract Test {\n function test() constant returns (address, bool, bytes14[1]) {\n address a = address(0x061C7F399Ee738c97C7b7cD840892B281bf772B5);\n bool b = bool(true);\n bytes14[1] memory c;\n c[0] = bytes14(0x327621c4abe12d4f21804ed40455);\n return (a, b, c);\n }\n}\n", "types": "[\"address\",\"bool\",\"bytes14[1]\"]", "interface": "[{\"constant\":true,\"inputs\":[],\"name\":\"test\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"bool\"},{\"name\":\"\",\"type\":\"bytes14[1]\"}],\"type\":\"function\"}]\n", "bytecode": "0x6060604052610175806100126000396000f360606040526000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d1461003957610037565b005b610046600480505061009d565b604051808473ffffffffffffffffffffffffffffffffffffffff1681526020018315158152602001826001602002808383829060006004602084601f0104600f02600301f150905001935050505060405180910390f35b600060006020604051908101604052806001905b60008152602001906001900390816100b157905050600060006020604051908101604052806001905b60008152602001906001900390816100da5790505073061c7f399ee738c97c7b7cd840892b281bf772b59250600191506d327621c4abe12d4f21804ed404557201000000000000000000000000000000000000028160006001811015610002579090602002019071ffffffffffffffffffffffffffffffffffff191690818152602001505082828295509550955061016d565b50505090919256", "result": "0x000000000000000000000000061c7f399ee738c97c7b7cd840892b281bf772b50000000000000000000000000000000000000000000000000000000000000001327621c4abe12d4f21804ed40455000000000000000000000000000000000000", "values": "[{\"type\":\"string\",\"value\":\"0x061C7F399Ee738c97C7b7cD840892B281bf772B5\"},{\"type\":\"boolean\",\"value\":true},[{\"type\":\"buffer\",\"value\":\"0x327621c4abe12d4f21804ed40455\"}]]", "normalizedValues": "[{\"type\":\"string\",\"value\":\"0x061C7F399Ee738c97C7b7cD840892B281bf772B5\"},{\"type\":\"boolean\",\"value\":true},[{\"type\":\"buffer\",\"value\":\"0x327621c4abe12d4f21804ed40455\"}]]", "runtimeBytecode": "0x60606040526000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d1461003957610037565b005b610046600480505061009d565b604051808473ffffffffffffffffffffffffffffffffffffffff1681526020018315158152602001826001602002808383829060006004602084601f0104600f02600301f150905001935050505060405180910390f35b600060006020604051908101604052806001905b60008152602001906001900390816100b157905050600060006020604051908101604052806001905b60008152602001906001900390816100da5790505073061c7f399ee738c97c7b7cd840892b281bf772b59250600191506d327621c4abe12d4f21804ed404557201000000000000000000000000000000000000028160006001811015610002579090602002019071ffffffffffffffffffffffffffffffffffff191690818152602001505082828295509550955061016d565b50505090919256" }

Contract Signatures

Computed ABI signatures and the selector hash.

Example
{ "name": "random-1999", "sigHash": "0xf51e9244", "abi": "[{\"constant\":false,\"inputs\":[{\"name\":\"r0\",\"type\":\"string[2]\"},{\"name\":\"r1\",\"type\":\"uint128\"},{\"components\":[{\"name\":\"a\",\"type\":\"bytes\"},{\"name\":\"b\",\"type\":\"bytes\"},{\"name\":\"c\",\"type\":\"bytes\"}],\"name\":\"r2\",\"type\":\"tuple\"},{\"name\":\"r3\",\"type\":\"bytes\"}],\"name\":\"testSig\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"test\",\"outputs\":[{\"name\":\"r0\",\"type\":\"string[2]\"},{\"name\":\"r1\",\"type\":\"uint128\"},{\"components\":[{\"name\":\"a\",\"type\":\"bytes\"},{\"name\":\"b\",\"type\":\"bytes\"},{\"name\":\"c\",\"type\":\"bytes\"}],\"name\":\"r2\",\"type\":\"tuple\"},{\"name\":\"r3\",\"type\":\"bytes\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"}]", "signature": "testSig(string[2],uint128,(bytes,bytes,bytes),bytes)" }

Hashes

Examples
{ "data": "0x3718a88ceb214c1480c32a9d", "keccak256": "0x82d7d2dc3d384ddb289f41917b8280675bb1283f4fe2b601ac7c8f0a2c2824fa", "sha512": "0xe93462bb1de62ba3e6a980c3cb0b61728d3f771cea9680b0fa947b6f8fb2198a2690a3a837495c753b57f936401258dfe333a819e85f958b7d786fb9ab2b066c", "sha256": "0xe761d897e667aa72141dd729264c393c4ddda5c62312bbd21b0f4d954eba1a8d" }

Hierarchal Deterministic Node (BIP-32)

Tests for BIP-32 HD Wallets.

Example
{ "name": "trezor-23", "entropy": "0xf585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f", "mnemonic": "void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold", "locale": "en", "password": "TREZOR", "hdnodes": [ { "path": "m", "address": "0xfd8eb95169ce57eab52fb69bc6922e9b6454d9aa", "privateKey": "0x679bf92c04cf16307053cbed33784f3c4266b362bf5f3d7ee13bed6f2719743c" }, { "address": "0xada964e9f10c4fc9787f9e17f00c63fe188722b0", "privateKey": "0xdcbcb48a2b11eef0aab93a8f88d83f60a3aaabb34f9ffdbe939b8f059b30f2b7", "path": "m/8'/8'/2/3/4" }, { "privateKey": "0x10fd3776145dbeccb3d6925e4fdc0d58b452fce40cb8760b12f8b4223fafdfa6", "address": "0xf3f6b1ef343d5f5f231a2287e801a46add43eb06", "path": "m/1'/3'" }, { "address": "0xb7b0fdb6e0f79f0529e95400903321e8a601b411", "privateKey": "0x093a8ff506c95a2b79d397aed59703f6212ff3084731c2f03089b069ae76e69d", "path": "m/8'/4'/7'" }, { "path": "m/7'/5'/11", "privateKey": "0x6bd79da4dfa7dd0abf566a011bdb7cba0d28bba9ca249ba25880d5dabf861b42", "address": "0x1b3ad5fa50ae32875748107f4b2160829cc10536" }, { "path": "m/9'/6'/2'/7'/3'", "address": "0x42eb4bed59f3291d02387cf0fb23098c55d82611", "privateKey": "0xfc173acba7bc8bb2c434965d9e99f5a221f81add421bae96a891d08d60be11dd" } ], "seed": "0x01f5bced59dec48e362f2c45b5de68b9fd6c92c6634f44d6d40aab69056506f0e35524a518034ddc1192e1dacd32c1ed3eaa3c3b131c88ed8e7e54c49a5d0998" }

ENS Namehash

Test cases for the ENS Namehash Algorithm.

Examples
{ "expected": "0x33868cc5c3fd3a9cd3adbc1e868ea133d2218f60dc2660c3bc48d8b1f4961384", "name": "ViTalIk.WALlet.Eth", "test": "mixed case" }

RLP Coder

Examples
{ "name": "arrayWithNullString3", "encoded": "0xc3808080", "decoded": [ "0x", "0x", "0x" ] }

Solidity Hashes

Tests for the non-standard packed form of the Solidity hash functions.

These tests were created by procedurally generating random signatures and values that match those signatures, constructing the equivalent Soldity, compiling it and deploying it to a Parity node then evaluating the response.

Example
{ "name": "random-1999", "keccak256": "0x7d98f1144a0cd689f720aa2f11f0a73bd52a2da1117175bc4bacd93c130966a1", "ripemd160": "0x59384617f8a06efd57ab106c9e0c20c3e64137ac000000000000000000000000", "sha256": "0xf9aeea729ff39f8d372d8552bca81eb2a3c5d433dc8f98140040a03b7d81ac92", "values": [ "0xcdffcb5242e6", "0xc1e101b60ebe4688", "0x5819f0ef5537796e43bdcd48309f717d6f7ccffa", "0xec3f3f9f", false, true ], "types": [ "int184", "int176", "address", "int64", "bool", "bool" ] }

Transactions

Serialized signed and unsigned transactions with both EIP-155 enabled and disabled.

Examples
{ "name": "random-998", "privateKey": "0xd16c8076a15f7fb583f05dc12686fe526bc59d298f1eb7b9a237b458133d1dec", "signedTransactionChainId5": "0xf8708391d450848517cfba8736fcf36da03ee4949577303fd4e0acbe72c6c116acab5bf63f0b1e9c8365fdc7827dc82ea059891894eb180cb7c6c45a52f62d2103420d3ad0bc3ba518d0a25ed910842522a0155c0ea2aee2ea82e75843aab297420bad907d46809d046b13d692928f4d78aa", "gasLimit": "0x36fcf36da03ee4", "to": "0x9577303fd4e0acbe72c6c116acab5bf63f0b1e9c", "data": "0x7dc8", "accountAddress": "0x6d4a6aff30ca5ca4b8422eea0ebcb669c7d79859", "unsignedTransaction": "0xed8391d450848517cfba8736fcf36da03ee4949577303fd4e0acbe72c6c116acab5bf63f0b1e9c8365fdc7827dc8", "nonce": "0x91d450", "gasPrice": "0x8517cfba", "signedTransaction": "0xf8708391d450848517cfba8736fcf36da03ee4949577303fd4e0acbe72c6c116acab5bf63f0b1e9c8365fdc7827dc81ba05030832331e6be48c95e1569a1ca9505c495486f72d6009b3a30fadfa05d9686a05cd3116b416d2362da1e9b0ca7fb1856c4e591cc22e63b395bd881ce2d3735e6", "unsignedTransactionChainId5": "0xf08391d450848517cfba8736fcf36da03ee4949577303fd4e0acbe72c6c116acab5bf63f0b1e9c8365fdc7827dc8058080", "value": "0x65fdc7" }

Units

Unit conversion.

Example
{ "name": "one-two-three-3", "gwei_format": "-1234567890123456.789012345", "ether_format": "-1234567.890123456789012345", "gwei": "-1234567890123456.789012345", "ether": "-1234567.890123456789012345", "finney": "-1234567890.123456789012345", "wei": "-1234567890123456789012345", "finney_format": "-1234567890.123456789012345" }

Wallets

Tests for the JSON keystore format.

Example
{ "mnemonic": null, "name": "secretstorage_password", "type": "secret-storage", "password": "foo", "privateKey": "0xf03e581353c794928373fb0893bc731aefc4c4e234e643f3a46998b03cd4d7c5", "hasAddress": true, "json": "{\"address\":\"88a5c2d9919e46f883eb62f7b8dd9d0cc45bc290\",\"Crypto\":{\"cipher\":\"aes-128-ctr\",\"ciphertext\":\"10adcc8bcaf49474c6710460e0dc974331f71ee4c7baa7314b4a23d25fd6c406\",\"cipherparams\":{\"iv\":\"1dcdf13e49cea706994ed38804f6d171\"},\"kdf\":\"scrypt\",\"kdfparams\":{\"dklen\":32,\"n\":262144,\"p\":1,\"r\":8,\"salt\":\"bbfa53547e3e3bfcc9786a2cbef8504a5031d82734ecef02153e29daeed658fd\"},\"mac\":\"1cf53b5ae8d75f8c037b453e7c3c61b010225d916768a6b145adf5cf9cb3a703\"},\"id\":\"fb1280c0-d646-4e40-9550-7026b1be504a\",\"version\":3}\n", "address": "0x88a5c2d9919e46f883eb62f7b8dd9d0cc45bc290" }

Contributing and Hacking

The ethers.js library is something that I've written out of necessity, and has grown somewhat organically over time.

Many things are the way they are for good (at the time, at least) reasons, but I always welcome criticism, and am completely willing to have my mind changed on things.

Pull requests are always welcome, but please keep a few points in mind:

In general, please start an issue before beginning a pull request, so we can have a public discussion and figure out the best way to address the problem/feature. :)

Building

The build process for ethers is unfortunatly not super trivial, but I have attempted to make it as straightforward as possible.

It is a mono-repo which attempts to be compatibile with a large number of environments, build tools and platforms, which is why there are a some weird things it must do.

There are several custom scripts in the misc/admin folder to help manage the monorepo. Developers working on contributing to ethers should not generally need to worry about those, since they are wrapped up behind npm run SCRIPT operations.

Installing
# Clone the repository /home/ricmoo> git clone https://github.com/ethers-io/ethers.js.git /home/ricmoo> cd ethers.js # Install all dependencies: # - Hoists all sub-package dependencies in the package.json (preinstall) # - Installs all the (hoisted) dependencies and devDependencies (install) # - Build the rat-nests (in .package_node_modules) (postinstall) # - Create a dependency graph for the TypeScript (postinstall) # - Link the rat-nets into each project (postinstall) /home/ricmoo/ethers.js> npm install

Making Changes

Once your environment is set up, you should be able to simply start the auto-build feature, and make changes to the TypeScript source.

Watching and Building
# Begin watching the files and re-building whenever they change /home/ricmoo/ethers.js> npm run auto-build # Or if you do not want to watch and just build /home/ricmoo/ethers.js> npm run build

Creating Browser-Ready Files

To create files for use directly in a browser, the distribution files (located in packages/ethers/dist) need to be built which requires several intermediate builds, scripts and for various rollup scripts to execute.

Building Distribution Files
# If you need to rebuild all the libs (esm + cjs) and dist files # Note: this requires node 10 or newer /home/ricmoo/ethers.js> npm run build-all

Testing

Testing
# Rebuilds all files (npm run build-all) and bundles testcases up for testing /home/ricmoo/ethers.js> npm test # Often you don't need the full CI experience /home/ricmoo/ethers.js> npm run test-node

Distribution

Most developers should not ever require this step, but for people forking ethers and creating alternates (for example if you have a non-EVM compatible chain but are trying to reuse this package).

This script will rebuild the entire ethers project, compare it against npm, re-write package versions, update internal hashes, re-write various TypeScript files (to get around some ES+TS limitations for Tree Shaking and linking), re-write map files, bundle stripped versions of dependencies and basically just a whole bunch of stuff.

If you use this and get stuck, message me.

Preparing the Distribution
# Prepare all the distribution files # - Remove all generated files (i.e. npm run clean) # - Re-install all dependencies, hoisting, etc. (npm install) # - Spell check all strings in every TypeScript files # - Build everything from scratch with this clean install # - Compare local with npm, bumping the version if changed # - Build everything again (with the updated versions) # - Update the CHANGELOG.md with the git history since the last change /home/ricmoo/ethers.js> npm run update-version
Do NOT check in dist files in a PR

For Pull Requests, please ONLY commit files in the docs.wrm/ and packages/*/src.ts/ folders. I will prepare the distribution builds myself and keeping the PR relevant makes it easier to verify the changes.

Publishing

Again, this should not be necessary for most developers. This step requires using the misc/admin/cmds/config-set script for a number of values, including private keys, NPM session keys, AWS access keys, GitHub API tokens, etc.

The config file is encrypted with about 30 seconds of scrypt password-based key derivation function, so brute-forcing the file is quite expensive.

The config file also contains a plain-text mnemonic. This is a money-pot. Place a tempting amount of ether or Bitcoin on this account and set up an e-mail alert for this account.

If any attacker happens across your encrypted config, they will have instant access to the plain-text mnemonic, so they have the option to immediately steal the ether (i.e. the responsible-disclosure bond).

If you ever see this ether taken, your encrypted file is compromised! Rotate all your AWS keys, NPM session keys, etc. immedately.

@TODO: document all the keys that need to be set for each step

Preparing the Distribution
# Publish # - Update any changed packages to NPM # - Create a release on GitHub with the latest CHANGELOG.md description # - Upload the bundled files the the CDN # - Flush the CDN edge caches /home/ricmoo/ethers.js> npm run publish-all

Documentation

The documents are generated using Flatworm documentation generation tool, which was written for the purpose of writing the documentation for ethers.

Style Guide (this section will have much more coming):

Building

To build the documentation, you should first follow the above steps to build the ethers library.

Building the docs will generate several types of output:

Building the Documentations
/home/ricmoo/ethers.js> npm run build-docs

Evaluation

When building the documentation, all code samples are run through a JavaScript VM to ensure there are no typos in the example code, as well the exact output of results are injected into the output, so there is no need to keep the results and code in-sync.

However, this can be a bit of a headache when making many small changes, so to build the documentation faster, you can skip the evaluation step, which will inject the code directly.

Build docs skipping evaluation
/home/ricmoo/ethers.js> npm run build-docs -- --skip-eval

Previewing Changes

To preview the changes locally, you can use any standard web server and run from the /docs/ folder, or use the built-in web server.

The same caveats as normal web development apply, such flushing browser caches after changing (and re-building) the docs.

Running a webserver
/home/ricmoo/ethers.js> npm run serve-docs

Other Resources

There is a lot of documentation on the internet to help you get started, learn more or cover advanced topics. Here are a few resources to check out.

Ethereum Overview

Tutorials

I do not manage or maintain these tutorials, but have happened across them. If a link is dead or outdated, please let me know and I'll update it.

Flatworm Docs

The Flatworm Docs rendering engine is designed to be very simple, but provide enough formatting necessary for documenting JavaScript libraries.

A lot of its inspiration came from Read the Docs and the Sphinx project.

Fragments

Each page is made up of fragments. A fragment is a directive, with an value and optional link, extensions and a body.

Many directives support markdown in their value and body.

A fragment's body continues until another fragment is encountered.

Directive Format

_DIRECTIVE: VALUE @<LINK> @EXTENSION<PARAMETER> BODY MORE BODY DIRECTIVE: The directive name VALUE: Optional; the value to pass to the directive LINK: Optional; a name for internal linking EXTENSION: Optional; extended directive functionality PARAMETER: Optional; value to pass to extended directive functions BODY: Optional; the directive body (certain directives only)

Flatworm Directives

_section: TITLE

A section has its TITLE in an H1 font. Sections are linked to in Table of Contents and have a dividing line drawn above them.

The body supports markdown.

There should only be one _section: per page.

Extensions: @inherit, @src, @nav, @note

_subsection: TITLE

A subsection has its TITLE in an H2 font. Subsections are linked to in Table of Contents and have a dividing line drawn above them.

The title and body support markdown.

Extensions: @inherit, @src, @note

_heading: TITLE

A heading has its TITLE in an H3 font.

The title and body support markdown.

Extensions: @inherit, @src, @note

_definition: TERM

A definition has its TERM in normal text and the body is indented.

The title and body support markdown.

_property: SIGNATURE

A property has its JavaScript SIGNATURE formatted.

The body supports markdown and the return portion of the signature support markdown links.

Extensions: @src

_note: BANNER

A note is placed in a blue bordered-box to draw attention to it.

The body supports markdown.

_warning: BANNER

A warning is placed in an orange bordered-box to draw attention to it.

The body supports markdown.

_code: CAPTION

Creates a Code block.

The body does not support markdown, and will be output exactly as is, with the exception of Code Evaluation.

If a line begins with a "_", it should be escaped with a "\".

Extensions: @lang

_table: FOOTER

Creates a Table structured according to the body.

Each cell contents supports markdown and variables supports markdown.

Extensions: @style

_toc:

A toc injects a Table of Contents, loading each line of the body as a filename and recursively loads the toc if present, otherwise all the sections and subsections.

The body does not support markdown, as it is interpreted as a list of files and directories to process.

_null:

A null is used to terminated a directive. For example, after a definition, the bodies are indented, so a null can be used to reset the indentation.

The body supports markdown.

Example
_section: Hello World @<link-main> Body for section... _subsection: Some Example @<link-secondary> Body for subsection... _heading: Large Bold Text @<link-here> Body for heading... _definition: Flatworm A phylum of relatively **simple** bilaterian, unsegmented, soft-bodied invertebrates. _property: String.fromCharCode(code) => string Returns a string created from //code//, a sequence of UTF-16 code units. _code: heading // Some code goes here while(1); _table: Table Footer | **Name** | **Color** | | Apple | Red | | Banana | Yellow | | Grape | Purple | _toc: some-file some-directory _note: Title This is placed in a blue box. _warning: Title This is placed in an orange box. _null: This breaks out of a directive. For example, to end a ``_note:`` or ``_code:``.

Markdown

The markdown is simple and does not have the flexibility of other dialects, but allows for bold, italic, underlined, monospaced, superscript and strike text, supporting links and lists.

Lists are rendered as blocks of a body, so cannot be used within a title or within another list.

**bold text** //italic text// __underlined text__ ``monospace code`` ^^superscript text^^ ~~strikeout text~~ - This is a list - With bullet points - With a total of three items This is a [Link to Ethereum](https://ethereum.org) and this is an [Internal Link](some-link). This is a self-titled link [[https://ethereumorg]] and this [[some-link]] will use the title from its directives value.

Code

The code directive creates a monospace, contained block useful for displaying code samples.

JavaScript Evaluation

For JavaScript files, the file is transpiled and executed in a VM, allowiung output (or exceptions) of blocks to be included in the fragment output.

The entire code fragment source is included in an async IIFE, whick means await is allowed, and several special comment directives are allowed.

A //_hide: will include any following code directly into the output, but will not include it in the generated output for the fragment.

A //_log: will include the value of any following expression in the output, prefixed with a // . Renderers will mark output in different style if possible.

A //_result: will begin a block, assigning the contents to _. The block can be ended with a //_log: or //_null:, if no value is given to log, then _ is assumed. If an error occurs, generation fails.

A //_throws: will begin a block, which is expected to throw assigning the error to _. The block can be ended with a //_log: or //_null:, if no value is given to log, then _ is assumed. If an error do not occur, generation fails.

Code Evaluation Example
_code: Result of Code Example @lang<javascript> //_hide: const url = require("url"); //_result: url.parse("https://www.ricmoo.com/").protocol //_log: //_throws: url.parse(45) //_log: // You want to assign (doesn't emit eval) AND display the value const foo = 4 + 5; //_log: foo
Result of Code Example
url.parse("https://www.ricmoo.com/").protocol // 'https:' url.parse(45) // Error: The "url" argument must be of type string. Received type number (45) // You want to assign (doesn't emit eval) AND display the value const foo = 4 + 5; // 9

Languages

The language can be specified using the @lang extension.

LanguageNotes 
javascriptSyntax highlights and evaluates the JavaScript 
scriptSame as javascript, but does not evaluate the results 
shellShell scripts or command-line 
textPlain text with no syntax highlighting 

Tables

The table directive consumes the entire body up until the next directive. To terminate a table early to begin a text block, use a _null: directive.

Each line of the body should be Row Data or a Variable Declaration (or continuation of a Variable Declaration). Blank lines are ignored.

Row Data

Each Row Data line must begin and end with a "|", with each gap representing the cell data, alignment with optional column and row spanning.

Alignment

The alignment for a cell is determined by the whitespace surrounding the cell data.

AlignmentWhitespace 
Left1 or fewer spaces before the content 
Right1 or fewer spaces after the content 
Center2 or more space both before and after the content 
Alignment Conditions (higher precedence listed first) 
Alignment Example
_table: Result of Alignment Example @style<compact> | center | | left | |left | | right | | right|
center 
left 
left 
right 
right 
Result of Alignment Example 

Row and Column Spanning

A column may end its content with any number of "<" which indicates how many additional columns to extend into.

If the cell content contains only a "^", then the row above is extended into this cell (into the same number of columns).

Cell Spanning Example
_table: Result of Cell Spanning Example @style<compact> | (1x1) | (1x2) <| (2x1) | | (2x2) <| (2x1) | ^ | | ^ | ^ | (1x1) |
(1x1)(1x2)(2x1) 
(2x2)(2x1) 
(1x1) 
Result of Cell Spanning Example 

Styles

The @style extension for a table can be used to control its appearance.

NameWidthColumns 
minimalminimum sizebest fit 
compact40%evenly spaced 
wide67%evenly spaced 
full100%evenly spaced 

Variables

Often the layout of a table is easier to express and maintain without uneven or changing content within it. So the content can be defined separately within a table directive using variables. A variable name must begin with a letter and must only contain letters and numbers.

Variables are also useful when content is repeated throughout a table.

A variable is declared by starting a line with "$NAME:", which consumes all lines until the next variable declaration or until the next table row line.

A variable name must start with a letter and may consist of letters and numbers. (i.e. /[a-z][a-z0-9]*/i)

Variables Example
_table: Result of Variables Example $Yes: This option is supported. $No: This option is **not** supported $bottom: This just represents an example of what is possible. Notice that variable content can span multiple lines. | **Feature** | **Supported** | | Dancing Monkey | $Yes | | Singing Turtle | $No | | Newt Hair | $Yes | | $bottom <|
FeatureSupported 
Dancing MonkeyThis option is supported. 
Singing TurtleThis option is not supported. 
Newt HairThis option is supported. 
This just represents an example of what is possible. Notice that variable content can span multiple lines. 
Result of Variables Example 

Configuration

Configuration is optional (but highly recommended) and may be either a simple JSON file (config.json) or a JS file (config.js) placed in the top of the source folder.

TODO: example JSON and example JS

Extensions

@inherit< markdown >

Adds an inherits description to a directive. The markdown may contain links.

@lang< text >

Set the language a code directive should be syntax-highlighted for. If "javascript", the code will be evaluated.

@nav< text >

Sets the name in the breadcrumbs when not the current node.

@note< markdown >

Adds a note to a directive. The markdown may contain links. If the directive already has an @INHERIT extension, that will be used instead and the @NOTE will be ignored.

@src< key >

Calls the configuration getSourceUrl(key, VALUE) to get a URL which will be linked to by a link next to the directive.

This extended directive function requires an advanced config.js Configuration file since it requires a JavaScript function.

@style< text >

The Table Style to use for a table directive.

License and Copyright

The ethers library (including all dependencies) are available under the MIT License, which permits a wide variety of uses.

MIT License

Copyright © 2019-2021 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.