TExcelTAD
Home › Solidity › ABI Encoding & keccak256

ABI Encoding & keccak256

Everything that crosses a contract boundary (function arguments, return values, events, errors) is encoded with the Contract ABI (Application Binary Interface). Solidity exposes the encoder through the global abi object, and the hash function keccak256 turns any bytes into a 32-byte fingerprint. Together they're used for signatures, unique ids, commitments and low-level calls.

Function selectors

A call's data starts with a 4-byte selector: the first four bytes of keccak256 of the function's signature, with no spaces and no parameter names. The arguments follow, each padded to 32 bytes.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

interface IToken {
    function transfer(address to, uint256 amount) external returns (bool);
}

contract Main {
    function main() external pure {
        bytes4 manual = bytes4(keccak256("transfer(address,uint256)"));
        bytes4 builtin = IToken.transfer.selector;
        console.logBytes4(manual);
        console.log("same selector?", manual == builtin);

        bytes memory callData = abi.encodeCall(IToken.transfer, (address(0xBEEF), 1000));
        console.log("call data length:", callData.length);   // 4 + 32 + 32
        console.logBytes(callData);
    }
}
0xa9059cbb
same selector? true
call data length: 68
0xa9059cbb000000000000000000000000000000000000000000000000000000000000beef00000000000000000000000000000000000000000000000000000000000003e8

0xa9059cbb is the famous ERC-20 transfer selector you'll see in every block explorer.

The encoding functions

Function Output
abi.encode(a, b, …) standard ABI encoding: every value padded to 32 bytes
abi.encodePacked(a, b, …) compact: values concatenated with minimal size, no padding for dynamic types
abi.encodeWithSelector(sel, a, …) selector + abi.encode(a, …)
abi.encodeWithSignature("f(uint256)", a) same, selector computed from a string
abi.encodeCall(C.f, (a, …)) same, type-checked against C.f
abi.decode(data, (T1, T2)) the reverse of abi.encode
solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    function main() external pure {
        uint16 small = 0x1234;
        address who = address(0xABCD);

        bytes memory standard = abi.encode(small, who);
        bytes memory packed = abi.encodePacked(small, who);
        console.log("abi.encode length      :", standard.length);
        console.log("abi.encodePacked length:", packed.length);
        console.logBytes(packed);

        (uint16 s, address w) = abi.decode(standard, (uint16, address));
        console.log("decoded:", s, w);
    }
}
abi.encode length      : 64
abi.encodePacked length: 22
0x1234000000000000000000000000000000000000abcd
decoded: 4660 0x000000000000000000000000000000000000ABcD

abi.encode gives 64 bytes (two 32-byte words); abi.encodePacked gives 22 (2 bytes + 20 bytes).

Hashing with keccak256

keccak256(bytes) returns a bytes32. Combined with abi.encode, it creates unique ids from several values, for example an order id from its fields:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    function orderId(address buyer, uint256 itemId, uint256 nonce) internal pure returns (bytes32) {
        return keccak256(abi.encode(buyer, itemId, nonce));
    }

    function main() external pure {
        address buyer = address(0xB0B);
        bytes32 a = orderId(buyer, 7, 1);
        bytes32 b = orderId(buyer, 7, 2);
        console.logBytes32(a);
        console.logBytes32(b);
        console.log("same inputs, same hash?", a == orderId(buyer, 7, 1));
    }
}
0xa3b5da11326af08387505795c0514e208faa4b956c614c360b2bec9fa297edea
0xb0e94afab2d4e4f4f7d3829f4e45c9e6e3381c692ca3c5c425d4e45553d54696
same inputs, same hash? true

The encodePacked collision trap

abi.encodePacked with two or more dynamic values (strings, bytes, arrays) is ambiguous, because the boundary between them is lost. Different inputs can then produce the same hash:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    function main() external pure {
        bytes32 h1 = keccak256(abi.encodePacked("ab", "c"));
        bytes32 h2 = keccak256(abi.encodePacked("a", "bc"));
        console.log("packed: same hash for (ab,c) and (a,bc)?", h1 == h2);

        bytes32 e1 = keccak256(abi.encode("ab", "c"));
        bytes32 e2 = keccak256(abi.encode("a", "bc"));
        console.log("encode: same hash?", e1 == e2);
    }
}
packed: same hash for (ab,c) and (a,bc)? true
encode: same hash? false

If a hash is used for authorization (a signed permission, a unique claim), an attacker could exploit such a collision. Use abi.encode for hashing multiple values, or make sure at most one value is dynamic.

Commit-reveal

Hashes let users commit to a value without revealing it, then reveal later. That is the basis of fair sealed-bid auctions and games, since everything on chain is public:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    mapping(address => bytes32) public commitments;

    function commit(address player, bytes32 hash) internal {
        commitments[player] = hash;
    }

    function reveal(address player, string memory choice, bytes32 secret) internal view returns (bool) {
        return keccak256(abi.encode(choice, secret)) == commitments[player];
    }

    function main() external {
        address ann = address(0xA22);
        bytes32 secret = keccak256("ann's private salt");
        commit(ann, keccak256(abi.encode("rock", secret)));   // phase 1: only the hash is public

        console.log("reveal 'paper':", reveal(ann, "paper", secret));
        console.log("reveal 'rock' :", reveal(ann, "rock", secret));
    }
}
reveal 'paper': false
reveal 'rock' : true

The secret salt matters: without it, anyone could hash "rock", "paper" and "scissors" and compare.

Test yourself

How is a function selector computed?

  1. sha256 of the function name
  2. First 4 bytes of keccak256 of the signature, e.g. transfer(address,uint256)
  3. The function's index in the contract
  4. keccak256 of the full ABI JSON

Why can keccak256(abi.encodePacked(a, b)) be unsafe for two strings?

  1. It's too slow
  2. Different pairs of strings can produce the same packed bytes
  3. It reverts for long strings
  4. It only hashes the first string

How many bytes does abi.encode(uint8(1), true) produce?

  1. 2
  2. 33
  3. 64
  4. 4