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

onERC1155Received

onERC1155Received is a callback function a smart contract must implement to safely accept ERC-1155 tokens via `safeTransferFrom` or `safeBatchTransferFrom`, ensuring atomic composability.
Chainscore © 2026
definition
ERC-1155 STANDARD

What is onERC1155Received?

A critical callback function in the ERC-1155 multi-token standard that enables safe transfers to smart contracts.

onERC1155Received is a mandatory callback function that a smart contract must implement to accept transfers of ERC-1155 tokens. It is invoked by an ERC-1155 compliant contract (like a marketplace or a wallet) when tokens are sent to the recipient contract's address using the safeTransferFrom or safeBatchTransferFrom functions. This mechanism is part of the ERC-1155 safe transfer protocol, designed to prevent tokens from being permanently locked in contracts that cannot handle them. The function must return a predefined magic value, bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")), to signal successful acceptance; otherwise, the transfer is reverted.

The function's signature is function onERC1155Received(address operator, address from, uint256 id, uint256 value, bytes calldata data) external returns (bytes4). Its parameters provide essential context for the receiving contract: the operator is the address that initiated the transfer (which could be the token owner or an approved contract), from is the sender's address, id and value specify the token type and quantity being transferred, and data contains arbitrary extra information sent by the caller. This allows the recipient contract to execute custom logic upon receipt, such as updating internal balances, minting a related asset, or triggering a specific action within a game or application.

Implementing onERC1155Received correctly is fundamental for composability and security in the Ethereum ecosystem. Without it, any attempt to send tokens via a safeTransferFrom call will fail, protecting users from accidental loss. This pattern is analogous to the onERC721Received function in the ERC-721 standard but is extended to handle both fungible and non-fungible tokens within a single interface. Common use cases include decentralized exchanges that need to custody tokens, gaming contracts that manage in-game items, and vaults that wrap ERC-1155 tokens into other representations.

how-it-works
ERC-1155 STANDARD

How onERC1155Received Works

A technical breakdown of the `onERC1155Received` function, the mandatory callback that enables safe transfers in the ERC-1155 multi-token standard.

The onERC1155Received function is a mandatory callback function defined by the ERC-1155 token standard (EIP-1155) that a smart contract must implement to accept transfers of ERC-1155 tokens. This mechanism, part of the safe transfer family of functions (safeTransferFrom, safeBatchTransferFrom), prevents tokens from being permanently locked by sending them to a contract that cannot manage them. When called, the function returns a predefined magic value, bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")), to confirm the contract is prepared to handle the incoming assets.

The function is invoked with specific parameters: the operator (the address initiating the transfer), the from address, the token id and amount, and arbitrary data bytes. This data parameter is crucial for composability, allowing the sender to pass additional instructions—such as a specific action for the receiving contract to execute with the tokens—within a single transaction. The receiving contract's logic inside onERC1155Received can then decode this data and act accordingly, enabling complex interactions like depositing into a liquidity pool or staking in a single step.

A contract's implementation of onERC1155Received must return the aforementioned 4-byte magic value. If it does not, or if the function call reverts, the entire safe transfer transaction is reverted, ensuring atomicity. This is a critical security feature. For contrast, the non-safe transferFrom function in ERC-1155 does not call this hook, transferring tokens blindly and risking permanent loss if sent to an incompatible contract. Therefore, dApp interfaces and wallets should default to using the safe transfer functions.

Developers integrating ERC-1155 tokens must carefully implement this hook. Common patterns include updating internal accounting balances, emitting custom events, or executing logic based on the data payload. It is also the standard location to enforce whitelists or other transfer restrictions for a contract. Failure to implement the function correctly will render a contract unable to receive tokens via the standard, safe methods, breaking interoperability with major marketplaces and DeFi protocols that rely on these functions.

key-features
ERC-1155 STANDARD

Key Features & Purpose

The onERC1155Received function is a mandatory callback that enables smart contracts to safely accept ERC-1155 tokens, preventing them from being locked forever. This section details its core mechanisms and use cases.

01

Mandatory Safe Transfer Hook

The onERC1155Received function is a hook that the receiving contract must implement and return a specific magic value (0xf23a6e61) to accept an ERC-1155 token transfer. This mechanism, defined by ERC-1155's safeTransferFrom and safeBatchTransferFrom functions, prevents tokens from being sent to contracts that cannot handle them, which would result in permanent loss.

02

Function Signature & Parameters

The function has a specific signature that provides context for the transfer: function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns (bytes4)

  • _operator: The address that initiated the transfer.
  • _from: The address sending the tokens.
  • _id: The token type (ID) being transferred.
  • _value: The amount of tokens being transferred.
  • _data: Additional data sent with the transfer.
03

Return Magic Value

To signal successful acceptance, the function must return the 4-byte selector 0xf23a6e61. This is the return value of bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")). If the receiving contract does not implement this function or returns any other value, the calling safeTransferFrom transaction will revert, protecting the sender's assets.

04

Enabling Programmable Logic on Receipt

This callback allows a contract to execute custom logic upon receiving tokens. For example, a staking contract can automatically credit staking rewards, a marketplace can list the token for sale, or a game can equip an item to a character. The _data parameter can be used to pass instructions for this logic.

05

Batch Transfer Support

For batch transfers via safeBatchTransferFrom, the corresponding onERC1155BatchReceived hook is used. It receives arrays of IDs and values, allowing a contract to handle multiple token types in a single, gas-efficient transaction. Both hooks are part of the IERC1155Receiver interface.

06

Contrast with ERC-721's safeTransfer

Unlike ERC-721's onERC721Received, which handles single NFTs, ERC-1155's hook is designed for fungible and non-fungible tokens. It includes a _value parameter for amounts, making it suitable for both single items and bundles of fungible tokens. This dual nature is a core innovation of the ERC-1155 standard.

code-example
ERC-1155 INTERFACE

onERC1155Received

The `onERC1155Received` function is a mandatory callback handler that a smart contract must implement to safely accept transfers of single ERC-1155 tokens.

onERC1155Received is a function defined by the ERC-1155 token standard's IERC1155Receiver interface. Its primary purpose is to allow a smart contract to signal it can safely hold ERC-1155 tokens and to execute logic upon receipt. When a contract like a marketplace or game vault receives a token via safeTransferFrom or safeBatchTransferFrom, the sending contract calls onERC1155Received on the recipient. This function must return a predefined magic value, bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")), to confirm successful handling; otherwise, the transfer is reverted.

This mechanism is a critical security feature known as safe transfers. It prevents tokens from being permanently locked in contracts that are not equipped to manage them, which was a common issue with earlier standards like ERC-721. The function parameters provide essential context: the operator (who initiated the transfer), the from address, the token id and value (amount), and any data passed along. Contracts use this data to update internal state, mint in-game assets, or record deposits.

Developers must implement onERC1155Received (and its batch counterpart, onERC1155BatchReceived) for any contract designed to hold ERC-1155 tokens. A common implementation pattern checks the operator and then updates a mapping that tracks balances per token ID for the contract. Failure to implement the interface or return the correct magic value will cause all safe transfer calls to the contract to fail, enforcing compliance. This callback system is a cornerstone of the ERC-1155 standard's flexibility and safety for managing both fungible and non-fungible assets.

ecosystem-usage
ERC-1155 STANDARD

Ecosystem Usage & Examples

The onERC1155Received function is a critical security and interoperability hook for smart contracts that manage ERC-1155 tokens. These examples illustrate its practical implementation across different use cases.

01

NFT Marketplace Escrow

A marketplace contract uses onERC1155Received to safely accept tokens from users for listing. The function performs checks before allowing the deposit.

  • Key Logic: Validates the _operator (the marketplace) and _from address.
  • State Update: Stores the token ID, amount, and seller in an internal escrow mapping.
  • Security: Returns the magic value 0xf23a6e61 only after all checks pass, preventing accidental lock-up.
02

Gaming Inventory System

In-game smart contracts act as player inventories, receiving ERC-1155 items like weapons, potions, and crafting materials.

  • Batch Support: Uses onERC1155BatchReceived for equipping multiple items in one transaction.
  • Game Logic Hook: The function can trigger in-game events (e.g., "item equipped") upon successful receipt.
  • Access Control: Often restricts _operator to approved game logic contracts to prevent unauthorized transfers.
03

DeFi Collateral Vault

Lending protocols accept ERC-1155 tokens (e.g., semi-fungible LP positions) as collateral. The vault contract must implement the receiver hook.

  • Collateralization: The function records the received token IDs/amounts, linking them to a user's debt position.
  • Reentrancy Guard: Critical to place the external call (safeTransferFrom) before vault state updates, following Checks-Effects-Interactions pattern.
  • Data Field: The _data parameter can encode loan-specific metadata for the vault.
04

Composability & Staking Pools

Staking pools and yield farms accept ERC-1155 tokens to represent staked positions, enabling complex DeFi Lego.

  • Receipt Token: The pool mints a new ERC-1155 or ERC-20 receipt token to the user upon receiving their assets.
  • Inter-Contract Flow: Enables seamless movement of assets between compliant contracts without manual approval steps.
  • Standardization: This hook is why ERC-1155 tokens work across thousands of dApps without custom integrations.
05

Common Implementation Pitfalls

Incorrect implementation can lead to locked funds. Key mistakes to avoid:

  • Missing Return Value: Failing to return 0xf23a6e61 (or 0xbc197c81 for batches) will cause transfers to revert.
  • Ignoring the _data Field: This parameter is often used by sending contracts; ignoring it can break expected functionality.
  • Insufficient Access Control: Not validating the _operator can allow unauthorized contracts to deposit tokens.
security-considerations
ERC-1155

Security Considerations

The onERC1155Received and onERC1155BatchReceived functions are critical security hooks for smart contracts that accept ERC-1155 tokens. Implementing them incorrectly can lead to token loss, reentrancy attacks, and protocol insolvency.

01

The Reentrancy Attack Vector

The most critical risk is reentrancy. The onERC1155Received hook is called during the token transfer. A malicious contract can re-enter your contract's logic before the initial transfer state is finalized.

  • Classic Example: A staking contract that updates user balances after the hook call can be drained if the hook calls back into the stake function.
  • Mitigation: Follow the Checks-Effects-Interactions pattern. Update all internal state (balances, totals) before making any external calls, including the token transfer that triggers the hook.
02

Return Value Enforcement

The ERC-1155 standard mandates that onERC1155Received must return a specific magic value: bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")). Failure to return this exact value will cause the entire transfer to revert.

  • Common Pitfall: Forgetting the returns statement or returning an incorrect selector.
  • Best Practice: Use the provided interface and the IERC1155Receiver abstract contract from OpenZeppelin, which includes the correct function signatures and return values.
03

Batch Receive Complexity

The onERC1155BatchReceived hook introduces additional complexity. It must handle multiple token IDs and values in a single transaction, which amplifies risks.

  • Atomicity Risk: The entire batch operation must be treated as atomic. If logic fails for one token type, the entire batch should revert to avoid partial state corruption.
  • Gas & Validation: Processing arrays requires careful gas management and validation of array lengths to prevent out-of-gas errors or malformed input exploits.
04

Access Control & Context

The hook must validate the caller (msg.sender) is a trusted token contract. It receives an operator argument, which is the address that initiated the transfer (not necessarily the token holder).

  • Spoofing Risk: Do not trust the operator or from arguments for authorization; use msg.sender to verify the calling token contract.
  • Context Separation: The hook may be called outside of a user-initiated action (e.g., during a marketplace settlement). Ensure business logic accounts for this and does not make unsafe assumptions about the from address.
06

Integration with Upgradeable Proxies

If your receiving contract uses a proxy pattern (e.g., UUPS or Transparent Proxy), special care is needed.

  • Selector Clash: Ensure the hook function selector does not clash with the proxy's own functions (like upgradeTo).
  • Storage Layout: State variables updated in the hook must remain consistent across upgrades. Changing storage layout can corrupt data when the hook is called.
  • Initialization: The hook must not be callable before the contract is fully initialized, to prevent initialization exploits.
SAFE TRANSFER MECHANISMS

Comparison: ERC-1155 vs. ERC-721 & ERC-20 Callbacks

A technical comparison of the callback functions used to secure token transfers across different Ethereum token standards.

FeatureERC-1155ERC-721ERC-20

Primary Callback Function

onERC1155Received, onERC1155BatchReceived

onERC721Received

No standard callback

Callback Trigger

Single and batch transfers

Single token transfers only

Return Value Required

bytes4 magic value (0xf23a6e61 / 0xbc197c81)

bytes4 magic value (0x150b7a02)

Standard Interface

IERC1155Receiver

IERC721Receiver

Batch Transfer Support

Prevents Token Lockup

Defined In EIP

EIP-1155

EIP-721

Common Use Case

Game items, bundles

Unique NFTs

Fungible tokens

ERC-1155 STANDARD

Common Misconceptions

The `onERC1155Received` and `onERC1155BatchReceived` functions are critical for safe ERC-1155 token transfers, but their implementation and purpose are often misunderstood. This section clarifies frequent points of confusion for developers.

No, the onERC1155Received callback is for all ERC-1155 token types, including both fungible tokens (like in-game currency) and non-fungible tokens (NFTs). The ERC-1155 standard is a multi-token standard designed to handle multiple token types within a single contract. The callback's purpose is to notify a receiving contract that tokens have arrived, regardless of whether the token ID represents a fungible or non-fungible asset. The logic inside the callback function must be written to handle both cases appropriately, often by checking the _id and _value parameters.

ERC-1155 STANDARD

Technical Deep Dive

A detailed exploration of the `onERC1155Received` function, the critical security hook for the ERC-1155 multi-token standard that enables atomic swaps and batch transfers to smart contracts.

The onERC1155Received function is a mandatory callback function that a smart contract must implement to safely accept transfers of ERC-1155 tokens. It is part of the ERC-1155 Token Receiver specification and acts as a security check, allowing a receiving contract to explicitly accept or reject incoming tokens. When an ERC-1155 token is sent to a contract address using the safeTransferFrom or safeBatchTransferFrom methods, the token contract calls onERC1155Received on the recipient. This mechanism prevents tokens from being permanently locked in contracts that don't know how to handle them, a common vulnerability in earlier token standards like ERC-721.

Key Parameters:

  • operator: The address which initiated the transfer.
  • from: The address which previously owned the token.
  • id & amount: The token ID and quantity being transferred.
  • data: Additional data with no specified format, passed from the caller.

The function must return the function selector bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) to signal successful acceptance.

ERC-1155 STANDARD

Frequently Asked Questions (FAQ)

Common developer questions about the `onERC1155Received` hook, a critical function for safely handling incoming ERC-1155 tokens in smart contracts.

The onERC1155Received function is a mandatory callback hook defined by the ERC-1155 token standard that a smart contract must implement to safely accept transfers of single ERC-1155 tokens. When an ERC-1155 token is sent to a contract address using safeTransferFrom, the token contract calls onERC1155Received on the recipient contract, which must return a predefined magic value (0xf23a6e61) to confirm the transfer was intentional and the contract is prepared to handle the asset; if the correct value is not returned, the entire transfer is reverted.

Key Components:

  • Hook Invocation: Automatically called by the token contract.
  • Magic Value: Must return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")).
  • Safety: Prevents tokens from being permanently locked in contracts that cannot manage them.
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
onERC1155Received: ERC-1155 Safe Transfer Function | ChainScore Glossary