Secure NFT marketplace escrow in Solidity
A marketplace purchase moves an NFT, pays a seller and refunds change, all in one transaction. Get the order wrong and an attacker can re-enter your contract mid-purchase. Here's the pattern I use, with code.
Why escrow?
If a listed NFT stays in the seller's wallet, the seller can transfer it away after listing, and buyers hit failed purchases. Holding listed tokens in the marketplace contract guarantees that what's listed can actually be sold. In my AGENT.EX marketplace, a single mintAndList call mints the ERC-721 straight into escrow.
The reentrancy problem
A purchase makes several external calls: it transfers the NFT (which, with safeTransferFrom, calls onERC721Received on a contract buyer), sends ETH to the seller and refunds the buyer. Each of those hands control to code you don't own.
If your contract updates its own state after those calls, a malicious receiver can call back into buy while the first call is still running and the listing still looks valid. That's a reentrancy attack, the same class of bug behind the 2016 DAO hack.
Checks, Effects, Interactions
Order every state-changing function the same way.
- Checks: validate inputs and conditions (is it listed, did they pay enough).
- Effects: update your contract's state (delete the listing).
- Interactions: only then call other contracts or send ETH.
Then add OpenZeppelin's nonReentrant modifier as a second line of defence:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract MarketplaceEscrow is ReentrancyGuard {
struct Listing {
address seller;
uint256 price;
}
IERC721 public immutable nft;
mapping(uint256 => Listing) public listings; // tokenId => listing
error NotListed();
error InsufficientPayment();
error TransferFailed();
event Sold(uint256 indexed tokenId, address indexed buyer, uint256 price);
constructor(IERC721 _nft) {
nft = _nft;
}
// Listing (moving the NFT into escrow) omitted for brevity.
function buy(uint256 tokenId) external payable nonReentrant {
// 1. Checks
Listing memory item = listings[tokenId];
if (item.seller == address(0)) revert NotListed();
if (msg.value < item.price) revert InsufficientPayment();
// 2. Effects: update state before any external call
delete listings[tokenId];
// 3. Interactions
nft.safeTransferFrom(address(this), msg.sender, tokenId);
(bool paid, ) = item.seller.call{value: item.price}("");
if (!paid) revert TransferFailed();
uint256 refund = msg.value - item.price;
if (refund > 0) {
(bool refunded, ) = msg.sender.call{value: refund}("");
if (!refunded) revert TransferFailed();
}
emit Sold(tokenId, msg.sender, item.price);
}
}
Because the listing is deleted before any external call, a re-entrant buy sees NotListed and reverts. The nonReentrant guard blocks it even earlier. If any transfer fails, the whole transaction reverts, so the buyer never pays without receiving the NFT.
Push vs pull payments
The example pushes ETH to the seller. If the seller is a contract that rejects ETH, every purchase of their item reverts. For many marketplaces that's acceptable, since only that seller's listings are affected. For high-value or permissionless markets, consider pull payments: credit the seller's balance and let them call withdraw(), which isolates failures and simplifies the purchase path.
Tests worth writing
In Hardhat or Foundry.
- An attacker contract that re-enters
buyfromonERC721Received: the purchase must revert or the attack must fail. - Underpayment reverts; overpayment refunds the exact difference.
- Buying the same token twice fails the second time.
- A seller contract that rejects ETH: confirm the behaviour you chose (revert or pull payment).
- Events are emitted with the right arguments, so indexers and front ends stay in sync.
This pattern lowers risk; it doesn't replace an independent audit before mainnet.
FAQ
What is a reentrancy attack in Solidity?
It's when a contract makes an external call before finishing its own state updates, and the called contract calls back in to repeat an action, such as withdrawing or buying, while the original call is still running.
Is ReentrancyGuard enough on its own?
It blocks re-entry into guarded functions, but you should still follow Checks-Effects-Interactions. Cross-function and read-only reentrancy can bypass a guard that doesn't cover every path.
Should a marketplace use safeTransferFrom or transferFrom?
safeTransferFrom makes sure a contract recipient can handle ERC-721 tokens, which prevents NFTs getting stuck. It also triggers a callback on the recipient, which is why the purchase must be reentrancy-safe.