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:
_134access(all)_134struct Storage {_134 /// The current amount of storage used by the account in bytes._134 access(all)_134 let used: UInt64_134_134 /// The storage capacity of the account in bytes._134 access(all)_134 let capacity: UInt64_134_134 /// All public paths of this account._134 access(all)_134 let publicPaths: [PublicPath]_134_134 /// All storage paths of this account._134 access(all)_134 let storagePaths: [StoragePath]_134_134 /// Saves the given object into the account's storage at the given path._134 ///_134 /// Resources are moved into storage, and structures are copied._134 ///_134 /// If there is already an object stored under the given path, the program aborts._134 ///_134 /// The path must be a storage path, i.e., only the domain `storage` is allowed._134 access(Storage | SaveValue)_134 fun save<T: Storable>(_ value: T, to: StoragePath)_134_134 /// Reads the type of an object from the account's storage, which is stored under the given path,_134 /// or nil if no object is stored under the given path._134 ///_134 /// If there is an object stored, the type of the object is returned without modifying the stored object._134 ///_134 /// The path must be a storage path, i.e., only the domain `storage` is allowed._134 access(all)_134 view fun type(at path: StoragePath): Type?_134_134 /// Loads an object from the account's storage, which is stored under the given path,_134 /// or nil if no object is stored under the given path._134 ///_134 /// If there is an object stored,_134 /// the stored resource or structure is moved out of storage and returned as an optional._134 ///_134 /// When the function returns, the storage no longer contains an object under the given path._134 ///_134 /// The given type must be a supertype of the type of the loaded object._134 /// If it is not, the function panics._134 ///_134 /// The given type must not necessarily be exactly the same as the type of the loaded object._134 ///_134 /// The path must be a storage path, i.e., only the domain `storage` is allowed._134 access(Storage | LoadValue)_134 fun load<T: Storable>(from: StoragePath): T?_134_134 /// Returns a copy of a structure stored in account storage under the given path,_134 /// without removing it from storage,_134 /// or nil if no object is stored under the given path._134 ///_134 /// If there is a structure stored, it is copied._134 /// The structure stays stored in storage after the function returns._134 ///_134 /// The given type must be a supertype of the type of the copied structure._134 /// If it is not, the function panics._134 ///_134 /// The given type must not necessarily be exactly the same as the type of the copied structure._134 ///_134 /// The path must be a storage path, i.e., only the domain `storage` is allowed._134 access(Storage | CopyValue)_134 view fun copy<T: AnyStruct>(from: StoragePath): T?_134_134 /// Returns true if the object in account storage under the given path satisfies the given type,_134 /// i.e. could be borrowed using the given type._134 ///_134 /// The given type must not necessarily be exactly the same as the type of the borrowed object._134 ///_134 /// The path must be a storage path, i.e., only the domain `storage` is allowed._134 access(all)_134 view fun check<T: Any>(from: StoragePath): Bool_134_134 /// Returns a reference to an object in storage without removing it from storage._134 ///_134 /// If no object is stored under the given path, the function returns nil._134 /// If there is an object stored, a reference is returned as an optional,_134 /// provided it can be borrowed using the given type._134 /// If the stored object cannot be borrowed using the given type, the function panics._134 ///_134 /// The given type must not necessarily be exactly the same as the type of the borrowed object._134 ///_134 /// The path must be a storage path, i.e., only the domain `storage` is allowed_134 access(Storage | BorrowValue)_134 view fun borrow<T: &Any>(from: StoragePath): T?_134_134 /// Iterate over all the public paths of an account,_134 /// passing each path and type in turn to the provided callback function._134 ///_134 /// The callback function takes two arguments:_134 /// 1. The path of the stored object_134 /// 2. The run-time type of that object_134 ///_134 /// Iteration is stopped early if the callback function returns `false`._134 ///_134 /// The order of iteration is undefined._134 ///_134 /// If an object is stored under a new public path,_134 /// or an existing object is removed from a public path,_134 /// then the callback must stop iteration by returning false._134 /// Otherwise, iteration aborts._134 ///_134 access(all)_134 fun forEachPublic(_ function: fun(PublicPath, Type): Bool)_134_134 /// Iterate over all the stored paths of an account,_134 /// passing each path and type in turn to the provided callback function._134 ///_134 /// The callback function takes two arguments:_134 /// 1. The path of the stored object_134 /// 2. The run-time type of that object_134 ///_134 /// Iteration is stopped early if the callback function returns `false`._134 ///_134 /// If an object is stored under a new storage path,_134 /// or an existing object is removed from a storage path,_134 /// then the callback must stop iteration by returning false._134 /// Otherwise, iteration aborts._134 access(all)_134 fun forEachStored(_ function: fun (StoragePath, Type): Bool)_134}_134_134entitlement Storage_134_134entitlement SaveValue_134entitlement LoadValue_134entitlement CopyValue_134entitlement BorrowValue
Saving objects
_10access(Storage | SaveValue)_10fun 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
_10access(all)_10view 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
_10access(Storage | LoadValue)_10fun 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
_10access(Storage | CopyValue)_10view 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
_10access(Storage | BorrowValue)_10view 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:
-
Declare a resource interface named
HasCountthat has a fieldcount:_10resource interface HasCount {_10count: Int_10} -
Declare a resource named
Counterthat conforms toHasCount:_10resource Counter: HasCount {_10access(all)_10var count: Int_10_10access(all)_10init(count: Int) {_10self.count = count_10}_10}In this example, an authorized reference to an account is available through the constant
account. -
Create a new instance of the resource type
Counterand save it in the storage of the account.- The path
/storage/counteris used to refer to the stored value. - Its identifier
counterwas chosen freely and could be something else.
_11account.storage.save(_11<-create Counter(count: 42),_11to: /storage/counter_11)_11_11// Run-time error: Storage already contains an object under path `/storage/counter`_11//_11account.storage.save(_11<-create Counter(count: 123),_11to: /storage/counter_11) - The path
-
Load the
Counterresource from storage path/storage/counter.The new constant
counterhas the typeCounter?(i.e., it is an optional), and its value is the counter resource that was saved at the beginning of the example:_10let 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. -
Load the
Counterresource again from storage path/storage/counter.The new constant
counter2has the typeCounter?and isnil, as nothing is stored under the path/storage/counteranymore because the previous load moved the counter out of storage:_10let counter2 <- account.storage.load<@Counter>(from: /storage/counter) -
Create another new instance of the resource type
Counterand save it in the storage of the account.The path
/storage/otherCounteris used to refer to the stored value:_10account.storage.save(_10<-create Counter(count: 123),_10to: /storage/otherCounter_10) -
Load the
Vaultresource from storage path/storage/otherCounter.The new constant
vaulthas the typeVault?and its value isnilas there is a resource with typeCounterstored under the path, which is not a subtype of the requested typeVault:_10let vault <- account.storage.load<@Vault>(from: /storage/otherCounter)The storage still stores a
Counterresource under the path/storage/otherCounter. -
Save the string "Hello, World" in storage under the path
/storage/helloWorldMessage:_10account.storage.save(_10"Hello, world!",_10to: /storage/helloWorldMessage_10) -
Copy the stored message from storage.
After the copy, the storage still stores the string under the path. Unlike
load,copydoes not remove the object from storage:_10let message = account.storage.copy<String>(from: /storage/helloWorldMessage) -
Create a new instance of the resource type
Vaultand save it in the storage of the account:_10account.storage.save(_10<-createEmptyVault(),_10to: /storage/vault_10)_10_10// Invalid: Cannot copy a resource, as this would allow arbitrary duplication._10//_10let vault <- account.storage.copy<@Vault>(from: /storage/vault) -
Create a reference to the object stored under path
/storage/counter, typed as&Counter.counterRefhas type&Counter?and is a valid reference (i.e., non-nil) because the borrow succeeded.- There is an object stored under path
/storage/otherCounterand it has typeCounter, so it can be borrowed as&Counter:
_10let counterRef = account.storage.borrow<&Counter>(from: /storage/otherCounter)_10_10counterRef?.count // is `42` -
Create a reference to the object stored under path
/storage/otherCounter, typed as&{HasCount}.hasCountRefis non-nilas there is an object stored under path/storage/otherCounter, and the stored value of typeCounterconforms to the requested type{HasCount}— the typeCounterimplements the intersection type's interfaceHasCount:_10let hasCountRef = account.storage.borrow<&{HasCount}>(from: /storage/otherCounter) -
Create a reference to the object stored under path
/storage/otherCounter, typed as&{SomethingElse}.otherRefisnilas there is an object stored under path/storage/otherCounter, but the stored value of typeCounterdoes not conform to the requested type{SomethingElse}— the typeCounterdoes not implement the intersection type's interfaceSomethingElse:_10let otherRef = account.storage.borrow<&{SomethingElse}>(from: /storage/otherCounter) -
Create a reference to the object stored under path
/storage/nonExistent, typed as&{HasCount}.nonExistentRefisnil, as there is nothing stored under path/storage/nonExistent:_10let nonExistentRef = account.storage.borrow<&{HasCount}>(from: /storage/nonExistent)
Iterating over stored objects
The following functions allow iterating over an account's storage:
_10fun forEachPublic(_ function: fun(PublicPath, Type): Bool)_10fun 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.
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:
_17account.storage.save(1, to: /storage/foo1)_17account.storage.save(2, to: /storage/foo2)_17account.storage.save(3, to: /storage/foo3)_17account.storage.save("qux", to: /storage/foo4)_17_17account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool {_17 if type == Type<String>() {_17 // Save a value to storage while iterating_17 account.storage.save("bar", to: /storage/foo5)_17_17 // Returning false here ends iteration after storage is modified,_17 // preventing the program from aborting_17 return false_17 }_17_17 return true_17})
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:
_13// Query the storage used before saving an object_13let storageUsedBefore = account.storage.used_13_13// Save a resource into storage_13account.storage.save(_13 <-create Counter(count: 123),_13 to: /storage/counter_13)_13_13// Query the storage used again after saving_13let storageUsedAfter = account.storage.used_13_13let storageUsedChanged = storageUsedAfter > storageUsedBefore // is true