在 Solidity 中,给定一个名为 foo
的智能合约实例
MySmartContract foo = new MySmartContract()
我可以使用address(foo)
获取此智能合约实例的地址
address fooAdress = address(foo)
仅给出地址fooAdress
,如何取回foo
对象?
我期望类似的东西:
MySmartContract originalFoo = some_function_goes_here(fooAdress)
最佳答案
你也需要合约的接口(interface)。如果你没有合约代码并且你想调用合约方法,但是如果你没有代码你怎么知道要调用哪些方法?
interface InterfaceA {
function count() external view returns (uint256);
function increment() external;
}
你知道合约的地址
InterfaceA a = InterfaceA(addressA);
a
是合约实例
如果您只知道地址,则可以使用
address.call
,但这并不安全,不推荐。您需要知道函数的选择器。例如,如果您有“转账”功能// we need function name and its argument types (address and uint256) bytes4 private constant TRANSFER_SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
然后
// abi.encodeWithSignature() method is the standard way to interact with contracts
(bool success, bytes memory data) = contractAddress.call(abi.encodeWithSelector(TRANSFER_SELECTOR, to, value));
关于blockchain - 从其地址获取智能合约实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74369486/