Skip to main content

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
}
}
}