4

What is the purpose of using Bitwise AND operator to get singleton address in the fallback function of GnosisSafeProxy.sol? Each bit of sload(0) , singleton address and 0xffff... are compared, although sload(0) would always return a value stored in storage slot 0 which should be singleton address.

 assembly {
    let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
  ・・・
 }

ref:https://github.com/safe-global/safe-contracts/blob/ee92957307653ae6cf7312bbcb1a13c6884ea6ea/contracts/proxies/GnosisSafeProxy.sol#L29

0

1 Answer 1

5

General objective of doing this and operation is to get extract the 20 bytes address with in a 32 bytes slot. There can be packed values with the address to clean up this is needed. The following example will give a good understanding.

pragma solidity >=0.7.0 <0.9.0;

import "./Gnosis.sol";

contract childProxy is GnosisSafeProxy {
    bool A = true;

    constructor(address singleton) GnosisSafeProxy(singleton){

    }

    function getSlotValue(uint256 slot) external view returns(bytes32 ret){
        assembly {
            ret := sload(slot)
        }
    }

}

deploying this contract with the address0x5B38Da6a701c568545dCfcB03FcB875f56beddC4 as the singleton address.

reading the slot 0 value

> 0x0000000000000000000000015b38da6a701c568545dcfcb03fcb875f56beddc4

In the output additional 1 is available with the address. The Boolean value is also packed with the slot 0 as an address only needs 20 bytes. To extract the address needed, bitwise and operation is used here.

Input

and(0x0000000000000000000000015b38da6a701c568545dcfcb03fcb875f56beddc4, 0xffffffffffffffffffffffffffffffffffffffff)

output

> 0x0000000000000000000000005b38da6a701c568545dcfcb03fcb875f56beddc4

EDIT

This same scenario can happen when delegating, if the logic contract has a value which is possible to be packed in the same given slot 1, using the and operation to clean up ensures the cleaned address retrieval.

1
  • Thanks for your answer! Interesting. Though, I wonder why you should be cautious about possible packed values in this case where the GnosisSafeProxy contract doesn't have any storage values declared before singleton. You know you wouldn't put anything that could cause trouble as a deployer, would you?
    – Porco
    Commented Jan 17, 2023 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.