
单位和全局可用变量(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 的幂。
注意:Solidity 从 0.7.0 版本起已移除 finney 和 szabo 单位。
时间单位(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
2397

被折叠的 条评论
为什么被折叠?



