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:
📄️ 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.
📄️ Use persistent storage in a contract
Persistent storage can be very useful for ledger entrys that are not common across every user of the contract instance, but that are not suitable to be temporary (user balances, for example). In this guide, we'll assume we want to store a random number for a user, and store it in the contract's persistent storage as though it were their favorite number.
📄️ Use temporary storage in a contract
Temporary storage is useful for a contract to store data that can quickly become irrelevant or out-dated. For example, here's how a contract might be used to store a recent price of BTC against the US Dollar.