0

How do you check if a contract mapping/variable is still to be initialized ?

comparing

contractTypeVariable != address(0)

gives a type error

Operator != not compatible with types contract BasicToken and address

sample pseudocode:

Contract XYZ {

    mapping(uint256 => MyContract) private _contracts;
    ...
    function doStuff(uint256 i) ... {   
        require(_contracts[i] == address(0), "Contract already exists");
        ...

    }
}

1 Answer 1

1

If MyContract is an imported contract then you can get its address with address(_contracts[i]) and then compare it to the zero address.

Contract XYZ {

    mapping(uint256 => MyContract) private _contracts;
    ...
    function doStuff(uint256 i) ... {   
        require(address(_contracts[i]) == address(0), "Contract already exists");
        ...

    }
}

————-

If MyContract is a struct then: You need to compare the values inside the struct and not the struct it self.

If the struct looks like this

struct MyContract {
  address addressOfContract;
  ..
}

and this addressOfContract is set when it is initialized and never change or get deleted.

Then you need to do this:

Contract XYZ {

    mapping(uint256 => MyContract) private _contracts;
    ...
    function doStuff(uint256 i) ... {   
        require(_contracts[i].addressOfContract == address(0), "Contract already exists");
        ...

    }
}
7
  • no, MyContract is a different contract, imagine the "import .../MyContract.sol" at the beginning of the file and then _contracts[i] = new MyContract(constructor_params)
    – Stormsson
    May 17, 2022 at 10:44
  • @Stormsson okay then try -> address(_contracts[i]) == address(0)
    – Majd TL
    May 17, 2022 at 11:14
  • @Stormsson if it works then tell me to update my answer , otherwise i will delete it and edit your question.
    – Majd TL
    May 17, 2022 at 11:14
  • yes, it works thank you! If you update the answer i'll flag it as solved.
    – Stormsson
    May 17, 2022 at 16:57
  • @Stormsson Great I updated it , thanks
    – Majd TL
    May 17, 2022 at 19:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.