Skip to content

Transient Storage

Soroban Transient Storage
#![no_std]
use soroban_sdk::{contract, contractimpl, Env, log};
 
extern crate alloc;
 
use alloc::vec::Vec;
 
#[contract]
pub struct TransientStorage;
 
#[contractimpl]
impl TransientStorage {
    /// Allocates a temporary vector holding the values 0 to the set count-1, performs a computation and returns the sum.
    pub fn sum(env: Env, count: u32) {
        // Create a new empty vector to store the values.
        let mut values = Vec::new();
 
        // Perform the vector with values from 0 to count-1.
        for i in 0..count {
            values.push(i);
        }
 
        // Calculate the sum of the values in the vector.
        let sum: u32 = values.iter().sum();
 
        // Return the calculated value.
        log!(&env, "Sum of values: {}", sum);
    }
}

Guide

#![no_std] This attribute prevents linking to the standard library, making the code lighter and more efficient for Soroban contracts. It's big so we save on size.

use soroban_sdk::{contract, contractimpl, Env, log} Imports stuffs from the Soroban SDK. Env is basic Soroban type, we need it because we can't use the Rust standard library.

extern crate alloc Sets the alloc package to be used in creating a vector for the transient storage functionality.

use alloc::vec::Vec Targets the Vec attribute to be used in creating a list of values.

#[contract] Marks the struct as a Soroban smart contract. Soroban smart contracts are defined as Rust structs.

#[contractimpl] Marks the implementation block as containing contract methods and transforms it to code that Soroban can evaluate directly

pub Marks a function as external, meaning it can be invoked outside of the context of the contract code it self.

Explanation

The function sets an empty vector, loops from 0 to the number just before the set count and returns the sum as a logged output.

Run in Playground

Loading playground...