Skip to main content
Version: Current

Accounts

Every account can be accessed through two types, PublicAccount and AuthAccount.

PublicAccount

Public Account objects have the type PublicAccount, which represents the publicly available portion of an account.


pub struct PublicAccount {

/// The address of the account.
pub let address: Address

/// The FLOW balance of the default vault of this account.
pub let balance: UFix64

/// The FLOW balance of the default vault of this account that is available to be moved.
pub let availableBalance: UFix64

/// The current amount of storage used by the account in bytes.
pub let storageUsed: UInt64

/// The storage capacity of the account in bytes.
pub let storageCapacity: UInt64

/// The contracts deployed to the account.
pub let contracts: PublicAccount.Contracts

/// The keys assigned to the account.
pub let keys: PublicAccount.Keys

/// The capabilities of the account.
pub let capabilities: PublicAccount.Capabilities

/// All public paths of this account.
pub let publicPaths: [PublicPath]

/// **DEPRECATED**: Use `capabilities.get` instead.
///
/// Returns the capability at the given public path.
pub fun getCapability<T: &Any>(_ path: PublicPath): Capability<T>

/// **DEPRECATED**
///
/// Returns the target path of the capability at the given public or private path,
/// or nil if there exists no capability at the given path.
pub fun getLinkTarget(_ path: CapabilityPath): Path?

/// 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 runtime type of that object
///
/// Iteration is stopped early if the callback function returns `false`.
///
/// The order of iteration, as well as the behavior of adding or removing objects from storage during iteration,
/// is undefined.
pub fun forEachPublic(_ function: ((PublicPath, Type): Bool))

pub struct Contracts {

/// The names of all contracts deployed in the account.
pub let names: [String]

/// Returns the deployed contract for the contract/contract interface with the given name in the account, if any.
///
/// Returns nil if no contract/contract interface with the given name exists in the account.
pub fun get(name: String): DeployedContract?

/// Returns a reference of the given type to the contract with the given name in the account, if any.
///
/// Returns nil if no contract with the given name exists in the account,
/// or if the contract does not conform to the given type.
pub fun borrow<T: &Any>(name: String): T?
}

pub struct Keys {

/// Returns the key at the given index, if it exists, or nil otherwise.
///
/// Revoked keys are always returned, but they have `isRevoked` field set to true.
pub fun get(keyIndex: Int): AccountKey?

/// Iterate over all unrevoked keys in this account,
/// passing each key in turn to the provided function.
///
/// Iteration is stopped early if the function returns `false`.
/// The order of iteration is undefined.
pub fun forEach(_ function: ((AccountKey): Bool))

/// The total number of unrevoked keys in this account.
pub let count: UInt64
}

pub struct Capabilities {
/// get returns the storage capability at the given path, if one was stored there.
pub fun get<T: &Any>(_ path: PublicPath): Capability<T>?

/// borrow gets the storage capability at the given path, and borrows the capability if it exists.
///
/// Returns nil if the capability does not exist or cannot be borrowed using the given type.
/// The function is equivalent to `get(path)?.borrow()`.
pub fun borrow<T: &Any>(_ path: PublicPath): T?
}
}

Any code can get the PublicAccount for an account address using the built-in getAccount function:

fun getAccount(_ address: Address): PublicAccount

AuthAccount

Authorized Account object have the type AuthAccount, which represents the authorized portion of an account.

Access to an AuthAccount means having full access to its storage, public keys, and code.

Only signed transactions can get the AuthAccount for an account. For each signer of the transaction that signs as an authorizer, the corresponding AuthAccount object is passed to the prepare phase of the transaction.


pub struct AuthAccount {

/// The address of the account.
pub let address: Address

/// The FLOW balance of the default vault of this account.
pub let balance: UFix64

/// The FLOW balance of the default vault of this account that is available to be moved.
pub let availableBalance: UFix64

/// The current amount of storage used by the account in bytes.
pub let storageUsed: UInt64

/// The storage capacity of the account in bytes.
pub let storageCapacity: UInt64

/// The contracts deployed to the account.
pub let contracts: AuthAccount.Contracts

/// The keys assigned to the account.
pub let keys: AuthAccount.Keys

/// The inbox allows bootstrapping (sending and receiving) capabilities.
pub let inbox: AuthAccount.Inbox

/// The capabilities of the account.
pub let capabilities: AuthAccount.Capabilities

/// All public paths of this account.
pub let publicPaths: [PublicPath]

/// All private paths of this account.
pub let privatePaths: [PrivatePath]

/// All storage paths of this account.
pub let storagePaths: [StoragePath]

/// **DEPRECATED**: Use `keys.add` instead.
///
/// Adds a public key to the account.
///
/// The public key must be encoded together with their signature algorithm, hashing algorithm and weight.
pub fun addPublicKey(_ publicKey: [UInt8])

/// **DEPRECATED**: Use `keys.revoke` instead.
///
/// Revokes the key at the given index.
pub fun removePublicKey(_ index: Int)

/// 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.
pub 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.
pub fun type(at: 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.
pub 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.
pub fun copy<T: AnyStruct>(from: StoragePath): T?

/// 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
pub fun borrow<T: &Any>(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.
pub fun check<T: Any>(from: StoragePath): Bool

/// **DEPRECATED**: Instead, use `capabilities.storage.issue`, and `capabilities.publish` if the path is public.
///
/// Creates a capability at the given public or private path,
/// which targets the given public, private, or storage path.
///
/// The target path leads to the object that will provide the functionality defined by this capability.
///
/// The given type defines how the capability can be borrowed, i.e., how the stored value can be accessed.
///
/// Returns nil if a link for the given capability path already exists, or the newly created capability if not.
///
/// It is not necessary for the target path to lead to a valid object; the target path could be empty,
/// or could lead to an object which does not provide the necessary type interface:
/// The link function does **not** check if the target path is valid/exists at the time the capability is created
/// and does **not** check if the target value conforms to the given type.
///
/// The link is latent.
///
/// The target value might be stored after the link is created,
/// and the target value might be moved out after the link has been created.
pub fun link<T: &Any>(_ newCapabilityPath: CapabilityPath, target: Path): Capability<T>?

/// **DEPRECATED**: Use `capabilities.account.issue` instead.
///
/// Creates a capability at the given public or private path which targets this account.
///
/// Returns nil if a link for the given capability path already exists, or the newly created capability if not.
pub fun linkAccount(_ newCapabilityPath: PrivatePath): Capability<&AuthAccount>?

/// **DEPRECATED**: Use `capabilities.get` instead.
///
/// Returns the capability at the given private or public path.
pub fun getCapability<T: &Any>(_ path: CapabilityPath): Capability<T>

/// **DEPRECATED**: Use `capabilities.storage.getController` and `StorageCapabilityController.target()`.
///
/// Returns the target path of the capability at the given public or private path,
/// or nil if there exists no capability at the given path.
pub fun getLinkTarget(_ path: CapabilityPath): Path?

/// **DEPRECATED**: Use `capabilities.unpublish` instead if the path is public.
///
/// Removes the capability at the given public or private path.
pub fun unlink(_ path: CapabilityPath)

/// 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 runtime 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.
///
pub fun forEachPublic(_ function: ((PublicPath, Type): Bool))

/// Iterate over all the private 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 runtime 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 private path,
/// or an existing object is removed from a private path,
/// then the callback must stop iteration by returning false.
/// Otherwise, iteration aborts.
pub fun forEachPrivate(_ function: ((PrivatePath, 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 runtime 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.
pub fun forEachStored(_ function: ((StoragePath, Type): Bool))

pub struct Contracts {

/// The names of all contracts deployed in the account.
pub let names: [String]

/// Adds the given contract to the account.
///
/// The `code` parameter is the UTF-8 encoded representation of the source code.
/// The code must contain exactly one contract or contract interface,
/// which must have the same name as the `name` parameter.
///
/// All additional arguments that are given are passed further to the initializer
/// of the contract that is being deployed.
///
/// The function fails if a contract/contract interface with the given name already exists in the account,
/// if the given code does not declare exactly one contract or contract interface,
/// or if the given name does not match the name of the contract/contract interface declaration in the code.
///
/// Returns the deployed contract.
pub fun add(
name: String,
code: [UInt8]
): DeployedContract

/// **Experimental**
///
/// Updates the code for the contract/contract interface in the account.
///
/// The `code` parameter is the UTF-8 encoded representation of the source code.
/// The code must contain exactly one contract or contract interface,
/// which must have the same name as the `name` parameter.
///
/// Does **not** run the initializer of the contract/contract interface again.
/// The contract instance in the world state stays as is.
///
/// Fails if no contract/contract interface with the given name exists in the account,
/// if the given code does not declare exactly one contract or contract interface,
/// or if the given name does not match the name of the contract/contract interface declaration in the code.
///
/// Returns the deployed contract for the updated contract.
pub fun update__experimental(name: String, code: [UInt8]): DeployedContract

/// Returns the deployed contract for the contract/contract interface with the given name in the account, if any.
///
/// Returns nil if no contract/contract interface with the given name exists in the account.
pub fun get(name: String): DeployedContract?

/// Removes the contract/contract interface from the account which has the given name, if any.
///
/// Returns the removed deployed contract, if any.
///
/// Returns nil if no contract/contract interface with the given name exists in the account.
pub fun remove(name: String): DeployedContract?

/// Returns a reference of the given type to the contract with the given name in the account, if any.
///
/// Returns nil if no contract with the given name exists in the account,
/// or if the contract does not conform to the given type.
pub fun borrow<T: &Any>(name: String): T?
}

pub struct Keys {

/// Adds a new key with the given hashing algorithm and a weight.
///
/// Returns the added key.
pub fun add(
publicKey: PublicKey,
hashAlgorithm: HashAlgorithm,
weight: UFix64
): AccountKey

/// Returns the key at the given index, if it exists, or nil otherwise.
///
/// Revoked keys are always returned, but they have `isRevoked` field set to true.
pub fun get(keyIndex: Int): AccountKey?

/// Marks the key at the given index revoked, but does not delete it.
///
/// Returns the revoked key if it exists, or nil otherwise.
pub fun revoke(keyIndex: Int): AccountKey?

/// Iterate over all unrevoked keys in this account,
/// passing each key in turn to the provided function.
///
/// Iteration is stopped early if the function returns `false`.
///
/// The order of iteration is undefined.
pub fun forEach(_ function: ((AccountKey): Bool))

/// The total number of unrevoked keys in this account.
pub let count: UInt64
}

pub struct Inbox {

/// Publishes a new Capability under the given name,
/// to be claimed by the specified recipient.
pub fun publish(_ value: Capability, name: String, recipient: Address)

/// Unpublishes a Capability previously published by this account.
///
/// Returns `nil` if no Capability is published under the given name.
///
/// Errors if the Capability under that name does not match the provided type.
pub fun unpublish<T: &Any>(_ name: String): Capability<T>?

/// Claims a Capability previously published by the specified provider.
///
/// Returns `nil` if no Capability is published under the given name,
/// or if this account is not its intended recipient.
///
/// Errors if the Capability under that name does not match the provided type.
pub fun claim<T: &Any>(_ name: String, provider: Address): Capability<T>?
}

pub struct Capabilities {

/// The storage capabilities of the account.
pub let storage: AuthAccount.StorageCapabilities

/// The account capabilities of the account.
pub let account: AuthAccount.AccountCapabilities

/// Returns the capability at the given public path.
/// Returns nil if the capability does not exist,
/// or if the given type is not a supertype of the capability's borrow type.
pub fun get<T: &Any>(_ path: PublicPath): Capability<T>?

/// Borrows the capability at the given public path.
/// Returns nil if the capability does not exist, or cannot be borrowed using the given type.
/// The function is equivalent to `get(path)?.borrow()`.
pub fun borrow<T: &Any>(_ path: PublicPath): T?

/// Publish the capability at the given public path.
///
/// If there is already a capability published under the given path, the program aborts.
///
/// The path must be a public path, i.e., only the domain `public` is allowed.
pub fun publish(_ capability: Capability, at: PublicPath)

/// Unpublish the capability published at the given path.
///
/// Returns the capability if one was published at the path.
/// Returns nil if no capability was published at the path.
pub fun unpublish(_ path: PublicPath): Capability?

/// **DEPRECATED**: This function only exists temporarily to aid in the migration of links.
/// This function will not be part of the final Capability Controller API.
///
/// Migrates the link at the given path to a capability controller.
/// Returns the capability ID of the newly issued controller.
/// Returns nil if the migration fails,
/// e.g. when the path does not lead to a storage path.
///
/// Does not migrate intermediate links of the chain.
///
/// Returns the ID of the issued capability controller, if any.
/// Returns nil if migration fails.
pub fun migrateLink(_ newCapabilityPath: CapabilityPath): UInt64?
}

pub struct StorageCapabilities {

/// Get the storage capability controller for the capability with the specified ID.
///
/// Returns nil if the ID does not reference an existing storage capability.
pub fun getController(byCapabilityID: UInt64): &StorageCapabilityController?

/// Get all storage capability controllers for capabilities that target this storage path
pub fun getControllers(forPath: StoragePath): [&StorageCapabilityController]

/// Iterate over all storage capability controllers for capabilities that target this storage path,
/// passing a reference to each controller to the provided callback function.
///
/// Iteration is stopped early if the callback function returns `false`.
///
/// If a new storage capability controller is issued for the path,
/// an existing storage capability controller for the path is deleted,
/// or a storage capability controller is retargeted from or to the path,
/// then the callback must stop iteration by returning false.
/// Otherwise, iteration aborts.
pub fun forEachController(forPath: StoragePath, _ function: ((&StorageCapabilityController): Bool))

/// Issue/create a new storage capability.
pub fun issue<T: &Any>(_ path: StoragePath): Capability<T>
}

pub struct AccountCapabilities {
/// Get capability controller for capability with the specified ID.
///
/// Returns nil if the ID does not reference an existing account capability.
pub fun getController(byCapabilityID: UInt64): &AccountCapabilityController?

/// Get all capability controllers for all account capabilities.
pub fun getControllers(): [&AccountCapabilityController]

/// Iterate over all account capability controllers for all account capabilities,
/// passing a reference to each controller to the provided callback function.
///
/// Iteration is stopped early if the callback function returns `false`.
///
/// If a new account capability controller is issued for the account,
/// or an existing account capability controller for the account is deleted,
/// then the callback must stop iteration by returning false.
/// Otherwise, iteration aborts.
pub fun forEachController(_ function: ((&AccountCapabilityController): Bool))

/// Issue/create a new account capability.
pub fun issue<T: &AuthAccount{}>(): Capability<T>
}
}

A script can get the AuthAccount for an account address using the built-in getAuthAccount function:

fun getAuthAccount(_ address: Address): AuthAccount

This AuthAccount object can perform all operations associated with authorized accounts, and as such this function is only available in scripts, which discard their changes upon completion. Attempting to use this function outside of a script will cause a type error.

Account Creation

Accounts can be created by calling the AuthAccount constructor and passing the account that should pay for the account creation for the payer parameter.

The payer must have enough funds to be able to create an account. If the account does not have the required funds, the program aborts.

transaction() {
prepare(signer: AuthAccount) {
let account = AuthAccount(payer: signer)
}
}

Account Keys

An account (both PublicAccount and AuthAccount) has keys associated with it. An account key has the following structure.

struct AccountKey {
let keyIndex: Int
let publicKey: PublicKey
let hashAlgorithm: HashAlgorithm
let weight: UFix64
let isRevoked: Bool
}

Refer to the PublicKey section for more details on the creation and validity of public keys.

Account Key API

Account key API provides a set of functions to manage account keys.

Add Account Keys

To authorize access to the account, keys can be added using the add() function. Keys can only be added to an AuthAccount.

For example, to create an account and have the signer of the transaction pay for the account creation, and authorize one key to access the account:

transaction(publicKey: [UInt8]) {
prepare(signer: AuthAccount) {
let key = PublicKey(
publicKey: publicKey,
signatureAlgorithm: SignatureAlgorithm.ECDSA_P256
)

let account = AuthAccount(payer: signer)

account.keys.add(
publicKey: key,
hashAlgorithm: HashAlgorithm.SHA3_256,
weight: 10.0
)
}
}

To add a public key to an existing account, which signed the transaction:

transaction(publicKey: [UInt8]) {
prepare(signer: AuthAccount) {
let key = PublicKey(
publicKey: publicKey,
signatureAlgorithm: SignatureAlgorithm.ECDSA_P256
)

signer.keys.add(
publicKey: key,
hashAlgorithm: HashAlgorithm.SHA3_256,
weight: 10.0
)
}
}
info

⚠️ Note: Keys can also be added using the addPublicKey function. However, this method is currently deprecated and is available only for the backward compatibility. The addPublicKey method accepts the public key encoded together with their signature algorithm, hashing algorithm and weight.

transaction(key: [UInt8]) {
prepare(signer: AuthAccount) {
let account = AuthAccount(payer: signer)
account.addPublicKey(key)
}
}

Get Account Keys

Keys that are added to an account can be retrieved using get() function, using the index of the key. Revoked keys are always returned, but they have isRevoked field set to true. Returns nil if there is no key available at the given index. Keys can be retrieved from both PublicAccout and AuthAccount.

transaction() {
prepare(signer: AuthAccount) {
// Get a key from an auth account.
let keyA = signer.keys.get(keyIndex: 2)

// Get a key from the public aacount.
let publicAccount = getAccount(0x42)
let keyB = publicAccount.keys.get(keyIndex: 2)
}
}

Revoke Account Keys

Keys that have been added to an account can be revoked using revoke() function. Revoke function only marks the key at the given index as revoked, but never deletes it. Keys can only be revoked from an AuthAccount.

transaction() {
prepare(signer: AuthAccount) {
// Get a key from an auth account.
let keyA = signer.keys.revoke(keyIndex: 2)
}
}
info

⚠️ Note: Keys can also be removed using the removePublicKey function. However, this method is deprecated and is available only for the backward compatibility.

Account Inbox

Accounts also possess an Inbox that can be used to make Capabilities available to specific accounts. The functions in this Inbox provide a convenient means to "bootstrap" Capabilities, setting up an initial connection between two accounts that will later allow them to transfer data or permissions through a Capability.

Publishing a Capability

An account (the provider) that would like to provide a Capability to another account (the recipient) can do so using the publish function:

fun publish(_ value: Capability, name: String, recipient: Address)

This publishes the specified Capability using the provided string as an identifier, to be later claimed by the recipient. Note, however, that until the recipient does claim this Capability, it is stored on the provider's account, and contributes towards their Account Storage total.

Calling this function emits an event, InboxValuePublished, that includes the address of both the provider and the recipient, as well as the name and the type of the published Capability. Refer to the Core Events section for more details on this event.

Claiming a Capability

The intended recipient of a Capability can claim that Capability from the provider using the claim function:

fun claim<T: &Any>(_ name: String, provider: Address): Capability<T>?

This looks up the specified name in the provider's inbox, returning it to the recipient if it is present, conforms to the provided type argument, and is intended for the calling recipient. If the provider has no Capability stored under the provided name, or if the calling recipient is not the intended recipient of the Capability, the function returns nil. If the borrow type of the Capability is not a subtype of the provided type argument, the function will error at runtime.

Upon successful completion of the claim function, the claimed Capability is removed from the provider's inbox. Note that this means a given Capability can only be claimed once.

Calling this function emits an event, InboxValueClaimed, that includes the address of both the provider and the recipient, as well as the name of the claimed Capability. Refer to the Core Events section for more details on this event.

Unpublishing a Capability

If the provider of a Capability no longer wishes for it to be published for some reason (e.g. they no longer wish to pay for its storage costs), they can unpublish it using the unpublish function:

fun unpublish<T: &Any>(_ name: String): Capability<T>?

This looks up the specified name in the provider's inbox, returning it to the provider if it is present and conforms to the provided type argument. If the provider has no Capability stored under the provided name, the function returns nil. If the borrow type of the Capability is not a subtype of the provided type argument, the function will error at runtime.

Upon successful completion of the unpublish function, the unpublished Capability is removed from the provider's inbox.

Calling this function emits an event, InboxValueUnpublished, that includes the address of the provider, and the name of the claimed Capability. Refer to the Core Events section for more details on this event.

Account Storage

All accounts have storage. Both resources and structures can be stored in account storage.

Paths

Objects are stored under paths. Paths consist of a domain and an identifier.

Paths start with the character /, followed by the domain, the path separator /, and finally the identifier. For example, the path /storage/test has the domain storage and the identifier test.

There are only three valid domains: storage, private, and public.

Objects in storage are always stored in the storage domain.

Paths in the storage domain have type StoragePath, in the private domain PrivatePath, and in the public domain PublicPath.

PrivatePath and PublicPath are subtypes of CapabilityPath.

Both StoragePath and CapabilityPath are subtypes of Path.

Path
CapabilityPathStoragePath
PrivatePathPublicPath

Path Functions

fun toString(): String

Returns the string representation of the path.

let storagePath = /storage/path

storagePath.toString() // is "/storage/path"

There are also utilities to produce paths from strings:

fun PublicPath(identifier: string): PublicPath?
fun PrivatePath(identifier: string): PrivatePath?
fun StoragePath(identifier: string): StoragePath?

Each of these functions take an identifier and produce a path of the appropriate domain:

let pathID = "foo"
let path = PublicPath(identifier: pathID) // is /public/foo

Account Storage API

Account storage is accessed through the following functions of AuthAccount. This means that any code that has access to the authorized account has access to all its stored objects.

fun save<T>(_ value: T, to: StoragePath)

Saves an object to account storage. Resources are moved into storage, and structures are copied.

T is the type parameter for the object type. It can be inferred from the argument's type.

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.

fun type(at: StoragePath): Type?

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

fun load<T>(from: StoragePath): T?

Loads an object from account storage. If no object is stored under the given path, the function returns nil. 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.

T is the type parameter for the object type. A type argument for the parameter must be provided explicitly.

The type T must be a supertype of the type of the loaded object. If it is not, execution will abort with an error. 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, i.e., only the domain storage is allowed.

fun copy<T: AnyStruct>(from: StoragePath): T?

Returns a copy of a structure stored in account storage, without removing it from storage.

If no structure is stored under the given path, the function returns nil. If there is a structure stored, it is copied. The structure stays stored in storage after the function returns.

T is the type parameter for the structure type. A type argument for the parameter must be provided explicitly.

The type T must be a supertype of the type of the copied structure. If it is not, execution will abort with an error. The given type does not necessarily need to 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.

// Declare a resource named `Counter`.
//
resource Counter {
pub var count: Int

pub init(count: Int) {
self.count = count
}
}

// In this example an authorized account is available through the constant `authAccount`.

// 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.
//
authAccount.save(<-create Counter(count: 42), to: /storage/counter)

// Run-time error: Storage already contains an object under path `/storage/counter`
//
authAccount.save(<-create Counter(count: 123), to: /storage/counter)

// 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 <- authAccount.load<@Counter>(from: /storage/counter)

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

// 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 <- authAccount.load<@Counter>(from: /storage/counter)

// 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.
//
authAccount.save(<-create Counter(count: 123), to: /storage/otherCounter)

// 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 <- authAccount.load<@Vault>(from: /storage/otherCounter)

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

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

authAccount.save("Hello, world!", to: /storage/helloWorldMessage)

// 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 = authAccount.copy<String>(from: /storage/helloWorldMessage)

// Create a new instance of the resource type `Vault`
// and save it in the storage of the account.
//
authAccount.save(<-createEmptyVault(), to: /storage/vault)

// Invalid: Cannot copy a resource, as this would allow arbitrary duplication.
//
let vault <- authAccount.copy<@Vault>(from: /storage/vault)

As it is convenient to work with objects in storage without having to move them out of storage, as it is necessary for resources, it is also possible to create references to objects in storage: This is possible using the borrow function of an AuthAccount:

fun borrow<T: &Any>(from: StoragePath): T?

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.

T is the type parameter for the object type. A type argument for the parameter must be provided explicitly. The type argument must be a reference to any type (&Any; Any is the supertype of all types). It must be possible to create the given reference type T for the stored / borrowed object. If it is not, execution will abort with an error. The given type does not necessarily need to 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.

// Declare a resource interface named `HasCount`, that has a field `count`
//
resource interface HasCount {
count: Int
}

// Declare a resource named `Counter` that conforms to `HasCount`
//
resource Counter: HasCount {
pub var count: Int

pub init(count: Int) {
self.count = count
}
}

// In this example an authorized account is available through the constant `authAccount`.

// 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.
//
authAccount.save(<-create Counter(count: 42), to: /storage/counter)

// 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/counter`
// and it has type `Counter`, so it can be borrowed as `&Counter`
//
let counterRef = authAccount.borrow<&Counter>(from: /storage/counter)

counterRef?.count // is `42`

// Create a reference to the object stored under path `/storage/counter`,
// typed as `&{HasCount}`.
//
// `hasCountRef` is non-`nil`, as there is an object stored under path `/storage/counter`,
// and the stored value of type `Counter` conforms to the requested type `{HasCount}`:
// the type `Counter` implements the restricted type's restriction `HasCount`

let hasCountRef = authAccount.borrow<&{HasCount}>(from: /storage/counter)

// Create a reference to the object stored under path `/storage/counter`,
// typed as `&{SomethingElse}`.
//
// `otherRef` is `nil`, as there is an object stored under path `/storage/counter`,
// but the stored value of type `Counter` does not conform to the requested type `{Other}`:
// the type `Counter` does not implement the restricted type's restriction `Other`

let otherRef = authAccount.borrow<&{Other}>(from: /storage/counter)

// 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 = authAccount.borrow<&{HasCount}>(from: /storage/nonExistent)

Storage Iteration

It is possible to iterate over an account's storage using the following iteration functions:

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

Each of these iterates over every element in the specified domain (public, private, and storage), applying the function argument to each. The first argument of the function is the path of the element, and the second is its runtime type. In the case of the private and public path iteration functions, this is the runtime type of the capability linked at that path. The Bool return value determines whether iteration continues; true will proceed to the next stored element, while false will terminate iteration. 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.

warning

The order of iteration is undefined. Do not rely on any particular behaviour.

Saving to or removing from storage during iteration can cause the order in which values are stored to change arbitrarily.

Continuing to iterate after such an operation will cause Cadence to panic and abort execution. In order to avoid such errors, we recommend not modifying storage during iteration. If you do, return false from the iteration callback to cause iteration to end after the mutation like so:

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

account.forEachStored(fun (path: StoragePath, type: Type): Bool {
if type == Type<String>() {
account.save("bar", to: /storage/foo5)
// returning false here ends iteration after storage is modified, preventing a panic
return false
}
return true
})
info

The iteration will skip any broken elements in the storage. An element could be broken due to invalid types associated with the stored value. e.g: A value belongs to type T of a contract with syntax/semantic errors.

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 is stored in an account (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 will fail.

An account's storage used and storage capacity can be checked using the storageUsed and storageCapacity fields. The fields represent current values of storage which means this would be true:

let storageUsedBefore = authAccount.storageUsed
authAccount.save(<-create Counter(count: 123), to: /storage/counter)
let storageUsedAfter = authAccount.storageUsed

let storageUsedChanged = storageUsedBefore != storageUsedAfter // is true