Overview
Persistent storage is designed for data that must remain available indefinitely and be recoverable after expiration. Access persistent storage viaenv.storage().persistent().
Key Properties:
- More expensive than temporary storage
- Expired entries move to Expired State Stack (ESS) for recovery
- Only one version can exist at a time (cannot recreate while expired version exists)
- Best for critical data: token balances, ownership records, user profiles
Type Definition
Storage type:
Methods
has
Checks if a value exists for the given key.key: The key to check
true if a value exists, false otherwise
Example:
get
Retrieves a value for the given key.key: The key to retrieve
Some(V) if the value exists, None otherwise
Panics: If the stored value cannot be converted to type V
Example:
set
Stores a value for the given key.key: The key to store underval: The value to store
update
Updates a value by applying a function to the current value.key: The key to updatef: Function that receives current value (orNone) and returns new value
try_update
Updates a value by applying a fallible function.key: The key to updatef: Fallible function that receives current value and returnsResult<V, E>
Ok(V) with the new value, or Err(E) if the function fails
Example:
extend_ttl
Extends the time-to-live for a storage entry.key: The storage key to extendthreshold: Only extend if TTL is below this value (in ledgers)extend_to: New TTL value when extended (in ledgers)
- Only extends TTL if current TTL < threshold
- Sets TTL to
extend_toledgers from current ledger - No-op if TTL >= threshold (prevents unnecessary operations)
- Set
thresholdto allow time for extension before expiration - Set
extend_toconsidering access patterns and costs - Extend TTL on every write or read for critical data
- Use higher
extend_tovalues for frequently accessed data
remove
Removes a key and its value from storage.key: The key to remove
Complete Example
Here’s a complete token contract demonstrating persistent storage usage:Test Utilities
When thetestutils feature is enabled, additional methods are available:
See Also
- Storage Overview - Overview of all storage types
- Temporary Storage - Lower-cost temporary storage
- Instance Storage - Contract instance storage
Source Reference
Implementation:soroban-sdk/src/storage.rs:301-388