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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
- Unsigned EIP-155 legacy transactions decode as `%Legacy{}` instead of `%Signed{}`
- All returned addresses are EIP-55 checksummed, including `Ethers.Event` `address` and `Ethers.deployed_address/2`
- `Ethers.get_transaction_receipt/2` returns an `Ethers.Receipt` struct instead of the raw RPC map
- `Ethers.Transaction.from_rpc_map/1` and `Ethers.get_transaction/2` return `Ethers.Transaction.Unknown` for unregistered transaction types instead of `{:error, :unsupported_type}`
- `Ethers.Transaction.decode/1` returns `Ethers.Transaction.Unknown` for unregistered transaction types instead of `{:error, :unsupported_transaction_type}`

### Enhancements

Expand All @@ -28,6 +30,7 @@
- Add `Ethers.Receipt.decode_logs/2` to decode receipt logs with event filters
- Add `Ethers.Event.eth_transfer_log?/1` and `Ethers.Event.system_address/0` to identify [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) ETH transfer logs
- Document that `Transfer` event filters also match EIP-7708 ETH transfer logs
- Add `Ethers.Transaction.Unknown` for unregistered transaction types like OP-stack deposit transactions

### Bug Fixes

Expand Down
33 changes: 32 additions & 1 deletion guides/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,36 @@ adapters and custom `Ethers.Signer` implementations built on `to_rpc_map/1` (lik
values it cannot encode, including storage keys and blob versioned hashes that are not 32-byte
binaries.

#### Unregistered transaction types return `Ethers.Transaction.Unknown`

`Ethers.get_transaction/2` (also in `Ethers.batch/2`), `Ethers.Transaction.from_rpc_map/1` and
`Ethers.Transaction.decode/1` return an `Ethers.Transaction.Unknown` for a transaction type that is
not registered, like OP-stack deposit transactions (type `0x7e`). It keeps the transaction
undecoded: the JSON-RPC object in `rpc_map` (and its block metadata in `metadata`), or the bytes
after the type byte in `raw_payload`. `Ethers.Transaction.encode/1` and `transaction_hash/2` work
on one with `raw_payload` and raise `ArgumentError` on one with only `rpc_map`;
`to_rpc_map/1` raises for both.

`{:error, :unsupported_type}` is no longer returned: a `type` that is not a hex quantity now
returns `{:error, :invalid_type}`. `decode/1` no longer returns
`{:error, :unsupported_transaction_type}` for an unregistered type byte, only for a `0x00` type
byte (legacy transactions have no type byte).

```elixir
# Before (0.8.x)
{:error, :unsupported_type} = Ethers.get_transaction(deposit_tx_hash)

# After (1.0.0)
{:ok, %Ethers.Transaction.Unknown{type_id: 0x7E, rpc_map: rpc_map}} =
Ethers.get_transaction(deposit_tx_hash)

rpc_map["from"]
#=> "0xdeaddeaddeaddeaddeaddeaddeaddeaddead0001"

{:ok, %Ethers.Transaction.Unknown{type_id: 0x7E, raw_payload: raw_payload}} =
Ethers.Transaction.decode(raw_deposit_tx)
```

### Transaction Validation

#### Missing required fields return an error
Expand Down Expand Up @@ -143,7 +173,8 @@ with one of `:invalid_rlp`, `:unsupported_transaction_type`, `:transaction_decod
rescued exceptions must match on the tuple instead.

Decoding is also stricter: a first byte in `0x00..0x7f` that is not a registered transaction type
is rejected instead of being decoded as a legacy transaction, and access list addresses (20 bytes),
is no longer decoded as a legacy transaction (it returns an `Ethers.Transaction.Unknown`, see
above, or `:unsupported_transaction_type` for `0x00`), and access list addresses (20 bytes),
storage keys (32 bytes) and blob versioned hashes (32 bytes) of the wrong size are rejected.

```elixir
Expand Down
4 changes: 4 additions & 0 deletions lib/ethers.ex
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,10 @@ defmodule Ethers do
@doc """
Returns the native transaction (ETH) by transaction hash.

The transaction is decoded with `Ethers.Transaction.from_rpc_map/1`: a transaction of a type
that is not registered (for example an OP-stack deposit transaction, type `0x7e`) is returned as
an `Ethers.Transaction.Unknown` holding the RPC map in `rpc_map`.

## Parameters
- tx_hash: Transaction hash which the transaction is queried for.
- overrides:
Expand Down
169 changes: 121 additions & 48 deletions lib/ethers/transaction.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ defmodule Ethers.Transaction do
(type 4) transactions

Signed transactions of any type are wrapped in `Ethers.Transaction.Signed`.

Transactions of any other type (for example OP-stack deposit transactions, type `0x7e`) read
with `from_rpc_map/1` or `decode/1` are returned undecoded as `Ethers.Transaction.Unknown`.
"""

alias Ethers.Authorization
Expand All @@ -32,6 +35,7 @@ defmodule Ethers.Transaction do
alias Ethers.Transaction.Metadata
alias Ethers.Transaction.Protocol, as: TxProtocol
alias Ethers.Transaction.Signed
alias Ethers.Transaction.Unknown
alias Ethers.Utils

require Logger
Expand Down Expand Up @@ -69,7 +73,7 @@ defmodule Ethers.Transaction do
@typedoc """
EVM Transaction type
"""
@type t :: t_payload() | Signed.t()
@type t :: t_payload() | Signed.t() | Unknown.t()

@typedoc """
EVM Transaction payload type
Expand Down Expand Up @@ -243,13 +247,27 @@ defmodule Ethers.Transaction do
`decode/1` reads back as the unsigned transaction). EIP-4844 transactions are encoded without
a blob sidecar (see `Ethers.Transaction.Eip4844`).

An `Ethers.Transaction.Unknown` transaction is encoded as its type byte followed by its
`raw_payload`, the bytes it was decoded from. One without `raw_payload` (read with
`from_rpc_map/1`) raises `ArgumentError`.

## Parameters
- `transaction` - Transaction struct to encode

## Returns
- `binary` - RLP encoded transaction with appropriate type envelope
"""
@spec encode(t()) :: binary()
def encode(%Unknown{raw_payload: raw_payload} = transaction) when is_binary(raw_payload),
do: TxProtocol.type_envelope(transaction) <> raw_payload

def encode(%Unknown{} = transaction) do
Unknown.raise_unsupported(
transaction,
"#{inspect(Unknown)} without raw_payload cannot be encoded"
)
end

def encode(%mod{} = transaction) do
mode = if mod == Signed, do: :payload, else: :hash

Expand All @@ -269,6 +287,10 @@ defmodule Ethers.Transaction do
struct. EIP-4844 transactions are decoded from the transaction envelope only (without a blob
sidecar). Malformed input returns an error instead of raising.

A first byte in `0x01..0x7f` that is not a registered transaction type (for example an
OP-stack deposit transaction, type `0x7e`) returns an `Ethers.Transaction.Unknown` with the
rest of the bytes, undecoded and unvalidated, in `raw_payload`.

## Parameters
- `raw_transaction` - Raw transaction data as a binary or hex string starting with "0x"

Expand All @@ -277,8 +299,8 @@ defmodule Ethers.Transaction do
- `{:error, reason}` - The input is not a valid transaction, with `reason` one of:
- `:invalid_hex` - invalid hex string
- `:invalid_rlp` - invalid RLP, or trailing bytes after the transaction
- `:unsupported_transaction_type` - a first byte in `0x00..0x7f` that is not a
registered transaction type
- `:unsupported_transaction_type` - a first byte of `0x00` (legacy transactions have no
type byte)
- `:transaction_decode_failed` - fields of the wrong shape, kind or size
- `:invalid_address` - a `to` address that is not 20 bytes
- `:missing_to_address` - an EIP-7702 transaction without `to`
Expand All @@ -294,10 +316,18 @@ defmodule Ethers.Transaction do
end

def decode(raw_transaction_bin) when is_binary(raw_transaction_bin) do
with {:ok, module, rlp_binary} <- split_type_envelope(raw_transaction_bin),
{:ok, rlp_list} <- decode_rlp_list(rlp_binary),
{:ok, transaction, signature} <- module.from_rlp_list(rlp_list) do
maybe_decode_signature(transaction, signature)
case split_type_envelope(raw_transaction_bin) do
{:ok, Unknown, type_id, raw_payload} ->
{:ok, %Unknown{type_id: type_id, raw_payload: raw_payload}}

{:ok, module, rlp_binary} ->
with {:ok, rlp_list} <- decode_rlp_list(rlp_binary),
{:ok, transaction, signature} <- module.from_rlp_list(rlp_list) do
maybe_decode_signature(transaction, signature)
end

{:error, reason} ->
{:error, reason}
end
end

Expand All @@ -310,9 +340,12 @@ defmodule Ethers.Transaction do
do: {:ok, unquote(module), rest}
end)

# EIP-2718: a first byte in 0x00..0x7f is a transaction type, a legacy transaction is an RLP list
defp split_type_envelope(<<type, _rest::binary>>) when type <= 0x7F,
do: {:error, :unsupported_transaction_type}
# EIP-2718: a first byte in 0x00..0x7f is a transaction type, a legacy transaction is an RLP list.
# Type 0 is legacy, which has no type byte.
defp split_type_envelope(<<0, _rest::binary>>), do: {:error, :unsupported_transaction_type}

defp split_type_envelope(<<type, raw_payload::binary>>) when type <= 0x7F,
do: {:ok, Unknown, type, raw_payload}

defp split_type_envelope(legacy_transaction), do: {:ok, Legacy, legacy_transaction}

Expand Down Expand Up @@ -360,9 +393,23 @@ defmodule Ethers.Transaction do
## Returns Either
- `binary` - Transaction hash in binary format (when `format` is `:bin`)
- `String.t()` - Transaction hash in hex format prefixed with "0x" (when `format` is `:hex`)

The hash of an `Ethers.Transaction.Unknown` transaction is the keccak hash of its encoding
(see `encode/1`). One without `raw_payload` (read with `from_rpc_map/1`) raises
`ArgumentError`, the hash reported by the node is in its `rpc_map`.
"""
@spec transaction_hash(t(), :bin | :hex) :: binary() | String.t()
def transaction_hash(transaction, format \\ :hex) do
def transaction_hash(transaction, format \\ :hex)

def transaction_hash(%Unknown{raw_payload: nil} = transaction, _format) do
Unknown.raise_unsupported(
transaction,
~s(#{inspect(Unknown)} without raw_payload cannot be hashed, ) <>
~s(the hash reported by the node is in rpc_map["hash"])
)
end

def transaction_hash(transaction, format) do
hash_bin =
transaction
|> encode()
Expand All @@ -379,48 +426,58 @@ defmodule Ethers.Transaction do

Handles different field naming conventions and transaction types.

A transaction of a type that is not registered (for example an OP-stack deposit transaction,
type `0x7e`) is returned as an `Ethers.Transaction.Unknown` holding the map, unchanged, in
`rpc_map` and its block metadata in `metadata`.

## Parameters
- `tx` - Map containing transaction data. Keys can be camelCase strings or atoms.
(e.g `:chainId`, `"gasPrice"`)

## Returns
- `{:ok, transaction}` - Converted transaction struct
- `{:error, :unsupported_type}` - If transaction type is not supported
- `{:error, :invalid_type}` - If the transaction type is not a hex quantity
- `{:error, reason}` - If transaction fields are missing or invalid (see `new/1`)
"""
@spec from_rpc_map(map()) :: {:ok, t()} | {:error, :unsupported_type | term()}
@spec from_rpc_map(map()) :: {:ok, t()} | {:error, term()}
def from_rpc_map(tx) do
with {:ok, type} <- decode_type(from_map_value(tx, :type)) do
# Convert from RPC-style field names to EVM field names.
new(%{
access_list: tx |> from_map_value(:accessList) |> from_rpc_access_list(),
authorization_list:
tx |> from_map_value(:authorizationList) |> from_rpc_authorization_list(),
blob_versioned_hashes:
tx |> from_map_value(:blobVersionedHashes) |> from_rpc_blob_versioned_hashes(),
block_hash: from_map_value(tx, :blockHash),
block_number: from_map_value_int(tx, :blockNumber),
chain_id: from_map_value_int(tx, :chainId),
input: from_map_value_bin(tx, :input) || from_map_value_bin(tx, :data) || "",
from: from_map_value(tx, :from),
gas: from_map_value_int(tx, :gas),
gas_price: from_map_value_int(tx, :gasPrice),
hash: from_map_value(tx, :hash),
max_fee_per_blob_gas: from_map_value_int(tx, :maxFeePerBlobGas),
max_fee_per_gas: from_map_value_int(tx, :maxFeePerGas),
max_priority_fee_per_gas: from_map_value_int(tx, :maxPriorityFeePerGas),
nonce: from_map_value_int(tx, :nonce),
signature_r: from_map_value_bin(tx, :r),
signature_s: from_map_value_bin(tx, :s),
signature_y_parity_or_v: from_map_value_int(tx, :yParity) || from_map_value_int(tx, :v),
to: from_map_value(tx, :to),
transaction_index: from_map_value_int(tx, :transactionIndex),
value: from_map_value_int(tx, :value),
type: type
})
case decode_type(from_map_value(tx, :type)) do
{:ok, Unknown, type_id} -> {:ok, Unknown.from_rpc_map(tx, type_id)}
{:ok, type} -> new(rpc_map_to_params(tx, type))
{:error, reason} -> {:error, reason}
end
end

# Converts from RPC-style field names to EVM field names
defp rpc_map_to_params(tx, type) do
%{
access_list: tx |> from_map_value(:accessList) |> from_rpc_access_list(),
authorization_list:
tx |> from_map_value(:authorizationList) |> from_rpc_authorization_list(),
blob_versioned_hashes:
tx |> from_map_value(:blobVersionedHashes) |> from_rpc_blob_versioned_hashes(),
block_hash: from_map_value(tx, :blockHash),
block_number: from_map_value_int(tx, :blockNumber),
chain_id: from_map_value_int(tx, :chainId),
input: from_map_value_bin(tx, :input) || from_map_value_bin(tx, :data) || "",
from: from_map_value(tx, :from),
gas: from_map_value_int(tx, :gas),
gas_price: from_map_value_int(tx, :gasPrice),
hash: from_map_value(tx, :hash),
max_fee_per_blob_gas: from_map_value_int(tx, :maxFeePerBlobGas),
max_fee_per_gas: from_map_value_int(tx, :maxFeePerGas),
max_priority_fee_per_gas: from_map_value_int(tx, :maxPriorityFeePerGas),
nonce: from_map_value_int(tx, :nonce),
signature_r: from_map_value_bin(tx, :r),
signature_s: from_map_value_bin(tx, :s),
signature_y_parity_or_v: from_map_value_int(tx, :yParity) || from_map_value_int(tx, :v),
to: from_map_value(tx, :to),
transaction_index: from_map_value_int(tx, :transactionIndex),
value: from_map_value_int(tx, :value),
type: type
}
end

@doc """
Converts a Transaction struct into a map suitable for JSON-RPC.

Expand All @@ -434,9 +491,18 @@ defmodule Ethers.Transaction do
## Returns
- map containing transaction parameters with RPC field names and "0x" prefixed hex values

Raises `ArgumentError` if a field holds a value that has no JSON-RPC representation.
Raises `ArgumentError` if a field holds a value that has no JSON-RPC representation, and for an
`Ethers.Transaction.Unknown` transaction (one read with `from_rpc_map/1` keeps the map in
`rpc_map`).
"""
@spec to_rpc_map(t()) :: map()
def to_rpc_map(%Unknown{} = transaction) do
Unknown.raise_unsupported(
transaction,
"#{inspect(Unknown)} cannot be converted to an RPC map"
)
end

def to_rpc_map(%Signed{payload: payload} = signed_transaction) do
payload
|> to_rpc_map()
Expand Down Expand Up @@ -598,16 +664,23 @@ defmodule Ethers.Transaction do

defp do_post_process(_key, {:error, reason}, _opts), do: {:error, reason}

defp decode_type("0x" <> _ = type), do: decode_type(Utils.hex_decode!(type))
defp decode_type(nil), do: {:ok, Legacy}

defp decode_type("0x" <> _ = type) do
case Utils.hex_to_integer(type) do
{:ok, type_id} -> type_module(type_id)
{:error, :invalid_hex} -> {:error, :invalid_type}
end
end

defp decode_type(_type), do: {:error, :invalid_type}

Enum.each(@transaction_types, fn module ->
type_envelope = module.type_envelope()
defp decode_type(unquote(type_envelope)), do: {:ok, unquote(module)}
type_id = module.type_id()
defp type_module(unquote(type_id)), do: {:ok, unquote(module)}
end)

defp decode_type(<<0>>), do: {:ok, Legacy}
defp decode_type(nil), do: {:ok, Legacy}
defp decode_type(_type), do: {:error, :unsupported_type}
defp type_module(type_id), do: {:ok, Unknown, type_id}

defp from_map_value_bin(tx, key) do
case from_map_value(tx, key) do
Expand Down
Loading
Loading