Back to Learn
basic examples
Constants
Define compile-time constants in your Stylus contracts.
Constants
Constants are values that are set at compile time and cannot be changed.
Defining Constants
Use Rust's const keyword:
`` const MAX_SUPPLY: u64 = 1_000_000; const DECIMALS: u8 = 18; const OWNER: &str = "0x...";rust
`
Benefits
- No storage costs (compiled into bytecode)
- Gas efficient access
- Type safety at compile time
Usage with Alloy Types
`rust
use alloy_primitives::{U256, address, Address};
const MAX_UINT: U256 = U256::MAX;
const ZERO_ADDRESS: Address = Address::ZERO;
``Code Example
#![cfg_attr(not(feature = "export-abi"), no_main)]
extern crate alloc;
use stylus_sdk::prelude::*;
use alloy_primitives::{U256, Address, address};
// Compile-time constants
const MAX_SUPPLY: u64 = 1_000_000;
const DECIMALS: u8 = 18;
const FEE_PERCENT: u64 = 3;
// Address constants using the address! macro
const TREASURY: Address = address!("0000000000000000000000000000000000000001");
#[storage]
#[entrypoint]
pub struct Token {
total_supply: StorageU256,
}
#[public]
impl Token {
pub fn max_supply(&self) -> U256 {
U256::from(MAX_SUPPLY)
}
pub fn decimals(&self) -> u8 {
DECIMALS
}
pub fn calculate_fee(&self, amount: U256) -> U256 {
amount * U256::from(FEE_PERCENT) / U256::from(100)
}
}