diff --git a/docs/CAPABILITIES.md b/docs/CAPABILITIES.md index e647274c85..fde6affe53 100644 --- a/docs/CAPABILITIES.md +++ b/docs/CAPABILITIES.md @@ -1,27 +1,19 @@ -# Capabilities - -Capabilities are a mechanism to negotiate functionality between a contract and -an environment (i.e. the chain that embeds cosmwasm-vm/[wasmvm]) in a very -primitive way. The contract defines required capabilities. The environment -defines it's capabilities. If the required capabilities are all available, the -contract can be used. Doing this check when the contract is first stored ensures -missing capabilities are detected early and not when a user tries to execute a -certain code path. - -## Origin and Disambiguation - -Before August 2022, we had two types of "features": app level features in the -CosmWasm VM and Cargo's build system features. In order to avoid the confusion, -the former have been renamed to capabilities. - -Capabilities can be implemented in any language that compiles to Wasm whereas -features are Rust build system specific. - -## Required capabilities - -The contract defines required capabilities using marker export functions that -take no arguments and return no value. The name of the export needs to start -with "requires\_" followed by the name of the capability. +# Overview +**Capabilities** in CosmosWasm are a fundamental concept, designed to facilitate the interaction between a smart contract and its operational environment (i.e., the blockchain implementing the cosmwasm-vm or [wasmvm]). This mechanism operates by matching the capabilities required by a contract with those offered by the environment. + +# The Essence of Capabilities +**Purpose:** They serve as a negotiation tool, ensuring that a contract only operates in an environment where all its necessary functionalities are present. +**Early Detection:** By verifying capabilities when a contract is first stored, any discrepancies or missing capabilities are identified early. This preemptive approach prevents potential runtime failures during execution. + +# Historical Context: Origin and Disambiguation +**Prior to August 2022:** The term "features" was used ambiguously to describe both app-level features in the CosmWasm VM and features in Cargo's build system. ++**Redefinition:** To mitigate this confusion, app-level features in the CosmWasm VM were renamed to "capabilities", distinguishing them from Cargo's build system features. ++**Language Independence:** Unlike Rust-specific features, capabilities can be implemented in any language that compiles to Wasm, broadening their applicability. + +# Defining Required Capabilities +## Implementation +**Marker Export Functions:** Contracts specify required capabilities using these functions, which have no arguments and return no value. +**Naming Convention:** The export name begins with "requires\_" followed by the capability name, establishing a clear and standardized method for declaration. An example of such markers in cosmwasm-std are those: diff --git a/docs/STORAGE_KEYS.md b/docs/STORAGE_KEYS.md index 52f7b5f44e..061bc43dbe 100644 --- a/docs/STORAGE_KEYS.md +++ b/docs/STORAGE_KEYS.md @@ -1,17 +1,21 @@ # Storage keys -CosmWasm provides a generic key value store to contract developers via the -`Storage` trait. This is powerful but the nature of low level byte operations -makes it hard to use for high level storage types. In this document we discuss -the foundations of storage key composition all the way up to cw-storage-plus. - -In a simple world, all you need is a `&[u8]` key which you can get e.g. using -`&17u64.to_be_bytes()`. This is an 8 bytes key with an encoded integer. But if -you have multiple data types in your contract, you want to prefix those keys in -order to avoid collisions. A simple concatenation is not sufficient because you -want to avoid collisions when part of the prefixes and part of the key overlap. -E.g. `b"keya" | b"x"` and `b"key" | b"ax"` (`|` denotes concatenation) must not -have the same binary representation. +CosmWasm introduces a versatile key-value store accessible to contract developers +through the `Storage` trait. This low-level byte operation-based system, while powerful, +can be challenging for managing high-level storage types. This documentation explores +the evolution of storage key composition in CosmWasm, leading up to the current +implementation in cw-storage-plus. + +# The Challenge of Key Composition + +The fundamental requirement for storage keys in CosmWasm is a `&[u8]` key, which +can be obtained from basic types like integers (e.g., `&17u64.to_be_bytes()`). +However, when handling various data types within a contract, it's crucial to +use prefixed keys to prevent data collisions. +Simple concatenation of keys is insufficient due to potential overlap issues. +For instance, `b"keya" | b"x"` and `b"key" | b"ax"` should not yield the same binary representation, where | denotes concatenation. + +# Evolution of Key Namespacing In the early days, multiple approaches of key namespacing were discussed and were documented here: https://github.com/webmaster128/key-namespacing. The "0x00 @@ -39,12 +43,11 @@ pub fn to_length_prefixed_nested(namespaces: &[&[u8]]) -> Vec fn concat(namespace: &[u8], key: &[u8]) -> Vec ``` -With the emerging cw-storage-plus we see two additions to that approach: +# Transition to `cw-storage-plus` +With the introduction of cw-storage-plus, there were significant enhancements: -1. Manually creating the namespace and concatenating it with `concat` makes no - sense anymore. Instead `namespace` and `key` are always provided and a - composed database key is created. -2. Using a multi component namespace becomes the norm. +1. **Simplified Key Composition:** The manual creation of namespaces followed by concatenation using concat was replaced by a more integrated approach, where namespace and key are provided together to create a composed database key. +2. **Multi-component Namespaces:** Using multiple components in a namespace became commonplace. This led to the following addition in cw-storage-plus: @@ -68,14 +71,10 @@ With the deprecation if cosmwasm-storage and the adoption of the system in cw-storage-plus, it is time to do a few changes to the Length-prefixed keys standard, without breaking existing users. -1. Remove the single component `to_length_prefixed` implementation and fully - commit to the multi-component version. This shifts focus from the recursive - implementation to the compatible iterative implementation. -2. Rename "namespaces" to just "namespace" and let one namespace have multiple - components. -3. Adopt the combined namespace + key encoder `namespaces_with_key` from - cw-storage-plus. -4. Add a decomposition implementation +1. **Removal of Single Component Implementation:** The `to_length_prefixed` single-component version will be deprecated in favor of the multi-component `to_length_prefixed_nested` approach. +2. **Terminology Adjustment:** The term "namespaces" will be simplified to "namespace", encompassing multiple components. +3. **Adoption of Combined Encoder:** The `namespaces_with_key` function from `cw-storage-plus` will be the standard for key encoding. +4. **Decomposition Feature:** Introduction of a feature to decompose keys for enhanced flexibility. Given the importance of Length-prefixed keys for the entire CosmWasm ecosystem, those implementations should be maintained in cosmwasm-std. The generic approach diff --git a/packages/std/src/addresses.rs b/packages/std/src/addresses.rs index c41ab4c8a0..8f9c20dc01 100644 --- a/packages/std/src/addresses.rs +++ b/packages/std/src/addresses.rs @@ -249,7 +249,8 @@ impl fmt::Display for CanonicalAddr { Ok(()) } } - +/// Errors related to the instantiation of contracts and generation of addresses. +/// Ensures the integrity and validity of newly created contracts. #[derive(Error, Debug, PartialEq, Eq)] pub enum Instantiate2AddressError { /// Checksum must be 32 bytes diff --git a/packages/std/src/deps.rs b/packages/std/src/deps.rs index cc7a4681ab..897789b666 100644 --- a/packages/std/src/deps.rs +++ b/packages/std/src/deps.rs @@ -15,13 +15,13 @@ pub struct OwnedDeps { pub querier: Q, pub custom_query_type: PhantomData, } - +/// A mutable version of `Deps` that allows changes to the dependencies. pub struct DepsMut<'a, C: CustomQuery = Empty> { pub storage: &'a mut dyn Storage, pub api: &'a dyn Api, pub querier: QuerierWrapper<'a, C>, } - +/// Represents dependencies required by a contract for execution, like storage and API access. #[derive(Clone)] pub struct Deps<'a, C: CustomQuery = Empty> { pub storage: &'a dyn Storage, diff --git a/packages/std/src/errors/recover_pubkey_error.rs b/packages/std/src/errors/recover_pubkey_error.rs index ac2b174a26..539338908e 100644 --- a/packages/std/src/errors/recover_pubkey_error.rs +++ b/packages/std/src/errors/recover_pubkey_error.rs @@ -4,7 +4,8 @@ use cosmwasm_crypto::CryptoError; use super::BT; use thiserror::Error; - +/// Errors encountered during the recovery of a public key. +/// Typically arises from operations involving signatures or encrypted data. #[derive(Error, Debug)] pub enum RecoverPubkeyError { #[error("Invalid hash format")] diff --git a/packages/std/src/errors/std_error.rs b/packages/std/src/errors/std_error.rs index 22bbe71f24..d6d6ab3cff 100644 --- a/packages/std/src/errors/std_error.rs +++ b/packages/std/src/errors/std_error.rs @@ -393,12 +393,12 @@ impl From for StdError { } } -/// The return type for init, execute and query. Since the error type cannot be serialized to JSON, -/// this is only available within the contract and its unit tests. -/// -/// The prefix "Std" means "the standard result within the standard library". This is not the only -/// result/error type in cosmwasm-std. +/// `StdResult` is typically used in scenarios where a function within the contract needs to return a result or indicate an error +/// that is specific to the contract's internal operations. Since the error component of `StdResult` is not meant for JSON serialization, +/// it should be used with caution when designing functions that interact with external systems or data formats. pub type StdResult = core::result::Result; +/// Indicates operations that are prone to overflow. +/// Used to mark numerical operations where overflow checks are necessary. #[derive(Error, Debug, PartialEq, Eq)] pub enum OverflowOperation { @@ -415,7 +415,7 @@ impl fmt::Display for OverflowOperation { write!(f, "{self:?}") } } - +/// An error struct used when a numeric operation results in an overflow. #[derive(Error, Debug, PartialEq, Eq)] #[error("Cannot {operation} with given operands")] pub struct OverflowError { @@ -449,7 +449,7 @@ impl ConversionOverflowError { } } } - +///An error struct used when a division operation in a contract attempts to divide by zero. #[derive(Error, Debug, Default, PartialEq, Eq)] #[error("Cannot divide by zero")] pub struct DivideByZeroError; @@ -468,7 +468,8 @@ pub enum DivisionError { #[error("Overflow in division")] Overflow, } - +/// Errors that occur when multiplying a value by a [Fraction](crate::Fraction) in a checked manner. +/// Ensures overflow safety in the operation. #[derive(Error, Debug, PartialEq, Eq)] pub enum CheckedMultiplyFractionError { #[error("{0}")] @@ -480,7 +481,8 @@ pub enum CheckedMultiplyFractionError { #[error("{0}")] Overflow(#[from] OverflowError), } - +/// Represents errors during safe multiplication of a number by a fraction. +/// Ensures accuracy and overflow prevention in calculations. #[derive(Error, Debug, PartialEq, Eq)] pub enum CheckedMultiplyRatioError { #[error("Denominator must not be zero")] @@ -489,7 +491,8 @@ pub enum CheckedMultiplyRatioError { #[error("Multiplication overflow")] Overflow, } - +/// Errors that occur when safely converting from a ratio type. +/// Ensures mathematical accuracy and prevents potential overflow issues. #[derive(Error, Debug, PartialEq, Eq)] pub enum CheckedFromRatioError { #[error("Denominator must not be zero")] @@ -506,7 +509,8 @@ pub struct RoundUpOverflowError; #[derive(Error, Debug, PartialEq, Eq)] #[error("Round down operation failed because of overflow")] pub struct RoundDownOverflowError; - +/// General errors related to operations with coins, +/// such as invalid amounts or unsupported denominations. #[derive(Error, Debug, PartialEq, Eq)] pub enum CoinsError { #[error("Duplicate denom")] @@ -518,7 +522,8 @@ impl From for StdError { Self::generic_err(format!("Creating Coins: {value}")) } } - +/// Errors encountered when parsing coin values from strings. +/// Ensures that coin strings are in the correct format and valid. #[derive(Error, Debug, PartialEq, Eq)] pub enum CoinFromStrError { #[error("Missing denominator")] @@ -786,4 +791,4 @@ mod tests { err => panic!("Unexpected error: {err:?}"), } } -} +} \ No newline at end of file diff --git a/packages/std/src/hex_binary.rs b/packages/std/src/hex_binary.rs index aeb30b4c48..5f6eaab999 100644 --- a/packages/std/src/hex_binary.rs +++ b/packages/std/src/hex_binary.rs @@ -6,6 +6,7 @@ use serde::{de, ser, Deserialize, Deserializer, Serialize}; use crate::{Binary, StdError, StdResult}; +/// A wrapper around a vector (Vec) for hex-encoded binary data, supporting encoding and decoding operations. /// This is a wrapper around Vec to add hex de/serialization /// with serde. It also adds some helper methods to help encode inline. /// diff --git a/packages/std/src/ibc.rs b/packages/std/src/ibc.rs index 91fb7cf63a..170dad3fc6 100644 --- a/packages/std/src/ibc.rs +++ b/packages/std/src/ibc.rs @@ -13,8 +13,8 @@ use crate::results::{Attribute, CosmosMsg, Empty, Event, SubMsg}; use crate::serde::to_json_binary; use crate::timestamp::Timestamp; -/// These are messages in the IBC lifecycle. Only usable by IBC-enabled contracts -/// (contracts that directly speak the IBC protocol via 6 entry points) +/// Messages pertaining to the IBC lifecycle, specifically for contracts with IBC capabilities. +/// Manages cross-chain communications and other IBC protocol interactions. #[non_exhaustive] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] @@ -50,7 +50,7 @@ pub enum IbcMsg { /// Port is auto-assigned to the contract's IBC port CloseChannel { channel_id: String }, } - +///Details about an IBC endpoint, including its port and channel information. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct IbcEndpoint { pub port_id: String, @@ -147,9 +147,9 @@ impl IbcChannel { } } -/// IbcOrder defines if a channel is ORDERED or UNORDERED +/// Enumerates the ordering of messages in an IBC channel, such as ORDERED or UNORDERED. +/// Based on the IBC specifications for message sequencing. /// Values come from https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/ibc/core/channel/v1/channel.proto#L69-L80 -/// Naming comes from the protobuf files and go translations. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub enum IbcOrder { #[serde(rename = "ORDER_UNORDERED")] @@ -192,7 +192,7 @@ impl Ord for IbcTimeoutBlock { } } } - +///Struct representing an IBC packet, which contains data transferred across different blockchains. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[non_exhaustive] pub struct IbcPacket { @@ -225,7 +225,7 @@ impl IbcPacket { } } } - +///Represents an acknowledgement message in the IBC protocol. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[non_exhaustive] pub struct IbcAcknowledgement { @@ -246,7 +246,8 @@ impl IbcAcknowledgement { } } -/// The message that is passed into `ibc_channel_open` +/// Message used to establish a connection in an IBC channel. +/// Initiates the setup for cross-chain or inter-module communication. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum IbcChannelOpenMsg { @@ -304,12 +305,14 @@ impl From for IbcChannel { pub type IbcChannelOpenResponse = Option; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +///A response format for IBC channel open queries, providing details about the channel's status. pub struct Ibc3ChannelOpenResponse { /// We can set the channel version to a different one than we were called with pub version: String, } -/// The message that is passed into `ibc_channel_connect` +/// Message used to establish a connection in an IBC channel. +/// Initiates the setup for cross-chain or inter-module communication. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum IbcChannelConnectMsg { @@ -410,8 +413,7 @@ impl IbcPacketReceiveMsg { Self { packet, relayer } } } - -/// The message that is passed into `ibc_packet_ack` +/// Message format used when acknowledging the receipt of an IBC packet. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[non_exhaustive] pub struct IbcPacketAckMsg { @@ -454,7 +456,8 @@ impl IbcPacketTimeoutMsg { /// /// Callbacks that have return values (like receive_packet) /// or that cannot redispatch messages (like the handshake callbacks) -/// will use other Response types +/// will use other Response types. +/// A general response structure for IBC handler operations, used when a specific response format isn't required. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[non_exhaustive] pub struct IbcBasicResponse { diff --git a/packages/std/src/math/fraction.rs b/packages/std/src/math/fraction.rs index c13c746182..9fd12312be 100644 --- a/packages/std/src/math/fraction.rs +++ b/packages/std/src/math/fraction.rs @@ -31,7 +31,8 @@ impl + PartialEq> Fraction for (T, T) { } } } - +//Adds a function to a type that allows you to multiply instances of that type by a fraction. +//It's useful for calculations involving fractional multiplication. #[macro_export] macro_rules! impl_mul_fraction { ($Uint:ident) => { diff --git a/packages/std/src/math/signed_decimal.rs b/packages/std/src/math/signed_decimal.rs index 911e30293c..0621d8dc8b 100644 --- a/packages/std/src/math/signed_decimal.rs +++ b/packages/std/src/math/signed_decimal.rs @@ -26,7 +26,7 @@ use super::Int128; pub struct SignedDecimal(#[schemars(with = "String")] Int128); forward_ref_partial_eq!(SignedDecimal, SignedDecimal); - +///Similar to `SignedDecimal256RangeExceeded`, but for standard `SignedDecimal` operations. #[derive(Error, Debug, PartialEq, Eq)] #[error("SignedDecimal range exceeded")] pub struct SignedDecimalRangeExceeded; diff --git a/packages/std/src/math/signed_decimal_256.rs b/packages/std/src/math/signed_decimal_256.rs index 464346547d..19bf596de3 100644 --- a/packages/std/src/math/signed_decimal_256.rs +++ b/packages/std/src/math/signed_decimal_256.rs @@ -31,7 +31,7 @@ use super::Int256; pub struct SignedDecimal256(#[schemars(with = "String")] Int256); forward_ref_partial_eq!(SignedDecimal256, SignedDecimal256); - +/// Indicates an error when a SignedDecimal256 operation exceeds its range. #[derive(Error, Debug, PartialEq, Eq)] #[error("SignedDecimal256 range exceeded")] pub struct SignedDecimal256RangeExceeded; diff --git a/packages/std/src/never.rs b/packages/std/src/never.rs index 51173892f5..430ff88d66 100644 --- a/packages/std/src/never.rs +++ b/packages/std/src/never.rs @@ -1,17 +1,15 @@ -/// Never can never be instantiated. This can be used in places -/// where we want to ensure that no error is returned, such as -/// the `ibc_packet_receive` entry point. +/// `Never` represents a type that can never be instantiated. +/// It's primarily used in contexts where it's important to signify that an error cannot occur. +/// For example, it can be used in the `ibc_packet_receive` entry point to indicate +/// that no error is expected to be returned. /// -/// In contrast to `Empty`, this does not have a JSON schema -/// and cannot be used for message and query types. -/// -/// Once the ! type is stable, this is not needed anymore. -/// See . -/// -/// ## Examples -/// -/// When using `Never` in a `Result`, we can unwrap in a type-safe way: +/// Unlike the `Empty` type, `Never` is distinct in that it doesn't have an associated JSON schema. +/// Consequently, it's not suitable for use in message or query types where JSON representation is required. /// +/// The existence of `Never` is a temporary necessity. It is anticipated to be deprecated +/// once the Rust `!` type, which represents a never type in the Rust language, becomes stable. +/// The stabilization of the `!` type is an ongoing discussion, which you can follow here: +/// . /// ``` /// use cosmwasm_std::Never; /// diff --git a/packages/std/src/query/bank.rs b/packages/std/src/query/bank.rs index d8ecb3baec..d4f64ede6c 100644 --- a/packages/std/src/query/bank.rs +++ b/packages/std/src/query/bank.rs @@ -8,7 +8,8 @@ use crate::PageRequest; use crate::{Binary, DenomMetadata}; use super::query_response::QueryResponseType; - +///Defines the types of queries that can be made to the bank module. +///This includes queries for account balances, transaction history, etc. #[non_exhaustive] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] @@ -34,7 +35,7 @@ pub enum BankQuery { #[cfg(feature = "cosmwasm_1_3")] AllDenomMetadata { pagination: Option }, } - +///A response format that provides information about the supply of a specific asset or token. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] #[non_exhaustive] @@ -50,6 +51,7 @@ impl QueryResponseType for SupplyResponse {} #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] +///This struct holds the response information for a balance query, detailing the amounts held. #[non_exhaustive] pub struct BalanceResponse { /// Always returns a Coin with the requested denom. @@ -63,6 +65,8 @@ impl QueryResponseType for BalanceResponse {} #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] +///A response structure that contains all balances for a query, +///typically used in balance-related requests. #[non_exhaustive] pub struct AllBalanceResponse { /// Returns all non-zero coins held by this account. @@ -76,6 +80,7 @@ impl QueryResponseType for AllBalanceResponse {} #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] #[non_exhaustive] +/// A response format that contains metadata for a specific denomination in a query. pub struct DenomMetadataResponse { /// The metadata for the queried denom. pub metadata: DenomMetadata, diff --git a/packages/std/src/query/distribution.rs b/packages/std/src/query/distribution.rs index 5dbdfec2e4..c5423deaaf 100644 --- a/packages/std/src/query/distribution.rs +++ b/packages/std/src/query/distribution.rs @@ -4,7 +4,8 @@ use serde::{Deserialize, Serialize}; use crate::{Addr, Decimal256}; use super::query_response::QueryResponseType; - +/// Query types for interacting with the distribution module. +/// Queries might include requests for reward information or distribution parameters. #[non_exhaustive] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] diff --git a/packages/std/src/query/ibc.rs b/packages/std/src/query/ibc.rs index 511c61274e..d9ad268e4d 100644 --- a/packages/std/src/query/ibc.rs +++ b/packages/std/src/query/ibc.rs @@ -29,7 +29,7 @@ pub enum IbcQuery { }, // TODO: Add more } - +/// Contains the response information for a query about a port ID in IBC. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[non_exhaustive] pub struct PortIdResponse { @@ -37,7 +37,7 @@ pub struct PortIdResponse { } impl_response_constructor!(PortIdResponse, port_id: String); - +///: A response format containing a list of IBC channels and their details. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[non_exhaustive] pub struct ListChannelsResponse { @@ -47,6 +47,7 @@ pub struct ListChannelsResponse { impl_response_constructor!(ListChannelsResponse, channels: Vec); #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +///Contains details about a channel, typically used in IBC (Inter-Blockchain Communication) queries. #[non_exhaustive] pub struct ChannelResponse { pub channel: Option, diff --git a/packages/std/src/query/mod.rs b/packages/std/src/query/mod.rs index a957574a89..3bd3461e0d 100644 --- a/packages/std/src/query/mod.rs +++ b/packages/std/src/query/mod.rs @@ -36,7 +36,8 @@ pub use distribution::*; pub use ibc::*; pub use staking::*; pub use wasm::*; - +/// Enumerates different types of query requests. +/// Facilitates data retrieval from various modules or contracts in a structured manner. #[non_exhaustive] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] @@ -63,7 +64,6 @@ pub enum QueryRequest { Ibc(IbcQuery), Wasm(WasmQuery), } - /// A trait that is required to avoid conflicts with other query types like BankQuery and WasmQuery /// in generic implementations. /// You need to implement it in your custom query type. diff --git a/packages/std/src/query/staking.rs b/packages/std/src/query/staking.rs index b8104b8f12..ad4f7be018 100644 --- a/packages/std/src/query/staking.rs +++ b/packages/std/src/query/staking.rs @@ -4,7 +4,8 @@ use serde::{Deserialize, Serialize}; use crate::{Addr, Coin, Decimal}; use super::query_response::QueryResponseType; - +/// Query types for interacting with the staking module. +/// Includes queries for delegation status and staking rewards. #[non_exhaustive] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] @@ -99,6 +100,7 @@ impl_response_constructor!(DelegationResponse, delegation: Option = ContractResult::Err(error_msg); /// assert_eq!(to_vec(&result).unwrap(), br#"{"error":"Something went wrong"}"#); /// ``` +/// The final result type for contract calls (init/execute/migrate). +/// Used by the VM to differentiate between successful and failed executions. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ContractResult { diff --git a/packages/std/src/results/cosmos_msg.rs b/packages/std/src/results/cosmos_msg.rs index 9c60c25bbf..bf553e9099 100644 --- a/packages/std/src/results/cosmos_msg.rs +++ b/packages/std/src/results/cosmos_msg.rs @@ -19,7 +19,8 @@ use super::Empty; pub trait CustomMsg: Serialize + Clone + fmt::Debug + PartialEq + JsonSchema {} impl CustomMsg for Empty {} - +/// Enumerates the various message types within the Cosmos ecosystem. +/// Covers a range of transaction and operation types. #[non_exhaustive] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] @@ -41,7 +42,8 @@ pub enum CosmosMsg { Gov(GovMsg), } -/// The message types of the bank module. +/// Represents the different types of messages processed by the bank module. +/// These messages could include actions like transfers and account updates. /// /// See https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/bank/v1beta1/tx.proto #[non_exhaustive] @@ -62,7 +64,7 @@ pub enum BankMsg { Burn { amount: Vec }, } -/// The message types of the staking module. +/// Message types for the staking module, covering actions like delegation and reward collection. /// /// See https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/staking/v1beta1/tx.proto #[cfg(feature = "staking")] @@ -85,7 +87,8 @@ pub enum StakingMsg { }, } -/// The message types of the distribution module. +/// Defines the message types used within the distribution module. +/// These messages typically involve operations like reward distribution. /// /// See https://github.com/cosmos/cosmos-sdk/blob/v0.42.4/proto/cosmos/distribution/v1beta1/tx.proto #[cfg(feature = "staking")] @@ -291,6 +294,8 @@ pub enum WasmMsg { /// })) /// } /// ``` +/// Message types for interacting with the governance module. +/// Allows contracts to cast votes and participate in governance processes. #[cfg(feature = "stargate")] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] diff --git a/packages/std/src/results/empty.rs b/packages/std/src/results/empty.rs index 91e3b581bf..d75a60a99f 100644 --- a/packages/std/src/results/empty.rs +++ b/packages/std/src/results/empty.rs @@ -8,6 +8,7 @@ use serde::{Deserialize, Serialize}; /// contains no meaningful data. Previously we used enums without cases, /// but those cannot represented as valid JSON Schema (https://github.com/CosmWasm/cosmwasm/issues/451) #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, Default)] +///An error struct used when a division operation in a contract attempts to divide by zero. pub struct Empty {} #[cfg(test)] diff --git a/packages/std/src/results/events.rs b/packages/std/src/results/events.rs index 51eb7ace00..469a1930f0 100644 --- a/packages/std/src/results/events.rs +++ b/packages/std/src/results/events.rs @@ -13,6 +13,7 @@ use crate::forward_ref_partial_eq; /// [*Cosmos SDK* StringEvent]: https://github.com/cosmos/cosmos-sdk/blob/v0.42.5/proto/cosmos/base/abci/v1beta1/abci.proto#L56-L70 #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[non_exhaustive] +///Represents a full event in the Cosmos SDK, used for logging and tracking contract activities. pub struct Event { /// The event type. This is renamed to "ty" because "type" is reserved in Rust. This sucks, we know. #[serde(rename = "type")] diff --git a/packages/std/src/results/submessages.rs b/packages/std/src/results/submessages.rs index 5d58e87d2c..dbbdf6ffab 100644 --- a/packages/std/src/results/submessages.rs +++ b/packages/std/src/results/submessages.rs @@ -5,9 +5,8 @@ use crate::Binary; use super::{CosmosMsg, Empty, Event}; -/// Use this to define when the contract gets a response callback. -/// If you only need it for errors or success you can select just those in order -/// to save gas. +/// Specifies when a contract receives a callback response. +/// Useful for optimizing gas usage and tailoring response handling. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum ReplyOn { diff --git a/packages/std/src/storage.rs b/packages/std/src/storage.rs index 26d7f710d2..fc26129050 100644 --- a/packages/std/src/storage.rs +++ b/packages/std/src/storage.rs @@ -8,7 +8,7 @@ use core::ops::{Bound, RangeBounds}; #[cfg(feature = "iterator")] use crate::iterator::{Order, Record}; use crate::traits::Storage; - +///Represents a storage mechanism that exists only in memory (not persisted). #[derive(Default)] pub struct MemoryStorage { data: BTreeMap, Vec>, diff --git a/packages/std/src/traits.rs b/packages/std/src/traits.rs index 2ddc669add..09afd07549 100644 --- a/packages/std/src/traits.rs +++ b/packages/std/src/traits.rs @@ -194,7 +194,7 @@ pub trait Querier { /// helper methods fn raw_query(&self, bin_request: &[u8]) -> QuerierResult; } - +/// A wrapper struct that enables querying blockchain state from within a contract. #[derive(Clone)] pub struct QuerierWrapper<'a, C: CustomQuery = Empty> { querier: &'a dyn Querier, diff --git a/packages/std/src/types.rs b/packages/std/src/types.rs index 782ad1e726..44d0bf696b 100644 --- a/packages/std/src/types.rs +++ b/packages/std/src/types.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use crate::addresses::Addr; use crate::coin::Coin; use crate::timestamp::Timestamp; - +///Holds the environmental information of the contract's execution context, like block info and transaction details. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct Env { pub block: BlockInfo, @@ -14,7 +14,7 @@ pub struct Env { pub transaction: Option, pub contract: ContractInfo, } - +/// Contains information about a transaction, like its ID and other relevant data. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct TransactionInfo { /// The position of this transaction in the block. The first @@ -25,7 +25,7 @@ pub struct TransactionInfo { /// pub index: u32, } - +/// Represents information about a specific blockchain block, such as its height, timestamp, and other relevant data. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct BlockInfo { /// The height of a block is the number of blocks preceding it in the blockchain. @@ -104,7 +104,7 @@ pub struct MessageInfo { /// is executed such that the new balance is visible during contract execution. pub funds: Vec, } - +///Stores information about a smart contract, like its creator, admin, and other relevant details. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct ContractInfo { pub address: Addr,