How to understand the initialization of a contract as an interface in Solidity

Viewed 65

I am learning SmartContract development on Ethereum with Solidity and I would highly appreciate your help to understand this one basic thing:

KittyInterface as a contract has no parameters, just one function:

contract KittyInterface {
  function getKitty(uint256 _id) external view returns (
    bool isGestating,
    bool isReady,
    uint256 cooldownIndex,
    uint256 nextActionAt,
    uint256 siringWithId,
    uint256 birthTime,
    uint256 matronId,
    uint256 sireId,
    uint256 generation,
    uint256 genes
  );
}

But then it gets initialized like this, giving one parameter (ckAddress).

address ckAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
KittyInterface kittyContract = KittyInterface(ckAddress);

So my question is:

What happens when we call KittyInterface(ckAddress); when the contract has no parameters to take, but only a function? Where does the "ckAddress" go?

Is the address taken to write/connect to the blockchain? Or is it given to the first function of the contract?

It works, there are no errors, but I struggle to understand it.

It is part of the Cryptozombie-Course, so I cannot debug it.

Can anybody please help me understand?

2 Answers

The following part is not actual initiating, nor function calling.

KittyInterface kittyContract = KittyInterface(ckAddress);

It is just converting ckAddress to callable smart contract, when you know the type-signature of the function you want to call.

This is called dependency-injection mechanism.

More info can be found in the link.

Sometimes the contract code is not available to us. The contract is already deployed on a network and only its address is available to us. The only way to use such a contract is through low-level address-provided functions ( send, transfer, staticcall , call , and delegatecall ). This is because we do not have the definition of that contract and we cannot use the new keyword for it. If such a contract implements an interface and that interface definition is available to us, we will be able to use it to reference the target contract through its address itself. with this

KittyInterface(ckAddress)

you are telling the compiler which functions are available in this deployed contract ckAddress so you can call those functions.

  • Interface might not contain all the functions defined in the contract. Note that only functions defined within the interface are callable using this method: KittyInterface(ckAddress)
Related