040. Getting started with Solidity - 27 low-level calls

In Solidity, calling low-level calls in other contracts requires the use of the address.call() function . The function accepts a parameter of type bytes , which is an array of bytes containing the calling data. A low-level call will send the specified data to the address of the target contract and return a boolean indicating whether the call was successful.

Sample code:


contract ContractA {
    uint256 public numA;

    // 合约A的低级调用函数
    function lowLevelCall(address payable _addressB, uint256 _num) external {
        //编码函数abi.encodeWithSignature将setNumB函数名和参数_num打包
        bytes memory payload = abi.encodeWithSignature("setNumB(uint256)", _num);
        // 发起低级调用(低级调用需要传入一个字节数组作为参数,所以需要将编码后的字节数组赋值给变量payload。)
        (bool success,) = _addressB.call(payload);
        //判断调用是否成功,如果失败则抛出异常
        require(success, "Low-level call failed");
    }
}

// 合约B
contract ContractB {
    uint256 public numB;

    // 合约B的函数,供合约A低级调用
    function setNumB(uint256 _num) external {
        numB = _num;
    }
}

Notes:

lowLevelCall function: call the setNumB function in contract B through a low-level call , and set the value of the numB variable in contract B to the incoming parameter _num .

abi.encodeWithSignature: encoding function, which will pack the function name and parameters into a byte array. Use it to encode the setNumB function name of contract B and the parameter _num to be passed in .

In the lowLevelCall function, use _addressB.call(payload) to initiate a low-level call. This function returns two values, the first value indicates whether the call is successful, and the second value is a returned byte array, which can be ignored for functions that do not return a value.

When using low-level calls to call other contracts, the following points need to be paid special attention to:

  1. Make sure the address of the target contract is correct to avoid calling other contracts by mistake.

  1. Make sure the function of the target contract exists, and the parameter types and numbers match, otherwise a runtime error will result.

  1. During the call, you need to ensure that exceptions and error conditions are handled properly to avoid the contract being attacked or losing control.

  1. In low-level calls, the code of the called contract will be executed in the context of the current contract, so state variables and storage need to be handled with special care.

In short, when using low-level calls, you need to write the calling code carefully and ensure that the called contract is trusted, because it can execute arbitrary code in the called contract.

Guess you like

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