使用test1调用test2的函数,编译没有报错,但是调用的时候调用失败,报错如下:
revert
The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.
Debug the transaction to get more information.
(我上一篇文章也是报这个错,但是错的原因不一样。合约调试真NM难)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Test2{
uint8 num=5;
function getNum()public view returns (uint8){
return num;
}
}
contract Test1{
Test2 test2;
function getNumFromTest2 ()public view returns (uint8){
uint8 _num = test2.getNum();
return _num;
}
}
问题分析:虽然编译没有报错,但是Test2 test2;这个变量中应该是空的,没有赋值。
想要调用其他合约,需要先知道其他合约的地址,然后再调用。
解决办法:
第一步.更改代码如下
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Test2{
uint8 num=5;
function getNum()public view returns (uint8){
return num;
}
}
contract Test1{
Test2 test2;
constructor(address _addr){
test2=Test2(_addr);
}
function getNumFromTest2 ()public view returns (uint8){
uint8 _num = test2.getNum();
return _num;
}
}
第二部,部署Test2,获得test2的地址address
第三步,用address为参数部署test1,然后就能正常调用了。
PS:也可以用call函数调用,参照: