Why Multiply and Divide by 1đť‘’18 in Solidity?

prince_ad7e7c212e5c5ecf40

prince

Posted on November 22, 2024

Why Multiply and Divide by 1đť‘’18 in Solidity?

When developing smart contracts for decentralized finance (DeFi), precision handling is crucial. A common pattern you’ll encounter is multiplying and then dividing by 1e18 in calculations involving token prices, amounts, and values. At first glance, this may seem redundant—but it serves a critical purpose.

-Ethereum and DeFi systems heavily rely on consistent precision across calculations:
Ethereum’s 18 Decimal Standard: Most tokens, including ERC20 tokens, use 18 decimal places for their values.
For example, 1 ETH is represented as 1 Ă— 10 ^18 . This standard ensures consistency across token operations.

-Chainlink Price Feed Precision: Chainlink, a popular oracle for fetching token prices, provides values with 8 decimal places (e.g., 1000 Ă— 10 ^8 ).
This mismatch in precision needs to be addressed when integrating Chainlink data with Ethereum-based systems.

The Problem: Mismatched Precisions Imagine you want to calculate the USD value of 1 ETH: Token Price from Chainlink = 1000 Ă— 10^8
Token Amount = 1Ă—10 ^18.
If you directly multiply these values:

USD Value = 1000 × 10^8 * 10^18

The result has 26 decimal places, far exceeding Ethereum’s standard of 18. Using this value in other parts of your contract—such as calculating collateralization or health factors—can lead to inconsistencies and errors.

The Solution:
1.Multiply the price by 1e10 to bring Chainlink's 8-decimal precision up to 18-decimal precision.

-Adjust price precision: 1000 10^8 * 10^10 = 1000 10^18

2.Multiply the result by the token amount

-Multiply by the token amount of 1ETH:
(1000*10^18) *(1*10^18) = 1000 * 10^36

  1. Divide by 1e18 to normalize the final value back to 18 decimals

Note 10e8 = 10^8 0r 10 raised to the power of 8.
10e18 = 10^18 or 10 raised to the power of 18.

An Example Let’s calculate the USD value of 1 ETH at $1,000:

  1. Inputs: -Price = 1000 Ă— 10^8 (from Chainlink) -Amount = 1 Ă— 10^18 (1 ETH).

Step-by-Step Calculation:

-Adjust price precision: 1000 10^8 * 10^10 = 1000 10^18
-Multiply by the amount:(1000*10^18) *(1*10^18) = 1000 *
10^36
-Normalize precision:
USD Value = 1000 * 10^36 / 10^18 = 1000 * 10^18

1000 * 10^18 represents $1,000 in 18-decimal precision.
NOTE:
Without dividing by 1e18, the result would have 36 decimals, making it incompatible with other values that adhere to Ethereum’s 18-decimal standard.

đź’– đź’Ş đź™… đźš©
prince_ad7e7c212e5c5ecf40
prince

Posted on November 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related