ethers.js/docs.wrm/api/providers/provider.wrm

553 lines
20 KiB
Plaintext
Raw Normal View History

2020-05-08 10:24:40 +03:00
_section: Provider @<Provider>
2021-02-08 22:52:31 +03:00
A **Provider** in ethers is a read-only abstraction to
access the blockchain data.
_note: 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.
2020-05-08 10:24:40 +03:00
_subsection: Accounts Methods @<Provider--account-methods>
2020-05-08 10:24:40 +03:00
_property: provider.getBalance(address [ , blockTag = latest ]) => Promise<[[BigNumber]]> @<Provider-getBalance> @SRC<providers/base-provider>
Returns the balance of //address// as of the //blockTag// block height.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_result:
await provider.getBalance("ricmoo.eth");
//_log:
2020-05-08 10:24:40 +03:00
_property: provider.getCode(address [ , blockTag = latest ]) => Promise<string<[[DataHexString]]>> @<Provider-getCode> @SRC<providers/base-provider>
Returns the contract code of //address// as of the //blockTag// block height. If there is
no contract currently deployed, the result is ``0x``.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_result:
await provider.getCode("registrar.firefly.eth");
//_log:
2021-06-12 00:13:46 +03:00
_property: provider.getStorageAt(addr, pos [ , blockTag = latest ]) => Promise<string<[[DataHexString]]>> @<Provider-getStorageAt> @SRC<providers/base-provider>
Returns the ``Bytes32`` value of the position //pos// at address //addr//, as of the //blockTag//.
_code: @lang<javascript>
//_result:
await provider.getStorageAt("registrar.firefly.eth", 0)
//_log:
2021-06-12 00:13:46 +03:00
_property: provider.getTransactionCount(address [ , blockTag = latest ]) => Promise<number> @<Provider-getTransactionCount> @SRC<providers/base-provider>
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.
_code: @lang<javascript>
//_result:
2021-06-12 00:13:46 +03:00
await provider.getTransactionCount("ricmoo.eth");
//_log:
2020-05-08 10:24:40 +03:00
_subsection: Blocks Methods @<Provider--block-methods>
2020-05-08 10:24:40 +03:00
_property: provider.getBlock(block) => Promise<[[providers-Block]]> @<Provider-getBlock> @SRC<providers/base-provider>
Get the //block// from the network, where the ``result.transactions`` is a list
of transaction hashes.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
2020-06-12 10:38:55 +03:00
//_result:
await provider.getBlock(100004)
//_log:
2020-06-12 10:38:55 +03:00
2021-06-12 00:13:46 +03:00
_property: provider.getBlockWithTransactions(block) => Promise<[[providers-BlockWithTransactions]]> @<Provider-getBlockWithTransactions> @SRC<providers/base-provider>
Get the //block// from the network, where the ``result.transactions`` is
an Array of [[providers-TransactionResponse]] objects.
_code: @lang<javascript>
//_result:
await provider.getBlockWithTransactions(100004)
//_log:
2020-06-12 10:38:55 +03:00
_subsection: Ethereum Naming Service (ENS) Methods @<Provider--ens-methods>
2020-06-12 10:38:55 +03:00
The [Ethereum Naming Service](link-ens) (ENS) allows a short and
easy-to-remember ENS Name to be attached to any set of keys
2020-06-12 10:38:55 +03:00
and values.
One of the most common uses for this is to use a simple name to
refer to an [Ethereum Address](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.
2022-01-31 06:58:43 +03:00
_property: provider.getAvatar(name) => Promise<string>
Returns the URL for the avatar associated to the ENS name, or null
if no avatar was configured.
_property: provider.getResolver(name) => Promise<[[EnsResolver]]>
Returns an EnsResolver instance which can be used to further inquire
about specific entries for an ENS name.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_hide: provider = ethers.getDefaultProvider();
// See below (Resolver) for examples of using this object
const resolver = await provider.getResolver("ricmoo.eth");
//_hide: _page.resolver = resolver;
2020-05-08 10:24:40 +03:00
_property: provider.lookupAddress(address) => Promise<string> @<Provider-lookupAddress> @SRC<providers/base-provider>
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.
2021-06-12 00:13:46 +03:00
An ENS name requries additional configuration to setup a reverse
record, they are not automatically set up.
_code: @lang<javascript>
//_result:
await provider.lookupAddress("0x5555763613a12D8F3e73be831DFf8598089d3dCa");
//_log:
2020-05-08 10:24:40 +03:00
_property: provider.resolveName(name) => Promise<string<[Address](address)>> @<Provider-ResolveName> @SRC<providers/base-provider>
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.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_result:
2021-06-12 00:13:46 +03:00
await provider.resolveName("ricmoo.eth");
//_log:
_subsection: EnsResolver @<EnsResolver>
_property: resolver.name => string
The name of this resolver.
_property: resolver.address => string<[[address]]>
The address of the Resolver.
_property: resolver.getAddress([ cointType = 60 ]) => Promise<string>
Returns a Promise which resolves to the [[link-eip-2304]] multicoin address
stored for the //coinType//. By default an Ethereum [[address]]
(``coinType = 60``) will be returned.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_hide: const resolver = _page.resolver;
// By default, looks up the Ethereum address
// (this will match provider.resolveName)
//_result:
await resolver.getAddress();
//_log:
// Specify the coinType for other coin addresses (0 = Bitcoin)
//_result:
await resolver.getAddress(0);
//_log:
2022-01-31 06:58:43 +03:00
_property: 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
_property: resolver.getContentHash() => Promise<string>
Returns a Promise which resolves to any stored [[link-eip-1577]] content hash.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_hide: const resolver = _page.resolver;
//_result:
await resolver.getContentHash();
//_log:
_property: resolver.getText(key) => Promise<string>
Returns a Promise which resolves to any stored [[link-eip-634]] text entry for //key//.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_hide: const resolver = _page.resolver;
//_result:
await resolver.getText("email");
//_log:
//_result:
await resolver.getText("url");
//_log:
//_result:
await resolver.getText("com.twitter");
//_log:
2020-05-08 10:24:40 +03:00
_subsection: Logs Methods @<Provider--log-methods>
2020-05-08 10:24:40 +03:00
_property: provider.getLogs(filter) => Promise<Array<[[providers-Log]]>> @<Provider-getLogs> @SRC<providers/base-provider>
Returns the Array of [[providers-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.
2020-05-08 10:24:40 +03:00
_subsection: Network Status Methods @<Provider--network-methods>
2020-05-08 10:24:40 +03:00
_property: provider.getNetwork() => Promise<[[providers-Network]]> @<Provider-getNetwork> @SRC<providers/base-provider:method.BaseProvider.getNetwork>
Returns the [[providers-Network]] this Provider is connected to.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
2021-06-12 00:13:46 +03:00
//_result:
await provider.getNetwork()
//_hide: _ = utils.shallowCopy(_);
//_hide: delete _._defaultProvider;
//_log:
2021-06-12 00:13:46 +03:00
_property: provider.getBlockNumber() => Promise<number> @<Provider-getBlockNumber> @SRC<providers/base-provider>
Returns the block number (or height) of the most recently mined block.
2020-06-12 10:38:55 +03:00
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
2020-06-12 10:38:55 +03:00
//_result:
await provider.getBlockNumber()
//_log:
2020-06-12 10:38:55 +03:00
2021-06-12 00:13:46 +03:00
_property: provider.getGasPrice() => Promise<[[BigNumber]]> @<Provider-getGasPrice> @SRC<providers/base-provider>
Returns a //best guess// of the [[gas-price]] to use in a transaction.
_code: @lang<javascript>
// The gas price (in wei)...
2020-06-12 10:38:55 +03:00
gasPrice = await provider.getGasPrice()
//_log: gasPrice
2020-06-12 10:38:55 +03:00
// ...often this gas price is easier to understand or
2021-06-12 00:13:46 +03:00
// display to the user in gwei
//_result:
2020-06-12 10:38:55 +03:00
utils.formatUnits(gasPrice, "gwei")
//_log:
2020-06-12 10:38:55 +03:00
2021-08-27 22:35:23 +03:00
_property: provider.getFeeData() => Promise<[[providers-FeeData]]> @<Provider-getFeeData> @SRC<abstract-provider>
Returns the current recommended [[providers-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.
_code: @lang<javascript>
// The gas price (in wei)...
feeData = await provider.getFeeData()
//_log: feeData
// ...often these values are easier to understand or
// display to the user in gwei
//_result:
utils.formatUnits(feeData.maxFeePerGas, "gwei")
//_log:
2021-06-12 00:13:46 +03:00
_property: provider.ready => Promise<[[providers-Network]]> @<Provider-ready> @src<providers/base-provider>
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.
2020-05-08 10:24:40 +03:00
_subsection: Transactions Methods @<Provider--transaction-methods>
2020-05-08 10:24:40 +03:00
_property: provider.call(transaction [ , blockTag = latest ]) => Promise<string<[[DataHexString]]>> @<Provider-call> @SRC<providers/base-provider>
2020-01-10 09:01:00 +03:00
Returns the result of executing the //transaction//, using //call//. A call
does not require any ether, but cannot change any state. This is useful
2020-11-23 07:03:50 +03:00
for calling getters on Contracts.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_result:
await provider.call({
// ENS public resovler address
to: "0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41",
// `function addr(namehash("ricmoo.eth")) view returns (address)`
data: "0x3b3b57debf074faa138b72c65adbdcfb329847e4f2c04bde7f7dd7fcad5a52d2f395a558"
});
//_log:
2020-05-08 10:24:40 +03:00
_property: provider.estimateGas(transaction) => Promise<[[BigNumber]]> @<Provider-estimateGas> @SRC<providers/base-provider>
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.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_hide: const parseEther = ethers.utils.parseEther;
//_result:
await provider.estimateGas({
// Wrapped ETH address
to: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
// `function deposit() payable`
data: "0xd0e30db0",
// 1 ether
value: parseEther("1.0")
});
//_log:
_property: provider.getTransaction(hash) => Promise<[[providers-TransactionResponse]]> @<Provider-getTransaction> @src<providers/base-provider>
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.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_result:
await provider.getTransaction("0x5b73e239c55d790e3c9c3bbb84092652db01bb8dbf49ccc9e4a318470419d9a0");
//_log:
_property: provider.getTransactionReceipt(hash) => Promise<[[providers-TransactionReceipt]]> @<Provider-getTransactionReceipt> @src<providers/base-provider>
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.
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_result:
await provider.getTransactionReceipt("0x5b73e239c55d790e3c9c3bbb84092652db01bb8dbf49ccc9e4a318470419d9a0");
//_log:
2020-05-08 10:24:40 +03:00
_property: provider.sendTransaction(transaction) => Promise<[[providers-TransactionResponse]]> @<Provider-sendTransaction> @SRC<providers/base-provider>
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).
2021-06-12 00:13:46 +03:00
_code: @lang<javascript>
//_hide: const provider = localProvider;
//_hide: const wallet = new ethers.Wallet(ethers.utils.id("HelloWorld"), provider);
//_hide: const fundTx = await localSigner.sendTransaction({
//_hide: to: wallet.address,
//_hide: value: ethers.utils.parseEther("2.0")
//_hide: });
//_hide: await fundTx.wait();
//_hide: const tx = await localSigner.populateTransaction({ to: "ricmoo.eth", value: ethers.utils.parseEther("3.14159") });
//_hide: const signedTx = await localSigner.signTransaction(tx);
2021-06-12 00:13:46 +03:00
//_verbatim: `const signedTx = ${ JSON.stringify(signedTx) };`
2021-06-12 00:13:46 +03:00
//_result:
await provider.sendTransaction(signedTx);
2021-06-12 00:13:46 +03:00
//_log:
2020-05-08 10:24:40 +03:00
_property: provider.waitForTransaction(hash [ , confirms = 1 [ , timeout ] ]) => Promise<[TxReceipt](providers-TransactionReceipt)> @<Provider-waitForTransaction> @SRC<providers/base-provider>
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.
2020-05-08 10:24:40 +03:00
_subsection: Event Emitter Methods @<Provider--event-methods>
The EventEmitter API allows applications to use an
[[link-wiki-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](Provider--events), not only strings. The objects
are normalized internally.
2020-05-08 10:24:40 +03:00
_property: provider.on(eventName, listener) => this @<Provider-on> @SRC<providers/base-provider>
Add a //listener// to be triggered for each //eventName// [event](Provider--events).
2020-05-08 10:24:40 +03:00
_property: provider.once(eventName, listener) => this @<Provider-once> @SRC<providers/base-provider>
Add a //listener// to be triggered for only the next
//eventName// [event](Provider--events), at which time it will be removed.
2020-05-08 10:24:40 +03:00
_property: provider.emit(eventName, ...args) => boolean @<Provider-emit> @SRC<providers/base-provider>
Notify all listeners of the //eventName// [event](Provider--events),
passing //args// to each listener. This is generally only used internally.
2020-05-08 10:24:40 +03:00
_property: provider.off(eventName [ , listener ]) => this @<Provider-off> @SRC<providers/base-provider>
Remove a //listener// for the //eventName// [event](Provider--events).
If no //listener// is provided, all listeners for //eventName// are removed.
2020-05-08 10:24:40 +03:00
_property: provider.removeAllListeners([ eventName ]) => this @<Provider-removeAllListeners> @SRC<providers/base-provider>
Remove all the listeners for the //eventName// [events](Provider--events).
If no //eventName// is provided, **all** events are removed.
2020-05-08 10:24:40 +03:00
_property: provider.listenerCount([ eventName ]) => number @<Provider-listenerCount> @SRC<providers/base-provider>
Returns the number of listeners for the //eventName// [events](Provider--events).
If no //eventName// is provided, the total number of listeners is returned.
2020-05-08 10:24:40 +03:00
_property: provider.listeners(eventName) => Array<Listener> @<Provider-listeners> @SRC<providers/base-provider>
Returns the list of Listeners for the //eventName// [events](Provider--events).
2020-05-08 10:24:40 +03:00
_heading: Events @<Provider--events>
2020-05-08 10:24:40 +03:00
Any of the following may be used as the //eventName// in the above methods.
_definition: **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](providers-EventFilter) for more information on filtering events.
2020-05-08 10:24:40 +03:00
_definition: **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](providers-EventFilter) for more information on filtering events.
2020-05-08 10:24:40 +03:00
_definition: **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](Provider-once) method is used than the [on](Provider-on) method.
_null:
In addition to transaction and filter events, there are several named
events.
_table: Named Provider Events @style<full>
$Block: emitted when a new block is mined
$Error: emitted on any error
$Pending: 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: emitted prior to a polling loop is about to begin;
//(very rarely used by most developers)//
$DidPoll: emitted after all events from a polling loop are emitted;
//(very rarely used by most developers)//
$Poll: 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)//
$Debug: each Provider may use this to emit useful debugging information
and the format is up to the developer;
//(very rarely used by most developers)//
| **Event Name** | **Arguments** <| **Description** <<<|
| ``"block"`` | //blockNumber// <| $Block <<<|
| ``"error"`` | //error// <| $Error <<<|
| ``"pending"`` | //pendingTransaction// <| $Pending <<<|
| ``"willPoll"`` | //pollId// <| $WillPoll <<<|
| ``"poll"`` | //pollId//, //blockNumber// <| $Poll <<<|
| ``"didPoll"`` | //pollId// <| $DidPoll <<<|
| ``"debug"`` | provider dependent <| $Debug <<<|
2020-06-12 10:38:55 +03:00
_code: Events Example @lang<javascript>
2020-05-08 10:24:40 +03:00
//_hide: const txHash = utils.id("dummy-data");
//_hide: const myAddress = ethers.constants.HashZero;
//_hide: const myOtherAddress = ethers.constants.HashZero;
2021-08-09 21:48:02 +03:00
//_hide: const hexZeroPad = ethers.utils.hexZeroPad;
2020-05-08 10:24:40 +03:00
2020-06-12 10:38:55 +03:00
provider.on("block", (blockNumber) => {
2020-05-08 10:24:40 +03:00
// 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
2020-06-12 10:38:55 +03:00
filter = {
2020-05-08 10:24:40 +03:00
address: "dai.tokens.ethers.eth",
topics: [
2020-07-18 13:08:45 +03:00
utils.id("Transfer(address,address,uint256)")
2020-05-08 10:24:40 +03:00
]
}
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)
2020-06-12 10:38:55 +03:00
topicSets = [
2020-07-18 13:08:45 +03:00
utils.id("Transfer(address,address,uint256)"),
2020-05-08 10:24:40 +03:00
null,
[
2021-08-09 21:48:02 +03:00
hexZeroPad(myAddress, 32),
hexZeroPad(myOtherAddress, 32)
2020-05-08 10:24:40 +03:00
]
]
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
});
2020-06-12 10:38:55 +03:00
2020-05-08 10:24:40 +03:00
provider.on("error", (tx) => {
// Emitted when any error occurs
});
//_hide: provider.removeAllListeners() /* Make sure the docs build without waiting forever */
2020-05-08 10:24:40 +03:00
_subsection: Inspection Methods @<Provider--inspection-methods>
_property: Provider.isProvider(object) => boolean @<Provider-isProvider> @SRC<abstract-provider>
2019-08-22 08:52:17 +03:00
Returns true if and only if //object// is a Provider.