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());
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端段

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值