From 16654c4026474ca41fa9e1e0a41761365fcec691 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Wed, 7 Dec 2022 12:53:11 +0300 Subject: [PATCH 01/72] Fix bug with double `AssetRegistered` event Signed-off-by: Daniil Polyakov --- pallets/assets/src/lib.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/pallets/assets/src/lib.rs b/pallets/assets/src/lib.rs index d86a853f83..cf352dffd2 100644 --- a/pallets/assets/src/lib.rs +++ b/pallets/assets/src/lib.rs @@ -304,7 +304,7 @@ pub mod pallet { DEFAULT_BALANCE_PRECISION }; - let asset_id = Self::register_from( + Self::register_from( &author, symbol, name, @@ -315,8 +315,6 @@ pub mod pallet { opt_desc, )?; - Self::deposit_event(Event::AssetRegistered(asset_id, author)); - Ok(().into()) } From c79259a81b5ec1e99ba72e39a201e7064cf731b0 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Wed, 7 Dec 2022 20:44:22 +0300 Subject: [PATCH 02/72] Take `DataFeed` trait from `oracle-proxy-pallet` branch Signed-off-by: Daniil Polyakov --- common/src/traits.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/common/src/traits.rs b/common/src/traits.rs index d31943a534..cd827c35a4 100644 --- a/common/src/traits.rs +++ b/common/src/traits.rs @@ -706,3 +706,23 @@ impl LiquidityProxyTrait { + /// Get rate for the specified symbol + /// - `symbol`: which symbol to query + fn quote(symbol: Symbol) -> Result, Error>; + + /// Get all supported symbols and their last update time + fn list_enabled_symbols() -> Result, Error>; +} + +impl DataFeed for () { + fn quote(_symbol: Symbol) -> Result, Error> { + Ok(None) + } + + fn list_enabled_symbols() -> Result, Error> { + Ok(Vec::new()) + } +} From 079d7af2d5db7361b07f75264810c2f70ac98afa Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Wed, 7 Dec 2022 20:45:23 +0300 Subject: [PATCH 03/72] Allow trading pair registration via method Signed-off-by: Daniil Polyakov --- pallets/trading-pair/src/lib.rs | 61 +++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 26 deletions(-) diff --git a/pallets/trading-pair/src/lib.rs b/pallets/trading-pair/src/lib.rs index 4f957c0dec..a91847d427 100644 --- a/pallets/trading-pair/src/lib.rs +++ b/pallets/trading-pair/src/lib.rs @@ -75,6 +75,40 @@ impl EnsureTradingPairExists for } impl Pallet { + pub fn register_pair( + dex_id: T::DEXId, + base_asset_id: T::AssetId, + target_asset_id: T::AssetId, + ) -> Result<(), DispatchError> { + let dex_info = DEXManager::::get_dex_info(&dex_id)?; + ensure!( + base_asset_id == dex_info.base_asset_id + || base_asset_id == dex_info.synthetic_base_asset_id, + Error::::ForbiddenBaseAssetId + ); + Assets::::ensure_asset_exists(&base_asset_id)?; + Assets::::ensure_asset_exists(&target_asset_id)?; + ensure!( + base_asset_id != target_asset_id, + Error::::IdenticalAssetIds + ); + let trading_pair = TradingPair:: { + base_asset_id, + target_asset_id, + }; + ensure!( + Self::enabled_sources(&dex_id, &trading_pair).is_none(), + Error::::TradingPairExists + ); + EnabledSources::::insert( + &dex_id, + &trading_pair, + BTreeSet::::new(), + ); + Self::deposit_event(Event::TradingPairStored(dex_id, trading_pair)); + Ok(().into()) + } + pub fn list_trading_pairs(dex_id: &T::DEXId) -> Result>, DispatchError> { DEXManager::::ensure_dex_exists(dex_id)?; Ok(EnabledSources::::iter_prefix(dex_id) @@ -195,32 +229,7 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { let _author = T::EnsureDEXManager::ensure_can_manage(&dex_id, origin, ManagementMode::Public)?; - let dex_info = DEXManager::::get_dex_info(&dex_id)?; - ensure!( - base_asset_id == dex_info.base_asset_id - || base_asset_id == dex_info.synthetic_base_asset_id, - Error::::ForbiddenBaseAssetId - ); - Assets::::ensure_asset_exists(&base_asset_id)?; - Assets::::ensure_asset_exists(&target_asset_id)?; - ensure!( - base_asset_id != target_asset_id, - Error::::IdenticalAssetIds - ); - let trading_pair = TradingPair:: { - base_asset_id, - target_asset_id, - }; - ensure!( - Self::enabled_sources(&dex_id, &trading_pair).is_none(), - Error::::TradingPairExists - ); - EnabledSources::::insert( - &dex_id, - &trading_pair, - BTreeSet::::new(), - ); - Self::deposit_event(Event::TradingPairStored(dex_id, trading_pair)); + Self::register_pair(dex_id, base_asset_id, target_asset_id)?; Ok(().into()) } } From 14dc82367295575ca8bb5156d483434963aa4bf6 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Wed, 7 Dec 2022 21:04:37 +0300 Subject: [PATCH 04/72] Introduce new extrinsics Signed-off-by: Daniil Polyakov --- pallets/xst/src/benchmarking.rs | 39 ++---- pallets/xst/src/lib.rs | 204 +++++++++++++++++++++++--------- pallets/xst/src/weights.rs | 17 +-- 3 files changed, 161 insertions(+), 99 deletions(-) diff --git a/pallets/xst/src/benchmarking.rs b/pallets/xst/src/benchmarking.rs index 1561130209..d1b1fd6176 100644 --- a/pallets/xst/src/benchmarking.rs +++ b/pallets/xst/src/benchmarking.rs @@ -59,36 +59,11 @@ fn assert_last_event(generic_event: ::Event) { } // TODO: properly implement benchmarks -benchmarks! { - initialize_pool { - let caller = alice::(); - let dex_id: T::DEXId = common::DEXId::Polkaswap.into(); - Permissions::::assign_permission( - caller.clone(), - &caller, - permissions::MANAGE_DEX, - permissions::Scope::Limited(common::hash(&dex_id)), - ).unwrap(); - }: _( - RawOrigin::Signed(caller.clone()), - DAI.into() - ) - verify { - assert_last_event::(Event::PoolInitialized(common::DEXId::Polkaswap.into(), DAI.into()).into()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::mock::{ExtBuilder, Runtime}; - use frame_support::assert_ok; +// benchmarks! {} - #[test] - #[ignore] - fn test_benchmarks() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(Pallet::::test_benchmark_initialize_pool()); - }); - } -} +// #[cfg(test)] +// mod tests { +// use super::*; +// use crate::mock::{ExtBuilder, Runtime}; +// use frame_support::assert_ok; +// } diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index eaee086c81..4efd6a72fd 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -47,17 +47,18 @@ use codec::{Decode, Encode}; use common::fixnum::ops::Zero as _; use common::prelude::{ Balance, EnsureDEXManager, EnsureTradingPairExists, Fixed, FixedWrapper, PriceToolsPallet, - QuoteAmount, SwapAmount, SwapOutcome, + QuoteAmount, SwapAmount, SwapOutcome, DEFAULT_BALANCE_PRECISION, }; use common::{ - balance, fixed, fixed_wrapper, DEXId, DexIdOf, GetMarketInfo, LiquidityProxyTrait, - LiquiditySource, LiquiditySourceFilter, LiquiditySourceType, ManagementMode, RewardReason, DAI, - XSTUSD, + balance, fixed, fixed_wrapper, AssetName, AssetSymbol, DEXId, DataFeed, GetMarketInfo, + LiquidityProxyTrait, LiquiditySource, LiquiditySourceFilter, LiquiditySourceType, RewardReason, + DAI, XSTUSD, }; use frame_support::traits::Get; use frame_support::weights::Weight; use frame_support::{ensure, fail}; use permissions::{Scope, BURN, MINT}; +use scale_info::prelude::{format, string::ToString}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; use sp_runtime::{DispatchError, DispatchResult}; @@ -66,9 +67,9 @@ use sp_std::vec::Vec; pub trait WeightInfo { fn on_initialize(_elems: u32) -> Weight; - fn initialize_pool() -> Weight; fn set_reference_asset() -> Weight; fn enable_synthetic_asset() -> Weight; + fn disable_synthetic_asset() -> Weight; } type Assets = assets::Pallet; @@ -120,8 +121,8 @@ impl DistributionAccountData { #[frame_support::pallet] pub mod pallet { use super::*; - use frame_support::pallet_prelude::*; use frame_support::traits::StorageVersion; + use frame_support::{pallet_prelude::*, Parameter}; use frame_system::pallet_prelude::*; #[pallet::config] @@ -131,12 +132,16 @@ pub mod pallet { type GetSyntheticBaseAssetId: Get; type LiquidityProxy: LiquidityProxyTrait; type EnsureDEXManager: EnsureDEXManager; + // TODO Remove type EnsureTradingPairExists: EnsureTradingPairExists< Self::DEXId, Self::AssetId, DispatchError, >; type PriceToolsPallet: PriceToolsPallet; + type Oracle: DataFeed; + /// Type of symbol received from oracles + type Symbol: Parameter + ToString + From<&'static str> + MaybeSerializeDeserialize; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } @@ -159,21 +164,6 @@ pub mod pallet { #[pallet::call] impl Pallet { - /// Enable exchange path on the pool for pair BaseAsset-SyntheticAsset. - #[pallet::weight(::WeightInfo::initialize_pool())] - pub fn initialize_pool( - origin: OriginFor, - synthetic_asset_id: T::AssetId, - ) -> DispatchResultWithPostInfo { - let _who = ::EnsureDEXManager::ensure_can_manage( - &DEXId::Polkaswap.into(), - origin, - ManagementMode::Private, - )?; - Self::initialize_pool_unchecked(synthetic_asset_id, true)?; - Ok(().into()) - } - /// Change reference asset which is used to determine collateral assets value. Intended to be e.g., stablecoin DAI. #[pallet::weight(::WeightInfo::set_reference_asset())] pub fn set_reference_asset( @@ -190,9 +180,33 @@ pub mod pallet { pub fn enable_synthetic_asset( origin: OriginFor, synthetic_asset: T::AssetId, + reference_symbol: T::Symbol, + ) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + + Self::enable_synthetic_asset_unchecked(synthetic_asset, reference_symbol, true)?; + Ok(().into()) + } + + /// TODO + /// + /// Should it unregister asset or just disable exchanging? + /// What to do with users? + #[pallet::weight(::WeightInfo::disable_synthetic_asset())] + pub fn disable_synthetic_asset( + origin: OriginFor, + synthetic_asset: T::AssetId, ) -> DispatchResultWithPostInfo { ensure_root(origin)?; - EnabledSynthetics::::mutate(|set| set.insert(synthetic_asset)); + + let reference_symbol = EnabledSynthetics::::try_get(synthetic_asset) + .map_err(|_| Error::::SyntheticIsNotEnabled)? + .expect("Synthetic tables always store `Some`"); + + EnabledSynthetics::::remove(synthetic_asset); + EnabledSymbols::::remove(reference_symbol); + + Self::deposit_event(Event::SyntheticAssetDisabled(synthetic_asset)); Ok(().into()) } } @@ -200,10 +214,12 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// Pool is initialized for pair. [DEX Id, Synthetic Asset Id] - PoolInitialized(DexIdOf, AssetIdOf), /// Reference Asset has been changed for pool. [New Reference Asset Id] ReferenceAssetChanged(AssetIdOf), + /// Synthetic asset has been enabled. [Synthetic Asset Id, Reference Symbol] + SyntheticAssetEnabled(AssetIdOf, T::Symbol), + /// Synthetic asset has been disabled. [Synthetic Asset Id] + SyntheticAssetDisabled(AssetIdOf), } #[pallet::error] @@ -228,6 +244,15 @@ pub mod pallet { CantExchange, /// Increment account reference error. IncRefError, + /// Attempt to enable synthetic asset with inexistent symbol. + SymbolDoesNotExist, + /// Attempt to enable synthetic asset with symbol + /// that is already referenced to another synthetic. + SymbolAlreadyReferencedToSynthetic, + /// Attempt to enable synthetic asset that is already enabled. + SyntheticAlreadyEnabled, + /// Attempt to disable synthetic asset that is not enabled. + SyntheticIsNotEnabled, } // TODO: better by replaced with Get<> @@ -246,10 +271,21 @@ pub mod pallet { #[pallet::getter(fn base_fee)] pub(super) type BaseFee = StorageValue<_, Fixed, ValueQuery, DefaultForBaseFee>; - /// XST Assets allowed to be traded using XST. + /// Synthetic assets and their reference symbols. + /// + /// It's a programmer responsibility to keep this collection consistent with [`EnabledSymbols`]. #[pallet::storage] #[pallet::getter(fn enabled_synthetics)] - pub type EnabledSynthetics = StorageValue<_, BTreeSet, ValueQuery>; + pub type EnabledSynthetics = + StorageMap<_, Blake2_128Concat, T::AssetId, Option, ValueQuery>; + + /// Reference symbols and their synthetic assets. + /// + /// It's a programmer responsibility to keep this collection consistent with [`EnabledSynthetics`]. + #[pallet::storage] + #[pallet::getter(fn enabled_symbols)] + pub type EnabledSymbols = + StorageMap<_, Blake2_128Concat, T::Symbol, Option, ValueQuery>; /// Asset that is used to compare collateral assets by value, e.g., DAI. #[pallet::storage] @@ -268,7 +304,7 @@ pub mod pallet { /// Asset that is used to compare collateral assets by value, e.g., DAI. pub reference_asset_id: T::AssetId, /// List of tokens enabled as collaterals initially. - pub initial_synthetic_assets: Vec, + pub initial_synthetic_assets: Vec<(T::AssetId, T::Symbol)>, } #[cfg(feature = "std")] @@ -277,7 +313,7 @@ pub mod pallet { Self { tech_account_id: Default::default(), reference_asset_id: DAI.into(), - initial_synthetic_assets: [XSTUSD.into()].into(), + initial_synthetic_assets: [(XSTUSD.into(), "USD".into())].into(), } } } @@ -287,13 +323,12 @@ pub mod pallet { fn build(&self) { PermissionedTechAccount::::put(&self.tech_account_id); ReferenceAssetId::::put(&self.reference_asset_id); - self.initial_synthetic_assets - .iter() - .cloned() - .for_each(|asset_id| { - Pallet::::initialize_pool_unchecked(asset_id, false) + self.initial_synthetic_assets.iter().cloned().for_each( + |(asset_id, reference_symbol)| { + Pallet::::enable_synthetic_asset_unchecked(asset_id, reference_symbol, false) .expect("Failed to initialize XST synthetics.") - }); + }, + ); } } } @@ -309,34 +344,37 @@ impl Pallet { ) } - fn initialize_pool_unchecked( - synthetic_asset_id: T::AssetId, + fn enable_synthetic_asset_unchecked( + synthetic_asset: T::AssetId, + reference_symbol: T::Symbol, transactional: bool, ) -> DispatchResult { let code = || { - ensure!( - !EnabledSynthetics::::get().contains(&synthetic_asset_id), - Error::::PoolAlreadyInitializedForPair - ); - T::EnsureTradingPairExists::ensure_trading_pair_exists( - &DEXId::Polkaswap.into(), - &T::GetSyntheticBaseAssetId::get(), - &synthetic_asset_id, - )?; - trading_pair::Pallet::::enable_source_for_trading_pair( - &DEXId::Polkaswap.into(), - &T::GetSyntheticBaseAssetId::get(), - &synthetic_asset_id, - LiquiditySourceType::XSTPool, - )?; + if EnabledSynthetics::::contains_key(&synthetic_asset) { + return Err(Error::::SyntheticAlreadyEnabled.into()); + } + + if EnabledSymbols::::contains_key(&reference_symbol) { + return Err(Error::::SymbolAlreadyReferencedToSynthetic.into()); + } - EnabledSynthetics::::mutate(|set| set.insert(synthetic_asset_id)); - Self::deposit_event(Event::PoolInitialized( - DEXId::Polkaswap.into(), - synthetic_asset_id, + Self::ensure_symbol_exists(&reference_symbol)?; + + Self::register_synthetic_asset(synthetic_asset, reference_symbol.clone())?; + + Self::enable_synthetic_pair(synthetic_asset)?; + + // TODO: Technically it's possible to use references to avoid cloning + EnabledSynthetics::::insert(synthetic_asset, Some(reference_symbol.clone())); + EnabledSymbols::::insert(reference_symbol.clone(), Some(synthetic_asset)); + + Self::deposit_event(Event::SyntheticAssetEnabled( + synthetic_asset, + reference_symbol, )); - Ok(()) + Ok(().into()) }; + if transactional { common::with_transaction(|| code()) } else { @@ -344,6 +382,23 @@ impl Pallet { } } + fn enable_synthetic_pair(synthetic_asset_id: T::AssetId) -> DispatchResult { + trading_pair::Pallet::::register_pair( + DEXId::Polkaswap.into(), + T::GetSyntheticBaseAssetId::get(), + synthetic_asset_id, + )?; + + trading_pair::Pallet::::enable_source_for_trading_pair( + &DEXId::Polkaswap.into(), + &T::GetSyntheticBaseAssetId::get(), + &synthetic_asset_id, + LiquiditySourceType::XSTPool, + )?; + + Ok(()) + } + /// Buys the main asset (e.g., XST). /// Calculates and returns the current buy price, assuming that input is the synthetic asset and output is the main asset. pub fn buy_price( @@ -654,6 +709,35 @@ impl Pallet { }) } } + + fn ensure_symbol_exists(reference_symbol: &T::Symbol) -> Result<(), DispatchError> { + let all_symbols = T::Oracle::list_enabled_symbols()?; + all_symbols + .into_iter() + .find(|(symbol, _rate)| symbol == reference_symbol) + .map(|_| ()) + .ok_or_else(|| Error::::SymbolDoesNotExist.into()) + } + + fn register_synthetic_asset( + synthetic_asset: T::AssetId, + reference_symbol: T::Symbol, + ) -> Result<(), DispatchError> { + let permissioned_tech_account_id = Self::permissioned_tech_account(); + let permissioned_account_id = + Technical::::tech_account_id_to_account_id(&permissioned_tech_account_id)?; + Assets::::register_asset_id( + permissioned_account_id, + synthetic_asset, + AssetSymbol(format!("XST{}", reference_symbol.to_string()).into_bytes()), + AssetName(format!("Sora Synthetic {}", reference_symbol.to_string()).into_bytes()), + DEFAULT_BALANCE_PRECISION, + balance!(0), + true, + None, + None, + ) + } } impl LiquiditySource @@ -668,9 +752,9 @@ impl LiquiditySource::get().contains(&output_asset_id) + EnabledSynthetics::::contains_key(&output_asset_id) } else if output_asset_id == &T::GetSyntheticBaseAssetId::get() { - EnabledSynthetics::::get().contains(&input_asset_id) + EnabledSynthetics::::contains_key(&input_asset_id) } else { false } @@ -774,6 +858,8 @@ impl GetMarketInfo for Pallet { /// `target_assets` refer to synthetic assets fn enabled_target_assets() -> BTreeSet { - EnabledSynthetics::::get() + EnabledSynthetics::::iter() + .map(|(asset_id, _)| asset_id) + .collect() } } diff --git a/pallets/xst/src/weights.rs b/pallets/xst/src/weights.rs index 1e9bee1a8e..a122dd7bea 100644 --- a/pallets/xst/src/weights.rs +++ b/pallets/xst/src/weights.rs @@ -43,11 +43,6 @@ impl crate::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().writes(1 as Weight)) } - fn initialize_pool() -> Weight { - (387_780_000 as Weight) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } fn set_reference_asset() -> Weight { (210_815_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) @@ -58,19 +53,25 @@ impl crate::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + fn disable_synthetic_asset() -> Weight { + // TODO + (210_815_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } impl crate::WeightInfo for () { fn on_initialize(_elems: u32) -> Weight { EXTRINSIC_FIXED_WEIGHT } - fn initialize_pool() -> Weight { - EXTRINSIC_FIXED_WEIGHT - } fn set_reference_asset() -> Weight { EXTRINSIC_FIXED_WEIGHT } fn enable_synthetic_asset() -> Weight { EXTRINSIC_FIXED_WEIGHT } + fn disable_synthetic_asset() -> Weight { + EXTRINSIC_FIXED_WEIGHT + } } From 4e05c6f8de7724e0facc01b15881ffaea0ab7bb5 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Fri, 9 Dec 2022 14:00:24 +0300 Subject: [PATCH 05/72] Add "USD" corner case Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 4efd6a72fd..550d5661dd 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -141,7 +141,11 @@ pub mod pallet { type PriceToolsPallet: PriceToolsPallet; type Oracle: DataFeed; /// Type of symbol received from oracles - type Symbol: Parameter + ToString + From<&'static str> + MaybeSerializeDeserialize; + type Symbol: Parameter + + ToString + + From<&'static str> + + PartialEq<&'static str> + + MaybeSerializeDeserialize; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } @@ -364,7 +368,6 @@ impl Pallet { Self::enable_synthetic_pair(synthetic_asset)?; - // TODO: Technically it's possible to use references to avoid cloning EnabledSynthetics::::insert(synthetic_asset, Some(reference_symbol.clone())); EnabledSymbols::::insert(reference_symbol.clone(), Some(synthetic_asset)); @@ -711,6 +714,10 @@ impl Pallet { } fn ensure_symbol_exists(reference_symbol: &T::Symbol) -> Result<(), DispatchError> { + if *reference_symbol == "USD" { + return Ok(()); + } + let all_symbols = T::Oracle::list_enabled_symbols()?; all_symbols .into_iter() @@ -730,7 +737,7 @@ impl Pallet { permissioned_account_id, synthetic_asset, AssetSymbol(format!("XST{}", reference_symbol.to_string()).into_bytes()), - AssetName(format!("Sora Synthetic {}", reference_symbol.to_string()).into_bytes()), + AssetName(format!("SORA Synthetic {}", reference_symbol.to_string()).into_bytes()), DEFAULT_BALANCE_PRECISION, balance!(0), true, From da06c1ae8abe64dd985c3ed66402cae72a0ebaab Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Fri, 9 Dec 2022 14:07:25 +0300 Subject: [PATCH 06/72] Add `asset_symbol` and `asset_name` parameters Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 45 +++++++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 550d5661dd..23ea0c2448 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -58,7 +58,6 @@ use frame_support::traits::Get; use frame_support::weights::Weight; use frame_support::{ensure, fail}; use permissions::{Scope, BURN, MINT}; -use scale_info::prelude::{format, string::ToString}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; use sp_runtime::{DispatchError, DispatchResult}; @@ -142,7 +141,6 @@ pub mod pallet { type Oracle: DataFeed; /// Type of symbol received from oracles type Symbol: Parameter - + ToString + From<&'static str> + PartialEq<&'static str> + MaybeSerializeDeserialize; @@ -184,11 +182,19 @@ pub mod pallet { pub fn enable_synthetic_asset( origin: OriginFor, synthetic_asset: T::AssetId, + asset_symbol: AssetSymbol, + asset_name: AssetName, reference_symbol: T::Symbol, ) -> DispatchResultWithPostInfo { ensure_root(origin)?; - Self::enable_synthetic_asset_unchecked(synthetic_asset, reference_symbol, true)?; + Self::enable_synthetic_asset_unchecked( + synthetic_asset, + asset_symbol, + asset_name, + reference_symbol, + true, + )?; Ok(().into()) } @@ -308,7 +314,7 @@ pub mod pallet { /// Asset that is used to compare collateral assets by value, e.g., DAI. pub reference_asset_id: T::AssetId, /// List of tokens enabled as collaterals initially. - pub initial_synthetic_assets: Vec<(T::AssetId, T::Symbol)>, + pub initial_synthetic_assets: Vec<(T::AssetId, AssetSymbol, AssetName, T::Symbol)>, } #[cfg(feature = "std")] @@ -317,7 +323,13 @@ pub mod pallet { Self { tech_account_id: Default::default(), reference_asset_id: DAI.into(), - initial_synthetic_assets: [(XSTUSD.into(), "USD".into())].into(), + initial_synthetic_assets: [( + XSTUSD.into(), + AssetSymbol(b"XSTUSD".to_vec()), + AssetName(b"SORA Synthetic USD".to_vec()), + "USD".into(), + )] + .into(), } } } @@ -328,9 +340,15 @@ pub mod pallet { PermissionedTechAccount::::put(&self.tech_account_id); ReferenceAssetId::::put(&self.reference_asset_id); self.initial_synthetic_assets.iter().cloned().for_each( - |(asset_id, reference_symbol)| { - Pallet::::enable_synthetic_asset_unchecked(asset_id, reference_symbol, false) - .expect("Failed to initialize XST synthetics.") + |(asset_id, asset_symbol, asset_name, reference_symbol)| { + Pallet::::enable_synthetic_asset_unchecked( + asset_id, + asset_symbol, + asset_name, + reference_symbol, + false, + ) + .expect("Failed to initialize XST synthetics.") }, ); } @@ -350,6 +368,8 @@ impl Pallet { fn enable_synthetic_asset_unchecked( synthetic_asset: T::AssetId, + asset_symbol: AssetSymbol, + asset_name: AssetName, reference_symbol: T::Symbol, transactional: bool, ) -> DispatchResult { @@ -364,7 +384,7 @@ impl Pallet { Self::ensure_symbol_exists(&reference_symbol)?; - Self::register_synthetic_asset(synthetic_asset, reference_symbol.clone())?; + Self::register_synthetic_asset(synthetic_asset, asset_symbol, asset_name)?; Self::enable_synthetic_pair(synthetic_asset)?; @@ -728,7 +748,8 @@ impl Pallet { fn register_synthetic_asset( synthetic_asset: T::AssetId, - reference_symbol: T::Symbol, + asset_symbol: AssetSymbol, + asset_name: AssetName, ) -> Result<(), DispatchError> { let permissioned_tech_account_id = Self::permissioned_tech_account(); let permissioned_account_id = @@ -736,8 +757,8 @@ impl Pallet { Assets::::register_asset_id( permissioned_account_id, synthetic_asset, - AssetSymbol(format!("XST{}", reference_symbol.to_string()).into_bytes()), - AssetName(format!("SORA Synthetic {}", reference_symbol.to_string()).into_bytes()), + asset_symbol, + asset_name, DEFAULT_BALANCE_PRECISION, balance!(0), true, From 1f0daf792a1d0ce0c61db2785b62801a3bfe0abe Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Fri, 9 Dec 2022 15:07:02 +0300 Subject: [PATCH 07/72] Add synthetic asset id generation Signed-off-by: Daniil Polyakov --- Cargo.lock | 1 + pallets/xst/Cargo.toml | 4 ++++ pallets/xst/src/lib.rs | 49 +++++++++++++++++++++++++----------------- 3 files changed, 34 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 020c360fc5..bd9735fcf5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13489,6 +13489,7 @@ name = "xst" version = "1.0.1" dependencies = [ "assets", + "blake2 0.10.5", "ceres-liquidity-locker", "common", "demeter-farming-platform", diff --git a/pallets/xst/Cargo.toml b/pallets/xst/Cargo.toml index eef07b92aa..214509c917 100644 --- a/pallets/xst/Cargo.toml +++ b/pallets/xst/Cargo.toml @@ -27,6 +27,7 @@ serde = { version = "1.0.101", default-features = false, optional = true, featur sp-arithmetic = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-tokens", default-features = false } assets = { path = "../assets", default-features = false } common = { path = "../../common", default-features = false } @@ -38,6 +39,7 @@ technical = { path = "../technical", default-features = false } trading-pair = { path = "../trading-pair", default-features = false } pool-xyk = { path = "../pool-xyk", default-features = false } pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +blake2 = { version = "0.10.5", default-features = false } [dev-dependencies] ceres-liquidity-locker = { path = "../ceres-liquidity-locker" } @@ -66,6 +68,7 @@ std = [ 'sp-arithmetic/std', 'sp-runtime/std', 'sp-std/std', + 'sp-core/std', 'tokens/std', 'pool-xyk/std', 'pallet-timestamp/std', @@ -75,6 +78,7 @@ std = [ 'liquidity-proxy/std', 'dex-api/std', 'common/std', + 'blake2/std' ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 23ea0c2448..b620f96922 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -60,6 +60,7 @@ use frame_support::{ensure, fail}; use permissions::{Scope, BURN, MINT}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; +use sp_core::H256; use sp_runtime::{DispatchError, DispatchResult}; use sp_std::collections::btree_set::BTreeSet; use sp_std::vec::Vec; @@ -76,6 +77,7 @@ type Technical = technical::Pallet; pub const TECH_ACCOUNT_PREFIX: &[u8] = b"xst-pool"; pub const TECH_ACCOUNT_PERMISSIONED: &[u8] = b"permissioned"; +pub const SYNTHETIC_ASSET_ID_PREFIX: [u8; 5] = hex_literal::hex!("0200077700"); pub use pallet::*; @@ -181,7 +183,6 @@ pub mod pallet { #[pallet::weight(::WeightInfo::enable_synthetic_asset())] pub fn enable_synthetic_asset( origin: OriginFor, - synthetic_asset: T::AssetId, asset_symbol: AssetSymbol, asset_name: AssetName, reference_symbol: T::Symbol, @@ -189,7 +190,6 @@ pub mod pallet { ensure_root(origin)?; Self::enable_synthetic_asset_unchecked( - synthetic_asset, asset_symbol, asset_name, reference_symbol, @@ -259,8 +259,6 @@ pub mod pallet { /// Attempt to enable synthetic asset with symbol /// that is already referenced to another synthetic. SymbolAlreadyReferencedToSynthetic, - /// Attempt to enable synthetic asset that is already enabled. - SyntheticAlreadyEnabled, /// Attempt to disable synthetic asset that is not enabled. SyntheticIsNotEnabled, } @@ -314,7 +312,7 @@ pub mod pallet { /// Asset that is used to compare collateral assets by value, e.g., DAI. pub reference_asset_id: T::AssetId, /// List of tokens enabled as collaterals initially. - pub initial_synthetic_assets: Vec<(T::AssetId, AssetSymbol, AssetName, T::Symbol)>, + pub initial_synthetic_assets: Vec<(AssetSymbol, AssetName, T::Symbol)>, } #[cfg(feature = "std")] @@ -324,7 +322,6 @@ pub mod pallet { tech_account_id: Default::default(), reference_asset_id: DAI.into(), initial_synthetic_assets: [( - XSTUSD.into(), AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), "USD".into(), @@ -340,9 +337,8 @@ pub mod pallet { PermissionedTechAccount::::put(&self.tech_account_id); ReferenceAssetId::::put(&self.reference_asset_id); self.initial_synthetic_assets.iter().cloned().for_each( - |(asset_id, asset_symbol, asset_name, reference_symbol)| { + |(asset_symbol, asset_name, reference_symbol)| { Pallet::::enable_synthetic_asset_unchecked( - asset_id, asset_symbol, asset_name, reference_symbol, @@ -367,32 +363,26 @@ impl Pallet { } fn enable_synthetic_asset_unchecked( - synthetic_asset: T::AssetId, asset_symbol: AssetSymbol, asset_name: AssetName, reference_symbol: T::Symbol, transactional: bool, ) -> DispatchResult { let code = || { - if EnabledSynthetics::::contains_key(&synthetic_asset) { - return Err(Error::::SyntheticAlreadyEnabled.into()); - } - if EnabledSymbols::::contains_key(&reference_symbol) { return Err(Error::::SymbolAlreadyReferencedToSynthetic.into()); } - Self::ensure_symbol_exists(&reference_symbol)?; - Self::register_synthetic_asset(synthetic_asset, asset_symbol, asset_name)?; - - Self::enable_synthetic_pair(synthetic_asset)?; + let synthetic_asset_id = Self::generate_synthetic_asset_id(&reference_symbol); + Self::register_synthetic_asset(synthetic_asset_id, asset_symbol, asset_name)?; + Self::enable_synthetic_pair(synthetic_asset_id)?; - EnabledSynthetics::::insert(synthetic_asset, Some(reference_symbol.clone())); - EnabledSymbols::::insert(reference_symbol.clone(), Some(synthetic_asset)); + EnabledSynthetics::::insert(synthetic_asset_id, Some(reference_symbol.clone())); + EnabledSymbols::::insert(reference_symbol.clone(), Some(synthetic_asset_id)); Self::deposit_event(Event::SyntheticAssetEnabled( - synthetic_asset, + synthetic_asset_id, reference_symbol, )); Ok(().into()) @@ -405,6 +395,25 @@ impl Pallet { } } + fn generate_synthetic_asset_id(reference_symbol: &T::Symbol) -> T::AssetId { + use blake2::{Blake2s256, Digest}; + + if *reference_symbol == "USD" { + return XSTUSD.into(); + } + + let bytes = reference_symbol.encode(); + let mut hasher = Blake2s256::new(); + hasher.update(bytes); + let mut hashed_bytes = hasher.finalize(); + + hashed_bytes[0..SYNTHETIC_ASSET_ID_PREFIX.len()] + .copy_from_slice(&SYNTHETIC_ASSET_ID_PREFIX); + + let h256 = H256::from_slice(&hashed_bytes); + h256.into() + } + fn enable_synthetic_pair(synthetic_asset_id: T::AssetId) -> DispatchResult { trading_pair::Pallet::::register_pair( DEXId::Polkaswap.into(), From b91fd238b767bcfa51a98acc67a048cc4de1f3ac Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Fri, 9 Dec 2022 18:17:28 +0300 Subject: [PATCH 08/72] Fix reference_price() to work with all synthetics Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 46 ++++++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index b620f96922..7072acf8c5 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -254,6 +254,8 @@ pub mod pallet { CantExchange, /// Increment account reference error. IncRefError, + /// Synthetic asset does not exist. + SyntheticDoesNotExist, /// Attempt to enable synthetic asset with inexistent symbol. SymbolDoesNotExist, /// Attempt to enable synthetic asset with symbol @@ -261,6 +263,8 @@ pub mod pallet { SymbolAlreadyReferencedToSynthetic, /// Attempt to disable synthetic asset that is not enabled. SyntheticIsNotEnabled, + /// Error quoting price from oracle. + OracleQuoteError, } // TODO: better by replaced with Get<> @@ -721,24 +725,32 @@ impl Pallet { /// Example use: understand actual value of two tokens in terms of USD. fn reference_price(asset_id: &T::AssetId) -> Result { let reference_asset_id = ReferenceAssetId::::get(); - // XSTUSD is a special case because it is equal to the reference asset, DAI - if asset_id == &reference_asset_id || asset_id == &XSTUSD.into() { - Ok(balance!(1)) - } else { - ::PriceToolsPallet::get_average_price( - asset_id, - &reference_asset_id, - ) - .map(|avg| { + let synthetic_base_asset_id = T::GetSyntheticBaseAssetId::get(); + + match asset_id { + // XSTUSD is a special case because it is equal to the reference asset, DAI + id if id == &XSTUSD.into() || id == &reference_asset_id => Ok(balance!(1)), + id if id == &synthetic_base_asset_id => { // We don't let the price of XST w.r.t. DAI go under $3, to prevent manipulation attacks - if asset_id == &T::GetSyntheticBaseAssetId::get() - && &reference_asset_id == &DAI.into() - { - avg.max(balance!(3)) - } else { - avg - } - }) + T::PriceToolsPallet::get_average_price(id, &reference_asset_id).map(|avg| { + if reference_asset_id == DAI.into() { + avg.max(balance!(3)) + } else { + avg + } + }) + } + id => { + let symbol = + EnabledSynthetics::::get(id).ok_or(Error::::SyntheticDoesNotExist)?; + let price = + balance!(T::Oracle::quote(symbol)?.ok_or(Error::::OracleQuoteError)?); + // Just for convenience. Right now will always return 1. + let reference_asset_price = Self::reference_price(&reference_asset_id)?; + Ok(price + .checked_div(reference_asset_price) + .expect("Reference asset price is never 0.")) + } } } From 1b1c2ebf77a7635c39efb20dc0b30fa93036a88c Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Fri, 9 Dec 2022 18:22:19 +0300 Subject: [PATCH 09/72] Add oracle prices to `buy_price()` Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 7072acf8c5..d1d8707690 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -439,30 +439,28 @@ impl Pallet { /// Calculates and returns the current buy price, assuming that input is the synthetic asset and output is the main asset. pub fn buy_price( main_asset_id: &T::AssetId, - _synthetic_asset_id: &T::AssetId, //TODO: we will use this once we have more XST assets + synthetic_asset_id: &T::AssetId, quantity: QuoteAmount, ) -> Result { - let main_asset_price_per_reference_unit: FixedWrapper = - Self::reference_price(main_asset_id)?.into(); + let main_asset_price: FixedWrapper = Self::reference_price(main_asset_id)?.into(); + let synthetic_asset_price: FixedWrapper = Self::reference_price(synthetic_asset_id)?.into(); match quantity { - // Input target amount of XST(USD) to get some XST + // Input target amount of synthetic asset (e.g. XSTUSD) to get some synthetic base asset (e.g. XST) QuoteAmount::WithDesiredInput { desired_amount_in: synthetic_quantity, } => { - //TODO: here we assume only DAI-pegged XST(USD) synthetics. Need to have a price oracle to handle other synthetics in the future! - let main_out = synthetic_quantity / main_asset_price_per_reference_unit; + let main_out = synthetic_quantity * synthetic_asset_price / main_asset_price; main_out .get() .map_err(|_| Error::::PriceCalculationFailed.into()) .map(|value| value.max(Fixed::ZERO)) } - // Input some XST(USD) to get a target amount of XST + // Input some synthetic asset (e.g. XSTUSD) to get a target amount of synthetic base asset (e.g. XST) QuoteAmount::WithDesiredOutput { desired_amount_out: main_quantity, } => { - //TODO: here we assume only DAI-pegged XST(USD) synthetics. Need to have a price oracle to handle other synthetics in the future! - let synthetic_quantity = main_quantity * main_asset_price_per_reference_unit; + let synthetic_quantity = main_quantity * main_asset_price / synthetic_asset_price; synthetic_quantity .get() .map_err(|_| Error::::PriceCalculationFailed.into()) From 01d0e6508467be35bceb31183ab3d79b5462c3aa Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Fri, 9 Dec 2022 18:26:20 +0300 Subject: [PATCH 10/72] Add oracle prices to `sell_price()` Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index d1d8707690..abac780d2a 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -482,29 +482,28 @@ impl Pallet { /// in curve-like dependency. pub fn sell_price( main_asset_id: &T::AssetId, - _synthetic_asset_id: &T::AssetId, + synthetic_asset_id: &T::AssetId, quantity: QuoteAmount, ) -> Result { // Get reference prices for base and synthetic to understand token value. - let main_asset_price_per_reference_unit: FixedWrapper = - Self::reference_price(main_asset_id)?.into(); + let main_asset_price: FixedWrapper = Self::reference_price(main_asset_id)?.into(); + let synthetic_asset_price: FixedWrapper = Self::reference_price(synthetic_asset_id)?.into(); match quantity { - // Sell desired amount of XST for some XST(USD) + // Sell desired amount of synthetic base asset (e.g. XST) for some synthetic asset (e.g. XSTUSD) QuoteAmount::WithDesiredInput { desired_amount_in: quantity_main, } => { - let output_synthetic = quantity_main * main_asset_price_per_reference_unit; - let output_synthetic_unwrapped = output_synthetic + let output_synthetic = quantity_main * main_asset_price / synthetic_asset_price; + output_synthetic .get() - .map_err(|_| Error::::PriceCalculationFailed)?; - Ok(output_synthetic_unwrapped) + .map_err(|_| Error::::PriceCalculationFailed.into()) } - // Sell some amount of XST for desired amount of XST(USD) + // Sell some amount of synthetic base asset (e.g. XST) for desired amount of synthetic asset (e.g. XSTUSD) QuoteAmount::WithDesiredOutput { desired_amount_out: quantity_synthetic, } => { - let output_main = quantity_synthetic / main_asset_price_per_reference_unit; + let output_main = quantity_synthetic * synthetic_asset_price / main_asset_price; output_main .get() .map_err(|_| Error::::PriceCalculationFailed.into()) From 7f0bfe6ff5ea5a4559b998a5d995a9ebe6c75baa Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Mon, 12 Dec 2022 16:35:50 +0300 Subject: [PATCH 11/72] Add `SyntheticInfo` struct Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index abac780d2a..f4671ef545 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -56,7 +56,7 @@ use common::{ }; use frame_support::traits::Get; use frame_support::weights::Weight; -use frame_support::{ensure, fail}; +use frame_support::{ensure, fail, RuntimeDebug}; use permissions::{Scope, BURN, MINT}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; @@ -119,6 +119,14 @@ impl DistributionAccountData { } } +#[derive(RuntimeDebug, Clone, Encode, Decode, scale_info::TypeInfo)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] +pub struct SyntheticInfo { + reference_symbol: Symbol, + buy_fee_percent: Fixed, + sell_fee_percent: Fixed, +} + #[frame_support::pallet] pub mod pallet { use super::*; @@ -211,7 +219,8 @@ pub mod pallet { let reference_symbol = EnabledSynthetics::::try_get(synthetic_asset) .map_err(|_| Error::::SyntheticIsNotEnabled)? - .expect("Synthetic tables always store `Some`"); + .expect("Synthetic tables always store `Some`") + .reference_symbol; EnabledSynthetics::::remove(synthetic_asset); EnabledSymbols::::remove(reference_symbol); @@ -289,7 +298,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn enabled_synthetics)] pub type EnabledSynthetics = - StorageMap<_, Blake2_128Concat, T::AssetId, Option, ValueQuery>; + StorageMap<_, Blake2_128Concat, T::AssetId, Option>, ValueQuery>; /// Reference symbols and their synthetic assets. /// @@ -382,7 +391,14 @@ impl Pallet { Self::register_synthetic_asset(synthetic_asset_id, asset_symbol, asset_name)?; Self::enable_synthetic_pair(synthetic_asset_id)?; - EnabledSynthetics::::insert(synthetic_asset_id, Some(reference_symbol.clone())); + EnabledSynthetics::::insert( + synthetic_asset_id, + Some(SyntheticInfo { + reference_symbol: reference_symbol.clone(), + buy_fee_percent: Fixed::ZERO, + sell_fee_percent: Fixed::ZERO, + }), + ); EnabledSymbols::::insert(reference_symbol.clone(), Some(synthetic_asset_id)); Self::deposit_event(Event::SyntheticAssetEnabled( @@ -400,6 +416,7 @@ impl Pallet { } fn generate_synthetic_asset_id(reference_symbol: &T::Symbol) -> T::AssetId { + // TODO: Maybe we don't need cryptographic hash here, but just a simple hash function. use blake2::{Blake2s256, Digest}; if *reference_symbol == "USD" { @@ -513,6 +530,8 @@ impl Pallet { /// Decompose SwapAmount into particular buy quotation query. /// + /// *Buy* means main asset buy (e.g., XST buy). + /// /// Returns ordered pair: (input_amount, output_amount, fee_amount). fn decide_buy_amounts( main_asset_id: &T::AssetId, @@ -569,6 +588,8 @@ impl Pallet { /// Decompose SwapAmount into particular sell quotation query. /// + /// *Sell* means main asset sell (e.g., XST sell). + /// /// Returns ordered pair: (input_amount, output_amount, fee_amount). fn decide_sell_amounts( main_asset_id: &T::AssetId, @@ -738,8 +759,9 @@ impl Pallet { }) } id => { - let symbol = - EnabledSynthetics::::get(id).ok_or(Error::::SyntheticDoesNotExist)?; + let symbol = EnabledSynthetics::::get(id) + .ok_or(Error::::SyntheticDoesNotExist)? + .reference_symbol; let price = balance!(T::Oracle::quote(symbol)?.ok_or(Error::::OracleQuoteError)?); // Just for convenience. Right now will always return 1. From 60acb346f9d90f482e62e1a382fbcb102f1cd930 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Mon, 12 Dec 2022 16:59:27 +0300 Subject: [PATCH 12/72] Add extrinsics to set fees Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 55 +++++++++++++++++++++++++++++++++++--- pallets/xst/src/weights.rs | 18 +++++++++++++ 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index f4671ef545..7332f06479 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -61,7 +61,7 @@ use permissions::{Scope, BURN, MINT}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; use sp_core::H256; -use sp_runtime::{DispatchError, DispatchResult}; +use sp_runtime::DispatchError; use sp_std::collections::btree_set::BTreeSet; use sp_std::vec::Vec; @@ -70,6 +70,8 @@ pub trait WeightInfo { fn set_reference_asset() -> Weight; fn enable_synthetic_asset() -> Weight; fn disable_synthetic_asset() -> Weight; + fn set_synthetic_asset_buy_fee() -> Weight; + fn set_synthetic_asset_sell_fee() -> Weight; } type Assets = assets::Pallet; @@ -167,6 +169,7 @@ pub mod pallet { #[pallet::without_storage_info] pub struct Pallet(PhantomData); + // TODO Remove #[pallet::hooks] impl Hooks> for Pallet { fn on_initialize(_block_number: T::BlockNumber) -> Weight { @@ -228,6 +231,52 @@ pub mod pallet { Self::deposit_event(Event::SyntheticAssetDisabled(synthetic_asset)); Ok(().into()) } + + /// Set synthetic asset buy fee. Default value is `0%`. + /// + /// This fee will be used to determine the amount of synthetic base asset (e.g. XST) to be + /// burned when user buys synthetic asset. + #[pallet::weight(::WeightInfo::set_synthetic_asset_buy_fee())] + pub fn set_synthetic_asset_buy_fee( + origin: OriginFor, + synthetic_asset: T::AssetId, + fee_percent: Fixed, + ) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + + EnabledSynthetics::::try_mutate(synthetic_asset, |option_info| -> DispatchResult { + let info = option_info + .as_mut() + .ok_or(Error::::SyntheticIsNotEnabled)?; + info.buy_fee_percent = fee_percent; + Ok(()) + })?; + + Ok(().into()) + } + + /// Set synthetic asset sell fee. Default value is `0%`. + /// + /// This fee will be used to determine the amount of synthetic base asset (e.g. XST) to be + /// burned when user sells synthetic asset. + #[pallet::weight(::WeightInfo::set_synthetic_asset_sell_fee())] + pub fn set_synthetic_asset_sell_fee( + origin: OriginFor, + synthetic_asset: T::AssetId, + fee_percent: Fixed, + ) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + + EnabledSynthetics::::try_mutate(synthetic_asset, |option_info| -> DispatchResult { + let info = option_info + .as_mut() + .ok_or(Error::::SyntheticIsNotEnabled)?; + info.sell_fee_percent = fee_percent; + Ok(()) + })?; + + Ok(().into()) + } } #[pallet::event] @@ -380,7 +429,7 @@ impl Pallet { asset_name: AssetName, reference_symbol: T::Symbol, transactional: bool, - ) -> DispatchResult { + ) -> sp_runtime::DispatchResult { let code = || { if EnabledSymbols::::contains_key(&reference_symbol) { return Err(Error::::SymbolAlreadyReferencedToSynthetic.into()); @@ -435,7 +484,7 @@ impl Pallet { h256.into() } - fn enable_synthetic_pair(synthetic_asset_id: T::AssetId) -> DispatchResult { + fn enable_synthetic_pair(synthetic_asset_id: T::AssetId) -> sp_runtime::DispatchResult { trading_pair::Pallet::::register_pair( DEXId::Polkaswap.into(), T::GetSyntheticBaseAssetId::get(), diff --git a/pallets/xst/src/weights.rs b/pallets/xst/src/weights.rs index a122dd7bea..9874262989 100644 --- a/pallets/xst/src/weights.rs +++ b/pallets/xst/src/weights.rs @@ -59,6 +59,18 @@ impl crate::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + fn set_synthetic_asset_buy_fee() -> Weight { + // TODO + (210_815_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn set_synthetic_asset_sell_fee() -> Weight { + // TODO + (210_815_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } impl crate::WeightInfo for () { @@ -74,4 +86,10 @@ impl crate::WeightInfo for () { fn disable_synthetic_asset() -> Weight { EXTRINSIC_FIXED_WEIGHT } + fn set_synthetic_asset_buy_fee() -> Weight { + EXTRINSIC_FIXED_WEIGHT + } + fn set_synthetic_asset_sell_fee() -> Weight { + EXTRINSIC_FIXED_WEIGHT + } } From 8bcd912a98fd35ee022122118f6fb49b904e3e2a Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Mon, 12 Dec 2022 19:01:53 +0300 Subject: [PATCH 13/72] Implement fees logic Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 163 ++++++++++++++++++++++++++++++++--------- 1 file changed, 127 insertions(+), 36 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 7332f06479..51ee5a0ea0 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -129,6 +129,12 @@ pub struct SyntheticInfo { sell_fee_percent: Fixed, } +#[derive(RuntimeDebug, Copy, Clone)] +enum QuoteType { + BaseAssetBuy, + BaseAssetSell, +} + #[frame_support::pallet] pub mod pallet { use super::*; @@ -323,6 +329,8 @@ pub mod pallet { SyntheticIsNotEnabled, /// Error quoting price from oracle. OracleQuoteError, + /// Failure while calculating an amount of synthetic base asset to burn. + FailedToCalculateBurnAmount, } // TODO: better by replaced with Get<> @@ -702,7 +710,7 @@ impl Pallet { /// If there's not enough reserves in the pool, `NotEnoughReserves` error will be returned. /// fn swap_mint_burn_assets( - _dex_id: &T::DEXId, + dex_id: &T::DEXId, input_asset_id: &T::AssetId, output_asset_id: &T::AssetId, swap_amount: SwapAmount, @@ -714,38 +722,34 @@ impl Pallet { let permissioned_account_id = Technical::::tech_account_id_to_account_id(&permissioned_tech_account_id)?; - let synthetic_base_asset_id = &T::GetSyntheticBaseAssetId::get(); - let (input_amount, output_amount, fee_amount) = - if input_asset_id == synthetic_base_asset_id { - Self::decide_sell_amounts( - &input_asset_id, - &output_asset_id, - swap_amount.into(), - true, - )? - } else { - Self::decide_buy_amounts( - &output_asset_id, - &input_asset_id, - swap_amount.into(), - true, - )? - }; + let swap_outcome = Self::quote( + dex_id, + input_asset_id, + output_asset_id, + swap_amount.into(), + true, + )?; - let result = match swap_amount { - SwapAmount::WithDesiredInput { min_amount_out, .. } => { + let (input_amount, output_amount) = match swap_amount { + SwapAmount::WithDesiredInput { + desired_amount_in, + min_amount_out, + } => { ensure!( - output_amount >= min_amount_out, + swap_outcome.amount >= min_amount_out, Error::::SlippageLimitExceeded ); - SwapOutcome::new(output_amount, fee_amount) + (desired_amount_in, swap_outcome.amount) } - SwapAmount::WithDesiredOutput { max_amount_in, .. } => { + SwapAmount::WithDesiredOutput { + desired_amount_out, + max_amount_in, + } => { ensure!( - input_amount <= max_amount_in, + swap_outcome.amount <= max_amount_in, Error::::SlippageLimitExceeded ); - SwapOutcome::new(input_amount, fee_amount) + (swap_outcome.amount, desired_amount_out) } }; @@ -763,7 +767,7 @@ impl Pallet { output_amount, )?; - Ok(result) + Ok(swap_outcome) }) } @@ -855,6 +859,36 @@ impl Pallet { None, ) } + + /// Decide how much of synthetic base asset should be holded depending on + /// set fee percent per every synthetic asset. + fn decide_base_asset_fee_amount( + synthetic_asset_id: &T::AssetId, + synthetic_base_asset_amount: Balance, + quote_type: QuoteType, + ) -> Result { + use QuoteType::*; + + let info = EnabledSynthetics::::get(synthetic_asset_id) + .ok_or(Error::::SyntheticDoesNotExist)?; + let fee_percent = match quote_type { + BaseAssetBuy => { + // Synthetic base asset buying == synthetic asset selling + info.sell_fee_percent + } + BaseAssetSell => { + // Synthetic base asset selling == synthetic asset buying + info.buy_fee_percent + } + }; + + let base_fee_amount = FixedWrapper::from(synthetic_base_asset_amount) + * FixedWrapper::from(fee_percent) + / FixedWrapper::from(100); + base_fee_amount + .try_into_balance() + .map_err(|_| Error::::FailedToCalculateBurnAmount.into()) + } } impl LiquiditySource @@ -887,16 +921,73 @@ impl LiquiditySource::CantExchange); } - let synthetic_base_asset_id = &T::GetSyntheticBaseAssetId::get(); - let (input_amount, output_amount, fee_amount) = if input_asset_id == synthetic_base_asset_id - { - Self::decide_sell_amounts(&input_asset_id, &output_asset_id, amount, deduce_fee)? - } else { - Self::decide_buy_amounts(&output_asset_id, &input_asset_id, amount, deduce_fee)? - }; - match amount { - QuoteAmount::WithDesiredInput { .. } => Ok(SwapOutcome::new(output_amount, fee_amount)), - QuoteAmount::WithDesiredOutput { .. } => Ok(SwapOutcome::new(input_amount, fee_amount)), + + let base_is_input = input_asset_id == &T::GetSyntheticBaseAssetId::get(); + match (base_is_input, amount) { + // Synthetic base selling + (true, QuoteAmount::WithDesiredInput { desired_amount_in }) => { + let base_fee_amount = Self::decide_base_asset_fee_amount( + &output_asset_id, + desired_amount_in, + QuoteType::BaseAssetSell, + )?; + let new_amount = amount.copy_direction(desired_amount_in - base_fee_amount); + let (_, output_amount, fee_amount) = Self::decide_sell_amounts( + &input_asset_id, + &output_asset_id, + new_amount, + deduce_fee, + )?; + Ok(SwapOutcome::new(output_amount, fee_amount)) + } + (true, QuoteAmount::WithDesiredOutput { .. }) => { + let (input_amount, _, fee_amount) = Self::decide_sell_amounts( + &input_asset_id, + &output_asset_id, + amount, + deduce_fee, + )?; + let base_fee_amount = Self::decide_base_asset_fee_amount( + &output_asset_id, + input_amount, + QuoteType::BaseAssetSell, + )?; + Ok(SwapOutcome::new(input_amount + base_fee_amount, fee_amount)) + } + + // Synthetic base buying + (false, QuoteAmount::WithDesiredInput { desired_amount_in }) => { + let base_fee_amount = Self::decide_base_asset_fee_amount( + &input_asset_id, + desired_amount_in, + QuoteType::BaseAssetBuy, + )?; + let (_, output_amount, fee_amount) = Self::decide_buy_amounts( + &input_asset_id, + &output_asset_id, + amount, + deduce_fee, + )?; + Ok(SwapOutcome::new( + output_amount - base_fee_amount, + fee_amount, + )) + } + (false, QuoteAmount::WithDesiredOutput { desired_amount_out }) => { + let base_fee_amount = Self::decide_base_asset_fee_amount( + &input_asset_id, + desired_amount_out, + QuoteType::BaseAssetBuy, + )?; + let new_amount = amount.copy_direction(desired_amount_out + base_fee_amount); + let (input_amount, _, fee_amount) = Self::decide_buy_amounts( + &input_asset_id, + &output_asset_id, + new_amount, + deduce_fee, + )?; + Ok(SwapOutcome::new(input_amount, fee_amount)) + } } } From dfe3f4c29c8fdb71643e81338da7c14729db8c9e Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Tue, 13 Dec 2022 16:12:58 +0300 Subject: [PATCH 14/72] Add fees into `enable_synthetic_asset()` extrinsic Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 51ee5a0ea0..57b4af9cf5 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -203,6 +203,8 @@ pub mod pallet { asset_symbol: AssetSymbol, asset_name: AssetName, reference_symbol: T::Symbol, + buy_fee_percent: Fixed, + sell_fee_percent: Fixed, ) -> DispatchResultWithPostInfo { ensure_root(origin)?; @@ -210,6 +212,8 @@ pub mod pallet { asset_symbol, asset_name, reference_symbol, + buy_fee_percent, + sell_fee_percent, true, )?; Ok(().into()) @@ -382,7 +386,7 @@ pub mod pallet { /// Asset that is used to compare collateral assets by value, e.g., DAI. pub reference_asset_id: T::AssetId, /// List of tokens enabled as collaterals initially. - pub initial_synthetic_assets: Vec<(AssetSymbol, AssetName, T::Symbol)>, + pub initial_synthetic_assets: Vec<(AssetSymbol, AssetName, T::Symbol, Fixed, Fixed)>, } #[cfg(feature = "std")] @@ -395,6 +399,8 @@ pub mod pallet { AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), "USD".into(), + Fixed::ZERO, + Fixed::ZERO, )] .into(), } @@ -407,11 +413,19 @@ pub mod pallet { PermissionedTechAccount::::put(&self.tech_account_id); ReferenceAssetId::::put(&self.reference_asset_id); self.initial_synthetic_assets.iter().cloned().for_each( - |(asset_symbol, asset_name, reference_symbol)| { + |( + asset_symbol, + asset_name, + reference_symbol, + buy_fee_percent, + sell_fee_percent, + )| { Pallet::::enable_synthetic_asset_unchecked( asset_symbol, asset_name, reference_symbol, + buy_fee_percent, + sell_fee_percent, false, ) .expect("Failed to initialize XST synthetics.") @@ -436,6 +450,8 @@ impl Pallet { asset_symbol: AssetSymbol, asset_name: AssetName, reference_symbol: T::Symbol, + buy_fee_percent: Fixed, + sell_fee_percent: Fixed, transactional: bool, ) -> sp_runtime::DispatchResult { let code = || { @@ -452,8 +468,8 @@ impl Pallet { synthetic_asset_id, Some(SyntheticInfo { reference_symbol: reference_symbol.clone(), - buy_fee_percent: Fixed::ZERO, - sell_fee_percent: Fixed::ZERO, + buy_fee_percent, + sell_fee_percent, }), ); EnabledSymbols::::insert(reference_symbol.clone(), Some(synthetic_asset_id)); From 1dad40e6e376317df7fe019d853d8f3c43f08ec2 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Tue, 13 Dec 2022 16:16:14 +0300 Subject: [PATCH 15/72] Remove some useless code Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 19 ++----------------- pallets/xst/src/weights.rs | 11 ----------- 2 files changed, 2 insertions(+), 28 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 57b4af9cf5..ee796155f1 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -46,8 +46,8 @@ use assets::AssetIdOf; use codec::{Decode, Encode}; use common::fixnum::ops::Zero as _; use common::prelude::{ - Balance, EnsureDEXManager, EnsureTradingPairExists, Fixed, FixedWrapper, PriceToolsPallet, - QuoteAmount, SwapAmount, SwapOutcome, DEFAULT_BALANCE_PRECISION, + Balance, EnsureDEXManager, Fixed, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapAmount, + SwapOutcome, DEFAULT_BALANCE_PRECISION, }; use common::{ balance, fixed, fixed_wrapper, AssetName, AssetSymbol, DEXId, DataFeed, GetMarketInfo, @@ -66,7 +66,6 @@ use sp_std::collections::btree_set::BTreeSet; use sp_std::vec::Vec; pub trait WeightInfo { - fn on_initialize(_elems: u32) -> Weight; fn set_reference_asset() -> Weight; fn enable_synthetic_asset() -> Weight; fn disable_synthetic_asset() -> Weight; @@ -149,12 +148,6 @@ pub mod pallet { type GetSyntheticBaseAssetId: Get; type LiquidityProxy: LiquidityProxyTrait; type EnsureDEXManager: EnsureDEXManager; - // TODO Remove - type EnsureTradingPairExists: EnsureTradingPairExists< - Self::DEXId, - Self::AssetId, - DispatchError, - >; type PriceToolsPallet: PriceToolsPallet; type Oracle: DataFeed; /// Type of symbol received from oracles @@ -175,14 +168,6 @@ pub mod pallet { #[pallet::without_storage_info] pub struct Pallet(PhantomData); - // TODO Remove - #[pallet::hooks] - impl Hooks> for Pallet { - fn on_initialize(_block_number: T::BlockNumber) -> Weight { - ::WeightInfo::on_initialize(0) - } - } - #[pallet::call] impl Pallet { /// Change reference asset which is used to determine collateral assets value. Intended to be e.g., stablecoin DAI. diff --git a/pallets/xst/src/weights.rs b/pallets/xst/src/weights.rs index 9874262989..eea0810d46 100644 --- a/pallets/xst/src/weights.rs +++ b/pallets/xst/src/weights.rs @@ -35,14 +35,6 @@ use sp_std::marker::PhantomData; pub struct WeightInfo(PhantomData); impl crate::WeightInfo for WeightInfo { - fn on_initialize(n: u32) -> Weight { - (261_343_886 as Weight) - .saturating_add((3_457_545_517 as Weight).saturating_mul(n as Weight)) - .saturating_add(T::DbWeight::get().reads(16 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(n as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn set_reference_asset() -> Weight { (210_815_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) @@ -74,9 +66,6 @@ impl crate::WeightInfo for WeightInfo { } impl crate::WeightInfo for () { - fn on_initialize(_elems: u32) -> Weight { - EXTRINSIC_FIXED_WEIGHT - } fn set_reference_asset() -> Weight { EXTRINSIC_FIXED_WEIGHT } From 0a7c8fc74ef3bea3d77aaf2cd801ead9147a39a4 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Tue, 13 Dec 2022 16:44:40 +0300 Subject: [PATCH 16/72] Update Config usage in mock and runtime Signed-off-by: Daniil Polyakov --- Cargo.lock | 1 + pallets/band/src/lib.rs | 13 +++++++++++++ pallets/xst/Cargo.toml | 1 + pallets/xst/src/mock.rs | 10 +++++++++- runtime/src/lib.rs | 3 ++- 5 files changed, 26 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bd9735fcf5..03925df155 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13489,6 +13489,7 @@ name = "xst" version = "1.0.1" dependencies = [ "assets", + "band", "blake2 0.10.5", "ceres-liquidity-locker", "common", diff --git a/pallets/band/src/lib.rs b/pallets/band/src/lib.rs index ebe158a3b2..334b552dd2 100644 --- a/pallets/band/src/lib.rs +++ b/pallets/band/src/lib.rs @@ -30,6 +30,7 @@ #![cfg_attr(not(feature = "std"), no_std)] +use common::DataFeed; use frame_support::pallet_prelude::*; use frame_support::weights::Weight; use frame_system::pallet_prelude::*; @@ -317,3 +318,15 @@ impl, I: 'static> Pallet { .ok_or_else(|| Error::::UnauthorizedRelayer.into()) } } + +impl, I: 'static> DataFeed for Pallet { + fn quote(symbol: T::Symbol) -> Result, DispatchError> { + Ok(SymbolRates::::get(symbol).map(|rate| rate.value)) + } + + fn list_enabled_symbols() -> Result, DispatchError> { + Ok(SymbolRates::::iter() + .filter_map(|(symbol, option_rate)| option_rate.map(|rate| (symbol, rate.last_updated))) + .collect()) + } +} diff --git a/pallets/xst/Cargo.toml b/pallets/xst/Cargo.toml index 214509c917..3e015aadb2 100644 --- a/pallets/xst/Cargo.toml +++ b/pallets/xst/Cargo.toml @@ -53,6 +53,7 @@ dex-manager = { path = "../dex-manager" } mock-liquidity-source = { path = "../mock-liquidity-source" } technical = { path = "../technical" } trading-pair = { path = "../trading-pair" } +band = { path = "../band" } [features] default = ['std'] diff --git a/pallets/xst/src/mock.rs b/pallets/xst/src/mock.rs index 0a9c5f698d..02b78bdc4c 100644 --- a/pallets/xst/src/mock.rs +++ b/pallets/xst/src/mock.rs @@ -124,6 +124,7 @@ construct_runtime! { XSTPool: xstpool::{Pallet, Call, Storage, Event}, PswapDistribution: pswap_distribution::{Pallet, Call, Storage, Event}, DEXApi: dex_api::{Pallet, Storage}, + Band: band::{Pallet, Call, Storage, Event}, CeresLiquidityLocker: ceres_liquidity_locker::{Pallet, Call, Storage, Event}, DemeterFarmingPlatform: demeter_farming_platform::{Pallet, Call, Storage, Event}, } @@ -174,9 +175,16 @@ impl Config for Runtime { type Event = Event; type GetSyntheticBaseAssetId = GetSyntheticBaseAssetId; type LiquidityProxy = MockDEXApi; - type EnsureTradingPairExists = trading_pair::Pallet; type EnsureDEXManager = dex_manager::Pallet; type PriceToolsPallet = MockDEXApi; + type Oracle = band::Pallet; // TODO: Replace with oracle-proxy + type Symbol = ::Symbol; + type WeightInfo = (); +} + +impl band::Config for Runtime { + type Event = Event; + type Symbol = String; type WeightInfo = (); } diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index ab9bfd7e8e..c516690e64 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1671,9 +1671,10 @@ impl xst::Config for Runtime { type GetSyntheticBaseAssetId = GetXstPoolConversionAssetId; type LiquidityProxy = LiquidityProxy; type EnsureDEXManager = DEXManager; - type EnsureTradingPairExists = TradingPair; type PriceToolsPallet = PriceTools; type WeightInfo = xst::weights::WeightInfo; + type Oracle = band::Pallet; // TODO: Replace with oracle-proxy + type Symbol = ::Symbol; } parameter_types! { From 0c85af8bc7cf05febf84be55e113cdd1538cf5e6 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Wed, 14 Dec 2022 16:05:35 +0300 Subject: [PATCH 17/72] Some fixes to make it all compile Signed-off-by: Daniil Polyakov --- node/chain_spec/src/lib.rs | 10 +++- pallets/xst/src/lib.rs | 11 ++-- pallets/xst/src/mock.rs | 47 +++++++-------- pallets/xst/src/tests.rs | 113 +++++++++++++++++++------------------ 4 files changed, 99 insertions(+), 82 deletions(-) diff --git a/node/chain_spec/src/lib.rs b/node/chain_spec/src/lib.rs index c034c17bc0..f0256dd8a5 100644 --- a/node/chain_spec/src/lib.rs +++ b/node/chain_spec/src/lib.rs @@ -1440,6 +1440,8 @@ fn mainnet_genesis( council_accounts: Vec, technical_committee_accounts: Vec, ) -> GenesisConfig { + use common::fixnum::ops::Zero as _; + // Minimum stake for an active validator let initial_staking = balance!(0.2); // XOR amount which already exists on Ethereum @@ -2014,7 +2016,13 @@ fn mainnet_genesis( xst_pool: XSTPoolConfig { tech_account_id: xst_pool_permissioned_tech_account_id, // TODO: move to defaults reference_asset_id: DAI, - initial_synthetic_assets: vec![XSTUSD], + initial_synthetic_assets: vec![( + AssetSymbol(b"XSTUSD".to_vec()), + AssetName(b"SORA Synthetic USD".to_vec()), + "USD".into(), + Fixed::ZERO, + Fixed::ZERO, + )], }, beefy: BeefyConfig { authorities: vec![], diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index ee796155f1..2beb03c98c 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -146,6 +146,7 @@ pub mod pallet { type Event: From> + IsType<::Event>; /// AssetId which is convertible to/from XSTUSD type GetSyntheticBaseAssetId: Get; + // TODO: Remove type LiquidityProxy: LiquidityProxyTrait; type EnsureDEXManager: EnsureDEXManager; type PriceToolsPallet: PriceToolsPallet; @@ -397,6 +398,10 @@ pub mod pallet { fn build(&self) { PermissionedTechAccount::::put(&self.tech_account_id); ReferenceAssetId::::put(&self.reference_asset_id); + + technical::Pallet::::register_tech_account_id(self.tech_account_id.clone()) + .expect("Failed to register technical account"); + self.initial_synthetic_assets.iter().cloned().for_each( |( asset_symbol, @@ -923,9 +928,8 @@ impl LiquiditySource::CantExchange); } - let base_is_input = input_asset_id == &T::GetSyntheticBaseAssetId::get(); - match (base_is_input, amount) { - // Synthetic base selling + let base_selling = input_asset_id == &T::GetSyntheticBaseAssetId::get(); + match (base_selling, amount) { (true, QuoteAmount::WithDesiredInput { desired_amount_in }) => { let base_fee_amount = Self::decide_base_asset_fee_amount( &output_asset_id, @@ -956,7 +960,6 @@ impl LiquiditySource { let base_fee_amount = Self::decide_base_asset_fee_amount( &input_asset_id, diff --git a/pallets/xst/src/mock.rs b/pallets/xst/src/mock.rs index 02b78bdc4c..3c5464e5ed 100644 --- a/pallets/xst/src/mock.rs +++ b/pallets/xst/src/mock.rs @@ -35,7 +35,7 @@ use common::prelude::{ }; use common::{ self, balance, fixed, fixed_wrapper, hash, Amount, AssetId32, AssetName, AssetSymbol, DEXInfo, - Fixed, LiquidityProxyTrait, LiquiditySourceFilter, LiquiditySourceType, TechPurpose, + Fixed, LiquidityProxyTrait, LiquiditySourceFilter, LiquiditySourceType, TechPurpose, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, XSTUSD, }; use currencies::BasicCurrencyAdapter; @@ -76,9 +76,6 @@ pub fn assets_owner() -> AccountId { } pub const DEX_A_ID: DEXId = DEXId::Polkaswap; -pub const DAI: AssetId = common::AssetId32::from_bytes(hex!( - "0200060000000000000000000000000000000000000000000000000000000111" -)); parameter_types! { pub const BlockHashCount: u64 = 250; @@ -548,10 +545,11 @@ impl LiquidityProxyTrait for MockDEXApi { pub struct ExtBuilder { endowed_accounts: Vec<(AccountId, AssetId, Balance, AssetSymbol, AssetName, u8)>, + endowed_accounts_with_synthetics: + Vec<(AccountId, AssetId, Balance, AssetSymbol, AssetName, u8)>, dex_list: Vec<(DEXId, DEXInfo)>, initial_permission_owners: Vec<(u32, Scope, Vec)>, initial_permissions: Vec<(AccountId, Scope, Vec)>, - reference_asset_id: AssetId, } impl Default for ExtBuilder { @@ -598,15 +596,15 @@ impl Default for ExtBuilder { AssetName(b"Sora Synthetics".to_vec()), DEFAULT_BALANCE_PRECISION, ), - ( - alice(), - XSTUSD, - balance!(100000), - AssetSymbol(b"XSTUSD".to_vec()), - AssetName(b"SORA Synthetic USD".to_vec()), - DEFAULT_BALANCE_PRECISION, - ), ], + endowed_accounts_with_synthetics: vec![( + alice(), + XSTUSD, + balance!(100000), + AssetSymbol(b"XSTUSD".to_vec()), + AssetName(b"SORA Synthetic USD".to_vec()), + DEFAULT_BALANCE_PRECISION, + )], dex_list: vec![( DEX_A_ID, DEXInfo { @@ -628,7 +626,6 @@ impl Default for ExtBuilder { vec![permissions::MINT, permissions::BURN], ), ], - reference_asset_id: DAI, } } } @@ -657,9 +654,18 @@ impl PriceToolsPallet for MockDEXApi { impl ExtBuilder { pub fn new( endowed_accounts: Vec<(AccountId, AssetId, Balance, AssetSymbol, AssetName, u8)>, + endowed_accounts_with_synthetics: Vec<( + AccountId, + AssetId, + Balance, + AssetSymbol, + AssetName, + u8, + )>, ) -> Self { Self { endowed_accounts, + endowed_accounts_with_synthetics, ..Default::default() } } @@ -687,14 +693,6 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); - crate::GenesisConfig:: { - tech_account_id: Default::default(), - reference_asset_id: self.reference_asset_id, - initial_synthetic_assets: Default::default(), - } - .assimilate_storage(&mut t) - .unwrap(); - dex_manager::GenesisConfig:: { dex_list: self.dex_list, } @@ -731,10 +729,15 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); + crate::GenesisConfig::::default() + .assimilate_storage(&mut t) + .unwrap(); + tokens::GenesisConfig:: { balances: self .endowed_accounts .into_iter() + .chain(self.endowed_accounts_with_synthetics.into_iter()) .map(|(account_id, asset_id, balance, ..)| (account_id, asset_id, balance)) .collect(), } diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index 8561a8691f..429a2f1f50 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -31,7 +31,7 @@ #[rustfmt::skip] mod tests { use crate::{Error, Pallet, mock::*}; - use common::{self, AssetName, AssetSymbol, DEXId, FromGenericPair, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, balance, fixed, prelude::{Balance, SwapAmount, QuoteAmount,}}; + use common::{self, AssetName, AssetSymbol, DEXId, FromGenericPair, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, prelude::{Balance, SwapAmount, QuoteAmount,}}; use frame_support::assert_ok; use frame_support::assert_noop; use sp_arithmetic::traits::{Zero}; @@ -57,8 +57,6 @@ use frame_support::assert_noop; MockDEXApi::init().unwrap(); let _ = xst_pool_init().unwrap(); let alice = &alice(); - TradingPair::register(Origin::signed(alice.clone()), DEXId::Polkaswap.into(), XST, XSTUSD).expect("Failed to register trading pair."); - XSTPool::initialize_pool_unchecked(XSTUSD, false).expect("Failed to initialize pool."); // base case for buy assert_eq!( @@ -103,8 +101,6 @@ use frame_support::assert_noop; let _ = xst_pool_init().unwrap(); let alice = alice(); - TradingPair::register(Origin::signed(alice.clone()), DEXId::Polkaswap.into(), XST, XSTUSD).expect("Failed to register trading pair."); - XSTPool::initialize_pool_unchecked(XSTUSD, false).expect("Failed to initialize pool."); // add some reserves XSTPool::exchange(&alice, &alice, &DEXId::Polkaswap, &XSTUSD, &XST, SwapAmount::with_desired_input(balance!(1), 0)).expect("Failed to buy XST."); @@ -178,19 +174,20 @@ use frame_support::assert_noop; #[test] fn should_set_new_reference_token() { - let mut ext = ExtBuilder::new(vec![ - (alice(), DAI, balance!(0), AssetSymbol(b"DAI".to_vec()), AssetName(b"DAI".to_vec()), 18), - (alice(), USDT, balance!(0), AssetSymbol(b"USDT".to_vec()), AssetName(b"Tether USD".to_vec()), 18), - (alice(), XOR, balance!(1), AssetSymbol(b"XOR".to_vec()), AssetName(b"SORA".to_vec()), 18), - (alice(), VAL, balance!(0), AssetSymbol(b"VAL".to_vec()), AssetName(b"SORA Validator Token".to_vec()), 18), - (alice(), XST, balance!(0), AssetSymbol(b"XST".to_vec()), AssetName(b"SORA Synthetics".to_vec()), 18), - (alice(), XSTUSD, balance!(0), AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), 18), - ]) - .build(); + let mut ext = ExtBuilder::new( + vec![ + (alice(), DAI, balance!(0), AssetSymbol(b"DAI".to_vec()), AssetName(b"DAI".to_vec()), 18), + (alice(), USDT, balance!(0), AssetSymbol(b"USDT".to_vec()), AssetName(b"Tether USD".to_vec()), 18), + (alice(), XOR, balance!(1), AssetSymbol(b"XOR".to_vec()), AssetName(b"SORA".to_vec()), 18), + (alice(), VAL, balance!(0), AssetSymbol(b"VAL".to_vec()), AssetName(b"SORA Validator Token".to_vec()), 18), + (alice(), XST, balance!(0), AssetSymbol(b"XST".to_vec()), AssetName(b"SORA Synthetics".to_vec()), 18), + ], + vec![ + (alice(), XSTUSD, balance!(0), AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), 18), + ] + ).build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); - TradingPair::register(Origin::signed(alice()), DEXId::Polkaswap.into(), XST, XSTUSD).expect("Failed to register trading pair."); - XSTPool::initialize_pool_unchecked(XSTUSD, false).expect("Failed to initialize pool."); let price_a = XSTPool::quote( &DEXId::Polkaswap.into(), @@ -218,20 +215,22 @@ use frame_support::assert_noop; #[test] fn similar_returns_should_be_identical() { - let mut ext = ExtBuilder::new(vec![ - (alice(), DAI, balance!(0), AssetSymbol(b"DAI".to_vec()), AssetName(b"DAI".to_vec()), 18), - (alice(), USDT, balance!(0), AssetSymbol(b"USDT".to_vec()), AssetName(b"Tether USD".to_vec()), 18), - (alice(), XOR, balance!(0), AssetSymbol(b"XOR".to_vec()), AssetName(b"SORA".to_vec()), 18), - (alice(), VAL, balance!(4000), AssetSymbol(b"VAL".to_vec()), AssetName(b"SORA Validator Token".to_vec()), 18), - (alice(), XST, balance!(0), AssetSymbol(b"XST".to_vec()), AssetName(b"SORA Synthetics".to_vec()), 18), - (alice(), XSTUSD, balance!(50000), AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), 18), - ]) + let mut ext = ExtBuilder::new( + vec![ + (alice(), DAI, balance!(0), AssetSymbol(b"DAI".to_vec()), AssetName(b"DAI".to_vec()), 18), + (alice(), USDT, balance!(0), AssetSymbol(b"USDT".to_vec()), AssetName(b"Tether USD".to_vec()), 18), + (alice(), XOR, balance!(0), AssetSymbol(b"XOR".to_vec()), AssetName(b"SORA".to_vec()), 18), + (alice(), VAL, balance!(4000), AssetSymbol(b"VAL".to_vec()), AssetName(b"SORA Validator Token".to_vec()), 18), + (alice(), XST, balance!(0), AssetSymbol(b"XST".to_vec()), AssetName(b"SORA Synthetics".to_vec()), 18), + ], + vec![ + (alice(), XSTUSD, balance!(50000), AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), 18), + ] + ) .build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); let _ = xst_pool_init().unwrap(); - TradingPair::register(Origin::signed(alice()), DEXId::Polkaswap.into(), XST, XSTUSD).expect("Failed to register trading pair."); - XSTPool::initialize_pool_unchecked(XSTUSD, false).expect("Failed to initialize pool."); // Buy with desired input let amount_a: Balance = balance!(2000); @@ -346,18 +345,20 @@ use frame_support::assert_noop; #[test] fn test_deducing_fee() { - let mut ext = ExtBuilder::new(vec![ - (alice(), DAI, balance!(0), AssetSymbol(b"DAI".to_vec()), AssetName(b"DAI".to_vec()), 18), - (alice(), XOR, balance!(0), AssetSymbol(b"XOR".to_vec()), AssetName(b"SORA".to_vec()), 18), - (alice(), XST, balance!(0), AssetSymbol(b"XST".to_vec()), AssetName(b"SORA Synthetics".to_vec()), 18), - (alice(), XSTUSD, balance!(2000), AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), 18), - ]) - .build(); + let mut ext = ExtBuilder::new( + vec![ + (alice(), DAI, balance!(0), AssetSymbol(b"DAI".to_vec()), AssetName(b"DAI".to_vec()), 18), + (alice(), XOR, balance!(0), AssetSymbol(b"XOR".to_vec()), AssetName(b"SORA".to_vec()), 18), + (alice(), XST, balance!(0), AssetSymbol(b"XST".to_vec()), AssetName(b"SORA Synthetics".to_vec()), 18), + ], + vec![ + (alice(), XSTUSD, balance!(2000), AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), 18), + ] + ) + .build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); let _ = xst_pool_init().unwrap(); - TradingPair::register(Origin::signed(alice()), DEXId::Polkaswap.into(), XST, XSTUSD).expect("Failed to register trading pair."); - XSTPool::initialize_pool_unchecked(XSTUSD, false).expect("Failed to initialize pool."); let price_a = XSTPool::quote( &DEXId::Polkaswap.into(), @@ -367,6 +368,8 @@ use frame_support::assert_noop; true, ) .unwrap(); + // 100 XSTUSD will cost 100 DAI + // 100 DAI will cost 0,5467468562 assert_eq!(price_a.fee, balance!(0.003667003083916557)); assert_eq!(price_a.amount, balance!(0.546934060567218204)); @@ -408,19 +411,20 @@ use frame_support::assert_noop; #[test] fn fees_for_equivalent_trades_should_match() { let mut ext = ExtBuilder::new(vec![ - (alice(), DAI, balance!(0), AssetSymbol(b"DAI".to_vec()), AssetName(b"DAI".to_vec()), 18), - (alice(), USDT, balance!(0), AssetSymbol(b"USDT".to_vec()), AssetName(b"Tether USD".to_vec()), 18), - (alice(), XOR, balance!(0), AssetSymbol(b"XOR".to_vec()), AssetName(b"SORA".to_vec()), 18), - (alice(), VAL, balance!(2000), AssetSymbol(b"VAL".to_vec()), AssetName(b"SORA Validator Token".to_vec()), 18), - (alice(), XST, balance!(0), AssetSymbol(b"XST".to_vec()), AssetName(b"SORA Synthetics".to_vec()), 18), - (alice(), XSTUSD, balance!(2000), AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), 18), - ]) + (alice(), DAI, balance!(0), AssetSymbol(b"DAI".to_vec()), AssetName(b"DAI".to_vec()), 18), + (alice(), USDT, balance!(0), AssetSymbol(b"USDT".to_vec()), AssetName(b"Tether USD".to_vec()), 18), + (alice(), XOR, balance!(0), AssetSymbol(b"XOR".to_vec()), AssetName(b"SORA".to_vec()), 18), + (alice(), VAL, balance!(2000), AssetSymbol(b"VAL".to_vec()), AssetName(b"SORA Validator Token".to_vec()), 18), + (alice(), XST, balance!(0), AssetSymbol(b"XST".to_vec()), AssetName(b"SORA Synthetics".to_vec()), 18), + ], + vec![ + (alice(), XSTUSD, balance!(2000), AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), 18), + ] + ) .build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); let _ = xst_pool_init().unwrap(); - TradingPair::register(Origin::signed(alice()),DEXId::Polkaswap.into(), XST, XSTUSD).expect("Failed to register trading pair."); - XSTPool::initialize_pool_unchecked(XSTUSD, false).expect("Failed to initialize pool."); XSTPool::exchange( &alice(), @@ -477,19 +481,20 @@ use frame_support::assert_noop; #[test] fn price_without_impact() { let mut ext = ExtBuilder::new(vec![ - (alice(), DAI, balance!(0), AssetSymbol(b"DAI".to_vec()), AssetName(b"DAI".to_vec()), 18), - (alice(), USDT, balance!(0), AssetSymbol(b"USDT".to_vec()), AssetName(b"Tether USD".to_vec()), 18), - (alice(), XOR, balance!(0), AssetSymbol(b"XOR".to_vec()), AssetName(b"SORA".to_vec()), 18), - (alice(), VAL, balance!(0), AssetSymbol(b"VAL".to_vec()), AssetName(b"SORA Validator Token".to_vec()), 18), - (alice(), XST, balance!(0), AssetSymbol(b"XST".to_vec()), AssetName(b"SORA Synthetics".to_vec()), 18), - (alice(), XSTUSD, 0, AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), 18), - ]) + (alice(), DAI, balance!(0), AssetSymbol(b"DAI".to_vec()), AssetName(b"DAI".to_vec()), 18), + (alice(), USDT, balance!(0), AssetSymbol(b"USDT".to_vec()), AssetName(b"Tether USD".to_vec()), 18), + (alice(), XOR, balance!(0), AssetSymbol(b"XOR".to_vec()), AssetName(b"SORA".to_vec()), 18), + (alice(), VAL, balance!(0), AssetSymbol(b"VAL".to_vec()), AssetName(b"SORA Validator Token".to_vec()), 18), + (alice(), XST, balance!(0), AssetSymbol(b"XST".to_vec()), AssetName(b"SORA Synthetics".to_vec()), 18), + ], + vec![ + (alice(), XSTUSD, 0, AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), 18), + ] + ) .build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); let _ = xst_pool_init().unwrap(); - TradingPair::register(Origin::signed(alice()),DEXId::Polkaswap.into(), XST, XSTUSD).expect("Failed to register trading pair."); - XSTPool::initialize_pool_unchecked(XSTUSD, false).expect("Failed to initialize pool."); // Buy with desired input let amount_a: Balance = balance!(200); @@ -581,8 +586,6 @@ use frame_support::assert_noop; let _ = xst_pool_init().unwrap(); let alice = alice(); - TradingPair::register(Origin::signed(alice.clone()), DEXId::Polkaswap.into(), XST, XSTUSD).expect("Failed to register trading pair."); - XSTPool::initialize_pool_unchecked(XSTUSD, false).expect("Failed to initialize pool."); // add some reserves assert_noop!(XSTPool::exchange(&alice, &alice, &DEXId::Polkaswap, &XSTUSD, &DAI, SwapAmount::with_desired_input(balance!(1), 0)), Error::::CantExchange); }); From 2e47d6b78160e1071364b381bab5d90402b1bce2 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Wed, 14 Dec 2022 16:35:01 +0300 Subject: [PATCH 18/72] Revert "Implement fees logic" This reverts commit 8bcd912a98fd35ee022122118f6fb49b904e3e2a. Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 161 +++++++++-------------------------------- 1 file changed, 36 insertions(+), 125 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 2beb03c98c..96112db3f9 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -128,12 +128,6 @@ pub struct SyntheticInfo { sell_fee_percent: Fixed, } -#[derive(RuntimeDebug, Copy, Clone)] -enum QuoteType { - BaseAssetBuy, - BaseAssetSell, -} - #[frame_support::pallet] pub mod pallet { use super::*; @@ -319,8 +313,6 @@ pub mod pallet { SyntheticIsNotEnabled, /// Error quoting price from oracle. OracleQuoteError, - /// Failure while calculating an amount of synthetic base asset to burn. - FailedToCalculateBurnAmount, } // TODO: better by replaced with Get<> @@ -716,7 +708,7 @@ impl Pallet { /// If there's not enough reserves in the pool, `NotEnoughReserves` error will be returned. /// fn swap_mint_burn_assets( - dex_id: &T::DEXId, + _dex_id: &T::DEXId, input_asset_id: &T::AssetId, output_asset_id: &T::AssetId, swap_amount: SwapAmount, @@ -728,34 +720,38 @@ impl Pallet { let permissioned_account_id = Technical::::tech_account_id_to_account_id(&permissioned_tech_account_id)?; - let swap_outcome = Self::quote( - dex_id, - input_asset_id, - output_asset_id, - swap_amount.into(), - true, - )?; + let synthetic_base_asset_id = &T::GetSyntheticBaseAssetId::get(); + let (input_amount, output_amount, fee_amount) = + if input_asset_id == synthetic_base_asset_id { + Self::decide_sell_amounts( + &input_asset_id, + &output_asset_id, + swap_amount.into(), + true, + )? + } else { + Self::decide_buy_amounts( + &output_asset_id, + &input_asset_id, + swap_amount.into(), + true, + )? + }; - let (input_amount, output_amount) = match swap_amount { - SwapAmount::WithDesiredInput { - desired_amount_in, - min_amount_out, - } => { + let result = match swap_amount { + SwapAmount::WithDesiredInput { min_amount_out, .. } => { ensure!( - swap_outcome.amount >= min_amount_out, + output_amount >= min_amount_out, Error::::SlippageLimitExceeded ); - (desired_amount_in, swap_outcome.amount) + SwapOutcome::new(output_amount, fee_amount) } - SwapAmount::WithDesiredOutput { - desired_amount_out, - max_amount_in, - } => { + SwapAmount::WithDesiredOutput { max_amount_in, .. } => { ensure!( - swap_outcome.amount <= max_amount_in, + input_amount <= max_amount_in, Error::::SlippageLimitExceeded ); - (swap_outcome.amount, desired_amount_out) + SwapOutcome::new(input_amount, fee_amount) } }; @@ -773,7 +769,7 @@ impl Pallet { output_amount, )?; - Ok(swap_outcome) + Ok(result) }) } @@ -865,36 +861,6 @@ impl Pallet { None, ) } - - /// Decide how much of synthetic base asset should be holded depending on - /// set fee percent per every synthetic asset. - fn decide_base_asset_fee_amount( - synthetic_asset_id: &T::AssetId, - synthetic_base_asset_amount: Balance, - quote_type: QuoteType, - ) -> Result { - use QuoteType::*; - - let info = EnabledSynthetics::::get(synthetic_asset_id) - .ok_or(Error::::SyntheticDoesNotExist)?; - let fee_percent = match quote_type { - BaseAssetBuy => { - // Synthetic base asset buying == synthetic asset selling - info.sell_fee_percent - } - BaseAssetSell => { - // Synthetic base asset selling == synthetic asset buying - info.buy_fee_percent - } - }; - - let base_fee_amount = FixedWrapper::from(synthetic_base_asset_amount) - * FixedWrapper::from(fee_percent) - / FixedWrapper::from(100); - base_fee_amount - .try_into_balance() - .map_err(|_| Error::::FailedToCalculateBurnAmount.into()) - } } impl LiquiditySource @@ -927,71 +893,16 @@ impl LiquiditySource::CantExchange); } - - let base_selling = input_asset_id == &T::GetSyntheticBaseAssetId::get(); - match (base_selling, amount) { - (true, QuoteAmount::WithDesiredInput { desired_amount_in }) => { - let base_fee_amount = Self::decide_base_asset_fee_amount( - &output_asset_id, - desired_amount_in, - QuoteType::BaseAssetSell, - )?; - let new_amount = amount.copy_direction(desired_amount_in - base_fee_amount); - let (_, output_amount, fee_amount) = Self::decide_sell_amounts( - &input_asset_id, - &output_asset_id, - new_amount, - deduce_fee, - )?; - Ok(SwapOutcome::new(output_amount, fee_amount)) - } - (true, QuoteAmount::WithDesiredOutput { .. }) => { - let (input_amount, _, fee_amount) = Self::decide_sell_amounts( - &input_asset_id, - &output_asset_id, - amount, - deduce_fee, - )?; - let base_fee_amount = Self::decide_base_asset_fee_amount( - &output_asset_id, - input_amount, - QuoteType::BaseAssetSell, - )?; - Ok(SwapOutcome::new(input_amount + base_fee_amount, fee_amount)) - } - - (false, QuoteAmount::WithDesiredInput { desired_amount_in }) => { - let base_fee_amount = Self::decide_base_asset_fee_amount( - &input_asset_id, - desired_amount_in, - QuoteType::BaseAssetBuy, - )?; - let (_, output_amount, fee_amount) = Self::decide_buy_amounts( - &input_asset_id, - &output_asset_id, - amount, - deduce_fee, - )?; - Ok(SwapOutcome::new( - output_amount - base_fee_amount, - fee_amount, - )) - } - (false, QuoteAmount::WithDesiredOutput { desired_amount_out }) => { - let base_fee_amount = Self::decide_base_asset_fee_amount( - &input_asset_id, - desired_amount_out, - QuoteType::BaseAssetBuy, - )?; - let new_amount = amount.copy_direction(desired_amount_out + base_fee_amount); - let (input_amount, _, fee_amount) = Self::decide_buy_amounts( - &input_asset_id, - &output_asset_id, - new_amount, - deduce_fee, - )?; - Ok(SwapOutcome::new(input_amount, fee_amount)) - } + let synthetic_base_asset_id = &T::GetSyntheticBaseAssetId::get(); + let (input_amount, output_amount, fee_amount) = if input_asset_id == synthetic_base_asset_id + { + Self::decide_sell_amounts(&input_asset_id, &output_asset_id, amount, deduce_fee)? + } else { + Self::decide_buy_amounts(&output_asset_id, &input_asset_id, amount, deduce_fee)? + }; + match amount { + QuoteAmount::WithDesiredInput { .. } => Ok(SwapOutcome::new(output_amount, fee_amount)), + QuoteAmount::WithDesiredOutput { .. } => Ok(SwapOutcome::new(input_amount, fee_amount)), } } From 6ec0ae44f08a296d685eaf11f237ba1845920475 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Wed, 14 Dec 2022 17:55:18 +0300 Subject: [PATCH 19/72] Make one fee instead of buy and sell fees Signed-off-by: Daniil Polyakov --- node/chain_spec/src/lib.rs | 3 +- pallets/xst/src/lib.rs | 107 ++++++++++++------------------------- pallets/xst/src/weights.rs | 13 +---- 3 files changed, 38 insertions(+), 85 deletions(-) diff --git a/node/chain_spec/src/lib.rs b/node/chain_spec/src/lib.rs index f0256dd8a5..dc54b07614 100644 --- a/node/chain_spec/src/lib.rs +++ b/node/chain_spec/src/lib.rs @@ -2020,8 +2020,7 @@ fn mainnet_genesis( AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), "USD".into(), - Fixed::ZERO, - Fixed::ZERO, + fixed!(0.00666), )], }, beefy: BeefyConfig { diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 96112db3f9..9f09aec4a9 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -69,8 +69,7 @@ pub trait WeightInfo { fn set_reference_asset() -> Weight; fn enable_synthetic_asset() -> Weight; fn disable_synthetic_asset() -> Weight; - fn set_synthetic_asset_buy_fee() -> Weight; - fn set_synthetic_asset_sell_fee() -> Weight; + fn set_synthetic_asset_fee() -> Weight; } type Assets = assets::Pallet; @@ -124,8 +123,8 @@ impl DistributionAccountData { #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] pub struct SyntheticInfo { reference_symbol: Symbol, - buy_fee_percent: Fixed, - sell_fee_percent: Fixed, + /// Fee ratio. 1 = 100% + fee_ratio: Fixed, } #[frame_support::pallet] @@ -183,8 +182,7 @@ pub mod pallet { asset_symbol: AssetSymbol, asset_name: AssetName, reference_symbol: T::Symbol, - buy_fee_percent: Fixed, - sell_fee_percent: Fixed, + fee_ratio: Fixed, ) -> DispatchResultWithPostInfo { ensure_root(origin)?; @@ -192,8 +190,7 @@ pub mod pallet { asset_symbol, asset_name, reference_symbol, - buy_fee_percent, - sell_fee_percent, + fee_ratio, true, )?; Ok(().into()) @@ -222,15 +219,15 @@ pub mod pallet { Ok(().into()) } - /// Set synthetic asset buy fee. Default value is `0%`. + /// Set synthetic asset fee. /// /// This fee will be used to determine the amount of synthetic base asset (e.g. XST) to be /// burned when user buys synthetic asset. - #[pallet::weight(::WeightInfo::set_synthetic_asset_buy_fee())] - pub fn set_synthetic_asset_buy_fee( + #[pallet::weight(::WeightInfo::set_synthetic_asset_fee())] + pub fn set_synthetic_asset_fee( origin: OriginFor, synthetic_asset: T::AssetId, - fee_percent: Fixed, + fee_ratio: Fixed, ) -> DispatchResultWithPostInfo { ensure_root(origin)?; @@ -238,30 +235,7 @@ pub mod pallet { let info = option_info .as_mut() .ok_or(Error::::SyntheticIsNotEnabled)?; - info.buy_fee_percent = fee_percent; - Ok(()) - })?; - - Ok(().into()) - } - - /// Set synthetic asset sell fee. Default value is `0%`. - /// - /// This fee will be used to determine the amount of synthetic base asset (e.g. XST) to be - /// burned when user sells synthetic asset. - #[pallet::weight(::WeightInfo::set_synthetic_asset_sell_fee())] - pub fn set_synthetic_asset_sell_fee( - origin: OriginFor, - synthetic_asset: T::AssetId, - fee_percent: Fixed, - ) -> DispatchResultWithPostInfo { - ensure_root(origin)?; - - EnabledSynthetics::::try_mutate(synthetic_asset, |option_info| -> DispatchResult { - let info = option_info - .as_mut() - .ok_or(Error::::SyntheticIsNotEnabled)?; - info.sell_fee_percent = fee_percent; + info.fee_ratio = fee_ratio; Ok(()) })?; @@ -321,16 +295,6 @@ pub mod pallet { #[pallet::getter(fn permissioned_tech_account)] pub type PermissionedTechAccount = StorageValue<_, T::TechAccountId, ValueQuery>; - #[pallet::type_value] - pub(super) fn DefaultForBaseFee() -> Fixed { - fixed!(0.00666) - } - - /// Base fee in XOR which is deducted on all trades, currently it's burned: 0.3%. - #[pallet::storage] - #[pallet::getter(fn base_fee)] - pub(super) type BaseFee = StorageValue<_, Fixed, ValueQuery, DefaultForBaseFee>; - /// Synthetic assets and their reference symbols. /// /// It's a programmer responsibility to keep this collection consistent with [`EnabledSymbols`]. @@ -364,7 +328,7 @@ pub mod pallet { /// Asset that is used to compare collateral assets by value, e.g., DAI. pub reference_asset_id: T::AssetId, /// List of tokens enabled as collaterals initially. - pub initial_synthetic_assets: Vec<(AssetSymbol, AssetName, T::Symbol, Fixed, Fixed)>, + pub initial_synthetic_assets: Vec<(AssetSymbol, AssetName, T::Symbol, Fixed)>, } #[cfg(feature = "std")] @@ -377,8 +341,7 @@ pub mod pallet { AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), "USD".into(), - Fixed::ZERO, - Fixed::ZERO, + fixed!(0.00666), )] .into(), } @@ -395,19 +358,12 @@ pub mod pallet { .expect("Failed to register technical account"); self.initial_synthetic_assets.iter().cloned().for_each( - |( - asset_symbol, - asset_name, - reference_symbol, - buy_fee_percent, - sell_fee_percent, - )| { + |(asset_symbol, asset_name, reference_symbol, fee_ratio)| { Pallet::::enable_synthetic_asset_unchecked( asset_symbol, asset_name, reference_symbol, - buy_fee_percent, - sell_fee_percent, + fee_ratio, false, ) .expect("Failed to initialize XST synthetics.") @@ -432,8 +388,7 @@ impl Pallet { asset_symbol: AssetSymbol, asset_name: AssetName, reference_symbol: T::Symbol, - buy_fee_percent: Fixed, - sell_fee_percent: Fixed, + fee_ratio: Fixed, transactional: bool, ) -> sp_runtime::DispatchResult { let code = || { @@ -450,8 +405,7 @@ impl Pallet { synthetic_asset_id, Some(SyntheticInfo { reference_symbol: reference_symbol.clone(), - buy_fee_percent, - sell_fee_percent, + fee_ratio, }), ); EnabledSymbols::::insert(reference_symbol.clone(), Some(synthetic_asset_id)); @@ -594,6 +548,12 @@ impl Pallet { amount: QuoteAmount, deduce_fee: bool, ) -> Result<(Balance, Balance, Balance), DispatchError> { + let fee_ratio = FixedWrapper::from( + EnabledSynthetics::::get(synthetic_asset_id) + .ok_or(Error::::SyntheticDoesNotExist)? + .fee_ratio, + ); + Ok(match amount { QuoteAmount::WithDesiredInput { desired_amount_in } => { let mut output_amount: Balance = FixedWrapper::from(Self::buy_price( @@ -604,7 +564,7 @@ impl Pallet { .try_into_balance() .map_err(|_| Error::::PriceCalculationFailed)?; if deduce_fee { - let fee_amount = (FixedWrapper::from(BaseFee::::get()) * output_amount) + let fee_amount = (fee_ratio * output_amount) .try_into_balance() .map_err(|_| Error::::PriceCalculationFailed)?; output_amount = output_amount.saturating_sub(fee_amount); @@ -616,10 +576,9 @@ impl Pallet { QuoteAmount::WithDesiredOutput { desired_amount_out } => { let desired_amount_out_with_fee = if deduce_fee { - (FixedWrapper::from(desired_amount_out) - / (fixed_wrapper!(1) - BaseFee::::get())) - .try_into_balance() - .map_err(|_| Error::::PriceCalculationFailed)? + (FixedWrapper::from(desired_amount_out) / (fixed_wrapper!(1) - fee_ratio)) + .try_into_balance() + .map_err(|_| Error::::PriceCalculationFailed)? } else { desired_amount_out }; @@ -648,14 +607,19 @@ impl Pallet { /// Returns ordered pair: (input_amount, output_amount, fee_amount). fn decide_sell_amounts( main_asset_id: &T::AssetId, - collateral_asset_id: &T::AssetId, + synthetic_asset_id: &T::AssetId, amount: QuoteAmount, deduce_fee: bool, ) -> Result<(Balance, Balance, Balance), DispatchError> { + let fee_ratio = FixedWrapper::from( + EnabledSynthetics::::get(synthetic_asset_id) + .ok_or(Error::::SyntheticDoesNotExist)? + .fee_ratio, + ); + Ok(match amount { QuoteAmount::WithDesiredInput { desired_amount_in } => { let fee_amount = if deduce_fee { - let fee_ratio = FixedWrapper::from(BaseFee::::get()); (fee_ratio * FixedWrapper::from(desired_amount_in)) .try_into_balance() .map_err(|_| Error::::PriceCalculationFailed)? @@ -664,7 +628,7 @@ impl Pallet { }; let output_amount = Self::sell_price( main_asset_id, - collateral_asset_id, + synthetic_asset_id, QuoteAmount::with_desired_input( desired_amount_in.saturating_sub(fee_amount.clone()), ), @@ -678,13 +642,12 @@ impl Pallet { QuoteAmount::WithDesiredOutput { desired_amount_out } => { let input_amount: Balance = FixedWrapper::from(Self::sell_price( main_asset_id, - collateral_asset_id, + synthetic_asset_id, QuoteAmount::with_desired_output(desired_amount_out), )?) .try_into_balance() .map_err(|_| Error::::PriceCalculationFailed)?; if deduce_fee { - let fee_ratio = FixedWrapper::from(BaseFee::::get()); let input_amount_with_fee = FixedWrapper::from(input_amount) / (fixed_wrapper!(1) - fee_ratio); let input_amount_with_fee = input_amount_with_fee diff --git a/pallets/xst/src/weights.rs b/pallets/xst/src/weights.rs index eea0810d46..0c8731b026 100644 --- a/pallets/xst/src/weights.rs +++ b/pallets/xst/src/weights.rs @@ -51,13 +51,7 @@ impl crate::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } - fn set_synthetic_asset_buy_fee() -> Weight { - // TODO - (210_815_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn set_synthetic_asset_sell_fee() -> Weight { + fn set_synthetic_asset_fee() -> Weight { // TODO (210_815_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) @@ -75,10 +69,7 @@ impl crate::WeightInfo for () { fn disable_synthetic_asset() -> Weight { EXTRINSIC_FIXED_WEIGHT } - fn set_synthetic_asset_buy_fee() -> Weight { - EXTRINSIC_FIXED_WEIGHT - } - fn set_synthetic_asset_sell_fee() -> Weight { + fn set_synthetic_asset_fee() -> Weight { EXTRINSIC_FIXED_WEIGHT } } From a9f5db1985e6bd483a3cc516a461582410818482 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Thu, 15 Dec 2022 13:23:20 +0300 Subject: [PATCH 20/72] Fix calculation in `reference_price()` Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 9f09aec4a9..dedceacb9f 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -780,13 +780,15 @@ impl Pallet { let symbol = EnabledSynthetics::::get(id) .ok_or(Error::::SyntheticDoesNotExist)? .reference_symbol; - let price = - balance!(T::Oracle::quote(symbol)?.ok_or(Error::::OracleQuoteError)?); + let price = FixedWrapper::from(balance!( + T::Oracle::quote(symbol)?.ok_or(Error::::OracleQuoteError)? + )); // Just for convenience. Right now will always return 1. - let reference_asset_price = Self::reference_price(&reference_asset_id)?; - Ok(price - .checked_div(reference_asset_price) - .expect("Reference asset price is never 0.")) + let reference_asset_price = + FixedWrapper::from(Self::reference_price(&reference_asset_id)?); + (price / reference_asset_price) + .try_into_balance() + .map_err(|_| Error::::PriceCalculationFailed.into()) } } } From a46da94fa63a34840228b9bff41f22a725ad985b Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Thu, 15 Dec 2022 13:23:42 +0300 Subject: [PATCH 21/72] Add tests for new extrinsics Signed-off-by: Daniil Polyakov --- pallets/xst/src/tests.rs | 99 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index 429a2f1f50..fd9c135fa2 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -579,7 +579,7 @@ use frame_support::assert_noop; } #[test] - fn exchange_synthesic_to_any_token_disallowed() { + fn exchange_synthetic_to_any_token_disallowed() { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); @@ -591,4 +591,101 @@ use frame_support::assert_noop; }); } + #[test] + fn enable_and_disable_synthetic_should_work() { + let mut ext = ExtBuilder::default().build(); + ext.execute_with(|| { + MockDEXApi::init().unwrap(); + let _ = xst_pool_init().unwrap(); + + let euro = "EURO".to_owned(); + let alice = alice(); + + Band::add_relayers(Origin::root(), vec![alice.clone()]) + .expect("Failed to add relayers"); + Band::relay(Origin::signed(alice.clone()), vec![(euro.clone(), 1)], 0, 0) + .expect("Failed to relay"); + + XSTPool::enable_synthetic_asset( + Origin::root(), + AssetSymbol(b"XSTEURO".to_vec()), + AssetName(b"Sora Synthetic Euro".to_vec()), + euro.clone(), + fixed!(0), + ).expect("Failed to enable synthetic asset"); + + let opt_xsteuro = XSTPool::enabled_symbols(&euro); + assert!(opt_xsteuro.is_some()); + + let xsteuro = opt_xsteuro.unwrap(); + assert_eq!( + XSTPool::enabled_synthetics(&xsteuro).expect("Failed to get synthetic asset").reference_symbol, + euro + ); + + XSTPool::disable_synthetic_asset(Origin::root(), xsteuro.clone()) + .expect("Failed to disable synthetic asset"); + + assert!(XSTPool::enabled_synthetics(&xsteuro).is_none()); + assert!(XSTPool::enabled_symbols(&euro).is_none()); + }); + } + + #[test] + fn set_synthetic_fee_should_work() { + let mut ext = ExtBuilder::default().build(); + ext.execute_with(|| { + MockDEXApi::init().unwrap(); + let _ = xst_pool_init().unwrap(); + + let euro = "EURO".to_owned(); + let alice = alice(); + + Band::add_relayers(Origin::root(), vec![alice.clone()]) + .expect("Failed to add relayers"); + Band::relay(Origin::signed(alice.clone()), vec![(euro.clone(), 1)], 0, 0) + .expect("Failed to relay"); + + XSTPool::enable_synthetic_asset( + Origin::root(), + AssetSymbol(b"XSTEURO".to_vec()), + AssetName(b"Sora Synthetic Euro".to_vec()), + euro.clone(), + fixed!(0), + ).expect("Failed to enable synthetic asset"); + + let xsteuro = XSTPool::enabled_symbols(&euro).expect("Expected synthetic asset"); + let quote_amount = QuoteAmount::with_desired_input(balance!(100)); + + let swap_outcome_before = XSTPool::quote( + &DEXId::Polkaswap, + &XST.into(), + &xsteuro, + quote_amount.clone(), + true + ) + .expect("Failed to quote XST -> XSTEURO "); + assert_eq!(swap_outcome_before.fee, 0); + + + assert_ok!(XSTPool::set_synthetic_asset_fee( + Origin::root(), + xsteuro.clone(), + fixed!(0.5)) + ); + + + let swap_outcome_after = XSTPool::quote( + &DEXId::Polkaswap, + &XST.into(), + &xsteuro, + quote_amount, + true + ) + .expect("Failed to quote XST -> XSTEURO"); + + assert_eq!(swap_outcome_after.amount, swap_outcome_before.amount / 2); + assert_eq!(swap_outcome_after.fee, quote_amount.amount() / 2); + }); + } } From 7ad8bc35ecc7f30ce8bb9c9284f9dca3516516ec Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Fri, 16 Dec 2022 17:24:43 +0300 Subject: [PATCH 22/72] Partly fix benchmarks Signed-off-by: Daniil Polyakov --- node/chain_spec/src/lib.rs | 43 +++----------------- pallets/band/src/benchmarking.rs | 1 + pallets/xst/src/benchmarking.rs | 67 +++++++++++++++++++++++--------- pallets/xst/src/lib.rs | 20 ++++++---- 4 files changed, 69 insertions(+), 62 deletions(-) diff --git a/node/chain_spec/src/lib.rs b/node/chain_spec/src/lib.rs index dc54b07614..fb8fbec2c7 100644 --- a/node/chain_spec/src/lib.rs +++ b/node/chain_spec/src/lib.rs @@ -923,7 +923,6 @@ fn testnet_genesis( }; let initial_collateral_assets = vec![DAI.into(), VAL.into(), PSWAP.into(), ETH.into(), XST.into()]; - let initial_synthetic_assets = vec![XSTUSD.into()]; GenesisConfig { system: SystemConfig { code: WASM_BINARY.unwrap_or_default().to_vec(), @@ -1057,17 +1056,6 @@ fn testnet_genesis( None, None, ), - ( - XSTUSD.into(), - assets_and_permissions_account_id.clone(), - AssetSymbol(b"XSTUSD".to_vec()), - AssetName(b"SORA Synthetic USD".to_vec()), - DEFAULT_BALANCE_PRECISION, - Balance::zero(), - true, - None, - None, - ), ( common::AssetId32::from_bytes(hex!( "008bcfd2387d3fc453333557eecb0efe59fcba128769b2feefdd306e98e66440" @@ -1186,12 +1174,6 @@ fn testnet_genesis( .iter() .cloned() .map(|target_asset_id| create_trading_pair(XOR, target_asset_id)) - .chain( - initial_synthetic_assets - .iter() - .cloned() - .map(|target_asset_id| create_trading_pair(XST, target_asset_id)), - ) .collect(), }, dexapi: DEXAPIConfig { @@ -1278,7 +1260,12 @@ fn testnet_genesis( xst_pool: XSTPoolConfig { tech_account_id: xst_pool_permissioned_tech_account_id, // TODO: move to defaults reference_asset_id: DAI, - initial_synthetic_assets: vec![XSTUSD], + initial_synthetic_assets: vec![( + AssetSymbol(b"XSTUSD".to_vec()), + AssetName(b"SORA Synthetic USD".to_vec()), + "USD".into(), + fixed!(0.00666), + )], }, beefy: BeefyConfig { authorities: vec![], @@ -1607,7 +1594,6 @@ fn mainnet_genesis( umi_nfts: Vec::new(), }; let initial_collateral_assets = vec![DAI.into(), VAL.into(), PSWAP.into(), ETH.into()]; - let initial_synthetic_assets = vec![XSTUSD.into()]; let mut bridge_assets = vec![ AssetConfig::Sidechain { id: XOR.into(), @@ -1684,17 +1670,6 @@ fn mainnet_genesis( None, None, ), - ( - XSTUSD.into(), - assets_and_permissions_account_id.clone(), - AssetSymbol(b"XSTUSD".to_vec()), - AssetName(b"SORA Synthetic USD".to_vec()), - DEFAULT_BALANCE_PRECISION, - Balance::zero(), - true, - None, - None, - ), ( common::AssetId32::from_bytes(hex!( "008bcfd2387d3fc453333557eecb0efe59fcba128769b2feefdd306e98e66440" @@ -1947,12 +1922,6 @@ fn mainnet_genesis( .iter() .cloned() .map(|target_asset_id| create_trading_pair(XOR.into(), target_asset_id)) - .chain( - initial_synthetic_assets - .iter() - .cloned() - .map(|target_asset_id| create_trading_pair(XST.into(), target_asset_id)), - ) .collect(), }, dexapi: DEXAPIConfig { diff --git a/pallets/band/src/benchmarking.rs b/pallets/band/src/benchmarking.rs index c5337b7310..8990111e83 100644 --- a/pallets/band/src/benchmarking.rs +++ b/pallets/band/src/benchmarking.rs @@ -38,6 +38,7 @@ use crate::Pallet as Band; use frame_benchmarking::benchmarks; use frame_system::RawOrigin; use hex_literal::hex; +#[cfg(no_std)] use sp_std::prelude::*; fn relayer() -> T::AccountId { diff --git a/pallets/xst/src/benchmarking.rs b/pallets/xst/src/benchmarking.rs index 728a867ed7..0d3bcb3d39 100644 --- a/pallets/xst/src/benchmarking.rs +++ b/pallets/xst/src/benchmarking.rs @@ -34,21 +34,12 @@ use super::*; -use codec::Decode; -use common::{DAI, XST}; +use crate::Pallet as XSTPool; +use common::{fixed, DAI}; use frame_benchmarking::benchmarks; use frame_system::{EventRecord, RawOrigin}; -use hex_literal::hex; use sp_std::prelude::*; -// Support Functions -fn alice() -> T::AccountId { - let bytes = hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"); - let account = T::AccountId::decode(&mut &bytes[..]).expect("Failed to decode account ID"); - frame_system::Pallet::::inc_providers(&account); - account -} - fn assert_last_event(generic_event: ::Event) { let events = frame_system::Pallet::::events(); let system_event: ::Event = generic_event.into(); @@ -67,17 +58,57 @@ benchmarks! { assert_last_event::(Event::ReferenceAssetChanged(DAI.into()).into()) } - enable_synthetic_asset{ + enable_synthetic_asset { + let reference_symbol = "EURO"; }: _( - Origin::root(), + RawOrigin::Root, AssetSymbol(b"XSTEURO".to_vec()), - AssetName(b"Sora Synthetic Euro".to_vec()), - "EURO".to_owned(), - fixed!(0), + AssetName(b"Sora Synthetic EURO".to_vec()), + reference_symbol.into(), + fixed!(0) + ) + verify { + assert!(XSTPool::::enabled_symbols(T::Symbol::from(reference_symbol)).is_some()); + } + + disable_synthetic_asset { + let reference_symbol = "EURO"; + XSTPool::::enable_synthetic_asset( + RawOrigin::Root.into(), + AssetSymbol(b"XSTEURO".to_vec()), + AssetName(b"Sora Synthetic EURO".to_vec()), + reference_symbol.into(), + fixed!(0), + )?; + let asset_id = XSTPool::::enabled_symbols(T::Symbol::from(reference_symbol)) + .expect("Expected enabled synthetic"); + }: _( + RawOrigin::Root, + asset_id + ) + verify { + assert_last_event::(Event::SyntheticAssetDisabled(asset_id).into()) + } + + set_synthetic_asset_fee { + let reference_symbol = "EURO"; + XSTPool::::enable_synthetic_asset( + RawOrigin::Root.into(), + AssetSymbol(b"XSTEURO".to_vec()), + AssetName(b"Sora Synthetic EURO".to_vec()), + reference_symbol.into(), + fixed!(0), + )?; + let asset_id = XSTPool::::enabled_symbols(T::Symbol::from(reference_symbol)) + .expect("Expected enabled synthetic"); + let fee_ratio = fixed!(0.06); + }: _( + RawOrigin::Root, + asset_id.clone(), + fee_ratio ) verify { - let event = frame_system::Pallet::::events().pop().expect("Expected event"); - assert!(matches!(event.event, Event::SyntheticAssetEnabled(..))); + assert_last_event::(Event::SyntheticAssetFeeChanged(asset_id, fee_ratio).into()) } set_synthetic_base_asset_floor_price { diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index a3ecc4326e..3688c73ea5 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -232,14 +232,18 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { ensure_root(origin)?; - EnabledSynthetics::::try_mutate(synthetic_asset, |option_info| -> DispatchResult { - let info = option_info - .as_mut() - .ok_or(Error::::SyntheticIsNotEnabled)?; - info.fee_ratio = fee_ratio; - Ok(()) - })?; + EnabledSynthetics::::try_mutate( + &synthetic_asset, + |option_info| -> DispatchResult { + let info = option_info + .as_mut() + .ok_or(Error::::SyntheticIsNotEnabled)?; + info.fee_ratio = fee_ratio; + Ok(()) + }, + )?; + Self::deposit_event(Event::SyntheticAssetFeeChanged(synthetic_asset, fee_ratio)); Ok(().into()) } @@ -268,6 +272,8 @@ pub mod pallet { SyntheticAssetEnabled(AssetIdOf, T::Symbol), /// Synthetic asset has been disabled. [Synthetic Asset Id] SyntheticAssetDisabled(AssetIdOf), + /// Synthetic asset fee has been changed. [Synthetic Asset Id, New Fee] + SyntheticAssetFeeChanged(AssetIdOf, Fixed), /// Floor price of the synthetic base asset has been changed. [New Floor Price] SyntheticBaseAssetFloorPriceChanged(Balance), } From 1acec10cba4b74615fde0bf9ea5a9dbdd70fa1d1 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Fri, 16 Dec 2022 18:15:19 +0300 Subject: [PATCH 23/72] Move `xst` pallet benchmarks to a separate crate Signed-off-by: Daniil Polyakov --- Cargo.lock | 25 +- pallets/xst/Cargo.toml | 8 - pallets/xst/benchmarking/Cargo.toml | 49 ++ .../src/lib.rs} | 13 +- pallets/xst/benchmarking/src/mock.rs | 757 ++++++++++++++++++ pallets/xst/src/lib.rs | 2 - runtime/Cargo.toml | 3 +- runtime/src/lib.rs | 7 +- 8 files changed, 843 insertions(+), 21 deletions(-) create mode 100644 pallets/xst/benchmarking/Cargo.toml rename pallets/xst/{src/benchmarking.rs => benchmarking/src/lib.rs} (93%) create mode 100644 pallets/xst/benchmarking/src/mock.rs diff --git a/Cargo.lock b/Cargo.lock index 03925df155..afee6bc9c8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4008,6 +4008,7 @@ dependencies = [ "vested-rewards-runtime-api", "xor-fee", "xst", + "xst-benchmarking", ] [[package]] @@ -13496,7 +13497,6 @@ dependencies = [ "demeter-farming-platform", "dex-api", "dex-manager", - "frame-benchmarking", "frame-support", "frame-system", "hex-literal", @@ -13515,13 +13515,34 @@ dependencies = [ "serde", "sp-arithmetic", "sp-core", - "sp-io", "sp-runtime", "sp-std", "technical", "trading-pair", ] +[[package]] +name = "xst-benchmarking" +version = "0.1.0" +dependencies = [ + "band", + "common", + "dex-manager", + "frame-benchmarking", + "frame-support", + "frame-system", + "hex-literal", + "mock-liquidity-source", + "orml-currencies", + "permissions", + "sp-core", + "sp-runtime", + "sp-std", + "technical", + "trading-pair", + "xst", +] + [[package]] name = "yamux" version = "0.10.2" diff --git a/pallets/xst/Cargo.toml b/pallets/xst/Cargo.toml index d3b2a6d896..fe3b73816a 100644 --- a/pallets/xst/Cargo.toml +++ b/pallets/xst/Cargo.toml @@ -18,7 +18,6 @@ scale-info = { version = "2", default-features = false, features = ["derive"] } currencies = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-currencies", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } -frame-benchmarking = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false, optional = true } hex-literal = { version = "0.3.1" } orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-traits", default-features = false } serde = { version = "1.0.101", default-features = false, optional = true, features = [ @@ -47,8 +46,6 @@ demeter-farming-platform = { path = "../demeter-farming-platform" } hex-literal = "0.3.1" pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25" } sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25" } -sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25" } -common = { path = "../../common", features = ["test"] } dex-manager = { path = "../dex-manager" } mock-liquidity-source = { path = "../mock-liquidity-source" } technical = { path = "../technical" } @@ -82,8 +79,3 @@ std = [ 'common/std', 'blake2/std' ] -runtime-benchmarks = [ - "frame-benchmarking", - "frame-system/runtime-benchmarks", - "frame-support/runtime-benchmarks", -] diff --git a/pallets/xst/benchmarking/Cargo.toml b/pallets/xst/benchmarking/Cargo.toml new file mode 100644 index 0000000000..ff44655c4c --- /dev/null +++ b/pallets/xst/benchmarking/Cargo.toml @@ -0,0 +1,49 @@ +[package] +edition = "2021" +name = "xst-benchmarking" +version = "0.1.0" +authors = ["Polka Biome Ltd. "] +license = "BSD-4-Clause" +homepage = "https://sora.org" +repository = "https://github.com/sora-xor/sora2-network" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +currencies = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-currencies", default-features = false } +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +frame-benchmarking = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +hex-literal = { version = "0.3.1" } +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +common = { path = "../../../common", default-features = false } +permissions = { path = "../../permissions", default-features = false } +dex-manager = { path = "../../dex-manager", default-features = false } +mock-liquidity-source = { path = "../../mock-liquidity-source", default-features = false } +technical = { path = "../../technical", default-features = false } +trading-pair = { path = "../../trading-pair", default-features = false } +band = { path = "../../band", default-features = false } +xst = {path = "../../xst", default-features = false } + +[features] +default = ["std"] +std = [ + "currencies/std", + "frame-support/std", + "frame-system/std", + "frame-benchmarking/std", + "sp-core/std", + "sp-runtime/std", + "sp-std/std", + "common/std", + "permissions/std", + "dex-manager/std", + "mock-liquidity-source/std", + "technical/std", + "trading-pair/std", + "band/std", + "xst/std", +] diff --git a/pallets/xst/src/benchmarking.rs b/pallets/xst/benchmarking/src/lib.rs similarity index 93% rename from pallets/xst/src/benchmarking.rs rename to pallets/xst/benchmarking/src/lib.rs index 0d3bcb3d39..30d38bc22d 100644 --- a/pallets/xst/src/benchmarking.rs +++ b/pallets/xst/benchmarking/src/lib.rs @@ -30,17 +30,15 @@ //! XST pool module benchmarking. -#![cfg(feature = "runtime-benchmarks")] +#![cfg_attr(not(feature = "std"), no_std)] -use super::*; - -use crate::Pallet as XSTPool; -use common::{fixed, DAI}; +use common::{balance, fixed, AssetName, AssetSymbol, DAI}; use frame_benchmarking::benchmarks; use frame_system::{EventRecord, RawOrigin}; use sp_std::prelude::*; +use xst::{Call, Event, Pallet as XSTPool}; -fn assert_last_event(generic_event: ::Event) { +fn assert_last_event(generic_event: ::Event) { let events = frame_system::Pallet::::events(); let system_event: ::Event = generic_event.into(); // compare to the last event record @@ -48,6 +46,9 @@ fn assert_last_event(generic_event: ::Event) { assert_eq!(event, &system_event); } +pub struct Pallet(xst::Pallet); +pub trait Config: xst::Config {} + benchmarks! { set_reference_asset { }: _( diff --git a/pallets/xst/benchmarking/src/mock.rs b/pallets/xst/benchmarking/src/mock.rs new file mode 100644 index 0000000000..82c714768f --- /dev/null +++ b/pallets/xst/benchmarking/src/mock.rs @@ -0,0 +1,757 @@ +// This file is part of the SORA network and Polkaswap app. + +// Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved. +// SPDX-License-Identifier: BSD-4-Clause + +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: + +// Redistributions of source code must retain the above copyright notice, this list +// of conditions and the following disclaimer. +// Redistributions in binary form must reproduce the above copyright notice, this +// list of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// All advertising materials mentioning features or use of this software must display +// the following acknowledgement: This product includes software developed by Polka Biome +// Ltd., SORA, and Polkaswap. +// +// Neither the name of the Polka Biome Ltd. nor the names of its contributors may be used +// to endorse or promote products derived from this software without specific prior written permission. + +// THIS SOFTWARE IS PROVIDED BY Polka Biome Ltd. AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, +// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Polka Biome Ltd. BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +use crate::{self as xstpool, Config}; +use common::mock::ExistentialDeposits; +use common::prelude::{ + Balance, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapAmount, SwapOutcome, +}; +use common::{ + self, balance, fixed, fixed_wrapper, hash, Amount, AssetId32, AssetName, AssetSymbol, DEXInfo, + Fixed, LiquidityProxyTrait, LiquiditySourceFilter, LiquiditySourceType, TechPurpose, DAI, + DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, XSTUSD, +}; +use currencies::BasicCurrencyAdapter; +use frame_support::traits::{Everything, GenesisBuild}; +use frame_support::weights::Weight; +use frame_support::{construct_runtime, parameter_types}; +use frame_system::pallet_prelude::BlockNumberFor; +use hex_literal::hex; +use permissions::{Scope, INIT_DEX, MANAGE_DEX}; +use sp_core::crypto::AccountId32; +use sp_core::H256; +use sp_runtime::testing::Header; +use sp_runtime::traits::{BlakeTwo256, IdentityLookup, Zero}; +use sp_runtime::{DispatchError, DispatchResult, Perbill, Percent}; +use std::collections::HashMap; + +pub type AccountId = AccountId32; +pub type BlockNumber = u64; +pub type TechAccountId = common::TechAccountId; +type TechAssetId = common::TechAssetId; +pub type ReservesAccount = + mock_liquidity_source::ReservesAcc; +pub type AssetId = AssetId32; +type DEXId = common::DEXId; +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +pub fn alice() -> AccountId { + AccountId32::from([1u8; 32]) +} + +pub fn bob() -> AccountId { + AccountId32::from([2u8; 32]) +} + +pub fn assets_owner() -> AccountId { + AccountId32::from([3u8; 32]) +} + +pub const DEX_A_ID: DEXId = DEXId::Polkaswap; + +parameter_types! { + pub const BlockHashCount: u64 = 250; + pub const MaximumBlockWeight: Weight = 1024; + pub const MaximumBlockLength: u32 = 2 * 1024; + pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); + pub const GetDefaultFee: u16 = 30; + pub const GetDefaultProtocolFee: u16 = 0; + pub const GetBaseAssetId: AssetId = XOR; + pub const GetSyntheticBaseAssetId: AssetId = XST; + pub const ExistentialDeposit: u128 = 0; + pub const TransferFee: u128 = 0; + pub const CreationFee: u128 = 0; + pub const TransactionByteFee: u128 = 1; + pub const GetNumSamples: usize = 40; + pub GetIncentiveAssetId: AssetId = common::AssetId32::from_bytes(hex!("0200050000000000000000000000000000000000000000000000000000000000").into()); + pub GetPswapDistributionAccountId: AccountId = AccountId32::from([151; 32]); + pub const GetDefaultSubscriptionFrequency: BlockNumber = 10; + pub const GetBurnUpdateFrequency: BlockNumber = 14400; + pub GetParliamentAccountId: AccountId = AccountId32::from([152; 32]); + pub GetXykFee: Fixed = fixed!(0.003); + pub const MinimumPeriod: u64 = 5; +} + +construct_runtime! { + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, + DexManager: dex_manager::{Pallet, Call, Storage}, + TradingPair: trading_pair::{Pallet, Call, Storage, Event}, + MockLiquiditySource: mock_liquidity_source::::{Pallet, Call, Config, Storage}, + Tokens: tokens::{Pallet, Call, Config, Storage, Event}, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, + Currencies: currencies::{Pallet, Call, Storage}, + Assets: assets::{Pallet, Call, Config, Storage, Event}, + Permissions: permissions::{Pallet, Call, Config, Storage, Event}, + Technical: technical::{Pallet, Call, Storage, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Event}, + PoolXYK: pool_xyk::{Pallet, Call, Storage, Event}, + XSTPool: xstpool::{Pallet, Call, Storage, Event}, + PswapDistribution: pswap_distribution::{Pallet, Call, Storage, Event}, + DEXApi: dex_api::{Pallet, Storage}, + Band: band::{Pallet, Call, Storage, Event}, + CeresLiquidityLocker: ceres_liquidity_locker::{Pallet, Call, Storage, Event}, + DemeterFarmingPlatform: demeter_farming_platform::{Pallet, Call, Storage, Event}, + } +} + +impl frame_system::Config for Runtime { + type BaseCallFilter = Everything; + type BlockWeights = (); + type BlockLength = (); + type Origin = Origin; + type Call = Call; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + type DbWeight = (); + type Version = (); + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type PalletInfo = PalletInfo; + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<65536>; +} + +impl dex_manager::Config for Runtime {} + +impl trading_pair::Config for Runtime { + type Event = Event; + type EnsureDEXManager = dex_manager::Pallet; + type WeightInfo = (); +} + +impl mock_liquidity_source::Config for Runtime { + type GetFee = (); + type EnsureDEXManager = (); + type EnsureTradingPairExists = (); +} + +impl Config for Runtime { + type Event = Event; + type GetSyntheticBaseAssetId = GetSyntheticBaseAssetId; + type LiquidityProxy = MockDEXApi; + type EnsureDEXManager = dex_manager::Pallet; + type PriceToolsPallet = MockDEXApi; + type Oracle = band::Pallet; // TODO: Replace with oracle-proxy + type Symbol = ::Symbol; + type WeightInfo = (); +} + +impl band::Config for Runtime { + type Event = Event; + type Symbol = String; + type WeightInfo = (); +} + +impl tokens::Config for Runtime { + type Event = Event; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = ::AssetId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type OnDust = (); + type MaxLocks = (); + type MaxReserves = (); + type ReserveIdentifier = (); + type OnNewTokenAccount = (); + type OnKilledTokenAccount = (); + type DustRemovalWhitelist = Everything; +} + +impl currencies::Config for Runtime { + type MultiCurrency = Tokens; + type NativeCurrency = BasicCurrencyAdapter; + type GetNativeCurrencyId = ::GetBaseAssetId; + type WeightInfo = (); +} + +impl common::Config for Runtime { + type DEXId = DEXId; + type LstId = common::LiquiditySourceType; +} + +parameter_types! { + pub const GetBuyBackAssetId: AssetId = XST; + pub GetBuyBackSupplyAssets: Vec = vec![VAL, PSWAP]; + pub const GetBuyBackPercentage: u8 = 10; + pub const GetBuyBackAccountId: AccountId = AccountId::new(hex!( + "0000000000000000000000000000000000000000000000000000000000000023" + )); + pub const GetBuyBackDexId: DEXId = DEXId::Polkaswap; +} + +impl assets::Config for Runtime { + type Event = Event; + type ExtraAccountId = [u8; 32]; + type ExtraAssetRecordArg = + common::AssetIdExtraAssetRecordArg; + type AssetId = AssetId; + type GetBaseAssetId = GetBaseAssetId; + type GetBuyBackAssetId = GetBuyBackAssetId; + type GetBuyBackSupplyAssets = GetBuyBackSupplyAssets; + type GetBuyBackPercentage = GetBuyBackPercentage; + type GetBuyBackAccountId = GetBuyBackAccountId; + type GetBuyBackDexId = GetBuyBackDexId; + type BuyBackLiquidityProxy = (); + type Currency = currencies::Pallet; + type GetTotalBalance = (); + type WeightInfo = (); +} + +impl dex_api::Config for Runtime { + type MockLiquiditySource = (); + type MockLiquiditySource2 = (); + type MockLiquiditySource3 = (); + type MockLiquiditySource4 = (); + type XYKPool = MockLiquiditySource; + type XSTPool = XSTPool; + type MulticollateralBondingCurvePool = (); + type WeightInfo = (); +} + +impl permissions::Config for Runtime { + type Event = Event; +} + +impl technical::Config for Runtime { + type Event = Event; + type TechAssetId = TechAssetId; + type TechAccountId = TechAccountId; + type Trigger = (); + type Condition = (); + type SwapAction = pool_xyk::PolySwapAction; +} + +impl pallet_balances::Config for Runtime { + type Balance = Balance; + type Event = Event; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type MaxLocks = (); + type MaxReserves = (); + type ReserveIdentifier = (); +} + +impl pswap_distribution::Config for Runtime { + const PSWAP_BURN_PERCENT: Percent = Percent::from_percent(3); + type Event = Event; + type GetIncentiveAssetId = GetIncentiveAssetId; + type LiquidityProxy = (); + type CompatBalance = Balance; + type GetDefaultSubscriptionFrequency = GetDefaultSubscriptionFrequency; + type GetBurnUpdateFrequency = GetBurnUpdateFrequency; + type GetTechnicalAccountId = GetPswapDistributionAccountId; + type EnsureDEXManager = (); + type OnPswapBurnedAggregator = (); + type WeightInfo = (); + type GetParliamentAccountId = GetParliamentAccountId; + type PoolXykPallet = PoolXYK; +} + +impl demeter_farming_platform::Config for Runtime { + type Event = Event; + type DemeterAssetId = (); + const BLOCKS_PER_HOUR_AND_A_HALF: BlockNumberFor = 900; + type WeightInfo = (); +} + +impl pool_xyk::Config for Runtime { + const MIN_XOR: Balance = balance!(0.0007); + type Event = Event; + type PairSwapAction = pool_xyk::PairSwapAction; + type DepositLiquidityAction = + pool_xyk::DepositLiquidityAction; + type WithdrawLiquidityAction = + pool_xyk::WithdrawLiquidityAction; + type PolySwapAction = pool_xyk::PolySwapAction; + type EnsureDEXManager = dex_manager::Pallet; + type GetFee = GetXykFee; + type OnPoolCreated = PswapDistribution; + type OnPoolReservesChanged = (); + type WeightInfo = (); +} + +impl pallet_timestamp::Config for Runtime { + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); +} + +impl ceres_liquidity_locker::Config for Runtime { + const BLOCKS_PER_ONE_DAY: BlockNumberFor = 14_440; + type Event = Event; + type XYKPool = PoolXYK; + type DemeterFarmingPlatform = DemeterFarmingPlatform; + type CeresAssetId = (); + type WeightInfo = (); +} + +pub struct MockDEXApi; + +impl MockDEXApi { + fn get_mock_source_account() -> Result<(TechAccountId, AccountId), DispatchError> { + let tech_account_id = + TechAccountId::Pure(DEXId::Polkaswap.into(), TechPurpose::FeeCollector); + let account_id = Technical::tech_account_id_to_account_id(&tech_account_id)?; + Ok((tech_account_id, account_id)) + } + + pub fn init_without_reserves() -> Result<(), DispatchError> { + let (tech_account_id, _) = Self::get_mock_source_account()?; + Technical::register_tech_account_id(tech_account_id.clone())?; + MockLiquiditySource::set_reserves_account_id(tech_account_id)?; + Ok(()) + } + + pub fn init() -> Result<(), DispatchError> { + Self::init_without_reserves()?; + Ok(()) + } + + fn _can_exchange( + _target_id: &DEXId, + input_asset_id: &AssetId, + output_asset_id: &AssetId, + ) -> bool { + get_mock_prices().contains_key(&(*input_asset_id, *output_asset_id)) + } + + fn inner_quote( + _target_id: &DEXId, + input_asset_id: &AssetId, + output_asset_id: &AssetId, + amount: QuoteAmount, + deduce_fee: bool, + ) -> Result, DispatchError> { + match amount { + QuoteAmount::WithDesiredInput { + desired_amount_in, .. + } => { + let amount_out = FixedWrapper::from(desired_amount_in) + * get_mock_prices()[&(*input_asset_id, *output_asset_id)]; + let fee = if deduce_fee { + let fee = amount_out.clone() * balance!(0.007); // XST uses 0.7% fees + fee.into_balance() + } else { + 0 + }; + let amount_out: Balance = amount_out.into_balance(); + let amount_out = amount_out - fee; + Ok(SwapOutcome::new(amount_out, fee)) + } + QuoteAmount::WithDesiredOutput { + desired_amount_out, .. + } => { + let amount_in = FixedWrapper::from(desired_amount_out) + / get_mock_prices()[&(*input_asset_id, *output_asset_id)]; + if deduce_fee { + let with_fee = amount_in.clone() / balance!(0.993); // XST uses 0.7% fees + let fee = with_fee.clone() - amount_in; + let fee = fee.into_balance(); + let with_fee = with_fee.into_balance(); + Ok(SwapOutcome::new(with_fee, fee)) + } else { + Ok(SwapOutcome::new(amount_in.into_balance(), 0)) + } + } + } + } + + fn inner_exchange( + sender: &AccountId, + receiver: &AccountId, + target_id: &DEXId, + input_asset_id: &AssetId, + output_asset_id: &AssetId, + swap_amount: SwapAmount, + ) -> Result, DispatchError> { + match swap_amount { + SwapAmount::WithDesiredInput { + desired_amount_in, .. + } => { + let outcome = Self::inner_quote( + target_id, + input_asset_id, + output_asset_id, + swap_amount.into(), + true, + )?; + let reserves_account_id = + &Technical::tech_account_id_to_account_id(&ReservesAccount::get())?; + assert_ne!(desired_amount_in, 0); + let old = Assets::total_balance(input_asset_id, sender)?; + Assets::transfer_from( + input_asset_id, + sender, + reserves_account_id, + desired_amount_in, + )?; + let new = Assets::total_balance(input_asset_id, sender)?; + assert_ne!(old, new); + Assets::transfer_from( + output_asset_id, + reserves_account_id, + receiver, + outcome.amount, + )?; + Ok(SwapOutcome::new(outcome.amount, outcome.fee)) + } + SwapAmount::WithDesiredOutput { + desired_amount_out, .. + } => { + let outcome = Self::inner_quote( + target_id, + input_asset_id, + output_asset_id, + swap_amount.into(), + true, + )?; + let reserves_account_id = + &Technical::tech_account_id_to_account_id(&ReservesAccount::get())?; + assert_ne!(outcome.amount, 0); + let old = Assets::total_balance(input_asset_id, sender)?; + Assets::transfer_from(input_asset_id, sender, reserves_account_id, outcome.amount)?; + let new = Assets::total_balance(input_asset_id, sender)?; + assert_ne!(old, new); + Assets::transfer_from( + output_asset_id, + reserves_account_id, + receiver, + desired_amount_out, + )?; + Ok(SwapOutcome::new(outcome.amount, outcome.fee)) + } + } + } +} + +pub fn get_mock_prices() -> HashMap<(AssetId, AssetId), Balance> { + let direct = vec![ + ((XOR, VAL), balance!(2.0)), + // USDT + ((XOR, USDT), balance!(100.0)), + ((VAL, USDT), balance!(50.0)), + // DAI + ((XOR, DAI), balance!(102.0)), + ((XST, DAI), balance!(182.9)), + ((VAL, DAI), balance!(51.0)), + ((USDT, DAI), balance!(1.02)), + // PSWAP + ((XOR, PSWAP), balance!(10)), + ((VAL, PSWAP), balance!(5)), + ((USDT, PSWAP), balance!(0.1)), + ((DAI, PSWAP), balance!(0.098)), + // XSTUSD + ((XOR, XSTUSD), balance!(103.0)), + ((VAL, XSTUSD), balance!(52.0)), + ((USDT, XSTUSD), balance!(1.03)), + ((DAI, XSTUSD), balance!(1.03)), + ((XST, XSTUSD), balance!(183.0)), + ]; + let reverse = direct.clone().into_iter().map(|((a, b), price)| { + ( + (b, a), + (fixed_wrapper!(1) / FixedWrapper::from(price)) + .try_into_balance() + .unwrap(), + ) + }); + direct.into_iter().chain(reverse).collect() +} + +impl LiquidityProxyTrait for MockDEXApi { + fn exchange( + _dex_id: DEXId, + sender: &AccountId, + receiver: &AccountId, + input_asset_id: &AssetId, + output_asset_id: &AssetId, + amount: SwapAmount, + filter: LiquiditySourceFilter, + ) -> Result, DispatchError> { + Self::inner_exchange( + sender, + receiver, + &filter.dex_id, + input_asset_id, + output_asset_id, + amount, + ) + } + + fn quote( + _dex_id: DEXId, + input_asset_id: &AssetId, + output_asset_id: &AssetId, + amount: QuoteAmount, + filter: LiquiditySourceFilter, + deduce_fee: bool, + ) -> Result, DispatchError> { + Self::inner_quote( + &filter.dex_id, + input_asset_id, + output_asset_id, + amount, + deduce_fee, + ) + } +} + +pub struct ExtBuilder { + endowed_accounts: Vec<(AccountId, AssetId, Balance, AssetSymbol, AssetName, u8)>, + endowed_accounts_with_synthetics: + Vec<(AccountId, AssetId, Balance, AssetSymbol, AssetName, u8)>, + dex_list: Vec<(DEXId, DEXInfo)>, + initial_permission_owners: Vec<(u32, Scope, Vec)>, + initial_permissions: Vec<(AccountId, Scope, Vec)>, +} + +impl Default for ExtBuilder { + fn default() -> Self { + Self { + endowed_accounts: vec![ + ( + alice(), + USDT, + 0, + AssetSymbol(b"USDT".to_vec()), + AssetName(b"Tether USD".to_vec()), + DEFAULT_BALANCE_PRECISION, + ), + ( + alice(), + XOR, + balance!(350000), + AssetSymbol(b"XOR".to_vec()), + AssetName(b"SORA".to_vec()), + DEFAULT_BALANCE_PRECISION, + ), + ( + alice(), + VAL, + balance!(500000), + AssetSymbol(b"VAL".to_vec()), + AssetName(b"SORA Validator Token".to_vec()), + DEFAULT_BALANCE_PRECISION, + ), + ( + alice(), + PSWAP, + balance!(0), + AssetSymbol(b"PSWAP".to_vec()), + AssetName(b"Polkaswap Token".to_vec()), + DEFAULT_BALANCE_PRECISION, + ), + ( + alice(), + XST, + balance!(250000), + AssetSymbol(b"XST".to_vec()), + AssetName(b"Sora Synthetics".to_vec()), + DEFAULT_BALANCE_PRECISION, + ), + ( + alice(), + DAI, + balance!(100000), + AssetSymbol(b"DAI".to_vec()), + AssetName(b"DAI".to_vec()), + DEFAULT_BALANCE_PRECISION, + ), + ], + endowed_accounts_with_synthetics: vec![( + alice(), + XSTUSD, + balance!(100000), + AssetSymbol(b"XSTUSD".to_vec()), + AssetName(b"SORA Synthetic USD".to_vec()), + DEFAULT_BALANCE_PRECISION, + )], + dex_list: vec![( + DEX_A_ID, + DEXInfo { + base_asset_id: GetBaseAssetId::get(), + synthetic_base_asset_id: GetSyntheticBaseAssetId::get(), + is_public: true, + }, + )], + initial_permission_owners: vec![ + (INIT_DEX, Scope::Unlimited, vec![alice()]), + (MANAGE_DEX, Scope::Limited(hash(&DEX_A_ID)), vec![alice()]), + ], + initial_permissions: vec![ + (alice(), Scope::Unlimited, vec![INIT_DEX]), + (alice(), Scope::Limited(hash(&DEX_A_ID)), vec![MANAGE_DEX]), + ( + assets_owner(), + Scope::Unlimited, + vec![permissions::MINT, permissions::BURN], + ), + ], + } + } +} + +impl PriceToolsPallet for MockDEXApi { + fn get_average_price( + input_asset_id: &AssetId, + output_asset_id: &AssetId, + ) -> Result { + Ok(Self::inner_quote( + &DEXId::Polkaswap.into(), + input_asset_id, + output_asset_id, + QuoteAmount::with_desired_input(balance!(1)), + true, + )? + .amount) + } + + fn register_asset(_: &AssetId) -> DispatchResult { + // do nothing + Ok(()) + } +} + +impl ExtBuilder { + pub fn new( + endowed_accounts: Vec<(AccountId, AssetId, Balance, AssetSymbol, AssetName, u8)>, + endowed_accounts_with_synthetics: Vec<( + AccountId, + AssetId, + Balance, + AssetSymbol, + AssetName, + u8, + )>, + ) -> Self { + Self { + endowed_accounts, + endowed_accounts_with_synthetics, + ..Default::default() + } + } + + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: self + .endowed_accounts + .iter() + .cloned() + .filter_map(|(account_id, asset_id, balance, ..)| { + if asset_id == GetBaseAssetId::get() { + Some((account_id, balance)) + } else { + None + } + }) + .chain(vec![(bob(), 0), (assets_owner(), 0)]) + .collect(), + } + .assimilate_storage(&mut t) + .unwrap(); + + dex_manager::GenesisConfig:: { + dex_list: self.dex_list, + } + .assimilate_storage(&mut t) + .unwrap(); + + permissions::GenesisConfig:: { + initial_permission_owners: self.initial_permission_owners, + initial_permissions: self.initial_permissions, + } + .assimilate_storage(&mut t) + .unwrap(); + + assets::GenesisConfig:: { + endowed_assets: self + .endowed_accounts + .iter() + .cloned() + .map(|(account_id, asset_id, _, symbol, name, precision)| { + ( + asset_id, + account_id, + symbol, + name, + precision, + Balance::zero(), + true, + None, + None, + ) + }) + .collect(), + } + .assimilate_storage(&mut t) + .unwrap(); + + crate::GenesisConfig::::default() + .assimilate_storage(&mut t) + .unwrap(); + + tokens::GenesisConfig:: { + balances: self + .endowed_accounts + .into_iter() + .chain(self.endowed_accounts_with_synthetics.into_iter()) + .map(|(account_id, asset_id, balance, ..)| (account_id, asset_id, balance)) + .collect(), + } + .assimilate_storage(&mut t) + .unwrap(); + + t.into() + } +} diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 3688c73ea5..c3c9f58887 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -38,8 +38,6 @@ mod mock; #[cfg(test)] mod tests; -mod benchmarking; - use core::convert::TryInto; use assets::AssetIdOf; diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index 0b7e9beedc..7fd5e3a5a7 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -74,6 +74,7 @@ vested-rewards = { path = "../pallets/vested-rewards", default-features = false vested-rewards-runtime-api = { path = "../pallets/vested-rewards/runtime-api", default-features = false } xor-fee = { path = "../pallets/xor-fee", default-features = false } xst = { path = "../pallets/xst", default-features = false } +xst-benchmarking = { path = "../pallets/xst/benchmarking", default-features = false, optional = true } # Substrate dependencies frame-benchmarking = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false, optional = true } @@ -273,7 +274,7 @@ runtime-benchmarks = [ "price-tools/runtime-benchmarks", "vested-rewards/runtime-benchmarks", "xor-fee/runtime-benchmarks", - "xst/runtime-benchmarks", + "xst-benchmarking", ] reduced-pswap-reward-periods = [] diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 2b8f203312..14b39d8ee2 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -2568,6 +2568,7 @@ impl_runtime_apis! { use pool_xyk_benchmarking::Pallet as XYKPoolBench; use pswap_distribution_benchmarking::Pallet as PswapDistributionBench; use ceres_liquidity_locker_benchmarking::Pallet as CeresLiquidityLockerBench; + use xst_benchmarking::Pallet as XSTPoolBench; let mut list = Vec::::new(); @@ -2590,7 +2591,7 @@ impl_runtime_apis! { list_benchmark!(list, extra, ceres_staking, CeresStaking); list_benchmark!(list, extra, ceres_liquidity_locker, CeresLiquidityLockerBench::); list_benchmark!(list, extra, band, Band); - list_benchmark!(list, extra, xst, XSTPool); + list_benchmark!(list, extra, xst, XSTPoolBench::); let storage_info = AllPalletsWithSystem::storage_info(); @@ -2607,11 +2608,13 @@ impl_runtime_apis! { use pswap_distribution_benchmarking::Pallet as PswapDistributionBench; use ceres_liquidity_locker_benchmarking::Pallet as CeresLiquidityLockerBench; use demeter_farming_platform_benchmarking::Pallet as DemeterFarmingPlatformBench; + use xst_benchmarking::Pallet as XSTPoolBench; impl liquidity_proxy_benchmarking::Config for Runtime {} impl pool_xyk_benchmarking::Config for Runtime {} impl pswap_distribution_benchmarking::Config for Runtime {} impl ceres_liquidity_locker_benchmarking::Config for Runtime {} + impl xst_benchmarking::Config for Runtime {} let whitelist: Vec = vec![ // Block Number @@ -2655,7 +2658,7 @@ impl_runtime_apis! { add_benchmark!(params, batches, ceres_launchpad, CeresLaunchpad); add_benchmark!(params, batches, demeter_farming_platform, DemeterFarmingPlatformBench::); add_benchmark!(params, batches, band, Band); - add_benchmark!(params, batches, xst, XSTPool); + add_benchmark!(params, batches, xst, XSTPoolBench::); if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } Ok(batches) From ae9b7418720984b1da6a4db15ac654bcc61c161b Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Sun, 18 Dec 2022 16:35:01 +0300 Subject: [PATCH 24/72] Finish fixing benchmarks Signed-off-by: Daniil Polyakov --- Cargo.lock | 12 +++ pallets/xst/benchmarking/Cargo.toml | 17 +++++ pallets/xst/benchmarking/src/lib.rs | 108 ++++++++++++++++++--------- pallets/xst/benchmarking/src/mock.rs | 28 ++----- 4 files changed, 108 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index afee6bc9c8..ade82dcb73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13525,8 +13525,12 @@ dependencies = [ name = "xst-benchmarking" version = "0.1.0" dependencies = [ + "assets", "band", + "ceres-liquidity-locker", "common", + "demeter-farming-platform", + "dex-api", "dex-manager", "frame-benchmarking", "frame-support", @@ -13534,8 +13538,16 @@ dependencies = [ "hex-literal", "mock-liquidity-source", "orml-currencies", + "orml-tokens", + "pallet-balances", + "pallet-timestamp", + "parity-scale-codec", "permissions", + "pool-xyk", + "pswap-distribution", + "scale-info", "sp-core", + "sp-io", "sp-runtime", "sp-std", "technical", diff --git a/pallets/xst/benchmarking/Cargo.toml b/pallets/xst/benchmarking/Cargo.toml index ff44655c4c..1f340b3cdd 100644 --- a/pallets/xst/benchmarking/Cargo.toml +++ b/pallets/xst/benchmarking/Cargo.toml @@ -11,6 +11,7 @@ repository = "https://github.com/sora-xor/sora2-network" targets = ["x86_64-unknown-linux-gnu"] [dependencies] +codec = { package = "parity-scale-codec", version = "3", default-features = false } currencies = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-currencies", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } @@ -28,6 +29,22 @@ trading-pair = { path = "../../trading-pair", default-features = false } band = { path = "../../band", default-features = false } xst = {path = "../../xst", default-features = false } +[dev-dependencies] +scale-info = { version = "2", default-features = false } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-tokens", default-features = false } +assets = { path = "../../assets", default-features = false } +dex-api = { path = "../../dex-api", default-features = false } +pool-xyk = { path = "../../pool-xyk", default-features = false } +pswap-distribution = { path = "../../pswap-distribution", default-features = false } +demeter-farming-platform = { path = "../../demeter-farming-platform", default-features = false } +ceres-liquidity-locker = { path = "../../ceres-liquidity-locker", default-features = false } +common = { path = "../../../common", default-features = false, features = [ + "test", +] } + [features] default = ["std"] std = [ diff --git a/pallets/xst/benchmarking/src/lib.rs b/pallets/xst/benchmarking/src/lib.rs index 30d38bc22d..bf224111e7 100644 --- a/pallets/xst/benchmarking/src/lib.rs +++ b/pallets/xst/benchmarking/src/lib.rs @@ -32,22 +32,73 @@ #![cfg_attr(not(feature = "std"), no_std)] +use band::Pallet as Band; +use codec::{Decode as _, Encode as _}; use common::{balance, fixed, AssetName, AssetSymbol, DAI}; use frame_benchmarking::benchmarks; +use frame_support::pallet_prelude::DispatchResultWithPostInfo; use frame_system::{EventRecord, RawOrigin}; +use hex_literal::hex; use sp_std::prelude::*; use xst::{Call, Event, Pallet as XSTPool}; -fn assert_last_event(generic_event: ::Event) { - let events = frame_system::Pallet::::events(); - let system_event: ::Event = generic_event.into(); - // compare to the last event record - let EventRecord { event, .. } = &events[events.len() - 1]; - assert_eq!(event, &system_event); -} +#[cfg(test)] +mod mock; + +mod utils { + use frame_support::{dispatch::DispatchErrorWithPostInfo, Parameter}; + + use super::*; + + pub const REFERENCE_SYMBOL: &str = "EURO"; + + pub fn symbol() -> Symbol { + let bytes = REFERENCE_SYMBOL.encode(); + Symbol::decode(&mut &bytes[..]).expect("Failed to decode symbol") + } + + pub fn alice() -> T::AccountId { + let bytes = hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"); + T::AccountId::decode(&mut &bytes[..]).unwrap() + } + + pub fn assert_last_event(generic_event: ::Event) { + let events = frame_system::Pallet::::events(); + let system_event: ::Event = generic_event.into(); + // compare to the last event record + let EventRecord { event, .. } = &events[events.len() - 1]; + assert_eq!(event, &system_event); + } + + pub fn relay_symbol() -> DispatchResultWithPostInfo { + Band::::add_relayers(RawOrigin::Root.into(), vec![alice::()])?; + Band::::relay( + RawOrigin::Signed(alice::()).into(), + vec![(symbol::<::Symbol>(), 1)], + 0, + 0, + ) + } + + pub fn enable_synthetic_asset() -> Result { + relay_symbol::()?; + + XSTPool::::enable_synthetic_asset( + RawOrigin::Root.into(), + AssetSymbol(b"XSTEURO".to_vec()), + AssetName(b"Sora Synthetic EURO".to_vec()), + symbol(), + fixed!(0), + )?; + Ok( + XSTPool::::enabled_symbols(symbol::<::Symbol>()) + .expect("Expected enabled synthetic"), + ) + } +} pub struct Pallet(xst::Pallet); -pub trait Config: xst::Config {} +pub trait Config: xst::Config + band::Config {} benchmarks! { set_reference_asset { @@ -56,52 +107,39 @@ benchmarks! { DAI.into() ) verify { - assert_last_event::(Event::ReferenceAssetChanged(DAI.into()).into()) + utils::assert_last_event::(Event::ReferenceAssetChanged(DAI.into()).into()) } enable_synthetic_asset { - let reference_symbol = "EURO"; + utils::relay_symbol::()?; }: _( RawOrigin::Root, AssetSymbol(b"XSTEURO".to_vec()), AssetName(b"Sora Synthetic EURO".to_vec()), - reference_symbol.into(), + utils::REFERENCE_SYMBOL.into(), fixed!(0) ) verify { - assert!(XSTPool::::enabled_symbols(T::Symbol::from(reference_symbol)).is_some()); + assert!( + XSTPool::::enabled_symbols( + ::Symbol::from(utils::REFERENCE_SYMBOL) + ) + .is_some() + ); } disable_synthetic_asset { - let reference_symbol = "EURO"; - XSTPool::::enable_synthetic_asset( - RawOrigin::Root.into(), - AssetSymbol(b"XSTEURO".to_vec()), - AssetName(b"Sora Synthetic EURO".to_vec()), - reference_symbol.into(), - fixed!(0), - )?; - let asset_id = XSTPool::::enabled_symbols(T::Symbol::from(reference_symbol)) - .expect("Expected enabled synthetic"); + let asset_id = utils::enable_synthetic_asset::()?; }: _( RawOrigin::Root, asset_id ) verify { - assert_last_event::(Event::SyntheticAssetDisabled(asset_id).into()) + utils::assert_last_event::(Event::SyntheticAssetDisabled(asset_id).into()) } set_synthetic_asset_fee { - let reference_symbol = "EURO"; - XSTPool::::enable_synthetic_asset( - RawOrigin::Root.into(), - AssetSymbol(b"XSTEURO".to_vec()), - AssetName(b"Sora Synthetic EURO".to_vec()), - reference_symbol.into(), - fixed!(0), - )?; - let asset_id = XSTPool::::enabled_symbols(T::Symbol::from(reference_symbol)) - .expect("Expected enabled synthetic"); + let asset_id = utils::enable_synthetic_asset::()?; let fee_ratio = fixed!(0.06); }: _( RawOrigin::Root, @@ -109,13 +147,13 @@ benchmarks! { fee_ratio ) verify { - assert_last_event::(Event::SyntheticAssetFeeChanged(asset_id, fee_ratio).into()) + utils::assert_last_event::(Event::SyntheticAssetFeeChanged(asset_id, fee_ratio).into()) } set_synthetic_base_asset_floor_price { }: _(RawOrigin::Root, balance!(200)) verify { - assert_last_event::(Event::SyntheticBaseAssetFloorPriceChanged(balance!(200)).into()) + utils::assert_last_event::(Event::SyntheticBaseAssetFloorPriceChanged(balance!(200)).into()) } impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Runtime); diff --git a/pallets/xst/benchmarking/src/mock.rs b/pallets/xst/benchmarking/src/mock.rs index 82c714768f..4834dbda7e 100644 --- a/pallets/xst/benchmarking/src/mock.rs +++ b/pallets/xst/benchmarking/src/mock.rs @@ -28,7 +28,7 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use crate::{self as xstpool, Config}; +use crate::Config; use common::mock::ExistentialDeposits; use common::prelude::{ Balance, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapAmount, SwapOutcome, @@ -118,7 +118,7 @@ construct_runtime! { Technical: technical::{Pallet, Call, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Event}, PoolXYK: pool_xyk::{Pallet, Call, Storage, Event}, - XSTPool: xstpool::{Pallet, Call, Storage, Event}, + XSTPool: xst::{Pallet, Call, Storage, Event}, PswapDistribution: pswap_distribution::{Pallet, Call, Storage, Event}, DEXApi: dex_api::{Pallet, Storage}, Band: band::{Pallet, Call, Storage, Event}, @@ -168,7 +168,7 @@ impl mock_liquidity_source::Config for Runtime type EnsureTradingPairExists = (); } -impl Config for Runtime { +impl xst::Config for Runtime { type Event = Event; type GetSyntheticBaseAssetId = GetSyntheticBaseAssetId; type LiquidityProxy = MockDEXApi; @@ -323,6 +323,8 @@ impl pallet_timestamp::Config for Runtime { type WeightInfo = (); } +impl Config for Runtime {} + impl ceres_liquidity_locker::Config for Runtime { const BLOCKS_PER_ONE_DAY: BlockNumberFor = 14_440; type Event = Event; @@ -660,24 +662,6 @@ impl PriceToolsPallet for MockDEXApi { } impl ExtBuilder { - pub fn new( - endowed_accounts: Vec<(AccountId, AssetId, Balance, AssetSymbol, AssetName, u8)>, - endowed_accounts_with_synthetics: Vec<( - AccountId, - AssetId, - Balance, - AssetSymbol, - AssetName, - u8, - )>, - ) -> Self { - Self { - endowed_accounts, - endowed_accounts_with_synthetics, - ..Default::default() - } - } - pub fn build(self) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() .build_storage::() @@ -737,7 +721,7 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); - crate::GenesisConfig::::default() + xst::GenesisConfig::::default() .assimilate_storage(&mut t) .unwrap(); From a5fdf5c362a93b23806422dce1c4053a98e099c4 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Sun, 18 Dec 2022 16:46:27 +0300 Subject: [PATCH 25/72] Update weights Signed-off-by: Daniil Polyakov --- pallets/xst/src/weights.rs | 64 +++++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 28 deletions(-) diff --git a/pallets/xst/src/weights.rs b/pallets/xst/src/weights.rs index 85d458cbb3..57dc698510 100644 --- a/pallets/xst/src/weights.rs +++ b/pallets/xst/src/weights.rs @@ -31,7 +31,7 @@ //! Autogenerated weights for `xst` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2022-12-05, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2022-12-18, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! HOSTNAME: `Amaterasu.local`, CPU: `` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("local"), DB CACHE: 1024 @@ -62,36 +62,44 @@ use common::weights::constants::EXTRINSIC_FIXED_WEIGHT; /// Weight functions for `xst`. pub struct WeightInfo(PhantomData); -impl super::WeightInfo for WeightInfo { - // Storage: XSTPool ReferenceAssetId (r:0 w:1) - fn set_reference_asset() -> Weight { - (20_000_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - - // Storage: XSTPool SyntheticBaseAssetFloorPrice (r:0 w:1) - fn set_synthetic_base_asset_floor_price() -> Weight { - (20_000_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - - // Storage: XSTPool EnabledSynthetics (r:1 w:1) - fn enable_synthetic_asset() -> Weight { - (23_000_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - - fn disable_synthetic_asset() -> Weight { - // TODO - (210_815_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) +impl crate::WeightInfo for WeightInfo { + // Storage: XSTPool ReferenceAssetId (r:0 w:1) + fn set_reference_asset() -> Weight { + (12_000_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + // Storage: XSTPool EnabledSymbols (r:1 w:1) + // Storage: Band SymbolRates (r:2 w:0) + // Storage: XSTPool PermissionedTechAccount (r:1 w:0) + // Storage: Assets AssetOwners (r:2 w:1) + // Storage: System Account (r:1 w:1) + // Storage: Permissions Owners (r:2 w:2) + // Storage: Permissions Permissions (r:4 w:1) + // Storage: DEXManager DEXInfos (r:1 w:0) + // Storage: TradingPair EnabledSources (r:1 w:1) + // Storage: Assets AssetInfos (r:0 w:1) + // Storage: XSTPool EnabledSynthetics (r:0 w:1) + fn enable_synthetic_asset() -> Weight { + (149_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(15 as Weight)) + .saturating_add(T::DbWeight::get().writes(9 as Weight)) + } + // Storage: XSTPool EnabledSynthetics (r:1 w:1) + // Storage: XSTPool EnabledSymbols (r:0 w:1) + fn disable_synthetic_asset() -> Weight { + (21_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: XSTPool EnabledSynthetics (r:1 w:1) fn set_synthetic_asset_fee() -> Weight { - // TODO - (210_815_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) + (19_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: XSTPool SyntheticBaseAssetFloorPrice (r:0 w:1) + fn set_synthetic_base_asset_floor_price() -> Weight { + (12_000_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } } From d14c1098c911523345afa239a3cafb8ac4c88cca Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Sun, 18 Dec 2022 18:02:44 +0300 Subject: [PATCH 26/72] Update extrinsics doc comments Signed-off-by: Daniil Polyakov --- pallets/xst/src/lib.rs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index c3c9f58887..91153e48b7 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -163,7 +163,11 @@ pub mod pallet { #[pallet::call] impl Pallet { - /// Change reference asset which is used to determine collateral assets value. Intended to be e.g., stablecoin DAI. + /// Change reference asset which is used to determine collateral assets value. + /// Intended to be e.g., stablecoin DAI. + /// + /// - `origin`: the sudo account on whose behalf the transaction is being executed, + /// - `reference_asset_id`: asset id of the new reference asset. #[pallet::weight(::WeightInfo::set_reference_asset())] pub fn set_reference_asset( origin: OriginFor, @@ -195,10 +199,14 @@ pub mod pallet { Ok(().into()) } - /// TODO + /// Disable synthetic asset. + /// + /// Just remove synthetic from exchanging. + /// Will not unregister trading pair because `trading_pair` pallet does not provide this + /// ability. And will not unregister trading synthetic asset because of that. /// - /// Should it unregister asset or just disable exchanging? - /// What to do with users? + /// - `origin`: the sudo account on whose behalf the transaction is being executed, + /// - `synthetic_asset`: synthetic asset id to disable. #[pallet::weight(::WeightInfo::disable_synthetic_asset())] pub fn disable_synthetic_asset( origin: OriginFor, @@ -222,6 +230,10 @@ pub mod pallet { /// /// This fee will be used to determine the amount of synthetic base asset (e.g. XST) to be /// burned when user buys synthetic asset. + /// + /// - `origin`: the sudo account on whose behalf the transaction is being executed, + /// - `synthetic_asset`: synthetic asset id to set fee for, + /// - `fee_ratio`: fee ratio with precision = 18, so 1000000000000000000 = 1 = 100% fee. #[pallet::weight(::WeightInfo::set_synthetic_asset_fee())] pub fn set_synthetic_asset_fee( origin: OriginFor, From 057b2ed4f88326311b91e175b4166132a7147715 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Sun, 18 Dec 2022 18:46:00 +0300 Subject: [PATCH 27/72] Add migration Signed-off-by: Daniil Polyakov --- Cargo.lock | 1 + pallets/xst/Cargo.toml | 8 +++- pallets/xst/src/lib.rs | 4 +- pallets/xst/src/migrations/mod.rs | 59 +++++++++++++++++++++++++++++ pallets/xst/src/migrations/tests.rs | 50 ++++++++++++++++++++++++ runtime/src/lib.rs | 4 +- runtime/src/migrations.rs | 12 +++++- 7 files changed, 132 insertions(+), 6 deletions(-) create mode 100644 pallets/xst/src/migrations/mod.rs create mode 100644 pallets/xst/src/migrations/tests.rs diff --git a/Cargo.lock b/Cargo.lock index ade82dcb73..147dffd3cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13515,6 +13515,7 @@ dependencies = [ "serde", "sp-arithmetic", "sp-core", + "sp-io", "sp-runtime", "sp-std", "technical", diff --git a/pallets/xst/Cargo.toml b/pallets/xst/Cargo.toml index fe3b73816a..d04d514bb7 100644 --- a/pallets/xst/Cargo.toml +++ b/pallets/xst/Cargo.toml @@ -41,16 +41,20 @@ pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch blake2 = { version = "0.10.5", default-features = false } [dev-dependencies] -ceres-liquidity-locker = { path = "../ceres-liquidity-locker" } -demeter-farming-platform = { path = "../demeter-farming-platform" } hex-literal = "0.3.1" pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25" } sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +ceres-liquidity-locker = { path = "../ceres-liquidity-locker" } +demeter-farming-platform = { path = "../demeter-farming-platform" } dex-manager = { path = "../dex-manager" } mock-liquidity-source = { path = "../mock-liquidity-source" } technical = { path = "../technical" } trading-pair = { path = "../trading-pair" } band = { path = "../band" } +common = { path = "../../common", default-features = false, features = [ + "test", +] } [features] default = ['std'] diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 91153e48b7..f691ba4579 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -38,6 +38,8 @@ mod mock; #[cfg(test)] mod tests; +pub mod migrations; + use core::convert::TryInto; use assets::AssetIdOf; @@ -153,7 +155,7 @@ pub mod pallet { } /// The current storage version. - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); + const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] diff --git a/pallets/xst/src/migrations/mod.rs b/pallets/xst/src/migrations/mod.rs new file mode 100644 index 0000000000..6efac2cf2a --- /dev/null +++ b/pallets/xst/src/migrations/mod.rs @@ -0,0 +1,59 @@ +// This file is part of the SORA network and Polkaswap app. + +// Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved. +// SPDX-License-Identifier: BSD-4-Clause + +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: + +// Redistributions of source code must retain the above copyright notice, this list +// of conditions and the following disclaimer. +// Redistributions in binary form must reproduce the above copyright notice, this +// list of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// All advertising materials mentioning features or use of this software must display +// the following acknowledgement: This product includes software developed by Polka Biome +// Ltd., SORA, and Polkaswap. +// +// Neither the name of the Polka Biome Ltd. nor the names of its contributors may be used +// to endorse or promote products derived from this software without specific prior written permission. + +// THIS SOFTWARE IS PROVIDED BY Polka Biome Ltd. AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, +// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Polka Biome Ltd. BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +use super::pallet::{Config, Pallet}; +use common::{fixed, XSTUSD}; +use frame_support::pallet_prelude::{Get, StorageVersion}; +use frame_support::{log::info, traits::GetStorageVersion as _, weights::Weight}; + +use crate::{EnabledSymbols, EnabledSynthetics, SyntheticInfo}; + +/// Migration which migrates `XSTUSD` synthetic to the new format. +pub fn migrate() -> Weight { + if Pallet::::on_chain_storage_version() >= 2 { + info!("Migration to version 2 has already been applied"); + return 0; + } + + EnabledSynthetics::::insert( + T::AssetId::from(XSTUSD), + Some(SyntheticInfo { + reference_symbol: T::Symbol::from("USD"), + fee_ratio: fixed!(0.00666), + }), + ); + EnabledSymbols::::insert(T::Symbol::from("USD"), Some(T::AssetId::from(XSTUSD))); + + StorageVersion::new(2).put::>(); + T::DbWeight::get().reads_writes(0, 2) +} + +#[cfg(test)] +mod tests; diff --git a/pallets/xst/src/migrations/tests.rs b/pallets/xst/src/migrations/tests.rs new file mode 100644 index 0000000000..22c046deb9 --- /dev/null +++ b/pallets/xst/src/migrations/tests.rs @@ -0,0 +1,50 @@ +// This file is part of the SORA network and Polkaswap app. + +// Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved. +// SPDX-License-Identifier: BSD-4-Clause + +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: + +// Redistributions of source code must retain the above copyright notice, this list +// of conditions and the following disclaimer. +// Redistributions in binary form must reproduce the above copyright notice, this +// list of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// All advertising materials mentioning features or use of this software must display +// the following acknowledgement: This product includes software developed by Polka Biome +// Ltd., SORA, and Polkaswap. +// +// Neither the name of the Polka Biome Ltd. nor the names of its contributors may be used +// to endorse or promote products derived from this software without specific prior written permission. + +// THIS SOFTWARE IS PROVIDED BY Polka Biome Ltd. AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, +// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Polka Biome Ltd. BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +use crate::{mock::*, pallet::Pallet, EnabledSynthetics}; +use common::{fixed, XSTUSD}; +use frame_support::traits::{GetStorageVersion as _, StorageVersion}; + +#[test] +fn test() { + ExtBuilder::default().build().execute_with(|| { + StorageVersion::new(1).put::>(); + + super::migrate::(); + + let info = EnabledSynthetics::::get(XSTUSD) + .expect("XSTUSD synthetic should be enabled after migration"); + + assert_eq!(info.reference_symbol, "USD"); + assert_eq!(info.fee_ratio, fixed!(0.00666)); + + assert_eq!(Pallet::::on_chain_storage_version(), 2); + }); +} diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 14b39d8ee2..eb2dc2ce98 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -223,10 +223,10 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("sora-substrate"), impl_name: create_runtime_str!("sora-substrate"), authoring_version: 1, - spec_version: 43, + spec_version: 44, impl_version: 1, apis: RUNTIME_API_VERSIONS, - transaction_version: 43, + transaction_version: 44, state_version: 0, }; diff --git a/runtime/src/migrations.rs b/runtime/src/migrations.rs index 49d7aa7e1d..1ea7e66fbe 100644 --- a/runtime/src/migrations.rs +++ b/runtime/src/migrations.rs @@ -1,7 +1,7 @@ use crate::*; use frame_support::traits::OnRuntimeUpgrade; -pub type Migrations = (EthBridgeMigration,); +pub type Migrations = (EthBridgeMigration, XSTPoolMigration); pub struct EthBridgeMigration; @@ -12,3 +12,13 @@ impl OnRuntimeUpgrade for EthBridgeMigration { ::BlockWeights::get().max_block } } + +pub struct XSTPoolMigration; + +impl OnRuntimeUpgrade for XSTPoolMigration { + fn on_runtime_upgrade() -> Weight { + frame_support::log::warn!("Run migration XSTPoolMigration"); + xst::migrations::migrate::(); + ::BlockWeights::get().max_block + } +} From b0c5df0a38e747b7fc2f18f91c309d527460c28d Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Sun, 18 Dec 2022 19:17:04 +0300 Subject: [PATCH 28/72] Remove useless `LiquidityProxy` from xst::Config Signed-off-by: Daniil Polyakov --- pallets/xst/benchmarking/src/mock.rs | 123 +-------------------------- pallets/xst/src/lib.rs | 5 +- pallets/xst/src/mock.rs | 123 +-------------------------- runtime/src/lib.rs | 1 - 4 files changed, 5 insertions(+), 247 deletions(-) diff --git a/pallets/xst/benchmarking/src/mock.rs b/pallets/xst/benchmarking/src/mock.rs index 4834dbda7e..1b9bc087f6 100644 --- a/pallets/xst/benchmarking/src/mock.rs +++ b/pallets/xst/benchmarking/src/mock.rs @@ -30,13 +30,10 @@ use crate::Config; use common::mock::ExistentialDeposits; -use common::prelude::{ - Balance, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapAmount, SwapOutcome, -}; +use common::prelude::{Balance, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapOutcome}; use common::{ self, balance, fixed, fixed_wrapper, hash, Amount, AssetId32, AssetName, AssetSymbol, DEXInfo, - Fixed, LiquidityProxyTrait, LiquiditySourceFilter, LiquiditySourceType, TechPurpose, DAI, - DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, XSTUSD, + Fixed, TechPurpose, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, XSTUSD, }; use currencies::BasicCurrencyAdapter; use frame_support::traits::{Everything, GenesisBuild}; @@ -56,8 +53,6 @@ pub type AccountId = AccountId32; pub type BlockNumber = u64; pub type TechAccountId = common::TechAccountId; type TechAssetId = common::TechAssetId; -pub type ReservesAccount = - mock_liquidity_source::ReservesAcc; pub type AssetId = AssetId32; type DEXId = common::DEXId; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -171,7 +166,6 @@ impl mock_liquidity_source::Config for Runtime impl xst::Config for Runtime { type Event = Event; type GetSyntheticBaseAssetId = GetSyntheticBaseAssetId; - type LiquidityProxy = MockDEXApi; type EnsureDEXManager = dex_manager::Pallet; type PriceToolsPallet = MockDEXApi; type Oracle = band::Pallet; // TODO: Replace with oracle-proxy @@ -356,14 +350,6 @@ impl MockDEXApi { Ok(()) } - fn _can_exchange( - _target_id: &DEXId, - input_asset_id: &AssetId, - output_asset_id: &AssetId, - ) -> bool { - get_mock_prices().contains_key(&(*input_asset_id, *output_asset_id)) - } - fn inner_quote( _target_id: &DEXId, input_asset_id: &AssetId, @@ -404,73 +390,6 @@ impl MockDEXApi { } } } - - fn inner_exchange( - sender: &AccountId, - receiver: &AccountId, - target_id: &DEXId, - input_asset_id: &AssetId, - output_asset_id: &AssetId, - swap_amount: SwapAmount, - ) -> Result, DispatchError> { - match swap_amount { - SwapAmount::WithDesiredInput { - desired_amount_in, .. - } => { - let outcome = Self::inner_quote( - target_id, - input_asset_id, - output_asset_id, - swap_amount.into(), - true, - )?; - let reserves_account_id = - &Technical::tech_account_id_to_account_id(&ReservesAccount::get())?; - assert_ne!(desired_amount_in, 0); - let old = Assets::total_balance(input_asset_id, sender)?; - Assets::transfer_from( - input_asset_id, - sender, - reserves_account_id, - desired_amount_in, - )?; - let new = Assets::total_balance(input_asset_id, sender)?; - assert_ne!(old, new); - Assets::transfer_from( - output_asset_id, - reserves_account_id, - receiver, - outcome.amount, - )?; - Ok(SwapOutcome::new(outcome.amount, outcome.fee)) - } - SwapAmount::WithDesiredOutput { - desired_amount_out, .. - } => { - let outcome = Self::inner_quote( - target_id, - input_asset_id, - output_asset_id, - swap_amount.into(), - true, - )?; - let reserves_account_id = - &Technical::tech_account_id_to_account_id(&ReservesAccount::get())?; - assert_ne!(outcome.amount, 0); - let old = Assets::total_balance(input_asset_id, sender)?; - Assets::transfer_from(input_asset_id, sender, reserves_account_id, outcome.amount)?; - let new = Assets::total_balance(input_asset_id, sender)?; - assert_ne!(old, new); - Assets::transfer_from( - output_asset_id, - reserves_account_id, - receiver, - desired_amount_out, - )?; - Ok(SwapOutcome::new(outcome.amount, outcome.fee)) - } - } - } } pub fn get_mock_prices() -> HashMap<(AssetId, AssetId), Balance> { @@ -507,44 +426,6 @@ pub fn get_mock_prices() -> HashMap<(AssetId, AssetId), Balance> { direct.into_iter().chain(reverse).collect() } -impl LiquidityProxyTrait for MockDEXApi { - fn exchange( - _dex_id: DEXId, - sender: &AccountId, - receiver: &AccountId, - input_asset_id: &AssetId, - output_asset_id: &AssetId, - amount: SwapAmount, - filter: LiquiditySourceFilter, - ) -> Result, DispatchError> { - Self::inner_exchange( - sender, - receiver, - &filter.dex_id, - input_asset_id, - output_asset_id, - amount, - ) - } - - fn quote( - _dex_id: DEXId, - input_asset_id: &AssetId, - output_asset_id: &AssetId, - amount: QuoteAmount, - filter: LiquiditySourceFilter, - deduce_fee: bool, - ) -> Result, DispatchError> { - Self::inner_quote( - &filter.dex_id, - input_asset_id, - output_asset_id, - amount, - deduce_fee, - ) - } -} - pub struct ExtBuilder { endowed_accounts: Vec<(AccountId, AssetId, Balance, AssetSymbol, AssetName, u8)>, endowed_accounts_with_synthetics: diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index f691ba4579..60140882d6 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -51,8 +51,7 @@ use common::prelude::{ }; use common::{ balance, fixed_wrapper, AssetName, AssetSymbol, DEXId, DataFeed, GetMarketInfo, - LiquidityProxyTrait, LiquiditySource, LiquiditySourceFilter, LiquiditySourceType, RewardReason, - DAI, XSTUSD, + LiquiditySource, LiquiditySourceFilter, LiquiditySourceType, RewardReason, DAI, XSTUSD, }; use frame_support::traits::Get; use frame_support::weights::Weight; @@ -140,8 +139,6 @@ pub mod pallet { type Event: From> + IsType<::Event>; /// AssetId which is convertible to/from XSTUSD type GetSyntheticBaseAssetId: Get; - // TODO: Remove - type LiquidityProxy: LiquidityProxyTrait; type EnsureDEXManager: EnsureDEXManager; type PriceToolsPallet: PriceToolsPallet; type Oracle: DataFeed; diff --git a/pallets/xst/src/mock.rs b/pallets/xst/src/mock.rs index 82c714768f..06b2daf4e5 100644 --- a/pallets/xst/src/mock.rs +++ b/pallets/xst/src/mock.rs @@ -30,13 +30,10 @@ use crate::{self as xstpool, Config}; use common::mock::ExistentialDeposits; -use common::prelude::{ - Balance, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapAmount, SwapOutcome, -}; +use common::prelude::{Balance, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapOutcome}; use common::{ self, balance, fixed, fixed_wrapper, hash, Amount, AssetId32, AssetName, AssetSymbol, DEXInfo, - Fixed, LiquidityProxyTrait, LiquiditySourceFilter, LiquiditySourceType, TechPurpose, DAI, - DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, XSTUSD, + Fixed, TechPurpose, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, XSTUSD, }; use currencies::BasicCurrencyAdapter; use frame_support::traits::{Everything, GenesisBuild}; @@ -56,8 +53,6 @@ pub type AccountId = AccountId32; pub type BlockNumber = u64; pub type TechAccountId = common::TechAccountId; type TechAssetId = common::TechAssetId; -pub type ReservesAccount = - mock_liquidity_source::ReservesAcc; pub type AssetId = AssetId32; type DEXId = common::DEXId; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -171,7 +166,6 @@ impl mock_liquidity_source::Config for Runtime impl Config for Runtime { type Event = Event; type GetSyntheticBaseAssetId = GetSyntheticBaseAssetId; - type LiquidityProxy = MockDEXApi; type EnsureDEXManager = dex_manager::Pallet; type PriceToolsPallet = MockDEXApi; type Oracle = band::Pallet; // TODO: Replace with oracle-proxy @@ -354,14 +348,6 @@ impl MockDEXApi { Ok(()) } - fn _can_exchange( - _target_id: &DEXId, - input_asset_id: &AssetId, - output_asset_id: &AssetId, - ) -> bool { - get_mock_prices().contains_key(&(*input_asset_id, *output_asset_id)) - } - fn inner_quote( _target_id: &DEXId, input_asset_id: &AssetId, @@ -402,73 +388,6 @@ impl MockDEXApi { } } } - - fn inner_exchange( - sender: &AccountId, - receiver: &AccountId, - target_id: &DEXId, - input_asset_id: &AssetId, - output_asset_id: &AssetId, - swap_amount: SwapAmount, - ) -> Result, DispatchError> { - match swap_amount { - SwapAmount::WithDesiredInput { - desired_amount_in, .. - } => { - let outcome = Self::inner_quote( - target_id, - input_asset_id, - output_asset_id, - swap_amount.into(), - true, - )?; - let reserves_account_id = - &Technical::tech_account_id_to_account_id(&ReservesAccount::get())?; - assert_ne!(desired_amount_in, 0); - let old = Assets::total_balance(input_asset_id, sender)?; - Assets::transfer_from( - input_asset_id, - sender, - reserves_account_id, - desired_amount_in, - )?; - let new = Assets::total_balance(input_asset_id, sender)?; - assert_ne!(old, new); - Assets::transfer_from( - output_asset_id, - reserves_account_id, - receiver, - outcome.amount, - )?; - Ok(SwapOutcome::new(outcome.amount, outcome.fee)) - } - SwapAmount::WithDesiredOutput { - desired_amount_out, .. - } => { - let outcome = Self::inner_quote( - target_id, - input_asset_id, - output_asset_id, - swap_amount.into(), - true, - )?; - let reserves_account_id = - &Technical::tech_account_id_to_account_id(&ReservesAccount::get())?; - assert_ne!(outcome.amount, 0); - let old = Assets::total_balance(input_asset_id, sender)?; - Assets::transfer_from(input_asset_id, sender, reserves_account_id, outcome.amount)?; - let new = Assets::total_balance(input_asset_id, sender)?; - assert_ne!(old, new); - Assets::transfer_from( - output_asset_id, - reserves_account_id, - receiver, - desired_amount_out, - )?; - Ok(SwapOutcome::new(outcome.amount, outcome.fee)) - } - } - } } pub fn get_mock_prices() -> HashMap<(AssetId, AssetId), Balance> { @@ -505,44 +424,6 @@ pub fn get_mock_prices() -> HashMap<(AssetId, AssetId), Balance> { direct.into_iter().chain(reverse).collect() } -impl LiquidityProxyTrait for MockDEXApi { - fn exchange( - _dex_id: DEXId, - sender: &AccountId, - receiver: &AccountId, - input_asset_id: &AssetId, - output_asset_id: &AssetId, - amount: SwapAmount, - filter: LiquiditySourceFilter, - ) -> Result, DispatchError> { - Self::inner_exchange( - sender, - receiver, - &filter.dex_id, - input_asset_id, - output_asset_id, - amount, - ) - } - - fn quote( - _dex_id: DEXId, - input_asset_id: &AssetId, - output_asset_id: &AssetId, - amount: QuoteAmount, - filter: LiquiditySourceFilter, - deduce_fee: bool, - ) -> Result, DispatchError> { - Self::inner_quote( - &filter.dex_id, - input_asset_id, - output_asset_id, - amount, - deduce_fee, - ) - } -} - pub struct ExtBuilder { endowed_accounts: Vec<(AccountId, AssetId, Balance, AssetSymbol, AssetName, u8)>, endowed_accounts_with_synthetics: diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index eb2dc2ce98..e3301b7d9f 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1669,7 +1669,6 @@ parameter_types! { impl xst::Config for Runtime { type Event = Event; type GetSyntheticBaseAssetId = GetXstPoolConversionAssetId; - type LiquidityProxy = LiquidityProxy; type EnsureDEXManager = DEXManager; type PriceToolsPallet = PriceTools; type WeightInfo = xst::weights::WeightInfo; From e74857111408fe38d5209f9a039fc0d00198038a Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Thu, 12 Jan 2023 16:06:45 +0300 Subject: [PATCH 29/72] Move synthetic asset id generation to primitives Signed-off-by: Daniil Polyakov --- Cargo.lock | 8 +++++++- common/Cargo.toml | 24 ++---------------------- common/src/primitives.rs | 18 ++++++++++++++++++ pallets/xst/Cargo.toml | 2 -- pallets/xst/src/lib.rs | 30 ++++++------------------------ 5 files changed, 33 insertions(+), 49 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 49e927d1c3..b14149dbc8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1590,6 +1590,7 @@ name = "common" version = "0.1.0" dependencies = [ "blake2-rfc", + "fastmurmur3", "fixnum", "frame-support", "frame-system", @@ -3382,6 +3383,12 @@ dependencies = [ "sp-std", ] +[[package]] +name = "fastmurmur3" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d922f481ae01f2a3f1fff7b9e0e789f18f0c755a38ec983a3e6f37762cdcc2a2" + [[package]] name = "fastrand" version = "1.8.0" @@ -13491,7 +13498,6 @@ version = "1.0.1" dependencies = [ "assets", "band", - "blake2 0.10.5", "ceres-liquidity-locker", "common", "demeter-farming-platform", diff --git a/common/Cargo.toml b/common/Cargo.toml index 675af81a4d..e3e08920e8 100644 --- a/common/Cargo.toml +++ b/common/Cargo.toml @@ -43,32 +43,12 @@ sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkad static_assertions = "1.1.0" hex = { version = "*", default-features = false } hex-literal = "0.3.1" +fastmurmur3 = "0.1.2" [dev-dependencies] serde_json = "1.0.41" [features] default = ['std'] -std = [ - 'codec/std', - "scale-info/std", - 'serde', - 'secp256k1/std', - 'rustc-hex/std', - 'blake2-rfc/std', - 'num-traits/std', - 'frame-support/std', - 'frame-system/std', - 'fixnum/std', - 'pallet-timestamp/std', - 'sp-arithmetic/std', - 'sp-core/std', - 'sp-io/std', - 'sp-runtime/std', - 'sp-std/std', - 'currencies/std', - 'orml-traits/std', - 'hex/std', - "fixnum/std", -] +std = ['codec/std', "scale-info/std", 'serde', 'secp256k1/std', 'rustc-hex/std', 'blake2-rfc/std', 'num-traits/std', 'frame-support/std', 'frame-system/std', 'fixnum/std', 'pallet-timestamp/std', 'sp-arithmetic/std', 'sp-core/std', 'sp-io/std', 'sp-runtime/std', 'sp-std/std', 'currencies/std', 'orml-traits/std', 'hex/std', "fixnum/std"] test = [] diff --git a/common/src/primitives.rs b/common/src/primitives.rs index fb24fde91b..8edf7b4136 100644 --- a/common/src/primitives.rs +++ b/common/src/primitives.rs @@ -305,6 +305,24 @@ impl AssetId32 { bytes[2] = asset_id as u8; Self::from_bytes(bytes) } + + /// Construct asset id for synthetic asset using its `reference_symbol` + pub fn from_synthetic_reference_symbol(reference_symbol: &Symbol) -> Self + where + Symbol: PartialEq<&'static str> + Encode, + { + if *reference_symbol == "USD" { + return Self::from_asset_id(PredefinedAssetId::XSTUSD); + } + + let mut bytes = [0u8; 32]; + let symbol_bytes = reference_symbol.encode(); + let symbol_hash = fastmurmur3::hash(&symbol_bytes); + bytes[0] = 3; + bytes[2..18].copy_from_slice(&symbol_hash.to_le_bytes()); + + Self::from_bytes(bytes) + } } impl From for AssetId32 { diff --git a/pallets/xst/Cargo.toml b/pallets/xst/Cargo.toml index d04d514bb7..606f94fbef 100644 --- a/pallets/xst/Cargo.toml +++ b/pallets/xst/Cargo.toml @@ -38,7 +38,6 @@ technical = { path = "../technical", default-features = false } trading-pair = { path = "../trading-pair", default-features = false } pool-xyk = { path = "../pool-xyk", default-features = false } pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } -blake2 = { version = "0.10.5", default-features = false } [dev-dependencies] hex-literal = "0.3.1" @@ -81,5 +80,4 @@ std = [ 'liquidity-proxy/std', 'dex-api/std', 'common/std', - 'blake2/std' ] diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 113006f04e..474af74f33 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -50,7 +50,7 @@ use common::prelude::{ SwapOutcome, DEFAULT_BALANCE_PRECISION, }; use common::{ - balance, fixed_wrapper, AssetName, AssetSymbol, DEXId, DataFeed, GetMarketInfo, + balance, fixed_wrapper, AssetId32, AssetName, AssetSymbol, DEXId, DataFeed, GetMarketInfo, LiquiditySource, LiquiditySourceFilter, LiquiditySourceType, PriceVariant, RewardReason, DAI, XSTUSD, }; @@ -60,7 +60,6 @@ use frame_support::{ensure, fail, RuntimeDebug}; use permissions::{Scope, BURN, MINT}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; -use sp_core::H256; use sp_runtime::DispatchError; use sp_std::collections::btree_set::BTreeSet; use sp_std::vec::Vec; @@ -78,7 +77,6 @@ type Technical = technical::Pallet; pub const TECH_ACCOUNT_PREFIX: &[u8] = b"xst-pool"; pub const TECH_ACCOUNT_PERMISSIONED: &[u8] = b"permissioned"; -pub const SYNTHETIC_ASSET_ID_PREFIX: [u8; 5] = hex_literal::hex!("0200077700"); pub use pallet::*; @@ -442,7 +440,11 @@ impl Pallet { } Self::ensure_symbol_exists(&reference_symbol)?; - let synthetic_asset_id = Self::generate_synthetic_asset_id(&reference_symbol); + let synthetic_asset_id: T::AssetId = + AssetId32::::from_synthetic_reference_symbol( + &reference_symbol, + ) + .into(); Self::register_synthetic_asset(synthetic_asset_id, asset_symbol, asset_name)?; Self::enable_synthetic_pair(synthetic_asset_id)?; @@ -469,26 +471,6 @@ impl Pallet { } } - fn generate_synthetic_asset_id(reference_symbol: &T::Symbol) -> T::AssetId { - // TODO: Maybe we don't need cryptographic hash here, but just a simple hash function. - use blake2::{Blake2s256, Digest}; - - if *reference_symbol == "USD" { - return XSTUSD.into(); - } - - let bytes = reference_symbol.encode(); - let mut hasher = Blake2s256::new(); - hasher.update(bytes); - let mut hashed_bytes = hasher.finalize(); - - hashed_bytes[0..SYNTHETIC_ASSET_ID_PREFIX.len()] - .copy_from_slice(&SYNTHETIC_ASSET_ID_PREFIX); - - let h256 = H256::from_slice(&hashed_bytes); - h256.into() - } - fn enable_synthetic_pair(synthetic_asset_id: T::AssetId) -> sp_runtime::DispatchResult { trading_pair::Pallet::::register_pair( DEXId::Polkaswap.into(), From 4dfd15a05febffeec8303498800d0097f58c034b Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Thu, 12 Jan 2023 16:21:50 +0300 Subject: [PATCH 30/72] Add old base fee storage killing Signed-off-by: Daniil Polyakov --- pallets/xst/src/migrations/mod.rs | 11 ++++++++++- pallets/xst/src/migrations/tests.rs | 6 ++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/pallets/xst/src/migrations/mod.rs b/pallets/xst/src/migrations/mod.rs index 6efac2cf2a..f111e65637 100644 --- a/pallets/xst/src/migrations/mod.rs +++ b/pallets/xst/src/migrations/mod.rs @@ -29,12 +29,17 @@ // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use super::pallet::{Config, Pallet}; -use common::{fixed, XSTUSD}; +use common::generate_storage_instance; +use common::{fixed, Fixed, XSTUSD}; use frame_support::pallet_prelude::{Get, StorageVersion}; +use frame_support::pallet_prelude::{StorageValue, ValueQuery}; use frame_support::{log::info, traits::GetStorageVersion as _, weights::Weight}; use crate::{EnabledSymbols, EnabledSynthetics, SyntheticInfo}; +generate_storage_instance!(PoolXST, BaseFee); +type OldBaseFee = StorageValue; + /// Migration which migrates `XSTUSD` synthetic to the new format. pub fn migrate() -> Weight { if Pallet::::on_chain_storage_version() >= 2 { @@ -42,6 +47,10 @@ pub fn migrate() -> Weight { return 0; } + if OldBaseFee::exists() { + OldBaseFee::kill(); + } + EnabledSynthetics::::insert( T::AssetId::from(XSTUSD), Some(SyntheticInfo { diff --git a/pallets/xst/src/migrations/tests.rs b/pallets/xst/src/migrations/tests.rs index 22c046deb9..6262823ded 100644 --- a/pallets/xst/src/migrations/tests.rs +++ b/pallets/xst/src/migrations/tests.rs @@ -28,14 +28,15 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use crate::{mock::*, pallet::Pallet, EnabledSynthetics}; -use common::{fixed, XSTUSD}; +use crate::{migrations::OldBaseFee, mock::*, pallet::Pallet, EnabledSynthetics}; +use common::{fixed, Fixed, XSTUSD}; use frame_support::traits::{GetStorageVersion as _, StorageVersion}; #[test] fn test() { ExtBuilder::default().build().execute_with(|| { StorageVersion::new(1).put::>(); + OldBaseFee::put::(fixed!(0.00666)); super::migrate::(); @@ -44,6 +45,7 @@ fn test() { assert_eq!(info.reference_symbol, "USD"); assert_eq!(info.fee_ratio, fixed!(0.00666)); + assert!(!OldBaseFee::exists()); assert_eq!(Pallet::::on_chain_storage_version(), 2); }); From ef4d1a76f594818606361b573211ccbfebbcd6d4 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Mon, 16 Jan 2023 14:05:08 +0300 Subject: [PATCH 31/72] Replace `fastmurmur3` with `sp_io::hashing` Signed-off-by: Daniil Polyakov --- Cargo.lock | 7 ------- common/Cargo.toml | 1 - common/src/primitives.rs | 4 ++-- 3 files changed, 2 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c4fc2561e6..5c2d7ceb2b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1590,7 +1590,6 @@ name = "common" version = "0.1.0" dependencies = [ "blake2-rfc", - "fastmurmur3", "fixnum", "frame-support", "frame-system", @@ -3384,12 +3383,6 @@ dependencies = [ "sp-std", ] -[[package]] -name = "fastmurmur3" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d922f481ae01f2a3f1fff7b9e0e789f18f0c755a38ec983a3e6f37762cdcc2a2" - [[package]] name = "fastrand" version = "1.8.0" diff --git a/common/Cargo.toml b/common/Cargo.toml index 9044be0cce..58fe56a7ca 100644 --- a/common/Cargo.toml +++ b/common/Cargo.toml @@ -44,7 +44,6 @@ sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkad static_assertions = "1.1.0" hex = { version = "*", default-features = false } hex-literal = "0.3.1" -fastmurmur3 = "0.1.2" [dev-dependencies] serde_json = "1.0.41" diff --git a/common/src/primitives.rs b/common/src/primitives.rs index f121fa6186..1c4df4f52e 100644 --- a/common/src/primitives.rs +++ b/common/src/primitives.rs @@ -317,9 +317,9 @@ impl AssetId32 { let mut bytes = [0u8; 32]; let symbol_bytes = reference_symbol.encode(); - let symbol_hash = fastmurmur3::hash(&symbol_bytes); + let symbol_hash = sp_io::hashing::blake2_128(&symbol_bytes); bytes[0] = 3; - bytes[2..18].copy_from_slice(&symbol_hash.to_le_bytes()); + bytes[2..18].copy_from_slice(&symbol_hash); Self::from_bytes(bytes) } From 9146ae7ccc4d5239888a394c7d45dcc926d74866 Mon Sep 17 00:00:00 2001 From: Daniil Polyakov Date: Mon, 23 Jan 2023 20:42:37 +0300 Subject: [PATCH 32/72] Improve trait bounds for `xst::Config` Signed-off-by: Daniil Polyakov --- Cargo.lock | 1 + common/src/primitives.rs | 16 ++++++++-------- node/chain_spec/src/lib.rs | 8 ++------ pallets/xst/benchmarking/Cargo.toml | 2 ++ pallets/xst/benchmarking/src/lib.rs | 6 ++++-- pallets/xst/benchmarking/src/mock.rs | 12 ++++++++++-- pallets/xst/src/lib.rs | 18 +++++------------- pallets/xst/src/migrations/mod.rs | 9 ++------- pallets/xst/src/migrations/tests.rs | 2 +- pallets/xst/src/mock.rs | 2 +- pallets/xst/src/tests.rs | 8 +++++--- 11 files changed, 41 insertions(+), 43 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e3131f1fab..4005cd247b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13696,6 +13696,7 @@ dependencies = [ "frame-system", "hex-literal", "mock-liquidity-source", + "oracle-proxy", "orml-currencies", "orml-tokens", "pallet-balances", diff --git a/common/src/primitives.rs b/common/src/primitives.rs index 4a395a9fb8..6711b1c586 100644 --- a/common/src/primitives.rs +++ b/common/src/primitives.rs @@ -268,9 +268,9 @@ impl AssetId32 { /// Construct asset id for synthetic asset using its `reference_symbol` pub fn from_synthetic_reference_symbol(reference_symbol: &Symbol) -> Self where - Symbol: PartialEq<&'static str> + Encode, + Symbol: From + PartialEq + Encode, { - if *reference_symbol == "USD" { + if *reference_symbol == SymbolName::usd().into() { return Self::from_asset_id(PredefinedAssetId::XSTUSD); } @@ -530,6 +530,12 @@ impl IsValid for Description { #[cfg_attr(feature = "std", derive(Hash))] pub struct SymbolName(pub Vec); +impl SymbolName { + pub fn usd() -> Self { + Self::from_str("USD").expect("`USD` is a valid symbol name") + } +} + impl FromStr for SymbolName { type Err = &'static str; @@ -565,12 +571,6 @@ impl IsValid for SymbolName { } } -impl PartialEq<&'static str> for SymbolName { - fn eq(&self, other: &&'static str) -> bool { - self.0 == other.as_bytes() - } -} - #[derive( Encode, Decode, Eq, PartialEq, PartialOrd, Ord, Debug, Copy, Clone, Hash, scale_info::TypeInfo, )] diff --git a/node/chain_spec/src/lib.rs b/node/chain_spec/src/lib.rs index 9fbd96907e..093b4e9281 100644 --- a/node/chain_spec/src/lib.rs +++ b/node/chain_spec/src/lib.rs @@ -1248,9 +1248,7 @@ fn testnet_genesis( initial_synthetic_assets: vec![( AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), - "USD" - .parse() - .expect("`USD` should be a valid reference symbol"), + common::SymbolName::usd().into(), fixed!(0.00666), )], }, @@ -1975,9 +1973,7 @@ fn mainnet_genesis( initial_synthetic_assets: vec![( AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), - "USD" - .parse() - .expect("`USD` should be a valid reference symbol"), + common::SymbolName::usd().into(), fixed!(0.00666), )], }, diff --git a/pallets/xst/benchmarking/Cargo.toml b/pallets/xst/benchmarking/Cargo.toml index 1f340b3cdd..12d5459935 100644 --- a/pallets/xst/benchmarking/Cargo.toml +++ b/pallets/xst/benchmarking/Cargo.toml @@ -27,6 +27,7 @@ mock-liquidity-source = { path = "../../mock-liquidity-source", default-features technical = { path = "../../technical", default-features = false } trading-pair = { path = "../../trading-pair", default-features = false } band = { path = "../../band", default-features = false } +oracle-proxy = {path = "../../oracle-proxy", default-features = false} xst = {path = "../../xst", default-features = false } [dev-dependencies] @@ -62,5 +63,6 @@ std = [ "technical/std", "trading-pair/std", "band/std", + "oracle-proxy/std", "xst/std", ] diff --git a/pallets/xst/benchmarking/src/lib.rs b/pallets/xst/benchmarking/src/lib.rs index 9b9470add2..53b7418c9f 100644 --- a/pallets/xst/benchmarking/src/lib.rs +++ b/pallets/xst/benchmarking/src/lib.rs @@ -34,11 +34,12 @@ use band::Pallet as Band; use codec::{Decode as _, Encode as _}; -use common::{balance, fixed, AssetName, AssetSymbol, DAI}; +use common::{balance, fixed, AssetName, AssetSymbol, Oracle, DAI}; use frame_benchmarking::benchmarks; use frame_support::pallet_prelude::DispatchResultWithPostInfo; use frame_system::{EventRecord, RawOrigin}; use hex_literal::hex; +use oracle_proxy::Pallet as OracleProxy; use sp_std::prelude::*; use xst::{Call, Event, Pallet as XSTPool}; @@ -71,6 +72,7 @@ mod utils { } pub fn relay_symbol() -> DispatchResultWithPostInfo { + OracleProxy::::enable_oracle(RawOrigin::Root.into(), Oracle::BandChainFeed)?; Band::::add_relayers(RawOrigin::Root.into(), vec![alice::()])?; Band::::relay( RawOrigin::Signed(alice::()).into(), @@ -98,7 +100,7 @@ mod utils { } } pub struct Pallet(xst::Pallet); -pub trait Config: xst::Config + band::Config {} +pub trait Config: xst::Config + band::Config + oracle_proxy::Config {} benchmarks! { set_reference_asset { diff --git a/pallets/xst/benchmarking/src/mock.rs b/pallets/xst/benchmarking/src/mock.rs index 8f5840fe7c..3331316789 100644 --- a/pallets/xst/benchmarking/src/mock.rs +++ b/pallets/xst/benchmarking/src/mock.rs @@ -118,6 +118,7 @@ construct_runtime! { PswapDistribution: pswap_distribution::{Pallet, Call, Storage, Event}, DEXApi: dex_api::{Pallet, Storage}, Band: band::{Pallet, Call, Storage, Event}, + OracleProxy: oracle_proxy::{Pallet, Call, Storage, Event}, CeresLiquidityLocker: ceres_liquidity_locker::{Pallet, Call, Storage, Event}, DemeterFarmingPlatform: demeter_farming_platform::{Pallet, Call, Storage, Event}, } @@ -169,18 +170,25 @@ impl xst::Config for Runtime { type GetSyntheticBaseAssetId = GetSyntheticBaseAssetId; type EnsureDEXManager = dex_manager::Pallet; type PriceToolsPallet = MockDEXApi; - type Oracle = band::Pallet; // TODO: Replace with oracle-proxy + type Oracle = OracleProxy; type Symbol = ::Symbol; type WeightInfo = (); } impl band::Config for Runtime { type Event = Event; - type Symbol = String; + type Symbol = common::SymbolName; type WeightInfo = (); type OnNewSymbolsRelayedHook = (); } +impl oracle_proxy::Config for Runtime { + type Event = Event; + type WeightInfo = (); + type Symbol = ::Symbol; + type BandChainOracle = Band; +} + impl tokens::Config for Runtime { type Event = Event; type Balance = Balance; diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index a7f98d4192..84662f2547 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -128,8 +128,6 @@ pub struct SyntheticInfo { #[frame_support::pallet] pub mod pallet { - use core::str::FromStr; - use super::*; use frame_support::traits::StorageVersion; use frame_support::{pallet_prelude::*, Parameter}; @@ -144,7 +142,7 @@ pub mod pallet { type PriceToolsPallet: PriceToolsPallet; type Oracle: DataFeed; /// Type of symbol received from oracles - type Symbol: Parameter + FromStr + PartialEq<&'static str> + MaybeSerializeDeserialize; + type Symbol: Parameter + From + MaybeSerializeDeserialize; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } @@ -374,10 +372,7 @@ pub mod pallet { } #[cfg(feature = "std")] - impl Default for GenesisConfig - where - ::Err: core::fmt::Debug, - { + impl Default for GenesisConfig { fn default() -> Self { Self { tech_account_id: Default::default(), @@ -385,7 +380,7 @@ pub mod pallet { initial_synthetic_assets: [( AssetSymbol(b"XSTUSD".to_vec()), AssetName(b"SORA Synthetic USD".to_vec()), - T::Symbol::from_str("USD").expect("`USD` should be a valid symbol name"), + common::SymbolName::usd().into(), common::fixed!(0.00666), )] .into(), @@ -394,10 +389,7 @@ pub mod pallet { } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig - where - ::Err: core::fmt::Debug, - { + impl GenesisBuild for GenesisConfig { fn build(&self) { PermissionedTechAccount::::put(&self.tech_account_id); ReferenceAssetId::::put(&self.reference_asset_id); @@ -835,7 +827,7 @@ impl Pallet { } fn ensure_symbol_exists(reference_symbol: &T::Symbol) -> Result<(), DispatchError> { - if *reference_symbol == "USD" { + if *reference_symbol == common::SymbolName::usd().into() { return Ok(()); } diff --git a/pallets/xst/src/migrations/mod.rs b/pallets/xst/src/migrations/mod.rs index 0b7b8c615c..4d02a1431a 100644 --- a/pallets/xst/src/migrations/mod.rs +++ b/pallets/xst/src/migrations/mod.rs @@ -31,8 +31,6 @@ use super::pallet::{Config, Pallet}; use common::generate_storage_instance; use common::{fixed, Fixed, XSTUSD}; -use core::fmt::Debug; -use core::str::FromStr; use frame_support::pallet_prelude::{Get, StorageVersion}; use frame_support::pallet_prelude::{StorageValue, ValueQuery}; use frame_support::{log::info, traits::GetStorageVersion as _, weights::Weight}; @@ -43,10 +41,7 @@ generate_storage_instance!(PoolXST, BaseFee); type OldBaseFee = StorageValue; /// Migration which migrates `XSTUSD` synthetic to the new format. -pub fn migrate() -> Weight -where - ::Err: Debug, -{ +pub fn migrate() -> Weight { if Pallet::::on_chain_storage_version() >= 2 { info!("Migration to version 2 has already been applied"); return 0; @@ -56,7 +51,7 @@ where OldBaseFee::kill(); } - let xstusd_symbol = T::Symbol::from_str("USD").expect("`USD` should be a valid symbol name"); + let xstusd_symbol = T::Symbol::from(common::SymbolName::usd()); EnabledSynthetics::::insert( T::AssetId::from(XSTUSD), diff --git a/pallets/xst/src/migrations/tests.rs b/pallets/xst/src/migrations/tests.rs index 6262823ded..be1d02ebe5 100644 --- a/pallets/xst/src/migrations/tests.rs +++ b/pallets/xst/src/migrations/tests.rs @@ -43,7 +43,7 @@ fn test() { let info = EnabledSynthetics::::get(XSTUSD) .expect("XSTUSD synthetic should be enabled after migration"); - assert_eq!(info.reference_symbol, "USD"); + assert_eq!(info.reference_symbol, common::SymbolName::usd().into()); assert_eq!(info.fee_ratio, fixed!(0.00666)); assert!(!OldBaseFee::exists()); diff --git a/pallets/xst/src/mock.rs b/pallets/xst/src/mock.rs index e75e31ee93..61b43f1af6 100644 --- a/pallets/xst/src/mock.rs +++ b/pallets/xst/src/mock.rs @@ -177,7 +177,7 @@ impl Config for Runtime { impl band::Config for Runtime { type Event = Event; - type Symbol = String; + type Symbol = common::SymbolName; type WeightInfo = (); type OnNewSymbolsRelayedHook = oracle_proxy::Pallet; } diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index 8a8e89181f..8295282e37 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -30,8 +30,10 @@ #[rustfmt::skip] mod tests { + use core::str::FromStr; + use crate::{Error, Pallet, mock::*}; - use common::{self, AssetName, AssetSymbol, DEXId, FromGenericPair, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, prelude::{Balance, SwapAmount, QuoteAmount,}, GetMarketInfo, Oracle }; + use common::{self, AssetName, AssetSymbol, DEXId, FromGenericPair, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, prelude::{Balance, SwapAmount, QuoteAmount,}, GetMarketInfo, Oracle, SymbolName }; use frame_support::assert_ok; use frame_support::assert_noop; use sp_arithmetic::traits::{Zero}; @@ -622,7 +624,7 @@ use frame_support::assert_noop; MockDEXApi::init().unwrap(); let _ = xst_pool_init().unwrap(); - let euro = "EURO".to_owned(); + let euro = SymbolName::from_str("EURO").expect("Failed to parse `EURO` as a symbol name"); let alice = alice(); OracleProxy::enable_oracle(Origin::root(), Oracle::BandChainFeed).expect("Failed to enable `Band` oracle"); @@ -663,7 +665,7 @@ use frame_support::assert_noop; MockDEXApi::init().unwrap(); let _ = xst_pool_init().unwrap(); - let euro = "EURO".to_owned(); + let euro = SymbolName::from_str("EURO").expect("Failed to parse `EURO` as a symbol name"); let alice = alice(); OracleProxy::enable_oracle(Origin::root(), Oracle::BandChainFeed).expect("Failed to enable `Band` oracle"); From 4f3e71219d4fa987beb761a014433ebfb0060754 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Fri, 10 Feb 2023 00:35:37 +0400 Subject: [PATCH 33/72] quickfix --- node/chain_spec/src/lib.rs | 12 ------------ runtime/src/lib.rs | 2 +- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/node/chain_spec/src/lib.rs b/node/chain_spec/src/lib.rs index 4b74efc8ab..01fe71b670 100644 --- a/node/chain_spec/src/lib.rs +++ b/node/chain_spec/src/lib.rs @@ -916,7 +916,6 @@ fn testnet_genesis( XST.into(), TBCD.into(), ]; - let initial_synthetic_assets = vec![XSTUSD.into()]; GenesisConfig { system: SystemConfig { code: WASM_BINARY.unwrap_or_default().to_vec(), @@ -1061,17 +1060,6 @@ fn testnet_genesis( None, None, ), - ( - XSTUSD.into(), - assets_and_permissions_account_id.clone(), - AssetSymbol(b"XSTUSD".to_vec()), - AssetName(b"SORA Synthetic USD".to_vec()), - DEFAULT_BALANCE_PRECISION, - Balance::zero(), - true, - None, - None, - ), ( common::AssetId32::from_bytes(hex!( "008bcfd2387d3fc453333557eecb0efe59fcba128769b2feefdd306e98e66440" diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 419071b75c..68231ba02b 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -2719,7 +2719,7 @@ impl_runtime_apis! { add_benchmark!(params, batches, ceres_launchpad, CeresLaunchpad); add_benchmark!(params, batches, demeter_farming_platform, DemeterFarmingPlatformBench::); add_benchmark!(params, batches, band, Band); - add_benchmark!(params, batches, xst, XSTPool); + add_benchmark!(params, batches, xst, XSTPoolBench::); add_benchmark!(params, batches, hermes_governance_platform, HermesGovernancePlatform); add_benchmark!(params, batches, oracle_proxy, OracleProxy); From 49bf6cc0f9d71f743d629a9a1a5d63404a95dc88 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 13 Feb 2023 14:21:32 +0400 Subject: [PATCH 34/72] remove unnecessary imports --- pallets/xst/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 84662f2547..95fec311fa 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -44,7 +44,6 @@ use core::convert::TryInto; use assets::AssetIdOf; use codec::{Decode, Encode}; -use common::fixnum::ops::Zero as _; use common::prelude::{ Balance, EnsureDEXManager, Fixed, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapAmount, SwapOutcome, DEFAULT_BALANCE_PRECISION, From 37dda2e1cc9184fdaa103431a9ab4798bfecc132 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 13 Feb 2023 14:23:45 +0400 Subject: [PATCH 35/72] fix --- pallets/xst/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 95fec311fa..84662f2547 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -44,6 +44,7 @@ use core::convert::TryInto; use assets::AssetIdOf; use codec::{Decode, Encode}; +use common::fixnum::ops::Zero as _; use common::prelude::{ Balance, EnsureDEXManager, Fixed, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapAmount, SwapOutcome, DEFAULT_BALANCE_PRECISION, From c77e6875ce4aa19e06ffc1946128addbc3f45b70 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Tue, 14 Feb 2023 13:32:59 +0400 Subject: [PATCH 36/72] fix --- node/chain_spec/src/lib.rs | 2 -- pallets/referrals/Cargo.toml | 10 ++++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/node/chain_spec/src/lib.rs b/node/chain_spec/src/lib.rs index 01fe71b670..1c13ba2b5a 100644 --- a/node/chain_spec/src/lib.rs +++ b/node/chain_spec/src/lib.rs @@ -1442,8 +1442,6 @@ fn mainnet_genesis( council_accounts: Vec, technical_committee_accounts: Vec, ) -> GenesisConfig { - use common::fixnum::ops::Zero as _; - // Minimum stake for an active validator let initial_staking = balance!(0.2); // XOR amount which already exists on Ethereum diff --git a/pallets/referrals/Cargo.toml b/pallets/referrals/Cargo.toml index 0d95a12697..a30d1c91a2 100644 --- a/pallets/referrals/Cargo.toml +++ b/pallets/referrals/Cargo.toml @@ -28,10 +28,10 @@ traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library [dev-dependencies] common = { path = "../../common", features = ["test"] } -pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } -sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } -sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25" } +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25" } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25" } tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-tokens" } currencies = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-currencies" } permissions = { path = "../permissions" } @@ -50,6 +50,8 @@ runtime-benchmarks = [ std = [ "codec/std", "scale-info/std", + "assets/std", + "common/std", "frame-benchmarking/std", "frame-support/std", "frame-system/std", From c171811c09ece8c7fdf86094b2a3867ccd06320d Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Tue, 14 Feb 2023 14:37:55 +0400 Subject: [PATCH 37/72] removed XSTUSD from Assets pallet init (initialized in XST palllet) --- Cargo.lock | 689 ++++++++++++++++++++----------------- node/chain_spec/src/lib.rs | 11 - 2 files changed, 365 insertions(+), 335 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 236e41dc9a..9c0741edf0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -27,7 +27,7 @@ version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a76fd60b23679b7d19bd066031410fb7e458ccc5e958eb5c325888ce4baedc97" dependencies = [ - "gimli 0.27.0", + "gimli 0.27.1", ] [[package]] @@ -82,6 +82,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "ahash" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" +dependencies = [ + "cfg-if 1.0.0", + "once_cell", + "version_check", +] + [[package]] name = "aho-corasick" version = "0.7.20" @@ -111,9 +122,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.68" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cb2f989d18dd141ab8ae82f64d1a8cdd37e0840f73a406896cf5e99502fab61" +checksum = "224afbd727c3d6e4b90103ece64b8d1b67fbb1973b1046c2281eed3f3803f800" [[package]] name = "approx" @@ -302,7 +313,7 @@ dependencies = [ "slab", "socket2", "waker-fn", - "windows-sys", + "windows-sys 0.42.0", ] [[package]] @@ -330,7 +341,7 @@ dependencies = [ "futures-lite", "libc", "signal-hook", - "windows-sys", + "windows-sys 0.42.0", ] [[package]] @@ -384,9 +395,9 @@ checksum = "7a40729d2133846d9ed0ea60a8b9541bccddab49cd30f0715a1da672fe9a2524" [[package]] name = "async-trait" -version = "0.1.61" +version = "0.1.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "705339e0e4a9690e2908d2b3d049d85682cf19fbd5782494498fbf7003a6a282" +checksum = "1cd7fce9ba8c3c042128ce72d8b2ddbf3a05747efb67ea0313c635e10bda47a2" dependencies = [ "proc-macro2", "quote", @@ -399,7 +410,7 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d7b9decdf35d8908a7e3ef02f64c5e9b1695e230154c0e8de3969142d9b94c" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "pharos", "rustc_version 0.4.0", ] @@ -419,9 +430,9 @@ dependencies = [ [[package]] name = "atomic-waker" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "065374052e7df7ee4047b1160cca5e1467a12351a40b3da123c870ba0b8eda2a" +checksum = "debc29dde2e69f9e47506b525f639ed42300fc014a3e007832592448fa8e4599" [[package]] name = "atty" @@ -472,7 +483,7 @@ dependencies = [ "cfg-if 1.0.0", "libc", "miniz_oxide", - "object 0.30.2", + "object 0.30.3", "rustc-demangle", ] @@ -621,7 +632,7 @@ source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25- dependencies = [ "beefy-primitives", "fnv", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "hex", "log", @@ -655,7 +666,7 @@ source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25- dependencies = [ "beefy-gadget", "beefy-primitives", - "futures 0.3.25", + "futures 0.3.26", "jsonrpsee", "log", "parity-scale-codec", @@ -802,24 +813,24 @@ dependencies = [ [[package]] name = "blake2b_simd" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72936ee4afc7f8f736d1c38383b56480b5497b4617b4a77bdbf1d2ababc76127" +checksum = "3c2f0dc9a68c6317d884f97cc36cf5a3d20ba14ce404227df55e1af708ab04bc" dependencies = [ "arrayref", "arrayvec 0.7.2", - "constant_time_eq 0.1.5", + "constant_time_eq 0.2.4", ] [[package]] name = "blake2s_simd" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db539cc2b5f6003621f1cd9ef92d7ded8ea5232c7de0f9faa2de251cd98730d4" +checksum = "6637f448b9e61dfadbdcbae9a885fadee1f3eaffb1f8d3c1965d3ade8bdfd44f" dependencies = [ "arrayref", "arrayvec 0.7.2", - "constant_time_eq 0.1.5", + "constant_time_eq 0.2.4", ] [[package]] @@ -897,19 +908,19 @@ dependencies = [ [[package]] name = "borsh" -version = "0.9.3" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15bf3650200d8bffa99015595e10f1fbd17de07abbc25bb067da79e769939bfa" +checksum = "a3ef05d137e34b7ac51dbec170ee523a9b728cff71385796771d259771d592f8" dependencies = [ "borsh-derive", - "hashbrown 0.11.2", + "hashbrown 0.13.2", ] [[package]] name = "borsh-derive" -version = "0.9.3" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6441c552f230375d18e3cc377677914d2ca2b0d36e52129fe15450a2dce46775" +checksum = "190b1188f062217531748807129459c8c14641b648e887e39681a433db7fc939" dependencies = [ "borsh-derive-internal", "borsh-schema-derive-internal", @@ -920,9 +931,9 @@ dependencies = [ [[package]] name = "borsh-derive-internal" -version = "0.9.3" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5449c28a7b352f2d1e592a8a28bf139bc71afb0764a14f3c02500935d8c44065" +checksum = "b0fcf747a3e4eb47869441664df09d0eb88dcc9a85d499860efb82c2cfe6affc" dependencies = [ "proc-macro2", "quote", @@ -931,9 +942,9 @@ dependencies = [ [[package]] name = "borsh-schema-derive-internal" -version = "0.9.3" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdbd5696d8bfa21d53d9fe39a714a18538bad11492a42d066dbbc395fb1951c0" +checksum = "f671d085f791c5fd3331c843ded45454b034b6188bf0f78ed28e7fd66a8b3f69" dependencies = [ "proc-macro2", "quote", @@ -979,9 +990,9 @@ checksum = "771fe0050b883fcc3ea2359b1a96bcfbc090b7116eae7c3c512c7a083fdf23d3" [[package]] name = "bstr" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b45ea9b00a7b3f2988e9a65ad3917e62123c38dba709b666506207be96d1790b" +checksum = "b7f0778972c64420fdedc63f09919c8a88bda7b25135357fd25a5d9f3257e832" dependencies = [ "memchr", "serde", @@ -998,9 +1009,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.11.1" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "572f695136211188308f16ad2ca5c851a712c464060ae6974944458eb83880ba" +checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535" [[package]] name = "byte-slice-cast" @@ -1043,9 +1054,9 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "bytes" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfb24e866b15a1af2a1b663f10c6b6b8f397a84aadb828f12e5b289ec23a3a3c" +checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" dependencies = [ "serde", ] @@ -1104,9 +1115,9 @@ dependencies = [ [[package]] name = "cargo_metadata" -version = "0.15.2" +version = "0.15.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "982a0cf6a99c350d7246035613882e376d58cebe571785abc5da4f648d53ac0a" +checksum = "08a1ec454bc3eead8719cb56e15dbbfecdbc14e4b3a3ae4936cc6e31f5fc0d07" dependencies = [ "camino", "cargo-platform", @@ -1118,9 +1129,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.78" +version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a20104e2335ce8a659d6dd92a51a767a0c062599c73b343fd152cb401e828c3d" +checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" dependencies = [ "jobserver", ] @@ -1479,7 +1490,7 @@ version = "3.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea0c8bce528c4be4da13ea6fead8965e95b6073585a2f05204bd8f4119f82a65" dependencies = [ - "heck 0.4.0", + "heck 0.4.1", "proc-macro-error", "proc-macro2", "quote", @@ -1635,9 +1646,9 @@ dependencies = [ [[package]] name = "concurrent-queue" -version = "2.0.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd7bef69dc86e3c610e4e7aed41035e2a7ed12e72dd7530f61327a6579a4390b" +checksum = "c278839b831783b70278b14df4d45e1beb1aad306c07bb796637de9a0e323e8e" dependencies = [ "crossbeam-utils", ] @@ -1659,14 +1670,14 @@ dependencies = [ [[package]] name = "console" -version = "0.15.4" +version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9b6515d269224923b26b5febea2ed42b2d5f2ce37284a4dd670fedd6cb8347a" +checksum = "c3d79fbe8970a77e3e34151cc13d3b3e248aa0faaecb9f6091fa07ebefe5ad60" dependencies = [ "encode_unicode", "lazy_static", "libc", - "windows-sys", + "windows-sys 0.42.0", ] [[package]] @@ -2005,9 +2016,9 @@ dependencies = [ [[package]] name = "curve25519-dalek" -version = "4.0.0-pre.5" +version = "4.0.0-rc.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67bc65846be335cb20f4e52d49a437b773a2c1fdb42b19fc84e79e6f6771536f" +checksum = "8da00a7a9a4eb92a0a0f8e75660926d48f0d0f3c537e455c457bcdaa1e16b1ac" dependencies = [ "cfg-if 1.0.0", "fiat-crypto", @@ -2019,9 +2030,9 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.86" +version = "1.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d1075c37807dcf850c379432f0df05ba52cc30f279c5cfc43cc221ce7f8579" +checksum = "90d59d9acd2a682b4e40605a242f6670eaa58c5957471cbf85e8aa6a0b97a5e8" dependencies = [ "cc", "cxxbridge-flags", @@ -2031,9 +2042,9 @@ dependencies = [ [[package]] name = "cxx-build" -version = "1.0.86" +version = "1.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5044281f61b27bc598f2f6647d480aed48d2bf52d6eb0b627d84c0361b17aa70" +checksum = "ebfa40bda659dd5c864e65f4c9a2b0aff19bea56b017b9b77c73d3766a453a38" dependencies = [ "cc", "codespan-reporting", @@ -2046,15 +2057,15 @@ dependencies = [ [[package]] name = "cxxbridge-flags" -version = "1.0.86" +version = "1.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61b50bc93ba22c27b0d31128d2d130a0a6b3d267ae27ef7e4fae2167dfe8781c" +checksum = "457ce6757c5c70dc6ecdbda6925b958aae7f959bda7d8fb9bde889e34a09dc03" [[package]] name = "cxxbridge-macro" -version = "1.0.86" +version = "1.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e61fda7e62115119469c7b3591fd913ecca96fb766cfd3f2e2502ab7bc87a5" +checksum = "ebf883b7aacd7b2aeb2a7b338648ee19f57c140d4ee8e52c68979c6b2f7f2263" dependencies = [ "proc-macro2", "quote", @@ -2063,9 +2074,9 @@ dependencies = [ [[package]] name = "darling" -version = "0.14.2" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0dd3cd20dc6b5a876612a6e5accfe7f3dd883db6d07acfbf14c128f61550dfa" +checksum = "c0808e1bd8671fb44a113a14e13497557533369847788fa2ae912b6ebfce9fa8" dependencies = [ "darling_core", "darling_macro", @@ -2073,9 +2084,9 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.14.2" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a784d2ccaf7c98501746bf0be29b2022ba41fd62a2e622af997a03e9f972859f" +checksum = "001d80444f28e193f30c2f293455da62dcf9a6b29918a4253152ae2b1de592cb" dependencies = [ "fnv", "ident_case", @@ -2087,9 +2098,9 @@ dependencies = [ [[package]] name = "darling_macro" -version = "0.14.2" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7618812407e9402654622dd402b0a89dff9ba93badd6540781526117b92aab7e" +checksum = "b36230598a2d5de7ec1c6f51f72d8a99a9208daff41de2084d06e3fd3ea56685" dependencies = [ "darling_core", "quote", @@ -2536,9 +2547,9 @@ dependencies = [ [[package]] name = "ed25519" -version = "1.5.2" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e9c280362032ea4203659fc489832d0204ef09f247a0506f170dafcac08c369" +checksum = "91cff35c70bba8a626e3185d8cd48cc11b5437e1a5bcd15b9b5fa3c64b6dfee7" dependencies = [ "signature", ] @@ -2570,9 +2581,9 @@ dependencies = [ [[package]] name = "either" -version = "1.8.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797" +checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" [[package]] name = "elliptic-curve" @@ -2609,9 +2620,9 @@ checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" [[package]] name = "encoding_rs" -version = "0.8.31" +version = "0.8.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b" +checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394" dependencies = [ "cfg-if 1.0.0", ] @@ -2622,7 +2633,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21cdad81446a7f7dc43f6a77409efeb9733d2fa65553efef6018ef257c959b73" dependencies = [ - "heck 0.4.0", + "heck 0.4.1", "proc-macro2", "quote", "syn", @@ -3168,7 +3179,7 @@ source = "git+https://github.com/sora-xor/ethers-rs?branch=polkadot-v0.9.25#6fd4 dependencies = [ "arrayvec 0.7.2", "bytes", - "cargo_metadata 0.15.2", + "cargo_metadata 0.15.3", "chrono", "convert_case 0.5.0", "elliptic-curve", @@ -3327,7 +3338,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e43f2f1833d64e33f15592464d6fdd70f349dda7b1a53088eb83cd94014008c5" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", ] [[package]] @@ -3415,9 +3426,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "1.8.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499" +checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" dependencies = [ "instant", ] @@ -3486,14 +3497,14 @@ dependencies = [ [[package]] name = "filetime" -version = "0.2.19" +version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e884668cd0c7480504233e951174ddc3b382f7c2666e3b7310b5c4e7b0c37f9" +checksum = "8a3de6e8d11b22ff9edc6d916f890800597d60f8b2da1caf2955c274638d6412" dependencies = [ "cfg-if 1.0.0", "libc", "redox_syscall 0.2.16", - "windows-sys", + "windows-sys 0.45.0", ] [[package]] @@ -3503,7 +3514,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e24e6c429951433ccb7c87fd528c60084834dcd14763182c1f83291bcde24c34" dependencies = [ "either", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "log", "num-traits", @@ -3666,7 +3677,7 @@ name = "frame-election-provider-solution-type" version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "proc-macro-crate 1.2.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn", @@ -3764,7 +3775,7 @@ version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "frame-support-procedural-tools-derive", - "proc-macro-crate 1.2.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn", @@ -3843,7 +3854,7 @@ dependencies = [ "frame-benchmarking-cli", "framenode-chain-spec", "framenode-runtime", - "futures 0.3.25", + "futures 0.3.26", "iroha-migration", "iroha-migration-rpc", "jsonrpsee", @@ -4076,9 +4087,9 @@ dependencies = [ [[package]] name = "fs_extra" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2022715d62ab30faffd124d40b76f4134a550a87792276512b18d63272333394" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fuchsia-cprng" @@ -4100,9 +4111,9 @@ checksum = "3a471a38ef8ed83cd6e40aa59c1ffe17db6855c18e3604d9c4ed8c08ebc28678" [[package]] name = "futures" -version = "0.3.25" +version = "0.3.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38390104763dc37a5145a53c29c63c1290b5d316d6086ec32c293f6736051bb0" +checksum = "13e2792b0ff0340399d58445b88fd9770e3489eff258a4cbc1523418f12abf84" dependencies = [ "futures-channel", "futures-core", @@ -4115,9 +4126,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.25" +version = "0.3.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ba265a92256105f45b719605a571ffe2d1f0fea3807304b522c1d778f79eed" +checksum = "2e5317663a9089767a1ec00a487df42e0ca174b61b4483213ac24448e4664df5" dependencies = [ "futures-core", "futures-sink", @@ -4125,15 +4136,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.25" +version = "0.3.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac" +checksum = "ec90ff4d0fe1f57d600049061dc6bb68ed03c7d2fbd697274c41805dcb3f8608" [[package]] name = "futures-executor" -version = "0.3.25" +version = "0.3.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7acc85df6714c176ab5edf386123fafe217be88c0840ec11f199441134a074e2" +checksum = "e8de0a35a6ab97ec8869e32a2473f4b1324459e14c29275d14b10cb1fd19b50e" dependencies = [ "futures-core", "futures-task", @@ -4143,9 +4154,9 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.25" +version = "0.3.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00f5fb52a06bdcadeb54e8d3671f8888a39697dcb0b81b23b55174030427f4eb" +checksum = "bfb8371b6fb2aeb2d280374607aeabfc99d95c72edfe51692e42d3d7f0d08531" [[package]] name = "futures-lite" @@ -4175,9 +4186,9 @@ dependencies = [ [[package]] name = "futures-macro" -version = "0.3.25" +version = "0.3.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdfb8ce053d86b91919aad980c220b1fb8401a9394410e1c289ed7e66b61835d" +checksum = "95a73af87da33b5acf53acfebdc339fe592ecf5357ac7c0a7734ab9d8c876a70" dependencies = [ "proc-macro2", "quote", @@ -4197,15 +4208,15 @@ dependencies = [ [[package]] name = "futures-sink" -version = "0.3.25" +version = "0.3.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39c15cf1a4aa79df40f1bb462fb39676d0ad9e366c2a33b590d7c66f4f81fcf9" +checksum = "f310820bb3e8cfd46c80db4d7fb8353e15dfff853a127158425f31e0be6c8364" [[package]] name = "futures-task" -version = "0.3.25" +version = "0.3.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ffb393ac5d9a6eaa9d3fdf37ae2776656b706e200c8e16b1bdb227f5198e6ea" +checksum = "dcf79a1bf610b10f42aea489289c5a2c478a786509693b80cd39c44ccd936366" [[package]] name = "futures-timer" @@ -4215,9 +4226,9 @@ checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" [[package]] name = "futures-util" -version = "0.3.25" +version = "0.3.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6" +checksum = "9c1d6de3acfef38d2be4b1f543f553131788603495be83da675e180c8d6b7bd1" dependencies = [ "futures 0.1.31", "futures-channel", @@ -4335,9 +4346,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.27.0" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dec7af912d60cdbd3677c1af9352ebae6fb8394d165568a2234df0fa00f87793" +checksum = "221996f774192f0f718773def8201c4ae31f02616a54ccfc2d358bb0e5cefdec" [[package]] name = "git2" @@ -4373,9 +4384,9 @@ dependencies = [ [[package]] name = "gloo-timers" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98c4a8d6391675c6b2ee1a6c8d06e8e2d03605c44cec1270675985a4c2a5500b" +checksum = "9b995a66bb87bebce9a0f4a95aed01daca4872c050bfcb21653361c03bc35e5c" dependencies = [ "futures-channel", "futures-core", @@ -4450,20 +4461,20 @@ checksum = "29fba9abe4742d586dfd0c06ae4f7e73a1c2d86b856933509b269d82cdf06e18" [[package]] name = "hashbrown" -version = "0.11.2" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" dependencies = [ - "ahash", + "ahash 0.7.6", ] [[package]] name = "hashbrown" -version = "0.12.3" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" dependencies = [ - "ahash", + "ahash 0.8.3", ] [[package]] @@ -4495,9 +4506,9 @@ dependencies = [ [[package]] name = "heck" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" [[package]] name = "hermes-governance-platform" @@ -4553,6 +4564,12 @@ dependencies = [ "libc", ] +[[package]] +name = "hermit-abi" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" + [[package]] name = "hex" version = "0.4.3" @@ -4676,9 +4693,9 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" [[package]] name = "hyper" -version = "0.14.23" +version = "0.14.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "034711faac9d2166cb1baf1a2fb0b60b1f277f8492fd72176c17f3515e1abd3c" +checksum = "5e011372fa0b68db8350aa7a248930ecc7839bf46d8485577d69f117a75f164c" dependencies = [ "bytes", "futures-channel", @@ -4784,7 +4801,7 @@ dependencies = [ "async-io", "core-foundation", "fnv", - "futures 0.3.25", + "futures 0.3.26", "if-addrs", "ipnet", "log", @@ -4904,7 +4921,7 @@ version = "0.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d207dc617c7a380ab07ff572a6e52fa202a2a8f355860ac9c38e23f8196be1b" dependencies = [ - "console 0.15.4", + "console 0.15.5", "lazy_static", "number_prefix", "regex", @@ -4948,12 +4965,12 @@ checksum = "ec58677acfea8a15352d42fc87d11d63596ade9239e0a7c9352914417515dbe6" [[package]] name = "io-lifetimes" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7d6c6f8c91b4b9ed43484ad1a938e393caf35960fce7f82a040497207bd8e9e" +checksum = "1abeb7a0dd0f8181267ff8adc397075586500b81b28a73e8a0208b00fc170fb3" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.45.0", ] [[package]] @@ -5033,14 +5050,14 @@ dependencies = [ [[package]] name = "is-terminal" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dfb6c8100ccc63462345b67d1bbc3679177c75ee4bf59bf29c8b1d110b8189" +checksum = "22e18b0a45d56fe973d6db23972bf5bc46f988a4a2385deac9cc29572f09daef" dependencies = [ - "hermit-abi 0.2.6", - "io-lifetimes 1.0.4", - "rustix 0.36.6", - "windows-sys", + "hermit-abi 0.3.1", + "io-lifetimes 1.0.5", + "rustix 0.36.8", + "windows-sys 0.45.0", ] [[package]] @@ -5069,9 +5086,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.60" +version = "0.3.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49409df3e3bf0856b916e2ceaca09ee28e6871cf7d9ce97a692cacfdb2a25a47" +checksum = "445dde2150c55e483f3d8416706b97ec8e8237c307e5b7b4b8dd15e6af2a0730" dependencies = [ "wasm-bindgen", ] @@ -5081,7 +5098,7 @@ name = "jsonrpc-core" version = "17.0.0" source = "git+https://github.com/sora-xor/jsonrpc.git?branch=no-std#ef5d2846b52f7d7202b381be4936a75dd34fed49" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "log", "serde", "serde_derive", @@ -5198,7 +5215,7 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "874cf3f6a027cebf36cae767feca9aa2e8a8f799880e49eb5540819fcbd8eada" dependencies = [ - "proc-macro-crate 1.2.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn", @@ -5496,7 +5513,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41726ee8f662563fafba2d2d484b14037cc8ecb8c953fbfc8439d4ce3a0a9029" dependencies = [ "bytes", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "getrandom 0.2.8", "instant", @@ -5540,7 +5557,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d45945fd2f96c4b133c23d5c28a8b7fc8d7138e6dd8d5a8cd492dd384f888e3" dependencies = [ "async-trait", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "instant", "libp2p-core 0.33.0", @@ -5563,7 +5580,7 @@ dependencies = [ "ed25519-dalek", "either", "fnv", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "instant", "lazy_static", @@ -5597,7 +5614,7 @@ dependencies = [ "ed25519-dalek", "either", "fnv", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "instant", "lazy_static", @@ -5628,7 +5645,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86adefc55ea4ed8201149f052fb441210727481dff1fb0b8318460206a79f5fb" dependencies = [ "flate2", - "futures 0.3.25", + "futures 0.3.26", "libp2p-core 0.33.0", ] @@ -5639,7 +5656,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbb462ec3a51fab457b4b44ac295e8b0a4b04dc175127e615cf996b1f0f1a268" dependencies = [ "async-std-resolver", - "futures 0.3.25", + "futures 0.3.26", "libp2p-core 0.33.0", "log", "parking_lot 0.12.1", @@ -5655,7 +5672,7 @@ checksum = "a505d0c6f851cbf2919535150198e530825def8bd3757477f13dc3a57f46cbcc" dependencies = [ "cuckoofilter", "fnv", - "futures 0.3.25", + "futures 0.3.26", "libp2p-core 0.33.0", "libp2p-swarm", "log", @@ -5676,7 +5693,7 @@ dependencies = [ "byteorder", "bytes", "fnv", - "futures 0.3.25", + "futures 0.3.26", "hex_fmt", "instant", "libp2p-core 0.33.0", @@ -5700,7 +5717,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b84b53490442d086db1fa5375670c9666e79143dccadef3f7c74a4346899a984" dependencies = [ "asynchronous-codec", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "libp2p-core 0.33.0", "libp2p-swarm", @@ -5725,7 +5742,7 @@ dependencies = [ "bytes", "either", "fnv", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "instant", "libp2p-core 0.33.0", @@ -5751,7 +5768,7 @@ dependencies = [ "async-io", "data-encoding", "dns-parser", - "futures 0.3.25", + "futures 0.3.26", "if-watch", "lazy_static", "libp2p-core 0.33.0", @@ -5787,7 +5804,7 @@ checksum = "5ff9c893f2367631a711301d703c47432af898c9bb8253bea0e2c051a13f7640" dependencies = [ "asynchronous-codec", "bytes", - "futures 0.3.25", + "futures 0.3.26", "libp2p-core 0.33.0", "log", "nohash-hasher", @@ -5805,7 +5822,7 @@ checksum = "cf2cee1dad1c83325bbd182a8e94555778699cec8a9da00086efb7522c4c15ad" dependencies = [ "bytes", "curve25519-dalek 3.2.0", - "futures 0.3.25", + "futures 0.3.26", "lazy_static", "libp2p-core 0.33.0", "log", @@ -5825,7 +5842,7 @@ version = "0.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d41516c82fe8dd148ec925eead0c5ec08a0628f7913597e93e126e4dfb4e0787" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "instant", "libp2p-core 0.33.0", @@ -5843,7 +5860,7 @@ checksum = "db007e737adc5d28b2e03223b0210164928ad742591127130796a72aa8eaf54f" dependencies = [ "asynchronous-codec", "bytes", - "futures 0.3.25", + "futures 0.3.26", "libp2p-core 0.33.0", "log", "prost 0.10.4", @@ -5858,7 +5875,7 @@ version = "0.22.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "de160c5631696cea22be326c19bd9d306e254c4964945263aea10f25f6e0864e" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "log", "pin-project 1.0.12", "rand 0.8.5", @@ -5875,7 +5892,7 @@ dependencies = [ "asynchronous-codec", "bytes", "either", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "instant", "libp2p-core 0.33.0", @@ -5900,7 +5917,7 @@ checksum = "c59967ea2db2c7560f641aa58ac05982d42131863fcd3dd6dcf0dd1daf81c60c" dependencies = [ "asynchronous-codec", "bimap", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "instant", "libp2p-core 0.33.0", @@ -5923,7 +5940,7 @@ checksum = "b02e0acb725e5a757d77c96b95298fd73a7394fe82ba7b8bbeea510719cbe441" dependencies = [ "async-trait", "bytes", - "futures 0.3.25", + "futures 0.3.26", "instant", "libp2p-core 0.33.0", "libp2p-swarm", @@ -5941,7 +5958,7 @@ checksum = "8f4bb21c5abadbf00360c734f16bf87f1712ed4f23cd46148f625d2ddb867346" dependencies = [ "either", "fnv", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "instant", "libp2p-core 0.33.0", @@ -5970,7 +5987,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f4933e38ef21b50698aefc87799c24f2a365c9d3f6cf50471f3f6a0bc410892" dependencies = [ "async-io", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "if-watch", "ipnet", @@ -5987,7 +6004,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24bdab114f7f2701757d6541266e1131b429bbae382008f207f2114ee4222dcb" dependencies = [ "async-std", - "futures 0.3.25", + "futures 0.3.26", "libp2p-core 0.32.1", "log", ] @@ -5998,7 +6015,7 @@ version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f066f2b8b1a1d64793f05da2256e6842ecd0293d6735ca2e9bda89831a1bdc06" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "js-sys", "libp2p-core 0.33.0", "parity-send-wrapper", @@ -6013,7 +6030,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39d398fbb29f432c4128fabdaac2ed155c3bcaf1b9bd40eeeb10a471eefacbf5" dependencies = [ "either", - "futures 0.3.25", + "futures 0.3.26", "futures-rustls", "libp2p-core 0.33.0", "log", @@ -6031,7 +6048,7 @@ version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fe653639ad74877c759720febb0cbcbf4caa221adde4eed2d3126ce5c6f381f" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "libp2p-core 0.33.0", "parking_lot 0.12.1", "thiserror", @@ -6357,9 +6374,9 @@ dependencies = [ [[package]] name = "matches" -version = "0.1.9" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" +checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" [[package]] name = "matrixmultiply" @@ -6519,7 +6536,7 @@ dependencies = [ "libc", "log", "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys", + "windows-sys 0.42.0", ] [[package]] @@ -6640,11 +6657,11 @@ dependencies = [ [[package]] name = "multihash-derive" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc076939022111618a5026d3be019fd8b366e76314538ff9a1b59ffbcbf98bcd" +checksum = "1d6d4752e6230d8ef7adf7bd5d8c4b1f6561c1014c5ba9a37445ccefe18aa1db" dependencies = [ - "proc-macro-crate 1.2.1", + "proc-macro-crate 1.1.3", "proc-macro-error", "proc-macro2", "quote", @@ -6665,7 +6682,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "363a84be6453a70e63513660f4894ef815daf88e3356bffcda9ca27d810ce83b" dependencies = [ "bytes", - "futures 0.3.25", + "futures 0.3.26", "log", "pin-project 1.0.12", "smallvec 1.10.0", @@ -6738,9 +6755,9 @@ dependencies = [ [[package]] name = "netlink-packet-utils" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25af9cf0dc55498b7bd94a1508af7a78706aa0ab715a73c5169273e03c84845e" +checksum = "0ede8a08c71ad5a95cdd0e4e52facd37190977039a4704eb82a283f713747d34" dependencies = [ "anyhow", "byteorder", @@ -6755,7 +6772,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65b4b14489ab424703c092062176d52ba55485a89c076b4f9db05092b7223aa6" dependencies = [ "bytes", - "futures 0.3.25", + "futures 0.3.26", "log", "netlink-packet-core", "netlink-sys", @@ -6765,13 +6782,13 @@ dependencies = [ [[package]] name = "netlink-sys" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92b654097027250401127914afb37cb1f311df6610a9891ff07a757e94199027" +checksum = "260e21fbb6f3d253a14df90eb0000a6066780a15dd901a7519ce02d77a94985b" dependencies = [ "async-io", "bytes", - "futures 0.3.25", + "futures 0.3.26", "libc", "log", ] @@ -6819,9 +6836,9 @@ checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" [[package]] name = "nom" -version = "7.1.2" +version = "7.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5507769c4919c998e69e49c839d9dc6e693ede4cc4290d6ad8b41d4f09c548c" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" dependencies = [ "memchr", "minimal-lexical", @@ -6840,9 +6857,9 @@ dependencies = [ [[package]] name = "num-complex" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ae39348c8bc5fbd7f40c727a9925f03517afd2ab27d46702108b6a7e5414c19" +checksum = "02e0d21255c828d6f128a1e41534206671e8c3ea0c62f32291e808dc82cff17d" dependencies = [ "num-traits", ] @@ -6929,9 +6946,9 @@ dependencies = [ [[package]] name = "object" -version = "0.30.2" +version = "0.30.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b8c786513eb403643f2a88c244c2aaa270ef2153f55094587d0c48a3cf22a83" +checksum = "ea86265d3d3dcb6a27fc51bd29a4bf387fae9d2986b823079d4986af253eb439" dependencies = [ "memchr", ] @@ -7636,9 +7653,9 @@ dependencies = [ [[package]] name = "parity-scale-codec" -version = "3.2.1" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "366e44391a8af4cfd6002ef6ba072bae071a96aafca98d7d448a34c5dca38b6a" +checksum = "637935964ff85a605d114591d4d2c13c5d1ba2806dae97cea6bf180238a749ac" dependencies = [ "arrayvec 0.7.2", "bitvec 1.0.1", @@ -7650,11 +7667,11 @@ dependencies = [ [[package]] name = "parity-scale-codec-derive" -version = "3.1.3" +version = "3.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9299338969a3d2f491d65f140b00ddec470858402f888af98e8642fb5e8965cd" +checksum = "86b26a931f824dd4eca30b3e43bb4f31cd5f0d3a403c5f5ff27106b805bfde7b" dependencies = [ - "proc-macro-crate 1.2.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn", @@ -7743,7 +7760,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" dependencies = [ "lock_api 0.4.9", - "parking_lot_core 0.9.6", + "parking_lot_core 0.9.7", ] [[package]] @@ -7778,15 +7795,15 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.6" +version = "0.9.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba1ef8814b5c993410bb3adfad7a5ed269563e4a2f90c41f5d85be7fb47133bf" +checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" dependencies = [ "cfg-if 1.0.0", "libc", "redox_syscall 0.2.16", "smallvec 1.10.0", - "windows-sys", + "windows-sys 0.45.0", ] [[package]] @@ -7922,9 +7939,9 @@ dependencies = [ [[package]] name = "pest" -version = "2.5.3" +version = "2.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4257b4a04d91f7e9e6290be5d3da4804dd5784fafde3a497d73eb2b4a158c30a" +checksum = "028accff104c4e513bad663bbcd2ad7cfd5304144404c31ed0a77ac103d00660" dependencies = [ "thiserror", "ucd-trie", @@ -7932,9 +7949,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.5.3" +version = "2.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "241cda393b0cdd65e62e07e12454f1f25d57017dcc514b1514cd3c4645e3a0a6" +checksum = "2ac3922aac69a40733080f53c1ce7f91dcf57e1a5f6c52f421fadec7fbdc4b69" dependencies = [ "pest", "pest_generator", @@ -7942,9 +7959,9 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.5.3" +version = "2.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46b53634d8c8196302953c74d5352f33d0c512a9499bd2ce468fc9f4128fa27c" +checksum = "d06646e185566b5961b4058dd107e0a7f56e77c3f484549fb119867773c0f202" dependencies = [ "pest", "pest_meta", @@ -7955,9 +7972,9 @@ dependencies = [ [[package]] name = "pest_meta" -version = "2.5.3" +version = "2.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ef4f1332a8d4678b41966bb4cc1d0676880e84183a1ecc3f4b69f03e99c7a51" +checksum = "e6f60b2ba541577e2a0c307c8f39d1439108120eb7903adeb6497fa880c59616" dependencies = [ "once_cell", "pest", @@ -7966,9 +7983,9 @@ dependencies = [ [[package]] name = "petgraph" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5014253a1331579ce62aa67443b4a658c5e7dd03d4bc6d302b94474888143" +checksum = "4dd7d28ee937e54fe3080c91faa1c3a46c06de6252988a7f4592ba2310ef22a4" dependencies = [ "fixedbitset", "indexmap", @@ -7980,7 +7997,7 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e9567389417feee6ce15dd6527a8a1ecac205ef62c2932bcf3d9f6fc5b78b414" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "rustc_version 0.4.0", ] @@ -8132,7 +8149,7 @@ dependencies = [ "libc", "log", "wepoll-ffi", - "windows-sys", + "windows-sys 0.42.0", ] [[package]] @@ -8332,11 +8349,10 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "1.2.1" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eda0fc3b0fb7c975631757e14d9049da17374063edb6ebbcbc54d880d4fe94e9" +checksum = "e17d47ce914bf4de440332250b0edd23ce48c005f59fab39d3335866b114f11a" dependencies = [ - "once_cell", "thiserror", "toml", ] @@ -8373,9 +8389,9 @@ checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" [[package]] name = "proc-macro2" -version = "1.0.49" +version = "1.0.51" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57a8eca9f9c4ffde41714334dee777596264c7825420f521abc92b5b5deb63a5" +checksum = "5d727cae5b39d21da60fa540906919ad737832fe0b1c165da3a34d6548c849d6" dependencies = [ "unicode-ident", ] @@ -8466,7 +8482,7 @@ dependencies = [ "bytes", "cfg-if 1.0.0", "cmake", - "heck 0.4.0", + "heck 0.4.1", "itertools", "lazy_static", "log", @@ -8939,9 +8955,9 @@ dependencies = [ [[package]] name = "rayon-core" -version = "1.10.1" +version = "1.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cac410af5d00ab6884528b4ab69d1e8e146e8d471201800fa1b4524126de6ad3" +checksum = "356a0625f1954f730c0201cdab48611198dc6ce21f4acff55089b5a78e6e835b" dependencies = [ "crossbeam-channel", "crossbeam-deque", @@ -9099,7 +9115,7 @@ dependencies = [ "ethereum-gen", "ethereum-types 0.13.1", "ethers", - "futures 0.3.25", + "futures 0.3.26", "hex", "hex-literal", "http", @@ -9188,20 +9204,20 @@ dependencies = [ [[package]] name = "rend" -version = "0.3.6" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79af64b4b6362ffba04eef3a4e10829718a4896dac19daa741851c86781edf95" +checksum = "581008d2099240d37fb08d77ad713bcaec2c4d89d50b5b21a8bb1996bbab68ab" dependencies = [ "bytecheck", ] [[package]] name = "reqwest" -version = "0.11.13" +version = "0.11.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68cc60575865c7831548863cc02356512e3f1dc2f3f82cb837d7fc4cc8f3c97c" +checksum = "21eed90ec8570952d53b772ecf8f206aa1ec9a3d76b2521c56c42973f2d91ee9" dependencies = [ - "base64 0.13.1", + "base64 0.21.0", "bytes", "encoding_rs", "futures-core", @@ -9346,9 +9362,9 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.7.39" +version = "0.7.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cec2b3485b07d96ddfd3134767b8a447b45ea4eb91448d0a35180ec0ffd5ed15" +checksum = "c30f1d45d9aa61cbc8cd1eb87705470892289bb2d01943e7803b873a57404dc3" dependencies = [ "bytecheck", "hashbrown 0.12.3", @@ -9360,9 +9376,9 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.7.39" +version = "0.7.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6eaedadc88b53e36dd32d940ed21ae4d850d5916f2581526921f553a72ac34c4" +checksum = "ff26ed6c7c4dfc2aa9480b86a60e3c7233543a270a680e10758a507c5a4ce476" dependencies = [ "proc-macro2", "quote", @@ -9437,7 +9453,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "322c53fd76a18698f1c27381d58091de3a043d356aa5bd0d510608b565f469a0" dependencies = [ "async-global-executor", - "futures 0.3.25", + "futures 0.3.26", "log", "netlink-packet-route", "netlink-proto", @@ -9447,9 +9463,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.27.0" +version = "1.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33c321ee4e17d2b7abe12b5d20c1231db708dd36185c8a21e9de5fed6da4dbe9" +checksum = "e13cf35f7140155d02ba4ec3294373d513a3c7baa8364c162b030e33c61520a8" dependencies = [ "arrayvec 0.7.2", "borsh", @@ -9515,16 +9531,16 @@ dependencies = [ [[package]] name = "rustix" -version = "0.36.6" +version = "0.36.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4feacf7db682c6c329c4ede12649cd36ecab0f3be5b7d74e6a20304725db4549" +checksum = "f43abb88211988493c1abb44a70efa56ff0ce98f233b7b276146f1f3f7ba9644" dependencies = [ "bitflags", "errno", - "io-lifetimes 1.0.4", + "io-lifetimes 1.0.5", "libc", "linux-raw-sys 0.1.4", - "windows-sys", + "windows-sys 0.45.0", ] [[package]] @@ -9572,7 +9588,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4da5fcb054c46f5a5dff833b129285a93d3f0179531735e6c866e8cc307d2020" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "pin-project 0.4.30", "static_assertions", ] @@ -9583,7 +9599,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26338f5e09bb721b85b135ea05af7767c90b52f6de4f087d4f4a3a9d64e7dc04" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "pin-project 1.0.12", "static_assertions", ] @@ -9646,7 +9662,7 @@ name = "sc-basic-authorship" version = "0.10.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "log", "parity-scale-codec", @@ -9702,7 +9718,7 @@ name = "sc-chain-spec-derive" version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "proc-macro-crate 1.2.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn", @@ -9716,7 +9732,7 @@ dependencies = [ "chrono", "clap 3.2.23", "fdlimit", - "futures 0.3.25", + "futures 0.3.26", "hex", "libp2p", "log", @@ -9753,7 +9769,7 @@ version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "fnv", - "futures 0.3.25", + "futures 0.3.26", "hash-db", "log", "parity-scale-codec", @@ -9806,7 +9822,7 @@ version = "0.10.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "async-trait", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "libp2p", "log", @@ -9830,7 +9846,7 @@ version = "0.10.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "async-trait", - "futures 0.3.25", + "futures 0.3.26", "log", "parity-scale-codec", "sc-block-builder", @@ -9860,7 +9876,7 @@ source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25- dependencies = [ "async-trait", "fork-tree", - "futures 0.3.25", + "futures 0.3.26", "log", "merlin", "num-bigint", @@ -9915,7 +9931,7 @@ version = "0.10.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "async-trait", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "log", "parity-scale-codec", @@ -10016,12 +10032,12 @@ name = "sc-finality-grandpa" version = "0.10.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "ahash", + "ahash 0.7.6", "async-trait", "dyn-clone", "finality-grandpa", "fork-tree", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "hex", "log", @@ -10057,7 +10073,7 @@ version = "0.10.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "ansi_term", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "log", "parity-util-mem", @@ -10096,7 +10112,7 @@ dependencies = [ "either", "fnv", "fork-tree", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "hex", "ip_network", @@ -10140,7 +10156,7 @@ name = "sc-network-common" version = "0.10.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "libp2p", "parity-scale-codec", "prost-build 0.10.4", @@ -10153,8 +10169,8 @@ name = "sc-network-gossip" version = "0.10.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "ahash", - "futures 0.3.25", + "ahash 0.7.6", + "futures 0.3.26", "futures-timer", "libp2p", "log", @@ -10170,7 +10186,7 @@ name = "sc-network-light" version = "0.10.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "libp2p", "log", "parity-scale-codec", @@ -10193,7 +10209,7 @@ dependencies = [ "bitflags", "either", "fork-tree", - "futures 0.3.25", + "futures 0.3.26", "libp2p", "log", "lru", @@ -10221,7 +10237,7 @@ source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25- dependencies = [ "bytes", "fnv", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "hex", "hyper", @@ -10247,7 +10263,7 @@ name = "sc-peerset" version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "libp2p", "log", "sc-utils", @@ -10269,7 +10285,7 @@ name = "sc-rpc" version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "hash-db", "jsonrpsee", "log", @@ -10299,7 +10315,7 @@ name = "sc-rpc-api" version = "0.10.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "jsonrpsee", "log", "parity-scale-codec", @@ -10322,7 +10338,7 @@ name = "sc-rpc-server" version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "jsonrpsee", "log", "serde_json", @@ -10338,7 +10354,7 @@ dependencies = [ "async-trait", "directories", "exit-future", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "hash-db", "jsonrpsee", @@ -10414,7 +10430,7 @@ name = "sc-sysinfo" version = "6.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "libc", "log", "rand 0.7.3", @@ -10434,7 +10450,7 @@ version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "chrono", - "futures 0.3.25", + "futures 0.3.26", "libp2p", "log", "parking_lot 0.12.1", @@ -10482,7 +10498,7 @@ name = "sc-tracing-proc-macro" version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "proc-macro-crate 1.2.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn", @@ -10493,7 +10509,7 @@ name = "sc-transaction-pool" version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "linked-hash-map", "log", @@ -10520,7 +10536,7 @@ name = "sc-transaction-pool-api" version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "log", "serde", "sp-blockchain", @@ -10533,7 +10549,7 @@ name = "sc-utils" version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "lazy_static", "log", @@ -10561,7 +10577,7 @@ version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "303959cf613a6f6efd19ed4b4ad5bf79966a13352716299ad532cfb115f4205c" dependencies = [ - "proc-macro-crate 1.2.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn", @@ -10589,7 +10605,7 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3" dependencies = [ - "windows-sys", + "windows-sys 0.42.0", ] [[package]] @@ -10699,9 +10715,9 @@ dependencies = [ [[package]] name = "security-framework" -version = "2.7.0" +version = "2.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bc1bb97804af6631813c55739f771071e0f2ed33ee20b68c86ec505d906356c" +checksum = "a332be01508d814fed64bf28f798a146d73792121129962fdf335bb3c49a4254" dependencies = [ "bitflags", "core-foundation", @@ -10712,9 +10728,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.6.1" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0160a13a177a45bfb43ce71c01580998474f556ad854dcbca936dd2841a5c556" +checksum = "31c9bb296072e961fcbd8853511dd39c2d8be2deb1e17c6860b1d30732b323b4" dependencies = [ "core-foundation-sys", "libc", @@ -10755,9 +10771,9 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" [[package]] name = "send_wrapper" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "930c0acf610d3fdb5e2ab6213019aaa04e227ebe9547b0649ba599b16d788bd7" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" [[package]] name = "serde" @@ -10780,9 +10796,9 @@ dependencies = [ [[package]] name = "serde_bytes" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "718dc5fff5b36f99093fc49b280cfc96ce6fc824317783bff5a1fed0c7a64819" +checksum = "416bda436f9aab92e02c8e10d49a15ddd339cea90b6e340fe51ed97abb548294" dependencies = [ "serde", ] @@ -10800,9 +10816,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.91" +version = "1.0.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877c235533714907a8c2464236f5c4b2a17262ef1bd71f38f35ea592c8da6883" +checksum = "cad406b69c91885b5107daf2c29572f6c8cdb3c66826821e286c533490c0bc76" dependencies = [ "itoa", "ryu", @@ -10955,9 +10971,9 @@ checksum = "43b2853a4d09f215c24cc5489c992ce46052d359b5109343cbafbf26bc62f8a3" [[package]] name = "signal-hook" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a253b5e89e2698464fc26b545c9edceb338e18a89effeeecfea192c3025be29d" +checksum = "732768f1176d21d09e076c23a93123d40bba92d50c4058da34d45c8de8e682b9" dependencies = [ "libc", "signal-hook-registry", @@ -10965,9 +10981,9 @@ dependencies = [ [[package]] name = "signal-hook-registry" -version = "1.4.0" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0" +checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" dependencies = [ "libc", ] @@ -11032,14 +11048,14 @@ checksum = "5e9f0ab6ef7eb7353d9119c170a436d1bf248eea575ac42d19d12f4e34130831" [[package]] name = "snow" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "774d05a3edae07ce6d68ea6984f3c05e9bba8927e3dd591e3b479e5b03213d0d" +checksum = "12ba5f4d4ff12bdb6a169ed51b7c48c0e0ac4b0b4b31012b2571e97d78d3201d" dependencies = [ "aes-gcm", "blake2 0.10.6", "chacha20poly1305", - "curve25519-dalek 4.0.0-pre.5", + "curve25519-dalek 4.0.0-rc.0", "rand_core 0.6.4", "ring", "rustc_version 0.4.0", @@ -11066,7 +11082,7 @@ dependencies = [ "base64 0.13.1", "bytes", "flate2", - "futures 0.3.25", + "futures 0.3.26", "httparse", "log", "rand 0.8.5", @@ -11109,7 +11125,7 @@ version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "blake2 0.10.6", - "proc-macro-crate 1.2.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn", @@ -11172,7 +11188,7 @@ name = "sp-blockchain" version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "log", "lru", "parity-scale-codec", @@ -11191,7 +11207,7 @@ version = "0.10.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "async-trait", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "log", "parity-scale-codec", @@ -11283,7 +11299,7 @@ dependencies = [ "byteorder", "dyn-clonable", "ed25519-dalek", - "futures 0.3.25", + "futures 0.3.26", "hash-db", "hash256-std-hasher", "hex", @@ -11410,7 +11426,7 @@ name = "sp-io" version = "6.0.0" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "hash-db", "libsecp256k1", "log", @@ -11447,7 +11463,7 @@ version = "0.12.0" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "async-trait", - "futures 0.3.25", + "futures 0.3.26", "merlin", "parity-scale-codec", "parking_lot 0.12.1", @@ -11571,7 +11587,7 @@ version = "5.0.0" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "Inflector", - "proc-macro-crate 1.2.1", + "proc-macro-crate 1.1.3", "proc-macro2", "quote", "syn", @@ -11806,9 +11822,9 @@ dependencies = [ [[package]] name = "ss58-registry" -version = "1.37.0" +version = "1.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d44528162f980c0e03c71e005d334332c8da0aec9f2b0b4bdc557ed4a9f24776" +checksum = "e40c020d72bc0a9c5660bb71e4a6fdef081493583062c474740a7d59f55f0e7b" dependencies = [ "Inflector", "num-format", @@ -11900,7 +11916,7 @@ version = "0.24.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59" dependencies = [ - "heck 0.4.0", + "heck 0.4.1", "proc-macro2", "quote", "rustversion", @@ -11935,7 +11951,7 @@ version = "4.0.0-dev" source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.25-leak-fix#43d3df1e32425fdc124f4c5cd8c79e0e24701930" dependencies = [ "frame-system-rpc-runtime-api", - "futures 0.3.25", + "futures 0.3.26", "jsonrpsee", "log", "parity-scale-codec", @@ -12012,7 +12028,7 @@ dependencies = [ "bitvec 1.0.1", "derivative", "frame-metadata", - "futures 0.3.25", + "futures 0.3.26", "hex", "jsonrpsee", "parity-scale-codec", @@ -12036,7 +12052,7 @@ source = "git+https://github.com/sora-xor/subxt?branch=polkadot-v0.9.25#1e812a53 dependencies = [ "darling", "frame-metadata", - "heck 0.4.0", + "heck 0.4.1", "parity-scale-codec", "proc-macro-error", "proc-macro2", @@ -12151,9 +12167,9 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "target-lexicon" -version = "0.12.5" +version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9410d0f6853b1d94f0e519fb95df60f29d2c1eff2d921ffdf01a4c8a3b54f12d" +checksum = "8ae9980cab1db3fceee2f6c6f643d5d8de2997c58ee8d25fb0cc8a9e9e7348e5" [[package]] name = "technical" @@ -12209,9 +12225,9 @@ dependencies = [ [[package]] name = "termcolor" -version = "1.1.3" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" dependencies = [ "winapi-util", ] @@ -12384,15 +12400,15 @@ dependencies = [ [[package]] name = "tinyvec_macros" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.24.1" +version = "1.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d9f76183f91ecfb55e1d7d5602bd1d979e38a3a522fe900241cf195624d67ae" +checksum = "c8e00990ebabbe4c14c08aca901caed183ecd5c09562a12c824bb53d3c3fd3af" dependencies = [ "autocfg 1.1.0", "bytes", @@ -12405,7 +12421,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.42.0", ] [[package]] @@ -12459,9 +12475,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.4" +version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb2e075f03b3d66d8d8785356224ba688d2906a371015e225beeb65ca92c740" +checksum = "5427d89453009325de0d8f342c9490009f76e999cb7672d77e46267448f7e6b2" dependencies = [ "bytes", "futures-core", @@ -12474,9 +12490,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.5.10" +version = "0.5.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1333c76748e868a4d9d1017b5ab53171dfd095f70c712fdb4653a406547f598f" +checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" dependencies = [ "serde", ] @@ -12536,7 +12552,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" dependencies = [ - "ahash", + "ahash 0.7.6", "lazy_static", "log", "lru", @@ -12806,9 +12822,9 @@ dependencies = [ [[package]] name = "unicode-bidi" -version = "0.3.8" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" +checksum = "d54675592c1dbefd78cbd98db9bacd89886e1ca50692a0692baefffdeb92dd58" [[package]] name = "unicode-ident" @@ -12827,9 +12843,9 @@ dependencies = [ [[package]] name = "unicode-segmentation" -version = "1.10.0" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fdbf052a0783de01e944a6ce7a8cb939e295b1e7be835a1112c3b9a7f047a5a" +checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" [[package]] name = "unicode-width" @@ -13057,9 +13073,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.83" +version = "0.2.84" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268" +checksum = "31f8dcbc21f30d9b8f2ea926ecb58f6b91192c17e9d33594b3df58b2007ca53b" dependencies = [ "cfg-if 1.0.0", "wasm-bindgen-macro", @@ -13067,9 +13083,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.83" +version = "0.2.84" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c8ffb332579b0557b52d268b91feab8df3615f265d5270fec2a8c95b17c1142" +checksum = "95ce90fd5bcc06af55a641a86428ee4229e44e07033963a2290a8e241607ccb9" dependencies = [ "bumpalo", "log", @@ -13082,9 +13098,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.33" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23639446165ca5a5de86ae1d8896b737ae80319560fbaa4c2887b7da6e7ebd7d" +checksum = "f219e0d211ba40266969f6dbdd90636da12f75bee4fc9d6c23d1260dadb51454" dependencies = [ "cfg-if 1.0.0", "js-sys", @@ -13094,9 +13110,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.83" +version = "0.2.84" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "052be0f94026e6cbc75cdefc9bae13fd6052cdcaf532fa6c45e7ae33a1e6c810" +checksum = "4c21f77c0bedc37fd5dc21f897894a5ca01e7bb159884559461862ae90c0b4c5" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -13104,9 +13120,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.83" +version = "0.2.84" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c" +checksum = "2aff81306fcac3c7515ad4e177f521b5c9a15f2b08f4e32d823066102f35a5f6" dependencies = [ "proc-macro2", "quote", @@ -13117,15 +13133,15 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.83" +version = "0.2.84" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f" +checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d" [[package]] name = "wasm-bindgen-test" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09d2fff962180c3fadf677438054b1db62bee4aa32af26a45388af07d1287e1d" +checksum = "6db36fc0f9fb209e88fb3642590ae0205bb5a56216dabd963ba15879fe53a30b" dependencies = [ "console_error_panic_hook", "js-sys", @@ -13137,9 +13153,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-test-macro" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4683da3dfc016f704c9f82cf401520c4f1cb3ee440f7f52b3d6ac29506a49ca7" +checksum = "0734759ae6b3b1717d661fe4f016efcfb9828f5edb4520c18eaee05af3b43be9" dependencies = [ "proc-macro2", "quote", @@ -13171,7 +13187,7 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be0ecb0db480561e9a7642b5d3e4187c128914e58aa84330b9493e3eb68c5e7f" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "js-sys", "parking_lot 0.11.2", "pin-utils", @@ -13381,9 +13397,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.60" +version = "0.3.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcda906d8be16e728fd5adc5b729afad4e444e106ab28cd1c7256e54fa61510f" +checksum = "e33b99f4b23ba3eec1a53ac264e35a755f00e966e0065077d6027c0f575b0b97" dependencies = [ "js-sys", "wasm-bindgen", @@ -13419,9 +13435,9 @@ dependencies = [ [[package]] name = "which" -version = "4.3.0" +version = "4.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c831fbbee9e129a8cf93e7747a82da9d95ba8e16621cae60ec2cdc849bacb7b" +checksum = "2441c784c52b289a054b7201fc93253e288f094e2f4be9058343127c4226a269" dependencies = [ "either", "libc", @@ -13493,6 +13509,30 @@ dependencies = [ "windows_x86_64_msvc 0.42.1", ] +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.42.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2522491fbfcd58cc84d47aeb2958948c4b8982e9a2d8a2a35bbaed431390e7" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc 0.42.1", + "windows_i686_gnu 0.42.1", + "windows_i686_msvc 0.42.1", + "windows_x86_64_gnu 0.42.1", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc 0.42.1", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.42.1" @@ -13576,13 +13616,14 @@ dependencies = [ [[package]] name = "ws_stream_wasm" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47ca1ab42f5afed7fc332b22b6e932ca5414b209465412c8cdf0ad23bc0de645" +checksum = "7999f5f4217fe3818726b66257a4475f71e74ffd190776ad053fa159e50737f5" dependencies = [ "async_io_stream", - "futures 0.3.25", + "futures 0.3.26", "js-sys", + "log", "pharos", "rustc_version 0.4.0", "send_wrapper", @@ -13758,7 +13799,7 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5d9ba232399af1783a58d8eb26f6b5006fbefe2dc9ef36bd283324792d03ea5" dependencies = [ - "futures 0.3.25", + "futures 0.3.26", "log", "nohash-hasher", "parking_lot 0.12.1", diff --git a/node/chain_spec/src/lib.rs b/node/chain_spec/src/lib.rs index 1c13ba2b5a..b78da250a3 100644 --- a/node/chain_spec/src/lib.rs +++ b/node/chain_spec/src/lib.rs @@ -1694,17 +1694,6 @@ fn mainnet_genesis( None, None, ), - ( - XSTUSD.into(), - assets_and_permissions_account_id.clone(), - AssetSymbol(b"XSTUSD".to_vec()), - AssetName(b"SORA Synthetic USD".to_vec()), - DEFAULT_BALANCE_PRECISION, - Balance::zero(), - true, - None, - None, - ), ( common::AssetId32::from_bytes(hex!( "008bcfd2387d3fc453333557eecb0efe59fcba128769b2feefdd306e98e66440" From ba02ab6f5b9138539faf06e0d1f488331a900e54 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Wed, 22 Feb 2023 02:15:26 +0400 Subject: [PATCH 38/72] quickfix --- Cargo.lock | 2 +- runtime/src/migrations.rs | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ad73969cb6..267b842338 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3854,7 +3854,7 @@ dependencies = [ "frame-benchmarking-cli", "framenode-chain-spec", "framenode-runtime", - "futures 0.3.25", + "futures 0.3.26", "futures-timer", "iroha-migration", "iroha-migration-rpc", diff --git a/runtime/src/migrations.rs b/runtime/src/migrations.rs index 2497a871ea..4e560a9c69 100644 --- a/runtime/src/migrations.rs +++ b/runtime/src/migrations.rs @@ -1,2 +1 @@ pub type Migrations = (); - From 0a8558a79897e45e142275c797d8af1c64a20bb4 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Tue, 21 Mar 2023 13:14:17 +0300 Subject: [PATCH 39/72] updated tests --- pallets/xst/src/tests.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index d0156a04c3..6322ff1b9b 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -33,7 +33,7 @@ mod tests { use core::str::FromStr; use crate::{Error, Pallet, mock::*}; - use common::{self, AssetName, AssetSymbol, DEXId, FromGenericPair, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, prelude::{Balance, SwapAmount, QuoteAmount, FixedWrapper,}, GetMarketInfo, assert_approx_eq, PriceToolsPallet }; + use common::{self, AssetName, AssetSymbol, DEXId, FromGenericPair, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, GetMarketInfo, assert_approx_eq, PriceToolsPallet, prelude::{Balance, SwapAmount, QuoteAmount, FixedWrapper, }, SymbolName, Oracle, PriceVariant}; use frame_support::{assert_ok, assert_noop}; use sp_arithmetic::traits::{Zero}; use sp_runtime::DispatchError; @@ -721,8 +721,15 @@ mod tests { ) .expect("Failed to quote XST -> XSTEURO"); + let xst_to_xor_price = MockDEXApi::get_average_price( + &XST.into(), + &XOR.into(), + PriceVariant::Buy, + ).expect("Expected to calculate price XST->XOR"); + let expected_fee_amount = FixedWrapper::from(quote_amount.amount() / 2) * FixedWrapper::from(xst_to_xor_price); + assert_eq!(swap_outcome_after.amount, swap_outcome_before.amount / 2); - assert_eq!(swap_outcome_after.fee, quote_amount.amount() / 2); + assert_eq!(swap_outcome_after.fee, expected_fee_amount.into_balance()); }); } } From 205e20d66bcfee0caf3a2f3f53cbe200f7bc7288 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Thu, 23 Mar 2023 11:09:30 +0300 Subject: [PATCH 40/72] updated storage definitions --- pallets/xst/src/lib.rs | 16 ++++++++-------- pallets/xst/src/migrations/mod.rs | 6 +++--- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 9a832b5d57..2892814ff8 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -209,9 +209,8 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { ensure_root(origin)?; - let reference_symbol = EnabledSynthetics::::try_get(synthetic_asset) - .map_err(|_| Error::::SyntheticIsNotEnabled)? - .expect("Synthetic tables always store `Some`") + let reference_symbol = EnabledSynthetics::::get(synthetic_asset) + .ok_or_else(|| Error::::SyntheticIsNotEnabled)? .reference_symbol; EnabledSynthetics::::remove(synthetic_asset); @@ -330,7 +329,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn enabled_synthetics)] pub type EnabledSynthetics = - StorageMap<_, Blake2_128Concat, T::AssetId, Option>, ValueQuery>; + StorageMap<_, Blake2_128Concat, T::AssetId, SyntheticInfo, OptionQuery>; /// Reference symbols and their synthetic assets. /// @@ -338,7 +337,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn enabled_symbols)] pub type EnabledSymbols = - StorageMap<_, Blake2_128Concat, T::Symbol, Option, ValueQuery>; + StorageMap<_, Blake2_128Concat, T::Symbol, T::AssetId, OptionQuery>; /// Asset that is used to compare collateral assets by value, e.g., DAI. #[pallet::storage] @@ -368,6 +367,7 @@ pub mod pallet { /// Asset that is used to compare collateral assets by value, e.g., DAI. pub reference_asset_id: T::AssetId, /// List of tokens enabled as collaterals initially. + /// TODO: replace with Vec and make corresponding changes to build() function pub initial_synthetic_assets: Vec<(AssetSymbol, AssetName, T::Symbol, Fixed)>, } @@ -447,12 +447,12 @@ impl Pallet { EnabledSynthetics::::insert( synthetic_asset_id, - Some(SyntheticInfo { + SyntheticInfo { reference_symbol: reference_symbol.clone(), fee_ratio, - }), + }, ); - EnabledSymbols::::insert(reference_symbol.clone(), Some(synthetic_asset_id)); + EnabledSymbols::::insert(reference_symbol.clone(), synthetic_asset_id); Self::deposit_event(Event::SyntheticAssetEnabled( synthetic_asset_id, diff --git a/pallets/xst/src/migrations/mod.rs b/pallets/xst/src/migrations/mod.rs index 4d02a1431a..a74648752c 100644 --- a/pallets/xst/src/migrations/mod.rs +++ b/pallets/xst/src/migrations/mod.rs @@ -55,12 +55,12 @@ pub fn migrate() -> Weight { EnabledSynthetics::::insert( T::AssetId::from(XSTUSD), - Some(SyntheticInfo { + SyntheticInfo { reference_symbol: xstusd_symbol.clone(), fee_ratio: fixed!(0.00666), - }), + }, ); - EnabledSymbols::::insert(xstusd_symbol, Some(T::AssetId::from(XSTUSD))); + EnabledSymbols::::insert(xstusd_symbol, T::AssetId::from(XSTUSD)); StorageVersion::new(2).put::>(); T::DbWeight::get().reads_writes(0, 2) From feb8818aa27c497b851b677c231b1bd02224ff34 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Tue, 28 Mar 2023 13:31:48 +0300 Subject: [PATCH 41/72] fix --- pallets/xst/benchmarking/src/lib.rs | 26 +++++++++--- pallets/xst/src/lib.rs | 64 ++++++++++++++++++----------- pallets/xst/src/migrations/mod.rs | 51 +++++++++++++---------- pallets/xst/src/migrations/tests.rs | 8 ++-- pallets/xst/src/tests.rs | 7 ++-- 5 files changed, 98 insertions(+), 58 deletions(-) diff --git a/pallets/xst/benchmarking/src/lib.rs b/pallets/xst/benchmarking/src/lib.rs index 53b7418c9f..b5b0c9cf94 100644 --- a/pallets/xst/benchmarking/src/lib.rs +++ b/pallets/xst/benchmarking/src/lib.rs @@ -34,7 +34,7 @@ use band::Pallet as Band; use codec::{Decode as _, Encode as _}; -use common::{balance, fixed, AssetName, AssetSymbol, Oracle, DAI}; +use common::{balance, fixed, AssetName, AssetSymbol, Oracle, DAI, XSTUSD}; use frame_benchmarking::benchmarks; use frame_support::pallet_prelude::DispatchResultWithPostInfo; use frame_system::{EventRecord, RawOrigin}; @@ -47,6 +47,8 @@ use xst::{Call, Event, Pallet as XSTPool}; mod mock; mod utils { + use common::AssetId32; + use common::PredefinedAssetId::XSTUSD; use frame_support::{dispatch::DispatchErrorWithPostInfo, Parameter}; use super::*; @@ -84,11 +86,12 @@ mod utils { pub fn enable_synthetic_asset() -> Result { relay_symbol::()?; + let asset_id = + AssetId32::::from_synthetic_reference_symbol(&symbol()); XSTPool::::enable_synthetic_asset( RawOrigin::Root.into(), - AssetSymbol(b"XSTEURO".to_vec()), - AssetName(b"Sora Synthetic EURO".to_vec()), + asset_id, symbol(), fixed!(0), )?; @@ -116,8 +119,7 @@ benchmarks! { utils::relay_symbol::()?; }: _( RawOrigin::Root, - AssetSymbol(b"XSTEURO".to_vec()), - AssetName(b"Sora Synthetic EURO".to_vec()), + XSTUSD.into(), utils::symbol(), fixed!(0) ) @@ -140,6 +142,20 @@ benchmarks! { utils::assert_last_event::(Event::SyntheticAssetDisabled(asset_id).into()) } + register_synthetic_asset { + let asset_id = AssetId32::::from_synthetic_reference_symbol( + &reference_symbol, + ).into(); + }: _( + RawOrigin::Root, + AssetSymbol(b"XSTEURO".to_vec()), + AssetName(b"Sora Synthetic EURO".to_vec()), + utils::symbol(), + ) + verify { + utils::assert_last_event::(Event::AssetRegistered(asset_id, RawOrigin::Root.into()).into()) + } + set_synthetic_asset_fee { let asset_id = utils::enable_synthetic_asset::()?; let fee_ratio = fixed!(0.06); diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 2892814ff8..b24ae40672 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -176,21 +176,34 @@ pub mod pallet { #[pallet::weight(::WeightInfo::enable_synthetic_asset())] pub fn enable_synthetic_asset( + origin: OriginFor, + asset_id: T::AssetId, + reference_symbol: T::Symbol, + fee_ratio: Fixed, + ) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + + Self::enable_synthetic_asset_unchecked(asset_id, reference_symbol, fee_ratio, true)?; + Ok(().into()) + } + + #[pallet::weight(10_000_000)] + pub fn register_synthetic_asset( origin: OriginFor, asset_symbol: AssetSymbol, asset_name: AssetName, reference_symbol: T::Symbol, - fee_ratio: Fixed, ) -> DispatchResultWithPostInfo { ensure_root(origin)?; - Self::enable_synthetic_asset_unchecked( - asset_symbol, - asset_name, - reference_symbol, - fee_ratio, - true, - )?; + let synthetic_asset_id: T::AssetId = + AssetId32::::from_synthetic_reference_symbol( + &reference_symbol, + ) + .into(); + + Self::register_synthetic_asset_unchecked(synthetic_asset_id, asset_symbol, asset_name)?; + Ok(().into()) } @@ -368,7 +381,7 @@ pub mod pallet { pub reference_asset_id: T::AssetId, /// List of tokens enabled as collaterals initially. /// TODO: replace with Vec and make corresponding changes to build() function - pub initial_synthetic_assets: Vec<(AssetSymbol, AssetName, T::Symbol, Fixed)>, + pub initial_synthetic_assets: Vec<(T::AssetId, T::Symbol, Fixed)>, } #[cfg(feature = "std")] @@ -378,8 +391,7 @@ pub mod pallet { tech_account_id: Default::default(), reference_asset_id: DAI.into(), initial_synthetic_assets: [( - AssetSymbol(b"XSTUSD".to_vec()), - AssetName(b"SORA Synthetic USD".to_vec()), + XSTUSD.into(), common::SymbolName::usd().into(), common::fixed!(0.00666), )] @@ -398,10 +410,9 @@ pub mod pallet { .expect("Failed to register technical account"); self.initial_synthetic_assets.iter().cloned().for_each( - |(asset_symbol, asset_name, reference_symbol, fee_ratio)| { + |(asset_id, reference_symbol, fee_ratio)| { Pallet::::enable_synthetic_asset_unchecked( - asset_symbol, - asset_name, + asset_id, reference_symbol, fee_ratio, false, @@ -425,8 +436,7 @@ impl Pallet { } fn enable_synthetic_asset_unchecked( - asset_symbol: AssetSymbol, - asset_name: AssetName, + synthetic_asset_id: T::AssetId, reference_symbol: T::Symbol, fee_ratio: Fixed, transactional: bool, @@ -437,13 +447,9 @@ impl Pallet { } Self::ensure_symbol_exists(&reference_symbol)?; - let synthetic_asset_id: T::AssetId = - AssetId32::::from_synthetic_reference_symbol( - &reference_symbol, - ) - .into(); - Self::register_synthetic_asset(synthetic_asset_id, asset_symbol, asset_name)?; - Self::enable_synthetic_pair(synthetic_asset_id)?; + Assets::::ensure_asset_exists(&synthetic_asset_id)?; + + Self::enable_synthetic_trading_pair(synthetic_asset_id)?; EnabledSynthetics::::insert( synthetic_asset_id, @@ -468,7 +474,15 @@ impl Pallet { } } - fn enable_synthetic_pair(synthetic_asset_id: T::AssetId) -> sp_runtime::DispatchResult { + fn enable_synthetic_trading_pair(synthetic_asset_id: T::AssetId) -> sp_runtime::DispatchResult { + if trading_pair::Pallet::::is_trading_pair_enabled( + &DEXId::Polkaswap.into(), + &T::GetSyntheticBaseAssetId::get(), + &synthetic_asset_id, + )? { + return Ok(()); + } + trading_pair::Pallet::::register_pair( DEXId::Polkaswap.into(), T::GetSyntheticBaseAssetId::get(), @@ -857,7 +871,7 @@ impl Pallet { .ok_or_else(|| Error::::SymbolDoesNotExist.into()) } - fn register_synthetic_asset( + fn register_synthetic_asset_unchecked( synthetic_asset: T::AssetId, asset_symbol: AssetSymbol, asset_name: AssetName, diff --git a/pallets/xst/src/migrations/mod.rs b/pallets/xst/src/migrations/mod.rs index a74648752c..7acac5aa79 100644 --- a/pallets/xst/src/migrations/mod.rs +++ b/pallets/xst/src/migrations/mod.rs @@ -33,37 +33,46 @@ use common::generate_storage_instance; use common::{fixed, Fixed, XSTUSD}; use frame_support::pallet_prelude::{Get, StorageVersion}; use frame_support::pallet_prelude::{StorageValue, ValueQuery}; +use frame_support::traits::OnRuntimeUpgrade; use frame_support::{log::info, traits::GetStorageVersion as _, weights::Weight}; use crate::{EnabledSymbols, EnabledSynthetics, SyntheticInfo}; -generate_storage_instance!(PoolXST, BaseFee); -type OldBaseFee = StorageValue; +#[frame_support::storage_alias] +type BaseFee = StorageValue, Fixed, ValueQuery>; + +pub struct CustomSyntheticsUpgrade(core::marker::PhantomData); /// Migration which migrates `XSTUSD` synthetic to the new format. -pub fn migrate() -> Weight { - if Pallet::::on_chain_storage_version() >= 2 { - info!("Migration to version 2 has already been applied"); - return 0; - } +impl OnRuntimeUpgrade for CustomSyntheticsUpgrade +where + T: crate::Config, + ::AccountId: From<[u8; 32]>, +{ + fn on_runtime_upgrade() -> Weight { + if Pallet::::on_chain_storage_version() >= 2 { + info!("Migration to version 2 has already been applied"); + return 0; + } - if OldBaseFee::exists() { - OldBaseFee::kill(); - } + if BaseFee::::exists() { + BaseFee::::kill(); + } - let xstusd_symbol = T::Symbol::from(common::SymbolName::usd()); + let xstusd_symbol = T::Symbol::from(common::SymbolName::usd()); - EnabledSynthetics::::insert( - T::AssetId::from(XSTUSD), - SyntheticInfo { - reference_symbol: xstusd_symbol.clone(), - fee_ratio: fixed!(0.00666), - }, - ); - EnabledSymbols::::insert(xstusd_symbol, T::AssetId::from(XSTUSD)); + EnabledSynthetics::::insert( + T::AssetId::from(XSTUSD), + SyntheticInfo { + reference_symbol: xstusd_symbol.clone(), + fee_ratio: fixed!(0.00666), + }, + ); + EnabledSymbols::::insert(xstusd_symbol, T::AssetId::from(XSTUSD)); - StorageVersion::new(2).put::>(); - T::DbWeight::get().reads_writes(0, 2) + StorageVersion::new(2).put::>(); + T::DbWeight::get().reads_writes(0, 2) + } } #[cfg(test)] diff --git a/pallets/xst/src/migrations/tests.rs b/pallets/xst/src/migrations/tests.rs index be1d02ebe5..baf76e3666 100644 --- a/pallets/xst/src/migrations/tests.rs +++ b/pallets/xst/src/migrations/tests.rs @@ -28,17 +28,17 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use crate::{migrations::OldBaseFee, mock::*, pallet::Pallet, EnabledSynthetics}; +use crate::{migrations::BaseFee, mock::*, pallet::Pallet, EnabledSynthetics}; use common::{fixed, Fixed, XSTUSD}; -use frame_support::traits::{GetStorageVersion as _, StorageVersion}; +use frame_support::traits::{GetStorageVersion as _, OnRuntimeUpgrade, StorageVersion}; #[test] fn test() { ExtBuilder::default().build().execute_with(|| { StorageVersion::new(1).put::>(); - OldBaseFee::put::(fixed!(0.00666)); + BaseFee::::put::(fixed!(0.00666)); - super::migrate::(); + super::CustomSyntheticsUpgrade::::on_runtime_upgrade(); let info = EnabledSynthetics::::get(XSTUSD) .expect("XSTUSD synthetic should be enabled after migration"); diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index 6322ff1b9b..c986abef24 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -33,7 +33,7 @@ mod tests { use core::str::FromStr; use crate::{Error, Pallet, mock::*}; - use common::{self, AssetName, AssetSymbol, DEXId, FromGenericPair, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, GetMarketInfo, assert_approx_eq, PriceToolsPallet, prelude::{Balance, SwapAmount, QuoteAmount, FixedWrapper, }, SymbolName, Oracle, PriceVariant}; + use common::{self, AssetName, AssetSymbol, DEXId, FromGenericPair, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, GetMarketInfo, assert_approx_eq, PriceToolsPallet, prelude::{Balance, SwapAmount, QuoteAmount, FixedWrapper, }, SymbolName, Oracle, PriceVariant, PredefinedAssetId, AssetId32}; use frame_support::{assert_ok, assert_noop}; use sp_arithmetic::traits::{Zero}; use sp_runtime::DispatchError; @@ -642,10 +642,11 @@ mod tests { Band::relay(Origin::signed(alice.clone()), vec![(euro.clone(), 1)], 0, 0) .expect("Failed to relay"); + let asset_id = AssetId32::::from_synthetic_reference_symbol(&euro).expect("Failed to get asset id"); + XSTPool::enable_synthetic_asset( Origin::root(), - AssetSymbol(b"XSTEURO".to_vec()), - AssetName(b"Sora Synthetic Euro".to_vec()), + asset_id, euro.clone(), fixed!(0), ).expect("Failed to enable synthetic asset"); From d362897ceabfacdc068354ed77c91ce0dd1bbeb4 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Tue, 28 Mar 2023 13:37:09 +0300 Subject: [PATCH 42/72] fix tests --- pallets/xst/src/migrations/tests.rs | 2 +- pallets/xst/src/tests.rs | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/pallets/xst/src/migrations/tests.rs b/pallets/xst/src/migrations/tests.rs index baf76e3666..0aa5fa74e1 100644 --- a/pallets/xst/src/migrations/tests.rs +++ b/pallets/xst/src/migrations/tests.rs @@ -45,7 +45,7 @@ fn test() { assert_eq!(info.reference_symbol, common::SymbolName::usd().into()); assert_eq!(info.fee_ratio, fixed!(0.00666)); - assert!(!OldBaseFee::exists()); + assert!(!BaseFee::::exists()); assert_eq!(Pallet::::on_chain_storage_version(), 2); }); diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index c986abef24..d24de7af2d 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -642,7 +642,7 @@ mod tests { Band::relay(Origin::signed(alice.clone()), vec![(euro.clone(), 1)], 0, 0) .expect("Failed to relay"); - let asset_id = AssetId32::::from_synthetic_reference_symbol(&euro).expect("Failed to get asset id"); + let asset_id = AssetId32::::from_synthetic_reference_symbol(&euro); XSTPool::enable_synthetic_asset( Origin::root(), @@ -683,11 +683,10 @@ mod tests { .expect("Failed to add relayers"); Band::relay(Origin::signed(alice.clone()), vec![(euro.clone(), 1)], 0, 0) .expect("Failed to relay"); - + let asset_id = AssetId32::::from_synthetic_reference_symbol(&euro); XSTPool::enable_synthetic_asset( Origin::root(), - AssetSymbol(b"XSTEURO".to_vec()), - AssetName(b"Sora Synthetic Euro".to_vec()), + asset_id, euro.clone(), fixed!(0), ).expect("Failed to enable synthetic asset"); From 368e92b04de55f8ed996255fccf2c8616b4b0239 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Wed, 29 Mar 2023 13:23:40 +0300 Subject: [PATCH 43/72] fixed migrations --- pallets/xst/src/migrations/mod.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/pallets/xst/src/migrations/mod.rs b/pallets/xst/src/migrations/mod.rs index 7acac5aa79..2a7931839a 100644 --- a/pallets/xst/src/migrations/mod.rs +++ b/pallets/xst/src/migrations/mod.rs @@ -29,10 +29,8 @@ // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use super::pallet::{Config, Pallet}; -use common::generate_storage_instance; use common::{fixed, Fixed, XSTUSD}; -use frame_support::pallet_prelude::{Get, StorageVersion}; -use frame_support::pallet_prelude::{StorageValue, ValueQuery}; +use frame_support::pallet_prelude::{Get, StorageVersion, ValueQuery}; use frame_support::traits::OnRuntimeUpgrade; use frame_support::{log::info, traits::GetStorageVersion as _, weights::Weight}; From b0fb66b14222e8892b3a34b83a383f7e5d0cc3e9 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Wed, 29 Mar 2023 13:24:26 +0300 Subject: [PATCH 44/72] fixed benchmarks --- pallets/xst/benchmarking/Cargo.toml | 2 +- pallets/xst/benchmarking/src/lib.rs | 45 +++++++++++++++++---- pallets/xst/benchmarking/src/mock.rs | 1 + pallets/xst/src/lib.rs | 3 +- pallets/xst/src/weights.rs | 59 ++++++++++++++++------------ 5 files changed, 75 insertions(+), 35 deletions(-) diff --git a/pallets/xst/benchmarking/Cargo.toml b/pallets/xst/benchmarking/Cargo.toml index 12d5459935..a413a10f21 100644 --- a/pallets/xst/benchmarking/Cargo.toml +++ b/pallets/xst/benchmarking/Cargo.toml @@ -29,6 +29,7 @@ trading-pair = { path = "../../trading-pair", default-features = false } band = { path = "../../band", default-features = false } oracle-proxy = {path = "../../oracle-proxy", default-features = false} xst = {path = "../../xst", default-features = false } +assets = { path = "../../assets", default-features = false } [dev-dependencies] scale-info = { version = "2", default-features = false } @@ -36,7 +37,6 @@ sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkado pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-tokens", default-features = false } -assets = { path = "../../assets", default-features = false } dex-api = { path = "../../dex-api", default-features = false } pool-xyk = { path = "../../pool-xyk", default-features = false } pswap-distribution = { path = "../../pswap-distribution", default-features = false } diff --git a/pallets/xst/benchmarking/src/lib.rs b/pallets/xst/benchmarking/src/lib.rs index b5b0c9cf94..2d35345444 100644 --- a/pallets/xst/benchmarking/src/lib.rs +++ b/pallets/xst/benchmarking/src/lib.rs @@ -32,6 +32,7 @@ #![cfg_attr(not(feature = "std"), no_std)] +use assets::Event as AssetsEvent; use band::Pallet as Band; use codec::{Decode as _, Encode as _}; use common::{balance, fixed, AssetName, AssetSymbol, Oracle, DAI, XSTUSD}; @@ -41,6 +42,7 @@ use frame_system::{EventRecord, RawOrigin}; use hex_literal::hex; use oracle_proxy::Pallet as OracleProxy; use sp_std::prelude::*; +use technical::Pallet as Technical; use xst::{Call, Event, Pallet as XSTPool}; #[cfg(test)] @@ -48,7 +50,6 @@ mod mock; mod utils { use common::AssetId32; - use common::PredefinedAssetId::XSTUSD; use frame_support::{dispatch::DispatchErrorWithPostInfo, Parameter}; use super::*; @@ -60,6 +61,13 @@ mod utils { Symbol::decode(&mut &bytes[..]).expect("Failed to decode symbol") } + pub fn symbol_asset_id() -> T::AssetId { + AssetId32::::from_synthetic_reference_symbol(&symbol::< + ::Symbol, + >()) + .into() + } + pub fn alice() -> T::AccountId { let bytes = hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"); T::AccountId::decode(&mut &bytes[..]).unwrap() @@ -73,6 +81,14 @@ mod utils { assert_eq!(event, &system_event); } + pub fn assert_last_assets_event(generic_event: ::Event) { + let events = frame_system::Pallet::::events(); + let system_event: ::Event = generic_event.into(); + // compare to the last event record + let EventRecord { event, .. } = &events[events.len() - 1]; + assert_eq!(event, &system_event); + } + pub fn relay_symbol() -> DispatchResultWithPostInfo { OracleProxy::::enable_oracle(RawOrigin::Root.into(), Oracle::BandChainFeed)?; Band::::add_relayers(RawOrigin::Root.into(), vec![alice::()])?; @@ -86,8 +102,14 @@ mod utils { pub fn enable_synthetic_asset() -> Result { relay_symbol::()?; - let asset_id = - AssetId32::::from_synthetic_reference_symbol(&symbol()); + let asset_id = symbol_asset_id::(); + + XSTPool::::register_synthetic_asset( + RawOrigin::Root.into(), + AssetSymbol(b"XSTEURO".to_vec()), + AssetName(b"Sora Synthetic EURO".to_vec()), + symbol::<::Symbol>(), + )?; XSTPool::::enable_synthetic_asset( RawOrigin::Root.into(), @@ -143,17 +165,24 @@ benchmarks! { } register_synthetic_asset { - let asset_id = AssetId32::::from_synthetic_reference_symbol( - &reference_symbol, - ).into(); + let permissioned_tech_account_id = XSTPool::::permissioned_tech_account(); + let permissioned_account_id = + Technical::::tech_account_id_to_account_id(&permissioned_tech_account_id) + .expect("Expected to generate account id from technical"); + let reference_symbol = utils::symbol::<::Symbol>(); }: _( RawOrigin::Root, AssetSymbol(b"XSTEURO".to_vec()), AssetName(b"Sora Synthetic EURO".to_vec()), - utils::symbol(), + reference_symbol ) verify { - utils::assert_last_event::(Event::AssetRegistered(asset_id, RawOrigin::Root.into()).into()) + utils::assert_last_assets_event::( + AssetsEvent::AssetRegistered( + utils::symbol_asset_id::(), + permissioned_account_id + ).into() + ); } set_synthetic_asset_fee { diff --git a/pallets/xst/benchmarking/src/mock.rs b/pallets/xst/benchmarking/src/mock.rs index 3331316789..140987ee83 100644 --- a/pallets/xst/benchmarking/src/mock.rs +++ b/pallets/xst/benchmarking/src/mock.rs @@ -595,6 +595,7 @@ impl ExtBuilder { .endowed_accounts .iter() .cloned() + .chain(self.endowed_accounts_with_synthetics.iter().cloned()) .map(|(account_id, asset_id, _, symbol, name, precision)| { ( asset_id, diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index b24ae40672..60925a4973 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -68,6 +68,7 @@ pub trait WeightInfo { fn set_reference_asset() -> Weight; fn enable_synthetic_asset() -> Weight; fn disable_synthetic_asset() -> Weight; + fn register_synthetic_asset() -> Weight; fn set_synthetic_asset_fee() -> Weight; fn set_synthetic_base_asset_floor_price() -> Weight; } @@ -187,7 +188,7 @@ pub mod pallet { Ok(().into()) } - #[pallet::weight(10_000_000)] + #[pallet::weight(::WeightInfo::register_synthetic_asset())] pub fn register_synthetic_asset( origin: OriginFor, asset_symbol: AssetSymbol, diff --git a/pallets/xst/src/weights.rs b/pallets/xst/src/weights.rs index 57dc698510..48a8bb9c0a 100644 --- a/pallets/xst/src/weights.rs +++ b/pallets/xst/src/weights.rs @@ -31,26 +31,25 @@ //! Autogenerated weights for `xst` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2022-12-18, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! HOSTNAME: `Amaterasu.local`, CPU: `` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("local"), DB CACHE: 1024 +//! DATE: 2023-03-29, STEPS: `10`, REPEAT: 2, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `MacBook-Pro-qwerty.local`, CPU: `` +//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/framenode +// ./target/debug/framenode // benchmark // pallet -// --chain=local -// --execution=wasm -// --wasm-execution=compiled +// --chain=dev // --pallet // xst -// --extrinsic=* +// --extrinsic +// * // --steps -// 50 +// 10 // --repeat -// 20 +// 2 // --output -// ./ +// pallets/xst/src/weigths_raw.rs #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -65,41 +64,48 @@ pub struct WeightInfo(PhantomData); impl crate::WeightInfo for WeightInfo { // Storage: XSTPool ReferenceAssetId (r:0 w:1) fn set_reference_asset() -> Weight { - (12_000_000 as Weight) + (99_000_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: XSTPool EnabledSymbols (r:1 w:1) + // Storage: OracleProxy EnabledOracles (r:1 w:0) // Storage: Band SymbolRates (r:2 w:0) - // Storage: XSTPool PermissionedTechAccount (r:1 w:0) - // Storage: Assets AssetOwners (r:2 w:1) - // Storage: System Account (r:1 w:1) - // Storage: Permissions Owners (r:2 w:2) - // Storage: Permissions Permissions (r:4 w:1) + // Storage: Assets AssetOwners (r:1 w:0) // Storage: DEXManager DEXInfos (r:1 w:0) - // Storage: TradingPair EnabledSources (r:1 w:1) - // Storage: Assets AssetInfos (r:0 w:1) + // Storage: TradingPair EnabledSources (r:1 w:0) // Storage: XSTPool EnabledSynthetics (r:0 w:1) fn enable_synthetic_asset() -> Weight { - (149_000_000 as Weight) - .saturating_add(T::DbWeight::get().reads(15 as Weight)) - .saturating_add(T::DbWeight::get().writes(9 as Weight)) + (339_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(7 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: XSTPool EnabledSynthetics (r:1 w:1) // Storage: XSTPool EnabledSymbols (r:0 w:1) fn disable_synthetic_asset() -> Weight { - (21_000_000 as Weight) + (157_000_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } + // Storage: XSTPool PermissionedTechAccount (r:1 w:0) + // Storage: Assets AssetOwners (r:1 w:1) + // Storage: System Account (r:1 w:1) + // Storage: Permissions Owners (r:2 w:2) + // Storage: Permissions Permissions (r:3 w:1) + // Storage: Assets AssetInfos (r:0 w:1) + fn register_synthetic_asset() -> Weight { + (689_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(8 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) + } // Storage: XSTPool EnabledSynthetics (r:1 w:1) fn set_synthetic_asset_fee() -> Weight { - (19_000_000 as Weight) + (134_000_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: XSTPool SyntheticBaseAssetFloorPrice (r:0 w:1) fn set_synthetic_base_asset_floor_price() -> Weight { - (12_000_000 as Weight) + (90_000_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } } @@ -114,6 +120,9 @@ impl crate::WeightInfo for () { fn disable_synthetic_asset() -> Weight { EXTRINSIC_FIXED_WEIGHT } + fn register_synthetic_asset() -> Weight { + EXTRINSIC_FIXED_WEIGHT + } fn set_synthetic_asset_fee() -> Weight { EXTRINSIC_FIXED_WEIGHT } From 96c18e4dfd2360f078d9ce86c6c3294c30d8fcbd Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Wed, 29 Mar 2023 13:25:39 +0300 Subject: [PATCH 45/72] fixed tests --- pallets/xst/src/mock.rs | 1 + pallets/xst/src/tests.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/pallets/xst/src/mock.rs b/pallets/xst/src/mock.rs index f6eb6f8e12..06ccbe6d1d 100644 --- a/pallets/xst/src/mock.rs +++ b/pallets/xst/src/mock.rs @@ -612,6 +612,7 @@ impl ExtBuilder { .endowed_accounts .iter() .cloned() + .chain(self.endowed_accounts_with_synthetics.iter().cloned()) .map(|(account_id, asset_id, _, symbol, name, precision)| { ( asset_id, diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index d24de7af2d..ce4b540e59 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -644,6 +644,13 @@ mod tests { let asset_id = AssetId32::::from_synthetic_reference_symbol(&euro); + XSTPool::register_synthetic_asset( + Origin::root(), + AssetSymbol("XSTEUR".into()), + AssetName("XST Euro".into()), + euro.clone(), + ).expect("Failed to register synthetic asset"); + XSTPool::enable_synthetic_asset( Origin::root(), asset_id, @@ -665,6 +672,22 @@ mod tests { assert!(XSTPool::enabled_synthetics(&xsteuro).is_none()); assert!(XSTPool::enabled_symbols(&euro).is_none()); + + XSTPool::enable_synthetic_asset( + Origin::root(), + asset_id, + euro.clone(), + fixed!(0), + ).expect("Failed to enable synthetic asset"); + + let opt_xsteuro = XSTPool::enabled_symbols(&euro); + assert!(opt_xsteuro.is_some()); + + let xsteuro = opt_xsteuro.unwrap(); + assert_eq!( + XSTPool::enabled_synthetics(&xsteuro).expect("Failed to get synthetic asset").reference_symbol, + euro + ); }); } @@ -683,7 +706,16 @@ mod tests { .expect("Failed to add relayers"); Band::relay(Origin::signed(alice.clone()), vec![(euro.clone(), 1)], 0, 0) .expect("Failed to relay"); + let asset_id = AssetId32::::from_synthetic_reference_symbol(&euro); + + XSTPool::register_synthetic_asset( + Origin::root(), + AssetSymbol("XSTEUR".into()), + AssetName("XST Euro".into()), + euro.clone(), + ).expect("Failed to register synthetic asset"); + XSTPool::enable_synthetic_asset( Origin::root(), asset_id, From 63576bbbf22b58e15bf2271438498d696b494fe2 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Wed, 29 Mar 2023 13:25:57 +0300 Subject: [PATCH 46/72] updated xst config --- node/chain_spec/src/lib.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/node/chain_spec/src/lib.rs b/node/chain_spec/src/lib.rs index 60122be308..e1823027bf 100644 --- a/node/chain_spec/src/lib.rs +++ b/node/chain_spec/src/lib.rs @@ -1086,6 +1086,17 @@ fn testnet_genesis( None, None, ), + ( + XSTUSD, + assets_and_permissions_account_id.clone(), + AssetSymbol(b"XSTUSD".to_vec()), + AssetName(b"SORA Synthetics USD".to_vec()), + DEFAULT_BALANCE_PRECISION, + Balance::zero(), + true, + None, + None, + ), ], }, permissions: PermissionsConfig { @@ -1277,8 +1288,7 @@ fn testnet_genesis( tech_account_id: xst_pool_permissioned_tech_account_id, // TODO: move to defaults reference_asset_id: DAI, initial_synthetic_assets: vec![( - AssetSymbol(b"XSTUSD".to_vec()), - AssetName(b"SORA Synthetic USD".to_vec()), + XSTUSD.into(), common::SymbolName::usd().into(), fixed!(0.00666), )], From ce79b5cfa94d54428f9aaa9ed5c7464afc6873b6 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Thu, 30 Mar 2023 01:36:40 +0300 Subject: [PATCH 47/72] quickfix --- node/chain_spec/src/lib.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/node/chain_spec/src/lib.rs b/node/chain_spec/src/lib.rs index e1823027bf..c6f48f6d47 100644 --- a/node/chain_spec/src/lib.rs +++ b/node/chain_spec/src/lib.rs @@ -1719,6 +1719,17 @@ fn mainnet_genesis( None, None, ), + ( + XSTUSD.into(), + assets_and_permissions_account_id.clone(), + AssetSymbol(b"XSTUSD".to_vec()), + AssetName(b"SORA Synthetics USD".to_vec()), + DEFAULT_BALANCE_PRECISION, + Balance::zero(), + true, + None, + None, + ), ]; let bridge_assets_data: Vec> = Vec::new(); bridge_assets.extend(bridge_assets_data.iter().map(|x| { @@ -2021,8 +2032,7 @@ fn mainnet_genesis( tech_account_id: xst_pool_permissioned_tech_account_id, // TODO: move to defaults reference_asset_id: DAI, initial_synthetic_assets: vec![( - AssetSymbol(b"XSTUSD".to_vec()), - AssetName(b"SORA Synthetic USD".to_vec()), + XSTUSD, common::SymbolName::usd().into(), fixed!(0.00666), )], From 6efb7574a6759e21abb4d39520f3217db2387b7c Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Tue, 4 Apr 2023 11:00:08 +0300 Subject: [PATCH 48/72] added outdated oracle rates check --- pallets/xst/src/lib.rs | 38 +++++++++++++++++++++--- pallets/xst/src/tests.rs | 63 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 96 insertions(+), 5 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 60925a4973..e92dc92625 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -57,6 +57,7 @@ use common::{ use frame_support::traits::Get; use frame_support::weights::Weight; use frame_support::{ensure, fail, RuntimeDebug}; +use pallet_timestamp::Pallet as Timestamp; use permissions::{Scope, BURN, MINT}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; @@ -78,6 +79,7 @@ type Technical = technical::Pallet; pub const TECH_ACCOUNT_PREFIX: &[u8] = b"xst-pool"; pub const TECH_ACCOUNT_PERMISSIONED: &[u8] = b"permissioned"; +pub const ORACLE_RATE_STALE_PERIOD: u64 = 60 * 5; // 5 minutes pub use pallet::*; @@ -135,7 +137,9 @@ pub mod pallet { use frame_system::pallet_prelude::*; #[pallet::config] - pub trait Config: frame_system::Config + technical::Config + dex_api::Config { + pub trait Config: + frame_system::Config + technical::Config + dex_api::Config + pallet_timestamp::Config + { type Event: From> + IsType<::Event>; /// AssetId which is convertible to/from XSTUSD type GetSyntheticBaseAssetId: Get; @@ -329,6 +333,10 @@ pub mod pallet { SyntheticIsNotEnabled, /// Error quoting price from oracle. OracleQuoteError, + /// Oracle quote is outdated. + OracleRateIsOutdated, + /// Oracle quote's timestamp exceeds current time. + OracleRateHasInvalidTimestamp, } // TODO: better by replaced with Get<> @@ -846,9 +854,23 @@ impl Pallet { let symbol = EnabledSynthetics::::get(id) .ok_or(Error::::SyntheticDoesNotExist)? .reference_symbol; - let price = FixedWrapper::from(balance!(T::Oracle::quote(&symbol)? - .map(|rate| rate.value) - .ok_or(Error::::OracleQuoteError)?)); + + let oracle_quote = + T::Oracle::quote(&symbol)?.ok_or(Error::::OracleQuoteError)?; + + let current_timestamp: u64 = + Self::convert_timestamp_to_number(Timestamp::::get()); + + let time_passed: u64 = current_timestamp + .checked_sub(oracle_quote.last_updated) + .ok_or(Error::::OracleRateHasInvalidTimestamp)?; + + ensure!( + time_passed <= ORACLE_RATE_STALE_PERIOD, + Error::::OracleRateIsOutdated + ); + + let price = FixedWrapper::from(balance!(oracle_quote.value)); // Just for convenience. Right now will always return 1. let reference_asset_price = FixedWrapper::from(Self::reference_price(&reference_asset_id, price_variant)?); @@ -859,6 +881,14 @@ impl Pallet { } } + fn convert_timestamp_to_number(timestamp: T::Moment) -> u64 { + if let Ok(timestamp) = TryInto::::try_into(timestamp) { + timestamp + } else { + panic!("Timestamp is too big to fit into u64"); // Should never happen, but if it does, then we have a problem. + } + } + fn ensure_symbol_exists(reference_symbol: &T::Symbol) -> Result<(), DispatchError> { if *reference_symbol == common::SymbolName::usd().into() { return Ok(()); diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index ce4b540e59..06d26ec9af 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -32,7 +32,7 @@ mod tests { use core::str::FromStr; - use crate::{Error, Pallet, mock::*}; + use crate::{Error, Pallet, mock::*, ORACLE_RATE_STALE_PERIOD}; use common::{self, AssetName, AssetSymbol, DEXId, FromGenericPair, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, GetMarketInfo, assert_approx_eq, PriceToolsPallet, prelude::{Balance, SwapAmount, QuoteAmount, FixedWrapper, }, SymbolName, Oracle, PriceVariant, PredefinedAssetId, AssetId32}; use frame_support::{assert_ok, assert_noop}; use sp_arithmetic::traits::{Zero}; @@ -764,4 +764,65 @@ mod tests { assert_eq!(swap_outcome_after.fee, expected_fee_amount.into_balance()); }); } + + #[test] + fn reference_price_for_bad_oracle_rate_should_fail() { + let mut ext = ExtBuilder::default().build(); + ext.execute_with(|| { + MockDEXApi::init().unwrap(); + let _ = xst_pool_init().unwrap(); + + let euro = SymbolName::from_str("EURO").expect("Failed to parse `EURO` as a symbol name"); + let alice = alice(); + + OracleProxy::enable_oracle(Origin::root(), Oracle::BandChainFeed).expect("Failed to enable `Band` oracle"); + Band::add_relayers(Origin::root(), vec![alice.clone()]) + .expect("Failed to add relayers"); + Band::relay(Origin::signed(alice.clone()), vec![(euro.clone(), 1)], 0, 0) + .expect("Failed to relay"); + + let asset_id = AssetId32::::from_synthetic_reference_symbol(&euro); + + XSTPool::register_synthetic_asset( + Origin::root(), + AssetSymbol("XSTEUR".into()), + AssetName("XST Euro".into()), + euro.clone(), + ).expect("Failed to register synthetic asset"); + + XSTPool::enable_synthetic_asset( + Origin::root(), + asset_id, + euro.clone(), + fixed!(0), + ).expect("Failed to enable synthetic asset"); + + let xsteuro = XSTPool::enabled_symbols(&euro).expect("Expected synthetic asset"); + + Timestamp::set_timestamp(ORACLE_RATE_STALE_PERIOD + 1); + + assert_eq!( + XSTPool::reference_price(&xsteuro, PriceVariant::Buy), + Err(Error::::OracleRateIsOutdated.into()) + ); + + assert_eq!( + XSTPool::reference_price(&xsteuro, PriceVariant::Sell), + Err(Error::::OracleRateIsOutdated.into()) + ); + + Band::relay(Origin::signed(alice.clone()), vec![(euro.clone(), 1)], ORACLE_RATE_STALE_PERIOD + 2, 0) + .expect("Failed to relay"); + + assert_eq!( + XSTPool::reference_price(&xsteuro, PriceVariant::Buy), + Err(Error::::OracleRateHasInvalidTimestamp.into()) + ); + + assert_eq!( + XSTPool::reference_price(&xsteuro, PriceVariant::Sell), + Err(Error::::OracleRateHasInvalidTimestamp.into()) + ); + }) + } } From b230c2e74335fdd905be94d2f502b17c6377e159 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Wed, 5 Apr 2023 13:28:35 +0300 Subject: [PATCH 49/72] moved rate expiration check to band pallet --- Cargo.lock | 2 + pallets/band/Cargo.toml | 1 + pallets/band/src/lib.rs | 39 +++++++++++------ pallets/band/src/mock.rs | 15 +++++++ pallets/band/src/tests.rs | 36 +++++++++++++++- pallets/oracle-proxy/Cargo.toml | 1 + pallets/oracle-proxy/src/mock.rs | 16 +++++++ pallets/oracle-proxy/src/tests.rs | 4 +- pallets/xst/benchmarking/src/mock.rs | 5 +++ pallets/xst/src/lib.rs | 38 ++--------------- pallets/xst/src/mock.rs | 3 ++ pallets/xst/src/tests.rs | 63 +--------------------------- runtime/src/lib.rs | 6 +++ 13 files changed, 117 insertions(+), 112 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2f9f88c053..2f95b55610 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -498,6 +498,7 @@ dependencies = [ "hex-literal", "oracle-proxy", "pallet-balances", + "pallet-timestamp", "parity-scale-codec", "scale-info", "sp-core", @@ -6990,6 +6991,7 @@ dependencies = [ "frame-system", "hex-literal", "pallet-balances", + "pallet-timestamp", "parity-scale-codec", "scale-info", "serde", diff --git a/pallets/band/Cargo.toml b/pallets/band/Cargo.toml index 7f48dae178..1b03079863 100644 --- a/pallets/band/Cargo.toml +++ b/pallets/band/Cargo.toml @@ -21,6 +21,7 @@ frame-benchmarking = { git = "https://github.com/paritytech/substrate.git", bran sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } common = { path = "../../common", default-features = false } hex-literal = "0.3.1" +pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } [dev-dependencies] pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } diff --git a/pallets/band/src/lib.rs b/pallets/band/src/lib.rs index 3141e43893..2ddf6fc2ae 100644 --- a/pallets/band/src/lib.rs +++ b/pallets/band/src/lib.rs @@ -33,6 +33,8 @@ use common::prelude::FixedWrapper; use common::{Balance, DataFeed, Fixed, OnNewSymbolsRelayed, Oracle, Rate}; use frame_support::pallet_prelude::*; +use frame_support::sp_runtime::SaturatedConversion; +use frame_support::traits::UnixTime; use frame_support::weights::Weight; use frame_system::pallet_prelude::*; use sp_std::collections::btree_set::BTreeSet; @@ -92,7 +94,22 @@ pub use pallet::*; impl, I: 'static> DataFeed for Pallet { fn quote(symbol: &T::Symbol) -> Result, DispatchError> { - Ok(Self::rates(symbol).map(|rate| rate.into())) + let option_rate = Self::rates(symbol); + if let Some(rate) = option_rate { + let current_time = T::UnixTime::now().as_millis().saturated_into::(); + let stale_period = T::GetBandRateStalePeriod::get(); + let current_period = current_time + .checked_sub(rate.last_updated) + .ok_or(Error::::RateHasInvalidTimestamp)?; + sp_std::if_std! { + println!("current_time: {}; current_period: {}", current_time, current_period); + } + ensure!(current_period < stale_period, Error::::RateExpired); + + Ok(Some(rate.into())) + } else { + Ok(None) + } } fn list_enabled_symbols() -> Result, DispatchError> { @@ -134,6 +151,10 @@ pub mod pallet { type WeightInfo: WeightInfo; /// Hook which is being executed when some new symbols were relayed type OnNewSymbolsRelayedHook: OnNewSymbolsRelayed; + /// Rate expiration period in seconds. + type GetBandRateStalePeriod: Get; + /// Time used for checking if rate expired + type UnixTime: UnixTime; } #[pallet::storage] @@ -167,6 +188,10 @@ pub mod pallet { NoSuchRelayer, /// Relayed rate is too big to be stored in the pallet. RateConversionOverflow, + /// Rate has invalid timestamp. + RateHasInvalidTimestamp, + /// Rate is expired and can't be used until next update. + RateExpired, } #[pallet::call] @@ -379,15 +404,3 @@ impl, I: 'static> Pallet { .ok_or_else(|| Error::::RateConversionOverflow.into()) } } - -impl, I: 'static> DataFeed for Pallet { - fn quote(symbol: &T::Symbol) -> Result, DispatchError> { - Ok(SymbolRates::::get(symbol).map(|rate| rate.value)) - } - - fn list_enabled_symbols() -> Result, DispatchError> { - Ok(SymbolRates::::iter() - .filter_map(|(symbol, option_rate)| option_rate.map(|rate| (symbol, rate.last_updated))) - .collect()) - } -} diff --git a/pallets/band/src/mock.rs b/pallets/band/src/mock.rs index bc6e0eb747..1082dd2e30 100644 --- a/pallets/band/src/mock.rs +++ b/pallets/band/src/mock.rs @@ -50,9 +50,15 @@ frame_support::construct_runtime!( System: frame_system, Band: band, OracleProxy: oracle_proxy, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, } ); +frame_support::parameter_types! { + pub const GetRateStalePeriod: u64 = 60*5; + pub const MinimumPeriod: u64 = 5; +} + impl system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -80,11 +86,20 @@ impl system::Config for Runtime { type MaxConsumers = frame_support::traits::ConstU32<16>; } +impl pallet_timestamp::Config for Runtime { + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); +} + impl Config for Runtime { type Symbol = String; type Event = Event; type WeightInfo = (); type OnNewSymbolsRelayedHook = oracle_proxy::Pallet; + type UnixTime = Timestamp; + type GetBandRateStalePeriod = GetRateStalePeriod; } impl oracle_proxy::Config for Runtime { diff --git a/pallets/band/src/tests.rs b/pallets/band/src/tests.rs index 20545168b6..a7d49156e0 100644 --- a/pallets/band/src/tests.rs +++ b/pallets/band/src/tests.rs @@ -374,7 +374,7 @@ fn quote_and_list_enabled_symbols_should_work() { let symbols = vec!["USD".to_owned(), "RUB".to_owned(), "YEN".to_owned()]; let rates = vec![1, 2, 3]; let relayer = 1; - let initial_resolve_time = 100; + let initial_resolve_time = 0; for symbol in &symbols { assert_eq!(Band::rates(symbol), None); @@ -427,3 +427,37 @@ fn quote_and_list_enabled_symbols_should_work() { assert_eq!(enabled_symbols_res, enabled_symbols) }); } + +#[test] +fn quote_invalid_rate_should_fail() { + new_test_ext().execute_with(|| { + let relayer = 1; + + assert_eq!(Band::rates("USD".to_owned()), None); + assert_eq!(Band::rates("RUB".to_owned()), None); + + Band::add_relayers(Origin::root(), vec![relayer]).expect("Failed to add relayers"); + Band::relay(Origin::signed(relayer), vec![("USD".to_owned(), 1)], 0, 0) + .expect("Failed to relay rates"); + + Band::relay( + Origin::signed(relayer), + vec![("RUB".to_owned(), 1)], + 10000000, + 0, + ) + .expect("Failed to relay rates"); + + Timestamp::set_timestamp(GetRateStalePeriod::get() + 10); + + assert_eq!( + >::quote(&"USD".to_owned()), + Err(Error::::RateExpired.into()) + ); + + assert_eq!( + >::quote(&"RUB".to_owned()), + Err(Error::::RateHasInvalidTimestamp.into()) + ); + }) +} diff --git a/pallets/oracle-proxy/Cargo.toml b/pallets/oracle-proxy/Cargo.toml index 2af5c1c76c..0a2a7fd36a 100644 --- a/pallets/oracle-proxy/Cargo.toml +++ b/pallets/oracle-proxy/Cargo.toml @@ -28,6 +28,7 @@ sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polka hex-literal = "0.3.1" pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } band = { path = "../band", default-features = false } +pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } [features] default = ['std'] diff --git a/pallets/oracle-proxy/src/mock.rs b/pallets/oracle-proxy/src/mock.rs index a6d9265c8a..f12cf9e5d6 100644 --- a/pallets/oracle-proxy/src/mock.rs +++ b/pallets/oracle-proxy/src/mock.rs @@ -34,6 +34,7 @@ use frame_support::traits::{ConstU16, ConstU64}; use frame_system as system; use sp_core::H256; use sp_runtime::{ + parameter_types, testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; @@ -51,6 +52,7 @@ frame_support::construct_runtime!( System: frame_system, Band: band, OracleProxy: oracle_proxy, + Timestamp: pallet_timestamp, } ); @@ -88,11 +90,25 @@ impl Config for Runtime { type BandChainOracle = band::Pallet; } +parameter_types! { + pub const GetBandRateStalePeriod: u64 = 5*60; + pub const MinimumPeriod: u64 = 5; +} + +impl pallet_timestamp::Config for Runtime { + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); +} + impl band::Config for Runtime { type Symbol = ::Symbol; type Event = Event; type WeightInfo = (); type OnNewSymbolsRelayedHook = oracle_proxy::Pallet; + type UnixTime = Timestamp; + type GetBandRateStalePeriod = GetBandRateStalePeriod; } // Build genesis storage according to the mock runtime. diff --git a/pallets/oracle-proxy/src/tests.rs b/pallets/oracle-proxy/src/tests.rs index 2ce81ea719..ec3f7a244b 100644 --- a/pallets/oracle-proxy/src/tests.rs +++ b/pallets/oracle-proxy/src/tests.rs @@ -38,7 +38,7 @@ fn relay_symbols() { let symbols = vec!["USD".to_owned(), "RUB".to_owned(), "YEN".to_owned()]; let rates = vec![1, 2, 3]; let relayer = 1; - let initial_resolve_time = 100; + let initial_resolve_time = 0; Band::add_relayers(Origin::root(), vec![relayer]).expect("Failed to add relayers"); Band::relay( @@ -98,7 +98,7 @@ fn quote_and_list_enabled_symbols_should_work() { let symbols = vec!["USD".to_owned(), "RUB".to_owned(), "YEN".to_owned()]; let rates = vec![1, 2, 3]; - let resolve_time = 100; + let resolve_time = 0; symbols .iter() diff --git a/pallets/xst/benchmarking/src/mock.rs b/pallets/xst/benchmarking/src/mock.rs index 140987ee83..503bdafa2e 100644 --- a/pallets/xst/benchmarking/src/mock.rs +++ b/pallets/xst/benchmarking/src/mock.rs @@ -94,6 +94,7 @@ parameter_types! { pub GetParliamentAccountId: AccountId = AccountId32::from([152; 32]); pub GetXykFee: Fixed = fixed!(0.003); pub const MinimumPeriod: u64 = 5; + pub const GetBandRateStalePeriod: u64 = 60*5; } construct_runtime! { @@ -180,6 +181,8 @@ impl band::Config for Runtime { type Symbol = common::SymbolName; type WeightInfo = (); type OnNewSymbolsRelayedHook = (); + type UnixTime = Timestamp; + type GetBandRateStalePeriod = GetBandRateStalePeriod; } impl oracle_proxy::Config for Runtime { @@ -295,6 +298,8 @@ impl pswap_distribution::Config for Runtime { type WeightInfo = (); type GetParliamentAccountId = GetParliamentAccountId; type PoolXykPallet = PoolXYK; + type GetXSTAssetId = GetSyntheticBaseAssetId; + type BuyBackHandler = (); } impl demeter_farming_platform::Config for Runtime { diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index e92dc92625..60925a4973 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -57,7 +57,6 @@ use common::{ use frame_support::traits::Get; use frame_support::weights::Weight; use frame_support::{ensure, fail, RuntimeDebug}; -use pallet_timestamp::Pallet as Timestamp; use permissions::{Scope, BURN, MINT}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; @@ -79,7 +78,6 @@ type Technical = technical::Pallet; pub const TECH_ACCOUNT_PREFIX: &[u8] = b"xst-pool"; pub const TECH_ACCOUNT_PERMISSIONED: &[u8] = b"permissioned"; -pub const ORACLE_RATE_STALE_PERIOD: u64 = 60 * 5; // 5 minutes pub use pallet::*; @@ -137,9 +135,7 @@ pub mod pallet { use frame_system::pallet_prelude::*; #[pallet::config] - pub trait Config: - frame_system::Config + technical::Config + dex_api::Config + pallet_timestamp::Config - { + pub trait Config: frame_system::Config + technical::Config + dex_api::Config { type Event: From> + IsType<::Event>; /// AssetId which is convertible to/from XSTUSD type GetSyntheticBaseAssetId: Get; @@ -333,10 +329,6 @@ pub mod pallet { SyntheticIsNotEnabled, /// Error quoting price from oracle. OracleQuoteError, - /// Oracle quote is outdated. - OracleRateIsOutdated, - /// Oracle quote's timestamp exceeds current time. - OracleRateHasInvalidTimestamp, } // TODO: better by replaced with Get<> @@ -854,23 +846,9 @@ impl Pallet { let symbol = EnabledSynthetics::::get(id) .ok_or(Error::::SyntheticDoesNotExist)? .reference_symbol; - - let oracle_quote = - T::Oracle::quote(&symbol)?.ok_or(Error::::OracleQuoteError)?; - - let current_timestamp: u64 = - Self::convert_timestamp_to_number(Timestamp::::get()); - - let time_passed: u64 = current_timestamp - .checked_sub(oracle_quote.last_updated) - .ok_or(Error::::OracleRateHasInvalidTimestamp)?; - - ensure!( - time_passed <= ORACLE_RATE_STALE_PERIOD, - Error::::OracleRateIsOutdated - ); - - let price = FixedWrapper::from(balance!(oracle_quote.value)); + let price = FixedWrapper::from(balance!(T::Oracle::quote(&symbol)? + .map(|rate| rate.value) + .ok_or(Error::::OracleQuoteError)?)); // Just for convenience. Right now will always return 1. let reference_asset_price = FixedWrapper::from(Self::reference_price(&reference_asset_id, price_variant)?); @@ -881,14 +859,6 @@ impl Pallet { } } - fn convert_timestamp_to_number(timestamp: T::Moment) -> u64 { - if let Ok(timestamp) = TryInto::::try_into(timestamp) { - timestamp - } else { - panic!("Timestamp is too big to fit into u64"); // Should never happen, but if it does, then we have a problem. - } - } - fn ensure_symbol_exists(reference_symbol: &T::Symbol) -> Result<(), DispatchError> { if *reference_symbol == common::SymbolName::usd().into() { return Ok(()); diff --git a/pallets/xst/src/mock.rs b/pallets/xst/src/mock.rs index a644527790..d692903569 100644 --- a/pallets/xst/src/mock.rs +++ b/pallets/xst/src/mock.rs @@ -94,6 +94,7 @@ parameter_types! { pub GetParliamentAccountId: AccountId = AccountId32::from([152; 32]); pub GetXykFee: Fixed = fixed!(0.003); pub const MinimumPeriod: u64 = 5; + pub const GetBandRateStalePeriod: u64 = 60*5; } construct_runtime! { @@ -180,6 +181,8 @@ impl band::Config for Runtime { type Symbol = common::SymbolName; type WeightInfo = (); type OnNewSymbolsRelayedHook = oracle_proxy::Pallet; + type GetBandRateStalePeriod = GetBandRateStalePeriod; + type UnixTime = Timestamp; } impl oracle_proxy::Config for Runtime { diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index 06d26ec9af..ce4b540e59 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -32,7 +32,7 @@ mod tests { use core::str::FromStr; - use crate::{Error, Pallet, mock::*, ORACLE_RATE_STALE_PERIOD}; + use crate::{Error, Pallet, mock::*}; use common::{self, AssetName, AssetSymbol, DEXId, FromGenericPair, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, GetMarketInfo, assert_approx_eq, PriceToolsPallet, prelude::{Balance, SwapAmount, QuoteAmount, FixedWrapper, }, SymbolName, Oracle, PriceVariant, PredefinedAssetId, AssetId32}; use frame_support::{assert_ok, assert_noop}; use sp_arithmetic::traits::{Zero}; @@ -764,65 +764,4 @@ mod tests { assert_eq!(swap_outcome_after.fee, expected_fee_amount.into_balance()); }); } - - #[test] - fn reference_price_for_bad_oracle_rate_should_fail() { - let mut ext = ExtBuilder::default().build(); - ext.execute_with(|| { - MockDEXApi::init().unwrap(); - let _ = xst_pool_init().unwrap(); - - let euro = SymbolName::from_str("EURO").expect("Failed to parse `EURO` as a symbol name"); - let alice = alice(); - - OracleProxy::enable_oracle(Origin::root(), Oracle::BandChainFeed).expect("Failed to enable `Band` oracle"); - Band::add_relayers(Origin::root(), vec![alice.clone()]) - .expect("Failed to add relayers"); - Band::relay(Origin::signed(alice.clone()), vec![(euro.clone(), 1)], 0, 0) - .expect("Failed to relay"); - - let asset_id = AssetId32::::from_synthetic_reference_symbol(&euro); - - XSTPool::register_synthetic_asset( - Origin::root(), - AssetSymbol("XSTEUR".into()), - AssetName("XST Euro".into()), - euro.clone(), - ).expect("Failed to register synthetic asset"); - - XSTPool::enable_synthetic_asset( - Origin::root(), - asset_id, - euro.clone(), - fixed!(0), - ).expect("Failed to enable synthetic asset"); - - let xsteuro = XSTPool::enabled_symbols(&euro).expect("Expected synthetic asset"); - - Timestamp::set_timestamp(ORACLE_RATE_STALE_PERIOD + 1); - - assert_eq!( - XSTPool::reference_price(&xsteuro, PriceVariant::Buy), - Err(Error::::OracleRateIsOutdated.into()) - ); - - assert_eq!( - XSTPool::reference_price(&xsteuro, PriceVariant::Sell), - Err(Error::::OracleRateIsOutdated.into()) - ); - - Band::relay(Origin::signed(alice.clone()), vec![(euro.clone(), 1)], ORACLE_RATE_STALE_PERIOD + 2, 0) - .expect("Failed to relay"); - - assert_eq!( - XSTPool::reference_price(&xsteuro, PriceVariant::Buy), - Err(Error::::OracleRateHasInvalidTimestamp.into()) - ); - - assert_eq!( - XSTPool::reference_price(&xsteuro, PriceVariant::Sell), - Err(Error::::OracleRateHasInvalidTimestamp.into()) - ); - }) - } } diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 58ce21431d..f3a1b42ea6 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1800,11 +1800,17 @@ impl oracle_proxy::Config for Runtime { type BandChainOracle = band::Pallet; } +parameter_types! { + pub const GetBandRateStalePeriod: u64 = 60*5; +} + impl band::Config for Runtime { type Event = Event; type Symbol = Symbol; type WeightInfo = band::weights::WeightInfo; type OnNewSymbolsRelayedHook = oracle_proxy::Pallet; + type UnixTime = Timestamp; + type GetBandRateStalePeriod = GetBandRateStalePeriod; } parameter_types! { From 3b764a544bf03adf1bb1e44b203ae33aa3134868 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Thu, 6 Apr 2023 13:00:58 +0300 Subject: [PATCH 50/72] quickfix --- pallets/band/src/lib.rs | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/pallets/band/src/lib.rs b/pallets/band/src/lib.rs index 2ddf6fc2ae..5c45eb25c3 100644 --- a/pallets/band/src/lib.rs +++ b/pallets/band/src/lib.rs @@ -94,22 +94,21 @@ pub use pallet::*; impl, I: 'static> DataFeed for Pallet { fn quote(symbol: &T::Symbol) -> Result, DispatchError> { - let option_rate = Self::rates(symbol); - if let Some(rate) = option_rate { - let current_time = T::UnixTime::now().as_millis().saturated_into::(); - let stale_period = T::GetBandRateStalePeriod::get(); - let current_period = current_time - .checked_sub(rate.last_updated) - .ok_or(Error::::RateHasInvalidTimestamp)?; - sp_std::if_std! { - println!("current_time: {}; current_period: {}", current_time, current_period); - } - ensure!(current_period < stale_period, Error::::RateExpired); - - Ok(Some(rate.into())) + let rate = if let Some(rate) = Self::rates(symbol) { + rate } else { - Ok(None) + return Ok(None); + }; + let current_time = T::UnixTime::now().as_millis().saturated_into::(); + let stale_period = T::GetBandRateStalePeriod::get(); + let current_period = current_time + .checked_sub(rate.last_updated) + .ok_or(Error::::RateHasInvalidTimestamp)?; + sp_std::if_std! { + println!("current_time: {}; current_period: {}", current_time, current_period); } + ensure!(current_period < stale_period, Error::::RateExpired); + Ok(Some(rate.into())) } fn list_enabled_symbols() -> Result, DispatchError> { From 0740eef82c8d5099338e5e6a2897b4f3baa60488 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Fri, 7 Apr 2023 13:29:45 +0300 Subject: [PATCH 51/72] quickfix --- pallets/band/src/lib.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pallets/band/src/lib.rs b/pallets/band/src/lib.rs index 5c45eb25c3..f4ca4f5738 100644 --- a/pallets/band/src/lib.rs +++ b/pallets/band/src/lib.rs @@ -99,15 +99,15 @@ impl, I: 'static> DataFeed for Pallet { } else { return Ok(None); }; + let current_time = T::UnixTime::now().as_millis().saturated_into::(); let stale_period = T::GetBandRateStalePeriod::get(); let current_period = current_time .checked_sub(rate.last_updated) .ok_or(Error::::RateHasInvalidTimestamp)?; - sp_std::if_std! { - println!("current_time: {}; current_period: {}", current_time, current_period); - } + ensure!(current_period < stale_period, Error::::RateExpired); + Ok(Some(rate.into())) } From a4d12c3968c75a225d940f9d5f0344e9d5692a08 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Fri, 7 Apr 2023 13:45:20 +0300 Subject: [PATCH 52/72] quickfix --- pallets/band/src/lib.rs | 1 + pallets/oracle-proxy/src/mock.rs | 2 +- pallets/xst/benchmarking/src/mock.rs | 2 +- pallets/xst/src/mock.rs | 2 +- runtime/src/lib.rs | 2 +- 5 files changed, 5 insertions(+), 4 deletions(-) diff --git a/pallets/band/src/lib.rs b/pallets/band/src/lib.rs index f4ca4f5738..d5e40c922d 100644 --- a/pallets/band/src/lib.rs +++ b/pallets/band/src/lib.rs @@ -151,6 +151,7 @@ pub mod pallet { /// Hook which is being executed when some new symbols were relayed type OnNewSymbolsRelayedHook: OnNewSymbolsRelayed; /// Rate expiration period in seconds. + #[pallet::constant] type GetBandRateStalePeriod: Get; /// Time used for checking if rate expired type UnixTime: UnixTime; diff --git a/pallets/oracle-proxy/src/mock.rs b/pallets/oracle-proxy/src/mock.rs index f12cf9e5d6..ac2138244a 100644 --- a/pallets/oracle-proxy/src/mock.rs +++ b/pallets/oracle-proxy/src/mock.rs @@ -91,7 +91,7 @@ impl Config for Runtime { } parameter_types! { - pub const GetBandRateStalePeriod: u64 = 5*60; + pub const GetBandRateStalePeriod: u64 = 5*60; // 5 minutes pub const MinimumPeriod: u64 = 5; } diff --git a/pallets/xst/benchmarking/src/mock.rs b/pallets/xst/benchmarking/src/mock.rs index 503bdafa2e..c14e8e6250 100644 --- a/pallets/xst/benchmarking/src/mock.rs +++ b/pallets/xst/benchmarking/src/mock.rs @@ -94,7 +94,7 @@ parameter_types! { pub GetParliamentAccountId: AccountId = AccountId32::from([152; 32]); pub GetXykFee: Fixed = fixed!(0.003); pub const MinimumPeriod: u64 = 5; - pub const GetBandRateStalePeriod: u64 = 60*5; + pub const GetBandRateStalePeriod: u64 = 60*5; // 5 minutes } construct_runtime! { diff --git a/pallets/xst/src/mock.rs b/pallets/xst/src/mock.rs index d692903569..f1681157bb 100644 --- a/pallets/xst/src/mock.rs +++ b/pallets/xst/src/mock.rs @@ -94,7 +94,7 @@ parameter_types! { pub GetParliamentAccountId: AccountId = AccountId32::from([152; 32]); pub GetXykFee: Fixed = fixed!(0.003); pub const MinimumPeriod: u64 = 5; - pub const GetBandRateStalePeriod: u64 = 60*5; + pub const GetBandRateStalePeriod: u64 = 60*5; // 5 minutes } construct_runtime! { diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 63e0e74085..e7fe7f5bf8 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1804,7 +1804,7 @@ impl oracle_proxy::Config for Runtime { } parameter_types! { - pub const GetBandRateStalePeriod: u64 = 60*5; + pub const GetBandRateStalePeriod: u64 = 60*5; // 5 minutes } impl band::Config for Runtime { From ea4e2da37259fdf5533622cbd94a486667b6f414 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Wed, 12 Apr 2023 15:31:29 +0300 Subject: [PATCH 53/72] quickfix --- node/chain_spec/src/lib.rs | 13 +++++++-- pallets/xst/benchmarking/src/lib.rs | 41 ++++++++++++++++++++++++++-- pallets/xst/benchmarking/src/mock.rs | 36 ++++++++++++++++++++++-- pallets/xst/src/lib.rs | 37 ++----------------------- pallets/xst/src/mock.rs | 33 ++++++++++++++++++++-- pallets/xst/src/tests.rs | 24 +--------------- runtime/src/lib.rs | 1 + 7 files changed, 118 insertions(+), 67 deletions(-) diff --git a/node/chain_spec/src/lib.rs b/node/chain_spec/src/lib.rs index 899f740474..451f84f1a8 100644 --- a/node/chain_spec/src/lib.rs +++ b/node/chain_spec/src/lib.rs @@ -1526,7 +1526,6 @@ fn testnet_genesis( technical_membership: Default::default(), im_online: Default::default(), xst_pool: XSTPoolConfig { - tech_account_id: xst_pool_permissioned_tech_account_id, // TODO: move to defaults reference_asset_id: DAI, initial_synthetic_assets: vec![( XSTUSD.into(), @@ -1769,6 +1768,8 @@ fn mainnet_genesis( let xst_pool_permissioned_tech_account_id = framenode_runtime::GetXSTPoolPermissionedTechAccountId::get(); + let xst_pool_permissioned_account_id = + framenode_runtime::GetXSTPoolPermissionedAccountId::get(); let market_maker_rewards_tech_account_id = framenode_runtime::GetMarketMakerRewardsTechAccountId::get(); @@ -1846,6 +1847,10 @@ fn mainnet_genesis( mbc_pool_free_reserves_account_id.clone(), mbc_pool_free_reserves_tech_account_id.clone(), ), + ( + xst_pool_permissioned_account_id.clone(), + xst_pool_permissioned_tech_account_id.clone(), + ), ( iroha_migration_account_id.clone(), iroha_migration_tech_account_id.clone(), @@ -2154,6 +2159,11 @@ fn mainnet_genesis( Scope::Unlimited, vec![permissions::MINT, permissions::BURN], ), + ( + xst_pool_permissioned_account_id.clone(), + Scope::Unlimited, + vec![permissions::MINT, permissions::BURN], + ), ], }, balances: BalancesConfig { @@ -2310,7 +2320,6 @@ fn mainnet_genesis( technical_membership: Default::default(), im_online: Default::default(), xst_pool: XSTPoolConfig { - tech_account_id: xst_pool_permissioned_tech_account_id, // TODO: move to defaults reference_asset_id: DAI, initial_synthetic_assets: vec![( XSTUSD, diff --git a/pallets/xst/benchmarking/src/lib.rs b/pallets/xst/benchmarking/src/lib.rs index 5328d8624e..b3e5592f30 100644 --- a/pallets/xst/benchmarking/src/lib.rs +++ b/pallets/xst/benchmarking/src/lib.rs @@ -35,9 +35,13 @@ use assets::Event as AssetsEvent; use band::Pallet as Band; use codec::{Decode as _, Encode as _}; -use common::{balance, fixed, AssetName, AssetSymbol, Oracle, DAI, XSTUSD}; +use common::prelude::{QuoteAmount, SwapAmount}; +use common::{ + balance, fixed, AssetName, AssetSymbol, DEXId, LiquiditySource, Oracle, DAI, XST, XSTUSD, +}; use frame_benchmarking::benchmarks; use frame_support::pallet_prelude::DispatchResultWithPostInfo; +use frame_support::traits::Get; use frame_system::{EventRecord, RawOrigin}; use hex_literal::hex; use oracle_proxy::Pallet as OracleProxy; @@ -94,7 +98,7 @@ mod utils { Band::::add_relayers(RawOrigin::Root.into(), vec![alice::()])?; Band::::relay( RawOrigin::Signed(alice::()).into(), - vec![(symbol::<::Symbol>(), 1)], + vec![(symbol::<::Symbol>(), 1000000000)], 0, 0, ) @@ -165,7 +169,7 @@ benchmarks! { } register_synthetic_asset { - let permissioned_tech_account_id = XSTPool::::permissioned_tech_account(); + let permissioned_tech_account_id = T::GetXSTPoolPermissionedTechAccountId::get(); let permissioned_account_id = Technical::::tech_account_id_to_account_id(&permissioned_tech_account_id) .expect("Expected to generate account id from technical"); @@ -203,5 +207,36 @@ benchmarks! { utils::assert_last_event::(Event::SyntheticBaseAssetFloorPriceChanged(balance!(200)).into()) } + quote { + let asset_id = utils::enable_synthetic_asset::()?; + }: { + let _ = XSTPool::::quote( + &DEXId::Polkaswap.into(), + &XST.into(), + &asset_id, + QuoteAmount::with_desired_input(balance!(1)), + true, + ).unwrap(); + } + + exchange { + let asset_id = utils::enable_synthetic_asset::()?; + assets::Pallet::::update_balance( + RawOrigin::Root.into(), + utils::alice::().into(), + XST.into(), + 1000000000000000000, + ).unwrap(); + }: { + let _ = XSTPool::::exchange( + &utils::alice::(), + &utils::alice::(), + &DEXId::Polkaswap.into(), + &XST.into(), + &asset_id, + SwapAmount::with_desired_input(balance!(1), 1), + ).unwrap(); + } + impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Runtime); } diff --git a/pallets/xst/benchmarking/src/mock.rs b/pallets/xst/benchmarking/src/mock.rs index 9054c52035..bf27838326 100644 --- a/pallets/xst/benchmarking/src/mock.rs +++ b/pallets/xst/benchmarking/src/mock.rs @@ -33,8 +33,8 @@ use common::mock::ExistentialDeposits; use common::prelude::{Balance, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapOutcome}; use common::{ self, balance, fixed, fixed_wrapper, hash, Amount, AssetId32, AssetName, AssetSymbol, DEXInfo, - Fixed, PriceVariant, TechPurpose, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, - XSTUSD, + Fixed, FromGenericPair, PriceVariant, TechPurpose, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, + VAL, XOR, XST, XSTUSD, }; use currencies::BasicCurrencyAdapter; use frame_support::traits::{Everything, GenesisBuild}; @@ -95,6 +95,20 @@ parameter_types! { pub GetXykFee: Fixed = fixed!(0.003); pub const MinimumPeriod: u64 = 5; pub const GetBandRateStalePeriod: u64 = 60*5*1000; // 5 minutes + pub GetXSTPoolPermissionedTechAccountId: TechAccountId = { + let tech_account_id = TechAccountId::from_generic_pair( + xst::TECH_ACCOUNT_PREFIX.to_vec(), + xst::TECH_ACCOUNT_PERMISSIONED.to_vec(), + ); + tech_account_id + }; + pub GetXSTPoolPermissionedAccountId: AccountId = { + let tech_account_id = GetXSTPoolPermissionedTechAccountId::get(); + let account_id = + technical::Pallet::::tech_account_id_to_account_id(&tech_account_id) + .expect("Failed to get ordinary account id for technical account id."); + account_id + }; } construct_runtime! { @@ -169,6 +183,7 @@ impl mock_liquidity_source::Config for Runtime impl xst::Config for Runtime { type RuntimeEvent = RuntimeEvent; type GetSyntheticBaseAssetId = GetSyntheticBaseAssetId; + type GetXSTPoolPermissionedTechAccountId = GetXSTPoolPermissionedTechAccountId; type EnsureDEXManager = dex_manager::Pallet; type PriceToolsPallet = MockDEXApi; type Oracle = OracleProxy; @@ -180,7 +195,7 @@ impl band::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Symbol = common::SymbolName; type WeightInfo = (); - type OnNewSymbolsRelayedHook = (); + type OnNewSymbolsRelayedHook = OracleProxy; type UnixTime = Timestamp; type GetBandRateStalePeriod = GetBandRateStalePeriod; } @@ -407,6 +422,7 @@ impl MockDEXApi { pub fn get_mock_prices() -> HashMap<(AssetId, AssetId), Balance> { let direct = vec![ ((XOR, VAL), balance!(2.0)), + ((XOR, XST), balance!(0.55768)), // USDT ((XOR, USDT), balance!(100.0)), ((VAL, USDT), balance!(50.0)), @@ -528,6 +544,11 @@ impl Default for ExtBuilder { Scope::Unlimited, vec![permissions::MINT, permissions::BURN], ), + ( + GetXSTPoolPermissionedAccountId::get(), + Scope::Unlimited, + vec![permissions::MINT, permissions::BURN], + ), ], } } @@ -585,6 +606,15 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); + technical::GenesisConfig:: { + register_tech_accounts: vec![( + GetXSTPoolPermissionedAccountId::get(), + GetXSTPoolPermissionedTechAccountId::get(), + )], + } + .assimilate_storage(&mut t) + .unwrap(); + permissions::GenesisConfig:: { initial_permission_owners: self.initial_permission_owners, initial_permissions: self.initial_permissions, diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index 297dd22b93..c99e7bf914 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -57,7 +57,6 @@ use common::{ use frame_support::traits::Get; use frame_support::weights::Weight; use frame_support::{ensure, fail, RuntimeDebug}; -use permissions::{Scope, BURN, MINT}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; use sp_runtime::DispatchError; @@ -141,6 +140,7 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// AssetId which is convertible to/from XSTUSD type GetSyntheticBaseAssetId: Get; + type GetXSTPoolPermissionedTechAccountId: Get; type EnsureDEXManager: EnsureDEXManager; type PriceToolsPallet: PriceToolsPallet; type Oracle: DataFeed; @@ -339,12 +339,6 @@ pub mod pallet { OracleQuoteError, } - // TODO: better by replaced with Get<> - /// Technical account used to store collateral tokens. - #[pallet::storage] - #[pallet::getter(fn permissioned_tech_account)] - pub type PermissionedTechAccount = StorageValue<_, T::TechAccountId, ValueQuery>; - /// Synthetic assets and their reference symbols. /// /// It's a programmer responsibility to keep this collection consistent with [`EnabledSymbols`]. @@ -384,8 +378,6 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { - /// Technical account used to perform permissioned actions e.g. mint/burn. - pub tech_account_id: T::TechAccountId, /// Asset that is used to compare collateral assets by value, e.g., DAI. pub reference_asset_id: T::AssetId, /// List of tokens enabled as collaterals initially. @@ -397,7 +389,6 @@ pub mod pallet { impl Default for GenesisConfig { fn default() -> Self { Self { - tech_account_id: Default::default(), reference_asset_id: DAI.into(), initial_synthetic_assets: [( XSTUSD.into(), @@ -412,12 +403,8 @@ pub mod pallet { #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) { - PermissionedTechAccount::::put(&self.tech_account_id); ReferenceAssetId::::put(&self.reference_asset_id); - technical::Pallet::::register_tech_account_id(self.tech_account_id.clone()) - .expect("Failed to register technical account"); - self.initial_synthetic_assets.iter().cloned().for_each( |(asset_id, reference_symbol, fee_ratio)| { Pallet::::enable_synthetic_asset_unchecked( @@ -748,7 +735,7 @@ impl Pallet { to_account_id: &T::AccountId, ) -> Result, DispatchError> { common::with_transaction(|| { - let permissioned_tech_account_id = Self::permissioned_tech_account(); + let permissioned_tech_account_id = T::GetXSTPoolPermissionedTechAccountId::get(); let permissioned_account_id = Technical::::tech_account_id_to_account_id(&permissioned_tech_account_id)?; @@ -805,24 +792,6 @@ impl Pallet { }) } - /// Assign account id that is used to burn and mint. - pub fn set_tech_account_id(account: T::TechAccountId) -> Result<(), DispatchError> { - common::with_transaction(|| { - PermissionedTechAccount::::set(account.clone()); - let account_id = Technical::::tech_account_id_to_account_id(&account)?; - let permissions = [BURN, MINT]; - for permission in &permissions { - permissions::Pallet::::assign_permission( - account_id.clone(), - &account_id, - *permission, - Scope::Unlimited, - )?; - } - Ok(()) - }) - } - /// This function is used to determine particular asset price in terms of a reference asset, which is set for /// XOR quotes (there can be only single token chosen as reference for all comparisons). /// The reference token here is expected to be DAI. @@ -885,7 +854,7 @@ impl Pallet { asset_symbol: AssetSymbol, asset_name: AssetName, ) -> Result<(), DispatchError> { - let permissioned_tech_account_id = Self::permissioned_tech_account(); + let permissioned_tech_account_id = T::GetXSTPoolPermissionedTechAccountId::get(); let permissioned_account_id = Technical::::tech_account_id_to_account_id(&permissioned_tech_account_id)?; Assets::::register_asset_id( diff --git a/pallets/xst/src/mock.rs b/pallets/xst/src/mock.rs index d8ffb8a5b1..89b3523ec3 100644 --- a/pallets/xst/src/mock.rs +++ b/pallets/xst/src/mock.rs @@ -33,8 +33,8 @@ use common::mock::ExistentialDeposits; use common::prelude::{Balance, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapOutcome}; use common::{ self, balance, fixed, fixed_wrapper, hash, Amount, AssetId32, AssetName, AssetSymbol, DEXInfo, - Fixed, PriceVariant, TechPurpose, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, - XSTUSD, + Fixed, FromGenericPair, PriceVariant, TechPurpose, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, + VAL, XOR, XST, XSTUSD, }; use currencies::BasicCurrencyAdapter; use frame_support::traits::{Everything, GenesisBuild}; @@ -95,6 +95,20 @@ parameter_types! { pub GetXykFee: Fixed = fixed!(0.003); pub const MinimumPeriod: u64 = 5; pub const GetBandRateStalePeriod: u64 = 60*5*1000; // 5 minutes + pub GetXSTPoolPermissionedTechAccountId: TechAccountId = { + let tech_account_id = TechAccountId::from_generic_pair( + crate::TECH_ACCOUNT_PREFIX.to_vec(), + crate::TECH_ACCOUNT_PERMISSIONED.to_vec(), + ); + tech_account_id + }; + pub GetXSTPoolPermissionedAccountId: AccountId = { + let tech_account_id = GetXSTPoolPermissionedTechAccountId::get(); + let account_id = + technical::Pallet::::tech_account_id_to_account_id(&tech_account_id) + .expect("Failed to get ordinary account id for technical account id."); + account_id + }; } construct_runtime! { @@ -170,6 +184,7 @@ impl mock_liquidity_source::Config for Runtime impl Config for Runtime { type RuntimeEvent = RuntimeEvent; type GetSyntheticBaseAssetId = GetSyntheticBaseAssetId; + type GetXSTPoolPermissionedTechAccountId = GetXSTPoolPermissionedTechAccountId; type EnsureDEXManager = dex_manager::Pallet; type PriceToolsPallet = MockDEXApi; type Oracle = oracle_proxy::Pallet; @@ -534,6 +549,11 @@ impl Default for ExtBuilder { Scope::Unlimited, vec![permissions::MINT, permissions::BURN], ), + ( + GetXSTPoolPermissionedAccountId::get(), + Scope::Unlimited, + vec![permissions::MINT, permissions::BURN], + ), ], } } @@ -603,6 +623,15 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); + technical::GenesisConfig:: { + register_tech_accounts: vec![( + GetXSTPoolPermissionedAccountId::get(), + GetXSTPoolPermissionedTechAccountId::get(), + )], + } + .assimilate_storage(&mut t) + .unwrap(); + dex_manager::GenesisConfig:: { dex_list: self.dex_list, } diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index bab492748d..6e9cac5190 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -33,30 +33,17 @@ mod tests { use core::str::FromStr; use crate::{Error, Pallet, mock::*}; - use common::{self, AssetName, AssetSymbol, DEXId, FromGenericPair, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, GetMarketInfo, assert_approx_eq, PriceToolsPallet, prelude::{Balance, SwapAmount, QuoteAmount, FixedWrapper, }, SymbolName, Oracle, PriceVariant, PredefinedAssetId, AssetId32}; + use common::{self, AssetName, AssetSymbol, DEXId, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, GetMarketInfo, assert_approx_eq, PriceToolsPallet, prelude::{Balance, SwapAmount, QuoteAmount, FixedWrapper, }, SymbolName, Oracle, PriceVariant, PredefinedAssetId, AssetId32}; use frame_support::{assert_ok, assert_noop}; use sp_arithmetic::traits::{Zero}; - use sp_runtime::DispatchError; type XSTPool = Pallet; - /// Sets up the tech account so that mint permission is enabled - fn xst_pool_init() -> Result { - let xst_tech_account_id = TechAccountId::from_generic_pair( - crate::TECH_ACCOUNT_PREFIX.to_vec(), crate::TECH_ACCOUNT_PERMISSIONED.to_vec() - ); - Technical::register_tech_account_id(xst_tech_account_id.clone())?; - XSTPool::set_tech_account_id(xst_tech_account_id.clone())?; - - Ok(xst_tech_account_id) - } - #[test] fn should_calculate_price() { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); - let _ = xst_pool_init().unwrap(); let alice = &alice(); // base case for buy @@ -99,7 +86,6 @@ mod tests { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); - let _ = xst_pool_init().unwrap(); let alice = alice(); // add some reserves @@ -231,7 +217,6 @@ mod tests { .build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); - let _ = xst_pool_init().unwrap(); // Buy with desired input let amount_a: Balance = balance!(2000); @@ -359,7 +344,6 @@ mod tests { .build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); - let _ = xst_pool_init().unwrap(); let (price_a, _) = XSTPool::quote( &DEXId::Polkaswap.into(), @@ -435,7 +419,6 @@ mod tests { .build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); - let _ = xst_pool_init().unwrap(); XSTPool::exchange( &alice(), @@ -505,7 +488,6 @@ mod tests { .build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); - let _ = xst_pool_init().unwrap(); // Buy with desired input let amount_a: Balance = balance!(200); @@ -594,7 +576,6 @@ mod tests { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); - let _ = xst_pool_init().unwrap(); let alice = alice(); // add some reserves @@ -607,7 +588,6 @@ mod tests { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); - let _ = xst_pool_init().unwrap(); let price_before = >::buy_price(&XST, &XSTUSD).expect("Failed to get buy price before setting floor price."); assert_eq!(price_before, fixed!(181.6197)); @@ -631,7 +611,6 @@ mod tests { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); - let _ = xst_pool_init().unwrap(); let euro = SymbolName::from_str("EURO").expect("Failed to parse `EURO` as a symbol name"); let alice = alice(); @@ -696,7 +675,6 @@ mod tests { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { MockDEXApi::init().unwrap(); - let _ = xst_pool_init().unwrap(); let euro = SymbolName::from_str("EURO").expect("Failed to parse `EURO` as a symbol name"); let alice = alice(); diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index fdb749f783..020df81615 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1773,6 +1773,7 @@ parameter_types! { impl xst::Config for Runtime { type RuntimeEvent = RuntimeEvent; type GetSyntheticBaseAssetId = GetXstPoolConversionAssetId; + type GetXSTPoolPermissionedTechAccountId = GetXSTPoolPermissionedTechAccountId; type EnsureDEXManager = DEXManager; type PriceToolsPallet = PriceTools; type WeightInfo = xst::weights::WeightInfo; From f1d88d4fefee4e2c885a8cca4a4d2e9c77c49cd6 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Wed, 12 Apr 2023 23:17:39 +0300 Subject: [PATCH 54/72] quickfix --- Cargo.lock | 30 ++++++++++++++--------------- node/chain_spec/src/lib.rs | 1 + pallets/xst/benchmarking/Cargo.toml | 28 +++++++++++++++++---------- runtime/Cargo.toml | 1 + 4 files changed, 35 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d098575e80..47ec4d4acb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6967,13 +6967,13 @@ dependencies = [ [[package]] name = "mmr-gadget" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "futures 0.3.27", "log", "parity-scale-codec", "sc-client-api", - "sc-offchain 4.0.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sc-offchain 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "sp-api", "sp-beefy", "sp-blockchain", @@ -10718,7 +10718,7 @@ dependencies = [ [[package]] name = "sc-network-common" version = "0.10.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "async-trait", "bitflags", @@ -10730,7 +10730,7 @@ dependencies = [ "parity-scale-codec", "prost-build", "sc-consensus", - "sc-peerset 4.0.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sc-peerset 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "serde", "smallvec 1.10.0", "sp-blockchain", @@ -10860,7 +10860,7 @@ dependencies = [ [[package]] name = "sc-offchain" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "array-bytes", "bytes", @@ -10876,9 +10876,9 @@ dependencies = [ "parking_lot 0.12.1", "rand 0.8.5", "sc-client-api", - "sc-network-common 0.10.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", - "sc-peerset 4.0.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", - "sc-utils 4.0.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sc-network-common 0.10.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", + "sc-peerset 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "sp-api", "sp-core", "sp-offchain", @@ -10920,12 +10920,12 @@ dependencies = [ [[package]] name = "sc-peerset" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "futures 0.3.27", "libp2p", "log", - "sc-utils 4.0.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sc-utils 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "serde_json", "wasm-timer", ] @@ -11259,7 +11259,7 @@ dependencies = [ [[package]] name = "sc-utils" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "backtrace", "futures 0.3.27", @@ -12128,7 +12128,7 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "proc-macro2", "quote", @@ -12547,7 +12547,7 @@ dependencies = [ [[package]] name = "sp-weights" version = "4.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "parity-scale-codec", "scale-info", @@ -12555,7 +12555,7 @@ dependencies = [ "smallvec 1.10.0", "sp-arithmetic", "sp-core", - "sp-debug-derive 5.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sp-debug-derive 5.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "sp-std", ] @@ -15026,7 +15026,7 @@ dependencies = [ "scale-info", "serde", "sp-core", - "sp-weights 4.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sp-weights 4.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "xcm-procedural", ] diff --git a/node/chain_spec/src/lib.rs b/node/chain_spec/src/lib.rs index 451f84f1a8..0670e0e17e 100644 --- a/node/chain_spec/src/lib.rs +++ b/node/chain_spec/src/lib.rs @@ -2180,6 +2180,7 @@ fn mainnet_genesis( (mbc_pool_rewards_account_id.clone(), 0), (mbc_pool_free_reserves_account_id.clone(), 0), (market_maker_rewards_account_id.clone(), 0), + (xst_pool_permissioned_account_id.clone(), 0), ] .into_iter() .chain( diff --git a/pallets/xst/benchmarking/Cargo.toml b/pallets/xst/benchmarking/Cargo.toml index a413a10f21..97789b6c42 100644 --- a/pallets/xst/benchmarking/Cargo.toml +++ b/pallets/xst/benchmarking/Cargo.toml @@ -13,13 +13,13 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3", default-features = false } currencies = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-currencies", default-features = false } -frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } -frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } -frame-benchmarking = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.38", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.38", default-features = false } +frame-benchmarking = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.38", default-features = false } hex-literal = { version = "0.3.1" } -sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.38", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.38", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.38", default-features = false } common = { path = "../../../common", default-features = false } permissions = { path = "../../permissions", default-features = false } dex-manager = { path = "../../dex-manager", default-features = false } @@ -30,12 +30,12 @@ band = { path = "../../band", default-features = false } oracle-proxy = {path = "../../oracle-proxy", default-features = false} xst = {path = "../../xst", default-features = false } assets = { path = "../../assets", default-features = false } +scale-info = { version = "2", default-features = false } [dev-dependencies] -scale-info = { version = "2", default-features = false } -sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } -pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } -pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.38", default-features = false } +pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.38", default-features = false } +pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.38", default-features = false } tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-tokens", default-features = false } dex-api = { path = "../../dex-api", default-features = false } pool-xyk = { path = "../../pool-xyk", default-features = false } @@ -49,6 +49,7 @@ common = { path = "../../../common", default-features = false, features = [ [features] default = ["std"] std = [ + 'codec/std', "currencies/std", "frame-support/std", "frame-system/std", @@ -65,4 +66,11 @@ std = [ "band/std", "oracle-proxy/std", "xst/std", + "assets/std", + "scale-info/std", ] + +runtime-benchmarks = [ + "frame-system/runtime-benchmarks", + "frame-support/runtime-benchmarks", +] \ No newline at end of file diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index a0a2781202..6aee812170 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -349,6 +349,7 @@ runtime-benchmarks = [ "vested-rewards/runtime-benchmarks", "xor-fee/runtime-benchmarks", "xst-benchmarking", + "xst-benchmarking/runtime-benchmarks", ] reduced-pswap-reward-periods = [] From 13ae71fa561194188eb7006af4a62229374e89ef Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Thu, 13 Apr 2023 12:07:52 +0300 Subject: [PATCH 55/72] fix --- Cargo.lock | 185 +++++++++++++++------------------------------ runtime/Cargo.toml | 1 + 2 files changed, 64 insertions(+), 122 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 47ec4d4acb..3c9e303000 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -743,9 +743,9 @@ dependencies = [ "sc-consensus", "sc-keystore", "sc-network", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", "sc-network-gossip", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils", "sp-api", "sp-application-crypto", "sp-arithmetic", @@ -4462,7 +4462,7 @@ dependencies = [ "rewards", "sc-finality-grandpa", "sc-network", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", "sc-service", "serde", "serde_json", @@ -4537,6 +4537,7 @@ dependencies = [ "multicollateral-bonding-curve-pool", "oracle-proxy", "oracle-proxy-runtime-api", + "order-book", "orml-currencies", "orml-tokens", "orml-traits", @@ -6967,13 +6968,13 @@ dependencies = [ [[package]] name = "mmr-gadget" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38#b12c8d200054c92586ec33f5dfc5d0e109958004" dependencies = [ "futures 0.3.27", "log", "parity-scale-codec", "sc-client-api", - "sc-offchain 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", + "sc-offchain", "sp-api", "sp-beefy", "sp-blockchain", @@ -7658,6 +7659,29 @@ dependencies = [ "sp-std", ] +[[package]] +name = "order-book" +version = "0.1.0" +dependencies = [ + "assets", + "common", + "frame-benchmarking", + "frame-support", + "frame-system", + "framenode-chain-spec", + "framenode-runtime", + "orml-tokens", + "pallet-timestamp", + "parity-scale-codec", + "scale-info", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "technical", + "trading-pair", +] + [[package]] name = "orml-currencies" version = "0.4.1-dev" @@ -10278,7 +10302,7 @@ source = "git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38# dependencies = [ "memmap2", "sc-chain-spec-derive", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", "sc-telemetry", "serde", "serde_json", @@ -10318,11 +10342,11 @@ dependencies = [ "sc-client-db", "sc-keystore", "sc-network", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", "sc-service", "sc-telemetry", "sc-tracing", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils", "serde", "serde_json", "sp-blockchain", @@ -10349,7 +10373,7 @@ dependencies = [ "parking_lot 0.12.1", "sc-executor", "sc-transaction-pool-api", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils", "sp-api", "sp-blockchain", "sp-consensus", @@ -10402,7 +10426,7 @@ dependencies = [ "mockall", "parking_lot 0.12.1", "sc-client-api", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils", "serde", "sp-api", "sp-blockchain", @@ -10606,10 +10630,10 @@ dependencies = [ "sc-client-api", "sc-consensus", "sc-network", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", "sc-network-gossip", "sc-telemetry", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils", "serde_json", "sp-api", "sp-application-crypto", @@ -10634,7 +10658,7 @@ dependencies = [ "futures-timer", "log", "sc-client-api", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", "sp-blockchain", "sp-runtime", ] @@ -10679,9 +10703,9 @@ dependencies = [ "sc-block-builder", "sc-client-api", "sc-consensus", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", - "sc-peerset 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", + "sc-peerset", + "sc-utils", "serde", "serde_json", "smallvec 1.10.0", @@ -10708,39 +10732,13 @@ dependencies = [ "prost", "prost-build", "sc-client-api", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", "sp-blockchain", "sp-runtime", "thiserror", "unsigned-varint", ] -[[package]] -name = "sc-network-common" -version = "0.10.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" -dependencies = [ - "async-trait", - "bitflags", - "bytes", - "futures 0.3.27", - "futures-timer", - "libp2p", - "linked_hash_set", - "parity-scale-codec", - "prost-build", - "sc-consensus", - "sc-peerset 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", - "serde", - "smallvec 1.10.0", - "sp-blockchain", - "sp-consensus", - "sp-finality-grandpa", - "sp-runtime", - "substrate-prometheus-endpoint", - "thiserror", -] - [[package]] name = "sc-network-common" version = "0.10.0-dev" @@ -10756,7 +10754,7 @@ dependencies = [ "parity-scale-codec", "prost-build", "sc-consensus", - "sc-peerset 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-peerset", "serde", "smallvec 1.10.0", "sp-blockchain", @@ -10778,8 +10776,8 @@ dependencies = [ "libp2p", "log", "lru 0.8.1", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", - "sc-peerset 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", + "sc-peerset", "sp-runtime", "substrate-prometheus-endpoint", "tracing", @@ -10798,8 +10796,8 @@ dependencies = [ "prost", "prost-build", "sc-client-api", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", - "sc-peerset 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", + "sc-peerset", "sp-blockchain", "sp-core", "sp-runtime", @@ -10824,9 +10822,9 @@ dependencies = [ "prost-build", "sc-client-api", "sc-consensus", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", - "sc-peerset 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", + "sc-peerset", + "sc-utils", "smallvec 1.10.0", "sp-arithmetic", "sp-blockchain", @@ -10849,44 +10847,14 @@ dependencies = [ "log", "parity-scale-codec", "pin-project", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", - "sc-peerset 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", + "sc-peerset", + "sc-utils", "sp-consensus", "sp-runtime", "substrate-prometheus-endpoint", ] -[[package]] -name = "sc-offchain" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" -dependencies = [ - "array-bytes", - "bytes", - "fnv", - "futures 0.3.27", - "futures-timer", - "hyper", - "hyper-rustls", - "libp2p", - "num_cpus", - "once_cell", - "parity-scale-codec", - "parking_lot 0.12.1", - "rand 0.8.5", - "sc-client-api", - "sc-network-common 0.10.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", - "sc-peerset 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", - "sc-utils 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", - "sp-api", - "sp-core", - "sp-offchain", - "sp-runtime", - "threadpool", - "tracing", -] - [[package]] name = "sc-offchain" version = "4.0.0-dev" @@ -10906,9 +10874,9 @@ dependencies = [ "parking_lot 0.12.1", "rand 0.8.5", "sc-client-api", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", - "sc-peerset 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", + "sc-peerset", + "sc-utils", "sp-api", "sp-core", "sp-offchain", @@ -10917,19 +10885,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "sc-peerset" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" -dependencies = [ - "futures 0.3.27", - "libp2p", - "log", - "sc-utils 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", - "serde_json", - "wasm-timer", -] - [[package]] name = "sc-peerset" version = "4.0.0-dev" @@ -10938,7 +10893,7 @@ dependencies = [ "futures 0.3.27", "libp2p", "log", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils", "serde_json", "wasm-timer", ] @@ -10968,7 +10923,7 @@ dependencies = [ "sc-rpc-api", "sc-tracing", "sc-transaction-pool-api", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils", "serde_json", "sp-api", "sp-blockchain", @@ -11068,11 +11023,11 @@ dependencies = [ "sc-keystore", "sc-network", "sc-network-bitswap", - "sc-network-common 0.10.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-network-common", "sc-network-light", "sc-network-sync", "sc-network-transactions", - "sc-offchain 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-offchain", "sc-rpc", "sc-rpc-server", "sc-rpc-spec-v2", @@ -11082,7 +11037,7 @@ dependencies = [ "sc-tracing", "sc-transaction-pool", "sc-transaction-pool-api", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils", "serde", "serde_json", "sp-api", @@ -11129,7 +11084,7 @@ dependencies = [ "log", "nix 0.26.2", "sc-client-db", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils", "sp-core", "thiserror", "tokio", @@ -11166,7 +11121,7 @@ dependencies = [ "parking_lot 0.12.1", "pin-project", "rand 0.8.5", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils", "serde", "serde_json", "thiserror", @@ -11230,7 +11185,7 @@ dependencies = [ "parking_lot 0.12.1", "sc-client-api", "sc-transaction-pool-api", - "sc-utils 4.0.0-dev (git+https://github.com/sora-xor/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils", "serde", "sp-api", "sp-blockchain", @@ -11256,20 +11211,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "sc-utils" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" -dependencies = [ - "backtrace", - "futures 0.3.27", - "futures-timer", - "lazy_static", - "log", - "parking_lot 0.12.1", - "prometheus", -] - [[package]] name = "sc-utils" version = "4.0.0-dev" diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index a66c2f5598..0c8ef2209f 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -281,6 +281,7 @@ std = [ "vested-rewards-runtime-api/std", "xor-fee/std", "xst/std", + "xst-benchmarking/std", ] private-net = [ From a61fd6875aef14b78b4c69a2afb4761880877b40 Mon Sep 17 00:00:00 2001 From: Mikhail Tagirov Date: Fri, 14 Apr 2023 13:53:22 +0300 Subject: [PATCH 56/72] build fix Signed-off-by: Mikhail Tagirov --- pallets/xst/benchmarking/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/pallets/xst/benchmarking/src/lib.rs b/pallets/xst/benchmarking/src/lib.rs index b3e5592f30..3dcab56c17 100644 --- a/pallets/xst/benchmarking/src/lib.rs +++ b/pallets/xst/benchmarking/src/lib.rs @@ -30,6 +30,7 @@ //! XST pool module benchmarking. +#![cfg(feature = "runtime-benchmarks")] #![cfg_attr(not(feature = "std"), no_std)] use assets::Event as AssetsEvent; From 2fdc8f15da1f122f91054da3c39f1c743f1040ba Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 02:11:03 +0300 Subject: [PATCH 57/72] fixed xst benchmarks --- Cargo.lock | 1 + pallets/xst/benchmarking/Cargo.toml | 4 + pallets/xst/benchmarking/src/lib.rs | 53 ++++++++--- pallets/xst/benchmarking/src/mock.rs | 136 ++------------------------- 4 files changed, 56 insertions(+), 138 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3c9e303000..1d3ba1af22 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15088,6 +15088,7 @@ dependencies = [ "parity-scale-codec", "permissions", "pool-xyk", + "price-tools", "pswap-distribution", "scale-info", "sp-core", diff --git a/pallets/xst/benchmarking/Cargo.toml b/pallets/xst/benchmarking/Cargo.toml index 97789b6c42..84701b06fc 100644 --- a/pallets/xst/benchmarking/Cargo.toml +++ b/pallets/xst/benchmarking/Cargo.toml @@ -31,6 +31,8 @@ oracle-proxy = {path = "../../oracle-proxy", default-features = false} xst = {path = "../../xst", default-features = false } assets = { path = "../../assets", default-features = false } scale-info = { version = "2", default-features = false } +tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", package = "orml-tokens", default-features = false } +price-tools = { path = "../../price-tools", default-features = false } [dev-dependencies] sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.38", default-features = false } @@ -68,6 +70,8 @@ std = [ "xst/std", "assets/std", "scale-info/std", + "tokens/std", + "price-tools/std" ] runtime-benchmarks = [ diff --git a/pallets/xst/benchmarking/src/lib.rs b/pallets/xst/benchmarking/src/lib.rs index 3dcab56c17..df64757411 100644 --- a/pallets/xst/benchmarking/src/lib.rs +++ b/pallets/xst/benchmarking/src/lib.rs @@ -38,7 +38,8 @@ use band::Pallet as Band; use codec::{Decode as _, Encode as _}; use common::prelude::{QuoteAmount, SwapAmount}; use common::{ - balance, fixed, AssetName, AssetSymbol, DEXId, LiquiditySource, Oracle, DAI, XST, XSTUSD, + balance, fixed, AssetName, AssetSymbol, DEXId, LiquiditySource, Oracle, PriceToolsPallet, + PriceVariant, DAI, XST, XSTUSD, }; use frame_benchmarking::benchmarks; use frame_support::pallet_prelude::DispatchResultWithPostInfo; @@ -46,6 +47,7 @@ use frame_support::traits::Get; use frame_system::{EventRecord, RawOrigin}; use hex_literal::hex; use oracle_proxy::Pallet as OracleProxy; +use price_tools::Pallet as PriceTools; use sp_std::prelude::*; use technical::Pallet as Technical; use xst::{Call, Event, Pallet as XSTPool}; @@ -73,6 +75,40 @@ mod utils { .into() } + pub fn permissioned_account_id() -> T::AccountId { + let permissioned_tech_account_id = T::GetXSTPoolPermissionedTechAccountId::get(); + Technical::::tech_account_id_to_account_id(&permissioned_tech_account_id) + .expect("Expected to generate account id from technical") + } + + pub fn set_asset_mock_price(asset_id: &T::AssetId) + where + T: price_tools::Config, + { + let _ = PriceTools::::register_asset(asset_id); + + for _ in 0..31 { + PriceTools::::incoming_spot_price(asset_id, balance!(1), PriceVariant::Buy) + .expect("Failed to relay spot price"); + PriceTools::::incoming_spot_price(asset_id, balance!(1), PriceVariant::Sell) + .expect("Failed to relay spot price"); + } + } + + pub fn setup_exchange_benchmark() { + set_asset_mock_price::(&DAI.into()); + set_asset_mock_price::(&XST.into()); + + let amount: i128 = balance!(1).try_into().unwrap(); + assets::Pallet::::update_balance( + RawOrigin::Root.into(), + alice::().into(), + XST.into(), + amount, + ) + .unwrap(); + } + pub fn alice() -> T::AccountId { let bytes = hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"); T::AccountId::decode(&mut &bytes[..]).unwrap() @@ -130,7 +166,7 @@ mod utils { } } pub struct Pallet(xst::Pallet); -pub trait Config: xst::Config + band::Config + oracle_proxy::Config {} +pub trait Config: xst::Config + band::Config + oracle_proxy::Config + price_tools::Config {} benchmarks! { set_reference_asset { @@ -170,10 +206,7 @@ benchmarks! { } register_synthetic_asset { - let permissioned_tech_account_id = T::GetXSTPoolPermissionedTechAccountId::get(); - let permissioned_account_id = - Technical::::tech_account_id_to_account_id(&permissioned_tech_account_id) - .expect("Expected to generate account id from technical"); + let permissioned_account_id = utils::permissioned_account_id::(); let reference_symbol = utils::symbol::<::Symbol>(); }: _( RawOrigin::Root, @@ -209,6 +242,7 @@ benchmarks! { } quote { + utils::setup_exchange_benchmark::(); let asset_id = utils::enable_synthetic_asset::()?; }: { let _ = XSTPool::::quote( @@ -221,13 +255,8 @@ benchmarks! { } exchange { + utils::setup_exchange_benchmark::(); let asset_id = utils::enable_synthetic_asset::()?; - assets::Pallet::::update_balance( - RawOrigin::Root.into(), - utils::alice::().into(), - XST.into(), - 1000000000000000000, - ).unwrap(); }: { let _ = XSTPool::::exchange( &utils::alice::(), diff --git a/pallets/xst/benchmarking/src/mock.rs b/pallets/xst/benchmarking/src/mock.rs index bf27838326..be5023d4a5 100644 --- a/pallets/xst/benchmarking/src/mock.rs +++ b/pallets/xst/benchmarking/src/mock.rs @@ -30,11 +30,10 @@ use crate::Config; use common::mock::ExistentialDeposits; -use common::prelude::{Balance, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapOutcome}; +use common::prelude::Balance; use common::{ - self, balance, fixed, fixed_wrapper, hash, Amount, AssetId32, AssetName, AssetSymbol, DEXInfo, - Fixed, FromGenericPair, PriceVariant, TechPurpose, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, - VAL, XOR, XST, XSTUSD, + self, balance, fixed, hash, Amount, AssetId32, AssetName, AssetSymbol, DEXInfo, Fixed, + FromGenericPair, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, XSTUSD, }; use currencies::BasicCurrencyAdapter; use frame_support::traits::{Everything, GenesisBuild}; @@ -47,8 +46,7 @@ use sp_core::crypto::AccountId32; use sp_core::H256; use sp_runtime::testing::Header; use sp_runtime::traits::{BlakeTwo256, IdentityLookup, Zero}; -use sp_runtime::{DispatchError, DispatchResult, Perbill, Percent}; -use std::collections::HashMap; +use sp_runtime::{Perbill, Percent}; pub type AccountId = AccountId32; pub type BlockNumber = u64; @@ -136,6 +134,7 @@ construct_runtime! { OracleProxy: oracle_proxy::{Pallet, Call, Storage, Event}, CeresLiquidityLocker: ceres_liquidity_locker::{Pallet, Call, Storage, Event}, DemeterFarmingPlatform: demeter_farming_platform::{Pallet, Call, Storage, Event}, + PriceTools: price_tools::{Pallet, Call, Storage, Event} } } @@ -185,7 +184,7 @@ impl xst::Config for Runtime { type GetSyntheticBaseAssetId = GetSyntheticBaseAssetId; type GetXSTPoolPermissionedTechAccountId = GetXSTPoolPermissionedTechAccountId; type EnsureDEXManager = dex_manager::Pallet; - type PriceToolsPallet = MockDEXApi; + type PriceToolsPallet = price_tools::Pallet; type Oracle = OracleProxy; type Symbol = ::Symbol; type WeightInfo = (); @@ -355,103 +354,10 @@ impl ceres_liquidity_locker::Config for Runtime { type WeightInfo = (); } -pub struct MockDEXApi; - -impl MockDEXApi { - fn get_mock_source_account() -> Result<(TechAccountId, AccountId), DispatchError> { - let tech_account_id = - TechAccountId::Pure(DEXId::Polkaswap.into(), TechPurpose::FeeCollector); - let account_id = Technical::tech_account_id_to_account_id(&tech_account_id)?; - Ok((tech_account_id, account_id)) - } - - pub fn init_without_reserves() -> Result<(), DispatchError> { - let (tech_account_id, _) = Self::get_mock_source_account()?; - Technical::register_tech_account_id(tech_account_id.clone())?; - MockLiquiditySource::set_reserves_account_id(tech_account_id)?; - Ok(()) - } - - pub fn init() -> Result<(), DispatchError> { - Self::init_without_reserves()?; - Ok(()) - } - - fn inner_quote( - _target_id: &DEXId, - input_asset_id: &AssetId, - output_asset_id: &AssetId, - amount: QuoteAmount, - deduce_fee: bool, - ) -> Result, DispatchError> { - match amount { - QuoteAmount::WithDesiredInput { - desired_amount_in, .. - } => { - let amount_out = FixedWrapper::from(desired_amount_in) - * get_mock_prices()[&(*input_asset_id, *output_asset_id)]; - let fee = if deduce_fee { - let fee = amount_out.clone() * balance!(0.007); // XST uses 0.7% fees - fee.into_balance() - } else { - 0 - }; - let amount_out: Balance = amount_out.into_balance(); - let amount_out = amount_out - fee; - Ok(SwapOutcome::new(amount_out, fee)) - } - QuoteAmount::WithDesiredOutput { - desired_amount_out, .. - } => { - let amount_in = FixedWrapper::from(desired_amount_out) - / get_mock_prices()[&(*input_asset_id, *output_asset_id)]; - if deduce_fee { - let with_fee = amount_in.clone() / balance!(0.993); // XST uses 0.7% fees - let fee = with_fee.clone() - amount_in; - let fee = fee.into_balance(); - let with_fee = with_fee.into_balance(); - Ok(SwapOutcome::new(with_fee, fee)) - } else { - Ok(SwapOutcome::new(amount_in.into_balance(), 0)) - } - } - } - } -} - -pub fn get_mock_prices() -> HashMap<(AssetId, AssetId), Balance> { - let direct = vec![ - ((XOR, VAL), balance!(2.0)), - ((XOR, XST), balance!(0.55768)), - // USDT - ((XOR, USDT), balance!(100.0)), - ((VAL, USDT), balance!(50.0)), - // DAI - ((XOR, DAI), balance!(102.0)), - ((XST, DAI), balance!(182.9)), - ((VAL, DAI), balance!(51.0)), - ((USDT, DAI), balance!(1.02)), - // PSWAP - ((XOR, PSWAP), balance!(10)), - ((VAL, PSWAP), balance!(5)), - ((USDT, PSWAP), balance!(0.1)), - ((DAI, PSWAP), balance!(0.098)), - // XSTUSD - ((XOR, XSTUSD), balance!(103.0)), - ((VAL, XSTUSD), balance!(52.0)), - ((USDT, XSTUSD), balance!(1.03)), - ((DAI, XSTUSD), balance!(1.03)), - ((XST, XSTUSD), balance!(183.0)), - ]; - let reverse = direct.clone().into_iter().map(|((a, b), price)| { - ( - (b, a), - (fixed_wrapper!(1) / FixedWrapper::from(price)) - .try_into_balance() - .unwrap(), - ) - }); - direct.into_iter().chain(reverse).collect() +impl price_tools::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type LiquidityProxy = (); + type WeightInfo = (); } pub struct ExtBuilder { @@ -554,28 +460,6 @@ impl Default for ExtBuilder { } } -impl PriceToolsPallet for MockDEXApi { - fn get_average_price( - input_asset_id: &AssetId, - output_asset_id: &AssetId, - _price_variant: PriceVariant, - ) -> Result { - Ok(Self::inner_quote( - &DEXId::Polkaswap.into(), - input_asset_id, - output_asset_id, - QuoteAmount::with_desired_input(balance!(1)), - true, - )? - .amount) - } - - fn register_asset(_: &AssetId) -> DispatchResult { - // do nothing - Ok(()) - } -} - impl ExtBuilder { pub fn build(self) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() From 2e463fd2e2eed8b9db25ca4b4a5748cd0fd9f9c7 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 02:11:14 +0300 Subject: [PATCH 58/72] updated xst weights --- pallets/xst/src/weights.rs | 182 +++++++++++++++++++++++++++++++++---- 1 file changed, 166 insertions(+), 16 deletions(-) diff --git a/pallets/xst/src/weights.rs b/pallets/xst/src/weights.rs index 3bab81f460..06e7fd86fb 100644 --- a/pallets/xst/src/weights.rs +++ b/pallets/xst/src/weights.rs @@ -28,36 +28,186 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +//! Autogenerated weights for `xst` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-04-16, STEPS: `10`, REPEAT: `10`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `MacBook-Pro-qwerty.local`, CPU: `` +//! EXECUTION: Some(Native), WASM-EXECUTION: Compiled, CHAIN: Some("local"), DB CACHE: 1024 + +// Executed Command: +// target/debug/framenode +// benchmark +// pallet +// --chain +// local +// --steps +// 10 +// --repeat +// 10 +// --pallet +// xst +// --extrinsic +// * +// --execution=native +// --output=pallets/xst/src/weights_raw.rs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; use common::weights::constants::EXTRINSIC_FIXED_WEIGHT; -use frame_support::weights::Weight; use sp_std::marker::PhantomData; /// Weight functions for `xst`. pub struct WeightInfo(PhantomData); impl crate::WeightInfo for WeightInfo { + /// Storage: XSTPool ReferenceAssetId (r:0 w:1) + /// Proof Skipped: XSTPool ReferenceAssetId (max_values: Some(1), max_size: None, mode: Measured) fn set_reference_asset() -> Weight { - Weight::zero() - } + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 32_000 nanoseconds. + Weight::from_ref_time(33_000_000) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: XSTPool EnabledSymbols (r:1 w:1) + /// Proof Skipped: XSTPool EnabledSymbols (max_values: None, max_size: None, mode: Measured) + /// Storage: OracleProxy EnabledOracles (r:1 w:0) + /// Proof Skipped: OracleProxy EnabledOracles (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: Band SymbolRates (r:2 w:0) + /// Proof Skipped: Band SymbolRates (max_values: None, max_size: None, mode: Measured) + /// Storage: Assets AssetOwners (r:1 w:0) + /// Proof Skipped: Assets AssetOwners (max_values: None, max_size: None, mode: Measured) + /// Storage: DEXManager DEXInfos (r:1 w:0) + /// Proof Skipped: DEXManager DEXInfos (max_values: None, max_size: None, mode: Measured) + /// Storage: TradingPair EnabledSources (r:1 w:0) + /// Proof Skipped: TradingPair EnabledSources (max_values: None, max_size: None, mode: Measured) + /// Storage: XSTPool EnabledSynthetics (r:0 w:1) + /// Proof Skipped: XSTPool EnabledSynthetics (max_values: None, max_size: None, mode: Measured) fn enable_synthetic_asset() -> Weight { - Weight::zero() - } + // Proof Size summary in bytes: + // Measured: `1558` + // Estimated: `26251` + // Minimum execution time: 456_000 nanoseconds. + Weight::from_parts(467_000_000, 26251) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: XSTPool EnabledSynthetics (r:1 w:1) + /// Proof Skipped: XSTPool EnabledSynthetics (max_values: None, max_size: None, mode: Measured) + /// Storage: XSTPool EnabledSymbols (r:0 w:1) + /// Proof Skipped: XSTPool EnabledSymbols (max_values: None, max_size: None, mode: Measured) fn disable_synthetic_asset() -> Weight { - Weight::zero() - } + // Proof Size summary in bytes: + // Measured: `309` + // Estimated: `3093` + // Minimum execution time: 130_000 nanoseconds. + Weight::from_parts(131_000_000, 3093) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: Assets AssetOwners (r:1 w:1) + /// Proof Skipped: Assets AssetOwners (max_values: None, max_size: None, mode: Measured) + /// Storage: System Account (r:1 w:1) + /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// Storage: Permissions Owners (r:2 w:2) + /// Proof Skipped: Permissions Owners (max_values: None, max_size: None, mode: Measured) + /// Storage: Permissions Permissions (r:3 w:1) + /// Proof Skipped: Permissions Permissions (max_values: None, max_size: None, mode: Measured) + /// Storage: Assets AssetInfos (r:0 w:1) + /// Proof Skipped: Assets AssetInfos (max_values: None, max_size: None, mode: Measured) fn register_synthetic_asset() -> Weight { - Weight::zero() - } + // Proof Size summary in bytes: + // Measured: `1951` + // Estimated: `25257` + // Minimum execution time: 630_000 nanoseconds. + Weight::from_parts(633_000_000, 25257) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: XSTPool EnabledSynthetics (r:1 w:1) + /// Proof Skipped: XSTPool EnabledSynthetics (max_values: None, max_size: None, mode: Measured) fn set_synthetic_asset_fee() -> Weight { - Weight::zero() - } + // Proof Size summary in bytes: + // Measured: `309` + // Estimated: `2784` + // Minimum execution time: 105_000 nanoseconds. + Weight::from_parts(106_000_000, 2784) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: XSTPool SyntheticBaseAssetFloorPrice (r:0 w:1) + /// Proof Skipped: XSTPool SyntheticBaseAssetFloorPrice (max_values: Some(1), max_size: None, mode: Measured) fn set_synthetic_base_asset_floor_price() -> Weight { - Weight::zero() - } + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 31_000 nanoseconds. + Weight::from_ref_time(32_000_000) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: XSTPool EnabledSynthetics (r:1 w:0) + /// Proof Skipped: XSTPool EnabledSynthetics (max_values: None, max_size: None, mode: Measured) + /// Storage: XSTPool ReferenceAssetId (r:1 w:0) + /// Proof Skipped: XSTPool ReferenceAssetId (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: PriceTools PriceInfos (r:2 w:0) + /// Proof Skipped: PriceTools PriceInfos (max_values: None, max_size: None, mode: Measured) + /// Storage: XSTPool SyntheticBaseAssetFloorPrice (r:1 w:0) + /// Proof Skipped: XSTPool SyntheticBaseAssetFloorPrice (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: OracleProxy EnabledOracles (r:1 w:0) + /// Proof Skipped: OracleProxy EnabledOracles (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: OracleProxy SymbolProviders (r:1 w:0) + /// Proof Skipped: OracleProxy SymbolProviders (max_values: None, max_size: None, mode: Measured) + /// Storage: Band SymbolRates (r:1 w:0) + /// Proof Skipped: Band SymbolRates (max_values: None, max_size: None, mode: Measured) + /// Storage: Timestamp Now (r:1 w:0) + /// Proof: Timestamp Now (max_values: Some(1), max_size: Some(8), added: 503, mode: MaxEncodedLen) fn quote() -> Weight { - Weight::zero() - } + // Proof Size summary in bytes: + // Measured: `3144` + // Estimated: `36371` + // Minimum execution time: 421_000 nanoseconds. + Weight::from_parts(427_000_000, 36371) + .saturating_add(T::DbWeight::get().reads(9)) + } + /// Storage: XSTPool EnabledSynthetics (r:1 w:0) + /// Proof Skipped: XSTPool EnabledSynthetics (max_values: None, max_size: None, mode: Measured) + /// Storage: XSTPool ReferenceAssetId (r:1 w:0) + /// Proof Skipped: XSTPool ReferenceAssetId (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: PriceTools PriceInfos (r:2 w:0) + /// Proof Skipped: PriceTools PriceInfos (max_values: None, max_size: None, mode: Measured) + /// Storage: XSTPool SyntheticBaseAssetFloorPrice (r:1 w:0) + /// Proof Skipped: XSTPool SyntheticBaseAssetFloorPrice (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: OracleProxy EnabledOracles (r:1 w:0) + /// Proof Skipped: OracleProxy EnabledOracles (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: OracleProxy SymbolProviders (r:1 w:0) + /// Proof Skipped: OracleProxy SymbolProviders (max_values: None, max_size: None, mode: Measured) + /// Storage: Band SymbolRates (r:1 w:0) + /// Proof Skipped: Band SymbolRates (max_values: None, max_size: None, mode: Measured) + /// Storage: Timestamp Now (r:1 w:0) + /// Proof: Timestamp Now (max_values: Some(1), max_size: Some(8), added: 503, mode: MaxEncodedLen) + /// Storage: Permissions Permissions (r:3 w:0) + /// Proof Skipped: Permissions Permissions (max_values: None, max_size: None, mode: Measured) + /// Storage: Tokens Accounts (r:2 w:2) + /// Proof: Tokens Accounts (max_values: None, max_size: Some(136), added: 2611, mode: MaxEncodedLen) + /// Storage: Tokens TotalIssuance (r:2 w:2) + /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(56), added: 2531, mode: MaxEncodedLen) + /// Storage: Assets AssetInfos (r:1 w:0) + /// Proof Skipped: Assets AssetInfos (max_values: None, max_size: None, mode: Measured) + /// Storage: System Account (r:1 w:1) + /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) fn exchange() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `4865` + // Estimated: `80935` + // Minimum execution time: 967_000 nanoseconds. + Weight::from_parts(992_000_000, 80935) + .saturating_add(T::DbWeight::get().reads(18)) + .saturating_add(T::DbWeight::get().writes(5)) } } From b6812134023c8112df917060dfaf6d7566278c64 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 02:11:23 +0300 Subject: [PATCH 59/72] removed mocks --- pallets/xst/src/mock.rs | 176 +++++++++++---------------------------- pallets/xst/src/tests.rs | 73 ++++------------ 2 files changed, 66 insertions(+), 183 deletions(-) diff --git a/pallets/xst/src/mock.rs b/pallets/xst/src/mock.rs index 89b3523ec3..2218740373 100644 --- a/pallets/xst/src/mock.rs +++ b/pallets/xst/src/mock.rs @@ -30,10 +30,10 @@ use crate::{self as xstpool, Config}; use common::mock::ExistentialDeposits; -use common::prelude::{Balance, FixedWrapper, PriceToolsPallet, QuoteAmount, SwapOutcome}; +use common::prelude::{Balance, FixedWrapper, PriceToolsPallet}; use common::{ - self, balance, fixed, fixed_wrapper, hash, Amount, AssetId32, AssetName, AssetSymbol, DEXInfo, - Fixed, FromGenericPair, PriceVariant, TechPurpose, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, + self, balance, fixed, hash, Amount, AssetId32, AssetName, AssetSymbol, DEXInfo, Fixed, + FromGenericPair, PredefinedAssetId, PriceVariant, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, XSTUSD, }; use currencies::BasicCurrencyAdapter; @@ -47,8 +47,7 @@ use sp_core::crypto::AccountId32; use sp_core::H256; use sp_runtime::testing::Header; use sp_runtime::traits::{BlakeTwo256, IdentityLookup, Zero}; -use sp_runtime::{DispatchError, DispatchResult, Perbill, Percent}; -use std::collections::HashMap; +use sp_runtime::{Perbill, Percent}; pub type AccountId = AccountId32; pub type BlockNumber = u64; @@ -186,7 +185,7 @@ impl Config for Runtime { type GetSyntheticBaseAssetId = GetSyntheticBaseAssetId; type GetXSTPoolPermissionedTechAccountId = GetXSTPoolPermissionedTechAccountId; type EnsureDEXManager = dex_manager::Pallet; - type PriceToolsPallet = MockDEXApi; + type PriceToolsPallet = price_tools::Pallet; type Oracle = oracle_proxy::Pallet; type Symbol = ::Symbol; type WeightInfo = (); @@ -318,7 +317,7 @@ impl pswap_distribution::Config for Runtime { impl price_tools::Config for Runtime { type RuntimeEvent = RuntimeEvent; type LiquidityProxy = (); - type WeightInfo = price_tools::weights::WeightInfo; + type WeightInfo = (); } impl demeter_farming_platform::Config for Runtime { @@ -360,103 +359,33 @@ impl ceres_liquidity_locker::Config for Runtime { type WeightInfo = (); } -pub struct MockDEXApi; - -impl MockDEXApi { - fn get_mock_source_account() -> Result<(TechAccountId, AccountId), DispatchError> { - let tech_account_id = - TechAccountId::Pure(DEXId::Polkaswap.into(), TechPurpose::FeeCollector); - let account_id = Technical::tech_account_id_to_account_id(&tech_account_id)?; - Ok((tech_account_id, account_id)) - } - - pub fn init_without_reserves() -> Result<(), DispatchError> { - let (tech_account_id, _) = Self::get_mock_source_account()?; - Technical::register_tech_account_id(tech_account_id.clone())?; - MockLiquiditySource::set_reserves_account_id(tech_account_id)?; - Ok(()) - } - - pub fn init() -> Result<(), DispatchError> { - Self::init_without_reserves()?; - Ok(()) - } - - fn inner_quote( - _target_id: &DEXId, - input_asset_id: &AssetId, - output_asset_id: &AssetId, - amount: QuoteAmount, - deduce_fee: bool, - ) -> Result, DispatchError> { - match amount { - QuoteAmount::WithDesiredInput { - desired_amount_in, .. - } => { - let amount_out = FixedWrapper::from(desired_amount_in) - * get_mock_prices()[&(*input_asset_id, *output_asset_id)]; - let fee = if deduce_fee { - let fee = amount_out.clone() * balance!(0.007); // XST uses 0.7% fees - fee.into_balance() - } else { - 0 - }; - let amount_out: Balance = amount_out.into_balance(); - let amount_out = amount_out - fee; - Ok(SwapOutcome::new(amount_out, fee)) - } - QuoteAmount::WithDesiredOutput { - desired_amount_out, .. - } => { - let amount_in = FixedWrapper::from(desired_amount_out) - / get_mock_prices()[&(*input_asset_id, *output_asset_id)]; - if deduce_fee { - let with_fee = amount_in.clone() / balance!(0.993); // XST uses 0.7% fees - let fee = with_fee.clone() - amount_in; - let fee = fee.into_balance(); - let with_fee = with_fee.into_balance(); - Ok(SwapOutcome::new(with_fee, fee)) - } else { - Ok(SwapOutcome::new(amount_in.into_balance(), 0)) - } - } - } - } -} - -pub fn get_mock_prices() -> HashMap<(AssetId, AssetId), Balance> { - let direct = vec![ - ((XOR, VAL), balance!(2.0)), - ((XOR, XST), balance!(425.71)), - // USDT - ((XOR, USDT), balance!(100.0)), - ((VAL, USDT), balance!(50.0)), - // DAI - ((XOR, DAI), balance!(102.0)), - ((XST, DAI), balance!(182.9)), - ((VAL, DAI), balance!(51.0)), - ((USDT, DAI), balance!(1.02)), - // PSWAP - ((XOR, PSWAP), balance!(10)), - ((VAL, PSWAP), balance!(5)), - ((USDT, PSWAP), balance!(0.1)), - ((DAI, PSWAP), balance!(0.098)), - // XSTUSD - ((XOR, XSTUSD), balance!(103.0)), - ((VAL, XSTUSD), balance!(52.0)), - ((USDT, XSTUSD), balance!(1.03)), - ((DAI, XSTUSD), balance!(1.03)), - ((XST, XSTUSD), balance!(183.0)), - ]; - let reverse = direct.clone().into_iter().map(|((a, b), price)| { - ( - (b, a), - (fixed_wrapper!(1) / FixedWrapper::from(price)) - .try_into_balance() - .unwrap(), +pub fn set_mock_price( + asset_id: &AssetId, + price: Balance, + buy_ratio: Balance, + sell_ratio: Balance, +) where + T: price_tools::Config + assets::Config>, +{ + let _ = price_tools::Pallet::::register_asset(asset_id); + + let price_buy = (FixedWrapper::from(price) * buy_ratio).into_balance(); + let price_sell = (FixedWrapper::from(price) * sell_ratio).into_balance(); + + for _ in 0..31 { + price_tools::Pallet::::incoming_spot_price( + asset_id.into(), + price_buy, + PriceVariant::Buy, + ) + .expect("Failed to relay spot price"); + price_tools::Pallet::::incoming_spot_price( + asset_id.into(), + price_sell, + PriceVariant::Sell, ) - }); - direct.into_iter().chain(reverse).collect() + .expect("Failed to relay spot price"); + } } pub struct ExtBuilder { @@ -466,6 +395,8 @@ pub struct ExtBuilder { dex_list: Vec<(DEXId, DEXInfo)>, initial_permission_owners: Vec<(u32, Scope, Vec)>, initial_permissions: Vec<(AccountId, Scope, Vec)>, + // Vec<(AssetId, Price, Buy fee ratio, Sell fee ratio)> + initial_prices: Vec<(AssetId, Balance, Balance, Balance)>, } impl Default for ExtBuilder { @@ -555,32 +486,17 @@ impl Default for ExtBuilder { vec![permissions::MINT, permissions::BURN], ), ], + initial_prices: vec![ + (VAL, balance!(2), balance!(0.993), balance!(1.007)), + (XST, balance!(0.64), balance!(0.993), balance!(1.007)), + (XSTUSD, balance!(100), balance!(1), balance!(1)), + (DAI, balance!(100), balance!(1), balance!(1)), + (PSWAP, balance!(10), balance!(0.993), balance!(1.007)), + ], } } } -impl PriceToolsPallet for MockDEXApi { - fn get_average_price( - input_asset_id: &AssetId, - output_asset_id: &AssetId, - _price_variant: PriceVariant, - ) -> Result { - Ok(Self::inner_quote( - &DEXId::Polkaswap.into(), - input_asset_id, - output_asset_id, - QuoteAmount::with_desired_input(balance!(1)), - true, - )? - .amount) - } - - fn register_asset(_: &AssetId) -> DispatchResult { - // do nothing - Ok(()) - } -} - impl ExtBuilder { pub fn new( endowed_accounts: Vec<(AccountId, AssetId, Balance, AssetSymbol, AssetName, u8)>, @@ -684,6 +600,14 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); - t.into() + let mut ext: sp_io::TestExternalities = t.into(); + ext.execute_with(|| { + self.initial_prices + .into_iter() + .for_each(|(asset_id, price, buy_r, sell_r)| { + set_mock_price::(&asset_id, price, buy_r, sell_r) + }) + }); + ext } } diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index 6e9cac5190..bdc067f70b 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -38,45 +38,24 @@ mod tests { use sp_arithmetic::traits::{Zero}; type XSTPool = Pallet; + type PriceTools = price_tools::Pallet; #[test] fn should_calculate_price() { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { - MockDEXApi::init().unwrap(); - let alice = &alice(); - // base case for buy assert_eq!( XSTPool::buy_price(&XST, &XSTUSD, QuoteAmount::with_desired_output(balance!(100000))) .expect("failed to calculate buy assets price"), - fixed!(18161970.0) // (100000.0-100000.0*0.007)*182.9 - ); - assert_eq!( - XSTPool::buy_price(&XST, &XSTUSD, QuoteAmount::with_desired_input(balance!(1151397.348365215316854563))) - .expect("failed to calculate buy assets price"), - fixed!(6339.606046949837032296) // (1151397.348365215316854563+1151397.348365215316854563*0.007)/182.9 + fixed!(15516385.30287984111) // ~ (100000.0-100000.0*0.007)*156.25 ); // base case for sell - assert_ok!( - XSTPool::sell_price(&XST, &XSTUSD, QuoteAmount::with_desired_output(balance!(100000))) - ); - assert_ok!( - XSTPool::sell_price(&XST, &XSTUSD, QuoteAmount::with_desired_input(balance!(100000))) - ); - - // base case for sell with some reserves - XSTPool::exchange(alice, alice, &DEXId::Polkaswap, &XSTUSD, &XST, SwapAmount::with_desired_input(balance!(100000), 0)).expect("Failed to buy XST."); - assert_eq!( - XSTPool::sell_price(&XST, &XSTUSD, QuoteAmount::with_desired_output(balance!(50000))) - .expect("failed to calculate buy assets price"), - fixed!(275.300531825567380631) // (50000+50000*0.007)/182.9 - ); assert_eq!( - XSTPool::sell_price(&XST, &XSTUSD, QuoteAmount::with_desired_input(balance!(15287.903511880099065528))) + XSTPool::sell_price(&XST, &XSTUSD, QuoteAmount::with_desired_output(balance!(100000))) .expect("failed to calculate buy assets price"), - fixed!(2776584.449456610028251475) // (15287.903511880099065528-15287.903511880099065528*0.007)*182.9 + fixed!(635.520000000000000371) // ~ (100000+100000*0.007)/156.25 ); }); } @@ -85,8 +64,6 @@ mod tests { fn calculate_price_for_boundary_values() { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { - MockDEXApi::init().unwrap(); - let alice = alice(); // add some reserves XSTPool::exchange(&alice, &alice, &DEXId::Polkaswap, &XSTUSD, &XST, SwapAmount::with_desired_input(balance!(1), 0)).expect("Failed to buy XST."); @@ -174,8 +151,6 @@ mod tests { ] ).build(); ext.execute_with(|| { - MockDEXApi::init().unwrap(); - let price_a = XSTPool::quote( &DEXId::Polkaswap.into(), &XST, @@ -216,8 +191,6 @@ mod tests { ) .build(); ext.execute_with(|| { - MockDEXApi::init().unwrap(); - // Buy with desired input let amount_a: Balance = balance!(2000); let (quote_outcome_a, _) = XSTPool::quote( @@ -272,7 +245,7 @@ mod tests { assert_eq!(quote_outcome_b.amount, exchange_outcome_b.amount); assert_eq!(xor_balance_a + amount_b.clone(), xor_balance_b); - assert_eq!(xstusd_balance_b, balance!(11432.520587110153623278)); + assert_eq!(xstusd_balance_b, balance!(16759.165436044373306346)); // Sell with desired input let amount_c: Balance = balance!(205); @@ -343,8 +316,6 @@ mod tests { ) .build(); ext.execute_with(|| { - MockDEXApi::init().unwrap(); - let (price_a, _) = XSTPool::quote( &DEXId::Polkaswap.into(), &XSTUSD, @@ -353,15 +324,15 @@ mod tests { true, ) .unwrap(); - assert_approx_eq!(price_a.fee, balance!(0.000008553555383546), balance!(0.000000000000000002)); - assert_eq!(price_a.amount, balance!(0.546934060567218204)); + assert_approx_eq!(price_a.fee, balance!(0.00666), balance!(0.000001)); + assert_eq!(price_a.amount, balance!(0.640187763200000000)); // mock uses conversion with fee let price_a_fee_without_fee = ( FixedWrapper::from(price_a.fee) / balance!(0.993) ).into_balance(); // convert fee back to output_asset_id (XST) for comparison - let base_to_output: FixedWrapper = MockDEXApi::get_average_price(&XOR, &XST, common::PriceVariant::Buy) + let base_to_output: FixedWrapper = PriceTools::get_average_price(&XOR, &XST, common::PriceVariant::Buy) .expect("Failed to convert fee back to synthetic base asset") .into(); // mock returns get_average_price with fee, we want no fee for this comparison @@ -377,7 +348,7 @@ mod tests { .unwrap(); assert_eq!(price_b.fee, balance!(0)); // more error, because more computations/roundings or larger coefficients - assert_approx_eq!(price_b.amount, price_a_fee_in_synthetic_base_asset + price_a.amount, balance!(0.000000000000001000)); + assert_approx_eq!(price_b.amount, price_a_fee_in_synthetic_base_asset + price_a.amount, balance!(0.000001)); let (price_a, _) = XSTPool::quote( &DEXId::Polkaswap.into(), @@ -387,8 +358,8 @@ mod tests { true, ) .unwrap(); - assert_approx_eq!(price_a.fee, balance!(0.001563909801974061), balance!(0.000000000000000002)); - assert_eq!(price_a.amount, balance!(18283.739706444923188361)); + assert_approx_eq!(price_a.fee, balance!(1.04), balance!(0.001)); + assert_eq!(price_a.amount, balance!(15620.417281977813346827)); let (price_b, _) = XSTPool::quote( &DEXId::Polkaswap.into(), @@ -399,7 +370,7 @@ mod tests { ) .unwrap(); assert_eq!(price_b.fee, balance!(0)); - assert_eq!(price_b.amount, balance!(18161.970000000000000000)); + assert_eq!(price_b.amount, balance!(15516.38530287984111)); }); } @@ -418,8 +389,6 @@ mod tests { ) .build(); ext.execute_with(|| { - MockDEXApi::init().unwrap(); - XSTPool::exchange( &alice(), &alice(), @@ -448,7 +417,7 @@ mod tests { ) .unwrap(); assert_eq!(price_a.fee, price_b.fee); - assert_approx_eq!(price_a.fee, balance!(0.000008553555383546), balance!(0.000000000000000002)); + assert_approx_eq!(price_a.fee, balance!(0.00666), balance!(0.000000000000000002)); // Sell let (price_c, _) = XSTPool::quote( @@ -468,7 +437,7 @@ mod tests { ) .unwrap(); assert_eq!(price_c.fee, price_d.fee); - assert_approx_eq!(price_c.fee, balance!(0.000008610904004214), balance!(0.000000000000000002)); + assert_approx_eq!(price_c.fee, balance!(0.0066), balance!(0.00002)); }); } @@ -487,8 +456,6 @@ mod tests { ) .build(); ext.execute_with(|| { - MockDEXApi::init().unwrap(); - // Buy with desired input let amount_a: Balance = balance!(200); let (quote_outcome_a, _) = XSTPool::quote( @@ -575,8 +542,6 @@ mod tests { fn exchange_synthetic_to_any_token_disallowed() { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { - MockDEXApi::init().unwrap(); - let alice = alice(); // add some reserves assert_noop!(XSTPool::exchange(&alice, &alice, &DEXId::Polkaswap, &XSTUSD, &DAI, SwapAmount::with_desired_input(balance!(1), 0)), Error::::CantExchange); @@ -587,10 +552,8 @@ mod tests { fn set_synthetic_base_asset_floor_price_should_work() { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { - MockDEXApi::init().unwrap(); - let price_before = >::buy_price(&XST, &XSTUSD).expect("Failed to get buy price before setting floor price."); - assert_eq!(price_before, fixed!(181.6197)); + assert_eq!(price_before, fixed!(155.1638530287984111)); XSTPool::set_synthetic_base_asset_floor_price(RuntimeOrigin::root(), balance!(200)).expect("Failed to set floor price."); let price_after = >::buy_price(&XST, &XSTUSD).expect("Failed to get buy price after setting floor price."); @@ -610,8 +573,6 @@ mod tests { fn enable_and_disable_synthetic_should_work() { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { - MockDEXApi::init().unwrap(); - let euro = SymbolName::from_str("EURO").expect("Failed to parse `EURO` as a symbol name"); let alice = alice(); @@ -674,8 +635,6 @@ mod tests { fn set_synthetic_fee_should_work() { let mut ext = ExtBuilder::default().build(); ext.execute_with(|| { - MockDEXApi::init().unwrap(); - let euro = SymbolName::from_str("EURO").expect("Failed to parse `EURO` as a symbol name"); let alice = alice(); @@ -731,7 +690,7 @@ mod tests { ) .expect("Failed to quote XST -> XSTEURO"); - let xst_to_xor_price = MockDEXApi::get_average_price( + let xst_to_xor_price = PriceTools::get_average_price( &XST.into(), &XOR.into(), PriceVariant::Buy, From 12f9e269b776cfed416d66e61889416d5f73b839 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 09:03:01 +0300 Subject: [PATCH 60/72] removed unused imports --- pallets/xst/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index bdc067f70b..8fecf04f02 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -33,7 +33,7 @@ mod tests { use core::str::FromStr; use crate::{Error, Pallet, mock::*}; - use common::{self, AssetName, AssetSymbol, DEXId, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, GetMarketInfo, assert_approx_eq, PriceToolsPallet, prelude::{Balance, SwapAmount, QuoteAmount, FixedWrapper, }, SymbolName, Oracle, PriceVariant, PredefinedAssetId, AssetId32}; + use common::{self, AssetName, AssetSymbol, DEXId, LiquiditySource, USDT, VAL, XOR, XST, XSTUSD, DAI, balance, fixed, GetMarketInfo, assert_approx_eq, prelude::{Balance, SwapAmount, QuoteAmount, FixedWrapper, }, SymbolName, Oracle, PriceVariant, PredefinedAssetId, AssetId32}; use frame_support::{assert_ok, assert_noop}; use sp_arithmetic::traits::{Zero}; From 9b1e0c49890ebbe653a6850e482aa5e42895944c Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 10:27:52 +0300 Subject: [PATCH 61/72] resolved conflict --- Cargo.lock | 50 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 72aac20bb5..9dd20f399d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -688,6 +688,7 @@ dependencies = [ "hex-literal", "oracle-proxy", "pallet-balances", + "pallet-timestamp", "parity-scale-codec", "scale-info", "sp-core", @@ -4667,6 +4668,7 @@ dependencies = [ "vested-rewards-runtime-api", "xor-fee", "xst", + "xst-benchmarking", ] [[package]] @@ -7670,6 +7672,7 @@ dependencies = [ "frame-system", "hex-literal", "pallet-balances", + "pallet-timestamp", "parity-scale-codec", "scale-info", "serde", @@ -12110,7 +12113,7 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "proc-macro2", "quote", @@ -12529,7 +12532,7 @@ dependencies = [ [[package]] name = "sp-weights" version = "4.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "parity-scale-codec", "scale-info", @@ -12537,7 +12540,7 @@ dependencies = [ "smallvec 1.10.0", "sp-arithmetic", "sp-core", - "sp-debug-derive 5.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sp-debug-derive 5.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "sp-std", ] @@ -15079,7 +15082,7 @@ dependencies = [ "scale-info", "serde", "sp-core", - "sp-weights 4.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sp-weights 4.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "xcm-procedural", ] @@ -15143,17 +15146,18 @@ name = "xst" version = "1.0.1" dependencies = [ "assets", + "band", "ceres-liquidity-locker", "common", "demeter-farming-platform", "dex-api", "dex-manager", - "frame-benchmarking", "frame-support", "frame-system", "hex-literal", "liquidity-proxy", "mock-liquidity-source", + "oracle-proxy", "orml-currencies", "orml-tokens", "orml-traits", @@ -15175,6 +15179,42 @@ dependencies = [ "trading-pair", ] +[[package]] +name = "xst-benchmarking" +version = "0.1.0" +dependencies = [ + "assets", + "band", + "ceres-liquidity-locker", + "common", + "demeter-farming-platform", + "dex-api", + "dex-manager", + "frame-benchmarking", + "frame-support", + "frame-system", + "hex-literal", + "mock-liquidity-source", + "oracle-proxy", + "orml-currencies", + "orml-tokens", + "pallet-balances", + "pallet-timestamp", + "parity-scale-codec", + "permissions", + "pool-xyk", + "price-tools", + "pswap-distribution", + "scale-info", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "technical", + "trading-pair", + "xst", +] + [[package]] name = "yamux" version = "0.10.2" From d78c875cabfa6a6d93f72882b64d696a5c5d4746 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 12:57:50 +0300 Subject: [PATCH 62/72] reverted benchmarks --- pallets/xst/src/weights.rs | 182 ++++--------------------------------- 1 file changed, 16 insertions(+), 166 deletions(-) diff --git a/pallets/xst/src/weights.rs b/pallets/xst/src/weights.rs index 06e7fd86fb..3bab81f460 100644 --- a/pallets/xst/src/weights.rs +++ b/pallets/xst/src/weights.rs @@ -28,186 +28,36 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -//! Autogenerated weights for `xst` -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-04-16, STEPS: `10`, REPEAT: `10`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `MacBook-Pro-qwerty.local`, CPU: `` -//! EXECUTION: Some(Native), WASM-EXECUTION: Compiled, CHAIN: Some("local"), DB CACHE: 1024 - -// Executed Command: -// target/debug/framenode -// benchmark -// pallet -// --chain -// local -// --steps -// 10 -// --repeat -// 10 -// --pallet -// xst -// --extrinsic -// * -// --execution=native -// --output=pallets/xst/src/weights_raw.rs - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] - -use frame_support::{traits::Get, weights::Weight}; use common::weights::constants::EXTRINSIC_FIXED_WEIGHT; +use frame_support::weights::Weight; use sp_std::marker::PhantomData; /// Weight functions for `xst`. pub struct WeightInfo(PhantomData); impl crate::WeightInfo for WeightInfo { - /// Storage: XSTPool ReferenceAssetId (r:0 w:1) - /// Proof Skipped: XSTPool ReferenceAssetId (max_values: Some(1), max_size: None, mode: Measured) fn set_reference_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 32_000 nanoseconds. - Weight::from_ref_time(33_000_000) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: XSTPool EnabledSymbols (r:1 w:1) - /// Proof Skipped: XSTPool EnabledSymbols (max_values: None, max_size: None, mode: Measured) - /// Storage: OracleProxy EnabledOracles (r:1 w:0) - /// Proof Skipped: OracleProxy EnabledOracles (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Band SymbolRates (r:2 w:0) - /// Proof Skipped: Band SymbolRates (max_values: None, max_size: None, mode: Measured) - /// Storage: Assets AssetOwners (r:1 w:0) - /// Proof Skipped: Assets AssetOwners (max_values: None, max_size: None, mode: Measured) - /// Storage: DEXManager DEXInfos (r:1 w:0) - /// Proof Skipped: DEXManager DEXInfos (max_values: None, max_size: None, mode: Measured) - /// Storage: TradingPair EnabledSources (r:1 w:0) - /// Proof Skipped: TradingPair EnabledSources (max_values: None, max_size: None, mode: Measured) - /// Storage: XSTPool EnabledSynthetics (r:0 w:1) - /// Proof Skipped: XSTPool EnabledSynthetics (max_values: None, max_size: None, mode: Measured) + Weight::zero() + } fn enable_synthetic_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `1558` - // Estimated: `26251` - // Minimum execution time: 456_000 nanoseconds. - Weight::from_parts(467_000_000, 26251) - .saturating_add(T::DbWeight::get().reads(7)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: XSTPool EnabledSynthetics (r:1 w:1) - /// Proof Skipped: XSTPool EnabledSynthetics (max_values: None, max_size: None, mode: Measured) - /// Storage: XSTPool EnabledSymbols (r:0 w:1) - /// Proof Skipped: XSTPool EnabledSymbols (max_values: None, max_size: None, mode: Measured) + Weight::zero() + } fn disable_synthetic_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `309` - // Estimated: `3093` - // Minimum execution time: 130_000 nanoseconds. - Weight::from_parts(131_000_000, 3093) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: Assets AssetOwners (r:1 w:1) - /// Proof Skipped: Assets AssetOwners (max_values: None, max_size: None, mode: Measured) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - /// Storage: Permissions Owners (r:2 w:2) - /// Proof Skipped: Permissions Owners (max_values: None, max_size: None, mode: Measured) - /// Storage: Permissions Permissions (r:3 w:1) - /// Proof Skipped: Permissions Permissions (max_values: None, max_size: None, mode: Measured) - /// Storage: Assets AssetInfos (r:0 w:1) - /// Proof Skipped: Assets AssetInfos (max_values: None, max_size: None, mode: Measured) + Weight::zero() + } fn register_synthetic_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `1951` - // Estimated: `25257` - // Minimum execution time: 630_000 nanoseconds. - Weight::from_parts(633_000_000, 25257) - .saturating_add(T::DbWeight::get().reads(7)) - .saturating_add(T::DbWeight::get().writes(6)) - } - /// Storage: XSTPool EnabledSynthetics (r:1 w:1) - /// Proof Skipped: XSTPool EnabledSynthetics (max_values: None, max_size: None, mode: Measured) + Weight::zero() + } fn set_synthetic_asset_fee() -> Weight { - // Proof Size summary in bytes: - // Measured: `309` - // Estimated: `2784` - // Minimum execution time: 105_000 nanoseconds. - Weight::from_parts(106_000_000, 2784) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: XSTPool SyntheticBaseAssetFloorPrice (r:0 w:1) - /// Proof Skipped: XSTPool SyntheticBaseAssetFloorPrice (max_values: Some(1), max_size: None, mode: Measured) + Weight::zero() + } fn set_synthetic_base_asset_floor_price() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 31_000 nanoseconds. - Weight::from_ref_time(32_000_000) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: XSTPool EnabledSynthetics (r:1 w:0) - /// Proof Skipped: XSTPool EnabledSynthetics (max_values: None, max_size: None, mode: Measured) - /// Storage: XSTPool ReferenceAssetId (r:1 w:0) - /// Proof Skipped: XSTPool ReferenceAssetId (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: PriceTools PriceInfos (r:2 w:0) - /// Proof Skipped: PriceTools PriceInfos (max_values: None, max_size: None, mode: Measured) - /// Storage: XSTPool SyntheticBaseAssetFloorPrice (r:1 w:0) - /// Proof Skipped: XSTPool SyntheticBaseAssetFloorPrice (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: OracleProxy EnabledOracles (r:1 w:0) - /// Proof Skipped: OracleProxy EnabledOracles (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: OracleProxy SymbolProviders (r:1 w:0) - /// Proof Skipped: OracleProxy SymbolProviders (max_values: None, max_size: None, mode: Measured) - /// Storage: Band SymbolRates (r:1 w:0) - /// Proof Skipped: Band SymbolRates (max_values: None, max_size: None, mode: Measured) - /// Storage: Timestamp Now (r:1 w:0) - /// Proof: Timestamp Now (max_values: Some(1), max_size: Some(8), added: 503, mode: MaxEncodedLen) + Weight::zero() + } fn quote() -> Weight { - // Proof Size summary in bytes: - // Measured: `3144` - // Estimated: `36371` - // Minimum execution time: 421_000 nanoseconds. - Weight::from_parts(427_000_000, 36371) - .saturating_add(T::DbWeight::get().reads(9)) - } - /// Storage: XSTPool EnabledSynthetics (r:1 w:0) - /// Proof Skipped: XSTPool EnabledSynthetics (max_values: None, max_size: None, mode: Measured) - /// Storage: XSTPool ReferenceAssetId (r:1 w:0) - /// Proof Skipped: XSTPool ReferenceAssetId (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: PriceTools PriceInfos (r:2 w:0) - /// Proof Skipped: PriceTools PriceInfos (max_values: None, max_size: None, mode: Measured) - /// Storage: XSTPool SyntheticBaseAssetFloorPrice (r:1 w:0) - /// Proof Skipped: XSTPool SyntheticBaseAssetFloorPrice (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: OracleProxy EnabledOracles (r:1 w:0) - /// Proof Skipped: OracleProxy EnabledOracles (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: OracleProxy SymbolProviders (r:1 w:0) - /// Proof Skipped: OracleProxy SymbolProviders (max_values: None, max_size: None, mode: Measured) - /// Storage: Band SymbolRates (r:1 w:0) - /// Proof Skipped: Band SymbolRates (max_values: None, max_size: None, mode: Measured) - /// Storage: Timestamp Now (r:1 w:0) - /// Proof: Timestamp Now (max_values: Some(1), max_size: Some(8), added: 503, mode: MaxEncodedLen) - /// Storage: Permissions Permissions (r:3 w:0) - /// Proof Skipped: Permissions Permissions (max_values: None, max_size: None, mode: Measured) - /// Storage: Tokens Accounts (r:2 w:2) - /// Proof: Tokens Accounts (max_values: None, max_size: Some(136), added: 2611, mode: MaxEncodedLen) - /// Storage: Tokens TotalIssuance (r:2 w:2) - /// Proof: Tokens TotalIssuance (max_values: None, max_size: Some(56), added: 2531, mode: MaxEncodedLen) - /// Storage: Assets AssetInfos (r:1 w:0) - /// Proof Skipped: Assets AssetInfos (max_values: None, max_size: None, mode: Measured) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + Weight::zero() + } fn exchange() -> Weight { - // Proof Size summary in bytes: - // Measured: `4865` - // Estimated: `80935` - // Minimum execution time: 967_000 nanoseconds. - Weight::from_parts(992_000_000, 80935) - .saturating_add(T::DbWeight::get().reads(18)) - .saturating_add(T::DbWeight::get().writes(5)) + Weight::zero() } } From 6d92d5efb6a1bc1fdf935f848909fc89f436581d Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 13:02:11 +0300 Subject: [PATCH 63/72] fixed pallet-timestamp repo --- pallets/band/Cargo.toml | 2 +- pallets/oracle-proxy/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pallets/band/Cargo.toml b/pallets/band/Cargo.toml index aa4882461c..77de68d48e 100644 --- a/pallets/band/Cargo.toml +++ b/pallets/band/Cargo.toml @@ -21,7 +21,7 @@ frame-benchmarking = { git = "https://github.com/sora-xor/substrate.git", branch sp-std = { git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false } common = { path = "../../common", default-features = false } hex-literal = "0.3.1" -pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +pallet-timestamp = { git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false } [dev-dependencies] pallet-balances = { git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false } diff --git a/pallets/oracle-proxy/Cargo.toml b/pallets/oracle-proxy/Cargo.toml index e2f872401c..748afb7049 100644 --- a/pallets/oracle-proxy/Cargo.toml +++ b/pallets/oracle-proxy/Cargo.toml @@ -28,7 +28,7 @@ sp-core = { git = "https://github.com/sora-xor/substrate.git", branch = "polkado hex-literal = "0.3.1" pallet-balances = { git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false } band = { path = "../band", default-features = false } -pallet-timestamp = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.25", default-features = false } +pallet-timestamp = { git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false } [features] default = ['std'] From 1eca45c263d2318d9aa2b4d5b238a3071138b6d5 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 13:02:19 +0300 Subject: [PATCH 64/72] added empty line --- pallets/xst/benchmarking/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/xst/benchmarking/Cargo.toml b/pallets/xst/benchmarking/Cargo.toml index 84701b06fc..67bf33dd4a 100644 --- a/pallets/xst/benchmarking/Cargo.toml +++ b/pallets/xst/benchmarking/Cargo.toml @@ -77,4 +77,4 @@ std = [ runtime-benchmarks = [ "frame-system/runtime-benchmarks", "frame-support/runtime-benchmarks", -] \ No newline at end of file +] From 3a2cc74d86d0aec6dbe0164ccad33142fd8a1574 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 13:02:33 +0300 Subject: [PATCH 65/72] fixed rate stale period constant --- pallets/band/src/mock.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/band/src/mock.rs b/pallets/band/src/mock.rs index 8b4a3c4bca..b8f283d1f3 100644 --- a/pallets/band/src/mock.rs +++ b/pallets/band/src/mock.rs @@ -55,7 +55,7 @@ frame_support::construct_runtime!( ); frame_support::parameter_types! { - pub const GetRateStalePeriod: u64 = 60*5; + pub const GetRateStalePeriod: u64 = 60*5*1000; // 5 minutes pub const MinimumPeriod: u64 = 5; } From a13f5f8d9698981334d53fff9fb8a9321bb2639c Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 13:59:30 +0300 Subject: [PATCH 66/72] fixed xst migrations --- pallets/xst/src/migrations/mod.rs | 39 +++++++++++++++++++++++++++-- pallets/xst/src/migrations/tests.rs | 9 ++++++- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/pallets/xst/src/migrations/mod.rs b/pallets/xst/src/migrations/mod.rs index 44de7313a8..893bfcfd8f 100644 --- a/pallets/xst/src/migrations/mod.rs +++ b/pallets/xst/src/migrations/mod.rs @@ -33,12 +33,21 @@ use common::{fixed, Fixed, XSTUSD}; use frame_support::pallet_prelude::{Get, StorageVersion, ValueQuery}; use frame_support::traits::OnRuntimeUpgrade; use frame_support::{log::info, traits::GetStorageVersion as _, weights::Weight}; +use sp_std::collections::btree_set::BTreeSet; -use crate::{EnabledSymbols, EnabledSynthetics, SyntheticInfo}; +use crate::{EnabledSymbols, EnabledSynthetics as NewEnabledSynthetics, SyntheticInfo}; #[frame_support::storage_alias] type BaseFee = StorageValue, Fixed, ValueQuery>; +#[frame_support::storage_alias] +type PermissionedTechAccount = + StorageValue, ::TechAccountId, ValueQuery>; + +#[frame_support::storage_alias] +type EnabledSynthetics = + StorageValue, BTreeSet<::AssetId>, ValueQuery>; + pub struct CustomSyntheticsUpgrade(core::marker::PhantomData); /// Migration which migrates `XSTUSD` synthetic to the new format. @@ -57,9 +66,17 @@ where BaseFee::::kill(); } + if PermissionedTechAccount::::exists() { + PermissionedTechAccount::::kill(); + } + + if EnabledSynthetics::::exists() { + EnabledSynthetics::::kill(); + } + let xstusd_symbol = T::Symbol::from(common::SymbolName::usd()); - EnabledSynthetics::::insert( + NewEnabledSynthetics::::insert( T::AssetId::from(XSTUSD), SyntheticInfo { reference_symbol: xstusd_symbol.clone(), @@ -71,6 +88,24 @@ where StorageVersion::new(2).put::>(); T::DbWeight::get().reads_writes(0, 2) } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, &'static str> { + frame_support::ensure!( + Pallet::::on_chain_storage_version() == 1, + "must upgrade linearly" + ); + Ok(Vec::new()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(_state: Vec) -> Result<(), &'static str> { + frame_support::ensure!( + Pallet::::on_chain_storage_version() == 2, + "should be upgraded to version 2" + ); + Ok(()) + } } #[cfg(test)] diff --git a/pallets/xst/src/migrations/tests.rs b/pallets/xst/src/migrations/tests.rs index 0aa5fa74e1..f58621cabe 100644 --- a/pallets/xst/src/migrations/tests.rs +++ b/pallets/xst/src/migrations/tests.rs @@ -28,7 +28,12 @@ // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use crate::{migrations::BaseFee, mock::*, pallet::Pallet, EnabledSynthetics}; +use crate::{ + migrations::{BaseFee, EnabledSynthetics as OldEnabledSynthetics, PermissionedTechAccount}, + mock::*, + pallet::Pallet, + EnabledSynthetics, +}; use common::{fixed, Fixed, XSTUSD}; use frame_support::traits::{GetStorageVersion as _, OnRuntimeUpgrade, StorageVersion}; @@ -46,6 +51,8 @@ fn test() { assert_eq!(info.reference_symbol, common::SymbolName::usd().into()); assert_eq!(info.fee_ratio, fixed!(0.00666)); assert!(!BaseFee::::exists()); + assert!(!PermissionedTechAccount::::exists()); + assert!(!OldEnabledSynthetics::::exists()); assert_eq!(Pallet::::on_chain_storage_version(), 2); }); From 6c057067dd67eaecdf4f280e8718e12b9a6831be Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 13:59:57 +0300 Subject: [PATCH 67/72] updated synthetic asset registration process --- pallets/xst/src/lib.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index c99e7bf914..34efb976f2 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -192,6 +192,7 @@ pub mod pallet { Ok(().into()) } + /// Register and enable new synthetic asset with `reference_symbol` price binding #[pallet::call_index(3)] #[pallet::weight(::WeightInfo::register_synthetic_asset())] pub fn register_synthetic_asset( @@ -199,6 +200,7 @@ pub mod pallet { asset_symbol: AssetSymbol, asset_name: AssetName, reference_symbol: T::Symbol, + fee_ratio: Fixed, ) -> DispatchResultWithPostInfo { ensure_root(origin)?; @@ -209,6 +211,12 @@ pub mod pallet { .into(); Self::register_synthetic_asset_unchecked(synthetic_asset_id, asset_symbol, asset_name)?; + Self::enable_synthetic_asset_unchecked( + synthetic_asset_id, + reference_symbol, + fee_ratio, + true, + )?; Ok(().into()) } From 8e135745862fb074a9f3ee70b354543ebff0412b Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 14:00:35 +0300 Subject: [PATCH 68/72] fixed --- pallets/xst/benchmarking/src/lib.rs | 22 +++++++++++----------- pallets/xst/src/tests.rs | 18 ++---------------- 2 files changed, 13 insertions(+), 27 deletions(-) diff --git a/pallets/xst/benchmarking/src/lib.rs b/pallets/xst/benchmarking/src/lib.rs index df64757411..748dc83288 100644 --- a/pallets/xst/benchmarking/src/lib.rs +++ b/pallets/xst/benchmarking/src/lib.rs @@ -125,8 +125,8 @@ mod utils { pub fn assert_last_assets_event(generic_event: ::RuntimeEvent) { let events = frame_system::Pallet::::events(); let system_event: ::RuntimeEvent = generic_event.into(); - // compare to the last event record - let EventRecord { event, .. } = &events[events.len() - 1]; + // compare to the event record precending to trading pair and xst event records + let EventRecord { event, .. } = &events[events.len() - 3]; assert_eq!(event, &system_event); } @@ -143,19 +143,11 @@ mod utils { pub fn enable_synthetic_asset() -> Result { relay_symbol::()?; - let asset_id = symbol_asset_id::(); - XSTPool::::register_synthetic_asset( RawOrigin::Root.into(), AssetSymbol(b"XSTEURO".to_vec()), AssetName(b"Sora Synthetic EURO".to_vec()), symbol::<::Symbol>(), - )?; - - XSTPool::::enable_synthetic_asset( - RawOrigin::Root.into(), - asset_id, - symbol(), fixed!(0), )?; @@ -208,11 +200,13 @@ benchmarks! { register_synthetic_asset { let permissioned_account_id = utils::permissioned_account_id::(); let reference_symbol = utils::symbol::<::Symbol>(); + utils::relay_symbol::()?; }: _( RawOrigin::Root, AssetSymbol(b"XSTEURO".to_vec()), AssetName(b"Sora Synthetic EURO".to_vec()), - reference_symbol + reference_symbol, + fixed!(0) ) verify { utils::assert_last_assets_event::( @@ -221,6 +215,12 @@ benchmarks! { permissioned_account_id ).into() ); + assert!( + XSTPool::::enabled_symbols( + utils::symbol::<::Symbol>() + ) + .is_some() + ); } set_synthetic_asset_fee { diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index 8fecf04f02..9463fcd998 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -589,14 +589,8 @@ mod tests { AssetSymbol("XSTEUR".into()), AssetName("XST Euro".into()), euro.clone(), - ).expect("Failed to register synthetic asset"); - - XSTPool::enable_synthetic_asset( - RuntimeOrigin::root(), - asset_id, - euro.clone(), fixed!(0), - ).expect("Failed to enable synthetic asset"); + ).expect("Failed to register synthetic asset"); let opt_xsteuro = XSTPool::enabled_symbols(&euro); assert!(opt_xsteuro.is_some()); @@ -644,21 +638,13 @@ mod tests { Band::relay(RuntimeOrigin::signed(alice.clone()), vec![(euro.clone(), 1)], 0, 0) .expect("Failed to relay"); - let asset_id = AssetId32::::from_synthetic_reference_symbol(&euro); - XSTPool::register_synthetic_asset( RuntimeOrigin::root(), AssetSymbol("XSTEUR".into()), AssetName("XST Euro".into()), euro.clone(), - ).expect("Failed to register synthetic asset"); - - XSTPool::enable_synthetic_asset( - RuntimeOrigin::root(), - asset_id, - euro.clone(), fixed!(0), - ).expect("Failed to enable synthetic asset"); + ).expect("Failed to register synthetic asset"); let xsteuro = XSTPool::enabled_symbols(&euro).expect("Expected synthetic asset"); let quote_amount = QuoteAmount::with_desired_input(balance!(100)); From 7db3b6b86fe15da53d7b8fc845efe3f7481eecd7 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 14:41:38 +0300 Subject: [PATCH 69/72] removed unused import --- pallets/xst/benchmarking/src/mock.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pallets/xst/benchmarking/src/mock.rs b/pallets/xst/benchmarking/src/mock.rs index a12d3de005..be5023d4a5 100644 --- a/pallets/xst/benchmarking/src/mock.rs +++ b/pallets/xst/benchmarking/src/mock.rs @@ -32,9 +32,8 @@ use crate::Config; use common::mock::ExistentialDeposits; use common::prelude::Balance; use common::{ - self, balance, fixed, hash, Amount, AssetId32, AssetInfoProvider, AssetName, AssetSymbol, - DEXInfo, Fixed, FromGenericPair, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, - XSTUSD, + self, balance, fixed, hash, Amount, AssetId32, AssetName, AssetSymbol, DEXInfo, Fixed, + FromGenericPair, DAI, DEFAULT_BALANCE_PRECISION, PSWAP, USDT, VAL, XOR, XST, XSTUSD, }; use currencies::BasicCurrencyAdapter; use frame_support::traits::{Everything, GenesisBuild}; From c4dc78f2e3d8bbf5a55595f00b7e6df58fb0965b Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 20:49:25 +0300 Subject: [PATCH 70/72] fixed band dependencies --- Cargo.lock | 22 +++++++++++----------- pallets/band/Cargo.toml | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 12603656d3..adaf71feeb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7018,13 +7018,13 @@ dependencies = [ [[package]] name = "mmr-gadget" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "futures 0.3.28", "log", "parity-scale-codec", "sc-client-api", - "sc-offchain 4.0.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sc-offchain 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "sp-api", "sp-beefy", "sp-blockchain", @@ -10787,7 +10787,7 @@ dependencies = [ [[package]] name = "sc-network-common" version = "0.10.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "async-trait", "bitflags", @@ -10799,7 +10799,7 @@ dependencies = [ "parity-scale-codec", "prost-build", "sc-consensus", - "sc-peerset 4.0.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sc-peerset 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "serde", "smallvec 1.10.0", "sp-blockchain", @@ -10929,7 +10929,7 @@ dependencies = [ [[package]] name = "sc-offchain" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "array-bytes", "bytes", @@ -10945,9 +10945,9 @@ dependencies = [ "parking_lot 0.12.1", "rand 0.8.5", "sc-client-api", - "sc-network-common 0.10.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", - "sc-peerset 4.0.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", - "sc-utils 4.0.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sc-network-common 0.10.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", + "sc-peerset 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", + "sc-utils 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "sp-api", "sp-core", "sp-offchain", @@ -10989,12 +10989,12 @@ dependencies = [ [[package]] name = "sc-peerset" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "futures 0.3.28", "libp2p", "log", - "sc-utils 4.0.0-dev (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38)", + "sc-utils 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38)", "serde_json", "wasm-timer", ] @@ -11328,7 +11328,7 @@ dependencies = [ [[package]] name = "sc-utils" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.38#18bb7c7c841b101c19a8d1881b893ae8e37de460" dependencies = [ "backtrace", "futures 0.3.28", diff --git a/pallets/band/Cargo.toml b/pallets/band/Cargo.toml index 77de68d48e..860b58fa3d 100644 --- a/pallets/band/Cargo.toml +++ b/pallets/band/Cargo.toml @@ -21,10 +21,10 @@ frame-benchmarking = { git = "https://github.com/sora-xor/substrate.git", branch sp-std = { git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false } common = { path = "../../common", default-features = false } hex-literal = "0.3.1" -pallet-timestamp = { git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false } [dev-dependencies] pallet-balances = { git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false } +pallet-timestamp = { git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false } sp-core = { git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false } sp-io = { git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false } sp-runtime = { version = "7.0.0", git = "https://github.com/sora-xor/substrate.git", branch = "polkadot-v0.9.38", default-features = false} From a313b7e51eff5061f382bac3325500e68c3418c0 Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 20:49:44 +0300 Subject: [PATCH 71/72] check optimization --- pallets/trading-pair/src/lib.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/pallets/trading-pair/src/lib.rs b/pallets/trading-pair/src/lib.rs index 0eb6c1d209..20fd4043b3 100644 --- a/pallets/trading-pair/src/lib.rs +++ b/pallets/trading-pair/src/lib.rs @@ -83,6 +83,11 @@ impl Pallet { base_asset_id: T::AssetId, target_asset_id: T::AssetId, ) -> Result<(), DispatchError> { + ensure!( + base_asset_id != target_asset_id, + Error::::IdenticalAssetIds + ); + let dex_info = DEXManager::::get_dex_info(&dex_id)?; ensure!( base_asset_id == dex_info.base_asset_id @@ -91,10 +96,7 @@ impl Pallet { ); Assets::::ensure_asset_exists(&base_asset_id)?; Assets::::ensure_asset_exists(&target_asset_id)?; - ensure!( - base_asset_id != target_asset_id, - Error::::IdenticalAssetIds - ); + let trading_pair = TradingPair:: { base_asset_id, target_asset_id, From e58ef02cf0e281dd07ce5b9ca1596585afdf2a2c Mon Sep 17 00:00:00 2001 From: Nikita Smirnov Date: Mon, 17 Apr 2023 20:50:02 +0300 Subject: [PATCH 72/72] added fee ratio check --- pallets/xst/src/lib.rs | 20 +++++++++++++------- pallets/xst/src/tests.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/pallets/xst/src/lib.rs b/pallets/xst/src/lib.rs index bf64a0de03..26e910140d 100644 --- a/pallets/xst/src/lib.rs +++ b/pallets/xst/src/lib.rs @@ -50,9 +50,9 @@ use common::prelude::{ SwapOutcome, DEFAULT_BALANCE_PRECISION, }; use common::{ - balance, fixed_wrapper, AssetId32, AssetInfoProvider, AssetName, AssetSymbol, DEXId, DataFeed, - GetMarketInfo, LiquiditySource, LiquiditySourceFilter, LiquiditySourceType, PriceVariant, Rate, - RewardReason, DAI, XSTUSD, + balance, fixed, fixed_wrapper, AssetId32, AssetInfoProvider, AssetName, AssetSymbol, DEXId, + DataFeed, GetMarketInfo, LiquiditySource, LiquiditySourceFilter, LiquiditySourceType, + PriceVariant, Rate, RewardReason, DAI, XSTUSD, }; use frame_support::traits::Get; use frame_support::weights::Weight; @@ -193,7 +193,7 @@ pub mod pallet { } /// Register and enable new synthetic asset with `reference_symbol` price binding - #[pallet::call_index(3)] + #[pallet::call_index(2)] #[pallet::weight(::WeightInfo::register_synthetic_asset())] pub fn register_synthetic_asset( origin: OriginFor, @@ -229,7 +229,7 @@ pub mod pallet { /// /// - `origin`: the sudo account on whose behalf the transaction is being executed, /// - `synthetic_asset`: synthetic asset id to disable. - #[pallet::call_index(4)] + #[pallet::call_index(3)] #[pallet::weight(::WeightInfo::disable_synthetic_asset())] pub fn disable_synthetic_asset( origin: OriginFor, @@ -256,7 +256,7 @@ pub mod pallet { /// - `origin`: the sudo account on whose behalf the transaction is being executed, /// - `synthetic_asset`: synthetic asset id to set fee for, /// - `fee_ratio`: fee ratio with precision = 18, so 1000000000000000000 = 1 = 100% fee. - #[pallet::call_index(5)] + #[pallet::call_index(4)] #[pallet::weight(::WeightInfo::set_synthetic_asset_fee())] pub fn set_synthetic_asset_fee( origin: OriginFor, @@ -284,7 +284,7 @@ pub mod pallet { /// /// - `origin`: root account /// - `floor_price`: floor price for the synthetic base asset - #[pallet::call_index(6)] + #[pallet::call_index(5)] #[pallet::weight(::WeightInfo::set_synthetic_base_asset_floor_price())] pub fn set_synthetic_base_asset_floor_price( origin: OriginFor, @@ -345,6 +345,8 @@ pub mod pallet { SyntheticIsNotEnabled, /// Error quoting price from oracle. OracleQuoteError, + /// Invalid fee ratio value. + InvalidFeeRatio, } /// Synthetic assets and their reference symbols. @@ -449,6 +451,10 @@ impl Pallet { if EnabledSymbols::::contains_key(&reference_symbol) { return Err(Error::::SymbolAlreadyReferencedToSynthetic.into()); } + ensure!( + fee_ratio >= fixed!(0) && fee_ratio < fixed!(1), + Error::::InvalidFeeRatio + ); Self::ensure_symbol_exists(&reference_symbol)?; Assets::::ensure_asset_exists(&synthetic_asset_id)?; diff --git a/pallets/xst/src/tests.rs b/pallets/xst/src/tests.rs index 4e92da0b2d..30b6860e50 100644 --- a/pallets/xst/src/tests.rs +++ b/pallets/xst/src/tests.rs @@ -687,4 +687,41 @@ mod tests { assert_eq!(swap_outcome_after.fee, expected_fee_amount.into_balance()); }); } + + #[test] + fn should_disallow_invalid_fee_ratio() { + let mut ext = ExtBuilder::default().build(); + ext.execute_with(|| { + let euro = SymbolName::from_str("EURO").expect("Failed to parse `EURO` as a symbol name"); + let alice = alice(); + + OracleProxy::enable_oracle(RuntimeOrigin::root(), Oracle::BandChainFeed).expect("Failed to enable `Band` oracle"); + Band::add_relayers(RuntimeOrigin::root(), vec![alice.clone()]) + .expect("Failed to add relayers"); + Band::relay(RuntimeOrigin::signed(alice.clone()), vec![(euro.clone(), 1)], 0, 0) + .expect("Failed to relay"); + + assert_eq!( + XSTPool::register_synthetic_asset( + RuntimeOrigin::root(), + AssetSymbol("XSTEUR".into()), + AssetName("XST Euro".into()), + euro.clone(), + fixed!(-0.1), + ), + Err(Error::::InvalidFeeRatio.into()) + ); + + assert_eq!( + XSTPool::register_synthetic_asset( + RuntimeOrigin::root(), + AssetSymbol("XSTEUR".into()), + AssetName("XST Euro".into()), + euro.clone(), + fixed!(1), + ), + Err(Error::::InvalidFeeRatio.into()) + ) + }); + } }