Smart contracts require deterministic calculations. Many programming languages like Javascript employ floating point arithmetic, which is convenient to work with and simply gives us a "number" type for all numbers. However, the way computers store floating point numbers creates the possibility of rounding errors when doing calculations. Any kind of rounding error would be a catastrophe in a smart contract, so Solidity employs fixed point arithmetic.
Smart contract developers must understand their level of precision and treat it as their atomic unit of calculation. Ethereum defines the Ether, Gwei, and Wei where one Ether is equal to 1e18 Wei. This precision becomes especially apparent when working with ERC20 tokens and Chainlink price feeds. You might be surprised when you try to mint 1 token in your ERC20 contract and only receive a fraction of a coin in your wallet. Similarly, a Chainlink price feed will return a large value for a coins price in USD. In both cases this is because the level of precision in the values must be accounted for. Many price feeds return with 8 points of precision, which must be adjusted to achieve a constant level of precession across calculations. Defining precision levels as constants in your smart contract is a good practice.
No comments:
Post a Comment