From 1ad0781e2f81bf50862dfdd5061b9d7d72e5dde0 Mon Sep 17 00:00:00 2001 From: Alisina Bahadori Date: Sun, 15 Nov 2026 16:23:01 -0500 Subject: [PATCH 1/5] Return an Ethers.Receipt struct from get_transaction_receipt/2 `Ethers.get_transaction_receipt/2` returned the node's JSON untouched: a string-keyed map with hex quantities. It now returns an `Ethers.Receipt` struct decoded after the execution-apis `ReceiptInfo` schema: - quantities (including `type`, the EIP-2718 type id, also for types the library has no module for) are integers - `status` is `:success | :failure`, `nil` for pre-Byzantium receipts, which carry `root` instead - addresses are checksummed, hashes stay `0x` hex strings, `logs_bloom` is a binary and `logs` are kept as returned by the node - omitted members are `nil`, unknown members are ignored and the node's map is kept in `raw` for chain specific members (OP Stack L1 fees...) - a member not matching the schema returns `{:error, {:invalid_receipt_member, member}}` instead of raising The `:get_transaction_receipt` batch action now works and returns the same struct: it was not mapped to `eth_getTransactionReceipt`, so the node answered "Method not found". This is a breaking change for 1.0.0. Issue: #294 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012hqvX8DbbP3mgXy5hVEDc6 --- lib/ethers.ex | 33 ++- lib/ethers/receipt.ex | 216 +++++++++++++++ test/ethers/receipt_test.exs | 516 +++++++++++++++++++++++++++++++++++ test/ethers_test.exs | 22 +- 4 files changed, 773 insertions(+), 14 deletions(-) create mode 100644 lib/ethers/receipt.ex create mode 100644 test/ethers/receipt_test.exs diff --git a/lib/ethers.ex b/lib/ethers.ex index e0ebb0a..1223e68 100644 --- a/lib/ethers.ex +++ b/lib/ethers.ex @@ -69,6 +69,7 @@ defmodule Ethers do alias Ethers.EventFilter alias Ethers.ExecutionError alias Ethers.ForkConfig + alias Ethers.Receipt alias Ethers.StateOverride alias Ethers.Transaction alias Ethers.TxData @@ -103,6 +104,7 @@ defmodule Ethers do get_logs: :eth_get_logs, get_transaction_count: :eth_get_transaction_count, get_transaction: :eth_get_transaction_by_hash, + 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, @@ -248,16 +250,38 @@ defmodule Ethers do end @doc """ - Returns the receipt of a transaction by it's hash. + Returns the receipt of a transaction by its hash (`eth_getTransactionReceipt`), decoded to an + `Ethers.Receipt` struct. + + The logs of the receipt are kept as returned by the node, decode them with + `Ethers.Receipt.decode_logs/2`. The receipt as returned by the node, including chain + specific members, is available in the `raw` field. + + Also works with `Ethers.batch/2` as `{:get_transaction_receipt, tx_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. + + ## Returns + - `{:ok, receipt}` with an `Ethers.Receipt` struct. + - `{:error, :transaction_receipt_not_found}` if the node has no receipt for the + transaction (unknown or not yet included in a block). + - `{:error, {:invalid_receipt_member, member}}` if the node returned a member that does + not match the receipt schema (e.g. `{:invalid_receipt_member, "status"}`). + - `{:error, reason}` on RPC failures. + + ## Examples + + ```elixir + Ethers.get_transaction_receipt("0x9c4e...6e5d") + {:ok, %Ethers.Receipt{status: :success, gas_used: 45029, type: 2, ...}} + ``` """ @spec get_transaction_receipt(Types.t_hash(), Keyword.t()) :: - {:ok, map()} | {:error, term()} + {:ok, Receipt.t()} | {:error, term()} def get_transaction_receipt(tx_hash, opts \\ []) when is_binary(tx_hash) do {rpc_client, rpc_opts} = get_rpc_client(opts) @@ -268,7 +292,7 @@ defmodule Ethers do @doc """ Same as `Ethers.get_transaction_receipt/2` but raises on error. """ - @spec get_transaction_receipt!(Types.t_hash(), Keyword.t()) :: map() | no_return() + @spec get_transaction_receipt!(Types.t_hash(), Keyword.t()) :: Receipt.t() | no_return() def get_transaction_receipt!(tx_hash, opts \\ []) do case get_transaction_receipt(tx_hash, opts) do {:ok, receipt} -> receipt @@ -1473,6 +1497,9 @@ defmodule Ethers do defp post_process({:ok, nil}, _tx_hash, :get_transaction_receipt), do: {:error, :transaction_receipt_not_found} + defp post_process({:ok, receipt}, _tx_hash, :get_transaction_receipt), + do: Receipt.from_rpc_map(receipt) + defp post_process({:ok, resp}, _data, :fee_history) when is_map(resp) do {:ok, %{ diff --git a/lib/ethers/receipt.ex b/lib/ethers/receipt.ex new file mode 100644 index 0000000..594adeb --- /dev/null +++ b/lib/ethers/receipt.ex @@ -0,0 +1,216 @@ +defmodule Ethers.Receipt do + @moduledoc """ + Receipt of a transaction included in a block, as returned by + `Ethers.get_transaction_receipt/2` (the `eth_getTransactionReceipt` RPC method). + + The fields are the members of the `ReceiptInfo` schema of the + [Ethereum execution APIs](https://github.com/ethereum/execution-apis/blob/main/src/schemas/receipt.yaml), + named after the snake case of their RPC member names. See `t:t/0` for the fields and how + each of them is decoded. + + Decoding rules: + + - Quantities are decoded to integers, including `type` (the + [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction type id). + - `status` is decoded to `:success` or `:failure`. + - Addresses are checksummed. + - Hashes are kept as returned by the node: `0x` prefixed hex strings. + - `logs_bloom` is decoded to a binary. + - `logs` are kept as returned by the node, see [Logs](#module-logs). + - A member the node omits is `nil` (e.g. `status` of a pre-Byzantium receipt, or + `blob_gas_used` of a non-blob transaction). + - Members not defined by the schema are ignored. Chain specific members (e.g. the L1 fee + members of OP Stack chains) are available in `raw`, the receipt exactly as returned by the + node. + + `Ethers.get_transaction_receipt/2` returns `{:error, {:invalid_receipt_member, member}}` + when the node returns a member that does not match the schema (e.g. a `status` other than + `"0x0"` or `"0x1"`), with `member` the RPC member name (e.g. `"status"`). + + ## Logs + + A receipt holds the logs of every contract the transaction called, and decoding a log + requires the ABI of its event. The logs are therefore kept as returned by the node (maps + with string keys, the form `Ethers.Event.decode/2` and `Ethers.Event.find_and_decode/2` + accept). + + ## Example + + {:ok, receipt} = Ethers.get_transaction_receipt(tx_hash) + + %Ethers.Receipt{ + block_hash: "0x5f3a...3b20", + block_number: 21563820, + contract_address: nil, + cumulative_gas_used: 7014293, + effective_gas_price: 7349186131, + from: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", + gas_used: 45029, + logs: [%{"address" => "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", ...}], + logs_bloom: <<0, 0, 0, ...>>, + status: :success, + to: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", + transaction_hash: "0x9c4e...6e5d", + transaction_index: 94, + type: 2, + raw: %{"blockHash" => "0x5f3a...3b20", "status" => "0x1", ...}, + ... + } + """ + + alias Ethers.Types + alias Ethers.Utils + + defstruct [ + :blob_gas_price, + :blob_gas_used, + :block_hash, + :block_number, + :contract_address, + :cumulative_gas_used, + :effective_gas_price, + :from, + :gas_used, + :logs, + :logs_bloom, + :root, + :status, + :to, + :transaction_hash, + :transaction_index, + :type, + raw: %{} + ] + + @typedoc """ + A transaction receipt with the following fields (`nil` when the node omits the member): + + - `transaction_hash` - hash of the transaction. + - `transaction_index` - index of the transaction in its block. + - `block_hash` - hash of the block including the transaction. + - `block_number` - number of the block including the transaction. + - `from` - checksummed address of the sender. + - `to` - checksummed address of the receiver, `nil` for a contract creation transaction. + - `contract_address` - checksummed address of the contract created by the transaction, + `nil` if it is not a contract creation transaction. + - `type` - the [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) type id of the + transaction as an integer (e.g. `2` for EIP-1559), including types the library has no + transaction module for (e.g. `126` for OP Stack deposit transactions). Compare it with + the `type_id/0` of a transaction module, e.g. `Ethers.Transaction.Eip1559.type_id()`. + - `status` - `:success` or `:failure`. `nil` for transactions included before the + Byzantium upgrade, whose receipts hold `root` instead. + - `root` - the post-transaction state root, only present in receipts of transactions + included before the Byzantium upgrade. + - `gas_used` - gas used by this transaction alone. + - `cumulative_gas_used` - sum of the gas used by this transaction and all preceding + transactions in the same block. + - `effective_gas_price` - the actual price per gas paid by the sender in wei. + - `blob_gas_used` - blob gas used by the transaction, only present for blob + ([EIP-4844](https://eips.ethereum.org/EIPS/eip-4844)) transactions. + - `blob_gas_price` - the actual price per blob gas paid by the sender in wei, only present + for blob transactions. + - `logs` - the logs emitted by the transaction, as returned by the node. + - `logs_bloom` - the 256 byte bloom filter of the logs, as a binary. + - `raw` - the receipt exactly as returned by the node, including chain specific members. + """ + @type t :: %__MODULE__{ + blob_gas_price: non_neg_integer() | nil, + blob_gas_used: non_neg_integer() | nil, + block_hash: Types.t_hash() | nil, + block_number: non_neg_integer() | nil, + contract_address: Types.t_address() | nil, + cumulative_gas_used: non_neg_integer() | nil, + effective_gas_price: non_neg_integer() | nil, + from: Types.t_address() | nil, + gas_used: non_neg_integer() | nil, + logs: [map()] | nil, + logs_bloom: binary() | nil, + raw: map(), + root: Types.t_hash() | nil, + status: :success | :failure | nil, + to: Types.t_address() | nil, + transaction_hash: Types.t_hash() | nil, + transaction_index: non_neg_integer() | nil, + type: non_neg_integer() | nil + } + + # Struct field => {RPC member, decoder} + @members [ + transaction_hash: {"transactionHash", :hash}, + transaction_index: {"transactionIndex", :quantity}, + block_hash: {"blockHash", :hash}, + block_number: {"blockNumber", :quantity}, + from: {"from", :address}, + to: {"to", :address}, + contract_address: {"contractAddress", :address}, + type: {"type", :quantity}, + status: {"status", :status}, + root: {"root", :hash}, + gas_used: {"gasUsed", :quantity}, + cumulative_gas_used: {"cumulativeGasUsed", :quantity}, + effective_gas_price: {"effectiveGasPrice", :quantity}, + blob_gas_used: {"blobGasUsed", :quantity}, + blob_gas_price: {"blobGasPrice", :quantity}, + logs: {"logs", :logs}, + logs_bloom: {"logsBloom", :bytes} + ] + + @doc false + @spec from_rpc_map(term()) :: + {:ok, t()} | {:error, :invalid_receipt | {:invalid_receipt_member, String.t()}} + def from_rpc_map(receipt) when is_map(receipt) do + Enum.reduce_while(@members, {:ok, %__MODULE__{raw: receipt}}, fn + {field, {member, kind}}, {:ok, decoded} -> + case receipt |> Map.get(member) |> decode_member(kind) do + {:ok, value} -> {:cont, {:ok, Map.put(decoded, field, value)}} + :error -> {:halt, {:error, {:invalid_receipt_member, member}}} + end + end) + end + + def from_rpc_map(_receipt), do: {:error, :invalid_receipt} + + defp decode_member(nil, _kind), do: {:ok, nil} + + defp decode_member("0x" <> hex = hash, :hash) when byte_size(hex) == 64 do + case Utils.hex_decode(hex) do + {:ok, _hash_bin} -> {:ok, hash} + :error -> :error + end + end + + defp decode_member("0x" <> _ = quantity, :quantity) do + case Utils.hex_to_integer(quantity) do + {:ok, integer} -> {:ok, integer} + {:error, _reason} -> :error + end + end + + defp decode_member(address, :address) do + case Utils.decode_address(address) do + {:ok, address_bin} -> {:ok, Utils.encode_address!(address_bin)} + _invalid -> :error + end + end + + defp decode_member(status, :status) do + case decode_member(status, :quantity) do + {:ok, 1} -> {:ok, :success} + {:ok, 0} -> {:ok, :failure} + _invalid -> :error + end + end + + defp decode_member("0x" <> hex, :bytes) do + case Utils.hex_decode(hex) do + {:ok, bytes} -> {:ok, bytes} + :error -> :error + end + end + + defp decode_member(logs, :logs) when is_list(logs) do + if Enum.all?(logs, &is_map/1), do: {:ok, logs}, else: :error + end + + defp decode_member(_value, _kind), do: :error +end diff --git a/test/ethers/receipt_test.exs b/test/ethers/receipt_test.exs new file mode 100644 index 0000000..78a2d73 --- /dev/null +++ b/test/ethers/receipt_test.exs @@ -0,0 +1,516 @@ +defmodule Ethers.Contract.Test.ReceiptHelloWorldContract do + @moduledoc false + use Ethers.Contract, abi_file: "tmp/hello_world_abi.json" +end + +defmodule Ethers.ReceiptTest.Fixtures do + @moduledoc false + # Receipts in the form nodes return them (execution-apis `ReceiptInfo` schema) + + @block_hash "0xffeca860ae9ca8f0db4dd0601f9a323d715ab7bf46a326cfc1ffc84c9c07b76c" + @empty_logs_bloom "0x" <> String.duplicate("0", 512) + + @vitalik "0xd8da6bf26964af9d7eed9e03e53415d37aa96045" + @receiver "0x70997970c51812dc3a010c7d01b50e0d17dc79c8" + @usdc "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" + @weth "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" + @bayc "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d" + + @transfer_topic "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" + @approval_topic "0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925" + + def block_hash, do: @block_hash + + def eip1559_transfer do + %{ + "blockHash" => @block_hash, + "blockNumber" => "0x14909ac", + "contractAddress" => nil, + "cumulativeGasUsed" => "0x6b0795", + "effectiveGasPrice" => "0x1b60bae53", + "from" => @vitalik, + "gasUsed" => "0x5208", + "logs" => [], + "logsBloom" => @empty_logs_bloom, + "status" => "0x1", + "to" => @receiver, + "transactionHash" => "0xcedec15c0525b48d07e8d008771747bdcf880ff179606a27d884542344a4d46b", + "transactionIndex" => "0x5e", + "type" => "0x2" + } + end + + def contract_creation do + %{ + "blockHash" => @block_hash, + "blockNumber" => "0x1", + "contractAddress" => "0x5fbdb2315678afecb367f032d93f642f64180aa3", + "cumulativeGasUsed" => "0x108b47", + "effectiveGasPrice" => "0x3b9aca00", + "from" => "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", + "gasUsed" => "0x108b47", + "logs" => [], + "logsBloom" => @empty_logs_bloom, + "status" => "0x1", + "to" => nil, + "transactionHash" => "0xc2f01a029629919baa5c0b7a6a3a7288bcfc5af60a3f95cb4d82afc3647f99df", + "transactionIndex" => "0x0", + "type" => "0x2" + } + end + + def failed_transaction do + %{ + "blockHash" => @block_hash, + "blockNumber" => "0x14909ac", + "contractAddress" => nil, + "cumulativeGasUsed" => "0x6b0795", + "effectiveGasPrice" => "0x1b60bae53", + "from" => @vitalik, + "gasUsed" => "0xcb99", + "logs" => [], + "logsBloom" => @empty_logs_bloom, + "status" => "0x0", + "to" => @usdc, + "transactionHash" => "0x2d00ed0b403a747d1e293e4da85f095aa074499f11d16c7dd0a075d93c60150e", + "transactionIndex" => "0xc", + "type" => "0x2" + } + end + + def blob_transaction do + %{ + "blobGasPrice" => "0x1", + "blobGasUsed" => "0x20000", + "blockHash" => @block_hash, + "blockNumber" => "0x14909ac", + "contractAddress" => nil, + "cumulativeGasUsed" => "0x35b6d3", + "effectiveGasPrice" => "0x3b9aca00", + "from" => "0x5050f69a9786f081509234f1a7f4684b5e5b76c9", + "gasUsed" => "0x5208", + "logs" => [], + "logsBloom" => @empty_logs_bloom, + "status" => "0x1", + "to" => "0xff00000000000000000000000000000000008453", + "transactionHash" => "0x89c39187fae2bfd1862e8bbed55aa5f4b73e0e615264c815faa565991b0a577c", + "transactionIndex" => "0x2", + "type" => "0x3" + } + end + + def pre_byzantium do + %{ + "blockHash" => @block_hash, + "blockNumber" => "0xb443", + "contractAddress" => nil, + "cumulativeGasUsed" => "0x5208", + "effectiveGasPrice" => "0x2d79883d2000", + "from" => @vitalik, + "gasUsed" => "0x5208", + "logs" => [], + "logsBloom" => @empty_logs_bloom, + "root" => "0x49fbd619f601e32aeeefa0b02d9706c669a437a0ada61baf9c21ac5c8d320517", + "to" => @receiver, + "transactionHash" => "0x1f33f7057724f269ae65284509615ad86fa1994af92d2abce0b82c82a2b7b46b", + "transactionIndex" => "0x0", + "type" => "0x0" + } + end + + # Receipt of an OP Stack chain, with the chain specific L1 fee members + def op_stack_transaction do + Map.merge(eip1559_transfer(), %{ + "l1BaseFeeScalar" => "0x8dd", + "l1BlobBaseFee" => "0x1", + "l1BlobBaseFeeScalar" => "0x101c12", + "l1Fee" => "0x1c5ee8a2b4", + "l1GasPrice" => "0x2540be400", + "l1GasUsed" => "0x640" + }) + end + + # OP Stack deposit transaction (type 0x7e), unknown to the library + def op_stack_deposit do + Map.merge(eip1559_transfer(), %{ + "depositNonce" => "0x9a2b1", + "depositReceiptVersion" => "0x1", + "effectiveGasPrice" => "0x0", + "type" => "0x7e" + }) + end + + def token_transfers do + tx_hash = "0x8a15ef80cd16fdde1c4d8283d81c02902486fd3ae01f48a9da6da88995809d1a" + + logs = + [ + # ERC-20 Approval(owner, spender, 1 USDC) + {@usdc, [@approval_topic, address_topic(@vitalik), address_topic(@receiver)], + word(1_000_000)}, + # ERC-20 Transfer(from, to, 1 USDC) + {@usdc, [@transfer_topic, address_topic(@vitalik), address_topic(@receiver)], + word(1_000_000)}, + # ERC-721 Transfer(from, to, tokenId): same signature, the token id is indexed + {@bayc, [@transfer_topic, address_topic(@vitalik), address_topic(@receiver), word(7382)], + "0x"}, + # An event unknown to the ERC-20 and ERC-721 ABIs + {@weth, ["0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c"], word(10)}, + # ERC-20 Transfer of another token + {@weth, [@transfer_topic, address_topic(@receiver), address_topic(@vitalik)], + word(2_000)}, + # ERC-20 Transfer signature and topics but data that does not decode as a uint256 + {@weth, [@transfer_topic, address_topic(@receiver), address_topic(@vitalik)], "0x01"} + ] + |> Enum.with_index() + |> Enum.map(fn {{address, topics, data}, index} -> + %{ + "address" => address, + "blockHash" => @block_hash, + "blockNumber" => "0x14909ac", + "data" => data, + "logIndex" => Ethers.Utils.integer_to_hex(16 + index), + "removed" => false, + "topics" => topics, + "transactionHash" => tx_hash, + "transactionIndex" => "0x5e" + } + end) + + Map.merge(eip1559_transfer(), %{ + "gasUsed" => "0x15586", + "logs" => logs, + "logsBloom" => "0x" <> String.duplicate("00200000", 64), + "to" => @usdc, + "transactionHash" => tx_hash + }) + end + + defp address_topic("0x" <> address), do: "0x" <> String.duplicate("0", 24) <> address + + defp word(integer) do + hex = Integer.to_string(integer, 16) |> String.downcase() + "0x" <> String.pad_leading(hex, 64, "0") + end +end + +defmodule Ethers.ReceiptTest.ReceiptRPC do + @moduledoc false + # Returns the response given in the `:response` rpc option + + def eth_get_transaction_receipt(tx_hash, opts) do + if pid = opts[:send_params_to_pid] do + send(pid, {:eth_get_transaction_receipt, tx_hash}) + end + + Keyword.fetch!(opts, :response) + end + + def batch_request(requests, opts) do + if pid = opts[:send_params_to_pid] do + send(pid, {:batch_request, requests}) + end + + {:ok, + Enum.map(requests, fn {:eth_get_transaction_receipt, [_tx_hash]} -> + Keyword.fetch!(opts, :response) + end)} + end +end + +defmodule Ethers.ReceiptTest do + use ExUnit.Case + + import Ethers.TestHelpers + + alias Ethers.Contract.Test.ReceiptHelloWorldContract + alias Ethers.Contract.Test.RevertContract + alias Ethers.ExecutionError + alias Ethers.Receipt + alias Ethers.ReceiptTest.Fixtures + alias Ethers.ReceiptTest.ReceiptRPC + alias Ethers.Utils + + @from "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" + # Not a funded test account: other tests assert the exact balance of those + @value_receiver "0x9965507D1a55bcC2695C58ba16FB37d819B0A4da" + @from_private_key "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" + + @vitalik "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" + @receiver "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" + @usdc "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" + @missing_tx_hash "0x5194596d703a53f65dcb1d7df60fcfa1f7d904ad3145887677a6ab68a425d8d3" + + defp get_receipt(response) do + Ethers.get_transaction_receipt(@missing_tx_hash, + rpc_client: ReceiptRPC, + rpc_opts: [response: response] + ) + end + + defp receipt!(rpc_receipt) do + {:ok, receipt} = get_receipt({:ok, rpc_receipt}) + receipt + end + + describe "get_transaction_receipt/2 decoding" do + test "decodes a successful EIP-1559 transfer" do + rpc_receipt = Fixtures.eip1559_transfer() + + assert {:ok, receipt} = get_receipt({:ok, rpc_receipt}) + + assert receipt == %Receipt{ + transaction_hash: + "0xcedec15c0525b48d07e8d008771747bdcf880ff179606a27d884542344a4d46b", + transaction_index: 94, + block_hash: Fixtures.block_hash(), + block_number: 21_563_820, + from: @vitalik, + to: @receiver, + contract_address: nil, + type: 2, + status: :success, + root: nil, + gas_used: 21_000, + cumulative_gas_used: 7_014_293, + effective_gas_price: 7_349_186_131, + blob_gas_used: nil, + blob_gas_price: nil, + logs: [], + logs_bloom: :binary.copy(<<0>>, 256), + raw: rpc_receipt + } + end + + test "decodes a contract creation" do + assert %Receipt{ + to: nil, + contract_address: "0x5FbDB2315678afecb367f032d93F642f64180aa3", + from: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", + status: :success, + gas_used: 1_084_231 + } = receipt!(Fixtures.contract_creation()) + end + + test "decodes a failed transaction" do + assert %Receipt{status: :failure, gas_used: 52_121, to: @usdc, root: nil} = + receipt!(Fixtures.failed_transaction()) + end + + test "decodes a blob transaction" do + assert %Receipt{ + type: 3, + blob_gas_used: 131_072, + blob_gas_price: 1, + effective_gas_price: 1_000_000_000, + to: "0xFf00000000000000000000000000000000008453", + from: "0x5050F69a9786F081509234F1a7F4684b5E5b76C9" + } = receipt!(Fixtures.blob_transaction()) + end + + test "decodes a pre-Byzantium receipt with root instead of status" do + assert %Receipt{ + status: nil, + root: "0x49fbd619f601e32aeeefa0b02d9706c669a437a0ada61baf9c21ac5c8d320517", + type: 0, + block_number: 46_147 + } = receipt!(Fixtures.pre_byzantium()) + end + + test "keeps chain specific members in raw" do + rpc_receipt = Fixtures.op_stack_transaction() + receipt = receipt!(rpc_receipt) + + assert receipt.raw == rpc_receipt + assert receipt.raw["l1Fee"] == "0x1c5ee8a2b4" + assert %{receipt | raw: nil} == %{receipt!(Fixtures.eip1559_transfer()) | raw: nil} + end + + test "decodes transaction types unknown to the library to their type id" do + assert %Receipt{type: 126, effective_gas_price: 0} = receipt!(Fixtures.op_stack_deposit()) + end + + test "keeps logs as returned by the node" do + rpc_receipt = Fixtures.token_transfers() + + assert %Receipt{logs: logs, logs_bloom: logs_bloom} = receipt!(rpc_receipt) + assert logs == rpc_receipt["logs"] + assert logs_bloom == :binary.copy(<<0, 32, 0, 0>>, 64) + end + + test "decodes members omitted by the node to nil" do + rpc_receipt = Map.take(Fixtures.eip1559_transfer(), ["transactionHash"]) + + assert receipt!(rpc_receipt) == %Receipt{ + transaction_hash: rpc_receipt["transactionHash"], + raw: rpc_receipt + } + end + + test "returns an error for members not matching the schema" do + for {member, value} <- [ + {"status", "0x2"}, + {"status", "0x"}, + {"status", true}, + {"gasUsed", "5208"}, + {"gasUsed", 21_000}, + {"gasUsed", "0xzz"}, + {"gasUsed", "0x-1"}, + {"blockNumber", "0x"}, + {"type", "2"}, + {"from", "0x1234"}, + {"to", "0x" <> String.duplicate("z", 40)}, + {"contractAddress", String.duplicate("a", 40)}, + {"transactionHash", "0x1234"}, + {"blockHash", "0x" <> String.duplicate("z", 64)}, + {"root", 1}, + {"logsBloom", "0xzz"}, + {"logs", %{}}, + {"logs", ["0x1234"]} + ] do + rpc_receipt = Map.put(Fixtures.eip1559_transfer(), member, value) + + assert {:error, {:invalid_receipt_member, ^member}} = get_receipt({:ok, rpc_receipt}), + "expected #{inspect(value)} to be rejected for #{member}" + end + end + + test "returns an error for a receipt that is not an object" do + assert {:error, :invalid_receipt} = get_receipt({:ok, "0x1234"}) + end + + test "returns not found for a null receipt" do + assert {:error, :transaction_receipt_not_found} = get_receipt({:ok, nil}) + end + + test "returns RPC errors as is" do + error = %{"code" => -32_000, "message" => "boom"} + + assert {:error, ^error} = get_receipt({:error, error}) + end + + test "bang version raises on malformed receipts" do + rpc_receipt = Map.put(Fixtures.eip1559_transfer(), "status", "0x2") + + assert_raise ExecutionError, ~r/invalid_receipt_member/, fn -> + Ethers.get_transaction_receipt!(@missing_tx_hash, + rpc_client: ReceiptRPC, + rpc_opts: [response: {:ok, rpc_receipt}] + ) + end + end + + test "batch decodes :get_transaction_receipt results" do + rpc_receipt = Fixtures.eip1559_transfer() + + opts = [ + rpc_client: ReceiptRPC, + rpc_opts: [response: {:ok, rpc_receipt}, send_params_to_pid: self()] + ] + + assert {:ok, [{:ok, %Receipt{type: 2, status: :success, raw: ^rpc_receipt}}]} = + Ethers.batch([{:get_transaction_receipt, @missing_tx_hash}], opts) + + assert_received {:batch_request, [{:eth_get_transaction_receipt, [@missing_tx_hash]}]} + + opts = [rpc_client: ReceiptRPC, rpc_opts: [response: {:ok, nil}]] + + assert {:ok, [{:error, :transaction_receipt_not_found}]} = + Ethers.batch([{:get_transaction_receipt, @missing_tx_hash}], opts) + end + end + + describe "get_transaction_receipt/2 with a node" do + test "returns the receipt of a transfer" do + tx_hash = + Ethers.send_transaction!(%{value: 1000}, + from: @from, + to: @value_receiver, + signer: Ethers.Signer.Local, + signer_opts: [private_key: @from_private_key] + ) + + wait_for_transaction!(tx_hash) + + to = Utils.to_checksum_address(@value_receiver) + + assert {:ok, receipt} = Ethers.get_transaction_receipt(tx_hash) + + assert %Receipt{ + transaction_hash: ^tx_hash, + from: @from, + to: ^to, + contract_address: nil, + type: 2, + status: :success, + gas_used: 21_000, + logs: [], + raw: %{"transactionHash" => ^tx_hash} + } = receipt + + assert receipt.cumulative_gas_used >= receipt.gas_used + assert receipt.effective_gas_price > 0 + assert byte_size(receipt.logs_bloom) == 256 + + %Ethers.Transaction.Signed{metadata: metadata} = Ethers.get_transaction!(tx_hash) + assert metadata.block_hash == receipt.block_hash + assert metadata.block_number == receipt.block_number + assert metadata.transaction_index == receipt.transaction_index + end + + test "returns the contract address of a deployment" do + {:ok, tx_hash} = Ethers.deploy(ReceiptHelloWorldContract, from: @from) + wait_for_transaction!(tx_hash) + + assert {:ok, address} = Ethers.deployed_address(tx_hash) + + assert %Receipt{to: nil, status: :success, contract_address: contract_address} = + Ethers.get_transaction_receipt!(tx_hash) + + assert contract_address == Utils.to_checksum_address(address) + + assert ReceiptHelloWorldContract.say_hello() |> Ethers.call!(to: contract_address) == + "Hello World!" + end + + test "returns failure status for a reverted transaction" do + address = deploy(RevertContract, from: @from) + + tx_hash = + RevertContract.reverting() + |> Ethers.send_transaction!(from: @from, to: address, gas: 100_000) + + wait_for_transaction!(tx_hash) + + assert %Receipt{status: :failure, to: to} = Ethers.get_transaction_receipt!(tx_hash) + assert to == Utils.to_checksum_address(address) + end + + test "batch returns receipts" do + tx_hash = + Ethers.send_transaction!(%{value: 1000}, + from: @from, + to: @value_receiver, + signer: Ethers.Signer.Local, + signer_opts: [private_key: @from_private_key] + ) + + wait_for_transaction!(tx_hash) + + assert {:ok, + [ + {:ok, %Receipt{transaction_hash: ^tx_hash, status: :success}}, + {:error, :transaction_receipt_not_found} + ]} = + Ethers.batch([ + {:get_transaction_receipt, tx_hash}, + {:get_transaction_receipt, @missing_tx_hash} + ]) + end + + test "returns not found for an unknown transaction" do + assert {:error, :transaction_receipt_not_found} = + Ethers.get_transaction_receipt(@missing_tx_hash) + end + end +end diff --git a/test/ethers_test.exs b/test/ethers_test.exs index 564422b..8b6c04b 100644 --- a/test/ethers_test.exs +++ b/test/ethers_test.exs @@ -279,13 +279,15 @@ defmodule EthersTest do wait_for_transaction!(tx_hash) - downcased_to_addr = String.downcase(@to) + from = Utils.to_checksum_address(@from) + to = Utils.to_checksum_address(@to) assert {:ok, - %{ - "transactionHash" => ^tx_hash, - "from" => @from, - "to" => ^downcased_to_addr + %Ethers.Receipt{ + transaction_hash: ^tx_hash, + from: ^from, + to: ^to, + status: :success }} = Ethers.get_transaction_receipt(tx_hash) end @@ -304,9 +306,9 @@ defmodule EthersTest do wait_for_transaction!(tx_hash) receipt = Ethers.get_transaction_receipt!(tx_hash) - assert receipt["transactionHash"] == tx_hash - assert receipt["from"] == @from - assert receipt["to"] == String.downcase(@to) + assert receipt.transaction_hash == tx_hash + assert receipt.from == Utils.to_checksum_address(@from) + assert receipt.to == Utils.to_checksum_address(@to) end test "bang version raises on error" do @@ -794,10 +796,8 @@ defmodule EthersTest do wait_for_transaction!(tx_hash) - type_id = Ethers.Utils.integer_to_hex(type.type_id()) - assert %Ethers.Transaction.Signed{payload: %^type{}} = Ethers.get_transaction!(tx_hash) - assert Ethers.get_transaction_receipt!(tx_hash)["type"] == type_id + assert Ethers.get_transaction_receipt!(tx_hash).type == type.type_id() end end end From b4ed4d23ecdab2a2e2676f11a4f4d530d22bfc28 Mon Sep 17 00:00:00 2001 From: Alisina Bahadori Date: Sun, 15 Nov 2026 16:24:07 -0500 Subject: [PATCH 2/5] Add Ethers.Receipt.decode_logs/2 A receipt holds the logs of every contract the transaction called, so its logs are kept as returned by the node. `decode_logs/2` decodes the ones matching an event filter, a combined event filter or a contract's EventFilters module into `%Ethers.Event{}` structs, in emission order. A log matches like with `eth_getLogs` (topic_0, indexed argument values with `nil` as a wildcard, the filter's default address compared case insensitively) plus two checks receipts need: the topic count must equal 1 + the number of indexed arguments, so ERC-20 and ERC-721 `Transfer` logs are not decoded as each other, and logs whose data does not ABI decode as the event are skipped instead of raising. Logs matching none of the events are skipped. Also note in the typedoc that some nodes (anvil) return `blobGasPrice` for non-blob transactions. Issue: #294 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012hqvX8DbbP3mgXy5hVEDc6 --- lib/ethers/receipt.ex | 129 ++++++++++++++++++++++++- test/ethers/receipt_test.exs | 180 +++++++++++++++++++++++++++++++++++ 2 files changed, 305 insertions(+), 4 deletions(-) diff --git a/lib/ethers/receipt.ex b/lib/ethers/receipt.ex index 594adeb..4d4c309 100644 --- a/lib/ethers/receipt.ex +++ b/lib/ethers/receipt.ex @@ -32,7 +32,8 @@ defmodule Ethers.Receipt do A receipt holds the logs of every contract the transaction called, and decoding a log requires the ABI of its event. The logs are therefore kept as returned by the node (maps with string keys, the form `Ethers.Event.decode/2` and `Ethers.Event.find_and_decode/2` - accept). + accept). Use `decode_logs/2` to decode the logs matching an event filter, a combined event + filter or all events of a contract into `Ethers.Event` structs. ## Example @@ -56,11 +57,20 @@ defmodule Ethers.Receipt do raw: %{"blockHash" => "0x5f3a...3b20", "status" => "0x1", ...}, ... } + + Ethers.Receipt.decode_logs(receipt, Ethers.Contracts.ERC20.EventFilters) + #=> [%Ethers.Event{topics: ["Transfer(address,address,uint256)", ...], ...}] """ + alias Ethers.CombinedEventFilter + alias Ethers.ContractHelpers + alias Ethers.Event + alias Ethers.EventFilter alias Ethers.Types alias Ethers.Utils + import Ethers.Types, only: [is_module: 1] + defstruct [ :blob_gas_price, :blob_gas_used, @@ -107,9 +117,10 @@ defmodule Ethers.Receipt do - `effective_gas_price` - the actual price per gas paid by the sender in wei. - `blob_gas_used` - blob gas used by the transaction, only present for blob ([EIP-4844](https://eips.ethereum.org/EIPS/eip-4844)) transactions. - - `blob_gas_price` - the actual price per blob gas paid by the sender in wei, only present - for blob transactions. - - `logs` - the logs emitted by the transaction, as returned by the node. + - `blob_gas_price` - the actual price per blob gas paid by the sender in wei. Specified for + blob transactions only, but some nodes (e.g. anvil) return it for every transaction. + - `logs` - the logs emitted by the transaction, as returned by the node. See + `decode_logs/2`. - `logs_bloom` - the 256 byte bloom filter of the logs, as a binary. - `raw` - the receipt exactly as returned by the node, including chain specific members. """ @@ -170,6 +181,56 @@ defmodule Ethers.Receipt do def from_rpc_map(_receipt), do: {:error, :invalid_receipt} + @doc """ + Decodes the logs of the receipt matching the given filter into `Ethers.Event` structs, in + the order they were emitted. + + The filter can be one of: + + - A single event filter. (e.g. `MyContract.EventFilters.transfer(nil, nil)`) + - A combined event filter matching multiple events, created with + `Ethers.EventFilter.combine/1`. + - An EventFilters module of a contract (e.g. `MyContract.EventFilters`) to match all + events of that contract. + + A log matches an event of the filter when: + + - its first topic is the event signature hash, + - its other topics match the indexed argument values of the filter (`nil` matches any + value) and their count matches the number of indexed arguments of the event, + - it was emitted by the default address of the filter (if it has one), and + - its data decodes as the non-indexed arguments of the event. + + Apart from the exact topic count and the data check, these are the rules `Ethers.get_logs/2` + filters logs with. The two extra checks matter for receipts, which hold the logs of every + contract the transaction called: events with the same signature can differ in which + arguments are indexed (e.g. the ERC-20 and ERC-721 `Transfer` events), and any contract can + emit a log with an event's signature but malformed data. Such logs are skipped instead of + being decoded as the wrong event or raising, like all logs matching none of the events of + the filter. + + ## Examples + + {:ok, receipt} = Ethers.get_transaction_receipt(tx_hash) + + # All events of a contract + Ethers.Receipt.decode_logs(receipt, Ethers.Contracts.ERC20.EventFilters) + #=> [%Ethers.Event{topics: ["Transfer(address,address,uint256)", from, to], ...}] + + # Only transfers to `to` + Ethers.Receipt.decode_logs(receipt, Ethers.Contracts.ERC20.EventFilters.transfer(nil, to)) + #=> [%Ethers.Event{data: [amount], ...}] + """ + @spec decode_logs(t(), EventFilter.t() | CombinedEventFilter.t() | module()) :: [Event.t()] + def decode_logs(%__MODULE__{} = receipt, events_module) when is_module(events_module), + do: decode_logs(receipt, CombinedEventFilter.all!(events_module)) + + def decode_logs(%__MODULE__{logs: logs}, filter) do + {address, events} = log_matchers(filter) + + Enum.flat_map(logs || [], &decode_log(&1, address, events)) + end + defp decode_member(nil, _kind), do: {:ok, nil} defp decode_member("0x" <> hex = hash, :hash) when byte_size(hex) == 64 do @@ -213,4 +274,64 @@ defmodule Ethers.Receipt do end defp decode_member(_value, _kind), do: :error + + # Returns the default address of the filter and its events as a map of lowercase topic_0 + # to the event selector and the filter of each indexed argument (nil matches any value) + defp log_matchers(%EventFilter{topics: [topic_0 | sub_topics], selector: selector} = filter), + do: {filter.default_address, %{String.downcase(topic_0) => {selector, sub_topics}}} + + defp log_matchers(%CombinedEventFilter{selectors: selectors} = filter) do + events = + Map.new(selectors, fn {topic_0, selector} -> + wildcards = selector |> ContractHelpers.event_indexed_types() |> Enum.map(fn _ -> nil end) + + {topic_0, {selector, wildcards}} + end) + + {filter.default_address, events} + end + + defp decode_log(%{"topics" => [topic_0 | sub_topics]} = log, address, events) + when is_binary(topic_0) do + with true <- address_matches?(log, address), + {:ok, {selector, sub_topic_filters}} <- Map.fetch(events, String.downcase(topic_0)), + true <- sub_topics_match?(sub_topics, sub_topic_filters), + {:ok, event} <- decode_event(log, selector) do + [event] + else + _no_match -> [] + end + end + + defp decode_log(_log, _address, _events), do: [] + + defp address_matches?(_log, nil), do: true + + defp address_matches?(%{"address" => log_address}, address) when is_binary(log_address), + do: String.downcase(log_address) == String.downcase(address) + + defp address_matches?(_log, _address), do: false + + # Unlike eth_getLogs, the topic count must be exact: events with the same signature but + # different indexed arguments (e.g. ERC-20 and ERC-721 Transfer) differ in their topic count + defp sub_topics_match?(sub_topics, filters) when length(sub_topics) == length(filters) do + sub_topics + |> Enum.zip(filters) + |> Enum.all?(fn + {_topic, nil} -> true + {topic, filter} when is_binary(topic) -> String.downcase(topic) == String.downcase(filter) + _mismatch -> false + end) + end + + defp sub_topics_match?(_sub_topics, _filters), do: false + + # Any contract can emit a log with the signature and topic count of an event but data that + # does not ABI decode as its arguments, on which the decoder raises (MatchError on short + # data, ArgumentError on invalid hex). Such a log is not an instance of the event. + defp decode_event(log, selector) do + {:ok, Event.decode(log, selector)} + rescue + _error in [ArgumentError, MatchError] -> :error + end end diff --git a/test/ethers/receipt_test.exs b/test/ethers/receipt_test.exs index 78a2d73..e66c210 100644 --- a/test/ethers/receipt_test.exs +++ b/test/ethers/receipt_test.exs @@ -1,8 +1,18 @@ +defmodule Ethers.Contract.Test.ReceiptCounterContract do + @moduledoc false + use Ethers.Contract, abi_file: "tmp/counter_abi.json" +end + defmodule Ethers.Contract.Test.ReceiptHelloWorldContract do @moduledoc false use Ethers.Contract, abi_file: "tmp/hello_world_abi.json" end +defmodule Ethers.Contract.Test.ReceiptUsdcContract do + @moduledoc false + use Ethers.Contract, abi: :erc20, default_address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" +end + defmodule Ethers.ReceiptTest.Fixtures do @moduledoc false # Receipts in the form nodes return them (execution-apis `ReceiptInfo` schema) @@ -223,8 +233,14 @@ defmodule Ethers.ReceiptTest do import Ethers.TestHelpers + alias Ethers.Contract.Test.ReceiptCounterContract alias Ethers.Contract.Test.ReceiptHelloWorldContract + alias Ethers.Contract.Test.ReceiptUsdcContract alias Ethers.Contract.Test.RevertContract + alias Ethers.Contracts.ERC20 + alias Ethers.Contracts.ERC721 + alias Ethers.Event + alias Ethers.EventFilter alias Ethers.ExecutionError alias Ethers.Receipt alias Ethers.ReceiptTest.Fixtures @@ -420,6 +436,114 @@ defmodule Ethers.ReceiptTest do end end + describe "decode_logs/2" do + setup do + [receipt: receipt!(Fixtures.token_transfers())] + end + + test "decodes all events of an EventFilters module", %{receipt: receipt} do + assert [ + %Event{ + address: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", + topics: ["Approval(address,address,uint256)", @vitalik, @receiver], + data: [1_000_000], + log_index: 16 + }, + %Event{ + address: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", + topics: ["Transfer(address,address,uint256)", @vitalik, @receiver], + data: [1_000_000], + log_index: 17, + block_hash: block_hash, + block_number: 21_563_820, + transaction_hash: transaction_hash, + transaction_index: 94, + removed: false + }, + %Event{ + address: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", + topics: ["Transfer(address,address,uint256)", @receiver, @vitalik], + data: [2_000], + log_index: 20 + } + ] = Receipt.decode_logs(receipt, ERC20.EventFilters) + + assert block_hash == receipt.block_hash + assert transaction_hash == receipt.transaction_hash + end + + test "skips events with the same signature but other indexed arguments", %{receipt: receipt} do + assert [ + %Event{ + address: "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d", + topics: ["Transfer(address,address,uint256)", @vitalik, @receiver, 7382], + data: [], + log_index: 18 + } + ] = Receipt.decode_logs(receipt, ERC721.EventFilters) + end + + test "decodes logs matching a single event filter", %{receipt: receipt} do + assert [%Event{log_index: 17}, %Event{log_index: 20}] = + Receipt.decode_logs(receipt, ERC20.EventFilters.transfer(nil, nil)) + + assert [%Event{log_index: 17}] = + Receipt.decode_logs(receipt, ERC20.EventFilters.transfer(@vitalik, nil)) + + assert [%Event{log_index: 20}] = + Receipt.decode_logs(receipt, ERC20.EventFilters.transfer(nil, @vitalik)) + + assert [] = Receipt.decode_logs(receipt, ERC20.EventFilters.transfer(@usdc, nil)) + end + + test "skips logs with the signature of an event but malformed data", %{receipt: receipt} do + # Logs 20 and 21 have the same topics, the data of log 21 is not a uint256 + assert [%Event{log_index: 20}] = + Receipt.decode_logs(receipt, ERC20.EventFilters.transfer(@receiver, @vitalik)) + + [approval_log | _] = receipt.logs + receipt = %{receipt | logs: [%{approval_log | "data" => "0xzz"}]} + + assert [] = Receipt.decode_logs(receipt, ERC20.EventFilters) + end + + test "decodes logs matching a combined event filter", %{receipt: receipt} do + filter = + EventFilter.combine([ + ERC20.EventFilters.transfer(nil, nil), + ERC20.EventFilters.approval(nil, nil) + ]) + + assert [%Event{log_index: 16}, %Event{log_index: 17}, %Event{log_index: 20}] = + Receipt.decode_logs(receipt, filter) + end + + test "only decodes logs of the default address of the filter", %{receipt: receipt} do + assert [%Event{log_index: 16}, %Event{log_index: 17}] = + Receipt.decode_logs(receipt, ReceiptUsdcContract.EventFilters) + + assert [%Event{log_index: 17}] = + Receipt.decode_logs(receipt, ReceiptUsdcContract.EventFilters.transfer(nil, nil)) + + filter = %{ERC20.EventFilters.transfer(nil, nil) | default_address: String.downcase(@usdc)} + assert [%Event{log_index: 17}] = Receipt.decode_logs(receipt, filter) + + filter = %{ERC20.EventFilters.transfer(nil, nil) | default_address: @vitalik} + assert [] = Receipt.decode_logs(receipt, filter) + end + + test "returns an empty list without logs" do + assert [] = Receipt.decode_logs(receipt!(Fixtures.eip1559_transfer()), ERC20.EventFilters) + assert [] = Receipt.decode_logs(%Receipt{}, ERC20.EventFilters) + end + + test "raises for a module which is not an EventFilters module", %{receipt: receipt} do + assert_raise ArgumentError, ~r/is not an EventFilters module/, fn -> + Receipt.decode_logs(receipt, ERC20) + end + end + end + describe "get_transaction_receipt/2 with a node" do test "returns the receipt of a transfer" do tx_hash = @@ -486,6 +610,62 @@ defmodule Ethers.ReceiptTest do assert to == Utils.to_checksum_address(address) end + test "decode_logs/2 decodes the events emitted by a contract call" do + address = + deploy(ReceiptCounterContract, + encoded_constructor: ReceiptCounterContract.constructor(100), + from: @from + ) + + tx_hash = + ReceiptCounterContract.set(101) + |> Ethers.send_transaction!(from: @from, to: address) + + wait_for_transaction!(tx_hash) + + receipt = Ethers.get_transaction_receipt!(tx_hash) + block_number = receipt.block_number + + assert [ + %Event{ + address: ^address, + topics: ["SetCalled(uint256,uint256)", 100], + data: [101], + transaction_hash: ^tx_hash, + block_number: ^block_number + } + ] = events = Receipt.decode_logs(receipt, ReceiptCounterContract.EventFilters) + + assert events == + Ethers.get_logs!(ReceiptCounterContract.EventFilters.set_called(nil), + address: address, + from_block: block_number, + to_block: block_number + ) + + assert ^events = + Receipt.decode_logs(receipt, ReceiptCounterContract.EventFilters.set_called(100)) + + assert [] = + Receipt.decode_logs(receipt, ReceiptCounterContract.EventFilters.set_called(105)) + + assert [] = Receipt.decode_logs(receipt, ReceiptHelloWorldContract.EventFilters) + + checksummed_default_address = %{ + ReceiptCounterContract.EventFilters.set_called(nil) + | default_address: Utils.to_checksum_address(address) + } + + assert ^events = Receipt.decode_logs(receipt, checksummed_default_address) + + other_default_address = %{ + ReceiptCounterContract.EventFilters.set_called(nil) + | default_address: @value_receiver + } + + assert [] = Receipt.decode_logs(receipt, other_default_address) + end + test "batch returns receipts" do tx_hash = Ethers.send_transaction!(%{value: 1000}, From 0269019b5ff5b90f700269bc75d6c345913e2c93 Mon Sep 17 00:00:00 2001 From: Alisina Bahadori Date: Sun, 15 Nov 2026 16:24:07 -0500 Subject: [PATCH 3/5] Add changelog and upgrade guide entries for Ethers.Receipt Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012hqvX8DbbP3mgXy5hVEDc6 --- CHANGELOG.md | 4 ++++ guides/upgrading.md | 29 +++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e2ed79..4ab8c61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,12 +14,15 @@ - `Ethers.Transaction.decode/1` returns `{:error, reason}` instead of raising on malformed input - 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 ### Enhancements - Add `Ethers.config/1` (`eth_config`, [EIP-7910](https://eips.ethereum.org/EIPS/eip-7910)) returning `Ethers.ForkConfig` structs - Update dependencies - Allow `idna` 8.x +- Add `Ethers.Receipt` struct with decoded transaction receipt fields +- Add `Ethers.Receipt.decode_logs/2` to decode receipt logs with event filters ### Bug Fixes @@ -33,6 +36,7 @@ - Fix `Ethers.Transaction.Signed.from_address/1` raising on out-of-range recovery ids - Fix `:deployed_address` in `Ethers.batch/2` - Compare the `:signer_opts` `from` address with the transaction `from` case-insensitively +- Fix the `:get_transaction_receipt` action of `Ethers.batch/2` ## 0.8.0 (2026-07-29) diff --git a/guides/upgrading.md b/guides/upgrading.md index 4125770..40481cd 100644 --- a/guides/upgrading.md +++ b/guides/upgrading.md @@ -212,8 +212,8 @@ casing they were configured with: build Other returned addresses (ABI-decoded values, transaction `to`, recovered signers, ...) were -already checksummed. Raw RPC values (`topics_raw`, `data_raw`, `Ethers.get_transaction_receipt/2` -maps) are unchanged, and addresses are still accepted in any casing. +already checksummed. Raw RPC values (`topics_raw`, `data_raw`, the `logs` of an `Ethers.Receipt`) +are unchanged, and addresses are still accepted in any casing. ```elixir {:ok, address} = Ethers.deployed_address(tx_hash) @@ -234,6 +234,31 @@ address == Ethers.Utils.to_checksum_address(other_address) Ethers.Utils.decode_address!(address) == Ethers.Utils.decode_address!(other_address) ``` +### Transaction Receipts + +#### `get_transaction_receipt/2` returns an `Ethers.Receipt` struct + +`Ethers.get_transaction_receipt/2`, `Ethers.get_transaction_receipt!/2` and the +`:get_transaction_receipt` action of `Ethers.batch/2` return an `Ethers.Receipt` struct instead of +the node's JSON map: quantities are integers, `status` is `:success` or `:failure` and addresses are +checksummed. Logs are kept as returned by the node, decode them with +`Ethers.Receipt.decode_logs/2`. The node's map, including chain specific members, is available as +`raw`. A malformed receipt returns `{:error, {:invalid_receipt_member, member}}`. + +```elixir +{:ok, receipt} = Ethers.get_transaction_receipt(tx_hash) + +# Before (0.8.x) +%{"status" => "0x1", "gasUsed" => gas_used_hex, "contractAddress" => contract_address} = receipt +gas_used = Ethers.Utils.hex_to_integer!(gas_used_hex) +l1_fee = receipt["l1Fee"] + +# After (1.0.0) +%Ethers.Receipt{status: :success, gas_used: gas_used, contract_address: contract_address} = receipt +l1_fee = receipt.raw["l1Fee"] +events = Ethers.Receipt.decode_logs(receipt, MyContract.EventFilters) +``` + ## Upgrading to 0.6.x Version 0.6.x and onwards introduce several breaking changes to improve type safety and explicitness. From 52984a4e564eeef421ec849792ea5403245847ff Mon Sep 17 00:00:00 2001 From: Alisina Bahadori Date: Sun, 15 Nov 2026 16:39:58 -0500 Subject: [PATCH 4/5] Replace Ethers.Receipt raw with extra `raw` duplicated the whole node map, including every member the struct already decodes. It is replaced by `extra`, which holds only the members this version of the library does not decode (the receipt map minus every member of the decoder table, present or not): chain specific members such as the OP Stack L1 fee fields, and node extras such as anvil's `blockTimestamp`. Keys and values stay as returned by the node, and it is `%{}` when there are none. A member can move from `extra` to a struct field in a later release. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012hqvX8DbbP3mgXy5hVEDc6 --- guides/upgrading.md | 7 ++-- lib/ethers.ex | 4 +-- lib/ethers/receipt.ex | 24 +++++++++----- test/ethers/receipt_test.exs | 62 ++++++++++++++++++++++++++++-------- 4 files changed, 71 insertions(+), 26 deletions(-) diff --git a/guides/upgrading.md b/guides/upgrading.md index 40481cd..ff6ce89 100644 --- a/guides/upgrading.md +++ b/guides/upgrading.md @@ -242,8 +242,9 @@ Ethers.Utils.decode_address!(address) == Ethers.Utils.decode_address!(other_addr `:get_transaction_receipt` action of `Ethers.batch/2` return an `Ethers.Receipt` struct instead of the node's JSON map: quantities are integers, `status` is `:success` or `:failure` and addresses are checksummed. Logs are kept as returned by the node, decode them with -`Ethers.Receipt.decode_logs/2`. The node's map, including chain specific members, is available as -`raw`. A malformed receipt returns `{:error, {:invalid_receipt_member, member}}`. +`Ethers.Receipt.decode_logs/2`. Members the library does not decode, such as chain specific +members, are kept undecoded in `extra`. A malformed receipt returns +`{:error, {:invalid_receipt_member, member}}`. ```elixir {:ok, receipt} = Ethers.get_transaction_receipt(tx_hash) @@ -255,7 +256,7 @@ l1_fee = receipt["l1Fee"] # After (1.0.0) %Ethers.Receipt{status: :success, gas_used: gas_used, contract_address: contract_address} = receipt -l1_fee = receipt.raw["l1Fee"] +l1_fee = receipt.extra["l1Fee"] events = Ethers.Receipt.decode_logs(receipt, MyContract.EventFilters) ``` diff --git a/lib/ethers.ex b/lib/ethers.ex index 1223e68..2dff131 100644 --- a/lib/ethers.ex +++ b/lib/ethers.ex @@ -254,8 +254,8 @@ defmodule Ethers do `Ethers.Receipt` struct. The logs of the receipt are kept as returned by the node, decode them with - `Ethers.Receipt.decode_logs/2`. The receipt as returned by the node, including chain - specific members, is available in the `raw` field. + `Ethers.Receipt.decode_logs/2`. Members the library does not decode, such as chain + specific members, are kept undecoded in the `extra` field. Also works with `Ethers.batch/2` as `{:get_transaction_receipt, tx_hash}`. diff --git a/lib/ethers/receipt.ex b/lib/ethers/receipt.ex index 4d4c309..d8e6185 100644 --- a/lib/ethers/receipt.ex +++ b/lib/ethers/receipt.ex @@ -19,9 +19,9 @@ defmodule Ethers.Receipt do - `logs` are kept as returned by the node, see [Logs](#module-logs). - A member the node omits is `nil` (e.g. `status` of a pre-Byzantium receipt, or `blob_gas_used` of a non-blob transaction). - - Members not defined by the schema are ignored. Chain specific members (e.g. the L1 fee - members of OP Stack chains) are available in `raw`, the receipt exactly as returned by the - node. + - Members this version of the library does not decode, such as chain specific members + (e.g. the L1 fee members of OP Stack chains) or node extras, are kept undecoded in + `extra`. `Ethers.get_transaction_receipt/2` returns `{:error, {:invalid_receipt_member, member}}` when the node returns a member that does not match the schema (e.g. a `status` other than @@ -54,7 +54,7 @@ defmodule Ethers.Receipt do transaction_hash: "0x9c4e...6e5d", transaction_index: 94, type: 2, - raw: %{"blockHash" => "0x5f3a...3b20", "status" => "0x1", ...}, + extra: %{}, ... } @@ -89,7 +89,7 @@ defmodule Ethers.Receipt do :transaction_hash, :transaction_index, :type, - raw: %{} + extra: %{} ] @typedoc """ @@ -122,7 +122,11 @@ defmodule Ethers.Receipt do - `logs` - the logs emitted by the transaction, as returned by the node. See `decode_logs/2`. - `logs_bloom` - the 256 byte bloom filter of the logs, as a binary. - - `raw` - the receipt exactly as returned by the node, including chain specific members. + - `extra` - the members returned by the node that this version of the library does not + decode (e.g. the L1 fee members of OP Stack chains), with their RPC member names as keys + and their values as returned by the node. `%{}` when there are none. It only holds + members this version does not decode, so a member can move from `extra` to a struct + field in a later release. """ @type t :: %__MODULE__{ blob_gas_price: non_neg_integer() | nil, @@ -132,11 +136,11 @@ defmodule Ethers.Receipt do contract_address: Types.t_address() | nil, cumulative_gas_used: non_neg_integer() | nil, effective_gas_price: non_neg_integer() | nil, + extra: %{optional(String.t()) => term()}, from: Types.t_address() | nil, gas_used: non_neg_integer() | nil, logs: [map()] | nil, logs_bloom: binary() | nil, - raw: map(), root: Types.t_hash() | nil, status: :success | :failure | nil, to: Types.t_address() | nil, @@ -166,11 +170,15 @@ defmodule Ethers.Receipt do logs_bloom: {"logsBloom", :bytes} ] + @known_members Enum.map(@members, fn {_field, {member, _kind}} -> member end) + @doc false @spec from_rpc_map(term()) :: {:ok, t()} | {:error, :invalid_receipt | {:invalid_receipt_member, String.t()}} def from_rpc_map(receipt) when is_map(receipt) do - Enum.reduce_while(@members, {:ok, %__MODULE__{raw: receipt}}, fn + extra = Map.drop(receipt, @known_members) + + Enum.reduce_while(@members, {:ok, %__MODULE__{extra: extra}}, fn {field, {member, kind}}, {:ok, decoded} -> case receipt |> Map.get(member) |> decode_member(kind) do {:ok, value} -> {:cont, {:ok, Map.put(decoded, field, value)}} diff --git a/test/ethers/receipt_test.exs b/test/ethers/receipt_test.exs index e66c210..808a358 100644 --- a/test/ethers/receipt_test.exs +++ b/test/ethers/receipt_test.exs @@ -257,6 +257,10 @@ defmodule Ethers.ReceiptTest do @usdc "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" @missing_tx_hash "0x5194596d703a53f65dcb1d7df60fcfa1f7d904ad3145887677a6ab68a425d8d3" + @known_members ~w(transactionHash transactionIndex blockHash blockNumber from to + contractAddress type status root gasUsed cumulativeGasUsed + effectiveGasPrice blobGasUsed blobGasPrice logs logsBloom) + defp get_receipt(response) do Ethers.get_transaction_receipt(@missing_tx_hash, rpc_client: ReceiptRPC, @@ -294,7 +298,7 @@ defmodule Ethers.ReceiptTest do blob_gas_price: nil, logs: [], logs_bloom: :binary.copy(<<0>>, 256), - raw: rpc_receipt + extra: %{} } end @@ -333,17 +337,43 @@ defmodule Ethers.ReceiptTest do } = receipt!(Fixtures.pre_byzantium()) end - test "keeps chain specific members in raw" do - rpc_receipt = Fixtures.op_stack_transaction() - receipt = receipt!(rpc_receipt) + test "keeps the members it does not decode undecoded in extra" do + receipt = receipt!(Fixtures.op_stack_transaction()) + + assert receipt.extra == %{ + "l1BaseFeeScalar" => "0x8dd", + "l1BlobBaseFee" => "0x1", + "l1BlobBaseFeeScalar" => "0x101c12", + "l1Fee" => "0x1c5ee8a2b4", + "l1GasPrice" => "0x2540be400", + "l1GasUsed" => "0x640" + } - assert receipt.raw == rpc_receipt - assert receipt.raw["l1Fee"] == "0x1c5ee8a2b4" - assert %{receipt | raw: nil} == %{receipt!(Fixtures.eip1559_transfer()) | raw: nil} + for member <- ["gasUsed", "status", "logs"] do + refute Map.has_key?(receipt.extra, member) + end + + assert %{receipt | extra: %{}} == receipt!(Fixtures.eip1559_transfer()) + end + + test "has empty extra when the node sends no members it does not decode" do + for rpc_receipt <- [ + Fixtures.eip1559_transfer(), + Fixtures.contract_creation(), + Fixtures.failed_transaction(), + Fixtures.blob_transaction(), + Fixtures.pre_byzantium(), + Fixtures.token_transfers() + ] do + assert receipt!(rpc_receipt).extra == %{} + end end test "decodes transaction types unknown to the library to their type id" do - assert %Receipt{type: 126, effective_gas_price: 0} = receipt!(Fixtures.op_stack_deposit()) + assert %Receipt{type: 126, effective_gas_price: 0, extra: extra} = + receipt!(Fixtures.op_stack_deposit()) + + assert extra == %{"depositNonce" => "0x9a2b1", "depositReceiptVersion" => "0x1"} end test "keeps logs as returned by the node" do @@ -359,7 +389,7 @@ defmodule Ethers.ReceiptTest do assert receipt!(rpc_receipt) == %Receipt{ transaction_hash: rpc_receipt["transactionHash"], - raw: rpc_receipt + extra: %{} } end @@ -424,9 +454,11 @@ defmodule Ethers.ReceiptTest do rpc_opts: [response: {:ok, rpc_receipt}, send_params_to_pid: self()] ] - assert {:ok, [{:ok, %Receipt{type: 2, status: :success, raw: ^rpc_receipt}}]} = + assert {:ok, [{:ok, receipt}]} = Ethers.batch([{:get_transaction_receipt, @missing_tx_hash}], opts) + assert receipt == receipt!(rpc_receipt) + assert_received {:batch_request, [{:eth_get_transaction_receipt, [@missing_tx_hash]}]} opts = [rpc_client: ReceiptRPC, rpc_opts: [response: {:ok, nil}]] @@ -568,10 +600,13 @@ defmodule Ethers.ReceiptTest do type: 2, status: :success, gas_used: 21_000, - logs: [], - raw: %{"transactionHash" => ^tx_hash} + logs: [] } = receipt + # Node extras differ between anvil versions: only check that known members are decoded + assert is_map(receipt.extra) + assert Map.take(receipt.extra, @known_members) == %{} + assert receipt.cumulative_gas_used >= receipt.gas_used assert receipt.effective_gas_price > 0 assert byte_size(receipt.logs_bloom) == 256 @@ -588,10 +623,11 @@ defmodule Ethers.ReceiptTest do assert {:ok, address} = Ethers.deployed_address(tx_hash) - assert %Receipt{to: nil, status: :success, contract_address: contract_address} = + assert %Receipt{to: nil, status: :success, contract_address: contract_address, extra: extra} = Ethers.get_transaction_receipt!(tx_hash) assert contract_address == Utils.to_checksum_address(address) + assert Map.take(extra, @known_members) == %{} assert ReceiptHelloWorldContract.say_hello() |> Ethers.call!(to: contract_address) == "Hello World!" From 5a8098b1e5678fdced7f8206be988d262d24d7b6 Mon Sep 17 00:00:00 2001 From: Alisina Bahadori Date: Sun, 15 Nov 2026 18:16:18 -0500 Subject: [PATCH 5/5] Expect checksummed event and deployed addresses in receipt tests Since #312, `Ethers.Event.address` and `Ethers.deployed_address/2` are checksummed, so the receipt tests compare them with the receipt's addresses directly. The default address case uses a lowercase address to keep covering case-insensitive matching in `decode_logs/2`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012hqvX8DbbP3mgXy5hVEDc6 --- test/ethers/receipt_test.exs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/test/ethers/receipt_test.exs b/test/ethers/receipt_test.exs index 808a358..76b34ce 100644 --- a/test/ethers/receipt_test.exs +++ b/test/ethers/receipt_test.exs @@ -476,13 +476,13 @@ defmodule Ethers.ReceiptTest do test "decodes all events of an EventFilters module", %{receipt: receipt} do assert [ %Event{ - address: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", + address: @usdc, topics: ["Approval(address,address,uint256)", @vitalik, @receiver], data: [1_000_000], log_index: 16 }, %Event{ - address: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", + address: @usdc, topics: ["Transfer(address,address,uint256)", @vitalik, @receiver], data: [1_000_000], log_index: 17, @@ -493,7 +493,7 @@ defmodule Ethers.ReceiptTest do removed: false }, %Event{ - address: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", + address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", topics: ["Transfer(address,address,uint256)", @receiver, @vitalik], data: [2_000], log_index: 20 @@ -507,7 +507,7 @@ defmodule Ethers.ReceiptTest do test "skips events with the same signature but other indexed arguments", %{receipt: receipt} do assert [ %Event{ - address: "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d", + address: "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D", topics: ["Transfer(address,address,uint256)", @vitalik, @receiver, 7382], data: [], log_index: 18 @@ -626,7 +626,7 @@ defmodule Ethers.ReceiptTest do assert %Receipt{to: nil, status: :success, contract_address: contract_address, extra: extra} = Ethers.get_transaction_receipt!(tx_hash) - assert contract_address == Utils.to_checksum_address(address) + assert contract_address == address assert Map.take(extra, @known_members) == %{} assert ReceiptHelloWorldContract.say_hello() |> Ethers.call!(to: contract_address) == @@ -642,8 +642,7 @@ defmodule Ethers.ReceiptTest do wait_for_transaction!(tx_hash) - assert %Receipt{status: :failure, to: to} = Ethers.get_transaction_receipt!(tx_hash) - assert to == Utils.to_checksum_address(address) + assert %Receipt{status: :failure, to: ^address} = Ethers.get_transaction_receipt!(tx_hash) end test "decode_logs/2 decodes the events emitted by a contract call" do @@ -687,12 +686,12 @@ defmodule Ethers.ReceiptTest do assert [] = Receipt.decode_logs(receipt, ReceiptHelloWorldContract.EventFilters) - checksummed_default_address = %{ + lowercase_default_address = %{ ReceiptCounterContract.EventFilters.set_called(nil) - | default_address: Utils.to_checksum_address(address) + | default_address: String.downcase(address) } - assert ^events = Receipt.decode_logs(receipt, checksummed_default_address) + assert ^events = Receipt.decode_logs(receipt, lowercase_default_address) other_default_address = %{ ReceiptCounterContract.EventFilters.set_called(nil)