Introducing a new way to review your PRs.

Read the announcement

near / near-sdk-rs

Rust library for writing NEAR smart contracts

View on GitHub

20 documents · Updated Nov 20, 2026

docs / runtime-environment-and-context

Runtime environment and execution context

The runtime environment is the contract-facing API for reading the current call and blockchain state, using contract storage, emitting logs, returning data, and receiving results from earlier promises. The near_sdk::env API combines typed SDK wrappers with shared helpers from the near-sdk-env crate, while the NEAR runtime supplies the execution facts. It is the runtime part of contract SDK authoring.

Environment API

The environment API is the boundary between contract code and the NEAR host. The shared near-sdk-env crate provides low-level hashing and related helpers across wasm32 and non-wasm32 builds. Wasm32 builds use NEAR host support, while non-wasm32 builds use Rust implementations. near_sdk::env adds SDK types and contract-oriented behavior around them. Most calls read data for the current execution. Storage and output calls change the execution result or the contract's persistent data.

The environment also keeps two hash naming patterns for compatibility. Older hashes have both byte-vector and fixed-array forms. Newer hashes use a fixed-size array from the base function name.

The main API groups are:

GroupContract-facing purpose
ContextIdentify the contract, signer, predecessor, chain, block, and call input.
EconomicsRead account balances, attached deposit, storage use, and gas.
Randomness and cryptographyRead the block random seed and use host-supported cryptographic checks.
StorageRead, write, remove, and inspect key-value data.
Results and outputRead promise results, return bytes, log messages, and stop with an error.
PromisesSchedule later work and configure actions for another account.

Contract authors should use env or higher-level SDK APIs instead of the raw host boundary. The higher-level Promise API is the usual choice for cross-contract work. See promises and cross-contract calls for that flow. The low-level relationship between SDK calls and host functions is described in NEAR host ABI bindings.

The main boundary between a contract and the host is shown below.

flowchart LR
    C[Contract method] --> E[near_sdk::env and near-sdk-env]
    E --> H[NEAR host]
    H --> R[Context and results]
    H --> S[Storage and logs]
    H --> P[Promises and return value]

References: near-sdk/…/env.rs• L1-16 near-sdk/…/env.rs• L37-41 near-sdk/…/env.rs• L188-190 near-sdk-env/Cargo.toml• L12-16

Execution context

Execution context describes who caused the current call, which contract is running, what data arrived with the call, and where the call sits in chain time. The runtime supplies these values and the environment API makes them available to contract code.

Account identities

The account identity APIs distinguish the contract that runs now from the accounts that began or directly caused the call. This distinction is important in access checks and in cross-contract flows.

APIMeaning
current_account_id()Account that owns the running contract.
current_contract_code()Code source used by the running contract when deterministic account IDs are enabled.
current_global_contract_id()Global code identifier for the running contract when one applies.
signer_account_id()Account that signed the original transaction or began the call chain.
signer_account_pk()Public key used for the original signature.
predecessor_account_id()Account that directly called the current contract. On a direct transaction it matches the signer.
refund_to_account_id()Account that receives a refund after a failed action when deterministic account IDs are enabled.

Use predecessor_account_id() for the immediate caller. Do not use the signer as a substitute when a request can pass through another contract.

References: near-sdk/…/env.rs• L188-314 near-sdk/…/mocked_blockchain.rs• L343-394

Call input

input() reads the raw bytes sent with the current contract call. It returns None when the call has no input. The generated method boundary normally deserializes these bytes into method arguments. Direct environment use is useful for custom formats or migration paths. See contract interface macros for the method boundary that consumes this input.

References: near-sdk/…/env.rs• L316-335 near-sdk/…/mocked_blockchain.rs• L367-378

Block and chain data

The environment exposes the chain ID and the current block height, block time, and epoch height. Block time is available in nanoseconds through block_timestamp() and as milliseconds through block_timestamp_ms().

These values describe the execution point. They do not provide a wall-clock service that advances during one call.

References: near-sdk/…/env.rs• L337-412 near-sdk/…/mocked_blockchain.rs• L375-395

Economic context

Economic APIs let a contract reason about the funds and gas available to the current execution. They separate the account's balance from the deposit attached to this call. They also separate the gas limit from gas already used.

APIMeaning
account_balance()Current balance of the contract account, including the attached deposit.
account_locked_balance()Balance locked for possible validator staking.
attached_deposit()Funds attached to this call and deposited before execution starts.
storage_usage()Storage used by the contract account.
storage_byte_cost()SDK value for the price of one byte of storage.
prepaid_gas()Gas attached to the call for execution fees.
used_gas()Gas already consumed by the current execution.
validator_stake(account_id)Current stake of a named validator account, or zero when it is not a validator.
validator_total_stake()Total validator stake in the current epoch.

The method annotation layer uses attached_deposit() to reject deposits on methods that are not marked payable. Contract code can use the same value to apply payment rules of its own.

References: near-sdk/…/env.rs• L415-503 near-sdk/…/env.rs• L2688-2733 near-sdk/…/mocked_blockchain.rs• L392-453

Randomness and cryptographic results

The runtime gives each block a 32-byte random seed derived from the block's verifiable random value. random_seed() and random_seed_array() return the same seed for repeated reads in the same method and block. Contract code can use it as input to a deterministic random process within that execution.

The environment also exposes host cryptographic operations such as hashing, signature checks, curve operations, and post-quantum signature verification. These operations return bytes, a Boolean, or an optional result. Some newer operations require a minimum host protocol version. The caller must apply any protocol rule that the host operation does not enforce. For example, code that treats P-256 signature bytes as unique must require low-S form. Code that needs BLS subgroup membership must use an operation or check that provides it.

References: near-sdk/…/env.rs• L10-16 near-sdk/…/env.rs• L505-581 near-sdk/…/env.rs• L896-968 near-sdk/…/env.rs• L584-1165 near-sdk/…/mocked_blockchain.rs• L455-610

Persistent storage

Contract storage is a persistent key-value space. The environment stores keys and values as bytes and reports whether a key existed when a write or remove occurs.

The direct storage calls form a small read/write model:

  • storage_read(key) returns the bytes for a key or None.
  • storage_write(key, value) replaces or creates a value and returns whether the key existed.
  • storage_remove(key) deletes a value and returns whether the key existed.
  • storage_has_key(key) checks presence without loading the value.
  • storage_get_evicted() reads the prior value displaced by the most recent write or remove.

The SDK state helpers use the reserved STATE key. state_read() deserializes the contract state when it exists, state_write() serializes and stores it, and state_exists() checks that key. The contract method boundary relies on these helpers when it loads and saves a contract state value. See contract state and initialization for how this state lifecycle begins.

References: near-sdk/…/env.rs• L2815-2957 near-sdk/…/mocked_blockchain.rs• L1343-1379

Storage-backed collections

The store collections build larger data structures on the same environment storage API. They load and save only the data needed by an operation instead of treating a full native collection as one value. This makes them the higher-level choice for contract state that must scale beyond a small in-memory value.

Most store collections keep changes in memory until Drop or an explicit flush(). LookupSet writes directly on each operation. This persistence timing matters when contract state is written before the collection has flushed its own changes. See persistent collections and store for collection choices and lifecycle rules.

References: near-sdk/…/mod.rs• L16-23 near-sdk/…/mod.rs• L63-98

Logs and returned values

Output APIs send the result of the current execution back to the runtime or record a message for observers. log_str() writes a UTF-8 log message, value_return() sets raw return bytes, and panic_str() or the panic host calls terminate execution with an error.

Generated method wrappers normally serialize a method's return value and call value_return() for the contract author. Direct use of value_return() is mainly for low-level entry points or custom return formats. Logs are also the channel used by the SDK event API to emit NEP-297 event records. See events, JSON, and contract types for event format rules.

References: near-sdk/…/env.rs• L2736-2813 near-sdk/…/mocked_blockchain.rs• L613-663

Promise results

Promise result APIs let a callback inspect the outcomes of work scheduled by earlier promises. A callback first reads promise_results_count() and then reads each result by its zero-based index.

The result API has two forms:

APIBehavior
promise_result_checked(index, max_len)Returns bytes on success and reports failure or an over-size result. This is the preferred form for data from an unknown contract.
promise_result(index)Returns PromiseResult, but is deprecated because it does not bound the result size.

The callback interface features turn these host results into typed method arguments. Promise-yield APIs can also pause work and later resume a callback with a supplied payload or a timeout result. The low-level environment also supports caller-chosen yield IDs for flows that need a stable request key. See promises and cross-contract calls for the full asynchronous flow.

References: near-sdk/…/env.rs• L2211-2307 near-sdk/…/env.rs• L2334-2550 near-sdk/…/mocked_blockchain.rs• L1326-1341

Unit-test environment

Unit tests replace the runtime host with a mock blockchain. The mock forwards environment calls to the same host behavior used by the runtime, so host errors can fail the unit test in the same way that they abort a contract on chain.

VMContextBuilder creates the call context. testing_env! installs it with optional VM, fee, validator, storage, and promise-result data. The test context can set identities, input, block values, balances, attached deposit, gas, random seed, view mode, and other runtime facts. The mock also exposes captured logs and created receipts so tests can inspect observable output and scheduled actions. Receipt actions cover calls, transfers, account and key changes, yield work, and newer global-contract, gas-key, deterministic-account, and universal-account actions when their features are enabled.

The mock keeps storage when testing_env! installs a new context. This lets a test model several executions in sequence. A callback test must supply the expected promise results. The mock also applies host limits to inputs, logs, and returned values, so tests can observe host failures instead of bypassing them.

References: near-sdk/…/mocked_blockchain.rs• L15-29 near-sdk/…/mocked_blockchain.rs• L40-159 near-sdk/…/mocked_blockchain.rs• L161-195 near-sdk/…/mocked_blockchain.rs• L198-313 near-sdk/…/receipt.rs• L8-130 near-sdk/…/receipt.rs• L133-160 near-sdk/…/receipt.rs• L173-310

Change checklist

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

  • Keep the meanings of signer and predecessor aligned with private-method checks and callback authorization.
  • Keep new environment host calls aligned across the near-sdk-env helper surface, the near_sdk::env wrapper, the near-sys declaration, and the unit-test mock.
  • Keep storage key and serialization changes aligned between state_read/state_write, contract initialization, and migration code.
  • Keep callback result size limits aligned between promise-result readers and generated callback argument handling.
  • Keep VMContextBuilder fields aligned with runtime context fields so unit tests do not hide missing execution data.
  • Keep event output changes aligned with the log format consumed by event readers.
  • Keep feature-gated deterministic-account context aligned with the host protocol version that supports it.
  • Keep receipt action mappings aligned with host actions so tests continue to inspect the same cross-contract effects, including feature-gated account, key, global-contract, gas-key, yield, and universal-account actions.
  • Keep protocol-gated cryptographic and yield APIs aligned with the minimum host version that supports them.
  • Keep hash helper names and return shapes aligned between near-sdk-env re-exports and the SDK environment API.
  • Keep validator stake reads aligned with the epoch context used by the contract's economic rules.

Important failure modes

TriggerConsequenceGuard
A contract trusts signer_account_id() as the immediate callerA forwarded call can pass an authorization check meant for the direct predecessorUse predecessor_account_id() for caller checks.
A callback reads an unbounded result from an unknown contractReading a large result can consume the available gasUse promise_result_checked() with a suitable limit.
Contract state bytes do not match the expected Borsh typestate_read() panics and the method cannot continueUse an explicit migration path before changing the state shape.
A method receives a deposit without accepting itThe generated wrapper panics before the method runsMark the method payable only when its business rules handle the deposit.
A test changes context without supplying callback resultsCallback code sees no matching promise resultPass the expected PromiseResult values to testing_env!.
A storage collection is flushed after top-level state persistenceCollection changes may not be included in the stored state lifecycle expected by the methodUnderstand collection flush timing and use the collection's flush() when needed.
A contract treats every valid P-256 signature as a unique byte valueHigh-S and low-S forms can represent the same signed messageRequire low-S form when signature bytes must be unique.
A contract assumes every accepted BLS curve point is in the required subgroupA curve operation can accept a point outside the subgroup needed by the protocolUse an operation that checks subgroup membership or add the required check.
A contract calls a protocol-gated host function on an older runtimeThe host rejects the call or the contract cannot use the requested featureCheck the host protocol requirement before relying on the API.
A caller resumes a yield with the wrong or reused IDThe waiting callback does not receive the intended payloadTreat the yield ID as a stable request key and check the resume result.
A mock host shim does not match a runtime host callUnit tests can miss a chain failure or report a different resultKeep the mock host surface and its context conversion aligned with the runtime host.

Key files

FileWhy to read it
near-sdk/…/env.rsDefines the public contract environment for context, economics, storage, output, cryptographic host calls, and promise results.
near-sdk-env/Cargo.tomlDefines the shared environment crate and its target-specific host and Rust support for hashing and related helpers.
near-sys/…/lib.rsShows the host boundary that supplies runtime data and accepts contract effects.
near-sdk/…/state.rsConnects the reserved contract state value to the general storage API.
near-sdk/…/context.rsDefines the execution facts that tests can control.
near-sdk/…/mod.rsDefines how tests install mock context and inspect logs and receipts.
near-sdk/…/mocked_blockchain.rsConnects the test context to the runtime host behavior and captures logs, storage, and scheduled effects.
near-sdk/…/receipt.rsDefines the test view of receipts and scheduled actions so cross-contract effects can be inspected.
near-sdk/…/mod.rsExplains how higher-level persistent collections use the environment storage model.
near-sdk/…/promise.rsShows how high-level promises turn scheduled work into host actions.