Thaiminhpv
Thaiminhpv

Reputation: 374

Get Smart Contract instance from its address

In Solidity, given a Smart Contract instance named foo

MySmartContract foo = new MySmartContract()

I can get this Smart Contract instance's address by using address(foo)

address fooAdress = address(foo)

How do I get back foo object, given only its address fooAdress?

I expect something like:

MySmartContract originalFoo = some_function_goes_here(fooAdress)

Upvotes: 2

Views: 1133

Answers (2)

Yilmaz
Yilmaz

Reputation: 49261

you need the interface of the contract too. If you do not have a contract code and you want to call contract methods but if you do not have the code how would you know which methods to call?

interface InterfaceA {
    function count() external view returns (uint256);
    function increment() external;
}

you know the address of the contract

InterfaceA a = InterfaceA(addressA);

a is the contract instance

  • If you know only the address you can use address.call but this is not Safe ant Not recommended. You need to know the selector of the function. For example if you have "transfer" function

        // we need function name and its argument types (address and uint256)
        bytes4 private constant TRANSFER_SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
    

then

// abi.encodeWithSignature() method is the standard way to interact with contracts
        (bool success, bytes memory data) = contractAddress.call(abi.encodeWithSelector(TRANSFER_SELECTOR, to, value));

Upvotes: 3

Jeffrey
Jeffrey

Reputation: 36

You cannot get the "object", unless your intent is to get the bytecode of the contract. In that case some_function_goes_here is fooAddress.code.

MySmartContract is really just an address under the hood. It's a convenient way to specify the ABI protocol for that address. Without it, if you wanted to call a function in foo, you'd have to do foo.call(abi.encodeWithSignature("someFunction")) which is a lot less convenient.

If your intent is to get a public variable from foo, you can just do foo.someVariable().

Upvotes: 0

Related Questions