Skip to content

Instantly share code, notes, and snippets.

@pcaversaccio
Last active April 21, 2023 22:57
Show Gist options
  • Save pcaversaccio/3200082995e813f3a1f59f1734417b06 to your computer and use it in GitHub Desktop.
Save pcaversaccio/3200082995e813f3a1f59f1734417b06 to your computer and use it in GitHub Desktop.
A Solidity snippet showing that `CODESIZE` returns the size of the called code (i.e. the implementation contract) when called via `DELEGATECALL`, rather than the size of the delegating contract.
// SPDX-License-Identifier: WTFPL
pragma solidity 0.8.19;
contract A {
/**
* @dev Returns 118 for contract `A`.
*/
function codesize() external pure returns (uint256 code) {
// solhint-disable-next-line no-inline-assembly
assembly {
code := codesize()
}
}
}
contract B {
/**
* @dev Returns 623 for contract `B`.
*/
function codesize() external pure returns (uint256 code) {
// solhint-disable-next-line no-inline-assembly
assembly {
code := codesize()
}
}
function delegatecallCodesize() public returns (uint256) {
A a = new A();
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returnData) = address(a).delegatecall(abi.encodeWithSelector(a.codesize.selector));
// `assert` is cooler than `require`, I'm sorry.
assert(success);
/**
* @dev Returns 181 (and NOT 623).
*/
return abi.decode(returnData, (uint256));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment