[Solidity 實戰全書] 第 3 章 單位 Unit & 運算子 Operators

【單位】

如同前一個章節在整數時的內容,我們沒辦法使用小數來表達一個值,所以在 Solidity 裡面有許多單位可供使用。

Unitwei valueweiether value
wei1 wei110^-18 ETH
kwei10^3 wei1,00010^-15 ETH
mwei10^6 wei1,000,00010^-12 ETH
gwei10^9 wei1,000,000,00010^-9 ETH
microether10^12 wei1,000,000,000,00010^-6 ETH
milliether10^15 wei1,000,000,000,000,00010^-3 ETH
ether10^18 wei1,000,000,000,000,000,0001 ETH
pragma solidity ^0.8.11;

contract MyUnits {
    // 1 wei == 1;
    // 1 gwei == 1e9;
    // 1 ether == 1e18;
    uint256 public costOfNFT = 0.0000000000005 ether;
}

【Time】

Solidity 還提供時間的語法,只是跟我們平常熟知的表示形式不同,Solidity 內表示時間的方式是 UNIX 時間 (Unix time)

所謂的 UNIX 時間是從 UTC 1970 年 1 月 1 日 0 時 0 分 0 秒起至現在的總秒數,不考慮閏秒。

pragma solidity ^0.8.11;

contract MyTime {
    // 1 == 1 seconds
    // 1 minutes == 60 seconds
    // 1 hours == 60 minutes
    // 1 days == 24 hours
    // 1 weeks == 7 days
    uint256 public levelUpRate = 1 days; // 回傳秒
    uint public constant FIRST_MINTING_DATE = 1640995200;
    // uint time = now;
}

其中在 Solidity 0.7.0 之前我們還可以使用語法 now 得到當前的時間,而 now 與 我們會來會提到的 block.timestamp 是一樣的,因為 now 代表的就是當前的 block timestamp。

由於當前版本已經超過 0.7.0,所以要表示當前時間只能使用 block.timestamp。至於什麼是 block timestamp 之後在全局變量的地方會介紹。

 

【運算子】

以下是運算子,在敘述計算公式時需要注意優先順序,避免不必要的計算錯誤。

PrecedenceDescriptionOperator
1Postfix increment and decrement++, --
 New expressionnew \
 Array subscripting\[\]
 Member access\.\
 Function-like call\(\)
 Parentheses(\)
2Unary minus-
 Unary operationsdelete
 Logical NOT!
 Bitwise NOT~
3Exponentiation**
4Multiplication, division and modulo*, /, %
5Addition and subtraction+, -
6Bitwise shift operators<<, >>
7Bitwise AND&
8Bitwise XOR^
9Bitwise OR\ 
10Inequality operators<, >, <=, >=
11Equality operators==, !=
12Logical AND&&
13Logical OR\\ 
14Ternary operator\ ? \ : \
 Assignment operators=, \=, ^=, &=, <<=, >>=, +=, -=, *=, /=, %=
15Comma operator,

 

【Practice】

  • Practice 1
    • 在 Solidity 0.7.0 之後 now 已經不能使用,我們使用什麼來獲得當前區塊時間。
  • Practice 2
    • 請問1 hour 在 uint 型別下會回傳多少?
  • Practice 3
    • 請問1 ether 是多少 wei?