solidity ライブラリの使用

1. ライブラリとは
コントラクトのようにデプロイできるが、状態変数を持たず、イーサを格納できない特殊なコントラクト

再利用可能
一度デプロイすれば、異なるコントラクトで繰り返し使用
ガスを節約し、同じ機能を持つコードを繰り返しデプロイする必要はありません

1. ライブラリを定義し、ライブラリを使用
library mathlib{ plus(); } contract C{ mathlib.plus(); }




ライブラリ関数は委任の方法で delegateCall を呼び出し、ライブラリ コードは元のコントラクトで実行されます。

2. 拡張タイプ A を使用すると、A を B に使用する
ライブラリ ライブラリが(ライブラリ A からの) ライブラリ関数をタイプ B に関連付けます。ライブラリに関数 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();
    }

}

2. サードパーティ ライブラリ
OpenZeppelin
https://github.com/OpenZeppelin/openzeppelin-contracts
ベスト プラクティス ケース
safeMath
ERC20
ERC721
所有権
ホワイトリスト
Crowdsale

イーサリアム ライブラリ
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 // トラバース マップ
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