# ERC-721 safeTransferFrom & onERC721Received Reentrancy Audit

> Eliminate _safeMint and safeTransferFrom onERC721Received callback reentrancy: max-per-wallet mint bypasses, Dutch-auction refund drains, and EIP-1153 guards.

Canonical: https://nftvenueledger.com/protocols/erc721-safetransferfrom-onerc721received-callback-reentrancy
Last updated: 2026-11-14T19:43:05.524Z

**Publication:** NFTVenue Ledger
**Category:** Erc721 Erc1155 Eip712 Permit Security
**Published:** 2026-11-13T19:25:25.915Z
**Author:** Dr. Devon Kurosawa, PhD (PhD in Distributed Systems & Cryptographic Protocol Verification)
**Reviewer:** Not recorded

## Answer-first summary

OpenZeppelin _safeMint and safeTransferFrom hand execution control directly to untrusted receiver contracts via onERC721Received, causing classic CEI violations across NFT venues.

## Key takeaways

- OpenZeppelin _safeMint and safeTransferFrom perform an untrusted external CALL to onERC721Received whenever the recipient has bytecode—making CEI ordering mandatory.
- Updating minted counters, allowlist bitmaps, or collateral balances AFTER _safeMint/safeTransferFrom enables single-transaction supply drain and lending over-borrow exploits.
- Cancun EIP-1153 ReentrancyGuardTransient slashes reentrancy-lock overhead from ~5,100 gas down to ~300 gas while leaving zero storage dirt.
- Auctions and liquidations must never let an untrusted bidder/borrower revert settlement via a malicious onERC721Received hook—use pull-claim patterns or non-callback transferFrom.

## Related financial entities

- **Checks-Effects-Interactions (CEI) Security Pattern** (CEI-SEC) — product: Foundational programming design pattern in smart contract development preventing reentrancy attacks by executing internal state updates before external calls.
- **ERC-2981 NFT Royalty Standard** (ERC-2981) — product: Universal Ethereum standard allowing contracts to signal a royalty payout amount and receiver address upon token sales.
- **Seaport Marketplace Protocol Standard** (SEAPORT) — product: Open-source, highly optimized marketplace contract suite for efficiently buying and selling fungible and non-fungible tokens.

## Analysis

Ask junior Solidity developers to name an untrusted external call, and everyone spots `msg.sender.call{value: eth}("")`—yet dozens of audited NFT mints, lending escrows, and staking vaults got drained for millions (`HypeBears, Revest Finance, Omni NFT lending, Sudoswap-fork forks`) because developers treated **`_safeMint(to, tokenId)`** and **`safeTransferFrom(from, to, tokenId)`** as "trusted internal library helpers"! In reality, per **EIP-721**, whenever `to.code.length > 0`, `_checkOnERC721Received` makes an **untrusted external `CALL`** forwarding `63/64` of remaining gas to `IERC721Receiver(to).onERC721Received(...)`!

Anchored in our [EIP-712, Permit2 & proxy security master guide](/protocols/eip712-permit2-erc721-royalty-proxy-timelock-security-2026), enforcing the **[Checks-Effects-Interactions (CEI) security pattern](/tokens/cei-smart-contract-security-pattern)** and Cancun **EIP-1153 `ReentrancyGuardTransient`** is mandatory across every NFT mint, auction, and collateral vault in our [marketplaces directory](/marketplaces) (from [Azuki](/marketplaces/azuki) and [Basepunks](/marketplaces/basepunks) to [Based Punks](/marketplaces/based-punks) and [Beanz Officia](/marketplaces/beanz-officia)).

## Three Real-World `onERC721Received` Reentrancy Exploit Patterns!

1. **Pattern A — Allowlist / Max-Per-Wallet Mint Cap Bypass (`HypeBears Style`)**:
 `require(!hasMinted[msg.sender]); _safeMint(msg.sender, nextId++); hasMinted[msg.sender] = true;`
 Because `hasMinted[msg.sender] = true` sits **after** `_safeMint`, the attacker's `onERC721Received` callback re-invokes `mint` 100 times in a recursive loop while `hasMinted[msg.sender]` is still `false`—minting out the entire collection in 1 transaction!
2. **Pattern B — `for`-Loop Batch Mint Same-Token-ID Overwrite / Supply Under-Count**:
 If a contract caches `uint256 id = totalSupply` in a local stack variable before a loop calling `_safeMint`, reentering inside `onERC721Received` reads the stale `totalSupply` storage variable before the outer frame writes `totalSupply += qty`!
3. **Pattern C — NFT Lending / Escrow Collateral Double-Withdraw (`Omni Style`)**:
 A borrower repays debt or liquidates a sub-position, triggering `collateralNFT.safeTransferFrom(vault, borrower, id)` *before* updating `userCollateralCount[borrower]--` or health factor. Inside `onERC721Received`, the borrower's contract still registers healthy collateral and **borrows the entire WETH lending pool with zero backing**!

![onERC721Received recursive callback attack vs Checks-Effects-Interactions + EIP-1153 TSTORE defense](/api/figure?type=flow&title=Closing%20the%20_safeMint%20%2F%20safeTransferFrom%20Callback%20Window&subtitle=Enforcing%20state%20completion%20and%20transient%20reentrancy%20locks%20prior%20to%20untrusted%20receiver%20hooks&steps=1.%20TSTORE%20Lock%20%28100g%29%3A%3AnonReentrant%20modifier%20sets%20EIP-1153%20transient%20lock%20slot%20%3D%201%7C2.%20Strict%20Checks%3A%3AVerify%20Merkle%20allowlist%2C%20msg.value%2C%20maxSupply%20%26%20health%20factor%7C3.%20Commit%20All%20Effects%3A%3AWrite%20hasMinted%20%3D%20true%2C%20nextTokenId%20%2B%3D%20qty%2C%20debt%20%3D%200%20to%20storage!%7C4.%20Last%20%20safeTransfer%3A%3ACall%20_safeMint%20%2F%20safeTransferFrom%20ONLY%20at%20final%20line%3B%20clear%20TSTORE&metrics=CALLBACK%20SELECTOR%3A%3A0x150b7a02%3A%3AIERC721Receiver.onERC721Received%7CEIP-1153%20GUARD%20GAS%3A%3A~200%20Gas%20Total%3A%3A100g%20TSTORE%20set%20%2B%20100g%20TSTORE%20clear!%7CLEGACY%20SSTORE%20GUARD%3A%3A~5%2C000%20Gas%3A%3A25x%20costlier%20than%20Cancun%20transient%20lock%7CBATCH%20MINT%20SPEC%3A%3AERC-721A%3A%3AUpdates%20_currentIndex%20BEFORE%20callback!)

## Push vs Pull Settlement: What Happens When `onERC721Received` Intentionally Reverts?

Reentrancy isn't the only weapon inside `onERC721Received`! Suppose an English NFT auction contract settles bids by automatically calling `nft.safeTransferFrom(escrow, winningBidder, id)` or refunding outbid bidder A via `prevBidder.call{value: prevBid}("")` when bidder B bids higher:
- A malicious bidder deploys a contract whose `onERC721Received` (or `receive`) **unconditionally `revert`s** (`or burns 50,000,000 gas in an infinite loop!`)!
- Suddenly, **nobody can outbid the attacker**, or **the seller can never finalize the auction to collect ETH** (`Permanent Auction Griefing DoS`)!
- **Mandatory Pull-Over-Push Pattern**: English auctions and [Seaport](/tokens/seaport-marketplace-protocol)-style clearinghouses credit unsuccessful bids to an internal claimable `pendingWithdrawals[bidder]` mapping (or wrap to `WETH`) and isolate `transferFrom` (non-callback!) fallback paths when settlement finality is required!

## ERC-721 Transfer & Mint Security Comparison Matrix

| Solidity Transfer Function | Invokes `0x150b7a02` Callback? | Reentrancy Risk | Receiver Revert DoS Risk | Correct Protocol Usage |
| :--- | :--- | :--- | :--- | :--- |
| `_mint(to, id)` / `transferFrom` | **No** (Zero external call) | **Zero** | **Zero** | Forced liquidations & auction clears |
| `_safeMint(to, id)` + **No CEI** | **Yes** (if `to.code.length > 0`) | **CRITICAL DRAIN** | High in batch loops | **NEVER DEPLOY** |
| `_safeMint` + **CEI + EIP-1153 Guard** | **Yes** | **Blocked (0%)** | Self-only (Caller reverts own mint) | Standard retail NFT drops |
| **ERC-721A `_safeMint(to, qty)`** | **Yes** (per token, post-index update) | Blocked on supply; **add `nonReentrant`** for custom mappings! | Self-only | Low-gas multi-mint drops ([Azuki](/marketplaces/azuki)) |

![EVM gas overhead of reentrancy protection from OpenZeppelin SSTORE ReentrancyGuard to Cancun EIP-1153 TSTORE](/api/figure?type=bars&title=Reentrancy%20Guard%20Gas%20Cost%3A%20Legacy%20SSTORE%20vs%20EIP-1153&subtitle=Additional%20gas%20paid%20per%20NFT%20mint%20or%20marketplace%20swap%20to%20lock%20all%20callback%20entrypoints&steps=Unprotected%20_safeMint%3A%3A0%20guard%20gas%20-%3E%20100%25%20vulnerable%20to%20recursive%20callback%20exploits!%7CCold%20SSTORE%20Guard%20%280-%3E1-%3E0%29%3A%3A~22%2C100%20gas%20pre-refund%20if%20slot%20uninitialized%20%28anti-pattern!%29%7COZ%20Warm%20SSTORE%20%281%20-%3E%202%20-%3E%201%29%3A%3A~5%2C100%20gas%20%28classic%20_status%20%3D%201%20initialized%20in%20constructor%29%7CCancun%20EIP-1153%20Transient%3A%3A~220%20gas%20TOTAL%20%28TLOAD%20%2B%20TSTORE%201%20%2B%20TSTORE%200%20-%3E%20zero%20SLOAD%2FSSTORE!%29&metrics=GAS%20REDUCTION%3A%3A-95.6%25%20Guard%20Gas%3A%3ACancun%20TSTORE%20vs%20warm%20SSTORE%20lock%7CCROSS-CONTRACT%20LOCK%3A%3AShared%20Locker%3A%3AUniswap%20v4%20%2F%20Vault%20global%20transient%20lock%7CREAD-ONLY%20GUARD%3A%3AreentrancyGuardEntered%28%29%3A%3AProtects%20view%20price%20oracles%20too!%7CGAS%20CAP%20ON%20HOOK%3A%3ABounded%20Stipend%3A%3ABlocks%2063%2F64%20gas-griefing%20bombs)

## Cancun EIP-1153 `ReentrancyGuardTransient` Cost & Cross-Function Lock Invariant

Why must `nonReentrant` be applied to **every state-mutating AND price-reading view function** sharing collateral state, rather than just `mint` alone? Because **Cross-Function Reentrancy** enters Function B (`e.g., borrow or transfer `) from Function A's `onERC721Received` callback!

```formula
1) Cross-Function State Invariant Across Untrusted Callback Boundary:
 Let I(S) denote protocol solvency & supply invariant (e.g., Minted[u] <= Cap && Debt[u] <= LTV * Collateral[u]).
 REQUIRED BEFORE ANY safeTransferFrom / _safeMint / ETH call:
 I(S_pre_callback) == TRUE AND Transient_Lock_Slot(tload(LOCK_SLOT)) == LOCKED (1)

2) Cancun EIP-1153 Transient Guard Gas Savings:
 Legacy SSTORE Guard (1 -> 2 -> 1): G_legacy = SLOAD_cold(2,100) + SSTORE_dirty(2,900) + SSTORE_reset(100) = 5,100 gas
 EIP-1153 TSTORE Guard (0 -> 1 -> 0): G_transient = TLOAD(100) + TSTORE(100) + TSTORE_clear(100) = 300 gas (-94.1%!)

Worked Cross-Function Lending Audit:
 Vault applies nonReentrantTransient to deposit, withdrawNFT, borrow, AND checks !reentrancyGuardEntered inside getAccountHealth
 => Borrower's onERC721Received callback during withdrawNFT calls borrow -> Instant Revert ReentrancyGuardReentrantCall at 300 gas!
```

## Extending Callback Defenses to ERC-1155 Batch Hooks

While ERC-721 callbacks only trigger when the *recipient* is a contract, **ERC-1155 unconditionally requires `onERC1155Received` / `onERC1155BatchReceived` on EVERY transfer** (`there is NO non-safe transferFrom in ERC-1155!`)—creating acute gas-stipend DoS vectors on marketplaces examined next in [ERC-1155 batch transfer gas-stipend DoS](/protocols/erc1155-batch-transfer-hook-gas-stipend-dos-marketplace) and [setApprovalForAll blast radius](/protocols/erc721-erc1155-setapprovalforall-operator-blast-radius) inside our [EIP-712, Permit2 & Proxy Security hub](/topics/erc721-erc1155-eip712-permit-security).

## Frequently asked questions

### Why did _safeMint cause so many max-supply NFT mint hacks?

Developers assumed _safeMint only wrote storage like _mint, overlooking that _safeMint invokes to.onERC721Received BEFORE returning—allowing a smart-contract minter to re-call mint recursively before hasMinted[msg.sender] updated.

### Does Azuki ERC-721A prevent all _safeMint reentrancy bugs automatically?

ERC-721A updates _currentIndex and ownership state before invoking onERC721Received, protecting totalSupply; however, custom per-wallet allowlist mappings written in your wrapper mint function after _safeMint STILL require CEI or nonReentrant!

### When should a smart contract use transferFrom instead of safeTransferFrom?

During forced protocol actions such as collateral liquidations or auction settlements where a malicious borrower/bidder contract could intentionally revert onERC721Received to block liquidation indefinitely.

### How does EIP-1153 ReentrancyGuardTransient improve on classic ReentrancyGuard?

EIP-1153 uses transient memory-like TLOAD/TSTORE opcodes (100 gas each) that automatically wipe at transaction end, saving ~4,800 gas per call compared to warm storage SSTORE locks.


## Source URLs

- https://eips.ethereum.org/EIPS/eip-721
- https://eips.ethereum.org/EIPS/eip-1153
- https://docs.openzeppelin.com/contracts/5.x/api/utils#ReentrancyGuardTransient

## Citation

- APA: Dr. Devon Kurosawa, PhD. (2026). ERC-721 safeTransferFrom & onERC721Received Reentrancy: Max-Supply Bypass & Escrow Drains. NFTVenue Ledger. https://nftvenueledger.com/protocols/erc721-safetransferfrom-onerc721received-callback-reentrancy
- Canonical article: [ERC-721 safeTransferFrom & onERC721Received Reentrancy: Max-Supply Bypass & Escrow Drains](https://nftvenueledger.com/protocols/erc721-safetransferfrom-onerc721received-callback-reentrancy)
- Site research index: [NFTVenue Ledger](https://nftvenueledger.com/llms-full.txt)
