Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std: Add BankQuery::AllDenomMetadata gated by cosmwasm_1_3 feature flag #1647

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -362,15 +362,15 @@ jobs:
- 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,cosmwasm_1_3
- 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,cosmwasm_1_3
- 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,cosmwasm_1_3
- save_cache:
paths:
- /usr/local/cargo/registry
Expand Down Expand Up @@ -913,7 +913,7 @@ jobs:
- run:
name: Clippy linting on std (all feature flags)
working_directory: ~/project/packages/std
command: cargo clippy --all-targets --features abort,iterator,staking,stargate,cosmwasm_1_2 -- -D warnings
command: cargo clippy --all-targets --features abort,iterator,staking,stargate,cosmwasm_1_3 -- -D warnings
- run:
name: Clippy linting on storage (no feature flags)
working_directory: ~/project/packages/storage
Expand Down Expand Up @@ -990,7 +990,7 @@ jobs:
CRYPTO=" cargo tarpaulin --skip-clean --out Xml --output-dir reports/crypto --packages cosmwasm-crypto"
DERIVE=" cargo tarpaulin --skip-clean --out Xml --output-dir reports/derive --packages cosmwasm-derive"
SCHEMA=" cargo tarpaulin --skip-clean --out Xml --output-dir reports/schema --packages cosmwasm-schema"
STD=" cargo tarpaulin --skip-clean --out Xml --output-dir reports/std --packages cosmwasm-std --features abort,iterator,staking,stargate,cosmwasm_1_2"
STD=" cargo tarpaulin --skip-clean --out Xml --output-dir reports/std --packages cosmwasm-std --features abort,iterator,staking,stargate,cosmwasm_1_3"
STORAGE="cargo tarpaulin --skip-clean --out Xml --output-dir reports/storage --packages cosmwasm-storage"
docker run --security-opt seccomp=unconfined -v "${PWD}:/volume" xd009642/tarpaulin:0.21.0 \
sh -c "$CRYPTO && $DERIVE && $SCHEMA && $STD && $STORAGE"
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,17 @@ and this project adheres to

### Added

- cosmwasm-std: Implement `BankQuery::AllDenomMetadata` to allow querying all
the denom metadata. In order to use this query in a contract, the
`cosmwasm_1_3` feature needs to be enabled for the `cosmwasm_std` dependency.
This makes the contract incompatible with chains running anything lower than
CosmWasm `1.3.0`. ([#1647])
- cosmwasm-vm: Add `Cache::save_wasm_unchecked` to save Wasm blobs that have
been checked before. This is useful for state-sync where we know the Wasm code
was checked when it was first uploaded. ([#1635])

[#1635]: https://github.com/CosmWasm/cosmwasm/pull/1635
[#1647]: https://github.com/CosmWasm/cosmwasm/pull/1647

### Changed

Expand Down
27 changes: 27 additions & 0 deletions MIGRATING.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,33 @@ This guide explains what is needed to upgrade contracts when migrating over
major releases of `cosmwasm`. Note that you can also view the
[complete CHANGELOG](./CHANGELOG.md) to understand the differences.

## 1.2.x -> 1.3.0

- Update `cosmwasm-*` dependencies in Cargo.toml (skip the ones you don't use):

```
[dependencies]
cosmwasm-std = "1.3.0"
cosmwasm-storage = "1.3.0"
# ...

[dev-dependencies]
cosmwasm-schema = "1.3.0"
cosmwasm-vm = "1.3.0"
# ...
```

- If you want to use a fewture that os only available on CosmWasm 1.3+ chains,
use this feature:

```diff
-cosmwasm-std = { version = "1.1.0", features = ["stargate"] }
+cosmwasm-std = { version = "1.1.0", features = ["stargate", "cosmwasm_1_3"] }
```

Please note that `cosmwasm_1_2` implies `cosmwasm_1_1`, and `cosmwasm_1_3`
implies `cosmwasm_1_2`, and so on, so there is no need to set multiple.

## 1.1.x -> 1.2.0

- Update `cosmwasm-*` dependencies in Cargo.toml (skip the ones you don't use):
Expand Down
2 changes: 2 additions & 0 deletions docs/CAPABILITIES-BUILT-IN.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ might define others.
CosmWasm `1.1.0` or higher support this.
- `cosmwasm_1_2` enables the `GovMsg::VoteWeighted` and `WasmMsg::Instantiate2`
messages. Only chains running CosmWasm `1.2.0` or higher support this.
- `cosmwasm_1_3` enables the `BankQuery::AllDenomMetadata` query. Only chains
running CosmWasm `1.3.0` or higher support this.
1 change: 1 addition & 0 deletions docs/USING_COSMWASM_STD.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ The libarary comes with the following features:
| baktraces | | Add backtraces to errors (for unit testing) |
| cosmwasm_1_1 | | Features that require CosmWasm 1.1+ on the chain |
| cosmwasm_1_2 | | Features that require CosmWasm 1.2+ on the chain |
| cosmwasm_1_3 | | Features that require CosmWasm 1.3+ on the chain |

## The cosmwasm-std dependency for contract developers

Expand Down
3 changes: 2 additions & 1 deletion packages/check/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ use colored::Colorize;
use cosmwasm_vm::capabilities_from_csv;
use cosmwasm_vm::internals::{check_wasm, compile};

const DEFAULT_AVAILABLE_CAPABILITIES: &str = "iterator,staking,stargate,cosmwasm_1_1,cosmwasm_1_2";
const DEFAULT_AVAILABLE_CAPABILITIES: &str =
"iterator,staking,stargate,cosmwasm_1_1,cosmwasm_1_2,cosmwasm_1_3";

pub fn main() {
let matches = App::new("Contract checking")
Expand Down
3 changes: 3 additions & 0 deletions packages/std/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ 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"]
# This feature makes `BankQuery::DenomMetadata` available for the contract to call, but requires
# the host blockchain to run CosmWasm `1.3.0` or higher.
cosmwasm_1_3 = ["cosmwasm_1_2"]

[dependencies]
base64 = "0.13.0"
Expand Down
4 changes: 4 additions & 0 deletions packages/std/src/exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ extern "C" fn requires_cosmwasm_1_1() -> () {}
#[no_mangle]
extern "C" fn requires_cosmwasm_1_2() -> () {}

#[cfg(feature = "cosmwasm_1_3")]
#[no_mangle]
extern "C" fn requires_cosmwasm_1_3() -> () {}

/// interface_version_* exports mark which Wasm VM interface level this contract is compiled for.
/// They can be checked by cosmwasm_vm.
/// Update this whenever the Wasm VM interface breaks.
Expand Down
4 changes: 4 additions & 0 deletions packages/std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ mod import_helpers;
#[cfg(feature = "iterator")]
mod iterator;
mod math;
mod metadata;
mod never;
mod pagination;
mod panic;
mod query;
mod results;
Expand Down Expand Up @@ -50,7 +52,9 @@ pub use crate::math::{
Decimal, Decimal256, Decimal256RangeExceeded, DecimalRangeExceeded, Fraction, Isqrt, Uint128,
Uint256, Uint512, Uint64,
};
pub use crate::metadata::{DenomMetadata, DenomUnit};
pub use crate::never::Never;
pub use crate::pagination::PageRequest;
#[cfg(feature = "cosmwasm_1_2")]
pub use crate::query::CodeInfoResponse;
#[cfg(feature = "cosmwasm_1_1")]
Expand Down
23 changes: 23 additions & 0 deletions packages/std/src/metadata.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Replicates the cosmos-sdk bank module Metadata type
#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq, JsonSchema)]
pub struct DenomMetadata {
pub description: String,
pub denom_units: Vec<DenomUnit>,
pub base: String,
pub display: String,
pub name: String,
pub symbol: String,
pub uri: String,
pub uri_hash: String,
}

/// Replicates the cosmos-sdk bank module DenomUnit type
#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq, JsonSchema)]
pub struct DenomUnit {
pub denom: String,
pub exponent: u32,
pub aliases: Vec<String>,
}
14 changes: 14 additions & 0 deletions packages/std/src/pagination.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::{Binary, Uint64};

/// Replicates the PageRequest type for pagination from the cosmos-sdk
#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq, JsonSchema)]
pub struct PageRequest {
pub key: Binary,
pub offset: Uint64,
pub limit: Uint64,
pub count_total: bool,
pub reverse: bool,
}
38 changes: 38 additions & 0 deletions packages/std/src/query/bank.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ use serde::{Deserialize, Serialize};

use crate::Coin;

#[cfg(feature = "cosmwasm_1_3")]
use crate::DenomMetadata;

#[cfg(feature = "cosmwasm_1_3")]
use crate::PageRequest;

use super::query_response::QueryResponseType;

#[non_exhaustive]
Expand All @@ -21,6 +27,14 @@ pub enum BankQuery {
/// Note that this may be much more expensive than Balance and should be avoided if possible.
/// Return value is AllBalanceResponse.
AllBalances { address: String },
/// This calls into the native bank module for querying metadata for a specific bank token.
/// Return value is DenomMetadataResponse
#[cfg(feature = "cosmwasm_1_3")]
DenomMetadata { denom: String },
/// This calls into the native bank module for querying metadata for all bank tokens that have a metadata entry.
/// Return value is AllDenomMetadataResponse
#[cfg(feature = "cosmwasm_1_3")]
AllDenomMetadata { pagination: Option<PageRequest> },
}

#[cfg(feature = "cosmwasm_1_1")]
Expand Down Expand Up @@ -54,3 +68,27 @@ pub struct AllBalanceResponse {
}

impl QueryResponseType for AllBalanceResponse {}

#[cfg(feature = "cosmwasm_1_3")]
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub struct DenomMetadataResponse {
/// Always returns metadata for all token denoms on the base chain.
pub metadata: DenomMetadata,
}

#[cfg(feature = "cosmwasm_1_3")]
impl QueryResponseType for DenomMetadataResponse {}

#[cfg(feature = "cosmwasm_1_3")]
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub struct AllDenomMetadataResponse {
/// Always returns metadata for all token denoms on the base chain.
pub metadata: Vec<DenomMetadata>,
}

#[cfg(feature = "cosmwasm_1_3")]
impl QueryResponseType for AllDenomMetadataResponse {}
2 changes: 2 additions & 0 deletions packages/std/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ mod wasm;
#[cfg(feature = "cosmwasm_1_1")]
pub use bank::SupplyResponse;
pub use bank::{AllBalanceResponse, BalanceResponse, BankQuery};
#[cfg(feature = "cosmwasm_1_3")]
pub use bank::{AllDenomMetadataResponse, DenomMetadataResponse};
#[cfg(feature = "stargate")]
pub use ibc::{ChannelResponse, IbcQuery, ListChannelsResponse, PortIdResponse};
#[cfg(feature = "staking")]
Expand Down
31 changes: 30 additions & 1 deletion packages/std/src/testing/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,15 @@ use crate::query::{
AllDelegationsResponse, AllValidatorsResponse, BondedDenomResponse, DelegationResponse,
FullDelegation, StakingQuery, Validator, ValidatorResponse,
};
#[cfg(feature = "cosmwasm_1_3")]
use crate::query::{AllDenomMetadataResponse, DenomMetadataResponse};
use crate::results::{ContractResult, Empty, SystemResult};
use crate::serde::{from_slice, to_binary};
use crate::storage::MemoryStorage;
use crate::timestamp::Timestamp;
use crate::traits::{Api, Querier, QuerierResult};
use crate::types::{BlockInfo, ContractInfo, Env, MessageInfo, TransactionInfo};
use crate::Attribute;
use crate::{Attribute, DenomMetadata};
#[cfg(feature = "stargate")]
use crate::{ChannelResponse, IbcQuery, ListChannelsResponse, PortIdResponse};

Expand Down Expand Up @@ -599,6 +601,8 @@ pub struct BankQuerier {
supplies: HashMap<String, Uint128>,
/// HashMap<address, coins>
balances: HashMap<String, Vec<Coin>>,
/// Vec<Metadata>
denom_metadata: Vec<DenomMetadata>,
}

impl BankQuerier {
Expand All @@ -611,6 +615,7 @@ impl BankQuerier {
BankQuerier {
supplies: Self::calculate_supplies(&balances),
balances,
denom_metadata: Vec::new(),
}
}

Expand All @@ -625,6 +630,10 @@ impl BankQuerier {
result
}

pub fn set_denom_metadata(&mut self, denom_metadata: &[DenomMetadata]) {
self.denom_metadata = denom_metadata.to_vec();
}

fn calculate_supplies(balances: &HashMap<String, Vec<Coin>>) -> HashMap<String, Uint128> {
let mut supplies = HashMap::new();

Expand Down Expand Up @@ -678,6 +687,26 @@ impl BankQuerier {
};
to_binary(&bank_res).into()
}
#[cfg(feature = "cosmwasm_1_3")]
BankQuery::DenomMetadata { denom } => {
let denom_metadata = self.denom_metadata.iter().find(|m| &m.base == denom);
match denom_metadata {
Some(m) => {
let metadata_res = DenomMetadataResponse {
metadata: m.clone(),
};
to_binary(&metadata_res).into()
}
None => return SystemResult::Err(SystemError::Unknown {}),
}
}
#[cfg(feature = "cosmwasm_1_3")]
BankQuery::AllDenomMetadata { pagination: _ } => {
let metadata_res = AllDenomMetadataResponse {
metadata: self.denom_metadata.clone(),
};
to_binary(&metadata_res).into()
}
};
// system result is always ok in the mock implementation
SystemResult::Ok(contract_result)
Expand Down
26 changes: 26 additions & 0 deletions packages/std/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,15 @@ use crate::query::{
AllDelegationsResponse, AllValidatorsResponse, BondedDenomResponse, Delegation,
DelegationResponse, FullDelegation, StakingQuery, Validator, ValidatorResponse,
};
#[cfg(feature = "cosmwasm_1_3")]
use crate::query::{AllDenomMetadataResponse, DenomMetadataResponse};
use crate::results::{ContractResult, Empty, SystemResult};
use crate::serde::{from_binary, to_binary, to_vec};
use crate::ContractInfoResponse;
#[cfg(feature = "cosmwasm_1_3")]
use crate::DenomMetadata;
#[cfg(feature = "cosmwasm_1_3")]
use crate::PageRequest;

/// Storage provides read and write access to a persistent storage.
/// If you only want to provide read access, provide `&Storage`
Expand Down Expand Up @@ -239,6 +245,26 @@ impl<'a, C: CustomQuery> QuerierWrapper<'a, C> {
Ok(res.amount)
}

#[cfg(feature = "cosmwasm_1_3")]
pub fn query_denom_metadata(&self, denom: impl Into<String>) -> StdResult<DenomMetadata> {
let request = BankQuery::DenomMetadata {
denom: denom.into(),
}
.into();
let res: DenomMetadataResponse = self.query(&request)?;
Ok(res.metadata)
}

#[cfg(feature = "cosmwasm_1_3")]
pub fn query_all_denom_metadata(
&self,
pagination: Option<PageRequest>,
) -> StdResult<Vec<DenomMetadata>> {
let request = BankQuery::AllDenomMetadata { pagination }.into();
let res: AllDenomMetadataResponse = self.query(&request)?;
Ok(res.metadata)
}

// this queries another wasm contract. You should know a priori the proper types for T and U
// (response and request) based on the contract API
pub fn query_wasm_smart<T: DeserializeOwned>(
Expand Down
3 changes: 2 additions & 1 deletion packages/vm/src/testing/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ pub struct MockInstanceOptions<'a> {
impl MockInstanceOptions<'_> {
fn default_capabilities() -> HashSet<String> {
#[allow(unused_mut)]
let mut out = capabilities_from_csv("iterator,staking,cosmwasm_1_1,cosmwasm_1_2");
let mut out =
capabilities_from_csv("iterator,staking,cosmwasm_1_1,cosmwasm_1_2,cosmwasm_1_3");
#[cfg(feature = "stargate")]
out.insert("stargate".to_string());
out
Expand Down