Solidity

是否可以在另一個內部使用solidity庫?

  • April 9, 2018

我正在嘗試在另一個內部使用一個可靠的庫。最小的程式碼是這樣的:

最深的圖書館:SLib.sol

pragma solidity ^0.4.18;

library SLib {
 struct SCtx {
   uint a;
 }

 function init(SCtx storage self, uint _a) public
 {
   self.a = _a;
 }

 function getA(SCtx storage self) public view returns (uint)
 {
   return self.a;
 }
}

然後TLib.sol使用上一個:

pragma solidity ^0.4.18;

import "./SLib.sol";

library TLib {
 using SLib for SLib.SCtx;

 struct TCtx {
   SLib.SCtx s;
 }

 function init(TCtx storage self, uint _a) public
 {
   self.s.init(_a);
 }

 function getA(TCtx storage self) public view returns (uint) {
   return self.s.getA();
 }
}

然後是一些使用它們的契約TInterface.sol

pragma solidity ^0.4.18;

import "./TLib.sol";

contract TInterface {
 using TLib for TLib.TCtx;
 TLib.TCtx t;

 function TInterface(uint _a) public {
   t.init(_a);
 }

 function getA() public view returns (uint) {
   return t.getA();
 }
}

在 Truffle 中,我什至無法將這些人聯繫起來。在2_deploy_libraries.js

var TLib = artifacts.require("./TLib.sol");
var SLib = artifacts.require("./SLib.sol");
var TInterface = artifacts.require("./TInterface.sol");

module.exports = function(deployer) {
 deployer.deploy(SLib);
 deployer.deploy(TLib);
 deployer.link(SLib, TLib);
 deployer.link(TLib, TInterface);
};

回報:

 Deploying SLib...
 ... 0xe0317d15a3eac...
 SLib: 0x8e4c131b37383e431b9cd0635d3cf9f3f628edae
 Deploying TLib...
 Linking SLib to TLib
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: TLib contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of TLib: SLib
   at /usr/l...:/~/truffle-contract/contract.js:371:1
   at <anonymous>
   at process._tickDomainCallback (internal/process/next_tick.js:228:7)

甚至允許這樣做嗎?如果是,那麼連結和使用它的正確方法是什麼?

我明白我做錯了什麼。它與應該連結/部署庫的順序有關。這是正確的方法:

var TLib = artifacts.require("./TLib.sol");
var SLib = artifacts.require("./SLib.sol");
var TInterface = artifacts.require("./TInterface.sol");

module.exports = function(deployer) {
 deployer.deploy(SLib);
 deployer.link(SLib, TLib);
 deployer.deploy(TLib);
 deployer.link(TLib, TInterface);
};

事實上這是有道理的。

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