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:
`` let x = 42; let mut y = 100;rust
`
Important: Stylus local variables are 100x cheaper than Solidity!
State Variables
Persist on-chain using Storage types:
` #[storage] pub struct Contract { owner: StorageAddress, count: StorageU256, }rust
`
Global Variables
Access blockchain context through SDK functions:
` use stylus_sdk::{msg, block}; let sender = msg::sender(); // msg.sender equivalent let timestamp = block::timestamp(); // block.timestamp let value = msg::value(); // msg.valuerust
``
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
}
}