1

I'm using Chainlink's pricefeed to get the latest ETHUSD price.

The value returned is 10**8, i.e. if the price of ETHUSD is 3981.43 then the value will be 398143000000.

How can I calculate the WEI value of $10 of ETH without causing an arithmetic overflow error?

ETHUSD = 398143000000
$10 = 0.002511660383329608 ETH
$10 = 2511660383329608 WEI // How can I get this?

Doing the following results in "reverted with panic code 0x11 (Arithmetic operation underflowed or overflowed outside of an unchecked block)":

uint256 ethUsdPrice = 398143000000;
uint256 usdTicketPrice = 10;
uint256 ethTicketPrice = ticketPrice*(10**8) / ethUsdPrice*(10**18);

I was hoping since I don't divide into decimals this would be OK.

In JavaScript you can see this is the correct calculation:

// Dividing down into decimals and then up.
(10 / (398143000000 / 10**8)) * 10**18 = 2511660383329608
// Dividing without decimals.
10*(10**8) / 398143000000*(10**18) = 2511660383329608

I'm using Solidity 0.8.7.

P.S. Seems like there are similar questions but they'd result in an overflow too?

1
  • We have that 10^18 wei = (x / 10^8) USD, where x = 398143000000 then 10 USD = 10^18 * 10 * 10^8 / x wei = 10^27 / 398143000000 wei = 2511660383329607 wei.
    – Ismael
    Dec 17 '21 at 6:33
2

If the value of ethUsdPrice is with 8 decimals, and it equals to 1 ether, it means:

1 ether = (ethUsdPrice / 10^8) dollars

We isolate 1 dollar from the equation and get:

1 dollar = 1 ether * 10^8 / ethUsdPrice

In Solidity, to maintain accuracy, we always first of all do multiplication and only after doing division - otherwise, we will lose the remainder for the operation. For example 2/3 = 0.

So if that's the value of 1 dollar, we just need to multiply it by usdTicketPrice (10), so your final calculation will be:

uint256 ethTicketPrice = usdTicketPrice * 1 ether * 10**8 / ethUsdPrice.

1
  • 1
    This is great thanks!
    – Dominic
    Dec 17 '21 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.