Blockchain infrastructure · 5 MIN READ

Receipts and logs: decode ERC-20 transfers from the right contract and reverse them on reorg

Interpret receipt status and gas, decode an ERC-20 Transfer log with accounts/abi, and reject impostor or removed logs before crediting a balance.

A receipt is the node's report of what a transaction did: whether execution succeeded, how much gas it used and which events contracts emitted. Deposit detectors, payment processors and indexers turn those events into balances, which makes the decoding rules security rules. Anyone can deploy a contract that emits a log shaped exactly like a token transfer, and a log from a block that is later reorganized away has to be reversed.

blockchain · A MAP OF THE IDEA

  1. Check receipt status
  2. Match address + topic0
  3. Decode topics and data
  4. Key credit, honor Removed

Useful when

  • Impostor contracts and look-alike events are rejected before money moves.
  • Duplicate and removed deliveries keep the projection consistent.

Watch out

  • Log position fields come from the provider and are not consensus-checked.
  • Reversal works only while credits are internal; irreversible effects need finality.

Implementation & operation cost: A per-chain token allow-list, an idempotency key per delivered log and reversal logic in every projection that consumes events.

01

What a receipt proves, and what it does not

Receipt.Status is 1 (types.ReceiptStatusSuccessful) or 0 (types.ReceiptStatusFailed). A failed transaction is still included: the sender paid GasUsed * EffectiveGasPrice, the nonce is consumed, and every state change and log from the execution was discarded, so Logs is empty. A successful status only says execution did not revert; whether your business effect happened depends on which logs were emitted and by which contract. Each Log carries the emitting contract Address, zero to four Topics and an opaque Data section. Its block number, block hash, transaction hash and log index are derived fields filled in by the node; go-ethereum's own comment says they are not secured by consensus, so they are only as trustworthy as the provider that served them.

02

Indexed fields live in topics, the rest in data

For a non-anonymous Solidity event, topic 0 is keccak256 of the canonical signature, Transfer(address,address,uint256) for ERC-20. Each indexed parameter takes one further topic as a 32-byte word, and the non-indexed parameters are ABI-encoded into Data. The program builds a successful receipt in memory with three logs (a genuine transfer from the expected token contract, the same bytes from an impostor contract and a four-topic log), adds a reverted receipt, then pushes the genuine log through a reorg.

go
package main

import (
	"fmt"
	"math/big"
	"strings"

	"github.com/ethereum/go-ethereum/accounts/abi"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/crypto"
)

const transferABI = `[{"type":"event","name":"Transfer","anonymous":false,"inputs":[
{"name":"from","type":"address","indexed":true},
{"name":"to","type":"address","indexed":true},
{"name":"value","type":"uint256","indexed":false}]}]`

type Transfer struct {
	From  common.Address
	To    common.Address
	Value *big.Int
}

func decodeTransfer(token abi.ABI, want common.Address, lg *types.Log) (Transfer, error) {
	ev := token.Events["Transfer"]
	if lg.Address != want {
		return Transfer{}, fmt.Errorf("emitted by %s, not the token", lg.Address.Hex())
	}
	if len(lg.Topics) != 3 || lg.Topics[0] != ev.ID {
		return Transfer{}, fmt.Errorf("%d topics, not an ERC-20 Transfer", len(lg.Topics))
	}
	var out Transfer
	if err := token.UnpackIntoInterface(&out, "Transfer", lg.Data); err != nil {
		return Transfer{}, err // fills Value from the data section
	}
	var indexed abi.Arguments
	for _, arg := range ev.Inputs {
		if arg.Indexed {
			indexed = append(indexed, arg)
		}
	}
	if err := abi.ParseTopics(&out, indexed, lg.Topics[1:]); err != nil {
		return Transfer{}, err // fills From and To from topics 1 and 2
	}
	return out, nil
}

// deposits credits each delivered log once, keyed by block hash and log index,
// and reverses the credit when the same log comes back with Removed set.
type deposits struct {
	token    abi.ABI
	contract common.Address
	applied  map[string]bool
	balance  map[common.Address]*big.Int
}

func (d *deposits) onLog(lg *types.Log) {
	t, err := decodeTransfer(d.token, d.contract, lg)
	if err != nil {
		fmt.Printf("log %d skipped: %v\n", lg.Index, err)
		return
	}
	key := fmt.Sprintf("%s/%d", lg.BlockHash.Hex(), lg.Index)
	if d.balance[t.To] == nil {
		d.balance[t.To] = new(big.Int)
	}
	switch {
	case lg.Removed && d.applied[key]:
		d.balance[t.To].Sub(d.balance[t.To], t.Value)
		delete(d.applied, key)
		fmt.Printf("log %d removed: reverse %s\n", lg.Index, t.Value)
	case !lg.Removed && !d.applied[key]:
		d.balance[t.To].Add(d.balance[t.To], t.Value)
		d.applied[key] = true
		fmt.Printf("log %d: credit %s from %s\n", lg.Index, t.Value, t.From.Hex())
	}
}

func (d *deposits) onReceipt(r *types.Receipt) {
	fee := new(big.Int).Mul(new(big.Int).SetUint64(r.GasUsed), r.EffectiveGasPrice)
	fmt.Printf("status %d, gas used %d, fee %s wei, %d logs\n", r.Status, r.GasUsed, fee, len(r.Logs))
	if r.Status != types.ReceiptStatusSuccessful {
		return // reverted: the fee was paid, but no token moved
	}
	for _, lg := range r.Logs {
		d.onLog(lg)
	}
}

func main() {
	token, err := abi.JSON(strings.NewReader(transferABI))
	if err != nil {
		panic(err)
	}
	ev := token.Events["Transfer"]
	fmt.Println("topic0", ev.ID.Hex())
	fmt.Println("equals keccak256 of the signature:", ev.ID == crypto.Keccak256Hash([]byte(ev.Sig)))

	contract := common.HexToAddress("0x00000000000000000000000000000000000000c0")
	impostor := common.HexToAddress("0x00000000000000000000000000000000000000ee")
	from := common.HexToAddress("0x1a642f0E3c3aF545E7AcBD38b07251B3990914F1")
	to := common.HexToAddress("0x00000000000000000000000000000000000000bb")
	data, err := ev.Inputs.NonIndexed().Pack(big.NewInt(2_500_000))
	if err != nil {
		panic(err)
	}
	fromTopic, toTopic := common.BytesToHash(from.Bytes()), common.BytesToHash(to.Bytes())
	blockA := common.HexToHash("0xa1")
	ok := &types.Receipt{
		Status: types.ReceiptStatusSuccessful, GasUsed: 51_000,
		EffectiveGasPrice: big.NewInt(32_000_000_000), BlockHash: blockA,
		Logs: []*types.Log{
			{Address: contract, Topics: []common.Hash{ev.ID, fromTopic, toTopic}, Data: data, BlockHash: blockA, Index: 4},
			{Address: impostor, Topics: []common.Hash{ev.ID, fromTopic, toTopic}, Data: data, BlockHash: blockA, Index: 5},
			{Address: contract, Topics: []common.Hash{ev.ID, fromTopic, toTopic, common.BigToHash(big.NewInt(9))}, BlockHash: blockA, Index: 6},
		},
	}
	reverted := &types.Receipt{Status: types.ReceiptStatusFailed, GasUsed: 29_000, EffectiveGasPrice: big.NewInt(32_000_000_000)}

	d := &deposits{token: token, contract: contract, applied: map[string]bool{}, balance: map[common.Address]*big.Int{}}
	d.onReceipt(ok)
	d.onLog(ok.Logs[0]) // a duplicate delivery changes nothing
	d.onReceipt(reverted)
	fmt.Printf("credited to %s: %s\n", to.Hex(), d.balance[to])

	// Reorg: block A leaves the canonical chain, the log is re-sent with Removed
	// set, and the transaction is included again in block B at another index.
	gone := *ok.Logs[0]
	gone.Removed = true
	d.onLog(&gone)
	again := *ok.Logs[0]
	again.BlockHash, again.Index = common.HexToHash("0xb1"), 0
	d.onLog(&again)
	fmt.Printf("credited after reorg: %s\n", d.balance[to])
}
Read the code

abi.JSON parses the event, and Event.ID is the topic-0 hash computed from Event.Sig. decodeTransfer checks the emitting address first, then requires exactly three topics with the right topic 0: an ERC-721 Transfer has the same signature and topic 0 but indexes tokenId as a fourth topic and leaves Data empty. UnpackIntoInterface fills only the non-indexed Value from Data, and abi.ParseTopics fills From and To from topics 1 and 2. The reverted receipt is charged a fee and credits nothing. Credits are keyed by block hash and log index, so the duplicate delivery is a no-op, the Removed copy reverses the credit, and the re-inclusion in block B is credited once under its new key.

03

Two decoding traps in accounts/abi

Unpacking event data never reads topics. ABI.UnpackIntoInterface and Arguments.Unpack skip indexed arguments entirely, so a struct decoded only from Data has zero-value From and To fields and no error. ParseTopics wants the indexed arguments alone and the topics after topic 0, and it sets struct fields by reflection from the camel-cased ABI names; if the struct lacks a field, it panics rather than returning an error, so keep the struct next to the ABI and cover it with a test. Indexed strings, bytes and arrays cannot be decoded at all, because the topic holds keccak256 of the value instead of the value. When the ABI comes from a third party, decode with the ABI you reviewed for that deployed address, not with whatever interface the contract claims; the abi-calls lesson makes the same point for calls.

04

Filter in the query, verify again in the handler

Push the cheap filters to the node with an ethereum.FilterQuery: the contract address and topic 0 limit what you download, and a topic-2 filter restricts results to transfers into your own addresses. Then repeat every check in the handler anyway. A provider can be buggy or hostile, a query can be widened later by someone else, and the handler is where the money moves.

go
transferID := token.Events["Transfer"].ID
watched := common.BytesToHash(depositAddress.Bytes())
q := ethereum.FilterQuery{
	FromBlock: new(big.Int).SetUint64(from),
	ToBlock:   new(big.Int).SetUint64(to), // bounded range, never open-ended
	Addresses: []common.Address{tokenAddress},
	Topics:    [][]common.Hash{{transferID}, nil, {watched}},
}
logs, err := client.FilterLogs(ctx, q)
if err != nil {
	return err
}
for i := range logs {
	d.onLog(&logs[i]) // the same checks as the offline example
}
Read the code

Run this fragment in your own native environment against a node for the expected chain. Topics is positional: the first inner slice matches topic 0, nil accepts any sender in position 1, and the third restricts topic 2, the recipient, to the watched address. FilterLogs returns []types.Log by value, so the loop passes the address of each element. Keep the range bounded, because providers cap block spans and result counts; the events-finality lesson covers backfill and checkpoints.

05

Removed logs and what a credit should wait for

Logs from FilterLogs reflect the canonical chain at query time. Logs delivered through SubscribeFilterLogs or polling filters can arrive twice: once when the block is imported and again with Removed set to true when a reorganization takes that block off the canonical chain. The handler must reverse exactly what it applied, which is why the example keys credits by the delivered log's block hash and log index rather than by transaction hash: the same transaction is often re-included on the new branch at another position and deserves its own credit. Reversal is only possible while the credit is still internal. Anything irreversible, such as shipping goods or withdrawing to another chain, should wait for the confirmation or finality policy from the events-finality lesson. Test the handler with a reverted receipt, an impostor contract, a four-topic Transfer, truncated Data, a duplicate delivery and a removed log whose credit was never applied.

TAKE THIS WITH YOU

Credit a token transfer only from a successful receipt, the expected contract address, the exact topic 0 and topic count, and key the credit so a Removed log reverses precisely what was applied.

Check your understanding

Which checks must pass before a log is credited as an ERC-20 deposit?

Go to the source

Progress stays in this browser. No account needed.