0

I have a contract with 2 tightly packed values in storage slot1, how do I return the second address value with assembly?

Contract MyContract{
  bool a;
  address b;
  
  function getAddress() public returns (address){
    assembly {
      mstore(mload(0x40), sload(1))
      return(0x40, 32)    
    }
  }
}

as this will return the packed value of both a+b

1 Answer 1

1

suppose the values are similar to follows

  bool a = true;
  address b=0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;

then the slot 0 value would be

>> 0x00000000000000000000005b38da6a701c568545dcfcb03fcb875f56beddc401

Right most digit would be the bool value.

To extract the address,

  1. load the slot 0
  2. extract only the address and shifting right
contract MyContract{
  bool a = true;
  address b=0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;
  
  function getAddress() public view returns (address){
    assembly {
        mstore(0x40, shr(8, and(sload(0),0x00000000000000000000ffffffffffffffffffffffffffffffffffffffffff00)))
       return(0x40, 0x60)    
    }
  }

}

and operation zero out the bool and possible other values gives a result as follows

>> 0x00000000000000000000005b38da6a701c568545dcfcb03fcb875f56beddc400

Then 8 bits are shifted right to get the result as follows

>> 0x0000000000000000000000005b38da6a701c568545dcfcb03fcb875f56beddc4
2
  • perfect, thanks for your answer, i think when you say shift right 8 bytes, you actually mean bits right? Jan 20 at 6:53
  • sorry, yes and corrected it Jan 20 at 8:33

Your Answer

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

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