From 0a89e4973887389f5cf569992c511b9b6de0c614 Mon Sep 17 00:00:00 2001 From: gautham Date: Thu, 25 Jan 2024 11:49:55 +0530 Subject: [PATCH] crago fmt, clippy --- Cargo.lock | 1 + pallets/liquidity-mining/Cargo.toml | 6 +++++ pallets/liquidity-mining/src/lib.rs | 40 +++++++++++++---------------- pallets/ocex/rpc/src/lib.rs | 8 +++--- pallets/ocex/src/benchmarking.rs | 35 +++---------------------- pallets/ocex/src/lib.rs | 17 ++++++++++-- pallets/ocex/src/validator.rs | 28 ++++++-------------- runtimes/mainnet/Cargo.toml | 6 ++++- runtimes/mainnet/src/lib.rs | 5 +--- 9 files changed, 62 insertions(+), 84 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 22c5617f0..bf5045072 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5117,6 +5117,7 @@ dependencies = [ "sp-staking", "sp-statement-store", "sp-std", + "sp-storage", "sp-transaction-pool", "sp-version", "static_assertions", diff --git a/pallets/liquidity-mining/Cargo.toml b/pallets/liquidity-mining/Cargo.toml index 44ac27f20..1bcf2a2aa 100644 --- a/pallets/liquidity-mining/Cargo.toml +++ b/pallets/liquidity-mining/Cargo.toml @@ -54,3 +54,9 @@ std = [ "sp-application-crypto/std", "sp-io/std" ] +runtime-benchmarks = [ + "sp-runtime/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", +] +try-runtime = ["frame-support/try-runtime"] \ No newline at end of file diff --git a/pallets/liquidity-mining/src/lib.rs b/pallets/liquidity-mining/src/lib.rs index 33b796c8b..0a7f06a25 100644 --- a/pallets/liquidity-mining/src/lib.rs +++ b/pallets/liquidity-mining/src/lib.rs @@ -72,6 +72,11 @@ pub mod pallet { MMClaimFlag, ); + type LMPScoreSheet = BTreeMap< + (TradingPair, ::AccountId, u16), + (BTreeMap<::AccountId, (BalanceOf, bool)>, BalanceOf), + >; + #[pallet::config] pub trait Config: frame_system::Config + SendTransactionTypes> { type RuntimeEvent: IsType<::RuntimeEvent> + From>; @@ -279,12 +284,9 @@ pub mod pallet { if >::get().is_none() { return InvalidTransaction::Call.into() } - match source { - TransactionSource::External => { - // Don't accept externally sourced calls - return InvalidTransaction::Call.into() - }, - _ => {}, + if source == TransactionSource::External { + // Don't accept externally sourced calls + return InvalidTransaction::Call.into() } // TODO: @zktony Update the verification logic to make it more stringent. @@ -315,7 +317,7 @@ pub mod pallet { .propagate(true) .build() } else { - return InvalidTransaction::Call.into() + InvalidTransaction::Call.into() } } } @@ -471,10 +473,10 @@ pub mod pallet { let config = >::get(market, market_maker).ok_or(Error::::UnknownPool)?; ensure!(>::get().is_none(), Error::::SnapshotInProgress); // TODO: @zktony Replace with pool level flags - let total = T::OtherAssets::total_issuance(config.share_id.into()); + let total = T::OtherAssets::total_issuance(config.share_id); ensure!(!total.is_zero(), Error::::TotalShareIssuanceIsZero); let burned_amt = T::OtherAssets::burn_from( - config.share_id.into(), + config.share_id, &lp, shares, Precision::Exact, @@ -617,10 +619,7 @@ pub mod pallet { #[transactional] pub fn submit_scores_of_lps( origin: OriginFor, - results: BTreeMap< - (TradingPair, T::AccountId, u16), - (BTreeMap, bool)>, BalanceOf), - >, + results: LMPScoreSheet, ) -> DispatchResult { ensure_none(origin)?; @@ -655,13 +654,13 @@ pub mod pallet { let pool_config = >::get(market, &market_maker).ok_or(Error::::UnknownPool)?; let mut requests = >::get(epoch, &pool_config.pool_id); - for index in 0..num_requests { + for request in requests.iter().take(num_requests) { T::OCEX::remove_liquidity( market, pool_config.pool_id.clone(), - requests[index].0.clone(), - requests[index].1, - requests[index].2, + request.0.clone(), + request.1, + request.2, ); } requests = requests[num_requests..].to_vec(); @@ -749,10 +748,7 @@ pub mod pallet { }; // TODO: Only compute the result every five blocks - let mut results: BTreeMap< - (TradingPair, T::AccountId, u16), - (BTreeMap, bool)>, BalanceOf), - > = BTreeMap::new(); + let mut results: LMPScoreSheet = BTreeMap::new(); // Loop over all pools and lps and calculate score of all LPs for (market, mm, config) in >::iter() { let mut scores_map = BTreeMap::new(); @@ -825,7 +821,7 @@ pub mod pallet { }, AssetId::Asset(id) => { T::OtherAssets::transfer( - id.into(), + id, payer, payee, amount.unique_saturated_into(), diff --git a/pallets/ocex/rpc/src/lib.rs b/pallets/ocex/rpc/src/lib.rs index 9df6f22e1..2e0244215 100644 --- a/pallets/ocex/rpc/src/lib.rs +++ b/pallets/ocex/rpc/src/lib.rs @@ -67,7 +67,7 @@ pub trait PolkadexOcexRpcApi { async fn account_scores_by_market( &self, at: Option, - epoch: u32, + epoch: u16, market: TradingPair, sorted_by_mm_score: bool, limit: u16, @@ -77,7 +77,7 @@ pub trait PolkadexOcexRpcApi { fn eligible_rewards( &self, at: Option, - epoch: u32, + epoch: u16, market: TradingPair, main: AccountId, ) -> RpcResult<(String, String, bool)>; @@ -228,7 +228,7 @@ where async fn account_scores_by_market( &self, at: Option<::Hash>, - epoch: u32, + epoch: u16, market: TradingPair, sorted_by_mm_score: bool, limit: u16, @@ -249,7 +249,7 @@ where fn eligible_rewards( &self, at: Option<::Hash>, - epoch: u32, + epoch: u16, market: TradingPair, main: AccountId, ) -> RpcResult<(String, String, bool)> { diff --git a/pallets/ocex/src/benchmarking.rs b/pallets/ocex/src/benchmarking.rs index 90ae13846..de489182a 100644 --- a/pallets/ocex/src/benchmarking.rs +++ b/pallets/ocex/src/benchmarking.rs @@ -25,10 +25,7 @@ use frame_benchmarking::{ v1::{account, benchmarks}, whitelisted_caller, }; -use frame_support::{ - traits::{EnsureOrigin, UnfilteredDispatchable}, - BoundedVec, -}; +use frame_support::traits::{EnsureOrigin, UnfilteredDispatchable}; use frame_system::RawOrigin; use orderbook_primitives::Fees; use parity_scale_codec::Decode; @@ -36,10 +33,7 @@ use polkadex_primitives::{ ocex::TradingPairConfig, withdrawal::Withdrawal, ProxyLimit, UNIT_BALANCE, }; use rust_decimal::{prelude::*, Decimal}; -use sp_runtime::{ - traits::{BlockNumberProvider, One}, - BoundedBTreeSet, -}; +use sp_runtime::{traits::One, BoundedBTreeSet}; // Check if last event generated by pallet is the one we're expecting fn assert_last_event(generic_event: ::RuntimeEvent) { @@ -299,29 +293,6 @@ benchmarks! { assert_eq!(>::get(), !state); } - set_balances { - let x in 0 .. 255; // should not overflow up - let origin = T::GovernanceOrigin::try_successful_origin().unwrap(); - let main_account = T::AccountId::decode(&mut &[x as u8; 32][..]).unwrap(); - let asset_id = AssetId::Asset(x as u128); - let hb = polkadex_primitives::ingress::HandleBalance { - main_account, - asset_id, - free: (x * 100) as u128, - reserve: (x * 10) as u128 - }; - let mut change_in_balances: BoundedVec< - polkadex_primitives::ingress::HandleBalance, - polkadex_primitives::ingress::HandleBalanceLimit, - > = BoundedVec::default(); - change_in_balances.try_push(hb).unwrap(); - let call = Call::::set_balances { change_in_balances }; - }: { call.dispatch_bypass_filter(origin)? } - verify { - let current_blk = frame_system::Pallet::::current_block_number(); - assert_eq!(>::get(current_blk).len(), 1); - } - claim_withdraw { let x in 1 .. 255; // should not overflow u8 let governance = T::GovernanceOrigin::try_successful_origin().unwrap(); @@ -420,6 +391,8 @@ fn get_dummy_snapshot() -> SnapshotSummary { state_change_id: 10, last_processed_blk: 11, withdrawals, + egress_messages: Vec::new(), + trader_metrics: Default::default(), } } diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index fadcb86c5..bff4cd4f3 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -59,8 +59,7 @@ use orderbook_primitives::{ }; pub use pallet::*; use polkadex_primitives::ocex::TradingPairConfig; -#[cfg(feature = "runtime-benchmarks")] -use sp_runtime::traits::One; + use sp_std::vec::Vec; #[cfg(test)] @@ -175,6 +174,20 @@ pub mod pallet { Vec::AccountId>>, >; + pub type BatchProcessResult = ( + Vec::AccountId>>, + Vec::AccountId>>, + Option< + BTreeMap< + TradingPair, + ( + BTreeMap<::AccountId, (Decimal, Decimal)>, + (Decimal, Decimal), + ), + >, + >, + ); + pub struct AllowlistedTokenLimit; impl Get for AllowlistedTokenLimit { diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index fbe173959..b61adb47e 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -26,7 +26,7 @@ use crate::{ settlement::{add_balance, get_balance, sub_balance}, snapshot::StateInfo, storage::{store_trie_root, OffchainState}, - Config, Pallet, SnapshotNonce, Snapshots, + BatchProcessResult, Config, Pallet, SnapshotNonce, Snapshots, }; use core::ops::Div; use frame_system::pallet_prelude::BlockNumberFor; @@ -66,6 +66,11 @@ pub const LAST_PROCESSED_SNAPSHOT: [u8; 26] = *b"offchain-ocex::snapshot_id"; pub const AGGREGATOR: &str = "https://ob.aggregator.polkadex.trade"; pub const CHECKPOINT_BLOCKS: u64 = 1260; +type TraderMetricsType = BTreeMap< + TradingPair, + (BTreeMap<::AccountId, (Decimal, Decimal)>, (Decimal, Decimal)), +>; + impl Pallet { /// Runs the offchain worker computes the next batch of user actions and /// submits snapshot summary to aggregator endpoint @@ -671,19 +676,7 @@ impl Pallet { state: &mut OffchainState, batch: &UserActionBatch, state_info: &mut StateInfo, - ) -> Result< - ( - Vec>, - Vec>, - Option< - BTreeMap< - TradingPair, - (BTreeMap, (Decimal, Decimal)), - >, - >, - ), - &'static str, - > { + ) -> Result, &'static str> { if state_info.stid >= batch.stid { return Err("Invalid stid") } @@ -746,12 +739,7 @@ impl Pallet { pub fn compute_trader_metrics( state: &mut OffchainState, - ) -> Result< - Option< - BTreeMap, (Decimal, Decimal))>, - >, - &'static str, - > { + ) -> Result>, &'static str> { // Check if epoch has ended and score is computed if yes, then continue if let Some(epoch) = >::get() { let config = diff --git a/runtimes/mainnet/Cargo.toml b/runtimes/mainnet/Cargo.toml index 1c4de1dd0..a5d2d133b 100644 --- a/runtimes/mainnet/Cargo.toml +++ b/runtimes/mainnet/Cargo.toml @@ -71,7 +71,7 @@ sp-transaction-pool = { default-features = false, workspace = true } sp-version = { default-features = false, workspace = true } sp-io = { workspace = true, default-features = false } sp-statement-store = { workspace = true, default-features = false } - +sp-storage = {workspace = true, default-features = false, optional = true} #added sp-authority-discovery = { default-features = false, workspace = true } sp-block-builder = { default-features = false, workspace = true } @@ -198,6 +198,7 @@ std = [ "pallet-asset-tx-payment/std", "pallet-statement/std", "sp-statement-store/std", + "sp-storage?/std" ] runtime-benchmarks = [ #theirs @@ -209,12 +210,14 @@ runtime-benchmarks = [ "hex-literal", "pallet-assets/runtime-benchmarks", "pallet-collective/runtime-benchmarks", + "sp-storage", #our "pallet-ocex-lmp/runtime-benchmarks", "pdex-migration/runtime-benchmarks", "pallet-rewards/runtime-benchmarks", "thea/runtime-benchmarks", "thea-executor/runtime-benchmarks", + "pallet-lmp/runtime-benchmarks", "thea-message-handler/runtime-benchmarks", "pallet-asset-conversion/runtime-benchmarks", "pallet-asset-tx-payment/runtime-benchmarks", @@ -258,6 +261,7 @@ try-runtime = [ "pallet-child-bounties/try-runtime", "pallet-assets/try-runtime", "pallet-ocex-lmp/try-runtime", + "pallet-lmp/try-runtime", "pallet-collective/try-runtime", "thea/try-runtime", "pallet-rewards/try-runtime", diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index c9623d403..44d40473a 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -1492,14 +1492,13 @@ construct_runtime!( OrderbookCommittee: pallet_collective:: = 36, Thea: thea::pallet = 39, Rewards: pallet_rewards = 40, - Liquidity: liquidity = 41, TheaExecutor: thea_executor::pallet = 44, TheaMH: thea_message_handler::pallet = 45, AssetConversion: pallet_asset_conversion = 46, AssetConversionTxPayment: pallet_asset_conversion_tx_payment = 47, Statement: pallet_statement = 48, AssetTxPayment: pallet_asset_tx_payment = 49, - CrowdSourceLMP: pallet_lmp = 50, + CrowdSourceLMP: pallet_lmp::pallet = 50, } ); @@ -1891,7 +1890,6 @@ impl_runtime_apis! { list_benchmark!(list, extra, pallet_ocex_lmp, OCEX); list_benchmark!(list, extra, pdex_migration, PDEXMigration); list_benchmark!(list, extra, pallet_rewards, Rewards); - list_benchmark!(list, extra, liquidity, Liquidity); list_benchmark!(list, extra, thea_executor, TheaExecutor); list_benchmark!(list, extra, thea, Thea); list_benchmark!(list, extra, thea_message_handler, TheaMH); @@ -1928,7 +1926,6 @@ impl_runtime_apis! { add_benchmark!(params, batches, pallet_ocex_lmp, OCEX); add_benchmark!(params, batches, pdex_migration, PDEXMigration); add_benchmark!(params, batches, pallet_rewards, Rewards); - add_benchmark!(params, batches, liquidity, Liquidity); add_benchmark!(params, batches, thea_executor, TheaExecutor); //TheaExecutor: thea_executor add_benchmark!(params, batches, thea, Thea); add_benchmark!(params, batches, thea_message_handler, TheaMH);