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.
#[contracttype]
pub enum DataKey {
Favorite(Address),
}
#[contract]
pub struct FavoriteContract;
#[contractimpl]
impl FavoriteContract {
// This function generates, stores, and returns a random number for the user
pub fn generate_fave(env: Env, user: Address) -> u64 {
let key = DataKey::Favorite(user);
let fave: u64 = env.prng().gen();
env.storage().persistent().set(&key, &fave);
fave
}
// This function retrieves and returns the random number for the user
pub fn get_fave(env: Env, user: Address) -> u64 {
let key = DataKey::Favorite(user);
if let Some(fave) = env.storage().persistent().get(&key) {
fave
} else {
0
}
}
}
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