Introducing a new way to review your PRs.

Read the announcement

near / nearcore

Reference client for NEAR Protocol

View on GitHub

20 documents · Updated Nov 23, 2026

docs / runtime-execution

Runtime execution

The near-runtime applies one shard chunk to its prior state. It turns signed transactions and trusted receipts into a deterministic state root, new receipts, and execution outcomes. It also keeps gas, compute, storage proofs, cross-shard flow, and account funding within protocol limits. The result feeds chain data processing and the shard state described in storage and state. Contract calls use transaction and contract execution, which crosses into virtual-machine execution.

Runtime role

Shard state transition

The runtime is the state-transition engine for one shard. A shard is one partition of chain state. The runtime reads the chunk inputs and the shard's Merkle-tree state, then produces the state and records that the chain needs to carry the result forward.

Its main outputs are:

  • a new state root and state changes;
  • execution outcomes for transactions and receipts;
  • outgoing and delayed receipts;
  • validator proposals, storage proofs, and contract access updates;
  • congestion and bandwidth data for later chunks.

Transactions create the first receipt. Contract execution can create more receipts for local work or for accounts on other shards. An external call executes without creating a receipt and has its own acceptance and resource limits. The asynchronous receipt model lets shards progress independently instead of making a cross-shard transaction atomic.

References: runtime/…/lib.rs• L475-514 runtime/…/lib.rs• L2020-2122 runtime/…/lib.rs• L2986-3130 runtime/…/apply.rs• L1024-1051

Transaction and receipt model

A transaction envelope is signed user work or a supported unsigned external call. A receipt is trusted work that a chunk accepts for later execution. Signed transactions are validated before they create receipts. External calls follow a separate direct-execution path, while newly created and incoming receipts are validated before the runtime stores or runs them.

Receipts have different roles in the execution graph:

  • Action receipts run account or contract actions.
  • Data receipts deliver a return value or failure to work that waits for it.
  • Yield and resume receipts pause work until a response or timeout.
  • Global contract distribution receipts copy shared contract code across shards.

An action receipt runs its actions in order. Its data dependencies must be ready first. A repeated transaction hash in one chunk is skipped so that it cannot produce two outcomes under the same identity. New work follows the current validation rules, while older receipts already in state remain processable under the compatible existing-receipt rules. This protects in-flight work when a protocol rule becomes stricter or removes an action.

References: runtime/…/verifier.rs• L929-1041 runtime/…/action_validation.rs• L88-170 runtime/…/lib.rs• L959-1052 runtime/…/lib.rs• L2830-2867 runtime/…/apply.rs• L696-739

Execution lifecycle

Chunk application

Runtime::apply coordinates the complete transition for one chunk. It prepares read-ahead work, updates validator accounts when needed, schedules cross-shard capacity, admits transactions, processes receipts, and finalizes one chain-facing result.

The lifecycle follows this order:

  1. Start optional transaction read-ahead.
  2. Apply validator account updates.
  3. Load delayed receipts and run the bandwidth scheduler.
  4. If the chunk is missing, finalize scheduling state and stop.
  5. Forward receipts held in outgoing buffers.
  6. Validate transactions and create local or outgoing receipts.
  7. Process local, delayed, and incoming receipts.
  8. Resolve data dependencies and expired yields.
  9. Validate and finalize state, outcomes, proofs, queues, and shard metadata.

The scheduler still runs for a missing chunk. This keeps scheduling state aligned without executing work that the chunk does not contain.

The diagram shows how chunk inputs become state and chain outputs.

flowchart LR
    A[Chunk state and inputs] --> B[Validator updates]
    B --> C[Bandwidth scheduling]
    C --> D[Buffered receipt forwarding]
    D --> E[Transaction admission]
    E --> F[Receipt processing]
    F --> G[State validation and finalization]
    G --> H[New state root]
    G --> I[Execution outcomes]
    G --> J[Outgoing and delayed receipts]
    G --> K[Proofs and shard metadata]
    L[Incoming receipts] --> F

References: runtime/…/lib.rs• L2020-2122 runtime/…/lib.rs• L2921-2976 runtime/…/lib.rs• L2986-3130 runtime/…/apply.rs• L237-256

Transaction admission

Transaction admission decides whether signed work can create an execution receipt. It checks the envelope and actions first. It then checks the signer account, authorization key, nonce, balance, allowance, storage stake, and action permissions before it applies the transaction charge.

The runtime supports three authorization paths:

PathMain state usedResult when accepted
Regular access keyOne access-key nonce and optional allowanceAccount charge and key update
Gas keyA selected gas-key nonce and gas-key balanceGas-key charge plus account deposit handling
Self-signed universal initializationThe uninitialized account's bootstrap nonceAccount charge before state initialization installs keys

An accepted transaction creates a receipt and an outcome that points to it. A failed transaction creates an outcome without an execution receipt. A gas-key transaction can charge the gas-key work and nonce even when the account cannot cover its deposit, so admission must keep those two balances separate.

Action rules also bound the work carried by transactions and newly created receipts. They cover action shape, action count, deployment and state-init size, state-init entries and keys, gas-key nonce creation, delegated work, dependencies, and prepaid gas. The checks apply to each receipt and recurse into delegated actions. New receipts use the strict current rules; existing receipts use compatible rules so that in-flight work can finish. Deterministic and universal state initialization also bind the account identity to the supplied state and settle its deposit against storage needs.

For the detailed action boundary, see transaction and contract execution.

References: runtime/…/verifier.rs• L99-201 runtime/…/verifier.rs• L279-432 runtime/…/verifier.rs• L554-927 runtime/…/action_validation.rs• L40-170 runtime/…/lib.rs• L2171-2340

Receipt scheduling

Receipt scheduling decides which accepted work can run in the current chunk. The runtime gives local receipts priority, then delayed receipts, then incoming receipts. It stops when the chunk's compute budget or storage-proof budget is full.

When a receipt cannot run, the runtime keeps it in the right waiting place:

  • a receipt with missing data becomes postponed;
  • a data receipt releases a waiting action when its dependencies are complete;
  • a yielded receipt waits for a resume receipt or its timeout;
  • work that exceeds the current chunk budget enters the delayed queue.

The runtime checks limits for the whole receipt as well as for the chunk. An oversized promise input or storage proof fails that receipt and cleans up its waiting data. It does not stop unrelated receipts.

References: runtime/…/lib.rs• L1573-1702 runtime/…/lib.rs• L2616-2795 runtime/…/lib.rs• L2798-2879 runtime/…/lib.rs• L2912-2976

Action receipt execution

An action receipt applies account and contract actions in order. These actions can move funds, manage keys, deploy or select code, call a contract, create accounts, stake, delete accounts, or create more receipts.

The receipt is the rollback boundary. If an action fails, later actions do not run and receipt-scoped state changes and new receipts are discarded. Gas, logs, profiles, and the failure remain in the outcome. A successful receipt commits its account state, sends or runs its generated receipts, and creates data receipts for dependent work.

Access keys and gas keys are part of the same account state transition. Key storage, gas-key nonce records, balance movements, refunds, and account deletion must stay consistent with the account's storage stake. Deterministic and universal state initialization install code, data, and keys only after the account identity and storage rules pass. A failed install rolls back the partial work.

References: runtime/…/lib.rs• L682-957 runtime/…/lib.rs• L959-1216 runtime/…/lib.rs• L596-652 runtime/…/apply.rs• L381-606

Contract preparation

Contract preparation makes executable code ready before a function call needs it. It first resolves the contract identity and checks the call's contract-loading cost. It can then prepare code in parallel, while execution remains the authority for the state transition.

Preparation is skipped for actions that can change an account's executable code in the same chunk. When it is used, the runtime checks that the prepared identity still matches the code selected at execution time. If preparation is missing or stale, the runtime prepares the call on the execution thread.

Optional read-ahead and cache warming improve latency only. The runtime can request account, access-key, gas-key nonce, and contract-code data for transactions and receipts before their work runs. These requests use bounded background work and a separate landing area, so a dropped, failed, or stale prefetch does not change consensus state or the execution result. Function-call code is prefetched only when its gas can cover the protocol's contract-loading base cost. The runtime also records protocol-level compilation status so cold code bytes can be accounted for even if the ordinary cache later evicts the code.

Compilation status is tied to the code hash and VM generation. It deduplicates cold-code accounting across accounts and repeated calls, and it remains available to replay even when a receipt later rolls back or the local compiled-code cache is empty.

References: runtime/…/pipelining.rs• L33-75 runtime/…/pipelining.rs• L162-335 runtime/…/pipelining.rs• L363-475 runtime/…/prefetch.rs• L55-216 runtime/…/lib.rs• L2642-2857 runtime/…/lib.rs• L3702-3787 runtime/…/contract_compilation_status.rs• L112-196 runtime/…/contract_preparation.rs• L57-203

External contract calls

External contract calls are unsigned calls that ask a contract to accept work outside the normal transaction and receipt admission flow. The runtime gives each call a protocol-defined execution mode, checks that the contract can pay, runs its reserved method, and accepts the state changes only when the call returns with a valid charge.

The runtime limits these calls by their share of chunk compute and recorded storage proof. An admitted call is counted after processing, whether validation or contract execution refuses it. A call refused because a share is already full is counted neither as work nor as recorded proof because the runtime rejects it before reading the contract account. A refused call leaves its run writes and account charge out of state, while bounded validator work before refusal can still count toward compute. Generated receipts are checked as new receipts before an accepted call can emit them. The chunk producer can dry-run the same path before packing the call, so packing and apply use the same acceptance rules when they use the same validator-account context.

External calls see the parent block context. They have no signer, attached deposit, promise results, random seed, or receipt output receivers in their execution context. An accepted call can still create validated receipts for later work. A successful call reports its return value, logs, resource use, and charge in its own execution outcome.

This boundary complements transaction and contract execution: ordinary function calls enter receipt work, while external calls are accepted or refused as one bounded chunk input.

References: runtime/…/external_call.rs• L65-129 runtime/…/external_call.rs• L148-230 runtime/…/external_call.rs• L272-372 runtime/…/external_call.rs• L374-460 runtime/…/external_call.rs• L635-869 runtime/…/apply.rs• L699-742 runtime/…/apply.rs• L1079-1121

State transition and outcomes

State validation and rollback

The runtime stages writes in a trie update. A trie update is the working state layered over the shard's committed Merkle tree. It commits completed phases and rolls back the current receipt when execution or a receipt-level check fails.

Before a successful receipt commits, the receiver must have enough balance and locked stake for its stored state. Finalization then commits delayed-queue changes and permitted state patches, computes the new root, and returns trie changes, state changes, proofs, and contract updates. These outputs describe the same transition that the outcomes report.

References: runtime/…/lib.rs• L1048-1052 runtime/…/lib.rs• L1168-1216 runtime/…/lib.rs• L2986-3130 runtime/…/verifier.rs• L44-91 runtime/…/apply.rs• L1151-1222

Resource and fee accounting

Gas pays for bounded execution work. Compute is a separate work limit used to bound validator effort. The runtime accounts for transaction conversion, receipt execution, contract work, storage access, receipt creation, and signature checks across the sender and receiver shards.

The signer pays to convert a transaction into a receipt. The receipt carries the remaining execution budget to its receiver. Unused gas and eligible deposits become refund receipts after execution. The runtime also tracks burnt tokens, receiver rewards, subsidies, storage charges, and balance deficits so chunk totals reconcile with account state.

Receipt fees use the protocol configuration from the time the receipt was created for static gas charges. The current configuration supplies the execution compute charge. This keeps a receipt's prepaid gas stable across protocol changes while keeping validator work priced by current rules.

Contract loading and compilation are part of this economic flow. Cold code bytes are reported for runtime accounting, while background preparation does not add a consensus charge. Contract storage reads and writes also record trie access for storage-proof limits and deterministic resource accounting. Access-key and gas-key storage use the representation stored in shard state, while send-side accounting uses the representation placed on the wire.

References: runtime/…/receipt_runtime_configs.rs• L11-95 runtime/…/lib.rs• L682-705 runtime/…/lib.rs• L1195-1250 runtime/…/ext.rs• L150-160 runtime/…/ext.rs• L165-240 runtime/…/function_call.rs• L264-289 runtime/…/metrics.rs• L437-473

Execution outcomes

An execution outcome is the chain-facing record of processed work. It reports success or failure, returned data or a receipt ID, logs, gas and compute use, burnt tokens, the executor, and the receipt IDs created by the work.

The state root and outcomes must describe one deterministic transition. Receipt-origin mappings can connect generated receipts to their transaction or parent receipt. Action metadata preserves the contract identity seen at each action position, including empty entries for actions that did not run after an earlier failure. This gives chain consumers and RPC clients a stable view of the receipt graph and its result.

References: runtime/…/lib.rs• L475-514 runtime/…/lib.rs• L558-652 runtime/…/lib.rs• L3081-3130 runtime/…/external_call.rs• L132-146 runtime/…/external_call.rs• L503-565

Contract execution boundary

FunctionCall is the runtime boundary for smart-contract execution. The runtime supplies the account, contract identity, call input, promise results, attached deposit, gas, block context, and a controlled host interface. The VM returns a value, promise reference, or guest-level failure, and the runtime converts it into state changes, receipts, logs, resource use, and action status.

The host interface lets contract code read context and state, write contract storage, and build asynchronous work. Storage writes stay in the current trie update until the receipt commits. Storage reads, writes, and removals also record the trie access and proof work that the call consumes. Host calls record storage access for deterministic proof and resource accounting. Some context values are unavailable in views or external calls because those modes do not have the same signer or block guarantees.

The runtime separates a normal contract failure from an infrastructure failure. A guest trap, method error, or host error becomes a function-call failure. Missing witness data, storage errors, cache errors, and nondeterministic VM errors remain runtime failures because they cannot safely produce a chain result.

For the VM contract and host behavior, see virtual-machine execution.

References: runtime/…/function_call.rs• L121-291 runtime/…/function_call.rs• L294-475 runtime/…/ext.rs• L150-329 runtime/…/ext.rs• L332-455 runtime/…/apply.rs• L1224-1235

Runtime views

Runtime views read shard state without committing a consensus transition. They expose account data, local or global contract code, access keys, gas-key nonces, contract storage, and bounded read-only function calls for tools such as RPC.

Views reuse contract resolution and VM execution with a view gas cap and no attached deposit. They return typed errors for missing resources, invalid cursors, size limits, proof restrictions, VM failures, and storage failures. Access-key listings stay within the requested account and hide gas-key nonce rows. Paginated access-key requests are capped and return a cursor when more keys remain. State pages have item and byte bounds, while proofs are available only for unpaginated state reads.

References: runtime/…/mod.rs• L125-212 runtime/…/mod.rs• L225-381 runtime/…/mod.rs• L383-484 runtime/…/mod.rs• L486-655 runtime/…/errors.rs• L1-155

Cross-shard coordination

Receipt forwarding

Receipt forwarding moves generated work to its receiver shard. The receipt sink sends work when the current bandwidth and congestion limits allow it. Otherwise it stores the receipt in an outgoing buffer for a later chunk.

Buffered receipts are forwarded before new receipt output in the next chunk. This preserves progress for accepted work and applies backpressure when a destination cannot accept more work. Instant receipts do not leave the shard; the runtime executes them immediately after their parent receipt.

References: runtime/…/congestion_control.rs• L140-185 runtime/…/congestion_control.rs• L287-315 runtime/…/lib.rs• L2097-2105 runtime/…/lib.rs• L2881-2909

Congestion and bandwidth

Congestion control limits work sent to a busy shard. The bandwidth scheduler grants a bounded number of receipt bytes between each pair of shards. Together they limit queue growth without blocking work that uses other shard links.

The scheduler uses shard status, prior bandwidth requests, congestion levels, missed chunks, and the prior block to compute grants. The runtime stores the scheduler state and returns new requests and congestion information with the chunk result. During resharding, buffers for a retired parent shard are included in the request for its child and are drained through the current layout. Self-mapped parent shards are not counted twice.

The runtime keeps congestion totals for delayed and buffered receipts. It uses those totals to select an allowed destination when the local shard is fully congested, and it exposes queue size, receipt bytes, and unused forwarding capacity through runtime metrics.

References: runtime/…/congestion_control.rs• L45-137 runtime/…/congestion_control.rs• L231-315 runtime/…/congestion_control.rs• L471-632 runtime/…/lib.rs• L3018-3044 runtime/…/metrics.rs• L866-920

Global contract distribution

Global contracts let accounts select shared code by a code hash or account identity. Deployment pays for the stored code and creates a distribution receipt. Each shard accepts only fresh distribution work, stores the code, and forwards it to the next shard that needs it.

Distribution records code access and compilation status for later validation. Same-chunk calls use the current state even when the compiled cache is cold. A stale distribution receipt does not repeat deployment work. Compilation status records cold bytes once for a code hash and VM generation, so replay and later calls keep the same protocol view even when local cache contents change.

References: runtime/…/lib.rs• L760-781 runtime/…/function_call.rs• L477-535 runtime/…/pipelining.rs• L180-210 runtime/…/contract_compilation_status.rs• L148-275

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep transaction authorization, gas-key charging, bootstrap nonce use, and receipt creation aligned across verifier.rs and lib.rs.
  • Keep action validation consistent for user transactions, generated receipts, delegated actions, state initialization, gas-key nonce creation, and congestion limits. Apply stricter rules only to new receipts when older in-flight receipts must remain executable.
  • Preserve the receipt rollback boundary. New account writes, access-key rows, promise state, compilation status, and generated receipts must enter the right commit path.
  • Keep receipt static gas pricing tied to its creation protocol version while current compute pricing follows the active version.
  • Keep deterministic and universal state initialization identity checks, storage accounting, key nonce seeding, deposit settlement, and actor permissions aligned.
  • Keep contract identity resolution consistent across local code, global code, wallet code, preparation, pipelining, views, and VM execution.
  • Keep VM execution modes aligned. Internal calls, external calls, and views do not have the same signer, gas, promise-result, random-seed, or block-context semantics.
  • Keep external-call acceptance and dry-run decisions aligned with compute and storage-proof shares. A call that is refused after a failed run must not leave its writes or account charge.
  • Keep cold compilation accounting separate from optional cache warming and prefetching. Background work must not change state, proof, gas, or outcome data.
  • Keep prefetch eligibility aligned with the data that validation and execution will read, including access keys, gas-key nonce rows, and contract code loading costs.
  • Keep the preparation scan bound and its resume signal aligned with local, delayed, incoming, and resharded receipt sources.
  • Keep storage-access accounting aligned with trie node cache hits, proof recording, host calls, and the gas and compute costs configured for those operations.
  • Keep outcome action positions, contract metadata, receipt IDs, and receipt-origin mappings aligned with downstream chain and RPC consumers.
  • Keep forwarding, delayed queues, congestion information, and bandwidth requests consistent for buffered, local, incoming, and global-contract receipts. Include retired-parent buffers once during resharding.
  • Keep view pagination boundaries and typed errors aligned with access-key nonce rows, account prefixes, state-size limits, and proof support.

Important failure modes

TriggerConsequenceGuard
Invalid transaction authorization, nonce, balance, or action shapeThe transaction gets a failed outcome and creates no execution receipt.Admission validates the envelope, signer state, authorization path, and action limits before receipt creation.
Gas-key work cannot cover its account deposit or storage needGas-side work and nonce update can remain charged, but no execution receipt is created.The gas-key verdict separates gas-key charging from account deposit acceptance.
A receipt exceeds the chunk budgetThe receipt remains delayed for a later chunk.Local, delayed, and incoming processing checks the shared compute and proof limits.
A receipt has missing or oversized promise dataThe receipt waits, or fails with its dependency state cleaned up.Data dependencies and whole-receipt input limits are checked before execution.
A new receipt exceeds state-init, deployment, or gas-key nonce limitsThe work is rejected before it can create oversized state, code work, or nonce rows.New-receipt action validation totals these resources across all actions and delegated action lists.
An action fails inside a receiptLater actions and receipt-scoped writes or receipts are discarded.The trie update rolls back at the receipt boundary.
The receiver cannot fund its stored stateThe receipt fails and its state changes do not persist.Storage stake is checked before the receipt commits.
A state-init deposit cannot cover the required storage stakeAccount initialization fails and its partial state is rolled back.State-init handlers settle the deposit against storage before commit.
Prepared code no longer matches the account's current codeThe prepared artifact is discarded or preparation runs in the execution thread.Code-changing actions block preparation and execution checks the expected identity.
A preparation scan reaches its bound before it finds more workLater receipts could remain unprepared if the caller stops scanning.The bounded scheduler returns a resume signal until it reaches the end of the source.
VM, cache, witness, or storage work cannot produce a trustworthy resultThe runtime returns an infrastructure error instead of a normal contract failure.Function-call execution separates guest failures from runtime errors.
An external call exceeds its chunk shareThe call is refused without reading or changing its contract state.The runtime checks compute and recorded-proof shares before the call's account read.
An external call fails, cannot pay, or emits invalid receiptsIts run writes, account charge, and generated receipts are rolled back, and the outcome reports refusal.External calls validate the reserved-method result, new receipts, balance, storage stake, and commit only after all checks pass.
A generated receipt is invalidThe current action receipt fails instead of creating invalid work.New receipts pass receipt validation before forwarding.
A receipt is invalid under new rules but already exists in stateThe old work could become unprocessable if new and existing rules are merged.Existing receipts use compatible validation that is less strict than new-receipt validation.
A receipt uses the wrong protocol version for static pricingIts refund or charge can differ from the amount prepaid when it was created.Receipt runtime configs retain creation-time gas pricing and use current compute pricing.
A receipt cannot leave because of bandwidth or congestionIt stays in an outgoing buffer and runs later.The receipt sink persists blocked work and drains it before new output.
A view crosses an account, size, cursor, or proof limitThe query returns a typed view error without changing chain state.The state viewer bounds account-scoped iteration and function-call execution.
A global contract distribution is stale or a same-chunk cache is coldOld work is ignored, or a valid same-chunk call could be rejected.Distribution freshness and current state records control code visibility.

Key files

FileWhy to read it
runtime/…/lib.rsMain chunk lifecycle, transaction and receipt processing, rollback, finalization, outcomes, and ApplyResult.
runtime/…/verifier.rsTransaction admission, authorization paths, storage checks, and receipt validation.
runtime/…/action_validation.rsShared limits and protocol checks for actions in new and existing receipts.
runtime/…/receipt_runtime_configs.rsCreation-time gas pricing and current-version compute pricing for receipts.
runtime/…/congestion_control.rsReceipt forwarding, outgoing buffers, congestion totals, bandwidth requests, and resharding handoff.
runtime/…/external_call.rsExternal call limits, dry-run parity, execution context, charging, receipt validation, and rollback.
runtime/…/function_call.rsRuntime-to-VM call boundary, outcomes, receipts, and VM error handling.
runtime/…/ext.rsContract storage access, proof recording, trie resource accounting, and promise creation.
runtime/…/prefetch.rsBounded read-ahead for transaction and receipt state without consensus-side effects.
runtime/…/pipelining.rsSafe parallel preparation and same-chunk code-change handling.
runtime/…/mod.rsRead-only account, code, key, state, and function-call views with pagination limits.
runtime/…/metrics.rsRuntime signals for receipt work, resource use, preparation, proof size, and congestion.
runtime/…/apply.rsEnd-to-end guarantees for chunk application, delayed receipts, external calls, rollback, dry-run parity, validator updates, and outcomes.
runtime/…/contract_compilation_status.rsGuarantees for cold-code accounting, VM-generation changes, rollback, and cache-independent replay.
runtime/…/contract_preparation.rsGuarantees for bounded contract-preparation scans across delayed and resharded receipt queues.
runtime/…/mod.rsShared runtime test setup and checks for state and VM type cost alignment.