Handling tokens with varying decimal in Solidity.

In Solidity, handling tokens with varying decimals can be challenging, especially when performing arithmetic operations across different token types. A common solution is to normalize token amounts to a consistent decimal base, often 18 decimals, which is the standard used by Ether and many ERC-20 tokens.

ERC20 tokens can have different decimal places. For example, USDT (Tether) uses 6 decimals, whereas many other tokens like WETH use 18 and some others even more decimals . Unfortunately, it is very common for devs to implement bugs due to that.

However, there is a pretty trivial solution which can be used across codebases:
A normalization function can adjust token amounts to a common decimal base (18 decimals in this case). This function either scales up or scales down the token amount based on the number of decimals the token uses, ensuring the final amount will be always displayed with 18 decimals. Of course this can result in a minor truncation if tokens >18 decimals are being used, this must be considered.

Here's a simple implementation in Solidity: