2

Inside view method it's not possible to do delegatecall due to compilation errors. Is there any way to delegate view calls?

2

Yep, but it is tricky:

pragma solidity ^0.5.0;

contract D {
    function g(uint256 a) public view returns(uint256) {
        return a*2;
    }
}

contract A {
    D public impl;

    constructor() public {
        impl = new D();
    }

    function() external {
        require(msg.sender == address(this));

        (bool success, bytes memory data) = address(impl).delegatecall(msg.data);
        assembly {
            switch success
                // delegatecall returns 0 on error.
                case 0 { revert(add(data, 32), returndatasize) }
                default { return(add(data, 32), returndatasize) }
        }
    }

    function f(uint256 a)
        public
        view
        returns(uint256)
    {
        (bool success, bytes memory data) = address(this).staticcall(
            abi.encodeWithSelector(
                impl.g.selector,
                10
            )
        );

        assembly {
            switch success
                // delegatecall returns 0 on error.
                case 0 { revert(add(data, 32), returndatasize) }
                default { return(add(data, 32), returndatasize) }
        }
    }
}
| improve this answer | |
  • A static call is different from a delegate call, for example delegate doesn't change msg.sender and static call does change it. – Ismael Apr 10 at 17:05

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.