Difference between abi.encode, abi.encodePacked, abi.encodeWithSignature and encodeWithSelector
A guide to the two types of encoding on the ABI object
Table of Contents for Difference between abi.encode, abi.encodePacked, abi.encodeWithSignature and encodeWithSelector
There are a few ways to serialise arguments when calling other smart contracts.
You will often see use of abi.encode()
, abi.encodepacked()
, abi.encodePacked()
, abi.encodeWithSelector()
.
You can use them like this:
(success, result) = address(someDeployedContract)
.call(abi.encodeWithSignature("foo(string)", "hello, world"));
You can also ‘manually’ calculate the call argument with something like this:
(success, result) = address(someDeployedContract)
.call(bytes4(keccak256("foo(string)")), "hello, world");
abi.encode()
Encodes the params according to the ABI specs. Params are padded out to 32 bytes.
abi.encodePacked()
Encodes the params using the minimal amount of space.
There will be no padding for static types, if they’re smaller than 32 bytes. Dynamic types are encoded without the length. Encoding for example a uint8
will use 1 byte. You would use this when saving space, not when calling another contract.
abi.encodeWithSignature()
When you already have a function signature (e.g. bytes4(keccak256("foo(string)"))
) then you can use encodeWithSignature()
to encode the params
abi.encodeWithSelector()
Very similar to encodeWithSignature.
These two are equivalent
abi.encodeWithSelector(bytes4(keccak256(signature), ...)
abi.encodeWithSignature(string signature, ...)
You can get the selector of a function) by adding .selector
to it:
// assumes someContract is typed as a contract that has `foo` as a function
(e.g. `foo(uint256)`)
bytes4 selector = someContract.foo.selector;
Spotted a typo or have a suggestion to make this crypto dev article better? Please let me know!
Next post
Previous post
📙 Solidity Auditing online quiz
Learn how to audit smart contracts by looking at some example code and trying to find the bugs
⛽ Solidity Gas Optimizations Guide
How to optimize and reduce gas usage in your smart contracts in Solidity
🧪 Guide to testing with Foundry
Guide to adding testing for your Solidity contracts, using the Foundry and Forge tools
📌 Guide to UTXO
UTXO and the UTXO set (used by blockchains such as Bitcoin) explained
📐 Solidity Assembly Guide
Introduction guide to using assembly in your Solidity smart contracts
📦 Ethereum EOF format explained
Information explaining what the upcoming Ethereum EOF format is all about