The Concept Of Time In Ethereum
While the clock on a computer ticks at least once a millisecond, the clock on a blockchain only ticks as often as blocks are added to the chain. The concept of time in blockchain can be perplexing for new Solidity developers. The way they compare time can be incorrect or even lead to a Front-running attack, so in this article, I’d like to shed some light on the subject and try to clear the air.
Most programming languages allow programmers to check and use time, typically provided by the computer on which the program is running. The following python script, for example, displays the current time as it runs.
This is what the program’s output would look like.
Even though the change is minimal, there is a change of time as the program executes. On the other hand, if we look at the Solidity equivalent code:
The time attribute would be the same for all events emitted by this function as it is set by block.timestamp.
Solidity’s block.timestamp
is a type of Special Variables and Functions; they are always present in the global namespace and are primarily used to provide blockchain information. The block.timestamp
returns the current block timestamp in seconds since the UNIX epoch as a unit256 number.
As a result, the block.timestamp
property will be identical for each transaction on the block. We can never expect an exact second due to the low-resolution clock of blockchain; therefore, our time comparison should always include greater or less than, rather than equal.
It’s also worth remembering that block creators can influence the time a block is created and the order in which transactions are processed to their benefit, leading to a Front-Running attack, a known Ethereum protocol issue. However, this is only possible if the block creator successfully makes a block, which is extremely difficult. As a result, while these problems are not a substantial weakness of smart contracts, they are crucial to address while considering designs and incentives.
In conclusion, it would be prudent not to take non-trivial decisions based on the time provided by the blockchain. When comparing time instead of exact seconds, use greater than or less than.
Join Coinmonks Telegram Channel and Youtube Channel learn about crypto trading and investing