1

I'm trying to understand below code:

pragma solidity ^0.4.23;

contract Relay {
    address public currentVersion;
    address public owner;

    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }
    function Relay(address initAddr) {
        currentVersion = initAddr;
        owner = msg.sender; // this owner may be another contract with multisig, not a single contract owner
    }

    function changeContract(address newVersion) public onlyOwner(){
        currentVersion = newVersion;
    }

    function() {
        require(currentVersion.delegatecall(msg.data));
    }
}

This code is for maintaining version of a contract, but I'm not getting use of fallback function here.
I know that msg.data is complete calldata which is non-modifiable, but have no idea use of delegatecall here.

2

The fallback function gets called when no other function matches the calldata signature. In this code, the fallback functions is used as a universal function.

This is done by forwarding the calldata to the contract at currentVersion. Forwarding the calldata to another smart contract results in it running the proper funcion. There are two ways to do this: address.call and address.delegatecall. The difference between those is the context in which the receiving contract is going to run the code.

With delegatecall, the receiving contract accesses the Relay contract's storage. This way, the receiving contract can alter all fields of the Relay.

Effectively, by updating currentVersion, Relay can update it's code without changing it's address or migrating it's storage contents.

Docs:

  • Thanks! could you please explain what do you mean by Forwarding the calldata to another smart contract results in it running the proper funcion – Div Aug 9 '18 at 9:52
  • As currentVersion is not a contract right? it's a state variable – Div Aug 9 '18 at 9:55
  • 1
    That's correct, but it's an address that should be pointing to a smart contract, as external accounts can't be called – Henk Aug 9 '18 at 10:16
  • Okay, I understand it partially, I think in order to understand this code I would need to understand fallback function and delegateCall first. I'm having doubt regarding fallback. – Div Aug 9 '18 at 10:21
  • I've updated my answer with a couple of links to the documentation. Be sure to check them out – Henk Aug 9 '18 at 10:33

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.