Cadence

Storage

Accounts allow storing storable objects, such as resources and structures.

An account exposes its storage through the storage field, which has the type Account.Storage.

Account.Storage

Here's an example:

access(all)
struct Storage {
    /// The current amount of storage used by the account in bytes.
    access(all)
    let used: UInt64

    /// The storage capacity of the account in bytes.
    access(all)
    let capacity: UInt64

    /// All public paths of this account.
    access(all)
    let publicPaths: [PublicPath]

    /// All storage paths of this account.
    access(all)
    let storagePaths: [StoragePath]

    /// Saves the given object into the account's storage at the given path.
    ///
    /// Resources are moved into storage, and structures are copied.
    ///
    /// If there is already an object stored under the given path, the program aborts.
    ///
    /// The path must be a storage path, i.e., only the domain `storage` is allowed.
    access(Storage | SaveValue)
    fun save<T: Storable>(_ value: T, to: StoragePath)

    /// Reads the type of an object from the account's storage, which is stored under the given path,
    /// or nil if no object is stored under the given path.
    ///
    /// If there is an object stored, the type of the object is returned without modifying the stored object.
    ///
    /// The path must be a storage path, i.e., only the domain `storage` is allowed.
    access(all)
    view fun type(at path: StoragePath): Type?

    /// Loads an object from the account's storage, which is stored under the given path,
    /// or nil if no object is stored under the given path.
    ///
    /// If there is an object stored,
    /// the stored resource or structure is moved out of storage and returned as an optional.
    ///
    /// When the function returns, the storage no longer contains an object under the given path.
    ///
    /// The given type must be a supertype of the type of the loaded object.
    /// If it is not, the function panics.
    ///
    /// The given type must not necessarily be exactly the same as the type of the loaded object.
    ///
    /// The path must be a storage path, i.e., only the domain `storage` is allowed.
    access(Storage | LoadValue)
    fun load<T: Storable>(from: StoragePath): T?

    /// Returns a copy of a structure stored in account storage under the given path,
    /// without removing it from storage,
    /// or nil if no object is stored under the given path.
    ///
    /// If there is a structure stored, it is copied.
    /// The structure stays stored in storage after the function returns.
    ///
    /// The given type must be a supertype of the type of the copied structure.
    /// If it is not, the function panics.
    ///
    /// The given type must not necessarily be exactly the same as the type of the copied structure.
    ///
    /// The path must be a storage path, i.e., only the domain `storage` is allowed.
    access(Storage | CopyValue)
    view fun copy<T: AnyStruct>(from: StoragePath): T?

    /// Returns true if the object in account storage under the given path satisfies the given type,
    /// i.e. could be borrowed using the given type.
    ///
    /// The given type must not necessarily be exactly the same as the type of the borrowed object.
    ///
    /// The path must be a storage path, i.e., only the domain `storage` is allowed.
    access(all)
    view fun check<T: Any>(from: StoragePath): Bool

    /// Returns a reference to an object in storage without removing it from storage.
    ///
    /// If no object is stored under the given path, the function returns nil.
    /// If there is an object stored, a reference is returned as an optional,
    /// provided it can be borrowed using the given type.
    /// If the stored object cannot be borrowed using the given type, the function panics.
    ///
    /// The given type must not necessarily be exactly the same as the type of the borrowed object.
    ///
    /// The path must be a storage path, i.e., only the domain `storage` is allowed
    access(Storage | BorrowValue)
    view fun borrow<T: &Any>(from: StoragePath): T?

    /// Iterate over all the public paths of an account,
    /// passing each path and type in turn to the provided callback function.
    ///
    /// The callback function takes two arguments:
    ///   1. The path of the stored object
    ///   2. The run-time type of that object
    ///
    /// Iteration is stopped early if the callback function returns `false`.
    ///
    /// The order of iteration is undefined.
    ///
    /// If an object is stored under a new public path,
    /// or an existing object is removed from a public path,
    /// then the callback must stop iteration by returning false.
    /// Otherwise, iteration aborts.
    ///
    access(all)
    fun forEachPublic(_ function: fun(PublicPath, Type): Bool)

    /// Iterate over all the stored paths of an account,
    /// passing each path and type in turn to the provided callback function.
    ///
    /// The callback function takes two arguments:
    ///   1. The path of the stored object
    ///   2. The run-time type of that object
    ///
    /// Iteration is stopped early if the callback function returns `false`.
    ///
    /// If an object is stored under a new storage path,
    /// or an existing object is removed from a storage path,
    /// then the callback must stop iteration by returning false.
    /// Otherwise, iteration aborts.
    access(all)
    fun forEachStored(_ function: fun (StoragePath, Type): Bool)
}

entitlement Storage

entitlement SaveValue
entitlement LoadValue
entitlement CopyValue
entitlement BorrowValue

Saving objects

access(Storage | SaveValue)
fun save<T: Storable>(_ value: T, to: StoragePath)

The save function saves an object to account storage. The function moves resources and copies structures. If there is already an object stored under the given path, the program aborts. The path must be a storage path, and it must have the domain storage.

T is the type parameter for the object type. Cadence can infer this type parameter from the argument's type.

Getting object type information

access(all)
view fun type(at path: StoragePath): Type?

The type function returns the type of the object stored under the given path, or nil if the account does not store an object under the given path.

The function does not change the stored object.

The path must be a storage path, and it must have the domain storage.

Loading (removing) objects

access(Storage | LoadValue)
fun load<T: Storable>(from: StoragePath): T?

The load function loads an object from account storage. If there is an object stored under the given path, the function moves the stored resource or structure out of storage and returns it as an optional. If there is no object stored under the given path, the function returns nil. When the function returns with an object, the storage no longer stores an object under the given path.

T is the type parameter for the object type. Programs must explicitly provide a type argument for the parameter.

The type T must be a supertype of the type of the loaded object. If it is not, the program aborts. The given type does not necessarily need to be exactly the same as the type of the loaded object.

The path must be a storage path, and it must have the domain storage.

Copying objects

access(Storage | CopyValue)
view fun copy<T: AnyStruct>(from: StoragePath): T?

The copy function returns a copy of a structure stored in account storage, without removing it from storage. If there is a structure stored under the given path, the function copies the stored structure and returns it as an optional. If there is no structure stored under the given path, the function returns nil. When the function returns with an object, the structure stays stored in storage after the function returns.

T is the type parameter for the structure type. Programs must explicitly provide a type argument for the parameter.

The type T must be a supertype of the type of the copied structure. If it is not, the program aborts. The given type does not necessarily have to be exactly the same as the type of the copied structure.

The path must be a storage path, and it must have the domain storage.

Borrowing objects

access(Storage | BorrowValue)
view fun borrow<T: &Any>(from: StoragePath): T?

The borrow function returns a reference to an objects stored in storage, without removing the object from storage. The function makes it convenient to work with objects in storage without having to move them out of storage.

If there is a structure stored under the given path, the function creates a reference to the object and returns the reference as an optional. If there is no structure stored under the given path, the function returns nil.

T is the type parameter for the object type. Programs must explicitly provide a type argument for the parameter.

The type argument must be a reference to any type, &Any (Any is the supertype of all types). The type T must be a supertype of the type of the borrowed object. If it is not, the program aborts. The given type does not necessarily have to be exactly the same as the type of the borrowed object.

The path must be a storage path, and it must have the domain storage.

Example

The following steps show you how to declare a resource, create a new instance, and save it in the storage of the account:

  1. Declare a resource interface named HasCount that has a field count:

    resource interface HasCount {
        count: Int
    }
  2. Declare a resource named Counter that conforms to HasCount:

    resource Counter: HasCount {
        access(all)
        var count: Int
    
        access(all)
        init(count: Int) {
            self.count = count
        }
    }

    In this example, an authorized reference to an account is available through the constant account.

  3. Create a new instance of the resource type Counter and save it in the storage of the account.

    • The path /storage/counter is used to refer to the stored value.
    • Its identifier counter was chosen freely and could be something else.
    account.storage.save(
        <-create Counter(count: 42),
        to: /storage/counter
    )
    
    // Run-time error: Storage already contains an object under path `/storage/counter`
    //
    account.storage.save(
        <-create Counter(count: 123),
        to: /storage/counter
    )
  4. Load the Counter resource from storage path /storage/counter.

    The new constant counter has the type Counter? (i.e., it is an optional), and its value is the counter resource that was saved at the beginning of the example:

    let counter <- account.storage.load<@Counter>(from: /storage/counter)

    The storage is now empty, there is no longer an object stored under the path /storage/counter.

  5. Load the Counter resource again from storage path /storage/counter.

    The new constant counter2 has the type Counter? and is nil, as nothing is stored under the path /storage/counter anymore because the previous load moved the counter out of storage:

    let counter2 <- account.storage.load<@Counter>(from: /storage/counter)
  6. Create another new instance of the resource type Counter and save it in the storage of the account.

    The path /storage/otherCounter is used to refer to the stored value:

    account.storage.save(
        <-create Counter(count: 123),
        to: /storage/otherCounter
    )
  7. Load the Vault resource from storage path /storage/otherCounter.

    The new constant vault has the type Vault? and its value is nil as there is a resource with type Counter stored under the path, which is not a subtype of the requested type Vault:

    let vault <- account.storage.load<@Vault>(from: /storage/otherCounter)

    The storage still stores a Counter resource under the path /storage/otherCounter.

  8. Save the string "Hello, World" in storage under the path /storage/helloWorldMessage:

    account.storage.save(
        "Hello, world!",
        to: /storage/helloWorldMessage
    )
  9. Copy the stored message from storage.

    After the copy, the storage still stores the string under the path. Unlike load, copy does not remove the object from storage:

    let message = account.storage.copy<String>(from: /storage/helloWorldMessage)
  10. Create a new instance of the resource type Vault and save it in the storage of the account:

    account.storage.save(
        <-createEmptyVault(),
        to: /storage/vault
    )
    
    // Invalid: Cannot copy a resource, as this would allow arbitrary duplication.
    //
    let vault <- account.storage.copy<@Vault>(from: /storage/vault)
  11. Create a reference to the object stored under path /storage/counter, typed as &Counter.

    • counterRef has type &Counter? and is a valid reference (i.e., non-nil) because the borrow succeeded.
    • There is an object stored under path /storage/otherCounter and it has type Counter, so it can be borrowed as &Counter:
    let counterRef = account.storage.borrow<&Counter>(from: /storage/otherCounter)
    
    counterRef?.count // is `42`
  12. Create a reference to the object stored under path /storage/otherCounter, typed as &{HasCount}.

    hasCountRef is non-nil as there is an object stored under path /storage/otherCounter, and the stored value of type Counter conforms to the requested type {HasCount} — the type Counter implements the intersection type's interface HasCount:

    let hasCountRef = account.storage.borrow<&{HasCount}>(from: /storage/otherCounter)
  13. Create a reference to the object stored under path /storage/otherCounter, typed as &{SomethingElse}.

    otherRef is nil as there is an object stored under path /storage/otherCounter, but the stored value of type Counter does not conform to the requested type {SomethingElse} — the type Counter does not implement the intersection type's interface SomethingElse:

    let otherRef = account.storage.borrow<&{SomethingElse}>(from: /storage/otherCounter)
  14. Create a reference to the object stored under path /storage/nonExistent, typed as &{HasCount}.

    nonExistentRef is nil, as there is nothing stored under path /storage/nonExistent:

    let nonExistentRef = account.storage.borrow<&{HasCount}>(from: /storage/nonExistent)

Iterating over stored objects

The following functions allow iterating over an account's storage:

fun forEachPublic(_ function: fun(PublicPath, Type): Bool)
fun forEachStored(_ function: fun(StoragePath, Type): Bool)

The functions iterate over all stored objects in the particular domain, by calling the callback function for each stored object, and passing the path and the run-time type of the stored object.

The Bool value returned from the callback function determines whether iteration continues. If the callback function returns true, iteration proceeds to the next stored object. If the callback function returns false, the iteration function stops. The specific order in which the objects are iterated over is undefined, as is the behavior when a path is added or removed from storage.

The iteration functions skip broken objects.

An object could be broken due to invalid types associated with the stored value. For example, the contract for the stored object might have syntactic or semantic errors. [!WARNING] The order of iteration is undefined. Do not rely on any particular behavior.

Saving an object to a path or loading an object from storage during iteration can cause the order in which values are stored to change arbitrarily.

When a program continues to iterate after such an operation, the program aborts.

To avoid such errors, do not save objects to storage or load objects from storage during iteration. If you do perform such an operation, return false from the iteration callback to cause the iteration to end after the mutation like so:

account.storage.save(1, to: /storage/foo1)
account.storage.save(2, to: /storage/foo2)
account.storage.save(3, to: /storage/foo3)
account.storage.save("qux", to: /storage/foo4)

account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool {
    if type == Type<String>() {
        // Save a value to storage while iterating
        account.storage.save("bar", to: /storage/foo5)

        // Returning false here ends iteration after storage is modified,
        // preventing the program from aborting
        return false
    }

    return true
})

Storage limit

An account's storage is limited by its storage capacity.

An account's storage used is the sum of the size of all the data that the account stores, in MB. An account's storage capacity is a value that is calculated from the amount of $FLOW that is stored in the account's main $FLOW token vault.

At the end of every transaction, the storage used is compared to the storage capacity. For all accounts involved in the transaction, if the account's storage used is greater than its storage capacity, the transaction fails.

An account exposes its storage used through the storage.used field, and its storage capacity through the storage.capacity field.

The fields represent current values:

// Query the storage used before saving an object
let storageUsedBefore = account.storage.used

// Save a resource into storage
account.storage.save(
    <-create Counter(count: 123),
    to: /storage/counter
)

// Query the storage used again after saving
let storageUsedAfter = account.storage.used

let storageUsedChanged = storageUsedAfter > storageUsedBefore  // is true

On this page