Free 30-min Web3 Consultation
Book Now
Smart Contract Security Audits
Learn More
Custom DeFi Protocol Development
Explore
Full-Stack Web3 dApp Development
View Services
Free 30-min Web3 Consultation
Book Now
Smart Contract Security Audits
Learn More
Custom DeFi Protocol Development
Explore
Full-Stack Web3 dApp Development
View Services
Free 30-min Web3 Consultation
Book Now
Smart Contract Security Audits
Learn More
Custom DeFi Protocol Development
Explore
Full-Stack Web3 dApp Development
View Services
Free 30-min Web3 Consultation
Book Now
Smart Contract Security Audits
Learn More
Custom DeFi Protocol Development
Explore
Full-Stack Web3 dApp Development
View Services
LABS
Glossary

ERC721 Receiver

An ERC721 Receiver is a smart contract interface that must be implemented to safely accept ERC-721 non-fungible tokens (NFTs) via transfers.
Chainscore © 2026
definition
SMART CONTRACT INTERFACE

What is ERC721 Receiver?

A technical standard for smart contracts that can safely accept non-fungible tokens (NFTs) on the Ethereum blockchain.

An ERC721 Receiver is a smart contract interface, defined by the ERC721 standard, that a contract must implement to safely accept non-fungible tokens (NFTs) sent via the safeTransferFrom function. The core of this interface is the onERC721Received function, which is automatically called by the sending contract to notify the recipient. This callback mechanism ensures the receiving contract is aware of and prepared to handle the incoming NFT, preventing tokens from being permanently locked in contracts that cannot interact with them.

The primary purpose of this interface is security and interoperability. Without it, an NFT sent to a contract that lacks the logic to manage it could become irretrievably stuck. The onERC721Received function must return a specific magic value (0x150b7a02) to confirm successful receipt. This return value acts as a cryptographic handshake, signaling to the ERC721 token contract that the transfer was intentional and the recipient is a valid, aware destination. This prevents accidental loss of assets.

Common use cases for ERC721 Receiver contracts include NFT marketplaces (for escrow during listings), auction houses, staking vaults, and composability layers like meta-universes or lending protocols. For example, when you list an NFT on a marketplace, it is often transferred to the marketplace's smart contract, which must implement onERC721Received to custody the asset. Similarly, a wallet contract or a DAO treasury that wishes to hold NFTs must be a receiver to accept them via standard safe transfer methods.

Developers implementing this interface must ensure the onERC721Received function handles logic such as updating internal accounting, emitting events, or triggering subsequent actions. It receives four parameters: the operator (address initiating the transfer), the from address, the tokenId, and arbitrary data. The function's execution is a critical point where custom business logic—like validating the sender or integrating the NFT into a game world—can be securely executed as part of the atomic transfer process.

It is important to distinguish between contract accounts and externally owned accounts (EOAs). Standard user wallets (EOAs) cannot implement smart contract interfaces; they receive NFTs by default without needing the receiver pattern. The safeTransferFrom function will revert if the to address is a contract that does not return the correct magic value, while the basic transferFrom function bypasses this check, transferring to any address but with the associated risk of locking tokens in incompatible contracts.

how-it-works
SMART CONTRACT INTERFACE

How the ERC721 Receiver Works

An explanation of the ERC721 Receiver interface, a critical security mechanism for safely handling non-fungible token (NFT) transfers to smart contracts.

The ERC721 Receiver is a smart contract interface defined by the IERC721Receiver standard that allows a contract to safely accept incoming transfers of ERC721 non-fungible tokens (NFTs). When an NFT is sent via safeTransferFrom(), the receiving contract must implement the onERC721Received function to acknowledge and process the transfer; if it does not, the transaction will revert, preventing tokens from being permanently locked in an incompatible contract. This mechanism is essential for enabling smart contracts—such as marketplaces, lending protocols, or DAO treasuries—to act as custodians for NFTs without the risk of accidental loss.

The core of the interface is the onERC721Received function, which must return a specific magic value, bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). This return value acts as a cryptographic handshake, proving the contract is prepared to handle the NFT. The function receives four parameters: the operator (the address initiating the transfer), the from address, the tokenId, and optional data bytes. Implementing this callback allows the contract to execute custom logic upon receipt, such as updating internal records, minting a derivative asset, or triggering a secondary action.

A common implementation pattern is seen in NFT marketplace escrow contracts. When a user lists an NFT for sale, the marketplace contract calls safeTransferFrom to move the token from the seller to its own custody. The marketplace's onERC721Received function logs the deposit, associates the tokenId with the seller's listing, and stores the sale parameters. Without this receiver logic, the transfer would fail, making automated marketplace functionality impossible. Other key use cases include NFT staking vaults, fractionalization protocols, and automated bundling tools.

It is crucial to distinguish between transferFrom and safeTransferFrom. The standard transferFrom method sends an NFT without checking if the recipient can handle it, which is risky for contract addresses. The safeTransferFrom methods (overloaded with and without data) perform this vital receiver check. Developers must ensure their consuming contracts implement IERC721Receiver and correctly return the magic value. Failure to do so is a common source of failed transactions and locked funds, as tokens sent via the safe method become stuck in contracts that cannot respond appropriately.

Beyond basic compliance, advanced implementations use the data parameter to pass arbitrary information to the receiver. This allows for complex, single-transaction workflows. For example, a contract could bundle an NFT purchase with an immediate listing on a rental market by encoding the rental terms in the data field. The receiving contract's onERC721Received function decodes this data and executes the subsequent setup. This extensibility makes the ERC721 Receiver a foundational primitive for composable NFT-based DeFi and governance applications.

key-features
SMART CONTRACT INTERFACE

Key Features of ERC721 Receiver

The ERC721 Receiver is a critical interface that smart contracts must implement to safely accept non-fungible tokens (NFTs) via transfers. It prevents tokens from being permanently locked in contracts that cannot handle them.

01

OnERC721Received Function

The core of the interface is the onERC721Received function, which a contract must implement. This function is called by an ERC721 token contract (like a CryptoPunk or Bored Ape) when a token is transferred to the receiving contract using safeTransferFrom. The function must return a specific magic value (bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))) to confirm the contract is prepared to hold the NFT.

02

Prevents Token Locking

The primary purpose is to prevent irreversible token loss. Without this check, an NFT sent to a contract that lacks the logic to manage it (like a simple wallet or a contract not designed for NFTs) would be stuck forever. The safeTransferFrom function will revert the transaction if the recipient is not an Externally Owned Account (EOA) and does not return the correct magic value from onERC721Received.

03

Mandatory for Safe Transfers

The interface is only invoked when using the safeTransferFrom method in an ERC721 contract, not the standard transferFrom. This gives users and applications a choice: use transferFrom for speed (accepting the risk of sending to an incompatible contract) or use safeTransferFrom for security, which guarantees the recipient can handle the NFT.

04

Data Parameter for Context

The onERC721Received function includes a bytes data parameter. This allows the sender to pass arbitrary data to the receiving contract, providing context for the transfer. For example, a marketplace could use this data to indicate a specific auction ID or a game could pass metadata about why a character NFT is being sent to a staking contract.

05

Essential for NFT Marketplaces & Vaults

Any smart contract designed to hold NFTs on behalf of users must implement this interface. Common examples include:

  • NFT Marketplaces (for escrow during sales)
  • NFT Lending/Vault Protocols (for collateralized loans)
  • NFT Staking Contracts
  • DAO Treasuries that manage NFT assets
  • Bridge Contracts for cross-chain NFT transfers
06

Interface ID & ERC-165

The ERC721 Receiver interface has a formal Interface ID (0x150b7a02), which is the XOR of all function selectors in the interface. Contracts can use ERC-165 (supportsInterface) to publicly declare that they implement IERC721Receiver, allowing other contracts to check compatibility before attempting a transfer.

security-considerations
ERC721 RECEIVER

Security Considerations & Risks

The ERC721Receiver interface is a critical security mechanism for safely transferring NFTs to smart contracts. These considerations highlight the risks and best practices for implementing the onERC721Received function.

01

Reentrancy Vulnerabilities

The onERC721Received function is an external callback that can be exploited for reentrancy attacks. A malicious NFT contract could re-enter the receiving contract before its state is updated. To mitigate this, apply the Checks-Effects-Interactions pattern and use reentrancy guards (e.g., OpenZeppelin's ReentrancyGuard) within the callback logic.

  • Example: A contract that mints a token upon receiving an NFT could be tricked into minting multiple times if state updates occur after the callback.
02

Gas Limit & Execution Failures

If the onERC721Received function execution runs out of gas or reverts, the entire NFT transfer (safeTransferFrom) will fail. This can be used in denial-of-service (DoS) attacks or cause operational issues.

  • Complex logic or external calls within the callback increase gas costs and failure risk.
  • Transfers to contracts not implementing the interface will always revert, which is the intended safety mechanism of safeTransferFrom.
03

Interface Compliance & Return Magic Value

The function must return the magic value bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) to accept the transfer. Incorrect implementation (wrong return value, missing function) causes transfers to revert.

  • This is a strict interface check enforced by the calling ERC721 contract.
  • Use established libraries like OpenZeppelin's ERC721Holder for a compliant, minimal implementation.
04

Malicious Data in `_data` Parameter

The bytes _data parameter passed to onERC721Received is arbitrary and untrusted. Processing this data without validation can lead to vulnerabilities.

  • Treat _data as user-controlled input. Decoding and using it can expose the contract to malicious payloads.
  • If not needed, the function should ignore the _data parameter entirely.
05

Ownership & Access Control

The callback is invoked with the _operator (who initiated the transfer) and _from (the previous owner). Failing to validate these addresses can break internal accounting or access control.

  • Example: A contract that grants privileges based on NFT ownership must verify that _from is not a malicious address attempting to spoof state.
  • Implement explicit checks if the callback logic depends on the identity of the _operator.
06

Testing & Static Analysis

Due to the callback's critical role, rigorous testing is essential. Use tools like:

  • Unit Tests: Simulate successful and failing transfers, including reentrancy attempts.
  • Static Analyzers: Slither or MythX can detect common vulnerability patterns in callback logic.
  • Formal Verification: For high-value contracts, consider tools that mathematically prove the callback's correctness.
transfer-semantics
ERC721 STANDARD

Transfer Semantics: Safe vs. Unsafe

This section explains the critical distinction between the two primary methods for transferring ERC721 tokens, focusing on their security implications and intended use cases.

In the ERC721 standard, safe transfers and unsafe transfers represent two distinct methods for moving non-fungible tokens (NFTs) between addresses, defined by their interaction with the receiving contract. The key difference is that a safe transfer invokes a callback function on the recipient's address to confirm it can handle ERC721 tokens, while an unsafe transfer performs the transfer without any such check. This distinction is crucial for preventing tokens from becoming permanently locked in contracts that are not designed to manage them.

The safe transfer mechanism is implemented through the safeTransferFrom function, which calls onERC721Received on the target address. This function must return a specific magic value (0x150b7a02) to confirm successful receipt; if the recipient is a contract that does not implement this function or returns an incorrect value, the transaction reverts. This check prevents tokens from being sent to contracts by accident, a common vulnerability in early NFT implementations. The ERC721Holder contract provides a simple implementation for contracts that wish to safely receive tokens.

Conversely, the unsafe transfer, performed via the standard transferFrom function, moves the token without any callback. This method is inherently riskier when sending to smart contract addresses, as it assumes the recipient is prepared to custody the NFT. If the recipient contract lacks logic to handle incoming ERC721 tokens, the asset becomes locked and irretrievable. This method is generally only recommended for transfers to externally owned accounts (EOAs—user wallets) where no contract execution is expected.

Best practice dictates that applications should default to using safeTransferFrom for all transfers unless there is a specific, audited reason to use transferFrom. Most modern marketplaces and wallets exclusively use the safe variant. The ERC721 standard also includes _safeMint, which applies the same receiver check during the initial minting process, ensuring tokens are not created directly into incompatible contracts. Understanding this semantic difference is fundamental to writing secure NFT-interacting code.

ecosystem-usage
ERC721 RECEIVER

Ecosystem Usage & Examples

The ERC721 Receiver interface is a critical security component for smart contracts that accept NFTs. These examples illustrate its practical implementation and necessity across the ecosystem.

01

NFT Marketplace Escrow

A marketplace contract must implement onERC721Received to safely accept NFTs into escrow during a listing or auction. This prevents NFTs from being permanently locked if sent directly. The function validates the transfer and updates the marketplace's internal ledger, ensuring the seller can be paid upon a successful sale. Key actions:

  • Validates the sender is a known NFT contract.
  • Stores the token ID and owner in a pending sale mapping.
  • Returns the function selector to confirm safe receipt.
02

NFT Lending & Collateralization

DeFi protocols for NFT-backed loans use the receiver to custody collateral. When a user deposits an NFT to borrow assets, the protocol's vault contract must safely receive it. The onERC721Received function ensures the NFT is recorded as collateral against the loan before funds are released. Process flow:

  1. User approves and sends NFT to the lending contract.
  2. Contract's receiver function validates and stores collateral details.
  3. Loan in stablecoins or ETH is minted to the user. Failure to implement the interface would make direct NFT deposits impossible.
03

NFT Staking & Yield Farming

Staking contracts that accept NFTs for rewards or governance power are prime examples of ERC721 Receivers. The interface allows users to 'deposit' their NFT into the staking pool securely. The contract's onERC721Received function typically:

  • Locks the token ID for a specified duration.
  • Starts accruing reward points or tokens for the staker.
  • Maps the token to the staker's address for later withdrawal. This enables composable yield strategies without risking permanent loss of the asset.
04

Composability with ERC-6551 (Token-Bound Accounts)

ERC-6551 allows NFTs to own assets via their own smart contract accounts. These Token-Bound Accounts (TBAs) must implement IERC721Receiver to enable the NFT itself to receive other NFTs or ERC1155 tokens. This creates nested ownership structures where an NFT can hold a portfolio of other assets. Use case: A gaming character NFT (ERC-721) uses its TBA to receive and hold item NFTs (also ERC-721), all verifiable on-chain.

05

Common Pitfall: Locked Assets

The most critical reason to implement the receiver is to prevent permanent asset loss. If a contract does not implement IERC721Receiver, any NFT sent via safeTransferFrom() will be rejected, causing the transaction to revert. However, NFTs sent via the older transferFrom() method will arrive but become irretrievably stuck, as the contract has no functions to move them out. This is a frequent source of user error and lost funds, underscoring the interface's role as a safety standard.

06

Implementation Code Snippet

A minimal, compliant implementation in Solidity includes the function selector check and returns it. Example:

solidity
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
contract MyReceiver is IERC721Receiver {
    function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external override returns (bytes4) {
        // Custom logic for handling the received NFT
        return this.onERC721Received.selector;
    }
}

The returned selector (0x150b7a02) is the magic value that confirms safe receipt to the calling NFT contract.

INTERFACE SPECIFICATION

Comparison: ERC721 vs. ERC1155 Receiver

Key differences between the two primary token receiver interfaces for handling safe transfers.

FeatureERC721 Receiver (IERC721Receiver)ERC1155 Receiver (IERC1155Receiver)

Interface ID

0x150b7a02

0x4e2312e0

Primary Function

Receive safeTransferFrom calls

Receive safeTransferFrom and safeBatchTransferFrom calls

Required Callback Function

onERC721Received

onERC1155Received, onERC1155BatchReceived

Return Value

bytes4(keccak256('onERC721Received(address,address,uint256,bytes)'))

bytes4(keccak256('onERC1155Received(address,address,uint256,uint256,bytes)'))

Batch Transfer Support

Token Type Handling

Single, Non-Fungible Token (NFT)

Fungible, Non-Fungible, and Semi-Fungible Tokens

Data Parameter

Optional bytes calldata

Optional bytes calldata

ERC721 RECEIVER

Common Misconceptions

Clarifying frequent misunderstandings about the `ERC721Receiver` interface, a critical component for secure NFT transfers.

An ERC721 Receiver is a smart contract interface that must be implemented by any contract designed to accept ERC-721 Non-Fungible Tokens (NFTs) via a safe transfer method. It is needed because a standard Ethereum transfer to a contract address could result in the NFT being permanently locked if the recipient contract lacks the logic to handle it. The onERC721Received function acts as a handshake, confirming the contract is prepared to custody the token.

Key Mechanism:

  • The sending contract (e.g., an NFT marketplace) calls a safeTransferFrom function.
  • This function checks if the to address is a contract.
  • If it is, it calls onERC721Received on the recipient contract.
  • The transfer only completes if the call returns the correct magic value (0x150b7a02). This prevents accidental loss of assets, a common pitfall in early smart contract development.
ERC721 RECEIVER

Frequently Asked Questions (FAQ)

Common technical questions about the ERC721 Receiver interface, a critical component for safely handling NFT transfers on the Ethereum blockchain.

An ERC721 Receiver is a smart contract interface that must be implemented by any contract designed to accept ERC-721 Non-Fungible Tokens (NFTs) via the safeTransferFrom function. The interface defines a single function, onERC721Received, which is called by the transferring NFT contract after the tokens have been moved but before the transaction is finalized. This callback mechanism allows the receiving contract to verify it can handle the NFT, execute related logic (like staking or listing), or revert the transaction if it cannot, preventing tokens from being permanently locked in an incompatible contract. The function must return a specific magic value, 0x150b7a02, to confirm successful acceptance.

ENQUIRY

Get In Touch
today.

Our experts will offer a free quote and a 30min call to discuss your project.

NDA Protected
24h Response
Directly to Engineering Team
10+
Protocols Shipped
$20M+
TVL Overall
NDA Protected direct pipeline
ERC721 Receiver: Definition & Smart Contract Interface | ChainScore Glossary