Solidity Delegatecall – Fix Delegate Call from Fallback Function Using msg.data

delegatecallfallback-functionremixsolidity

Please look into the following 3 contracts:

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.7;

contract implementationProxy {
    uint public a;
    uint public b;

    address owner;
    address implementation;

    constructor() {
        owner = msg.sender;
    }

    function implementationAdd(address _add) external {
        require(msg.sender == owner, "Not allowed");

        implementation = _add;
    }

    fallback() payable external {
        implementation.delegatecall(msg.data);
    }
}

contract Implementation {
    uint public a;
    uint public b;

    function setVar(uint _a, uint _b) external {
        a= _a;
        b= _b;
    } 

    function add() external view returns (uint) {
        return a+b;
    }
}

contract User {

    function varChange(address _add, uint _a, uint _b) external {
        _add.call(
      abi.encodeWithSelector(
        bytes4(keccak256("setVar(uint256, uint256)")), _a, _b
      )
    );
        
    }
}

implementationProxy has a function implementationAdd(address _add) that takes input of deployed Implementation contract.

The User contract calls a function that triggers fallback in implementationProxy (the address _add in varChange() is of implementationProxy)

So ideally the state variables a and b must change in implementationProxy as it delegates call to Implementation. But the state variables are unchanged.

Can anyone help me find out my mistake please?

Best Answer

the problem is in the space between the comma and the second uint256

try this:

abi.encodeWithSelector(bytes4(keccak256("setVar(uint256,uint256)")), _a, _b)

instead of

"setVar(uint256, uint256)"

or in the other hand you can use:

_add.call(abi.encodeWithSelector(Implementation.setVar.selector, _a, _b));
Related Topic