#
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 >
source

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

provider.getCode( address [ , blockTag = latest ] ) ⇒ Promise< string< DataHexString > >
source

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

provider.getStorageAt( addr , pos [ , blockTag = latest ] ) ⇒ Promise< string< DataHexString > >
source

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

provider.getTransactionCount( address [ , blockTag = latest ] ) ⇒ Promise< number >
source

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.

Account Examples
// Get the balance for an account... provider.getBalance("ricmoo.firefly.eth"); // { Promise: { BigNumber: "25334210474552466902" } } // Get the code for a contract... provider.getCode("registrar.firefly.eth"); // { Promise: ' ' } // Get the storage value at position 0... provider.getStorageAt("registrar.firefly.eth", 0) // { Promise: '0x000000000000000000000000314159265dd8dbb310642f98f50c066173c1259b' } // Get transaction count of an account... provider.getTransactionCount("ricmoo.firefly.eth"); // { Promise: 712 }

##
Blocks Methods

provider.getBlock( block ) ⇒ Promise< Block >
source

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

provider.getBlockWithTransactions( block ) ⇒ Promise< BlockWithTransactions >
source

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

Block Examples
provider.getBlock(100004) // { Promise: { // 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(100004) // { Promise: { // difficulty: 3849295379889, // extraData: '0x476574682f76312e302e312d39383130306634372f6c696e75782f676f312e34', // gasLimit: { BigNumber: "3141592" }, // gasUsed: { BigNumber: "21000" }, // hash: '0xf93283571ae16dcecbe1816adc126954a739350cd1523a1559eabeae155fbb63', // miner: '0x909755D480A27911cB7EeeB5edB918fae50883c0', // nonce: '0x1a455280001cc3f8', // number: 100004, // parentHash: '0x73d88d376f6b4d232d70dc950d9515fad3b5aa241937e362fdbfd74d1c901781', // timestamp: 1439799168, // transactions: [ // { // blockHash: '0xf93283571ae16dcecbe1816adc126954a739350cd1523a1559eabeae155fbb63', // blockNumber: 100004, // chainId: 0, // confirmations: 11717911, // creates: null, // data: '0x', // from: '0xcf00A85f3826941e7A25BFcF9Aac575d40410852', // gasLimit: { BigNumber: "90000" }, // gasPrice: { BigNumber: "54588778004" }, // hash: '0x6f12399cc2cb42bed5b267899b08a847552e8c42a64f5eb128c1bcbd1974fb0c', // nonce: 25, // r: '0xb23adc880d3735e4389698dddc953fb02f1fa9b57e84d3510a2a4b3597ac2486', // s: '0x4e856f95c4e2828933246fb4765a5bfd2ca5959840643bef0e80b4e3a243d064', // to: '0xD9666150A9dA92d9108198a4072970805a8B3428', // transactionIndex: 0, // v: 27, // value: { BigNumber: "5000000000000000000" } // } // ] // } }

##
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.getResolver( name ) ⇒ Promise< EnsResolver >

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

provider.lookupAddress( address ) ⇒ Promise< string >
source

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.

provider.resolveName( name ) ⇒ Promise< string< Address > >
source

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.

ENS Examples
// Reverse lookup of an ENS by address... provider.lookupAddress("0x6fC21092DA55B392b045eD78F4732bff3C580e2c"); // { Promise: 'registrar.firefly.eth' } // Lookup an address of an ENS name... provider.resolveName("ricmoo.firefly.eth"); // { Promise: '0x8ba1f109551bD432803012645Ac136ddd64DBA72' }

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

resolver.getContentHash( ) ⇒ Promise< string >

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

resolver.getText( key ) ⇒ Promise< string >

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

##
Logs Methods

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

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 >
source

Returns the Network this Provider is connected to.

provider.getBlockNumber( ) ⇒ Promise< number >
source

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

provider.getGasPrice( ) ⇒ Promise< BigNumber >
source

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

provider.ready ⇒ Promise< Network >
source

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.

Network Status Examples
// The network information provider.getNetwork() // { // chainId: 1, // ensAddress: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', // name: 'homestead' // } // The current block number provider.getBlockNumber() // { Promise: 11817914 } // Get the current suggested gas price (in wei)... gasPrice = await provider.getGasPrice() // { BigNumber: "207000000000" } // ...often this gas price is easier to understand or // display to the user in gwei (giga-wei, or 1e9 wei) utils.formatUnits(gasPrice, "gwei") // '207.0'

##
Transactions Methods

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

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.

provider.estimateGas( transaction ) ⇒ Promise< BigNumber >
source

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.

provider.getTransaction( hash ) ⇒ Promise< TransactionResponse >
source

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.

provider.getTransactionReceipt( hash ) ⇒ Promise< TransactionReceipt >
source

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.

provider.sendTransaction( transaction ) ⇒ Promise< TransactionResponse >
source

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

provider.waitForTransaction( hash [ , confirms = 1 [ , timeout ] ] ) ⇒ Promise< TxReceipt >
source

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 Obeserver 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
source

Add a listener to be triggered for each eventName event.

provider.once( eventName , listener ) ⇒ this
source

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

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

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

provider.off( eventName [ , listener ] ) ⇒ this
source

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

provider.removeAllListeners( [ eventName ] ) ⇒ this
source

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

provider.listenerCount( [ eventName ] ) ⇒ number
source

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 >
source

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 Name | Arguments | Description |
`"block"` | blockNumber | emitted when a new block is mined |
`"error"` | error | emitted on any error |
`"pending"` | pendingTransaction | emitted 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"` | pollId | emitted prior to a polling loop is about to begin; (very rarely used by most developers) |
`"poll"` | pollId, blockNumber | emitted 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"` | pollId | emitted after all events from a polling loop are emitted; (very rarely used by most developers) |
`"debug"` | provider dependent | each 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, [ myAddress, myOtherAddress ] ] provider.on(topicSets, (log, event) => { // 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
source

Returns true if and only if object is a Provider.

The content of this site is licensed under the Creative Commons License. Generated on February 8, 2021, 3:25pm.