solidity - get return value of delegatecall with assembly

2.1k views Asked by At

I have a contract A and a contract B.

Contract A declares this function:

function getIntValue() constant returns (uint);

What would be the appropriate assembly code to delegatecall contract A's getIntValue function from B? I'm not yet very experienced with assembly so I only have this so far which doesn't work:

function getContractAIntValue() constant returns (uint c) {
    address addr = address(contractA); // contract A is stored in B.
    bytes4 sig = bytes4(sha3("getIntValue()")); // function signature

    assembly {
        let x := mload(0x40) // find empty storage location using "free memory pointer"
        mstore(x,sig) // attach function signature
        let status := delegatecall(sub(gas, 10000), addr, add(x, 0x04), 0, x, 0x20)
        jumpi(invalidJumpLabel, iszero(status)) // error out if unsuccessful delegatecall
        c := mload(x)
    }
}
1

There are 1 answers

0
imazzara On

Maybe you have solved it cause was asked more than one year ago, but in case some is still looking for it...

address addr = address(contractA); // contract A is stored in B.
bytes memory sig = abi.encodeWithSignature("getIntValue()"); // function signature

// solium-disable-next-line security/no-inline-assembly
assembly {
  let result := delegatecall(sub(gas, 10000), addr, add(sig, 0x20), mload(sig), 0, 0)

  let size := returndatasize

  let ptr := mload(0x40)
  returndatacopy(ptr, 0, size)

  // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
  // if the call returned error data, forward it
  switch result case 0 { revert(ptr, size) }
  default { return(ptr, size) }
}