Loading...
Hello, World!
In this smart contract i used the Chainlink Api (https://docs.chain.link/docs/using-chainlink-reference-contracts/) to get the ether price, but how can i convert usd in eth?
Ethereum doesn't work with decimals, but it has different units: Eth, Gei and Wei, so we need have all these values in same unit.
The Api return ether price in 8 decimals, and we need 18 decimals:
uint adjust_price = uint(price) * 1e10;
Usd to wei:
uint usd = _amount * 1e18;
To get the final result in unit wei, i multiply usd * (10 ** 18), then i divide for eth adjust_price:
uint rate = (usd * 1e18) / adjust_price;
Math check using $50 usd:
usd = 50 * (10**18)
eth = 4696022434670000000000
result= usd / eth
print(result)
0.01064730858840405
usd = 50 * (10**18)
eth = 4696022434670000000000
result = (usd * (10**18)) / eth
print(result)
1.0647308588404052e+16
You can check convert Wei->Gei->Eth in this page: https://eth-converter.com/
Full code here down:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract PriceConsumerV3 {
AggregatorV3Interface internal priceFeed;
constructor() {
//Rinkeby address
priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
}
function getPriceRate(uint _amount) public view returns (uint) {
(, int price,,,) = priceFeed.latestRoundData();
uint adjust_price = uint(price) * 1e10;
uint usd = _amount * 1e18;
uint rate = (usd * 1e18) / adjust_price;
return rate;
}
}
If you have any question, you can ask me: