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:
@@ -0,0 +1,70 @@
|
||||
[package]
|
||||
name = "pezpallet-asset-tx-payment"
|
||||
version = "28.0.0"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license = "Apache-2.0"
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
description = "pallet to manage transaction payments in assets"
|
||||
readme = "README.md"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
# Bizinikiwi dependencies
|
||||
pezsp-io = { workspace = true }
|
||||
pezsp-runtime = { workspace = true }
|
||||
|
||||
pezframe-benchmarking = { optional = true, workspace = true }
|
||||
pezframe-support = { workspace = true }
|
||||
pezframe-system = { workspace = true }
|
||||
pezpallet-transaction-payment = { workspace = true }
|
||||
|
||||
# Other dependencies
|
||||
codec = { features = ["derive"], workspace = true }
|
||||
scale-info = { features = ["derive"], workspace = true }
|
||||
serde = { optional = true, workspace = true, default-features = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pezpallet-assets = { workspace = true, default-features = true }
|
||||
pezpallet-authorship = { workspace = true, default-features = true }
|
||||
pezpallet-balances = { workspace = true, default-features = true }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"codec/std",
|
||||
"pezframe-benchmarking?/std",
|
||||
"pezframe-support/std",
|
||||
"pezframe-system/std",
|
||||
"pezpallet-transaction-payment/std",
|
||||
"scale-info/std",
|
||||
"serde",
|
||||
"pezsp-io/std",
|
||||
"pezsp-runtime/std",
|
||||
]
|
||||
runtime-benchmarks = [
|
||||
"pezframe-benchmarking/runtime-benchmarks",
|
||||
"pezframe-support/runtime-benchmarks",
|
||||
"pezframe-system/runtime-benchmarks",
|
||||
"pezpallet-assets/runtime-benchmarks",
|
||||
"pezpallet-authorship/runtime-benchmarks",
|
||||
"pezpallet-balances/runtime-benchmarks",
|
||||
"pezpallet-transaction-payment/runtime-benchmarks",
|
||||
"pezsp-io/runtime-benchmarks",
|
||||
"pezsp-runtime/runtime-benchmarks",
|
||||
]
|
||||
try-runtime = [
|
||||
"pezframe-support/try-runtime",
|
||||
"pezframe-system/try-runtime",
|
||||
"pezpallet-assets/try-runtime",
|
||||
"pezpallet-authorship/try-runtime",
|
||||
"pezpallet-balances/try-runtime",
|
||||
"pezpallet-transaction-payment/try-runtime",
|
||||
"pezsp-runtime/try-runtime",
|
||||
]
|
||||
@@ -0,0 +1,21 @@
|
||||
# pezpallet-asset-tx-payment
|
||||
|
||||
## Asset Transaction Payment Pallet
|
||||
|
||||
This pallet allows runtimes that include it to pay for transactions in assets other than the
|
||||
native token of the chain.
|
||||
|
||||
### Overview
|
||||
It does this by extending transactions to include an optional `AssetId` that specifies the asset
|
||||
to be used for payment (defaulting to the native token on `None`). It expects an
|
||||
[`OnChargeAssetTransaction`] implementation analogously to [`pezpallet-transaction-payment`]. The
|
||||
included [`FungiblesAdapter`] (implementing [`OnChargeAssetTransaction`]) determines the fee
|
||||
amount by converting the fee calculated by [`pezpallet-transaction-payment`] into the desired
|
||||
asset.
|
||||
|
||||
### Integration
|
||||
This pallet 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`]).
|
||||
|
||||
License: Apache-2.0
|
||||
@@ -0,0 +1,131 @@
|
||||
// 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 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>,
|
||||
AssetBalanceOf<T>: Send + Sync,
|
||||
BalanceOf<T>: Send + Sync + From<u64> + IsType<ChargeAssetBalanceOf<T>>,
|
||||
ChargeAssetIdOf<T>: Send + Sync,
|
||||
<T::RuntimeCall as Dispatchable>::RuntimeOrigin: AsSystemOriginSigner<T::AccountId> + Clone,
|
||||
Credit<T::AccountId, T::Fungibles>: IsType<ChargeAssetLiquidityOf<T>>,
|
||||
)]
|
||||
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(0u32.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(10u32.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,
|
||||
};
|
||||
let post_info = PostDispatchInfo {
|
||||
actual_weight: Some(Weight::from_parts(10, 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.clone(),
|
||||
caller.clone(),
|
||||
);
|
||||
let tip = 10u32.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,
|
||||
};
|
||||
let post_info = PostDispatchInfo {
|
||||
actual_weight: Some(Weight::from_parts(10, 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,443 @@
|
||||
// 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 Transaction Payment Pallet
|
||||
//!
|
||||
//! This pallet allows runtimes that include it to pay for transactions in assets other than the
|
||||
//! main token of the chain.
|
||||
//!
|
||||
//! ## Overview
|
||||
|
||||
//! It does this by extending transactions to include an optional `AssetId` that specifies the asset
|
||||
//! to be used for payment (defaulting to the native token on `None`). It expects an
|
||||
//! [`OnChargeAssetTransaction`] implementation analogously to [`pezpallet-transaction-payment`]. The
|
||||
//! included [`FungiblesAdapter`] (implementing [`OnChargeAssetTransaction`]) determines the fee
|
||||
//! amount by converting the fee calculated by [`pezpallet-transaction-payment`] into the desired
|
||||
//! asset.
|
||||
//!
|
||||
//! ## Integration
|
||||
|
||||
//! This pallet 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`]).
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use codec::{Decode, DecodeWithMemTracking, Encode};
|
||||
use pezframe_support::{
|
||||
dispatch::{DispatchInfo, DispatchResult, PostDispatchInfo},
|
||||
pezpallet_prelude::{TransactionSource, Weight},
|
||||
traits::{
|
||||
tokens::{
|
||||
fungibles::{Balanced, Credit, Inspect},
|
||||
WithdrawConsequence,
|
||||
},
|
||||
IsType,
|
||||
},
|
||||
DefaultNoBound,
|
||||
};
|
||||
use pezpallet_transaction_payment::OnChargeTransaction;
|
||||
use scale_info::TypeInfo;
|
||||
use pezsp_runtime::{
|
||||
traits::{
|
||||
AsSystemOriginSigner, DispatchInfoOf, Dispatchable, PostDispatchInfoOf, RefundWeight,
|
||||
TransactionExtension, Zero,
|
||||
},
|
||||
transaction_validity::{InvalidTransaction, TransactionValidityError, ValidTransaction},
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod mock;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
mod benchmarking;
|
||||
|
||||
mod payment;
|
||||
pub mod weights;
|
||||
|
||||
pub use payment::*;
|
||||
pub use weights::WeightInfo;
|
||||
|
||||
/// Type aliases used for interaction with `OnChargeTransaction`.
|
||||
pub(crate) type OnChargeTransactionOf<T> =
|
||||
<T as pezpallet_transaction_payment::Config>::OnChargeTransaction;
|
||||
/// Balance type alias.
|
||||
pub(crate) type BalanceOf<T> = <OnChargeTransactionOf<T> as OnChargeTransaction<T>>::Balance;
|
||||
/// Liquidity info type alias.
|
||||
pub(crate) type LiquidityInfoOf<T> =
|
||||
<OnChargeTransactionOf<T> as OnChargeTransaction<T>>::LiquidityInfo;
|
||||
|
||||
/// Type alias used for interaction with fungibles (assets).
|
||||
/// Balance type alias.
|
||||
pub(crate) type AssetBalanceOf<T> =
|
||||
<<T as Config>::Fungibles as Inspect<<T as pezframe_system::Config>::AccountId>>::Balance;
|
||||
/// Asset id type alias.
|
||||
pub(crate) type AssetIdOf<T> =
|
||||
<<T as Config>::Fungibles as Inspect<<T as pezframe_system::Config>::AccountId>>::AssetId;
|
||||
|
||||
// Type aliases used for interaction with `OnChargeAssetTransaction`.
|
||||
/// Balance type alias.
|
||||
pub(crate) type ChargeAssetBalanceOf<T> =
|
||||
<<T as Config>::OnChargeAssetTransaction as OnChargeAssetTransaction<T>>::Balance;
|
||||
/// Asset id type alias.
|
||||
pub(crate) type ChargeAssetIdOf<T> =
|
||||
<<T as Config>::OnChargeAssetTransaction as OnChargeAssetTransaction<T>>::AssetId;
|
||||
/// Liquidity info type alias.
|
||||
pub(crate) type ChargeAssetLiquidityOf<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(LiquidityInfoOf<T>),
|
||||
/// The initial fee was paid in an asset.
|
||||
Asset(Credit<T::AccountId, T::Fungibles>),
|
||||
}
|
||||
|
||||
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 fungibles instance used to pay for transactions in assets.
|
||||
type Fungibles: Balanced<Self::AccountId>;
|
||||
/// The actual transaction charging logic that charges the fees.
|
||||
type OnChargeAssetTransaction: OnChargeAssetTransaction<Self>;
|
||||
/// The weight information of this pallet.
|
||||
type WeightInfo: WeightInfo;
|
||||
/// Benchmark helper
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
type BenchmarkHelper: BenchmarkHelperTrait<
|
||||
Self::AccountId,
|
||||
<<Self as Config>::Fungibles as Inspect<Self::AccountId>>::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: AssetBalanceOf<T>,
|
||||
tip: AssetBalanceOf<T>,
|
||||
asset_id: Option<ChargeAssetIdOf<T>>,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Require the transactor pay for themselves and maybe include a tip to gain additional priority
|
||||
/// in the queue. Allows paying via both `Currency` as well as `fungibles::Balanced`.
|
||||
///
|
||||
/// 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 via the native currency.
|
||||
#[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<ChargeAssetIdOf<T>>,
|
||||
}
|
||||
|
||||
impl<T: Config> ChargeAssetTxPayment<T>
|
||||
where
|
||||
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
|
||||
AssetBalanceOf<T>: Send + Sync,
|
||||
BalanceOf<T>: Send + Sync + IsType<ChargeAssetBalanceOf<T>>,
|
||||
ChargeAssetIdOf<T>: Send + Sync,
|
||||
Credit<T::AccountId, T::Fungibles>: IsType<ChargeAssetLiquidityOf<T>>,
|
||||
{
|
||||
/// Utility constructor. Used only in client/factory code.
|
||||
pub fn from(tip: BalanceOf<T>, asset_id: Option<ChargeAssetIdOf<T>>) -> Self {
|
||||
Self { tip, asset_id }
|
||||
}
|
||||
|
||||
/// Fee withdrawal logic that dispatches to either `OnChargeAssetTransaction` or
|
||||
/// `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.clone() {
|
||||
T::OnChargeAssetTransaction::withdraw_fee(
|
||||
who,
|
||||
call,
|
||||
info,
|
||||
asset_id,
|
||||
fee.into(),
|
||||
self.tip.into(),
|
||||
)
|
||||
.map(|i| (fee, InitialPayment::Asset(i.into())))
|
||||
} else {
|
||||
<OnChargeTransactionOf<T> as OnChargeTransaction<T>>::withdraw_fee(
|
||||
who, call, info, fee, self.tip,
|
||||
)
|
||||
.map(|i| (fee, InitialPayment::Native(i)))
|
||||
.map_err(|_| -> TransactionValidityError { InvalidTransaction::Payment.into() })
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.clone() {
|
||||
T::OnChargeAssetTransaction::can_withdraw_fee(
|
||||
who,
|
||||
call,
|
||||
info,
|
||||
asset_id,
|
||||
fee.into(),
|
||||
self.tip.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>,
|
||||
// asset_id for the transaction payment
|
||||
asset_id: Option<ChargeAssetIdOf<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>,
|
||||
AssetBalanceOf<T>: Send + Sync,
|
||||
BalanceOf<T>: Send + Sync + From<u64> + IsType<ChargeAssetBalanceOf<T>>,
|
||||
ChargeAssetIdOf<T>: Send + Sync,
|
||||
Credit<T::AccountId, T::Fungibles>: IsType<ChargeAssetLiquidityOf<T>>,
|
||||
<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,
|
||||
) -> Result<
|
||||
(ValidTransaction, Self::Val, <T::RuntimeCall as Dispatchable>::RuntimeOrigin),
|
||||
TransactionValidityError,
|
||||
> {
|
||||
use pezpallet_transaction_payment::ChargeTransactionPayment;
|
||||
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 val = Val::Charge { tip: self.tip, who: who.clone(), fee };
|
||||
let validity = ValidTransaction { priority, ..Default::default() };
|
||||
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,
|
||||
asset_id: self.asset_id.clone(),
|
||||
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, asset_id, extension_weight) = match pre {
|
||||
Pre::Charge { tip, who, initial_payment, asset_id, weight } =>
|
||||
(tip, who, initial_payment, asset_id, weight),
|
||||
Pre::NoCharge { refund } => {
|
||||
// No-op: Refund everything
|
||||
return Ok(refund);
|
||||
},
|
||||
};
|
||||
|
||||
match initial_payment {
|
||||
InitialPayment::Native(liquidity_info) => {
|
||||
// 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);
|
||||
pezpallet_transaction_payment::ChargeTransactionPayment::<T>::post_dispatch_details(
|
||||
pezpallet_transaction_payment::Pre::Charge { tip, who, liquidity_info },
|
||||
info,
|
||||
&actual_post_info,
|
||||
len,
|
||||
result,
|
||||
)?;
|
||||
Ok(unspent_weight)
|
||||
},
|
||||
InitialPayment::Asset(already_withdrawn) => {
|
||||
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, converted_tip) =
|
||||
T::OnChargeAssetTransaction::correct_and_deposit_fee(
|
||||
&who,
|
||||
info,
|
||||
&actual_post_info,
|
||||
actual_fee.into(),
|
||||
tip.into(),
|
||||
already_withdrawn.into(),
|
||||
)?;
|
||||
Pallet::<T>::deposit_event(Event::<T>::AssetTxFeePaid {
|
||||
who,
|
||||
actual_fee: converted_fee,
|
||||
tip: converted_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,257 @@
|
||||
// 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_tx_payment;
|
||||
|
||||
use codec;
|
||||
use pezframe_support::{
|
||||
derive_impl,
|
||||
dispatch::DispatchClass,
|
||||
pezpallet_prelude::*,
|
||||
parameter_types,
|
||||
traits::{AsEnsureOriginWithArg, ConstU32, ConstU64, ConstU8, FindAuthor},
|
||||
weights::{Weight, WeightToFee as WeightToFeeT},
|
||||
ConsensusEngineId,
|
||||
};
|
||||
use pezframe_system as system;
|
||||
use pezframe_system::EnsureRoot;
|
||||
use pezpallet_transaction_payment::FungibleAdapter;
|
||||
use pezsp_runtime::traits::{ConvertInto, SaturatedConversion};
|
||||
|
||||
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,
|
||||
Authorship: pezpallet_authorship,
|
||||
AssetTxPayment: pezpallet_asset_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 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()))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MockTxPaymentWeights;
|
||||
|
||||
impl pezpallet_transaction_payment::WeightInfo for MockTxPaymentWeights {
|
||||
fn charge_transaction_payment() -> Weight {
|
||||
Weight::from_parts(10, 0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive_impl(pezpallet_transaction_payment::config_preludes::TestDefaultConfig)]
|
||||
impl pezpallet_transaction_payment::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type OnChargeTransaction = FungibleAdapter<Balances, ()>;
|
||||
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 = ();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HardcodedAuthor;
|
||||
pub(crate) const BLOCK_AUTHOR: AccountId = 1234;
|
||||
impl FindAuthor<AccountId> for HardcodedAuthor {
|
||||
fn find_author<'a, I>(_: I) -> Option<AccountId>
|
||||
where
|
||||
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
|
||||
{
|
||||
Some(BLOCK_AUTHOR)
|
||||
}
|
||||
}
|
||||
|
||||
impl pezpallet_authorship::Config for Runtime {
|
||||
type FindAuthor = HardcodedAuthor;
|
||||
type EventHandler = ();
|
||||
}
|
||||
|
||||
pub struct CreditToBlockAuthor;
|
||||
impl HandleCredit<AccountId, Assets> for CreditToBlockAuthor {
|
||||
fn handle_credit(credit: Credit<AccountId, Assets>) {
|
||||
if let Some(author) = pezpallet_authorship::Pallet::<Runtime>::author() {
|
||||
// What to do in case paying the author fails (e.g. because `fee < min_balance`)
|
||||
// default: drop the result which will trigger the `OnDrop` of the imbalance.
|
||||
let _ = <Assets as Balanced<AccountId>>::resolve(&author, credit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 Fungibles = Assets;
|
||||
type OnChargeAssetTransaction = FungiblesAdapter<
|
||||
pezpallet_assets::BalanceToAssetBalance<Balances, Runtime, ConvertInto>,
|
||||
CreditToBlockAuthor,
|
||||
>;
|
||||
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, u32, u32> for Helper {
|
||||
fn create_asset_id_parameter(id: u32) -> (u32, u32) {
|
||||
(id.into(), id.into())
|
||||
}
|
||||
|
||||
fn setup_balances_and_pool(asset_id: u32, account: u64) {
|
||||
use pezframe_support::{assert_ok, traits::fungibles::Mutate};
|
||||
use pezsp_runtime::traits::StaticLookup;
|
||||
let min_balance = 1;
|
||||
assert_ok!(Assets::force_create(
|
||||
RuntimeOrigin::root(),
|
||||
asset_id.into(),
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
|
||||
// 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);
|
||||
|
||||
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_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, account), balance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
// 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 codec::FullCodec;
|
||||
use core::{fmt::Debug, marker::PhantomData};
|
||||
use pezframe_support::{
|
||||
traits::{
|
||||
fungibles::{Balanced, Credit, Inspect},
|
||||
tokens::{
|
||||
Balance, ConversionToAssetBalance, Fortitude::Polite, Precision::Exact,
|
||||
Preservation::Protect,
|
||||
},
|
||||
},
|
||||
unsigned::TransactionValidityError,
|
||||
};
|
||||
use scale_info::TypeInfo;
|
||||
use pezsp_runtime::{
|
||||
traits::{DispatchInfoOf, MaybeSerializeDeserialize, One, PostDispatchInfoOf},
|
||||
transaction_validity::InvalidTransaction,
|
||||
};
|
||||
|
||||
/// 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: FullCodec
|
||||
+ DecodeWithMemTracking
|
||||
+ Clone
|
||||
+ MaybeSerializeDeserialize
|
||||
+ Debug
|
||||
+ Default
|
||||
+ Eq
|
||||
+ TypeInfo;
|
||||
/// The type used to store the intermediate values between pre- and post-dispatch.
|
||||
type LiquidityInfo;
|
||||
|
||||
/// Before the transaction is executed the payment of the transaction fees needs to be secured.
|
||||
///
|
||||
/// 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,
|
||||
call: &T::RuntimeCall,
|
||||
dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
asset_id: Self::AssetId,
|
||||
fee: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
) -> Result<(), TransactionValidityError>;
|
||||
|
||||
/// After the transaction was executed the actual fee can be calculated.
|
||||
/// This function should refund any overpaid fees and optionally deposit
|
||||
/// the corrected amount.
|
||||
///
|
||||
/// Note: The `fee` already includes the `tip`.
|
||||
///
|
||||
/// Returns the fee and tip in the asset used for payment as (fee, tip).
|
||||
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,
|
||||
already_withdrawn: Self::LiquidityInfo,
|
||||
) -> Result<(AssetBalanceOf<T>, AssetBalanceOf<T>), TransactionValidityError>;
|
||||
}
|
||||
|
||||
/// Allows specifying what to do with the withdrawn asset fees.
|
||||
pub trait HandleCredit<AccountId, B: Balanced<AccountId>> {
|
||||
/// Implement to determine what to do with the withdrawn asset fees.
|
||||
/// Default for `CreditOf` from the assets pallet is to burn and
|
||||
/// decrease total issuance.
|
||||
fn handle_credit(credit: Credit<AccountId, B>);
|
||||
}
|
||||
|
||||
/// Default implementation that just drops the credit according to the `OnDrop` in the underlying
|
||||
/// imbalance type.
|
||||
impl<A, B: Balanced<A>> HandleCredit<A, B> for () {
|
||||
fn handle_credit(_credit: Credit<A, B>) {}
|
||||
}
|
||||
|
||||
/// Implements the asset transaction for a balance to asset converter (implementing
|
||||
/// [`ConversionToAssetBalance`]) and a credit handler (implementing [`HandleCredit`]).
|
||||
///
|
||||
/// The credit handler is given the complete fee in terms of the asset used for the transaction.
|
||||
pub struct FungiblesAdapter<CON, HC>(PhantomData<(CON, HC)>);
|
||||
|
||||
/// Default implementation for a runtime instantiating this pallet, a balance to asset converter and
|
||||
/// a credit handler.
|
||||
impl<T, CON, HC> OnChargeAssetTransaction<T> for FungiblesAdapter<CON, HC>
|
||||
where
|
||||
T: Config,
|
||||
CON: ConversionToAssetBalance<BalanceOf<T>, AssetIdOf<T>, AssetBalanceOf<T>>,
|
||||
HC: HandleCredit<T::AccountId, T::Fungibles>,
|
||||
AssetIdOf<T>: FullCodec + Clone + MaybeSerializeDeserialize + Debug + Default + Eq + TypeInfo,
|
||||
{
|
||||
type Balance = BalanceOf<T>;
|
||||
type AssetId = AssetIdOf<T>;
|
||||
type LiquidityInfo = Credit<T::AccountId, T::Fungibles>;
|
||||
|
||||
/// Withdraw the predicted fee from the transaction origin.
|
||||
///
|
||||
/// Note: The `fee` already includes the `tip`.
|
||||
fn withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
_call: &T::RuntimeCall,
|
||||
_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
asset_id: Self::AssetId,
|
||||
fee: Self::Balance,
|
||||
_tip: Self::Balance,
|
||||
) -> Result<Self::LiquidityInfo, TransactionValidityError> {
|
||||
// We don't know the precision of the underlying asset. Because the converted fee could be
|
||||
// less than one (e.g. 0.5) but gets rounded down by integer division we introduce a minimum
|
||||
// fee.
|
||||
let min_converted_fee = if fee.is_zero() { Zero::zero() } else { One::one() };
|
||||
let converted_fee = CON::to_asset_balance(fee, asset_id.clone())
|
||||
.map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment))?
|
||||
.max(min_converted_fee);
|
||||
let can_withdraw = <T::Fungibles as Inspect<T::AccountId>>::can_withdraw(
|
||||
asset_id.clone(),
|
||||
who,
|
||||
converted_fee,
|
||||
);
|
||||
if can_withdraw != WithdrawConsequence::Success {
|
||||
return Err(InvalidTransaction::Payment.into());
|
||||
}
|
||||
<T::Fungibles as Balanced<T::AccountId>>::withdraw(
|
||||
asset_id,
|
||||
who,
|
||||
converted_fee,
|
||||
Exact,
|
||||
Protect,
|
||||
Polite,
|
||||
)
|
||||
.map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment))
|
||||
}
|
||||
|
||||
/// Ensure payment of the transaction fees can be withdrawn.
|
||||
///
|
||||
/// Note: The `fee` already includes the `tip`.
|
||||
fn can_withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
_call: &T::RuntimeCall,
|
||||
_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
asset_id: Self::AssetId,
|
||||
fee: Self::Balance,
|
||||
_tip: Self::Balance,
|
||||
) -> Result<(), TransactionValidityError> {
|
||||
// We don't know the precision of the underlying asset. Because the converted fee could be
|
||||
// less than one (e.g. 0.5) but gets rounded down by integer division we introduce a minimum
|
||||
// fee.
|
||||
let min_converted_fee = if fee.is_zero() { Zero::zero() } else { One::one() };
|
||||
let converted_fee = CON::to_asset_balance(fee, asset_id.clone())
|
||||
.map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment))?
|
||||
.max(min_converted_fee);
|
||||
let can_withdraw =
|
||||
<T::Fungibles as Inspect<T::AccountId>>::can_withdraw(asset_id, who, converted_fee);
|
||||
if can_withdraw != WithdrawConsequence::Success {
|
||||
return Err(InvalidTransaction::Payment.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Hand the fee and the tip over to the `[HandleCredit]` implementation.
|
||||
/// Since the predicted fee might have been too high, parts of the fee may be refunded.
|
||||
///
|
||||
/// Note: The `corrected_fee` already includes the `tip`.
|
||||
///
|
||||
/// Returns the fee and tip in the asset used for payment as (fee, tip).
|
||||
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,
|
||||
paid: Self::LiquidityInfo,
|
||||
) -> Result<(AssetBalanceOf<T>, AssetBalanceOf<T>), TransactionValidityError> {
|
||||
let min_converted_fee = if corrected_fee.is_zero() { Zero::zero() } else { One::one() };
|
||||
// Convert the corrected fee and tip into the asset used for payment.
|
||||
let converted_fee = CON::to_asset_balance(corrected_fee, paid.asset())
|
||||
.map_err(|_| -> TransactionValidityError { InvalidTransaction::Payment.into() })?
|
||||
.max(min_converted_fee);
|
||||
let converted_tip = CON::to_asset_balance(tip, paid.asset())
|
||||
.map_err(|_| -> TransactionValidityError { InvalidTransaction::Payment.into() })?;
|
||||
|
||||
// Calculate how much refund we should return.
|
||||
let (final_fee, refund) = paid.split(converted_fee);
|
||||
// Refund to the account that paid the fees. If this fails, the account might have dropped
|
||||
// below the existential balance. In that case we don't refund anything.
|
||||
let _ = <T::Fungibles as Balanced<T::AccountId>>::resolve(who, refund);
|
||||
// Handle the final fee, e.g. by transferring to the block author or burning.
|
||||
HC::handle_credit(final_fee);
|
||||
Ok((converted_fee, converted_tip))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,651 @@
|
||||
// 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::{fungibles::Mutate, 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() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_payment_in_native_possible() {
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(Weight::from_parts(5, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
let len = 10;
|
||||
let mut info = info_from_weight(Weight::from_parts(5, 0));
|
||||
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::from_parts(100, 0));
|
||||
let ext = ChargeAssetTxPayment::<Runtime>::from(5 /* tipped */, None);
|
||||
info.extension_weight = ext.weight(CALL);
|
||||
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::from_parts(50, 0);
|
||||
// The extension weight refund should be taken into account in `post_dispatch`.
|
||||
let post_info = post_info_from_weight(call_actual_weight.saturating_add(
|
||||
ChargeAssetTxPayment::<Runtime>::from(5 /* tipped */, None).weight(CALL),
|
||||
));
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info,
|
||||
&post_info,
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
assert_eq!(
|
||||
post_info.actual_weight,
|
||||
Some(
|
||||
call_actual_weight
|
||||
.saturating_add(MockWeights::charge_asset_tx_payment_native())
|
||||
)
|
||||
);
|
||||
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 = 100;
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
let weight = 5;
|
||||
let len = 10;
|
||||
// we convert the from weight to fee based on the ratio between asset min balance and
|
||||
// existential deposit
|
||||
let fee = (base_weight + weight + len as u64) * min_balance / ExistentialDeposit::get();
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_weight(Weight::from_parts(weight, 0)),
|
||||
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);
|
||||
assert_eq!(Assets::balance(asset_id, BLOCK_AUTHOR), 0);
|
||||
|
||||
System::assert_has_event(RuntimeEvent::Assets(pezpallet_assets::Event::Withdrawn {
|
||||
asset_id,
|
||||
who: caller,
|
||||
amount: fee,
|
||||
}));
|
||||
|
||||
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);
|
||||
// check that the block author gets rewarded
|
||||
assert_eq!(Assets::balance(asset_id, BLOCK_AUTHOR), fee);
|
||||
|
||||
System::assert_has_event(RuntimeEvent::Assets(pezpallet_assets::Event::Deposited {
|
||||
asset_id,
|
||||
who: BLOCK_AUTHOR,
|
||||
amount: fee,
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
#[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(|| {
|
||||
// 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 = 100;
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
let weight = 5;
|
||||
let len = 10;
|
||||
// we convert the from weight to fee based on the ratio between asset min balance and
|
||||
// existential deposit
|
||||
let fee = (base_weight + weight + len as u64) * min_balance / ExistentialDeposit::get();
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_weight(Weight::from_parts(weight, 0)),
|
||||
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);
|
||||
assert_eq!(Assets::balance(asset_id, BLOCK_AUTHOR), 0);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info_from_weight(Weight::from_parts(weight, 0)),
|
||||
&post_info_from_pays(Pays::No),
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
// caller should be refunded
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
// check that the block author did not get rewarded
|
||||
assert_eq!(Assets::balance(asset_id, BLOCK_AUTHOR), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asset_transaction_payment_with_tip_and_refund() {
|
||||
let base_weight = 5;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(100)
|
||||
.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 = 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 = 100;
|
||||
let tip = 5;
|
||||
let ext = ChargeAssetTxPayment::<Runtime>::from(tip, Some(asset_id));
|
||||
let ext_weight = ext.weight(CALL);
|
||||
let len = 10;
|
||||
// we convert the from weight to fee based on the ratio between asset min balance and
|
||||
// existential deposit
|
||||
let fee_with_tip = (base_weight + weight + ext_weight.ref_time() + len as u64 + tip) *
|
||||
min_balance / ExistentialDeposit::get();
|
||||
let mut info = info_from_weight(Weight::from_parts(weight, 0));
|
||||
info.extension_weight = ext_weight;
|
||||
let (pre, _) =
|
||||
ext.validate_and_prepare(Some(caller).into(), CALL, &info, len, 0).unwrap();
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee_with_tip);
|
||||
|
||||
System::assert_has_event(RuntimeEvent::Assets(pezpallet_assets::Event::Withdrawn {
|
||||
asset_id,
|
||||
who: caller,
|
||||
amount: fee_with_tip,
|
||||
}));
|
||||
|
||||
let final_weight = 50;
|
||||
let mut post_info = post_info_from_weight(Weight::from_parts(final_weight, 0));
|
||||
post_info
|
||||
.actual_weight
|
||||
.as_mut()
|
||||
.map(|w| w.saturating_accrue(MockWeights::charge_asset_tx_payment_asset()));
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch_details(
|
||||
pre,
|
||||
&info,
|
||||
&post_info,
|
||||
len,
|
||||
&Ok(()),
|
||||
));
|
||||
let final_fee = fee_with_tip -
|
||||
(weight - final_weight + ext_weight.ref_time() -
|
||||
MockWeights::charge_asset_tx_payment_asset().ref_time()) *
|
||||
min_balance / ExistentialDeposit::get();
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - (final_fee));
|
||||
assert_eq!(Assets::balance(asset_id, BLOCK_AUTHOR), final_fee);
|
||||
|
||||
System::assert_has_event(RuntimeEvent::Assets(pezpallet_assets::Event::Deposited {
|
||||
asset_id,
|
||||
who: caller,
|
||||
amount: fee_with_tip - final_fee,
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payment_from_account_with_only_assets() {
|
||||
let base_weight = 5;
|
||||
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 = 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 = 333;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 100;
|
||||
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;
|
||||
// we convert the from weight to fee based on the ratio between asset min balance and
|
||||
// existential deposit
|
||||
let fee = (base_weight + weight + len as u64) * min_balance / ExistentialDeposit::get();
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_weight(Weight::from_parts(weight, 0)),
|
||||
len,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(Balances::free_balance(caller), 0);
|
||||
// check that fee was charged in the given asset
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee);
|
||||
|
||||
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);
|
||||
assert_eq!(Balances::free_balance(caller), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payment_only_with_existing_sufficient_asset() {
|
||||
let base_weight = 5;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(100)
|
||||
.base_weight(Weight::from_parts(base_weight, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
let asset_id = 1;
|
||||
let caller = 1;
|
||||
let weight = 5;
|
||||
let len = 10;
|
||||
// pre_dispatch fails for non-existent asset
|
||||
assert!(ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_weight(Weight::from_parts(weight, 0)),
|
||||
len,
|
||||
0,
|
||||
)
|
||||
.is_err());
|
||||
|
||||
// create the non-sufficient asset
|
||||
let min_balance = 2;
|
||||
assert_ok!(Assets::force_create(
|
||||
RuntimeOrigin::root(),
|
||||
asset_id.into(),
|
||||
42, /* owner */
|
||||
false, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
// pre_dispatch fails for non-sufficient asset
|
||||
assert!(ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_weight(Weight::from_parts(weight, 0)),
|
||||
len,
|
||||
0,
|
||||
)
|
||||
.is_err());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_fee_is_never_zero_if_input_fee_is_not() {
|
||||
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 = 1;
|
||||
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 = 100;
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
let weight = 1;
|
||||
let len = 1;
|
||||
// we convert the from weight to fee based on the ratio between asset min balance and
|
||||
// existential deposit
|
||||
let fee = (base_weight + weight + len as u64) * min_balance / ExistentialDeposit::get();
|
||||
// naive fee calculation would round down to zero
|
||||
assert_eq!(fee, 0);
|
||||
{
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_pays(Pays::No),
|
||||
len,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
// `Pays::No` still implies 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);
|
||||
}
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.validate_and_prepare(
|
||||
Some(caller).into(),
|
||||
CALL,
|
||||
&info_from_weight(Weight::from_parts(weight, 0)),
|
||||
len,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
// check that at least one coin was charged in the given asset
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - 1);
|
||||
|
||||
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 - 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[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 = 100;
|
||||
assert_ok!(Assets::mint_into(asset_id.into(), &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
let weight = 1;
|
||||
let len = 1;
|
||||
// we convert the from weight to fee based on the ratio between asset min balance and
|
||||
// existential deposit
|
||||
let fee = (base_weight + weight + len as u64) * min_balance / ExistentialDeposit::get();
|
||||
// calculated fee is greater than 0
|
||||
assert!(fee > 0);
|
||||
let (pre, _) = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.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 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,146 @@
|
||||
// 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_tx_payment`
|
||||
//!
|
||||
//! THIS FILE WAS AUTO-GENERATED USING THE BIZINIKIWI BENCHMARK CLI VERSION 32.0.0
|
||||
//! DATE: 2024-03-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
|
||||
//! WORST CASE MAP SIZE: `1000000`
|
||||
//! HOSTNAME: `runner-bn-ce5rx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz`
|
||||
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024`
|
||||
|
||||
// Executed Command:
|
||||
// ./target/production/bizinikiwi-node
|
||||
// benchmark
|
||||
// pallet
|
||||
// --chain=dev
|
||||
// --steps=50
|
||||
// --repeat=20
|
||||
// --pallet=pezpallet_asset_tx_payment
|
||||
// --no-storage-info
|
||||
// --no-median-slopes
|
||||
// --no-min-squares
|
||||
// --extrinsic=*
|
||||
// --wasm-execution=compiled
|
||||
// --heap-pages=4096
|
||||
// --output=./bizinikiwi/pezframe/transaction-payment/asset-tx-payment/src/weights.rs
|
||||
// --header=./bizinikiwi/HEADER-APACHE2
|
||||
// --template=./bizinikiwi/.maintain/frame-weight-template.hbs
|
||||
|
||||
#![cfg_attr(rustfmt, rustfmt_skip)]
|
||||
#![allow(unused_parens)]
|
||||
#![allow(unused_imports)]
|
||||
#![allow(missing_docs)]
|
||||
|
||||
use pezframe_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
|
||||
use core::marker::PhantomData;
|
||||
|
||||
/// Weight functions needed for `pezpallet_asset_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_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: 542_000 picoseconds.
|
||||
Weight::from_parts(597_000, 0)
|
||||
}
|
||||
/// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0)
|
||||
/// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`)
|
||||
/// Storage: `Authorship::Author` (r:1 w:0)
|
||||
/// Proof: `Authorship::Author` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`)
|
||||
/// Storage: `System::Digest` (r:1 w:0)
|
||||
/// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
fn charge_asset_tx_payment_native() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `248`
|
||||
// Estimated: `1733`
|
||||
// Minimum execution time: 33_162_000 picoseconds.
|
||||
Weight::from_parts(34_716_000, 1733)
|
||||
.saturating_add(T::DbWeight::get().reads(3_u64))
|
||||
}
|
||||
/// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0)
|
||||
/// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`)
|
||||
/// 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:1 w:1)
|
||||
/// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`)
|
||||
/// Storage: `Authorship::Author` (r:1 w:0)
|
||||
/// Proof: `Authorship::Author` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`)
|
||||
/// Storage: `System::Digest` (r:1 w:0)
|
||||
/// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
fn charge_asset_tx_payment_asset() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `747`
|
||||
// Estimated: `3675`
|
||||
// Minimum execution time: 44_230_000 picoseconds.
|
||||
Weight::from_parts(45_297_000, 3675)
|
||||
.saturating_add(T::DbWeight::get().reads(5_u64))
|
||||
.saturating_add(T::DbWeight::get().writes(2_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: 542_000 picoseconds.
|
||||
Weight::from_parts(597_000, 0)
|
||||
}
|
||||
/// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0)
|
||||
/// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`)
|
||||
/// Storage: `Authorship::Author` (r:1 w:0)
|
||||
/// Proof: `Authorship::Author` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`)
|
||||
/// Storage: `System::Digest` (r:1 w:0)
|
||||
/// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
fn charge_asset_tx_payment_native() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `248`
|
||||
// Estimated: `1733`
|
||||
// Minimum execution time: 33_162_000 picoseconds.
|
||||
Weight::from_parts(34_716_000, 1733)
|
||||
.saturating_add(RocksDbWeight::get().reads(3_u64))
|
||||
}
|
||||
/// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0)
|
||||
/// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`)
|
||||
/// 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:1 w:1)
|
||||
/// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`)
|
||||
/// Storage: `Authorship::Author` (r:1 w:0)
|
||||
/// Proof: `Authorship::Author` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`)
|
||||
/// Storage: `System::Digest` (r:1 w:0)
|
||||
/// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
fn charge_asset_tx_payment_asset() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `747`
|
||||
// Estimated: `3675`
|
||||
// Minimum execution time: 44_230_000 picoseconds.
|
||||
Weight::from_parts(45_297_000, 3675)
|
||||
.saturating_add(RocksDbWeight::get().reads(5_u64))
|
||||
.saturating_add(RocksDbWeight::get().writes(2_u64))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user