Skip to content

Commit

Permalink
crago fmt, clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
Gauthamastro committed Jan 25, 2024
1 parent 8d7a959 commit 0a89e49
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 84 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions pallets/liquidity-mining/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
40 changes: 18 additions & 22 deletions pallets/liquidity-mining/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ pub mod pallet {
MMClaimFlag,
);

type LMPScoreSheet<T> = BTreeMap<
(TradingPair, <T as frame_system::Config>::AccountId, u16),
(BTreeMap<<T as frame_system::Config>::AccountId, (BalanceOf<T>, bool)>, BalanceOf<T>),
>;

#[pallet::config]
pub trait Config: frame_system::Config + SendTransactionTypes<Call<Self>> {
type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;
Expand Down Expand Up @@ -279,12 +284,9 @@ pub mod pallet {
if <SnapshotFlag<T>>::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.
Expand Down Expand Up @@ -315,7 +317,7 @@ pub mod pallet {
.propagate(true)
.build()
} else {
return InvalidTransaction::Call.into()
InvalidTransaction::Call.into()
}
}
}
Expand Down Expand Up @@ -471,10 +473,10 @@ pub mod pallet {
let config = <Pools<T>>::get(market, market_maker).ok_or(Error::<T>::UnknownPool)?;
ensure!(<SnapshotFlag<T>>::get().is_none(), Error::<T>::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::<T>::TotalShareIssuanceIsZero);
let burned_amt = T::OtherAssets::burn_from(
config.share_id.into(),
config.share_id,
&lp,
shares,
Precision::Exact,
Expand Down Expand Up @@ -617,10 +619,7 @@ pub mod pallet {
#[transactional]
pub fn submit_scores_of_lps(
origin: OriginFor<T>,
results: BTreeMap<
(TradingPair, T::AccountId, u16),
(BTreeMap<T::AccountId, (BalanceOf<T>, bool)>, BalanceOf<T>),
>,
results: LMPScoreSheet<T>,
) -> DispatchResult {
ensure_none(origin)?;

Expand Down Expand Up @@ -655,13 +654,13 @@ pub mod pallet {
let pool_config =
<Pools<T>>::get(market, &market_maker).ok_or(Error::<T>::UnknownPool)?;
let mut requests = <WithdrawalRequests<T>>::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();
Expand Down Expand Up @@ -749,10 +748,7 @@ pub mod pallet {
};
// TODO: Only compute the result every five blocks

let mut results: BTreeMap<
(TradingPair, T::AccountId, u16),
(BTreeMap<T::AccountId, (BalanceOf<T>, bool)>, BalanceOf<T>),
> = BTreeMap::new();
let mut results: LMPScoreSheet<T> = BTreeMap::new();
// Loop over all pools and lps and calculate score of all LPs
for (market, mm, config) in <Pools<T>>::iter() {
let mut scores_map = BTreeMap::new();
Expand Down Expand Up @@ -825,7 +821,7 @@ pub mod pallet {
},
AssetId::Asset(id) => {
T::OtherAssets::transfer(
id.into(),
id,
payer,
payee,
amount.unique_saturated_into(),
Expand Down
8 changes: 4 additions & 4 deletions pallets/ocex/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub trait PolkadexOcexRpcApi<BlockHash, AccountId, Hash> {
async fn account_scores_by_market(
&self,
at: Option<BlockHash>,
epoch: u32,
epoch: u16,
market: TradingPair,
sorted_by_mm_score: bool,
limit: u16,
Expand All @@ -77,7 +77,7 @@ pub trait PolkadexOcexRpcApi<BlockHash, AccountId, Hash> {
fn eligible_rewards(
&self,
at: Option<BlockHash>,
epoch: u32,
epoch: u16,
market: TradingPair,
main: AccountId,
) -> RpcResult<(String, String, bool)>;
Expand Down Expand Up @@ -228,7 +228,7 @@ where
async fn account_scores_by_market(
&self,
at: Option<<Block as BlockT>::Hash>,
epoch: u32,
epoch: u16,
market: TradingPair,
sorted_by_mm_score: bool,
limit: u16,
Expand All @@ -249,7 +249,7 @@ where
fn eligible_rewards(
&self,
at: Option<<Block as BlockT>::Hash>,
epoch: u32,
epoch: u16,
market: TradingPair,
main: AccountId,
) -> RpcResult<(String, String, bool)> {
Expand Down
35 changes: 4 additions & 31 deletions pallets/ocex/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,15 @@ 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;
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<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
Expand Down Expand Up @@ -299,29 +293,6 @@ benchmarks! {
assert_eq!(<ExchangeState<T>>::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<T::AccountId>,
polkadex_primitives::ingress::HandleBalanceLimit,
> = BoundedVec::default();
change_in_balances.try_push(hb).unwrap();
let call = Call::<T>::set_balances { change_in_balances };
}: { call.dispatch_bypass_filter(origin)? }
verify {
let current_blk = frame_system::Pallet::<T>::current_block_number();
assert_eq!(<IngressMessages<T>>::get(current_blk).len(), 1);
}

claim_withdraw {
let x in 1 .. 255; // should not overflow u8
let governance = T::GovernanceOrigin::try_successful_origin().unwrap();
Expand Down Expand Up @@ -420,6 +391,8 @@ fn get_dummy_snapshot<T: Config>() -> SnapshotSummary<T::AccountId> {
state_change_id: 10,
last_processed_blk: 11,
withdrawals,
egress_messages: Vec::new(),
trader_metrics: Default::default(),
}
}

Expand Down
17 changes: 15 additions & 2 deletions pallets/ocex/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -175,6 +174,20 @@ pub mod pallet {
Vec<Withdrawal<<T as frame_system::Config>::AccountId>>,
>;

pub type BatchProcessResult<T> = (
Vec<Withdrawal<<T as frame_system::Config>::AccountId>>,
Vec<EgressMessages<<T as frame_system::Config>::AccountId>>,
Option<
BTreeMap<
TradingPair,
(
BTreeMap<<T as frame_system::Config>::AccountId, (Decimal, Decimal)>,
(Decimal, Decimal),
),
>,
>,
);

pub struct AllowlistedTokenLimit;

impl Get<u32> for AllowlistedTokenLimit {
Expand Down
28 changes: 8 additions & 20 deletions pallets/ocex/src/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<T> = BTreeMap<
TradingPair,
(BTreeMap<<T as frame_system::Config>::AccountId, (Decimal, Decimal)>, (Decimal, Decimal)),
>;

impl<T: Config> Pallet<T> {
/// Runs the offchain worker computes the next batch of user actions and
/// submits snapshot summary to aggregator endpoint
Expand Down Expand Up @@ -671,19 +676,7 @@ impl<T: Config> Pallet<T> {
state: &mut OffchainState,
batch: &UserActionBatch<T::AccountId>,
state_info: &mut StateInfo,
) -> Result<
(
Vec<Withdrawal<T::AccountId>>,
Vec<EgressMessages<T::AccountId>>,
Option<
BTreeMap<
TradingPair,
(BTreeMap<T::AccountId, (Decimal, Decimal)>, (Decimal, Decimal)),
>,
>,
),
&'static str,
> {
) -> Result<BatchProcessResult<T>, &'static str> {
if state_info.stid >= batch.stid {
return Err("Invalid stid")
}
Expand Down Expand Up @@ -746,12 +739,7 @@ impl<T: Config> Pallet<T> {

pub fn compute_trader_metrics(
state: &mut OffchainState,
) -> Result<
Option<
BTreeMap<TradingPair, (BTreeMap<T::AccountId, (Decimal, Decimal)>, (Decimal, Decimal))>,
>,
&'static str,
> {
) -> Result<Option<TraderMetricsType<T>>, &'static str> {
// Check if epoch has ended and score is computed if yes, then continue
if let Some(epoch) = <FinalizeLMPScore<T>>::get() {
let config =
Expand Down
6 changes: 5 additions & 1 deletion runtimes/mainnet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -198,6 +198,7 @@ std = [
"pallet-asset-tx-payment/std",
"pallet-statement/std",
"sp-statement-store/std",
"sp-storage?/std"
]
runtime-benchmarks = [
#theirs
Expand All @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
5 changes: 1 addition & 4 deletions runtimes/mainnet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1492,14 +1492,13 @@ construct_runtime!(
OrderbookCommittee: pallet_collective::<Instance3> = 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,
}
);

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 0a89e49

Please sign in to comment.