From aa8691aa9c583fdf7d18e0f78d44529b71f57d37 Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Tue, 15 Jun 2021 19:04:23 +0800 Subject: [PATCH 01/17] update transaction fee xpallet --- .gitignore | 30 ----------- Cargo.lock | 1 + primitives/rpc/src/lib.rs | 4 +- runtime/chainx/src/lib.rs | 14 +++-- xpallets/assets/rpc/src/lib.rs | 2 +- xpallets/dex/spot/rpc/src/lib.rs | 4 +- xpallets/gateway/common/rpc/src/lib.rs | 2 +- xpallets/mining/asset/rpc/src/lib.rs | 4 +- xpallets/mining/staking/rpc/src/lib.rs | 4 +- xpallets/transaction-fee/rpc/Cargo.toml | 1 + .../rpc/runtime-api/src/lib.rs | 2 +- xpallets/transaction-fee/rpc/src/lib.rs | 30 ++++++++--- xpallets/transaction-fee/src/lib.rs | 27 ++++++---- xpallets/transaction-fee/src/types.rs | 54 ++++++++++--------- 14 files changed, 90 insertions(+), 89 deletions(-) delete mode 100644 .gitignore diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 7091c02f5..000000000 --- a/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -**/target/ -**/*.rs.bk -*.swp -.wasm-binaries -chainx/runtime/wasm/target/ -!runtime/wasm/target/wasm32-unknown-unknown/release/chainx_runtime.compact.wasm -node_modules -**/._* -.vscode/ -.DS_Store -*.o -*.so -*.rlib -*.dll -/target/ -*.exe -**/*.rs.bk -.vs/ -.idea/ -chainx/ -!runtime/chainx -!rpc/src/chainx -bak/ -.chainx/ -.sub/ -log/ - -# for substrate weight -/*.rs -/traits.rs diff --git a/Cargo.lock b/Cargo.lock index a968159e0..f717f5706 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10167,6 +10167,7 @@ dependencies = [ "jsonrpc-core", "jsonrpc-core-client", "jsonrpc-derive", + "pallet-transaction-payment", "pallet-transaction-payment-rpc", "parity-scale-codec", "serde", diff --git a/primitives/rpc/src/lib.rs b/primitives/rpc/src/lib.rs index f42522e12..13ed03f51 100644 --- a/primitives/rpc/src/lib.rs +++ b/primitives/rpc/src/lib.rs @@ -80,10 +80,10 @@ pub type RpcVoteWeight = RpcU128; /// A helper struct for handling u128 serialization/deserialization of RPC. /// See https://github.com/polkadot-js/api/issues/2464 for details (shit!). -#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)] +#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize, Default)] pub struct RpcU128(#[serde(with = "self::serde_num_str")] T); -impl From for RpcU128 { +impl From for RpcU128 { fn from(value: T) -> Self { RpcU128(value) } diff --git a/runtime/chainx/src/lib.rs b/runtime/chainx/src/lib.rs index ecdc7c01f..469d3beef 100644 --- a/runtime/chainx/src/lib.rs +++ b/runtime/chainx/src/lib.rs @@ -1323,8 +1323,12 @@ impl_runtime_apis! { TransactionPayment::query_info(uxt, len) } } - fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment::FeeDetails { - todo!("Migrate ChainX query_fee_details") + fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment_rpc_runtime_api::FeeDetails { + //todo!("Migrate ChainX query_fee_details") + //In https://github.com/paritytech/substrate/blob/master/frame/transaction-payment/rpc/runtime-api/src/lib.rs , the function(query_fee_details) + //in trait(TransactionPaymentApi) returns the result FeeDetails which has been defined in frame before , so there is no need to take + // care of the property extra_fee,maybe the function here is useless.. + TransactionPayment::query_fee_details(uxt, len) } } @@ -1334,11 +1338,11 @@ impl_runtime_apis! { len: u32, ) -> xpallet_transaction_fee::FeeDetails { if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let details = XTransactionFee::query_fee_details(uxt, len); + let partial_details = XTransactionFee::query_fee_details(uxt, len); xpallet_transaction_fee::FeeDetails { extra_fee, - final_fee: details.final_fee + extra_fee, - ..details + final_fee: partial_details.final_fee + extra_fee, + ..partial_details } } else { XTransactionFee::query_fee_details(uxt, len) diff --git a/xpallets/assets/rpc/src/lib.rs b/xpallets/assets/rpc/src/lib.rs index be1adddc6..e6669b01f 100644 --- a/xpallets/assets/rpc/src/lib.rs +++ b/xpallets/assets/rpc/src/lib.rs @@ -64,7 +64,7 @@ where C::Api: XAssetsRuntimeApi, Block: BlockT, AccountId: Clone + Display + Codec, - Balance: Clone + Copy + Display + FromStr + Codec + Zero, + Balance: Clone + Copy + Display + FromStr + Codec + Zero + Default, { fn assets_by_account( &self, diff --git a/xpallets/dex/spot/rpc/src/lib.rs b/xpallets/dex/spot/rpc/src/lib.rs index 3ff79c5f1..d2f60407d 100644 --- a/xpallets/dex/spot/rpc/src/lib.rs +++ b/xpallets/dex/spot/rpc/src/lib.rs @@ -92,9 +92,9 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XSpotRuntimeApi, AccountId: Codec, - Balance: Codec + Display + FromStr, + Balance: Codec + Display + FromStr + Default, BlockNumber: Codec, - Price: Codec + Display + FromStr, + Price: Codec + Display + FromStr + Default, { fn trading_pairs( &self, diff --git a/xpallets/gateway/common/rpc/src/lib.rs b/xpallets/gateway/common/rpc/src/lib.rs index 56bee89c8..893d34abc 100644 --- a/xpallets/gateway/common/rpc/src/lib.rs +++ b/xpallets/gateway/common/rpc/src/lib.rs @@ -171,7 +171,7 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XGatewayCommonRuntimeApi, AccountId: Codec + Send + Sync + 'static, - Balance: Codec + Display + FromStr + Send + Sync + 'static + From, + Balance: Codec + Display + FromStr + Send + Sync + 'static + From + Default, { fn bound_addrs( &self, diff --git a/xpallets/mining/asset/rpc/src/lib.rs b/xpallets/mining/asset/rpc/src/lib.rs index 9e363afba..9bfd727cb 100644 --- a/xpallets/mining/asset/rpc/src/lib.rs +++ b/xpallets/mining/asset/rpc/src/lib.rs @@ -85,8 +85,8 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XMiningAssetRuntimeApi, AccountId: Codec, - Balance: Codec + Display + FromStr, - MiningWeight: Codec + Display + FromStr, + Balance: Codec + Display + FromStr + Default, + MiningWeight: Codec + Display + FromStr + Default, BlockNumber: Codec, { fn mining_assets( diff --git a/xpallets/mining/staking/rpc/src/lib.rs b/xpallets/mining/staking/rpc/src/lib.rs index 2df4ea0e3..e2864bab2 100644 --- a/xpallets/mining/staking/rpc/src/lib.rs +++ b/xpallets/mining/staking/rpc/src/lib.rs @@ -100,8 +100,8 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XStakingRuntimeApi, AccountId: Codec + Ord, - Balance: Codec + Display + FromStr, - VoteWeight: Codec + Display + FromStr, + Balance: Codec + Display + FromStr + Default, + VoteWeight: Codec + Display + FromStr + Default, BlockNumber: Codec, { fn validators( diff --git a/xpallets/transaction-fee/rpc/Cargo.toml b/xpallets/transaction-fee/rpc/Cargo.toml index 7a23cf50b..ed5f412a2 100644 --- a/xpallets/transaction-fee/rpc/Cargo.toml +++ b/xpallets/transaction-fee/rpc/Cargo.toml @@ -22,6 +22,7 @@ sp-runtime = "3.0.0" # Substrate pallets pallet-transaction-payment-rpc = "3.0.0" +pallet-transaction-payment = { version = "3.0.0", default-features = false } xp-rpc = { path = "../../../primitives/rpc" } diff --git a/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs b/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs index 1719b6587..4c8a2a0b5 100644 --- a/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs +++ b/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs @@ -10,7 +10,7 @@ use sp_runtime::traits::{MaybeDisplay, MaybeFromStr}; pub use xpallet_transaction_fee::{FeeDetails, InclusionFee}; sp_api::decl_runtime_apis! { - pub trait XTransactionFeeApi where + pub trait XTransactionFeeApi where Balance: Codec + MaybeDisplay + MaybeFromStr, { fn query_fee_details(uxt: Block::Extrinsic, len: u32) -> FeeDetails; diff --git a/xpallets/transaction-fee/rpc/src/lib.rs b/xpallets/transaction-fee/rpc/src/lib.rs index 10dd84440..cb4933120 100644 --- a/xpallets/transaction-fee/rpc/src/lib.rs +++ b/xpallets/transaction-fee/rpc/src/lib.rs @@ -52,7 +52,7 @@ where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XTransactionFeeRuntimeApi, - Balance: Codec + MaybeDisplay + MaybeFromStr, + Balance: Codec + MaybeDisplay + MaybeFromStr + Default, { fn query_fee_details( &self, @@ -68,12 +68,28 @@ where api.query_fee_details(&at, uxt, encoded_len) .map(|fee_details| FeeDetails { - inclusion_fee: fee_details.inclusion_fee.map(|fee| InclusionFee { - base_fee: fee.base_fee.into(), - len_fee: fee.len_fee.into(), - adjusted_weight_fee: fee.adjusted_weight_fee.into(), - }), - tip: fee_details.tip.into(), + // inclusion_fee: fee_details.inclusion_fee.map(|fee| InclusionFee { + // base_fee: fee.base_fee.into(), + // len_fee: fee.len_fee.into(), + // adjusted_weight_fee: fee.adjusted_weight_fee.into(), + // }), + // tip: fee_details.tip.into(), + // partial_details: {inclusion_fee: fee_details.partial_details.inclusion_fee.map(|fee| InclusionFee { + // base_fee: fee.base_fee.into(), + // len_fee: fee.len_fee.into(), + // adjusted_weight_fee: fee.adjusted_weight_fee.into(), + // }), + // tip: fee_details.partial_details.tip.into()}, + partial_details: pallet_transaction_payment::FeeDetails { + inclusion_fee: fee_details.partial_details.inclusion_fee.map(|fee| { + pallet_transaction_payment::InclusionFee { + base_fee: fee.base_fee.into(), + len_fee: fee.len_fee.into(), + adjusted_weight_fee: fee.adjusted_weight_fee.into(), + } + }), + tip: fee_details.partial_details.tip.into(), + }, extra_fee: fee_details.extra_fee.into(), final_fee: fee_details.final_fee.into(), }) diff --git a/xpallets/transaction-fee/src/lib.rs b/xpallets/transaction-fee/src/lib.rs index 3f9e9c348..09fd5f893 100644 --- a/xpallets/transaction-fee/src/lib.rs +++ b/xpallets/transaction-fee/src/lib.rs @@ -13,10 +13,11 @@ mod types; +use codec::DecodeLimit; use sp_std::prelude::*; use frame_support::{ - decl_event, decl_module, + decl_event, decl_module, pallet, traits::Get, weights::{ DispatchClass, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, Weight, @@ -28,7 +29,8 @@ use sp_runtime::{ FixedPointNumber, FixedPointOperand, }; -pub use self::types::{FeeDetails, InclusionFee}; +pub use self::types::FeeDetails; +pub use pallet_transaction_payment::InclusionFee; type BalanceOf = <::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction>::Balance; @@ -123,6 +125,7 @@ where // the adjustable part of the fee. let unadjusted_weight_fee = Self::weight_to_fee(weight); + let multiplier = pallet_transaction_payment::Module::::next_fee_multiplier(); // final adjusted weight fee. let adjusted_weight_fee = multiplier.saturating_mul_int(unadjusted_weight_fee); @@ -134,19 +137,23 @@ where .saturating_add(tip); FeeDetails { - inclusion_fee: Some(InclusionFee { - base_fee, - len_fee: fixed_len_fee, - adjusted_weight_fee, - }), - tip, + partial_details: pallet_transaction_payment::FeeDetails { + inclusion_fee: Some(pallet_transaction_payment::InclusionFee { + base_fee, + len_fee: fixed_len_fee, + adjusted_weight_fee, + }), + tip, + }, extra_fee: 0u32.into(), final_fee: total, } } else { FeeDetails { - inclusion_fee: None, - tip, + partial_details: pallet_transaction_payment::FeeDetails { + inclusion_fee: None, + tip, + }, extra_fee: 0u32.into(), final_fee: tip, } diff --git a/xpallets/transaction-fee/src/types.rs b/xpallets/transaction-fee/src/types.rs index df3e29021..324fe2f8d 100644 --- a/xpallets/transaction-fee/src/types.rs +++ b/xpallets/transaction-fee/src/types.rs @@ -6,29 +6,30 @@ use serde::{Deserialize, Serialize}; use sp_runtime::RuntimeDebug; -/// The base fee and adjusted weight and length fees constitute the _inclusion fee,_ which is -/// the minimum fee for a transaction to be included in a block. -/// -/// ```ignore -/// inclusion_fee = base_fee + len_fee + [targeted_fee_adjustment * weight_fee]; -/// ``` -#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -pub struct InclusionFee { - /// This is the minimum amount a user pays for a transaction. It is declared - /// as a base _weight_ in the runtime and converted to a fee using `WeightToFee`. - pub base_fee: Balance, - /// The length fee, the amount paid for the encoded length (in bytes) of the transaction. - pub len_fee: Balance, - /// - `targeted_fee_adjustment`: This is a multiplier that can tune the final fee based on - /// the congestion of the network. - /// - `weight_fee`: This amount is computed based on the weight of the transaction. Weight - /// accounts for the execution time of a transaction. - /// - /// adjusted_weight_fee = targeted_fee_adjustment * weight_fee - pub adjusted_weight_fee: Balance, -} +// replace by the struct InclusionFee in substrate frame +// /// The base fee and adjusted weight and length fees constitute the _inclusion fee,_ which is +// /// the minimum fee for a transaction to be included in a block. +// /// +// /// ```ignore +// /// inclusion_fee = base_fee + len_fee + [targeted_fee_adjustment * weight_fee]; +// /// ``` +// #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)] +// #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +// #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] +// pub struct InclusionFee { +// /// This is the minimum amount a user pays for a transaction. It is declared +// /// as a base _weight_ in the runtime and converted to a fee using `WeightToFee`. +// pub base_fee: Balance, +// /// The length fee, the amount paid for the encoded length (in bytes) of the transaction. +// pub len_fee: Balance, +// /// - `targeted_fee_adjustment`: This is a multiplier that can tune the final fee based on +// /// the congestion of the network. +// /// - `weight_fee`: This amount is computed based on the weight of the transaction. Weight +// /// accounts for the execution time of a transaction. +// /// +// /// adjusted_weight_fee = targeted_fee_adjustment * weight_fee +// pub adjusted_weight_fee: Balance, +// } /// The `final_fee` is composed of: /// - (Optional) `inclusion_fee`: Only the `Pays::Yes` transaction can have the inclusion fee. @@ -41,10 +42,11 @@ pub struct InclusionFee { #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -pub struct FeeDetails { - pub inclusion_fee: Option>, +pub struct FeeDetails { /// Some calls might be charged extra fee besides the essential `inclusion_fee`. + /// use the struct Feedetails in substrate instead of the previous protery inclusion_fee and tip + pub partial_details: pallet_transaction_payment::FeeDetails, pub extra_fee: Balance, - pub tip: Balance, pub final_fee: Balance, } + From 7230b6fea409a79fd21ac6c6ee17998de5dd33a4 Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Wed, 16 Jun 2021 09:48:31 +0800 Subject: [PATCH 02/17] update transaction fee xpallet --- xpallets/transaction-fee/src/types.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/xpallets/transaction-fee/src/types.rs b/xpallets/transaction-fee/src/types.rs index 324fe2f8d..f6e1db215 100644 --- a/xpallets/transaction-fee/src/types.rs +++ b/xpallets/transaction-fee/src/types.rs @@ -49,4 +49,3 @@ pub struct FeeDetails { pub extra_fee: Balance, pub final_fee: Balance, } - From 9d68d890e3188255f999758b48d2bb7ec5bc8b52 Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Wed, 16 Jun 2021 10:17:17 +0800 Subject: [PATCH 03/17] Update transaction fee xpallet --- .gitignore | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..7091c02f5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ +**/target/ +**/*.rs.bk +*.swp +.wasm-binaries +chainx/runtime/wasm/target/ +!runtime/wasm/target/wasm32-unknown-unknown/release/chainx_runtime.compact.wasm +node_modules +**/._* +.vscode/ +.DS_Store +*.o +*.so +*.rlib +*.dll +/target/ +*.exe +**/*.rs.bk +.vs/ +.idea/ +chainx/ +!runtime/chainx +!rpc/src/chainx +bak/ +.chainx/ +.sub/ +log/ + +# for substrate weight +/*.rs +/traits.rs From 5339958650ee391108676bbf842614dd7b7d7a4c Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Thu, 17 Jun 2021 11:45:27 +0800 Subject: [PATCH 04/17] Update transaction fee xpallet & Migrate xpallet-transaction-fee --- runtime/chainx/src/lib.rs | 14 ++++---- runtime/dev/src/lib.rs | 4 ++- runtime/malan/src/lib.rs | 4 ++- xpallets/transaction-fee/rpc/src/lib.rs | 20 +++-------- xpallets/transaction-fee/src/lib.rs | 45 +++++++++++++++---------- xpallets/transaction-fee/src/types.rs | 28 +-------------- 6 files changed, 45 insertions(+), 70 deletions(-) diff --git a/runtime/chainx/src/lib.rs b/runtime/chainx/src/lib.rs index 469d3beef..07a903bc6 100644 --- a/runtime/chainx/src/lib.rs +++ b/runtime/chainx/src/lib.rs @@ -391,7 +391,9 @@ impl pallet_transaction_payment::Config for Runtime { type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; } -impl xpallet_transaction_fee::Config for Runtime {} +impl xpallet_transaction_fee::Config for Runtime { + type Event = Event; +} parameter_types! { pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_BLOCKS; @@ -1324,10 +1326,6 @@ impl_runtime_apis! { } } fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment_rpc_runtime_api::FeeDetails { - //todo!("Migrate ChainX query_fee_details") - //In https://github.com/paritytech/substrate/blob/master/frame/transaction-payment/rpc/runtime-api/src/lib.rs , the function(query_fee_details) - //in trait(TransactionPaymentApi) returns the result FeeDetails which has been defined in frame before , so there is no need to take - // care of the property extra_fee,maybe the function here is useless.. TransactionPayment::query_fee_details(uxt, len) } } @@ -1338,11 +1336,11 @@ impl_runtime_apis! { len: u32, ) -> xpallet_transaction_fee::FeeDetails { if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let partial_details = XTransactionFee::query_fee_details(uxt, len); + let base = XTransactionFee::query_fee_details(uxt, len); xpallet_transaction_fee::FeeDetails { extra_fee, - final_fee: partial_details.final_fee + extra_fee, - ..partial_details + final_fee: base.final_fee + extra_fee, + ..base } } else { XTransactionFee::query_fee_details(uxt, len) diff --git a/runtime/dev/src/lib.rs b/runtime/dev/src/lib.rs index 223f15bbd..18c08deaf 100644 --- a/runtime/dev/src/lib.rs +++ b/runtime/dev/src/lib.rs @@ -396,7 +396,9 @@ impl pallet_transaction_payment::Config for Runtime { type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; } -impl xpallet_transaction_fee::Config for Runtime {} +impl xpallet_transaction_fee::Config for Runtime { + type Event = Event; +} parameter_types! { pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_BLOCKS; diff --git a/runtime/malan/src/lib.rs b/runtime/malan/src/lib.rs index 3b191122a..fdb592cee 100644 --- a/runtime/malan/src/lib.rs +++ b/runtime/malan/src/lib.rs @@ -391,7 +391,9 @@ impl pallet_transaction_payment::Config for Runtime { type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; } -impl xpallet_transaction_fee::Config for Runtime {} +impl xpallet_transaction_fee::Config for Runtime { + type Event = Event; +} parameter_types! { pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_BLOCKS; diff --git a/xpallets/transaction-fee/rpc/src/lib.rs b/xpallets/transaction-fee/rpc/src/lib.rs index cb4933120..04f5580dd 100644 --- a/xpallets/transaction-fee/rpc/src/lib.rs +++ b/xpallets/transaction-fee/rpc/src/lib.rs @@ -20,7 +20,7 @@ use sp_runtime::{ use pallet_transaction_payment_rpc::Error; use xp_rpc::RpcBalance; -use xpallet_transaction_fee_rpc_runtime_api::{FeeDetails, InclusionFee}; +use xpallet_transaction_fee_rpc_runtime_api::FeeDetails; pub use xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi as XTransactionFeeRuntimeApi; @@ -68,27 +68,15 @@ where api.query_fee_details(&at, uxt, encoded_len) .map(|fee_details| FeeDetails { - // inclusion_fee: fee_details.inclusion_fee.map(|fee| InclusionFee { - // base_fee: fee.base_fee.into(), - // len_fee: fee.len_fee.into(), - // adjusted_weight_fee: fee.adjusted_weight_fee.into(), - // }), - // tip: fee_details.tip.into(), - // partial_details: {inclusion_fee: fee_details.partial_details.inclusion_fee.map(|fee| InclusionFee { - // base_fee: fee.base_fee.into(), - // len_fee: fee.len_fee.into(), - // adjusted_weight_fee: fee.adjusted_weight_fee.into(), - // }), - // tip: fee_details.partial_details.tip.into()}, - partial_details: pallet_transaction_payment::FeeDetails { - inclusion_fee: fee_details.partial_details.inclusion_fee.map(|fee| { + base: pallet_transaction_payment::FeeDetails { + inclusion_fee: fee_details.base.inclusion_fee.map(|fee| { pallet_transaction_payment::InclusionFee { base_fee: fee.base_fee.into(), len_fee: fee.len_fee.into(), adjusted_weight_fee: fee.adjusted_weight_fee.into(), } }), - tip: fee_details.partial_details.tip.into(), + tip: fee_details.base.tip.into(), }, extra_fee: fee_details.extra_fee.into(), final_fee: fee_details.final_fee.into(), diff --git a/xpallets/transaction-fee/src/lib.rs b/xpallets/transaction-fee/src/lib.rs index 09fd5f893..9c7897c6d 100644 --- a/xpallets/transaction-fee/src/lib.rs +++ b/xpallets/transaction-fee/src/lib.rs @@ -17,7 +17,7 @@ use codec::DecodeLimit; use sp_std::prelude::*; use frame_support::{ - decl_event, decl_module, pallet, + //decl_event, decl_module, pallet, traits::Get, weights::{ DispatchClass, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, Weight, @@ -34,26 +34,37 @@ pub use pallet_transaction_payment::InclusionFee; type BalanceOf = <::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction>::Balance; -pub trait Config: pallet_transaction_payment::Config {} +pub use pallet::*; -decl_module! { - pub struct Module for enum Call where origin: T::Origin {} -} +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; -decl_event!( - /// Event for the XTransactionFee Module - pub enum Event - where - Balance = BalanceOf, - ::AccountId, - { + #[pallet::pallet] + #[pallet::generate_store(pub(crate) trait Store)] + pub struct Pallet(PhantomData); + + #[pallet::config] + pub trait Config: frame_system::Config + pallet_transaction_payment::Config { + type Event: From> + IsType<::Event>; + } + + #[pallet::call] + impl Pallet {} + + #[pallet::event] + #[pallet::metadata(T::AccountId = "AccountId", BalanceOf = "Balance")] // Optional + #[pallet::generate_deposit(pub(super) fn deposit_event)] // Optional + pub enum Event { /// Transaction fee was paid to the block author and its reward pot in 1:9. /// [author, author_fee, reward_pot, reward_pot_fee] - FeePaid(AccountId, Balance, AccountId, Balance), + FeePaid(T::AccountId, BalanceOf, T::AccountId, BalanceOf), } -); +} -impl Module +impl Pallet where BalanceOf: FixedPointOperand, { @@ -137,7 +148,7 @@ where .saturating_add(tip); FeeDetails { - partial_details: pallet_transaction_payment::FeeDetails { + base: pallet_transaction_payment::FeeDetails { inclusion_fee: Some(pallet_transaction_payment::InclusionFee { base_fee, len_fee: fixed_len_fee, @@ -150,7 +161,7 @@ where } } else { FeeDetails { - partial_details: pallet_transaction_payment::FeeDetails { + base: pallet_transaction_payment::FeeDetails { inclusion_fee: None, tip, }, diff --git a/xpallets/transaction-fee/src/types.rs b/xpallets/transaction-fee/src/types.rs index f6e1db215..574319467 100644 --- a/xpallets/transaction-fee/src/types.rs +++ b/xpallets/transaction-fee/src/types.rs @@ -6,31 +6,6 @@ use serde::{Deserialize, Serialize}; use sp_runtime::RuntimeDebug; -// replace by the struct InclusionFee in substrate frame -// /// The base fee and adjusted weight and length fees constitute the _inclusion fee,_ which is -// /// the minimum fee for a transaction to be included in a block. -// /// -// /// ```ignore -// /// inclusion_fee = base_fee + len_fee + [targeted_fee_adjustment * weight_fee]; -// /// ``` -// #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)] -// #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -// #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -// pub struct InclusionFee { -// /// This is the minimum amount a user pays for a transaction. It is declared -// /// as a base _weight_ in the runtime and converted to a fee using `WeightToFee`. -// pub base_fee: Balance, -// /// The length fee, the amount paid for the encoded length (in bytes) of the transaction. -// pub len_fee: Balance, -// /// - `targeted_fee_adjustment`: This is a multiplier that can tune the final fee based on -// /// the congestion of the network. -// /// - `weight_fee`: This amount is computed based on the weight of the transaction. Weight -// /// accounts for the execution time of a transaction. -// /// -// /// adjusted_weight_fee = targeted_fee_adjustment * weight_fee -// pub adjusted_weight_fee: Balance, -// } - /// The `final_fee` is composed of: /// - (Optional) `inclusion_fee`: Only the `Pays::Yes` transaction can have the inclusion fee. /// - (Optional) `tip`: If included in the transaction, the tip will be added on top. Only @@ -44,8 +19,7 @@ use sp_runtime::RuntimeDebug; #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] pub struct FeeDetails { /// Some calls might be charged extra fee besides the essential `inclusion_fee`. - /// use the struct Feedetails in substrate instead of the previous protery inclusion_fee and tip - pub partial_details: pallet_transaction_payment::FeeDetails, + pub base: pallet_transaction_payment::FeeDetails, pub extra_fee: Balance, pub final_fee: Balance, } From 7c55ec93fb654f71e38f8591897b6c431b90dee0 Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Thu, 17 Jun 2021 15:33:50 +0800 Subject: [PATCH 05/17] Remove functions in lib.rs --- xpallets/transaction-fee/src/lib.rs | 111 ++++++---------------------- 1 file changed, 22 insertions(+), 89 deletions(-) diff --git a/xpallets/transaction-fee/src/lib.rs b/xpallets/transaction-fee/src/lib.rs index 9c7897c6d..b69bdf4a2 100644 --- a/xpallets/transaction-fee/src/lib.rs +++ b/xpallets/transaction-fee/src/lib.rs @@ -80,101 +80,34 @@ where ) -> FeeDetails> where T: Send + Sync, - BalanceOf: Send + Sync, + BalanceOf: Send + Sync + Default, T::Call: Dispatchable, { let dispatch_info = ::get_dispatch_info(&unchecked_extrinsic); - Self::compute_fee(len, &dispatch_info, 0u32.into()) - } - - pub fn compute_fee( - len: u32, - info: &DispatchInfoOf, - tip: BalanceOf, - ) -> FeeDetails> - where - T::Call: Dispatchable, - { - Self::compute_fee_raw(len, info.weight, tip, info.pays_fee, info.class) - } - - /// Returns the details of the actual post dispatch fee for a particular transaction. - /// - /// Identical to `compute_fee_details` with the only difference that the post dispatch corrected - /// weight is used for the weight fee calculation. - pub fn compute_actual_fee_details( - len: u32, - info: &DispatchInfoOf, - post_info: &PostDispatchInfoOf, - tip: BalanceOf, - ) -> FeeDetails> - where - T::Call: Dispatchable, - { - Self::compute_fee_raw( + let details = pallet_transaction_payment::Module::::compute_fee_details( len, - post_info.calc_actual_weight(info), - tip, - post_info.pays_fee(info), - info.class, - ) - } - - fn compute_fee_raw( - len: u32, - weight: Weight, - tip: BalanceOf, - pays_fee: Pays, - class: DispatchClass, - ) -> FeeDetails> { - if pays_fee == Pays::Yes { - let len = >::from(len); - let per_byte = T::TransactionByteFee::get(); - - // length fee. this is not adjusted. - let fixed_len_fee = per_byte.saturating_mul(len); - - // the adjustable part of the fee. - let unadjusted_weight_fee = Self::weight_to_fee(weight); - - let multiplier = pallet_transaction_payment::Module::::next_fee_multiplier(); - // final adjusted weight fee. - let adjusted_weight_fee = multiplier.saturating_mul_int(unadjusted_weight_fee); - - let base_fee = Self::weight_to_fee(T::BlockWeights::get().get(class).base_extrinsic); - let total = base_fee - .saturating_add(fixed_len_fee) - .saturating_add(adjusted_weight_fee) - .saturating_add(tip); - - FeeDetails { - base: pallet_transaction_payment::FeeDetails { - inclusion_fee: Some(pallet_transaction_payment::InclusionFee { - base_fee, - len_fee: fixed_len_fee, - adjusted_weight_fee, - }), - tip, - }, - extra_fee: 0u32.into(), - final_fee: total, + &dispatch_info, + 0u32.into(), + ); + let details_clone = details.clone(); + match details.inclusion_fee { + Some(fee) => { + let total = fee + .base_fee + .saturating_add(fee.len_fee) + .saturating_add(fee.adjusted_weight_fee) + .saturating_add(details.tip); + FeeDetails { + base: details_clone, + extra_fee: 0u32.into(), + final_fee: total, + } } - } else { - FeeDetails { - base: pallet_transaction_payment::FeeDetails { - inclusion_fee: None, - tip, - }, + None => FeeDetails { + base: details_clone, extra_fee: 0u32.into(), - final_fee: tip, - } + final_fee: details.tip, + }, } } - - fn weight_to_fee(weight: Weight) -> BalanceOf { - // cap the weight to the maximum defined in runtime, otherwise it will be the - // `Bounded` maximum of its data type, which is not desired. - let capped_weight = weight.min(T::BlockWeights::get().max_block); - T::WeightToFee::calc(&capped_weight) - } } From ea455a85b7fe4b0ca10eaebbae4a15b67f4e6f2a Mon Sep 17 00:00:00 2001 From: Alan WANG Date: Thu, 17 Jun 2021 18:28:54 +0800 Subject: [PATCH 06/17] Remove `Default` trait bound --- primitives/rpc/src/lib.rs | 4 ++-- runtime/chainx/src/lib.rs | 9 +++++---- runtime/dev/src/lib.rs | 2 +- runtime/malan/src/lib.rs | 2 +- xpallets/assets/rpc/src/lib.rs | 2 +- xpallets/dex/spot/rpc/src/lib.rs | 4 ++-- xpallets/gateway/common/rpc/src/lib.rs | 2 +- xpallets/mining/asset/rpc/src/lib.rs | 4 ++-- xpallets/mining/staking/rpc/src/lib.rs | 4 ++-- xpallets/transaction-fee/rpc/src/lib.rs | 18 ++++++++---------- xpallets/transaction-fee/src/lib.rs | 23 ++++++++--------------- xpallets/transaction-fee/src/types.rs | 10 +++++++--- 12 files changed, 40 insertions(+), 44 deletions(-) diff --git a/primitives/rpc/src/lib.rs b/primitives/rpc/src/lib.rs index 13ed03f51..f42522e12 100644 --- a/primitives/rpc/src/lib.rs +++ b/primitives/rpc/src/lib.rs @@ -80,10 +80,10 @@ pub type RpcVoteWeight = RpcU128; /// A helper struct for handling u128 serialization/deserialization of RPC. /// See https://github.com/polkadot-js/api/issues/2464 for details (shit!). -#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize, Default)] +#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)] pub struct RpcU128(#[serde(with = "self::serde_num_str")] T); -impl From for RpcU128 { +impl From for RpcU128 { fn from(value: T) -> Self { RpcU128(value) } diff --git a/runtime/chainx/src/lib.rs b/runtime/chainx/src/lib.rs index 07a903bc6..92bce83d1 100644 --- a/runtime/chainx/src/lib.rs +++ b/runtime/chainx/src/lib.rs @@ -1325,7 +1325,7 @@ impl_runtime_apis! { TransactionPayment::query_info(uxt, len) } } - fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment_rpc_runtime_api::FeeDetails { + fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment::FeeDetails { TransactionPayment::query_fee_details(uxt, len) } } @@ -1335,12 +1335,13 @@ impl_runtime_apis! { uxt: ::Extrinsic, len: u32, ) -> xpallet_transaction_fee::FeeDetails { + todo!("migrate"); if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let base = XTransactionFee::query_fee_details(uxt, len); + let details = XTransactionFee::query_fee_details(uxt, len); xpallet_transaction_fee::FeeDetails { extra_fee, - final_fee: base.final_fee + extra_fee, - ..base + final_fee: details.final_fee + extra_fee, + ..details } } else { XTransactionFee::query_fee_details(uxt, len) diff --git a/runtime/dev/src/lib.rs b/runtime/dev/src/lib.rs index 18c08deaf..860b8ecee 100644 --- a/runtime/dev/src/lib.rs +++ b/runtime/dev/src/lib.rs @@ -1336,7 +1336,7 @@ impl_runtime_apis! { } } fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment::FeeDetails { - todo!("Migrate ChainX query_fee_details") + TransactionPayment::query_fee_details(uxt, len) } } diff --git a/runtime/malan/src/lib.rs b/runtime/malan/src/lib.rs index fdb592cee..beba818a4 100644 --- a/runtime/malan/src/lib.rs +++ b/runtime/malan/src/lib.rs @@ -1333,7 +1333,7 @@ impl_runtime_apis! { } } fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment::FeeDetails { - todo!("Migrate ChainX query_fee_details") + TransactionPayment::query_fee_details(uxt, len) } } diff --git a/xpallets/assets/rpc/src/lib.rs b/xpallets/assets/rpc/src/lib.rs index e6669b01f..be1adddc6 100644 --- a/xpallets/assets/rpc/src/lib.rs +++ b/xpallets/assets/rpc/src/lib.rs @@ -64,7 +64,7 @@ where C::Api: XAssetsRuntimeApi, Block: BlockT, AccountId: Clone + Display + Codec, - Balance: Clone + Copy + Display + FromStr + Codec + Zero + Default, + Balance: Clone + Copy + Display + FromStr + Codec + Zero, { fn assets_by_account( &self, diff --git a/xpallets/dex/spot/rpc/src/lib.rs b/xpallets/dex/spot/rpc/src/lib.rs index d2f60407d..3ff79c5f1 100644 --- a/xpallets/dex/spot/rpc/src/lib.rs +++ b/xpallets/dex/spot/rpc/src/lib.rs @@ -92,9 +92,9 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XSpotRuntimeApi, AccountId: Codec, - Balance: Codec + Display + FromStr + Default, + Balance: Codec + Display + FromStr, BlockNumber: Codec, - Price: Codec + Display + FromStr + Default, + Price: Codec + Display + FromStr, { fn trading_pairs( &self, diff --git a/xpallets/gateway/common/rpc/src/lib.rs b/xpallets/gateway/common/rpc/src/lib.rs index 893d34abc..56bee89c8 100644 --- a/xpallets/gateway/common/rpc/src/lib.rs +++ b/xpallets/gateway/common/rpc/src/lib.rs @@ -171,7 +171,7 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XGatewayCommonRuntimeApi, AccountId: Codec + Send + Sync + 'static, - Balance: Codec + Display + FromStr + Send + Sync + 'static + From + Default, + Balance: Codec + Display + FromStr + Send + Sync + 'static + From, { fn bound_addrs( &self, diff --git a/xpallets/mining/asset/rpc/src/lib.rs b/xpallets/mining/asset/rpc/src/lib.rs index 9bfd727cb..9e363afba 100644 --- a/xpallets/mining/asset/rpc/src/lib.rs +++ b/xpallets/mining/asset/rpc/src/lib.rs @@ -85,8 +85,8 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XMiningAssetRuntimeApi, AccountId: Codec, - Balance: Codec + Display + FromStr + Default, - MiningWeight: Codec + Display + FromStr + Default, + Balance: Codec + Display + FromStr, + MiningWeight: Codec + Display + FromStr, BlockNumber: Codec, { fn mining_assets( diff --git a/xpallets/mining/staking/rpc/src/lib.rs b/xpallets/mining/staking/rpc/src/lib.rs index e2864bab2..2df4ea0e3 100644 --- a/xpallets/mining/staking/rpc/src/lib.rs +++ b/xpallets/mining/staking/rpc/src/lib.rs @@ -100,8 +100,8 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XStakingRuntimeApi, AccountId: Codec + Ord, - Balance: Codec + Display + FromStr + Default, - VoteWeight: Codec + Display + FromStr + Default, + Balance: Codec + Display + FromStr, + VoteWeight: Codec + Display + FromStr, BlockNumber: Codec, { fn validators( diff --git a/xpallets/transaction-fee/rpc/src/lib.rs b/xpallets/transaction-fee/rpc/src/lib.rs index 04f5580dd..a0cc0f5bb 100644 --- a/xpallets/transaction-fee/rpc/src/lib.rs +++ b/xpallets/transaction-fee/rpc/src/lib.rs @@ -68,16 +68,14 @@ where api.query_fee_details(&at, uxt, encoded_len) .map(|fee_details| FeeDetails { - base: pallet_transaction_payment::FeeDetails { - inclusion_fee: fee_details.base.inclusion_fee.map(|fee| { - pallet_transaction_payment::InclusionFee { - base_fee: fee.base_fee.into(), - len_fee: fee.len_fee.into(), - adjusted_weight_fee: fee.adjusted_weight_fee.into(), - } - }), - tip: fee_details.base.tip.into(), - }, + inclusion_fee: fee_details.inclusion_fee.map(|fee| { + pallet_transaction_payment::InclusionFee { + base_fee: fee.base_fee.into(), + len_fee: fee.len_fee.into(), + adjusted_weight_fee: fee.adjusted_weight_fee.into(), + } + }), + tip: fee_details.tip.into(), extra_fee: fee_details.extra_fee.into(), final_fee: fee_details.final_fee.into(), }) diff --git a/xpallets/transaction-fee/src/lib.rs b/xpallets/transaction-fee/src/lib.rs index b69bdf4a2..eb85c2567 100644 --- a/xpallets/transaction-fee/src/lib.rs +++ b/xpallets/transaction-fee/src/lib.rs @@ -13,20 +13,12 @@ mod types; -use codec::DecodeLimit; use sp_std::prelude::*; -use frame_support::{ - //decl_event, decl_module, pallet, - traits::Get, - weights::{ - DispatchClass, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, Weight, - WeightToFeePolynomial, - }, -}; +use frame_support::weights::{DispatchInfo, GetDispatchInfo}; use sp_runtime::{ - traits::{DispatchInfoOf, Dispatchable, PostDispatchInfoOf, Saturating}, - FixedPointNumber, FixedPointOperand, + traits::{Dispatchable, Saturating}, + FixedPointOperand, }; pub use self::types::FeeDetails; @@ -40,7 +32,6 @@ pub use pallet::*; pub mod pallet { use super::*; use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; #[pallet::pallet] #[pallet::generate_store(pub(crate) trait Store)] @@ -89,7 +80,7 @@ where &dispatch_info, 0u32.into(), ); - let details_clone = details.clone(); + match details.inclusion_fee { Some(fee) => { let total = fee @@ -98,13 +89,15 @@ where .saturating_add(fee.adjusted_weight_fee) .saturating_add(details.tip); FeeDetails { - base: details_clone, + inclusion_fee: Some(fee), + tip: details.tip, extra_fee: 0u32.into(), final_fee: total, } } None => FeeDetails { - base: details_clone, + inclusion_fee: None, + tip: details.tip, extra_fee: 0u32.into(), final_fee: details.tip, }, diff --git a/xpallets/transaction-fee/src/types.rs b/xpallets/transaction-fee/src/types.rs index 574319467..7703eea69 100644 --- a/xpallets/transaction-fee/src/types.rs +++ b/xpallets/transaction-fee/src/types.rs @@ -1,6 +1,7 @@ // Copyright 2019-2020 ChainX Project Authors. Licensed under GPL-3.0. use codec::{Decode, Encode}; +use pallet_transaction_payment::InclusionFee; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; @@ -17,9 +18,12 @@ use sp_runtime::RuntimeDebug; #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -pub struct FeeDetails { - /// Some calls might be charged extra fee besides the essential `inclusion_fee`. - pub base: pallet_transaction_payment::FeeDetails, +pub struct FeeDetails { + /// The minimum fee for a transaction to be included in a block. + pub inclusion_fee: Option>, + // Do not serialize and deserialize `tip` as we actually can not pass any tip to the RPC. + #[cfg_attr(feature = "std", serde(skip))] + pub tip: Balance, pub extra_fee: Balance, pub final_fee: Balance, } From c3c0c3bf92675f59ec170c0746ee16a0ccc7f527 Mon Sep 17 00:00:00 2001 From: Alan WANG Date: Thu, 17 Jun 2021 18:31:05 +0800 Subject: [PATCH 07/17] Remove `Default` trait bound --- xpallets/transaction-fee/rpc/runtime-api/src/lib.rs | 2 +- xpallets/transaction-fee/rpc/src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs b/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs index 4c8a2a0b5..1719b6587 100644 --- a/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs +++ b/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs @@ -10,7 +10,7 @@ use sp_runtime::traits::{MaybeDisplay, MaybeFromStr}; pub use xpallet_transaction_fee::{FeeDetails, InclusionFee}; sp_api::decl_runtime_apis! { - pub trait XTransactionFeeApi where + pub trait XTransactionFeeApi where Balance: Codec + MaybeDisplay + MaybeFromStr, { fn query_fee_details(uxt: Block::Extrinsic, len: u32) -> FeeDetails; diff --git a/xpallets/transaction-fee/rpc/src/lib.rs b/xpallets/transaction-fee/rpc/src/lib.rs index a0cc0f5bb..ad6084802 100644 --- a/xpallets/transaction-fee/rpc/src/lib.rs +++ b/xpallets/transaction-fee/rpc/src/lib.rs @@ -52,7 +52,7 @@ where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XTransactionFeeRuntimeApi, - Balance: Codec + MaybeDisplay + MaybeFromStr + Default, + Balance: Codec + MaybeDisplay + MaybeFromStr, { fn query_fee_details( &self, From 9171f83af7c423a9e5d73a40a94d7c39fbde2db4 Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Fri, 18 Jun 2021 15:04:25 +0800 Subject: [PATCH 08/17] Pretend to remove transaction-fee-xpallet-runtime-rpc, but there is an error in xpallets/transaction-fee/rpc/src/lib.rs:89:69 --- Cargo.lock | 2 + primitives/rpc/src/lib.rs | 4 +- runtime/chainx/src/lib.rs | 21 +- runtime/dev/src/lib.rs | 38 +- runtime/malan/src/lib.rs | 38 +- xpallets/assets/rpc/src/lib.rs | 2 +- xpallets/assets/src/lib.rs | 405 +++++++------- xpallets/assets/src/mock.rs | 2 +- xpallets/assets/src/multicurrency.rs | 14 +- xpallets/assets/src/trigger.rs | 10 +- xpallets/assets/src/weights.rs | 6 +- xpallets/dex/spot/rpc/src/lib.rs | 4 +- xpallets/dex/spot/src/benchmarking.rs | 2 +- xpallets/dex/spot/src/execution/asset.rs | 2 +- xpallets/dex/spot/src/execution/mod.rs | 2 +- xpallets/dex/spot/src/execution/order.rs | 4 +- xpallets/dex/spot/src/execution/state.rs | 2 +- xpallets/dex/spot/src/lib.rs | 503 ++++++++++-------- xpallets/dex/spot/src/mock.rs | 6 +- xpallets/dex/spot/src/rpc.rs | 2 +- xpallets/dex/spot/src/types.rs | 2 +- xpallets/gateway/common/rpc/src/lib.rs | 2 +- xpallets/gateway/common/src/lib.rs | 371 +++++++------ xpallets/gateway/common/src/mock.rs | 6 +- xpallets/gateway/records/src/mock.rs | 5 +- xpallets/mining/asset/rpc/src/lib.rs | 4 +- xpallets/mining/staking/rpc/src/lib.rs | 4 +- xpallets/system/src/lib.rs | 141 +++-- xpallets/transaction-fee/rpc/Cargo.toml | 4 + .../rpc/runtime-api/src/lib.rs | 26 +- xpallets/transaction-fee/rpc/src/lib.rs | 84 ++- xpallets/transaction-fee/src/lib.rs | 66 +-- xpallets/transaction-fee/src/types.rs | 10 +- 33 files changed, 986 insertions(+), 808 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f717f5706..341c26e44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10164,6 +10164,7 @@ dependencies = [ name = "xpallet-transaction-fee-rpc" version = "2.0.9" dependencies = [ + "chainx-runtime", "jsonrpc-core", "jsonrpc-core-client", "jsonrpc-derive", @@ -10176,6 +10177,7 @@ dependencies = [ "sp-core", "sp-runtime", "xp-rpc", + "xpallet-transaction-fee", "xpallet-transaction-fee-rpc-runtime-api", ] diff --git a/primitives/rpc/src/lib.rs b/primitives/rpc/src/lib.rs index 13ed03f51..f42522e12 100644 --- a/primitives/rpc/src/lib.rs +++ b/primitives/rpc/src/lib.rs @@ -80,10 +80,10 @@ pub type RpcVoteWeight = RpcU128; /// A helper struct for handling u128 serialization/deserialization of RPC. /// See https://github.com/polkadot-js/api/issues/2464 for details (shit!). -#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize, Default)] +#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)] pub struct RpcU128(#[serde(with = "self::serde_num_str")] T); -impl From for RpcU128 { +impl From for RpcU128 { fn from(value: T) -> Self { RpcU128(value) } diff --git a/runtime/chainx/src/lib.rs b/runtime/chainx/src/lib.rs index 07a903bc6..3a8711ff2 100644 --- a/runtime/chainx/src/lib.rs +++ b/runtime/chainx/src/lib.rs @@ -1325,30 +1325,11 @@ impl_runtime_apis! { TransactionPayment::query_info(uxt, len) } } - fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment_rpc_runtime_api::FeeDetails { + fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment::FeeDetails { TransactionPayment::query_fee_details(uxt, len) } } - impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> xpallet_transaction_fee::FeeDetails { - if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let base = XTransactionFee::query_fee_details(uxt, len); - xpallet_transaction_fee::FeeDetails { - extra_fee, - final_fee: base.final_fee + extra_fee, - ..base - } - } else { - XTransactionFee::query_fee_details(uxt, len) - } - - } - } - impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { fn assets_for_account(who: AccountId) -> BTreeMap> { XAssets::valid_assets_of(&who) diff --git a/runtime/dev/src/lib.rs b/runtime/dev/src/lib.rs index 18c08deaf..a846c6a03 100644 --- a/runtime/dev/src/lib.rs +++ b/runtime/dev/src/lib.rs @@ -1336,28 +1336,28 @@ impl_runtime_apis! { } } fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment::FeeDetails { - todo!("Migrate ChainX query_fee_details") + TransactionPayment::query_fee_details(uxt, len) } } - impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> xpallet_transaction_fee::FeeDetails { - if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let details = XTransactionFee::query_fee_details(uxt, len); - xpallet_transaction_fee::FeeDetails { - extra_fee, - final_fee: details.final_fee + extra_fee, - ..details - } - } else { - XTransactionFee::query_fee_details(uxt, len) - } - - } - } + // impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { + // fn query_fee_details( + // uxt: ::Extrinsic, + // len: u32, + // ) -> xpallet_transaction_fee::FeeDetails { + // if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { + // let details = XTransactionFee::query_fee_details(uxt, len); + // xpallet_transaction_fee::FeeDetails { + // extra_fee, + // final_fee: details.final_fee + extra_fee, + // ..details + // } + // } else { + // XTransactionFee::query_fee_details(uxt, len) + // } + + // } + // } impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { fn assets_for_account(who: AccountId) -> BTreeMap> { diff --git a/runtime/malan/src/lib.rs b/runtime/malan/src/lib.rs index fdb592cee..511f21189 100644 --- a/runtime/malan/src/lib.rs +++ b/runtime/malan/src/lib.rs @@ -1333,28 +1333,28 @@ impl_runtime_apis! { } } fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment::FeeDetails { - todo!("Migrate ChainX query_fee_details") + TransactionPayment::query_fee_details(uxt, len) } } - impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> xpallet_transaction_fee::FeeDetails { - if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let details = XTransactionFee::query_fee_details(uxt, len); - xpallet_transaction_fee::FeeDetails { - extra_fee, - final_fee: details.final_fee + extra_fee, - ..details - } - } else { - XTransactionFee::query_fee_details(uxt, len) - } - - } - } + // impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { + // fn query_fee_details( + // uxt: ::Extrinsic, + // len: u32, + // ) -> xpallet_transaction_fee::FeeDetails { + // if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { + // let details = XTransactionFee::query_fee_details(uxt, len); + // xpallet_transaction_fee::FeeDetails { + // extra_fee, + // final_fee: details.final_fee + extra_fee, + // ..details + // } + // } else { + // XTransactionFee::query_fee_details(uxt, len) + // } + + // } + // } impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { fn assets_for_account(who: AccountId) -> BTreeMap> { diff --git a/xpallets/assets/rpc/src/lib.rs b/xpallets/assets/rpc/src/lib.rs index e6669b01f..be1adddc6 100644 --- a/xpallets/assets/rpc/src/lib.rs +++ b/xpallets/assets/rpc/src/lib.rs @@ -64,7 +64,7 @@ where C::Api: XAssetsRuntimeApi, Block: BlockT, AccountId: Clone + Display + Codec, - Balance: Clone + Copy + Display + FromStr + Codec + Zero + Default, + Balance: Clone + Copy + Display + FromStr + Codec + Zero, { fn assets_by_account( &self, diff --git a/xpallets/assets/src/lib.rs b/xpallets/assets/src/lib.rs index e422515f9..129d634ee 100644 --- a/xpallets/assets/src/lib.rs +++ b/xpallets/assets/src/lib.rs @@ -24,192 +24,112 @@ pub mod weights; use sp_std::{ collections::btree_map::BTreeMap, convert::{TryFrom, TryInto}, - prelude::*, }; use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, dispatch::{DispatchError, DispatchResult}, ensure, + inherent::Vec, log::{debug, error, info}, traits::{Currency, Get, HandleLifetime, LockableCurrency, ReservableCurrency}, - Parameter, StorageDoubleMap, + Parameter, }; + use frame_system::{ensure_root, ensure_signed, AccountInfo}; use orml_traits::arithmetic::{Signed, SimpleArithmetic}; -use sp_runtime::traits::{ - CheckedAdd, CheckedSub, MaybeSerializeDeserialize, Member, Saturating, StaticLookup, Zero, -}; +use sp_runtime::traits::{CheckedAdd, CheckedSub, Saturating, StaticLookup, Zero}; +use self::trigger::AssetChangedTrigger; use chainx_primitives::AssetId; -pub use xpallet_assets_registrar::{AssetInfo, Chain}; use xpallet_support::traits::TreasuryAccount; pub use self::traits::{ChainT, OnAssetChanged}; -use self::trigger::AssetChangedTrigger; pub use self::types::{ AssetErr, AssetRestrictions, AssetType, BalanceLock, TotalAssetInfo, WithdrawalLimit, }; pub use self::weights::WeightInfo; +pub use xpallet_assets_registrar::{AssetInfo, Chain}; pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; -/// The module's config trait. -/// -/// `frame_system::Config` should always be included in our implied traits. -pub trait Config: xpallet_assets_registrar::Config { - /// The overarching event type. - type Event: From> + Into<::Event>; - - /// The native currency. - type Currency: ReservableCurrency - + LockableCurrency; - - /// The amount type, should be signed version of `Balance` - type Amount: Parameter - + Member - + Default - + Copy - + MaybeSerializeDeserialize - + Signed - + SimpleArithmetic - + TryInto> - + TryFrom>; - - /// The treasury account. - type TreasuryAccount: TreasuryAccount; - - /// The hook for doing something on the event of creating an account. - type OnCreatedAccount: HandleLifetime; - - /// The hook triggered whenever the asset balance of an account is changed. - type OnAssetChanged: OnAssetChanged>; - - /// Weight information for extrinsics in this pallet. - type WeightInfo: WeightInfo; -} - -decl_error! { - /// Error for the Assets Module - pub enum Error for Module { - /// - InvalidAsset, - /// Got an overflow after adding - Overflow, - /// Balance too low to send value - InsufficientBalance, - /// Failed because liquidity restrictions due to locking - LiquidityRestrictions, - /// Cannot convert Amount into Balance type - AmountIntoBalanceFailed, - /// Got an overflow after adding - TotalAssetOverflow, - /// Balance too low to send value - TotalAssetInsufficientBalance, - /// Not Allow native asset, - DenyNativeAsset, - /// Action is not allowed. - ActionNotAllowed, - /// Account still has active reserved - StillHasActiveReserved - } -} - -decl_event!( - pub enum Event - where - ::AccountId, - Balance = BalanceOf, - { - /// Some balances of an asset was moved from one to another. [asset_id, from, from_type, to, to_type, amount] - Moved(AssetId, AccountId, AssetType, AccountId, AssetType, Balance), - /// New balances of an asset were issued. [asset_id, receiver, amount] - Issued(AssetId, AccountId, Balance), - /// Some balances of an asset were destoryed. [asset_id, who, amount] - Destroyed(AssetId, AccountId, Balance), - /// Set asset balance of an account by root. [asset_id, who, asset_type, amount] - BalanceSet(AssetId, AccountId, AssetType, Balance), - } -); - -decl_storage! { - trait Store for Module as XAssets { - /// asset extend limit properties, set asset "can do", example, `CanTransfer`, `CanDestroyWithdrawal` - /// notice if not set AssetRestriction, default is true for this limit - /// if want let limit make sense, must set false for the limit - pub AssetRestrictionsOf get(fn asset_restrictions_of): - map hasher(twox_64_concat) AssetId => AssetRestrictions; - - /// asset balance for user&asset_id, use btree_map to accept different asset type - pub AssetBalance get(fn asset_balance): - double_map hasher(blake2_128_concat) T::AccountId, hasher(twox_64_concat) AssetId - => BTreeMap>; - - /// Any liquidity locks of a token type under an account. - /// NOTE: Should only be accessed when setting, changing and freeing a lock. - pub Locks get(fn locks): - double_map hasher(blake2_128_concat) T::AccountId, hasher(twox_64_concat) AssetId - => Vec>>; - - /// asset balance for an asset_id, use btree_map to accept different asset type - pub TotalAssetBalance get(fn total_asset_balance): - map hasher(twox_64_concat) AssetId => BTreeMap>; - } - add_extra_genesis { - config(assets_restrictions): Vec<(AssetId, AssetRestrictions)>; - config(endowed): BTreeMap)>>; - build(|config| { - for (id, endowed) in &config.endowed { - if *id != T::NativeAssetId::get() { - for (accountid, value) in endowed.iter() { - Module::::issue(id, accountid, *value) - .expect("asset issuance during the genesis can not fail"); - } - } - } - for (id, restrictions) in &config.assets_restrictions { - if *id != T::NativeAssetId::get() { - Module::::set_asset_restrictions(*id, *restrictions) - .expect("should not fail in genesis, qed"); - } - } - }) - } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - type Error = Error; - - fn deposit_event() = default; - - /// transfer between account - #[weight = 0] +pub use pallet::*; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + + /// The pallet's config trait. + /// + /// `frame_system::Config` should always be included in our implied traits. + #[pallet::config] + pub trait Config: frame_system::Config + xpallet_assets_registrar::Config { + /// The overarching event type. + type Event: From> + IsType<::Event>; + + /// The native currency. + type Currency: ReservableCurrency + + LockableCurrency; + + /// The amount type, should be signed version of `Balance` + type Amount: Parameter + + Member + + Default + + Copy + + MaybeSerializeDeserialize + + Signed + + SimpleArithmetic + + TryInto> + + TryFrom>; + + /// The treasury account. + type TreasuryAccount: TreasuryAccount; + + /// The hook for doing something on the event of creating an account. + type OnCreatedAccount: HandleLifetime; + + /// The hook triggered whenever the asset balance of an account is changed. + type OnAssetChanged: OnAssetChanged>; + + /// Weight information for extrinsics in this pallet. + type WeightInfo: WeightInfo; + } + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData); + + #[pallet::call] + impl Pallet { + /// transfer between two accounts + #[pallet::weight(0)] pub fn transfer( - origin, + origin: OriginFor, dest: ::Source, - #[compact] id: AssetId, - #[compact] value: BalanceOf + #[pallet::compact] id: AssetId, + #[pallet::compact] value: BalanceOf, ) -> DispatchResult { let transactor = ensure_signed(origin)?; let dest = T::Lookup::lookup(dest)?; debug!(target: "runtime::assets", "[transfer] from:{:?}, to:{:?}, id:{}, value:{:?}", transactor, dest, id, value); Self::can_transfer(&id)?; - Self::move_usable_balance(&id, &transactor, &dest, value).map_err::, _>(Into::into)?; + Self::move_usable_balance(&id, &transactor, &dest, value) + .map_err::, _>(Into::into)?; Ok(()) } - /// for transfer by root - #[weight = 0] + /// transfer method reserved for root(sudo) + #[pallet::weight(0)] pub fn force_transfer( - origin, + origin: OriginFor, transactor: ::Source, dest: ::Source, - #[compact] id: AssetId, - #[compact] value: BalanceOf + #[pallet::compact] id: AssetId, + #[pallet::compact] value: BalanceOf, ) -> DispatchResult { ensure_root(origin)?; @@ -217,17 +137,18 @@ decl_module! { let dest = T::Lookup::lookup(dest)?; debug!(target: "runtime::assets", "[force_transfer] from:{:?}, to:{:?}, id:{}, value:{:?}", transactor, dest, id, value); Self::can_transfer(&id)?; - Self::move_usable_balance(&id, &transactor, &dest, value).map_err::, _>(Into::into)?; + Self::move_usable_balance(&id, &transactor, &dest, value) + .map_err::, _>(Into::into)?; Ok(()) } /// set free token for an account - #[weight = 0] + #[pallet::weight(0)] pub fn set_balance( - origin, + origin: OriginFor, who: ::Source, - #[compact] id: AssetId, - balances: BTreeMap> + #[pallet::compact] id: AssetId, + balances: BTreeMap>, ) -> DispatchResult { ensure_root(origin)?; @@ -237,27 +158,156 @@ decl_module! { Ok(()) } - #[weight = ::WeightInfo::set_asset_limit()] - pub fn set_asset_limit(origin, #[compact] id: AssetId, restrictions: AssetRestrictions) -> DispatchResult { + /// asset restriction method reserved for root + #[pallet::weight(::WeightInfo::set_asset_limit())] + pub fn set_asset_limit( + origin: OriginFor, + #[pallet::compact] id: AssetId, + restrictions: AssetRestrictions, + ) -> DispatchResult { ensure_root(origin)?; Self::set_asset_restrictions(id, restrictions) } } + + /// Event for the Assets Pallet + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + #[pallet::metadata(T::AccountId = "AccountId", BalanceOf = "Balance")] + pub enum Event { + /// Some balances of an asset was moved from one to another. [asset_id, from, from_type, to, to_type, amount] + Moved( + AssetId, + T::AccountId, + AssetType, + T::AccountId, + AssetType, + BalanceOf, + ), + /// New balances of an asset were issued. [asset_id, receiver, amount] + Issued(AssetId, T::AccountId, BalanceOf), + /// Some balances of an asset were destoryed. [asset_id, who, amount] + Destroyed(AssetId, T::AccountId, BalanceOf), + /// Set asset balance of an account by root. [asset_id, who, asset_type, amount] + BalanceSet(AssetId, T::AccountId, AssetType, BalanceOf), + } + + /// Error for the Assets Pallet + #[pallet::error] + pub enum Error { + /// Got and Invalid Asset + InvalidAsset, + /// Got an overflow after adding + Overflow, + /// Balance too low to send value + InsufficientBalance, + /// Failed because liquidity restrictions due to locking + LiquidityRestrictions, + /// Cannot convert Amount into Balance type + AmountIntoBalanceFailed, + /// Got an overflow after adding + TotalAssetOverflow, + /// Balance too low to send value + TotalAssetInsufficientBalance, + /// Not Allow native asset, + DenyNativeAsset, + /// Action is not allowed. + ActionNotAllowed, + /// Account still has active reserved + StillHasActiveReserved, + } + + /// asset extend limit properties, set asset "can do", example, `CanTransfer`, `CanDestroyWithdrawal` + /// notice if not set AssetRestriction, default is true for this limit + /// if want let limit make sense, must set false for the limit + #[pallet::storage] + #[pallet::getter(fn asset_restrictions_of)] + pub type AssetRestrictionsOf = + StorageMap<_, Twox64Concat, AssetId, AssetRestrictions, ValueQuery>; + + /// asset balance for user&asset_id, use btree_map to accept different asset type + #[pallet::storage] + #[pallet::getter(fn asset_balance)] + pub type AssetBalance = StorageDoubleMap< + _, + Blake2_128Concat, + T::AccountId, + Twox64Concat, + AssetId, + BTreeMap>, + ValueQuery, + >; + + /// Any liquidity locks of a token type under an account. + /// NOTE: Should only be accessed when setting, changing and freeing a lock. + #[pallet::storage] + #[pallet::getter(fn locks)] + pub type Locks = StorageDoubleMap< + _, + Blake2_128Concat, + T::AccountId, + Twox64Concat, + AssetId, + Vec>>, + ValueQuery, + >; + + /// asset balance for an asset_id, use btree_map to accept different asset type + #[pallet::storage] + #[pallet::getter(fn total_asset_balance)] + pub type TotalAssetBalance = + StorageMap<_, Twox64Concat, AssetId, BTreeMap>, ValueQuery>; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub assets_restrictions: Vec<(AssetId, AssetRestrictions)>, + pub endowed: BTreeMap)>>, + } + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { + assets_restrictions: Default::default(), + endowed: Default::default(), + } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + let extra_genesis_builder: fn(&Self) = |config| { + for (id, endowed) in &config.endowed { + if *id != T::NativeAssetId::get() { + for (accountid, value) in endowed.iter() { + Pallet::::issue(id, accountid, *value) + .expect("asset issuance during the genesis can not fail"); + } + } + } + for (id, restrictions) in &config.assets_restrictions { + if *id != T::NativeAssetId::get() { + Pallet::::set_asset_restrictions(*id, *restrictions) + .expect("should not fail in genesis, qed"); + } + } + }; + extra_genesis_builder(self); + } + } } -// others -impl Module { +impl Pallet { fn set_asset_restrictions( asset_id: AssetId, restrictions: AssetRestrictions, ) -> DispatchResult { - xpallet_assets_registrar::Module::::ensure_asset_exists(&asset_id)?; - AssetRestrictionsOf::insert(asset_id, restrictions); + xpallet_assets_registrar::Pallet::::ensure_asset_exists(&asset_id)?; + AssetRestrictionsOf::::insert(asset_id, restrictions); Ok(()) } -} -impl Module { pub fn ensure_not_native_asset(asset_id: &AssetId) -> DispatchResult { ensure!( *asset_id != T::NativeAssetId::get(), @@ -265,13 +315,11 @@ impl Module { ); Ok(()) } -} -// asset related -impl Module { + // Asset related /// Returns a map of all registered assets by far. pub fn total_asset_infos() -> BTreeMap>> { - xpallet_assets_registrar::Module::::asset_infos() + xpallet_assets_registrar::Pallet::::asset_infos() .filter_map(|(id, info)| { if id == T::NativeAssetId::get() { // ignore native asset @@ -282,7 +330,7 @@ impl Module { TotalAssetInfo { info, balance: Self::total_asset_balance(id), - is_online: xpallet_assets_registrar::Module::::is_online(&id), + is_online: xpallet_assets_registrar::Pallet::::is_online(&id), restrictions: Self::asset_restrictions_of(id), }, ); @@ -292,17 +340,16 @@ impl Module { .collect() } - /// Retutrns the invalid asset info of `who`. + /// Returns the invalid asset info of `who`. pub fn valid_assets_of( who: &T::AccountId, ) -> BTreeMap>> { - use frame_support::IterableStorageDoubleMap; AssetBalance::::iter_prefix(who) - .filter(|(id, _)| xpallet_assets_registrar::Module::::asset_online(id)) + .filter(|(id, _)| xpallet_assets_registrar::Pallet::::asset_online(id)) .collect() } - /// Retutrns whether `restriction` is applied for given asset `id`. + /// Returns whether `restriction` is applied for given asset `id`. pub fn can_do(id: &AssetId, restriction: AssetRestrictions) -> bool { !Self::asset_restrictions_of(id).contains(restriction) } @@ -343,10 +390,8 @@ impl Module { } Ok(()) } -} -// Public read functions. -impl Module { + // Public read functions. /// Returns the total issuance of asset `id` by far. pub fn total_issuance(id: &AssetId) -> BalanceOf { let map = Self::total_asset_balance(id); @@ -389,10 +434,7 @@ impl Module { balance_for(Reserved) + balance_for(ReservedWithdrawal) + balance_for(ReservedDexSpot) } -} -// Public write functions. -impl Module { /// Sets the free balance of `who` without sanity checks and triggering the asset changed hook. #[cfg(feature = "std")] pub fn force_set_free_balance(id: &AssetId, who: &T::AccountId, value: BalanceOf) { @@ -402,7 +444,7 @@ impl Module { /// Increases the Usable balance of `who` given the asset `id` by this `value`. pub fn issue(id: &AssetId, who: &T::AccountId, value: BalanceOf) -> DispatchResult { Self::ensure_not_native_asset(id)?; - xpallet_assets_registrar::Module::::ensure_asset_is_valid(id)?; + xpallet_assets_registrar::Pallet::::ensure_asset_is_valid(id)?; let _imbalance = Self::inner_issue(id, who, AssetType::Usable, value)?; Ok(()) @@ -414,7 +456,7 @@ impl Module { value: BalanceOf, ) -> DispatchResult { Self::ensure_not_native_asset(id)?; - xpallet_assets_registrar::Module::::ensure_asset_is_valid(id)?; + xpallet_assets_registrar::Pallet::::ensure_asset_is_valid(id)?; Self::can_destroy_withdrawal(id)?; Self::inner_destroy(id, who, AssetType::ReservedWithdrawal, value)?; @@ -423,7 +465,7 @@ impl Module { pub fn destroy_usable(id: &AssetId, who: &T::AccountId, value: BalanceOf) -> DispatchResult { Self::ensure_not_native_asset(id)?; - xpallet_assets_registrar::Module::::ensure_asset_is_valid(id)?; + xpallet_assets_registrar::Pallet::::ensure_asset_is_valid(id)?; Self::can_destroy_usable(id)?; Self::inner_destroy(id, who, AssetType::Usable, value)?; @@ -439,7 +481,7 @@ impl Module { value: BalanceOf, ) -> Result<(), AssetErr> { Self::ensure_not_native_asset(id).map_err(|_| AssetErr::InvalidAsset)?; - xpallet_assets_registrar::Module::::ensure_asset_is_valid(id) + xpallet_assets_registrar::Pallet::::ensure_asset_is_valid(id) .map_err(|_| AssetErr::InvalidAsset)?; Self::can_move(id).map_err(|_| AssetErr::NotAllow)?; @@ -510,10 +552,7 @@ impl Module { } Ok(()) } -} -/// token issue destroy reserve/unreserve, it's core function -impl Module { /// Returns the balance of `who` given `asset_id` and `ty`. fn asset_typed_balance(who: &T::AccountId, asset_id: &AssetId, ty: AssetType) -> BalanceOf { Self::asset_balance(who, asset_id) diff --git a/xpallets/assets/src/mock.rs b/xpallets/assets/src/mock.rs index 538cbff95..06311f7b9 100644 --- a/xpallets/assets/src/mock.rs +++ b/xpallets/assets/src/mock.rs @@ -8,7 +8,7 @@ use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, }; -use frame_support::{parameter_types, sp_io}; +use frame_support::{parameter_types, sp_io, traits::GenesisBuild}; use chainx_primitives::AssetId; pub use xp_protocol::X_BTC; diff --git a/xpallets/assets/src/multicurrency.rs b/xpallets/assets/src/multicurrency.rs index 7ec0c549f..f8a2f890f 100644 --- a/xpallets/assets/src/multicurrency.rs +++ b/xpallets/assets/src/multicurrency.rs @@ -10,7 +10,7 @@ use frame_support::{ ensure, log::error, traits::{BalanceStatus, LockIdentifier}, - transactional, IterableStorageDoubleMap, + transactional, }; use orml_traits::{ @@ -22,9 +22,9 @@ use chainx_primitives::AssetId; use xpallet_support::traits::TreasuryAccount; use crate::types::{AssetType, BalanceLock}; -use crate::{AssetBalance, BalanceOf, Config, Error, Module}; +use crate::{AssetBalance, BalanceOf, Config, Error, Pallet}; -impl MultiCurrency for Module { +impl MultiCurrency for Pallet { type CurrencyId = AssetId; type Balance = BalanceOf; @@ -173,7 +173,7 @@ impl MultiCurrency for Module { } } -impl MultiCurrencyExtended for Module { +impl MultiCurrencyExtended for Pallet { type Amount = T::Amount; fn update_balance( @@ -195,7 +195,7 @@ impl MultiCurrencyExtended for Module { } } -impl MultiReservableCurrency for Module { +impl MultiReservableCurrency for Pallet { fn can_reserve( currency_id: Self::CurrencyId, who: &T::AccountId, @@ -326,7 +326,7 @@ impl MultiReservableCurrency for Module { } } -impl MultiLockableCurrency for Module { +impl MultiLockableCurrency for Pallet { type Moment = T::BlockNumber; fn set_lock( @@ -404,7 +404,7 @@ impl MultiLockableCurrency for Module { } } -impl MergeAccount for Module { +impl MergeAccount for Pallet { #[transactional] fn merge_account(source: &T::AccountId, dest: &T::AccountId) -> DispatchResult { AssetBalance::::iter_prefix(source).try_for_each( diff --git a/xpallets/assets/src/trigger.rs b/xpallets/assets/src/trigger.rs index 4b4a12a8c..b457926e8 100644 --- a/xpallets/assets/src/trigger.rs +++ b/xpallets/assets/src/trigger.rs @@ -6,7 +6,7 @@ use chainx_primitives::AssetId; use crate::traits::OnAssetChanged; use crate::types::{AssetErr, AssetType}; -use crate::{BalanceOf, Config, Event, Module}; +use crate::{BalanceOf, Config, Event, Pallet}; impl OnAssetChanged for () {} @@ -32,7 +32,7 @@ impl AssetChangedTrigger { to_type: AssetType, value: BalanceOf, ) -> Result<(), AssetErr> { - Module::::deposit_event(Event::::Moved( + Pallet::::deposit_event(Event::::Moved( *id, from.clone(), from_type, @@ -49,7 +49,7 @@ impl AssetChangedTrigger { } pub fn on_issue_post(id: &AssetId, who: &T::AccountId, value: BalanceOf) -> DispatchResult { - Module::::deposit_event(Event::::Issued(*id, who.clone(), value)); + Pallet::::deposit_event(Event::::Issued(*id, who.clone(), value)); T::OnAssetChanged::on_issue_post(id, who, value)?; Ok(()) } @@ -63,7 +63,7 @@ impl AssetChangedTrigger { who: &T::AccountId, value: BalanceOf, ) -> DispatchResult { - Module::::deposit_event(Event::::Destroyed(*id, who.clone(), value)); + Pallet::::deposit_event(Event::::Destroyed(*id, who.clone(), value)); T::OnAssetChanged::on_destroy_post(id, who, value)?; Ok(()) } @@ -74,7 +74,7 @@ impl AssetChangedTrigger { type_: AssetType, value: BalanceOf, ) -> DispatchResult { - Module::::deposit_event(Event::::BalanceSet(*id, who.clone(), type_, value)); + Pallet::::deposit_event(Event::::BalanceSet(*id, who.clone(), type_, value)); T::OnAssetChanged::on_set_balance(id, who, type_, value)?; Ok(()) } diff --git a/xpallets/assets/src/weights.rs b/xpallets/assets/src/weights.rs index 7a26cd8af..4cdd06dab 100644 --- a/xpallets/assets/src/weights.rs +++ b/xpallets/assets/src/weights.rs @@ -32,7 +32,7 @@ use sp_std::marker::PhantomData; pub trait WeightInfo { fn transfer() -> Weight; fn force_transfer() -> Weight; - fn set_balance(n: u32) -> Weight; + fn set_balance() -> Weight; fn set_asset_limit() -> Weight; } @@ -49,7 +49,7 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().reads(8 as Weight)) .saturating_add(T::DbWeight::get().writes(6 as Weight)) } - fn set_balance(_n: u32) -> Weight { + fn set_balance() -> Weight { (218_742_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) @@ -73,7 +73,7 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(8 as Weight)) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) } - fn set_balance(_n: u32) -> Weight { + fn set_balance() -> Weight { (218_742_000 as Weight) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) diff --git a/xpallets/dex/spot/rpc/src/lib.rs b/xpallets/dex/spot/rpc/src/lib.rs index d2f60407d..3ff79c5f1 100644 --- a/xpallets/dex/spot/rpc/src/lib.rs +++ b/xpallets/dex/spot/rpc/src/lib.rs @@ -92,9 +92,9 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XSpotRuntimeApi, AccountId: Codec, - Balance: Codec + Display + FromStr + Default, + Balance: Codec + Display + FromStr, BlockNumber: Codec, - Price: Codec + Display + FromStr + Default, + Price: Codec + Display + FromStr, { fn trading_pairs( &self, diff --git a/xpallets/dex/spot/src/benchmarking.rs b/xpallets/dex/spot/src/benchmarking.rs index 383af4bbd..d7484f376 100644 --- a/xpallets/dex/spot/src/benchmarking.rs +++ b/xpallets/dex/spot/src/benchmarking.rs @@ -88,7 +88,7 @@ benchmarks! { set_price_fluctuation { }: _(RawOrigin::Root, PAIR_ID, 1000) verify { - assert_eq!(PriceFluctuationOf::get(PAIR_ID), 1000); + assert_eq!(PriceFluctuationOf::::get(PAIR_ID), 1000); } add_trading_pair { diff --git a/xpallets/dex/spot/src/execution/asset.rs b/xpallets/dex/spot/src/execution/asset.rs index a7803f442..06563ed11 100644 --- a/xpallets/dex/spot/src/execution/asset.rs +++ b/xpallets/dex/spot/src/execution/asset.rs @@ -5,7 +5,7 @@ use super::*; use xpallet_assets::AssetType::{self, ReservedDexSpot, Usable}; -impl Module { +impl Pallet { /// Delivery the assets to maker and taker respectively when executing the order. pub(super) fn delivery_asset_to_each_other( maker_order_side: Side, diff --git a/xpallets/dex/spot/src/execution/mod.rs b/xpallets/dex/spot/src/execution/mod.rs index 30be6c67b..8a5c6d618 100644 --- a/xpallets/dex/spot/src/execution/mod.rs +++ b/xpallets/dex/spot/src/execution/mod.rs @@ -9,7 +9,7 @@ use frame_support::log::debug; use super::*; use crate::types::*; -impl Module { +impl Pallet { fn check_bid_price( quote: T::Price, lowest_ask: T::Price, diff --git a/xpallets/dex/spot/src/execution/order.rs b/xpallets/dex/spot/src/execution/order.rs index 693fef20e..544d92361 100644 --- a/xpallets/dex/spot/src/execution/order.rs +++ b/xpallets/dex/spot/src/execution/order.rs @@ -6,7 +6,7 @@ use super::*; use sp_runtime::traits::CheckedAdd; use sp_std::cmp::Ordering; -impl Module { +impl Pallet { /// When the price is far from the current handicap, i.e., /// - buy: less than the lowest_ask /// - sell: larger than the highest_bid @@ -353,7 +353,7 @@ impl Module { let pair = Self::trading_pair(pair_id)?; let trading_history_idx = Self::trading_history_index_of(pair_id); - TradingHistoryIndexOf::insert(pair_id, trading_history_idx + 1); + TradingHistoryIndexOf::::insert(pair_id, trading_history_idx + 1); Self::update_order_on_execute(maker_order, &turnover, trading_history_idx); Self::update_order_on_execute(taker_order, &turnover, trading_history_idx); diff --git a/xpallets/dex/spot/src/execution/state.rs b/xpallets/dex/spot/src/execution/state.rs index 0f19fa385..a5051940e 100644 --- a/xpallets/dex/spot/src/execution/state.rs +++ b/xpallets/dex/spot/src/execution/state.rs @@ -7,7 +7,7 @@ use crate::types::Side::{Buy, Sell}; use sp_runtime::traits::{CheckedAdd, CheckedSub}; /// Internal mutables -impl Module { +impl Pallet { /// It's worth noting that the handicap is not always related to some real orders, i.e., /// current lowest_ask(or highest_bid) is suprious. /// diff --git a/xpallets/dex/spot/src/lib.rs b/xpallets/dex/spot/src/lib.rs index 0ff481b83..d5d746c3d 100644 --- a/xpallets/dex/spot/src/lib.rs +++ b/xpallets/dex/spot/src/lib.rs @@ -27,7 +27,6 @@ use sp_std::prelude::*; use sp_std::{cmp, fmt::Debug}; use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, dispatch::{DispatchError, DispatchResult}, ensure, log::info, @@ -72,101 +71,195 @@ pub type OrderInfo = Order< pub type HandicapInfo = Handicap<::Price>; -pub trait Config: xpallet_assets::Config { - /// The overarching event type. - type Event: From> + Into<::Event>; - - /// The price of an order. - type Price: Parameter - + Member - + AtLeast32BitUnsigned - + Codec - + Default - + Copy - + MaybeSerializeDeserialize - + Debug; - - type WeightInfo: WeightInfo; -} +pub use pallet::*; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + + #[pallet::config] + pub trait Config: frame_system::Config + xpallet_assets::Config { + /// The overarching event type. + type Event: From> + IsType<::Event>; + + /// The price of an order. + type Price: Parameter + + Member + + AtLeast32BitUnsigned + + Codec + + Default + + Copy + + MaybeSerializeDeserialize + + Debug; + + type WeightInfo: WeightInfo; + } -decl_storage! { - trait Store for Module as XSpot { - /// How many trading pairs so far. - pub TradingPairCount get(fn trading_pair_count): TradingPairId; + #[pallet::pallet] + #[pallet::generate_store(pub(crate) trait Store)] + pub struct Pallet(PhantomData); - /// Record the exact balance of reserved native coins in Spot. - pub NativeReserves get(fn native_reserves): - map hasher(twox_64_concat) T::AccountId => BalanceOf; + #[pallet::call] + impl Pallet { + #[pallet::weight(::WeightInfo::put_order())] + pub fn put_order( + origin: OriginFor, + #[pallet::compact] pair_id: TradingPairId, + order_type: OrderType, + side: Side, + #[pallet::compact] amount: BalanceOf, + #[pallet::compact] price: T::Price, + ) -> DispatchResult { + let who = ensure_signed(origin)?; - /// The map from trading pair id to its static profile. - pub TradingPairOf get(fn trading_pair_of): - map hasher(twox_64_concat) TradingPairId => Option; + ensure!(!price.is_zero(), Error::::InvalidPrice); + ensure!(!amount.is_zero(), Error::::ZeroAmount); + ensure!(order_type == OrderType::Limit, Error::::InvalidOrderType); - /// (latest price, last update height) of trading pair - pub TradingPairInfoOf get(fn trading_pair_info_of): - map hasher(twox_64_concat) TradingPairId => Option>; + let pair = Self::trading_pair(pair_id)?; - /// Total transactions has been made for a trading pair. - pub TradingHistoryIndexOf get(fn trading_history_index_of): - map hasher(twox_64_concat) TradingPairId => TradingHistoryIndex; + ensure!(pair.tradable, Error::::TradingPairUntradable); + ensure!(pair.is_valid_price(price), Error::::InvalidPrice); - /// Total orders made by an account. - pub OrderCountOf get(fn order_count_of): - map hasher(twox_64_concat) T::AccountId => OrderId; + Self::is_valid_quote(price, side, pair_id)?; + Self::has_too_many_backlog_orders(pair_id, price, side)?; - /// Details of an user order given the account ID and order ID. - pub OrderInfoOf get(fn order_info_of): - double_map hasher(twox_64_concat) T::AccountId, hasher(twox_64_concat) OrderId - => Option>; + // Reserve the token according to the order side. + let (reserve_asset, reserve_amount) = match side { + Side::Buy => ( + pair.quote(), + Self::convert_base_to_quote(amount, price, &pair)?, + ), + Side::Sell => (pair.base(), amount), + }; + Self::put_order_reserve(&who, reserve_asset, reserve_amount)?; + Self::apply_put_order( + who, + pair_id, + order_type, + side, + amount, + price, + reserve_amount, + )?; + Ok(()) + } - /// All the accounts and the order number given the trading pair ID and price. - pub QuotationsOf get(fn quotations_of): - double_map hasher(twox_64_concat) TradingPairId, hasher(twox_64_concat) T::Price - => Vec<(T::AccountId, OrderId)>; + #[pallet::weight(::WeightInfo::cancel_order())] + pub fn cancel_order( + origin: OriginFor, + #[pallet::compact] pair_id: TradingPairId, + #[pallet::compact] order_id: OrderId, + ) -> DispatchResult { + let who = ensure_signed(origin)?; + Self::do_cancel_order(&who, pair_id, order_id)?; + Ok(()) + } - /// TradingPairId => (highest_bid, lowest_ask) - pub HandicapOf get(fn handicap_of): - map hasher(twox_64_concat) TradingPairId => HandicapInfo; + /// Force cancel an order. + #[pallet::weight(::WeightInfo::force_cancel_order())] + fn force_cancel_order( + origin: OriginFor, + who: ::Source, + #[pallet::compact] pair_id: TradingPairId, + #[pallet::compact] order_id: OrderId, + ) -> DispatchResult { + ensure_root(origin)?; + let who = T::Lookup::lookup(who)?; + Self::do_cancel_order(&who, pair_id, order_id)?; + Ok(()) + } - /// The map of trading pair ID to the price fluctuation. Use with caution! - pub PriceFluctuationOf get(fn price_fluctuation_of): - map hasher(twox_64_concat) TradingPairId => PriceFluctuation = DEFAULT_FLUCTUATION; - } + #[pallet::weight(::WeightInfo::set_handicap())] + pub fn set_handicap( + origin: OriginFor, + #[pallet::compact] pair_id: TradingPairId, + new: Handicap, + ) -> DispatchResult { + ensure_root(origin)?; + info!(target: "runtime::dex::spot", "[set_handicap] pair_id:{:?}, new handicap:{:?}", pair_id, new); + HandicapOf::::insert(pair_id, new); + Ok(()) + } - add_extra_genesis { - config(trading_pairs): Vec<(AssetId, AssetId, u32, u32, T::Price, bool)>; - build(|config| { - for (base, quote, pip_decimals, tick_decimals, price, tradable) in config.trading_pairs.iter() { - Module::::apply_add_trading_pair( - CurrencyPair::new(*base, *quote), - *pip_decimals, - *tick_decimals, - *price, - *tradable - ); - } - }) + #[pallet::weight(::WeightInfo::set_price_fluctuation())] + pub fn set_price_fluctuation( + origin: OriginFor, + #[pallet::compact] pair_id: TradingPairId, + #[pallet::compact] new: PriceFluctuation, + ) -> DispatchResult { + ensure_root(origin)?; + PriceFluctuationOf::::insert(pair_id, new); + Self::deposit_event(Event::::PriceFluctuationUpdated(pair_id, new)); + Ok(()) + } + + /// Add a new trading pair. + #[pallet::weight(::WeightInfo::add_trading_pair())] + pub fn add_trading_pair( + origin: OriginFor, + currency_pair: CurrencyPair, + #[pallet::compact] pip_decimals: u32, + #[pallet::compact] tick_decimals: u32, + #[pallet::compact] latest_price: T::Price, + tradable: bool, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::get_trading_pair_by_currency_pair(¤cy_pair).is_none(), + Error::::TradingPairAlreadyExists + ); + Self::apply_add_trading_pair( + currency_pair, + pip_decimals, + tick_decimals, + latest_price, + tradable, + ); + Ok(()) + } + + /// Update the trading pair profile. + #[pallet::weight(::WeightInfo::update_trading_pair())] + pub fn update_trading_pair( + origin: OriginFor, + #[pallet::compact] pair_id: TradingPairId, + #[pallet::compact] tick_decimals: u32, + tradable: bool, + ) -> DispatchResult { + ensure_root(origin)?; + let pair = Self::trading_pair(pair_id)?; + ensure!( + tick_decimals >= pair.tick_decimals, + Error::::InvalidTickdecimals + ); + Self::apply_update_trading_pair(pair_id, tick_decimals, tradable); + Ok(()) + } } -} -decl_event!( - pub enum Event - where - Balance = BalanceOf, - ::AccountId, - ::BlockNumber, - ::Price, - { + #[pallet::event] + #[pallet::metadata(BalanceOf = "Balance", T::AccountId = "AccountId", T::BlockNumber = "BlockNumber", T::Price = "Price")] + #[pallet::generate_deposit(pub(crate) fn deposit_event)] + pub enum Event { /// A new order was created. [order_info] - NewOrder(Order), + NewOrder(Order, T::Price, T::BlockNumber>), /// There was an update to the order due to it gets executed. [maker_order_info] - MakerOrderUpdated(Order), + MakerOrderUpdated( + Order, T::Price, T::BlockNumber>, + ), /// There was an update to the order due to it gets executed. [taker_order_info] - TakerOrderUpdated(Order), + TakerOrderUpdated( + Order, T::Price, T::BlockNumber>, + ), /// Overall information about the maker and taker orders when there was an order execution. [order_executed_info] - OrderExecuted(OrderExecutedInfo), + OrderExecuted(OrderExecutedInfo, T::BlockNumber, T::Price>), /// There is an update to the order due to it gets canceled. [order_info] - CanceledOrderUpdated(Order), + CanceledOrderUpdated( + Order, T::Price, T::BlockNumber>, + ), /// A new trading pair is added. [pair_profile] TradingPairAdded(TradingPairProfile), /// Trading pair profile has been updated. [pair_profile] @@ -174,11 +267,10 @@ decl_event!( /// Price fluctuation of trading pair has been updated. [pair_id, price_fluctuation] PriceFluctuationUpdated(TradingPairId, PriceFluctuation), } -); -decl_error! { /// Error for the spot module. - pub enum Error for Module { + #[pallet::error] + pub enum Error { /// Price can not be zero, and must be an integer multiple of the tick decimals. InvalidPrice, /// The bid price can not higher than the PriceVolatility of current lowest ask. @@ -216,142 +308,133 @@ decl_error! { /// Error from assets module. AssetError, } -} -impl From for Error { - fn from(_: AssetErr) -> Self { - Self::AssetError + /// How many trading pairs so far. + #[pallet::storage] + #[pallet::getter(fn trading_pair_count)] + pub(crate) type TradingPairCount = StorageValue<_, TradingPairId, ValueQuery>; + + /// Record the exact balance of reserved native coins in Spot. + #[pallet::storage] + #[pallet::getter(fn native_reserves)] + pub(crate) type NativeReserves = + StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; + + /// The map from trading pair id to its static profile. + #[pallet::storage] + #[pallet::getter(fn trading_pair_of)] + pub(crate) type TradingPairOf = + StorageMap<_, Twox64Concat, TradingPairId, TradingPairProfile>; + + /// (latest price, last update height) of trading pair + #[pallet::storage] + #[pallet::getter(fn trading_pair_info_of)] + pub(crate) type TradingPairInfoOf = + StorageMap<_, Twox64Concat, TradingPairId, TradingPairInfo>; + + /// Total transactions has been made for a trading pair. + #[pallet::storage] + #[pallet::getter(fn trading_history_index_of)] + pub(crate) type TradingHistoryIndexOf = + StorageMap<_, Twox64Concat, TradingPairId, TradingHistoryIndex, ValueQuery>; + + /// Total orders made by an account. + #[pallet::storage] + #[pallet::getter(fn order_count_of)] + pub(crate) type OrderCountOf = + StorageMap<_, Twox64Concat, T::AccountId, OrderId, ValueQuery>; + + /// Details of an user order given the account ID and order ID. + #[pallet::storage] + #[pallet::getter(fn order_info_of)] + pub(crate) type OrderInfoOf = + StorageDoubleMap<_, Twox64Concat, T::AccountId, Twox64Concat, OrderId, OrderInfo>; + + /// All the accounts and the order number given the trading pair ID and price. + #[pallet::storage] + #[pallet::getter(fn quotations_of)] + pub(crate) type QuotationsOf = StorageDoubleMap< + _, + Twox64Concat, + TradingPairId, + Twox64Concat, + T::Price, + Vec<(T::AccountId, OrderId)>, + ValueQuery, + >; + + /// TradingPairId => (highest_bid, lowest_ask) + #[pallet::storage] + #[pallet::getter(fn handicap_of)] + pub(crate) type HandicapOf = + StorageMap<_, Twox64Concat, TradingPairId, HandicapInfo, ValueQuery>; + + #[pallet::type_value] + pub fn DefaultForPriceFluctuationOf() -> PriceFluctuation { + DEFAULT_FLUCTUATION } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - - type Error = Error; - fn deposit_event() = default; - - #[weight = ::WeightInfo::put_order()] - pub fn put_order( - origin, - #[compact] pair_id: TradingPairId, - order_type: OrderType, - side: Side, - #[compact] amount: BalanceOf, - #[compact] price: T::Price - ) { - let who = ensure_signed(origin)?; - - ensure!(!price.is_zero(), Error::::InvalidPrice); - ensure!(!amount.is_zero(), Error::::ZeroAmount); - ensure!(order_type == OrderType::Limit, Error::::InvalidOrderType); - - let pair = Self::trading_pair(pair_id)?; - - ensure!(pair.tradable, Error::::TradingPairUntradable); - ensure!(pair.is_valid_price(price), Error::::InvalidPrice); - - Self::is_valid_quote(price, side, pair_id)?; - Self::has_too_many_backlog_orders(pair_id, price, side)?; - - // Reserve the token according to the order side. - let (reserve_asset, reserve_amount) = match side { - Side::Buy => (pair.quote(), Self::convert_base_to_quote(amount, price, &pair)?), - Side::Sell => (pair.base(), amount) - }; - Self::put_order_reserve(&who, reserve_asset, reserve_amount)?; - Self::apply_put_order(who, pair_id, order_type, side, amount, price, reserve_amount)?; - } - - #[weight = ::WeightInfo::cancel_order()] - pub fn cancel_order( - origin, - #[compact] pair_id: TradingPairId, - #[compact] order_id: OrderId - ) { - let who = ensure_signed(origin)?; - Self::do_cancel_order(&who, pair_id, order_id)?; - } - - /// Force cancel an order. - #[weight = ::WeightInfo::force_cancel_order()] - fn force_cancel_order( - origin, - who: ::Source, - #[compact] pair_id: TradingPairId, - #[compact] order_id: OrderId - ) { - ensure_root(origin)?; - let who = T::Lookup::lookup(who)?; - Self::do_cancel_order(&who, pair_id, order_id)?; - } - - #[weight = ::WeightInfo::set_handicap()] - fn set_handicap(origin, #[compact] pair_id: TradingPairId, new: Handicap< T::Price>) { - ensure_root(origin)?; - info!(target: "runtime::dex::spot", "[set_handicap] pair_id:{:?}, new handicap:{:?}", pair_id, new); - HandicapOf::::insert(pair_id, new); - } + /// The map of trading pair ID to the price fluctuation. Use with caution! + #[pallet::storage] + #[pallet::getter(fn price_fluctuation_of)] + pub(crate) type PriceFluctuationOf = StorageMap< + _, + Twox64Concat, + TradingPairId, + PriceFluctuation, + ValueQuery, + DefaultForPriceFluctuationOf, + >; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub trading_pairs: Vec<(AssetId, AssetId, u32, u32, T::Price, bool)>, + } - #[weight = ::WeightInfo::set_price_fluctuation()] - fn set_price_fluctuation( - origin, - #[compact] pair_id: TradingPairId, - #[compact] new: PriceFluctuation - ) { - ensure_root(origin)?; - PriceFluctuationOf::insert(pair_id, new); - Self::deposit_event(Event::::PriceFluctuationUpdated(pair_id, new)); + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { + trading_pairs: Default::default(), + } } + } - /// Add a new trading pair. - #[weight = ::WeightInfo::add_trading_pair()] - pub fn add_trading_pair( - origin, - currency_pair: CurrencyPair, - #[compact] pip_decimals: u32, - #[compact] tick_decimals: u32, - #[compact] latest_price: T::Price, - tradable: bool, - ) { - ensure_root(origin)?; - ensure!( - Self::get_trading_pair_by_currency_pair(¤cy_pair).is_none(), - Error::::TradingPairAlreadyExists - ); - Self::apply_add_trading_pair( - currency_pair, - pip_decimals, - tick_decimals, - latest_price, - tradable - ); + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + let extra_genesis_builder: fn(&Self) = |config| { + for (base, quote, pip_decimals, tick_decimals, price, tradable) in + config.trading_pairs.iter() + { + Pallet::::apply_add_trading_pair( + CurrencyPair::new(*base, *quote), + *pip_decimals, + *tick_decimals, + *price, + *tradable, + ); + } + }; + extra_genesis_builder(self); } + } +} - /// Update the trading pair profile. - #[weight = ::WeightInfo::update_trading_pair()] - pub fn update_trading_pair( - origin, - #[compact] pair_id: TradingPairId, - #[compact] tick_decimals: u32, - tradable: bool - ) { - ensure_root(origin)?; - let pair = Self::trading_pair(pair_id)?; - ensure!(tick_decimals >= pair.tick_decimals, Error::::InvalidTickdecimals); - Self::apply_update_trading_pair(pair_id, tick_decimals, tradable); - } +impl From for Error { + fn from(_: AssetErr) -> Self { + Self::AssetError } } -impl Module { +impl Pallet { /// Public mutables pub fn get_trading_pair_by_currency_pair( currency_pair: &CurrencyPair, ) -> Option { - let pair_count = TradingPairCount::get(); + let pair_count = TradingPairCount::::get(); for i in 0..pair_count { - if let Some(pair) = TradingPairOf::get(i) { + if let Some(pair) = TradingPairOf::::get(i) { if pair.base() == currency_pair.base && pair.quote() == currency_pair.quote { return Some(pair); } @@ -362,7 +445,7 @@ impl Module { #[inline] fn trading_pair(pair_id: TradingPairId) -> Result> { - TradingPairOf::get(pair_id).ok_or(Error::::InvalidTradingPair) + TradingPairOf::::get(pair_id).ok_or(Error::::InvalidTradingPair) } fn get_order(who: &T::AccountId, order_id: OrderId) -> Result, Error> { @@ -377,7 +460,7 @@ impl Module { latest_price: T::Price, tradable: bool, ) { - let pair_id = TradingPairCount::get(); + let pair_id = TradingPairCount::::get(); let pair = TradingPairProfile { id: pair_id, @@ -389,7 +472,7 @@ impl Module { info!(target: "runtime::dex::spot", "New trading pair: {:?}", pair); - TradingPairOf::insert(pair_id, &pair); + TradingPairOf::::insert(pair_id, &pair); TradingPairInfoOf::::insert( pair_id, TradingPairInfo { @@ -398,7 +481,7 @@ impl Module { }, ); - TradingPairCount::put(pair_id + 1); + TradingPairCount::::put(pair_id + 1); Self::deposit_event(Event::::TradingPairAdded(pair)); } @@ -409,7 +492,7 @@ impl Module { "[update_trading_pair] pair_id: {:}, tick_decimals: {:}, tradable:{:}", pair_id, tick_decimals, tradable ); - TradingPairOf::mutate(pair_id, |pair| { + TradingPairOf::::mutate(pair_id, |pair| { if let Some(pair) = pair { pair.tick_decimals = tick_decimals; pair.tradable = tradable; @@ -498,14 +581,14 @@ impl Module { } } -impl xpallet_assets_registrar::RegistrarHandler for Module { +impl xpallet_assets_registrar::RegistrarHandler for Pallet { fn on_deregister(token: &AssetId) -> DispatchResult { - let pair_len = TradingPairCount::get(); + let pair_len = TradingPairCount::::get(); for i in 0..pair_len { - if let Some(mut pair) = TradingPairOf::get(i) { + if let Some(mut pair) = TradingPairOf::::get(i) { if pair.base().eq(token) || pair.quote().eq(token) { pair.tradable = false; - TradingPairOf::insert(i, &pair); + TradingPairOf::::insert(i, &pair); Self::deposit_event(Event::::TradingPairUpdated(pair)); } } diff --git a/xpallets/dex/spot/src/mock.rs b/xpallets/dex/spot/src/mock.rs index 2d85711ce..c68376518 100644 --- a/xpallets/dex/spot/src/mock.rs +++ b/xpallets/dex/spot/src/mock.rs @@ -5,7 +5,11 @@ use std::{ collections::{BTreeMap, HashSet}, }; -use frame_support::{parameter_types, traits::Get, weights::Weight}; +use frame_support::{ + parameter_types, + traits::{GenesisBuild, Get}, + weights::Weight, +}; use sp_core::H256; use sp_runtime::{ testing::Header, diff --git a/xpallets/dex/spot/src/rpc.rs b/xpallets/dex/spot/src/rpc.rs index 546b4faae..4312d5863 100644 --- a/xpallets/dex/spot/src/rpc.rs +++ b/xpallets/dex/spot/src/rpc.rs @@ -57,7 +57,7 @@ pub struct Depth { pub bids: Vec<(Price, Balance)>, } -impl Module { +impl Pallet { /// Returns the range of a valid quotation for a trading pair. fn get_quotation_range(profile: &TradingPairProfile) -> (T::Price, T::Price) { let handicap = Self::handicap_of(profile.id); diff --git a/xpallets/dex/spot/src/types.rs b/xpallets/dex/spot/src/types.rs index 10a6aea92..114598ea5 100644 --- a/xpallets/dex/spot/src/types.rs +++ b/xpallets/dex/spot/src/types.rs @@ -205,7 +205,7 @@ impl TradingPairProfile { /// The maximum ticks that the price can deviate from the handicap. pub fn calc_fluctuation(&self) -> Tick { - let price_fluctuation = >::price_fluctuation_of(self.id); + let price_fluctuation = >::price_fluctuation_of(self.id); price_fluctuation .saturated_into::() .saturating_mul(self.tick()) diff --git a/xpallets/gateway/common/rpc/src/lib.rs b/xpallets/gateway/common/rpc/src/lib.rs index 893d34abc..56bee89c8 100644 --- a/xpallets/gateway/common/rpc/src/lib.rs +++ b/xpallets/gateway/common/rpc/src/lib.rs @@ -171,7 +171,7 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XGatewayCommonRuntimeApi, AccountId: Codec + Send + Sync + 'static, - Balance: Codec + Display + FromStr + Send + Sync + 'static + From + Default, + Balance: Codec + Display + FromStr + Send + Sync + 'static + From, { fn bound_addrs( &self, diff --git a/xpallets/gateway/common/src/lib.rs b/xpallets/gateway/common/src/lib.rs index 25487d859..cc3f8cb6a 100644 --- a/xpallets/gateway/common/src/lib.rs +++ b/xpallets/gateway/common/src/lib.rs @@ -22,11 +22,9 @@ pub mod utils; pub mod weights; use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, dispatch::{DispatchError, DispatchResult}, ensure, log::{error, info}, - IterableStorageMap, }; use frame_system::{ensure_root, ensure_signed}; use sp_runtime::traits::StaticLookup; @@ -44,179 +42,82 @@ use self::types::{ TrusteeIntentionProps, }; pub use self::weights::WeightInfo; +pub use pallet::*; -pub trait Config: xpallet_gateway_records::Config { - type Event: From> + Into<::Event>; +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; - type Validator: Validator; + #[pallet::config] + pub trait Config: frame_system::Config + xpallet_gateway_records::Config { + type Event: From> + IsType<::Event>; - type DetermineMultisigAddress: MultisigAddressFor; + type Validator: Validator; - // for bitcoin - type Bitcoin: ChainT>; - type BitcoinTrustee: TrusteeForChain< - Self::AccountId, - trustees::bitcoin::BtcTrusteeType, - trustees::bitcoin::BtcTrusteeAddrInfo, - >; + type DetermineMultisigAddress: MultisigAddressFor; - type WeightInfo: WeightInfo; -} + // for bitcoin + type Bitcoin: ChainT>; + type BitcoinTrustee: TrusteeForChain< + Self::AccountId, + trustees::bitcoin::BtcTrusteeType, + trustees::bitcoin::BtcTrusteeAddrInfo, + >; -decl_event!( - pub enum Event where - ::AccountId, - { - /// A (potential) trustee set the required properties. [who, chain, trustee_props] - SetTrusteeProps(AccountId, Chain, GenericTrusteeIntentionProps), - /// An account set its referral_account of some chain. [who, chain, referral_account] - ReferralBinded(AccountId, Chain, AccountId), - /// The trustee set of a chain was changed. [chain, session_number, session_info] - TrusteeSetChanged(Chain, u32, GenericTrusteeSessionInfo), + type WeightInfo: WeightInfo; } -); -decl_error! { - /// Error for the This Module - pub enum Error for Module { - /// the value of withdrawal less than than the minimum value - InvalidWithdrawal, - /// convert generic data into trustee session info error - InvalidGenericData, - /// trustee session info not found - InvalidTrusteeSession, - /// exceed the maximum length of the about field of trustess session info - InvalidAboutLen, - /// invalid multisig - InvalidMultisig, - /// Unsupported chain - NotSupportedChain, - /// existing duplicate account - DuplicatedAccountId, - /// not registered as trustee - NotRegistered, - /// just allow validator to register trustee - NotValidator, - } -} - -decl_storage! { - trait Store for Module as XGatewayCommon { - // Trustee multisig address of the corresponding chain. - pub TrusteeMultiSigAddr get(fn trustee_multisig_addr): - map hasher(twox_64_concat) Chain => T::AccountId; - - /// Trustee info config of the corresponding chain. - pub TrusteeInfoConfigOf get(fn trustee_info_config_of): - map hasher(twox_64_concat) Chain => TrusteeInfoConfig; - - /// Next Trustee session info number of the chain. - /// - /// Auto generate a new session number (0) when generate new trustee of a chain. - /// If the trustee of a chain is changed, the corresponding number will increase by 1. - /// - /// NOTE: The number can't be modified by users. - pub TrusteeSessionInfoLen get(fn trustee_session_info_len): - map hasher(twox_64_concat) Chain => u32 = 0; - - /// Trustee session info of the corresponding chain and number. - pub TrusteeSessionInfoOf get(fn trustee_session_info_of): - double_map hasher(twox_64_concat) Chain, hasher(twox_64_concat) u32 - => Option>; - - /// Trustee intention properties of the corresponding account and chain. - pub TrusteeIntentionPropertiesOf get(fn trustee_intention_props_of): - double_map hasher(blake2_128_concat) T::AccountId, hasher(twox_64_concat) Chain - => Option; - - /// The account of the corresponding chain and chain address. - pub AddressBindingOf: - double_map hasher(twox_64_concat) Chain, hasher(blake2_128_concat) ChainAddress - => Option; - - /// The bound address of the corresponding account and chain. - pub BoundAddressOf: - double_map hasher(blake2_128_concat) T::AccountId, hasher(twox_64_concat) Chain - => Vec; - - /// The referral account of the corresponding account and chain. - pub ReferralBindingOf get(fn referral_binding_of): - double_map hasher(blake2_128_concat) T::AccountId, hasher(twox_64_concat) Chain - => Option; - } - add_extra_genesis { - config(trustees): Vec<(Chain, TrusteeInfoConfig, Vec<(T::AccountId, Text, Vec, Vec)>)>; - build(|config| { - for (chain, info_config, trustee_infos) in config.trustees.iter() { - let mut trustees = Vec::with_capacity(trustee_infos.len()); - for (who, about, hot, cold) in trustee_infos.iter() { - Module::::setup_trustee_impl( - who.clone(), - *chain, - about.clone(), - hot.clone(), - cold.clone(), - ) - .expect("setup trustee can not fail; qed"); - trustees.push(who.clone()); - } - // config set should before transition - TrusteeInfoConfigOf::insert(chain, info_config.clone()); - // trustee init should happen in chain module like gateway_bitcoin/gateway_ethereum. - } - }) - } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - type Error = Error; - - fn deposit_event() = default; + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData); + #[pallet::call] + impl Pallet { /// Create a withdrawal. /// Withdraws some balances of `asset_id` to address `addr` of target chain. /// /// WithdrawalRecord State: `Applying` /// /// NOTE: `ext` is for the compatibility purpose, e.g., EOS requires a memo when doing the transfer. - #[weight = ::WeightInfo::withdraw()] + #[pallet::weight(::WeightInfo::withdraw())] pub fn withdraw( - origin, - #[compact] asset_id: AssetId, - #[compact] value: BalanceOf, + origin: OriginFor, + #[pallet::compact] asset_id: AssetId, + #[pallet::compact] value: BalanceOf, addr: AddrStr, - ext: Memo + ext: Memo, ) -> DispatchResult { let who = ensure_signed(origin)?; ensure!( - xpallet_assets::Module::::can_do(&asset_id, AssetRestrictions::WITHDRAW), + xpallet_assets::Pallet::::can_do(&asset_id, AssetRestrictions::WITHDRAW), xpallet_assets::Error::::ActionNotAllowed, ); Self::verify_withdrawal(asset_id, value, &addr, &ext)?; - xpallet_gateway_records::Module::::withdraw(&who, asset_id, value, addr, ext)?; + xpallet_gateway_records::Pallet::::withdraw(&who, asset_id, value, addr, ext)?; Ok(()) } /// Cancel the withdrawal by the applicant. /// /// WithdrawalRecord State: `Applying` ==> `NormalCancel` - #[weight = ::WeightInfo::cancel_withdrawal()] - pub fn cancel_withdrawal(origin, id: WithdrawalRecordId) -> DispatchResult { + #[pallet::weight(::WeightInfo::cancel_withdrawal())] + pub fn cancel_withdrawal(origin: OriginFor, id: WithdrawalRecordId) -> DispatchResult { let from = ensure_signed(origin)?; - xpallet_gateway_records::Module::::cancel_withdrawal(id, &from) + xpallet_gateway_records::Pallet::::cancel_withdrawal(id, &from) } /// Setup the trustee. - #[weight = ::WeightInfo::setup_trustee()] + #[pallet::weight(::WeightInfo::setup_trustee())] pub fn setup_trustee( - origin, + origin: OriginFor, chain: Chain, about: Text, hot_entity: Vec, - cold_entity: Vec + cold_entity: Vec, ) -> DispatchResult { let who = ensure_signed(origin)?; ensure!(T::Validator::is_validator(&who), Error::::NotValidator); @@ -224,21 +125,21 @@ decl_module! { } /// Transition the trustee session. - #[weight = ::WeightInfo::transition_trustee_session(new_trustees.len() as u32)] + #[pallet::weight(::WeightInfo::transition_trustee_session(new_trustees.len() as u32))] pub fn transition_trustee_session( - origin, + origin: OriginFor, chain: Chain, - new_trustees: Vec + new_trustees: Vec, ) -> DispatchResult { match ensure_signed(origin.clone()) { Ok(who) => { if who != Self::trustee_multisig_addr(chain) { return Err(Error::::InvalidMultisig.into()); } - }, + } Err(_) => { ensure_root(origin)?; - }, + } }; info!( @@ -251,11 +152,11 @@ decl_module! { } /// Set the state of withdraw record by the trustees. - #[weight = ::WeightInfo::set_withdrawal_state()] + #[pallet::weight(::WeightInfo::set_withdrawal_state())] pub fn set_withdrawal_state( - origin, - #[compact] id: WithdrawalRecordId, - state: WithdrawalState + origin: OriginFor, + #[pallet::compact] id: WithdrawalRecordId, + state: WithdrawalState, ) -> DispatchResult { let from = ensure_signed(origin)?; @@ -265,28 +166,32 @@ decl_module! { .find_map(|(chain, multisig)| if from == multisig { Some(chain) } else { None }) .ok_or(Error::::InvalidMultisig)?; - xpallet_gateway_records::Module::::set_withdrawal_state_by_trustees(id, chain, state) + xpallet_gateway_records::Pallet::::set_withdrawal_state_by_trustees(id, chain, state) } /// Set the config of trustee information. /// /// This is a root-only operation. - #[weight = ::WeightInfo::set_trustee_info_config()] - pub fn set_trustee_info_config(origin, chain: Chain, config: TrusteeInfoConfig) -> DispatchResult { + #[pallet::weight(::WeightInfo::set_trustee_info_config())] + pub fn set_trustee_info_config( + origin: OriginFor, + chain: Chain, + config: TrusteeInfoConfig, + ) -> DispatchResult { ensure_root(origin)?; - TrusteeInfoConfigOf::insert(chain, config); + TrusteeInfoConfigOf::::insert(chain, config); Ok(()) } /// Set the referral binding of corresponding chain and account. /// /// This is a root-only operation. - #[weight = ::WeightInfo::force_set_referral_binding()] + #[pallet::weight(::WeightInfo::force_set_referral_binding())] pub fn force_set_referral_binding( - origin, + origin: OriginFor, chain: Chain, who: ::Source, - referral: ::Source + referral: ::Source, ) -> DispatchResult { ensure_root(origin)?; let who = T::Lookup::lookup(who)?; @@ -295,14 +200,164 @@ decl_module! { Ok(()) } } + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + #[pallet::metadata(T::AccountId = "AccountId")] + pub enum Event { + /// A (potential) trustee set the required properties. [who, chain, trustee_props] + SetTrusteeProps(T::AccountId, Chain, GenericTrusteeIntentionProps), + /// An account set its referral_account of some chain. [who, chain, referral_account] + ReferralBinded(T::AccountId, Chain, T::AccountId), + /// The trustee set of a chain was changed. [chain, session_number, session_info] + TrusteeSetChanged(Chain, u32, GenericTrusteeSessionInfo), + } + + #[pallet::error] + pub enum Error { + /// the value of withdrawal less than than the minimum value + InvalidWithdrawal, + /// convert generic data into trustee session info error + InvalidGenericData, + /// trustee session info not found + InvalidTrusteeSession, + /// exceed the maximum length of the about field of trustess session info + InvalidAboutLen, + /// invalid multisig + InvalidMultisig, + /// Unsupported chain + NotSupportedChain, + /// existing duplicate account + DuplicatedAccountId, + /// not registered as trustee + NotRegistered, + /// just allow validator to register trustee + NotValidator, + } + + #[pallet::storage] + #[pallet::getter(fn trustee_multisig_addr)] + pub type TrusteeMultiSigAddr = + StorageMap<_, Twox64Concat, Chain, T::AccountId, ValueQuery>; + + /// Trustee info config of the corresponding chain. + #[pallet::storage] + #[pallet::getter(fn trustee_info_config_of)] + pub type TrusteeInfoConfigOf = + StorageMap<_, Twox64Concat, Chain, TrusteeInfoConfig, ValueQuery>; + + #[pallet::type_value] + pub fn DefaultForTrusteeSessionInfoLen() -> u32 { + 0 + } + + /// Next Trustee session info number of the chain. + /// + /// Auto generate a new session number (0) when generate new trustee of a chain. + /// If the trustee of a chain is changed, the corresponding number will increase by 1. + /// + /// NOTE: The number can't be modified by users. + #[pallet::storage] + #[pallet::getter(fn trustee_session_info_len)] + pub type TrusteeSessionInfoLen = + StorageMap<_, Twox64Concat, Chain, u32, ValueQuery, DefaultForTrusteeSessionInfoLen>; + + /// Trustee session info of the corresponding chain and number. + #[pallet::storage] + #[pallet::getter(fn trustee_session_info_of)] + pub type TrusteeSessionInfoOf = StorageDoubleMap< + _, + Twox64Concat, + Chain, + Twox64Concat, + u32, + GenericTrusteeSessionInfo, + >; + + /// Trustee intention properties of the corresponding account and chain. + #[pallet::storage] + #[pallet::getter(fn trustee_intention_props_of)] + pub type TrusteeIntentionPropertiesOf = StorageDoubleMap< + _, + Blake2_128Concat, + T::AccountId, + Twox64Concat, + Chain, + GenericTrusteeIntentionProps, + >; + + /// The account of the corresponding chain and chain address. + #[pallet::storage] + pub type AddressBindingOf = + StorageDoubleMap<_, Twox64Concat, Chain, Blake2_128Concat, ChainAddress, T::AccountId>; + + /// The bound address of the corresponding account and chain. + #[pallet::storage] + pub type BoundAddressOf = StorageDoubleMap< + _, + Blake2_128Concat, + T::AccountId, + Twox64Concat, + Chain, + Vec, + ValueQuery, + >; + + /// The referral account of the corresponding account and chain. + #[pallet::storage] + #[pallet::getter(fn referral_binding_of)] + pub type ReferralBindingOf = + StorageDoubleMap<_, Blake2_128Concat, T::AccountId, Twox64Concat, Chain, T::AccountId>; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub trustees: Vec<( + Chain, + TrusteeInfoConfig, + Vec<(T::AccountId, Text, Vec, Vec)>, + )>, + } + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { + trustees: Default::default(), + } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + let extra_genesis_builder: fn(&Self) = |config| { + for (chain, info_config, trustee_infos) in config.trustees.iter() { + let mut trustees = Vec::with_capacity(trustee_infos.len()); + for (who, about, hot, cold) in trustee_infos.iter() { + Pallet::::setup_trustee_impl( + who.clone(), + *chain, + about.clone(), + hot.clone(), + cold.clone(), + ) + .expect("setup trustee can not fail; qed"); + trustees.push(who.clone()); + } + TrusteeInfoConfigOf::::insert(chain, info_config.clone()); + } + }; + extra_genesis_builder(self); + } + } } // withdraw -impl Module { +impl Pallet { pub fn withdrawal_limit( asset_id: &AssetId, ) -> Result>, DispatchError> { - let chain = xpallet_assets_registrar::Module::::chain_of(asset_id)?; + let chain = xpallet_assets_registrar::Pallet::::chain_of(asset_id)?; match chain { Chain::Bitcoin => T::Bitcoin::withdrawal_limit(&asset_id), _ => Err(Error::::NotSupportedChain.into()), @@ -317,7 +372,7 @@ impl Module { ) -> DispatchResult { ext.check_validity()?; - let chain = xpallet_assets_registrar::Module::::chain_of(&asset_id)?; + let chain = xpallet_assets_registrar::Pallet::::chain_of(&asset_id)?; match chain { Chain::Bitcoin => { // bitcoin do not need memo @@ -346,7 +401,7 @@ pub fn is_valid_about(about: &[u8]) -> DispatchResult { } // trustees -impl Module { +impl Pallet { pub fn setup_trustee_impl( who: T::AccountId, chain: Chain, @@ -435,7 +490,7 @@ impl Module { // FIXME: rethink about the overflow case. let next_number = session_number.checked_add(1).unwrap_or(0u32); - TrusteeSessionInfoLen::insert(chain, next_number); + TrusteeSessionInfoLen::::insert(chain, next_number); TrusteeSessionInfoOf::::insert(chain, session_number, info.clone()); TrusteeMultiSigAddr::::insert(chain, multi_addr); @@ -467,7 +522,7 @@ impl Module { } } -impl Module { +impl Pallet { pub fn trustee_multisigs() -> BTreeMap { TrusteeMultiSigAddr::::iter().collect() } diff --git a/xpallets/gateway/common/src/mock.rs b/xpallets/gateway/common/src/mock.rs index 19f6cf702..150baccce 100644 --- a/xpallets/gateway/common/src/mock.rs +++ b/xpallets/gateway/common/src/mock.rs @@ -3,8 +3,10 @@ use std::{cell::RefCell, convert::TryFrom, time::Duration}; use codec::{Decode, Encode}; -use frame_support::traits::UnixTime; -use frame_support::{parameter_types, sp_io}; +use frame_support::{ + parameter_types, sp_io, + traits::{GenesisBuild, UnixTime}, +}; use frame_system::EnsureSignedBy; use sp_core::{crypto::UncheckedInto, H256}; use sp_io::hashing::blake2_256; diff --git a/xpallets/gateway/records/src/mock.rs b/xpallets/gateway/records/src/mock.rs index 5c8a319e0..e804be402 100644 --- a/xpallets/gateway/records/src/mock.rs +++ b/xpallets/gateway/records/src/mock.rs @@ -1,6 +1,6 @@ // Copyright 2019-2020 ChainX Project Authors. Licensed under GPL-3.0. -use frame_support::{parameter_types, sp_io}; +use frame_support::{parameter_types, sp_io, traits::GenesisBuild}; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -8,10 +8,11 @@ use sp_runtime::{ }; use chainx_primitives::AssetId; -pub use xp_protocol::{X_BTC, X_ETH}; use xpallet_assets::AssetRestrictions; use xpallet_assets_registrar::AssetInfo; +pub use xp_protocol::{X_BTC, X_ETH}; + use crate::{self as xpallet_gateway_records, *}; /// The AccountId alias in this test module. diff --git a/xpallets/mining/asset/rpc/src/lib.rs b/xpallets/mining/asset/rpc/src/lib.rs index 9bfd727cb..9e363afba 100644 --- a/xpallets/mining/asset/rpc/src/lib.rs +++ b/xpallets/mining/asset/rpc/src/lib.rs @@ -85,8 +85,8 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XMiningAssetRuntimeApi, AccountId: Codec, - Balance: Codec + Display + FromStr + Default, - MiningWeight: Codec + Display + FromStr + Default, + Balance: Codec + Display + FromStr, + MiningWeight: Codec + Display + FromStr, BlockNumber: Codec, { fn mining_assets( diff --git a/xpallets/mining/staking/rpc/src/lib.rs b/xpallets/mining/staking/rpc/src/lib.rs index e2864bab2..2df4ea0e3 100644 --- a/xpallets/mining/staking/rpc/src/lib.rs +++ b/xpallets/mining/staking/rpc/src/lib.rs @@ -100,8 +100,8 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XStakingRuntimeApi, AccountId: Codec + Ord, - Balance: Codec + Display + FromStr + Default, - VoteWeight: Codec + Display + FromStr + Default, + Balance: Codec + Display + FromStr, + VoteWeight: Codec + Display + FromStr, BlockNumber: Codec, { fn validators( diff --git a/xpallets/system/src/lib.rs b/xpallets/system/src/lib.rs index 23008db74..f917baf9d 100644 --- a/xpallets/system/src/lib.rs +++ b/xpallets/system/src/lib.rs @@ -7,71 +7,55 @@ use sp_std::{collections::btree_map::BTreeMap, prelude::*}; use sp_runtime::traits::StaticLookup; use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, dispatch::{CallMetadata, DispatchResult}, traits::Currency, - IterableStorageMap, }; -use frame_system::ensure_root; +use frame_system::ensure_root; use xp_protocol::NetworkType; +pub use pallet::*; + const PALLET_MARK: &[u8; 1] = b"#"; const ALWAYS_ALLOW: [&str; 1] = ["Sudo"]; -/// The module's config trait. +/// The pallet's config trait. /// /// `frame_system::Config` should always be included in our implied traits. -pub trait Config: frame_system::Config { - /// The overarching event type. - type Event: From> + Into<::Event>; - - /// The currency mechanism. - type Currency: Currency; -} - -decl_error! { - /// Error for the XSystem Module - pub enum Error for Module {} -} - -decl_event!( - /// Event for the XSystem Module - pub enum Event - where - ::AccountId, - { - /// An account was added to the blacklist. [who] - Blacklisted(AccountId), - /// An account was removed from the blacklist. [who] - Unblacklisted(AccountId), - } -); - -decl_storage! { - trait Store for Module as XSystem { - /// Network property (Mainnet / Testnet). - pub NetworkProps get(fn network_props) config(): NetworkType; - - /// Paused pallet call. - pub Paused get(fn paused): map hasher(twox_64_concat) Vec => BTreeMap, ()>; - - /// The accounts that are blocked. - pub Blacklist get(fn blacklist): map hasher(blake2_128_concat) T::AccountId => bool; +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + + /// The pallet's config trait. + /// + /// `frame_system::Config` should always be included in our implied traits. + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type Event: From> + IsType<::Event>; + + /// The currency mechanism. + type Currency: Currency; } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - type Error = Error; - fn deposit_event() = default; + #[pallet::pallet] + #[pallet::generate_store(pub(crate) trait Store)] + pub struct Pallet(PhantomData); + #[pallet::call] + impl Pallet { /// Modify the paused status of the given pallet call. /// /// This is a root-only operation. - #[weight = 0] - pub fn modify_paused(origin, pallet: Vec, call: Option>, should_paused: bool) -> DispatchResult { + #[pallet::weight(0)] + pub fn modify_paused( + origin: OriginFor, + pallet: Vec, + call: Option>, + should_paused: bool, + ) -> DispatchResult { ensure_root(origin)?; let mut paused = Self::paused(&pallet); @@ -95,9 +79,9 @@ decl_module! { } if paused.is_empty() { - Paused::remove(&pallet); + Paused::::remove(&pallet); } else { - Paused::insert(pallet, paused); + Paused::::insert(pallet, paused); } Ok(()) } @@ -105,8 +89,12 @@ decl_module! { /// Toggle the blacklist status of the given account id. /// /// This is a root-only operation. - #[weight = 0] - fn toggle_blacklist(origin, who: ::Source, should_blacklist: bool) -> DispatchResult { + #[pallet::weight(0)] + fn toggle_blacklist( + origin: OriginFor, + who: ::Source, + should_blacklist: bool, + ) -> DispatchResult { ensure_root(origin)?; let who = T::Lookup::lookup(who)?; @@ -120,9 +108,56 @@ decl_module! { Ok(()) } } + + /// Event for the XSystem Pallet + #[pallet::event] + #[pallet::generate_deposit(pub(crate) fn deposit_event)] + #[pallet::metadata(T::AccountId = "AccountId")] + pub enum Event { + /// An account was added to the blacklist. [who] + Blacklisted(T::AccountId), + /// An account was removed from the blacklist. [who] + Unblacklisted(T::AccountId), + } + + /// Network property (Mainnet / Testnet). + #[pallet::storage] + #[pallet::getter(fn network_props)] + pub type NetworkProps = StorageValue<_, NetworkType, ValueQuery>; + + /// Paused pallet call + #[pallet::storage] + #[pallet::getter(fn paused)] + pub type Paused = StorageMap<_, Twox64Concat, Vec, BTreeMap, ()>, ValueQuery>; + + /// The accounts that are blocked + #[pallet::storage] + #[pallet::getter(fn blacklist)] + pub type Blacklist = StorageMap<_, Blake2_128Concat, T::AccountId, bool, ValueQuery>; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub network_props: NetworkType, + } + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { + network_props: Default::default(), + } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + NetworkProps::::put(self.network_props); + } + } } -impl Module { +impl Pallet { /// Returns true if the given pallet call has been paused. pub fn is_paused(metadata: CallMetadata) -> bool { if ALWAYS_ALLOW.contains(&metadata.pallet_name) { diff --git a/xpallets/transaction-fee/rpc/Cargo.toml b/xpallets/transaction-fee/rpc/Cargo.toml index ed5f412a2..f9580bf74 100644 --- a/xpallets/transaction-fee/rpc/Cargo.toml +++ b/xpallets/transaction-fee/rpc/Cargo.toml @@ -27,4 +27,8 @@ pallet-transaction-payment = { version = "3.0.0", default-features = false } xp-rpc = { path = "../../../primitives/rpc" } # ChainX pallets api +chainx-runtime = {path = "../../../runtime/chainx",default-features = false} +xpallet-transaction-fee = { path = "../", default-features = false } xpallet-transaction-fee-rpc-runtime-api = { path = "./runtime-api" } + + diff --git a/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs b/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs index 4c8a2a0b5..68c236ea5 100644 --- a/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs +++ b/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs @@ -1,18 +1,18 @@ -// Copyright 2019-2020 ChainX Project Authors. Licensed under GPL-3.0. +// // Copyright 2019-2020 ChainX Project Authors. Licensed under GPL-3.0. -//! Runtime API definition for transaction fee module. +// //! Runtime API definition for transaction fee module. -#![cfg_attr(not(feature = "std"), no_std)] +// #![cfg_attr(not(feature = "std"), no_std)] -use codec::Codec; -use sp_runtime::traits::{MaybeDisplay, MaybeFromStr}; +// use codec::Codec; +// use sp_runtime::traits::{MaybeDisplay, MaybeFromStr}; -pub use xpallet_transaction_fee::{FeeDetails, InclusionFee}; +// pub use xpallet_transaction_fee::{FeeDetails, InclusionFee}; -sp_api::decl_runtime_apis! { - pub trait XTransactionFeeApi where - Balance: Codec + MaybeDisplay + MaybeFromStr, - { - fn query_fee_details(uxt: Block::Extrinsic, len: u32) -> FeeDetails; - } -} +// sp_api::decl_runtime_apis! { +// pub trait XTransactionFeeApi where +// Balance: Codec + MaybeDisplay + MaybeFromStr, +// { +// fn query_fee_details(uxt: Block::Extrinsic, len: u32) -> FeeDetails; +// } +// } diff --git a/xpallets/transaction-fee/rpc/src/lib.rs b/xpallets/transaction-fee/rpc/src/lib.rs index 04f5580dd..94c8b4101 100644 --- a/xpallets/transaction-fee/rpc/src/lib.rs +++ b/xpallets/transaction-fee/rpc/src/lib.rs @@ -2,28 +2,30 @@ //! RPC interface for the transaction fee module. -use std::fmt::Debug; -use std::sync::Arc; - use codec::{Codec, Decode}; +use jsonrpc_core::serde_json::Number; use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; use jsonrpc_derive::rpc; +use sp_runtime::generic::Header; +use std::fmt::Debug; +use std::sync::Arc; +use chainx_runtime::impls::ChargeExtraFee; +use chainx_runtime::UncheckedExtrinsic; +use pallet_transaction_payment::InclusionFee; +use pallet_transaction_payment_rpc::Error; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_core::Bytes; use sp_runtime::{ + generic, generic::BlockId, traits::{Block as BlockT, MaybeDisplay, MaybeFromStr}, }; - -use pallet_transaction_payment_rpc::Error; - -use xp_rpc::RpcBalance; -use xpallet_transaction_fee_rpc_runtime_api::FeeDetails; - -pub use xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi as XTransactionFeeRuntimeApi; - +use xp_rpc::{RpcBalance, RpcU128}; +use xpallet_transaction_fee::FeeDetails; +//pub use xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi as XTransactionFeeRuntimeApi; +pub use pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi as XTransactionFeeRuntimeApi; #[rpc] pub trait XTransactionFeeApi { #[rpc(name = "xfee_queryDetails")] @@ -52,7 +54,8 @@ where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XTransactionFeeRuntimeApi, - Balance: Codec + MaybeDisplay + MaybeFromStr + Default, + Balance: Codec + MaybeDisplay + MaybeFromStr, + RpcU128: From + From, { fn query_fee_details( &self, @@ -64,24 +67,49 @@ where let encoded_len = encoded_xt.len() as u32; - let uxt: Block::Extrinsic = Decode::decode(&mut &*encoded_xt).map_err(into_rpc_err)?; + let uxt: ::Extrinsic = + Decode::decode(&mut &*encoded_xt).map_err(into_rpc_err)?; - api.query_fee_details(&at, uxt, encoded_len) - .map(|fee_details| FeeDetails { - base: pallet_transaction_payment::FeeDetails { - inclusion_fee: fee_details.base.inclusion_fee.map(|fee| { - pallet_transaction_payment::InclusionFee { - base_fee: fee.base_fee.into(), - len_fee: fee.len_fee.into(), - adjusted_weight_fee: fee.adjusted_weight_fee.into(), - } - }), - tip: fee_details.base.tip.into(), - }, - extra_fee: fee_details.extra_fee.into(), - final_fee: fee_details.final_fee.into(), + let result = api + .query_fee_details(&at, uxt, encoded_len) + .map(|fee_details| pallet_transaction_payment::FeeDetails { + inclusion_fee: fee_details.inclusion_fee.map(|fee| InclusionFee { + base_fee: fee.base_fee.into(), + len_fee: fee.len_fee.into(), + adjusted_weight_fee: fee.adjusted_weight_fee.into(), + }), + tip: fee_details.tip.into(), }) - .map_err(into_rpc_err) + .map_err(into_rpc_err); + let base = match result { + Ok(res) => res, + Err(Error) => return Err(Error), + }; + let uxt_clone = uxt.clone(); + if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { + let base_clone = base.clone(); + let total = match base.inclusion_fee { + Some(fee) => fee + .base_fee + .saturating_add(fee.len_fee) + .saturating_add(fee.adjusted_weight_fee) + .saturating_add(base.tip), + None => 0, + }; + Ok(FeeDetails { + inclusion_fee: base_clone.inclusion_fee, + tip: base.tip, + extra_fee: extra_fee.into(), + final_fee: total + extra_fee, + }) + } else { + Ok(FeeDetails { + inclusion_fee: base.inclusion_fee, + tip: base.tip, + extra_fee: 0u32.into(), + final_fee: base.tip, + }) + } } } diff --git a/xpallets/transaction-fee/src/lib.rs b/xpallets/transaction-fee/src/lib.rs index b69bdf4a2..1382cd150 100644 --- a/xpallets/transaction-fee/src/lib.rs +++ b/xpallets/transaction-fee/src/lib.rs @@ -13,20 +13,12 @@ mod types; -use codec::DecodeLimit; use sp_std::prelude::*; -use frame_support::{ - //decl_event, decl_module, pallet, - traits::Get, - weights::{ - DispatchClass, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, Weight, - WeightToFeePolynomial, - }, -}; +use frame_support::weights::{DispatchInfo, GetDispatchInfo}; use sp_runtime::{ - traits::{DispatchInfoOf, Dispatchable, PostDispatchInfoOf, Saturating}, - FixedPointNumber, FixedPointOperand, + traits::{Dispatchable, Saturating}, + FixedPointOperand, }; pub use self::types::FeeDetails; @@ -40,7 +32,6 @@ pub use pallet::*; pub mod pallet { use super::*; use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; #[pallet::pallet] #[pallet::generate_store(pub(crate) trait Store)] @@ -51,9 +42,6 @@ pub mod pallet { type Event: From> + IsType<::Event>; } - #[pallet::call] - impl Pallet {} - #[pallet::event] #[pallet::metadata(T::AccountId = "AccountId", BalanceOf = "Balance")] // Optional #[pallet::generate_deposit(pub(super) fn deposit_event)] // Optional @@ -63,51 +51,3 @@ pub mod pallet { FeePaid(T::AccountId, BalanceOf, T::AccountId, BalanceOf), } } - -impl Pallet -where - BalanceOf: FixedPointOperand, -{ - /// Returns the details of fee for a particular transaction. - /// - /// The basic logic is identical to [`compute_fee`] but returns - /// the details of final fee instead. - /// - /// [`compute_fee`]: https://docs.rs/pallet-transaction-payment/2.0.0/pallet_transaction_payment/struct.Module.html#method.compute_fee - pub fn query_fee_details( - unchecked_extrinsic: Extrinsic, - len: u32, - ) -> FeeDetails> - where - T: Send + Sync, - BalanceOf: Send + Sync + Default, - T::Call: Dispatchable, - { - let dispatch_info = ::get_dispatch_info(&unchecked_extrinsic); - let details = pallet_transaction_payment::Module::::compute_fee_details( - len, - &dispatch_info, - 0u32.into(), - ); - let details_clone = details.clone(); - match details.inclusion_fee { - Some(fee) => { - let total = fee - .base_fee - .saturating_add(fee.len_fee) - .saturating_add(fee.adjusted_weight_fee) - .saturating_add(details.tip); - FeeDetails { - base: details_clone, - extra_fee: 0u32.into(), - final_fee: total, - } - } - None => FeeDetails { - base: details_clone, - extra_fee: 0u32.into(), - final_fee: details.tip, - }, - } - } -} diff --git a/xpallets/transaction-fee/src/types.rs b/xpallets/transaction-fee/src/types.rs index 574319467..7703eea69 100644 --- a/xpallets/transaction-fee/src/types.rs +++ b/xpallets/transaction-fee/src/types.rs @@ -1,6 +1,7 @@ // Copyright 2019-2020 ChainX Project Authors. Licensed under GPL-3.0. use codec::{Decode, Encode}; +use pallet_transaction_payment::InclusionFee; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; @@ -17,9 +18,12 @@ use sp_runtime::RuntimeDebug; #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] -pub struct FeeDetails { - /// Some calls might be charged extra fee besides the essential `inclusion_fee`. - pub base: pallet_transaction_payment::FeeDetails, +pub struct FeeDetails { + /// The minimum fee for a transaction to be included in a block. + pub inclusion_fee: Option>, + // Do not serialize and deserialize `tip` as we actually can not pass any tip to the RPC. + #[cfg_attr(feature = "std", serde(skip))] + pub tip: Balance, pub extra_fee: Balance, pub final_fee: Balance, } From 32ad6faae49f5bed094917e4f69d98d7bd5bbc6c Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Fri, 18 Jun 2021 16:23:43 +0800 Subject: [PATCH 09/17] Remove duplicated functions in xpallets-transaction-fee lib.rs --- Cargo.lock | 2 - runtime/chainx/src/lib.rs | 34 +++++++++- runtime/dev/src/lib.rs | 51 ++++++++------ runtime/malan/src/lib.rs | 51 ++++++++------ xpallets/transaction-fee/rpc/Cargo.toml | 2 - .../rpc/runtime-api/src/lib.rs | 22 +++---- xpallets/transaction-fee/rpc/src/lib.rs | 66 +++++-------------- xpallets/transaction-fee/src/lib.rs | 18 +---- 8 files changed, 126 insertions(+), 120 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 341c26e44..f717f5706 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10164,7 +10164,6 @@ dependencies = [ name = "xpallet-transaction-fee-rpc" version = "2.0.9" dependencies = [ - "chainx-runtime", "jsonrpc-core", "jsonrpc-core-client", "jsonrpc-derive", @@ -10177,7 +10176,6 @@ dependencies = [ "sp-core", "sp-runtime", "xp-rpc", - "xpallet-transaction-fee", "xpallet-transaction-fee-rpc-runtime-api", ] diff --git a/runtime/chainx/src/lib.rs b/runtime/chainx/src/lib.rs index 3a8711ff2..d5cca8156 100644 --- a/runtime/chainx/src/lib.rs +++ b/runtime/chainx/src/lib.rs @@ -1330,6 +1330,39 @@ impl_runtime_apis! { } } + impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> xpallet_transaction_fee::FeeDetails { + if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { + let base = TransactionPayment::query_fee_details(uxt, len); + let base_clone = base.clone(); + let total = match base.inclusion_fee { + Some(fee) => fee + .base_fee + .saturating_add(fee.len_fee) + .saturating_add(fee.adjusted_weight_fee) + .saturating_add(base.tip), + None => 0,}; + xpallet_transaction_fee::FeeDetails { + inclusion_fee: base_clone.inclusion_fee, + tip: base.tip, + extra_fee: extra_fee.into(), + final_fee: total + extra_fee, + } + } else { + let base = TransactionPayment::query_fee_details(uxt, len); + xpallet_transaction_fee::FeeDetails { + inclusion_fee: base.inclusion_fee, + tip: base.tip, + extra_fee: 0u32.into(), + final_fee: base.tip, + } + } + } + } + impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { fn assets_for_account(who: AccountId) -> BTreeMap> { XAssets::valid_assets_of(&who) @@ -1472,5 +1505,4 @@ impl_runtime_apis! { Ok(batches) } } - } diff --git a/runtime/dev/src/lib.rs b/runtime/dev/src/lib.rs index a846c6a03..0c06f5dae 100644 --- a/runtime/dev/src/lib.rs +++ b/runtime/dev/src/lib.rs @@ -1340,25 +1340,38 @@ impl_runtime_apis! { } } - // impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { - // fn query_fee_details( - // uxt: ::Extrinsic, - // len: u32, - // ) -> xpallet_transaction_fee::FeeDetails { - // if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - // let details = XTransactionFee::query_fee_details(uxt, len); - // xpallet_transaction_fee::FeeDetails { - // extra_fee, - // final_fee: details.final_fee + extra_fee, - // ..details - // } - // } else { - // XTransactionFee::query_fee_details(uxt, len) - // } - - // } - // } - + impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> xpallet_transaction_fee::FeeDetails { + if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { + let base = TransactionPayment::query_fee_details(uxt, len); + let base_clone = base.clone(); + let total = match base.inclusion_fee { + Some(fee) => fee + .base_fee + .saturating_add(fee.len_fee) + .saturating_add(fee.adjusted_weight_fee) + .saturating_add(base.tip), + None => 0,}; + xpallet_transaction_fee::FeeDetails { + inclusion_fee: base_clone.inclusion_fee, + tip: base.tip, + extra_fee: extra_fee.into(), + final_fee: total + extra_fee, + } + } else { + let base = TransactionPayment::query_fee_details(uxt, len); + xpallet_transaction_fee::FeeDetails { + inclusion_fee: base.inclusion_fee, + tip: base.tip, + extra_fee: 0u32.into(), + final_fee: base.tip, + } + } + } + } impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { fn assets_for_account(who: AccountId) -> BTreeMap> { XAssets::valid_assets_of(&who) diff --git a/runtime/malan/src/lib.rs b/runtime/malan/src/lib.rs index 511f21189..00d5b6259 100644 --- a/runtime/malan/src/lib.rs +++ b/runtime/malan/src/lib.rs @@ -1337,25 +1337,38 @@ impl_runtime_apis! { } } - // impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { - // fn query_fee_details( - // uxt: ::Extrinsic, - // len: u32, - // ) -> xpallet_transaction_fee::FeeDetails { - // if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - // let details = XTransactionFee::query_fee_details(uxt, len); - // xpallet_transaction_fee::FeeDetails { - // extra_fee, - // final_fee: details.final_fee + extra_fee, - // ..details - // } - // } else { - // XTransactionFee::query_fee_details(uxt, len) - // } - - // } - // } - + impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> xpallet_transaction_fee::FeeDetails { + if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { + let base = TransactionPayment::query_fee_details(uxt, len); + let base_clone = base.clone(); + let total = match base.inclusion_fee { + Some(fee) => fee + .base_fee + .saturating_add(fee.len_fee) + .saturating_add(fee.adjusted_weight_fee) + .saturating_add(base.tip), + None => 0,}; + xpallet_transaction_fee::FeeDetails { + inclusion_fee: base_clone.inclusion_fee, + tip: base.tip, + extra_fee: extra_fee.into(), + final_fee: total + extra_fee, + } + } else { + let base = TransactionPayment::query_fee_details(uxt, len); + xpallet_transaction_fee::FeeDetails { + inclusion_fee: base.inclusion_fee, + tip: base.tip, + extra_fee: 0u32.into(), + final_fee: base.tip, + } + } + } + } impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { fn assets_for_account(who: AccountId) -> BTreeMap> { XAssets::valid_assets_of(&who) diff --git a/xpallets/transaction-fee/rpc/Cargo.toml b/xpallets/transaction-fee/rpc/Cargo.toml index f9580bf74..93b3f0069 100644 --- a/xpallets/transaction-fee/rpc/Cargo.toml +++ b/xpallets/transaction-fee/rpc/Cargo.toml @@ -27,8 +27,6 @@ pallet-transaction-payment = { version = "3.0.0", default-features = false } xp-rpc = { path = "../../../primitives/rpc" } # ChainX pallets api -chainx-runtime = {path = "../../../runtime/chainx",default-features = false} -xpallet-transaction-fee = { path = "../", default-features = false } xpallet-transaction-fee-rpc-runtime-api = { path = "./runtime-api" } diff --git a/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs b/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs index 68c236ea5..e9415892c 100644 --- a/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs +++ b/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs @@ -2,17 +2,17 @@ // //! Runtime API definition for transaction fee module. -// #![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(not(feature = "std"), no_std)] -// use codec::Codec; -// use sp_runtime::traits::{MaybeDisplay, MaybeFromStr}; +use codec::Codec; +use sp_runtime::traits::{MaybeDisplay, MaybeFromStr}; -// pub use xpallet_transaction_fee::{FeeDetails, InclusionFee}; +pub use xpallet_transaction_fee::{FeeDetails, InclusionFee}; -// sp_api::decl_runtime_apis! { -// pub trait XTransactionFeeApi where -// Balance: Codec + MaybeDisplay + MaybeFromStr, -// { -// fn query_fee_details(uxt: Block::Extrinsic, len: u32) -> FeeDetails; -// } -// } +sp_api::decl_runtime_apis! { + pub trait XTransactionFeeApi where + Balance: Codec + MaybeDisplay + MaybeFromStr, + { + fn query_fee_details(uxt: Block::Extrinsic, len: u32) -> FeeDetails; + } +} diff --git a/xpallets/transaction-fee/rpc/src/lib.rs b/xpallets/transaction-fee/rpc/src/lib.rs index 94c8b4101..10dd84440 100644 --- a/xpallets/transaction-fee/rpc/src/lib.rs +++ b/xpallets/transaction-fee/rpc/src/lib.rs @@ -2,30 +2,28 @@ //! RPC interface for the transaction fee module. +use std::fmt::Debug; +use std::sync::Arc; + use codec::{Codec, Decode}; -use jsonrpc_core::serde_json::Number; use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; use jsonrpc_derive::rpc; -use sp_runtime::generic::Header; -use std::fmt::Debug; -use std::sync::Arc; -use chainx_runtime::impls::ChargeExtraFee; -use chainx_runtime::UncheckedExtrinsic; -use pallet_transaction_payment::InclusionFee; -use pallet_transaction_payment_rpc::Error; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_core::Bytes; use sp_runtime::{ - generic, generic::BlockId, traits::{Block as BlockT, MaybeDisplay, MaybeFromStr}, }; -use xp_rpc::{RpcBalance, RpcU128}; -use xpallet_transaction_fee::FeeDetails; -//pub use xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi as XTransactionFeeRuntimeApi; -pub use pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi as XTransactionFeeRuntimeApi; + +use pallet_transaction_payment_rpc::Error; + +use xp_rpc::RpcBalance; +use xpallet_transaction_fee_rpc_runtime_api::{FeeDetails, InclusionFee}; + +pub use xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi as XTransactionFeeRuntimeApi; + #[rpc] pub trait XTransactionFeeApi { #[rpc(name = "xfee_queryDetails")] @@ -55,7 +53,6 @@ where C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, C::Api: XTransactionFeeRuntimeApi, Balance: Codec + MaybeDisplay + MaybeFromStr, - RpcU128: From + From, { fn query_fee_details( &self, @@ -67,49 +64,20 @@ where let encoded_len = encoded_xt.len() as u32; - let uxt: ::Extrinsic = - Decode::decode(&mut &*encoded_xt).map_err(into_rpc_err)?; + let uxt: Block::Extrinsic = Decode::decode(&mut &*encoded_xt).map_err(into_rpc_err)?; - let result = api - .query_fee_details(&at, uxt, encoded_len) - .map(|fee_details| pallet_transaction_payment::FeeDetails { + api.query_fee_details(&at, uxt, encoded_len) + .map(|fee_details| FeeDetails { inclusion_fee: fee_details.inclusion_fee.map(|fee| InclusionFee { base_fee: fee.base_fee.into(), len_fee: fee.len_fee.into(), adjusted_weight_fee: fee.adjusted_weight_fee.into(), }), tip: fee_details.tip.into(), + extra_fee: fee_details.extra_fee.into(), + final_fee: fee_details.final_fee.into(), }) - .map_err(into_rpc_err); - let base = match result { - Ok(res) => res, - Err(Error) => return Err(Error), - }; - let uxt_clone = uxt.clone(); - if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let base_clone = base.clone(); - let total = match base.inclusion_fee { - Some(fee) => fee - .base_fee - .saturating_add(fee.len_fee) - .saturating_add(fee.adjusted_weight_fee) - .saturating_add(base.tip), - None => 0, - }; - Ok(FeeDetails { - inclusion_fee: base_clone.inclusion_fee, - tip: base.tip, - extra_fee: extra_fee.into(), - final_fee: total + extra_fee, - }) - } else { - Ok(FeeDetails { - inclusion_fee: base.inclusion_fee, - tip: base.tip, - extra_fee: 0u32.into(), - final_fee: base.tip, - }) - } + .map_err(into_rpc_err) } } diff --git a/xpallets/transaction-fee/src/lib.rs b/xpallets/transaction-fee/src/lib.rs index 1382cd150..885053d33 100644 --- a/xpallets/transaction-fee/src/lib.rs +++ b/xpallets/transaction-fee/src/lib.rs @@ -1,26 +1,11 @@ // Copyright 2019-2020 ChainX Project Authors. Licensed under GPL-3.0. //! # Transaction Fee Module -//! -//! This module is a complement to pallet-transaction-payment module, unlike -//! pallet-transaction-payment which merely returns the value of final fee, it -//! exposes all the details of calculated transation fee in a struct `FeeDetails`. -//! -//! The future improvement is to make this feature native to Substrate's transaction-payment -//! module so that we don't have to copy and paste the core logic of fee calculation. #![cfg_attr(not(feature = "std"), no_std)] mod types; -use sp_std::prelude::*; - -use frame_support::weights::{DispatchInfo, GetDispatchInfo}; -use sp_runtime::{ - traits::{Dispatchable, Saturating}, - FixedPointOperand, -}; - pub use self::types::FeeDetails; pub use pallet_transaction_payment::InclusionFee; @@ -43,8 +28,7 @@ pub mod pallet { } #[pallet::event] - #[pallet::metadata(T::AccountId = "AccountId", BalanceOf = "Balance")] // Optional - #[pallet::generate_deposit(pub(super) fn deposit_event)] // Optional + #[pallet::metadata(T::AccountId = "AccountId", BalanceOf = "Balance")] pub enum Event { /// Transaction fee was paid to the block author and its reward pot in 1:9. /// [author, author_fee, reward_pot, reward_pot_fee] From 569056d914e7dfc0004e2031424004bf901c9a6e Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Mon, 21 Jun 2021 15:04:25 +0800 Subject: [PATCH 10/17] Update transaction xpallet --- Cargo.lock | 1 - runtime/chainx/src/lib.rs | 567 +++++++++--------- xpallets/transaction-fee/rpc/Cargo.toml | 1 - .../rpc/runtime-api/src/lib.rs | 4 +- xpallets/transaction-fee/src/types.rs | 37 ++ 5 files changed, 335 insertions(+), 275 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f717f5706..a968159e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10167,7 +10167,6 @@ dependencies = [ "jsonrpc-core", "jsonrpc-core-client", "jsonrpc-derive", - "pallet-transaction-payment", "pallet-transaction-payment-rpc", "parity-scale-codec", "serde", diff --git a/runtime/chainx/src/lib.rs b/runtime/chainx/src/lib.rs index d5cca8156..05f474e6e 100644 --- a/runtime/chainx/src/lib.rs +++ b/runtime/chainx/src/lib.rs @@ -1149,332 +1149,355 @@ pub type Executive = frame_executive::Executive< >; impl_runtime_apis! { - impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } +impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } - fn execute_block(block: Block) { - Executive::execute_block(block) - } + fn execute_block(block: Block) { + Executive::execute_block(block) + } - fn initialize_block(header: &::Header) { - Executive::initialize_block(header) - } + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) } +} - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - Runtime::metadata().into() - } +impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + Runtime::metadata().into() } +} - impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } +impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } - fn finalize_block() -> ::Header { - Executive::finalize_block() - } + fn finalize_block() -> ::Header { + Executive::finalize_block() + } - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) } +} - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx) - } +impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx) } +} - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) - } +impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) } +} - impl sp_consensus_babe::BabeApi for Runtime { - fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { - // The choice of `c` parameter (where `1 - c` represents the - // probability of a slot being empty), is done in accordance to the - // slot duration and expected target block time, for safely - // resisting network delays of maximum two seconds. - // - sp_consensus_babe::BabeGenesisConfiguration { - slot_duration: Babe::slot_duration(), - epoch_length: EpochDuration::get(), - c: PRIMARY_PROBABILITY, - genesis_authorities: Babe::authorities(), - randomness: Babe::randomness(), - allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryVRFSlots, - } +impl sp_consensus_babe::BabeApi for Runtime { + fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { + // The choice of `c` parameter (where `1 - c` represents the + // probability of a slot being empty), is done in accordance to the + // slot duration and expected target block time, for safely + // resisting network delays of maximum two seconds. + // + sp_consensus_babe::BabeGenesisConfiguration { + slot_duration: Babe::slot_duration(), + epoch_length: EpochDuration::get(), + c: PRIMARY_PROBABILITY, + genesis_authorities: Babe::authorities(), + randomness: Babe::randomness(), + allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryVRFSlots, } + } - fn current_epoch_start() -> sp_consensus_babe::Slot { - Babe::current_epoch_start() - } + fn current_epoch_start() -> sp_consensus_babe::Slot { + Babe::current_epoch_start() + } - fn current_epoch() -> sp_consensus_babe::Epoch { - Babe::current_epoch() - } + fn current_epoch() -> sp_consensus_babe::Epoch { + Babe::current_epoch() + } - fn next_epoch() -> sp_consensus_babe::Epoch { - Babe::next_epoch() - } + fn next_epoch() -> sp_consensus_babe::Epoch { + Babe::next_epoch() + } - fn generate_key_ownership_proof( - _slot: sp_consensus_babe::Slot, - authority_id: sp_consensus_babe::AuthorityId, - ) -> Option { - Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id)) - .map(|p| p.encode()) - .map(sp_consensus_babe::OpaqueKeyOwnershipProof::new) - } + fn generate_key_ownership_proof( + _slot: sp_consensus_babe::Slot, + authority_id: sp_consensus_babe::AuthorityId, + ) -> Option { + Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id)) + .map(|p| p.encode()) + .map(sp_consensus_babe::OpaqueKeyOwnershipProof::new) + } - fn submit_report_equivocation_unsigned_extrinsic( - equivocation_proof: sp_consensus_babe::EquivocationProof<::Header>, - key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof, - ) -> Option<()> { - let key_owner_proof = key_owner_proof.decode()?; + fn submit_report_equivocation_unsigned_extrinsic( + equivocation_proof: sp_consensus_babe::EquivocationProof<::Header>, + key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof, + ) -> Option<()> { + let key_owner_proof = key_owner_proof.decode()?; - Babe::submit_unsigned_equivocation_report( - equivocation_proof, - key_owner_proof, - ) - } + Babe::submit_unsigned_equivocation_report( + equivocation_proof, + key_owner_proof, + ) } +} - impl sp_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - SessionKeys::generate(seed) - } +impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + SessionKeys::generate(seed) + } - fn decode_session_keys( - encoded: Vec, - ) -> Option, KeyTypeId)>> { - SessionKeys::decode_into_raw_public_keys(&encoded) - } + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + SessionKeys::decode_into_raw_public_keys(&encoded) } +} - impl fg_primitives::GrandpaApi for Runtime { - fn grandpa_authorities() -> GrandpaAuthorityList { - Grandpa::grandpa_authorities() - } +impl fg_primitives::GrandpaApi for Runtime { + fn grandpa_authorities() -> GrandpaAuthorityList { + Grandpa::grandpa_authorities() + } - fn submit_report_equivocation_unsigned_extrinsic( - equivocation_proof: fg_primitives::EquivocationProof< - ::Hash, - NumberFor, - >, - key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, - ) -> Option<()> { - let key_owner_proof = key_owner_proof.decode()?; - - Grandpa::submit_unsigned_equivocation_report( - equivocation_proof, - key_owner_proof, - ) - } + fn submit_report_equivocation_unsigned_extrinsic( + equivocation_proof: fg_primitives::EquivocationProof< + ::Hash, + NumberFor, + >, + key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, + ) -> Option<()> { + let key_owner_proof = key_owner_proof.decode()?; + + Grandpa::submit_unsigned_equivocation_report( + equivocation_proof, + key_owner_proof, + ) + } - fn generate_key_ownership_proof( - _set_id: fg_primitives::SetId, - authority_id: GrandpaId, - ) -> Option { - Historical::prove((fg_primitives::KEY_TYPE, authority_id)) - .map(|p| p.encode()) - .map(fg_primitives::OpaqueKeyOwnershipProof::new) - } + fn generate_key_ownership_proof( + _set_id: fg_primitives::SetId, + authority_id: GrandpaId, + ) -> Option { + Historical::prove((fg_primitives::KEY_TYPE, authority_id)) + .map(|p| p.encode()) + .map(fg_primitives::OpaqueKeyOwnershipProof::new) } +} - impl sp_authority_discovery::AuthorityDiscoveryApi for Runtime { - fn authorities() -> Vec { - AuthorityDiscovery::authorities() - } +impl sp_authority_discovery::AuthorityDiscoveryApi for Runtime { + fn authorities() -> Vec { + AuthorityDiscovery::authorities() } +} - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { - System::account_nonce(account) - } +impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Index { + System::account_nonce(account) } +} - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { - fn query_info( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let base_info = TransactionPayment::query_info(uxt, len); - pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - partial_fee: base_info.partial_fee + extra_fee, - ..base_info - } - } else { - TransactionPayment::query_info(uxt, len) +impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { + let base_info = TransactionPayment::query_info(uxt, len); + pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + partial_fee: base_info.partial_fee + extra_fee, + ..base_info } - } - fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_fee_details(uxt, len) + } else { + TransactionPayment::query_info(uxt, len) } } + fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } +} - impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> xpallet_transaction_fee::FeeDetails { - if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let base = TransactionPayment::query_fee_details(uxt, len); - let base_clone = base.clone(); - let total = match base.inclusion_fee { - Some(fee) => fee - .base_fee - .saturating_add(fee.len_fee) - .saturating_add(fee.adjusted_weight_fee) - .saturating_add(base.tip), - None => 0,}; - xpallet_transaction_fee::FeeDetails { - inclusion_fee: base_clone.inclusion_fee, - tip: base.tip, - extra_fee: extra_fee.into(), - final_fee: total + extra_fee, - } - } else { - let base = TransactionPayment::query_fee_details(uxt, len); - xpallet_transaction_fee::FeeDetails { - inclusion_fee: base.inclusion_fee, - tip: base.tip, - extra_fee: 0u32.into(), - final_fee: base.tip, - } - } - } +impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> xpallet_transaction_fee::FeeDetails { + let extra_fee = ChargeExtraFee::has_extra_fee(&uxt.function); + let base = TransactionPayment::query_fee_details(uxt, len); + xpallet_transaction_fee::FeeDetails::add_extra_fee_or_not(extra_fee,base) } +} - impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { - fn assets_for_account(who: AccountId) -> BTreeMap> { - XAssets::valid_assets_of(&who) - } +impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { + fn assets_for_account(who: AccountId) -> BTreeMap> { + XAssets::valid_assets_of(&who) + } - fn assets() -> BTreeMap> { - XAssets::total_asset_infos() - } + fn assets() -> BTreeMap> { + XAssets::total_asset_infos() } +} - impl xpallet_mining_staking_rpc_runtime_api::XStakingApi for Runtime { - fn validators() -> Vec> { - XStaking::validators_info() - } - fn validator_info_of(who: AccountId) -> ValidatorInfo { - XStaking::validator_info_of(who) - } - fn staking_dividend_of(who: AccountId) -> BTreeMap { - XStaking::staking_dividend_of(who) - } - fn nomination_details_of(who: AccountId) -> BTreeMap> { - XStaking::nomination_details_of(who) - } - fn nominator_info_of(who: AccountId) -> NominatorInfo { - XStaking::nominator_info_of(who) - } +impl + xpallet_mining_staking_rpc_runtime_api::XStakingApi< + Block, + AccountId, + Balance, + VoteWeight, + BlockNumber, + > for Runtime +{ + fn validators() -> Vec> { + XStaking::validators_info() + } + fn validator_info_of( + who: AccountId, + ) -> ValidatorInfo { + XStaking::validator_info_of(who) + } + fn staking_dividend_of(who: AccountId) -> BTreeMap { + XStaking::staking_dividend_of(who) + } + fn nomination_details_of( + who: AccountId, + ) -> BTreeMap> { + XStaking::nomination_details_of(who) } + fn nominator_info_of(who: AccountId) -> NominatorInfo { + XStaking::nominator_info_of(who) + } +} - impl xpallet_dex_spot_rpc_runtime_api::XSpotApi for Runtime { - fn trading_pairs() -> Vec> { - XSpot::trading_pairs() - } +impl xpallet_dex_spot_rpc_runtime_api::XSpotApi + for Runtime +{ + fn trading_pairs() -> Vec> { + XSpot::trading_pairs() + } - fn orders(who: AccountId, page_index: u32, page_size: u32) -> Vec> { - XSpot::orders(who, page_index, page_size) - } + fn orders( + who: AccountId, + page_index: u32, + page_size: u32, + ) -> Vec> { + XSpot::orders(who, page_index, page_size) + } - fn depth(pair_id: TradingPairId, depth_size: u32) -> Option> { - XSpot::depth(pair_id, depth_size) - } + fn depth(pair_id: TradingPairId, depth_size: u32) -> Option> { + XSpot::depth(pair_id, depth_size) } +} - impl xpallet_mining_asset_rpc_runtime_api::XMiningAssetApi for Runtime { - fn mining_assets() -> Vec> { - XMiningAsset::mining_assets() - } +impl + xpallet_mining_asset_rpc_runtime_api::XMiningAssetApi< + Block, + AccountId, + Balance, + MiningWeight, + BlockNumber, + > for Runtime +{ + fn mining_assets() -> Vec> { + XMiningAsset::mining_assets() + } - fn mining_dividend(who: AccountId) -> BTreeMap> { - XMiningAsset::mining_dividend(who) - } + fn mining_dividend(who: AccountId) -> BTreeMap> { + XMiningAsset::mining_dividend(who) + } - fn miner_ledger(who: AccountId) -> BTreeMap> { - XMiningAsset::miner_ledger(who) - } + fn miner_ledger(who: AccountId) -> BTreeMap> { + XMiningAsset::miner_ledger(who) } +} - impl xpallet_gateway_records_rpc_runtime_api::XGatewayRecordsApi for Runtime { - fn withdrawal_list() -> BTreeMap> { - XGatewayRecords::withdrawal_list() - } +impl + xpallet_gateway_records_rpc_runtime_api::XGatewayRecordsApi< + Block, + AccountId, + Balance, + BlockNumber, + > for Runtime +{ + fn withdrawal_list() -> BTreeMap> { + XGatewayRecords::withdrawal_list() + } - fn withdrawal_list_by_chain(chain: Chain) -> BTreeMap> { - XGatewayRecords::withdrawals_list_by_chain(chain) - } + fn withdrawal_list_by_chain( + chain: Chain, + ) -> BTreeMap> { + XGatewayRecords::withdrawals_list_by_chain(chain) } +} - impl xpallet_gateway_common_rpc_runtime_api::XGatewayCommonApi for Runtime { - fn bound_addrs(who: AccountId) -> BTreeMap> { - XGatewayCommon::bound_addrs(&who) - } +impl xpallet_gateway_common_rpc_runtime_api::XGatewayCommonApi + for Runtime +{ + fn bound_addrs(who: AccountId) -> BTreeMap> { + XGatewayCommon::bound_addrs(&who) + } - fn withdrawal_limit(asset_id: AssetId) -> Result, DispatchError> { - XGatewayCommon::withdrawal_limit(&asset_id) - } + fn withdrawal_limit(asset_id: AssetId) -> Result, DispatchError> { + XGatewayCommon::withdrawal_limit(&asset_id) + } - fn verify_withdrawal(asset_id: AssetId, value: Balance, addr: AddrStr, memo: Memo) -> Result<(), DispatchError> { - XGatewayCommon::verify_withdrawal(asset_id, value, &addr, &memo) - } + fn verify_withdrawal( + asset_id: AssetId, + value: Balance, + addr: AddrStr, + memo: Memo, + ) -> Result<(), DispatchError> { + XGatewayCommon::verify_withdrawal(asset_id, value, &addr, &memo) + } - fn trustee_multisigs() -> BTreeMap { - XGatewayCommon::trustee_multisigs() - } + fn trustee_multisigs() -> BTreeMap { + XGatewayCommon::trustee_multisigs() + } - fn trustee_properties(chain: Chain, who: AccountId) -> Option { - XGatewayCommon::trustee_intention_props_of(who, chain) - } + fn trustee_properties(chain: Chain, who: AccountId) -> Option { + XGatewayCommon::trustee_intention_props_of(who, chain) + } - fn trustee_session_info(chain: Chain) -> Option> { - let number = XGatewayCommon::trustee_session_info_len(chain) - .checked_sub(1) - .unwrap_or_else(u32::max_value); - XGatewayCommon::trustee_session_info_of(chain, number) - } + fn trustee_session_info(chain: Chain) -> Option> { + let number = XGatewayCommon::trustee_session_info_len(chain) + .checked_sub(1) + .unwrap_or_else(u32::max_value); + XGatewayCommon::trustee_session_info_of(chain, number) + } - fn generate_trustee_session_info(chain: Chain, candidates: Vec) -> Result, DispatchError> { - let info = XGatewayCommon::try_generate_session_info(chain, candidates)?; - // check multisig address - let _ = XGatewayCommon::generate_multisig_addr(chain, &info)?; - Ok(info) - } + fn generate_trustee_session_info( + chain: Chain, + candidates: Vec, + ) -> Result, DispatchError> { + let info = XGatewayCommon::try_generate_session_info(chain, candidates)?; + // check multisig address + let _ = XGatewayCommon::generate_multisig_addr(chain, &info)?; + Ok(info) } +} - #[cfg(feature = "runtime-benchmarks")] - impl frame_benchmarking::Benchmark for Runtime { - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig - ) -> Result, RuntimeString> { - use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey}; +#[cfg(feature = "runtime-benchmarks")] +impl frame_benchmarking::Benchmark for Runtime { + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig, + ) -> Result, RuntimeString> { + use frame_benchmarking::{add_benchmark, BenchmarkBatch, Benchmarking, TrackedStorageKey}; - impl frame_system_benchmarking::Config for Runtime {} + impl frame_system_benchmarking::Config for Runtime {} - let whitelist: Vec = vec![ + let whitelist: Vec = vec![ // // Block Number hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), // // Total Issuance @@ -1489,20 +1512,22 @@ impl_runtime_apis! { hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(), ]; - let mut batches = Vec::::new(); - let params = (&config, &whitelist); + let mut batches = Vec::::new(); + let params = (&config, &whitelist); - add_benchmark!(params, batches, xpallet_assets, XAssets); - add_benchmark!(params, batches, xpallet_assets_registrar, XAssetsRegistrar); - add_benchmark!(params, batches, xpallet_mining_asset, XMiningAsset); - add_benchmark!(params, batches, xpallet_mining_staking, XStaking); - add_benchmark!(params, batches, xpallet_gateway_records, XGatewayRecords); - add_benchmark!(params, batches, xpallet_gateway_common, XGatewayCommon); - add_benchmark!(params, batches, xpallet_gateway_bitcoin, XGatewayBitcoin); - add_benchmark!(params, batches, xpallet_dex_spot, XSpot); + add_benchmark!(params, batches, xpallet_assets, XAssets); + add_benchmark!(params, batches, xpallet_assets_registrar, XAssetsRegistrar); + add_benchmark!(params, batches, xpallet_mining_asset, XMiningAsset); + add_benchmark!(params, batches, xpallet_mining_staking, XStaking); + add_benchmark!(params, batches, xpallet_gateway_records, XGatewayRecords); + add_benchmark!(params, batches, xpallet_gateway_common, XGatewayCommon); + add_benchmark!(params, batches, xpallet_gateway_bitcoin, XGatewayBitcoin); + add_benchmark!(params, batches, xpallet_dex_spot, XSpot); - if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } - Ok(batches) + if batches.is_empty() { + return Err("Benchmark not found for this pallet.".into()); + } + Ok(batches) } } } diff --git a/xpallets/transaction-fee/rpc/Cargo.toml b/xpallets/transaction-fee/rpc/Cargo.toml index 93b3f0069..f7e212cca 100644 --- a/xpallets/transaction-fee/rpc/Cargo.toml +++ b/xpallets/transaction-fee/rpc/Cargo.toml @@ -22,7 +22,6 @@ sp-runtime = "3.0.0" # Substrate pallets pallet-transaction-payment-rpc = "3.0.0" -pallet-transaction-payment = { version = "3.0.0", default-features = false } xp-rpc = { path = "../../../primitives/rpc" } diff --git a/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs b/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs index e9415892c..1719b6587 100644 --- a/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs +++ b/xpallets/transaction-fee/rpc/runtime-api/src/lib.rs @@ -1,6 +1,6 @@ -// // Copyright 2019-2020 ChainX Project Authors. Licensed under GPL-3.0. +// Copyright 2019-2020 ChainX Project Authors. Licensed under GPL-3.0. -// //! Runtime API definition for transaction fee module. +//! Runtime API definition for transaction fee module. #![cfg_attr(not(feature = "std"), no_std)] diff --git a/xpallets/transaction-fee/src/types.rs b/xpallets/transaction-fee/src/types.rs index 7703eea69..042e787ce 100644 --- a/xpallets/transaction-fee/src/types.rs +++ b/xpallets/transaction-fee/src/types.rs @@ -5,6 +5,7 @@ use pallet_transaction_payment::InclusionFee; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; +use sp_runtime::traits::AtLeast32BitUnsigned; use sp_runtime::RuntimeDebug; /// The `final_fee` is composed of: @@ -27,3 +28,39 @@ pub struct FeeDetails { pub extra_fee: Balance, pub final_fee: Balance, } + +impl FeeDetails { + pub fn add_extra_fee_or_not( + extra_fee: Option, + base: pallet_transaction_payment::FeeDetails, + ) -> FeeDetails { + match extra_fee { + Some(fee) => { + let total = pallet_transaction_payment::FeeDetails::final_fee(&base); + FeeDetails { + extra_fee: fee, + final_fee: total + fee, + ..base.into() + } + } + None => FeeDetails { + extra_fee: 0u32.into(), + final_fee: base.tip, + ..base.into() + }, + } + } +} + +impl> From> + for FeeDetails +{ + fn from(details: pallet_transaction_payment::FeeDetails) -> FeeDetails { + FeeDetails { + inclusion_fee: details.inclusion_fee, + tip: details.tip, + extra_fee: 0u32.into(), + final_fee: 0u32.into(), + } + } +} From 5105ab46d7fa8568748958e8656d0f05d927c7a7 Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Mon, 21 Jun 2021 15:17:58 +0800 Subject: [PATCH 11/17] update transaction-fee-xpallet --- runtime/dev/src/lib.rs | 27 +++------------------------ runtime/malan/src/lib.rs | 27 +++------------------------ 2 files changed, 6 insertions(+), 48 deletions(-) diff --git a/runtime/dev/src/lib.rs b/runtime/dev/src/lib.rs index 0c06f5dae..6deff8cc2 100644 --- a/runtime/dev/src/lib.rs +++ b/runtime/dev/src/lib.rs @@ -1345,33 +1345,12 @@ impl_runtime_apis! { uxt: ::Extrinsic, len: u32, ) -> xpallet_transaction_fee::FeeDetails { - if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let base = TransactionPayment::query_fee_details(uxt, len); - let base_clone = base.clone(); - let total = match base.inclusion_fee { - Some(fee) => fee - .base_fee - .saturating_add(fee.len_fee) - .saturating_add(fee.adjusted_weight_fee) - .saturating_add(base.tip), - None => 0,}; - xpallet_transaction_fee::FeeDetails { - inclusion_fee: base_clone.inclusion_fee, - tip: base.tip, - extra_fee: extra_fee.into(), - final_fee: total + extra_fee, - } - } else { + let extra_fee = ChargeExtraFee::has_extra_fee(&uxt.function); let base = TransactionPayment::query_fee_details(uxt, len); - xpallet_transaction_fee::FeeDetails { - inclusion_fee: base.inclusion_fee, - tip: base.tip, - extra_fee: 0u32.into(), - final_fee: base.tip, - } - } + xpallet_transaction_fee::FeeDetails::add_extra_fee_or_not(extra_fee,base) } } + impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { fn assets_for_account(who: AccountId) -> BTreeMap> { XAssets::valid_assets_of(&who) diff --git a/runtime/malan/src/lib.rs b/runtime/malan/src/lib.rs index 00d5b6259..835afc0f6 100644 --- a/runtime/malan/src/lib.rs +++ b/runtime/malan/src/lib.rs @@ -1342,33 +1342,12 @@ impl_runtime_apis! { uxt: ::Extrinsic, len: u32, ) -> xpallet_transaction_fee::FeeDetails { - if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let base = TransactionPayment::query_fee_details(uxt, len); - let base_clone = base.clone(); - let total = match base.inclusion_fee { - Some(fee) => fee - .base_fee - .saturating_add(fee.len_fee) - .saturating_add(fee.adjusted_weight_fee) - .saturating_add(base.tip), - None => 0,}; - xpallet_transaction_fee::FeeDetails { - inclusion_fee: base_clone.inclusion_fee, - tip: base.tip, - extra_fee: extra_fee.into(), - final_fee: total + extra_fee, - } - } else { + let extra_fee = ChargeExtraFee::has_extra_fee(&uxt.function); let base = TransactionPayment::query_fee_details(uxt, len); - xpallet_transaction_fee::FeeDetails { - inclusion_fee: base.inclusion_fee, - tip: base.tip, - extra_fee: 0u32.into(), - final_fee: base.tip, - } - } + xpallet_transaction_fee::FeeDetails::add_extra_fee_or_not(extra_fee,base) } } + impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { fn assets_for_account(who: AccountId) -> BTreeMap> { XAssets::valid_assets_of(&who) From 0f2df6b3027a39a9f707c395de8ba9d1ca67fe18 Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Mon, 21 Jun 2021 16:11:40 +0800 Subject: [PATCH 12/17] update transaction fee xpallet --- runtime/chainx/src/lib.rs | 544 +++++++++++++++++--------------------- 1 file changed, 249 insertions(+), 295 deletions(-) diff --git a/runtime/chainx/src/lib.rs b/runtime/chainx/src/lib.rs index 05f474e6e..0e3336d75 100644 --- a/runtime/chainx/src/lib.rs +++ b/runtime/chainx/src/lib.rs @@ -422,8 +422,7 @@ impl frame_support::traits::ValidatorSet for Runtime { } fn validators() -> Vec { - // TODO: return the active validator set in Staking. - Session::validators() + XStaking::active_validator_set().collect() } } @@ -1149,355 +1148,311 @@ pub type Executive = frame_executive::Executive< >; impl_runtime_apis! { -impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } - fn execute_block(block: Block) { - Executive::execute_block(block) - } + fn execute_block(block: Block) { + Executive::execute_block(block) + } - fn initialize_block(header: &::Header) { - Executive::initialize_block(header) + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } } -} -impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - Runtime::metadata().into() + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + Runtime::metadata().into() + } } -} -impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } - fn finalize_block() -> ::Header { - Executive::finalize_block() - } + fn finalize_block() -> ::Header { + Executive::finalize_block() + } - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } } -} -impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx) + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx) + } } -} -impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } } -} -impl sp_consensus_babe::BabeApi for Runtime { - fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { - // The choice of `c` parameter (where `1 - c` represents the - // probability of a slot being empty), is done in accordance to the - // slot duration and expected target block time, for safely - // resisting network delays of maximum two seconds. - // - sp_consensus_babe::BabeGenesisConfiguration { - slot_duration: Babe::slot_duration(), - epoch_length: EpochDuration::get(), - c: PRIMARY_PROBABILITY, - genesis_authorities: Babe::authorities(), - randomness: Babe::randomness(), - allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryVRFSlots, + impl sp_consensus_babe::BabeApi for Runtime { + fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { + // The choice of `c` parameter (where `1 - c` represents the + // probability of a slot being empty), is done in accordance to the + // slot duration and expected target block time, for safely + // resisting network delays of maximum two seconds. + // + sp_consensus_babe::BabeGenesisConfiguration { + slot_duration: Babe::slot_duration(), + epoch_length: EpochDuration::get(), + c: PRIMARY_PROBABILITY, + genesis_authorities: Babe::authorities(), + randomness: Babe::randomness(), + allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryVRFSlots, + } } - } - fn current_epoch_start() -> sp_consensus_babe::Slot { - Babe::current_epoch_start() - } + fn current_epoch_start() -> sp_consensus_babe::Slot { + Babe::current_epoch_start() + } - fn current_epoch() -> sp_consensus_babe::Epoch { - Babe::current_epoch() - } + fn current_epoch() -> sp_consensus_babe::Epoch { + Babe::current_epoch() + } - fn next_epoch() -> sp_consensus_babe::Epoch { - Babe::next_epoch() - } + fn next_epoch() -> sp_consensus_babe::Epoch { + Babe::next_epoch() + } - fn generate_key_ownership_proof( - _slot: sp_consensus_babe::Slot, - authority_id: sp_consensus_babe::AuthorityId, - ) -> Option { - Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id)) - .map(|p| p.encode()) - .map(sp_consensus_babe::OpaqueKeyOwnershipProof::new) - } + fn generate_key_ownership_proof( + _slot: sp_consensus_babe::Slot, + authority_id: sp_consensus_babe::AuthorityId, + ) -> Option { + Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id)) + .map(|p| p.encode()) + .map(sp_consensus_babe::OpaqueKeyOwnershipProof::new) + } - fn submit_report_equivocation_unsigned_extrinsic( - equivocation_proof: sp_consensus_babe::EquivocationProof<::Header>, - key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof, - ) -> Option<()> { - let key_owner_proof = key_owner_proof.decode()?; + fn submit_report_equivocation_unsigned_extrinsic( + equivocation_proof: sp_consensus_babe::EquivocationProof<::Header>, + key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof, + ) -> Option<()> { + let key_owner_proof = key_owner_proof.decode()?; - Babe::submit_unsigned_equivocation_report( - equivocation_proof, - key_owner_proof, - ) + Babe::submit_unsigned_equivocation_report( + equivocation_proof, + key_owner_proof, + ) + } } -} -impl sp_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - SessionKeys::generate(seed) - } + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + SessionKeys::generate(seed) + } - fn decode_session_keys( - encoded: Vec, - ) -> Option, KeyTypeId)>> { - SessionKeys::decode_into_raw_public_keys(&encoded) + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + SessionKeys::decode_into_raw_public_keys(&encoded) + } } -} -impl fg_primitives::GrandpaApi for Runtime { - fn grandpa_authorities() -> GrandpaAuthorityList { - Grandpa::grandpa_authorities() - } + impl fg_primitives::GrandpaApi for Runtime { + fn grandpa_authorities() -> GrandpaAuthorityList { + Grandpa::grandpa_authorities() + } - fn submit_report_equivocation_unsigned_extrinsic( - equivocation_proof: fg_primitives::EquivocationProof< - ::Hash, - NumberFor, - >, - key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, - ) -> Option<()> { - let key_owner_proof = key_owner_proof.decode()?; - - Grandpa::submit_unsigned_equivocation_report( - equivocation_proof, - key_owner_proof, - ) - } + fn submit_report_equivocation_unsigned_extrinsic( + equivocation_proof: fg_primitives::EquivocationProof< + ::Hash, + NumberFor, + >, + key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, + ) -> Option<()> { + let key_owner_proof = key_owner_proof.decode()?; + + Grandpa::submit_unsigned_equivocation_report( + equivocation_proof, + key_owner_proof, + ) + } - fn generate_key_ownership_proof( - _set_id: fg_primitives::SetId, - authority_id: GrandpaId, - ) -> Option { - Historical::prove((fg_primitives::KEY_TYPE, authority_id)) - .map(|p| p.encode()) - .map(fg_primitives::OpaqueKeyOwnershipProof::new) + fn generate_key_ownership_proof( + _set_id: fg_primitives::SetId, + authority_id: GrandpaId, + ) -> Option { + Historical::prove((fg_primitives::KEY_TYPE, authority_id)) + .map(|p| p.encode()) + .map(fg_primitives::OpaqueKeyOwnershipProof::new) + } } -} -impl sp_authority_discovery::AuthorityDiscoveryApi for Runtime { - fn authorities() -> Vec { - AuthorityDiscovery::authorities() + impl sp_authority_discovery::AuthorityDiscoveryApi for Runtime { + fn authorities() -> Vec { + AuthorityDiscovery::authorities() + } } -} -impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { - System::account_nonce(account) + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Index { + System::account_nonce(account) + } } -} -impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { - fn query_info( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { - let base_info = TransactionPayment::query_info(uxt, len); - pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - partial_fee: base_info.partial_fee + extra_fee, - ..base_info + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + if let Some(extra_fee) = ChargeExtraFee::has_extra_fee(&uxt.function) { + let base_info = TransactionPayment::query_info(uxt, len); + pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + partial_fee: base_info.partial_fee + extra_fee, + ..base_info + } + } else { + TransactionPayment::query_info(uxt, len) } - } else { - TransactionPayment::query_info(uxt, len) + } + fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) } } - fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_fee_details(uxt, len) - } -} -impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> xpallet_transaction_fee::FeeDetails { + impl xpallet_transaction_fee_rpc_runtime_api::XTransactionFeeApi for Runtime { + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> xpallet_transaction_fee::FeeDetails { let extra_fee = ChargeExtraFee::has_extra_fee(&uxt.function); let base = TransactionPayment::query_fee_details(uxt, len); xpallet_transaction_fee::FeeDetails::add_extra_fee_or_not(extra_fee,base) - } -} -impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { - fn assets_for_account(who: AccountId) -> BTreeMap> { - XAssets::valid_assets_of(&who) + } } - fn assets() -> BTreeMap> { - XAssets::total_asset_infos() - } -} + impl xpallet_assets_rpc_runtime_api::XAssetsApi for Runtime { + fn assets_for_account(who: AccountId) -> BTreeMap> { + XAssets::valid_assets_of(&who) + } -impl - xpallet_mining_staking_rpc_runtime_api::XStakingApi< - Block, - AccountId, - Balance, - VoteWeight, - BlockNumber, - > for Runtime -{ - fn validators() -> Vec> { - XStaking::validators_info() - } - fn validator_info_of( - who: AccountId, - ) -> ValidatorInfo { - XStaking::validator_info_of(who) - } - fn staking_dividend_of(who: AccountId) -> BTreeMap { - XStaking::staking_dividend_of(who) - } - fn nomination_details_of( - who: AccountId, - ) -> BTreeMap> { - XStaking::nomination_details_of(who) - } - fn nominator_info_of(who: AccountId) -> NominatorInfo { - XStaking::nominator_info_of(who) + fn assets() -> BTreeMap> { + XAssets::total_asset_infos() + } } -} -impl xpallet_dex_spot_rpc_runtime_api::XSpotApi - for Runtime -{ - fn trading_pairs() -> Vec> { - XSpot::trading_pairs() + impl xpallet_mining_staking_rpc_runtime_api::XStakingApi for Runtime { + fn validators() -> Vec> { + XStaking::validators_info() + } + fn validator_info_of(who: AccountId) -> ValidatorInfo { + XStaking::validator_info_of(who) + } + fn staking_dividend_of(who: AccountId) -> BTreeMap { + XStaking::staking_dividend_of(who) + } + fn nomination_details_of(who: AccountId) -> BTreeMap> { + XStaking::nomination_details_of(who) + } + fn nominator_info_of(who: AccountId) -> NominatorInfo { + XStaking::nominator_info_of(who) + } } - fn orders( - who: AccountId, - page_index: u32, - page_size: u32, - ) -> Vec> { - XSpot::orders(who, page_index, page_size) - } + impl xpallet_dex_spot_rpc_runtime_api::XSpotApi for Runtime { + fn trading_pairs() -> Vec> { + XSpot::trading_pairs() + } - fn depth(pair_id: TradingPairId, depth_size: u32) -> Option> { - XSpot::depth(pair_id, depth_size) - } -} + fn orders(who: AccountId, page_index: u32, page_size: u32) -> Vec> { + XSpot::orders(who, page_index, page_size) + } -impl - xpallet_mining_asset_rpc_runtime_api::XMiningAssetApi< - Block, - AccountId, - Balance, - MiningWeight, - BlockNumber, - > for Runtime -{ - fn mining_assets() -> Vec> { - XMiningAsset::mining_assets() + fn depth(pair_id: TradingPairId, depth_size: u32) -> Option> { + XSpot::depth(pair_id, depth_size) + } } - fn mining_dividend(who: AccountId) -> BTreeMap> { - XMiningAsset::mining_dividend(who) - } + impl xpallet_mining_asset_rpc_runtime_api::XMiningAssetApi for Runtime { + fn mining_assets() -> Vec> { + XMiningAsset::mining_assets() + } - fn miner_ledger(who: AccountId) -> BTreeMap> { - XMiningAsset::miner_ledger(who) - } -} + fn mining_dividend(who: AccountId) -> BTreeMap> { + XMiningAsset::mining_dividend(who) + } -impl - xpallet_gateway_records_rpc_runtime_api::XGatewayRecordsApi< - Block, - AccountId, - Balance, - BlockNumber, - > for Runtime -{ - fn withdrawal_list() -> BTreeMap> { - XGatewayRecords::withdrawal_list() + fn miner_ledger(who: AccountId) -> BTreeMap> { + XMiningAsset::miner_ledger(who) + } } - fn withdrawal_list_by_chain( - chain: Chain, - ) -> BTreeMap> { - XGatewayRecords::withdrawals_list_by_chain(chain) - } -} + impl xpallet_gateway_records_rpc_runtime_api::XGatewayRecordsApi for Runtime { + fn withdrawal_list() -> BTreeMap> { + XGatewayRecords::withdrawal_list() + } -impl xpallet_gateway_common_rpc_runtime_api::XGatewayCommonApi - for Runtime -{ - fn bound_addrs(who: AccountId) -> BTreeMap> { - XGatewayCommon::bound_addrs(&who) + fn withdrawal_list_by_chain(chain: Chain) -> BTreeMap> { + XGatewayRecords::withdrawals_list_by_chain(chain) + } } - fn withdrawal_limit(asset_id: AssetId) -> Result, DispatchError> { - XGatewayCommon::withdrawal_limit(&asset_id) - } + impl xpallet_gateway_common_rpc_runtime_api::XGatewayCommonApi for Runtime { + fn bound_addrs(who: AccountId) -> BTreeMap> { + XGatewayCommon::bound_addrs(&who) + } - fn verify_withdrawal( - asset_id: AssetId, - value: Balance, - addr: AddrStr, - memo: Memo, - ) -> Result<(), DispatchError> { - XGatewayCommon::verify_withdrawal(asset_id, value, &addr, &memo) - } + fn withdrawal_limit(asset_id: AssetId) -> Result, DispatchError> { + XGatewayCommon::withdrawal_limit(&asset_id) + } - fn trustee_multisigs() -> BTreeMap { - XGatewayCommon::trustee_multisigs() - } + fn verify_withdrawal(asset_id: AssetId, value: Balance, addr: AddrStr, memo: Memo) -> Result<(), DispatchError> { + XGatewayCommon::verify_withdrawal(asset_id, value, &addr, &memo) + } - fn trustee_properties(chain: Chain, who: AccountId) -> Option { - XGatewayCommon::trustee_intention_props_of(who, chain) - } + fn trustee_multisigs() -> BTreeMap { + XGatewayCommon::trustee_multisigs() + } - fn trustee_session_info(chain: Chain) -> Option> { - let number = XGatewayCommon::trustee_session_info_len(chain) - .checked_sub(1) - .unwrap_or_else(u32::max_value); - XGatewayCommon::trustee_session_info_of(chain, number) - } + fn trustee_properties(chain: Chain, who: AccountId) -> Option { + XGatewayCommon::trustee_intention_props_of(who, chain) + } - fn generate_trustee_session_info( - chain: Chain, - candidates: Vec, - ) -> Result, DispatchError> { - let info = XGatewayCommon::try_generate_session_info(chain, candidates)?; - // check multisig address - let _ = XGatewayCommon::generate_multisig_addr(chain, &info)?; - Ok(info) + fn trustee_session_info(chain: Chain) -> Option> { + let number = XGatewayCommon::trustee_session_info_len(chain) + .checked_sub(1) + .unwrap_or_else(u32::max_value); + XGatewayCommon::trustee_session_info_of(chain, number) + } + + fn generate_trustee_session_info(chain: Chain, candidates: Vec) -> Result, DispatchError> { + let info = XGatewayCommon::try_generate_session_info(chain, candidates)?; + // check multisig address + let _ = XGatewayCommon::generate_multisig_addr(chain, &info)?; + Ok(info) + } } -} -#[cfg(feature = "runtime-benchmarks")] -impl frame_benchmarking::Benchmark for Runtime { - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig, - ) -> Result, RuntimeString> { - use frame_benchmarking::{add_benchmark, BenchmarkBatch, Benchmarking, TrackedStorageKey}; + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey}; - impl frame_system_benchmarking::Config for Runtime {} + impl frame_system_benchmarking::Config for Runtime {} - let whitelist: Vec = vec![ + let whitelist: Vec = vec![ // // Block Number hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), // // Total Issuance @@ -1512,22 +1467,21 @@ impl frame_benchmarking::Benchmark for Runtime { hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(), ]; - let mut batches = Vec::::new(); - let params = (&config, &whitelist); + let mut batches = Vec::::new(); + let params = (&config, &whitelist); - add_benchmark!(params, batches, xpallet_assets, XAssets); - add_benchmark!(params, batches, xpallet_assets_registrar, XAssetsRegistrar); - add_benchmark!(params, batches, xpallet_mining_asset, XMiningAsset); - add_benchmark!(params, batches, xpallet_mining_staking, XStaking); - add_benchmark!(params, batches, xpallet_gateway_records, XGatewayRecords); - add_benchmark!(params, batches, xpallet_gateway_common, XGatewayCommon); - add_benchmark!(params, batches, xpallet_gateway_bitcoin, XGatewayBitcoin); - add_benchmark!(params, batches, xpallet_dex_spot, XSpot); + add_benchmark!(params, batches, xpallet_assets, XAssets); + add_benchmark!(params, batches, xpallet_assets_registrar, XAssetsRegistrar); + add_benchmark!(params, batches, xpallet_mining_asset, XMiningAsset); + add_benchmark!(params, batches, xpallet_mining_staking, XStaking); + add_benchmark!(params, batches, xpallet_gateway_records, XGatewayRecords); + add_benchmark!(params, batches, xpallet_gateway_common, XGatewayCommon); + add_benchmark!(params, batches, xpallet_gateway_bitcoin, XGatewayBitcoin); + add_benchmark!(params, batches, xpallet_dex_spot, XSpot); - if batches.is_empty() { - return Err("Benchmark not found for this pallet.".into()); - } - Ok(batches) + if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } + Ok(batches) } } + } From 2ac1f2b02bafb40fe973c2f20306fa3a60b90d6f Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Mon, 21 Jun 2021 16:33:13 +0800 Subject: [PATCH 13/17] Some format change --- runtime/chainx/src/lib.rs | 3 ++- xpallets/transaction-fee/rpc/Cargo.toml | 4 +--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/runtime/chainx/src/lib.rs b/runtime/chainx/src/lib.rs index 0e3336d75..49dc0b542 100644 --- a/runtime/chainx/src/lib.rs +++ b/runtime/chainx/src/lib.rs @@ -422,7 +422,8 @@ impl frame_support::traits::ValidatorSet for Runtime { } fn validators() -> Vec { - XStaking::active_validator_set().collect() + // TODO: return the active validator set in Staking. + Session::validators() } } diff --git a/xpallets/transaction-fee/rpc/Cargo.toml b/xpallets/transaction-fee/rpc/Cargo.toml index f7e212cca..dfe2f06f5 100644 --- a/xpallets/transaction-fee/rpc/Cargo.toml +++ b/xpallets/transaction-fee/rpc/Cargo.toml @@ -26,6 +26,4 @@ pallet-transaction-payment-rpc = "3.0.0" xp-rpc = { path = "../../../primitives/rpc" } # ChainX pallets api -xpallet-transaction-fee-rpc-runtime-api = { path = "./runtime-api" } - - +xpallet-transaction-fee-rpc-runtime-api = { path = "./runtime-api" } \ No newline at end of file From 1c358641d26209357b5b7d68e4944631ee8b6ca8 Mon Sep 17 00:00:00 2001 From: rain-9811 <545132695@qq.com> Date: Mon, 21 Jun 2021 16:37:42 +0800 Subject: [PATCH 14/17] Do some format change --- runtime/chainx/src/lib.rs | 2 +- xpallets/transaction-fee/rpc/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/chainx/src/lib.rs b/runtime/chainx/src/lib.rs index 49dc0b542..af1190393 100644 --- a/runtime/chainx/src/lib.rs +++ b/runtime/chainx/src/lib.rs @@ -422,7 +422,7 @@ impl frame_support::traits::ValidatorSet for Runtime { } fn validators() -> Vec { - // TODO: return the active validator set in Staking. + // TODO: return the active validator set in Staking. Session::validators() } } diff --git a/xpallets/transaction-fee/rpc/Cargo.toml b/xpallets/transaction-fee/rpc/Cargo.toml index dfe2f06f5..7a23cf50b 100644 --- a/xpallets/transaction-fee/rpc/Cargo.toml +++ b/xpallets/transaction-fee/rpc/Cargo.toml @@ -26,4 +26,4 @@ pallet-transaction-payment-rpc = "3.0.0" xp-rpc = { path = "../../../primitives/rpc" } # ChainX pallets api -xpallet-transaction-fee-rpc-runtime-api = { path = "./runtime-api" } \ No newline at end of file +xpallet-transaction-fee-rpc-runtime-api = { path = "./runtime-api" } From c277551a93b744fc272e987085ade59f70831b7a Mon Sep 17 00:00:00 2001 From: Liu-Cheng Xu Date: Tue, 22 Jun 2021 09:56:17 +0800 Subject: [PATCH 15/17] Fix the From impl for xpallet_transaction_fee::FeeDetails --- runtime/chainx/src/lib.rs | 5 ++--- runtime/dev/src/lib.rs | 4 ++-- runtime/malan/src/lib.rs | 4 ++-- xpallets/transaction-fee/src/types.rs | 32 +++++++++++---------------- 4 files changed, 19 insertions(+), 26 deletions(-) diff --git a/runtime/chainx/src/lib.rs b/runtime/chainx/src/lib.rs index 29c526215..12ae29380 100644 --- a/runtime/chainx/src/lib.rs +++ b/runtime/chainx/src/lib.rs @@ -1334,10 +1334,9 @@ impl_runtime_apis! { uxt: ::Extrinsic, len: u32, ) -> xpallet_transaction_fee::FeeDetails { - let extra_fee = ChargeExtraFee::has_extra_fee(&uxt.function); + let maybe_extra = ChargeExtraFee::has_extra_fee(&uxt.function); let base = TransactionPayment::query_fee_details(uxt, len); - xpallet_transaction_fee::FeeDetails::add_extra_fee_or_not(extra_fee,base) - + xpallet_transaction_fee::FeeDetails::new(base, maybe_extra) } } diff --git a/runtime/dev/src/lib.rs b/runtime/dev/src/lib.rs index 79d0fe2b2..b581160db 100644 --- a/runtime/dev/src/lib.rs +++ b/runtime/dev/src/lib.rs @@ -1344,9 +1344,9 @@ impl_runtime_apis! { uxt: ::Extrinsic, len: u32, ) -> xpallet_transaction_fee::FeeDetails { - let extra_fee = ChargeExtraFee::has_extra_fee(&uxt.function); + let maybe_extra = ChargeExtraFee::has_extra_fee(&uxt.function); let base = TransactionPayment::query_fee_details(uxt, len); - xpallet_transaction_fee::FeeDetails::add_extra_fee_or_not(extra_fee,base) + xpallet_transaction_fee::FeeDetails::new(base, maybe_extra) } } diff --git a/runtime/malan/src/lib.rs b/runtime/malan/src/lib.rs index 79027ac80..73211a1a4 100644 --- a/runtime/malan/src/lib.rs +++ b/runtime/malan/src/lib.rs @@ -1341,9 +1341,9 @@ impl_runtime_apis! { uxt: ::Extrinsic, len: u32, ) -> xpallet_transaction_fee::FeeDetails { - let extra_fee = ChargeExtraFee::has_extra_fee(&uxt.function); + let maybe_extra = ChargeExtraFee::has_extra_fee(&uxt.function); let base = TransactionPayment::query_fee_details(uxt, len); - xpallet_transaction_fee::FeeDetails::add_extra_fee_or_not(extra_fee,base) + xpallet_transaction_fee::FeeDetails::new(base, maybe_extra) } } diff --git a/xpallets/transaction-fee/src/types.rs b/xpallets/transaction-fee/src/types.rs index 042e787ce..412a23af2 100644 --- a/xpallets/transaction-fee/src/types.rs +++ b/xpallets/transaction-fee/src/types.rs @@ -30,37 +30,31 @@ pub struct FeeDetails { } impl FeeDetails { - pub fn add_extra_fee_or_not( - extra_fee: Option, + pub fn new( base: pallet_transaction_payment::FeeDetails, - ) -> FeeDetails { - match extra_fee { - Some(fee) => { - let total = pallet_transaction_payment::FeeDetails::final_fee(&base); - FeeDetails { - extra_fee: fee, - final_fee: total + fee, - ..base.into() - } - } - None => FeeDetails { - extra_fee: 0u32.into(), - final_fee: base.tip, + maybe_extra_fee: Option, + ) -> Self { + match maybe_extra_fee { + Some(extra_fee) => Self { + extra_fee, + final_fee: base.final_fee() + extra_fee, ..base.into() }, + None => base.into(), } } } -impl> From> +impl From> for FeeDetails { - fn from(details: pallet_transaction_payment::FeeDetails) -> FeeDetails { - FeeDetails { + fn from(details: pallet_transaction_payment::FeeDetails) -> Self { + let final_fee = details.final_fee(); + Self { inclusion_fee: details.inclusion_fee, tip: details.tip, extra_fee: 0u32.into(), - final_fee: 0u32.into(), + final_fee, } } } From b9237b07d765b0ab645c903c684228bd46b9d466 Mon Sep 17 00:00:00 2001 From: Liu-Cheng Xu Date: Tue, 22 Jun 2021 10:09:43 +0800 Subject: [PATCH 16/17] Nits --- xpallets/transaction-fee/src/types.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/xpallets/transaction-fee/src/types.rs b/xpallets/transaction-fee/src/types.rs index 412a23af2..25c64d4b2 100644 --- a/xpallets/transaction-fee/src/types.rs +++ b/xpallets/transaction-fee/src/types.rs @@ -1,12 +1,12 @@ // Copyright 2019-2020 ChainX Project Authors. Licensed under GPL-3.0. use codec::{Decode, Encode}; -use pallet_transaction_payment::InclusionFee; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; -use sp_runtime::traits::AtLeast32BitUnsigned; -use sp_runtime::RuntimeDebug; +use sp_runtime::{traits::AtLeast32BitUnsigned, RuntimeDebug}; + +use pallet_transaction_payment::InclusionFee; /// The `final_fee` is composed of: /// - (Optional) `inclusion_fee`: Only the `Pays::Yes` transaction can have the inclusion fee. @@ -25,6 +25,7 @@ pub struct FeeDetails { // Do not serialize and deserialize `tip` as we actually can not pass any tip to the RPC. #[cfg_attr(feature = "std", serde(skip))] pub tip: Balance, + /// Additional fee for some ChainX specific calls. pub extra_fee: Balance, pub final_fee: Balance, } From 3dff2419b216a234aac40b3e657eda556135e71f Mon Sep 17 00:00:00 2001 From: Liu-Cheng Xu Date: Tue, 22 Jun 2021 13:30:12 +0800 Subject: [PATCH 17/17] Fix indent --- runtime/dev/src/lib.rs | 6 +++--- runtime/malan/src/lib.rs | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/runtime/dev/src/lib.rs b/runtime/dev/src/lib.rs index b581160db..e2fc4b6a3 100644 --- a/runtime/dev/src/lib.rs +++ b/runtime/dev/src/lib.rs @@ -1344,9 +1344,9 @@ impl_runtime_apis! { uxt: ::Extrinsic, len: u32, ) -> xpallet_transaction_fee::FeeDetails { - let maybe_extra = ChargeExtraFee::has_extra_fee(&uxt.function); - let base = TransactionPayment::query_fee_details(uxt, len); - xpallet_transaction_fee::FeeDetails::new(base, maybe_extra) + let maybe_extra = ChargeExtraFee::has_extra_fee(&uxt.function); + let base = TransactionPayment::query_fee_details(uxt, len); + xpallet_transaction_fee::FeeDetails::new(base, maybe_extra) } } diff --git a/runtime/malan/src/lib.rs b/runtime/malan/src/lib.rs index 73211a1a4..28e9049b0 100644 --- a/runtime/malan/src/lib.rs +++ b/runtime/malan/src/lib.rs @@ -1341,9 +1341,9 @@ impl_runtime_apis! { uxt: ::Extrinsic, len: u32, ) -> xpallet_transaction_fee::FeeDetails { - let maybe_extra = ChargeExtraFee::has_extra_fee(&uxt.function); - let base = TransactionPayment::query_fee_details(uxt, len); - xpallet_transaction_fee::FeeDetails::new(base, maybe_extra) + let maybe_extra = ChargeExtraFee::has_extra_fee(&uxt.function); + let base = TransactionPayment::query_fee_details(uxt, len); + xpallet_transaction_fee::FeeDetails::new(base, maybe_extra) } }