美文网首页我爱编程
智能合约语言 Solidity 教程系列7 - 以太单位及时间单

智能合约语言 Solidity 教程系列7 - 以太单位及时间单

作者: 半亩房顶 | 来源:发表于2018-05-24 17:46 被阅读31次

    转自:https://learnblockchain.cn/2018/02/02/solidity-unit/

    货币单位(Ether Units)

    一个数字常量(字面量)后面跟随一个后缀wei, finney,szaboether,这个后缀就是货币单位。不同的单位可以转换。不含任何后缀的默认单位是wei。
    不同的以太币单位转换关系如下:

    • 1 ether == 10^3 finney == 1000 finney
    • 1 ether == 10^6 szabo
    • 1 ether == 10^18 wei

    插曲:以太币单位其实是密码学家的名字,是以太坊创始人为了纪念他们在数字货币的领域的贡献。他们分别是:
    wei: Wei Dai 戴伟 密码学家 ,发表 B-money
    finney: Hal Finney 芬尼 密码学家、工作量证明机制(POW)提出
    szabo: Nick Szabo 尼克萨博 密码学家、智能合约的提出者

    我们可以使用一下代码验证一个转换关系:

    pragma solidity ^0.4.16;
    
    contract testUnit {
        function tf() public pure returns (bool) {
          if (1 ether == 1000 finney){
              return true;
          }
          return false;
        }
        
        function ts() public pure returns (bool) {
          if (1 ether == 1000000 szabo){
              return true;
          }
          return false;
        }
        
        function tgw() public pure returns (bool) {
          if (1 ether == 1000000000000000000 wei){
              return true;
          }
          return false;
        }
    }
    

    时间单位(Time Units)

    时间单位: seconds, minutes, hours, days, weeks, years均可做为后缀,并进行相互转换,规则如下:

    • 1 == 1 seconds (默认是seconds为单位)
    • 1 minutes == 60 seconds
    • 1 hours == 60 minutes
    • 1 days == 24 hours
    • 1 weeks = 7 days
    • 1 years = 365 days

    使用这些单位进行日期计算需要特别小心,因为不是每年都是365天,且并不是每天都有24小时,因为还有闰秒。由于无法预测闰秒,必须由外部的预言(oracle)来更新从而得到一个精确的日历库。

    这些后缀不能用于变量。如果想对输入的变量说明其不同的单位,可以使用下面的方式:

    pragma solidity ^0.4.16;
    
    contract testTUnit {
    
        function currTimeInSeconds() public pure returns (uint256){
            return now;
        }
    
        function f(uint start, uint daysAfter) public {
            if (now >= start + daysAfter * 1 days) {
            // ...
            }
        }
    }
    

    参考文档

    相关文章

      网友评论

        本文标题:智能合约语言 Solidity 教程系列7 - 以太单位及时间单

        本文链接:https://www.haomeiwen.com/subject/eewsjftx.html