Cookies are used for the best experience on my website.

Accept Cookie Policy

No internet detected

Check your connection and try again.

Logo Image

No match found

Buy a coffee

I launched this blog in 1995. Since then, we have published 1603 articles. It's all free and means a lot of work in my spare time. I enjoy sharing knowledge and experiences with you.

Your support

Have you learned something new by reading, listening, or watching my content? With your help, I can spend enough time to keep publishing great content in the future.

Or, select an option below:

A small slice of my data processing time each month

It's ongoing work running this site and what's really great is ongoing support. Here's a sense of what goes into this site: research topics for discussion. Manage the Tech stuff: website, SEO, graphics, email, back-end servers, DNS routing, edge servers. Create advertisements and load the campaigns in Google Ads. Manage the social media forums (Facebook, Reddit, Twitter). Write updates to the blog. Keep GitHub up-to-date.

$4.50 — A large cappuccino at my local

Things just work better with coffee! I like to take the kids to school then grab a cappuccino from my local on the way home before beginning the things that take mental energy.

$8.99 — A month of Netflix for some quiet nights in

A lot of the work on this happens after hours when I should be relaxing on the couch. Help me make it so and I promise to keep off the devices for a bit!

$11.50 — Fund a month of email delivery

This site sends out thousands of emails every month. For that volume and to ensure deliverability, I need to pay MailChimp.

$20 — Pay for one month of AWS storage fees

Websites are not free. The storage alone takes some cash. If you are willing to lighten the burden, we can keep this site up online.

$30 — One hour's pay for a graphics artist

Art doesn't create itself without a hand to guide it. I can't draw, so I need to pay others to help.

$45 — Pay a full-stack web developer for one hour

Much of the work on this site happens on weekends which means giving up time with the kids. Help me pay the developers so I can give my kids more time.

How to Convert From ETH to USD in Solidity

Intro tutorial on how to convert ETH to USD.

Author

Scofield O. IDEHEN


  • 678

  • 4003

  • 1

  • 0

  • 4

In solidity, converting is not just taking the value of one Eth and pegging it against the USD. We must be able to tell solidity how to do it, but since the rate is constantly changing, it is sometimes difficult to know the latest value.

This is where Chainlink oracle comes in.

Chainlink is like a decentralized aggregator that takes a consensus of different nodes, making it tamper-proof and reliable for the network to work with.

Networks were not communicating with the outside world as there were deterministic approaches, making it difficult to get accurate world data into the chain.

Let us dive in and see an example of how to do this. We will be getting the real conversion value of ETH to USD.

First, we create a smart contract.

Full code can be found here:

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceOFETHTOUSD{

    uint minimalValue = 50;
    
    function PriceFeed() public payable{
        msg.value > minimalValue;
    }

    function GetLastestPrice() public view returns (uint){
        AggregatorV3Interface Price = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
        (,int256 price,,,) = Price.latestRoundData();
        return uint (price * 1e18);
    }

    function GetValueInDOllar(uint _ethAmount) public view returns(uint){
        uint ValuePrice = GetLastestPrice();
        uint AmountinDollars =(ValuePrice * _ethAmount) /1e18;
        return AmountinDollars;
    }

}

Here we made a function where we called the payable function which can be called when we carry out a transaction.

Next we said the msg.value > minimalValue which we created a variable for above uint minimalValue = 50;

This makes sense but we only determine the value of USD by making it 50, how do we allow our solidity to talk to the internet and get real value USD to ETH.

Next we will create a new function that will speak to the chainlink and get data from an Oracle and gives us an updated value.

For our function to speak to the oracle we must have two things.

  • Address
  • ABI — Application Binary Interface.

Here we made a function called the payable function called when we carry out a transaction.

To get the chainlink data feed address of ETH — USD conversion we must copy the address, remember for this article we will be using rinkerby testnet data feed which is good enough for our testing.

We also need to get our ABI which we can get from here as it calls the answer from this address we got from Chainlink.

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

Copying whole code makes our work messy, we would need to import it directly from Github, using the import.

    function GetLastestPrice() public view returns (uint){
        AggregatorV3Interface Price = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
        (,int256 price,,,) = Price.latestRoundData();
        return uint (price * 1e18);
    }

Here we created the second function, which will get the priceFeed, and then we want to return the price of ETH to USD inside our contract, and since we have imported the contract, we can call functions from it.

But we only need the price and not everything; solidity is warning us that the other values are unused.

Let us make our syntax much more readable and straightforward.

We called the AggregatorV3Interface Price = AggregatorV3Interface( address ) solidity knows there are other variables which we skipped by using the comma.

We ask solidity to return the price * 1e18.

Do not worry about 1e18 as we convert using the smallest value, which wei.

Remember, at this point; we can only get the price in ETH, which is not what we have set out to do.

Let’s create a new function that allows us to convert the ETH to USD.

    function GetValueInDOllar(uint _ethAmount) public view returns(uint){
        uint ValuePrice = GetLastestPrice();
        uint AmountinDollars =(ValuePrice * _ethAmount) /1e18;
        return AmountinDollars;
    }

Here we created a function that called an argument of _ethAmount.

We want it to return the converted value, which we called here by saying whatever we get in GetLastestPrice() should be called ValuePrice we said the AmountinDollars is equal to (PriceEth * _ethAmount). _ethAmount is the value the user inputs inside the contract.

Return the value.

Conclusion 🔗

Here we went through the steps to follow when converting. Although we did not touch on many best practices, we saw how to convert from ETH to USD. You can go ahead and try other conversion values like ETH to BTC.

This license allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, so long as attribution is given to the creator. The license allows for commercial use. If you remix, adapt, or build upon the material, you must license the modified material under identical terms.