View Source Ethers (Ethers v0.5.5)

high-level module providing a convenient and efficient interface for interacting with the Ethereum blockchain using Elixir.

This module offers a simple API for common Ethereum operations such as deploying contracts, fetching current gas prices, and querying event logs.

Batching Requests

Often you would find yourself executing different actions without dependency. These actions can be combined together in one JSON RPC call. This will save on the number of round trips and improves latency.

Before continuing, please note that batching JSON RPC requests and using Ethers.Multicall are two different things. As a rule of thumb:

  • Use Ethers.Multicall if you need to make multiple contract calls and get the result on the same block.
  • Use Ethers.batch/2 if you need to make multiple JSON RPC operations which may or may not run on the same block (or even be related to any specific block e.g. eth_gas_price)

Make batch requests

Ethers.batch/2 supports all operations which the RPC module (Ethereumex by default) implements. Although some actions support pre and post processing and some are just forwarded to the RPC module.

Every request passed to Ethers.batch/2 can be in one of the following formats

  • action_name_atom: This only works with requests which do not require any additional data. e.g. :current_gas_price or :net_version.
  • {action_name_atom, data}: This works with all other actions which accept input data. e.g. :call, :send or :get_logs.
  • {action_name_atom, data, overrides_keyword_list}: Use this to override or add attributes to the action data. This is only accepted for these actions and will through error on others.
    • :call: data should be a Ethers.TxData struct and overrides are accepted.
    • :estimate_gas: data should be a Ethers.TxData struct or a map and overrides are accepted.
    • :get_logs: data should be a Ethers.EventFilter struct and overrides are accepted.
    • :send: data should be a Ethers.TxData struct and overrides are accepted.

Example

Ethers.batch([
  :current_block_number,
  :current_gas_price,
  {:call, Ethers.Contracts.ERC20.name(), to: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"},
  {:send, MyContract.ping(), from: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"},
  {:get_logs, Ethers.Contracts.ERC20.EventFilters.approval(nil, nil)} # <- can have add overrides
])
{:ok, [
  {:ok, 18539069},
  {:ok, 21221},
  {:ok, "Wrapped Ether"},
  {:ok, "0xed67b1aafdc823077166c8ee9da13c6a621d19f4d7a24a80353219c09bdac87f"},
  {:ok, [%Ethers.EventFilter{}]}
]}

Summary

Functions

Combines multiple requests and make a batch json RPC request.

Same as Ethers.batch/2 but raises on error.

Makes an eth_call to with the given Ethers.TxData struct and overrides. It then parses the response using the selector in the TxData struct.

Same as Ethers.call/2 but raises on error.

Returns the current block number of the blockchain.

Returns the current gas price from the RPC API

Deploys a contract to the blockchain.

Returns the address of the deployed contract if the deployment is finished and successful

Makes an eth_estimate_gas rpc call with the given parameters and overrides.

Returns the native token (ETH) balance of an account in wei.

Fetches the event logs with the given filter.

Returns the native transaction (ETH) by transaction hash.

Returns the transaction count of an address.

Returns the receipt of a transaction by it's hash.

Returns the current max priority fee per gas from the RPC API

Makes an eth_send rpc call to with the given data and overrides, Then returns the transaction hash.

Same as Ethers.send/2 but raises on error.

Signs a transaction and returns the encoded signed transaction hex.

Types

t_batch_request()

@type t_batch_request() :: atom() | {atom(), term()} | {atom(), term(), Keyword.t()}

Functions

batch(requests, opts \\ [])

@spec batch([t_batch_request()], Keyword.t()) ::
  {:ok, ok: term(), error: term()} | {:error, term()}

Combines multiple requests and make a batch json RPC request.

It returns {:ok, results} in case of success or {:error, reason} in case of RPC failure.

Each action will have an entry in the results. Each entry is again a tuple and either {:ok, result} or {:error, reason} in case of action failure.

Checkout Batching Requests sections in Ethers module for more examples.

Parameters

  • requests: A list of requests to execute.
  • opts: RPC related options. (No account and block options are accepted in batch)

Action

An action can be in either of the following formats.

  • {action_name_atom, action_data, action_overrides}
  • {action_name_atom, action_data}
  • action_name_atom

Examples

Ethers.batch([
  {:call, WETH.name()},
  {:call, WETH.symbol(), to: "[WETH ADDRESS]"},
  {:send, WETH.transfer("[RECEIVER]", 1000), from: "[SENDER]"},
  :current_block_number
])
{:ok, [ok: "Weapped Ethereum", ok: "WETH", ok: "0xhash...", ok: 182394532]}

batch!(actions, opts \\ [])

@spec batch!([t_batch_request()], Keyword.t()) :: [ok: term(), error: term()]

Same as Ethers.batch/2 but raises on error.

call(params, overrides \\ [])

@spec call(Ethers.TxData.t(), Keyword.t()) ::
  {:ok, [term()]} | {:ok, term()} | {:error, term()}

Makes an eth_call to with the given Ethers.TxData struct and overrides. It then parses the response using the selector in the TxData struct.

Overrides and Options

Other than what stated below, any other option given in the overrides keyword list will be merged with the map that the RPC client will receive.

  • :to: Indicates recepient address. (Contract address in this case)
  • :block: The block number or block alias. Defaults to latest
  • :rpc_client: The RPC Client to use. It should implement ethereum jsonRPC API. default: Ethereumex.HttpClient
  • :rpc_opts: Extra options to pass to rpc_client. (Like timeout, Server URL, etc.)

Return structure

For contract functions which return a single value (e.g. function test() returns (uint)) this returns {:ok, value} and for the functions which return multiple values it will return {:ok, [value0, value1]} (A list).

Examples

Ethers.Contract.ERC20.total_supply() |> Ethers.call(to: "0xa0b...ef6")
{:ok, 100000000000000}

call!(params, overrides \\ [])

@spec call!(Ethers.TxData.t(), Keyword.t()) :: term() | no_return()

Same as Ethers.call/2 but raises on error.

current_block_number(opts \\ [])

@spec current_block_number(Keyword.t()) :: {:ok, non_neg_integer()} | {:error, term()}

Returns the current block number of the blockchain.

current_gas_price(opts \\ [])

@spec current_gas_price(Keyword.t()) :: {:ok, non_neg_integer()}

Returns the current gas price from the RPC API

deploy(contract_module_or_binary, overrides \\ [])

@spec deploy(atom() | binary(), Keyword.t()) ::
  {:ok, Ethers.Types.t_hash()} | {:error, term()}

Deploys a contract to the blockchain.

This will return the transaction hash for the deployment transaction. To get the address of your deployed contract, use Ethers.deployed_address/2.

To deploy a cotract you must have the binary related to it. It can either be a part of the ABI File you have or as a separate file.

Parameters

  • contract_module_or_binary: Either the contract module which was already loaded or the compiled binary of the contract. The binary MUST be hex encoded.
  • overrides: A keyword list containing options and overrides.
    • :encoded_constructor: Hex encoded value for constructor parameters. (See constructor function of the contract module)
    • All other options from Ethers.send/2

deployed_address(tx_hash, opts \\ [])

@spec deployed_address(binary(), Keyword.t()) ::
  {:ok, Ethers.Types.t_address()}
  | {:error, :no_contract_address | :transaction_not_found | term()}

Returns the address of the deployed contract if the deployment is finished and successful

Parameters

  • tx_hash: Hash of the Transaction which created a contract.
  • opts: RPC and account options.

estimate_gas(tx_data, overrides \\ [])

@spec estimate_gas(map(), Keyword.t()) :: {:ok, non_neg_integer()} | {:error, term()}

Makes an eth_estimate_gas rpc call with the given parameters and overrides.

Overrides and Options

  • :to: Indicates recepient address. (Contract address in this case)
  • :rpc_client: The RPC Client to use. It should implement ethereum jsonRPC API. default: Ethereumex.HttpClient
  • :rpc_opts: Extra options to pass to rpc_client. (Like timeout, Server URL, etc.)
Ethers.Contract.ERC20.transfer("0xff0...ea2", 1000) |> Ethers.estimate_gas(to: "0xa0b...ef6")
{:ok, 12345}

estimate_gas!(tx_data, overrides \\ [])

@spec estimate_gas!(map(), Keyword.t()) :: non_neg_integer() | no_return()

Same as Ethers.estimate_gas/2 but raises on error.

get_balance(account, overrides \\ [])

@spec get_balance(Ethers.Types.t_address(), Keyword.t()) ::
  {:ok, non_neg_integer()} | {:error, term()}

Returns the native token (ETH) balance of an account in wei.

Parameters

  • account: Account which the balance is queried for.
  • overrides:
    • block: The block you want to query the balance of account in (defaults to latest).
    • rpc_client: The RPC module to use for this request (overrides default).
    • rpc_opts: Specific RPC options to specify for this request.

get_logs(event_filter, overrides \\ [])

@spec get_logs(map(), Keyword.t()) :: {:ok, [Ethers.Event.t()]} | {:error, atom()}

Fetches the event logs with the given filter.

Overrides and Options

  • :address: Indicates event emitter contract address. (nil means all contracts)
  • :rpc_client: The RPC Client to use. It should implement ethereum jsonRPC API. default: Ethereumex.HttpClient
  • :rpc_opts: Extra options to pass to rpc_client. (Like timeout, Server URL, etc.)
  • :fromBlock | :from_block: Minimum block number of logs to filter.

  • :toBlock | :to_block: Maximum block number of logs to filter.

get_logs!(params, overrides \\ [])

@spec get_logs!(map(), Keyword.t()) :: [Ethers.Event.t()] | no_return()

Same as Ethers.get_logs/2 but raises on error.

get_transaction(tx_hash, opts \\ [])

@spec get_transaction(Ethers.Types.t_hash(), Keyword.t()) ::
  {:ok, Ethers.Transaction.t()} | {:error, term()}

Returns the native transaction (ETH) by transaction hash.

Parameters

  • tx_hash: Transaction hash which the transaction is queried for.
  • overrides:
    • rpc_client: The RPC module to use for this request (overrides default).
    • rpc_opts: Specific RPC options to specify for this request.

get_transaction_count(account, overrides \\ [])

@spec get_transaction_count(Ethers.Types.t_address(), Keyword.t()) ::
  {:ok, non_neg_integer()} | {:error, term()}

Returns the transaction count of an address.

Parameters

  • account: Account which the transaction count is queried for.
  • overrides:
    • block: The block you want to query the transaction count in (defaults to latest).
    • rpc_client: The RPC module to use for this request (overrides default).
    • rpc_opts: Specific RPC options to specify for this request.

get_transaction_receipt(tx_hash, opts \\ [])

@spec get_transaction_receipt(Ethers.Types.t_hash(), Keyword.t()) ::
  {:ok, map()} | {:error, term()}

Returns the receipt of a transaction by it's hash.

Parameters

  • tx_hash: Transaction hash which the transaction receipt is queried for.
  • overrides:
    • rpc_client: The RPC module to use for this request (overrides default).
    • rpc_opts: Specific RPC options to specify for this request.

max_priority_fee_per_gas(opts \\ [])

@spec max_priority_fee_per_gas(Keyword.t()) :: {:ok, non_neg_integer()}

Returns the current max priority fee per gas from the RPC API

send(tx_data, overrides \\ [])

@spec send(map() | Ethers.TxData.t(), Keyword.t()) ::
  {:ok, String.t()} | {:error, term()}

Makes an eth_send rpc call to with the given data and overrides, Then returns the transaction hash.

Overrides and Options

Other than what stated below, any other option given in the overrides keyword list will be merged with the map that the RPC client will receive.

Required Options

  • :from: The address of the account to sign the transaction with.

Optional Options

  • :access_list: List of storage slots that this transaction accesses (optional)
  • :chain_id: Chain id for the transaction (defaults to chain id from RPC server).
  • :gas_price: (legacy only) max price willing to pay for each gas.
  • :gas: Gas limit for execution of this transaction.
  • :max_fee_per_gas: (EIP-1559 only) max fee per gas (defaults to 120% current gas price estimate).
  • :max_priority_fee_per_gas: (EIP-1559 only) max priority fee per gas or validator tip. (defaults to zero)
  • :nonce: Nonce of the transaction. (defaults to number of transactions of from address)
  • :rpc_client: The RPC Client to use. It should implement ethereum jsonRPC API. default: Ethereumex.HttpClient
  • :rpc_opts: Extra options to pass to rpc_client. (Like timeout, Server URL, etc.)
  • :signer: The signer module to use for signing transaction. Default is nil and will rely on the RPC server for signing.
  • :signer_opts: Options for signer module. See your signer docs for more details.
  • :tx_type: Transaction type. Either :eip1559 (default) or :legacy.
  • :to: Address of the contract or a receiver of this transaction. (required if TxData does not have default_address)
  • :value: Ether value to send with the transaction to the receiver (from => to).

Examples

Ethers.Contract.ERC20.transfer("0xff0...ea2", 1000) |> Ethers.send(to: "0xa0b...ef6")
{:ok, _tx_hash}

send!(tx_data, overrides \\ [])

@spec send!(map() | Ethers.TxData.t(), Keyword.t()) :: String.t() | no_return()

Same as Ethers.send/2 but raises on error.

sign_transaction(tx_data, overrides \\ [])

@spec sign_transaction(map(), Keyword.t()) :: {:ok, binary()} | {:error, term()}

Signs a transaction and returns the encoded signed transaction hex.

Parameters

Accepts same parameters as Ethers.send/2.

sign_transaction!(tx_data, overrides \\ [])

@spec sign_transaction!(map(), Keyword.t()) :: binary() | no_return()

Same as Ethers.sign_transaction/2 but raises on error.