Skip to content

Instantly share code, notes, and snippets.

@jioXo
Created April 23, 2025 05:46
Show Gist options
  • Save jioXo/3951967acf06dac0c219a396f6726387 to your computer and use it in GitHub Desktop.
Save jioXo/3951967acf06dac0c219a396f6726387 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.26+commit.8a97fa7a.js&optimize=false&runs=200&gist=
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;
import "tests/OtherContract.sol";
contract Call {
//定义response事件,输出call调用的success和data
event Response(bool success, bytes data);
//定义callSetX函数来调用目标合约的setX(),转入msg.value数额的ETH,并释放Response事件输出success和data
function callSetx(address payable _addr, uint256 x) public payable {
(bool success, bytes memory data) = _addr.call{value: msg.value}(
abi.encodeWithSignature("setX(unit256)", x)
);
emit Response(success, data); //释放事件
}
//调用getX()函数,它将返回目标合约_x的值,类型为uint256。我们可以利用abi.decode来解码call的返回值data,并读出数值。
function callGetX(address _addr) external returns (uint256) {
// call getX()
(bool success, bytes memory data) = _addr.call(
abi.encodeWithSignature("getX()")
);
emit Response(success, data); //释放事件
return abi.decode(data, (uint256));
}
//如果我们给call输入的函数不存在于目标合约,那么目标合约的fallback函数会被触发。
function callNonExist(address _addr) external{
// call 不存在的函数
(bool success, bytes memory data) = _addr.call(
abi.encodeWithSignature("foo(uint256)")
);
emit Response(success, data); //释放事件
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment