XION
DiscordGithub
  • Welcome to XION
  • XION'S Core
    • Concepts
      • Generalized Chain Abstraction
      • Intro to Account Abstraction
      • XION's Meta Accounts
      • Meta Accounts Design
      • Architecture & Tech Glossary
      • Use Cases
  • developers
    • XION Quick Start
      • Zero to App in 5 Minutes
        • Launch a User Map App on XION in 5 Minutes
        • React Native Mobile App on XION in 5 Minutes
        • Todo App
          • Build a TODO App using the Collection-Document Storage Smart Contract
          • Build a TODO Mobile App using the DocuStore Contract
    • Mobile App Development
      • Set up your XION Mobile Development Environment
      • Build a TODO Mobile App using the DocuStore Contract
      • Create Mobile App and Integrate Meta Account Authentication
      • Building a React Native Mobile App with Abstraxion (Xion.js)
    • Getting Started (Advanced)
      • Set Up Local Environment
        • Setting up your Local Smart Contract Development Environment for XION
          • Setting up your XION Smart Contract Development Environment on Windows (WSL2 + Ubuntu)
        • Set Up an Integrated Development Environment (IDE)
        • Interacting with Xion Chain using Xion Daemon
      • Your First Contract
        • Deploying Your First Smart Contract on XION
      • Gasless UX & Permission Grants
        • Enabling Gasless Transactions with Treasury Contracts
      • App Development
        • Account Abstraction with Gasless Transactions
        • Interact with XION via your Backend Service
    • Re-using Existing Contracts
      • Deployed Contracts on XION
      • Non-Fungible Tokens (NFTs)
      • Fungible Tokens
      • Marketplace
      • Multisig
      • Proxy Contracts
      • Membership Management
      • Governance
      • Valuts
      • SCV Audited Contracts
    • Web3 for Web2 Developers
      • Web2 vs Web3 App Architecture: A Comparison
      • Misconceptions and Misapplied Web2 Patterns
      • Recommended Architecture for Apps on XION
    • Building for Mainnet
      • Xion Testnet: Your Development Playground
      • Building with Audited & Battle-Tested Contracts
      • Community Engagement: Building Support for Your app
      • Deploying to Xion Mainnet
        • Smart Contract Audits: Process, Costs & Support
        • Governance Process to Deploying Smart Contracts to Mainnet
    • Learn & Build
      • Token Factory
        • Creating, Minting, and Interacting with a Token Factory Token
        • Building a React dApp to Interact with Token Factory Tokens
        • Integrating a Token Factory Token in a Smart Contract
      • Websockets
        • WebSockets with Xion: Real-Time Communication
      • Oracles
        • Creating a Smart Contract with Pyth Oracle Integration
      • Indexers: Optimized Data Retrieval
        • SubQuery
      • Use Cases
        • Building a Per-User Data Storage App
        • Build a TODO App using the Collection-Document Storage Smart Contract
      • Crossmint Integration
        • Crossmint Digital Collectibles Checkout via Credit Card
    • Reference and Resources
      • Requesting XION Testnet Tokens
      • Public Endpoints & Resources
      • Block Explorers
      • Governance
        • Deploying Smart Contracts to Mainnet
      • Developer Tools: Abstract
      • IBC Denoms on XION Networks
      • Frequently Asked Questions
      • XION Token Contract Addresses on EVM Chains
  • Nodes & Validators
    • Run a Node
      • System Specifications
      • Build the Xion Daemon
      • Download the Xion Daemon
      • Configure the Xion Daemon
        • app.toml
        • client.toml
        • config.toml
      • Join the XION Network
        • xion-testnet-1
      • Confirm node is running
    • Become a Validator
      • Initial Setup
      • Obtain a XION Wallet Address
      • Obtain Funds
        • Testnet
      • Create Validator
    • IBC Relayers and Tokens
  • Others
    • Resources
Powered by GitBook
On this page
  • Simple State
  • Complex State

Was this helpful?

Edit on GitHub
  1. developers
  2. Reference and Resources
  3. CosmWasm Resources
  4. Contract Semantics

Simple and Complex States

Simple State

The state serves as the repository for storing and accessing data within a smart contract. Conceptually, it operates in a manner akin to the database interaction layer found in conventional applications.

A basic approach to managing state entails the storage of a single entity. For instance, in the case of the cw20 contract, the TokenInfo is established and recorded during the contract's initialization phase.

Initially, a TokenInfo type is defined 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");

Within the contract, the instantiate function demonstrates the process of saving data to this:

let data = TokenInfo {
  name: msg.name,
  symbol: msg.symbol,
  decimals: msg.decimals,
  total_supply,
  mint,
};
TOKEN_INFO.save(deps.storage, & data) ?;

Complex State

In more intricate solutions, there might be a requirement to store supplementary information. One approach to accomplish this is by serializing comprehensive JSON data structures, which enables data retrieval using key-value pairs.

In the context of CW20, the association of addresses with their CW20 balances is accomplished using a Map data structure

pub const BALANCES: Map<&Addr, Uint128> = Map::new("balance");
let rcpt_addr = deps.api.addr_validate(&recipient)?;
BALANCES.update(
   deps.storage,
   &info.sender,
   |balance: Option<Uint128>| -> StdResult<_> {
      Ok(balance.unwrap_or_default().checked_sub(amount)?)
   },
)?;

There's a lot of complexity here, so let's dissect it step by step:

  1. deps.storage is an input provided, originating from the contract context. Think of deps as similar to the ctx you might have encountered in the Cosmos SDK.

  2. &rcpt_addr is a borrowed reference to the validated recipient address. It's been verified and confirmed as valid; otherwise, the "let" statement would have triggered an error. This reference corresponds to the key within the key/value pair.

  3. The third statement consists of an anonymous function (lambda) that returns a StdResult and carries out a computation based on the current value of balance. In this context, balance signifies the value within the key/value pair, while &rcpt_addr serves as the key.

Last updated 1 year ago

Was this helpful?

You can locate the code for this right

Here's an illustrative example of how to work with the value within the BALANCES map (), as demonstrated in the subsequent code snippet:

here.
seen here