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

Receiver Hook

A receiver hook is a callback function in a smart contract that is automatically invoked upon receiving tokens, enabling atomic post-transfer logic.
Chainscore © 2026
definition
SMART CONTRACT PATTERN

What is a Receiver Hook?

A receiver hook is a callback function in a smart contract that is automatically executed upon receiving tokens or other assets, enabling complex, conditional logic for asset transfers.

A receiver hook is a smart contract function designed to be invoked automatically when the contract receives a token transfer or other on-chain asset. This mechanism, often implemented via standards like ERC-1155's onERC1155Received or ERC-721's onERC721Received, allows a contract to execute custom logic—such as validating the transfer, updating internal state, or triggering subsequent actions—before the transaction is finalized. This pattern is essential for creating composable and reactive DeFi applications, as it prevents assets from being sent to a contract that cannot handle them, a common failure mode known as token locking.

The primary technical function of a receiver hook is to enforce a handshake protocol between the sending and receiving contracts. When a transfer is initiated, the token contract calls the designated hook function on the recipient's address. If the recipient is a contract, it must return a predefined magic value (e.g., bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))) to signal successful acceptance; if it fails to do so, the entire transfer transaction is reverted. This ensures atomicity, meaning the transfer and the hook's logic succeed or fail together, preventing inconsistent states.

Receiver hooks are foundational for advanced blockchain applications. In NFT marketplaces, a receiver hook can automatically list a received NFT for sale. In lending protocols, it can use incoming collateral to mint a debt position atomically. The pattern also underpins batch operations and multi-call transactions, where a single transaction can transfer multiple assets and trigger complex, interdependent logic across several contracts. Understanding hooks is critical for developers building secure, interoperable systems that interact with token standards.

how-it-works
ERC-4337 MECHANISM

How Does a Receiver Hook Work?

A receiver hook is a smart contract function that automatically executes logic when the contract receives tokens or native currency, enabling complex, programmable interactions within account abstraction.

A receiver hook is a callback function, typically onERC721Received, onERC1155Received, or a custom receive/fallback function, that is automatically invoked when a smart contract receives an asset. This mechanism is central to ERC-4337 account abstraction, where a smart contract wallet (the account) uses these hooks to validate and execute logic for incoming transactions. For example, a hook can automatically stake received tokens, swap them via a decentralized exchange, or bundle the transfer with other operations in a single UserOperation. This transforms passive token reception into an active, programmable event.

The workflow begins when a UserOperation targeting the smart contract account is relayed through the network. The EntryPoint contract validates the operation and, if the call involves transferring value, triggers the account's receiver hook. This hook contains the core business logic the account owner has predefined. Crucially, the hook's execution is atomic with the initial transaction call; it all succeeds or fails as one unit, ensuring consistency. This design prevents assets from being stuck in a contract that cannot handle them, a common issue addressed by standards like ERC-721 and ERC-1155 for NFTs.

From a security and design perspective, receiver hooks must be implemented carefully to avoid reentrancy attacks and gas limit issues. They enable powerful patterns like session keys for limited permissions, automated gas sponsorship where received funds pay for the transaction, and conditional logic based on token type. This functionality is a key differentiator from Externally Owned Accounts (EOAs), which cannot natively execute code upon receiving funds. By leveraging hooks, smart contract accounts become active agents in the decentralized ecosystem, capable of complex, automated behaviors without requiring a separate transaction from the owner.

key-features
RECEIVER HOOK

Key Features & Characteristics

A Receiver Hook is a smart contract function that is automatically executed when a token is transferred to a contract address, enabling programmatic logic to run on receipt of funds. This mechanism is central to the ERC-777 and ERC-1155 token standards.

01

Core Mechanism: The `tokensReceived` Hook

The primary function is the tokensReceived hook, defined in the IERC777Recipient or IERC1155Receiver interface. When tokens are sent to a contract implementing this interface, the token contract's transfer function calls tokensReceived on the recipient, passing details of the transaction.

  • Automatic Execution: Logic runs atomically within the same transaction as the transfer.
  • Context Data: Receives the sender's address, recipient's address, token amount, and optional user data (data and operatorData fields).
  • Atomic Composability: Ensures the recipient's intended action (e.g., minting an NFT, swapping tokens) either completes fully or the entire transfer is reverted.
02

Comparison to ERC-20's `approve` & `transferFrom`

Receiver Hooks solve a critical UX and security flaw in the ERC-20 standard. With ERC-20:

  • Two-Step Process: A contract must first be approved to spend a user's tokens, then call transferFrom.
  • Funds Locked Risk: Tokens sent directly to a non-upgraded contract are permanently lost, as the contract has no way to react.

With ERC-777/ERC-1155 Hooks:

  • One-Step Process: A user can send tokens directly; the recipient contract's logic executes immediately.
  • No Lost Funds: The hook can reject the transaction if the contract is not prepared to handle it, refunding the sender.
03

Key Use Cases & Applications

Hooks enable complex, trust-minimized interactions by making contracts reactive.

  • DeFi Vaults & Yield Strategies: Automatically stake received tokens into a farming protocol.
  • NFT Marketplaces: Mint an NFT automatically upon receipt of payment in a single transaction.
  • Subscription Services: Grant access or extend a membership period when a periodic payment is received.
  • Batch Operations (ERC-1155): Handle the receipt of multiple token types (fungible and non-fungible) in a single batch transfer, with logic for each.
04

Security Considerations & Best Practices

While powerful, hooks introduce new security vectors that must be managed.

  • Reentrancy Guard: The hook is called during the transfer; the token contract is temporarily in control of the recipient's execution. Recipient contracts must use reentrancy guards (like OpenZeppelin's) to prevent malicious token contracts from re-entering the hook.
  • Hook Gas Limits: The token contract must ensure the call to tokensReceived has a sufficient gas stipend, or the transfer may fail.
  • Trust in Token Contract: The recipient must trust the token contract's implementation to call the hook correctly and not maliciously.
05

Technical Implementation (ERC-777 Example)

A compliant recipient contract must implement the interface and function.

solidity
interface IERC777Recipient {
    function tokensReceived(
        address operator,
        address from,
        address to,
        uint256 amount,
        bytes calldata userData,
        bytes calldata operatorData
    ) external;
}

The implementing contract overrides this function. It can:

  • Revert: To reject the transfer (e.g., invalid userData).
  • Execute Logic: Swap tokens, mint an asset, update internal accounting.
  • Emit Events: For off-chain tracking of the automated action.
06

Related Concept: ERC-1363 (Payable Token)

ERC-1363 is a separate standard that builds upon ERC-20 to add similar hook functionality. It defines transferAndCall and approveAndCall functions that, upon transfer, execute a function on the recipient contract.

  • Key Difference: While ERC-777 hooks are called automatically on any transfer, ERC-1363 requires the sender to explicitly choose a transferAndCall method, specifying the target function.
  • Backward Compatibility: ERC-1363 is designed to be more easily integrated with existing ERC-20 infrastructure, acting as an extension rather than a replacement.
code-example
IMPLEMENTATION GUIDE

Code Example: ERC-777 Receiver Hook

A practical walkthrough for implementing the mandatory `tokensReceived` hook in an ERC-777-compatible smart contract.

A receiver hook is a callback function, specifically tokensReceived, that a smart contract must implement to receive ERC-777 tokens, enabling advanced logic execution upon token transfer. Unlike the passive reception of ERC-20 tokens, this hook allows a receiving contract to automatically react to incoming transfers—such as minting derivative assets, updating internal ledgers, or rejecting unauthorized transactions. The hook is invoked by the token contract's send or transfer functions, making the transfer atomic with the receiver's custom logic.

The function signature is defined by the IERC777Recipient interface: function tokensReceived(address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData) external. Key parameters include the operator (the address executing the transfer), the from and to addresses, the amount, and optional data fields. Crucially, the function must be marked external and should include access control, typically by validating that the caller is a known, authorized ERC-777 token contract to prevent malicious invocations.

A common implementation pattern involves using the hook to perform a state update. For example, a staking contract could use tokensReceived to automatically credit a user's staked balance upon deposit, eliminating the need for a separate approval-and-deposit transaction. The hook can also enforce business rules, such as rejecting tokens from a blacklisted address or ensuring transfers include specific data in the userData field. This transforms simple token transfers into programmable, trust-minimized interactions between contracts.

Developers must ensure their hook implementation is secure and gas-efficient, as it executes within the gas limits of the initial transfer transaction. A critical security practice is to implement a reentrancy guard, as the hook is called during the token contract's state change. Furthermore, the contract must be registered as an ERC-777 recipient by implementing ERC1820Registry's interface and setting itself with the ERC777TokensRecipient interface hash, otherwise token transfers to it will revert.

examples
RECEIVER HOOK

Common Use Cases & Examples

A receiver hook is a smart contract interface that enables a token contract to notify and interact with a receiving contract upon a token transfer. This mechanism is central to composable DeFi and programmable token flows.

02

On-Chain Fee Collection

Projects can implement receiver hooks to deduct and route fees automatically during transfers. This is essential for revenue-generating protocols like NFT marketplaces or cross-chain bridges.

  • Example: A DEX's liquidity pool token uses a hook to take a 0.05% protocol fee on every transfer, sending it to a treasury contract.
  • Mechanism: The hook logic executes after the core transfer validation but before final state settlement.
04

Enhanced Token Gating & Compliance

Receiver hooks can enforce transfer conditions based on the state of the receiving address or external data. This enables programmable compliance for regulated assets or membership tokens.

  • Use Cases:
    • KYC/AML: Verify the recipient's credentials via an oracle before allowing the transfer to complete.
    • Vesting: Enforce lock-up schedules for team or investor tokens on transfer.
  • Key Feature: Allows for reverting transfers that do not meet predefined conditions.
05

Cross-Chain Asset Bridging

In cross-chain messaging protocols, a receiver hook on the destination chain is the execution endpoint for a bridged asset transfer. It mints wrapped tokens or releases native assets upon verification of the source chain proof.

  • Flow: A bridge relayer calls the token contract's receiver hook with a validity proof after detecting a burn/lock on the source chain.
  • Security Critical: The hook must rigorously validate the cross-chain message to prevent unauthorized minting.
06

Real-World Asset (RWA) Settlement

For tokenized real-world assets like treasury bills or real estate, receiver hooks can trigger off-chain settlement processes and update registries upon transfer of ownership.

  • Example: Transferring a tokenized bond might trigger the hook to notify a custodian's API to update the legal beneficiary record.
  • Architecture: Often involves a trusted oracle or verifiable credential system to connect on-chain transfers to off-chain legal events.
MECHANISM COMPARISON

Receiver Hooks vs. Traditional ERC-20 Approve/TransferFrom

A technical comparison of the token transfer flow control mechanisms defined by ERC-777/ERC-1155 receiver hooks versus the standard ERC-20 allowance pattern.

Feature / MechanismTraditional ERC-20 (Approve/TransferFrom)Receiver Hooks (ERC-777/ERC-1155)

Primary Control Flow

Pull-based (Spender initiates)

Push-based (Sender initiates)

Transfer Authorization

Pre-approved allowance set by token holder

Real-time check via tokensToSend/tokensReceived hooks

Atomic Operations

Reentrancy Risk

Low (standard pattern)

High (requires careful hook design)

Gas Overhead for Sender

Lower (simple transfer)

Higher (hook execution cost)

Default Behavior on Rejection

Transaction reverts

Transaction reverts via hook revert

Standard Interface

ERC-20 (approve, transferFrom)

ERC-1820 Registry & hook interfaces

Use Case Example

DEX swaps, simple payments

Auto-staking, auto-collateralization, complex DAO logic

security-considerations
RECEIVER HOOK

Security Considerations & Risks

While receiver hooks enable powerful, automated token interactions, they introduce critical attack vectors that developers and users must understand. This section details the primary security risks associated with this mechanism.

01

Reentrancy Attacks

The primary risk for a receiver hook is reentrancy, where a malicious contract exploits the callback to re-enter the calling function before its state is finalized. This can drain funds or corrupt logic.

  • Classic Pattern: A hook makes a recursive call back to the original transfer or mint function.
  • Mitigation: Use Checks-Effects-Interactions pattern or a reentrancy guard (e.g., OpenZeppelin's ReentrancyGuard) to lock the state during the hook execution.
02

Unbounded Gas Consumption

The calling contract must provide gas for the hook's execution, which can be exploited for Denial-of-Service (DoS).

  • Attack Vector: A malicious hook implements an infinite loop or complex computation, causing the original transaction to run out of gas and revert.
  • Mitigation: Implement a gas limit for the hook call or use low-level call with a specified gas stipend, though this can lead to failed hooks.
03

Unexpected State Changes

Hooks execute arbitrary code, which can alter the state assumptions of the calling contract in ways the developer did not anticipate.

  • Example: A hook could change the balance of a critical address, manipulate approval amounts, or call other system functions.
  • Implication: Contract logic must be robust against all possible state changes during the hook, not just the intended ones. Avoid making state assumptions after a hook call.
04

Sandwich Attacks & MEV

Receiver hooks that perform on-chain actions like swaps or liquidity provision are vulnerable to Maximal Extractable Value (MEV) exploitation.

  • Mechanism: A searcher can front-run the transaction containing the hook, manipulate market prices, and back-run to profit, at the expense of the hook executor.
  • Impact: Results in worse execution prices (slippage) for users. This is a systemic risk for any hook that interacts with AMMs or lending markets.
05

Trust Assumptions & Centralization

Contracts implementing hooks often must trust the logic of the receiving contract. This creates a trust surface that can be compromised.

  • Risk: If a popular wallet or vault contract with a hook is upgraded maliciously or hacked, all tokens that call it become vulnerable.
  • Consideration: Hooks can lead to centralization risks, as protocols may whitelist only a few "trusted" hook implementations to mitigate risk.
06

Best Practices for Secure Implementation

To mitigate these risks, developers should adhere to strict security patterns:

  • Use Established Standards: Implement widely-audited interfaces like ERC-777's tokensReceived or ERC-1155's onERC1155Received.
  • Minimize Hook Scope: Restrict what the hook is allowed to do; avoid granting approval or transfer capabilities within the hook context.
  • Thorough Testing & Auditing: Use fuzzing (e.g., with Foundry) and static analysis to test hook interactions under adversarial conditions. Always audit hook logic.
evolution
EVOLUTION & STANDARDIZATION

Receiver Hook

A technical standard enabling smart contracts to execute custom logic upon receiving tokens, fundamentally altering the token transfer flow.

A receiver hook is a function defined within the ERC-6672 standard that allows a smart contract to execute custom code automatically when it receives tokens via a compliant transfer method. This mechanism inverts the traditional push-based transfer model, where the sender initiates the entire transaction, to a pull-based model where the receiving contract can validate, process, or reject the transfer. It is a critical component of token-aware contracts, enabling features like automated staking, fee processing, or real-time balance reconciliation without requiring a separate, follow-up transaction from the receiver.

The development of receiver hooks addresses a key limitation in earlier token standards like ERC-20 and ERC-721, where transfers were simple, one-way operations. In those models, a receiving contract could only become aware of an incoming transfer through an optional event log, which is not executable code. The ERC-6672 standard formalizes the hook interface, ensuring a consistent and secure method for contracts to react. This standardization prevents fragmentation and reduces integration complexity for developers building applications that must interact with multiple token types.

From a security perspective, receiver hooks introduce both power and risk. They can prevent tokens from being accidentally locked in contracts that cannot handle them by allowing the receiver to reject invalid transfers. However, they also expand the attack surface, as the hook execution becomes part of the transfer transaction. Malicious or poorly implemented hooks can lead to reentrancy attacks or cause transfers to fail unexpectedly. Therefore, rigorous auditing and adherence to the checks-effects-interactions pattern are paramount when implementing receiver hooks.

Practical use cases for receiver hooks are extensive. In DeFi, a vault contract can use a hook to automatically deposit received tokens into a yield-bearing strategy. In gaming, an NFT marketplace's escrow contract can instantly verify and list a newly received asset. For cross-chain applications, a bridge's minting contract can execute a hook to confirm a deposit event on another chain before releasing wrapped tokens. This automation streamlines user experience and enables complex, multi-step financial operations in a single transaction.

The evolution towards receiver hooks represents a broader trend in blockchain interoperability and composability. By giving smart contracts active agency in token transfers, they enable more sophisticated and gas-efficient application logic. As the standard gains adoption, it is poised to become a foundational primitive, much like the ERC-165 interface detection standard, ensuring that tokens and the contracts designed to hold them can communicate and interact in a predictable, secure, and powerful manner.

RECEIVER HOOK

Frequently Asked Questions (FAQ)

A receiver hook is a specialized callback function that allows a smart contract to react to incoming token transfers. This section answers common technical questions about its purpose, implementation, and security.

A receiver hook is a callback function on a smart contract that is automatically executed when the contract receives tokens via a compliant transfer standard, such as ERC-1155 or ERC-777. It allows the receiving contract to implement custom logic—like auto-staking, rebalancing, or validation—immediately upon receiving an asset, moving beyond the basic, passive receipt of the older ERC-20 standard. This mechanism enables more complex, automated, and secure interactions between protocols.

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