Back to Learn
basic examples

Variables

Learn about local, state, and global variables in Stylus contracts.

Variables in Stylus

Stylus contracts have three types of variables: local, state, and global.

Local Variables

Declared with let or let mut, not stored on-chain:

``rust

let x = 42;

let mut y = 100;

`

Important: Stylus local variables are 100x cheaper than Solidity!

State Variables

Persist on-chain using Storage types:

`rust

#[storage]

pub struct Contract {

owner: StorageAddress,

count: StorageU256,

}

`

Global Variables

Access blockchain context through SDK functions:

`rust

use stylus_sdk::{msg, block};

let sender = msg::sender(); // msg.sender equivalent

let timestamp = block::timestamp(); // block.timestamp

let value = msg::value(); // msg.value

``

Code Example

#![cfg_attr(not(feature = "export-abi"), no_main)]
extern crate alloc;

use stylus_sdk::prelude::*;
use stylus_sdk::storage::{StorageAddress, StorageU256};
use stylus_sdk::{msg, block};
use alloy_primitives::{Address, U256};

#[storage]
#[entrypoint]
pub struct Variables {
    // State variables (on-chain)
    owner: StorageAddress,
    last_updated: StorageU256,
}

#[public]
impl Variables {
    pub fn do_something(&mut self) -> Address {
        // Local variable (not stored)
        let caller = msg::sender();

        // Global variables
        let _timestamp = block::timestamp();
        let _value = msg::value();

        // Update state
        self.owner.set(caller);
        self.last_updated.set(U256::from(block::timestamp()));

        caller
    }
}

Key Points

  • Local variables are cheap and temporary
  • State variables persist on-chain in Storage types
  • msg::sender() returns the caller address
  • block::timestamp() returns current block time
  • msg::value() returns ETH sent with the call