Promises and cross-contract calls
The NEAR SDK promise system lets a contract schedule work in another contract or account and connect later work to its result. It gives contract methods one model for direct calls, ordered and parallel call graphs, callback data, and failure handling. For the wider authoring model, see Smart contract SDK authoring.
Cross-contract call model
A cross-contract call is a scheduled action, not a local function call. The current execution creates a promise with a target, method, serialized arguments, attached deposit, and gas. The runtime executes that action later and makes its result available to a callback or to the caller when the promise is returned. The generated interfaces described in Contract interface macros provide the typed surface for this flow.
The SDK supports two call styles:
- Generated interface: An
#[ext_contract]trait or a contract's generatedExtAPI turns a method-shaped call into aPromise. The call can start from an account or from an existing promise. - Environment API:
env::promise_create,env::promise_then,env::promise_and, andenv::promise_returnexpose the lower-level scheduling model when a contract needs direct control.
References: near-sdk/…/env.rs• L1167-1317 near-sdk-macros/…/lib.rs• L362-397
Promise construction
Promise represents work that the runtime must schedule. Promise::new(account_id) starts an action list for an account. The builder then adds a function call or account action. A generated external call follows the same model and applies its input serializer before it schedules the call. A promise with no returned value can be explicitly detached when the contract only needs the side effect.
The generated call builder also carries the call's attached deposit and gas settings. ext(account_id) starts a new call. ext_on(promise) places the call after an existing promise. A contract's generated ext_self() targets the current contract for a callback or another self-call.
References: near-sdk/…/promise.rs• L305-347 near-sdk/…/promise.rs• L371-380 near-sdk-macros/…/ext.rs• L9-87 near-sdk-macros/…/ext.rs• L138-186
Promise graph
Promise methods form a dependency graph. then makes one call wait for another. and joins independent work so a later call waits for all members. then_concurrent starts several dependent calls in parallel. ConcurrentPromises::join turns that group into one join point for the next step.
This diagram shows how a contract can build a call graph with both ordered and parallel stages.
flowchart LR
A[Initial contract method] --> B[Promise A]
B --> C[Promise B]
B --> D[Promise C]
B --> E[Promise D]
C --> F[Join]
D --> F
E --> F
F --> G[Callback or final call]
Use one promise as the dependency for each ordered continuation. A joint promise is a wait point and cannot receive another action directly. A yielded promise is a special suspended call that must be first in a chain. It cannot be used as a continuation after another promise. These rules protect the graph from ambiguous dependencies.
References: near-sdk/…/promise.rs• L783-860 near-sdk/…/promise.rs• L863-903 near-sdk/…/promise.rs• L1190-1232 near-sdk/…/promise.rs• L384-431
Callback handling
A callback is a later contract method that receives the results of the promises that lead to it. The callback method should describe how it wants to treat those results. The #[near] method wrapper reads callback results before it invokes the contract method, so callback data is separate from normal call arguments.
The callback attributes define the main policies:
| Attribute | Callback input | Failure behavior |
|---|---|---|
#[callback_unwrap] | One successful result decoded as T | Panics if the promise fails, exceeds the byte limit, or cannot be decoded |
#[callback_result] | One result decoded as Result<T, PromiseError> | Gives the method a recoverable Err value for a failed or oversized result |
#[callback_vec] | All results decoded as Vec<T> | Panics if any result fails, exceeds the byte limit, or cannot be decoded |
The callback index follows the promise order supplied to the callback. A callback with several #[callback_result] parameters reads one result for each parameter. A callback with #[callback_vec] reads the full result set. The callback attributes can set max_bytes to bound each result. JSON is the default callback serializer. Borsh can be selected when the call contract uses it.
Callbacks normally use #[private] when only the contract's own promise chain should invoke them. The generated method wrapper checks that the predecessor is the current account before it runs the callback. This access rule is part of the callback boundary and complements the result policy.
References: near-sdk/…/lib.rs• L871-959 near-sdk/…/lib.rs• L959-1051 near-sdk-macros/…/impl_item_method_info.rs• L7-49 near-sdk-macros/…/impl_item_method_info.rs• L185-196 near-sdk-macros/…/arg_info.rs• L57-108
Result inspection
The environment API exposes callback results as bytes. A callback first checks how many results it received with env::promise_results_count(). This count covers the complete and incomplete results supplied by the promises that led to the callback. It then reads a result by index with env::promise_result_checked(index, max_len). The checked form returns the bytes on success and a PromiseError on failure or when the result is larger than the allowed limit.
Use the checked form for results from an unknown contract. It places a limit on data that the callback will read and helps avoid an out-of-gas failure caused by an unexpectedly large result. The older unbounded result helper remains available for compatibility, but the SDK marks it as deprecated.
The SDK also provides is_promise_success() for the narrow case where a callback expects exactly one result and only needs a success flag. It panics when the current execution does not contain exactly one callback result, so it is not a general replacement for result counting and indexed reads.
References: near-sdk/…/env.rs• L2211-2306 near-sdk/…/mod.rs• L91-116 near-sdk/…/vm_types.rs• L30-72
Return propagation
The promise returned by a contract method becomes the method's asynchronous result. A method can return Promise directly. It can also return PromiseOrValue<T> when it may finish immediately with a value or schedule a call whose result will become the method result.
The SDK marks a promise as the return value when the method returns it or when the code calls as_return(). Serialization of a promise does not write a normal value. Instead, it causes the runtime to treat the promise's result as the contract call result. A promise that is only a side effect must be detached or dropped without being exposed as the method result.
This diagram shows the two possible outcomes of a method that returns PromiseOrValue<T>.
flowchart TD
A[Contract method] --> B{Result ready now?}
B -->|Yes| C[PromiseOrValue::Value<T>]
B -->|No| D[PromiseOrValue::Promise]
C --> E[Immediate serialized value]
D --> F[Scheduled call chain]
F --> G[Final promise result]
References: near-sdk/…/promise.rs• L905-976 near-sdk/…/promise.rs• L1115-1177 examples/…/lib.rs• L8-30
Error behavior
Promise failure is reported when a later callback inspects the result. A failed upstream call does not automatically become a Rust exception in the contract that scheduled it. The callback chooses whether to panic, return an error, or apply another recovery policy.
The SDK uses these error paths:
#[callback_unwrap]converts a failed, oversized, or invalid result into a panic before the callback method receives its argument.#[callback_result]passesErr(PromiseError::Failed)for a failed promise orErr(PromiseError::TooLong(bytes))for a result over its limit. Decode errors after a successful read still panic because the callback type does not match the returned bytes.#[callback_vec]applies the unwrap policy to every result. One failed or invalid item stops callback processing.- A callback that returns a
Resultcan use#[handle_result]to turn its own decision into a normal value or contract error. This is distinct fromPromiseError, which describes an upstream promise result.
The factory example shows a recovery boundary: it inspects the first call with #[callback_result], makes the next call only after success, and returns a contract error when the first call fails. The low-level example expresses the same boundary with promise_result_checked and an explicit panic.
References: near-sdk/…/vm_types.rs• L48-72 near-sdk/…/lib.rs• L959-1009 near-sdk-macros/…/attr_sig_info.rs• L228-347 examples/…/lib.rs• L27-49 examples/…/lib.rs• L36-73
Yielded calls
A yielded call suspends a callback until a later transaction resumes it with data. Promise::new_yield returns both the scheduled promise and a runtime-created YieldId. The contract can store that identifier and later call YieldId::resume(data). The resumed callback receives the supplied bytes as its one promise result.
Promise::new_yield_with_id uses a contract-provided UserYieldId instead. The identifier is a caller-chosen 32-byte value, so the creator and later resumer can derive it independently without passing a runtime token through contract state. This form can attach a deposit to the resumed callback. Creation returns None when that identifier is already pending. Resumption returns ResumeError when the identifier is missing, expired, or already used.
Yielded calls are local to the contract account. They also have a protocol support requirement for the user-provided identifier form. Treat the resume result as part of the application flow because a failed resume does not produce the callback payload.
References: near-sdk/…/promise.rs• L384-480 near-sdk/…/promise.rs• L993-1047 near-sdk/…/promise.rs• L1049-1107 near-sdk/…/env.rs• L2338-2547
Change checklist
When these files or sections are changed, remember to consider these:
- Keep generated external-call argument and result serializers aligned with the callback serializer selected by the receiving method.
- Keep callback result positions aligned with the promise order. Changes to a joined or concurrent graph can change which result an indexed callback reads.
- Preserve the distinction between a promise returned as the contract result and a promise detached as a side effect.
- Recheck byte limits when a callback starts accepting results from a new or less trusted contract.
- Keep private callback access rules aligned with any change that moves a callback to another account or changes the promise predecessor.
- When using yielded calls, handle duplicate
UserYieldIdcreation, keep the create and resume paths on the same local account, and confirm host protocol support for user-provided yield IDs.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A callback expects one result but receives zero or several | is_promise_success or a single-result helper panics | Check promise_results_count() or use the matching callback attribute |
An upstream call fails with #[callback_unwrap] | The callback panics before its method body runs | Use #[callback_result] when the contract can recover |
| A callback reads an unbounded or very large external result | The callback can run out of gas while reading it | Use promise_result_checked or max_bytes |
| A joint promise receives a direct action or a joint promise is used as a continuation | Promise construction panics | Add actions before and, then use the joint promise only as a wait point |
| A yielded promise is placed after another promise | Promise construction panics | Start the chain with the yielded promise |
| A user-provided yield ID is already pending | new_yield_with_id returns None and creates no new yielded call | Treat None as a duplicate request and choose a recovery path |
| A callback is marked private but is called by another account | The generated entrypoint panics | Schedule the callback from the same contract account |
| A promise is neither returned nor detached | The SDK's drop behavior still schedules it, but the intended return contract can be unclear | Return the promise when its result is part of the method result; detach side-effect-only work |
Key files
| File | Why to read it |
|---|---|
| near-sdk/…/promise.rs | Defines the high-level promise model, call graph operations, return propagation, mixed immediate-or-async values, and yielded calls. |
| near-sdk/…/env.rs | Defines the low-level scheduling, callback result inspection, yielded-call boundary, and promise return boundary. |
| near-sdk/…/vm_types.rs | Defines the public result and error types used when callback data succeeds or fails. |
| near-sdk/…/mod.rs | Provides the narrow single-result success helpers used by callbacks. |
| near-sdk-macros/…/ext.rs | Shows how generated external-call builders connect account targets and existing promises to scheduled calls. |
| near-sdk-macros/…/attr_sig_info.rs | Shows the callback input policies at the contract boundary. |
| examples/…/lib.rs | Shows a compact generated-interface chain with a private callback and a typed successful result. |
| examples/…/lib.rs | Shows the same ordered flow through direct environment calls and explicit result inspection. |
| examples/…/lib.rs | Shows a multi-step call that branches on PromiseError before scheduling the next call. |