diff --git a/.github/workflows/Static.yml b/.github/workflows/Static.yml index ca488fb..c191f82 100644 --- a/.github/workflows/Static.yml +++ b/.github/workflows/Static.yml @@ -13,7 +13,7 @@ jobs: rust: [stable] make: - name: Clippy - task: "cargo clippy" + task: "cargo clippy --all --all-features -- -D warnings" - name: Unit tests task: "cargo test --all --all-features" include: diff --git a/Releases.md b/Releases.md index 5c35aca..75dc592 100644 --- a/Releases.md +++ b/Releases.md @@ -1,15 +1,27 @@ # Release notes for the Secret Toolkit +## v0.6.0 + +This release upgrades all `secret-toolkit` packages to be compatible with Cosmwasm v1.0 (Secret Network v1.4). +The APIs remains the same, but it is necessary to upgrade the contract's `cosmwasm` dependencies to `v1.0.0`. + +### Breaking + +- This version will not work with `cosmwasm v0.10`. It is necessary to upgrade to `cosmwasm v1` in order to use this release. + ## v0.5.0 + This release includes some minor fixed to the storage package which required some breaking changes. We are releasing these breaking changes because we reached the conclusion that the current interfaces are prone to bugs, or inefficient. Unless you are using these specific interfaces, you should be able to upgrade from 0.4 without issues. ### Breaking + - Removed the implementations of Clone for storage types which are not useful and may cause data corruption if used incorrectly. - Changed `Keymap::insert` to take the item by reference rather than by value. This should reduce the cost of calling that function by avoiding cloning. ### Features + - Changed the implementation of the `add_prefix` methods in the storage package to use length prefixing, which should help avoid namespace collisions. ## secret-toolkit-storage v0.4.2 @@ -65,12 +77,12 @@ A full guide to using the new `storage` types can be found * docs.rs documentation now includes all sub-crates. * BUGFIX: `secret-toolkit::snip721::Metadata` was severely out of date with the SNIP-721 specification, and not useful. It is now compatible with deployed SNIP-721 contracts. -* Added `types` module under the `util` package, to standardize often used types. -* Added `secret-toolkit::viewing_key`, which can be imported by enabling the `viewing-key` feature. -* Added `secret-toolkit::permit::PubKey::canonical_address()`. -* Types in `secret-toolkit::permit::Permit` are now generic over the type of permissions they accept. -* Added the `maxheap` type to the incubator. -* Added `secret-toolkit::utils::feature_toggle` which allow managing feature flags in your contract. +- Added `types` module under the `util` package, to standardize often used types. +- Added `secret-toolkit::viewing_key`, which can be imported by enabling the `viewing-key` feature. +- Added `secret-toolkit::permit::PubKey::canonical_address()`. +- Types in `secret-toolkit::permit::Permit` are now generic over the type of permissions they accept. +- Added the `maxheap` type to the incubator. +- Added `secret-toolkit::utils::feature_toggle` which allow managing feature flags in your contract. ### Breaking @@ -78,15 +90,15 @@ A full guide to using the new `storage` types can be found Interface changes: Now takes a reference to the current token address instead of taking it by value and an optional hrp string. In addition, it returns a String and not HumanAddr. -* Renamed `secret-toolkit::permit::Permission` to `secret-toolkit::permit::TokenPermission`. -* `secret-toolkit-crypto` now has features `["hash", "rng" and "ecc-secp256k1"]` which are all off by default - enable those you need. -* `secret-toolkit-crypto::secp256k1::PublicKey::parse` now returns `StdResult`. -* Changes to `secret-toolkit::crypto::secp256k1::PrivateKey::sign`: - * The `data` argument is now any slice of bytes, and not the hash of a slice of data. - * the `Api` from `deps.api` is now required as the second argument as we now use the precompiled implementation. -* Changes to `secret-toolkit::crypto::secp256k1::PublicKey::verify`: - * the `Api` from `deps.api` is now required as the third argument as we now use the precompiled implementation. -* `secret-toolkit-incubator` now has features `["cashmap", "generational-store"]` which are all off by default. +- Renamed `secret-toolkit::permit::Permission` to `secret-toolkit::permit::TokenPermission`. +- `secret-toolkit-crypto` now has features `["hash", "rng" and "ecc-secp256k1"]` which are all off by default - enable those you need. +- `secret-toolkit-crypto::secp256k1::PublicKey::parse` now returns `StdResult`. +- Changes to `secret-toolkit::crypto::secp256k1::PrivateKey::sign`: + - The `data` argument is now any slice of bytes, and not the hash of a slice of data. + - the `Api` from `deps.api` is now required as the second argument as we now use the precompiled implementation. +- Changes to `secret-toolkit::crypto::secp256k1::PublicKey::verify`: + - the `Api` from `deps.api` is now required as the third argument as we now use the precompiled implementation. +- `secret-toolkit-incubator` now has features `["cashmap", "generational-store"]` which are all off by default. ## v0.2.0 @@ -103,11 +115,11 @@ This version is also the first released to [crates.io](https://crates.io)! which are wrappers that automatically deserializes base64 strings to `T`. It can be used in message types' fields instead of `Binary` when the contents of the string should have more specific contents. -* Added `storage::DequeStore` - Similar to `AppendStore` but allows pushing and popping on both ends -* Added the `secret-toolkit::incubator` package intended for experimental features. It contains: - * `CashMap` - A hashmap like storage abstraction - * `GenerationalIndex` - A generational index storage abstraction -* The various subpackages can now be selected using feature flags. The default flags are `["serialization", "snip20", "snip721", "storage", "utils"]` +- Added `storage::DequeStore` - Similar to `AppendStore` but allows pushing and popping on both ends +- Added the `secret-toolkit::incubator` package intended for experimental features. It contains: + - `CashMap` - A hashmap like storage abstraction + - `GenerationalIndex` - A generational index storage abstraction +- The various subpackages can now be selected using feature flags. The default flags are `["serialization", "snip20", "snip721", "storage", "utils"]` while `["crypto", "permit", "incubator"]` are left disabled by default. ## v0.1.1 @@ -118,16 +130,16 @@ This version is also the first released to [crates.io](https://crates.io)! This is the first release of `secret-toolkit`. It supports: -* `secret-toolkit::snip20` - Helper types and functions for interaction with +- `secret-toolkit::snip20` - Helper types and functions for interaction with SNIP-20 contracts. -* `secret-toolkit::snip721` - Helper types and functions for interaction with +- `secret-toolkit::snip721` - Helper types and functions for interaction with SNIP-721 contracts. -* `secret-toolkit::crypto` - Wrappers for known-to-work crypto primitives from +- `secret-toolkit::crypto` - Wrappers for known-to-work crypto primitives from ecosystem libraries. We include implementations for Sha256, Secp256k1 keys, and ChaChaRng. -* `secret-toolkit::storage` - Types implementing useful storage managements +- `secret-toolkit::storage` - Types implementing useful storage managements techniques: `AppendStore` and `TypedStore`, using `bincode2` by default. -* `secret-toolkit::serialization` - marker types for overriding the storage +- `secret-toolkit::serialization` - marker types for overriding the storage format used by types in `secret-toolkit::storage`. `Json` and `Bincode2`. * `secret-toolkit::utils` - General utilities for writing contract code. * `padding` - tools for padding queries and responses. diff --git a/packages/crypto/Cargo.toml b/packages/crypto/Cargo.toml index d24ebdd..53cca5b 100644 --- a/packages/crypto/Cargo.toml +++ b/packages/crypto/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "secret-toolkit-crypto" -version = "0.3.0" +version = "0.6.0" edition = "2018" authors = ["SCRT Labs "] license-file = "../../LICENSE" @@ -23,7 +23,7 @@ rand_chacha = { version = "0.2.2", default-features = false, optional = true } rand_core = { version = "0.5.1", default-features = false, optional = true } sha2 = { version = "0.9.1", default-features = false, optional = true } secp256k1 = { version = "0.21.3", optional = true } -cosmwasm-std = { package = "secret-cosmwasm-std", version = "0.10" } +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.0.0" } [dev-dependencies] secp256k1-test = { package = "secp256k1", version = "0.17", features = [ diff --git a/packages/crypto/src/secp256k1.rs b/packages/crypto/src/secp256k1.rs index ff25b4f..6448596 100644 --- a/packages/crypto/src/secp256k1.rs +++ b/packages/crypto/src/secp256k1.rs @@ -112,20 +112,20 @@ mod tests { } #[test] - #[ignore] // Crypto functions are not implemented in `MockApi` fn test_sign() { let s = Secp256k1::new(); let (secp_privkey, _) = s.generate_keypair(&mut thread_rng()); - let mock_api = MockApi::new(20); + let mock_api = MockApi::default(); let mut privkey = [0u8; PRIVATE_KEY_SIZE]; privkey.copy_from_slice(&secp_privkey[..]); - let data = sha_256(b"test"); + let data = b"test"; + let data_hash = sha_256(data); let pk = PrivateKey::parse(&privkey).unwrap(); - let signature = pk.sign(&data, mock_api); + let signature = pk.sign(data, mock_api); let pubkey = pk.pubkey(); - assert!(pubkey.verify(&data, signature, mock_api)); + assert!(pubkey.verify(&data_hash, signature, mock_api)); } } diff --git a/packages/incubator/Cargo.toml b/packages/incubator/Cargo.toml index 9798848..ca6f50e 100644 --- a/packages/incubator/Cargo.toml +++ b/packages/incubator/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "secret-toolkit-incubator" -version = "0.4.0" +version = "0.6.0" edition = "2018" authors = ["SCRT Labs "] license-file = "../../LICENSE" @@ -15,9 +15,9 @@ all-features = true [dependencies] serde = { version = "1.0", optional = true } -cosmwasm-std = { package = "secret-cosmwasm-std", version = "0.10", optional = true } -cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "0.10", optional = true } -secret-toolkit-serialization = { version = "0.3", path = "../serialization", optional = true } +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.0.0", optional = true } +cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "1.0.0", optional = true } +secret-toolkit-serialization = { version = "0.6", path = "../serialization", optional = true } [features] generational-store = ["secret-toolkit-serialization", "serde", "cosmwasm-std"] diff --git a/packages/incubator/src/generational_store.rs b/packages/incubator/src/generational_store.rs index dc934aa..6d1ae84 100644 --- a/packages/incubator/src/generational_store.rs +++ b/packages/incubator/src/generational_store.rs @@ -18,7 +18,7 @@ use std::marker::PhantomData; use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use cosmwasm_std::{ReadonlyStorage, StdError, StdResult, Storage}; +use cosmwasm_std::{StdError, StdResult, Storage}; use secret_toolkit_serialization::{Bincode2, Serde}; @@ -62,7 +62,7 @@ impl Index { } } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub enum Entry { Free { next_free: u32 }, Occupied { generation: u64, value: T }, @@ -82,14 +82,12 @@ pub struct StoredOccupiedEntry { // Mutable generational index store /// A type allowing both reads from and writes to the generational store. -#[derive(Debug)] -pub struct GenerationalStoreMut<'a, T, S, Ser = Bincode2> +pub struct GenerationalStoreMut<'a, T, Ser = Bincode2> where T: Serialize + DeserializeOwned, - S: Storage, Ser: Serde, { - storage: &'a mut S, + storage: &'a mut dyn Storage, item_type: PhantomData<*const T>, serialization_type: PhantomData<*const Ser>, len: u32, @@ -99,16 +97,15 @@ where capacity: u32, } -impl<'a, T, S> GenerationalStoreMut<'a, T, S, Bincode2> +impl<'a, T> GenerationalStoreMut<'a, T, Bincode2> where T: Serialize + DeserializeOwned, - S: Storage, { /// Try to use the provided storage as an GenerationalStore. If it doesn't seem to be one, then /// initialize it as one. /// /// Returns Err if the contents of the storage can not be parsed. - pub fn attach_or_create(storage: &'a mut S) -> StdResult { + pub fn attach_or_create(storage: &'a mut dyn Storage) -> StdResult { GenerationalStoreMut::attach_or_create_with_serialization(storage, Bincode2) } @@ -116,22 +113,24 @@ where /// /// Returns None if the provided storage doesn't seem like an GenerationalStore. /// Returns Err if the contents of the storage can not be parsed. - pub fn attach(storage: &'a mut S) -> Option> { + pub fn attach(storage: &'a mut dyn Storage) -> Option> { GenerationalStoreMut::attach_with_serialization(storage, Bincode2) } } -impl<'a, T, S, Ser> GenerationalStoreMut<'a, T, S, Ser> +impl<'a, T, Ser> GenerationalStoreMut<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: Storage, Ser: Serde, { /// Try to use the provided storage as an GenerationalStore. If it doesn't seem to be one, then /// initialize it as one. This method allows choosing the serialization format you want to use. /// /// Returns Err if the contents of the storage can not be parsed. - pub fn attach_or_create_with_serialization(storage: &'a mut S, _ser: Ser) -> StdResult { + pub fn attach_or_create_with_serialization( + storage: &'a mut dyn Storage, + _ser: Ser, + ) -> StdResult { let len_vec = storage.get(LEN_KEY); let generation_vec = storage.get(GENERATION_KEY); let free_list_head_vec = storage.get(FREE_LIST_HEAD_KEY); @@ -172,7 +171,10 @@ where /// /// Returns None if the provided storage doesn't seem like an GenerationalStore. /// Returns Err if the contents of the storage can not be parsed. - pub fn attach_with_serialization(storage: &'a mut S, _ser: Ser) -> Option> { + pub fn attach_with_serialization( + storage: &'a mut dyn Storage, + _ser: Ser, + ) -> Option> { let len_vec = storage.get(LEN_KEY)?; let generation_vec = storage.get(GENERATION_KEY)?; let free_list_head_vec = storage.get(FREE_LIST_HEAD_KEY)?; @@ -187,7 +189,7 @@ where } fn new( - storage: &'a mut S, + storage: &'a mut dyn Storage, len_vec: &[u8], generation_vec: &[u8], free_list_head_vec: &[u8], @@ -351,16 +353,16 @@ where self.len == 0 } - pub fn storage(&mut self) -> &mut S { + pub fn storage(&'a mut self) -> &'a mut dyn Storage { self.storage } - pub fn readonly_storage(&self) -> &S { + pub fn readonly_storage(&'a self) -> &'a dyn Storage { self.storage } /// Return an iterator over the items in the collection - pub fn iter(&self) -> Iter { + pub fn iter(&self) -> Iter { self.as_readonly().iter() } @@ -437,7 +439,7 @@ where } /// Gain access to the implementation of the immutable methods - fn as_readonly(&self) -> GenerationalStore { + fn as_readonly(&self) -> GenerationalStore { GenerationalStore { storage: self.storage, item_type: self.item_type, @@ -453,14 +455,12 @@ where // Readonly generational index store /// A type allowing only reads from an append store. useful in the context_, u8 of queries. -#[derive(Debug)] -pub struct GenerationalStore<'a, T, S, Ser = Bincode2> +pub struct GenerationalStore<'a, T, Ser = Bincode2> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { - storage: &'a S, + storage: &'a dyn Storage, item_type: PhantomData<*const T>, serialization_type: PhantomData<*const Ser>, len: u32, @@ -469,24 +469,22 @@ where capacity: u32, } -impl<'a, T, S> GenerationalStore<'a, T, S, Bincode2> +impl<'a, T> GenerationalStore<'a, T, Bincode2> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, { /// Try to use the provided storage as an GenerationalStore. /// /// Returns None if the provided storage doesn't seem like an GenerationalStore. /// Returns Err if the contents of the storage can not be parsed. - pub fn attach(storage: &'a S) -> Option> { + pub fn attach(storage: &'a dyn Storage) -> Option> { GenerationalStore::attach_with_serialization(storage, Bincode2) } } -impl<'a, T, S, Ser> GenerationalStore<'a, T, S, Ser> +impl<'a, T, Ser> GenerationalStore<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { /// Try to use the provided storage as an GenerationalStore. @@ -494,7 +492,10 @@ where /// /// Returns None if the provided storage doesn't seem like an GenerationalStore. /// Returns Err if the contents of the storage can not be parsed. - pub fn attach_with_serialization(storage: &'a S, _ser: Ser) -> Option> { + pub fn attach_with_serialization( + storage: &'a dyn Storage, + _ser: Ser, + ) -> Option> { let len_vec = storage.get(LEN_KEY)?; let generation_vec = storage.get(GENERATION_KEY)?; let free_list_head_vec = storage.get(FREE_LIST_HEAD_KEY)?; @@ -509,7 +510,7 @@ where } fn new( - storage: &'a S, + storage: &'a dyn Storage, len_vec: Vec, generation_vec: Vec, free_list_head_vec: Vec, @@ -562,12 +563,12 @@ where self.capacity } - pub fn readonly_storage(&self) -> &S { + pub fn readonly_storage(&self) -> &'a dyn Storage { self.storage } /// Return an iterator over the items in the collection - pub fn iter(&self) -> Iter<'a, T, S, Ser> { + pub fn iter(&self) -> Iter<'a, T, Ser> { Iter { storage: GenerationalStore::clone(self), start: 0, @@ -638,10 +639,9 @@ where } } -impl<'a, T, S, Ser> IntoIterator for GenerationalStore<'a, T, S, Ser> +impl<'a, T, Ser> IntoIterator for GenerationalStore<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { type Item = (Option, Entry); @@ -649,9 +649,9 @@ where // alternate version, see below //type Item = (Index, T); - type IntoIter = Iter<'a, T, S, Ser>; + type IntoIter = Iter<'a, T, Ser>; - fn into_iter(self) -> Iter<'a, T, S, Ser> { + fn into_iter(self) -> Iter<'a, T, Ser> { let end = self.len; Iter { storage: self, @@ -662,10 +662,9 @@ where } // Manual `Clone` implementation because the default one tries to clone the Storage?? -impl<'a, T, S, Ser> Clone for GenerationalStore<'a, T, S, Ser> +impl<'a, T, Ser> Clone for GenerationalStore<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { fn clone(&self) -> Self { @@ -684,22 +683,19 @@ where // Owning iterator /// An iterator over the contents of the generational store. -#[derive(Debug)] -pub struct Iter<'a, T, S, Ser> +pub struct Iter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { - storage: GenerationalStore<'a, T, S, Ser>, + storage: GenerationalStore<'a, T, Ser>, start: u32, end: u32, } -impl<'a, T, S, Ser> Iterator for Iter<'a, T, S, Ser> +impl<'a, T, Ser> Iterator for Iter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { type Item = (Option, Entry); @@ -785,10 +781,9 @@ where } } -impl<'a, T, S, Ser> DoubleEndedIterator for Iter<'a, T, S, Ser> +impl<'a, T, Ser> DoubleEndedIterator for Iter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { fn next_back(&mut self) -> Option { @@ -825,10 +820,9 @@ where } // This enables writing `append_store.iter().skip(n).rev()` -impl<'a, T, S, Ser> ExactSizeIterator for Iter<'a, T, S, Ser> +impl<'a, T, Ser> ExactSizeIterator for Iter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { } diff --git a/packages/incubator/src/maxheap.rs b/packages/incubator/src/maxheap.rs index a3cb127..1c8afac 100644 --- a/packages/incubator/src/maxheap.rs +++ b/packages/incubator/src/maxheap.rs @@ -11,7 +11,7 @@ use std::marker::PhantomData; use serde::{de::DeserializeOwned, Serialize}; use std::cmp::PartialOrd; -use cosmwasm_std::{ReadonlyStorage, StdError, StdResult, Storage}; +use cosmwasm_std::{StdError, StdResult, Storage}; use secret_toolkit_serialization::{Bincode2, Serde}; @@ -20,29 +20,26 @@ const LEN_KEY: &[u8] = b"len"; // Mutable maxheap store /// A type allowing both reads from and writes to the maxheap store at a given storage location. -#[derive(Debug)] -pub struct MaxHeapStoreMut<'a, T, S, Ser = Bincode2> +pub struct MaxHeapStoreMut<'a, T, Ser = Bincode2> where T: Serialize + DeserializeOwned + PartialOrd, - S: Storage, Ser: Serde, { - storage: &'a mut S, + storage: &'a mut dyn Storage, item_type: PhantomData<*const T>, serialization_type: PhantomData<*const Ser>, len: u32, } -impl<'a, T, S> MaxHeapStoreMut<'a, T, S, Bincode2> +impl<'a, T> MaxHeapStoreMut<'a, T, Bincode2> where T: Serialize + DeserializeOwned + PartialOrd, - S: Storage, { /// Try to use the provided storage as an MaxHeapStore. If it doesn't seem to be one, then /// initialize it as one. /// /// Returns Err if the contents of the storage can not be parsed. - pub fn attach_or_create(storage: &'a mut S) -> StdResult { + pub fn attach_or_create(storage: &'a mut dyn Storage) -> StdResult { MaxHeapStoreMut::attach_or_create_with_serialization(storage, Bincode2) } @@ -50,22 +47,24 @@ where /// /// Returns None if the provided storage doesn't seem like an MaxHeapStore. /// Returns Err if the contents of the storage can not be parsed. - pub fn attach(storage: &'a mut S) -> Option> { + pub fn attach(storage: &'a mut dyn Storage) -> Option> { MaxHeapStoreMut::attach_with_serialization(storage, Bincode2) } } -impl<'a, T, S, Ser> MaxHeapStoreMut<'a, T, S, Ser> +impl<'a, T, Ser> MaxHeapStoreMut<'a, T, Ser> where T: Serialize + DeserializeOwned + PartialOrd, - S: Storage, Ser: Serde, { /// Try to use the provided storage as an MaxHeapStore. If it doesn't seem to be one, then /// initialize it as one. This method allows choosing the serialization format you want to use. /// /// Returns Err if the contents of the storage can not be parsed. - pub fn attach_or_create_with_serialization(storage: &'a mut S, _ser: Ser) -> StdResult { + pub fn attach_or_create_with_serialization( + storage: &'a mut dyn Storage, + _ser: Ser, + ) -> StdResult { if let Some(len_vec) = storage.get(LEN_KEY) { Self::new(storage, &len_vec) } else { @@ -80,12 +79,15 @@ where /// /// Returns None if the provided storage doesn't seem like an MaxHeapStore. /// Returns Err if the contents of the storage can not be parsed. - pub fn attach_with_serialization(storage: &'a mut S, _ser: Ser) -> Option> { + pub fn attach_with_serialization( + storage: &'a mut dyn Storage, + _ser: Ser, + ) -> Option> { let len_vec = storage.get(LEN_KEY)?; Some(Self::new(storage, &len_vec)) } - fn new(storage: &'a mut S, len_vec: &[u8]) -> StdResult { + fn new(storage: &'a mut dyn Storage, len_vec: &[u8]) -> StdResult { let len_array = len_vec .try_into() .map_err(|err| StdError::parse_err("u32", err))?; @@ -107,11 +109,11 @@ where self.len == 0 } - pub fn storage(&mut self) -> &mut S { + pub fn storage(&mut self) -> &mut dyn Storage { self.storage } - pub fn readonly_storage(&self) -> &S { + pub fn readonly_storage(&self) -> &dyn Storage { self.storage } @@ -244,7 +246,7 @@ where } /// Gain access to the implementation of the immutable methods - fn as_readonly(&self) -> MaxHeapStore { + fn as_readonly(&self) -> MaxHeapStore { MaxHeapStore { storage: self.storage, item_type: self.item_type, @@ -257,37 +259,33 @@ where // Readonly maxheap store /// A type allowing only reads from an max heap store. useful in the context of queries. -#[derive(Debug)] -pub struct MaxHeapStore<'a, T, S, Ser = Bincode2> +pub struct MaxHeapStore<'a, T, Ser = Bincode2> where T: Serialize + DeserializeOwned + PartialOrd, - S: ReadonlyStorage, Ser: Serde, { - storage: &'a S, + storage: &'a dyn Storage, item_type: PhantomData<*const T>, serialization_type: PhantomData<*const Ser>, len: u32, } -impl<'a, T, S> MaxHeapStore<'a, T, S, Bincode2> +impl<'a, T> MaxHeapStore<'a, T, Bincode2> where T: Serialize + DeserializeOwned + PartialOrd, - S: ReadonlyStorage, { /// Try to use the provided storage as a MaxHeapStore. /// /// Returns None if the provided storage doesn't seem like a MaxHeapStore. /// Returns Err if the contents of the storage can not be parsed. - pub fn attach(storage: &'a S) -> Option> { + pub fn attach(storage: &'a dyn Storage) -> Option> { MaxHeapStore::attach_with_serialization(storage, Bincode2) } } -impl<'a, T, S, Ser> MaxHeapStore<'a, T, S, Ser> +impl<'a, T, Ser> MaxHeapStore<'a, T, Ser> where T: Serialize + DeserializeOwned + PartialOrd, - S: ReadonlyStorage, Ser: Serde, { /// Try to use the provided storage as an MaxHeapStore. @@ -295,12 +293,15 @@ where /// /// Returns None if the provided storage doesn't seem like an MaxHeapStore. /// Returns Err if the contents of the storage can not be parsed. - pub fn attach_with_serialization(storage: &'a S, _ser: Ser) -> Option> { + pub fn attach_with_serialization( + storage: &'a dyn Storage, + _ser: Ser, + ) -> Option> { let len_vec = storage.get(LEN_KEY)?; Some(MaxHeapStore::new(storage, len_vec)) } - fn new(storage: &'a S, len_vec: Vec) -> StdResult { + fn new(storage: &'a dyn Storage, len_vec: Vec) -> StdResult { let len_array = len_vec .as_slice() .try_into() @@ -323,7 +324,7 @@ where self.len == 0 } - pub fn readonly_storage(&self) -> &S { + pub fn readonly_storage(&self) -> &'a dyn Storage { self.storage } @@ -356,7 +357,6 @@ mod tests { use cosmwasm_std::testing::MockStorage; use serde::Deserialize; - use cosmwasm_std::HumanAddr; use secret_toolkit_serialization::Json; use std::cmp::Ordering; @@ -389,7 +389,7 @@ mod tests { fn test_custom_ord() -> StdResult<()> { #[derive(Serialize, Deserialize, Clone, Debug, Eq)] pub struct Tx { - address: HumanAddr, + address: String, amount: u128, } @@ -415,58 +415,58 @@ mod tests { let mut heap_store = MaxHeapStoreMut::attach_or_create(&mut storage)?; heap_store.insert(&Tx { - address: HumanAddr("address1".to_string()), + address: "address1".to_string(), amount: 200, })?; heap_store.insert(&Tx { - address: HumanAddr("address2".to_string()), + address: "address2".to_string(), amount: 100, })?; heap_store.insert(&Tx { - address: HumanAddr("address3".to_string()), + address: "address3".to_string(), amount: 400, })?; heap_store.insert(&Tx { - address: HumanAddr("address4".to_string()), + address: "address4".to_string(), amount: 300, })?; heap_store.insert(&Tx { - address: HumanAddr("address5".to_string()), + address: "address5".to_string(), amount: 50, })?; assert_eq!( heap_store.remove(), Ok(Tx { - address: HumanAddr("address3".to_string()), + address: "address3".to_string(), amount: 400, }) ); assert_eq!( heap_store.remove(), Ok(Tx { - address: HumanAddr("address4".to_string()), + address: "address4".to_string(), amount: 300, }) ); assert_eq!( heap_store.remove(), Ok(Tx { - address: HumanAddr("address1".to_string()), + address: "address1".to_string(), amount: 200, }) ); assert_eq!( heap_store.remove(), Ok(Tx { - address: HumanAddr("address2".to_string()), + address: "address2".to_string(), amount: 100, }) ); assert_eq!( heap_store.remove(), Ok(Tx { - address: HumanAddr("address5".to_string()), + address: "address5".to_string(), amount: 50, }) ); diff --git a/packages/permit/Cargo.toml b/packages/permit/Cargo.toml index 9bdeaf0..31195ff 100644 --- a/packages/permit/Cargo.toml +++ b/packages/permit/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "secret-toolkit-permit" -version = "0.3.1" +version = "0.6.0" edition = "2018" authors = ["SCRT Labs "] license-file = "../../LICENSE" @@ -14,11 +14,12 @@ keywords = ["secret-network", "secret-contracts", "secret-toolkit"] all-features = true [dependencies] -cosmwasm-std = { package = "secret-cosmwasm-std", version = "0.10.1" } - +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.0.0" } serde = "1.0" ripemd160 = { version = "0.9.1", default-features = false } -schemars = "0.7" +schemars = "0.8.1" bech32 = "0.8.1" remain = "0.2.2" -secret-toolkit-crypto = { version = "0.3.0", path = "../crypto", features=["hash"] } +secret-toolkit-crypto = { version = "0.6.0", path = "../crypto", features = [ + "hash", +] } diff --git a/packages/permit/src/funcs.rs b/packages/permit/src/funcs.rs index d6fbf6a..6cde3b3 100644 --- a/packages/permit/src/funcs.rs +++ b/packages/permit/src/funcs.rs @@ -1,17 +1,15 @@ -use cosmwasm_std::{ - to_binary, Api, Binary, CanonicalAddr, Extern, HumanAddr, Querier, StdError, StdResult, Storage, -}; +use cosmwasm_std::{to_binary, Binary, CanonicalAddr, Deps, StdError, StdResult}; use ripemd160::{Digest, Ripemd160}; use crate::{Permissions, Permit, RevokedPermits, SignedPermit}; use bech32::{ToBase32, Variant}; use secret_toolkit_crypto::sha_256; -pub fn validate( - deps: &Extern, +pub fn validate( + deps: Deps, storage_prefix: &str, permit: &Permit, - current_token_address: HumanAddr, + current_token_address: String, hrp: Option<&str>, ) -> StdResult { let account_hrp = hrp.unwrap_or("secret"); @@ -37,12 +35,8 @@ pub fn validate( // Validate permit_name let permit_name = &permit.params.permit_name; - let is_permit_revoked = RevokedPermits::is_permit_revoked( - &deps.storage, - storage_prefix, - &HumanAddr(account.clone()), - permit_name, - ); + let is_permit_revoked = + RevokedPermits::is_permit_revoked(deps.storage, storage_prefix, &account, permit_name); if is_permit_revoked { return Err(StdError::generic_err(format!( "Permit {:?} was revoked by account {:?}", @@ -83,11 +77,11 @@ mod tests { #[test] fn test_verify_permit() { - let deps = mock_dependencies(20, &[]); + let deps = mock_dependencies(); //{"permit": {"params":{"chain_id":"pulsar-2","permit_name":"memo_secret1rf03820fp8gngzg2w02vd30ns78qkc8rg8dxaq","allowed_tokens":["secret1rf03820fp8gngzg2w02vd30ns78qkc8rg8dxaq"],"permissions":["history"]},"signature":{"pub_key":{"type":"tendermint/PubKeySecp256k1","value":"A5M49l32ZrV+SDsPnoRv8fH7ivNC4gEX9prvd4RwvRaL"},"signature":"hw/Mo3ZZYu1pEiDdymElFkuCuJzg9soDHw+4DxK7cL9rafiyykh7VynS+guotRAKXhfYMwCiyWmiznc6R+UlsQ=="}}} - let token = HumanAddr("secret1rf03820fp8gngzg2w02vd30ns78qkc8rg8dxaq".to_string()); + let token = "secret1rf03820fp8gngzg2w02vd30ns78qkc8rg8dxaq".to_string(); let permit: Permit = Permit{ params: PermitParams { @@ -105,14 +99,21 @@ mod tests { } }; - let address = validate(&deps, "test", &permit, token.clone(), Some("secret")).unwrap(); + let address = validate::<_>( + deps.as_ref(), + "test", + &permit, + token.clone(), + Some("secret"), + ) + .unwrap(); assert_eq!( address, "secret1399pyvvk3hvwgxwt3udkslsc5jl3rqv4yshfrl".to_string() ); - let address = validate(&deps, "test", &permit, token, Some("cosmos")).unwrap(); + let address = validate::<_>(deps.as_ref(), "test", &permit, token, Some("cosmos")).unwrap(); assert_eq!( address, diff --git a/packages/permit/src/state.rs b/packages/permit/src/state.rs index fd9df80..9a47e93 100644 --- a/packages/permit/src/state.rs +++ b/packages/permit/src/state.rs @@ -1,4 +1,4 @@ -use cosmwasm_std::{HumanAddr, Storage}; +use cosmwasm_std::Storage; pub struct RevokedPermits; @@ -6,10 +6,10 @@ impl RevokedPermits { pub fn is_permit_revoked( storgae: &dyn Storage, storage_prefix: &str, - account: &HumanAddr, + account: &str, permit_name: &str, ) -> bool { - let storage_key = storage_prefix.to_string() + &account.to_string() + permit_name; + let storage_key = storage_prefix.to_string() + account + permit_name; storgae.get(storage_key.as_bytes()).is_some() } @@ -17,11 +17,16 @@ impl RevokedPermits { pub fn revoke_permit( storage: &mut dyn Storage, storage_prefix: &str, - account: &HumanAddr, + account: &str, permit_name: &str, ) { - let storage_key = storage_prefix.to_string() + &account.to_string() + permit_name; + let storage_key = storage_prefix.to_string() + account + permit_name; - storage.set(storage_key.as_bytes(), &[]) + // Since cosmwasm V1.0 it's not possible to set an empty value, hence set some unimportant + // character '_' + // + // Here is the line of the new panic that was added when trying to insert an empty value: + // https://github.com/scrtlabs/cosmwasm/blob/f7e2b1dbf11e113e258d796288752503a5012367/packages/std/src/storage.rs#L30 + storage.set(storage_key.as_bytes(), "_".as_bytes()) } } diff --git a/packages/permit/src/structs.rs b/packages/permit/src/structs.rs index fc9f387..9c03c41 100644 --- a/packages/permit/src/structs.rs +++ b/packages/permit/src/structs.rs @@ -4,9 +4,9 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::pubkey_to_account; -use cosmwasm_std::{Binary, CanonicalAddr, HumanAddr, Uint128}; +use cosmwasm_std::{Binary, CanonicalAddr, Uint128}; -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct Permit { #[serde(bound = "")] @@ -15,8 +15,8 @@ pub struct Permit { } impl Permit { - pub fn check_token(&self, token: &HumanAddr) -> bool { - self.params.allowed_tokens.contains(token) + pub fn check_token(&self, token: &str) -> bool { + self.params.allowed_tokens.contains(&token.to_string()) } pub fn check_permission(&self, permission: &Permission) -> bool { @@ -24,24 +24,24 @@ impl Permit { } } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct PermitParams { - pub allowed_tokens: Vec, + pub allowed_tokens: Vec, pub permit_name: String, pub chain_id: String, #[serde(bound = "")] pub permissions: Vec, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct PermitSignature { pub pub_key: PubKey, pub signature: Binary, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct PubKey { /// ignored, but must be "tendermint/PubKeySecp256k1" otherwise the verification will fail @@ -58,7 +58,7 @@ impl PubKey { // Note: The order of fields in this struct is important for the permit signature verification! #[remain::sorted] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct SignedPermit { /// ignored @@ -91,7 +91,7 @@ impl SignedPermit { // Note: The order of fields in this struct is important for the permit signature verification! #[remain::sorted] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct Fee { pub amount: Vec, @@ -102,7 +102,7 @@ impl Fee { pub fn new() -> Self { Self { amount: vec![Coin::new()], - gas: Uint128(1), + gas: Uint128::new(1), } } } @@ -115,7 +115,7 @@ impl Default for Fee { // Note: The order of fields in this struct is important for the permit signature verification! #[remain::sorted] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct Coin { pub amount: Uint128, @@ -139,7 +139,7 @@ impl Default for Coin { // Note: The order of fields in this struct is important for the permit signature verification! #[remain::sorted] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct PermitMsg { pub r#type: String, @@ -158,10 +158,10 @@ impl PermitMsg { // Note: The order of fields in this struct is important for the permit signature verification! #[remain::sorted] -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub struct PermitContent { - pub allowed_tokens: Vec, + pub allowed_tokens: Vec, #[serde(bound = "")] pub permissions: Vec, pub permit_name: String, @@ -190,7 +190,7 @@ impl Permissions for T where { } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum TokenPermissions { /// Allowance for SNIP-20 - Permission to query allowance of the owner & spender diff --git a/packages/serialization/Cargo.toml b/packages/serialization/Cargo.toml index d6781e2..2f2a53e 100644 --- a/packages/serialization/Cargo.toml +++ b/packages/serialization/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "secret-toolkit-serialization" -version = "0.3.0" +version = "0.6.0" edition = "2018" authors = ["SCRT Labs "] license-file = "../../LICENSE" @@ -21,9 +21,9 @@ base64 = ["schemars"] [dependencies] serde = "1.0" bincode2 = { version = "2.0", optional = true } -schemars = { version = "0.7", optional = true } -cosmwasm-std = { package = "secret-cosmwasm-std", version = "0.10" } +schemars = { version = "0.8.1", optional = true } +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.0.0" } [dev-dependencies] serde_json = "1" -cosmwasm-schema = { version = "0.9.2" } +cosmwasm-schema = { version = "1.0" } diff --git a/packages/snip20/Cargo.toml b/packages/snip20/Cargo.toml index 160f817..034289b 100644 --- a/packages/snip20/Cargo.toml +++ b/packages/snip20/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "secret-toolkit-snip20" -version = "0.3.0" +version = "0.6.0" edition = "2018" authors = ["SCRT Labs "] license-file = "../../LICENSE" @@ -15,6 +15,6 @@ all-features = true [dependencies] serde = "1.0" -schemars = "0.7" -cosmwasm-std = { package = "secret-cosmwasm-std", version = "0.10" } -secret-toolkit-utils = { version = "0.3", path = "../utils" } +schemars = "0.8.1" +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.0.0" } +secret-toolkit-utils = { version = "0.6", path = "../utils" } diff --git a/packages/snip20/src/batch.rs b/packages/snip20/src/batch.rs index 41868f3..4be8566 100644 --- a/packages/snip20/src/batch.rs +++ b/packages/snip20/src/batch.rs @@ -1,18 +1,18 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use cosmwasm_std::{Binary, HumanAddr, Uint128}; +use cosmwasm_std::{Binary, Uint128}; -#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct TransferAction { - pub recipient: HumanAddr, + pub recipient: String, pub amount: Uint128, pub memo: Option, } impl TransferAction { - pub fn new(recipient: HumanAddr, amount: Uint128, memo: Option) -> Self { + pub fn new(recipient: String, amount: Uint128, memo: Option) -> Self { Self { recipient, amount, @@ -21,10 +21,10 @@ impl TransferAction { } } -#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct SendAction { - pub recipient: HumanAddr, + pub recipient: String, pub recipient_code_hash: Option, pub amount: Uint128, pub msg: Option, @@ -33,7 +33,7 @@ pub struct SendAction { impl SendAction { pub fn new( - recipient: HumanAddr, + recipient: String, amount: Uint128, msg: Option, memo: Option, @@ -48,7 +48,7 @@ impl SendAction { } pub fn new_with_code_hash( - recipient: HumanAddr, + recipient: String, recipient_code_hash: Option, amount: Uint128, msg: Option, @@ -64,22 +64,17 @@ impl SendAction { } } -#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct TransferFromAction { - pub owner: HumanAddr, - pub recipient: HumanAddr, + pub owner: String, + pub recipient: String, pub amount: Uint128, pub memo: Option, } impl TransferFromAction { - pub fn new( - owner: HumanAddr, - recipient: HumanAddr, - amount: Uint128, - memo: Option, - ) -> Self { + pub fn new(owner: String, recipient: String, amount: Uint128, memo: Option) -> Self { Self { owner, recipient, @@ -89,11 +84,11 @@ impl TransferFromAction { } } -#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct SendFromAction { - pub owner: HumanAddr, - pub recipient: HumanAddr, + pub owner: String, + pub recipient: String, pub recipient_code_hash: Option, pub amount: Uint128, pub msg: Option, @@ -102,8 +97,8 @@ pub struct SendFromAction { impl SendFromAction { pub fn new( - owner: HumanAddr, - recipient: HumanAddr, + owner: String, + recipient: String, amount: Uint128, msg: Option, memo: Option, @@ -119,8 +114,8 @@ impl SendFromAction { } pub fn new_with_code_hash( - owner: HumanAddr, - recipient: HumanAddr, + owner: String, + recipient: String, recipient_code_hash: Option, amount: Uint128, msg: Option, @@ -137,16 +132,16 @@ impl SendFromAction { } } -#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct MintAction { - pub recipient: HumanAddr, + pub recipient: String, pub amount: Uint128, pub memo: Option, } impl MintAction { - pub fn new(recipient: HumanAddr, amount: Uint128, memo: Option) -> Self { + pub fn new(recipient: String, amount: Uint128, memo: Option) -> Self { Self { recipient, amount, @@ -155,16 +150,16 @@ impl MintAction { } } -#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, PartialEq)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct BurnFromAction { - pub owner: HumanAddr, + pub owner: String, pub amount: Uint128, pub memo: Option, } impl BurnFromAction { - pub fn new(owner: HumanAddr, amount: Uint128, memo: Option) -> Self { + pub fn new(owner: String, amount: Uint128, memo: Option) -> Self { Self { owner, amount, diff --git a/packages/snip20/src/handle.rs b/packages/snip20/src/handle.rs index 4952d68..7d8cc09 100644 --- a/packages/snip20/src/handle.rs +++ b/packages/snip20/src/handle.rs @@ -1,6 +1,6 @@ use serde::Serialize; -use cosmwasm_std::{to_binary, Binary, Coin, CosmosMsg, HumanAddr, StdResult, Uint128, WasmMsg}; +use cosmwasm_std::{to_binary, Binary, Coin, CosmosMsg, StdResult, Uint128, WasmMsg}; use crate::batch::{ BurnFromAction, MintAction, SendAction, SendFromAction, TransferAction, TransferFromAction, @@ -8,7 +8,7 @@ use crate::batch::{ use secret_toolkit_utils::space_pad; /// SNIP20 token handle messages -#[derive(Serialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Clone, Debug, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum HandleMsg { // Native coin interactions @@ -25,13 +25,13 @@ pub enum HandleMsg { // Basic SNIP20 functions Transfer { - recipient: HumanAddr, + recipient: String, amount: Uint128, memo: Option, padding: Option, }, Send { - recipient: HumanAddr, + recipient: String, recipient_code_hash: Option, amount: Uint128, msg: Option, @@ -66,27 +66,27 @@ pub enum HandleMsg { // Allowance functions IncreaseAllowance { - spender: HumanAddr, + spender: String, amount: Uint128, expiration: Option, padding: Option, }, DecreaseAllowance { - spender: HumanAddr, + spender: String, amount: Uint128, expiration: Option, padding: Option, }, TransferFrom { - owner: HumanAddr, - recipient: HumanAddr, + owner: String, + recipient: String, amount: Uint128, memo: Option, padding: Option, }, SendFrom { - owner: HumanAddr, - recipient: HumanAddr, + owner: String, + recipient: String, recipient_code_hash: Option, amount: Uint128, msg: Option, @@ -102,7 +102,7 @@ pub enum HandleMsg { padding: Option, }, BurnFrom { - owner: HumanAddr, + owner: String, amount: Uint128, memo: Option, padding: Option, @@ -114,7 +114,7 @@ pub enum HandleMsg { // Mint Mint { - recipient: HumanAddr, + recipient: String, amount: Uint128, memo: Option, padding: Option, @@ -124,15 +124,15 @@ pub enum HandleMsg { padding: Option, }, AddMinters { - minters: Vec, + minters: Vec, padding: Option, }, RemoveMinters { - minters: Vec, + minters: Vec, padding: Option, }, SetMinters { - minters: Vec, + minters: Vec, padding: Option, }, } @@ -150,8 +150,8 @@ impl HandleMsg { pub fn to_cosmos_msg( &self, mut block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, send_amount: Option, ) -> StdResult { // can not have block size of 0 @@ -160,18 +160,18 @@ impl HandleMsg { } let mut msg = to_binary(self)?; space_pad(&mut msg.0, block_size); - let mut send = Vec::new(); + let mut funds = Vec::new(); if let Some(amount) = send_amount { - send.push(Coin { + funds.push(Coin { amount, denom: String::from("uscrt"), }); } let execute = WasmMsg::Execute { - msg, contract_addr, - callback_code_hash, - send, + code_hash, + msg, + funds, }; Ok(execute.into()) } @@ -193,7 +193,7 @@ pub fn redeem_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::Redeem { amount, @@ -217,7 +217,7 @@ pub fn deposit_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::Deposit { padding }.to_cosmos_msg( block_size, @@ -239,13 +239,13 @@ pub fn deposit_msg( /// * `callback_code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn transfer_msg( - recipient: HumanAddr, + recipient: String, amount: Uint128, memo: Option, padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::Transfer { recipient, @@ -271,14 +271,14 @@ pub fn transfer_msg( /// * `contract_addr` - address of the contract being called #[allow(clippy::too_many_arguments)] pub fn send_msg( - recipient: HumanAddr, + recipient: String, amount: Uint128, msg: Option, memo: Option, padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::Send { recipient, @@ -307,7 +307,7 @@ pub fn send_msg( /// * `contract_addr` - address of the contract being called #[allow(clippy::too_many_arguments)] pub fn send_msg_with_code_hash( - recipient: HumanAddr, + recipient: String, recipient_code_hash: Option, amount: Uint128, msg: Option, @@ -315,7 +315,7 @@ pub fn send_msg_with_code_hash( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::Send { recipient, @@ -341,7 +341,7 @@ pub fn batch_transfer_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::BatchTransfer { actions, padding }.to_cosmos_msg( block_size, @@ -364,7 +364,7 @@ pub fn batch_send_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::BatchSend { actions, padding }.to_cosmos_msg( block_size, @@ -390,7 +390,7 @@ pub fn burn_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::Burn { amount, @@ -413,7 +413,7 @@ pub fn create_viewing_key_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::CreateViewingKey { entropy, padding }.to_cosmos_msg( block_size, @@ -437,7 +437,7 @@ pub fn register_receive_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::RegisterReceive { code_hash: your_contracts_code_hash, @@ -460,7 +460,7 @@ pub fn set_viewing_key_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::SetViewingKey { key, padding }.to_cosmos_msg( block_size, @@ -482,13 +482,13 @@ pub fn set_viewing_key_msg( /// * `callback_code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn increase_allowance_msg( - spender: HumanAddr, + spender: String, amount: Uint128, expiration: Option, padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::IncreaseAllowance { spender, @@ -511,13 +511,13 @@ pub fn increase_allowance_msg( /// * `callback_code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn decrease_allowance_msg( - spender: HumanAddr, + spender: String, amount: Uint128, expiration: Option, padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::DecreaseAllowance { spender, @@ -542,14 +542,14 @@ pub fn decrease_allowance_msg( /// * `contract_addr` - address of the contract being called #[allow(clippy::too_many_arguments)] pub fn transfer_from_msg( - owner: HumanAddr, - recipient: HumanAddr, + owner: String, + recipient: String, amount: Uint128, memo: Option, padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::TransferFrom { owner, @@ -577,15 +577,15 @@ pub fn transfer_from_msg( /// * `contract_addr` - address of the contract being called #[allow(clippy::too_many_arguments)] pub fn send_from_msg( - owner: HumanAddr, - recipient: HumanAddr, + owner: String, + recipient: String, amount: Uint128, msg: Option, memo: Option, padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::SendFrom { owner, @@ -616,8 +616,8 @@ pub fn send_from_msg( /// * `contract_addr` - address of the contract being called #[allow(clippy::too_many_arguments)] pub fn send_from_msg_with_code_hash( - owner: HumanAddr, - recipient: HumanAddr, + owner: String, + recipient: String, recipient_code_hash: Option, amount: Uint128, msg: Option, @@ -625,7 +625,7 @@ pub fn send_from_msg_with_code_hash( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::SendFrom { owner, @@ -652,7 +652,7 @@ pub fn batch_transfer_from_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::BatchTransferFrom { actions, padding }.to_cosmos_msg( block_size, @@ -675,7 +675,7 @@ pub fn batch_send_from_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::BatchSendFrom { actions, padding }.to_cosmos_msg( block_size, @@ -697,13 +697,13 @@ pub fn batch_send_from_msg( /// * `callback_code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn burn_from_msg( - owner: HumanAddr, + owner: String, amount: Uint128, memo: Option, padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::BurnFrom { owner, @@ -727,7 +727,7 @@ pub fn batch_burn_from_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::BatchBurnFrom { actions, padding }.to_cosmos_msg( block_size, @@ -749,13 +749,13 @@ pub fn batch_burn_from_msg( /// * `callback_code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn mint_msg( - recipient: HumanAddr, + recipient: String, amount: Uint128, memo: Option, padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::Mint { recipient, @@ -779,7 +779,7 @@ pub fn batch_mint_msg( padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::BatchMint { actions, padding }.to_cosmos_msg( block_size, @@ -799,11 +799,11 @@ pub fn batch_mint_msg( /// * `callback_code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn add_minters_msg( - minters: Vec, + minters: Vec, padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::AddMinters { minters, padding }.to_cosmos_msg( block_size, @@ -823,11 +823,11 @@ pub fn add_minters_msg( /// * `callback_code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn remove_minters_msg( - minters: Vec, + minters: Vec, padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::RemoveMinters { minters, padding }.to_cosmos_msg( block_size, @@ -847,11 +847,11 @@ pub fn remove_minters_msg( /// * `callback_code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn set_minters_msg( - minters: Vec, + minters: Vec, padding: Option, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { HandleMsg::SetMinters { minters, padding }.to_cosmos_msg( block_size, diff --git a/packages/snip20/src/query.rs b/packages/snip20/src/query.rs index 93f0a6d..1e26099 100644 --- a/packages/snip20/src/query.rs +++ b/packages/snip20/src/query.rs @@ -3,13 +3,14 @@ use schemars::JsonSchema; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use cosmwasm_std::{ - to_binary, Coin, HumanAddr, Querier, QueryRequest, StdError, StdResult, Uint128, WasmQuery, + to_binary, Coin, CustomQuery, QuerierWrapper, QueryRequest, StdError, StdResult, Uint128, + WasmQuery, }; use secret_toolkit_utils::space_pad; /// TokenInfo response -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct TokenInfo { pub name: String, pub symbol: String, @@ -19,7 +20,7 @@ pub struct TokenInfo { } /// TokenConfig response -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct TokenConfig { pub public_total_supply: bool, pub deposit_enabled: bool, @@ -29,7 +30,7 @@ pub struct TokenConfig { } /// Contract status -#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] +#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, JsonSchema, Debug)] pub enum ContractStatusLevel { NormalRun, StopAllButRedeems, @@ -37,30 +38,30 @@ pub enum ContractStatusLevel { } /// ContractStatus Response -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct ContractStatus { pub status: ContractStatusLevel, } /// ExchangeRate response -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct ExchangeRate { pub rate: Uint128, pub denom: String, } /// Allowance response -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct Allowance { - pub spender: HumanAddr, - pub owner: HumanAddr, + pub spender: String, + pub owner: String, pub allowance: Uint128, #[serde(skip_serializing_if = "Option::is_none")] pub expiration: Option, } /// Balance response -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct Balance { pub amount: Uint128, } @@ -69,9 +70,9 @@ pub struct Balance { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Tx { pub id: u64, - pub from: HumanAddr, - pub sender: HumanAddr, - pub receiver: HumanAddr, + pub from: String, + pub sender: String, + pub receiver: String, pub coins: Coin, #[serde(skip_serializing_if = "Option::is_none")] pub memo: Option, @@ -89,21 +90,21 @@ pub struct TransferHistory { } /// Types of transactions for RichTx -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum TxAction { Transfer { - from: HumanAddr, - sender: HumanAddr, - recipient: HumanAddr, + from: String, + sender: String, + recipient: String, }, Mint { - minter: HumanAddr, - recipient: HumanAddr, + minter: String, + recipient: String, }, Burn { - burner: HumanAddr, - owner: HumanAddr, + burner: String, + owner: String, }, Deposit {}, Redeem {}, @@ -129,9 +130,9 @@ pub struct TransactionHistory { } /// Minters response -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct Minters { - pub minters: Vec, + pub minters: Vec, } /// SNIP20 queries @@ -143,22 +144,22 @@ pub enum QueryMsg { ContractStatus {}, ExchangeRate {}, Allowance { - owner: HumanAddr, - spender: HumanAddr, + owner: String, + spender: String, key: String, }, Balance { - address: HumanAddr, + address: String, key: String, }, TransferHistory { - address: HumanAddr, + address: String, key: String, page: Option, page_size: u32, }, TransactionHistory { - address: HumanAddr, + address: String, key: String, page: Option, page_size: u32, @@ -191,12 +192,12 @@ impl QueryMsg { /// * `block_size` - pad the message to blocks of this size /// * `callback_code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried - pub fn query( + pub fn query( &self, - querier: &Q, + querier: QuerierWrapper, mut block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { // can not have block size of 0 if block_size == 0 { @@ -207,7 +208,7 @@ impl QueryMsg { querier .query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr, - callback_code_hash, + code_hash, msg, })) .map_err(|err| { @@ -221,8 +222,8 @@ impl QueryMsg { #[serde(rename_all = "snake_case")] pub enum AuthenticatedQueryResponse { Allowance { - spender: HumanAddr, - owner: HumanAddr, + spender: String, + owner: String, allowance: Uint128, expiration: Option, }, @@ -280,11 +281,11 @@ pub struct MintersResponse { /// * `block_size` - pad the message to blocks of this size /// * `callback_code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn token_info_query( - querier: &Q, +pub fn token_info_query( + querier: QuerierWrapper, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { let answer: TokenInfoResponse = QueryMsg::TokenInfo {}.query(querier, block_size, callback_code_hash, contract_addr)?; @@ -299,11 +300,11 @@ pub fn token_info_query( /// * `block_size` - pad the message to blocks of this size /// * `callback_code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn token_config_query( - querier: &Q, +pub fn token_config_query( + querier: QuerierWrapper, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { let answer: TokenConfigResponse = QueryMsg::TokenConfig {}.query(querier, block_size, callback_code_hash, contract_addr)?; @@ -318,11 +319,11 @@ pub fn token_config_query( /// * `block_size` - pad the message to blocks of this size /// * `callback_code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn contract_status_query( - querier: &Q, +pub fn contract_status_query( + querier: QuerierWrapper, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { let answer: ContractStatusResponse = QueryMsg::ContractStatus {}.query( querier, @@ -341,11 +342,11 @@ pub fn contract_status_query( /// * `block_size` - pad the message to blocks of this size /// * `callback_code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn exchange_rate_query( - querier: &Q, +pub fn exchange_rate_query( + querier: QuerierWrapper, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { let answer: ExchangeRateResponse = QueryMsg::ExchangeRate {}.query(querier, block_size, callback_code_hash, contract_addr)?; @@ -364,14 +365,14 @@ pub fn exchange_rate_query( /// * `callback_code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried #[allow(clippy::too_many_arguments)] -pub fn allowance_query( - querier: &Q, - owner: HumanAddr, - spender: HumanAddr, +pub fn allowance_query( + querier: QuerierWrapper, + owner: String, + spender: String, key: String, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { let answer: AuthenticatedQueryResponse = QueryMsg::Allowance { owner, @@ -391,7 +392,9 @@ pub fn allowance_query( allowance, expiration, }), - AuthenticatedQueryResponse::ViewingKeyError { .. } => Err(StdError::unauthorized()), + AuthenticatedQueryResponse::ViewingKeyError { .. } => { + Err(StdError::generic_err("unaithorized")) + } _ => Err(StdError::generic_err("Invalid Allowance query response")), } } @@ -406,13 +409,13 @@ pub fn allowance_query( /// * `block_size` - pad the message to blocks of this size /// * `callback_code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn balance_query( - querier: &Q, - address: HumanAddr, +pub fn balance_query( + querier: QuerierWrapper, + address: String, key: String, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { let answer: AuthenticatedQueryResponse = QueryMsg::Balance { address, key }.query( querier, @@ -422,7 +425,9 @@ pub fn balance_query( )?; match answer { AuthenticatedQueryResponse::Balance { amount } => Ok(Balance { amount }), - AuthenticatedQueryResponse::ViewingKeyError { .. } => Err(StdError::unauthorized()), + AuthenticatedQueryResponse::ViewingKeyError { .. } => { + Err(StdError::generic_err("unaithorized")) + } _ => Err(StdError::generic_err("Invalid Balance query response")), } } @@ -440,15 +445,15 @@ pub fn balance_query( /// * `callback_code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried #[allow(clippy::too_many_arguments)] -pub fn transfer_history_query( - querier: &Q, - address: HumanAddr, +pub fn transfer_history_query( + querier: QuerierWrapper, + address: String, key: String, page: Option, page_size: u32, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { let answer: AuthenticatedQueryResponse = QueryMsg::TransferHistory { address, @@ -461,7 +466,9 @@ pub fn transfer_history_query( AuthenticatedQueryResponse::TransferHistory { txs, total } => { Ok(TransferHistory { txs, total }) } - AuthenticatedQueryResponse::ViewingKeyError { .. } => Err(StdError::unauthorized()), + AuthenticatedQueryResponse::ViewingKeyError { .. } => { + Err(StdError::generic_err("unaithorized")) + } _ => Err(StdError::generic_err( "Invalid TransferHistory query response", )), @@ -481,15 +488,15 @@ pub fn transfer_history_query( /// * `callback_code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried #[allow(clippy::too_many_arguments)] -pub fn transaction_history_query( - querier: &Q, - address: HumanAddr, +pub fn transaction_history_query( + querier: QuerierWrapper, + address: String, key: String, page: Option, page_size: u32, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { let answer: AuthenticatedQueryResponse = QueryMsg::TransactionHistory { address, @@ -502,7 +509,9 @@ pub fn transaction_history_query( AuthenticatedQueryResponse::TransactionHistory { txs, total } => { Ok(TransactionHistory { txs, total }) } - AuthenticatedQueryResponse::ViewingKeyError { .. } => Err(StdError::unauthorized()), + AuthenticatedQueryResponse::ViewingKeyError { .. } => { + Err(StdError::generic_err("unaithorized")) + } _ => Err(StdError::generic_err( "Invalid TransactionHistory query response", )), @@ -517,11 +526,11 @@ pub fn transaction_history_query( /// * `block_size` - pad the message to blocks of this size /// * `callback_code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn minters_query( - querier: &Q, +pub fn minters_query( + querier: QuerierWrapper, block_size: usize, callback_code_hash: String, - contract_addr: HumanAddr, + contract_addr: String, ) -> StdResult { let answer: MintersResponse = QueryMsg::Minters {}.query(querier, block_size, callback_code_hash, contract_addr)?; diff --git a/packages/snip721/Cargo.toml b/packages/snip721/Cargo.toml index 01aee26..9491535 100644 --- a/packages/snip721/Cargo.toml +++ b/packages/snip721/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "secret-toolkit-snip721" -version = "0.3.0" +version = "0.6.0" edition = "2018" authors = ["SCRT Labs "] license-file = "../../LICENSE" @@ -15,6 +15,6 @@ all-features = true [dependencies] serde = "1.0" -schemars = "0.7" -cosmwasm-std = { package = "secret-cosmwasm-std", version = "0.10" } -secret-toolkit-utils = { version = "0.3", path = "../utils" } +schemars = "0.8.1" +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.0.0" } +secret-toolkit-utils = { version = "0.6", path = "../utils" } diff --git a/packages/snip721/src/expiration.rs b/packages/snip721/src/expiration.rs index 263fb78..ac7855e 100644 --- a/packages/snip721/src/expiration.rs +++ b/packages/snip721/src/expiration.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use cosmwasm_std::BlockInfo; use std::fmt; -#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, JsonSchema, Debug)] +#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, JsonSchema, Debug)] #[serde(rename_all = "snake_case")] /// at the given point in time and after, Expiration will be considered expired pub enum Expiration { @@ -42,7 +42,8 @@ impl Expiration { pub fn is_expired(&self, block: &BlockInfo) -> bool { match self { Expiration::AtHeight(height) => block.height >= *height, - Expiration::AtTime(time) => block.time >= *time, + // When snip721 will be migrated, `time` might be a Timestamp. For now, just keeping it compatible + Expiration::AtTime(time) => block.time.seconds() >= *time, Expiration::Never => false, } } @@ -50,19 +51,21 @@ impl Expiration { #[cfg(test)] mod test { + use cosmwasm_std::Timestamp; + use super::*; #[test] fn test_expiration() { let block_h1000_t1000000 = BlockInfo { height: 1000, - time: 1000000, + time: Timestamp::from_seconds(1000000), chain_id: "test".to_string(), }; let block_h2000_t2000000 = BlockInfo { height: 2000, - time: 2000000, + time: Timestamp::from_seconds(2000000), chain_id: "test".to_string(), }; let exp_h1000 = Expiration::AtHeight(1000); diff --git a/packages/snip721/src/handle.rs b/packages/snip721/src/handle.rs index 431715e..48ca781 100644 --- a/packages/snip721/src/handle.rs +++ b/packages/snip721/src/handle.rs @@ -1,7 +1,7 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use cosmwasm_std::{to_binary, Binary, Coin, CosmosMsg, HumanAddr, StdResult, Uint128, WasmMsg}; +use cosmwasm_std::{to_binary, Binary, Coin, CosmosMsg, StdResult, Uint128, WasmMsg}; use crate::expiration::Expiration; use crate::metadata::Metadata; @@ -13,7 +13,7 @@ use secret_toolkit_utils::space_pad; // /// permission access level -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug)] #[serde(rename_all = "snake_case")] pub enum AccessLevel { /// approve permission only for the specified token @@ -32,12 +32,12 @@ pub enum AccessLevel { // /// token mint info used when doing a [`BatchMintNft`](HandleMsg::BatchMintNft) -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug)] pub struct Mint { /// optional token id. if omitted, use current token index pub token_id: Option, /// optional owner address. if omitted, owned by the message sender - pub owner: Option, + pub owner: Option, /// optional public metadata that can be seen by everyone pub public_metadata: Option, /// optional private metadata that can only be seen by the owner and whitelist @@ -47,7 +47,7 @@ pub struct Mint { } /// token burn info used when doing a [`BatchBurnNft`](HandleMsg::BatchBurnNft) -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug)] pub struct Burn { /// tokens being burnt pub token_ids: Vec, @@ -56,10 +56,10 @@ pub struct Burn { } /// token transfer info used when doing a [`BatchTransferNft`](HandleMsg::BatchTransferNft) -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug)] pub struct Transfer { /// recipient of the transferred tokens - pub recipient: HumanAddr, + pub recipient: String, /// tokens being transferred pub token_ids: Vec, /// optional memo for the tx @@ -67,10 +67,10 @@ pub struct Transfer { } /// send token info used when doing a [`BatchSendNft`](HandleMsg::BatchSendNft) -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug)] pub struct Send { /// recipient of the sent tokens - pub contract: HumanAddr, + pub contract: String, /// tokens being sent pub token_ids: Vec, /// optional message to send with the (Batch)RecieveNft callback @@ -80,7 +80,7 @@ pub struct Send { } /// SNIP-721 contract handle messages -#[derive(Serialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Clone, Debug, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum HandleMsg { // @@ -89,7 +89,7 @@ pub enum HandleMsg { /// transfer a token TransferNft { /// recipient of the transfer - recipient: HumanAddr, + recipient: String, /// id of the token to transfer token_id: String, /// optional memo for the tx @@ -100,7 +100,7 @@ pub enum HandleMsg { /// send a token and call receiving contract's (Batch)ReceiveNft SendNft { /// address to send the token to - contract: HumanAddr, + contract: String, /// id of the token to send token_id: String, /// optional message to send with the (Batch)RecieveNft callback @@ -115,7 +115,7 @@ pub enum HandleMsg { /// you are an operator, you can only use Approve Approve { /// address being granted the permission - spender: HumanAddr, + spender: String, /// id of the token that the spender can transfer token_id: String, /// optional expiration for this approval @@ -129,7 +129,7 @@ pub enum HandleMsg { /// of another operator Revoke { /// address whose permission is revoked - spender: HumanAddr, + spender: String, /// id of the token that the spender can no longer transfer token_id: String, /// optional message length padding @@ -139,7 +139,7 @@ pub enum HandleMsg { /// gives the operator permission to transfer all of the message sender's tokens ApproveAll { /// address being granted permission to transfer - operator: HumanAddr, + operator: String, /// optional expiration for this approval expires: Option, /// optional message length padding @@ -149,7 +149,7 @@ pub enum HandleMsg { /// revokes the operator's permission to transfer any of the message sender's tokens RevokeAll { /// address whose permissions are revoked - operator: HumanAddr, + operator: String, /// optional message length padding padding: Option, }, @@ -157,7 +157,7 @@ pub enum HandleMsg { /// that are omitted will keep the current permission setting for that whitelist address SetWhitelistedApproval { /// address being granted/revoked permission - address: HumanAddr, + address: String, /// optional token id to apply approval/revocation to token_id: Option, /// optional permission level for viewing the owner @@ -201,7 +201,7 @@ pub enum HandleMsg { /// optional token id. if omitted, uses current token index token_id: Option, /// optional owner address. if omitted, owned by the message sender - owner: Option, + owner: Option, /// optional public metadata that can be seen by everyone public_metadata: Option, /// optional private metadata that can only be seen by the owner and whitelist @@ -214,21 +214,21 @@ pub enum HandleMsg { /// add addresses with minting authority AddMinters { /// list of addresses that can now mint - minters: Vec, + minters: Vec, /// optional message length padding padding: Option, }, /// revoke minting authority from addresses RemoveMinters { /// list of addresses no longer allowed to mint - minters: Vec, + minters: Vec, /// optional message length padding padding: Option, }, /// define list of addresses with minting authority SetMinters { /// list of addresses with minting authority - minters: Vec, + minters: Vec, /// optional message length padding padding: Option, }, @@ -324,7 +324,7 @@ impl HandleMsg { /// # Arguments /// /// * `block_size` - pad the message to blocks of this size - /// * `callback_code_hash` - String holding the code hash of the contract being called + /// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called /// * `send_amount` - Optional Uint128 amount of native coin to send with the callback message /// NOTE: No SNIP721 messages send native coin, but the parameter is @@ -332,8 +332,8 @@ impl HandleMsg { pub fn to_cosmos_msg( &self, mut block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, send_amount: Option, ) -> StdResult { // can not have block size of 0 @@ -342,9 +342,9 @@ impl HandleMsg { } let mut msg = to_binary(self)?; space_pad(&mut msg.0, block_size); - let mut send = Vec::new(); + let mut funds = Vec::new(); if let Some(amount) = send_amount { - send.push(Coin { + funds.push(Coin { amount, denom: String::from("uscrt"), }); @@ -352,8 +352,8 @@ impl HandleMsg { let execute = WasmMsg::Execute { msg, contract_addr, - callback_code_hash, - send, + code_hash, + funds, }; Ok(execute.into()) } @@ -372,16 +372,16 @@ impl HandleMsg { /// * `memo` - Optional String memo for the tx /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn transfer_nft_msg( - recipient: HumanAddr, + recipient: String, token_id: String, memo: Option, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::TransferNft { recipient, @@ -389,7 +389,7 @@ pub fn transfer_nft_msg( memo, padding, } - .to_cosmos_msg(block_size, callback_code_hash, contract_addr, None) + .to_cosmos_msg(block_size, code_hash, contract_addr, None) } /// Returns a StdResult used to execute [`SendNft`](HandleMsg::SendNft) @@ -404,18 +404,18 @@ pub fn transfer_nft_msg( /// * `memo` - Optional String memo for the tx /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called #[allow(clippy::too_many_arguments)] pub fn send_nft_msg( - contract: HumanAddr, + contract: String, token_id: String, msg: Option, memo: Option, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::SendNft { contract, @@ -424,7 +424,7 @@ pub fn send_nft_msg( memo, padding, } - .to_cosmos_msg(block_size, callback_code_hash, contract_addr, None) + .to_cosmos_msg(block_size, code_hash, contract_addr, None) } /// Returns a StdResult used to execute [`Approve`](HandleMsg::Approve) @@ -436,16 +436,16 @@ pub fn send_nft_msg( /// * `expires` - Optional Expiration of this approval /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn approve_msg( - spender: HumanAddr, + spender: String, token_id: String, expires: Option, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::Approve { spender, @@ -453,7 +453,7 @@ pub fn approve_msg( expires, padding, } - .to_cosmos_msg(block_size, callback_code_hash, contract_addr, None) + .to_cosmos_msg(block_size, code_hash, contract_addr, None) } /// Returns a StdResult used to execute [`Revoke`](HandleMsg::Revoke) @@ -464,22 +464,22 @@ pub fn approve_msg( /// * `token_id` - ID String of the token that can no longer be transferred /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn revoke_msg( - spender: HumanAddr, + spender: String, token_id: String, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::Revoke { spender, token_id, padding, } - .to_cosmos_msg(block_size, callback_code_hash, contract_addr, None) + .to_cosmos_msg(block_size, code_hash, contract_addr, None) } /// Returns a StdResult used to execute [`ApproveAll`](HandleMsg::ApproveAll) @@ -490,22 +490,22 @@ pub fn revoke_msg( /// * `expires` - Optional Expiration of this approval /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn approve_all_msg( - operator: HumanAddr, + operator: String, expires: Option, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::ApproveAll { operator, expires, padding, } - .to_cosmos_msg(block_size, callback_code_hash, contract_addr, None) + .to_cosmos_msg(block_size, code_hash, contract_addr, None) } /// Returns a StdResult used to execute [`RevokeAll`](HandleMsg::RevokeAll) @@ -515,18 +515,18 @@ pub fn approve_all_msg( /// * `operator` - the address whose permission to transfer tokens is being revoked /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn revoke_all_msg( - operator: HumanAddr, + operator: String, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::RevokeAll { operator, padding }.to_cosmos_msg( block_size, - callback_code_hash, + code_hash, contract_addr, None, ) @@ -544,11 +544,11 @@ pub fn revoke_all_msg( /// * `expires` - Optional Expiration of any approvals in this message /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called #[allow(clippy::too_many_arguments)] pub fn set_whitelisted_approval_msg( - address: HumanAddr, + address: String, token_id: Option, view_owner: Option, view_private_metadata: Option, @@ -556,8 +556,8 @@ pub fn set_whitelisted_approval_msg( expires: Option, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::SetWhitelistedApproval { address, @@ -568,7 +568,7 @@ pub fn set_whitelisted_approval_msg( expires, padding, } - .to_cosmos_msg(block_size, callback_code_hash, contract_addr, None) + .to_cosmos_msg(block_size, code_hash, contract_addr, None) } /// Returns a StdResult used to execute [`RegisterReceiveNft`](HandleMsg::RegisterReceiveNft) @@ -580,22 +580,22 @@ pub fn set_whitelisted_approval_msg( /// implements BatchReceiveNft. Defaults to false if omitted /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn register_receive_nft_msg( your_contracts_code_hash: String, also_implements_batch_receive_nft: Option, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::RegisterReceiveNft { code_hash: your_contracts_code_hash, also_implements_batch_receive_nft, padding, } - .to_cosmos_msg(block_size, callback_code_hash, contract_addr, None) + .to_cosmos_msg(block_size, code_hash, contract_addr, None) } /// Returns a StdResult used to execute [`SetViewingKey`](HandleMsg::SetViewingKey) @@ -605,18 +605,18 @@ pub fn register_receive_nft_msg( /// * `key` - String holding the authentication key used for later queries /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn set_viewing_key_msg( key: String, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::SetViewingKey { key, padding }.to_cosmos_msg( block_size, - callback_code_hash, + code_hash, contract_addr, None, ) @@ -640,19 +640,19 @@ pub fn set_viewing_key_msg( /// * `memo` - Optional String memo for the tx /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called #[allow(clippy::too_many_arguments)] pub fn mint_nft_msg( token_id: Option, - owner: Option, + owner: Option, public_metadata: Option, private_metadata: Option, memo: Option, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::MintNft { token_id, @@ -662,7 +662,7 @@ pub fn mint_nft_msg( memo, padding, } - .to_cosmos_msg(block_size, callback_code_hash, contract_addr, None) + .to_cosmos_msg(block_size, code_hash, contract_addr, None) } /// Returns a StdResult used to execute [`AddMinters`](HandleMsg::AddMinters) @@ -672,18 +672,18 @@ pub fn mint_nft_msg( /// * `minters` - list of new addresses that will be allowed to mint /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn add_minters_msg( - minters: Vec, + minters: Vec, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::AddMinters { minters, padding }.to_cosmos_msg( block_size, - callback_code_hash, + code_hash, contract_addr, None, ) @@ -696,18 +696,18 @@ pub fn add_minters_msg( /// * `minters` - list of addresses that are no longer allowed to mint /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn remove_minters_msg( - minters: Vec, + minters: Vec, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::RemoveMinters { minters, padding }.to_cosmos_msg( block_size, - callback_code_hash, + code_hash, contract_addr, None, ) @@ -720,18 +720,18 @@ pub fn remove_minters_msg( /// * `minters` - list of the only addresses that are allowed to mint /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn set_minters_msg( - minters: Vec, + minters: Vec, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::SetMinters { minters, padding }.to_cosmos_msg( block_size, - callback_code_hash, + code_hash, contract_addr, None, ) @@ -746,7 +746,7 @@ pub fn set_minters_msg( /// * `private_metadata` - optional new Metadata that only the owner and whitelist can view /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn set_metadata_msg( token_id: String, @@ -754,8 +754,8 @@ pub fn set_metadata_msg( private_metadata: Option, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::SetMetadata { token_id, @@ -763,7 +763,7 @@ pub fn set_metadata_msg( private_metadata, padding, } - .to_cosmos_msg(block_size, callback_code_hash, contract_addr, None) + .to_cosmos_msg(block_size, code_hash, contract_addr, None) } // @@ -777,18 +777,18 @@ pub fn set_metadata_msg( /// * `mints` - list of mint operations to perform /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn batch_mint_nft_msg( mints: Vec, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::BatchMintNft { mints, padding }.to_cosmos_msg( block_size, - callback_code_hash, + code_hash, contract_addr, None, ) @@ -801,18 +801,18 @@ pub fn batch_mint_nft_msg( /// * `transfers` - list of Transfers to perform /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn batch_transfer_nft_msg( transfers: Vec, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::BatchTransferNft { transfers, padding }.to_cosmos_msg( block_size, - callback_code_hash, + code_hash, contract_addr, None, ) @@ -825,18 +825,18 @@ pub fn batch_transfer_nft_msg( /// * `sends` - list of Sends to perform /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn batch_send_nft_msg( sends: Vec, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::BatchSendNft { sends, padding }.to_cosmos_msg( block_size, - callback_code_hash, + code_hash, contract_addr, None, ) @@ -854,22 +854,22 @@ pub fn batch_send_nft_msg( /// * `memo` - Optional String memo for the tx /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn burn_nft_msg( token_id: String, memo: Option, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::BurnNft { token_id, memo, padding, } - .to_cosmos_msg(block_size, callback_code_hash, contract_addr, None) + .to_cosmos_msg(block_size, code_hash, contract_addr, None) } /// Returns a StdResult used to execute [`BatchBurnNft`](HandleMsg::BatchBurnNft) @@ -879,18 +879,18 @@ pub fn burn_nft_msg( /// * `burns` - list of Burns to perform /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn batch_burn_nft_msg( burns: Vec, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::BatchBurnNft { burns, padding }.to_cosmos_msg( block_size, - callback_code_hash, + code_hash, contract_addr, None, ) @@ -910,7 +910,7 @@ pub fn batch_burn_nft_msg( /// * `expires` - Optional Expiration of any approvals in this message /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called #[allow(clippy::too_many_arguments)] pub fn set_global_approval_msg( @@ -920,8 +920,8 @@ pub fn set_global_approval_msg( expires: Option, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::SetGlobalApproval { token_id, @@ -930,7 +930,7 @@ pub fn set_global_approval_msg( expires, padding, } - .to_cosmos_msg(block_size, callback_code_hash, contract_addr, None) + .to_cosmos_msg(block_size, code_hash, contract_addr, None) } // @@ -944,18 +944,18 @@ pub fn set_global_approval_msg( /// * `token_id` - ID String of the token to unwrap /// * `padding` - Optional String used as padding if you don't want to use block padding /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being called +/// * `code_hash` - String holding the code hash of the contract being called /// * `contract_addr` - address of the contract being called pub fn reveal_msg( token_id: String, padding: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { HandleMsg::Reveal { token_id, padding }.to_cosmos_msg( block_size, - callback_code_hash, + code_hash, contract_addr, None, ) @@ -969,12 +969,12 @@ mod tests { #[test] fn test_transfer_nft_msg() -> StdResult<()> { - let recipient = HumanAddr("alice".to_string()); + let recipient = "alice".to_string(); let token_id = "NFT1".to_string(); let memo = Some("memo".to_string()); let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = transfer_nft_msg( recipient.clone(), @@ -982,7 +982,7 @@ mod tests { memo.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::TransferNft { @@ -995,8 +995,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1004,13 +1004,13 @@ mod tests { #[test] fn test_send_nft_msg() -> StdResult<()> { - let contract = HumanAddr("alice".to_string()); - let recipient = HumanAddr("bob".to_string()); + let contract = "alice".to_string(); + let recipient = "bob".to_string(); let token_id = "NFT1".to_string(); let memo = Some("memo".to_string()); let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); // just using an arbitrary msg let send_msg = Some(to_binary(&HandleMsg::TransferNft { recipient, @@ -1025,7 +1025,7 @@ mod tests { memo.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::SendNft { @@ -1039,8 +1039,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1048,12 +1048,12 @@ mod tests { #[test] fn test_approve_msg() -> StdResult<()> { - let spender = HumanAddr("alice".to_string()); + let spender = "alice".to_string(); let token_id = "NFT1".to_string(); let expires = Some(Expiration::AtHeight(1000000)); let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = approve_msg( spender.clone(), @@ -1061,7 +1061,7 @@ mod tests { expires.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::Approve { @@ -1074,8 +1074,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1083,18 +1083,18 @@ mod tests { #[test] fn test_revoke_msg() -> StdResult<()> { - let spender = HumanAddr("alice".to_string()); + let spender = "alice".to_string(); let token_id = "NFT1".to_string(); let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = revoke_msg( spender.clone(), token_id.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::Revoke { @@ -1106,8 +1106,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1115,18 +1115,18 @@ mod tests { #[test] fn test_approve_all_msg() -> StdResult<()> { - let operator = HumanAddr("alice".to_string()); + let operator = "alice".to_string(); let expires = Some(Expiration::AtHeight(1000000)); let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = approve_all_msg( operator.clone(), expires.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::ApproveAll { @@ -1138,8 +1138,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1147,16 +1147,16 @@ mod tests { #[test] fn test_revoke_all_msg() -> StdResult<()> { - let operator = HumanAddr("alice".to_string()); + let operator = "alice".to_string(); let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = revoke_all_msg( operator.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::RevokeAll { operator, padding })?; @@ -1164,8 +1164,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1173,15 +1173,15 @@ mod tests { #[test] fn test_set_whitelisted_approval_msg() -> StdResult<()> { - let address = HumanAddr("alice".to_string()); + let address = "alice".to_string(); let token_id = Some("NFT1".to_string()); let view_owner = Some(AccessLevel::All); let view_private_metadata = None; let transfer = Some(AccessLevel::RevokeToken); let expires = Some(Expiration::AtTime(1000000000)); let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = set_whitelisted_approval_msg( address.clone(), @@ -1192,7 +1192,7 @@ mod tests { expires.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::SetWhitelistedApproval { @@ -1208,8 +1208,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1221,7 +1221,7 @@ mod tests { let also_implements_batch_receive_nft = Some(true); let padding = Some("padding".to_string()); let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let contract_addr = "contract".to_string(); let test_msg = register_receive_nft_msg( code_hash.clone(), @@ -1240,8 +1240,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash: callback_code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1251,14 +1251,14 @@ mod tests { fn test_set_viewing_key_msg() -> StdResult<()> { let key = "key".to_string(); let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = set_viewing_key_msg( key.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::SetViewingKey { key, padding })?; @@ -1266,8 +1266,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1275,7 +1275,7 @@ mod tests { #[test] fn test_mint_nft_msg() -> StdResult<()> { - let owner = Some(HumanAddr("alice".to_string())); + let owner = Some("alice".to_string()); let token_id = Some("NFT1".to_string()); let public_metadata = Some(Metadata { token_uri: Some("token uri".to_string()), @@ -1321,8 +1321,8 @@ mod tests { }); let memo = Some("memo".to_string()); let padding = None; - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = mint_nft_msg( token_id.clone(), @@ -1332,7 +1332,7 @@ mod tests { memo.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::MintNft { @@ -1347,8 +1347,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1356,16 +1356,16 @@ mod tests { #[test] fn test_add_minters_msg() -> StdResult<()> { - let minters = vec![HumanAddr("alice".to_string()), HumanAddr("bob".to_string())]; + let minters = vec!["alice".to_string(), "bob".to_string()]; let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = add_minters_msg( minters.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::AddMinters { minters, padding })?; @@ -1373,8 +1373,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1383,19 +1383,19 @@ mod tests { #[test] fn test_remove_minters_msg() -> StdResult<()> { let minters = vec![ - HumanAddr("alice".to_string()), - HumanAddr("bob".to_string()), - HumanAddr("charlie".to_string()), + "alice".to_string(), + "bob".to_string(), + "charlie".to_string(), ]; let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = remove_minters_msg( minters.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::RemoveMinters { minters, padding })?; @@ -1403,8 +1403,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1413,19 +1413,19 @@ mod tests { #[test] fn test_set_minters_msg() -> StdResult<()> { let minters = vec![ - HumanAddr("alice".to_string()), - HumanAddr("bob".to_string()), - HumanAddr("charlie".to_string()), + "alice".to_string(), + "bob".to_string(), + "charlie".to_string(), ]; let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = set_minters_msg( minters.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::SetMinters { minters, padding })?; @@ -1433,8 +1433,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1486,8 +1486,8 @@ mod tests { }), }); let padding = None; - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = set_metadata_msg( token_id.clone(), @@ -1495,7 +1495,7 @@ mod tests { private_metadata.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::SetMetadata { @@ -1508,8 +1508,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1520,7 +1520,7 @@ mod tests { let mints = vec![ Mint { token_id: None, - owner: Some(HumanAddr("alice".to_string())), + owner: Some("alice".to_string()), public_metadata: Some(Metadata { token_uri: Some("token uri".to_string()), extension: Some(Extension { @@ -1594,7 +1594,7 @@ mod tests { }, Mint { token_id: Some("NFT3".to_string()), - owner: Some(HumanAddr("bob".to_string())), + owner: Some("bob".to_string()), public_metadata: None, private_metadata: Some(Metadata { token_uri: Some("token uri3".to_string()), @@ -1621,14 +1621,14 @@ mod tests { }, ]; let padding = None; - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = batch_mint_nft_msg( mints.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::BatchMintNft { mints, padding })?; @@ -1636,8 +1636,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1647,25 +1647,25 @@ mod tests { fn test_batch_transfer_nft_msg() -> StdResult<()> { let transfers = vec![ Transfer { - recipient: HumanAddr("alice".to_string()), + recipient: "alice".to_string(), token_ids: vec!["NFT1".to_string()], memo: Some("memo 1".to_string()), }, Transfer { - recipient: HumanAddr("bob".to_string()), + recipient: "bob".to_string(), token_ids: vec!["NFT2".to_string(), "NFT3".to_string(), "NFT4".to_string()], memo: None, }, ]; let padding = None; - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = batch_transfer_nft_msg( transfers.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::BatchTransferNft { transfers, padding })?; @@ -1673,8 +1673,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1684,10 +1684,10 @@ mod tests { fn test_batch_send_nft_msg() -> StdResult<()> { let sends = vec![ Send { - contract: HumanAddr("alice".to_string()), + contract: "alice".to_string(), token_ids: vec!["NFT1".to_string()], msg: Some(to_binary(&HandleMsg::TransferNft { - recipient: HumanAddr("bob".to_string()), + recipient: "bob".to_string(), token_id: "NFT1".to_string(), memo: Some("send msg memo".to_string()), padding: None, @@ -1695,21 +1695,21 @@ mod tests { memo: Some("memo 1".to_string()), }, Send { - contract: HumanAddr("bob".to_string()), + contract: "bob".to_string(), token_ids: vec!["NFT2".to_string(), "NFT3".to_string(), "NFT4".to_string()], msg: None, memo: None, }, ]; let padding = None; - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = batch_send_nft_msg( sends.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::BatchSendNft { sends, padding })?; @@ -1717,8 +1717,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1729,15 +1729,15 @@ mod tests { let token_id = "NFT1".to_string(); let memo = Some("memo".to_string()); let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = burn_nft_msg( token_id.clone(), memo.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::BurnNft { @@ -1749,8 +1749,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1769,14 +1769,14 @@ mod tests { }, ]; let padding = None; - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = batch_burn_nft_msg( burns.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::BatchBurnNft { burns, padding })?; @@ -1784,8 +1784,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1798,8 +1798,8 @@ mod tests { let view_private_metadata = None; let expires = Some(Expiration::AtTime(1000000000)); let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = set_global_approval_msg( token_id.clone(), @@ -1808,7 +1808,7 @@ mod tests { expires.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::SetGlobalApproval { @@ -1822,8 +1822,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) @@ -1833,14 +1833,14 @@ mod tests { fn test_reveal_msg() -> StdResult<()> { let token_id = "NFT1".to_string(); let padding = Some("padding".to_string()); - let callback_code_hash = "code hash".to_string(); - let contract_addr = HumanAddr("contract".to_string()); + let code_hash = "code hash".to_string(); + let contract_addr = "contract".to_string(); let test_msg = reveal_msg( token_id.clone(), padding.clone(), 256usize, - callback_code_hash.clone(), + code_hash.clone(), contract_addr.clone(), )?; let mut msg = to_binary(&HandleMsg::Reveal { token_id, padding })?; @@ -1848,8 +1848,8 @@ mod tests { let expected_msg = CosmosMsg::Wasm(WasmMsg::Execute { msg: Binary(msg.to_vec()), contract_addr, - callback_code_hash, - send: vec![], + code_hash, + funds: vec![], }); assert_eq!(test_msg, expected_msg); Ok(()) diff --git a/packages/snip721/src/metadata.rs b/packages/snip721/src/metadata.rs index 6a7d491..7b0355c 100644 --- a/packages/snip721/src/metadata.rs +++ b/packages/snip721/src/metadata.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; // /// token metadata -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug, Default)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug, Default)] pub struct Metadata { /// optional uri for off-chain metadata. This should be prefixed with `http://`, `https://`, `ipfs://`, or /// `ar://`. Only use this if you are not using `extension` @@ -19,7 +19,7 @@ pub struct Metadata { /// and are the metadata fields that /// Stashh uses for robust NFT display. Urls should be prefixed with `http://`, `https://`, `ipfs://`, or /// `ar://` -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug, Default)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug, Default)] pub struct Extension { /// url to the image pub image: Option, @@ -49,7 +49,7 @@ pub struct Extension { } /// attribute trait -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug, Default)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug, Default)] pub struct Trait { /// indicates how a trait should be displayed pub display_type: Option, @@ -62,7 +62,7 @@ pub struct Trait { } /// media file -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug, Default)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug, Default)] pub struct MediaFile { /// file type /// Stashh currently uses: "image", "video", "audio", "text", "font", "application" @@ -76,7 +76,7 @@ pub struct MediaFile { } /// media file authentication -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug, Default)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug, Default)] pub struct Authentication { /// either a decryption key for encrypted files or a password for basic authentication pub key: Option, diff --git a/packages/snip721/src/query.rs b/packages/snip721/src/query.rs index 42a89be..96d69ea 100644 --- a/packages/snip721/src/query.rs +++ b/packages/snip721/src/query.rs @@ -2,7 +2,9 @@ use core::fmt; use schemars::JsonSchema; use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use cosmwasm_std::{to_binary, HumanAddr, Querier, QueryRequest, StdError, StdResult, WasmQuery}; +use cosmwasm_std::{ + to_binary, CustomQuery, QuerierWrapper, QueryRequest, StdError, StdResult, WasmQuery, +}; use crate::expiration::Expiration; use crate::metadata::Metadata; @@ -13,10 +15,10 @@ use secret_toolkit_utils::space_pad; // /// the address and viewing key making an authenticated query request -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct ViewerInfo { /// querying address - pub address: HumanAddr, + pub address: String, /// authentication key string pub viewing_key: String, } @@ -28,7 +30,7 @@ pub struct ViewerInfo { /// [`ContractInfo`](QueryMsg::ContractInfo) response /// /// display the contract's name and symbol -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct ContractInfo { pub name: String, pub symbol: String, @@ -38,7 +40,7 @@ pub struct ContractInfo { /// /// display the number of tokens controlled by the contract. The token supply must /// either be public, or the querier must be authorized to view -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct NumTokens { pub count: u32, } @@ -51,17 +53,17 @@ pub struct NumTokens { /// * Tokens: /// displays a list of all the tokens belonging to the input owner in which the viewer /// has view_owner permission -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct TokenList { /// list of token IDs pub tokens: Vec, } /// CW-721 Approval -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct Cw721Approval { /// address that can transfer the token - pub spender: HumanAddr, + pub spender: String, /// expiration of this approval pub expires: Expiration, } @@ -72,10 +74,10 @@ pub struct Cw721Approval { /// is also the token's owner, the response will also include a list of any addresses /// that can transfer this token. The transfer approval list is for CW721 compliance, /// but the [`NftDossier`](QueryMsg::NftDossier) query will be more complete by showing viewing approvals as well -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct OwnerOf { /// Owner of the token if permitted to view it - pub owner: Option, + pub owner: Option, /// list of addresses approved to transfer this token pub approvals: Vec, } @@ -83,7 +85,7 @@ pub struct OwnerOf { /// response of [`AllNftInfo`](QueryMsg::AllNftInfo) /// /// displays all the information contained in the [`OwnerOf`](QueryMsg::OwnerOf) and [`NftInfo`](QueryMsg::NftInfo) queries -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct AllNftInfo { /// OwnerOf response pub access: OwnerOf, @@ -92,10 +94,10 @@ pub struct AllNftInfo { } /// SNIP721 Approval -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct Snip721Approval { /// whitelisted address - pub address: HumanAddr, + pub address: String, /// optional expiration if the address has view owner permission pub view_owner_expiration: Option, /// optional expiration if the address has view private metadata permission @@ -109,10 +111,10 @@ pub struct Snip721Approval { /// displays all the information about a token that the viewer has permission to /// see. This may include the owner, the public metadata, the private metadata, and /// the token and inventory approvals -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct NftDossier { /// owner of the token if permitted to view it - pub owner: Option, + pub owner: Option, /// the token's public metadata pub public_metadata: Option, /// the token's private metadata if permitted to view it @@ -138,7 +140,7 @@ pub struct NftDossier { /// /// list all the [`Approvals`](Snip721Approval) in place for a specified token if given the owner's viewing /// key -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct TokenApprovals { /// true if the owner is publicly viewable pub owner_is_public: bool, @@ -158,7 +160,7 @@ pub struct TokenApprovals { /// approval to transfer all of the owner's tokens). This query is provided to maintain /// CW-721 compliance, however, approvals are private on secret network, so only the /// owner's viewing key will authorize the ability to see the list of operators -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct ApprovedForAll { pub operators: Vec, } @@ -167,7 +169,7 @@ pub struct ApprovedForAll { /// /// list all the inventory-wide [`Approvals`](Snip721Approval) in place for the specified address if given the /// the correct viewing key for the address -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct InventoryApprovals { /// true if the owner is publicly viewable pub owner_is_public: bool, @@ -182,36 +184,36 @@ pub struct InventoryApprovals { } /// tx type and specifics -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug)] #[serde(rename_all = "snake_case")] pub enum TxAction { /// transferred token ownership Transfer { /// previous owner - from: HumanAddr, + from: String, /// optional sender if not owner - sender: Option, + sender: Option, /// new owner - recipient: HumanAddr, + recipient: String, }, /// minted new token Mint { /// minter's address - minter: HumanAddr, + minter: String, /// token's first owner - recipient: HumanAddr, + recipient: String, }, /// burned a token Burn { /// previous owner - owner: HumanAddr, + owner: String, /// burner's address if not owner - burner: Option, + burner: Option, }, } /// tx for display -#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] +#[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Eq, Debug)] #[serde(rename_all = "snake_case")] pub struct Tx { /// tx id @@ -232,7 +234,7 @@ pub struct Tx { /// /// display the transaction history for the specified address in reverse /// chronological order -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct TransactionHistory { /// total transaction count pub total: u64, @@ -247,15 +249,15 @@ pub struct TransactionHistory { /// response of [`Minters`](QueryMsg::Minters) /// /// display the list of authorized minters -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct Minters { - pub minters: Vec, + pub minters: Vec, } /// response of [`IsUnwrapped`](QueryMsg::IsUnwrapped) /// /// display if a token is unwrapped -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct IsUnwrapped { pub token_is_unwrapped: bool, } @@ -263,7 +265,7 @@ pub struct IsUnwrapped { /// response of [`VerifyTransferApproval`](QueryMsg::VerifyTransferApproval) /// /// verify that the specified address has approval to transfer every listed token -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] pub struct VerifyTransferApproval { /// true if `address` has transfer approval for all tokens in the list pub approved_for_all: bool, @@ -272,7 +274,7 @@ pub struct VerifyTransferApproval { } /// SNIP-721 queries -#[derive(Serialize, Clone, Debug, PartialEq)] +#[derive(Serialize, Clone, Debug, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum QueryMsg { // @@ -352,7 +354,7 @@ pub enum QueryMsg { /// CW-721 compliance, however, approvals are private on secret network, so only the /// owner's viewing key will authorize the ability to see the list of operators ApprovedForAll { - owner: HumanAddr, + owner: String, /// optional viewing key to authenticate this query. It is "optional" only in the /// sense that a CW721 query does not have this field. However, not providing the /// key will always result in an empty list @@ -364,7 +366,7 @@ pub enum QueryMsg { /// list all the inventory-wide [`Approvals`](Snip721Approval) in place for the specified address if given the /// the correct viewing key for the address InventoryApprovals { - address: HumanAddr, + address: String, /// the viewing key viewing_key: String, /// optionally include expired [`Approvals`](Snip721Approval) in the response list. If ommitted or @@ -374,9 +376,9 @@ pub enum QueryMsg { /// displays a list of all the tokens belonging to the input owner in which the viewer /// has view_owner permission Tokens { - owner: HumanAddr, + owner: String, /// optional address of the querier if different from the owner - viewer: Option, + viewer: Option, /// optional viewing key viewing_key: Option, /// optionally display only token ids that come after the input String in @@ -388,7 +390,7 @@ pub enum QueryMsg { /// display the transaction history for the specified address in reverse /// chronological order TransactionHistory { - address: HumanAddr, + address: String, /// viewing key viewing_key: String, /// optional page to display @@ -409,7 +411,7 @@ pub enum QueryMsg { /// list of tokens to verify approval for token_ids: Vec, /// address that has approval - address: HumanAddr, + address: String, /// viewing key viewing_key: String, }, @@ -445,14 +447,14 @@ impl QueryMsg { /// /// * `querier` - a reference to the Querier dependency of the querying contract /// * `block_size` - pad the message to blocks of this size - /// * `callback_code_hash` - String holding the code hash of the contract being queried + /// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried - pub fn query( + pub fn query( &self, - querier: &Q, + querier: QuerierWrapper, mut block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { // can not have block size of 0 if block_size == 0 { @@ -463,7 +465,7 @@ impl QueryMsg { querier .query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr, - callback_code_hash, + code_hash, msg, })) .map_err(|err| { @@ -568,16 +570,16 @@ pub struct VerifyTransferApprovalResponse { /// /// * `querier` - a reference to the Querier dependency of the querying contract /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn contract_info_query( - querier: &Q, +pub fn contract_info_query( + querier: QuerierWrapper, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: ContractInfoResponse = - QueryMsg::ContractInfo {}.query(querier, block_size, callback_code_hash, contract_addr)?; + QueryMsg::ContractInfo {}.query(querier, block_size, code_hash, contract_addr)?; Ok(answer.contract_info) } @@ -588,21 +590,17 @@ pub fn contract_info_query( /// * `querier` - a reference to the Querier dependency of the querying contract /// * `viewer` - Optional ViewerInfo holding the address and viewing key of the querier /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn num_tokens_query( - querier: &Q, +pub fn num_tokens_query( + querier: QuerierWrapper, viewer: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { - let answer: NumTokensResponse = QueryMsg::NumTokens { viewer }.query( - querier, - block_size, - callback_code_hash, - contract_addr, - )?; + let answer: NumTokensResponse = + QueryMsg::NumTokens { viewer }.query(querier, block_size, code_hash, contract_addr)?; Ok(answer.num_tokens) } @@ -616,23 +614,23 @@ pub fn num_tokens_query( /// lexicographical order /// * `limit` - Optional u32 number of token ids to display /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn all_tokens_query( - querier: &Q, +pub fn all_tokens_query( + querier: QuerierWrapper, viewer: Option, start_after: Option, limit: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: TokenListResponse = QueryMsg::AllTokens { viewer, start_after, limit, } - .query(querier, block_size, callback_code_hash, contract_addr)?; + .query(querier, block_size, code_hash, contract_addr)?; Ok(answer.token_list) } @@ -647,23 +645,23 @@ pub fn all_tokens_query( /// ommitted or false, expired Approvals will be filtered out of /// the response /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn owner_of_query( - querier: &Q, +pub fn owner_of_query( + querier: QuerierWrapper, token_id: String, viewer: Option, include_expired: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: OwnerOfResponse = QueryMsg::OwnerOf { token_id, viewer, include_expired, } - .query(querier, block_size, callback_code_hash, contract_addr)?; + .query(querier, block_size, code_hash, contract_addr)?; Ok(answer.owner_of) } @@ -674,21 +672,17 @@ pub fn owner_of_query( /// * `querier` - a reference to the Querier dependency of the querying contract /// * `token_id` - ID of the token whose info is being requested /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn nft_info_query( - querier: &Q, +pub fn nft_info_query( + querier: QuerierWrapper, token_id: String, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { - let answer: NftInfoResponse = QueryMsg::NftInfo { token_id }.query( - querier, - block_size, - callback_code_hash, - contract_addr, - )?; + let answer: NftInfoResponse = + QueryMsg::NftInfo { token_id }.query(querier, block_size, code_hash, contract_addr)?; Ok(answer.nft_info) } @@ -703,23 +697,23 @@ pub fn nft_info_query( /// ommitted or false, expired Approvals will be filtered out of /// the response /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn all_nft_info_query( - querier: &Q, +pub fn all_nft_info_query( + querier: QuerierWrapper, token_id: String, viewer: Option, include_expired: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: AllNftInfoResponse = QueryMsg::AllNftInfo { token_id, viewer, include_expired, } - .query(querier, block_size, callback_code_hash, contract_addr)?; + .query(querier, block_size, code_hash, contract_addr)?; Ok(answer.all_nft_info) } @@ -731,20 +725,20 @@ pub fn all_nft_info_query( /// * `token_id` - ID of the token whose info is being requested /// * `viewer` - Optional ViewerInfo holding the address and viewing key of the querier /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn private_metadata_query( - querier: &Q, +pub fn private_metadata_query( + querier: QuerierWrapper, token_id: String, viewer: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: PrivateMetadataResponse = QueryMsg::PrivateMetadata { token_id, viewer }.query( querier, block_size, - callback_code_hash, + code_hash, contract_addr, )?; Ok(answer.private_metadata) @@ -761,23 +755,23 @@ pub fn private_metadata_query( /// ommitted or false, expired Approvals will be filtered out of /// the response /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn nft_dossier_query( - querier: &Q, +pub fn nft_dossier_query( + querier: QuerierWrapper, token_id: String, viewer: Option, include_expired: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: NftDossierResponse = QueryMsg::NftDossier { token_id, viewer, include_expired, } - .query(querier, block_size, callback_code_hash, contract_addr)?; + .query(querier, block_size, code_hash, contract_addr)?; Ok(answer.nft_dossier) } @@ -792,23 +786,23 @@ pub fn nft_dossier_query( /// ommitted or false, expired Approvals will be filtered out of /// the response /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn token_approvals_query( - querier: &Q, +pub fn token_approvals_query( + querier: QuerierWrapper, token_id: String, viewing_key: String, include_expired: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: TokenApprovalsResponse = QueryMsg::TokenApprovals { token_id, viewing_key, include_expired, } - .query(querier, block_size, callback_code_hash, contract_addr)?; + .query(querier, block_size, code_hash, contract_addr)?; Ok(answer.token_approvals) } @@ -823,23 +817,23 @@ pub fn token_approvals_query( /// ommitted or false, expired Approvals will be filtered out of /// the response /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn approved_for_all_query( - querier: &Q, - owner: HumanAddr, +pub fn approved_for_all_query( + querier: QuerierWrapper, + owner: String, viewing_key: Option, include_expired: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: ApprovedForAllResponse = QueryMsg::ApprovedForAll { owner, viewing_key, include_expired, } - .query(querier, block_size, callback_code_hash, contract_addr)?; + .query(querier, block_size, code_hash, contract_addr)?; Ok(answer.approved_for_all) } @@ -854,23 +848,23 @@ pub fn approved_for_all_query( /// ommitted or false, expired Approvals will be filtered out of /// the response /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn inventory_approvals_query( - querier: &Q, - address: HumanAddr, +pub fn inventory_approvals_query( + querier: QuerierWrapper, + address: String, viewing_key: String, include_expired: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: InventoryApprovalsResponse = QueryMsg::InventoryApprovals { address, viewing_key, include_expired, } - .query(querier, block_size, callback_code_hash, contract_addr)?; + .query(querier, block_size, code_hash, contract_addr)?; Ok(answer.inventory_approvals) } @@ -886,19 +880,19 @@ pub fn inventory_approvals_query( /// lexicographical order /// * `limit` - Optional u32 number of token ids to display /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried #[allow(clippy::too_many_arguments)] -pub fn tokens_query( - querier: &Q, - owner: HumanAddr, - viewer: Option, +pub fn tokens_query( + querier: QuerierWrapper, + owner: String, + viewer: Option, viewing_key: Option, start_after: Option, limit: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: TokenListResponse = QueryMsg::Tokens { owner, @@ -907,7 +901,7 @@ pub fn tokens_query( start_after, limit, } - .query(querier, block_size, callback_code_hash, contract_addr)?; + .query(querier, block_size, code_hash, contract_addr)?; Ok(answer.token_list) } @@ -921,18 +915,18 @@ pub fn tokens_query( /// * `page` - Optional u32 representing the page number of transactions to display /// * `page_size` - Optional u32 number of transactions to return /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried #[allow(clippy::too_many_arguments)] -pub fn transaction_history_query( - querier: &Q, - address: HumanAddr, +pub fn transaction_history_query( + querier: QuerierWrapper, + address: String, viewing_key: String, page: Option, page_size: Option, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: TransactionHistoryResponse = QueryMsg::TransactionHistory { address, @@ -940,7 +934,7 @@ pub fn transaction_history_query( page, page_size, } - .query(querier, block_size, callback_code_hash, contract_addr)?; + .query(querier, block_size, code_hash, contract_addr)?; Ok(answer.transaction_history) } @@ -950,16 +944,16 @@ pub fn transaction_history_query( /// /// * `querier` - a reference to the Querier dependency of the querying contract /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn minters_query( - querier: &Q, +pub fn minters_query( + querier: QuerierWrapper, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: MintersResponse = - QueryMsg::Minters {}.query(querier, block_size, callback_code_hash, contract_addr)?; + QueryMsg::Minters {}.query(querier, block_size, code_hash, contract_addr)?; Ok(answer.minters) } @@ -970,21 +964,17 @@ pub fn minters_query( /// * `querier` - a reference to the Querier dependency of the querying contract /// * `token_id` - ID of the token whose info is being requested /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn is_unwrapped_query( - querier: &Q, +pub fn is_unwrapped_query( + querier: QuerierWrapper, token_id: String, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { - let answer: IsUnwrappedResponse = QueryMsg::IsUnwrapped { token_id }.query( - querier, - block_size, - callback_code_hash, - contract_addr, - )?; + let answer: IsUnwrappedResponse = + QueryMsg::IsUnwrapped { token_id }.query(querier, block_size, code_hash, contract_addr)?; Ok(answer.is_unwrapped) } @@ -997,23 +987,23 @@ pub fn is_unwrapped_query( /// * `address` - address that has transfer approval /// * `viewing_key` - String holding the address' viewing key /// * `block_size` - pad the message to blocks of this size -/// * `callback_code_hash` - String holding the code hash of the contract being queried +/// * `code_hash` - String holding the code hash of the contract being queried /// * `contract_addr` - address of the contract being queried -pub fn verify_transfer_approval_query( - querier: &Q, +pub fn verify_transfer_approval_query( + querier: QuerierWrapper, token_ids: Vec, - address: HumanAddr, + address: String, viewing_key: String, block_size: usize, - callback_code_hash: String, - contract_addr: HumanAddr, + code_hash: String, + contract_addr: String, ) -> StdResult { let answer: VerifyTransferApprovalResponse = QueryMsg::VerifyTransferApproval { token_ids, address, viewing_key, } - .query(querier, block_size, callback_code_hash, contract_addr)?; + .query(querier, block_size, code_hash, contract_addr)?; Ok(answer.verify_transfer_approval) } @@ -1022,7 +1012,18 @@ mod tests { use crate::{Extension, Trait}; use super::*; - use cosmwasm_std::{to_vec, QuerierResult, SystemError}; + use cosmwasm_std::{ + to_vec, ContractResult, Empty, Querier, QuerierResult, SystemError, SystemResult, + }; + + macro_rules! try_querier_result { + ($result: expr) => { + match $result { + std::result::Result::Ok(ok) => ok, + std::result::Result::Err(err) => return cosmwasm_std::QuerierResult::Err(err), + } + }; + } #[test] fn test_contract_info_query() -> StdResult<()> { @@ -1030,17 +1031,20 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { - let mut expected_msg = - to_binary(&QueryMsg::ContractInfo {}).map_err(|_e| SystemError::Unknown {})?; + let mut expected_msg = try_querier_result!( + to_binary(&QueryMsg::ContractInfo {}).map_err(|_e| SystemError::Unknown {}) + ); + space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = ContractInfoResponse { contract_info: ContractInfo { @@ -1048,12 +1052,14 @@ mod tests { symbol: "NFTS".to_string(), }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let expected_response = ContractInfo { @@ -1061,7 +1067,7 @@ mod tests { symbol: "NFTS".to_string(), }; - let response = contract_info_query(&querier, 256usize, hash, address)?; + let response = contract_info_query(querier, 256usize, hash, address)?; assert_eq!(response, expected_response); Ok(()) @@ -1074,42 +1080,46 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); - let mut expected_msg = to_binary(&QueryMsg::NumTokens { viewer }) - .map_err(|_e| SystemError::Unknown {})?; + let mut expected_msg = + try_querier_result!(to_binary(&QueryMsg::NumTokens { viewer }) + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = NumTokensResponse { num_tokens: NumTokens { count: 32 }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); let expected_response = NumTokens { count: 32 }; - let response = num_tokens_query(&querier, viewer, 256usize, hash, address)?; + let response = num_tokens_query(querier, viewer, 256usize, hash, address)?; assert_eq!(response, expected_response); Ok(()) @@ -1122,27 +1132,28 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); let start_after = Some("NFT1".to_string()); let limit = None; - let mut expected_msg = to_binary(&QueryMsg::AllTokens { + let mut expected_msg = try_querier_result!(to_binary(&QueryMsg::AllTokens { viewer, start_after, limit, }) - .map_err(|_e| SystemError::Unknown {})?; + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = TokenListResponse { @@ -1150,16 +1161,18 @@ mod tests { tokens: vec!["NFT2".to_string(), "NFT3".to_string(), "NFT4".to_string()], }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); let start_after = Some("NFT1".to_string()); @@ -1169,15 +1182,8 @@ mod tests { tokens: vec!["NFT2".to_string(), "NFT3".to_string(), "NFT4".to_string()], }; - let response = all_tokens_query( - &querier, - viewer, - start_after, - limit, - 256usize, - hash, - address, - )?; + let response = + all_tokens_query(querier, viewer, start_after, limit, 256usize, hash, address)?; assert_eq!(response, expected_response); Ok(()) @@ -1190,75 +1196,78 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); let token_id = "NFT1".to_string(); let include_expired = Some(true); - let mut expected_msg = to_binary(&QueryMsg::OwnerOf { + let mut expected_msg = try_querier_result!(to_binary(&QueryMsg::OwnerOf { token_id, viewer, include_expired, }) - .map_err(|_e| SystemError::Unknown {})?; + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = OwnerOfResponse { owner_of: OwnerOf { - owner: Some(HumanAddr("alice".to_string())), + owner: Some("alice".to_string()), approvals: vec![ Cw721Approval { - spender: HumanAddr("bob".to_string()), + spender: "bob".to_string(), expires: Expiration::Never, }, Cw721Approval { - spender: HumanAddr("charlie".to_string()), + spender: "charlie".to_string(), expires: Expiration::AtHeight(1000000), }, ], }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); let token_id = "NFT1".to_string(); let include_expired = Some(true); let expected_response = OwnerOf { - owner: Some(HumanAddr("alice".to_string())), + owner: Some("alice".to_string()), approvals: vec![ Cw721Approval { - spender: HumanAddr("bob".to_string()), + spender: "bob".to_string(), expires: Expiration::Never, }, Cw721Approval { - spender: HumanAddr("charlie".to_string()), + spender: "charlie".to_string(), expires: Expiration::AtHeight(1000000), }, ], }; let response = owner_of_query( - &querier, + querier, token_id, viewer, include_expired, @@ -1278,18 +1287,20 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { let token_id = "NFT1".to_string(); - let mut expected_msg = to_binary(&QueryMsg::NftInfo { token_id }) - .map_err(|_e| SystemError::Unknown {})?; + let mut expected_msg = + try_querier_result!(to_binary(&QueryMsg::NftInfo { token_id }) + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = NftInfoResponse { @@ -1315,12 +1326,14 @@ mod tests { }), }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let token_id = "NFT1".to_string(); @@ -1347,7 +1360,7 @@ mod tests { }), }; - let response = nft_info_query(&querier, token_id, 256usize, hash, address)?; + let response = nft_info_query(querier, token_id, 256usize, hash, address)?; assert_eq!(response, expected_response); Ok(()) @@ -1360,40 +1373,41 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); let token_id = "NFT1".to_string(); let include_expired = Some(true); - let mut expected_msg = to_binary(&QueryMsg::AllNftInfo { + let mut expected_msg = try_querier_result!(to_binary(&QueryMsg::AllNftInfo { token_id, viewer, include_expired, }) - .map_err(|_e| SystemError::Unknown {})?; + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = AllNftInfoResponse { all_nft_info: AllNftInfo { access: OwnerOf { - owner: Some(HumanAddr("alice".to_string())), + owner: Some("alice".to_string()), approvals: vec![ Cw721Approval { - spender: HumanAddr("bob".to_string()), + spender: "bob".to_string(), expires: Expiration::Never, }, Cw721Approval { - spender: HumanAddr("charlie".to_string()), + spender: "charlie".to_string(), expires: Expiration::AtHeight(1000000), }, ], @@ -1421,16 +1435,18 @@ mod tests { }), }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); let token_id = "NFT1".to_string(); @@ -1438,14 +1454,14 @@ mod tests { let expected_response = AllNftInfo { access: OwnerOf { - owner: Some(HumanAddr("alice".to_string())), + owner: Some("alice".to_string()), approvals: vec![ Cw721Approval { - spender: HumanAddr("bob".to_string()), + spender: "bob".to_string(), expires: Expiration::Never, }, Cw721Approval { - spender: HumanAddr("charlie".to_string()), + spender: "charlie".to_string(), expires: Expiration::AtHeight(1000000), }, ], @@ -1474,7 +1490,7 @@ mod tests { }; let response = all_nft_info_query( - &querier, + querier, token_id, viewer, include_expired, @@ -1495,21 +1511,23 @@ mod tests { fn raw_query(&self, request: &[u8]) -> QuerierResult { let token_id = "NFT1".to_string(); let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); - let mut expected_msg = to_binary(&QueryMsg::PrivateMetadata { token_id, viewer }) - .map_err(|_e| SystemError::Unknown {})?; + let mut expected_msg = + try_querier_result!(to_binary(&QueryMsg::PrivateMetadata { token_id, viewer }) + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = PrivateMetadataResponse { @@ -1535,17 +1553,19 @@ mod tests { }), }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let token_id = "NFT1".to_string(); let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); @@ -1571,7 +1591,7 @@ mod tests { }), }; - let response = private_metadata_query(&querier, token_id, viewer, 256usize, hash, address)?; + let response = private_metadata_query(querier, token_id, viewer, 256usize, hash, address)?; assert_eq!(response, expected_response); Ok(()) @@ -1584,32 +1604,33 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); let token_id = "NFT1".to_string(); let include_expired = Some(true); - let mut expected_msg = to_binary(&QueryMsg::NftDossier { + let mut expected_msg = try_querier_result!(to_binary(&QueryMsg::NftDossier { token_id, viewer, include_expired, }) - .map_err(|_e| SystemError::Unknown {})?; + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = NftDossierResponse { nft_dossier: NftDossier { - owner: Some(HumanAddr("alice".to_string())), + owner: Some("alice".to_string()), public_metadata: Some(Metadata { token_uri: Some("token uri2".to_string()), extension: Some(Extension { @@ -1639,13 +1660,13 @@ mod tests { private_metadata_is_public_expiration: None, token_approvals: Some(vec![ Snip721Approval { - address: HumanAddr("bob".to_string()), + address: "bob".to_string(), view_owner_expiration: None, view_private_metadata_expiration: Some(Expiration::AtTime(1000000)), transfer_expiration: Some(Expiration::AtHeight(10000)), }, Snip721Approval { - address: HumanAddr("charlie".to_string()), + address: "charlie".to_string(), view_owner_expiration: Some(Expiration::Never), view_private_metadata_expiration: None, transfer_expiration: None, @@ -1654,23 +1675,25 @@ mod tests { inventory_approvals: None, }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let viewer = Some(ViewerInfo { - address: HumanAddr("alice".to_string()), + address: "alice".to_string(), viewing_key: "key".to_string(), }); let token_id = "NFT1".to_string(); let include_expired = Some(true); let expected_response = NftDossier { - owner: Some(HumanAddr("alice".to_string())), + owner: Some("alice".to_string()), public_metadata: Some(Metadata { token_uri: Some("token uri2".to_string()), extension: Some(Extension { @@ -1700,13 +1723,13 @@ mod tests { private_metadata_is_public_expiration: None, token_approvals: Some(vec![ Snip721Approval { - address: HumanAddr("bob".to_string()), + address: "bob".to_string(), view_owner_expiration: None, view_private_metadata_expiration: Some(Expiration::AtTime(1000000)), transfer_expiration: Some(Expiration::AtHeight(10000)), }, Snip721Approval { - address: HumanAddr("charlie".to_string()), + address: "charlie".to_string(), view_owner_expiration: Some(Expiration::Never), view_private_metadata_expiration: None, transfer_expiration: None, @@ -1716,7 +1739,7 @@ mod tests { }; let response = nft_dossier_query( - &querier, + querier, token_id, viewer, include_expired, @@ -1738,22 +1761,23 @@ mod tests { let viewing_key = "key".to_string(); let token_id = "NFT1".to_string(); let include_expired = None; - let mut expected_msg = to_binary(&QueryMsg::TokenApprovals { + let mut expected_msg = try_querier_result!(to_binary(&QueryMsg::TokenApprovals { token_id, viewing_key, include_expired, }) - .map_err(|_e| SystemError::Unknown {})?; + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = TokenApprovalsResponse { @@ -1764,13 +1788,13 @@ mod tests { private_metadata_is_public_expiration: None, token_approvals: vec![ Snip721Approval { - address: HumanAddr("bob".to_string()), + address: "bob".to_string(), view_owner_expiration: None, view_private_metadata_expiration: Some(Expiration::AtTime(1000000)), transfer_expiration: Some(Expiration::AtHeight(10000)), }, Snip721Approval { - address: HumanAddr("charlie".to_string()), + address: "charlie".to_string(), view_owner_expiration: Some(Expiration::Never), view_private_metadata_expiration: None, transfer_expiration: None, @@ -1778,12 +1802,14 @@ mod tests { ], }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let viewing_key = "key".to_string(); @@ -1797,13 +1823,13 @@ mod tests { private_metadata_is_public_expiration: None, token_approvals: vec![ Snip721Approval { - address: HumanAddr("bob".to_string()), + address: "bob".to_string(), view_owner_expiration: None, view_private_metadata_expiration: Some(Expiration::AtTime(1000000)), transfer_expiration: Some(Expiration::AtHeight(10000)), }, Snip721Approval { - address: HumanAddr("charlie".to_string()), + address: "charlie".to_string(), view_owner_expiration: Some(Expiration::Never), view_private_metadata_expiration: None, transfer_expiration: None, @@ -1812,7 +1838,7 @@ mod tests { }; let response = token_approvals_query( - &querier, + querier, token_id, viewing_key, include_expired, @@ -1832,67 +1858,70 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { let viewing_key = Some("key".to_string()); - let owner = HumanAddr("alice".to_string()); + let owner = "alice".to_string(); let include_expired = None; - let mut expected_msg = to_binary(&QueryMsg::ApprovedForAll { + let mut expected_msg = try_querier_result!(to_binary(&QueryMsg::ApprovedForAll { owner, viewing_key, include_expired, }) - .map_err(|_e| SystemError::Unknown {})?; + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = ApprovedForAllResponse { approved_for_all: ApprovedForAll { operators: vec![ Cw721Approval { - spender: HumanAddr("bob".to_string()), + spender: "bob".to_string(), expires: Expiration::Never, }, Cw721Approval { - spender: HumanAddr("charlie".to_string()), + spender: "charlie".to_string(), expires: Expiration::AtHeight(1000000), }, ], }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let viewing_key = Some("key".to_string()); - let owner = HumanAddr("alice".to_string()); + let owner = "alice".to_string(); let include_expired = None; let expected_response = ApprovedForAll { operators: vec![ Cw721Approval { - spender: HumanAddr("bob".to_string()), + spender: "bob".to_string(), expires: Expiration::Never, }, Cw721Approval { - spender: HumanAddr("charlie".to_string()), + spender: "charlie".to_string(), expires: Expiration::AtHeight(1000000), }, ], }; let response = approved_for_all_query( - &querier, + querier, owner, viewing_key, include_expired, @@ -1912,24 +1941,26 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { let viewing_key = "key".to_string(); - let address = HumanAddr("alice".to_string()); + let address = "alice".to_string(); let include_expired = None; - let mut expected_msg = to_binary(&QueryMsg::InventoryApprovals { - address, - viewing_key, - include_expired, - }) - .map_err(|_e| SystemError::Unknown {})?; + let mut expected_msg = + try_querier_result!(to_binary(&QueryMsg::InventoryApprovals { + address, + viewing_key, + include_expired, + }) + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = InventoryApprovalsResponse { @@ -1940,13 +1971,13 @@ mod tests { private_metadata_is_public_expiration: None, inventory_approvals: vec![ Snip721Approval { - address: HumanAddr("bob".to_string()), + address: "bob".to_string(), view_owner_expiration: None, view_private_metadata_expiration: Some(Expiration::AtTime(1000000)), transfer_expiration: Some(Expiration::AtHeight(10000)), }, Snip721Approval { - address: HumanAddr("charlie".to_string()), + address: "charlie".to_string(), view_owner_expiration: Some(Expiration::Never), view_private_metadata_expiration: None, transfer_expiration: None, @@ -1954,16 +1985,18 @@ mod tests { ], }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let contract_address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let contract_address = "contract".to_string(); let hash = "code hash".to_string(); let viewing_key = "key".to_string(); - let address = HumanAddr("alice".to_string()); + let address = "alice".to_string(); let include_expired = None; let expected_response = InventoryApprovals { @@ -1973,13 +2006,13 @@ mod tests { private_metadata_is_public_expiration: None, inventory_approvals: vec![ Snip721Approval { - address: HumanAddr("bob".to_string()), + address: "bob".to_string(), view_owner_expiration: None, view_private_metadata_expiration: Some(Expiration::AtTime(1000000)), transfer_expiration: Some(Expiration::AtHeight(10000)), }, Snip721Approval { - address: HumanAddr("charlie".to_string()), + address: "charlie".to_string(), view_owner_expiration: Some(Expiration::Never), view_private_metadata_expiration: None, transfer_expiration: None, @@ -1988,7 +2021,7 @@ mod tests { }; let response = inventory_approvals_query( - &querier, + querier, address, viewing_key, include_expired, @@ -2007,29 +2040,30 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { - let owner = HumanAddr("alice".to_string()); - let viewer = Some(HumanAddr("bob".to_string())); + let owner = "alice".to_string(); + let viewer = Some("bob".to_string()); let viewing_key = Some("key".to_string()); let start_after = Some("NFT1".to_string()); let limit = Some(33); - let mut expected_msg = to_binary(&QueryMsg::Tokens { + let mut expected_msg = try_querier_result!(to_binary(&QueryMsg::Tokens { owner, viewer, viewing_key, start_after, limit, }) - .map_err(|_e| SystemError::Unknown {})?; + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = TokenListResponse { @@ -2037,16 +2071,18 @@ mod tests { tokens: vec!["NFT2".to_string(), "NFT3".to_string(), "NFT4".to_string()], }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); - let owner = HumanAddr("alice".to_string()); - let viewer = Some(HumanAddr("bob".to_string())); + let owner = "alice".to_string(); + let viewer = Some("bob".to_string()); let viewing_key = Some("key".to_string()); let start_after = Some("NFT1".to_string()); let limit = Some(33); @@ -2056,7 +2092,7 @@ mod tests { }; let response = tokens_query( - &querier, + querier, owner, viewer, viewing_key, @@ -2077,27 +2113,29 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { - let address = HumanAddr("alice".to_string()); + let address = "alice".to_string(); let viewing_key = "key".to_string(); let page = Some(2); let page_size = None; - let mut expected_msg = to_binary(&QueryMsg::TransactionHistory { - address, - viewing_key, - page, - page_size, - }) - .map_err(|_e| SystemError::Unknown {})?; + let mut expected_msg = + try_querier_result!(to_binary(&QueryMsg::TransactionHistory { + address, + viewing_key, + page, + page_size, + }) + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = TransactionHistoryResponse { @@ -2110,8 +2148,8 @@ mod tests { block_time: 2000000000, token_id: "NFT3".to_string(), action: TxAction::Burn { - owner: HumanAddr("alice".to_string()), - burner: Some(HumanAddr("bob".to_string())), + owner: "alice".to_string(), + burner: Some("bob".to_string()), }, memo: None, }, @@ -2121,9 +2159,9 @@ mod tests { block_time: 1900000000, token_id: "NFT2".to_string(), action: TxAction::Transfer { - from: HumanAddr("alice".to_string()), + from: "alice".to_string(), sender: None, - recipient: HumanAddr("bob".to_string()), + recipient: "bob".to_string(), }, memo: Some("xfer memo".to_string()), }, @@ -2133,23 +2171,25 @@ mod tests { block_time: 1800000000, token_id: "NFT1".to_string(), action: TxAction::Mint { - minter: HumanAddr("admin".to_string()), - recipient: HumanAddr("alice".to_string()), + minter: "admin".to_string(), + recipient: "alice".to_string(), }, memo: None, }, ], }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let contract_address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let contract_address = "contract".to_string(); let hash = "code hash".to_string(); - let address = HumanAddr("alice".to_string()); + let address = "alice".to_string(); let viewing_key = "key".to_string(); let page = Some(2); let page_size = None; @@ -2163,8 +2203,8 @@ mod tests { block_time: 2000000000, token_id: "NFT3".to_string(), action: TxAction::Burn { - owner: HumanAddr("alice".to_string()), - burner: Some(HumanAddr("bob".to_string())), + owner: "alice".to_string(), + burner: Some("bob".to_string()), }, memo: None, }, @@ -2174,9 +2214,9 @@ mod tests { block_time: 1900000000, token_id: "NFT2".to_string(), action: TxAction::Transfer { - from: HumanAddr("alice".to_string()), + from: "alice".to_string(), sender: None, - recipient: HumanAddr("bob".to_string()), + recipient: "bob".to_string(), }, memo: Some("xfer memo".to_string()), }, @@ -2186,8 +2226,8 @@ mod tests { block_time: 1800000000, token_id: "NFT1".to_string(), action: TxAction::Mint { - minter: HumanAddr("admin".to_string()), - recipient: HumanAddr("alice".to_string()), + minter: "admin".to_string(), + recipient: "alice".to_string(), }, memo: None, }, @@ -2195,7 +2235,7 @@ mod tests { }; let response = transaction_history_query( - &querier, + querier, address, viewing_key, page, @@ -2215,46 +2255,50 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { - let mut expected_msg = - to_binary(&QueryMsg::Minters {}).map_err(|_e| SystemError::Unknown {})?; + let mut expected_msg = try_querier_result!( + to_binary(&QueryMsg::Minters {}).map_err(|_e| SystemError::Unknown {}) + ); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = MintersResponse { minters: Minters { minters: vec![ - HumanAddr("alice".to_string()), - HumanAddr("bob".to_string()), - HumanAddr("charlie".to_string()), + "alice".to_string(), + "bob".to_string(), + "charlie".to_string(), ], }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let expected_response = Minters { minters: vec![ - HumanAddr("alice".to_string()), - HumanAddr("bob".to_string()), - HumanAddr("charlie".to_string()), + "alice".to_string(), + "bob".to_string(), + "charlie".to_string(), ], }; - let response = minters_query(&querier, 256usize, hash, address)?; + let response = minters_query(querier, 256usize, hash, address)?; assert_eq!(response, expected_response); Ok(()) @@ -2267,18 +2311,20 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { let token_id = "NFT1".to_string(); - let mut expected_msg = to_binary(&QueryMsg::IsUnwrapped { token_id }) - .map_err(|_e| SystemError::Unknown {})?; + let mut expected_msg = + try_querier_result!(to_binary(&QueryMsg::IsUnwrapped { token_id }) + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = IsUnwrappedResponse { @@ -2286,12 +2332,14 @@ mod tests { token_is_unwrapped: false, }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "contract".to_string(); let hash = "code hash".to_string(); let token_id = "NFT1".to_string(); @@ -2300,7 +2348,7 @@ mod tests { token_is_unwrapped: false, }; - let response = is_unwrapped_query(&querier, token_id, 256usize, hash, address)?; + let response = is_unwrapped_query(querier, token_id, 256usize, hash, address)?; assert_eq!(response, expected_response); Ok(()) @@ -2313,25 +2361,27 @@ mod tests { impl Querier for MyMockQuerier { fn raw_query(&self, request: &[u8]) -> QuerierResult { let token_ids = vec!["NFT1".to_string(), "NFT2".to_string(), "NFT3".to_string()]; - let address = HumanAddr("alice".to_string()); + let address = "alice".to_string(); let viewing_key = "key".to_string(); - let mut expected_msg = to_binary(&QueryMsg::VerifyTransferApproval { - token_ids, - address, - viewing_key, - }) - .map_err(|_e| SystemError::Unknown {})?; + let mut expected_msg = + try_querier_result!(to_binary(&QueryMsg::VerifyTransferApproval { + token_ids, + address, + viewing_key, + }) + .map_err(|_e| SystemError::Unknown {})); space_pad(&mut expected_msg.0, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("contract".to_string()), - callback_code_hash: "code hash".to_string(), + contract_addr: "contract".to_string(), + code_hash: "code hash".to_string(), msg: expected_msg, }); - let test_req: &[u8] = - &to_vec(&expected_request).map_err(|_e| SystemError::Unknown {})?; + let test_req: &[u8] = &try_querier_result!( + to_vec(&expected_request).map_err(|_e| SystemError::Unknown {}) + ); assert_eq!(request, test_req); let response = VerifyTransferApprovalResponse { @@ -2340,16 +2390,18 @@ mod tests { first_unapproved_token: Some("NFT3".to_string()), }, }; - Ok(to_binary(&response)) + let response = + try_querier_result!(to_binary(&response).map_err(|_e| SystemError::Unknown {})); + SystemResult::Ok(ContractResult::Ok(response)) } } - let querier = MyMockQuerier {}; - let contract_address = HumanAddr("contract".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let contract_address = "contract".to_string(); let hash = "code hash".to_string(); let token_ids = vec!["NFT1".to_string(), "NFT2".to_string(), "NFT3".to_string()]; - let address = HumanAddr("alice".to_string()); + let address = "alice".to_string(); let viewing_key = "key".to_string(); let expected_response = VerifyTransferApproval { @@ -2358,7 +2410,7 @@ mod tests { }; let response = verify_transfer_approval_query( - &querier, + querier, token_ids, address, viewing_key, diff --git a/packages/storage/Cargo.toml b/packages/storage/Cargo.toml index db8529a..5f55634 100644 --- a/packages/storage/Cargo.toml +++ b/packages/storage/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "secret-toolkit-storage" -version = "0.5.0" +version = "0.6.0" edition = "2018" authors = ["SCRT Labs "] license-file = "../../LICENSE" @@ -15,6 +15,6 @@ all-features = true [dependencies] serde = "1.0" -cosmwasm-std = { package = "secret-cosmwasm-std", version = "0.10" } -cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "0.10" } -secret-toolkit-serialization = { version = "0.3", path = "../serialization" } +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.0.0" } +cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "1.0.0" } +secret-toolkit-serialization = { version = "0.6", path = "../serialization" } diff --git a/packages/storage/Readme.md b/packages/storage/Readme.md index aaedf4d..ff481c9 100644 --- a/packages/storage/Readme.md +++ b/packages/storage/Readme.md @@ -9,7 +9,7 @@ This package contains many tools related to storage access patterns. This readme To import this package, add one of the following lines to your `Cargo.toml` file ```toml -secret-toolkit = { version = "0.4", default-features = false, features = ["utils", "storage", "serialization"] } +secret-toolkit = { version = "0.6", default-features = false, features = ["utils", "storage", "serialization"] } ``` for the release versions, or @@ -31,7 +31,7 @@ This is the simplest storage object in this toolkit. It based on the similarly n This object is meant to be initialized as a static constant in `state.rs`. However, it would also work perfectly fine if it was initialized during run time with a variable key (in this case though, you'd have to remind it what type of object is stored and its serde). Import it using the following lines: ```ignore -use secret_toolkit::storage::{Item} +use secret_toolkit_storage::{Item} ``` And initialize it using the following lines: @@ -40,7 +40,7 @@ And initialize it using the following lines: pub static OWNER: Item = Item::new(b"owner"); ``` -This uses Bincode2 to serde HumanAddr by default. To specify the Serde algorithm as Json, first import it from `secret-toolkit-serialization` +This uses Bincode2 to serde HumanAddr by default. To specify the Serde algorithm as Json, first import it from `secret-toolkit::serialization` ```ignore use secret_toolkit::serialization::{Bincode2, Json}; diff --git a/packages/storage/src/append_store.rs b/packages/storage/src/append_store.rs index 9db04fc..89bd287 100644 --- a/packages/storage/src/append_store.rs +++ b/packages/storage/src/append_store.rs @@ -10,7 +10,7 @@ use std::sync::Mutex; use serde::{de::DeserializeOwned, Serialize}; -use cosmwasm_std::{ReadonlyStorage, StdError, StdResult, Storage}; +use cosmwasm_std::{StdError, StdResult, Storage}; use cosmwasm_storage::to_length_prefixed; use secret_toolkit_serialization::{Bincode2, Serde}; @@ -61,7 +61,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { /// gets the length from storage, and otherwise sets it to 0 - pub fn get_len(&self, storage: &S) -> StdResult { + pub fn get_len(&self, storage: &dyn Storage) -> StdResult { let mut may_len = self.length.lock().unwrap(); match *may_len { Some(len) => Ok(len), @@ -84,12 +84,12 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { } /// checks if the collection has any elements - pub fn is_empty(&self, storage: &S) -> StdResult { + pub fn is_empty(&self, storage: &dyn Storage) -> StdResult { Ok(self.get_len(storage)? == 0) } /// gets the element at pos if within bounds - pub fn get_at(&self, storage: &S, pos: u32) -> StdResult { + pub fn get_at(&self, storage: &dyn Storage, pos: u32) -> StdResult { let len = self.get_len(storage)?; if pos > len { return Err(StdError::generic_err("AppendStore access out of bounds")); @@ -98,13 +98,13 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { } /// tries to get the element at pos - fn get_at_unchecked(&self, storage: &S, pos: u32) -> StdResult { + fn get_at_unchecked(&self, storage: &dyn Storage, pos: u32) -> StdResult { let key = pos.to_be_bytes(); self.load_impl(storage, &key) } /// Set the length of the collection - fn set_len(&self, storage: &mut S, len: u32) { + fn set_len(&self, storage: &mut dyn Storage, len: u32) { let len_key = [self.as_slice(), LEN_KEY].concat(); storage.set(&len_key, &len.to_be_bytes()); @@ -113,12 +113,12 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { } /// Clear the collection - pub fn clear(&self, storage: &mut S) { + pub fn clear(&self, storage: &mut dyn Storage) { self.set_len(storage, 0); } /// Replaces data at a position within bounds - pub fn set_at(&self, storage: &mut S, pos: u32, item: &T) -> StdResult<()> { + pub fn set_at(&self, storage: &mut dyn Storage, pos: u32, item: &T) -> StdResult<()> { let len = self.get_len(storage)?; if pos >= len { return Err(StdError::generic_err("AppendStore access out of bounds")); @@ -127,12 +127,12 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { } /// Sets data at a given index - fn set_at_unchecked(&self, storage: &mut S, pos: u32, item: &T) -> StdResult<()> { + fn set_at_unchecked(&self, storage: &mut dyn Storage, pos: u32, item: &T) -> StdResult<()> { self.save_impl(storage, &pos.to_be_bytes(), item) } /// Pushes an item to AppendStorage - pub fn push(&self, storage: &mut S, item: &T) -> StdResult<()> { + pub fn push(&self, storage: &mut dyn Storage, item: &T) -> StdResult<()> { let len = self.get_len(storage)?; self.set_at_unchecked(storage, len, item)?; self.set_len(storage, len + 1); @@ -140,7 +140,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { } /// Pops an item from AppendStore - pub fn pop(&self, storage: &mut S) -> StdResult { + pub fn pop(&self, storage: &mut dyn Storage) -> StdResult { if let Some(len) = self.get_len(storage)?.checked_sub(1) { let item = self.get_at_unchecked(storage, len); self.set_len(storage, len); @@ -158,7 +158,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { /// /// Removing an element from the start (head) of the collection /// has the worst runtime and gas cost. - pub fn remove(&self, storage: &mut S, pos: u32) -> StdResult { + pub fn remove(&self, storage: &mut dyn Storage, pos: u32) -> StdResult { let len = self.get_len(storage)?; if pos >= len { @@ -175,22 +175,14 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { } /// Returns a readonly iterator - pub fn iter( - &self, - storage: &'a S, - ) -> StdResult> { + pub fn iter(&self, storage: &'a dyn Storage) -> StdResult> { let len = self.get_len(storage)?; let iter = AppendStoreIter::new(self, storage, 0, len); Ok(iter) } /// does paging with the given parameters - pub fn paging( - &self, - storage: &S, - start_page: u32, - size: u32, - ) -> StdResult> { + pub fn paging(&self, storage: &dyn Storage, start_page: u32, size: u32) -> StdResult> { self.iter(storage)? .skip((start_page as usize) * (size as usize)) .take(size as usize) @@ -214,7 +206,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { /// /// * `storage` - a reference to the storage this item is in /// * `key` - a byte slice representing the key to access the stored item - fn load_impl(&self, storage: &S, key: &[u8]) -> StdResult { + fn load_impl(&self, storage: &dyn Storage, key: &[u8]) -> StdResult { let prefixed_key = [self.as_slice(), key].concat(); Ser::deserialize( &storage @@ -230,7 +222,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { /// * `storage` - a mutable reference to the storage this item should go to /// * `key` - a byte slice representing the key to access the stored item /// * `value` - a reference to the item to store - fn save_impl(&self, storage: &mut S, key: &[u8], value: &T) -> StdResult<()> { + fn save_impl(&self, storage: &mut dyn Storage, key: &[u8], value: &T) -> StdResult<()> { let prefixed_key = [self.as_slice(), key].concat(); storage.set(&prefixed_key, &Ser::serialize(value)?); Ok(()) @@ -238,28 +230,26 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> AppendStore<'a, T, Ser> { } /// An iterator over the contents of the append store. -pub struct AppendStoreIter<'a, T, S, Ser> +pub struct AppendStoreIter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { append_store: &'a AppendStore<'a, T, Ser>, - storage: &'a S, + storage: &'a dyn Storage, start: u32, end: u32, } -impl<'a, T, S, Ser> AppendStoreIter<'a, T, S, Ser> +impl<'a, T, Ser> AppendStoreIter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { /// constructor pub fn new( append_store: &'a AppendStore<'a, T, Ser>, - storage: &'a S, + storage: &'a dyn Storage, start: u32, end: u32, ) -> Self { @@ -272,10 +262,9 @@ where } } -impl<'a, T, S, Ser> Iterator for AppendStoreIter<'a, T, S, Ser> +impl<'a, T, Ser> Iterator for AppendStoreIter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { type Item = StdResult; @@ -307,10 +296,9 @@ where } } -impl<'a, T, S, Ser> DoubleEndedIterator for AppendStoreIter<'a, T, S, Ser> +impl<'a, T, Ser> DoubleEndedIterator for AppendStoreIter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { fn next_back(&mut self) -> Option { @@ -335,10 +323,9 @@ where } // This enables writing `append_store.iter().skip(n).rev()` -impl<'a, T, S, Ser> ExactSizeIterator for AppendStoreIter<'a, T, S, Ser> +impl<'a, T, Ser> ExactSizeIterator for AppendStoreIter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { } @@ -375,7 +362,7 @@ mod tests { let append_store: AppendStore = AppendStore::new(b"test"); assert!(append_store.length.lock().unwrap().eq(&None)); - assert_eq!(append_store.get_len(&storage)?, 0); + assert_eq!(append_store.get_len(&mut storage)?, 0); assert!(append_store.length.lock().unwrap().eq(&Some(0))); append_store.push(&mut storage, &1234)?; @@ -383,21 +370,21 @@ mod tests { append_store.push(&mut storage, &3412)?; append_store.push(&mut storage, &4321)?; assert!(append_store.length.lock().unwrap().eq(&Some(4))); - assert_eq!(append_store.get_len(&storage)?, 4); + assert_eq!(append_store.get_len(&mut storage)?, 4); assert_eq!(append_store.pop(&mut storage), Ok(4321)); assert_eq!(append_store.pop(&mut storage), Ok(3412)); assert!(append_store.length.lock().unwrap().eq(&Some(2))); - assert_eq!(append_store.get_len(&storage)?, 2); + assert_eq!(append_store.get_len(&mut storage)?, 2); assert_eq!(append_store.pop(&mut storage), Ok(2143)); assert_eq!(append_store.pop(&mut storage), Ok(1234)); assert!(append_store.length.lock().unwrap().eq(&Some(0))); - assert_eq!(append_store.get_len(&storage)?, 0); + assert_eq!(append_store.get_len(&mut storage)?, 0); assert!(append_store.pop(&mut storage).is_err()); assert!(append_store.length.lock().unwrap().eq(&Some(0))); - assert_eq!(append_store.get_len(&storage)?, 0); + assert_eq!(append_store.get_len(&mut storage)?, 0); Ok(()) } diff --git a/packages/storage/src/deque_store.rs b/packages/storage/src/deque_store.rs index e2f7edb..5e917ad 100644 --- a/packages/storage/src/deque_store.rs +++ b/packages/storage/src/deque_store.rs @@ -11,7 +11,7 @@ use std::sync::Mutex; use serde::{de::DeserializeOwned, Serialize}; -use cosmwasm_std::{ReadonlyStorage, StdError, StdResult, Storage}; +use cosmwasm_std::{StdError, StdResult, Storage}; use cosmwasm_storage::to_length_prefixed; use secret_toolkit_serialization::{Bincode2, Serde}; @@ -66,7 +66,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { /// gets the length from storage, and otherwise sets it to 0 - pub fn get_len(&self, storage: &S) -> StdResult { + pub fn get_len(&self, storage: &dyn Storage) -> StdResult { let mut may_len = self.length.lock().unwrap(); match *may_len { Some(len) => Ok(len), @@ -81,7 +81,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { } /// gets the offset from storage, and otherwise sets it to 0 - pub fn get_off(&self, storage: &S) -> StdResult { + pub fn get_off(&self, storage: &dyn Storage) -> StdResult { let mut may_off = self.offset.lock().unwrap(); match *may_off { Some(len) => Ok(len), @@ -96,7 +96,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { } /// gets offset or length - fn _get_u32(&self, storage: &S, key: &[u8]) -> StdResult { + fn _get_u32(&self, storage: &dyn Storage, key: &[u8]) -> StdResult { let num_key = [self.as_slice(), key].concat(); if let Some(num_vec) = storage.get(&num_key) { let num_bytes = num_vec @@ -111,12 +111,12 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { } /// checks if the collection has any elements - pub fn is_empty(&self, storage: &S) -> StdResult { + pub fn is_empty(&self, storage: &dyn Storage) -> StdResult { Ok(self.get_len(storage)? == 0) } /// gets the element at pos if within bounds - pub fn get_at(&self, storage: &S, pos: u32) -> StdResult { + pub fn get_at(&self, storage: &dyn Storage, pos: u32) -> StdResult { let len = self.get_len(storage)?; if pos >= len { return Err(StdError::generic_err("DequeStore access out of bounds")); @@ -125,44 +125,44 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { } /// tries to get the element at pos - fn get_at_unchecked(&self, storage: &S, pos: u32) -> StdResult { + fn get_at_unchecked(&self, storage: &dyn Storage, pos: u32) -> StdResult { self.load_impl(storage, &self._get_offset_pos(storage, pos)?.to_be_bytes()) } /// add the offset to the pos - fn _get_offset_pos(&self, storage: &S, pos: u32) -> StdResult { + fn _get_offset_pos(&self, storage: &dyn Storage, pos: u32) -> StdResult { let off = self.get_off(storage)?; Ok(pos.overflowing_add(off).0) } /// Set the length of the collection - fn set_len(&self, storage: &mut S, len: u32) { + fn set_len(&self, storage: &mut dyn Storage, len: u32) { let mut may_len = self.length.lock().unwrap(); *may_len = Some(len); self._set_u32(storage, LEN_KEY, len) } /// Set the offset of the collection - fn set_off(&self, storage: &mut S, off: u32) { + fn set_off(&self, storage: &mut dyn Storage, off: u32) { let mut may_off = self.offset.lock().unwrap(); *may_off = Some(off); self._set_u32(storage, OFFSET_KEY, off) } /// Set the length or offset of the collection - fn _set_u32(&self, storage: &mut S, key: &[u8], num: u32) { + fn _set_u32(&self, storage: &mut dyn Storage, key: &[u8], num: u32) { let num_key = [self.as_slice(), key].concat(); storage.set(&num_key, &num.to_be_bytes()); } /// Clear the collection - pub fn clear(&self, storage: &mut S) { + pub fn clear(&self, storage: &mut dyn Storage) { self.set_len(storage, 0); self.set_off(storage, 0); } /// Replaces data at a position within bounds - pub fn set_at(&self, storage: &mut S, pos: u32, item: &T) -> StdResult<()> { + pub fn set_at(&self, storage: &mut dyn Storage, pos: u32, item: &T) -> StdResult<()> { let len = self.get_len(storage)?; if pos >= len { return Err(StdError::generic_err("DequeStore access out of bounds")); @@ -171,16 +171,13 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { } /// Sets data at a given index - fn set_at_unchecked(&self, storage: &mut S, pos: u32, item: &T) -> StdResult<()> { - self.save_impl( - storage, - &self._get_offset_pos(storage, pos)?.to_be_bytes(), - item, - ) + fn set_at_unchecked(&self, storage: &mut dyn Storage, pos: u32, item: &T) -> StdResult<()> { + let get_offset_pos = self._get_offset_pos(storage, pos)?; + self.save_impl(storage, &get_offset_pos.to_be_bytes(), item) } /// Pushes an item to the back - pub fn push_back(&self, storage: &mut S, item: &T) -> StdResult<()> { + pub fn push_back(&self, storage: &mut dyn Storage, item: &T) -> StdResult<()> { let len = self.get_len(storage)?; self.set_at_unchecked(storage, len, item)?; self.set_len(storage, len + 1); @@ -188,7 +185,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { } /// Pushes an item to the front - pub fn push_front(&self, storage: &mut S, item: &T) -> StdResult<()> { + pub fn push_front(&self, storage: &mut dyn Storage, item: &T) -> StdResult<()> { let off = self.get_off(storage)?; let len = self.get_len(storage)?; self.set_off(storage, off.overflowing_sub(1).0); @@ -198,7 +195,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { } /// Pops an item from the back - pub fn pop_back(&self, storage: &mut S) -> StdResult { + pub fn pop_back(&self, storage: &mut dyn Storage) -> StdResult { if let Some(len) = self.get_len(storage)?.checked_sub(1) { let item = self.get_at_unchecked(storage, len); self.set_len(storage, len); @@ -209,7 +206,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { } /// Pops an item from the front - pub fn pop_front(&self, storage: &mut S) -> StdResult { + pub fn pop_front(&self, storage: &mut dyn Storage) -> StdResult { if let Some(len) = self.get_len(storage)?.checked_sub(1) { let off = self.get_off(storage)?; let item = self.get_at_unchecked(storage, 0); @@ -230,7 +227,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { /// /// Removing an element from the middle of the collection /// has the worst runtime and gas cost. - pub fn remove(&self, storage: &mut S, pos: u32) -> StdResult { + pub fn remove(&self, storage: &mut dyn Storage, pos: u32) -> StdResult { let off = self.get_off(storage)?; let len = self.get_len(storage)?; if pos >= len { @@ -257,19 +254,14 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { } /// Returns a readonly iterator - pub fn iter(&self, storage: &'a S) -> StdResult> { + pub fn iter(&self, storage: &'a dyn Storage) -> StdResult> { let len = self.get_len(storage)?; let iter = DequeStoreIter::new(self, storage, 0, len); Ok(iter) } /// does paging with the given parameters - pub fn paging( - &self, - storage: &S, - start_page: u32, - size: u32, - ) -> StdResult> { + pub fn paging(&self, storage: &dyn Storage, start_page: u32, size: u32) -> StdResult> { self.iter(storage)? .skip((start_page as usize) * (size as usize)) .take(size as usize) @@ -293,7 +285,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { /// /// * `storage` - a reference to the storage this item is in /// * `key` - a byte slice representing the key to access the stored item - fn load_impl(&self, storage: &S, key: &[u8]) -> StdResult { + fn load_impl(&self, storage: &dyn Storage, key: &[u8]) -> StdResult { let prefixed_key = [self.as_slice(), key].concat(); Ser::deserialize( &storage @@ -309,7 +301,7 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { /// * `storage` - a mutable reference to the storage this item should go to /// * `key` - a byte slice representing the key to access the stored item /// * `value` - a reference to the item to store - fn save_impl(&self, storage: &mut S, key: &[u8], value: &T) -> StdResult<()> { + fn save_impl(&self, storage: &mut dyn Storage, key: &[u8], value: &T) -> StdResult<()> { let prefixed_key = [self.as_slice(), key].concat(); storage.set(&prefixed_key, &Ser::serialize(value)?); Ok(()) @@ -317,28 +309,26 @@ impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> DequeStore<'a, T, Ser> { } /// An iterator over the contents of the deque store. -pub struct DequeStoreIter<'a, T, S, Ser> +pub struct DequeStoreIter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { deque_store: &'a DequeStore<'a, T, Ser>, - storage: &'a S, + storage: &'a dyn Storage, start: u32, end: u32, } -impl<'a, T, S, Ser> DequeStoreIter<'a, T, S, Ser> +impl<'a, T, Ser> DequeStoreIter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { /// constructor pub fn new( deque_store: &'a DequeStore<'a, T, Ser>, - storage: &'a S, + storage: &'a dyn Storage, start: u32, end: u32, ) -> Self { @@ -351,10 +341,9 @@ where } } -impl<'a, T, S, Ser> Iterator for DequeStoreIter<'a, T, S, Ser> +impl<'a, T, Ser> Iterator for DequeStoreIter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { type Item = StdResult; @@ -386,10 +375,9 @@ where } } -impl<'a, T, S, Ser> DoubleEndedIterator for DequeStoreIter<'a, T, S, Ser> +impl<'a, T, Ser> DoubleEndedIterator for DequeStoreIter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { fn next_back(&mut self) -> Option { @@ -414,10 +402,9 @@ where } // This enables writing `deque_store.iter().skip(n).rev()` -impl<'a, T, S, Ser> ExactSizeIterator for DequeStoreIter<'a, T, S, Ser> +impl<'a, T, Ser> ExactSizeIterator for DequeStoreIter<'a, T, Ser> where T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { } diff --git a/packages/storage/src/item.rs b/packages/storage/src/item.rs index a965351..155debe 100644 --- a/packages/storage/src/item.rs +++ b/packages/storage/src/item.rs @@ -2,8 +2,9 @@ use std::any::type_name; use std::marker::PhantomData; -use cosmwasm_std::{ReadonlyStorage, StdError, StdResult, Storage}; +use cosmwasm_std::{StdError, StdResult, Storage}; use cosmwasm_storage::to_length_prefixed; + use secret_toolkit_serialization::{Bincode2, Serde}; use serde::{de::DeserializeOwned, Serialize}; @@ -21,6 +22,7 @@ where } impl<'a, T: Serialize + DeserializeOwned, Ser: Serde> Item<'a, T, Ser> { + /// constructor pub const fn new(key: &'a [u8]) -> Self { Self { storage_key: key, @@ -51,28 +53,28 @@ where Ser: Serde, { /// save will serialize the model and store, returns an error on serialization issues - pub fn save(&self, storage: &mut S, data: &T) -> StdResult<()> { + pub fn save(&self, storage: &mut dyn Storage, data: &T) -> StdResult<()> { self.save_impl(storage, data) } /// userfacing remove function - pub fn remove(&self, storage: &mut S) { + pub fn remove(&self, storage: &mut dyn Storage) { self.remove_impl(storage); } /// load will return an error if no data is set at the given key, or on parse error - pub fn load(&self, storage: &S) -> StdResult { + pub fn load(&self, storage: &dyn Storage) -> StdResult { self.load_impl(storage) } /// may_load will parse the data stored at the key if present, returns `Ok(None)` if no data there. /// returns an error on issues parsing - pub fn may_load(&self, storage: &S) -> StdResult> { + pub fn may_load(&self, storage: &dyn Storage) -> StdResult> { self.may_load_impl(storage) } /// efficient way to see if any object is currently saved. - pub fn is_empty(&self, storage: &S) -> bool { + pub fn is_empty(&self, storage: &dyn Storage) -> bool { storage.get(self.as_slice()).is_none() } @@ -81,9 +83,8 @@ where /// /// It assumes, that data was initialized before, and if it doesn't exist, `Err(StdError::NotFound)` /// is returned. - pub fn update(&self, storage: &mut S, action: A) -> StdResult + pub fn update(&self, storage: &mut dyn Storage, action: A) -> StdResult where - S: Storage, A: FnOnce(T) -> StdResult, { let input = self.load_impl(storage)?; @@ -98,7 +99,7 @@ where /// # Arguments /// /// * `storage` - a reference to the storage this item is in - fn load_impl(&self, storage: &S) -> StdResult { + fn load_impl(&self, storage: &dyn Storage) -> StdResult { Ser::deserialize( &storage .get(self.as_slice()) @@ -112,7 +113,7 @@ where /// # Arguments /// /// * `storage` - a reference to the storage this item is in - fn may_load_impl(&self, storage: &S) -> StdResult> { + fn may_load_impl(&self, storage: &dyn Storage) -> StdResult> { match storage.get(self.as_slice()) { Some(value) => Ser::deserialize(&value).map(Some), None => Ok(None), @@ -125,7 +126,7 @@ where /// /// * `storage` - a mutable reference to the storage this item should go to /// * `value` - a reference to the item to store - fn save_impl(&self, storage: &mut S, value: &T) -> StdResult<()> { + fn save_impl(&self, storage: &mut dyn Storage, value: &T) -> StdResult<()> { storage.set(self.as_slice(), &Ser::serialize(value)?); Ok(()) } @@ -135,7 +136,7 @@ where /// # Arguments /// /// * `storage` - a mutable reference to the storage this item is in - fn remove_impl(&self, storage: &mut S) { + fn remove_impl(&self, storage: &mut dyn Storage) { storage.remove(self.as_slice()); } diff --git a/packages/storage/src/keymap.rs b/packages/storage/src/keymap.rs index 930ab30..ebc809d 100644 --- a/packages/storage/src/keymap.rs +++ b/packages/storage/src/keymap.rs @@ -6,7 +6,7 @@ use std::sync::Mutex; use serde::Deserialize; use serde::{de::DeserializeOwned, Serialize}; -use cosmwasm_std::{ReadonlyStorage, StdError, StdResult, Storage}; +use cosmwasm_std::{StdError, StdResult, Storage}; use cosmwasm_storage::to_length_prefixed; use secret_toolkit_serialization::{Bincode2, Serde}; @@ -41,6 +41,7 @@ impl InternalItem { serialization_type: PhantomData, }) } + fn get_item(&self) -> StdResult { Ser::deserialize(&self.item_vec) } @@ -108,7 +109,7 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// get total number of objects saved - pub fn get_len(&self, storage: &S) -> StdResult { + pub fn get_len(&self, storage: &dyn Storage) -> StdResult { let mut may_len = self.length.lock().unwrap(); match *may_len { Some(length) => Ok(length), @@ -131,12 +132,12 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// checks if the collection has any elements - pub fn is_empty(&self, storage: &S) -> StdResult { + pub fn is_empty(&self, storage: &dyn Storage) -> StdResult { Ok(self.get_len(storage)? == 0) } /// set length of the map - fn set_len(&self, storage: &mut S, len: u32) -> StdResult<()> { + fn set_len(&self, storage: &mut dyn Storage, len: u32) -> StdResult<()> { let len_key = [self.as_slice(), MAP_LENGTH].concat(); storage.set(&len_key, &len.to_be_bytes()); @@ -147,7 +148,7 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// Used to get the indexes stored in the given page number - fn _get_indexes(&self, storage: &S, page: u32) -> StdResult>> { + fn _get_indexes(&self, storage: &dyn Storage, page: u32) -> StdResult>> { let indexes_key = [self.as_slice(), INDEXES, page.to_be_bytes().as_slice()].concat(); let maybe_serialized = storage.get(&indexes_key); match maybe_serialized { @@ -157,9 +158,9 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// Set an indexes page - fn _set_indexes_page( + fn _set_indexes_page( &self, - storage: &mut S, + storage: &mut dyn Storage, page: u32, indexes: &Vec>, ) -> StdResult<()> { @@ -169,7 +170,7 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// user facing get function - pub fn get(&self, storage: &S, key: &K) -> Option { + pub fn get(&self, storage: &dyn Storage, key: &K) -> Option { if let Ok(internal_item) = self._get_from_key(storage, key) { internal_item.get_item().ok() } else { @@ -178,17 +179,13 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// internal item get function - fn _get_from_key( - &self, - storage: &S, - key: &K, - ) -> StdResult> { + fn _get_from_key(&self, storage: &dyn Storage, key: &K) -> StdResult> { let key_vec = self.serialize_key(key)?; self.load_impl(storage, &key_vec) } /// user facing remove function - pub fn remove(&self, storage: &mut S, key: &K) -> StdResult<()> { + pub fn remove(&self, storage: &mut dyn Storage, key: &K) -> StdResult<()> { let key_vec = self.serialize_key(key)?; let removed_pos = self._get_from_key(storage, key)?.index_pos; @@ -249,7 +246,7 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// user facing insert function - pub fn insert(&self, storage: &mut S, key: &K, item: &T) -> StdResult<()> { + pub fn insert(&self, storage: &mut dyn Storage, key: &K, item: &T) -> StdResult<()> { let key_vec = self.serialize_key(key)?; match self.may_load_impl(storage, &key_vec)? { Some(existing_internal_item) => { @@ -274,7 +271,7 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// user facing method that checks if any item is stored with this key. - pub fn contains(&self, storage: &S, key: &K) -> bool { + pub fn contains(&self, storage: &dyn Storage, key: &K) -> bool { match self.serialize_key(key) { Ok(key_vec) => self.contains_impl(storage, &key_vec), Err(_) => false, @@ -282,9 +279,9 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// paginates (key, item) pairs. - pub fn paging( + pub fn paging( &self, - storage: &S, + storage: &dyn Storage, start_page: u32, size: u32, ) -> StdResult> { @@ -300,7 +297,6 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: if start_pos > max_size { return Err(StdError::NotFound { kind: "Out of bounds".to_string(), - backtrace: None, }); } else if end_pos > max_size { end_pos = max_size - 1; @@ -309,9 +305,9 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// paginates only the keys. More efficient than paginating both items and keys - pub fn paging_keys( + pub fn paging_keys( &self, - storage: &S, + storage: &dyn Storage, start_page: u32, size: u32, ) -> StdResult> { @@ -327,7 +323,6 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: if start_pos > max_size { return Err(StdError::NotFound { kind: "Out of bounds".to_string(), - backtrace: None, }); } else if end_pos > max_size { end_pos = max_size - 1; @@ -336,9 +331,9 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// tries to list keys without checking start/end bounds - fn get_keys_at_positions( + fn get_keys_at_positions( &self, - storage: &S, + storage: &dyn Storage, start: u32, end: u32, ) -> StdResult> { @@ -369,9 +364,9 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// tries to list (key, item) pairs without checking start/end bounds - fn get_pairs_at_positions( + fn get_pairs_at_positions( &self, - storage: &S, + storage: &dyn Storage, start: u32, end: u32, ) -> StdResult> { @@ -403,7 +398,7 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// gets a key from a specific position in indexes - fn get_key_from_pos(&self, storage: &S, pos: u32) -> StdResult { + fn get_key_from_pos(&self, storage: &dyn Storage, pos: u32) -> StdResult { let page = _page_from_position(pos); let indexes = self._get_indexes(storage, page)?; let index = pos % PAGE_SIZE; @@ -412,7 +407,7 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// gets a key from a specific position in indexes - fn get_pair_from_pos(&self, storage: &S, pos: u32) -> StdResult<(K, T)> { + fn get_pair_from_pos(&self, storage: &dyn Storage, pos: u32) -> StdResult<(K, T)> { let page = _page_from_position(pos); let indexes = self._get_indexes(storage, page)?; let index = pos % PAGE_SIZE; @@ -423,17 +418,14 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// Returns a readonly iterator only for keys. More efficient than iter(). - pub fn iter_keys( - &self, - storage: &'a S, - ) -> StdResult> { + pub fn iter_keys(&self, storage: &'a dyn Storage) -> StdResult> { let len = self.get_len(storage)?; let iter = KeyIter::new(self, storage, 0, len); Ok(iter) } /// Returns a readonly iterator for (key-item) pairs - pub fn iter(&self, storage: &'a S) -> StdResult> { + pub fn iter(&self, storage: &'a dyn Storage) -> StdResult> { let len = self.get_len(storage)?; let iter = KeyItemIter::new(self, storage, 0, len); Ok(iter) @@ -453,15 +445,14 @@ impl<'a, K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, Ser: } /// An iterator over the keys of the Keymap. -pub struct KeyIter<'a, K, T, S, Ser> +pub struct KeyIter<'a, K, T, Ser> where K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { keymap: &'a Keymap<'a, K, T, Ser>, - storage: &'a S, + storage: &'a dyn Storage, start: u32, end: u32, saved_indexes: Option>>, @@ -470,15 +461,19 @@ where saved_back_index_page: Option, } -impl<'a, K, T, S, Ser> KeyIter<'a, K, T, S, Ser> +impl<'a, K, T, Ser> KeyIter<'a, K, T, Ser> where K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { /// constructor - pub fn new(keymap: &'a Keymap<'a, K, T, Ser>, storage: &'a S, start: u32, end: u32) -> Self { + pub fn new( + keymap: &'a Keymap<'a, K, T, Ser>, + storage: &'a dyn Storage, + start: u32, + end: u32, + ) -> Self { Self { keymap, storage, @@ -492,11 +487,10 @@ where } } -impl<'a, K, T, S, Ser> Iterator for KeyIter<'a, K, T, S, Ser> +impl<'a, K, T, Ser> Iterator for KeyIter<'a, K, T, Ser> where K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { type Item = StdResult; @@ -618,11 +612,10 @@ where } } -impl<'a, K, T, S, Ser> DoubleEndedIterator for KeyIter<'a, K, T, S, Ser> +impl<'a, K, T, Ser> DoubleEndedIterator for KeyIter<'a, K, T, Ser> where K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { fn next_back(&mut self) -> Option { @@ -738,11 +731,10 @@ where } // This enables writing `append_store.iter().skip(n).rev()` -impl<'a, K, T, S, Ser> ExactSizeIterator for KeyIter<'a, K, T, S, Ser> +impl<'a, K, T, Ser> ExactSizeIterator for KeyIter<'a, K, T, Ser> where K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { } @@ -750,15 +742,14 @@ where // =============================================================================================== /// An iterator over the (key, item) pairs of the Keymap. Less efficient than just iterating over keys. -pub struct KeyItemIter<'a, K, T, S, Ser> +pub struct KeyItemIter<'a, K, T, Ser> where K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { keymap: &'a Keymap<'a, K, T, Ser>, - storage: &'a S, + storage: &'a dyn Storage, start: u32, end: u32, saved_indexes: Option>>, @@ -767,15 +758,19 @@ where saved_back_index_page: Option, } -impl<'a, K, T, S, Ser> KeyItemIter<'a, K, T, S, Ser> +impl<'a, K, T, Ser> KeyItemIter<'a, K, T, Ser> where K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { /// constructor - pub fn new(keymap: &'a Keymap<'a, K, T, Ser>, storage: &'a S, start: u32, end: u32) -> Self { + pub fn new( + keymap: &'a Keymap<'a, K, T, Ser>, + storage: &'a dyn Storage, + start: u32, + end: u32, + ) -> Self { Self { keymap, storage, @@ -789,11 +784,10 @@ where } } -impl<'a, K, T, S, Ser> Iterator for KeyItemIter<'a, K, T, S, Ser> +impl<'a, K, T, Ser> Iterator for KeyItemIter<'a, K, T, Ser> where K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { type Item = StdResult<(K, T)>; @@ -918,11 +912,10 @@ where } } -impl<'a, K, T, S, Ser> DoubleEndedIterator for KeyItemIter<'a, K, T, S, Ser> +impl<'a, K, T, Ser> DoubleEndedIterator for KeyItemIter<'a, K, T, Ser> where K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { fn next_back(&mut self) -> Option { @@ -1041,11 +1034,10 @@ where } // This enables writing `append_store.iter().skip(n).rev()` -impl<'a, K, T, S, Ser> ExactSizeIterator for KeyItemIter<'a, K, T, S, Ser> +impl<'a, K, T, Ser> ExactSizeIterator for KeyItemIter<'a, K, T, Ser> where K: Serialize + DeserializeOwned, T: Serialize + DeserializeOwned, - S: ReadonlyStorage, Ser: Serde, { } @@ -1059,7 +1051,7 @@ trait PrefixedTypedStorage { /// /// * `storage` - a reference to the storage this item is in /// * `key` - a byte slice representing the key to access the stored item - fn contains_impl(&self, storage: &S, key: &[u8]) -> bool { + fn contains_impl(&self, storage: &dyn Storage, key: &[u8]) -> bool { let prefixed_key = [self.as_slice(), key].concat(); storage.get(&prefixed_key).is_some() } @@ -1071,7 +1063,7 @@ trait PrefixedTypedStorage { /// /// * `storage` - a reference to the storage this item is in /// * `key` - a byte slice representing the key to access the stored item - fn load_impl(&self, storage: &S, key: &[u8]) -> StdResult { + fn load_impl(&self, storage: &dyn Storage, key: &[u8]) -> StdResult { let prefixed_key = [self.as_slice(), key].concat(); Ser::deserialize( &storage @@ -1087,7 +1079,7 @@ trait PrefixedTypedStorage { /// /// * `storage` - a reference to the storage this item is in /// * `key` - a byte slice representing the key to access the stored item - fn may_load_impl(&self, storage: &S, key: &[u8]) -> StdResult> { + fn may_load_impl(&self, storage: &dyn Storage, key: &[u8]) -> StdResult> { let prefixed_key = [self.as_slice(), key].concat(); match storage.get(&prefixed_key) { Some(value) => Ser::deserialize(&value).map(Some), @@ -1102,7 +1094,7 @@ trait PrefixedTypedStorage { /// * `storage` - a mutable reference to the storage this item should go to /// * `key` - a byte slice representing the key to access the stored item /// * `value` - a reference to the item to store - fn save_impl(&self, storage: &mut S, key: &[u8], value: &T) -> StdResult<()> { + fn save_impl(&self, storage: &mut dyn Storage, key: &[u8], value: &T) -> StdResult<()> { let prefixed_key = [self.as_slice(), key].concat(); storage.set(&prefixed_key, &Ser::serialize(value)?); Ok(()) @@ -1114,7 +1106,7 @@ trait PrefixedTypedStorage { /// /// * `storage` - a mutable reference to the storage this item is in /// * `key` - a byte slice representing the key to access the stored item - fn remove_impl(&self, storage: &mut S, key: &[u8]) { + fn remove_impl(&self, storage: &mut dyn Storage, key: &[u8]) { let prefixed_key = [self.as_slice(), key].concat(); storage.remove(&prefixed_key); } @@ -1262,7 +1254,7 @@ mod tests { keymap.insert(&mut storage, &b"key1".to_vec(), &foo1)?; let contains_k1 = keymap.contains(&storage, &b"key1".to_vec()); - assert!(contains_k1); + assert_eq!(contains_k1, true); Ok(()) } diff --git a/packages/toolkit/Cargo.toml b/packages/toolkit/Cargo.toml index db876bb..148b486 100644 --- a/packages/toolkit/Cargo.toml +++ b/packages/toolkit/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "secret-toolkit" -version = "0.5.0" +version = "0.6.0" edition = "2018" authors = ["SCRT Labs "] license-file = "../../LICENSE" @@ -16,9 +16,18 @@ all-features = true [features] default = ["serialization", "snip20", "snip721", "storage", "utils"] -crypto = ["secret-toolkit-crypto"] # Not in default features because this is slow to compile -incubator = ["secret-toolkit-incubator", "serialization"] # Should never be in default features! -permit = ["secret-toolkit-permit", "crypto", "utils"] # Not in default features because it requires "crypto" +crypto = [ + "secret-toolkit-crypto", +] # Not in default features because this is slow to compile +incubator = [ + "secret-toolkit-incubator", + "serialization", +] # Should never be in default features! +permit = [ + "secret-toolkit-permit", + "crypto", + "utils", +] # Not in default features because it requires "crypto" serialization = ["secret-toolkit-serialization"] snip20 = ["secret-toolkit-snip20", "utils"] snip721 = ["secret-toolkit-snip721", "utils"] @@ -27,12 +36,12 @@ utils = ["secret-toolkit-utils"] viewing-key = ["secret-toolkit-viewing-key"] [dependencies] -secret-toolkit-crypto = { version = "0.3.0", path = "../crypto", optional = true } -secret-toolkit-incubator = { version = "0.4.0", path = "../incubator", optional = true } -secret-toolkit-permit = { version = "0.3.0", path = "../permit", optional = true } -secret-toolkit-serialization = { version = "0.3", path = "../serialization", optional = true } -secret-toolkit-snip20 = { version = "0.3", path = "../snip20", optional = true } -secret-toolkit-snip721 = { version = "0.3", path = "../snip721", optional = true } -secret-toolkit-storage = { version = "0.5", path = "../storage", optional = true } -secret-toolkit-utils = { version = "0.3", path = "../utils", optional = true } -secret-toolkit-viewing-key = { version = "0.3", path = "../viewing_key", optional = true } +secret-toolkit-crypto = { version = "0.6.0", path = "../crypto", optional = true } +secret-toolkit-incubator = { version = "0.6.0", path = "../incubator", optional = true } +secret-toolkit-permit = { version = "0.6.0", path = "../permit", optional = true } +secret-toolkit-serialization = { version = "0.6", path = "../serialization", optional = true } +secret-toolkit-snip20 = { version = "0.6", path = "../snip20", optional = true } +secret-toolkit-snip721 = { version = "0.6", path = "../snip721", optional = true } +secret-toolkit-storage = { version = "0.6", path = "../storage", optional = true } +secret-toolkit-utils = { version = "0.6", path = "../utils", optional = true } +secret-toolkit-viewing-key = { version = "0.6", path = "../viewing_key", optional = true } diff --git a/packages/utils/Cargo.toml b/packages/utils/Cargo.toml index 49ad01f..02267c4 100644 --- a/packages/utils/Cargo.toml +++ b/packages/utils/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "secret-toolkit-utils" -version = "0.3.1" +version = "0.6.0" edition = "2018" authors = ["SCRT Labs "] license-file = "../../LICENSE" @@ -15,6 +15,6 @@ all-features = true [dependencies] serde = "1.0" -schemars = "0.7" -cosmwasm-std = { package = "secret-cosmwasm-std", version = "0.10" } -cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "0.10"} +schemars = "0.8.1" +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.0.0" } +cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "1.0.0" } diff --git a/packages/utils/src/calls.rs b/packages/utils/src/calls.rs index 5f94321..b4de5a3 100755 --- a/packages/utils/src/calls.rs +++ b/packages/utils/src/calls.rs @@ -1,8 +1,8 @@ use serde::{de::DeserializeOwned, Serialize}; use cosmwasm_std::{ - to_binary, Coin, CosmosMsg, HumanAddr, Querier, QueryRequest, StdResult, Uint128, WasmMsg, - WasmQuery, + to_binary, Coin, CosmosMsg, CustomQuery, QuerierWrapper, QueryRequest, StdResult, Uint128, + WasmMsg, WasmQuery, }; use super::space_pad; @@ -25,14 +25,14 @@ pub trait InitCallback: Serialize { /// /// * `label` - String holding the label for the new contract instance /// * `code_id` - code ID of the contract to be instantiated - /// * `callback_code_hash` - String holding the code hash of the contract to be instantiated - /// * `send_amount` - Optional Uint128 amount of native coin to send with instantiation message + /// * `code_hash` - String holding the code hash of the contract to be instantiated + /// * `funds_amount` - Optional Uint128 amount of native coin to send with instantiation message fn to_cosmos_msg( &self, label: String, code_id: u64, - callback_code_hash: String, - send_amount: Option, + code_hash: String, + funds_amount: Option, ) -> StdResult { let mut msg = to_binary(self)?; // can not have 0 block size @@ -42,9 +42,9 @@ pub trait InitCallback: Serialize { Self::BLOCK_SIZE }; space_pad(&mut msg.0, padding); - let mut send = Vec::new(); - if let Some(amount) = send_amount { - send.push(Coin { + let mut funds = Vec::new(); + if let Some(amount) = funds_amount { + funds.push(Coin { amount, denom: String::from("uscrt"), }); @@ -52,8 +52,8 @@ pub trait InitCallback: Serialize { let init = WasmMsg::Instantiate { code_id, msg, - callback_code_hash, - send, + code_hash, + funds, label, }; Ok(init.into()) @@ -76,14 +76,14 @@ pub trait HandleCallback: Serialize { /// /// # Arguments /// - /// * `callback_code_hash` - String holding the code hash of the contract to be executed + /// * `code_hash` - String holding the code hash of the contract to be executed /// * `contract_addr` - address of the contract being called - /// * `send_amount` - Optional Uint128 amount of native coin to send with the handle message + /// * `funds_amount` - Optional Uint128 amount of native coin to send with the handle message fn to_cosmos_msg( &self, - callback_code_hash: String, - contract_addr: HumanAddr, - send_amount: Option, + code_hash: String, + contract_addr: String, + funds_amount: Option, ) -> StdResult { let mut msg = to_binary(self)?; // can not have 0 block size @@ -93,9 +93,9 @@ pub trait HandleCallback: Serialize { Self::BLOCK_SIZE }; space_pad(&mut msg.0, padding); - let mut send = Vec::new(); - if let Some(amount) = send_amount { - send.push(Coin { + let mut funds = Vec::new(); + if let Some(amount) = funds_amount { + funds.push(Coin { amount, denom: String::from("uscrt"), }); @@ -103,8 +103,8 @@ pub trait HandleCallback: Serialize { let execute = WasmMsg::Execute { msg, contract_addr, - callback_code_hash, - send, + code_hash, + funds, }; Ok(execute.into()) } @@ -127,11 +127,11 @@ pub trait Query: Serialize { /// * `querier` - a reference to the Querier dependency of the querying contract /// * `callback_code_hash` - String holding the code hash of the contract to be queried /// * `contract_addr` - address of the contract being queried - fn query( + fn query( &self, - querier: &Q, - callback_code_hash: String, - contract_addr: HumanAddr, + querier: QuerierWrapper, + code_hash: String, + contract_addr: String, ) -> StdResult { let mut msg = to_binary(self)?; // can not have 0 block size @@ -143,7 +143,7 @@ pub trait Query: Serialize { space_pad(&mut msg.0, padding); querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr, - callback_code_hash, + code_hash, msg, })) } @@ -152,7 +152,9 @@ pub trait Query: Serialize { #[cfg(test)] mod tests { use super::*; - use cosmwasm_std::{to_vec, Binary, Querier, QuerierResult}; + use cosmwasm_std::{ + to_vec, Binary, ContractResult, Empty, Querier, QuerierResult, SystemError, SystemResult, + }; use serde::Deserialize; #[derive(Serialize)] @@ -186,9 +188,9 @@ mod tests { #[test] fn test_handle_callback_implementation_works() -> StdResult<()> { - let address = HumanAddr("secret1xyzasdf".to_string()); + let address = "secret1xyzasdf".to_string(); let hash = "asdf".to_string(); - let amount = Uint128(1234); + let amount = Uint128::new(1234); let cosmos_message: CosmosMsg = FooHandle::Var1 { f1: 1, f2: 2 }.to_cosmos_msg( hash.clone(), @@ -199,16 +201,16 @@ mod tests { match cosmos_message { CosmosMsg::Wasm(WasmMsg::Execute { contract_addr, - callback_code_hash, + code_hash, msg, - send, + funds, }) => { assert_eq!(contract_addr, address); - assert_eq!(callback_code_hash, hash); + assert_eq!(code_hash, hash); let mut expected_msg = r#"{"Var1":{"f1":1,"f2":2}}"#.as_bytes().to_vec(); space_pad(&mut expected_msg, 256); assert_eq!(msg.0, expected_msg); - assert_eq!(send, vec![Coin::new(amount.0, "uscrt")]) + assert_eq!(funds, vec![Coin::new(amount.u128(), "uscrt")]) } other => panic!("unexpected CosmosMsg variant: {:?}", other), }; @@ -221,7 +223,7 @@ mod tests { let lbl = "testlabel".to_string(); let id = 17u64; let hash = "asdf".to_string(); - let amount = Uint128(1234); + let amount = Uint128::new(1234); let cosmos_message: CosmosMsg = FooInit { f1: 1, f2: 2 }.to_cosmos_msg(lbl.clone(), id, hash.clone(), Some(amount))?; @@ -230,16 +232,16 @@ mod tests { CosmosMsg::Wasm(WasmMsg::Instantiate { code_id, msg, - callback_code_hash, - send, + code_hash, + funds, label, }) => { assert_eq!(code_id, id); let mut expected_msg = r#"{"f1":1,"f2":2}"#.as_bytes().to_vec(); space_pad(&mut expected_msg, 256); assert_eq!(msg.0, expected_msg); - assert_eq!(callback_code_hash, hash); - assert_eq!(send, vec![Coin::new(amount.0, "uscrt")]); + assert_eq!(code_hash, hash); + assert_eq!(funds, vec![Coin::new(amount.u128(), "uscrt")]); assert_eq!(label, lbl) } other => panic!("unexpected CosmosMsg variant: {:?}", other), @@ -264,22 +266,26 @@ mod tests { space_pad(&mut expected_msg, 256); let expected_request: QueryRequest = QueryRequest::Wasm(WasmQuery::Smart { - contract_addr: HumanAddr("secret1xyzasdf".to_string()), - callback_code_hash: "asdf".to_string(), + contract_addr: "secret1xyzasdf".to_string(), + code_hash: "asdf".to_string(), msg: Binary(expected_msg), }); let test_req: &[u8] = &to_vec(&expected_request).unwrap(); assert_eq!(request, test_req); - Ok(to_binary(&QueryResponse { bar1: 1, bar2: 2 })) + let response = match to_binary(&QueryResponse { bar1: 1, bar2: 2 }) { + Ok(response) => ContractResult::Ok(response), + Err(_e) => return SystemResult::Err(SystemError::Unknown {}), + }; + SystemResult::Ok(response) } } - let querier = MyMockQuerier {}; - let address = HumanAddr("secret1xyzasdf".to_string()); + let querier = QuerierWrapper::::new(&MyMockQuerier {}); + let address = "secret1xyzasdf".to_string(); let hash = "asdf".to_string(); let response: QueryResponse = - FooQuery::Query1 { f1: 1, f2: 2 }.query(&querier, hash, address)?; + FooQuery::Query1 { f1: 1, f2: 2 }.query(querier, hash, address)?; assert_eq!(response, QueryResponse { bar1: 1, bar2: 2 }); Ok(()) diff --git a/packages/utils/src/feature_toggle.rs b/packages/utils/src/feature_toggle.rs index 60912eb..82bab57 100644 --- a/packages/utils/src/feature_toggle.rs +++ b/packages/utils/src/feature_toggle.rs @@ -1,6 +1,6 @@ use cosmwasm_std::{ - to_binary, to_vec, Api, Env, Extern, HandleResponse, HandleResult, HumanAddr, Querier, - QueryResult, ReadonlyStorage, StdError, StdResult, Storage, + to_binary, to_vec, Addr, Binary, Deps, DepsMut, MessageInfo, Response, StdError, StdResult, + Storage, }; use cosmwasm_storage::{Bucket, ReadonlyBucket}; use schemars::JsonSchema; @@ -19,10 +19,10 @@ impl FeatureToggleTrait for FeatureToggle { pub trait FeatureToggleTrait { const STORAGE_KEY: &'static [u8]; - fn init_features( - storage: &mut S, + fn init_features( + storage: &mut dyn Storage, feature_statuses: Vec>, - pausers: Vec, + pausers: Vec, ) -> StdResult<()> { for fs in feature_statuses { Self::set_feature_status(storage, &fs.feature, fs.status)?; @@ -35,10 +35,7 @@ pub trait FeatureToggleTrait { Ok(()) } - fn require_not_paused( - storage: &S, - features: Vec, - ) -> StdResult<()> { + fn require_not_paused(storage: &dyn Storage, features: Vec) -> StdResult<()> { for feature in features { let status = Self::get_feature_status(storage, &feature)?; match status { @@ -63,7 +60,7 @@ pub trait FeatureToggleTrait { Ok(()) } - fn pause(storage: &mut S, features: Vec) -> StdResult<()> { + fn pause(storage: &mut dyn Storage, features: Vec) -> StdResult<()> { for f in features { Self::set_feature_status(storage, &f, Status::Paused)?; } @@ -71,7 +68,7 @@ pub trait FeatureToggleTrait { Ok(()) } - fn unpause(storage: &mut S, features: Vec) -> StdResult<()> { + fn unpause(storage: &mut dyn Storage, features: Vec) -> StdResult<()> { for f in features { Self::set_feature_status(storage, &f, Status::NotPaused)?; } @@ -79,122 +76,97 @@ pub trait FeatureToggleTrait { Ok(()) } - fn is_pauser(storage: &S, key: &HumanAddr) -> StdResult { - let feature_store: ReadonlyBucket = - ReadonlyBucket::multilevel(&[Self::STORAGE_KEY, PREFIX_PAUSERS], storage); - feature_store - .may_load(key.0.as_bytes()) - .map(|p| p.is_some()) + fn is_pauser(storage: &dyn Storage, key: &Addr) -> StdResult { + let feature_store: ReadonlyBucket = + ReadonlyBucket::multilevel(storage, &[Self::STORAGE_KEY, PREFIX_PAUSERS]); + feature_store.may_load(key.as_bytes()).map(|p| p.is_some()) } - fn set_pauser(storage: &mut S, key: &HumanAddr) -> StdResult<()> { - let mut feature_store = Bucket::multilevel(&[Self::STORAGE_KEY, PREFIX_PAUSERS], storage); - feature_store.save(key.0.as_bytes(), &true /* value is insignificant */) + fn set_pauser(storage: &mut dyn Storage, key: &Addr) -> StdResult<()> { + let mut feature_store = Bucket::multilevel(storage, &[Self::STORAGE_KEY, PREFIX_PAUSERS]); + feature_store.save(key.as_bytes(), &true /* value is insignificant */) } - fn remove_pauser(storage: &mut S, key: &HumanAddr) { - let mut feature_store: Bucket = - Bucket::multilevel(&[Self::STORAGE_KEY, PREFIX_PAUSERS], storage); - feature_store.remove(key.0.as_bytes()) + fn remove_pauser(storage: &mut dyn Storage, key: &Addr) { + let mut feature_store: Bucket = + Bucket::multilevel(storage, &[Self::STORAGE_KEY, PREFIX_PAUSERS]); + feature_store.remove(key.as_bytes()) } - fn get_feature_status( - storage: &S, + fn get_feature_status( + storage: &dyn Storage, key: &T, ) -> StdResult> { let feature_store = - ReadonlyBucket::multilevel(&[Self::STORAGE_KEY, PREFIX_FEATURES], storage); + ReadonlyBucket::multilevel(storage, &[Self::STORAGE_KEY, PREFIX_FEATURES]); feature_store.may_load(&cosmwasm_std::to_vec(&key)?) } - fn set_feature_status( - storage: &mut S, + fn set_feature_status( + storage: &mut dyn Storage, key: &T, item: Status, ) -> StdResult<()> { - let mut feature_store = Bucket::multilevel(&[Self::STORAGE_KEY, PREFIX_FEATURES], storage); + let mut feature_store = Bucket::multilevel(storage, &[Self::STORAGE_KEY, PREFIX_FEATURES]); feature_store.save(&cosmwasm_std::to_vec(&key)?, &item) } - fn handle_pause( - deps: &mut Extern, - env: &Env, + fn handle_pause( + deps: DepsMut, + info: &MessageInfo, features: Vec, - ) -> HandleResult { - if !Self::is_pauser(&deps.storage, &env.message.sender)? { - return Err(StdError::unauthorized()); + ) -> StdResult { + if !Self::is_pauser(deps.storage, &info.sender)? { + return Err(StdError::generic_err("unauthorized")); } - Self::pause(&mut deps.storage, features)?; + Self::pause(deps.storage, features)?; - Ok(HandleResponse { - messages: vec![], - log: vec![], - data: Some(to_binary(&HandleAnswer::Pause { - status: ResponseStatus::Success, - })?), - }) + Ok(Response::new().set_data(to_binary(&HandleAnswer::Pause { + status: ResponseStatus::Success, + })?)) } - fn handle_unpause( - deps: &mut Extern, - env: &Env, + fn handle_unpause( + deps: DepsMut, + info: &MessageInfo, features: Vec, - ) -> HandleResult { - if !Self::is_pauser(&deps.storage, &env.message.sender)? { - return Err(StdError::unauthorized()); + ) -> StdResult { + if !Self::is_pauser(deps.storage, &info.sender)? { + return Err(StdError::generic_err("unauthorized")); } - Self::unpause(&mut deps.storage, features)?; + Self::unpause(deps.storage, features)?; - Ok(HandleResponse { - messages: vec![], - log: vec![], - data: Some(to_binary(&HandleAnswer::Unpause { - status: ResponseStatus::Success, - })?), - }) + Ok(Response::new().set_data(to_binary(&HandleAnswer::Unpause { + status: ResponseStatus::Success, + })?)) } - fn handle_set_pauser( - deps: &mut Extern, - _env: &Env, - address: HumanAddr, - ) -> HandleResult { - Self::set_pauser(&mut deps.storage, &address)?; - - Ok(HandleResponse { - messages: vec![], - log: vec![], - data: Some(to_binary(&HandleAnswer::SetPauser { + fn handle_set_pauser(deps: DepsMut, address: Addr) -> StdResult { + Self::set_pauser(deps.storage, &address)?; + + Ok( + Response::new().set_data(to_binary(&HandleAnswer::SetPauser { status: ResponseStatus::Success, })?), - }) + ) } - fn handle_remove_pauser( - deps: &mut Extern, - _env: &Env, - address: HumanAddr, - ) -> HandleResult { - Self::remove_pauser(&mut deps.storage, &address); - - Ok(HandleResponse { - messages: vec![], - log: vec![], - data: Some(to_binary(&HandleAnswer::RemovePauser { + fn handle_remove_pauser(deps: DepsMut, address: Addr) -> StdResult { + Self::remove_pauser(deps.storage, &address); + + Ok( + Response::new().set_data(to_binary(&HandleAnswer::RemovePauser { status: ResponseStatus::Success, })?), - }) + ) } - fn query_status( - deps: &Extern, - features: Vec, - ) -> QueryResult { + fn query_status(deps: Deps, features: Vec) -> StdResult { let mut status = Vec::with_capacity(features.len()); for feature in features { - match Self::get_feature_status(&deps.storage, &feature)? { + match Self::get_feature_status(deps.storage, &feature)? { None => { return Err(StdError::generic_err(format!( "invalid feature: {} does not exist", @@ -208,17 +180,14 @@ pub trait FeatureToggleTrait { to_binary(&FeatureToggleQueryAnswer::Status { features: status }) } - fn query_is_pauser( - deps: &Extern, - address: HumanAddr, - ) -> QueryResult { - let is_pauser = Self::is_pauser(&deps.storage, &address)?; + fn query_is_pauser(deps: Deps, address: Addr) -> StdResult { + let is_pauser = Self::is_pauser(deps.storage, &address)?; to_binary(&FeatureToggleQueryAnswer::<()>::IsPauser { is_pauser }) } } -#[derive(Serialize, Debug, Deserialize, Clone, JsonSchema, PartialEq)] +#[derive(Serialize, Debug, Deserialize, Clone, JsonSchema, PartialEq, Eq)] pub enum Status { NotPaused, Paused, @@ -230,7 +199,7 @@ impl Default for Status { } } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum FeatureToggleHandleMsg { #[serde(bound = "")] @@ -242,10 +211,10 @@ pub enum FeatureToggleHandleMsg { features: Vec, }, SetPauser { - address: HumanAddr, + address: String, }, RemovePauser { - address: HumanAddr, + address: String, }, } @@ -265,7 +234,7 @@ enum HandleAnswer { RemovePauser { status: ResponseStatus }, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum FeatureToggleQueryMsg { #[serde(bound = "")] @@ -273,7 +242,7 @@ pub enum FeatureToggleQueryMsg { features: Vec, }, IsPauser { - address: HumanAddr, + address: String, }, } @@ -296,8 +265,8 @@ mod tests { FeatureStatus, FeatureToggle, FeatureToggleHandleMsg, FeatureToggleQueryMsg, FeatureToggleTrait, HandleAnswer, ResponseStatus, Status, }; - use cosmwasm_std::testing::{mock_dependencies, mock_env, MockStorage}; - use cosmwasm_std::{from_binary, HumanAddr, MemoryStorage, StdError, StdResult}; + use cosmwasm_std::testing::{mock_dependencies, mock_info, MockStorage}; + use cosmwasm_std::{from_binary, Addr, MemoryStorage, StdError, StdResult}; fn init_features(storage: &mut MemoryStorage) -> StdResult<()> { FeatureToggle::init_features( @@ -316,7 +285,7 @@ mod tests { status: Status::Paused, }, ], - vec![HumanAddr("alice".to_string())], + vec![Addr::unchecked("alice".to_string())], ) } @@ -343,11 +312,11 @@ mod tests { ); assert_eq!( - FeatureToggle::is_pauser(&storage, &HumanAddr("alice".to_string()))?, + FeatureToggle::is_pauser(&storage, &Addr::unchecked("alice".to_string()))?, true ); assert_eq!( - FeatureToggle::is_pauser(&storage, &HumanAddr("bob".to_string()))?, + FeatureToggle::is_pauser(&storage, &Addr::unchecked("bob".to_string()))?, false ); @@ -370,16 +339,17 @@ mod tests { #[test] fn test_handle_unpause() -> StdResult<()> { - let mut deps = mock_dependencies(20, &[]); + let mut deps = mock_dependencies(); init_features(&mut deps.storage)?; - let env = mock_env("non-pauser", &[]); - let error = FeatureToggle::handle_unpause(&mut deps, &env, vec!["Feature3".to_string()]); - assert_eq!(error, Err(StdError::unauthorized())); + let info = mock_info("non-pauser", &[]); + let error = + FeatureToggle::handle_unpause(deps.as_mut(), &info, vec!["Feature3".to_string()]); + assert_eq!(error, Err(StdError::generic_err("unauthorized"))); - let env = mock_env("alice", &[]); + let info = mock_info("alice", &[]); let response = - FeatureToggle::handle_unpause(&mut deps, &env, vec!["Feature3".to_string()])?; + FeatureToggle::handle_unpause(deps.as_mut(), &info, vec!["Feature3".to_string()])?; let answer: HandleAnswer = from_binary(&response.data.unwrap())?; assert_eq!( @@ -407,15 +377,16 @@ mod tests { #[test] fn test_handle_pause() -> StdResult<()> { - let mut deps = mock_dependencies(20, &[]); + let mut deps = mock_dependencies(); init_features(&mut deps.storage)?; - let env = mock_env("non-pauser", &[]); - let error = FeatureToggle::handle_pause(&mut deps, &env, vec!["Feature2".to_string()]); - assert_eq!(error, Err(StdError::unauthorized())); + let info = mock_info("non-pauser", &[]); + let error = FeatureToggle::handle_pause(deps.as_mut(), &info, vec!["Feature2".to_string()]); + assert_eq!(error, Err(StdError::generic_err("unauthorized"))); - let env = mock_env("alice", &[]); - let response = FeatureToggle::handle_pause(&mut deps, &env, vec!["Feature2".to_string()])?; + let info = mock_info("alice", &[]); + let response = + FeatureToggle::handle_pause(deps.as_mut(), &info, vec!["Feature2".to_string()])?; let answer: HandleAnswer = from_binary(&response.data.unwrap())?; assert_eq!( @@ -451,7 +422,7 @@ mod tests { let mut storage = MockStorage::new(); init_features(&mut storage)?; - let bob = HumanAddr("bob".to_string()); + let bob = Addr::unchecked("bob".to_string()); FeatureToggle::set_pauser(&mut storage, &bob)?; assert!( diff --git a/packages/utils/src/padding.rs b/packages/utils/src/padding.rs index b7c3817..a778083 100644 --- a/packages/utils/src/padding.rs +++ b/packages/utils/src/padding.rs @@ -1,4 +1,4 @@ -use cosmwasm_std::{HandleResult, QueryResult}; +use cosmwasm_std::{Binary, Response}; /// Take a Vec and pad it up to a multiple of `block_size`, using spaces at the end. pub fn space_pad(message: &mut Vec, block_size: usize) -> &mut Vec { @@ -14,11 +14,13 @@ pub fn space_pad(message: &mut Vec, block_size: usize) -> &mut Vec { message } -/// Pad the data and logs in a `HandleResult` to the block size, with spaces. -// The big `where` clause is based on the `where` clause of `HandleResponse`. +/// Pad the data and logs in a `Result` to the block size, with spaces. // Users don't need to care about it as the type `T` has a default, and will // always be known in the context of the caller. -pub fn pad_handle_result(response: HandleResult, block_size: usize) -> HandleResult +pub fn pad_handle_result( + response: Result, E>, + block_size: usize, +) -> Result, E> where T: Clone + std::fmt::Debug + PartialEq + schemars::JsonSchema, { @@ -27,18 +29,18 @@ where space_pad(&mut data.0, block_size); data }); - for log in &mut response.log { + for attribute in &mut response.attributes { // Safety: These two are safe because we know the characters that // `space_pad` appends are valid UTF-8 - unsafe { space_pad(log.key.as_mut_vec(), block_size) }; - unsafe { space_pad(log.value.as_mut_vec(), block_size) }; + unsafe { space_pad(attribute.key.as_mut_vec(), block_size) }; + unsafe { space_pad(attribute.value.as_mut_vec(), block_size) }; } response }) } /// Pad a `QueryResult` with spaces -pub fn pad_query_result(response: QueryResult, block_size: usize) -> QueryResult { +pub fn pad_query_result(response: Result, block_size: usize) -> Result { response.map(|mut response| { space_pad(&mut response.0, block_size); response diff --git a/packages/utils/src/types.rs b/packages/utils/src/types.rs index 608fabd..2870025 100644 --- a/packages/utils/src/types.rs +++ b/packages/utils/src/types.rs @@ -1,9 +1,21 @@ -use cosmwasm_std::HumanAddr; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone, JsonSchema)] pub struct Contract { - pub address: HumanAddr, + pub address: String, pub hash: String, } + +#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone, JsonSchema)] +pub struct WasmCode { + pub code_id: u64, + pub hash: String, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Token { + Snip20(Contract), + Native(String), +} diff --git a/packages/viewing_key/Cargo.toml b/packages/viewing_key/Cargo.toml index bd05cd6..46632fc 100644 --- a/packages/viewing_key/Cargo.toml +++ b/packages/viewing_key/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "secret-toolkit-viewing-key" -version = "0.3.0" +version = "0.6.0" edition = "2018" authors = ["SCRT Labs "] license-file = "../../LICENSE" @@ -18,7 +18,10 @@ serde = "1.0" schemars = "0.7" base64 = "0.11.0" # Same as used by cosmwas-std subtle = { version = "2.2.3", default-features = false } -cosmwasm-std = { package = "secret-cosmwasm-std", version = "0.10" } -cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "0.10" } -secret-toolkit-crypto = { version = "0.3", path = "../crypto", default-features = false, features = ["hash", "rand"] } -secret-toolkit-utils = { version = "0.3", path = "../utils" } +cosmwasm-std = { package = "secret-cosmwasm-std", version = "1.0.0" } +cosmwasm-storage = { package = "secret-cosmwasm-storage", version = "1.0.0" } +secret-toolkit-crypto = { version = "0.6", path = "../crypto", default-features = false, features = [ + "hash", + "rand", +] } +secret-toolkit-utils = { version = "0.6", path = "../utils" } diff --git a/packages/viewing_key/src/lib.rs b/packages/viewing_key/src/lib.rs index 5c05009..a31c0a9 100644 --- a/packages/viewing_key/src/lib.rs +++ b/packages/viewing_key/src/lib.rs @@ -4,7 +4,7 @@ extern crate core; use subtle::ConstantTimeEq; -use cosmwasm_std::{Env, HumanAddr, ReadonlyStorage, StdError, StdResult, Storage}; +use cosmwasm_std::{Env, MessageInfo, StdError, StdResult, Storage}; use cosmwasm_storage::{PrefixedStorage, ReadonlyPrefixedStorage}; use secret_toolkit_crypto::{sha_256, Prng, SHA256_HASH_SIZE}; @@ -31,7 +31,7 @@ pub trait ViewingKeyStore { const STORAGE_KEY: &'static [u8]; /// Set the initial prng seed for the store - fn set_seed(storage: &mut S, seed: &[u8]) { + fn set_seed(storage: &mut dyn Storage, seed: &[u8]) { let mut seed_key = Vec::new(); seed_key.extend_from_slice(Self::STORAGE_KEY); seed_key.extend_from_slice(SEED_KEY); @@ -42,10 +42,11 @@ pub trait ViewingKeyStore { /// Create a new viewing key, save it to storage, and return it. /// /// The random entropy should be provided from some external source, such as the user. - fn create( - storage: &mut S, + fn create( + storage: &mut dyn Storage, + info: &MessageInfo, env: &Env, - account: &HumanAddr, + account: &str, entropy: &[u8], ) -> String { let mut seed_key = Vec::with_capacity(Self::STORAGE_KEY.len() + SEED_KEY.len()); @@ -53,10 +54,10 @@ pub trait ViewingKeyStore { seed_key.extend_from_slice(SEED_KEY); let seed = storage.get(&seed_key).unwrap_or_default(); - let (viewing_key, next_seed) = new_viewing_key(env, &seed, entropy); - let mut balance_store = PrefixedStorage::new(Self::STORAGE_KEY, storage); + let (viewing_key, next_seed) = new_viewing_key(info, env, &seed, entropy); + let mut balance_store = PrefixedStorage::new(storage, Self::STORAGE_KEY); let hashed_key = sha_256(viewing_key.as_bytes()); - balance_store.set(account.as_str().as_bytes(), &hashed_key); + balance_store.set(account.as_bytes(), &hashed_key); storage.set(&seed_key, &next_seed); @@ -64,22 +65,15 @@ pub trait ViewingKeyStore { } /// Set a new viewing key based on a predetermined value. - fn set(storage: &mut S, account: &HumanAddr, viewing_key: &str) { - let mut balance_store = PrefixedStorage::new(Self::STORAGE_KEY, storage); - balance_store.set( - account.as_str().as_bytes(), - &sha_256(viewing_key.as_bytes()), - ); + fn set(storage: &mut dyn Storage, account: &str, viewing_key: &str) { + let mut balance_store = PrefixedStorage::new(storage, Self::STORAGE_KEY); + balance_store.set(account.as_bytes(), &sha_256(viewing_key.as_bytes())); } /// Check if a viewing key matches an account. - fn check( - storage: &S, - account: &HumanAddr, - viewing_key: &str, - ) -> StdResult<()> { - let balance_store = ReadonlyPrefixedStorage::new(Self::STORAGE_KEY, storage); - let expected_hash = balance_store.get(account.as_str().as_bytes()); + fn check(storage: &dyn Storage, account: &str, viewing_key: &str) -> StdResult<()> { + let balance_store = ReadonlyPrefixedStorage::new(storage, Self::STORAGE_KEY); + let expected_hash = balance_store.get(account.as_bytes()); let expected_hash = match &expected_hash { Some(hash) => hash.as_slice(), None => &[0u8; VIEWING_KEY_SIZE], @@ -88,18 +82,23 @@ pub trait ViewingKeyStore { if ct_slice_compare(&key_hash, expected_hash) { Ok(()) } else { - Err(StdError::unauthorized()) + Err(StdError::generic_err("unauthorized")) } } } -fn new_viewing_key(env: &Env, seed: &[u8], entropy: &[u8]) -> (String, [u8; 32]) { +fn new_viewing_key( + info: &MessageInfo, + env: &Env, + seed: &[u8], + entropy: &[u8], +) -> (String, [u8; 32]) { // 16 here represents the lengths in bytes of the block height and time. - let entropy_len = 16 + env.message.sender.len() + entropy.len(); + let entropy_len = 16 + info.sender.to_string().len() + entropy.len(); let mut rng_entropy = Vec::with_capacity(entropy_len); rng_entropy.extend_from_slice(&env.block.height.to_be_bytes()); - rng_entropy.extend_from_slice(&env.block.time.to_be_bytes()); - rng_entropy.extend_from_slice(env.message.sender.0.as_bytes()); + rng_entropy.extend_from_slice(&env.block.time.seconds().to_be_bytes()); + rng_entropy.extend_from_slice(info.sender.as_bytes()); rng_entropy.extend_from_slice(entropy); let mut rng = Prng::new(seed, &rng_entropy); @@ -120,32 +119,34 @@ fn ct_slice_compare(s1: &[u8], s2: &[u8]) -> bool { mod tests { use super::*; - use cosmwasm_std::testing::{mock_dependencies, mock_env}; + use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; #[test] fn test_viewing_keys() { - let account = HumanAddr("user-1".to_string()); + let account = "user-1".to_string(); - let mut deps = mock_dependencies(20, &[]); - let env = mock_env(account.as_str(), &[]); + let mut deps = mock_dependencies(); + let env = mock_env(); + let info = mock_info(account.as_str(), &[]); // VK not set yet: let result = ViewingKey::check(&deps.storage, &account, "fake key"); - assert_eq!(result, Err(StdError::unauthorized())); + assert_eq!(result, Err(StdError::generic_err("unauthorized"))); ViewingKey::set_seed(&mut deps.storage, b"seed"); - let viewing_key = ViewingKey::create(&mut deps.storage, &env, &account, b"entropy"); + let viewing_key = ViewingKey::create(&mut deps.storage, &info, &env, &account, b"entropy"); let result = ViewingKey::check(&deps.storage, &account, &viewing_key); assert_eq!(result, Ok(())); // Create a key with the same entropy. Check that it's different - let viewing_key_2 = ViewingKey::create(&mut deps.storage, &env, &account, b"entropy"); + let viewing_key_2 = + ViewingKey::create(&mut deps.storage, &info, &env, &account, b"entropy"); assert_ne!(viewing_key, viewing_key_2); // VK set to another key: let result = ViewingKey::check(&deps.storage, &account, "fake key"); - assert_eq!(result, Err(StdError::unauthorized())); + assert_eq!(result, Err(StdError::generic_err("unauthorized"))); let viewing_key = "custom key"; @@ -156,6 +157,6 @@ mod tests { // VK set to another key: let result = ViewingKey::check(&deps.storage, &account, "fake key"); - assert_eq!(result, Err(StdError::unauthorized())); + assert_eq!(result, Err(StdError::generic_err("unauthorized"))); } }