Created
May 4, 2025 18:02
-
-
Save 333cipher/7584dadae3bc217e208aa262ebc677d3 to your computer and use it in GitHub Desktop.
Decoding ERC20 Approval Transactions Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from eth_abi import decode | |
from eth_utils import to_checksum_address | |
def decode_erc20_approve(calldata: str, token_decimals: int = 18) -> dict: | |
""" | |
Decode ERC-20 approve calldata with human-readable output | |
Parameters: | |
- calldata: The hex calldata string | |
- token_decimals: Number of decimals for the token (default: 18) | |
Returns: Dictionary with decoded information | |
""" | |
# Remove '0x' prefix if present | |
hex_data = calldata[2:] if calldata.startswith("0x") else calldata | |
# Extract function selector and parameters | |
selector = hex_data[:8] | |
params_hex = hex_data[8:] | |
# Decode parameters using eth_abi.decode (equivalent to decode_abi in earlier versions) | |
# Note: We're explicitly using decode as the ABI decoder function | |
spender, amount = decode(["address", "uint256"], bytes.fromhex(params_hex)) | |
# Convert to human-readable format | |
spender_address = to_checksum_address(spender) | |
amount_raw = amount | |
amount_normalized = amount / (10 ** token_decimals) | |
return { | |
"function": "approve(address,uint256)", | |
"selector": f"0x{selector}", | |
"spender": spender_address, | |
"amount_raw": amount_raw, | |
"amount_normalized": amount_normalized, | |
"token_decimals": token_decimals | |
} | |
# Example usage | |
calldata = "0x095ea7b30000000000000000000000006a000f20005980200259b80c510200304000106800000000000000000000000000000000000000000000000000000000017d7840" | |
result = decode_erc20_approve(calldata, token_decimals=6) # USDC has 6 decimals | |
print("Calldata Breakdown:") | |
print(f"Function: {result['function']}") | |
print(f"Function Selector: {result['selector']}") | |
print(f"Spender Address: {result['spender']}") | |
print(f"Raw Amount: {result['amount_raw']}") | |
print(f"Normalized Amount: {result['amount_normalized']} USDC") | |
print(f"\nSummary: Approving {result['amount_normalized']} USDC to {result['spender']}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment