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:

``rust

const MAX_SUPPLY: u64 = 1_000_000;

const DECIMALS: u8 = 18;

const OWNER: &str = "0x...";

`

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)
    }
}

Key Points

  • Constants use the const keyword
  • No storage costs - embedded in bytecode
  • Use for fixed values like max supply, decimals
  • address! macro for address constants
  • Type annotations required for const

Navigation