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?
10^18 wei = (x / 10^8) USD, wherex = 398143000000then10 USD = 10^18 * 10 * 10^8 / x wei = 10^27 / 398143000000 wei = 2511660383329607 wei. – Ismael Dec 17 '21 at 06:33