From 6d849468b4d8078eafc9f044c8521aefcf7e10da Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Fri, 12 Mar 2021 14:46:13 +1300 Subject: [PATCH 01/49] Use MultiLocation as xtokens transfer dest type. (#396) * Use MultiLocation as xtokens transfer dest type. * Make clippy happy. --- xtokens/src/lib.rs | 63 +++++++++++----------------------------------- 1 file changed, 14 insertions(+), 49 deletions(-) diff --git a/xtokens/src/lib.rs b/xtokens/src/lib.rs index e045c3529..94f1ea3e8 100644 --- a/xtokens/src/lib.rs +++ b/xtokens/src/lib.rs @@ -1,6 +1,7 @@ #![cfg_attr(not(feature = "std"), no_std)] #![allow(clippy::from_over_into)] #![allow(clippy::unused_unit)] +#![allow(clippy::large_enum_variant)] pub use module::*; @@ -89,19 +90,11 @@ pub mod module { /// Transferred to parachain. \[x_currency_id, src, para_id, dest, /// dest_network, amount\] - TransferredToParachain(XCurrencyId, T::AccountId, ParaId, T::AccountId, NetworkId, T::Balance), + TransferredToParachain(XCurrencyId, T::AccountId, ParaId, MultiLocation, T::Balance), /// Transfer to parachain failed. \[x_currency_id, src, para_id, dest, /// dest_network, amount, error\] - TransferToParachainFailed( - XCurrencyId, - T::AccountId, - ParaId, - T::AccountId, - NetworkId, - T::Balance, - XcmError, - ), + TransferToParachainFailed(XCurrencyId, T::AccountId, ParaId, MultiLocation, T::Balance, XcmError), } #[pallet::error] @@ -164,8 +157,7 @@ pub mod module { origin: OriginFor, x_currency_id: XCurrencyId, para_id: ParaId, - dest: T::AccountId, - dest_network: NetworkId, + dest: MultiLocation, amount: T::Balance, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; @@ -175,25 +167,16 @@ pub mod module { } let xcm = match x_currency_id.chain_id { - ChainId::RelayChain => { - Self::transfer_relay_chain_tokens_to_parachain(para_id, &dest, dest_network.clone(), amount) - } + 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, - dest_network.clone(), - amount, - ) + 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, - dest_network.clone(), + dest.clone(), amount, ) } @@ -209,7 +192,6 @@ pub mod module { who, para_id, dest, - dest_network, amount, )), Err(err) => Self::deposit_event(Event::::TransferToParachainFailed( @@ -217,7 +199,6 @@ pub mod module { who, para_id, dest, - dest_network, amount, err, )), @@ -228,12 +209,7 @@ pub mod module { } impl Pallet { - fn transfer_relay_chain_tokens_to_parachain( - para_id: ParaId, - dest: &T::AccountId, - dest_network: NetworkId, - amount: T::Balance, - ) -> Xcm { + 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), @@ -244,14 +220,11 @@ pub mod module { reserve: MultiLocation::X1(Junction::Parent), effects: vec![Order::DepositReserveAsset { assets: vec![MultiAsset::All], - // `dest` is children parachain(of parent). + // 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: MultiLocation::X1(Junction::AccountId32 { - network: dest_network, - id: T::AccountId32Convert::convert(dest.clone()), - }), + dest, }], }], }], @@ -265,8 +238,7 @@ pub mod module { fn transfer_owned_tokens_to_parachain( x_currency_id: XCurrencyId, para_id: ParaId, - dest: &T::AccountId, - dest_network: NetworkId, + dest: MultiLocation, amount: T::Balance, ) -> Xcm { Xcm::WithdrawAsset { @@ -279,10 +251,7 @@ pub mod module { dest: MultiLocation::X2(Junction::Parent, Junction::Parachain { id: para_id.into() }), effects: vec![Order::DepositAsset { assets: vec![MultiAsset::All], - dest: MultiLocation::X1(Junction::AccountId32 { - network: dest_network, - id: T::AccountId32Convert::convert(dest.clone()), - }), + dest, }], }], } @@ -294,16 +263,12 @@ pub mod module { reserve_chain: ParaId, x_currency_id: XCurrencyId, para_id: ParaId, - dest: &T::AccountId, - dest_network: NetworkId, + dest: MultiLocation, amount: T::Balance, ) -> Xcm { let deposit_to_dest = Order::DepositAsset { assets: vec![MultiAsset::All], - dest: MultiLocation::X1(Junction::AccountId32 { - network: dest_network, - id: T::AccountId32Convert::convert(dest.clone()), - }), + dest, }; // If transfer to reserve chain, deposit to `dest` on reserve chain, // else deposit reserve asset. From c98bdffbac7a63da7e4d1f8fdabf3f2de1f01110 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Mon, 15 Mar 2021 12:12:01 +1300 Subject: [PATCH 02/49] Use xcm-handler to execute XCM locally (#401) * Use cumulus xcm-handler to execute XCM locally. * Add docstring for xtokens config. --- xcm-support/src/lib.rs | 8 +++-- xtokens/Cargo.toml | 4 ++- xtokens/src/lib.rs | 68 +++++++++++++----------------------------- 3 files changed, 30 insertions(+), 50 deletions(-) diff --git a/xcm-support/src/lib.rs b/xcm-support/src/lib.rs index a5d55ed10..656968748 100644 --- a/xcm-support/src/lib.rs +++ b/xcm-support/src/lib.rs @@ -12,10 +12,14 @@ use sp_std::{ result, }; -use xcm::v0::{Error, Junction, MultiAsset, MultiLocation, Result}; +use xcm::v0::{Error, Junction, MultiAsset, MultiLocation, Result, Xcm}; use xcm_executor::traits::{FilterAssetLocation, LocationConversion, MatchesFungible, NativeAsset, TransactAsset}; -use frame_support::{log, traits::Get}; +use frame_support::{dispatch::DispatchResult, log, traits::Get}; + +pub trait XcmHandler { + fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult; +} pub trait CurrencyIdConversion { fn from_asset(asset: &MultiAsset) -> Option; diff --git a/xtokens/Cargo.toml b/xtokens/Cargo.toml index 5124431b1..8bce15bc9 100644 --- a/xtokens/Cargo.toml +++ b/xtokens/Cargo.toml @@ -20,7 +20,8 @@ frame-system = { git = "https://github.com/paritytech/substrate", branch = "roco cumulus-primitives-core = { git = "https://github.com/paritytech/cumulus", branch = "rococo-v1", default-features = false } xcm = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1", default-features = false } -xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1", default-features = false } + +orml-xcm-support = { path = "../xcm-support", default-features = false } [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } @@ -39,4 +40,5 @@ std = [ "frame-system/std", "cumulus-primitives-core/std", "xcm/std", + "orml-xcm-support/std", ] diff --git a/xtokens/src/lib.rs b/xtokens/src/lib.rs index 94f1ea3e8..cada34e21 100644 --- a/xtokens/src/lib.rs +++ b/xtokens/src/lib.rs @@ -17,8 +17,9 @@ pub mod module { use sp_std::prelude::*; use cumulus_primitives_core::{relay_chain::Balance as RelayChainBalance, ParaId}; - use xcm::v0::{Error as XcmError, ExecuteXcm, Junction, MultiAsset, MultiLocation, NetworkId, Order, Xcm}; - use xcm_executor::traits::LocationConversion; + 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. @@ -64,19 +65,21 @@ pub mod module { + MaybeSerializeDeserialize + Into; - /// Convertor `Balance` to `RelayChainBalance`. + /// Convert `Balance` to `RelayChainBalance`. type ToRelayChainBalance: Convert; + /// Convert `Self::Account` to `AccountId32` type AccountId32Convert: Convert; + /// The network id of relay chain. Typically `NetworkId::Polkadot` or + /// `NetworkId::Kusama`. type RelayChainNetworkId: Get; - /// Parachain ID. + /// Self parachain ID. type ParaId: Get; - type AccountIdConverter: LocationConversion; - - type XcmExecutor: ExecuteXcm; + /// Xcm handler to execute XCM. + type XcmHandler: XcmHandler; } #[pallet::event] @@ -85,23 +88,13 @@ pub mod module { /// Transferred to relay chain. \[src, dest, amount\] TransferredToRelayChain(T::AccountId, T::AccountId, T::Balance), - /// Transfer to relay chain failed. \[src, dest, amount, error\] - TransferToRelayChainFailed(T::AccountId, T::AccountId, T::Balance, XcmError), - /// Transferred to parachain. \[x_currency_id, src, para_id, dest, /// dest_network, amount\] TransferredToParachain(XCurrencyId, T::AccountId, ParaId, MultiLocation, T::Balance), - - /// Transfer to parachain failed. \[x_currency_id, src, para_id, dest, - /// dest_network, amount, error\] - TransferToParachainFailed(XCurrencyId, T::AccountId, ParaId, MultiLocation, T::Balance, XcmError), } #[pallet::error] - pub enum Error { - /// Bad location. - BadLocation, - } + pub enum Error {} #[pallet::hooks] impl Hooks for Pallet {} @@ -138,15 +131,9 @@ pub mod module { }], }], }; + T::XcmHandler::execute_xcm(who.clone(), xcm)?; - let xcm_origin = - T::AccountIdConverter::try_into_location(who.clone()).map_err(|_| Error::::BadLocation)?; - // TODO: revert state on xcm execution failure. - match T::XcmExecutor::execute_xcm(xcm_origin, xcm) { - Ok(_) => Self::deposit_event(Event::::TransferredToRelayChain(who, dest, amount)), - Err(err) => Self::deposit_event(Event::::TransferToRelayChainFailed(who, dest, amount, err)), - } - + Self::deposit_event(Event::::TransferredToRelayChain(who, dest, amount)); Ok(().into()) } @@ -182,28 +169,15 @@ pub mod module { } } }; + T::XcmHandler::execute_xcm(who.clone(), xcm)?; - let xcm_origin = - T::AccountIdConverter::try_into_location(who.clone()).map_err(|_| Error::::BadLocation)?; - // TODO: revert state on xcm execution failure. - match T::XcmExecutor::execute_xcm(xcm_origin, xcm) { - Ok(_) => Self::deposit_event(Event::::TransferredToParachain( - x_currency_id, - who, - para_id, - dest, - amount, - )), - Err(err) => Self::deposit_event(Event::::TransferToParachainFailed( - x_currency_id, - who, - para_id, - dest, - amount, - err, - )), - } - + Self::deposit_event(Event::::TransferredToParachain( + x_currency_id, + who, + para_id, + dest, + amount, + )); Ok(().into()) } } From b2d59388a5adbe99d2a676ca8ec64003cdd05654 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Mon, 15 Mar 2021 15:53:09 +1300 Subject: [PATCH 03/49] Replace XcmError::Undefined usage. (#402) * Replace XcmError::Undefined usage. * make clippy happy --- xcm-support/src/currency_adapter.rs | 80 +++++++++++++++++++++++++++++ xcm-support/src/lib.rs | 67 +++--------------------- 2 files changed, 87 insertions(+), 60 deletions(-) create mode 100644 xcm-support/src/currency_adapter.rs diff --git a/xcm-support/src/currency_adapter.rs b/xcm-support/src/currency_adapter.rs new file mode 100644 index 000000000..5eb76945f --- /dev/null +++ b/xcm-support/src/currency_adapter.rs @@ -0,0 +1,80 @@ +use codec::FullCodec; +use sp_runtime::traits::{MaybeSerializeDeserialize, SaturatedConversion}; +use sp_std::{ + cmp::{Eq, PartialEq}, + fmt::Debug, + marker::PhantomData, + prelude::*, + result, +}; + +use xcm::v0::{Error as XcmError, MultiAsset, MultiLocation, Result}; +use xcm_executor::traits::{LocationConversion, MatchesFungible, TransactAsset}; + +use crate::CurrencyIdConversion; + +/// Asset transaction errors. +enum Error { + /// Asset not found. + AssetNotFound, + /// `MultiLocation` to `AccountId` Conversion failed. + AccountIdConversionFailed, + /// `CurrencyId` conversion failed. + CurrencyIdConversionFailed, +} + +impl From for XcmError { + fn from(e: Error) -> Self { + match e { + Error::AssetNotFound => XcmError::FailedToTransactAsset("AssetNotFound"), + Error::AccountIdConversionFailed => XcmError::FailedToTransactAsset("AccountIdConversionFailed"), + Error::CurrencyIdConversionFailed => XcmError::FailedToTransactAsset("CurrencyIdConversionFailed"), + } + } +} + +pub struct MultiCurrencyAdapter( + PhantomData<( + MultiCurrency, + Matcher, + AccountIdConverter, + AccountId, + CurrencyIdConverter, + CurrencyId, + )>, +); + +impl< + MultiCurrency: orml_traits::MultiCurrency, + Matcher: MatchesFungible, + AccountIdConverter: LocationConversion, + AccountId: sp_std::fmt::Debug, + CurrencyIdConverter: CurrencyIdConversion, + CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug, + > TransactAsset + for MultiCurrencyAdapter +{ + fn deposit_asset(asset: &MultiAsset, location: &MultiLocation) -> Result { + 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 amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset) + .ok_or_else(|| XcmError::from(Error::AssetNotFound))? + .saturated_into(); + MultiCurrency::deposit(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into()))?; + Ok(()) + } + + fn withdraw_asset(asset: &MultiAsset, location: &MultiLocation) -> result::Result { + 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 amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset) + .ok_or_else(|| XcmError::from(Error::AssetNotFound))? + .saturated_into(); + MultiCurrency::withdraw(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into()))?; + Ok(asset.clone()) + } +} diff --git a/xcm-support/src/lib.rs b/xcm-support/src/lib.rs index 656968748..890744d97 100644 --- a/xcm-support/src/lib.rs +++ b/xcm-support/src/lib.rs @@ -1,21 +1,20 @@ #![cfg_attr(not(feature = "std"), no_std)] -use codec::FullCodec; -use sp_runtime::traits::{CheckedConversion, Convert, MaybeSerializeDeserialize, SaturatedConversion}; +use frame_support::{dispatch::DispatchResult, traits::Get}; +use sp_runtime::traits::{CheckedConversion, Convert}; use sp_std::{ - cmp::{Eq, PartialEq}, collections::btree_set::BTreeSet, convert::{TryFrom, TryInto}, - fmt::Debug, marker::PhantomData, prelude::*, - result, }; -use xcm::v0::{Error, Junction, MultiAsset, MultiLocation, Result, Xcm}; -use xcm_executor::traits::{FilterAssetLocation, LocationConversion, MatchesFungible, NativeAsset, TransactAsset}; +use xcm::v0::{Junction, MultiAsset, MultiLocation, Xcm}; +use xcm_executor::traits::{FilterAssetLocation, MatchesFungible, NativeAsset}; -use frame_support::{dispatch::DispatchResult, log, traits::Get}; +pub use currency_adapter::MultiCurrencyAdapter; + +mod currency_adapter; pub trait XcmHandler { fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult; @@ -25,58 +24,6 @@ pub trait CurrencyIdConversion { fn from_asset(asset: &MultiAsset) -> Option; } -pub struct MultiCurrencyAdapter( - PhantomData<( - MultiCurrency, - Matcher, - AccountIdConverter, - AccountId, - CurrencyIdConverter, - CurrencyId, - )>, -); - -impl< - MultiCurrency: orml_traits::MultiCurrency, - Matcher: MatchesFungible, - AccountIdConverter: LocationConversion, - AccountId: sp_std::fmt::Debug, - CurrencyIdConverter: CurrencyIdConversion, - CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug, - > TransactAsset - for MultiCurrencyAdapter -{ - fn deposit_asset(asset: &MultiAsset, location: &MultiLocation) -> Result { - log::info!("------------------------------------------------"); - log::info!(">>> trying deposit. asset: {:?}, location: {:?}", asset, location); - let who = AccountIdConverter::from_location(location).ok_or(())?; - log::info!("who: {:?}", who); - let currency_id = CurrencyIdConverter::from_asset(asset).ok_or(())?; - log::info!("currency_id: {:?}", currency_id); - let amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset).ok_or(())?.saturated_into(); - log::info!("amount: {:?}", amount); - MultiCurrency::deposit(currency_id, &who, amount).map_err(|_| ())?; - log::info!(">>> success deposit."); - log::info!("------------------------------------------------"); - Ok(()) - } - - fn withdraw_asset(asset: &MultiAsset, location: &MultiLocation) -> result::Result { - log::info!("------------------------------------------------"); - log::info!(">>> trying withdraw. asset: {:?}, location: {:?}", asset, location); - let who = AccountIdConverter::from_location(location).ok_or(())?; - log::info!("who: {:?}", who); - let currency_id = CurrencyIdConverter::from_asset(asset).ok_or(())?; - log::info!("currency_id: {:?}", currency_id); - let amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset).ok_or(())?.saturated_into(); - log::info!("amount: {:?}", amount); - MultiCurrency::withdraw(currency_id, &who, amount).map_err(|_| ())?; - log::info!(">>> success withdraw."); - log::info!("------------------------------------------------"); - Ok(asset.clone()) - } -} - pub struct IsConcreteWithGeneralKey( PhantomData<(CurrencyId, FromRelayChainBalance)>, ); From 8d7e29744d13697b7ea2b31f57605bade1000ebc Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Mon, 15 Mar 2021 16:10:06 +1300 Subject: [PATCH 04/49] Bump and unify serde versions. (#403) --- auction/Cargo.toml | 2 +- authority/Cargo.toml | 2 +- benchmarking/Cargo.toml | 2 +- currencies/Cargo.toml | 2 +- gradually-update/Cargo.toml | 2 +- nft/Cargo.toml | 2 +- oracle/Cargo.toml | 2 +- rewards/Cargo.toml | 2 +- tokens/Cargo.toml | 2 +- traits/Cargo.toml | 2 +- utilities/Cargo.toml | 4 ++-- vesting/Cargo.toml | 2 +- xtokens/Cargo.toml | 2 +- 13 files changed, 14 insertions(+), 14 deletions(-) diff --git a/auction/Cargo.toml b/auction/Cargo.toml index 5c568933b..64d024a3d 100644 --- a/auction/Cargo.toml +++ b/auction/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Acala Developers"] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/authority/Cargo.toml b/authority/Cargo.toml index 5d7a393f4..f124a7d20 100644 --- a/authority/Cargo.toml +++ b/authority/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Acala Developers"] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/benchmarking/Cargo.toml b/benchmarking/Cargo.toml index e2ae5e252..5727669c6 100644 --- a/benchmarking/Cargo.toml +++ b/benchmarking/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } paste = "0.1.16" codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-api = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/currencies/Cargo.toml b/currencies/Cargo.toml index a7029ed79..a58fd4cf8 100644 --- a/currencies/Cargo.toml +++ b/currencies/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/gradually-update/Cargo.toml b/gradually-update/Cargo.toml index 6df11cae4..1bde0d610 100644 --- a/gradually-update/Cargo.toml +++ b/gradually-update/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/nft/Cargo.toml b/nft/Cargo.toml index 1870aa65e..27fb6a414 100644 --- a/nft/Cargo.toml +++ b/nft/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Acala Developers"] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/oracle/Cargo.toml b/oracle/Cargo.toml index 8bd2e9df9..54e7bde93 100644 --- a/oracle/Cargo.toml +++ b/oracle/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-application-crypto = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/rewards/Cargo.toml b/rewards/Cargo.toml index fb7c747f6..674018a63 100644 --- a/rewards/Cargo.toml +++ b/rewards/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Acala Developers"] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/tokens/Cargo.toml b/tokens/Cargo.toml index 641eb41b2..ddb39ec31 100644 --- a/tokens/Cargo.toml +++ b/tokens/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/traits/Cargo.toml b/traits/Cargo.toml index e99c0d48b..75c492365 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/utilities/Cargo.toml b/utilities/Cargo.toml index 955ebc0ec..4b505a7a6 100644 --- a/utilities/Cargo.toml +++ b/utilities/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } @@ -18,7 +18,7 @@ sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 [dev-dependencies] -serde_json = "1.0.53" +serde_json = "1.0.64" frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } [features] diff --git a/vesting/Cargo.toml b/vesting/Cargo.toml index bb4cdc717..9f0cd14d8 100644 --- a/vesting/Cargo.toml +++ b/vesting/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Laminar Developers "] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/xtokens/Cargo.toml b/xtokens/Cargo.toml index 8bce15bc9..f36757779 100644 --- a/xtokens/Cargo.toml +++ b/xtokens/Cargo.toml @@ -8,7 +8,7 @@ authors = ["Acala Developers"] edition = "2018" [dependencies] -serde = { version = "1.0.111", optional = true } +serde = { version = "1.0.124", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } From 667a6d7f47ed0d1ffe8cac2f1972eb8b133db9fc Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Wed, 17 Mar 2021 15:47:26 +1300 Subject: [PATCH 05/49] xtokens and xcm-support documentations (#404) * Add xtokens module docstring. * Add xtokens readme. * Add documentations for xcm-support. * Add xtokens and xcm-support entries in main readme. --- README.md | 6 +++++- xcm-support/README.md | 6 ++++++ xcm-support/src/lib.rs | 17 +++++++++++++++++ xtokens/README.md | 39 +++++++++++++++++++++++++++++++++++++++ xtokens/src/lib.rs | 22 +++++++++++++++++++++- 5 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 xcm-support/README.md create mode 100644 xtokens/README.md diff --git a/README.md b/README.md index 7cc205fcc..273d09e80 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,10 @@ The Open Runtime Module Library (ORML) is a community maintained collection of S - Provides scheduled balance locking mechanism, in a *graded vesting* way. - [orml-gradually-update](./gradually-update) - Provides way to adjust numeric parameter gradually over a period of time. +- [orml-xtokens](./xtokens) + - Provides way to do cross-chain assets transfer. +- [orml-xcm-support](./xcm-support) + - Provides traits, types, and implementations to support XCM integration. ## Example @@ -48,7 +52,7 @@ ORML use `Cargo.dev.toml` to avoid workspace conflicts with project cargo config - change the command to `make dev-check` etc which does the copy. (For the full list of `make` commands, check `Makefile`) # Web3 Foundation Grant Project -ORML is part of the bigger `Open-Web3-Stack` initiative, that is currently under a General Grant from Web3 Foundation. See Application details [here](https://github.com/open-web3-stack/General-Grants-Program/blob/master/grants/speculative/open_web3_stack.md). The 1st milestone has been delivered. +ORML is part of the bigger `Open-Web3-Stack` initiative, that is currently under a General Grant from Web3 Foundation. See Application details [here](https://github.com/open-web3-stack/General-Grants-Program/blob/master/grants/speculative/open_web3_stack.md). The 1st milestone has been delivered. # Projects using ORML - [If you intend or are using ORML, please add your project here](https://github.com/open-web3-stack/open-runtime-module-library/edit/master/README.md) diff --git a/xcm-support/README.md b/xcm-support/README.md new file mode 100644 index 000000000..11fa712a6 --- /dev/null +++ b/xcm-support/README.md @@ -0,0 +1,6 @@ +# XCM Support Module. + +## Overview + +The XCM support module provides supporting traits, types and implementations, +to support cross-chain message(XCM) integration with ORML modules. diff --git a/xcm-support/src/lib.rs b/xcm-support/src/lib.rs index 890744d97..a2a59ed31 100644 --- a/xcm-support/src/lib.rs +++ b/xcm-support/src/lib.rs @@ -1,3 +1,11 @@ +//! # XCM Support Module. +//! +//! ## Overview +//! +//! The XCM support module provides supporting traits, types and +//! implementations, to support cross-chain message(XCM) integration with ORML +//! modules. + #![cfg_attr(not(feature = "std"), no_std)] use frame_support::{dispatch::DispatchResult, traits::Get}; @@ -16,14 +24,19 @@ pub use currency_adapter::MultiCurrencyAdapter; mod currency_adapter; +/// The XCM handler to execute XCM locally. 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)>, ); @@ -51,6 +64,8 @@ where } } +/// 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 { @@ -69,6 +84,8 @@ impl, MultiLocation)>>> FilterAssetLocation for Nat } } +/// `CurrencyIdConversion` implementation. Converts relay chain tokens, or +/// parachain tokens that could be decoded from a general key. pub struct CurrencyIdConverter( PhantomData, PhantomData, diff --git a/xtokens/README.md b/xtokens/README.md new file mode 100644 index 000000000..7032f29b8 --- /dev/null +++ b/xtokens/README.md @@ -0,0 +1,39 @@ +# Xtokens Module + +## Overview + +The xtokens module provides cross-chain token transfer functionality, by cross-consensus +messages(XCM). + +The xtokens module provides functions for +- Token transfer from parachains to relay chain. +- Token transfer between parachains, including relay chain tokens like DOT, + KSM, and parachain tokens like ACA, aUSD. + +## 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 cada34e21..92f4ad9b3 100644 --- a/xtokens/src/lib.rs +++ b/xtokens/src/lib.rs @@ -1,3 +1,22 @@ +//! # Xtokens Module +//! +//! ## Overview +//! +//! The xtokens module provides cross-chain token transfer functionality, by +//! cross-consensus messages(XCM). +//! +//! The xtokens module provides functions for +//! - Token transfer from parachains to relay chain. +//! - Token transfer between parachains, including relay chain tokens like DOT, +//! KSM, and parachain tokens like ACA, aUSD. +//! +//! ## Interface +//! +//! ### Dispatchable functions +//! +//! - `transfer_to_relay_chain`: Transfer relay chain tokens to relay chain. +//! - `transfer_to_parachain`: Transfer tokens to a sibling parachain. + #![cfg_attr(not(feature = "std"), no_std)] #![allow(clippy::from_over_into)] #![allow(clippy::unused_unit)] @@ -57,6 +76,7 @@ pub mod module { pub trait Config: frame_system::Config { type Event: From> + IsType<::Event>; + /// The balance type. type Balance: Parameter + Member + AtLeast32BitUnsigned @@ -137,7 +157,7 @@ pub mod module { Ok(().into()) } - /// Transfer tokens to parachain. + /// Transfer tokens to a sibling parachain. #[pallet::weight(10)] #[transactional] pub fn transfer_to_parachain( From e4ece39e4c7c862ebb8257ef0a037810a70338a9 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Wed, 17 Mar 2021 16:39:03 +1300 Subject: [PATCH 06/49] Add unit tests for xcm-support. (#405) --- xcm-support/src/lib.rs | 3 + xcm-support/src/tests.rs | 145 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 148 insertions(+) create mode 100644 xcm-support/src/tests.rs diff --git a/xcm-support/src/lib.rs b/xcm-support/src/lib.rs index a2a59ed31..e3a4aaacc 100644 --- a/xcm-support/src/lib.rs +++ b/xcm-support/src/lib.rs @@ -24,6 +24,9 @@ pub use currency_adapter::MultiCurrencyAdapter; mod currency_adapter; +#[cfg(test)] +mod tests; + /// The XCM handler to execute XCM locally. pub trait XcmHandler { fn execute_xcm(origin: AccountId, xcm: Xcm) -> DispatchResult; diff --git a/xcm-support/src/tests.rs b/xcm-support/src/tests.rs new file mode 100644 index 000000000..eb2bb777f --- /dev/null +++ b/xcm-support/src/tests.rs @@ -0,0 +1,145 @@ +//! Unit tests for xcm-support implementations. + +use super::*; + +use frame_support::parameter_types; +use sp_runtime::traits::{Convert, Identity}; + +#[derive(Debug, PartialEq, Eq)] +pub enum TestCurrencyId { + TokenA, + TokenB, + RelayChainToken, +} +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), + _ => 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; + +#[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)); + assert_eq!( + >::matches_fungible(&unknown_token), + None, + ); +} + +#[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 }), + )); +} + +#[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 }), + )); +} + +#[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]), + ), + amount: 10, + }; + + assert_eq!( + TestCurrencyIdConverter::from_asset(&token_a), + Some(TestCurrencyId::TokenA), + ); +} From a78aaed8abaa21627739a9595d54467731d40a29 Mon Sep 17 00:00:00 2001 From: "dzianis.ramanouski" Date: Wed, 17 Mar 2021 11:08:01 +0200 Subject: [PATCH 07/49] Added Minterest to the list of users. (#406) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 273d09e80..011c765b4 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ _In alphabetical order_ - [ChainX](https://github.com/chainx-org/ChainX) - [HydraDX](https://github.com/galacticcouncil/hack.HydraDX-node) - [Laminar Chain](https://github.com/laminar-protocol/laminar-chain) +- [Minterest](https://github.com/minterest-finance/minterest-chain-node) - [Plasm Network](https://github.com/PlasmNetwork) - [Setheum Network](https://github.com/Setheum-Labs/Setheum) - [Valiu Liquidity Network](https://github.com/valibre-org/vln-node) From ce683b02d901faed03deec099cc2e5d9326c7c67 Mon Sep 17 00:00:00 2001 From: Bette <42193328+bette7@users.noreply.github.com> Date: Thu, 18 Mar 2021 17:37:43 +1300 Subject: [PATCH 08/49] update step guide link --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 011c765b4..ce06987fa 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ The Open Runtime Module Library (ORML) is a community maintained collection of S - Provides way to adjust numeric parameter gradually over a period of time. - [orml-xtokens](./xtokens) - Provides way to do cross-chain assets transfer. + - [Step-by-Step guide](https://github.com/open-web3-stack/open-runtime-module-library/wiki/xtokens) to make XCM cross-chain fungible asset transfer available on your parachain - [orml-xcm-support](./xcm-support) - Provides traits, types, and implementations to support XCM integration. From 2ab8404ca9c4368fbf47251cd6815a01c6563b91 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Fri, 19 Mar 2021 07:34:17 +1300 Subject: [PATCH 09/49] Handle unknown assets in TransactAsset impl (#409) * Handle unknown assets in TransactAsset impl. * More documentations. * Clean code. * Renaming. * Should try to deposit known asset first. * Return error if no UnknownAsset impl. * Make clippy happy. --- xcm-support/src/currency_adapter.rs | 74 ++++++++++++++++++++--------- xcm-support/src/lib.rs | 25 +++++++++- 2 files changed, 75 insertions(+), 24 deletions(-) diff --git a/xcm-support/src/currency_adapter.rs b/xcm-support/src/currency_adapter.rs index 5eb76945f..6b8cf0b8f 100644 --- a/xcm-support/src/currency_adapter.rs +++ b/xcm-support/src/currency_adapter.rs @@ -11,12 +11,12 @@ use sp_std::{ use xcm::v0::{Error as XcmError, MultiAsset, MultiLocation, Result}; use xcm_executor::traits::{LocationConversion, MatchesFungible, TransactAsset}; -use crate::CurrencyIdConversion; +use crate::{CurrencyIdConversion, UnknownAsset as UnknownAssetT}; /// Asset transaction errors. enum Error { - /// Asset not found. - AssetNotFound, + /// Failed to match fungible. + FailedToMatchFungible, /// `MultiLocation` to `AccountId` Conversion failed. AccountIdConversionFailed, /// `CurrencyId` conversion failed. @@ -26,16 +26,29 @@ enum Error { impl From for XcmError { fn from(e: Error) -> Self { match e { - Error::AssetNotFound => XcmError::FailedToTransactAsset("AssetNotFound"), + Error::FailedToMatchFungible => XcmError::FailedToTransactAsset("FailedToMatchFungible"), Error::AccountIdConversionFailed => XcmError::FailedToTransactAsset("AccountIdConversionFailed"), Error::CurrencyIdConversionFailed => XcmError::FailedToTransactAsset("CurrencyIdConversionFailed"), } } } -pub struct MultiCurrencyAdapter( +/// The `TransactAsset` implementation, to handle `MultiAsset` deposit/withdraw. +/// +/// 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, +>( PhantomData<( MultiCurrency, + UnknownAsset, Matcher, AccountIdConverter, AccountId, @@ -46,35 +59,50 @@ pub struct MultiCurrencyAdapter, + UnknownAsset: UnknownAssetT, Matcher: MatchesFungible, AccountIdConverter: LocationConversion, AccountId: sp_std::fmt::Debug, CurrencyIdConverter: CurrencyIdConversion, CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug, > TransactAsset - for MultiCurrencyAdapter + for MultiCurrencyAdapter< + MultiCurrency, + UnknownAsset, + Matcher, + AccountIdConverter, + AccountId, + CurrencyIdConverter, + CurrencyId, + > { fn deposit_asset(asset: &MultiAsset, location: &MultiLocation) -> Result { - 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 amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset) - .ok_or_else(|| XcmError::from(Error::AssetNotFound))? - .saturated_into(); - MultiCurrency::deposit(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into()))?; - Ok(()) + match ( + AccountIdConverter::from_location(location), + CurrencyIdConverter::from_asset(asset), + Matcher::matches_fungible(&asset), + ) { + // known asset + (Some(who), Some(currency_id), Some(amount)) => { + MultiCurrency::deposit(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into())) + } + // unknown asset + _ => UnknownAsset::deposit(asset, location).map_err(|e| XcmError::FailedToTransactAsset(e.into())), + } } fn withdraw_asset(asset: &MultiAsset, location: &MultiLocation) -> result::Result { - 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 amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset) - .ok_or_else(|| XcmError::from(Error::AssetNotFound))? - .saturated_into(); - MultiCurrency::withdraw(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into()))?; + 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 amount: MultiCurrency::Balance = Matcher::matches_fungible(&asset) + .ok_or_else(|| XcmError::from(Error::FailedToMatchFungible))? + .saturated_into(); + MultiCurrency::withdraw(currency_id, &who, amount).map_err(|e| XcmError::FailedToTransactAsset(e.into())) + })?; + Ok(asset.clone()) } } diff --git a/xcm-support/src/lib.rs b/xcm-support/src/lib.rs index e3a4aaacc..e95d3c2f7 100644 --- a/xcm-support/src/lib.rs +++ b/xcm-support/src/lib.rs @@ -8,7 +8,10 @@ #![cfg_attr(not(feature = "std"), no_std)] -use frame_support::{dispatch::DispatchResult, traits::Get}; +use frame_support::{ + dispatch::{DispatchError, DispatchResult}, + traits::Get, +}; use sp_runtime::traits::{CheckedConversion, Convert}; use sp_std::{ collections::btree_set::BTreeSet, @@ -111,3 +114,23 @@ where None } } + +/// Handlers unknown asset deposit and withdraw. +pub trait UnknownAsset { + /// Deposit unknown asset. + fn deposit(asset: &MultiAsset, to: &MultiLocation) -> DispatchResult; + + /// Withdraw unknown asset. + fn withdraw(asset: &MultiAsset, from: &MultiLocation) -> DispatchResult; +} + +const NO_UNKNOWN_ASSET_IMPL: &str = "NoUnknownAssetImpl"; + +impl UnknownAsset for () { + fn deposit(_asset: &MultiAsset, _to: &MultiLocation) -> DispatchResult { + Err(DispatchError::Other(NO_UNKNOWN_ASSET_IMPL)) + } + fn withdraw(_asset: &MultiAsset, _from: &MultiLocation) -> DispatchResult { + Err(DispatchError::Other(NO_UNKNOWN_ASSET_IMPL)) + } +} From 83b05e2718e775bf59010e45ae191d742718480f Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Fri, 19 Mar 2021 13:00:32 +1300 Subject: [PATCH 10/49] Fix description and repo link. (#410) --- xcm-support/Cargo.toml | 2 +- xtokens/Cargo.toml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/xcm-support/Cargo.toml b/xcm-support/Cargo.toml index 045d9898c..d6b1ae783 100644 --- a/xcm-support/Cargo.toml +++ b/xcm-support/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "orml-xcm-support" -description = "Crosschain token transfer" +description = "Supporting module for XCM integration." repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/xcm-support" license = "Apache-2.0" version = "0.4.1-dev" diff --git a/xtokens/Cargo.toml b/xtokens/Cargo.toml index f36757779..3340fbacc 100644 --- a/xtokens/Cargo.toml +++ b/xtokens/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "orml-xtokens" -description = "Crosschain token transfer" -repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/tokens" +description = "Cross-chain token transfer." +repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/xtokens" license = "Apache-2.0" version = "0.4.1-dev" authors = ["Acala Developers"] From 918da400c7645b3f4c28afa9a670c9034390bc10 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Sat, 20 Mar 2021 10:05:49 +1300 Subject: [PATCH 11/49] Unknown tokens pallet (#411) * Impl unknown tokens pallet. * Fix workspace pallet path. * Make clippy happy. * Clippy, be happy. * Unit tests. --- Cargo.dev.toml | 1 + unknown-tokens/Cargo.toml | 36 +++++++ unknown-tokens/src/lib.rs | 127 ++++++++++++++++++++++ unknown-tokens/src/mock.rs | 73 +++++++++++++ unknown-tokens/src/tests.rs | 206 ++++++++++++++++++++++++++++++++++++ xcm-support/src/lib.rs | 2 +- xcm-support/src/tests.rs | 2 + 7 files changed, 446 insertions(+), 1 deletion(-) create mode 100644 unknown-tokens/Cargo.toml create mode 100644 unknown-tokens/src/lib.rs create mode 100644 unknown-tokens/src/mock.rs create mode 100644 unknown-tokens/src/tests.rs diff --git a/Cargo.dev.toml b/Cargo.dev.toml index a38c164db..bb6b15656 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -16,6 +16,7 @@ members = [ "nft", "xtokens", "xcm-support", + "unknown-tokens", ] resolver = "2" diff --git a/unknown-tokens/Cargo.toml b/unknown-tokens/Cargo.toml new file mode 100644 index 000000000..3518ee05d --- /dev/null +++ b/unknown-tokens/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "orml-unknown-tokens" +description = "Unknown tokens module that implements `UnknownAsset` trait." +repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/unknown-tokens" +license = "Apache-2.0" +version = "0.4.1-dev" +authors = ["Acala Developers"] +edition = "2018" + +[dependencies] +serde = { version = "1.0.124", optional = true } +codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } + +xcm = { git = "https://github.com/paritytech/polkadot", branch = "rococo-v1", default-features = false } + +orml-xcm-support = { path = "../xcm-support", default-features = false } + +[dev-dependencies] +sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } + +[features] +default = ["std"] +std = [ + "serde", + "codec/std", + "sp-std/std", + "frame-support/std", + "frame-system/std", + "xcm/std", + "orml-xcm-support/std", +] diff --git a/unknown-tokens/src/lib.rs b/unknown-tokens/src/lib.rs new file mode 100644 index 000000000..f162c91bb --- /dev/null +++ b/unknown-tokens/src/lib.rs @@ -0,0 +1,127 @@ +#![cfg_attr(not(feature = "std"), no_std)] +#![allow(clippy::unused_unit)] + +use frame_support::pallet_prelude::*; +use sp_std::vec::Vec; +use xcm::v0::{MultiAsset, MultiLocation}; + +use orml_xcm_support::UnknownAsset; + +pub use module::*; + +mod mock; +mod tests; + +#[frame_support::pallet] +pub mod module { + use super::*; + + #[pallet::config] + pub trait Config: frame_system::Config { + type Event: From + IsType<::Event>; + } + + #[pallet::event] + #[pallet::generate_deposit(pub(crate) fn deposit_event)] + 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] + pub enum Error { + /// The balance is too low. + BalanceTooLow, + /// The operation will cause balance to overflow. + BalanceOverflow, + /// Unhandled asset. + UnhandledAsset, + } + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::hooks] + impl Hooks for Pallet {} + + /// Concrete fungible balances under a given location and a concrete + /// fungible id. + /// + /// double_map: who, asset_id => u128 + #[pallet::storage] + #[pallet::getter(fn concrete_fungible_balances)] + pub(crate) type ConcreteFungibleBalances = + StorageDoubleMap<_, Blake2_128Concat, MultiLocation, Blake2_128Concat, MultiLocation, u128, ValueQuery>; + + /// Abstract fungible balances under a given location and a abstract + /// fungible id. + /// + /// double_map: who, asset_id => u128 + #[pallet::storage] + #[pallet::getter(fn abstract_fungible_balances)] + pub(crate) type AbstractFungibleBalances = + StorageDoubleMap<_, Blake2_128Concat, MultiLocation, Blake2_128Concat, Vec, u128, ValueQuery>; + + #[pallet::call] + impl Pallet {} +} + +impl UnknownAsset for Pallet { + fn deposit(asset: &MultiAsset, to: &MultiLocation) -> DispatchResult { + let result = match asset { + MultiAsset::ConcreteFungible { id, amount } => { + ConcreteFungibleBalances::::try_mutate(to, id, |b| -> DispatchResult { + *b = b.checked_add(*amount).ok_or(Error::::BalanceOverflow)?; + Ok(()) + }) + } + MultiAsset::AbstractFungible { id, amount } => { + AbstractFungibleBalances::::try_mutate(to, id, |b| -> DispatchResult { + *b = b.checked_add(*amount).ok_or(Error::::BalanceOverflow)?; + Ok(()) + }) + } + _ => 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())); + } + + result + } + + fn withdraw(asset: &MultiAsset, from: &MultiLocation) -> DispatchResult { + let result = match asset { + MultiAsset::ConcreteFungible { id, amount } => { + ConcreteFungibleBalances::::try_mutate(from, id, |b| -> DispatchResult { + *b = b.checked_sub(*amount).ok_or(Error::::BalanceTooLow)?; + Ok(()) + }) + } + MultiAsset::AbstractFungible { id, amount } => { + AbstractFungibleBalances::::try_mutate(from, id, |b| -> DispatchResult { + *b = b.checked_sub(*amount).ok_or(Error::::BalanceTooLow)?; + Ok(()) + }) + } + _ => 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())); + } + + result + } +} diff --git a/unknown-tokens/src/mock.rs b/unknown-tokens/src/mock.rs new file mode 100644 index 000000000..ee1a68842 --- /dev/null +++ b/unknown-tokens/src/mock.rs @@ -0,0 +1,73 @@ +//! Mocks for the unknown pallet. + +#![cfg(test)] + +use super::*; +use crate as unknown_tokens; + +use frame_support::{construct_runtime, parameter_types}; +use sp_core::H256; +use sp_runtime::{testing::Header, traits::IdentityLookup, AccountId32}; + +pub type AccountId = AccountId32; + +parameter_types! { + pub const BlockHashCount: u64 = 250; +} + +impl frame_system::Config for Runtime { + type Origin = Origin; + type Call = Call; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + type BlockWeights = (); + type BlockLength = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = (); + type SystemWeightInfo = (); + type SS58Prefix = (); +} + +impl Config for Runtime { + type Event = Event; +} + +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Module, Call, Storage, Config, Event}, + UnknownTokens: unknown_tokens::{Module, Storage, Event}, + } +); + +pub struct ExtBuilder; + +impl ExtBuilder { + pub fn build(self) -> sp_io::TestExternalities { + let t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext + } +} diff --git a/unknown-tokens/src/tests.rs b/unknown-tokens/src/tests.rs new file mode 100644 index 000000000..395f803c7 --- /dev/null +++ b/unknown-tokens/src/tests.rs @@ -0,0 +1,206 @@ +//! Unit tests for unknown tokens pallet. + +#![cfg(test)] + +use super::*; +use mock::{Event, *}; + +use codec::{Decode, Encode}; + +use frame_support::{assert_err, assert_ok}; +use xcm::v0::Junction; + +const MOCK_RECIPIENT: MultiLocation = MultiLocation::X1(Junction::Parent); +const MOCK_CONCRETE_FUNGIBLE_ID: MultiLocation = MultiLocation::X1(Junction::Parent); + +fn mock_abstract_fungible_id() -> Vec { + vec![1] +} + +fn concrete_fungible(amount: u128) -> MultiAsset { + MultiAsset::ConcreteFungible { + id: MOCK_CONCRETE_FUNGIBLE_ID, + amount, + } +} + +fn abstract_fungible(amount: u128) -> MultiAsset { + MultiAsset::AbstractFungible { + id: mock_abstract_fungible_id(), + amount, + } +} + +// `message` field of `DispatchError` would be gone after inserted into system +// pallet storage. +fn convert_err(err: DispatchError) -> DispatchError { + DispatchError::decode(&mut &err.encode()[..]).expect("encode then decode cannot fail") +} + +#[test] +fn deposit_concrete_fungible_asset_works() { + ExtBuilder.build().execute_with(|| { + let asset = concrete_fungible(3); + assert_ok!(UnknownTokens::deposit(&asset, &MOCK_RECIPIENT)); + assert_eq!( + UnknownTokens::concrete_fungible_balances(&MOCK_RECIPIENT, &MOCK_CONCRETE_FUNGIBLE_ID), + 3 + ); + + let deposited_event = Event::unknown_tokens(crate::Event::Deposited(asset, MOCK_RECIPIENT)); + assert!(System::events().iter().any(|record| record.event == deposited_event)); + + // overflow case + let max_asset = concrete_fungible(u128::max_value()); + assert_err!( + UnknownTokens::deposit(&max_asset, &MOCK_RECIPIENT), + Error::::BalanceOverflow + ); + + let deposit_failed_event = Event::unknown_tokens(crate::Event::DepositFailed( + max_asset, + MOCK_RECIPIENT, + convert_err(Error::::BalanceOverflow.into()), + )); + assert!(System::events() + .iter() + .any(|record| record.event == deposit_failed_event)); + }); +} + +#[test] +fn deposit_abstract_fungible_asset() { + ExtBuilder.build().execute_with(|| { + let asset = abstract_fungible(3); + assert_ok!(UnknownTokens::deposit(&asset, &MOCK_RECIPIENT)); + assert_eq!( + UnknownTokens::abstract_fungible_balances(&MOCK_RECIPIENT, &mock_abstract_fungible_id()), + 3 + ); + + let deposited_event = Event::unknown_tokens(crate::Event::Deposited(asset, MOCK_RECIPIENT)); + assert!(System::events().iter().any(|record| record.event == deposited_event)); + + // overflow case + let max_asset = abstract_fungible(u128::max_value()); + assert_err!( + UnknownTokens::deposit(&max_asset, &MOCK_RECIPIENT), + Error::::BalanceOverflow + ); + assert_eq!( + 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, + convert_err(Error::::BalanceOverflow.into()), + )); + assert!(System::events() + .iter() + .any(|record| record.event == deposit_failed_event)); + }); +} + +#[test] +fn deposit_unhandled_asset_should_fail() { + ExtBuilder.build().execute_with(|| { + assert_err!( + UnknownTokens::deposit(&MultiAsset::All, &MOCK_RECIPIENT), + Error::::UnhandledAsset + ); + + let deposit_failed_event = Event::unknown_tokens(crate::Event::DepositFailed( + MultiAsset::All, + MOCK_RECIPIENT, + convert_err(Error::::UnhandledAsset.into()), + )); + assert!(System::events() + .iter() + .any(|record| record.event == deposit_failed_event)); + }); +} + +#[test] +fn withdraw_concrete_fungible_asset_works() { + ExtBuilder.build().execute_with(|| { + ConcreteFungibleBalances::::insert(&MOCK_RECIPIENT, &MOCK_CONCRETE_FUNGIBLE_ID, 3); + + let asset = concrete_fungible(3); + assert_ok!(UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT)); + assert_eq!( + UnknownTokens::concrete_fungible_balances(&MOCK_RECIPIENT, &MOCK_CONCRETE_FUNGIBLE_ID), + 0 + ); + + let withdrawn_event = Event::unknown_tokens(crate::Event::Withdrawn(asset.clone(), MOCK_RECIPIENT)); + assert!(System::events().iter().any(|record| record.event == withdrawn_event)); + + // balance too low case + assert_err!( + UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT), + Error::::BalanceTooLow + ); + + let withdraw_failed_event = Event::unknown_tokens(crate::Event::WithdrawFailed( + asset, + MOCK_RECIPIENT, + convert_err(Error::::BalanceTooLow.into()), + )); + assert!(System::events() + .iter() + .any(|record| record.event == withdraw_failed_event)); + }); +} + +#[test] +fn withdraw_abstract_fungible_asset_works() { + ExtBuilder.build().execute_with(|| { + AbstractFungibleBalances::::insert(&MOCK_RECIPIENT, &mock_abstract_fungible_id(), 3); + + let asset = abstract_fungible(3); + assert_ok!(UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT)); + assert_eq!( + UnknownTokens::abstract_fungible_balances(&MOCK_RECIPIENT, &mock_abstract_fungible_id()), + 0 + ); + + let withdrawn_event = Event::unknown_tokens(crate::Event::Withdrawn(asset.clone(), MOCK_RECIPIENT)); + assert!(System::events().iter().any(|record| record.event == withdrawn_event)); + + // balance too low case + assert_err!( + UnknownTokens::withdraw(&asset, &MOCK_RECIPIENT), + Error::::BalanceTooLow + ); + + let withdraw_failed_event = Event::unknown_tokens(crate::Event::WithdrawFailed( + asset, + MOCK_RECIPIENT, + convert_err(Error::::BalanceTooLow.into()), + )); + assert!(System::events() + .iter() + .any(|record| record.event == withdraw_failed_event)); + }); +} + +#[test] +fn withdraw_unhandled_asset_should_fail() { + ExtBuilder.build().execute_with(|| { + assert_err!( + UnknownTokens::withdraw(&MultiAsset::All, &MOCK_RECIPIENT), + Error::::UnhandledAsset + ); + + let withdraw_failed_event = Event::unknown_tokens(crate::Event::WithdrawFailed( + MultiAsset::All, + MOCK_RECIPIENT, + convert_err(Error::::UnhandledAsset.into()), + )); + assert!(System::events() + .iter() + .any(|record| record.event == withdraw_failed_event)); + }); +} diff --git a/xcm-support/src/lib.rs b/xcm-support/src/lib.rs index e95d3c2f7..5b419a71d 100644 --- a/xcm-support/src/lib.rs +++ b/xcm-support/src/lib.rs @@ -7,6 +7,7 @@ //! modules. #![cfg_attr(not(feature = "std"), no_std)] +#![allow(clippy::unused_unit)] use frame_support::{ dispatch::{DispatchError, DispatchResult}, @@ -27,7 +28,6 @@ pub use currency_adapter::MultiCurrencyAdapter; mod currency_adapter; -#[cfg(test)] mod tests; /// The XCM handler to execute XCM locally. diff --git a/xcm-support/src/tests.rs b/xcm-support/src/tests.rs index eb2bb777f..b0348befd 100644 --- a/xcm-support/src/tests.rs +++ b/xcm-support/src/tests.rs @@ -1,5 +1,7 @@ //! Unit tests for xcm-support implementations. +#![cfg(test)] + use super::*; use frame_support::parameter_types; From 25db9ed77db5ba01ccfca834baf9b98f75565da7 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Mon, 22 Mar 2021 13:36:06 +1300 Subject: [PATCH 12/49] Remove nonces from oracle pallet. (#413) --- oracle/src/lib.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/oracle/src/lib.rs b/oracle/src/lib.rs index 4292be64f..0716ff3b9 100644 --- a/oracle/src/lib.rs +++ b/oracle/src/lib.rs @@ -139,10 +139,6 @@ pub mod module { #[pallet::getter(fn members)] pub type Members, I: 'static = ()> = StorageValue<_, OrderedSet, ValueQuery>; - #[pallet::storage] - #[pallet::getter(fn nonces)] - pub type Nonces, I: 'static = ()> = StorageMap<_, Twox64Concat, T::AccountId, u32>; - #[pallet::genesis_config] pub struct GenesisConfig, I: 'static = ()> { pub members: OrderedSet, From 68f3081876ea89904ca4b41d30ef3e532e01b288 Mon Sep 17 00:00:00 2001 From: wangjj9219 <183318287@qq.com> Date: Mon, 22 Mar 2021 10:28:28 +0800 Subject: [PATCH 13/49] refactor rewards (#412) --- rewards/src/default_weight.rs | 16 ----- rewards/src/lib.rs | 49 +++++---------- rewards/src/mock.rs | 36 ++--------- rewards/src/tests.rs | 109 +++++++--------------------------- traits/src/rewards.rs | 20 ++----- 5 files changed, 44 insertions(+), 186 deletions(-) delete mode 100644 rewards/src/default_weight.rs diff --git a/rewards/src/default_weight.rs b/rewards/src/default_weight.rs deleted file mode 100644 index a2be6a5dc..000000000 --- a/rewards/src/default_weight.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 2.0.0 - -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::weights::{constants::RocksDbWeight as DbWeight, Weight}; - -impl crate::WeightInfo for () { - fn on_initialize(c: u32) -> Weight { - (33_360_000 as Weight) - .saturating_add((23_139_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(DbWeight::get().reads(2 as Weight)) - .saturating_add(DbWeight::get().reads((1 as Weight).saturating_mul(c as Weight))) - } -} diff --git a/rewards/src/lib.rs b/rewards/src/lib.rs index 057c7e3d1..55be0d164 100644 --- a/rewards/src/lib.rs +++ b/rewards/src/lib.rs @@ -1,7 +1,6 @@ #![allow(clippy::unused_unit)] #![cfg_attr(not(feature = "std"), no_std)] -mod default_weight; mod mock; mod tests; @@ -37,10 +36,6 @@ pub use module::*; pub mod module { use super::*; - pub trait WeightInfo { - fn on_initialize(c: u32) -> Weight; - } - #[pallet::config] pub trait Config: frame_system::Config { /// The share type of pool. @@ -64,19 +59,10 @@ pub mod module { + FixedPointOperand; /// The reward pool ID type. - type PoolId: Parameter + Member + Copy + FullCodec; + type PoolId: Parameter + Member + Clone + FullCodec; /// The `RewardHandler` - type Handler: RewardHandler< - Self::AccountId, - Self::BlockNumber, - Share = Self::Share, - Balance = Self::Balance, - PoolId = Self::PoolId, - >; - - /// Weight information for extrinsics in this module. - type WeightInfo: WeightInfo; + type Handler: RewardHandler; } /// Stores reward pool info. @@ -95,27 +81,22 @@ pub mod module { pub struct Pallet(PhantomData); #[pallet::hooks] - impl Hooks for Pallet { - fn on_initialize(now: T::BlockNumber) -> Weight { - let mut count = 0; - T::Handler::accumulate_reward(now, |pool, reward_to_accumulate| { - if !reward_to_accumulate.is_zero() { - count += 1; - Pools::::mutate(pool, |pool_info| { - pool_info.total_rewards = pool_info.total_rewards.saturating_add(reward_to_accumulate) - }); - } - }); - T::WeightInfo::on_initialize(count) - } - } + impl Hooks for Pallet {} #[pallet::call] impl Pallet {} } impl Pallet { - pub fn add_share(who: &T::AccountId, pool: T::PoolId, add_amount: T::Share) { + pub fn accumulate_reward(pool: &T::PoolId, reward_increment: T::Balance) { + if !reward_increment.is_zero() { + Pools::::mutate(pool, |pool_info| { + pool_info.total_rewards = pool_info.total_rewards.saturating_add(reward_increment) + }); + } + } + + pub fn add_share(who: &T::AccountId, pool: &T::PoolId, add_amount: T::Share) { if add_amount.is_zero() { return; } @@ -135,7 +116,7 @@ impl Pallet { }); } - pub fn remove_share(who: &T::AccountId, pool: T::PoolId, remove_amount: T::Share) { + pub fn remove_share(who: &T::AccountId, pool: &T::PoolId, remove_amount: T::Share) { if remove_amount.is_zero() { return; } @@ -167,7 +148,7 @@ impl Pallet { }); } - pub fn set_share(who: &T::AccountId, pool: T::PoolId, new_share: T::Share) { + pub fn set_share(who: &T::AccountId, pool: &T::PoolId, new_share: T::Share) { let (share, _) = Self::share_and_withdrawn_reward(pool, who); if new_share > share { @@ -177,7 +158,7 @@ impl Pallet { } } - pub fn claim_rewards(who: &T::AccountId, pool: T::PoolId) { + pub fn claim_rewards(who: &T::AccountId, pool: &T::PoolId) { ShareAndWithdrawnReward::::mutate(pool, who, |(share, withdrawn_rewards)| { if share.is_zero() { return; diff --git a/rewards/src/mock.rs b/rewards/src/mock.rs index 5838f30bc..1baf08c98 100644 --- a/rewards/src/mock.rs +++ b/rewards/src/mock.rs @@ -16,14 +16,11 @@ pub type Balance = u64; pub type Share = u64; pub type PoolId = u32; pub type BlockNumber = u64; -pub type CurrencyId = u32; pub const ALICE: AccountId = 1; pub const BOB: AccountId = 2; pub const CAROL: AccountId = 3; pub const DOT_POOL: PoolId = 1; -pub const BTC_POOL: PoolId = 2; -pub const XBTC_POOL: PoolId = 3; parameter_types! { pub const BlockHashCount: u64 = 250; @@ -59,41 +56,17 @@ thread_local! { } pub struct Handler; -impl RewardHandler for Handler { - type Share = Share; +impl RewardHandler for Handler { type Balance = Balance; type PoolId = PoolId; - type CurrencyId = CurrencyId; - - fn accumulate_reward( - now: BlockNumber, - mut callback: impl FnMut(Self::PoolId, Self::Balance), - ) -> Vec<(Self::CurrencyId, Self::Balance)> { - if now % 2 == 0 { - let mut total_accumulated_rewards = 0; - let valid_pool_ids = vec![DOT_POOL, BTC_POOL]; - - for (pool, _) in Pools::::iter() { - if valid_pool_ids.contains(&pool) { - let rewards: Balance = 100; - callback(pool, rewards); - total_accumulated_rewards += rewards; - } - } - - vec![(1, total_accumulated_rewards)] - } else { - vec![] - } - } - fn payout(who: &AccountId, pool: Self::PoolId, amount: Self::Balance) { + fn payout(who: &AccountId, pool: &Self::PoolId, amount: Self::Balance) { RECEIVED_PAYOUT.with(|v| { let mut old_map = v.borrow().clone(); - if let Some(before) = old_map.get_mut(&(pool, *who)) { + if let Some(before) = old_map.get_mut(&(*pool, *who)) { *before += amount; } else { - old_map.insert((pool, *who), amount); + old_map.insert((*pool, *who), amount); }; *v.borrow_mut() = old_map; @@ -106,7 +79,6 @@ impl Config for Runtime { type Balance = Balance; type PoolId = PoolId; type Handler = Handler; - type WeightInfo = (); } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; diff --git a/rewards/src/tests.rs b/rewards/src/tests.rs index b3d8b9d30..cc2380db8 100644 --- a/rewards/src/tests.rs +++ b/rewards/src/tests.rs @@ -18,7 +18,7 @@ fn add_share_should_work() { ); assert_eq!(RewardsModule::share_and_withdrawn_reward(DOT_POOL, ALICE), (0, 0)); - RewardsModule::add_share(&ALICE, DOT_POOL, 0); + RewardsModule::add_share(&ALICE, &DOT_POOL, 0); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -29,7 +29,7 @@ fn add_share_should_work() { ); assert_eq!(RewardsModule::share_and_withdrawn_reward(DOT_POOL, ALICE), (0, 0)); - RewardsModule::add_share(&ALICE, DOT_POOL, 100); + RewardsModule::add_share(&ALICE, &DOT_POOL, 100); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -54,7 +54,7 @@ fn add_share_should_work() { ); assert_eq!(RewardsModule::share_and_withdrawn_reward(DOT_POOL, BOB), (0, 0)); - RewardsModule::add_share(&BOB, DOT_POOL, 50); + RewardsModule::add_share(&BOB, &DOT_POOL, 50); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -65,7 +65,7 @@ fn add_share_should_work() { ); assert_eq!(RewardsModule::share_and_withdrawn_reward(DOT_POOL, BOB), (50, 2500)); - RewardsModule::add_share(&ALICE, DOT_POOL, 150); + RewardsModule::add_share(&ALICE, &DOT_POOL, 150); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -81,12 +81,12 @@ fn add_share_should_work() { #[test] fn claim_rewards_should_work() { ExtBuilder::default().build().execute_with(|| { - RewardsModule::add_share(&ALICE, DOT_POOL, 100); - RewardsModule::add_share(&BOB, DOT_POOL, 100); + RewardsModule::add_share(&ALICE, &DOT_POOL, 100); + RewardsModule::add_share(&BOB, &DOT_POOL, 100); Pools::::mutate(DOT_POOL, |pool_info| { pool_info.total_rewards += 5000; }); - RewardsModule::add_share(&CAROL, DOT_POOL, 200); + RewardsModule::add_share(&CAROL, &DOT_POOL, 200); assert_eq!( RewardsModule::pools(DOT_POOL), @@ -112,7 +112,7 @@ fn claim_rewards_should_work() { 0 ); - RewardsModule::claim_rewards(&ALICE, DOT_POOL); + RewardsModule::claim_rewards(&ALICE, &DOT_POOL); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -127,7 +127,7 @@ fn claim_rewards_should_work() { 2500 ); - RewardsModule::claim_rewards(&CAROL, DOT_POOL); + RewardsModule::claim_rewards(&CAROL, &DOT_POOL); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -142,7 +142,7 @@ fn claim_rewards_should_work() { 0 ); - RewardsModule::claim_rewards(&BOB, DOT_POOL); + RewardsModule::claim_rewards(&BOB, &DOT_POOL); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -162,8 +162,8 @@ fn claim_rewards_should_work() { #[test] fn remove_share_should_work() { ExtBuilder::default().build().execute_with(|| { - RewardsModule::add_share(&ALICE, DOT_POOL, 100); - RewardsModule::add_share(&BOB, DOT_POOL, 100); + RewardsModule::add_share(&ALICE, &DOT_POOL, 100); + RewardsModule::add_share(&BOB, &DOT_POOL, 100); Pools::::mutate(DOT_POOL, |pool_info| { pool_info.total_rewards += 10000; }); @@ -188,7 +188,7 @@ fn remove_share_should_work() { ); // remove amount is zero, do not claim interest - RewardsModule::remove_share(&ALICE, DOT_POOL, 0); + RewardsModule::remove_share(&ALICE, &DOT_POOL, 0); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -203,7 +203,7 @@ fn remove_share_should_work() { 0 ); - RewardsModule::remove_share(&BOB, DOT_POOL, 50); + RewardsModule::remove_share(&BOB, &DOT_POOL, 50); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -218,7 +218,7 @@ fn remove_share_should_work() { 5000 ); - RewardsModule::remove_share(&ALICE, DOT_POOL, 101); + RewardsModule::remove_share(&ALICE, &DOT_POOL, 101); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -248,7 +248,7 @@ fn set_share_should_work() { ); assert_eq!(RewardsModule::share_and_withdrawn_reward(DOT_POOL, ALICE), (0, 0)); - RewardsModule::set_share(&ALICE, DOT_POOL, 100); + RewardsModule::set_share(&ALICE, &DOT_POOL, 100); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -271,7 +271,7 @@ fn set_share_should_work() { } ); - RewardsModule::set_share(&ALICE, DOT_POOL, 500); + RewardsModule::set_share(&ALICE, &DOT_POOL, 500); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -286,7 +286,7 @@ fn set_share_should_work() { 0 ); - RewardsModule::set_share(&ALICE, DOT_POOL, 100); + RewardsModule::set_share(&ALICE, &DOT_POOL, 100); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -304,43 +304,18 @@ fn set_share_should_work() { } #[test] -fn on_initialize_should_work() { +fn accumulate_reward_should_work() { ExtBuilder::default().build().execute_with(|| { - Pools::::mutate(DOT_POOL, |pool_info| { - pool_info.total_rewards += 100; - }); - Pools::::mutate(BTC_POOL, |pool_info| { - pool_info.total_rewards += 200; - }); - Pools::::mutate(XBTC_POOL, |pool_info| { - pool_info.total_rewards += 300; - }); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { total_shares: 0, - total_rewards: 100, - total_withdrawn_rewards: 0, - } - ); - assert_eq!( - RewardsModule::pools(BTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 200, - total_withdrawn_rewards: 0, - } - ); - assert_eq!( - RewardsModule::pools(XBTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 300, + total_rewards: 0, total_withdrawn_rewards: 0, } ); - RewardsModule::on_initialize(1); + RewardsModule::accumulate_reward(&DOT_POOL, 100); assert_eq!( RewardsModule::pools(DOT_POOL), PoolInfo { @@ -349,47 +324,5 @@ fn on_initialize_should_work() { total_withdrawn_rewards: 0, } ); - assert_eq!( - RewardsModule::pools(BTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 200, - total_withdrawn_rewards: 0, - } - ); - assert_eq!( - RewardsModule::pools(XBTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 300, - total_withdrawn_rewards: 0, - } - ); - - RewardsModule::on_initialize(2); - assert_eq!( - RewardsModule::pools(DOT_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 200, - total_withdrawn_rewards: 0, - } - ); - assert_eq!( - RewardsModule::pools(BTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 300, - total_withdrawn_rewards: 0, - } - ); - assert_eq!( - RewardsModule::pools(XBTC_POOL), - PoolInfo { - total_shares: 0, - total_rewards: 300, - total_withdrawn_rewards: 0, - } - ); }); } diff --git a/traits/src/rewards.rs b/traits/src/rewards.rs index e53b905a6..ebf21f4b8 100644 --- a/traits/src/rewards.rs +++ b/traits/src/rewards.rs @@ -1,27 +1,15 @@ use codec::FullCodec; use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize}; -use sp_std::{fmt::Debug, vec::Vec}; +use sp_std::fmt::Debug; /// Hooks to manage reward pool -pub trait RewardHandler { - /// The share type of pool - type Share: AtLeast32BitUnsigned + Default + Copy + MaybeSerializeDeserialize + Debug; - +pub trait RewardHandler { /// The reward balance type type Balance: AtLeast32BitUnsigned + Default + Copy + MaybeSerializeDeserialize + Debug; /// The reward pool ID type - type PoolId: Copy + FullCodec; - - /// The currency type - type CurrencyId: FullCodec + Eq + PartialEq + Copy + MaybeSerializeDeserialize + Debug; - - /// Accumulate rewards - fn accumulate_reward( - now: BlockNumber, - callback: impl FnMut(Self::PoolId, Self::Balance), - ) -> Vec<(Self::CurrencyId, Self::Balance)>; + type PoolId: FullCodec; /// Payout the reward to `who` - fn payout(who: &AccountId, pool: Self::PoolId, amount: Self::Balance); + fn payout(who: &AccountId, pool: &Self::PoolId, amount: Self::Balance); } From 523c95a66e7b1b3703f90b1512b42bf1505edd33 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Wed, 24 Mar 2021 17:11:33 +1300 Subject: [PATCH 14/49] Bump rococo v1 dependencies (#418) * Fix mocks. * Replace deprecated. --- auction/src/lib.rs | 2 +- auction/src/mock.rs | 4 ++-- authority/src/lib.rs | 6 +++--- authority/src/mock.rs | 6 +++--- benchmarking/src/lib.rs | 8 ++++---- benchmarking/src/tests.rs | 4 ++-- currencies/src/mock.rs | 10 +++++----- gradually-update/src/mock.rs | 5 ++--- nft/src/mock.rs | 4 ++-- oracle/src/mock.rs | 4 ++-- rewards/src/mock.rs | 4 ++-- tokens/src/lib.rs | 8 ++++---- tokens/src/mock.rs | 8 ++++---- unknown-tokens/src/mock.rs | 4 ++-- vesting/src/lib.rs | 2 +- vesting/src/mock.rs | 8 ++++---- 16 files changed, 43 insertions(+), 44 deletions(-) diff --git a/auction/src/lib.rs b/auction/src/lib.rs index 115861bbf..65879960e 100644 --- a/auction/src/lib.rs +++ b/auction/src/lib.rs @@ -131,7 +131,7 @@ pub mod module { Auctions::::try_mutate_exists(id, |auction| -> DispatchResult { let mut auction = auction.as_mut().ok_or(Error::::AuctionNotExist)?; - let block_number = >::block_number(); + let block_number = >::block_number(); // make sure auction is started ensure!(block_number >= auction.start, Error::::AuctionNotStarted); diff --git a/auction/src/mock.rs b/auction/src/mock.rs index ab409e6f0..25558c2eb 100644 --- a/auction/src/mock.rs +++ b/auction/src/mock.rs @@ -86,8 +86,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - AuctionModule: auction::{Module, Storage, Call, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + AuctionModule: auction::{Pallet, Storage, Call, Event}, } ); diff --git a/authority/src/lib.rs b/authority/src/lib.rs index 01d45f920..6481a2c01 100644 --- a/authority/src/lib.rs +++ b/authority/src/lib.rs @@ -244,7 +244,7 @@ pub mod module { *id = id.checked_add(1).ok_or(Error::::Overflow)?; Ok(current_id) })?; - let now = frame_system::Module::::block_number(); + let now = frame_system::Pallet::::block_number(); let delay = match when { DispatchTime::At(x) => x.checked_sub(&now).ok_or(Error::::Overflow)?, DispatchTime::After(x) => x, @@ -283,7 +283,7 @@ pub mod module { task_id: ScheduleTaskIndex, when: DispatchTime, ) -> DispatchResultWithPostInfo { - let now = frame_system::Module::::block_number(); + let now = frame_system::Pallet::::block_number(); let new_delay = match when { DispatchTime::At(x) => x.checked_sub(&now).ok_or(Error::::Overflow)?, DispatchTime::After(x) => x, @@ -317,7 +317,7 @@ pub mod module { ) .map_err(|_| Error::::FailedToDelay)?; - let now = frame_system::Module::::block_number(); + let now = frame_system::Pallet::::block_number(); let dispatch_at = now.saturating_add(additional_delay); Self::deposit_event(Event::Delayed(initial_origin, task_id, dispatch_at)); diff --git a/authority/src/mock.rs b/authority/src/mock.rs index a3f6fa02d..069f994a8 100644 --- a/authority/src/mock.rs +++ b/authority/src/mock.rs @@ -162,9 +162,9 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Module, Call, Config, Event}, - Authority: authority::{Module, Call, Origin, Event}, - Scheduler: pallet_scheduler::{Module, Call, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Event}, + Authority: authority::{Pallet, Call, Origin, Event}, + Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event}, } ); diff --git a/benchmarking/src/lib.rs b/benchmarking/src/lib.rs index 71c6af4e7..75218e3e0 100644 --- a/benchmarking/src/lib.rs +++ b/benchmarking/src/lib.rs @@ -844,8 +844,8 @@ macro_rules! impl_benchmark { >::instance(&selected_benchmark, c, verify)?; // Set the block number to at least 1 so events are deposited. - if $crate::Zero::is_zero(&frame_system::Module::<$runtime>::block_number()) { - frame_system::Module::<$runtime>::set_block_number(1u32.into()); + if $crate::Zero::is_zero(&frame_system::Pallet::<$runtime>::block_number()) { + frame_system::Pallet::<$runtime>::set_block_number(1u32.into()); } // Commit the externalities to the database, flushing the DB cache. @@ -990,8 +990,8 @@ macro_rules! impl_benchmark_test { >::instance(&selected_benchmark, &c, true)?; // Set the block number to at least 1 so events are deposited. - if $crate::Zero::is_zero(&frame_system::Module::<$runtime>::block_number()) { - frame_system::Module::<$runtime>::set_block_number(1u32.into()); + if $crate::Zero::is_zero(&frame_system::Pallet::<$runtime>::block_number()) { + frame_system::Pallet::<$runtime>::set_block_number(1u32.into()); } // Run execution + verification diff --git a/benchmarking/src/tests.rs b/benchmarking/src/tests.rs index 2c015f329..5068c8146 100644 --- a/benchmarking/src/tests.rs +++ b/benchmarking/src/tests.rs @@ -97,8 +97,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - Pallet: test::{Module, Call, Storage, Config}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Pallet: test::{Pallet, Call, Storage, Config}, } ); diff --git a/currencies/src/mock.rs b/currencies/src/mock.rs index 621876964..a71a81f23 100644 --- a/currencies/src/mock.rs +++ b/currencies/src/mock.rs @@ -56,7 +56,7 @@ impl pallet_balances::Config for Runtime { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; + type AccountStore = frame_system::Pallet; type MaxLocks = (); type WeightInfo = (); } @@ -107,10 +107,10 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - Currencies: currencies::{Module, Call, Event}, - Tokens: orml_tokens::{Module, Storage, Event, Config}, - PalletBalances: pallet_balances::{Module, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Currencies: currencies::{Pallet, Call, Event}, + Tokens: orml_tokens::{Pallet, Storage, Event, Config}, + PalletBalances: pallet_balances::{Pallet, Call, Storage, Config, Event}, } ); diff --git a/gradually-update/src/mock.rs b/gradually-update/src/mock.rs index 981492564..d837e6367 100644 --- a/gradually-update/src/mock.rs +++ b/gradually-update/src/mock.rs @@ -61,9 +61,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - GraduallyUpdateModule: gradually_update::{Module, Storage, Call, Event}, - + System: frame_system::{Pallet, Call, Storage, Config, Event}, + GraduallyUpdateModule: gradually_update::{Pallet, Storage, Call, Event}, } ); diff --git a/nft/src/mock.rs b/nft/src/mock.rs index a8d1dae2a..cf4bac4f2 100644 --- a/nft/src/mock.rs +++ b/nft/src/mock.rs @@ -58,8 +58,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - NonFungibleTokenModule: nft::{Module, Storage, Config}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + NonFungibleTokenModule: nft::{Pallet, Storage, Config}, } ); diff --git a/oracle/src/mock.rs b/oracle/src/mock.rs index b0173ac2b..c7ea7487f 100644 --- a/oracle/src/mock.rs +++ b/oracle/src/mock.rs @@ -92,8 +92,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - ModuleOracle: oracle::{Module, Storage, Call, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + ModuleOracle: oracle::{Pallet, Storage, Call, Config, Event}, } ); diff --git a/rewards/src/mock.rs b/rewards/src/mock.rs index 1baf08c98..d088983b2 100644 --- a/rewards/src/mock.rs +++ b/rewards/src/mock.rs @@ -90,8 +90,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - RewardsModule: rewards::{Module, Storage, Call}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + RewardsModule: rewards::{Pallet, Storage, Call}, } ); diff --git a/tokens/src/lib.rs b/tokens/src/lib.rs index 717698ff4..64ecb0f95 100644 --- a/tokens/src/lib.rs +++ b/tokens/src/lib.rs @@ -381,10 +381,10 @@ impl Pallet { // If existed before, decrease account provider. // Ignore the result, because if it failed means that these’s remain consumers, // and the account storage in frame_system shouldn't be repeaded. - let _ = frame_system::Module::::dec_providers(who); + let _ = frame_system::Pallet::::dec_providers(who); } else if !existed && exists { // if new, increase account provider - frame_system::Module::::inc_providers(who); + frame_system::Pallet::::inc_providers(who); } if let Some(dust_amount) = handle_dust { @@ -446,13 +446,13 @@ impl Pallet { >::remove(who, currency_id); if existed { // decrease account ref count when destruct lock - frame_system::Module::::dec_consumers(who); + frame_system::Pallet::::dec_consumers(who); } } else { >::insert(who, currency_id, locks); if !existed { // increase account ref count when initialize lock - if frame_system::Module::::inc_consumers(who).is_err() { + if frame_system::Pallet::::inc_consumers(who).is_err() { // No providers for the locks. This is impossible under normal circumstances // since the funds that are under the lock will themselves be stored in the // account and therefore will need a reference. diff --git a/tokens/src/mock.rs b/tokens/src/mock.rs index a46a04667..bc430b16a 100644 --- a/tokens/src/mock.rs +++ b/tokens/src/mock.rs @@ -226,10 +226,10 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - Tokens: tokens::{Module, Storage, Event, Config}, - Treasury: pallet_treasury::{Module, Call, Storage, Config, Event}, - ElectionsPhragmen: pallet_elections_phragmen::{Module, Call, Storage, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Tokens: tokens::{Pallet, Storage, Event, Config}, + Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event}, + ElectionsPhragmen: pallet_elections_phragmen::{Pallet, Call, Storage, Event}, } ); diff --git a/unknown-tokens/src/mock.rs b/unknown-tokens/src/mock.rs index ee1a68842..1a68d01c4 100644 --- a/unknown-tokens/src/mock.rs +++ b/unknown-tokens/src/mock.rs @@ -53,8 +53,8 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - UnknownTokens: unknown_tokens::{Module, Storage, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + UnknownTokens: unknown_tokens::{Pallet, Storage, Event}, } ); diff --git a/vesting/src/lib.rs b/vesting/src/lib.rs index b314dfb0b..b913d0516 100644 --- a/vesting/src/lib.rs +++ b/vesting/src/lib.rs @@ -277,7 +277,7 @@ impl Pallet { /// Returns locked balance based on current block number. fn locked_balance(who: &T::AccountId) -> BalanceOf { - let now = >::block_number(); + let now = >::block_number(); >::mutate_exists(who, |maybe_schedules| { let total = if let Some(schedules) = maybe_schedules.as_mut() { let mut total: BalanceOf = Zero::zero(); diff --git a/vesting/src/mock.rs b/vesting/src/mock.rs index 7274ef9c7..c99f50059 100644 --- a/vesting/src/mock.rs +++ b/vesting/src/mock.rs @@ -52,7 +52,7 @@ impl pallet_balances::Config for Runtime { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; + type AccountStore = frame_system::Pallet; type MaxLocks = (); type WeightInfo = (); } @@ -92,9 +92,9 @@ construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { - System: frame_system::{Module, Call, Storage, Config, Event}, - Vesting: vesting::{Module, Storage, Call, Event, Config}, - PalletBalances: pallet_balances::{Module, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Vesting: vesting::{Pallet, Storage, Call, Event, Config}, + PalletBalances: pallet_balances::{Pallet, Call, Storage, Config, Event}, } ); From 11175f6c60e2b414bf1047ba556c0c58ae519384 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Thu, 25 Mar 2021 13:11:09 +1300 Subject: [PATCH 15/49] Update orml-unknown-tokens unit tests. (#421) --- unknown-tokens/src/tests.rs | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/unknown-tokens/src/tests.rs b/unknown-tokens/src/tests.rs index 395f803c7..63ad7a2d4 100644 --- a/unknown-tokens/src/tests.rs +++ b/unknown-tokens/src/tests.rs @@ -31,12 +31,6 @@ fn abstract_fungible(amount: u128) -> MultiAsset { } } -// `message` field of `DispatchError` would be gone after inserted into system -// pallet storage. -fn convert_err(err: DispatchError) -> DispatchError { - DispatchError::decode(&mut &err.encode()[..]).expect("encode then decode cannot fail") -} - #[test] fn deposit_concrete_fungible_asset_works() { ExtBuilder.build().execute_with(|| { @@ -60,7 +54,7 @@ fn deposit_concrete_fungible_asset_works() { let deposit_failed_event = Event::unknown_tokens(crate::Event::DepositFailed( max_asset, MOCK_RECIPIENT, - convert_err(Error::::BalanceOverflow.into()), + Error::::BalanceOverflow.into(), )); assert!(System::events() .iter() @@ -95,7 +89,7 @@ fn deposit_abstract_fungible_asset() { let deposit_failed_event = Event::unknown_tokens(crate::Event::DepositFailed( max_asset, MOCK_RECIPIENT, - convert_err(Error::::BalanceOverflow.into()), + Error::::BalanceOverflow.into(), )); assert!(System::events() .iter() @@ -114,7 +108,7 @@ fn deposit_unhandled_asset_should_fail() { let deposit_failed_event = Event::unknown_tokens(crate::Event::DepositFailed( MultiAsset::All, MOCK_RECIPIENT, - convert_err(Error::::UnhandledAsset.into()), + Error::::UnhandledAsset.into(), )); assert!(System::events() .iter() @@ -146,7 +140,7 @@ fn withdraw_concrete_fungible_asset_works() { let withdraw_failed_event = Event::unknown_tokens(crate::Event::WithdrawFailed( asset, MOCK_RECIPIENT, - convert_err(Error::::BalanceTooLow.into()), + Error::::BalanceTooLow.into(), )); assert!(System::events() .iter() @@ -178,7 +172,7 @@ fn withdraw_abstract_fungible_asset_works() { let withdraw_failed_event = Event::unknown_tokens(crate::Event::WithdrawFailed( asset, MOCK_RECIPIENT, - convert_err(Error::::BalanceTooLow.into()), + Error::::BalanceTooLow.into(), )); assert!(System::events() .iter() @@ -197,7 +191,7 @@ fn withdraw_unhandled_asset_should_fail() { let withdraw_failed_event = Event::unknown_tokens(crate::Event::WithdrawFailed( MultiAsset::All, MOCK_RECIPIENT, - convert_err(Error::::UnhandledAsset.into()), + Error::::UnhandledAsset.into(), )); assert!(System::events() .iter() From d81bd2517ae63651cd0e20a153a1e379e4bd83cc Mon Sep 17 00:00:00 2001 From: Xiliang Chen Date: Thu, 25 Mar 2021 13:34:13 +1300 Subject: [PATCH 16/49] add build-script-utils from Substrate (#422) --- Cargo.dev.toml | 1 + build-script-utils/Cargo.toml | 14 ++++++++ build-script-utils/README.md | 3 ++ build-script-utils/src/lib.rs | 5 +++ build-script-utils/src/version.rs | 55 +++++++++++++++++++++++++++++++ 5 files changed, 78 insertions(+) create mode 100644 build-script-utils/Cargo.toml create mode 100644 build-script-utils/README.md create mode 100644 build-script-utils/src/lib.rs create mode 100644 build-script-utils/src/version.rs diff --git a/Cargo.dev.toml b/Cargo.dev.toml index bb6b15656..62df286d2 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -17,6 +17,7 @@ members = [ "xtokens", "xcm-support", "unknown-tokens", + "build-script-utils", ] resolver = "2" diff --git a/build-script-utils/Cargo.toml b/build-script-utils/Cargo.toml new file mode 100644 index 000000000..c5d311634 --- /dev/null +++ b/build-script-utils/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "orml-build-script-utils" +description = "Crate with utility functions for `build.rs` scripts." +repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/build-script-utils" +license = "Apache-2.0" +version = "0.4.1-dev" +authors = ["Parity Technologies ", "Laminar Developers "] +edition = "2018" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +platforms = "1.1" diff --git a/build-script-utils/README.md b/build-script-utils/README.md new file mode 100644 index 000000000..1c184f673 --- /dev/null +++ b/build-script-utils/README.md @@ -0,0 +1,3 @@ +Crate with utility functions for `build.rs` scripts. + +License: Apache-2.0 \ No newline at end of file diff --git a/build-script-utils/src/lib.rs b/build-script-utils/src/lib.rs new file mode 100644 index 000000000..6d3177d51 --- /dev/null +++ b/build-script-utils/src/lib.rs @@ -0,0 +1,5 @@ +//! Crate with utility functions for `build.rs` scripts. + +mod version; + +pub use version::*; diff --git a/build-script-utils/src/version.rs b/build-script-utils/src/version.rs new file mode 100644 index 000000000..599f0d617 --- /dev/null +++ b/build-script-utils/src/version.rs @@ -0,0 +1,55 @@ +use platforms::*; +use std::process::Command; + +/// Generate the `cargo:` key output +pub fn generate_cargo_keys() { + println!( + "cargo:rustc-env=SUBSTRATE_CLI_IMPL_VERSION={}", + get_version(get_commit()) + ) +} + +fn get_platform() -> String { + let env_dash = if TARGET_ENV.is_some() { "-" } else { "" }; + + format!( + "{}-{}{}{}", + TARGET_ARCH.as_str(), + TARGET_OS.as_str(), + env_dash, + TARGET_ENV.map(|x| x.as_str()).unwrap_or(""), + ) +} + +fn get_version(impl_commit: String) -> String { + let commit_dash = if impl_commit.is_empty() { "" } else { "-" }; + + format!( + "{}{}{}-{}", + std::env::var("CARGO_PKG_VERSION").unwrap_or_default(), + commit_dash, + impl_commit, + get_platform(), + ) +} + +fn get_commit() -> String { + let commit = std::env::var("GIT_COMMIT").unwrap_or_default(); + if !commit.is_empty() { + return commit; + } + + let output = Command::new("git").args(&["rev-parse", "--short", "HEAD"]).output(); + + match output { + Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().into(), + Ok(o) => { + println!("cargo:warning=Git command failed with status: {}", o.status); + "unknown".into() + } + Err(err) => { + println!("cargo:warning=Failed to execute git command: {}", err); + "unknown".into() + } + } +} From e6af4298069cd5fdb2a0e0d8ada3575ee47b6b9c Mon Sep 17 00:00:00 2001 From: transxask <68648225+transxask@users.noreply.github.com> Date: Thu, 25 Mar 2021 14:07:03 +0800 Subject: [PATCH 17/49] Update README.md (#420) * Update README.md * Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index ce06987fa..73c620144 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,9 @@ _In alphabetical order_ - [ChainX](https://github.com/chainx-org/ChainX) - [HydraDX](https://github.com/galacticcouncil/hack.HydraDX-node) - [Laminar Chain](https://github.com/laminar-protocol/laminar-chain) +- [Listen](https://github.com/listenofficial) - [Minterest](https://github.com/minterest-finance/minterest-chain-node) - [Plasm Network](https://github.com/PlasmNetwork) - [Setheum Network](https://github.com/Setheum-Labs/Setheum) - [Valiu Liquidity Network](https://github.com/valibre-org/vln-node) + From 53eccda448f45289da9b334a6651073b738b918b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aaro=20Per=C3=A4maa?= Date: Fri, 26 Mar 2021 22:29:54 +0200 Subject: [PATCH 18/49] Bump impl-trait-for-tuples to 0.2.1 (#424) --- traits/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/traits/Cargo.toml b/traits/Cargo.toml index 75c492365..99f411be7 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -14,7 +14,7 @@ sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } num-traits = { version = "0.2.14", default-features = false } -impl-trait-for-tuples = "0.1.3" +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 } From a62cf43ff7ba548600c2d2c36b1c662ff026e60a Mon Sep 17 00:00:00 2001 From: Xiliang Chen Date: Tue, 30 Mar 2021 21:36:08 +1300 Subject: [PATCH 19/49] update Cargo.toml (#429) --- Cargo.dev.toml | 2 ++ oracle/rpc/Cargo.toml | 4 +++- oracle/rpc/runtime-api/Cargo.toml | 2 ++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Cargo.dev.toml b/Cargo.dev.toml index 62df286d2..2b30f836e 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -8,6 +8,8 @@ members = [ "currencies", "gradually-update", "oracle", + "oracle/rpc", + "oracle/rpc/runtime-api", "tokens", "traits", "utilities", diff --git a/oracle/rpc/Cargo.toml b/oracle/rpc/Cargo.toml index 9ab71dbee..d64349197 100644 --- a/oracle/rpc/Cargo.toml +++ b/oracle/rpc/Cargo.toml @@ -3,6 +3,8 @@ name = "orml-oracle-rpc" version = "0.4.1-dev" authors = ["Laminar Developers "] edition = "2018" +license = "Apache-2.0" +description = "RPC module for orml-oracle." [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0" } @@ -13,6 +15,6 @@ sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo sp-api = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } -orml-oracle-rpc-runtime-api = { path = "runtime-api" } +orml-oracle-rpc-runtime-api = { path = "runtime-api", version = "0.4.1-dev" } funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 diff --git a/oracle/rpc/runtime-api/Cargo.toml b/oracle/rpc/runtime-api/Cargo.toml index 3003f32f8..19edb53a2 100644 --- a/oracle/rpc/runtime-api/Cargo.toml +++ b/oracle/rpc/runtime-api/Cargo.toml @@ -3,6 +3,8 @@ name = "orml-oracle-rpc-runtime-api" version = "0.4.1-dev" authors = ["Laminar Developers "] edition = "2018" +license = "Apache-2.0" +description = "Runtime API module for orml-oracle-rpc." [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } From db10cfda77388524b6b30faa7300b165c740e6d4 Mon Sep 17 00:00:00 2001 From: Xiliang Chen Date: Thu, 1 Apr 2021 16:15:32 +1300 Subject: [PATCH 20/49] 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 21/49] 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 22/49] 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 23/49] 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 24/49] 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 25/49] 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 26/49] 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 27/49] 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 28/49] 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 29/49] 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 30/49] 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 31/49] 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 32/49] 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 bfb7b7253ee97b1a6cb2d5c7d7c8ceda5e17ea80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Nem=C4=8Dek?= <5887929+yangwao@users.noreply.github.com> Date: Sat, 17 Apr 2021 02:53:30 +0200 Subject: [PATCH 33/49] Added orml-nft to README.md, list in lexicographic order. (#453) --- README.md | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 852832c49..31e8b2774 100644 --- a/README.md +++ b/README.md @@ -7,27 +7,29 @@ The Open Runtime Module Library (ORML) is a community maintained collection of S ## Runtime Modules Overview -- [orml-traits](./traits) - - Shared traits including `BasicCurrency`, `MultiCurrency`, `Auction` and more. -- [orml-utilities](./utilities) - - Various utilities including `OrderSet`. -- [orml-tokens](./tokens) - - Fungible tokens module that implements `MultiCurrency` trait. +- [orml-auction](./auction) + - Auction module that implements `Auction` trait. - [orml-currencies](./currencies) - Provide `MultiCurrency` implementation using `pallet-balances` and `orml-tokens` module. +- [orml-gradually-update](./gradually-update) + - Provides way to adjust numeric parameter gradually over a period of time. +- [orml-nft](./nft) + - Non-fungible-token module provides basic functions to create and manager NFT(non fungible token) such as `create_class`, `transfer`, `mint`, `burn`, `destroy_class`. - [orml-oracle](./oracle) - - Oracle module that makes off-chain data available on-chain. -- [orml-auction](./auction) - - Auction module that implements `Auction` trait. + - Oracle module that makes off-chain data available on-chain. +- [orml-tokens](./tokens) + - Fungible tokens module that implements `MultiCurrency` trait. +- [orml-traits](./traits) + - Shared traits including `BasicCurrency`, `MultiCurrency`, `Auction` and more. +- [orml-utilities](./utilities) + - Various utilities including `OrderSet`. - [orml-vesting](./vesting) - - Provides scheduled balance locking mechanism, in a *graded vesting* way. -- [orml-gradually-update](./gradually-update) - - Provides way to adjust numeric parameter gradually over a period of time. -- [orml-xtokens](./xtokens) - - Provides way to do cross-chain assets transfer. - - [Step-by-Step guide](https://github.com/open-web3-stack/open-runtime-module-library/wiki/xtokens) to make XCM cross-chain fungible asset transfer available on your parachain + - Provides scheduled balance locking mechanism, in a *graded vesting* way. - [orml-xcm-support](./xcm-support) - - Provides traits, types, and implementations to support XCM integration. + - Provides traits, types, and implementations to support XCM integration. +- [orml-xtokens](./xtokens) + - Provides way to do cross-chain assets transfer. + - [Step-by-Step guide](https://github.com/open-web3-stack/open-runtime-module-library/wiki/xtokens) to make XCM cross-chain fungible asset transfer available on your parachain ## Example From be0229a9ff56674766a5c375246f515f5af2f193 Mon Sep 17 00:00:00 2001 From: Xiliang Chen Date: Mon, 19 Apr 2021 17:18:55 +1200 Subject: [PATCH 34/49] no longer need to pin funty (#455) * no longer need to pin funty * pin xcm-simulator version --- Cargo.dev.toml | 3 +++ auction/Cargo.toml | 2 -- authority/Cargo.toml | 2 -- benchmarking/Cargo.toml | 2 -- currencies/Cargo.toml | 2 -- gradually-update/Cargo.toml | 2 -- nft/Cargo.toml | 2 -- oracle/Cargo.toml | 2 -- oracle/rpc/Cargo.toml | 2 -- oracle/rpc/runtime-api/Cargo.toml | 2 -- rewards/Cargo.toml | 2 -- tokens/Cargo.toml | 2 -- traits/Cargo.toml | 2 -- utilities/Cargo.toml | 2 -- vesting/Cargo.toml | 2 -- 15 files changed, 3 insertions(+), 28 deletions(-) diff --git a/Cargo.dev.toml b/Cargo.dev.toml index b09dd6547..f19d8d328 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -87,3 +87,6 @@ polkadot-core-primitives = { git = "https://github.com/paritytech//polkadot", re 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" } + +[patch.'https://github.com/shaunxw/xcm-simulator'] +xcm-simulator = { git = "https://github.com/shaunxw//xcm-simulator", rev = "c52bd64a41a51d08bd5a1e27f32c47419b41f3e5" } diff --git a/auction/Cargo.toml b/auction/Cargo.toml index 64d024a3d..ab367b80f 100644 --- a/auction/Cargo.toml +++ b/auction/Cargo.toml @@ -17,8 +17,6 @@ frame-support = { git = "https://github.com/paritytech/substrate", branch = "roc frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } diff --git a/authority/Cargo.toml b/authority/Cargo.toml index ecd262d0d..2debd0b50 100644 --- a/authority/Cargo.toml +++ b/authority/Cargo.toml @@ -19,8 +19,6 @@ frame-system = { git = "https://github.com/paritytech/substrate", branch = "roco orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [dev-dependencies] sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } diff --git a/benchmarking/Cargo.toml b/benchmarking/Cargo.toml index 5727669c6..1c72472a1 100644 --- a/benchmarking/Cargo.toml +++ b/benchmarking/Cargo.toml @@ -20,8 +20,6 @@ frame-support = { git = "https://github.com/paritytech/substrate", branch = "roc frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [dev-dependencies] hex-literal = "0.2.1" diff --git a/currencies/Cargo.toml b/currencies/Cargo.toml index a58fd4cf8..da5f2e0b4 100644 --- a/currencies/Cargo.toml +++ b/currencies/Cargo.toml @@ -20,8 +20,6 @@ frame-system = { git = "https://github.com/paritytech/substrate", branch = "roco orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } orml-utilities = { path = "../utilities", version = "0.4.1-dev", default-features = false } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } diff --git a/gradually-update/Cargo.toml b/gradually-update/Cargo.toml index 1bde0d610..b9d11b63b 100644 --- a/gradually-update/Cargo.toml +++ b/gradually-update/Cargo.toml @@ -17,8 +17,6 @@ sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [features] default = ["std"] std = [ diff --git a/nft/Cargo.toml b/nft/Cargo.toml index 35f1b3cee..6866cac4b 100644 --- a/nft/Cargo.toml +++ b/nft/Cargo.toml @@ -20,8 +20,6 @@ frame-system = { git = "https://github.com/paritytech/substrate", branch = "roco sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [features] default = ["std"] std = [ diff --git a/oracle/Cargo.toml b/oracle/Cargo.toml index 54e7bde93..5ba51042e 100644 --- a/oracle/Cargo.toml +++ b/oracle/Cargo.toml @@ -21,8 +21,6 @@ frame-system = { git = "https://github.com/paritytech/substrate", branch = "roco orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } orml-utilities = { path = "../utilities", version = "0.4.1-dev", default-features = false } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/oracle/rpc/Cargo.toml b/oracle/rpc/Cargo.toml index d64349197..c27a5d01c 100644 --- a/oracle/rpc/Cargo.toml +++ b/oracle/rpc/Cargo.toml @@ -16,5 +16,3 @@ sp-api = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } orml-oracle-rpc-runtime-api = { path = "runtime-api", version = "0.4.1-dev" } - -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 diff --git a/oracle/rpc/runtime-api/Cargo.toml b/oracle/rpc/runtime-api/Cargo.toml index 19edb53a2..5976c9233 100644 --- a/oracle/rpc/runtime-api/Cargo.toml +++ b/oracle/rpc/runtime-api/Cargo.toml @@ -11,8 +11,6 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = sp-api = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [features] default = ["std"] std = [ diff --git a/rewards/Cargo.toml b/rewards/Cargo.toml index 674018a63..e329d4fee 100644 --- a/rewards/Cargo.toml +++ b/rewards/Cargo.toml @@ -17,8 +17,6 @@ frame-support = { git = "https://github.com/paritytech/substrate", branch = "roc frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } diff --git a/tokens/Cargo.toml b/tokens/Cargo.toml index 735420dd3..2f86a11ad 100644 --- a/tokens/Cargo.toml +++ b/tokens/Cargo.toml @@ -16,8 +16,6 @@ frame-support = { git = "https://github.com/paritytech/substrate", branch = "ro frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [dev-dependencies] sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } diff --git a/traits/Cargo.toml b/traits/Cargo.toml index 2c92c0f16..bf3b3ddf4 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -19,8 +19,6 @@ frame-support = { git = "https://github.com/paritytech/substrate", branch = "roc 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 - [features] default = ["std"] std = [ diff --git a/utilities/Cargo.toml b/utilities/Cargo.toml index 4b505a7a6..1d8806bab 100644 --- a/utilities/Cargo.toml +++ b/utilities/Cargo.toml @@ -15,8 +15,6 @@ sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [dev-dependencies] serde_json = "1.0.64" frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } diff --git a/vesting/Cargo.toml b/vesting/Cargo.toml index 064519e91..bd241011a 100644 --- a/vesting/Cargo.toml +++ b/vesting/Cargo.toml @@ -17,8 +17,6 @@ sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } -funty = { version = "=1.1.0", default-features = false } # https://github.com/bitvecto-rs/bitvec/issues/105 - [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } From b9d5087d042fb3848a255852cc3ed18e9b733b89 Mon Sep 17 00:00:00 2001 From: Bryan Chen Date: Mon, 19 Apr 2021 21:37:19 +1200 Subject: [PATCH 35/49] disable cargo unleash check --- .github/workflows/{master.yml => master.yml.disabled} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/workflows/{master.yml => master.yml.disabled} (100%) diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml.disabled similarity index 100% rename from .github/workflows/master.yml rename to .github/workflows/master.yml.disabled From ae67850c7b48afeb521ab0b6f25d2cd73639fede Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Tue, 20 Apr 2021 16:19:22 +1200 Subject: [PATCH 36/49] Use idiomatic 'Pallet' struct decl. (#457) --- auction/src/lib.rs | 2 +- authority/src/lib.rs | 2 +- currencies/src/lib.rs | 2 +- gradually-update/src/lib.rs | 2 +- nft/src/lib.rs | 2 +- rewards/src/lib.rs | 2 +- tokens/src/lib.rs | 2 +- vesting/src/lib.rs | 2 +- xtokens/src/lib.rs | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/auction/src/lib.rs b/auction/src/lib.rs index 53b40f31c..184fc4259 100644 --- a/auction/src/lib.rs +++ b/auction/src/lib.rs @@ -95,7 +95,7 @@ pub mod module { StorageDoubleMap<_, Twox64Concat, T::BlockNumber, Blake2_128Concat, T::AuctionId, (), OptionQuery>; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::hooks] impl Hooks for Pallet { diff --git a/authority/src/lib.rs b/authority/src/lib.rs index 6481a2c01..9ee84333b 100644 --- a/authority/src/lib.rs +++ b/authority/src/lib.rs @@ -202,7 +202,7 @@ pub mod module { pub type NextTaskIndex = StorageValue<_, ScheduleTaskIndex, ValueQuery>; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::hooks] impl Hooks for Pallet {} diff --git a/currencies/src/lib.rs b/currencies/src/lib.rs index adf09dfd2..29159df0d 100644 --- a/currencies/src/lib.rs +++ b/currencies/src/lib.rs @@ -132,7 +132,7 @@ pub mod module { } #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::hooks] impl Hooks for Pallet {} diff --git a/gradually-update/src/lib.rs b/gradually-update/src/lib.rs index 2167fe187..9479e766e 100644 --- a/gradually-update/src/lib.rs +++ b/gradually-update/src/lib.rs @@ -112,7 +112,7 @@ pub mod module { pub(crate) type LastUpdatedAt = StorageValue<_, T::BlockNumber, ValueQuery>; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::hooks] impl Hooks for Pallet { diff --git a/nft/src/lib.rs b/nft/src/lib.rs index 19110231b..ba6b831ef 100644 --- a/nft/src/lib.rs +++ b/nft/src/lib.rs @@ -168,7 +168,7 @@ pub mod module { } #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::hooks] impl Hooks for Pallet {} diff --git a/rewards/src/lib.rs b/rewards/src/lib.rs index 55be0d164..cd2acfb11 100644 --- a/rewards/src/lib.rs +++ b/rewards/src/lib.rs @@ -78,7 +78,7 @@ pub mod module { StorageDoubleMap<_, Twox64Concat, T::PoolId, Twox64Concat, T::AccountId, (T::Share, T::Balance), ValueQuery>; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::hooks] impl Hooks for Pallet {} diff --git a/tokens/src/lib.rs b/tokens/src/lib.rs index 6c1202fca..4cb1f8a02 100644 --- a/tokens/src/lib.rs +++ b/tokens/src/lib.rs @@ -298,7 +298,7 @@ pub mod module { } #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::hooks] impl Hooks for Pallet {} diff --git a/vesting/src/lib.rs b/vesting/src/lib.rs index b913d0516..bfce0556b 100644 --- a/vesting/src/lib.rs +++ b/vesting/src/lib.rs @@ -216,7 +216,7 @@ pub mod module { } #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::hooks] impl Hooks for Pallet {} diff --git a/xtokens/src/lib.rs b/xtokens/src/lib.rs index 7df979629..c98981145 100644 --- a/xtokens/src/lib.rs +++ b/xtokens/src/lib.rs @@ -105,7 +105,7 @@ pub mod module { impl Hooks for Pallet {} #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::call] impl Pallet { From b63b6667a0809165bda20ba57cbe85e1c0687b8c Mon Sep 17 00:00:00 2001 From: Shumo Chu Date: Tue, 20 Apr 2021 20:00:49 -0700 Subject: [PATCH 37/49] Add Manta Network (#439) Add manta network to the list of orml users. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 31e8b2774..126fddb04 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ _In alphabetical order_ - [HydraDX](https://github.com/galacticcouncil/hack.HydraDX-node) - [Laminar Chain](https://github.com/laminar-protocol/laminar-chain) - [Listen](https://github.com/listenofficial) +- [Manta Network](https://github.com/Manta-Network) - [Minterest](https://github.com/minterest-finance/minterest-chain-node) - [Plasm Network](https://github.com/PlasmNetwork) - [Setheum Network](https://github.com/Setheum-Labs/Setheum) From ffe1601fa97cebaefcbc4bc4793aeb2bcd17e515 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Wed, 28 Apr 2021 14:30:31 +1200 Subject: [PATCH 38/49] Speed up incremental build. (#465) --- Cargo.dev.toml | 3 +++ tokens/Cargo.toml | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Cargo.dev.toml b/Cargo.dev.toml index f19d8d328..768282f89 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -23,6 +23,9 @@ members = [ ] resolver = "2" +[profile.dev] +split-debuginfo = "unpacked" + [patch.'https://github.com/paritytech/substrate'] frame-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } frame-support = { git = "https://github.com/paritytech//substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } diff --git a/tokens/Cargo.toml b/tokens/Cargo.toml index 2f86a11ad..6c4b86fda 100644 --- a/tokens/Cargo.toml +++ b/tokens/Cargo.toml @@ -20,7 +20,9 @@ orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = fa sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } pallet-treasury = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } -pallet-elections-phragmen = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } +# Patch doesn't work as `pallet-elections-phragmen` is now 4.0.0 version. Revert `rev` to `rococo-v1` branch after +# other `rococo-v1` dependencies upgraded. +pallet-elections-phragmen = { git = "https://github.com/paritytech/substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } [features] default = ["std"] From 5f74630d0742b12a3bd363d1634b877ba61d773b Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Wed, 28 Apr 2021 17:27:20 +1200 Subject: [PATCH 39/49] Use 'select_nth_unstable' to get median. (#467) * Use 'select_nth_unstable' to get median. * fix * Update comments doc. --- oracle/src/default_combine_data.rs | 10 +++++----- traits/src/data_provider.rs | 7 +++---- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/oracle/src/default_combine_data.rs b/oracle/src/default_combine_data.rs index 4f096cfff..d8c3f080c 100644 --- a/oracle/src/default_combine_data.rs +++ b/oracle/src/default_combine_data.rs @@ -27,13 +27,13 @@ where let count = values.len() as u32; let minimum_count = MinimumCount::get(); - if count < minimum_count { + if count < minimum_count || count == 0 { return prev_value; } - values.sort_by(|a, b| a.value.cmp(&b.value)); - - let median_index = count / 2; - Some(values[median_index as usize].clone()) + let mid_index = count / 2; + // Won't panic as `values` ensured not empty. + let (_, value, _) = values.select_nth_unstable_by(mid_index as usize, |a, b| a.value.cmp(&b.value)); + Some(value.clone()) } } diff --git a/traits/src/data_provider.rs b/traits/src/data_provider.rs index 4b3483df3..650d3982c 100644 --- a/traits/src/data_provider.rs +++ b/traits/src/data_provider.rs @@ -30,10 +30,9 @@ pub fn median(mut items: Vec) -> Option { let mid_index = items.len() / 2; - items.sort(); - - // Won't panic as guarded items not empty case. - Some(items[mid_index as usize].clone()) + // Won't panic as `items` ensured not empty. + let (_, item, _) = items.select_nth_unstable(mid_index); + Some(item.clone()) } #[macro_export] From 693651c1e961ae9e34f140c3d70817816d7365ee Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Thu, 29 Apr 2021 18:17:39 +1200 Subject: [PATCH 40/49] Bump rococo-v1 dependencies (#468) * Bump dependencies. * fix * Update run script. --- Cargo.dev.toml | 132 ++++++++++++++++++++++----------------------- scripts/run.sh | 4 ++ tokens/Cargo.toml | 2 +- tokens/src/mock.rs | 4 +- 4 files changed, 73 insertions(+), 69 deletions(-) diff --git a/Cargo.dev.toml b/Cargo.dev.toml index 768282f89..e9b842bd1 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -16,9 +16,9 @@ members = [ "vesting", "rewards", "nft", - "xtokens", - "xcm-support", - "unknown-tokens", + # "xtokens", + # "xcm-support", + # "unknown-tokens", "build-script-utils", ] resolver = "2" @@ -27,69 +27,69 @@ resolver = "2" split-debuginfo = "unpacked" [patch.'https://github.com/paritytech/substrate'] -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" } +frame-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +frame-support = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +frame-system = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +pallet-balances = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +pallet-elections-phragmen = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +pallet-scheduler = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +pallet-treasury = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +pallet-authorship = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +pallet-vesting = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +pallet-timestamp = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +pallet-session = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +pallet-staking = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +pallet-offences = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +pallet-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-api = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-application-crypto = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-arithmetic = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-core = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-inherents = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-io = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-runtime = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-runtime-interface = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-std = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-trie = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-version = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-externalities = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-state-machine = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-wasm-interface = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-keystore = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-staking = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-storage = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-panic-handler = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-npos-elections = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-npos-elections-compact = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-debug-derive = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-allocator = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sc-executor-common = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sc-executor-wasmi = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sc-executor = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sc-client-api = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-tasks = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-authorship = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-consensus = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-timestamp = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-session = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-blockchain = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } +sp-transaction-pool = { git = "https://github.com/paritytech//substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } -[patch.'https://github.com/paritytech/cumulus'] -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/cumulus'] +# cumulus-primitives-core = { git = "https://github.com/paritytech//cumulus", rev = "da4c3bac6e9584e65740ef5db4dbd2c31c1a91db" } +# cumulus-pallet-parachain-system = { git = "https://github.com/paritytech//cumulus", rev = "da4c3bac6e9584e65740ef5db4dbd2c31c1a91db" } +# parachain-info = { git = "https://github.com/paritytech//cumulus", rev = "da4c3bac6e9584e65740ef5db4dbd2c31c1a91db" } +# cumulus-pallet-xcm-handler = { git = "https://github.com/paritytech//cumulus", rev = "da4c3bac6e9584e65740ef5db4dbd2c31c1a91db" } -[patch.'https://github.com/paritytech/polkadot'] -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" } +# [patch.'https://github.com/paritytech/polkadot'] +# xcm = { git = "https://github.com/paritytech//polkadot", rev = "127eb17a25bbe2a9f2731ff11a65d7f8170f2373" } +# xcm-executor = { git = "https://github.com/paritytech//polkadot", rev = "127eb17a25bbe2a9f2731ff11a65d7f8170f2373" } +# xcm-builder = { git = "https://github.com/paritytech//polkadot", rev = "127eb17a25bbe2a9f2731ff11a65d7f8170f2373" } +# polkadot-core-primitives = { git = "https://github.com/paritytech//polkadot", rev = "127eb17a25bbe2a9f2731ff11a65d7f8170f2373" } +# polkadot-runtime-parachains = { git = "https://github.com/paritytech//polkadot", rev = "127eb17a25bbe2a9f2731ff11a65d7f8170f2373" } +# polkadot-parachain = { git = "https://github.com/paritytech//polkadot", rev = "127eb17a25bbe2a9f2731ff11a65d7f8170f2373" } +# polkadot-primitives = { git = "https://github.com/paritytech//polkadot", rev = "127eb17a25bbe2a9f2731ff11a65d7f8170f2373" } -[patch.'https://github.com/shaunxw/xcm-simulator'] -xcm-simulator = { git = "https://github.com/shaunxw//xcm-simulator", rev = "c52bd64a41a51d08bd5a1e27f32c47419b41f3e5" } +# [patch.'https://github.com/shaunxw/xcm-simulator'] +# xcm-simulator = { git = "https://github.com/shaunxw//xcm-simulator", rev = "c52bd64a41a51d08bd5a1e27f32c47419b41f3e5" } diff --git a/scripts/run.sh b/scripts/run.sh index 1e5a5b3e7..fd8cc73ec 100755 --- a/scripts/run.sh +++ b/scripts/run.sh @@ -8,6 +8,10 @@ shift set -x for file in **/Cargo.toml; do + if [ "$file" == "xtokens/Cargo.toml" ] || [ "$file" == "xcm-support/Cargo.toml" ] || [ "$file" == "unknown-tokens/Cargo.toml" ] + then + continue + fi cargo $COMMAND --manifest-path "$file" $@; done diff --git a/tokens/Cargo.toml b/tokens/Cargo.toml index 6c4b86fda..ba4b68433 100644 --- a/tokens/Cargo.toml +++ b/tokens/Cargo.toml @@ -22,7 +22,7 @@ sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1 pallet-treasury = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } # Patch doesn't work as `pallet-elections-phragmen` is now 4.0.0 version. Revert `rev` to `rococo-v1` branch after # other `rococo-v1` dependencies upgraded. -pallet-elections-phragmen = { git = "https://github.com/paritytech/substrate", rev = "816ed3d4e77a2463c86e69ec5a26fc307ef452b9" } +pallet-elections-phragmen = { git = "https://github.com/paritytech/substrate", rev = "2be8fcc4236d32786c62f6f27a98e7fe7e550807" } [features] default = ["std"] diff --git a/tokens/src/mock.rs b/tokens/src/mock.rs index c83901dae..85229a717 100644 --- a/tokens/src/mock.rs +++ b/tokens/src/mock.rs @@ -5,7 +5,7 @@ use super::*; use frame_support::{ construct_runtime, parameter_types, - traits::{ChangeMembers, Contains, ContainsLengthBound, SaturatingCurrencyToVote}, + traits::{ChangeMembers, ContainsLengthBound, SaturatingCurrencyToVote, SortedMembers}, }; use orml_traits::parameter_type_with_key; use sp_core::H256; @@ -68,7 +68,7 @@ thread_local! { } pub struct TenToFourteen; -impl Contains for TenToFourteen { +impl SortedMembers for TenToFourteen { fn sorted_members() -> Vec { TEN_TO_FOURTEEN.with(|v| v.borrow().clone()) } From f6ecabf7cc3eecf42f2e3f89bf6edd6b0d330ca3 Mon Sep 17 00:00:00 2001 From: Xiliang Chen Date: Fri, 30 Apr 2021 11:30:23 +1200 Subject: [PATCH 41/49] add whitelist_account (#464) --- benchmarking/src/lib.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/benchmarking/src/lib.rs b/benchmarking/src/lib.rs index 0755894cd..4777a2a9f 100644 --- a/benchmarking/src/lib.rs +++ b/benchmarking/src/lib.rs @@ -1139,3 +1139,12 @@ macro_rules! add_benchmark { } ) } + +#[macro_export] +macro_rules! whitelist_account { + ($acc:ident) => { + frame_benchmarking::benchmarking::add_to_whitelist( + frame_system::Account::::hashed_key_for(&$acc).into(), + ); + }; +} From 45d55b7ea557d5ddb785e01a49ed2e131afbd690 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Fri, 30 Apr 2021 11:43:41 +1200 Subject: [PATCH 42/49] Remove common parameters from benchmarking. (#469) --- benchmarking/src/lib.rs | 131 ++------------------------------------ benchmarking/src/tests.rs | 11 +--- 2 files changed, 10 insertions(+), 132 deletions(-) diff --git a/benchmarking/src/lib.rs b/benchmarking/src/lib.rs index 4777a2a9f..0e52fa817 100644 --- a/benchmarking/src/lib.rs +++ b/benchmarking/src/lib.rs @@ -54,11 +54,6 @@ pub use sp_runtime::traits::Zero; /// for arbitrary expresions to be evaluated in a benchmark (including for /// example, `on_initialize`). /// -/// The macro allows for common parameters whose ranges and instancing -/// expressions may be drawn upon (or not) by each arm. Syntax is available to -/// allow for only the range to be drawn upon if desired, allowing an -/// alternative instancing expression to be given. -/// /// Note that the ranges are *inclusive* on both sides. This is in contrast to /// ranges in Rust which are left-inclusive right-exclusive. /// @@ -68,9 +63,6 @@ pub use sp_runtime::traits::Zero; /// between the two pre- and post- code blocks, but do not leak from the /// interior of any instancing expressions. /// -/// Any common parameters that are unused in an arm do not have their instancing -/// expressions evaluated. -/// /// Example: /// ```ignore /// use path_to_node_runtime::MyRuntime; @@ -87,21 +79,20 @@ pub use sp_runtime::traits::Zero; /// // size `l`, which we allow to be initialized as usual. /// foo { /// let caller = account::(b"caller", 0, benchmarks_seed); -/// let l = ...; +/// let l in 1 .. MAX_LENGTH => initialize_l(l); /// }: _(Origin::Signed(caller), vec![0u8; l]) /// /// // second dispatchable: bar; this is a root dispatchable and accepts a `u8` vector of size -/// // `l`. We don't want it pre-initialized like before so we override using the `=> ()` notation. +/// // `l`. /// // In this case, we explicitly name the call using `bar` instead of `_`. /// bar { -/// let l = _ .. _ => (); +/// let l in 1 .. MAX_LENGTH => initialize_l(l); /// }: bar(Origin::Root, vec![0u8; l]) /// /// // third dispatchable: baz; this is a user dispatchable. It isn't dependent on length like the /// // other two but has its own complexity `c` that needs setting up. It uses `caller` (in the /// // pre-instancing block) within the code block. This is only allowed in the param instancers -/// // of arms. Instancers of common params cannot optimistically draw upon hypothetical variables -/// // that the arm's pre-instancing code block might have declared. +/// // of arms. /// baz1 { /// let caller = account::(b"caller", 0, benchmarks_seed); /// let c = 0 .. 10 => setup_c(&caller, c); @@ -168,18 +159,12 @@ pub use sp_runtime::traits::Zero; macro_rules! runtime_benchmarks { ( { $runtime:ident, $pallet:ident } - _ { - $( - let $common:ident in $common_from:tt .. $common_to:expr => $common_instancer:expr; - )* - } $( $rest:tt )* ) => { $crate::benchmarks_iter!( { } $runtime $pallet - { $( { $common , $common_from , $common_to , $common_instancer } )* } ( ) ( ) $( $rest )* @@ -192,18 +177,12 @@ macro_rules! runtime_benchmarks { macro_rules! runtime_benchmarks_instance { ( { $runtime:ident, $pallet:ident, $instance:ident } - _ { - $( - let $common:ident in $common_from:tt .. $common_to:expr => $common_instancer:expr; - )* - } $( $rest:tt )* ) => { $crate::benchmarks_iter!( { $instance } $runtime $pallet - { $( { $common , $common_from , $common_to , $common_instancer } )* } ( ) ( ) $( $rest )* @@ -219,7 +198,6 @@ macro_rules! benchmarks_iter { { $( $instance:ident )? } $runtime:ident $pallet:ident - { $( $common:tt )* } ( $( $names:tt )* ) ( $( $names_extra:tt )* ) #[extra] @@ -230,7 +208,6 @@ macro_rules! benchmarks_iter { { $( $instance)? } $runtime $pallet - { $( $common )* } ( $( $names )* ) ( $( $names_extra )* $name ) $name @@ -242,7 +219,6 @@ macro_rules! benchmarks_iter { { $( $instance:ident )? } $runtime:ident $pallet:ident - { $( $common:tt )* } ( $( $names:tt )* ) // This contains $( $( { $instance } )? $name:ident )* ( $( $names_extra:tt )* ) $name:ident { $( $code:tt )* }: _ ( $origin:expr $( , $arg:expr )* ) @@ -253,7 +229,6 @@ macro_rules! benchmarks_iter { { $( $instance)? } $runtime $pallet - { $( $common )* } ( $( $names )* ) ( $( $names_extra )* ) $name { $( $code )* }: $name ( $origin $( , $arg )* ) @@ -266,7 +241,6 @@ macro_rules! benchmarks_iter { { $( $instance:ident )? } $runtime:ident $pallet:ident - { $( $common:tt )* } ( $( $names:tt )* ) ( $( $names_extra:tt )* ) $name:ident { $( $code:tt )* }: $dispatch:ident ( $origin:expr $( , $arg:expr )* ) @@ -277,7 +251,6 @@ macro_rules! benchmarks_iter { { $( $instance)? } $runtime $pallet - { $( $common )* } ( $( $names )* ) ( $( $names_extra )* ) $name { $( $code )* }: { @@ -297,7 +270,6 @@ macro_rules! benchmarks_iter { { $( $instance:ident )? } $runtime:ident $pallet:ident - { $( $common:tt )* } ( $( $names:tt )* ) ( $( $names_extra:tt )* ) $name:ident { $( $code:tt )* }: $eval:block @@ -309,7 +281,6 @@ macro_rules! benchmarks_iter { $name $runtime $pallet - { $( $common )* } { } { $eval } { $( $code )* } @@ -328,7 +299,6 @@ macro_rules! benchmarks_iter { { $( $instance)? } $runtime $pallet - { $( $common )* } ( $( $names )* { $( $instance )? } $name ) ( $( $names_extra )* ) $( $rest )* @@ -339,7 +309,6 @@ macro_rules! benchmarks_iter { { $( $instance:ident )? } $runtime:ident $pallet:ident - { $( $common:tt )* } ( $( $names:tt )* ) ( $( $names_extra:tt )* ) ) => { @@ -362,7 +331,6 @@ macro_rules! benchmarks_iter { { $( $instance:ident )? } $runtime:ident $pallet:ident - { $( $common:tt )* } ( $( $names:tt )* ) ( $( $names_extra:tt )* ) $name:ident { $( $code:tt )* }: _ ( $origin:expr $( , $arg:expr )* ) @@ -372,7 +340,6 @@ macro_rules! benchmarks_iter { { $( $instance)? } $runtime $pallet - { $( $common )* } ( $( $names )* ) ( $( $names_extra )* ) $name { $( $code )* }: _ ( $origin $( , $arg )* ) @@ -385,7 +352,6 @@ macro_rules! benchmarks_iter { { $( $instance:ident )? } $runtime:ident $pallet:ident - { $( $common:tt )* } ( $( $names:tt )* ) ( $( $names_extra:tt )* ) $name:ident { $( $code:tt )* }: $dispatch:ident ( $origin:expr $( , $arg:expr )* ) @@ -395,7 +361,6 @@ macro_rules! benchmarks_iter { { $( $instance)? } $runtime $pallet - { $( $common )* } ( $( $names )* ) ( $( $names_extra )* ) $name { $( $code )* }: $dispatch ( $origin $( , $arg )* ) @@ -408,7 +373,6 @@ macro_rules! benchmarks_iter { { $( $instance:ident )? } $runtime:ident $pallet:ident - { $( $common:tt )* } ( $( $names:tt )* ) ( $( $names_extra:tt )* ) $name:ident { $( $code:tt )* }: $eval:block @@ -418,7 +382,6 @@ macro_rules! benchmarks_iter { { $( $instance)? } $runtime $pallet - { $( $common )* } ( $( $names )* ) ( $( $names_extra )* ) $name { $( $code )* }: $eval @@ -437,7 +400,6 @@ macro_rules! benchmark_backend { $name:ident $runtime:ident $pallet:ident - { $( $common:tt )* } { $( PRE { $( $pre_parsed:tt )* } )* } { $eval:block } { @@ -451,7 +413,6 @@ macro_rules! benchmark_backend { $name $runtime $pallet - { $( $common )* } { $( PRE { $( $pre_parsed )* } )* PRE { $pre_id , $pre_ty , $pre_ex } @@ -466,7 +427,6 @@ macro_rules! benchmark_backend { $name:ident $runtime:ident $pallet:ident - { $( $common:tt )* } { $( $parsed:tt )* } { $eval:block } { @@ -480,7 +440,6 @@ macro_rules! benchmark_backend { $name $runtime $pallet - { $( $common )* } { $( $parsed )* PARAM { $param , $param_from , $param_to , $param_instancer } @@ -490,79 +449,12 @@ macro_rules! benchmark_backend { $postcode } }; - // mutation arm to look after defaulting to a common param - ( - { $( $instance:ident )? } - $name:ident - $runtime:ident - $pallet:ident - { $( { $common:ident , $common_from:tt , $common_to:expr , $common_instancer:expr } )* } - { $( $parsed:tt )* } - { $eval:block } - { - let $param:ident in ...; - $( $rest:tt )* - } - $postcode:block - ) => { - $crate::benchmark_backend! { - { $( $instance)? } - $name - $runtime - $pallet - { $( { $common , $common_from , $common_to , $common_instancer } )* } - { $( $parsed )* } - { $eval } - { - let $param - in ({ $( let $common = $common_from; )* $param }) - .. ({ $( let $common = $common_to; )* $param }) - => ({ $( let $common = || -> Result<(), &'static str> { $common_instancer ; Ok(()) }; )* $param()? }); - $( $rest )* - } - $postcode - } - }; - // mutation arm to look after defaulting only the range to common param - ( - { $( $instance:ident )? } - $name:ident - $runtime:ident - $pallet:ident - { $( { $common:ident , $common_from:tt , $common_to:expr , $common_instancer:expr } )* } - { $( $parsed:tt )* } - { $eval:block } - { - let $param:ident in _ .. _ => $param_instancer:expr ; - $( $rest:tt )* - } - $postcode:block - ) => { - $crate::benchmark_backend! { - { $( $instance)? } - $name - $runtime - $pallet - { $( { $common , $common_from , $common_to , $common_instancer } )* } - { $( $parsed )* } - { $eval } - { - let $param - in ({ $( let $common = $common_from; )* $param }) - .. ({ $( let $common = $common_to; )* $param }) - => $param_instancer ; - $( $rest )* - } - $postcode - } - }; // mutation arm to look after a single tt for param_from. ( { $( $instance:ident )? } $name:ident $runtime:ident $pallet:ident - { $( $common:tt )* } { $( $parsed:tt )* } { $eval:block } { @@ -576,7 +468,6 @@ macro_rules! benchmark_backend { $name $runtime $pallet - { $( $common )* } { $( $parsed )* } { $eval } { @@ -592,7 +483,6 @@ macro_rules! benchmark_backend { $name:ident $runtime:ident $pallet:ident - { $( $common:tt )* } { $( $parsed:tt )* } { $eval:block } { @@ -606,7 +496,6 @@ macro_rules! benchmark_backend { $name $runtime $pallet - { $( $common )* } { $( $parsed )* } { $eval } { @@ -622,7 +511,6 @@ macro_rules! benchmark_backend { $name:ident $runtime:ident $pallet:ident - { $( $common:tt )* } { $( $parsed:tt )* } { $eval:block } { @@ -636,7 +524,6 @@ macro_rules! benchmark_backend { $name $runtime $pallet - { $( $common )* } { $( $parsed )* } { $eval } { @@ -652,7 +539,6 @@ macro_rules! benchmark_backend { $name:ident $runtime:ident $pallet:ident - { $( { $common:ident , $common_from:tt , $common_to:expr , $common_instancer:expr } )* } { $( PRE { $pre_id:tt , $pre_ty:ty , $pre_ex:expr } )* $( PARAM { $param:ident , $param_from:expr , $param_to:expr , $param_instancer:expr } )* @@ -678,9 +564,6 @@ macro_rules! benchmark_backend { components: &[($crate::BenchmarkParameter, u32)], verify: bool ) -> Result Result<(), &'static str>>, &'static str> { - $( - let $common = $common_from; - )* $( // Prepare instance let $param = components.iter() @@ -1050,15 +933,15 @@ macro_rules! impl_benchmark_test { /// ``` /// /// The `whitelist` is a parameter you pass to control the DB read/write -/// tracking. We use a vector of [TrackedStorageKey], which is a simple struct -/// used to set if a key has been read or written to. +/// tracking. We use a vector of +/// [TrackedStorageKey](./struct.TrackedStorageKey.html), which is a simple +/// struct used to set if a key has been read or written to. /// /// For values that should be skipped entirely, we can just pass `key.into()`. /// For example: /// /// ``` /// use frame_benchmarking::TrackedStorageKey; -/// use hex_literal; /// let whitelist: Vec = vec![ /// // Block Number /// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), diff --git a/benchmarking/src/tests.rs b/benchmarking/src/tests.rs index 333a776cb..455b9f710 100644 --- a/benchmarking/src/tests.rs +++ b/benchmarking/src/tests.rs @@ -116,13 +116,8 @@ fn new_test_ext() -> sp_io::TestExternalities { runtime_benchmarks! { { Test, test } - _ { - // Define a common range for `b`. - let b in 1 .. 1000 => (); - } - set_value { - let b in ...; + let b in 1 .. 1000; let caller = account::("caller", 0, 0); }: _ (RawOrigin::Signed(caller), b.into()) verify { @@ -130,7 +125,7 @@ runtime_benchmarks! { } other_name { - let b in ...; + let b in 1 .. 1000; }: dummy (RawOrigin::None, b.into()) sort_vector { @@ -146,7 +141,7 @@ runtime_benchmarks! { } bad_origin { - let b in ...; + let b in 1 .. 1000; let caller = account::("caller", 0, 0); }: dummy (RawOrigin::Signed(caller), b.into()) From dcc83ae5b58f72bd8c2d32e0016e14c60cdd34c5 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Fri, 30 Apr 2021 16:01:29 +1200 Subject: [PATCH 43/49] More benchmarking update (#470) * Show benchmark debug info. * Use current crate dependencies. * Make clippy happy. --- benchmarking/Cargo.toml | 1 + benchmarking/src/lib.rs | 125 +++++++++++++++++++++++++++++----------- 2 files changed, 93 insertions(+), 33 deletions(-) diff --git a/benchmarking/Cargo.toml b/benchmarking/Cargo.toml index 1c72472a1..ea330ec35 100644 --- a/benchmarking/Cargo.toml +++ b/benchmarking/Cargo.toml @@ -16,6 +16,7 @@ sp-runtime-interface = { git = "https://github.com/paritytech/substrate", branch sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } +sp-storage = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/benchmarking/src/lib.rs b/benchmarking/src/lib.rs index 0e52fa817..e3b95c6e9 100644 --- a/benchmarking/src/lib.rs +++ b/benchmarking/src/lib.rs @@ -7,16 +7,22 @@ mod tests; pub use frame_benchmarking::{ benchmarking, whitelisted_caller, BenchmarkBatch, BenchmarkConfig, BenchmarkParameter, BenchmarkResults, - Benchmarking, BenchmarkingSetup, TrackedStorageKey, + Benchmarking, BenchmarkingSetup, }; #[cfg(feature = "std")] pub use frame_benchmarking::{Analysis, BenchmarkSelector}; +#[doc(hidden)] pub use frame_support; +#[doc(hidden)] pub use paste; #[doc(hidden)] pub use sp_io::storage::root as storage_root; +#[doc(hidden)] pub use sp_runtime::traits::Zero; - +#[doc(hidden)] +pub use sp_std::{self, boxed::Box, prelude::Vec, vec}; +#[doc(hidden)] +pub use sp_storage::TrackedStorageKey; /// Construct pallet benchmarks for weighing dispatchables. /// /// Works around the idea of complexity parameters, named by a single letter @@ -551,8 +557,8 @@ macro_rules! benchmark_backend { struct $name; #[allow(unused_variables)] impl $crate::BenchmarkingSetup<$runtime $(, $instance)?> for $name { - fn components(&self) -> Vec<($crate::BenchmarkParameter, u32, u32)> { - vec! [ + fn components(&self) -> $crate::Vec<($crate::BenchmarkParameter, u32, u32)> { + $crate::vec! [ $( ($crate::BenchmarkParameter::$param, $param_from, $param_to) ),* @@ -563,7 +569,7 @@ macro_rules! benchmark_backend { &self, components: &[($crate::BenchmarkParameter, u32)], verify: bool - ) -> Result Result<(), &'static str>>, &'static str> { + ) -> Result<$crate::Box Result<(), &'static str>>, &'static str> { $( // Prepare instance let $param = components.iter() @@ -577,7 +583,7 @@ macro_rules! benchmark_backend { $( $param_instancer ; )* $( $post )* - Ok(Box::new(move || -> Result<(), &'static str> { + Ok($crate::Box::new(move || -> Result<(), &'static str> { $eval; if verify { $postcode; @@ -620,7 +626,7 @@ macro_rules! selected_benchmark { // Allow us to select a benchmark from the list of available benchmarks. impl $crate::BenchmarkingSetup<$runtime $(, $instance)?> for SelectedBenchmark { - fn components(&self) -> Vec<($crate::BenchmarkParameter, u32, u32)> { + fn components(&self) -> $crate::Vec<($crate::BenchmarkParameter, u32, u32)> { match self { $( Self::$bench => < @@ -634,9 +640,7 @@ macro_rules! selected_benchmark { &self, components: &[($crate::BenchmarkParameter, u32)], verify: bool - ) - -> Result Result<(), &'static str>>, &'static str> - { + ) -> Result<$crate::Box Result<(), &'static str>>, &'static str> { match self { $( Self::$bench => < @@ -662,8 +666,8 @@ macro_rules! impl_benchmark { pub struct Benchmark; impl $crate::Benchmarking<$crate::BenchmarkResults> for Benchmark { - fn benchmarks(extra: bool) -> Vec<&'static [u8]> { - let mut all = vec![ $( stringify!($name).as_ref() ),* ]; + fn benchmarks(extra: bool) -> $crate::Vec<&'static [u8]> { + let mut all = $crate::vec![ $( stringify!($name).as_ref() ),* ]; if !extra { let extra = [ $( stringify!($name_extra).as_ref() ),* ]; all.retain(|x| !extra.contains(x)); @@ -679,15 +683,15 @@ macro_rules! impl_benchmark { repeat: u32, whitelist: &[$crate::TrackedStorageKey], verify: bool, - ) -> Result, &'static str> { + ) -> Result<$crate::Vec<$crate::BenchmarkResults>, &'static str> { // Map the input to the selected benchmark. - let extrinsic = sp_std::str::from_utf8(extrinsic) + let extrinsic = $crate::sp_std::str::from_utf8(extrinsic) .map_err(|_| "`extrinsic` is not a valid utf8 string!")?; let selected_benchmark = match extrinsic { $( stringify!($name) => SelectedBenchmark::$name, )* _ => return Err("Could not find extrinsic."), }; - let mut results: Vec<$crate::BenchmarkResults> = Vec::new(); + let mut results: $crate::Vec<$crate::BenchmarkResults> = $crate::Vec::new(); if repeat == 0 { return Ok(results); } @@ -695,7 +699,7 @@ macro_rules! impl_benchmark { // Add whitelist to DB including whitelisted caller let mut whitelist = whitelist.to_vec(); let whitelisted_caller_key = - as frame_support::storage::StorageMap<_,_>>::hashed_key_for( + as $crate::frame_support::storage::StorageMap<_,_>>::hashed_key_for( $crate::whitelisted_caller::<<$runtime as frame_system::Config>::AccountId>() ); whitelist.push(whitelisted_caller_key.into()); @@ -715,7 +719,7 @@ macro_rules! impl_benchmark { let repeat_benchmark = | repeat: u32, c: &[($crate::BenchmarkParameter, u32)], - results: &mut Vec<$crate::BenchmarkResults>, + results: &mut $crate::Vec<$crate::BenchmarkResults>, verify: bool, | -> Result<(), &'static str> { // Run the benchmark `repeat` times. @@ -742,7 +746,7 @@ macro_rules! impl_benchmark { closure_to_benchmark()?; } else { // Time the extrinsic logic. - frame_support::log::trace!( + $crate::frame_support::log::trace!( target: "benchmark", "Start Benchmark: {:?}", c ); @@ -764,12 +768,12 @@ macro_rules! impl_benchmark { // Commit the changes to get proper write count $crate::benchmarking::commit_db(); - frame_support::log::trace!( + $crate::frame_support::log::trace!( target: "benchmark", "End Benchmark: {} ns", elapsed_extrinsic ); let read_write_count = $crate::benchmarking::read_write_count(); - frame_support::log::trace!( + $crate::frame_support::log::trace!( target: "benchmark", "Read/Write Count {:?}", read_write_count ); @@ -802,7 +806,7 @@ macro_rules! impl_benchmark { if components.is_empty() { if verify { // If `--verify` is used, run the benchmark once to verify it would complete. - repeat_benchmark(1, Default::default(), &mut Vec::new(), true)?; + repeat_benchmark(1, Default::default(), &mut $crate::Vec::new(), true)?; } repeat_benchmark(repeat, Default::default(), &mut results, false)?; } else { @@ -829,7 +833,7 @@ macro_rules! impl_benchmark { let component_value = lowest + step_size * s; // Select the max value for all the other components. - let c: Vec<($crate::BenchmarkParameter, u32)> = components.iter() + let c: $crate::Vec<($crate::BenchmarkParameter, u32)> = components.iter() .enumerate() .map(|(idx, (n, _, h))| if n == name { @@ -842,7 +846,7 @@ macro_rules! impl_benchmark { if verify { // If `--verify` is used, run the benchmark once to verify it would complete. - repeat_benchmark(1, &c, &mut Vec::new(), true)?; + repeat_benchmark(1, &c, &mut $crate::Vec::new(), true)?; } repeat_benchmark(repeat, &c, &mut results, false)?; } @@ -875,7 +879,7 @@ macro_rules! impl_benchmark_test { >::components(&selected_benchmark); let execute_benchmark = | - c: Vec<($crate::BenchmarkParameter, u32)> + c: $crate::Vec<($crate::BenchmarkParameter, u32)> | -> Result<(), &'static str> { // Set up the benchmark, return execution + verification function. let closure_to_verify = < @@ -901,9 +905,9 @@ macro_rules! impl_benchmark_test { } else { for (_, (name, low, high)) in components.iter().enumerate() { // Test only the low and high value, assuming values in the middle won't break - for component_value in vec![low, high] { + for component_value in $crate::vec![low, high] { // Select the max value for all the other components. - let c: Vec<($crate::BenchmarkParameter, u32)> = components.iter() + let c: $crate::Vec<($crate::BenchmarkParameter, u32)> = components.iter() .enumerate() .map(|(_, (n, _, h))| if n == name { @@ -924,6 +928,39 @@ macro_rules! impl_benchmark_test { }; } +/// show error message and debugging info for the case of an error happening +/// during a benchmark +#[allow(clippy::too_many_arguments)] +pub fn show_benchmark_debug_info( + instance_string: &[u8], + benchmark: &[u8], + lowest_range_values: &[u32], + highest_range_values: &[u32], + steps: &[u32], + repeat: &u32, + verify: &bool, + error_message: &str, +) -> sp_runtime::RuntimeString { + sp_runtime::format_runtime_string!( + "\n* Pallet: {}\n\ + * Benchmark: {}\n\ + * Lowest_range_values: {:?}\n\ + * Highest_range_values: {:?}\n\ + * Steps: {:?}\n\ + * Repeat: {:?}\n\ + * Verify: {:?}\n\ + * Error message: {}", + sp_std::str::from_utf8(instance_string).expect("it's all just strings ran through the wasm interface. qed"), + sp_std::str::from_utf8(benchmark).expect("it's all just strings ran through the wasm interface. qed"), + lowest_range_values, + highest_range_values, + steps, + repeat, + verify, + error_message, + ) +} + /// This macro adds pallet benchmarks to a `Vec` object. /// /// First create an object that holds in the input parameters for the benchmark: @@ -989,7 +1026,9 @@ macro_rules! add_benchmark { if &pallet[..] == &b"*"[..] || &benchmark[..] == &b"*"[..] { for benchmark in $( $location )*::Benchmark::benchmarks(*extra).into_iter() { $batches.push($crate::BenchmarkBatch { + pallet: name_string.to_vec(), instance: instance_string.to_vec(), + benchmark: benchmark.to_vec(), results: $( $location )*::Benchmark::run_benchmark( benchmark, &lowest_range_values[..], @@ -998,14 +1037,25 @@ macro_rules! add_benchmark { *repeat, whitelist, *verify, - )?, - pallet: name_string.to_vec(), - benchmark: benchmark.to_vec(), - }); + ).map_err(|e| { + $crate::show_benchmark_debug_info( + instance_string, + benchmark, + lowest_range_values, + highest_range_values, + steps, + repeat, + verify, + e, + ) + })?, + }); } } else { $batches.push($crate::BenchmarkBatch { + pallet: name_string.to_vec(), instance: instance_string.to_vec(), + benchmark: benchmark.clone(), results: $( $location )*::Benchmark::run_benchmark( &benchmark[..], &lowest_range_values[..], @@ -1014,9 +1064,18 @@ macro_rules! add_benchmark { *repeat, whitelist, *verify, - )?, - pallet: name_string.to_vec(), - benchmark: benchmark.clone(), + ).map_err(|e| { + $crate::show_benchmark_debug_info( + instance_string, + benchmark, + lowest_range_values, + highest_range_values, + steps, + repeat, + verify, + e, + ) + })?, }); } } From 9f43dbf672b08625b0ea2fb6174dfa0661f8072d Mon Sep 17 00:00:00 2001 From: Xiliang Chen Date: Sun, 2 May 2021 16:59:15 +1200 Subject: [PATCH 44/49] rename MergeAccount to TransferAll (#472) * rename MergeAccount to TransferAll * fix --- currencies/src/lib.rs | 13 +++++-------- tokens/src/lib.rs | 15 ++++----------- tokens/src/tests.rs | 18 +++++++++--------- traits/src/account.rs | 19 ------------------- traits/src/currency.rs | 20 +++++++++++++++++++- traits/src/lib.rs | 1 - 6 files changed, 37 insertions(+), 49 deletions(-) delete mode 100644 traits/src/account.rs diff --git a/currencies/src/lib.rs b/currencies/src/lib.rs index 29159df0d..db2fd9d44 100644 --- a/currencies/src/lib.rs +++ b/currencies/src/lib.rs @@ -49,8 +49,8 @@ use frame_support::{ }; use frame_system::{ensure_root, ensure_signed, pallet_prelude::*}; use orml_traits::{ - account::MergeAccount, arithmetic::{Signed, SimpleArithmetic}, + currency::TransferAll, BalanceStatus, BasicCurrency, BasicCurrencyExtended, BasicLockableCurrency, BasicReservableCurrency, LockIdentifier, MultiCurrency, MultiCurrencyExtended, MultiLockableCurrency, MultiReservableCurrency, }; @@ -94,7 +94,7 @@ pub mod module { pub trait Config: frame_system::Config { type Event: From> + IsType<::Event>; - type MultiCurrency: MergeAccount + type MultiCurrency: TransferAll + MultiCurrencyExtended + MultiLockableCurrency + MultiReservableCurrency; @@ -685,14 +685,11 @@ where } } -impl MergeAccount for Pallet { - fn merge_account(source: &T::AccountId, dest: &T::AccountId) -> DispatchResult { +impl TransferAll for Pallet { + fn transfer_all(source: &T::AccountId, dest: &T::AccountId) -> DispatchResult { with_transaction_result(|| { // transfer non-native free to dest - T::MultiCurrency::merge_account(source, dest)?; - - // unreserve all reserved currency - T::NativeCurrency::unreserve(source, T::NativeCurrency::reserved_balance(source)); + T::MultiCurrency::transfer_all(source, dest)?; // transfer all free to dest T::NativeCurrency::transfer(source, dest, T::NativeCurrency::free_balance(source)) diff --git a/tokens/src/lib.rs b/tokens/src/lib.rs index 4cb1f8a02..f29e336b5 100644 --- a/tokens/src/lib.rs +++ b/tokens/src/lib.rs @@ -51,8 +51,8 @@ use frame_support::{ }; use frame_system::{ensure_signed, pallet_prelude::*}; use orml_traits::{ - account::MergeAccount, arithmetic::{self, Signed}, + currency::TransferAll, BalanceStatus, GetByKey, LockIdentifier, MultiCurrency, MultiCurrencyExtended, MultiLockableCurrency, MultiReservableCurrency, OnDust, }; @@ -198,8 +198,6 @@ pub mod module { AmountIntoBalanceFailed, /// Failed because liquidity restrictions due to locking LiquidityRestrictions, - /// Account still has active reserved - StillHasActiveReserved, } #[pallet::event] @@ -1042,16 +1040,11 @@ where } } -impl MergeAccount for Pallet { +impl TransferAll for Pallet { #[transactional] - fn merge_account(source: &T::AccountId, dest: &T::AccountId) -> DispatchResult { + fn transfer_all(source: &T::AccountId, dest: &T::AccountId) -> DispatchResult { Accounts::::iter_prefix(source).try_for_each(|(currency_id, account_data)| -> DispatchResult { - // ensure the account has no active reserved of non-native token - ensure!(account_data.reserved.is_zero(), Error::::StillHasActiveReserved); - - // transfer all free to recipient - >::transfer(currency_id, source, dest, account_data.free)?; - Ok(()) + >::transfer(currency_id, source, dest, account_data.free) }) } } diff --git a/tokens/src/tests.rs b/tokens/src/tests.rs index 1b2f04021..ff2c5cf02 100644 --- a/tokens/src/tests.rs +++ b/tokens/src/tests.rs @@ -431,7 +431,7 @@ fn no_op_if_amount_is_zero() { } #[test] -fn merge_account_should_work() { +fn transfer_all_trait_should_work() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (ALICE, BTC, 200)]) .build() @@ -440,18 +440,18 @@ fn merge_account_should_work() { assert_eq!(Tokens::free_balance(BTC, &ALICE), 200); assert_eq!(Tokens::free_balance(DOT, &BOB), 0); - assert_ok!(Tokens::reserve(DOT, &ALICE, 1)); - assert_noop!( - Tokens::merge_account(&ALICE, &BOB), - Error::::StillHasActiveReserved - ); - Tokens::unreserve(DOT, &ALICE, 1); - - assert_ok!(Tokens::merge_account(&ALICE, &BOB)); + assert_ok!(>::transfer_all(&ALICE, &BOB)); assert_eq!(Tokens::free_balance(DOT, &ALICE), 0); assert_eq!(Tokens::free_balance(BTC, &ALICE), 0); assert_eq!(Tokens::free_balance(DOT, &BOB), 100); assert_eq!(Tokens::free_balance(BTC, &BOB), 200); + + assert_ok!(Tokens::reserve(DOT, &BOB, 1)); + assert_ok!(>::transfer_all(&BOB, &ALICE)); + assert_eq!(Tokens::free_balance(DOT, &ALICE), 99); + assert_eq!(Tokens::free_balance(BTC, &ALICE), 200); + assert_eq!(Tokens::free_balance(DOT, &BOB), 0); + assert_eq!(Tokens::free_balance(BTC, &BOB), 0); }); } diff --git a/traits/src/account.rs b/traits/src/account.rs deleted file mode 100644 index f3c74c66d..000000000 --- a/traits/src/account.rs +++ /dev/null @@ -1,19 +0,0 @@ -use impl_trait_for_tuples::impl_for_tuples; -use orml_utilities::with_transaction_result; -use sp_runtime::DispatchResult; - -pub trait MergeAccount { - fn merge_account(source: &AccountId, dest: &AccountId) -> DispatchResult; -} - -#[impl_for_tuples(5)] -impl MergeAccount for Tuple { - fn merge_account(source: &AccountId, dest: &AccountId) -> DispatchResult { - with_transaction_result(|| { - for_tuples!( #( { - Tuple::merge_account(source, dest)?; - } )* ); - Ok(()) - }) - } -} diff --git a/traits/src/currency.rs b/traits/src/currency.rs index a7034d586..c104368ff 100644 --- a/traits/src/currency.rs +++ b/traits/src/currency.rs @@ -1,6 +1,9 @@ use crate::arithmetic; use codec::{Codec, FullCodec}; -pub use frame_support::traits::{BalanceStatus, LockIdentifier}; +pub use frame_support::{ + traits::{BalanceStatus, LockIdentifier}, + transactional, +}; use sp_runtime::{ traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize}, DispatchError, DispatchResult, @@ -341,3 +344,18 @@ pub trait OnDust { impl OnDust for () { fn on_dust(_: &AccountId, _: CurrencyId, _: Balance) {} } + +pub trait TransferAll { + fn transfer_all(source: &AccountId, dest: &AccountId) -> DispatchResult; +} + +#[impl_trait_for_tuples::impl_for_tuples(5)] +impl TransferAll for Tuple { + #[transactional] + fn transfer_all(source: &AccountId, dest: &AccountId) -> DispatchResult { + for_tuples!( #( { + Tuple::transfer_all(source, dest)?; + } )* ); + Ok(()) + } +} diff --git a/traits/src/lib.rs b/traits/src/lib.rs index a8962dbcf..7ec0efb4a 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -22,7 +22,6 @@ pub use nft::NFT; pub use price::{DefaultPriceProvider, PriceProvider}; pub use rewards::RewardHandler; -pub mod account; pub mod arithmetic; pub mod auction; pub mod currency; From d4298f3a3914cd7527b9f3c46b95ce1037eebafa Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Mon, 3 May 2021 13:53:34 +1200 Subject: [PATCH 45/49] Deps cleanup. (#473) * Deps cleanup. * fix --- authority/Cargo.toml | 3 --- benchmarking/Cargo.toml | 3 +-- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/authority/Cargo.toml b/authority/Cargo.toml index 2debd0b50..3a3a432df 100644 --- a/authority/Cargo.toml +++ b/authority/Cargo.toml @@ -17,8 +17,6 @@ sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } -orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } - [dev-dependencies] sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } @@ -33,7 +31,6 @@ std = [ "sp-std/std", "frame-support/std", "frame-system/std", - "orml-traits/std", ] runtime-benchmarks = [ "frame-support/runtime-benchmarks", diff --git a/benchmarking/Cargo.toml b/benchmarking/Cargo.toml index ea330ec35..cc20614b8 100644 --- a/benchmarking/Cargo.toml +++ b/benchmarking/Cargo.toml @@ -18,10 +18,10 @@ sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-storage = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } -frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } [dev-dependencies] +frame-system = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1" } hex-literal = "0.2.1" [features] @@ -34,7 +34,6 @@ std = [ "sp-api/std", "sp-std/std", "frame-support/std", - "frame-system/std", "frame-benchmarking/std", ] From fc3a222072664999a91b77ba5449d052c7b21d11 Mon Sep 17 00:00:00 2001 From: Xiliang Chen Date: Tue, 4 May 2021 14:51:36 +1200 Subject: [PATCH 46/49] update weights for auction & authority (#474) * update weights for auction & authority * update * update weight info for orml-currencies * oracle & tokens * update orml-vesting * rebenchmark everything --- Makefile | 14 +++++++ auction/src/default_weight.rs | 23 ----------- auction/src/lib.rs | 8 +--- auction/src/weights.rs | 53 ++++++++++++++++++++++++ authority/src/default_weight.rs | 44 -------------------- authority/src/lib.rs | 13 ++---- authority/src/weights.rs | 71 +++++++++++++++++++++++++++++++++ currencies/src/lib.rs | 11 +---- currencies/src/weights.rs | 67 +++++++++++++++++++++++++++++++ oracle/src/lib.rs | 8 +--- oracle/src/weights.rs | 51 +++++++++++++++++++++++ tokens/src/default_weight.rs | 20 ---------- tokens/src/lib.rs | 9 ++--- tokens/src/weights.rs | 49 +++++++++++++++++++++++ vesting/src/lib.rs | 9 +---- vesting/src/weights.rs | 59 +++++++++++++++++++++++++++ 16 files changed, 378 insertions(+), 131 deletions(-) delete mode 100644 auction/src/default_weight.rs create mode 100644 auction/src/weights.rs delete mode 100644 authority/src/default_weight.rs create mode 100644 authority/src/weights.rs create mode 100644 currencies/src/weights.rs create mode 100644 oracle/src/weights.rs delete mode 100644 tokens/src/default_weight.rs create mode 100644 tokens/src/weights.rs create mode 100644 vesting/src/weights.rs diff --git a/Makefile b/Makefile index 0583cd27d..51dfe8fe8 100644 --- a/Makefile +++ b/Makefile @@ -47,3 +47,17 @@ dev-check-tests: Cargo.toml dev-test: Cargo.toml cargo test --all --features runtime-benchmarks + +# run benchmarks via Acala node +benchmark-all: + cargo run --release --bin=acala --features=runtime-benchmarks -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=orml_auction --extrinsic="*" --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./auction/src/weights.rs --template ../templates/orml-weight-template.hbs + + cargo run --release --bin=acala --features=runtime-benchmarks -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=orml_authority --extrinsic="*" --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./authority/src/weights.rs --template ../templates/orml-weight-template.hbs + + cargo run --release --bin=acala --features=runtime-benchmarks -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=module_currencies --extrinsic="*" --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./currencies/src/weights.rs --template ../templates/orml-weight-template.hbs + + cargo run --release --bin=acala --features=runtime-benchmarks -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=orml_oracle --extrinsic="*" --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./oracle/src/weights.rs --template ../templates/orml-weight-template.hbs + + cargo run --release --bin=acala --features=runtime-benchmarks -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=orml_tokens --extrinsic="*" --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./tokens/src/weights.rs --template ../templates/orml-weight-template.hbs + + cargo run --release --bin=acala --features=runtime-benchmarks -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=orml_vesting --extrinsic="*" --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./vesting/src/weights.rs --template ../templates/orml-weight-template.hbs diff --git a/auction/src/default_weight.rs b/auction/src/default_weight.rs deleted file mode 100644 index 26e552fef..000000000 --- a/auction/src/default_weight.rs +++ /dev/null @@ -1,23 +0,0 @@ -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 2.0.0 - -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::weights::{constants::RocksDbWeight as DbWeight, Weight}; - -impl crate::WeightInfo for () { - fn bid_collateral_auction() -> Weight { - (493_957_000 as Weight) - .saturating_add(DbWeight::get().reads(12 as Weight)) - .saturating_add(DbWeight::get().writes(12 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)) - .saturating_add(DbWeight::get().reads(3 as Weight)) - .saturating_add(DbWeight::get().reads((4 as Weight).saturating_mul(c as Weight))) - .saturating_add(DbWeight::get().writes(2 as Weight)) - .saturating_add(DbWeight::get().writes((3 as Weight).saturating_mul(c as Weight))) - } -} diff --git a/auction/src/lib.rs b/auction/src/lib.rs index 184fc4259..69aefa886 100644 --- a/auction/src/lib.rs +++ b/auction/src/lib.rs @@ -21,21 +21,17 @@ use sp_runtime::{ DispatchError, DispatchResult, }; -mod default_weight; mod mock; mod tests; +mod weights; pub use module::*; +pub use weights::WeightInfo; #[frame_support::pallet] pub mod module { use super::*; - pub trait WeightInfo { - fn bid_collateral_auction() -> Weight; - fn on_finalize(c: u32) -> Weight; - } - #[pallet::config] pub trait Config: frame_system::Config { type Event: From> + IsType<::Event>; diff --git a/auction/src/weights.rs b/auction/src/weights.rs new file mode 100644 index 000000000..9dcb4f32d --- /dev/null +++ b/auction/src/weights.rs @@ -0,0 +1,53 @@ +//! Autogenerated weights for orml_auction +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 +//! DATE: 2021-05-04, STEPS: [50, ], REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 + +// Executed Command: +// /Users/xiliangchen/projects/acala/target/release/acala +// benchmark +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=orml_auction +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./auction/src/weights.rs +// --template +// ../templates/orml-weight-template.hbs + + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(clippy::unnecessary_cast)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for orml_auction. +pub trait WeightInfo { + fn bid_collateral_auction() -> Weight; + fn on_finalize(c: u32, ) -> Weight; +} + +/// Default weights. +impl WeightInfo for () { + fn bid_collateral_auction() -> Weight { + (108_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(8 as Weight)) + .saturating_add(RocksDbWeight::get().writes(9 as Weight)) + } + fn on_finalize(c: u32, ) -> Weight { + (9_779_000 as Weight) + // Standard Error: 13_000 + .saturating_add((57_962_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(10 as Weight)) + .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(c as Weight))) + .saturating_add(RocksDbWeight::get().writes(7 as Weight)) + .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(c as Weight))) + } +} diff --git a/authority/src/default_weight.rs b/authority/src/default_weight.rs deleted file mode 100644 index 802a567bb..000000000 --- a/authority/src/default_weight.rs +++ /dev/null @@ -1,44 +0,0 @@ -//! Weights for orml_authority -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 2.0.0 -//! DATE: 2020-11-18, STEPS: [1, ], REPEAT: 1, LOW RANGE: [], HIGH RANGE: [] -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB -//! CACHE: 128 - -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::weights::{constants::RocksDbWeight as DbWeight, Weight}; -use sp_std::marker::PhantomData; - -/// Weight functions for orml_authority. -impl crate::WeightInfo for () { - fn dispatch_as() -> Weight { - (48_680_000 as Weight) - } - fn schedule_dispatch_without_delay() -> Weight { - (121_510_000 as Weight) - .saturating_add(DbWeight::get().reads(3 as Weight)) - .saturating_add(DbWeight::get().writes(3 as Weight)) - } - fn schedule_dispatch_with_delay() -> Weight { - (130_696_000 as Weight) - .saturating_add(DbWeight::get().reads(3 as Weight)) - .saturating_add(DbWeight::get().writes(3 as Weight)) - } - fn fast_track_scheduled_dispatch() -> Weight { - (145_530_000 as Weight) - .saturating_add(DbWeight::get().reads(3 as Weight)) - .saturating_add(DbWeight::get().writes(3 as Weight)) - } - fn delay_scheduled_dispatch() -> Weight { - (145_169_000 as Weight) - .saturating_add(DbWeight::get().reads(3 as Weight)) - .saturating_add(DbWeight::get().writes(3 as Weight)) - } - fn cancel_scheduled_dispatch() -> Weight { - (104_990_000 as Weight) - .saturating_add(DbWeight::get().reads(2 as Weight)) - .saturating_add(DbWeight::get().writes(2 as Weight)) - } -} diff --git a/authority/src/lib.rs b/authority/src/lib.rs index 9ee84333b..ef4aec224 100644 --- a/authority/src/lib.rs +++ b/authority/src/lib.rs @@ -35,9 +35,11 @@ use sp_runtime::{ }; use sp_std::prelude::*; -mod default_weight; mod mock; mod tests; +mod weights; + +pub use weights::WeightInfo; /// A delayed origin. Can only be dispatched via `dispatch_as` with a delay. #[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode)] @@ -120,15 +122,6 @@ pub use module::*; pub mod module { use super::*; - pub trait WeightInfo { - fn dispatch_as() -> Weight; - fn schedule_dispatch_without_delay() -> Weight; - fn schedule_dispatch_with_delay() -> Weight; - fn fast_track_scheduled_dispatch() -> Weight; - fn delay_scheduled_dispatch() -> Weight; - fn cancel_scheduled_dispatch() -> Weight; - } - /// Origin for the authority module. pub type Origin = DelayedOrigin<::BlockNumber, ::PalletsOrigin>; pub(crate) type CallOf = ::Call; diff --git a/authority/src/weights.rs b/authority/src/weights.rs new file mode 100644 index 000000000..59c1354f1 --- /dev/null +++ b/authority/src/weights.rs @@ -0,0 +1,71 @@ +//! Autogenerated weights for orml_authority +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 +//! DATE: 2021-05-04, STEPS: [50, ], REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 + +// Executed Command: +// /Users/xiliangchen/projects/acala/target/release/acala +// benchmark +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=orml_authority +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./authority/src/weights.rs +// --template +// ../templates/orml-weight-template.hbs + + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(clippy::unnecessary_cast)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for orml_authority. +pub trait WeightInfo { + fn dispatch_as() -> Weight; + fn schedule_dispatch_without_delay() -> Weight; + fn schedule_dispatch_with_delay() -> Weight; + fn fast_track_scheduled_dispatch() -> Weight; + fn delay_scheduled_dispatch() -> Weight; + fn cancel_scheduled_dispatch() -> Weight; +} + +/// Default weights. +impl WeightInfo for () { + fn dispatch_as() -> Weight { + (10_000_000 as Weight) + } + fn schedule_dispatch_without_delay() -> Weight { + (28_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + fn schedule_dispatch_with_delay() -> Weight { + (29_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + fn fast_track_scheduled_dispatch() -> Weight { + (36_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + fn delay_scheduled_dispatch() -> Weight { + (36_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + fn cancel_scheduled_dispatch() -> Weight { + (24_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/currencies/src/lib.rs b/currencies/src/lib.rs index db2fd9d44..cec25c405 100644 --- a/currencies/src/lib.rs +++ b/currencies/src/lib.rs @@ -65,24 +65,17 @@ use sp_std::{ marker, result, }; -mod default_weight; mod mock; mod tests; +mod weights; pub use module::*; +pub use weights::WeightInfo; #[frame_support::pallet] pub mod module { use super::*; - pub trait WeightInfo { - fn transfer_non_native_currency() -> Weight; - fn transfer_native_currency() -> Weight; - fn update_balance_non_native_currency() -> Weight; - fn update_balance_native_currency_creating() -> Weight; - fn update_balance_native_currency_killing() -> Weight; - } - pub(crate) type BalanceOf = <::MultiCurrency as MultiCurrency<::AccountId>>::Balance; pub(crate) type CurrencyIdOf = diff --git a/currencies/src/weights.rs b/currencies/src/weights.rs new file mode 100644 index 000000000..a75ebb239 --- /dev/null +++ b/currencies/src/weights.rs @@ -0,0 +1,67 @@ +//! Autogenerated weights for module_currencies +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 +//! DATE: 2021-05-04, STEPS: [50, ], REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 + +// Executed Command: +// /Users/xiliangchen/projects/acala/target/release/acala +// benchmark +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=module_currencies +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./currencies/src/weights.rs +// --template +// ../templates/orml-weight-template.hbs + + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(clippy::unnecessary_cast)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for module_currencies. +pub trait WeightInfo { + fn transfer_non_native_currency() -> Weight; + fn transfer_native_currency() -> Weight; + fn update_balance_non_native_currency() -> Weight; + fn update_balance_native_currency_creating() -> Weight; + fn update_balance_native_currency_killing() -> Weight; +} + +/// Default weights. +impl WeightInfo for () { + fn transfer_non_native_currency() -> Weight { + (60_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + fn transfer_native_currency() -> Weight { + (60_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + fn update_balance_non_native_currency() -> Weight { + (29_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + fn update_balance_native_currency_creating() -> Weight { + (31_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + fn update_balance_native_currency_killing() -> Weight { + (37_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/oracle/src/lib.rs b/oracle/src/lib.rs index 0716ff3b9..e17708f2c 100644 --- a/oracle/src/lib.rs +++ b/oracle/src/lib.rs @@ -42,21 +42,17 @@ use sp_std::{prelude::*, vec}; pub use crate::default_combine_data::DefaultCombineData; mod default_combine_data; -mod default_weight; mod mock; mod tests; +mod weights; pub use module::*; +pub use weights::WeightInfo; #[frame_support::pallet] pub mod module { use super::*; - pub trait WeightInfo { - fn feed_values(c: u32) -> Weight; - fn on_finalize() -> Weight; - } - pub(crate) type MomentOf = <>::Time as Time>::Moment; pub(crate) type TimestampedValueOf = TimestampedValue<>::OracleValue, MomentOf>; diff --git a/oracle/src/weights.rs b/oracle/src/weights.rs new file mode 100644 index 000000000..36447bdd5 --- /dev/null +++ b/oracle/src/weights.rs @@ -0,0 +1,51 @@ +//! Autogenerated weights for orml_oracle +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 +//! DATE: 2021-05-04, STEPS: [50, ], REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 + +// Executed Command: +// /Users/xiliangchen/projects/acala/target/release/acala +// benchmark +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=orml_oracle +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./oracle/src/weights.rs +// --template +// ../templates/orml-weight-template.hbs + + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(clippy::unnecessary_cast)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for orml_oracle. +pub trait WeightInfo { + fn feed_values(c: u32, ) -> Weight; + fn on_finalize() -> Weight; +} + +/// Default weights. +impl WeightInfo for () { + fn feed_values(c: u32, ) -> Weight { + (16_800_000 as Weight) + // Standard Error: 84_000 + .saturating_add((3_600_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + } + fn on_finalize() -> Weight { + (3_000_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } +} diff --git a/tokens/src/default_weight.rs b/tokens/src/default_weight.rs deleted file mode 100644 index e46bf5656..000000000 --- a/tokens/src/default_weight.rs +++ /dev/null @@ -1,20 +0,0 @@ -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 2.0.0 - -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::weights::{constants::RocksDbWeight as DbWeight, Weight}; - -impl crate::WeightInfo for () { - fn transfer() -> Weight { - (158_835_000 as Weight) - .saturating_add(DbWeight::get().reads(4 as Weight)) - .saturating_add(DbWeight::get().writes(2 as Weight)) - } - fn transfer_all() -> Weight { - (162_545_000 as Weight) - .saturating_add(DbWeight::get().reads(4 as Weight)) - .saturating_add(DbWeight::get().writes(2 as Weight)) - } -} diff --git a/tokens/src/lib.rs b/tokens/src/lib.rs index f29e336b5..955b56856 100644 --- a/tokens/src/lib.rs +++ b/tokens/src/lib.rs @@ -70,10 +70,12 @@ use sp_std::{ vec::Vec, }; -mod default_weight; mod imbalances; mod mock; mod tests; +mod weights; + +pub use weights::WeightInfo; pub struct TransferDust(marker::PhantomData<(T, GetAccountId)>); impl OnDust for TransferDust @@ -150,11 +152,6 @@ pub use module::*; pub mod module { use super::*; - pub trait WeightInfo { - fn transfer() -> Weight; - fn transfer_all() -> Weight; - } - #[pallet::config] pub trait Config: frame_system::Config { type Event: From> + IsType<::Event>; diff --git a/tokens/src/weights.rs b/tokens/src/weights.rs new file mode 100644 index 000000000..5b6ed9474 --- /dev/null +++ b/tokens/src/weights.rs @@ -0,0 +1,49 @@ +//! Autogenerated weights for orml_tokens +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 +//! DATE: 2021-05-04, STEPS: [50, ], REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 + +// Executed Command: +// /Users/xiliangchen/projects/acala/target/release/acala +// benchmark +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=orml_tokens +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./tokens/src/weights.rs +// --template +// ../templates/orml-weight-template.hbs + + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(clippy::unnecessary_cast)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for orml_tokens. +pub trait WeightInfo { + fn transfer() -> Weight; + fn transfer_all() -> Weight; +} + +/// Default weights. +impl WeightInfo for () { + fn transfer() -> Weight { + (60_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + fn transfer_all() -> Weight { + (62_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } +} diff --git a/vesting/src/lib.rs b/vesting/src/lib.rs index bfce0556b..2d3db167d 100644 --- a/vesting/src/lib.rs +++ b/vesting/src/lib.rs @@ -44,11 +44,12 @@ use sp_std::{ vec::Vec, }; -mod default_weight; mod mock; mod tests; +mod weights; pub use module::*; +pub use weights::WeightInfo; /// The maximum number of vesting schedules an account can have. pub const MAX_VESTINGS: usize = 20; @@ -109,12 +110,6 @@ impl VestingSche pub mod module { use super::*; - pub trait WeightInfo { - fn vested_transfer() -> Weight; - fn claim(i: u32) -> Weight; - fn update_vesting_schedules(i: u32) -> Weight; - } - pub(crate) type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; pub(crate) type VestingScheduleOf = VestingSchedule<::BlockNumber, BalanceOf>; diff --git a/vesting/src/weights.rs b/vesting/src/weights.rs new file mode 100644 index 000000000..0efb3bb8b --- /dev/null +++ b/vesting/src/weights.rs @@ -0,0 +1,59 @@ +//! Autogenerated weights for orml_vesting +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 +//! DATE: 2021-05-04, STEPS: [50, ], REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 + +// Executed Command: +// /Users/xiliangchen/projects/acala/target/release/acala +// benchmark +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=orml_vesting +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./vesting/src/weights.rs +// --template +// ../templates/orml-weight-template.hbs + + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(clippy::unnecessary_cast)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for orml_vesting. +pub trait WeightInfo { + fn vested_transfer() -> Weight; + fn claim(i: u32, ) -> Weight; + fn update_vesting_schedules(i: u32, ) -> Weight; +} + +/// Default weights. +impl WeightInfo for () { + fn vested_transfer() -> Weight { + (69_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + fn claim(i: u32, ) -> Weight { + (31_747_000 as Weight) + // Standard Error: 4_000 + .saturating_add((63_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + fn update_vesting_schedules(i: u32, ) -> Weight { + (29_457_000 as Weight) + // Standard Error: 4_000 + .saturating_add((117_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } +} From 6f7ac4067255b5f03a3b655b6bde1d073c6062c4 Mon Sep 17 00:00:00 2001 From: Shaun Wang Date: Tue, 4 May 2021 16:20:26 +1200 Subject: [PATCH 47/49] Add benchmark test suite impl. (#475) * Add benchmark test suite impl. * make clippy happy --- benchmarking/Cargo.toml | 2 +- benchmarking/src/lib.rs | 222 ++++++++++++++++++++++++++++++++++++++ benchmarking/src/tests.rs | 1 - 3 files changed, 223 insertions(+), 2 deletions(-) diff --git a/benchmarking/Cargo.toml b/benchmarking/Cargo.toml index cc20614b8..7fc86eb67 100644 --- a/benchmarking/Cargo.toml +++ b/benchmarking/Cargo.toml @@ -9,7 +9,7 @@ edition = "2018" [dependencies] serde = { version = "1.0.124", optional = true } -paste = "0.1.16" +paste = "1.0" codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-api = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } sp-runtime-interface = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false } diff --git a/benchmarking/src/lib.rs b/benchmarking/src/lib.rs index e3b95c6e9..332f452e6 100644 --- a/benchmarking/src/lib.rs +++ b/benchmarking/src/lib.rs @@ -855,6 +855,28 @@ macro_rules! impl_benchmark { return Ok(results); } } + + /// Test a particular benchmark by name. + /// + /// This isn't called `test_benchmark_by_name` just in case some end-user eventually + /// writes a benchmark, itself called `by_name`; the function would be shadowed in + /// that case. + /// + /// This is generally intended to be used by child test modules such as those created + /// by the `impl_benchmark_test_suite` macro. However, it is not an error if a pallet + /// author chooses not to implement benchmarks. + #[cfg(test)] + #[allow(unused)] + fn test_bench_by_name(name: &[u8]) -> Result<(), &'static str> { + let name = $crate::sp_std::str::from_utf8(name) + .map_err(|_| "`name` is not a valid utf8 string!")?; + match name { + $( stringify!($name) => { + $crate::paste::paste! { [< test_benchmark_ $name >]() } + } )* + _ => Err("Could not find test for requested benchmark."), + } + } }; } @@ -928,6 +950,206 @@ macro_rules! impl_benchmark_test { }; } +/// This creates a test suite which runs the module's benchmarks. +/// +/// When called in `pallet_example` as +/// +/// ```rust,ignore +/// impl_benchmark_test_suite!(crate::tests::new_test_ext()); +/// ``` +/// +/// It expands to the equivalent of: +/// +/// ```rust,ignore +/// #[cfg(test)] +/// mod tests { +/// use super::*; +/// use crate::tests::new_test_ext; +/// use frame_support::assert_ok; +/// +/// #[test] +/// fn test_benchmarks() { +/// new_test_ext().execute_with(|| { +/// assert_ok!(test_benchmark_accumulate_dummy()); +/// assert_ok!(test_benchmark_set_dummy()); +/// assert_ok!(test_benchmark_another_set_dummy()); +/// assert_ok!(test_benchmark_sort_vector()); +/// }); +/// } +/// } +/// ``` +/// +/// ## Arguments +/// +/// The first argument, `new_test_ext`, must be a function call which returns +/// either a `sp_io::TestExternalities`, or some other type with a similar +/// interface. +/// +/// Note that this function call is _not_ evaluated at compile time, but is +/// instead copied textually into each appropriate invocation site. +/// +/// There is an optional second argument, with keyword syntax: `benchmarks_path +/// = path_to_benchmarks_invocation`. In the typical case in which this macro is +/// in the same module as the `benchmarks!` invocation, you don't need to supply +/// this. However, if the `impl_benchmark_test_suite!` invocation is in a +/// different module than the `runtime_benchmarks!` invocation, then you should +/// provide the path to the module containing the `benchmarks!` invocation: +/// +/// ```rust,ignore +/// mod benches { +/// runtime_benchmarks!{ +/// ... +/// } +/// } +/// +/// mod tests { +/// // because of macro syntax limitations, benches can't be paths, but has +/// // to be idents in the scope of `impl_benchmark_test_suite`. +/// use crate::benches; +/// +/// impl_benchmark_test_suite!(new_test_ext(), benchmarks_path = benches); +/// +/// // new_test_ext are defined later in this module +/// } +/// ``` +/// +/// There is an optional 3rd argument, with keyword syntax: `extra = true` or +/// `extra = false`. By default, this generates a test suite which iterates over +/// all benchmarks, including those marked with the `#[extra]` annotation. +/// Setting `extra = false` excludes those. +/// +/// There is an optional 4th argument, with keyword syntax: `exec_name = +/// custom_exec_name`. By default, this macro uses `execute_with` for this +/// parameter. This argument, if set, is subject to these restrictions: +/// +/// - It must be the name of a method applied to the output of the +/// `new_test_ext` argument. +/// - That method must have a signature capable of receiving a single argument +/// of the form `impl FnOnce()`. +#[macro_export] +macro_rules! impl_benchmark_test_suite { + // user might or might not have set some keyword arguments; set the defaults + // + // The weird syntax indicates that `rest` comes only after a comma, which is otherwise optional + ( + $new_test_ext:expr, + $(, $( $rest:tt )* )? + ) => { + impl_benchmark_test_suite!( + @selected: + $new_test_ext, + benchmarks_path = super, + extra = true, + exec_name = execute_with, + @user: + $( $( $rest )* )? + ); + }; + // pick off the benchmarks_path keyword argument + ( + @selected: + $new_test_ext:expr, + benchmarks_path = $old:ident, + extra = $extra:expr, + exec_name = $exec_name:ident, + @user: + benchmarks_path = $benchmarks_path:ident + $(, $( $rest:tt )* )? + ) => { + impl_benchmark_test_suite!( + @selected: + $new_test_ext, + benchmarks_path = $benchmarks_path, + extra = $extra, + exec_name = $exec_name, + @user: + $( $( $rest )* )? + ); + }; + // pick off the extra keyword argument + ( + @selected: + $new_test_ext:expr, + benchmarks_path = $benchmarks_path:ident, + extra = $old:expr, + exec_name = $exec_name:ident, + @user: + extra = $extra:expr + $(, $( $rest:tt )* )? + ) => { + impl_benchmark_test_suite!( + @selected: + $new_test_ext, + benchmarks_path = $benchmarks_path, + extra = $extra, + exec_name = $exec_name, + @user: + $( $( $rest )* )? + ); + }; + // pick off the exec_name keyword argument + ( + @selected: + $new_test_ext:expr, + benchmarks_path = $benchmarks_path:ident, + extra = $extra:expr, + exec_name = $old:ident, + @user: + exec_name = $exec_name:ident + $(, $( $rest:tt )* )? + ) => { + impl_benchmark_test_suite!( + @selected: + $new_test_ext, + benchmarks_path = $benchmarks_path, + extra = $extra, + exec_name = $exec_name, + @user: + $( $( $rest )* )? + ); + }; + // all options set; nothing else in user-provided keyword arguments + ( + @selected: + $new_test_ext:expr, + benchmarks_path = $path_to_benchmarks_invocation:ident, + extra = $extra:expr, + exec_name = $exec_name:ident, + @user: + $(,)? + ) => { + #[cfg(test)] + mod benchmark_tests { + use $path_to_benchmarks_invocation::test_bench_by_name; + use super::*; + + #[test] + fn test_benchmarks() { + $new_test_ext.$exec_name(|| { + use $crate::Benchmarking; + + let mut anything_failed = false; + println!("failing benchmark tests:"); + for benchmark_name in $path_to_benchmarks_invocation::Benchmark::benchmarks($extra) { + match std::panic::catch_unwind(|| test_bench_by_name(benchmark_name)) { + Err(err) => { + println!("{}: {:?}", String::from_utf8_lossy(benchmark_name), err); + anything_failed = true; + }, + Ok(Err(err)) => { + println!("{}: {}", String::from_utf8_lossy(benchmark_name), err); + anything_failed = true; + }, + Ok(Ok(_)) => (), + } + } + assert!(!anything_failed); + }); + } + } + }; +} + /// show error message and debugging info for the case of an error happening /// during a benchmark #[allow(clippy::too_many_arguments)] diff --git a/benchmarking/src/tests.rs b/benchmarking/src/tests.rs index 455b9f710..56717b50c 100644 --- a/benchmarking/src/tests.rs +++ b/benchmarking/src/tests.rs @@ -100,7 +100,6 @@ construct_runtime!( { System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: test::{Pallet, Call, Storage, Config}, - } ); From ef5285c2bb997bd61d8ba1106804866d16717b3b Mon Sep 17 00:00:00 2001 From: Xiliang Chen Date: Tue, 4 May 2021 16:26:59 +1200 Subject: [PATCH 48/49] delete no longer used file (#476) --- oracle/src/default_weight.rs | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 oracle/src/default_weight.rs diff --git a/oracle/src/default_weight.rs b/oracle/src/default_weight.rs deleted file mode 100644 index d910445d9..000000000 --- a/oracle/src/default_weight.rs +++ /dev/null @@ -1,20 +0,0 @@ -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 2.0.0 - -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::weights::{constants::RocksDbWeight as DbWeight, Weight}; - -impl crate::WeightInfo for () { - fn feed_values(c: u32) -> Weight { - (74_792_000 as Weight) - .saturating_add((11_208_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(DbWeight::get().reads(3 as Weight)) - .saturating_add(DbWeight::get().writes(1 as Weight)) - .saturating_add(DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) - } - fn on_finalize() -> Weight { - (15_881_000 as Weight).saturating_add(DbWeight::get().writes(1 as Weight)) - } -} From 778e830e3faefaf6b6af14fa5a049486758f1895 Mon Sep 17 00:00:00 2001 From: Brett Kolodny Date: Tue, 4 May 2021 14:19:01 -0400 Subject: [PATCH 49/49] Add thread_local to METER --- weight-meter/src/meter_std.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/weight-meter/src/meter_std.rs b/weight-meter/src/meter_std.rs index 9622d05cb..0b787762c 100644 --- a/weight-meter/src/meter_std.rs +++ b/weight-meter/src/meter_std.rs @@ -3,10 +3,12 @@ use super::{Meter, Weight}; -static METER: spin::Mutex = spin::Mutex::new(Meter { - used_weight: 0, - depth: 0, -}); +thread_local! { + static METER: spin::Mutex = spin::Mutex::new(Meter { + used_weight: 0, + depth: 0, + }); +} /// Start weight meter with base weight pub fn start_with(base: Weight) {