Skip to main content

Storing Values

Here is how you store simple values in storage:

#[ink(storage)]pub struct MyContract {    // Store a bool    my_bool: bool,    // Store some number    my_number: u32,}/* --snip-- */

Supported Types#

Substrate contracts may store types that are encodable and decodable with Parity Codec which includes most Rust common data types such as bool, u{8,16,32,64,128}, i{8,16,32,64,128}, String, tuples, and arrays.

ink! provides Substrate specific types like AccountId, Balance, and Hash to smart contracts as if they were primitive types. ink! also provides storage types for more elaborate storage interactions through the storage module:

use ink_storage::collections::{Vec, HashMap, Stash, Bitvec};

Here is an example of how you would store an AccountId and Balance:

// We are importing the default ink! typesuse ink_lang as ink;
#[ink::contract]mod MyContract {
    // Our struct will use those default ink! types    #[ink(storage)]    pub struct MyContract {        // Store some AccountId        my_account: AccountId,        // Store some Balance        my_balance: Balance,    }    /* --snip-- */}

You can find all the supported Substrate types in the ink_storage crate.

Initializing Storage in Constructors#

Constructors are how values get initialized. Every ink! smart contract must have a constructor which is run once when a contract is created. ink! smart contracts can have multiple constructors:

use ink_lang as ink;
#[ink::contract]mod mycontract {
    #[ink(storage)]    pub struct MyContract {        number: u32,    }
    impl MyContract {        /// Constructor that initializes the `u32` value to the given `init_value`.        #[ink(constructor)]        pub fn new(init_value: u32) -> Self {            Self {                number: init_value,            }        }
        /// Constructor that initializes the `u32` value to the `u32` default.        #[ink(constructor)]        pub fn default() -> Self {            Self {                number: Default::default(),            }        }    /* --snip-- */    }}