solidity库的使用

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

可重用
部署一次,在不同合约内反复使用
节约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();
    }

}

二、第三方库
OpenZeppelin
https://github.com/OpenZeppelin/openzeppelin-contracts
最佳实践案例
safeMath
ERC20
ERC721
Ownership
Whitelist
Crowdsale

ethereum-libraries
https://github.com/modular-network/ethereum-libraries

dapp-bin
https://github.com/ethereum/dapp-bin
https://github.com/ethereum/dapp-bin/tree/master/library
iterable_mapping.sol // 遍历map
linkedList.sol //双向链表

stringutils
https://github.com/Arachnid/solidity-stringutils


//SPDX-License-Identifier: MIT
pragma solidity  ^0.8.0;

import "./strings/strings.sol";
// import "github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol";


contract C {
    using strings for *;
    string public s;
 
    function foo(string memory s1, string memory s2) public {
        s = s1.toSlice().concat(s2.toSlice());
    }
}

猜你喜欢

转载自blog.csdn.net/hkduan/article/details/123718473