0

I have an NFT marketplace contract that sells NFTs with stable price and uses chainlink aggregator for price feed. the contract code is like this:

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

contract NFTSale {
    AggregatorV3Interface internal priceFeed;

    constructor() {
        priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);
    }

    function getLatestPrice() public view returns (int) {
        (, int price,,,) = priceFeed.latestRoundData();
        return price;
    }

    // Calculate the cost in wei of an NFT that costs nft price
    function getNFTPrice() public view returns (uint256) {
        int price = getLatestPrice();
        uint256 costInEther = 10**18 / uint256(price);
        uint256 costInWei = costInEther * 1e18;
        return costInWei;
    }

    function buyNFT() public payable {
        // Check if the sent value is enough to cover the cost of the NFT
        require(msg.value >= getNFTPrice(), "Not enough ether sent");

        // Transfer the NFT to the buyer
    }
}

now i want to create the front-end side of this marketplace that connects to chainlink and buys the NFT. it gets the price feed from chainlink and calculate how much ether should it send to the contract. but the problem is that the transactions are not instant and the price may differ at the time of execution. what is the best way to handle this so that the buy transaction doesn't fail and revert?

1 Answer 1

0

There are several ways to deal with slippage. In this case, the simplest is to send more than is required and return the excess amount to the sender. There isn't a way to prevent it from reverting if the caller doesn't send enough value, though.

Something similar to this

function buyNFT() public payable {
    uint price = getNFTPrice();

    // Check if the sent value is enough to cover the cost of the NFT
    require(msg.value >= price, "Not enough ether sent");

    // If user sent more than the price, return the difference
    uint excessAmount = msg.value - price;
    if (excessAmount > 0) {
        payable(msg.sender).transfer(excessAmount);
    }

    // Transfer the NFT to the buyer
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.