041. Getting started with Solidity - 28 delegate calls

A delegate call is a special low-level call that hands over the storage, state, and code of the current contract to another contract for execution. In a delegate call, the caller and the callee share the same storage space, so the called contract can access the state variables of the caller, but cannot modify them.

Sample code:

interface GreeterInterface {
    function greet() external view returns (string memory);
}
contract Greeter1 is GreeterInterface {
    string greeting;
    constructor(string memory _greeting) {
        greeting = _greeting;
    }
    function greet() public view override returns (string memory) {
        return greeting;
    }
    function setGreeting(string memory _greeting) public {
        greeting = _greeting;
    }
}

contract Greeter2 {
    address public greeter1Address;

    constructor(address _greeter1Address) {
        greeter1Address = _greeter1Address;
    }

    function greet() public view returns (string memory) {
        // 使用普通调用,直接调用Greeter1合约的greet函数
        return Greeter1(greeter1Address).greet();
    }

    function delegateGreet() public view returns (string memory) {
        // 使用委托调用,将调用转发给Greeter1合约的greet函数
        (bool success, bytes memory result) = greeter1Address.delegatecall(abi.encodeWithSignature("greet()"));
        require(success, "delegatecall to Greeter1 failed");

        return abi.decode(result, (string));
    }

    function setGreeting(string memory _greeting) public {
        // 使用普通调用,直接调用Greeter1合约的setGreeting函数
        Greeter1(greeter1Address).setGreeting(_greeting);
    }

    function delegateSetGreeting(string memory _greeting) public {
        // 使用委托调用,将调用转发给Greeter1合约的setGreeting函数
        (bool success, bytes memory result) = greeter1Address.delegatecall(abi.encodeWithSignature("setGreeting(string)", _greeting));
        require(success, "delegatecall to Greeter1 failed");
    }
}

The following points need to be paid attention to when using delegate calls:

  1. The called contract must exist and its code must have been deployed to the blockchain.

  1. When using a delegate call, you need to manually pass the contract's storage and code to the called contract.

  1. The code in the called contract may overwrite the caller's storage space, so it needs to be used with caution.

  1. Tokens or Gas cannot be passed in the delegate call, so when calling functions of other contracts, you need to ensure that they do not consume too much Gas, otherwise the delegate call may fail.

In short, delegate calls need to be used with caution, and their potential risks and precautions should be carefully considered when calling to ensure the security and stability of the contract.

Guess you like

Origin blog.csdn.net/qq_35369459/article/details/129209264