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.
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);
}
Guides in this category:
📄️ How to choose the right storage type for your use case
This guide walks you through choosing the most suitable storage type for your use case and how to implement it
📄️ Use instance storage in a contract
Instance storage has an archival TTL that is tied to the contract instance itself
📄️ Use persistent storage in a contract
Persistent storage can be useful for ledger entrys that are not common across every user of the contract instance
📄️ Use temporary storage in a contract
Temporary storage is useful for a contract to store data that can quickly become irrelevant or out-dated