From f6e9a963ace83266876f7542b460ba660cf58ecf Mon Sep 17 00:00:00 2001 From: Gautham Date: Tue, 19 Mar 2024 09:38:04 +0700 Subject: [PATCH 01/24] Change sub to use saturating sub --- pallets/ocex/src/lib.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index 23afc3383..31765e841 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -2118,11 +2118,12 @@ pub mod pallet { let _ = T::NativeCurrency::unreserve(&bidder, total_bidder_reserve_balance); let amount_to_be_burnt = Percent::from_percent(fee_config.burn_ration) * total_bidder_reserve_balance; - let trasnferable_amount = total_bidder_reserve_balance - amount_to_be_burnt; + let transferable_amount = + total_bidder_reserve_balance.saturating_sub(amount_to_be_burnt); T::NativeCurrency::transfer( &bidder, &fee_config.recipient_address, - trasnferable_amount, + transferable_amount, ExistenceRequirement::KeepAlive, )?; @@ -2139,7 +2140,7 @@ pub mod pallet { Self::deposit_event(Event::::AuctionClosed { bidder, burned: Compact::from(amount_to_be_burnt), - paid_to_operator: Compact::from(trasnferable_amount), + paid_to_operator: Compact::from(transferable_amount), }) } Ok(()) From 163e2b411edac5010b3c7019728e8d0f9f886fb9 Mon Sep 17 00:00:00 2001 From: Gautham Date: Tue, 19 Mar 2024 09:40:35 +0700 Subject: [PATCH 02/24] Change sub to use saturating sub --- pallets/ocex/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index 31765e841..fb024c8d1 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -1530,7 +1530,7 @@ pub mod pallet { ); let fee_to_be_burnt = Percent::from_percent(distribution.burn_ration) * fees; - let fee_to_be_distributed = fees - fee_to_be_burnt; + let fee_to_be_distributed = fees.saturating_sub(fee_to_be_burnt); // Burn the fee let imbalance = T::NativeCurrency::burn( fee_to_be_burnt.saturated_into(), From c68818efd94cc9f69de92ef422903ca7ca06b5cc Mon Sep 17 00:00:00 2001 From: Gautham Date: Tue, 19 Mar 2024 09:40:55 +0700 Subject: [PATCH 03/24] cargo fmt --- pallets/ocex/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index fb024c8d1..468861cb4 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -1530,7 +1530,8 @@ pub mod pallet { ); let fee_to_be_burnt = Percent::from_percent(distribution.burn_ration) * fees; - let fee_to_be_distributed = fees.saturating_sub(fee_to_be_burnt); + let fee_to_be_distributed = + fees.saturating_sub(fee_to_be_burnt); // Burn the fee let imbalance = T::NativeCurrency::burn( fee_to_be_burnt.saturated_into(), From bbc863cf3b141c77b67b591bf2626fc1bcc52271 Mon Sep 17 00:00:00 2001 From: Gautham Date: Tue, 19 Mar 2024 14:33:45 +0700 Subject: [PATCH 04/24] Remove unsafe check for Node RPCs --- nodes/mainnet/src/chain_spec.rs | 2 +- nodes/mainnet/src/node_rpc.rs | 1 - pallets/ocex/rpc/src/lib.rs | 7 +------ 3 files changed, 2 insertions(+), 8 deletions(-) diff --git a/nodes/mainnet/src/chain_spec.rs b/nodes/mainnet/src/chain_spec.rs index 5c3e553ba..576c90297 100644 --- a/nodes/mainnet/src/chain_spec.rs +++ b/nodes/mainnet/src/chain_spec.rs @@ -335,7 +335,7 @@ fn mainnet_genesis_constuctor() -> RuntimeGenesisConfig { } pub fn mainnet_testnet_config() -> ChainSpec { - let bootnodes = vec![]; + let bootnodes = vec![String::from("/dns/mainnet-eu-1.polkadex.trade/tcp/30333/ws/p2p/12D3KooWBkf4SQe38JS3RQx9RsDuYfA1PpVMMjjE4d23wPfGGVa1").try_into().unwrap()]; const POLKADEX_PROTOCOL_ID: &str = "pdex"; ChainSpec::from_genesis( "Polkadex Main Network", diff --git a/nodes/mainnet/src/node_rpc.rs b/nodes/mainnet/src/node_rpc.rs index a42c52a94..e082ec1ee 100644 --- a/nodes/mainnet/src/node_rpc.rs +++ b/nodes/mainnet/src/node_rpc.rs @@ -189,7 +189,6 @@ where backend .offchain_storage() .ok_or("Backend doesn't provide an offchain storage")?, - deny_unsafe, ) .into_rpc(), )?; diff --git a/pallets/ocex/rpc/src/lib.rs b/pallets/ocex/rpc/src/lib.rs index c786a7de9..21fd63077 100644 --- a/pallets/ocex/rpc/src/lib.rs +++ b/pallets/ocex/rpc/src/lib.rs @@ -35,7 +35,6 @@ pub use pallet_ocex_runtime_api::PolkadexOcexRuntimeApi; use parity_scale_codec::{Codec, Decode}; use polkadex_primitives::AssetId; use rust_decimal::Decimal; -use sc_rpc_api::DenyUnsafe; use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_blockchain::HeaderBackend; use sp_core::offchain::{storage::OffchainDb, OffchainDbExt, OffchainStorage}; @@ -141,7 +140,6 @@ pub struct PolkadexOcexRpc { /// Offchain storage offchain_db: OffchainDb, - deny_unsafe: DenyUnsafe, /// A marker for the `Block` type parameter, used to ensure the struct /// is covariant with respect to the block type. @@ -149,11 +147,10 @@ pub struct PolkadexOcexRpc { } impl PolkadexOcexRpc { - pub fn new(client: Arc, storage: T, deny_unsafe: DenyUnsafe) -> Self { + pub fn new(client: Arc, storage: T) -> Self { Self { client, offchain_db: OffchainDb::new(storage), - deny_unsafe, _marker: Default::default(), } } @@ -218,7 +215,6 @@ where &self, at: Option<::Hash>, ) -> RpcResult { - self.deny_unsafe.check_if_safe()?; let mut api = self.client.runtime_api(); let at = match at { Some(at) => at, @@ -250,7 +246,6 @@ where &self, at: Option<::Hash>, ) -> RpcResult { - //self.deny_unsafe.check_if_safe()?; //As it is used by the aggregator, we need to allow it let mut api = self.client.runtime_api(); let at = match at { Some(at) => at, From 9937b4cdfd6085b9d1751e90e954c7d21042dfdd Mon Sep 17 00:00:00 2001 From: zktony Date: Tue, 19 Mar 2024 19:47:34 +0700 Subject: [PATCH 05/24] Added changes for frontend --- pallets/thea-executor/src/lib.rs | 19 +++++++++++++++---- pallets/thea-message-handler/src/lib.rs | 5 +++++ pallets/thea/src/lib.rs | 5 +++++ primitives/thea/src/lib.rs | 1 + 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index 51d92c6ef..2b6a5d6ca 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -197,6 +197,8 @@ pub mod pallet { WithdrawalFeeSet(u8, u128), /// Native Token Burn event NativeTokenBurned(T::AccountId, u128), + /// Withdrawal Sent (Network, Withdrawal Id,Batch Outgoing Nonce, Withdrawal Index) + WithdrawalSent(Network, Vec, u64, u8), } // Errors inform users that something went wrong. @@ -243,13 +245,22 @@ pub mod pallet { >::iter_prefix(block_no.saturating_sub(1u8.into())); let mut withdrawal_len = 0; let mut network_len = 0; - for (network_id, withdrawal) in pending_withdrawals { - withdrawal_len += withdrawal.len(); + for (network_id, withdrawals) in pending_withdrawals { + withdrawal_len += withdrawals.len(); + let batch_nonce = T::Executor::get_outgoing_nonce(network_id); + for (index, withdrawal) in withdrawals.iter().enumerate() { + Self::deposit_event(Event::::WithdrawalSent( + network_id, + withdrawal.id.clone(), + batch_nonce, + index as u8, + )); + } // This is fine as this trait is not supposed to fail - if T::Executor::execute_withdrawals(network_id, withdrawal.clone().encode()) + if T::Executor::execute_withdrawals(network_id, withdrawals.clone().encode()) .is_err() { - Self::deposit_event(Event::::WithdrawalFailed(network_id, withdrawal)) + Self::deposit_event(Event::::WithdrawalFailed(network_id, withdrawals)) } network_len += 1; } diff --git a/pallets/thea-message-handler/src/lib.rs b/pallets/thea-message-handler/src/lib.rs index 777690e01..424a0cc07 100644 --- a/pallets/thea-message-handler/src/lib.rs +++ b/pallets/thea-message-handler/src/lib.rs @@ -338,4 +338,9 @@ impl thea_primitives::TheaOutgoingExecutor for Pallet { Ok(()) } + + fn get_outgoing_nonce(network: Network) -> u64 { + let nonce = >::get(); + nonce.saturating_add(1) + } } diff --git a/pallets/thea/src/lib.rs b/pallets/thea/src/lib.rs index 3f9c486dc..804b2aa40 100644 --- a/pallets/thea/src/lib.rs +++ b/pallets/thea/src/lib.rs @@ -880,4 +880,9 @@ impl thea_primitives::TheaOutgoingExecutor for Pallet { >::insert(network, payload.nonce, payload); Ok(()) } + + fn get_outgoing_nonce(network: Network) -> u64 { + let nonce = >::get(network); + nonce.saturating_add(1) + } } diff --git a/primitives/thea/src/lib.rs b/primitives/thea/src/lib.rs index 1b883ad73..c2c5e3e3c 100644 --- a/primitives/thea/src/lib.rs +++ b/primitives/thea/src/lib.rs @@ -99,6 +99,7 @@ pub trait TheaIncomingExecutor { /// Thea outgoing message executor abstraction which should be implemented by the "Thea" pallet. pub trait TheaOutgoingExecutor { fn execute_withdrawals(network: Network, withdrawals: Vec) -> DispatchResult; + fn get_outgoing_nonce(network: Network) -> u64; } impl TheaIncomingExecutor for () { From 4770385e2261e45d73e9666b3e6a62e4383fed2d Mon Sep 17 00:00:00 2001 From: Gautham Date: Wed, 20 Mar 2024 07:12:51 +0700 Subject: [PATCH 06/24] Increment spec version --- runtimes/mainnet/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 510c05536..a5f0e7329 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -122,7 +122,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 334, + spec_version: 335, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 85a7914f43f85324bb25e87eef5d018c4d2fb0a9 Mon Sep 17 00:00:00 2001 From: Gautham Date: Wed, 20 Mar 2024 07:21:07 +0700 Subject: [PATCH 07/24] fix clippy --- pallets/thea-message-handler/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/thea-message-handler/src/lib.rs b/pallets/thea-message-handler/src/lib.rs index 424a0cc07..71d13d864 100644 --- a/pallets/thea-message-handler/src/lib.rs +++ b/pallets/thea-message-handler/src/lib.rs @@ -339,7 +339,7 @@ impl thea_primitives::TheaOutgoingExecutor for Pallet { Ok(()) } - fn get_outgoing_nonce(network: Network) -> u64 { + fn get_outgoing_nonce(_network: Network) -> u64 { let nonce = >::get(); nonce.saturating_add(1) } From f70e5731e7a6cf1a06579cf27d9aace5864d235a Mon Sep 17 00:00:00 2001 From: Gautham Date: Wed, 20 Mar 2024 07:21:18 +0700 Subject: [PATCH 08/24] cargo fmt --- pallets/ocex/rpc/src/lib.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/pallets/ocex/rpc/src/lib.rs b/pallets/ocex/rpc/src/lib.rs index 21fd63077..78353af64 100644 --- a/pallets/ocex/rpc/src/lib.rs +++ b/pallets/ocex/rpc/src/lib.rs @@ -148,11 +148,7 @@ pub struct PolkadexOcexRpc { impl PolkadexOcexRpc { pub fn new(client: Arc, storage: T) -> Self { - Self { - client, - offchain_db: OffchainDb::new(storage), - _marker: Default::default(), - } + Self { client, offchain_db: OffchainDb::new(storage), _marker: Default::default() } } } From 6f507237de05b865edcdb4f769a781c961a4442a Mon Sep 17 00:00:00 2001 From: Gautham Date: Wed, 20 Mar 2024 11:47:13 +0700 Subject: [PATCH 09/24] added lmpconfig to checkpoint --- pallets/ocex/src/lib.rs | 64 ++++++++++++++++++++++-- pallets/ocex/src/lmp.rs | 73 ++++++++++++++++++++++++---- primitives/orderbook/src/lib.rs | 7 ++- primitives/orderbook/src/lmp.rs | 2 +- primitives/orderbook/src/recovery.rs | 4 ++ 5 files changed, 135 insertions(+), 15 deletions(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index 468861cb4..ea1ee6bfb 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -1889,31 +1889,89 @@ pub mod pallet { /// Fetch checkpoint for recovery pub fn fetch_checkpoint() -> Result { log::debug!(target:"ocex", "fetch_checkpoint called"); - let account_id = + let account_ids = >::iter().fold(vec![], |mut ids_accum, (acc, acc_info)| { ids_accum.push((acc.clone(), acc_info.proxies)); ids_accum }); let mut balances: BTreeMap = BTreeMap::new(); + let mut q_scores_uptime_map = BTreeMap::new(); + let mut maker_volume_map = BTreeMap::new(); + let mut taker_volume_map = BTreeMap::new(); + let mut fees_paid_map = BTreeMap::new(); + let mut total_maker_volume_map = BTreeMap::new(); // all offchain balances for main accounts - for account in account_id { - let main = Self::transform_account(account.0)?; + for (account, _) in &account_ids { + let main = Self::transform_account(account.clone())?; let b = Self::get_offchain_balance(&main)?; for (asset, balance) in b.into_iter() { balances.insert(AccountAsset { main: main.clone(), asset }, balance); } } + let state_info = Self::get_state_info().map_err(|_err| DispatchError::Corruption)?; let last_processed_block_number = state_info.last_block; let snapshot_id = state_info.snapshot_id; let state_change_id = state_info.stid; + + let mut root = crate::storage::load_trie_root(); + let mut storage = crate::storage::State; + let mut state = OffchainState::load(&mut storage, &mut root); + + let registered_tradingpairs = >::iter() + .map(|(base, quote, _)| (base, quote)) + .collect::>(); + + let current_epoch = >::get(); + + for epoch in 0..=current_epoch { + for (base, quote) in ®istered_tradingpairs { + let pair = TradingPair::from(*quote, *base); + for (account, _) in &account_ids { + let main = Self::transform_account(account.clone())?; + // Get Q scores + let (q_scores, uptime) = + crate::lmp::get_q_score_and_uptime(&mut state, epoch, &pair, &main)?; + + if !q_scores.is_zero() || !uptime.is_zero() { + q_scores_uptime_map.insert((epoch,pair,main.clone()),(q_scores,uptime)); + } + + let fees_paid = crate::lmp::get_fees_paid_by_main_account_in_quote( + &mut state, epoch, &pair, &main, + )?; + + fees_paid_map.insert((epoch,pair,main.clone()),fees_paid); + + let maker_volume = crate::lmp::get_maker_volume_by_main_account( + &mut state, epoch, &pair, &main, + )?; + + maker_volume_map.insert((epoch,pair,main.clone()),maker_volume); + + let trade_volume = crate::lmp::get_trade_volume_by_main_account( + &mut state, epoch, &pair, &main, + )?; + + taker_volume_map.insert((epoch, pair, main.clone()),trade_volume); + } + let total_maker_volume = + crate::lmp::get_total_maker_volume(&mut state, epoch, &pair)?; + total_maker_volume_map.insert((epoch,pair), total_maker_volume); + } + } + + let config = crate::lmp::get_lmp_config(&mut state, current_epoch)?; + + log::debug!(target:"ocex", "fetch_checkpoint returning"); Ok(ObCheckpointRaw::new( snapshot_id, balances, last_processed_block_number, state_change_id, + config )) } diff --git a/pallets/ocex/src/lmp.rs b/pallets/ocex/src/lmp.rs index 9dda18e12..af3cdafd6 100644 --- a/pallets/ocex/src/lmp.rs +++ b/pallets/ocex/src/lmp.rs @@ -16,6 +16,11 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::lmp::keys::{ + get_fees_paid_by_main_account, get_maker_volume_by_main_account_key, + get_q_score_uptime_by_main_account, get_total_maker_volume_key, + get_trade_volume_by_main_account_key, +}; use crate::{ pallet::{IngressMessages, PriceOracle, TraderMetrics, TradingPairs}, storage::OffchainState, @@ -42,6 +47,54 @@ use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; pub const LMP_CONFIG_KEY: [u8; 14] = *b"LMP_CONFIG_KEY"; +pub mod keys { + use crate::lmp::LMP_CONFIG_KEY; + use orderbook_primitives::types::TradingPair; + use parity_scale_codec::Encode; + use polkadex_primitives::AccountId; + + pub fn get_trade_volume_by_main_account_key( + epoch: u16, + pair: TradingPair, + main: &AccountId, + ) -> Vec { + (epoch, pair, "trading_volume", main).encode() + } + + pub fn get_maker_volume_by_main_account_key( + epoch: u16, + pair: TradingPair, + main: &AccountId, + ) -> Vec { + (epoch, pair, "maker_volume", main).encode() + } + + pub fn get_total_maker_volume_key(epoch: u16, pair: TradingPair) -> Vec { + (epoch, pair, "maker_volume").encode() + } + + pub fn get_fees_paid_by_main_account( + epoch: u16, + pair: TradingPair, + main: &AccountId, + ) -> Vec { + (epoch, pair, "fees_paid", main).encode() + } + + #[allow(dead_code)] + pub fn get_lmp_config_key() -> Vec { + LMP_CONFIG_KEY.encode() + } + + pub fn get_q_score_uptime_by_main_account( + epoch: u16, + pair: TradingPair, + main: &AccountId, + ) -> Vec { + (epoch, pair, "q_score&uptime", main).encode() + } +} + /// Updates the trade volume generated by main account in offchain work state trie pub fn update_trade_volume_by_main_account( state: &mut OffchainState, @@ -51,7 +104,7 @@ pub fn update_trade_volume_by_main_account( main: &AccountId, ) -> Result { let trading_pair = TradingPair::from(market.quote_asset, market.base_asset); - let key = (epoch, trading_pair, "trading_volume", main).encode(); + let key = get_trade_volume_by_main_account_key(epoch, trading_pair, &main); Ok(match state.get(&key)? { None => { state.insert(key, volume.encode()); @@ -74,7 +127,7 @@ pub fn get_trade_volume_by_main_account( trading_pair: &TradingPair, main: &AccountId, ) -> Result { - let key = (epoch, trading_pair, "trading_volume", main).encode(); + let key = get_trade_volume_by_main_account_key(epoch, *trading_pair, &main); Ok(match state.get(&key)? { None => Decimal::zero(), Some(encoded_volume) => { @@ -90,7 +143,7 @@ pub fn get_maker_volume_by_main_account( trading_pair: &TradingPair, main: &AccountId, ) -> Result { - let key = (epoch, trading_pair, "maker_volume", main).encode(); + let key = get_maker_volume_by_main_account_key(epoch, *trading_pair, &main); Ok(match state.get(&key)? { None => Decimal::zero(), Some(encoded_volume) => { @@ -108,7 +161,7 @@ pub fn update_maker_volume_by_main_account( main: &AccountId, ) -> Result { let trading_pair = TradingPair::from(market.quote_asset, market.base_asset); - let key = (epoch, trading_pair, "maker_volume", main).encode(); + let key = get_maker_volume_by_main_account_key(epoch, trading_pair, &main); Ok(match state.get(&key)? { None => { state.insert(key, volume.encode()); @@ -134,7 +187,7 @@ pub fn get_total_maker_volume( return Ok(Decimal::zero()); } - let key = (epoch, trading_pair, "maker_volume").encode(); + let key = get_total_maker_volume_key(epoch, *trading_pair); Ok(match state.get(&key)? { None => Decimal::zero(), Some(encoded_volume) => { @@ -151,7 +204,7 @@ pub fn update_total_maker_volume( volume: Decimal, ) -> Result { let trading_pair = TradingPair::from(market.quote_asset, market.base_asset); - let key = (epoch, trading_pair, "maker_volume").encode(); + let key = get_total_maker_volume_key(epoch, trading_pair); Ok(match state.get(&key)? { None => { state.insert(key, volume.encode()); @@ -176,7 +229,7 @@ pub fn store_fees_paid_by_main_account_in_quote( main: &AccountId, ) -> Result { let trading_pair = TradingPair::from(market.quote_asset, market.base_asset); - let key = (epoch, trading_pair, "fees_paid", main).encode(); + let key = get_fees_paid_by_main_account(epoch, trading_pair, main); Ok(match state.get(&key)? { None => { state.insert(key, fees_in_quote_terms.encode()); @@ -199,7 +252,7 @@ pub fn get_fees_paid_by_main_account_in_quote( trading_pair: &TradingPair, main: &AccountId, ) -> Result { - let key = (epoch, trading_pair, "fees_paid", main).encode(); + let key = get_fees_paid_by_main_account(epoch, *trading_pair, main); Ok(match state.get(&key)? { None => Decimal::zero(), Some(encoded_fees_paid) => { @@ -243,7 +296,7 @@ pub fn store_q_score_and_uptime( trading_pair: &TradingPair, main: &AccountId, ) -> Result<(), &'static str> { - let key = (epoch, trading_pair, "q_score&uptime", main).encode(); + let key = get_q_score_uptime_by_main_account(epoch, *trading_pair, main); match state.get(&key)? { None => state.insert(key, BTreeMap::from([(index, score)]).encode()), Some(encoded_q_scores_map) => { @@ -267,7 +320,7 @@ pub fn get_q_score_and_uptime( trading_pair: &TradingPair, main: &AccountId, ) -> Result<(Decimal, u16), &'static str> { - let key = (epoch, trading_pair, "q_score&uptime", main).encode(); + let key = get_q_score_uptime_by_main_account(epoch, *trading_pair, main); match state.get(&key)? { None => { log::warn!(target:"ocex","q_score&uptime not found for: main: {:?}, market: {:?}",main.to_ss58check_with_version(Ss58AddressFormat::from(POLKADEX_MAINNET_SS58)), trading_pair.to_string()); diff --git a/primitives/orderbook/src/lib.rs b/primitives/orderbook/src/lib.rs index 47500ef42..bb923a063 100644 --- a/primitives/orderbook/src/lib.rs +++ b/primitives/orderbook/src/lib.rs @@ -37,6 +37,7 @@ use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; use sp_core::H256; use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; +use crate::lmp::LMPConfig; pub mod constants; pub mod types; @@ -168,6 +169,8 @@ pub struct ObCheckpointRaw { pub last_processed_block_number: BlockNumber, /// State change id pub state_change_id: u64, + /// LMPConfig + pub config: LMPConfig } impl ObCheckpointRaw { @@ -184,8 +187,9 @@ impl ObCheckpointRaw { balances: BTreeMap, last_processed_block_number: BlockNumber, state_change_id: u64, + config: LMPConfig ) -> Self { - Self { snapshot_id, balances, last_processed_block_number, state_change_id } + Self { snapshot_id, balances, last_processed_block_number, state_change_id, config } } /// Convert `ObCheckpointRaw` to `ObCheckpoint`. @@ -198,6 +202,7 @@ impl ObCheckpointRaw { balances: self.balances, last_processed_block_number: self.last_processed_block_number, state_change_id: self.state_change_id, + config: self.config, } } } diff --git a/primitives/orderbook/src/lmp.rs b/primitives/orderbook/src/lmp.rs index e2ce045db..8dbe18e81 100644 --- a/primitives/orderbook/src/lmp.rs +++ b/primitives/orderbook/src/lmp.rs @@ -29,7 +29,7 @@ use sp_std::collections::btree_map::BTreeMap; use sp_std::vec::Vec; /// LMP Epoch config -#[derive(Decode, Encode, TypeInfo, Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Decode, Encode, TypeInfo, Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default)] pub struct LMPConfig { pub epoch: u16, pub index: u16, diff --git a/primitives/orderbook/src/recovery.rs b/primitives/orderbook/src/recovery.rs index 2f151f22d..58765b33f 100644 --- a/primitives/orderbook/src/recovery.rs +++ b/primitives/orderbook/src/recovery.rs @@ -23,6 +23,7 @@ use rust_decimal::Decimal; use scale_info::TypeInfo; use serde_with::{json::JsonString, serde_as}; use std::collections::BTreeMap; +use crate::lmp::LMPConfig; /// A struct representing the recovery state of an Order Book. #[serde_as] @@ -56,6 +57,8 @@ pub struct ObCheckpoint { pub last_processed_block_number: BlockNumber, /// State change id pub state_change_id: u64, + /// LMP COnfig + pub config: LMPConfig } impl ObCheckpoint { @@ -66,6 +69,7 @@ impl ObCheckpoint { balances: self.balances.clone(), last_processed_block_number: self.last_processed_block_number, state_change_id: self.state_change_id, + config: self.config } } } From faafa3a86eb53cd3ae028ae8fded768c038fb9cb Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Wed, 20 Mar 2024 16:15:42 +0700 Subject: [PATCH 10/24] fix: change check to governance --- pallets/thea-executor/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index 2b6a5d6ca..9dca60a41 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -353,7 +353,7 @@ pub mod pallet { asset_id: u128, decimal: u8, ) -> DispatchResult { - ensure_root(origin)?; + T::GovernanceOrigin::ensure_origin(origin)?; let metadata = AssetMetadata::new(decimal).ok_or(Error::::InvalidDecimal)?; >::insert(asset_id, metadata); Self::deposit_event(Event::::AssetMetadataSet(metadata)); From 955d78d4f11fd31c5751e3e5a7986adcbc7bfdd9 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Wed, 20 Mar 2024 16:22:57 +0700 Subject: [PATCH 11/24] chore: increment spec --- runtimes/mainnet/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index a5f0e7329..6d9f39639 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -122,7 +122,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 335, + spec_version: 336, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 8f42e19fc388314e8d1c72b360f5fef73c897d79 Mon Sep 17 00:00:00 2001 From: Gautham Date: Wed, 20 Mar 2024 16:46:01 +0700 Subject: [PATCH 12/24] Restore offchin worker state --- pallets/ocex/src/lib.rs | 25 ++++++---- pallets/ocex/src/lmp.rs | 69 ++++++++++++++-------------- pallets/ocex/src/validator.rs | 41 +++++++++++++++++ primitives/orderbook/src/lib.rs | 33 +++++++++++-- primitives/orderbook/src/recovery.rs | 21 ++++++++- 5 files changed, 140 insertions(+), 49 deletions(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index ea1ee6bfb..ea156dce5 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -1931,47 +1931,52 @@ pub mod pallet { for (account, _) in &account_ids { let main = Self::transform_account(account.clone())?; // Get Q scores - let (q_scores, uptime) = - crate::lmp::get_q_score_and_uptime(&mut state, epoch, &pair, &main)?; + let q_scores_map = crate::lmp::get_q_score_and_uptime_for_checkpoint( + &mut state, epoch, &pair, &main, + )?; - if !q_scores.is_zero() || !uptime.is_zero() { - q_scores_uptime_map.insert((epoch,pair,main.clone()),(q_scores,uptime)); + if !q_scores_map.is_empty() { + q_scores_uptime_map.insert((epoch, pair, main.clone()), q_scores_map); } let fees_paid = crate::lmp::get_fees_paid_by_main_account_in_quote( &mut state, epoch, &pair, &main, )?; - fees_paid_map.insert((epoch,pair,main.clone()),fees_paid); + fees_paid_map.insert((epoch, pair, main.clone()), fees_paid); let maker_volume = crate::lmp::get_maker_volume_by_main_account( &mut state, epoch, &pair, &main, )?; - maker_volume_map.insert((epoch,pair,main.clone()),maker_volume); + maker_volume_map.insert((epoch, pair, main.clone()), maker_volume); let trade_volume = crate::lmp::get_trade_volume_by_main_account( &mut state, epoch, &pair, &main, )?; - taker_volume_map.insert((epoch, pair, main.clone()),trade_volume); + taker_volume_map.insert((epoch, pair, main.clone()), trade_volume); } let total_maker_volume = crate::lmp::get_total_maker_volume(&mut state, epoch, &pair)?; - total_maker_volume_map.insert((epoch,pair), total_maker_volume); + total_maker_volume_map.insert((epoch, pair), total_maker_volume); } } let config = crate::lmp::get_lmp_config(&mut state, current_epoch)?; - log::debug!(target:"ocex", "fetch_checkpoint returning"); Ok(ObCheckpointRaw::new( snapshot_id, balances, last_processed_block_number, state_change_id, - config + config, + q_scores_uptime_map, + maker_volume_map, + taker_volume_map, + fees_paid_map, + total_maker_volume_map, )) } diff --git a/pallets/ocex/src/lmp.rs b/pallets/ocex/src/lmp.rs index af3cdafd6..f46080fde 100644 --- a/pallets/ocex/src/lmp.rs +++ b/pallets/ocex/src/lmp.rs @@ -99,11 +99,10 @@ pub mod keys { pub fn update_trade_volume_by_main_account( state: &mut OffchainState, epoch: u16, - market: &TradingPairConfig, + trading_pair: TradingPair, volume: Decimal, main: &AccountId, ) -> Result { - let trading_pair = TradingPair::from(market.quote_asset, market.base_asset); let key = get_trade_volume_by_main_account_key(epoch, trading_pair, &main); Ok(match state.get(&key)? { None => { @@ -156,11 +155,10 @@ pub fn get_maker_volume_by_main_account( pub fn update_maker_volume_by_main_account( state: &mut OffchainState, epoch: u16, - market: &TradingPairConfig, + trading_pair: TradingPair, volume: Decimal, main: &AccountId, ) -> Result { - let trading_pair = TradingPair::from(market.quote_asset, market.base_asset); let key = get_maker_volume_by_main_account_key(epoch, trading_pair, &main); Ok(match state.get(&key)? { None => { @@ -200,10 +198,9 @@ pub fn get_total_maker_volume( pub fn update_total_maker_volume( state: &mut OffchainState, epoch: u16, - market: &TradingPairConfig, + trading_pair: TradingPair, volume: Decimal, ) -> Result { - let trading_pair = TradingPair::from(market.quote_asset, market.base_asset); let key = get_total_maker_volume_key(epoch, trading_pair); Ok(match state.get(&key)? { None => { @@ -224,11 +221,10 @@ pub fn update_total_maker_volume( pub fn store_fees_paid_by_main_account_in_quote( state: &mut OffchainState, epoch: u16, - market: &TradingPairConfig, + trading_pair: TradingPair, fees_in_quote_terms: Decimal, main: &AccountId, ) -> Result { - let trading_pair = TradingPair::from(market.quote_asset, market.base_asset); let key = get_fees_paid_by_main_account(epoch, trading_pair, main); Ok(match state.get(&key)? { None => { @@ -340,6 +336,28 @@ pub fn get_q_score_and_uptime( } } +/// Returns the individial Q score and uptime indexe +pub fn get_q_score_and_uptime_for_checkpoint( + state: &mut OffchainState, + epoch: u16, + trading_pair: &TradingPair, + main: &AccountId, +) -> Result, &'static str> { + let key = get_q_score_uptime_by_main_account(epoch, *trading_pair, main); + match state.get(&key)? { + None => { + log::warn!(target:"ocex","q_score&uptime not found for: main: {:?}, market: {:?}",main.to_ss58check_with_version(Ss58AddressFormat::from(POLKADEX_MAINNET_SS58)), trading_pair.to_string()); + // If the q_score is not found, zero will be returned. + Ok(Default::default()) + }, + Some(encoded_q_scores_map) => { + let map = BTreeMap::::decode(&mut &encoded_q_scores_map[..]) + .map_err(|_| "Unable to decode decimal")?; + Ok(map) + }, + } +} + impl Pallet { /// Updates the respective offchain DB trie keys for LMP metrics from given trade pub fn update_lmp_storage_from_trade( @@ -350,35 +368,18 @@ impl Pallet { taker_fees: Decimal, ) -> Result<(), &'static str> { let epoch: u16 = >::get(); + let pair = TradingPair::from(config.quote_asset, config.base_asset); // Store trade.price * trade.volume as maker volume for this epoch let volume = trade.price.saturating_mul(trade.amount); // Update the trade volume generated to maker account - update_trade_volume_by_main_account( - state, - epoch, - &config, - volume, - &trade.maker.main_account, - )?; + update_trade_volume_by_main_account(state, epoch, pair, volume, &trade.maker.main_account)?; // Update the trade volume generated to taker account - update_trade_volume_by_main_account( - state, - epoch, - &config, - volume, - &trade.taker.main_account, - )?; + update_trade_volume_by_main_account(state, epoch, pair, volume, &trade.taker.main_account)?; // Update the maker volume generated to account - update_maker_volume_by_main_account( - state, - epoch, - &config, - volume, - &trade.maker.main_account, - )?; + update_maker_volume_by_main_account(state, epoch, pair, volume, &trade.maker.main_account)?; // Update the total maker volume generated - update_total_maker_volume(state, epoch, &config, volume)?; + update_total_maker_volume(state, epoch, pair, volume)?; // Store maker_fees and taker_fees for the corresponding main account for this epoch match trade.maker.side { @@ -387,7 +388,7 @@ impl Pallet { store_fees_paid_by_main_account_in_quote( state, epoch, - &config, + pair, fees, &trade.maker.main_account, )?; @@ -397,7 +398,7 @@ impl Pallet { store_fees_paid_by_main_account_in_quote( state, epoch, - &config, + pair, fees, &trade.taker.main_account, )?; @@ -408,7 +409,7 @@ impl Pallet { store_fees_paid_by_main_account_in_quote( state, epoch, - &config, + pair, fees, &trade.maker.main_account, )?; @@ -418,7 +419,7 @@ impl Pallet { store_fees_paid_by_main_account_in_quote( state, epoch, - &config, + pair, fees, &trade.taker.main_account, )?; diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index 4c5b64279..36a40fcb2 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -859,6 +859,47 @@ impl Pallet { value.insert(account_asset.asset, *balance); state.insert(key, value.encode()); } + // Store LMP Config + crate::lmp::store_lmp_config(state, checkpoint.config); + // Restore Q scores and Uptime map + for ((epoch, pair, main), map) in &checkpoint.q_scores_uptime_map { + for (index, q_score) in map { + crate::lmp::store_q_score_and_uptime(state, *epoch, *index, *q_score, pair, main)?; + } + } + // Restore maker volume + for ((epoch, pair, main), maker_volume) in &checkpoint.maker_volume_map { + crate::lmp::update_maker_volume_by_main_account( + state, + *epoch, + *pair, + *maker_volume, + main, + )?; + } + + // Restore taker volume + for ((epoch, pair, main), maker_volume) in &checkpoint.taker_volume_map { + crate::lmp::update_trade_volume_by_main_account( + state, + *epoch, + *pair, + *maker_volume, + main, + )?; + } + + // Restore taker volume + for ((epoch, pair, main), fees_paid) in &checkpoint.fees_paid_map { + crate::lmp::store_fees_paid_by_main_account_in_quote( + state, *epoch, *pair, *fees_paid, main, + )?; + } + + for ((epoch, pair), total_maker_volume) in &checkpoint.total_maker_volume_map { + crate::lmp::update_total_maker_volume(state, *epoch, *pair, *total_maker_volume)?; + } + Ok(()) } diff --git a/primitives/orderbook/src/lib.rs b/primitives/orderbook/src/lib.rs index bb923a063..765ed79e0 100644 --- a/primitives/orderbook/src/lib.rs +++ b/primitives/orderbook/src/lib.rs @@ -35,6 +35,7 @@ use rust_decimal::prelude::ToPrimitive; use rust_decimal::Decimal; use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; +use sp_core::crypto::AccountId32; use sp_core::H256; use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; use crate::lmp::LMPConfig; @@ -170,7 +171,12 @@ pub struct ObCheckpointRaw { /// State change id pub state_change_id: u64, /// LMPConfig - pub config: LMPConfig + pub config: LMPConfig, + pub q_scores_uptime_map: BTreeMap<(u16, TradingPair, AccountId32), BTreeMap>, + pub maker_volume_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, + pub taker_volume_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, + pub fees_paid_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, + pub total_maker_volume_map: BTreeMap<(u16, TradingPair), Decimal>, } impl ObCheckpointRaw { @@ -187,9 +193,25 @@ impl ObCheckpointRaw { balances: BTreeMap, last_processed_block_number: BlockNumber, state_change_id: u64, - config: LMPConfig + config: LMPConfig, + q_scores_uptime_map: BTreeMap<(u16, TradingPair, AccountId32), BTreeMap>, + maker_volume_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, + taker_volume_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, + fees_paid_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, + total_maker_volume_map: BTreeMap<(u16, TradingPair), Decimal>, ) -> Self { - Self { snapshot_id, balances, last_processed_block_number, state_change_id, config } + Self { + snapshot_id, + balances, + last_processed_block_number, + state_change_id, + config, + q_scores_uptime_map, + maker_volume_map, + taker_volume_map, + fees_paid_map, + total_maker_volume_map + } } /// Convert `ObCheckpointRaw` to `ObCheckpoint`. @@ -203,6 +225,11 @@ impl ObCheckpointRaw { last_processed_block_number: self.last_processed_block_number, state_change_id: self.state_change_id, config: self.config, + q_scores_uptime_map: self.q_scores_uptime_map, + maker_volume_map: self.maker_volume_map, + taker_volume_map: self.taker_volume_map, + fees_paid_map: self.fees_paid_map, + total_maker_volume_map: self.total_maker_volume_map } } } diff --git a/primitives/orderbook/src/recovery.rs b/primitives/orderbook/src/recovery.rs index 58765b33f..60bd2bcd9 100644 --- a/primitives/orderbook/src/recovery.rs +++ b/primitives/orderbook/src/recovery.rs @@ -23,7 +23,9 @@ use rust_decimal::Decimal; use scale_info::TypeInfo; use serde_with::{json::JsonString, serde_as}; use std::collections::BTreeMap; +use sp_core::crypto::AccountId32; use crate::lmp::LMPConfig; +use crate::types::TradingPair; /// A struct representing the recovery state of an Order Book. #[serde_as] @@ -58,7 +60,17 @@ pub struct ObCheckpoint { /// State change id pub state_change_id: u64, /// LMP COnfig - pub config: LMPConfig + pub config: LMPConfig, + #[serde_as(as = "JsonString>")] + pub q_scores_uptime_map: BTreeMap<(u16, TradingPair, AccountId32), BTreeMap>, + #[serde_as(as = "JsonString>")] + pub maker_volume_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, + #[serde_as(as = "JsonString>")] + pub taker_volume_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, + #[serde_as(as = "JsonString>")] + pub fees_paid_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, + #[serde_as(as = "JsonString>")] + pub total_maker_volume_map: BTreeMap<(u16, TradingPair), Decimal>, } impl ObCheckpoint { @@ -69,7 +81,12 @@ impl ObCheckpoint { balances: self.balances.clone(), last_processed_block_number: self.last_processed_block_number, state_change_id: self.state_change_id, - config: self.config + config: self.config, + q_scores_uptime_map: self.q_scores_uptime_map.clone(), + maker_volume_map: self.maker_volume_map.clone(), + taker_volume_map: self.taker_volume_map.clone(), + fees_paid_map: self.fees_paid_map.clone(), + total_maker_volume_map: self.total_maker_volume_map.clone(), } } } From f27cd6ab8083df573946f2d6ab749e74e151a084 Mon Sep 17 00:00:00 2001 From: Gautham Date: Wed, 20 Mar 2024 18:13:23 +0700 Subject: [PATCH 13/24] Fix CI issues --- pallets/ocex/src/lib.rs | 4 +-- pallets/ocex/src/lmp.rs | 9 ++++--- primitives/orderbook/src/lib.rs | 38 ++-------------------------- primitives/orderbook/src/lmp.rs | 4 ++- primitives/orderbook/src/recovery.rs | 6 ++--- 5 files changed, 15 insertions(+), 46 deletions(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index ea156dce5..c1ed649d0 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -1966,7 +1966,7 @@ pub mod pallet { let config = crate::lmp::get_lmp_config(&mut state, current_epoch)?; log::debug!(target:"ocex", "fetch_checkpoint returning"); - Ok(ObCheckpointRaw::new( + Ok(ObCheckpointRaw { snapshot_id, balances, last_processed_block_number, @@ -1977,7 +1977,7 @@ pub mod pallet { taker_volume_map, fees_paid_map, total_maker_volume_map, - )) + }) } /// Fetches balance of given `AssetId` for given `AccountId` from offchain storage diff --git a/pallets/ocex/src/lmp.rs b/pallets/ocex/src/lmp.rs index f46080fde..2432c96a5 100644 --- a/pallets/ocex/src/lmp.rs +++ b/pallets/ocex/src/lmp.rs @@ -52,6 +52,7 @@ pub mod keys { use orderbook_primitives::types::TradingPair; use parity_scale_codec::Encode; use polkadex_primitives::AccountId; + use sp_std::vec::Vec; pub fn get_trade_volume_by_main_account_key( epoch: u16, @@ -103,7 +104,7 @@ pub fn update_trade_volume_by_main_account( volume: Decimal, main: &AccountId, ) -> Result { - let key = get_trade_volume_by_main_account_key(epoch, trading_pair, &main); + let key = get_trade_volume_by_main_account_key(epoch, trading_pair, main); Ok(match state.get(&key)? { None => { state.insert(key, volume.encode()); @@ -126,7 +127,7 @@ pub fn get_trade_volume_by_main_account( trading_pair: &TradingPair, main: &AccountId, ) -> Result { - let key = get_trade_volume_by_main_account_key(epoch, *trading_pair, &main); + let key = get_trade_volume_by_main_account_key(epoch, *trading_pair, main); Ok(match state.get(&key)? { None => Decimal::zero(), Some(encoded_volume) => { @@ -142,7 +143,7 @@ pub fn get_maker_volume_by_main_account( trading_pair: &TradingPair, main: &AccountId, ) -> Result { - let key = get_maker_volume_by_main_account_key(epoch, *trading_pair, &main); + let key = get_maker_volume_by_main_account_key(epoch, *trading_pair, main); Ok(match state.get(&key)? { None => Decimal::zero(), Some(encoded_volume) => { @@ -159,7 +160,7 @@ pub fn update_maker_volume_by_main_account( volume: Decimal, main: &AccountId, ) -> Result { - let key = get_maker_volume_by_main_account_key(epoch, trading_pair, &main); + let key = get_maker_volume_by_main_account_key(epoch, trading_pair, main); Ok(match state.get(&key)? { None => { state.insert(key, volume.encode()); diff --git a/primitives/orderbook/src/lib.rs b/primitives/orderbook/src/lib.rs index 765ed79e0..ee11f2e43 100644 --- a/primitives/orderbook/src/lib.rs +++ b/primitives/orderbook/src/lib.rs @@ -24,6 +24,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use crate::ingress::EgressMessages; +use crate::lmp::LMPConfig; #[cfg(feature = "std")] use crate::recovery::ObCheckpoint; use crate::types::{AccountAsset, TradingPair}; @@ -38,7 +39,6 @@ use serde::{Deserialize, Serialize}; use sp_core::crypto::AccountId32; use sp_core::H256; use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; -use crate::lmp::LMPConfig; pub mod constants; pub mod types; @@ -180,40 +180,6 @@ pub struct ObCheckpointRaw { } impl ObCheckpointRaw { - /// Create a new `ObCheckpointRaw` instance. - /// # Parameters - /// * `snapshot_id`: The snapshot ID of the order book recovery state. - /// * `balances`: A `BTreeMap` that maps `AccountAsset`s to `Decimal` balances. - /// * `last_processed_block_number`: The last block number that was processed by validator. - /// * `state_change_id`: State change id - /// # Returns - /// * `ObCheckpointRaw`: A new `ObCheckpointRaw` instance. - pub fn new( - snapshot_id: u64, - balances: BTreeMap, - last_processed_block_number: BlockNumber, - state_change_id: u64, - config: LMPConfig, - q_scores_uptime_map: BTreeMap<(u16, TradingPair, AccountId32), BTreeMap>, - maker_volume_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, - taker_volume_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, - fees_paid_map: BTreeMap<(u16, TradingPair, AccountId32), Decimal>, - total_maker_volume_map: BTreeMap<(u16, TradingPair), Decimal>, - ) -> Self { - Self { - snapshot_id, - balances, - last_processed_block_number, - state_change_id, - config, - q_scores_uptime_map, - maker_volume_map, - taker_volume_map, - fees_paid_map, - total_maker_volume_map - } - } - /// Convert `ObCheckpointRaw` to `ObCheckpoint`. /// # Returns /// * `ObCheckpoint`: A new `ObCheckpoint` instance. @@ -229,7 +195,7 @@ impl ObCheckpointRaw { maker_volume_map: self.maker_volume_map, taker_volume_map: self.taker_volume_map, fees_paid_map: self.fees_paid_map, - total_maker_volume_map: self.total_maker_volume_map + total_maker_volume_map: self.total_maker_volume_map, } } } diff --git a/primitives/orderbook/src/lmp.rs b/primitives/orderbook/src/lmp.rs index 8dbe18e81..2853581e6 100644 --- a/primitives/orderbook/src/lmp.rs +++ b/primitives/orderbook/src/lmp.rs @@ -29,7 +29,9 @@ use sp_std::collections::btree_map::BTreeMap; use sp_std::vec::Vec; /// LMP Epoch config -#[derive(Decode, Encode, TypeInfo, Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default)] +#[derive( + Decode, Encode, TypeInfo, Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default, +)] pub struct LMPConfig { pub epoch: u16, pub index: u16, diff --git a/primitives/orderbook/src/recovery.rs b/primitives/orderbook/src/recovery.rs index 60bd2bcd9..b8aa00041 100644 --- a/primitives/orderbook/src/recovery.rs +++ b/primitives/orderbook/src/recovery.rs @@ -16,16 +16,16 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::lmp::LMPConfig; +use crate::types::TradingPair; use crate::{types::AccountAsset, ObCheckpointRaw}; use parity_scale_codec::{Decode, Encode}; use polkadex_primitives::{AccountId, AssetId, BlockNumber}; use rust_decimal::Decimal; use scale_info::TypeInfo; use serde_with::{json::JsonString, serde_as}; -use std::collections::BTreeMap; use sp_core::crypto::AccountId32; -use crate::lmp::LMPConfig; -use crate::types::TradingPair; +use std::collections::BTreeMap; /// A struct representing the recovery state of an Order Book. #[serde_as] From cf4883c74387a320b520ed01c0186abb532e70a6 Mon Sep 17 00:00:00 2001 From: Gautham Date: Thu, 21 Mar 2024 15:26:01 +0700 Subject: [PATCH 14/24] Update fetch checkpoint api --- pallets/ocex/src/lib.rs | 16 ++++++++++++---- pallets/ocex/src/validator.rs | 2 +- runtimes/mainnet/src/lib.rs | 2 +- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index c1ed649d0..f6e0faa9c 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -1943,23 +1943,31 @@ pub mod pallet { &mut state, epoch, &pair, &main, )?; - fees_paid_map.insert((epoch, pair, main.clone()), fees_paid); + if !fees_paid.is_zero() { + fees_paid_map.insert((epoch, pair, main.clone()), fees_paid); + } let maker_volume = crate::lmp::get_maker_volume_by_main_account( &mut state, epoch, &pair, &main, )?; - maker_volume_map.insert((epoch, pair, main.clone()), maker_volume); + if !maker_volume.is_zero() { + maker_volume_map.insert((epoch, pair, main.clone()), maker_volume); + } let trade_volume = crate::lmp::get_trade_volume_by_main_account( &mut state, epoch, &pair, &main, )?; - taker_volume_map.insert((epoch, pair, main.clone()), trade_volume); + if !trade_volume.is_zero(){ + taker_volume_map.insert((epoch, pair, main.clone()), trade_volume); + } } let total_maker_volume = crate::lmp::get_total_maker_volume(&mut state, epoch, &pair)?; - total_maker_volume_map.insert((epoch, pair), total_maker_volume); + if !total_maker_volume.is_zero() { + total_maker_volume_map.insert((epoch, pair), total_maker_volume); + } } } diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index 36a40fcb2..beb6e4e84 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -889,7 +889,7 @@ impl Pallet { )?; } - // Restore taker volume + // Restore trading fees for ((epoch, pair, main), fees_paid) in &checkpoint.fees_paid_map { crate::lmp::store_fees_paid_by_main_account_in_quote( state, *epoch, *pair, *fees_paid, main, diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 6d9f39639..c846f8a3c 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -122,7 +122,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 336, + spec_version: 337, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 6642502a8976448f7137684dbaa4860a80042dbf Mon Sep 17 00:00:00 2001 From: Gautham Date: Thu, 21 Mar 2024 15:26:20 +0700 Subject: [PATCH 15/24] cargo fmt --- pallets/ocex/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index f6e0faa9c..f28ffd08f 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -1959,7 +1959,7 @@ pub mod pallet { &mut state, epoch, &pair, &main, )?; - if !trade_volume.is_zero(){ + if !trade_volume.is_zero() { taker_volume_map.insert((epoch, pair, main.clone()), trade_volume); } } From 103f4357a0e99a571f9e2855670b2af4a0f7d4b5 Mon Sep 17 00:00:00 2001 From: Gautham Date: Thu, 21 Mar 2024 16:11:34 +0700 Subject: [PATCH 16/24] Add pot accounts to checkpoint --- pallets/ocex/src/lib.rs | 5 ++++- pallets/ocex/src/validator.rs | 1 + runtimes/mainnet/src/lib.rs | 2 +- scripts/get_balance_rpc.sh | 2 +- 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index f28ffd08f..754eca04d 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -1889,12 +1889,15 @@ pub mod pallet { /// Fetch checkpoint for recovery pub fn fetch_checkpoint() -> Result { log::debug!(target:"ocex", "fetch_checkpoint called"); - let account_ids = + let mut account_ids = >::iter().fold(vec![], |mut ids_accum, (acc, acc_info)| { ids_accum.push((acc.clone(), acc_info.proxies)); ids_accum }); + // Add pot account to it + account_ids.push((Self::get_pot_account(), Default::default())); + let mut balances: BTreeMap = BTreeMap::new(); let mut q_scores_uptime_map = BTreeMap::new(); let mut maker_volume_map = BTreeMap::new(); diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index beb6e4e84..e1556d2e9 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -896,6 +896,7 @@ impl Pallet { )?; } + // Restore total maker volume for ((epoch, pair), total_maker_volume) in &checkpoint.total_maker_volume_map { crate::lmp::update_total_maker_volume(state, *epoch, *pair, *total_maker_volume)?; } diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index c846f8a3c..63bf482f8 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -122,7 +122,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 337, + spec_version: 338, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, diff --git a/scripts/get_balance_rpc.sh b/scripts/get_balance_rpc.sh index 627c20125..e5d953680 100755 --- a/scripts/get_balance_rpc.sh +++ b/scripts/get_balance_rpc.sh @@ -3,5 +3,5 @@ curl -H "Content-Type: application/json" -d '{ "jsonrpc":"2.0", "id":1, "method":"ob_getBalance", - "params":["esntiQCvLG55kFN3cqJjQoA1VeBrx9oiorDobuejDta7xcokf",{"asset":"3496813586714279103986568049643838918"}] + "params":["esr4dJBv5123tkiA3beRZ3TrHbppJ6PdPxo2xHN4rmZJGDQJo",{"asset":"3496813586714279103986568049643838918"}] }' http://localhost:9944 From 149f47a6543208b787ced26a63e80a7224230b6f Mon Sep 17 00:00:00 2001 From: Gautham Date: Fri, 22 Mar 2024 08:01:25 +0700 Subject: [PATCH 17/24] Wrap around the Lmp index --- pallets/ocex/src/lmp.rs | 5 +---- pallets/ocex/src/validator.rs | 3 ++- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/pallets/ocex/src/lmp.rs b/pallets/ocex/src/lmp.rs index 2432c96a5..9b31bff88 100644 --- a/pallets/ocex/src/lmp.rs +++ b/pallets/ocex/src/lmp.rs @@ -299,10 +299,7 @@ pub fn store_q_score_and_uptime( Some(encoded_q_scores_map) => { let mut map = BTreeMap::::decode(&mut &encoded_q_scores_map[..]) .map_err(|_| "Unable to decode decimal")?; - if map.insert(index, score).is_some() { - log::error!(target:"ocex","Overwriting q score with index: {:?}, epoch: {:?}, main: {:?}, market: {:?}",index,epoch,main,trading_pair); - return Err("Overwriting q score"); - } + map.insert(index, score); // We overwrite on wrapping around log::info!(target: "ocex","Writing Q score and uptime for main: {:?}",main); state.insert(key, map.encode()); }, diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index e1556d2e9..2cda417f0 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -749,7 +749,8 @@ impl Pallet { current_on_chain_epoch: u16, ) -> Result<(), &'static str> { let mut config = get_lmp_config(state, current_on_chain_epoch)?; - let next_index = config.index.saturating_add(1); + // We wrap around the index if we overflow + let next_index = config.index.checked_add(1).unwrap_or_else(|| 0); for (main, score) in scores { store_q_score_and_uptime( state, From 25b8eff571a1a18fbbcbbcf656cdbd508141535f Mon Sep 17 00:00:00 2001 From: Gautham Date: Fri, 22 Mar 2024 08:01:47 +0700 Subject: [PATCH 18/24] Increment runtime spec --- runtimes/mainnet/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 63bf482f8..885427ee4 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -122,7 +122,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 338, + spec_version: 339, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 18bd76cbe7022eeadff214ff867285b74214d94c Mon Sep 17 00:00:00 2001 From: Gautham Date: Mon, 25 Mar 2024 08:14:24 +0700 Subject: [PATCH 19/24] Fix minor deviation error --- pallets/ocex/src/settlement.rs | 27 +++++++++++++++++++-------- runtimes/mainnet/src/lib.rs | 2 +- scripts/get_balance_rpc.sh | 2 +- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/pallets/ocex/src/settlement.rs b/pallets/ocex/src/settlement.rs index ecd5c1a9b..c8202337c 100644 --- a/pallets/ocex/src/settlement.rs +++ b/pallets/ocex/src/settlement.rs @@ -18,6 +18,7 @@ //! Helper functions for updating the balance +use core::ops::Sub; use crate::{storage::OffchainState, Config, Pallet}; use log::{error, info}; use orderbook_primitives::ocex::TradingPairConfig; @@ -26,9 +27,11 @@ use orderbook_primitives::{constants::FEE_POT_PALLET_ID, types::Trade}; use parity_scale_codec::{alloc::string::ToString, Decode, Encode}; use polkadex_primitives::{fees::FeeConfig, AccountId, AssetId}; use rust_decimal::{prelude::ToPrimitive, Decimal}; -use sp_core::crypto::ByteArray; +use rust_decimal::RoundingStrategy::ToZero; +use sp_core::crypto::{ByteArray, Ss58AddressFormat, Ss58Codec}; use sp_runtime::traits::AccountIdConversion; use sp_std::collections::btree_map::BTreeMap; +use orderbook_primitives::constants::POLKADEX_MAINNET_SS58; /// Returns the balance of an account and asset from state /// @@ -88,7 +91,7 @@ pub fn add_balance( /// Updates provided trie db with reducing balance of account asset if it exists in the db. /// /// If account asset balance does not exists in the db `AccountBalanceNotFound` error will be -/// returned. +/// returned. Balance returned is the acutal balance that was deduced accounting for rounding errors/deviation. /// /// # Parameters /// @@ -100,8 +103,8 @@ pub fn sub_balance( state: &mut OffchainState, account: &AccountId, asset: AssetId, - balance: Decimal, -) -> Result<(), &'static str> { + mut balance: Decimal, +) -> Result { log::info!(target:"ocex", "subtracting {:?} asset {:?} from account {:?}", balance.to_f64().unwrap(), asset.to_string(), account); let mut balances: BTreeMap = match state.get(&account.to_raw_vec())? { None => return Err("Account not found in trie"), @@ -109,17 +112,25 @@ pub fn sub_balance( .map_err(|_| "Unable to decode balances for account")?, }; - let account_balance = balances.get_mut(&asset).ok_or("NotEnoughBalance")?; + let account_balance = balances.get_mut(&asset).ok_or("NotEnoughBalance: zero balance")?; + if *account_balance < balance { - log::error!(target:"ocex","Asset found but balance low for asset: {:?}, of account: {:?}",asset, account); - return Err("NotEnoughBalance"); + // If the deviation is smaller that system limit, then we can allow what's stored in the offchain balance + let deviation = balance.sub(&*account_balance); + if !deviation.round_dp_with_strategy(8, ToZero).is_zero() { + log::error!(target:"ocex","Asset found but balance low for asset: {:?}, of account: {:?}",asset, account); + return Err("NotEnoughBalance"); + }else{ + log::warn!(target:"ocex","Asset found but minor balance deviation of {:?} for asset: {:?}, of account: {:?}",deviation,asset.to_string(), account.to_ss58check_with_version(Ss58AddressFormat::from(POLKADEX_MAINNET_SS58))); + balance = *account_balance; + } } *account_balance = Order::rounding_off(account_balance.saturating_sub(balance)); state.insert(account.to_raw_vec(), balances.encode()); - Ok(()) + Ok(balance) } impl Pallet { diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 63bf482f8..5f2393b85 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -122,7 +122,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 338, + spec_version: 340, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, diff --git a/scripts/get_balance_rpc.sh b/scripts/get_balance_rpc.sh index e5d953680..c22e4dc56 100755 --- a/scripts/get_balance_rpc.sh +++ b/scripts/get_balance_rpc.sh @@ -3,5 +3,5 @@ curl -H "Content-Type: application/json" -d '{ "jsonrpc":"2.0", "id":1, "method":"ob_getBalance", - "params":["esr4dJBv5123tkiA3beRZ3TrHbppJ6PdPxo2xHN4rmZJGDQJo",{"asset":"3496813586714279103986568049643838918"}] + "params":["espg8YLUhUDVXcrfNMyHqzjBBrrq3HBKj3FBQNq6Hte3p28Eh",{"asset":"95930534000017180603917534864279132680"}] }' http://localhost:9944 From 225d766669ec66dd08c67c504297889f1eb20a46 Mon Sep 17 00:00:00 2001 From: Gautham Date: Mon, 25 Mar 2024 08:27:48 +0700 Subject: [PATCH 20/24] Fix minor deviation error --- pallets/ocex/src/settlement.rs | 9 ++++----- pallets/ocex/src/validator.rs | 6 +++--- runtimes/mainnet/src/lib.rs | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/pallets/ocex/src/settlement.rs b/pallets/ocex/src/settlement.rs index c8202337c..efe6753dc 100644 --- a/pallets/ocex/src/settlement.rs +++ b/pallets/ocex/src/settlement.rs @@ -18,20 +18,20 @@ //! Helper functions for updating the balance -use core::ops::Sub; use crate::{storage::OffchainState, Config, Pallet}; +use core::ops::Sub; use log::{error, info}; +use orderbook_primitives::constants::POLKADEX_MAINNET_SS58; use orderbook_primitives::ocex::TradingPairConfig; use orderbook_primitives::types::Order; use orderbook_primitives::{constants::FEE_POT_PALLET_ID, types::Trade}; use parity_scale_codec::{alloc::string::ToString, Decode, Encode}; use polkadex_primitives::{fees::FeeConfig, AccountId, AssetId}; -use rust_decimal::{prelude::ToPrimitive, Decimal}; use rust_decimal::RoundingStrategy::ToZero; +use rust_decimal::{prelude::ToPrimitive, Decimal}; use sp_core::crypto::{ByteArray, Ss58AddressFormat, Ss58Codec}; use sp_runtime::traits::AccountIdConversion; use sp_std::collections::btree_map::BTreeMap; -use orderbook_primitives::constants::POLKADEX_MAINNET_SS58; /// Returns the balance of an account and asset from state /// @@ -114,14 +114,13 @@ pub fn sub_balance( let account_balance = balances.get_mut(&asset).ok_or("NotEnoughBalance: zero balance")?; - if *account_balance < balance { // If the deviation is smaller that system limit, then we can allow what's stored in the offchain balance let deviation = balance.sub(&*account_balance); if !deviation.round_dp_with_strategy(8, ToZero).is_zero() { log::error!(target:"ocex","Asset found but balance low for asset: {:?}, of account: {:?}",asset, account); return Err("NotEnoughBalance"); - }else{ + } else { log::warn!(target:"ocex","Asset found but minor balance deviation of {:?} for asset: {:?}, of account: {:?}",deviation,asset.to_string(), account.to_ss58check_with_version(Ss58AddressFormat::from(POLKADEX_MAINNET_SS58))); balance = *account_balance; } diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index e1556d2e9..5fc93eb87 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -681,15 +681,15 @@ impl Pallet { if !request.verify() { return Err("SignatureVerificationFailed"); } - sub_balance( + let actual_deducted = sub_balance( state, &Decode::decode(&mut &request.main.encode()[..]) .map_err(|_| "account id decode error")?, request.asset(), amount, )?; - let withdrawal = request.convert(stid).map_err(|_| "Withdrawal conversion error")?; - + let mut withdrawal = request.convert(stid).map_err(|_| "Withdrawal conversion error")?; + withdrawal.amount = actual_deducted; // The acutal deducted balance Ok(withdrawal) } diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 5f2393b85..f07f53e42 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -122,7 +122,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 340, + spec_version: 341, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 3be800f3a0deb90a3d27a1f27e5e7df873547a2c Mon Sep 17 00:00:00 2001 From: Gautham Date: Mon, 25 Mar 2024 09:48:16 +0700 Subject: [PATCH 21/24] fix cargo test --- pallets/ocex/src/tests.rs | 14 +++++++------- runtimes/parachain/src/lib.rs | 1 + 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/pallets/ocex/src/tests.rs b/pallets/ocex/src/tests.rs index 78e859d7c..6bf81925b 100644 --- a/pallets/ocex/src/tests.rs +++ b/pallets/ocex/src/tests.rs @@ -316,16 +316,16 @@ fn test_sub_balance_existing_account_with_balance() { //sub balance let amount2 = 2000000; - let result = sub_balance(&mut state, &account_id, asset_id, amount2.into()); - assert_eq!(result, Ok(())); + let result = sub_balance(&mut state, &account_id, asset_id, amount2.into()).unwrap(); + assert_eq!(result,amount2.into()); let encoded = state.get(&account_id.to_raw_vec()).unwrap().unwrap(); let account_info: BTreeMap = BTreeMap::decode(&mut &encoded[..]).unwrap(); assert_eq!(account_info.get(&asset_id).unwrap(), &(amount - amount2).into()); //sub balance till 0 let amount3 = amount - amount2; - let result = sub_balance(&mut state, &account_id, asset_id, amount3.into()); - assert_eq!(result, Ok(())); + let result = sub_balance(&mut state, &account_id, asset_id, amount3.into()).unwrap(); + assert_eq!(result, amount3.into()); let encoded = state.get(&account_id.to_raw_vec()).unwrap().unwrap(); let account_info: BTreeMap = BTreeMap::decode(&mut &encoded[..]).unwrap(); assert_eq!(amount - amount2 - amount3, 0); @@ -416,8 +416,8 @@ fn test_balance_update_depost_first_then_trade() { //sub balance till 0 let amount3 = Decimal::from_f64_retain(2.0).unwrap(); - let result = sub_balance(&mut state, &account_id, AssetId::Polkadex, amount3.into()); - assert_eq!(result, Ok(())); + let result = sub_balance(&mut state, &account_id, AssetId::Polkadex, amount3.into()).unwrap(); + assert_eq!(result, amount3); }); } @@ -469,7 +469,7 @@ fn test_trade_between_two_accounts_without_balance() { let result = OCEX::process_trade(&mut state, &trade, config, maker_fees, taker_fees); match result { Ok(_) => assert!(false), - Err(e) => assert_eq!(e, "NotEnoughBalance"), + Err(e) => assert_eq!(e, "NotEnoughBalance: zero balance"), } }); } diff --git a/runtimes/parachain/src/lib.rs b/runtimes/parachain/src/lib.rs index 7919b941c..768814b30 100644 --- a/runtimes/parachain/src/lib.rs +++ b/runtimes/parachain/src/lib.rs @@ -837,6 +837,7 @@ impl_runtime_apis! { } } +#[allow(dead_code)] struct CheckInherents; impl cumulus_pallet_parachain_system::CheckInherents for CheckInherents { From 2e0cbc99747af6cff89965fd54df4eb39a74233f Mon Sep 17 00:00:00 2001 From: Gautham Date: Mon, 25 Mar 2024 11:51:32 +0700 Subject: [PATCH 22/24] fix CI --- pallets/ocex/src/validator.rs | 2 +- runtimes/parachain/src/lib.rs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index 2cda417f0..752054726 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -750,7 +750,7 @@ impl Pallet { ) -> Result<(), &'static str> { let mut config = get_lmp_config(state, current_on_chain_epoch)?; // We wrap around the index if we overflow - let next_index = config.index.checked_add(1).unwrap_or_else(|| 0); + let next_index = config.index.checked_add(1).unwrap_or(0); for (main, score) in scores { store_q_score_and_uptime( state, diff --git a/runtimes/parachain/src/lib.rs b/runtimes/parachain/src/lib.rs index 7919b941c..768814b30 100644 --- a/runtimes/parachain/src/lib.rs +++ b/runtimes/parachain/src/lib.rs @@ -837,6 +837,7 @@ impl_runtime_apis! { } } +#[allow(dead_code)] struct CheckInherents; impl cumulus_pallet_parachain_system::CheckInherents for CheckInherents { From 7a4cd90a058adc62b3400b41eec5b8860b7ddf79 Mon Sep 17 00:00:00 2001 From: Gautham Date: Mon, 25 Mar 2024 11:53:33 +0700 Subject: [PATCH 23/24] cargo fmt --- pallets/ocex/src/tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pallets/ocex/src/tests.rs b/pallets/ocex/src/tests.rs index 6bf81925b..afb9c7bf9 100644 --- a/pallets/ocex/src/tests.rs +++ b/pallets/ocex/src/tests.rs @@ -317,7 +317,7 @@ fn test_sub_balance_existing_account_with_balance() { //sub balance let amount2 = 2000000; let result = sub_balance(&mut state, &account_id, asset_id, amount2.into()).unwrap(); - assert_eq!(result,amount2.into()); + assert_eq!(result, amount2.into()); let encoded = state.get(&account_id.to_raw_vec()).unwrap().unwrap(); let account_info: BTreeMap = BTreeMap::decode(&mut &encoded[..]).unwrap(); assert_eq!(account_info.get(&asset_id).unwrap(), &(amount - amount2).into()); @@ -416,7 +416,8 @@ fn test_balance_update_depost_first_then_trade() { //sub balance till 0 let amount3 = Decimal::from_f64_retain(2.0).unwrap(); - let result = sub_balance(&mut state, &account_id, AssetId::Polkadex, amount3.into()).unwrap(); + let result = + sub_balance(&mut state, &account_id, AssetId::Polkadex, amount3.into()).unwrap(); assert_eq!(result, amount3); }); } From ec0abbb1e609507a606ecd79da2c7011a95bf229 Mon Sep 17 00:00:00 2001 From: Gautham Date: Mon, 25 Mar 2024 12:02:55 +0700 Subject: [PATCH 24/24] Increase ED for AutoSwap to 1.5 PDEX --- runtimes/mainnet/src/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index f07f53e42..dcaa09cf0 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -122,7 +122,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 341, + spec_version: 342, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, @@ -1352,6 +1352,7 @@ parameter_types! { pub const TheaPalletAccount: PalletId = PalletId(*b"th/accnt"); pub const WithdrawalSize: u32 = 10; pub const ParaId: u32 = 2040; + pub const AutoSwapInitialNativeDeposit: Balance = 1500000000000; } impl thea_executor::Config for Runtime { @@ -1370,7 +1371,7 @@ impl thea_executor::Config for Runtime { type MultiAssetIdAdapter = AssetId; type AssetBalanceAdapter = u128; type GovernanceOrigin = EnsureRootOrHalfCouncil; - type ExistentialDeposit = ExistentialDeposit; + type ExistentialDeposit = AutoSwapInitialNativeDeposit; } #[cfg(feature = "runtime-benchmarks")]