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

Add AllDenomMetadata BankQuery #1703

Merged
merged 16 commits into from
Jun 22, 2023
Merged
Show file tree
Hide file tree
Changes from 13 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 @@ -356,15 +356,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 @@ -907,7 +907,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 @@ -984,7 +984,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
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"rust-analyzer.cargo.features": ["abort", "stargate", "staking", "cosmwasm_1_2"]
"rust-analyzer.cargo.features": ["abort", "stargate", "staking", "cosmwasm_1_3"]
}
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,19 @@ and this project adheres to

### Added

- cosmwasm-std: Implement `BankQuery::AllDenomMetadata` to allow querying all
chipshort marked this conversation as resolved.
Show resolved Hide resolved
the denom metadata and `BankQuery::DenomMetadata` to query a specific one. 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])
- cosmwasm-std: Add `FromStr` impl for `Coin`. ([#1684])

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

### 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 feature that is only available on CosmWasm 1.3+ chains,
use this feature:

```diff
-cosmwasm-std = { version = "1.3.0", features = ["stargate"] }
+cosmwasm-std = { version = "1.3.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: 1 addition & 1 deletion contracts/cyberpunk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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", "cosmwasm_1_3"] }
rust-argon2 = "0.8"
thiserror = "1.0.26"

Expand Down
78 changes: 74 additions & 4 deletions contracts/cyberpunk/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use cosmwasm_std::{
entry_point, to_binary, Api, Deps, DepsMut, Empty, Env, MessageInfo, QueryResponse, Response,
StdError, StdResult, WasmMsg,
entry_point, to_binary, Api, Deps, DepsMut, Empty, Env, MessageInfo, PageRequest,
QueryResponse, Response, StdError, StdResult, WasmMsg,
};

use crate::errors::ContractError;
Expand Down Expand Up @@ -179,25 +179,51 @@ fn execute_debug(api: &dyn Api) -> Result<Response, ContractError> {
}

#[entry_point]
pub fn query(_deps: Deps, env: Env, msg: QueryMsg) -> StdResult<QueryResponse> {
pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<QueryResponse> {
use QueryMsg::*;

match msg {
MirrorEnv {} => to_binary(&query_mirror_env(env)),
Denoms {} => to_binary(&query_denoms(deps)?),
}
}

fn query_mirror_env(env: Env) -> Env {
env
}

fn query_denoms(deps: Deps) -> StdResult<(String, Vec<String>)> {
chipshort marked this conversation as resolved.
Show resolved Hide resolved
let metadata = deps.querier.query_denom_metadata("uatom")?;

const PAGE_SIZE: u32 = 10;
let mut next_key = None;
let mut all_metadata = Vec::new();
loop {
let page = deps.querier.query_all_denom_metadata(PageRequest {
key: next_key,
limit: PAGE_SIZE,
reverse: false,
})?;

let len = page.metadata.len() as u32;
all_metadata.extend(page.metadata.into_iter().map(|m| m.symbol));
next_key = page.next_key;

if next_key.is_none() || len < PAGE_SIZE {
break;
}
}

Ok((metadata.symbol, all_metadata))
}

#[cfg(test)]
mod tests {
use super::*;
use cosmwasm_std::testing::{
mock_dependencies, mock_env, mock_info, MockApi, MockQuerier, MockStorage,
};
use cosmwasm_std::OwnedDeps;
use cosmwasm_std::{from_binary, DenomMetadata, DenomUnit, OwnedDeps};

fn setup() -> OwnedDeps<MockStorage, MockApi, MockQuerier> {
let mut deps = mock_dependencies();
Expand All @@ -220,4 +246,48 @@ mod tests {
let msg = ExecuteMsg::Debug {};
execute(deps.as_mut(), mock_env(), mock_info("caller", &[]), msg).unwrap();
}

#[test]
fn query_denoms_works() {
let mut deps = setup();

deps.querier.set_denom_metadata(
&(0..98)
.map(|i| DenomMetadata {
symbol: format!("FOO{i}"),
name: "Foo".to_string(),
description: "Foo coin".to_string(),
denom_units: vec![DenomUnit {
denom: "ufoo".to_string(),
exponent: 8,
aliases: vec!["microfoo".to_string(), "foobar".to_string()],
}],
display: "FOO".to_string(),
base: "ufoo".to_string(),
uri: "https://foo.bar".to_string(),
uri_hash: "foo".to_string(),
})
.chain(std::iter::once(DenomMetadata {
description: "Atom".to_string(),
denom_units: vec![DenomUnit {
denom: "uatom".to_string(),
exponent: 8,
aliases: vec!["microatom".to_string()],
}],
base: "uatom".to_string(),
display: "ATOM".to_string(),
name: "Cosmos Atom".to_string(),
symbol: "ATOM".to_string(),
uri: "https://cosmos.network".to_string(),
uri_hash: "hash".to_string(),
}))
.collect::<Vec<_>>(),
);

let (atom, symbols): (String, Vec<String>) =
from_binary(&query(deps.as_ref(), mock_env(), QueryMsg::Denoms {}).unwrap()).unwrap();

assert_eq!(atom, "ATOM");
assert_eq!(symbols.len(), 99);
}
}
4 changes: 4 additions & 0 deletions contracts/cyberpunk/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,8 @@ pub enum QueryMsg {
/// Returns the env for testing
#[returns(cosmwasm_std::Env)]
MirrorEnv {},

/// Queries `DenomMetadata` and `AllDenomMetadata` from the bank module and returns the symbols
#[returns((String, Vec<String>))]
Denoms {},
chipshort marked this conversation as resolved.
Show resolved Hide resolved
}
3 changes: 3 additions & 0 deletions docs/CAPABILITIES-BUILT-IN.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,6 @@ 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` and
`BankQuery::DenomMetadata` queries. 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:
| backtraces | | 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 = Command::new("Contract checking")
Expand Down
5 changes: 4 additions & 1 deletion packages/std/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ license = "Apache-2.0"
readme = "README.md"

[package.metadata.docs.rs]
features = ["abort", "stargate", "staking", "ibc3", "cosmwasm_1_2"]
features = ["abort", "stargate", "staking", "ibc3", "cosmwasm_1_3"]

[features]
default = ["iterator", "abort"]
Expand Down 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
2 changes: 1 addition & 1 deletion packages/std/src/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::errors::StdError;
/// allows contracts to reuse the type when deserializing database records.
pub type Record<V = Vec<u8>> = (Vec<u8>, V);

#[derive(Copy, Clone)]
#[derive(Copy, Clone, PartialEq, Eq)]
// We assign these to integers to provide a stable API for passing over FFI (to wasm and Go)
pub enum Order {
Ascending = 1,
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 @@ -17,7 +17,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 @@ -56,7 +58,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>,
}
12 changes: 12 additions & 0 deletions packages/std/src/pagination.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::Binary;

/// Simplified version of the PageRequest type for pagination from the cosmos-sdk
#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, Eq, JsonSchema)]
pub struct PageRequest {
pub key: Option<Binary>,
pub limit: u32,
pub reverse: bool,
}
Loading