[Ethereum] How to set dynamic buy and sell price for the token

contract-developmentpricesolidity

I have built a simple erc-20 token. I used the code given on ethereum.org code as a reference. There they have talked about setting the price of my token. But how do I set it dynamically, as in automatically change the buy and sell price based on market ? Where do I get this price from ? Ethereum.org has said something about data feeds, what is that ? and How do you use it ?

Best Answer

To get the price

First you'll have to get the price. You can get price easily by using Chainlink Price Feeds.

// note, this is using node.js syntax. see the docs for remix syntax
pragma solidity ^0.6.7;

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

contract PriceConsumerV3 {

    AggregatorV3Interface internal priceFeed;

    /**
     * Network: Kovan
     * Aggregator: ETH/USD
     * Address: 0x9326BFA02ADD2366b30bacB125260Af641031331
     */
    constructor() public {
        priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);
    }

    /**
     * Returns the latest price
     */
    function getLatestPrice() public view returns (int) {
        (
            uint80 roundID, 
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        // If the round is not complete yet, timestamp is 0
        require(timeStamp > 0, "Round not complete");
        return price;
    }
}

Otherwise you can use an oracle to make an API call to an API with the price.

To make it dynamic

You'll need some off-chain service making a call to update periodically. You could use something like the Chainlink alarm clock, or Chainlink cron initiator for it to be automatic. You'd set one of these up to call your price updating contract (deployed from above) at the intervals you'd please.

Hope it helps.