Back to Learn
storage

Storage Data Types

Understand the storage-specific types for persisting data on-chain.

Storage Data Types

Stylus provides special storage types for on-chain persistence. These are different from regular Rust types.

Basic Storage Types

- StorageU256 - Stores unsigned 256-bit integers

- StorageI256 - Stores signed 256-bit integers

- StorageBool - Stores boolean values

- StorageAddress - Stores Ethereum addresses

- StorageString - Stores dynamic strings

Storage Maps

StorageMap provides key-value storage:

``rust

balances: StorageMap,

`

Storage Vectors

StorageVec for dynamic arrays:

`rust

items: StorageVec,

`

Access Methods

All storage types use:

- .get() - Read the value

- .set(value) - Write a value

- StorageString uses .get_string() and .set_string()`

Code Example

use stylus_sdk::prelude::*;
use stylus_sdk::storage::{
    StorageU256, StorageBool, StorageAddress,
    StorageString, StorageMap, StorageVec
};
use alloy_primitives::{Address, U256};

#[storage]
pub struct MyContract {
    // Basic types
    count: StorageU256,
    is_active: StorageBool,
    owner: StorageAddress,
    name: StorageString,

    // Collections
    balances: StorageMap<Address, U256>,
    items: StorageVec<U256>,
}

#[public]
impl MyContract {
    pub fn get_count(&self) -> U256 {
        self.count.get()
    }

    pub fn set_count(&mut self, value: U256) {
        self.count.set(value);
    }

    pub fn get_balance(&self, addr: Address) -> U256 {
        self.balances.get(addr)
    }

    pub fn set_balance(&mut self, addr: Address, amount: U256) {
        self.balances.insert(addr, amount);
    }
}

Practice Challenge

Key Points

  • Storage types persist data on-chain
  • Use .get() and .set() for basic types
  • StorageMap for key-value mappings
  • StorageVec for dynamic arrays
  • StorageString has special get_string/set_string methods