1

I would like to implement two contracts that extend another contract with an information store. Example:

contract MonsterData {
    struct Monster {
        string name;
        int8 category;
    }
    
    Monster[] monsters;
}

contract MonsterCommon is MonsterData {
    function createMonsterCommon(string name) external{
        monsters.push(Monster(name, 1));
    }
}

contract MonsterRare is MonsterData {
    function createMonsterRare(string name) external{
        monsters.push(Monster(name, 2));
    }
}

And deployed these contract using truffle migration:

module.exports = function (deployer) {
  deployer.deploy(MonsterData);
};

module.exports = function (deployer) {
  deployer.deploy(MonsterCommon);
};

module.exports = function (deployer) {
  deployer.deploy(MonsterRare);
};

What will be the behavior when i create a new rare or common monster? Will they be inserted into the same array? If I access the array through any of the contracts will I be able to see all monsters entered in both contracts? Thank you.

1

Contract inheritance is basically just a coding trick. What happens in the compiler, is that all of the code is flattened into a single contract. So if A inherits B and you compile A, the compiler simply inserts the code of B into contract A.

Therefore you shouldn't need to deploy the base contract. You only need to deploy the two contracts which inherit from it. And because those contracts are separate deployments, they are also separate contracts, at separate addresses, with separate storage. So, if you deploy only the two contracts, you will have contracts MonsterRare and MonsterCommon which both include the same code from MonsterData - but the two are completely separate entities.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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