Data Feeds

In this section we will learn about Chainlink Data Feeds. Here are some reference resources on Data feeds.

Documentation - Chainlink Market and Data Feeds
Chainlink Data Feeds Contract Addresses
Data Feed Contract addresses from the Sepolia Test Network

Token Shop Exercise

In this exercise we will be creating the TokenShop Smart Contract where other people will be able to buy our newly created token.

Open the REMIX IDE and open the second Icon titled - FILE EXPLORER

Example of the File Explorer
Example of creating a new File

Name your new file TokenShop.sol

Below is the code for the Tokenshop.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

// Deploy this contract on Sepolia

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

interface TokenInterface {
    function mint(address account, uint256 amount) external;
}

contract TokenShop {
    
	AggregatorV3Interface internal priceFeed;
	TokenInterface public minter;
	uint256 public tokenPrice = 200; //1 token = 2.00 usd, with 2 decimal places
	address public owner;
    
	constructor(address tokenAddress) {
    	minter = TokenInterface(tokenAddress);
        /**
        * Network: Sepolia
        * Aggregator: ETH/USD
        * Address: 0x694AA1769357215DE4FAC081bf1f309aDC325306
        */
        priceFeed = AggregatorV3Interface(0x694AA1769357215DE4FAC081bf1f309aDC325306);
        owner = msg.sender;
	}

	/**
 	* Returns the latest answer
 	*/
	function getChainlinkDataFeedLatestAnswer() public view returns (int) {
    	(
        	/*uint80 roundID*/,
        	int price,
        	/*uint startedAt*/,
        	/*uint timeStamp*/,
        	/*uint80 answeredInRound*/
    	) = priceFeed.latestRoundData();
    	return price;
	}

	function tokenAmount(uint256 amountETH) public view returns (uint256) {
    	//Sent amountETH, how many usd I have
    	uint256 ethUsd = uint256(getChainlinkDataFeedLatestAnswer());		//with 8 decimal places
    	uint256 amountUSD = amountETH * ethUsd / 10**18; //ETH = 18 decimal places
    	uint256 amountToken = amountUSD / tokenPrice / 10**(8/2);  //8 decimal places from ETHUSD / 2 decimal places from token 
    	return amountToken;
	} 

	receive() external payable {
    	uint256 amountToken = tokenAmount(msg.value);
    	minter.mint(msg.sender, amountToken);
	}

    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }

    function withdraw() external onlyOwner {
        payable(owner).transfer(address(this).balance);
    }    
}
TokenShop.sol Source Code

Deploying the TokenShop Contract

Go to the Deploy & Run Transactions tab within the Remix IDE

This is an example of what your Deploy & Run Transactions should look like

You want to make sure you select the TokenShop.sol Contract (not the TokenInterface called TokenShop.sol) from the contract field in the deployment tab. You will receive an error if you choose the TokenShop's Interface file.

IMPORTANT: SELECT THE TOKENSHOP

After it's deployed to Sepolia, and you see the transaction details in Remix's console sub-window, copy your Token.sol Contract address from the Deployed Contracts UI in Remix

Example of how to copy your Token.sol Contract address

Paste your Token.sol Contract (which you deployed in the previous section) address as the TOKENADDRESS deployment parameter in the deploy tab

Example of token address being included in TokenShop.sol for Deployment

Confirm your transaction in Metamask

Example MetaMask Transaction Confirmation

Giving Token Shop Token-minting rights

On the Token.Sol dropdown in the deployed contracts section, you are looking for the MINTER_ROLE property. Click it to read the data from your smart contract. It should be โ€œ0x9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6โ€

For your knowledge it is the hash of the word โ€œMINTER_ROLEโ€

MINTER_ROLE Call

Next, you are going to run paste that MINTER_ROLE hash string into the grantRole() function along with the TokenShop Address: role: 0x9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6 account: "Your tokenshop address"

Example of grantRole
This is an example of how to copy your TokenShop Contract Address for the account: parameter in last image

Doing this will authorize your TokenShop to mint your newly created token.


We will now double-check and confirm that your TokenShop has indeed been authorized

In your Token.sol Dropdown menu you will want to find the hasRole function. You will open this up and see that it requires two parameters. These are as follows role: 0x9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6 account: "your TokenShop address"

Example of the hasRole call with fields inputted

We are expecting a boolean response of true

Example of completed confirmation of authorization

Now we are going to use the Chainlink USD/ETH price feed that we have referenced inside our TokenShop Contract.

Go to your TokenShop.sol deployed contract dropdown and find the getChainlinkDataFeedLatestAnswer() function. You can hover your mouse over the buttons to see the full name : it should show something like this

Example of getChainlinkDataFeedLatestAnswer
This is an example of a return value from clicking the getChainlinkDataFeedLatestAnswer

Notice the integer returned is quite large, that is because solidity does handle decimal points. Note that you need to know how many decimal points a given feed has. You can find this data in the Price Feeds Documentation (make sure "Show More Details" is checked)

The integer we got back needs to be converted. Since the ETH/USD price feed's data has 8 decimal places, we can see that the price as per the screenshot is $3125.42553378 (divide the returned value by 10^8 to add the decimals back in).


Buying tokens on metamask

Open your Metamask and send 0.01 ETH to your TokenShop.sol Address

The address at the top and beginning with 0xD1 is my TokenShop.sol Address, The amount I chose was .01 ETH
Confirm the transaction

You can check your wallet's token balance on Metamask & through Remix IDE in the Token.sol Deployed Contracts UI.

What it looks like in my imported Tokens list in Metamask
Using REMIX IDE - balanceOf call in the Token.sol dropdown menu

Token Shop Exercise - In this exercise we will be creating the TokenShop.sol Contract where other people will be able to buy our newly created token.

Last updated