Developer reviewing smart contract architecture diagrams on a glass wall in a modern WeWork space, standing desk in background, natural industrial aesthetic, candid engineering moment.
Protocols

Cross-Contract Call Patterns and Gas Management

A technical deep dive into NEAR's asynchronous cross-contract call model, including callback handling, gas budgeting, and failure modes on the sharded runtime. Covers the patterns that determine composability and resilience for multi-contract applications.
introduction
CROSS-CONTRACT CALL ARCHITECTURE

The Asynchronous Execution Model

How NEAR's sharded runtime uses asynchronous execution and callback-based patterns to manage cross-contract calls, gas budgeting, and composability risks.

NEAR Protocol enforces an asynchronous execution model for all cross-contract calls. Unlike single-threaded EVM environments where a contract call executes atomically within the caller's transaction, a cross-contract call on NEAR is split into multiple receipts. The initial transaction spawns one or more action receipts that are executed independently by the receiving contract's shard. Any return value or state mutation from the called contract is not available to the caller in the same execution context. Instead, the caller must define a callback function that the protocol invokes in a separate receipt once the callee's execution completes. This model is fundamental to NEAR's sharded runtime design, where each shard processes receipts for its own contracts in parallel, and cross-shard communication relies on the receipt system rather than synchronous state access.

This architecture directly impacts gas management and error handling. The user or originating account pre-pays for all gas across the receipt chain at transaction submission. If a cross-contract call fails—due to a panic, assertion failure, or gas exhaustion—the protocol does not automatically revert state changes made by the callee. The callback function must explicitly inspect the execution status and implement rollback or recovery logic. A common pattern is to check promise_result in the callback and either commit or revert state based on success or failure. Teams that assume atomic rollback semantics from EVM or SVM environments risk introducing state inconsistencies, such as burning tokens without completing a swap or locking funds in an intermediate contract. The #[private] macro and env::promise_return are critical tools for enforcing that only the expected callback can finalize a multi-step flow.

Operationally, builders must budget gas across the entire call chain, including the callback. Under-budgeting the callback can leave a contract in an unresolved state with no further execution possible unless a separate retry mechanism is implemented. Monitoring solutions should track receipt chains, not just top-level transactions, to detect stuck or failed cross-contract flows. Chainscore Labs reviews cross-contract architectures to verify that callback handling is exhaustive, gas budgets account for worst-case callback execution, and state invariants hold across asynchronous boundaries. For protocols integrating with NEAR-native DEXs, lending markets, or bridges, a formal review of the receipt-chain topology is essential to prevent composability failures that are unique to asynchronous runtimes.

OPERATIONAL IMPACT MATRIX

Cross-Contract Call Quick Facts

How NEAR's asynchronous execution model affects gas budgeting, error handling, and composability for protocols, wallets, and integration teams.

AreaWhat changesWho is affectedAction

Execution Model

All cross-contract calls are asynchronous and sharded; no atomic composability across contracts

DeFi protocols, DEXs, lending markets

Review architecture for callback-based state transitions and idempotent operations

Gas Budgeting

Gas is prepaid per action; callbacks require separate gas allocation or can fail silently

Wallet teams, relayer operators, dApp developers

Verify gas estimation logic accounts for callback execution and cross-shard network round-trips

Error Handling

Failed cross-contract calls do not revert the caller's state automatically; callbacks must handle failure explicitly

Smart contract developers, auditors

Audit all callback handlers for unhandled promise rejections that could leave contracts in inconsistent states

Retry Logic

No built-in retry mechanism; developers must implement custom retry or fallback patterns in callbacks

Bridge operators, cross-chain messaging protocols

Design and test retry flows with bounded gas and dead-letter queues to prevent stuck transactions

State Access

Contracts on different shards cannot read each other's state directly; all data must be passed via call arguments or callbacks

Oracle providers, data indexers

Validate that cross-contract data dependencies are explicitly passed and not assumed to be synchronously available

Security Model

Malicious or buggy callee contracts can consume all forwarded gas without returning a callback

Protocol architects, security engineers

Set explicit gas limits on all cross-contract calls and never forward unlimited gas to untrusted contracts

Monitoring

Silent callback failures are a common source of undetected protocol breakage

Infrastructure teams, protocol operators

Implement monitoring for callback success rates, gas exhaustion patterns, and promise chain timeouts

technical-context
ASYNCHRONOUS EXECUTION MODEL

Receipts, Callbacks, and Gas Flow

How NEAR's sharded runtime uses receipts and callbacks to manage asynchronous cross-contract calls and deterministic gas accounting.

On NEAR Protocol, cross-contract calls are not atomic synchronous executions but are instead decomposed into an asynchronous chain of Receipts. When a contract invokes another, the action is split into a series of receipts representing the function call, the transfer of attached tokens, and crucially, a callback receipt to return the result to the caller. This receipt-based model is fundamental to NEAR's sharded, parallelized runtime, allowing execution to be distributed across multiple shards without global locking, but it fundamentally changes how developers must handle errors, state, and gas.

Gas management in this model is deterministic but requires explicit budgeting. The initial transaction provides a fixed amount of gas, which is then partitioned and attached to each generated receipt. If a cross-contract call runs out of gas, the execution environment does not revert the entire transaction chain; instead, it signals a failure that must be handled by the developer-defined callback. This places a critical burden on the callback logic to manage state rollbacks, refund locked assets, or implement retry mechanisms. A missing or incorrectly implemented callback is a primary vector for permanently locked funds and broken protocol composability.

For builders and integration teams, the operational risk lies in the implicit trust chain of asynchronous calls. A protocol that relies on a multi-hop cross-contract interaction must verify that every contract in the chain correctly implements its callback interface and has a robust gas budget for failure scenarios. Chainscore Labs provides architecture reviews and formal verification of cross-contract call graphs to ensure that callback logic is resilient against out-of-gas errors and that state consistency is maintained across all asynchronous execution branches.

CROSS-CONTRACT CALL RISK EXPOSURE

Who Is Affected

Builders of Composable Protocols

Cross-contract calls are the primary mechanism for composability on NEAR. Developers building DEXs, lending markets, yield aggregators, and NFT marketplaces are directly affected by the asynchronous execution model.

Key risks include:

  • Unbounded gas consumption in callback chains causing transaction failures.
  • State inconsistency if a cross-contract call succeeds but the callback logic fails to update local state.
  • Re-entrancy-like attacks where malicious contracts exploit the gap between a promise and its callback.

Action: Audit the error-handling logic in every Promise::then callback. Ensure that failed promises do not leave the calling contract in a broken state. Implement explicit gas budgeting for each leg of a cross-contract call chain.

implementation-impact
CROSS-CONTRACT EXECUTION RISK

Implementation Impact Areas

Asynchronous cross-contract calls are fundamental to NEAR's sharded runtime but introduce unique failure modes around gas management, callback handling, and state consistency. Teams must review their architecture against these specific risk vectors.

01

Callback Failure and State Inconsistency

A cross-contract call on NEAR is a two-step process: the initial call and an asynchronous callback. If the callback fails—due to a panic, an unhandled error, or insufficient gas—the state changes from the first call are not automatically reverted. This can leave a contract in a permanently broken state, such as having deducted a user's balance without completing a swap. Developers must implement explicit, idempotent cleanup logic in callback handlers and avoid state changes before external calls where possible.

02

Static Gas Budgeting and Attached Gas Forwarding

NEAR requires callers to pre-allocate a static gas budget for the entire execution tree. A common failure pattern is attaching insufficient gas to the initial call to cover both its own execution and the subsequent cross-contract call's execution. If the forwarded gas runs out mid-execution in the callback, the transaction fails with an ExceededGasLimit error. Teams must calculate gas requirements for the full call chain, including the callback's logic, and build in a safety margin to account for future contract upgrades that may increase execution costs.

03

Reentrancy via Callback Exploitation

The asynchronous callback model does not eliminate reentrancy risks; it transforms them. An attacker can exploit the gap between the initial call and the callback to manipulate state that the callback will later depend on, such as a price oracle or liquidity pool balance. The classic single-block reentrancy guard is insufficient. A secure pattern involves using a global execution lock or a strictly monotonic nonce that is validated at the start of the callback to ensure the contract's assumptions still hold.

04

Cross-Shard Composability and Latency

A call between contracts on different shards introduces a full block of latency for the receipt to be routed and executed. This delay breaks atomic composability assumptions common in single-threaded EVM environments. Flash loan arbitrage or multi-hop DEX aggregator logic that expects synchronous execution will fail. Architects must redesign these flows to be asynchronous, using a pattern of chained callbacks, and account for the risk that state changes during the latency window can invalidate the transaction's original intent.

06

Contract Upgrade Risks for Active Call Chains

Upgrading a contract's code while pending cross-contract callbacks are in flight can lead to undefined behavior. If the new code changes the interface or logic expected by the callback, the execution will fail in an unpredictable way. This is a critical risk for protocols with continuous user activity. A safe upgrade procedure requires pausing the contract, waiting for all pending receipts to resolve, deploying the new code, and then unpausing. Teams should implement a pausable pattern and a robust off-chain monitoring system to track pending receipts before any migration.

ASYNC CALL & GAS FAILURE MODES

Risk Matrix for Cross-Contract Interactions

Evaluates the primary failure modes, affected actors, and required actions for development teams building on NEAR's asynchronous, sharded runtime. Focuses on cross-contract call patterns, callback handling, and gas management to ensure composability and resilience.

Risk AreaFailure ModeAffected ActorsMitigation & Action

Unhandled Callback

A cross-contract call fails or panics, but the calling contract lacks a callback function to handle the result, leaving state permanently inconsistent.

DeFi protocols, DEXs, bridges, wallet backends

Implement mandatory callback logic for every cross-contract call. Conduct a formal architecture review of all promise chains.

Callback Gas Starvation

Insufficient gas is attached to the callback execution, causing it to fail silently and locking funds or corrupting state in the calling contract.

DeFi protocols, NFT marketplaces, relayers

Explicitly budget gas for callback execution using Gas::left() checks. Simulate callback gas usage under worst-case conditions.

Excessive Cross-Contract Gas

A single transaction spawns a deep chain of cross-contract calls that exceeds the per-transaction gas limit, causing a mid-execution revert.

Yield aggregators, multi-step routers, account aggregators

Flatten deep call chains into batched, independent transactions. Monitor per-transaction gas consumption against the current protocol limit.

Retry Logic Amplification

Automated retry logic on a failed cross-contract call creates a cascade of redundant transactions, wasting user gas and congesting the network.

Relayers, meta-transaction services, liquidation bots

Implement exponential backoff and nonce management. Verify retry logic does not trigger on deterministic failures.

Shard-Aware State Access

A contract assumes synchronous access to state on another shard, leading to read-after-write inconsistencies or unexpected delays in settlement.

Oracles, cross-shard DeFi protocols, chain abstraction services

Design contracts to be shard-agnostic. Do not rely on synchronous state views across account boundaries. Verify finality before acting on cross-shard data.

Unbounded Promise Chains

A contract creates a dynamic, data-dependent number of promises in a loop, risking a hard gas limit breach that is difficult to predict statically.

NFT minting platforms, airdrop distributors, DAO tooling

Cap the number of promises created in a single transaction. Use off-chain indexing and batched execution for operations on unbounded sets.

Receiver Contract Panic

A called contract panics due to an unhandled edge case, causing the entire promise chain to unwind and the initiating transaction to fail.

Composable DeFi protocols, cross-contract liquidators

Implement defensive wrappers for external calls. Conduct integration tests that simulate panics in every dependent contract.

CROSS-CONTRACT RESILIENCE

Development and Audit Checklist

A practical checklist for development and security teams to harden cross-contract interactions on NEAR's asynchronous, sharded runtime. Each item identifies a critical failure mode, explains why it matters, and specifies the signal or artifact that confirms readiness.

What to check: Every cross-contract call (Promise::create) must attach an explicit gas weight that is at least 10 TGas less than the available gas in the current execution context. The remaining gas must cover the callback execution.

Why it matters: NEAR's asynchronous execution model requires the calling contract to pre-pay for the execution of its own callback. If a contract forwards all available gas to an external call, the callback will fail with an ExceededGasLimit error, leaving the contract in an unrecoverable state. This is the most common cause of locked funds in cross-contract interactions.

Readiness signal: Unit tests that simulate the external contract consuming all forwarded gas and verify that the callback still executes successfully. A static analysis rule in the CI pipeline that flags any cross-contract call without an explicit gas subtraction.

Chains We Build On

Looking to build on a specific blockchain?

We build smart contracts, DeFi applications, wallets, tokenization platforms, and blockchain infrastructure across the major ecosystems teams choose today. That includes Ethereum, Arbitrum, Optimism, Polygon, Avalanche, Solana, Sui, Aptos, Hedera, Stellar, and NEAR, with support for additional EVM and non-EVM networks based on your product requirements.

EVM ecosystems

  • Ethereum logo
    Ethereum
  • Arbitrum logo
    Arbitrum
  • Optimism logo
    Optimism
  • Polygon logo
    Polygon
  • Avalanche logo
    Avalanche
  • Cronos logo
    Cronos

Non-EVM ecosystems

  • Solana logo
    Solana
  • Sui logo
    Sui
  • Aptos logo
    Aptos
  • Hedera logo
    Hedera
  • Stellar logo
    Stellar
  • NEAR logo
    NEAR

Additional ecosystems

  • Polkadot logo
    Polkadot
  • Cosmos logo
    Cosmos
  • TON logo
    TON
  • Cardano logo
    Cardano
  • Algorand logo
    Algorand
  • Tempo logo
    Tempo

Also available for Base, appchains, custom EVM networks, and cross-chain product architecture.

CROSS-CONTRACT CALL FAQ

Frequently Asked Questions

Common questions from development teams building composable protocols on NEAR's asynchronous runtime.

NEAR's asynchronous execution model means that a cross-contract call does not revert the calling transaction on failure. Instead, the failure is only visible in the callback. If your contract does not implement a proper callback handler, the failure is swallowed.

What to check:

  • Verify that every Promise::then call has an attached callback method.
  • Ensure the callback method inspects the PromiseResult for failure status.
  • Log or store failure data on-chain for debugging; off-chain monitoring of receipts is also recommended.

Why it matters: Silent failures lead to broken state assumptions. A DeFi protocol that assumes a token transfer succeeded without checking the callback can lose user funds or corrupt its internal accounting.

Trusted by Industry Leaders

Delivering blockchain solutions for 5+ years.

We have partnered with 50+ leading DeFi protocols, NFT ecosystems, and fintech innovators to build secure, scalable, and capital-efficient blockchain products.

Selected Partners & Clients

ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
“I've been working with Chainscore Labs for last 3+ years, they've consistently delivered with strong ownership across multiple projects. The team is reliable and detail-oriented.”
L
Lee Erswell
CEO, Telos Foundation
how to get started

How to get started?

If you're looking for blockchain integration, ChainScore Labs has 5+ years of experience helping teams build and integrate exchanges, wallets, smart contracts, tokenization solutions, and protocol-connected products, we can help you choose the right path, integrate securely, and get to production faster. Our team consists of experienced blockchain developers and architects who can help you with your blockchain integration needs.

01

Exploration & Strategy

Define your product goals and choose the right blockchain architecture for your use case.

02

Architecture & Design

Design the smart contracts, tokenomics, and security parameters of your system.

03

Development & Integration

Build and integrate with wallets, oracles, and front-end dApps for a seamless experience.

04

Security & Launch

Comprehensive audits followed by a risk-managed mainnet deployment to protect your users.

Start a build

Need a blockchain engineering team?

Send the project context and we will respond with next steps, scope questions, and a practical path to delivery.