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?