Library

如何使用庫在兩個合約之間創建公共列舉和結構?

  • March 4, 2022

這是我通過在兩個合約之間使用通用列舉和結構來嘗試做的事情:

庫程式碼: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
}
}

通過使用這個庫,我希望能夠在兩個合約之間擁有一個通用的列舉和結構,以便我能夠通過從另一個合約呼叫它的函式來更新一個合約。嘗試從另一個合約呼叫該函式時,我收到錯誤:DeclarationError: Identifier not found or not unique。使用區域庫;

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);        
}

其中“areaAddress”是我要更新的合約地址,“giveAreaFeatures”是我要呼叫的函式。

我想我應該問的第一個問題是,這甚至可能嗎?如果是這樣,我犯了什麼錯誤?

似乎您忘記從庫中引用此Library.Areas,這就是它無法正常工作並顯示錯誤的原因。我在官方 Solidity 文件中找到了一個範例,該範例向您展示瞭如何正確使用庫。我編寫了一個在下面執行良好的展示,它執行良好。

使用具有列舉和結構的庫的案例範常式式碼。

  • 在 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;
   }

}

引用自:https://ethereum.stackexchange.com/questions/123049