Library – How to Create Common Enum and Struct Between Two Contracts

enumlibrary

Here is what I'm trying to do by using a common enum and struct between two contracts:

Library Code:
pragma solidity ^0.8.7;

library Library {

enum Areas {
    Burrow, School, Forest, Mine, DeepMine, Trails
}

struct AreaFeatures{
    uint travelTime;
    uint resource;
    uint resourceRate;
    uint commonItem;
    uint rareItem;
    uint legendaryItem;
    uint[] rarityTable;
    uint minLevel;
    bool isEnabled;
    Powers powa;

}

enum Powers{
    EmptyHead, BrainPower, AxeStrength, Speed, Scavenge
}
}

By using this Library, I want to be able to have a common enum and struct between two contracts so that I am able to update one contract by calling its function from another contract. When trying to call the function from another contract, I get the error: DeclarationError: Identifier not found or not unique. using Library for Areas;

 import "./Library.sol";

 contract Tester {
 using Library for Areas;
 using Library for Powers;
 AreaCreation public areaAddress;

function giveAreaTheFeatures(Areas place, uint travel, uint resourceId, uint rate, uint common, uint rare, uint legendary, uint[] memory rarity, uint level, bool open, Powers power) public{
areaAddress.giveAreaFeatures(place, travel, resourceId, rate, common, rare, legendary, rarity,  level, open, power);        
}

Where the "areaAddress" is the address of the contract I want to update and "giveAreaFeatures" is the function that I want to call.

I guess the first question that I should ask is, is this even possible to do? And if so, what is the mistake that I am making?

Best Answer

It seems like you forgot to reference from the library like this Library.Areas , which is why it isn't working and calling out an error. I found an example on the official solidity doc that shows you how to use library correctly. I coded a demo that is working just fine below that works just fine.



Example code of the use case of using Library that has enum & struct.

  • Tested it on remix.ethereum
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

library Lib {

    enum Areas {
        Burrow, School, Forest, Mine, DeepMine, Trails
    }

    struct AreaFeatures{
        string name;
    }

    enum Powers{
        EmptyHead, BrainPower, AxeStrength, Speed, Scavenge
    }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./OurLibrary.sol";


contract TestingSomething {

    function testingEnum(Lib.Areas _x) public pure returns (Lib.Areas) {
        return _x;
    }

    function testingStruct() public pure returns (Lib.AreaFeatures memory) {
        Lib.AreaFeatures memory y = Lib.AreaFeatures("example");
        return y;
    }

}
Related Topic