From 3302020136418b6321cb124229896c1b348bb8d5 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sat, 4 Jun 2022 15:40:27 +0200 Subject: [PATCH 01/59] Reorganize XCM configuration --- runtime/src/lib.rs | 2 +- runtime/src/parachain_params.rs | 91 ++------------------------------- runtime/src/xcm_config.rs | 91 +++++++++++++++++++++++++++++++-- 3 files changed, 92 insertions(+), 92 deletions(-) diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 5a41e6ecb..8b72bb1ca 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -53,7 +53,7 @@ use { frame_system::EnsureSigned, nimbus_primitives::{CanAuthor, NimbusId}, xcm_builder::{EnsureXcmOrigin, FixedWeightBounds, LocationInverter}, - xcm_config::XcmConfig, + xcm_config::{XcmConfig, XcmOriginToTransactDispatchOrigin, LocalOriginToLocation, XcmRouter} }; pub const VERSION: RuntimeVersion = RuntimeVersion { diff --git a/runtime/src/parachain_params.rs b/runtime/src/parachain_params.rs index 70c615f76..98b353cc0 100644 --- a/runtime/src/parachain_params.rs +++ b/runtime/src/parachain_params.rs @@ -4,30 +4,13 @@ clippy::integer_arithmetic )] -use crate::{ - AccountId, Balances, Origin, ParachainInfo, ParachainSystem, XcmpQueue, BASE, - BLOCKS_PER_MINUTE, MAXIMUM_BLOCK_WEIGHT, -}; -use frame_support::{match_types, parameter_types, traits::Everything, weights::Weight}; -use pallet_xcm::XcmPassthrough; -use polkadot_parachain::primitives::Sibling; +use crate::{Origin, ParachainInfo, BASE, BLOCKS_PER_MINUTE, MAXIMUM_BLOCK_WEIGHT}; +use frame_support::{parameter_types, weights::Weight}; use sp_runtime::{Perbill, Percent, SaturatedConversion}; -use xcm::latest::{BodyId, Junction, Junctions, MultiLocation, NetworkId}; -use xcm_builder::{ - AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter, - IsConcrete, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, - SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, TakeWeightCredit, -}; +use xcm::latest::{Junction, MultiLocation, NetworkId}; use zeitgeist_primitives::{constants::MICRO, types::Balance}; -match_types! { - pub type ParentOrParentsUnitPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Junctions::Here } | - // Potentially change "Unit" to "Executive" for mainnet once we have separate runtimes - MultiLocation { parents: 1, interior: Junctions::X1(Junction::Plurality { id: BodyId::Unit, .. }) } - }; -} + parameter_types! { // Author-Mapping /// The amount that should be taken as a security deposit when registering a NimbusId. @@ -88,69 +71,3 @@ parameter_types! { // XCM pub const MaxInstructions: u32 = 100; } - -pub type Barrier = ( - TakeWeightCredit, - AllowTopLevelPaidExecutionFrom, - AllowUnpaidExecutionFrom, - // ^^^ Parent and its exec plurality get free execution -); - -/// Means for transacting assets on this chain. -pub type LocalAssetTransactor = CurrencyAdapter< - // Use this currency: - Balances, - // Use this currency when it is a fungible asset matching the given location or name: - IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: - LocationToAccountId, - // Our chain's account ID type (we can't get away without mentioning it explicitly): - AccountId, - // We don't track any teleports. - (), ->; - -/// No local origins on this chain are allowed to dispatch XCM sends/executions. -pub type LocalOriginToLocation = SignedToAccountId32; - -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used -/// when determining ownership of accounts for asset transacting and when attempting to use XCM -/// `Transact` in order to determine the dispatch Origin. -pub type LocationToAccountId = ( - // The parent (Relay-chain) origin converts to the parent `AccountId`. - ParentIsPreset, - // Sibling parachain origins convert to AccountId via the `ParaId::into`. - SiblingParachainConvertsVia, - // Straight up local `AccountId32` origins just alias directly to `AccountId`. - AccountId32Aliases, -); - -/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, -/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can -/// biases the kind of local `Origin` it will become. -pub type XcmOriginToTransactDispatchOrigin = ( - // Sovereign account converter; this attempts to derive an `AccountId` from the origin location - // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for - // foreign chains who want to have a local sovereign account on this chain which they control. - SovereignSignedViaLocation, - // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when - // recognized. - RelayChainAsNative, - // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when - // recognized. - SiblingParachainAsNative, - // Native signed account converter; this just converts an `AccountId32` origin into a normal - // `Origin::Signed` origin of the same 32-byte value. - SignedAccountId32AsNative, - // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. - XcmPassthrough, -); - -/// The means for routing XCM messages which are not for local execution into the right message -/// queues. -pub type XcmRouter = ( - // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, - // ..and XCMP to communicate with the sibling chains. - XcmpQueue, -); diff --git a/runtime/src/xcm_config.rs b/runtime/src/xcm_config.rs index 830f03f68..39e0a7368 100644 --- a/runtime/src/xcm_config.rs +++ b/runtime/src/xcm_config.rs @@ -1,10 +1,19 @@ use crate::{ - AccountId, Ancestry, Balance, Balances, Barrier, Call, LocalAssetTransactor, MaxInstructions, - PolkadotXcm, RelayLocation, UnitWeightCost, XcmOriginToTransactDispatchOrigin, XcmRouter, + AccountId, Ancestry, Balance, Balances, Call, MaxInstructions, Origin, ParachainSystem, + PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, UnitWeightCost, XcmpQueue, +}; +use frame_support::{match_types, traits::Everything, weights::IdentityFee}; +use pallet_xcm::XcmPassthrough; +use polkadot_parachain::primitives::Sibling; +use xcm_builder::{ + AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter, + FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset, ParentIsPreset, + RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + UsingComponents, }; -use frame_support::weights::IdentityFee; -use xcm_builder::{FixedWeightBounds, LocationInverter, NativeAsset, UsingComponents}; use xcm_executor::Config; +use xcm::latest::{BodyId, Junction, Junctions, MultiLocation}; pub struct XcmConfig; @@ -24,3 +33,77 @@ impl Config for XcmConfig { type Weigher = FixedWeightBounds; type XcmSender = XcmRouter; } + +pub type Barrier = ( + TakeWeightCredit, + AllowTopLevelPaidExecutionFrom, + AllowUnpaidExecutionFrom, + // ^^^ Parent and its exec plurality get free execution +); + +/// Means for transacting assets on this chain. +pub type LocalAssetTransactor = CurrencyAdapter< + // Use this currency: + Balances, + // Use this currency when it is a fungible asset matching the given location or name: + IsConcrete, + // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We don't track any teleports. + (), +>; + +/// No local origins on this chain are allowed to dispatch XCM sends/executions. +pub type LocalOriginToLocation = SignedToAccountId32; + +/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// when determining ownership of accounts for asset transacting and when attempting to use XCM +/// `Transact` in order to determine the dispatch Origin. +pub type LocationToAccountId = ( + // The parent (Relay-chain) origin converts to the parent `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, +); + +/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, +/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can +/// biases the kind of local `Origin` it will become. +pub type XcmOriginToTransactDispatchOrigin = ( + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when + // recognized. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognized. + SiblingParachainAsNative, + // Native signed account converter; this just converts an `AccountId32` origin into a normal + // `Origin::Signed` origin of the same 32-byte value. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, +); + +/// The means for routing XCM messages which are not for local execution into the right message +/// queues. +pub type XcmRouter = ( + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, +); + +match_types! { + pub type ParentOrParentsUnitPlurality: impl Contains = { + MultiLocation { parents: 1, interior: Junctions::Here } | + // Potentially change "Unit" to "Executive" for mainnet once we have separate runtimes + MultiLocation { parents: 1, interior: Junctions::X1(Junction::Plurality { id: BodyId::Unit, .. }) } + }; +} From 2bae5e500f2e8cf3164b2575f0acfd09a5568737 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sat, 4 Jun 2022 17:17:14 +0200 Subject: [PATCH 02/59] Comment XcmConfig and mark necessary changes --- runtime/src/xcm_config.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/runtime/src/xcm_config.rs b/runtime/src/xcm_config.rs index 39e0a7368..b02862b60 100644 --- a/runtime/src/xcm_config.rs +++ b/runtime/src/xcm_config.rs @@ -17,20 +17,38 @@ use xcm::latest::{BodyId, Junction, Junctions, MultiLocation}; pub struct XcmConfig; +/// The main XCM config +/// This is where we configure the core of our XCM integrations: how tokens are transferred, +/// how fees are calculated, what barriers we impose on incoming XCM messages, etc. impl Config for XcmConfig { + /// The handler for when there is an instruction to claim assets. type AssetClaims = PolkadotXcm; + /// TODO: How to withdraw and deposit an asset. type AssetTransactor = LocalAssetTransactor; + /// The general asset trap - handler for when assets are left in the Holding Register at the + /// end of execution. type AssetTrap = PolkadotXcm; + /// Additional filters that specify whether the XCM call should be executed at all. type Barrier = Barrier; + /// The outer call dispatch type. type Call = Call; + /// TODO: Combinations of (Location, Asset) pairs which are trusted as reserves type IsReserve = NativeAsset; + /// Combinations of (Location, Asset) pairs which we trust as teleporters. type IsTeleporter = (); + /// Means of inverting a location. type LocationInverter = LocationInverter; + /// TODO: How to get a call origin from a `OriginKind` value. type OriginConverter = XcmOriginToTransactDispatchOrigin; + /// Module that handles responses of queries. type ResponseHandler = PolkadotXcm; + /// Module that handles subscription requests. type SubscriptionService = PolkadotXcm; + /// TODO: The means of purchasing weight credit for XCM execution. type Trader = UsingComponents, RelayLocation, AccountId, Balances, ()>; + /// TODO: The means of determining an XCM message's weight. type Weigher = FixedWeightBounds; + /// How to send an onward XCM message. type XcmSender = XcmRouter; } From f172dc4dede418290db22e61e25d45de3dfcaed9 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 5 Jun 2022 22:30:02 +0200 Subject: [PATCH 03/59] Implement and configure AssetTransactor --- Cargo.lock | 31 ++++ primitives/src/asset.rs | 3 + runtime/Cargo.toml | 19 ++- runtime/src/lib.rs | 7 +- runtime/src/parachain_params.rs | 1 - runtime/src/parameters.rs | 1 + runtime/src/weights/pallet_author_mapping.rs | 6 +- runtime/src/xcm_config.rs | 165 ++++++++++++++++--- 8 files changed, 199 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aac75ec8d..e77114d18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5190,6 +5190,21 @@ dependencies = [ "xcm", ] +[[package]] +name = "orml-unknown-tokens" +version = "0.4.1-dev" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest#d6a7fb53042ab3bf4a5b02d597a14cf02f43ba97" +dependencies = [ + "frame-support", + "frame-system", + "orml-xcm-support", + "parity-scale-codec", + "scale-info", + "serde", + "sp-std", + "xcm", +] + [[package]] name = "orml-utilities" version = "0.4.1-dev" @@ -5204,6 +5219,20 @@ dependencies = [ "sp-std", ] +[[package]] +name = "orml-xcm-support" +version = "0.4.1-dev" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest#d6a7fb53042ab3bf4a5b02d597a14cf02f43ba97" +dependencies = [ + "frame-support", + "orml-traits", + "parity-scale-codec", + "sp-runtime", + "sp-std", + "xcm", + "xcm-executor", +] + [[package]] name = "os_str_bytes" version = "6.0.1" @@ -12530,6 +12559,8 @@ dependencies = [ "orml-currencies", "orml-tokens", "orml-traits", + "orml-unknown-tokens", + "orml-xcm-support", "pallet-aura", "pallet-author-inherent", "pallet-author-mapping", diff --git a/primitives/src/asset.rs b/primitives/src/asset.rs index 7ac95b476..a24709163 100644 --- a/primitives/src/asset.rs +++ b/primitives/src/asset.rs @@ -18,6 +18,9 @@ pub enum Asset { ScalarOutcome(MI, ScalarPosition), CombinatorialOutcome, PoolShare(SerdeWrapper), + Ausd, + Ksm, + Roc, Ztg, } diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index ef914c770..c81c21d42 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -64,11 +64,12 @@ pallet-author-mapping = { rev = "78db06c0203f61b35059304f7194ed5c10dcfda8", defa pallet-author-slot-filter = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/nimbus", optional = true } pallet-crowdloan-rewards = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/crowdloan-rewards", optional = true } parachain-staking = { rev = "78db06c0203f61b35059304f7194ed5c10dcfda8", default-features = false, git = "https://github.com/purestake/moonbeam", optional = true } +polkadot-parachain = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -# Polkadot - +# XCM +orml-xcm-support = { branch = "polkadot-0.9.19-latest", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-unknown-tokens = { branch = "polkadot-0.9.19-latest", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } pallet-xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -polkadot-parachain = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm-builder = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm-executor = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } @@ -123,11 +124,13 @@ parachain = [ "pallet-author-slot-filter", "pallet-crowdloan-rewards", "parachain-staking", + "polkadot-parachain", - # Polkadot + # XCM + "orml-unknown-tokens", + "orml-xcm-support", "pallet-xcm", - "polkadot-parachain", "xcm-builder", "xcm-executor", "xcm", @@ -239,11 +242,13 @@ std = [ "pallet-author-slot-filter?/std", "pallet-crowdloan-rewards?/std", "parachain-staking?/std", + "polkadot-parachain?/std", - # Polkadot + # XCM + "orml-unknown-tokens?/std", + "orml-xcm-support?/std", "pallet-xcm?/std", - "polkadot-parachain?/std", "xcm-builder?/std", "xcm-executor?/std", "xcm?/std", diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 8b72bb1ca..96b1ca17f 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -53,7 +53,7 @@ use { frame_system::EnsureSigned, nimbus_primitives::{CanAuthor, NimbusId}, xcm_builder::{EnsureXcmOrigin, FixedWeightBounds, LocationInverter}, - xcm_config::{XcmConfig, XcmOriginToTransactDispatchOrigin, LocalOriginToLocation, XcmRouter} + xcm_config::{LocalOriginToLocation, XcmConfig, XcmOriginToTransactDispatchOrigin, XcmRouter}, }; pub const VERSION: RuntimeVersion = RuntimeVersion { @@ -204,6 +204,7 @@ macro_rules! create_zeitgeist_runtime { // Third-party Currency: orml_currencies::{Call, Pallet, Storage} = 40, Tokens: orml_tokens::{Config, Event, Pallet, Storage} = 41, + UnknownTokens: orml_unknown_tokens::{Pallet, Storage, Event} = 42, // Zeitgeist MarketCommons: zrml_market_commons::{Pallet, Storage} = 50, @@ -549,6 +550,10 @@ impl orml_tokens::Config for Runtime { type WeightInfo = weights::orml_tokens::WeightInfo; } +impl orml_unknown_tokens::Config for Runtime { + type Event = Event; +} + #[cfg(feature = "parachain")] impl pallet_crowdloan_rewards::Config for Runtime { type Event = Event; diff --git a/runtime/src/parachain_params.rs b/runtime/src/parachain_params.rs index 98b353cc0..8c9d2a040 100644 --- a/runtime/src/parachain_params.rs +++ b/runtime/src/parachain_params.rs @@ -10,7 +10,6 @@ use sp_runtime::{Perbill, Percent, SaturatedConversion}; use xcm::latest::{Junction, MultiLocation, NetworkId}; use zeitgeist_primitives::{constants::MICRO, types::Balance}; - parameter_types! { // Author-Mapping /// The amount that should be taken as a security deposit when registering a NimbusId. diff --git a/runtime/src/parameters.rs b/runtime/src/parameters.rs index 92511fbee..76c89d904 100644 --- a/runtime/src/parameters.rs +++ b/runtime/src/parameters.rs @@ -135,6 +135,7 @@ parameter_types! { pub const ProposalBondMaximum: Balance = 500 * BASE; pub const SpendPeriod: BlockNumber = 24 * BLOCKS_PER_DAY; pub const TreasuryPalletId: PalletId = PalletId(*b"zge/tsry"); + pub ZeitgeistTreasuryAccount: AccountId = TreasuryPalletId::get().into_account(); // Vesting pub const MinVestedTransfer: Balance = CENT; diff --git a/runtime/src/weights/pallet_author_mapping.rs b/runtime/src/weights/pallet_author_mapping.rs index 8e4614504..4ffe23d56 100644 --- a/runtime/src/weights/pallet_author_mapping.rs +++ b/runtime/src/weights/pallet_author_mapping.rs @@ -33,14 +33,14 @@ pub struct WeightInfo(PhantomData); impl pallet_author_mapping::weights::WeightInfo for WeightInfo { // Storage: AuthorMapping MappingWithDeposit (r:1 w:1) // Storage: System Account (r:1 w:1) - #[rustfmt::skip] + #[rustfmt::skip] fn add_association() -> Weight { (60_010_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: AuthorMapping MappingWithDeposit (r:2 w:2) - #[rustfmt::skip] + #[rustfmt::skip] fn update_association() -> Weight { (45_540_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) @@ -48,7 +48,7 @@ impl pallet_author_mapping::weights::WeightInfo for Wei } // Storage: AuthorMapping MappingWithDeposit (r:1 w:1) // Storage: System Account (r:1 w:1) - #[rustfmt::skip] + #[rustfmt::skip] fn clear_association() -> Weight { (60_780_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) diff --git a/runtime/src/xcm_config.rs b/runtime/src/xcm_config.rs index b02862b60..195c9bb93 100644 --- a/runtime/src/xcm_config.rs +++ b/runtime/src/xcm_config.rs @@ -1,19 +1,25 @@ use crate::{ - AccountId, Ancestry, Balance, Balances, Call, MaxInstructions, Origin, ParachainSystem, - PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, UnitWeightCost, XcmpQueue, + AccountId, Ancestry, Balance, Balances, Call, Currency, MaxInstructions, Origin, + ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, Runtime, + UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; -use frame_support::{match_types, traits::Everything, weights::IdentityFee}; +use frame_support::{match_types, parameter_types, traits::Everything, weights::IdentityFee}; +use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; +use sp_runtime::traits::Convert; +use xcm::latest::{ + prelude::{Concrete, GeneralKey, MultiAsset, Parachain, X1, X2}, + BodyId, Junction, Junctions, MultiLocation, +}; use xcm_builder::{ - AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter, - FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset, ParentIsPreset, - RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - UsingComponents, + AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, + FixedWeightBounds, LocationInverter, NativeAsset, ParentIsPreset, RelayChainAsNative, + SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents, }; use xcm_executor::Config; -use xcm::latest::{BodyId, Junction, Junctions, MultiLocation}; +use zeitgeist_primitives::types::Asset; pub struct XcmConfig; @@ -23,12 +29,12 @@ pub struct XcmConfig; impl Config for XcmConfig { /// The handler for when there is an instruction to claim assets. type AssetClaims = PolkadotXcm; - /// TODO: How to withdraw and deposit an asset. - type AssetTransactor = LocalAssetTransactor; + /// How to withdraw and deposit an asset. + type AssetTransactor = MultiAssetTransactor; /// The general asset trap - handler for when assets are left in the Holding Register at the /// end of execution. type AssetTrap = PolkadotXcm; - /// Additional filters that specify whether the XCM call should be executed at all. + /// TODO: Additional filters that specify whether the XCM call should be executed at all. type Barrier = Barrier; /// The outer call dispatch type. type Call = Call; @@ -58,21 +64,136 @@ pub type Barrier = ( AllowUnpaidExecutionFrom, // ^^^ Parent and its exec plurality get free execution ); +type AssetT = ::CurrencyId; + +parameter_types! { + pub CheckAccount: AccountId = PolkadotXcm::check_account(); +} /// Means for transacting assets on this chain. -pub type LocalAssetTransactor = CurrencyAdapter< - // Use this currency: - Balances, - // Use this currency when it is a fungible asset matching the given location or name: - IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: - LocationToAccountId, - // Our chain's account ID type (we can't get away without mentioning it explicitly): +pub type MultiAssetTransactor = MultiCurrencyAdapter< + // All known Assets will be processed by the following MultiCurrency implementation. + Currency, + // Any unknown Assets will be processed by the following implementation. + UnknownTokens, + // This means that this adapter should handle any token that `AssetConvert` can convert + // using Currency and UnknownTokens in all other cases. + IsNativeConcrete, + // Our chain's account ID type (we can't get away without mentioning it explicitly). AccountId, - // We don't track any teleports. - (), + // Convert an XCM `MultiLocation` into a local account id. + LocationToAccountId, + // The AssetId that corresponds to the native currency. + AssetT, + // Struct that provides functions to convert `Asset` <=> `MultiLocation`. + AssetConvert, + // In case of deposit failure, known assets will be placed in treasury. + DepositToAlternative, >; +/// Listing of parachains we integrate with. +/// For each parachain, we are interested in stating their parachain ID +/// as well as any of their token key ID that we possibly support in our +/// XCM configuration. These token keys are defined in said parachain +/// and must always match the value there defined, which is expected to +/// never change once defined since they help define the canonical id +/// of said tokens in the network, which is relevant for XCM transfers. +pub mod parachains { + pub mod karura { + pub const ID: u32 = 2000; + pub const AUSD_KEY: &[u8] = &[0, 129]; + } + + pub mod zeitgeist { + pub const ID: u32 = 2101; + pub const ZTG_KEY: &[u8] = &[0, 1]; + } +} + +/// AssetConvert +/// This type implements conversions from our `Asset` type into `MultiLocation` and vice-versa. +/// A currency locally is identified with a `Asset` variant but in the network it is identified +/// in the form of a `MultiLocation`, in this case a pair (Para-Id, Currency-Id). +pub struct AssetConvert; +// TODO: Use KSM or ROC depending on runtime that's built +const RELAY_CURRENCY: AssetT = Asset::Roc; + +/// Convert our `Asset` type into its `MultiLocation` representation. +/// Other chains need to know how this conversion takes place in order to +/// handle it on their side. +impl Convert> for AssetConvert { + fn convert(id: AssetT) -> Option { + let x = match id { + RELAY_CURRENCY => MultiLocation::parent(), + Asset::Ausd => MultiLocation::new( + 1, + X2( + Parachain(parachains::karura::ID), + GeneralKey(parachains::karura::AUSD_KEY.into()), + ), + ), + Asset::Ztg => MultiLocation::new( + 1, + X2( + Parachain(parachains::zeitgeist::ID), + GeneralKey(parachains::zeitgeist::ZTG_KEY.to_vec()), + ), + ), + _ => return None, + }; + Some(x) + } +} + +/// Convert an incoming `MultiLocation` into a `Asset` if possible. +/// Here we need to know the canonical representation of all the tokens we handle in order to +/// correctly convert their `MultiLocation` representation into our internal `Asset` type. +impl xcm_executor::traits::Convert for AssetConvert { + fn convert(location: MultiLocation) -> Result { + if location == MultiLocation::parent() { + return Ok(RELAY_CURRENCY); + } + + match location.clone() { + MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { + parachains::zeitgeist::ZTG_KEY => Ok(Asset::Ztg), + _ => Err(location.clone()), + }, + MultiLocation { parents: 1, interior: X2(Parachain(para_id), GeneralKey(key)) } => { + match para_id { + parachains::zeitgeist::ID => match &key[..] { + parachains::zeitgeist::ZTG_KEY => Ok(Asset::Ztg), + _ => Err(location.clone()), + }, + + parachains::karura::ID => match &key[..] { + parachains::karura::AUSD_KEY => Ok(Asset::Ausd), + _ => Err(location.clone()), + }, + _ => Err(location.clone()), + } + } + _ => Err(location.clone()), + } + } +} + +impl Convert> for AssetConvert { + fn convert(asset: MultiAsset) -> Option { + if let MultiAsset { id: Concrete(location), .. } = asset { + >::convert(location).ok() + } else { + None + } + } +} + +impl Convert> for AssetConvert { + fn convert(location: MultiLocation) -> Option { + >::convert(location).ok() + } +} + /// No local origins on this chain are allowed to dispatch XCM sends/executions. pub type LocalOriginToLocation = SignedToAccountId32; From a09a350dafa7bde695de31bf9b7c3e29fdc1df7a Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 16 Jun 2022 13:48:30 +0200 Subject: [PATCH 04/59] Configure and comment XCM Barrier --- runtime/src/xcm_config.rs | 17 +++++++++++------ zrml/swaps/src/tests.rs | 18 ------------------ 2 files changed, 11 insertions(+), 24 deletions(-) diff --git a/runtime/src/xcm_config.rs b/runtime/src/xcm_config.rs index 195c9bb93..db1e41b63 100644 --- a/runtime/src/xcm_config.rs +++ b/runtime/src/xcm_config.rs @@ -13,7 +13,7 @@ use xcm::latest::{ BodyId, Junction, Junctions, MultiLocation, }; use xcm_builder::{ - AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, + AllowSubscriptionsFrom, AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowKnownQueryResponses, FixedWeightBounds, LocationInverter, NativeAsset, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents, @@ -34,7 +34,7 @@ impl Config for XcmConfig { /// The general asset trap - handler for when assets are left in the Holding Register at the /// end of execution. type AssetTrap = PolkadotXcm; - /// TODO: Additional filters that specify whether the XCM call should be executed at all. + /// Additional filters that specify whether the XCM instruction should be executed at all. type Barrier = Barrier; /// The outer call dispatch type. type Call = Call; @@ -58,11 +58,16 @@ impl Config for XcmConfig { type XcmSender = XcmRouter; } +/// Additional filters that specify whether the XCM instruction should be executed at all. pub type Barrier = ( - TakeWeightCredit, - AllowTopLevelPaidExecutionFrom, - AllowUnpaidExecutionFrom, - // ^^^ Parent and its exec plurality get free execution + // Execution barrier that just takes max_weight from weight_credit + TakeWeightCredit, + // Ensures that execution time is bought with BuyExecution instruction + AllowTopLevelPaidExecutionFrom, + // Expected responses are OK. + AllowKnownQueryResponses, + // Subscriptions for version tracking are OK. + AllowSubscriptionsFrom, ); type AssetT = ::CurrencyId; diff --git a/zrml/swaps/src/tests.rs b/zrml/swaps/src/tests.rs index 2e93a0506..f188a066b 100644 --- a/zrml/swaps/src/tests.rs +++ b/zrml/swaps/src/tests.rs @@ -1590,24 +1590,6 @@ fn create_pool_fails_if_base_asset_is_not_in_asset_vector() { }); } -// Macro for comparing fixed point u128. -macro_rules! assert_approx { - ($left:expr, $right:expr, $precision:expr $(,)?) => { - match (&$left, &$right, &$precision) { - (left_val, right_val, precision_val) => { - let diff = if *left_val > *right_val { - *left_val - *right_val - } else { - *right_val - *left_val - }; - if diff > $precision { - panic!("{} is not {}-close to {}", *left_val, *precision_val, *right_val); - } - } - } - }; -} - #[test] fn join_pool_exit_pool_does_not_create_extra_tokens() { ExtBuilder::default().build().execute_with(|| { From 8c5f16497ca8886f3f6f4683eac9dbfc39339ea5 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 16 Jun 2022 14:59:09 +0200 Subject: [PATCH 05/59] Configure XCM IsReserve --- runtime/src/xcm_config.rs | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/runtime/src/xcm_config.rs b/runtime/src/xcm_config.rs index db1e41b63..6467c1b17 100644 --- a/runtime/src/xcm_config.rs +++ b/runtime/src/xcm_config.rs @@ -4,7 +4,8 @@ use crate::{ UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; use frame_support::{match_types, parameter_types, traits::Everything, weights::IdentityFee}; -use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter}; +use orml_traits::location::AbsoluteReserveProvider; +use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use sp_runtime::traits::Convert; @@ -13,10 +14,11 @@ use xcm::latest::{ BodyId, Junction, Junctions, MultiLocation, }; use xcm_builder::{ - AllowSubscriptionsFrom, AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowKnownQueryResponses, - FixedWeightBounds, LocationInverter, NativeAsset, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents, + AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, FixedWeightBounds, LocationInverter, + ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + UsingComponents, }; use xcm_executor::Config; use zeitgeist_primitives::types::Asset; @@ -38,8 +40,8 @@ impl Config for XcmConfig { type Barrier = Barrier; /// The outer call dispatch type. type Call = Call; - /// TODO: Combinations of (Location, Asset) pairs which are trusted as reserves - type IsReserve = NativeAsset; + // Filters multi native assets whose reserve is same with `origin`. + type IsReserve = MultiNativeAsset; /// Combinations of (Location, Asset) pairs which we trust as teleporters. type IsTeleporter = (); /// Means of inverting a location. @@ -61,13 +63,13 @@ impl Config for XcmConfig { /// Additional filters that specify whether the XCM instruction should be executed at all. pub type Barrier = ( // Execution barrier that just takes max_weight from weight_credit - TakeWeightCredit, + TakeWeightCredit, // Ensures that execution time is bought with BuyExecution instruction - AllowTopLevelPaidExecutionFrom, - // Expected responses are OK. - AllowKnownQueryResponses, - // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, + // Expected responses are OK. + AllowKnownQueryResponses, + // Subscriptions for version tracking are OK. + AllowSubscriptionsFrom, ); type AssetT = ::CurrencyId; From 47179af435cbdecd58b3a3dd91933d2a0788018d Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 16 Jun 2022 19:12:16 +0200 Subject: [PATCH 06/59] Prepare Trader implementation for XcmConfig - Add TokenInfo macro and implementation for Asset type - Add fee per second functions for all supported currencies - Use uppercase names for currencies in Asset enum --- Cargo.lock | 7 + docs/changelog_for_devs.md | 5 + primitives/Cargo.toml | 1 + primitives/src/asset.rs | 139 +++++++++- primitives/src/constants.rs | 4 +- runtime/src/lib.rs | 2 +- runtime/src/xcm_config.rs | 258 +----------------- runtime/src/xcm_config/config.rs | 239 ++++++++++++++++ runtime/src/xcm_config/fees.rs | 150 ++++++++++ runtime/src/xcm_config/parachains.rs | 19 ++ .../fuzz/orderbook_v1_full_workflow.rs | 2 +- zrml/prediction-markets/src/lib.rs | 6 +- zrml/prediction-markets/src/tests.rs | 28 +- zrml/swaps/fuzz/swaps_full_workflow.rs | 2 +- zrml/swaps/src/migrations.rs | 205 -------------- 15 files changed, 580 insertions(+), 487 deletions(-) create mode 100644 runtime/src/xcm_config/config.rs create mode 100644 runtime/src/xcm_config/fees.rs create mode 100644 runtime/src/xcm_config/parachains.rs diff --git a/Cargo.lock b/Cargo.lock index e77114d18..48db55d44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -896,6 +896,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "bstringify" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd769563b4ea2953e2825c9e6b7470a5f55f67e0be00030bf3e390a2a6071f64" + [[package]] name = "build-helper" version = "0.1.1" @@ -12521,6 +12527,7 @@ name = "zeitgeist-primitives" version = "0.3.2" dependencies = [ "arbitrary", + "bstringify", "frame-support", "frame-system", "orml-currencies", diff --git a/docs/changelog_for_devs.md b/docs/changelog_for_devs.md index 87b6ecd06..0aa5540dc 100644 --- a/docs/changelog_for_devs.md +++ b/docs/changelog_for_devs.md @@ -1,3 +1,8 @@ +# v0.3.4 +- Asset::Ztg was renamed to Asset::ZTG. All currency symbols will be written in uppercase. +- Added two more currencies: AUSD and KSM (or ROC on testnet) +- Added xTokens pallet to transfer tokens accross chains + # v0.3.3 - Replaced `create_categorical_market` and `create_scalar_market` with diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index d4f827115..a8116247a 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -1,5 +1,6 @@ [dependencies] arbitrary = { default-features = false, optional = true, version = "1.0" } +bstringify = "0.1.2" frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } orml-tokens = { branch = "polkadot-0.9.19-latest", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } diff --git a/primitives/src/asset.rs b/primitives/src/asset.rs index a24709163..42c778ad5 100644 --- a/primitives/src/asset.rs +++ b/primitives/src/asset.rs @@ -1,6 +1,12 @@ -use crate::types::{CategoryIndex, PoolId, SerdeWrapper}; +use crate::types::{CategoryIndex, MarketId, PoolId, SerdeWrapper}; +use alloc::{vec, vec::Vec}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; +use bstringify::bstringify; +use sp_runtime::RuntimeDebug; +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; + /// The `Asset` enum represents all types of assets available in the Zeitgeist /// system. @@ -8,7 +14,7 @@ use scale_info::TypeInfo; /// # Types /// /// * `MI`: Market Id -#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] +#[cfg_attr(feature = "std", derive(Deserialize, Serialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] #[derive( Clone, Copy, Debug, Decode, Eq, Encode, MaxEncodedLen, Ord, PartialEq, PartialOrd, TypeInfo, @@ -18,12 +24,133 @@ pub enum Asset { ScalarOutcome(MI, ScalarPosition), CombinatorialOutcome, PoolShare(SerdeWrapper), - Ausd, - Ksm, - Roc, - Ztg, + ZTG, + // TODO: Use either Roc in Battery Station or KSM on mainnet + ROC, + AUSD, +} + +impl Asset { + pub fn is_token(&self) -> bool { + !matches!(self, Asset::CategoricalOutcome(_, _) | Asset::ScalarOutcome(_, _) | Asset::CombinatorialOutcome | Asset::PoolShare(_)) + } + + pub fn is_outcome_token(&self) -> bool { + matches!(self, Asset::CategoricalOutcome(_, _) | Asset::ScalarOutcome(_, _) | Asset::CombinatorialOutcome) + } + + pub fn is_pool_share(&self) -> bool { + matches!(self, Asset::PoolShare(_)) + } +} + +pub trait TokenInfo { + fn currency_id(&self) -> Option; + fn name(&self) -> Option<&str>; + fn symbol(&self) -> Option<&str>; + fn decimals(&self) -> Option; +} + +macro_rules! create_currency_id { + ($(#[$meta:meta])* + $vis:vis enum TokenSymbol { + $($(#[$vmeta:meta])* $symbol:ident($name:expr, $deci:literal) = $val:literal,)* + }) => { + $(#[$meta])* + $vis enum TokenSymbol { + $($(#[$vmeta])* $symbol = $val,)* + } + + impl TryFrom for TokenSymbol { + type Error = (); + + fn try_from(v: u8) -> Result { + match v { + $($val => Ok(TokenSymbol::$symbol),)* + _ => Err(()), + } + } + } + + impl Into for TokenSymbol { + fn into(self) -> u8 { + match self { + $(TokenSymbol::$symbol => ($val),)* + } + } + } + + impl TryFrom> for Asset { + type Error = (); + fn try_from(v: Vec) -> Result, ()> { + match v.as_slice() { + $(bstringify!($symbol) => Ok(Asset::$symbol),)* + _ => Err(()), + } + } + } + + impl TokenInfo for Asset { + fn currency_id(&self) -> Option { + match self { + $(Asset::$symbol => Some($val),)* + _ => None, + } + } + fn name(&self) -> Option<&str> { + match self { + $(Asset::$symbol => Some($name),)* + _ => None, + } + } + fn symbol(&self) -> Option<&str> { + match self { + $(Asset::$symbol => Some(stringify!($symbol)),)* + _ => None, + } + } + fn decimals(&self) -> Option { + match self { + $(Asset::$symbol => Some($deci),)* + _ => None, + } + } + } + + $(pub const $symbol: Asset = Asset::$symbol;)* + + impl TokenSymbol { + pub fn get_info() -> Vec<(&'static str, u32)> { + vec![ + $((stringify!($symbol), $deci),)* + ] + } + } + } } +create_currency_id! { + // Represent a Token symbol with 8 bit + // + // 0 - 19: Zeitgeist & Rococo/Kusama native tokens + // 20 - 49: Bridged tokens + // 50 - 127: Rococo / Kusama parachain tokens + // 128 - 255: Unreserved + #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord, TypeInfo, MaxEncodedLen)] + #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] + #[repr(u8)] + pub enum TokenSymbol { + // TODO: Use either ROC or KSM depending on runtime that's build + ROC("Rococo", 12) = 0, + // 0 - 19: Zeitgeist & Rococo/Kusama native tokens + ZTG("Zeitgeist", 10) = 1, + // 20 - 49: Bridged tokens + // 50 - 127: Rococo / Kusama parachain tokens + AUSD("Acala Dollar", 12) = 50, + } +} + + /// In a scalar market, users can either choose a `Long` position, /// meaning that they think the outcome will be closer to the upper bound /// or a `Short` position meaning that they think the outcome will be closer diff --git a/primitives/src/constants.rs b/primitives/src/constants.rs index 943697831..5fdab65dd 100644 --- a/primitives/src/constants.rs +++ b/primitives/src/constants.rs @@ -114,14 +114,14 @@ parameter_types! { // ORML parameter_types! { // ORML - pub const GetNativeCurrencyId: CurrencyId = Asset::Ztg; + pub const GetNativeCurrencyId: CurrencyId = Asset::ZTG; } parameter_type_with_key! { // Well, not every asset is a currency ¯\_(ツ)_/¯ pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance { match currency_id { - Asset::Ztg => ExistentialDeposit::get(), + Asset::ZTG => ExistentialDeposit::get(), _ => 0 } }; diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 96b1ca17f..a5d81f664 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -53,7 +53,7 @@ use { frame_system::EnsureSigned, nimbus_primitives::{CanAuthor, NimbusId}, xcm_builder::{EnsureXcmOrigin, FixedWeightBounds, LocationInverter}, - xcm_config::{LocalOriginToLocation, XcmConfig, XcmOriginToTransactDispatchOrigin, XcmRouter}, + xcm_config::{config::{LocalOriginToLocation, XcmConfig, XcmOriginToTransactDispatchOrigin, XcmRouter}}, }; pub const VERSION: RuntimeVersion = RuntimeVersion { diff --git a/runtime/src/xcm_config.rs b/runtime/src/xcm_config.rs index 6467c1b17..7fa3a2542 100644 --- a/runtime/src/xcm_config.rs +++ b/runtime/src/xcm_config.rs @@ -1,255 +1,5 @@ -use crate::{ - AccountId, Ancestry, Balance, Balances, Call, Currency, MaxInstructions, Origin, - ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, Runtime, - UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, -}; -use frame_support::{match_types, parameter_types, traits::Everything, weights::IdentityFee}; -use orml_traits::location::AbsoluteReserveProvider; -use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset}; -use pallet_xcm::XcmPassthrough; -use polkadot_parachain::primitives::Sibling; -use sp_runtime::traits::Convert; -use xcm::latest::{ - prelude::{Concrete, GeneralKey, MultiAsset, Parachain, X1, X2}, - BodyId, Junction, Junctions, MultiLocation, -}; -use xcm_builder::{ - AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, FixedWeightBounds, LocationInverter, - ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - UsingComponents, -}; -use xcm_executor::Config; -use zeitgeist_primitives::types::Asset; +#![cfg(feature = "parachain")] -pub struct XcmConfig; - -/// The main XCM config -/// This is where we configure the core of our XCM integrations: how tokens are transferred, -/// how fees are calculated, what barriers we impose on incoming XCM messages, etc. -impl Config for XcmConfig { - /// The handler for when there is an instruction to claim assets. - type AssetClaims = PolkadotXcm; - /// How to withdraw and deposit an asset. - type AssetTransactor = MultiAssetTransactor; - /// The general asset trap - handler for when assets are left in the Holding Register at the - /// end of execution. - type AssetTrap = PolkadotXcm; - /// Additional filters that specify whether the XCM instruction should be executed at all. - type Barrier = Barrier; - /// The outer call dispatch type. - type Call = Call; - // Filters multi native assets whose reserve is same with `origin`. - type IsReserve = MultiNativeAsset; - /// Combinations of (Location, Asset) pairs which we trust as teleporters. - type IsTeleporter = (); - /// Means of inverting a location. - type LocationInverter = LocationInverter; - /// TODO: How to get a call origin from a `OriginKind` value. - type OriginConverter = XcmOriginToTransactDispatchOrigin; - /// Module that handles responses of queries. - type ResponseHandler = PolkadotXcm; - /// Module that handles subscription requests. - type SubscriptionService = PolkadotXcm; - /// TODO: The means of purchasing weight credit for XCM execution. - type Trader = UsingComponents, RelayLocation, AccountId, Balances, ()>; - /// TODO: The means of determining an XCM message's weight. - type Weigher = FixedWeightBounds; - /// How to send an onward XCM message. - type XcmSender = XcmRouter; -} - -/// Additional filters that specify whether the XCM instruction should be executed at all. -pub type Barrier = ( - // Execution barrier that just takes max_weight from weight_credit - TakeWeightCredit, - // Ensures that execution time is bought with BuyExecution instruction - AllowTopLevelPaidExecutionFrom, - // Expected responses are OK. - AllowKnownQueryResponses, - // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, -); -type AssetT = ::CurrencyId; - -parameter_types! { - pub CheckAccount: AccountId = PolkadotXcm::check_account(); -} - -/// Means for transacting assets on this chain. -pub type MultiAssetTransactor = MultiCurrencyAdapter< - // All known Assets will be processed by the following MultiCurrency implementation. - Currency, - // Any unknown Assets will be processed by the following implementation. - UnknownTokens, - // This means that this adapter should handle any token that `AssetConvert` can convert - // using Currency and UnknownTokens in all other cases. - IsNativeConcrete, - // Our chain's account ID type (we can't get away without mentioning it explicitly). - AccountId, - // Convert an XCM `MultiLocation` into a local account id. - LocationToAccountId, - // The AssetId that corresponds to the native currency. - AssetT, - // Struct that provides functions to convert `Asset` <=> `MultiLocation`. - AssetConvert, - // In case of deposit failure, known assets will be placed in treasury. - DepositToAlternative, ->; - -/// Listing of parachains we integrate with. -/// For each parachain, we are interested in stating their parachain ID -/// as well as any of their token key ID that we possibly support in our -/// XCM configuration. These token keys are defined in said parachain -/// and must always match the value there defined, which is expected to -/// never change once defined since they help define the canonical id -/// of said tokens in the network, which is relevant for XCM transfers. -pub mod parachains { - pub mod karura { - pub const ID: u32 = 2000; - pub const AUSD_KEY: &[u8] = &[0, 129]; - } - - pub mod zeitgeist { - pub const ID: u32 = 2101; - pub const ZTG_KEY: &[u8] = &[0, 1]; - } -} - -/// AssetConvert -/// This type implements conversions from our `Asset` type into `MultiLocation` and vice-versa. -/// A currency locally is identified with a `Asset` variant but in the network it is identified -/// in the form of a `MultiLocation`, in this case a pair (Para-Id, Currency-Id). -pub struct AssetConvert; -// TODO: Use KSM or ROC depending on runtime that's built -const RELAY_CURRENCY: AssetT = Asset::Roc; - -/// Convert our `Asset` type into its `MultiLocation` representation. -/// Other chains need to know how this conversion takes place in order to -/// handle it on their side. -impl Convert> for AssetConvert { - fn convert(id: AssetT) -> Option { - let x = match id { - RELAY_CURRENCY => MultiLocation::parent(), - Asset::Ausd => MultiLocation::new( - 1, - X2( - Parachain(parachains::karura::ID), - GeneralKey(parachains::karura::AUSD_KEY.into()), - ), - ), - Asset::Ztg => MultiLocation::new( - 1, - X2( - Parachain(parachains::zeitgeist::ID), - GeneralKey(parachains::zeitgeist::ZTG_KEY.to_vec()), - ), - ), - _ => return None, - }; - Some(x) - } -} - -/// Convert an incoming `MultiLocation` into a `Asset` if possible. -/// Here we need to know the canonical representation of all the tokens we handle in order to -/// correctly convert their `MultiLocation` representation into our internal `Asset` type. -impl xcm_executor::traits::Convert for AssetConvert { - fn convert(location: MultiLocation) -> Result { - if location == MultiLocation::parent() { - return Ok(RELAY_CURRENCY); - } - - match location.clone() { - MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { - parachains::zeitgeist::ZTG_KEY => Ok(Asset::Ztg), - _ => Err(location.clone()), - }, - MultiLocation { parents: 1, interior: X2(Parachain(para_id), GeneralKey(key)) } => { - match para_id { - parachains::zeitgeist::ID => match &key[..] { - parachains::zeitgeist::ZTG_KEY => Ok(Asset::Ztg), - _ => Err(location.clone()), - }, - - parachains::karura::ID => match &key[..] { - parachains::karura::AUSD_KEY => Ok(Asset::Ausd), - _ => Err(location.clone()), - }, - _ => Err(location.clone()), - } - } - _ => Err(location.clone()), - } - } -} - -impl Convert> for AssetConvert { - fn convert(asset: MultiAsset) -> Option { - if let MultiAsset { id: Concrete(location), .. } = asset { - >::convert(location).ok() - } else { - None - } - } -} - -impl Convert> for AssetConvert { - fn convert(location: MultiLocation) -> Option { - >::convert(location).ok() - } -} - -/// No local origins on this chain are allowed to dispatch XCM sends/executions. -pub type LocalOriginToLocation = SignedToAccountId32; - -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used -/// when determining ownership of accounts for asset transacting and when attempting to use XCM -/// `Transact` in order to determine the dispatch Origin. -pub type LocationToAccountId = ( - // The parent (Relay-chain) origin converts to the parent `AccountId`. - ParentIsPreset, - // Sibling parachain origins convert to AccountId via the `ParaId::into`. - SiblingParachainConvertsVia, - // Straight up local `AccountId32` origins just alias directly to `AccountId`. - AccountId32Aliases, -); - -/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, -/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can -/// biases the kind of local `Origin` it will become. -pub type XcmOriginToTransactDispatchOrigin = ( - // Sovereign account converter; this attempts to derive an `AccountId` from the origin location - // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for - // foreign chains who want to have a local sovereign account on this chain which they control. - SovereignSignedViaLocation, - // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when - // recognized. - RelayChainAsNative, - // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when - // recognized. - SiblingParachainAsNative, - // Native signed account converter; this just converts an `AccountId32` origin into a normal - // `Origin::Signed` origin of the same 32-byte value. - SignedAccountId32AsNative, - // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. - XcmPassthrough, -); - -/// The means for routing XCM messages which are not for local execution into the right message -/// queues. -pub type XcmRouter = ( - // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, - // ..and XCMP to communicate with the sibling chains. - XcmpQueue, -); - -match_types! { - pub type ParentOrParentsUnitPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Junctions::Here } | - // Potentially change "Unit" to "Executive" for mainnet once we have separate runtimes - MultiLocation { parents: 1, interior: Junctions::X1(Junction::Plurality { id: BodyId::Unit, .. }) } - }; -} +mod fees; +mod parachains; +pub mod config; \ No newline at end of file diff --git a/runtime/src/xcm_config/config.rs b/runtime/src/xcm_config/config.rs new file mode 100644 index 000000000..198ac757c --- /dev/null +++ b/runtime/src/xcm_config/config.rs @@ -0,0 +1,239 @@ +use crate::{ + AccountId, Ancestry, Balance, Balances, Call, Currency, MaxInstructions, Origin, + ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, Runtime, + UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, +}; +use super::parachains; +use frame_support::{match_types, parameter_types, traits::Everything, weights::IdentityFee}; +use orml_traits::location::AbsoluteReserveProvider; +use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset}; +use pallet_xcm::XcmPassthrough; +use polkadot_parachain::primitives::Sibling; +use sp_runtime::traits::Convert; +use xcm::latest::{ + prelude::{Concrete, GeneralKey, MultiAsset, Parachain, X1, X2}, + BodyId, Junction, Junctions, MultiLocation, +}; +use xcm_builder::{ + AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, FixedWeightBounds, LocationInverter, + ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + UsingComponents, +}; +use xcm_executor::Config; +use zeitgeist_primitives::types::Asset; + +pub struct XcmConfig; + +/// The main XCM config +/// This is where we configure the core of our XCM integrations: how tokens are transferred, +/// how fees are calculated, what barriers we impose on incoming XCM messages, etc. +impl Config for XcmConfig { + /// The handler for when there is an instruction to claim assets. + type AssetClaims = PolkadotXcm; + /// How to withdraw and deposit an asset. + type AssetTransactor = MultiAssetTransactor; + /// The general asset trap - handler for when assets are left in the Holding Register at the + /// end of execution. + type AssetTrap = PolkadotXcm; + /// Additional filters that specify whether the XCM instruction should be executed at all. + type Barrier = Barrier; + /// The outer call dispatch type. + type Call = Call; + // Filters multi native assets whose reserve is same with `origin`. + type IsReserve = MultiNativeAsset; + /// Combinations of (Location, Asset) pairs which we trust as teleporters. + type IsTeleporter = (); + /// Means of inverting a location. + type LocationInverter = LocationInverter; + // How to get a call origin from a `OriginKind` value. + type OriginConverter = XcmOriginToTransactDispatchOrigin; + /// Module that handles responses of queries. + type ResponseHandler = PolkadotXcm; + /// Module that handles subscription requests. + type SubscriptionService = PolkadotXcm; + /// TODO: The means of purchasing weight credit for XCM execution. + type Trader = UsingComponents, RelayLocation, AccountId, Balances, ()>; + /// TODO: The means of determining an XCM message's weight. + type Weigher = FixedWeightBounds; + /// How to send an onward XCM message. + type XcmSender = XcmRouter; +} + +/// Additional filters that specify whether the XCM instruction should be executed at all. +pub type Barrier = ( + // Execution barrier that just takes max_weight from weight_credit + TakeWeightCredit, + // Ensures that execution time is bought with BuyExecution instruction + AllowTopLevelPaidExecutionFrom, + // Expected responses are OK. + AllowKnownQueryResponses, + // Subscriptions for version tracking are OK. + AllowSubscriptionsFrom, +); +type AssetT = ::CurrencyId; + +parameter_types! { + pub CheckAccount: AccountId = PolkadotXcm::check_account(); +} + +/// Means for transacting assets on this chain. +pub type MultiAssetTransactor = MultiCurrencyAdapter< + // All known Assets will be processed by the following MultiCurrency implementation. + Currency, + // Any unknown Assets will be processed by the following implementation. + UnknownTokens, + // This means that this adapter should handle any token that `AssetConvert` can convert + // using Currency and UnknownTokens in all other cases. + IsNativeConcrete, + // Our chain's account ID type (we can't get away without mentioning it explicitly). + AccountId, + // Convert an XCM `MultiLocation` into a local account id. + LocationToAccountId, + // The AssetId that corresponds to the native currency. + AssetT, + // Struct that provides functions to convert `Asset` <=> `MultiLocation`. + AssetConvert, + // In case of deposit failure, known assets will be placed in treasury. + DepositToAlternative, +>; + +/// AssetConvert +/// This type implements conversions from our `Asset` type into `MultiLocation` and vice-versa. +/// A currency locally is identified with a `Asset` variant but in the network it is identified +/// in the form of a `MultiLocation`, in this case a pair (Para-Id, Currency-Id). +pub struct AssetConvert; +// TODO: Use KSM or ROC depending on runtime that's built +const RELAY_CURRENCY: AssetT = Asset::ROC; + +/// Convert our `Asset` type into its `MultiLocation` representation. +/// Other chains need to know how this conversion takes place in order to +/// handle it on their side. +impl Convert> for AssetConvert { + fn convert(id: AssetT) -> Option { + let x = match id { + RELAY_CURRENCY => MultiLocation::parent(), + Asset::AUSD => MultiLocation::new( + 1, + X2( + Parachain(parachains::karura::ID), + GeneralKey(parachains::karura::AUSD_KEY.into()), + ), + ), + Asset::ZTG => MultiLocation::new( + 1, + X2( + Parachain(parachains::zeitgeist::ID), + GeneralKey(parachains::zeitgeist::ZTG_KEY.to_vec()), + ), + ), + _ => return None, + }; + Some(x) + } +} + +/// Convert an incoming `MultiLocation` into a `Asset` if possible. +/// Here we need to know the canonical representation of all the tokens we handle in order to +/// correctly convert their `MultiLocation` representation into our internal `Asset` type. +impl xcm_executor::traits::Convert for AssetConvert { + fn convert(location: MultiLocation) -> Result { + if location == MultiLocation::parent() { + return Ok(RELAY_CURRENCY); + } + + match location.clone() { + MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { + parachains::zeitgeist::ZTG_KEY => Ok(Asset::ZTG), + _ => Err(location.clone()), + }, + MultiLocation { parents: 1, interior: X2(Parachain(para_id), GeneralKey(key)) } => { + match para_id { + parachains::zeitgeist::ID => match &key[..] { + parachains::zeitgeist::ZTG_KEY => Ok(Asset::ZTG), + _ => Err(location.clone()), + }, + + parachains::karura::ID => match &key[..] { + parachains::karura::AUSD_KEY => Ok(Asset::AUSD), + _ => Err(location.clone()), + }, + + // TODO: MOVR + _ => Err(location.clone()), + } + } + _ => Err(location.clone()), + } + } +} + +impl Convert> for AssetConvert { + fn convert(asset: MultiAsset) -> Option { + if let MultiAsset { id: Concrete(location), .. } = asset { + >::convert(location).ok() + } else { + None + } + } +} + +impl Convert> for AssetConvert { + fn convert(location: MultiLocation) -> Option { + >::convert(location).ok() + } +} + +/// No local origins on this chain are allowed to dispatch XCM sends/executions. +pub type LocalOriginToLocation = SignedToAccountId32; + +/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// when determining ownership of accounts for asset transacting and when attempting to use XCM +/// `Transact` in order to determine the dispatch Origin. +pub type LocationToAccountId = ( + // The parent (Relay-chain) origin converts to the parent `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, +); + +/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, +/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can +/// biases the kind of local `Origin` it will become. +pub type XcmOriginToTransactDispatchOrigin = ( + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when + // recognized. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognized. + SiblingParachainAsNative, + // Native signed account converter; this just converts an `AccountId32` origin into a normal + // `Origin::Signed` origin of the same 32-byte value. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, +); + +/// The means for routing XCM messages which are not for local execution into the right message +/// queues. +pub type XcmRouter = ( + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, +); + +match_types! { + pub type ParentOrParentsUnitPlurality: impl Contains = { + MultiLocation { parents: 1, interior: Junctions::Here } | + // Potentially change "Unit" to "Executive" for mainnet once we have separate runtimes + MultiLocation { parents: 1, interior: Junctions::X1(Junction::Plurality { id: BodyId::Unit, .. }) } + }; +} diff --git a/runtime/src/xcm_config/fees.rs b/runtime/src/xcm_config/fees.rs new file mode 100644 index 000000000..fd5cfc65a --- /dev/null +++ b/runtime/src/xcm_config/fees.rs @@ -0,0 +1,150 @@ +use core::fmt::Debug; +use frame_support::weights::constants::{ExtrinsicBaseWeight, WEIGHT_PER_SECOND}; +use parity_scale_codec::MaxEncodedLen; +use zeitgeist_primitives::types::{Balance, Asset, TokenInfo}; + +// The fee cost per second for transferring the ztg token +pub fn ztg_per_second() -> Balance { + base_tx_per_second(>::ZTG) +} + +// The fee cost per second for transferring the KSM token +// We assume that KSM price is 50x Ztg price +// TODO: Use either ksm_per_second or roc_per_second depending on current runtime +/* +pub fn ksm_per_second() -> Balance { + base_tx_per_second(>::KSM) / 50 +} +*/ + +// The fee cost per second for transferring the KSM token +// We assume that ROC "price" is 10x ZBS price +pub fn roc_per_second() -> Balance { + base_tx_per_second(>::ROC) / 10 +} + + +// The fee cost per second for transferring the aUSD token +// We assume that 1 aUSD = 1 USD = 1 ZTG +pub fn ausd_per_second() -> Balance { + base_tx_per_second(>::AUSD) +} + + +// The fee cost per second for any Asset +fn base_tx_per_second(currency: Asset) -> Balance { + let base_weight = Balance::from(ExtrinsicBaseWeight::get()); + let base_tx_per_second = (WEIGHT_PER_SECOND as u128) / base_weight; + base_tx_per_second * base_tx(currency) +} + +// Base transaction fee that reflects 0.1 cent for any Asset +fn base_tx(currency: Asset) -> Balance { + cent(currency) / 10 +} + +// 1 Asset in fixed point decimal representation +pub fn dollar(currency_id: Asset) -> Balance { + // We assume every asset is registered properly. For any non-currency + // asset we will use the native precision of 10 decimal places + match currency_id.decimals() { + Some(decimals) => decimals.into(), + None => { + log::warn!("dollar() was called for a non-currency asset: {:?}", currency_id); + 10 + } + } +} + +// 0.01 Asset in fixed point decimal presentation +pub fn cent(currency_id: Asset) -> Balance { + dollar(currency_id) / 100 +} + +/* +parameter_types! { + // One XCM operation is 200_000_000 weight, cross-chain transfer ~= 2x of transfer. + pub const UnitWeightCost: Weight = 200_000_000; + pub KsmPerSecond: (AssetId, u128) = (MultiLocation::parent().into(), ksm_per_second()); + pub KusdPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 0, + X1(GeneralKey(KUSD.encode())), + ).into(), + // kUSD:KSM = 400:1 + ksm_per_second() * 400 + ); + pub KarPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 0, + X1(GeneralKey(KAR.encode())), + ).into(), + kar_per_second() + ); + pub LksmPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 0, + X1(GeneralKey(LKSM.encode())), + ).into(), + // LKSM:KSM = 10:1 + ksm_per_second() * 10 + ); + pub PHAPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X1(Parachain(parachains::phala::ID)), + ).into(), + // PHA:KSM = 400:1 + ksm_per_second() * 400 + ); + pub BncPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X2(Parachain(parachains::bifrost::ID), GeneralKey(parachains::bifrost::BNC_KEY.to_vec())), + ).into(), + // BNC:KSM = 80:1 + ksm_per_second() * 80 + ); + pub VsksmPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X2(Parachain(parachains::bifrost::ID), GeneralKey(parachains::bifrost::VSKSM_KEY.to_vec())), + ).into(), + // VSKSM:KSM = 1:1 + ksm_per_second() + ); + pub KbtcPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X2(Parachain(parachains::kintsugi::ID), GeneralKey(parachains::kintsugi::KBTC_KEY.to_vec())), + ).into(), + // KBTC:KSM = 1:150 & Satoshi:Planck = 1:10_000 + ksm_per_second() / 1_500_000 + ); + pub KintPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X2(Parachain(parachains::kintsugi::ID), GeneralKey(parachains::kintsugi::KINT_KEY.to_vec())), + ).into(), + // KINT:KSM = 4:3 + (ksm_per_second() * 4) / 3 + ); + + pub BaseRate: u128 = kar_per_second(); +} + +pub type Trader = ( + FixedRateOfAsset>, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfAsset>, + FixedRateOfAsset>, +); +*/ \ No newline at end of file diff --git a/runtime/src/xcm_config/parachains.rs b/runtime/src/xcm_config/parachains.rs new file mode 100644 index 000000000..41fbdb2c5 --- /dev/null +++ b/runtime/src/xcm_config/parachains.rs @@ -0,0 +1,19 @@ +/// Listing of parachains we integrate with. +/// For each parachain, we are interested in stating their parachain ID +/// as well as any of their token key ID that we possibly support in our +/// XCM configuration. These token keys are defined in said parachain +/// and must always match the value there defined, which is expected to +/// never change once defined since they help define the canonical id +/// of said tokens in the network, which is relevant for XCM transfers. +pub mod karura { + pub const ID: u32 = 2000; + pub const AUSD_KEY: &[u8] = &[0, 129]; +} + +pub mod zeitgeist { + pub const ID: u32 = 2101; + pub const ZTG_KEY: &[u8] = &[0, 1]; +} + +// TODO: Integrate MOVR +// TODO: Integrate USDT \ No newline at end of file diff --git a/zrml/orderbook-v1/fuzz/orderbook_v1_full_workflow.rs b/zrml/orderbook-v1/fuzz/orderbook_v1_full_workflow.rs index 22dc06f61..ce9c6a5f2 100644 --- a/zrml/orderbook-v1/fuzz/orderbook_v1_full_workflow.rs +++ b/zrml/orderbook-v1/fuzz/orderbook_v1_full_workflow.rs @@ -86,7 +86,7 @@ fn asset(seed: (u128, u16)) -> Asset { } 2 => Asset::CombinatorialOutcome, 3 => Asset::PoolShare(SerdeWrapper(seed0)), - _ => Asset::Ztg, + _ => Asset::ZTG, } } diff --git a/zrml/prediction-markets/src/lib.rs b/zrml/prediction-markets/src/lib.rs index 447a90f16..90426fcda 100644 --- a/zrml/prediction-markets/src/lib.rs +++ b/zrml/prediction-markets/src/lib.rs @@ -663,7 +663,7 @@ mod pallet { (amount_base_asset).saturating_sub(MinLiquidity::get().saturated_into()); if remaining_amount > zero_balance { - add_liqudity(remaining_amount, Asset::Ztg)?; + add_liqudity(remaining_amount, Asset::ZTG)?; } Ok(Some( @@ -702,7 +702,7 @@ mod pallet { ensure!(T::MarketCommons::market_pool(&market_id).is_err(), Error::::SwapPoolExists); let mut assets = Self::outcome_assets(market_id, &market); - let base_asset = Asset::Ztg; + let base_asset = Asset::ZTG; assets.push(base_asset); let pool_id = T::Swaps::create_pool( @@ -1995,7 +1995,7 @@ mod pallet { ); let mut assets = Self::outcome_assets(market_id, market); - let base_asset = Asset::Ztg; + let base_asset = Asset::ZTG; assets.push(base_asset); let total_assets = assets.len(); diff --git a/zrml/prediction-markets/src/tests.rs b/zrml/prediction-markets/src/tests.rs index f808f4cd3..a5c5b349b 100644 --- a/zrml/prediction-markets/src/tests.rs +++ b/zrml/prediction-markets/src/tests.rs @@ -94,7 +94,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_active() { 0..1, ScoringRule::CPMM, ); - assert_ok!(Currency::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(Currency::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named(&RESERVE_ID, &ALICE, SENTINEL_AMOUNT)); let balance_free_before_alice = Balances::free_balance(&ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); @@ -118,7 +118,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_reported() { 0, OutcomeReport::Categorical(1) )); - assert_ok!(Currency::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(Currency::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named(&RESERVE_ID, &ALICE, SENTINEL_AMOUNT)); let balance_free_before_alice = Balances::free_balance(&ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); @@ -147,7 +147,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_disputed() { 0, OutcomeReport::Categorical(0) )); - assert_ok!(Currency::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(Currency::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named(&RESERVE_ID, &ALICE, SENTINEL_AMOUNT)); let balance_free_before_alice = Balances::free_balance(&ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); @@ -173,7 +173,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_resolved() { )); run_to_block(9000); // Wait until market resolves assert_eq!(Balances::reserved_balance_named(&RESERVE_ID, &ALICE), 0); - assert_ok!(Currency::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(Currency::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named(&RESERVE_ID, &ALICE, SENTINEL_AMOUNT)); let balance_free_before_alice = Balances::free_balance(&ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); @@ -191,7 +191,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_proposed() { 0..1, ScoringRule::CPMM, ); - assert_ok!(Currency::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(Currency::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named(&RESERVE_ID, &ALICE, SENTINEL_AMOUNT)); let balance_free_before_alice = Balances::free_balance(&ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); @@ -210,7 +210,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_active() { ScoringRule::CPMM, ); assert_ok!(PredictionMarkets::approve_market(Origin::signed(SUDO), 0)); - assert_ok!(Currency::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(Currency::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named(&RESERVE_ID, &ALICE, SENTINEL_AMOUNT)); let balance_free_before_alice = Balances::free_balance(&ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); @@ -235,7 +235,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_reported() { 0, OutcomeReport::Categorical(1) )); - assert_ok!(Currency::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(Currency::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named(&RESERVE_ID, &ALICE, SENTINEL_AMOUNT)); let balance_free_before_alice = Balances::free_balance(&ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); @@ -265,7 +265,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_disputed() { 0, OutcomeReport::Categorical(0) )); - assert_ok!(Currency::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(Currency::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named(&RESERVE_ID, &ALICE, SENTINEL_AMOUNT)); let balance_free_before_alice = Balances::free_balance(&ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); @@ -292,7 +292,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_resolved() { )); run_to_block(9000); // Wait until market resolves assert_eq!(Balances::reserved_balance_named(&RESERVE_ID, &ALICE), 0); - assert_ok!(Currency::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(Currency::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named(&RESERVE_ID, &ALICE, SENTINEL_AMOUNT)); let balance_free_before_alice = Balances::free_balance(&ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); @@ -323,20 +323,20 @@ fn admin_destroy_market_correctly_cleans_up_accounts() { let pool_id = 0; let pool_account = Swaps::pool_account_id(pool_id); let market_account = PredictionMarkets::market_account(market_id); - let alice_ztg_before = Currency::free_balance(Asset::Ztg, &ALICE); + let alice_ztg_before = Currency::free_balance(Asset::ZTG, &ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); assert_eq!(Currency::free_balance(Asset::CategoricalOutcome(0, 0), &pool_account), 0); assert_eq!(Currency::free_balance(Asset::CategoricalOutcome(0, 1), &pool_account), 0); assert_eq!(Currency::free_balance(Asset::CategoricalOutcome(0, 2), &pool_account), 0); - assert_eq!(Currency::free_balance(Asset::Ztg, &pool_account), 0); + assert_eq!(Currency::free_balance(Asset::ZTG, &pool_account), 0); assert_eq!(Currency::free_balance(Asset::CategoricalOutcome(0, 0), &market_account), 0); assert_eq!(Currency::free_balance(Asset::CategoricalOutcome(0, 1), &market_account), 0); assert_eq!(Currency::free_balance(Asset::CategoricalOutcome(0, 2), &market_account), 0); - assert_eq!(Currency::free_balance(Asset::Ztg, &market_account), 0); + assert_eq!(Currency::free_balance(Asset::ZTG, &market_account), 0); assert_eq!(Currency::free_balance(Asset::CategoricalOutcome(0, 0), &ALICE), 0); assert_eq!(Currency::free_balance(Asset::CategoricalOutcome(0, 1), &ALICE), 0); assert_eq!(Currency::free_balance(Asset::CategoricalOutcome(0, 2), &ALICE), 0); - assert_eq!(Currency::free_balance(Asset::Ztg, &ALICE), alice_ztg_before); + assert_eq!(Currency::free_balance(Asset::ZTG, &ALICE), alice_ztg_before); }); } @@ -601,7 +601,7 @@ fn reject_market_unreserves_oracle_bond_and_slashes_advisory_bond() { // Give ALICE `SENTINEL_AMOUNT` free and reserved ZTG; we record the free balance to check // that the AdvisoryBond gets slashed but the OracleBond gets unreserved. - assert_ok!(Currency::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(Currency::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named(&RESERVE_ID, &ALICE, SENTINEL_AMOUNT)); let balance_free_before_alice = Balances::free_balance(&ALICE); diff --git a/zrml/swaps/fuzz/swaps_full_workflow.rs b/zrml/swaps/fuzz/swaps_full_workflow.rs index 27c217f4d..afe00420d 100644 --- a/zrml/swaps/fuzz/swaps_full_workflow.rs +++ b/zrml/swaps/fuzz/swaps_full_workflow.rs @@ -141,6 +141,6 @@ fn asset(seed: (u128, u16)) -> Asset { } 2 => Asset::CombinatorialOutcome, 3 => Asset::PoolShare(SerdeWrapper(seed0)), - _ => Asset::Ztg, + _ => Asset::ZTG, } } diff --git a/zrml/swaps/src/migrations.rs b/zrml/swaps/src/migrations.rs index ece3e0904..e69de29bb 100644 --- a/zrml/swaps/src/migrations.rs +++ b/zrml/swaps/src/migrations.rs @@ -1,205 +0,0 @@ -use crate::{BalanceOf, Config, Pallet}; -use alloc::{collections::btree_map::BTreeMap, vec::Vec}; -use frame_support::{ - dispatch::Weight, - log, - pallet_prelude::PhantomData, - storage::migration::{put_storage_value, storage_iter}, - traits::{Get, OnRuntimeUpgrade, StorageVersion}, -}; -use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use zeitgeist_primitives::types::{Asset, Pool, PoolStatus, ScoringRule}; - -const SWAPS: &[u8] = b"Swaps"; -const POOLS: &[u8] = b"Pools"; -const REQUIRED_STORAGE_VERSION: u16 = 0; -const NEXT_STORAGE_VERSION: u16 = 1; - -#[derive(Decode, Encode, Clone)] -struct PoolDeprecated -where - MarketId: MaxEncodedLen, -{ - pub assets: Vec>, - pub base_asset: Option>, - pub market_id: MarketId, - pub pool_status: PoolStatus, - pub scoring_rule: ScoringRule, - pub swap_fee: Option, - pub total_subsidy: Option, - pub total_weight: Option, - pub weights: Option, u128>>, -} - -pub struct MigratePoolBaseAsset(PhantomData); - -impl OnRuntimeUpgrade for MigratePoolBaseAsset { - fn on_runtime_upgrade() -> Weight - where - T: Config, - { - if StorageVersion::get::>() != REQUIRED_STORAGE_VERSION { - return 0; - } - let mut total_weight: Weight = 0; - log::info!( - "Starting migration of Pool::base_asset from Option> to \ - Asset" - ); - - for (key, value) in - storage_iter::, T::MarketId>>>(SWAPS, POOLS) - { - if let Some(old_pool) = value { - let new_pool = Pool { - assets: old_pool.assets, - base_asset: old_pool.base_asset.unwrap_or(Asset::Ztg), - market_id: old_pool.market_id, - pool_status: old_pool.pool_status, - scoring_rule: old_pool.scoring_rule, - swap_fee: old_pool.swap_fee, - total_subsidy: old_pool.total_subsidy, - total_weight: old_pool.total_weight, - weights: old_pool.weights, - }; - put_storage_value::, T::MarketId>>>( - SWAPS, - POOLS, - &key, - Some(new_pool), - ); - total_weight = total_weight.saturating_add(T::DbWeight::get().writes(1)); - } - - total_weight = total_weight.saturating_add(T::DbWeight::get().reads(1)); - } - - StorageVersion::new(NEXT_STORAGE_VERSION).put::>(); - total_weight = total_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); - - log::info!( - "Completed migration of Pool::base_asset from Option> to \ - Asset" - ); - total_weight - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::mock::{ExtBuilder, Runtime}; - use core::fmt::Debug; - use frame_support::{storage::migration::get_storage_value, Blake2_128Concat, StorageHasher}; - use parity_scale_codec::Encode; - use zeitgeist_primitives::types::{PoolId, ScalarPosition}; - - type Balance = BalanceOf; - type MarketId = ::MarketId; - - #[test] - fn test_on_runtime_upgrade() { - ExtBuilder::default().build().execute_with(|| { - let (old_pools, expected_pools) = create_test_data(); - populate_test_data::>>( - SWAPS, POOLS, old_pools, - ); - MigratePoolBaseAsset::::on_runtime_upgrade(); - for (key, pool_expected) in expected_pools.iter().enumerate() { - let storage_hash = key_to_hash::(key); - let pool_actual = get_storage_value::>>( - SWAPS, - POOLS, - &storage_hash, - ) - .unwrap() - .unwrap(); // Unwrap twice because get_storage returns an option! - assert_eq!(pool_actual, *pool_expected); - } - }); - } - - fn populate_test_data(pallet: &[u8], prefix: &[u8], data: Vec) - where - H: StorageHasher, - K: TryFrom + Encode, - V: Encode + Clone, - >::Error: Debug, - { - for (key, value) in data.iter().enumerate() { - let storage_hash = key_to_hash::(key); - put_storage_value::(pallet, prefix, &storage_hash, (*value).clone()); - } - } - - fn key_to_hash(key: usize) -> Vec - where - H: StorageHasher, - K: TryFrom + Encode, - >::Error: Debug, - { - K::try_from(key).unwrap().using_encoded(H::hash).as_ref().to_vec() - } - - fn create_test_data() - -> (Vec>>, Vec>) { - let mut weights = BTreeMap::new(); - weights.insert(Asset::ScalarOutcome(1, ScalarPosition::Long), 567); - weights.insert(Asset::ScalarOutcome(1, ScalarPosition::Short), 678); - let old_pools: Vec>> = vec![ - Some(PoolDeprecated { - assets: vec![Asset::CategoricalOutcome(0, 0), Asset::CategoricalOutcome(0, 1)], - base_asset: None, - market_id: 0, - pool_status: PoolStatus::Active, - scoring_rule: ScoringRule::CPMM, - swap_fee: None, - total_subsidy: None, - total_weight: None, - weights: None, - }), - Some(PoolDeprecated { - assets: vec![ - Asset::ScalarOutcome(1, ScalarPosition::Long), - Asset::ScalarOutcome(1, ScalarPosition::Short), - ], - base_asset: Some(Asset::CombinatorialOutcome), - market_id: 123, - pool_status: PoolStatus::Stale, - scoring_rule: ScoringRule::RikiddoSigmoidFeeMarketEma, - swap_fee: Some(234), - total_subsidy: Some(345), - total_weight: Some(456), - weights: Some(weights.clone()), - }), - ]; - let expected_pools: Vec> = vec![ - Pool { - assets: vec![Asset::CategoricalOutcome(0, 0), Asset::CategoricalOutcome(0, 1)], - base_asset: Asset::Ztg, - market_id: 0, - pool_status: PoolStatus::Active, - scoring_rule: ScoringRule::CPMM, - swap_fee: None, - total_subsidy: None, - total_weight: None, - weights: None, - }, - Pool { - assets: vec![ - Asset::ScalarOutcome(1, ScalarPosition::Long), - Asset::ScalarOutcome(1, ScalarPosition::Short), - ], - base_asset: Asset::CombinatorialOutcome, - market_id: 123, - pool_status: PoolStatus::Stale, - scoring_rule: ScoringRule::RikiddoSigmoidFeeMarketEma, - swap_fee: Some(234), - total_subsidy: Some(345), - total_weight: Some(456), - weights: Some(weights.clone()), - }, - ]; - (old_pools, expected_pools) - } -} From 62c05d91a90f81269b16fd97d25f7bc78e673d1f Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Wed, 17 Aug 2022 13:40:50 +0200 Subject: [PATCH 07/59] Rename Asset::Ztg -> Asset::ZTG (merge artifact) --- primitives/src/constants/mock.rs | 4 +- runtime/battery-station/src/parameters.rs | 4 +- runtime/zeitgeist/src/parameters.rs | 4 +- zrml/prediction-markets/src/benchmarks.rs | 2 +- zrml/prediction-markets/src/lib.rs | 64 +++++++++++------------ zrml/prediction-markets/src/migrations.rs | 2 +- zrml/prediction-markets/src/tests.rs | 40 +++++++------- zrml/swaps/fuzz/utils.rs | 2 +- 8 files changed, 61 insertions(+), 61 deletions(-) diff --git a/primitives/src/constants/mock.rs b/primitives/src/constants/mock.rs index 0ea728082..60127625a 100644 --- a/primitives/src/constants/mock.rs +++ b/primitives/src/constants/mock.rs @@ -79,14 +79,14 @@ parameter_types! { // ORML parameter_types! { // ORML - pub const GetNativeCurrencyId: CurrencyId = Asset::Ztg; + pub const GetNativeCurrencyId: CurrencyId = Asset::ZTG; } parameter_type_with_key! { // Well, not every asset is a currency ¯\_(ツ)_/¯ pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance { match currency_id { - Asset::Ztg => ExistentialDeposit::get(), + Asset::ZTG => ExistentialDeposit::get(), _ => 0 } }; diff --git a/runtime/battery-station/src/parameters.rs b/runtime/battery-station/src/parameters.rs index 6814ea199..a0ccb74b4 100644 --- a/runtime/battery-station/src/parameters.rs +++ b/runtime/battery-station/src/parameters.rs @@ -131,7 +131,7 @@ parameter_types! { pub const DepositFactor: Balance = deposit(0, 32); // ORML - pub const GetNativeCurrencyId: CurrencyId = Asset::Ztg; + pub const GetNativeCurrencyId: CurrencyId = Asset::ZTG; pub DustAccount: AccountId = PalletId(*b"orml/dst").into_account(); // Prediction Market parameters @@ -298,7 +298,7 @@ parameter_type_with_key! { // Well, not every asset is a currency ¯\_(ツ)_/¯ pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance { match currency_id { - Asset::Ztg => ExistentialDeposit::get(), + Asset::ZTG => ExistentialDeposit::get(), _ => 0 } }; diff --git a/runtime/zeitgeist/src/parameters.rs b/runtime/zeitgeist/src/parameters.rs index 43a18ba62..7654c4216 100644 --- a/runtime/zeitgeist/src/parameters.rs +++ b/runtime/zeitgeist/src/parameters.rs @@ -131,7 +131,7 @@ parameter_types! { pub const DepositFactor: Balance = deposit(0, 32); // ORML - pub const GetNativeCurrencyId: CurrencyId = Asset::Ztg; + pub const GetNativeCurrencyId: CurrencyId = Asset::ZTG; pub DustAccount: AccountId = PalletId(*b"orml/dst").into_account(); // Prediction Market parameters @@ -296,7 +296,7 @@ parameter_type_with_key! { // Well, not every asset is a currency ¯\_(ツ)_/¯ pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance { match currency_id { - Asset::Ztg => ExistentialDeposit::get(), + Asset::ZTG => ExistentialDeposit::get(), _ => 0 } }; diff --git a/zrml/prediction-markets/src/benchmarks.rs b/zrml/prediction-markets/src/benchmarks.rs index 01f6e41dd..9d3fab1e2 100644 --- a/zrml/prediction-markets/src/benchmarks.rs +++ b/zrml/prediction-markets/src/benchmarks.rs @@ -59,7 +59,7 @@ fn create_market_common_parameters( &'static str, > { let caller: T::AccountId = whitelisted_caller(); - let _ = T::AssetManager::deposit(Asset::Ztg, &caller, (u128::MAX).saturated_into()); + let _ = T::AssetManager::deposit(Asset::ZTG, &caller, (u128::MAX).saturated_into()); let oracle = caller.clone(); let period = MarketPeriod::Timestamp(T::MinSubsidyPeriod::get()..T::MaxSubsidyPeriod::get()); let mut metadata = [0u8; 50]; diff --git a/zrml/prediction-markets/src/lib.rs b/zrml/prediction-markets/src/lib.rs index b98f3cfbc..10cbe2900 100644 --- a/zrml/prediction-markets/src/lib.rs +++ b/zrml/prediction-markets/src/lib.rs @@ -180,7 +180,7 @@ mod pallet { let slash_market_creator = |amount| { T::AssetManager::slash_reserved_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &market.creator, amount, ); @@ -216,9 +216,9 @@ mod pallet { } } T::AssetManager::slash( - Asset::Ztg, + Asset::ZTG, &market_account, - T::AssetManager::free_balance(Asset::Ztg, &market_account), + T::AssetManager::free_balance(Asset::ZTG, &market_account), ); if let Ok(pool_id) = T::MarketCommons::market_pool(&market_id) { T::Swaps::destroy_pool(pool_id)?; @@ -345,7 +345,7 @@ mod pallet { T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &m.creator, T::AdvisoryBond::get(), ); @@ -402,7 +402,7 @@ mod pallet { Self::validate_dispute(&disputes, &market, num_disputes, &outcome)?; T::AssetManager::reserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &who, default_dispute_bond::(disputes.len()), )?; @@ -557,7 +557,7 @@ mod pallet { let required_bond = T::ValidityBond::get().saturating_add(T::OracleBond::get()); T::AssetManager::reserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &sender, required_bond, )?; @@ -571,7 +571,7 @@ mod pallet { let required_bond = T::AdvisoryBond::get().saturating_add(T::OracleBond::get()); T::AssetManager::reserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &sender, required_bond, )?; @@ -691,7 +691,7 @@ mod pallet { Self::ensure_market_is_active(&market)?; let mut assets = Self::outcome_assets(market_id, &market); - let base_asset = Asset::Ztg; + let base_asset = Asset::ZTG; assets.push(base_asset); let base_asset_weight = weights.iter().fold(0u128, |acc, val| acc.saturating_add(*val)); weights.push(base_asset_weight); @@ -771,7 +771,7 @@ mod pallet { // Ensure the market account has enough to pay out - if this is // ever not true then we have an accounting problem. ensure!( - T::AssetManager::free_balance(Asset::Ztg, &market_account) + T::AssetManager::free_balance(Asset::ZTG, &market_account) >= winning_balance, Error::::InsufficientFundsInMarketAccount, ); @@ -825,7 +825,7 @@ mod pallet { // Ensure the market account has enough to pay out - if this is // ever not true then we have an accounting problem. ensure!( - T::AssetManager::free_balance(Asset::Ztg, &market_account) + T::AssetManager::free_balance(Asset::ZTG, &market_account) >= long_payout.saturating_add(short_payout), Error::::InsufficientFundsInMarketAccount, ); @@ -842,10 +842,10 @@ mod pallet { T::AssetManager::slash(currency_id, &sender, balance); // Pay out the winner. - let remaining_bal = T::AssetManager::free_balance(Asset::Ztg, &market_account); + let remaining_bal = T::AssetManager::free_balance(Asset::ZTG, &market_account); let actual_payout = payout.min(remaining_bal); - T::AssetManager::transfer(Asset::Ztg, &market_account, &sender, actual_payout)?; + T::AssetManager::transfer(Asset::ZTG, &market_account, &sender, actual_payout)?; // The if-check prevents scalar markets to emit events even if sender only owns one // of the outcome tokens. if balance != >::zero() { @@ -976,7 +976,7 @@ mod pallet { let market_account = Self::market_account(market_id); ensure!( - T::AssetManager::free_balance(Asset::Ztg, &market_account) >= amount, + T::AssetManager::free_balance(Asset::ZTG, &market_account) >= amount, "Market account does not have sufficient reserves.", ); @@ -997,7 +997,7 @@ mod pallet { T::AssetManager::slash(*asset, &sender, amount); } - T::AssetManager::transfer(Asset::Ztg, &market_account, &sender, amount)?; + T::AssetManager::transfer(Asset::ZTG, &market_account, &sender, amount)?; Self::deposit_event(Event::SoldCompleteSet(market_id, amount, sender)); let assets_len: u32 = assets.len().saturated_into(); @@ -1525,7 +1525,7 @@ mod pallet { ) -> DispatchResultWithPostInfo { ensure!(amount != BalanceOf::::zero(), Error::::ZeroAmount); ensure!( - T::AssetManager::free_balance(Asset::Ztg, &who) >= amount, + T::AssetManager::free_balance(Asset::ZTG, &who) >= amount, Error::::NotEnoughBalance ); @@ -1534,7 +1534,7 @@ mod pallet { Self::ensure_market_is_active(&market)?; let market_account = Self::market_account(market_id); - T::AssetManager::transfer(Asset::Ztg, &who, &market_account, amount)?; + T::AssetManager::transfer(Asset::ZTG, &who, &market_account, amount)?; let assets = Self::outcome_assets(market_id, &market); for asset in assets.iter() { @@ -1556,13 +1556,13 @@ mod pallet { let creator = &market.creator; T::AssetManager::slash_reserved_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, creator, T::AdvisoryBond::get(), ); T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, creator, T::OracleBond::get(), ); @@ -1580,13 +1580,13 @@ mod pallet { let creator = &market.creator; T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, creator, T::AdvisoryBond::get(), ); T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, creator, T::OracleBond::get(), ); @@ -1829,7 +1829,7 @@ mod pallet { if market.creation == MarketCreation::Permissionless { T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &market.creator, T::ValidityBond::get(), ); @@ -1846,14 +1846,14 @@ mod pallet { if report.by == market.oracle { T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &market.creator, T::OracleBond::get(), ); } else { let excess = T::AssetManager::slash_reserved_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &market.creator, T::OracleBond::get(), ); @@ -1861,7 +1861,7 @@ mod pallet { let negative_imbalance = T::OracleBond::get().saturating_sub(excess); if let Err(err) = - T::AssetManager::deposit(Asset::Ztg, &report.by, negative_imbalance) + T::AssetManager::deposit(Asset::ZTG, &report.by, negative_imbalance) { log::warn!( "[PredictionMarkets] Cannot deposit to the reporter. error: {:?}", @@ -1898,14 +1898,14 @@ mod pallet { if report.outcome == resolved_outcome { T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &market.creator, T::OracleBond::get(), ); } else { let excess = T::AssetManager::slash_reserved_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &market.creator, T::OracleBond::get(), ); @@ -1920,7 +1920,7 @@ mod pallet { if dispute.outcome == resolved_outcome { T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &dispute.by, actual_bond, ); @@ -1929,7 +1929,7 @@ mod pallet { } else { let excess = T::AssetManager::slash_reserved_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &dispute.by, actual_bond, ); @@ -1952,7 +1952,7 @@ mod pallet { overall_imbalance = overall_imbalance.saturating_sub(reward); if let Err(err) = - T::AssetManager::deposit(Asset::Ztg, correct_reporter, reward) + T::AssetManager::deposit(Asset::ZTG, correct_reporter, reward) { log::warn!( "[PredictionMarkets] Cannot deposit to the correct reporter. \ @@ -2086,7 +2086,7 @@ mod pallet { .saturating_add(T::OracleBond::get()); T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &m.creator, required_bond, ); @@ -2095,7 +2095,7 @@ mod pallet { // was approved. Approval is inevitable to reach this. T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::Ztg, + Asset::ZTG, &m.creator, T::OracleBond::get(), ); @@ -2309,7 +2309,7 @@ mod pallet { ); let mut assets = Self::outcome_assets(market_id, market); - let base_asset = Asset::Ztg; + let base_asset = Asset::ZTG; assets.push(base_asset); let total_assets = assets.len(); diff --git a/zrml/prediction-markets/src/migrations.rs b/zrml/prediction-markets/src/migrations.rs index 6fbbd5c2d..c7a3ba906 100644 --- a/zrml/prediction-markets/src/migrations.rs +++ b/zrml/prediction-markets/src/migrations.rs @@ -438,7 +438,7 @@ mod tests { fn test_market_ids_per_open_block_on_runtime_upgrade() { ExtBuilder::default().build().execute_with(|| { setup_chain(); - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 1_000 * BASE)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 1_000 * BASE)); // Markets which end here will have to be closed on migration: let time_11: MomentOf = (11 * MILLISECS_PER_BLOCK).into(); diff --git a/zrml/prediction-markets/src/tests.rs b/zrml/prediction-markets/src/tests.rs index f5b1c3112..5a3402976 100644 --- a/zrml/prediction-markets/src/tests.rs +++ b/zrml/prediction-markets/src/tests.rs @@ -217,7 +217,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_active() { 0..2, ScoringRule::CPMM, ); - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -249,7 +249,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_reported() { 0, OutcomeReport::Categorical(1) )); - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -286,7 +286,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_disputed() { 0, OutcomeReport::Categorical(0) )); - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -320,7 +320,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_resolved() { )); run_blocks(::DisputePeriod::get()); assert_eq!(Balances::reserved_balance_named(&PredictionMarkets::reserve_id(), &ALICE), 0); - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -345,7 +345,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_proposed() { 0..1, ScoringRule::CPMM, ); - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -371,7 +371,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_active() { ScoringRule::CPMM, ); assert_ok!(PredictionMarkets::approve_market(Origin::signed(SUDO), 0)); - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -404,7 +404,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_reported() { 0, OutcomeReport::Categorical(1) )); - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -442,7 +442,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_disputed() { 0, OutcomeReport::Categorical(0) )); - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -477,7 +477,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_resolved() { )); run_blocks(::ReportingPeriod::get().into()); // Wait until market resolves assert_eq!(Balances::reserved_balance_named(&PredictionMarkets::reserve_id(), &ALICE), 0); - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -514,20 +514,20 @@ fn admin_destroy_market_correctly_cleans_up_accounts() { let pool_id = 0; let pool_account = Swaps::pool_account_id(pool_id); let market_account = PredictionMarkets::market_account(market_id); - let alice_ztg_before = AssetManager::free_balance(Asset::Ztg, &ALICE); + let alice_ztg_before = AssetManager::free_balance(Asset::ZTG, &ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 0), &pool_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 1), &pool_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 2), &pool_account), 0); - assert_eq!(AssetManager::free_balance(Asset::Ztg, &pool_account), 0); + assert_eq!(AssetManager::free_balance(Asset::ZTG, &pool_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 0), &market_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 1), &market_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 2), &market_account), 0); - assert_eq!(AssetManager::free_balance(Asset::Ztg, &market_account), 0); + assert_eq!(AssetManager::free_balance(Asset::ZTG, &market_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 0), &ALICE), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 1), &ALICE), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 2), &ALICE), 0); - assert_eq!(AssetManager::free_balance(Asset::Ztg, &ALICE), alice_ztg_before); + assert_eq!(AssetManager::free_balance(Asset::ZTG, &ALICE), alice_ztg_before); }); } @@ -593,7 +593,7 @@ fn admin_move_market_to_resolved_resolves_reported_market() { // Give ALICE `SENTINEL_AMOUNT` free and reserved ZTG; we record the free balance to check // that the correct bonds are unreserved! - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -846,7 +846,7 @@ fn reject_market_unreserves_oracle_bond_and_slashes_advisory_bond() { // Give ALICE `SENTINEL_AMOUNT` free and reserved ZTG; we record the free balance to check // that the AdvisoryBond gets slashed but the OracleBond gets unreserved. - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -910,7 +910,7 @@ fn on_market_close_auto_rejects_expired_advised_market() { ExtBuilder::default().build().execute_with(|| { // Give ALICE `SENTINEL_AMOUNT` free and reserved ZTG; we record the free balance to check // that the AdvisoryBond and the OracleBond gets unreserved, when the advised market expires. - assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -2056,10 +2056,10 @@ fn create_market_and_deploy_assets_results_in_expected_balances_and_pool_params( Asset::CategoricalOutcome(market_id, 1), Asset::CategoricalOutcome(market_id, 2), Asset::CategoricalOutcome(market_id, 3), - Asset::Ztg, + Asset::ZTG, ]; assert_eq!(pool.assets, assets_expected); - assert_eq!(pool.base_asset, Asset::Ztg); + assert_eq!(pool.base_asset, Asset::ZTG); assert_eq!(pool.market_id, market_id); assert_eq!(pool.scoring_rule, ScoringRule::CPMM); assert_eq!(pool.swap_fee, Some(swap_fee)); @@ -2071,7 +2071,7 @@ fn create_market_and_deploy_assets_results_in_expected_balances_and_pool_params( assert_eq!(pool_weights[&Asset::CategoricalOutcome(market_id, 1)], weight); assert_eq!(pool_weights[&Asset::CategoricalOutcome(market_id, 2)], weight); assert_eq!(pool_weights[&Asset::CategoricalOutcome(market_id, 3)], weight); - assert_eq!(pool_weights[&Asset::Ztg], base_asset_weight); + assert_eq!(pool_weights[&Asset::ZTG], base_asset_weight); }); } @@ -2688,7 +2688,7 @@ fn deploy_swap_pool_correctly_sets_weight_of_base_asset() { let pool = >::get(0).unwrap(); let pool_weights = pool.weights.unwrap(); assert_eq!( - pool_weights[&Asset::Ztg], + pool_weights[&Asset::ZTG], 3 * ::MinWeight::get() + 66 ); }); diff --git a/zrml/swaps/fuzz/utils.rs b/zrml/swaps/fuzz/utils.rs index ec6e54171..972823601 100644 --- a/zrml/swaps/fuzz/utils.rs +++ b/zrml/swaps/fuzz/utils.rs @@ -43,7 +43,7 @@ pub fn construct_asset(seed: (u8, u128, u16)) -> Asset { } 2 => Asset::CombinatorialOutcome, 3 => Asset::PoolShare(SerdeWrapper(seed0)), - _ => Asset::Ztg, + _ => Asset::ZTG, } } From a204b9aa389c62e02f4f19446d97b270b17a76d4 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Fri, 19 Aug 2022 14:35:39 +0200 Subject: [PATCH 08/59] Merge artifacts, work on XCM impl --- Cargo.lock | 58 ++++-- misc/types.json | 2 +- primitives/src/asset.rs | 134 +++++++++++++- runtime/battery-station/Cargo.toml | 2 - .../battery-station/src/xcm_config/config.rs | 12 +- .../battery-station/src/xcm_config/fees.rs | 166 +++++++++--------- 6 files changed, 268 insertions(+), 106 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a6ee3e59b..6c22ab62e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -467,7 +467,9 @@ dependencies = [ "orml-benchmarking", "orml-currencies", "orml-tokens", - "orml-traits", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", + "orml-unknown-tokens", + "orml-xcm-support", "pallet-aura", "pallet-author-inherent", "pallet-author-mapping", @@ -5270,8 +5272,8 @@ source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch= dependencies = [ "frame-support", "frame-system", - "orml-traits", - "orml-utilities", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", + "orml-utilities 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", "parity-scale-codec", "scale-info", "serde", @@ -5287,7 +5289,7 @@ source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch= dependencies = [ "frame-support", "frame-system", - "orml-traits", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", "parity-scale-codec", "scale-info", "serde", @@ -5303,7 +5305,25 @@ dependencies = [ "frame-support", "impl-trait-for-tuples", "num-traits", - "orml-utilities", + "orml-utilities 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", + "parity-scale-codec", + "scale-info", + "serde", + "sp-io", + "sp-runtime", + "sp-std", + "xcm", +] + +[[package]] +name = "orml-traits" +version = "0.4.1-dev" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest#d6a7fb53042ab3bf4a5b02d597a14cf02f43ba97" +dependencies = [ + "frame-support", + "impl-trait-for-tuples", + "num-traits", + "orml-utilities 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest)", "parity-scale-codec", "scale-info", "serde", @@ -5342,13 +5362,27 @@ dependencies = [ "sp-std", ] +[[package]] +name = "orml-utilities" +version = "0.4.1-dev" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest#d6a7fb53042ab3bf4a5b02d597a14cf02f43ba97" +dependencies = [ + "frame-support", + "parity-scale-codec", + "scale-info", + "serde", + "sp-io", + "sp-runtime", + "sp-std", +] + [[package]] name = "orml-xcm-support" version = "0.4.1-dev" source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest#d6a7fb53042ab3bf4a5b02d597a14cf02f43ba97" dependencies = [ "frame-support", - "orml-traits", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest)", "parity-scale-codec", "sp-runtime", "sp-std", @@ -12651,7 +12685,7 @@ dependencies = [ "frame-system", "orml-currencies", "orml-tokens", - "orml-traits", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", "parity-scale-codec", "scale-info", "serde", @@ -12686,7 +12720,7 @@ dependencies = [ "orml-benchmarking", "orml-currencies", "orml-tokens", - "orml-traits", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", "orml-unknown-tokens", "orml-xcm-support", "pallet-aura", @@ -12847,7 +12881,7 @@ dependencies = [ "frame-support", "frame-system", "orml-tokens", - "orml-traits", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", "pallet-balances", "parity-scale-codec", "scale-info", @@ -12878,7 +12912,7 @@ dependencies = [ "more-asserts", "orml-currencies", "orml-tokens", - "orml-traits", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", "pallet-balances", "pallet-randomness-collective-flip", "pallet-timestamp", @@ -12999,7 +13033,7 @@ dependencies = [ "more-asserts", "orml-currencies", "orml-tokens", - "orml-traits", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", "pallet-balances", "pallet-timestamp", "parity-scale-codec", @@ -13024,7 +13058,7 @@ dependencies = [ "arbitrary", "frame-support", "libfuzzer-sys", - "orml-traits", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", "rand 0.8.5", "sp-runtime", "zeitgeist-primitives", diff --git a/misc/types.json b/misc/types.json index 171eef842..1484a1354 100644 --- a/misc/types.json +++ b/misc/types.json @@ -19,7 +19,7 @@ "ScalarOutcome": "(MarketId, ScalarPosition)", "CombinatorialOutcome": null, "PoolShare": "u128", - "Ztg": null + "ZTG": null } }, "AuthorId": "AccountId", diff --git a/primitives/src/asset.rs b/primitives/src/asset.rs index 551bbfb8a..b91b8836a 100644 --- a/primitives/src/asset.rs +++ b/primitives/src/asset.rs @@ -15,9 +15,14 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::types::{CategoryIndex, PoolId, SerdeWrapper}; +use crate::types::{CategoryIndex, MarketId, PoolId, SerdeWrapper}; +use alloc::{vec, vec::Vec}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; +use bstringify::bstringify; +use sp_runtime::RuntimeDebug; +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; /// The `Asset` enum represents all types of assets available in the Zeitgeist /// system. @@ -35,9 +40,134 @@ pub enum Asset { ScalarOutcome(MI, ScalarPosition), CombinatorialOutcome, PoolShare(SerdeWrapper), - Ztg, + ZTG, + // TODO: Use either Roc in Battery Station or KSM on mainnet + ROC, + AUSD, } +impl Asset { + pub fn is_token(&self) -> bool { + !matches!(self, Asset::CategoricalOutcome(_, _) | Asset::ScalarOutcome(_, _) | Asset::CombinatorialOutcome | Asset::PoolShare(_)) + } + + pub fn is_outcome_token(&self) -> bool { + matches!(self, Asset::CategoricalOutcome(_, _) | Asset::ScalarOutcome(_, _) | Asset::CombinatorialOutcome) + } + + pub fn is_pool_share(&self) -> bool { + matches!(self, Asset::PoolShare(_)) + } +} + +pub trait TokenInfo { + fn currency_id(&self) -> Option; + fn name(&self) -> Option<&str>; + fn symbol(&self) -> Option<&str>; + fn decimals(&self) -> Option; +} + +macro_rules! create_currency_id { + ($(#[$meta:meta])* + $vis:vis enum TokenSymbol { + $($(#[$vmeta:meta])* $symbol:ident($name:expr, $deci:literal) = $val:literal,)* + }) => { + $(#[$meta])* + $vis enum TokenSymbol { + $($(#[$vmeta])* $symbol = $val,)* + } + + impl TryFrom for TokenSymbol { + type Error = (); + + fn try_from(v: u8) -> Result { + match v { + $($val => Ok(TokenSymbol::$symbol),)* + _ => Err(()), + } + } + } + + impl Into for TokenSymbol { + fn into(self) -> u8 { + match self { + $(TokenSymbol::$symbol => ($val),)* + } + } + } + + impl TryFrom> for Asset { + type Error = (); + fn try_from(v: Vec) -> Result, ()> { + match v.as_slice() { + $(bstringify!($symbol) => Ok(Asset::$symbol),)* + _ => Err(()), + } + } + } + + impl TokenInfo for Asset { + fn currency_id(&self) -> Option { + match self { + $(Asset::$symbol => Some($val),)* + _ => None, + } + } + fn name(&self) -> Option<&str> { + match self { + $(Asset::$symbol => Some($name),)* + _ => None, + } + } + fn symbol(&self) -> Option<&str> { + match self { + $(Asset::$symbol => Some(stringify!($symbol)),)* + _ => None, + } + } + fn decimals(&self) -> Option { + match self { + $(Asset::$symbol => Some($deci),)* + _ => None, + } + } + } + + $(pub const $symbol: Asset = Asset::$symbol;)* + + impl TokenSymbol { + pub fn get_info() -> Vec<(&'static str, u32)> { + vec![ + $((stringify!($symbol), $deci),)* + ] + } + } + } +} + +create_currency_id! { + // Represent a Token symbol with 8 bit + // + // 0 - 19: Zeitgeist & Rococo/Kusama native tokens + // 20 - 49: Bridged tokens + // 50 - 127: Rococo / Kusama parachain tokens + // 128 - 255: Unreserved + #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord, TypeInfo, MaxEncodedLen)] + #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] + #[repr(u8)] + pub enum TokenSymbol { + // TODO: Use either ROC or KSM depending on runtime that's build + ROC("Rococo", 12) = 0, + // 0 - 19: Zeitgeist & Rococo/Kusama native tokens + ZTG("Zeitgeist", 10) = 1, + // 20 - 49: Bridged tokens + // 50 - 127: Rococo / Kusama parachain tokens + AUSD("Acala Dollar", 12) = 50, + } +} + + + /// In a scalar market, users can either choose a `Long` position, /// meaning that they think the outcome will be closer to the upper bound /// or a `Short` position meaning that they think the outcome will be closer diff --git a/runtime/battery-station/Cargo.toml b/runtime/battery-station/Cargo.toml index 0b374a84c..e618a1153 100644 --- a/runtime/battery-station/Cargo.toml +++ b/runtime/battery-station/Cargo.toml @@ -316,8 +316,6 @@ try-runtime = [ # ORML runtime pallets "orml-currencies/try-runtime", "orml-tokens/try-runtime", - "orml-unknown-tokens?/try-runtime", - "orml-xcm-support?/try-runtime", # Zeitgeist runtime pallets "zrml-authorized/try-runtime", diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 198ac757c..630612bed 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -1,5 +1,5 @@ use crate::{ - AccountId, Ancestry, Balance, Balances, Call, Currency, MaxInstructions, Origin, + AccountId, Ancestry, Balance, Balances, Call, AssetManager, MaxInstructions, Origin, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, Runtime, UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; @@ -42,7 +42,7 @@ impl Config for XcmConfig { /// The outer call dispatch type. type Call = Call; // Filters multi native assets whose reserve is same with `origin`. - type IsReserve = MultiNativeAsset; + type IsReserve = (); // MultiNativeAsset; /// Combinations of (Location, Asset) pairs which we trust as teleporters. type IsTeleporter = (); /// Means of inverting a location. @@ -81,11 +81,11 @@ parameter_types! { /// Means for transacting assets on this chain. pub type MultiAssetTransactor = MultiCurrencyAdapter< // All known Assets will be processed by the following MultiCurrency implementation. - Currency, + AssetManager, // Any unknown Assets will be processed by the following implementation. UnknownTokens, // This means that this adapter should handle any token that `AssetConvert` can convert - // using Currency and UnknownTokens in all other cases. + // using AssetManager and UnknownTokens in all other cases. IsNativeConcrete, // Our chain's account ID type (we can't get away without mentioning it explicitly). AccountId, @@ -96,7 +96,7 @@ pub type MultiAssetTransactor = MultiCurrencyAdapter< // Struct that provides functions to convert `Asset` <=> `MultiLocation`. AssetConvert, // In case of deposit failure, known assets will be placed in treasury. - DepositToAlternative, + DepositToAlternative, >; /// AssetConvert @@ -208,7 +208,7 @@ pub type XcmOriginToTransactDispatchOrigin = ( // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for // foreign chains who want to have a local sovereign account on this chain which they control. SovereignSignedViaLocation, - // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when + // Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when // recognized. RelayChainAsNative, // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when diff --git a/runtime/battery-station/src/xcm_config/fees.rs b/runtime/battery-station/src/xcm_config/fees.rs index fd5cfc65a..f0f647c97 100644 --- a/runtime/battery-station/src/xcm_config/fees.rs +++ b/runtime/battery-station/src/xcm_config/fees.rs @@ -9,7 +9,7 @@ pub fn ztg_per_second() -> Balance { } // The fee cost per second for transferring the KSM token -// We assume that KSM price is 50x Ztg price +// We assume that KSM price is 50x ZTG price // TODO: Use either ksm_per_second or roc_per_second depending on current runtime /* pub fn ksm_per_second() -> Balance { @@ -17,7 +17,7 @@ pub fn ksm_per_second() -> Balance { } */ -// The fee cost per second for transferring the KSM token +// The fee cost per second for transferring the ROC token // We assume that ROC "price" is 10x ZBS price pub fn roc_per_second() -> Balance { base_tx_per_second(>::ROC) / 10 @@ -61,90 +61,90 @@ pub fn cent(currency_id: Asset) -> Balance { dollar(currency_id) / 100 } + /* parameter_types! { - // One XCM operation is 200_000_000 weight, cross-chain transfer ~= 2x of transfer. - pub const UnitWeightCost: Weight = 200_000_000; - pub KsmPerSecond: (AssetId, u128) = (MultiLocation::parent().into(), ksm_per_second()); - pub KusdPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 0, - X1(GeneralKey(KUSD.encode())), - ).into(), - // kUSD:KSM = 400:1 - ksm_per_second() * 400 - ); - pub KarPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 0, - X1(GeneralKey(KAR.encode())), - ).into(), - kar_per_second() - ); - pub LksmPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 0, - X1(GeneralKey(LKSM.encode())), - ).into(), - // LKSM:KSM = 10:1 - ksm_per_second() * 10 - ); - pub PHAPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 1, - X1(Parachain(parachains::phala::ID)), - ).into(), - // PHA:KSM = 400:1 - ksm_per_second() * 400 - ); - pub BncPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 1, - X2(Parachain(parachains::bifrost::ID), GeneralKey(parachains::bifrost::BNC_KEY.to_vec())), - ).into(), - // BNC:KSM = 80:1 - ksm_per_second() * 80 - ); - pub VsksmPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 1, - X2(Parachain(parachains::bifrost::ID), GeneralKey(parachains::bifrost::VSKSM_KEY.to_vec())), - ).into(), - // VSKSM:KSM = 1:1 - ksm_per_second() - ); - pub KbtcPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 1, - X2(Parachain(parachains::kintsugi::ID), GeneralKey(parachains::kintsugi::KBTC_KEY.to_vec())), - ).into(), - // KBTC:KSM = 1:150 & Satoshi:Planck = 1:10_000 - ksm_per_second() / 1_500_000 - ); - pub KintPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 1, - X2(Parachain(parachains::kintsugi::ID), GeneralKey(parachains::kintsugi::KINT_KEY.to_vec())), - ).into(), - // KINT:KSM = 4:3 - (ksm_per_second() * 4) / 3 - ); + // One XCM operation is 200_000_000 weight, cross-chain transfer ~= 2x of transfer. + pub const UnitWeightCost: Weight = 200_000_000; + pub KsmPerSecond: (AssetId, u128) = (MultiLocation::parent().into(), ksm_per_second()); + pub KusdPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 0, + X1(GeneralKey(KUSD.encode())), + ).into(), + // kUSD:KSM = 400:1 + ksm_per_second() * 400 + ); + pub KarPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 0, + X1(GeneralKey(KAR.encode())), + ).into(), + kar_per_second() + ); + pub LksmPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 0, + X1(GeneralKey(LKSM.encode())), + ).into(), + // LKSM:KSM = 10:1 + ksm_per_second() * 10 + ); + pub PHAPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X1(Parachain(parachains::phala::ID)), + ).into(), + // PHA:KSM = 400:1 + ksm_per_second() * 400 + ); + pub BncPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X2(Parachain(parachains::bifrost::ID), GeneralKey(parachains::bifrost::BNC_KEY.to_vec())), + ).into(), + // BNC:KSM = 80:1 + ksm_per_second() * 80 + ); + pub VsksmPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X2(Parachain(parachains::bifrost::ID), GeneralKey(parachains::bifrost::VSKSM_KEY.to_vec())), + ).into(), + // VSKSM:KSM = 1:1 + ksm_per_second() + ); + pub KbtcPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X2(Parachain(parachains::kintsugi::ID), GeneralKey(parachains::kintsugi::KBTC_KEY.to_vec())), + ).into(), + // KBTC:KSM = 1:150 & Satoshi:Planck = 1:10_000 + ksm_per_second() / 1_500_000 + ); + pub KintPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X2(Parachain(parachains::kintsugi::ID), GeneralKey(parachains::kintsugi::KINT_KEY.to_vec())), + ).into(), + // KINT:KSM = 4:3 + (ksm_per_second() * 4) / 3 + ); - pub BaseRate: u128 = kar_per_second(); + pub BaseRate: u128 = kar_per_second(); } pub type Trader = ( - FixedRateOfAsset>, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfAsset>, - FixedRateOfAsset>, -); -*/ \ No newline at end of file + FixedRateOfAsset>, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfFungible, + FixedRateOfAsset>, + FixedRateOfAsset>, +);*/ \ No newline at end of file From c735f2494a95db1d5bb0bd91ba9989bc5d423b0b Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 25 Sep 2022 19:58:38 +0200 Subject: [PATCH 09/59] Use MultiAssetTransactor and latest orml pallets --- Cargo.lock | 91 ++++++++++++++----- primitives/Cargo.toml | 6 +- runtime/battery-station/Cargo.toml | 17 ++-- runtime/battery-station/src/lib.rs | 23 ++++- .../battery-station/src/xcm_config/config.rs | 52 +++++------ .../battery-station/src/xcm_config/fees.rs | 17 ++++ .../src/xcm_config/parachains.rs | 17 ++++ runtime/common/Cargo.toml | 4 +- runtime/zeitgeist/Cargo.toml | 8 +- rust-toolchain | 2 +- zrml/orderbook-v1/Cargo.toml | 4 +- zrml/prediction-markets/Cargo.toml | 6 +- zrml/swaps/Cargo.toml | 6 +- zrml/swaps/fuzz/Cargo.toml | 2 +- 14 files changed, 182 insertions(+), 73 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6c22ab62e..8ebe35923 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -464,12 +464,13 @@ dependencies = [ "hex-literal", "log", "nimbus-primitives", + "orml-asset-registry", "orml-benchmarking", "orml-currencies", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", - "orml-unknown-tokens", - "orml-xcm-support", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-unknown-tokens 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-xcm-support 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", "pallet-aura", "pallet-author-inherent", "pallet-author-mapping", @@ -5245,10 +5246,29 @@ dependencies = [ "num-traits", ] +[[package]] +name = "orml-asset-registry" +version = "0.4.1-dev" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#f163e2cb3f93265c23ffba32fc9653618022c0be" +dependencies = [ + "frame-support", + "frame-system", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "pallet-xcm", + "parity-scale-codec", + "scale-info", + "serde", + "sp-runtime", + "sp-std", + "xcm", + "xcm-builder", + "xcm-executor", +] + [[package]] name = "orml-benchmarking" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" dependencies = [ "frame-benchmarking", "frame-support", @@ -5268,12 +5288,12 @@ dependencies = [ [[package]] name = "orml-currencies" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" dependencies = [ "frame-support", "frame-system", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", - "orml-utilities 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-utilities 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", "parity-scale-codec", "scale-info", "serde", @@ -5285,11 +5305,11 @@ dependencies = [ [[package]] name = "orml-tokens" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" dependencies = [ "frame-support", "frame-system", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", "parity-scale-codec", "scale-info", "serde", @@ -5300,12 +5320,12 @@ dependencies = [ [[package]] name = "orml-traits" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" dependencies = [ "frame-support", "impl-trait-for-tuples", "num-traits", - "orml-utilities 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", + "orml-utilities 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", "parity-scale-codec", "scale-info", "serde", @@ -5333,6 +5353,21 @@ dependencies = [ "xcm", ] +[[package]] +name = "orml-unknown-tokens" +version = "0.4.1-dev" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +dependencies = [ + "frame-support", + "frame-system", + "orml-xcm-support 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "parity-scale-codec", + "scale-info", + "serde", + "sp-std", + "xcm", +] + [[package]] name = "orml-unknown-tokens" version = "0.4.1-dev" @@ -5340,7 +5375,7 @@ source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch= dependencies = [ "frame-support", "frame-system", - "orml-xcm-support", + "orml-xcm-support 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest)", "parity-scale-codec", "scale-info", "serde", @@ -5351,7 +5386,7 @@ dependencies = [ [[package]] name = "orml-utilities" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" dependencies = [ "frame-support", "parity-scale-codec", @@ -5376,6 +5411,20 @@ dependencies = [ "sp-std", ] +[[package]] +name = "orml-xcm-support" +version = "0.4.1-dev" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +dependencies = [ + "frame-support", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "parity-scale-codec", + "sp-runtime", + "sp-std", + "xcm", + "xcm-executor", +] + [[package]] name = "orml-xcm-support" version = "0.4.1-dev" @@ -12685,7 +12734,7 @@ dependencies = [ "frame-system", "orml-currencies", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", "parity-scale-codec", "scale-info", "serde", @@ -12720,9 +12769,9 @@ dependencies = [ "orml-benchmarking", "orml-currencies", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", - "orml-unknown-tokens", - "orml-xcm-support", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-unknown-tokens 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest)", + "orml-xcm-support 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest)", "pallet-aura", "pallet-author-inherent", "pallet-author-mapping", @@ -12881,7 +12930,7 @@ dependencies = [ "frame-support", "frame-system", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", "pallet-balances", "parity-scale-codec", "scale-info", @@ -12912,7 +12961,7 @@ dependencies = [ "more-asserts", "orml-currencies", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", "pallet-balances", "pallet-randomness-collective-flip", "pallet-timestamp", @@ -13033,7 +13082,7 @@ dependencies = [ "more-asserts", "orml-currencies", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", "pallet-balances", "pallet-timestamp", "parity-scale-codec", @@ -13058,7 +13107,7 @@ dependencies = [ "arbitrary", "frame-support", "libfuzzer-sys", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=2022-06-v0.9.19)", + "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", "rand 0.8.5", "sp-runtime", "zeitgeist-primitives", diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index 9dab76528..992320c11 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -3,9 +3,9 @@ arbitrary = { default-features = false, optional = true, version = "1.0" } bstringify = "0.1.2" frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } -orml-tokens = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } -orml-traits = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } -orml-currencies = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-traits = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-currencies = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } parity-scale-codec = { default-features = false, features = ["derive", "max-encoded-len"], version = "3.0.0" } scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } serde = { default-features = false, features = ["derive"], optional = true, version = "1.0.136" } diff --git a/runtime/battery-station/Cargo.toml b/runtime/battery-station/Cargo.toml index e618a1153..53366e7bc 100644 --- a/runtime/battery-station/Cargo.toml +++ b/runtime/battery-station/Cargo.toml @@ -6,10 +6,10 @@ frame-executive = { branch = "moonbeam-polkadot-v0.9.19", default-features = fal frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-system-rpc-runtime-api = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } -orml-benchmarking = { branch = "2022-06-v0.9.19", default-features = false, optional = true, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } -orml-currencies = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } -orml-tokens = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } -orml-traits = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-benchmarking = { branch = "7e1123e-v0.9.19", default-features = false, optional = true, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-currencies = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-traits = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } pallet-balances = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } pallet-collective = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } pallet-democracy = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } @@ -83,8 +83,9 @@ hex-literal = { default-features = false, optional = true, version = "0.3.4" } log = { version = "0.4.8", default-features = false, optional = true } # XCM -orml-xcm-support = { branch = "polkadot-0.9.19-latest", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-unknown-tokens = { branch = "polkadot-0.9.19-latest", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-asset-registry = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-unknown-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } pallet-xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm-builder = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } @@ -134,6 +135,7 @@ parachain = [ # XCM + "orml-asset-registry", "orml-unknown-tokens", "orml-xcm-support", "pallet-xcm", @@ -263,6 +265,7 @@ std = [ # XCM + "orml-asset-registry?/std", "orml-unknown-tokens?/std", "orml-xcm-support?/std", "pallet-xcm?/std", @@ -314,8 +317,10 @@ try-runtime = [ "pallet-utility/try-runtime", # ORML runtime pallets + "orml-asset-registry?/try-runtime", "orml-currencies/try-runtime", "orml-tokens/try-runtime", + "orml-unknown-tokens?/try-runtime", # Zeitgeist runtime pallets "zrml-authorized/try-runtime", diff --git a/runtime/battery-station/src/lib.rs b/runtime/battery-station/src/lib.rs index 04c3cbe25..988ac2caf 100644 --- a/runtime/battery-station/src/lib.rs +++ b/runtime/battery-station/src/lib.rs @@ -128,17 +128,38 @@ impl Contains for IsCallable { decl_common_types!(); +#[cfg(not(feature = "parachain"))] create_runtime_with_additional_pallets!( // Others Sudo: pallet_sudo::{Call, Config, Event, Pallet, Storage} = 150, - UnknownTokens: orml_unknown_tokens::{Pallet, Storage, Event} = 151, ); +#[cfg(feature = "parachain")] +create_runtime_with_additional_pallets!( + // Others + Sudo: pallet_sudo::{Call, Config, Event, Pallet, Storage} = 150, + AssetRegistry: orml_unknown_tokens::{Pallet, Storage, Event} = 151, + UnknownTokens: orml_unknown_tokens::{Pallet, Storage, Event} = 152, +); + + impl pallet_sudo::Config for Runtime { type Call = Call; type Event = Event; } +#[cfg(feature = "parachain")] +impl orml_asset_registry::Config for Runtime { + type AssetId = CurrencyId; + type AssetProcessor = asset_registry::CustomAssetProcessor; + type AuthorityOrigin = asset_registry::AuthorityOrigin>; + type Balance = Balance; + type CustomMetadata = CustomMetadata; + type Event = Event; + type WeightInfo = (); +} + +#[cfg(feature = "parachain")] impl orml_unknown_tokens::Config for Runtime { type Event = Event; } diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 630612bed..e0aa55966 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -1,3 +1,20 @@ +// Copyright 2022 Zeitgeist PM LLC. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + use crate::{ AccountId, Ancestry, Balance, Balances, Call, AssetManager, MaxInstructions, Origin, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, Runtime, @@ -42,7 +59,7 @@ impl Config for XcmConfig { /// The outer call dispatch type. type Call = Call; // Filters multi native assets whose reserve is same with `origin`. - type IsReserve = (); // MultiNativeAsset; + type IsReserve = MultiNativeAsset; /// Combinations of (Location, Asset) pairs which we trust as teleporters. type IsTeleporter = (); /// Means of inverting a location. @@ -88,7 +105,7 @@ pub type MultiAssetTransactor = MultiCurrencyAdapter< // using AssetManager and UnknownTokens in all other cases. IsNativeConcrete, // Our chain's account ID type (we can't get away without mentioning it explicitly). - AccountId, + sp_runtime::AccountId32, // Convert an XCM `MultiLocation` into a local account id. LocationToAccountId, // The AssetId that corresponds to the native currency. @@ -104,8 +121,6 @@ pub type MultiAssetTransactor = MultiCurrencyAdapter< /// A currency locally is identified with a `Asset` variant but in the network it is identified /// in the form of a `MultiLocation`, in this case a pair (Para-Id, Currency-Id). pub struct AssetConvert; -// TODO: Use KSM or ROC depending on runtime that's built -const RELAY_CURRENCY: AssetT = Asset::ROC; /// Convert our `Asset` type into its `MultiLocation` representation. /// Other chains need to know how this conversion takes place in order to @@ -113,14 +128,6 @@ const RELAY_CURRENCY: AssetT = Asset::ROC; impl Convert> for AssetConvert { fn convert(id: AssetT) -> Option { let x = match id { - RELAY_CURRENCY => MultiLocation::parent(), - Asset::AUSD => MultiLocation::new( - 1, - X2( - Parachain(parachains::karura::ID), - GeneralKey(parachains::karura::AUSD_KEY.into()), - ), - ), Asset::ZTG => MultiLocation::new( 1, X2( @@ -128,6 +135,7 @@ impl Convert> for AssetConvert { GeneralKey(parachains::zeitgeist::ZTG_KEY.to_vec()), ), ), + // TODO: Asset registry _ => return None, }; Some(x) @@ -139,32 +147,24 @@ impl Convert> for AssetConvert { /// correctly convert their `MultiLocation` representation into our internal `Asset` type. impl xcm_executor::traits::Convert for AssetConvert { fn convert(location: MultiLocation) -> Result { - if location == MultiLocation::parent() { - return Ok(RELAY_CURRENCY); - } - match location.clone() { MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { parachains::zeitgeist::ZTG_KEY => Ok(Asset::ZTG), - _ => Err(location.clone()), + _ => Err(location), }, MultiLocation { parents: 1, interior: X2(Parachain(para_id), GeneralKey(key)) } => { match para_id { parachains::zeitgeist::ID => match &key[..] { parachains::zeitgeist::ZTG_KEY => Ok(Asset::ZTG), - _ => Err(location.clone()), + _ => Err(location), }, - parachains::karura::ID => match &key[..] { - parachains::karura::AUSD_KEY => Ok(Asset::AUSD), - _ => Err(location.clone()), - }, - - // TODO: MOVR - _ => Err(location.clone()), + _ => Err(location), } } - _ => Err(location.clone()), + + // TODO: Asset registry + _ => Err(location), } } } diff --git a/runtime/battery-station/src/xcm_config/fees.rs b/runtime/battery-station/src/xcm_config/fees.rs index f0f647c97..dd0e53f6e 100644 --- a/runtime/battery-station/src/xcm_config/fees.rs +++ b/runtime/battery-station/src/xcm_config/fees.rs @@ -1,3 +1,20 @@ +// Copyright 2022 Zeitgeist PM LLC. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + use core::fmt::Debug; use frame_support::weights::constants::{ExtrinsicBaseWeight, WEIGHT_PER_SECOND}; use parity_scale_codec::MaxEncodedLen; diff --git a/runtime/battery-station/src/xcm_config/parachains.rs b/runtime/battery-station/src/xcm_config/parachains.rs index 41fbdb2c5..844286695 100644 --- a/runtime/battery-station/src/xcm_config/parachains.rs +++ b/runtime/battery-station/src/xcm_config/parachains.rs @@ -1,3 +1,20 @@ +// Copyright 2022 Zeitgeist PM LLC. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + /// Listing of parachains we integrate with. /// For each parachain, we are interested in stating their parachain ID /// as well as any of their token key ID that we possibly support in our diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index 7c6377661..882b3ed1f 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -3,8 +3,8 @@ cumulus-pallet-xcmp-queue = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/cumulus", optional = true } frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } -orml-currencies = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } -orml-tokens = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-currencies = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } pallet-author-mapping = { rev = "78db06c0203f61b35059304f7194ed5c10dcfda8", default-features = false, git = "https://github.com/purestake/moonbeam", optional = true } pallet-author-slot-filter = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/nimbus", optional = true } pallet-balances = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } diff --git a/runtime/zeitgeist/Cargo.toml b/runtime/zeitgeist/Cargo.toml index 5926d1032..7808a6612 100644 --- a/runtime/zeitgeist/Cargo.toml +++ b/runtime/zeitgeist/Cargo.toml @@ -6,10 +6,10 @@ frame-executive = { branch = "moonbeam-polkadot-v0.9.19", default-features = fal frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-system-rpc-runtime-api = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } -orml-benchmarking = { branch = "2022-06-v0.9.19", default-features = false, optional = true, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } -orml-currencies = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } -orml-tokens = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } -orml-traits = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-benchmarking = { branch = "7e1123e-v0.9.19", default-features = false, optional = true, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-currencies = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-traits = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } pallet-balances = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } pallet-collective = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } pallet-democracy = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } diff --git a/rust-toolchain b/rust-toolchain index dd042da89..c01060c80 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,5 +1,5 @@ [toolchain] -channel = "nightly-2022-04-13" +channel = "nightly-2022-08-24" components = ["clippy", "rustfmt"] profile = "minimal" targets = ["wasm32-unknown-unknown"] \ No newline at end of file diff --git a/zrml/orderbook-v1/Cargo.toml b/zrml/orderbook-v1/Cargo.toml index 59be5b236..ace52779c 100644 --- a/zrml/orderbook-v1/Cargo.toml +++ b/zrml/orderbook-v1/Cargo.toml @@ -3,14 +3,14 @@ frame-benchmarking = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, optional = true, git = "https://github.com/purestake/substrate" } frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } -orml-traits = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-traits = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } parity-scale-codec = { default-features = false, features = ["derive", "max-encoded-len"], version = "3.0.0" } sp-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } zeitgeist-primitives = { default-features = false, path = "../../primitives" } scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } # Mock -orml-tokens = { branch = "2022-06-v0.9.19", git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-tokens = { branch = "7e1123e-v0.9.19", git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } pallet-balances = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } sp-io = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } diff --git a/zrml/prediction-markets/Cargo.toml b/zrml/prediction-markets/Cargo.toml index 44b66670c..1a2ef1da3 100644 --- a/zrml/prediction-markets/Cargo.toml +++ b/zrml/prediction-markets/Cargo.toml @@ -2,7 +2,7 @@ frame-benchmarking = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, optional = true, git = "https://github.com/purestake/substrate" } frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } -orml-traits = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-traits = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } parity-scale-codec = { default-features = false, features = ["derive", "max-encoded-len"], version = "3.0.0" } sp-arithmetic = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } sp-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } @@ -16,8 +16,8 @@ zrml-simple-disputes = { default-features = false, path = "../simple-disputes" } # Mock -orml-currencies = { branch = "2022-06-v0.9.19", git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-tokens = { branch = "2022-06-v0.9.19", git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-currencies = { branch = "7e1123e-v0.9.19", git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-tokens = { branch = "7e1123e-v0.9.19", git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } pallet-balances = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } pallet-randomness-collective-flip = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } pallet-timestamp = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } diff --git a/zrml/swaps/Cargo.toml b/zrml/swaps/Cargo.toml index 4d1c078d0..3a74ff82f 100644 --- a/zrml/swaps/Cargo.toml +++ b/zrml/swaps/Cargo.toml @@ -2,7 +2,7 @@ frame-benchmarking = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, optional = true, git = "https://github.com/purestake/substrate" } frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } -orml-traits = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-traits = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } parity-scale-codec = { default-features = false, features = ["derive", "max-encoded-len"], version = "3.0.0" } sp-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } substrate-fixed = { default-features = false, git = "https://github.com/encointer/substrate-fixed" } @@ -14,8 +14,8 @@ zrml-rikiddo = { default-features = false, path = "../rikiddo" } # Mock -orml-currencies = { branch = "2022-06-v0.9.19", git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-tokens = { branch = "2022-06-v0.9.19", git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-currencies = { branch = "7e1123e-v0.9.19", git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-tokens = { branch = "7e1123e-v0.9.19", git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } pallet-balances = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } pallet-timestamp = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } sp-api = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate", optional = true } diff --git a/zrml/swaps/fuzz/Cargo.toml b/zrml/swaps/fuzz/Cargo.toml index 5be51cf57..ff9b325be 100644 --- a/zrml/swaps/fuzz/Cargo.toml +++ b/zrml/swaps/fuzz/Cargo.toml @@ -59,7 +59,7 @@ zrml-swaps = { features = ["mock"], path = ".." } zeitgeist-primitives = { features = ["mock"], path = "../../../primitives" } sp-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } -orml-traits = { branch = "2022-06-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } +orml-traits = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } rand = "0.8.4" [package] From 15153e81baf6692e47de137eb466a1dfe2e523d0 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 25 Sep 2022 21:17:54 +0200 Subject: [PATCH 10/59] Add asset registry and AssetProcessor implementation --- runtime/battery-station/src/lib.rs | 2 +- runtime/battery-station/src/xcm_config.rs | 23 ++++++++ .../src/xcm_config/asset_registry.rs | 53 +++++++++++++++++++ .../battery-station/src/xcm_config/config.rs | 25 +++++---- 4 files changed, 89 insertions(+), 14 deletions(-) create mode 100644 runtime/battery-station/src/xcm_config.rs create mode 100644 runtime/battery-station/src/xcm_config/asset_registry.rs diff --git a/runtime/battery-station/src/lib.rs b/runtime/battery-station/src/lib.rs index 988ac2caf..73fcfd9e0 100644 --- a/runtime/battery-station/src/lib.rs +++ b/runtime/battery-station/src/lib.rs @@ -152,7 +152,7 @@ impl pallet_sudo::Config for Runtime { impl orml_asset_registry::Config for Runtime { type AssetId = CurrencyId; type AssetProcessor = asset_registry::CustomAssetProcessor; - type AuthorityOrigin = asset_registry::AuthorityOrigin>; + type AuthorityOrigin = EnsureRootOrTwoThirdsCouncil; type Balance = Balance; type CustomMetadata = CustomMetadata; type Event = Event; diff --git a/runtime/battery-station/src/xcm_config.rs b/runtime/battery-station/src/xcm_config.rs new file mode 100644 index 000000000..a74527351 --- /dev/null +++ b/runtime/battery-station/src/xcm_config.rs @@ -0,0 +1,23 @@ +// Copyright 2022 Zeitgeist PM LLC. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +#![cfg(feature = "parachain")] + +pub mod asset_registry; +pub mod config; +pub mod fees; +pub mod parachains; \ No newline at end of file diff --git a/runtime/battery-station/src/xcm_config/asset_registry.rs b/runtime/battery-station/src/xcm_config/asset_registry.rs new file mode 100644 index 000000000..01c9cd76b --- /dev/null +++ b/runtime/battery-station/src/xcm_config/asset_registry.rs @@ -0,0 +1,53 @@ +// Copyright 2022 Zeitgeist PM LLC. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use core::marker::PhantomData; +use frame_support::{ + dispatch::RawOrigin, + traits::{EnsureOrigin, EnsureOriginWithArg}, +}; +use orml_traits::asset_registry::{AssetMetadata, AssetProcessor}; +use sp_runtime::DispatchError; + +use super::*; + +#[derive( + Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen, +)] +/// Implements orml_traits::asset_registry::AssetProcessor. Does not apply any post checks. +/// Only pre check is to ensure an asset id was passed. +pub struct CustomAssetProcessor; + +impl AssetProcessor> for CustomAssetProcessor { + fn pre_register( + id: Option, + metadata: AssetMetadata, + ) -> Result<(CurrencyId, AssetMetadata), DispatchError> { + match id { + Some(id) => Ok((id, metadata)), + None => Err(DispatchError::Other("asset-registry: AssetId is required")), + } + } + + fn post_register( + _id: CurrencyId, + _asset_metadata: AssetMetadata, + ) -> Result<(), DispatchError> { + Ok(()) + } +} + diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index e0aa55966..2a1b40855 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -16,7 +16,7 @@ // along with Zeitgeist. If not, see . use crate::{ - AccountId, Ancestry, Balance, Balances, Call, AssetManager, MaxInstructions, Origin, + AccountId, Ancestry, Balance, Balances, Call, CurrencyId, AssetManager, MaxInstructions, Origin, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, Runtime, UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; @@ -89,7 +89,6 @@ pub type Barrier = ( // Subscriptions for version tracking are OK. AllowSubscriptionsFrom, ); -type AssetT = ::CurrencyId; parameter_types! { pub CheckAccount: AccountId = PolkadotXcm::check_account(); @@ -103,17 +102,17 @@ pub type MultiAssetTransactor = MultiCurrencyAdapter< UnknownTokens, // This means that this adapter should handle any token that `AssetConvert` can convert // using AssetManager and UnknownTokens in all other cases. - IsNativeConcrete, + IsNativeConcrete, // Our chain's account ID type (we can't get away without mentioning it explicitly). sp_runtime::AccountId32, // Convert an XCM `MultiLocation` into a local account id. LocationToAccountId, // The AssetId that corresponds to the native currency. - AssetT, + CurrencyId, // Struct that provides functions to convert `Asset` <=> `MultiLocation`. AssetConvert, // In case of deposit failure, known assets will be placed in treasury. - DepositToAlternative, + DepositToAlternative, >; /// AssetConvert @@ -125,8 +124,8 @@ pub struct AssetConvert; /// Convert our `Asset` type into its `MultiLocation` representation. /// Other chains need to know how this conversion takes place in order to /// handle it on their side. -impl Convert> for AssetConvert { - fn convert(id: AssetT) -> Option { +impl Convert> for AssetConvert { + fn convert(id: CurrencyId) -> Option { let x = match id { Asset::ZTG => MultiLocation::new( 1, @@ -145,8 +144,8 @@ impl Convert> for AssetConvert { /// Convert an incoming `MultiLocation` into a `Asset` if possible. /// Here we need to know the canonical representation of all the tokens we handle in order to /// correctly convert their `MultiLocation` representation into our internal `Asset` type. -impl xcm_executor::traits::Convert for AssetConvert { - fn convert(location: MultiLocation) -> Result { +impl xcm_executor::traits::Convert for AssetConvert { + fn convert(location: MultiLocation) -> Result { match location.clone() { MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { parachains::zeitgeist::ZTG_KEY => Ok(Asset::ZTG), @@ -169,8 +168,8 @@ impl xcm_executor::traits::Convert for AssetConvert { } } -impl Convert> for AssetConvert { - fn convert(asset: MultiAsset) -> Option { +impl Convert> for AssetConvert { + fn convert(asset: MultiAsset) -> Option { if let MultiAsset { id: Concrete(location), .. } = asset { >::convert(location).ok() } else { @@ -179,8 +178,8 @@ impl Convert> for AssetConvert { } } -impl Convert> for AssetConvert { - fn convert(location: MultiLocation) -> Option { +impl Convert> for AssetConvert { + fn convert(location: MultiLocation) -> Option { >::convert(location).ok() } } From 071e50db1e8fad3abd96bc835bdb8b9b20e68354 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Mon, 26 Sep 2022 00:13:38 +0200 Subject: [PATCH 11/59] Integrate asset-registry, implement fee structure --- Cargo.lock | 113 +++-------- docs/changelog_for_devs.md | 2 +- primitives/src/asset.rs | 136 +------------ primitives/src/constants/mock.rs | 4 +- primitives/src/types.rs | 3 +- runtime/battery-station/src/lib.rs | 10 +- runtime/battery-station/src/parameters.rs | 4 +- .../src/xcm_config/asset_registry.rs | 55 +++++- .../battery-station/src/xcm_config/config.rs | 10 +- .../battery-station/src/xcm_config/fees.rs | 181 +++++------------- .../src/xcm_config/parachains.rs | 3 - runtime/zeitgeist/Cargo.toml | 4 +- runtime/zeitgeist/src/parameters.rs | 4 +- .../fuzz/orderbook_v1_full_workflow.rs | 2 +- zrml/prediction-markets/src/benchmarks.rs | 2 +- zrml/prediction-markets/src/lib.rs | 64 +++---- zrml/prediction-markets/src/migrations.rs | 2 +- zrml/prediction-markets/src/tests.rs | 40 ++-- zrml/swaps/fuzz/utils.rs | 2 +- zrml/swaps/src/lib.rs | 6 +- 20 files changed, 205 insertions(+), 442 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8ebe35923..9ddb5aeae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -468,9 +468,9 @@ dependencies = [ "orml-benchmarking", "orml-currencies", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", - "orml-unknown-tokens 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", - "orml-xcm-support 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-traits", + "orml-unknown-tokens", + "orml-xcm-support", "pallet-aura", "pallet-author-inherent", "pallet-author-mapping", @@ -5249,11 +5249,11 @@ dependencies = [ [[package]] name = "orml-asset-registry" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#f163e2cb3f93265c23ffba32fc9653618022c0be" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" dependencies = [ "frame-support", "frame-system", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-traits", "pallet-xcm", "parity-scale-codec", "scale-info", @@ -5268,7 +5268,7 @@ dependencies = [ [[package]] name = "orml-benchmarking" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" dependencies = [ "frame-benchmarking", "frame-support", @@ -5288,12 +5288,12 @@ dependencies = [ [[package]] name = "orml-currencies" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" dependencies = [ "frame-support", "frame-system", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", - "orml-utilities 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-traits", + "orml-utilities", "parity-scale-codec", "scale-info", "serde", @@ -5305,11 +5305,11 @@ dependencies = [ [[package]] name = "orml-tokens" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" dependencies = [ "frame-support", "frame-system", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-traits", "parity-scale-codec", "scale-info", "serde", @@ -5320,12 +5320,12 @@ dependencies = [ [[package]] name = "orml-traits" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" dependencies = [ "frame-support", "impl-trait-for-tuples", "num-traits", - "orml-utilities 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-utilities", "parity-scale-codec", "scale-info", "serde", @@ -5335,47 +5335,14 @@ dependencies = [ "xcm", ] -[[package]] -name = "orml-traits" -version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest#d6a7fb53042ab3bf4a5b02d597a14cf02f43ba97" -dependencies = [ - "frame-support", - "impl-trait-for-tuples", - "num-traits", - "orml-utilities 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest)", - "parity-scale-codec", - "scale-info", - "serde", - "sp-io", - "sp-runtime", - "sp-std", - "xcm", -] - -[[package]] -name = "orml-unknown-tokens" -version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" -dependencies = [ - "frame-support", - "frame-system", - "orml-xcm-support 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", - "parity-scale-codec", - "scale-info", - "serde", - "sp-std", - "xcm", -] - [[package]] name = "orml-unknown-tokens" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest#d6a7fb53042ab3bf4a5b02d597a14cf02f43ba97" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" dependencies = [ "frame-support", "frame-system", - "orml-xcm-support 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest)", + "orml-xcm-support", "parity-scale-codec", "scale-info", "serde", @@ -5386,7 +5353,7 @@ dependencies = [ [[package]] name = "orml-utilities" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" dependencies = [ "frame-support", "parity-scale-codec", @@ -5397,41 +5364,13 @@ dependencies = [ "sp-std", ] -[[package]] -name = "orml-utilities" -version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest#d6a7fb53042ab3bf4a5b02d597a14cf02f43ba97" -dependencies = [ - "frame-support", - "parity-scale-codec", - "scale-info", - "serde", - "sp-io", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "orml-xcm-support" -version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#3ce73acad85fb10b3325ebfbbdb2c1d75b0bd981" -dependencies = [ - "frame-support", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", - "parity-scale-codec", - "sp-runtime", - "sp-std", - "xcm", - "xcm-executor", -] - [[package]] name = "orml-xcm-support" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest#d6a7fb53042ab3bf4a5b02d597a14cf02f43ba97" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" dependencies = [ "frame-support", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest)", + "orml-traits", "parity-scale-codec", "sp-runtime", "sp-std", @@ -12734,7 +12673,7 @@ dependencies = [ "frame-system", "orml-currencies", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-traits", "parity-scale-codec", "scale-info", "serde", @@ -12769,9 +12708,9 @@ dependencies = [ "orml-benchmarking", "orml-currencies", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", - "orml-unknown-tokens 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest)", - "orml-xcm-support 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=polkadot-0.9.19-latest)", + "orml-traits", + "orml-unknown-tokens", + "orml-xcm-support", "pallet-aura", "pallet-author-inherent", "pallet-author-mapping", @@ -12930,7 +12869,7 @@ dependencies = [ "frame-support", "frame-system", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-traits", "pallet-balances", "parity-scale-codec", "scale-info", @@ -12961,7 +12900,7 @@ dependencies = [ "more-asserts", "orml-currencies", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-traits", "pallet-balances", "pallet-randomness-collective-flip", "pallet-timestamp", @@ -13082,7 +13021,7 @@ dependencies = [ "more-asserts", "orml-currencies", "orml-tokens", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-traits", "pallet-balances", "pallet-timestamp", "parity-scale-codec", @@ -13107,7 +13046,7 @@ dependencies = [ "arbitrary", "frame-support", "libfuzzer-sys", - "orml-traits 0.4.1-dev (git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19)", + "orml-traits", "rand 0.8.5", "sp-runtime", "zeitgeist-primitives", diff --git a/docs/changelog_for_devs.md b/docs/changelog_for_devs.md index 9aeb685a4..1b1307552 100644 --- a/docs/changelog_for_devs.md +++ b/docs/changelog_for_devs.md @@ -1,5 +1,5 @@ # v0.3.6 -- Asset::Ztg was renamed to Asset::ZTG. All currency symbols will be written in uppercase. +- Asset::Ztg was renamed to Asset::Ztg. All currency symbols will be written in uppercase. - Added two more currencies: AUSD and KSM (or ROC on testnet) - Added xTokens pallet to transfer tokens accross chains diff --git a/primitives/src/asset.rs b/primitives/src/asset.rs index b91b8836a..90079f24b 100644 --- a/primitives/src/asset.rs +++ b/primitives/src/asset.rs @@ -15,14 +15,9 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::types::{CategoryIndex, MarketId, PoolId, SerdeWrapper}; -use alloc::{vec, vec::Vec}; +use crate::types::{CategoryIndex, PoolId, SerdeWrapper}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; -use bstringify::bstringify; -use sp_runtime::RuntimeDebug; -#[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; /// The `Asset` enum represents all types of assets available in the Zeitgeist /// system. @@ -33,140 +28,17 @@ use serde::{Deserialize, Serialize}; #[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] #[derive( - Clone, Copy, Debug, Decode, Eq, Encode, MaxEncodedLen, Ord, PartialEq, PartialOrd, TypeInfo, + Clone, Copy, Debug, Decode, Default, Eq, Encode, MaxEncodedLen, Ord, PartialEq, PartialOrd, TypeInfo, )] pub enum Asset { CategoricalOutcome(MI, CategoryIndex), ScalarOutcome(MI, ScalarPosition), CombinatorialOutcome, PoolShare(SerdeWrapper), - ZTG, - // TODO: Use either Roc in Battery Station or KSM on mainnet - ROC, - AUSD, -} - -impl Asset { - pub fn is_token(&self) -> bool { - !matches!(self, Asset::CategoricalOutcome(_, _) | Asset::ScalarOutcome(_, _) | Asset::CombinatorialOutcome | Asset::PoolShare(_)) - } - - pub fn is_outcome_token(&self) -> bool { - matches!(self, Asset::CategoricalOutcome(_, _) | Asset::ScalarOutcome(_, _) | Asset::CombinatorialOutcome) - } - - pub fn is_pool_share(&self) -> bool { - matches!(self, Asset::PoolShare(_)) - } + #[default] Ztg, + ForeignAsset(u32), } -pub trait TokenInfo { - fn currency_id(&self) -> Option; - fn name(&self) -> Option<&str>; - fn symbol(&self) -> Option<&str>; - fn decimals(&self) -> Option; -} - -macro_rules! create_currency_id { - ($(#[$meta:meta])* - $vis:vis enum TokenSymbol { - $($(#[$vmeta:meta])* $symbol:ident($name:expr, $deci:literal) = $val:literal,)* - }) => { - $(#[$meta])* - $vis enum TokenSymbol { - $($(#[$vmeta])* $symbol = $val,)* - } - - impl TryFrom for TokenSymbol { - type Error = (); - - fn try_from(v: u8) -> Result { - match v { - $($val => Ok(TokenSymbol::$symbol),)* - _ => Err(()), - } - } - } - - impl Into for TokenSymbol { - fn into(self) -> u8 { - match self { - $(TokenSymbol::$symbol => ($val),)* - } - } - } - - impl TryFrom> for Asset { - type Error = (); - fn try_from(v: Vec) -> Result, ()> { - match v.as_slice() { - $(bstringify!($symbol) => Ok(Asset::$symbol),)* - _ => Err(()), - } - } - } - - impl TokenInfo for Asset { - fn currency_id(&self) -> Option { - match self { - $(Asset::$symbol => Some($val),)* - _ => None, - } - } - fn name(&self) -> Option<&str> { - match self { - $(Asset::$symbol => Some($name),)* - _ => None, - } - } - fn symbol(&self) -> Option<&str> { - match self { - $(Asset::$symbol => Some(stringify!($symbol)),)* - _ => None, - } - } - fn decimals(&self) -> Option { - match self { - $(Asset::$symbol => Some($deci),)* - _ => None, - } - } - } - - $(pub const $symbol: Asset = Asset::$symbol;)* - - impl TokenSymbol { - pub fn get_info() -> Vec<(&'static str, u32)> { - vec![ - $((stringify!($symbol), $deci),)* - ] - } - } - } -} - -create_currency_id! { - // Represent a Token symbol with 8 bit - // - // 0 - 19: Zeitgeist & Rococo/Kusama native tokens - // 20 - 49: Bridged tokens - // 50 - 127: Rococo / Kusama parachain tokens - // 128 - 255: Unreserved - #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord, TypeInfo, MaxEncodedLen)] - #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] - #[repr(u8)] - pub enum TokenSymbol { - // TODO: Use either ROC or KSM depending on runtime that's build - ROC("Rococo", 12) = 0, - // 0 - 19: Zeitgeist & Rococo/Kusama native tokens - ZTG("Zeitgeist", 10) = 1, - // 20 - 49: Bridged tokens - // 50 - 127: Rococo / Kusama parachain tokens - AUSD("Acala Dollar", 12) = 50, - } -} - - /// In a scalar market, users can either choose a `Long` position, /// meaning that they think the outcome will be closer to the upper bound diff --git a/primitives/src/constants/mock.rs b/primitives/src/constants/mock.rs index 60127625a..0ea728082 100644 --- a/primitives/src/constants/mock.rs +++ b/primitives/src/constants/mock.rs @@ -79,14 +79,14 @@ parameter_types! { // ORML parameter_types! { // ORML - pub const GetNativeCurrencyId: CurrencyId = Asset::ZTG; + pub const GetNativeCurrencyId: CurrencyId = Asset::Ztg; } parameter_type_with_key! { // Well, not every asset is a currency ¯\_(ツ)_/¯ pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance { match currency_id { - Asset::ZTG => ExistentialDeposit::get(), + Asset::Ztg => ExistentialDeposit::get(), _ => 0 } }; diff --git a/primitives/src/types.rs b/primitives/src/types.rs index c06478a7e..2d0a331d2 100644 --- a/primitives/src/types.rs +++ b/primitives/src/types.rs @@ -21,7 +21,8 @@ pub use crate::{ }; #[cfg(feature = "arbitrary")] use arbitrary::{Arbitrary, Result, Unstructured}; -use frame_support::dispatch::{Decode, Encode, Weight}; +use frame_support::dispatch::Weight; +use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::{ generic, diff --git a/runtime/battery-station/src/lib.rs b/runtime/battery-station/src/lib.rs index 73fcfd9e0..238cb9b61 100644 --- a/runtime/battery-station/src/lib.rs +++ b/runtime/battery-station/src/lib.rs @@ -53,10 +53,10 @@ use zeitgeist_primitives::{constants::*, types::*}; use zrml_rikiddo::types::{EmaMarketVolume, FeeSigmoid, RikiddoSigmoidMV}; #[cfg(feature = "parachain")] use { - frame_support::traits::{Everything, Nothing}, + frame_support::traits::{AsEnsureOriginWithArg, Everything, Nothing}, frame_system::EnsureSigned, xcm_builder::{EnsureXcmOrigin, FixedWeightBounds, LocationInverter}, - xcm_config::{config::{LocalOriginToLocation, XcmConfig, XcmOriginToTransactDispatchOrigin, XcmRouter}}, + xcm_config::{asset_registry::{CustomAssetProcessor, CustomMetadata}, config::{LocalOriginToLocation, XcmConfig, XcmOriginToTransactDispatchOrigin, XcmRouter}}, }; use frame_support::construct_runtime; @@ -138,7 +138,7 @@ create_runtime_with_additional_pallets!( create_runtime_with_additional_pallets!( // Others Sudo: pallet_sudo::{Call, Config, Event, Pallet, Storage} = 150, - AssetRegistry: orml_unknown_tokens::{Pallet, Storage, Event} = 151, + AssetRegistry: orml_asset_registry::{Call, Config, Event, Pallet, Storage} = 151, UnknownTokens: orml_unknown_tokens::{Pallet, Storage, Event} = 152, ); @@ -151,8 +151,8 @@ impl pallet_sudo::Config for Runtime { #[cfg(feature = "parachain")] impl orml_asset_registry::Config for Runtime { type AssetId = CurrencyId; - type AssetProcessor = asset_registry::CustomAssetProcessor; - type AuthorityOrigin = EnsureRootOrTwoThirdsCouncil; + type AssetProcessor = CustomAssetProcessor; + type AuthorityOrigin = AsEnsureOriginWithArg; type Balance = Balance; type CustomMetadata = CustomMetadata; type Event = Event; diff --git a/runtime/battery-station/src/parameters.rs b/runtime/battery-station/src/parameters.rs index a0ccb74b4..6814ea199 100644 --- a/runtime/battery-station/src/parameters.rs +++ b/runtime/battery-station/src/parameters.rs @@ -131,7 +131,7 @@ parameter_types! { pub const DepositFactor: Balance = deposit(0, 32); // ORML - pub const GetNativeCurrencyId: CurrencyId = Asset::ZTG; + pub const GetNativeCurrencyId: CurrencyId = Asset::Ztg; pub DustAccount: AccountId = PalletId(*b"orml/dst").into_account(); // Prediction Market parameters @@ -298,7 +298,7 @@ parameter_type_with_key! { // Well, not every asset is a currency ¯\_(ツ)_/¯ pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance { match currency_id { - Asset::ZTG => ExistentialDeposit::get(), + Asset::Ztg => ExistentialDeposit::get(), _ => 0 } }; diff --git a/runtime/battery-station/src/xcm_config/asset_registry.rs b/runtime/battery-station/src/xcm_config/asset_registry.rs index 01c9cd76b..1f3ac9a2b 100644 --- a/runtime/battery-station/src/xcm_config/asset_registry.rs +++ b/runtime/battery-station/src/xcm_config/asset_registry.rs @@ -15,15 +15,11 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use core::marker::PhantomData; -use frame_support::{ - dispatch::RawOrigin, - traits::{EnsureOrigin, EnsureOriginWithArg}, -}; +use crate::{Balance, CurrencyId}; use orml_traits::asset_registry::{AssetMetadata, AssetProcessor}; +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use sp_runtime::DispatchError; - -use super::*; +use scale_info::TypeInfo; #[derive( Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen, @@ -51,3 +47,48 @@ impl AssetProcessor> for Cust } } +#[derive( + Clone, + Copy, + Default, + PartialOrd, + Ord, + PartialEq, + Eq, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, +)] +/// Custom XC asset metadata +pub struct CustomMetadata { + /// XCM-related metadata. + pub xcm: XcmMetadata, + + /// Whether an asset can be used in pools. + pub allow_in_pool: bool, +} + +#[derive( + Clone, + Copy, + Default, + PartialOrd, + Ord, + PartialEq, + Eq, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, +)] +pub struct XcmMetadata { + /// The factor used to determine the fee. + /// It is multiplied by the fee that would have been paind in native currency, so it represents + /// the ratio `native_price / other_asset_price`. It is a fixed point decimal number containing + /// as many fractional decimals as the asset it is used for contains. + /// Should be updated regularly. + pub fee_factor: Option, +} \ No newline at end of file diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 2a1b40855..c587a55de 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -17,7 +17,7 @@ use crate::{ AccountId, Ancestry, Balance, Balances, Call, CurrencyId, AssetManager, MaxInstructions, Origin, - ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, Runtime, + ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; use super::parachains; @@ -104,7 +104,7 @@ pub type MultiAssetTransactor = MultiCurrencyAdapter< // using AssetManager and UnknownTokens in all other cases. IsNativeConcrete, // Our chain's account ID type (we can't get away without mentioning it explicitly). - sp_runtime::AccountId32, + AccountId, // Convert an XCM `MultiLocation` into a local account id. LocationToAccountId, // The AssetId that corresponds to the native currency. @@ -127,7 +127,7 @@ pub struct AssetConvert; impl Convert> for AssetConvert { fn convert(id: CurrencyId) -> Option { let x = match id { - Asset::ZTG => MultiLocation::new( + Asset::Ztg => MultiLocation::new( 1, X2( Parachain(parachains::zeitgeist::ID), @@ -148,13 +148,13 @@ impl xcm_executor::traits::Convert for AssetConvert { fn convert(location: MultiLocation) -> Result { match location.clone() { MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { - parachains::zeitgeist::ZTG_KEY => Ok(Asset::ZTG), + parachains::zeitgeist::ZTG_KEY => Ok(Asset::Ztg), _ => Err(location), }, MultiLocation { parents: 1, interior: X2(Parachain(para_id), GeneralKey(key)) } => { match para_id { parachains::zeitgeist::ID => match &key[..] { - parachains::zeitgeist::ZTG_KEY => Ok(Asset::ZTG), + parachains::zeitgeist::ZTG_KEY => Ok(Asset::Ztg), _ => Err(location), }, diff --git a/runtime/battery-station/src/xcm_config/fees.rs b/runtime/battery-station/src/xcm_config/fees.rs index dd0e53f6e..9642240b6 100644 --- a/runtime/battery-station/src/xcm_config/fees.rs +++ b/runtime/battery-station/src/xcm_config/fees.rs @@ -15,153 +15,66 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use core::fmt::Debug; +use crate::{Balance, CurrencyId, xcm_config::asset_registry::CustomMetadata}; +use core::{marker::PhantomData}; use frame_support::weights::constants::{ExtrinsicBaseWeight, WEIGHT_PER_SECOND}; -use parity_scale_codec::MaxEncodedLen; -use zeitgeist_primitives::types::{Balance, Asset, TokenInfo}; +use xcm::latest::MultiLocation; +use zeitgeist_primitives::{ + constants::BalanceFractionalDecimals, +}; +use zrml_swaps::check_arithm_rslt::CheckArithmRslt; -// The fee cost per second for transferring the ztg token -pub fn ztg_per_second() -> Balance { - base_tx_per_second(>::ZTG) +/// The fee cost per second for transferring the native token in cents. +pub fn native_per_second() -> Balance { + default_per_second(BalanceFractionalDecimals::get().into()) } -// The fee cost per second for transferring the KSM token -// We assume that KSM price is 50x ZTG price -// TODO: Use either ksm_per_second or roc_per_second depending on current runtime -/* -pub fn ksm_per_second() -> Balance { - base_tx_per_second(>::KSM) / 50 +pub fn default_per_second(decimals: u32) -> Balance { + let base_weight = Balance::from(ExtrinsicBaseWeight::get()); + let default_per_second = (WEIGHT_PER_SECOND as u128) / base_weight; + default_per_second * base_fee(decimals) } -*/ -// The fee cost per second for transferring the ROC token -// We assume that ROC "price" is 10x ZBS price -pub fn roc_per_second() -> Balance { - base_tx_per_second(>::ROC) / 10 +fn base_fee(decimals: u32) -> Balance { + cent(decimals).saturating_div(10) } - -// The fee cost per second for transferring the aUSD token -// We assume that 1 aUSD = 1 USD = 1 ZTG -pub fn ausd_per_second() -> Balance { - base_tx_per_second(>::AUSD) +/// 1 Asset in fixed point decimal representation +pub fn dollar(decimals: u32) -> Balance { + 10u128.saturating_pow(decimals) } - -// The fee cost per second for any Asset -fn base_tx_per_second(currency: Asset) -> Balance { - let base_weight = Balance::from(ExtrinsicBaseWeight::get()); - let base_tx_per_second = (WEIGHT_PER_SECOND as u128) / base_weight; - base_tx_per_second * base_tx(currency) +/// 0.01 Asset in fixed point decimal presentation +pub fn cent(decimals: u32) -> Balance { + dollar(decimals).saturating_div(100) } -// Base transaction fee that reflects 0.1 cent for any Asset -fn base_tx(currency: Asset) -> Balance { - cent(currency) / 10 +pub fn bmul(a: u128, b: u128, base: u128) -> Option { + let c0 = a.check_mul_rslt(&b).ok()?; + let c1 = c0.check_add_rslt(&base.check_div_rslt(&2).ok()?).ok()?; + c1.check_div_rslt(&base).ok() } -// 1 Asset in fixed point decimal representation -pub fn dollar(currency_id: Asset) -> Balance { - // We assume every asset is registered properly. For any non-currency - // asset we will use the native precision of 10 decimal places - match currency_id.decimals() { - Some(decimals) => decimals.into(), - None => { - log::warn!("dollar() was called for a non-currency asset: {:?}", currency_id); - 10 +/// Our FixedConversionRateProvider, used to charge XCM-related fees for tokens registered in +/// the asset registry that were not already handled by native Trader rules. +pub struct FixedConversionRateProvider(PhantomData); + +impl< + OrmlAssetRegistry: orml_traits::asset_registry::Inspect< + AssetId = CurrencyId, + Balance = Balance, + CustomMetadata = CustomMetadata, + >, + > orml_traits::FixedConversionRateProvider for FixedConversionRateProvider +{ + fn get_fee_per_second(location: &MultiLocation) -> Option { + let metadata = OrmlAssetRegistry::metadata_by_location(&location)?; + let default_per_second = default_per_second(metadata.decimals); + + if let Some(fee_factor) = metadata.additional.xcm.fee_factor { + bmul(default_per_second, fee_factor, metadata.decimals.into()) + } else { + Some(default_per_second) } } -} - -// 0.01 Asset in fixed point decimal presentation -pub fn cent(currency_id: Asset) -> Balance { - dollar(currency_id) / 100 -} - - -/* -parameter_types! { - // One XCM operation is 200_000_000 weight, cross-chain transfer ~= 2x of transfer. - pub const UnitWeightCost: Weight = 200_000_000; - pub KsmPerSecond: (AssetId, u128) = (MultiLocation::parent().into(), ksm_per_second()); - pub KusdPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 0, - X1(GeneralKey(KUSD.encode())), - ).into(), - // kUSD:KSM = 400:1 - ksm_per_second() * 400 - ); - pub KarPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 0, - X1(GeneralKey(KAR.encode())), - ).into(), - kar_per_second() - ); - pub LksmPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 0, - X1(GeneralKey(LKSM.encode())), - ).into(), - // LKSM:KSM = 10:1 - ksm_per_second() * 10 - ); - pub PHAPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 1, - X1(Parachain(parachains::phala::ID)), - ).into(), - // PHA:KSM = 400:1 - ksm_per_second() * 400 - ); - pub BncPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 1, - X2(Parachain(parachains::bifrost::ID), GeneralKey(parachains::bifrost::BNC_KEY.to_vec())), - ).into(), - // BNC:KSM = 80:1 - ksm_per_second() * 80 - ); - pub VsksmPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 1, - X2(Parachain(parachains::bifrost::ID), GeneralKey(parachains::bifrost::VSKSM_KEY.to_vec())), - ).into(), - // VSKSM:KSM = 1:1 - ksm_per_second() - ); - pub KbtcPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 1, - X2(Parachain(parachains::kintsugi::ID), GeneralKey(parachains::kintsugi::KBTC_KEY.to_vec())), - ).into(), - // KBTC:KSM = 1:150 & Satoshi:Planck = 1:10_000 - ksm_per_second() / 1_500_000 - ); - pub KintPerSecond: (AssetId, u128) = ( - MultiLocation::new( - 1, - X2(Parachain(parachains::kintsugi::ID), GeneralKey(parachains::kintsugi::KINT_KEY.to_vec())), - ).into(), - // KINT:KSM = 4:3 - (ksm_per_second() * 4) / 3 - ); - - pub BaseRate: u128 = kar_per_second(); -} - -pub type Trader = ( - FixedRateOfAsset>, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfFungible, - FixedRateOfAsset>, - FixedRateOfAsset>, -);*/ \ No newline at end of file +} \ No newline at end of file diff --git a/runtime/battery-station/src/xcm_config/parachains.rs b/runtime/battery-station/src/xcm_config/parachains.rs index 844286695..853786a94 100644 --- a/runtime/battery-station/src/xcm_config/parachains.rs +++ b/runtime/battery-station/src/xcm_config/parachains.rs @@ -31,6 +31,3 @@ pub mod zeitgeist { pub const ID: u32 = 2101; pub const ZTG_KEY: &[u8] = &[0, 1]; } - -// TODO: Integrate MOVR -// TODO: Integrate USDT \ No newline at end of file diff --git a/runtime/zeitgeist/Cargo.toml b/runtime/zeitgeist/Cargo.toml index 7808a6612..a8aa0aa2a 100644 --- a/runtime/zeitgeist/Cargo.toml +++ b/runtime/zeitgeist/Cargo.toml @@ -70,8 +70,8 @@ parachain-staking = { rev = "78db06c0203f61b35059304f7194ed5c10dcfda8", default- polkadot-parachain = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } # XCM -orml-xcm-support = { branch = "polkadot-0.9.19-latest", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-unknown-tokens = { branch = "polkadot-0.9.19-latest", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-unknown-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } pallet-xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm-builder = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } diff --git a/runtime/zeitgeist/src/parameters.rs b/runtime/zeitgeist/src/parameters.rs index 7654c4216..43a18ba62 100644 --- a/runtime/zeitgeist/src/parameters.rs +++ b/runtime/zeitgeist/src/parameters.rs @@ -131,7 +131,7 @@ parameter_types! { pub const DepositFactor: Balance = deposit(0, 32); // ORML - pub const GetNativeCurrencyId: CurrencyId = Asset::ZTG; + pub const GetNativeCurrencyId: CurrencyId = Asset::Ztg; pub DustAccount: AccountId = PalletId(*b"orml/dst").into_account(); // Prediction Market parameters @@ -296,7 +296,7 @@ parameter_type_with_key! { // Well, not every asset is a currency ¯\_(ツ)_/¯ pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance { match currency_id { - Asset::ZTG => ExistentialDeposit::get(), + Asset::Ztg => ExistentialDeposit::get(), _ => 0 } }; diff --git a/zrml/orderbook-v1/fuzz/orderbook_v1_full_workflow.rs b/zrml/orderbook-v1/fuzz/orderbook_v1_full_workflow.rs index cb8497a08..c624197df 100644 --- a/zrml/orderbook-v1/fuzz/orderbook_v1_full_workflow.rs +++ b/zrml/orderbook-v1/fuzz/orderbook_v1_full_workflow.rs @@ -103,7 +103,7 @@ fn asset(seed: (u128, u16)) -> Asset { } 2 => Asset::CombinatorialOutcome, 3 => Asset::PoolShare(SerdeWrapper(seed0)), - _ => Asset::ZTG, + _ => Asset::Ztg, } } diff --git a/zrml/prediction-markets/src/benchmarks.rs b/zrml/prediction-markets/src/benchmarks.rs index 9d3fab1e2..01f6e41dd 100644 --- a/zrml/prediction-markets/src/benchmarks.rs +++ b/zrml/prediction-markets/src/benchmarks.rs @@ -59,7 +59,7 @@ fn create_market_common_parameters( &'static str, > { let caller: T::AccountId = whitelisted_caller(); - let _ = T::AssetManager::deposit(Asset::ZTG, &caller, (u128::MAX).saturated_into()); + let _ = T::AssetManager::deposit(Asset::Ztg, &caller, (u128::MAX).saturated_into()); let oracle = caller.clone(); let period = MarketPeriod::Timestamp(T::MinSubsidyPeriod::get()..T::MaxSubsidyPeriod::get()); let mut metadata = [0u8; 50]; diff --git a/zrml/prediction-markets/src/lib.rs b/zrml/prediction-markets/src/lib.rs index 10cbe2900..b98f3cfbc 100644 --- a/zrml/prediction-markets/src/lib.rs +++ b/zrml/prediction-markets/src/lib.rs @@ -180,7 +180,7 @@ mod pallet { let slash_market_creator = |amount| { T::AssetManager::slash_reserved_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &market.creator, amount, ); @@ -216,9 +216,9 @@ mod pallet { } } T::AssetManager::slash( - Asset::ZTG, + Asset::Ztg, &market_account, - T::AssetManager::free_balance(Asset::ZTG, &market_account), + T::AssetManager::free_balance(Asset::Ztg, &market_account), ); if let Ok(pool_id) = T::MarketCommons::market_pool(&market_id) { T::Swaps::destroy_pool(pool_id)?; @@ -345,7 +345,7 @@ mod pallet { T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &m.creator, T::AdvisoryBond::get(), ); @@ -402,7 +402,7 @@ mod pallet { Self::validate_dispute(&disputes, &market, num_disputes, &outcome)?; T::AssetManager::reserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &who, default_dispute_bond::(disputes.len()), )?; @@ -557,7 +557,7 @@ mod pallet { let required_bond = T::ValidityBond::get().saturating_add(T::OracleBond::get()); T::AssetManager::reserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &sender, required_bond, )?; @@ -571,7 +571,7 @@ mod pallet { let required_bond = T::AdvisoryBond::get().saturating_add(T::OracleBond::get()); T::AssetManager::reserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &sender, required_bond, )?; @@ -691,7 +691,7 @@ mod pallet { Self::ensure_market_is_active(&market)?; let mut assets = Self::outcome_assets(market_id, &market); - let base_asset = Asset::ZTG; + let base_asset = Asset::Ztg; assets.push(base_asset); let base_asset_weight = weights.iter().fold(0u128, |acc, val| acc.saturating_add(*val)); weights.push(base_asset_weight); @@ -771,7 +771,7 @@ mod pallet { // Ensure the market account has enough to pay out - if this is // ever not true then we have an accounting problem. ensure!( - T::AssetManager::free_balance(Asset::ZTG, &market_account) + T::AssetManager::free_balance(Asset::Ztg, &market_account) >= winning_balance, Error::::InsufficientFundsInMarketAccount, ); @@ -825,7 +825,7 @@ mod pallet { // Ensure the market account has enough to pay out - if this is // ever not true then we have an accounting problem. ensure!( - T::AssetManager::free_balance(Asset::ZTG, &market_account) + T::AssetManager::free_balance(Asset::Ztg, &market_account) >= long_payout.saturating_add(short_payout), Error::::InsufficientFundsInMarketAccount, ); @@ -842,10 +842,10 @@ mod pallet { T::AssetManager::slash(currency_id, &sender, balance); // Pay out the winner. - let remaining_bal = T::AssetManager::free_balance(Asset::ZTG, &market_account); + let remaining_bal = T::AssetManager::free_balance(Asset::Ztg, &market_account); let actual_payout = payout.min(remaining_bal); - T::AssetManager::transfer(Asset::ZTG, &market_account, &sender, actual_payout)?; + T::AssetManager::transfer(Asset::Ztg, &market_account, &sender, actual_payout)?; // The if-check prevents scalar markets to emit events even if sender only owns one // of the outcome tokens. if balance != >::zero() { @@ -976,7 +976,7 @@ mod pallet { let market_account = Self::market_account(market_id); ensure!( - T::AssetManager::free_balance(Asset::ZTG, &market_account) >= amount, + T::AssetManager::free_balance(Asset::Ztg, &market_account) >= amount, "Market account does not have sufficient reserves.", ); @@ -997,7 +997,7 @@ mod pallet { T::AssetManager::slash(*asset, &sender, amount); } - T::AssetManager::transfer(Asset::ZTG, &market_account, &sender, amount)?; + T::AssetManager::transfer(Asset::Ztg, &market_account, &sender, amount)?; Self::deposit_event(Event::SoldCompleteSet(market_id, amount, sender)); let assets_len: u32 = assets.len().saturated_into(); @@ -1525,7 +1525,7 @@ mod pallet { ) -> DispatchResultWithPostInfo { ensure!(amount != BalanceOf::::zero(), Error::::ZeroAmount); ensure!( - T::AssetManager::free_balance(Asset::ZTG, &who) >= amount, + T::AssetManager::free_balance(Asset::Ztg, &who) >= amount, Error::::NotEnoughBalance ); @@ -1534,7 +1534,7 @@ mod pallet { Self::ensure_market_is_active(&market)?; let market_account = Self::market_account(market_id); - T::AssetManager::transfer(Asset::ZTG, &who, &market_account, amount)?; + T::AssetManager::transfer(Asset::Ztg, &who, &market_account, amount)?; let assets = Self::outcome_assets(market_id, &market); for asset in assets.iter() { @@ -1556,13 +1556,13 @@ mod pallet { let creator = &market.creator; T::AssetManager::slash_reserved_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, creator, T::AdvisoryBond::get(), ); T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, creator, T::OracleBond::get(), ); @@ -1580,13 +1580,13 @@ mod pallet { let creator = &market.creator; T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, creator, T::AdvisoryBond::get(), ); T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, creator, T::OracleBond::get(), ); @@ -1829,7 +1829,7 @@ mod pallet { if market.creation == MarketCreation::Permissionless { T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &market.creator, T::ValidityBond::get(), ); @@ -1846,14 +1846,14 @@ mod pallet { if report.by == market.oracle { T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &market.creator, T::OracleBond::get(), ); } else { let excess = T::AssetManager::slash_reserved_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &market.creator, T::OracleBond::get(), ); @@ -1861,7 +1861,7 @@ mod pallet { let negative_imbalance = T::OracleBond::get().saturating_sub(excess); if let Err(err) = - T::AssetManager::deposit(Asset::ZTG, &report.by, negative_imbalance) + T::AssetManager::deposit(Asset::Ztg, &report.by, negative_imbalance) { log::warn!( "[PredictionMarkets] Cannot deposit to the reporter. error: {:?}", @@ -1898,14 +1898,14 @@ mod pallet { if report.outcome == resolved_outcome { T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &market.creator, T::OracleBond::get(), ); } else { let excess = T::AssetManager::slash_reserved_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &market.creator, T::OracleBond::get(), ); @@ -1920,7 +1920,7 @@ mod pallet { if dispute.outcome == resolved_outcome { T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &dispute.by, actual_bond, ); @@ -1929,7 +1929,7 @@ mod pallet { } else { let excess = T::AssetManager::slash_reserved_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &dispute.by, actual_bond, ); @@ -1952,7 +1952,7 @@ mod pallet { overall_imbalance = overall_imbalance.saturating_sub(reward); if let Err(err) = - T::AssetManager::deposit(Asset::ZTG, correct_reporter, reward) + T::AssetManager::deposit(Asset::Ztg, correct_reporter, reward) { log::warn!( "[PredictionMarkets] Cannot deposit to the correct reporter. \ @@ -2086,7 +2086,7 @@ mod pallet { .saturating_add(T::OracleBond::get()); T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &m.creator, required_bond, ); @@ -2095,7 +2095,7 @@ mod pallet { // was approved. Approval is inevitable to reach this. T::AssetManager::unreserve_named( &Self::reserve_id(), - Asset::ZTG, + Asset::Ztg, &m.creator, T::OracleBond::get(), ); @@ -2309,7 +2309,7 @@ mod pallet { ); let mut assets = Self::outcome_assets(market_id, market); - let base_asset = Asset::ZTG; + let base_asset = Asset::Ztg; assets.push(base_asset); let total_assets = assets.len(); diff --git a/zrml/prediction-markets/src/migrations.rs b/zrml/prediction-markets/src/migrations.rs index c7a3ba906..6fbbd5c2d 100644 --- a/zrml/prediction-markets/src/migrations.rs +++ b/zrml/prediction-markets/src/migrations.rs @@ -438,7 +438,7 @@ mod tests { fn test_market_ids_per_open_block_on_runtime_upgrade() { ExtBuilder::default().build().execute_with(|| { setup_chain(); - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 1_000 * BASE)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 1_000 * BASE)); // Markets which end here will have to be closed on migration: let time_11: MomentOf = (11 * MILLISECS_PER_BLOCK).into(); diff --git a/zrml/prediction-markets/src/tests.rs b/zrml/prediction-markets/src/tests.rs index 5a3402976..f5b1c3112 100644 --- a/zrml/prediction-markets/src/tests.rs +++ b/zrml/prediction-markets/src/tests.rs @@ -217,7 +217,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_active() { 0..2, ScoringRule::CPMM, ); - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -249,7 +249,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_reported() { 0, OutcomeReport::Categorical(1) )); - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -286,7 +286,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_disputed() { 0, OutcomeReport::Categorical(0) )); - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -320,7 +320,7 @@ fn admin_destroy_market_correctly_slashes_permissionless_market_resolved() { )); run_blocks(::DisputePeriod::get()); assert_eq!(Balances::reserved_balance_named(&PredictionMarkets::reserve_id(), &ALICE), 0); - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -345,7 +345,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_proposed() { 0..1, ScoringRule::CPMM, ); - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -371,7 +371,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_active() { ScoringRule::CPMM, ); assert_ok!(PredictionMarkets::approve_market(Origin::signed(SUDO), 0)); - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -404,7 +404,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_reported() { 0, OutcomeReport::Categorical(1) )); - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -442,7 +442,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_disputed() { 0, OutcomeReport::Categorical(0) )); - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -477,7 +477,7 @@ fn admin_destroy_market_correctly_slashes_advised_market_resolved() { )); run_blocks(::ReportingPeriod::get().into()); // Wait until market resolves assert_eq!(Balances::reserved_balance_named(&PredictionMarkets::reserve_id(), &ALICE), 0); - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -514,20 +514,20 @@ fn admin_destroy_market_correctly_cleans_up_accounts() { let pool_id = 0; let pool_account = Swaps::pool_account_id(pool_id); let market_account = PredictionMarkets::market_account(market_id); - let alice_ztg_before = AssetManager::free_balance(Asset::ZTG, &ALICE); + let alice_ztg_before = AssetManager::free_balance(Asset::Ztg, &ALICE); assert_ok!(PredictionMarkets::admin_destroy_market(Origin::signed(SUDO), 0)); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 0), &pool_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 1), &pool_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 2), &pool_account), 0); - assert_eq!(AssetManager::free_balance(Asset::ZTG, &pool_account), 0); + assert_eq!(AssetManager::free_balance(Asset::Ztg, &pool_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 0), &market_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 1), &market_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 2), &market_account), 0); - assert_eq!(AssetManager::free_balance(Asset::ZTG, &market_account), 0); + assert_eq!(AssetManager::free_balance(Asset::Ztg, &market_account), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 0), &ALICE), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 1), &ALICE), 0); assert_eq!(AssetManager::free_balance(Asset::CategoricalOutcome(0, 2), &ALICE), 0); - assert_eq!(AssetManager::free_balance(Asset::ZTG, &ALICE), alice_ztg_before); + assert_eq!(AssetManager::free_balance(Asset::Ztg, &ALICE), alice_ztg_before); }); } @@ -593,7 +593,7 @@ fn admin_move_market_to_resolved_resolves_reported_market() { // Give ALICE `SENTINEL_AMOUNT` free and reserved ZTG; we record the free balance to check // that the correct bonds are unreserved! - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -846,7 +846,7 @@ fn reject_market_unreserves_oracle_bond_and_slashes_advisory_bond() { // Give ALICE `SENTINEL_AMOUNT` free and reserved ZTG; we record the free balance to check // that the AdvisoryBond gets slashed but the OracleBond gets unreserved. - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -910,7 +910,7 @@ fn on_market_close_auto_rejects_expired_advised_market() { ExtBuilder::default().build().execute_with(|| { // Give ALICE `SENTINEL_AMOUNT` free and reserved ZTG; we record the free balance to check // that the AdvisoryBond and the OracleBond gets unreserved, when the advised market expires. - assert_ok!(AssetManager::deposit(Asset::ZTG, &ALICE, 2 * SENTINEL_AMOUNT)); + assert_ok!(AssetManager::deposit(Asset::Ztg, &ALICE, 2 * SENTINEL_AMOUNT)); assert_ok!(Balances::reserve_named( &PredictionMarkets::reserve_id(), &ALICE, @@ -2056,10 +2056,10 @@ fn create_market_and_deploy_assets_results_in_expected_balances_and_pool_params( Asset::CategoricalOutcome(market_id, 1), Asset::CategoricalOutcome(market_id, 2), Asset::CategoricalOutcome(market_id, 3), - Asset::ZTG, + Asset::Ztg, ]; assert_eq!(pool.assets, assets_expected); - assert_eq!(pool.base_asset, Asset::ZTG); + assert_eq!(pool.base_asset, Asset::Ztg); assert_eq!(pool.market_id, market_id); assert_eq!(pool.scoring_rule, ScoringRule::CPMM); assert_eq!(pool.swap_fee, Some(swap_fee)); @@ -2071,7 +2071,7 @@ fn create_market_and_deploy_assets_results_in_expected_balances_and_pool_params( assert_eq!(pool_weights[&Asset::CategoricalOutcome(market_id, 1)], weight); assert_eq!(pool_weights[&Asset::CategoricalOutcome(market_id, 2)], weight); assert_eq!(pool_weights[&Asset::CategoricalOutcome(market_id, 3)], weight); - assert_eq!(pool_weights[&Asset::ZTG], base_asset_weight); + assert_eq!(pool_weights[&Asset::Ztg], base_asset_weight); }); } @@ -2688,7 +2688,7 @@ fn deploy_swap_pool_correctly_sets_weight_of_base_asset() { let pool = >::get(0).unwrap(); let pool_weights = pool.weights.unwrap(); assert_eq!( - pool_weights[&Asset::ZTG], + pool_weights[&Asset::Ztg], 3 * ::MinWeight::get() + 66 ); }); diff --git a/zrml/swaps/fuzz/utils.rs b/zrml/swaps/fuzz/utils.rs index 972823601..ec6e54171 100644 --- a/zrml/swaps/fuzz/utils.rs +++ b/zrml/swaps/fuzz/utils.rs @@ -43,7 +43,7 @@ pub fn construct_asset(seed: (u8, u128, u16)) -> Asset { } 2 => Asset::CombinatorialOutcome, 3 => Asset::PoolShare(SerdeWrapper(seed0)), - _ => Asset::ZTG, + _ => Asset::Ztg, } } diff --git a/zrml/swaps/src/lib.rs b/zrml/swaps/src/lib.rs index 86d9fe8ab..ff2fb57e0 100644 --- a/zrml/swaps/src/lib.rs +++ b/zrml/swaps/src/lib.rs @@ -35,11 +35,11 @@ extern crate alloc; mod utils; mod benchmarks; -mod check_arithm_rslt; +pub mod check_arithm_rslt; mod consts; mod events; -mod fixed; -mod math; +pub mod fixed; +pub mod math; pub mod migrations; pub mod mock; mod tests; From dd80b2609203df9e4d701768a38628bcfe58d366 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Mon, 26 Sep 2022 17:19:11 +0200 Subject: [PATCH 12/59] Finalize: XCM Weight/Fee, Trader, Treasury --- .../battery-station/src/xcm_config/config.rs | 117 ++++++++++++------ .../src/xcm_config/parachains.rs | 7 +- 2 files changed, 78 insertions(+), 46 deletions(-) diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index c587a55de..b16f42256 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -16,29 +16,33 @@ // along with Zeitgeist. If not, see . use crate::{ - AccountId, Ancestry, Balance, Balances, Call, CurrencyId, AssetManager, MaxInstructions, Origin, + AssetManager, AccountId, Ancestry, Balance, Balances, Call, CurrencyId, MaxInstructions, Origin, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, - UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, + UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, AssetRegistry }; -use super::parachains; +use super::{fees::{native_per_second, FixedConversionRateProvider}, parachains::zeitgeist::ZTG_KEY}; + +use alloc::{vec}; use frame_support::{match_types, parameter_types, traits::Everything, weights::IdentityFee}; -use orml_traits::location::AbsoluteReserveProvider; -use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset}; +use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; +use orml_traits::{MultiCurrency, location::AbsoluteReserveProvider}; +use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset, UnknownAsset}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use sp_runtime::traits::Convert; use xcm::latest::{ - prelude::{Concrete, GeneralKey, MultiAsset, Parachain, X1, X2}, + prelude::{GeneralKey, X1, AssetId, Concrete, MultiAsset}, BodyId, Junction, Junctions, MultiLocation, }; use xcm_builder::{ AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, FixedWeightBounds, LocationInverter, + AllowTopLevelPaidExecutionFrom, FixedWeightBounds, FixedRateOfFungible, LocationInverter, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - UsingComponents, + UsingComponents, TakeRevenue, }; use xcm_executor::Config; +use xcm::opaque::latest::Fungibility::Fungible; use zeitgeist_primitives::types::Asset; pub struct XcmConfig; @@ -58,7 +62,8 @@ impl Config for XcmConfig { type Barrier = Barrier; /// The outer call dispatch type. type Call = Call; - // Filters multi native assets whose reserve is same with `origin`. + /// Combinations of (Location, Asset) pairs which we trust as reserves. + // Trust the parent chain, sibling parachains and children chains of this chain. type IsReserve = MultiNativeAsset; /// Combinations of (Location, Asset) pairs which we trust as teleporters. type IsTeleporter = (); @@ -70,8 +75,8 @@ impl Config for XcmConfig { type ResponseHandler = PolkadotXcm; /// Module that handles subscription requests. type SubscriptionService = PolkadotXcm; - /// TODO: The means of purchasing weight credit for XCM execution. - type Trader = UsingComponents, RelayLocation, AccountId, Balances, ()>; + /// The means of purchasing weight credit for XCM execution. + type Trader = Trader; /// TODO: The means of determining an XCM message's weight. type Weigher = FixedWeightBounds; /// How to send an onward XCM message. @@ -90,15 +95,61 @@ pub type Barrier = ( AllowSubscriptionsFrom, ); +/// The means of purchasing weight credit for XCM execution. +/// Every token that is accepted for XC transfers should be handled here. +pub type Trader = ( + // In case the asset in question is the native currency, it will charge + // the default base fee per second and deposits them into treasury + FixedRateOfFungible, + // For all other assets the base fee per second will tried to be derived + // through the `fee_factor` entry in the asset registry. If the asset is + // not present in the asset registry, the default base fee per second is used. + // Deposits all fees into the treasury. + AssetRegistryTrader< + FixedRateAssetRegistryTrader>, + ToTreasury, + >, +); + +pub struct ToTreasury; +impl TakeRevenue for ToTreasury { + fn take_revenue(revenue: MultiAsset) { + use xcm_executor::traits::Convert; + + if let MultiAsset { + id: Concrete(location), + fun: Fungible(amount), + } = revenue.clone() + { + if let Ok(asset_id) = + >::convert(location.clone()) + { + let _ = AssetManager::deposit(asset_id, &ZeitgeistTreasuryAccount::get(), amount); + } else { + // TODO this is wrong, use target as second parameter + let _ = UnknownTokens::deposit(&revenue, &location); + } + } + } +} + parameter_types! { pub CheckAccount: AccountId = PolkadotXcm::check_account(); + /// The amount of ZTG charged per second of execution. + pub ZtgPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 0, + X1(GeneralKey(ZTG_KEY)), + ), + native_per_second(), + ); } /// Means for transacting assets on this chain. pub type MultiAssetTransactor = MultiCurrencyAdapter< // All known Assets will be processed by the following MultiCurrency implementation. AssetManager, - // Any unknown Assets will be processed by the following implementation. + // Any unknown Assets will be processed by the following UnknownAsset implementation. UnknownTokens, // This means that this adapter should handle any token that `AssetConvert` can convert // using AssetManager and UnknownTokens in all other cases. @@ -126,18 +177,14 @@ pub struct AssetConvert; /// handle it on their side. impl Convert> for AssetConvert { fn convert(id: CurrencyId) -> Option { - let x = match id { - Asset::Ztg => MultiLocation::new( - 1, - X2( - Parachain(parachains::zeitgeist::ID), - GeneralKey(parachains::zeitgeist::ZTG_KEY.to_vec()), - ), - ), - // TODO: Asset registry - _ => return None, - }; - Some(x) + match id { + Asset::Ztg => Some(MultiLocation::new( + 0, + X1(GeneralKey(ZTG_KEY)), + ).into()), + Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, + _ => None, + } } } @@ -147,23 +194,11 @@ impl Convert> for AssetConvert { impl xcm_executor::traits::Convert for AssetConvert { fn convert(location: MultiLocation) -> Result { match location.clone() { - MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { - parachains::zeitgeist::ZTG_KEY => Ok(Asset::Ztg), - _ => Err(location), - }, - MultiLocation { parents: 1, interior: X2(Parachain(para_id), GeneralKey(key)) } => { - match para_id { - parachains::zeitgeist::ID => match &key[..] { - parachains::zeitgeist::ZTG_KEY => Ok(Asset::Ztg), - _ => Err(location), - }, - - _ => Err(location), - } - } - - // TODO: Asset registry - _ => Err(location), + MultiLocation::new( + 0, + X1(GeneralKey(ZTG_KEY)), + ) => Ok(Asset::Ztg), + _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), } } } diff --git a/runtime/battery-station/src/xcm_config/parachains.rs b/runtime/battery-station/src/xcm_config/parachains.rs index 853786a94..883aeeb60 100644 --- a/runtime/battery-station/src/xcm_config/parachains.rs +++ b/runtime/battery-station/src/xcm_config/parachains.rs @@ -22,12 +22,9 @@ /// and must always match the value there defined, which is expected to /// never change once defined since they help define the canonical id /// of said tokens in the network, which is relevant for XCM transfers. -pub mod karura { - pub const ID: u32 = 2000; - pub const AUSD_KEY: &[u8] = &[0, 129]; -} + pub mod zeitgeist { pub const ID: u32 = 2101; - pub const ZTG_KEY: &[u8] = &[0, 1]; + pub const ZTG_KEY: &[u8] = &[0,1]; } From 9f2ef6721f9fc54630cb77f583a554cf892bf4a6 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Mon, 26 Sep 2022 21:22:26 +0200 Subject: [PATCH 13/59] Fix key conversion & GenesisConfig --- node/src/chain_spec/battery_station.rs | 10 ++++-- node/src/chain_spec/dev.rs | 13 ++++++-- .../battery-station/src/xcm_config/config.rs | 32 ++++++++++++------- 3 files changed, 38 insertions(+), 17 deletions(-) diff --git a/node/src/chain_spec/battery_station.rs b/node/src/chain_spec/battery_station.rs index 5590d94aa..2de1e3cb1 100644 --- a/node/src/chain_spec/battery_station.rs +++ b/node/src/chain_spec/battery_station.rs @@ -28,7 +28,7 @@ use zeitgeist_primitives::{ ztg::{LIQUIDITY_MINING, LIQUIDITY_MINING_PTD}, BASE, }, - types::AccountId, + types::{Asset::ForeignAsset, AccountId} }; #[cfg(feature = "parachain")] @@ -115,7 +115,13 @@ pub(super) fn get_wasm() -> Result<&'static [u8], String> { generate_generic_genesis_function!( battery_station_runtime, - sudo: battery_station_runtime::SudoConfig { key: Some(root_key_staging_battery_station()) }, + asset_registry: battery_station_runtime::AssetRegistryConfig { + assets: vec![], + last_asset_id: ForeignAsset(0), + }, + sudo: battery_station_runtime::SudoConfig { + key: Some(root_key_staging_battery_station()), + }, ); pub fn battery_station_staging_config( diff --git a/node/src/chain_spec/dev.rs b/node/src/chain_spec/dev.rs index 0c7fc1c27..1c7461316 100644 --- a/node/src/chain_spec/dev.rs +++ b/node/src/chain_spec/dev.rs @@ -29,7 +29,7 @@ use sc_service::ChainType; use sp_core::sr25519; use zeitgeist_primitives::{ constants::ztg::{LIQUIDITY_MINING, LIQUIDITY_MINING_PTD}, - types::Balance, + types::{Asset::ForeignAsset, Balance}, }; const INITIAL_BALANCE: Balance = Balance::MAX >> 4; @@ -44,8 +44,15 @@ fn authority_keys_from_seed( ) } -generate_generic_genesis_function! {battery_station_runtime, - sudo: battery_station_runtime::SudoConfig { key: Some(get_account_id_from_seed::("Alice")) }, +generate_generic_genesis_function! { + battery_station_runtime, + asset_registry: battery_station_runtime::AssetRegistryConfig { + assets: vec![], + last_asset_id: ForeignAsset(0), + }, + sudo: battery_station_runtime::SudoConfig { + key: Some(get_account_id_from_seed::("Alice")), + }, } // Dev currently uses battery station runtime for the following reasons: diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index b16f42256..41fdd543c 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -16,14 +16,14 @@ // along with Zeitgeist. If not, see . use crate::{ - AssetManager, AccountId, Ancestry, Balance, Balances, Call, CurrencyId, MaxInstructions, Origin, - ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayLocation, RelayNetwork, + AssetManager, AccountId, Ancestry, Balance, Call, CurrencyId, MaxInstructions, Origin, + ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, AssetRegistry }; use super::{fees::{native_per_second, FixedConversionRateProvider}, parachains::zeitgeist::ZTG_KEY}; -use alloc::{vec}; -use frame_support::{match_types, parameter_types, traits::Everything, weights::IdentityFee}; +use alloc::vec::Vec; +use frame_support::{match_types, parameter_types, traits::Everything}; use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{MultiCurrency, location::AbsoluteReserveProvider}; use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset, UnknownAsset}; @@ -39,7 +39,7 @@ use xcm_builder::{ AllowTopLevelPaidExecutionFrom, FixedWeightBounds, FixedRateOfFungible, LocationInverter, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - UsingComponents, TakeRevenue, + TakeRevenue, }; use xcm_executor::Config; use xcm::opaque::latest::Fungibility::Fungible; @@ -139,8 +139,8 @@ parameter_types! { pub ZtgPerSecond: (AssetId, u128) = ( MultiLocation::new( 0, - X1(GeneralKey(ZTG_KEY)), - ), + X1(general_key(ZTG_KEY)), + ).into(), native_per_second(), ); } @@ -180,7 +180,7 @@ impl Convert> for AssetConvert { match id { Asset::Ztg => Some(MultiLocation::new( 0, - X1(GeneralKey(ZTG_KEY)), + X1(general_key(ZTG_KEY)), ).into()), Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, _ => None, @@ -194,10 +194,13 @@ impl Convert> for AssetConvert { impl xcm_executor::traits::Convert for AssetConvert { fn convert(location: MultiLocation) -> Result { match location.clone() { - MultiLocation::new( - 0, - X1(GeneralKey(ZTG_KEY)), - ) => Ok(Asset::Ztg), + MultiLocation { + parents: 0, + interior: X1(GeneralKey(key)), + } => match &key[..] { + ZTG_KEY => Ok(CurrencyId::Ztg), + _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), + } _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), } } @@ -271,3 +274,8 @@ match_types! { MultiLocation { parents: 1, interior: Junctions::X1(Junction::Plurality { id: BodyId::Unit, .. }) } }; } + +#[inline] +fn general_key(key: &[u8]) -> Junction { + GeneralKey(Vec::from(key)) +} From 28517a811a15492d12eb161b4328d214f5647629 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Mon, 26 Sep 2022 21:39:32 +0200 Subject: [PATCH 14/59] Comment + Cargo fmt --- node/src/chain_spec/battery_station.rs | 8 +- node/src/chain_spec/dev.rs | 6 +- primitives/src/asset.rs | 17 +++- runtime/battery-station/src/lib.rs | 20 +++-- runtime/battery-station/src/xcm_config.rs | 2 +- .../src/xcm_config/asset_registry.rs | 64 ++++++------- .../battery-station/src/xcm_config/config.rs | 89 +++++++++---------- .../battery-station/src/xcm_config/fees.rs | 24 +++-- .../src/xcm_config/parachains.rs | 3 +- 9 files changed, 121 insertions(+), 112 deletions(-) diff --git a/node/src/chain_spec/battery_station.rs b/node/src/chain_spec/battery_station.rs index 2de1e3cb1..63eab79c6 100644 --- a/node/src/chain_spec/battery_station.rs +++ b/node/src/chain_spec/battery_station.rs @@ -28,7 +28,7 @@ use zeitgeist_primitives::{ ztg::{LIQUIDITY_MINING, LIQUIDITY_MINING_PTD}, BASE, }, - types::{Asset::ForeignAsset, AccountId} + types::{AccountId, Asset::ForeignAsset}, }; #[cfg(feature = "parachain")] @@ -115,11 +115,11 @@ pub(super) fn get_wasm() -> Result<&'static [u8], String> { generate_generic_genesis_function!( battery_station_runtime, - asset_registry: battery_station_runtime::AssetRegistryConfig { - assets: vec![], + asset_registry: battery_station_runtime::AssetRegistryConfig { + assets: vec![], last_asset_id: ForeignAsset(0), }, - sudo: battery_station_runtime::SudoConfig { + sudo: battery_station_runtime::SudoConfig { key: Some(root_key_staging_battery_station()), }, ); diff --git a/node/src/chain_spec/dev.rs b/node/src/chain_spec/dev.rs index 1c7461316..df247450d 100644 --- a/node/src/chain_spec/dev.rs +++ b/node/src/chain_spec/dev.rs @@ -46,11 +46,11 @@ fn authority_keys_from_seed( generate_generic_genesis_function! { battery_station_runtime, - asset_registry: battery_station_runtime::AssetRegistryConfig { - assets: vec![], + asset_registry: battery_station_runtime::AssetRegistryConfig { + assets: vec![], last_asset_id: ForeignAsset(0), }, - sudo: battery_station_runtime::SudoConfig { + sudo: battery_station_runtime::SudoConfig { key: Some(get_account_id_from_seed::("Alice")), }, } diff --git a/primitives/src/asset.rs b/primitives/src/asset.rs index 90079f24b..92a99dc23 100644 --- a/primitives/src/asset.rs +++ b/primitives/src/asset.rs @@ -28,18 +28,29 @@ use scale_info::TypeInfo; #[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] #[derive( - Clone, Copy, Debug, Decode, Default, Eq, Encode, MaxEncodedLen, Ord, PartialEq, PartialOrd, TypeInfo, + Clone, + Copy, + Debug, + Decode, + Default, + Eq, + Encode, + MaxEncodedLen, + Ord, + PartialEq, + PartialOrd, + TypeInfo, )] pub enum Asset { CategoricalOutcome(MI, CategoryIndex), ScalarOutcome(MI, ScalarPosition), CombinatorialOutcome, PoolShare(SerdeWrapper), - #[default] Ztg, + #[default] + Ztg, ForeignAsset(u32), } - /// In a scalar market, users can either choose a `Long` position, /// meaning that they think the outcome will be closer to the upper bound /// or a `Short` position meaning that they think the outcome will be closer diff --git a/runtime/battery-station/src/lib.rs b/runtime/battery-station/src/lib.rs index 238cb9b61..474d42954 100644 --- a/runtime/battery-station/src/lib.rs +++ b/runtime/battery-station/src/lib.rs @@ -56,7 +56,10 @@ use { frame_support::traits::{AsEnsureOriginWithArg, Everything, Nothing}, frame_system::EnsureSigned, xcm_builder::{EnsureXcmOrigin, FixedWeightBounds, LocationInverter}, - xcm_config::{asset_registry::{CustomAssetProcessor, CustomMetadata}, config::{LocalOriginToLocation, XcmConfig, XcmOriginToTransactDispatchOrigin, XcmRouter}}, + xcm_config::{ + asset_registry::{CustomAssetProcessor, CustomMetadata}, + config::{LocalOriginToLocation, XcmConfig, XcmOriginToTransactDispatchOrigin, XcmRouter}, + }, }; use frame_support::construct_runtime; @@ -142,7 +145,6 @@ create_runtime_with_additional_pallets!( UnknownTokens: orml_unknown_tokens::{Pallet, Storage, Event} = 152, ); - impl pallet_sudo::Config for Runtime { type Call = Call; type Event = Event; @@ -150,13 +152,13 @@ impl pallet_sudo::Config for Runtime { #[cfg(feature = "parachain")] impl orml_asset_registry::Config for Runtime { - type AssetId = CurrencyId; - type AssetProcessor = CustomAssetProcessor; - type AuthorityOrigin = AsEnsureOriginWithArg; - type Balance = Balance; - type CustomMetadata = CustomMetadata; - type Event = Event; - type WeightInfo = (); + type AssetId = CurrencyId; + type AssetProcessor = CustomAssetProcessor; + type AuthorityOrigin = AsEnsureOriginWithArg; + type Balance = Balance; + type CustomMetadata = CustomMetadata; + type Event = Event; + type WeightInfo = (); } #[cfg(feature = "parachain")] diff --git a/runtime/battery-station/src/xcm_config.rs b/runtime/battery-station/src/xcm_config.rs index a74527351..0343f29b6 100644 --- a/runtime/battery-station/src/xcm_config.rs +++ b/runtime/battery-station/src/xcm_config.rs @@ -20,4 +20,4 @@ pub mod asset_registry; pub mod config; pub mod fees; -pub mod parachains; \ No newline at end of file +pub mod parachains; diff --git a/runtime/battery-station/src/xcm_config/asset_registry.rs b/runtime/battery-station/src/xcm_config/asset_registry.rs index 1f3ac9a2b..ea2d2456c 100644 --- a/runtime/battery-station/src/xcm_config/asset_registry.rs +++ b/runtime/battery-station/src/xcm_config/asset_registry.rs @@ -18,8 +18,8 @@ use crate::{Balance, CurrencyId}; use orml_traits::asset_registry::{AssetMetadata, AssetProcessor}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use sp_runtime::DispatchError; use scale_info::TypeInfo; +use sp_runtime::DispatchError; #[derive( Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen, @@ -48,47 +48,47 @@ impl AssetProcessor> for Cust } #[derive( - Clone, - Copy, - Default, - PartialOrd, - Ord, - PartialEq, - Eq, - Debug, - Encode, - Decode, - TypeInfo, - MaxEncodedLen, + Clone, + Copy, + Default, + PartialOrd, + Ord, + PartialEq, + Eq, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, )] /// Custom XC asset metadata pub struct CustomMetadata { - /// XCM-related metadata. - pub xcm: XcmMetadata, + /// XCM-related metadata. + pub xcm: XcmMetadata, - /// Whether an asset can be used in pools. - pub allow_in_pool: bool, + /// Whether an asset can be used in pools. + pub allow_in_pool: bool, } #[derive( - Clone, - Copy, - Default, - PartialOrd, - Ord, - PartialEq, - Eq, - Debug, - Encode, - Decode, - TypeInfo, - MaxEncodedLen, + Clone, + Copy, + Default, + PartialOrd, + Ord, + PartialEq, + Eq, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, )] pub struct XcmMetadata { - /// The factor used to determine the fee. + /// The factor used to determine the fee. /// It is multiplied by the fee that would have been paind in native currency, so it represents /// the ratio `native_price / other_asset_price`. It is a fixed point decimal number containing /// as many fractional decimals as the asset it is used for contains. /// Should be updated regularly. - pub fee_factor: Option, -} \ No newline at end of file + pub fee_factor: Option, +} diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 41fdd543c..9952bf3e0 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -15,34 +15,41 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . +use super::{ + fees::{native_per_second, FixedConversionRateProvider}, + parachains::zeitgeist::ZTG_KEY, +}; use crate::{ - AssetManager, AccountId, Ancestry, Balance, Call, CurrencyId, MaxInstructions, Origin, - ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, - UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, AssetRegistry + AccountId, Ancestry, AssetManager, AssetRegistry, Balance, Call, CurrencyId, MaxInstructions, + Origin, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, UnitWeightCost, + UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; -use super::{fees::{native_per_second, FixedConversionRateProvider}, parachains::zeitgeist::ZTG_KEY}; use alloc::vec::Vec; use frame_support::{match_types, parameter_types, traits::Everything}; use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; -use orml_traits::{MultiCurrency, location::AbsoluteReserveProvider}; -use orml_xcm_support::{DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset, UnknownAsset}; +use orml_traits::{location::AbsoluteReserveProvider, MultiCurrency}; +use orml_xcm_support::{ + DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset, UnknownAsset, +}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use sp_runtime::traits::Convert; -use xcm::latest::{ - prelude::{GeneralKey, X1, AssetId, Concrete, MultiAsset}, - BodyId, Junction, Junctions, MultiLocation, +use xcm::{ + latest::{ + prelude::{AssetId, Concrete, GeneralKey, MultiAsset, X1}, + BodyId, Junction, Junctions, MultiLocation, + }, + opaque::latest::Fungibility::Fungible, }; use xcm_builder::{ AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, FixedWeightBounds, FixedRateOfFungible, LocationInverter, + AllowTopLevelPaidExecutionFrom, FixedRateOfFungible, FixedWeightBounds, LocationInverter, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - TakeRevenue, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeRevenue, + TakeWeightCredit, }; use xcm_executor::Config; -use xcm::opaque::latest::Fungibility::Fungible; use zeitgeist_primitives::types::Asset; pub struct XcmConfig; @@ -77,7 +84,9 @@ impl Config for XcmConfig { type SubscriptionService = PolkadotXcm; /// The means of purchasing weight credit for XCM execution. type Trader = Trader; - /// TODO: The means of determining an XCM message's weight. + /// The means of determining an XCM message's weight. + // Adds UnitWeightCost per instruction plus the weight of each instruction. + // The total number of instructions are bounded by MaxInstructions type Weigher = FixedWeightBounds; /// How to send an onward XCM message. type XcmSender = XcmRouter; @@ -100,49 +109,45 @@ pub type Barrier = ( pub type Trader = ( // In case the asset in question is the native currency, it will charge // the default base fee per second and deposits them into treasury - FixedRateOfFungible, + FixedRateOfFungible, // For all other assets the base fee per second will tried to be derived // through the `fee_factor` entry in the asset registry. If the asset is // not present in the asset registry, the default base fee per second is used. // Deposits all fees into the treasury. - AssetRegistryTrader< - FixedRateAssetRegistryTrader>, - ToTreasury, - >, + AssetRegistryTrader< + FixedRateAssetRegistryTrader>, + ToTreasury, + >, ); pub struct ToTreasury; impl TakeRevenue for ToTreasury { - fn take_revenue(revenue: MultiAsset) { + fn take_revenue(revenue: MultiAsset) { use xcm_executor::traits::Convert; - if let MultiAsset { - id: Concrete(location), - fun: Fungible(amount), - } = revenue.clone() - { - if let Ok(asset_id) = - >::convert(location.clone()) - { - let _ = AssetManager::deposit(asset_id, &ZeitgeistTreasuryAccount::get(), amount); - } else { + if let MultiAsset { id: Concrete(location), fun: Fungible(amount) } = revenue.clone() { + if let Ok(asset_id) = + >::convert(location.clone()) + { + let _ = AssetManager::deposit(asset_id, &ZeitgeistTreasuryAccount::get(), amount); + } else { // TODO this is wrong, use target as second parameter let _ = UnknownTokens::deposit(&revenue, &location); } - } - } + } + } } parameter_types! { pub CheckAccount: AccountId = PolkadotXcm::check_account(); /// The amount of ZTG charged per second of execution. - pub ZtgPerSecond: (AssetId, u128) = ( - MultiLocation::new( + pub ZtgPerSecond: (AssetId, u128) = ( + MultiLocation::new( 0, X1(general_key(ZTG_KEY)), ).into(), - native_per_second(), - ); + native_per_second(), + ); } /// Means for transacting assets on this chain. @@ -178,10 +183,7 @@ pub struct AssetConvert; impl Convert> for AssetConvert { fn convert(id: CurrencyId) -> Option { match id { - Asset::Ztg => Some(MultiLocation::new( - 0, - X1(general_key(ZTG_KEY)), - ).into()), + Asset::Ztg => Some(MultiLocation::new(0, X1(general_key(ZTG_KEY))).into()), Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, _ => None, } @@ -194,13 +196,10 @@ impl Convert> for AssetConvert { impl xcm_executor::traits::Convert for AssetConvert { fn convert(location: MultiLocation) -> Result { match location.clone() { - MultiLocation { - parents: 0, - interior: X1(GeneralKey(key)), - } => match &key[..] { + MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { ZTG_KEY => Ok(CurrencyId::Ztg), _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), - } + }, _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), } } diff --git a/runtime/battery-station/src/xcm_config/fees.rs b/runtime/battery-station/src/xcm_config/fees.rs index 9642240b6..de0321886 100644 --- a/runtime/battery-station/src/xcm_config/fees.rs +++ b/runtime/battery-station/src/xcm_config/fees.rs @@ -15,13 +15,11 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::{Balance, CurrencyId, xcm_config::asset_registry::CustomMetadata}; -use core::{marker::PhantomData}; +use crate::{xcm_config::asset_registry::CustomMetadata, Balance, CurrencyId}; +use core::marker::PhantomData; use frame_support::weights::constants::{ExtrinsicBaseWeight, WEIGHT_PER_SECOND}; use xcm::latest::MultiLocation; -use zeitgeist_primitives::{ - constants::BalanceFractionalDecimals, -}; +use zeitgeist_primitives::constants::BalanceFractionalDecimals; use zrml_swaps::check_arithm_rslt::CheckArithmRslt; /// The fee cost per second for transferring the native token in cents. @@ -60,21 +58,21 @@ pub fn bmul(a: u128, b: u128, base: u128) -> Option { pub struct FixedConversionRateProvider(PhantomData); impl< - OrmlAssetRegistry: orml_traits::asset_registry::Inspect< - AssetId = CurrencyId, - Balance = Balance, - CustomMetadata = CustomMetadata, - >, - > orml_traits::FixedConversionRateProvider for FixedConversionRateProvider + OrmlAssetRegistry: orml_traits::asset_registry::Inspect< + AssetId = CurrencyId, + Balance = Balance, + CustomMetadata = CustomMetadata, + >, +> orml_traits::FixedConversionRateProvider for FixedConversionRateProvider { fn get_fee_per_second(location: &MultiLocation) -> Option { let metadata = OrmlAssetRegistry::metadata_by_location(&location)?; let default_per_second = default_per_second(metadata.decimals); - + if let Some(fee_factor) = metadata.additional.xcm.fee_factor { bmul(default_per_second, fee_factor, metadata.decimals.into()) } else { Some(default_per_second) } } -} \ No newline at end of file +} diff --git a/runtime/battery-station/src/xcm_config/parachains.rs b/runtime/battery-station/src/xcm_config/parachains.rs index 883aeeb60..73f2012c8 100644 --- a/runtime/battery-station/src/xcm_config/parachains.rs +++ b/runtime/battery-station/src/xcm_config/parachains.rs @@ -23,8 +23,7 @@ /// never change once defined since they help define the canonical id /// of said tokens in the network, which is relevant for XCM transfers. - pub mod zeitgeist { pub const ID: u32 = 2101; - pub const ZTG_KEY: &[u8] = &[0,1]; + pub const ZTG_KEY: &[u8] = &[0, 1]; } From 49030cb7e7f3200728f458d9f4727b06c47a50b3 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Tue, 11 Oct 2022 10:51:13 +0200 Subject: [PATCH 15/59] Include xTokens --- Cargo.lock | 24 +++- runtime/battery-station/Cargo.toml | 5 + runtime/battery-station/src/lib.rs | 24 ++++ .../battery-station/src/parachain_params.rs | 103 ++++-------------- .../battery-station/src/xcm_config/config.rs | 40 ++++++- 5 files changed, 105 insertions(+), 91 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9ddb5aeae..d88b46ac4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -471,6 +471,7 @@ dependencies = [ "orml-traits", "orml-unknown-tokens", "orml-xcm-support", + "orml-xtokens", "pallet-aura", "pallet-author-inherent", "pallet-author-mapping", @@ -5378,6 +5379,27 @@ dependencies = [ "xcm-executor", ] +[[package]] +name = "orml-xtokens" +version = "0.4.1-dev" +source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" +dependencies = [ + "cumulus-primitives-core", + "frame-support", + "frame-system", + "orml-traits", + "orml-xcm-support", + "pallet-xcm", + "parity-scale-codec", + "scale-info", + "serde", + "sp-io", + "sp-runtime", + "sp-std", + "xcm", + "xcm-executor", +] + [[package]] name = "os_str_bytes" version = "6.0.1" @@ -11702,7 +11724,7 @@ version = "1.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" dependencies = [ - "cfg-if 1.0.0", + "cfg-if 0.1.10", "digest 0.10.3", "rand 0.8.5", "static_assertions", diff --git a/runtime/battery-station/Cargo.toml b/runtime/battery-station/Cargo.toml index c5825d56b..29129b1d8 100644 --- a/runtime/battery-station/Cargo.toml +++ b/runtime/battery-station/Cargo.toml @@ -86,6 +86,7 @@ log = { version = "0.4.8", default-features = false, optional = true } orml-asset-registry = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-unknown-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-xtokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } pallet-xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm-builder = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } @@ -138,6 +139,7 @@ parachain = [ "orml-asset-registry", "orml-unknown-tokens", "orml-xcm-support", + "orml-xtokens", "pallet-xcm", "xcm-builder", "xcm-executor", @@ -157,6 +159,7 @@ runtime-benchmarks = [ "hex-literal", "orml-tokens/runtime-benchmarks", "orml-benchmarking", + "orml-xtokens?/runtime-benchmarks", "pallet-author-mapping/runtime-benchmarks", "pallet-author-slot-filter/runtime-benchmarks", "pallet-balances/runtime-benchmarks", @@ -268,6 +271,7 @@ std = [ "orml-asset-registry?/std", "orml-unknown-tokens?/std", "orml-xcm-support?/std", + "orml-xtokens?/std", "pallet-xcm?/std", "xcm-builder?/std", "xcm-executor?/std", @@ -321,6 +325,7 @@ try-runtime = [ "orml-currencies/try-runtime", "orml-tokens/try-runtime", "orml-unknown-tokens?/try-runtime", + "orml-xtokens?/try-runtime", # Zeitgeist runtime pallets "zrml-authorized/try-runtime", diff --git a/runtime/battery-station/src/lib.rs b/runtime/battery-station/src/lib.rs index 474d42954..3f78b81e7 100644 --- a/runtime/battery-station/src/lib.rs +++ b/runtime/battery-station/src/lib.rs @@ -143,6 +143,7 @@ create_runtime_with_additional_pallets!( Sudo: pallet_sudo::{Call, Config, Event, Pallet, Storage} = 150, AssetRegistry: orml_asset_registry::{Call, Config, Event, Pallet, Storage} = 151, UnknownTokens: orml_unknown_tokens::{Pallet, Storage, Event} = 152, + XTokens: orml_xtokens::{Pallet, Storage, Call, Event} = 153, ); impl pallet_sudo::Config for Runtime { @@ -166,6 +167,29 @@ impl orml_unknown_tokens::Config for Runtime { type Event = Event; } +#[cfg(feature = "parachain")] +use xcm_config::config::*; + + +#[cfg(feature = "parachain")] +impl orml_xtokens::Config for Runtime { + type AccountIdToMultiLocation = AccountIdToMultiLocation; + type Balance = Balance; + type BaseXcmWeight = BaseXcmWeight; + type CurrencyId = CurrencyId; + type CurrencyIdConvert = AssetConvert; + type Event = Event; + type LocationInverter = LocationInverter; + type MaxAssetsForTransfer = MaxAssetsForTransfer; + type MinXcmFee = ParachainMinFee; + type MultiLocationsFilter = Everything; + type ReserveProvider = orml_traits::location::AbsoluteReserveProvider; + type SelfLocation = SelfLocation; + type Weigher = FixedWeightBounds; + type XcmExecutor = xcm_executor::XcmExecutor; +} + + impl_config_traits!(); create_runtime_api!(); create_common_benchmark_logic!(); diff --git a/runtime/battery-station/src/parachain_params.rs b/runtime/battery-station/src/parachain_params.rs index 733f4ea16..234f81325 100644 --- a/runtime/battery-station/src/parachain_params.rs +++ b/runtime/battery-station/src/parachain_params.rs @@ -23,32 +23,18 @@ #![cfg(feature = "parachain")] use super::{ - parameters::MAXIMUM_BLOCK_WEIGHT, AccountId, Balances, Origin, ParachainInfo, ParachainSystem, - XcmpQueue, + parameters::MAXIMUM_BLOCK_WEIGHT, Origin, ParachainInfo, + xcm_config::parachains::zeitgeist::{ID as ZTG_PARAID}, }; -use frame_support::{match_types, parameter_types, traits::Everything, weights::Weight}; -use pallet_xcm::XcmPassthrough; -use polkadot_parachain::primitives::Sibling; +use frame_support::{parameter_types, weights::Weight}; +use orml_traits::parameter_type_with_key; use sp_runtime::{Perbill, Percent, SaturatedConversion}; -use xcm::latest::{BodyId, Junction, Junctions, MultiLocation, NetworkId}; -use xcm_builder::{ - AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter, - IsConcrete, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, - SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, TakeWeightCredit, -}; +use xcm::latest::{Junction, MultiLocation, NetworkId, prelude::X1}; use zeitgeist_primitives::{ constants::{BASE, BLOCKS_PER_MINUTE, MICRO}, types::Balance, }; -match_types! { - pub type ParentOrParentsUnitPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Junctions::Here } | - // Potentially change "Unit" to "Executive" for mainnet once we have separate runtimes - MultiLocation { parents: 1, interior: Junctions::X1(Junction::Plurality { id: BodyId::Unit, .. }) } - }; -} parameter_types! { // Author-Mapping /// The amount that should be taken as a security deposit when registering a NimbusId. @@ -107,71 +93,20 @@ parameter_types! { pub const RewardPaymentDelay: u32 = 2; // XCM + /// Base weight for XCM execution + pub const BaseXcmWeight: Weight = 100_000_000; + /// The maximum number of distinct assets allowed to be transferred in a + /// single helper extrinsic. + pub const MaxAssetsForTransfer: usize = 2; + /// Max instructions per XCM pub const MaxInstructions: u32 = 100; + // Relative self location + pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Junction::Parachain(ZTG_PARAID))); } -pub type Barrier = ( - TakeWeightCredit, - AllowTopLevelPaidExecutionFrom, - AllowUnpaidExecutionFrom, - // ^^^ Parent and its exec plurality get free execution -); - -/// Means for transacting assets on this chain. -pub type LocalAssetTransactor = CurrencyAdapter< - // Use this currency: - Balances, - // Use this currency when it is a fungible asset matching the given location or name: - IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: - LocationToAccountId, - // Our chain's account ID type (we can't get away without mentioning it explicitly): - AccountId, - // We don't track any teleports. - (), ->; - -/// No local origins on this chain are allowed to dispatch XCM sends/executions. -pub type LocalOriginToLocation = SignedToAccountId32; - -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used -/// when determining ownership of accounts for asset transacting and when attempting to use XCM -/// `Transact` in order to determine the dispatch Origin. -pub type LocationToAccountId = ( - // The parent (Relay-chain) origin converts to the parent `AccountId`. - ParentIsPreset, - // Sibling parachain origins convert to AccountId via the `ParaId::into`. - SiblingParachainConvertsVia, - // Straight up local `AccountId32` origins just alias directly to `AccountId`. - AccountId32Aliases, -); - -/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, -/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can -/// biases the kind of local `Origin` it will become. -pub type XcmOriginToTransactDispatchOrigin = ( - // Sovereign account converter; this attempts to derive an `AccountId` from the origin location - // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for - // foreign chains who want to have a local sovereign account on this chain which they control. - SovereignSignedViaLocation, - // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when - // recognized. - RelayChainAsNative, - // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when - // recognized. - SiblingParachainAsNative, - // Native signed account converter; this just converts an `AccountId32` origin into a normal - // `Origin::Signed` origin of the same 32-byte value. - SignedAccountId32AsNative, - // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. - XcmPassthrough, -); - -/// The means for routing XCM messages which are not for local execution into the right message -/// queues. -pub type XcmRouter = ( - // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, - // ..and XCMP to communicate with the sibling chains. - XcmpQueue, -); +parameter_type_with_key! { + // XCM + pub ParachainMinFee: |_location: MultiLocation| -> Option { + None + }; +} diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 9952bf3e0..fa128363f 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -17,7 +17,7 @@ use super::{ fees::{native_per_second, FixedConversionRateProvider}, - parachains::zeitgeist::ZTG_KEY, + parachains::zeitgeist::{ID as ZTG_PARAID, ZTG_KEY}, }; use crate::{ AccountId, Ancestry, AssetManager, AssetRegistry, Balance, Call, CurrencyId, MaxInstructions, @@ -37,7 +37,7 @@ use polkadot_parachain::primitives::Sibling; use sp_runtime::traits::Convert; use xcm::{ latest::{ - prelude::{AssetId, Concrete, GeneralKey, MultiAsset, X1}, + prelude::{AccountId32, AssetId, Concrete, GeneralKey, MultiAsset, NetworkId, X1, X2}, BodyId, Junction, Junctions, MultiLocation, }, opaque::latest::Fungibility::Fungible, @@ -69,7 +69,7 @@ impl Config for XcmConfig { type Barrier = Barrier; /// The outer call dispatch type. type Call = Call; - /// Combinations of (Location, Asset) pairs which we trust as reserves. + /// Combinations of (Location, Asset) pairs which are trusted as reserves. // Trust the parent chain, sibling parachains and children chains of this chain. type IsReserve = MultiNativeAsset; /// Combinations of (Location, Asset) pairs which we trust as teleporters. @@ -183,7 +183,13 @@ pub struct AssetConvert; impl Convert> for AssetConvert { fn convert(id: CurrencyId) -> Option { match id { - Asset::Ztg => Some(MultiLocation::new(0, X1(general_key(ZTG_KEY))).into()), + Asset::Ztg => Some(MultiLocation::new( + 1, + X2( + Junction::Parachain(ZTG_PARAID), + general_key(ZTG_KEY), + ), + )), Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, _ => None, } @@ -198,8 +204,18 @@ impl xcm_executor::traits::Convert for AssetConvert { match location.clone() { MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { ZTG_KEY => Ok(CurrencyId::Ztg), - _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), + _ => Err(location), }, + MultiLocation { + parents: 1, + interior: X2(Junction::Parachain(para_id), GeneralKey(key)), + } => match para_id { + ZTG_PARAID => match &key[..] { + ZTG_KEY => Ok(CurrencyId::Ztg), + _ => Err(location), + }, + _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), + }, _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), } } @@ -221,6 +237,18 @@ impl Convert> for AssetConvert { } } +pub struct AccountIdToMultiLocation; + +impl Convert for AccountIdToMultiLocation { + fn convert(account: AccountId) -> MultiLocation { + X1(AccountId32 { + network: NetworkId::Any, + id: account.into(), + }) + .into() + } +} + /// No local origins on this chain are allowed to dispatch XCM sends/executions. pub type LocalOriginToLocation = SignedToAccountId32; @@ -270,7 +298,7 @@ match_types! { pub type ParentOrParentsUnitPlurality: impl Contains = { MultiLocation { parents: 1, interior: Junctions::Here } | // Potentially change "Unit" to "Executive" for mainnet once we have separate runtimes - MultiLocation { parents: 1, interior: Junctions::X1(Junction::Plurality { id: BodyId::Unit, .. }) } + MultiLocation { parents: 1, interior: X1(Junction::Plurality { id: BodyId::Unit, .. }) } }; } From 4f5ab0f0f04a45a22398f6cfb956d59afc3f8f7e Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Mon, 31 Oct 2022 20:59:58 +0200 Subject: [PATCH 16/59] Add integration test environment & XCM test setup --- Cargo.lock | 3 + runtime/battery-station/Cargo.toml | 15 ++ .../src/integration_tests/mod.rs | 19 ++ .../src/integration_tests/xcm/mod.rs | 22 +++ .../integration_tests/xcm/restricted_calls.rs | 0 .../src/integration_tests/xcm/setup.rs | 144 +++++++++++++++ .../src/integration_tests/xcm/test_net.rs | 165 ++++++++++++++++++ .../xcm/tests/asset_registry.rs | 0 .../xcm/tests/currency_id_convert.rs | 0 .../src/integration_tests/xcm/tests/mod.rs | 3 + .../integration_tests/xcm/tests/transfers.rs | 0 runtime/battery-station/src/lib.rs | 3 + .../battery-station/src/parachain_params.rs | 2 +- .../battery-station/src/xcm_config/config.rs | 18 +- 14 files changed, 386 insertions(+), 8 deletions(-) create mode 100644 runtime/battery-station/src/integration_tests/mod.rs create mode 100644 runtime/battery-station/src/integration_tests/xcm/mod.rs create mode 100644 runtime/battery-station/src/integration_tests/xcm/restricted_calls.rs create mode 100644 runtime/battery-station/src/integration_tests/xcm/setup.rs create mode 100644 runtime/battery-station/src/integration_tests/xcm/test_net.rs create mode 100644 runtime/battery-station/src/integration_tests/xcm/tests/asset_registry.rs create mode 100644 runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs create mode 100644 runtime/battery-station/src/integration_tests/xcm/tests/mod.rs create mode 100644 runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs diff --git a/Cargo.lock b/Cargo.lock index d88b46ac4..5d0e38c0b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -462,6 +462,7 @@ dependencies = [ "frame-system-rpc-runtime-api", "frame-try-runtime", "hex-literal", + "kusama-runtime", "log", "nimbus-primitives", "orml-asset-registry", @@ -500,6 +501,8 @@ dependencies = [ "parachain-staking", "parity-scale-codec", "polkadot-parachain", + "polkadot-primitives", + "polkadot-runtime-parachains", "scale-info", "sp-api", "sp-block-builder", diff --git a/runtime/battery-station/Cargo.toml b/runtime/battery-station/Cargo.toml index 29129b1d8..3d2d45793 100644 --- a/runtime/battery-station/Cargo.toml +++ b/runtime/battery-station/Cargo.toml @@ -83,6 +83,10 @@ hex-literal = { default-features = false, optional = true, version = "0.3.4" } log = { version = "0.4.8", default-features = false, optional = true } # XCM +kusama-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +polkadot-primitives = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +polkadot-runtime-parachains = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +#xcm-emulator = { rev = "897fff07c8ac51baf9afcb0a895980fce7a5c921", default-features = false, git = "https://github.com/shaunxw/xcm-simulator", optional = true } orml-asset-registry = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-unknown-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } @@ -136,6 +140,10 @@ parachain = [ # XCM + "kusama-runtime", + "polkadot-primitives", + "polkadot-runtime-parachains", + #"xcm-emulator", "orml-asset-registry", "orml-unknown-tokens", "orml-xcm-support", @@ -276,6 +284,13 @@ std = [ "xcm-builder?/std", "xcm-executor?/std", "xcm?/std", + + # XCM test dependencies + # TODO Only include those when in test environment and feature=parachain + "kusama-runtime?/std", + "polkadot-primitives?/std", + "polkadot-runtime-parachains?/std", + #"xcm-emulator?/std", # Zeitgeist diff --git a/runtime/battery-station/src/integration_tests/mod.rs b/runtime/battery-station/src/integration_tests/mod.rs new file mode 100644 index 000000000..3e18ffdd8 --- /dev/null +++ b/runtime/battery-station/src/integration_tests/mod.rs @@ -0,0 +1,19 @@ +// Copyright 2022 Forecasting Technologies LTD. +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +#![cfg(test)] + +mod xcm; \ No newline at end of file diff --git a/runtime/battery-station/src/integration_tests/xcm/mod.rs b/runtime/battery-station/src/integration_tests/xcm/mod.rs new file mode 100644 index 000000000..1ab18d3f5 --- /dev/null +++ b/runtime/battery-station/src/integration_tests/xcm/mod.rs @@ -0,0 +1,22 @@ +// Copyright 2022 Forecasting Technologies LTD. +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +#![cfg(all(feature = "parachain", test))] + +mod restricted_calls; +mod setup; +mod test_net; +mod tests; diff --git a/runtime/battery-station/src/integration_tests/xcm/restricted_calls.rs b/runtime/battery-station/src/integration_tests/xcm/restricted_calls.rs new file mode 100644 index 000000000..e69de29bb diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs new file mode 100644 index 000000000..b06d89234 --- /dev/null +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -0,0 +1,144 @@ +// Copyright 2021 Centrifuge Foundation (centrifuge.io). +// Copyright 2022 Forecasting Technologies LTD. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use crate::{AccountId, Balance, CurrencyId, Origin, Runtime, System, xcm_config::{asset_registry::CustomMetadata, config::zeitgeist}}; +use frame_support::traits::GenesisBuild; +use orml_traits::asset_registry::AssetMetadata; +use zeitgeist_primitives::types::Asset; + +/// Accounts +pub const ALICE: [u8; 32] = [4u8; 32]; +pub const BOB: [u8; 32] = [5u8; 32]; + +/// A PARA ID used for a sibling parachain. +/// It must be one that doesn't collide with any other in use. +pub const PARA_ID_SIBLING: u32 = 3000; + +/// IDs that are used to represent tokens from other chains +pub const FOREIGN_ZTG: Asset = CurrencyId::ForeignAsset(0); +pub const FOREIGN_KSM: Asset = CurrencyId::ForeigAsset(1); +pub const FOREIGN_SIBLING: Asset = CurrencyId::ForeignAsset(2); + + +pub struct ExtBuilder { + balances: Vec<(AccountId, CurrencyId, Balance)>, + parachain_id: u32, +} + +impl Default for ExtBuilder { + fn default() -> Self { + Self { + balances: vec![], + parachain_id: zeitgeist::ID, + } + } +} + +impl ExtBuilder { + pub fn balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { + self.balances = balances; + self + } + + pub fn parachain_id(mut self, parachain_id: u32) -> Self { + self.parachain_id = parachain_id; + self + } + + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + let native_currency_id = CurrencyId::Ztg; + pallet_balances::GenesisConfig:: { + balances: self + .balances + .clone() + .into_iter() + .filter(|(_, currency_id, _)| *currency_id == native_currency_id) + .map(|(account_id, _, initial_balance)| (account_id, initial_balance)) + .collect::>(), + } + .assimilate_storage(&mut t) + .unwrap(); + + orml_tokens::GenesisConfig:: { + balances: self + .balances + .into_iter() + .filter(|(_, currency_id, _)| *currency_id != native_currency_id) + .collect::>(), + } + .assimilate_storage(&mut t) + .unwrap(); + + >::assimilate_storage( + ¶chain_info::GenesisConfig { + parachain_id: self.parachain_id.into(), + }, + &mut t, + ) + .unwrap(); + + >::assimilate_storage( + &pallet_xcm::GenesisConfig { + safe_xcm_version: Some(2), + }, + &mut t, + ) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext + } +} + +pub fn ztg(amount: Balance) -> Balance { + amount * dollar(10) +} + +pub fn sibling(amount: Balance) -> Balance { + foreign(amount, 10) +} + +pub fn ksm(amount: Balance) -> Balance { + foreign(amount, 12) +} + +pub fn foreign(amount: Balance, decimals: u32) -> Balance { + amount * dollar(decimals) +} + +pub fn dollar(decimals: u32) -> Balance { + 10u128.saturating_pow(decimals.into()) +} + +pub fn sibling_account() -> AccountId { + parachain_account(PARA_ID_SIBLING.into()) +} + +pub fn zeitgeist_account() -> AccountId { + parachain_account(zeitgeist::ID) +} + +fn parachain_account(id: u32) -> AccountId { + use sp_runtime::traits::AccountIdConversion; + + polkadot_parachain::primitives::Sibling::from(id).into_account_truncating() +} \ No newline at end of file diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs new file mode 100644 index 000000000..c8b7bee57 --- /dev/null +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -0,0 +1,165 @@ +// Copyright 2021-2022 Centrifuge GmbH (centrifuge.io). +// Copyright 2022 Forecasting Technologies LTD. +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use crate::{AccountId, CurrencyId, Runtime, Origin, XcmpQueue, DmpQueue, TreasuryAccount, xcm_config::config::zeitgeist}; +use cumulus_primitives_core::ParaId; +use frame_support::{traits::GenesisBuild, weights::Weight}; +use polkadot_primitives::v2::{BlockNumber, MAX_CODE_SIZE, MAX_POV_SIZE}; +use polkadot_runtime_parachains::configuration::HostConfiguration; +use sp_runtime::traits::AccountIdConversion; +use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; + +use super::setup::{ztg, ksm, sibling, ExtBuilder, ALICE, BOB, PARA_ID_SIBLING}; + +decl_test_relay_chain! { + pub struct KusamaNet { + Runtime = kusama_runtime::Runtime, + XcmConfig = kusama_runtime::xcm_config::XcmConfig, + new_ext = relay_ext(), + } +} + +decl_test_parachain! { + pub struct Zeitgeist { + Runtime = Runtime, + Origin = Origin, + XcmpMessageHandler = XcmpQueue, + DmpMessageHandler = DmpQueue, + new_ext = para_ext(zeitgeist::ID), + } +} + +decl_test_parachain! { + pub struct Sibling { + Runtime = Runtime, + Origin = Origin, + XcmpMessageHandler = XcmpQueue, + DmpMessageHandler = DmpQueue, + new_ext = para_ext(PARA_ID_SIBLING), + } +} + +decl_test_network! { + pub struct TestNet { + relay_chain = KusamaNet, + parachains = vec![ + // N.B: Ideally, we could use the defined para id constants but doing so + // fails with: "error: arbitrary expressions aren't allowed in patterns" + + // Be sure to use `xcm_config::config::zeitgeist::ID` + (2101, Zeitgeist), + // Be sure to use `PARA_ID_SIBLING` + (3000, Sibling), + ], + } +} + +pub fn relay_ext() -> sp_io::TestExternalities { + use kusama_runtime::{Runtime, System}; + + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![ + (AccountId::from(ALICE), ksm(2002)), + ( + ParaId::from(zeitgeist::ID).into_account_truncating(), + ztg(7), + ), + ( + ParaId::from(PARA_ID_SIBLING).into_account_truncating(), + sibling(7), + ), + ], + } + .assimilate_storage(&mut t) + .unwrap(); + + polkadot_runtime_parachains::configuration::GenesisConfig:: { + config: default_parachains_host_configuration(), + } + .assimilate_storage(&mut t) + .unwrap(); + + >::assimilate_storage( + &pallet_xcm::GenesisConfig { + safe_xcm_version: Some(2), + }, + &mut t, + ) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} + +pub fn para_ext(parachain_id: u32) -> sp_io::TestExternalities { + ExtBuilder::default() + .balances(vec![ + (AccountId::from(ALICE), CurrencyId::Ztg, ztg(10)), + (AccountId::from(BOB), CurrencyId::Ztg, ztg(10)), + (AccountId::from(ALICE), CurrencyId::ForeignAsset(FOREIGN_KSM), ksm(10)), + ( + TreasuryAccount::get(), + CurrencyId::ForeignAsset(FOREIGN_KSM), + ksm(1), + ), + ]) + .parachain_id(parachain_id) + .build() +} + +fn default_parachains_host_configuration() -> HostConfiguration { + HostConfiguration { + minimum_validation_upgrade_delay: 5, + validation_upgrade_cooldown: 5u32, + validation_upgrade_delay: 5, + code_retention_period: 1200, + max_code_size: MAX_CODE_SIZE, + max_pov_size: MAX_POV_SIZE, + max_head_data_size: 32 * 1024, + group_rotation_frequency: 20, + chain_availability_period: 4, + thread_availability_period: 4, + max_upward_queue_count: 8, + max_upward_queue_size: 1024 * 1024, + max_downward_message_size: 1024, + ump_service_total_weight: Weight::from_ref_time(4 * 1_000_000_000), + max_upward_message_size: 50 * 1024, + max_upward_message_num_per_candidate: 5, + hrmp_sender_deposit: 0, + hrmp_recipient_deposit: 0, + hrmp_channel_max_capacity: 8, + hrmp_channel_max_total_size: 8 * 1024, + hrmp_max_parachain_inbound_channels: 4, + hrmp_max_parathread_inbound_channels: 4, + hrmp_channel_max_message_size: 1024 * 1024, + hrmp_max_parachain_outbound_channels: 4, + hrmp_max_parathread_outbound_channels: 4, + hrmp_max_message_num_per_candidate: 5, + dispute_period: 6, + no_show_slots: 2, + n_delay_tranches: 25, + needed_approvals: 2, + relay_vrf_modulo_samples: 2, + zeroth_delay_tranche_width: 0, + ..Default::default() + } +} \ No newline at end of file diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/asset_registry.rs b/runtime/battery-station/src/integration_tests/xcm/tests/asset_registry.rs new file mode 100644 index 000000000..e69de29bb diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs new file mode 100644 index 000000000..e69de29bb diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/mod.rs b/runtime/battery-station/src/integration_tests/xcm/tests/mod.rs new file mode 100644 index 000000000..06be98bf8 --- /dev/null +++ b/runtime/battery-station/src/integration_tests/xcm/tests/mod.rs @@ -0,0 +1,3 @@ +mod asset_registry; +mod currency_id_convert; +mod transfers; diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs new file mode 100644 index 000000000..e69de29bb diff --git a/runtime/battery-station/src/lib.rs b/runtime/battery-station/src/lib.rs index 3f78b81e7..e296e1a62 100644 --- a/runtime/battery-station/src/lib.rs +++ b/runtime/battery-station/src/lib.rs @@ -81,6 +81,9 @@ use sp_version::RuntimeVersion; pub mod parachain_params; pub mod parameters; #[cfg(feature = "parachain")] +#[cfg(test)] +pub mod integration_tests; +#[cfg(feature = "parachain")] pub mod xcm_config; pub const VERSION: RuntimeVersion = RuntimeVersion { diff --git a/runtime/battery-station/src/parachain_params.rs b/runtime/battery-station/src/parachain_params.rs index 234f81325..6c64c81ca 100644 --- a/runtime/battery-station/src/parachain_params.rs +++ b/runtime/battery-station/src/parachain_params.rs @@ -24,7 +24,7 @@ use super::{ parameters::MAXIMUM_BLOCK_WEIGHT, Origin, ParachainInfo, - xcm_config::parachains::zeitgeist::{ID as ZTG_PARAID}, + xcm_config::config::zeitgeist::{ID as ZTG_PARAID}, }; use frame_support::{parameter_types, weights::Weight}; use orml_traits::parameter_type_with_key; diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index fa128363f..7a458cce0 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -17,7 +17,6 @@ use super::{ fees::{native_per_second, FixedConversionRateProvider}, - parachains::zeitgeist::{ID as ZTG_PARAID, ZTG_KEY}, }; use crate::{ AccountId, Ancestry, AssetManager, AssetRegistry, Balance, Call, CurrencyId, MaxInstructions, @@ -52,6 +51,11 @@ use xcm_builder::{ use xcm_executor::Config; use zeitgeist_primitives::types::Asset; +pub mod zeitgeist { + pub const ID: u32 = 2101; + pub const KEY: &[u8] = &[0, 1]; +} + pub struct XcmConfig; /// The main XCM config @@ -144,7 +148,7 @@ parameter_types! { pub ZtgPerSecond: (AssetId, u128) = ( MultiLocation::new( 0, - X1(general_key(ZTG_KEY)), + X1(general_key(zeitgeist::KEY)), ).into(), native_per_second(), ); @@ -186,8 +190,8 @@ impl Convert> for AssetConvert { Asset::Ztg => Some(MultiLocation::new( 1, X2( - Junction::Parachain(ZTG_PARAID), - general_key(ZTG_KEY), + Junction::Parachain(zeitgeist::ID), + general_key(zeitgeist::KEY), ), )), Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, @@ -203,15 +207,15 @@ impl xcm_executor::traits::Convert for AssetConvert { fn convert(location: MultiLocation) -> Result { match location.clone() { MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { - ZTG_KEY => Ok(CurrencyId::Ztg), + zeitgeist::KEY => Ok(CurrencyId::Ztg), _ => Err(location), }, MultiLocation { parents: 1, interior: X2(Junction::Parachain(para_id), GeneralKey(key)), } => match para_id { - ZTG_PARAID => match &key[..] { - ZTG_KEY => Ok(CurrencyId::Ztg), + zeitgeist::ID => match &key[..] { + zeitgeist::KEY => Ok(CurrencyId::Ztg), _ => Err(location), }, _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), From c1e2b968a093638e1061d35a197b3dc9a3bfcd53 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Tue, 1 Nov 2022 12:49:00 +0200 Subject: [PATCH 17/59] Finalize simulated network preparation --- Cargo.lock | 25 +++++++++++++++++++ Cargo.toml | 3 +++ primitives/src/constants.rs | 5 ++++ primitives/src/constants/mock.rs | 2 +- runtime/battery-station/Cargo.toml | 4 +-- .../src/integration_tests/xcm/setup.rs | 4 +-- .../src/integration_tests/xcm/test_net.rs | 16 ++++++------ runtime/battery-station/src/parameters.rs | 2 +- runtime/zeitgeist/src/parameters.rs | 2 +- 9 files changed, 47 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d0e38c0b..7fc7e2610 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -520,6 +520,7 @@ dependencies = [ "substrate-wasm-builder", "xcm", "xcm-builder", + "xcm-emulator", "xcm-executor", "zeitgeist-primitives", "zrml-authorized", @@ -12564,6 +12565,30 @@ dependencies = [ "xcm-executor", ] +[[package]] +name = "xcm-emulator" +version = "0.1.0" +source = "git+https://github.com/sea212/xcm-simulator?branch=polkadot-v0.9.19-moonbeam#44f8a9ab874f1ce990c551b4e2429cb4a0e36e04" +dependencies = [ + "cumulus-pallet-dmp-queue", + "cumulus-pallet-parachain-system", + "cumulus-pallet-xcmp-queue", + "cumulus-primitives-core", + "cumulus-primitives-parachain-inherent", + "cumulus-test-relay-sproof-builder", + "frame-support", + "frame-system", + "parachain-info", + "parity-scale-codec", + "paste", + "polkadot-primitives", + "polkadot-runtime-parachains", + "sp-io", + "sp-std", + "xcm", + "xcm-executor", +] + [[package]] name = "xcm-executor" version = "0.9.19" diff --git a/Cargo.toml b/Cargo.toml index d20aa83bc..1f159b367 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,3 +48,6 @@ resolver = "2" [patch."https://github.com/purestake/moonbeam"] pallet-author-mapping = { git = "https://github.com/zeitgeistpm/moonbeam", branch = "downgrade-staking-and-mapping" } parachain-staking = { git = "https://github.com/zeitgeistpm/moonbeam", branch = "downgrade-staking-and-mapping" } + +[patch."https://github.com/shaunxw/xcm-simulator"] +xcm-emulator = { git = "https://github.com/sea212/xcm-simulator", branch = "polkadot-v0.9.19-moonbeam" } \ No newline at end of file diff --git a/primitives/src/constants.rs b/primitives/src/constants.rs index 92a6ca28e..18df2d88d 100644 --- a/primitives/src/constants.rs +++ b/primitives/src/constants.rs @@ -85,3 +85,8 @@ pub const SD_PALLET_ID: PalletId = PalletId(*b"zge/sedp"); pub const MAX_ASSETS: u16 = MAX_CATEGORIES + 1; /// Pallet identifier, mainly used for named balance reserves. pub const SWAPS_PALLET_ID: PalletId = PalletId(*b"zge/swap"); + + +// Treasury +/// Pallet identifier, used to derive treasury account +pub const TREASURY_PALLET_ID: PalletId = PalletId(*b"zge/swap"); \ No newline at end of file diff --git a/primitives/src/constants/mock.rs b/primitives/src/constants/mock.rs index 0ea728082..0e6a1299f 100644 --- a/primitives/src/constants/mock.rs +++ b/primitives/src/constants/mock.rs @@ -100,4 +100,4 @@ parameter_types! { // Time parameter_types! { pub const MinimumPeriod: u64 = MILLISECS_PER_BLOCK as u64 / 2; -} +} \ No newline at end of file diff --git a/runtime/battery-station/Cargo.toml b/runtime/battery-station/Cargo.toml index 3d2d45793..a42e5d186 100644 --- a/runtime/battery-station/Cargo.toml +++ b/runtime/battery-station/Cargo.toml @@ -86,7 +86,6 @@ log = { version = "0.4.8", default-features = false, optional = true } kusama-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } polkadot-primitives = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } polkadot-runtime-parachains = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -#xcm-emulator = { rev = "897fff07c8ac51baf9afcb0a895980fce7a5c921", default-features = false, git = "https://github.com/shaunxw/xcm-simulator", optional = true } orml-asset-registry = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-unknown-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } @@ -113,6 +112,7 @@ zrml-swaps-runtime-api = { default-features = false, path = "../../zrml/swaps/ru [dev-dependencies] sp-io = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate" } +xcm-emulator = { rev = "6c358483d8e119cd3b631ebb14d3b0cf0041d94e", git = "https://github.com/shaunxw/xcm-simulator" } [features] default = ["std"] @@ -143,7 +143,6 @@ parachain = [ "kusama-runtime", "polkadot-primitives", "polkadot-runtime-parachains", - #"xcm-emulator", "orml-asset-registry", "orml-unknown-tokens", "orml-xcm-support", @@ -290,7 +289,6 @@ std = [ "kusama-runtime?/std", "polkadot-primitives?/std", "polkadot-runtime-parachains?/std", - #"xcm-emulator?/std", # Zeitgeist diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs index b06d89234..3d134d7fb 100644 --- a/runtime/battery-station/src/integration_tests/xcm/setup.rs +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -31,7 +31,7 @@ pub const PARA_ID_SIBLING: u32 = 3000; /// IDs that are used to represent tokens from other chains pub const FOREIGN_ZTG: Asset = CurrencyId::ForeignAsset(0); -pub const FOREIGN_KSM: Asset = CurrencyId::ForeigAsset(1); +pub const FOREIGN_KSM: Asset = CurrencyId::ForeignAsset(1); pub const FOREIGN_SIBLING: Asset = CurrencyId::ForeignAsset(2); @@ -140,5 +140,5 @@ pub fn zeitgeist_account() -> AccountId { fn parachain_account(id: u32) -> AccountId { use sp_runtime::traits::AccountIdConversion; - polkadot_parachain::primitives::Sibling::from(id).into_account_truncating() + polkadot_parachain::primitives::Sibling::from(id).into_account() } \ No newline at end of file diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index c8b7bee57..129d451d0 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -15,7 +15,7 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::{AccountId, CurrencyId, Runtime, Origin, XcmpQueue, DmpQueue, TreasuryAccount, xcm_config::config::zeitgeist}; +use crate::{AccountId, CurrencyId, Runtime, Origin, XcmpQueue, DmpQueue, parameters::ZeitgeistTreasuryAccount, xcm_config::config::zeitgeist}; use cumulus_primitives_core::ParaId; use frame_support::{traits::GenesisBuild, weights::Weight}; use polkadot_primitives::v2::{BlockNumber, MAX_CODE_SIZE, MAX_POV_SIZE}; @@ -23,7 +23,7 @@ use polkadot_runtime_parachains::configuration::HostConfiguration; use sp_runtime::traits::AccountIdConversion; use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; -use super::setup::{ztg, ksm, sibling, ExtBuilder, ALICE, BOB, PARA_ID_SIBLING}; +use super::setup::{ztg, ksm, sibling, ExtBuilder, ALICE, BOB, PARA_ID_SIBLING, FOREIGN_KSM}; decl_test_relay_chain! { pub struct KusamaNet { @@ -79,11 +79,11 @@ pub fn relay_ext() -> sp_io::TestExternalities { balances: vec![ (AccountId::from(ALICE), ksm(2002)), ( - ParaId::from(zeitgeist::ID).into_account_truncating(), + ParaId::from(zeitgeist::ID).into_account(), ztg(7), ), ( - ParaId::from(PARA_ID_SIBLING).into_account_truncating(), + ParaId::from(PARA_ID_SIBLING).into_account(), sibling(7), ), ], @@ -115,10 +115,10 @@ pub fn para_ext(parachain_id: u32) -> sp_io::TestExternalities { .balances(vec![ (AccountId::from(ALICE), CurrencyId::Ztg, ztg(10)), (AccountId::from(BOB), CurrencyId::Ztg, ztg(10)), - (AccountId::from(ALICE), CurrencyId::ForeignAsset(FOREIGN_KSM), ksm(10)), + (AccountId::from(ALICE), FOREIGN_KSM, ksm(10)), ( - TreasuryAccount::get(), - CurrencyId::ForeignAsset(FOREIGN_KSM), + ZeitgeistTreasuryAccount::get(), + FOREIGN_KSM, ksm(1), ), ]) @@ -141,7 +141,7 @@ fn default_parachains_host_configuration() -> HostConfiguration { max_upward_queue_count: 8, max_upward_queue_size: 1024 * 1024, max_downward_message_size: 1024, - ump_service_total_weight: Weight::from_ref_time(4 * 1_000_000_000), + ump_service_total_weight: Weight::from(4 * 1_000_000_000u32), max_upward_message_size: 50 * 1024, max_upward_message_num_per_candidate: 5, hrmp_sender_deposit: 0, diff --git a/runtime/battery-station/src/parameters.rs b/runtime/battery-station/src/parameters.rs index ad6d6ee8e..345959981 100644 --- a/runtime/battery-station/src/parameters.rs +++ b/runtime/battery-station/src/parameters.rs @@ -286,7 +286,7 @@ parameter_types! { /// Period between successive spends. pub const SpendPeriod: BlockNumber = 24 * BLOCKS_PER_DAY; /// Pallet identifier, mainly used for named balance reserves. - pub const TreasuryPalletId: PalletId = PalletId(*b"zge/tsry"); + pub const TreasuryPalletId: PalletId = TREASURY_PALLET_ID; /// Treasury account. pub ZeitgeistTreasuryAccount: AccountId = TreasuryPalletId::get().into_account(); diff --git a/runtime/zeitgeist/src/parameters.rs b/runtime/zeitgeist/src/parameters.rs index 73c8c8b53..e4b95358b 100644 --- a/runtime/zeitgeist/src/parameters.rs +++ b/runtime/zeitgeist/src/parameters.rs @@ -286,7 +286,7 @@ parameter_types! { /// Period between successive spends. pub const SpendPeriod: BlockNumber = 24 * BLOCKS_PER_DAY; /// Pallet identifier, mainly used for named balance reserves. DO NOT CHANGE. - pub const TreasuryPalletId: PalletId = PalletId(*b"zge/tsry"); + pub const TreasuryPalletId: PalletId = TREASURY_PALLET_ID; // Vesting pub const MinVestedTransfer: Balance = ExistentialDeposit::get(); From 49d468e6c141f2388d5ef6f3be5cd68fdaf5b017 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Tue, 1 Nov 2022 14:10:14 +0200 Subject: [PATCH 18/59] Add currency conversion tests --- .../xcm/tests/currency_id_convert.rs | 147 ++++++++++++++++++ .../src/xcm_config/asset_registry.rs | 2 +- .../battery-station/src/xcm_config/config.rs | 2 +- 3 files changed, 149 insertions(+), 2 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs index e69de29bb..505f2c17a 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -0,0 +1,147 @@ +// Copyright 2021 Centrifuge Foundation (centrifuge.io). +// Copyright 2022 Forecasting Technologies LTD. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use crate::{ + Balances, CurrencyId, Origin, AssetRegistry, Tokens, XTokens, + xcm_config::{ + asset_registry::{CustomMetadata, XcmMetadata}, + config::{general_key, zeitgeist, AssetConvert}, + fees::default_per_second, + }, + integration_tests::xcm::{ + setup::{ + ztg, zeitgeist_account, sibling, foreign, ksm, sibling_account, ALICE, BOB, + PARA_ID_SIBLING, + }, + test_net::{Zeitgeist, KusamaNet, Sibling, TestNet}, + }, +}; + +use parity_scale_codec::Encode; +use frame_support::assert_ok; +use orml_traits::{asset_registry::AssetMetadata, FixedConversionRateProvider, MultiCurrency}; +use sp_runtime::{ + traits::{Convert as C2}, +}; +use xcm::{ + latest::{Error::BadOrigin, Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, + VersionedMultiLocation, +}; +use xcm_emulator::TestExt; +use xcm_executor::traits::Convert as C1; + +/* + +#[test] +fn convert_native() { + assert_eq!(parachains::kusama::altair::AIR_KEY.to_vec(), vec![0, 1]); + + // The way AIR is represented relative within the Altair runtime + let air_location_inner: MultiLocation = + MultiLocation::new(0, X1(general_key(parachains::kusama::altair::AIR_KEY))); + + assert_eq!( + >::convert(air_location_inner), + Ok(CurrencyId::Native), + ); + + // The canonical way AIR is represented out in the wild + let air_location_canonical: MultiLocation = MultiLocation::new( + 1, + X2( + Parachain(parachains::kusama::altair::ID), + general_key(parachains::kusama::altair::AIR_KEY), + ), + ); + + Altair::execute_with(|| { + assert_eq!( + >::convert(CurrencyId::Native), + Some(air_location_canonical) + ) + }); +} + +#[test] +fn convert_sibling() { + assert_eq!(parachains::kusama::karura::AUSD_KEY, &[0, 129]); + + let ausd_location: MultiLocation = MultiLocation::new( + 1, + X2( + Parachain(parachains::kusama::karura::ID), + general_key(parachains::kusama::karura::AUSD_KEY), + ), + ); + + Altair::execute_with(|| { + assert_eq!( + >::convert(ausd_location.clone()), + Ok(CurrencyId::AUSD), + ); + + assert_eq!( + >::convert(CurrencyId::AUSD), + Some(ausd_location) + ) + }); +} + +#[test] +fn convert_parent() { + let ksm_location: MultiLocation = MultiLocation::parent().into(); + + Altair::execute_with(|| { + assert_eq!( + >::convert(ksm_location.clone()), + Ok(CurrencyId::KSM), + ); + + assert_eq!( + >::convert(CurrencyId::KSM), + Some(ksm_location) + ) + }); +} + +*/ + +#[test] +fn convert_unkown_multilocation() { + let unknown_location: MultiLocation = MultiLocation::new( + 1, + X2( + Parachain(zeitgeist::ID), + general_key(&[42]), + ), + ); + + Zeitgeist::execute_with(|| { + assert!(>::convert(unknown_location.clone()).is_err()); + }); +} + +#[test] +fn convert_unsupported_currency() { + Zeitgeist::execute_with(|| { + assert_eq!( + >::convert(CurrencyId::CombinatorialOutcome), + None + ) + }); +} \ No newline at end of file diff --git a/runtime/battery-station/src/xcm_config/asset_registry.rs b/runtime/battery-station/src/xcm_config/asset_registry.rs index ea2d2456c..ba7807a8c 100644 --- a/runtime/battery-station/src/xcm_config/asset_registry.rs +++ b/runtime/battery-station/src/xcm_config/asset_registry.rs @@ -86,7 +86,7 @@ pub struct CustomMetadata { )] pub struct XcmMetadata { /// The factor used to determine the fee. - /// It is multiplied by the fee that would have been paind in native currency, so it represents + /// It is multiplied by the fee that would have been paid in native currency, so it represents /// the ratio `native_price / other_asset_price`. It is a fixed point decimal number containing /// as many fractional decimals as the asset it is used for contains. /// Should be updated regularly. diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 7a458cce0..7039b525a 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -307,6 +307,6 @@ match_types! { } #[inline] -fn general_key(key: &[u8]) -> Junction { +pub(crate) fn general_key(key: &[u8]) -> Junction { GeneralKey(Vec::from(key)) } From 31933cd7c178136e52630f2834e28eb9e44f1989 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Wed, 2 Nov 2022 10:02:51 +0200 Subject: [PATCH 19/59] Finalize CurrencyID<>MultiLocation tests --- .../src/integration_tests/mod.rs | 2 +- .../integration_tests/xcm/restricted_calls.rs | 1 + .../src/integration_tests/xcm/setup.rs | 153 ++++++------ .../src/integration_tests/xcm/test_net.rs | 225 +++++++++--------- .../xcm/tests/asset_registry.rs | 1 + .../xcm/tests/currency_id_convert.rs | 165 ++++++------- .../integration_tests/xcm/tests/transfers.rs | 162 +++++++++++++ runtime/battery-station/src/lib.rs | 36 ++- .../battery-station/src/parachain_params.rs | 12 +- .../battery-station/src/xcm_config/config.rs | 39 ++- 10 files changed, 452 insertions(+), 344 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/mod.rs b/runtime/battery-station/src/integration_tests/mod.rs index 3e18ffdd8..64f89683b 100644 --- a/runtime/battery-station/src/integration_tests/mod.rs +++ b/runtime/battery-station/src/integration_tests/mod.rs @@ -16,4 +16,4 @@ #![cfg(test)] -mod xcm; \ No newline at end of file +mod xcm; diff --git a/runtime/battery-station/src/integration_tests/xcm/restricted_calls.rs b/runtime/battery-station/src/integration_tests/xcm/restricted_calls.rs index e69de29bb..8b1378917 100644 --- a/runtime/battery-station/src/integration_tests/xcm/restricted_calls.rs +++ b/runtime/battery-station/src/integration_tests/xcm/restricted_calls.rs @@ -0,0 +1 @@ + diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs index 3d134d7fb..280b4c7d6 100644 --- a/runtime/battery-station/src/integration_tests/xcm/setup.rs +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -16,7 +16,10 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::{AccountId, Balance, CurrencyId, Origin, Runtime, System, xcm_config::{asset_registry::CustomMetadata, config::zeitgeist}}; +use crate::{ + xcm_config::{asset_registry::CustomMetadata, config::zeitgeist}, + AccountId, Balance, CurrencyId, Origin, Runtime, System, +}; use frame_support::traits::GenesisBuild; use orml_traits::asset_registry::AssetMetadata; use zeitgeist_primitives::types::Asset; @@ -30,115 +33,105 @@ pub const BOB: [u8; 32] = [5u8; 32]; pub const PARA_ID_SIBLING: u32 = 3000; /// IDs that are used to represent tokens from other chains -pub const FOREIGN_ZTG: Asset = CurrencyId::ForeignAsset(0); -pub const FOREIGN_KSM: Asset = CurrencyId::ForeignAsset(1); -pub const FOREIGN_SIBLING: Asset = CurrencyId::ForeignAsset(2); - +pub const FOREIGN_ZTG_ID: Asset = CurrencyId::ForeignAsset(0); +pub const FOREIGN_KSM_ID: Asset = CurrencyId::ForeignAsset(1); +pub const FOREIGN_SIBLING_ID: Asset = CurrencyId::ForeignAsset(2); pub struct ExtBuilder { - balances: Vec<(AccountId, CurrencyId, Balance)>, - parachain_id: u32, + balances: Vec<(AccountId, CurrencyId, Balance)>, + parachain_id: u32, } impl Default for ExtBuilder { - fn default() -> Self { - Self { - balances: vec![], - parachain_id: zeitgeist::ID, - } - } + fn default() -> Self { + Self { balances: vec![], parachain_id: zeitgeist::ID } + } } impl ExtBuilder { - pub fn balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { - self.balances = balances; - self - } - - pub fn parachain_id(mut self, parachain_id: u32) -> Self { - self.parachain_id = parachain_id; - self - } - - pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - let native_currency_id = CurrencyId::Ztg; - pallet_balances::GenesisConfig:: { - balances: self - .balances - .clone() - .into_iter() - .filter(|(_, currency_id, _)| *currency_id == native_currency_id) - .map(|(account_id, _, initial_balance)| (account_id, initial_balance)) - .collect::>(), - } - .assimilate_storage(&mut t) - .unwrap(); - - orml_tokens::GenesisConfig:: { - balances: self - .balances - .into_iter() - .filter(|(_, currency_id, _)| *currency_id != native_currency_id) - .collect::>(), - } - .assimilate_storage(&mut t) - .unwrap(); - - >::assimilate_storage( - ¶chain_info::GenesisConfig { - parachain_id: self.parachain_id.into(), - }, - &mut t, - ) - .unwrap(); - - >::assimilate_storage( - &pallet_xcm::GenesisConfig { - safe_xcm_version: Some(2), - }, - &mut t, - ) - .unwrap(); - - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext - } + pub fn balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { + self.balances = balances; + self + } + + pub fn parachain_id(mut self, parachain_id: u32) -> Self { + self.parachain_id = parachain_id; + self + } + + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let native_currency_id = CurrencyId::Ztg; + pallet_balances::GenesisConfig:: { + balances: self + .balances + .clone() + .into_iter() + .filter(|(_, currency_id, _)| *currency_id == native_currency_id) + .map(|(account_id, _, initial_balance)| (account_id, initial_balance)) + .collect::>(), + } + .assimilate_storage(&mut t) + .unwrap(); + + orml_tokens::GenesisConfig:: { + balances: self + .balances + .into_iter() + .filter(|(_, currency_id, _)| *currency_id != native_currency_id) + .collect::>(), + } + .assimilate_storage(&mut t) + .unwrap(); + + >::assimilate_storage( + ¶chain_info::GenesisConfig { parachain_id: self.parachain_id.into() }, + &mut t, + ) + .unwrap(); + + >::assimilate_storage( + &pallet_xcm::GenesisConfig { safe_xcm_version: Some(2) }, + &mut t, + ) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext + } } pub fn ztg(amount: Balance) -> Balance { - amount * dollar(10) + amount * dollar(10) } pub fn sibling(amount: Balance) -> Balance { - foreign(amount, 10) + foreign(amount, 10) } pub fn ksm(amount: Balance) -> Balance { - foreign(amount, 12) + foreign(amount, 12) } pub fn foreign(amount: Balance, decimals: u32) -> Balance { - amount * dollar(decimals) + amount * dollar(decimals) } pub fn dollar(decimals: u32) -> Balance { - 10u128.saturating_pow(decimals.into()) + 10u128.saturating_pow(decimals.into()) } pub fn sibling_account() -> AccountId { - parachain_account(PARA_ID_SIBLING.into()) + parachain_account(PARA_ID_SIBLING.into()) } pub fn zeitgeist_account() -> AccountId { - parachain_account(zeitgeist::ID) + parachain_account(zeitgeist::ID) } fn parachain_account(id: u32) -> AccountId { - use sp_runtime::traits::AccountIdConversion; + use sp_runtime::traits::AccountIdConversion; - polkadot_parachain::primitives::Sibling::from(id).into_account() -} \ No newline at end of file + polkadot_parachain::primitives::Sibling::from(id).into_account() +} diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index 129d451d0..2100f8ec1 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -15,151 +15,144 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::{AccountId, CurrencyId, Runtime, Origin, XcmpQueue, DmpQueue, parameters::ZeitgeistTreasuryAccount, xcm_config::config::zeitgeist}; +use crate::{ + parameters::ZeitgeistTreasuryAccount, + xcm_config::{asset_registry::CustomMetadata, config::zeitgeist}, + AccountId, CurrencyId, DmpQueue, Origin, Runtime, XcmpQueue, +}; use cumulus_primitives_core::ParaId; use frame_support::{traits::GenesisBuild, weights::Weight}; +use orml_traits::asset_registry::AssetMetadata; use polkadot_primitives::v2::{BlockNumber, MAX_CODE_SIZE, MAX_POV_SIZE}; use polkadot_runtime_parachains::configuration::HostConfiguration; use sp_runtime::traits::AccountIdConversion; use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; -use super::setup::{ztg, ksm, sibling, ExtBuilder, ALICE, BOB, PARA_ID_SIBLING, FOREIGN_KSM}; +use super::setup::{ksm, sibling, ztg, ExtBuilder, ALICE, BOB, FOREIGN_KSM_ID, PARA_ID_SIBLING}; decl_test_relay_chain! { - pub struct KusamaNet { - Runtime = kusama_runtime::Runtime, - XcmConfig = kusama_runtime::xcm_config::XcmConfig, - new_ext = relay_ext(), - } + pub struct KusamaNet { + Runtime = kusama_runtime::Runtime, + XcmConfig = kusama_runtime::xcm_config::XcmConfig, + new_ext = relay_ext(), + } } decl_test_parachain! { - pub struct Zeitgeist { - Runtime = Runtime, - Origin = Origin, - XcmpMessageHandler = XcmpQueue, - DmpMessageHandler = DmpQueue, - new_ext = para_ext(zeitgeist::ID), - } + pub struct Zeitgeist { + Runtime = Runtime, + Origin = Origin, + XcmpMessageHandler = XcmpQueue, + DmpMessageHandler = DmpQueue, + new_ext = para_ext(zeitgeist::ID), + } } decl_test_parachain! { - pub struct Sibling { - Runtime = Runtime, - Origin = Origin, - XcmpMessageHandler = XcmpQueue, - DmpMessageHandler = DmpQueue, - new_ext = para_ext(PARA_ID_SIBLING), - } + pub struct Sibling { + Runtime = Runtime, + Origin = Origin, + XcmpMessageHandler = XcmpQueue, + DmpMessageHandler = DmpQueue, + new_ext = para_ext(PARA_ID_SIBLING), + } } decl_test_network! { - pub struct TestNet { - relay_chain = KusamaNet, - parachains = vec![ - // N.B: Ideally, we could use the defined para id constants but doing so - // fails with: "error: arbitrary expressions aren't allowed in patterns" + pub struct TestNet { + relay_chain = KusamaNet, + parachains = vec![ + // N.B: Ideally, we could use the defined para id constants but doing so + // fails with: "error: arbitrary expressions aren't allowed in patterns" - // Be sure to use `xcm_config::config::zeitgeist::ID` - (2101, Zeitgeist), - // Be sure to use `PARA_ID_SIBLING` - (3000, Sibling), - ], - } + // Be sure to use `xcm_config::config::zeitgeist::ID` + (2101, Zeitgeist), + // Be sure to use `PARA_ID_SIBLING` + (3000, Sibling), + ], + } } pub fn relay_ext() -> sp_io::TestExternalities { - use kusama_runtime::{Runtime, System}; + use kusama_runtime::{Runtime, System}; - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - pallet_balances::GenesisConfig:: { - balances: vec![ - (AccountId::from(ALICE), ksm(2002)), - ( - ParaId::from(zeitgeist::ID).into_account(), - ztg(7), - ), - ( - ParaId::from(PARA_ID_SIBLING).into_account(), - sibling(7), - ), - ], - } - .assimilate_storage(&mut t) - .unwrap(); + pallet_balances::GenesisConfig:: { + balances: vec![ + (AccountId::from(ALICE), ksm(2002)), + (ParaId::from(zeitgeist::ID).into_account(), ztg(7)), + (ParaId::from(PARA_ID_SIBLING).into_account(), sibling(7)), + ], + } + .assimilate_storage(&mut t) + .unwrap(); - polkadot_runtime_parachains::configuration::GenesisConfig:: { - config: default_parachains_host_configuration(), - } - .assimilate_storage(&mut t) - .unwrap(); + polkadot_runtime_parachains::configuration::GenesisConfig:: { + config: default_parachains_host_configuration(), + } + .assimilate_storage(&mut t) + .unwrap(); - >::assimilate_storage( - &pallet_xcm::GenesisConfig { - safe_xcm_version: Some(2), - }, - &mut t, - ) - .unwrap(); + >::assimilate_storage( + &pallet_xcm::GenesisConfig { safe_xcm_version: Some(2) }, + &mut t, + ) + .unwrap(); - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext } -pub fn para_ext(parachain_id: u32) -> sp_io::TestExternalities { - ExtBuilder::default() - .balances(vec![ - (AccountId::from(ALICE), CurrencyId::Ztg, ztg(10)), - (AccountId::from(BOB), CurrencyId::Ztg, ztg(10)), - (AccountId::from(ALICE), FOREIGN_KSM, ksm(10)), - ( - ZeitgeistTreasuryAccount::get(), - FOREIGN_KSM, - ksm(1), - ), - ]) - .parachain_id(parachain_id) - .build() +pub fn para_ext( + parachain_id: u32, +) -> sp_io::TestExternalities { + ExtBuilder::default() + .balances(vec![ + (AccountId::from(ALICE), CurrencyId::Ztg, ztg(10)), + (AccountId::from(BOB), CurrencyId::Ztg, ztg(10)), + (AccountId::from(ALICE), FOREIGN_KSM_ID, ksm(10)), + (ZeitgeistTreasuryAccount::get(), FOREIGN_KSM_ID, ksm(1)), + ]) + .parachain_id(parachain_id) + .build() } fn default_parachains_host_configuration() -> HostConfiguration { - HostConfiguration { - minimum_validation_upgrade_delay: 5, - validation_upgrade_cooldown: 5u32, - validation_upgrade_delay: 5, - code_retention_period: 1200, - max_code_size: MAX_CODE_SIZE, - max_pov_size: MAX_POV_SIZE, - max_head_data_size: 32 * 1024, - group_rotation_frequency: 20, - chain_availability_period: 4, - thread_availability_period: 4, - max_upward_queue_count: 8, - max_upward_queue_size: 1024 * 1024, - max_downward_message_size: 1024, - ump_service_total_weight: Weight::from(4 * 1_000_000_000u32), - max_upward_message_size: 50 * 1024, - max_upward_message_num_per_candidate: 5, - hrmp_sender_deposit: 0, - hrmp_recipient_deposit: 0, - hrmp_channel_max_capacity: 8, - hrmp_channel_max_total_size: 8 * 1024, - hrmp_max_parachain_inbound_channels: 4, - hrmp_max_parathread_inbound_channels: 4, - hrmp_channel_max_message_size: 1024 * 1024, - hrmp_max_parachain_outbound_channels: 4, - hrmp_max_parathread_outbound_channels: 4, - hrmp_max_message_num_per_candidate: 5, - dispute_period: 6, - no_show_slots: 2, - n_delay_tranches: 25, - needed_approvals: 2, - relay_vrf_modulo_samples: 2, - zeroth_delay_tranche_width: 0, - ..Default::default() - } -} \ No newline at end of file + HostConfiguration { + minimum_validation_upgrade_delay: 5, + validation_upgrade_cooldown: 5u32, + validation_upgrade_delay: 5, + code_retention_period: 1200, + max_code_size: MAX_CODE_SIZE, + max_pov_size: MAX_POV_SIZE, + max_head_data_size: 32 * 1024, + group_rotation_frequency: 20, + chain_availability_period: 4, + thread_availability_period: 4, + max_upward_queue_count: 8, + max_upward_queue_size: 1024 * 1024, + max_downward_message_size: 1024, + ump_service_total_weight: Weight::from(4 * 1_000_000_000u32), + max_upward_message_size: 50 * 1024, + max_upward_message_num_per_candidate: 5, + hrmp_sender_deposit: 0, + hrmp_recipient_deposit: 0, + hrmp_channel_max_capacity: 8, + hrmp_channel_max_total_size: 8 * 1024, + hrmp_max_parachain_inbound_channels: 4, + hrmp_max_parathread_inbound_channels: 4, + hrmp_channel_max_message_size: 1024 * 1024, + hrmp_max_parachain_outbound_channels: 4, + hrmp_max_parathread_outbound_channels: 4, + hrmp_max_message_num_per_candidate: 5, + dispute_period: 6, + no_show_slots: 2, + n_delay_tranches: 25, + needed_approvals: 2, + relay_vrf_modulo_samples: 2, + zeroth_delay_tranche_width: 0, + ..Default::default() + } +} diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/asset_registry.rs b/runtime/battery-station/src/integration_tests/xcm/tests/asset_registry.rs index e69de29bb..8b1378917 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/asset_registry.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/asset_registry.rs @@ -0,0 +1 @@ + diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs index 505f2c17a..74835a7cc 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -17,131 +17,100 @@ // along with Zeitgeist. If not, see . use crate::{ - Balances, CurrencyId, Origin, AssetRegistry, Tokens, XTokens, + integration_tests::xcm::{ + setup::{ + foreign, ksm, sibling, sibling_account, zeitgeist_account, ztg, ALICE, BOB, + PARA_ID_SIBLING, FOREIGN_KSM_ID, + }, + test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, + }, xcm_config::{ asset_registry::{CustomMetadata, XcmMetadata}, config::{general_key, zeitgeist, AssetConvert}, fees::default_per_second, }, - integration_tests::xcm::{ - setup::{ - ztg, zeitgeist_account, sibling, foreign, ksm, sibling_account, ALICE, BOB, - PARA_ID_SIBLING, - }, - test_net::{Zeitgeist, KusamaNet, Sibling, TestNet}, - }, + AssetRegistry, Balance, Balances, CurrencyId, Origin, Tokens, XTokens, }; -use parity_scale_codec::Encode; use frame_support::assert_ok; use orml_traits::{asset_registry::AssetMetadata, FixedConversionRateProvider, MultiCurrency}; -use sp_runtime::{ - traits::{Convert as C2}, -}; +use parity_scale_codec::Encode; +use sp_runtime::traits::Convert as C2; use xcm::{ - latest::{Error::BadOrigin, Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, + latest::{Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, VersionedMultiLocation, }; use xcm_emulator::TestExt; use xcm_executor::traits::Convert as C1; -/* #[test] fn convert_native() { - assert_eq!(parachains::kusama::altair::AIR_KEY.to_vec(), vec![0, 1]); - - // The way AIR is represented relative within the Altair runtime - let air_location_inner: MultiLocation = - MultiLocation::new(0, X1(general_key(parachains::kusama::altair::AIR_KEY))); - - assert_eq!( - >::convert(air_location_inner), - Ok(CurrencyId::Native), - ); - - // The canonical way AIR is represented out in the wild - let air_location_canonical: MultiLocation = MultiLocation::new( - 1, - X2( - Parachain(parachains::kusama::altair::ID), - general_key(parachains::kusama::altair::AIR_KEY), - ), - ); - - Altair::execute_with(|| { - assert_eq!( - >::convert(CurrencyId::Native), - Some(air_location_canonical) - ) - }); -} + assert_eq!(zeitgeist::KEY.to_vec(), vec![0, 1]); -#[test] -fn convert_sibling() { - assert_eq!(parachains::kusama::karura::AUSD_KEY, &[0, 129]); - - let ausd_location: MultiLocation = MultiLocation::new( - 1, - X2( - Parachain(parachains::kusama::karura::ID), - general_key(parachains::kusama::karura::AUSD_KEY), - ), - ); - - Altair::execute_with(|| { - assert_eq!( - >::convert(ausd_location.clone()), - Ok(CurrencyId::AUSD), - ); - - assert_eq!( - >::convert(CurrencyId::AUSD), - Some(ausd_location) - ) - }); + // The way Ztg is represented relative within the Zeitgeist runtime + let ztg_location_inner: MultiLocation = MultiLocation::new(0, X1(general_key(zeitgeist::KEY))); + + assert_eq!(>::convert(ztg_location_inner), Ok(CurrencyId::Ztg),); + + // The canonical way Ztg is represented out in the wild + let air_location_canonical: MultiLocation = + MultiLocation::new(1, X2(Parachain(zeitgeist::ID), general_key(zeitgeist::KEY))); + + Zeitgeist::execute_with(|| { + assert_eq!( + >::convert(CurrencyId::Ztg), + Some(air_location_canonical) + ) + }); } #[test] -fn convert_parent() { - let ksm_location: MultiLocation = MultiLocation::parent().into(); - - Altair::execute_with(|| { - assert_eq!( - >::convert(ksm_location.clone()), - Ok(CurrencyId::KSM), - ); - - assert_eq!( - >::convert(CurrencyId::KSM), - Some(ksm_location) - ) - }); +fn convert_any_registered_multilocation() { + let ksm_location: MultiLocation = MultiLocation::parent().into(); + + Zeitgeist::execute_with(|| { + // Register KSM as foreign asset in the sibling parachain + let meta: AssetMetadata = AssetMetadata { + decimals: 12, + name: "Kusama".into(), + symbol: "KSM".into(), + existential_deposit: 10_000_000_000, + location: Some(VersionedMultiLocation::V1(ksm_location.clone())), + additional: CustomMetadata::default(), + }; + + assert_ok!(AssetRegistry::register_asset( + Origin::root(), + meta, + Some(FOREIGN_KSM_ID) + )); + + assert_eq!( + >::convert(ksm_location.clone()), + Ok(FOREIGN_KSM_ID), + ); + + assert_eq!( + >::convert(FOREIGN_KSM_ID), + Some(ksm_location) + ) + }); } -*/ - #[test] fn convert_unkown_multilocation() { - let unknown_location: MultiLocation = MultiLocation::new( - 1, - X2( - Parachain(zeitgeist::ID), - general_key(&[42]), - ), - ); - - Zeitgeist::execute_with(|| { - assert!(>::convert(unknown_location.clone()).is_err()); - }); + let unknown_location: MultiLocation = + MultiLocation::new(1, X2(Parachain(zeitgeist::ID), general_key(&[42]))); + + Zeitgeist::execute_with(|| { + assert!(>::convert(unknown_location.clone()).is_err()); + }); } #[test] fn convert_unsupported_currency() { - Zeitgeist::execute_with(|| { - assert_eq!( - >::convert(CurrencyId::CombinatorialOutcome), - None - ) - }); -} \ No newline at end of file + Zeitgeist::execute_with(|| { + assert_eq!(>::convert(CurrencyId::CombinatorialOutcome), None) + }); +} diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index e69de29bb..d7ae60b92 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -0,0 +1,162 @@ + +// Copyright 2021 Centrifuge Foundation (centrifuge.io). +// Copyright 2022 Forecasting Technologies LTD. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + + +use crate::{ + integration_tests::xcm::{ + setup::{ + foreign, ksm, sibling, sibling_account, zeitgeist_account, ztg, ALICE, BOB, + PARA_ID_SIBLING, FOREIGN_KSM_ID, + }, + test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, + }, + xcm_config::{ + asset_registry::{CustomMetadata, XcmMetadata}, + config::{general_key, zeitgeist, AssetConvert}, + fees::default_per_second, + }, + AssetRegistry, Balance, Balances, CurrencyId, Origin, Tokens, XTokens, ExistentialDeposit +}; + +use frame_support::assert_ok; +use orml_traits::{asset_registry::AssetMetadata, FixedConversionRateProvider, MultiCurrency}; +use parity_scale_codec::Encode; +use sp_runtime::traits::Convert as C2; +use xcm::{ + latest::{Error::BadOrigin, Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, + VersionedMultiLocation, +}; +use xcm_emulator::TestExt; +use xcm_executor::traits::Convert as C1; +use zeitgeist_primitives::constants::BalanceFractionalDecimals; + +/* + +#[test] +fn transfer_ztg_to_sibling() { + TestNet::reset(); + + let alice_initial_balance = ztg(10); + let bob_initial_balance = ztg(10); + let transfer_amount = ztg(1); + let transfer_amount = ztg(5); + let ztg_in_sibling = CurrencyId::ForeignAsset(12); + + Zeitgeist::execute_with(|| { + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); + assert_eq!(Balances::free_balance(&sibling_account()), 0); + }); + + Sibling::execute_with(|| { + assert_eq!( + OrmlTokens::free_balance(ztg_in_sibling.clone(), &BOB.into()), + 0 + ); + + // Register AIR as foreign asset in the sibling parachain + let meta: AssetMetadata = AssetMetadata { + decimals: 10, + name: "Zeitgeist".into(), + symbol: "ZTG".into(), + existential_deposit: ExistentialDeposit::get(), + location: Some(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2( + Parachain(zeitgeist::ID), + general_key(zeitgeist::KEY), + ), + ))), + additional: CustomMetadata::default(), + }; + assert_ok!(OrmlAssetRegistry::register_asset( + Origin::root(), + meta, + Some(ztg_in_sibling.clone()) + )); + }); + + Zeitgeist::execute_with(|| { + assert_ok!(XTokens::transfer( + Origin::signed(ALICE.into()), + CurrencyId::Native, + transfer_amount, + Box::new( + MultiLocation::new( + 1, + X2( + Parachain(PARA_ID_SIBLING), + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into(), + } + ) + ) + .into() + ), + 8_000_000_000_000, + )); + + // Confirm that Alice's balance is initial balance - amount transferred + assert_eq!( + Balances::free_balance(&ALICE.into()), + alice_initial_balance - transfer_amount + ); + + // Verify that the amount transferred is now part of the sibling account here + assert_eq!(Balances::free_balance(&sibling_account()), transfer_amount); + }); + + Sibling::execute_with(|| { + let current_balance = OrmlTokens::free_balance(ztg_in_sibling, &BOB.into()); + + // Verify that BOB now has (amount transferred - fee) + assert_eq!(current_balance, transfer_amount - fee(18)); + + // Sanity check for the actual amount BOB ends up with + assert_eq!(current_balance, 4990730400000000000); + }); +} + +*/ + +#[test] +fn test_total_fee() { + assert_eq!(ztg_fee(), 926960000000); + assert_eq!(fee(12), 9269600000); +} + +fn ztg_fee() -> Balance { + fee(BalanceFractionalDecimals::get().into()) +} + +fn fee(decimals: u32) -> Balance { + calc_fee(default_per_second(decimals)) +} + +// The fee associated with transferring KSM tokens +fn ksm_fee() -> Balance { + fee(12) +} + +fn calc_fee(fee_per_second: Balance) -> Balance { + // We divide the fee to align its unit and multiply by 4 as that seems to be the unit of + // time the tests take. + // NOTE: it is possible that in different machines this value may differ. We shall see. + fee_per_second.div_euclid(10_000) * 8 +} diff --git a/runtime/battery-station/src/lib.rs b/runtime/battery-station/src/lib.rs index e296e1a62..4378bee2d 100644 --- a/runtime/battery-station/src/lib.rs +++ b/runtime/battery-station/src/lib.rs @@ -77,13 +77,13 @@ use sp_runtime::{ use nimbus_primitives::{CanAuthor, NimbusId}; use sp_version::RuntimeVersion; -#[cfg(feature = "parachain")] -pub mod parachain_params; -pub mod parameters; #[cfg(feature = "parachain")] #[cfg(test)] pub mod integration_tests; #[cfg(feature = "parachain")] +pub mod parachain_params; +pub mod parameters; +#[cfg(feature = "parachain")] pub mod xcm_config; pub const VERSION: RuntimeVersion = RuntimeVersion { @@ -173,26 +173,24 @@ impl orml_unknown_tokens::Config for Runtime { #[cfg(feature = "parachain")] use xcm_config::config::*; - #[cfg(feature = "parachain")] impl orml_xtokens::Config for Runtime { - type AccountIdToMultiLocation = AccountIdToMultiLocation; - type Balance = Balance; - type BaseXcmWeight = BaseXcmWeight; - type CurrencyId = CurrencyId; - type CurrencyIdConvert = AssetConvert; - type Event = Event; - type LocationInverter = LocationInverter; - type MaxAssetsForTransfer = MaxAssetsForTransfer; - type MinXcmFee = ParachainMinFee; - type MultiLocationsFilter = Everything; - type ReserveProvider = orml_traits::location::AbsoluteReserveProvider; - type SelfLocation = SelfLocation; - type Weigher = FixedWeightBounds; - type XcmExecutor = xcm_executor::XcmExecutor; + type AccountIdToMultiLocation = AccountIdToMultiLocation; + type Balance = Balance; + type BaseXcmWeight = BaseXcmWeight; + type CurrencyId = CurrencyId; + type CurrencyIdConvert = AssetConvert; + type Event = Event; + type LocationInverter = LocationInverter; + type MaxAssetsForTransfer = MaxAssetsForTransfer; + type MinXcmFee = ParachainMinFee; + type MultiLocationsFilter = Everything; + type ReserveProvider = orml_traits::location::AbsoluteReserveProvider; + type SelfLocation = SelfLocation; + type Weigher = FixedWeightBounds; + type XcmExecutor = xcm_executor::XcmExecutor; } - impl_config_traits!(); create_runtime_api!(); create_common_benchmark_logic!(); diff --git a/runtime/battery-station/src/parachain_params.rs b/runtime/battery-station/src/parachain_params.rs index 6c64c81ca..3b823823c 100644 --- a/runtime/battery-station/src/parachain_params.rs +++ b/runtime/battery-station/src/parachain_params.rs @@ -23,13 +23,13 @@ #![cfg(feature = "parachain")] use super::{ - parameters::MAXIMUM_BLOCK_WEIGHT, Origin, ParachainInfo, - xcm_config::config::zeitgeist::{ID as ZTG_PARAID}, + parameters::MAXIMUM_BLOCK_WEIGHT, xcm_config::config::zeitgeist::ID as ZTG_PARAID, Origin, + ParachainInfo, }; use frame_support::{parameter_types, weights::Weight}; use orml_traits::parameter_type_with_key; use sp_runtime::{Perbill, Percent, SaturatedConversion}; -use xcm::latest::{Junction, MultiLocation, NetworkId, prelude::X1}; +use xcm::latest::{prelude::X1, Junction, MultiLocation, NetworkId}; use zeitgeist_primitives::{ constants::{BASE, BLOCKS_PER_MINUTE, MICRO}, types::Balance, @@ -106,7 +106,7 @@ parameter_types! { parameter_type_with_key! { // XCM - pub ParachainMinFee: |_location: MultiLocation| -> Option { - None - }; + pub ParachainMinFee: |_location: MultiLocation| -> Option { + None + }; } diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 7039b525a..76655aeae 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -15,9 +15,7 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use super::{ - fees::{native_per_second, FixedConversionRateProvider}, -}; +use super::fees::{native_per_second, FixedConversionRateProvider}; use crate::{ AccountId, Ancestry, AssetManager, AssetRegistry, Balance, Call, CurrencyId, MaxInstructions, Origin, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, UnitWeightCost, @@ -188,12 +186,9 @@ impl Convert> for AssetConvert { fn convert(id: CurrencyId) -> Option { match id { Asset::Ztg => Some(MultiLocation::new( - 1, - X2( - Junction::Parachain(zeitgeist::ID), - general_key(zeitgeist::KEY), - ), - )), + 1, + X2(Junction::Parachain(zeitgeist::ID), general_key(zeitgeist::KEY)), + )), Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, _ => None, } @@ -211,15 +206,15 @@ impl xcm_executor::traits::Convert for AssetConvert { _ => Err(location), }, MultiLocation { - parents: 1, - interior: X2(Junction::Parachain(para_id), GeneralKey(key)), - } => match para_id { - zeitgeist::ID => match &key[..] { - zeitgeist::KEY => Ok(CurrencyId::Ztg), - _ => Err(location), - }, + parents: 1, + interior: X2(Junction::Parachain(para_id), GeneralKey(key)), + } => match para_id { + zeitgeist::ID => match &key[..] { + zeitgeist::KEY => Ok(CurrencyId::Ztg), + _ => Err(location), + }, _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), - }, + }, _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), } } @@ -244,13 +239,9 @@ impl Convert> for AssetConvert { pub struct AccountIdToMultiLocation; impl Convert for AccountIdToMultiLocation { - fn convert(account: AccountId) -> MultiLocation { - X1(AccountId32 { - network: NetworkId::Any, - id: account.into(), - }) - .into() - } + fn convert(account: AccountId) -> MultiLocation { + X1(AccountId32 { network: NetworkId::Any, id: account.into() }).into() + } } /// No local origins on this chain are allowed to dispatch XCM sends/executions. From 208c862ace2f88d3c61c4ba8318a24ba116b3879 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Wed, 2 Nov 2022 11:52:46 +0200 Subject: [PATCH 20/59] Add helper functions and sibling currency<>location conversion test --- .../src/integration_tests/xcm/setup.rs | 121 +++++++++--- .../src/integration_tests/xcm/test_net.rs | 12 +- .../xcm/tests/currency_id_convert.rs | 79 +++++--- .../integration_tests/xcm/tests/transfers.rs | 187 +++++++++--------- 4 files changed, 244 insertions(+), 155 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs index 280b4c7d6..36431a9b5 100644 --- a/runtime/battery-station/src/integration_tests/xcm/setup.rs +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -17,27 +17,21 @@ // along with Zeitgeist. If not, see . use crate::{ - xcm_config::{asset_registry::CustomMetadata, config::zeitgeist}, - AccountId, Balance, CurrencyId, Origin, Runtime, System, + xcm_config::{ + asset_registry::CustomMetadata, + config::{general_key, zeitgeist}, + }, + AccountId, AssetRegistry, Balance, CurrencyId, Origin, Runtime, System, }; -use frame_support::traits::GenesisBuild; +use frame_support::{assert_ok, traits::GenesisBuild}; use orml_traits::asset_registry::AssetMetadata; +use xcm::{ + latest::{Junction::Parachain, Junctions::X2, MultiLocation}, + VersionedMultiLocation, +}; use zeitgeist_primitives::types::Asset; -/// Accounts -pub const ALICE: [u8; 32] = [4u8; 32]; -pub const BOB: [u8; 32] = [5u8; 32]; - -/// A PARA ID used for a sibling parachain. -/// It must be one that doesn't collide with any other in use. -pub const PARA_ID_SIBLING: u32 = 3000; - -/// IDs that are used to represent tokens from other chains -pub const FOREIGN_ZTG_ID: Asset = CurrencyId::ForeignAsset(0); -pub const FOREIGN_KSM_ID: Asset = CurrencyId::ForeignAsset(1); -pub const FOREIGN_SIBLING_ID: Asset = CurrencyId::ForeignAsset(2); - -pub struct ExtBuilder { +pub(super) struct ExtBuilder { balances: Vec<(AccountId, CurrencyId, Balance)>, parachain_id: u32, } @@ -102,34 +96,113 @@ impl ExtBuilder { } } -pub fn ztg(amount: Balance) -> Balance { +/// Accounts +pub const ALICE: [u8; 32] = [4u8; 32]; +pub const BOB: [u8; 32] = [5u8; 32]; + +/// A PARA ID used for a sibling parachain. +/// It must be one that doesn't collide with any other in use. +pub const PARA_ID_SIBLING: u32 = 3000; + +/// IDs that are used to represent tokens from other chains +pub const FOREIGN_ZTG_ID: Asset = CurrencyId::ForeignAsset(0); +pub const FOREIGN_PARENT_ID: Asset = CurrencyId::ForeignAsset(1); +pub const FOREIGN_SIBLING_ID: Asset = CurrencyId::ForeignAsset(2); + +// Multilocations that are used to represent tokens from other chains +#[inline] +pub(super) fn foreign_ztg_multilocation() -> MultiLocation { + MultiLocation::new(1, X2(Parachain(zeitgeist::ID), general_key(zeitgeist::KEY))) +} + +#[inline] +pub(super) fn foreign_sibling_multilocation() -> MultiLocation { + MultiLocation::new(1, X2(Parachain(PARA_ID_SIBLING), general_key(zeitgeist::KEY))) +} + +#[inline] +pub(super) fn foreign_parent_multilocation() -> MultiLocation { + MultiLocation::parent() +} + +pub(super) fn register_foreign_ztg(additional_meta: Option) { + // Register ZTG as foreign asset. + let meta: AssetMetadata = AssetMetadata { + decimals: 10, + name: "Zeitgeist".into(), + symbol: "ZTG".into(), + existential_deposit: 500_000_000, // 0.05 + location: Some(VersionedMultiLocation::V1(foreign_ztg_multilocation())), + additional: additional_meta.unwrap_or_default(), + }; + + assert_ok!(AssetRegistry::register_asset(Origin::root(), meta, Some(FOREIGN_ZTG_ID))); +} + +pub(super) fn register_foreign_sibling(additional_meta: Option) { + // Register native Sibling token as foreign asset. + let meta: AssetMetadata = AssetMetadata { + decimals: 10, + name: "Sibling".into(), + symbol: "SBL".into(), + existential_deposit: 500_000_000, // 0.05 + location: Some(VersionedMultiLocation::V1(foreign_sibling_multilocation())), + additional: additional_meta.unwrap_or_default(), + }; + + assert_ok!(AssetRegistry::register_asset(Origin::root(), meta, Some(FOREIGN_SIBLING_ID))); +} + +pub(super) fn register_foreign_parent(additional_meta: Option) { + // Register KSM as foreign asset in the sibling parachain + let meta: AssetMetadata = AssetMetadata { + decimals: 12, + name: "Kusama".into(), + symbol: "KSM".into(), + existential_deposit: 10_000_000_000, // 0.01 + location: Some(VersionedMultiLocation::V1(foreign_parent_multilocation())), + additional: additional_meta.unwrap_or_default(), + }; + + assert_ok!(AssetRegistry::register_asset(Origin::root(), meta, Some(FOREIGN_PARENT_ID))); +} + +#[inline] +pub(super) fn ztg(amount: Balance) -> Balance { amount * dollar(10) } -pub fn sibling(amount: Balance) -> Balance { +#[inline] +pub(super) fn sibling(amount: Balance) -> Balance { foreign(amount, 10) } -pub fn ksm(amount: Balance) -> Balance { +#[inline] +pub(super) fn ksm(amount: Balance) -> Balance { foreign(amount, 12) } -pub fn foreign(amount: Balance, decimals: u32) -> Balance { +#[inline] +pub(super) fn foreign(amount: Balance, decimals: u32) -> Balance { amount * dollar(decimals) } -pub fn dollar(decimals: u32) -> Balance { +#[inline] +pub(super) fn dollar(decimals: u32) -> Balance { 10u128.saturating_pow(decimals.into()) } -pub fn sibling_account() -> AccountId { +#[inline] +pub(super) fn sibling_account() -> AccountId { parachain_account(PARA_ID_SIBLING.into()) } -pub fn zeitgeist_account() -> AccountId { +#[inline] +pub(super) fn zeitgeist_account() -> AccountId { parachain_account(zeitgeist::ID) } +#[inline] fn parachain_account(id: u32) -> AccountId { use sp_runtime::traits::AccountIdConversion; diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index 2100f8ec1..28893e81a 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -28,7 +28,7 @@ use polkadot_runtime_parachains::configuration::HostConfiguration; use sp_runtime::traits::AccountIdConversion; use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; -use super::setup::{ksm, sibling, ztg, ExtBuilder, ALICE, BOB, FOREIGN_KSM_ID, PARA_ID_SIBLING}; +use super::setup::{ksm, sibling, ztg, ExtBuilder, ALICE, BOB, FOREIGN_PARENT_ID, PARA_ID_SIBLING}; decl_test_relay_chain! { pub struct KusamaNet { @@ -73,7 +73,7 @@ decl_test_network! { } } -pub fn relay_ext() -> sp_io::TestExternalities { +pub(super) fn relay_ext() -> sp_io::TestExternalities { use kusama_runtime::{Runtime, System}; let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); @@ -105,15 +105,13 @@ pub fn relay_ext() -> sp_io::TestExternalities { ext } -pub fn para_ext( - parachain_id: u32, -) -> sp_io::TestExternalities { +pub(super) fn para_ext(parachain_id: u32) -> sp_io::TestExternalities { ExtBuilder::default() .balances(vec![ (AccountId::from(ALICE), CurrencyId::Ztg, ztg(10)), (AccountId::from(BOB), CurrencyId::Ztg, ztg(10)), - (AccountId::from(ALICE), FOREIGN_KSM_ID, ksm(10)), - (ZeitgeistTreasuryAccount::get(), FOREIGN_KSM_ID, ksm(1)), + (AccountId::from(ALICE), FOREIGN_PARENT_ID, ksm(10)), + (ZeitgeistTreasuryAccount::get(), FOREIGN_PARENT_ID, ksm(1)), ]) .parachain_id(parachain_id) .build() diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs index 74835a7cc..14c16ec12 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -19,8 +19,10 @@ use crate::{ integration_tests::xcm::{ setup::{ - foreign, ksm, sibling, sibling_account, zeitgeist_account, ztg, ALICE, BOB, - PARA_ID_SIBLING, FOREIGN_KSM_ID, + foreign, foreign_parent_multilocation, foreign_sibling_multilocation, ksm, + register_foreign_parent, register_foreign_sibling, sibling, sibling_account, + zeitgeist_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_SIBLING_ID, + PARA_ID_SIBLING, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, @@ -32,18 +34,17 @@ use crate::{ AssetRegistry, Balance, Balances, CurrencyId, Origin, Tokens, XTokens, }; -use frame_support::assert_ok; +use frame_support::{assert_err, assert_ok}; use orml_traits::{asset_registry::AssetMetadata, FixedConversionRateProvider, MultiCurrency}; use parity_scale_codec::Encode; use sp_runtime::traits::Convert as C2; use xcm::{ - latest::{Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, - VersionedMultiLocation, + latest::{Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, + VersionedMultiLocation, }; use xcm_emulator::TestExt; use xcm_executor::traits::Convert as C1; - #[test] fn convert_native() { assert_eq!(zeitgeist::KEY.to_vec(), vec![0, 1]); @@ -54,47 +55,65 @@ fn convert_native() { assert_eq!(>::convert(ztg_location_inner), Ok(CurrencyId::Ztg),); // The canonical way Ztg is represented out in the wild - let air_location_canonical: MultiLocation = + let ztg_location_canonical: MultiLocation = MultiLocation::new(1, X2(Parachain(zeitgeist::ID), general_key(zeitgeist::KEY))); + // TODO USE variable Zeitgeist::execute_with(|| { assert_eq!( >::convert(CurrencyId::Ztg), - Some(air_location_canonical) + Some(ztg_location_canonical) ) }); } #[test] -fn convert_any_registered_multilocation() { - let ksm_location: MultiLocation = MultiLocation::parent().into(); +fn convert_any_registered_parent_multilocation() { + Zeitgeist::execute_with(|| { + assert_err!( + >::convert(foreign_parent_multilocation()), + foreign_parent_multilocation() + ); + + assert_eq!(>::convert(FOREIGN_PARENT_ID), None,); + + // Register parent as foreign asset in the Zeitgeist parachain + register_foreign_parent(None); + assert_eq!( + >::convert(foreign_parent_multilocation()), + Ok(FOREIGN_PARENT_ID), + ); + + assert_eq!( + >::convert(FOREIGN_PARENT_ID), + Some(foreign_parent_multilocation()) + ); + }); +} + +#[test] +fn convert_any_registered_sibling_multilocation() { Zeitgeist::execute_with(|| { - // Register KSM as foreign asset in the sibling parachain - let meta: AssetMetadata = AssetMetadata { - decimals: 12, - name: "Kusama".into(), - symbol: "KSM".into(), - existential_deposit: 10_000_000_000, - location: Some(VersionedMultiLocation::V1(ksm_location.clone())), - additional: CustomMetadata::default(), - }; - - assert_ok!(AssetRegistry::register_asset( - Origin::root(), - meta, - Some(FOREIGN_KSM_ID) - )); + assert_err!( + >::convert(foreign_sibling_multilocation()), + foreign_sibling_multilocation() + ); + + assert_eq!(>::convert(FOREIGN_SIBLING_ID), None,); + + // Register parent as foreign asset in the Zeitgeist parachain + register_foreign_sibling(None); assert_eq!( - >::convert(ksm_location.clone()), - Ok(FOREIGN_KSM_ID), + >::convert(foreign_sibling_multilocation()), + Ok(FOREIGN_SIBLING_ID), ); assert_eq!( - >::convert(FOREIGN_KSM_ID), - Some(ksm_location) - ) + >::convert(FOREIGN_SIBLING_ID), + Some(foreign_sibling_multilocation()) + ); }); } diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index d7ae60b92..fa0251f79 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -1,4 +1,3 @@ - // Copyright 2021 Centrifuge Foundation (centrifuge.io). // Copyright 2022 Forecasting Technologies LTD. // @@ -17,12 +16,11 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . - use crate::{ integration_tests::xcm::{ setup::{ foreign, ksm, sibling, sibling_account, zeitgeist_account, ztg, ALICE, BOB, - PARA_ID_SIBLING, FOREIGN_KSM_ID, + FOREIGN_PARENT_ID, FOREIGN_SIBLING_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, @@ -31,7 +29,7 @@ use crate::{ config::{general_key, zeitgeist, AssetConvert}, fees::default_per_second, }, - AssetRegistry, Balance, Balances, CurrencyId, Origin, Tokens, XTokens, ExistentialDeposit + AssetRegistry, Balance, Balances, CurrencyId, ExistentialDeposit, Origin, Tokens, XTokens, }; use frame_support::assert_ok; @@ -50,113 +48,114 @@ use zeitgeist_primitives::constants::BalanceFractionalDecimals; #[test] fn transfer_ztg_to_sibling() { - TestNet::reset(); - - let alice_initial_balance = ztg(10); - let bob_initial_balance = ztg(10); - let transfer_amount = ztg(1); - let transfer_amount = ztg(5); - let ztg_in_sibling = CurrencyId::ForeignAsset(12); - - Zeitgeist::execute_with(|| { - assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); - assert_eq!(Balances::free_balance(&sibling_account()), 0); - }); - - Sibling::execute_with(|| { - assert_eq!( - OrmlTokens::free_balance(ztg_in_sibling.clone(), &BOB.into()), - 0 - ); - - // Register AIR as foreign asset in the sibling parachain - let meta: AssetMetadata = AssetMetadata { - decimals: 10, - name: "Zeitgeist".into(), - symbol: "ZTG".into(), - existential_deposit: ExistentialDeposit::get(), - location: Some(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2( - Parachain(zeitgeist::ID), - general_key(zeitgeist::KEY), - ), - ))), - additional: CustomMetadata::default(), - }; - assert_ok!(OrmlAssetRegistry::register_asset( - Origin::root(), - meta, - Some(ztg_in_sibling.clone()) - )); - }); - - Zeitgeist::execute_with(|| { - assert_ok!(XTokens::transfer( - Origin::signed(ALICE.into()), - CurrencyId::Native, - transfer_amount, - Box::new( - MultiLocation::new( - 1, - X2( - Parachain(PARA_ID_SIBLING), - Junction::AccountId32 { - network: NetworkId::Any, - id: BOB.into(), - } - ) - ) - .into() - ), - 8_000_000_000_000, - )); - - // Confirm that Alice's balance is initial balance - amount transferred - assert_eq!( - Balances::free_balance(&ALICE.into()), - alice_initial_balance - transfer_amount - ); - - // Verify that the amount transferred is now part of the sibling account here - assert_eq!(Balances::free_balance(&sibling_account()), transfer_amount); - }); - - Sibling::execute_with(|| { - let current_balance = OrmlTokens::free_balance(ztg_in_sibling, &BOB.into()); - - // Verify that BOB now has (amount transferred - fee) - assert_eq!(current_balance, transfer_amount - fee(18)); - - // Sanity check for the actual amount BOB ends up with - assert_eq!(current_balance, 4990730400000000000); - }); + TestNet::reset(); + + let alice_initial_balance = ztg(10); + let bob_initial_balance = ztg(10); + let transfer_amount = ztg(5); + let ztg_in_sibling = FOREIGN_ZTG_ID; + + Zeitgeist::execute_with(|| { + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); + assert_eq!(Balances::free_balance(&sibling_account()), 0); + }); + + Sibling::execute_with(|| { + assert_eq!( + Tokens::free_balance(ztg_in_sibling.clone(), &BOB.into()), + 0 + ); + + // Register ZTG as foreign asset in the sibling parachain + let meta: AssetMetadata = AssetMetadata { + decimals: 10, + name: "Zeitgeist".into(), + symbol: "ZTG".into(), + existential_deposit: ExistentialDeposit::get(), + location: Some(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2( + Parachain(zeitgeist::ID), + general_key(zeitgeist::KEY), + ), + ))), + additional: CustomMetadata::default(), + }; + assert_ok!(OrmlAssetRegistry::register_asset( + Origin::root(), + meta, + Some(ztg_in_sibling.clone()) + )); + }); + + Zeitgeist::execute_with(|| { + assert_ok!(XTokens::transfer( + Origin::signed(ALICE.into()), + CurrencyId::Native, + transfer_amount, + Box::new( + MultiLocation::new( + 1, + X2( + Parachain(PARA_ID_SIBLING), + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB.into(), + } + ) + ) + .into() + ), + 8_000_000_000_000, + )); + + // Confirm that Alice's balance is initial balance - amount transferred + assert_eq!( + Balances::free_balance(&ALICE.into()), + alice_initial_balance - transfer_amount + ); + + // Verify that the amount transferred is now part of the sibling account here + assert_eq!(Balances::free_balance(&sibling_account()), transfer_amount); + }); + + Sibling::execute_with(|| { + let current_balance = OrmlTokens::free_balance(ztg_in_sibling, &BOB.into()); + + // Verify that BOB now has (amount transferred - fee) + assert_eq!(current_balance, transfer_amount - fee(18)); + + // Sanity check for the actual amount BOB ends up with + assert_eq!(current_balance, 4990730400000000000); + }); } */ +/* #[test] fn test_total_fee() { - assert_eq!(ztg_fee(), 926960000000); - assert_eq!(fee(12), 9269600000); + assert_eq!(ztg_fee(), 926960000000); + assert_eq!(fee(12), 9269600000); } fn ztg_fee() -> Balance { - fee(BalanceFractionalDecimals::get().into()) + fee(BalanceFractionalDecimals::get().into()) } fn fee(decimals: u32) -> Balance { - calc_fee(default_per_second(decimals)) + calc_fee(default_per_second(decimals)) } // The fee associated with transferring KSM tokens fn ksm_fee() -> Balance { - fee(12) + fee(12) } fn calc_fee(fee_per_second: Balance) -> Balance { - // We divide the fee to align its unit and multiply by 4 as that seems to be the unit of - // time the tests take. - // NOTE: it is possible that in different machines this value may differ. We shall see. - fee_per_second.div_euclid(10_000) * 8 + // We divide the fee to align its unit and multiply by 4 as that seems to be the unit of + // time the tests take. + // NOTE: it is possible that in different machines this value may differ. We shall see. + fee_per_second //.div_euclid(10_000) * 8 } +*/ From 78b10185be5813cbc0eee989c39d6d89236881dc Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Wed, 2 Nov 2022 15:50:38 +0200 Subject: [PATCH 21/59] Add relative view trader for ZTG --- runtime/battery-station/src/xcm_config/config.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 76655aeae..6327507b2 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -112,6 +112,7 @@ pub type Trader = ( // In case the asset in question is the native currency, it will charge // the default base fee per second and deposits them into treasury FixedRateOfFungible, + FixedRateOfFungible, // For all other assets the base fee per second will tried to be derived // through the `fee_factor` entry in the asset registry. If the asset is // not present in the asset registry, the default base fee per second is used. @@ -128,12 +129,12 @@ impl TakeRevenue for ToTreasury { use xcm_executor::traits::Convert; if let MultiAsset { id: Concrete(location), fun: Fungible(amount) } = revenue.clone() { + if let Ok(asset_id) = >::convert(location.clone()) { let _ = AssetManager::deposit(asset_id, &ZeitgeistTreasuryAccount::get(), amount); } else { - // TODO this is wrong, use target as second parameter let _ = UnknownTokens::deposit(&revenue, &location); } } @@ -142,14 +143,22 @@ impl TakeRevenue for ToTreasury { parameter_types! { pub CheckAccount: AccountId = PolkadotXcm::check_account(); - /// The amount of ZTG charged per second of execution. - pub ZtgPerSecond: (AssetId, u128) = ( + /// The amount of ZTG charged per second of execution (canonical multilocation). + pub ZtgPerSecondCanonical: (AssetId, u128) = ( MultiLocation::new( 0, X1(general_key(zeitgeist::KEY)), ).into(), native_per_second(), ); + /// The amount of canonical ZTG charged per second of execution. + pub ZtgPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X2(Junction::Parachain(zeitgeist::ID), general_key(zeitgeist::KEY)), + ).into(), + native_per_second(), + ); } /// Means for transacting assets on this chain. From bb30dfa0f0df4bc3f801bff4f346785419fce399 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Fri, 4 Nov 2022 09:42:47 +0200 Subject: [PATCH 22/59] Extend XCM transfer tests --- .../src/integration_tests/xcm/test_net.rs | 1 - .../xcm/tests/currency_id_convert.rs | 10 +- .../integration_tests/xcm/tests/transfers.rs | 135 ++++++++++++------ .../battery-station/src/xcm_config/config.rs | 1 - 4 files changed, 95 insertions(+), 52 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index 28893e81a..7185aee5a 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -109,7 +109,6 @@ pub(super) fn para_ext(parachain_id: u32) -> sp_io::TestExternalities { ExtBuilder::default() .balances(vec![ (AccountId::from(ALICE), CurrencyId::Ztg, ztg(10)), - (AccountId::from(BOB), CurrencyId::Ztg, ztg(10)), (AccountId::from(ALICE), FOREIGN_PARENT_ID, ksm(10)), (ZeitgeistTreasuryAccount::get(), FOREIGN_PARENT_ID, ksm(1)), ]) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs index 14c16ec12..e171b362f 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -22,7 +22,7 @@ use crate::{ foreign, foreign_parent_multilocation, foreign_sibling_multilocation, ksm, register_foreign_parent, register_foreign_sibling, sibling, sibling_account, zeitgeist_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_SIBLING_ID, - PARA_ID_SIBLING, + PARA_ID_SIBLING, foreign_ztg_multilocation, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, @@ -52,17 +52,13 @@ fn convert_native() { // The way Ztg is represented relative within the Zeitgeist runtime let ztg_location_inner: MultiLocation = MultiLocation::new(0, X1(general_key(zeitgeist::KEY))); - assert_eq!(>::convert(ztg_location_inner), Ok(CurrencyId::Ztg),); + assert_eq!(>::convert(ztg_location_inner), Ok(CurrencyId::Ztg)); // The canonical way Ztg is represented out in the wild - let ztg_location_canonical: MultiLocation = - MultiLocation::new(1, X2(Parachain(zeitgeist::ID), general_key(zeitgeist::KEY))); - - // TODO USE variable Zeitgeist::execute_with(|| { assert_eq!( >::convert(CurrencyId::Ztg), - Some(ztg_location_canonical) + Some(foreign_ztg_multilocation()) ) }); } diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index fa0251f79..add735aeb 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -20,7 +20,7 @@ use crate::{ integration_tests::xcm::{ setup::{ foreign, ksm, sibling, sibling_account, zeitgeist_account, ztg, ALICE, BOB, - FOREIGN_PARENT_ID, FOREIGN_SIBLING_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, + FOREIGN_PARENT_ID, FOREIGN_SIBLING_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, register_foreign_ztg }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, @@ -32,7 +32,7 @@ use crate::{ AssetRegistry, Balance, Balances, CurrencyId, ExistentialDeposit, Origin, Tokens, XTokens, }; -use frame_support::assert_ok; +use frame_support::{assert_ok, traits::tokens::fungible::Mutate}; use orml_traits::{asset_registry::AssetMetadata, FixedConversionRateProvider, MultiCurrency}; use parity_scale_codec::Encode; use sp_runtime::traits::Convert as C2; @@ -44,54 +44,32 @@ use xcm_emulator::TestExt; use xcm_executor::traits::Convert as C1; use zeitgeist_primitives::constants::BalanceFractionalDecimals; -/* #[test] fn transfer_ztg_to_sibling() { TestNet::reset(); let alice_initial_balance = ztg(10); - let bob_initial_balance = ztg(10); let transfer_amount = ztg(5); let ztg_in_sibling = FOREIGN_ZTG_ID; - Zeitgeist::execute_with(|| { - assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); - assert_eq!(Balances::free_balance(&sibling_account()), 0); - }); - Sibling::execute_with(|| { assert_eq!( - Tokens::free_balance(ztg_in_sibling.clone(), &BOB.into()), + Balances::free_balance(&BOB.into()), 0 ); - // Register ZTG as foreign asset in the sibling parachain - let meta: AssetMetadata = AssetMetadata { - decimals: 10, - name: "Zeitgeist".into(), - symbol: "ZTG".into(), - existential_deposit: ExistentialDeposit::get(), - location: Some(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2( - Parachain(zeitgeist::ID), - general_key(zeitgeist::KEY), - ), - ))), - additional: CustomMetadata::default(), - }; - assert_ok!(OrmlAssetRegistry::register_asset( - Origin::root(), - meta, - Some(ztg_in_sibling.clone()) - )); + // We don't have to register ZTG because ZTG is the native currency + // of the sibling chain (it is a Zeitgeist clone). }); Zeitgeist::execute_with(|| { + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); + assert_eq!(Balances::free_balance(&sibling_account()), 0); + assert_ok!(XTokens::transfer( Origin::signed(ALICE.into()), - CurrencyId::Native, + CurrencyId::Ztg, transfer_amount, Box::new( MultiLocation::new( @@ -106,10 +84,10 @@ fn transfer_ztg_to_sibling() { ) .into() ), - 8_000_000_000_000, + 80_000_000, )); - // Confirm that Alice's balance is initial balance - amount transferred + // Confirm that Alice's balance is initial_balance - amount_transferred assert_eq!( Balances::free_balance(&ALICE.into()), alice_initial_balance - transfer_amount @@ -120,42 +98,113 @@ fn transfer_ztg_to_sibling() { }); Sibling::execute_with(|| { - let current_balance = OrmlTokens::free_balance(ztg_in_sibling, &BOB.into()); + let current_balance = Balances::free_balance(&BOB.into()); // Verify that BOB now has (amount transferred - fee) - assert_eq!(current_balance, transfer_amount - fee(18)); + assert_eq!(current_balance, transfer_amount - ztg_fee()); // Sanity check for the actual amount BOB ends up with - assert_eq!(current_balance, 4990730400000000000); + //assert_eq!(current_balance, 4990730400000000000); }); } -*/ -/* +#[test] +fn transfer_ztg_sibling_to_zeitgeist() { + TestNet::reset(); + + // In order to be able to transfer ZTG from Sibling to Zeitgeist, we need to first send + // ZTG from Zeitgeist to Sibling, or else it fails since it'd be like Sibling had minted + // ZTG on their side. + transfer_ztg_to_sibling(); + + let alice_initial_balance = ztg(5); + let bob_initial_balance = ztg(5) - ztg_fee(); + let transfer_amount = ztg(1); + // Note: This asset was registered in `transfer_ztg_to_sibling` + + Zeitgeist::execute_with(|| { + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); + }); + + Sibling::execute_with(|| { + assert_eq!(Balances::free_balance(&zeitgeist_account()), 0); + assert_eq!( + Balances::free_balance(&BOB.into()), + bob_initial_balance + ); + }); + + Sibling::execute_with(|| { + assert_ok!(XTokens::transfer( + Origin::signed(BOB.into()), + CurrencyId::Ztg, + transfer_amount, + Box::new( + MultiLocation::new( + 1, + X2( + Parachain(zeitgeist::ID), + Junction::AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + } + ) + ) + .into() + ), + 80_000_000, + )); + + // Confirm that Bobs's balance is initial balance - amount transferred + assert_eq!( + Balances::free_balance(&BOB.into()), + bob_initial_balance - transfer_amount + ); + }); + + Zeitgeist::execute_with(|| { + // Verify that ALICE now has initial balance + amount transferred - fee + assert_eq!( + Balances::free_balance(&ALICE.into()), + alice_initial_balance + transfer_amount - ztg_fee(), + ); + }); +} + +// Test correct fees +// Test handling of unknown tokens +// Test treasury assignments +/* #[test] fn test_total_fee() { assert_eq!(ztg_fee(), 926960000000); - assert_eq!(fee(12), 9269600000); + assert_eq!(ksm_fee(), 9269600000); } +*/ +#[inline] fn ztg_fee() -> Balance { - fee(BalanceFractionalDecimals::get().into()) + // fee(BalanceFractionalDecimals::get().into()) + 3200 } +#[inline] fn fee(decimals: u32) -> Balance { calc_fee(default_per_second(decimals)) } // The fee associated with transferring KSM tokens +#[inline] fn ksm_fee() -> Balance { fee(12) } +#[inline] fn calc_fee(fee_per_second: Balance) -> Balance { - // We divide the fee to align its unit and multiply by 4 as that seems to be the unit of + // We divide the fee to align its unit and multiply by 8 as that seems to be the unit of // time the tests take. // NOTE: it is possible that in different machines this value may differ. We shall see. - fee_per_second //.div_euclid(10_000) * 8 + (fee_per_second * 8).div_euclid(100_000_000) } -*/ + diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 6327507b2..30e6efdb2 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -129,7 +129,6 @@ impl TakeRevenue for ToTreasury { use xcm_executor::traits::Convert; if let MultiAsset { id: Concrete(location), fun: Fungible(amount) } = revenue.clone() { - if let Ok(asset_id) = >::convert(location.clone()) { From b28542b9ca79cece2ea4c4a9e2ea1dbce2384aa4 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Fri, 4 Nov 2022 12:57:05 +0200 Subject: [PATCH 23/59] Add ZTG -> Sibling -> ZTG test --- .../src/integration_tests/xcm/tests/transfers.rs | 6 +++++- runtime/battery-station/src/parachain_params.rs | 10 +++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index add735aeb..65c1a1e14 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -51,7 +51,6 @@ fn transfer_ztg_to_sibling() { let alice_initial_balance = ztg(10); let transfer_amount = ztg(5); - let ztg_in_sibling = FOREIGN_ZTG_ID; Sibling::execute_with(|| { assert_eq!( @@ -119,11 +118,13 @@ fn transfer_ztg_sibling_to_zeitgeist() { let alice_initial_balance = ztg(5); let bob_initial_balance = ztg(5) - ztg_fee(); + let sibling_sovereign_initial_balance = ztg(5); let transfer_amount = ztg(1); // Note: This asset was registered in `transfer_ztg_to_sibling` Zeitgeist::execute_with(|| { assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); + assert_eq!(Balances::free_balance(&sibling_account()), sibling_sovereign_initial_balance); }); Sibling::execute_with(|| { @@ -168,6 +169,9 @@ fn transfer_ztg_sibling_to_zeitgeist() { Balances::free_balance(&ALICE.into()), alice_initial_balance + transfer_amount - ztg_fee(), ); + + // Verify that the reserve has been adjusted properly + assert_eq!(Balances::free_balance(&sibling_account()), sibling_sovereign_initial_balance - transfer_amount); }); } diff --git a/runtime/battery-station/src/parachain_params.rs b/runtime/battery-station/src/parachain_params.rs index 3b823823c..dde480052 100644 --- a/runtime/battery-station/src/parachain_params.rs +++ b/runtime/battery-station/src/parachain_params.rs @@ -23,13 +23,13 @@ #![cfg(feature = "parachain")] use super::{ - parameters::MAXIMUM_BLOCK_WEIGHT, xcm_config::config::zeitgeist::ID as ZTG_PARAID, Origin, + parameters::MAXIMUM_BLOCK_WEIGHT, Origin, ParachainInfo, }; -use frame_support::{parameter_types, weights::Weight}; +use frame_support::{parameter_types, traits::Get, weights::Weight}; use orml_traits::parameter_type_with_key; use sp_runtime::{Perbill, Percent, SaturatedConversion}; -use xcm::latest::{prelude::X1, Junction, MultiLocation, NetworkId}; +use xcm::latest::{prelude::X1, Junction::Parachain, MultiLocation, NetworkId}; use zeitgeist_primitives::{ constants::{BASE, BLOCKS_PER_MINUTE, MICRO}, types::Balance, @@ -49,7 +49,7 @@ parameter_types! { pub const SignatureNetworkIdentifier: &'static [u8] = b"zeitgeist-"; // Cumulus and Polkadot - pub Ancestry: MultiLocation = Junction::Parachain(ParachainInfo::parachain_id().into()).into(); + pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); pub const RelayLocation: MultiLocation = MultiLocation::parent(); // Have to change "Any" to "Kusama" for mainnet once we have separate runtimes pub const RelayNetwork: NetworkId = NetworkId::Any; @@ -101,7 +101,7 @@ parameter_types! { /// Max instructions per XCM pub const MaxInstructions: u32 = 100; // Relative self location - pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Junction::Parachain(ZTG_PARAID))); + pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into()))); } parameter_type_with_key! { From b6a7d92728cebd583e999e4acea0e29fa80a61a6 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sat, 5 Nov 2022 10:52:21 +0200 Subject: [PATCH 24/59] Read ParaId from ParachainInfo + fix tests This change makes the XCM implementation more generic. Since any asset is registered via AssetRegistry and no asset is pre-registered, the XCM implementation can be used in any Zeitgeist runtime --- .../xcm/tests/currency_id_convert.rs | 8 +- .../integration_tests/xcm/tests/transfers.rs | 175 ++++++++++++------ .../battery-station/src/parachain_params.rs | 5 +- .../battery-station/src/xcm_config/config.rs | 8 +- 4 files changed, 128 insertions(+), 68 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs index e171b362f..f297ac29d 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -19,10 +19,10 @@ use crate::{ integration_tests::xcm::{ setup::{ - foreign, foreign_parent_multilocation, foreign_sibling_multilocation, ksm, - register_foreign_parent, register_foreign_sibling, sibling, sibling_account, - zeitgeist_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_SIBLING_ID, - PARA_ID_SIBLING, foreign_ztg_multilocation, + foreign, foreign_parent_multilocation, foreign_sibling_multilocation, + foreign_ztg_multilocation, ksm, register_foreign_parent, register_foreign_sibling, + sibling, sibling_account, zeitgeist_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, + FOREIGN_SIBLING_ID, PARA_ID_SIBLING, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index 65c1a1e14..ac6fc6c7a 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -19,8 +19,9 @@ use crate::{ integration_tests::xcm::{ setup::{ - foreign, ksm, sibling, sibling_account, zeitgeist_account, ztg, ALICE, BOB, - FOREIGN_PARENT_ID, FOREIGN_SIBLING_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, register_foreign_ztg + foreign, ksm, register_foreign_ztg, sibling, sibling_account, zeitgeist_account, ztg, + ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_SIBLING_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, register_foreign_parent, foreign_ztg_multilocation, + foreign_parent_multilocation, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, @@ -44,7 +45,6 @@ use xcm_emulator::TestExt; use xcm_executor::traits::Convert as C1; use zeitgeist_primitives::constants::BalanceFractionalDecimals; - #[test] fn transfer_ztg_to_sibling() { TestNet::reset(); @@ -53,13 +53,11 @@ fn transfer_ztg_to_sibling() { let transfer_amount = ztg(5); Sibling::execute_with(|| { - assert_eq!( - Balances::free_balance(&BOB.into()), - 0 - ); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), 0); // We don't have to register ZTG because ZTG is the native currency // of the sibling chain (it is a Zeitgeist clone). + register_foreign_ztg(None); }); Zeitgeist::execute_with(|| { @@ -75,10 +73,7 @@ fn transfer_ztg_to_sibling() { 1, X2( Parachain(PARA_ID_SIBLING), - Junction::AccountId32 { - network: NetworkId::Any, - id: BOB.into(), - } + Junction::AccountId32 { network: NetworkId::Any, id: BOB.into() } ) ) .into() @@ -87,17 +82,14 @@ fn transfer_ztg_to_sibling() { )); // Confirm that Alice's balance is initial_balance - amount_transferred - assert_eq!( - Balances::free_balance(&ALICE.into()), - alice_initial_balance - transfer_amount - ); + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance - transfer_amount); // Verify that the amount transferred is now part of the sibling account here assert_eq!(Balances::free_balance(&sibling_account()), transfer_amount); }); Sibling::execute_with(|| { - let current_balance = Balances::free_balance(&BOB.into()); + let current_balance = Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()); // Verify that BOB now has (amount transferred - fee) assert_eq!(current_balance, transfer_amount - ztg_fee()); @@ -109,71 +101,142 @@ fn transfer_ztg_to_sibling() { #[test] fn transfer_ztg_sibling_to_zeitgeist() { - TestNet::reset(); + TestNet::reset(); - // In order to be able to transfer ZTG from Sibling to Zeitgeist, we need to first send - // ZTG from Zeitgeist to Sibling, or else it fails since it'd be like Sibling had minted - // ZTG on their side. - transfer_ztg_to_sibling(); + // In order to be able to transfer ZTG from Sibling to Zeitgeist, we need to first send + // ZTG from Zeitgeist to Sibling, or else it fails since it'd be like Sibling had minted + // ZTG on their side. + transfer_ztg_to_sibling(); - let alice_initial_balance = ztg(5); - let bob_initial_balance = ztg(5) - ztg_fee(); + let alice_initial_balance = ztg(5); + let bob_initial_balance = ztg(5) - ztg_fee(); let sibling_sovereign_initial_balance = ztg(5); - let transfer_amount = ztg(1); - // Note: This asset was registered in `transfer_ztg_to_sibling` + let transfer_amount = ztg(1); + // Note: This asset was registered in `transfer_ztg_to_sibling` - Zeitgeist::execute_with(|| { - assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); + Zeitgeist::execute_with(|| { + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); assert_eq!(Balances::free_balance(&sibling_account()), sibling_sovereign_initial_balance); + }); + + Sibling::execute_with(|| { + assert_eq!(Balances::free_balance(&zeitgeist_account()), 0); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), bob_initial_balance); + }); + + Sibling::execute_with(|| { + assert_ok!(XTokens::transfer( + Origin::signed(BOB.into()), + FOREIGN_ZTG_ID, + transfer_amount, + Box::new( + MultiLocation::new( + 1, + X2( + Parachain(zeitgeist::ID), + Junction::AccountId32 { network: NetworkId::Any, id: ALICE.into() } + ) + ) + .into() + ), + 80_000_000, + )); + + // Confirm that Bobs's balance is initial balance - amount transferred + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), bob_initial_balance - transfer_amount); + }); + + Zeitgeist::execute_with(|| { + // Verify that ALICE now has initial balance + amount transferred - fee + assert_eq!( + Balances::free_balance(&ALICE.into()), + alice_initial_balance + transfer_amount - ztg_fee(), + ); + + // Verify that the reserve has been adjusted properly + assert_eq!( + Balances::free_balance(&sibling_account()), + sibling_sovereign_initial_balance - transfer_amount + ); + }); +} + +#[test] +fn transfer_ksm_from_relay_chain() { + let transfer_amount: Balance = ksm(1); + + Zeitgeist::execute_with(|| { + register_foreign_parent(None); + }); + + KusamaNet::execute_with(|| { + assert_ok!(kusama_runtime::XcmPallet::reserve_transfer_assets( + kusama_runtime::Origin::signed(ALICE.into()), + Box::new(Parachain(zeitgeist::ID).into().into()), + Box::new( + Junction::AccountId32 { + network: NetworkId::Any, + id: BOB, + } + .into() + .into() + ), + Box::new((Here, transfer_amount).into()), + 0 + )); }); - Sibling::execute_with(|| { - assert_eq!(Balances::free_balance(&zeitgeist_account()), 0); + Zeitgeist::execute_with(|| { assert_eq!( - Balances::free_balance(&BOB.into()), - bob_initial_balance + Tokens::free_balance(FOREIGN_PARENT_ID, &BOB.into()), + transfer_amount - ksm_fee() ); }); +} + +/* +#[test] +fn transfer_ksm_to_relay_chain() { + let transfer_amount: Balance = ksm(1); + + Zeitgeist::execute_with(|| { + let initial_balance = Tokens::free_balance(FOREIGN_PARENT_ID, &ALICE.into()); + assert!(initial_balance >= transfer_amount); + + register_foreign_parent(None); - Sibling::execute_with(|| { assert_ok!(XTokens::transfer( - Origin::signed(BOB.into()), - CurrencyId::Ztg, + Origin::signed(ALICE.into()), + FOREIGN_PARENT_ID, transfer_amount, Box::new( MultiLocation::new( 1, - X2( - Parachain(zeitgeist::ID), - Junction::AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - } - ) + X1(Junction::AccountId32 { + id: BOB, + network: NetworkId::Any, + }) ) .into() ), - 80_000_000, + 4_000_000_000 )); - // Confirm that Bobs's balance is initial balance - amount transferred - assert_eq!( - Balances::free_balance(&BOB.into()), - bob_initial_balance - transfer_amount - ); + assert_eq!( + Tokens::free_balance(FOREIGN_PARENT_ID, &ALICE.into()), + initial_balance - transfer_amount + ) }); - Zeitgeist::execute_with(|| { - // Verify that ALICE now has initial balance + amount transferred - fee + KusamaNet::execute_with(|| { assert_eq!( - Balances::free_balance(&ALICE.into()), - alice_initial_balance + transfer_amount - ztg_fee(), + kusama_runtime::Balances::free_balance(&BOB.into()), + transfer_amount - ksm_fee() ); - - // Verify that the reserve has been adjusted properly - assert_eq!(Balances::free_balance(&sibling_account()), sibling_sovereign_initial_balance - transfer_amount); }); } +*/ + // Test correct fees // Test handling of unknown tokens @@ -201,7 +264,8 @@ fn fee(decimals: u32) -> Balance { // The fee associated with transferring KSM tokens #[inline] fn ksm_fee() -> Balance { - fee(12) + // fee(12) + 320000 } #[inline] @@ -211,4 +275,3 @@ fn calc_fee(fee_per_second: Balance) -> Balance { // NOTE: it is possible that in different machines this value may differ. We shall see. (fee_per_second * 8).div_euclid(100_000_000) } - diff --git a/runtime/battery-station/src/parachain_params.rs b/runtime/battery-station/src/parachain_params.rs index dde480052..16e4c7bc9 100644 --- a/runtime/battery-station/src/parachain_params.rs +++ b/runtime/battery-station/src/parachain_params.rs @@ -22,10 +22,7 @@ )] #![cfg(feature = "parachain")] -use super::{ - parameters::MAXIMUM_BLOCK_WEIGHT, Origin, - ParachainInfo, -}; +use super::{parameters::MAXIMUM_BLOCK_WEIGHT, Origin, ParachainInfo}; use frame_support::{parameter_types, traits::Get, weights::Weight}; use orml_traits::parameter_type_with_key; use sp_runtime::{Perbill, Percent, SaturatedConversion}; diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 30e6efdb2..b1ef50442 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -18,7 +18,7 @@ use super::fees::{native_per_second, FixedConversionRateProvider}; use crate::{ AccountId, Ancestry, AssetManager, AssetRegistry, Balance, Call, CurrencyId, MaxInstructions, - Origin, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, UnitWeightCost, + Origin, ParachainInfo, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; @@ -154,7 +154,7 @@ parameter_types! { pub ZtgPerSecond: (AssetId, u128) = ( MultiLocation::new( 1, - X2(Junction::Parachain(zeitgeist::ID), general_key(zeitgeist::KEY)), + X2(Junction::Parachain(ParachainInfo::parachain_id().into()), general_key(zeitgeist::KEY)), ).into(), native_per_second(), ); @@ -195,7 +195,7 @@ impl Convert> for AssetConvert { match id { Asset::Ztg => Some(MultiLocation::new( 1, - X2(Junction::Parachain(zeitgeist::ID), general_key(zeitgeist::KEY)), + X2(Junction::Parachain(ParachainInfo::parachain_id().into()), general_key(zeitgeist::KEY)), )), Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, _ => None, @@ -217,7 +217,7 @@ impl xcm_executor::traits::Convert for AssetConvert { parents: 1, interior: X2(Junction::Parachain(para_id), GeneralKey(key)), } => match para_id { - zeitgeist::ID => match &key[..] { + id if id == u32::from(ParachainInfo::parachain_id()) => match &key[..] { zeitgeist::KEY => Ok(CurrencyId::Ztg), _ => Err(location), }, From 5a079b6e0c85c0642e15cedb8f349df6fbe736f8 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sat, 5 Nov 2022 11:20:50 +0200 Subject: [PATCH 25/59] Fix KSM <> ZTG XCM tests --- .../src/integration_tests/xcm/tests/transfers.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index ac6fc6c7a..50a861a5f 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -194,17 +194,17 @@ fn transfer_ksm_from_relay_chain() { }); } -/* +// TODO + #[test] fn transfer_ksm_to_relay_chain() { let transfer_amount: Balance = ksm(1); + transfer_ksm_from_relay_chain(); Zeitgeist::execute_with(|| { let initial_balance = Tokens::free_balance(FOREIGN_PARENT_ID, &ALICE.into()); assert!(initial_balance >= transfer_amount); - register_foreign_parent(None); - assert_ok!(XTokens::transfer( Origin::signed(ALICE.into()), FOREIGN_PARENT_ID, @@ -231,11 +231,10 @@ fn transfer_ksm_to_relay_chain() { KusamaNet::execute_with(|| { assert_eq!( kusama_runtime::Balances::free_balance(&BOB.into()), - transfer_amount - ksm_fee() + 999834059328 ); }); } -*/ // Test correct fees From 4e6754916c87a01ea572811a91abf44d50eeeb4e Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sat, 5 Nov 2022 13:02:36 +0200 Subject: [PATCH 26/59] Fix Fee (off by 2000x) --- .../integration_tests/xcm/tests/transfers.rs | 31 ++++++++----------- .../battery-station/src/parachain_params.rs | 4 +-- 2 files changed, 15 insertions(+), 20 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index 50a861a5f..b7d24cb0d 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -45,6 +45,8 @@ use xcm_emulator::TestExt; use xcm_executor::traits::Convert as C1; use zeitgeist_primitives::constants::BalanceFractionalDecimals; + + #[test] fn transfer_ztg_to_sibling() { TestNet::reset(); @@ -78,7 +80,7 @@ fn transfer_ztg_to_sibling() { ) .into() ), - 80_000_000, + 4_000_000_000, )); // Confirm that Alice's balance is initial_balance - amount_transferred @@ -95,7 +97,7 @@ fn transfer_ztg_to_sibling() { assert_eq!(current_balance, transfer_amount - ztg_fee()); // Sanity check for the actual amount BOB ends up with - //assert_eq!(current_balance, 4990730400000000000); + assert_eq!(current_balance, 49_936_000_000); }); } @@ -122,9 +124,6 @@ fn transfer_ztg_sibling_to_zeitgeist() { Sibling::execute_with(|| { assert_eq!(Balances::free_balance(&zeitgeist_account()), 0); assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), bob_initial_balance); - }); - - Sibling::execute_with(|| { assert_ok!(XTokens::transfer( Origin::signed(BOB.into()), FOREIGN_ZTG_ID, @@ -139,7 +138,7 @@ fn transfer_ztg_sibling_to_zeitgeist() { ) .into() ), - 80_000_000, + 4_000_000_000, )); // Confirm that Bobs's balance is initial balance - amount transferred @@ -194,8 +193,6 @@ fn transfer_ksm_from_relay_chain() { }); } -// TODO - #[test] fn transfer_ksm_to_relay_chain() { let transfer_amount: Balance = ksm(1); @@ -237,22 +234,21 @@ fn transfer_ksm_to_relay_chain() { } -// Test correct fees + // Test handling of unknown tokens // Test treasury assignments -/* + #[test] fn test_total_fee() { - assert_eq!(ztg_fee(), 926960000000); - assert_eq!(ksm_fee(), 9269600000); + assert_eq!(ztg_fee(), 64000000); + assert_eq!(ksm_fee(), 6400000000); } -*/ + #[inline] fn ztg_fee() -> Balance { - // fee(BalanceFractionalDecimals::get().into()) - 3200 + fee(BalanceFractionalDecimals::get().into()) } #[inline] @@ -263,8 +259,7 @@ fn fee(decimals: u32) -> Balance { // The fee associated with transferring KSM tokens #[inline] fn ksm_fee() -> Balance { - // fee(12) - 320000 + fee(12) } #[inline] @@ -272,5 +267,5 @@ fn calc_fee(fee_per_second: Balance) -> Balance { // We divide the fee to align its unit and multiply by 8 as that seems to be the unit of // time the tests take. // NOTE: it is possible that in different machines this value may differ. We shall see. - (fee_per_second * 8).div_euclid(100_000_000) + fee_per_second / 10_000 * 8 } diff --git a/runtime/battery-station/src/parachain_params.rs b/runtime/battery-station/src/parachain_params.rs index 16e4c7bc9..95fedee22 100644 --- a/runtime/battery-station/src/parachain_params.rs +++ b/runtime/battery-station/src/parachain_params.rs @@ -53,7 +53,7 @@ parameter_types! { pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UnitWeightCost: Weight = MICRO.saturated_into(); + pub UnitWeightCost: Weight = 200_000_000; // Staking /// Rounds before the candidate bond increase/decrease can be executed @@ -91,7 +91,7 @@ parameter_types! { // XCM /// Base weight for XCM execution - pub const BaseXcmWeight: Weight = 100_000_000; + pub const BaseXcmWeight: Weight = 200_000_000; /// The maximum number of distinct assets allowed to be transferred in a /// single helper extrinsic. pub const MaxAssetsForTransfer: usize = 2; From a708fb11e11eef8f703aaa5a552fa8170c831b93 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sat, 5 Nov 2022 15:35:06 +0200 Subject: [PATCH 27/59] Increase ExistentialDeposit & Add Treasury to dust whitelist Increasing the Existential deposit is necessary, because otherwise the existential deposit requirements are not met when depositing XCM fees into the treasury --- .../integration_tests/xcm/tests/transfers.rs | 134 +++++++++--------- runtime/battery-station/src/parameters.rs | 2 +- .../battery-station/src/xcm_config/config.rs | 10 +- runtime/common/src/lib.rs | 1 + runtime/zeitgeist/src/parameters.rs | 2 +- 5 files changed, 80 insertions(+), 69 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index b7d24cb0d..0c15f0977 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -19,9 +19,10 @@ use crate::{ integration_tests::xcm::{ setup::{ - foreign, ksm, register_foreign_ztg, sibling, sibling_account, zeitgeist_account, ztg, - ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_SIBLING_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, register_foreign_parent, foreign_ztg_multilocation, - foreign_parent_multilocation, + foreign, foreign_parent_multilocation, foreign_ztg_multilocation, ksm, + register_foreign_parent, register_foreign_ztg, sibling, sibling_account, + zeitgeist_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_SIBLING_ID, + FOREIGN_ZTG_ID, PARA_ID_SIBLING, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, @@ -30,7 +31,7 @@ use crate::{ config::{general_key, zeitgeist, AssetConvert}, fees::default_per_second, }, - AssetRegistry, Balance, Balances, CurrencyId, ExistentialDeposit, Origin, Tokens, XTokens, + AssetRegistry, Balance, Balances, CurrencyId, ExistentialDeposit, Origin, Tokens, XTokens, ZeitgeistTreasuryAccount, }; use frame_support::{assert_ok, traits::tokens::fungible::Mutate}; @@ -46,26 +47,24 @@ use xcm_executor::traits::Convert as C1; use zeitgeist_primitives::constants::BalanceFractionalDecimals; - #[test] fn transfer_ztg_to_sibling() { TestNet::reset(); let alice_initial_balance = ztg(10); let transfer_amount = ztg(5); + let mut treasury_initial_balance = 0; Sibling::execute_with(|| { + treasury_initial_balance = + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()); assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), 0); - - // We don't have to register ZTG because ZTG is the native currency - // of the sibling chain (it is a Zeitgeist clone). register_foreign_ztg(None); }); Zeitgeist::execute_with(|| { assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); assert_eq!(Balances::free_balance(&sibling_account()), 0); - assert_ok!(XTokens::transfer( Origin::signed(ALICE.into()), CurrencyId::Ztg, @@ -80,7 +79,7 @@ fn transfer_ztg_to_sibling() { ) .into() ), - 4_000_000_000, + 4_000_000_000, )); // Confirm that Alice's balance is initial_balance - amount_transferred @@ -98,6 +97,12 @@ fn transfer_ztg_to_sibling() { // Sanity check for the actual amount BOB ends up with assert_eq!(current_balance, 49_936_000_000); + + // Verify that fees (of foreign currency) have been put into treasury + assert_eq!( + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()), + treasury_initial_balance + ztg_fee() + ) }); } @@ -112,11 +117,15 @@ fn transfer_ztg_sibling_to_zeitgeist() { let alice_initial_balance = ztg(5); let bob_initial_balance = ztg(5) - ztg_fee(); + let mut treasury_initial_balance = 0; let sibling_sovereign_initial_balance = ztg(5); let transfer_amount = ztg(1); // Note: This asset was registered in `transfer_ztg_to_sibling` Zeitgeist::execute_with(|| { + treasury_initial_balance = + Balances::free_balance(ZeitgeistTreasuryAccount::get()); + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); assert_eq!(Balances::free_balance(&sibling_account()), sibling_sovereign_initial_balance); }); @@ -138,11 +147,14 @@ fn transfer_ztg_sibling_to_zeitgeist() { ) .into() ), - 4_000_000_000, + 4_000_000_000, )); // Confirm that Bobs's balance is initial balance - amount transferred - assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), bob_initial_balance - transfer_amount); + assert_eq!( + Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), + bob_initial_balance - transfer_amount + ); }); Zeitgeist::execute_with(|| { @@ -157,40 +169,41 @@ fn transfer_ztg_sibling_to_zeitgeist() { Balances::free_balance(&sibling_account()), sibling_sovereign_initial_balance - transfer_amount ); + + // Verify that fees (of native currency) have been put into treasury + assert_eq!( + Balances::free_balance(ZeitgeistTreasuryAccount::get()), + treasury_initial_balance + ztg_fee() + ) }); } +/* + #[test] fn transfer_ksm_from_relay_chain() { - let transfer_amount: Balance = ksm(1); + let transfer_amount: Balance = ksm(1); Zeitgeist::execute_with(|| { register_foreign_parent(None); }); - KusamaNet::execute_with(|| { - assert_ok!(kusama_runtime::XcmPallet::reserve_transfer_assets( - kusama_runtime::Origin::signed(ALICE.into()), - Box::new(Parachain(zeitgeist::ID).into().into()), - Box::new( - Junction::AccountId32 { - network: NetworkId::Any, - id: BOB, - } - .into() - .into() - ), - Box::new((Here, transfer_amount).into()), - 0 - )); - }); - - Zeitgeist::execute_with(|| { - assert_eq!( - Tokens::free_balance(FOREIGN_PARENT_ID, &BOB.into()), - transfer_amount - ksm_fee() - ); - }); + KusamaNet::execute_with(|| { + assert_ok!(kusama_runtime::XcmPallet::reserve_transfer_assets( + kusama_runtime::Origin::signed(ALICE.into()), + Box::new(Parachain(zeitgeist::ID).into().into()), + Box::new(Junction::AccountId32 { network: NetworkId::Any, id: BOB }.into().into()), + Box::new((Here, transfer_amount).into()), + 0 + )); + }); + + Zeitgeist::execute_with(|| { + assert_eq!( + Tokens::free_balance(FOREIGN_PARENT_ID, &BOB.into()), + transfer_amount - ksm_fee() + ); + }); } #[test] @@ -198,54 +211,47 @@ fn transfer_ksm_to_relay_chain() { let transfer_amount: Balance = ksm(1); transfer_ksm_from_relay_chain(); - Zeitgeist::execute_with(|| { + Zeitgeist::execute_with(|| { let initial_balance = Tokens::free_balance(FOREIGN_PARENT_ID, &ALICE.into()); assert!(initial_balance >= transfer_amount); - assert_ok!(XTokens::transfer( - Origin::signed(ALICE.into()), - FOREIGN_PARENT_ID, - transfer_amount, - Box::new( - MultiLocation::new( - 1, - X1(Junction::AccountId32 { - id: BOB, - network: NetworkId::Any, - }) - ) - .into() - ), - 4_000_000_000 - )); + assert_ok!(XTokens::transfer( + Origin::signed(ALICE.into()), + FOREIGN_PARENT_ID, + transfer_amount, + Box::new( + MultiLocation::new( + 1, + X1(Junction::AccountId32 { id: BOB, network: NetworkId::Any }) + ) + .into() + ), + 4_000_000_000 + )); assert_eq!( Tokens::free_balance(FOREIGN_PARENT_ID, &ALICE.into()), initial_balance - transfer_amount ) - }); - - KusamaNet::execute_with(|| { - assert_eq!( - kusama_runtime::Balances::free_balance(&BOB.into()), - 999834059328 - ); - }); -} + }); + KusamaNet::execute_with(|| { + assert_eq!(kusama_runtime::Balances::free_balance(&BOB.into()), 999834059328); + }); +} +*/ +// Test custom fees // Test handling of unknown tokens // Test treasury assignments - #[test] fn test_total_fee() { assert_eq!(ztg_fee(), 64000000); assert_eq!(ksm_fee(), 6400000000); } - #[inline] fn ztg_fee() -> Balance { fee(BalanceFractionalDecimals::get().into()) diff --git a/runtime/battery-station/src/parameters.rs b/runtime/battery-station/src/parameters.rs index 345959981..9ef06f111 100644 --- a/runtime/battery-station/src/parameters.rs +++ b/runtime/battery-station/src/parameters.rs @@ -49,7 +49,7 @@ parameter_types! { pub const MaxAuthorities: u32 = 32; // Balance - pub const ExistentialDeposit: u128 = 5 * CENT; + pub const ExistentialDeposit: u128 = 5 * MILLI; pub const MaxLocks: u32 = 50; pub const MaxReserves: u32 = 50; diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index b1ef50442..7d11dfa01 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -18,8 +18,8 @@ use super::fees::{native_per_second, FixedConversionRateProvider}; use crate::{ AccountId, Ancestry, AssetManager, AssetRegistry, Balance, Call, CurrencyId, MaxInstructions, - Origin, ParachainInfo, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, UnitWeightCost, - UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, + Origin, ParachainInfo, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, + UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; use alloc::vec::Vec; @@ -50,6 +50,7 @@ use xcm_executor::Config; use zeitgeist_primitives::types::Asset; pub mod zeitgeist { + #[cfg(test)] pub const ID: u32 = 2101; pub const KEY: &[u8] = &[0, 1]; } @@ -195,7 +196,10 @@ impl Convert> for AssetConvert { match id { Asset::Ztg => Some(MultiLocation::new( 1, - X2(Junction::Parachain(ParachainInfo::parachain_id().into()), general_key(zeitgeist::KEY)), + X2( + Junction::Parachain(ParachainInfo::parachain_id().into()), + general_key(zeitgeist::KEY), + ), )), Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, _ => None, diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index fcd29ab6d..7b57fe61b 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -139,6 +139,7 @@ macro_rules! decl_common_types { PmPalletId::get(), SimpleDisputesPalletId::get(), SwapsPalletId::get(), + TreasuryPalletId::get(), ]; if let Some(pallet_id) = frame_support::PalletId::try_from_sub_account::(ai) { diff --git a/runtime/zeitgeist/src/parameters.rs b/runtime/zeitgeist/src/parameters.rs index e4b95358b..8c11c0de2 100644 --- a/runtime/zeitgeist/src/parameters.rs +++ b/runtime/zeitgeist/src/parameters.rs @@ -49,7 +49,7 @@ parameter_types! { pub const MaxAuthorities: u32 = 32; // Balance - pub const ExistentialDeposit: u128 = 5 * CENT; + pub const ExistentialDeposit: u128 = 5 * MILLI; pub const MaxLocks: u32 = 50; pub const MaxReserves: u32 = 50; From b7b665b4559562835fe17388bc85e6d564a2e2d7 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sat, 5 Nov 2022 16:15:41 +0200 Subject: [PATCH 28/59] Fix custom fee calculation --- runtime/battery-station/src/xcm_config/fees.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/runtime/battery-station/src/xcm_config/fees.rs b/runtime/battery-station/src/xcm_config/fees.rs index de0321886..e5ba9d6ea 100644 --- a/runtime/battery-station/src/xcm_config/fees.rs +++ b/runtime/battery-station/src/xcm_config/fees.rs @@ -55,22 +55,23 @@ pub fn bmul(a: u128, b: u128, base: u128) -> Option { /// Our FixedConversionRateProvider, used to charge XCM-related fees for tokens registered in /// the asset registry that were not already handled by native Trader rules. -pub struct FixedConversionRateProvider(PhantomData); +pub struct FixedConversionRateProvider(PhantomData); impl< - OrmlAssetRegistry: orml_traits::asset_registry::Inspect< + AssetRegistry: orml_traits::asset_registry::Inspect< AssetId = CurrencyId, Balance = Balance, CustomMetadata = CustomMetadata, >, -> orml_traits::FixedConversionRateProvider for FixedConversionRateProvider +> orml_traits::FixedConversionRateProvider for FixedConversionRateProvider { fn get_fee_per_second(location: &MultiLocation) -> Option { - let metadata = OrmlAssetRegistry::metadata_by_location(&location)?; + let metadata = AssetRegistry::metadata_by_location(&location)?; let default_per_second = default_per_second(metadata.decimals); if let Some(fee_factor) = metadata.additional.xcm.fee_factor { - bmul(default_per_second, fee_factor, metadata.decimals.into()) + let base = 10u128.checked_pow(metadata.decimals.into())?; + bmul(default_per_second, fee_factor, base) } else { Some(default_per_second) } From d31dcc6feafeb45af891b2a4ba1f8fc6e6f070af Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sat, 5 Nov 2022 16:39:18 +0200 Subject: [PATCH 29/59] Add custom fee test --- .../integration_tests/xcm/tests/transfers.rs | 90 ++++++++++++++++--- 1 file changed, 80 insertions(+), 10 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index 0c15f0977..f28e29033 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -31,7 +31,8 @@ use crate::{ config::{general_key, zeitgeist, AssetConvert}, fees::default_per_second, }, - AssetRegistry, Balance, Balances, CurrencyId, ExistentialDeposit, Origin, Tokens, XTokens, ZeitgeistTreasuryAccount, + AssetRegistry, Balance, Balances, CurrencyId, ExistentialDeposit, Origin, Tokens, XTokens, + ZeitgeistTreasuryAccount, }; use frame_support::{assert_ok, traits::tokens::fungible::Mutate}; @@ -46,7 +47,6 @@ use xcm_emulator::TestExt; use xcm_executor::traits::Convert as C1; use zeitgeist_primitives::constants::BalanceFractionalDecimals; - #[test] fn transfer_ztg_to_sibling() { TestNet::reset(); @@ -123,9 +123,8 @@ fn transfer_ztg_sibling_to_zeitgeist() { // Note: This asset was registered in `transfer_ztg_to_sibling` Zeitgeist::execute_with(|| { - treasury_initial_balance = - Balances::free_balance(ZeitgeistTreasuryAccount::get()); - + treasury_initial_balance = Balances::free_balance(ZeitgeistTreasuryAccount::get()); + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); assert_eq!(Balances::free_balance(&sibling_account()), sibling_sovereign_initial_balance); }); @@ -178,8 +177,6 @@ fn transfer_ztg_sibling_to_zeitgeist() { }); } -/* - #[test] fn transfer_ksm_from_relay_chain() { let transfer_amount: Balance = ksm(1); @@ -240,11 +237,84 @@ fn transfer_ksm_to_relay_chain() { }); } -*/ +#[test] +fn transfer_ztg_to_sibling_with_custom_fee() { + TestNet::reset(); + + let alice_initial_balance = ztg(10); + // 10x fee factor, so ZTG has 10x the worth of sibling currency. + let fee_factor = 100_000_000_000; + let transfer_amount = ztg(5); + let mut treasury_initial_balance = 0; + + Sibling::execute_with(|| { + treasury_initial_balance = + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), 0); + + register_foreign_ztg(None); + let custom_metadata = CustomMetadata { + xcm: XcmMetadata { fee_factor: Some(fee_factor) }, + ..Default::default() + }; + assert_ok!(AssetRegistry::do_update_asset( + FOREIGN_ZTG_ID, + None, + None, + None, + None, + None, + Some(custom_metadata) + )); + }); + + Zeitgeist::execute_with(|| { + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); + assert_eq!(Balances::free_balance(&sibling_account()), 0); + assert_ok!(XTokens::transfer( + Origin::signed(ALICE.into()), + CurrencyId::Ztg, + transfer_amount, + Box::new( + MultiLocation::new( + 1, + X2( + Parachain(PARA_ID_SIBLING), + Junction::AccountId32 { network: NetworkId::Any, id: BOB.into() } + ) + ) + .into() + ), + 4_000_000_000, + )); + + // Confirm that Alice's balance is initial_balance - amount_transferred + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance - transfer_amount); + + // Verify that the amount transferred is now part of the sibling account here + assert_eq!(Balances::free_balance(&sibling_account()), transfer_amount); + }); + + Sibling::execute_with(|| { + let current_balance = Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()); + let custom_fee = calc_fee(default_per_second(10) * 10); + + // Verify that BOB now has (amount transferred - fee) + assert_eq!(current_balance, transfer_amount - custom_fee); + + // Sanity check for the actual amount BOB ends up with + assert_eq!(current_balance, 49_360_000_000); + + // Verify that fees (of foreign currency) have been put into treasury + assert_eq!( + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()), + treasury_initial_balance + custom_fee + ) + }); +} + -// Test custom fees // Test handling of unknown tokens -// Test treasury assignments #[test] fn test_total_fee() { From 6cee15d48c18cd5a8e6f17fa651da05b7e38c7fa Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sat, 5 Nov 2022 17:00:18 +0200 Subject: [PATCH 30/59] Finalize XCM integration tests --- .../src/integration_tests/xcm/restricted_calls.rs | 1 - .../src/integration_tests/xcm/tests/asset_registry.rs | 1 - .../src/integration_tests/xcm/tests/transfers.rs | 3 --- runtime/battery-station/src/xcm_config/config.rs | 2 -- 4 files changed, 7 deletions(-) delete mode 100644 runtime/battery-station/src/integration_tests/xcm/restricted_calls.rs delete mode 100644 runtime/battery-station/src/integration_tests/xcm/tests/asset_registry.rs diff --git a/runtime/battery-station/src/integration_tests/xcm/restricted_calls.rs b/runtime/battery-station/src/integration_tests/xcm/restricted_calls.rs deleted file mode 100644 index 8b1378917..000000000 --- a/runtime/battery-station/src/integration_tests/xcm/restricted_calls.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/asset_registry.rs b/runtime/battery-station/src/integration_tests/xcm/tests/asset_registry.rs deleted file mode 100644 index 8b1378917..000000000 --- a/runtime/battery-station/src/integration_tests/xcm/tests/asset_registry.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index f28e29033..10f03033c 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -313,9 +313,6 @@ fn transfer_ztg_to_sibling_with_custom_fee() { }); } - -// Test handling of unknown tokens - #[test] fn test_total_fee() { assert_eq!(ztg_fee(), 64000000); diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 7d11dfa01..985672abb 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -134,8 +134,6 @@ impl TakeRevenue for ToTreasury { >::convert(location.clone()) { let _ = AssetManager::deposit(asset_id, &ZeitgeistTreasuryAccount::get(), amount); - } else { - let _ = UnknownTokens::deposit(&revenue, &location); } } } From e914d54d59068bd2c78d675a055300d4002b053b Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Mon, 7 Nov 2022 14:23:38 +0200 Subject: [PATCH 31/59] Remove unused modules --- .../src/integration_tests/xcm/mod.rs | 1 - .../src/integration_tests/xcm/tests/mod.rs | 19 ++++++++++++++++++- .../src/{xcm_config.rs => xcm_config/mod.rs} | 1 - 3 files changed, 18 insertions(+), 3 deletions(-) rename runtime/battery-station/src/{xcm_config.rs => xcm_config/mod.rs} (97%) diff --git a/runtime/battery-station/src/integration_tests/xcm/mod.rs b/runtime/battery-station/src/integration_tests/xcm/mod.rs index 1ab18d3f5..d2226363f 100644 --- a/runtime/battery-station/src/integration_tests/xcm/mod.rs +++ b/runtime/battery-station/src/integration_tests/xcm/mod.rs @@ -16,7 +16,6 @@ #![cfg(all(feature = "parachain", test))] -mod restricted_calls; mod setup; mod test_net; mod tests; diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/mod.rs b/runtime/battery-station/src/integration_tests/xcm/tests/mod.rs index 06be98bf8..44d31098b 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/mod.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/mod.rs @@ -1,3 +1,20 @@ -mod asset_registry; +// Copyright 2022 Forecasting Technologies LTD. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + + mod currency_id_convert; mod transfers; diff --git a/runtime/battery-station/src/xcm_config.rs b/runtime/battery-station/src/xcm_config/mod.rs similarity index 97% rename from runtime/battery-station/src/xcm_config.rs rename to runtime/battery-station/src/xcm_config/mod.rs index 0343f29b6..363ac87b1 100644 --- a/runtime/battery-station/src/xcm_config.rs +++ b/runtime/battery-station/src/xcm_config/mod.rs @@ -20,4 +20,3 @@ pub mod asset_registry; pub mod config; pub mod fees; -pub mod parachains; From ec00ef244c909f39da3f8f29be9640e380f5b531 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Mon, 7 Nov 2022 14:29:16 +0200 Subject: [PATCH 32/59] Add XCM related pallets to common runtime --- runtime/battery-station/src/lib.rs | 40 ------------------------------ runtime/common/src/lib.rs | 39 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 40 deletions(-) diff --git a/runtime/battery-station/src/lib.rs b/runtime/battery-station/src/lib.rs index 4378bee2d..63071ac3a 100644 --- a/runtime/battery-station/src/lib.rs +++ b/runtime/battery-station/src/lib.rs @@ -144,9 +144,6 @@ create_runtime_with_additional_pallets!( create_runtime_with_additional_pallets!( // Others Sudo: pallet_sudo::{Call, Config, Event, Pallet, Storage} = 150, - AssetRegistry: orml_asset_registry::{Call, Config, Event, Pallet, Storage} = 151, - UnknownTokens: orml_unknown_tokens::{Pallet, Storage, Event} = 152, - XTokens: orml_xtokens::{Pallet, Storage, Call, Event} = 153, ); impl pallet_sudo::Config for Runtime { @@ -154,43 +151,6 @@ impl pallet_sudo::Config for Runtime { type Event = Event; } -#[cfg(feature = "parachain")] -impl orml_asset_registry::Config for Runtime { - type AssetId = CurrencyId; - type AssetProcessor = CustomAssetProcessor; - type AuthorityOrigin = AsEnsureOriginWithArg; - type Balance = Balance; - type CustomMetadata = CustomMetadata; - type Event = Event; - type WeightInfo = (); -} - -#[cfg(feature = "parachain")] -impl orml_unknown_tokens::Config for Runtime { - type Event = Event; -} - -#[cfg(feature = "parachain")] -use xcm_config::config::*; - -#[cfg(feature = "parachain")] -impl orml_xtokens::Config for Runtime { - type AccountIdToMultiLocation = AccountIdToMultiLocation; - type Balance = Balance; - type BaseXcmWeight = BaseXcmWeight; - type CurrencyId = CurrencyId; - type CurrencyIdConvert = AssetConvert; - type Event = Event; - type LocationInverter = LocationInverter; - type MaxAssetsForTransfer = MaxAssetsForTransfer; - type MinXcmFee = ParachainMinFee; - type MultiLocationsFilter = Everything; - type ReserveProvider = orml_traits::location::AbsoluteReserveProvider; - type SelfLocation = SelfLocation; - type Weigher = FixedWeightBounds; - type XcmExecutor = xcm_executor::XcmExecutor; -} - impl_config_traits!(); create_runtime_api!(); create_common_benchmark_logic!(); diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 7b57fe61b..60a4b9087 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -273,6 +273,9 @@ macro_rules! create_runtime_with_additional_pallets { DmpQueue: cumulus_pallet_dmp_queue::{Call, Event, Pallet, Storage} = 121, PolkadotXcm: pallet_xcm::{Call, Config, Event, Origin, Pallet, Storage} = 122, XcmpQueue: cumulus_pallet_xcmp_queue::{Call, Event, Pallet, Storage} = 123, + AssetRegistry: orml_asset_registry::{Call, Config, Event, Pallet, Storage} = 124, + UnknownTokens: orml_unknown_tokens::{Pallet, Storage, Event} = 125, + XTokens: orml_xtokens::{Pallet, Storage, Call, Event} = 126, // Third-party Crowdloan: pallet_crowdloan_rewards::{Call, Config, Event, Pallet, Storage} = 130, @@ -297,6 +300,8 @@ macro_rules! create_runtime_with_additional_pallets { macro_rules! impl_config_traits { {} => { use common_runtime::weights; + #[cfg(feature = "parachain")] + use xcm_config::config::*; // Configure Pallets #[cfg(feature = "parachain")] @@ -467,6 +472,17 @@ macro_rules! impl_config_traits { type WeightInfo = weights::parachain_staking::WeightInfo; } + #[cfg(feature = "parachain")] + impl orml_asset_registry::Config for Runtime { + type AssetId = CurrencyId; + type AssetProcessor = CustomAssetProcessor; + type AuthorityOrigin = AsEnsureOriginWithArg; + type Balance = Balance; + type CustomMetadata = CustomMetadata; + type Event = Event; + type WeightInfo = (); + } + impl orml_currencies::Config for Runtime { type GetNativeCurrencyId = GetNativeCurrencyId; type MultiCurrency = Tokens; @@ -490,6 +506,29 @@ macro_rules! impl_config_traits { type OnKilledTokenAccount = (); } + #[cfg(feature = "parachain")] + impl orml_unknown_tokens::Config for Runtime { + type Event = Event; + } + + #[cfg(feature = "parachain")] + impl orml_xtokens::Config for Runtime { + type AccountIdToMultiLocation = AccountIdToMultiLocation; + type Balance = Balance; + type BaseXcmWeight = BaseXcmWeight; + type CurrencyId = CurrencyId; + type CurrencyIdConvert = AssetConvert; + type Event = Event; + type LocationInverter = LocationInverter; + type MaxAssetsForTransfer = MaxAssetsForTransfer; + type MinXcmFee = ParachainMinFee; + type MultiLocationsFilter = Everything; + type ReserveProvider = orml_traits::location::AbsoluteReserveProvider; + type SelfLocation = SelfLocation; + type Weigher = FixedWeightBounds; + type XcmExecutor = xcm_executor::XcmExecutor; + } + #[cfg(feature = "parachain")] impl pallet_crowdloan_rewards::Config for Runtime { type Event = Event; From 0d460a19796c1b09199b5b2f60123621a366caff Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Mon, 7 Nov 2022 14:39:36 +0200 Subject: [PATCH 33/59] Cleanup code --- .../src/integration_tests/xcm/test_net.rs | 5 ++--- .../xcm/tests/currency_id_convert.rs | 21 +++++++------------ .../integration_tests/xcm/tests/transfers.rs | 20 +++++++----------- .../battery-station/src/parachain_params.rs | 4 ++-- .../battery-station/src/xcm_config/config.rs | 2 +- 5 files changed, 21 insertions(+), 31 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index 7185aee5a..94abd1225 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -17,18 +17,17 @@ use crate::{ parameters::ZeitgeistTreasuryAccount, - xcm_config::{asset_registry::CustomMetadata, config::zeitgeist}, + xcm_config::{config::zeitgeist}, AccountId, CurrencyId, DmpQueue, Origin, Runtime, XcmpQueue, }; use cumulus_primitives_core::ParaId; use frame_support::{traits::GenesisBuild, weights::Weight}; -use orml_traits::asset_registry::AssetMetadata; use polkadot_primitives::v2::{BlockNumber, MAX_CODE_SIZE, MAX_POV_SIZE}; use polkadot_runtime_parachains::configuration::HostConfiguration; use sp_runtime::traits::AccountIdConversion; use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; -use super::setup::{ksm, sibling, ztg, ExtBuilder, ALICE, BOB, FOREIGN_PARENT_ID, PARA_ID_SIBLING}; +use super::setup::{ksm, sibling, ztg, ExtBuilder, ALICE, FOREIGN_PARENT_ID, PARA_ID_SIBLING}; decl_test_relay_chain! { pub struct KusamaNet { diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs index f297ac29d..ced783a67 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -19,28 +19,23 @@ use crate::{ integration_tests::xcm::{ setup::{ - foreign, foreign_parent_multilocation, foreign_sibling_multilocation, - foreign_ztg_multilocation, ksm, register_foreign_parent, register_foreign_sibling, - sibling, sibling_account, zeitgeist_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, - FOREIGN_SIBLING_ID, PARA_ID_SIBLING, + foreign_parent_multilocation, foreign_sibling_multilocation, + foreign_ztg_multilocation, register_foreign_parent, register_foreign_sibling, + FOREIGN_PARENT_ID, + FOREIGN_SIBLING_ID, }, - test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, + test_net::{Zeitgeist}, }, xcm_config::{ - asset_registry::{CustomMetadata, XcmMetadata}, config::{general_key, zeitgeist, AssetConvert}, - fees::default_per_second, }, - AssetRegistry, Balance, Balances, CurrencyId, Origin, Tokens, XTokens, + CurrencyId }; -use frame_support::{assert_err, assert_ok}; -use orml_traits::{asset_registry::AssetMetadata, FixedConversionRateProvider, MultiCurrency}; -use parity_scale_codec::Encode; +use frame_support::{assert_err}; use sp_runtime::traits::Convert as C2; use xcm::{ - latest::{Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, - VersionedMultiLocation, + latest::{Junction::*, Junctions::*, MultiLocation}, }; use xcm_emulator::TestExt; use xcm_executor::traits::Convert as C1; diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index 10f03033c..993c04370 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -19,32 +19,28 @@ use crate::{ integration_tests::xcm::{ setup::{ - foreign, foreign_parent_multilocation, foreign_ztg_multilocation, ksm, - register_foreign_parent, register_foreign_ztg, sibling, sibling_account, - zeitgeist_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_SIBLING_ID, + ksm, + register_foreign_parent, register_foreign_ztg, sibling_account, + zeitgeist_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, xcm_config::{ asset_registry::{CustomMetadata, XcmMetadata}, - config::{general_key, zeitgeist, AssetConvert}, + config::{zeitgeist,}, fees::default_per_second, }, - AssetRegistry, Balance, Balances, CurrencyId, ExistentialDeposit, Origin, Tokens, XTokens, + AssetRegistry, Balance, Balances, CurrencyId, Origin, Tokens, XTokens, ZeitgeistTreasuryAccount, }; -use frame_support::{assert_ok, traits::tokens::fungible::Mutate}; -use orml_traits::{asset_registry::AssetMetadata, FixedConversionRateProvider, MultiCurrency}; -use parity_scale_codec::Encode; -use sp_runtime::traits::Convert as C2; +use frame_support::{assert_ok}; +use orml_traits::{MultiCurrency}; use xcm::{ - latest::{Error::BadOrigin, Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, - VersionedMultiLocation, + latest::{Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, }; use xcm_emulator::TestExt; -use xcm_executor::traits::Convert as C1; use zeitgeist_primitives::constants::BalanceFractionalDecimals; #[test] diff --git a/runtime/battery-station/src/parachain_params.rs b/runtime/battery-station/src/parachain_params.rs index 95fedee22..6d471c331 100644 --- a/runtime/battery-station/src/parachain_params.rs +++ b/runtime/battery-station/src/parachain_params.rs @@ -25,10 +25,10 @@ use super::{parameters::MAXIMUM_BLOCK_WEIGHT, Origin, ParachainInfo}; use frame_support::{parameter_types, traits::Get, weights::Weight}; use orml_traits::parameter_type_with_key; -use sp_runtime::{Perbill, Percent, SaturatedConversion}; +use sp_runtime::{Perbill, Percent}; use xcm::latest::{prelude::X1, Junction::Parachain, MultiLocation, NetworkId}; use zeitgeist_primitives::{ - constants::{BASE, BLOCKS_PER_MINUTE, MICRO}, + constants::{BASE, BLOCKS_PER_MINUTE}, types::Balance, }; diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 985672abb..34be2ff3a 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -27,7 +27,7 @@ use frame_support::{match_types, parameter_types, traits::Everything}; use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{location::AbsoluteReserveProvider, MultiCurrency}; use orml_xcm_support::{ - DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset, UnknownAsset, + DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset, }; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; From d990634e8bb3249f8cf0a58024ec35540073532a Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Mon, 7 Nov 2022 15:51:22 +0200 Subject: [PATCH 34/59] Add proper XCM configuration to Zeitgeist runtime --- Cargo.lock | 5 + runtime/battery-station/Cargo.toml | 9 +- .../src/integration_tests/xcm/setup.rs | 4 +- runtime/battery-station/src/lib.rs | 7 - runtime/zeitgeist/Cargo.toml | 19 ++ runtime/zeitgeist/src/lib.rs | 7 +- runtime/zeitgeist/src/parachain_params.rs | 110 ++---- runtime/zeitgeist/src/parameters.rs | 2 + runtime/zeitgeist/src/xcm_config.rs | 43 --- .../src/xcm_config/asset_registry.rs | 94 ++++++ runtime/zeitgeist/src/xcm_config/config.rs | 313 ++++++++++++++++++ runtime/zeitgeist/src/xcm_config/fees.rs | 79 +++++ .../src/xcm_config/mod.rs} | 15 +- 13 files changed, 549 insertions(+), 158 deletions(-) delete mode 100644 runtime/zeitgeist/src/xcm_config.rs create mode 100644 runtime/zeitgeist/src/xcm_config/asset_registry.rs create mode 100644 runtime/zeitgeist/src/xcm_config/config.rs create mode 100644 runtime/zeitgeist/src/xcm_config/fees.rs rename runtime/{battery-station/src/xcm_config/parachains.rs => zeitgeist/src/xcm_config/mod.rs} (55%) diff --git a/Cargo.lock b/Cargo.lock index 7fc7e2610..40ae0ea88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12753,14 +12753,17 @@ dependencies = [ "frame-system-rpc-runtime-api", "frame-try-runtime", "hex-literal", + "kusama-runtime", "log", "nimbus-primitives", + "orml-asset-registry", "orml-benchmarking", "orml-currencies", "orml-tokens", "orml-traits", "orml-unknown-tokens", "orml-xcm-support", + "orml-xtokens", "pallet-aura", "pallet-author-inherent", "pallet-author-mapping", @@ -12788,6 +12791,8 @@ dependencies = [ "parachain-staking", "parity-scale-codec", "polkadot-parachain", + "polkadot-primitives", + "polkadot-runtime-parachains", "scale-info", "sp-api", "sp-block-builder", diff --git a/runtime/battery-station/Cargo.toml b/runtime/battery-station/Cargo.toml index a42e5d186..9d39d3080 100644 --- a/runtime/battery-station/Cargo.toml +++ b/runtime/battery-station/Cargo.toml @@ -275,6 +275,9 @@ std = [ # XCM + "kusama-runtime?/std", + "polkadot-primitives?/std", + "polkadot-runtime-parachains?/std", "orml-asset-registry?/std", "orml-unknown-tokens?/std", "orml-xcm-support?/std", @@ -283,12 +286,6 @@ std = [ "xcm-builder?/std", "xcm-executor?/std", "xcm?/std", - - # XCM test dependencies - # TODO Only include those when in test environment and feature=parachain - "kusama-runtime?/std", - "polkadot-primitives?/std", - "polkadot-runtime-parachains?/std", # Zeitgeist diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs index 36431a9b5..19697f0e3 100644 --- a/runtime/battery-station/src/integration_tests/xcm/setup.rs +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -131,7 +131,7 @@ pub(super) fn register_foreign_ztg(additional_meta: Option) { decimals: 10, name: "Zeitgeist".into(), symbol: "ZTG".into(), - existential_deposit: 500_000_000, // 0.05 + existential_deposit: 50_000_000, // 0.005 location: Some(VersionedMultiLocation::V1(foreign_ztg_multilocation())), additional: additional_meta.unwrap_or_default(), }; @@ -145,7 +145,7 @@ pub(super) fn register_foreign_sibling(additional_meta: Option) decimals: 10, name: "Sibling".into(), symbol: "SBL".into(), - existential_deposit: 500_000_000, // 0.05 + existential_deposit: 50_000_000, // 0.005 location: Some(VersionedMultiLocation::V1(foreign_sibling_multilocation())), additional: additional_meta.unwrap_or_default(), }; diff --git a/runtime/battery-station/src/lib.rs b/runtime/battery-station/src/lib.rs index 63071ac3a..a747cd226 100644 --- a/runtime/battery-station/src/lib.rs +++ b/runtime/battery-station/src/lib.rs @@ -134,13 +134,6 @@ impl Contains for IsCallable { decl_common_types!(); -#[cfg(not(feature = "parachain"))] -create_runtime_with_additional_pallets!( - // Others - Sudo: pallet_sudo::{Call, Config, Event, Pallet, Storage} = 150, -); - -#[cfg(feature = "parachain")] create_runtime_with_additional_pallets!( // Others Sudo: pallet_sudo::{Call, Config, Event, Pallet, Storage} = 150, diff --git a/runtime/zeitgeist/Cargo.toml b/runtime/zeitgeist/Cargo.toml index 6cc634dae..a5fcab724 100644 --- a/runtime/zeitgeist/Cargo.toml +++ b/runtime/zeitgeist/Cargo.toml @@ -70,8 +70,13 @@ parachain-staking = { rev = "78db06c0203f61b35059304f7194ed5c10dcfda8", default- polkadot-parachain = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } # XCM +kusama-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +polkadot-primitives = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +polkadot-runtime-parachains = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +orml-asset-registry = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-unknown-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-xtokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } pallet-xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm-builder = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } @@ -133,8 +138,13 @@ parachain = [ # XCM + "kusama-runtime", + "polkadot-primitives", + "polkadot-runtime-parachains", + "orml-asset-registry", "orml-unknown-tokens", "orml-xcm-support", + "orml-xtokens", "pallet-xcm", "xcm-builder", "xcm-executor", @@ -153,6 +163,7 @@ runtime-benchmarks = [ "frame-system/runtime-benchmarks", "hex-literal", "orml-tokens/runtime-benchmarks", + "orml-xtokens?/runtime-benchmarks", "orml-benchmarking", "pallet-author-mapping/runtime-benchmarks", "pallet-author-slot-filter/runtime-benchmarks", @@ -254,8 +265,13 @@ std = [ # XCM + "kusama-runtime?/std", + "polkadot-primitives?/std", + "polkadot-runtime-parachains?/std", + "orml-asset-registry?/std", "orml-unknown-tokens?/std", "orml-xcm-support?/std", + "orml-xtokens?/std", "pallet-xcm?/std", "xcm-builder?/std", "xcm-executor?/std", @@ -312,8 +328,11 @@ try-runtime = [ "pallet-utility/try-runtime", # ORML runtime pallets + "orml-asset-registry?/try-runtime", "orml-currencies/try-runtime", "orml-tokens/try-runtime", + "orml-unknown-tokens?/try-runtime", + "orml-xtokens?/try-runtime", # Zeitgeist runtime pallets "zrml-authorized/try-runtime", diff --git a/runtime/zeitgeist/src/lib.rs b/runtime/zeitgeist/src/lib.rs index 9faab27b0..fb17574af 100644 --- a/runtime/zeitgeist/src/lib.rs +++ b/runtime/zeitgeist/src/lib.rs @@ -53,10 +53,13 @@ use zeitgeist_primitives::{constants::*, types::*}; use zrml_rikiddo::types::{EmaMarketVolume, FeeSigmoid, RikiddoSigmoidMV}; #[cfg(feature = "parachain")] use { - frame_support::traits::{Everything, Nothing}, + frame_support::traits::{AsEnsureOriginWithArg, Everything, Nothing}, frame_system::EnsureSigned, xcm_builder::{EnsureXcmOrigin, FixedWeightBounds, LocationInverter}, - xcm_config::XcmConfig, + xcm_config::{ + asset_registry::{CustomAssetProcessor, CustomMetadata}, + config::{LocalOriginToLocation, XcmConfig, XcmOriginToTransactDispatchOrigin, XcmRouter}, + }, }; use frame_support::construct_runtime; diff --git a/runtime/zeitgeist/src/parachain_params.rs b/runtime/zeitgeist/src/parachain_params.rs index 733f4ea16..920841ea1 100644 --- a/runtime/zeitgeist/src/parachain_params.rs +++ b/runtime/zeitgeist/src/parachain_params.rs @@ -23,32 +23,18 @@ #![cfg(feature = "parachain")] use super::{ - parameters::MAXIMUM_BLOCK_WEIGHT, AccountId, Balances, Origin, ParachainInfo, ParachainSystem, - XcmpQueue, -}; -use frame_support::{match_types, parameter_types, traits::Everything, weights::Weight}; -use pallet_xcm::XcmPassthrough; -use polkadot_parachain::primitives::Sibling; -use sp_runtime::{Perbill, Percent, SaturatedConversion}; -use xcm::latest::{BodyId, Junction, Junctions, MultiLocation, NetworkId}; -use xcm_builder::{ - AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter, - IsConcrete, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, - SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, TakeWeightCredit, + parameters::MAXIMUM_BLOCK_WEIGHT, Origin, ParachainInfo, }; +use frame_support::{parameter_types, traits::{Get}, weights::Weight}; +use orml_traits::parameter_type_with_key; +use sp_runtime::{Perbill, Percent}; +use xcm::latest::{prelude::X1, Junction::Parachain, MultiLocation, NetworkId}; use zeitgeist_primitives::{ - constants::{BASE, BLOCKS_PER_MINUTE, MICRO}, + constants::{BASE, BLOCKS_PER_MINUTE}, types::Balance, }; -match_types! { - pub type ParentOrParentsUnitPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Junctions::Here } | - // Potentially change "Unit" to "Executive" for mainnet once we have separate runtimes - MultiLocation { parents: 1, interior: Junctions::X1(Junction::Plurality { id: BodyId::Unit, .. }) } - }; -} + parameter_types! { // Author-Mapping /// The amount that should be taken as a security deposit when registering a NimbusId. @@ -63,14 +49,14 @@ parameter_types! { pub const SignatureNetworkIdentifier: &'static [u8] = b"zeitgeist-"; // Cumulus and Polkadot - pub Ancestry: MultiLocation = Junction::Parachain(ParachainInfo::parachain_id().into()).into(); + pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); pub const RelayLocation: MultiLocation = MultiLocation::parent(); // Have to change "Any" to "Kusama" for mainnet once we have separate runtimes pub const RelayNetwork: NetworkId = NetworkId::Any; pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into(); - pub UnitWeightCost: Weight = MICRO.saturated_into(); + pub UnitWeightCost: Weight = 200_000_000; // Staking /// Rounds before the candidate bond increase/decrease can be executed @@ -107,71 +93,21 @@ parameter_types! { pub const RewardPaymentDelay: u32 = 2; // XCM + /// Base weight for XCM execution + pub const BaseXcmWeight: Weight = 200_000_000; + /// The maximum number of distinct assets allowed to be transferred in a + /// single helper extrinsic. + pub const MaxAssetsForTransfer: usize = 2; + /// Max instructions per XCM pub const MaxInstructions: u32 = 100; + // Relative self location + pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into()))); } -pub type Barrier = ( - TakeWeightCredit, - AllowTopLevelPaidExecutionFrom, - AllowUnpaidExecutionFrom, - // ^^^ Parent and its exec plurality get free execution -); - -/// Means for transacting assets on this chain. -pub type LocalAssetTransactor = CurrencyAdapter< - // Use this currency: - Balances, - // Use this currency when it is a fungible asset matching the given location or name: - IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: - LocationToAccountId, - // Our chain's account ID type (we can't get away without mentioning it explicitly): - AccountId, - // We don't track any teleports. - (), ->; - -/// No local origins on this chain are allowed to dispatch XCM sends/executions. -pub type LocalOriginToLocation = SignedToAccountId32; -/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used -/// when determining ownership of accounts for asset transacting and when attempting to use XCM -/// `Transact` in order to determine the dispatch Origin. -pub type LocationToAccountId = ( - // The parent (Relay-chain) origin converts to the parent `AccountId`. - ParentIsPreset, - // Sibling parachain origins convert to AccountId via the `ParaId::into`. - SiblingParachainConvertsVia, - // Straight up local `AccountId32` origins just alias directly to `AccountId`. - AccountId32Aliases, -); - -/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, -/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can -/// biases the kind of local `Origin` it will become. -pub type XcmOriginToTransactDispatchOrigin = ( - // Sovereign account converter; this attempts to derive an `AccountId` from the origin location - // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for - // foreign chains who want to have a local sovereign account on this chain which they control. - SovereignSignedViaLocation, - // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when - // recognized. - RelayChainAsNative, - // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when - // recognized. - SiblingParachainAsNative, - // Native signed account converter; this just converts an `AccountId32` origin into a normal - // `Origin::Signed` origin of the same 32-byte value. - SignedAccountId32AsNative, - // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. - XcmPassthrough, -); - -/// The means for routing XCM messages which are not for local execution into the right message -/// queues. -pub type XcmRouter = ( - // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, - // ..and XCMP to communicate with the sibling chains. - XcmpQueue, -); +parameter_type_with_key! { + // XCM + pub ParachainMinFee: |_location: MultiLocation| -> Option { + None + }; +} diff --git a/runtime/zeitgeist/src/parameters.rs b/runtime/zeitgeist/src/parameters.rs index 8c11c0de2..612e1ffc0 100644 --- a/runtime/zeitgeist/src/parameters.rs +++ b/runtime/zeitgeist/src/parameters.rs @@ -287,6 +287,8 @@ parameter_types! { pub const SpendPeriod: BlockNumber = 24 * BLOCKS_PER_DAY; /// Pallet identifier, mainly used for named balance reserves. DO NOT CHANGE. pub const TreasuryPalletId: PalletId = TREASURY_PALLET_ID; + /// Treasury account. + pub ZeitgeistTreasuryAccount: AccountId = TreasuryPalletId::get().into_account(); // Vesting pub const MinVestedTransfer: Balance = ExistentialDeposit::get(); diff --git a/runtime/zeitgeist/src/xcm_config.rs b/runtime/zeitgeist/src/xcm_config.rs deleted file mode 100644 index 6a70b65b6..000000000 --- a/runtime/zeitgeist/src/xcm_config.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2021-2022 Zeitgeist PM LLC. -// -// This file is part of Zeitgeist. -// -// Zeitgeist is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by the -// Free Software Foundation, either version 3 of the License, or (at -// your option) any later version. -// -// Zeitgeist is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Zeitgeist. If not, see . - -use super::{ - AccountId, Ancestry, Balance, Balances, Barrier, Call, LocalAssetTransactor, MaxInstructions, - PolkadotXcm, RelayLocation, UnitWeightCost, XcmOriginToTransactDispatchOrigin, XcmRouter, -}; -use frame_support::weights::IdentityFee; -use xcm_builder::{FixedWeightBounds, LocationInverter, NativeAsset, UsingComponents}; -use xcm_executor::Config; - -pub struct XcmConfig; - -impl Config for XcmConfig { - type AssetClaims = PolkadotXcm; - type AssetTransactor = LocalAssetTransactor; - type AssetTrap = PolkadotXcm; - type Barrier = Barrier; - type Call = Call; - type IsReserve = NativeAsset; - type IsTeleporter = (); - type LocationInverter = LocationInverter; - type OriginConverter = XcmOriginToTransactDispatchOrigin; - type ResponseHandler = PolkadotXcm; - type SubscriptionService = PolkadotXcm; - type Trader = UsingComponents, RelayLocation, AccountId, Balances, ()>; - type Weigher = FixedWeightBounds; - type XcmSender = XcmRouter; -} diff --git a/runtime/zeitgeist/src/xcm_config/asset_registry.rs b/runtime/zeitgeist/src/xcm_config/asset_registry.rs new file mode 100644 index 000000000..ba7807a8c --- /dev/null +++ b/runtime/zeitgeist/src/xcm_config/asset_registry.rs @@ -0,0 +1,94 @@ +// Copyright 2022 Zeitgeist PM LLC. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use crate::{Balance, CurrencyId}; +use orml_traits::asset_registry::{AssetMetadata, AssetProcessor}; +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; +use scale_info::TypeInfo; +use sp_runtime::DispatchError; + +#[derive( + Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen, +)] +/// Implements orml_traits::asset_registry::AssetProcessor. Does not apply any post checks. +/// Only pre check is to ensure an asset id was passed. +pub struct CustomAssetProcessor; + +impl AssetProcessor> for CustomAssetProcessor { + fn pre_register( + id: Option, + metadata: AssetMetadata, + ) -> Result<(CurrencyId, AssetMetadata), DispatchError> { + match id { + Some(id) => Ok((id, metadata)), + None => Err(DispatchError::Other("asset-registry: AssetId is required")), + } + } + + fn post_register( + _id: CurrencyId, + _asset_metadata: AssetMetadata, + ) -> Result<(), DispatchError> { + Ok(()) + } +} + +#[derive( + Clone, + Copy, + Default, + PartialOrd, + Ord, + PartialEq, + Eq, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, +)] +/// Custom XC asset metadata +pub struct CustomMetadata { + /// XCM-related metadata. + pub xcm: XcmMetadata, + + /// Whether an asset can be used in pools. + pub allow_in_pool: bool, +} + +#[derive( + Clone, + Copy, + Default, + PartialOrd, + Ord, + PartialEq, + Eq, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, +)] +pub struct XcmMetadata { + /// The factor used to determine the fee. + /// It is multiplied by the fee that would have been paid in native currency, so it represents + /// the ratio `native_price / other_asset_price`. It is a fixed point decimal number containing + /// as many fractional decimals as the asset it is used for contains. + /// Should be updated regularly. + pub fee_factor: Option, +} diff --git a/runtime/zeitgeist/src/xcm_config/config.rs b/runtime/zeitgeist/src/xcm_config/config.rs new file mode 100644 index 000000000..34be2ff3a --- /dev/null +++ b/runtime/zeitgeist/src/xcm_config/config.rs @@ -0,0 +1,313 @@ +// Copyright 2022 Zeitgeist PM LLC. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use super::fees::{native_per_second, FixedConversionRateProvider}; +use crate::{ + AccountId, Ancestry, AssetManager, AssetRegistry, Balance, Call, CurrencyId, MaxInstructions, + Origin, ParachainInfo, ParachainSystem, PolkadotXcm, RelayChainOrigin, RelayNetwork, + UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, +}; + +use alloc::vec::Vec; +use frame_support::{match_types, parameter_types, traits::Everything}; +use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; +use orml_traits::{location::AbsoluteReserveProvider, MultiCurrency}; +use orml_xcm_support::{ + DepositToAlternative, IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset, +}; +use pallet_xcm::XcmPassthrough; +use polkadot_parachain::primitives::Sibling; +use sp_runtime::traits::Convert; +use xcm::{ + latest::{ + prelude::{AccountId32, AssetId, Concrete, GeneralKey, MultiAsset, NetworkId, X1, X2}, + BodyId, Junction, Junctions, MultiLocation, + }, + opaque::latest::Fungibility::Fungible, +}; +use xcm_builder::{ + AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, FixedRateOfFungible, FixedWeightBounds, LocationInverter, + ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeRevenue, + TakeWeightCredit, +}; +use xcm_executor::Config; +use zeitgeist_primitives::types::Asset; + +pub mod zeitgeist { + #[cfg(test)] + pub const ID: u32 = 2101; + pub const KEY: &[u8] = &[0, 1]; +} + +pub struct XcmConfig; + +/// The main XCM config +/// This is where we configure the core of our XCM integrations: how tokens are transferred, +/// how fees are calculated, what barriers we impose on incoming XCM messages, etc. +impl Config for XcmConfig { + /// The handler for when there is an instruction to claim assets. + type AssetClaims = PolkadotXcm; + /// How to withdraw and deposit an asset. + type AssetTransactor = MultiAssetTransactor; + /// The general asset trap - handler for when assets are left in the Holding Register at the + /// end of execution. + type AssetTrap = PolkadotXcm; + /// Additional filters that specify whether the XCM instruction should be executed at all. + type Barrier = Barrier; + /// The outer call dispatch type. + type Call = Call; + /// Combinations of (Location, Asset) pairs which are trusted as reserves. + // Trust the parent chain, sibling parachains and children chains of this chain. + type IsReserve = MultiNativeAsset; + /// Combinations of (Location, Asset) pairs which we trust as teleporters. + type IsTeleporter = (); + /// Means of inverting a location. + type LocationInverter = LocationInverter; + // How to get a call origin from a `OriginKind` value. + type OriginConverter = XcmOriginToTransactDispatchOrigin; + /// Module that handles responses of queries. + type ResponseHandler = PolkadotXcm; + /// Module that handles subscription requests. + type SubscriptionService = PolkadotXcm; + /// The means of purchasing weight credit for XCM execution. + type Trader = Trader; + /// The means of determining an XCM message's weight. + // Adds UnitWeightCost per instruction plus the weight of each instruction. + // The total number of instructions are bounded by MaxInstructions + type Weigher = FixedWeightBounds; + /// How to send an onward XCM message. + type XcmSender = XcmRouter; +} + +/// Additional filters that specify whether the XCM instruction should be executed at all. +pub type Barrier = ( + // Execution barrier that just takes max_weight from weight_credit + TakeWeightCredit, + // Ensures that execution time is bought with BuyExecution instruction + AllowTopLevelPaidExecutionFrom, + // Expected responses are OK. + AllowKnownQueryResponses, + // Subscriptions for version tracking are OK. + AllowSubscriptionsFrom, +); + +/// The means of purchasing weight credit for XCM execution. +/// Every token that is accepted for XC transfers should be handled here. +pub type Trader = ( + // In case the asset in question is the native currency, it will charge + // the default base fee per second and deposits them into treasury + FixedRateOfFungible, + FixedRateOfFungible, + // For all other assets the base fee per second will tried to be derived + // through the `fee_factor` entry in the asset registry. If the asset is + // not present in the asset registry, the default base fee per second is used. + // Deposits all fees into the treasury. + AssetRegistryTrader< + FixedRateAssetRegistryTrader>, + ToTreasury, + >, +); + +pub struct ToTreasury; +impl TakeRevenue for ToTreasury { + fn take_revenue(revenue: MultiAsset) { + use xcm_executor::traits::Convert; + + if let MultiAsset { id: Concrete(location), fun: Fungible(amount) } = revenue.clone() { + if let Ok(asset_id) = + >::convert(location.clone()) + { + let _ = AssetManager::deposit(asset_id, &ZeitgeistTreasuryAccount::get(), amount); + } + } + } +} + +parameter_types! { + pub CheckAccount: AccountId = PolkadotXcm::check_account(); + /// The amount of ZTG charged per second of execution (canonical multilocation). + pub ZtgPerSecondCanonical: (AssetId, u128) = ( + MultiLocation::new( + 0, + X1(general_key(zeitgeist::KEY)), + ).into(), + native_per_second(), + ); + /// The amount of canonical ZTG charged per second of execution. + pub ZtgPerSecond: (AssetId, u128) = ( + MultiLocation::new( + 1, + X2(Junction::Parachain(ParachainInfo::parachain_id().into()), general_key(zeitgeist::KEY)), + ).into(), + native_per_second(), + ); +} + +/// Means for transacting assets on this chain. +pub type MultiAssetTransactor = MultiCurrencyAdapter< + // All known Assets will be processed by the following MultiCurrency implementation. + AssetManager, + // Any unknown Assets will be processed by the following UnknownAsset implementation. + UnknownTokens, + // This means that this adapter should handle any token that `AssetConvert` can convert + // using AssetManager and UnknownTokens in all other cases. + IsNativeConcrete, + // Our chain's account ID type (we can't get away without mentioning it explicitly). + AccountId, + // Convert an XCM `MultiLocation` into a local account id. + LocationToAccountId, + // The AssetId that corresponds to the native currency. + CurrencyId, + // Struct that provides functions to convert `Asset` <=> `MultiLocation`. + AssetConvert, + // In case of deposit failure, known assets will be placed in treasury. + DepositToAlternative, +>; + +/// AssetConvert +/// This type implements conversions from our `Asset` type into `MultiLocation` and vice-versa. +/// A currency locally is identified with a `Asset` variant but in the network it is identified +/// in the form of a `MultiLocation`, in this case a pair (Para-Id, Currency-Id). +pub struct AssetConvert; + +/// Convert our `Asset` type into its `MultiLocation` representation. +/// Other chains need to know how this conversion takes place in order to +/// handle it on their side. +impl Convert> for AssetConvert { + fn convert(id: CurrencyId) -> Option { + match id { + Asset::Ztg => Some(MultiLocation::new( + 1, + X2( + Junction::Parachain(ParachainInfo::parachain_id().into()), + general_key(zeitgeist::KEY), + ), + )), + Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, + _ => None, + } + } +} + +/// Convert an incoming `MultiLocation` into a `Asset` if possible. +/// Here we need to know the canonical representation of all the tokens we handle in order to +/// correctly convert their `MultiLocation` representation into our internal `Asset` type. +impl xcm_executor::traits::Convert for AssetConvert { + fn convert(location: MultiLocation) -> Result { + match location.clone() { + MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { + zeitgeist::KEY => Ok(CurrencyId::Ztg), + _ => Err(location), + }, + MultiLocation { + parents: 1, + interior: X2(Junction::Parachain(para_id), GeneralKey(key)), + } => match para_id { + id if id == u32::from(ParachainInfo::parachain_id()) => match &key[..] { + zeitgeist::KEY => Ok(CurrencyId::Ztg), + _ => Err(location), + }, + _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), + }, + _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), + } + } +} + +impl Convert> for AssetConvert { + fn convert(asset: MultiAsset) -> Option { + if let MultiAsset { id: Concrete(location), .. } = asset { + >::convert(location).ok() + } else { + None + } + } +} + +impl Convert> for AssetConvert { + fn convert(location: MultiLocation) -> Option { + >::convert(location).ok() + } +} + +pub struct AccountIdToMultiLocation; + +impl Convert for AccountIdToMultiLocation { + fn convert(account: AccountId) -> MultiLocation { + X1(AccountId32 { network: NetworkId::Any, id: account.into() }).into() + } +} + +/// No local origins on this chain are allowed to dispatch XCM sends/executions. +pub type LocalOriginToLocation = SignedToAccountId32; + +/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// when determining ownership of accounts for asset transacting and when attempting to use XCM +/// `Transact` in order to determine the dispatch Origin. +pub type LocationToAccountId = ( + // The parent (Relay-chain) origin converts to the parent `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, +); + +/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, +/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can +/// biases the kind of local `Origin` it will become. +pub type XcmOriginToTransactDispatchOrigin = ( + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when + // recognized. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognized. + SiblingParachainAsNative, + // Native signed account converter; this just converts an `AccountId32` origin into a normal + // `Origin::Signed` origin of the same 32-byte value. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, +); + +/// The means for routing XCM messages which are not for local execution into the right message +/// queues. +pub type XcmRouter = ( + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, +); + +match_types! { + pub type ParentOrParentsUnitPlurality: impl Contains = { + MultiLocation { parents: 1, interior: Junctions::Here } | + // Potentially change "Unit" to "Executive" for mainnet once we have separate runtimes + MultiLocation { parents: 1, interior: X1(Junction::Plurality { id: BodyId::Unit, .. }) } + }; +} + +#[inline] +pub(crate) fn general_key(key: &[u8]) -> Junction { + GeneralKey(Vec::from(key)) +} diff --git a/runtime/zeitgeist/src/xcm_config/fees.rs b/runtime/zeitgeist/src/xcm_config/fees.rs new file mode 100644 index 000000000..e5ba9d6ea --- /dev/null +++ b/runtime/zeitgeist/src/xcm_config/fees.rs @@ -0,0 +1,79 @@ +// Copyright 2022 Zeitgeist PM LLC. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use crate::{xcm_config::asset_registry::CustomMetadata, Balance, CurrencyId}; +use core::marker::PhantomData; +use frame_support::weights::constants::{ExtrinsicBaseWeight, WEIGHT_PER_SECOND}; +use xcm::latest::MultiLocation; +use zeitgeist_primitives::constants::BalanceFractionalDecimals; +use zrml_swaps::check_arithm_rslt::CheckArithmRslt; + +/// The fee cost per second for transferring the native token in cents. +pub fn native_per_second() -> Balance { + default_per_second(BalanceFractionalDecimals::get().into()) +} + +pub fn default_per_second(decimals: u32) -> Balance { + let base_weight = Balance::from(ExtrinsicBaseWeight::get()); + let default_per_second = (WEIGHT_PER_SECOND as u128) / base_weight; + default_per_second * base_fee(decimals) +} + +fn base_fee(decimals: u32) -> Balance { + cent(decimals).saturating_div(10) +} + +/// 1 Asset in fixed point decimal representation +pub fn dollar(decimals: u32) -> Balance { + 10u128.saturating_pow(decimals) +} + +/// 0.01 Asset in fixed point decimal presentation +pub fn cent(decimals: u32) -> Balance { + dollar(decimals).saturating_div(100) +} + +pub fn bmul(a: u128, b: u128, base: u128) -> Option { + let c0 = a.check_mul_rslt(&b).ok()?; + let c1 = c0.check_add_rslt(&base.check_div_rslt(&2).ok()?).ok()?; + c1.check_div_rslt(&base).ok() +} + +/// Our FixedConversionRateProvider, used to charge XCM-related fees for tokens registered in +/// the asset registry that were not already handled by native Trader rules. +pub struct FixedConversionRateProvider(PhantomData); + +impl< + AssetRegistry: orml_traits::asset_registry::Inspect< + AssetId = CurrencyId, + Balance = Balance, + CustomMetadata = CustomMetadata, + >, +> orml_traits::FixedConversionRateProvider for FixedConversionRateProvider +{ + fn get_fee_per_second(location: &MultiLocation) -> Option { + let metadata = AssetRegistry::metadata_by_location(&location)?; + let default_per_second = default_per_second(metadata.decimals); + + if let Some(fee_factor) = metadata.additional.xcm.fee_factor { + let base = 10u128.checked_pow(metadata.decimals.into())?; + bmul(default_per_second, fee_factor, base) + } else { + Some(default_per_second) + } + } +} diff --git a/runtime/battery-station/src/xcm_config/parachains.rs b/runtime/zeitgeist/src/xcm_config/mod.rs similarity index 55% rename from runtime/battery-station/src/xcm_config/parachains.rs rename to runtime/zeitgeist/src/xcm_config/mod.rs index 73f2012c8..363ac87b1 100644 --- a/runtime/battery-station/src/xcm_config/parachains.rs +++ b/runtime/zeitgeist/src/xcm_config/mod.rs @@ -15,15 +15,8 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -/// Listing of parachains we integrate with. -/// For each parachain, we are interested in stating their parachain ID -/// as well as any of their token key ID that we possibly support in our -/// XCM configuration. These token keys are defined in said parachain -/// and must always match the value there defined, which is expected to -/// never change once defined since they help define the canonical id -/// of said tokens in the network, which is relevant for XCM transfers. +#![cfg(feature = "parachain")] -pub mod zeitgeist { - pub const ID: u32 = 2101; - pub const ZTG_KEY: &[u8] = &[0, 1]; -} +pub mod asset_registry; +pub mod config; +pub mod fees; From 3e84785dd1a2f6a99969c5573136b03899c2070c Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Tue, 8 Nov 2022 19:30:08 +0100 Subject: [PATCH 35/59] Use ExistentialDeposit directly in integration test --- .../src/integration_tests/xcm/setup.rs | 16 ++++++++-------- .../src/integration_tests/xcm/test_net.rs | 10 +++++----- .../xcm/tests/currency_id_convert.rs | 8 ++++---- .../src/integration_tests/xcm/tests/transfers.rs | 6 +++--- runtime/battery-station/src/xcm_config/config.rs | 14 +++++++------- runtime/zeitgeist/src/lib.rs | 2 ++ 6 files changed, 29 insertions(+), 27 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs index 19697f0e3..a2eb4f0bd 100644 --- a/runtime/battery-station/src/integration_tests/xcm/setup.rs +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -19,9 +19,9 @@ use crate::{ xcm_config::{ asset_registry::CustomMetadata, - config::{general_key, zeitgeist}, + config::{general_key, battery_station}, }, - AccountId, AssetRegistry, Balance, CurrencyId, Origin, Runtime, System, + AccountId, AssetRegistry, Balance, CurrencyId, Origin, Runtime, System, ExistentialDeposit, }; use frame_support::{assert_ok, traits::GenesisBuild}; use orml_traits::asset_registry::AssetMetadata; @@ -38,7 +38,7 @@ pub(super) struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { - Self { balances: vec![], parachain_id: zeitgeist::ID } + Self { balances: vec![], parachain_id: battery_station::ID } } } @@ -112,12 +112,12 @@ pub const FOREIGN_SIBLING_ID: Asset = CurrencyId::ForeignAsset(2); // Multilocations that are used to represent tokens from other chains #[inline] pub(super) fn foreign_ztg_multilocation() -> MultiLocation { - MultiLocation::new(1, X2(Parachain(zeitgeist::ID), general_key(zeitgeist::KEY))) + MultiLocation::new(1, X2(Parachain(battery_station::ID), general_key(battery_station::KEY))) } #[inline] pub(super) fn foreign_sibling_multilocation() -> MultiLocation { - MultiLocation::new(1, X2(Parachain(PARA_ID_SIBLING), general_key(zeitgeist::KEY))) + MultiLocation::new(1, X2(Parachain(PARA_ID_SIBLING), general_key(battery_station::KEY))) } #[inline] @@ -131,7 +131,7 @@ pub(super) fn register_foreign_ztg(additional_meta: Option) { decimals: 10, name: "Zeitgeist".into(), symbol: "ZTG".into(), - existential_deposit: 50_000_000, // 0.005 + existential_deposit: ExistentialDeposit::get(), location: Some(VersionedMultiLocation::V1(foreign_ztg_multilocation())), additional: additional_meta.unwrap_or_default(), }; @@ -145,7 +145,7 @@ pub(super) fn register_foreign_sibling(additional_meta: Option) decimals: 10, name: "Sibling".into(), symbol: "SBL".into(), - existential_deposit: 50_000_000, // 0.005 + existential_deposit: ExistentialDeposit::get(), location: Some(VersionedMultiLocation::V1(foreign_sibling_multilocation())), additional: additional_meta.unwrap_or_default(), }; @@ -199,7 +199,7 @@ pub(super) fn sibling_account() -> AccountId { #[inline] pub(super) fn zeitgeist_account() -> AccountId { - parachain_account(zeitgeist::ID) + parachain_account(battery_station::ID) } #[inline] diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index 94abd1225..2ada2c237 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -17,7 +17,7 @@ use crate::{ parameters::ZeitgeistTreasuryAccount, - xcm_config::{config::zeitgeist}, + xcm_config::{config::battery_station}, AccountId, CurrencyId, DmpQueue, Origin, Runtime, XcmpQueue, }; use cumulus_primitives_core::ParaId; @@ -43,7 +43,7 @@ decl_test_parachain! { Origin = Origin, XcmpMessageHandler = XcmpQueue, DmpMessageHandler = DmpQueue, - new_ext = para_ext(zeitgeist::ID), + new_ext = para_ext(battery_station::ID), } } @@ -64,8 +64,8 @@ decl_test_network! { // N.B: Ideally, we could use the defined para id constants but doing so // fails with: "error: arbitrary expressions aren't allowed in patterns" - // Be sure to use `xcm_config::config::zeitgeist::ID` - (2101, Zeitgeist), + // Be sure to use `xcm_config::config::battery_station::ID` + (2050, Zeitgeist), // Be sure to use `PARA_ID_SIBLING` (3000, Sibling), ], @@ -80,7 +80,7 @@ pub(super) fn relay_ext() -> sp_io::TestExternalities { pallet_balances::GenesisConfig:: { balances: vec![ (AccountId::from(ALICE), ksm(2002)), - (ParaId::from(zeitgeist::ID).into_account(), ztg(7)), + (ParaId::from(battery_station::ID).into_account(), ztg(7)), (ParaId::from(PARA_ID_SIBLING).into_account(), sibling(7)), ], } diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs index ced783a67..963d9448b 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -27,7 +27,7 @@ use crate::{ test_net::{Zeitgeist}, }, xcm_config::{ - config::{general_key, zeitgeist, AssetConvert}, + config::{general_key, battery_station, AssetConvert}, }, CurrencyId }; @@ -42,10 +42,10 @@ use xcm_executor::traits::Convert as C1; #[test] fn convert_native() { - assert_eq!(zeitgeist::KEY.to_vec(), vec![0, 1]); + assert_eq!(battery_station::KEY.to_vec(), vec![0, 1]); // The way Ztg is represented relative within the Zeitgeist runtime - let ztg_location_inner: MultiLocation = MultiLocation::new(0, X1(general_key(zeitgeist::KEY))); + let ztg_location_inner: MultiLocation = MultiLocation::new(0, X1(general_key(battery_station::KEY))); assert_eq!(>::convert(ztg_location_inner), Ok(CurrencyId::Ztg)); @@ -111,7 +111,7 @@ fn convert_any_registered_sibling_multilocation() { #[test] fn convert_unkown_multilocation() { let unknown_location: MultiLocation = - MultiLocation::new(1, X2(Parachain(zeitgeist::ID), general_key(&[42]))); + MultiLocation::new(1, X2(Parachain(battery_station::ID), general_key(&[42]))); Zeitgeist::execute_with(|| { assert!(>::convert(unknown_location.clone()).is_err()); diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index 993c04370..a02546dce 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -28,7 +28,7 @@ use crate::{ }, xcm_config::{ asset_registry::{CustomMetadata, XcmMetadata}, - config::{zeitgeist,}, + config::battery_station, fees::default_per_second, }, AssetRegistry, Balance, Balances, CurrencyId, Origin, Tokens, XTokens, @@ -136,7 +136,7 @@ fn transfer_ztg_sibling_to_zeitgeist() { MultiLocation::new( 1, X2( - Parachain(zeitgeist::ID), + Parachain(battery_station::ID), Junction::AccountId32 { network: NetworkId::Any, id: ALICE.into() } ) ) @@ -184,7 +184,7 @@ fn transfer_ksm_from_relay_chain() { KusamaNet::execute_with(|| { assert_ok!(kusama_runtime::XcmPallet::reserve_transfer_assets( kusama_runtime::Origin::signed(ALICE.into()), - Box::new(Parachain(zeitgeist::ID).into().into()), + Box::new(Parachain(battery_station::ID).into().into()), Box::new(Junction::AccountId32 { network: NetworkId::Any, id: BOB }.into().into()), Box::new((Here, transfer_amount).into()), 0 diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 34be2ff3a..743c99a6a 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -49,9 +49,9 @@ use xcm_builder::{ use xcm_executor::Config; use zeitgeist_primitives::types::Asset; -pub mod zeitgeist { +pub mod battery_station { #[cfg(test)] - pub const ID: u32 = 2101; + pub const ID: u32 = 2050; pub const KEY: &[u8] = &[0, 1]; } @@ -145,7 +145,7 @@ parameter_types! { pub ZtgPerSecondCanonical: (AssetId, u128) = ( MultiLocation::new( 0, - X1(general_key(zeitgeist::KEY)), + X1(general_key(battery_station::KEY)), ).into(), native_per_second(), ); @@ -153,7 +153,7 @@ parameter_types! { pub ZtgPerSecond: (AssetId, u128) = ( MultiLocation::new( 1, - X2(Junction::Parachain(ParachainInfo::parachain_id().into()), general_key(zeitgeist::KEY)), + X2(Junction::Parachain(ParachainInfo::parachain_id().into()), general_key(battery_station::KEY)), ).into(), native_per_second(), ); @@ -196,7 +196,7 @@ impl Convert> for AssetConvert { 1, X2( Junction::Parachain(ParachainInfo::parachain_id().into()), - general_key(zeitgeist::KEY), + general_key(battery_station::KEY), ), )), Asset::ForeignAsset(_) => AssetRegistry::multilocation(&id).ok()?, @@ -212,7 +212,7 @@ impl xcm_executor::traits::Convert for AssetConvert { fn convert(location: MultiLocation) -> Result { match location.clone() { MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { - zeitgeist::KEY => Ok(CurrencyId::Ztg), + battery_station::KEY => Ok(CurrencyId::Ztg), _ => Err(location), }, MultiLocation { @@ -220,7 +220,7 @@ impl xcm_executor::traits::Convert for AssetConvert { interior: X2(Junction::Parachain(para_id), GeneralKey(key)), } => match para_id { id if id == u32::from(ParachainInfo::parachain_id()) => match &key[..] { - zeitgeist::KEY => Ok(CurrencyId::Ztg), + battery_station::KEY => Ok(CurrencyId::Ztg), _ => Err(location), }, _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), diff --git a/runtime/zeitgeist/src/lib.rs b/runtime/zeitgeist/src/lib.rs index fb17574af..35f0dac6a 100644 --- a/runtime/zeitgeist/src/lib.rs +++ b/runtime/zeitgeist/src/lib.rs @@ -77,6 +77,8 @@ use sp_runtime::{ use nimbus_primitives::{CanAuthor, NimbusId}; use sp_version::RuntimeVersion; +#[cfg(test)] +pub mod integration_tests; #[cfg(feature = "parachain")] pub mod parachain_params; pub mod parameters; From 857cf743e52130f5252fc939f42298363e5188a9 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Tue, 8 Nov 2022 19:38:38 +0100 Subject: [PATCH 36/59] Add integration tests to Zeitgeist runtime --- Cargo.lock | 1 + runtime/zeitgeist/Cargo.toml | 1 + .../zeitgeist/src/integration_tests/mod.rs | 19 + .../src/integration_tests/xcm/mod.rs | 21 ++ .../src/integration_tests/xcm/setup.rs | 210 +++++++++++ .../src/integration_tests/xcm/test_net.rs | 154 ++++++++ .../xcm/tests/currency_id_convert.rs | 126 +++++++ .../src/integration_tests/xcm/tests/mod.rs | 20 ++ .../integration_tests/xcm/tests/transfers.rs | 340 ++++++++++++++++++ 9 files changed, 892 insertions(+) create mode 100644 runtime/zeitgeist/src/integration_tests/mod.rs create mode 100644 runtime/zeitgeist/src/integration_tests/xcm/mod.rs create mode 100644 runtime/zeitgeist/src/integration_tests/xcm/setup.rs create mode 100644 runtime/zeitgeist/src/integration_tests/xcm/test_net.rs create mode 100644 runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs create mode 100644 runtime/zeitgeist/src/integration_tests/xcm/tests/mod.rs create mode 100644 runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs diff --git a/Cargo.lock b/Cargo.lock index 40ae0ea88..4492516b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12810,6 +12810,7 @@ dependencies = [ "substrate-wasm-builder", "xcm", "xcm-builder", + "xcm-emulator", "xcm-executor", "zeitgeist-primitives", "zrml-authorized", diff --git a/runtime/zeitgeist/Cargo.toml b/runtime/zeitgeist/Cargo.toml index a5fcab724..4b790e733 100644 --- a/runtime/zeitgeist/Cargo.toml +++ b/runtime/zeitgeist/Cargo.toml @@ -111,6 +111,7 @@ zrml-swaps-runtime-api = { default-features = false, path = "../../zrml/swaps/ru [dev-dependencies] sp-io = { branch = "moonbeam-polkadot-v0.9.19", git = "https://github.com/purestake/substrate" } +xcm-emulator = { rev = "6c358483d8e119cd3b631ebb14d3b0cf0041d94e", git = "https://github.com/shaunxw/xcm-simulator" } [features] default = ["std"] diff --git a/runtime/zeitgeist/src/integration_tests/mod.rs b/runtime/zeitgeist/src/integration_tests/mod.rs new file mode 100644 index 000000000..64f89683b --- /dev/null +++ b/runtime/zeitgeist/src/integration_tests/mod.rs @@ -0,0 +1,19 @@ +// Copyright 2022 Forecasting Technologies LTD. +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +#![cfg(test)] + +mod xcm; diff --git a/runtime/zeitgeist/src/integration_tests/xcm/mod.rs b/runtime/zeitgeist/src/integration_tests/xcm/mod.rs new file mode 100644 index 000000000..d2226363f --- /dev/null +++ b/runtime/zeitgeist/src/integration_tests/xcm/mod.rs @@ -0,0 +1,21 @@ +// Copyright 2022 Forecasting Technologies LTD. +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +#![cfg(all(feature = "parachain", test))] + +mod setup; +mod test_net; +mod tests; diff --git a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs new file mode 100644 index 000000000..d3565a9bd --- /dev/null +++ b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs @@ -0,0 +1,210 @@ +// Copyright 2021 Centrifuge Foundation (centrifuge.io). +// Copyright 2022 Forecasting Technologies LTD. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use crate::{ + xcm_config::{ + asset_registry::CustomMetadata, + config::{general_key, zeitgeist}, + }, + AccountId, AssetRegistry, Balance, CurrencyId, Origin, Runtime, System, ExistentialDeposit, +}; +use frame_support::{assert_ok, traits::GenesisBuild}; +use orml_traits::asset_registry::AssetMetadata; +use xcm::{ + latest::{Junction::Parachain, Junctions::X2, MultiLocation}, + VersionedMultiLocation, +}; +use zeitgeist_primitives::types::Asset; + +pub(super) struct ExtBuilder { + balances: Vec<(AccountId, CurrencyId, Balance)>, + parachain_id: u32, +} + +impl Default for ExtBuilder { + fn default() -> Self { + Self { balances: vec![], parachain_id: zeitgeist::ID } + } +} + +impl ExtBuilder { + pub fn balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { + self.balances = balances; + self + } + + pub fn parachain_id(mut self, parachain_id: u32) -> Self { + self.parachain_id = parachain_id; + self + } + + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let native_currency_id = CurrencyId::Ztg; + pallet_balances::GenesisConfig:: { + balances: self + .balances + .clone() + .into_iter() + .filter(|(_, currency_id, _)| *currency_id == native_currency_id) + .map(|(account_id, _, initial_balance)| (account_id, initial_balance)) + .collect::>(), + } + .assimilate_storage(&mut t) + .unwrap(); + + orml_tokens::GenesisConfig:: { + balances: self + .balances + .into_iter() + .filter(|(_, currency_id, _)| *currency_id != native_currency_id) + .collect::>(), + } + .assimilate_storage(&mut t) + .unwrap(); + + >::assimilate_storage( + ¶chain_info::GenesisConfig { parachain_id: self.parachain_id.into() }, + &mut t, + ) + .unwrap(); + + >::assimilate_storage( + &pallet_xcm::GenesisConfig { safe_xcm_version: Some(2) }, + &mut t, + ) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext + } +} + +/// Accounts +pub const ALICE: [u8; 32] = [4u8; 32]; +pub const BOB: [u8; 32] = [5u8; 32]; + +/// A PARA ID used for a sibling parachain. +/// It must be one that doesn't collide with any other in use. +pub const PARA_ID_SIBLING: u32 = 3000; + +/// IDs that are used to represent tokens from other chains +pub const FOREIGN_ZTG_ID: Asset = CurrencyId::ForeignAsset(0); +pub const FOREIGN_PARENT_ID: Asset = CurrencyId::ForeignAsset(1); +pub const FOREIGN_SIBLING_ID: Asset = CurrencyId::ForeignAsset(2); + +// Multilocations that are used to represent tokens from other chains +#[inline] +pub(super) fn foreign_ztg_multilocation() -> MultiLocation { + MultiLocation::new(1, X2(Parachain(zeitgeist::ID), general_key(zeitgeist::KEY))) +} + +#[inline] +pub(super) fn foreign_sibling_multilocation() -> MultiLocation { + MultiLocation::new(1, X2(Parachain(PARA_ID_SIBLING), general_key(zeitgeist::KEY))) +} + +#[inline] +pub(super) fn foreign_parent_multilocation() -> MultiLocation { + MultiLocation::parent() +} + +pub(super) fn register_foreign_ztg(additional_meta: Option) { + // Register ZTG as foreign asset. + let meta: AssetMetadata = AssetMetadata { + decimals: 10, + name: "Zeitgeist".into(), + symbol: "ZTG".into(), + existential_deposit: ExistentialDeposit::get(), + location: Some(VersionedMultiLocation::V1(foreign_ztg_multilocation())), + additional: additional_meta.unwrap_or_default(), + }; + + assert_ok!(AssetRegistry::register_asset(Origin::root(), meta, Some(FOREIGN_ZTG_ID))); +} + +pub(super) fn register_foreign_sibling(additional_meta: Option) { + // Register native Sibling token as foreign asset. + let meta: AssetMetadata = AssetMetadata { + decimals: 10, + name: "Sibling".into(), + symbol: "SBL".into(), + existential_deposit: ExistentialDeposit::get(), + location: Some(VersionedMultiLocation::V1(foreign_sibling_multilocation())), + additional: additional_meta.unwrap_or_default(), + }; + + assert_ok!(AssetRegistry::register_asset(Origin::root(), meta, Some(FOREIGN_SIBLING_ID))); +} + +pub(super) fn register_foreign_parent(additional_meta: Option) { + // Register KSM as foreign asset in the sibling parachain + let meta: AssetMetadata = AssetMetadata { + decimals: 12, + name: "Kusama".into(), + symbol: "KSM".into(), + existential_deposit: 10_000_000_000, // 0.01 + location: Some(VersionedMultiLocation::V1(foreign_parent_multilocation())), + additional: additional_meta.unwrap_or_default(), + }; + + assert_ok!(AssetRegistry::register_asset(Origin::root(), meta, Some(FOREIGN_PARENT_ID))); +} + +#[inline] +pub(super) fn ztg(amount: Balance) -> Balance { + amount * dollar(10) +} + +#[inline] +pub(super) fn sibling(amount: Balance) -> Balance { + foreign(amount, 10) +} + +#[inline] +pub(super) fn ksm(amount: Balance) -> Balance { + foreign(amount, 12) +} + +#[inline] +pub(super) fn foreign(amount: Balance, decimals: u32) -> Balance { + amount * dollar(decimals) +} + +#[inline] +pub(super) fn dollar(decimals: u32) -> Balance { + 10u128.saturating_pow(decimals.into()) +} + +#[inline] +pub(super) fn sibling_account() -> AccountId { + parachain_account(PARA_ID_SIBLING.into()) +} + +#[inline] +pub(super) fn zeitgeist_account() -> AccountId { + parachain_account(zeitgeist::ID) +} + +#[inline] +fn parachain_account(id: u32) -> AccountId { + use sp_runtime::traits::AccountIdConversion; + + polkadot_parachain::primitives::Sibling::from(id).into_account() +} diff --git a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs new file mode 100644 index 000000000..94abd1225 --- /dev/null +++ b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs @@ -0,0 +1,154 @@ +// Copyright 2021-2022 Centrifuge GmbH (centrifuge.io). +// Copyright 2022 Forecasting Technologies LTD. +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use crate::{ + parameters::ZeitgeistTreasuryAccount, + xcm_config::{config::zeitgeist}, + AccountId, CurrencyId, DmpQueue, Origin, Runtime, XcmpQueue, +}; +use cumulus_primitives_core::ParaId; +use frame_support::{traits::GenesisBuild, weights::Weight}; +use polkadot_primitives::v2::{BlockNumber, MAX_CODE_SIZE, MAX_POV_SIZE}; +use polkadot_runtime_parachains::configuration::HostConfiguration; +use sp_runtime::traits::AccountIdConversion; +use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; + +use super::setup::{ksm, sibling, ztg, ExtBuilder, ALICE, FOREIGN_PARENT_ID, PARA_ID_SIBLING}; + +decl_test_relay_chain! { + pub struct KusamaNet { + Runtime = kusama_runtime::Runtime, + XcmConfig = kusama_runtime::xcm_config::XcmConfig, + new_ext = relay_ext(), + } +} + +decl_test_parachain! { + pub struct Zeitgeist { + Runtime = Runtime, + Origin = Origin, + XcmpMessageHandler = XcmpQueue, + DmpMessageHandler = DmpQueue, + new_ext = para_ext(zeitgeist::ID), + } +} + +decl_test_parachain! { + pub struct Sibling { + Runtime = Runtime, + Origin = Origin, + XcmpMessageHandler = XcmpQueue, + DmpMessageHandler = DmpQueue, + new_ext = para_ext(PARA_ID_SIBLING), + } +} + +decl_test_network! { + pub struct TestNet { + relay_chain = KusamaNet, + parachains = vec![ + // N.B: Ideally, we could use the defined para id constants but doing so + // fails with: "error: arbitrary expressions aren't allowed in patterns" + + // Be sure to use `xcm_config::config::zeitgeist::ID` + (2101, Zeitgeist), + // Be sure to use `PARA_ID_SIBLING` + (3000, Sibling), + ], + } +} + +pub(super) fn relay_ext() -> sp_io::TestExternalities { + use kusama_runtime::{Runtime, System}; + + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![ + (AccountId::from(ALICE), ksm(2002)), + (ParaId::from(zeitgeist::ID).into_account(), ztg(7)), + (ParaId::from(PARA_ID_SIBLING).into_account(), sibling(7)), + ], + } + .assimilate_storage(&mut t) + .unwrap(); + + polkadot_runtime_parachains::configuration::GenesisConfig:: { + config: default_parachains_host_configuration(), + } + .assimilate_storage(&mut t) + .unwrap(); + + >::assimilate_storage( + &pallet_xcm::GenesisConfig { safe_xcm_version: Some(2) }, + &mut t, + ) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} + +pub(super) fn para_ext(parachain_id: u32) -> sp_io::TestExternalities { + ExtBuilder::default() + .balances(vec![ + (AccountId::from(ALICE), CurrencyId::Ztg, ztg(10)), + (AccountId::from(ALICE), FOREIGN_PARENT_ID, ksm(10)), + (ZeitgeistTreasuryAccount::get(), FOREIGN_PARENT_ID, ksm(1)), + ]) + .parachain_id(parachain_id) + .build() +} + +fn default_parachains_host_configuration() -> HostConfiguration { + HostConfiguration { + minimum_validation_upgrade_delay: 5, + validation_upgrade_cooldown: 5u32, + validation_upgrade_delay: 5, + code_retention_period: 1200, + max_code_size: MAX_CODE_SIZE, + max_pov_size: MAX_POV_SIZE, + max_head_data_size: 32 * 1024, + group_rotation_frequency: 20, + chain_availability_period: 4, + thread_availability_period: 4, + max_upward_queue_count: 8, + max_upward_queue_size: 1024 * 1024, + max_downward_message_size: 1024, + ump_service_total_weight: Weight::from(4 * 1_000_000_000u32), + max_upward_message_size: 50 * 1024, + max_upward_message_num_per_candidate: 5, + hrmp_sender_deposit: 0, + hrmp_recipient_deposit: 0, + hrmp_channel_max_capacity: 8, + hrmp_channel_max_total_size: 8 * 1024, + hrmp_max_parachain_inbound_channels: 4, + hrmp_max_parathread_inbound_channels: 4, + hrmp_channel_max_message_size: 1024 * 1024, + hrmp_max_parachain_outbound_channels: 4, + hrmp_max_parathread_outbound_channels: 4, + hrmp_max_message_num_per_candidate: 5, + dispute_period: 6, + no_show_slots: 2, + n_delay_tranches: 25, + needed_approvals: 2, + relay_vrf_modulo_samples: 2, + zeroth_delay_tranche_width: 0, + ..Default::default() + } +} diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs new file mode 100644 index 000000000..ced783a67 --- /dev/null +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -0,0 +1,126 @@ +// Copyright 2021 Centrifuge Foundation (centrifuge.io). +// Copyright 2022 Forecasting Technologies LTD. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use crate::{ + integration_tests::xcm::{ + setup::{ + foreign_parent_multilocation, foreign_sibling_multilocation, + foreign_ztg_multilocation, register_foreign_parent, register_foreign_sibling, + FOREIGN_PARENT_ID, + FOREIGN_SIBLING_ID, + }, + test_net::{Zeitgeist}, + }, + xcm_config::{ + config::{general_key, zeitgeist, AssetConvert}, + }, + CurrencyId +}; + +use frame_support::{assert_err}; +use sp_runtime::traits::Convert as C2; +use xcm::{ + latest::{Junction::*, Junctions::*, MultiLocation}, +}; +use xcm_emulator::TestExt; +use xcm_executor::traits::Convert as C1; + +#[test] +fn convert_native() { + assert_eq!(zeitgeist::KEY.to_vec(), vec![0, 1]); + + // The way Ztg is represented relative within the Zeitgeist runtime + let ztg_location_inner: MultiLocation = MultiLocation::new(0, X1(general_key(zeitgeist::KEY))); + + assert_eq!(>::convert(ztg_location_inner), Ok(CurrencyId::Ztg)); + + // The canonical way Ztg is represented out in the wild + Zeitgeist::execute_with(|| { + assert_eq!( + >::convert(CurrencyId::Ztg), + Some(foreign_ztg_multilocation()) + ) + }); +} + +#[test] +fn convert_any_registered_parent_multilocation() { + Zeitgeist::execute_with(|| { + assert_err!( + >::convert(foreign_parent_multilocation()), + foreign_parent_multilocation() + ); + + assert_eq!(>::convert(FOREIGN_PARENT_ID), None,); + + // Register parent as foreign asset in the Zeitgeist parachain + register_foreign_parent(None); + + assert_eq!( + >::convert(foreign_parent_multilocation()), + Ok(FOREIGN_PARENT_ID), + ); + + assert_eq!( + >::convert(FOREIGN_PARENT_ID), + Some(foreign_parent_multilocation()) + ); + }); +} + +#[test] +fn convert_any_registered_sibling_multilocation() { + Zeitgeist::execute_with(|| { + assert_err!( + >::convert(foreign_sibling_multilocation()), + foreign_sibling_multilocation() + ); + + assert_eq!(>::convert(FOREIGN_SIBLING_ID), None,); + + // Register parent as foreign asset in the Zeitgeist parachain + register_foreign_sibling(None); + + assert_eq!( + >::convert(foreign_sibling_multilocation()), + Ok(FOREIGN_SIBLING_ID), + ); + + assert_eq!( + >::convert(FOREIGN_SIBLING_ID), + Some(foreign_sibling_multilocation()) + ); + }); +} + +#[test] +fn convert_unkown_multilocation() { + let unknown_location: MultiLocation = + MultiLocation::new(1, X2(Parachain(zeitgeist::ID), general_key(&[42]))); + + Zeitgeist::execute_with(|| { + assert!(>::convert(unknown_location.clone()).is_err()); + }); +} + +#[test] +fn convert_unsupported_currency() { + Zeitgeist::execute_with(|| { + assert_eq!(>::convert(CurrencyId::CombinatorialOutcome), None) + }); +} diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/mod.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/mod.rs new file mode 100644 index 000000000..44d31098b --- /dev/null +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/mod.rs @@ -0,0 +1,20 @@ +// Copyright 2022 Forecasting Technologies LTD. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + + +mod currency_id_convert; +mod transfers; diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs new file mode 100644 index 000000000..993c04370 --- /dev/null +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs @@ -0,0 +1,340 @@ +// Copyright 2021 Centrifuge Foundation (centrifuge.io). +// Copyright 2022 Forecasting Technologies LTD. +// +// This file is part of Zeitgeist. +// +// Zeitgeist is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the +// Free Software Foundation, either version 3 of the License, or (at +// your option) any later version. +// +// Zeitgeist is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Zeitgeist. If not, see . + +use crate::{ + integration_tests::xcm::{ + setup::{ + ksm, + register_foreign_parent, register_foreign_ztg, sibling_account, + zeitgeist_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, + FOREIGN_ZTG_ID, PARA_ID_SIBLING, + }, + test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, + }, + xcm_config::{ + asset_registry::{CustomMetadata, XcmMetadata}, + config::{zeitgeist,}, + fees::default_per_second, + }, + AssetRegistry, Balance, Balances, CurrencyId, Origin, Tokens, XTokens, + ZeitgeistTreasuryAccount, +}; + +use frame_support::{assert_ok}; +use orml_traits::{MultiCurrency}; +use xcm::{ + latest::{Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, +}; +use xcm_emulator::TestExt; +use zeitgeist_primitives::constants::BalanceFractionalDecimals; + +#[test] +fn transfer_ztg_to_sibling() { + TestNet::reset(); + + let alice_initial_balance = ztg(10); + let transfer_amount = ztg(5); + let mut treasury_initial_balance = 0; + + Sibling::execute_with(|| { + treasury_initial_balance = + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), 0); + register_foreign_ztg(None); + }); + + Zeitgeist::execute_with(|| { + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); + assert_eq!(Balances::free_balance(&sibling_account()), 0); + assert_ok!(XTokens::transfer( + Origin::signed(ALICE.into()), + CurrencyId::Ztg, + transfer_amount, + Box::new( + MultiLocation::new( + 1, + X2( + Parachain(PARA_ID_SIBLING), + Junction::AccountId32 { network: NetworkId::Any, id: BOB.into() } + ) + ) + .into() + ), + 4_000_000_000, + )); + + // Confirm that Alice's balance is initial_balance - amount_transferred + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance - transfer_amount); + + // Verify that the amount transferred is now part of the sibling account here + assert_eq!(Balances::free_balance(&sibling_account()), transfer_amount); + }); + + Sibling::execute_with(|| { + let current_balance = Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()); + + // Verify that BOB now has (amount transferred - fee) + assert_eq!(current_balance, transfer_amount - ztg_fee()); + + // Sanity check for the actual amount BOB ends up with + assert_eq!(current_balance, 49_936_000_000); + + // Verify that fees (of foreign currency) have been put into treasury + assert_eq!( + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()), + treasury_initial_balance + ztg_fee() + ) + }); +} + +#[test] +fn transfer_ztg_sibling_to_zeitgeist() { + TestNet::reset(); + + // In order to be able to transfer ZTG from Sibling to Zeitgeist, we need to first send + // ZTG from Zeitgeist to Sibling, or else it fails since it'd be like Sibling had minted + // ZTG on their side. + transfer_ztg_to_sibling(); + + let alice_initial_balance = ztg(5); + let bob_initial_balance = ztg(5) - ztg_fee(); + let mut treasury_initial_balance = 0; + let sibling_sovereign_initial_balance = ztg(5); + let transfer_amount = ztg(1); + // Note: This asset was registered in `transfer_ztg_to_sibling` + + Zeitgeist::execute_with(|| { + treasury_initial_balance = Balances::free_balance(ZeitgeistTreasuryAccount::get()); + + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); + assert_eq!(Balances::free_balance(&sibling_account()), sibling_sovereign_initial_balance); + }); + + Sibling::execute_with(|| { + assert_eq!(Balances::free_balance(&zeitgeist_account()), 0); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), bob_initial_balance); + assert_ok!(XTokens::transfer( + Origin::signed(BOB.into()), + FOREIGN_ZTG_ID, + transfer_amount, + Box::new( + MultiLocation::new( + 1, + X2( + Parachain(zeitgeist::ID), + Junction::AccountId32 { network: NetworkId::Any, id: ALICE.into() } + ) + ) + .into() + ), + 4_000_000_000, + )); + + // Confirm that Bobs's balance is initial balance - amount transferred + assert_eq!( + Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), + bob_initial_balance - transfer_amount + ); + }); + + Zeitgeist::execute_with(|| { + // Verify that ALICE now has initial balance + amount transferred - fee + assert_eq!( + Balances::free_balance(&ALICE.into()), + alice_initial_balance + transfer_amount - ztg_fee(), + ); + + // Verify that the reserve has been adjusted properly + assert_eq!( + Balances::free_balance(&sibling_account()), + sibling_sovereign_initial_balance - transfer_amount + ); + + // Verify that fees (of native currency) have been put into treasury + assert_eq!( + Balances::free_balance(ZeitgeistTreasuryAccount::get()), + treasury_initial_balance + ztg_fee() + ) + }); +} + +#[test] +fn transfer_ksm_from_relay_chain() { + let transfer_amount: Balance = ksm(1); + + Zeitgeist::execute_with(|| { + register_foreign_parent(None); + }); + + KusamaNet::execute_with(|| { + assert_ok!(kusama_runtime::XcmPallet::reserve_transfer_assets( + kusama_runtime::Origin::signed(ALICE.into()), + Box::new(Parachain(zeitgeist::ID).into().into()), + Box::new(Junction::AccountId32 { network: NetworkId::Any, id: BOB }.into().into()), + Box::new((Here, transfer_amount).into()), + 0 + )); + }); + + Zeitgeist::execute_with(|| { + assert_eq!( + Tokens::free_balance(FOREIGN_PARENT_ID, &BOB.into()), + transfer_amount - ksm_fee() + ); + }); +} + +#[test] +fn transfer_ksm_to_relay_chain() { + let transfer_amount: Balance = ksm(1); + transfer_ksm_from_relay_chain(); + + Zeitgeist::execute_with(|| { + let initial_balance = Tokens::free_balance(FOREIGN_PARENT_ID, &ALICE.into()); + assert!(initial_balance >= transfer_amount); + + assert_ok!(XTokens::transfer( + Origin::signed(ALICE.into()), + FOREIGN_PARENT_ID, + transfer_amount, + Box::new( + MultiLocation::new( + 1, + X1(Junction::AccountId32 { id: BOB, network: NetworkId::Any }) + ) + .into() + ), + 4_000_000_000 + )); + + assert_eq!( + Tokens::free_balance(FOREIGN_PARENT_ID, &ALICE.into()), + initial_balance - transfer_amount + ) + }); + + KusamaNet::execute_with(|| { + assert_eq!(kusama_runtime::Balances::free_balance(&BOB.into()), 999834059328); + }); +} + +#[test] +fn transfer_ztg_to_sibling_with_custom_fee() { + TestNet::reset(); + + let alice_initial_balance = ztg(10); + // 10x fee factor, so ZTG has 10x the worth of sibling currency. + let fee_factor = 100_000_000_000; + let transfer_amount = ztg(5); + let mut treasury_initial_balance = 0; + + Sibling::execute_with(|| { + treasury_initial_balance = + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()); + assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), 0); + + register_foreign_ztg(None); + let custom_metadata = CustomMetadata { + xcm: XcmMetadata { fee_factor: Some(fee_factor) }, + ..Default::default() + }; + assert_ok!(AssetRegistry::do_update_asset( + FOREIGN_ZTG_ID, + None, + None, + None, + None, + None, + Some(custom_metadata) + )); + }); + + Zeitgeist::execute_with(|| { + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); + assert_eq!(Balances::free_balance(&sibling_account()), 0); + assert_ok!(XTokens::transfer( + Origin::signed(ALICE.into()), + CurrencyId::Ztg, + transfer_amount, + Box::new( + MultiLocation::new( + 1, + X2( + Parachain(PARA_ID_SIBLING), + Junction::AccountId32 { network: NetworkId::Any, id: BOB.into() } + ) + ) + .into() + ), + 4_000_000_000, + )); + + // Confirm that Alice's balance is initial_balance - amount_transferred + assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance - transfer_amount); + + // Verify that the amount transferred is now part of the sibling account here + assert_eq!(Balances::free_balance(&sibling_account()), transfer_amount); + }); + + Sibling::execute_with(|| { + let current_balance = Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()); + let custom_fee = calc_fee(default_per_second(10) * 10); + + // Verify that BOB now has (amount transferred - fee) + assert_eq!(current_balance, transfer_amount - custom_fee); + + // Sanity check for the actual amount BOB ends up with + assert_eq!(current_balance, 49_360_000_000); + + // Verify that fees (of foreign currency) have been put into treasury + assert_eq!( + Tokens::free_balance(FOREIGN_ZTG_ID, &ZeitgeistTreasuryAccount::get()), + treasury_initial_balance + custom_fee + ) + }); +} + +#[test] +fn test_total_fee() { + assert_eq!(ztg_fee(), 64000000); + assert_eq!(ksm_fee(), 6400000000); +} + +#[inline] +fn ztg_fee() -> Balance { + fee(BalanceFractionalDecimals::get().into()) +} + +#[inline] +fn fee(decimals: u32) -> Balance { + calc_fee(default_per_second(decimals)) +} + +// The fee associated with transferring KSM tokens +#[inline] +fn ksm_fee() -> Balance { + fee(12) +} + +#[inline] +fn calc_fee(fee_per_second: Balance) -> Balance { + // We divide the fee to align its unit and multiply by 8 as that seems to be the unit of + // time the tests take. + // NOTE: it is possible that in different machines this value may differ. We shall see. + fee_per_second / 10_000 * 8 +} From d6030ac52d3a3cdab22735e482755ad043f41fdb Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Tue, 8 Nov 2022 19:51:30 +0100 Subject: [PATCH 37/59] Allow only Kusama as parent on Zeitgeist + Cleanup --- Cargo.toml | 2 +- primitives/Cargo.toml | 2 +- primitives/src/constants.rs | 3 +-- primitives/src/constants/mock.rs | 2 +- runtime/battery-station/Cargo.toml | 6 ++--- .../src/integration_tests/xcm/setup.rs | 4 ++-- .../src/integration_tests/xcm/test_net.rs | 5 ++-- .../xcm/tests/currency_id_convert.rs | 24 ++++++++----------- .../src/integration_tests/xcm/tests/mod.rs | 1 - .../integration_tests/xcm/tests/transfers.rs | 14 ++++------- .../battery-station/src/parachain_params.rs | 1 - runtime/zeitgeist/Cargo.toml | 6 ++--- .../src/integration_tests/xcm/setup.rs | 2 +- .../src/integration_tests/xcm/test_net.rs | 5 ++-- .../xcm/tests/currency_id_convert.rs | 21 +++++++--------- .../src/integration_tests/xcm/tests/mod.rs | 1 - .../integration_tests/xcm/tests/transfers.rs | 16 +++++-------- runtime/zeitgeist/src/parachain_params.rs | 11 +++------ runtime/zeitgeist/src/xcm_config/config.rs | 12 ++-------- 19 files changed, 51 insertions(+), 87 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 1f159b367..21740f461 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,4 +50,4 @@ pallet-author-mapping = { git = "https://github.com/zeitgeistpm/moonbeam", branc parachain-staking = { git = "https://github.com/zeitgeistpm/moonbeam", branch = "downgrade-staking-and-mapping" } [patch."https://github.com/shaunxw/xcm-simulator"] -xcm-emulator = { git = "https://github.com/sea212/xcm-simulator", branch = "polkadot-v0.9.19-moonbeam" } \ No newline at end of file +xcm-emulator = { git = "https://github.com/sea212/xcm-simulator", branch = "polkadot-v0.9.19-moonbeam" } diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index 992320c11..54df1c0b3 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -3,9 +3,9 @@ arbitrary = { default-features = false, optional = true, version = "1.0" } bstringify = "0.1.2" frame-support = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } frame-system = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/substrate" } +orml-currencies = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } orml-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } orml-traits = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } -orml-currencies = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library" } parity-scale-codec = { default-features = false, features = ["derive", "max-encoded-len"], version = "3.0.0" } scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } serde = { default-features = false, features = ["derive"], optional = true, version = "1.0.136" } diff --git a/primitives/src/constants.rs b/primitives/src/constants.rs index 18df2d88d..d6330dda4 100644 --- a/primitives/src/constants.rs +++ b/primitives/src/constants.rs @@ -86,7 +86,6 @@ pub const MAX_ASSETS: u16 = MAX_CATEGORIES + 1; /// Pallet identifier, mainly used for named balance reserves. pub const SWAPS_PALLET_ID: PalletId = PalletId(*b"zge/swap"); - // Treasury /// Pallet identifier, used to derive treasury account -pub const TREASURY_PALLET_ID: PalletId = PalletId(*b"zge/swap"); \ No newline at end of file +pub const TREASURY_PALLET_ID: PalletId = PalletId(*b"zge/swap"); diff --git a/primitives/src/constants/mock.rs b/primitives/src/constants/mock.rs index 0e6a1299f..0ea728082 100644 --- a/primitives/src/constants/mock.rs +++ b/primitives/src/constants/mock.rs @@ -100,4 +100,4 @@ parameter_types! { // Time parameter_types! { pub const MinimumPeriod: u64 = MILLISECS_PER_BLOCK as u64 / 2; -} \ No newline at end of file +} diff --git a/runtime/battery-station/Cargo.toml b/runtime/battery-station/Cargo.toml index 9d39d3080..be3643cbc 100644 --- a/runtime/battery-station/Cargo.toml +++ b/runtime/battery-station/Cargo.toml @@ -84,13 +84,13 @@ log = { version = "0.4.8", default-features = false, optional = true } # XCM kusama-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -polkadot-primitives = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -polkadot-runtime-parachains = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } orml-asset-registry = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-unknown-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-xtokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } pallet-xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +polkadot-primitives = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +polkadot-runtime-parachains = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm-builder = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm-executor = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs index a2eb4f0bd..ea79cc6c5 100644 --- a/runtime/battery-station/src/integration_tests/xcm/setup.rs +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -19,9 +19,9 @@ use crate::{ xcm_config::{ asset_registry::CustomMetadata, - config::{general_key, battery_station}, + config::{battery_station, general_key}, }, - AccountId, AssetRegistry, Balance, CurrencyId, Origin, Runtime, System, ExistentialDeposit, + AccountId, AssetRegistry, Balance, CurrencyId, ExistentialDeposit, Origin, Runtime, System, }; use frame_support::{assert_ok, traits::GenesisBuild}; use orml_traits::asset_registry::AssetMetadata; diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index 2ada2c237..ba4207833 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -16,9 +16,8 @@ // along with Zeitgeist. If not, see . use crate::{ - parameters::ZeitgeistTreasuryAccount, - xcm_config::{config::battery_station}, - AccountId, CurrencyId, DmpQueue, Origin, Runtime, XcmpQueue, + parameters::ZeitgeistTreasuryAccount, xcm_config::config::battery_station, AccountId, + CurrencyId, DmpQueue, Origin, Runtime, XcmpQueue, }; use cumulus_primitives_core::ParaId; use frame_support::{traits::GenesisBuild, weights::Weight}; diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs index 963d9448b..d35d48cf3 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -19,24 +19,19 @@ use crate::{ integration_tests::xcm::{ setup::{ - foreign_parent_multilocation, foreign_sibling_multilocation, - foreign_ztg_multilocation, register_foreign_parent, register_foreign_sibling, - FOREIGN_PARENT_ID, - FOREIGN_SIBLING_ID, + foreign_parent_multilocation, foreign_sibling_multilocation, foreign_ztg_multilocation, + register_foreign_parent, register_foreign_sibling, FOREIGN_PARENT_ID, + FOREIGN_SIBLING_ID, }, - test_net::{Zeitgeist}, + test_net::Zeitgeist, }, - xcm_config::{ - config::{general_key, battery_station, AssetConvert}, - }, - CurrencyId + xcm_config::config::{battery_station, general_key, AssetConvert}, + CurrencyId, }; -use frame_support::{assert_err}; +use frame_support::assert_err; use sp_runtime::traits::Convert as C2; -use xcm::{ - latest::{Junction::*, Junctions::*, MultiLocation}, -}; +use xcm::latest::{Junction::*, Junctions::*, MultiLocation}; use xcm_emulator::TestExt; use xcm_executor::traits::Convert as C1; @@ -45,7 +40,8 @@ fn convert_native() { assert_eq!(battery_station::KEY.to_vec(), vec![0, 1]); // The way Ztg is represented relative within the Zeitgeist runtime - let ztg_location_inner: MultiLocation = MultiLocation::new(0, X1(general_key(battery_station::KEY))); + let ztg_location_inner: MultiLocation = + MultiLocation::new(0, X1(general_key(battery_station::KEY))); assert_eq!(>::convert(ztg_location_inner), Ok(CurrencyId::Ztg)); diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/mod.rs b/runtime/battery-station/src/integration_tests/xcm/tests/mod.rs index 44d31098b..8194bed88 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/mod.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/mod.rs @@ -15,6 +15,5 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . - mod currency_id_convert; mod transfers; diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index a02546dce..62c8cf64a 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -19,10 +19,8 @@ use crate::{ integration_tests::xcm::{ setup::{ - ksm, - register_foreign_parent, register_foreign_ztg, sibling_account, - zeitgeist_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, - FOREIGN_ZTG_ID, PARA_ID_SIBLING, + ksm, register_foreign_parent, register_foreign_ztg, sibling_account, zeitgeist_account, + ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, @@ -35,11 +33,9 @@ use crate::{ ZeitgeistTreasuryAccount, }; -use frame_support::{assert_ok}; -use orml_traits::{MultiCurrency}; -use xcm::{ - latest::{Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, -}; +use frame_support::assert_ok; +use orml_traits::MultiCurrency; +use xcm::latest::{Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}; use xcm_emulator::TestExt; use zeitgeist_primitives::constants::BalanceFractionalDecimals; diff --git a/runtime/battery-station/src/parachain_params.rs b/runtime/battery-station/src/parachain_params.rs index 6d471c331..a8f0e0893 100644 --- a/runtime/battery-station/src/parachain_params.rs +++ b/runtime/battery-station/src/parachain_params.rs @@ -48,7 +48,6 @@ parameter_types! { // Cumulus and Polkadot pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); pub const RelayLocation: MultiLocation = MultiLocation::parent(); - // Have to change "Any" to "Kusama" for mainnet once we have separate runtimes pub const RelayNetwork: NetworkId = NetworkId::Any; pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; diff --git a/runtime/zeitgeist/Cargo.toml b/runtime/zeitgeist/Cargo.toml index 4b790e733..455d0041e 100644 --- a/runtime/zeitgeist/Cargo.toml +++ b/runtime/zeitgeist/Cargo.toml @@ -71,13 +71,13 @@ polkadot-parachain = { branch = "moonbeam-polkadot-v0.9.19", default-features = # XCM kusama-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -polkadot-primitives = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -polkadot-runtime-parachains = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } orml-asset-registry = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-unknown-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } +orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } orml-xtokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } pallet-xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +polkadot-primitives = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +polkadot-runtime-parachains = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm-builder = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } xcm-executor = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } diff --git a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs index d3565a9bd..316b5c32c 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs @@ -21,7 +21,7 @@ use crate::{ asset_registry::CustomMetadata, config::{general_key, zeitgeist}, }, - AccountId, AssetRegistry, Balance, CurrencyId, Origin, Runtime, System, ExistentialDeposit, + AccountId, AssetRegistry, Balance, CurrencyId, ExistentialDeposit, Origin, Runtime, System, }; use frame_support::{assert_ok, traits::GenesisBuild}; use orml_traits::asset_registry::AssetMetadata; diff --git a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs index 94abd1225..edd61dbfe 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs @@ -16,9 +16,8 @@ // along with Zeitgeist. If not, see . use crate::{ - parameters::ZeitgeistTreasuryAccount, - xcm_config::{config::zeitgeist}, - AccountId, CurrencyId, DmpQueue, Origin, Runtime, XcmpQueue, + parameters::ZeitgeistTreasuryAccount, xcm_config::config::zeitgeist, AccountId, CurrencyId, + DmpQueue, Origin, Runtime, XcmpQueue, }; use cumulus_primitives_core::ParaId; use frame_support::{traits::GenesisBuild, weights::Weight}; diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs index ced783a67..0ed1e6aa4 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -19,24 +19,19 @@ use crate::{ integration_tests::xcm::{ setup::{ - foreign_parent_multilocation, foreign_sibling_multilocation, - foreign_ztg_multilocation, register_foreign_parent, register_foreign_sibling, - FOREIGN_PARENT_ID, - FOREIGN_SIBLING_ID, + foreign_parent_multilocation, foreign_sibling_multilocation, foreign_ztg_multilocation, + register_foreign_parent, register_foreign_sibling, FOREIGN_PARENT_ID, + FOREIGN_SIBLING_ID, }, - test_net::{Zeitgeist}, + test_net::Zeitgeist, }, - xcm_config::{ - config::{general_key, zeitgeist, AssetConvert}, - }, - CurrencyId + xcm_config::config::{general_key, zeitgeist, AssetConvert}, + CurrencyId, }; -use frame_support::{assert_err}; +use frame_support::assert_err; use sp_runtime::traits::Convert as C2; -use xcm::{ - latest::{Junction::*, Junctions::*, MultiLocation}, -}; +use xcm::latest::{Junction::*, Junctions::*, MultiLocation}; use xcm_emulator::TestExt; use xcm_executor::traits::Convert as C1; diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/mod.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/mod.rs index 44d31098b..8194bed88 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/mod.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/mod.rs @@ -15,6 +15,5 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . - mod currency_id_convert; mod transfers; diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs index 993c04370..b22c7f816 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs @@ -19,27 +19,23 @@ use crate::{ integration_tests::xcm::{ setup::{ - ksm, - register_foreign_parent, register_foreign_ztg, sibling_account, - zeitgeist_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, - FOREIGN_ZTG_ID, PARA_ID_SIBLING, + ksm, register_foreign_parent, register_foreign_ztg, sibling_account, zeitgeist_account, + ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, xcm_config::{ asset_registry::{CustomMetadata, XcmMetadata}, - config::{zeitgeist,}, + config::zeitgeist, fees::default_per_second, }, AssetRegistry, Balance, Balances, CurrencyId, Origin, Tokens, XTokens, ZeitgeistTreasuryAccount, }; -use frame_support::{assert_ok}; -use orml_traits::{MultiCurrency}; -use xcm::{ - latest::{Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}, -}; +use frame_support::assert_ok; +use orml_traits::MultiCurrency; +use xcm::latest::{Junction, Junction::*, Junctions::*, MultiLocation, NetworkId}; use xcm_emulator::TestExt; use zeitgeist_primitives::constants::BalanceFractionalDecimals; diff --git a/runtime/zeitgeist/src/parachain_params.rs b/runtime/zeitgeist/src/parachain_params.rs index 920841ea1..08d0c1539 100644 --- a/runtime/zeitgeist/src/parachain_params.rs +++ b/runtime/zeitgeist/src/parachain_params.rs @@ -22,10 +22,8 @@ )] #![cfg(feature = "parachain")] -use super::{ - parameters::MAXIMUM_BLOCK_WEIGHT, Origin, ParachainInfo, -}; -use frame_support::{parameter_types, traits::{Get}, weights::Weight}; +use super::{parameters::MAXIMUM_BLOCK_WEIGHT, Origin, ParachainInfo}; +use frame_support::{parameter_types, traits::Get, weights::Weight}; use orml_traits::parameter_type_with_key; use sp_runtime::{Perbill, Percent}; use xcm::latest::{prelude::X1, Junction::Parachain, MultiLocation, NetworkId}; @@ -34,7 +32,6 @@ use zeitgeist_primitives::{ types::Balance, }; - parameter_types! { // Author-Mapping /// The amount that should be taken as a security deposit when registering a NimbusId. @@ -51,8 +48,7 @@ parameter_types! { // Cumulus and Polkadot pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); pub const RelayLocation: MultiLocation = MultiLocation::parent(); - // Have to change "Any" to "Kusama" for mainnet once we have separate runtimes - pub const RelayNetwork: NetworkId = NetworkId::Any; + pub const RelayNetwork: NetworkId = NetworkId::Kusama; pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into(); @@ -104,7 +100,6 @@ parameter_types! { pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into()))); } - parameter_type_with_key! { // XCM pub ParachainMinFee: |_location: MultiLocation| -> Option { diff --git a/runtime/zeitgeist/src/xcm_config/config.rs b/runtime/zeitgeist/src/xcm_config/config.rs index 34be2ff3a..561cca8e9 100644 --- a/runtime/zeitgeist/src/xcm_config/config.rs +++ b/runtime/zeitgeist/src/xcm_config/config.rs @@ -23,7 +23,7 @@ use crate::{ }; use alloc::vec::Vec; -use frame_support::{match_types, parameter_types, traits::Everything}; +use frame_support::{parameter_types, traits::Everything}; use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{location::AbsoluteReserveProvider, MultiCurrency}; use orml_xcm_support::{ @@ -35,7 +35,7 @@ use sp_runtime::traits::Convert; use xcm::{ latest::{ prelude::{AccountId32, AssetId, Concrete, GeneralKey, MultiAsset, NetworkId, X1, X2}, - BodyId, Junction, Junctions, MultiLocation, + Junction, MultiLocation, }, opaque::latest::Fungibility::Fungible, }; @@ -299,14 +299,6 @@ pub type XcmRouter = ( XcmpQueue, ); -match_types! { - pub type ParentOrParentsUnitPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Junctions::Here } | - // Potentially change "Unit" to "Executive" for mainnet once we have separate runtimes - MultiLocation { parents: 1, interior: X1(Junction::Plurality { id: BodyId::Unit, .. }) } - }; -} - #[inline] pub(crate) fn general_key(key: &[u8]) -> Junction { GeneralKey(Vec::from(key)) From 0ff4e5f93baf04bbf543ce3577e04f3e3bec8053 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Wed, 9 Nov 2022 16:16:57 +0100 Subject: [PATCH 38/59] Remove dead code --- runtime/battery-station/src/xcm_config/config.rs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 743c99a6a..48e310052 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -299,14 +299,6 @@ pub type XcmRouter = ( XcmpQueue, ); -match_types! { - pub type ParentOrParentsUnitPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Junctions::Here } | - // Potentially change "Unit" to "Executive" for mainnet once we have separate runtimes - MultiLocation { parents: 1, interior: X1(Junction::Plurality { id: BodyId::Unit, .. }) } - }; -} - #[inline] pub(crate) fn general_key(key: &[u8]) -> Junction { GeneralKey(Vec::from(key)) From e170adb979115d5794bcf2510acfe74a59146686 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Wed, 9 Nov 2022 16:34:01 +0100 Subject: [PATCH 39/59] Update changelog_for_devs.md --- docs/changelog_for_devs.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/changelog_for_devs.md b/docs/changelog_for_devs.md index 1b1307552..83e1b69a5 100644 --- a/docs/changelog_for_devs.md +++ b/docs/changelog_for_devs.md @@ -1,7 +1,7 @@ -# v0.3.6 -- Asset::Ztg was renamed to Asset::Ztg. All currency symbols will be written in uppercase. -- Added two more currencies: AUSD and KSM (or ROC on testnet) +# v0.3.7 - Added xTokens pallet to transfer tokens accross chains +- Added AssetRegistry pallet to register foreign asset +- Asset UnknownTokens pallet to handle unknown foreign assets # v0.3.5 From a5ed0762ebc5695760d4d9107f2278d4ec19c685 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 17 Nov 2022 11:44:20 +0100 Subject: [PATCH 40/59] Use correct treasury pallet id (as before) --- primitives/src/constants.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/primitives/src/constants.rs b/primitives/src/constants.rs index d6330dda4..e41e0fe1d 100644 --- a/primitives/src/constants.rs +++ b/primitives/src/constants.rs @@ -88,4 +88,4 @@ pub const SWAPS_PALLET_ID: PalletId = PalletId(*b"zge/swap"); // Treasury /// Pallet identifier, used to derive treasury account -pub const TREASURY_PALLET_ID: PalletId = PalletId(*b"zge/swap"); +pub const TREASURY_PALLET_ID: PalletId = PalletId(*b"zge/tsry"); \ No newline at end of file From 7ebe84aff0b32e56910207031bc5d7d7399ba123 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 17 Nov 2022 11:52:47 +0100 Subject: [PATCH 41/59] Use unambiguous names for setters --- runtime/battery-station/src/integration_tests/xcm/setup.rs | 4 ++-- runtime/battery-station/src/integration_tests/xcm/test_net.rs | 4 ++-- runtime/zeitgeist/src/integration_tests/xcm/setup.rs | 4 ++-- runtime/zeitgeist/src/integration_tests/xcm/test_net.rs | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs index ea79cc6c5..67296d470 100644 --- a/runtime/battery-station/src/integration_tests/xcm/setup.rs +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -43,12 +43,12 @@ impl Default for ExtBuilder { } impl ExtBuilder { - pub fn balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { + pub fn set_balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { self.balances = balances; self } - pub fn parachain_id(mut self, parachain_id: u32) -> Self { + pub fn set_parachain_id(mut self, parachain_id: u32) -> Self { self.parachain_id = parachain_id; self } diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index ba4207833..1e6bfc33d 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -105,12 +105,12 @@ pub(super) fn relay_ext() -> sp_io::TestExternalities { pub(super) fn para_ext(parachain_id: u32) -> sp_io::TestExternalities { ExtBuilder::default() - .balances(vec![ + .set_balances(vec![ (AccountId::from(ALICE), CurrencyId::Ztg, ztg(10)), (AccountId::from(ALICE), FOREIGN_PARENT_ID, ksm(10)), (ZeitgeistTreasuryAccount::get(), FOREIGN_PARENT_ID, ksm(1)), ]) - .parachain_id(parachain_id) + .set_parachain_id(parachain_id) .build() } diff --git a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs index 316b5c32c..0acb7f48c 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs @@ -43,12 +43,12 @@ impl Default for ExtBuilder { } impl ExtBuilder { - pub fn balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { + pub fn set_balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { self.balances = balances; self } - pub fn parachain_id(mut self, parachain_id: u32) -> Self { + pub fn set_parachain_id(mut self, parachain_id: u32) -> Self { self.parachain_id = parachain_id; self } diff --git a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs index edd61dbfe..1c56434ca 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs @@ -105,12 +105,12 @@ pub(super) fn relay_ext() -> sp_io::TestExternalities { pub(super) fn para_ext(parachain_id: u32) -> sp_io::TestExternalities { ExtBuilder::default() - .balances(vec![ + .set_balances(vec![ (AccountId::from(ALICE), CurrencyId::Ztg, ztg(10)), (AccountId::from(ALICE), FOREIGN_PARENT_ID, ksm(10)), (ZeitgeistTreasuryAccount::get(), FOREIGN_PARENT_ID, ksm(1)), ]) - .parachain_id(parachain_id) + .set_parachain_id(parachain_id) .build() } From fc6ae1930f7c350a3ec8d7b0edf1ab6e63b195c8 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 17 Nov 2022 11:53:38 +0100 Subject: [PATCH 42/59] Convert comment to docstring --- runtime/battery-station/src/xcm_config/config.rs | 2 +- runtime/zeitgeist/src/xcm_config/config.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 48e310052..ffa148f14 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -79,7 +79,7 @@ impl Config for XcmConfig { type IsTeleporter = (); /// Means of inverting a location. type LocationInverter = LocationInverter; - // How to get a call origin from a `OriginKind` value. + /// How to get a call origin from a `OriginKind` value. type OriginConverter = XcmOriginToTransactDispatchOrigin; /// Module that handles responses of queries. type ResponseHandler = PolkadotXcm; diff --git a/runtime/zeitgeist/src/xcm_config/config.rs b/runtime/zeitgeist/src/xcm_config/config.rs index 561cca8e9..6c64e7b32 100644 --- a/runtime/zeitgeist/src/xcm_config/config.rs +++ b/runtime/zeitgeist/src/xcm_config/config.rs @@ -79,7 +79,7 @@ impl Config for XcmConfig { type IsTeleporter = (); /// Means of inverting a location. type LocationInverter = LocationInverter; - // How to get a call origin from a `OriginKind` value. + /// How to get a call origin from a `OriginKind` value. type OriginConverter = XcmOriginToTransactDispatchOrigin; /// Module that handles responses of queries. type ResponseHandler = PolkadotXcm; From 354de95323b087cc9d639c447d33dca4d1ca074c Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 17 Nov 2022 12:03:41 +0100 Subject: [PATCH 43/59] Fix wrong comment --- .../src/integration_tests/xcm/tests/currency_id_convert.rs | 2 +- .../src/integration_tests/xcm/tests/currency_id_convert.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs index d35d48cf3..626ef8125 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -89,7 +89,7 @@ fn convert_any_registered_sibling_multilocation() { assert_eq!(>::convert(FOREIGN_SIBLING_ID), None,); - // Register parent as foreign asset in the Zeitgeist parachain + // Register sibling as foreign asset in the Zeitgeist parachain register_foreign_sibling(None); assert_eq!( diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs index 0ed1e6aa4..bf82a63e4 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -88,7 +88,7 @@ fn convert_any_registered_sibling_multilocation() { assert_eq!(>::convert(FOREIGN_SIBLING_ID), None,); - // Register parent as foreign asset in the Zeitgeist parachain + // Register sibling as foreign asset in the Zeitgeist parachain register_foreign_sibling(None); assert_eq!( From b2c1e1f3f41d3ada12db337ff502b9181896f44f Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Tue, 22 Nov 2022 21:35:54 +0100 Subject: [PATCH 44/59] Reset emulated testnet in any case --- .../zeitgeist/src/integration_tests/xcm/tests/transfers.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs index b22c7f816..8c88debbd 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs @@ -171,6 +171,8 @@ fn transfer_ztg_sibling_to_zeitgeist() { #[test] fn transfer_ksm_from_relay_chain() { + TestNet::reset(); + let transfer_amount: Balance = ksm(1); Zeitgeist::execute_with(|| { @@ -197,6 +199,8 @@ fn transfer_ksm_from_relay_chain() { #[test] fn transfer_ksm_to_relay_chain() { + TestNet::reset(); + let transfer_amount: Balance = ksm(1); transfer_ksm_from_relay_chain(); From 0f59db035a9f8f1d7195f28b96ebfd07b5c64eec Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Wed, 23 Nov 2022 11:50:49 +0100 Subject: [PATCH 45/59] Remove unnecessary commas Co-authored-by: Chralt --- .../src/integration_tests/xcm/tests/currency_id_convert.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs index bf82a63e4..757e13be5 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -61,7 +61,7 @@ fn convert_any_registered_parent_multilocation() { foreign_parent_multilocation() ); - assert_eq!(>::convert(FOREIGN_PARENT_ID), None,); + assert_eq!(>::convert(FOREIGN_PARENT_ID), None); // Register parent as foreign asset in the Zeitgeist parachain register_foreign_parent(None); @@ -86,7 +86,7 @@ fn convert_any_registered_sibling_multilocation() { foreign_sibling_multilocation() ); - assert_eq!(>::convert(FOREIGN_SIBLING_ID), None,); + assert_eq!(>::convert(FOREIGN_SIBLING_ID), None); // Register sibling as foreign asset in the Zeitgeist parachain register_foreign_sibling(None); From 49b54ac521343ef03d93fd91bf87195e308644b3 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Wed, 23 Nov 2022 12:18:30 +0100 Subject: [PATCH 46/59] Improve readability of numbers Co-authored-by: Chralt --- .../zeitgeist/src/integration_tests/xcm/tests/transfers.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs index 8c88debbd..79f4ca486 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs @@ -229,7 +229,7 @@ fn transfer_ksm_to_relay_chain() { }); KusamaNet::execute_with(|| { - assert_eq!(kusama_runtime::Balances::free_balance(&BOB.into()), 999834059328); + assert_eq!(kusama_runtime::Balances::free_balance(&BOB.into()), 999_834_059_328); }); } @@ -311,8 +311,8 @@ fn transfer_ztg_to_sibling_with_custom_fee() { #[test] fn test_total_fee() { - assert_eq!(ztg_fee(), 64000000); - assert_eq!(ksm_fee(), 6400000000); + assert_eq!(ztg_fee(), 64_000_000); + assert_eq!(ksm_fee(), 6_400_000_000); } #[inline] From 391fc02d6a9852f095656effa0b2fcd8494f6682 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Wed, 23 Nov 2022 12:26:21 +0100 Subject: [PATCH 47/59] Fix docstring Co-authored-by: Chralt --- runtime/zeitgeist/src/xcm_config/config.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/zeitgeist/src/xcm_config/config.rs b/runtime/zeitgeist/src/xcm_config/config.rs index 6c64e7b32..b7cb968c0 100644 --- a/runtime/zeitgeist/src/xcm_config/config.rs +++ b/runtime/zeitgeist/src/xcm_config/config.rs @@ -149,7 +149,7 @@ parameter_types! { ).into(), native_per_second(), ); - /// The amount of canonical ZTG charged per second of execution. + /// The amount of ZTG charged per second of execution. pub ZtgPerSecond: (AssetId, u128) = ( MultiLocation::new( 1, From b6ef8cc6f5818c7b4ae1ee3dafc1dcc288361675 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Wed, 23 Nov 2022 16:34:43 +0100 Subject: [PATCH 48/59] Remove invalid initial balance (integration test) --- runtime/battery-station/src/integration_tests/xcm/test_net.rs | 2 -- runtime/zeitgeist/src/integration_tests/xcm/test_net.rs | 2 -- 2 files changed, 4 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index 1e6bfc33d..55432256d 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -79,8 +79,6 @@ pub(super) fn relay_ext() -> sp_io::TestExternalities { pallet_balances::GenesisConfig:: { balances: vec![ (AccountId::from(ALICE), ksm(2002)), - (ParaId::from(battery_station::ID).into_account(), ztg(7)), - (ParaId::from(PARA_ID_SIBLING).into_account(), sibling(7)), ], } .assimilate_storage(&mut t) diff --git a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs index 1c56434ca..a4d0ce9d7 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs @@ -79,8 +79,6 @@ pub(super) fn relay_ext() -> sp_io::TestExternalities { pallet_balances::GenesisConfig:: { balances: vec![ (AccountId::from(ALICE), ksm(2002)), - (ParaId::from(zeitgeist::ID).into_account(), ztg(7)), - (ParaId::from(PARA_ID_SIBLING).into_account(), sibling(7)), ], } .assimilate_storage(&mut t) From dab6d1167a1f95abe119cd0eb4da425ee008e210 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 24 Nov 2022 09:41:40 +0100 Subject: [PATCH 49/59] Improve style Co-authored-by: Chralt --- .../src/integration_tests/xcm/tests/currency_id_convert.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs index 626ef8125..a2d744b5a 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/currency_id_convert.rs @@ -62,7 +62,7 @@ fn convert_any_registered_parent_multilocation() { foreign_parent_multilocation() ); - assert_eq!(>::convert(FOREIGN_PARENT_ID), None,); + assert_eq!(>::convert(FOREIGN_PARENT_ID), None); // Register parent as foreign asset in the Zeitgeist parachain register_foreign_parent(None); @@ -87,7 +87,7 @@ fn convert_any_registered_sibling_multilocation() { foreign_sibling_multilocation() ); - assert_eq!(>::convert(FOREIGN_SIBLING_ID), None,); + assert_eq!(>::convert(FOREIGN_SIBLING_ID), None); // Register sibling as foreign asset in the Zeitgeist parachain register_foreign_sibling(None); From 884a32d26b878eacf487c66e40ef636280f90c3e Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 24 Nov 2022 09:48:10 +0100 Subject: [PATCH 50/59] Use more descriptive function name --- .../src/integration_tests/xcm/setup.rs | 4 ++-- .../src/integration_tests/xcm/tests/transfers.rs | 16 ++++++++-------- .../zeitgeist/src/integration_tests/xcm/setup.rs | 4 ++-- .../src/integration_tests/xcm/tests/transfers.rs | 16 ++++++++-------- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs index 67296d470..3ce4802da 100644 --- a/runtime/battery-station/src/integration_tests/xcm/setup.rs +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -193,12 +193,12 @@ pub(super) fn dollar(decimals: u32) -> Balance { } #[inline] -pub(super) fn sibling_account() -> AccountId { +pub(super) fn sibling_parachain_account() -> AccountId { parachain_account(PARA_ID_SIBLING.into()) } #[inline] -pub(super) fn zeitgeist_account() -> AccountId { +pub(super) fn zeitgeist_parachain_account() -> AccountId { parachain_account(battery_station::ID) } diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index 62c8cf64a..242195617 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -19,7 +19,7 @@ use crate::{ integration_tests::xcm::{ setup::{ - ksm, register_foreign_parent, register_foreign_ztg, sibling_account, zeitgeist_account, + ksm, register_foreign_parent, register_foreign_ztg, sibling_parachain_account, zeitgeist_parachain_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, @@ -56,7 +56,7 @@ fn transfer_ztg_to_sibling() { Zeitgeist::execute_with(|| { assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); - assert_eq!(Balances::free_balance(&sibling_account()), 0); + assert_eq!(Balances::free_balance(&sibling_parachain_account()), 0); assert_ok!(XTokens::transfer( Origin::signed(ALICE.into()), CurrencyId::Ztg, @@ -78,7 +78,7 @@ fn transfer_ztg_to_sibling() { assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance - transfer_amount); // Verify that the amount transferred is now part of the sibling account here - assert_eq!(Balances::free_balance(&sibling_account()), transfer_amount); + assert_eq!(Balances::free_balance(&sibling_parachain_account()), transfer_amount); }); Sibling::execute_with(|| { @@ -118,11 +118,11 @@ fn transfer_ztg_sibling_to_zeitgeist() { treasury_initial_balance = Balances::free_balance(ZeitgeistTreasuryAccount::get()); assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); - assert_eq!(Balances::free_balance(&sibling_account()), sibling_sovereign_initial_balance); + assert_eq!(Balances::free_balance(&sibling_parachain_account()), sibling_sovereign_initial_balance); }); Sibling::execute_with(|| { - assert_eq!(Balances::free_balance(&zeitgeist_account()), 0); + assert_eq!(Balances::free_balance(&zeitgeist_parachain_account()), 0); assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), bob_initial_balance); assert_ok!(XTokens::transfer( Origin::signed(BOB.into()), @@ -157,7 +157,7 @@ fn transfer_ztg_sibling_to_zeitgeist() { // Verify that the reserve has been adjusted properly assert_eq!( - Balances::free_balance(&sibling_account()), + Balances::free_balance(&sibling_parachain_account()), sibling_sovereign_initial_balance - transfer_amount ); @@ -262,7 +262,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { Zeitgeist::execute_with(|| { assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); - assert_eq!(Balances::free_balance(&sibling_account()), 0); + assert_eq!(Balances::free_balance(&sibling_parachain_account()), 0); assert_ok!(XTokens::transfer( Origin::signed(ALICE.into()), CurrencyId::Ztg, @@ -284,7 +284,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance - transfer_amount); // Verify that the amount transferred is now part of the sibling account here - assert_eq!(Balances::free_balance(&sibling_account()), transfer_amount); + assert_eq!(Balances::free_balance(&sibling_parachain_account()), transfer_amount); }); Sibling::execute_with(|| { diff --git a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs index 0acb7f48c..bf09038e5 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs @@ -193,12 +193,12 @@ pub(super) fn dollar(decimals: u32) -> Balance { } #[inline] -pub(super) fn sibling_account() -> AccountId { +pub(super) fn sibling_parachain_account() -> AccountId { parachain_account(PARA_ID_SIBLING.into()) } #[inline] -pub(super) fn zeitgeist_account() -> AccountId { +pub(super) fn zeitgeist_parachain_account() -> AccountId { parachain_account(zeitgeist::ID) } diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs index 79f4ca486..ab6b6a48d 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs @@ -19,7 +19,7 @@ use crate::{ integration_tests::xcm::{ setup::{ - ksm, register_foreign_parent, register_foreign_ztg, sibling_account, zeitgeist_account, + ksm, register_foreign_parent, register_foreign_ztg, sibling_parachain_account, zeitgeist_parachain_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, @@ -56,7 +56,7 @@ fn transfer_ztg_to_sibling() { Zeitgeist::execute_with(|| { assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); - assert_eq!(Balances::free_balance(&sibling_account()), 0); + assert_eq!(Balances::free_balance(&sibling_parachain_account()), 0); assert_ok!(XTokens::transfer( Origin::signed(ALICE.into()), CurrencyId::Ztg, @@ -78,7 +78,7 @@ fn transfer_ztg_to_sibling() { assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance - transfer_amount); // Verify that the amount transferred is now part of the sibling account here - assert_eq!(Balances::free_balance(&sibling_account()), transfer_amount); + assert_eq!(Balances::free_balance(&sibling_parachain_account()), transfer_amount); }); Sibling::execute_with(|| { @@ -118,11 +118,11 @@ fn transfer_ztg_sibling_to_zeitgeist() { treasury_initial_balance = Balances::free_balance(ZeitgeistTreasuryAccount::get()); assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); - assert_eq!(Balances::free_balance(&sibling_account()), sibling_sovereign_initial_balance); + assert_eq!(Balances::free_balance(&sibling_parachain_account()), sibling_sovereign_initial_balance); }); Sibling::execute_with(|| { - assert_eq!(Balances::free_balance(&zeitgeist_account()), 0); + assert_eq!(Balances::free_balance(&zeitgeist_parachain_account()), 0); assert_eq!(Tokens::free_balance(FOREIGN_ZTG_ID, &BOB.into()), bob_initial_balance); assert_ok!(XTokens::transfer( Origin::signed(BOB.into()), @@ -157,7 +157,7 @@ fn transfer_ztg_sibling_to_zeitgeist() { // Verify that the reserve has been adjusted properly assert_eq!( - Balances::free_balance(&sibling_account()), + Balances::free_balance(&sibling_parachain_account()), sibling_sovereign_initial_balance - transfer_amount ); @@ -266,7 +266,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { Zeitgeist::execute_with(|| { assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); - assert_eq!(Balances::free_balance(&sibling_account()), 0); + assert_eq!(Balances::free_balance(&sibling_parachain_account()), 0); assert_ok!(XTokens::transfer( Origin::signed(ALICE.into()), CurrencyId::Ztg, @@ -288,7 +288,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance - transfer_amount); // Verify that the amount transferred is now part of the sibling account here - assert_eq!(Balances::free_balance(&sibling_account()), transfer_amount); + assert_eq!(Balances::free_balance(&sibling_parachain_account()), transfer_amount); }); Sibling::execute_with(|| { From fdfa04bbe948929dcbe30a2f349641c3dc182899 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 24 Nov 2022 10:16:43 +0100 Subject: [PATCH 51/59] Add additional balance guard to xcm tests --- .../src/integration_tests/xcm/tests/transfers.rs | 7 +++++++ .../zeitgeist/src/integration_tests/xcm/tests/transfers.rs | 5 ++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index 242195617..6bd16f58c 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -171,6 +171,8 @@ fn transfer_ztg_sibling_to_zeitgeist() { #[test] fn transfer_ksm_from_relay_chain() { + TestNet::reset(); + let transfer_amount: Balance = ksm(1); Zeitgeist::execute_with(|| { @@ -178,6 +180,9 @@ fn transfer_ksm_from_relay_chain() { }); KusamaNet::execute_with(|| { + let initial_balance = kusama_runtime::Balances::free_balance(&ALICE.into()); + assert!(initial_balance >= transfer_amount); + assert_ok!(kusama_runtime::XcmPallet::reserve_transfer_assets( kusama_runtime::Origin::signed(ALICE.into()), Box::new(Parachain(battery_station::ID).into().into()), @@ -197,6 +202,8 @@ fn transfer_ksm_from_relay_chain() { #[test] fn transfer_ksm_to_relay_chain() { + TestNet::reset(); + let transfer_amount: Balance = ksm(1); transfer_ksm_from_relay_chain(); diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs index ab6b6a48d..f87f77c29 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs @@ -172,7 +172,7 @@ fn transfer_ztg_sibling_to_zeitgeist() { #[test] fn transfer_ksm_from_relay_chain() { TestNet::reset(); - + let transfer_amount: Balance = ksm(1); Zeitgeist::execute_with(|| { @@ -180,6 +180,9 @@ fn transfer_ksm_from_relay_chain() { }); KusamaNet::execute_with(|| { + let initial_balance = kusama_runtime::Balances::free_balance(&ALICE.into()); + assert!(initial_balance >= transfer_amount); + assert_ok!(kusama_runtime::XcmPallet::reserve_transfer_assets( kusama_runtime::Origin::signed(ALICE.into()), Box::new(Parachain(zeitgeist::ID).into().into()), From 54d388935551b3afcb43e30c27013c387e0c2c4e Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 24 Nov 2022 10:23:40 +0100 Subject: [PATCH 52/59] Use ::parachain_id() instead of ::get() --- runtime/battery-station/src/parachain_params.rs | 2 +- runtime/zeitgeist/src/parachain_params.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/battery-station/src/parachain_params.rs b/runtime/battery-station/src/parachain_params.rs index a8f0e0893..05ddeddf0 100644 --- a/runtime/battery-station/src/parachain_params.rs +++ b/runtime/battery-station/src/parachain_params.rs @@ -97,7 +97,7 @@ parameter_types! { /// Max instructions per XCM pub const MaxInstructions: u32 = 100; // Relative self location - pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into()))); + pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::parachain_id().into()))); } parameter_type_with_key! { diff --git a/runtime/zeitgeist/src/parachain_params.rs b/runtime/zeitgeist/src/parachain_params.rs index 08d0c1539..0d0afffda 100644 --- a/runtime/zeitgeist/src/parachain_params.rs +++ b/runtime/zeitgeist/src/parachain_params.rs @@ -97,7 +97,7 @@ parameter_types! { /// Max instructions per XCM pub const MaxInstructions: u32 = 100; // Relative self location - pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into()))); + pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::parachain_id().into()))); } parameter_type_with_key! { From 37a15365492dde078578bc96c4b457d840009ce2 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 24 Nov 2022 10:41:34 +0100 Subject: [PATCH 53/59] Reduce nested match depth --- .../battery-station/src/xcm_config/config.rs | 29 ++++++++++++------- runtime/zeitgeist/src/xcm_config/config.rs | 29 ++++++++++++------- 2 files changed, 36 insertions(+), 22 deletions(-) diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index ffa148f14..aea0ecbad 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -211,20 +211,27 @@ impl Convert> for AssetConvert { impl xcm_executor::traits::Convert for AssetConvert { fn convert(location: MultiLocation) -> Result { match location.clone() { - MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { - battery_station::KEY => Ok(CurrencyId::Ztg), - _ => Err(location), - }, + MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => { + if &key[..] == battery_station::KEY { + return Ok(CurrencyId::Ztg); + } + + Err(location) + } MultiLocation { parents: 1, interior: X2(Junction::Parachain(para_id), GeneralKey(key)), - } => match para_id { - id if id == u32::from(ParachainInfo::parachain_id()) => match &key[..] { - battery_station::KEY => Ok(CurrencyId::Ztg), - _ => Err(location), - }, - _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), - }, + } => { + if para_id == u32::from(ParachainInfo::parachain_id()) { + if &key[..] == battery_station::KEY { + return Ok(CurrencyId::Ztg); + } + + return Err(location); + } + + AssetRegistry::location_to_asset_id(location.clone()).ok_or(location) + } _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), } } diff --git a/runtime/zeitgeist/src/xcm_config/config.rs b/runtime/zeitgeist/src/xcm_config/config.rs index b7cb968c0..d861d640e 100644 --- a/runtime/zeitgeist/src/xcm_config/config.rs +++ b/runtime/zeitgeist/src/xcm_config/config.rs @@ -211,20 +211,27 @@ impl Convert> for AssetConvert { impl xcm_executor::traits::Convert for AssetConvert { fn convert(location: MultiLocation) -> Result { match location.clone() { - MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => match &key[..] { - zeitgeist::KEY => Ok(CurrencyId::Ztg), - _ => Err(location), - }, + MultiLocation { parents: 0, interior: X1(GeneralKey(key)) } => { + if &key[..] == zeitgeist::KEY { + return Ok(CurrencyId::Ztg); + } + + Err(location) + } MultiLocation { parents: 1, interior: X2(Junction::Parachain(para_id), GeneralKey(key)), - } => match para_id { - id if id == u32::from(ParachainInfo::parachain_id()) => match &key[..] { - zeitgeist::KEY => Ok(CurrencyId::Ztg), - _ => Err(location), - }, - _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), - }, + } => { + if para_id == u32::from(ParachainInfo::parachain_id()) { + if &key[..] == zeitgeist::KEY { + return Ok(CurrencyId::Ztg); + } + + return Err(location); + } + + AssetRegistry::location_to_asset_id(location.clone()).ok_or(location) + } _ => AssetRegistry::location_to_asset_id(location.clone()).ok_or(location), } } From b503c3450ef90b97b16a26a1df9859f8e78d1781 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 24 Nov 2022 10:47:28 +0100 Subject: [PATCH 54/59] Update changelog --- docs/changelog_for_devs.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/changelog_for_devs.md b/docs/changelog_for_devs.md index 83e1b69a5..11861d8b6 100644 --- a/docs/changelog_for_devs.md +++ b/docs/changelog_for_devs.md @@ -1,7 +1,9 @@ # v0.3.7 -- Added xTokens pallet to transfer tokens accross chains -- Added AssetRegistry pallet to register foreign asset -- Asset UnknownTokens pallet to handle unknown foreign assets +- Properly configured reserve asset transfers via XCM: + - Added xTokens pallet to transfer tokens accross chains + - Added AssetRegistry pallet to register foreign asset + - Added UnknownTokens pallet to handle unknown foreign assets + - More information at https://github.com/zeitgeistpm/zeitgeist/pull/661#top # v0.3.5 From b20e13f9a525fdf5f2c0bf15f830ce011c908891 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 24 Nov 2022 19:39:55 +0100 Subject: [PATCH 55/59] Add missing crates to runtime-benchmarks feature --- runtime/battery-station/Cargo.toml | 2 ++ runtime/zeitgeist/Cargo.toml | 2 ++ 2 files changed, 4 insertions(+) diff --git a/runtime/battery-station/Cargo.toml b/runtime/battery-station/Cargo.toml index be3643cbc..9c7d468cb 100644 --- a/runtime/battery-station/Cargo.toml +++ b/runtime/battery-station/Cargo.toml @@ -164,6 +164,8 @@ runtime-benchmarks = [ "frame-system-benchmarking", "frame-system/runtime-benchmarks", "hex-literal", + "kusama-runtime?/runtime-benchmarks", + "orml-asset-registry?/runtime-benchmarks", "orml-tokens/runtime-benchmarks", "orml-benchmarking", "orml-xtokens?/runtime-benchmarks", diff --git a/runtime/zeitgeist/Cargo.toml b/runtime/zeitgeist/Cargo.toml index 455d0041e..74591d513 100644 --- a/runtime/zeitgeist/Cargo.toml +++ b/runtime/zeitgeist/Cargo.toml @@ -163,6 +163,8 @@ runtime-benchmarks = [ "frame-system-benchmarking", "frame-system/runtime-benchmarks", "hex-literal", + "kusama-runtime?/runtime-benchmarks", + "orml-asset-registry?/runtime-benchmarks", "orml-tokens/runtime-benchmarks", "orml-xtokens?/runtime-benchmarks", "orml-benchmarking", From 77495eddfa8422c7a2d47101249512529ca99309 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 24 Nov 2022 21:27:12 +0100 Subject: [PATCH 56/59] Repair build --- Cargo.lock | 28 ++++++++----------- node/Cargo.toml | 2 +- node/src/chain_spec/battery_station.rs | 6 +--- node/src/chain_spec/dev.rs | 6 +--- node/src/chain_spec/mod.rs | 2 ++ runtime/battery-station/Cargo.toml | 24 ++++++++-------- .../src/integration_tests/xcm/setup.rs | 2 +- .../battery-station/src/parachain_params.rs | 2 +- runtime/battery-station/src/parameters.rs | 2 +- .../battery-station/src/xcm_config/config.rs | 7 ++--- runtime/zeitgeist/Cargo.toml | 23 +++++++-------- .../src/integration_tests/xcm/setup.rs | 2 +- runtime/zeitgeist/src/parachain_params.rs | 2 +- runtime/zeitgeist/src/parameters.rs | 2 +- runtime/zeitgeist/src/xcm_config/config.rs | 5 ++-- zrml/market-commons/src/migrations.rs | 2 +- 16 files changed, 52 insertions(+), 65 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4bdc24ff7..762f77161 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -783,12 +783,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "bstringify" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd769563b4ea2953e2825c9e6b7470a5f55f67e0be00030bf3e390a2a6071f64" - [[package]] name = "build-helper" version = "0.1.1" @@ -5137,7 +5131,7 @@ dependencies = [ [[package]] name = "orml-asset-registry" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" +source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.26#33dbc5e35305d0cf5937c896dae8655ca7da95d8" dependencies = [ "frame-support", "frame-system", @@ -5226,7 +5220,7 @@ dependencies = [ [[package]] name = "orml-unknown-tokens" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" +source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.26#33dbc5e35305d0cf5937c896dae8655ca7da95d8" dependencies = [ "frame-support", "frame-system", @@ -5255,7 +5249,7 @@ dependencies = [ [[package]] name = "orml-xcm-support" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" +source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.26#33dbc5e35305d0cf5937c896dae8655ca7da95d8" dependencies = [ "frame-support", "orml-traits", @@ -5269,7 +5263,7 @@ dependencies = [ [[package]] name = "orml-xtokens" version = "0.4.1-dev" -source = "git+https://github.com/zeitgeistpm/open-runtime-module-library?branch=7e1123e-v0.9.19#8bd7166da7797bef16f90993d5872c7c0a280a55" +source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.26#33dbc5e35305d0cf5937c896dae8655ca7da95d8" dependencies = [ "cumulus-primitives-core", "frame-support", @@ -11379,9 +11373,9 @@ checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] name = "tracing" -version = "0.1.34" +version = "0.1.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09" +checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" dependencies = [ "cfg-if 1.0.0", "pin-project-lite 0.2.9", @@ -11402,11 +11396,11 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.26" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f" +checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a" dependencies = [ - "lazy_static", + "once_cell", "valuable", ] @@ -12500,7 +12494,7 @@ dependencies = [ [[package]] name = "xcm-emulator" version = "0.1.0" -source = "git+https://github.com/sea212/xcm-simulator?branch=polkadot-v0.9.19-moonbeam#44f8a9ab874f1ce990c551b4e2429cb4a0e36e04" +source = "git+https://github.com/shaunxw/xcm-simulator?rev=ab5cd6c5fabe6ddda52ed6803ee1bf54c258fefe#ab5cd6c5fabe6ddda52ed6803ee1bf54c258fefe" dependencies = [ "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", @@ -12515,6 +12509,7 @@ dependencies = [ "paste", "polkadot-primitives", "polkadot-runtime-parachains", + "quote", "sp-io", "sp-std", "xcm", @@ -12654,7 +12649,6 @@ name = "zeitgeist-primitives" version = "0.3.6" dependencies = [ "arbitrary", - "bstringify", "frame-support", "frame-system", "orml-currencies", diff --git a/node/Cargo.toml b/node/Cargo.toml index 39bd7866d..84e16cfc7 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -99,7 +99,7 @@ hex-literal = { version = "0.3.4" } jsonrpsee = { version = "0.14.0", features = ["server"] } log = { optional = true, version = "0.4.17" } # TODO(#865): Remove in future Polkadot release -tracing-core = "=0.1.26" +tracing-core = "=0.1.30" # Zeitgeist diff --git a/node/src/chain_spec/battery_station.rs b/node/src/chain_spec/battery_station.rs index 2962afba1..5c37cf1a9 100644 --- a/node/src/chain_spec/battery_station.rs +++ b/node/src/chain_spec/battery_station.rs @@ -28,7 +28,7 @@ use zeitgeist_primitives::{ ztg::{LIQUIDITY_MINING, LIQUIDITY_MINING_PTD}, BASE, }, - types::{AccountId, Asset::ForeignAsset}, + types::{AccountId}, }; #[cfg(feature = "parachain")] @@ -115,10 +115,6 @@ pub(super) fn get_wasm() -> Result<&'static [u8], String> { generate_generic_genesis_function!( battery_station_runtime, - asset_registry: battery_station_runtime::AssetRegistryConfig { - assets: vec![], - last_asset_id: ForeignAsset(0), - }, sudo: battery_station_runtime::SudoConfig { key: Some(root_key_staging_battery_station()), }, diff --git a/node/src/chain_spec/dev.rs b/node/src/chain_spec/dev.rs index 89492b3b8..7acb21fb8 100644 --- a/node/src/chain_spec/dev.rs +++ b/node/src/chain_spec/dev.rs @@ -29,7 +29,7 @@ use sc_service::ChainType; use sp_core::sr25519; use zeitgeist_primitives::{ constants::ztg::{LIQUIDITY_MINING, LIQUIDITY_MINING_PTD}, - types::{Asset::ForeignAsset, Balance}, + types::{Balance}, }; const INITIAL_BALANCE: Balance = Balance::MAX >> 4; @@ -46,10 +46,6 @@ fn authority_keys_from_seed( generate_generic_genesis_function! { battery_station_runtime, - asset_registry: battery_station_runtime::AssetRegistryConfig { - assets: vec![], - last_asset_id: ForeignAsset(0), - }, sudo: battery_station_runtime::SudoConfig { key: Some(get_account_id_from_seed::("Alice")), }, diff --git a/node/src/chain_spec/mod.rs b/node/src/chain_spec/mod.rs index ed0a69156..fa2ebaa97 100644 --- a/node/src/chain_spec/mod.rs +++ b/node/src/chain_spec/mod.rs @@ -108,6 +108,8 @@ macro_rules! generate_generic_genesis_function { members: vec![].try_into().unwrap(), phantom: Default::default(), }, + #[cfg(feature = "parachain")] + asset_registry: Default::default(), #[cfg(not(feature = "parachain"))] aura: $runtime::AuraConfig { authorities: acs.initial_authorities.iter().map(|x| (x.0.clone())).collect(), diff --git a/runtime/battery-station/Cargo.toml b/runtime/battery-station/Cargo.toml index a11f7295c..c0b8d2407 100644 --- a/runtime/battery-station/Cargo.toml +++ b/runtime/battery-station/Cargo.toml @@ -86,17 +86,17 @@ hex-literal = { default-features = false, optional = true, version = "0.3.4" } log = { version = "0.4.17", default-features = false, optional = true } # XCM -kusama-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -orml-asset-registry = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-unknown-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-xtokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -pallet-xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -polkadot-primitives = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -polkadot-runtime-parachains = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -xcm-builder = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -xcm-executor = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +kusama-runtime = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +orml-asset-registry = { branch = "polkadot-v0.9.26", default-features = false, git = "https://github.com/open-web3-stack/open-runtime-module-library", optional = true } +orml-unknown-tokens = { branch = "polkadot-v0.9.26", default-features = false, git = "https://github.com/open-web3-stack/open-runtime-module-library", optional = true } +orml-xcm-support = { branch = "polkadot-v0.9.26", default-features = false, git = "https://github.com/open-web3-stack/open-runtime-module-library", optional = true } +orml-xtokens = { branch = "polkadot-v0.9.26", default-features = false, git = "https://github.com/open-web3-stack/open-runtime-module-library", optional = true } +pallet-xcm = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +polkadot-primitives = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +polkadot-runtime-parachains = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +xcm = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +xcm-builder = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +xcm-executor = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } # Zeitgeist @@ -116,7 +116,7 @@ zrml-swaps-runtime-api = { default-features = false, path = "../../zrml/swaps/ru [dev-dependencies] sp-io = { branch = "polkadot-v0.9.26", git = "https://github.com/paritytech/substrate" } -xcm-emulator = { rev = "0460d04c798028e7bef82c907082e11753ed173b", git = "https://github.com/shaunxw/xcm-simulator" } +xcm-emulator = { rev = "ab5cd6c5fabe6ddda52ed6803ee1bf54c258fefe", git = "https://github.com/shaunxw/xcm-simulator" } [features] default = ["std"] diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs index 3ce4802da..96249f370 100644 --- a/runtime/battery-station/src/integration_tests/xcm/setup.rs +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -206,5 +206,5 @@ pub(super) fn zeitgeist_parachain_account() -> AccountId { fn parachain_account(id: u32) -> AccountId { use sp_runtime::traits::AccountIdConversion; - polkadot_parachain::primitives::Sibling::from(id).into_account() + polkadot_parachain::primitives::Sibling::from(id).into_account_truncating() } diff --git a/runtime/battery-station/src/parachain_params.rs b/runtime/battery-station/src/parachain_params.rs index 05ddeddf0..1d5092151 100644 --- a/runtime/battery-station/src/parachain_params.rs +++ b/runtime/battery-station/src/parachain_params.rs @@ -23,7 +23,7 @@ #![cfg(feature = "parachain")] use super::{parameters::MAXIMUM_BLOCK_WEIGHT, Origin, ParachainInfo}; -use frame_support::{parameter_types, traits::Get, weights::Weight}; +use frame_support::{parameter_types, weights::Weight}; use orml_traits::parameter_type_with_key; use sp_runtime::{Perbill, Percent}; use xcm::latest::{prelude::X1, Junction::Parachain, MultiLocation, NetworkId}; diff --git a/runtime/battery-station/src/parameters.rs b/runtime/battery-station/src/parameters.rs index 11b8e1883..c5403f65f 100644 --- a/runtime/battery-station/src/parameters.rs +++ b/runtime/battery-station/src/parameters.rs @@ -313,7 +313,7 @@ parameter_types! { /// Pallet identifier, mainly used for named balance reserves. pub const TreasuryPalletId: PalletId = TREASURY_PALLET_ID; /// Treasury account. - pub ZeitgeistTreasuryAccount: AccountId = TreasuryPalletId::get().into_account(); + pub ZeitgeistTreasuryAccount: AccountId = TreasuryPalletId::get().into_account_truncating(); // Bounties /// The amount held on deposit for placing a bounty proposal. diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index aea0ecbad..32b3331de 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -22,8 +22,7 @@ use crate::{ UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; -use alloc::vec::Vec; -use frame_support::{match_types, parameter_types, traits::Everything}; +use frame_support::{parameter_types, traits::Everything, WeakBoundedVec}; use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{location::AbsoluteReserveProvider, MultiCurrency}; use orml_xcm_support::{ @@ -35,7 +34,7 @@ use sp_runtime::traits::Convert; use xcm::{ latest::{ prelude::{AccountId32, AssetId, Concrete, GeneralKey, MultiAsset, NetworkId, X1, X2}, - BodyId, Junction, Junctions, MultiLocation, + Junction, MultiLocation, }, opaque::latest::Fungibility::Fungible, }; @@ -308,5 +307,5 @@ pub type XcmRouter = ( #[inline] pub(crate) fn general_key(key: &[u8]) -> Junction { - GeneralKey(Vec::from(key)) + GeneralKey(WeakBoundedVec::force_from(key.to_vec(), None)) } diff --git a/runtime/zeitgeist/Cargo.toml b/runtime/zeitgeist/Cargo.toml index 16677af30..eadfa3d5c 100644 --- a/runtime/zeitgeist/Cargo.toml +++ b/runtime/zeitgeist/Cargo.toml @@ -84,16 +84,17 @@ hex-literal = { default-features = false, optional = true, version = "0.3.4" } log = { version = "0.4.17", default-features = false, optional = true } # XCM -kusama-runtime = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -orml-asset-registry = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-unknown-tokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-xcm-support = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -orml-xtokens = { branch = "7e1123e-v0.9.19", default-features = false, git = "https://github.com/zeitgeistpm/open-runtime-module-library", optional = true } -pallet-xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -polkadot-primitives = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -polkadot-runtime-parachains = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -xcm = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } -xcm-builder = { branch = "moonbeam-polkadot-v0.9.19", default-features = false, git = "https://github.com/purestake/polkadot", optional = true } +kusama-runtime = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +orml-asset-registry = { branch = "polkadot-v0.9.26", default-features = false, git = "https://github.com/open-web3-stack/open-runtime-module-library", optional = true } +orml-unknown-tokens = { branch = "polkadot-v0.9.26", default-features = false, git = "https://github.com/open-web3-stack/open-runtime-module-library", optional = true } +orml-xcm-support = { branch = "polkadot-v0.9.26", default-features = false, git = "https://github.com/open-web3-stack/open-runtime-module-library", optional = true } +orml-xtokens = { branch = "polkadot-v0.9.26", default-features = false, git = "https://github.com/open-web3-stack/open-runtime-module-library", optional = true } +pallet-xcm = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +polkadot-primitives = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +polkadot-runtime-parachains = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +xcm = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +xcm-builder = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } +xcm-executor = { branch = "release-v0.9.26", default-features = false, git = "https://github.com/paritytech/polkadot", optional = true } # Zeitgeist @@ -113,7 +114,7 @@ zrml-swaps-runtime-api = { default-features = false, path = "../../zrml/swaps/ru [dev-dependencies] sp-io = { branch = "polkadot-v0.9.26", git = "https://github.com/paritytech/substrate" } -xcm-emulator = { rev = "0460d04c798028e7bef82c907082e11753ed173b", git = "https://github.com/shaunxw/xcm-simulator" } +xcm-emulator = { rev = "ab5cd6c5fabe6ddda52ed6803ee1bf54c258fefe", git = "https://github.com/shaunxw/xcm-simulator" } [features] default = ["std"] diff --git a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs index bf09038e5..084437644 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs @@ -206,5 +206,5 @@ pub(super) fn zeitgeist_parachain_account() -> AccountId { fn parachain_account(id: u32) -> AccountId { use sp_runtime::traits::AccountIdConversion; - polkadot_parachain::primitives::Sibling::from(id).into_account() + polkadot_parachain::primitives::Sibling::from(id).into_account_truncating() } diff --git a/runtime/zeitgeist/src/parachain_params.rs b/runtime/zeitgeist/src/parachain_params.rs index 0d0afffda..3e80d851c 100644 --- a/runtime/zeitgeist/src/parachain_params.rs +++ b/runtime/zeitgeist/src/parachain_params.rs @@ -23,7 +23,7 @@ #![cfg(feature = "parachain")] use super::{parameters::MAXIMUM_BLOCK_WEIGHT, Origin, ParachainInfo}; -use frame_support::{parameter_types, traits::Get, weights::Weight}; +use frame_support::{parameter_types, weights::Weight}; use orml_traits::parameter_type_with_key; use sp_runtime::{Perbill, Percent}; use xcm::latest::{prelude::X1, Junction::Parachain, MultiLocation, NetworkId}; diff --git a/runtime/zeitgeist/src/parameters.rs b/runtime/zeitgeist/src/parameters.rs index c9aad847e..76cf826a8 100644 --- a/runtime/zeitgeist/src/parameters.rs +++ b/runtime/zeitgeist/src/parameters.rs @@ -313,7 +313,7 @@ parameter_types! { /// Pallet identifier, mainly used for named balance reserves. DO NOT CHANGE. pub const TreasuryPalletId: PalletId = TREASURY_PALLET_ID; /// Treasury account. - pub ZeitgeistTreasuryAccount: AccountId = TreasuryPalletId::get().into_account(); + pub ZeitgeistTreasuryAccount: AccountId = TreasuryPalletId::get().into_account_truncating(); // Bounties /// The amount held on deposit for placing a bounty proposal. diff --git a/runtime/zeitgeist/src/xcm_config/config.rs b/runtime/zeitgeist/src/xcm_config/config.rs index d861d640e..49a82c8af 100644 --- a/runtime/zeitgeist/src/xcm_config/config.rs +++ b/runtime/zeitgeist/src/xcm_config/config.rs @@ -22,8 +22,7 @@ use crate::{ UnitWeightCost, UnknownTokens, XcmpQueue, ZeitgeistTreasuryAccount, }; -use alloc::vec::Vec; -use frame_support::{parameter_types, traits::Everything}; +use frame_support::{parameter_types, traits::Everything, WeakBoundedVec}; use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{location::AbsoluteReserveProvider, MultiCurrency}; use orml_xcm_support::{ @@ -308,5 +307,5 @@ pub type XcmRouter = ( #[inline] pub(crate) fn general_key(key: &[u8]) -> Junction { - GeneralKey(Vec::from(key)) + GeneralKey(WeakBoundedVec::force_from(key.to_vec(), None)) } diff --git a/zrml/market-commons/src/migrations.rs b/zrml/market-commons/src/migrations.rs index a7f570674..4205cab10 100644 --- a/zrml/market-commons/src/migrations.rs +++ b/zrml/market-commons/src/migrations.rs @@ -16,7 +16,7 @@ // along with Zeitgeist. If not, see . use crate::{Config, Pallet}; -use alloc::{string::ToString, vec::Vec}; +use alloc::{vec::Vec}; use frame_support::{ log, migration::{put_storage_value, storage_iter}, From 1d31ae0a3de4acc5caee3f63e4e2fd2e058c501b Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 24 Nov 2022 21:40:06 +0100 Subject: [PATCH 57/59] Satisfy cargo fmt and taplo --- node/src/chain_spec/battery_station.rs | 2 +- node/src/chain_spec/dev.rs | 2 +- primitives/src/constants.rs | 2 +- .../src/integration_tests/xcm/test_net.rs | 4 +--- .../src/integration_tests/xcm/tests/transfers.rs | 12 ++++++++---- runtime/battery-station/src/xcm_config/config.rs | 2 +- .../zeitgeist/src/integration_tests/xcm/test_net.rs | 4 +--- .../src/integration_tests/xcm/tests/transfers.rs | 12 ++++++++---- runtime/zeitgeist/src/xcm_config/config.rs | 2 +- zrml/market-commons/src/migrations.rs | 2 +- 10 files changed, 24 insertions(+), 20 deletions(-) diff --git a/node/src/chain_spec/battery_station.rs b/node/src/chain_spec/battery_station.rs index 5c37cf1a9..7c8835db4 100644 --- a/node/src/chain_spec/battery_station.rs +++ b/node/src/chain_spec/battery_station.rs @@ -28,7 +28,7 @@ use zeitgeist_primitives::{ ztg::{LIQUIDITY_MINING, LIQUIDITY_MINING_PTD}, BASE, }, - types::{AccountId}, + types::AccountId, }; #[cfg(feature = "parachain")] diff --git a/node/src/chain_spec/dev.rs b/node/src/chain_spec/dev.rs index 7acb21fb8..319b25403 100644 --- a/node/src/chain_spec/dev.rs +++ b/node/src/chain_spec/dev.rs @@ -29,7 +29,7 @@ use sc_service::ChainType; use sp_core::sr25519; use zeitgeist_primitives::{ constants::ztg::{LIQUIDITY_MINING, LIQUIDITY_MINING_PTD}, - types::{Balance}, + types::Balance, }; const INITIAL_BALANCE: Balance = Balance::MAX >> 4; diff --git a/primitives/src/constants.rs b/primitives/src/constants.rs index 88eccd73d..5675bbc16 100644 --- a/primitives/src/constants.rs +++ b/primitives/src/constants.rs @@ -107,4 +107,4 @@ pub const SWAPS_PALLET_ID: PalletId = PalletId(*b"zge/swap"); // Treasury /// Pallet identifier, used to derive treasury account -pub const TREASURY_PALLET_ID: PalletId = PalletId(*b"zge/tsry"); \ No newline at end of file +pub const TREASURY_PALLET_ID: PalletId = PalletId(*b"zge/tsry"); diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index 55432256d..4c9957b9c 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -77,9 +77,7 @@ pub(super) fn relay_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); pallet_balances::GenesisConfig:: { - balances: vec![ - (AccountId::from(ALICE), ksm(2002)), - ], + balances: vec![(AccountId::from(ALICE), ksm(2002))], } .assimilate_storage(&mut t) .unwrap(); diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index 6bd16f58c..c9a966ea8 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -19,8 +19,9 @@ use crate::{ integration_tests::xcm::{ setup::{ - ksm, register_foreign_parent, register_foreign_ztg, sibling_parachain_account, zeitgeist_parachain_account, - ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, + ksm, register_foreign_parent, register_foreign_ztg, sibling_parachain_account, + zeitgeist_parachain_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_ZTG_ID, + PARA_ID_SIBLING, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, @@ -118,7 +119,10 @@ fn transfer_ztg_sibling_to_zeitgeist() { treasury_initial_balance = Balances::free_balance(ZeitgeistTreasuryAccount::get()); assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); - assert_eq!(Balances::free_balance(&sibling_parachain_account()), sibling_sovereign_initial_balance); + assert_eq!( + Balances::free_balance(&sibling_parachain_account()), + sibling_sovereign_initial_balance + ); }); Sibling::execute_with(|| { @@ -203,7 +207,7 @@ fn transfer_ksm_from_relay_chain() { #[test] fn transfer_ksm_to_relay_chain() { TestNet::reset(); - + let transfer_amount: Balance = ksm(1); transfer_ksm_from_relay_chain(); diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 32b3331de..4fb6c1c58 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -214,7 +214,7 @@ impl xcm_executor::traits::Convert for AssetConvert { if &key[..] == battery_station::KEY { return Ok(CurrencyId::Ztg); } - + Err(location) } MultiLocation { diff --git a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs index a4d0ce9d7..c34dc9f47 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs @@ -77,9 +77,7 @@ pub(super) fn relay_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); pallet_balances::GenesisConfig:: { - balances: vec![ - (AccountId::from(ALICE), ksm(2002)), - ], + balances: vec![(AccountId::from(ALICE), ksm(2002))], } .assimilate_storage(&mut t) .unwrap(); diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs index f87f77c29..196283fc7 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs @@ -19,8 +19,9 @@ use crate::{ integration_tests::xcm::{ setup::{ - ksm, register_foreign_parent, register_foreign_ztg, sibling_parachain_account, zeitgeist_parachain_account, - ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_ZTG_ID, PARA_ID_SIBLING, + ksm, register_foreign_parent, register_foreign_ztg, sibling_parachain_account, + zeitgeist_parachain_account, ztg, ALICE, BOB, FOREIGN_PARENT_ID, FOREIGN_ZTG_ID, + PARA_ID_SIBLING, }, test_net::{KusamaNet, Sibling, TestNet, Zeitgeist}, }, @@ -118,7 +119,10 @@ fn transfer_ztg_sibling_to_zeitgeist() { treasury_initial_balance = Balances::free_balance(ZeitgeistTreasuryAccount::get()); assert_eq!(Balances::free_balance(&ALICE.into()), alice_initial_balance); - assert_eq!(Balances::free_balance(&sibling_parachain_account()), sibling_sovereign_initial_balance); + assert_eq!( + Balances::free_balance(&sibling_parachain_account()), + sibling_sovereign_initial_balance + ); }); Sibling::execute_with(|| { @@ -182,7 +186,7 @@ fn transfer_ksm_from_relay_chain() { KusamaNet::execute_with(|| { let initial_balance = kusama_runtime::Balances::free_balance(&ALICE.into()); assert!(initial_balance >= transfer_amount); - + assert_ok!(kusama_runtime::XcmPallet::reserve_transfer_assets( kusama_runtime::Origin::signed(ALICE.into()), Box::new(Parachain(zeitgeist::ID).into().into()), diff --git a/runtime/zeitgeist/src/xcm_config/config.rs b/runtime/zeitgeist/src/xcm_config/config.rs index 49a82c8af..0064e330d 100644 --- a/runtime/zeitgeist/src/xcm_config/config.rs +++ b/runtime/zeitgeist/src/xcm_config/config.rs @@ -214,7 +214,7 @@ impl xcm_executor::traits::Convert for AssetConvert { if &key[..] == zeitgeist::KEY { return Ok(CurrencyId::Ztg); } - + Err(location) } MultiLocation { diff --git a/zrml/market-commons/src/migrations.rs b/zrml/market-commons/src/migrations.rs index 4205cab10..6218c958d 100644 --- a/zrml/market-commons/src/migrations.rs +++ b/zrml/market-commons/src/migrations.rs @@ -16,7 +16,7 @@ // along with Zeitgeist. If not, see . use crate::{Config, Pallet}; -use alloc::{vec::Vec}; +use alloc::vec::Vec; use frame_support::{ log, migration::{put_storage_value, storage_iter}, From e153330bfa341cffd92500150e29c7a821ad5504 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 24 Nov 2022 21:50:10 +0100 Subject: [PATCH 58/59] Update XCM weight in tests --- .../src/integration_tests/xcm/tests/transfers.rs | 10 +++++----- .../src/integration_tests/xcm/tests/transfers.rs | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index c9a966ea8..e7f7febd6 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -89,7 +89,7 @@ fn transfer_ztg_to_sibling() { assert_eq!(current_balance, transfer_amount - ztg_fee()); // Sanity check for the actual amount BOB ends up with - assert_eq!(current_balance, 49_936_000_000); + assert_eq!(current_balance, 49_907_304_000); // Verify that fees (of foreign currency) have been put into treasury assert_eq!( @@ -236,7 +236,7 @@ fn transfer_ksm_to_relay_chain() { }); KusamaNet::execute_with(|| { - assert_eq!(kusama_runtime::Balances::free_balance(&BOB.into()), 999834059328); + assert_eq!(kusama_runtime::Balances::free_balance(&BOB.into()), 999_988_476_752); }); } @@ -306,7 +306,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { assert_eq!(current_balance, transfer_amount - custom_fee); // Sanity check for the actual amount BOB ends up with - assert_eq!(current_balance, 49_360_000_000); + assert_eq!(current_balance, 49_073_040_000); // Verify that fees (of foreign currency) have been put into treasury assert_eq!( @@ -318,8 +318,8 @@ fn transfer_ztg_to_sibling_with_custom_fee() { #[test] fn test_total_fee() { - assert_eq!(ztg_fee(), 64000000); - assert_eq!(ksm_fee(), 6400000000); + assert_eq!(ztg_fee(), 92_696_000); + assert_eq!(ksm_fee(), 9_269_600_000); } #[inline] diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs index 196283fc7..32c504f52 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs @@ -89,7 +89,7 @@ fn transfer_ztg_to_sibling() { assert_eq!(current_balance, transfer_amount - ztg_fee()); // Sanity check for the actual amount BOB ends up with - assert_eq!(current_balance, 49_936_000_000); + assert_eq!(current_balance, 49_907_304_000); // Verify that fees (of foreign currency) have been put into treasury assert_eq!( @@ -236,7 +236,7 @@ fn transfer_ksm_to_relay_chain() { }); KusamaNet::execute_with(|| { - assert_eq!(kusama_runtime::Balances::free_balance(&BOB.into()), 999_834_059_328); + assert_eq!(kusama_runtime::Balances::free_balance(&BOB.into()), 999_988_476_752); }); } @@ -306,7 +306,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { assert_eq!(current_balance, transfer_amount - custom_fee); // Sanity check for the actual amount BOB ends up with - assert_eq!(current_balance, 49_360_000_000); + assert_eq!(current_balance, 49_073_040_000); // Verify that fees (of foreign currency) have been put into treasury assert_eq!( @@ -318,8 +318,8 @@ fn transfer_ztg_to_sibling_with_custom_fee() { #[test] fn test_total_fee() { - assert_eq!(ztg_fee(), 64_000_000); - assert_eq!(ksm_fee(), 6_400_000_000); + assert_eq!(ztg_fee(), 92_696_000); + assert_eq!(ksm_fee(), 9_269_600_000); } #[inline] From c003dda306328409198658843fd270bf76e027c4 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Thu, 24 Nov 2022 22:03:57 +0100 Subject: [PATCH 59/59] Satisfy Clippy --- .../battery-station/src/integration_tests/xcm/setup.rs | 9 ++------- .../src/integration_tests/xcm/test_net.rs | 4 +--- .../src/integration_tests/xcm/tests/transfers.rs | 6 +++--- runtime/battery-station/src/xcm_config/config.rs | 4 ++-- runtime/battery-station/src/xcm_config/fees.rs | 4 ++-- runtime/zeitgeist/src/integration_tests/xcm/setup.rs | 9 ++------- runtime/zeitgeist/src/integration_tests/xcm/test_net.rs | 4 +--- .../src/integration_tests/xcm/tests/transfers.rs | 6 +++--- runtime/zeitgeist/src/xcm_config/config.rs | 4 ++-- runtime/zeitgeist/src/xcm_config/fees.rs | 4 ++-- zrml/market-commons/src/migrations.rs | 2 +- 11 files changed, 21 insertions(+), 35 deletions(-) diff --git a/runtime/battery-station/src/integration_tests/xcm/setup.rs b/runtime/battery-station/src/integration_tests/xcm/setup.rs index 96249f370..510c5b58d 100644 --- a/runtime/battery-station/src/integration_tests/xcm/setup.rs +++ b/runtime/battery-station/src/integration_tests/xcm/setup.rs @@ -172,11 +172,6 @@ pub(super) fn ztg(amount: Balance) -> Balance { amount * dollar(10) } -#[inline] -pub(super) fn sibling(amount: Balance) -> Balance { - foreign(amount, 10) -} - #[inline] pub(super) fn ksm(amount: Balance) -> Balance { foreign(amount, 12) @@ -189,12 +184,12 @@ pub(super) fn foreign(amount: Balance, decimals: u32) -> Balance { #[inline] pub(super) fn dollar(decimals: u32) -> Balance { - 10u128.saturating_pow(decimals.into()) + 10u128.saturating_pow(decimals) } #[inline] pub(super) fn sibling_parachain_account() -> AccountId { - parachain_account(PARA_ID_SIBLING.into()) + parachain_account(PARA_ID_SIBLING) } #[inline] diff --git a/runtime/battery-station/src/integration_tests/xcm/test_net.rs b/runtime/battery-station/src/integration_tests/xcm/test_net.rs index 4c9957b9c..8d6d8351d 100644 --- a/runtime/battery-station/src/integration_tests/xcm/test_net.rs +++ b/runtime/battery-station/src/integration_tests/xcm/test_net.rs @@ -19,14 +19,12 @@ use crate::{ parameters::ZeitgeistTreasuryAccount, xcm_config::config::battery_station, AccountId, CurrencyId, DmpQueue, Origin, Runtime, XcmpQueue, }; -use cumulus_primitives_core::ParaId; use frame_support::{traits::GenesisBuild, weights::Weight}; use polkadot_primitives::v2::{BlockNumber, MAX_CODE_SIZE, MAX_POV_SIZE}; use polkadot_runtime_parachains::configuration::HostConfiguration; -use sp_runtime::traits::AccountIdConversion; use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; -use super::setup::{ksm, sibling, ztg, ExtBuilder, ALICE, FOREIGN_PARENT_ID, PARA_ID_SIBLING}; +use super::setup::{ksm, ztg, ExtBuilder, ALICE, FOREIGN_PARENT_ID, PARA_ID_SIBLING}; decl_test_relay_chain! { pub struct KusamaNet { diff --git a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs index e7f7febd6..ffa956c08 100644 --- a/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/battery-station/src/integration_tests/xcm/tests/transfers.rs @@ -67,7 +67,7 @@ fn transfer_ztg_to_sibling() { 1, X2( Parachain(PARA_ID_SIBLING), - Junction::AccountId32 { network: NetworkId::Any, id: BOB.into() } + Junction::AccountId32 { network: NetworkId::Any, id: BOB } ) ) .into() @@ -137,7 +137,7 @@ fn transfer_ztg_sibling_to_zeitgeist() { 1, X2( Parachain(battery_station::ID), - Junction::AccountId32 { network: NetworkId::Any, id: ALICE.into() } + Junction::AccountId32 { network: NetworkId::Any, id: ALICE } ) ) .into() @@ -283,7 +283,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { 1, X2( Parachain(PARA_ID_SIBLING), - Junction::AccountId32 { network: NetworkId::Any, id: BOB.into() } + Junction::AccountId32 { network: NetworkId::Any, id: BOB } ) ) .into() diff --git a/runtime/battery-station/src/xcm_config/config.rs b/runtime/battery-station/src/xcm_config/config.rs index 4fb6c1c58..4e09b741c 100644 --- a/runtime/battery-station/src/xcm_config/config.rs +++ b/runtime/battery-station/src/xcm_config/config.rs @@ -128,9 +128,9 @@ impl TakeRevenue for ToTreasury { fn take_revenue(revenue: MultiAsset) { use xcm_executor::traits::Convert; - if let MultiAsset { id: Concrete(location), fun: Fungible(amount) } = revenue.clone() { + if let MultiAsset { id: Concrete(location), fun: Fungible(amount) } = revenue { if let Ok(asset_id) = - >::convert(location.clone()) + >::convert(location) { let _ = AssetManager::deposit(asset_id, &ZeitgeistTreasuryAccount::get(), amount); } diff --git a/runtime/battery-station/src/xcm_config/fees.rs b/runtime/battery-station/src/xcm_config/fees.rs index e5ba9d6ea..b70484d97 100644 --- a/runtime/battery-station/src/xcm_config/fees.rs +++ b/runtime/battery-station/src/xcm_config/fees.rs @@ -66,11 +66,11 @@ impl< > orml_traits::FixedConversionRateProvider for FixedConversionRateProvider { fn get_fee_per_second(location: &MultiLocation) -> Option { - let metadata = AssetRegistry::metadata_by_location(&location)?; + let metadata = AssetRegistry::metadata_by_location(location)?; let default_per_second = default_per_second(metadata.decimals); if let Some(fee_factor) = metadata.additional.xcm.fee_factor { - let base = 10u128.checked_pow(metadata.decimals.into())?; + let base = 10u128.checked_pow(metadata.decimals)?; bmul(default_per_second, fee_factor, base) } else { Some(default_per_second) diff --git a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs index 084437644..e3da82f91 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/setup.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/setup.rs @@ -172,11 +172,6 @@ pub(super) fn ztg(amount: Balance) -> Balance { amount * dollar(10) } -#[inline] -pub(super) fn sibling(amount: Balance) -> Balance { - foreign(amount, 10) -} - #[inline] pub(super) fn ksm(amount: Balance) -> Balance { foreign(amount, 12) @@ -189,12 +184,12 @@ pub(super) fn foreign(amount: Balance, decimals: u32) -> Balance { #[inline] pub(super) fn dollar(decimals: u32) -> Balance { - 10u128.saturating_pow(decimals.into()) + 10u128.saturating_pow(decimals) } #[inline] pub(super) fn sibling_parachain_account() -> AccountId { - parachain_account(PARA_ID_SIBLING.into()) + parachain_account(PARA_ID_SIBLING) } #[inline] diff --git a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs index c34dc9f47..ead4ca132 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/test_net.rs @@ -19,14 +19,12 @@ use crate::{ parameters::ZeitgeistTreasuryAccount, xcm_config::config::zeitgeist, AccountId, CurrencyId, DmpQueue, Origin, Runtime, XcmpQueue, }; -use cumulus_primitives_core::ParaId; use frame_support::{traits::GenesisBuild, weights::Weight}; use polkadot_primitives::v2::{BlockNumber, MAX_CODE_SIZE, MAX_POV_SIZE}; use polkadot_runtime_parachains::configuration::HostConfiguration; -use sp_runtime::traits::AccountIdConversion; use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; -use super::setup::{ksm, sibling, ztg, ExtBuilder, ALICE, FOREIGN_PARENT_ID, PARA_ID_SIBLING}; +use super::setup::{ksm, ztg, ExtBuilder, ALICE, FOREIGN_PARENT_ID, PARA_ID_SIBLING}; decl_test_relay_chain! { pub struct KusamaNet { diff --git a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs index 32c504f52..25543b4e1 100644 --- a/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs +++ b/runtime/zeitgeist/src/integration_tests/xcm/tests/transfers.rs @@ -67,7 +67,7 @@ fn transfer_ztg_to_sibling() { 1, X2( Parachain(PARA_ID_SIBLING), - Junction::AccountId32 { network: NetworkId::Any, id: BOB.into() } + Junction::AccountId32 { network: NetworkId::Any, id: BOB } ) ) .into() @@ -137,7 +137,7 @@ fn transfer_ztg_sibling_to_zeitgeist() { 1, X2( Parachain(zeitgeist::ID), - Junction::AccountId32 { network: NetworkId::Any, id: ALICE.into() } + Junction::AccountId32 { network: NetworkId::Any, id: ALICE } ) ) .into() @@ -283,7 +283,7 @@ fn transfer_ztg_to_sibling_with_custom_fee() { 1, X2( Parachain(PARA_ID_SIBLING), - Junction::AccountId32 { network: NetworkId::Any, id: BOB.into() } + Junction::AccountId32 { network: NetworkId::Any, id: BOB } ) ) .into() diff --git a/runtime/zeitgeist/src/xcm_config/config.rs b/runtime/zeitgeist/src/xcm_config/config.rs index 0064e330d..8520f5a86 100644 --- a/runtime/zeitgeist/src/xcm_config/config.rs +++ b/runtime/zeitgeist/src/xcm_config/config.rs @@ -128,9 +128,9 @@ impl TakeRevenue for ToTreasury { fn take_revenue(revenue: MultiAsset) { use xcm_executor::traits::Convert; - if let MultiAsset { id: Concrete(location), fun: Fungible(amount) } = revenue.clone() { + if let MultiAsset { id: Concrete(location), fun: Fungible(amount) } = revenue { if let Ok(asset_id) = - >::convert(location.clone()) + >::convert(location) { let _ = AssetManager::deposit(asset_id, &ZeitgeistTreasuryAccount::get(), amount); } diff --git a/runtime/zeitgeist/src/xcm_config/fees.rs b/runtime/zeitgeist/src/xcm_config/fees.rs index e5ba9d6ea..b70484d97 100644 --- a/runtime/zeitgeist/src/xcm_config/fees.rs +++ b/runtime/zeitgeist/src/xcm_config/fees.rs @@ -66,11 +66,11 @@ impl< > orml_traits::FixedConversionRateProvider for FixedConversionRateProvider { fn get_fee_per_second(location: &MultiLocation) -> Option { - let metadata = AssetRegistry::metadata_by_location(&location)?; + let metadata = AssetRegistry::metadata_by_location(location)?; let default_per_second = default_per_second(metadata.decimals); if let Some(fee_factor) = metadata.additional.xcm.fee_factor { - let base = 10u128.checked_pow(metadata.decimals.into())?; + let base = 10u128.checked_pow(metadata.decimals)?; bmul(default_per_second, fee_factor, base) } else { Some(default_per_second) diff --git a/zrml/market-commons/src/migrations.rs b/zrml/market-commons/src/migrations.rs index 6218c958d..a7f570674 100644 --- a/zrml/market-commons/src/migrations.rs +++ b/zrml/market-commons/src/migrations.rs @@ -16,7 +16,7 @@ // along with Zeitgeist. If not, see . use crate::{Config, Pallet}; -use alloc::vec::Vec; +use alloc::{string::ToString, vec::Vec}; use frame_support::{ log, migration::{put_storage_value, storage_iter},