feat: Rebrand Polkadot/Substrate references to PezkuwiChain
This commit systematically rebrands various references from Parity Technologies' Polkadot/Substrate ecosystem to PezkuwiChain within the kurdistan-sdk. Key changes include: - Updated external repository URLs (zombienet-sdk, parity-db, parity-scale-codec, wasm-instrument) to point to pezkuwichain forks. - Modified internal documentation and code comments to reflect PezkuwiChain naming and structure. - Replaced direct references to with or specific paths within the for XCM, Pezkuwi, and other modules. - Cleaned up deprecated issue and PR references in various and files, particularly in and modules. - Adjusted image and logo URLs in documentation to point to PezkuwiChain assets. - Removed or rephrased comments related to external Polkadot/Substrate PRs and issues. This is a significant step towards fully customizing the SDK for the PezkuwiChain ecosystem.
This commit is contained in:
+125
@@ -0,0 +1,125 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Benchmarks for Asset Conversion Tx Payment Pallet's transaction extension
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
use super::*;
|
||||
use crate::Pallet;
|
||||
use pezframe_benchmarking::v2::*;
|
||||
use pezframe_support::{
|
||||
dispatch::{DispatchInfo, PostDispatchInfo},
|
||||
pezpallet_prelude::*,
|
||||
};
|
||||
use pezframe_system::RawOrigin;
|
||||
use pezsp_runtime::traits::{
|
||||
AsSystemOriginSigner, AsTransactionAuthorizedOrigin, DispatchTransaction, Dispatchable,
|
||||
};
|
||||
|
||||
#[benchmarks(where
|
||||
T::RuntimeOrigin: AsTransactionAuthorizedOrigin,
|
||||
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
|
||||
BalanceOf<T>: Send + Sync + From<u64>,
|
||||
T::AssetId: Send + Sync,
|
||||
<T::RuntimeCall as Dispatchable>::RuntimeOrigin: AsSystemOriginSigner<T::AccountId> + Clone,
|
||||
)]
|
||||
mod benchmarks {
|
||||
use super::*;
|
||||
|
||||
#[benchmark]
|
||||
fn charge_asset_tx_payment_zero() {
|
||||
let caller: T::AccountId = account("caller", 0, 0);
|
||||
let ext: ChargeAssetTxPayment<T> = ChargeAssetTxPayment::from(0u64.into(), None);
|
||||
let inner = pezframe_system::Call::remark { remark: alloc::vec![] };
|
||||
let call = T::RuntimeCall::from(inner);
|
||||
let info = DispatchInfo {
|
||||
call_weight: Weight::zero(),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Normal,
|
||||
pays_fee: Pays::No,
|
||||
};
|
||||
let post_info = PostDispatchInfo { actual_weight: None, pays_fee: Pays::No };
|
||||
#[block]
|
||||
{
|
||||
assert!(ext
|
||||
.test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, 0, |_| Ok(post_info))
|
||||
.unwrap()
|
||||
.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[benchmark]
|
||||
fn charge_asset_tx_payment_native() {
|
||||
let caller: T::AccountId = account("caller", 0, 0);
|
||||
let (fun_asset_id, _) = <T as Config>::BenchmarkHelper::create_asset_id_parameter(1);
|
||||
<T as Config>::BenchmarkHelper::setup_balances_and_pool(fun_asset_id, caller.clone());
|
||||
let ext: ChargeAssetTxPayment<T> = ChargeAssetTxPayment::from(10u64.into(), None);
|
||||
let inner = pezframe_system::Call::remark { remark: alloc::vec![] };
|
||||
let call = T::RuntimeCall::from(inner);
|
||||
let info = DispatchInfo {
|
||||
call_weight: Weight::from_parts(10, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
// Submit a lower post info weight to trigger the refund path.
|
||||
let post_info =
|
||||
PostDispatchInfo { actual_weight: Some(Weight::from_parts(5, 0)), pays_fee: Pays::Yes };
|
||||
|
||||
#[block]
|
||||
{
|
||||
assert!(ext
|
||||
.test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, 0, |_| Ok(post_info))
|
||||
.unwrap()
|
||||
.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[benchmark]
|
||||
fn charge_asset_tx_payment_asset() {
|
||||
let caller: T::AccountId = account("caller", 0, 0);
|
||||
let (fun_asset_id, asset_id) = <T as Config>::BenchmarkHelper::create_asset_id_parameter(1);
|
||||
<T as Config>::BenchmarkHelper::setup_balances_and_pool(fun_asset_id, caller.clone());
|
||||
|
||||
let tip = 10u64.into();
|
||||
let ext: ChargeAssetTxPayment<T> = ChargeAssetTxPayment::from(tip, Some(asset_id));
|
||||
let inner = pezframe_system::Call::remark { remark: alloc::vec![] };
|
||||
let call = T::RuntimeCall::from(inner);
|
||||
let info = DispatchInfo {
|
||||
call_weight: Weight::from_parts(10, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
// Submit a lower post info weight to trigger the refund path.
|
||||
let post_info =
|
||||
PostDispatchInfo { actual_weight: Some(Weight::from_parts(5, 0)), pays_fee: Pays::Yes };
|
||||
|
||||
#[block]
|
||||
{
|
||||
assert!(ext
|
||||
.test_run(RawOrigin::Signed(caller.clone()).into(), &call, &info, 0, 0, |_| Ok(
|
||||
post_info
|
||||
))
|
||||
.unwrap()
|
||||
.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Runtime);
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! # Asset Conversion Transaction Payment Pallet
|
||||
//!
|
||||
//! This pallet allows runtimes that include it to pay for transactions in assets other than the
|
||||
//! chain's native asset.
|
||||
//!
|
||||
//! ## Overview
|
||||
//!
|
||||
//! This pallet provides a `TransactionExtension` with an optional `AssetId` that specifies the
|
||||
//! asset to be used for payment (defaulting to the native token on `None`). It expects an
|
||||
//! [`OnChargeAssetTransaction`] implementation analogous to [`pezpallet-transaction-payment`]. The
|
||||
//! included [`SwapAssetAdapter`] (implementing [`OnChargeAssetTransaction`]) determines the
|
||||
//! fee amount by converting the fee calculated by [`pezpallet-transaction-payment`] in the native
|
||||
//! asset into the amount required of the specified asset.
|
||||
//!
|
||||
//! ## Pallet API
|
||||
//!
|
||||
//! This pallet does not have any dispatchable calls or storage. It wraps FRAME's Transaction
|
||||
//! Payment pallet and functions as a replacement. This means you should include both pallets in
|
||||
//! your `construct_runtime` macro, but only include this pallet's [`TransactionExtension`]
|
||||
//! ([`ChargeAssetTxPayment`]).
|
||||
//!
|
||||
//! ## Terminology
|
||||
//!
|
||||
//! - Native Asset or Native Currency: The asset that a chain considers native, as in its default
|
||||
//! for transaction fee payment, deposits, inflation, etc.
|
||||
//! - Other assets: Other assets that may exist on chain, for example under the Assets pallet.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
use codec::{Decode, DecodeWithMemTracking, Encode};
|
||||
use pezframe_support::{
|
||||
dispatch::{DispatchInfo, DispatchResult, PostDispatchInfo},
|
||||
pezpallet_prelude::TransactionSource,
|
||||
traits::IsType,
|
||||
DefaultNoBound,
|
||||
};
|
||||
use pezpallet_transaction_payment::{ChargeTransactionPayment, OnChargeTransaction};
|
||||
use scale_info::TypeInfo;
|
||||
use pezsp_runtime::{
|
||||
traits::{
|
||||
AsSystemOriginSigner, DispatchInfoOf, Dispatchable, PostDispatchInfoOf, RefundWeight,
|
||||
TransactionExtension, ValidateResult, Zero,
|
||||
},
|
||||
transaction_validity::{InvalidTransaction, TransactionValidityError, ValidTransaction},
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod mock;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
pub mod weights;
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
mod benchmarking;
|
||||
|
||||
mod payment;
|
||||
use pezframe_support::{pezpallet_prelude::Weight, traits::tokens::AssetId};
|
||||
pub use payment::*;
|
||||
pub use weights::WeightInfo;
|
||||
|
||||
/// Balance type alias for balances of the chain's native asset.
|
||||
pub(crate) type BalanceOf<T> = <OnChargeTransactionOf<T> as OnChargeTransaction<T>>::Balance;
|
||||
|
||||
/// Type aliases used for interaction with `OnChargeTransaction`.
|
||||
pub(crate) type OnChargeTransactionOf<T> =
|
||||
<T as pezpallet_transaction_payment::Config>::OnChargeTransaction;
|
||||
|
||||
/// Liquidity info type alias for the chain's native asset.
|
||||
pub(crate) type NativeLiquidityInfoOf<T> =
|
||||
<OnChargeTransactionOf<T> as OnChargeTransaction<T>>::LiquidityInfo;
|
||||
|
||||
/// Liquidity info type alias for the chain's assets.
|
||||
pub(crate) type AssetLiquidityInfoOf<T> =
|
||||
<<T as Config>::OnChargeAssetTransaction as OnChargeAssetTransaction<T>>::LiquidityInfo;
|
||||
|
||||
/// Used to pass the initial payment info from pre- to post-dispatch.
|
||||
#[derive(Encode, Decode, DefaultNoBound, TypeInfo)]
|
||||
pub enum InitialPayment<T: Config> {
|
||||
/// No initial fee was paid.
|
||||
#[default]
|
||||
Nothing,
|
||||
/// The initial fee was paid in the native currency.
|
||||
Native(NativeLiquidityInfoOf<T>),
|
||||
/// The initial fee was paid in an asset.
|
||||
Asset((T::AssetId, AssetLiquidityInfoOf<T>)),
|
||||
}
|
||||
|
||||
pub use pallet::*;
|
||||
|
||||
#[pezframe_support::pallet]
|
||||
pub mod pallet {
|
||||
use super::*;
|
||||
|
||||
#[pallet::config]
|
||||
pub trait Config: pezframe_system::Config + pezpallet_transaction_payment::Config {
|
||||
/// The overarching event type.
|
||||
#[allow(deprecated)]
|
||||
type RuntimeEvent: From<Event<Self>> + IsType<<Self as pezframe_system::Config>::RuntimeEvent>;
|
||||
/// The asset ID type that can be used for transaction payments in addition to a
|
||||
/// native asset.
|
||||
type AssetId: AssetId;
|
||||
/// The actual transaction charging logic that charges the fees.
|
||||
type OnChargeAssetTransaction: OnChargeAssetTransaction<
|
||||
Self,
|
||||
Balance = BalanceOf<Self>,
|
||||
AssetId = Self::AssetId,
|
||||
>;
|
||||
/// The weight information of this pallet.
|
||||
type WeightInfo: WeightInfo;
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
/// Benchmark helper
|
||||
type BenchmarkHelper: BenchmarkHelperTrait<
|
||||
Self::AccountId,
|
||||
Self::AssetId,
|
||||
<<Self as Config>::OnChargeAssetTransaction as OnChargeAssetTransaction<Self>>::AssetId,
|
||||
>;
|
||||
}
|
||||
|
||||
#[pallet::pallet]
|
||||
pub struct Pallet<T>(_);
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
/// Helper trait to benchmark the `ChargeAssetTxPayment` transaction extension.
|
||||
pub trait BenchmarkHelperTrait<AccountId, FunAssetIdParameter, AssetIdParameter> {
|
||||
/// Returns the `AssetId` to be used in the liquidity pool by the benchmarking code.
|
||||
fn create_asset_id_parameter(id: u32) -> (FunAssetIdParameter, AssetIdParameter);
|
||||
/// Create a liquidity pool for a given asset and sufficiently endow accounts to benchmark
|
||||
/// the extension.
|
||||
fn setup_balances_and_pool(asset_id: FunAssetIdParameter, account: AccountId);
|
||||
}
|
||||
|
||||
#[pallet::event]
|
||||
#[pallet::generate_deposit(pub(super) fn deposit_event)]
|
||||
pub enum Event<T: Config> {
|
||||
/// A transaction fee `actual_fee`, of which `tip` was added to the minimum inclusion fee,
|
||||
/// has been paid by `who` in an asset `asset_id`.
|
||||
AssetTxFeePaid {
|
||||
who: T::AccountId,
|
||||
actual_fee: BalanceOf<T>,
|
||||
tip: BalanceOf<T>,
|
||||
asset_id: T::AssetId,
|
||||
},
|
||||
/// A swap of the refund in native currency back to asset failed.
|
||||
AssetRefundFailed { native_amount_kept: BalanceOf<T> },
|
||||
}
|
||||
}
|
||||
|
||||
/// Require payment for transaction inclusion and optionally include a tip to gain additional
|
||||
/// priority in the queue.
|
||||
///
|
||||
/// Wraps the transaction logic in [`pezpallet_transaction_payment`] and extends it with assets.
|
||||
/// An asset ID of `None` falls back to the underlying transaction payment logic via the native
|
||||
/// currency.
|
||||
///
|
||||
/// Transaction payments are processed using different handlers based on the asset type:
|
||||
/// - Payments with a native asset are charged by
|
||||
/// [pezpallet_transaction_payment::Config::OnChargeTransaction].
|
||||
/// - Payments with other assets are charged by [Config::OnChargeAssetTransaction].
|
||||
#[derive(Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, TypeInfo)]
|
||||
#[scale_info(skip_type_params(T))]
|
||||
pub struct ChargeAssetTxPayment<T: Config> {
|
||||
#[codec(compact)]
|
||||
tip: BalanceOf<T>,
|
||||
asset_id: Option<T::AssetId>,
|
||||
}
|
||||
|
||||
impl<T: Config> ChargeAssetTxPayment<T>
|
||||
where
|
||||
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
|
||||
{
|
||||
/// Utility constructor. Used only in client/factory code.
|
||||
pub fn from(tip: BalanceOf<T>, asset_id: Option<T::AssetId>) -> Self {
|
||||
Self { tip, asset_id }
|
||||
}
|
||||
|
||||
/// Fee withdrawal logic that dispatches to either [`Config::OnChargeAssetTransaction`] or
|
||||
/// [`pezpallet_transaction_payment::Config::OnChargeTransaction`].
|
||||
fn withdraw_fee(
|
||||
&self,
|
||||
who: &T::AccountId,
|
||||
call: &T::RuntimeCall,
|
||||
info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
fee: BalanceOf<T>,
|
||||
) -> Result<(BalanceOf<T>, InitialPayment<T>), TransactionValidityError> {
|
||||
debug_assert!(self.tip <= fee, "tip should be included in the computed fee");
|
||||
if fee.is_zero() {
|
||||
Ok((fee, InitialPayment::Nothing))
|
||||
} else if let Some(asset_id) = &self.asset_id {
|
||||
T::OnChargeAssetTransaction::withdraw_fee(
|
||||
who,
|
||||
call,
|
||||
info,
|
||||
asset_id.clone(),
|
||||
fee,
|
||||
self.tip,
|
||||
)
|
||||
.map(|payment| (fee, InitialPayment::Asset((asset_id.clone(), payment))))
|
||||
} else {
|
||||
T::OnChargeTransaction::withdraw_fee(who, call, info, fee, self.tip)
|
||||
.map(|payment| (fee, InitialPayment::Native(payment)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Fee withdrawal logic dry-run that dispatches to either `OnChargeAssetTransaction` or
|
||||
/// `OnChargeTransaction`.
|
||||
fn can_withdraw_fee(
|
||||
&self,
|
||||
who: &T::AccountId,
|
||||
call: &T::RuntimeCall,
|
||||
info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
fee: BalanceOf<T>,
|
||||
) -> Result<(), TransactionValidityError> {
|
||||
debug_assert!(self.tip <= fee, "tip should be included in the computed fee");
|
||||
if fee.is_zero() {
|
||||
Ok(())
|
||||
} else if let Some(asset_id) = &self.asset_id {
|
||||
T::OnChargeAssetTransaction::can_withdraw_fee(who, asset_id.clone(), fee.into())
|
||||
} else {
|
||||
<OnChargeTransactionOf<T> as OnChargeTransaction<T>>::can_withdraw_fee(
|
||||
who, call, info, fee, self.tip,
|
||||
)
|
||||
.map_err(|_| -> TransactionValidityError { InvalidTransaction::Payment.into() })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> core::fmt::Debug for ChargeAssetTxPayment<T> {
|
||||
#[cfg(feature = "std")]
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
|
||||
write!(f, "ChargeAssetTxPayment<{:?}, {:?}>", self.tip, self.asset_id.encode())
|
||||
}
|
||||
#[cfg(not(feature = "std"))]
|
||||
fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The info passed between the validate and prepare steps for the `ChargeAssetTxPayment` extension.
|
||||
pub enum Val<T: Config> {
|
||||
Charge {
|
||||
tip: BalanceOf<T>,
|
||||
// who paid the fee
|
||||
who: T::AccountId,
|
||||
// transaction fee
|
||||
fee: BalanceOf<T>,
|
||||
},
|
||||
NoCharge,
|
||||
}
|
||||
|
||||
/// The info passed between the prepare and post-dispatch steps for the `ChargeAssetTxPayment`
|
||||
/// extension.
|
||||
pub enum Pre<T: Config> {
|
||||
Charge {
|
||||
tip: BalanceOf<T>,
|
||||
// who paid the fee
|
||||
who: T::AccountId,
|
||||
// imbalance resulting from withdrawing the fee
|
||||
initial_payment: InitialPayment<T>,
|
||||
// weight used by the extension
|
||||
weight: Weight,
|
||||
},
|
||||
NoCharge {
|
||||
// weight initially estimated by the extension, to be refunded
|
||||
refund: Weight,
|
||||
},
|
||||
}
|
||||
|
||||
impl<T: Config> TransactionExtension<T::RuntimeCall> for ChargeAssetTxPayment<T>
|
||||
where
|
||||
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
|
||||
BalanceOf<T>: Send + Sync + From<u64>,
|
||||
T::AssetId: Send + Sync,
|
||||
<T::RuntimeCall as Dispatchable>::RuntimeOrigin: AsSystemOriginSigner<T::AccountId> + Clone,
|
||||
{
|
||||
const IDENTIFIER: &'static str = "ChargeAssetTxPayment";
|
||||
type Implicit = ();
|
||||
type Val = Val<T>;
|
||||
type Pre = Pre<T>;
|
||||
|
||||
fn weight(&self, _: &T::RuntimeCall) -> Weight {
|
||||
if self.asset_id.is_some() {
|
||||
<T as Config>::WeightInfo::charge_asset_tx_payment_asset()
|
||||
} else {
|
||||
<T as Config>::WeightInfo::charge_asset_tx_payment_native()
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(
|
||||
&self,
|
||||
origin: <T::RuntimeCall as Dispatchable>::RuntimeOrigin,
|
||||
call: &T::RuntimeCall,
|
||||
info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
len: usize,
|
||||
_self_implicit: Self::Implicit,
|
||||
_inherited_implication: &impl Encode,
|
||||
_source: TransactionSource,
|
||||
) -> ValidateResult<Self::Val, T::RuntimeCall> {
|
||||
let Some(who) = origin.as_system_origin_signer() else {
|
||||
return Ok((ValidTransaction::default(), Val::NoCharge, origin));
|
||||
};
|
||||
// Non-mutating call of `compute_fee` to calculate the fee used in the transaction priority.
|
||||
let fee = pezpallet_transaction_payment::Pallet::<T>::compute_fee(len as u32, info, self.tip);
|
||||
self.can_withdraw_fee(&who, call, info, fee)?;
|
||||
let priority = ChargeTransactionPayment::<T>::get_priority(info, len, self.tip, fee);
|
||||
let validity = ValidTransaction { priority, ..Default::default() };
|
||||
let val = Val::Charge { tip: self.tip, who: who.clone(), fee };
|
||||
Ok((validity, val, origin))
|
||||
}
|
||||
|
||||
fn prepare(
|
||||
self,
|
||||
val: Self::Val,
|
||||
_origin: &<T::RuntimeCall as Dispatchable>::RuntimeOrigin,
|
||||
call: &T::RuntimeCall,
|
||||
info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
_len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
match val {
|
||||
Val::Charge { tip, who, fee } => {
|
||||
// Mutating call of `withdraw_fee` to actually charge for the transaction.
|
||||
let (_fee, initial_payment) = self.withdraw_fee(&who, call, info, fee)?;
|
||||
Ok(Pre::Charge { tip, who, initial_payment, weight: self.weight(call) })
|
||||
},
|
||||
Val::NoCharge => Ok(Pre::NoCharge { refund: self.weight(call) }),
|
||||
}
|
||||
}
|
||||
|
||||
fn post_dispatch_details(
|
||||
pre: Self::Pre,
|
||||
info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
post_info: &PostDispatchInfoOf<T::RuntimeCall>,
|
||||
len: usize,
|
||||
_result: &DispatchResult,
|
||||
) -> Result<Weight, TransactionValidityError> {
|
||||
let (tip, who, initial_payment, extension_weight) = match pre {
|
||||
Pre::Charge { tip, who, initial_payment, weight } =>
|
||||
(tip, who, initial_payment, weight),
|
||||
Pre::NoCharge { refund } => {
|
||||
// No-op: Refund everything
|
||||
return Ok(refund);
|
||||
},
|
||||
};
|
||||
|
||||
match initial_payment {
|
||||
InitialPayment::Native(already_withdrawn) => {
|
||||
// Take into account the weight used by this extension before calculating the
|
||||
// refund.
|
||||
let actual_ext_weight = <T as Config>::WeightInfo::charge_asset_tx_payment_native();
|
||||
let unspent_weight = extension_weight.saturating_sub(actual_ext_weight);
|
||||
let mut actual_post_info = *post_info;
|
||||
actual_post_info.refund(unspent_weight);
|
||||
let actual_fee = pezpallet_transaction_payment::Pallet::<T>::compute_actual_fee(
|
||||
len as u32,
|
||||
info,
|
||||
&actual_post_info,
|
||||
tip,
|
||||
);
|
||||
T::OnChargeTransaction::correct_and_deposit_fee(
|
||||
&who,
|
||||
info,
|
||||
&actual_post_info,
|
||||
actual_fee,
|
||||
tip,
|
||||
already_withdrawn,
|
||||
)?;
|
||||
pezpallet_transaction_payment::Pallet::<T>::deposit_fee_paid_event(
|
||||
who, actual_fee, tip,
|
||||
);
|
||||
Ok(unspent_weight)
|
||||
},
|
||||
InitialPayment::Asset((asset_id, already_withdrawn)) => {
|
||||
// Take into account the weight used by this extension before calculating the
|
||||
// refund.
|
||||
let actual_ext_weight = <T as Config>::WeightInfo::charge_asset_tx_payment_asset();
|
||||
let unspent_weight = extension_weight.saturating_sub(actual_ext_weight);
|
||||
let mut actual_post_info = *post_info;
|
||||
actual_post_info.refund(unspent_weight);
|
||||
let actual_fee = pezpallet_transaction_payment::Pallet::<T>::compute_actual_fee(
|
||||
len as u32,
|
||||
info,
|
||||
&actual_post_info,
|
||||
tip,
|
||||
);
|
||||
let converted_fee = T::OnChargeAssetTransaction::correct_and_deposit_fee(
|
||||
&who,
|
||||
info,
|
||||
&actual_post_info,
|
||||
actual_fee,
|
||||
tip,
|
||||
asset_id.clone(),
|
||||
already_withdrawn,
|
||||
)?;
|
||||
|
||||
Pallet::<T>::deposit_event(Event::<T>::AssetTxFeePaid {
|
||||
who,
|
||||
actual_fee: converted_fee,
|
||||
tip,
|
||||
asset_id,
|
||||
});
|
||||
|
||||
Ok(unspent_weight)
|
||||
},
|
||||
InitialPayment::Nothing => {
|
||||
// `actual_fee` should be zero here for any signed extrinsic. It would be
|
||||
// non-zero here in case of unsigned extrinsics as they don't pay fees but
|
||||
// `compute_actual_fee` is not aware of them. In both cases it's fine to just
|
||||
// move ahead without adjusting the fee, though, so we do nothing.
|
||||
debug_assert!(tip.is_zero(), "tip should be zero if initial fee was zero.");
|
||||
Ok(extension_weight
|
||||
.saturating_sub(<T as Config>::WeightInfo::charge_asset_tx_payment_zero()))
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use super::*;
|
||||
use crate as pezpallet_asset_conversion_tx_payment;
|
||||
|
||||
use pezframe_support::{
|
||||
derive_impl,
|
||||
dispatch::DispatchClass,
|
||||
instances::Instance2,
|
||||
ord_parameter_types,
|
||||
pezpallet_prelude::*,
|
||||
parameter_types,
|
||||
traits::{
|
||||
fungible, fungibles,
|
||||
tokens::{
|
||||
fungible::{NativeFromLeft, NativeOrWithId, UnionOf},
|
||||
imbalance::ResolveAssetTo,
|
||||
},
|
||||
AsEnsureOriginWithArg, ConstU32, ConstU64, ConstU8, Imbalance, OnUnbalanced,
|
||||
},
|
||||
weights::{Weight, WeightToFee as WeightToFeeT},
|
||||
PalletId,
|
||||
};
|
||||
use pezframe_system as system;
|
||||
use pezframe_system::{EnsureRoot, EnsureSignedBy};
|
||||
use pezpallet_asset_conversion::{Ascending, Chain, WithFirstAsset};
|
||||
use pezpallet_transaction_payment::FungibleAdapter;
|
||||
use pezsp_runtime::{
|
||||
traits::{AccountIdConversion, IdentityLookup, SaturatedConversion},
|
||||
Permill,
|
||||
};
|
||||
|
||||
type Block = pezframe_system::mocking::MockBlock<Runtime>;
|
||||
type Balance = u64;
|
||||
type AccountId = u64;
|
||||
|
||||
pezframe_support::construct_runtime!(
|
||||
pub enum Runtime
|
||||
{
|
||||
System: system,
|
||||
Balances: pezpallet_balances,
|
||||
TransactionPayment: pezpallet_transaction_payment,
|
||||
Assets: pezpallet_assets,
|
||||
PoolAssets: pezpallet_assets::<Instance2>,
|
||||
AssetConversion: pezpallet_asset_conversion,
|
||||
AssetTxPayment: pezpallet_asset_conversion_tx_payment,
|
||||
}
|
||||
);
|
||||
|
||||
parameter_types! {
|
||||
pub(crate) static ExtrinsicBaseWeight: Weight = Weight::zero();
|
||||
}
|
||||
|
||||
pub struct BlockWeights;
|
||||
impl Get<pezframe_system::limits::BlockWeights> for BlockWeights {
|
||||
fn get() -> pezframe_system::limits::BlockWeights {
|
||||
pezframe_system::limits::BlockWeights::builder()
|
||||
.base_block(Weight::zero())
|
||||
.for_class(DispatchClass::all(), |weights| {
|
||||
weights.base_extrinsic = ExtrinsicBaseWeight::get().into();
|
||||
})
|
||||
.for_class(DispatchClass::non_mandatory(), |weights| {
|
||||
weights.max_total = Weight::from_parts(1024, u64::MAX).into();
|
||||
})
|
||||
.build_or_panic()
|
||||
}
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub static WeightToFee: u64 = 1;
|
||||
pub static TransactionByteFee: u64 = 1;
|
||||
}
|
||||
|
||||
#[derive_impl(pezframe_system::config_preludes::TestDefaultConfig)]
|
||||
impl pezframe_system::Config for Runtime {
|
||||
type BlockWeights = BlockWeights;
|
||||
type Nonce = u64;
|
||||
type AccountId = AccountId;
|
||||
type Lookup = IdentityLookup<Self::AccountId>;
|
||||
type Block = Block;
|
||||
type AccountData = pezpallet_balances::AccountData<u64>;
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const ExistentialDeposit: u64 = 10;
|
||||
}
|
||||
|
||||
#[derive_impl(pezpallet_balances::config_preludes::TestDefaultConfig)]
|
||||
impl pezpallet_balances::Config for Runtime {
|
||||
type ExistentialDeposit = ConstU64<10>;
|
||||
type AccountStore = System;
|
||||
}
|
||||
|
||||
impl WeightToFeeT for WeightToFee {
|
||||
type Balance = u64;
|
||||
|
||||
fn weight_to_fee(weight: &Weight) -> Self::Balance {
|
||||
Self::Balance::saturated_from(weight.ref_time())
|
||||
.saturating_mul(WEIGHT_TO_FEE.with(|v| *v.borrow()))
|
||||
}
|
||||
}
|
||||
|
||||
impl WeightToFeeT for TransactionByteFee {
|
||||
type Balance = u64;
|
||||
|
||||
fn weight_to_fee(weight: &Weight) -> Self::Balance {
|
||||
Self::Balance::saturated_from(weight.ref_time())
|
||||
.saturating_mul(TRANSACTION_BYTE_FEE.with(|v| *v.borrow()))
|
||||
}
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub(crate) static TipUnbalancedAmount: u64 = 0;
|
||||
pub(crate) static FeeUnbalancedAmount: u64 = 0;
|
||||
}
|
||||
|
||||
pub struct DealWithFees;
|
||||
impl OnUnbalanced<fungible::Credit<<Runtime as pezframe_system::Config>::AccountId, Balances>>
|
||||
for DealWithFees
|
||||
{
|
||||
fn on_unbalanceds(
|
||||
mut fees_then_tips: impl Iterator<
|
||||
Item = fungible::Credit<<Runtime as pezframe_system::Config>::AccountId, Balances>,
|
||||
>,
|
||||
) {
|
||||
if let Some(fees) = fees_then_tips.next() {
|
||||
FeeUnbalancedAmount::mutate(|a| *a += fees.peek());
|
||||
if let Some(tips) = fees_then_tips.next() {
|
||||
TipUnbalancedAmount::mutate(|a| *a += tips.peek());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MockTxPaymentWeights;
|
||||
|
||||
impl pezpallet_transaction_payment::WeightInfo for MockTxPaymentWeights {
|
||||
fn charge_transaction_payment() -> Weight {
|
||||
Weight::from_parts(10, 0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DealWithFungiblesFees;
|
||||
impl OnUnbalanced<fungibles::Credit<AccountId, NativeAndAssets>> for DealWithFungiblesFees {
|
||||
fn on_unbalanceds(
|
||||
mut fees_then_tips: impl Iterator<
|
||||
Item = fungibles::Credit<<Runtime as pezframe_system::Config>::AccountId, NativeAndAssets>,
|
||||
>,
|
||||
) {
|
||||
if let Some(fees) = fees_then_tips.next() {
|
||||
FeeUnbalancedAmount::mutate(|a| *a += fees.peek());
|
||||
if let Some(tips) = fees_then_tips.next() {
|
||||
TipUnbalancedAmount::mutate(|a| *a += tips.peek());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive_impl(pezpallet_transaction_payment::config_preludes::TestDefaultConfig)]
|
||||
impl pezpallet_transaction_payment::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type OnChargeTransaction = FungibleAdapter<Balances, DealWithFees>;
|
||||
type WeightToFee = WeightToFee;
|
||||
type LengthToFee = TransactionByteFee;
|
||||
type OperationalFeeMultiplier = ConstU8<5>;
|
||||
type WeightInfo = MockTxPaymentWeights;
|
||||
}
|
||||
|
||||
type AssetId = u32;
|
||||
|
||||
impl pezpallet_assets::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type Balance = Balance;
|
||||
type AssetId = AssetId;
|
||||
type AssetIdParameter = codec::Compact<AssetId>;
|
||||
type ReserveData = ();
|
||||
type Currency = Balances;
|
||||
type CreateOrigin = AsEnsureOriginWithArg<pezframe_system::EnsureSigned<AccountId>>;
|
||||
type ForceOrigin = EnsureRoot<AccountId>;
|
||||
type AssetDeposit = ConstU64<2>;
|
||||
type AssetAccountDeposit = ConstU64<2>;
|
||||
type MetadataDepositBase = ConstU64<0>;
|
||||
type MetadataDepositPerByte = ConstU64<0>;
|
||||
type ApprovalDeposit = ConstU64<0>;
|
||||
type StringLimit = ConstU32<20>;
|
||||
type Holder = ();
|
||||
type Freezer = ();
|
||||
type Extra = ();
|
||||
type CallbackHandle = ();
|
||||
type WeightInfo = ();
|
||||
type RemoveItemsLimit = ConstU32<1000>;
|
||||
pezpallet_assets::runtime_benchmarks_enabled! {
|
||||
type BenchmarkHelper = ();
|
||||
}
|
||||
}
|
||||
|
||||
impl pezpallet_assets::Config<Instance2> for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type Balance = u64;
|
||||
type RemoveItemsLimit = ConstU32<1000>;
|
||||
type AssetId = u32;
|
||||
type AssetIdParameter = u32;
|
||||
type ReserveData = ();
|
||||
type Currency = Balances;
|
||||
type CreateOrigin = AsEnsureOriginWithArg<EnsureSignedBy<AssetConversionOrigin, u64>>;
|
||||
type ForceOrigin = pezframe_system::EnsureRoot<u64>;
|
||||
type AssetDeposit = ConstU64<0>;
|
||||
type AssetAccountDeposit = ConstU64<0>;
|
||||
type MetadataDepositBase = ConstU64<0>;
|
||||
type MetadataDepositPerByte = ConstU64<0>;
|
||||
type ApprovalDeposit = ConstU64<0>;
|
||||
type StringLimit = ConstU32<50>;
|
||||
type Holder = ();
|
||||
type Freezer = ();
|
||||
type Extra = ();
|
||||
type WeightInfo = ();
|
||||
type CallbackHandle = ();
|
||||
pezpallet_assets::runtime_benchmarks_enabled! {
|
||||
type BenchmarkHelper = ();
|
||||
}
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const AssetConversionPalletId: PalletId = PalletId(*b"py/ascon");
|
||||
pub storage LiquidityWithdrawalFee: Permill = Permill::from_percent(0);
|
||||
pub const MaxSwapPathLength: u32 = 4;
|
||||
pub const Native: NativeOrWithId<u32> = NativeOrWithId::Native;
|
||||
}
|
||||
|
||||
ord_parameter_types! {
|
||||
pub const AssetConversionOrigin: u64 = AccountIdConversion::<u64>::into_account_truncating(&AssetConversionPalletId::get());
|
||||
}
|
||||
|
||||
pub type PoolIdToAccountId = pezpallet_asset_conversion::AccountIdConverter<
|
||||
AssetConversionPalletId,
|
||||
(NativeOrWithId<u32>, NativeOrWithId<u32>),
|
||||
>;
|
||||
|
||||
type NativeAndAssets = UnionOf<Balances, Assets, NativeFromLeft, NativeOrWithId<u32>, AccountId>;
|
||||
|
||||
impl pezpallet_asset_conversion::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type Balance = Balance;
|
||||
type HigherPrecisionBalance = u128;
|
||||
type AssetKind = NativeOrWithId<u32>;
|
||||
type Assets = NativeAndAssets;
|
||||
type PoolId = (Self::AssetKind, Self::AssetKind);
|
||||
type PoolLocator = Chain<
|
||||
WithFirstAsset<Native, AccountId, NativeOrWithId<u32>, PoolIdToAccountId>,
|
||||
Ascending<AccountId, NativeOrWithId<u32>, PoolIdToAccountId>,
|
||||
>;
|
||||
type PoolAssetId = u32;
|
||||
type PoolAssets = PoolAssets;
|
||||
type PoolSetupFee = ConstU64<100>; // should be more or equal to the existential deposit
|
||||
type PoolSetupFeeAsset = Native;
|
||||
type PoolSetupFeeTarget = ResolveAssetTo<AssetConversionOrigin, Self::Assets>;
|
||||
type PalletId = AssetConversionPalletId;
|
||||
type LPFee = ConstU32<3>; // means 0.3%
|
||||
type LiquidityWithdrawalFee = LiquidityWithdrawalFee;
|
||||
type MaxSwapPathLength = MaxSwapPathLength;
|
||||
type MintMinLiquidity = ConstU64<100>; // 100 is good enough when the main currency has 12 decimals.
|
||||
type WeightInfo = ();
|
||||
pezpallet_asset_conversion::runtime_benchmarks_enabled! {
|
||||
type BenchmarkHelper = ();
|
||||
}
|
||||
}
|
||||
|
||||
/// Weights used in testing.
|
||||
pub struct MockWeights;
|
||||
|
||||
impl WeightInfo for MockWeights {
|
||||
fn charge_asset_tx_payment_zero() -> Weight {
|
||||
Weight::from_parts(0, 0)
|
||||
}
|
||||
|
||||
fn charge_asset_tx_payment_native() -> Weight {
|
||||
Weight::from_parts(15, 0)
|
||||
}
|
||||
|
||||
fn charge_asset_tx_payment_asset() -> Weight {
|
||||
Weight::from_parts(20, 0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type AssetId = NativeOrWithId<u32>;
|
||||
type OnChargeAssetTransaction =
|
||||
SwapAssetAdapter<Native, NativeAndAssets, AssetConversion, DealWithFungiblesFees>;
|
||||
type WeightInfo = MockWeights;
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
type BenchmarkHelper = Helper;
|
||||
}
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
pub fn new_test_ext() -> pezsp_io::TestExternalities {
|
||||
let base_weight = 5;
|
||||
let balance_factor = 100;
|
||||
crate::tests::ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
}
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
pub struct Helper;
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
impl BenchmarkHelperTrait<u64, NativeOrWithId<u32>, NativeOrWithId<u32>> for Helper {
|
||||
fn create_asset_id_parameter(id: u32) -> (NativeOrWithId<u32>, NativeOrWithId<u32>) {
|
||||
(NativeOrWithId::WithId(id), NativeOrWithId::WithId(id))
|
||||
}
|
||||
|
||||
fn setup_balances_and_pool(asset_id: NativeOrWithId<u32>, account: u64) {
|
||||
use pezframe_support::{assert_ok, traits::fungibles::Mutate};
|
||||
use pezsp_runtime::traits::StaticLookup;
|
||||
let NativeOrWithId::WithId(asset_idx) = asset_id.clone() else { unimplemented!() };
|
||||
assert_ok!(Assets::force_create(
|
||||
RuntimeOrigin::root(),
|
||||
asset_idx.into(),
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
1,
|
||||
));
|
||||
|
||||
let lp_provider = 12;
|
||||
assert_ok!(Balances::force_set_balance(RuntimeOrigin::root(), lp_provider, u64::MAX / 2));
|
||||
let lp_provider_account = <Runtime as system::Config>::Lookup::unlookup(lp_provider);
|
||||
assert_ok!(Assets::mint_into(asset_idx, &lp_provider_account, u64::MAX / 2));
|
||||
|
||||
let token_1 = Box::new(NativeOrWithId::Native);
|
||||
let token_2 = Box::new(asset_id);
|
||||
assert_ok!(AssetConversion::create_pool(
|
||||
RuntimeOrigin::signed(lp_provider),
|
||||
token_1.clone(),
|
||||
token_2.clone()
|
||||
));
|
||||
|
||||
assert_ok!(AssetConversion::add_liquidity(
|
||||
RuntimeOrigin::signed(lp_provider),
|
||||
token_1,
|
||||
token_2,
|
||||
(u32::MAX / 8).into(), // 1 desired
|
||||
u32::MAX.into(), // 2 desired
|
||||
1, // 1 min
|
||||
1, // 2 min
|
||||
lp_provider_account,
|
||||
));
|
||||
|
||||
use pezframe_support::traits::Currency;
|
||||
let _ = Balances::deposit_creating(&account, u32::MAX.into());
|
||||
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(account);
|
||||
let balance = 1000;
|
||||
|
||||
assert_ok!(Assets::mint_into(asset_idx, &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_idx, account), balance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
///! Traits and default implementation for paying transaction fees in assets.
|
||||
use super::*;
|
||||
use crate::Config;
|
||||
|
||||
use alloc::vec;
|
||||
use core::marker::PhantomData;
|
||||
use pezframe_support::{
|
||||
defensive, ensure,
|
||||
traits::{
|
||||
fungibles,
|
||||
tokens::{Balance, Fortitude, Precision, Preservation, WithdrawConsequence},
|
||||
Defensive, OnUnbalanced, SameOrOther,
|
||||
},
|
||||
unsigned::TransactionValidityError,
|
||||
};
|
||||
use pezpallet_asset_conversion::{QuotePrice, SwapCredit};
|
||||
use pezsp_runtime::{
|
||||
traits::{DispatchInfoOf, Get, PostDispatchInfoOf, Zero},
|
||||
transaction_validity::InvalidTransaction,
|
||||
Saturating,
|
||||
};
|
||||
|
||||
/// Handle withdrawing, refunding and depositing of transaction fees.
|
||||
pub trait OnChargeAssetTransaction<T: Config> {
|
||||
/// The underlying integer type in which fees are calculated.
|
||||
type Balance: Balance;
|
||||
/// The type used to identify the assets used for transaction payment.
|
||||
type AssetId: AssetId;
|
||||
/// The type used to store the intermediate values between pre- and post-dispatch.
|
||||
type LiquidityInfo;
|
||||
|
||||
/// Secure the payment of the transaction fees before the transaction is executed.
|
||||
///
|
||||
/// Note: The `fee` already includes the `tip`.
|
||||
fn withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
call: &T::RuntimeCall,
|
||||
dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
asset_id: Self::AssetId,
|
||||
fee: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
) -> Result<Self::LiquidityInfo, TransactionValidityError>;
|
||||
|
||||
/// Ensure payment of the transaction fees can be withdrawn.
|
||||
///
|
||||
/// Note: The `fee` already includes the tip.
|
||||
fn can_withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
asset_id: Self::AssetId,
|
||||
fee: Self::Balance,
|
||||
) -> Result<(), TransactionValidityError>;
|
||||
|
||||
/// Refund any overpaid fees and deposit the corrected amount.
|
||||
/// The actual fee gets calculated once the transaction is executed.
|
||||
///
|
||||
/// Note: The `fee` already includes the `tip`.
|
||||
///
|
||||
/// Returns the amount of `asset_id` that was used for the payment.
|
||||
fn correct_and_deposit_fee(
|
||||
who: &T::AccountId,
|
||||
dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
post_info: &PostDispatchInfoOf<T::RuntimeCall>,
|
||||
corrected_fee: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
asset_id: Self::AssetId,
|
||||
already_withdraw: Self::LiquidityInfo,
|
||||
) -> Result<BalanceOf<T>, TransactionValidityError>;
|
||||
}
|
||||
|
||||
/// Means to withdraw, correct and deposit fees in the asset accepted by the system.
|
||||
///
|
||||
/// The type uses the [`SwapCredit`] implementation to swap the asset used by a user for the fee
|
||||
/// payment for the asset accepted as a fee payment be the system.
|
||||
///
|
||||
/// Parameters:
|
||||
/// - `A`: The asset identifier that system accepts as a fee payment (eg. native asset).
|
||||
/// - `F`: The fungibles registry that can handle assets provided by user and the `A` asset.
|
||||
/// - `S`: The swap implementation that can swap assets provided by user for the `A` asset.
|
||||
/// - OU: The handler for withdrawn `fee` and `tip`, passed in the respective order to
|
||||
/// [OnUnbalanced::on_unbalanceds].
|
||||
/// - `T`: The pallet's configuration.
|
||||
pub struct SwapAssetAdapter<A, F, S, OU>(PhantomData<(A, F, S, OU)>);
|
||||
|
||||
impl<A, F, S, OU, T> OnChargeAssetTransaction<T> for SwapAssetAdapter<A, F, S, OU>
|
||||
where
|
||||
A: Get<T::AssetId>,
|
||||
F: fungibles::Balanced<T::AccountId, Balance = BalanceOf<T>, AssetId = T::AssetId>,
|
||||
S: SwapCredit<
|
||||
T::AccountId,
|
||||
Balance = BalanceOf<T>,
|
||||
AssetKind = T::AssetId,
|
||||
Credit = fungibles::Credit<T::AccountId, F>,
|
||||
> + QuotePrice<Balance = BalanceOf<T>, AssetKind = T::AssetId>,
|
||||
OU: OnUnbalanced<fungibles::Credit<T::AccountId, F>>,
|
||||
T: Config,
|
||||
{
|
||||
type AssetId = T::AssetId;
|
||||
type Balance = BalanceOf<T>;
|
||||
type LiquidityInfo = (fungibles::Credit<T::AccountId, F>, BalanceOf<T>);
|
||||
|
||||
fn withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
_call: &T::RuntimeCall,
|
||||
_dispatch_info: &DispatchInfoOf<<T>::RuntimeCall>,
|
||||
asset_id: Self::AssetId,
|
||||
fee: Self::Balance,
|
||||
_tip: Self::Balance,
|
||||
) -> Result<Self::LiquidityInfo, TransactionValidityError> {
|
||||
if asset_id == A::get() {
|
||||
// The `asset_id` is the target asset, we do not need to swap.
|
||||
let fee_credit = F::withdraw(
|
||||
asset_id.clone(),
|
||||
who,
|
||||
fee,
|
||||
Precision::Exact,
|
||||
Preservation::Preserve,
|
||||
Fortitude::Polite,
|
||||
)
|
||||
.map_err(|_| InvalidTransaction::Payment)?;
|
||||
|
||||
return Ok((fee_credit, fee));
|
||||
}
|
||||
|
||||
// Quote the amount of the `asset_id` needed to pay the fee in the asset `A`.
|
||||
let asset_fee =
|
||||
S::quote_price_tokens_for_exact_tokens(asset_id.clone(), A::get(), fee, true)
|
||||
.ok_or(InvalidTransaction::Payment)?;
|
||||
|
||||
// Withdraw the `asset_id` credit for the swap.
|
||||
let asset_fee_credit = F::withdraw(
|
||||
asset_id.clone(),
|
||||
who,
|
||||
asset_fee,
|
||||
Precision::Exact,
|
||||
Preservation::Preserve,
|
||||
Fortitude::Polite,
|
||||
)
|
||||
.map_err(|_| InvalidTransaction::Payment)?;
|
||||
|
||||
let (fee_credit, change) = match S::swap_tokens_for_exact_tokens(
|
||||
vec![asset_id, A::get()],
|
||||
asset_fee_credit,
|
||||
fee,
|
||||
) {
|
||||
Ok((fee_credit, change)) => (fee_credit, change),
|
||||
Err((credit_in, _)) => {
|
||||
defensive!("Fee swap should pass for the quoted amount");
|
||||
let _ = F::resolve(who, credit_in).defensive_proof("Should resolve the credit");
|
||||
return Err(InvalidTransaction::Payment.into());
|
||||
},
|
||||
};
|
||||
|
||||
// Since the exact price for `fee` has been quoted, the change should be zero.
|
||||
ensure!(change.peek().is_zero(), InvalidTransaction::Payment);
|
||||
|
||||
Ok((fee_credit, asset_fee))
|
||||
}
|
||||
|
||||
/// Dry run of swap & withdraw the predicted fee from the transaction origin.
|
||||
///
|
||||
/// Note: The `fee` already includes the tip.
|
||||
///
|
||||
/// Returns an error if the total amount in native currency can't be exchanged for `asset_id`.
|
||||
fn can_withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
asset_id: Self::AssetId,
|
||||
fee: BalanceOf<T>,
|
||||
) -> Result<(), TransactionValidityError> {
|
||||
if asset_id == A::get() {
|
||||
// The `asset_id` is the target asset, we do not need to swap.
|
||||
match F::can_withdraw(asset_id.clone(), who, fee) {
|
||||
WithdrawConsequence::BalanceLow |
|
||||
WithdrawConsequence::UnknownAsset |
|
||||
WithdrawConsequence::Underflow |
|
||||
WithdrawConsequence::Overflow |
|
||||
WithdrawConsequence::Frozen =>
|
||||
return Err(TransactionValidityError::from(InvalidTransaction::Payment)),
|
||||
WithdrawConsequence::Success |
|
||||
WithdrawConsequence::ReducedToZero(_) |
|
||||
WithdrawConsequence::WouldDie => return Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
let asset_fee =
|
||||
S::quote_price_tokens_for_exact_tokens(asset_id.clone(), A::get(), fee, true)
|
||||
.ok_or(InvalidTransaction::Payment)?;
|
||||
|
||||
// Ensure we can withdraw enough `asset_id` for the swap.
|
||||
match F::can_withdraw(asset_id.clone(), who, asset_fee) {
|
||||
WithdrawConsequence::BalanceLow |
|
||||
WithdrawConsequence::UnknownAsset |
|
||||
WithdrawConsequence::Underflow |
|
||||
WithdrawConsequence::Overflow |
|
||||
WithdrawConsequence::Frozen =>
|
||||
return Err(TransactionValidityError::from(InvalidTransaction::Payment)),
|
||||
WithdrawConsequence::Success |
|
||||
WithdrawConsequence::ReducedToZero(_) |
|
||||
WithdrawConsequence::WouldDie => {},
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn correct_and_deposit_fee(
|
||||
who: &T::AccountId,
|
||||
_dispatch_info: &DispatchInfoOf<<T>::RuntimeCall>,
|
||||
_post_info: &PostDispatchInfoOf<<T>::RuntimeCall>,
|
||||
corrected_fee: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
asset_id: Self::AssetId,
|
||||
already_withdrawn: Self::LiquidityInfo,
|
||||
) -> Result<BalanceOf<T>, TransactionValidityError> {
|
||||
let (fee_paid, initial_asset_consumed) = already_withdrawn;
|
||||
let refund_amount = fee_paid.peek().saturating_sub(corrected_fee);
|
||||
let (fee_in_asset, adjusted_paid) = if refund_amount.is_zero() ||
|
||||
F::total_balance(asset_id.clone(), who).is_zero()
|
||||
{
|
||||
// Nothing to refund or the account was removed be the dispatched function.
|
||||
(initial_asset_consumed, fee_paid)
|
||||
} else if asset_id == A::get() {
|
||||
// The `asset_id` is the target asset, we do not need to swap.
|
||||
let (refund, fee_paid) = fee_paid.split(refund_amount);
|
||||
if let Err(refund) = F::resolve(who, refund) {
|
||||
let fee_paid = fee_paid.merge(refund).map_err(|_| {
|
||||
defensive!("`fee_paid` and `refund` are credits of the same asset.");
|
||||
InvalidTransaction::Payment
|
||||
})?;
|
||||
(initial_asset_consumed, fee_paid)
|
||||
} else {
|
||||
(fee_paid.peek().saturating_sub(refund_amount), fee_paid)
|
||||
}
|
||||
} else {
|
||||
// Check if the refund amount can be swapped back into the asset used by `who` for fee
|
||||
// payment.
|
||||
let refund_asset_amount = S::quote_price_exact_tokens_for_tokens(
|
||||
A::get(),
|
||||
asset_id.clone(),
|
||||
refund_amount,
|
||||
true,
|
||||
)
|
||||
// No refund given if it cannot be swapped back.
|
||||
.unwrap_or(Zero::zero());
|
||||
|
||||
let debt = if refund_asset_amount.is_zero() {
|
||||
fungibles::Debt::<T::AccountId, F>::zero(asset_id.clone())
|
||||
} else {
|
||||
// Deposit the refund before the swap to ensure it can be processed.
|
||||
match F::deposit(asset_id.clone(), &who, refund_asset_amount, Precision::BestEffort)
|
||||
{
|
||||
Ok(debt) => debt,
|
||||
// No refund given since it cannot be deposited.
|
||||
Err(_) => fungibles::Debt::<T::AccountId, F>::zero(asset_id.clone()),
|
||||
}
|
||||
};
|
||||
|
||||
if debt.peek().is_zero() {
|
||||
// No refund given.
|
||||
(initial_asset_consumed, fee_paid)
|
||||
} else {
|
||||
let (refund, adjusted_paid) = fee_paid.split(refund_amount);
|
||||
match S::swap_exact_tokens_for_tokens(
|
||||
vec![A::get(), asset_id],
|
||||
refund,
|
||||
Some(refund_asset_amount),
|
||||
) {
|
||||
Ok(refund_asset) => {
|
||||
match refund_asset.offset(debt) {
|
||||
Ok(SameOrOther::None) => {},
|
||||
// This arm should never be reached, as the amount of `debt` is
|
||||
// expected to be exactly equal to the amount of `refund_asset` credit.
|
||||
_ => {
|
||||
defensive!("Debt should be equal to the refund credit");
|
||||
return Err(InvalidTransaction::Payment.into());
|
||||
},
|
||||
};
|
||||
(
|
||||
initial_asset_consumed.saturating_sub(refund_asset_amount.into()),
|
||||
adjusted_paid,
|
||||
)
|
||||
},
|
||||
// The error should not occur since swap was quoted before.
|
||||
Err((refund, _)) => {
|
||||
defensive!("Refund swap should pass for the quoted amount");
|
||||
match F::settle(who, debt, Preservation::Expendable) {
|
||||
Ok(dust) => ensure!(dust.peek().is_zero(), InvalidTransaction::Payment),
|
||||
// The error should not occur as the `debt` was just withdrawn above.
|
||||
Err(_) => {
|
||||
defensive!("Should settle the debt");
|
||||
return Err(InvalidTransaction::Payment.into());
|
||||
},
|
||||
};
|
||||
let adjusted_paid = adjusted_paid.merge(refund).map_err(|_| {
|
||||
// The error should never occur since `adjusted_paid` and `refund` are
|
||||
// credits of the same asset.
|
||||
InvalidTransaction::Payment
|
||||
})?;
|
||||
(initial_asset_consumed, adjusted_paid)
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Handle the imbalance (fee and tip separately).
|
||||
let (tip, fee) = adjusted_paid.split(tip);
|
||||
OU::on_unbalanceds(Some(fee).into_iter().chain(Some(tip)));
|
||||
Ok(fee_in_asset)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,927 @@
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use super::*;
|
||||
|
||||
use pezframe_support::{
|
||||
assert_ok,
|
||||
dispatch::{DispatchInfo, GetDispatchInfo, PostDispatchInfo},
|
||||
pezpallet_prelude::*,
|
||||
traits::{
|
||||
fungible::{Inspect, NativeOrWithId},
|
||||
fungibles::{Inspect as FungiblesInspect, Mutate},
|
||||
tokens::{Fortitude, Precision, Preservation},
|
||||
OriginTrait,
|
||||
},
|
||||
weights::Weight,
|
||||
};
|
||||
use pezframe_system as system;
|
||||
use mock::{ExtrinsicBaseWeight, *};
|
||||
use pezpallet_balances::Call as BalancesCall;
|
||||
use pezsp_runtime::{
|
||||
traits::{DispatchTransaction, StaticLookup},
|
||||
BuildStorage,
|
||||
};
|
||||
|
||||
const CALL: &<Runtime as pezframe_system::Config>::RuntimeCall =
|
||||
&RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: 2, value: 69 });
|
||||
|
||||
pub struct ExtBuilder {
|
||||
balance_factor: u64,
|
||||
base_weight: Weight,
|
||||
byte_fee: u64,
|
||||
weight_to_fee: u64,
|
||||
}
|
||||
|
||||
impl Default for ExtBuilder {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
balance_factor: 1,
|
||||
base_weight: Weight::from_parts(0, 0),
|
||||
byte_fee: 1,
|
||||
weight_to_fee: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtBuilder {
|
||||
pub fn base_weight(mut self, base_weight: Weight) -> Self {
|
||||
self.base_weight = base_weight;
|
||||
self
|
||||
}
|
||||
pub fn balance_factor(mut self, factor: u64) -> Self {
|
||||
self.balance_factor = factor;
|
||||
self
|
||||
}
|
||||
fn set_constants(&self) {
|
||||
ExtrinsicBaseWeight::mutate(|v| *v = self.base_weight);
|
||||
TRANSACTION_BYTE_FEE.with(|v| *v.borrow_mut() = self.byte_fee);
|
||||
WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee);
|
||||
}
|
||||
pub fn build(self) -> pezsp_io::TestExternalities {
|
||||
self.set_constants();
|
||||
let mut t = pezframe_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();
|
||||
pezpallet_balances::GenesisConfig::<Runtime> {
|
||||
balances: if self.balance_factor > 0 {
|
||||
vec![
|
||||
(1, 10 * self.balance_factor),
|
||||
(2, 20 * self.balance_factor),
|
||||
(3, 30 * self.balance_factor),
|
||||
(4, 40 * self.balance_factor),
|
||||
(5, 50 * self.balance_factor),
|
||||
(6, 60 * self.balance_factor),
|
||||
]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
.assimilate_storage(&mut t)
|
||||
.unwrap();
|
||||
t.into()
|
||||
}
|
||||
}
|
||||
|
||||
/// create a transaction info struct from weight. Handy to avoid building the whole struct.
|
||||
pub fn info_from_weight(w: Weight) -> DispatchInfo {
|
||||
// pays_fee: Pays::Yes -- class: DispatchClass::Normal
|
||||
DispatchInfo { call_weight: w, ..Default::default() }
|
||||
}
|
||||
|
||||
fn post_info_from_weight(w: Weight) -> PostDispatchInfo {
|
||||
PostDispatchInfo { actual_weight: Some(w), pays_fee: Default::default() }
|
||||
}
|
||||
|
||||
fn info_from_pays(p: Pays) -> DispatchInfo {
|
||||
DispatchInfo { pays_fee: p, ..Default::default() }
|
||||
}
|
||||
|
||||
fn post_info_from_pays(p: Pays) -> PostDispatchInfo {
|
||||
PostDispatchInfo { actual_weight: None, pays_fee: p }
|
||||
}
|
||||
|
||||
fn default_post_info() -> PostDispatchInfo {
|
||||
PostDispatchInfo { actual_weight: None, pays_fee: Default::default() }
|
||||
}
|
||||
|
||||
fn setup_lp(asset_id: u32, balance_factor: u64) {
|
||||
let lp_provider = 5;
|
||||
let ed = Balances::minimum_balance();
|
||||
let ed_asset = Assets::minimum_balance(asset_id);
|
||||
assert_ok!(Balances::force_set_balance(
|
||||
RuntimeOrigin::root(),
|
||||
lp_provider,
|
||||
10_000 * balance_factor + ed,
|
||||
));
|
||||
let lp_provider_account = <Runtime as system::Config>::Lookup::unlookup(lp_provider);
|
||||
assert_ok!(Assets::mint_into(
|
||||
asset_id.into(),
|
||||
&lp_provider_account,
|
||||
10_000 * balance_factor + ed_asset
|
||||
));
|
||||
|
||||
let token_1 = NativeOrWithId::Native;
|
||||
let token_2 = NativeOrWithId::WithId(asset_id);
|
||||
assert_ok!(AssetConversion::create_pool(
|
||||
RuntimeOrigin::signed(lp_provider),
|
||||
Box::new(token_1.clone()),
|
||||
Box::new(token_2.clone())
|
||||
));
|
||||
|
||||
assert_ok!(AssetConversion::add_liquidity(
|
||||
RuntimeOrigin::signed(lp_provider),
|
||||
Box::new(token_1),
|
||||
Box::new(token_2),
|
||||
1_000 * balance_factor, // 1 desired
|
||||
10_000 * balance_factor, // 2 desired
|
||||
1, // 1 min
|
||||
1, // 2 min
|
||||
lp_provider_account,
|
||||
));
|
||||
}
|
||||
|
||||
const WEIGHT_5: Weight = Weight::from_parts(5, 0);
|
||||
const WEIGHT_50: Weight = Weight::from_parts(50, 0);
|
||||
const WEIGHT_100: Weight = Weight::from_parts(100, 0);
|
||||
|
||||
#[test]
|
||||
fn transaction_payment_in_native_possible() {
|
||||
let base_weight = 5;
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
let len = 10;
|
||||
let mut info = info_from_weight(WEIGHT_5);
|
||||
let ext = ChargeAssetTxPayment::<Runtime>::from(0, None);
|
||||
info.extension_weight = ext.weight(CALL);
|
||||
let (pre, _) = ext.validate_and_prepare(Some(1).into(), CALL, &info, len, 0).unwrap();
|
||||
let initial_balance = 10 * balance_factor;
|
||||
assert_eq!(Balances::free_balance(1), initial_balance - 5 - 5 - 15 - 10);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info,
|
||||
&default_post_info(),
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
assert_eq!(Balances::free_balance(1), initial_balance - 5 - 5 - 15 - 10);
|
||||
|
||||
let mut info = info_from_weight(WEIGHT_100);
|
||||
let ext = ChargeAssetTxPayment::<Runtime>::from(5 /* tipped */, None);
|
||||
let extension_weight = ext.weight(CALL);
|
||||
info.extension_weight = extension_weight;
|
||||
let (pre, _) = ext.validate_and_prepare(Some(2).into(), CALL, &info, len, 0).unwrap();
|
||||
let initial_balance_for_2 = 20 * balance_factor;
|
||||
|
||||
assert_eq!(Balances::free_balance(2), initial_balance_for_2 - 5 - 10 - 100 - 15 - 5);
|
||||
let call_actual_weight = WEIGHT_50;
|
||||
let post_info = post_info_from_weight(
|
||||
info.call_weight
|
||||
.saturating_sub(call_actual_weight)
|
||||
.saturating_add(extension_weight),
|
||||
);
|
||||
// The extension weight refund should be taken into account in `post_dispatch`.
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info,
|
||||
&post_info,
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
assert_eq!(Balances::free_balance(2), initial_balance_for_2 - 5 - 10 - 50 - 15 - 5);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_payment_in_asset_possible() {
|
||||
let base_weight = 5;
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
System::set_block_number(1);
|
||||
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 2;
|
||||
assert_ok!(Assets::force_create(
|
||||
RuntimeOrigin::root(),
|
||||
asset_id.into(),
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 1;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 1000;
|
||||
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
let len = 10;
|
||||
let tx_weight = 5;
|
||||
|
||||
setup_lp(asset_id, balance_factor);
|
||||
|
||||
let fee_in_native = base_weight + tx_weight + len as u64;
|
||||
let input_quote = AssetConversion::quote_price_tokens_for_exact_tokens(
|
||||
NativeOrWithId::WithId(asset_id),
|
||||
NativeOrWithId::Native,
|
||||
fee_in_native,
|
||||
true,
|
||||
);
|
||||
assert_eq!(input_quote, Some(201));
|
||||
|
||||
let fee_in_asset = input_quote.unwrap();
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id.into()))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_weight(WEIGHT_5),
|
||||
len,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
// assert that native balance is not used
|
||||
assert_eq!(Balances::free_balance(caller), 10 * balance_factor);
|
||||
|
||||
// check that fee was charged in the given asset
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset);
|
||||
|
||||
System::assert_has_event(RuntimeEvent::Assets(pezpallet_assets::Event::Withdrawn {
|
||||
asset_id,
|
||||
who: caller,
|
||||
amount: fee_in_asset,
|
||||
}));
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info_from_weight(WEIGHT_5), // estimated tx weight
|
||||
&default_post_info(), // weight actually used == estimated
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset);
|
||||
assert_eq!(TipUnbalancedAmount::get(), 0);
|
||||
assert_eq!(FeeUnbalancedAmount::get(), fee_in_native);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_payment_in_asset_fails_if_no_pool_for_that_asset() {
|
||||
let base_weight = 5;
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 2;
|
||||
assert_ok!(Assets::force_create(
|
||||
RuntimeOrigin::root(),
|
||||
asset_id.into(),
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 1;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 1000;
|
||||
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
let len = 10;
|
||||
let pre = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id.into()))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_weight(WEIGHT_5),
|
||||
len,
|
||||
0,
|
||||
);
|
||||
|
||||
// As there is no pool in the dex set up for this asset, conversion should fail.
|
||||
assert!(pre.is_err());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_payment_without_fee() {
|
||||
let base_weight = 5;
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
let caller = 1;
|
||||
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let balance = 1000;
|
||||
let min_balance = 2;
|
||||
|
||||
assert_ok!(Assets::force_create(
|
||||
RuntimeOrigin::root(),
|
||||
asset_id.into(),
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance,
|
||||
));
|
||||
|
||||
setup_lp(asset_id, balance_factor);
|
||||
|
||||
// mint into the caller account
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
let weight = 5;
|
||||
let len = 10;
|
||||
let fee_in_native = base_weight + weight + len as u64;
|
||||
let input_quote = AssetConversion::quote_price_tokens_for_exact_tokens(
|
||||
NativeOrWithId::WithId(asset_id),
|
||||
NativeOrWithId::Native,
|
||||
fee_in_native,
|
||||
true,
|
||||
);
|
||||
assert_eq!(input_quote, Some(201));
|
||||
|
||||
let fee_in_asset = input_quote.unwrap();
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id.into()))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_weight(WEIGHT_5),
|
||||
len,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// assert that native balance is not used
|
||||
assert_eq!(Balances::free_balance(caller), 10 * balance_factor);
|
||||
// check that fee was charged in the given asset
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset);
|
||||
|
||||
let refund = AssetConversion::quote_price_exact_tokens_for_tokens(
|
||||
NativeOrWithId::Native,
|
||||
NativeOrWithId::WithId(asset_id),
|
||||
fee_in_native,
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(refund, 199);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info_from_weight(WEIGHT_5),
|
||||
&post_info_from_pays(Pays::No),
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
|
||||
// caller should get refunded
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset + refund);
|
||||
assert_eq!(Balances::free_balance(caller), 10 * balance_factor);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asset_transaction_payment_with_tip_and_refund() {
|
||||
let base_weight = 5;
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
System::set_block_number(1);
|
||||
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 2;
|
||||
assert_ok!(Assets::force_create(
|
||||
RuntimeOrigin::root(),
|
||||
asset_id.into(),
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance,
|
||||
));
|
||||
|
||||
setup_lp(asset_id, balance_factor);
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 2;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 10000;
|
||||
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
let weight = 100;
|
||||
let tip = 5;
|
||||
let ext = ChargeAssetTxPayment::<Runtime>::from(tip, Some(asset_id.into()));
|
||||
let ext_weight = ext.weight(CALL);
|
||||
let len = 10;
|
||||
let fee_in_native = base_weight + weight + ext_weight.ref_time() + len as u64 + tip;
|
||||
let input_quote = AssetConversion::quote_price_tokens_for_exact_tokens(
|
||||
NativeOrWithId::WithId(asset_id),
|
||||
NativeOrWithId::Native,
|
||||
fee_in_native,
|
||||
true,
|
||||
);
|
||||
assert_eq!(input_quote, Some(1407));
|
||||
|
||||
let fee_in_asset = input_quote.unwrap();
|
||||
let mut info = info_from_weight(WEIGHT_100);
|
||||
let ext = ChargeAssetTxPayment::<Runtime>::from(tip, Some(asset_id.into()));
|
||||
info.extension_weight = ext.weight(CALL);
|
||||
let (pre, _) =
|
||||
ext.validate_and_prepare(Some(caller).into(), CALL, &info, len, 0).unwrap();
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset);
|
||||
|
||||
let final_weight = 50;
|
||||
let weight_refund = weight - final_weight;
|
||||
let ext_weight_refund = ext_weight - MockWeights::charge_asset_tx_payment_asset();
|
||||
let expected_fee = fee_in_native - weight_refund - ext_weight_refund.ref_time() - tip;
|
||||
let expected_token_refund = AssetConversion::quote_price_exact_tokens_for_tokens(
|
||||
NativeOrWithId::Native,
|
||||
NativeOrWithId::WithId(asset_id),
|
||||
fee_in_native - expected_fee - tip,
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
System::assert_has_event(RuntimeEvent::Assets(pezpallet_assets::Event::Withdrawn {
|
||||
asset_id,
|
||||
who: caller,
|
||||
amount: fee_in_asset,
|
||||
}));
|
||||
|
||||
let post_info = post_info_from_weight(WEIGHT_50.saturating_add(ext_weight));
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info,
|
||||
&post_info,
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
|
||||
assert_eq!(TipUnbalancedAmount::get(), tip);
|
||||
assert_eq!(FeeUnbalancedAmount::get(), expected_fee);
|
||||
|
||||
// caller should get refunded
|
||||
assert_eq!(
|
||||
Assets::balance(asset_id, caller),
|
||||
balance - fee_in_asset + expected_token_refund
|
||||
);
|
||||
assert_eq!(Balances::free_balance(caller), 20 * balance_factor);
|
||||
|
||||
System::assert_has_event(RuntimeEvent::Assets(pezpallet_assets::Event::Deposited {
|
||||
asset_id,
|
||||
who: caller,
|
||||
amount: expected_token_refund,
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payment_from_account_with_only_assets() {
|
||||
let base_weight = 5;
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 2;
|
||||
assert_ok!(Assets::force_create(
|
||||
RuntimeOrigin::root(),
|
||||
asset_id.into(),
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance,
|
||||
));
|
||||
|
||||
setup_lp(asset_id, balance_factor);
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 333;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 1000;
|
||||
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
// assert that native balance is not necessary
|
||||
assert_eq!(Balances::free_balance(caller), 0);
|
||||
let weight = 5;
|
||||
let len = 10;
|
||||
|
||||
let fee_in_native = base_weight + weight + len as u64;
|
||||
let fee_in_asset = AssetConversion::quote_price_tokens_for_exact_tokens(
|
||||
NativeOrWithId::WithId(asset_id),
|
||||
NativeOrWithId::Native,
|
||||
fee_in_native,
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(fee_in_asset, 201);
|
||||
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id.into()))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_weight(WEIGHT_5),
|
||||
len,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
// check that fee was charged in the given asset
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info_from_weight(WEIGHT_5),
|
||||
&default_post_info(),
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset);
|
||||
assert_eq!(Balances::free_balance(caller), 0);
|
||||
|
||||
assert_eq!(TipUnbalancedAmount::get(), 0);
|
||||
assert_eq!(FeeUnbalancedAmount::get(), fee_in_native);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_fee_is_never_zero_if_input_fee_is_not() {
|
||||
let base_weight = 1;
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 1;
|
||||
assert_ok!(Assets::force_create(
|
||||
RuntimeOrigin::root(),
|
||||
asset_id.into(),
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
|
||||
setup_lp(asset_id, balance_factor);
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 2;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 1000;
|
||||
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
let weight = 1;
|
||||
let len = 1;
|
||||
|
||||
// there will be no conversion when the fee is zero
|
||||
{
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id.into()))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_pays(Pays::No),
|
||||
len,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
// `Pays::No` implies there are no fees
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info_from_pays(Pays::No),
|
||||
&post_info_from_pays(Pays::No),
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
}
|
||||
|
||||
// validate even a small fee gets converted to asset.
|
||||
let fee_in_native = base_weight + weight + len as u64;
|
||||
let fee_in_asset = AssetConversion::quote_price_tokens_for_exact_tokens(
|
||||
NativeOrWithId::WithId(asset_id),
|
||||
NativeOrWithId::Native,
|
||||
fee_in_native,
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id.into()))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_weight(Weight::from_parts(weight, 0)),
|
||||
len,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info_from_weight(Weight::from_parts(weight, 0)),
|
||||
&default_post_info(),
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_dispatch_fee_is_zero_if_pre_dispatch_fee_is_zero() {
|
||||
let base_weight = 1;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(100)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 100;
|
||||
assert_ok!(Assets::force_create(
|
||||
RuntimeOrigin::root(),
|
||||
asset_id.into(),
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 333;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 1000;
|
||||
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
let weight = 1;
|
||||
let len = 1;
|
||||
let fee = base_weight + weight + len as u64;
|
||||
|
||||
// calculated fee is greater than 0
|
||||
assert!(fee > 0);
|
||||
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id.into()))
|
||||
.validate_and_prepare(Some(caller).into(), CALL, &info_from_pays(Pays::No), len, 0)
|
||||
.unwrap();
|
||||
// `Pays::No` implies no pre-dispatch fees
|
||||
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
let Pre::Charge { initial_payment, .. } = &pre else {
|
||||
panic!("Expected Charge");
|
||||
};
|
||||
let not_paying = match initial_payment {
|
||||
&InitialPayment::Nothing => true,
|
||||
_ => false,
|
||||
};
|
||||
assert!(not_paying, "initial payment should be Nothing if we pass Pays::No");
|
||||
|
||||
// `Pays::Yes` on post-dispatch does not mean we pay (we never charge more than the
|
||||
// initial fee)
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info_from_pays(Pays::No),
|
||||
&post_info_from_pays(Pays::Yes),
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fee_with_native_asset_passed_with_id() {
|
||||
let base_weight = 5;
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
let caller = 1;
|
||||
let caller_balance = 1000;
|
||||
// native asset
|
||||
let asset_id = NativeOrWithId::Native;
|
||||
// assert that native balance is not necessary
|
||||
assert_eq!(Balances::free_balance(caller), caller_balance);
|
||||
|
||||
let tip = 10;
|
||||
let call_weight = 100;
|
||||
let ext = ChargeAssetTxPayment::<Runtime>::from(tip, Some(asset_id.into()));
|
||||
let extension_weight = ext.weight(CALL);
|
||||
let len = 5;
|
||||
let initial_fee =
|
||||
base_weight + call_weight + extension_weight.ref_time() + len as u64 + tip;
|
||||
|
||||
let mut info = info_from_weight(WEIGHT_100);
|
||||
info.extension_weight = extension_weight;
|
||||
let (pre, _) =
|
||||
ext.validate_and_prepare(Some(caller).into(), CALL, &info, len, 0).unwrap();
|
||||
assert_eq!(Balances::free_balance(caller), caller_balance - initial_fee);
|
||||
|
||||
let final_weight = 50;
|
||||
// No refunds from the extension weight itself.
|
||||
let expected_fee = initial_fee - final_weight;
|
||||
|
||||
let post_info = post_info_from_weight(WEIGHT_50.saturating_add(extension_weight));
|
||||
assert_eq!(
|
||||
ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info_from_weight(WEIGHT_100),
|
||||
&post_info,
|
||||
len,
|
||||
&Ok(()),
|
||||
)
|
||||
.unwrap(),
|
||||
Weight::zero()
|
||||
);
|
||||
|
||||
assert_eq!(Balances::free_balance(caller), caller_balance - expected_fee);
|
||||
|
||||
assert_eq!(TipUnbalancedAmount::get(), tip);
|
||||
assert_eq!(FeeUnbalancedAmount::get(), expected_fee - tip);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transfer_add_and_remove_account() {
|
||||
let base_weight = 5;
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
System::set_block_number(1);
|
||||
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 2;
|
||||
assert_ok!(Assets::force_create(
|
||||
RuntimeOrigin::root(),
|
||||
asset_id.into(),
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance,
|
||||
));
|
||||
|
||||
setup_lp(asset_id, balance_factor);
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 222;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 10000;
|
||||
|
||||
assert_eq!(Balances::free_balance(caller), 0);
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
let call_weight = 100;
|
||||
let tip = 5;
|
||||
let ext = ChargeAssetTxPayment::<Runtime>::from(tip, Some(asset_id.into()));
|
||||
let extension_weight = ext.weight(CALL);
|
||||
let len = 10;
|
||||
let fee_in_native =
|
||||
base_weight + call_weight + extension_weight.ref_time() + len as u64 + tip;
|
||||
let input_quote = AssetConversion::quote_price_tokens_for_exact_tokens(
|
||||
NativeOrWithId::WithId(asset_id),
|
||||
NativeOrWithId::Native,
|
||||
fee_in_native,
|
||||
true,
|
||||
);
|
||||
assert!(!input_quote.unwrap().is_zero());
|
||||
|
||||
let fee_in_asset = input_quote.unwrap();
|
||||
let mut info = info_from_weight(WEIGHT_100);
|
||||
info.extension_weight = extension_weight;
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(tip, Some(asset_id.into()))
|
||||
.validate_and_prepare(Some(caller).into(), CALL, &info, len, 0)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(Assets::balance(asset_id, &caller), balance - fee_in_asset);
|
||||
|
||||
// remove caller account.
|
||||
assert_ok!(Assets::burn_from(
|
||||
asset_id,
|
||||
&caller,
|
||||
Assets::balance(asset_id, &caller),
|
||||
Preservation::Expendable,
|
||||
Precision::Exact,
|
||||
Fortitude::Force
|
||||
));
|
||||
|
||||
// Actual call weight + actual extension weight.
|
||||
let final_weight = 50 + 20;
|
||||
let final_fee_in_native = fee_in_native - final_weight - tip;
|
||||
let token_refund = AssetConversion::quote_price_exact_tokens_for_tokens(
|
||||
NativeOrWithId::Native,
|
||||
NativeOrWithId::WithId(asset_id),
|
||||
fee_in_native - final_fee_in_native - tip,
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// make sure the refund amount is enough to create the account.
|
||||
assert!(token_refund >= min_balance);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info,
|
||||
&post_info_from_weight(WEIGHT_50),
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
|
||||
// fee paid with no refund.
|
||||
assert_eq!(TipUnbalancedAmount::get(), tip);
|
||||
assert_eq!(FeeUnbalancedAmount::get(), fee_in_native - tip);
|
||||
|
||||
// caller account removed.
|
||||
assert_eq!(Assets::balance(asset_id, caller), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_fee_and_no_weight_for_other_origins() {
|
||||
ExtBuilder::default().build().execute_with(|| {
|
||||
let ext = ChargeAssetTxPayment::<Runtime>::from(0, None);
|
||||
|
||||
let mut info = CALL.get_dispatch_info();
|
||||
info.extension_weight = ext.weight(CALL);
|
||||
|
||||
// Ensure we test the refund.
|
||||
assert!(info.extension_weight != Weight::zero());
|
||||
|
||||
let len = CALL.encoded_size();
|
||||
|
||||
let origin = pezframe_system::RawOrigin::Root.into();
|
||||
let (pre, origin) = ext.validate_and_prepare(origin, CALL, &info, len, 0).unwrap();
|
||||
|
||||
assert!(origin.as_system_ref().unwrap().is_root());
|
||||
|
||||
let pd_res = Ok(());
|
||||
let mut post_info = pezframe_support::dispatch::PostDispatchInfo {
|
||||
actual_weight: Some(info.total_weight()),
|
||||
pays_fee: Default::default(),
|
||||
};
|
||||
|
||||
<ChargeAssetTxPayment<Runtime> as TransactionExtension<RuntimeCall>>::post_dispatch(
|
||||
pre,
|
||||
&info,
|
||||
&mut post_info,
|
||||
len,
|
||||
&pd_res,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(post_info.actual_weight, Some(info.call_weight));
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Autogenerated weights for `pezpallet_asset_conversion_tx_payment`
|
||||
//!
|
||||
//! THIS FILE WAS AUTO-GENERATED USING THE BIZINIKIWI BENCHMARK CLI VERSION 32.0.0
|
||||
//! DATE: 2025-02-21, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
|
||||
//! WORST CASE MAP SIZE: `1000000`
|
||||
//! HOSTNAME: `4563561839a5`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz`
|
||||
//! WASM-EXECUTION: `Compiled`, CHAIN: `None`, DB CACHE: `1024`
|
||||
|
||||
// Executed Command:
|
||||
// frame-omni-bencher
|
||||
// v1
|
||||
// benchmark
|
||||
// pallet
|
||||
// --extrinsic=*
|
||||
// --runtime=target/production/wbuild/kitchensink-runtime/kitchensink_runtime.wasm
|
||||
// --pallet=pezpallet_asset_conversion_tx_payment
|
||||
// --header=/__w/pezkuwi-sdk/pezkuwi-sdk/bizinikiwi/HEADER-APACHE2
|
||||
// --output=/__w/pezkuwi-sdk/pezkuwi-sdk/bizinikiwi/pezframe/transaction-payment/asset-conversion-tx-payment/src/weights.rs
|
||||
// --wasm-execution=compiled
|
||||
// --steps=50
|
||||
// --repeat=20
|
||||
// --heap-pages=4096
|
||||
// --template=bizinikiwi/.maintain/frame-weight-template.hbs
|
||||
// --no-storage-info
|
||||
// --no-min-squares
|
||||
// --no-median-slopes
|
||||
// --genesis-builder-policy=none
|
||||
// --exclude-pallets=pezpallet_xcm,pezpallet_xcm_benchmarks::fungible,pezpallet_xcm_benchmarks::generic,pezpallet_nomination_pools,pezpallet_remark,pezpallet_transaction_storage,pezpallet_election_provider_multi_block,pezpallet_election_provider_multi_block::signed,pezpallet_election_provider_multi_block::unsigned,pezpallet_election_provider_multi_block::verifier
|
||||
|
||||
#![cfg_attr(rustfmt, rustfmt_skip)]
|
||||
#![allow(unused_parens)]
|
||||
#![allow(unused_imports)]
|
||||
#![allow(missing_docs)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
use pezframe_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
|
||||
use core::marker::PhantomData;
|
||||
|
||||
/// Weight functions needed for `pezpallet_asset_conversion_tx_payment`.
|
||||
pub trait WeightInfo {
|
||||
fn charge_asset_tx_payment_zero() -> Weight;
|
||||
fn charge_asset_tx_payment_native() -> Weight;
|
||||
fn charge_asset_tx_payment_asset() -> Weight;
|
||||
}
|
||||
|
||||
/// Weights for `pezpallet_asset_conversion_tx_payment` using the Bizinikiwi node and recommended hardware.
|
||||
pub struct BizinikiwiWeight<T>(PhantomData<T>);
|
||||
impl<T: pezframe_system::Config> WeightInfo for BizinikiwiWeight<T> {
|
||||
fn charge_asset_tx_payment_zero() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `0`
|
||||
// Estimated: `0`
|
||||
// Minimum execution time: 679_000 picoseconds.
|
||||
Weight::from_parts(736_000, 0)
|
||||
}
|
||||
/// Storage: `System::Account` (r:1 w:1)
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
fn charge_asset_tx_payment_native() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `51`
|
||||
// Estimated: `3593`
|
||||
// Minimum execution time: 39_825_000 picoseconds.
|
||||
Weight::from_parts(40_645_000, 3593)
|
||||
.saturating_add(T::DbWeight::get().reads(1_u64))
|
||||
.saturating_add(T::DbWeight::get().writes(1_u64))
|
||||
}
|
||||
/// Storage: `Assets::Asset` (r:1 w:1)
|
||||
/// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`)
|
||||
/// Storage: `Assets::Account` (r:2 w:2)
|
||||
/// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`)
|
||||
/// Storage: `System::Account` (r:1 w:1)
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
fn charge_asset_tx_payment_asset() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `510`
|
||||
// Estimated: `6208`
|
||||
// Minimum execution time: 150_693_000 picoseconds.
|
||||
Weight::from_parts(152_207_000, 6208)
|
||||
.saturating_add(T::DbWeight::get().reads(4_u64))
|
||||
.saturating_add(T::DbWeight::get().writes(4_u64))
|
||||
}
|
||||
}
|
||||
|
||||
// For backwards compatibility and tests.
|
||||
impl WeightInfo for () {
|
||||
fn charge_asset_tx_payment_zero() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `0`
|
||||
// Estimated: `0`
|
||||
// Minimum execution time: 679_000 picoseconds.
|
||||
Weight::from_parts(736_000, 0)
|
||||
}
|
||||
/// Storage: `System::Account` (r:1 w:1)
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
fn charge_asset_tx_payment_native() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `51`
|
||||
// Estimated: `3593`
|
||||
// Minimum execution time: 39_825_000 picoseconds.
|
||||
Weight::from_parts(40_645_000, 3593)
|
||||
.saturating_add(RocksDbWeight::get().reads(1_u64))
|
||||
.saturating_add(RocksDbWeight::get().writes(1_u64))
|
||||
}
|
||||
/// Storage: `Assets::Asset` (r:1 w:1)
|
||||
/// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`)
|
||||
/// Storage: `Assets::Account` (r:2 w:2)
|
||||
/// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`)
|
||||
/// Storage: `System::Account` (r:1 w:1)
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
fn charge_asset_tx_payment_asset() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `510`
|
||||
// Estimated: `6208`
|
||||
// Minimum execution time: 150_693_000 picoseconds.
|
||||
Weight::from_parts(152_207_000, 6208)
|
||||
.saturating_add(RocksDbWeight::get().reads(4_u64))
|
||||
.saturating_add(RocksDbWeight::get().writes(4_u64))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user