Skip to content

Commit

Permalink
v6.0.1 (#932)
Browse files Browse the repository at this point in the history
## Describe your changes

1. Add Saturating sub for close auction calculations
2. Add more events in Thea executor
3. Fixed fetch_checkpoint API
4. Removed typos

## Checklist before requesting a review
- [x] I have performed a self-review of my code.
- [ ] If it is a core feature, I have added thorough tests.
- [x] I removed all Clippy and Formatting Warnings. 
- [x] I added required Copyrights.
  • Loading branch information
Gauthamastro authored Mar 27, 2024
2 parents 626cbfd + 3d7ed6e commit 0ba43f1
Show file tree
Hide file tree
Showing 18 changed files with 332 additions and 115 deletions.
2 changes: 1 addition & 1 deletion nodes/mainnet/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 0 additions & 1 deletion nodes/mainnet/src/node_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,6 @@ where
backend
.offchain_storage()
.ok_or("Backend doesn't provide an offchain storage")?,
deny_unsafe,
)
.into_rpc(),
)?;
Expand Down
13 changes: 2 additions & 11 deletions pallets/ocex/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -141,21 +140,15 @@ pub struct PolkadexOcexRpc<Client, Block, T: OffchainStorage + 'static> {

/// Offchain storage
offchain_db: OffchainDb<T>,
deny_unsafe: DenyUnsafe,

/// A marker for the `Block` type parameter, used to ensure the struct
/// is covariant with respect to the block type.
_marker: std::marker::PhantomData<Block>,
}

impl<Client, Block, T: OffchainStorage> PolkadexOcexRpc<Client, Block, T> {
pub fn new(client: Arc<Client>, storage: T, deny_unsafe: DenyUnsafe) -> Self {
Self {
client,
offchain_db: OffchainDb::new(storage),
deny_unsafe,
_marker: Default::default(),
}
pub fn new(client: Arc<Client>, storage: T) -> Self {
Self { client, offchain_db: OffchainDb::new(storage), _marker: Default::default() }
}
}

Expand Down Expand Up @@ -218,7 +211,6 @@ where
&self,
at: Option<<Block as BlockT>::Hash>,
) -> RpcResult<String> {
self.deny_unsafe.check_if_safe()?;
let mut api = self.client.runtime_api();
let at = match at {
Some(at) => at,
Expand Down Expand Up @@ -250,7 +242,6 @@ where
&self,
at: Option<<Block as BlockT>::Hash>,
) -> RpcResult<ObCheckpoint> {
//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,
Expand Down
94 changes: 85 additions & 9 deletions pallets/ocex/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 - 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(),
Expand Down Expand Up @@ -1888,32 +1889,106 @@ pub mod pallet {
/// Fetch checkpoint for recovery
pub fn fetch_checkpoint() -> Result<ObCheckpointRaw, DispatchError> {
log::debug!(target:"ocex", "fetch_checkpoint called");
let account_id =
let mut account_ids =
<Accounts<T>>::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<AccountAsset, Decimal> = 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 = <TradingPairs<T>>::iter()
.map(|(base, quote, _)| (base, quote))
.collect::<Vec<(AssetId, AssetId)>>();

let current_epoch = <LMPEpoch<T>>::get();

for epoch in 0..=current_epoch {
for (base, quote) in &registered_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_map = crate::lmp::get_q_score_and_uptime_for_checkpoint(
&mut state, epoch, &pair, &main,
)?;

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,
)?;

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,
)?;

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,
)?;

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)?;
if !total_maker_volume.is_zero() {
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(
Ok(ObCheckpointRaw {
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,
})
}

/// Fetches balance of given `AssetId` for given `AccountId` from offchain storage
Expand Down Expand Up @@ -2118,11 +2193,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,
)?;

Expand All @@ -2139,7 +2215,7 @@ pub mod pallet {
Self::deposit_event(Event::<T>::AuctionClosed {
bidder,
burned: Compact::from(amount_to_be_burnt),
paid_to_operator: Compact::from(trasnferable_amount),
paid_to_operator: Compact::from(transferable_amount),
})
}
Ok(())
Expand Down
Loading

0 comments on commit 0ba43f1

Please sign in to comment.