I'm new to smart contracts and testing some functions. I'm trying on buy nft function. it's not working somehow. Even though I've enough balance, the crypto transfer is not happening.
Please find the code below...!
function buyNFT(
uint256 _tokenId,
address _collectionAddress
) public payable nonReentrant {
require(_exists(_tokenId), "Token ID does not exist");
address payable _seller = payable(ownerOf(_tokenId));
require(_seller != msg.sender, "You can't buy your own NFT");
require(
collectionContract.isCollectionBlocked(_collectionAddress) == false,
"Collection is blocked"
);
NFTInfo storage info = nftInfo[_tokenId];
require(info.listedForSale, "NFT is not listed for sale");
// Convert price and tax rate from Ether to Wei for calculation
uint256 tokenPriceInWei = info.tokenPrice * 1 ether;
uint256 taxRateInWei = taxRate * 1 ether / 100;
uint256 taxAmount = tokenPriceInWei.mul(taxRateInWei).div(1 ether);
uint256 totalPrice = tokenPriceInWei.add(taxAmount);
require(msg.value == totalPrice, "Insufficient funds to buy NFT");
// Transfer funds to the seller and tax wallet
(bool sellerTransferSuccess, ) = _seller.call{value: tokenPriceInWei}("");
require(sellerTransferSuccess, "Failed to send token price to seller");
(bool taxWalletTransferSuccess, ) = payable(taxWallet).call{value: taxAmount}("");
require(taxWalletTransferSuccess, "Failed to send tax amount to tax wallet");
_transfer(_seller, msg.sender, _tokenId);
info.listedForSale = false;
transactionHistory.push(
NFTTransaction(
_tokenId,
msg.sender,
info.tokenPrice,
taxAmount,
block.timestamp
)
);
emit NFTBought(
_tokenId,
msg.sender,
info.tokenPrice,
taxAmount,
block.timestamp
);
// Refund any excess amount sent
if (msg.value > totalPrice) {
(bool refundSuccess, ) = payable(msg.sender).call{value: msg.value.sub(totalPrice)}("");
require(refundSuccess, "Failed to refund excess amount");
}
}
I was trying to deploy on BSC and Polygon Amoy.