本篇預計閱讀時間 10 分鐘。
在開始之前先來思考底下的練習題,閱讀後即可練習完成。
練習題
-
練習題 1
-
在 Solidity 0.7.0 之後 now 已經不能使用,我們如何獲得當前區塊時間?
-
-
練習題 2
-
請問 1 hour 在 uint 型別下會回傳多少?
-
-
練習題 3
-
請問 1 ether 是多少 wei?
-
單位
如同前一個章節在整數時的內容,我們沒辦法使用小數來表達一個值,所以在 Solidity 裡面有許多單位可供使用。
表3-1 單位全
使用的範例程式碼如下:
//SPDX-License-Identifier: MIT
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 秒起至現在的總秒數,不考慮閏秒。
//SPDX-License-Identifier: GPL-3.0
contract BlockTime {
//全部都是回傳秒數
uint256 public second = 1 seconds;
uint256 public minute = 1 minutes;
uint256 public hour = 1 hours;
uint256 public day = 1 days;
// 訪問當前區塊時間
function getBlockTime() public view returns (uint256) {return block.timestamp;
}
}
其中在 Solidity 0.7.0 之前我們還可以使用語法 now 得到當前的時間,而 now 與我們未來會提到的 block.timestamp 是一樣的,因為 now 代表的就是當前的 block timestamp。
由於當前版本已經超過 0.7.0,所以要表示當前時間只能使用 block.timestamp 。至於什麼是 block timestamp 之後在全局變量的地方會介紹。
運算子
以下是運算子,在敘述計算公式時需要注意優先順序,避免不必要的計算錯誤。
表 3-2 Solidity Operator Cheet Sheet
Solidity 官方文件 Operator Cheat Sheet
Mathematical Functions
除了以上運算子之外我們還可以使用這兩者數學函式來進行高精度運算:
-
addmod(uint x, uint y, uint k) returns (uint): 以高精度 (arbitrary precision) 計算 (x + y) % k
-
mulmod(uint x, uint y, uint k) returns (uint): 以高精度 (arbitrary precision) 計算 (x * y) % k
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
contract MOD {
function callAddMod() public pure returns(uint) {
return addmod(4, 5, 3); // 0
}
function callMulMod() public pure returns(uint) {
return mulmod(4, 5, 3); // 2
}
}
練習題解答
-
練習題 1
-
在 Solidity 0.7.0 之後 now 已經不能使用,我們使用 block.timestamp 來獲得當前區塊時間。
-
-
練習題 2
-
1 hour 在 uint 型別下會回傳 3600
-
-
練習題 3
-
1 ether 是 1018 wei
-