Developing a transaction decoder (human-readable)
A user confirms a transaction in MetaMask, sees the data: 0xa9059cbb000000000000000000000000... field — and clicks "Confirm" because they trust the dApp. This is a problem throughout Web3 UX. A proper decoder shows: "Transfer 100 USDC to 0xABC...". Wallet Guard, Rabby Wallet, WalletConnect — they've all already solved this. The task: embed similar functionality in your dApp or tool.
Anatomy of transaction data
EVM calldata has a fixed structure:
0xa9059cbb ← function selector (4 bytes)
000000000000000000000000742d35cc6634c0532925a3b8d2985e2b0e6d38e ← address (32 bytes)
00000000000000000000000000000000000000000000152d02c7e14af6800000 ← uint256 (32 bytes)
Function selector — the first 4 bytes of keccak256 of the function signature. keccak256("transfer(address,uint256)") → 0xa9059cbb. Database of selectors: 4byte.directory (7M+ signatures) — the foundation of decoding unknown contracts.
Decoding strategies
1. Decoding via ABI (known contract)
The most accurate option. ABI precisely describes parameter types and names:
import { decodeFunctionData, parseAbi } from "viem"
const erc20Abi = parseAbi([
"function transfer(address to, uint256 amount)",
"function approve(address spender, uint256 amount)",
"function transferFrom(address from, address to, uint256 amount)"
])
function decodeERC20Call(data: `0x${string}`) {
try {
const { functionName, args } = decodeFunctionData({ abi: erc20Abi, data })
return { functionName, args }
} catch {
return null
}
}
// Result: { functionName: "transfer", args: ["0xAddress", 100000000n] }
2. Decoding via 4byte.directory API
Unknown contract, no ABI — search by selector:
async function lookupSelector(selector: string): Promise<string[]> {
const response = await fetch(
`https://www.4byte.directory/api/v1/signatures/?hex_signature=${selector}`
)
const data = await response.json()
return data.results.map(r => r.text_signature)
// ["transfer(address,uint256)", "transfer(address,uint256)"]
// May have multiple matches (collisions)
}
async function decodeUnknownCalldata(data: `0x${string}`) {
const selector = data.slice(0, 10) // "0x" + 8 hex chars
const signatures = await lookupSelector(selector)
for (const sig of signatures) {
try {
const abi = parseAbi([`function ${sig}`])
const decoded = decodeFunctionData({ abi, data })
return { signature: sig, args: decoded.args }
} catch {
continue // try next variant on collision
}
}
return null
}
3. Etherscan API for verified contracts
Etherscan stores ABI of verified contracts:
async function fetchContractABI(contractAddress: string): Promise<any[] | null> {
const url = `https://api.etherscan.io/api?module=contract&action=getabi` +
`&address=${contractAddress}&apikey=${ETHERSCAN_KEY}`
const response = await fetch(url)
const data = await response.json()
if (data.status !== "1") return null
return JSON.parse(data.result)
}
Caching is essential: ABI doesn't change, TTL can be infinite.
4. Proxy contract resolution
Many contracts use proxy patterns (EIP-1967, EIP-1822, OpenZeppelin TransparentProxy). Proxy ABI is uninformative — you need to find the implementation:
import { createPublicClient, http } from "viem"
async function resolveImplementation(proxyAddress: `0x${string}`): Promise<`0x${string}` | null> {
const client = createPublicClient({ chain: mainnet, transport: http(RPC_URL) })
// EIP-1967: implementation slot
const EIP1967_SLOT = "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
const slotValue = await client.getStorageAt({
address: proxyAddress,
slot: EIP1967_SLOT
})
if (!slotValue || slotValue === "0x" + "0".repeat(64)) return null
// Take last 20 bytes (address)
return `0x${slotValue.slice(-40)}` as `0x${string}`
}
For complete resolution, check multiple slots (EIP-1967, EIP-1822, Gnosis Safe slot, custom).
Human-readable formatting
Decoding alone isn't enough — display understandably. Parameters like uint256 for ERC-20 need conversion considering decimals:
interface HumanReadableParam {
name: string
type: string
value: string // always string for display
rawValue: unknown
}
async function humanizeParam(
name: string,
type: string,
value: unknown
): Promise<HumanReadableParam> {
if (type === "address") {
const address = value as string
const ensName = await resolveENS(address) // 0xABC... → vitalik.eth
return {
name, type,
value: ensName || formatAddress(address), // "0x1234...5678"
rawValue: value
}
}
if (type === "uint256" && name.toLowerCase().includes("amount")) {
// Try to get decimals if token address is in neighboring parameters
return { name, type, value: formatBigInt(value as bigint), rawValue: value }
}
if (type === "bytes") {
const bytes = value as string
// Recursively decode if it's a nested call
const nested = await tryDecodeNested(bytes as `0x${string}`)
return { name, type, value: nested || bytes, rawValue: value }
}
return { name, type, value: String(value), rawValue: value }
}
ENS resolution is a key detail. 0x742d35Cc... → vitalik.eth dramatically changes readability.
Decoding event logs
Transaction logs are often as important as calldata:
import { decodeEventLog } from "viem"
async function decodeTransactionLogs(txHash: `0x${string}`) {
const receipt = await client.getTransactionReceipt({ hash: txHash })
const decodedLogs = await Promise.allSettled(
receipt.logs.map(async (log) => {
const abi = await fetchContractABI(log.address)
if (!abi) return { raw: log, decoded: null }
try {
const decoded = decodeEventLog({ abi, data: log.data, topics: log.topics })
return { raw: log, decoded }
} catch {
return { raw: log, decoded: null }
}
})
)
return decodedLogs
.filter(r => r.status === "fulfilled")
.map(r => (r as PromiseFulfilledResult<any>).value)
}
Visualizing call chains
For complex transactions (aggregator routes, batch calls), visualize the call trace. Alchemy and Tenderly provide APIs to get traces:
// Tenderly simulation + trace
const trace = await fetch("https://api.tenderly.co/api/v1/simulate", {
method: "POST",
headers: { "X-Access-Key": TENDERLY_KEY },
body: JSON.stringify({
network_id: "1",
from: senderAddress,
to: contractAddress,
input: calldata,
gas: 500000,
save: false
})
})
Result — a tree of calls with decoded functions at each level. Use for displaying multi-hop swaps, flash loan operations.
Decoder component
function TransactionDecoder({ txData, contractAddress }: {
txData: `0x${string}`
contractAddress: `0x${string}`
}) {
const { data, isLoading } = useDecodeTransaction(txData, contractAddress)
if (isLoading) return <Skeleton />
if (!data) return (
<div className="font-mono text-sm text-muted">
Unknown function: {txData.slice(0, 10)}
</div>
)
return (
<div className="space-y-2">
<div className="font-semibold">{data.functionName}</div>
{data.params.map(param => (
<div key={param.name} className="flex gap-2 text-sm">
<span className="text-muted">{param.name}:</span>
<span className="font-mono">{param.value}</span>
</div>
))}
</div>
)
}
Development timeline
Day 1: Core decoding — viem decodeFunctionData, 4byte.directory integration, Etherscan ABI fetcher with caching.
Day 2: Proxy resolution, ENS lookup, human-readable parameter formatting.
Day 3: Event logs decoding, basic React component for display.
Day 4-5: Call trace via Tenderly/Alchemy, multi-step transaction display, edge cases (multicall, batch operations).
Basic calldata + logs decoder — 3 days. Full tool with traces and rich formatting — 4-5 days.







