0
点赞
收藏
分享

微信扫一扫

solidity库的使用

雅典娜的棒槌 2022-03-24 阅读 40


一个特殊的合约
可以像合约一样进行部署,但是没有状态变量、不能存以太币

可重用
部署一次,在不同合约内反复使用
节约gas,相同功能的代码不用反复部署

1.定义库、使用库
library mathlib{
plus();
}
contract C{
mathlib.plus();
}

库函数使用委托的方式调用delegateCall,库代码是在发起合约中执行的。

2.using for 扩展类型
A是库library
using A for B 把库函数(从库A)关联到类型B
A库有函数add(B b), 则可使用b.add()

mathlib.sol

pragma solidity ^0.4.24;

library mathlib {
      uint constant age = 40;
      function plus(uint a, uint b) public pure returns (uint) {
            uint c = a + b;
            assert(c>=a && c>=b);
            return c;
      }

      function getThis() public view returns (address) {
          return this;
      }

}

testLib.sol中引入上面的库

pragma solidity ^0.4.24;

import "./mathLib.sol";

contract testLib {

    using mathlib for uint;

    function add (uint x, uint y) public returns (uint) {
        return x.plus(y);
        // return mathlib.plus(x,y);


    }

    function getThis() public view returns (address) {

        return mathlib.getThis();
    }

}

举报

相关推荐

0 条评论