From 3d279d9d46fed74bd6a3aa171202173b4b485d61 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 13:43:43 +0200 Subject: [PATCH 01/16] Update zrml-asset-router (#1321) --- primitives/src/constants/mock.rs | 2 +- primitives/src/math/checked_ops_res.rs | 2 +- primitives/src/math/fixed.rs | 3 +- primitives/src/traits.rs | 2 - .../src/traits/hybrid_router_amm_api.rs | 2 +- .../src/traits/hybrid_router_orderbook_api.rs | 2 +- .../src/traits/market_commons_pallet_api.rs | 8 +- primitives/src/traits/swaps.rs | 3 +- primitives/src/traits/weights.rs | 60 --------- primitives/src/types.rs | 2 +- zrml/asset-router/src/lib.rs | 26 ++-- zrml/asset-router/src/mock.rs | 38 +++--- zrml/asset-router/src/pallet_impl/inspect.rs | 89 +++---------- .../src/pallet_impl/multi_currency.rs | 124 +++++++++++++----- .../pallet_impl/multi_lockable_currency.rs | 2 +- .../src/pallet_impl/unbalanced.rs | 74 +++++++---- zrml/asset-router/src/tests/inspect.rs | 41 ++++-- zrml/asset-router/src/tests/unbalanced.rs | 123 +++++++++++------ 18 files changed, 324 insertions(+), 279 deletions(-) delete mode 100644 primitives/src/traits/weights.rs diff --git a/primitives/src/constants/mock.rs b/primitives/src/constants/mock.rs index 47530ebea..9cf150d8a 100644 --- a/primitives/src/constants/mock.rs +++ b/primitives/src/constants/mock.rs @@ -191,7 +191,7 @@ parameter_type_with_key! { // System parameter_types! { - pub const BlockHashCount: u64 = 250; + pub const BlockHashCount: u32 = 250; } // Time diff --git a/primitives/src/math/checked_ops_res.rs b/primitives/src/math/checked_ops_res.rs index 1265a6b2b..13cd420a6 100644 --- a/primitives/src/math/checked_ops_res.rs +++ b/primitives/src/math/checked_ops_res.rs @@ -15,12 +15,12 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use frame_support::dispatch::DispatchError; use num_traits::{checked_pow, One}; use sp_arithmetic::{ traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedRem, CheckedSub}, ArithmeticError, }; +use sp_runtime::DispatchError; pub trait CheckedAddRes where diff --git a/primitives/src/math/fixed.rs b/primitives/src/math/fixed.rs index cf9f5e942..fe262980e 100644 --- a/primitives/src/math/fixed.rs +++ b/primitives/src/math/fixed.rs @@ -31,11 +31,12 @@ use alloc::{ }; use core::{cmp::Ordering, convert::TryFrom, marker::PhantomData}; use fixed::{traits::Fixed, ParseFixedError}; -use frame_support::{dispatch::DispatchError, ensure}; +use frame_support::ensure; use sp_arithmetic::{ traits::{AtLeast32BitUnsigned, Zero}, ArithmeticError, }; +use sp_runtime::DispatchError; /// Trait for safely obtaining constants converted to generic types in a Substrate context. pub trait BaseProvider { diff --git a/primitives/src/traits.rs b/primitives/src/traits.rs index 7d7bde094..d4e987ce8 100644 --- a/primitives/src/traits.rs +++ b/primitives/src/traits.rs @@ -27,7 +27,6 @@ mod market_commons_pallet_api; mod market_id; mod market_transition_api; mod swaps; -mod weights; mod zeitgeist_asset; pub use complete_set_operations_api::*; @@ -41,5 +40,4 @@ pub use market_commons_pallet_api::*; pub use market_id::*; pub use market_transition_api::*; pub use swaps::*; -pub use weights::*; pub use zeitgeist_asset::*; diff --git a/primitives/src/traits/hybrid_router_amm_api.rs b/primitives/src/traits/hybrid_router_amm_api.rs index 50e6a7b05..677278e57 100644 --- a/primitives/src/traits/hybrid_router_amm_api.rs +++ b/primitives/src/traits/hybrid_router_amm_api.rs @@ -16,7 +16,7 @@ // along with Zeitgeist. If not, see . use crate::hybrid_router_api_types::{AmmSoftFail, AmmTrade, ApiError}; -use frame_support::dispatch::DispatchError; +use sp_runtime::DispatchError; /// A type alias for the return struct of AMM buy and sell. type AmmTradeOf = AmmTrade<::Balance>; diff --git a/primitives/src/traits/hybrid_router_orderbook_api.rs b/primitives/src/traits/hybrid_router_orderbook_api.rs index 9af727631..968dcd31c 100644 --- a/primitives/src/traits/hybrid_router_orderbook_api.rs +++ b/primitives/src/traits/hybrid_router_orderbook_api.rs @@ -15,7 +15,7 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use frame_support::dispatch::DispatchError; +use sp_runtime::DispatchError; use crate::hybrid_router_api_types::{ApiError, OrderbookSoftFail, OrderbookTrade}; diff --git a/primitives/src/traits/market_commons_pallet_api.rs b/primitives/src/traits/market_commons_pallet_api.rs index 3b5293d38..77e347d87 100644 --- a/primitives/src/traits/market_commons_pallet_api.rs +++ b/primitives/src/traits/market_commons_pallet_api.rs @@ -22,14 +22,18 @@ use crate::{ traits::MarketBuilderTrait, types::{BaseAsset, Market, PoolId}, }; +use alloc::fmt::Debug; use frame_support::{ - dispatch::{fmt::Debug, DispatchError, DispatchResult}, + dispatch::DispatchResult, pallet_prelude::{MaybeSerializeDeserialize, Member}, storage::PrefixIterator, Parameter, }; use parity_scale_codec::{FullCodec, HasCompact, MaxEncodedLen}; -use sp_runtime::traits::{AtLeast32Bit, AtLeast32BitUnsigned}; +use sp_runtime::{ + traits::{AtLeast32Bit, AtLeast32BitUnsigned}, + DispatchError, +}; // Abstraction of the market type, which is not a part of `MarketCommonsPalletApi` because Rust // doesn't support type aliases in traits. diff --git a/primitives/src/traits/swaps.rs b/primitives/src/traits/swaps.rs index 415c163bd..3a9093ee4 100644 --- a/primitives/src/traits/swaps.rs +++ b/primitives/src/traits/swaps.rs @@ -18,8 +18,9 @@ use crate::types::PoolId; use alloc::vec::Vec; -use frame_support::dispatch::{DispatchError, DispatchResult, Weight}; +use frame_support::{dispatch::DispatchResult, weights::Weight}; use parity_scale_codec::{HasCompact, MaxEncodedLen}; +use sp_runtime::DispatchError; pub trait Swaps { type Asset: MaxEncodedLen; diff --git a/primitives/src/traits/weights.rs b/primitives/src/traits/weights.rs deleted file mode 100644 index 8cc25046b..000000000 --- a/primitives/src/traits/weights.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2024 Forecasting Technologies LTD. -// Copyright 2023 Parity Technologies (UK) 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 . - -/// Provides `checked_div_per_component` implementation to determine the -/// smallest division result between two `ref_time` and `proof_size`. -/// To be removed once sp-weights is upgraded to polkadot-v0.9.39 -use frame_support::pallet_prelude::Weight; - -pub trait CheckedDivPerComponent { - /// Calculates how many `other` fit into `self`. - /// - /// Divides each component of `self` against the same component of `other`. Returns the minimum - /// of all those divisions. Returns `None` in case **all** components of `other` are zero. - /// - /// This returns `Some` even if some components of `other` are zero as long as there is at least - /// one non-zero component in `other`. The division for this particular component will then - /// yield the maximum value (e.g u64::MAX). This is because we assume not every operation and - /// hence each `Weight` will necessarily use each resource. - fn checked_div_per_component(self, other: &Self) -> Option; -} - -impl CheckedDivPerComponent for Weight { - fn checked_div_per_component(self, other: &Self) -> Option { - let mut all_zero = true; - let ref_time = match self.ref_time().checked_div(other.ref_time()) { - Some(ref_time) => { - all_zero = false; - ref_time - } - None => u64::MAX, - }; - let proof_size = match self.proof_size().checked_div(other.proof_size()) { - Some(proof_size) => { - all_zero = false; - proof_size - } - None => u64::MAX, - }; - if all_zero { - None - } else { - Some(if ref_time < proof_size { ref_time } else { proof_size }) - } - } -} diff --git a/primitives/src/types.rs b/primitives/src/types.rs index 68ce0b1c1..0cc42fb14 100644 --- a/primitives/src/types.rs +++ b/primitives/src/types.rs @@ -21,7 +21,7 @@ pub use crate::{ }; #[cfg(feature = "arbitrary")] use arbitrary::{Arbitrary, Result, Unstructured}; -use frame_support::dispatch::Weight; +use frame_support::weights::Weight; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_runtime::{ diff --git a/zrml/asset-router/src/lib.rs b/zrml/asset-router/src/lib.rs index ec97b3937..802a2406f 100644 --- a/zrml/asset-router/src/lib.rs +++ b/zrml/asset-router/src/lib.rs @@ -38,18 +38,21 @@ pub mod pallet { pub(crate) use alloc::collections::BTreeMap; pub(crate) use core::{fmt::Debug, marker::PhantomData}; pub(crate) use frame_support::{ - ensure, log, - pallet_prelude::{DispatchError, DispatchResult, Hooks, StorageValue, ValueQuery, Weight}, + ensure, + pallet_prelude::{DispatchResult, Hooks, StorageValue, ValueQuery, Weight}, require_transactional, traits::{ tokens::{ - fungibles::{Create, Destroy, Inspect, Mutate, Transfer, Unbalanced}, - DepositConsequence, WithdrawConsequence, + fungibles::{Create, Destroy, Inspect, Mutate, Unbalanced}, + DepositConsequence, Fortitude, Precision, Preservation, Provenance, + WithdrawConsequence, }, BalanceStatus as Status, ConstU32, }, BoundedVec, Parameter, }; + pub(crate) use frame_system::pallet_prelude::BlockNumberFor; + use log; pub(crate) use orml_traits::{ arithmetic::Signed, currency::{ @@ -62,13 +65,10 @@ pub mod pallet { use parity_scale_codec::{FullCodec, MaxEncodedLen}; use scale_info::TypeInfo; pub(crate) use sp_runtime::{ - traits::{ - AtLeast32BitUnsigned, Bounded, Get, MaybeSerializeDeserialize, Member, Saturating, Zero, - }, - FixedPointOperand, SaturatedConversion, + traits::{AtLeast32BitUnsigned, Bounded, Get, MaybeSerializeDeserialize, Member, Zero}, + DispatchError, FixedPointOperand, SaturatedConversion, }; use zeitgeist_macros::unreachable_non_terminating; - pub(crate) use zeitgeist_primitives::traits::CheckedDivPerComponent; pub(crate) const LOG_TARGET: &str = "runtime::asset-router"; pub(crate) const MAX_ASSET_DESTRUCTIONS_PER_BLOCK: u8 = 128; @@ -81,7 +81,6 @@ pub mod pallet { Create + Destroy + Inspect - + Transfer + Mutate + Unbalanced { @@ -92,7 +91,6 @@ pub mod pallet { G: Create + Destroy + Inspect - + Transfer + Mutate + Unbalanced, T: Config, @@ -216,14 +214,16 @@ pub mod pallet { UnknownAsset, /// Operation is not supported for given asset Unsupported, + /// Only a partial amount was deposited + DepositOnlyPartial, } #[pallet::pallet] pub struct Pallet(PhantomData); #[pallet::hooks] - impl Hooks for Pallet { - fn on_idle(_: T::BlockNumber, mut remaining_weight: Weight) -> Weight { + impl Hooks> for Pallet { + fn on_idle(_: BlockNumberFor, mut remaining_weight: Weight) -> Weight { let max_extra_weight = Self::on_idle_max_extra_weight(); if !remaining_weight diff --git a/zrml/asset-router/src/mock.rs b/zrml/asset-router/src/mock.rs index 716142b96..0faf258da 100644 --- a/zrml/asset-router/src/mock.rs +++ b/zrml/asset-router/src/mock.rs @@ -26,20 +26,19 @@ use frame_support::{ pallet_prelude::{DispatchResult, Weight}, traits::{AsEnsureOriginWithArg, Everything}, }; -use frame_system::EnsureSigned; +use frame_system::{mocking::MockBlockU32, EnsureSigned}; use orml_traits::parameter_type_with_key; use pallet_assets::ManagedDestroy; use parity_scale_codec::Compact; use sp_runtime::{ - testing::Header, traits::{parameter_types, BlakeTwo256, ConstU128, ConstU32, IdentityLookup}, + BuildStorage, }; use zeitgeist_primitives::{ constants::mock::{BlockHashCount, ExistentialDeposit, MaxLocks, MaxReserves, BASE}, types::{ - AccountIdTest, Amount, Assets, Balance, BlockNumber, BlockTest, CampaignAsset, - CampaignAssetClass, CampaignAssetId, Currencies, CustomAsset, CustomAssetClass, - CustomAssetId, Hash, Index, MarketAsset, UncheckedExtrinsicTest, + AccountIdTest, Amount, Assets, Balance, CampaignAsset, CampaignAssetClass, CampaignAssetId, + Currencies, CustomAsset, CustomAssetClass, CustomAssetId, Hash, MarketAsset, }, }; @@ -80,18 +79,14 @@ parameter_types! { construct_runtime!( pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, { - AssetRouter: zrml_asset_router::{Pallet}, - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Tokens: orml_tokens::{Config, Event, Pallet, Storage}, + AssetRouter: zrml_asset_router, + Balances: pallet_balances, + CustomAssets: pallet_assets::, + CampaignAssets: pallet_assets::, + MarketAssets: pallet_assets::, + System: frame_system, + Tokens: orml_tokens, } ); @@ -115,18 +110,17 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlockU32; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); @@ -264,8 +258,12 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; + type MaxHolds = (); + type MaxFreezes = (); type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; @@ -284,7 +282,7 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: self.balances } .assimilate_storage(&mut t) diff --git a/zrml/asset-router/src/pallet_impl/inspect.rs b/zrml/asset-router/src/pallet_impl/inspect.rs index 1c19338d4..22e441e98 100644 --- a/zrml/asset-router/src/pallet_impl/inspect.rs +++ b/zrml/asset-router/src/pallet_impl/inspect.rs @@ -23,55 +23,43 @@ impl Inspect for Pallet { type Balance = T::Balance; fn total_issuance(asset: Self::AssetId) -> Self::Balance { - route_call!(asset, total_issuance, total_issuance,).unwrap_or(Zero::zero()) + route_call_with_trait!(asset, Inspect, total_issuance,).unwrap_or(Zero::zero()) + } + + fn active_issuance(asset: Self::AssetId) -> Self::Balance { + route_call_with_trait!(asset, Inspect, active_issuance,).unwrap_or(Zero::zero()) } fn minimum_balance(asset: Self::AssetId) -> Self::Balance { - route_call!(asset, minimum_balance, minimum_balance,).unwrap_or(Zero::zero()) + route_call_with_trait!(asset, Inspect, minimum_balance,).unwrap_or(Zero::zero()) } fn balance(asset: Self::AssetId, who: &T::AccountId) -> Self::Balance { - route_call!(asset, total_balance, balance, who).unwrap_or(Zero::zero()) + route_call_with_trait!(asset, Inspect, balance, who).unwrap_or(Zero::zero()) + } + + fn total_balance(asset: Self::AssetId, who: &T::AccountId) -> Self::Balance { + route_call_with_trait!(asset, Inspect, total_balance, who).unwrap_or(Zero::zero()) } fn reducible_balance( asset: Self::AssetId, who: &T::AccountId, - keep_alive: bool, + preservation: Preservation, + force: Fortitude, ) -> Self::Balance { - if T::CurrencyType::try_from(asset).is_ok() { - >::free_balance(asset, who) - } else { - only_asset!(asset, Zero::zero(), Inspect, reducible_balance, who, keep_alive) - } + route_call_with_trait!(asset, Inspect, reducible_balance, who, preservation, force) + .unwrap_or(Zero::zero()) } fn can_deposit( asset: Self::AssetId, who: &T::AccountId, amount: Self::Balance, - mint: bool, + provenance: Provenance, ) -> DepositConsequence { - if T::CurrencyType::try_from(asset).is_err() { - return only_asset!( - asset, - DepositConsequence::UnknownAsset, - Inspect, - can_deposit, - who, - amount, - mint - ); - } - - let total_balance = >::total_balance(asset, who); - let min_balance = >::minimum_balance(asset); - - if total_balance.saturating_add(amount) < min_balance { - DepositConsequence::BelowMinimum - } else { - DepositConsequence::Success - } + route_call_with_trait!(asset, Inspect, can_deposit, who, amount, provenance) + .unwrap_or(DepositConsequence::UnknownAsset) } fn can_withdraw( @@ -79,46 +67,11 @@ impl Inspect for Pallet { who: &T::AccountId, amount: Self::Balance, ) -> WithdrawConsequence { - if T::CurrencyType::try_from(asset).is_err() { - return only_asset!( - asset, - WithdrawConsequence::UnknownAsset, - Inspect, - can_withdraw, - who, - amount - ); - } - - let can_withdraw = - >::ensure_can_withdraw(asset, who, amount); - - if let Err(_e) = can_withdraw { - return WithdrawConsequence::NoFunds; - } - - let total_balance = >::total_balance(asset, who); - let min_balance = >::minimum_balance(asset); - let remainder = total_balance.saturating_sub(amount); - - if remainder < min_balance { - WithdrawConsequence::ReducedToZero(remainder) - } else { - WithdrawConsequence::Success - } + route_call_with_trait!(asset, Inspect, can_withdraw, who, amount) + .unwrap_or(WithdrawConsequence::UnknownAsset) } fn asset_exists(asset: Self::AssetId) -> bool { - if let Ok(currency) = T::CurrencyType::try_from(asset) { - if >::total_issuance(currency) - > Zero::zero() - { - true - } else { - only_asset!(asset, false, Inspect, asset_exists,) - } - } else { - only_asset!(asset, false, Inspect, asset_exists,) - } + route_call_with_trait!(asset, Inspect, asset_exists,).unwrap_or(false) } } diff --git a/zrml/asset-router/src/pallet_impl/multi_currency.rs b/zrml/asset-router/src/pallet_impl/multi_currency.rs index 77a87d3a8..63518a7fb 100644 --- a/zrml/asset-router/src/pallet_impl/multi_currency.rs +++ b/zrml/asset-router/src/pallet_impl/multi_currency.rs @@ -49,16 +49,36 @@ impl MultiCurrency for Pallet { if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { // Route "pre new asset system" market assets to `CurrencyType` if T::MarketAssets::asset_exists(asset) { - T::MarketAssets::reducible_balance(asset, who, false) + T::MarketAssets::reducible_balance( + asset, + who, + Preservation::Expendable, + Fortitude::Polite, + ) } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { T::Currencies::free_balance(currency, who) } else { - T::MarketAssets::reducible_balance(asset, who, false) + T::MarketAssets::reducible_balance( + asset, + who, + Preservation::Expendable, + Fortitude::Polite, + ) } } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { - T::CampaignAssets::reducible_balance(asset, who, false) + T::CampaignAssets::reducible_balance( + asset, + who, + Preservation::Expendable, + Fortitude::Polite, + ) } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { - T::CustomAssets::reducible_balance(asset, who, false) + T::CustomAssets::reducible_balance( + asset, + who, + Preservation::Expendable, + Fortitude::Polite, + ) } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { T::Currencies::free_balance(currency, who) } else { @@ -91,7 +111,7 @@ impl MultiCurrency for Pallet { return Err(Error::::UnknownAsset.into()); }; - withdraw_consequence.into_result().map(|_| ()) + withdraw_consequence.into_result(false).map(|_| ()) } fn transfer( @@ -103,16 +123,19 @@ impl MultiCurrency for Pallet { if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { // Route "pre new asset system" market assets to `CurrencyType` if T::MarketAssets::asset_exists(asset) { - T::MarketAssets::transfer(asset, from, to, amount, false).map(|_| ()) + T::MarketAssets::transfer(asset, from, to, amount, Preservation::Expendable) + .map(|_| ()) } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { T::Currencies::transfer(currency, from, to, amount) } else { - T::MarketAssets::transfer(asset, from, to, amount, false).map(|_| ()) + T::MarketAssets::transfer(asset, from, to, amount, Preservation::Expendable) + .map(|_| ()) } } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { - T::CampaignAssets::transfer(asset, from, to, amount, false).map(|_| ()) + T::CampaignAssets::transfer(asset, from, to, amount, Preservation::Expendable) + .map(|_| ()) } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { - T::CustomAssets::transfer(asset, from, to, amount, false).map(|_| ()) + T::CustomAssets::transfer(asset, from, to, amount, Preservation::Expendable).map(|_| ()) } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { T::Currencies::transfer(currency, from, to, amount) } else { @@ -125,7 +148,28 @@ impl MultiCurrency for Pallet { who: &T::AccountId, amount: Self::Balance, ) -> DispatchResult { - route_call!(currency_id, deposit, mint_into, who, amount)? + let eval_fungible_result = |b: Self::Balance| { + if b != amount { Err(Error::::DepositOnlyPartial.into()) } else { Ok(()) } + }; + + if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { + // Route "pre new asset system" market assets to `CurrencyType` + if T::MarketAssets::asset_exists(asset) { + T::MarketAssets::mint_into(asset, who, amount).and_then(eval_fungible_result) + } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { + T::Currencies::deposit(currency, who, amount) + } else { + T::MarketAssets::mint_into(asset, who, amount).and_then(eval_fungible_result) + } + } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { + T::CampaignAssets::mint_into(asset, who, amount).and_then(eval_fungible_result) + } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { + T::CustomAssets::mint_into(asset, who, amount).and_then(eval_fungible_result) + } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { + T::Currencies::deposit(currency, who, amount) + } else { + Err(Error::::UnknownAsset.into()) + } } fn withdraw( @@ -138,16 +182,20 @@ impl MultiCurrency for Pallet { if T::MarketAssets::asset_exists(asset) { // Resulting balance can be ignored as `burn_from` ensures that the // requested amount can be burned. - T::MarketAssets::burn_from(asset, who, amount).map(|_| ()) + T::MarketAssets::burn_from(asset, who, amount, Precision::Exact, Fortitude::Force) + .map(|_| ()) } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { T::Currencies::withdraw(currency, who, amount) } else { - T::MarketAssets::burn_from(asset, who, amount).map(|_| ()) + T::MarketAssets::burn_from(asset, who, amount, Precision::Exact, Fortitude::Force) + .map(|_| ()) } } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { - T::CampaignAssets::burn_from(asset, who, amount).map(|_| ()) + T::CampaignAssets::burn_from(asset, who, amount, Precision::Exact, Fortitude::Force) + .map(|_| ()) } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { - T::CustomAssets::burn_from(asset, who, amount).map(|_| ()) + T::CustomAssets::burn_from(asset, who, amount, Precision::Exact, Fortitude::Force) + .map(|_| ()) } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { T::Currencies::withdraw(currency, who, amount) } else { @@ -161,16 +209,36 @@ impl MultiCurrency for Pallet { if T::MarketAssets::asset_exists(asset) { // Resulting balance can be ignored as `burn_from` ensures that the // requested amount can be burned. - T::MarketAssets::reducible_balance(asset, who, false) >= value + T::MarketAssets::reducible_balance( + asset, + who, + Preservation::Expendable, + Fortitude::Force, + ) >= value } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { T::Currencies::can_slash(currency, who, value) } else { - T::MarketAssets::reducible_balance(asset, who, false) >= value + T::MarketAssets::reducible_balance( + asset, + who, + Preservation::Expendable, + Fortitude::Force, + ) >= value } } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { - T::CampaignAssets::reducible_balance(asset, who, false) >= value + T::CampaignAssets::reducible_balance( + asset, + who, + Preservation::Expendable, + Fortitude::Force, + ) >= value } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { - T::CustomAssets::reducible_balance(asset, who, false) >= value + T::CustomAssets::reducible_balance( + asset, + who, + Preservation::Expendable, + Fortitude::Force, + ) >= value } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { T::Currencies::can_slash(currency, who, value) } else { @@ -189,24 +257,16 @@ impl MultiCurrency for Pallet { if T::MarketAssets::asset_exists(asset) { // Resulting balance can be ignored as `burn_from` ensures that the // requested amount can be burned. - T::MarketAssets::slash(asset, who, amount) - .map(|b| amount.saturating_sub(b)) - .unwrap_or_else(|_| amount) + Self::withdraw(currency_id, who, amount).map(|_| Zero::zero()).unwrap_or(amount) } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { T::Currencies::slash(currency, who, amount) } else { - T::MarketAssets::slash(asset, who, amount) - .map(|b| amount.saturating_sub(b)) - .unwrap_or_else(|_| amount) + Self::withdraw(currency_id, who, amount).map(|_| Zero::zero()).unwrap_or(amount) } - } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { - T::CampaignAssets::slash(asset, who, amount) - .map(|b| amount.saturating_sub(b)) - .unwrap_or_else(|_| amount) - } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { - T::CustomAssets::slash(asset, who, amount) - .map(|b| amount.saturating_sub(b)) - .unwrap_or_else(|_| amount) + } else if let Ok(_) = T::CampaignAssetType::try_from(currency_id) { + Self::withdraw(currency_id, who, amount).map(|_| Zero::zero()).unwrap_or(amount) + } else if let Ok(_) = T::CustomAssetType::try_from(currency_id) { + Self::withdraw(currency_id, who, amount).map(|_| Zero::zero()).unwrap_or(amount) } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { T::Currencies::slash(currency, who, amount) } else { diff --git a/zrml/asset-router/src/pallet_impl/multi_lockable_currency.rs b/zrml/asset-router/src/pallet_impl/multi_lockable_currency.rs index 55e9d5779..8a1fb832c 100644 --- a/zrml/asset-router/src/pallet_impl/multi_lockable_currency.rs +++ b/zrml/asset-router/src/pallet_impl/multi_lockable_currency.rs @@ -18,7 +18,7 @@ use crate::pallet::*; impl MultiLockableCurrency for Pallet { - type Moment = T::BlockNumber; + type Moment = BlockNumberFor; fn set_lock( lock_id: LockIdentifier, diff --git a/zrml/asset-router/src/pallet_impl/unbalanced.rs b/zrml/asset-router/src/pallet_impl/unbalanced.rs index fc91c047a..0dcb7bf5b 100644 --- a/zrml/asset-router/src/pallet_impl/unbalanced.rs +++ b/zrml/asset-router/src/pallet_impl/unbalanced.rs @@ -16,15 +16,42 @@ // along with Zeitgeist. If not, see . use crate::pallet::*; -use frame_support::traits::tokens::fungibles::Unbalanced; +use frame_support::traits::tokens::fungibles::{Dust, Unbalanced}; impl Unbalanced for Pallet { - fn set_balance( + fn handle_raw_dust(asset: Self::AssetId, amount: Self::Balance) { + let _ = route_call_with_trait!(asset, Unbalanced, handle_raw_dust, amount); + } + + fn handle_dust(dust: Dust) { + let Dust(currency_id, amount) = dust; + + if let Ok(asset) = T::MarketAssetType::try_from(currency_id) { + // Route "pre new asset system" market assets to `CurrencyType` + if T::MarketAssets::asset_exists(asset) { + T::MarketAssets::handle_dust(Dust(asset, amount)); + } else { + if let Ok(currency) = T::CurrencyType::try_from(currency_id) { + T::Currencies::handle_dust(Dust(currency, amount)); + } else { + T::MarketAssets::handle_dust(Dust(asset, amount)); + } + } + } else if let Ok(asset) = T::CampaignAssetType::try_from(currency_id) { + T::CampaignAssets::handle_dust(Dust(asset, amount)); + } else if let Ok(asset) = T::CustomAssetType::try_from(currency_id) { + T::CustomAssets::handle_dust(Dust(asset, amount)); + } else if let Ok(currency) = T::CurrencyType::try_from(currency_id) { + T::Currencies::handle_dust(Dust(currency, amount)); + } + } + + fn write_balance( asset: Self::AssetId, who: &T::AccountId, amount: Self::Balance, - ) -> DispatchResult { - route_call_with_trait!(asset, Unbalanced, set_balance, who, amount)? + ) -> Result, DispatchError> { + route_call_with_trait!(asset, Unbalanced, write_balance, who, amount)? } fn set_total_issuance(asset: Self::AssetId, amount: Self::Balance) { @@ -35,33 +62,36 @@ impl Unbalanced for Pallet { asset: Self::AssetId, who: &T::AccountId, amount: Self::Balance, + precision: Precision, + preservation: Preservation, + force: Fortitude, ) -> Result { - route_call_with_trait!(asset, Unbalanced, decrease_balance, who, amount)? - } - - fn decrease_balance_at_most( - asset: Self::AssetId, - who: &T::AccountId, - amount: Self::Balance, - ) -> Self::Balance { - route_call_with_trait!(asset, Unbalanced, decrease_balance_at_most, who, amount) - .unwrap_or(Zero::zero()) + route_call_with_trait!( + asset, + Unbalanced, + decrease_balance, + who, + amount, + precision, + preservation, + force + )? } fn increase_balance( asset: Self::AssetId, who: &T::AccountId, amount: Self::Balance, + precision: Precision, ) -> Result { - route_call_with_trait!(asset, Unbalanced, increase_balance, who, amount)? + route_call_with_trait!(asset, Unbalanced, increase_balance, who, amount, precision)? } - fn increase_balance_at_most( - asset: Self::AssetId, - who: &T::AccountId, - amount: Self::Balance, - ) -> Self::Balance { - route_call_with_trait!(asset, Unbalanced, increase_balance_at_most, who, amount) - .unwrap_or(Zero::zero()) + fn deactivate(asset: Self::AssetId, amount: Self::Balance) { + let _ = route_call_with_trait!(asset, Unbalanced, deactivate, amount); + } + + fn reactivate(asset: Self::AssetId, amount: Self::Balance) { + let _ = route_call_with_trait!(asset, Unbalanced, reactivate, amount); } } diff --git a/zrml/asset-router/src/tests/inspect.rs b/zrml/asset-router/src/tests/inspect.rs index e762a3115..ea71939c2 100644 --- a/zrml/asset-router/src/tests/inspect.rs +++ b/zrml/asset-router/src/tests/inspect.rs @@ -18,23 +18,36 @@ #![cfg(test)] use super::*; +use crate::*; use frame_support::traits::tokens::fungibles::Inspect; -fn test_helper(asset: Assets, initial_amount: ::Balance) { +fn test_helper( + asset: Assets, + initial_amount: ::Balance, + min_balance: ::Balance, +) { assert_ok!(>::deposit( asset, &ALICE, initial_amount )); assert!(AssetRouter::asset_exists(asset)); - assert_eq!(AssetRouter::total_issuance(asset), initial_amount); + assert_eq!(>::total_issuance(asset), initial_amount); + assert_eq!(AssetRouter::active_issuance(asset), initial_amount); assert_eq!(AssetRouter::balance(asset, &ALICE), initial_amount); - assert_eq!(AssetRouter::reducible_balance(asset, &ALICE, false), initial_amount); + assert_eq!(AssetRouter::free_balance(asset, &ALICE), initial_amount); + assert_eq!( + AssetRouter::reducible_balance(asset, &ALICE, Preservation::Protect, Fortitude::Force), + initial_amount - min_balance + ); assert_eq!( AssetRouter::can_withdraw(asset, &ALICE, initial_amount), WithdrawConsequence::ReducedToZero(0) ); - assert_eq!(AssetRouter::can_deposit(asset, &ALICE, 1, true), DepositConsequence::Success); + assert_eq!( + AssetRouter::can_deposit(asset, &ALICE, 1, Provenance::Minted), + DepositConsequence::Success + ); } #[test] @@ -47,7 +60,7 @@ fn routes_campaign_assets_correctly() { >::minimum_balance(CAMPAIGN_ASSET), CAMPAIGN_ASSET_MIN_BALANCE ); - test_helper(CAMPAIGN_ASSET, CAMPAIGN_ASSET_INITIAL_AMOUNT); + test_helper(CAMPAIGN_ASSET, CAMPAIGN_ASSET_INITIAL_AMOUNT, CAMPAIGN_ASSET_MIN_BALANCE); assert_eq!(>::total_issuance(CUSTOM_ASSET_INTERNAL), 0); assert_eq!(>::total_issuance(MARKET_ASSET_INTERNAL), 0); assert_eq!(>::total_issuance(CURRENCY_INTERNAL), 0); @@ -64,7 +77,7 @@ fn routes_custom_assets_correctly() { >::minimum_balance(CUSTOM_ASSET), CUSTOM_ASSET_MIN_BALANCE ); - test_helper(CUSTOM_ASSET, CUSTOM_ASSET_INITIAL_AMOUNT); + test_helper(CUSTOM_ASSET, CUSTOM_ASSET_INITIAL_AMOUNT, CUSTOM_ASSET_MIN_BALANCE); assert_eq!( >::total_issuance(CAMPAIGN_ASSET_INTERNAL), 0 @@ -84,7 +97,7 @@ fn routes_market_assets_correctly() { >::minimum_balance(MARKET_ASSET), MARKET_ASSET_MIN_BALANCE ); - test_helper(MARKET_ASSET, MARKET_ASSET_INITIAL_AMOUNT); + test_helper(MARKET_ASSET, MARKET_ASSET_INITIAL_AMOUNT, MARKET_ASSET_MIN_BALANCE); assert_eq!( >::total_issuance(CAMPAIGN_ASSET_INTERNAL), 0 @@ -97,11 +110,17 @@ fn routes_market_assets_correctly() { #[test] fn routes_currencies_correctly() { ExtBuilder::default().build().execute_with(|| { - assert_eq!(AssetRouter::minimum_balance(CURRENCY), CURRENCY_MIN_BALANCE); - assert_eq!(AssetRouter::minimum_balance(CURRENCY_OLD_OUTCOME), CURRENCY_MIN_BALANCE); + assert_eq!( + >::minimum_balance(CURRENCY), + CURRENCY_MIN_BALANCE + ); + assert_eq!( + >::minimum_balance(CURRENCY_OLD_OUTCOME), + CURRENCY_MIN_BALANCE + ); - test_helper(CURRENCY, CURRENCY_INITIAL_AMOUNT); - test_helper(CURRENCY_OLD_OUTCOME, CURRENCY_INITIAL_AMOUNT); + test_helper(CURRENCY, CURRENCY_INITIAL_AMOUNT, CURRENCY_MIN_BALANCE); + test_helper(CURRENCY_OLD_OUTCOME, CURRENCY_INITIAL_AMOUNT, CURRENCY_MIN_BALANCE); assert_eq!( >::total_issuance(CAMPAIGN_ASSET_INTERNAL), diff --git a/zrml/asset-router/src/tests/unbalanced.rs b/zrml/asset-router/src/tests/unbalanced.rs index 91b78ffad..08a461264 100644 --- a/zrml/asset-router/src/tests/unbalanced.rs +++ b/zrml/asset-router/src/tests/unbalanced.rs @@ -18,29 +18,40 @@ #![cfg(test)] use super::*; -use frame_support::traits::tokens::fungibles::Unbalanced; +use crate::*; +use frame_support::{ + assert_storage_noop, + traits::{fungibles::Dust, tokens::fungibles::Unbalanced}, +}; use orml_traits::MultiCurrency; -fn test_helper( - asset: Assets, - initial_amount: ::Balance, - min_balance: ::Balance, -) { - assert_eq!(AssetRouter::total_balance(asset, &ALICE), initial_amount); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, 1)); - assert_eq!(AssetRouter::total_balance(asset, &ALICE), initial_amount + 1); - assert_ok!(AssetRouter::decrease_balance(asset, &ALICE, 1)); - assert_eq!(AssetRouter::total_balance(asset, &ALICE), initial_amount); - assert_eq!(AssetRouter::increase_balance_at_most(asset, &ALICE, 1), 1); - assert_eq!(AssetRouter::total_balance(asset, &ALICE), initial_amount + 1); - let to_decrease = initial_amount + 2 - min_balance; +fn test_helper(asset: Assets, initial_amount: ::Balance) { assert_eq!( - AssetRouter::decrease_balance_at_most(asset, &ALICE, to_decrease), + >::total_balance(asset, &ALICE), + initial_amount + ); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, 1, Precision::Exact)); + assert_eq!( + >::total_balance(asset, &ALICE), initial_amount + 1 ); - assert_eq!(AssetRouter::total_balance(asset, &ALICE), 0); + assert_ok!(AssetRouter::decrease_balance( + asset, + &ALICE, + 1, + Precision::Exact, + Preservation::Expendable, + Fortitude::Polite + )); + assert_eq!( + >::total_balance(asset, &ALICE), + initial_amount + ); AssetRouter::set_total_issuance(asset, 1337); - assert_eq!(AssetRouter::total_issuance(asset), 1337); + assert_eq!(>::total_issuance(asset), 1337); + assert_storage_noop!(AssetRouter::deactivate(asset, 1)); + assert_storage_noop!(AssetRouter::reactivate(asset, 1)); + assert_storage_noop!(AssetRouter::handle_raw_dust(asset, 1)); } #[test] @@ -49,20 +60,29 @@ fn routes_campaign_assets_correctly() { assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); assert_ok!(AssetRouter::deposit(CAMPAIGN_ASSET, &ALICE, CAMPAIGN_ASSET_INITIAL_AMOUNT)); - test_helper(CAMPAIGN_ASSET, CAMPAIGN_ASSET_INITIAL_AMOUNT, CAMPAIGN_ASSET_MIN_BALANCE); + test_helper(CAMPAIGN_ASSET, CAMPAIGN_ASSET_INITIAL_AMOUNT); - assert_eq!(AssetRouter::total_issuance(CUSTOM_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(MARKET_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(CURRENCY), 0); + assert_eq!(>::total_issuance(CUSTOM_ASSET), 0); + assert_eq!(>::total_issuance(MARKET_ASSET), 0); + assert_eq!(>::total_issuance(CURRENCY), 0); }); } #[test] #[should_panic] -fn campaign_assets_panic_on_set_balance() { +fn campaign_assets_panic_on_write_balance() { ExtBuilder::default().build().execute_with(|| { assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); - let _ = AssetRouter::set_balance(CAMPAIGN_ASSET, &ALICE, 42); + let _ = AssetRouter::write_balance(CAMPAIGN_ASSET, &ALICE, 42); + }); +} + +#[test] +#[should_panic] +fn campaign_assets_panic_on_handle_dust() { + ExtBuilder::default().build().execute_with(|| { + assert_ok!(AssetRouter::create(CAMPAIGN_ASSET, ALICE, true, CAMPAIGN_ASSET_MIN_BALANCE)); + let _ = AssetRouter::handle_dust(Dust(CAMPAIGN_ASSET, 1)); }); } @@ -72,20 +92,29 @@ fn routes_custom_assets_correctly() { assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE)); assert_ok!(AssetRouter::deposit(CUSTOM_ASSET, &ALICE, CUSTOM_ASSET_INITIAL_AMOUNT)); - test_helper(CUSTOM_ASSET, CUSTOM_ASSET_INITIAL_AMOUNT, CUSTOM_ASSET_MIN_BALANCE); + test_helper(CUSTOM_ASSET, CUSTOM_ASSET_INITIAL_AMOUNT); + + assert_eq!(>::total_issuance(CAMPAIGN_ASSET), 0); + assert_eq!(>::total_issuance(MARKET_ASSET), 0); + assert_eq!(>::total_issuance(CURRENCY), 0); + }); +} - assert_eq!(AssetRouter::total_issuance(CAMPAIGN_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(MARKET_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(CURRENCY), 0); +#[test] +#[should_panic] +fn custom_assets_panic_on_write_balance() { + ExtBuilder::default().build().execute_with(|| { + assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE)); + let _ = AssetRouter::write_balance(CUSTOM_ASSET, &ALICE, 42); }); } #[test] #[should_panic] -fn custom_assets_panic_on_set_balance() { +fn custom_assets_panic_on_handle_dust() { ExtBuilder::default().build().execute_with(|| { assert_ok!(AssetRouter::create(CUSTOM_ASSET, ALICE, true, CUSTOM_ASSET_MIN_BALANCE)); - let _ = AssetRouter::set_balance(CUSTOM_ASSET, &ALICE, 42); + let _ = AssetRouter::handle_dust(Dust(CUSTOM_ASSET, 1)); }); } @@ -95,31 +124,43 @@ fn routes_market_assets_correctly() { assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, MARKET_ASSET_MIN_BALANCE)); assert_ok!(AssetRouter::deposit(MARKET_ASSET, &ALICE, MARKET_ASSET_INITIAL_AMOUNT)); - test_helper(MARKET_ASSET, MARKET_ASSET_INITIAL_AMOUNT, MARKET_ASSET_MIN_BALANCE); + test_helper(MARKET_ASSET, MARKET_ASSET_INITIAL_AMOUNT); - assert_eq!(AssetRouter::total_issuance(CAMPAIGN_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(CUSTOM_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(CURRENCY), 0); + assert_eq!(>::total_issuance(CAMPAIGN_ASSET), 0); + assert_eq!(>::total_issuance(CUSTOM_ASSET), 0); + assert_eq!(>::total_issuance(CURRENCY), 0); }); } #[test] #[should_panic] -fn market_assets_panic_on_set_balance() { +fn market_assets_panic_on_write_balance() { ExtBuilder::default().build().execute_with(|| { assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, MARKET_ASSET_MIN_BALANCE)); - let _ = AssetRouter::set_balance(MARKET_ASSET, &ALICE, 42); + let _ = AssetRouter::write_balance(MARKET_ASSET, &ALICE, 42); }); } #[test] -fn routes_currencies_correctly() { +#[should_panic] +fn market_assets_panic_on_handle_dust() { ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRouter::set_balance(CURRENCY, &ALICE, CURRENCY_INITIAL_AMOUNT)); - test_helper(CURRENCY, CURRENCY_INITIAL_AMOUNT, CURRENCY_MIN_BALANCE); + assert_ok!(AssetRouter::create(MARKET_ASSET, ALICE, true, MARKET_ASSET_MIN_BALANCE)); + let _ = AssetRouter::handle_dust(Dust(MARKET_ASSET, 1)); + }); +} - assert_eq!(AssetRouter::total_issuance(CAMPAIGN_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(CUSTOM_ASSET), 0); - assert_eq!(AssetRouter::total_issuance(MARKET_ASSET), 0); +#[test] +fn routes_currencies_correctly() { + ExtBuilder::default().build().execute_with(|| { + assert_ok!(AssetRouter::write_balance(CURRENCY, &ALICE, CURRENCY_INITIAL_AMOUNT)); + test_helper(CURRENCY, CURRENCY_INITIAL_AMOUNT); + assert_storage_noop!(AssetRouter::handle_dust(Dust(CURRENCY, 1))); + assert_ok!(AssetRouter::write_balance(CURRENCY, &ALICE, CURRENCY_MIN_BALANCE)); + assert_eq!(AssetRouter::free_balance(CURRENCY, &ALICE), CURRENCY_MIN_BALANCE); + + assert_eq!(>::total_issuance(CAMPAIGN_ASSET), 0); + assert_eq!(>::total_issuance(CUSTOM_ASSET), 0); + assert_eq!(>::total_issuance(MARKET_ASSET), 0); }); } From 715545917ffa9795b15105d2b48dac1cbd41bf93 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 14:03:15 +0200 Subject: [PATCH 02/16] Upgrade zrml-market-commons --- Cargo.lock | 1 + zrml/asset-router/src/mock.rs | 3 +- zrml/market-commons/Cargo.toml | 1 + zrml/market-commons/src/lib.rs | 16 +++---- zrml/market-commons/src/migrations.rs | 22 +++++----- zrml/market-commons/src/mock.rs | 44 +++++++++---------- zrml/market-commons/src/tests.rs | 6 +-- .../src/types/market_builder.rs | 7 +-- 8 files changed, 49 insertions(+), 51 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f183a257e..5406da71b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15151,6 +15151,7 @@ dependencies = [ "env_logger 0.10.2", "frame-support", "frame-system", + "log", "pallet-balances", "pallet-timestamp", "parity-scale-codec", diff --git a/zrml/asset-router/src/mock.rs b/zrml/asset-router/src/mock.rs index 0faf258da..964681f16 100644 --- a/zrml/asset-router/src/mock.rs +++ b/zrml/asset-router/src/mock.rs @@ -78,8 +78,7 @@ parameter_types! { } construct_runtime!( - pub enum Runtime - { + pub enum Runtime { AssetRouter: zrml_asset_router, Balances: pallet_balances, CustomAssets: pallet_assets::, diff --git a/zrml/market-commons/Cargo.toml b/zrml/market-commons/Cargo.toml index f25f7154f..cc72f8c11 100644 --- a/zrml/market-commons/Cargo.toml +++ b/zrml/market-commons/Cargo.toml @@ -1,6 +1,7 @@ [dependencies] frame-support = { workspace = true } frame-system = { workspace = true } +log = { workspace = true } parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } scale-info = { workspace = true, features = ["derive"] } sp-arithmetic = { workspace = true } diff --git a/zrml/market-commons/src/lib.rs b/zrml/market-commons/src/lib.rs index 3b2e1af6c..73deadb4a 100644 --- a/zrml/market-commons/src/lib.rs +++ b/zrml/market-commons/src/lib.rs @@ -42,6 +42,7 @@ mod pallet { traits::{Hooks, StorageVersion, Time}, Blake2_128Concat, Parameter, }; + use frame_system::pallet_prelude::BlockNumberFor; use parity_scale_codec::{FullCodec, HasCompact, MaxEncodedLen}; use sp_runtime::{ traits::{ @@ -62,22 +63,21 @@ mod pallet { pub(crate) type AccountIdOf = ::AccountId; pub(crate) type BalanceOf = ::Balance; - pub(crate) type BlockNumberOf = ::BlockNumber; pub(crate) type MarketIdOf = ::MarketId; pub(crate) type MarketOf = Market< AccountIdOf, BalanceOf, - BlockNumberOf, + BlockNumberFor, MomentOf, BaseAsset, MarketIdOf, >; pub(crate) type MomentOf = <::Timestamp as frame_support::traits::Time>::Moment; - pub(crate) type DeadlinesOf = Deadlines>; - pub(crate) type EarlyCloseOf = EarlyClose, MomentOf>; + pub(crate) type DeadlinesOf = Deadlines>; + pub(crate) type EarlyCloseOf = EarlyClose, MomentOf>; pub(crate) type MarketBondsOf = MarketBonds, BalanceOf>; - pub(crate) type MarketPeriodOf = MarketPeriod, MomentOf>; - pub(crate) type ReportOf = Report, BlockNumberOf>; + pub(crate) type MarketPeriodOf = MarketPeriod, MomentOf>; + pub(crate) type ReportOf = Report, BlockNumberFor>; #[pallet::call] impl Pallet {} @@ -125,7 +125,7 @@ mod pallet { } #[pallet::hooks] - impl Hooks for Pallet {} + impl Hooks> for Pallet {} #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] @@ -155,7 +155,7 @@ mod pallet { ::Timestamp: Time, { type AccountId = AccountIdOf; - type BlockNumber = T::BlockNumber; + type BlockNumber = BlockNumberFor; type Balance = T::Balance; type MarketId = T::MarketId; type Moment = MomentOf; diff --git a/zrml/market-commons/src/migrations.rs b/zrml/market-commons/src/migrations.rs index 2569b4a79..791d9dabb 100644 --- a/zrml/market-commons/src/migrations.rs +++ b/zrml/market-commons/src/migrations.rs @@ -16,17 +16,18 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use crate::{AccountIdOf, BalanceOf, BlockNumberOf, Config, MomentOf, Pallet as MarketCommons}; +use crate::{AccountIdOf, BalanceOf, Config, MomentOf, Pallet as MarketCommons}; use alloc::vec::Vec; use core::marker::PhantomData; use frame_support::{ - dispatch::Weight, - log, traits::{Get, OnRuntimeUpgrade, StorageVersion}, + weights::Weight, }; +use frame_system::pallet_prelude::BlockNumberFor; +use log; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; -use sp_runtime::{Perbill, RuntimeDebug, Saturating}; +use sp_runtime::{DispatchError, Perbill, RuntimeDebug, Saturating}; use zeitgeist_primitives::types::{ BaseAsset, Deadlines, EarlyClose, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, MarketType, OutcomeReport, Report, ScoringRule, @@ -68,7 +69,7 @@ pub struct OldMarket { } type OldMarketOf = - OldMarket, BalanceOf, BlockNumberOf, MomentOf, BaseAsset>; + OldMarket, BalanceOf, BlockNumberFor, MomentOf, BaseAsset>; #[derive(TypeInfo, Clone, Copy, Encode, Eq, Decode, MaxEncodedLen, PartialEq, RuntimeDebug)] pub enum OldScoringRule { @@ -147,7 +148,7 @@ where } #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, &'static str> { + fn pre_upgrade() -> Result, DispatchError> { let old_markets = storage_key_iter::, OldMarketOf, Blake2_128Concat>( MARKET_COMMONS, MARKETS, @@ -169,7 +170,7 @@ where } #[cfg(feature = "try-runtime")] - fn post_upgrade(previous_state: Vec) -> Result<(), &'static str> { + fn post_upgrade(previous_state: Vec) -> Result<(), DispatchError> { let old_markets: BTreeMap, OldMarketOf> = Decode::decode(&mut &previous_state[..]).unwrap(); let old_market_count = old_markets.len(); @@ -212,10 +213,9 @@ mod tests { MarketOf, }; use alloc::fmt::Debug; - use frame_support::{ - migration::put_storage_value, storage_root, Blake2_128Concat, StorageHasher, - }; + use frame_support::{migration::put_storage_value, Blake2_128Concat, StorageHasher}; use parity_scale_codec::Encode; + use sp_io::storage::root as storage_root; use sp_runtime::{Perbill, StateVersion}; use test_case::test_case; use zeitgeist_primitives::types::{BaseAssetClass, Bond, EarlyCloseState, MarketId}; @@ -269,7 +269,7 @@ mod tests { oracle: 4, metadata: vec![0x05; 50], market_type: MarketType::Categorical(999), - period: MarketPeriod::, MomentOf>::Block(6..7), + period: MarketPeriod::, MomentOf>::Block(6..7), deadlines: Deadlines { grace_period: 7, oracle_duration: 8, dispute_duration: 9 }, scoring_rule: ScoringRule::AmmCdaHybrid, status: MarketStatus::Active, diff --git a/zrml/market-commons/src/mock.rs b/zrml/market-commons/src/mock.rs index bf692a1a8..c9b5f20b2 100644 --- a/zrml/market-commons/src/mock.rs +++ b/zrml/market-commons/src/mock.rs @@ -20,29 +20,22 @@ use crate::{self as zrml_market_commons}; use frame_support::{construct_runtime, traits::Everything}; +use frame_system::mocking::MockBlockU32; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use zeitgeist_primitives::{ - constants::mock::{BlockHashCount, MaxReserves, MinimumPeriod}, - types::{ - AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, MarketId, Moment, - UncheckedExtrinsicTest, - }, + constants::mock::{BlockHashCount, ExistentialDeposit, MaxLocks, MaxReserves, MinimumPeriod}, + types::{AccountIdTest, Balance, Hash, MarketId, Moment}, }; construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - MarketCommons: zrml_market_commons::{Pallet, Storage}, - System: frame_system::{Call, Config,Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, + pub enum Runtime { + Balances: pallet_balances, + MarketCommons: zrml_market_commons, + System: frame_system, + Timestamp: pallet_timestamp, } ); @@ -56,18 +49,17 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlockU32; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); - type RuntimeEvent = (); + type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); @@ -83,9 +75,13 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); - type RuntimeEvent = (); - type ExistentialDeposit = (); - type MaxLocks = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); + type RuntimeEvent = RuntimeEvent; + type ExistentialDeposit = ExistentialDeposit; + type MaxHolds = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); @@ -103,7 +99,7 @@ pub struct ExtBuilder {} impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); diff --git a/zrml/market-commons/src/tests.rs b/zrml/market-commons/src/tests.rs index a7d26af88..392e1fcfd 100644 --- a/zrml/market-commons/src/tests.rs +++ b/zrml/market-commons/src/tests.rs @@ -47,9 +47,9 @@ fn create_market_builder(oracle: AccountIdOf) -> MarketBuilder .oracle(oracle) .period(MarketPeriod::Block(0..100)) .deadlines(Deadlines { - grace_period: 1_u64, - oracle_duration: 1_u64, - dispute_duration: 1_u64, + grace_period: 1_u32, + oracle_duration: 1_u32, + dispute_duration: 1_u32, }) .report(None) .resolved_outcome(None) diff --git a/zrml/market-commons/src/types/market_builder.rs b/zrml/market-commons/src/types/market_builder.rs index c121f19e0..537cc9eb7 100644 --- a/zrml/market-commons/src/types/market_builder.rs +++ b/zrml/market-commons/src/types/market_builder.rs @@ -16,10 +16,11 @@ // along with Zeitgeist. If not, see . use crate::{ - AccountIdOf, BalanceOf, BlockNumberOf, Config, DeadlinesOf, EarlyCloseOf, Error, MarketBondsOf, - MarketIdOf, MarketOf, MarketPeriodOf, MomentOf, ReportOf, + AccountIdOf, BalanceOf, Config, DeadlinesOf, EarlyCloseOf, Error, MarketBondsOf, MarketIdOf, + MarketOf, MarketPeriodOf, MomentOf, ReportOf, }; use alloc::vec::Vec; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{DispatchError, Perbill}; use zeitgeist_primitives::{ traits::MarketBuilderTrait, @@ -115,7 +116,7 @@ impl MarketBuilderTrait< AccountIdOf, BalanceOf, - BlockNumberOf, + BlockNumberFor, MomentOf, BaseAsset, MarketIdOf, From 6497c0238876ce5d7eaaa0e367710bbc55f316bc Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 14:30:45 +0200 Subject: [PATCH 03/16] Upgrade zrml-authorized && use MockBlock instead of MockBlockU32 --- zrml/asset-router/src/mock.rs | 4 +- zrml/authorized/src/benchmarks.rs | 5 +-- zrml/authorized/src/lib.rs | 18 ++++----- zrml/authorized/src/mock.rs | 58 ++++++++++++--------------- zrml/authorized/src/mock_storage.rs | 5 ++- zrml/authorized/src/tests.rs | 3 +- zrml/market-commons/src/migrations.rs | 3 +- zrml/market-commons/src/mock.rs | 4 +- zrml/market-commons/src/tests.rs | 6 +-- 9 files changed, 49 insertions(+), 57 deletions(-) diff --git a/zrml/asset-router/src/mock.rs b/zrml/asset-router/src/mock.rs index 964681f16..0b9486104 100644 --- a/zrml/asset-router/src/mock.rs +++ b/zrml/asset-router/src/mock.rs @@ -26,7 +26,7 @@ use frame_support::{ pallet_prelude::{DispatchResult, Weight}, traits::{AsEnsureOriginWithArg, Everything}, }; -use frame_system::{mocking::MockBlockU32, EnsureSigned}; +use frame_system::{mocking::MockBlock, EnsureSigned}; use orml_traits::parameter_type_with_key; use pallet_assets::ManagedDestroy; use parity_scale_codec::Compact; @@ -109,7 +109,7 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; - type Block = MockBlockU32; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); type BlockWeights = (); diff --git a/zrml/authorized/src/benchmarks.rs b/zrml/authorized/src/benchmarks.rs index db649941b..167af074e 100644 --- a/zrml/authorized/src/benchmarks.rs +++ b/zrml/authorized/src/benchmarks.rs @@ -27,10 +27,7 @@ use crate::{ Pallet, }; use frame_benchmarking::benchmarks; -use frame_support::{ - dispatch::UnfilteredDispatchable, - traits::{EnsureOrigin, Get, Imbalance}, -}; +use frame_support::traits::{EnsureOrigin, Get, Imbalance, UnfilteredDispatchable}; use sp_runtime::traits::Saturating; use zeitgeist_primitives::{ traits::{DisputeApi, DisputeResolutionApi}, diff --git a/zrml/authorized/src/lib.rs b/zrml/authorized/src/lib.rs index 1e5644cb6..cef2b7483 100644 --- a/zrml/authorized/src/lib.rs +++ b/zrml/authorized/src/lib.rs @@ -44,7 +44,7 @@ mod pallet { traits::{Currency, Get, Hooks, IsType, StorageVersion}, PalletId, Twox64Concat, }; - use frame_system::pallet_prelude::OriginFor; + use frame_system::pallet_prelude::{BlockNumberFor, OriginFor}; use sp_runtime::{traits::Saturating, DispatchError, DispatchResult}; use zeitgeist_primitives::{ traits::{DisputeApi, DisputeMaxWeightApi, DisputeResolutionApi}, @@ -70,7 +70,7 @@ mod pallet { pub(crate) type MarketOf = Market< ::AccountId, BalanceOf, - ::BlockNumber, + BlockNumberFor, MomentOf, BaseAsset, MarketIdOf, @@ -134,18 +134,18 @@ mod pallet { /// The period, in which the authority can correct the outcome of a market. /// This value must not be zero. #[pallet::constant] - type CorrectionPeriod: Get; + type CorrectionPeriod: Get>; type DisputeResolution: DisputeResolutionApi< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, MarketId = MarketIdOf, Moment = MomentOf, >; type MarketCommons: MarketCommonsPalletApi< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, Balance = BalanceOf, >; @@ -181,7 +181,7 @@ mod pallet { } #[pallet::hooks] - impl Hooks for Pallet {} + impl Hooks> for Pallet {} #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] @@ -192,7 +192,7 @@ mod pallet { T: Config, { /// Return the resolution block number for the given market. - fn get_auto_resolve(market_id: &MarketIdOf) -> Option { + fn get_auto_resolve(market_id: &MarketIdOf) -> Option> { AuthorizedOutcomeReports::::get(market_id).map(|report| report.resolve_at) } @@ -246,7 +246,7 @@ mod pallet { type AccountId = T::AccountId; type Balance = BalanceOf; type NegativeImbalance = NegativeImbalanceOf; - type BlockNumber = T::BlockNumber; + type BlockNumber = BlockNumberFor; type MarketId = MarketIdOf; type Moment = MomentOf; type Origin = T::RuntimeOrigin; @@ -361,7 +361,7 @@ mod pallet { #[pallet::storage] #[pallet::getter(fn outcomes)] pub type AuthorizedOutcomeReports = - StorageMap<_, Twox64Concat, MarketIdOf, AuthorityReport, OptionQuery>; + StorageMap<_, Twox64Concat, MarketIdOf, AuthorityReport>, OptionQuery>; } #[cfg(any(feature = "runtime-benchmarks", test))] diff --git a/zrml/authorized/src/mock.rs b/zrml/authorized/src/mock.rs index 5669d8096..a3df02779 100644 --- a/zrml/authorized/src/mock.rs +++ b/zrml/authorized/src/mock.rs @@ -22,25 +22,19 @@ extern crate alloc; use crate::{self as zrml_authorized, mock_storage::pallet as mock_storage}; use alloc::{vec, vec::Vec}; -use frame_support::{ - construct_runtime, ord_parameter_types, - pallet_prelude::{DispatchError, Weight}, - traits::Everything, -}; -use frame_system::EnsureSignedBy; +use frame_support::{construct_runtime, ord_parameter_types, traits::Everything, weights::Weight}; +use frame_system::{mocking::MockBlock, EnsureSignedBy}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, DispatchError, }; use zeitgeist_primitives::{ constants::mock::{ - AuthorizedPalletId, BlockHashCount, CorrectionPeriod, MaxReserves, MinimumPeriod, BASE, + AuthorizedPalletId, BlockHashCount, CorrectionPeriod, ExistentialDeposit, MaxLocks, + MaxReserves, MinimumPeriod, BASE, }, traits::{DisputeResolutionApi, MarketOfDisputeResolutionApi}, - types::{ - AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, MarketId, Moment, - UncheckedExtrinsicTest, - }, + types::{AccountIdTest, Balance, BlockNumber, Hash, MarketId, Moment}, }; pub const ALICE: AccountIdTest = 0; @@ -48,19 +42,14 @@ pub const BOB: AccountIdTest = 1; pub const CHARLIE: AccountIdTest = 2; construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - Authorized: zrml_authorized::{Event, Pallet, Storage}, - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - MarketCommons: zrml_market_commons::{Pallet, Storage}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, + pub enum Runtime { + Authorized: zrml_authorized, + Balances: pallet_balances, + MarketCommons: zrml_market_commons, + System: frame_system, + Timestamp: pallet_timestamp, // Just a mock storage for testing. - MockStorage: mock_storage::{Storage}, + MockStorage: mock_storage, } ); @@ -113,7 +102,7 @@ impl DisputeResolutionApi for MockResolution { impl crate::Config for Runtime { type Currency = Balances; - type RuntimeEvent = (); + type RuntimeEvent = RuntimeEvent; type CorrectionPeriod = CorrectionPeriod; type DisputeResolution = MockResolution; type MarketCommons = MarketCommons; @@ -131,18 +120,17 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); - type RuntimeEvent = (); + type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); @@ -158,9 +146,13 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); - type RuntimeEvent = (); - type ExistentialDeposit = (); - type MaxLocks = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); + type RuntimeEvent = RuntimeEvent; + type ExistentialDeposit = ExistentialDeposit; + type MaxHolds = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); @@ -191,7 +183,7 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); diff --git a/zrml/authorized/src/mock_storage.rs b/zrml/authorized/src/mock_storage.rs index a58bb2748..cacbc6926 100644 --- a/zrml/authorized/src/mock_storage.rs +++ b/zrml/authorized/src/mock_storage.rs @@ -23,6 +23,7 @@ pub(crate) mod pallet { use core::marker::PhantomData; use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::BlockNumberFor; use zrml_market_commons::MarketCommonsPalletApi; pub(crate) type MarketIdOf = @@ -32,7 +33,7 @@ pub(crate) mod pallet { #[pallet::config] pub trait Config: frame_system::Config { - type MarketCommons: MarketCommonsPalletApi; + type MarketCommons: MarketCommonsPalletApi>; } #[pallet::pallet] @@ -43,7 +44,7 @@ pub(crate) mod pallet { pub(crate) type MarketIdsPerDisputeBlock = StorageMap< _, Twox64Concat, - T::BlockNumber, + BlockNumberFor, BoundedVec, CacheSize>, ValueQuery, >; diff --git a/zrml/authorized/src/tests.rs b/zrml/authorized/src/tests.rs index 81192a638..d871247c3 100644 --- a/zrml/authorized/src/tests.rs +++ b/zrml/authorized/src/tests.rs @@ -24,7 +24,8 @@ use crate::{ mock_storage::pallet as mock_storage, AuthorizedOutcomeReports, Error, }; -use frame_support::{assert_noop, assert_ok, dispatch::DispatchError}; +use frame_support::{assert_noop, assert_ok}; +use sp_runtime::DispatchError; use zeitgeist_primitives::{ traits::DisputeApi, types::{AuthorityReport, MarketDisputeMechanism, MarketStatus, OutcomeReport}, diff --git a/zrml/market-commons/src/migrations.rs b/zrml/market-commons/src/migrations.rs index 791d9dabb..6fc68013b 100644 --- a/zrml/market-commons/src/migrations.rs +++ b/zrml/market-commons/src/migrations.rs @@ -27,7 +27,7 @@ use frame_system::pallet_prelude::BlockNumberFor; use log; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; -use sp_runtime::{DispatchError, Perbill, RuntimeDebug, Saturating}; +use sp_runtime::{Perbill, RuntimeDebug, Saturating}; use zeitgeist_primitives::types::{ BaseAsset, Deadlines, EarlyClose, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, MarketType, OutcomeReport, Report, ScoringRule, @@ -38,6 +38,7 @@ use { crate::MarketIdOf, alloc::{collections::BTreeMap, format}, frame_support::migration::storage_key_iter, + sp_runtime::DispatchError, }; #[cfg(any(feature = "try-runtime", feature = "test"))] diff --git a/zrml/market-commons/src/mock.rs b/zrml/market-commons/src/mock.rs index c9b5f20b2..ebc14469b 100644 --- a/zrml/market-commons/src/mock.rs +++ b/zrml/market-commons/src/mock.rs @@ -20,7 +20,7 @@ use crate::{self as zrml_market_commons}; use frame_support::{construct_runtime, traits::Everything}; -use frame_system::mocking::MockBlockU32; +use frame_system::mocking::MockBlock; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, BuildStorage, @@ -49,7 +49,7 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; - type Block = MockBlockU32; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); type BlockWeights = (); diff --git a/zrml/market-commons/src/tests.rs b/zrml/market-commons/src/tests.rs index 392e1fcfd..a7d26af88 100644 --- a/zrml/market-commons/src/tests.rs +++ b/zrml/market-commons/src/tests.rs @@ -47,9 +47,9 @@ fn create_market_builder(oracle: AccountIdOf) -> MarketBuilder .oracle(oracle) .period(MarketPeriod::Block(0..100)) .deadlines(Deadlines { - grace_period: 1_u32, - oracle_duration: 1_u32, - dispute_duration: 1_u32, + grace_period: 1_u64, + oracle_duration: 1_u64, + dispute_duration: 1_u64, }) .report(None) .resolved_outcome(None) From 98ac18d74aacb10f07125bbdc405d20530b4b7dd Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 15:11:45 +0200 Subject: [PATCH 04/16] Upgrade zrml-court --- Cargo.lock | 1 + primitives/src/constants/mock.rs | 2 +- zrml/court/Cargo.toml | 1 + zrml/court/src/benchmarks.rs | 43 ++++++++++++++------------- zrml/court/src/lib.rs | 47 +++++++++++++++-------------- zrml/court/src/mock.rs | 51 ++++++++++++++------------------ zrml/court/src/mock_storage.rs | 10 ++++--- zrml/court/src/tests.rs | 42 ++++++++++++++------------ 8 files changed, 103 insertions(+), 94 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5406da71b..47467504c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15047,6 +15047,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "log", "pallet-balances", "pallet-insecure-randomness-collective-flip", "pallet-timestamp", diff --git a/primitives/src/constants/mock.rs b/primitives/src/constants/mock.rs index 9cf150d8a..e38b7b97e 100644 --- a/primitives/src/constants/mock.rs +++ b/primitives/src/constants/mock.rs @@ -164,7 +164,7 @@ parameter_types! { // Shared within tests // Balance parameter_types! { - pub const ExistentialDeposit: u128 = CENT; + pub const ExistentialDeposit: u128 = 2; pub const MaxLocks: u32 = 50; pub const MaxReserves: u32 = 50; } diff --git a/zrml/court/Cargo.toml b/zrml/court/Cargo.toml index 6f4572b1d..e1a278cad 100644 --- a/zrml/court/Cargo.toml +++ b/zrml/court/Cargo.toml @@ -3,6 +3,7 @@ arrayvec = { workspace = true } frame-benchmarking = { workspace = true, optional = true } frame-support = { workspace = true } frame-system = { workspace = true } +log = { workspace = true } parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } rand = { workspace = true, features = ["alloc", "std_rng"] } rand_chacha = { workspace = true } diff --git a/zrml/court/src/benchmarks.rs b/zrml/court/src/benchmarks.rs index f463facfc..ace5d2ce1 100644 --- a/zrml/court/src/benchmarks.rs +++ b/zrml/court/src/benchmarks.rs @@ -31,8 +31,8 @@ use crate::{ }; use alloc::{vec, vec::Vec}; use frame_benchmarking::{account, benchmarks, whitelisted_caller}; -use frame_support::traits::{Currency, Get, NamedReservableCurrency}; -use frame_system::RawOrigin; +use frame_support::traits::{Currency, Get, Imbalance, NamedReservableCurrency}; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_arithmetic::Perbill; use sp_runtime::{ traits::{Bounded, Hash, Saturating, StaticLookup, Zero}, @@ -64,15 +64,16 @@ where metadata: vec![], oracle: account("oracle", 0, 0), period: MarketPeriod::Block( - 0u64.saturated_into::()..100u64.saturated_into::(), + 0u64.saturated_into::>() + ..100u64.saturated_into::>(), ), deadlines: Deadlines { - grace_period: 1_u64.saturated_into::(), - oracle_duration: 1_u64.saturated_into::(), - dispute_duration: 1_u64.saturated_into::(), + grace_period: 1_u64.saturated_into::>(), + oracle_duration: 1_u64.saturated_into::>(), + dispute_duration: 1_u64.saturated_into::>(), }, report: Some(Report { - at: 1u64.saturated_into::(), + at: 1u64.saturated_into::>(), by: account("oracle", 0, 0), outcome: ORACLE_REPORT, }), @@ -128,7 +129,7 @@ where court_participant: juror.clone(), consumed_stake, joined_at, - uneligible_index: 0u64.saturated_into::(), + uneligible_index: 0u64.saturated_into::>(), uneligible_stake: BalanceOf::::zero(), }; match pool.binary_search_by_key(&(stake, &juror), |pool_item| { @@ -178,10 +179,10 @@ fn setup_court() -> Result<(crate::MarketIdOf, CourtId), &'static str> where T: Config, { - >::set_block_number(1u64.saturated_into::()); + >::set_block_number(1u64.saturated_into::>()); let now = >::block_number(); - >::put(now + 1u64.saturated_into::()); + >::put(now + 1u64.saturated_into::>()); let market_id = T::MarketCommons::push_market(get_market::()).unwrap(); Court::::on_dispute(&market_id, &get_market::()).unwrap(); @@ -262,7 +263,7 @@ benchmarks! { joined_at_before, ); >::set_block_number( - joined_at_before + 1u64.saturated_into::(), + joined_at_before + 1u64.saturated_into::>(), ); let new_stake = T::MinJurorStake::get() @@ -298,7 +299,7 @@ benchmarks! { joined_at_before, ); >::set_block_number( - joined_at_before + 1u64.saturated_into::(), + joined_at_before + 1u64.saturated_into::>(), ); let juror_pool = >::get(); @@ -411,7 +412,7 @@ benchmarks! { >::insert(court_id, draws); >::set_block_number( - pre_vote + 1u64.saturated_into::(), + pre_vote + 1u64.saturated_into::>(), ); let commitment_vote = Default::default(); @@ -466,7 +467,7 @@ benchmarks! { >::insert(court_id, draws); >::set_block_number( - pre_vote + 1u64.saturated_into::(), + pre_vote + 1u64.saturated_into::>(), ); }: _(RawOrigin::Signed(caller), court_id, denounced_juror_unlookup, vote_item.clone(), salt) verify { @@ -515,7 +516,7 @@ benchmarks! { >::insert(court_id, draws); >::set_block_number( - vote_end + 1u64.saturated_into::() + vote_end + 1u64.saturated_into::>() ); }: _(RawOrigin::Signed(caller.clone()), court_id, vote_item.clone(), salt) verify { @@ -587,9 +588,9 @@ benchmarks! { } >::insert(court_id, draws); - >::set_block_number(aggregation + 1u64.saturated_into::()); + >::set_block_number(aggregation + 1u64.saturated_into::>()); let now = >::block_number(); - >::put(now + 1u64.saturated_into::()); + >::put(now + 1u64.saturated_into::>()); let new_resolve_at = >::get() + T::VotePeriod::get() @@ -699,7 +700,7 @@ benchmarks! { let r in 0..62; let now = >::block_number(); - let pre_vote_end = now + 1u64.saturated_into::(); + let pre_vote_end = now + 1u64.saturated_into::>(); >::put(pre_vote_end); let appeal_end = pre_vote_end @@ -763,7 +764,8 @@ benchmarks! { for i in 0..a { let backer = account("backer", i, 0); let bond = T::MinJurorStake::get(); - let _ = T::Currency::deposit_creating(&backer, bond); + let deposit = bond.saturating_add(T::Currency::minimum_balance()); + assert_eq!(T::Currency::deposit_creating(&backer, deposit).peek(), deposit); T::Currency::reserve_named(&Court::::reserve_id(), &backer, bond).unwrap(); let appeal_info = AppealInfo { backer, @@ -813,7 +815,8 @@ benchmarks! { for i in 0..a { let backer = account("backer", i, 0); let bond = T::MinJurorStake::get(); - let _ = T::Currency::deposit_creating(&backer, bond); + let deposit = bond.saturating_add(T::Currency::minimum_balance()); + assert_eq!(T::Currency::deposit_creating(&backer, deposit).peek(), deposit); T::Currency::reserve_named(&Court::::reserve_id(), &backer, bond).unwrap(); let appeal_info = AppealInfo { backer, diff --git a/zrml/court/src/lib.rs b/zrml/court/src/lib.rs index d3c83f8c2..1dcbb6580 100644 --- a/zrml/court/src/lib.rs +++ b/zrml/court/src/lib.rs @@ -34,22 +34,25 @@ use alloc::{ use core::marker::PhantomData; use frame_support::{ dispatch::DispatchResult, - ensure, log, + ensure, pallet_prelude::{ ConstU32, Decode, DispatchResultWithPostInfo, Encode, EnsureOrigin, Hooks, OptionQuery, - StorageMap, StorageValue, TypeInfo, ValueQuery, Weight, + StorageMap, StorageValue, TypeInfo, ValueQuery, }, traits::{ Currency, Get, Imbalance, IsType, LockIdentifier, LockableCurrency, NamedReservableCurrency, OnUnbalanced, Randomness, ReservableCurrency, StorageVersion, WithdrawReasons, }, - transactional, Blake2_128Concat, BoundedVec, PalletId, RuntimeDebug, Twox64Concat, + transactional, + weights::Weight, + Blake2_128Concat, BoundedVec, PalletId, Twox64Concat, }; use frame_system::{ ensure_signed, pallet_prelude::{BlockNumberFor, OriginFor}, }; +use log; use rand::{seq::SliceRandom, Rng, RngCore, SeedableRng}; use rand_chacha::ChaCha20Rng; use sp_arithmetic::{ @@ -58,7 +61,7 @@ use sp_arithmetic::{ }; use sp_runtime::{ traits::{AccountIdConversion, CheckedDiv, Hash, Saturating, StaticLookup, Zero}, - DispatchError, Perbill, SaturatedConversion, + DispatchError, Perbill, RuntimeDebug, SaturatedConversion, }; use zeitgeist_macros::unreachable_non_terminating; use zeitgeist_primitives::{ @@ -97,19 +100,19 @@ mod pallet { /// The expected blocks per year to calculate the inflation emission. #[pallet::constant] - type BlocksPerYear: Get; + type BlocksPerYear: Get>; /// The time in which the jurors can cast their commitment vote. #[pallet::constant] - type VotePeriod: Get; + type VotePeriod: Get>; /// The time in which the jurors should reveal their commitment vote. #[pallet::constant] - type AggregationPeriod: Get; + type AggregationPeriod: Get>; /// The time in which a court case can get appealed. #[pallet::constant] - type AppealPeriod: Get; + type AppealPeriod: Get>; /// The court lock identifier. #[pallet::constant] @@ -122,12 +125,12 @@ mod pallet { /// The currency implementation used to transfer, lock and reserve tokens. type Currency: Currency + NamedReservableCurrency - + LockableCurrency; + + LockableCurrency>; /// The functionality to allow controlling the markets resolution time. type DisputeResolution: DisputeResolutionApi< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, MarketId = MarketIdOf, Moment = MomentOf, >; @@ -137,12 +140,12 @@ mod pallet { /// The inflation period in which new tokens are minted. #[pallet::constant] - type InflationPeriod: Get; + type InflationPeriod: Get>; /// Market commons type MarketCommons: MarketCommonsPalletApi< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, Balance = BalanceOf, >; @@ -184,11 +187,11 @@ mod pallet { type MonetaryGovernanceOrigin: EnsureOrigin; /// Randomness source - type Random: Randomness; + type Random: Randomness>; /// The global interval which schedules the start of new court vote periods. #[pallet::constant] - type RequestInterval: Get; + type RequestInterval: Get>; /// Handler for slashed funds. type Slash: OnUnbalanced>; @@ -222,7 +225,7 @@ mod pallet { pub(crate) type MarketOf = Market< AccountIdOf, BalanceOf, - ::BlockNumber, + BlockNumberFor, MomentOf, BaseAsset, MarketIdOf, @@ -230,7 +233,7 @@ mod pallet { pub(crate) type HashOf = ::Hash; pub(crate) type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; - pub(crate) type CourtOf = CourtInfo<::BlockNumber, AppealsOf>; + pub(crate) type CourtOf = CourtInfo, AppealsOf>; pub(crate) type DelegatedStakesOf = BoundedVec<(AccountIdOf, BalanceOf), ::MaxDelegations>; pub(crate) type SelectionValueOf = SelectionValue, DelegatedStakesOf>; @@ -296,7 +299,7 @@ mod pallet { /// The future block number when jurors should start voting. /// This is useful for the user experience of the jurors to vote for multiple courts at once. #[pallet::storage] - pub type RequestBlock = StorageValue<_, T::BlockNumber, ValueQuery>; + pub type RequestBlock = StorageValue<_, BlockNumberFor, ValueQuery>; #[pallet::type_value] pub fn DefaultYearlyInflation() -> Perbill { @@ -489,8 +492,8 @@ mod pallet { } #[pallet::hooks] - impl Hooks for Pallet { - fn on_initialize(now: T::BlockNumber) -> Weight { + impl Hooks> for Pallet { + fn on_initialize(now: BlockNumberFor) -> Weight { let mut total_weight: Weight = Weight::zero(); total_weight = total_weight.saturating_add(Self::handle_inflation(now)); total_weight = total_weight.saturating_add(T::DbWeight::get().reads(1)); @@ -1363,7 +1366,7 @@ mod pallet { } // Handle the external incentivisation of the court system. - pub(crate) fn handle_inflation(now: T::BlockNumber) -> Weight { + pub(crate) fn handle_inflation(now: BlockNumberFor) -> Weight { let inflation_period = T::InflationPeriod::get(); match now.checked_rem(&inflation_period) { Some(rem) if rem.is_zero() => (), @@ -1968,7 +1971,7 @@ mod pallet { pub(crate) fn check_appealable_market( court_id: CourtId, court: &CourtOf, - now: T::BlockNumber, + now: BlockNumberFor, ) -> Result<(), DispatchError> { if let Some(market_id) = >::get(court_id) { let market = T::MarketCommons::market(&market_id)?; @@ -2308,7 +2311,7 @@ mod pallet { type AccountId = T::AccountId; type Balance = BalanceOf; type NegativeImbalance = NegativeImbalanceOf; - type BlockNumber = T::BlockNumber; + type BlockNumber = BlockNumberFor; type MarketId = MarketIdOf; type Moment = MomentOf; type Origin = T::RuntimeOrigin; diff --git a/zrml/court/src/mock.rs b/zrml/court/src/mock.rs index 6af67d134..ccfba25a7 100644 --- a/zrml/court/src/mock.rs +++ b/zrml/court/src/mock.rs @@ -26,23 +26,20 @@ use frame_support::{ traits::{Everything, Hooks, NeverEnsureOrigin}, PalletId, }; -use frame_system::{EnsureRoot, EnsureSignedBy}; +use frame_system::{mocking::MockBlock, EnsureRoot, EnsureSignedBy}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use zeitgeist_primitives::{ constants::mock::{ AggregationPeriod, AppealBond, AppealPeriod, BlockHashCount, BlocksPerYear, CourtPalletId, - InflationPeriod, LockId, MaxAppeals, MaxApprovals, MaxCourtParticipants, MaxDelegations, - MaxReserves, MaxSelectedDraws, MaxYearlyInflation, MinJurorStake, MinimumPeriod, - RequestInterval, VotePeriod, BASE, + ExistentialDeposit, InflationPeriod, LockId, MaxAppeals, MaxApprovals, + MaxCourtParticipants, MaxDelegations, MaxLocks, MaxReserves, MaxSelectedDraws, + MaxYearlyInflation, MinJurorStake, MinimumPeriod, RequestInterval, VotePeriod, BASE, }, traits::{DisputeResolutionApi, MarketOfDisputeResolutionApi}, - types::{ - AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, MarketId, Moment, - UncheckedExtrinsicTest, - }, + types::{AccountIdTest, Balance, BlockNumber, Hash, MarketId, Moment}, }; pub const ALICE: AccountIdTest = 0; @@ -63,20 +60,15 @@ parameter_types! { } construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - Court: zrml_court::{Event, Pallet, Storage}, - MarketCommons: zrml_market_commons::{Pallet, Storage}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, - Treasury: pallet_treasury::{Call, Event, Pallet, Storage}, + pub enum Runtime { + Balances: pallet_balances, + Court: zrml_court, + MarketCommons: zrml_market_commons, + System: frame_system, + Timestamp: pallet_timestamp, + Treasury: pallet_treasury, // Just a mock storage for testing. - MockStorage: mock_storage::{Storage}, + MockStorage: mock_storage, } ); @@ -161,18 +153,17 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); @@ -188,9 +179,13 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = (); - type MaxLocks = (); + type ExistentialDeposit = ExistentialDeposit; + type MaxHolds = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); @@ -249,7 +244,7 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); diff --git a/zrml/court/src/mock_storage.rs b/zrml/court/src/mock_storage.rs index 296766ea7..5d5599a28 100644 --- a/zrml/court/src/mock_storage.rs +++ b/zrml/court/src/mock_storage.rs @@ -19,6 +19,7 @@ #![allow(dead_code)] #![allow(unused_imports)] +use frame_system::pallet_prelude::BlockNumberFor; pub use pallet::*; use parity_scale_codec::Encode; use sp_runtime::traits::Hash; @@ -27,6 +28,7 @@ use sp_runtime::traits::Hash; pub(crate) mod pallet { use core::marker::PhantomData; use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::BlockNumberFor; use zrml_market_commons::MarketCommonsPalletApi; pub(crate) type MarketIdOf = @@ -36,7 +38,7 @@ pub(crate) mod pallet { #[pallet::config] pub trait Config: frame_system::Config { - type MarketCommons: MarketCommonsPalletApi; + type MarketCommons: MarketCommonsPalletApi>; } #[pallet::pallet] @@ -47,14 +49,14 @@ pub(crate) mod pallet { pub(crate) type MarketIdsPerDisputeBlock = StorageMap< _, Twox64Concat, - T::BlockNumber, + BlockNumberFor, BoundedVec, CacheSize>, ValueQuery, >; } -impl frame_support::traits::Randomness for Pallet { - fn random(subject: &[u8]) -> (T::Hash, T::BlockNumber) { +impl frame_support::traits::Randomness> for Pallet { + fn random(subject: &[u8]) -> (T::Hash, BlockNumberFor) { let block_number = >::block_number(); let seed = subject.using_encoded(T::Hashing::hash); diff --git a/zrml/court/src/tests.rs b/zrml/court/src/tests.rs index b0c80d6dc..3ac398a58 100644 --- a/zrml/court/src/tests.rs +++ b/zrml/court/src/tests.rs @@ -33,12 +33,18 @@ use crate::{ }; use alloc::collections::BTreeMap; use frame_support::{ - assert_noop, assert_ok, storage_root, - traits::{fungible::Balanced, tokens::imbalance::Imbalance, Currency, NamedReservableCurrency}, - StateVersion, + assert_noop, assert_ok, + storage::child::StateVersion, + traits::{ + fungible::Balanced, + tokens::{imbalance::Imbalance, Precision}, + Currency, NamedReservableCurrency, + }, }; +use frame_system::pallet_prelude::BlockNumberFor; use pallet_balances::{BalanceLock, NegativeImbalance}; use rand::seq::SliceRandom; +use sp_io::storage::root as storage_root; use sp_runtime::{ traits::{BlakeTwo256, Hash, Zero}, Perbill, Perquintill, @@ -61,8 +67,6 @@ use zeitgeist_primitives::{ }; use zrml_market_commons::{Error as MError, MarketCommonsPalletApi}; -type BlockNumberOf = ::BlockNumber; - const ORACLE_REPORT: OutcomeReport = OutcomeReport::Scalar(u128::MAX); const DEFAULT_MARKET: MarketOf = Market { @@ -119,7 +123,7 @@ fn fill_juror_pool(jurors_len: u32) { for i in 0..jurors_len { let amount = MinJurorStake::get() + i as u128; let juror = (i + 1000) as u128; - let _ = Balances::deposit(&juror, amount).unwrap(); + let _ = Balances::deposit(&juror, amount, Precision::Exact).unwrap(); assert_ok!(Court::join_court(RuntimeOrigin::signed(juror), amount)); } } @@ -467,7 +471,7 @@ fn join_court_fails_amount_below_lowest_juror() { let max_amount = min_amount + max_accounts as u128; for i in 1..=max_accounts { let amount = max_amount - i as u128; - let _ = Balances::deposit(&(i as u128), amount).unwrap(); + let _ = Balances::deposit(&(i as u128), amount, Precision::Exact).unwrap(); assert_ok!(Court::join_court(RuntimeOrigin::signed(i as u128), amount)); } @@ -513,7 +517,7 @@ fn prepare_exit_court_removes_lowest_staked_juror() { for i in 0..CourtPoolOf::::bound() { let amount = min_amount + i as u128; let juror = i as u128; - let _ = Balances::deposit(&juror, amount).unwrap(); + let _ = Balances::deposit(&juror, amount, Precision::Exact).unwrap(); assert_ok!(Court::join_court(RuntimeOrigin::signed(juror), amount)); } @@ -541,7 +545,7 @@ fn prepare_exit_court_removes_middle_staked_juror() { for i in 0..CourtPoolOf::::bound() { let amount = min_amount + i as u128; let juror = i as u128; - let _ = Balances::deposit(&juror, amount).unwrap(); + let _ = Balances::deposit(&juror, amount, Precision::Exact).unwrap(); assert_ok!(Court::join_court(RuntimeOrigin::signed(juror), amount)); } @@ -571,7 +575,7 @@ fn prepare_exit_court_removes_highest_staked_juror() { for i in 0..CourtPoolOf::::bound() { let amount = min_amount + i as u128; let juror = i as u128; - let _ = Balances::deposit(&juror, amount).unwrap(); + let _ = Balances::deposit(&juror, amount, Precision::Exact).unwrap(); assert_ok!(Court::join_court(RuntimeOrigin::signed(juror), amount)); } @@ -606,7 +610,7 @@ fn join_court_binary_search_sorted_insert_works() { for i in random_numbers { let amount = max_amount - i as u128; let juror = i as u128; - let _ = Balances::deposit(&juror, amount).unwrap(); + let _ = Balances::deposit(&juror, amount, Precision::Exact).unwrap(); assert_ok!(Court::join_court(RuntimeOrigin::signed(juror), amount)); } @@ -2179,7 +2183,7 @@ fn reassign_court_stakes_slashes_loosers_and_awards_winners() { let reward_pot = Court::reward_pot(court_id); let tardy_or_denounced_value = 5 * MinJurorStake::get(); - let _ = Balances::deposit(&reward_pot, tardy_or_denounced_value).unwrap(); + let _ = Balances::deposit(&reward_pot, tardy_or_denounced_value, Precision::Exact).unwrap(); assert_ok!(Court::reassign_court_stakes(RuntimeOrigin::signed(EVE), court_id)); @@ -2298,7 +2302,7 @@ fn reassign_court_stakes_works_for_delegations() { let reward_pot = Court::reward_pot(court_id); let tardy_or_denounced_value = 5 * MinJurorStake::get(); - let _ = Balances::deposit(&reward_pot, tardy_or_denounced_value).unwrap(); + let _ = Balances::deposit(&reward_pot, tardy_or_denounced_value, Precision::Exact).unwrap(); assert_ok!(Court::reassign_court_stakes(RuntimeOrigin::signed(EVE), court_id)); @@ -2534,7 +2538,7 @@ fn exchange_slashes_unjustified_and_unreserves_justified_appealers() { }; let backer = number; - let _ = Balances::deposit(&backer, bond).unwrap(); + let _ = Balances::deposit(&backer, bond, Precision::Exact).unwrap(); assert_ok!(Balances::reserve_named(&Court::reserve_id(), &backer, bond)); let free_balance = Balances::free_balance(backer); free_balances_before.insert(backer, free_balance); @@ -2680,7 +2684,7 @@ fn choose_multiple_weighted_works() { for i in 0..necessary_draws_weight { let amount = MinJurorStake::get() + i as u128; let juror = i as u128; - let _ = Balances::deposit(&juror, amount).unwrap(); + let _ = Balances::deposit(&juror, amount, Precision::Exact).unwrap(); assert_ok!(Court::join_court(RuntimeOrigin::signed(juror), amount)); } let random_jurors = Court::choose_multiple_weighted(necessary_draws_weight).unwrap(); @@ -2723,7 +2727,7 @@ fn select_participants_fails_if_not_enough_jurors(appeal_number: usize) { for i in 0..(necessary_draws_weight - 1usize) { let amount = MinJurorStake::get() + i as u128; let juror = (i + 1000) as u128; - let _ = Balances::deposit(&juror, amount).unwrap(); + let _ = Balances::deposit(&juror, amount, Precision::Exact).unwrap(); assert_ok!(Court::join_court(RuntimeOrigin::signed(juror), amount)); } @@ -3106,7 +3110,7 @@ fn handle_inflation_works() { for number in jurors_list.iter() { let stake = *number; let juror = *number; - let _ = Balances::deposit(&juror, stake).unwrap(); + let _ = Balances::deposit(&juror, stake, Precision::Exact).unwrap(); free_balances_before.insert(juror, stake); jurors .try_push(CourtPoolItem { @@ -3211,7 +3215,7 @@ fn gain_equal( struct Params { stake: BalanceOf, - uneligible_index: BlockNumberOf, + uneligible_index: BlockNumberFor, uneligible_stake: BalanceOf, } @@ -3424,7 +3428,7 @@ fn handle_inflation_without_waiting_one_inflation_period() { for number in jurors_list.iter() { let stake = *number; let juror = *number; - let _ = Balances::deposit(&juror, stake).unwrap(); + let _ = Balances::deposit(&juror, stake, Precision::Exact).unwrap(); free_balances_before.insert(juror, stake); jurors .try_push(CourtPoolItem { From 8c2899793a782fdfb1ac0781ad2f99115c13cebe Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 16:19:09 +0200 Subject: [PATCH 05/16] Upgrade zrml-global-disputes --- Cargo.lock | 1 + zrml/global-disputes/Cargo.toml | 3 ++- zrml/global-disputes/src/lib.rs | 32 +++++++++++------------ zrml/global-disputes/src/mock.rs | 42 ++++++++++++++----------------- zrml/global-disputes/src/tests.rs | 8 +++--- zrml/global-disputes/src/utils.rs | 3 ++- 6 files changed, 44 insertions(+), 45 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 47467504c..bcaaadfcc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15073,6 +15073,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "log", "num-traits", "pallet-balances", "pallet-timestamp", diff --git a/zrml/global-disputes/Cargo.toml b/zrml/global-disputes/Cargo.toml index 797dba502..e93b1153f 100644 --- a/zrml/global-disputes/Cargo.toml +++ b/zrml/global-disputes/Cargo.toml @@ -2,6 +2,7 @@ frame-benchmarking = { workspace = true, optional = true } frame-support = { workspace = true } frame-system = { workspace = true } +log = { workspace = true } parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } scale-info = { workspace = true, features = ["derive"] } sp-runtime = { workspace = true } @@ -15,7 +16,7 @@ num-traits = { workspace = true, optional = true } [dev-dependencies] env_logger = { workspace = true } -pallet-balances = { workspace = true, features = ["default"] } +pallet-balances = { workspace = true, features = ["default", "insecure_zero_ed"] } pallet-timestamp = { workspace = true, features = ["default"] } sp-io = { workspace = true, features = ["default"] } zeitgeist-primitives = { workspace = true, features = ["mock", "default"] } diff --git a/zrml/global-disputes/src/lib.rs b/zrml/global-disputes/src/lib.rs index 4ac07e4c0..0fde17912 100644 --- a/zrml/global-disputes/src/lib.rs +++ b/zrml/global-disputes/src/lib.rs @@ -40,7 +40,7 @@ mod pallet { use crate::{types::*, weights::WeightInfoZeitgeist, GlobalDisputesPalletApi, InitialItemOf}; use core::marker::PhantomData; use frame_support::{ - ensure, log, + ensure, pallet_prelude::{ DispatchResultWithPostInfo, OptionQuery, StorageDoubleMap, StorageMap, ValueQuery, }, @@ -51,7 +51,11 @@ mod pallet { }, Blake2_128Concat, BoundedVec, PalletId, Twox64Concat, }; - use frame_system::{ensure_signed, pallet_prelude::OriginFor}; + use frame_system::{ + ensure_signed, + pallet_prelude::{BlockNumberFor, OriginFor}, + }; + use log; use sp_runtime::{ traits::{AccountIdConversion, CheckedDiv, Saturating, Zero}, DispatchError, DispatchResult, @@ -69,12 +73,8 @@ mod pallet { pub(crate) type OwnerInfoOf = BoundedVec, ::MaxOwners>; pub type OutcomeInfoOf = OutcomeInfo, BalanceOf, OwnerInfoOf>; - pub type GlobalDisputeInfoOf = GlobalDisputeInfo< - AccountIdOf, - BalanceOf, - OwnerInfoOf, - ::BlockNumber, - >; + pub type GlobalDisputeInfoOf = + GlobalDisputeInfo, BalanceOf, OwnerInfoOf, BlockNumberFor>; type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; pub type LockInfoOf = @@ -91,16 +91,16 @@ mod pallet { pub trait Config: frame_system::Config { /// The time period in which the addition of new outcomes are allowed. #[pallet::constant] - type AddOutcomePeriod: Get; + type AddOutcomePeriod: Get>; /// The currency implementation used to lock tokens for voting. - type Currency: LockableCurrency; + type Currency: LockableCurrency>; type RuntimeEvent: From> + IsType<::RuntimeEvent>; type DisputeResolution: DisputeResolutionApi< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, MarketId = MarketIdOf, Moment = MomentOf, >; @@ -117,7 +117,7 @@ mod pallet { type MarketCommons: MarketCommonsPalletApi< AccountId = Self::AccountId, Balance = BalanceOf, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, >; /// The maximum numbers of distinct markets @@ -142,7 +142,7 @@ mod pallet { /// The time period in which votes are allowed. #[pallet::constant] - type GdVotingPeriod: Get; + type GdVotingPeriod: Get>; /// The fee required to add a voting outcome. #[pallet::constant] @@ -764,16 +764,16 @@ mod pallet { } } - impl GlobalDisputesPalletApi, AccountIdOf, BalanceOf, T::BlockNumber> + impl GlobalDisputesPalletApi, AccountIdOf, BalanceOf, BlockNumberFor> for Pallet where T: Config, { - fn get_add_outcome_period() -> T::BlockNumber { + fn get_add_outcome_period() -> BlockNumberFor { T::AddOutcomePeriod::get() } - fn get_vote_period() -> T::BlockNumber { + fn get_vote_period() -> BlockNumberFor { T::GdVotingPeriod::get() } diff --git a/zrml/global-disputes/src/mock.rs b/zrml/global-disputes/src/mock.rs index 25132468a..796eea66e 100644 --- a/zrml/global-disputes/src/mock.rs +++ b/zrml/global-disputes/src/mock.rs @@ -24,21 +24,19 @@ use frame_support::{ parameter_types, traits::Everything, }; +use frame_system::mocking::MockBlock; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use zeitgeist_primitives::{ constants::mock::{ AddOutcomePeriod, BlockHashCount, GdVotingPeriod, GlobalDisputeLockId, - GlobalDisputesPalletId, MaxReserves, MinOutcomeVoteAmount, MinimumPeriod, RemoveKeysLimit, - VotingOutcomeFee, BASE, + GlobalDisputesPalletId, MaxLocks, MaxReserves, MinOutcomeVoteAmount, MinimumPeriod, + RemoveKeysLimit, VotingOutcomeFee, BASE, }, traits::{DisputeResolutionApi, MarketOfDisputeResolutionApi}, - types::{ - AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, MarketId, Moment, - UncheckedExtrinsicTest, - }, + types::{AccountIdTest, Balance, BlockNumber, Hash, MarketId, Moment}, }; pub const ALICE: AccountIdTest = 0; @@ -49,17 +47,12 @@ pub const POOR_PAUL: AccountIdTest = 4; pub const DAVE: AccountIdTest = 5; construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - MarketCommons: zrml_market_commons::{Pallet, Storage}, - GlobalDisputes: zrml_global_disputes::{Event, Pallet, Storage}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, + pub enum Runtime { + Balances: pallet_balances, + MarketCommons: zrml_market_commons, + GlobalDisputes: zrml_global_disputes, + System: frame_system, + Timestamp: pallet_timestamp, } ); @@ -122,18 +115,17 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); @@ -149,9 +141,13 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = (); - type MaxLocks = (); + type MaxHolds = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); @@ -190,7 +186,7 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); diff --git a/zrml/global-disputes/src/tests.rs b/zrml/global-disputes/src/tests.rs index 78b3ff94a..2c6951833 100644 --- a/zrml/global-disputes/src/tests.rs +++ b/zrml/global-disputes/src/tests.rs @@ -29,8 +29,8 @@ use frame_support::{ traits::{Currency, ReservableCurrency}, BoundedVec, }; -use pallet_balances::{BalanceLock, Error as BalancesError}; -use sp_runtime::{traits::Zero, SaturatedConversion}; +use pallet_balances::BalanceLock; +use sp_runtime::{traits::Zero, DispatchError, SaturatedConversion, TokenError}; use test_case::test_case; use zeitgeist_primitives::{ constants::mock::{ @@ -479,7 +479,7 @@ fn add_vote_outcome_fails_if_balance_too_low() { market_id, OutcomeReport::Scalar(80), ), - BalancesError::::InsufficientBalance + DispatchError::Token(TokenError::FundsUnavailable) ); }); } @@ -846,7 +846,7 @@ fn transfer_fails_with_fully_locked_balance() { assert_noop!( Balances::transfer(RuntimeOrigin::signed(*disputor), BOB, arbitrary_amount + 1), - pallet_balances::Error::::LiquidityRestrictions + DispatchError::Token(TokenError::Frozen) ); assert_ok!(Balances::transfer(RuntimeOrigin::signed(*disputor), BOB, arbitrary_amount)); }); diff --git a/zrml/global-disputes/src/utils.rs b/zrml/global-disputes/src/utils.rs index dabebc965..c26bd8865 100644 --- a/zrml/global-disputes/src/utils.rs +++ b/zrml/global-disputes/src/utils.rs @@ -18,11 +18,12 @@ #![cfg(any(feature = "runtime-benchmarks", test))] use crate::*; +use frame_system::pallet_prelude::BlockNumberFor; type MarketOf = zeitgeist_primitives::types::Market< ::AccountId, BalanceOf, - ::BlockNumber, + BlockNumberFor, MomentOf, zeitgeist_primitives::types::BaseAsset, MarketIdOf, From df9d93d74b9f32bb8e21205e17fdc01fa695cd58 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 16:35:46 +0200 Subject: [PATCH 06/16] Upgrade liquidity mining --- Cargo.lock | 1 + zrml/liquidity-mining/Cargo.toml | 1 + zrml/liquidity-mining/src/lib.rs | 24 ++++----- zrml/liquidity-mining/src/mock.rs | 49 ++++++++----------- zrml/liquidity-mining/src/tests.rs | 2 +- ...track_incentives_based_on_bought_shares.rs | 11 +++-- zrml/liquidity-mining/src/utils.rs | 3 +- 7 files changed, 44 insertions(+), 47 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bcaaadfcc..46e497431 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15135,6 +15135,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "log", "pallet-balances", "pallet-timestamp", "parity-scale-codec", diff --git a/zrml/liquidity-mining/Cargo.toml b/zrml/liquidity-mining/Cargo.toml index cecf83500..75783bf67 100644 --- a/zrml/liquidity-mining/Cargo.toml +++ b/zrml/liquidity-mining/Cargo.toml @@ -2,6 +2,7 @@ frame-benchmarking = { workspace = true, optional = true } frame-support = { workspace = true } frame-system = { workspace = true } +log = { workspace = true } parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } scale-info = { workspace = true, features = ["derive"] } serde = { workspace = true, optional = true } diff --git a/zrml/liquidity-mining/src/lib.rs b/zrml/liquidity-mining/src/lib.rs index a2346ebfa..bf20f998b 100644 --- a/zrml/liquidity-mining/src/lib.rs +++ b/zrml/liquidity-mining/src/lib.rs @@ -52,10 +52,9 @@ mod pallet { use alloc::vec::Vec; use core::marker::PhantomData; #[cfg(feature = "std")] - use frame_support::traits::GenesisBuild; + use frame_support::traits::BuildGenesisConfig; use frame_support::{ dispatch::DispatchResult, - log, storage::{ types::{StorageDoubleMap, StorageValue, ValueQuery}, with_transaction, @@ -65,7 +64,11 @@ mod pallet { }, Blake2_128Concat, PalletId, Twox64Concat, }; - use frame_system::{ensure_root, pallet_prelude::OriginFor}; + use frame_system::{ + ensure_root, + pallet_prelude::{BlockNumberFor, OriginFor}, + }; + use log; use sp_runtime::{ traits::{AccountIdConversion, Saturating}, TransactionOutcome, @@ -107,7 +110,7 @@ mod pallet { type MarketCommons: MarketCommonsPalletApi< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, MarketId = Self::MarketId, Balance = BalanceOf, >; @@ -141,9 +144,8 @@ mod pallet { FundDoesNotHaveEnoughBalance, } - #[cfg(feature = "std")] #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { let _ = T::Currency::deposit_creating( &Pallet::::pallet_account_id(), @@ -153,7 +155,6 @@ mod pallet { } } - #[cfg(feature = "std")] #[derive(scale_info::TypeInfo, Debug)] #[pallet::genesis_config] pub struct GenesisConfig { @@ -161,7 +162,6 @@ mod pallet { pub per_block_distribution: BalanceOf, } - #[cfg(feature = "std")] impl Default for GenesisConfig where T: Config, @@ -176,9 +176,9 @@ mod pallet { } #[pallet::hooks] - impl Hooks for Pallet { + impl Hooks> for Pallet { // Manages incentives on each block finalization. - fn on_finalize(block: T::BlockNumber) { + fn on_finalize(block: BlockNumberFor) { let fun = || { let added_len = TrackIncentivesBasedOnBoughtShares::::exec(block)?; if added_len > 0 { @@ -221,7 +221,7 @@ mod pallet { { type AccountId = T::AccountId; type Balance = BalanceOf; - type BlockNumber = T::BlockNumber; + type BlockNumber = BlockNumberFor; type MarketId = T::MarketId; fn add_shares( @@ -339,7 +339,7 @@ mod pallet { T::MarketId, Twox64Concat, T::AccountId, - OwnedValuesParams, T::BlockNumber>, + OwnedValuesParams, BlockNumberFor>, ValueQuery, >; diff --git a/zrml/liquidity-mining/src/mock.rs b/zrml/liquidity-mining/src/mock.rs index b4fa05cbc..6cd49ddc1 100644 --- a/zrml/liquidity-mining/src/mock.rs +++ b/zrml/liquidity-mining/src/mock.rs @@ -19,46 +19,36 @@ #![cfg(test)] use crate as zrml_liquidity_mining; -use frame_support::{ - construct_runtime, - traits::{Everything, GenesisBuild}, -}; +use frame_support::{construct_runtime, traits::Everything}; +use frame_system::mocking::MockBlock; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use zeitgeist_primitives::{ constants::mock::{ BlockHashCount, ExistentialDeposit, LiquidityMiningPalletId, MaxLocks, MaxReserves, MinimumPeriod, BASE, }, - types::{ - AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, MarketId, Moment, - UncheckedExtrinsicTest, - }, + types::{AccountIdTest, Balance, Hash, MarketId, Moment}, }; pub const ALICE: AccountIdTest = 0; pub const BOB: AccountIdTest = 1; construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - LiquidityMining: zrml_liquidity_mining::{Config, Event, Pallet}, - MarketCommons: zrml_market_commons::{Pallet, Storage}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, + pub enum Runtime { + Balances: pallet_balances, + LiquidityMining: zrml_liquidity_mining, + MarketCommons: zrml_market_commons, + System: frame_system, + Timestamp: pallet_timestamp, } ); impl crate::Config for Runtime { type Currency = Balances; - type RuntimeEvent = (); + type RuntimeEvent = RuntimeEvent; type MarketCommons = MarketCommons; type MarketId = MarketId; type PalletId = LiquidityMiningPalletId; @@ -69,18 +59,17 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); - type RuntimeEvent = (); + type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); @@ -96,11 +85,15 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); - type ReserveIdentifier = [u8; 8]; - type RuntimeEvent = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); + type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; + type MaxHolds = (); + type MaxFreezes = (); type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; type WeightInfo = (); } @@ -135,7 +128,7 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); diff --git a/zrml/liquidity-mining/src/tests.rs b/zrml/liquidity-mining/src/tests.rs index 68363ff8c..1ec6f0387 100644 --- a/zrml/liquidity-mining/src/tests.rs +++ b/zrml/liquidity-mining/src/tests.rs @@ -27,10 +27,10 @@ use crate::{ use core::ops::Range; use frame_support::{ assert_err, assert_ok, - dispatch::DispatchError, traits::{Currency, OnFinalize}, }; use frame_system::RawOrigin; +use sp_runtime::DispatchError; use zeitgeist_primitives::types::{ BaseAsset, Deadlines, Market, MarketBonds, MarketCreation, MarketDisputeMechanism, MarketPeriod, MarketStatus, MarketType, ScoringRule, diff --git a/zrml/liquidity-mining/src/track_incentives_based_on_bought_shares.rs b/zrml/liquidity-mining/src/track_incentives_based_on_bought_shares.rs index b62893e30..1e6efbd21 100644 --- a/zrml/liquidity-mining/src/track_incentives_based_on_bought_shares.rs +++ b/zrml/liquidity-mining/src/track_incentives_based_on_bought_shares.rs @@ -22,6 +22,7 @@ use crate::{ }; use alloc::{collections::BTreeSet, vec::Vec}; use core::marker::PhantomData; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::traits::{CheckedDiv, Saturating}; use zeitgeist_primitives::types::MarketPeriod; use zrml_market_commons::MarketCommonsPalletApi; @@ -37,7 +38,7 @@ impl TrackIncentivesBasedOnBoughtShares where T: crate::Config, { - pub(crate) fn exec(curr_block: T::BlockNumber) -> Option { + pub(crate) fn exec(curr_block: BlockNumberFor) -> Option { let per_block_incentives = >::get(); let market_incentives = Self::markets_incentives(per_block_incentives, curr_block)?; let market_incentives_len = market_incentives.len(); @@ -59,7 +60,7 @@ where let perpetual_incentives = calculate_perthousand_value(ppb, raw_incentives); let incentives = raw_incentives.saturating_sub(perpetual_incentives); >::mutate(market_id, account_id, |values| { - let one = T::BlockNumber::from(1u8); + let one = BlockNumberFor::::from(1u8); values.perpetual_incentives = values.perpetual_incentives.saturating_add(perpetual_incentives); @@ -94,7 +95,7 @@ where )] fn markets_incentives( per_block_incentives: BalanceOf, - curr_block: T::BlockNumber, + curr_block: BlockNumberFor, ) -> Option)>> { let mut normalized_total = BalanceOf::::from(0u8); let markets_periods: BTreeSet<_> = >::iter().map(|el| el.0).collect(); @@ -141,9 +142,9 @@ where // // The greater the output, the more incentives the market will receive fn normalize_market( - curr_block: T::BlockNumber, + curr_block: BlockNumberFor, now: MomentOf, - period: &MarketPeriod>, + period: &MarketPeriod, MomentOf>, ) -> BalanceOf { let opt = match period { MarketPeriod::Block(range) => { diff --git a/zrml/liquidity-mining/src/utils.rs b/zrml/liquidity-mining/src/utils.rs index f05276dd3..c6f464838 100644 --- a/zrml/liquidity-mining/src/utils.rs +++ b/zrml/liquidity-mining/src/utils.rs @@ -17,6 +17,7 @@ use crate::MomentOf; use core::ops::{Div, Range}; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{ traits::{CheckedDiv, Saturating, UniqueSaturatedInto}, SaturatedConversion, @@ -29,7 +30,7 @@ use zeitgeist_primitives::constants::MILLISECS_PER_BLOCK; // To convert the block number type to the moment type, is is necessary to first convert the // block number value to `u32`, which caps the maximum output to `u32::MAX`. Since this function // is only used to evaluate perpetual balances, such limitation shouldn't be a problem. -pub fn calculate_average_blocks_of_a_time_period(range: &Range>) -> T::BlockNumber +pub fn calculate_average_blocks_of_a_time_period(range: &Range>) -> BlockNumberFor where T: crate::Config, { From eb69c207d1b1e11cef1d3c3d5149015210b5529d Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 16:42:36 +0200 Subject: [PATCH 07/16] Upgrade zrml-rikiddo --- zrml/rikiddo/src/lib.rs | 3 +- zrml/rikiddo/src/mock.rs | 42 +++++++++----------- zrml/rikiddo/src/types.rs | 3 +- zrml/rikiddo/src/types/ema_market_volume.rs | 3 +- zrml/rikiddo/src/types/rikiddo_sigmoid_mv.rs | 3 +- zrml/rikiddo/src/types/sigmoid_fee.rs | 3 +- 6 files changed, 25 insertions(+), 32 deletions(-) diff --git a/zrml/rikiddo/src/lib.rs b/zrml/rikiddo/src/lib.rs index be7f94817..2c64058f0 100644 --- a/zrml/rikiddo/src/lib.rs +++ b/zrml/rikiddo/src/lib.rs @@ -72,6 +72,7 @@ pub mod pallet { traits::{Get, Hooks, StorageVersion, Time}, Twox64Concat, }; + use frame_system::pallet_prelude::BlockNumberFor; use parity_scale_codec::{Decode, Encode, FullCodec, FullEncode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_runtime::DispatchError; @@ -150,7 +151,7 @@ pub mod pallet { StorageMap<_, Twox64Concat, T::PoolId, T::Rikiddo>; #[pallet::hooks] - impl, I: 'static> Hooks for Pallet {} + impl, I: 'static> Hooks> for Pallet {} #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] diff --git a/zrml/rikiddo/src/mock.rs b/zrml/rikiddo/src/mock.rs index 970a89d40..ea9fe77dd 100644 --- a/zrml/rikiddo/src/mock.rs +++ b/zrml/rikiddo/src/mock.rs @@ -26,17 +26,15 @@ use crate::types::{EmaMarketVolume, FeeSigmoid, RikiddoSigmoidMV}; use frame_support::{construct_runtime, parameter_types, traits::Everything}; +use frame_system::mocking::MockBlock; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use substrate_fixed::{types::extra::U33, FixedI128, FixedU128}; use zeitgeist_primitives::{ - constants::mock::{BlockHashCount, ExistentialDeposit, MaxReserves, BASE}, - types::{ - AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, Moment, PoolId, - UncheckedExtrinsicTest, - }, + constants::mock::{BlockHashCount, ExistentialDeposit, MaxLocks, MaxReserves, BASE}, + types::{AccountIdTest, Balance, Hash, Moment, PoolId}, }; pub const ALICE: AccountIdTest = 0; @@ -52,16 +50,11 @@ parameter_types! { } construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - Rikiddo: crate::{Pallet, Storage}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Call, Pallet, Storage, Inherent}, + pub enum Runtime { + Balances: pallet_balances, + Rikiddo: crate, + System: frame_system, + Timestamp: pallet_timestamp, } ); @@ -84,37 +77,40 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); - type OnSetCode = (); type RuntimeOrigin = RuntimeOrigin; type PalletInfo = PalletInfo; type SS58Prefix = (); type SystemWeightInfo = (); type Version = (); + type OnSetCode = (); } impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); type RuntimeEvent = RuntimeEvent; - type MaxReserves = MaxReserves; type ExistentialDeposit = ExistentialDeposit; - type MaxLocks = (); + type MaxHolds = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; + type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); } @@ -147,7 +143,7 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); diff --git a/zrml/rikiddo/src/types.rs b/zrml/rikiddo/src/types.rs index cff58f86b..220ad624a 100644 --- a/zrml/rikiddo/src/types.rs +++ b/zrml/rikiddo/src/types.rs @@ -23,8 +23,7 @@ extern crate alloc; use arbitrary::{Arbitrary, Result as ArbiraryResult, Unstructured}; #[cfg(feature = "arbitrary")] use core::mem; -use frame_support::dispatch::{Decode, Encode}; -use parity_scale_codec::MaxEncodedLen; +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_core::RuntimeDebug; use substrate_fixed::traits::Fixed; diff --git a/zrml/rikiddo/src/types/ema_market_volume.rs b/zrml/rikiddo/src/types/ema_market_volume.rs index a6d49cd27..0a2fb7838 100644 --- a/zrml/rikiddo/src/types/ema_market_volume.rs +++ b/zrml/rikiddo/src/types/ema_market_volume.rs @@ -25,8 +25,7 @@ use crate::{ use arbitrary::{Arbitrary, Result as ArbitraryResult, Unstructured}; #[cfg(feature = "arbitrary")] use core::mem; -use frame_support::dispatch::{Decode, Encode}; -use parity_scale_codec::MaxEncodedLen; +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_core::RuntimeDebug; use substrate_fixed::{ diff --git a/zrml/rikiddo/src/types/rikiddo_sigmoid_mv.rs b/zrml/rikiddo/src/types/rikiddo_sigmoid_mv.rs index 65e355b5d..766ee97e2 100644 --- a/zrml/rikiddo/src/types/rikiddo_sigmoid_mv.rs +++ b/zrml/rikiddo/src/types/rikiddo_sigmoid_mv.rs @@ -28,9 +28,8 @@ use alloc::vec::Vec; #[cfg(feature = "arbitrary")] use arbitrary::{Arbitrary, Result as ArbiraryResult, Unstructured}; use core::ops::{AddAssign, BitOrAssign, ShlAssign}; -use frame_support::dispatch::{Decode, Encode}; use hashbrown::HashMap; -use parity_scale_codec::MaxEncodedLen; +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_core::RuntimeDebug; use substrate_fixed::{ diff --git a/zrml/rikiddo/src/types/sigmoid_fee.rs b/zrml/rikiddo/src/types/sigmoid_fee.rs index d122c64ec..5fcaf1f51 100644 --- a/zrml/rikiddo/src/types/sigmoid_fee.rs +++ b/zrml/rikiddo/src/types/sigmoid_fee.rs @@ -26,8 +26,7 @@ use crate::{ use arbitrary::{Arbitrary, Result as ArbiraryResult, Unstructured}; #[cfg(feature = "arbitrary")] use core::mem; -use frame_support::dispatch::{Decode, Encode}; -use parity_scale_codec::MaxEncodedLen; +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_core::RuntimeDebug; use substrate_fixed::{ From 76675ea002acc45751673a184ecc03b7ae18a7ed Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 16:53:11 +0200 Subject: [PATCH 08/16] Upgrade zrml-simple-disputes --- zrml/simple-disputes/Cargo.toml | 2 +- zrml/simple-disputes/src/benchmarks.rs | 3 +- zrml/simple-disputes/src/lib.rs | 31 +++++++-------- zrml/simple-disputes/src/mock.rs | 53 +++++++++++++------------- zrml/simple-disputes/src/weights.rs | 34 ++++++++--------- 5 files changed, 59 insertions(+), 64 deletions(-) diff --git a/zrml/simple-disputes/Cargo.toml b/zrml/simple-disputes/Cargo.toml index 75265192f..ee72953df 100644 --- a/zrml/simple-disputes/Cargo.toml +++ b/zrml/simple-disputes/Cargo.toml @@ -13,7 +13,7 @@ zrml-market-commons = { workspace = true } env_logger = { workspace = true } orml-currencies = { workspace = true, features = ["default"] } orml-tokens = { workspace = true, features = ["default"] } -pallet-balances = { workspace = true, features = ["default"] } +pallet-balances = { workspace = true, features = ["default", "insecure_zero_ed"] } pallet-timestamp = { workspace = true, features = ["default"] } sp-io = { workspace = true, features = ["default"] } zeitgeist-primitives = { workspace = true, features = ["mock", "default"] } diff --git a/zrml/simple-disputes/src/benchmarks.rs b/zrml/simple-disputes/src/benchmarks.rs index 2f06b5652..b9bfaff98 100644 --- a/zrml/simple-disputes/src/benchmarks.rs +++ b/zrml/simple-disputes/src/benchmarks.rs @@ -31,6 +31,7 @@ use frame_support::{ dispatch::RawOrigin, traits::{Currency, Get, Imbalance}, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::traits::{One, Saturating}; use zrml_market_commons::MarketCommonsPalletApi; @@ -47,7 +48,7 @@ fn fill_disputes(market_id: MarketIdOf, d: u32) { outcome, ) .unwrap(); - >::set_block_number(now.saturating_add(T::BlockNumber::one())); + >::set_block_number(now.saturating_add(BlockNumberFor::::one())); } } diff --git a/zrml/simple-disputes/src/lib.rs b/zrml/simple-disputes/src/lib.rs index ba02d764b..dd45645bd 100644 --- a/zrml/simple-disputes/src/lib.rs +++ b/zrml/simple-disputes/src/lib.rs @@ -53,12 +53,11 @@ mod pallet { traits::{Currency, Get, Hooks, Imbalance, IsType, NamedReservableCurrency}, transactional, BoundedVec, PalletId, }; - use frame_system::pallet_prelude::*; + use frame_system::pallet_prelude::{BlockNumberFor, *}; use sp_runtime::{ traits::{CheckedDiv, Saturating, Zero}, DispatchError, SaturatedConversion, }; - use zrml_market_commons::MarketCommonsPalletApi; #[pallet::config] @@ -74,7 +73,7 @@ mod pallet { type DisputeResolution: DisputeResolutionApi< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, MarketId = MarketIdOf, Moment = MomentOf, >; @@ -87,7 +86,7 @@ mod pallet { /// The identifier of individual markets. type MarketCommons: MarketCommonsPalletApi< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, Balance = BalanceOf, >; @@ -113,17 +112,13 @@ mod pallet { pub(crate) type MarketOf = Market< ::AccountId, BalanceOf, - ::BlockNumber, + BlockNumberFor, MomentOf, BaseAsset, MarketIdOf, >; pub(crate) type DisputesOf = BoundedVec< - MarketDispute< - ::AccountId, - ::BlockNumber, - BalanceOf, - >, + MarketDispute<::AccountId, BlockNumberFor, BalanceOf>, ::MaxDisputes, >; pub type CacheSize = ConstU32<64>; @@ -145,7 +140,7 @@ mod pallet { { OutcomeReserved { market_id: MarketIdOf, - dispute: MarketDispute>, + dispute: MarketDispute, BalanceOf>, }, } @@ -165,7 +160,7 @@ mod pallet { } #[pallet::hooks] - impl Hooks for Pallet {} + impl Hooks> for Pallet {} #[pallet::call] impl Pallet { @@ -224,8 +219,8 @@ mod pallet { } fn ensure_can_not_dispute_the_same_outcome( - disputes: &[MarketDispute>], - report: &Report, + disputes: &[MarketDispute, BalanceOf>], + report: &Report>, outcome: &OutcomeReport, ) -> DispatchResult { if let Some(last_dispute) = disputes.last() { @@ -253,16 +248,16 @@ mod pallet { } fn get_auto_resolve( - disputes: &[MarketDispute>], + disputes: &[MarketDispute, BalanceOf>], market: &MarketOf, - ) -> Option { + ) -> Option> { disputes.last().map(|last_dispute| { last_dispute.at.saturating_add(market.deadlines.dispute_duration) }) } fn remove_auto_resolve( - disputes: &[MarketDispute>], + disputes: &[MarketDispute, BalanceOf>], market_id: &MarketIdOf, market: &MarketOf, ) -> u32 { @@ -316,7 +311,7 @@ mod pallet { type AccountId = T::AccountId; type Balance = BalanceOf; type NegativeImbalance = NegativeImbalanceOf; - type BlockNumber = T::BlockNumber; + type BlockNumber = BlockNumberFor; type MarketId = MarketIdOf; type Moment = MomentOf; type Origin = T::RuntimeOrigin; diff --git a/zrml/simple-disputes/src/mock.rs b/zrml/simple-disputes/src/mock.rs index b74e497f0..8b61bd18e 100644 --- a/zrml/simple-disputes/src/mock.rs +++ b/zrml/simple-disputes/src/mock.rs @@ -24,19 +24,20 @@ use frame_support::{ pallet_prelude::{DispatchError, Weight}, traits::Everything, }; +use frame_system::mocking::MockBlock; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use zeitgeist_primitives::{ constants::mock::{ - BlockHashCount, ExistentialDepositsAssets, GetNativeCurrencyId, MaxDisputes, MaxReserves, - MinimumPeriod, OutcomeBond, OutcomeFactor, SimpleDisputesPalletId, BASE, + BlockHashCount, ExistentialDepositsAssets, GetNativeCurrencyId, MaxDisputes, MaxLocks, + MaxReserves, MinimumPeriod, OutcomeBond, OutcomeFactor, SimpleDisputesPalletId, BASE, }, traits::{DisputeResolutionApi, MarketOfDisputeResolutionApi}, types::{ - AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, Hash, - Index, MarketId, Moment, UncheckedExtrinsicTest, + AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, Hash, MarketId, + Moment, }, }; @@ -55,19 +56,14 @@ ord_parameter_types! { } construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - AssetManager: orml_currencies::{Call, Pallet, Storage}, - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - MarketCommons: zrml_market_commons::{Pallet, Storage}, - SimpleDisputes: zrml_simple_disputes::{Event, Pallet, Storage}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, - Tokens: orml_tokens::{Config, Event, Pallet, Storage}, + pub enum Runtime { + AssetManager: orml_currencies, + Balances: pallet_balances, + MarketCommons: zrml_market_commons, + SimpleDisputes: zrml_simple_disputes, + System: frame_system, + Timestamp: pallet_timestamp, + Tokens: orml_tokens, } ); @@ -106,7 +102,7 @@ impl DisputeResolutionApi for NoopResolution { impl crate::Config for Runtime { type Currency = Balances; - type RuntimeEvent = (); + type RuntimeEvent = RuntimeEvent; type DisputeResolution = NoopResolution; type MarketCommons = MarketCommons; type MaxDisputes = MaxDisputes; @@ -120,18 +116,17 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); - type RuntimeEvent = (); + type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); @@ -147,9 +142,13 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); - type RuntimeEvent = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); + type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = (); - type MaxLocks = (); + type MaxHolds = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); @@ -167,7 +166,7 @@ impl orml_tokens::Config for Runtime { type Balance = Balance; type CurrencyId = Assets; type DustRemovalWhitelist = Everything; - type RuntimeEvent = (); + type RuntimeEvent = RuntimeEvent; type ExistentialDeposits = ExistentialDepositsAssets; type MaxLocks = (); type MaxReserves = MaxReserves; @@ -211,7 +210,7 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); diff --git a/zrml/simple-disputes/src/weights.rs b/zrml/simple-disputes/src/weights.rs index bfbc6cc8c..1c5b8bb04 100644 --- a/zrml/simple-disputes/src/weights.rs +++ b/zrml/simple-disputes/src/weights.rs @@ -64,34 +64,34 @@ impl WeightInfoZeitgeist for WeightInfo { // Storage: Balances Reserves (r:1 w:1) // Storage: PredictionMarkets MarketIdsPerDisputeBlock (r:2 w:2) fn suggest_outcome(d: u32, r: u32, e: u32) -> Weight { - Weight::from_ref_time(400_160_000) + Weight::from_parts(400_160_000, 0) // Standard Error: 1_302_000 - .saturating_add(Weight::from_ref_time(3_511_000).saturating_mul(d.into())) + .saturating_add(Weight::from_parts(3_511_000, 0).saturating_mul(d.into())) // Standard Error: 69_000 - .saturating_add(Weight::from_ref_time(324_000).saturating_mul(r.into())) + .saturating_add(Weight::from_parts(324_000, 0).saturating_mul(r.into())) // Standard Error: 69_000 - .saturating_add(Weight::from_ref_time(311_000).saturating_mul(e.into())) + .saturating_add(Weight::from_parts(311_000, 0).saturating_mul(e.into())) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) } fn on_dispute_weight() -> Weight { - Weight::from_ref_time(0) + Weight::from_all(0) } // Storage: SimpleDisputes Disputes (r:1 w:0) fn on_resolution_weight(d: u32) -> Weight { - Weight::from_ref_time(5_464_000) + Weight::from_parts(5_464_000, 0) // Standard Error: 3_000 - .saturating_add(Weight::from_ref_time(210_000).saturating_mul(d.into())) + .saturating_add(Weight::from_parts(210_000, 0).saturating_mul(d.into())) .saturating_add(T::DbWeight::get().reads(1)) } // Storage: SimpleDisputes Disputes (r:1 w:1) // Storage: Balances Reserves (r:1 w:1) // Storage: System Account (r:1 w:1) fn exchange_weight(d: u32) -> Weight { - Weight::from_ref_time(18_573_000) + Weight::from_parts(18_573_000, 0) // Standard Error: 14_000 - .saturating_add(Weight::from_ref_time(19_710_000).saturating_mul(d.into())) + .saturating_add(Weight::from_parts(19_710_000, 0).saturating_mul(d.into())) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(d.into()))) .saturating_add(T::DbWeight::get().writes(1)) @@ -99,32 +99,32 @@ impl WeightInfoZeitgeist for WeightInfo { } // Storage: SimpleDisputes Disputes (r:1 w:0) fn get_auto_resolve_weight(d: u32) -> Weight { - Weight::from_ref_time(5_535_000) + Weight::from_parts(5_535_000, 0) // Standard Error: 3_000 - .saturating_add(Weight::from_ref_time(145_000).saturating_mul(d.into())) + .saturating_add(Weight::from_parts(145_000, 0).saturating_mul(d.into())) .saturating_add(T::DbWeight::get().reads(1)) } // Storage: SimpleDisputes Disputes (r:1 w:0) fn has_failed_weight(d: u32) -> Weight { - Weight::from_ref_time(5_685_000) + Weight::from_parts(5_685_000, 0) // Standard Error: 2_000 - .saturating_add(Weight::from_ref_time(117_000).saturating_mul(d.into())) + .saturating_add(Weight::from_parts(117_000, 0).saturating_mul(d.into())) .saturating_add(T::DbWeight::get().reads(1)) } // Storage: SimpleDisputes Disputes (r:1 w:0) fn on_global_dispute_weight(d: u32) -> Weight { - Weight::from_ref_time(5_815_000) + Weight::from_parts(5_815_000, 0) // Standard Error: 2_000 - .saturating_add(Weight::from_ref_time(66_000).saturating_mul(d.into())) + .saturating_add(Weight::from_parts(66_000, 0).saturating_mul(d.into())) .saturating_add(T::DbWeight::get().reads(1)) } // Storage: SimpleDisputes Disputes (r:1 w:1) // Storage: Balances Reserves (r:1 w:1) // Storage: System Account (r:1 w:1) fn clear_weight(d: u32) -> Weight { - Weight::from_ref_time(15_958_000) + Weight::from_parts(15_958_000, 0) // Standard Error: 17_000 - .saturating_add(Weight::from_ref_time(13_085_000).saturating_mul(d.into())) + .saturating_add(Weight::from_parts(13_085_000, 0).saturating_mul(d.into())) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(d.into()))) .saturating_add(T::DbWeight::get().writes(1)) From 683ea8b4989a8df858e1e178e7a0434189bed404 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 17:00:44 +0200 Subject: [PATCH 09/16] Upgrade zrml-styx --- zrml/styx/Cargo.toml | 2 +- zrml/styx/src/benchmarks.rs | 5 +---- zrml/styx/src/lib.rs | 1 - zrml/styx/src/mock.rs | 34 ++++++++++++++++------------------ zrml/styx/src/tests.rs | 4 ++-- 5 files changed, 20 insertions(+), 26 deletions(-) diff --git a/zrml/styx/Cargo.toml b/zrml/styx/Cargo.toml index 22c701802..75cb13431 100644 --- a/zrml/styx/Cargo.toml +++ b/zrml/styx/Cargo.toml @@ -9,7 +9,7 @@ zeitgeist-primitives = { workspace = true } [dev-dependencies] env_logger = { workspace = true } -pallet-balances = { workspace = true, features = ["default"] } +pallet-balances = { workspace = true, features = ["default", "insecure_zero_ed"] } pallet-timestamp = { workspace = true, features = ["default"] } sp-io = { workspace = true, features = ["default"] } zeitgeist-primitives = { workspace = true, features = ["mock", "default"] } diff --git a/zrml/styx/src/benchmarks.rs b/zrml/styx/src/benchmarks.rs index 86d1dd06a..da88151b8 100644 --- a/zrml/styx/src/benchmarks.rs +++ b/zrml/styx/src/benchmarks.rs @@ -28,10 +28,7 @@ use crate::Config; #[cfg(test)] use crate::Pallet as Styx; use frame_benchmarking::{benchmarks, whitelisted_caller}; -use frame_support::{ - dispatch::UnfilteredDispatchable, - traits::{Currency, EnsureOrigin}, -}; +use frame_support::traits::{Currency, EnsureOrigin, UnfilteredDispatchable}; use frame_system::RawOrigin; use sp_runtime::SaturatedConversion; use zeitgeist_primitives::constants::BASE; diff --git a/zrml/styx/src/lib.rs b/zrml/styx/src/lib.rs index ab86b6baf..710fc7791 100644 --- a/zrml/styx/src/lib.rs +++ b/zrml/styx/src/lib.rs @@ -49,7 +49,6 @@ pub mod pallet { } #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(_); /// Keep track of crossings. Accounts are only able to cross once. diff --git a/zrml/styx/src/mock.rs b/zrml/styx/src/mock.rs index 263c25712..6f2eff6f0 100644 --- a/zrml/styx/src/mock.rs +++ b/zrml/styx/src/mock.rs @@ -20,14 +20,14 @@ use crate::{self as zrml_styx}; use frame_support::{construct_runtime, ord_parameter_types, traits::Everything}; -use frame_system::EnsureSignedBy; +use frame_system::{mocking::MockBlock, EnsureSignedBy}; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use zeitgeist_primitives::{ - constants::mock::{BlockHashCount, MaxReserves, BASE}, - types::{AccountIdTest, Balance, BlockNumber, BlockTest, Hash, Index, UncheckedExtrinsicTest}, + constants::mock::{BlockHashCount, MaxLocks, MaxReserves, BASE}, + types::{AccountIdTest, Balance, Hash}, }; pub const ALICE: AccountIdTest = 0; @@ -40,15 +40,10 @@ ord_parameter_types! { } construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - Styx: zrml_styx::{Event, Pallet, Storage}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, + pub enum Runtime { + Balances: pallet_balances, + Styx: zrml_styx, + System: frame_system, } ); @@ -63,18 +58,17 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); @@ -90,9 +84,13 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = (); - type MaxLocks = (); + type MaxHolds = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); @@ -110,7 +108,7 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); diff --git a/zrml/styx/src/tests.rs b/zrml/styx/src/tests.rs index dfcc0bf1a..8a3e0281d 100644 --- a/zrml/styx/src/tests.rs +++ b/zrml/styx/src/tests.rs @@ -18,7 +18,7 @@ #![cfg(test)] use crate::{mock::*, Crossings, Error, Event}; -use frame_support::{assert_noop, assert_ok, error::BadOrigin}; +use frame_support::{assert_noop, assert_ok, error::BadOrigin, traits::fungible::Mutate}; #[test] fn cross_slashes_funds_and_stores_crossing() { @@ -68,7 +68,7 @@ fn set_burn_amount_should_fail_with_unathorized_caller() { fn account_should_not_cross_without_sufficient_funds() { ExtBuilder::default().build().execute_with(|| { frame_system::Pallet::::set_block_number(1); - assert_ok!(Balances::set_balance(RuntimeOrigin::root(), ALICE, 0, 0)); + assert_eq!(Balances::set_balance(&ALICE, 0), 0); assert_noop!( Styx::cross(RuntimeOrigin::signed(ALICE)), Error::::FundDoesNotHaveEnoughFreeBalance From 19f5d36a00f0c697cd9ec95ead79862daddab0b4 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 17:07:06 +0200 Subject: [PATCH 10/16] Upgrade zrml-orderbook --- zrml/orderbook/src/benchmarks.rs | 2 +- zrml/orderbook/src/lib.rs | 7 +++-- zrml/orderbook/src/mock.rs | 54 ++++++++++++++------------------ zrml/orderbook/src/tests.rs | 5 ++- zrml/orderbook/src/utils.rs | 3 +- 5 files changed, 34 insertions(+), 37 deletions(-) diff --git a/zrml/orderbook/src/benchmarks.rs b/zrml/orderbook/src/benchmarks.rs index 751f990aa..920a3f2e3 100644 --- a/zrml/orderbook/src/benchmarks.rs +++ b/zrml/orderbook/src/benchmarks.rs @@ -26,7 +26,7 @@ use super::*; use crate::{utils::market_mock, Pallet as Orderbook}; use frame_benchmarking::{account, benchmarks, whitelisted_caller}; -use frame_support::dispatch::UnfilteredDispatchable; +use frame_support::traits::UnfilteredDispatchable; use frame_system::RawOrigin; use orml_traits::MultiCurrency; use sp_runtime::SaturatedConversion; diff --git a/zrml/orderbook/src/lib.rs b/zrml/orderbook/src/lib.rs index e2cc1c892..29e3a3094 100644 --- a/zrml/orderbook/src/lib.rs +++ b/zrml/orderbook/src/lib.rs @@ -32,7 +32,10 @@ use frame_support::{ traits::{IsType, StorageVersion}, transactional, PalletId, Twox64Concat, }; -use frame_system::{ensure_signed, pallet_prelude::OriginFor}; +use frame_system::{ + ensure_signed, + pallet_prelude::{BlockNumberFor, OriginFor}, +}; use orml_traits::{ BalanceStatus, MultiCurrency, MultiReservableCurrency, NamedMultiReservableCurrency, }; @@ -84,7 +87,7 @@ mod pallet { type MarketCommons: MarketCommonsPalletApi< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, Balance = BalanceOf, >; diff --git a/zrml/orderbook/src/mock.rs b/zrml/orderbook/src/mock.rs index 83f33231c..70b670927 100644 --- a/zrml/orderbook/src/mock.rs +++ b/zrml/orderbook/src/mock.rs @@ -27,13 +27,12 @@ use frame_support::{ parameter_types, traits::{AsEnsureOriginWithArg, Everything}, }; -use frame_system::{EnsureRoot, EnsureSigned}; +use frame_system::{mocking::MockBlock, EnsureRoot, EnsureSigned}; use orml_traits::MultiCurrency; use parity_scale_codec::Compact; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, ConstU32, IdentityLookup, Zero}, - Perbill, SaturatedConversion, + BuildStorage, Perbill, SaturatedConversion, }; use zeitgeist_primitives::{ constants::mock::{ @@ -44,19 +43,16 @@ use zeitgeist_primitives::{ }, traits::DistributeFees, types::{ - AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, - CampaignAsset, CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, Index, - MarketAsset, MarketId, Moment, UncheckedExtrinsicTest, + AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, CampaignAsset, + CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, MarketAsset, MarketId, + Moment, }, }; pub const ALICE: AccountIdTest = 0; pub const BOB: AccountIdTest = 1; - pub const MARKET_CREATOR: AccountIdTest = 42; - pub const INITIAL_BALANCE: Balance = 100 * BASE; - pub const EXTERNAL_FEES: Balance = CENT; parameter_types! { @@ -105,23 +101,18 @@ where } construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - AssetManager: orml_currencies::{Call, Pallet, Storage}, - AssetRouter: zrml_asset_router::{Pallet}, - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketCommons: zrml_market_commons::{Pallet, Storage}, - Orderbook: orderbook::{Call, Event, Pallet}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, - Tokens: orml_tokens::{Config, Event, Pallet, Storage}, + pub enum Runtime { + AssetManager: orml_currencies, + AssetRouter: zrml_asset_router, + Balances: pallet_balances, + CampaignAssets: pallet_assets::, + CustomAssets: pallet_assets::, + MarketAssets: pallet_assets::, + MarketCommons: zrml_market_commons, + Orderbook: orderbook, + System: frame_system, + Timestamp: pallet_timestamp, + Tokens: orml_tokens, } ); @@ -138,18 +129,17 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); @@ -286,8 +276,12 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; + type MaxHolds = (); + type MaxFreezes = (); type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; @@ -334,7 +328,7 @@ impl Default for ExtBuilder { } impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); diff --git a/zrml/orderbook/src/tests.rs b/zrml/orderbook/src/tests.rs index f037b408f..5061b7c16 100644 --- a/zrml/orderbook/src/tests.rs +++ b/zrml/orderbook/src/tests.rs @@ -20,8 +20,7 @@ use crate::{mock::*, utils::market_mock, Error, Event, Order, Orders}; use frame_support::{assert_noop, assert_ok, traits::fungibles::Create}; use orml_tokens::Error as AError; use orml_traits::{MultiCurrency, MultiReservableCurrency}; -use pallet_balances::Error as BError; -use sp_runtime::{Perbill, Perquintill}; +use sp_runtime::{DispatchError, Perbill, Perquintill, TokenError}; use test_case::test_case; use zeitgeist_primitives::{ constants::BASE, @@ -495,7 +494,7 @@ fn place_order_fails_if_maker_has_insufficient_funds() { taker_asset, 25 * BASE, ), - BError::::InsufficientBalance, + DispatchError::Token(TokenError::FundsUnavailable) ); }); } diff --git a/zrml/orderbook/src/utils.rs b/zrml/orderbook/src/utils.rs index 6504fa01f..e378d7aac 100644 --- a/zrml/orderbook/src/utils.rs +++ b/zrml/orderbook/src/utils.rs @@ -18,6 +18,7 @@ #![cfg(any(feature = "runtime-benchmarks", test))] use crate::*; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::traits::AccountIdConversion; use zeitgeist_primitives::types::{ BaseAsset, Deadlines, Market, MarketCreation, MarketDisputeMechanism, MarketPeriod, @@ -29,7 +30,7 @@ type MomentOf = <::MarketCommons as MarketCommonsPalletApi>::Mom type MarketOf = Market< ::AccountId, BalanceOf, - ::BlockNumber, + BlockNumberFor, MomentOf, BaseAsset, MarketIdOf, From f7769bea6335a3d1af9ff0a75b60832241490f1c Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 17:25:21 +0200 Subject: [PATCH 11/16] Upgrade zrml-parimutuel --- zrml/parimutuel/Cargo.toml | 3 +- zrml/parimutuel/src/benchmarking.rs | 14 ++++---- zrml/parimutuel/src/lib.rs | 11 +++--- zrml/parimutuel/src/mock.rs | 55 ++++++++++++++--------------- 4 files changed, 41 insertions(+), 42 deletions(-) diff --git a/zrml/parimutuel/Cargo.toml b/zrml/parimutuel/Cargo.toml index 6c0721295..c41b92679 100644 --- a/zrml/parimutuel/Cargo.toml +++ b/zrml/parimutuel/Cargo.toml @@ -2,6 +2,7 @@ frame-benchmarking = { workspace = true, optional = true } frame-support = { workspace = true } frame-system = { workspace = true } +log = { workspace = true } orml-traits = { workspace = true } pallet-assets = { workspace = true } parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } @@ -15,7 +16,7 @@ zrml-market-commons = { workspace = true } env_logger = { workspace = true } orml-currencies = { workspace = true, features = ["default"] } orml-tokens = { workspace = true, features = ["default"] } -pallet-balances = { workspace = true, features = ["default"] } +pallet-balances = { workspace = true, features = ["default", "insecure_zero_ed"] } pallet-timestamp = { workspace = true, features = ["default"] } sp-io = { workspace = true, features = ["default"] } zeitgeist-primitives = { workspace = true, features = ["mock", "default"] } diff --git a/zrml/parimutuel/src/benchmarking.rs b/zrml/parimutuel/src/benchmarking.rs index b45816e8c..a33561ec3 100644 --- a/zrml/parimutuel/src/benchmarking.rs +++ b/zrml/parimutuel/src/benchmarking.rs @@ -29,7 +29,7 @@ use frame_support::{ }; use frame_system::RawOrigin; use orml_traits::MultiCurrency; -use sp_runtime::{SaturatedConversion, Saturating}; +use sp_runtime::{traits::Zero, SaturatedConversion, Saturating}; use zeitgeist_primitives::{ traits::MarketTransitionApi, types::{MarketStatus, MarketType, OutcomeReport}, @@ -95,11 +95,11 @@ mod benchmarks { T::MinBetSize::get().saturating_mul(10u128.saturated_into::>()); buy_asset::(market_id, loser_asset, &loser, loser_amount); - T::MarketCommons::mutate_market(&market_id, |market| { + assert_ok!(T::MarketCommons::mutate_market(&market_id, |market| { market.status = MarketStatus::Resolved; market.resolved_outcome = Some(OutcomeReport::Categorical(0u16)); Ok(()) - })?; + })); #[extrinsic_call] claim_rewards(RawOrigin::Signed(winner), market_id); @@ -125,7 +125,7 @@ mod benchmarks { T::MinBetSize::get().saturating_mul(10u128.saturated_into::>()); buy_asset::(market_id, loser_1_asset, &loser_1, loser_1_amount); - T::MarketCommons::mutate_market(&market_id, |market| { + assert_ok!(T::MarketCommons::mutate_market(&market_id, |market| { market.status = MarketStatus::Resolved; let resolved_index = 9u16; let resolved_outcome = OutcomeReport::Categorical(resolved_index); @@ -136,7 +136,7 @@ mod benchmarks { assert!(resolved_issuance_asset.is_zero()); market.resolved_outcome = Some(resolved_outcome); Ok(()) - })?; + })); #[extrinsic_call] claim_refunds(RawOrigin::Signed(loser_0), loser_0_asset); @@ -167,12 +167,12 @@ mod benchmarks { assert!(T::AssetCreator::asset_exists(asset)); } - T::MarketCommons::mutate_market(&market_id, |market| { + assert_ok!(T::MarketCommons::mutate_market(&market_id, |market| { market.status = MarketStatus::Resolved; let resolved_outcome = OutcomeReport::Categorical(0u16); market.resolved_outcome = Some(resolved_outcome); Ok(()) - })?; + })); #[block] { diff --git a/zrml/parimutuel/src/lib.rs b/zrml/parimutuel/src/lib.rs index c04b70900..c90d2af65 100644 --- a/zrml/parimutuel/src/lib.rs +++ b/zrml/parimutuel/src/lib.rs @@ -34,24 +34,25 @@ mod pallet { use alloc::collections::BTreeMap; use core::marker::PhantomData; use frame_support::{ - ensure, log, - pallet_prelude::{Decode, DispatchError, Encode, TypeInfo}, + ensure, + pallet_prelude::{Decode, Encode, TypeInfo}, require_transactional, traits::{ fungibles::{Create, Inspect}, Get, IsType, StorageVersion, }, - PalletId, RuntimeDebug, + PalletId, }; use frame_system::{ ensure_signed, pallet_prelude::{BlockNumberFor, OriginFor}, }; + use log; use orml_traits::MultiCurrency; use pallet_assets::ManagedDestroy; use sp_runtime::{ traits::{AccountIdConversion, CheckedSub, Zero}, - DispatchResult, + DispatchError, DispatchResult, RuntimeDebug, }; use zeitgeist_macros::unreachable_non_terminating; use zeitgeist_primitives::{ @@ -85,7 +86,7 @@ mod pallet { type MarketCommons: MarketCommonsPalletApi< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, Balance = BalanceOf, >; diff --git a/zrml/parimutuel/src/mock.rs b/zrml/parimutuel/src/mock.rs index 0d8fab509..44403f38b 100644 --- a/zrml/parimutuel/src/mock.rs +++ b/zrml/parimutuel/src/mock.rs @@ -29,26 +29,25 @@ use frame_support::{ parameter_types, traits::{AsEnsureOriginWithArg, Everything}, }; -use frame_system::{EnsureRoot, EnsureSigned}; +use frame_system::{mocking::MockBlock, EnsureRoot, EnsureSigned}; use orml_traits::MultiCurrency; use parity_scale_codec::Compact; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, - Perbill, SaturatedConversion, + BuildStorage, Perbill, SaturatedConversion, }; use zeitgeist_primitives::{ constants::mock::{ AssetsAccountDeposit, AssetsApprovalDeposit, AssetsDeposit, AssetsMetadataDepositBase, AssetsMetadataDepositPerByte, AssetsStringLimit, BlockHashCount, DestroyAccountWeight, DestroyApprovalWeight, DestroyFinishWeight, ExistentialDeposits, GetNativeCurrencyId, - MaxReserves, MinBetSize, MinimumPeriod, ParimutuelPalletId, BASE, CENT, + MaxLocks, MaxReserves, MinBetSize, MinimumPeriod, ParimutuelPalletId, BASE, CENT, }, traits::DistributeFees, types::{ - AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, - CampaignAsset, CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, Index, - MarketAsset, MarketId, Moment, UncheckedExtrinsicTest, + AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, CampaignAsset, + CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, MarketAsset, MarketId, + Moment, }, }; @@ -106,23 +105,18 @@ type CampaignAssetsInstance = pallet_assets::Instance2; type MarketAssetsInstance = pallet_assets::Instance3; construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - AssetManager: orml_currencies::{Call, Pallet, Storage}, - AssetRouter: zrml_asset_router::{Pallet}, - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketCommons: zrml_market_commons::{Pallet, Storage}, - Parimutuel: zrml_parimutuel::{Event, Pallet, Storage}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, - Tokens: orml_tokens::{Config, Event, Pallet, Storage}, + pub enum Runtime { + AssetManager: orml_currencies, + AssetRouter: zrml_asset_router, + Balances: pallet_balances, + CampaignAssets: pallet_assets::, + CustomAssets: pallet_assets::, + MarketAssets: pallet_assets::, + MarketCommons: zrml_market_commons, + Parimutuel: zrml_parimutuel, + System: frame_system, + Timestamp: pallet_timestamp, + Tokens: orml_tokens, } ); @@ -142,18 +136,17 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); @@ -269,9 +262,13 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = (); - type MaxLocks = (); + type MaxHolds = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); @@ -345,7 +342,7 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); From ccb48d6e7a4e745273da9609878da6f6d809d6a8 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 17:35:48 +0200 Subject: [PATCH 12/16] Upgrade zrml-swaps --- zrml/swaps/src/benchmarks.rs | 3 ++- zrml/swaps/src/fixed.rs | 5 +++-- zrml/swaps/src/lib.rs | 6 ++--- zrml/swaps/src/math.rs | 2 +- zrml/swaps/src/mock.rs | 43 ++++++++++++++++++------------------ 5 files changed, 31 insertions(+), 28 deletions(-) diff --git a/zrml/swaps/src/benchmarks.rs b/zrml/swaps/src/benchmarks.rs index c7442491a..69bc5fc22 100644 --- a/zrml/swaps/src/benchmarks.rs +++ b/zrml/swaps/src/benchmarks.rs @@ -30,7 +30,8 @@ use super::*; #[cfg(test)] use crate::Pallet as Swaps; use crate::{types::PoolStatus, AssetOf, Config, Event, MAX_IN_RATIO, MAX_OUT_RATIO}; -use frame_benchmarking::{benchmarks, vec, whitelisted_caller, Vec}; +use alloc::{vec, vec::Vec}; +use frame_benchmarking::{benchmarks, whitelisted_caller}; use frame_support::traits::Get; use frame_system::RawOrigin; use orml_traits::MultiCurrency; diff --git a/zrml/swaps/src/fixed.rs b/zrml/swaps/src/fixed.rs index aa1aec648..607155a87 100644 --- a/zrml/swaps/src/fixed.rs +++ b/zrml/swaps/src/fixed.rs @@ -22,7 +22,7 @@ // balancer-core repository // . -use frame_support::dispatch::DispatchError; +use sp_runtime::DispatchError; use zeitgeist_primitives::{ constants::BASE, math::{ @@ -175,8 +175,9 @@ pub fn bpow_approx(base: u128, exp: u128) -> Result { #[cfg(test)] mod tests { use super::*; - use frame_support::{assert_err, dispatch::DispatchError}; + use frame_support::assert_err; use more_asserts::assert_le; + use sp_runtime::DispatchError; #[test] fn bpow_has_minimum_set_of_correct_values() { diff --git a/zrml/swaps/src/lib.rs b/zrml/swaps/src/lib.rs index 17e2e0132..54f55e4b3 100644 --- a/zrml/swaps/src/lib.rs +++ b/zrml/swaps/src/lib.rs @@ -58,12 +58,13 @@ mod pallet { use alloc::{collections::btree_map::BTreeMap, vec, vec::Vec}; use core::marker::PhantomData; use frame_support::{ - dispatch::Weight, ensure, pallet_prelude::{OptionQuery, StorageMap, StorageValue, ValueQuery}, require_transactional, traits::{Get, IsType, StorageVersion}, - transactional, Blake2_128Concat, PalletError, PalletId, Parameter, + transactional, + weights::Weight, + Blake2_128Concat, PalletError, PalletId, Parameter, }; use frame_system::{ensure_signed, pallet_prelude::OriginFor}; use orml_traits::MultiCurrency; @@ -564,7 +565,6 @@ mod pallet { #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData); #[pallet::storage] diff --git a/zrml/swaps/src/math.rs b/zrml/swaps/src/math.rs index 64b4d9606..8abf6b4d4 100644 --- a/zrml/swaps/src/math.rs +++ b/zrml/swaps/src/math.rs @@ -25,7 +25,7 @@ #![allow(clippy::let_and_return)] use crate::fixed::bpow; -use frame_support::dispatch::DispatchError; +use sp_runtime::DispatchError; use zeitgeist_primitives::{ constants::BASE, math::{ diff --git a/zrml/swaps/src/mock.rs b/zrml/swaps/src/mock.rs index de0c3fa27..12450ed6e 100644 --- a/zrml/swaps/src/mock.rs +++ b/zrml/swaps/src/mock.rs @@ -33,10 +33,11 @@ use frame_support::{ construct_runtime, parameter_types, traits::{Contains, Everything}, }; +use frame_system::mocking::MockBlock; use orml_traits::parameter_type_with_key; use sp_runtime::{ - testing::Header, traits::{AccountIdConversion, BlakeTwo256, IdentityLookup}, + BuildStorage, }; use zeitgeist_primitives::{ constants::mock::{ @@ -45,8 +46,8 @@ use zeitgeist_primitives::{ BASE, }, types::{ - AccountIdTest, Amount, Asset, Assets, Balance, BasicCurrencyAdapter, BlockNumber, - BlockTest, Hash, Index, MarketId, Moment, PoolId, UncheckedExtrinsicTest, + AccountIdTest, Amount, Asset, Assets, Balance, BasicCurrencyAdapter, Hash, MarketId, + Moment, PoolId, UncheckedExtrinsicTest, }, }; @@ -77,18 +78,13 @@ parameter_types! { } construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsic, - { - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - Currencies: orml_currencies::{Pallet}, - Swaps: zrml_swaps::{Call, Event, Pallet}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, - Tokens: orml_tokens::{Config, Event, Pallet, Storage}, + pub enum Runtime { + Balances: pallet_balances, + Currencies: orml_currencies, + Swaps: zrml_swaps, + System: frame_system, + Timestamp: pallet_timestamp, + Tokens: orml_tokens, } ); @@ -113,27 +109,26 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); - type OnSetCode = (); type RuntimeOrigin = RuntimeOrigin; type PalletInfo = PalletInfo; type SS58Prefix = (); type SystemWeightInfo = (); type Version = (); + type OnSetCode = (); } impl orml_currencies::Config for Runtime { @@ -196,8 +191,12 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; + type MaxHolds = (); + type MaxFreezes = (); type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; @@ -232,7 +231,7 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { let mut storage = - frame_system::GenesisConfig::default().build_storage::().unwrap(); + frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); @@ -245,8 +244,10 @@ impl ExtBuilder { } } +type Block = MockBlock; + sp_api::mock_impl_runtime_apis! { - impl zrml_swaps_runtime_api::SwapsApi, PoolId, AccountIdTest, Balance, MarketId> + impl zrml_swaps_runtime_api::SwapsApi, PoolId, AccountIdTest, Balance, MarketId> for Runtime { fn get_spot_price( From e9085273252ce92e61f31a48143a7a0248160f4f Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 18:56:08 +0200 Subject: [PATCH 13/16] Upgrade zrml-prediction-markets --- Cargo.lock | 3 + zrml/prediction-markets/Cargo.toml | 3 + zrml/prediction-markets/src/benchmarks.rs | 34 ++- zrml/prediction-markets/src/lib.rs | 68 ++--- zrml/prediction-markets/src/mock.rs | 209 +++++++------- .../src/orml_asset_registry.rs | 257 ------------------ zrml/prediction-markets/src/tests/mod.rs | 3 +- 7 files changed, 176 insertions(+), 401 deletions(-) delete mode 100644 zrml/prediction-markets/src/orml_asset_registry.rs diff --git a/Cargo.lock b/Cargo.lock index 46e497431..1f9dd0b00 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15257,6 +15257,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "log", "orml-currencies", "orml-tokens", "orml-traits", @@ -15278,10 +15279,12 @@ dependencies = [ name = "zrml-prediction-markets" version = "0.5.2" dependencies = [ + "cfg-if", "env_logger 0.10.2", "frame-benchmarking", "frame-support", "frame-system", + "log", "more-asserts", "orml-asset-registry", "orml-currencies", diff --git a/zrml/prediction-markets/Cargo.toml b/zrml/prediction-markets/Cargo.toml index 448761cb2..61e4bef75 100644 --- a/zrml/prediction-markets/Cargo.toml +++ b/zrml/prediction-markets/Cargo.toml @@ -2,6 +2,7 @@ frame-benchmarking = { workspace = true, optional = true } frame-support = { workspace = true } frame-system = { workspace = true } +log = { workspace = true } orml-traits = { workspace = true } pallet-assets = { workspace = true } parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } @@ -19,6 +20,7 @@ zrml-simple-disputes = { workspace = true } # Mock +cfg-if = { workspace = true, optional = true } env_logger = { workspace = true, optional = true } orml-asset-registry = { workspace = true, optional = true } orml-currencies = { workspace = true, optional = true } @@ -41,6 +43,7 @@ zrml-prediction-markets = { workspace = true, features = ["mock", "default"] } [features] default = ["std"] mock = [ + "cfg-if", "env_logger/default", "orml-asset-registry/default", "orml-currencies/default", diff --git a/zrml/prediction-markets/src/benchmarks.rs b/zrml/prediction-markets/src/benchmarks.rs index 01903a795..7fccef713 100644 --- a/zrml/prediction-markets/src/benchmarks.rs +++ b/zrml/prediction-markets/src/benchmarks.rs @@ -26,13 +26,13 @@ use super::*; #[cfg(test)] use crate::Pallet as PredictionMarket; -use alloc::vec::Vec; -use frame_benchmarking::{account, benchmarks, vec, whitelisted_caller}; +use alloc::{vec, vec::Vec}; +use frame_benchmarking::{account, benchmarks, whitelisted_caller}; use frame_support::{ - dispatch::UnfilteredDispatchable, - traits::{EnsureOrigin, Get}, + traits::{EnsureOrigin, Get, Hooks, UnfilteredDispatchable}, + BoundedVec, }; -use frame_system::RawOrigin; +use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use orml_traits::MultiCurrency; use sp_runtime::{ traits::{SaturatedConversion, Saturating, Zero}, @@ -54,8 +54,6 @@ use zrml_authorized::Pallet as AuthorizedPallet; use zrml_global_disputes::GlobalDisputesPalletApi; use zrml_market_commons::MarketCommonsPalletApi; -use frame_support::{traits::Hooks, BoundedVec}; - fn assert_last_event(generic_event: ::RuntimeEvent) { frame_system::Pallet::::assert_last_event(generic_event.into()); } @@ -66,11 +64,11 @@ const LIQUIDITY: u128 = 100 * BASE; // amount of native currency fn create_market_common_parameters( is_disputable: bool, -) -> Result<(T::AccountId, T::AccountId, Deadlines, MultiHash), &'static str> { +) -> Result<(T::AccountId, T::AccountId, Deadlines>, MultiHash), &'static str> { let caller: T::AccountId = whitelisted_caller(); T::AssetManager::deposit(Asset::Ztg, &caller, (100u128 * LIQUIDITY).saturated_into()).unwrap(); let oracle = caller.clone(); - let deadlines = Deadlines:: { + let deadlines = Deadlines::> { grace_period: 1_u32.into(), oracle_duration: T::MinOracleDuration::get(), dispute_duration: if is_disputable { T::MinDisputeDuration::get() } else { Zero::zero() }, @@ -86,7 +84,7 @@ fn create_market_common( creation: MarketCreation, options: MarketType, scoring_rule: ScoringRule, - period: Option>>, + period: Option, MomentOf>>, dispute_mechanism: Option, ) -> Result<(T::AccountId, MarketIdOf), &'static str> { pallet_timestamp::Pallet::::set_timestamp(0u32.into()); @@ -540,7 +538,7 @@ benchmarks! { |ids| ids.try_push(i.into()), ).unwrap(); } - let new_deadlines = Deadlines:: { + let new_deadlines = Deadlines::> { grace_period: 2_u32.into(), oracle_duration: T::MinOracleDuration::get(), dispute_duration: T::MinDisputeDuration::get(), @@ -620,7 +618,7 @@ benchmarks! { } MarketIdsPerDisputeBlock::::insert(appeal_end, market_ids_2); - frame_system::Pallet::::set_block_number(appeal_end - 1u64.saturated_into::()); + frame_system::Pallet::::set_block_number(appeal_end - 1u64.saturated_into::>()); let now = frame_system::Pallet::::block_number(); @@ -760,7 +758,7 @@ benchmarks! { on_initialize_resolve_overhead { // wait for timestamp to get initialized (that's why block 2) - let now = 2u64.saturated_into::(); + let now = 2u64.saturated_into::>(); }: { Pallet::::on_initialize(now) } redeem_shares_categorical { @@ -860,7 +858,7 @@ benchmarks! { creator_fee: Perbill::zero(), oracle: caller.clone(), period: MarketPeriod::Timestamp(start..end), - deadlines: Deadlines:: { + deadlines: Deadlines::> { grace_period: 0u8.into(), oracle_duration: T::MinOracleDuration::get(), dispute_duration: 0u8.into(), @@ -906,8 +904,8 @@ benchmarks! { let f in 1..31; // ensure markets exist - let start_block: T::BlockNumber = 100_000u64.saturated_into(); - let end_block: T::BlockNumber = 1_000_000u64.saturated_into(); + let start_block: BlockNumberFor = 100_000u64.saturated_into(); + let end_block: BlockNumberFor = 1_000_000u64.saturated_into(); for _ in 0..31 { create_market_common::( MarketCreation::Permissionless, @@ -930,7 +928,7 @@ benchmarks! { ).unwrap(); } - let block_number: T::BlockNumber = Zero::zero(); + let block_number: BlockNumberFor = Zero::zero(); for i in 1..=b { MarketIdsPerCloseBlock::::try_mutate(block_number, |ids| { ids.try_push(i.into()) @@ -986,7 +984,7 @@ benchmarks! { })?; } - let block_number: T::BlockNumber = Zero::zero(); + let block_number: BlockNumberFor = Zero::zero(); let mut r_ids_vec = Vec::new(); for i in 1..=r { diff --git a/zrml/prediction-markets/src/lib.rs b/zrml/prediction-markets/src/lib.rs index abefb9275..b4233568b 100644 --- a/zrml/prediction-markets/src/lib.rs +++ b/zrml/prediction-markets/src/lib.rs @@ -26,7 +26,6 @@ extern crate alloc; mod benchmarks; pub mod migrations; pub mod mock; -pub mod orml_asset_registry; mod tests; pub mod weights; @@ -38,8 +37,8 @@ mod pallet { use alloc::{collections::BTreeMap, format, vec, vec::Vec}; use core::{cmp, marker::PhantomData}; use frame_support::{ - dispatch::{DispatchResultWithPostInfo, Pays, Weight}, - ensure, log, + dispatch::{DispatchResultWithPostInfo, Pays}, + ensure, pallet_prelude::{ConstU32, StorageMap, StorageValue, ValueQuery}, require_transactional, storage::{with_transaction, TransactionOutcome}, @@ -49,7 +48,9 @@ mod pallet { Currency, EnsureOrigin, Get, Hooks, Imbalance, IsType, NamedReservableCurrency, OnUnbalanced, StorageVersion, }, - transactional, Blake2_128Concat, BoundedVec, PalletId, Twox64Concat, + transactional, + weights::Weight, + Blake2_128Concat, BoundedVec, PalletId, Twox64Concat, }; use frame_system::{ensure_signed, pallet_prelude::OriginFor}; use pallet_assets::ManagedDestroy; @@ -61,6 +62,8 @@ mod pallet { zeitgeist_primitives::types::{CustomMetadata, XcmAsset}, }; + use frame_system::pallet_prelude::BlockNumberFor; + use log; use orml_traits::{MultiCurrency, NamedMultiReservableCurrency}; use sp_arithmetic::per_things::{Perbill, Percent}; use sp_runtime::{ @@ -95,9 +98,8 @@ mod pallet { pub(crate) type AccountIdOf = ::AccountId; pub(crate) type AssetOf = Asset>; pub(crate) type BalanceOf = ::Balance; - pub(crate) type BlockNumberOf = ::BlockNumber; pub(crate) type CacheSize = ConstU32<64>; - pub(crate) type DeadlinesOf = Deadlines>; + pub(crate) type DeadlinesOf = Deadlines>; pub(crate) type EditReason = BoundedVec::MaxEditReasonLen>; pub(crate) type InitialItemOf = InitialItem, BalanceOf>; pub(crate) type MarketBondsOf = MarketBonds, BalanceOf>; @@ -105,18 +107,18 @@ mod pallet { pub(crate) type MarketOf = Market< AccountIdOf, BalanceOf, - BlockNumberOf, + BlockNumberFor, MomentOf, BaseAsset, MarketIdOf, >; - pub(crate) type MarketPeriodOf = MarketPeriod, MomentOf>; + pub(crate) type MarketPeriodOf = MarketPeriod, MomentOf>; pub(crate) type MomentOf = <::Timestamp as frame_support::traits::Time>::Moment; pub(crate) type NegativeImbalanceOf = <::Currency as Currency>>::NegativeImbalance; pub(crate) type RejectReason = BoundedVec::MaxRejectReasonLen>; - pub(crate) type ReportOf = Report, BlockNumberOf>; + pub(crate) type ReportOf = Report, BlockNumberFor>; pub(crate) type TimeFrame = u64; macro_rules! impl_unreserve_bond { @@ -1574,7 +1576,7 @@ mod pallet { AccountId = Self::AccountId, Balance = BalanceOf, NegativeImbalance = NegativeImbalanceOf, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, MarketId = MarketIdOf, Moment = MomentOf, Origin = Self::RuntimeOrigin, @@ -1605,7 +1607,7 @@ mod pallet { /// The block time to wait for the `CloseMarketsEarlyOrigin` /// before the early market close actually happens (fat-finger protection). #[pallet::constant] - type CloseEarlyProtectionBlockPeriod: Get; + type CloseEarlyProtectionBlockPeriod: Get>; /// The base amount of currency that must be bonded /// by the market creator in order to schedule an early market closure. @@ -1617,7 +1619,7 @@ mod pallet { AccountId = Self::AccountId, Balance = BalanceOf, NegativeImbalance = NegativeImbalanceOf, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, MarketId = MarketIdOf, Moment = MomentOf, Origin = Self::RuntimeOrigin, @@ -1642,13 +1644,13 @@ mod pallet { MarketIdOf, Self::AccountId, BalanceOf, - Self::BlockNumber, + BlockNumberFor, >; type LiquidityMining: LiquidityMiningPalletApi< AccountId = Self::AccountId, Balance = BalanceOf, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, MarketId = MarketIdOf, >; @@ -1671,27 +1673,27 @@ mod pallet { /// The minimum number of blocks allowed to be specified as dispute_duration /// in create_market. #[pallet::constant] - type MinDisputeDuration: Get; + type MinDisputeDuration: Get>; /// The minimum number of blocks allowed to be specified as oracle_duration /// in create_market. #[pallet::constant] - type MinOracleDuration: Get; + type MinOracleDuration: Get>; /// The maximum number of blocks allowed to be specified as grace_period /// in create_market. #[pallet::constant] - type MaxGracePeriod: Get; + type MaxGracePeriod: Get>; /// The maximum number of blocks allowed to be specified as oracle_duration /// in create_market. #[pallet::constant] - type MaxOracleDuration: Get; + type MaxOracleDuration: Get>; /// The maximum number of blocks allowed to be specified as dispute_duration /// in create_market. #[pallet::constant] - type MaxDisputeDuration: Get; + type MaxDisputeDuration: Get>; /// The maximum length of reject reason string. #[pallet::constant] @@ -1699,7 +1701,7 @@ mod pallet { /// The maximum allowed duration of a market from creation to market close in blocks. #[pallet::constant] - type MaxMarketLifetime: Get; + type MaxMarketLifetime: Get>; /// The maximum number of bytes allowed as edit reason. #[pallet::constant] @@ -1715,7 +1717,7 @@ mod pallet { /// The block time to wait for the market creator /// before the early market close actually happens. #[pallet::constant] - type CloseEarlyBlockPeriod: Get; + type CloseEarlyBlockPeriod: Get>; /// The milliseconds to wait for the market creator /// before the early market close actually happens. @@ -1744,7 +1746,7 @@ mod pallet { AccountId = Self::AccountId, Balance = BalanceOf, NegativeImbalance = NegativeImbalanceOf, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, MarketId = MarketIdOf, Moment = MomentOf, Origin = Self::RuntimeOrigin, @@ -1911,7 +1913,7 @@ mod pallet { /// A market has been scheduled to close early. MarketEarlyCloseScheduled { market_id: MarketIdOf, - new_period: MarketPeriod>, + new_period: MarketPeriod, MomentOf>, state: EarlyCloseState, }, /// A market early close request has been disputed. @@ -1945,8 +1947,8 @@ mod pallet { } #[pallet::hooks] - impl Hooks for Pallet { - fn on_initialize(now: T::BlockNumber) -> Weight { + impl Hooks> for Pallet { + fn on_initialize(now: BlockNumberFor) -> Weight { let mut total_weight: Weight = Weight::zero(); // If we are at genesis or the first block the timestamp is be undefined. No @@ -2043,7 +2045,7 @@ mod pallet { pub type MarketIdsPerCloseBlock = StorageMap< _, Blake2_128Concat, - T::BlockNumber, + BlockNumberFor, BoundedVec, CacheSize>, ValueQuery, >; @@ -2068,7 +2070,7 @@ mod pallet { pub type MarketIdsPerDisputeBlock = StorageMap< _, Twox64Concat, - T::BlockNumber, + BlockNumberFor, BoundedVec, CacheSize>, ValueQuery, >; @@ -2078,7 +2080,7 @@ mod pallet { pub type MarketIdsPerReportBlock = StorageMap< _, Twox64Concat, - T::BlockNumber, + BlockNumberFor, BoundedVec, CacheSize>, ValueQuery, >; @@ -2846,7 +2848,7 @@ mod pallet { } pub(crate) fn market_status_manager( - block_number: T::BlockNumber, + block_number: BlockNumberFor, last_time_frame: TimeFrame, current_time_frame: TimeFrame, mut mutation: F, @@ -2854,7 +2856,7 @@ mod pallet { where F: FnMut(&MarketIdOf, MarketOf) -> DispatchResult, MarketIdsPerBlock: frame_support::StorageMap< - T::BlockNumber, + BlockNumberFor, BoundedVec, CacheSize>, Query = BoundedVec, CacheSize>, >, @@ -2908,7 +2910,7 @@ mod pallet { } pub(crate) fn resolution_manager( - now: T::BlockNumber, + now: BlockNumberFor, mut cb: F, ) -> Result where @@ -3116,7 +3118,7 @@ mod pallet { fn remove_auto_resolve( market_id: &MarketIdOf, - resolve_at: T::BlockNumber, + resolve_at: BlockNumberFor, ) -> u32 { MarketIdsPerDisputeBlock::::mutate(resolve_at, |ids| -> u32 { let ids_len = ids.len() as u32; @@ -3131,7 +3133,7 @@ mod pallet { { type AccountId = T::AccountId; type Balance = BalanceOf; - type BlockNumber = T::BlockNumber; + type BlockNumber = BlockNumberFor; type MarketId = MarketIdOf; type Moment = MomentOf; diff --git a/zrml/prediction-markets/src/mock.rs b/zrml/prediction-markets/src/mock.rs index 392a7d2df..4847294b1 100644 --- a/zrml/prediction-markets/src/mock.rs +++ b/zrml/prediction-markets/src/mock.rs @@ -29,17 +29,15 @@ use frame_support::{ parameter_types, storage::unhashed::put, traits::{ - AsEnsureOriginWithArg, Everything, GenesisBuild, NeverEnsureOrigin, OnFinalize, OnIdle, - OnInitialize, + AsEnsureOriginWithArg, Everything, NeverEnsureOrigin, OnFinalize, OnIdle, OnInitialize, }, }; -use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy}; +use frame_system::{mocking::MockBlock, EnsureRoot, EnsureSigned, EnsureSignedBy}; use parity_scale_codec::Compact; use sp_arithmetic::per_things::Percent; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, ConstU32, IdentityLookup}, - DispatchError, DispatchResult, + BuildStorage, DispatchError, DispatchResult, }; use std::cell::RefCell; use zeitgeist_primitives::{ @@ -55,7 +53,7 @@ use zeitgeist_primitives::{ GlobalDisputesPalletId, InflationPeriod, LiquidityMiningPalletId, LockId, MaxAppeals, MaxApprovals, MaxCategories, MaxCourtParticipants, MaxCreatorFee, MaxDelegations, MaxDisputeDuration, MaxDisputes, MaxEditReasonLen, MaxGlobalDisputeVotes, MaxGracePeriod, - MaxMarketLifetime, MaxOracleDuration, MaxOwners, MaxRejectReasonLen, MaxReserves, + MaxLocks, MaxMarketLifetime, MaxOracleDuration, MaxOwners, MaxRejectReasonLen, MaxReserves, MaxSelectedDraws, MaxYearlyInflation, MinCategories, MinDisputeDuration, MinJurorStake, MinOracleDuration, MinOutcomeVoteAmount, MinimumPeriod, OutcomeBond, OutcomeFactor, OutsiderBond, PmPalletId, RemoveKeysLimit, RequestInterval, SimpleDisputesPalletId, @@ -65,12 +63,15 @@ use zeitgeist_primitives::{ types::{ AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, CampaignAsset, CampaignAssetClass, CampaignAssetId, Currencies, CustomAsset, CustomAssetId, - Hash, Index, MarketAsset, MarketId, Moment, ResultWithWeightInfo, UncheckedExtrinsicTest, + Hash, MarketAsset, MarketId, Moment, ResultWithWeightInfo, }, }; #[cfg(feature = "parachain")] -use {orml_asset_registry::AssetMetadata, zeitgeist_primitives::types::XcmAsset}; +use { + orml_traits::asset_registry::AssetProcessor, parity_scale_codec::Encode, + zeitgeist_primitives::types::CustomMetadata, zeitgeist_primitives::types::XcmAsset, +}; pub(super) const ON_PROPOSAL_STORAGE: [u8; 4] = [0x09, 0x09, 0x00, 0x00]; pub(super) const ON_ACTIVATION_STORAGE: [u8; 4] = [0x09, 0x09, 0x00, 0x01]; @@ -217,30 +218,26 @@ type CampaignAssetsInstance = pallet_assets::Instance2; type MarketAssetsInstance = pallet_assets::Instance3; construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsicTest, - { - AssetRouter: zrml_asset_router::{Pallet}, - Authorized: zrml_authorized::{Event, Pallet, Storage}, - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - Court: zrml_court::{Event, Pallet, Storage}, - AssetManager: orml_currencies::{Call, Pallet, Storage}, - LiquidityMining: zrml_liquidity_mining::{Config, Event, Pallet}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketCommons: zrml_market_commons::{Pallet, Storage}, - PredictionMarkets: prediction_markets::{Event, Pallet, Storage}, - RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage}, - SimpleDisputes: zrml_simple_disputes::{Event, Pallet, Storage}, - GlobalDisputes: zrml_global_disputes::{Event, Pallet, Storage}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, - Tokens: orml_tokens::{Config, Event, Pallet, Storage}, - Treasury: pallet_treasury::{Call, Event, Pallet, Storage}, + pub enum Runtime { + AssetRegistry: orml_asset_registry, + AssetRouter: zrml_asset_router, + Authorized: zrml_authorized, + Balances: pallet_balances, + CampaignAssets: pallet_assets::, + CustomAssets: pallet_assets::, + Court: zrml_court, + AssetManager: orml_currencies, + LiquidityMining: zrml_liquidity_mining, + MarketAssets: pallet_assets::, + MarketCommons: zrml_market_commons, + PredictionMarkets: prediction_markets, + RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, + SimpleDisputes: zrml_simple_disputes, + GlobalDisputes: zrml_global_disputes, + System: frame_system, + Timestamp: pallet_timestamp, + Tokens: orml_tokens, + Treasury: pallet_treasury, } ); @@ -252,7 +249,7 @@ impl crate::Config for Runtime { type AssetDestroyer = AssetRouter; type AssetManager = AssetManager; #[cfg(feature = "parachain")] - type AssetRegistry = MockRegistry; + type AssetRegistry = AssetRegistry; type Authorized = Authorized; type CloseEarlyDisputeBond = CloseEarlyDisputeBond; type CloseMarketEarlyOrigin = EnsureSignedBy; @@ -298,27 +295,26 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); - type OnSetCode = (); type RuntimeOrigin = RuntimeOrigin; type PalletInfo = PalletInfo; type SS58Prefix = (); type SystemWeightInfo = (); type Version = (); + type OnSetCode = (); } impl orml_currencies::Config for Runtime { @@ -328,6 +324,35 @@ impl orml_currencies::Config for Runtime { type WeightInfo = (); } +cfg_if::cfg_if!( + if #[cfg(feature = "parachain")] { + type AssetMetadata = orml_traits::asset_registry::AssetMetadata< + Balance, + CustomMetadata, + ConstU32<1024> + >; + pub struct NoopAssetProcessor {} + + impl AssetProcessor for NoopAssetProcessor { + fn pre_register(id: Option, asset_metadata: AssetMetadata) + -> Result<(XcmAsset, AssetMetadata), DispatchError> { + Ok((id.unwrap(), asset_metadata)) + } + } + + impl orml_asset_registry::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type CustomMetadata = CustomMetadata; + type AssetId = XcmAsset; + type AuthorityOrigin = EnsureRoot; + type AssetProcessor = NoopAssetProcessor; + type Balance = Balance; + type StringLimit = ConstU32<1024>; + type WeightInfo = (); + } + } +); + impl orml_tokens::Config for Runtime { type Amount = Amount; type Balance = Balance; @@ -342,27 +367,23 @@ impl orml_tokens::Config for Runtime { type WeightInfo = (); } -#[cfg(feature = "parachain")] -crate::orml_asset_registry::impl_mock_registry! { - MockRegistry, - XcmAsset, - Balance, - zeitgeist_primitives::types::CustomMetadata -} - impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; - type MaxLocks = (); + type MaxHolds = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type WeightInfo = (); } -impl pallet_randomness_collective_flip::Config for Runtime {} +impl pallet_insecure_randomness_collective_flip::Config for Runtime {} impl pallet_timestamp::Config for Runtime { type MinimumPeriod = MinimumPeriod; @@ -616,7 +637,7 @@ impl Default for ExtBuilder { impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); @@ -637,50 +658,52 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); - #[cfg(feature = "parachain")] - orml_tokens::GenesisConfig:: { - balances: (0..69) - .map(|idx| (idx, Currencies::ForeignAsset(100), INITIAL_BALANCE)) - .collect(), - } - .assimilate_storage(&mut t) - .unwrap(); - - #[cfg(feature = "parachain")] - let custom_metadata = zeitgeist_primitives::types::CustomMetadata { - allow_as_base_asset: true, - ..Default::default() - }; - - #[cfg(feature = "parachain")] - orml_asset_registry_mock::GenesisConfig { - metadata: vec![ - ( - XcmAsset::ForeignAsset(100), - AssetMetadata { - decimals: 18, - name: "ACALA USD".as_bytes().to_vec(), - symbol: "AUSD".as_bytes().to_vec(), - existential_deposit: 0, - location: None, - additional: custom_metadata, - }, - ), - ( - XcmAsset::ForeignAsset(420), - AssetMetadata { - decimals: 18, - name: "FANCY_TOKEN".as_bytes().to_vec(), - symbol: "FTK".as_bytes().to_vec(), - existential_deposit: 0, - location: None, - additional: zeitgeist_primitives::types::CustomMetadata::default(), - }, - ), - ], - } - .assimilate_storage(&mut t) - .unwrap(); + cfg_if::cfg_if!( + if #[cfg(feature = "parachain")] { + orml_tokens::GenesisConfig:: { + balances: (0..69) + .map(|idx| (idx, Currencies::ForeignAsset(100), INITIAL_BALANCE)) + .collect(), + } + .assimilate_storage(&mut t) + .unwrap(); + + let custom_metadata = zeitgeist_primitives::types::CustomMetadata { + allow_as_base_asset: true, + ..Default::default() + }; + + orml_asset_registry::GenesisConfig:: { + assets: vec![ + ( + XcmAsset::ForeignAsset(100), + AssetMetadata { + decimals: 18, + name: "ACALA USD".as_bytes().to_vec().try_into().unwrap(), + symbol: "AUSD".as_bytes().to_vec().try_into().unwrap(), + existential_deposit: 0, + location: None, + additional: custom_metadata, + }.encode(), + ), + ( + XcmAsset::ForeignAsset(420), + AssetMetadata { + decimals: 18, + name: "FANCY_TOKEN".as_bytes().to_vec().try_into().unwrap(), + symbol: "FTK".as_bytes().to_vec().try_into().unwrap(), + existential_deposit: 0, + location: None, + additional: zeitgeist_primitives::types::CustomMetadata::default(), + }.encode(), + ), + ], + last_asset_id: XcmAsset::ForeignAsset(420) + } + .assimilate_storage(&mut t) + .unwrap(); + } + ); let mut test_ext: sp_io::TestExternalities = t.into(); test_ext.execute_with(|| System::set_block_number(1)); @@ -714,6 +737,8 @@ pub fn set_timestamp_for_on_initialize(time: Moment) { Timestamp::set_timestamp(time - MILLISECS_PER_BLOCK as u64); } +type Block = MockBlock; + sp_api::mock_impl_runtime_apis! { impl zrml_prediction_markets_runtime_api::PredictionMarketsApi, MarketId, Hash> for Runtime { fn market_outcome_share_id(_: MarketId, _: u16) -> Assets { diff --git a/zrml/prediction-markets/src/orml_asset_registry.rs b/zrml/prediction-markets/src/orml_asset_registry.rs deleted file mode 100644 index ebabafa10..000000000 --- a/zrml/prediction-markets/src/orml_asset_registry.rs +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright 2023 Forecasting Technologies Ltd. -// Copyright 2021 Centrifuge Foundation (centrifuge.io). -// -// 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 = "mock", feature = "parachain"))] - -#[macro_export] -macro_rules! impl_mock_registry { - ($name:ident, $asset_id:ty, $balance:ty, $custom_metadata:ty) => { - pub use orml_asset_registry_mock::$name; - - mod orml_asset_registry_mock { - use frame_support::{ - dispatch::{DispatchError, DispatchResult}, - traits::GenesisBuild, - }; - use orml_traits::asset_registry::{AssetMetadata, Inspect, Mutate}; - use xcm::{latest::prelude::MultiLocation, VersionedMultiLocation}; - - use super::*; - - pub struct $name; - - impl Inspect for $name { - type AssetId = $asset_id; - type Balance = $balance; - type CustomMetadata = $custom_metadata; - - fn asset_id(location: &MultiLocation) -> Option { - __private::STATE.with(|s| s.borrow().get_asset_from_location(location)) - } - - fn metadata( - asset_id: &Self::AssetId, - ) -> Option> { - __private::STATE.with(|s| s.borrow().get_meta(asset_id)) - } - - fn metadata_by_location( - location: &MultiLocation, - ) -> Option> { - __private::STATE.with(|s| s.borrow().get_meta_from_location(location)) - } - - fn location( - asset_id: &Self::AssetId, - ) -> Result, DispatchError> { - let maybe_location = - __private::STATE.with(|s| s.borrow().get_location(asset_id)); - - Ok(maybe_location) - } - } - - impl Mutate for $name { - fn register_asset( - asset_id: Option, - metadata: AssetMetadata, - ) -> DispatchResult { - if let Some(asset_id) = asset_id { - __private::STATE.with(|s| s.borrow_mut().insert_meta(&asset_id, metadata)) - } else { - Err(DispatchError::Other("Mock can only register metadata with asset_id")) - } - } - - fn update_asset( - asset_id: Self::AssetId, - decimals: Option, - name: Option>, - symbol: Option>, - existential_deposit: Option, - location: Option>, - additional: Option, - ) -> DispatchResult { - __private::STATE.with(|s| { - s.borrow_mut().update_asset( - asset_id, - decimals, - name, - symbol, - existential_deposit, - location, - additional, - ) - }) - } - } - - #[derive(Default)] - pub struct GenesisConfig { - pub metadata: Vec<($asset_id, AssetMetadata<$balance, $custom_metadata>)>, - } - - use serde::{ - de::{Deserialize, Deserializer}, - ser::{Serialize, SerializeStruct, Serializer}, - }; - - impl GenesisBuild<()> for GenesisConfig { - fn build(&self) { - for (asset, metadata) in &self.metadata { - __private::STATE - .with(|s| s.borrow_mut().insert_meta(asset, metadata.clone())) - .expect("Genesis must not fail") - } - } - } - - // NOTE: We need this dummy impl as `AssetMetadata` does NOT derive - // serialize in std - impl Serialize for GenesisConfig { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let state = serializer.serialize_struct("GenesisConfig", 1)?; - state.end() - } - } - - // NOTE: We need this dummy impl as `AssetMetadata` does NOT derive - // deserialize in std - impl<'de> Deserialize<'de> for GenesisConfig { - fn deserialize(_deserializer: D) -> Result - where - D: Deserializer<'de>, - { - Ok(GenesisConfig::default()) - } - } - - mod __private { - use std::{cell::RefCell, vec::Vec}; - - use super::*; - - // TODO(#936): This will not be required post polkadot v0.9.29 upgrade. - pub struct RegistryState { - pub location_to_asset: Vec<(MultiLocation, $asset_id)>, - pub metadata: Vec<($asset_id, AssetMetadata<$balance, $custom_metadata>)>, - } - - impl RegistryState { - pub fn get_meta( - &self, - asset_id: &$asset_id, - ) -> Option> { - for (curr_id, meta) in &self.metadata { - if curr_id == asset_id { - return Some(meta.clone()); - } - } - - None - } - - pub fn insert_meta( - &mut self, - asset_id: &$asset_id, - meta: AssetMetadata<$balance, $custom_metadata>, - ) -> DispatchResult { - for (curr_id, curr_meta) in &mut self.metadata { - if curr_id == asset_id { - *curr_meta = meta; - return Ok(()); - } - } - - self.metadata.push((asset_id.clone(), meta)); - Ok(()) - } - - pub fn get_location(&self, asset_id: &$asset_id) -> Option { - for (curr_id, meta) in &self.metadata { - if curr_id == asset_id { - return meta - .location - .as_ref() - .map(|versioned| versioned.clone().try_into().ok()) - .flatten(); - } - } - - None - } - - pub fn get_asset_from_location( - &self, - location: &MultiLocation, - ) -> Option<$asset_id> { - for (curr_location, asset_id) in &self.location_to_asset { - if curr_location == location { - return Some(asset_id.clone()); - } - } - - None - } - - pub fn get_meta_from_location( - &self, - location: &MultiLocation, - ) -> Option> { - let asset_id = self.get_asset_from_location(location)?; - self.get_meta(&asset_id) - } - - pub fn update_asset( - &mut self, - asset_id: $asset_id, - _decimals: Option, - _name: Option>, - _symbol: Option>, - _existential_deposit: Option<$balance>, - _location: Option>, - _additional: Option<$custom_metadata>, - ) -> DispatchResult { - if let Some(_meta) = self.get_meta(&asset_id) { - Ok(()) - } else { - Err(DispatchError::Other("Asset not registered")) - } - } - } - - impl RegistryState { - fn new() -> Self { - Self { location_to_asset: Vec::new(), metadata: Vec::new() } - } - } - - thread_local! { - pub static STATE: RefCell< - RegistryState, - > = RefCell::new(RegistryState::new()); - } - } - } - }; -} - -pub use impl_mock_registry; diff --git a/zrml/prediction-markets/src/tests/mod.rs b/zrml/prediction-markets/src/tests/mod.rs index 662ff84f8..da264b1f9 100644 --- a/zrml/prediction-markets/src/tests/mod.rs +++ b/zrml/prediction-markets/src/tests/mod.rs @@ -47,6 +47,7 @@ use core::ops::Range; use frame_support::{ assert_noop, assert_ok, storage::unhashed::get_or, traits::NamedReservableCurrency, }; +use frame_system::pallet_prelude::BlockNumberFor; use orml_traits::MultiCurrency; use sp_arithmetic::Perbill; use sp_runtime::traits::{BlakeTwo256, Hash, Zero}; @@ -91,7 +92,7 @@ impl StateTransitionMock { } } -fn get_deadlines() -> Deadlines<::BlockNumber> { +fn get_deadlines() -> Deadlines> { Deadlines { grace_period: 1_u32.into(), oracle_duration: ::MinOracleDuration::get(), From 3ece979942e23ac07ce39b160aa0f54babe11d70 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 19:43:24 +0200 Subject: [PATCH 14/16] Upgrade zrml-neo-swaps --- Cargo.lock | 1 + zrml/neo-swaps/Cargo.toml | 1 + zrml/neo-swaps/src/benchmarking.rs | 6 +- zrml/neo-swaps/src/lib.rs | 12 +- .../traits/liquidity_tree_helper.rs | 5 - .../liquidity_tree/types/liquidity_tree.rs | 12 -- .../types/liquidity_tree_child_indices.rs | 18 --- zrml/neo-swaps/src/migration.rs | 20 +-- zrml/neo-swaps/src/mock.rs | 134 +++++++++++------- zrml/neo-swaps/src/tests/buy.rs | 2 +- zrml/neo-swaps/src/tests/deploy_pool.rs | 2 +- zrml/neo-swaps/src/tests/join.rs | 2 +- zrml/neo-swaps/src/tests/mod.rs | 2 +- zrml/neo-swaps/src/tests/sell.rs | 2 +- zrml/prediction-markets/src/mock.rs | 92 ++++++------ 15 files changed, 154 insertions(+), 157 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1f9dd0b00..1535b7070 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15177,6 +15177,7 @@ dependencies = [ "frame-support", "frame-system", "hydra-dx-math", + "log", "more-asserts", "orml-asset-registry", "orml-currencies", diff --git a/zrml/neo-swaps/Cargo.toml b/zrml/neo-swaps/Cargo.toml index e5cf62103..33e4a2b79 100644 --- a/zrml/neo-swaps/Cargo.toml +++ b/zrml/neo-swaps/Cargo.toml @@ -5,6 +5,7 @@ frame-benchmarking = { workspace = true, optional = true } frame-support = { workspace = true } frame-system = { workspace = true } hydra-dx-math = { workspace = true } +log = { workspace = true } orml-traits = { workspace = true } parity-scale-codec = { workspace = true, features = ["derive", "max-encoded-len"] } scale-info = { workspace = true, features = ["derive"] } diff --git a/zrml/neo-swaps/src/benchmarking.rs b/zrml/neo-swaps/src/benchmarking.rs index ad55064b0..0854e2e57 100644 --- a/zrml/neo-swaps/src/benchmarking.rs +++ b/zrml/neo-swaps/src/benchmarking.rs @@ -31,7 +31,10 @@ use frame_support::{ }; use frame_system::RawOrigin; use orml_traits::MultiCurrency; -use sp_runtime::{traits::Get, Perbill, SaturatedConversion}; +use sp_runtime::{ + traits::{Get, Zero}, + Perbill, SaturatedConversion, +}; use zeitgeist_primitives::{ constants::{base_multiples::*, CENT}, math::fixed::{BaseProvider, FixedDiv, FixedMul, ZeitgeistBase}, @@ -472,7 +475,6 @@ mod benchmarks { // Mock up some fees. Needs to be large enough to ensure that Bob's share is not smaller // than the existential deposit. - let pool = Pools::::get(market_id).unwrap(); let max_node_count = LiquidityTreeOf::::max_node_count() as u128; let fee_amount = (max_node_count * _10).saturated_into(); deposit_fees::(market_id, fee_amount); diff --git a/zrml/neo-swaps/src/lib.rs b/zrml/neo-swaps/src/lib.rs index 6519c130c..8b2e5bad0 100644 --- a/zrml/neo-swaps/src/lib.rs +++ b/zrml/neo-swaps/src/lib.rs @@ -53,15 +53,18 @@ mod pallet { pallet_prelude::StorageMap, require_transactional, traits::{Get, IsType, StorageVersion}, - transactional, PalletError, PalletId, RuntimeDebug, Twox64Concat, + transactional, PalletError, PalletId, Twox64Concat, + }; + use frame_system::{ + ensure_signed, + pallet_prelude::{BlockNumberFor, OriginFor}, }; - use frame_system::{ensure_signed, pallet_prelude::OriginFor}; use orml_traits::MultiCurrency; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::{ traits::{AccountIdConversion, CheckedSub, Saturating, Zero}, - DispatchError, DispatchResult, Perbill, SaturatedConversion, + DispatchError, DispatchResult, Perbill, RuntimeDebug, SaturatedConversion, }; use zeitgeist_primitives::{ constants::{BASE, CENT}, @@ -120,7 +123,7 @@ mod pallet { MarketId = MarketIdOf, >; - type MarketCommons: MarketCommonsPalletApi; + type MarketCommons: MarketCommonsPalletApi>; type MultiCurrency: MultiCurrency>; @@ -142,7 +145,6 @@ mod pallet { #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData); #[pallet::storage] diff --git a/zrml/neo-swaps/src/liquidity_tree/traits/liquidity_tree_helper.rs b/zrml/neo-swaps/src/liquidity_tree/traits/liquidity_tree_helper.rs index e73073d08..1bbe1c7df 100644 --- a/zrml/neo-swaps/src/liquidity_tree/traits/liquidity_tree_helper.rs +++ b/zrml/neo-swaps/src/liquidity_tree/traits/liquidity_tree_helper.rs @@ -84,11 +84,6 @@ where op: UpdateDescendantStakeOperation, ) -> DispatchResult; - /// Mutate each child of the node at `index` using `mutator`. - fn mutate_each_child(&mut self, index: u32, mutator: F) -> DispatchResult - where - F: FnMut(&mut Self::Node) -> DispatchResult; - /// Return the number of nodes in the tree. Note that abandoned nodes are counted. fn node_count(&self) -> u32; diff --git a/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree.rs b/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree.rs index 5986b85f2..7b8963f0f 100644 --- a/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree.rs +++ b/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree.rs @@ -377,18 +377,6 @@ where Ok(()) } - fn mutate_each_child(&mut self, index: u32, mut mutator: F) -> DispatchResult - where - F: FnMut(&mut Self::Node) -> DispatchResult, - { - let child_indices = self.children(index)?; - child_indices.apply(|index| { - self.mutate_node(index, |node| mutator(node))?; - Ok(()) - })?; - Ok(()) - } - fn node_count(&self) -> u32 { self.nodes.len() as u32 } diff --git a/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree_child_indices.rs b/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree_child_indices.rs index 4a4d47cad..e26788933 100644 --- a/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree_child_indices.rs +++ b/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree_child_indices.rs @@ -15,8 +15,6 @@ // You should have received a copy of the GNU General Public License // along with Zeitgeist. If not, see . -use sp_runtime::DispatchError; - /// Structure for managing children in a liquidity tree. pub(crate) struct LiquidityTreeChildIndices { /// Left-hand side child; `None` if there's no left-hand side child (the node is either empty or @@ -27,22 +25,6 @@ pub(crate) struct LiquidityTreeChildIndices { pub(crate) rhs: Option, } -impl LiquidityTreeChildIndices { - /// Applies a `mutator` function to each child if it exists. - pub fn apply(&self, mut mutator: F) -> Result<(), DispatchError> - where - F: FnMut(u32) -> Result<(), DispatchError>, - { - if let Some(lhs) = self.lhs { - mutator(lhs)?; - } - if let Some(rhs) = self.rhs { - mutator(rhs)?; - } - Ok(()) - } -} - // Implement `From` for destructuring impl From for (Option, Option) { fn from(child_indices: LiquidityTreeChildIndices) -> (Option, Option) { diff --git a/zrml/neo-swaps/src/migration.rs b/zrml/neo-swaps/src/migration.rs index 2aa4996f9..8650ec124 100644 --- a/zrml/neo-swaps/src/migration.rs +++ b/zrml/neo-swaps/src/migration.rs @@ -22,20 +22,20 @@ use crate::{ use alloc::collections::BTreeMap; use core::marker::PhantomData; use frame_support::{ - dispatch::Weight, - log, traits::{Get, OnRuntimeUpgrade, StorageVersion}, - RuntimeDebug, + weights::Weight, }; +use log; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; -use sp_runtime::Saturating; +use sp_runtime::{RuntimeDebug, Saturating}; cfg_if::cfg_if! { if #[cfg(feature = "try-runtime")] { use crate::{MarketIdOf}; use alloc::{format, vec::Vec}; use frame_support::{migration::storage_key_iter, pallet_prelude::Twox64Concat}; + use sp_runtime::DispatchError; } } @@ -111,7 +111,7 @@ where } #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, &'static str> { + fn pre_upgrade() -> Result, DispatchError> { let old_pools = storage_key_iter::, OldPoolOf, Twox64Concat>(NEO_SWAPS, POOLS) .collect::>(); @@ -119,7 +119,7 @@ where } #[cfg(feature = "try-runtime")] - fn post_upgrade(previous_state: Vec) -> Result<(), &'static str> { + fn post_upgrade(previous_state: Vec) -> Result<(), DispatchError> { let old_pools: BTreeMap, OldPoolOf> = Decode::decode(&mut &previous_state[..]) .map_err(|_| "Failed to decode state: Invalid state")?; @@ -152,11 +152,11 @@ mod tests { MarketIdOf, PoolOf, Pools, }; use alloc::collections::BTreeMap; - use frame_support::{ - dispatch::fmt::Debug, migration::put_storage_value, storage_root, StateVersion, - StorageHasher, Twox64Concat, - }; + use core::fmt::Debug; + use frame_support::{migration::put_storage_value, StorageHasher, Twox64Concat}; use parity_scale_codec::Encode; + use sp_io::storage::root as storage_root; + use sp_runtime::StateVersion; use zeitgeist_primitives::types::Asset; #[test] diff --git a/zrml/neo-swaps/src/mock.rs b/zrml/neo-swaps/src/mock.rs index 610bc955f..35f3f52fb 100644 --- a/zrml/neo-swaps/src/mock.rs +++ b/zrml/neo-swaps/src/mock.rs @@ -30,15 +30,12 @@ use frame_support::{ construct_runtime, ord_parameter_types, parameter_types, traits::{AsEnsureOriginWithArg, Contains, Everything, NeverEnsureOrigin}, }; -use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy}; -#[cfg(feature = "parachain")] -use orml_asset_registry::AssetMetadata; +use frame_system::{mocking::MockBlock, EnsureRoot, EnsureSigned, EnsureSignedBy}; use orml_traits::MultiCurrency; use parity_scale_codec::Compact; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, ConstU32, Get, IdentityLookup, Zero}, - DispatchResult, Perbill, Percent, SaturatedConversion, + BuildStorage, DispatchResult, Perbill, Percent, SaturatedConversion, }; use zeitgeist_primitives::{ constants::{ @@ -66,12 +63,19 @@ use zeitgeist_primitives::{ math::fixed::FixedMul, traits::{DeployPoolApi, DistributeFees}, types::{ - AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, - CampaignAsset, CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, Index, - MarketAsset, MarketId, Moment, UncheckedExtrinsicTest, + AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, CampaignAsset, + CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, MarketAsset, MarketId, + Moment, }, }; use zrml_neo_swaps::BalanceOf; +#[cfg(feature = "parachain")] +use { + orml_traits::asset_registry::AssetProcessor, + parity_scale_codec::Encode, + sp_runtime::DispatchError, + zeitgeist_primitives::types::{CustomMetadata, XcmAsset}, +}; pub const ALICE: AccountIdTest = 0; #[allow(unused)] @@ -154,8 +158,6 @@ where } } -pub type UncheckedExtrinsic = UncheckedExtrinsicTest; - pub struct DustRemovalWhitelist; impl Contains for DustRemovalWhitelist { @@ -169,31 +171,28 @@ pub(super) type CampaignAssetsInstance = pallet_assets::Instance2; pub(super) type MarketAssetsInstance = pallet_assets::Instance3; construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsic, - { - NeoSwaps: zrml_neo_swaps::{Call, Event, Pallet}, - AssetManager: orml_currencies::{Call, Pallet, Storage}, - AssetRouter: zrml_asset_router::{Pallet}, - Authorized: zrml_authorized::{Event, Pallet, Storage}, - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - Court: zrml_court::{Event, Pallet, Storage}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - LiquidityMining: zrml_liquidity_mining::{Config, Event, Pallet}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketCommons: zrml_market_commons::{Pallet, Storage}, - PredictionMarkets: zrml_prediction_markets::{Event, Pallet, Storage}, - RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage}, - SimpleDisputes: zrml_simple_disputes::{Event, Pallet, Storage}, - GlobalDisputes: zrml_global_disputes::{Event, Pallet, Storage}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, - Tokens: orml_tokens::{Config, Event, Pallet, Storage}, - Treasury: pallet_treasury::{Call, Event, Pallet, Storage}, + pub enum Runtime { + NeoSwaps: zrml_neo_swaps, + AssetManager: orml_currencies, + #[cfg(feature = "parachain")] + AssetRegistry: orml_asset_registry, + AssetRouter: zrml_asset_router, + Authorized: zrml_authorized, + Balances: pallet_balances, + CampaignAssets: pallet_assets::, + Court: zrml_court, + CustomAssets: pallet_assets::, + LiquidityMining: zrml_liquidity_mining, + MarketAssets: pallet_assets::, + MarketCommons: zrml_market_commons, + PredictionMarkets: zrml_prediction_markets, + RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, + SimpleDisputes: zrml_simple_disputes, + GlobalDisputes: zrml_global_disputes, + System: frame_system, + Timestamp: pallet_timestamp, + Tokens: orml_tokens, + Treasury: pallet_treasury, } ); @@ -325,7 +324,7 @@ impl zrml_asset_router::Config for Runtime { type MarketAssets = MarketAssets; } -impl pallet_randomness_collective_flip::Config for Runtime {} +impl pallet_insecure_randomness_collective_flip::Config for Runtime {} impl zrml_prediction_markets::Config for Runtime { type AdvisoryBond = AdvisoryBond; @@ -334,7 +333,7 @@ impl zrml_prediction_markets::Config for Runtime { type AssetCreator = AssetRouter; type AssetDestroyer = AssetRouter; #[cfg(feature = "parachain")] - type AssetRegistry = MockRegistry; + type AssetRegistry = AssetRegistry; type Authorized = Authorized; type CloseEarlyBlockPeriod = CloseEarlyBlockPeriod; type CloseEarlyDisputeBond = CloseEarlyDisputeBond; @@ -429,27 +428,26 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); - type OnSetCode = (); type RuntimeOrigin = RuntimeOrigin; type PalletInfo = PalletInfo; type SS58Prefix = (); type SystemWeightInfo = (); type Version = (); + type OnSetCode = (); } impl orml_currencies::Config for Runtime { @@ -477,8 +475,12 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; + type MaxHolds = (); + type MaxFreezes = (); type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; @@ -546,13 +548,34 @@ impl pallet_treasury::Config for Runtime { type WeightInfo = (); } -#[cfg(feature = "parachain")] -zrml_prediction_markets::impl_mock_registry! { - MockRegistry, - zeitgeist_primitives::types::XcmAsset, - Balance, - zeitgeist_primitives::types::CustomMetadata -} +cfg_if::cfg_if!( + if #[cfg(feature = "parachain")] { + type AssetMetadata = orml_traits::asset_registry::AssetMetadata< + Balance, + CustomMetadata, + ConstU32<1024> + >; + pub struct NoopAssetProcessor {} + + impl AssetProcessor for NoopAssetProcessor { + fn pre_register(id: Option, asset_metadata: AssetMetadata) + -> Result<(XcmAsset, AssetMetadata), DispatchError> { + Ok((id.unwrap(), asset_metadata)) + } + } + + impl orml_asset_registry::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type CustomMetadata = CustomMetadata; + type AssetId = XcmAsset; + type AuthorityOrigin = EnsureRoot; + type AssetProcessor = NoopAssetProcessor; + type Balance = Balance; + type StringLimit = ConstU32<1024>; + type WeightInfo = (); + } + } +); #[allow(unused)] pub struct ExtBuilder { @@ -570,7 +593,7 @@ impl Default for ExtBuilder { #[allow(unused)] impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); pallet_balances::GenesisConfig:: { balances: self.balances } @@ -578,7 +601,6 @@ impl ExtBuilder { .unwrap(); #[cfg(feature = "parachain")] { - use frame_support::traits::GenesisBuild; orml_tokens::GenesisConfig:: { balances: vec![(ALICE, FOREIGN_ASSET.try_into().unwrap(), 100_000_000_001 * _1)], } @@ -588,18 +610,20 @@ impl ExtBuilder { allow_as_base_asset: true, ..Default::default() }; - orml_asset_registry_mock::GenesisConfig { - metadata: vec![( + orml_asset_registry::GenesisConfig:: { + assets: vec![( FOREIGN_ASSET.try_into().unwrap(), AssetMetadata { decimals: 18, - name: "MKL".as_bytes().to_vec(), - symbol: "MKL".as_bytes().to_vec(), + name: "MKL".as_bytes().to_vec().try_into().unwrap(), + symbol: "MKL".as_bytes().to_vec().try_into().unwrap(), existential_deposit: 0, location: None, additional: custom_metadata, - }, + } + .encode(), )], + last_asset_id: FOREIGN_ASSET.try_into().unwrap(), } .assimilate_storage(&mut t) .unwrap(); diff --git a/zrml/neo-swaps/src/tests/buy.rs b/zrml/neo-swaps/src/tests/buy.rs index 799549c69..9ecd703bb 100644 --- a/zrml/neo-swaps/src/tests/buy.rs +++ b/zrml/neo-swaps/src/tests/buy.rs @@ -299,7 +299,7 @@ fn buy_fails_on_insufficient_funds() { ); let amount_in = _10; #[cfg(not(feature = "parachain"))] - let expected_error = pallet_balances::Error::::InsufficientBalance; + let expected_error = DispatchError::Token(TokenError::FundsUnavailable); #[cfg(feature = "parachain")] let expected_error = orml_tokens::Error::::BalanceTooLow; assert_ok!(AssetManager::deposit(BASE_ASSET, &BOB, amount_in - 1)); diff --git a/zrml/neo-swaps/src/tests/deploy_pool.rs b/zrml/neo-swaps/src/tests/deploy_pool.rs index ac02e5955..df7b8202a 100644 --- a/zrml/neo-swaps/src/tests/deploy_pool.rs +++ b/zrml/neo-swaps/src/tests/deploy_pool.rs @@ -429,7 +429,7 @@ fn deploy_pool_fails_on_insufficient_funds() { vec![_3_4, _1_4], CENT ), - pallet_assets::Error::::BalanceLow + DispatchError::Arithmetic(ArithmeticError::Underflow) ); }); } diff --git a/zrml/neo-swaps/src/tests/join.rs b/zrml/neo-swaps/src/tests/join.rs index a230bef0b..866c0b8e3 100644 --- a/zrml/neo-swaps/src/tests/join.rs +++ b/zrml/neo-swaps/src/tests/join.rs @@ -216,7 +216,7 @@ fn join_fails_on_insufficient_funds() { _100, vec![u128::MAX, u128::MAX] ), - pallet_assets::Error::::NoAccount + DispatchError::Arithmetic(ArithmeticError::Underflow) ); }); } diff --git a/zrml/neo-swaps/src/tests/mod.rs b/zrml/neo-swaps/src/tests/mod.rs index 6c8f9c98c..dc172faaf 100644 --- a/zrml/neo-swaps/src/tests/mod.rs +++ b/zrml/neo-swaps/src/tests/mod.rs @@ -29,7 +29,7 @@ mod withdraw_fees; use crate::{consts::*, mock::*, traits::*, *}; use frame_support::{assert_noop, assert_ok}; use orml_traits::MultiCurrency; -use sp_runtime::Perbill; +use sp_runtime::{ArithmeticError, DispatchError, Perbill, TokenError}; use zeitgeist_primitives::{ constants::{base_multiples::*, CENT}, math::fixed::{FixedDiv, FixedMul}, diff --git a/zrml/neo-swaps/src/tests/sell.rs b/zrml/neo-swaps/src/tests/sell.rs index dfbd415c8..b4a688b33 100644 --- a/zrml/neo-swaps/src/tests/sell.rs +++ b/zrml/neo-swaps/src/tests/sell.rs @@ -352,7 +352,7 @@ fn sell_fails_on_insufficient_funds() { amount_in, u128::MAX, ), - pallet_assets::Error::::BalanceLow, + DispatchError::Token(TokenError::FundsUnavailable), ); }); } diff --git a/zrml/prediction-markets/src/mock.rs b/zrml/prediction-markets/src/mock.rs index 4847294b1..13e383350 100644 --- a/zrml/prediction-markets/src/mock.rs +++ b/zrml/prediction-markets/src/mock.rs @@ -219,6 +219,7 @@ type MarketAssetsInstance = pallet_assets::Instance3; construct_runtime!( pub enum Runtime { + #[cfg(feature = "parachain")] AssetRegistry: orml_asset_registry, AssetRouter: zrml_asset_router, Authorized: zrml_authorized, @@ -658,52 +659,53 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); - cfg_if::cfg_if!( - if #[cfg(feature = "parachain")] { - orml_tokens::GenesisConfig:: { - balances: (0..69) - .map(|idx| (idx, Currencies::ForeignAsset(100), INITIAL_BALANCE)) - .collect(), - } - .assimilate_storage(&mut t) - .unwrap(); - - let custom_metadata = zeitgeist_primitives::types::CustomMetadata { - allow_as_base_asset: true, - ..Default::default() - }; - - orml_asset_registry::GenesisConfig:: { - assets: vec![ - ( - XcmAsset::ForeignAsset(100), - AssetMetadata { - decimals: 18, - name: "ACALA USD".as_bytes().to_vec().try_into().unwrap(), - symbol: "AUSD".as_bytes().to_vec().try_into().unwrap(), - existential_deposit: 0, - location: None, - additional: custom_metadata, - }.encode(), - ), - ( - XcmAsset::ForeignAsset(420), - AssetMetadata { - decimals: 18, - name: "FANCY_TOKEN".as_bytes().to_vec().try_into().unwrap(), - symbol: "FTK".as_bytes().to_vec().try_into().unwrap(), - existential_deposit: 0, - location: None, - additional: zeitgeist_primitives::types::CustomMetadata::default(), - }.encode(), - ), - ], - last_asset_id: XcmAsset::ForeignAsset(420) - } - .assimilate_storage(&mut t) - .unwrap(); + #[cfg(feature = "parachain")] + { + orml_tokens::GenesisConfig:: { + balances: (0..69) + .map(|idx| (idx, Currencies::ForeignAsset(100), INITIAL_BALANCE)) + .collect(), } - ); + .assimilate_storage(&mut t) + .unwrap(); + + let custom_metadata = zeitgeist_primitives::types::CustomMetadata { + allow_as_base_asset: true, + ..Default::default() + }; + + orml_asset_registry::GenesisConfig:: { + assets: vec![ + ( + XcmAsset::ForeignAsset(100), + AssetMetadata { + decimals: 18, + name: "ACALA USD".as_bytes().to_vec().try_into().unwrap(), + symbol: "AUSD".as_bytes().to_vec().try_into().unwrap(), + existential_deposit: 0, + location: None, + additional: custom_metadata, + } + .encode(), + ), + ( + XcmAsset::ForeignAsset(420), + AssetMetadata { + decimals: 18, + name: "FANCY_TOKEN".as_bytes().to_vec().try_into().unwrap(), + symbol: "FTK".as_bytes().to_vec().try_into().unwrap(), + existential_deposit: 0, + location: None, + additional: zeitgeist_primitives::types::CustomMetadata::default(), + } + .encode(), + ), + ], + last_asset_id: XcmAsset::ForeignAsset(420), + } + .assimilate_storage(&mut t) + .unwrap(); + } let mut test_ext: sp_io::TestExternalities = t.into(); test_ext.execute_with(|| System::set_block_number(1)); From ee3d3aebd3e45ce7a70a24d30a8034743683b88e Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 20:01:03 +0200 Subject: [PATCH 15/16] Upgrade zrml-hybrid-router --- Cargo.lock | 1 + zrml/hybrid-router/Cargo.toml | 3 +- zrml/hybrid-router/src/lib.rs | 13 +-- zrml/hybrid-router/src/mock.rs | 143 ++++++++++++++++----------- zrml/hybrid-router/src/tests/buy.rs | 2 +- zrml/hybrid-router/src/tests/mod.rs | 5 +- zrml/hybrid-router/src/tests/sell.rs | 36 +++---- zrml/hybrid-router/src/types.rs | 2 +- 8 files changed, 117 insertions(+), 88 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1535b7070..fdaa4123f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15091,6 +15091,7 @@ dependencies = [ name = "zrml-hybrid-router" version = "0.5.2" dependencies = [ + "cfg-if", "env_logger 0.10.2", "frame-benchmarking", "frame-support", diff --git a/zrml/hybrid-router/Cargo.toml b/zrml/hybrid-router/Cargo.toml index 5da70a8e7..6cafcae80 100644 --- a/zrml/hybrid-router/Cargo.toml +++ b/zrml/hybrid-router/Cargo.toml @@ -9,7 +9,7 @@ sp-runtime = { workspace = true } zeitgeist-primitives = { workspace = true } zrml-market-commons = { workspace = true } - +cfg-if = { workspace = true, optional = true } orml-asset-registry = { workspace = true, optional = true } orml-currencies = { workspace = true, optional = true } orml-tokens = { workspace = true, optional = true } @@ -41,6 +41,7 @@ zrml-hybrid-router = { workspace = true, features = ["mock"] } [features] default = ["std"] mock = [ + "cfg-if", "orml-asset-registry/default", "orml-currencies/default", "orml-tokens/default", diff --git a/zrml/hybrid-router/src/lib.rs b/zrml/hybrid-router/src/lib.rs index 1155ee832..d04f9476b 100644 --- a/zrml/hybrid-router/src/lib.rs +++ b/zrml/hybrid-router/src/lib.rs @@ -40,17 +40,18 @@ mod pallet { use alloc::{vec, vec::Vec}; use core::marker::PhantomData; use frame_support::{ - ensure, - pallet_prelude::DispatchError, - require_transactional, + ensure, require_transactional, traits::{IsType, StorageVersion}, PalletId, }; - use frame_system::{ensure_signed, pallet_prelude::OriginFor}; + use frame_system::{ + ensure_signed, + pallet_prelude::{BlockNumberFor, OriginFor}, + }; use orml_traits::MultiCurrency; use sp_runtime::{ traits::{Get, Zero}, - DispatchResult, SaturatedConversion, Saturating, + DispatchError, DispatchResult, SaturatedConversion, Saturating, }; #[cfg(feature = "runtime-benchmarks")] use zeitgeist_primitives::traits::{CompleteSetOperationsApi, DeployPoolApi}; @@ -90,7 +91,7 @@ mod pallet { /// The identifier of individual markets. type MarketCommons: MarketCommonsPalletApi< AccountId = Self::AccountId, - BlockNumber = Self::BlockNumber, + BlockNumber = BlockNumberFor, Balance = BalanceOf, >; diff --git a/zrml/hybrid-router/src/mock.rs b/zrml/hybrid-router/src/mock.rs index feb7f3718..c6195e160 100644 --- a/zrml/hybrid-router/src/mock.rs +++ b/zrml/hybrid-router/src/mock.rs @@ -29,18 +29,13 @@ use frame_support::{ construct_runtime, ord_parameter_types, parameter_types, traits::{AsEnsureOriginWithArg, Contains, Everything, NeverEnsureOrigin}, }; -use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy}; -#[cfg(feature = "parachain")] -use orml_asset_registry::AssetMetadata; +use frame_system::{mocking::MockBlock, EnsureRoot, EnsureSigned, EnsureSignedBy}; use orml_traits::MultiCurrency; use parity_scale_codec::Compact; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, ConstU32, Get, IdentityLookup, Zero}, - Perbill, Percent, SaturatedConversion, + BuildStorage, Perbill, Percent, SaturatedConversion, }; -#[cfg(feature = "parachain")] -use zeitgeist_primitives::types::Asset; use zeitgeist_primitives::{ constants::mock::{ AddOutcomePeriod, AggregationPeriod, AppealBond, AppealPeriod, AssetsAccountDeposit, @@ -64,11 +59,19 @@ use zeitgeist_primitives::{ }, traits::DistributeFees, types::{ - AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, BlockNumber, BlockTest, - CampaignAsset, CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, Index, - MarketAsset, MarketId, Moment, UncheckedExtrinsicTest, + AccountIdTest, Amount, Assets, Balance, BasicCurrencyAdapter, CampaignAsset, + CampaignAssetId, Currencies, CustomAsset, CustomAssetId, Hash, MarketAsset, MarketId, + Moment, }, }; +#[cfg(feature = "parachain")] +use { + orml_traits::asset_registry::AssetProcessor, + parity_scale_codec::Encode, + sp_runtime::DispatchError, + zeitgeist_primitives::types::Asset, + zeitgeist_primitives::types::{CustomMetadata, XcmAsset}, +}; pub const ALICE: AccountIdTest = 0; #[allow(unused)] @@ -143,8 +146,6 @@ where } } -pub type UncheckedExtrinsic = UncheckedExtrinsicTest; - pub struct DustRemovalWhitelist; impl Contains for DustRemovalWhitelist { @@ -158,33 +159,30 @@ pub(super) type CampaignAssetsInstance = pallet_assets::Instance2; pub(super) type MarketAssetsInstance = pallet_assets::Instance3; construct_runtime!( - pub enum Runtime - where - Block = BlockTest, - NodeBlock = BlockTest, - UncheckedExtrinsic = UncheckedExtrinsic, - { - HybridRouter: zrml_hybrid_router::{Pallet, Call, Storage, Event}, - Orderbook: zrml_orderbook::{Call, Event, Pallet, Storage}, - AssetRouter: zrml_asset_router::{Pallet}, - NeoSwaps: zrml_neo_swaps::{Call, Event, Pallet}, - Authorized: zrml_authorized::{Event, Pallet, Storage}, - Balances: pallet_balances::{Call, Config, Event, Pallet, Storage}, - Court: zrml_court::{Event, Pallet, Storage}, - CampaignAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - CustomAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - MarketAssets: pallet_assets::::{Call, Pallet, Storage, Event}, - AssetManager: orml_currencies::{Call, Pallet, Storage}, - LiquidityMining: zrml_liquidity_mining::{Config, Event, Pallet}, - MarketCommons: zrml_market_commons::{Pallet, Storage}, - PredictionMarkets: zrml_prediction_markets::{Event, Pallet, Storage}, - RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage}, - SimpleDisputes: zrml_simple_disputes::{Event, Pallet, Storage}, - GlobalDisputes: zrml_global_disputes::{Event, Pallet, Storage}, - System: frame_system::{Call, Config, Event, Pallet, Storage}, - Timestamp: pallet_timestamp::{Pallet}, - Tokens: orml_tokens::{Config, Event, Pallet, Storage}, - Treasury: pallet_treasury::{Call, Event, Pallet, Storage}, + pub enum Runtime { + HybridRouter: zrml_hybrid_router, + Orderbook: zrml_orderbook, + AssetRouter: zrml_asset_router, + NeoSwaps: zrml_neo_swaps, + #[cfg(feature = "parachain")] + AssetRegistry: orml_asset_registry, + Authorized: zrml_authorized, + Balances: pallet_balances, + Court: zrml_court, + CampaignAssets: pallet_assets::, + CustomAssets: pallet_assets::, + MarketAssets: pallet_assets::, + AssetManager: orml_currencies, + LiquidityMining: zrml_liquidity_mining, + MarketCommons: zrml_market_commons, + PredictionMarkets: zrml_prediction_markets, + RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, + SimpleDisputes: zrml_simple_disputes, + GlobalDisputes: zrml_global_disputes, + System: frame_system, + Timestamp: pallet_timestamp, + Tokens: orml_tokens, + Treasury: pallet_treasury, } ); @@ -340,7 +338,7 @@ impl zrml_neo_swaps::Config for Runtime { type WeightInfo = zrml_neo_swaps::weights::WeightInfo; } -impl pallet_randomness_collective_flip::Config for Runtime {} +impl pallet_insecure_randomness_collective_flip::Config for Runtime {} impl zrml_prediction_markets::Config for Runtime { type AdvisoryBond = AdvisoryBond; @@ -349,7 +347,7 @@ impl zrml_prediction_markets::Config for Runtime { type AssetCreator = AssetRouter; type AssetDestroyer = AssetRouter; #[cfg(feature = "parachain")] - type AssetRegistry = MockRegistry; + type AssetRegistry = AssetRegistry; type Authorized = Authorized; type CloseEarlyBlockPeriod = CloseEarlyBlockPeriod; type CloseEarlyDisputeBond = CloseEarlyDisputeBond; @@ -444,29 +442,57 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; type AccountId = AccountIdTest; type BaseCallFilter = Everything; + type Block = MockBlock; type BlockHashCount = BlockHashCount; type BlockLength = (); - type BlockNumber = BlockNumber; type BlockWeights = (); type RuntimeCall = RuntimeCall; type DbWeight = (); type RuntimeEvent = RuntimeEvent; type Hash = Hash; type Hashing = BlakeTwo256; - type Header = Header; - type Index = Index; type Lookup = IdentityLookup; + type Nonce = u64; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); type OnNewAccount = (); - type OnSetCode = (); type RuntimeOrigin = RuntimeOrigin; type PalletInfo = PalletInfo; type SS58Prefix = (); type SystemWeightInfo = (); type Version = (); + type OnSetCode = (); } +cfg_if::cfg_if!( + if #[cfg(feature = "parachain")] { + type AssetMetadata = orml_traits::asset_registry::AssetMetadata< + Balance, + CustomMetadata, + ConstU32<1024> + >; + pub struct NoopAssetProcessor {} + + impl AssetProcessor for NoopAssetProcessor { + fn pre_register(id: Option, asset_metadata: AssetMetadata) + -> Result<(XcmAsset, AssetMetadata), DispatchError> { + Ok((id.unwrap(), asset_metadata)) + } + } + + impl orml_asset_registry::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type CustomMetadata = CustomMetadata; + type AssetId = XcmAsset; + type AuthorityOrigin = EnsureRoot; + type AssetProcessor = NoopAssetProcessor; + type Balance = Balance; + type StringLimit = ConstU32<1024>; + type WeightInfo = (); + } + } +); + impl orml_currencies::Config for Runtime { type GetNativeCurrencyId = GetNativeCurrencyId; type MultiCurrency = AssetRouter; @@ -492,8 +518,12 @@ impl pallet_balances::Config for Runtime { type AccountStore = System; type Balance = Balance; type DustRemoval = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; + type MaxHolds = (); + type MaxFreezes = (); type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; @@ -561,14 +591,6 @@ impl pallet_treasury::Config for Runtime { type WeightInfo = (); } -#[cfg(feature = "parachain")] -zrml_prediction_markets::impl_mock_registry! { - MockRegistry, - zeitgeist_primitives::types::XcmAsset, - Balance, - zeitgeist_primitives::types::CustomMetadata -} - #[allow(unused)] pub struct ExtBuilder { balances: Vec<(AccountIdTest, Balance)>, @@ -593,7 +615,7 @@ impl Default for ExtBuilder { #[allow(unused)] impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); // see the logs in tests when using `RUST_LOG=debug cargo test -- --nocapture` let _ = env_logger::builder().is_test(true).try_init(); pallet_balances::GenesisConfig:: { balances: self.balances } @@ -601,7 +623,6 @@ impl ExtBuilder { .unwrap(); #[cfg(feature = "parachain")] { - use frame_support::traits::GenesisBuild; orml_tokens::GenesisConfig:: { balances: vec![ (ALICE, FOREIGN_ASSET.try_into().unwrap(), INITIAL_BALANCE), @@ -614,18 +635,20 @@ impl ExtBuilder { allow_as_base_asset: true, ..Default::default() }; - orml_asset_registry_mock::GenesisConfig { - metadata: vec![( + orml_asset_registry::GenesisConfig:: { + assets: vec![( FOREIGN_ASSET.try_into().unwrap(), AssetMetadata { decimals: 18, - name: "MKL".as_bytes().to_vec(), - symbol: "MKL".as_bytes().to_vec(), + name: "MKL".as_bytes().to_vec().try_into().unwrap(), + symbol: "MKL".as_bytes().to_vec().try_into().unwrap(), existential_deposit: 0, location: None, additional: custom_metadata, - }, + } + .encode(), )], + last_asset_id: FOREIGN_ASSET.try_into().unwrap(), } .assimilate_storage(&mut t) .unwrap(); diff --git a/zrml/hybrid-router/src/tests/buy.rs b/zrml/hybrid-router/src/tests/buy.rs index fb3630b5c..e3da80452 100644 --- a/zrml/hybrid-router/src/tests/buy.rs +++ b/zrml/hybrid-router/src/tests/buy.rs @@ -673,7 +673,7 @@ fn buy_fails_if_balance_too_low() { let asset = Assets::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; - assert_ok!(Balances::set_balance(RuntimeOrigin::root(), ALICE, amount - 1, 0)); + assert_eq!(Balances::set_balance(&ALICE, amount - 1), amount - 1); let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; let strategy = Strategy::LimitOrder; diff --git a/zrml/hybrid-router/src/tests/mod.rs b/zrml/hybrid-router/src/tests/mod.rs index 1abce4120..da55d7ba8 100644 --- a/zrml/hybrid-router/src/tests/mod.rs +++ b/zrml/hybrid-router/src/tests/mod.rs @@ -18,7 +18,10 @@ #![cfg(all(feature = "mock", test))] use crate::{mock::*, types::*, utils::*, AccountIdOf, BalanceOf, MarketIdOf, *}; -use frame_support::{assert_noop, assert_ok}; +use frame_support::{ + assert_noop, assert_ok, + traits::{fungible::Mutate, tokens::Precision}, +}; use orml_currencies::Error as CurrenciesError; use orml_tokens::Error as TokensError; use orml_traits::MultiCurrency; diff --git a/zrml/hybrid-router/src/tests/sell.rs b/zrml/hybrid-router/src/tests/sell.rs index a1c383945..030daf36d 100644 --- a/zrml/hybrid-router/src/tests/sell.rs +++ b/zrml/hybrid-router/src/tests/sell.rs @@ -52,7 +52,7 @@ fn sell_to_amm_and_then_fill_specified_order() { let order_ids = Orders::::iter().map(|(k, _)| k).collect::>(); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in, Precision::Exact)); let min_price = _1_4.saturated_into::>(); let strategy = Strategy::LimitOrder; @@ -135,7 +135,7 @@ fn sell_to_amm_if_specified_order_has_lower_prices_than_the_amm() { let order_ids = Orders::::iter().map(|(k, _)| k).collect::>(); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount, Precision::Exact)); let min_price = _1_4.saturated_into::>(); let strategy = Strategy::LimitOrder; @@ -210,7 +210,7 @@ fn sell_fill_multiple_orders_if_amm_spot_price_lower_than_order_prices() { let order_ids = Orders::::iter().map(|(k, _)| k).collect::>(); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in, Precision::Exact)); let min_price = _1_4.saturated_into::>(); let strategy = Strategy::LimitOrder; @@ -265,7 +265,7 @@ fn sell_fill_specified_order_partially_if_amm_spot_price_lower() { assert_eq!(order_ids.len(), 1); let order_id = order_ids[0]; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount, Precision::Exact)); let min_price = _1_4.saturated_into::>(); let orders = vec![order_id]; @@ -316,7 +316,7 @@ fn sell_fails_if_asset_not_equal_to_order_book_taker_asset() { let amount_in = _2; let maker_amount = _1; - assert_ok!(AssetRouter::increase_balance(asset, &CHARLIE, maker_amount,)); + assert_ok!(AssetRouter::increase_balance(asset, &CHARLIE, maker_amount, Precision::Exact)); assert_ok!(Orderbook::place_order( RuntimeOrigin::signed(CHARLIE), @@ -331,7 +331,7 @@ fn sell_fails_if_asset_not_equal_to_order_book_taker_asset() { assert_eq!(order_ids.len(), 1); let order_id = order_ids[0]; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in, Precision::Exact)); let min_price = _1_4.saturated_into::>(); let orders = vec![order_id]; @@ -386,7 +386,7 @@ fn sell_fails_if_order_price_below_min_price() { assert_eq!(order_ids.len(), 1); let order_id = order_ids[0]; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, 5 * amount,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, 5 * amount, Precision::Exact)); let min_price = _3_4.saturated_into::>(); let orders = vec![order_id]; @@ -426,7 +426,7 @@ fn sell_to_amm() { let asset = Assets::CategoricalOutcome(market_id, 0); let amount = _2; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount, Precision::Exact)); let min_price = _1_4.saturated_into::>(); let orders = vec![]; @@ -478,7 +478,7 @@ fn sell_min_price_higher_than_amm_spot_price_results_in_place_order() { let asset = Assets::CategoricalOutcome(market_id, 0); let amount = _2; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount, Precision::Exact)); //* spot price of the AMM is 1 smaller than the min_price //* this results in no sell on the AMM, but places an order on the order book @@ -535,7 +535,7 @@ fn sell_to_amm_but_low_amount() { let asset = Assets::CategoricalOutcome(market_id, 0); let amount_in = _2; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in, Precision::Exact)); //* min_price is just 1 smaller than the spot price of the AMM //* this results in a low sell amount_in on the AMM @@ -605,7 +605,7 @@ fn sell_succeeds_for_numerical_soft_failure() { // increase_balance does not set total issuance AssetRouter::set_total_issuance(asset, amount_in); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in, Precision::Exact)); let min_price = (_1_100 / 1000).saturated_into::>(); let orders = vec![]; @@ -655,7 +655,7 @@ fn sell_to_amm_only() { let asset = Assets::CategoricalOutcome(market_id, 0); let amount = _2; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount, Precision::Exact)); let min_price = _1_4.saturated_into::>(); let orders = vec![]; @@ -706,7 +706,7 @@ fn sell_places_limit_order_no_pool() { let asset = Assets::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount, Precision::Exact)); let min_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -756,7 +756,7 @@ fn sell_fails_if_balance_too_low() { let asset = Assets::CategoricalOutcome(market_id, 0); let amount = 10 * BASE; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount - 1,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount - 1, Precision::Exact)); let min_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -822,7 +822,7 @@ fn sell_emits_event() { // increase_balance does not set total issuance AssetRouter::set_total_issuance(asset, amount_in); - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in, Precision::Exact)); let strategy = Strategy::LimitOrder; assert_ok!(HybridRouter::sell( @@ -871,7 +871,7 @@ fn sell_fails_if_asset_count_mismatch() { let asset = Assets::CategoricalOutcome(market_id, 0); let amount_in = 2 * BASE; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in, Precision::Exact)); let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; @@ -941,7 +941,7 @@ fn sell_fails_if_cancel_strategy_applied() { let asset_count = required_asset_count; let asset = Assets::CategoricalOutcome(market_id, 0); let amount_in = 10 * BASE; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in, Precision::Exact)); let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; let strategy = Strategy::ImmediateOrCancel; @@ -968,7 +968,7 @@ fn sell_fails_if_market_does_not_exist() { let asset_count = 2; let asset = Assets::CategoricalOutcome(market_id, 0); let amount_in = 10 * BASE; - assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in,)); + assert_ok!(AssetRouter::increase_balance(asset, &ALICE, amount_in, Precision::Exact)); let max_price = (BASE / 2).saturated_into::>(); let orders = vec![]; let strategy = Strategy::ImmediateOrCancel; diff --git a/zrml/hybrid-router/src/types.rs b/zrml/hybrid-router/src/types.rs index 03296651e..2d6a1d2fc 100644 --- a/zrml/hybrid-router/src/types.rs +++ b/zrml/hybrid-router/src/types.rs @@ -19,7 +19,7 @@ use crate::{AmmTradeOf, BalanceOf, Config, OrderTradeOf}; use alloc::vec::Vec; use frame_support::pallet_prelude::*; use scale_info::TypeInfo; -use sp_runtime::traits::Zero; +use sp_runtime::{traits::Zero, DispatchError}; use zeitgeist_primitives::math::checked_ops_res::{CheckedAddRes, CheckedSubRes}; /// Represents the strategy used when placing an order in a trading environment. From 0c631995077cf4b601d6db4f47e33ec155e06571 Mon Sep 17 00:00:00 2001 From: Harald Heckmann Date: Sun, 21 Apr 2024 20:08:14 +0200 Subject: [PATCH 16/16] Update license headers --- zrml/authorized/src/benchmarks.rs | 2 +- zrml/authorized/src/tests.rs | 2 +- zrml/global-disputes/src/lib.rs | 2 +- .../src/track_incentives_based_on_bought_shares.rs | 2 +- zrml/liquidity-mining/src/utils.rs | 1 + .../src/liquidity_tree/traits/liquidity_tree_helper.rs | 2 +- zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree.rs | 2 +- .../src/liquidity_tree/types/liquidity_tree_child_indices.rs | 2 +- zrml/rikiddo/src/lib.rs | 1 + zrml/rikiddo/src/mock.rs | 2 +- zrml/rikiddo/src/types.rs | 1 + zrml/rikiddo/src/types/ema_market_volume.rs | 1 + zrml/rikiddo/src/types/rikiddo_sigmoid_mv.rs | 1 + zrml/rikiddo/src/types/sigmoid_fee.rs | 1 + zrml/simple-disputes/src/benchmarks.rs | 2 +- zrml/simple-disputes/src/weights.rs | 2 +- zrml/styx/src/lib.rs | 2 +- zrml/styx/src/mock.rs | 2 +- zrml/styx/src/tests.rs | 1 + 19 files changed, 19 insertions(+), 12 deletions(-) diff --git a/zrml/authorized/src/benchmarks.rs b/zrml/authorized/src/benchmarks.rs index 167af074e..658df6bc6 100644 --- a/zrml/authorized/src/benchmarks.rs +++ b/zrml/authorized/src/benchmarks.rs @@ -1,4 +1,4 @@ -// Copyright 2022-2023 Forecasting Technologies LTD. +// Copyright 2022-2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/authorized/src/tests.rs b/zrml/authorized/src/tests.rs index d871247c3..8780673ae 100644 --- a/zrml/authorized/src/tests.rs +++ b/zrml/authorized/src/tests.rs @@ -1,4 +1,4 @@ -// Copyright 2022-2023 Forecasting Technologies LTD. +// Copyright 2022-2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/global-disputes/src/lib.rs b/zrml/global-disputes/src/lib.rs index 0fde17912..49dbdf09e 100644 --- a/zrml/global-disputes/src/lib.rs +++ b/zrml/global-disputes/src/lib.rs @@ -1,4 +1,4 @@ -// Copyright 2022-2023 Forecasting Technologies LTD. +// Copyright 2022-2024 Forecasting Technologies LTD. // // This file is part of Zeitgeist. // diff --git a/zrml/liquidity-mining/src/track_incentives_based_on_bought_shares.rs b/zrml/liquidity-mining/src/track_incentives_based_on_bought_shares.rs index 1e6efbd21..24410c66d 100644 --- a/zrml/liquidity-mining/src/track_incentives_based_on_bought_shares.rs +++ b/zrml/liquidity-mining/src/track_incentives_based_on_bought_shares.rs @@ -1,4 +1,4 @@ -// Copyright 2022 Forecasting Technologies LTD. +// Copyright 2022-2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/liquidity-mining/src/utils.rs b/zrml/liquidity-mining/src/utils.rs index c6f464838..eb5523c52 100644 --- a/zrml/liquidity-mining/src/utils.rs +++ b/zrml/liquidity-mining/src/utils.rs @@ -1,3 +1,4 @@ +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/neo-swaps/src/liquidity_tree/traits/liquidity_tree_helper.rs b/zrml/neo-swaps/src/liquidity_tree/traits/liquidity_tree_helper.rs index 1bbe1c7df..8ec63ad2f 100644 --- a/zrml/neo-swaps/src/liquidity_tree/traits/liquidity_tree_helper.rs +++ b/zrml/neo-swaps/src/liquidity_tree/traits/liquidity_tree_helper.rs @@ -1,4 +1,4 @@ -// Copyright 2023 Forecasting Technologies LTD. +// Copyright 2023-2024 Forecasting Technologies LTD. // // This file is part of Zeitgeist. // diff --git a/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree.rs b/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree.rs index 7b8963f0f..c95a5d996 100644 --- a/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree.rs +++ b/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree.rs @@ -1,4 +1,4 @@ -// Copyright 2023 Forecasting Technologies LTD. +// Copyright 2023-2024 Forecasting Technologies LTD. // // This file is part of Zeitgeist. // diff --git a/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree_child_indices.rs b/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree_child_indices.rs index e26788933..55e4c51b4 100644 --- a/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree_child_indices.rs +++ b/zrml/neo-swaps/src/liquidity_tree/types/liquidity_tree_child_indices.rs @@ -1,4 +1,4 @@ -// Copyright 2023 Forecasting Technologies LTD. +// Copyright 2023-2024 Forecasting Technologies LTD. // // This file is part of Zeitgeist. // diff --git a/zrml/rikiddo/src/lib.rs b/zrml/rikiddo/src/lib.rs index 2c64058f0..049885acd 100644 --- a/zrml/rikiddo/src/lib.rs +++ b/zrml/rikiddo/src/lib.rs @@ -1,3 +1,4 @@ +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/rikiddo/src/mock.rs b/zrml/rikiddo/src/mock.rs index ea9fe77dd..40a1431e3 100644 --- a/zrml/rikiddo/src/mock.rs +++ b/zrml/rikiddo/src/mock.rs @@ -1,4 +1,4 @@ -// Copyright 2023 Forecasting Technologies LTD. +// Copyright 2023-2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/rikiddo/src/types.rs b/zrml/rikiddo/src/types.rs index 220ad624a..5a5858e1e 100644 --- a/zrml/rikiddo/src/types.rs +++ b/zrml/rikiddo/src/types.rs @@ -1,3 +1,4 @@ +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/rikiddo/src/types/ema_market_volume.rs b/zrml/rikiddo/src/types/ema_market_volume.rs index 0a2fb7838..847f1dbc5 100644 --- a/zrml/rikiddo/src/types/ema_market_volume.rs +++ b/zrml/rikiddo/src/types/ema_market_volume.rs @@ -1,3 +1,4 @@ +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/rikiddo/src/types/rikiddo_sigmoid_mv.rs b/zrml/rikiddo/src/types/rikiddo_sigmoid_mv.rs index 766ee97e2..eba866310 100644 --- a/zrml/rikiddo/src/types/rikiddo_sigmoid_mv.rs +++ b/zrml/rikiddo/src/types/rikiddo_sigmoid_mv.rs @@ -1,3 +1,4 @@ +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/rikiddo/src/types/sigmoid_fee.rs b/zrml/rikiddo/src/types/sigmoid_fee.rs index 5fcaf1f51..97640057a 100644 --- a/zrml/rikiddo/src/types/sigmoid_fee.rs +++ b/zrml/rikiddo/src/types/sigmoid_fee.rs @@ -1,3 +1,4 @@ +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/simple-disputes/src/benchmarks.rs b/zrml/simple-disputes/src/benchmarks.rs index b9bfaff98..8df924268 100644 --- a/zrml/simple-disputes/src/benchmarks.rs +++ b/zrml/simple-disputes/src/benchmarks.rs @@ -1,4 +1,4 @@ -// Copyright 2023 Forecasting Technologies LTD. +// Copyright 2023-2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/simple-disputes/src/weights.rs b/zrml/simple-disputes/src/weights.rs index 1c5b8bb04..4bc89e83a 100644 --- a/zrml/simple-disputes/src/weights.rs +++ b/zrml/simple-disputes/src/weights.rs @@ -1,4 +1,4 @@ -// Copyright 2023 Forecasting Technologies LTD. +// Copyright 2023-2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/styx/src/lib.rs b/zrml/styx/src/lib.rs index 710fc7791..300e3b3ed 100644 --- a/zrml/styx/src/lib.rs +++ b/zrml/styx/src/lib.rs @@ -1,4 +1,4 @@ -// Copyright 2022-2023 Forecasting Technologies LTD. +// Copyright 2022-2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/styx/src/mock.rs b/zrml/styx/src/mock.rs index 6f2eff6f0..307964602 100644 --- a/zrml/styx/src/mock.rs +++ b/zrml/styx/src/mock.rs @@ -1,4 +1,4 @@ -// Copyright 2023 Forecasting Technologies LTD. +// Copyright 2023-2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist. diff --git a/zrml/styx/src/tests.rs b/zrml/styx/src/tests.rs index 8a3e0281d..309abcc83 100644 --- a/zrml/styx/src/tests.rs +++ b/zrml/styx/src/tests.rs @@ -1,3 +1,4 @@ +// Copyright 2024 Forecasting Technologies LTD. // Copyright 2021-2022 Zeitgeist PM LLC. // // This file is part of Zeitgeist.