Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/elixir.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ jobs:
- otp: "28.x"
elixir: "1.19"
report_coverage: false
# Oldest supported Elixir (see `elixir:` in mix.exs)
- otp: "27.x"
elixir: "1.18"
report_coverage: false

steps:
- uses: actions/checkout@v7
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ erl_crash.dump
*.ez

# Ignore package tarball (built via "mix hex.build").
elixirium-*.tar
ethers-*.tar

# Temporary files, for example, from tests.
/tmp/
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

### Breaking Changes

- Require Elixir 1.18 or later
- Remove deprecated `Ethers.send/2`, `Ethers.send!/2` and the `:send` action of `Ethers.batch/2`
- Remove deprecated `Ethers.Utils.maybe_add_gas_limit/2` and `Ethers.Transaction.calculate_y_parity_or_v/2`
- Remove the `SKIP_EX_KECCAK` environment variable
- Fetched transactions hold `access_list` and `blob_versioned_hashes` as binaries instead of raw RPC values
- `Ethers.Transaction.to_rpc_map/1` emits access lists as `{address, storageKeys}` objects
- `Ethers.Transaction.to_rpc_map/1` emits EIP-7702 authorization `r` and `s` as quantities
Expand Down Expand Up @@ -33,6 +37,7 @@
- Add `Ethers.Transaction.Unknown` for unregistered transaction types like OP-stack deposit transactions
- Restructure the documentation into a shorter README, topic guides, a cheatsheet and a Livebook tour
- Add `usage-rules.md` for coding agents and ship the guides in the package
- Document the `Ethers.RpcClient.Adapter` behaviour for custom RPC clients

### Bug Fixes

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ Then point it at a JSON-RPC endpoint: your own node, a provider, or a public end
config :ethereumex, url: "https://your-ethereum-node.example"
```

Ethers needs Elixir 1.15 or later. Coming from 0.8 or earlier? Read the
Ethers needs Elixir 1.18 or later. Coming from 0.8 or earlier? Read the
[upgrade guide](https://ethers.hexdocs.pm/upgrading.html).

## Try it
Expand Down
8 changes: 3 additions & 5 deletions guides/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ ones.

### RPC Client `:rpc_client`

Specifies the module responsible for making JSON-RPC calls to the Ethereum node. This module must implement
`Ethers.RpcClient.Adapter` behaviour.
Specifies the module responsible for making JSON-RPC calls to the Ethereum node. This module must
implement the `Ethers.RpcClient.Adapter` behaviour, which also documents how to write your own.

#### Example

Expand All @@ -70,9 +70,7 @@ Module for Keccak-256 hashing operations. Uses `ExKeccak` by default.
config :ethers, keccak_module: ExKeccak
```

`ExKeccak` is a Rustler NIF. If your target cannot build or load it, set `:keccak_module` to a
module of your own that exports `hash_256/1`, and set the environment variable
`SKIP_EX_KECCAK=true` when fetching and compiling dependencies.
To use another implementation, set `:keccak_module` to a module that exports `hash_256/1`.

### JSON Module `json_module`

Expand Down
2 changes: 1 addition & 1 deletion guides/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ end
> It is needed for `Ethers.Signer.Local` and for recovering the signer of a message or a
> transaction locally. Leave it out if a node or a remote signer does all your signing.

Ethers needs Elixir 1.15 or later. If you are coming from 0.8 or earlier, read the
Ethers needs Elixir 1.18 or later. If you are coming from 0.8 or earlier, read the
[upgrade guide](upgrading.md) first.

## Connect to a node
Expand Down
39 changes: 39 additions & 0 deletions guides/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,45 @@ This guide provides information about upgrading between different versions of Et

## Upgrading to 1.0.0

### Requirements

#### Elixir 1.18 or later

Ethers 1.0.0 requires Elixir 1.18 or later. Versions up to 0.8.x accepted Elixir 1.15.

#### `SKIP_EX_KECCAK` is removed

The `SKIP_EX_KECCAK` environment variable no longer has any effect, `ex_keccak` and `ex_abi` are
always required. Use the `:keccak_module` [configuration](configuration.md) to hash with another
module.

### Removed Functions

The functions deprecated in 0.6.0 are removed.

| Removed | Use instead |
| --- | --- |
| `Ethers.send/2`, `Ethers.send!/2` | `Ethers.send_transaction/2`, `Ethers.send_transaction!/2` |
| `:send` action of `Ethers.batch/2` | `:send_transaction` |
| `Ethers.Utils.maybe_add_gas_limit/2` | `Ethers.estimate_gas/2` |
| `Ethers.Transaction.calculate_y_parity_or_v/2` | The same function of `Ethers.Transaction.Signed` |

```elixir
# Before (0.8.x)
Ethers.send(tx_data, from: sender)
Ethers.batch([{:send, tx_data, from: sender}])
{:ok, %{gas: gas_hex}} = Ethers.Utils.maybe_add_gas_limit(%{from: sender, to: recipient})

# After (1.0.0)
Ethers.send_transaction(tx_data, from: sender)
Ethers.batch([{:send_transaction, tx_data, from: sender}])
{:ok, gas} = Ethers.estimate_gas(%{from: sender, to: recipient})
```

`Ethers.estimate_gas/2` returns the estimate as an integer and adds no margin.
`Ethers.send_transaction/2` adds the [`:default_gas_margin`](configuration.md#gas-margins) itself
when it fills in the gas limit for a signer.

### Transaction RPC Maps

#### Decoded access lists and blob hashes in fetched transactions
Expand Down
25 changes: 7 additions & 18 deletions lib/ethers.ex
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,8 @@ defmodule Ethers do
get_transaction_receipt: :eth_get_transaction_receipt,
max_priority_fee_per_gas: :eth_max_priority_fee_per_gas,
send_transaction: :eth_send_transaction,
blob_base_fee: :eth_blob_base_fee,
# Deprecated, kept for backward compatibility
send: :eth_send_transaction
blob_base_fee: :eth_blob_base_fee
}
@send_transaction_actions [:send_transaction, :send]

# Percentiles the priority fees of recent blocks are sampled at per fee estimation speed
@fee_estimation_percentiles %{slow: 25, standard: 50, fast: 75}
Expand Down Expand Up @@ -609,9 +606,6 @@ defmodule Ethers do
end
end

@deprecated "Use `Ethers.send_transaction/2` instead"
def send(tx_data, overrides \\ []), do: send_transaction(tx_data, overrides)

@doc """
Same as `Ethers.send_transaction/2` but raises on error.
"""
Expand All @@ -623,9 +617,6 @@ defmodule Ethers do
end
end

@deprecated "Use `Ethers.send_transaction!/2` instead"
def send!(tx_data, overrides \\ []), do: send_transaction!(tx_data, overrides)

@doc """
Signs a transaction and returns the encoded signed transaction hex.

Expand Down Expand Up @@ -1495,12 +1486,11 @@ defmodule Ethers do
maybe_use_signer(tx_params, opts)
end

defp pre_process("0x" <> _ = signed_tx, _overrides, action, _opts)
when action in @send_transaction_actions do
defp pre_process("0x" <> _ = signed_tx, _overrides, :send_transaction, _opts) do
{:ok, signed_tx, :eth_send_raw_transaction}
end

defp pre_process(tx_data, overrides, action, opts) when action in @send_transaction_actions do
defp pre_process(tx_data, overrides, :send_transaction = action, opts) do
tx_params = TxData.to_map(tx_data, overrides)

with :ok <- check_params(tx_params, action) do
Expand Down Expand Up @@ -1589,9 +1579,8 @@ defmodule Ethers do
{:ok, resp}
end

defp post_process({:ok, tx_hash}, _tx_data, action)
when valid_result(tx_hash) and action in @send_transaction_actions,
do: {:ok, tx_hash}
defp post_process({:ok, tx_hash}, _tx_data, :send_transaction) when valid_result(tx_hash),
do: {:ok, tx_hash}

defp post_process({:ok, tx_hash}, _tx_params, _action = :deploy) when valid_result(tx_hash),
do: {:ok, tx_hash}
Expand Down Expand Up @@ -1935,15 +1924,15 @@ defmodule Ethers do
defp check_to_address(%{to: to_address}, _action) when is_binary(to_address), do: :ok

defp check_to_address(%{to: nil}, action)
when action in [:send, :send_transaction, :sign_transaction, :estimate_gas],
when action in [:send_transaction, :sign_transaction, :estimate_gas],
do: :ok

defp check_to_address(_params, _action), do: {:error, :no_to_address}

defp check_from_address(%{from: from}, _action) when not is_nil(from), do: :ok

defp check_from_address(_tx_params, action)
when action in [:send, :send_transaction, :sign_transaction],
when action in [:send_transaction, :sign_transaction],
do: {:error, :no_from_address}

defp check_from_address(_tx_params, _action), do: :ok
Expand Down
128 changes: 122 additions & 6 deletions lib/ethers/rpc_client/adapter.ex
Original file line number Diff line number Diff line change
@@ -1,59 +1,175 @@
defmodule Ethers.RpcClient.Adapter do
@moduledoc false
@moduledoc """
Behaviour of the JSON-RPC clients Ethers sends its requests with.

Ethers talks to a node through an RPC client module. The default one sends requests over HTTP
with Ethereumex. Implement this behaviour to use another transport, to route requests between
several endpoints, or to add retries, rate limiting or instrumentation.

## Using an adapter

Set it as the default client:

```elixir
config :ethers, rpc_client: MyApp.RpcClient
```

Or choose it for a single request with the `:rpc_client` option:

```elixir
Ethers.call(tx_data, rpc_client: MyApp.RpcClient, rpc_opts: [url: "https://..."])
```

## Implementing an adapter

Each callback sends the JSON-RPC method it is named after, `eth_get_balance/3` for
`eth_getBalance`.

```elixir
defmodule MyApp.RpcClient do
@behaviour Ethers.RpcClient.Adapter

@impl true
def eth_block_number(opts), do: request("eth_blockNumber", [], opts)

@impl true
def eth_get_balance(account, block, opts) do
request("eth_getBalance", [account, block], opts)
end

# ... the other callbacks

defp request(method, params, opts) do
# Send the request, then return {:ok, result} or {:error, reason}
end
end
```

- **Arguments** are the parameters of the method, in order and already encoded for JSON-RPC:
quantities and data are `0x` prefixed hex strings, blocks are a hex quantity or a tag such as
`"latest"`, and transactions, filters and state overrides are maps.
- **The last argument** is the `:rpc_opts` keyword list of the request (`[]` if not given). It is
passed as is, so an adapter defines its own options.
- **The return value** is `{:ok, result}` with the `result` member of the JSON-RPC response,
decoded from JSON and otherwise untouched, or `{:error, reason}`. Return the JSON-RPC `error`
member as `reason` when the node responds with one. Ethers decodes the custom errors of a
contract from its `"data"` member.

## Optional callbacks

An adapter may leave out the callbacks below. The functions that need them then return an error:

| Callback | Without it |
| --- | --- |
| `c:eth_call/4`, `c:eth_estimate_gas/4` | `:state_overrides` returns `{:error, :state_overrides_not_supported}` |
| `c:eth_config/1` | `Ethers.config/1` returns `{:error, :not_supported}` |
| `c:eth_create_access_list/3` | `Ethers.create_access_list/2` returns `{:error, :not_supported}` |
| `c:eth_fee_history/4` | `Ethers.fee_history/4` returns `{:error, :not_supported}`, and missing transaction fees are filled in from `eth_gasPrice` and `eth_maxPriorityFeePerGas` |
| `c:eth_get_code/3` | `Ethers.get_code/2` returns `{:error, :not_supported}` |
"""

@typedoc """
A failed request.

The reason is the `error` member of the JSON-RPC response (a map with `"code"`, `"message"` and
optionally `"data"`), or a description of a failure of the client itself.
"""
@type error :: {:error, map() | binary() | atom()}

@callback batch_request([{atom(), list(boolean() | binary())}], keyword()) ::
{:ok, [any()]} | error
@doc """
Sends several requests as one JSON-RPC batch.

Each request is a `{method, params}` tuple. `method` is the name of a callback of this
behaviour, or of any other method given to `Ethers.batch/2` (such as `:net_version`), and
`params` are its arguments without the options.

Returns the `{:ok, result}` or `{:error, reason}` of every request, in the order of the
requests.
"""
@callback batch_request([{method :: atom(), params :: [term()]}], keyword()) ::
{:ok, [{:ok, term()} | {:error, term()}]} | error()

@doc "Sends `eth_blockNumber`."
@callback eth_block_number(keyword()) :: {:ok, binary()} | error()

@doc "Sends `eth_call`."
@callback eth_call(map(), binary(), keyword()) :: {:ok, binary()} | error()

@doc "Sends `eth_call` with state overrides."
@callback eth_call(map(), binary(), state_overrides :: map(), keyword()) ::
{:ok, binary()} | error()

@doc "Sends `eth_chainId`."
@callback eth_chain_id(keyword()) :: {:ok, binary()} | error()

@doc "Sends `eth_config`."
@callback eth_config(keyword()) :: {:ok, map()} | error()

@doc "Sends `eth_createAccessList`."
@callback eth_create_access_list(map(), binary(), keyword()) :: {:ok, map()} | error()

@doc "Sends `eth_estimateGas`."
@callback eth_estimate_gas(map(), keyword()) :: {:ok, binary()} | error()

@doc "Sends `eth_estimateGas` with state overrides."
@callback eth_estimate_gas(map(), binary(), state_overrides :: map(), keyword()) ::
{:ok, binary()} | error()

@doc "Sends `eth_feeHistory`."
@callback eth_fee_history(
block_count :: binary(),
newest_block :: binary(),
reward_percentiles :: [number()],
keyword()
) :: {:ok, map()} | error()

@doc "Sends `eth_gasPrice`."
@callback eth_gas_price(keyword()) :: {:ok, binary()} | error()

@doc "Sends `eth_getBalance`."
@callback eth_get_balance(binary(), binary(), keyword()) :: {:ok, binary()} | error()

@doc "Sends `eth_getCode`."
@callback eth_get_code(binary(), binary(), keyword()) :: {:ok, binary()} | error()

@doc """
Sends `eth_getBlockByNumber`.

The result is `nil` if the block does not exist.
"""
@callback eth_get_block_by_number(binary() | non_neg_integer(), boolean(), keyword()) ::
{:ok, map()} | error()
{:ok, map() | nil} | error()

@callback eth_get_transaction_by_hash(binary(), keyword()) :: {:ok, map()} | error()
@doc """
Sends `eth_getTransactionByHash`.

The result is `nil` if the transaction is not found.
"""
@callback eth_get_transaction_by_hash(binary(), keyword()) :: {:ok, map() | nil} | error()

@doc "Sends `eth_getTransactionCount`."
@callback eth_get_transaction_count(binary(), binary(), keyword()) :: {:ok, binary()} | error()

@callback eth_get_transaction_receipt(binary(), keyword()) :: {:ok, map()} | error()
@doc """
Sends `eth_getTransactionReceipt`.

The result is `nil` if the transaction is not found or not mined yet.
"""
@callback eth_get_transaction_receipt(binary(), keyword()) :: {:ok, map() | nil} | error()

@doc "Sends `eth_maxPriorityFeePerGas`."
@callback eth_max_priority_fee_per_gas(keyword()) :: {:ok, binary()} | error()

@doc "Sends `eth_blobBaseFee`."
@callback eth_blob_base_fee(keyword()) :: {:ok, binary()} | error()

@doc "Sends `eth_getLogs`."
@callback eth_get_logs(map(), keyword()) :: {:ok, [binary()] | [map()]} | error()

@doc "Sends `eth_sendTransaction`."
@callback eth_send_transaction(map(), keyword()) :: {:ok, binary()} | error()

@doc "Sends `eth_sendRawTransaction`."
@callback eth_send_raw_transaction(binary(), keyword()) :: {:ok, binary()} | error()

# New callbacks are optional to keep custom RPC client adapters backwards compatible.
Expand Down
Loading
Loading