🇵🇹
DAO Lunes Labs - PT
  • 👋Seja Bem-vindo a DAO Lunes Labs
  • Overview
    • 🚪Introdução
    • 🚀Manifesto DAO Lunes Labs
    • 🍕Tokenomics
    • 👑Proposta de Valor
    • 🧑‍🚀Comunidade e Participação
    • 🗺️Roadmap
    • 💼Compromisso com Ética e Responsabilidade
    • 👾Programa de Bug Bounty: Lunes Security Initiative (LSI)
  • Developers
    • 💽Para Nodes
      • 🥾Instalar Node
        • 🏗️Rust toolchain
        • 🐧Linux
    • 🖥️Para Desenvolvedores
      • 📑Smart Contract Ink! 4.x
        • ✨Configuração
          • 📐Criando um projeto com ink!
          • 🖥️Compile Seu Contrato
          • ⛓️Executar um nó Lunes
          • ⬆️Implante seu contrato
          • 🔛Chame Seu Contrato
          • 🛠️Solução de problemas
        • 🪄Fundamentos
          • 👾Modelo de Contrato
          • 👨‍🚀Armazenando Valores
          • 🔭Lendo Valores do Armazenamento
          • 🦸‍♂️Alterando os Valores de Armazenamento
          • 🎡Eventos
          • 👨‍🔧Seletores
          • 🪶Definições de Trait
          • 🗣️Chamadas entre Contratos (Cross-Contract Calls)
          • 🦸Contratos Atualizáveis
          • 🤺Funções do Ambiente
          • 🏟️Tipos de Ambiente de Cadeia
          • 💠Metadados
          • 🧪Testes de Contrato
          • 🕵️‍♂️Depuração de Contratos
          • 🔬Verificação de Contrato
        • 🎙️Macros e Atributos
          • 📇#[ink::contract]
          • 👽#[ink(anonymous)]
          • 👷#[ink(constructor)]
          • 📏#[ink(default)]
          • 🎢#[ink(event)]
          • 🛩️#[ink(impl)]
          • 📧#[ink(message)]
          • 👨‍💼#[ink(namespace = "…")]
          • 💸#[ink(payable)]
          • ⚡#[ink(selector = S:u32)]
          • 💽#[ink(storage)]
          • 💣#[ink(topic)]
          • ⛓️#[ink::chain_extension]
        • 💽Storege & Data Structires
          • Working with Mapping
          • Storage Layout
          • Custom Data Structures
          • Metadata Format
        • 👾Frontend Development
          • Getting Started
          • Connect Wallet
          • Hooks
            • All Hooks
            • Contracts
              • useCall
              • useCallSubscription
              • useContract
              • useDryRun
              • useEventSubscription
              • useEvents
              • useTx
              • useTxPaymentInfo
            • Wallets
              • useWallet
              • useAllWallets
              • useInstalledWallets
              • useUninstalledWallets
            • API
              • useApi
              • useBalance
              • useBlockHeader
          • Configuration
          • useink / core
            • Contracts
              • Call
              • decodeCallResult
              • decodeError
              • getRegistryError
              • toAbiMessage
          • useink / chains
            • Getting Started
            • Chain Configurations
            • ChainId
          • useink / notifications
            • Getting Started
            • Configuration
            • useNotifications
            • toNotificationLevel
          • useink / utils
            • Getting Started
            • Pick Helpers
            • tx Helpers
            • Types
        • 💡Examples
          • 📔Smart Contracts
          • 📱Dapps
        • 🛠️Tools
          • 🖌️OpenBrush
      • 📒Smart Contract - EVM
        • Create ERC-20 Ink Token!
      • 💰Desenvolvendo uma Wallet Lunes
        • 👾Transações de Tokens PSP22
    • 🎨Para Designers
      • 🖌️Brand Lunes
Powered by GitBook
On this page
  • Tipos Suportados​
  • Inicializando o Storage nos Constructors

Was this helpful?

  1. Developers
  2. Para Desenvolvedores
  3. Smart Contract Ink! 4.x
  4. Fundamentos

Armazenando Valores

Last updated 1 year ago

Was this helpful?

Aqui está como você armazena valores simples no armazenamento:

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

Tipos Suportados

Os contratos Lunes podem armazenar tipos que são codificáveis e decodificáveis com o , o que inclui a maioria dos tipos de dados comuns do Rust, como bool, u{8,16,32,64,128}, i{8,16,32,64,128}, String, tuples e arrays.

Além disso, o ink! fornece tipos específicos do , como AccountId, Balance e Hash, para contratos inteligentes como se fossem tipos primitivos.

String, Vetor e Mais

Como o ink! opera em um ambiente no_std, precisamos fornecer nossas próprias definições para os tipos de dados incluídos em std, como String e Vec. A crate oferece essas definições para a maioria dos tipos de dados std comuns e pode ser usada com segurança em um contrato ink!.

Você pode usar as definições do prelude da seguinte forma:

#[ink::contract]
mod MyContractWithStringsAndArrays {
    use ink::prelude::string::String;
    use ink::prelude::vec::Vec;

    #[ink(storage)]
    pub struct MyContract {
        // Store some String
        my_string: String,
        // Store some u32 in a vec
        my_vector: Vec<u32>,
    }
    /* --snip-- */
}

Aqui está um exemplo de como você armazenaria tipos do Lunes AccountId, Balance and Hash:

Aqui está um exemplo de como você armazenaria os tipos da Lunes AccountId, Balance e Hash:

#[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,
        // Store some Hash
        my_hash: Hash,
    }
    /* --snip-- */
}
pub enum Status {
    /// An auction has not started yet.
    NotStarted,
    /// We are in the starting period of the auction, collecting initial bids.
    OpeningPeriod,
    /// We are in the ending period of the auction, where we are taking snapshots
    /// of the winning bids.
}

Você pode combinar todos os tipos mencionados acima, inclusive em uma struct personalizada, que pode ser armazenada no armazenamento do contrato.

mod MyContract {
    use ink::prelude::string::String;
    use ink::prelude::vec::Vec;


    pub struct Auction {
        /// Branded name of the auction event.
        name: String,
        /// Some hash identifying the auction subject.
        subject: Hash,
        /// Auction status.
        status: Status, // Enum: Usage shown in next section
        /// Candle auction can have no winner.
        /// If auction is finalized, that means that the winner is determined.
        finalized: bool,
        /// vector
        vector: Vec<u8>,
    }

    #[ink(storage)]
    pub struct MyContract {
        // Store Auctions in a vec
        auctions: Vec<Auction>,
    }
}

Os valores de uma enumeração devem ser referenciados como Status::OpeningPeriod.

Inicializando o Storage nos Constructors

Os construtores são responsáveis por inicializar os valores. Todo contrato inteligente ink! deve ter um construtor que é executado uma vez quando um contrato é criado. Os contratos inteligentes ink! podem ter vários construtores:

#[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-- */
    }
}

Mapeamento

O ink! também fornece um tipo de armazenamento chamado Mapping. Você pode ler mais sobre ele .

Lunes Tipos

Enum

Enum também pode ser usado como um tipo de dado. Sua utilização está presente no exemplo na seção "".

Struct

Observe que se você tiver um contrato cujo armazenamento contém Mappings, você precisará usar ink_lang::utils::initialize_contract em seu construtor. Consulte a do para obter mais detalhes.

🖥️
📑
🪄
👨‍🚀
​
Parity Codec
Lunes
​
ink_prelude
​
aqui
​
​
Struct
​
documentação
Mapping