2022-07-15 出版 KryptoCamp 撰稿

【單位】
如同前一個章節在整數時的內容,我們沒辦法使用小數來表達一個值,所以在 Solidity 裡面有許多單位可供使用。
Unit | wei value | wei | ether value |
---|---|---|---|
wei | 1 wei | 1 | 10^-18 ETH |
kwei | 10^3 wei | 1,000 | 10^-15 ETH |
mwei | 10^6 wei | 1,000,000 | 10^-12 ETH |
gwei | 10^9 wei | 1,000,000,000 | 10^-9 ETH |
microether | 10^12 wei | 1,000,000,000,000 | 10^-6 ETH |
milliether | 10^15 wei | 1,000,000,000,000,000 | 10^-3 ETH |
ether | 10^18 wei | 1,000,000,000,000,000,000 | 1 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 之後在全局變量的地方會介紹。
【運算子】
以下是運算子,在敘述計算公式時需要注意優先順序,避免不必要的計算錯誤。
Precedence | Description | Operator | ||
---|---|---|---|---|
1 | Postfix increment and decrement | ++, — | ||
New expression | new \ | |||
Array subscripting | \[\] | |||
Member access | \.\ | |||
Function-like call | \(\) | |||
Parentheses | (\) | |||
2 | Unary minus | – | ||
Unary operations | delete | |||
Logical NOT | ! | |||
Bitwise NOT | ~ | |||
3 | Exponentiation | ** | ||
4 | Multiplication, division and modulo | *, /, % | ||
5 | Addition and subtraction | +, – | ||
6 | Bitwise shift operators | <<, >> | ||
7 | Bitwise AND | & | ||
8 | Bitwise XOR | ^ | ||
9 | Bitwise OR | \ | ||
10 | Inequality operators | <, >, <=, >= | ||
11 | Equality operators | ==, != | ||
12 | Logical AND | && | ||
13 | Logical OR | \ | \ | |
14 | Ternary operator | \ ? \ : \ | ||
Assignment operators | =, \ | =, ^=, &=, <<=, >>=, +=, -=, *=, /=, %= | ||
15 | Comma operator | , |
【Practice】
- Practice 1
- 在 Solidity 0.7.0 之後
now
已經不能使用,我們使用什麼來獲得當前區塊時間。
- 在 Solidity 0.7.0 之後
- Practice 2
- 請問1 hour 在
uint
型別下會回傳多少?
- 請問1 hour 在
- Practice 3
- 請問1 ether 是多少 wei?