24

I'm trying to figure out how to use the delegatecall method on a contract address in a contract to call a function in a separate contract.

I know Libraries are the higher level interface to use but I want to understand the lower level actions and behaviors.

If someone could provide some good examples of a contract using delegatecall to another contract's functions, that would be greatly appreciated.

23

Here is a snippet of D using delegatecall on E from Difference between CALL, CALLCODE and DELEGATECALL

contract D {
  uint public n;
  address public sender;

  function delegatecallSetN(address _e, uint _n) {
    _e.delegatecall(bytes4(keccak256("setN(uint256)")), _n); // D's storage is set, E is not modified 
  }
}

contract E {
  uint public n;
  address public sender;
  function setN(uint _n) {
    n = _n;
    sender = msg.sender;
  }
}

When an address C invokes delegatecallSetN, D's sender will be set to C (E is not modified). Whatever msg.value is part of the invocation, will also be the value of msg.value inside setN.

You can quickly test above in Solidity Browser.

For libraries see the Solidity docs.

  • I was able to get it working though I could not get it working for strings or for bytes32 – aDude Aug 19 '16 at 19:38
  • I think it should work the same for bytes32. For string and bytes, I'm not sure and a separate question is probably needed. – eth Aug 20 '16 at 8:00
  • D.delcallCfunc(addressOfE, 10); is it the correct way to call it? Could addressOfE be a string? @eth – alper Mar 26 '17 at 15:24
  • 1
    @Avatar If you're using an example like the answer, the way your calling seems consistent, but addressOfE can't be a string since string doesn't have a delegatecall member. It's probably easier to stick to libraries instead of "plain" delegatecall. – eth Mar 31 '17 at 9:42
  • Does this work with enums ? – Kaki Master Of Time Mar 5 '18 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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