Solidity – How to Access Struct of Other Contracts via Interface

interfacesmigrationsoliditystruct

I am trying to access the struct of another contract via an interface. I am having two different contracts that I want to deploy on the chain:

  1. Contract:
contract cat {

    uint id = 0;
    mappung(uint => Cat) idToCat;

    struct Cat {
        string name;
        uint age;
        uint babys;
    }

    function aNewCatIsBorn(string _name) {
        Cat memory cat;
        cat.name = _name;
        cat._age = 0;
        cat.babys = 0;
        idToCat[id] = cat;
        id += 1;
    }
    
    function getCatById(uint _id) public view retruns(Cat memory cat){
        return idToCat[_id];
    }   
}
  1. Contract
interface ICat{
    struct Cat {
        string name;
        uint age;
        uint babys;
    }
    function getCatById(uint _id) external view retruns(Cat memory cat)
}

contract NextGenCat {
    address catContract = //address Of cat contract after beingd eployed
    
    /*
    * This is where I want to get the cats of the other contract. The problem is
    * that I cannot create a struct with the struct I am passing along in the interface.
    */
    ICat(catContract).Cat() cat = ICat(catContract).getCatById(0);
}

I already tried to have the struct of the cat contract in the NextGenCat contract as well and assign the struct via the function provided by the interface, but this didn't work either as the compiler doesn't allow this (he can't know whether the structs in NextGenCat and cat match, so I get that).

The question is: is there any way to do what I am trying to archive?

Best Answer

The syntax is wrong use ICat.Cat as the type.

contract NextGenCat {
    address catContract = 0x123412341234..0000;

    ICat.Cat cat;
    
    function foo() public {
      cat = ICat(catContract).getCatById(0);
    }
}
Related Topic