Units in Solidity¶
There are a number of really handy units in Solidity. We already used some before, but I haven't formally introduced them yet.
It's gonna be a quick lab, but I still want to talk about them.
Monetary or Ether Units¶
Let's start with a problem that we are going to solve.
Suppose you want to make sure a user doesn't send more than 2 ether, but not less than 1 ether.
There are three ways to write that:
require(msg.value >= 1000000000000000000 && msg.value <= 2000000000000000000, "msg.value must be between 1 and 2 ether)
version 2 is a bit easier:
require(msg.value >= 1e18 && msg.value <= 2e18);
version 3 is probably the best and most easily readable:
require(msg.value >= 1 ether && msg.value <= 2 ether);
There are three units available:
ether
which basically multiplies the number literal in front with 1e18
gwei
which stands for 1e9
wei
which stands for 1
It's still good to write simply 1 wei
if you mean "1 wei". It is much easier to catch bugs and it doesn't make a difference in the compiled smart contract size.
Time units¶
Let's suppose you want a crowdsale to start X days after the deployment, and run for 7 days. There are again multiple ways to achieve that:
Version 1:
uint runUntilTimestamp;
uint startTimestamp;
constructor(uint startInDays) {
startTimestamp = block.timestamp + (startInDays * 24 * 60 * 60)
runUntilTimestamp = startTimestamp + (7 * 24 * 60 * 60)
}
If you come from JavaScript you probably already know this dealing with timestamps too well...
Version 2 is much easier:
uint runUntilTimestamp;
uint startTimestamp;
constructor(uint startInDays) {
startTimestamp = block.timestamp + (startInDays * 1 days);
runUntilTimestamp = startTimestamp + 7 days;
}
Arguably, much easier to read. Now on to self-destruction of smart contracts.