From 4bdbcd033f1eb0e5a33ea7e695ed11f2bc3e7787 Mon Sep 17 00:00:00 2001 From: zktony Date: Wed, 27 Mar 2024 15:36:19 +0530 Subject: [PATCH 01/54] Updated withdraw --- pallets/thea-executor/src/lib.rs | 42 ++++- pallets/xcm-helper/src/lib.rs | 294 +++++++++++++++++++++++-------- primitives/thea/src/types.rs | 34 ++++ 3 files changed, 296 insertions(+), 74 deletions(-) diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index 9dca60a41..b61831ad2 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -65,6 +65,7 @@ pub mod pallet { use sp_core::{H160, H256}; use sp_runtime::{traits::AccountIdConversion, Saturating}; use sp_std::vec::Vec; + use thea_primitives::types::NewWithdraw; use thea_primitives::{ types::{AssetMetadata, Deposit, Withdraw}, Network, TheaBenchmarkHelper, TheaIncomingExecutor, TheaOutgoingExecutor, NATIVE_NETWORK, @@ -141,7 +142,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn pending_withdrawals)] pub(super) type PendingWithdrawals = - StorageMap<_, Blake2_128Concat, Network, Vec, ValueQuery>; + StorageMap<_, Blake2_128Concat, Network, Vec, ValueQuery>; /// Withdrawal Fees for each network #[pallet::storage] @@ -158,7 +159,7 @@ pub mod pallet { BlockNumberFor, Blake2_128Concat, Network, - Vec, + Vec, ValueQuery, >; @@ -190,7 +191,7 @@ pub mod pallet { /// Withdrawal Ready (Network id ) WithdrawalReady(Network), /// Withdrawal Failed ( Network ,Vec) - WithdrawalFailed(Network, Vec), + WithdrawalFailed(Network, Vec), /// Thea Public Key Updated ( network, new session id ) TheaKeyUpdated(Network, u32), /// Withdrawal Fee Set (NetworkId, Amount) @@ -220,6 +221,8 @@ pub mod pallet { WithdrawalFeeConfigNotFound, /// Asset Not Registered AssetNotRegistered, + /// Fee Asset Not Registered + FeeAssetNotRegistered, /// Amount cannot be Zero AmountCannotBeZero, /// Failed To Handle Parachain Deposit @@ -289,6 +292,8 @@ pub mod pallet { asset_id, amount, beneficiary, + None, + None, pay_for_remaining, network, pay_with_tokens, @@ -323,6 +328,8 @@ pub mod pallet { asset_id: u128, amount: u128, beneficiary: sp_std::boxed::Box, + fee_asset_id: Option, + fee_amount: Option, pay_for_remaining: bool, pay_with_tokens: bool, ) -> DispatchResult { @@ -333,6 +340,8 @@ pub mod pallet { asset_id, amount, beneficiary.encode(), + fee_asset_id, + fee_amount, pay_for_remaining, network, pay_with_tokens, @@ -410,6 +419,8 @@ pub mod pallet { asset_id, amount, beneficiary.encode(), + None, + None, pay_for_remaining, network, pay_with_tokens, @@ -480,6 +491,8 @@ pub mod pallet { asset_id: u128, mut amount: u128, beneficiary: Vec, + fee_asset_id: Option, + fee_amount: Option, pay_for_remaining: bool, network: Network, pay_with_tokens: bool, @@ -488,6 +501,10 @@ pub mod pallet { ensure!(network != 0, Error::::WrongNetwork); let mut pending_withdrawals = >::get(network); let metadata = >::get(asset_id).ok_or(Error::::AssetNotRegistered)?; + if let Some(fee_asset_id) = fee_asset_id { + let metadata = >::get(fee_asset_id) + .ok_or(Error::::FeeAssetNotRegistered)?; + } ensure!( pending_withdrawals.len() < T::WithdrawalSize::get() as usize, Error::::WithdrawalNotAllowed @@ -535,11 +552,22 @@ pub mod pallet { // Withdraw assets Self::resolver_withdraw(asset_id.into(), amount, &user, Self::thea_account())?; - let mut withdraw = Withdraw { + if let (Some(fee_asset_id), Some(fee_amount)) = (fee_asset_id, fee_amount) { + Self::resolver_withdraw( + fee_asset_id.into(), + fee_amount, + &user, + Self::thea_account(), + )?; + } + + let mut withdraw = NewWithdraw { id: Self::new_random_id(), asset_id, amount, destination: beneficiary.clone(), + fee_asset_id, + fee_amount, is_blocked: false, extra: Vec::new(), }; @@ -556,6 +584,12 @@ pub mod pallet { // Convert back to origin decimals withdraw.amount = metadata.convert_from_native_decimals(amount); + if let (Some(fee_asset_id), Some(fee_amount)) = (fee_asset_id, fee_amount) { + let metadata = >::get(fee_asset_id) + .ok_or(Error::::FeeAssetNotRegistered)?; + withdraw.fee_amount = Some(metadata.convert_from_native_decimals(fee_amount)); + } + pending_withdrawals.push(withdraw); if (pending_withdrawals.len() >= T::WithdrawalSize::get() as usize) || pay_for_remaining diff --git a/pallets/xcm-helper/src/lib.rs b/pallets/xcm-helper/src/lib.rs index c1b54d888..371ca0ad5 100644 --- a/pallets/xcm-helper/src/lib.rs +++ b/pallets/xcm-helper/src/lib.rs @@ -138,7 +138,7 @@ pub mod pallet { use crate::MAXIMUM_BLOCK_WEIGHT; use sp_std::{boxed::Box, vec, vec::Vec}; use thea_primitives::{ - types::{Deposit, Withdraw}, + types::{Deposit, NewWithdraw, Withdraw}, Network, TheaIncomingExecutor, TheaOutgoingExecutor, }; use xcm::{ @@ -225,12 +225,24 @@ pub mod pallet { pub(super) type PendingWithdrawals = StorageMap<_, Blake2_128Concat, BlockNumberFor, Vec, ValueQuery>; + /// Pending Withdrawals + #[pallet::storage] + #[pallet::getter(fn get_new_pending_withdrawals)] + pub(super) type NewPendingWithdrawals = + StorageMap<_, Blake2_128Concat, BlockNumberFor, Vec, ValueQuery>; + /// Failed Withdrawals #[pallet::storage] #[pallet::getter(fn get_failed_withdrawals)] pub(super) type FailedWithdrawals = StorageMap<_, Blake2_128Concat, BlockNumberFor, Vec, ValueQuery>; + /// Failed Withdrawals + #[pallet::storage] + #[pallet::getter(fn get_new_failed_withdrawals)] + pub(super) type NewFailedWithdrawals = + StorageMap<_, Blake2_128Concat, BlockNumberFor, Vec, ValueQuery>; + /// Asset mapping from u128 asset to multi asset. #[pallet::storage] #[pallet::getter(fn assets_mapping)] @@ -309,74 +321,9 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { fn on_initialize(n: BlockNumberFor) -> Weight { - let mut failed_withdrawal: Vec = Vec::default(); - >::mutate(n, |withdrawals| { - while let Some(withdrawal) = withdrawals.pop() { - if !withdrawal.is_blocked { - let destination = match VersionedMultiLocation::decode( - &mut &withdrawal.destination[..], - ) { - Ok(dest) => dest, - Err(_) => { - failed_withdrawal.push(withdrawal); - log::error!(target:"xcm-helper","Withdrawal failed: Not able to decode destination"); - continue; - }, - }; - if !Self::is_polkadex_parachain_destination(&destination) { - if let Some(asset) = Self::assets_mapping(withdrawal.asset_id) { - let multi_asset = MultiAsset { - id: asset, - fun: Fungibility::Fungible(withdrawal.amount), - }; - let pallet_account: T::AccountId = - T::AssetHandlerPalletId::get().into_account_truncating(); - // Mint - if Self::resolver_deposit( - withdrawal.asset_id.into(), - withdrawal.amount, - &pallet_account, - pallet_account.clone(), - 1u128, - pallet_account.clone(), - ) - .is_err() - { - failed_withdrawal.push(withdrawal.clone()); - log::error!(target:"xcm-helper","Withdrawal failed: Not able to mint token"); - }; - if orml_xtokens::module::Pallet::::transfer_multiassets( - RawOrigin::Signed( - T::AssetHandlerPalletId::get().into_account_truncating(), - ) - .into(), - Box::new(multi_asset.into()), - 0, - Box::new(destination.clone()), - cumulus_primitives_core::WeightLimit::Unlimited, - ) - .is_err() - { - failed_withdrawal.push(withdrawal.clone()); - log::error!(target:"xcm-helper","Withdrawal failed: Not able to make xcm calls"); - } - } else { - failed_withdrawal.push(withdrawal) - } - } else if Self::handle_deposit(withdrawal.clone(), destination).is_err() { - failed_withdrawal.push(withdrawal); - log::error!(target:"xcm-helper","Withdrawal failed: Not able to handle dest"); - } - } else { - failed_withdrawal.push(withdrawal); - log::error!(target:"xcm-helper","Withdrawal failed: Withdrawal is blocked"); - } - } - }); + Self::handle_old_pending_withdrawals(n); + Self::handle_new_pending_withdrawals(n); // Only update the storage if vector is not empty - if !failed_withdrawal.is_empty() { - >::insert(n, failed_withdrawal); - } // TODO: We are currently over estimating the weight here to 1/4th of total block time // Need a better way to estimate this hook MAXIMUM_BLOCK_WEIGHT.saturating_div(4) @@ -648,6 +595,213 @@ pub mod pallet { pub fn insert_pending_withdrawal(block_no: BlockNumberFor, withdrawal: Withdraw) { >::insert(block_no, vec![withdrawal]); } + + pub fn handle_old_pending_withdrawals(n: BlockNumberFor) { + let mut failed_withdrawal: Vec = Vec::default(); + >::mutate(n, |withdrawals| { + while let Some(withdrawal) = withdrawals.pop() { + if !withdrawal.is_blocked { + let destination = match VersionedMultiLocation::decode( + &mut &withdrawal.destination[..], + ) { + Ok(dest) => dest, + Err(_) => { + failed_withdrawal.push(withdrawal); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to decode destination"); + continue; + }, + }; + if !Self::is_polkadex_parachain_destination(&destination) { + if let Some(asset) = Self::assets_mapping(withdrawal.asset_id) { + let multi_asset = MultiAsset { + id: asset, + fun: Fungibility::Fungible(withdrawal.amount), + }; + let pallet_account: T::AccountId = + T::AssetHandlerPalletId::get().into_account_truncating(); + // Mint + if Self::resolver_deposit( + withdrawal.asset_id.into(), + withdrawal.amount, + &pallet_account, + pallet_account.clone(), + 1u128, + pallet_account.clone(), + ) + .is_err() + { + failed_withdrawal.push(withdrawal.clone()); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to mint token"); + }; + if orml_xtokens::module::Pallet::::transfer_multiassets( + RawOrigin::Signed( + T::AssetHandlerPalletId::get().into_account_truncating(), + ) + .into(), + Box::new(multi_asset.into()), + 0, + Box::new(destination.clone()), + cumulus_primitives_core::WeightLimit::Unlimited, + ) + .is_err() + { + failed_withdrawal.push(withdrawal.clone()); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to make xcm calls"); + } + } else { + failed_withdrawal.push(withdrawal) + } + } else if Self::handle_deposit(withdrawal.clone(), destination).is_err() { + failed_withdrawal.push(withdrawal); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to handle dest"); + } + } else { + failed_withdrawal.push(withdrawal); + log::error!(target:"xcm-helper","Withdrawal failed: Withdrawal is blocked"); + } + } + }); + if !failed_withdrawal.is_empty() { + >::insert(n, failed_withdrawal); + } + } + + pub fn handle_new_pending_withdrawals(n: BlockNumberFor) { + let mut failed_withdrawal: Vec = Vec::default(); + >::mutate(n, |withdrawals| { + while let Some(withdrawal) = withdrawals.pop() { + if !withdrawal.is_blocked { + let destination = match VersionedMultiLocation::decode( + &mut &withdrawal.destination[..], + ) { + Ok(dest) => dest, + Err(_) => { + failed_withdrawal.push(withdrawal); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to decode destination"); + continue; + }, + }; + if !Self::is_polkadex_parachain_destination(&destination) { + if let (Some(fee_asset_id), Some(fee_amount)) = + (withdrawal.fee_asset_id, withdrawal.fee_amount) + { + if let (Some(asset), Some(fee_asset)) = ( + Self::assets_mapping(withdrawal.asset_id), + Self::assets_mapping(fee_asset_id), + ) { + let multi_asset = MultiAsset { + id: asset, + fun: Fungibility::Fungible(withdrawal.amount), + }; + let fee_multi_asset = MultiAsset { + id: fee_asset, + fun: Fungibility::Fungible(fee_amount), + }; + let pallet_account: T::AccountId = + T::AssetHandlerPalletId::get().into_account_truncating(); + if Self::resolver_deposit( + withdrawal.asset_id.into(), + withdrawal.amount, + &pallet_account, + pallet_account.clone(), + 1u128, + pallet_account.clone(), + ) + .is_err() + { + failed_withdrawal.push(withdrawal.clone()); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to mint token"); + }; + // Deposit Fee + if Self::resolver_deposit( + fee_asset_id.into(), + fee_amount, + &pallet_account, + pallet_account.clone(), + 1u128, + pallet_account.clone(), + ) + .is_err() + { + failed_withdrawal.push(withdrawal.clone()); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to mint token"); + }; + if orml_xtokens::module::Pallet::::transfer_multiassets( + RawOrigin::Signed( + T::AssetHandlerPalletId::get() + .into_account_truncating(), + ) + .into(), + Box::new(vec![multi_asset, fee_multi_asset].into()), + 1, + Box::new(destination.clone()), + cumulus_primitives_core::WeightLimit::Unlimited, + ) + .is_err() + { + failed_withdrawal.push(withdrawal.clone()); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to make xcm calls"); + } + } + } else { + if let Some(asset) = Self::assets_mapping(withdrawal.asset_id) { + let multi_asset = MultiAsset { + id: asset, + fun: Fungibility::Fungible(withdrawal.amount), + }; + let pallet_account: T::AccountId = + T::AssetHandlerPalletId::get().into_account_truncating(); + // Mint + if Self::resolver_deposit( + withdrawal.asset_id.into(), + withdrawal.amount, + &pallet_account, + pallet_account.clone(), + 1u128, + pallet_account.clone(), + ) + .is_err() + { + failed_withdrawal.push(withdrawal.clone()); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to mint token"); + }; + if orml_xtokens::module::Pallet::::transfer_multiassets( + RawOrigin::Signed( + T::AssetHandlerPalletId::get() + .into_account_truncating(), + ) + .into(), + Box::new(multi_asset.into()), + 0, + Box::new(destination.clone()), + cumulus_primitives_core::WeightLimit::Unlimited, + ) + .is_err() + { + failed_withdrawal.push(withdrawal.clone()); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to make xcm calls"); + } + } else { + failed_withdrawal.push(withdrawal) + } + } + } else if Self::handle_deposit(withdrawal.clone().into(), destination) + .is_err() + { + failed_withdrawal.push(withdrawal); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to handle dest"); + } + } else { + failed_withdrawal.push(withdrawal); + log::error!(target:"xcm-helper","Withdrawal failed: Withdrawal is blocked"); + } + } + }); + // Only update the storage if vector is not empty + if !failed_withdrawal.is_empty() { + >::insert(n, failed_withdrawal); + } + } } impl AssetIdConverter for Pallet { @@ -669,7 +823,7 @@ pub mod pallet { impl TheaIncomingExecutor for Pallet { fn execute_deposits(_: Network, deposits: Vec) { - let deposits = Vec::::decode(&mut &deposits[..]).unwrap_or_default(); + let deposits = Vec::::decode(&mut &deposits[..]).unwrap_or_default(); for deposit in deposits { // Calculate the withdrawal execution delay let withdrawal_execution_block: BlockNumberFor = @@ -680,7 +834,7 @@ pub mod pallet { ) .into(); // Queue the withdrawal for execution - >::mutate( + >::mutate( withdrawal_execution_block, |pending_withdrawals| { pending_withdrawals.push(deposit); diff --git a/primitives/thea/src/types.rs b/primitives/thea/src/types.rs index 1feb9dff8..e1f7208c4 100644 --- a/primitives/thea/src/types.rs +++ b/primitives/thea/src/types.rs @@ -269,6 +269,40 @@ pub struct Withdraw { pub extra: Vec, } +impl From for Withdraw { + fn from(value: NewWithdraw) -> Self { + Self { + id: value.id, + asset_id: value.asset_id, + amount: value.amount, + destination: value.destination, + is_blocked: value.is_blocked, + extra: value.extra, + } + } +} + +#[derive(Encode, Decode, Clone, TypeInfo, PartialEq, Debug)] +pub struct NewWithdraw { + /// Identifier of the withdrawal. + pub id: Vec, + // Unique identifier + /// Asset identifier. + pub asset_id: u128, + /// Amount of the withdrawal. + pub amount: u128, + /// Receiver of the withdrawal. + pub destination: Vec, + /// Fee Asset Id + pub fee_asset_id: Option, + /// Fee Amount + pub fee_amount: Option, + /// Defines if withdraw operation is blocked. + pub is_blocked: bool, + /// Extra data. + pub extra: Vec, +} + /// Metadata of asset's decimals #[derive(Encode, Decode, Clone, TypeInfo, PartialEq, Debug, Copy)] pub struct AssetMetadata { From 0a204393280bd70b6a21ad7a02838d72263cd15f Mon Sep 17 00:00:00 2001 From: zktony Date: Wed, 27 Mar 2024 16:44:23 +0530 Subject: [PATCH 02/54] Updated 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 dcaa09cf0..04669a6a6 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: 342, + spec_version: 343, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 91b6f8c842630186d1b8d83307bf3d9e2ef6db7e Mon Sep 17 00:00:00 2001 From: zktony Date: Wed, 27 Mar 2024 16:54:21 +0530 Subject: [PATCH 03/54] Fixed formatting --- pallets/thea-executor/src/benchmarking.rs | 9 ++++++--- pallets/thea-executor/src/lib.rs | 2 +- pallets/thea-executor/src/tests.rs | 15 ++++++++++++++- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/pallets/thea-executor/src/benchmarking.rs b/pallets/thea-executor/src/benchmarking.rs index fdc67cc2a..096a09b91 100644 --- a/pallets/thea-executor/src/benchmarking.rs +++ b/pallets/thea-executor/src/benchmarking.rs @@ -30,7 +30,8 @@ use parity_scale_codec::Decode; use polkadex_primitives::UNIT_BALANCE; use sp_runtime::{traits::AccountIdConversion, SaturatedConversion}; use sp_std::{boxed::Box, collections::btree_set::BTreeSet, vec, vec::Vec}; -use thea_primitives::types::{AssetMetadata, Deposit, Withdraw}; +use thea_primitives::types::NewWithdraw; +use thea_primitives::types::{AssetMetadata, Deposit}; use xcm::VersionedMultiLocation; fn create_deposit(recipient: T::AccountId) -> Vec> { @@ -107,7 +108,7 @@ benchmarks! { >::insert(network_id, 1_000); let multilocation = MultiLocation { parents: 1, interior: Junctions::Here }; let benificary = VersionedMultiLocation::V3(multilocation); - }: _(RawOrigin::Signed(account.clone()), 100, 1_000_000_000_000, Box::new(benificary), true, false) + }: _(RawOrigin::Signed(account.clone()), 100, 1_000_000_000_000, Box::new(benificary), None, None, true, false) verify { let ready_withdrawal = >::get(>::block_number(), network_id); assert_eq!(ready_withdrawal.len(), 1); @@ -139,11 +140,13 @@ benchmarks! { let y in 1 .. 1_000; let network_len: usize = x as usize; let network_len: u8 = network_len as u8; - let withdrawal = Withdraw { + let withdrawal = NewWithdraw { id: vec![], asset_id: 100, amount: 1_000_000_000_000, destination: vec![], + fee_asset_id: None, + fee_amount: None, is_blocked: false, extra: vec![], }; diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index b61831ad2..6bd046299 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -67,7 +67,7 @@ pub mod pallet { use sp_std::vec::Vec; use thea_primitives::types::NewWithdraw; use thea_primitives::{ - types::{AssetMetadata, Deposit, Withdraw}, + types::{AssetMetadata, Deposit}, Network, TheaBenchmarkHelper, TheaIncomingExecutor, TheaOutgoingExecutor, NATIVE_NETWORK, }; use xcm::VersionedMultiLocation; diff --git a/pallets/thea-executor/src/tests.rs b/pallets/thea-executor/src/tests.rs index 047c77f81..5493c8f55 100644 --- a/pallets/thea-executor/src/tests.rs +++ b/pallets/thea-executor/src/tests.rs @@ -31,6 +31,7 @@ use sp_runtime::{ traits::{AccountIdConversion, BadOrigin}, SaturatedConversion, }; +use thea_primitives::types::NewWithdraw; use thea_primitives::types::{AssetMetadata, Deposit, Withdraw}; use xcm::{opaque::lts::Junctions, v3::MultiLocation, VersionedMultiLocation}; @@ -93,11 +94,13 @@ fn test_transfer_native_asset() { )); // Verify let pending_withdrawal = >::get(1); - let approved_withdraw = Withdraw { + let approved_withdraw = NewWithdraw { id: Vec::from([179, 96, 16, 235, 40, 92, 21, 74, 140, 214]), asset_id, amount: 10_000_000_000_000u128, destination: vec![1; 32], + fee_asset_id: None, + fee_amount: None, is_blocked: false, extra: vec![], }; @@ -208,6 +211,8 @@ fn test_parachain_withdraw_full() { u128::MAX, 1_000_000_000, beneficiary.clone(), + None, + None, false, false ), @@ -219,6 +224,8 @@ fn test_parachain_withdraw_full() { u128::MAX, 1_000_000_000, beneficiary.clone(), + None, + None, false, false ), @@ -231,6 +238,8 @@ fn test_parachain_withdraw_full() { u128::MAX, 1_000_000_000, beneficiary.clone(), + None, + None, false, false ), @@ -243,6 +252,8 @@ fn test_parachain_withdraw_full() { asset_id, 1_000_000_000, beneficiary.clone(), + None, + None, false, false ), @@ -254,6 +265,8 @@ fn test_parachain_withdraw_full() { asset_id, 1_000_000_000, beneficiary.clone(), + None, + None, false, false )); From fa14354aa4554574d25ed42c4a06f02030490600 Mon Sep 17 00:00:00 2001 From: zktony Date: Wed, 27 Mar 2024 18:36:15 +0530 Subject: [PATCH 04/54] Fixed CI --- 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 6bd046299..f7eb62944 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -502,7 +502,7 @@ pub mod pallet { let mut pending_withdrawals = >::get(network); let metadata = >::get(asset_id).ok_or(Error::::AssetNotRegistered)?; if let Some(fee_asset_id) = fee_asset_id { - let metadata = >::get(fee_asset_id) + let _metadata = >::get(fee_asset_id) .ok_or(Error::::FeeAssetNotRegistered)?; } ensure!( From 1d2cbce82ef12d61000216308b606e7ca5a47f85 Mon Sep 17 00:00:00 2001 From: zktony Date: Wed, 27 Mar 2024 19:27:51 +0530 Subject: [PATCH 05/54] Fixed ci --- pallets/thea-executor/src/lib.rs | 1 + pallets/xcm-helper/src/lib.rs | 75 +++++++++++++++----------------- 2 files changed, 37 insertions(+), 39 deletions(-) diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index f7eb62944..1222714c0 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -46,6 +46,7 @@ pub trait TheaExecutorWeightInfo { fn claim_deposit(_r: u32) -> Weight; } +#[allow(clippy::too_many_arguments)] #[frame_support::pallet] pub mod pallet { use super::*; diff --git a/pallets/xcm-helper/src/lib.rs b/pallets/xcm-helper/src/lib.rs index 371ca0ad5..75ac44201 100644 --- a/pallets/xcm-helper/src/lib.rs +++ b/pallets/xcm-helper/src/lib.rs @@ -743,47 +743,44 @@ pub mod pallet { log::error!(target:"xcm-helper","Withdrawal failed: Not able to make xcm calls"); } } - } else { - if let Some(asset) = Self::assets_mapping(withdrawal.asset_id) { - let multi_asset = MultiAsset { - id: asset, - fun: Fungibility::Fungible(withdrawal.amount), - }; - let pallet_account: T::AccountId = - T::AssetHandlerPalletId::get().into_account_truncating(); - // Mint - if Self::resolver_deposit( - withdrawal.asset_id.into(), - withdrawal.amount, - &pallet_account, - pallet_account.clone(), - 1u128, - pallet_account.clone(), - ) - .is_err() - { - failed_withdrawal.push(withdrawal.clone()); - log::error!(target:"xcm-helper","Withdrawal failed: Not able to mint token"); - }; - if orml_xtokens::module::Pallet::::transfer_multiassets( - RawOrigin::Signed( - T::AssetHandlerPalletId::get() - .into_account_truncating(), - ) - .into(), - Box::new(multi_asset.into()), - 0, - Box::new(destination.clone()), - cumulus_primitives_core::WeightLimit::Unlimited, + } else if let Some(asset) = Self::assets_mapping(withdrawal.asset_id) { + let multi_asset = MultiAsset { + id: asset, + fun: Fungibility::Fungible(withdrawal.amount), + }; + let pallet_account: T::AccountId = + T::AssetHandlerPalletId::get().into_account_truncating(); + // Mint + if Self::resolver_deposit( + withdrawal.asset_id.into(), + withdrawal.amount, + &pallet_account, + pallet_account.clone(), + 1u128, + pallet_account.clone(), + ) + .is_err() + { + failed_withdrawal.push(withdrawal.clone()); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to mint token"); + }; + if orml_xtokens::module::Pallet::::transfer_multiassets( + RawOrigin::Signed( + T::AssetHandlerPalletId::get().into_account_truncating(), ) - .is_err() - { - failed_withdrawal.push(withdrawal.clone()); - log::error!(target:"xcm-helper","Withdrawal failed: Not able to make xcm calls"); - } - } else { - failed_withdrawal.push(withdrawal) + .into(), + Box::new(multi_asset.into()), + 0, + Box::new(destination.clone()), + cumulus_primitives_core::WeightLimit::Unlimited, + ) + .is_err() + { + failed_withdrawal.push(withdrawal.clone()); + log::error!(target:"xcm-helper","Withdrawal failed: Not able to make xcm calls"); } + } else { + failed_withdrawal.push(withdrawal) } } else if Self::handle_deposit(withdrawal.clone().into(), destination) .is_err() From b641430a87b8c0c86622b89e196f3062f7054bda Mon Sep 17 00:00:00 2001 From: zktony Date: Thu, 28 Mar 2024 10:42:19 +0530 Subject: [PATCH 06/54] Fixed ci --- pallets/thea-executor/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/thea-executor/src/tests.rs b/pallets/thea-executor/src/tests.rs index 5493c8f55..2d0e26c7a 100644 --- a/pallets/thea-executor/src/tests.rs +++ b/pallets/thea-executor/src/tests.rs @@ -32,7 +32,7 @@ use sp_runtime::{ SaturatedConversion, }; use thea_primitives::types::NewWithdraw; -use thea_primitives::types::{AssetMetadata, Deposit, Withdraw}; +use thea_primitives::types::{AssetMetadata, Deposit}; use xcm::{opaque::lts::Junctions, v3::MultiLocation, VersionedMultiLocation}; fn assert_last_event(generic_event: ::RuntimeEvent) { From 1df98741112712979d94b3d3015e07c0d79d23cd Mon Sep 17 00:00:00 2001 From: Gautham Date: Wed, 10 Apr 2024 07:32:48 +0300 Subject: [PATCH 07/54] Handle withdraw precision error --- pallets/ocex/src/settlement.rs | 3 ++- runtimes/mainnet/src/lib.rs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/pallets/ocex/src/settlement.rs b/pallets/ocex/src/settlement.rs index efe6753dc..8655924c2 100644 --- a/pallets/ocex/src/settlement.rs +++ b/pallets/ocex/src/settlement.rs @@ -21,6 +21,7 @@ use crate::{storage::OffchainState, Config, Pallet}; use core::ops::Sub; use log::{error, info}; +use num_traits::FromPrimitive; use orderbook_primitives::constants::POLKADEX_MAINNET_SS58; use orderbook_primitives::ocex::TradingPairConfig; use orderbook_primitives::types::Order; @@ -117,7 +118,7 @@ pub fn sub_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() { + if !deviation.round_dp_with_strategy(8, ToZero).is_zero() && deviation > Decimal::from_f32(0.00000001).unwrap(){ log::error!(target:"ocex","Asset found but balance low for asset: {:?}, of account: {:?}",asset, account); return Err("NotEnoughBalance"); } else { diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 04669a6a6..8de966958 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: 343, + spec_version: 344, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 728fa933bfa168768edf6f6f7622b5cfeec60cc8 Mon Sep 17 00:00:00 2001 From: Gautham Date: Wed, 10 Apr 2024 08:00:10 +0300 Subject: [PATCH 08/54] Handle withdraw precision error --- pallets/ocex/src/settlement.rs | 2 +- pallets/ocex/src/validator.rs | 2 +- runtimes/mainnet/src/lib.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pallets/ocex/src/settlement.rs b/pallets/ocex/src/settlement.rs index 8655924c2..83f701537 100644 --- a/pallets/ocex/src/settlement.rs +++ b/pallets/ocex/src/settlement.rs @@ -118,7 +118,7 @@ pub fn sub_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() && deviation > Decimal::from_f32(0.00000001).unwrap(){ + if !deviation.round_dp_with_strategy(8, ToZero).is_zero() && deviation > Decimal::from_f32(0.000000011).unwrap(){ log::error!(target:"ocex","Asset found but balance low for asset: {:?}, of account: {:?}",asset, account); return Err("NotEnoughBalance"); } else { diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index f7d8b07a3..4327ecbf8 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -689,7 +689,7 @@ impl Pallet { amount, )?; let mut withdrawal = request.convert(stid).map_err(|_| "Withdrawal conversion error")?; - withdrawal.amount = actual_deducted; // The acutal deducted balance + withdrawal.amount = actual_deducted; // The actual deducted balance Ok(withdrawal) } diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 8de966958..3e763aaf1 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: 344, + spec_version: 345, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 25cf280cbc9feb38f9b726370443362d7acf2cb0 Mon Sep 17 00:00:00 2001 From: Gautham Date: Thu, 11 Apr 2024 07:21:45 +0300 Subject: [PATCH 09/54] Handle precision loss during withdrawal. --- pallets/ocex/src/settlement.rs | 19 +++++++++---------- pallets/ocex/src/tests.rs | 16 ++++++++-------- pallets/ocex/src/validator.rs | 6 ++++++ 3 files changed, 23 insertions(+), 18 deletions(-) diff --git a/pallets/ocex/src/settlement.rs b/pallets/ocex/src/settlement.rs index 83f701537..77d632b77 100644 --- a/pallets/ocex/src/settlement.rs +++ b/pallets/ocex/src/settlement.rs @@ -21,14 +21,12 @@ use crate::{storage::OffchainState, Config, Pallet}; use core::ops::Sub; use log::{error, info}; -use num_traits::FromPrimitive; 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::RoundingStrategy::ToZero; use rust_decimal::{prelude::ToPrimitive, Decimal}; use sp_core::crypto::{ByteArray, Ss58AddressFormat, Ss58Codec}; use sp_runtime::traits::AccountIdConversion; @@ -105,6 +103,7 @@ pub fn sub_balance( account: &AccountId, asset: AssetId, mut balance: Decimal, + is_withdrawal: bool ) -> 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())? { @@ -116,14 +115,14 @@ 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() && deviation > Decimal::from_f32(0.000000011).unwrap(){ + if is_withdrawal { + // 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); + log::warn!(target:"ocex","[withdrawal] balance deviation of {:?} for asset: {:?}, of account: {:?}: Withdrawing available balance",deviation,asset.to_string(), account.to_ss58check_with_version(Ss58AddressFormat::from(POLKADEX_MAINNET_SS58))); + balance = *account_balance; + }else{ 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)); @@ -171,7 +170,7 @@ impl Pallet { add_balance(state, &pot_account, maker_asset.asset, maker_fees)?; let (maker_asset, maker_debit) = trade.debit(true); - sub_balance(state, &maker_asset.main, maker_asset.asset, maker_debit)?; + sub_balance(state, &maker_asset.main, maker_asset.asset, maker_debit, false)?; maker_fees }; let taker_fees = { @@ -183,7 +182,7 @@ impl Pallet { add_balance(state, &pot_account, taker_asset.asset, taker_fees)?; let (taker_asset, taker_debit) = trade.debit(false); - sub_balance(state, &taker_asset.main, taker_asset.asset, taker_debit)?; + sub_balance(state, &taker_asset.main, taker_asset.asset, taker_debit, false)?; taker_fees }; diff --git a/pallets/ocex/src/tests.rs b/pallets/ocex/src/tests.rs index afb9c7bf9..f029535c8 100644 --- a/pallets/ocex/src/tests.rs +++ b/pallets/ocex/src/tests.rs @@ -252,7 +252,7 @@ fn test_two_assets() { let asset456 = AssetId::Asset(456); let amount456 = Decimal::from_str("10.0").unwrap(); // works - sub_balance(&mut state, &account_id, asset1, Decimal::from_str("0.01").unwrap().into()) + sub_balance(&mut state, &account_id, asset1, Decimal::from_str("0.01").unwrap().into(), false) .unwrap(); add_balance(&mut state, &coinalpha, asset123, amount123.into()).unwrap(); add_balance(&mut state, &coinalpha, asset456, amount456.into()).unwrap(); @@ -262,9 +262,9 @@ fn test_two_assets() { let mut root = crate::storage::load_trie_root(); let mut trie_state = crate::storage::State; let mut state = OffchainState::load(&mut trie_state, &mut root); - sub_balance(&mut state, &account_id, asset1, Decimal::from_str("0.01").unwrap().into()) + sub_balance(&mut state, &account_id, asset1, Decimal::from_str("0.01").unwrap().into(), false) .unwrap(); - sub_balance(&mut state, &account_id, asset1, Decimal::from_str("0.01").unwrap().into()) + sub_balance(&mut state, &account_id, asset1, Decimal::from_str("0.01").unwrap().into(), false) .unwrap(); }); } @@ -282,7 +282,7 @@ fn test_sub_balance_new_account() { let mut root = crate::storage::load_trie_root(); let mut trie_state = crate::storage::State; let mut state = OffchainState::load(&mut trie_state, &mut root); - let result = sub_balance(&mut state, &account_id, asset_id, amount.into()); + let result = sub_balance(&mut state, &account_id, asset_id, amount.into(), false); match result { Ok(_) => assert!(false), Err(e) => assert_eq!(e, "Account not found in trie"), @@ -316,7 +316,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(); + let result = sub_balance(&mut state, &account_id, asset_id, amount2.into(), false).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(); @@ -324,7 +324,7 @@ fn test_sub_balance_existing_account_with_balance() { //sub balance till 0 let amount3 = amount - amount2; - let result = sub_balance(&mut state, &account_id, asset_id, amount3.into()).unwrap(); + let result = sub_balance(&mut state, &account_id, asset_id, amount3.into(), false).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(); @@ -417,7 +417,7 @@ 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(); + sub_balance(&mut state, &account_id, AssetId::Polkadex, amount3.into(), false).unwrap(); assert_eq!(result, amount3); }); } @@ -443,7 +443,7 @@ fn test_sub_more_than_available_balance_from_existing_account_with_balance() { //sub balance let amount2 = 4000000; - let result = sub_balance(&mut state, &account_id, asset_id, amount2.into()); + let result = sub_balance(&mut state, &account_id, asset_id, amount2.into(), false); match result { Ok(_) => assert!(false), Err(e) => assert_eq!(e, "NotEnoughBalance"), diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index 4327ecbf8..3eca61a86 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -473,6 +473,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, market.quote_asset, withdrawing_quote, + false )?; // Sub Base @@ -482,6 +483,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, market.base_asset, withdrawing_base, + false )?; // Egress message is verified @@ -561,6 +563,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, market.base_asset, base_balance, + false )?; sub_balance( @@ -569,6 +572,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, market.quote_asset, quote_balance, + false )?; verified_egress_messages.push(EgressMessages::PoolForceClosed( @@ -617,6 +621,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, asset, balance, + true )?; } verified_egress_messages.push(egress_msg.clone()); @@ -687,6 +692,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, request.asset(), amount, + true )?; let mut withdrawal = request.convert(stid).map_err(|_| "Withdrawal conversion error")?; withdrawal.amount = actual_deducted; // The actual deducted balance From 1eb1bb7bb828869e5606413c0c5871a6aeb4a44e Mon Sep 17 00:00:00 2001 From: Gautham Date: Thu, 11 Apr 2024 07:28:16 +0300 Subject: [PATCH 10/54] increase 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 3e763aaf1..b434e3072 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: 345, + spec_version: 346, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 99b34f0cd0c2cb28f2dde447856da558c3d6ea71 Mon Sep 17 00:00:00 2001 From: Serhii Temchenko Date: Fri, 12 Apr 2024 00:23:10 -0700 Subject: [PATCH 11/54] Code style fixes --- pallets/ocex/src/settlement.rs | 4 ++-- pallets/ocex/src/tests.rs | 30 ++++++++++++++++++++++++------ pallets/ocex/src/validator.rs | 12 ++++++------ 3 files changed, 32 insertions(+), 14 deletions(-) diff --git a/pallets/ocex/src/settlement.rs b/pallets/ocex/src/settlement.rs index 77d632b77..d3e30d142 100644 --- a/pallets/ocex/src/settlement.rs +++ b/pallets/ocex/src/settlement.rs @@ -103,7 +103,7 @@ pub fn sub_balance( account: &AccountId, asset: AssetId, mut balance: Decimal, - is_withdrawal: bool + is_withdrawal: bool, ) -> 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())? { @@ -120,7 +120,7 @@ pub fn sub_balance( let deviation = balance.sub(&*account_balance); log::warn!(target:"ocex","[withdrawal] balance deviation of {:?} for asset: {:?}, of account: {:?}: Withdrawing available balance",deviation,asset.to_string(), account.to_ss58check_with_version(Ss58AddressFormat::from(POLKADEX_MAINNET_SS58))); balance = *account_balance; - }else{ + } else { log::error!(target:"ocex","Asset found but balance low for asset: {:?}, of account: {:?}",asset, account); return Err("NotEnoughBalance"); } diff --git a/pallets/ocex/src/tests.rs b/pallets/ocex/src/tests.rs index f029535c8..8793464fa 100644 --- a/pallets/ocex/src/tests.rs +++ b/pallets/ocex/src/tests.rs @@ -252,8 +252,14 @@ fn test_two_assets() { let asset456 = AssetId::Asset(456); let amount456 = Decimal::from_str("10.0").unwrap(); // works - sub_balance(&mut state, &account_id, asset1, Decimal::from_str("0.01").unwrap().into(), false) - .unwrap(); + sub_balance( + &mut state, + &account_id, + asset1, + Decimal::from_str("0.01").unwrap().into(), + false, + ) + .unwrap(); add_balance(&mut state, &coinalpha, asset123, amount123.into()).unwrap(); add_balance(&mut state, &coinalpha, asset456, amount456.into()).unwrap(); let root = state.commit().unwrap(); @@ -262,10 +268,22 @@ fn test_two_assets() { let mut root = crate::storage::load_trie_root(); let mut trie_state = crate::storage::State; let mut state = OffchainState::load(&mut trie_state, &mut root); - sub_balance(&mut state, &account_id, asset1, Decimal::from_str("0.01").unwrap().into(), false) - .unwrap(); - sub_balance(&mut state, &account_id, asset1, Decimal::from_str("0.01").unwrap().into(), false) - .unwrap(); + sub_balance( + &mut state, + &account_id, + asset1, + Decimal::from_str("0.01").unwrap().into(), + false, + ) + .unwrap(); + sub_balance( + &mut state, + &account_id, + asset1, + Decimal::from_str("0.01").unwrap().into(), + false, + ) + .unwrap(); }); } diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index 3eca61a86..96eb86352 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -473,7 +473,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, market.quote_asset, withdrawing_quote, - false + false, )?; // Sub Base @@ -483,7 +483,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, market.base_asset, withdrawing_base, - false + false, )?; // Egress message is verified @@ -563,7 +563,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, market.base_asset, base_balance, - false + false, )?; sub_balance( @@ -572,7 +572,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, market.quote_asset, quote_balance, - false + false, )?; verified_egress_messages.push(EgressMessages::PoolForceClosed( @@ -621,7 +621,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, asset, balance, - true + true, )?; } verified_egress_messages.push(egress_msg.clone()); @@ -692,7 +692,7 @@ impl Pallet { .map_err(|_| "account id decode error")?, request.asset(), amount, - true + true, )?; let mut withdrawal = request.convert(stid).map_err(|_| "Withdrawal conversion error")?; withdrawal.amount = actual_deducted; // The actual deducted balance From 0dd5198d1179fae62747512c1d57988ea50d7a3c Mon Sep 17 00:00:00 2001 From: zktony Date: Mon, 15 Apr 2024 21:29:12 +0530 Subject: [PATCH 12/54] Update do_claim ext --- pallets/rewards/src/lib.rs | 47 ++++---------------------------------- 1 file changed, 4 insertions(+), 43 deletions(-) diff --git a/pallets/rewards/src/lib.rs b/pallets/rewards/src/lib.rs index 072528157..7443813a6 100644 --- a/pallets/rewards/src/lib.rs +++ b/pallets/rewards/src/lib.rs @@ -425,33 +425,10 @@ impl Pallet { user_reward_info.initial_rewards_claimable.saturated_into::(); } - //calculate the number of blocks the user can claim rewards - let current_block_no: u128 = - >::block_number().saturated_into(); - let last_reward_claimed_block_no: u128 = - user_reward_info.last_block_rewards_claim.saturated_into(); - let unclaimed_blocks: u128 = - min(current_block_no, reward_info.end_block.saturated_into::()) - .saturating_sub(last_reward_claimed_block_no); - - // add the unclaimed block rewards to claimable rewards + // We compute the diff becasue end block is already complete rewards_claimable = rewards_claimable.saturating_add( - user_reward_info - .factor - .saturated_into::() - .saturating_mul(unclaimed_blocks), - ); - - //ensure total_rewards_claimable - rewards_claimed >= rewards_claimable - //sanity check - ensure!( - user_reward_info - .total_reward_amount - .saturated_into::() - .saturating_sub(user_reward_info.claim_amount.saturated_into::()) - >= rewards_claimable, - Error::::AllRewardsAlreadyClaimed - ); + user_reward_info.total_reward_amount.saturating_sub( + user_reward_info.claim_amount)); //ensure the claimable amount is greater than min claimable amount ensure!( @@ -466,23 +443,7 @@ impl Pallet { user_reward_info.last_block_rewards_claim = >::block_number(); user_reward_info.is_initial_rewards_claimed = true; - user_reward_info.claim_amount = user_reward_info - .claim_amount - .saturated_into::() - .saturating_add(rewards_claimable) - .saturated_into(); - - //set new lock on new amount - let reward_amount_to_lock = user_reward_info - .total_reward_amount - .saturated_into::() - .saturating_sub(user_reward_info.claim_amount.saturated_into::()); - T::NativeCurrency::set_lock( - user_reward_info.lock_id, - &user, - reward_amount_to_lock.saturated_into(), - WithdrawReasons::TRANSFER, - ); + user_reward_info.claim_amount = user_reward_info.total_reward_amount; Self::deposit_event(Event::UserClaimedReward { user, From 3901e397eefbb0044c68aebf32f25f54d04eb4a3 Mon Sep 17 00:00:00 2001 From: Gautham Date: Tue, 16 Apr 2024 11:01:03 +0300 Subject: [PATCH 13/54] Fix warnings --- pallets/rewards/src/lib.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/pallets/rewards/src/lib.rs b/pallets/rewards/src/lib.rs index 7443813a6..714a6c680 100644 --- a/pallets/rewards/src/lib.rs +++ b/pallets/rewards/src/lib.rs @@ -409,7 +409,7 @@ impl Pallet { fn do_claim(user: T::AccountId, reward_id: u32) -> DispatchResult { >::mutate(reward_id, user.clone(), |user_reward_info| { - if let Some(reward_info) = >::get(reward_id) { + if let Some(_reward_info) = >::get(reward_id) { if let Some(user_reward_info) = user_reward_info { //check if user has initialize rewards or not ensure!( @@ -417,22 +417,21 @@ impl Pallet { Error::::UserHasNotInitializeClaimRewards ); - let mut rewards_claimable: u128 = 0_u128.saturated_into(); + let mut rewards_claimable: BalanceOf = 0_u128.saturated_into(); //if initial rewards are not claimed add it to claimable rewards if !user_reward_info.is_initial_rewards_claimed { - rewards_claimable = - user_reward_info.initial_rewards_claimable.saturated_into::(); + rewards_claimable = user_reward_info.initial_rewards_claimable; } - // We compute the diff becasue end block is already complete + // We compute the diff because end block is already complete rewards_claimable = rewards_claimable.saturating_add( user_reward_info.total_reward_amount.saturating_sub( user_reward_info.claim_amount)); //ensure the claimable amount is greater than min claimable amount ensure!( - rewards_claimable > MIN_REWARDS_CLAIMABLE_AMOUNT, + rewards_claimable.saturated_into::() > MIN_REWARDS_CLAIMABLE_AMOUNT, Error::::AmountToLowToRedeem ); From aff15db22052226dab28180402f9b650628480be Mon Sep 17 00:00:00 2001 From: Gautham Date: Tue, 16 Apr 2024 11:37:26 +0300 Subject: [PATCH 14/54] cargo fmt --- pallets/rewards/src/lib.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pallets/rewards/src/lib.rs b/pallets/rewards/src/lib.rs index 714a6c680..2b52c908c 100644 --- a/pallets/rewards/src/lib.rs +++ b/pallets/rewards/src/lib.rs @@ -426,8 +426,10 @@ impl Pallet { // We compute the diff because end block is already complete rewards_claimable = rewards_claimable.saturating_add( - user_reward_info.total_reward_amount.saturating_sub( - user_reward_info.claim_amount)); + user_reward_info + .total_reward_amount + .saturating_sub(user_reward_info.claim_amount), + ); //ensure the claimable amount is greater than min claimable amount ensure!( From 0ce80f5c7938ef066763a3ead7cd05b4b2814327 Mon Sep 17 00:00:00 2001 From: Gautham Date: Tue, 16 Apr 2024 12:27:39 +0300 Subject: [PATCH 15/54] fix benchmarking and tests --- pallets/rewards/src/benchmarking.rs | 7 ------- pallets/rewards/src/tests.rs | 19 +------------------ runtimes/mainnet/src/lib.rs | 2 +- 3 files changed, 2 insertions(+), 26 deletions(-) diff --git a/pallets/rewards/src/benchmarking.rs b/pallets/rewards/src/benchmarking.rs index 5a7d8c7d5..a7d860745 100644 --- a/pallets/rewards/src/benchmarking.rs +++ b/pallets/rewards/src/benchmarking.rs @@ -141,13 +141,6 @@ benchmarks! { reward_id }; }: { call.dispatch_bypass_filter(RawOrigin::Signed(alice_account.clone()).into())? } - verify { - assert_last_event::(Event::UserClaimedReward { - user: alice_account.clone(), - reward_id, - claimed: (200 * UNIT_BALANCE).saturated_into(), - }.into()); - } } #[cfg(test)] diff --git a/pallets/rewards/src/tests.rs b/pallets/rewards/src/tests.rs index b315076f0..d5bdd2f24 100644 --- a/pallets/rewards/src/tests.rs +++ b/pallets/rewards/src/tests.rs @@ -938,24 +938,7 @@ pub fn claim_rewards_for_alice_at_multiple_intervals() { start_block.saturating_add(require_block_to_claim_50_percentage_of_rewards), ); - assert_ok!(Rewards::claim(RuntimeOrigin::signed(alice_account.clone()), reward_id)); - let (alice_claimable, _, _) = get_rewards_when_50_percentage_of_lock_amount_claimable(); - - //assert locked balances - assert_locked_balance(&alice_account, alice_claimable, total_reward_for_alice_in_pdex); - - //call claim at the end of cycle - System::set_block_number(end_block + 10); - assert_ok!(Rewards::claim(RuntimeOrigin::signed(alice_account.clone()), reward_id)); - //assert locked balances - assert_locked_balance( - &alice_account, - total_reward_for_alice_in_pdex, - total_reward_for_alice_in_pdex, - ); - - //re try to call claim at the end of cycle when all rewards claimed - System::set_block_number(end_block + 20); + // assert_ok!(Rewards::claim(RuntimeOrigin::signed(alice_account.clone()), reward_id)); - disabled since the whole amount is claimed now assert_noop!( Rewards::claim(RuntimeOrigin::signed(alice_account), reward_id), Error::::AmountToLowToRedeem diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 04669a6a6..7ca29b560 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: 343, + spec_version: 347, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 204c58d24033931e4ad6c5f75294403bfbfba9d1 Mon Sep 17 00:00:00 2001 From: Serhii Temchenko Date: Tue, 16 Apr 2024 20:43:29 -0700 Subject: [PATCH 16/54] Updated weights --- pallets/rewards/src/weights.rs | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/pallets/rewards/src/weights.rs b/pallets/rewards/src/weights.rs index f0ae28bde..3cb9a85e6 100644 --- a/pallets/rewards/src/weights.rs +++ b/pallets/rewards/src/weights.rs @@ -1,9 +1,9 @@ //! Autogenerated weights for `pallet_rewards` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2024-03-05, STEPS: `100`, REPEAT: `200`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-04-16, STEPS: `100`, REPEAT: `200`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `ip-172-31-9-163`, CPU: `AMD EPYC 7571` +//! HOSTNAME: `ip-172-31-44-62`, CPU: `AMD EPYC 7571` //! WASM-EXECUTION: `Compiled`, CHAIN: `None`, DB CACHE: 1024 // Executed Command: @@ -37,17 +37,15 @@ impl crate::WeightInfo for WeightInfo { /// The range of component `b` is `[0, 4838400]`. /// The range of component `i` is `[1, 100]`. /// The range of component `r` is `[0, 10]`. - fn create_reward_cycle(_b: u32, i: u32, r: u32, ) -> Weight { + fn create_reward_cycle(_b: u32, _i: u32, r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `76` // Estimated: `3541` - // Minimum execution time: 35_141_000 picoseconds. - Weight::from_parts(36_486_240, 0) + // Minimum execution time: 35_781_000 picoseconds. + Weight::from_parts(37_572_558, 0) .saturating_add(Weight::from_parts(0, 3541)) - // Standard Error: 49 - .saturating_add(Weight::from_parts(190, 0).saturating_mul(i.into())) - // Standard Error: 464 - .saturating_add(Weight::from_parts(2_517, 0).saturating_mul(r.into())) + // Standard Error: 515 + .saturating_add(Weight::from_parts(474, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -65,8 +63,8 @@ impl crate::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `1010` // Estimated: `6196` - // Minimum execution time: 263_131_000 picoseconds. - Weight::from_parts(266_091_000, 0) + // Minimum execution time: 263_202_000 picoseconds. + Weight::from_parts(266_531_000, 0) .saturating_add(Weight::from_parts(0, 6196)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) @@ -85,8 +83,8 @@ impl crate::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `1016` // Estimated: `4764` - // Minimum execution time: 146_781_000 picoseconds. - Weight::from_parts(148_411_000, 0) + // Minimum execution time: 110_391_000 picoseconds. + Weight::from_parts(112_260_000, 0) .saturating_add(Weight::from_parts(0, 4764)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) From 8a078a8cec285907d37a2f5521069bcce113ac87 Mon Sep 17 00:00:00 2001 From: Gautham Date: Thu, 18 Apr 2024 13:23:42 +0300 Subject: [PATCH 17/54] disable place bid --- pallets/ocex/src/lib.rs | 44 ++++++++++++++++++------------------- runtimes/mainnet/src/lib.rs | 2 +- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index 754eca04d..069bfce18 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -1023,28 +1023,28 @@ pub mod pallet { Ok(()) } - /// Place Bid - #[pallet::call_index(22)] - #[pallet::weight(< T as Config >::WeightInfo::place_bid())] - pub fn place_bid(origin: OriginFor, bid_amount: BalanceOf) -> DispatchResult { - let bidder = ensure_signed(origin)?; - let mut auction_info = >::get().ok_or(Error::::AuctionNotFound)?; - ensure!(bid_amount > Zero::zero(), Error::::InvalidBidAmount); - ensure!(bid_amount > auction_info.highest_bid, Error::::InvalidBidAmount); - ensure!( - T::NativeCurrency::can_reserve(&bidder, bid_amount), - Error::::InsufficientBalance - ); - T::NativeCurrency::reserve(&bidder, bid_amount)?; - if let Some(old_bidder) = auction_info.highest_bidder { - // Un-reserve the old bidder - T::NativeCurrency::unreserve(&old_bidder, auction_info.highest_bid); - } - auction_info.highest_bid = bid_amount; - auction_info.highest_bidder = Some(bidder); - >::put(auction_info); - Ok(()) - } + // /// Place Bid TODO: Enable it after frontend is ready. + // #[pallet::call_index(22)] + // #[pallet::weight(< T as Config >::WeightInfo::place_bid())] + // pub fn place_bid(origin: OriginFor, bid_amount: BalanceOf) -> DispatchResult { + // let bidder = ensure_signed(origin)?; + // let mut auction_info = >::get().ok_or(Error::::AuctionNotFound)?; + // ensure!(bid_amount > Zero::zero(), Error::::InvalidBidAmount); + // ensure!(bid_amount > auction_info.highest_bid, Error::::InvalidBidAmount); + // ensure!( + // T::NativeCurrency::can_reserve(&bidder, bid_amount), + // Error::::InsufficientBalance + // ); + // T::NativeCurrency::reserve(&bidder, bid_amount)?; + // if let Some(old_bidder) = auction_info.highest_bidder { + // // Un-reserve the old bidder + // T::NativeCurrency::unreserve(&old_bidder, auction_info.highest_bid); + // } + // auction_info.highest_bid = bid_amount; + // auction_info.highest_bidder = Some(bidder); + // >::put(auction_info); + // Ok(()) + // } /// Starts a new liquidity mining epoch #[pallet::call_index(23)] diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 7ca29b560..3ca3966e3 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: 347, + spec_version: 348, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 1fddf0f577aa6ca7e1845e609f23dfc593d14f05 Mon Sep 17 00:00:00 2001 From: Gautham Date: Thu, 18 Apr 2024 15:14:41 +0300 Subject: [PATCH 18/54] disable place bid benchmarks --- pallets/ocex/src/benchmarking.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pallets/ocex/src/benchmarking.rs b/pallets/ocex/src/benchmarking.rs index ea5e5fe33..079bc1bb0 100644 --- a/pallets/ocex/src/benchmarking.rs +++ b/pallets/ocex/src/benchmarking.rs @@ -475,14 +475,14 @@ verify { assert_eq!(current_fee_distribution.burn_ration, burn_ration); } - place_bid { - let old_bidder = T::AccountId::decode(&mut &[1; 32][..]).unwrap(); - let auction_info: AuctionInfo> = - AuctionInfo { fee_info: BTreeMap::new(), highest_bidder: None, highest_bid: Zero::zero() }; - >::put(auction_info); - let bidder = T::AccountId::decode(&mut &[2; 32][..]).unwrap(); - let _imbalance = T::NativeCurrency::deposit_creating(&bidder, (100 * UNIT_BALANCE).saturated_into()); - }: _(RawOrigin::Signed(bidder), (10 * UNIT_BALANCE).saturated_into()) + // place_bid { + // let old_bidder = T::AccountId::decode(&mut &[1; 32][..]).unwrap(); + // let auction_info: AuctionInfo> = + // AuctionInfo { fee_info: BTreeMap::new(), highest_bidder: None, highest_bid: Zero::zero() }; + // >::put(auction_info); + // let bidder = T::AccountId::decode(&mut &[2; 32][..]).unwrap(); + // let _imbalance = T::NativeCurrency::deposit_creating(&bidder, (100 * UNIT_BALANCE).saturated_into()); + // }: _(RawOrigin::Signed(bidder), (10 * UNIT_BALANCE).saturated_into()) on_initialize { let block_no: BlockNumberFor = 200u32.into(); From 3270fd82df3a786b87a82122658bfb9ce19d84db Mon Sep 17 00:00:00 2001 From: Gautham Date: Thu, 18 Apr 2024 21:12:13 +0300 Subject: [PATCH 19/54] disable place bid benchmarks --- pallets/ocex/src/benchmarking.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/ocex/src/benchmarking.rs b/pallets/ocex/src/benchmarking.rs index 079bc1bb0..8d040ea4f 100644 --- a/pallets/ocex/src/benchmarking.rs +++ b/pallets/ocex/src/benchmarking.rs @@ -604,7 +604,7 @@ use frame_benchmarking::impl_benchmark_test_suite; use frame_support::traits::fungibles::Create; use orderbook_primitives::lmp::LMPMarketConfigWrapper; use orderbook_primitives::ocex::TradingPairConfig; -use polkadex_primitives::auction::AuctionInfo; +// use polkadex_primitives::auction::AuctionInfo; #[cfg(test)] impl_benchmark_test_suite!(Ocex, crate::mock::new_test_ext(), crate::mock::Test); From 8efd34b566b81a10f8340227193755ebc9b3ff5a Mon Sep 17 00:00:00 2001 From: Gareth McDonald Date: Thu, 18 Apr 2024 12:48:21 -0700 Subject: [PATCH 20/54] Update the Proxy filter to allow all if the setting is set to any --- 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 dcaa09cf0..94a734b40 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -291,7 +291,7 @@ impl Default for ProxyType { impl InstanceFilter for ProxyType { fn filter(&self, c: &RuntimeCall) -> bool { match self { - ProxyType::Any => false, + ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, RuntimeCall::Balances(..) From 84066abd602039d9f181725ca1f037e36ebb7ae1 Mon Sep 17 00:00:00 2001 From: Gautham Date: Fri, 19 Apr 2024 12:17:39 +0300 Subject: [PATCH 21/54] Comment out place bid tests --- pallets/ocex/src/tests.rs | 204 +++++++++++++++++++------------------- 1 file changed, 102 insertions(+), 102 deletions(-) diff --git a/pallets/ocex/src/tests.rs b/pallets/ocex/src/tests.rs index 8793464fa..c7bf3e04d 100644 --- a/pallets/ocex/src/tests.rs +++ b/pallets/ocex/src/tests.rs @@ -2717,108 +2717,108 @@ fn test_close_auction_error_transfer_zero_fee() { }) } -#[test] -fn test_place_bid_happy_path() { - new_test_ext().execute_with(|| { - let auction_info = - AuctionInfo { fee_info: BTreeMap::new(), highest_bidder: None, highest_bid: 0 }; - >::put(auction_info); - let bidder = AccountId32::new([2; 32]); - let bid_amount = 20 * UNIT_BALANCE; - //Mint Bidder - Balances::mint_into(&bidder, 100 * UNIT_BALANCE).unwrap(); - assert_ok!(OCEX::place_bid(RuntimeOrigin::signed(bidder.clone()), bid_amount)); - let actual_auction_info = >::get(); - let expected_auction_info = AuctionInfo { - fee_info: BTreeMap::new(), - highest_bidder: Some(bidder.clone()), - highest_bid: bid_amount, - }; - assert_eq!(actual_auction_info, Some(expected_auction_info)); - let bidder_two = AccountId32::new([3; 32]); - let bid_amount_two = 30 * UNIT_BALANCE; - //Mint Bidder - Balances::mint_into(&bidder_two, 100 * UNIT_BALANCE).unwrap(); - assert_ok!(OCEX::place_bid(RuntimeOrigin::signed(bidder_two.clone()), bid_amount_two)); - let actual_auction_info = >::get(); - let expected_auction_info = AuctionInfo { - fee_info: BTreeMap::new(), - highest_bidder: Some(bidder_two.clone()), - highest_bid: bid_amount_two, - }; - assert_eq!(actual_auction_info, Some(expected_auction_info)); - assert_eq!(Balances::free_balance(&bidder), 100 * UNIT_BALANCE); - assert_eq!(Balances::free_balance(&bidder_two), 70 * UNIT_BALANCE); - }) -} - -#[test] -fn test_place_bid_error_use_ext_balance_later() { - new_test_ext().execute_with(|| { - let auction_info = - AuctionInfo { fee_info: BTreeMap::new(), highest_bidder: None, highest_bid: 0 }; - >::put(auction_info); - let bidder = AccountId32::new([2; 32]); - let bid_amount = 20 * UNIT_BALANCE; - //Mint Bidder - Balances::mint_into(&bidder, 100 * UNIT_BALANCE).unwrap(); - assert_ok!(OCEX::place_bid(RuntimeOrigin::signed(bidder.clone()), bid_amount)); - let actual_auction_info = >::get(); - let expected_auction_info = AuctionInfo { - fee_info: BTreeMap::new(), - highest_bidder: Some(bidder.clone()), - highest_bid: bid_amount, - }; - assert_eq!(actual_auction_info, Some(expected_auction_info)); - assert_eq!(Balances::free_balance(&bidder), 80 * UNIT_BALANCE); - assert_noop!( - Balances::transfer_allow_death( - RuntimeOrigin::signed(bidder), - AccountId32::new([9; 32]), - 80 * UNIT_BALANCE - ), - TokenError::Frozen - ); - }) -} - -#[test] -fn test_place_bid_error_low_bid() { - new_test_ext().execute_with(|| { - let auction_info = AuctionInfo { - fee_info: BTreeMap::new(), - highest_bidder: Some(AccountId32::new([10; 32])), - highest_bid: 20 * UNIT_BALANCE, - }; - >::put(auction_info); - let bidder = AccountId32::new([2; 32]); - let bid_amount = 10 * UNIT_BALANCE; - //Mint Bidder - Balances::mint_into(&bidder, 100 * UNIT_BALANCE).unwrap(); - assert_noop!( - OCEX::place_bid(RuntimeOrigin::signed(bidder.clone()), bid_amount), - crate::pallet::Error::::InvalidBidAmount - ); - }) -} - -#[test] -fn test_place_bid_error_insufficient_balance() { - new_test_ext().execute_with(|| { - let auction_info = AuctionInfo { - fee_info: BTreeMap::new(), - highest_bidder: Some(AccountId32::new([10; 32])), - highest_bid: 20 * UNIT_BALANCE, - }; - >::put(auction_info); - let bidder = AccountId32::new([2; 32]); - let bid_amount = 30 * UNIT_BALANCE; - assert_noop!( - OCEX::place_bid(RuntimeOrigin::signed(bidder.clone()), bid_amount), - crate::pallet::Error::::InsufficientBalance - ); - }) -} +// #[test] +// fn test_place_bid_happy_path() { +// new_test_ext().execute_with(|| { +// let auction_info = +// AuctionInfo { fee_info: BTreeMap::new(), highest_bidder: None, highest_bid: 0 }; +// >::put(auction_info); +// let bidder = AccountId32::new([2; 32]); +// let bid_amount = 20 * UNIT_BALANCE; +// //Mint Bidder +// Balances::mint_into(&bidder, 100 * UNIT_BALANCE).unwrap(); +// assert_ok!(OCEX::place_bid(RuntimeOrigin::signed(bidder.clone()), bid_amount)); +// let actual_auction_info = >::get(); +// let expected_auction_info = AuctionInfo { +// fee_info: BTreeMap::new(), +// highest_bidder: Some(bidder.clone()), +// highest_bid: bid_amount, +// }; +// assert_eq!(actual_auction_info, Some(expected_auction_info)); +// let bidder_two = AccountId32::new([3; 32]); +// let bid_amount_two = 30 * UNIT_BALANCE; +// //Mint Bidder +// Balances::mint_into(&bidder_two, 100 * UNIT_BALANCE).unwrap(); +// assert_ok!(OCEX::place_bid(RuntimeOrigin::signed(bidder_two.clone()), bid_amount_two)); +// let actual_auction_info = >::get(); +// let expected_auction_info = AuctionInfo { +// fee_info: BTreeMap::new(), +// highest_bidder: Some(bidder_two.clone()), +// highest_bid: bid_amount_two, +// }; +// assert_eq!(actual_auction_info, Some(expected_auction_info)); +// assert_eq!(Balances::free_balance(&bidder), 100 * UNIT_BALANCE); +// assert_eq!(Balances::free_balance(&bidder_two), 70 * UNIT_BALANCE); +// }) +// } +// +// #[test] +// fn test_place_bid_error_use_ext_balance_later() { +// new_test_ext().execute_with(|| { +// let auction_info = +// AuctionInfo { fee_info: BTreeMap::new(), highest_bidder: None, highest_bid: 0 }; +// >::put(auction_info); +// let bidder = AccountId32::new([2; 32]); +// let bid_amount = 20 * UNIT_BALANCE; +// //Mint Bidder +// Balances::mint_into(&bidder, 100 * UNIT_BALANCE).unwrap(); +// assert_ok!(OCEX::place_bid(RuntimeOrigin::signed(bidder.clone()), bid_amount)); +// let actual_auction_info = >::get(); +// let expected_auction_info = AuctionInfo { +// fee_info: BTreeMap::new(), +// highest_bidder: Some(bidder.clone()), +// highest_bid: bid_amount, +// }; +// assert_eq!(actual_auction_info, Some(expected_auction_info)); +// assert_eq!(Balances::free_balance(&bidder), 80 * UNIT_BALANCE); +// assert_noop!( +// Balances::transfer_allow_death( +// RuntimeOrigin::signed(bidder), +// AccountId32::new([9; 32]), +// 80 * UNIT_BALANCE +// ), +// TokenError::Frozen +// ); +// }) +// } +// +// #[test] +// fn test_place_bid_error_low_bid() { +// new_test_ext().execute_with(|| { +// let auction_info = AuctionInfo { +// fee_info: BTreeMap::new(), +// highest_bidder: Some(AccountId32::new([10; 32])), +// highest_bid: 20 * UNIT_BALANCE, +// }; +// >::put(auction_info); +// let bidder = AccountId32::new([2; 32]); +// let bid_amount = 10 * UNIT_BALANCE; +// //Mint Bidder +// Balances::mint_into(&bidder, 100 * UNIT_BALANCE).unwrap(); +// assert_noop!( +// OCEX::place_bid(RuntimeOrigin::signed(bidder.clone()), bid_amount), +// crate::pallet::Error::::InvalidBidAmount +// ); +// }) +// } +// +// #[test] +// fn test_place_bid_error_insufficient_balance() { +// new_test_ext().execute_with(|| { +// let auction_info = AuctionInfo { +// fee_info: BTreeMap::new(), +// highest_bidder: Some(AccountId32::new([10; 32])), +// highest_bid: 20 * UNIT_BALANCE, +// }; +// >::put(auction_info); +// let bidder = AccountId32::new([2; 32]); +// let bid_amount = 30 * UNIT_BALANCE; +// assert_noop!( +// OCEX::place_bid(RuntimeOrigin::signed(bidder.clone()), bid_amount), +// crate::pallet::Error::::InsufficientBalance +// ); +// }) +// } pub fn create_fee_config() { let recipient_address = AccountId32::new([1; 32]); From 140d32d7df8debd3e72835da212136711d8f34c8 Mon Sep 17 00:00:00 2001 From: Gautham Date: Fri, 19 Apr 2024 13:23:33 +0300 Subject: [PATCH 22/54] 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 aad6901ac..67f2678be 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: 348, + spec_version: 349, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 234c4fa525b8edcf1f243080a8b6873744675f6a Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Tue, 23 Apr 2024 17:21:48 +0530 Subject: [PATCH 23/54] feat: add support for extension signature --- primitives/orderbook/Cargo.toml | 1 + primitives/orderbook/src/traits.rs | 4 +++ primitives/orderbook/src/types.rs | 47 ++++++++++++++++++++++++++++-- 3 files changed, 49 insertions(+), 3 deletions(-) diff --git a/primitives/orderbook/Cargo.toml b/primitives/orderbook/Cargo.toml index 5a4b1bda2..d7109234f 100644 --- a/primitives/orderbook/Cargo.toml +++ b/primitives/orderbook/Cargo.toml @@ -20,6 +20,7 @@ rand = { version = "0.8.5", optional = true } serde = { workspace = true, default-features = false } serde_with = { version = "3.6.1", features = ["json", "macros"], default-features = false } log = { workspace = true, default-features = false } +serde_json = { workspace = true } anyhow = { version = "1.0.69", default-features = false } rust_decimal = { git = "https://github.com/Polkadex-Substrate/rust-decimal.git", branch = "master", features = [ "scale-codec", diff --git a/primitives/orderbook/src/traits.rs b/primitives/orderbook/src/traits.rs index 865411c81..2b3fe2f6e 100644 --- a/primitives/orderbook/src/traits.rs +++ b/primitives/orderbook/src/traits.rs @@ -111,3 +111,7 @@ impl LiquidityMiningCrowdSourcePallet for () { fn stop_accepting_lmp_withdrawals(_epoch: u16) {} } + +pub trait VerifyExtensionSignature { + fn verify_extension_signature(&self, payload: &str, account_id: &AccountId) -> bool; +} diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index c9d0443e4..ac0849542 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -41,6 +41,7 @@ use std::{ ops::{Mul, Rem}, str::FromStr, }; + pub type OrderId = H256; /// Defined account information required for the "Orderbook" client. @@ -88,6 +89,13 @@ pub struct Trade { pub time: i64, } +impl VerifyExtensionSignature for MultiSignature { + fn verify_extension_signature(&self, payload: &str, account: &AccountId) -> bool { + let wrapped_payload = format!("{}", payload); + return self.verify(wrapped_payload.as_bytes(), account); + } +} + impl Trade { /// Depends on the trade side - calculates and provides price and asset information required for /// further balances transfers. @@ -303,8 +311,10 @@ impl WithdrawalRequest { Decimal::from_str(&self.payload.amount) } } + use crate::ingress::{EgressMessages, IngressMessages}; use crate::ocex::TradingPairConfig; +use crate::traits::VerifyExtensionSignature; #[cfg(not(feature = "std"))] use core::{ ops::{Mul, Rem}, @@ -313,6 +323,7 @@ use core::{ use frame_support::{Deserialize, Serialize}; use parity_scale_codec::alloc::string::ToString; use scale_info::prelude::string::String; +use sp_runtime::MultiSignature; use sp_std::collections::btree_map::BTreeMap; /// Withdraw payload requested by user. @@ -644,10 +655,19 @@ impl Order { pub fn verify_signature(&self) -> bool { let payload: OrderPayload = self.clone().into(); let result = self.signature.verify(&payload.encode()[..], &self.user); - if !result { - log::error!(target:"orderbook","Order signature check failed"); + if result { + return true; } - result + log::error!(target:"orderbook","Order signature check failed"); + let payload_str = serde_json::to_string(&payload); + if let Ok(payload_str) = payload_str { + let result = + self.signature.verify_extension_signature(&payload_str, &self.main_account); + if result { + return true; + } + } + false } /// Returns the key used for storing in orderbook @@ -905,6 +925,7 @@ impl From for OrderPayload { } } } + #[cfg(feature = "std")] impl TryFrom for Order { type Error = &'static str; @@ -972,6 +993,26 @@ pub struct WithdrawalDetails { pub signature: Signature, } +impl WithdrawalDetails { + /// Verifies the signature. + pub fn verify_signature(&self) -> bool { + let result = self.signature.verify(self.payload.encode().as_ref(), &self.proxy); + if result { + return true; + } + log::error!(target:"orderbook","Withdrawal signature check failed"); + let payload_str = serde_json::to_string(&self.payload); + if let Ok(payload_str) = payload_str { + let result = self.signature.verify_extension_signature(&payload_str, &self.main); + if result { + return true; + } + } + log::error!(target:"orderbook","Withdrawal extension signature check failed"); + false + } +} + /// Overarching type used by validators when submitting /// their signature for a summary to aggregator #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] From 336eee63ed29b487696385ac047f594c207d2a00 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Wed, 24 Apr 2024 02:01:30 +0530 Subject: [PATCH 24/54] chore: add test case --- Cargo.lock | 1 + primitives/orderbook/Cargo.toml | 2 +- primitives/orderbook/src/types.rs | 19 ++++++++++++++++++- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7237ee942..743894dfa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6034,6 +6034,7 @@ dependencies = [ "anyhow", "chrono", "frame-support", + "hex", "log", "parity-scale-codec", "polkadex-primitives", diff --git a/primitives/orderbook/Cargo.toml b/primitives/orderbook/Cargo.toml index d7109234f..d651d34a0 100644 --- a/primitives/orderbook/Cargo.toml +++ b/primitives/orderbook/Cargo.toml @@ -25,7 +25,7 @@ anyhow = { version = "1.0.69", default-features = false } rust_decimal = { git = "https://github.com/Polkadex-Substrate/rust-decimal.git", branch = "master", features = [ "scale-codec", ], default-features = false } - +hex = { workspace = true } [dev-dependencies] serde_json = "1.0.94" diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index ac0849542..f0ae9c857 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -91,7 +91,7 @@ pub struct Trade { impl VerifyExtensionSignature for MultiSignature { fn verify_extension_signature(&self, payload: &str, account: &AccountId) -> bool { - let wrapped_payload = format!("{}", payload); + let wrapped_payload = format!("{}", payload); return self.verify(wrapped_payload.as_bytes(), account); } } @@ -1028,10 +1028,13 @@ pub struct ApprovedSnapshot { #[cfg(test)] mod tests { use crate::ingress::{EgressMessages, IngressMessages}; + use crate::traits::VerifyExtensionSignature; use crate::types::UserActions; use polkadex_primitives::{AccountId, AssetId}; use rust_decimal::Decimal; + use sp_runtime::MultiSignature; use std::collections::BTreeMap; + use std::str::FromStr; #[test] pub fn test_serialize_deserialize_user_actions() { @@ -1047,4 +1050,18 @@ mod tests { serde_json::to_vec(&action).unwrap(); } + + #[test] + pub fn verify_signature_from_extension() { + let payload = "hello world!"; + let account = + AccountId::from_str("5FYr5g1maSsAAw6w98xdAytZ6MEQ8sNPgp3PNLgy9o79kMug").unwrap(); + let raw_signature = "36751864552cb500ef323ad1b4bd559ade88cff9b922bfdd0b1c18ace7429f57eacc2421dc3ea38a9c434593461fcae0ffa751280e25fedb48e406e42e0f6b82"; + //convert raw signature to sr25519 signature + let sig = hex::decode(raw_signature).unwrap(); + let sig = sp_core::sr25519::Signature::from_slice(&sig[..]).unwrap(); + let sig = MultiSignature::from(sig); + let result = sig.verify_extension_signature(&payload, &account); + assert_eq!(result, true); + } } From 41b9d5020f7280e2ee3c7a390cbde4a07a891201 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Wed, 24 Apr 2024 02:04:06 +0530 Subject: [PATCH 25/54] chore: comments --- primitives/orderbook/src/types.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index f0ae9c857..5c741d258 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -1056,6 +1056,7 @@ mod tests { let payload = "hello world!"; let account = AccountId::from_str("5FYr5g1maSsAAw6w98xdAytZ6MEQ8sNPgp3PNLgy9o79kMug").unwrap(); + // raw signature from polkadot.js extension signRaw let raw_signature = "36751864552cb500ef323ad1b4bd559ade88cff9b922bfdd0b1c18ace7429f57eacc2421dc3ea38a9c434593461fcae0ffa751280e25fedb48e406e42e0f6b82"; //convert raw signature to sr25519 signature let sig = hex::decode(raw_signature).unwrap(); From 94a54ab8686d963f27bb965b57677d0e301eda67 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Wed, 24 Apr 2024 02:10:00 +0530 Subject: [PATCH 26/54] chore: logs --- primitives/orderbook/src/types.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index 5c741d258..f2fbb6c36 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -667,6 +667,7 @@ impl Order { return true; } } + log::error!(target:"orderbook","orderbook extension signature check failed"); false } From 25e32bf8e3350a5c0ca73faed7b41d31d5c3923a Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Wed, 24 Apr 2024 02:12:44 +0530 Subject: [PATCH 27/54] chore: comments --- primitives/orderbook/src/types.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index f2fbb6c36..1133ca66c 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -1054,10 +1054,11 @@ mod tests { #[test] pub fn verify_signature_from_extension() { + // the string signed by polkadot-js api extension using signRaw let payload = "hello world!"; let account = AccountId::from_str("5FYr5g1maSsAAw6w98xdAytZ6MEQ8sNPgp3PNLgy9o79kMug").unwrap(); - // raw signature from polkadot.js extension signRaw + // raw signature from polkadot-js api signRaw let raw_signature = "36751864552cb500ef323ad1b4bd559ade88cff9b922bfdd0b1c18ace7429f57eacc2421dc3ea38a9c434593461fcae0ffa751280e25fedb48e406e42e0f6b82"; //convert raw signature to sr25519 signature let sig = hex::decode(raw_signature).unwrap(); From 6993dcd81f90e8e7f769a7ea2d6af9f9770df817 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Wed, 24 Apr 2024 02:38:43 +0530 Subject: [PATCH 28/54] chore: build fix --- primitives/orderbook/src/types.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index 1133ca66c..15b4f2912 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -91,7 +91,9 @@ pub struct Trade { impl VerifyExtensionSignature for MultiSignature { fn verify_extension_signature(&self, payload: &str, account: &AccountId) -> bool { - let wrapped_payload = format!("{}", payload); + const PREFIX: &str = ""; + const POSTFIX: &str = ""; + let wrapped_payload = PREFIX.to_string() + payload + POSTFIX; return self.verify(wrapped_payload.as_bytes(), account); } } From 45e5d68f8c3e2ae160d4fa454c568d75039c9a45 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Wed, 24 Apr 2024 02:42:46 +0530 Subject: [PATCH 29/54] chore: build fix --- primitives/orderbook/src/constants.rs | 2 ++ primitives/orderbook/src/types.rs | 5 ++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/primitives/orderbook/src/constants.rs b/primitives/orderbook/src/constants.rs index d5fe7f159..a6b7029b6 100644 --- a/primitives/orderbook/src/constants.rs +++ b/primitives/orderbook/src/constants.rs @@ -35,6 +35,8 @@ pub const MAX_PRICE: Balance = 10000000 * UNIT_BALANCE; pub const FEE_POT_PALLET_ID: PalletId = PalletId(*b"ocexfees"); +pub const EXT_WRAP_PREFIX: &str = ""; +pub const EXT_WRAP_POSTFIX: &str = ""; #[cfg(test)] mod test { use crate::constants::{MAX_PRICE, MAX_QTY, POLKADEX_MAINNET_SS58}; diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index 15b4f2912..e36e3a11f 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -91,9 +91,8 @@ pub struct Trade { impl VerifyExtensionSignature for MultiSignature { fn verify_extension_signature(&self, payload: &str, account: &AccountId) -> bool { - const PREFIX: &str = ""; - const POSTFIX: &str = ""; - let wrapped_payload = PREFIX.to_string() + payload + POSTFIX; + let wrapped_payload = crate::constants::EXT_WRAP_PREFIX.to_string() + + payload + crate::constants::EXT_WRAP_POSTFIX; return self.verify(wrapped_payload.as_bytes(), account); } } From c0d102c8f60666c8e712d931211a0d007d96c1ee Mon Sep 17 00:00:00 2001 From: Gautham Date: Wed, 24 Apr 2024 14:06:32 +0300 Subject: [PATCH 30/54] Disable EVM authorities payload generation --- pallets/thea/src/lib.rs | 75 +++++++++++++++++++------------------ runtimes/mainnet/src/lib.rs | 2 +- 2 files changed, 39 insertions(+), 38 deletions(-) diff --git a/pallets/thea/src/lib.rs b/pallets/thea/src/lib.rs index 804b2aa40..cf07dfb4e 100644 --- a/pallets/thea/src/lib.rs +++ b/pallets/thea/src/lib.rs @@ -771,42 +771,43 @@ impl Pallet { // This last message should be signed by the outgoing set // Similar to how Grandpa's session change works. if incoming != queued { - let mut uncompressed_keys: Vec<[u8; 20]> = vec![]; - for public_key in queued.clone().into_iter() { - let public_key: sp_core::ecdsa::Public = public_key.into(); - if public_key.0 == [0u8; 33] { - uncompressed_keys.push([0u8; 20]); - continue; - } - if let Ok(compressed_key) = libsecp256k1::PublicKey::parse_compressed(&public_key.0) - { - let uncompressed_key = compressed_key.serialize(); - let uncompressed_key: [u8; 64] = - if let Ok(uncompressed_key) = uncompressed_key[1..65].try_into() { - uncompressed_key - } else { - log::error!(target: "thea", "Unable to slice last 64 bytes of uncompressed_key for Evm"); - Self::deposit_event(Event::::UnableToSlicePublicKeyHash( - public_key.into(), - )); - return; - }; - let hash: [u8; 32] = sp_io::hashing::keccak_256(&uncompressed_key); - if let Ok(address) = hash[12..32].try_into() { - uncompressed_keys.push(address); - } else { - log::error!(target: "thea", "Unable to slice last 20 bytes of hash for Evm"); - Self::deposit_event(Event::::UnableToSlicePublicKeyHash( - public_key.into(), - )); - return; - } - } else { - log::error!(target: "thea", "Unable to parse compressed key"); - Self::deposit_event(Event::::UnableToParsePublicKey(public_key.into())); - return; - } - } + let uncompressed_keys: Vec<[u8; 20]> = vec![]; + // TODO: Uncomment the following when parsing is fixed for ethereum keys. + // for public_key in queued.clone().into_iter() { + // let public_key: sp_core::ecdsa::Public = public_key.into(); + // if public_key.0 == [0u8; 33] { + // uncompressed_keys.push([0u8; 20]); + // continue; + // } + // if let Ok(compressed_key) = libsecp256k1::PublicKey::parse_compressed(&public_key.0) + // { + // let uncompressed_key = compressed_key.serialize(); + // let uncompressed_key: [u8; 64] = + // if let Ok(uncompressed_key) = uncompressed_key[1..65].try_into() { + // uncompressed_key + // } else { + // log::error!(target: "thea", "Unable to slice last 64 bytes of uncompressed_key for Evm"); + // Self::deposit_event(Event::::UnableToSlicePublicKeyHash( + // public_key.into(), + // )); + // return; + // }; + // let hash: [u8; 32] = sp_io::hashing::keccak_256(&uncompressed_key); + // if let Ok(address) = hash[12..32].try_into() { + // uncompressed_keys.push(address); + // } else { + // log::error!(target: "thea", "Unable to slice last 20 bytes of hash for Evm"); + // Self::deposit_event(Event::::UnableToSlicePublicKeyHash( + // public_key.into(), + // )); + // return; + // } + // } else { + // log::error!(target: "thea", "Unable to parse compressed key"); + // Self::deposit_event(Event::::UnableToParsePublicKey(public_key.into())); + // return; + // } + // } for network in &active_networks { let network_config = >::get(*network); let message = match network_config.network_type { @@ -849,7 +850,7 @@ impl Pallet { >::put(new_id); for network in active_networks { let message = - Self::generate_payload(PayloadType::ValidatorsRotated, network, Vec::new()); //Empty data means acitvate the next set_id + Self::generate_payload(PayloadType::ValidatorsRotated, network, Vec::new()); //Empty data means activate the next set_id >::insert(network, message.nonce); >::insert(network, message.nonce, message); } diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 67f2678be..acf284e2b 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: 349, + spec_version: 350, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 156c719fda15e156b6e19568d2d501559be8aa42 Mon Sep 17 00:00:00 2001 From: zktony Date: Fri, 26 Apr 2024 09:28:03 +0530 Subject: [PATCH 31/54] Fixed lmp bug --- pallets/ocex/src/lmp.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/ocex/src/lmp.rs b/pallets/ocex/src/lmp.rs index 9b31bff88..e9196f84e 100644 --- a/pallets/ocex/src/lmp.rs +++ b/pallets/ocex/src/lmp.rs @@ -413,7 +413,7 @@ impl Pallet { )?; // Taker fees is in quote because they put bid order. - let fees = taker_fees.saturating_mul(trade.price); + let fees = taker_fees; store_fees_paid_by_main_account_in_quote( state, epoch, From 602b220aa599c074bce015f756ab63800c3c5d94 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Sat, 27 Apr 2024 00:38:08 +0530 Subject: [PATCH 32/54] chore: add more tests --- primitives/orderbook/src/types.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index e36e3a11f..10e104b59 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -1031,7 +1031,7 @@ pub struct ApprovedSnapshot { mod tests { use crate::ingress::{EgressMessages, IngressMessages}; use crate::traits::VerifyExtensionSignature; - use crate::types::UserActions; + use crate::types::{Order, OrderDetails, OrderPayload, UserActions}; use polkadex_primitives::{AccountId, AssetId}; use rust_decimal::Decimal; use sp_runtime::MultiSignature; @@ -1068,4 +1068,19 @@ mod tests { let result = sig.verify_extension_signature(&payload, &account); assert_eq!(result, true); } + + #[test] + pub fn verify_order_signed_by_extension() { + let order_payload_str = "{\"client_order_id\":\"0x7765626170702d000079a87e313975c2490257e1ea808147fd0d7a096930b4c3\",\"user\":\"5Cct7e6gLzXHN35Zc9QYqA1DXPeJFhqt3RiZGzCMzo16JwjC\",\"main_account\":\"5FYr5g1maSsAAw6w98xdAytZ6MEQ8sNPgp3PNLgy9o79kMug\",\"pair\":\"PDEX-3496813586714279103986568049643838918\",\"side\":\"Ask\",\"order_type\":\"LIMIT\",\"quote_order_quantity\":\"0\",\"qty\":\"1\",\"price\":\"1\",\"timestamp\":1714158182636}"; + let signature_payload_str = "{\"Sr25519\":\"32ce7e9d9ca9eb84447a079e5309e313a3a6767211c5b5957d6512825f0d2f00dcccc1ca57cc514e9a82d605431e989b03bbceca29a421e515023f138ea6ff84\"}"; + let payload = serde_json::from_str::(order_payload_str).unwrap(); + let signature = serde_json::from_str::(signature_payload_str).unwrap(); + // Convert to Order type for primitives + let order_details = OrderDetails { payload: payload.clone(), signature: signature.clone() }; + let order: Order = Order::try_from(order_details).unwrap(); + let json_str = serde_json::to_string(&OrderPayload::from(order.clone())).unwrap(); + assert_eq!(json_str, order_payload_str); + let result = signature.verify_extension_signature(&json_str, &payload.main_account); + assert_eq!(order.verify_signature(), true); + } } From 99cf4cc20d97da761fa6f38400edfe86669260f5 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Sat, 27 Apr 2024 01:19:11 +0530 Subject: [PATCH 33/54] chore: add more tests --- primitives/orderbook/src/types.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index 10e104b59..59398b566 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -1078,9 +1078,6 @@ mod tests { // Convert to Order type for primitives let order_details = OrderDetails { payload: payload.clone(), signature: signature.clone() }; let order: Order = Order::try_from(order_details).unwrap(); - let json_str = serde_json::to_string(&OrderPayload::from(order.clone())).unwrap(); - assert_eq!(json_str, order_payload_str); - let result = signature.verify_extension_signature(&json_str, &payload.main_account); assert_eq!(order.verify_signature(), true); } } From 3794939b8b873f24940390710ee3cf8a42faba7d Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Sat, 27 Apr 2024 20:19:32 +0530 Subject: [PATCH 34/54] chore: add more tests --- primitives/orderbook/src/types.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index 59398b566..c22f17ac4 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -1031,7 +1031,10 @@ pub struct ApprovedSnapshot { mod tests { use crate::ingress::{EgressMessages, IngressMessages}; use crate::traits::VerifyExtensionSignature; - use crate::types::{Order, OrderDetails, OrderPayload, UserActions}; + use crate::types::{ + Order, OrderDetails, OrderPayload, UserActions, WithdrawPayloadCallByUser, + WithdrawalDetails, + }; use polkadex_primitives::{AccountId, AssetId}; use rust_decimal::Decimal; use sp_runtime::MultiSignature; @@ -1080,4 +1083,23 @@ mod tests { let order: Order = Order::try_from(order_details).unwrap(); assert_eq!(order.verify_signature(), true); } + + #[test] + pub fn verify_withdrawal_signed_by_extension() { + let withdraw_payload_str = + "{\"asset_id\":{\"asset\":\"PDEX\"},\"amount\":\"1.11111111\",\"timestamp\":1714229288928}"; + let signature_payload_str = + "{\"Sr25519\":\"785ae7c0ece6fb07429689f0b7d30f11e8f612507fbbc4edb3cbc668f7b4d3060a460b32ae2d4fed52b97faf21d9de768881d25711c9141fde40af4d58e57886\"}"; + let payload = + serde_json::from_str::(withdraw_payload_str).unwrap(); + let signature = serde_json::from_str::(signature_payload_str).unwrap(); + const MAIN_ACCOUNT: &str = "5FYr5g1maSsAAw6w98xdAytZ6MEQ8sNPgp3PNLgy9o79kMug"; + let details = WithdrawalDetails { + payload: payload.clone(), + main: AccountId::from_str(MAIN_ACCOUNT).unwrap(), + proxy: AccountId::from_str(MAIN_ACCOUNT).unwrap(), + signature: signature.clone(), + }; + assert_eq!(details.verify_signature(), true); + } } From 238e02b9bcd77b70ccf0cfd56b61e79be97d8cc2 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Sat, 27 Apr 2024 20:44:41 +0530 Subject: [PATCH 35/54] feat: add verify for withdraw request --- primitives/orderbook/src/types.rs | 52 +++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index c22f17ac4..bb771aa9f 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -295,11 +295,32 @@ impl WithdrawalRequest { impl WithdrawalRequest { /// Verifies request payload. pub fn verify(&self) -> bool { - let signer = match Decode::decode(&mut &self.proxy.encode()[..]) { - Ok(signer) => signer, - Err(_) => return false, - }; - self.signature.verify(self.payload.encode().as_ref(), &signer) + // check signature with proxy account + let signer = Decode::decode(&mut &self.proxy.encode()[..]); + let mut result = false; + if let Ok(signer) = signer { + result = self.signature.verify(self.payload.encode().as_ref(), &signer); + } + if result { + return true; + } + log::error!(target:"orderbook","Withdrawal request signature check failed"); + + // check signature with main account + let signer = Decode::decode(&mut &self.main.encode()[..]); + match signer { + Ok(main) => { + let payload_str = serde_json::to_string(&self.payload); + if let Ok(payload_str) = payload_str { + return self.signature.verify_extension_signature(&payload_str, &main); + } + false + }, + Err(err) => { + log::error!(target:"orderbook","Withdrawal request signature check failed {:}", err); + return false; + }, + } } /// Instantiates `AccountAsset` DTO based on owning data. @@ -1033,7 +1054,7 @@ mod tests { use crate::traits::VerifyExtensionSignature; use crate::types::{ Order, OrderDetails, OrderPayload, UserActions, WithdrawPayloadCallByUser, - WithdrawalDetails, + WithdrawalDetails, WithdrawalRequest, }; use polkadex_primitives::{AccountId, AssetId}; use rust_decimal::Decimal; @@ -1102,4 +1123,23 @@ mod tests { }; assert_eq!(details.verify_signature(), true); } + + #[test] + pub fn verify_withdrawal_request_signed_by_extension() { + let withdraw_payload_str = + "{\"asset_id\":{\"asset\":\"PDEX\"},\"amount\":\"1.11111111\",\"timestamp\":1714229288928}"; + let signature_payload_str = + "{\"Sr25519\":\"785ae7c0ece6fb07429689f0b7d30f11e8f612507fbbc4edb3cbc668f7b4d3060a460b32ae2d4fed52b97faf21d9de768881d25711c9141fde40af4d58e57886\"}"; + let payload = + serde_json::from_str::(withdraw_payload_str).unwrap(); + let signature = serde_json::from_str::(signature_payload_str).unwrap(); + const MAIN_ACCOUNT: &str = "5FYr5g1maSsAAw6w98xdAytZ6MEQ8sNPgp3PNLgy9o79kMug"; + let request = WithdrawalRequest { + payload: payload.clone(), + main: AccountId::from_str(MAIN_ACCOUNT).unwrap(), + proxy: AccountId::from_str(MAIN_ACCOUNT).unwrap(), + signature: signature.clone(), + }; + assert_eq!(request.verify(), true); + } } From b0e7bab0f38108348995b4d6c96e13cc6003ed0d Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Sat, 27 Apr 2024 20:50:49 +0530 Subject: [PATCH 36/54] chore: remove withdraw details struct --- primitives/orderbook/src/types.rs | 54 +------------------------------ 1 file changed, 1 insertion(+), 53 deletions(-) diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index bb771aa9f..8d1fbd827 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -1003,39 +1003,6 @@ impl TryFrom for Order { } } -/// Defines withdraw details DTO. -#[derive(Clone, Debug, Encode, Decode, Eq, PartialEq, Serialize, Deserialize)] -pub struct WithdrawalDetails { - /// Withdraw payload. - pub payload: WithdrawPayloadCallByUser, - /// Main account identifier. - pub main: AccountId, - /// Proxy account identifier. - pub proxy: AccountId, - /// Signature. - pub signature: Signature, -} - -impl WithdrawalDetails { - /// Verifies the signature. - pub fn verify_signature(&self) -> bool { - let result = self.signature.verify(self.payload.encode().as_ref(), &self.proxy); - if result { - return true; - } - log::error!(target:"orderbook","Withdrawal signature check failed"); - let payload_str = serde_json::to_string(&self.payload); - if let Ok(payload_str) = payload_str { - let result = self.signature.verify_extension_signature(&payload_str, &self.main); - if result { - return true; - } - } - log::error!(target:"orderbook","Withdrawal extension signature check failed"); - false - } -} - /// Overarching type used by validators when submitting /// their signature for a summary to aggregator #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] @@ -1054,7 +1021,7 @@ mod tests { use crate::traits::VerifyExtensionSignature; use crate::types::{ Order, OrderDetails, OrderPayload, UserActions, WithdrawPayloadCallByUser, - WithdrawalDetails, WithdrawalRequest, + WithdrawalRequest, }; use polkadex_primitives::{AccountId, AssetId}; use rust_decimal::Decimal; @@ -1105,25 +1072,6 @@ mod tests { assert_eq!(order.verify_signature(), true); } - #[test] - pub fn verify_withdrawal_signed_by_extension() { - let withdraw_payload_str = - "{\"asset_id\":{\"asset\":\"PDEX\"},\"amount\":\"1.11111111\",\"timestamp\":1714229288928}"; - let signature_payload_str = - "{\"Sr25519\":\"785ae7c0ece6fb07429689f0b7d30f11e8f612507fbbc4edb3cbc668f7b4d3060a460b32ae2d4fed52b97faf21d9de768881d25711c9141fde40af4d58e57886\"}"; - let payload = - serde_json::from_str::(withdraw_payload_str).unwrap(); - let signature = serde_json::from_str::(signature_payload_str).unwrap(); - const MAIN_ACCOUNT: &str = "5FYr5g1maSsAAw6w98xdAytZ6MEQ8sNPgp3PNLgy9o79kMug"; - let details = WithdrawalDetails { - payload: payload.clone(), - main: AccountId::from_str(MAIN_ACCOUNT).unwrap(), - proxy: AccountId::from_str(MAIN_ACCOUNT).unwrap(), - signature: signature.clone(), - }; - assert_eq!(details.verify_signature(), true); - } - #[test] pub fn verify_withdrawal_request_signed_by_extension() { let withdraw_payload_str = From 4f8064c78f10571de3090b2ef7839ef8ce9175e9 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Sat, 27 Apr 2024 21:08:12 +0530 Subject: [PATCH 37/54] feat: register funding account on new user deposit --- pallets/ocex/src/lib.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index 069bfce18..370c85430 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -1706,12 +1706,16 @@ pub mod pallet { ) -> DispatchResult { ensure!(Self::orderbook_operational_state(), Error::::ExchangeNotOperational); ensure!(>::get().contains(&asset), Error::::TokenNotAllowlisted); - // Check if account is registered - ensure!(>::contains_key(&user), Error::::AccountNotRegistered); ensure!(amount.saturated_into::() <= DEPOSIT_MAX, Error::::AmountOverflow); let converted_amount = Decimal::from(amount.saturated_into::()) .checked_div(Decimal::from(UNIT_BALANCE)) .ok_or(Error::::FailedToConvertDecimaltoBalance)?; + + // if a new user is depositing, then register the user with main account as proxy + if !>::contains_key(&user){ + Self::register_user(user.clone(), user.clone())?; + } + Self::transfer_asset(&user, &Self::get_pallet_account(), amount, asset)?; // Get Storage Map Value if let Some(expected_total_amount) = From d2426613a21cdd696b134bea04b855e85e53d83d Mon Sep 17 00:00:00 2001 From: zktony Date: Sun, 28 Apr 2024 18:22:45 +0530 Subject: [PATCH 38/54] feature:Added new create_parachain_ext --- pallets/rewards/src/lib.rs | 6 ------ pallets/thea-executor/src/lib.rs | 20 ++++++++++++++++++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/pallets/rewards/src/lib.rs b/pallets/rewards/src/lib.rs index 2b52c908c..a68895a8a 100644 --- a/pallets/rewards/src/lib.rs +++ b/pallets/rewards/src/lib.rs @@ -431,12 +431,6 @@ impl Pallet { .saturating_sub(user_reward_info.claim_amount), ); - //ensure the claimable amount is greater than min claimable amount - ensure!( - rewards_claimable.saturated_into::() > MIN_REWARDS_CLAIMABLE_AMOUNT, - Error::::AmountToLowToRedeem - ); - //remove lock T::NativeCurrency::remove_lock(user_reward_info.lock_id, &user); diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index 1222714c0..04d889fd7 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -25,6 +25,8 @@ extern crate core; use frame_support::pallet_prelude::Weight; +use frame_support::traits::fungibles::Create; +use sp_runtime::traits::One; pub use pallet::*; #[cfg(feature = "runtime-benchmarks")] @@ -470,6 +472,19 @@ pub mod pallet { Ok(()) } + + #[pallet::call_index(7)] + #[pallet::weight(< T as Config >::TheaExecWeightInfo::claim_deposit(1))] + #[transactional] + pub fn create_parachain_asset(origin: OriginFor, asset: AssetId, decimal: u8) -> DispatchResult { + T::GovernanceOrigin::ensure_origin(origin)?; + let asset_id = Self::generate_asset_id_for_parachain(asset); + Self::resolve_create(asset_id.into(), Self::thea_account(), 1u128)?; + let metadata = AssetMetadata::new(decimal).ok_or(Error::::InvalidDecimal)?; + >::insert(asset_id, metadata); + Self::deposit_event(Event::::AssetMetadataSet(metadata)); + Ok(()) + } } impl Pallet { @@ -677,6 +692,11 @@ pub mod pallet { )); Ok(()) } + + pub fn generate_asset_id_for_parachain(asset: AssetId) -> u128 { + let asset_id = u128::from_be_bytes(sp_io::hashing::blake2_128(&asset.encode()[..])); + asset_id + } } impl TheaIncomingExecutor for Pallet { From 6dac54374d566be29113e5db3d788c9c579495ac Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Sun, 28 Apr 2024 20:28:03 +0530 Subject: [PATCH 39/54] chore: clippy --- primitives/orderbook/src/types.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index 8d1fbd827..d53c05121 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -318,7 +318,7 @@ impl WithdrawalRequest { }, Err(err) => { log::error!(target:"orderbook","Withdrawal request signature check failed {:}", err); - return false; + false; }, } } From 1d02fa24a414a6aaa85a37a87b91d56c0052ec96 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Sun, 28 Apr 2024 20:28:16 +0530 Subject: [PATCH 40/54] chore: build --- primitives/orderbook/src/types.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index d53c05121..5be6d8557 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -318,7 +318,7 @@ impl WithdrawalRequest { }, Err(err) => { log::error!(target:"orderbook","Withdrawal request signature check failed {:}", err); - false; + false }, } } From 0f85977e02952603636f9dac2e37c93ecc0f45e0 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Mon, 29 Apr 2024 12:48:55 +0530 Subject: [PATCH 41/54] chore: 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 370c85430..2fddfc541 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -1712,7 +1712,7 @@ pub mod pallet { .ok_or(Error::::FailedToConvertDecimaltoBalance)?; // if a new user is depositing, then register the user with main account as proxy - if !>::contains_key(&user){ + if !>::contains_key(&user) { Self::register_user(user.clone(), user.clone())?; } From d51eba53a9125d9c1e9e8c38fd1da0fb57996696 Mon Sep 17 00:00:00 2001 From: zktony Date: Mon, 29 Apr 2024 13:20:41 +0530 Subject: [PATCH 42/54] Added test cases --- pallets/thea-executor/src/lib.rs | 7 ++++--- pallets/thea-executor/src/tests.rs | 23 +++++++++++++++++++---- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index 04d889fd7..c33c8a32e 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -26,6 +26,7 @@ extern crate core; use frame_support::pallet_prelude::Weight; use frame_support::traits::fungibles::Create; +use xcm::v3::AssetId as XcmAssetId; use sp_runtime::traits::One; pub use pallet::*; @@ -73,7 +74,7 @@ pub mod pallet { types::{AssetMetadata, Deposit}, Network, TheaBenchmarkHelper, TheaIncomingExecutor, TheaOutgoingExecutor, NATIVE_NETWORK, }; - use xcm::VersionedMultiLocation; + use xcm::{VersionedMultiLocation, VersionedMultiAsset}; #[pallet::pallet] #[pallet::without_storage_info] @@ -476,7 +477,7 @@ pub mod pallet { #[pallet::call_index(7)] #[pallet::weight(< T as Config >::TheaExecWeightInfo::claim_deposit(1))] #[transactional] - pub fn create_parachain_asset(origin: OriginFor, asset: AssetId, decimal: u8) -> DispatchResult { + pub fn create_parachain_asset(origin: OriginFor, asset: XcmAssetId, decimal: u8) -> DispatchResult { T::GovernanceOrigin::ensure_origin(origin)?; let asset_id = Self::generate_asset_id_for_parachain(asset); Self::resolve_create(asset_id.into(), Self::thea_account(), 1u128)?; @@ -693,7 +694,7 @@ pub mod pallet { Ok(()) } - pub fn generate_asset_id_for_parachain(asset: AssetId) -> u128 { + pub fn generate_asset_id_for_parachain(asset: XcmAssetId) -> u128 { let asset_id = u128::from_be_bytes(sp_io::hashing::blake2_128(&asset.encode()[..])); asset_id } diff --git a/pallets/thea-executor/src/tests.rs b/pallets/thea-executor/src/tests.rs index 2d0e26c7a..f51f87083 100644 --- a/pallets/thea-executor/src/tests.rs +++ b/pallets/thea-executor/src/tests.rs @@ -27,13 +27,13 @@ use frame_support::{ use frame_system::EventRecord; use parity_scale_codec::Encode; use sp_core::H160; -use sp_runtime::{ - traits::{AccountIdConversion, BadOrigin}, - SaturatedConversion, -}; +use sp_runtime::{traits::{AccountIdConversion, BadOrigin}, SaturatedConversion, TokenError}; use thea_primitives::types::NewWithdraw; use thea_primitives::types::{AssetMetadata, Deposit}; use xcm::{opaque::lts::Junctions, v3::MultiLocation, VersionedMultiLocation}; +use frame_support::traits::fungibles::Inspect; +use sp_runtime::legacy::byte_sized_error::DispatchError; +use xcm::v3::Junction; fn assert_last_event(generic_event: ::RuntimeEvent) { let events = frame_system::Pallet::::events(); @@ -517,6 +517,21 @@ fn test_claim_deposit_returns_asset_not_registered() { }) } +#[test] +fn test_create_parachain_asset() { + new_test_ext().execute_with(|| { + let multilocation = MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(100)) }; + let asset = xcm::v3::AssetId::Concrete(multilocation); + assert_ok!(TheaExecutor::create_parachain_asset(RuntimeOrigin::root(), asset, 10)); + let asset_id = TheaExecutor::generate_asset_id_for_parachain(asset); + assert!(Assets::asset_exists(asset_id)); + let expected_metadata = AssetMetadata::new(10); + let actual_metadata = >::get(asset_id); + assert_eq!(expected_metadata, actual_metadata); + assert!(TheaExecutor::create_parachain_asset(RuntimeOrigin::root(), asset, 10).is_err()); + }) +} + fn setup_pool() { let asset_id = 1u128; let admin = 1u64; From e9236fdc2c1a26ba6aa309cff28e6fdfb5063fd3 Mon Sep 17 00:00:00 2001 From: zktony Date: Mon, 29 Apr 2024 13:23:20 +0530 Subject: [PATCH 43/54] Formatted --- pallets/thea-executor/src/lib.rs | 14 +++++++++----- pallets/thea-executor/src/tests.rs | 14 +++++++++----- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index c33c8a32e..bdd81ee20 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -26,9 +26,9 @@ extern crate core; use frame_support::pallet_prelude::Weight; use frame_support::traits::fungibles::Create; -use xcm::v3::AssetId as XcmAssetId; -use sp_runtime::traits::One; pub use pallet::*; +use sp_runtime::traits::One; +use xcm::v3::AssetId as XcmAssetId; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; @@ -74,7 +74,7 @@ pub mod pallet { types::{AssetMetadata, Deposit}, Network, TheaBenchmarkHelper, TheaIncomingExecutor, TheaOutgoingExecutor, NATIVE_NETWORK, }; - use xcm::{VersionedMultiLocation, VersionedMultiAsset}; + use xcm::{VersionedMultiAsset, VersionedMultiLocation}; #[pallet::pallet] #[pallet::without_storage_info] @@ -477,9 +477,13 @@ pub mod pallet { #[pallet::call_index(7)] #[pallet::weight(< T as Config >::TheaExecWeightInfo::claim_deposit(1))] #[transactional] - pub fn create_parachain_asset(origin: OriginFor, asset: XcmAssetId, decimal: u8) -> DispatchResult { + pub fn create_parachain_asset( + origin: OriginFor, + asset: XcmAssetId, + decimal: u8, + ) -> DispatchResult { T::GovernanceOrigin::ensure_origin(origin)?; - let asset_id = Self::generate_asset_id_for_parachain(asset); + let asset_id = Self::generate_asset_id_for_parachain(asset); Self::resolve_create(asset_id.into(), Self::thea_account(), 1u128)?; let metadata = AssetMetadata::new(decimal).ok_or(Error::::InvalidDecimal)?; >::insert(asset_id, metadata); diff --git a/pallets/thea-executor/src/tests.rs b/pallets/thea-executor/src/tests.rs index f51f87083..62691a442 100644 --- a/pallets/thea-executor/src/tests.rs +++ b/pallets/thea-executor/src/tests.rs @@ -20,6 +20,7 @@ use crate::{ mock::{new_test_ext, Assets, Test, *}, PendingWithdrawals, WithdrawalFees, *, }; +use frame_support::traits::fungibles::Inspect; use frame_support::{ assert_noop, assert_ok, traits::{fungible::Mutate as FungibleMutate, fungibles::Mutate as FungiblesMutate}, @@ -27,13 +28,15 @@ use frame_support::{ use frame_system::EventRecord; use parity_scale_codec::Encode; use sp_core::H160; -use sp_runtime::{traits::{AccountIdConversion, BadOrigin}, SaturatedConversion, TokenError}; +use sp_runtime::legacy::byte_sized_error::DispatchError; +use sp_runtime::{ + traits::{AccountIdConversion, BadOrigin}, + SaturatedConversion, TokenError, +}; use thea_primitives::types::NewWithdraw; use thea_primitives::types::{AssetMetadata, Deposit}; -use xcm::{opaque::lts::Junctions, v3::MultiLocation, VersionedMultiLocation}; -use frame_support::traits::fungibles::Inspect; -use sp_runtime::legacy::byte_sized_error::DispatchError; use xcm::v3::Junction; +use xcm::{opaque::lts::Junctions, v3::MultiLocation, VersionedMultiLocation}; fn assert_last_event(generic_event: ::RuntimeEvent) { let events = frame_system::Pallet::::events(); @@ -520,7 +523,8 @@ fn test_claim_deposit_returns_asset_not_registered() { #[test] fn test_create_parachain_asset() { new_test_ext().execute_with(|| { - let multilocation = MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(100)) }; + let multilocation = + MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(100)) }; let asset = xcm::v3::AssetId::Concrete(multilocation); assert_ok!(TheaExecutor::create_parachain_asset(RuntimeOrigin::root(), asset, 10)); let asset_id = TheaExecutor::generate_asset_id_for_parachain(asset); From ca06cfca1085dc384e7174a3fc9d4e3beb1580c2 Mon Sep 17 00:00:00 2001 From: zktony Date: Mon, 29 Apr 2024 13:57:18 +0530 Subject: [PATCH 44/54] Removed unused imports --- pallets/thea-executor/src/lib.rs | 4 +--- pallets/xcm-helper/src/benchmarking.rs | 3 +++ 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index bdd81ee20..f79ab53b7 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -25,9 +25,7 @@ extern crate core; use frame_support::pallet_prelude::Weight; -use frame_support::traits::fungibles::Create; pub use pallet::*; -use sp_runtime::traits::One; use xcm::v3::AssetId as XcmAssetId; #[cfg(feature = "runtime-benchmarks")] @@ -74,7 +72,7 @@ pub mod pallet { types::{AssetMetadata, Deposit}, Network, TheaBenchmarkHelper, TheaIncomingExecutor, TheaOutgoingExecutor, NATIVE_NETWORK, }; - use xcm::{VersionedMultiAsset, VersionedMultiLocation}; + use xcm::VersionedMultiLocation; #[pallet::pallet] #[pallet::without_storage_info] diff --git a/pallets/xcm-helper/src/benchmarking.rs b/pallets/xcm-helper/src/benchmarking.rs index 7960aa457..376e8cea2 100644 --- a/pallets/xcm-helper/src/benchmarking.rs +++ b/pallets/xcm-helper/src/benchmarking.rs @@ -109,6 +109,9 @@ benchmarks! { // assert!(failed_withdrawals.is_empty()); // assert!(withdrawals.is_empty()) // } + + + } #[cfg(test)] From ae8e1aa838e0f9ecc7c3533943a7de9d679512e1 Mon Sep 17 00:00:00 2001 From: zktony Date: Mon, 29 Apr 2024 14:47:53 +0530 Subject: [PATCH 45/54] Fixed clippy warnings --- pallets/thea-executor/src/lib.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index f79ab53b7..098b65441 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -477,7 +477,7 @@ pub mod pallet { #[transactional] pub fn create_parachain_asset( origin: OriginFor, - asset: XcmAssetId, + asset: Box, decimal: u8, ) -> DispatchResult { T::GovernanceOrigin::ensure_origin(origin)?; @@ -696,9 +696,8 @@ pub mod pallet { Ok(()) } - pub fn generate_asset_id_for_parachain(asset: XcmAssetId) -> u128 { - let asset_id = u128::from_be_bytes(sp_io::hashing::blake2_128(&asset.encode()[..])); - asset_id + pub fn generate_asset_id_for_parachain(asset: Box) -> u128 { + u128::from_be_bytes(sp_io::hashing::blake2_128(&asset.encode()[..])) } } From d88e09adf4d4f852195cbee5c286f698f53433c9 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Mon, 29 Apr 2024 15:00:57 +0530 Subject: [PATCH 46/54] fix: tests --- pallets/ocex/src/tests.rs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/pallets/ocex/src/tests.rs b/pallets/ocex/src/tests.rs index c7bf3e04d..dd89e2d47 100644 --- a/pallets/ocex/src/tests.rs +++ b/pallets/ocex/src/tests.rs @@ -1509,15 +1509,13 @@ fn test_deposit_account_not_registered() { let account_id = create_account_id(); new_test_ext().execute_with(|| { assert_ok!(OCEX::set_exchange_state(RuntimeOrigin::root(), true)); - allowlist_token(AssetId::Asset(10)); - assert_noop!( - OCEX::deposit( - RuntimeOrigin::signed(account_id.clone().into()), - AssetId::Asset(10), - 100_u128.into() - ), - Error::::AccountNotRegistered - ); + mint_into_account(account_id.clone()); + assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), AssetId::Polkadex)); + assert_ok!(OCEX::deposit( + RuntimeOrigin::signed(account_id.clone().into()), + AssetId::Polkadex, + 100_u128.into() + )); }); } From 39cc7f4f98176d0b181167696ce9c6ed6ff40fbb Mon Sep 17 00:00:00 2001 From: zktony Date: Mon, 29 Apr 2024 15:29:11 +0530 Subject: [PATCH 47/54] Resolved Gj comment --- Cargo.lock | 1 + pallets/thea-executor/src/lib.rs | 8 ++------ pallets/xcm-helper/src/lib.rs | 3 ++- primitives/polkadex/Cargo.toml | 2 ++ primitives/polkadex/src/assets.rs | 5 +++++ 5 files changed, 12 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 743894dfa..cb3d02d24 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7975,6 +7975,7 @@ dependencies = [ "sp-core", "sp-runtime", "sp-std", + "staging-xcm", ] [[package]] diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index 098b65441..b91932ab4 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -477,11 +477,11 @@ pub mod pallet { #[transactional] pub fn create_parachain_asset( origin: OriginFor, - asset: Box, + asset: sp_std::boxed::Box, decimal: u8, ) -> DispatchResult { T::GovernanceOrigin::ensure_origin(origin)?; - let asset_id = Self::generate_asset_id_for_parachain(asset); + let asset_id = polkadex_primitives::assets::generate_asset_id_for_parachain(asset); Self::resolve_create(asset_id.into(), Self::thea_account(), 1u128)?; let metadata = AssetMetadata::new(decimal).ok_or(Error::::InvalidDecimal)?; >::insert(asset_id, metadata); @@ -695,10 +695,6 @@ pub mod pallet { )); Ok(()) } - - pub fn generate_asset_id_for_parachain(asset: Box) -> u128 { - u128::from_be_bytes(sp_io::hashing::blake2_128(&asset.encode()[..])) - } } impl TheaIncomingExecutor for Pallet { diff --git a/pallets/xcm-helper/src/lib.rs b/pallets/xcm-helper/src/lib.rs index 75ac44201..1b0929b76 100644 --- a/pallets/xcm-helper/src/lib.rs +++ b/pallets/xcm-helper/src/lib.rs @@ -552,7 +552,8 @@ pub mod pallet { return T::NativeAssetId::get().into(); } // If it's not native, then hash and generate the asset id - let asset_id = u128::from_be_bytes(sp_io::hashing::blake2_128(&asset.encode()[..])); + let asset_id = + polkadex_primitives::assets::generate_asset_id_for_parachain(Box::new(asset)); if !>::contains_key(asset_id) { // Store the mapping >::insert(asset_id, asset); diff --git a/primitives/polkadex/Cargo.toml b/primitives/polkadex/Cargo.toml index 3877e18bb..11652d1f2 100644 --- a/primitives/polkadex/Cargo.toml +++ b/primitives/polkadex/Cargo.toml @@ -22,6 +22,7 @@ rust_decimal = { git = "https://github.com/Polkadex-Substrate/rust-decimal.git", "scale-codec", "serde", ], default-features = false } +xcm = { workspace = true, default-features = false } [dev-dependencies] pretty_assertions = "1.2.1" @@ -45,5 +46,6 @@ std = [ "sp-runtime/std", "rust_decimal/std", "rust_decimal/serde", + "xcm/std" ] full_crypto = ['sp-core/full_crypto'] diff --git a/primitives/polkadex/src/assets.rs b/primitives/polkadex/src/assets.rs index 1b83c23cc..e6197d189 100644 --- a/primitives/polkadex/src/assets.rs +++ b/primitives/polkadex/src/assets.rs @@ -20,6 +20,7 @@ use crate::Balance; #[cfg(not(feature = "std"))] use codec::alloc::string::ToString; use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::__private::sp_io; use frame_support::{ ensure, traits::{ @@ -275,6 +276,10 @@ impl<'de> Visitor<'de> for AssetId { } } +pub fn generate_asset_id_for_parachain(asset: sp_std::boxed::Box) -> u128 { + u128::from_be_bytes(sp_io::hashing::blake2_128(&asset.encode()[..])) +} + #[cfg(feature = "std")] impl TryFrom for AssetId { type Error = anyhow::Error; From a0c5c2f9cac2d253e93b056f7e018ad35f9358b5 Mon Sep 17 00:00:00 2001 From: Gautham Date: Mon, 29 Apr 2024 13:21:09 +0300 Subject: [PATCH 48/54] update deposit test --- pallets/ocex/src/tests.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/pallets/ocex/src/tests.rs b/pallets/ocex/src/tests.rs index c7bf3e04d..e75da2f15 100644 --- a/pallets/ocex/src/tests.rs +++ b/pallets/ocex/src/tests.rs @@ -1509,15 +1509,14 @@ fn test_deposit_account_not_registered() { let account_id = create_account_id(); new_test_ext().execute_with(|| { assert_ok!(OCEX::set_exchange_state(RuntimeOrigin::root(), true)); - allowlist_token(AssetId::Asset(10)); - assert_noop!( + mint_into_account(account_id.clone()); + allowlist_token(AssetId::Polkadex); + assert_ok!( OCEX::deposit( RuntimeOrigin::signed(account_id.clone().into()), - AssetId::Asset(10), + AssetId::Polkadex, 100_u128.into() - ), - Error::::AccountNotRegistered - ); + )); }); } From 846fdf8034b6eaba1a4a4eeae2a4ff55f96d1d55 Mon Sep 17 00:00:00 2001 From: Emmanuel Thomas <50878033+nuel77@users.noreply.github.com> Date: Mon, 29 Apr 2024 16:44:52 +0530 Subject: [PATCH 49/54] fix: fmt --- pallets/ocex/src/tests.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/pallets/ocex/src/tests.rs b/pallets/ocex/src/tests.rs index e75da2f15..1ccaf0e7b 100644 --- a/pallets/ocex/src/tests.rs +++ b/pallets/ocex/src/tests.rs @@ -1511,12 +1511,11 @@ fn test_deposit_account_not_registered() { assert_ok!(OCEX::set_exchange_state(RuntimeOrigin::root(), true)); mint_into_account(account_id.clone()); allowlist_token(AssetId::Polkadex); - assert_ok!( - OCEX::deposit( - RuntimeOrigin::signed(account_id.clone().into()), - AssetId::Polkadex, - 100_u128.into() - )); + assert_ok!(OCEX::deposit( + RuntimeOrigin::signed(account_id.clone().into()), + AssetId::Polkadex, + 100_u128.into() + )); }); } From 0a9437fc4641064f438cde04dc54d36a55fcd5f7 Mon Sep 17 00:00:00 2001 From: zktony Date: Mon, 29 Apr 2024 20:00:45 +0530 Subject: [PATCH 50/54] Fixed tests --- pallets/rewards/src/tests.rs | 6 ------ pallets/thea-executor/src/tests.rs | 15 ++++++++++----- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/pallets/rewards/src/tests.rs b/pallets/rewards/src/tests.rs index d5bdd2f24..041835a94 100644 --- a/pallets/rewards/src/tests.rs +++ b/pallets/rewards/src/tests.rs @@ -937,11 +937,5 @@ pub fn claim_rewards_for_alice_at_multiple_intervals() { System::set_block_number( start_block.saturating_add(require_block_to_claim_50_percentage_of_rewards), ); - - // assert_ok!(Rewards::claim(RuntimeOrigin::signed(alice_account.clone()), reward_id)); - disabled since the whole amount is claimed now - assert_noop!( - Rewards::claim(RuntimeOrigin::signed(alice_account), reward_id), - Error::::AmountToLowToRedeem - ); }) } diff --git a/pallets/thea-executor/src/tests.rs b/pallets/thea-executor/src/tests.rs index 62691a442..71ec47daf 100644 --- a/pallets/thea-executor/src/tests.rs +++ b/pallets/thea-executor/src/tests.rs @@ -28,10 +28,9 @@ use frame_support::{ use frame_system::EventRecord; use parity_scale_codec::Encode; use sp_core::H160; -use sp_runtime::legacy::byte_sized_error::DispatchError; use sp_runtime::{ traits::{AccountIdConversion, BadOrigin}, - SaturatedConversion, TokenError, + SaturatedConversion, }; use thea_primitives::types::NewWithdraw; use thea_primitives::types::{AssetMetadata, Deposit}; @@ -526,13 +525,19 @@ fn test_create_parachain_asset() { let multilocation = MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(100)) }; let asset = xcm::v3::AssetId::Concrete(multilocation); - assert_ok!(TheaExecutor::create_parachain_asset(RuntimeOrigin::root(), asset, 10)); - let asset_id = TheaExecutor::generate_asset_id_for_parachain(asset); + assert_ok!(TheaExecutor::create_parachain_asset( + RuntimeOrigin::root(), + Box::new(asset), + 10 + )); + let asset_id = + polkadex_primitives::assets::generate_asset_id_for_parachain(Box::new(asset)); assert!(Assets::asset_exists(asset_id)); let expected_metadata = AssetMetadata::new(10); let actual_metadata = >::get(asset_id); assert_eq!(expected_metadata, actual_metadata); - assert!(TheaExecutor::create_parachain_asset(RuntimeOrigin::root(), asset, 10).is_err()); + assert!(TheaExecutor::create_parachain_asset(RuntimeOrigin::root(), Box::new(asset), 10) + .is_err()); }) } From 078856e6cd43e920e76c7f18844eac526f3aab8a Mon Sep 17 00:00:00 2001 From: zktony Date: Tue, 30 Apr 2024 12:51:05 +0530 Subject: [PATCH 51/54] Fixed Comment --- pallets/thea-executor/src/lib.rs | 10 ++++++++++ pallets/thea-executor/src/tests.rs | 13 +++++++++++-- pallets/xcm-helper/src/lib.rs | 3 ++- primitives/polkadex/src/assets.rs | 11 +++++++++++ 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/pallets/thea-executor/src/lib.rs b/pallets/thea-executor/src/lib.rs index b91932ab4..e1e879090 100644 --- a/pallets/thea-executor/src/lib.rs +++ b/pallets/thea-executor/src/lib.rs @@ -90,6 +90,7 @@ pub mod pallet { /// Assets Pallet type Assets: frame_support::traits::tokens::fungibles::Mutate + frame_support::traits::tokens::fungibles::Create + + frame_support::traits::tokens::fungibles::metadata::Mutate + frame_support::traits::tokens::fungibles::Inspect; /// Asset Id type AssetId: Member @@ -478,11 +479,20 @@ pub mod pallet { pub fn create_parachain_asset( origin: OriginFor, asset: sp_std::boxed::Box, + name: Vec, + symbol: Vec, decimal: u8, ) -> DispatchResult { T::GovernanceOrigin::ensure_origin(origin)?; let asset_id = polkadex_primitives::assets::generate_asset_id_for_parachain(asset); Self::resolve_create(asset_id.into(), Self::thea_account(), 1u128)?; + Self::set_token_metadata( + asset_id.into(), + &Self::thea_account(), + name, + symbol, + decimal, + )?; let metadata = AssetMetadata::new(decimal).ok_or(Error::::InvalidDecimal)?; >::insert(asset_id, metadata); Self::deposit_event(Event::::AssetMetadataSet(metadata)); diff --git a/pallets/thea-executor/src/tests.rs b/pallets/thea-executor/src/tests.rs index 71ec47daf..2cbde072e 100644 --- a/pallets/thea-executor/src/tests.rs +++ b/pallets/thea-executor/src/tests.rs @@ -525,9 +525,12 @@ fn test_create_parachain_asset() { let multilocation = MultiLocation { parents: 1, interior: Junctions::X1(Junction::Parachain(100)) }; let asset = xcm::v3::AssetId::Concrete(multilocation); + Balances::set_balance(&TheaExecutor::thea_account(), 1_000_000_000_000_000_000); assert_ok!(TheaExecutor::create_parachain_asset( RuntimeOrigin::root(), Box::new(asset), + Default::default(), + Default::default(), 10 )); let asset_id = @@ -536,8 +539,14 @@ fn test_create_parachain_asset() { let expected_metadata = AssetMetadata::new(10); let actual_metadata = >::get(asset_id); assert_eq!(expected_metadata, actual_metadata); - assert!(TheaExecutor::create_parachain_asset(RuntimeOrigin::root(), Box::new(asset), 10) - .is_err()); + assert!(TheaExecutor::create_parachain_asset( + RuntimeOrigin::root(), + Box::new(asset), + Default::default(), + Default::default(), + 10 + ) + .is_err()); }) } diff --git a/pallets/xcm-helper/src/lib.rs b/pallets/xcm-helper/src/lib.rs index 1b0929b76..cb6833941 100644 --- a/pallets/xcm-helper/src/lib.rs +++ b/pallets/xcm-helper/src/lib.rs @@ -184,7 +184,8 @@ pub mod pallet { /// Assets type Assets: frame_support::traits::tokens::fungibles::Mutate + frame_support::traits::tokens::fungibles::Create - + frame_support::traits::tokens::fungibles::Inspect; + + frame_support::traits::tokens::fungibles::Inspect + + frame_support::traits::tokens::fungibles::metadata::Mutate; /// Asset Id type AssetId: Member + Parameter diff --git a/primitives/polkadex/src/assets.rs b/primitives/polkadex/src/assets.rs index e6197d189..e51084e31 100644 --- a/primitives/polkadex/src/assets.rs +++ b/primitives/polkadex/src/assets.rs @@ -47,6 +47,7 @@ pub trait Resolver< + frame_support::traits::tokens::fungible::Inspect, Others: frame_support::traits::tokens::fungibles::Mutate + frame_support::traits::tokens::fungibles::Inspect + + frame_support::traits::tokens::fungibles::metadata::Mutate + frame_support::traits::tokens::fungibles::Create, AssetId: Into + sp_std::cmp::PartialEq + Copy, NativeAssetId: Get, @@ -150,6 +151,16 @@ pub trait Resolver< } Ok(()) } + + fn set_token_metadata( + asset: AssetId, + from: &AccountId, + name: sp_std::vec::Vec, + symbol: sp_std::vec::Vec, + decimal: u8, + ) -> Result<(), DispatchError> { + Others::set(asset.into(), from, name, symbol, decimal) + } } /// Enumerated asset on chain From a1c41539a7bacad2122cd78254ed0da5213bd702 Mon Sep 17 00:00:00 2001 From: Gautham Date: Fri, 3 May 2024 15:53:44 +0300 Subject: [PATCH 52/54] 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 acf284e2b..2e707e21e 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: 350, + spec_version: 351, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, From 4f140363bb927b71867e50c374843d306a35386f Mon Sep 17 00:00:00 2001 From: gautham Date: Mon, 6 May 2024 18:33:58 +0530 Subject: [PATCH 53/54] Fix clippy errors --- pallets/ocex/src/lib.rs | 8 ++------ pallets/thea/src/session.rs | 8 ++------ 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index 2fddfc541..5e36b3796 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -2367,9 +2367,7 @@ impl sp_application_crypto::BoundToRuntimeAppPublic for Pallet { impl OneSessionHandler for Pallet { type Key = T::AuthorityId; - fn on_genesis_session<'a, I: 'a>(authorities: I) - where - I: Iterator, + fn on_genesis_session<'a, I: 'a + Iterator>(authorities: I) { let authorities = authorities.map(|(_, k)| k).collect::>(); >::insert( @@ -2378,9 +2376,7 @@ impl OneSessionHandler for Pallet { ); } - fn on_new_session<'a, I: 'a>(_changed: bool, authorities: I, queued_authorities: I) - where - I: Iterator, + fn on_new_session<'a, I: 'a + Iterator>(_changed: bool, authorities: I, queued_authorities: I) { let next_authorities = authorities.map(|(_, k)| k).collect::>(); let next_queued_authorities = queued_authorities.map(|(_, k)| k).collect::>(); diff --git a/pallets/thea/src/session.rs b/pallets/thea/src/session.rs index a1dc54044..cb54e5fa6 100644 --- a/pallets/thea/src/session.rs +++ b/pallets/thea/src/session.rs @@ -28,9 +28,7 @@ impl sp_runtime::BoundToRuntimeAppPublic for Pallet { impl OneSessionHandler for Pallet { type Key = T::TheaId; - fn on_genesis_session<'a, I: 'a>(validators: I) - where - I: Iterator, + fn on_genesis_session<'a, I: 'a + Iterator>(validators: I) { let authorities = validators.map(|(_, k)| k).collect::>(); // we panic here as runtime maintainers can simply reconfigure genesis and restart @@ -38,9 +36,7 @@ impl OneSessionHandler for Pallet { Self::initialize_authorities(&authorities).expect("Authorities vec too big"); } - fn on_new_session<'a, I: 'a>(_changed: bool, validators: I, queued_validators: I) - where - I: Iterator, + fn on_new_session<'a, I: 'a + Iterator>(_changed: bool, validators: I, queued_validators: I) { // A new thea message will be sent on session changes when queued != next. let next_authorities = validators.map(|(_, k)| k).collect::>(); From 6a710e404d0eb7efdb0689f1edf3a55a40616682 Mon Sep 17 00:00:00 2001 From: gautham Date: Mon, 6 May 2024 18:38:25 +0530 Subject: [PATCH 54/54] cargo fmt --- pallets/ocex/src/lib.rs | 12 ++++++++---- pallets/thea/src/session.rs | 12 ++++++++---- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index 5e36b3796..9a5068e98 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -2367,8 +2367,9 @@ impl sp_application_crypto::BoundToRuntimeAppPublic for Pallet { impl OneSessionHandler for Pallet { type Key = T::AuthorityId; - fn on_genesis_session<'a, I: 'a + Iterator>(authorities: I) - { + fn on_genesis_session<'a, I: 'a + Iterator>( + authorities: I, + ) { let authorities = authorities.map(|(_, k)| k).collect::>(); >::insert( GENESIS_AUTHORITY_SET_ID, @@ -2376,8 +2377,11 @@ impl OneSessionHandler for Pallet { ); } - fn on_new_session<'a, I: 'a + Iterator>(_changed: bool, authorities: I, queued_authorities: I) - { + fn on_new_session<'a, I: 'a + Iterator>( + _changed: bool, + authorities: I, + queued_authorities: I, + ) { let next_authorities = authorities.map(|(_, k)| k).collect::>(); let next_queued_authorities = queued_authorities.map(|(_, k)| k).collect::>(); diff --git a/pallets/thea/src/session.rs b/pallets/thea/src/session.rs index cb54e5fa6..38f6899d0 100644 --- a/pallets/thea/src/session.rs +++ b/pallets/thea/src/session.rs @@ -28,16 +28,20 @@ impl sp_runtime::BoundToRuntimeAppPublic for Pallet { impl OneSessionHandler for Pallet { type Key = T::TheaId; - fn on_genesis_session<'a, I: 'a + Iterator>(validators: I) - { + fn on_genesis_session<'a, I: 'a + Iterator>( + validators: I, + ) { let authorities = validators.map(|(_, k)| k).collect::>(); // we panic here as runtime maintainers can simply reconfigure genesis and restart // the chain easily Self::initialize_authorities(&authorities).expect("Authorities vec too big"); } - fn on_new_session<'a, I: 'a + Iterator>(_changed: bool, validators: I, queued_validators: I) - { + fn on_new_session<'a, I: 'a + Iterator>( + _changed: bool, + validators: I, + queued_validators: I, + ) { // A new thea message will be sent on session changes when queued != next. let next_authorities = validators.map(|(_, k)| k).collect::>(); if next_authorities.len() as u32 > T::MaxAuthorities::get() {