Skip to main content

Use instance storage in a contract

Under the hood, instance storage is exactly like persistent storage. The only difference is that anything stored in instance storage has an archival TTL that is tied to the contract instance itself. So, if a contract is live and available, the instance storage is guaranteed to be so, too.

Instance storage is really useful for global contract data that is shared among all users of the contract (token administrator, for example). From the token example contract, the helper functions to set and retrieve the admininistrator address are basically just wrappers surrounding the one Admin ledger entry.

caution

It should be noted that every piece of data stored in instance() storage is retrieved from the ledger every time the contract is invoked. Even if the invoked function does not interact with any ledger data at all. This can lead to more expensive (computationally and financially) function invocations if the stored data grows over time. Choose judiciously which bits of data actually belong in the instance storage, and which should be kept in persistent storage.

pub fn has_administrator(e: &Env) -> bool {
let key = DataKey::Admin;
e.storage().instance().has(&key)
}

pub fn read_administrator(e: &Env) -> Address {
let key = DataKey::Admin;
e.storage().instance().get(&key).unwrap()
}

pub fn write_administrator(e: &Env, id: &Address) {
let key = DataKey::Admin;
e.storage().instance().set(&key, id);
}