Skip to main content

Understanding and verifying Ethereum transaction calldata

Updated 11 min readMarkdown

The Radiant Capital hack, which resulted in a loss of approximately $50 million, shows the importance of verifying calldata before signing transactions. In this sophisticated attack, hackers compromised developers' hardware wallets and injected malware that manipulated transaction data at the device level.

By verifying calldata before signing, users can catch discrepancies between what their wallet interface shows and what the actual transaction will do. This extra step can prevent unauthorized actions, such as approving large token amounts or interacting with malicious contracts.

This guide will explain the importance of this practice and provide both simple and technical methods to decode and verify calldata.

Now, let's understand the technical components. If you want to go straight to the easier section where I list a widely used tool you can use to verify the calldata of your transaction before you sign it, head to the Table of contents and go to the “Quickly verify your transaction with this tool” section.

Otherwise, let's continue with the fundamentals.

What is calldata?

Calldata refers to a specific area of memory used to store data that is sent to a smart contract during a transaction. This data typically includes the arguments for functions that are being called externally.

Hex data

This refers to data represented in hexadecimal format. Each byte of data is represented by two hexadecimal characters. For example, a string of hex digits can represent the encoded calldata sent to a smart contract.

While calldata is the actual data sent to a smart contract, hex data is simply a way of representing that data in a human-readable format. Calldata can be expressed as hex data, but they are not interchangeable terms.

Ethereum calldata can contain two types of data:

Static data: Fixed-length types that always use the same amount of bytes.

Examples:

  • address (20 bytes)

  • uint256 (32 bytes)

  • bool (1 byte)

  • bytes32 (32 bytes)

Dynamic data: Variable-length types that can use different amounts of bytes.

Examples:

  • bytes

  • arrays (int[], etc.)

In our following example, we're dealing with static data: an address (20 bytes) and a uint256 (32 bytes).

Consider this:

0x095ea7b3000000000000000000000000def1c0ded9bec7f1a1670819833240f027b25eff0000000000000000000000000000000000000000000000000000000000989680 is an example of calldata represented in hexadecimal format.

Hexadecimal format: The prefix 0x indicates that the following string is in hexadecimal format.

The provided string is both calldata (the actual data being sent to a smart contract) and hex data (the representation of that data in hexadecimal format).

Let’s break down the hex data:

  1. Function selector: The first 4 bytes (8 hexadecimal characters) after '0x' represent the function selector. In this case, it's 095ea7b3 (approve function). This selector is derived from the Keccak-256 hash of the function signature.

  2. Parameters

The remaining data is divided into 32-byte (64 hexadecimal character) chunks, each representing a parameter:

  • 000000000000000000000000def1c0ded9bec7f1a1670819833240f027b25eff

This is the address parameter, padded to 32 bytes. The actual address is the last 20 bytes: def1c0ded9bec7f1a1670819833240f027b25eff.

  • 0000000000000000000000000000000000000000000000000000000000989680

This is the uint256 parameter, representing the amount (989680). In decimal, this is 10000000.

This confirms that:

  • You're calling the approve function.

  • You're approving the address def1c0ded9bec7f1a1670819833240f027b25ef to spend your tokens.

  • The amount you're approving is 10000000 (note: depending on the token's decimals, this might represent a different "human-readable" amount). In this specific case, this transaction example intends to transfer 10 USDC, and USDC has 6 decimals, so this amount represents 10000000 / 10^6 = 10 USDC.

Verifying function selectors

To verify that 095ea7b3 is indeed the function selector for approve(address,uint256), you can use one of these methods:

  1. Using an online Keccak-256 online tool:

a) Input the function signature "approve(address,uint256)"

b) Take the first 4 bytes of the resulting hash

c) Verify it matches 095ea7b3

  1. Using a simple Python script:
from eth_hash.auto import keccak

def get_function_selector(function_signature):
    return keccak(function_signature.encode('utf-8')).hex()[:8]

function_signature = "approve(address,uint256)"
selector = get_function_selector(function_signature)
print(f"Function selector for '{function_signature}': 0x{selector}")

To use this script, you'll need to install the eth-hash library. You can do this with pip:

pip install eth-hash[pycryptodome]

This script will return 0x095ea7b3 as the function selector for "approve(address,uint256)". The eth-hash library provides the Ethereum-specific Keccak-256 implementation, which we need to calculate function selectors in Ethereum.

How to verify calldata before signing

Before learning how to verify transaction data, it's essential to understand the security implications revealed by the Radiant Capital hack.

The hack demonstrated how sophisticated malware can compromise devices and manipulate what users see in web interfaces. This creates a fundamental challenge: it's difficult to verify the "real" transaction data if your device is compromised.

Best security practices:

1. Hardware wallet verification:

  • Use a hardware wallet that displays full transaction details.

  • Carefully verify all data shown on the hardware wallet's physical screen.

  • Don't rely solely on what you see in web interfaces.

2. Multiple device verification:

  • Use a separate, uncompromised device to initiate and verify transactions.

  • Compare transaction details across different devices.

  • Consider writing custom scripts (with libraries such as web3.py/web3.js) to generate expected transaction data independently, (see example below).

  • Compare this independently generated data with what your wallet UI shows.

3. Dedicated device security:

If you manage a protocol or handle large amounts of funds, maintain a dedicated device ONLY for transaction signing.

This device should:

  • Never be used for general browsing or other activities

  • Be kept offline when not in use

  • Have minimal software installed

  • Be regularly checked for security updates

4. Warning signs:

  • Repeated transaction failures.

  • Unusual error messages.

  • Discrepancies between different interfaces or generated data.

If you encounter any suspicious behavior, stop the transaction process immediately.

Now that we understand the security considerations, let's look at how to verify your transaction data the easy way:

  1. When your wallet prompts you to sign a transaction, look for an option to view the raw transaction data or hex data. The example below shows the wallet pop-up for a 10 USDC transaction at DeFiLlama Swap.

  1. Copy this hex data and paste it into the tool mentioned next.

  2. Verify that the decoded function and parameters match what you intended to do.

  3. If anything looks suspicious or doesn't match your expectations, do not sign the transaction.

Quickly verify your transaction with this tool:

  1. Etherscan Input Data Decoder:

This tool allows you to paste the input data from a transaction and automatically decode it into a human-readable format. It breaks down the function being called and its parameters.

Before proceeding, you should verify:

  • Is this the correct function you intended to call? You’re about to approve the transaction.

  • Do you recognize and trust the address you're approving? This address will spend your tokens.

  • Is the amount correct? Check if you’re actually about to send the amount you intended to transfer. (Note: depending on the token's decimals, this might represent a different "human-readable" amount). The amount parameter is the last 64 characters: 0000000000000000000000000000000000000000000000000000000000989680. This hexadecimal value of 989680 is the amount that is converted to 10000000 in decimals, which represents 10 USDC when accounting for the 6 decimal places of the token.

Remember: In cases of sophisticated malware, even the hex data shown in your wallet UI might be compromised. Using independent verification methods, like the Python/SQL script shown later in this guide, can help verify the transaction data your wallet is showing you is correct.

Additional tools:

Simply copy and paste the address parameter of your hex data there, and it will return all the records Etherscan can find.

  • Etherscan Contract Diff Checker:

  • Compares different versions of contracts.

  • Helpful for identifying potential scam contracts.

  • Can compare against known legitimate contracts.

In the image provided, I compared the USDC and USDT token contracts. Both are the official ones, this is just an example of how this tool can quickly compare two contracts.

Programmatic approaches to decode calldata

For developers and analysts (or maybe, a non-technical user) who want to decode calldata, here are several simple approaches using SQL and Python.

Viewing transaction data with Python

For developers who want to verify transaction data before signing, here's a simple Python script that constructs the same approval transaction your wallet would create:

First, install the required packages:

pip install web3 eth-abi

Here's the script to generate and view the transaction data:

from web3 import Web3
from eth_abi import encode

# Connect to Ethereum network
w3 = Web3(Web3.HTTPProvider('YOUR_NODE_URL'))

# Contract addresses - convert to checksum format
USDC_ADDRESS = Web3.to_checksum_address('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48')
DEFILLAMA_ROUTER = Web3.to_checksum_address('0xDEF1C0DED9bec7F1a1670819833240f027b25EfF')

# Create transaction
def create_approve_transaction(amount):
    # Create contract instance with minimal ABI (only the approve function)
    abi = [{
        "constant": False,
        "inputs": [
            {"name": "spender", "type": "address"},
            {"name": "value", "type": "uint256"}
        ],
        "name": "approve",
        "outputs": [{"name": "", "type": "bool"}],
        "payable": False,
        "stateMutability": "nonpayable",
        "type": "function"
    }]

    contract = w3.eth.contract(address=USDC_ADDRESS, abi=abi)

    # Create transaction data
    transaction = contract.functions.approve(
        DEFILLAMA_ROUTER,
        amount  # For 10 USDC: 10 * 10**6
    ).build_transaction({
        'from': Web3.to_checksum_address('YOUR_WALLET_ADDRESS'),
        'nonce': w3.eth.get_transaction_count(Web3.to_checksum_address('YOUR_WALLET_ADDRESS')),
        'gas': 100000, # example estimated gas limit
        'gasPrice': w3.eth.gas_price
    })

    # Print transaction data
    print(f"Transaction Data (hex):")
    print(transaction['data'])
    return transaction


amount = 10 * 10**6  # 10 USDC
tx = create_approve_transaction(amount)

How this script works:

  1. The script connects to the Ethereum network using Web3.py and your chosen provider (like Infura).

  2. Creates an ABI (Application Binary Interface) for the approve function.

  3. Constructs the same transaction your wallet would create.

  4. Shows you the raw transaction calldata before it's sent.

The script returns the hex data in the same format we've been examining because it:

  • Uses the same function selector (0x095ea7b3 for 'approve').

  • Encodes the parameters (address and amount) in the same way.

  • Follows the same EVM (Ethereum Virtual Machine) standards for transaction construction.

Output:

Transaction data (hex):

0x095ea7b3000000000000000000000000def1c0ded9bec7f1a1670819833240f027b25eff0000000000000000000000000000000000000000000000000000000000989680

This output matches our example transaction data, showing:

  • The approve function selector.

  • The DeFiLlama router address as the spender.

  • The amount of 10000000 (10 USDC accounting for 6 decimals).

This method is particularly useful for:

  • Developers building DeFi applications.

  • Users who want to verify transactions.

  • Security researchers analyzing transaction patterns.

Decoding with SQL

Using Flipside, you can decode calldata:

-- Replace {{hex}} with your transaction's hex data
-- Replace {{decimals}} with your token's decimal places (e.g., 6 for USDC, 18 for most ERC20 tokens)
WITH HexData AS (
  SELECT 
    '{{hex}}' AS data
),
DecodedData AS (
  SELECT 
    data,
    SUBSTR(data, 1, 10) AS function_selector, -- Extract first 10 characters (0x + 4 bytes) as function selector
    regexp_substr_all(SUBSTR(data, 11), '.{64}') AS segmented_data
  FROM HexData -- Split remaining data into 64-character (32 byte) segments
)
SELECT 
  data AS original_hex_data, -- Original raw transaction data 
  function_selector, -- Extracted function selector (0x095ea7b3 for 'approve')  
 '0x' || SUBSTR(segmented_data[0], 25) AS approved_address, -- Extract last 20 bytes of first parameter as Ethereum address         livequery.utils.udf_hex_to_int(segmented_data[1]) AS raw_amount, -- Convert second parameter from hex to integer
  livequery.utils.udf_hex_to_int(segmented_data[1]) / POWER(10, {{decimals}}) AS amount -- Convert raw amount to USDC (6 decimal places)
FROM DecodedData;

This query breaks down the calldata, extracting the function selector and parameters. It also converts the amount to a human-readable format.

Find that query and dashboard here.

Decoding with Python

Here are two approaches: a specific decoder for approve functions and a general decoder that can handle multiple function types.

  1. Specific approve function decoder

This script is optimized for decoding approve function calldata:

from eth_hash.auto import keccak
from eth_abi import abi
from eth_utils import to_checksum_address

def decode_approve_calldata(hex_data):
    # Remove '0x' prefix if present
    hex_data = hex_data[2:] if hex_data.startswith('0x') else hex_data

    # Extract function selector and parameters
    function_selector = hex_data[:8]
    params_hex = hex_data[8:]

    # Decode parameters (assuming approve function)
    decoded_params = abi.decode(['address', 'uint256'], bytes.fromhex(params_hex))

    return {
        'function_selector': '0x' + function_selector,
        'approved_address': to_checksum_address(decoded_params[0]),
        'amount_raw': decoded_params[1],
        'amount_usdc': decoded_params[1] / 10**6
    }

# same example 
calldata = "0x095ea7b3000000000000000000000000def1c0ded9bec7f1a1670819833240f027b25eff0000000000000000000000000000000000000000000000000000000000989680"
result = decode_approve_calldata(calldata)
print(f"Function selector: {result['function_selector']}")
print(f"Approved address: {result['approved_address']}")
print(f"Amount (raw): {result['amount_raw']}")
print(f"Amount (USDC): {result['amount_usdc']}")

This script will output:

Function selector: 0x095ea7b3

Approved address: 0xDEF1C0DED9bec7F1a1670819833240f027b25EfF

Amount (raw): 10000000

Amount (USDC): 10.0

  1. General purpose decoder

This more versatile script can handle multiple function types, including approve, transfer, and transferFrom (keep in mind there are more functions than these ones, feel free to tweak it for your specific needs):

from eth_hash.auto import keccak
from eth_abi import abi
from eth_utils import to_checksum_address

def decode_calldata(hex_data, param_types):
    hex_data = hex_data[2:] if hex_data.startswith('0x') else hex_data
    function_selector = hex_data[:8]
    params_hex = hex_data[8:]
    decoded_params = abi.decode(param_types, bytes.fromhex(params_hex))
    return function_selector, decoded_params

def get_function_selector(function_signature):
    return keccak(function_signature.encode('utf-8')).hex()[:8]

# Example usage with multiple function types
calldata_examples = [
    ("0x095ea7b3000000000000000000000000def1c0ded9bec7f1a1670819833240f027b25eff0000000000000000000000000000000000000000000000000000000000989680",
     "approve(address,uint256)"),
    ("0xa9059cbb000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa96045000000000000000000000000000000000000000000000000000000e8d4a51000",
     "transfer(address,uint256)"),
    ("0x23b872dd000000000000000000000000b4e16d0168e52d35cacd2c6185b44281ec28c9dc0000000000000000000000008858eeb3dfffa017d4bce9801d340d36cf895ccf0000000000000000000000000000000000000000000000000de0b6b3a7640000",
     "transferFrom(address,address,uint256)")
]

for calldata, function_signature in calldata_examples:
    print(f"\nDecoding: {function_signature}")

    # Get function selector
    expected_selector = get_function_selector(function_signature)
    print(f"Expected function selector: 0x{expected_selector}")

    # Extract parameter types from function signature
    param_types = function_signature[function_signature.index('(') + 1:-1].split(',')

    # Decode calldata
    selector, params = decode_calldata(calldata, param_types)

    print(f"Actual function selector: 0x{selector}")
    print("Decoded parameters:")
    if function_signature.startswith("transferFrom"):
        print(f"  from_address: {to_checksum_address(params[0])}")
        print(f"  to_address: {to_checksum_address(params[1])}")
        print(f"  amount: {params[2]}")
    else:
        for i, (param_type, param) in enumerate(zip(param_types, params)):
            if param_type == 'address':
                print(f"  {param_type}: {to_checksum_address(param)}")
            else:
                print(f"  {param_type}: {param}")

This script will output:

Decoding: approve(address,uint256)

Expected function selector: 0x095ea7b3

Actual function selector: 0x095ea7b3

Decoded parameters:

address: 0xDEF1C0DED9bec7F1a1670819833240f027b25EfF

uint256: 10000000

Decoding: transfer(address,uint256)

Expected function selector: 0xa9059cbb

Actual function selector: 0xa9059cbb

Decoded parameters:

address: 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045

uint256: 1000000000000

Decoding: transferFrom(address,address,uint256)

Expected function selector: 0x23b872dd

Actual function selector: 0x23b872dd

Decoded parameters:

from_address: 0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc

to_address: 0x8858eeB3DfffA017D4BCE9801D340D36Cf895CCf

amount: 1000000000000000000

To use either Python script, you'll need to install these libraries:

pip install eth-abi eth-hash[pycryptodome] eth-utils

Remember: Verifying calldata before signing transactions is recommended, especially for high-value operations or when interacting with new contracts. The few seconds spent verifying could save you from significant losses.

Best practices:

1. Always check the function being called.

2. Verify addresses against known contracts.

3. Double-check amounts, accounting for token decimals.

4. Use multiple verification methods for high-value transactions.

5. When in doubt, don't sign.

By following these practices and using the tools and code provided in this guide, you can better protect yourself against transaction manipulation and other smart contract-related risks.

No comments yet. Be the first to comment.