跳到主要内容

合约间交互

合约允许与链上的其他合约进行交互

假设存在链上合约 LuckyNumber

contract LuckyNumber {
mapping(address => uint) numbers;

function setNum(uint _num) public {
numbers[msg.sender] = _num;
}

function getNum(address _myAddress) public view returns (uint) {
return numbers[_myAddress];
}
}

另一个合约希望访问 LuckyNumber 中的数据,需要先定义其 Interface

interface LuckyNumberInterface {
function getNum(address _myAddress) public view returns (uint);
}

contract MyContract {
// LuckyNumber 的合约地址
address NumberInterfaceAddress = 0xab38...;

// numberContract 指向一个合约对象
LuckyNumberInterface numberContract = NumberInterface(NumberInterfaceAddress);

function someFunction() public {
// 访问合约方法
uint num = numberContract.getNum(msg.sender);
}
}