Contract state and initialization
Contract state is the durable data that a NEAR contract reads during a call and writes back for later calls. The SDK defines the state boundary, protects normal initialization from accidental re-entry, and provides separate tools for upgrades and deterministic account state initialization.
State model
Contract state is the root object that represents the contract at a given point in time. Its lifecycle links the public method wrappers to NEAR key-value storage.
Contract state declaration
The #[near(contract_state)] annotation marks one struct or enum as the contract's root state. The SDK gives this type the ContractState behavior used by generated method wrappers. By default, the root value uses the STATE storage key. A contract can select another key through the annotation when it must keep its state under a different storage namespace. See contract interface macros for the wider role of the near annotations.
The root value is serialized with Borsh for storage. Large or frequently changing data should use a storage-backed collection rather than a native Rust collection in the root object. This keeps the root value small and lets collection entries follow their own storage rules; see persistent collections and store.
References: near-sdk/…/state.rs• L5-39 near-sdk/…/lib.rs• L171-181 near-sdk-macros/…/state.rs• L6-41
State loading and persistence
Generated wrappers load the root state before a view or a mutating method that has a receiver. A missing root value becomes Default::default() unless the type uses PanicOnDefault, which lets a contract reject calls made before state exists. A view returns its result without writing the root value. A mutating method writes the updated root value after the method returns.
The SDK's low-level env::state_read and env::state_write helpers use the fixed STATE key. The generated path uses ContractState, so it can honor a custom state key. This difference matters when a contract mixes generated wrappers with direct storage access.
The main lifecycle is:
flowchart TD
A[Contract method call] --> B{Initialization method?}
B -- yes --> C[Check root state]
C -->|missing| D[Create state from constructor or default]
C -->|present| E[Reject normal initialization]
D --> F[Write root state]
B -- no --> G[Load root state or default]
G --> H{View method?}
H -- yes --> I[Return result]
H -- no --> J[Apply state change]
J --> K[Write root state]
References: near-sdk-macros/…/impl_item_method_info.rs• L198-285 near-sdk/…/env.rs• L2941-2963 near-sdk/…/lib.rs• L1202-1256
Initialization
Initialization creates the first root state for an account. It is separate from ordinary calls because it uses a constructor path and has a one-time state check.
Constructor initialization
A contract can rely on Default::default() for its initial value or expose one or more custom methods marked with #[init]. A custom initializer can accept arguments and perform validation or setup before it returns the new state. The generated wrapper checks that the contract state does not exist, calls the initializer, and persists the returned value.
The existence check tests the contract's root state key. It does not prove that every other storage key is empty. Code that uses extra storage keys must define its own cleanup or migration rules.
References: near-sdk/…/lib.rs• L578-623 near-sdk/…/init_function.rs• L3-20 near-sdk-macros/…/impl_item_method_info.rs• L206-251
Reinitialization exception
#[init(ignore_state)] skips the normal root-state existence check. It is intended for a method that must run even when state already exists, such as a deliberate reset or a controlled repair. It still constructs and writes a new root value, so access control and input checks are the contract's responsibility.
This option does not turn an ordinary method into a migration. It does not read the old root value or transform it unless the initializer does that work through explicit storage operations.
References: near-sdk/…/lib.rs• L612-623 near-sdk-macros/…/attr_sig_info.rs• L100-110 near-sdk-macros/…/impl_item_method_info.rs• L201-217 near-sdk/…/init_ignore_state.rs• L3-19
State migration
Migration changes an existing state value so that a new contract version can read it safely. It is a deployment concern rather than a first-time initialization concern, and the SDK supplies storage primitives instead of choosing a migration policy for the contract.
Existing state conversion
When a Borsh state layout changes, the old bytes may no longer deserialize as the new root type. A migration method can read the old bytes from the relevant storage key, convert them into the new shape, and write the converted value back. The method must run before normal methods depend on the new type.
The contract controls how migration is authorized and how it handles partial or invalid data. The upgrade support in near-contract-standards stages replacement code and removes its temporary upgrade entry after deployment, but the migrate hook itself is intentionally contract-specific. A migration should not be confused with #[init]: normal initialization expects no root state, while migration expects state to be present.
References: near-sdk/…/env.rs• L2919-2963 near-contract-standards/…/mod.rs• L14-25 near-contract-standards/…/mod.rs• L51-78
Deterministic state initialization
State-init support is a runtime action for creating an account with contract code and initial storage data. It complements contract-level constructors but does not replace them: the action describes code and raw storage entries, while a Rust #[init] method remains a contract call with its own checks.
Deterministic account state initialization
With the deterministic-account-ids feature enabled, StateInit describes the code source and the data used to initialize an account. The code can be identified by a global contract code hash or by the account that deployed the global contract. The state description can derive the deterministic account ID from its serialized content under NEP-616.
The action is exposed through Promise::state_init. Low-level environment functions expose the same boundary when a contract needs direct control. A deposit can be attached to the action, and the promise can direct failed or unused funds to a refund account. See promises and cross-contract calls for the larger promise model.
References: near-sdk/…/state_init.rs• L1-13 near-global-contracts/…/state_init.rs• L22-74 near-sdk/…/promise.rs• L79-95 near-sdk/…/promise.rs• L483-504 near-sdk/…/promise.rs• L585-589 near-sdk/…/env.rs• L1429-1536
Universal account state initialization
With the universal-accounts feature enabled, a universal state initialization action creates a 0u account from versioned, canonical state-init bytes. The bytes can describe code, access keys, and raw storage data. The resulting account ID is the SHA3-256 commitment to those bytes in the NEP-655 format.
The SDK can ask the host to validate the bytes and derive the account ID before it builds the action. The promise receiver must be that derived ID. The runtime checks this relationship when the receipt is created, so a mismatch fails the call and rolls back its state changes. This support is separate from a contract constructor: it creates the account and its initial data, but it does not call a Rust #[init] method.
The low-level action forwards the state-init bytes unchanged. This lets a contract pass through a state-init version that its SDK does not know, while the host remains responsible for the versions it supports. The host also rejects malformed or non-canonical bytes; a valid account ID alone does not prove that funding, code, or action limits are sufficient.
References: near-sdk/…/env.rs• L2553-2685
State-init data
Deterministic state-init data carries a map from byte keys to byte values. These entries are raw storage data. Their meaning belongs to the contract that will use them, so the keys and values must match that contract's storage format and state key rules.
The promise builder adds the state-init action first and then attaches each data entry to that action. The low-level API follows the same order: create a state-init action, keep its action index, and add data entries to it. This is distinct from env::state_write, which serializes one Rust root value under the contract state key.
References: near-global-contracts/…/state_init.rs• L77-109 near-sdk/…/promise.rs• L198-224 near-sdk/…/env.rs• L1293-1399 near-sdk/…/env.rs• L1448-1536 near-sdk/…/env.rs• L2941-2959
Change checklist
When these files or sections are changed, remember to consider these:
- If the root type or its Borsh layout changes, update the migration path before deploying code that uses the new type.
- If the
contract_statekey changes, check every directenv::state_read,env::state_write, and raw storage access because those helpers do not inherit the custom key. - If a collection field changes, check its prefix and persistence boundary together with the root state update. See persistent collections and store.
- If deterministic or universal state-init data changes, keep the raw keys and values aligned with the target contract's storage format and account ID derivation. For universal accounts, preserve canonical ordering and byte content.
- If initialization access rules change, review every
#[init(ignore_state)]path because it can write over an existing root state. - If universal account support changes, check both the feature and the host protocol requirement. The action receiver must still match the account ID derived from the exact state-init bytes.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
A normal #[init] method runs after root state exists | The call panics before the constructor runs | Use an explicit migration or a tightly controlled reset path |
#[init(ignore_state)] is exposed without strong checks | Existing state can be replaced by a new constructor result | Restrict the method and validate the intended reset or repair |
| A new root layout cannot decode old Borsh bytes | State loading panics with a contract-state deserialization error | Deploy and run a compatible migration first |
A contract uses direct env::state_* helpers with a custom root key | The code reads or writes STATE instead of the configured key | Use the ContractState path or address the custom key explicitly |
| A cached storage collection is changed without its flush or drop boundary | Collection data can remain out of sync with the root state | Follow the collection lifecycle described in persistent collections and store |
| State-init data does not match the target storage format | The new account starts with unusable or unreadable data | Treat state-init entries as a versioned storage contract |
| Universal state-init bytes are malformed or non-canonical | The host cannot derive the intended 0u account ID | Build canonical state-init data and validate it before creating the action |
| A universal state-init action targets an account ID that does not match its bytes | Receipt creation fails and the calling state changes roll back | Derive the receiver from the exact bytes and do not alter them before forwarding |
| Universal account support runs on an older host | The required host action is unavailable | Require nearcore protocol version 88 or later |
Key files
| File | Why to read it |
|---|---|
| near-sdk/…/state.rs | Defines the root-state contract used by generated wrappers and the default state key. |
| near-sdk-macros/…/impl_item_method_info.rs | Shows the high-level boundaries for initialization, loading, method execution, and persistence. |
| near-sdk/…/env.rs | Defines direct state and storage reads, writes, removals, deterministic state-init actions, and universal account state-init actions. |
| near-sdk/…/lib.rs | Documents the public contract_state and init authoring model. |
| near-contract-standards/…/mod.rs | Illustrates the separation between code upgrade support and contract-specific state migration. |
| near-sdk/…/state_init.rs | Re-exports the deterministic state-init types when the feature is enabled. |
| near-global-contracts/…/state_init.rs | Defines the deterministic state-init description, raw data map, and account ID derivation. |
| near-sdk/…/promise.rs | Connects deterministic and universal state-init descriptions to promise actions and refund behavior. |
| near-sdk/…/mod.rs | Explains how storage-backed collections persist alongside the root state. |