Module near_sdk::store

source ·
Expand description

Collections and types used when interacting with storage.

These collections are more scalable versions of std::collections when used as contract state because it allows values to be lazily loaded and stored based on what is actually interacted with.

Fundamentally, a contract’s storage is a key/value store where both keys and values are just Vec<u8>. If you want to store some structured data, for example, Vec<Account>, one way to achieve that would be to serialize the Vec to bytes and store that. This has a drawback in that accessing or modifying a single element would require reading the whole Vec from the storage.

That’s where store module helps. Its collections are backed by a key value store. For example, a store::Vector is stored as several key-value pairs, where indices are the keys. So, accessing a single element would only load this specific element.

It can be expensive to load all values into memory, and because of this, serde Serialize and Deserialize traits are intentionally not implemented. If you want to return all values from a storage collection from a function, consider using pagination with the collection iterators.

All of the collections implement BorshSerialize and BorshDeserialize to be able to store the metadata of the collections to be able to access all values. Because only metadata is serialized, these structures should not be used as a borsh return value from a function.

The collections are as follows:


  • Vector: Analogous to Vec but not contiguous and persisted to storage.



Basic Types:

  • Lazy<T>: Lazily loaded type that can be used in place of a type T. Will only be loaded when interacted with and will persist on Drop.

  • LazyOption<T>: Lazily loaded, optional type that can be used in place of a type Option<T>. Will only be loaded when interacted with and will persist on Drop.




  • An persistent lazily loaded value, that stores a value in the storage.
  • An persistent lazily loaded option, that stores a value in the storage when Some(value) is set, and not when None is set. LazyOption also Derefs into Option so we get all its APIs for free.
  • A non-iterable implementation of a set that stores its content directly on the storage trie.