Constants
Constants are values that are bound to a name and cannot change. They are always immutable. In Rust, constants are declared with the const
keyword. Unlike variables declared with the let
keyword, constants must be annotated with their type.
Constants are valid for the entire length of the transaction. They are essentially inlined wherever they are used, meaning that their value is copied directly into whatever context invokes them.
Since their value is hardcoded, they can save on gas cost as their value does not need to be fetched from storage.
Learn More
src/main.rs
#![no_main]
#![no_std]
extern crate alloc;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
use alloc::vec;
use alloc::vec::Vec;
use stylus_sdk::alloy_primitives::Address;
use stylus_sdk::prelude::*;
use stylus_sdk::storage::StorageAddress;
// Consts must be 'static, so Rust primitives work well
// Addresses are 20 bytes long, this one is 'checksummed'
const OWNER: &str = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045";
#[solidity_storage]
#[entrypoint]
pub struct Contract {
owner: StorageAddress,
}
#[external]
impl Contract {
// Sets the owner to the OWNER const set above
pub fn init(&mut self) -> Result<(), Vec<u8>> {
// Parse the const hex &str as a local Address variable
let owner_address = Address::parse_checksummed(OWNER, None).expect("Invalid address");
// Save the result as the owner
self.owner.set(owner_address);
Ok(())
}
// Returns the current owner
pub fn owner(&self) -> Result<Address, Vec<u8>> {
let owner_address = self.owner.get();
Ok(owner_address)
}
}
Cargo.toml
[package]
name = "constants"
version = "0.1.0"
edition = "2021"
[dependencies]
# Note: Do not deploy to prod with debug flag set
stylus-sdk = { version = "0.4.2", features = ["debug"] }
wee_alloc = "0.4.5"
alloy-sol-types = "0.3.1"
[features]
export-abi = ["stylus-sdk/export-abi"]
[profile.release]
codegen-units = 1
strip = true
lto = true
panic = "abort"
opt-level = "s"
[workspace]