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 / contract-sdk-authoring

Smart contract SDK authoring

The NEAR Rust SDK gives a contract author a typed Rust surface for defining public methods, persistent state, wire formats, and calls to the NEAR runtime. It connects a Rust method to a runtime entry point, carries state and call data across that boundary, and lets the method return values, logs, errors, or work for later execution.

Authoring model

An SDK contract is a state type plus one or more annotated implementation blocks. The #[near(contract_state)] annotation identifies the contract state, while #[near] exposes its public methods as callable contract methods. The SDK then supplies the boundary between normal Rust code and the NEAR execution model. See the generated contract interface page for the interface that other contracts and clients use.

The public near-sdk crate brings together macro support from near-sdk-macros, runtime bindings from near-sys and near-sdk-env, shared boundary types from near-sdk-core, and account and contract identity types from near-global-contracts. Contract authors normally use near-sdk as the authoring surface while these component crates provide the typed boundary to the runtime.

The main authoring choices are:

ConcernPublic SDK surfaceSystem role
Contract methods#[near] and method attributesDefines callable entry points and their call rules
Contract state#[near(contract_state)], state, and storeDefines data that survives between executions
Data formatsJSON, Borsh, and json_typesDefines how arguments, results, and stored values become bytes
Runtime behaviorenvReads context and uses host services such as storage, logs, and results
Runtime boundary typesnear-sdk-core types re-exported by near-sdkGives method code stable types for identities, resources, time, hashes, and runtime errors
Asynchronous workPromise, PromiseOrValue, and ext_contractSchedules calls and actions for later receipts

Contract method surface

The method surface turns ordinary Rust methods into the contract's public API. A read method uses immutable state and returns a view result, while a mutating method receives mutable state and commits the resulting state at the end of the call.

Method entry points

The SDK exposes public methods from an annotated impl block. It creates the runtime-facing entry point for each method and applies the method's boundary rules before and after the Rust body runs. A method can therefore express business logic in Rust without manually decoding runtime input or writing the top-level state value.

The common method classes are:

  • A view method reads state and returns a value without changing the contract state.
  • A mutating method changes state and persists the new state after it runs.
  • An #[init] method creates the first state value. Initialization is rejected when state already exists.
  • A #[payable] method accepts an attached NEAR deposit. Other methods reject attached deposits.
  • A #[private] method accepts calls only from the contract itself. This is the usual boundary for callbacks.
  • A #[handle_result] method maps an application error into a contract failure instead of making each method panic by hand.

References: near-sdk/…/lib.rs• L162-260 near-sdk/…/lib.rs• L578-706 near-sdk/…/lib.rs• L790-869

Method boundary rules

Method annotations define the contract's trust and data boundary. The SDK separates normal arguments from callback results, checks deposits and callers, and serializes the method result for the runtime. These rules are part of the public method contract, so a change can affect both direct callers and other contracts.

Argument and result behavior is controlled by a small set of attributes:

  • #[serializer(borsh)] changes method argument decoding from the default JSON format to Borsh. All arguments in one method must use the same decoder.
  • #[result_serializer(borsh)] changes the result format from JSON to Borsh.
  • #[deny_unknown_arguments] makes JSON input reject fields that the method does not define.
  • #[callback_unwrap] turns a successful promise result into a method argument and fails the callback when the promise failed.
  • #[callback_result] passes success or failure as Result<T, PromiseError> so the callback can choose how to respond.
  • #[callback_vec] collects results from several promises for one callback.

These choices should match the interface expected by clients and by the contract that receives a cross-contract call. For generated call builders and their signature rules, continue to Contract interface macros.

References: near-sdk/…/lib.rs• L550-576 near-sdk/…/lib.rs• L709-757 near-sdk/…/lib.rs• L871-1051

Contract state

Contract state is the durable data owned by the contract account. The SDK treats the top-level state as one Borsh value under the contract state key, then lets that value refer to storage-backed collections for data that should not be loaded in full for every method call.

State root

The state root is the type marked with #[near(contract_state)]. The method boundary loads it before a view or mutating method and writes it after a mutating method. The state type must have a compatible Borsh representation, and its default value is used only when no state exists unless the contract deliberately requires explicit initialization.

An initialization method creates this root once. PanicOnDefault is useful when an absent state must not silently become a default value. State upgrades must preserve or migrate the stored representation before normal methods try to read it. See Contract state and initialization for the full initialization and migration model.

References: near-sdk/…/state.rs• L5-39 near-sdk/…/env.rs• L2717-2734 near-sdk/…/lib.rs• L1523-1538

Persistent data

The store APIs represent large or sparse data as separate storage entries. This lets a method load and change the entries that it uses instead of loading one large native collection as part of the state root. Storage keys provide the namespace that keeps separate collections from colliding.

Most store collections keep changes in memory until flush or Drop, while LookupSet writes on each operation. This lifetime rule matters because the generated mutating wrapper writes the state root before local collection values are flushed. Use Persistent collections and store when choosing a collection or reviewing its persistence behavior. The older collections module remains a legacy alternative.

References: near-sdk/…/mod.rs• L16-23 near-sdk/…/mod.rs• L63-91 near-sdk/…/storage_key_impl.rs• L1-37 near-sdk/…/lib.rs• L1598-1601

Serialization boundary

Serialization defines the bytes that cross each contract boundary. The SDK uses JSON by default for method input and output because it is easy for external clients to produce, while Borsh is available for compact or explicitly binary interfaces and for the top-level stored state.

Data formats

The #[near] annotation can add JSON and/or Borsh support to a struct or enum. SDK helper types under json_types give common values a stable JSON form, such as encoded byte arrays and display strings for large integers. Serde attributes further shape JSON field names and representations.

Use one format as the deliberate contract of each public method. A client that sends JSON to a Borsh argument boundary, or expects JSON from a Borsh result boundary, receives a decode or encode failure. Stored state has a separate compatibility concern: changing its Borsh shape without a migration can make the contract unable to read existing data.

References: near-sdk/…/lib.rs• L399-505 near-sdk/…/lib.rs• L550-576 near-sdk/…/mod.rs• L1-3 near-sdk-core/…/mod.rs• L1-49

Contract events

Events are a structured JSON output channel for off-chain indexers and users. An enum marked with #[near(event_json(...))] emits NEP-297-shaped log data with a standard name and version, so consumers can identify the event family and interpret its payload.

Event data is not contract state and does not replace a method result. It records an observable fact during execution. Keep event names, versions, and field meaning stable when downstream tools depend on them. See Events, JSON, and contract types for the event and type format rules.

References: near-sdk/…/lib.rs• L1053-1113 near-sdk/…/events.rs• L1

Runtime environment

The env surface is the contract's view of the NEAR runtime. It provides the current call context and exposes host operations for input, output, storage, logs, economics, block data, cryptography, and promise results. Contract code should use this layer instead of assuming that ordinary process state can persist between calls.

Call context

Context values describe who owns the current execution and how it reached the contract. The current account identifies the contract, the predecessor identifies the immediate caller, and the signer identifies the account that began the transaction or cross-contract chain. Deposit and gas values describe the resources attached to the current call.

Methods use these values to enforce access rules and business conditions. For example, private methods compare the predecessor with the current account, while payable methods inspect the attached deposit. Block height, timestamp, epoch, and the block random seed provide runtime inputs for time and deterministic per-block behavior. The chain ID identifies the NEAR network configured for the deployed runtime; the mocked environment returns "test". See Runtime, environment, and context for the complete context surface.

References: near-sdk/…/env.rs• L182-196 near-sdk/…/env.rs• L258-342 near-sdk/…/env.rs• L345-414 near-sdk/…/env.rs• L421-493

Host interaction

Host operations are the effects that a contract can ask the runtime to perform during one execution. The SDK exposes byte input and return values, UTF-8 logs, panic paths, key-value storage, cryptographic checks, and the results of earlier promises. These operations are bounded by the gas and storage rules of the runtime.

The direct storage functions are useful for migrations and low-level data layouts. The state helpers use the reserved top-level state key, while store and legacy collections build higher-level layouts on the same key-value storage. The SDK also provides a mock environment for unit tests, so contract logic can observe controlled context and inspect logs or created receipts without a validator node.

The unit-testing mock runs runtime host behavior against a controlled context and keeps mocked storage when a test resets its environment. Tests can inspect logs and receipt actions, including scheduled calls, account actions, yielded execution, gas-key actions, and universal-account initialization, without starting a validator node.

The crate separates contract builds from host-side tools. The default feature enables the WebAssembly allocator, unit-testing adds VM-backed runtime support, and abi enables contract interface schema support. Features such as non-contract-usage, global-contracts, digest, and universal-accounts opt into additional SDK surfaces. The package targets protocol version 85 or later; the universal-accounts feature raises that requirement to protocol version 88 or later. A contract built with that feature requires the matching host support even if it does not create a universal account.

The low-level environment cryptography functions use packed byte buffers or fixed-size typed inputs. Their result type distinguishes rejected input from a valid negative verification or pairing result. Callers must keep that distinction when deciding whether an operation failed or produced a valid false result.

References: near-sdk/…/env.rs• L922-1082 near-sdk/…/env.rs• L2344-2685 near-sdk/…/mod.rs• L1-27 near-sdk/…/mod.rs• L63-99 near-sdk/…/mocked_blockchain.rs• L15-20 near-sdk/…/mocked_blockchain.rs• L70-159 near-sdk/…/receipt.rs• L8-14 near-sdk/…/receipt.rs• L81-130 near-sdk/Cargo.toml• L106-171

BLS12-381 operations

The near_sdk::bls12381 module provides a typed public surface for batch BLS12-381 operations used by contracts that need curve, field, or pairing work. It complements the packed-byte functions in env by making point and field encodings explicit at the Rust boundary.

The surface covers point sums, multiexponentiation, field-to-curve mapping, decompression, and pairing checks. Malformed or rejected input returns Err(Error::InvalidInput). A pairing check returns Ok(false) when valid points do not satisfy the check, which is different from rejected input. The operations are batch calls, so a caller can pass all terms in one host operation.

References: near-sdk/…/bls12381.rs• L1-40 near-sdk/…/bls12381.rs• L86-118 near-sdk/…/bls12381.rs• L255-408 near-sdk/…/lib.rs• L1633-1637

Asynchronous contract calls

NEAR cross-contract calls are asynchronous: a method schedules work for a later receipt instead of waiting for another contract inside the current execution. Promise represents that scheduled work, while ext_contract and generated <ContractType>Ext builders provide typed method calls over it.

Promise graph

A promise can target an account, carry function-call arguments, attach a deposit, and reserve gas. It can also contain account and key actions. The builder can join independent promises with and, place work after another promise with then, and return the scheduled promise as the current method's result.

The resulting calls form a graph of receipts rather than a synchronous call stack. PromiseOrValue<T> expresses a method that may finish with an immediate value or schedule work for later. A promise must be returned or explicitly detached so its scheduled work has a clear lifetime.

The promise surface also supports yielded execution. A YieldId identifies a runtime-created pause, while UserYieldId lets the contract choose a stable 32-byte identifier that both the creator and resumer can derive. Creation with a duplicate user ID returns no promise, and resumption returns an error when the yield is missing or already complete. A yielded promise must start its chain; it cannot be used as a later continuation.

The following diagram shows how a contract method creates scheduled work and handles its later result.

flowchart LR
    A[Contract method] --> B[Typed external call]
    B --> C[Promise with gas and deposit]
    C --> D{Promise graph}
    D --> E[Next call with then]
    D --> F[Concurrent calls with and]
    E --> G[Private callback]
    F --> G
    G --> H[Value or error handling]

References: near-sdk/…/promise.rs• L305-346 near-sdk/…/promise.rs• L371-380 near-sdk/…/promise.rs• L395-492 near-sdk/…/promise.rs• L783-860 near-sdk/…/promise.rs• L905-957 near-sdk/…/promise.rs• L1095-1153 near-sdk/…/env.rs• L2390-2547

Callback results

A callback is a later contract method that receives the result of one or more scheduled calls. The callback annotations reserve selected parameters for promise results, so regular method input and asynchronous data remain separate at the method boundary.

Use unwrapping when failure should abort the callback. Use Result<T, PromiseError> when the contract must handle failure as a normal branch. Use a vector of results when several calls were joined and the callback needs to combine their outputs. Callback methods are normally private because their inputs are produced by the contract's own promise chain.

For typed external interfaces, use the generated builder from ext_contract or from the contract's own Ext type. It serializes method arguments and creates the Promise; the callback still defines how the returned bytes become application data. See Promises and cross-contract calls for call graphs, gas, and failure handling.

References: near-sdk/…/lib.rs• L959-1051 near-sdk/…/lib.rs• L1330-1489 near-sdk/…/promise.rs• L960-976

Universal account initialization

Universal account initialization creates a 0u account from a UniversalStateInit description. The SDK re-exports these types from near_global_contracts and near_sdk_core, lets a contract derive the account ID before creation, and schedules the funded initialization as a promise action.

The account ID commits to the SHA3-256 hash of the canonical Borsh bytes of the state description. The promise receiver must match that derived ID, so callers should derive the address from the same state bytes that they send to the runtime. Typed state descriptions are encoded once for the action, while RawStateInit preserves forwarded bytes. This surface requires the universal-accounts feature and nearcore protocol version 88 or later. See Contract data formats for related type and encoding rules.

References: near-sdk/…/universal_state_init.rs• L1-44 near-sdk/…/env.rs• L2549-2685 near-sdk/…/promise.rs• L598-685 near-sdk/…/receipt.rs• L122-130 near-sdk/…/lib.rs• L1628-1644

Contract execution flow

The SDK coordinates the runtime boundary around each public method. This flow shows how a call becomes Rust input and how the method's result becomes either committed state, returned bytes, or scheduled work.

sequenceDiagram
    participant R as NEAR runtime
    participant W as SDK method boundary
    participant S as Contract state
    participant M as Rust method
    R->>W: Call method with input and context
    W->>W: Check caller, deposit, and callback rules
    W->>S: Load state root
    W->>M: Decode arguments and invoke method
    alt State-changing method
        M->>S: Change state
        W->>S: Serialize and write state
    else View method
        M-->>W: Return view value
    end
    M-->>W: Return value, error, or promise
    W-->>R: Return bytes, panic, logs, or scheduled receipts

The same model applies when a method is called by another contract. The difference is that a promise carries the call to a later execution, and a callback reads the later execution's result through the runtime environment.

References: near-sdk/…/lib.rs• L1202-1256 near-sdk/…/state.rs• L17-39 near-sdk/…/env.rs• L315-326 near-sdk/…/env.rs• L2537-2540

Change checklist

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

  • When a public method signature or serializer changes, update every generated external caller and every client that sends its input or reads its result.
  • When the contract state type or a stored field changes, define the migration path before deployment and keep collection storage prefixes stable.
  • When a method becomes payable or private, review all direct callers and callback chains because the runtime now applies a different access or deposit rule.
  • When a callback changes its result annotation, review the promise order and the producer methods that define each result's format.
  • When a promise graph changes, recalculate the gas and deposit assigned to each receipt and check which promise is returned from the entry point.
  • When a core boundary type changes, review public method signatures, serialized state, runtime action builders, and client code that depends on its representation.
  • When event fields or versions change, review indexers and consumers that parse the NEP-297 log shape.
  • When chain-dependent behavior is added, keep the on-chain chain ID distinct from the mocked test value "test".
  • When SDK feature flags or protocol targets change, check that contract builds keep the intended feature set and that unit-testing still provides VM-backed test support.
  • When host cryptography changes, preserve the difference between rejected input and a valid negative result such as false.
  • When BLS12-381 encodings or batch rules change, review callers that rely on the protocol byte layout and on subgroup checks.
  • When universal account state-init fields or encoding change, update both the derived receiver ID and the bytes carried by the initialization action.
  • When yielded-call IDs or resume behavior change, review the stored ID format, duplicate handling, and the callback that receives resumed data.
  • When the mock host or receipt action model changes, review tests that inspect logs, storage, receipts, or action payloads.

Important failure modes

TriggerConsequenceGuard
A non-payable method receives a depositThe call panics before the method body runsMark methods that accept funds with #[payable] and check the attached amount in the method
An external account calls a private callbackThe runtime-facing wrapper rejects the callMark callback methods #[private] and schedule them through the contract's own promise chain
Input or output uses the wrong JSON/Borsh formatArgument decoding or result encoding failsTreat the serializer choice as part of the public method contract
Stored state no longer matches the deployed Rust typeState loading panics and the method cannot proceedKeep the Borsh shape compatible or run an explicit migration
A cached collection is changed but not flushed before an unexpected exitCollection metadata and entries can become inconsistentUse flush at a required commit point and avoid relying on a later Drop after code that can abort
A callback unwraps a failed promiseThe callback panics instead of handling the failureUse #[callback_result] when failure is an expected branch
A promise is built but neither returned nor deliberately detachedThe call may be lost from the intended execution flowReturn the promise or call .detach() when the side effect is intentionally independent
Packed cryptographic input is malformed and the caller treats rejection as a valid negative resultInvalid data can be accepted as a valid failed checkHandle rejected input separately from a valid false result
BLS12-381 point decompression or summation is used as a subgroup checkA point outside the required subgroup can pass operations defined over the whole curveUse the multiexponentiation or pairing operation when subgroup membership is required
Unit tests omit the unit-testing featureVM-backed runtime support is not available to the test buildEnable the SDK's unit-testing feature for host-side runtime tests and keep it out of contract builds
A contract build or deployment targets a runtime below protocol version 85Required host behavior is unavailableUse an SDK and runtime pair that meet the package's declared minimum protocol version
A contract using universal-accounts targets a runtime below protocol version 88Universal-account host behavior is unavailableEnable the feature only with a compatible runtime and deployment target
A universal account action targets an ID different from its state-init bytesThe runtime rejects the receipt during validationDerive the receiver from the exact canonical bytes carried by the action
A user-chosen yield ID is reused while a yield is pendingPromise creation returns no promise and no new pause is scheduledTreat None as a duplicate and choose an ID with a clear ownership and retry rule
A test assumes the removed mock memory layer is configurableThe test no longer compiles or models a behavior the SDK does not exposeConfigure the VM context and runtime settings through testing_env!; use the host-backed mock as the memory boundary

Key files

FileWhy to read it
near-sdk/…/lib.rsDefines the main near authoring model, method attributes, serializers, generated call interfaces, and public re-exports
near-sdk/Cargo.tomlDefines the SDK component-crate dependencies, contract and host feature groups, and the minimum supported runtime protocol version
near-sdk-core/…/mod.rsDefines the shared public types for account identity, keys, resources, time, hashes, errors, and gas allocation
near-sdk/…/state.rsShows the contract state abstraction and the durable state read/write contract
near-sdk/…/mod.rsExplains the storage-backed collection model and its persistence behavior
near-sdk/…/env.rsDefines the runtime context, host effects, cryptographic host results, storage helpers, promise results, and universal account operations
near-sdk/…/mocked_blockchain.rsShows how unit tests run runtime host behavior and expose mocked storage, logs, and created receipts
near-sdk/…/receipt.rsDefines the test-facing receipt and action model used to inspect scheduled runtime effects
near-sdk/…/bls12381.rsDefines the typed BLS12-381 operations and the distinction between malformed input and a valid failed pairing check
near-sdk/…/promise.rsDefines asynchronous calls, yielded execution, account initialization actions, promise composition, and PromiseOrValue
near-sdk/…/universal_state_init.rsRe-exports the state description and key types used to derive and create universal accounts
near-sdk/…/events.rsRe-exports the event traits used by structured contract event output
near-sdk/…/mod.rsRe-exports helper types for stable JSON representations
near-sdk/…/mod.rsDefines the mocked blockchain setup, context reset macro, and inspection helpers used in runtime-facing unit tests
near-sdk/…/storage_key_impl.rsDefines the storage-key contract used to namespace persistent collections