NFT合约解析(4)——Counters.sol——2021.5.19

一丶配置需求:

1.环境需求:WeBASE-Front

2.合约语言:Solidity >=0.6.0 <0.8.0

二丶Counters.sol


pragma solidity >=0.6.0 <0.8.0;

import "./SafeMath.sol";

library Counters {
    
    
    using SafeMath for uint256;

    struct Counter {
    
    
        uint256 _value; 
    }
    
    function current(Counter storage counter) internal view returns (uint256) {
    
    
        return counter._value;
    }

    function increment(Counter storage counter) internal {
    
    
        counter._value += 1;
    }

    function decrement(Counter storage counter) internal {
    
    
        counter._value = counter._value.sub(1);
    }
}

三丶解析合约

pragma solidity >=0.6.0 <0.8.0;	 //1
import "./SafeMath.sol";		 //2
library Counters {
    
    				 //3
    using SafeMath for uint256;  //4
    struct Counter {
    
    			 //5
        uint256 _value; 		 //6
    }							 //7
  • 第1行:申明版本
  • 第2行:导入SafeMath.sol合约
  • 第3行:创建库合约Counters
  • 第4行:将SafeMath的所有库函数引用到Counters库合约的uint256类型
  • 第5-7行:创建Counter结构体,申明一个uint256类型的状态变量_value
    function current(Counter storage counter) internal view returns (uint256) {
    
     //1
        return counter._value;													//2
    }																			//3
    function increment(Counter storage counter) internal {
    
    						//4
        counter._value += 1;													//5
    }																			//6
    function decrement(Counter storage counter) internal {
    
    						//7
        counter._value = counter._value.sub(1);									//8
    }																			//9														
  • 第1行:创建方法:current;参数:storage类型的结构体counter;internal:内置函数,view:不改变状态变量;returns (uint256): 返回值类型:uint256
  • 第2-3行:返回counter._value值
  • 第4行:创建方法:increment;参数:storage类型的结构体counter;internal:内置函数
  • 第5-6行:counter._value的值加1
  • 第7行:创建方法decrement;参数:storage类型的结构体counter;internal:内置函数
  • 第8-9行:counter._value.sub(1):调用SafeMath的sub函数,counter._value作第一参数,1作第二参数;其结果当前counter._value接受

四丶上一篇:NFT合约解析(3)——SafeMath.sol

NFT合约解析(3)——SafeMath.sol

五丶下一篇:未完待续

六丶参考相关文章

solidity笔记(1)——第一篇
solidity笔记(2)——第二篇
solidity笔记(3)——abstract用法
solidity笔记(4)——冻结和交易属性
solidity笔记(5)——event用法
solidity笔记(6)——modifier用法
solidity笔记(7)——存储区域memory storage stack
solidity笔记(8)——pure用法
solidity笔记(9)——library用法
solidity笔记(10)——using for用法
solidity笔记(11)——struct用法

猜你喜欢

转载自blog.csdn.net/weixin_43402353/article/details/117014792