Sub topic 3
Tracking token transfers through event logs
This chapter assumes you know what a transaction, an address, and a smart contract are. It also assumes you can read basic Python and have seen the account model from the previous chapter. You will learn where token transfers are recorded on Ethereum-style chains, how to query and decode them, and which cases make a naive transfer count wrong.
Why tokens need a different approach
Moving the chain's native coin (ETH on Ethereum) changes balances inside the protocol itself. Moving a token such as USDT or USDC does not. A token is a smart contract that keeps its own table of balances. A "transfer" is a call to that contract that edits its table.
So the sender and receiver of a token transfer usually do not appear as the from and to of the transaction. The transaction's to is the token contract, and the real sender and receiver are encoded inside the call data. Reading transactions alone gives you the wrong picture.
The contract also emits an event when balances change. Events are the reliable, cheap-to-query record of those changes, and they are what flow trackers read.
What an event log contains
An event log is a record written into a transaction receipt while the transaction runs. Each log has these fields:
| Field | Meaning |
|---|---|
| `address` | The contract that emitted the event |
| `topics` | Up to four 32-byte values. The first identifies the event type, and the rest are the indexed arguments |
| `data` | The non-indexed arguments, packed in 32-byte words |
| `blockNumber`, `transactionHash`, `logIndex` | Where the log sits on the chain |
| `removed` | `true` if a chain reorganization removed the log |
The ERC-20 standard defines this event:
Transfer(address indexed from, address indexed to, uint256 value)topics[0] is the keccak-256 hash of the signature string Transfer(address,address,uint256). This is always 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. The two indexed addresses become topics[1] and topics[2]. The amount is not indexed, so it sits in data.
An address is 20 bytes, but a topic is 32 bytes. The address is left-padded with 12 zero bytes, so you take the last 40 hex characters.
Querying logs with eth_getLogs
The JSON-RPC method eth_getLogs returns logs that match a filter. This request fetches Transfer events for one token over eleven blocks:
{
"jsonrpc": "2.0",
"id": 1,
"method": "eth_getLogs",
"params": [
{
"fromBlock": "0x10d4f00",
"toBlock": "0x10d4f0a",
"address": "<TOKEN_CONTRACT_ADDRESS>",
"topics": [
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
]
}
]
}Block numbers are hexadecimal strings. Replace the placeholder with the token's contract address.
You can narrow the filter in the topics array. Position 0 is the event type, position 1 is from, and position 2 is to. Use null to accept any value at a position. To find only transfers into a known exchange address, pass null for from and the padded exchange address for to. The node does this filtering with an index, which is much cheaper than downloading everything and filtering yourself.
{
"jsonrpc": "2.0",
"id": 2,
"method": "eth_getLogs",
"params": [
{
"fromBlock": "0x10d4f00",
"toBlock": "0x10d4f0a",
"address": "<TOKEN_CONTRACT_ADDRESS>",
"topics": [
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
null,
"0x000000000000000000000000<EXCHANGE_ADDRESS_WITHOUT_0x>"
]
}
]
}To match several addresses at one position, put an array of topics there. The array means "any of these".
Range and result limits
Providers cap how much one call may return. Common limits are a maximum block span (for example a few thousand blocks) or a maximum number of results. When a call fails because of a limit, split the range and retry. The helper below does that for any fetch function you give it.
def fetch_range(fetch, start, end, max_span=2000):
"""Call fetch(start, end) over [start, end], splitting on failure.
fetch must return a list of logs, or raise an exception if the
provider rejects the range (too many results or too wide a span).
"""
if end - start + 1 > max_span:
mid = (start + end) // 2
return (fetch_range(fetch, start, mid, max_span)
+ fetch_range(fetch, mid + 1, end, max_span))
try:
return fetch(start, end)
except Exception:
if start == end:
raise # a single block is still too large; give up loudly
mid = (start + end) // 2
return (fetch_range(fetch, start, mid, max_span)
+ fetch_range(fetch, mid + 1, end, max_span))
calls = []
def fake_fetch(a, b):
calls.append((a, b))
if b - a > 3:
raise RuntimeError("range too large")
return [{"blockNumber": n} for n in range(a, b + 1)]
logs = fetch_range(fake_fetch, 100, 109)
print(len(logs), "logs from", len(calls), "calls")Decoding a Transfer log
A decoder must check the log's shape before trusting it. The function below checks the event hash and the topic count, converts the amount using the token's decimals, and returns None for logs that are not ERC-20 transfers. It then builds a sample log in code so you can run it as shown.
TRANSFER_TOPIC = (
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
)
ZERO_ADDRESS = "0x" + "0" * 40
def topic_to_address(topic):
"""Take the low 20 bytes of a 32-byte topic."""
return "0x" + topic[-40:].lower()
def decode_transfer(log, decimals):
topics = log["topics"]
if len(topics) != 3 or topics[0].lower() != TRANSFER_TOPIC:
return None # other event, or an ERC-721 Transfer (4 topics)
raw = int(log["data"], 16)
return {
"token": log["address"].lower(),
"from": topic_to_address(topics[1]),
"to": topic_to_address(topics[2]),
"amount": raw / 10 ** decimals,
"block": int(log["blockNumber"], 16),
"log_index": int(log["logIndex"], 16),
"tx": log["transactionHash"],
}
def pad_address(addr):
return "0x" + "0" * 24 + addr[2:]
sample = {
"address": "0x" + "ab" * 20,
"topics": [
TRANSFER_TOPIC,
pad_address("0x" + "11" * 20),
pad_address("0x" + "22" * 20),
],
"data": "0x" + format(120_000_000, "064x"), # 120 tokens, 6 decimals
"blockNumber": "0x10d4f03",
"logIndex": "0x2",
"transactionHash": "0x" + "cd" * 32,
}
print(decode_transfer(sample, decimals=6))The printed amount is 120.0. The raw integer in the log is 120000000. Tokens report their precision through a decimals() call. USDT and USDC use 6, and many tokens use 18. Dividing by the wrong power of ten is a common silent error that makes flows off by orders of magnitude.
Cases that break a naive count
The output of decode_transfer feeds the netflow code from the exchange flow chapter. First handle these cases.
- ERC-721 collisions. NFT contracts emit a Transfer event with the same signature hash, but all three arguments are indexed. The log has four topics and empty
data. The topic-count check in the decoder rejects these. - Mints and burns. A mint is a transfer from the zero address, and a burn is a transfer to it. These change supply but are not user-to-user movement. Filter or tag them separately.
- Reorgs. Recent blocks can be replaced. A log with
removed: truemust be discarded. Most pipelines also wait for a confirmation depth, or store a block hash and re-check it, before treating data as final. - Native coin movements. Plain ETH transfers emit no log. Contract-to-contract ETH moves appear only in traces ("internal transactions"). Logs cover tokens only.
- Wrapped tokens. WETH deposits and withdrawals emit their own
DepositandWithdrawalevents and also a Transfer. Check which events a given contract emits. - Unusual token designs. Fee-on-transfer tokens deliver less than the stated amount. Rebasing tokens change balances without any Transfer event. Non-standard tokens may skip the event entirely. For these, a Transfer sum will not match balances.
- Intermediate hops. A swap through a router produces several Transfer logs in one transaction. Summing all of them counts one economic movement more than once.
Adding time and labels
A log gives you a block number but no timestamp. To group by day, look up each block's timestamp once with eth_getBlockByNumber and cache it by block number. Many logs share a block, so caching saves most of the calls.
Keep log_index and tx with each row. Sorting by (block, log_index) gives the exact order of events, and (tx, log_index) serves as a unique key. Use that key when you load data so that re-running a range does not create duplicate rows.
Once rows carry a day, convert them to the {"day", "from", "to", "amount"} shape that exchange_netflow expects. Then attach labels from your labeling source. Keep the token in each row too, because adding amounts of different tokens is meaningless. Compute netflow per token, or convert to a common unit with a price at the time of the transfer.
Alternatives to raw logs
You can query logs from your own node, from a hosted node provider, or from an indexed dataset. Raw eth_getLogs gives you the most control and the fewest assumptions. Indexed services and analytics APIs already decode and label transfers, and you pay for that convenience by trusting their decoding rules. Whichever you use, spot-check a few transactions against a block explorer before relying on totals.
Exercise
A log has topics[0] equal to the ERC-20 Transfer hash, four topics in total, and an empty data field. Is it an ERC-20 transfer, and how does your decoder handle it?
Show answer
No. ERC-20 Transfer logs have three topics and the amount in data. A log with four topics and empty data is an ERC-721 (NFT) Transfer, where the token ID is the fourth topic. The decoder's check len(topics) != 3 makes it return None, so the log is skipped.
Exercise
A token has 18 decimals. A decoded log has data equal to 0x00000000000000000000000000000000000000000000000ad78ebc5ac6200000. That is 200 × 10^18 as an integer. What amount should you record, and what happens if you wrongly assume 6 decimals?
Show answer
Record 200.0 tokens (raw divided by 10^18). Assuming 6 decimals divides by 10^6 instead, giving 200 × 10^12 tokens, which is a trillion-fold overstatement and would trigger every whale alert.
Exercise
A swap transaction produces three Transfer logs: user to pool (token A), pool to router (token B), and router to user (token B). If you count every log as a separate flow, what goes wrong, and what can you do about it?
Show answer
One economic action is counted as several movements, and intermediate hops through the pool and router are counted as flows even though no end holder changed. Group logs by transaction hash, drop or tag transfers whose endpoints are known contracts (pools, routers), and label those addresses so only transfers touching real exchange or holder addresses count.