The use of solidity library

1. What is a library?
A special contract that can be deployed like a contract, but has no state variables and cannot store Ethereum

Reusable
Deploy once and use repeatedly in different contracts
Save gas, code with the same function does not need to be deployed repeatedly

1. Define library, use library
library mathlib{ plus(); } contract C{ mathlib.plus(); }




The library function calls delegateCall in the way of delegation, and the library code is executed in the originating contract.

2. Using for extended type
A is a library library
using A for B associates library functions (from library A) to type B.
A library has function add(B b), then you can use 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;
      }

}

Introduce the above library in 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. The third-party library
OpenZeppelin
https://github.com/OpenZeppelin/openzeppelin-contracts
best practice case
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 // traverse map
linkedList.sol // doubly linked list

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

Guess you like

Origin blog.csdn.net/hkduan/article/details/123718473