Hey everyone, I’m stuck on adding a percentage fee to my NFT marketplace. I’ve got the basic stuff working fine, but now I want to add a 2.5% fee on every sale instead of the fixed fee I had before.
Here’s what I’ve tried:
function sellNFT(address nftContract, uint256 itemId, uint256 fee) public payable {
uint256 price = items[itemId].price;
uint256 tokenId = items[itemId].tokenId;
require(msg.value == price, "Pay the full price to buy");
items[itemId].seller.transfer(msg.value);
IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId);
items[itemId].owner = payable(msg.sender);
items[itemId].sold = true;
soldItems.increment();
payable(owner).transfer(fee);
}
I see the issue in your code. The problem is likely in how you’re handling the fee calculation and transfer. Instead of calculating the fee on the frontend and passing it as an argument, you should calculate it within the smart contract itself. This ensures accuracy and prevents potential manipulation.
Here’s a suggested modification to your sellNFT function:
This approach calculates the fee within the contract, ensuring it’s always correct. Remember to update your frontend code accordingly, removing the fee calculation and parameter. This should resolve your transfer error.
hey there strummingmelody! i’m curious about your nft marketplace project. it sounds pretty cool! have you considered using safeMath for your calculations? it could help prevent any overflow issues. also, what kind of nfts are you planning to list on your marketplace? i’d love to hear more about that!
i noticed you’re doing the fee calculation on the frontend. that could be risky, ya know? what if someone tries to mess with it? maybe you could move that calculation into the smart contract itself? that way it’s all handled securely on-chain.
oh, and have you thought about adding events to your contract? they could be super helpful for tracking sales and fees. just a thought!
what’s been the most challenging part of building this so far? i’m always interested in hearing about other devs’ experiences. keep us updated on how it goes!
hey, i think ur frontend fee calc is the issue. do it onchain instead. change it to: fee = (price * 25) / 1000; then compute sellerAmount = price - fee. that should fix it. good luck!