diff --git a/.circleci/config.yml b/.circleci/config.yml index 3c01ff12e9..51cf2b8487 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -348,29 +348,40 @@ jobs: name: Add wasm32 target command: rustup target add wasm32-unknown-unknown && rustup target list --installed - run: - name: Build library for native target (no features) + name: Add no_std target + command: rustup target add thumbv7em-none-eabi && rustup target list --installed + - run: + name: Build library for no_std target + working_directory: ~/project/packages/std + command: cargo build --locked --no-default-features --target thumbv7em-none-eabi + - run: + name: Build library for native target (only "std" feature) + working_directory: ~/project/packages/std + command: cargo build --locked --no-default-features --features std + - run: + name: Build library for wasm target (only "std" feature) working_directory: ~/project/packages/std - command: cargo build --locked --no-default-features + command: cargo wasm --locked --no-default-features --features std - run: - name: Build library for wasm target (no features) + name: Run unit tests (only "std" feature) working_directory: ~/project/packages/std - command: cargo wasm --locked --no-default-features + command: cargo test --locked --no-default-features --features std - run: - name: Run unit tests (no features) + name: Build library for no_std target (all features "no_std") working_directory: ~/project/packages/std - command: cargo test --locked --no-default-features + command: cargo build --locked --no-default-features --features abort,iterator,staking,stargate,cosmwasm_1_1 --target thumbv7em-none-eabi - run: name: Build library for native target (all features) working_directory: ~/project/packages/std - command: cargo build --locked --features abort,iterator,staking,stargate,cosmwasm_1_2 + command: cargo build --locked --features abort,iterator,staking,stargate,std,cosmwasm_1_2 - run: name: Build library for wasm target (all features) working_directory: ~/project/packages/std - command: cargo wasm --locked --features abort,iterator,staking,stargate,cosmwasm_1_2 + command: cargo wasm --locked --features abort,iterator,staking,stargate,std,cosmwasm_1_2 - run: name: Run unit tests (all features) working_directory: ~/project/packages/std - command: cargo test --locked --features abort,iterator,staking,stargate,cosmwasm_1_2 + command: cargo test --locked --features abort,iterator,staking,stargate,std,cosmwasm_1_2 - save_cache: paths: - /usr/local/cargo/registry diff --git a/CHANGELOG.md b/CHANGELOG.md index ea5f0b20d1..bb915670c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -117,8 +117,12 @@ and this project adheres to `CanonicalAddr` ([#1463]). - cosmwasm-std: Implement `PartialEq` between `CanonicalAddr` and `HexBinary`/`Binary` ([#1463]). +- cosmwasm-std: Add `std` feature to support `no_std` if this feature is not + enabled ([#1483]). +- cosmwasm-std: Add `std` feature to default features ([#1483]). [#1463]: https://github.com/CosmWasm/cosmwasm/pull/1463 +[#1483]: https://github.com/CosmWasm/cosmwasm/pull/1483 ### Changed diff --git a/Cargo.lock b/Cargo.lock index eae3adcab8..0a22a960a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -185,9 +185,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.19" +version = "0.4.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" +checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f" dependencies = [ "num-integer", "num-traits", diff --git a/contracts/cyberpunk/Cargo.toml b/contracts/cyberpunk/Cargo.toml index 32f43bf413..9db2e485f8 100644 --- a/contracts/cyberpunk/Cargo.toml +++ b/contracts/cyberpunk/Cargo.toml @@ -30,7 +30,7 @@ backtraces = ["cosmwasm-std/backtraces", "cosmwasm-vm/backtraces"] [dependencies] cosmwasm-schema = { path = "../../packages/schema" } -cosmwasm-std = { path = "../../packages/std", default-features = false, features = ["abort"] } +cosmwasm-std = { path = "../../packages/std", default-features = false, features = ["abort", "std"] } rust-argon2 = "0.8" thiserror = "1.0.26" diff --git a/contracts/hackatom/Cargo.toml b/contracts/hackatom/Cargo.toml index fa1b8ccf7d..bcbc7694d5 100644 --- a/contracts/hackatom/Cargo.toml +++ b/contracts/hackatom/Cargo.toml @@ -32,7 +32,7 @@ backtraces = ["cosmwasm-std/backtraces", "cosmwasm-vm/backtraces"] [dependencies] cosmwasm-schema = { path = "../../packages/schema" } -cosmwasm-std = { path = "../../packages/std", default-features = false, features = ["abort"] } +cosmwasm-std = { path = "../../packages/std", default-features = false, features = ["abort", "std"] } schemars = "0.8.3" serde = { version = "1.0.103", default-features = false, features = ["derive"] } sha2 = "0.10" diff --git a/contracts/reflect/Cargo.toml b/contracts/reflect/Cargo.toml index c331845ac1..199c3edaae 100644 --- a/contracts/reflect/Cargo.toml +++ b/contracts/reflect/Cargo.toml @@ -34,7 +34,7 @@ backtraces = ["cosmwasm-std/backtraces", "cosmwasm-vm/backtraces"] [dependencies] cosmwasm-schema = { path = "../../packages/schema" } -cosmwasm-std = { path = "../../packages/std", default-features = false, features = ["staking", "stargate", "cosmwasm_1_1"] } +cosmwasm-std = { path = "../../packages/std", default-features = false, features = ["staking", "stargate", "cosmwasm_1_1", "std"] } cosmwasm-storage = { path = "../../packages/storage", default-features = false } schemars = "0.8.3" serde = { version = "=1.0.103", default-features = false, features = ["derive"] } diff --git a/contracts/staking/Cargo.toml b/contracts/staking/Cargo.toml index 2cb5e43fa8..c0b3f3d1d6 100644 --- a/contracts/staking/Cargo.toml +++ b/contracts/staking/Cargo.toml @@ -33,7 +33,7 @@ backtraces = ["cosmwasm-std/backtraces", "cosmwasm-vm/backtraces"] [dependencies] cosmwasm-schema = { path = "../../packages/schema" } -cosmwasm-std = { path = "../../packages/std", default-features = false, features = ["staking"] } +cosmwasm-std = { path = "../../packages/std", default-features = false, features = ["staking", "std"] } cosmwasm-storage = { path = "../../packages/storage", default-features = false } schemars = "0.8.3" serde = { version = "1.0.103", default-features = false, features = ["derive"] } diff --git a/packages/std/Cargo.toml b/packages/std/Cargo.toml index 831b45ae22..baa3a6f95e 100644 --- a/packages/std/Cargo.toml +++ b/packages/std/Cargo.toml @@ -9,10 +9,10 @@ license = "Apache-2.0" readme = "README.md" [package.metadata.docs.rs] -features = ["abort", "stargate", "staking", "ibc3", "cosmwasm_1_2"] +features = ["abort", "std", "stargate", "staking", "ibc3", "cosmwasm_1_2"] [features] -default = ["iterator", "abort"] +default = ["std", "iterator", "abort"] abort = [] # iterator allows us to iterate over all DB items in a given range # optional as some merkle stores (like tries) don't support this @@ -39,22 +39,23 @@ cosmwasm_1_1 = [] # This feature makes `GovMsg::VoteWeighted` available for the contract to call, but requires # the host blockchain to run CosmWasm `1.2.0` or higher. cosmwasm_1_2 = ["cosmwasm_1_1"] +std = ["forward_ref", "schemars", "serde-json-wasm", "thiserror", "cosmwasm-crypto"] [dependencies] -base64 = "0.13.0" +base64 = { version = "0.13.0", default-features = false, features = ["alloc"] } cosmwasm-derive = { path = "../derive", version = "1.2.0" } -derivative = "2" -forward_ref = "1" -hex = "0.4" -schemars = "0.8.3" -sha2 = "0.10.3" +derivative = { version = "2", features = ["use_core"] } +forward_ref = { version = "1", optional = true } +hex = { version = "0.4", default-features = false, features = ["alloc"] } +schemars = { version = "0.8.3", optional = true } +sha2 = { version = "0.10.3", default-features = false } serde = { version = "1.0.103", default-features = false, features = ["derive", "alloc"] } -serde-json-wasm = { version = "0.5.0" } -thiserror = "1.0.26" -uint = "0.9.3" +serde-json-wasm = { version = "0.5.0", optional = true } +thiserror = { version = "1.0.26", optional = true } +uint = { version = "0.9.3", default-features = false } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -cosmwasm-crypto = { path = "../crypto", version = "1.2.0" } +cosmwasm-crypto = { path = "../crypto", version = "1.2.0", optional = true } [dev-dependencies] cosmwasm-schema = { path = "../schema" } diff --git a/packages/std/examples/schema.rs b/packages/std/examples/schema.rs new file mode 100644 index 0000000000..25778b7eaa --- /dev/null +++ b/packages/std/examples/schema.rs @@ -0,0 +1,23 @@ +#[cfg(feature = "std")] +use { + cosmwasm_schema::{export_schema, export_schema_with_title, remove_schemas, schema_for}, + cosmwasm_std::{BlockInfo, CosmosMsg, Empty, QueryRequest, Timestamp}, + std::env::current_dir, + std::fs::create_dir_all, +}; + +#[cfg(feature = "std")] +fn main() { + let mut out_dir = current_dir().unwrap(); + out_dir.push("schema"); + create_dir_all(&out_dir).unwrap(); + remove_schemas(&out_dir).unwrap(); + + export_schema(&schema_for!(BlockInfo), &out_dir); + export_schema(&schema_for!(Timestamp), &out_dir); + export_schema_with_title(&schema_for!(CosmosMsg), &out_dir, "CosmosMsg"); + export_schema_with_title(&schema_for!(QueryRequest), &out_dir, "QueryRequest"); +} + +#[cfg(not(feature = "std"))] +fn main() {} diff --git a/packages/std/src/addresses.rs b/packages/std/src/addresses.rs index 39a4719291..283abf90d5 100644 --- a/packages/std/src/addresses.rs +++ b/packages/std/src/addresses.rs @@ -1,13 +1,13 @@ -use schemars::JsonSchema; +use alloc::borrow::Cow; +use alloc::fmt; +use alloc::string::String; +use alloc::vec::Vec; +use core::ops::Deref; use serde::{Deserialize, Serialize}; use sha2::{ digest::{Digest, Update}, Sha256, }; -use std::borrow::Cow; -use std::fmt; -use std::ops::Deref; -use thiserror::Error; use crate::{binary::Binary, HexBinary}; @@ -27,9 +27,8 @@ use crate::{binary::Binary, HexBinary}; /// This type is immutable. If you really need to mutate it (Really? Are you sure?), create /// a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` /// instance. -#[derive( - Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, JsonSchema, -)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Addr(String); impl Addr { @@ -155,7 +154,8 @@ impl<'a> From<&'a Addr> for Cow<'a, Addr> { /// addition to that there are many unsafe ways to convert any binary data into an instance. /// So the type shoud be treated as a marker to express the intended data type, not as /// a validity guarantee of any sort. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] pub struct CanonicalAddr(pub Binary); /// Implement `CanonicalAddr == Binary` @@ -276,7 +276,8 @@ impl fmt::Display for CanonicalAddr { } } -#[derive(Error, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug, PartialEq, Eq)] pub enum Instantiate2AddressError { /// Checksum must be 32 bytes InvalidChecksumLength, @@ -383,9 +384,14 @@ fn hash(ty: &str, key: &[u8]) -> Vec { mod tests { use super::*; use crate::HexBinary; + use alloc::string::ToString; + use alloc::vec::Vec; use hex_literal::hex; + #[cfg(feature = "std")] use std::collections::hash_map::DefaultHasher; + #[cfg(feature = "std")] use std::collections::HashSet; + #[cfg(feature = "std")] use std::hash::{Hash, Hasher}; #[test] @@ -623,6 +629,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn canonical_addr_implements_hash() { let alice1 = CanonicalAddr::from([0, 187, 61, 11, 250, 0]); let mut hasher = DefaultHasher::new(); @@ -645,6 +652,7 @@ mod tests { /// This requires Hash and Eq to be implemented #[test] + #[cfg(feature = "std")] fn canonical_addr_can_be_used_in_hash_set() { let alice1 = CanonicalAddr::from([0, 187, 61, 11, 250, 0]); let alice2 = CanonicalAddr::from([0, 187, 61, 11, 250, 0]); diff --git a/packages/std/src/assertions.rs b/packages/std/src/assertions.rs index bc67312b71..fb02e26ab9 100644 --- a/packages/std/src/assertions.rs +++ b/packages/std/src/assertions.rs @@ -30,7 +30,7 @@ macro_rules! ensure { ($cond:expr, $e:expr) => { if !($cond) { - return Err(std::convert::From::from($e)); + return Err(core::convert::From::from($e)); } }; } @@ -68,7 +68,7 @@ macro_rules! ensure_eq { ($a:expr, $b:expr, $e:expr) => { // Not implemented via `ensure!` because the caller would have to import both macros. if !($a == $b) { - return Err(std::convert::From::from($e)); + return Err(core::convert::From::from($e)); } }; } @@ -100,7 +100,7 @@ macro_rules! ensure_ne { ($a:expr, $b:expr, $e:expr) => { // Not implemented via `ensure!` because the caller would have to import both macros. if !($a != $b) { - return Err(std::convert::From::from($e)); + return Err(core::convert::From::from($e)); } }; } diff --git a/packages/std/src/binary.rs b/packages/std/src/binary.rs index 4e69b0ff20..bed6fc62e9 100644 --- a/packages/std/src/binary.rs +++ b/packages/std/src/binary.rs @@ -1,7 +1,7 @@ -use std::fmt; -use std::ops::Deref; - -use schemars::JsonSchema; +use alloc::fmt; +use alloc::string::String; +use alloc::vec::Vec; +use core::ops::Deref; use serde::{de, ser, Deserialize, Deserializer, Serialize}; use crate::errors::{StdError, StdResult}; @@ -11,8 +11,9 @@ use crate::errors::{StdError, StdResult}; /// /// This is only needed as serde-json-{core,wasm} has a horrible encoding for Vec. /// See also . -#[derive(Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, JsonSchema)] -pub struct Binary(#[schemars(with = "String")] pub Vec); +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Binary(#[cfg_attr(feature = "std", schemars(with = "String"))] pub Vec); impl Binary { /// take an (untrusted) string and decode it into bytes. @@ -240,8 +241,11 @@ mod tests { use super::*; use crate::errors::StdError; use crate::serde::{from_slice, to_vec}; + #[cfg(feature = "std")] use std::collections::hash_map::DefaultHasher; + #[cfg(feature = "std")] use std::collections::HashSet; + #[cfg(feature = "std")] use std::hash::{Hash, Hasher}; #[test] @@ -504,6 +508,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn binary_implements_as_ref() { // Can use as_ref (this we already get via the Deref implementation) let data = Binary(vec![7u8, 35, 49, 101, 0, 255]); @@ -532,6 +537,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn binary_implements_hash() { let a1 = Binary::from([0, 187, 61, 11, 250, 0]); let mut hasher = DefaultHasher::new(); @@ -554,6 +560,7 @@ mod tests { /// This requires Hash and Eq to be implemented #[test] + #[cfg(feature = "std")] fn binary_can_be_used_in_hash_set() { let a1 = Binary::from([0, 187, 61, 11, 250, 0]); let a2 = Binary::from([0, 187, 61, 11, 250, 0]); diff --git a/packages/std/src/coin.rs b/packages/std/src/coin.rs index 289911deef..32ad4f2eac 100644 --- a/packages/std/src/coin.rs +++ b/packages/std/src/coin.rs @@ -1,10 +1,12 @@ -use schemars::JsonSchema; +use alloc::fmt; +use alloc::string::String; +use alloc::vec::Vec; use serde::{Deserialize, Serialize}; -use std::fmt; use crate::math::Uint128; -#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq)] pub struct Coin { pub denom: String, pub amount: Uint128, @@ -86,6 +88,7 @@ pub fn has_coins(coins: &[Coin], required: &Coin) -> bool { #[cfg(test)] mod tests { use super::*; + use alloc::string::ToString; #[test] fn coin_implements_display() { diff --git a/packages/std/src/deps.rs b/packages/std/src/deps.rs index 4d9a9ecdce..6aa8d543ce 100644 --- a/packages/std/src/deps.rs +++ b/packages/std/src/deps.rs @@ -1,4 +1,6 @@ -use std::marker::PhantomData; +#![cfg(feature = "std")] + +use core::marker::PhantomData; use crate::query::CustomQuery; use crate::results::Empty; diff --git a/packages/std/src/errors/recover_pubkey_error.rs b/packages/std/src/errors/recover_pubkey_error.rs index 75af03a7ca..41f8373da3 100644 --- a/packages/std/src/errors/recover_pubkey_error.rs +++ b/packages/std/src/errors/recover_pubkey_error.rs @@ -1,22 +1,24 @@ -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(not(target_arch = "wasm32"), feature = "std"))] use cosmwasm_crypto::CryptoError; #[cfg(feature = "backtraces")] use std::backtrace::Backtrace; -use std::fmt::Debug; -use thiserror::Error; -#[derive(Error, Debug)] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug)] pub enum RecoverPubkeyError { - #[error("Invalid hash format")] + #[cfg_attr(feature = "std", error("Invalid hash format"))] InvalidHashFormat, - #[error("Invalid signature format")] + #[cfg_attr(feature = "std", error("Invalid signature format"))] InvalidSignatureFormat, - #[error("Invalid recovery parameter. Supported values: 0 and 1.")] + #[cfg_attr( + feature = "std", + error("Invalid recovery parameter. Supported values: 0 and 1.") + )] InvalidRecoveryParam, - #[error("Unknown error: {error_code}")] + #[cfg_attr(feature = "std", error("Unknown error: {error_code}"))] UnknownErr { error_code: u32, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, } @@ -25,7 +27,7 @@ impl RecoverPubkeyError { pub fn unknown_err(error_code: u32) -> Self { RecoverPubkeyError::UnknownErr { error_code, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -58,7 +60,7 @@ impl PartialEq for RecoverPubkeyError { } } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(not(target_arch = "wasm32"), feature = "std"))] impl From for RecoverPubkeyError { fn from(original: CryptoError) -> Self { match original { diff --git a/packages/std/src/errors/std_error.rs b/packages/std/src/errors/std_error.rs index 79b6a82f27..ac2ae9663f 100644 --- a/packages/std/src/errors/std_error.rs +++ b/packages/std/src/errors/std_error.rs @@ -1,7 +1,7 @@ -#[cfg(feature = "backtraces")] +use alloc::fmt; +use alloc::string::{String, ToString}; +#[cfg(all(feature = "backtraces", feature = "std"))] use std::backtrace::Backtrace; -use std::fmt; -use thiserror::Error; use crate::errors::{RecoverPubkeyError, VerificationError}; @@ -20,101 +20,112 @@ use crate::errors::{RecoverPubkeyError, VerificationError}; /// Checklist for adding a new error: /// - Add enum case /// - Add creator function in std_error_helpers.rs -#[derive(Error, Debug)] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug)] pub enum StdError { - #[error("Verification error: {source}")] + #[cfg_attr(feature = "std", error("Verification error: {source}"))] VerificationErr { source: VerificationError, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, - #[error("Recover pubkey error: {source}")] + #[cfg_attr(feature = "std", error("Recover pubkey error: {source}"))] RecoverPubkeyErr { source: RecoverPubkeyError, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, /// Whenever there is no specific error type available - #[error("Generic error: {msg}")] + #[cfg_attr(feature = "std", error("Generic error: {msg}"))] GenericErr { msg: String, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, - #[error("Invalid Base64 string: {msg}")] + #[cfg_attr(feature = "std", error("Invalid Base64 string: {msg}"))] InvalidBase64 { msg: String, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, - #[error("Invalid data size: expected={expected} actual={actual}")] + #[cfg_attr( + feature = "std", + error("Invalid data size: expected={expected} actual={actual}") + )] InvalidDataSize { expected: u64, actual: u64, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, - #[error("Invalid hex string: {msg}")] + #[cfg_attr(feature = "std", error("Invalid hex string: {msg}"))] InvalidHex { msg: String, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, /// Whenever UTF-8 bytes cannot be decoded into a unicode string, e.g. in String::from_utf8 or str::from_utf8. - #[error("Cannot decode UTF8 bytes into string: {msg}")] + #[cfg_attr(feature = "std", error("Cannot decode UTF8 bytes into string: {msg}"))] InvalidUtf8 { msg: String, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, - #[error("{kind} not found")] + #[cfg_attr(feature = "std", error("{kind} not found"))] NotFound { kind: String, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, - #[error("Error parsing into type {target_type}: {msg}")] + #[cfg_attr(feature = "std", error("Error parsing into type {target_type}: {msg}"))] ParseErr { /// the target type that was attempted target_type: String, msg: String, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, - #[error("Error serializing type {source_type}: {msg}")] + #[cfg_attr(feature = "std", error("Error serializing type {source_type}: {msg}"))] SerializeErr { /// the source type that was attempted source_type: String, msg: String, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, - #[error("Overflow: {source}")] + #[cfg_attr(feature = "std", error("Overflow: {source}"))] Overflow { source: OverflowError, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, - #[error("Divide by zero: {source}")] + #[cfg_attr(feature = "std", error("Divide by zero: {source}"))] DivideByZero { source: DivideByZeroError, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, - #[error("Conversion error: ")] + #[cfg_attr(feature = "std", error("Conversion error: "))] ConversionOverflow { - #[from] + #[cfg_attr(feature = "std", from)] source: ConversionOverflowError, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, } +#[cfg(not(feature = "std"))] +impl fmt::Display for StdError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self) + } +} + impl StdError { pub fn verification_err(source: VerificationError) -> Self { StdError::VerificationErr { source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -122,7 +133,7 @@ impl StdError { pub fn recover_pubkey_err(source: RecoverPubkeyError) -> Self { StdError::RecoverPubkeyErr { source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -130,7 +141,7 @@ impl StdError { pub fn generic_err(msg: impl Into) -> Self { StdError::GenericErr { msg: msg.into(), - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -138,7 +149,7 @@ impl StdError { pub fn invalid_base64(msg: impl ToString) -> Self { StdError::InvalidBase64 { msg: msg.to_string(), - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -148,7 +159,7 @@ impl StdError { // Cast is safe because usize is 32 or 64 bit large in all environments we support expected: expected as u64, actual: actual as u64, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -156,7 +167,7 @@ impl StdError { pub fn invalid_hex(msg: impl ToString) -> Self { StdError::InvalidHex { msg: msg.to_string(), - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -164,7 +175,7 @@ impl StdError { pub fn invalid_utf8(msg: impl ToString) -> Self { StdError::InvalidUtf8 { msg: msg.to_string(), - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -172,7 +183,7 @@ impl StdError { pub fn not_found(kind: impl Into) -> Self { StdError::NotFound { kind: kind.into(), - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -181,7 +192,7 @@ impl StdError { StdError::ParseErr { target_type: target.into(), msg: msg.to_string(), - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -190,7 +201,7 @@ impl StdError { StdError::SerializeErr { source_type: source.into(), msg: msg.to_string(), - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -198,7 +209,7 @@ impl StdError { pub fn overflow(source: OverflowError) -> Self { StdError::Overflow { source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -206,7 +217,7 @@ impl StdError { pub fn divide_by_zero(source: DivideByZeroError) -> Self { StdError::DivideByZero { source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -217,12 +228,12 @@ impl PartialEq for StdError { match self { StdError::VerificationErr { source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::VerificationErr { source: rhs_source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -233,12 +244,12 @@ impl PartialEq for StdError { } StdError::RecoverPubkeyErr { source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::RecoverPubkeyErr { source: rhs_source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -249,12 +260,12 @@ impl PartialEq for StdError { } StdError::GenericErr { msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::GenericErr { msg: rhs_msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -265,12 +276,12 @@ impl PartialEq for StdError { } StdError::InvalidBase64 { msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::InvalidBase64 { msg: rhs_msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -282,13 +293,13 @@ impl PartialEq for StdError { StdError::InvalidDataSize { expected, actual, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::InvalidDataSize { expected: rhs_expected, actual: rhs_actual, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -299,12 +310,12 @@ impl PartialEq for StdError { } StdError::InvalidHex { msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::InvalidHex { msg: rhs_msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -315,12 +326,12 @@ impl PartialEq for StdError { } StdError::InvalidUtf8 { msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::InvalidUtf8 { msg: rhs_msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -331,12 +342,12 @@ impl PartialEq for StdError { } StdError::NotFound { kind, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::NotFound { kind: rhs_kind, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -348,13 +359,13 @@ impl PartialEq for StdError { StdError::ParseErr { target_type, msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::ParseErr { target_type: rhs_target_type, msg: rhs_msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -366,13 +377,13 @@ impl PartialEq for StdError { StdError::SerializeErr { source_type, msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::SerializeErr { source_type: rhs_source_type, msg: rhs_msg, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -383,12 +394,12 @@ impl PartialEq for StdError { } StdError::Overflow { source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::Overflow { source: rhs_source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -399,12 +410,12 @@ impl PartialEq for StdError { } StdError::DivideByZero { source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::DivideByZero { source: rhs_source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -415,12 +426,12 @@ impl PartialEq for StdError { } StdError::ConversionOverflow { source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } => { if let StdError::ConversionOverflow { source: rhs_source, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: _, } = rhs { @@ -433,14 +444,14 @@ impl PartialEq for StdError { } } -impl From for StdError { - fn from(source: std::str::Utf8Error) -> Self { +impl From for StdError { + fn from(source: core::str::Utf8Error) -> Self { Self::invalid_utf8(source) } } -impl From for StdError { - fn from(source: std::string::FromUtf8Error) -> Self { +impl From for StdError { + fn from(source: alloc::string::FromUtf8Error) -> Self { Self::invalid_utf8(source) } } @@ -476,7 +487,8 @@ impl From for StdError { /// result/error type in cosmwasm-std. pub type StdResult = core::result::Result; -#[derive(Error, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug, PartialEq, Eq)] pub enum OverflowOperation { Add, Sub, @@ -492,8 +504,12 @@ impl fmt::Display for OverflowOperation { } } -#[derive(Error, Debug, PartialEq, Eq)] -#[error("Cannot {operation} with {operand1} and {operand2}")] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug, PartialEq, Eq)] +#[cfg_attr( + feature = "std", + error("Cannot {operation} with {operand1} and {operand2}") +)] pub struct OverflowError { pub operation: OverflowOperation, pub operand1: String, @@ -520,8 +536,12 @@ impl OverflowError { /// [`TryFrom`]: std::convert::TryFrom /// [`Uint256`]: crate::Uint256 /// [`Uint128`]: crate::Uint128 -#[derive(Error, Debug, PartialEq, Eq)] -#[error("Error converting {source_type} to {target_type} for {value}")] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug, PartialEq, Eq)] +#[cfg_attr( + feature = "std", + error("Error converting {source_type} to {target_type} for {value}") +)] pub struct ConversionOverflowError { pub source_type: &'static str, pub target_type: &'static str, @@ -542,8 +562,9 @@ impl ConversionOverflowError { } } -#[derive(Error, Debug, PartialEq, Eq)] -#[error("Cannot divide {operand} by zero")] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", error("Cannot devide {operand} by zero"))] pub struct DivideByZeroError { pub operand: String, } @@ -556,44 +577,69 @@ impl DivideByZeroError { } } -#[derive(Error, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug, PartialEq, Eq)] pub enum CheckedMultiplyFractionError { - #[error("{0}")] - DivideByZero(#[from] DivideByZeroError), + #[cfg_attr(feature = "std", error("{0}"))] + DivideByZero(DivideByZeroError), - #[error("{0}")] - ConversionOverflow(#[from] ConversionOverflowError), + #[cfg_attr(feature = "std", error("{0}"))] + ConversionOverflow(ConversionOverflowError), - #[error("{0}")] - Overflow(#[from] OverflowError), + #[cfg_attr(feature = "std", error("{0}"))] + Overflow(OverflowError), +} + +impl From for CheckedMultiplyFractionError { + fn from(e: DivideByZeroError) -> Self { + Self::DivideByZero(e) + } +} + +impl From for CheckedMultiplyFractionError { + fn from(e: ConversionOverflowError) -> Self { + Self::ConversionOverflow(e) + } +} + +impl From for CheckedMultiplyFractionError { + fn from(e: OverflowError) -> Self { + Self::Overflow(e) + } } -#[derive(Error, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug, PartialEq, Eq)] pub enum CheckedMultiplyRatioError { - #[error("Denominator must not be zero")] + #[cfg_attr(feature = "std", error("Denominator must not be zero"))] DivideByZero, - #[error("Multiplication overflow")] + #[cfg_attr(feature = "std", error("Multiplication overflow"))] Overflow, } -#[derive(Error, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug, PartialEq, Eq)] pub enum CheckedFromRatioError { - #[error("Denominator must not be zero")] + #[cfg_attr(feature = "std", error("Denominator must not be zero"))] DivideByZero, - #[error("Overflow")] + #[cfg_attr(feature = "std", error("Overflow"))] Overflow, } -#[derive(Error, Debug, PartialEq, Eq)] -#[error("Round up operation failed because of overflow")] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug, PartialEq, Eq)] +#[cfg_attr( + feature = "std", + error("Round up operation failed because of overflow") +)] pub struct RoundUpOverflowError; #[cfg(test)] mod tests { use super::*; - use std::str; + use core::str; // constructors @@ -810,7 +856,13 @@ mod tests { fn implements_display() { let error: StdError = StdError::from(OverflowError::new(OverflowOperation::Sub, 3, 5)); let embedded = format!("Display: {}", error); + #[cfg(feature = "std")] assert_eq!(embedded, "Display: Overflow: Cannot Sub with 3 and 5"); + #[cfg(not(feature = "std"))] + assert_eq!( + embedded, + "Display: Overflow { source: OverflowError { operation: Sub, operand1: \"3\", operand2: \"5\" } }" + ); } #[test] diff --git a/packages/std/src/errors/system_error.rs b/packages/std/src/errors/system_error.rs index d763f213c8..ba76d5bf92 100644 --- a/packages/std/src/errors/system_error.rs +++ b/packages/std/src/errors/system_error.rs @@ -1,4 +1,4 @@ -use schemars::JsonSchema; +use alloc::string::String; use serde::{Deserialize, Serialize}; use crate::Binary; @@ -12,7 +12,8 @@ use crate::Binary; /// /// Such errors are only created by the VM. The error type is defined in the standard library, to ensure /// the contract understands the error format without creating a dependency on cosmwasm-vm. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] #[non_exhaustive] pub enum SystemError { @@ -39,10 +40,11 @@ pub enum SystemError { }, } +#[cfg(feature = "std")] impl std::error::Error for SystemError {} -impl std::fmt::Display for SystemError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for SystemError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { SystemError::InvalidRequest { error, request } => write!( f, diff --git a/packages/std/src/errors/verification_error.rs b/packages/std/src/errors/verification_error.rs index 26786596e5..b00edda382 100644 --- a/packages/std/src/errors/verification_error.rs +++ b/packages/std/src/errors/verification_error.rs @@ -1,29 +1,31 @@ -#[cfg(feature = "backtraces")] +#[cfg(all(feature = "backtraces", feature = "std"))] use std::backtrace::Backtrace; -use std::fmt::Debug; -use thiserror::Error; -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(not(target_arch = "wasm32"), feature = "std"))] use cosmwasm_crypto::CryptoError; -#[derive(Error, Debug)] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug)] pub enum VerificationError { - #[error("Batch error")] + #[cfg_attr(feature = "std", error("Batch error"))] BatchErr, - #[error("Generic error")] + #[cfg_attr(feature = "std", error("Generic error"))] GenericErr, - #[error("Invalid hash format")] + #[cfg_attr(feature = "std", error("Invalid hash format"))] InvalidHashFormat, - #[error("Invalid signature format")] + #[cfg_attr(feature = "std", error("Invalid signature format"))] InvalidSignatureFormat, - #[error("Invalid public key format")] + #[cfg_attr(feature = "std", error("Invalid public key format"))] InvalidPubkeyFormat, - #[error("Invalid recovery parameter. Supported values: 0 and 1.")] + #[cfg_attr( + feature = "std", + error("Invalid recovery parameter. Supported values: 0 and 1.") + )] InvalidRecoveryParam, - #[error("Unknown error: {error_code}")] + #[cfg_attr(feature = "std", error("Unknown error: {error_code}"))] UnknownErr { error_code: u32, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace, }, } @@ -32,7 +34,7 @@ impl VerificationError { pub fn unknown_err(error_code: u32) -> Self { VerificationError::UnknownErr { error_code, - #[cfg(feature = "backtraces")] + #[cfg(all(feature = "backtraces", feature = "std"))] backtrace: Backtrace::capture(), } } @@ -70,7 +72,7 @@ impl PartialEq for VerificationError { } } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(not(target_arch = "wasm32"), feature = "std"))] impl From for VerificationError { fn from(original: CryptoError) -> Self { match original { diff --git a/packages/std/src/exports.rs b/packages/std/src/exports.rs index 5b4b30925c..b42e6dc75b 100644 --- a/packages/std/src/exports.rs +++ b/packages/std/src/exports.rs @@ -7,8 +7,11 @@ //! and `do_sudo` should be wrapped with a extern "C" entry point including //! the contract-specific function pointer. This is done via the `#[entry_point]` //! macro attribute from cosmwasm-derive. -use std::marker::PhantomData; -use std::vec::Vec; +#![cfg(feature = "std")] + +use alloc::string::ToString; +use alloc::vec::Vec; +use core::marker::PhantomData; use serde::de::DeserializeOwned; diff --git a/packages/std/src/hex_binary.rs b/packages/std/src/hex_binary.rs index fcbcc4c05b..13c841fc24 100644 --- a/packages/std/src/hex_binary.rs +++ b/packages/std/src/hex_binary.rs @@ -1,7 +1,7 @@ -use std::fmt; -use std::ops::Deref; - -use schemars::JsonSchema; +use alloc::fmt; +use alloc::string::String; +use alloc::vec::Vec; +use core::ops::Deref; use serde::{de, ser, Deserialize, Deserializer, Serialize}; use crate::{Binary, StdError, StdResult}; @@ -11,8 +11,9 @@ use crate::{Binary, StdError, StdResult}; /// /// This is similar to `cosmwasm_std::Binary` but uses hex. /// See also . -#[derive(Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, JsonSchema)] -pub struct HexBinary(#[schemars(with = "String")] Vec); +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct HexBinary(#[cfg_attr(feature = "std", schemars(with = "String"))] Vec); impl HexBinary { pub fn from_hex(input: &str) -> StdResult { @@ -248,8 +249,11 @@ mod tests { use super::*; use crate::{from_slice, to_vec, StdError}; + #[cfg(feature = "std")] use std::collections::hash_map::DefaultHasher; + #[cfg(feature = "std")] use std::collections::HashSet; + #[cfg(feature = "std")] use std::hash::{Hash, Hasher}; #[test] @@ -568,6 +572,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn hex_binary_implements_as_ref() { // Can use as_ref (this we already get via the Deref implementation) let data = HexBinary(vec![7u8, 35, 49, 101, 0, 255]); @@ -596,6 +601,7 @@ mod tests { } #[test] + #[cfg(feature = "std")] fn hex_binary_implements_hash() { let a1 = HexBinary::from([0, 187, 61, 11, 250, 0]); let mut hasher = DefaultHasher::new(); @@ -618,6 +624,7 @@ mod tests { /// This requires Hash and Eq to be implemented #[test] + #[cfg(feature = "std")] fn hex_binary_can_be_used_in_hash_set() { let a1 = HexBinary::from([0, 187, 61, 11, 250, 0]); let a2 = HexBinary::from([0, 187, 61, 11, 250, 0]); diff --git a/packages/std/src/ibc.rs b/packages/std/src/ibc.rs index 1ce06432a6..06c6eef4e3 100644 --- a/packages/std/src/ibc.rs +++ b/packages/std/src/ibc.rs @@ -2,23 +2,28 @@ // The CosmosMsg variants are defined in results/cosmos_msg.rs // The rest of the IBC related functionality is defined here -use schemars::JsonSchema; +use core::cmp::{Ord, Ordering, PartialOrd}; use serde::{Deserialize, Serialize}; -use std::cmp::{Ord, Ordering, PartialOrd}; #[cfg(feature = "ibc3")] use crate::addresses::Addr; use crate::binary::Binary; use crate::coin::Coin; +#[cfg(feature = "std")] use crate::errors::StdResult; use crate::results::{Attribute, CosmosMsg, Empty, Event, SubMsg}; +#[cfg(feature = "std")] use crate::serde::to_binary; use crate::timestamp::Timestamp; +use alloc::string::String; +use alloc::vec::Vec; + /// These are messages in the IBC lifecycle. Only usable by IBC-enabled contracts /// (contracts that directly speak the IBC protocol via 6 entry points) #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum IbcMsg { /// Sends bank tokens owned by the contract to the given address on another chain. @@ -51,7 +56,8 @@ pub enum IbcMsg { CloseChannel { channel_id: String }, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct IbcEndpoint { pub port_id: String, pub channel_id: String, @@ -60,7 +66,8 @@ pub struct IbcEndpoint { /// In IBC each package must set at least one type of timeout: /// the timestamp or the block height. Using this rather complex enum instead of /// two timeout fields we ensure that at least one timeout is set. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct IbcTimeout { // use private fields to enforce the use of constructors, which ensure that at least one is set @@ -115,7 +122,8 @@ impl From for IbcTimeout { /// IbcChannel defines all information on a channel. /// This is generally used in the hand-shake process, but can be queried directly. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IbcChannel { pub endpoint: IbcEndpoint, @@ -150,7 +158,8 @@ impl IbcChannel { /// IbcOrder defines if a channel is ORDERED or UNORDERED /// 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)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub enum IbcOrder { #[serde(rename = "ORDER_UNORDERED")] Unordered, @@ -162,7 +171,8 @@ pub enum IbcOrder { /// that can be compared against another Height for the purposes of updating and /// freezing clients. /// Ordering is (revision_number, timeout_height) -#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq)] pub struct IbcTimeoutBlock { /// the version that the client is currently on /// (eg. after reseting the chain this could increment 1 as height drops to 0) @@ -193,7 +203,8 @@ impl Ord for IbcTimeoutBlock { } } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IbcPacket { /// The raw data sent from the other side in the packet @@ -226,7 +237,8 @@ impl IbcPacket { } } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IbcAcknowledgement { pub data: Binary, @@ -239,6 +251,7 @@ impl IbcAcknowledgement { IbcAcknowledgement { data: data.into() } } + #[cfg(feature = "std")] pub fn encode_json(data: &impl Serialize) -> StdResult { Ok(IbcAcknowledgement { data: to_binary(data)?, @@ -247,7 +260,8 @@ impl IbcAcknowledgement { } /// The message that is passed into `ibc_channel_open` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum IbcChannelOpenMsg { /// The ChanOpenInit step from https://github.com/cosmos/ibc/tree/master/spec/core/ics-004-channel-and-packet-semantics#channel-lifecycle-management @@ -305,14 +319,15 @@ pub type IbcChannelOpenResponse = (); #[cfg(feature = "ibc3")] pub type IbcChannelOpenResponse = Option; -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] 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` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum IbcChannelConnectMsg { /// The ChanOpenAck step from https://github.com/cosmos/ibc/tree/master/spec/core/ics-004-channel-and-packet-semantics#channel-lifecycle-management @@ -364,7 +379,8 @@ impl From for IbcChannel { } /// The message that is passed into `ibc_channel_close` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum IbcChannelCloseMsg { /// The ChanCloseInit step from https://github.com/cosmos/ibc/tree/master/spec/core/ics-004-channel-and-packet-semantics#channel-lifecycle-management @@ -400,7 +416,8 @@ impl From for IbcChannel { } /// The message that is passed into `ibc_packet_receive` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IbcPacketReceiveMsg { pub packet: IbcPacket, @@ -421,7 +438,8 @@ impl IbcPacketReceiveMsg { } /// The message that is passed into `ibc_packet_ack` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IbcPacketAckMsg { pub acknowledgement: IbcAcknowledgement, @@ -454,7 +472,8 @@ impl IbcPacketAckMsg { } /// The message that is passed into `ibc_packet_timeout` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IbcPacketTimeoutMsg { pub packet: IbcPacket, @@ -481,7 +500,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 -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IbcBasicResponse { /// Optional list of messages to pass. These will be executed in order. @@ -623,7 +643,8 @@ impl IbcBasicResponse { // Where the acknowledgement bytes contain an encoded error message to be returned to // the calling chain. (Returning ContractResult::Err will abort processing of this packet // and not inform the calling chain). -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IbcReceiveResponse { /// The bytes we return to the contract that sent the packet. @@ -773,6 +794,7 @@ impl IbcReceiveResponse { #[cfg(test)] mod tests { use super::*; + use alloc::string::ToString; use serde_json_wasm::to_string; #[test] diff --git a/packages/std/src/imports.rs b/packages/std/src/imports.rs index f7438a9df0..758a17abd1 100644 --- a/packages/std/src/imports.rs +++ b/packages/std/src/imports.rs @@ -1,4 +1,10 @@ -use std::vec::Vec; +#![cfg(feature = "std")] + +#[cfg(feature = "iterator")] +use alloc::boxed::Box; +use alloc::string::String; +use alloc::string::ToString; +use alloc::vec::Vec; use crate::addresses::{Addr, CanonicalAddr}; use crate::errors::{RecoverPubkeyError, StdError, StdResult, SystemError, VerificationError}; diff --git a/packages/std/src/iterator.rs b/packages/std/src/iterator.rs index e747581606..9d15c7db96 100644 --- a/packages/std/src/iterator.rs +++ b/packages/std/src/iterator.rs @@ -1,3 +1,5 @@ +use alloc::vec::Vec; + use crate::errors::StdError; /// A record of a key-value storage that is created through an iterator API. diff --git a/packages/std/src/lib.rs b/packages/std/src/lib.rs index a15f0f4c62..154154bf9c 100644 --- a/packages/std/src/lib.rs +++ b/packages/std/src/lib.rs @@ -1,4 +1,5 @@ -#![cfg_attr(feature = "backtraces", feature(backtrace))] +#![cfg_attr(all(feature = "backtraces", feature = "std"), feature(backtrace))] +#![cfg_attr(not(feature = "std"), no_std)] // Exposed on all platforms @@ -26,9 +27,13 @@ mod timestamp; mod traits; mod types; +#[macro_use] +extern crate alloc; + pub use crate::addresses::{instantiate2_address, Addr, CanonicalAddr, Instantiate2AddressError}; pub use crate::binary::Binary; pub use crate::coin::{coin, coins, has_coins, Coin}; +#[cfg(feature = "std")] pub use crate::deps::{Deps, DepsMut, OwnedDeps}; pub use crate::errors::{ CheckedFromRatioError, CheckedMultiplyRatioError, ConversionOverflowError, DivideByZeroError, @@ -70,42 +75,46 @@ pub use crate::results::SubMsgExecutionResponse; #[cfg(all(feature = "stargate", feature = "cosmwasm_1_2"))] pub use crate::results::WeightedVoteOption; pub use crate::results::{ - attr, wasm_execute, wasm_instantiate, Attribute, BankMsg, ContractResult, CosmosMsg, CustomMsg, - Empty, Event, QueryResponse, Reply, ReplyOn, Response, SubMsg, SubMsgResponse, SubMsgResult, - SystemResult, WasmMsg, + attr, Attribute, BankMsg, ContractResult, CosmosMsg, CustomMsg, Empty, Event, QueryResponse, + Reply, ReplyOn, Response, SubMsg, SubMsgResponse, SubMsgResult, SystemResult, WasmMsg, }; +#[cfg(feature = "std")] +pub use crate::results::{wasm_execute, wasm_instantiate}; #[cfg(feature = "staking")] pub use crate::results::{DistributionMsg, StakingMsg}; #[cfg(feature = "stargate")] pub use crate::results::{GovMsg, VoteOption}; +#[cfg(feature = "std")] pub use crate::serde::{from_binary, from_slice, to_binary, to_vec}; +#[cfg(feature = "std")] pub use crate::storage::MemoryStorage; pub use crate::timestamp::Timestamp; +#[cfg(feature = "std")] pub use crate::traits::{Api, Querier, QuerierResult, QuerierWrapper, Storage}; pub use crate::types::{BlockInfo, ContractInfo, Env, MessageInfo, TransactionInfo}; // Exposed in wasm build only -#[cfg(target_arch = "wasm32")] +#[cfg(all(target_arch = "wasm32", feature = "std"))] mod exports; -#[cfg(target_arch = "wasm32")] +#[cfg(all(target_arch = "wasm32", feature = "std"))] mod imports; -#[cfg(target_arch = "wasm32")] +#[cfg(all(target_arch = "wasm32", feature = "std"))] mod memory; // Used by exports and imports only. This assumes pointers are 32 bit long, which makes it untestable on dev machines. -#[cfg(target_arch = "wasm32")] +#[cfg(all(target_arch = "wasm32", feature = "std"))] pub use crate::exports::{do_execute, do_instantiate, do_migrate, do_query, do_reply, do_sudo}; -#[cfg(all(feature = "stargate", target_arch = "wasm32"))] +#[cfg(all(feature = "stargate", target_arch = "wasm32", feature = "std"))] pub use crate::exports::{ do_ibc_channel_close, do_ibc_channel_connect, do_ibc_channel_open, do_ibc_packet_ack, do_ibc_packet_receive, do_ibc_packet_timeout, }; -#[cfg(target_arch = "wasm32")] +#[cfg(all(target_arch = "wasm32", feature = "std"))] pub use crate::imports::{ExternalApi, ExternalQuerier, ExternalStorage}; // Exposed for testing only // Both unit tests and integration tests are compiled to native code, so everything in here does not need to compile to Wasm. -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(not(target_arch = "wasm32"), feature = "std"))] pub mod testing; // Re-exports diff --git a/packages/std/src/math/decimal.rs b/packages/std/src/math/decimal.rs index a146c62b94..fd8de36352 100644 --- a/packages/std/src/math/decimal.rs +++ b/packages/std/src/math/decimal.rs @@ -1,11 +1,11 @@ +use alloc::fmt::{self, Write}; +use alloc::str::FromStr; +use alloc::string::ToString; +use core::cmp::Ordering; +use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Sub, SubAssign}; +#[cfg(feature = "std")] use forward_ref::{forward_ref_binop, forward_ref_op_assign}; -use schemars::JsonSchema; use serde::{de, ser, Deserialize, Deserializer, Serialize}; -use std::cmp::Ordering; -use std::fmt::{self, Write}; -use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Sub, SubAssign}; -use std::str::FromStr; -use thiserror::Error; use crate::errors::{ CheckedFromRatioError, CheckedMultiplyRatioError, DivideByZeroError, OverflowError, @@ -19,11 +19,13 @@ use super::{Uint128, Uint256}; /// A fixed-point decimal value with 18 fractional digits, i.e. Decimal(1_000_000_000_000_000_000) == 1.0 /// /// The greatest possible value that can be represented is 340282366920938463463.374607431768211455 (which is (2^128 - 1) / 10^18) -#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, JsonSchema)] -pub struct Decimal(#[schemars(with = "String")] Uint128); +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord)] +pub struct Decimal(#[cfg_attr(feature = "std", schemars(with = "String"))] Uint128); -#[derive(Error, Debug, PartialEq, Eq)] -#[error("Decimal range exceeded")] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", error("Decimal range exceeded"))] pub struct DecimalRangeExceeded; impl Decimal { @@ -470,6 +472,7 @@ impl Add for Decimal { Decimal(self.0 + other.0) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Add, add for Decimal, Decimal); impl AddAssign for Decimal { @@ -477,6 +480,7 @@ impl AddAssign for Decimal { *self = *self + rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl AddAssign, add_assign for Decimal, Decimal); impl Sub for Decimal { @@ -486,6 +490,7 @@ impl Sub for Decimal { Decimal(self.0 - other.0) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Sub, sub for Decimal, Decimal); impl SubAssign for Decimal { @@ -493,6 +498,7 @@ impl SubAssign for Decimal { *self = *self - rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl SubAssign, sub_assign for Decimal, Decimal); impl Mul for Decimal { @@ -513,6 +519,7 @@ impl Mul for Decimal { } } } +#[cfg(feature = "std")] forward_ref_binop!(impl Mul, mul for Decimal, Decimal); impl MulAssign for Decimal { @@ -520,6 +527,7 @@ impl MulAssign for Decimal { *self = *self * rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl MulAssign, mul_assign for Decimal, Decimal); /// Both d*u and u*d with d: Decimal and u: Uint128 returns an Uint128. There is no @@ -561,6 +569,7 @@ impl Div for Decimal { } } } +#[cfg(feature = "std")] forward_ref_binop!(impl Div, div for Decimal, Decimal); impl DivAssign for Decimal { @@ -568,6 +577,7 @@ impl DivAssign for Decimal { *self = *self / rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl DivAssign, div_assign for Decimal, Decimal); impl Div for Decimal { @@ -595,6 +605,7 @@ impl Rem for Decimal { Self(self.0.rem(rhs.0)) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Rem, rem for Decimal, Decimal); impl RemAssign for Decimal { @@ -602,9 +613,10 @@ impl RemAssign for Decimal { *self = *self % rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl RemAssign, rem_assign for Decimal, Decimal); -impl std::iter::Sum for Decimal +impl core::iter::Sum for Decimal where Self: Add, { @@ -669,6 +681,7 @@ impl PartialEq for &Decimal { mod tests { use super::*; use crate::{from_slice, to_vec}; + use alloc::vec::Vec; fn dec(input: &str) -> Decimal { Decimal::from_str(input).unwrap() diff --git a/packages/std/src/math/decimal256.rs b/packages/std/src/math/decimal256.rs index 2ae938e614..0b022481d9 100644 --- a/packages/std/src/math/decimal256.rs +++ b/packages/std/src/math/decimal256.rs @@ -1,11 +1,11 @@ +use alloc::fmt::{self, Write}; +use alloc::str::FromStr; +use alloc::string::ToString; +use core::cmp::Ordering; +use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Sub, SubAssign}; +#[cfg(feature = "std")] use forward_ref::{forward_ref_binop, forward_ref_op_assign}; -use schemars::JsonSchema; use serde::{de, ser, Deserialize, Deserializer, Serialize}; -use std::cmp::Ordering; -use std::fmt::{self, Write}; -use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Sub, SubAssign}; -use std::str::FromStr; -use thiserror::Error; use crate::errors::{ CheckedFromRatioError, CheckedMultiplyRatioError, DivideByZeroError, OverflowError, @@ -22,11 +22,13 @@ use super::Uint256; /// The greatest possible value that can be represented is /// 115792089237316195423570985008687907853269984665640564039457.584007913129639935 /// (which is (2^256 - 1) / 10^18) -#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, JsonSchema)] -pub struct Decimal256(#[schemars(with = "String")] Uint256); +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord)] +pub struct Decimal256(#[cfg_attr(feature = "std", schemars(with = "String"))] Uint256); -#[derive(Error, Debug, PartialEq, Eq)] -#[error("Decimal256 range exceeded")] +#[cfg_attr(feature = "std", derive(thiserror::Error))] +#[derive(Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", error("Decimal256 range exceeded"))] pub struct Decimal256RangeExceeded; impl Decimal256 { @@ -495,6 +497,7 @@ impl Add for Decimal256 { Self(self.0 + other.0) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Add, add for Decimal256, Decimal256); impl AddAssign for Decimal256 { @@ -502,6 +505,7 @@ impl AddAssign for Decimal256 { *self = *self + rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl AddAssign, add_assign for Decimal256, Decimal256); impl Sub for Decimal256 { @@ -511,6 +515,7 @@ impl Sub for Decimal256 { Self(self.0 - other.0) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Sub, sub for Decimal256, Decimal256); impl SubAssign for Decimal256 { @@ -518,6 +523,7 @@ impl SubAssign for Decimal256 { *self = *self - rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl SubAssign, sub_assign for Decimal256, Decimal256); impl Mul for Decimal256 { @@ -538,6 +544,7 @@ impl Mul for Decimal256 { } } } +#[cfg(feature = "std")] forward_ref_binop!(impl Mul, mul for Decimal256, Decimal256); impl MulAssign for Decimal256 { @@ -545,6 +552,7 @@ impl MulAssign for Decimal256 { *self = *self * rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl MulAssign, mul_assign for Decimal256, Decimal256); /// Both d*u and u*d with d: Decimal256 and u: Uint256 returns an Uint256. There is no @@ -586,6 +594,7 @@ impl Div for Decimal256 { } } } +#[cfg(feature = "std")] forward_ref_binop!(impl Div, div for Decimal256, Decimal256); impl DivAssign for Decimal256 { @@ -593,6 +602,7 @@ impl DivAssign for Decimal256 { *self = *self / rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl DivAssign, div_assign for Decimal256, Decimal256); impl Div for Decimal256 { @@ -620,6 +630,7 @@ impl Rem for Decimal256 { Self(self.0.rem(rhs.0)) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Rem, rem for Decimal256, Decimal256); impl RemAssign for Decimal256 { @@ -627,9 +638,10 @@ impl RemAssign for Decimal256 { *self = *self % rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl RemAssign, rem_assign for Decimal256, Decimal256); -impl std::iter::Sum for Decimal256 +impl core::iter::Sum for Decimal256 where Self: Add, { @@ -695,6 +707,7 @@ mod tests { use super::*; use crate::errors::StdError; use crate::{from_slice, to_vec}; + use alloc::vec::Vec; fn dec(input: &str) -> Decimal256 { Decimal256::from_str(input).unwrap() diff --git a/packages/std/src/math/isqrt.rs b/packages/std/src/math/isqrt.rs index 6bf4b01f64..c8ee8f52c5 100644 --- a/packages/std/src/math/isqrt.rs +++ b/packages/std/src/math/isqrt.rs @@ -1,4 +1,4 @@ -use std::{cmp, ops}; +use core::{cmp, ops}; use crate::{Uint128, Uint256, Uint512, Uint64}; diff --git a/packages/std/src/math/mod.rs b/packages/std/src/math/mod.rs index 706d23005d..79fff92ac9 100644 --- a/packages/std/src/math/mod.rs +++ b/packages/std/src/math/mod.rs @@ -19,7 +19,7 @@ pub use uint64::Uint64; #[cfg(test)] mod tests { use super::*; - use std::ops::*; + use core::ops::*; /// An trait that ensures other traits are implemented for our number types trait AllImpl<'a>: diff --git a/packages/std/src/math/uint128.rs b/packages/std/src/math/uint128.rs index 2296f40bff..1fbd4af110 100644 --- a/packages/std/src/math/uint128.rs +++ b/packages/std/src/math/uint128.rs @@ -1,18 +1,19 @@ -use std::fmt::{self}; -use std::ops::{ +use alloc::fmt::{self}; +use alloc::string::{String, ToString}; +use core::ops::{ Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Shr, ShrAssign, Sub, SubAssign, }; -use std::str::FromStr; - +use core::str::FromStr; +#[cfg(feature = "std")] use forward_ref::{forward_ref_binop, forward_ref_op_assign}; -use schemars::JsonSchema; use serde::{de, ser, Deserialize, Deserializer, Serialize}; use crate::errors::{ CheckedMultiplyFractionError, CheckedMultiplyRatioError, DivideByZeroError, OverflowError, OverflowOperation, StdError, }; -use crate::{impl_mul_fraction, ConversionOverflowError, Fraction, Uint256, Uint64}; +use crate::{impl_mul_fraction, Fraction}; +use crate::{ConversionOverflowError, Uint256, Uint64}; /// A thin wrapper around u128 that is using strings for JSON encoding/decoding, /// such that the full u128 range can be used for clients that convert JSON numbers to floats, @@ -33,8 +34,9 @@ use crate::{impl_mul_fraction, ConversionOverflowError, Fraction, Uint256, Uint6 /// let c = Uint128::from(70u32); /// assert_eq!(c.u128(), 70); /// ``` -#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, JsonSchema)] -pub struct Uint128(#[schemars(with = "String")] u128); +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Uint128(#[cfg_attr(feature = "std", schemars(with = "String"))] u128); impl Uint128 { pub const MAX: Self = Self(u128::MAX); @@ -353,6 +355,7 @@ impl Sub for Uint128 { ) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Sub, sub for Uint128, Uint128); impl SubAssign for Uint128 { @@ -360,6 +363,7 @@ impl SubAssign for Uint128 { *self = *self - rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl SubAssign, sub_assign for Uint128, Uint128); impl Mul for Uint128 { @@ -373,6 +377,7 @@ impl Mul for Uint128 { ) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Mul, mul for Uint128, Uint128); impl MulAssign for Uint128 { @@ -380,6 +385,7 @@ impl MulAssign for Uint128 { *self = *self * rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl MulAssign, mul_assign for Uint128, Uint128); impl Div for Uint128 { @@ -457,6 +463,7 @@ impl Rem for Uint128 { Self(self.0.rem(rhs.0)) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Rem, rem for Uint128, Uint128); impl RemAssign for Uint128 { @@ -464,6 +471,7 @@ impl RemAssign for Uint128 { *self = *self % rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl RemAssign, rem_assign for Uint128, Uint128); impl ShrAssign for Uint128 { @@ -518,7 +526,7 @@ impl<'de> de::Visitor<'de> for Uint128Visitor { } } -impl std::iter::Sum for Uint128 +impl core::iter::Sum for Uint128 where Self: Add, { diff --git a/packages/std/src/math/uint256.rs b/packages/std/src/math/uint256.rs index d613436730..8447b59389 100644 --- a/packages/std/src/math/uint256.rs +++ b/packages/std/src/math/uint256.rs @@ -1,12 +1,13 @@ -use forward_ref::{forward_ref_binop, forward_ref_op_assign}; -use schemars::JsonSchema; -use serde::{de, ser, Deserialize, Deserializer, Serialize}; -use std::fmt; -use std::ops::{ +use alloc::fmt; +use alloc::string::{String, ToString}; +use core::ops::{ Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Shl, Shr, ShrAssign, Sub, SubAssign, }; -use std::str::FromStr; +use core::str::FromStr; +#[cfg(feature = "std")] +use forward_ref::{forward_ref_binop, forward_ref_op_assign}; +use serde::{de, ser, Deserialize, Deserializer, Serialize}; use crate::errors::{ CheckedMultiplyFractionError, CheckedMultiplyRatioError, ConversionOverflowError, @@ -47,8 +48,9 @@ use uints::U256; /// ]); /// assert_eq!(a, b); /// ``` -#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, JsonSchema)] -pub struct Uint256(#[schemars(with = "String")] U256); +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Uint256(#[cfg_attr(feature = "std", schemars(with = "String"))] U256); impl Uint256 { pub const MAX: Uint256 = Uint256(U256::MAX); @@ -139,7 +141,7 @@ impl Uint256 { (self.0).0[1].to_be_bytes(), (self.0).0[0].to_be_bytes(), ]; - unsafe { std::mem::transmute::<[[u8; 8]; 4], [u8; 32]>(words) } + unsafe { core::mem::transmute::<[[u8; 8]; 4], [u8; 32]>(words) } } /// Returns a copy of the number as little endian bytes. @@ -150,7 +152,7 @@ impl Uint256 { (self.0).0[2].to_le_bytes(), (self.0).0[3].to_le_bytes(), ]; - unsafe { std::mem::transmute::<[[u8; 8]; 4], [u8; 32]>(words) } + unsafe { core::mem::transmute::<[[u8; 8]; 4], [u8; 32]>(words) } } pub const fn is_zero(&self) -> bool { @@ -460,6 +462,7 @@ impl Sub for Uint256 { ) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Sub, sub for Uint256, Uint256); impl SubAssign for Uint256 { @@ -467,6 +470,7 @@ impl SubAssign for Uint256 { *self = *self - rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl SubAssign, sub_assign for Uint256, Uint256); impl Div for Uint256 { @@ -500,6 +504,7 @@ impl Rem for Uint256 { Self(self.0.rem(rhs.0)) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Rem, rem for Uint256, Uint256); impl RemAssign for Uint256 { @@ -507,6 +512,7 @@ impl RemAssign for Uint256 { *self = *self % rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl RemAssign, rem_assign for Uint256, Uint256); impl Mul for Uint256 { @@ -520,6 +526,7 @@ impl Mul for Uint256 { ) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Mul, mul for Uint256, Uint256); impl MulAssign for Uint256 { @@ -527,6 +534,7 @@ impl MulAssign for Uint256 { *self = *self * rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl MulAssign, mul_assign for Uint256, Uint256); impl Shr for Uint256 { @@ -644,7 +652,7 @@ impl<'de> de::Visitor<'de> for Uint256Visitor { } } -impl std::iter::Sum for Uint256 +impl core::iter::Sum for Uint256 where Self: Add, { diff --git a/packages/std/src/math/uint512.rs b/packages/std/src/math/uint512.rs index 99e3b87359..86ce6470f9 100644 --- a/packages/std/src/math/uint512.rs +++ b/packages/std/src/math/uint512.rs @@ -1,11 +1,12 @@ -use forward_ref::{forward_ref_binop, forward_ref_op_assign}; -use schemars::JsonSchema; -use serde::{de, ser, Deserialize, Deserializer, Serialize}; -use std::fmt; -use std::ops::{ +use alloc::fmt; +use alloc::string::{String, ToString}; +use core::ops::{ Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Shr, ShrAssign, Sub, SubAssign, }; -use std::str::FromStr; +use core::str::FromStr; +#[cfg(feature = "std")] +use forward_ref::{forward_ref_binop, forward_ref_op_assign}; +use serde::{de, ser, Deserialize, Deserializer, Serialize}; use crate::errors::{ ConversionOverflowError, DivideByZeroError, OverflowError, OverflowOperation, StdError, @@ -49,8 +50,9 @@ use uints::U512; /// ]); /// assert_eq!(a, b); /// ``` -#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, JsonSchema)] -pub struct Uint512(#[schemars(with = "String")] U512); +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Uint512(#[cfg_attr(feature = "std", schemars(with = "String"))] U512); impl Uint512 { pub const MAX: Uint512 = Uint512(U512::MAX); @@ -164,7 +166,7 @@ impl Uint512 { (self.0).0[1].to_be_bytes(), (self.0).0[0].to_be_bytes(), ]; - unsafe { std::mem::transmute::<[[u8; 8]; 8], [u8; 64]>(words) } + unsafe { core::mem::transmute::<[[u8; 8]; 8], [u8; 64]>(words) } } /// Returns a copy of the number as little endian bytes. @@ -179,7 +181,7 @@ impl Uint512 { (self.0).0[6].to_le_bytes(), (self.0).0[7].to_le_bytes(), ]; - unsafe { std::mem::transmute::<[[u8; 8]; 8], [u8; 64]>(words) } + unsafe { core::mem::transmute::<[[u8; 8]; 8], [u8; 64]>(words) } } pub const fn is_zero(&self) -> bool { @@ -442,6 +444,7 @@ impl Sub for Uint512 { Uint512(self.0.checked_sub(rhs.0).unwrap()) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Sub, sub for Uint512, Uint512); impl SubAssign for Uint512 { @@ -449,6 +452,7 @@ impl SubAssign for Uint512 { self.0 = self.0.checked_sub(rhs.0).unwrap(); } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl SubAssign, sub_assign for Uint512, Uint512); impl Div for Uint512 { @@ -478,6 +482,7 @@ impl Rem for Uint512 { Self(self.0.rem(rhs.0)) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Rem, rem for Uint512, Uint512); impl RemAssign for Uint512 { @@ -485,6 +490,7 @@ impl RemAssign for Uint512 { *self = *self % rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl RemAssign, rem_assign for Uint512, Uint512); impl Mul for Uint512 { @@ -494,6 +500,7 @@ impl Mul for Uint512 { Self(self.0.checked_mul(rhs.0).unwrap()) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Mul, mul for Uint512, Uint512); impl MulAssign for Uint512 { @@ -501,6 +508,7 @@ impl MulAssign for Uint512 { self.0 = self.0.checked_mul(rhs.0).unwrap(); } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl MulAssign, mul_assign for Uint512, Uint512); impl Shr for Uint512 { @@ -597,7 +605,7 @@ impl<'de> de::Visitor<'de> for Uint512Visitor { } } -impl std::iter::Sum for Uint512 +impl core::iter::Sum for Uint512 where Self: Add, { diff --git a/packages/std/src/math/uint64.rs b/packages/std/src/math/uint64.rs index d6fc5fca95..2e99fcafeb 100644 --- a/packages/std/src/math/uint64.rs +++ b/packages/std/src/math/uint64.rs @@ -1,10 +1,11 @@ -use forward_ref::{forward_ref_binop, forward_ref_op_assign}; -use schemars::JsonSchema; -use serde::{de, ser, Deserialize, Deserializer, Serialize}; -use std::fmt::{self}; -use std::ops::{ +use alloc::fmt::{self}; +use alloc::string::{String, ToString}; +use core::ops::{ Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Shr, ShrAssign, Sub, SubAssign, }; +#[cfg(feature = "std")] +use forward_ref::{forward_ref_binop, forward_ref_op_assign}; +use serde::{de, ser, Deserialize, Deserializer, Serialize}; use crate::errors::{ CheckedMultiplyFractionError, CheckedMultiplyRatioError, DivideByZeroError, OverflowError, @@ -28,8 +29,9 @@ use crate::{impl_mul_fraction, Fraction, Uint128}; /// let b = Uint64::from(70u32); /// assert_eq!(b.u64(), 70); /// ``` -#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, JsonSchema)] -pub struct Uint64(#[schemars(with = "String")] u64); +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Uint64(#[cfg_attr(feature = "std", schemars(with = "String"))] u64); impl Uint64 { pub const MAX: Self = Self(u64::MAX); @@ -314,6 +316,7 @@ impl Sub for Uint64 { ) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Sub, sub for Uint64, Uint64); impl SubAssign for Uint64 { @@ -321,6 +324,7 @@ impl SubAssign for Uint64 { *self = *self - rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl SubAssign, sub_assign for Uint64, Uint64); impl Mul for Uint64 { @@ -334,6 +338,7 @@ impl Mul for Uint64 { ) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Mul, mul for Uint64, Uint64); impl MulAssign for Uint64 { @@ -341,6 +346,7 @@ impl MulAssign for Uint64 { *self = *self * rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl MulAssign, mul_assign for Uint64, Uint64); impl Div for Uint64 { @@ -370,6 +376,7 @@ impl Rem for Uint64 { Self(self.0.rem(rhs.0)) } } +#[cfg(feature = "std")] forward_ref_binop!(impl Rem, rem for Uint64, Uint64); impl RemAssign for Uint64 { @@ -377,6 +384,7 @@ impl RemAssign for Uint64 { *self = *self % rhs; } } +#[cfg(feature = "std")] forward_ref_op_assign!(impl RemAssign, rem_assign for Uint64, Uint64); impl Shr for Uint64 { @@ -471,7 +479,7 @@ impl<'de> de::Visitor<'de> for Uint64Visitor { } } -impl std::iter::Sum for Uint64 +impl core::iter::Sum for Uint64 where Self: Add, { diff --git a/packages/std/src/memory.rs b/packages/std/src/memory.rs index c331a53c47..ec99d3c620 100644 --- a/packages/std/src/memory.rs +++ b/packages/std/src/memory.rs @@ -1,5 +1,6 @@ -use std::mem; -use std::vec::Vec; +use alloc::boxed::Box; +use alloc::vec::Vec; +use core::mem; /// Describes some data allocated in Wasm's linear memory. /// A pointer to an instance of this can be returned over FFI boundaries. diff --git a/packages/std/src/panic.rs b/packages/std/src/panic.rs index 7ca619e31a..a6a3f0acea 100644 --- a/packages/std/src/panic.rs +++ b/packages/std/src/panic.rs @@ -3,7 +3,7 @@ /// /// This overrides any previous panic handler. See /// for details. -#[cfg(all(feature = "abort", target_arch = "wasm32"))] +#[cfg(all(feature = "abort", target_arch = "wasm32", feature = "std"))] pub fn install_panic_handler() { use super::imports::handle_panic; std::panic::set_hook(Box::new(|info| { diff --git a/packages/std/src/query/bank.rs b/packages/std/src/query/bank.rs index b3a43e11d5..97f29281e3 100644 --- a/packages/std/src/query/bank.rs +++ b/packages/std/src/query/bank.rs @@ -1,4 +1,5 @@ -use schemars::JsonSchema; +use alloc::string::String; +use alloc::vec::Vec; use serde::{Deserialize, Serialize}; use crate::Coin; @@ -6,7 +7,8 @@ use crate::Coin; use super::query_response::QueryResponseType; #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum BankQuery { /// This calls into the native bank module for querying the total supply of one denomination. @@ -24,7 +26,8 @@ pub enum BankQuery { } #[cfg(feature = "cosmwasm_1_1")] -#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)] #[serde(rename_all = "snake_case")] #[non_exhaustive] pub struct SupplyResponse { @@ -36,7 +39,8 @@ pub struct SupplyResponse { #[cfg(feature = "cosmwasm_1_1")] impl QueryResponseType for SupplyResponse {} -#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct BalanceResponse { /// Always returns a Coin with the requested denom. @@ -46,7 +50,8 @@ pub struct BalanceResponse { impl QueryResponseType for BalanceResponse {} -#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct AllBalanceResponse { /// Returns all non-zero coins held by this account. diff --git a/packages/std/src/query/ibc.rs b/packages/std/src/query/ibc.rs index 0164de3301..175c5c3f3e 100644 --- a/packages/std/src/query/ibc.rs +++ b/packages/std/src/query/ibc.rs @@ -1,14 +1,17 @@ #![cfg(feature = "stargate")] -use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::ibc::IbcChannel; +use alloc::string::String; +use alloc::vec::Vec; + /// These are queries to the various IBC modules to see the state of the contract's /// IBC connection. These will return errors if the contract is not "ibc enabled" #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum IbcQuery { /// Gets the Port ID the current contract is bound to. @@ -32,17 +35,20 @@ pub enum IbcQuery { // TODO: Add more } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct PortIdResponse { pub port_id: String, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct ListChannelsResponse { pub channels: Vec, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct ChannelResponse { pub channel: Option, } diff --git a/packages/std/src/query/mod.rs b/packages/std/src/query/mod.rs index 50061df091..4ebaab6830 100644 --- a/packages/std/src/query/mod.rs +++ b/packages/std/src/query/mod.rs @@ -1,4 +1,5 @@ -use schemars::JsonSchema; +#[cfg(feature = "stargate")] +use alloc::string::String; use serde::{Deserialize, Serialize}; #[cfg(feature = "stargate")] @@ -26,7 +27,8 @@ pub use wasm::CodeInfoResponse; pub use wasm::{ContractInfoResponse, WasmQuery}; #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum QueryRequest { Bank(BankQuery), @@ -58,9 +60,9 @@ pub enum QueryRequest { /// /// ``` /// # use cosmwasm_std::CustomQuery; -/// # use schemars::JsonSchema; /// # use serde::{Deserialize, Serialize}; -/// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +/// #[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +/// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] /// #[serde(rename_all = "snake_case")] /// pub enum MyCustomQuery { /// Ping {}, diff --git a/packages/std/src/query/staking.rs b/packages/std/src/query/staking.rs index fa513ac52a..9e566787f9 100644 --- a/packages/std/src/query/staking.rs +++ b/packages/std/src/query/staking.rs @@ -1,12 +1,14 @@ #![cfg(feature = "staking")] -use schemars::JsonSchema; +use alloc::string::String; +use alloc::vec::Vec; use serde::{Deserialize, Serialize}; use crate::{Addr, Coin, Decimal}; #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum StakingQuery { /// Returns the denomination that can be bonded (if there are multiple native tokens on the chain) @@ -34,14 +36,16 @@ pub enum StakingQuery { } /// BondedDenomResponse is data format returned from StakingRequest::BondedDenom query -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct BondedDenomResponse { pub denom: String, } /// DelegationsResponse is data format returned from StakingRequest::AllDelegations query -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct AllDelegationsResponse { pub delegations: Vec, @@ -50,7 +54,8 @@ pub struct AllDelegationsResponse { /// Delegation is basic (cheap to query) data about a delegation. /// /// Instances are created in the querier. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Delegation { pub delegator: Addr, /// A validator address (e.g. cosmosvaloper1...) @@ -70,7 +75,8 @@ impl From for Delegation { } /// DelegationResponse is data format returned from StakingRequest::Delegation query -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct DelegationResponse { pub delegation: Option, @@ -80,7 +86,8 @@ pub struct DelegationResponse { /// is expensive to query. /// /// Instances are created in the querier. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct FullDelegation { pub delegator: Addr, /// A validator address (e.g. cosmosvaloper1...) @@ -96,19 +103,22 @@ pub struct FullDelegation { } /// The data format returned from StakingRequest::AllValidators query -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct AllValidatorsResponse { pub validators: Vec, } /// The data format returned from StakingRequest::Validator query -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct ValidatorResponse { pub validator: Option, } /// Instances are created in the querier. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Validator { /// A validator address (e.g. cosmosvaloper1...) pub address: String, diff --git a/packages/std/src/query/wasm.rs b/packages/std/src/query/wasm.rs index 039251a4d7..157fb7e093 100644 --- a/packages/std/src/query/wasm.rs +++ b/packages/std/src/query/wasm.rs @@ -1,4 +1,4 @@ -use schemars::JsonSchema; +use alloc::string::String; use serde::{Deserialize, Serialize}; use crate::Binary; @@ -8,7 +8,8 @@ use crate::HexBinary; use super::query_response::QueryResponseType; #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum WasmQuery { /// this queries the public API of another contract at a known address (with known ABI) @@ -34,7 +35,8 @@ pub enum WasmQuery { } #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq)] pub struct ContractInfoResponse { pub code_id: u64, /// address that instantiated this contract @@ -75,7 +77,8 @@ impl ContractInfoResponse { /// [CodeInfo]: https://github.com/CosmWasm/wasmd/blob/v0.30.0/proto/cosmwasm/wasm/v1/types.proto#L62-L72 /// [CodeInfoResponse]: https://github.com/CosmWasm/wasmd/blob/v0.30.0/proto/cosmwasm/wasm/v1/query.proto#L184-L199 #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] #[cfg(feature = "cosmwasm_1_2")] pub struct CodeInfoResponse { pub code_id: u64, diff --git a/packages/std/src/results/contract_result.rs b/packages/std/src/results/contract_result.rs index 380ecaeccb..0c58563f10 100644 --- a/packages/std/src/results/contract_result.rs +++ b/packages/std/src/results/contract_result.rs @@ -1,6 +1,6 @@ -use schemars::JsonSchema; +use alloc::fmt; +use alloc::string::{String, ToString}; use serde::{Deserialize, Serialize}; -use std::fmt; /// This is the final result type that is created and serialized in a contract for /// every init/execute/migrate call. The VM then deserializes this type to distinguish @@ -29,7 +29,8 @@ use std::fmt; /// let result: ContractResult = ContractResult::Err(error_msg); /// assert_eq!(to_vec(&result).unwrap(), br#"{"error":"Something went wrong"}"#); /// ``` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum ContractResult { Ok(S), @@ -155,10 +156,16 @@ mod tests { let original: Result = Err(StdError::generic_err("broken")); let converted: ContractResult = original.into(); + #[cfg(feature = "std")] assert_eq!( converted, ContractResult::Err("Generic error: broken".to_string()) ); + #[cfg(not(feature = "std"))] + assert_eq!( + converted, + ContractResult::Err("GenericErr { msg: \"broken\" }".to_string()) + ); } #[test] diff --git a/packages/std/src/results/cosmos_msg.rs b/packages/std/src/results/cosmos_msg.rs index 3e93ba1868..5d3ac210fe 100644 --- a/packages/std/src/results/cosmos_msg.rs +++ b/packages/std/src/results/cosmos_msg.rs @@ -1,13 +1,16 @@ +use alloc::fmt; +use alloc::string::String; +use alloc::vec::Vec; use derivative::Derivative; -use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use std::fmt; use crate::binary::Binary; use crate::coin::Coin; +#[cfg(feature = "std")] use crate::errors::StdResult; #[cfg(feature = "stargate")] use crate::ibc::IbcMsg; +#[cfg(feature = "std")] use crate::serde::to_binary; #[cfg(all(feature = "stargate", feature = "cosmwasm_1_2"))] use crate::Decimal; @@ -16,12 +19,16 @@ use super::Empty; /// Like CustomQuery for better type clarity. /// Also makes it shorter to use as a trait bound. -pub trait CustomMsg: Serialize + Clone + fmt::Debug + PartialEq + JsonSchema {} +#[cfg(feature = "std")] +pub trait CustomMsg: Serialize + Clone + fmt::Debug + PartialEq + schemars::JsonSchema {} +#[cfg(not(feature = "std"))] +pub trait CustomMsg: Serialize + Clone + fmt::Debug + PartialEq {} impl CustomMsg for Empty {} #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] // See https://github.com/serde-rs/serde/issues/1296 why we cannot add De-Serialize trait bounds to T pub enum CosmosMsg { @@ -51,7 +58,8 @@ pub enum CosmosMsg { /// /// See https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/bank/v1beta1/tx.proto #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum BankMsg { /// Sends native tokens from the contract to the given address. @@ -73,7 +81,8 @@ pub enum BankMsg { /// See https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/staking/v1beta1/tx.proto #[cfg(feature = "staking")] #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum StakingMsg { /// This is translated to a [MsgDelegate](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/staking/v1beta1/tx.proto#L81-L90). @@ -96,7 +105,8 @@ pub enum StakingMsg { /// See https://github.com/cosmos/cosmos-sdk/blob/v0.42.4/proto/cosmos/distribution/v1beta1/tx.proto #[cfg(feature = "staking")] #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum DistributionMsg { /// This is translated to a [MsgSetWithdrawAddress](https://github.com/cosmos/cosmos-sdk/blob/v0.42.4/proto/cosmos/distribution/v1beta1/tx.proto#L29-L37). @@ -113,8 +123,11 @@ pub enum DistributionMsg { }, } -fn binary_to_string(data: &Binary, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { - match std::str::from_utf8(data.as_slice()) { +fn binary_to_string( + data: &Binary, + fmt: &mut alloc::fmt::Formatter, +) -> Result<(), core::fmt::Error> { + match core::str::from_utf8(data.as_slice()) { Ok(s) => fmt.write_str(s), Err(_) => write!(fmt, "{:?}", data), } @@ -124,7 +137,8 @@ fn binary_to_string(data: &Binary, fmt: &mut std::fmt::Formatter) -> Result<(), /// /// See https://github.com/CosmWasm/wasmd/blob/v0.14.0/x/wasm/internal/types/tx.proto #[non_exhaustive] -#[derive(Serialize, Deserialize, Clone, Derivative, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Derivative, PartialEq, Eq)] #[derivative(Debug)] #[serde(rename_all = "snake_case")] pub enum WasmMsg { @@ -273,7 +287,8 @@ pub enum WasmMsg { /// } /// ``` #[cfg(feature = "stargate")] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum GovMsg { /// This maps directly to [MsgVote](https://github.com/cosmos/cosmos-sdk/blob/v0.42.5/proto/cosmos/gov/v1beta1/tx.proto#L46-L56) in the Cosmos SDK with voter set to the contract address. @@ -294,7 +309,8 @@ pub enum GovMsg { } #[cfg(feature = "stargate")] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum VoteOption { Yes, @@ -304,7 +320,8 @@ pub enum VoteOption { } #[cfg(all(feature = "stargate", feature = "cosmwasm_1_2"))] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct WeightedVoteOption { pub option: VoteOption, pub weight: Decimal, @@ -313,6 +330,7 @@ pub struct WeightedVoteOption { /// Shortcut helper as the construction of WasmMsg::Instantiate can be quite verbose in contract code. /// /// When using this, `admin` is always unset. If you need more flexibility, create the message directly. +#[cfg(feature = "std")] pub fn wasm_instantiate( code_id: u64, msg: &impl Serialize, @@ -330,6 +348,7 @@ pub fn wasm_instantiate( } /// Shortcut helper as the construction of WasmMsg::Instantiate can be quite verbose in contract code +#[cfg(feature = "std")] pub fn wasm_execute( contract_addr: impl Into, msg: &impl Serialize, @@ -386,7 +405,10 @@ impl From for CosmosMsg { #[cfg(test)] mod tests { use super::*; - use crate::{coin, coins}; + #[cfg(feature = "std")] + use crate::coin; + use crate::coins; + use alloc::string::ToString; #[test] fn from_bank_msg_works() { @@ -463,6 +485,7 @@ mod tests { } } + #[cfg(feature = "std")] #[test] fn wasm_msg_debug_decodes_binary_string_when_possible() { #[cosmwasm_schema::cw_serde] diff --git a/packages/std/src/results/empty.rs b/packages/std/src/results/empty.rs index 56ccf35868..21c3dfd1e5 100644 --- a/packages/std/src/results/empty.rs +++ b/packages/std/src/results/empty.rs @@ -1,4 +1,3 @@ -use schemars::JsonSchema; use serde::{Deserialize, Serialize}; /// An empty struct that serves as a placeholder in different places, @@ -7,7 +6,8 @@ use serde::{Deserialize, Serialize}; /// It is designed to be expressable in correct JSON and JSON Schema but /// 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)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)] pub struct Empty {} #[cfg(test)] diff --git a/packages/std/src/results/events.rs b/packages/std/src/results/events.rs index 5cf0e8d2a2..8ce016b5b6 100644 --- a/packages/std/src/results/events.rs +++ b/packages/std/src/results/events.rs @@ -1,4 +1,5 @@ -use schemars::JsonSchema; +use alloc::string::String; +use alloc::vec::Vec; use serde::{Deserialize, Serialize}; /// A full [*Cosmos SDK* event]. @@ -9,7 +10,8 @@ use serde::{Deserialize, Serialize}; /// /// [*Cosmos SDK* event]: https://docs.cosmos.network/main/core/events.html /// [*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)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct Event { /// The event type. This is renamed to "ty" because "type" is reserved in Rust. This sucks, we know. @@ -55,7 +57,8 @@ impl Event { } /// An key value pair that is used in the context of event attributes in logs -#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq)] pub struct Attribute { pub key: String, pub value: String, @@ -133,6 +136,7 @@ pub fn attr(key: impl Into, value: impl Into) -> Attribute { mod tests { use super::*; use crate::Uint128; + use alloc::string::ToString; #[test] fn event_construction() { diff --git a/packages/std/src/results/mod.rs b/packages/std/src/results/mod.rs index 90b8879746..9bcebd5e64 100644 --- a/packages/std/src/results/mod.rs +++ b/packages/std/src/results/mod.rs @@ -12,7 +12,9 @@ mod system_result; pub use contract_result::ContractResult; #[cfg(all(feature = "stargate", feature = "cosmwasm_1_2"))] pub use cosmos_msg::WeightedVoteOption; -pub use cosmos_msg::{wasm_execute, wasm_instantiate, BankMsg, CosmosMsg, CustomMsg, WasmMsg}; +#[cfg(feature = "std")] +pub use cosmos_msg::{wasm_execute, wasm_instantiate}; +pub use cosmos_msg::{BankMsg, CosmosMsg, CustomMsg, WasmMsg}; #[cfg(feature = "staking")] pub use cosmos_msg::{DistributionMsg, StakingMsg}; #[cfg(feature = "stargate")] diff --git a/packages/std/src/results/response.rs b/packages/std/src/results/response.rs index 2fa5ed82d0..2402585d06 100644 --- a/packages/std/src/results/response.rs +++ b/packages/std/src/results/response.rs @@ -1,4 +1,5 @@ -use schemars::JsonSchema; +use alloc::string::String; +use alloc::vec::Vec; use serde::{Deserialize, Serialize}; use crate::Binary; @@ -59,7 +60,8 @@ use super::{Attribute, CosmosMsg, Empty, Event, SubMsg}; /// Ok(response) /// } /// ``` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct Response { /// Optional list of messages to pass. These will be executed in order. @@ -236,10 +238,11 @@ mod tests { use super::*; use crate::results::submessages::{ReplyOn, UNUSED_MSG_ID}; use crate::{coins, from_slice, to_vec, ContractResult}; + use alloc::string::ToString; #[test] fn response_add_attributes_works() { - let res = Response::::new().add_attributes(std::iter::empty::()); + let res = Response::::new().add_attributes(core::iter::empty::()); assert_eq!(res.attributes.len(), 0); let res = Response::::new().add_attributes([Attribute::new("test", "ing")]); diff --git a/packages/std/src/results/submessages.rs b/packages/std/src/results/submessages.rs index 138680c1e3..5101f4df0e 100644 --- a/packages/std/src/results/submessages.rs +++ b/packages/std/src/results/submessages.rs @@ -1,4 +1,6 @@ -use schemars::JsonSchema; +use alloc::string::String; +use alloc::string::ToString; +use alloc::vec::Vec; use serde::{Deserialize, Serialize}; use crate::Binary; @@ -8,7 +10,8 @@ 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. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum ReplyOn { /// Always perform a callback after SubMsg is processed @@ -27,7 +30,8 @@ pub enum ReplyOn { /// Note: On error the submessage execution will revert any partial state changes due to this message, /// but not revert any state changes in the calling contract. If this is required, it must be done /// manually in the `reply` entry point. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct SubMsg { /// An arbitrary ID chosen by the contract. /// This is typically used to match `Reply`s in the `reply` entry point to the submessage. @@ -97,7 +101,8 @@ impl SubMsg { /// The result object returned to `reply`. We always get the ID from the submessage /// back and then must handle success and error cases ourselves. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Reply { /// The ID that the contract set when emitting the `SubMsg`. /// Use this to identify which submessage triggered the `reply`. @@ -137,7 +142,8 @@ pub struct Reply { /// let result = SubMsgResult::Err(error_msg); /// assert_eq!(to_vec(&result).unwrap(), br#"{"error":"Something went wrong"}"#); /// ``` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum SubMsgResult { Ok(SubMsgResponse), @@ -193,7 +199,8 @@ impl From for Result { /// The information we get back from a successful sub message execution, /// with full Cosmos SDK events. -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct SubMsgResponse { pub events: Vec, pub data: Option, @@ -341,10 +348,16 @@ mod tests { let original: Result = Err(StdError::generic_err("broken")); let converted: SubMsgResult = original.into(); + #[cfg(feature = "std")] assert_eq!( converted, SubMsgResult::Err("Generic error: broken".to_string()) ); + #[cfg(not(feature = "std"))] + assert_eq!( + converted, + SubMsgResult::Err("GenericErr { msg: \"broken\" }".to_string()) + ); } #[test] diff --git a/packages/std/src/results/system_result.rs b/packages/std/src/results/system_result.rs index 9cc7a48582..e8ad8174c6 100644 --- a/packages/std/src/results/system_result.rs +++ b/packages/std/src/results/system_result.rs @@ -1,6 +1,5 @@ -use schemars::JsonSchema; +use alloc::fmt; use serde::{Deserialize, Serialize}; -use std::fmt; use super::super::errors::SystemError; @@ -29,7 +28,8 @@ use super::super::errors::SystemError; /// let result: SystemResult = SystemResult::Err(error); /// assert_eq!(to_vec(&result).unwrap(), br#"{"error":{"unknown":{}}}"#); /// ``` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum SystemResult { Ok(S), diff --git a/packages/std/src/sections.rs b/packages/std/src/sections.rs index 89433f5537..0f5910dfd8 100644 --- a/packages/std/src/sections.rs +++ b/packages/std/src/sections.rs @@ -1,4 +1,5 @@ use crate::conversion::force_to_u32; +use alloc::vec::Vec; /// A sections decoder for the special case of two elements #[allow(dead_code)] // used in Wasm and tests only diff --git a/packages/std/src/serde.rs b/packages/std/src/serde.rs index e58a51e6dd..85d5cf2780 100644 --- a/packages/std/src/serde.rs +++ b/packages/std/src/serde.rs @@ -1,9 +1,12 @@ +#![cfg(feature = "std")] + // This file simply re-exports some methods from serde_json // The reason is two fold: // 1. To easily ensure that all calling libraries use the same version (minimize code size) // 2. To allow us to switch out to eg. serde-json-core more easily +use alloc::vec::Vec; +use core::any::type_name; use serde::{de::DeserializeOwned, Serialize}; -use std::any::type_name; use crate::binary::Binary; use crate::errors::{StdError, StdResult}; @@ -33,6 +36,7 @@ where #[cfg(test)] mod tests { use super::*; + use alloc::string::{String, ToString}; use serde::Deserialize; #[derive(Serialize, Deserialize, Debug, PartialEq)] diff --git a/packages/std/src/storage.rs b/packages/std/src/storage.rs index be80fcdae0..66a46a7950 100644 --- a/packages/std/src/storage.rs +++ b/packages/std/src/storage.rs @@ -1,9 +1,14 @@ -use std::collections::BTreeMap; -use std::fmt; +#![cfg(feature = "std")] + +#[cfg(feature = "iterator")] +use alloc::boxed::Box; +use alloc::collections::BTreeMap; +use alloc::fmt; +use alloc::vec::Vec; #[cfg(feature = "iterator")] -use std::iter; +use core::iter; #[cfg(feature = "iterator")] -use std::ops::{Bound, RangeBounds}; +use core::ops::{Bound, RangeBounds}; #[cfg(feature = "iterator")] use crate::iterator::{Order, Record}; diff --git a/packages/std/src/testing/assertions.rs b/packages/std/src/testing/assertions.rs index 3d5cf0a2d8..8f9a5c7147 100644 --- a/packages/std/src/testing/assertions.rs +++ b/packages/std/src/testing/assertions.rs @@ -1,5 +1,6 @@ use crate::{Decimal, Uint128}; -use std::str::FromStr as _; +use alloc::str::FromStr as _; +use alloc::string::String; /// Asserts that two expressions are approximately equal to each other. /// @@ -35,7 +36,7 @@ pub fn assert_approx_eq_impl>( let right = right.into(); let max_rel_diff = Decimal::from_str(max_rel_diff).unwrap(); - let largest = std::cmp::max(left, right); + let largest = core::cmp::max(left, right); let rel_diff = Decimal::from_ratio(left.abs_diff(right), largest); if rel_diff > max_rel_diff { diff --git a/packages/std/src/testing/mock.rs b/packages/std/src/testing/mock.rs index 023ef30ff8..c0c3c04145 100644 --- a/packages/std/src/testing/mock.rs +++ b/packages/std/src/testing/mock.rs @@ -1,8 +1,12 @@ +use alloc::boxed::Box; +use alloc::collections::BTreeMap; +use alloc::string::String; +use alloc::string::ToString; +use alloc::vec::Vec; +use core::marker::PhantomData; use serde::de::DeserializeOwned; #[cfg(feature = "stargate")] use serde::Serialize; -use std::collections::HashMap; -use std::marker::PhantomData; use crate::addresses::{Addr, CanonicalAddr}; use crate::binary::Binary; @@ -586,15 +590,15 @@ impl Default for WasmQuerier { #[derive(Clone, Default)] pub struct BankQuerier { #[allow(dead_code)] - /// HashMap - supplies: HashMap, - /// HashMap - balances: HashMap>, + /// BTreeMap + supplies: BTreeMap, + /// BTreeMap + balances: BTreeMap>, } impl BankQuerier { pub fn new(balances: &[(&str, &[Coin])]) -> Self { - let balances: HashMap<_, _> = balances + let balances: BTreeMap<_, _> = balances .iter() .map(|(s, c)| (s.to_string(), c.to_vec())) .collect(); @@ -616,8 +620,8 @@ impl BankQuerier { result } - fn calculate_supplies(balances: &HashMap>) -> HashMap { - let mut supplies = HashMap::new(); + fn calculate_supplies(balances: &BTreeMap>) -> BTreeMap { + let mut supplies = BTreeMap::new(); let all_coins = balances.iter().flat_map(|(_, coins)| coins); @@ -1439,7 +1443,7 @@ mod tests { querier.update_handler(|request| { let constract1 = Addr::unchecked("contract1"); - let mut storage1 = HashMap::::default(); + let mut storage1 = BTreeMap::::default(); storage1.insert(b"the key".into(), b"the value".into()); match request { @@ -1547,7 +1551,7 @@ mod tests { }); match result { SystemResult::Ok(ContractResult::Err(err)) => { - assert_eq!(err, "Error parsing into type cosmwasm_std::testing::mock::tests::wasm_querier_works::{{closure}}::MyMsg: Invalid type") + assert_eq!(err, "Error parsing into type cosmwasm_std::testing::mock::tests::wasm_querier_works::{{closure}}::MyMsg: Invalid type"); } res => panic!("Unexpected result: {:?}", res), } diff --git a/packages/std/src/testing/mod.rs b/packages/std/src/testing/mod.rs index 657aada5de..4c3051213d 100644 --- a/packages/std/src/testing/mod.rs +++ b/packages/std/src/testing/mod.rs @@ -1,3 +1,4 @@ +#![cfg(feature = "std")] #![cfg(not(target_arch = "wasm32"))] // Exposed for testing only diff --git a/packages/std/src/timestamp.rs b/packages/std/src/timestamp.rs index fa96fb477c..791180b676 100644 --- a/packages/std/src/timestamp.rs +++ b/packages/std/src/timestamp.rs @@ -1,6 +1,5 @@ -use schemars::JsonSchema; +use alloc::fmt; use serde::{Deserialize, Serialize}; -use std::fmt; use crate::math::Uint64; @@ -22,9 +21,8 @@ use crate::math::Uint64; /// assert_eq!(ts.seconds(), 3); /// assert_eq!(ts.subsec_nanos(), 202); /// ``` -#[derive( - Serialize, Deserialize, Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, JsonSchema, -)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Timestamp(Uint64); impl Timestamp { diff --git a/packages/std/src/traits.rs b/packages/std/src/traits.rs index e3ba067b6e..c249914032 100644 --- a/packages/std/src/traits.rs +++ b/packages/std/src/traits.rs @@ -1,6 +1,12 @@ +#![cfg(feature = "std")] + +#[cfg(feature = "iterator")] +use alloc::boxed::Box; +use alloc::string::String; +use alloc::vec::Vec; +use core::marker::PhantomData; +use core::ops::Deref; use serde::{de::DeserializeOwned, Serialize}; -use std::marker::PhantomData; -use std::ops::Deref; use crate::addresses::{Addr, CanonicalAddr}; use crate::binary::Binary; @@ -371,6 +377,7 @@ mod tests { use super::*; use crate::testing::MockQuerier; use crate::{coins, from_slice, Uint128}; + use alloc::string::ToString; // this is a simple demo helper to prove we can use it fn demo_helper(_querier: &dyn Querier) -> u64 { diff --git a/packages/std/src/types.rs b/packages/std/src/types.rs index 782ad1e726..248e549230 100644 --- a/packages/std/src/types.rs +++ b/packages/std/src/types.rs @@ -1,11 +1,13 @@ -use schemars::JsonSchema; +use alloc::string::String; +use alloc::vec::Vec; use serde::{Deserialize, Serialize}; use crate::addresses::Addr; use crate::coin::Coin; use crate::timestamp::Timestamp; -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Env { pub block: BlockInfo, /// Information on the transaction this message was executed in. @@ -15,7 +17,8 @@ pub struct Env { pub contract: ContractInfo, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct TransactionInfo { /// The position of this transaction in the block. The first /// transaction has index 0. @@ -26,7 +29,8 @@ pub struct TransactionInfo { pub index: u32, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct BlockInfo { /// The height of a block is the number of blocks preceding it in the blockchain. pub height: u64, @@ -105,7 +109,8 @@ pub struct MessageInfo { pub funds: Vec, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[cfg_attr(feature = "std", derive(schemars::JsonSchema))] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct ContractInfo { pub address: Addr, } diff --git a/packages/storage/Cargo.toml b/packages/storage/Cargo.toml index 6332d2e1b2..4645b53e0a 100644 --- a/packages/storage/Cargo.toml +++ b/packages/storage/Cargo.toml @@ -16,5 +16,5 @@ iterator = ["cosmwasm-std/iterator"] [dependencies] # Uses the path when built locally; uses the given version from crates.io when published -cosmwasm-std = { path = "../std", version = "1.2.0", default-features = false } +cosmwasm-std = { path = "../std", version = "1.2.0", default-features = false, features = ["std"]} serde = { version = "1.0.103", default-features = false, features = ["derive", "alloc"] } diff --git a/packages/vm/Cargo.toml b/packages/vm/Cargo.toml index 0fb8290d5b..5800555b2f 100644 --- a/packages/vm/Cargo.toml +++ b/packages/vm/Cargo.toml @@ -41,7 +41,7 @@ required-features = ["iterator"] [dependencies] clru = "0.4.0" # Uses the path when built locally; uses the given version from crates.io when published -cosmwasm-std = { path = "../std", version = "1.2.0", default-features = false } +cosmwasm-std = { path = "../std", version = "1.2.0", default-features = false, features = ["std"] } cosmwasm-crypto = { path = "../crypto", version = "1.2.0" } hex = "0.4" parity-wasm = "0.42"