pragma solidity 0.6.2;
/*
合约调用合约,并解析返回参数
*/
contract ContractCallContract{
event Call(bytes k1,uint256 k2,uint256 k3);
function callContractByEncodeWithSelector(address contractAddress,uint256 a,uint256 b) public {
(bool success, bytes memory data) = contractAddress.call(abi.encodeWithSelector(getSelector(),a,b));
require(success,"call A is fail");
(uint256 c,uint256 d) = abi.decode(data,(uint256,uint256));
emit Call(data,c,d);
}
function callContractByEncodeWithSignature(address contractAddress,uint256 a,uint256 b) public {
(bool success, bytes memory data) = contractAddress.call(abi.encodeWithSignature("add(uint256,uint256)",a,b));
require(success,"call A is fail");
// 解析data
(uint256 c,uint256 d) = abi.decode(data,(uint256,uint256));
emit Call(data,c,d);
}
function callA(bytes4 b4,uint256[] memory list,address contractAddress) public {
(bool success, bytes memory data) = contractAddress.call(abi.encodeWithSelector(b4,list));
require(success,"call A is fail");
// 解析data
(uint256 a,uint256 b) = abi.decode(data,(uint256,uint256));
emit Call(data,a,b);
}
function getSelector() public pure returns(bytes4){
return bytes4(keccak256(bytes('add(uint256,uint256)')));
}
function getAddSelector() public pure returns(bytes4){
return bytes4(keccak256(bytes('add(uint256[])')));
}
}
contract A{
function add(uint256 a,uint256 b) public pure returns(uint256,uint256){
return (a+b,a-b);
}
function add(uint256[] memory a) public pure returns(uint256,uint256){
return (a[0]+a[1],a[0]-a[1]);
}
}