文章目录
- 单位和全局可用变量(Units and Globally Available Variables)
- 以太单位(Ether Units)
- 时间单位(Time Units)
- 保留关键字
单位和全局可用变量(Units and Globally Available Variables)
以太单位(Ether Units)
在 Solidity 中,数字字面量可以使用 wei
、gwei
或 ether
作为后缀,指定以太的子单位。如果数字没有后缀,则默认单位为 wei
。
assert(1 wei == 1);
assert(1 gwei == 1e9); // 1 gwei = 10^9 wei
assert(1 ether == 1e18); // 1 ether = 10^18 wei
这些单位的后缀只是对数字进行以 10 为底的幂次乘法。
注意:
finney
和szabo
这两个单位在 Solidity 0.7.0 版本中被移除。
时间单位(Time Units)
数值字面量可以使用 seconds
、minutes
、hours
、days
和 weeks
作为后缀,指定时间单位。这些单位的基础单位是 seconds
,并且被简单地定义为:
1 == 1 seconds
1 minutes == 60 seconds
1 hours == 60 minutes
1 days == 24 hours
1 weeks == 7 days
注意
1.这些单位在日历计算中可能会导致误差,因为一年不总是 365 天,甚至一天也不总是 24 小时(例如由于闰秒的影响)。
2.由于闰秒无法预测,要实现精准的日历计算,需要使用外部预言机(oracle)提供更新的时间数据。
3.years
单位在 Solidity 0.5.0 版本中被移除,原因同上。
以下代码是不允许的:
uint duration = 3;
uint timePeriod = duration days; // 错误:无法对变量使用时间单位后缀
如果想要让函数参数表示天数,正确的做法是:
function f(uint start, uint daysAfter) public {if (block.timestamp >= start + daysAfter * 1 days) {// 逻辑代码}
}
保留关键字
以下关键字在 Solidity 中是保留的。它们可能在未来成为语法的一部分:
after
、alias
、apply
、auto
、byte
、case
、copyof
、default
、define
、final
、implements
、in
、inline
、let
、macro
、match
、mutable
、null
、of
、partial
、promise
、reference
、relocatable
、sealed
、sizeof
、static
、supports
、switch
、typedef
、typeof
、var
。