Skip to main content

Simple state

The state is where the smart contract saves and retrieves data. In a sense, the smart contract state functions similarly to a database interaction layer in a traditional application.

The simplest method of representing state involves storing a single item. For instance, in the cw20 contract, the TokenInfo is recorded during the contract's initialization.

First, a TokenInfo type is declared in state.rs:

#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub struct TokenInfo {
pub name: String,
pub symbol: String,
pub decimals: u8,
pub total_supply: Uint128,
pub mint: Option<MinterData>,
}

Then the storage is initialized:

pub const TOKEN_INFO: Item<TokenInfo> = Item::new("token_info");

In the contract, we see in the instantiate function how data can be saved to this:

let data = TokenInfo {
name: msg.name,
symbol: msg.symbol,
decimals: msg.decimals,
total_supply,
mint,
};

TOKEN_INFO.save(deps.storage, & data) ?;