From db10cfda77388524b6b30faa7300b165c740e6d4 Mon Sep 17 00:00:00 2001 From: Xiliang Chen Date: Thu, 1 Apr 2021 16:15:32 +1300 Subject: [PATCH 01/14] add Handler (#431) --- traits/src/lib.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/traits/src/lib.rs b/traits/src/lib.rs index d8dfbab39..2aa3e19c9 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -1,7 +1,8 @@ #![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; -use sp_runtime::RuntimeDebug; +use impl_trait_for_tuples::impl_for_tuples; +use sp_runtime::{DispatchResult, RuntimeDebug}; use sp_std::{ cmp::{Eq, PartialEq}, prelude::Vec, @@ -64,11 +65,23 @@ pub struct TimestampedValue { pub timestamp: Moment, } -#[impl_trait_for_tuples::impl_for_tuples(30)] +#[impl_for_tuples(30)] pub trait Happened { fn happened(t: &T); } +pub trait Handler { + fn handle(t: &T) -> DispatchResult; +} + +#[impl_for_tuples(30)] +impl Handler for Tuple { + fn handle(t: &T) -> DispatchResult { + for_tuples!( #( Tuple::handle(t); )* ); + Ok(()) + } +} + pub trait Contains { fn contains(t: &T) -> bool; } From ea01954dc99347451113a652681c2d0104eaa767 Mon Sep 17 00:00:00 2001 From: Xiliang Chen Date: Mon, 5 Apr 2021 17:14:26 +1200 Subject: [PATCH 02/14] remove disable-tokens-by-owner (#434) --- Makefile | 2 -- auction/src/mock.rs | 1 + authority/src/mock.rs | 1 + benchmarking/src/tests.rs | 1 + currencies/src/mock.rs | 1 + gradually-update/src/mock.rs | 1 + nft/Cargo.toml | 1 - nft/src/lib.rs | 16 ++-------------- nft/src/mock.rs | 1 + oracle/src/mock.rs | 1 + rewards/src/mock.rs | 1 + tokens/src/mock.rs | 1 + unknown-tokens/src/mock.rs | 1 + vesting/src/mock.rs | 1 + 14 files changed, 13 insertions(+), 17 deletions(-) diff --git a/Makefile b/Makefile index afee442fd..9b45dce09 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,6 @@ check-tests: githooks test: githooks ./scripts/run.sh test - cargo test --manifest-path nft/Cargo.toml -p orml-nft --features disable-tokens-by-owner GITHOOKS_SRC = $(wildcard githooks/*) GITHOOKS_DEST = $(patsubst githooks/%, $(GITHOOK)/%, $(GITHOOKS_SRC)) @@ -48,4 +47,3 @@ dev-check-tests: Cargo.toml dev-test: Cargo.toml cargo test --all - cargo test --manifest-path nft/Cargo.toml -p orml-nft --features disable-tokens-by-owner diff --git a/auction/src/mock.rs b/auction/src/mock.rs index 25558c2eb..718c25164 100644 --- a/auction/src/mock.rs +++ b/auction/src/mock.rs @@ -42,6 +42,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } pub struct Handler; diff --git a/authority/src/mock.rs b/authority/src/mock.rs index 069f994a8..593710bc6 100644 --- a/authority/src/mock.rs +++ b/authority/src/mock.rs @@ -51,6 +51,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } parameter_types! { diff --git a/benchmarking/src/tests.rs b/benchmarking/src/tests.rs index 5068c8146..333a776cb 100644 --- a/benchmarking/src/tests.rs +++ b/benchmarking/src/tests.rs @@ -76,6 +76,7 @@ impl frame_system::Config for Test { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } impl tests::test::Config for Test { diff --git a/currencies/src/mock.rs b/currencies/src/mock.rs index a71a81f23..6eb8d883e 100644 --- a/currencies/src/mock.rs +++ b/currencies/src/mock.rs @@ -42,6 +42,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } type CurrencyId = u32; diff --git a/gradually-update/src/mock.rs b/gradually-update/src/mock.rs index d837e6367..410cb935d 100644 --- a/gradually-update/src/mock.rs +++ b/gradually-update/src/mock.rs @@ -39,6 +39,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } parameter_types! { diff --git a/nft/Cargo.toml b/nft/Cargo.toml index 27fb6a414..35f1b3cee 100644 --- a/nft/Cargo.toml +++ b/nft/Cargo.toml @@ -32,4 +32,3 @@ std = [ "frame-support/std", "frame-system/std", ] -disable-tokens-by-owner = [] diff --git a/nft/src/lib.rs b/nft/src/lib.rs index 706a76000..19110231b 100644 --- a/nft/src/lib.rs +++ b/nft/src/lib.rs @@ -136,9 +136,6 @@ pub mod module { StorageDoubleMap<_, Twox64Concat, T::ClassId, Twox64Concat, T::TokenId, TokenInfoOf>; /// Token existence check by owner and class ID. - // TODO: pallet macro doesn't support conditional compiling. Always having `TokensByOwner` storage doesn't hurt but - // it could be removed once conditional compiling supported. - // #[cfg(not(feature = "disable-tokens-by-owner"))] #[pallet::storage] #[pallet::getter(fn tokens_by_owner)] pub type TokensByOwner = @@ -216,11 +213,8 @@ impl Pallet { info.owner = to.clone(); - #[cfg(not(feature = "disable-tokens-by-owner"))] - { - TokensByOwner::::remove(from, token); - TokensByOwner::::insert(to, token, ()); - } + TokensByOwner::::remove(from, token); + TokensByOwner::::insert(to, token, ()); Ok(()) }) @@ -252,7 +246,6 @@ impl Pallet { data, }; Tokens::::insert(class_id, token_id, token_info); - #[cfg(not(feature = "disable-tokens-by-owner"))] TokensByOwner::::insert(owner, (class_id, token_id), ()); Ok(token_id) @@ -274,7 +267,6 @@ impl Pallet { Ok(()) })?; - #[cfg(not(feature = "disable-tokens-by-owner"))] TokensByOwner::::remove(owner, token); Ok(()) @@ -295,10 +287,6 @@ impl Pallet { } pub fn is_owner(account: &T::AccountId, token: (T::ClassId, T::TokenId)) -> bool { - #[cfg(feature = "disable-tokens-by-owner")] - return Tokens::::get(token.0, token.1).map_or(false, |token| token.owner == *account); - - #[cfg(not(feature = "disable-tokens-by-owner"))] TokensByOwner::::contains_key(account, token) } } diff --git a/nft/src/mock.rs b/nft/src/mock.rs index cf4bac4f2..915f67561 100644 --- a/nft/src/mock.rs +++ b/nft/src/mock.rs @@ -40,6 +40,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } impl Config for Runtime { diff --git a/oracle/src/mock.rs b/oracle/src/mock.rs index c7ea7487f..569dcdc6a 100644 --- a/oracle/src/mock.rs +++ b/oracle/src/mock.rs @@ -45,6 +45,7 @@ impl frame_system::Config for Test { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } thread_local! { diff --git a/rewards/src/mock.rs b/rewards/src/mock.rs index d088983b2..2a34337b3 100644 --- a/rewards/src/mock.rs +++ b/rewards/src/mock.rs @@ -49,6 +49,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } thread_local! { diff --git a/tokens/src/mock.rs b/tokens/src/mock.rs index bc430b16a..607693940 100644 --- a/tokens/src/mock.rs +++ b/tokens/src/mock.rs @@ -54,6 +54,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } thread_local! { diff --git a/unknown-tokens/src/mock.rs b/unknown-tokens/src/mock.rs index 1a68d01c4..b8e297a15 100644 --- a/unknown-tokens/src/mock.rs +++ b/unknown-tokens/src/mock.rs @@ -38,6 +38,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } impl Config for Runtime { diff --git a/vesting/src/mock.rs b/vesting/src/mock.rs index c99f50059..e3b250191 100644 --- a/vesting/src/mock.rs +++ b/vesting/src/mock.rs @@ -38,6 +38,7 @@ impl frame_system::Config for Runtime { type BaseCallFilter = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } type Balance = u64; From 3a77e1a96aa49af09f4c5584ff212673132c5456 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Tue, 6 Apr 2021 12:03:35 +1200 Subject: [PATCH 03/14] Cross-chain transfer rework (#432) * Reserve chain trait. * Rework cross-chain transfer. * Remove relay chain balance convert. * Add 'Parse' trait. * Change transfer_multiasset fn signature. * Add transfer dispatchable call. * Update doc. * Use xcm-simulator to mock network. * Send relay chain asset to sibling unit test. * Move location traits into orml-traits. * Add MultiNativeAsset filter for is reserve check. * More unit tests. * Failing edge case unit tests. * Handle zero amount asset case. * Fix mocks. * Renaming. --- traits/Cargo.toml | 2 + traits/src/lib.rs | 1 + traits/src/location.rs | 123 ++++++++++ unknown-tokens/src/tests.rs | 2 - xcm-support/src/lib.rs | 16 ++ xtokens/Cargo.toml | 11 + xtokens/src/lib.rs | 333 ++++++++++++-------------- xtokens/src/mock.rs | 452 ++++++++++++++++++++++++++++++++++++ xtokens/src/tests.rs | 290 +++++++++++++++++++++++ 9 files changed, 1043 insertions(+), 187 deletions(-) create mode 100644 traits/src/location.rs create mode 100644 xtokens/src/mock.rs create mode 100644 xtokens/src/tests.rs diff --git a/traits/Cargo.toml b/traits/Cargo.toml index 99f411be7..2c92c0f16 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -17,6 +17,7 @@ num-traits = { version = "0.2.14", default-features = false } impl-trait-for-tuples = "0.2.1" frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } orml-utilities = { path = "../utilities", version = "0.4.1-dev", default-features = false } +xcm = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1", default-features = false } funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 @@ -31,4 +32,5 @@ std = [ "num-traits/std", "frame-support/std", "orml-utilities/std", + "xcm/std", ] diff --git a/traits/src/lib.rs b/traits/src/lib.rs index 2aa3e19c9..a8962dbcf 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -28,6 +28,7 @@ pub mod auction; pub mod currency; pub mod data_provider; pub mod get_by_key; +pub mod location; pub mod nft; pub mod price; pub mod rewards; diff --git a/traits/src/location.rs b/traits/src/location.rs new file mode 100644 index 000000000..a0b9bdd0b --- /dev/null +++ b/traits/src/location.rs @@ -0,0 +1,123 @@ +use xcm::v0::{ + Junction::{self, *}, + MultiAsset, MultiLocation, +}; + +pub trait Parse { + /// Returns the "chain" location part. It could be parent, sibling + /// parachain, or child parachain. + fn chain_part(&self) -> Option; + /// Returns "non-chain" location part. + fn non_chain_part(&self) -> Option; +} + +fn is_chain_junction(junction: Option<&Junction>) -> bool { + matches!(junction, Some(Parent) | Some(Parachain { id: _ })) +} + +impl Parse for MultiLocation { + fn chain_part(&self) -> Option { + match (self.first(), self.at(1)) { + (Some(Parent), Some(Parachain { id })) => Some((Parent, Parachain { id: *id }).into()), + (Some(Parent), _) => Some(Parent.into()), + (Some(Parachain { id }), _) => Some(Parachain { id: *id }.into()), + _ => None, + } + } + + fn non_chain_part(&self) -> Option { + let mut location = self.clone(); + while is_chain_junction(location.first()) { + let _ = location.take_first(); + } + + if location != MultiLocation::Null { + Some(location) + } else { + None + } + } +} + +pub trait Reserve { + /// Returns assets reserve location. + fn reserve(&self) -> Option; +} + +impl Reserve for MultiAsset { + fn reserve(&self) -> Option { + if let MultiAsset::ConcreteFungible { id, .. } = self { + id.chain_part() + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PARACHAIN: Junction = Parachain { id: 1 }; + const GENERAL_INDEX: Junction = GeneralIndex { id: 1 }; + + fn concrete_fungible(id: MultiLocation) -> MultiAsset { + MultiAsset::ConcreteFungible { id, amount: 1 } + } + + #[test] + fn parent_as_reserve_chain() { + assert_eq!( + concrete_fungible(MultiLocation::X2(Parent, GENERAL_INDEX)).reserve(), + Some(Parent.into()) + ); + } + + #[test] + fn sibling_parachain_as_reserve_chain() { + assert_eq!( + concrete_fungible(MultiLocation::X3(Parent, PARACHAIN, GENERAL_INDEX)).reserve(), + Some((Parent, PARACHAIN).into()) + ); + } + + #[test] + fn child_parachain_as_reserve_chain() { + assert_eq!( + concrete_fungible(MultiLocation::X2(PARACHAIN, GENERAL_INDEX)).reserve(), + Some(PARACHAIN.into()) + ); + } + + #[test] + fn no_reserve_chain() { + assert_eq!( + concrete_fungible(MultiLocation::X1(GeneralKey("DOT".into()))).reserve(), + None + ); + } + + #[test] + fn non_chain_part_works() { + assert_eq!(MultiLocation::X1(Parent).non_chain_part(), None); + assert_eq!(MultiLocation::X2(Parent, PARACHAIN).non_chain_part(), None); + assert_eq!(MultiLocation::X1(PARACHAIN).non_chain_part(), None); + + assert_eq!( + MultiLocation::X2(Parent, GENERAL_INDEX).non_chain_part(), + Some(GENERAL_INDEX.into()) + ); + assert_eq!( + MultiLocation::X3(Parent, GENERAL_INDEX, GENERAL_INDEX).non_chain_part(), + Some((GENERAL_INDEX, GENERAL_INDEX).into()) + ); + assert_eq!( + MultiLocation::X3(Parent, PARACHAIN, GENERAL_INDEX).non_chain_part(), + Some(GENERAL_INDEX.into()) + ); + assert_eq!( + MultiLocation::X2(PARACHAIN, GENERAL_INDEX).non_chain_part(), + Some(GENERAL_INDEX.into()) + ); + } +} diff --git a/unknown-tokens/src/tests.rs b/unknown-tokens/src/tests.rs index 63ad7a2d4..b2cb39627 100644 --- a/unknown-tokens/src/tests.rs +++ b/unknown-tokens/src/tests.rs @@ -5,8 +5,6 @@ use super::*; use mock::{Event, *}; -use codec::{Decode, Encode}; - use frame_support::{assert_err, assert_ok}; use xcm::v0::Junction; diff --git a/xcm-support/src/lib.rs b/xcm-support/src/lib.rs index 5b419a71d..6963f0d5b 100644 --- a/xcm-support/src/lib.rs +++ b/xcm-support/src/lib.rs @@ -24,6 +24,8 @@ use sp_std::{ use xcm::v0::{Junction, MultiAsset, MultiLocation, Xcm}; use xcm_executor::traits::{FilterAssetLocation, MatchesFungible, NativeAsset}; +use orml_traits::location::Reserve; + pub use currency_adapter::MultiCurrencyAdapter; mod currency_adapter; @@ -90,6 +92,20 @@ impl, MultiLocation)>>> FilterAssetLocation for Nat } } +/// A `FilterAssetLocation` implementation. Filters multi native assets whose +/// reserve is same with `origin`. +pub struct MultiNativeAsset; +impl FilterAssetLocation for MultiNativeAsset { + fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { + if let Some(ref reserve) = asset.reserve() { + if reserve == origin { + return true; + } + } + false + } +} + /// `CurrencyIdConversion` implementation. Converts relay chain tokens, or /// parachain tokens that could be decoded from a general key. pub struct CurrencyIdConverter( diff --git a/xtokens/Cargo.toml b/xtokens/Cargo.toml index 3340fbacc..6f45a4462 100644 --- a/xtokens/Cargo.toml +++ b/xtokens/Cargo.toml @@ -22,11 +22,21 @@ cumulus-primitives-core = { git = "https://github.com/paritytech/cumulus", branc xcm = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1", default-features = false } orml-xcm-support = { path = "../xcm-support", default-features = false } +orml-traits = { path = "../traits", default-features = false} [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } polkadot-core-primitives = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1" } +polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } +xcm-simulator = { git = "https://github.com/shaunxw/xcm-simulator", branch = "master" } +cumulus-pallet-xcm-handler = { git = "https://github.com/paritytech/cumulus", branch = "rococo-v1" } +parachain-info = { git = "https://github.com/paritytech/cumulus", branch = "rococo-v1" } +xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1" } +xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1" } + orml-tokens = { path = "../tokens", version = "0.4.1-dev" } +orml-traits = { path = "../traits", version = "0.4.1-dev" } [features] default = ["std"] @@ -41,4 +51,5 @@ std = [ "cumulus-primitives-core/std", "xcm/std", "orml-xcm-support/std", + "orml-traits/std", ] diff --git a/xtokens/src/lib.rs b/xtokens/src/lib.rs index 92f4ad9b3..5ba280bf4 100644 --- a/xtokens/src/lib.rs +++ b/xtokens/src/lib.rs @@ -22,55 +22,32 @@ #![allow(clippy::unused_unit)] #![allow(clippy::large_enum_variant)] +use frame_support::{pallet_prelude::*, traits::Get, transactional, Parameter}; +use frame_system::{ensure_signed, pallet_prelude::*}; +use sp_runtime::{ + traits::{AtLeast32BitUnsigned, Convert, MaybeSerializeDeserialize, Member, Zero}, + DispatchError, +}; +use sp_std::prelude::*; + +use xcm::v0::{ + Junction::*, + MultiAsset, MultiLocation, Order, + Order::*, + Xcm::{self, *}, +}; + +use orml_traits::location::{Parse, Reserve}; +use orml_xcm_support::XcmHandler; + +mod mock; +mod tests; + pub use module::*; #[frame_support::pallet] pub mod module { - use codec::{Decode, Encode}; - use frame_support::{pallet_prelude::*, traits::Get, transactional, Parameter}; - use frame_system::{ensure_signed, pallet_prelude::*}; - use sp_runtime::{ - traits::{AtLeast32BitUnsigned, Convert, MaybeSerializeDeserialize, Member}, - RuntimeDebug, - }; - use sp_std::prelude::*; - - use cumulus_primitives_core::{relay_chain::Balance as RelayChainBalance, ParaId}; - use xcm::v0::{Junction, MultiAsset, MultiLocation, NetworkId, Order, Xcm}; - - use orml_xcm_support::XcmHandler; - - #[derive(Encode, Decode, Eq, PartialEq, Clone, Copy, RuntimeDebug)] - /// Identity of chain. - pub enum ChainId { - /// The relay chain. - RelayChain, - /// A parachain. - ParaChain(ParaId), - } - - #[derive(Encode, Decode, Eq, PartialEq, Clone, RuntimeDebug)] - /// Identity of cross chain currency. - pub struct XCurrencyId { - /// The reserve chain of the currency. For instance, the reserve chain - /// of DOT is Polkadot. - pub chain_id: ChainId, - /// The identity of the currency. - pub currency_id: Vec, - } - - #[cfg(test)] - impl XCurrencyId { - pub fn new(chain_id: ChainId, currency_id: Vec) -> Self { - XCurrencyId { chain_id, currency_id } - } - } - - impl Into for XCurrencyId { - fn into(self) -> MultiLocation { - MultiLocation::X1(Junction::GeneralKey(self.currency_id)) - } - } + use super::*; #[pallet::config] pub trait Config: frame_system::Config { @@ -85,18 +62,15 @@ pub mod module { + MaybeSerializeDeserialize + Into; - /// Convert `Balance` to `RelayChainBalance`. - type ToRelayChainBalance: Convert; + /// Currency Id. + type CurrencyId: Parameter + Member + Clone + Into; /// Convert `Self::Account` to `AccountId32` type AccountId32Convert: Convert; - /// The network id of relay chain. Typically `NetworkId::Polkadot` or - /// `NetworkId::Kusama`. - type RelayChainNetworkId: Get; - - /// Self parachain ID. - type ParaId: Get; + /// Self chain location. + #[pallet::constant] + type SelfLocation: Get; /// Xcm handler to execute XCM. type XcmHandler: XcmHandler; @@ -104,17 +78,23 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] + #[pallet::metadata(T::AccountId = "AccountId", T::CurrencyId = "CurrencyId", T::Balance = "Balance")] pub enum Event { - /// Transferred to relay chain. \[src, dest, amount\] - TransferredToRelayChain(T::AccountId, T::AccountId, T::Balance), - - /// Transferred to parachain. \[x_currency_id, src, para_id, dest, - /// dest_network, amount\] - TransferredToParachain(XCurrencyId, T::AccountId, ParaId, MultiLocation, T::Balance), + /// Transferred. \[sender, currency_id, amount, dest\] + Transferred(T::AccountId, T::CurrencyId, T::Balance, MultiLocation), + /// Transferred `MultiAsset`. \[sender, asset, dest\] + TransferredMultiAsset(T::AccountId, MultiAsset, MultiLocation), } #[pallet::error] - pub enum Error {} + pub enum Error { + /// Asset has no reserve location. + AssetHasNoReserve, + /// Not cross-chain transfer. + NotCrossChainTransfer, + /// Invalid transfer destination. + InvalidDest, + } #[pallet::hooks] impl Hooks for Pallet {} @@ -124,173 +104,156 @@ pub mod module { #[pallet::call] impl Pallet { - /// Transfer relay chain tokens to relay chain. - #[pallet::weight(10)] + /// Transfer native currencies. #[transactional] - pub fn transfer_to_relay_chain( + #[pallet::weight(1000)] + pub fn transfer( origin: OriginFor, - dest: T::AccountId, + currency_id: T::CurrencyId, amount: T::Balance, + dest: MultiLocation, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; - let xcm = Xcm::WithdrawAsset { - assets: vec![MultiAsset::ConcreteFungible { - id: MultiLocation::X1(Junction::Parent), - amount: T::ToRelayChainBalance::convert(amount), - }], - effects: vec![Order::InitiateReserveWithdraw { - assets: vec![MultiAsset::All], - reserve: MultiLocation::X1(Junction::Parent), - effects: vec![Order::DepositAsset { - assets: vec![MultiAsset::All], - dest: MultiLocation::X1(Junction::AccountId32 { - network: T::RelayChainNetworkId::get(), - id: T::AccountId32Convert::convert(dest.clone()), - }), - }], - }], - }; - T::XcmHandler::execute_xcm(who.clone(), xcm)?; + if amount == Zero::zero() { + return Ok(().into()); + } - Self::deposit_event(Event::::TransferredToRelayChain(who, dest, amount)); + let asset = MultiAsset::ConcreteFungible { + id: currency_id.clone().into(), + amount: amount.into(), + }; + Self::do_transfer_multiasset(who.clone(), asset, dest.clone())?; + Self::deposit_event(Event::::Transferred(who, currency_id, amount, dest)); Ok(().into()) } - /// Transfer tokens to a sibling parachain. - #[pallet::weight(10)] + /// Transfer `MultiAsset`. #[transactional] - pub fn transfer_to_parachain( + #[pallet::weight(1000)] + pub fn transfer_multiasset( origin: OriginFor, - x_currency_id: XCurrencyId, - para_id: ParaId, + asset: MultiAsset, dest: MultiLocation, - amount: T::Balance, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; - if para_id == T::ParaId::get() { + if Self::is_zero_amount(&asset) { return Ok(().into()); } - let xcm = match x_currency_id.chain_id { - ChainId::RelayChain => Self::transfer_relay_chain_tokens_to_parachain(para_id, dest.clone(), amount), - ChainId::ParaChain(reserve_chain) => { - if T::ParaId::get() == reserve_chain { - Self::transfer_owned_tokens_to_parachain(x_currency_id.clone(), para_id, dest.clone(), amount) - } else { - Self::transfer_non_owned_tokens_to_parachain( - reserve_chain, - x_currency_id.clone(), - para_id, - dest.clone(), - amount, - ) - } - } - }; - T::XcmHandler::execute_xcm(who.clone(), xcm)?; - - Self::deposit_event(Event::::TransferredToParachain( - x_currency_id, - who, - para_id, - dest, - amount, - )); + Self::do_transfer_multiasset(who.clone(), asset.clone(), dest.clone())?; + Self::deposit_event(Event::::TransferredMultiAsset(who, asset, dest)); Ok(().into()) } } impl Pallet { - fn transfer_relay_chain_tokens_to_parachain(para_id: ParaId, dest: MultiLocation, amount: T::Balance) -> Xcm { - Xcm::WithdrawAsset { - assets: vec![MultiAsset::ConcreteFungible { - id: MultiLocation::X1(Junction::Parent), - amount: T::ToRelayChainBalance::convert(amount), + /// Transfer `MultiAsset` without depositing event. + fn do_transfer_multiasset( + who: T::AccountId, + asset: MultiAsset, + dest: MultiLocation, + ) -> DispatchResultWithPostInfo { + let (dest, recipient) = Self::ensure_valid_dest(dest)?; + + let self_location = T::SelfLocation::get(); + ensure!(dest != self_location, Error::::NotCrossChainTransfer); + + let reserve = asset.reserve().ok_or(Error::::AssetHasNoReserve)?; + let xcm = if reserve == self_location { + Self::transfer_self_reserve_asset(asset, dest, recipient) + } else if reserve == dest { + Self::transfer_to_reserve(asset, dest, recipient) + } else { + Self::transfer_to_non_reserve(asset, reserve, dest, recipient) + }; + + T::XcmHandler::execute_xcm(who, xcm)?; + + Ok(().into()) + } + + fn transfer_self_reserve_asset(asset: MultiAsset, dest: MultiLocation, recipient: MultiLocation) -> Xcm { + WithdrawAsset { + assets: vec![asset], + effects: vec![DepositReserveAsset { + assets: vec![MultiAsset::All], + dest, + effects: Self::deposit_asset(recipient), }], - effects: vec![Order::InitiateReserveWithdraw { + } + } + + fn transfer_to_reserve(asset: MultiAsset, reserve: MultiLocation, recipient: MultiLocation) -> Xcm { + WithdrawAsset { + assets: vec![asset], + effects: vec![InitiateReserveWithdraw { assets: vec![MultiAsset::All], - reserve: MultiLocation::X1(Junction::Parent), - effects: vec![Order::DepositReserveAsset { - assets: vec![MultiAsset::All], - // Reserve asset deposit dest is children parachain(of parent). - dest: MultiLocation::X1(Junction::Parachain { id: para_id.into() }), - effects: vec![Order::DepositAsset { - assets: vec![MultiAsset::All], - dest, - }], - }], + reserve, + effects: Self::deposit_asset(recipient), }], } } - /// Transfer parachain tokens "owned" by self parachain to another - /// parachain. - /// - /// NOTE - `para_id` must not be self parachain. - fn transfer_owned_tokens_to_parachain( - x_currency_id: XCurrencyId, - para_id: ParaId, + fn transfer_to_non_reserve( + asset: MultiAsset, + reserve: MultiLocation, dest: MultiLocation, - amount: T::Balance, + recipient: MultiLocation, ) -> Xcm { - Xcm::WithdrawAsset { - assets: vec![MultiAsset::ConcreteFungible { - id: x_currency_id.into(), - amount: amount.into(), - }], - effects: vec![Order::DepositReserveAsset { + let mut reanchored_dest = dest.clone(); + if reserve == Parent.into() { + if let MultiLocation::X2(Parent, Parachain { id }) = dest { + reanchored_dest = Parachain { id }.into(); + } + } + + WithdrawAsset { + assets: vec![asset], + effects: vec![InitiateReserveWithdraw { assets: vec![MultiAsset::All], - dest: MultiLocation::X2(Junction::Parent, Junction::Parachain { id: para_id.into() }), - effects: vec![Order::DepositAsset { + reserve, + effects: vec![DepositReserveAsset { assets: vec![MultiAsset::All], - dest, + dest: reanchored_dest, + effects: Self::deposit_asset(recipient), }], }], } } - /// Transfer parachain tokens not "owned" by self chain to another - /// parachain. - fn transfer_non_owned_tokens_to_parachain( - reserve_chain: ParaId, - x_currency_id: XCurrencyId, - para_id: ParaId, - dest: MultiLocation, - amount: T::Balance, - ) -> Xcm { - let deposit_to_dest = Order::DepositAsset { + fn deposit_asset(recipient: MultiLocation) -> Vec { + vec![DepositAsset { assets: vec![MultiAsset::All], - dest, - }; - // If transfer to reserve chain, deposit to `dest` on reserve chain, - // else deposit reserve asset. - let reserve_chain_order = if para_id == reserve_chain { - deposit_to_dest - } else { - Order::DepositReserveAsset { - assets: vec![MultiAsset::All], - dest: MultiLocation::X2(Junction::Parent, Junction::Parachain { id: para_id.into() }), - effects: vec![deposit_to_dest], + dest: recipient, + }] + } + + fn is_zero_amount(asset: &MultiAsset) -> bool { + if let MultiAsset::ConcreteFungible { id: _, amount } = asset { + if *amount == Zero::zero() { + return true; } - }; + } - Xcm::WithdrawAsset { - assets: vec![MultiAsset::ConcreteFungible { - id: x_currency_id.into(), - amount: amount.into(), - }], - effects: vec![Order::InitiateReserveWithdraw { - assets: vec![MultiAsset::All], - reserve: MultiLocation::X2( - Junction::Parent, - Junction::Parachain { - id: reserve_chain.into(), - }, - ), - effects: vec![reserve_chain_order], - }], + if let MultiAsset::AbstractFungible { id: _, amount } = asset { + if *amount == Zero::zero() { + return true; + } + } + + false + } + + /// Ensure has the `dest` has chain part and recipient part. + fn ensure_valid_dest( + dest: MultiLocation, + ) -> sp_std::result::Result<(MultiLocation, MultiLocation), DispatchError> { + if let (Some(dest), Some(recipient)) = (dest.chain_part(), dest.non_chain_part()) { + Ok((dest, recipient)) + } else { + Err(Error::::InvalidDest.into()) } } } diff --git a/xtokens/src/mock.rs b/xtokens/src/mock.rs new file mode 100644 index 000000000..c23f28436 --- /dev/null +++ b/xtokens/src/mock.rs @@ -0,0 +1,452 @@ +#![cfg(test)] + +use super::*; +use crate as orml_xtokens; + +use frame_support::parameter_types; +use orml_traits::parameter_type_with_key; +use orml_xcm_support::{ + CurrencyIdConverter, IsConcreteWithGeneralKey, MultiCurrencyAdapter, MultiNativeAsset, XcmHandler as XcmHandlerT, +}; +use polkadot_parachain::primitives::Sibling; +use serde::{Deserialize, Serialize}; +use sp_io::TestExternalities; +use sp_runtime::{traits::Identity, AccountId32}; +use sp_std::convert::TryFrom; +use xcm::v0::{Junction, NetworkId}; +use xcm_builder::{ + AccountId32Aliases, LocationInverter, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SovereignSignedViaLocation, +}; +use xcm_executor::Config as XcmConfigT; +use xcm_simulator::{decl_test_network, decl_test_parachain, prelude::*}; + +pub const ALICE: AccountId32 = AccountId32::new([0u8; 32]); +pub const BOB: AccountId32 = AccountId32::new([1u8; 32]); + +#[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +pub enum CurrencyId { + /// Relay chain token. + R, + /// Parachain A token. + A, + /// Parachain B token. + B, +} + +impl TryFrom> for CurrencyId { + type Error = (); + fn try_from(v: Vec) -> Result { + match v.as_slice() { + b"R" => Ok(CurrencyId::R), + b"A" => Ok(CurrencyId::A), + b"B" => Ok(CurrencyId::B), + _ => Err(()), + } + } +} + +impl From for MultiLocation { + fn from(id: CurrencyId) -> Self { + match id { + CurrencyId::R => Junction::Parent.into(), + CurrencyId::A => ( + Junction::Parent, + Junction::Parachain { id: 1 }, + Junction::GeneralKey("A".into()), + ) + .into(), + CurrencyId::B => ( + Junction::Parent, + Junction::Parachain { id: 2 }, + Junction::GeneralKey("B".into()), + ) + .into(), + } + } +} + +pub type Balance = u128; +pub type Amount = i128; + +decl_test_parachain! { + pub struct ParaA { + new_ext = parachain_ext::(1), + para_id = 1, + } + pub mod para_a { + test_network = super::TestNetwork, + xcm_config = { + use super::*; + + parameter_types! { + pub ParaANetwork: NetworkId = NetworkId::Any; + pub RelayChainOrigin: Origin = cumulus_pallet_xcm_handler::Origin::Relay.into(); + pub Ancestry: MultiLocation = MultiLocation::X1(Junction::Parachain { + id: ParachainInfo::get().into(), + }); + pub const RelayChainCurrencyId: CurrencyId = CurrencyId::R; + } + + pub type LocationConverter = ( + ParentIsDefault, + SiblingParachainConvertsVia, + AccountId32Aliases, + ); + + pub type LocalAssetTransactor = MultiCurrencyAdapter< + Tokens, + (), + IsConcreteWithGeneralKey, + LocationConverter, + AccountId, + CurrencyIdConverter, + CurrencyId, + >; + + pub type LocalOriginConverter = ( + SovereignSignedViaLocation, + RelayChainAsNative, + SiblingParachainAsNative, + SignedAccountId32AsNative, + ); + + pub struct XcmConfig; + impl XcmConfigT for XcmConfig { + type Call = Call; + type XcmSender = XcmHandler; + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = LocalOriginConverter; + type IsReserve = MultiNativeAsset; + type IsTeleporter = (); + type LocationInverter = LocationInverter; + } + }, + extra_config = { + parameter_type_with_key! { + pub ExistentialDeposits: |_currency_id: super::CurrencyId| -> Balance { + Default::default() + }; + } + + impl orml_tokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = super::CurrencyId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type OnDust = (); + } + + pub struct HandleXcm; + impl XcmHandlerT for HandleXcm { + fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult { + XcmHandler::execute_xcm(origin, xcm) + } + } + + pub struct AccountId32Convert; + impl Convert for AccountId32Convert { + fn convert(account_id: AccountId) -> [u8; 32] { + account_id.into() + } + } + + parameter_types! { + pub SelfLocation: MultiLocation = (Junction::Parent, Junction::Parachain { id: ParachainInfo::get().into() }).into(); + } + + impl orml_xtokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type CurrencyId = CurrencyId; + type AccountId32Convert = AccountId32Convert; + type SelfLocation = SelfLocation; + type XcmHandler = HandleXcm; + } + }, + extra_modules = { + Tokens: orml_tokens::{Pallet, Storage, Event, Config}, + XTokens: orml_xtokens::{Pallet, Storage, Call, Event}, + }, + } +} + +decl_test_parachain! { + pub struct ParaB { + new_ext = parachain_ext::(2), + para_id = 2, + } + pub mod para_c { + test_network = super::TestNetwork, + xcm_config = { + use super::*; + + parameter_types! { + pub ParaANetwork: NetworkId = NetworkId::Any; + pub RelayChainOrigin: Origin = cumulus_pallet_xcm_handler::Origin::Relay.into(); + pub Ancestry: MultiLocation = MultiLocation::X1(Junction::Parachain { + id: ParachainInfo::get().into(), + }); + pub const RelayChainCurrencyId: CurrencyId = CurrencyId::R; + } + + pub type LocationConverter = ( + ParentIsDefault, + SiblingParachainConvertsVia, + AccountId32Aliases, + ); + + pub type LocalAssetTransactor = MultiCurrencyAdapter< + Tokens, + (), + IsConcreteWithGeneralKey, + LocationConverter, + AccountId, + CurrencyIdConverter, + CurrencyId, + >; + + pub type LocalOriginConverter = ( + SovereignSignedViaLocation, + RelayChainAsNative, + SiblingParachainAsNative, + SignedAccountId32AsNative, + ); + + pub struct XcmConfig; + impl XcmConfigT for XcmConfig { + type Call = Call; + type XcmSender = XcmHandler; + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = LocalOriginConverter; + type IsReserve = MultiNativeAsset; + type IsTeleporter = (); + type LocationInverter = LocationInverter; + } + }, + extra_config = { + parameter_type_with_key! { + pub ExistentialDeposits: |_currency_id: super::CurrencyId| -> Balance { + Default::default() + }; + } + + impl orml_tokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = super::CurrencyId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type OnDust = (); + } + + pub struct HandleXcm; + impl XcmHandlerT for HandleXcm { + fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult { + XcmHandler::execute_xcm(origin, xcm) + } + } + + pub struct AccountId32Convert; + impl Convert for AccountId32Convert { + fn convert(account_id: AccountId) -> [u8; 32] { + account_id.into() + } + } + + parameter_types! { + pub SelfLocation: MultiLocation = (Junction::Parent, Junction::Parachain { id: ParachainInfo::get().into() }).into(); + } + + impl orml_xtokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type CurrencyId = CurrencyId; + type AccountId32Convert = AccountId32Convert; + type SelfLocation = SelfLocation; + type XcmHandler = HandleXcm; + } + }, + extra_modules = { + Tokens: orml_tokens::{Pallet, Storage, Event, Config}, + XTokens: orml_xtokens::{Pallet, Storage, Call, Event}, + }, + } +} + +decl_test_parachain! { + pub struct ParaC { + new_ext = parachain_ext::(3), + para_id = 3, + } + pub mod para_b { + test_network = super::TestNetwork, + xcm_config = { + use super::*; + + parameter_types! { + pub ParaANetwork: NetworkId = NetworkId::Any; + pub RelayChainOrigin: Origin = cumulus_pallet_xcm_handler::Origin::Relay.into(); + pub Ancestry: MultiLocation = MultiLocation::X1(Junction::Parachain { + id: ParachainInfo::get().into(), + }); + pub const RelayChainCurrencyId: CurrencyId = CurrencyId::R; + } + + pub type LocationConverter = ( + ParentIsDefault, + SiblingParachainConvertsVia, + AccountId32Aliases, + ); + + pub type LocalAssetTransactor = MultiCurrencyAdapter< + Tokens, + (), + IsConcreteWithGeneralKey, + LocationConverter, + AccountId, + CurrencyIdConverter, + CurrencyId, + >; + + pub type LocalOriginConverter = ( + SovereignSignedViaLocation, + RelayChainAsNative, + SiblingParachainAsNative, + SignedAccountId32AsNative, + ); + + pub struct XcmConfig; + impl XcmConfigT for XcmConfig { + type Call = Call; + type XcmSender = XcmHandler; + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = LocalOriginConverter; + type IsReserve = MultiNativeAsset; + type IsTeleporter = (); + type LocationInverter = LocationInverter; + } + }, + extra_config = { + parameter_type_with_key! { + pub ExistentialDeposits: |_currency_id: super::CurrencyId| -> Balance { + Default::default() + }; + } + + impl orml_tokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = super::CurrencyId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type OnDust = (); + } + + pub struct HandleXcm; + impl XcmHandlerT for HandleXcm { + fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult { + XcmHandler::execute_xcm(origin, xcm) + } + } + + pub struct AccountId32Convert; + impl Convert for AccountId32Convert { + fn convert(account_id: AccountId) -> [u8; 32] { + account_id.into() + } + } + + parameter_types! { + pub SelfLocation: MultiLocation = (Junction::Parent, Junction::Parachain { id: ParachainInfo::get().into() }).into(); + } + + impl orml_xtokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type CurrencyId = CurrencyId; + type AccountId32Convert = AccountId32Convert; + type SelfLocation = SelfLocation; + type XcmHandler = HandleXcm; + } + }, + extra_modules = { + Tokens: orml_tokens::{Pallet, Storage, Event, Config}, + XTokens: orml_xtokens::{Pallet, Storage, Call, Event}, + }, + } +} + +decl_test_network! { + pub struct TestNetwork { + relay_chain = default, + parachains = vec![ + (1, ParaA), + (2, ParaB), + (3, ParaC), + ], + } +} + +pub type ParaAXtokens = orml_xtokens::Pallet; +pub type ParaATokens = orml_tokens::Pallet; +pub type ParaBTokens = orml_tokens::Pallet; +pub type ParaCTokens = orml_tokens::Pallet; + +pub type RelayBalances = pallet_balances::Pallet; + +pub struct ParaExtBuilder; + +impl Default for ParaExtBuilder { + fn default() -> Self { + ParaExtBuilder + } +} + +impl ParaExtBuilder { + pub fn build< + Runtime: frame_system::Config + orml_tokens::Config, + >( + self, + para_id: u32, + ) -> TestExternalities + where + ::BlockNumber: From, + { + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + parachain_info::GenesisConfig { + parachain_id: para_id.into(), + } + .assimilate_storage(&mut t) + .unwrap(); + + orml_tokens::GenesisConfig:: { + endowed_accounts: vec![(ALICE, CurrencyId::R, 100)], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = TestExternalities::new(t); + ext.execute_with(|| frame_system::Pallet::::set_block_number(1.into())); + ext + } +} + +pub fn parachain_ext< + Runtime: frame_system::Config + orml_tokens::Config, +>( + para_id: u32, +) -> TestExternalities +where + ::BlockNumber: From, +{ + ParaExtBuilder::default().build::(para_id) +} diff --git a/xtokens/src/tests.rs b/xtokens/src/tests.rs new file mode 100644 index 000000000..a90ca0b32 --- /dev/null +++ b/xtokens/src/tests.rs @@ -0,0 +1,290 @@ +#![cfg(test)] + +use super::*; +use cumulus_primitives_core::ParaId; +use frame_support::{assert_noop, assert_ok, traits::Currency}; +use mock::*; +use orml_traits::MultiCurrency; +use polkadot_parachain::primitives::{AccountIdConversion, Sibling}; +use sp_runtime::AccountId32; +use xcm::v0::{Junction, NetworkId}; +use xcm_simulator::TestExt; + +fn para_a_account() -> AccountId32 { + ParaId::from(1).into_account() +} + +fn para_b_account() -> AccountId32 { + ParaId::from(2).into_account() +} + +fn sibling_a_account() -> AccountId32 { + use sp_runtime::traits::AccountIdConversion; + Sibling::from(1).into_account() +} + +fn sibling_b_account() -> AccountId32 { + use sp_runtime::traits::AccountIdConversion; + Sibling::from(2).into_account() +} + +fn sibling_c_account() -> AccountId32 { + use sp_runtime::traits::AccountIdConversion; + Sibling::from(3).into_account() +} + +#[test] +fn send_relay_chain_asset_to_relay_chain() { + TestNetwork::reset(); + + MockRelay::execute_with(|| { + let _ = RelayBalances::deposit_creating(¶_a_account(), 100); + }); + + ParaA::execute_with(|| { + assert_ok!(ParaAXtokens::transfer( + Some(ALICE).into(), + CurrencyId::R, + 30, + ( + Parent, + Junction::AccountId32 { + network: NetworkId::Polkadot, + id: BOB.into(), + }, + ) + .into(), + )); + assert_eq!(ParaATokens::free_balance(CurrencyId::R, &ALICE), 70); + }); + + MockRelay::execute_with(|| { + assert_eq!(RelayBalances::free_balance(¶_a_account()), 70); + assert_eq!(RelayBalances::free_balance(&BOB), 30); + }); +} + +#[test] +fn send_relay_chain_asset_to_sibling() { + TestNetwork::reset(); + + MockRelay::execute_with(|| { + let _ = RelayBalances::deposit_creating(¶_a_account(), 100); + }); + + ParaA::execute_with(|| { + assert_ok!(ParaAXtokens::transfer( + Some(ALICE).into(), + CurrencyId::R, + 30, + ( + Parent, + Parachain { id: 2 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into(), + }, + ) + .into(), + )); + assert_eq!(ParaATokens::free_balance(CurrencyId::R, &ALICE), 70); + }); + + MockRelay::execute_with(|| { + assert_eq!(RelayBalances::free_balance(¶_a_account()), 70); + assert_eq!(RelayBalances::free_balance(¶_b_account()), 30); + }); + + ParaB::execute_with(|| { + assert_eq!(ParaBTokens::free_balance(CurrencyId::R, &BOB), 30); + }); +} + +#[test] +fn send_sibling_asset_to_reserve_sibling() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_ok!(ParaATokens::deposit(CurrencyId::B, &ALICE, 100)); + }); + + ParaB::execute_with(|| { + assert_ok!(ParaBTokens::deposit(CurrencyId::B, &sibling_a_account(), 100)); + }); + + ParaA::execute_with(|| { + assert_ok!(ParaAXtokens::transfer( + Some(ALICE).into(), + CurrencyId::B, + 30, + ( + Parent, + Parachain { id: 2 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into(), + }, + ) + .into(), + )); + + assert_eq!(ParaATokens::free_balance(CurrencyId::B, &ALICE), 70); + }); + + ParaB::execute_with(|| { + assert_eq!(ParaBTokens::free_balance(CurrencyId::B, &sibling_a_account()), 70); + assert_eq!(ParaBTokens::free_balance(CurrencyId::B, &BOB), 30); + }); +} + +#[test] +fn send_sibling_asset_to_non_reserve_sibling() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_ok!(ParaATokens::deposit(CurrencyId::B, &ALICE, 100)); + }); + + ParaB::execute_with(|| { + assert_ok!(ParaBTokens::deposit(CurrencyId::B, &sibling_a_account(), 100)); + }); + + ParaA::execute_with(|| { + assert_ok!(ParaAXtokens::transfer( + Some(ALICE).into(), + CurrencyId::B, + 30, + ( + Parent, + Parachain { id: 3 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into(), + }, + ) + .into(), + )); + assert_eq!(ParaATokens::free_balance(CurrencyId::B, &ALICE), 70); + }); + + // check reserve accounts + ParaB::execute_with(|| { + assert_eq!(ParaBTokens::free_balance(CurrencyId::B, &sibling_a_account()), 70); + assert_eq!(ParaBTokens::free_balance(CurrencyId::B, &sibling_c_account()), 30); + }); + + ParaC::execute_with(|| { + assert_eq!(ParaCTokens::free_balance(CurrencyId::B, &BOB), 30); + }); +} + +#[test] +fn send_self_parachain_asset_to_sibling() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_ok!(ParaATokens::deposit(CurrencyId::A, &ALICE, 100)); + + assert_ok!(ParaAXtokens::transfer( + Some(ALICE).into(), + CurrencyId::A, + 30, + ( + Parent, + Parachain { id: 2 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into(), + }, + ) + .into(), + )); + + assert_eq!(ParaATokens::free_balance(CurrencyId::A, &ALICE), 70); + assert_eq!(ParaATokens::free_balance(CurrencyId::A, &sibling_b_account()), 30); + }); + + ParaB::execute_with(|| { + para_b::System::events().iter().for_each(|r| { + println!(">>> {:?}", r.event); + }); + assert_eq!(ParaBTokens::free_balance(CurrencyId::A, &BOB), 30); + }); +} + +#[test] +fn transfer_no_reserve_assets_fails() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_noop!( + ParaAXtokens::transfer_multiasset( + Some(ALICE).into(), + MultiAsset::ConcreteFungible { + id: GeneralKey("B".into()).into(), + amount: 1 + }, + ( + Parent, + Parachain { id: 2 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into() + } + ) + .into() + ), + Error::::AssetHasNoReserve + ); + }); +} + +#[test] +fn transfer_to_self_chain_fails() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_noop!( + ParaAXtokens::transfer_multiasset( + Some(ALICE).into(), + MultiAsset::ConcreteFungible { + id: (Parent, Parachain { id: 1 }, GeneralKey("A".into())).into(), + amount: 1 + }, + ( + Parent, + Parachain { id: 1 }, + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into() + } + ) + .into() + ), + Error::::NotCrossChainTransfer + ); + }); +} + +#[test] +fn transfer_to_invalid_dest_fails() { + TestNetwork::reset(); + + ParaA::execute_with(|| { + assert_noop!( + ParaAXtokens::transfer_multiasset( + Some(ALICE).into(), + MultiAsset::ConcreteFungible { + id: (Parent, Parachain { id: 1 }, GeneralKey("A".into())).into(), + amount: 1 + }, + (Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into() + }) + .into() + ), + Error::::InvalidDest + ); + }); +} From e4091cd89a7b5bd79743b52aef9d8adeeac3a259 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Tue, 6 Apr 2021 15:04:02 +1200 Subject: [PATCH 04/14] Update currency adapter to work with new xtokens impl (#436) * Xcm support implementations rework. * Update xtokens mock. --- xcm-support/src/currency_adapter.rs | 37 ++---- xcm-support/src/lib.rs | 98 +++------------ xcm-support/src/tests.rs | 188 +++++++++++----------------- xtokens/src/mock.rs | 55 ++++---- 4 files changed, 132 insertions(+), 246 deletions(-) diff --git a/xcm-support/src/currency_adapter.rs b/xcm-support/src/currency_adapter.rs index 6b8cf0b8f..5050eadd1 100644 --- a/xcm-support/src/currency_adapter.rs +++ b/xcm-support/src/currency_adapter.rs @@ -2,6 +2,7 @@ use codec::FullCodec; use sp_runtime::traits::{MaybeSerializeDeserialize, SaturatedConversion}; use sp_std::{ cmp::{Eq, PartialEq}, + convert::{TryFrom, TryInto}, fmt::Debug, marker::PhantomData, prelude::*, @@ -11,7 +12,7 @@ use sp_std::{ use xcm::v0::{Error as XcmError, MultiAsset, MultiLocation, Result}; use xcm_executor::traits::{LocationConversion, MatchesFungible, TransactAsset}; -use crate::{CurrencyIdConversion, UnknownAsset as UnknownAssetT}; +use crate::UnknownAsset as UnknownAssetT; /// Asset transaction errors. enum Error { @@ -37,22 +38,13 @@ impl From for XcmError { /// /// If the asset is known, deposit/withdraw will be handled by `MultiCurrency`, /// else by `UnknownAsset` if unknown. -pub struct MultiCurrencyAdapter< - MultiCurrency, - UnknownAsset, - Matcher, - AccountIdConverter, - AccountId, - CurrencyIdConverter, - CurrencyId, ->( +pub struct MultiCurrencyAdapter( PhantomData<( MultiCurrency, UnknownAsset, Matcher, AccountIdConverter, AccountId, - CurrencyIdConverter, CurrencyId, )>, ); @@ -63,27 +55,18 @@ impl< Matcher: MatchesFungible, AccountIdConverter: LocationConversion, AccountId: sp_std::fmt::Debug, - CurrencyIdConverter: CurrencyIdConversion, - CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug, + CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug + TryFrom, > TransactAsset - for MultiCurrencyAdapter< - MultiCurrency, - UnknownAsset, - Matcher, - AccountIdConverter, - AccountId, - CurrencyIdConverter, - CurrencyId, - > + for MultiCurrencyAdapter { fn deposit_asset(asset: &MultiAsset, location: &MultiLocation) -> Result { match ( AccountIdConverter::from_location(location), - CurrencyIdConverter::from_asset(asset), + asset.clone().try_into(), Matcher::matches_fungible(&asset), ) { // known asset - (Some(who), Some(currency_id), Some(amount)) => { + (Some(who), Ok(currency_id), Some(amount)) => { MultiCurrency::deposit(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into())) } // unknown asset @@ -95,8 +78,10 @@ impl< UnknownAsset::withdraw(asset, location).or_else(|_| { let who = AccountIdConverter::from_location(location) .ok_or_else(|| XcmError::from(Error::AccountIdConversionFailed))?; - let currency_id = CurrencyIdConverter::from_asset(asset) - .ok_or_else(|| XcmError::from(Error::CurrencyIdConversionFailed))?; + let currency_id = asset + .clone() + .try_into() + .map_err(|_| XcmError::from(Error::CurrencyIdConversionFailed))?; let amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset) .ok_or_else(|| XcmError::from(Error::FailedToMatchFungible))? .saturated_into(); diff --git a/xcm-support/src/lib.rs b/xcm-support/src/lib.rs index 6963f0d5b..d8223f0d9 100644 --- a/xcm-support/src/lib.rs +++ b/xcm-support/src/lib.rs @@ -9,20 +9,12 @@ #![cfg_attr(not(feature = "std"), no_std)] #![allow(clippy::unused_unit)] -use frame_support::{ - dispatch::{DispatchError, DispatchResult}, - traits::Get, -}; -use sp_runtime::traits::{CheckedConversion, Convert}; -use sp_std::{ - collections::btree_set::BTreeSet, - convert::{TryFrom, TryInto}, - marker::PhantomData, - prelude::*, -}; +use frame_support::dispatch::{DispatchError, DispatchResult}; +use sp_runtime::traits::CheckedConversion; +use sp_std::{convert::TryFrom, marker::PhantomData, prelude::*}; -use xcm::v0::{Junction, MultiAsset, MultiLocation, Xcm}; -use xcm_executor::traits::{FilterAssetLocation, MatchesFungible, NativeAsset}; +use xcm::v0::{MultiAsset, MultiLocation, Xcm}; +use xcm_executor::traits::{FilterAssetLocation, MatchesFungible}; use orml_traits::location::Reserve; @@ -37,61 +29,24 @@ pub trait XcmHandler { fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult; } -/// Convert `MultiAsset` to `CurrencyId`. -pub trait CurrencyIdConversion { - /// Get `CurrencyId` from `MultiAsset`. Returns `None` if conversion failed. - fn from_asset(asset: &MultiAsset) -> Option; -} - -/// A `MatchesFungible` implementation. It matches relay chain tokens or -/// parachain tokens that could be decoded from a general key. -pub struct IsConcreteWithGeneralKey( - PhantomData<(CurrencyId, FromRelayChainBalance)>, -); -impl MatchesFungible - for IsConcreteWithGeneralKey +/// A `MatchesFungible` implementation. It matches concrete fungible assets +/// whose `id` could be converted into `CurrencyId`. +pub struct IsNativeConcrete(PhantomData); +impl MatchesFungible for IsNativeConcrete where - CurrencyId: TryFrom>, - B: TryFrom, - FromRelayChainBalance: Convert, + CurrencyId: TryFrom, + Amount: TryFrom, { - fn matches_fungible(a: &MultiAsset) -> Option { + fn matches_fungible(a: &MultiAsset) -> Option { if let MultiAsset::ConcreteFungible { id, amount } = a { - if id == &MultiLocation::X1(Junction::Parent) { - // Convert relay chain decimals to local chain - let local_amount = FromRelayChainBalance::convert(*amount); - return CheckedConversion::checked_from(local_amount); - } - if let Some(Junction::GeneralKey(key)) = id.last() { - if TryInto::::try_into(key.clone()).is_ok() { - return CheckedConversion::checked_from(*amount); - } + if CurrencyId::try_from(id.clone()).is_ok() { + return CheckedConversion::checked_from(*amount); } } None } } -/// A `FilterAssetLocation` implementation. Filters native assets and ORML -/// tokens via provided general key to `MultiLocation` pairs. -pub struct NativePalletAssetOr(PhantomData); -impl, MultiLocation)>>> FilterAssetLocation for NativePalletAssetOr { - fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { - if NativeAsset::filter_asset_location(asset, origin) { - return true; - } - - // native orml-tokens with a general key - if let MultiAsset::ConcreteFungible { ref id, .. } = asset { - if let Some(Junction::GeneralKey(key)) = id.last() { - return Pairs::get().contains(&(key.clone(), origin.clone())); - } - } - - false - } -} - /// A `FilterAssetLocation` implementation. Filters multi native assets whose /// reserve is same with `origin`. pub struct MultiNativeAsset; @@ -106,31 +61,6 @@ impl FilterAssetLocation for MultiNativeAsset { } } -/// `CurrencyIdConversion` implementation. Converts relay chain tokens, or -/// parachain tokens that could be decoded from a general key. -pub struct CurrencyIdConverter( - PhantomData, - PhantomData, -); -impl CurrencyIdConversion - for CurrencyIdConverter -where - CurrencyId: TryFrom>, - RelayChainCurrencyId: Get, -{ - fn from_asset(asset: &MultiAsset) -> Option { - if let MultiAsset::ConcreteFungible { id: location, .. } = asset { - if location == &MultiLocation::X1(Junction::Parent) { - return Some(RelayChainCurrencyId::get()); - } - if let Some(Junction::GeneralKey(key)) = location.last() { - return CurrencyId::try_from(key.clone()).ok(); - } - } - None - } -} - /// Handlers unknown asset deposit and withdraw. pub trait UnknownAsset { /// Deposit unknown asset. diff --git a/xcm-support/src/tests.rs b/xcm-support/src/tests.rs index b0348befd..e8f680663 100644 --- a/xcm-support/src/tests.rs +++ b/xcm-support/src/tests.rs @@ -4,8 +4,7 @@ use super::*; -use frame_support::parameter_types; -use sp_runtime::traits::{Convert, Identity}; +use xcm::v0::{Junction::*, MultiAsset::*, MultiLocation::*}; #[derive(Debug, PartialEq, Eq)] pub enum TestCurrencyId { @@ -13,135 +12,98 @@ pub enum TestCurrencyId { TokenB, RelayChainToken, } -impl TryFrom> for TestCurrencyId { + +impl TryFrom for TestCurrencyId { type Error = (); - fn try_from(v: Vec) -> Result { - match v.as_slice() { - [1] => Ok(TestCurrencyId::TokenA), - [2] => Ok(TestCurrencyId::TokenB), - [3] => Ok(TestCurrencyId::RelayChainToken), + fn try_from(l: MultiLocation) -> Result { + use TestCurrencyId::*; + let token_a: Vec = "TokenA".into(); + let token_b: Vec = "TokenB".into(); + match l { + X1(Parent) => Ok(RelayChainToken), + X3(Parent, Parachain { id: 1 }, GeneralKey(k)) if k == token_a => Ok(TokenA), + X3(Parent, Parachain { id: 2 }, GeneralKey(k)) if k == token_b => Ok(TokenB), _ => Err(()), } } } -type IdentityMatch = IsConcreteWithGeneralKey; - -pub struct NativeToRelay; -impl Convert for NativeToRelay { - fn convert(val: u128) -> u128 { - // native is 13 - // relay is 12 - val / 10 - } -} - -type TenToOneMatch = IsConcreteWithGeneralKey; - -parameter_types! { - pub NativeOrmlTokens: BTreeSet<(Vec, MultiLocation)> = { - let mut t = BTreeSet::new(); - t.insert((vec![1], (Junction::Parent, Junction::Parachain { id: 1 }).into())); - t - }; - - pub const RelayChainCurrencyId: TestCurrencyId = TestCurrencyId::RelayChainToken; -} - -type AssetFilter = NativePalletAssetOr; - -type TestCurrencyIdConverter = CurrencyIdConverter; +type MatchesCurrencyId = IsNativeConcrete; #[test] -fn is_concrete_with_general_key_matches_relay_chain_token() { - let relay_chain_asset = MultiAsset::ConcreteFungible { - id: MultiLocation::X1(Junction::Parent), - amount: 10, - }; - assert_eq!(IdentityMatch::matches_fungible(&relay_chain_asset), Some(10)); - assert_eq!(TenToOneMatch::matches_fungible(&relay_chain_asset), Some(1)); -} - -#[test] -fn is_concrete_with_general_key_matches_parachain_token_with_general_key() { - let token_a = MultiAsset::ConcreteFungible { - id: MultiLocation::X3( - Junction::Parent, - Junction::Parachain { id: 1 }, - Junction::GeneralKey(vec![1]), - ), - amount: 10, - }; - let unknown_token = MultiAsset::ConcreteFungible { - id: MultiLocation::X3( - Junction::Parent, - Junction::Parachain { id: 1 }, - Junction::GeneralKey(vec![100]), - ), - amount: 10, - }; - assert_eq!(IdentityMatch::matches_fungible(&token_a), Some(10)); +fn is_native_concrete_matches_native_currencies() { + assert_eq!( + MatchesCurrencyId::matches_fungible(&ConcreteFungible { + id: X1(Parent), + amount: 100 + }), + Some(100), + ); assert_eq!( - >::matches_fungible(&unknown_token), - None, + MatchesCurrencyId::matches_fungible(&ConcreteFungible { + id: X3(Parent, Parachain { id: 1 }, GeneralKey("TokenA".into())), + amount: 100 + }), + Some(100), + ); + assert_eq!( + MatchesCurrencyId::matches_fungible(&ConcreteFungible { + id: X3(Parent, Parachain { id: 2 }, GeneralKey("TokenB".into())), + amount: 100 + }), + Some(100), ); } #[test] -fn native_pallet_asset_or_can_filter_native_asset() { - let token_a = MultiAsset::ConcreteFungible { - id: MultiLocation::X2(Junction::Parent, Junction::Parachain { id: 1 }), - amount: 10, - }; - assert!(AssetFilter::filter_asset_location( - &token_a, - &MultiLocation::X2(Junction::Parent, Junction::Parachain { id: 1 }), - )); +fn is_native_concrete_does_not_matches_non_native_currencies() { + assert!( + >::matches_fungible(&ConcreteFungible { + id: X3(Parent, Parachain { id: 2 }, GeneralKey("TokenC".into())), + amount: 100 + }) + .is_none() + ); + assert!( + >::matches_fungible(&ConcreteFungible { + id: X3(Parent, Parachain { id: 1 }, GeneralKey("TokenB".into())), + amount: 100 + }) + .is_none() + ); + assert!( + >::matches_fungible(&ConcreteFungible { + id: X1(GeneralKey("TokenB".into())), + amount: 100 + }) + .is_none() + ); } #[test] -fn native_pallet_asset_or_can_filter_orml_tokens() { - let token_a = MultiAsset::ConcreteFungible { - id: MultiLocation::X3( - Junction::Parent, - Junction::Parachain { id: 1 }, - Junction::GeneralKey(vec![1]), - ), - amount: 10, - }; - // origin is different from concrete fungible id, thus it's not native. - assert!(AssetFilter::filter_asset_location( - &token_a, - &MultiLocation::X2(Junction::Parent, Junction::Parachain { id: 1 }), +fn multi_native_asset() { + assert!(MultiNativeAsset::filter_asset_location( + &ConcreteFungible { + id: Parent.into(), + amount: 10, + }, + &Parent.into() + )); + assert!(MultiNativeAsset::filter_asset_location( + &ConcreteFungible { + id: X3(Parent, Parachain { id: 1 }, GeneralKey("TokenA".into())), + amount: 10, + }, + &X2(Parent, Parachain { id: 1 }), )); -} - -#[test] -fn currency_id_converts_relay_chain_token() { - let relay_chain_asset = MultiAsset::ConcreteFungible { - id: MultiLocation::X1(Junction::Parent), - amount: 10, - }; - assert_eq!( - TestCurrencyIdConverter::from_asset(&relay_chain_asset), - Some(TestCurrencyId::RelayChainToken), - ); -} - -#[test] -fn currency_id_converts_parachain_token() { - let token_a = MultiAsset::ConcreteFungible { - id: MultiLocation::X3( - Junction::Parent, - Junction::Parachain { id: 1 }, - Junction::GeneralKey(vec![1]), + MultiNativeAsset::filter_asset_location( + &ConcreteFungible { + id: X3(Parent, Parachain { id: 1 }, GeneralKey("TokenA".into())), + amount: 10, + }, + &X1(Parent), ), - amount: 10, - }; - - assert_eq!( - TestCurrencyIdConverter::from_asset(&token_a), - Some(TestCurrencyId::TokenA), + false ); } diff --git a/xtokens/src/mock.rs b/xtokens/src/mock.rs index c23f28436..823ae3629 100644 --- a/xtokens/src/mock.rs +++ b/xtokens/src/mock.rs @@ -5,15 +5,13 @@ use crate as orml_xtokens; use frame_support::parameter_types; use orml_traits::parameter_type_with_key; -use orml_xcm_support::{ - CurrencyIdConverter, IsConcreteWithGeneralKey, MultiCurrencyAdapter, MultiNativeAsset, XcmHandler as XcmHandlerT, -}; +use orml_xcm_support::{IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset, XcmHandler as XcmHandlerT}; use polkadot_parachain::primitives::Sibling; use serde::{Deserialize, Serialize}; use sp_io::TestExternalities; -use sp_runtime::{traits::Identity, AccountId32}; +use sp_runtime::AccountId32; use sp_std::convert::TryFrom; -use xcm::v0::{Junction, NetworkId}; +use xcm::v0::{Junction, MultiLocation::*, NetworkId}; use xcm_builder::{ AccountId32Aliases, LocationInverter, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SovereignSignedViaLocation, @@ -35,18 +33,6 @@ pub enum CurrencyId { B, } -impl TryFrom> for CurrencyId { - type Error = (); - fn try_from(v: Vec) -> Result { - match v.as_slice() { - b"R" => Ok(CurrencyId::R), - b"A" => Ok(CurrencyId::A), - b"B" => Ok(CurrencyId::B), - _ => Err(()), - } - } -} - impl From for MultiLocation { fn from(id: CurrencyId) -> Self { match id { @@ -67,6 +53,32 @@ impl From for MultiLocation { } } +impl TryFrom for CurrencyId { + type Error = (); + fn try_from(l: MultiLocation) -> Result { + let a: Vec = "A".into(); + let b: Vec = "B".into(); + match l { + X1(Parent) => Ok(CurrencyId::R), + X3(Junction::Parent, Junction::Parachain { id: 1 }, Junction::GeneralKey(k)) if k == a => Ok(CurrencyId::A), + X3(Junction::Parent, Junction::Parachain { id: 2 }, Junction::GeneralKey(k)) if k == b => Ok(CurrencyId::B), + + _ => Err(()), + } + } +} + +impl TryFrom for CurrencyId { + type Error = (); + fn try_from(a: MultiAsset) -> Result { + if let MultiAsset::ConcreteFungible { id, amount: _ } = a { + Self::try_from(id) + } else { + Err(()) + } + } +} + pub type Balance = u128; pub type Amount = i128; @@ -98,10 +110,9 @@ decl_test_parachain! { pub type LocalAssetTransactor = MultiCurrencyAdapter< Tokens, (), - IsConcreteWithGeneralKey, + IsNativeConcrete, LocationConverter, AccountId, - CurrencyIdConverter, CurrencyId, >; @@ -202,10 +213,9 @@ decl_test_parachain! { pub type LocalAssetTransactor = MultiCurrencyAdapter< Tokens, (), - IsConcreteWithGeneralKey, + IsNativeConcrete, LocationConverter, AccountId, - CurrencyIdConverter, CurrencyId, >; @@ -306,10 +316,9 @@ decl_test_parachain! { pub type LocalAssetTransactor = MultiCurrencyAdapter< Tokens, (), - IsConcreteWithGeneralKey, + IsNativeConcrete, LocationConverter, AccountId, - CurrencyIdConverter, CurrencyId, >; From a3724dc83edacddd0f140081aa1a852a74cf5e4e Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Tue, 6 Apr 2021 21:57:22 +1200 Subject: [PATCH 05/14] Use CurrencyId convert. (#437) * Use CurrencyId convert. * Apply review suggestions. --- xcm-support/src/currency_adapter.rs | 45 ++++++++++------ xcm-support/src/lib.rs | 10 ++-- xcm-support/src/tests.rs | 18 +++---- xtokens/src/lib.rs | 11 +++- xtokens/src/mock.rs | 83 ++++++++++++++++------------- 5 files changed, 99 insertions(+), 68 deletions(-) diff --git a/xcm-support/src/currency_adapter.rs b/xcm-support/src/currency_adapter.rs index 5050eadd1..8a9b820bf 100644 --- a/xcm-support/src/currency_adapter.rs +++ b/xcm-support/src/currency_adapter.rs @@ -1,8 +1,7 @@ use codec::FullCodec; -use sp_runtime::traits::{MaybeSerializeDeserialize, SaturatedConversion}; +use sp_runtime::traits::{Convert, MaybeSerializeDeserialize, SaturatedConversion}; use sp_std::{ cmp::{Eq, PartialEq}, - convert::{TryFrom, TryInto}, fmt::Debug, marker::PhantomData, prelude::*, @@ -38,14 +37,23 @@ impl From for XcmError { /// /// If the asset is known, deposit/withdraw will be handled by `MultiCurrency`, /// else by `UnknownAsset` if unknown. -pub struct MultiCurrencyAdapter( +pub struct MultiCurrencyAdapter< + MultiCurrency, + UnknownAsset, + Matcher, + AccountId, + AccountIdConvert, + CurrencyId, + CurrencyIdConvert, +>( PhantomData<( MultiCurrency, UnknownAsset, Matcher, - AccountIdConverter, AccountId, + AccountIdConvert, CurrencyId, + CurrencyIdConvert, )>, ); @@ -53,20 +61,29 @@ impl< MultiCurrency: orml_traits::MultiCurrency, UnknownAsset: UnknownAssetT, Matcher: MatchesFungible, - AccountIdConverter: LocationConversion, AccountId: sp_std::fmt::Debug, - CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug + TryFrom, + AccountIdConvert: LocationConversion, + CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug, + CurrencyIdConvert: Convert>, > TransactAsset - for MultiCurrencyAdapter + for MultiCurrencyAdapter< + MultiCurrency, + UnknownAsset, + Matcher, + AccountId, + AccountIdConvert, + CurrencyId, + CurrencyIdConvert, + > { fn deposit_asset(asset: &MultiAsset, location: &MultiLocation) -> Result { match ( - AccountIdConverter::from_location(location), - asset.clone().try_into(), + AccountIdConvert::from_location(location), + CurrencyIdConvert::convert(asset.clone()), Matcher::matches_fungible(&asset), ) { // known asset - (Some(who), Ok(currency_id), Some(amount)) => { + (Some(who), Some(currency_id), Some(amount)) => { MultiCurrency::deposit(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into())) } // unknown asset @@ -76,12 +93,10 @@ impl< fn withdraw_asset(asset: &MultiAsset, location: &MultiLocation) -> result::Result { UnknownAsset::withdraw(asset, location).or_else(|_| { - let who = AccountIdConverter::from_location(location) + let who = AccountIdConvert::from_location(location) .ok_or_else(|| XcmError::from(Error::AccountIdConversionFailed))?; - let currency_id = asset - .clone() - .try_into() - .map_err(|_| XcmError::from(Error::CurrencyIdConversionFailed))?; + let currency_id = CurrencyIdConvert::convert(asset.clone()) + .ok_or_else(|| XcmError::from(Error::CurrencyIdConversionFailed))?; let amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset) .ok_or_else(|| XcmError::from(Error::FailedToMatchFungible))? .saturated_into(); diff --git a/xcm-support/src/lib.rs b/xcm-support/src/lib.rs index d8223f0d9..039af0295 100644 --- a/xcm-support/src/lib.rs +++ b/xcm-support/src/lib.rs @@ -10,7 +10,7 @@ #![allow(clippy::unused_unit)] use frame_support::dispatch::{DispatchError, DispatchResult}; -use sp_runtime::traits::CheckedConversion; +use sp_runtime::traits::{CheckedConversion, Convert}; use sp_std::{convert::TryFrom, marker::PhantomData, prelude::*}; use xcm::v0::{MultiAsset, MultiLocation, Xcm}; @@ -31,15 +31,15 @@ pub trait XcmHandler { /// A `MatchesFungible` implementation. It matches concrete fungible assets /// whose `id` could be converted into `CurrencyId`. -pub struct IsNativeConcrete(PhantomData); -impl MatchesFungible for IsNativeConcrete +pub struct IsNativeConcrete(PhantomData<(CurrencyId, CurrencyIdConvert)>); +impl MatchesFungible for IsNativeConcrete where - CurrencyId: TryFrom, + CurrencyIdConvert: Convert>, Amount: TryFrom, { fn matches_fungible(a: &MultiAsset) -> Option { if let MultiAsset::ConcreteFungible { id, amount } = a { - if CurrencyId::try_from(id.clone()).is_ok() { + if CurrencyIdConvert::convert(id.clone()).is_some() { return CheckedConversion::checked_from(*amount); } } diff --git a/xcm-support/src/tests.rs b/xcm-support/src/tests.rs index e8f680663..c83b5021b 100644 --- a/xcm-support/src/tests.rs +++ b/xcm-support/src/tests.rs @@ -4,7 +4,7 @@ use super::*; -use xcm::v0::{Junction::*, MultiAsset::*, MultiLocation::*}; +use xcm::v0::{Junction::*, MultiAsset::ConcreteFungible, MultiLocation::*}; #[derive(Debug, PartialEq, Eq)] pub enum TestCurrencyId { @@ -13,22 +13,22 @@ pub enum TestCurrencyId { RelayChainToken, } -impl TryFrom for TestCurrencyId { - type Error = (); - fn try_from(l: MultiLocation) -> Result { +pub struct CurrencyIdConvert; +impl Convert> for CurrencyIdConvert { + fn convert(l: MultiLocation) -> Option { use TestCurrencyId::*; let token_a: Vec = "TokenA".into(); let token_b: Vec = "TokenB".into(); match l { - X1(Parent) => Ok(RelayChainToken), - X3(Parent, Parachain { id: 1 }, GeneralKey(k)) if k == token_a => Ok(TokenA), - X3(Parent, Parachain { id: 2 }, GeneralKey(k)) if k == token_b => Ok(TokenB), - _ => Err(()), + X1(Parent) => Some(RelayChainToken), + X3(Parent, Parachain { id: 1 }, GeneralKey(k)) if k == token_a => Some(TokenA), + X3(Parent, Parachain { id: 2 }, GeneralKey(k)) if k == token_b => Some(TokenB), + _ => None, } } } -type MatchesCurrencyId = IsNativeConcrete; +type MatchesCurrencyId = IsNativeConcrete; #[test] fn is_native_concrete_matches_native_currencies() { diff --git a/xtokens/src/lib.rs b/xtokens/src/lib.rs index 5ba280bf4..801dad819 100644 --- a/xtokens/src/lib.rs +++ b/xtokens/src/lib.rs @@ -63,7 +63,10 @@ pub mod module { + Into; /// Currency Id. - type CurrencyId: Parameter + Member + Clone + Into; + type CurrencyId: Parameter + Member + Clone; + + /// Convert `T::CurrencyIn` to `MultiLocation`. + type CurrencyIdConvert: Convert>; /// Convert `Self::Account` to `AccountId32` type AccountId32Convert: Convert; @@ -94,6 +97,8 @@ pub mod module { NotCrossChainTransfer, /// Invalid transfer destination. InvalidDest, + /// Currency is not cross-chain transferable. + NotCrossChainTransferableCurrency, } #[pallet::hooks] @@ -119,8 +124,10 @@ pub mod module { return Ok(().into()); } + let id: MultiLocation = T::CurrencyIdConvert::convert(currency_id.clone()) + .ok_or(Error::::NotCrossChainTransferableCurrency)?; let asset = MultiAsset::ConcreteFungible { - id: currency_id.clone().into(), + id, amount: amount.into(), }; Self::do_transfer_multiasset(who.clone(), asset, dest.clone())?; diff --git a/xtokens/src/mock.rs b/xtokens/src/mock.rs index 823ae3629..463aa3a03 100644 --- a/xtokens/src/mock.rs +++ b/xtokens/src/mock.rs @@ -10,7 +10,6 @@ use polkadot_parachain::primitives::Sibling; use serde::{Deserialize, Serialize}; use sp_io::TestExternalities; use sp_runtime::AccountId32; -use sp_std::convert::TryFrom; use xcm::v0::{Junction, MultiLocation::*, NetworkId}; use xcm_builder::{ AccountId32Aliases, LocationInverter, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative, @@ -33,48 +32,52 @@ pub enum CurrencyId { B, } -impl From for MultiLocation { - fn from(id: CurrencyId) -> Self { +pub struct CurrencyIdConvert; +impl Convert> for CurrencyIdConvert { + fn convert(id: CurrencyId) -> Option { match id { - CurrencyId::R => Junction::Parent.into(), - CurrencyId::A => ( - Junction::Parent, - Junction::Parachain { id: 1 }, - Junction::GeneralKey("A".into()), - ) - .into(), - CurrencyId::B => ( - Junction::Parent, - Junction::Parachain { id: 2 }, - Junction::GeneralKey("B".into()), - ) - .into(), + CurrencyId::R => Some(Junction::Parent.into()), + CurrencyId::A => Some( + ( + Junction::Parent, + Junction::Parachain { id: 1 }, + Junction::GeneralKey("A".into()), + ) + .into(), + ), + CurrencyId::B => Some( + ( + Junction::Parent, + Junction::Parachain { id: 2 }, + Junction::GeneralKey("B".into()), + ) + .into(), + ), } } } - -impl TryFrom for CurrencyId { - type Error = (); - fn try_from(l: MultiLocation) -> Result { +impl Convert> for CurrencyIdConvert { + fn convert(l: MultiLocation) -> Option { let a: Vec = "A".into(); let b: Vec = "B".into(); match l { - X1(Parent) => Ok(CurrencyId::R), - X3(Junction::Parent, Junction::Parachain { id: 1 }, Junction::GeneralKey(k)) if k == a => Ok(CurrencyId::A), - X3(Junction::Parent, Junction::Parachain { id: 2 }, Junction::GeneralKey(k)) if k == b => Ok(CurrencyId::B), - - _ => Err(()), + X1(Parent) => Some(CurrencyId::R), + X3(Junction::Parent, Junction::Parachain { id: 1 }, Junction::GeneralKey(k)) if k == a => { + Some(CurrencyId::A) + } + X3(Junction::Parent, Junction::Parachain { id: 2 }, Junction::GeneralKey(k)) if k == b => { + Some(CurrencyId::B) + } + _ => None, } } } - -impl TryFrom for CurrencyId { - type Error = (); - fn try_from(a: MultiAsset) -> Result { +impl Convert> for CurrencyIdConvert { + fn convert(a: MultiAsset) -> Option { if let MultiAsset::ConcreteFungible { id, amount: _ } = a { - Self::try_from(id) + Self::convert(id) } else { - Err(()) + None } } } @@ -110,10 +113,11 @@ decl_test_parachain! { pub type LocalAssetTransactor = MultiCurrencyAdapter< Tokens, (), - IsNativeConcrete, - LocationConverter, + IsNativeConcrete, AccountId, + LocationConverter, CurrencyId, + CurrencyIdConvert, >; pub type LocalOriginConverter = ( @@ -173,6 +177,7 @@ decl_test_parachain! { type Event = Event; type Balance = Balance; type CurrencyId = CurrencyId; + type CurrencyIdConvert = CurrencyIdConvert; type AccountId32Convert = AccountId32Convert; type SelfLocation = SelfLocation; type XcmHandler = HandleXcm; @@ -213,10 +218,11 @@ decl_test_parachain! { pub type LocalAssetTransactor = MultiCurrencyAdapter< Tokens, (), - IsNativeConcrete, - LocationConverter, + IsNativeConcrete, AccountId, + LocationConverter, CurrencyId, + CurrencyIdConvert, >; pub type LocalOriginConverter = ( @@ -276,6 +282,7 @@ decl_test_parachain! { type Event = Event; type Balance = Balance; type CurrencyId = CurrencyId; + type CurrencyIdConvert = CurrencyIdConvert; type AccountId32Convert = AccountId32Convert; type SelfLocation = SelfLocation; type XcmHandler = HandleXcm; @@ -316,10 +323,11 @@ decl_test_parachain! { pub type LocalAssetTransactor = MultiCurrencyAdapter< Tokens, (), - IsNativeConcrete, - LocationConverter, + IsNativeConcrete, AccountId, + LocationConverter, CurrencyId, + CurrencyIdConvert, >; pub type LocalOriginConverter = ( @@ -379,6 +387,7 @@ decl_test_parachain! { type Event = Event; type Balance = Balance; type CurrencyId = CurrencyId; + type CurrencyIdConvert = CurrencyIdConvert; type AccountId32Convert = AccountId32Convert; type SelfLocation = SelfLocation; type XcmHandler = HandleXcm; From d1749f000955179a9e2cd02c2d226bde13fb8e47 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Wed, 7 Apr 2021 13:07:53 +1200 Subject: [PATCH 06/14] Update xtokens docs. (#438) * Update xtokens docs. * Fix typo. * Update imbalances impl. --- tokens/src/imbalances.rs | 38 +++++++++++++++++++++++++++++--------- xtokens/README.md | 8 -------- xtokens/src/lib.rs | 4 ++-- 3 files changed, 31 insertions(+), 19 deletions(-) diff --git a/tokens/src/imbalances.rs b/tokens/src/imbalances.rs index 76faac858..084a3b9a5 100644 --- a/tokens/src/imbalances.rs +++ b/tokens/src/imbalances.rs @@ -1,7 +1,7 @@ // wrapping these imbalances in a private module is necessary to ensure absolute // privacy of the inner member. use crate::{Config, TotalIssuance}; -use frame_support::traits::{Get, Imbalance, TryDrop}; +use frame_support::traits::{Get, Imbalance, SameOrOther, TryDrop}; use sp_runtime::traits::{Saturating, Zero}; use sp_std::{marker, mem, result}; @@ -21,6 +21,12 @@ impl> PositiveImbalance> Default for PositiveImbalance { + fn default() -> Self { + Self::zero() + } +} + /// Opaque, move-only struct with private fields that serves as a token /// denoting that funds have been destroyed without any equal and opposite /// accounting. @@ -37,6 +43,12 @@ impl> NegativeImbalance> Default for NegativeImbalance { + fn default() -> Self { + Self::zero() + } +} + impl> TryDrop for PositiveImbalance { fn try_drop(self) -> result::Result<(), Self> { self.drop_zero() @@ -73,14 +85,18 @@ impl> Imbalance for Pos self.0 = self.0.saturating_add(other.0); mem::forget(other); } - fn offset(self, other: Self::Opposite) -> result::Result { + // allow to make the impl same with `pallet-balances` + #[allow(clippy::comparison_chain)] + fn offset(self, other: Self::Opposite) -> SameOrOther { let (a, b) = (self.0, other.0); mem::forget((self, other)); - if a >= b { - Ok(Self::new(a - b)) + if a > b { + SameOrOther::Same(Self::new(a - b)) + } else if b > a { + SameOrOther::Other(NegativeImbalance::new(b - a)) } else { - Err(NegativeImbalance::new(b - a)) + SameOrOther::None } } fn peek(&self) -> T::Balance { @@ -124,14 +140,18 @@ impl> Imbalance for Neg self.0 = self.0.saturating_add(other.0); mem::forget(other); } - fn offset(self, other: Self::Opposite) -> result::Result { + // allow to make the impl same with `pallet-balances` + #[allow(clippy::comparison_chain)] + fn offset(self, other: Self::Opposite) -> SameOrOther { let (a, b) = (self.0, other.0); mem::forget((self, other)); - if a >= b { - Ok(Self::new(a - b)) + if a > b { + SameOrOther::Same(Self::new(a - b)) + } else if b > a { + SameOrOther::Other(PositiveImbalance::new(b - a)) } else { - Err(PositiveImbalance::new(b - a)) + SameOrOther::None } } fn peek(&self) -> T::Balance { diff --git a/xtokens/README.md b/xtokens/README.md index 7032f29b8..4e12469b1 100644 --- a/xtokens/README.md +++ b/xtokens/README.md @@ -12,28 +12,20 @@ The xtokens module provides functions for ## Notes -#### Unit tests - -Unit tests could be added once Polkadot has XCM simulator. https://github.com/paritytech/polkadot/issues/2544 - #### Integration tests Integration tests could be done manually after integrating xtokens into runtime. To cover the full features, set up at least 4 relay chain validators and 3 collators of different parachains, and use dispatchable calls to include all these scenarios: - Transfer relay chain tokens to relay chain. - - Use dispatchable call `transfer_to_relay_chain`. - Transfer tokens issued by parachain A, from parachain A to parachain B. - - Use dispatchable call `transfer_to_parachain`. - Sending the tx from parachain A. - Set the destination as Parachain B. - Set the currency ID as parachain A token. - Transfer tokens issued by parachain B, from parachain A to parachain B. - - Use dispatchable call `transfer_to_parachain`. - Sending the tx from parachain A. - Set the destination as Parachain B. - Set the currency ID as parachain B token. - Transfer tokens issued by parachain C, from parachain A to parachain B. - - Use dispatchable call `transfer_to_parachain`. - Sending the tx from parachain A. - Set the destination as Parachain B. - Set the currency ID as parachain C token. diff --git a/xtokens/src/lib.rs b/xtokens/src/lib.rs index 801dad819..7df979629 100644 --- a/xtokens/src/lib.rs +++ b/xtokens/src/lib.rs @@ -14,8 +14,8 @@ //! //! ### Dispatchable functions //! -//! - `transfer_to_relay_chain`: Transfer relay chain tokens to relay chain. -//! - `transfer_to_parachain`: Transfer tokens to a sibling parachain. +//! - `transfer`: Transfer local assets with given `CurrencyId` and `Amount`. +//! - `transfer_multiasset`: Transfer `MultiAsset` assets. #![cfg_attr(not(feature = "std"), no_std)] #![allow(clippy::from_over_into)] From 8053ddb300eba954465d488161eee121475ed2e5 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Thu, 8 Apr 2021 14:49:55 +1200 Subject: [PATCH 07/14] Don't deposit failure event in orml-unknown-tokens. (#440) * Don't deposit failure event in orml-unknown-tokens. * Patch substrate/polkadot/cumulus. * Fix patch. --- Cargo.dev.toml | 83 ++++++++++++++++++++++++++++--------- unknown-tokens/src/lib.rs | 28 ++++--------- unknown-tokens/src/tests.rs | 54 ------------------------ 3 files changed, 72 insertions(+), 93 deletions(-) diff --git a/Cargo.dev.toml b/Cargo.dev.toml index 2b30f836e..7ffc22886 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -23,22 +23,67 @@ members = [ ] resolver = "2" -[patch.crates-io] -frame-benchmarking = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -pallet-elections-phragmen = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -pallet-scheduler = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -pallet-treasury = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-api = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-application-crypto = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-arithmetic = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-inherents = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-runtime-interface = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-trie = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } -sp-version = { git = "https://github.com/paritytech/substrate.git", branch = "rococo-v1" } +[patch.'https://github.com/paritytech/substrate'] +frame-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +frame-support = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +frame-system = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +pallet-balances = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +pallet-elections-phragmen = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +pallet-scheduler = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +pallet-treasury = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +pallet-authorship = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +pallet-vesting = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +pallet-timestamp = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +pallet-session = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +pallet-staking = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +pallet-offences = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +pallet-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-api = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-application-crypto = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-arithmetic = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-core = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-inherents = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-io = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-runtime = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-runtime-interface = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-std = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-trie = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-version = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-externalities = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-state-machine = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-wasm-interface = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-keystore = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-staking = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-storage = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-panic-handler = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-npos-elections = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-npos-elections-compact = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-debug-derive = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-allocator = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sc-executor-common = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sc-executor-wasmi = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sc-executor = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sc-client-api = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-tasks = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-authorship = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-consensus = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-timestamp = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-session = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-blockchain = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +sp-transaction-pool = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } + +[patch.'https://github.com/paritytech/cumulus'] +cumulus-primitives-core = { git = "https://github.com/paritytech//cumulus", rev = "c5be7306f425be9fcf3c6e0bc598c0f481588cd9" } +cumulus-pallet-parachain-system = { git = "https://github.com/paritytech//cumulus", rev = "c5be7306f425be9fcf3c6e0bc598c0f481588cd9" } +parachain-info = { git = "https://github.com/paritytech//cumulus", rev = "c5be7306f425be9fcf3c6e0bc598c0f481588cd9" } +cumulus-pallet-xcm-handler = { git = "https://github.com/paritytech//cumulus", rev = "c5be7306f425be9fcf3c6e0bc598c0f481588cd9" } + +[patch.'https://github.com/paritytech/polkadot'] +xcm = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } +xcm-executor = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } +xcm-builder = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } +polkadot-core-primitives = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } +polkadot-runtime-parachains = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } +polkadot-parachain = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } +polkadot-primitives = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } diff --git a/unknown-tokens/src/lib.rs b/unknown-tokens/src/lib.rs index f162c91bb..e048ba370 100644 --- a/unknown-tokens/src/lib.rs +++ b/unknown-tokens/src/lib.rs @@ -26,12 +26,8 @@ pub mod module { pub enum Event { /// Deposit success. [asset, to] Deposited(MultiAsset, MultiLocation), - /// Deposit failed. [asset, to, error] - DepositFailed(MultiAsset, MultiLocation, DispatchError), /// Withdraw success. [asset, from] Withdrawn(MultiAsset, MultiLocation), - /// Withdraw failed. [asset, from, error] - WithdrawFailed(MultiAsset, MultiLocation, DispatchError), } #[pallet::error] @@ -74,7 +70,7 @@ pub mod module { impl UnknownAsset for Pallet { fn deposit(asset: &MultiAsset, to: &MultiLocation) -> DispatchResult { - let result = match asset { + match asset { MultiAsset::ConcreteFungible { id, amount } => { ConcreteFungibleBalances::::try_mutate(to, id, |b| -> DispatchResult { *b = b.checked_add(*amount).ok_or(Error::::BalanceOverflow)?; @@ -88,19 +84,15 @@ impl UnknownAsset for Pallet { }) } _ => Err(Error::::UnhandledAsset.into()), - }; + }?; - if let Err(err) = result { - Self::deposit_event(Event::DepositFailed(asset.clone(), to.clone(), err)); - } else { - Self::deposit_event(Event::Deposited(asset.clone(), to.clone())); - } + Self::deposit_event(Event::Deposited(asset.clone(), to.clone())); - result + Ok(()) } fn withdraw(asset: &MultiAsset, from: &MultiLocation) -> DispatchResult { - let result = match asset { + match asset { MultiAsset::ConcreteFungible { id, amount } => { ConcreteFungibleBalances::::try_mutate(from, id, |b| -> DispatchResult { *b = b.checked_sub(*amount).ok_or(Error::::BalanceTooLow)?; @@ -114,14 +106,10 @@ impl UnknownAsset for Pallet { }) } _ => Err(Error::::UnhandledAsset.into()), - }; + }?; - if let Err(err) = result { - Self::deposit_event(Event::WithdrawFailed(asset.clone(), from.clone(), err)); - } else { - Self::deposit_event(Event::Withdrawn(asset.clone(), from.clone())); - } + Self::deposit_event(Event::Withdrawn(asset.clone(), from.clone())); - result + Ok(()) } } diff --git a/unknown-tokens/src/tests.rs b/unknown-tokens/src/tests.rs index b2cb39627..cc5c60686 100644 --- a/unknown-tokens/src/tests.rs +++ b/unknown-tokens/src/tests.rs @@ -48,15 +48,6 @@ fn deposit_concrete_fungible_asset_works() { UnknownTokens::deposit(&max_asset, &MOCK_RECIPIENT), Error::::BalanceOverflow ); - - let deposit_failed_event = Event::unknown_tokens(crate::Event::DepositFailed( - max_asset, - MOCK_RECIPIENT, - Error::::BalanceOverflow.into(), - )); - assert!(System::events() - .iter() - .any(|record| record.event == deposit_failed_event)); }); } @@ -83,15 +74,6 @@ fn deposit_abstract_fungible_asset() { UnknownTokens::abstract_fungible_balances(&MOCK_RECIPIENT, &mock_abstract_fungible_id()), 3 ); - - let deposit_failed_event = Event::unknown_tokens(crate::Event::DepositFailed( - max_asset, - MOCK_RECIPIENT, - Error::::BalanceOverflow.into(), - )); - assert!(System::events() - .iter() - .any(|record| record.event == deposit_failed_event)); }); } @@ -102,15 +84,6 @@ fn deposit_unhandled_asset_should_fail() { UnknownTokens::deposit(&MultiAsset::All, &MOCK_RECIPIENT), Error::::UnhandledAsset ); - - let deposit_failed_event = Event::unknown_tokens(crate::Event::DepositFailed( - MultiAsset::All, - MOCK_RECIPIENT, - Error::::UnhandledAsset.into(), - )); - assert!(System::events() - .iter() - .any(|record| record.event == deposit_failed_event)); }); } @@ -134,15 +107,6 @@ fn withdraw_concrete_fungible_asset_works() { UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT), Error::::BalanceTooLow ); - - let withdraw_failed_event = Event::unknown_tokens(crate::Event::WithdrawFailed( - asset, - MOCK_RECIPIENT, - Error::::BalanceTooLow.into(), - )); - assert!(System::events() - .iter() - .any(|record| record.event == withdraw_failed_event)); }); } @@ -166,15 +130,6 @@ fn withdraw_abstract_fungible_asset_works() { UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT), Error::::BalanceTooLow ); - - let withdraw_failed_event = Event::unknown_tokens(crate::Event::WithdrawFailed( - asset, - MOCK_RECIPIENT, - Error::::BalanceTooLow.into(), - )); - assert!(System::events() - .iter() - .any(|record| record.event == withdraw_failed_event)); }); } @@ -185,14 +140,5 @@ fn withdraw_unhandled_asset_should_fail() { UnknownTokens::withdraw(&MultiAsset::All, &MOCK_RECIPIENT), Error::::UnhandledAsset ); - - let withdraw_failed_event = Event::unknown_tokens(crate::Event::WithdrawFailed( - MultiAsset::All, - MOCK_RECIPIENT, - Error::::UnhandledAsset.into(), - )); - assert!(System::events() - .iter() - .any(|record| record.event == withdraw_failed_event)); }); } From af1b06900fea7a1f31940b2ca0147c1bb5848ff5 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sat, 10 Apr 2021 04:58:50 +0200 Subject: [PATCH 08/14] Update README.md (#441) Include Zeitgeist into "Projects using ORML" section --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 73c620144..852832c49 100644 --- a/README.md +++ b/README.md @@ -71,4 +71,5 @@ _In alphabetical order_ - [Plasm Network](https://github.com/PlasmNetwork) - [Setheum Network](https://github.com/Setheum-Labs/Setheum) - [Valiu Liquidity Network](https://github.com/valibre-org/vln-node) +- [Zeitgeist](https://github.com/zeitgeistpm/zeitgeist) From 2cd9ccfadafe6138c0400632cf26910a2d8d132d Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Mon, 12 Apr 2021 11:14:01 +1200 Subject: [PATCH 09/14] Add PoV size in benchmarking. (#442) --- Cargo.dev.toml | 118 ++++++++++++++++++++-------------------- benchmarking/src/lib.rs | 12 +++- 2 files changed, 70 insertions(+), 60 deletions(-) diff --git a/Cargo.dev.toml b/Cargo.dev.toml index 7ffc22886..1eeb2d6a6 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -24,66 +24,66 @@ members = [ resolver = "2" [patch.'https://github.com/paritytech/substrate'] -frame-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -frame-support = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -frame-system = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -pallet-balances = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -pallet-elections-phragmen = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -pallet-scheduler = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -pallet-treasury = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -pallet-authorship = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -pallet-vesting = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -pallet-timestamp = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -pallet-session = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -pallet-staking = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -pallet-offences = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -pallet-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-api = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-application-crypto = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-arithmetic = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-core = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-inherents = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-io = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-runtime = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-runtime-interface = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-std = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-trie = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-version = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-externalities = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-state-machine = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-wasm-interface = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-keystore = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-staking = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-storage = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-panic-handler = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-npos-elections = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-npos-elections-compact = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-debug-derive = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-allocator = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sc-executor-common = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sc-executor-wasmi = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sc-executor = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sc-client-api = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-tasks = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-authorship = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-consensus = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-timestamp = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-session = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-blockchain = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } -sp-transaction-pool = { git = "https://github.com/paritytech//substrate", rev = "3ec97a31b285181fb1beab426ee2a8e2cb1188ab" } +frame-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +frame-support = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +frame-system = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +pallet-balances = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +pallet-elections-phragmen = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +pallet-scheduler = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +pallet-treasury = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +pallet-authorship = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +pallet-vesting = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +pallet-timestamp = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +pallet-session = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +pallet-staking = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +pallet-offences = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +pallet-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-api = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-application-crypto = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-arithmetic = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-core = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-inherents = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-io = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-runtime = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-runtime-interface = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-std = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-trie = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-version = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-externalities = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-state-machine = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-wasm-interface = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-keystore = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-staking = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-storage = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-panic-handler = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-npos-elections = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-npos-elections-compact = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-debug-derive = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-allocator = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sc-executor-common = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sc-executor-wasmi = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sc-executor = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sc-client-api = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-tasks = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-authorship = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-consensus = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-timestamp = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-session = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-blockchain = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +sp-transaction-pool = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } [patch.'https://github.com/paritytech/cumulus'] -cumulus-primitives-core = { git = "https://github.com/paritytech//cumulus", rev = "c5be7306f425be9fcf3c6e0bc598c0f481588cd9" } -cumulus-pallet-parachain-system = { git = "https://github.com/paritytech//cumulus", rev = "c5be7306f425be9fcf3c6e0bc598c0f481588cd9" } -parachain-info = { git = "https://github.com/paritytech//cumulus", rev = "c5be7306f425be9fcf3c6e0bc598c0f481588cd9" } -cumulus-pallet-xcm-handler = { git = "https://github.com/paritytech//cumulus", rev = "c5be7306f425be9fcf3c6e0bc598c0f481588cd9" } +cumulus-primitives-core = { git = "https://github.com/paritytech//cumulus", rev = "b225faf24d3c25228fd25df93ed82c90e004d698" } +cumulus-pallet-parachain-system = { git = "https://github.com/paritytech//cumulus", rev = "b225faf24d3c25228fd25df93ed82c90e004d698" } +parachain-info = { git = "https://github.com/paritytech//cumulus", rev = "b225faf24d3c25228fd25df93ed82c90e004d698" } +cumulus-pallet-xcm-handler = { git = "https://github.com/paritytech//cumulus", rev = "b225faf24d3c25228fd25df93ed82c90e004d698" } [patch.'https://github.com/paritytech/polkadot'] -xcm = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } -xcm-executor = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } -xcm-builder = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } -polkadot-core-primitives = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } -polkadot-runtime-parachains = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } -polkadot-parachain = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } -polkadot-primitives = { git = "https://github.com/paritytech//polkadot", rev = "6b5b4a58a3f6a3fb647fec926609e04b7d5a336a" } +xcm = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } +xcm-executor = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } +xcm-builder = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } +polkadot-core-primitives = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } +polkadot-runtime-parachains = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } +polkadot-parachain = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } +polkadot-primitives = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } diff --git a/benchmarking/src/lib.rs b/benchmarking/src/lib.rs index 75218e3e0..0755894cd 100644 --- a/benchmarking/src/lib.rs +++ b/benchmarking/src/lib.rs @@ -864,12 +864,21 @@ macro_rules! impl_benchmark { "Start Benchmark: {:?}", c ); + let start_pov = $crate::benchmarking::proof_size(); let start_extrinsic = $crate::benchmarking::current_time(); closure_to_benchmark()?; let finish_extrinsic = $crate::benchmarking::current_time(); - let elapsed_extrinsic = finish_extrinsic - start_extrinsic; + let end_pov = $crate::benchmarking::proof_size(); + + // Calculate the diff caused by the benchmark. + let elapsed_extrinsic = finish_extrinsic.saturating_sub(start_extrinsic); + let diff_pov = match (start_pov, end_pov) { + (Some(start), Some(end)) => end.saturating_sub(start), + _ => Default::default(), + }; + // Commit the changes to get proper write count $crate::benchmarking::commit_db(); frame_support::log::trace!( @@ -896,6 +905,7 @@ macro_rules! impl_benchmark { repeat_reads: read_write_count.1, writes: read_write_count.2, repeat_writes: read_write_count.3, + proof_size: diff_pov, }); } From c7758ba6df78d4a332580713b87a7e85c7876853 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Mon, 12 Apr 2021 11:39:25 +1200 Subject: [PATCH 10/14] Bump cumulus ref in cargo patch. (#443) --- Cargo.dev.toml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.dev.toml b/Cargo.dev.toml index 1eeb2d6a6..b67a7c27f 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -74,10 +74,10 @@ sp-blockchain = { git = "https://github.com/paritytech//substrate", rev = "13a07 sp-transaction-pool = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } [patch.'https://github.com/paritytech/cumulus'] -cumulus-primitives-core = { git = "https://github.com/paritytech//cumulus", rev = "b225faf24d3c25228fd25df93ed82c90e004d698" } -cumulus-pallet-parachain-system = { git = "https://github.com/paritytech//cumulus", rev = "b225faf24d3c25228fd25df93ed82c90e004d698" } -parachain-info = { git = "https://github.com/paritytech//cumulus", rev = "b225faf24d3c25228fd25df93ed82c90e004d698" } -cumulus-pallet-xcm-handler = { git = "https://github.com/paritytech//cumulus", rev = "b225faf24d3c25228fd25df93ed82c90e004d698" } +cumulus-primitives-core = { git = "https://github.com/paritytech//cumulus", rev = "3db8a38cfad53c4fe742ca68d7b425b88c61813d" } +cumulus-pallet-parachain-system = { git = "https://github.com/paritytech//cumulus", rev = "3db8a38cfad53c4fe742ca68d7b425b88c61813d" } +parachain-info = { git = "https://github.com/paritytech//cumulus", rev = "3db8a38cfad53c4fe742ca68d7b425b88c61813d" } +cumulus-pallet-xcm-handler = { git = "https://github.com/paritytech//cumulus", rev = "3db8a38cfad53c4fe742ca68d7b425b88c61813d" } [patch.'https://github.com/paritytech/polkadot'] xcm = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } From 95ca80cd95dc1c189ccf047c538eb5d52eb16788 Mon Sep 17 00:00:00 2001 From: Xiliang Chen Date: Mon, 12 Apr 2021 14:28:13 +1200 Subject: [PATCH 11/14] fix missing features (#444) * fix missing features * test with benchmarks --- Makefile | 2 +- authority/Cargo.toml | 2 ++ tokens/Cargo.toml | 4 ++++ tokens/src/mock.rs | 2 +- vesting/Cargo.toml | 4 ++++ 5 files changed, 12 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 9b45dce09..0583cd27d 100644 --- a/Makefile +++ b/Makefile @@ -46,4 +46,4 @@ dev-check-tests: Cargo.toml cargo check --tests --all dev-test: Cargo.toml - cargo test --all + cargo test --all --features runtime-benchmarks diff --git a/authority/Cargo.toml b/authority/Cargo.toml index f124a7d20..ecd262d0d 100644 --- a/authority/Cargo.toml +++ b/authority/Cargo.toml @@ -38,4 +38,6 @@ std = [ "orml-traits/std", ] runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", ] diff --git a/tokens/Cargo.toml b/tokens/Cargo.toml index ddb39ec31..735420dd3 100644 --- a/tokens/Cargo.toml +++ b/tokens/Cargo.toml @@ -35,3 +35,7 @@ std = [ "frame-system/std", "orml-traits/std", ] +runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", +] diff --git a/tokens/src/mock.rs b/tokens/src/mock.rs index 607693940..8566bcf9b 100644 --- a/tokens/src/mock.rs +++ b/tokens/src/mock.rs @@ -76,7 +76,7 @@ impl Contains for TenToFourteen { fn add(new: &AccountId) { TEN_TO_FOURTEEN.with(|v| { let mut members = v.borrow_mut(); - members.push(*new); + members.push(new.clone()); members.sort(); }) } diff --git a/vesting/Cargo.toml b/vesting/Cargo.toml index 9f0cd14d8..064519e91 100644 --- a/vesting/Cargo.toml +++ b/vesting/Cargo.toml @@ -34,3 +34,7 @@ std = [ "frame-support/std", "frame-system/std", ] +runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", +] From 57af18a0a035c919e20eeed02bebba5dbd15114a Mon Sep 17 00:00:00 2001 From: wangjj9219 <183318287@qq.com> Date: Mon, 12 Apr 2021 23:47:22 +0800 Subject: [PATCH 12/14] update auction weight (#445) --- auction/src/default_weight.rs | 10 ---------- auction/src/lib.rs | 2 -- 2 files changed, 12 deletions(-) diff --git a/auction/src/default_weight.rs b/auction/src/default_weight.rs index 84a711aa7..26e552fef 100644 --- a/auction/src/default_weight.rs +++ b/auction/src/default_weight.rs @@ -12,16 +12,6 @@ impl crate::WeightInfo for () { .saturating_add(DbWeight::get().reads(12 as Weight)) .saturating_add(DbWeight::get().writes(12 as Weight)) } - fn bid_surplus_auction() -> Weight { - (257_830_000 as Weight) - .saturating_add(DbWeight::get().reads(6 as Weight)) - .saturating_add(DbWeight::get().writes(5 as Weight)) - } - fn bid_debit_auction() -> Weight { - (287_271_000 as Weight) - .saturating_add(DbWeight::get().reads(7 as Weight)) - .saturating_add(DbWeight::get().writes(8 as Weight)) - } fn on_finalize(c: u32) -> Weight { (50_992_000 as Weight) .saturating_add((171_653_000 as Weight).saturating_mul(c as Weight)) diff --git a/auction/src/lib.rs b/auction/src/lib.rs index 65879960e..53b40f31c 100644 --- a/auction/src/lib.rs +++ b/auction/src/lib.rs @@ -33,8 +33,6 @@ pub mod module { pub trait WeightInfo { fn bid_collateral_auction() -> Weight; - fn bid_surplus_auction() -> Weight; - fn bid_debit_auction() -> Weight; fn on_finalize(c: u32) -> Weight; } From 575518d6ce9408eadf8358e28e724461591a1556 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Tue, 13 Apr 2021 19:18:02 +1200 Subject: [PATCH 13/14] Bump dependencies. (#448) --- Cargo.dev.toml | 110 ++++++++++++++++++++--------------------- currencies/src/mock.rs | 6 +-- tokens/src/lib.rs | 6 +-- tokens/src/mock.rs | 10 ++-- 4 files changed, 66 insertions(+), 66 deletions(-) diff --git a/Cargo.dev.toml b/Cargo.dev.toml index b67a7c27f..b09dd6547 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -24,54 +24,54 @@ members = [ resolver = "2" [patch.'https://github.com/paritytech/substrate'] -frame-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -frame-support = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -frame-system = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -pallet-balances = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -pallet-elections-phragmen = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -pallet-scheduler = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -pallet-treasury = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -pallet-authorship = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -pallet-vesting = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -pallet-timestamp = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -pallet-session = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -pallet-staking = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -pallet-offences = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -pallet-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-api = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-application-crypto = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-arithmetic = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-core = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-inherents = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-io = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-runtime = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-runtime-interface = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-std = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-trie = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-version = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-externalities = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-state-machine = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-wasm-interface = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-keystore = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-staking = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-storage = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-panic-handler = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-npos-elections = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-npos-elections-compact = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-debug-derive = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-allocator = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sc-executor-common = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sc-executor-wasmi = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sc-executor = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sc-client-api = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-tasks = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-authorship = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-consensus = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-timestamp = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-session = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-blockchain = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } -sp-transaction-pool = { git = "https://github.com/paritytech//substrate", rev = "13a07b4b637b6e25397db7fcd62d8b93eeae76ac" } +frame-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +frame-support = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +frame-system = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-balances = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-elections-phragmen = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-scheduler = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-treasury = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-authorship = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-vesting = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-timestamp = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-session = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-staking = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-offences = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-api = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-application-crypto = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-arithmetic = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-core = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-inherents = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-io = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-runtime = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-runtime-interface = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-std = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-trie = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-version = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-externalities = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-state-machine = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-wasm-interface = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-keystore = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-staking = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-storage = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-panic-handler = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-npos-elections = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-npos-elections-compact = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-debug-derive = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-allocator = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sc-executor-common = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sc-executor-wasmi = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sc-executor = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sc-client-api = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-tasks = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-authorship = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-consensus = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-timestamp = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-session = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-blockchain = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +sp-transaction-pool = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } [patch.'https://github.com/paritytech/cumulus'] cumulus-primitives-core = { git = "https://github.com/paritytech//cumulus", rev = "3db8a38cfad53c4fe742ca68d7b425b88c61813d" } @@ -80,10 +80,10 @@ parachain-info = { git = "https://github.com/paritytech//cumulus", rev = "3db8a3 cumulus-pallet-xcm-handler = { git = "https://github.com/paritytech//cumulus", rev = "3db8a38cfad53c4fe742ca68d7b425b88c61813d" } [patch.'https://github.com/paritytech/polkadot'] -xcm = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } -xcm-executor = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } -xcm-builder = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } -polkadot-core-primitives = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } -polkadot-runtime-parachains = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } -polkadot-parachain = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } -polkadot-primitives = { git = "https://github.com/paritytech//polkadot", rev = "8eb16510f9fbdd077d0ac3edf304591b8f689eab" } +xcm = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +xcm-executor = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +xcm-builder = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +polkadot-core-primitives = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +polkadot-runtime-parachains = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +polkadot-parachain = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } +polkadot-primitives = { git = "https://github.com/paritytech//polkadot", rev = "8adff378fe35c850d5155732ae32260bcb5feb9b" } diff --git a/currencies/src/mock.rs b/currencies/src/mock.rs index 6eb8d883e..ef82359e4 100644 --- a/currencies/src/mock.rs +++ b/currencies/src/mock.rs @@ -3,13 +3,13 @@ #![cfg(test)] use super::*; -use frame_support::{construct_runtime, parameter_types}; +use frame_support::{construct_runtime, parameter_types, PalletId}; use orml_traits::parameter_type_with_key; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{AccountIdConversion, IdentityLookup}, - AccountId32, ModuleId, + AccountId32, }; use crate as currencies; @@ -69,7 +69,7 @@ parameter_type_with_key! { } parameter_types! { - pub DustAccount: AccountId = ModuleId(*b"orml/dst").into_account(); + pub DustAccount: AccountId = PalletId(*b"orml/dst").into_account(); } impl orml_tokens::Config for Runtime { diff --git a/tokens/src/lib.rs b/tokens/src/lib.rs index 64ecb0f95..6c1202fca 100644 --- a/tokens/src/lib.rs +++ b/tokens/src/lib.rs @@ -47,7 +47,7 @@ use frame_support::{ LockableCurrency as PalletLockableCurrency, ReservableCurrency as PalletReservableCurrency, SignedImbalance, WithdrawReasons, }, - transactional, + transactional, PalletId, }; use frame_system::{ensure_signed, pallet_prelude::*}; use orml_traits::{ @@ -61,7 +61,7 @@ use sp_runtime::{ AccountIdConversion, AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedSub, MaybeSerializeDeserialize, Member, Saturating, StaticLookup, Zero, }, - DispatchError, DispatchResult, ModuleId, RuntimeDebug, + DispatchError, DispatchResult, RuntimeDebug, }; use sp_std::{ convert::{Infallible, TryFrom, TryInto}, @@ -348,7 +348,7 @@ pub mod module { impl Pallet { /// Check whether account_id is a module account pub(crate) fn is_module_account_id(account_id: &T::AccountId) -> bool { - ModuleId::try_from_account(account_id).is_some() + PalletId::try_from_account(account_id).is_some() } pub(crate) fn try_mutate_account( diff --git a/tokens/src/mock.rs b/tokens/src/mock.rs index 8566bcf9b..c83901dae 100644 --- a/tokens/src/mock.rs +++ b/tokens/src/mock.rs @@ -96,12 +96,12 @@ parameter_types! { pub const ProposalBondMinimum: u64 = 1; pub const SpendPeriod: u64 = 2; pub const Burn: Permill = Permill::from_percent(50); - pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry"); + pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub const GetTokenId: CurrencyId = DOT; } impl pallet_treasury::Config for Runtime { - type ModuleId = TreasuryModuleId; + type PalletId = TreasuryPalletId; type Currency = CurrencyAdapter; type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; @@ -165,7 +165,7 @@ impl ChangeMembers for TestChangeMembers { } parameter_types! { - pub const ElectionsPhragmenModuleId: LockIdentifier = *b"phrelect"; + pub const ElectionsPhragmenPalletId: LockIdentifier = *b"phrelect"; pub const CandidacyBond: u64 = 3; pub const VotingBond: u64 = 2; pub const DesiredMembers: u32 = 2; @@ -176,7 +176,7 @@ parameter_types! { } impl pallet_elections_phragmen::Config for Runtime { - type ModuleId = ElectionsPhragmenModuleId; + type PalletId = ElectionsPhragmenPalletId; type Event = Event; type Currency = CurrencyAdapter; type CurrencyToVote = SaturatingCurrencyToVote; @@ -204,7 +204,7 @@ parameter_type_with_key! { } parameter_types! { - pub DustAccount: AccountId = ModuleId(*b"orml/dst").into_account(); + pub DustAccount: AccountId = PalletId(*b"orml/dst").into_account(); } impl Config for Runtime { From 273508d5973abcabb0f48451224dd8a2a5c29292 Mon Sep 17 00:00:00 2001 From: Brett Kolodny Date: Thu, 15 Apr 2021 11:31:45 -0400 Subject: [PATCH 14/14] Replaced unwraps with expects --- weight-gen/src/main.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/weight-gen/src/main.rs b/weight-gen/src/main.rs index 301f2514e..19d86aee5 100644 --- a/weight-gen/src/main.rs +++ b/weight-gen/src/main.rs @@ -44,7 +44,7 @@ impl handlebars::HelperDef for UnderscoreHelper { out: &mut dyn handlebars::Output, ) -> handlebars::HelperResult { use handlebars::JsonRender; - let param = h.param(0).unwrap(); + let param = h.param(0).expect("Unable to retrieve param from handlebars helper"); let underscore_param = underscore(param.value().render()); out.write(&underscore_param)?; Ok(()) @@ -82,7 +82,7 @@ impl handlebars::HelperDef for JoinHelper { out: &mut dyn handlebars::Output, ) -> handlebars::HelperResult { use handlebars::JsonRender; - let param = h.param(0).unwrap(); + let param = h.param(0).expect("Unable to retrieve param from handlebars helper"); let value = param.value(); let joined = if value.is_array() { value @@ -105,7 +105,7 @@ fn parse_stdio() -> Option> { let stdin = std::io::stdin(); let mut handle = stdin.lock(); - handle.read_to_string(&mut buffer).unwrap(); + handle.read_to_string(&mut buffer).expect("Unable to read from stdin"); let lines: Vec<&str> = buffer.split("\n").collect(); for line in lines { @@ -174,11 +174,11 @@ fn main() { handlebars .render_template_to_write(&template, &hbs_data, &mut output_file) - .unwrap(); + .expect("Unable to render template"); } else { let template_string = handlebars .render_template(&template, &hbs_data) - .unwrap(); + .expect("Unable to render template"); println!("{}", template_string); }