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,59 @@
|
||||
[package]
|
||||
name = "pezpallet-transaction-payment"
|
||||
version = "28.0.0"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license = "Apache-2.0"
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
description = "FRAME pallet to manage transaction payments"
|
||||
readme = "README.md"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
codec = { features = ["derive"], workspace = true }
|
||||
pezframe-benchmarking = { optional = true, workspace = true }
|
||||
pezframe-support = { workspace = true }
|
||||
pezframe-system = { workspace = true }
|
||||
log = { workspace = true }
|
||||
scale-info = { features = ["derive"], workspace = true }
|
||||
serde = { optional = true, workspace = true, default-features = true }
|
||||
pezsp-io = { workspace = true }
|
||||
pezsp-runtime = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pezpallet-balances = { workspace = true, default-features = true }
|
||||
serde_json = { workspace = true, default-features = true }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"codec/std",
|
||||
"pezframe-benchmarking?/std",
|
||||
"pezframe-support/std",
|
||||
"pezframe-system/std",
|
||||
"log/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-balances/runtime-benchmarks",
|
||||
"pezsp-io/runtime-benchmarks",
|
||||
"pezsp-runtime/runtime-benchmarks",
|
||||
]
|
||||
try-runtime = [
|
||||
"pezframe-support/try-runtime",
|
||||
"pezframe-system/try-runtime",
|
||||
"pezpallet-balances/try-runtime",
|
||||
"pezsp-runtime/try-runtime",
|
||||
]
|
||||
@@ -0,0 +1,16 @@
|
||||
# Transaction Payment Pallet
|
||||
|
||||
This pallet provides the basic logic needed to pay the absolute minimum amount needed for a
|
||||
transaction to be included. This includes:
|
||||
- _weight fee_: A fee proportional to amount of weight a transaction consumes.
|
||||
- _length fee_: A fee proportional to the encoded length of the transaction.
|
||||
- _tip_: An optional tip. Tip increases the priority of the transaction, giving it a higher
|
||||
chance to be included by the transaction queue.
|
||||
|
||||
Additionally, this pallet allows one to configure:
|
||||
- The mapping between one unit of weight to one unit of fee via [`Config::WeightToFee`].
|
||||
- A means of updating the fee for the next block, via defining a multiplier, based on the
|
||||
final state of the chain at the end of the previous block. This can be configured via
|
||||
[`Config::FeeMultiplierUpdate`]
|
||||
|
||||
License: Apache-2.0
|
||||
@@ -0,0 +1,65 @@
|
||||
[package]
|
||||
name = "pezpallet-asset-conversion-tx-payment"
|
||||
version = "10.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 by converting them to native assets."
|
||||
readme = "README.md"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
# Bizinikiwi dependencies
|
||||
codec = { features = ["derive"], workspace = true }
|
||||
pezframe-benchmarking = { optional = true, workspace = true }
|
||||
pezframe-support = { workspace = true }
|
||||
pezframe-system = { workspace = true }
|
||||
pezpallet-asset-conversion = { workspace = true }
|
||||
pezpallet-transaction-payment = { workspace = true }
|
||||
scale-info = { features = ["derive"], workspace = true }
|
||||
pezsp-runtime = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pezpallet-assets = { workspace = true, default-features = true }
|
||||
pezpallet-balances = { workspace = true, default-features = true }
|
||||
pezsp-io = { workspace = true, default-features = true }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"codec/std",
|
||||
"pezframe-benchmarking?/std",
|
||||
"pezframe-support/std",
|
||||
"pezframe-system/std",
|
||||
"pezpallet-asset-conversion/std",
|
||||
"pezpallet-transaction-payment/std",
|
||||
"scale-info/std",
|
||||
"pezsp-runtime/std",
|
||||
]
|
||||
runtime-benchmarks = [
|
||||
"pezframe-benchmarking/runtime-benchmarks",
|
||||
"pezframe-support/runtime-benchmarks",
|
||||
"pezframe-system/runtime-benchmarks",
|
||||
"pezpallet-asset-conversion/runtime-benchmarks",
|
||||
"pezpallet-assets/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-asset-conversion/try-runtime",
|
||||
"pezpallet-assets/try-runtime",
|
||||
"pezpallet-balances/try-runtime",
|
||||
"pezpallet-transaction-payment/try-runtime",
|
||||
"pezsp-runtime/try-runtime",
|
||||
]
|
||||
@@ -0,0 +1,21 @@
|
||||
# pezpallet-asset-conversion-tx-payment
|
||||
|
||||
## Asset Conversion 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 [`AssetConversionAdapter`] (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
|
||||
+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))
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
[package]
|
||||
name = "pezpallet-transaction-payment-rpc"
|
||||
version = "30.0.0"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license = "Apache-2.0"
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
description = "RPC interface for the transaction payment pallet."
|
||||
readme = "README.md"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
codec = { workspace = true, default-features = true }
|
||||
jsonrpsee = { features = [
|
||||
"client-core",
|
||||
"macros",
|
||||
"server-core",
|
||||
], workspace = true }
|
||||
pezpallet-transaction-payment-rpc-runtime-api = { workspace = true, default-features = true }
|
||||
pezsp-api = { workspace = true, default-features = true }
|
||||
pezsp-blockchain = { workspace = true, default-features = true }
|
||||
pezsp-core = { workspace = true, default-features = true }
|
||||
pezsp-rpc = { workspace = true, default-features = true }
|
||||
pezsp-runtime = { workspace = true, default-features = true }
|
||||
pezsp-weights = { workspace = true, default-features = true }
|
||||
|
||||
[features]
|
||||
runtime-benchmarks = [
|
||||
"pezpallet-transaction-payment-rpc-runtime-api/runtime-benchmarks",
|
||||
"pezsp-api/runtime-benchmarks",
|
||||
"pezsp-blockchain/runtime-benchmarks",
|
||||
"pezsp-runtime/runtime-benchmarks",
|
||||
]
|
||||
@@ -0,0 +1,3 @@
|
||||
RPC interface for the transaction payment pallet.
|
||||
|
||||
License: Apache-2.0
|
||||
@@ -0,0 +1,38 @@
|
||||
[package]
|
||||
name = "pezpallet-transaction-payment-rpc-runtime-api"
|
||||
version = "28.0.0"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license = "Apache-2.0"
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
description = "RPC runtime API for transaction payment FRAME pallet"
|
||||
readme = "README.md"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
codec = { features = ["derive"], workspace = true }
|
||||
pezpallet-transaction-payment = { workspace = true }
|
||||
pezsp-api = { workspace = true }
|
||||
pezsp-runtime = { workspace = true }
|
||||
pezsp-weights = { workspace = true }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"codec/std",
|
||||
"pezpallet-transaction-payment/std",
|
||||
"pezsp-api/std",
|
||||
"pezsp-runtime/std",
|
||||
"pezsp-weights/std",
|
||||
]
|
||||
runtime-benchmarks = [
|
||||
"pezpallet-transaction-payment/runtime-benchmarks",
|
||||
"pezsp-api/runtime-benchmarks",
|
||||
"pezsp-runtime/runtime-benchmarks",
|
||||
]
|
||||
@@ -0,0 +1,3 @@
|
||||
Runtime API definition for transaction payment pallet.
|
||||
|
||||
License: Apache-2.0
|
||||
@@ -0,0 +1,56 @@
|
||||
// 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.
|
||||
|
||||
//! Runtime API definition for transaction payment pallet.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use codec::Codec;
|
||||
use pezsp_runtime::traits::MaybeDisplay;
|
||||
|
||||
pub use pezpallet_transaction_payment::{FeeDetails, InclusionFee, RuntimeDispatchInfo};
|
||||
|
||||
pezsp_api::decl_runtime_apis! {
|
||||
#[api_version(4)]
|
||||
pub trait TransactionPaymentApi<Balance> where
|
||||
Balance: Codec + MaybeDisplay,
|
||||
{
|
||||
fn query_info(uxt: Block::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance>;
|
||||
fn query_fee_details(uxt: Block::Extrinsic, len: u32) -> FeeDetails<Balance>;
|
||||
fn query_weight_to_fee(weight: pezsp_weights::Weight) -> Balance;
|
||||
fn query_length_to_fee(length: u32) -> Balance;
|
||||
}
|
||||
|
||||
#[api_version(3)]
|
||||
pub trait TransactionPaymentCallApi<Balance, Call>
|
||||
where
|
||||
Balance: Codec + MaybeDisplay,
|
||||
Call: Codec,
|
||||
{
|
||||
/// Query information of a dispatch class, weight, and fee of a given encoded `Call`.
|
||||
fn query_call_info(call: Call, len: u32) -> RuntimeDispatchInfo<Balance>;
|
||||
|
||||
/// Query fee details of a given encoded `Call`.
|
||||
fn query_call_fee_details(call: Call, len: u32) -> FeeDetails<Balance>;
|
||||
|
||||
/// Query the output of the current `WeightToFee` given some input.
|
||||
fn query_weight_to_fee(weight: pezsp_weights::Weight) -> Balance;
|
||||
|
||||
/// Query the output of the current `LengthToFee` given some input.
|
||||
fn query_length_to_fee(length: u32) -> Balance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// 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.
|
||||
|
||||
//! RPC interface for the transaction payment pallet.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use codec::{Codec, Decode};
|
||||
use jsonrpsee::{
|
||||
core::RpcResult,
|
||||
proc_macros::rpc,
|
||||
types::{
|
||||
error::{ErrorCode, ErrorObject},
|
||||
ErrorObjectOwned,
|
||||
},
|
||||
};
|
||||
use pezpallet_transaction_payment_rpc_runtime_api::{FeeDetails, InclusionFee, RuntimeDispatchInfo};
|
||||
use pezsp_api::ProvideRuntimeApi;
|
||||
use pezsp_blockchain::HeaderBackend;
|
||||
use pezsp_core::Bytes;
|
||||
use pezsp_rpc::number::NumberOrHex;
|
||||
use pezsp_runtime::traits::{Block as BlockT, MaybeDisplay};
|
||||
|
||||
pub use pezpallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi as TransactionPaymentRuntimeApi;
|
||||
|
||||
#[rpc(client, server)]
|
||||
pub trait TransactionPaymentApi<BlockHash, ResponseType> {
|
||||
#[method(name = "payment_queryInfo")]
|
||||
fn query_info(&self, encoded_xt: Bytes, at: Option<BlockHash>) -> RpcResult<ResponseType>;
|
||||
|
||||
#[method(name = "payment_queryFeeDetails")]
|
||||
fn query_fee_details(
|
||||
&self,
|
||||
encoded_xt: Bytes,
|
||||
at: Option<BlockHash>,
|
||||
) -> RpcResult<FeeDetails<NumberOrHex>>;
|
||||
}
|
||||
|
||||
/// Provides RPC methods to query a dispatchable's class, weight and fee.
|
||||
pub struct TransactionPayment<C, P> {
|
||||
/// Shared reference to the client.
|
||||
client: Arc<C>,
|
||||
_marker: std::marker::PhantomData<P>,
|
||||
}
|
||||
|
||||
impl<C, P> TransactionPayment<C, P> {
|
||||
/// Creates a new instance of the TransactionPayment Rpc helper.
|
||||
pub fn new(client: Arc<C>) -> Self {
|
||||
Self { client, _marker: Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Error type of this RPC api.
|
||||
pub enum Error {
|
||||
/// The transaction was not decodable.
|
||||
DecodeError,
|
||||
/// The call to runtime failed.
|
||||
RuntimeError,
|
||||
}
|
||||
|
||||
impl From<Error> for i32 {
|
||||
fn from(e: Error) -> i32 {
|
||||
match e {
|
||||
Error::RuntimeError => 1,
|
||||
Error::DecodeError => 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, Block, Balance>
|
||||
TransactionPaymentApiServer<
|
||||
<Block as BlockT>::Hash,
|
||||
RuntimeDispatchInfo<Balance, pezsp_weights::Weight>,
|
||||
> for TransactionPayment<C, Block>
|
||||
where
|
||||
Block: BlockT,
|
||||
C: ProvideRuntimeApi<Block> + HeaderBackend<Block> + Send + Sync + 'static,
|
||||
C::Api: TransactionPaymentRuntimeApi<Block, Balance>,
|
||||
Balance: Codec + MaybeDisplay + Copy + TryInto<NumberOrHex> + Send + Sync + 'static,
|
||||
{
|
||||
fn query_info(
|
||||
&self,
|
||||
encoded_xt: Bytes,
|
||||
at: Option<Block::Hash>,
|
||||
) -> RpcResult<RuntimeDispatchInfo<Balance, pezsp_weights::Weight>> {
|
||||
let api = self.client.runtime_api();
|
||||
let at_hash = at.unwrap_or_else(|| self.client.info().best_hash);
|
||||
|
||||
let encoded_len = encoded_xt.len() as u32;
|
||||
|
||||
let uxt: Block::Extrinsic = Decode::decode(&mut &*encoded_xt).map_err(|e| {
|
||||
ErrorObject::owned(
|
||||
Error::DecodeError.into(),
|
||||
"Unable to query dispatch info.",
|
||||
Some(format!("{:?}", e)),
|
||||
)
|
||||
})?;
|
||||
|
||||
fn map_err(error: impl ToString, desc: &'static str) -> ErrorObjectOwned {
|
||||
ErrorObject::owned(Error::RuntimeError.into(), desc, Some(error.to_string()))
|
||||
}
|
||||
|
||||
let res = api
|
||||
.query_info(at_hash, uxt, encoded_len)
|
||||
.map_err(|e| map_err(e, "Unable to query dispatch info."))?;
|
||||
|
||||
Ok(RuntimeDispatchInfo {
|
||||
weight: res.weight,
|
||||
class: res.class,
|
||||
partial_fee: res.partial_fee,
|
||||
})
|
||||
}
|
||||
|
||||
fn query_fee_details(
|
||||
&self,
|
||||
encoded_xt: Bytes,
|
||||
at: Option<Block::Hash>,
|
||||
) -> RpcResult<FeeDetails<NumberOrHex>> {
|
||||
let api = self.client.runtime_api();
|
||||
let at_hash = at.unwrap_or_else(|| self.client.info().best_hash);
|
||||
|
||||
let encoded_len = encoded_xt.len() as u32;
|
||||
|
||||
let uxt: Block::Extrinsic = Decode::decode(&mut &*encoded_xt).map_err(|e| {
|
||||
ErrorObject::owned(
|
||||
Error::DecodeError.into(),
|
||||
"Unable to query fee details.",
|
||||
Some(format!("{:?}", e)),
|
||||
)
|
||||
})?;
|
||||
let fee_details = api.query_fee_details(at_hash, uxt, encoded_len).map_err(|e| {
|
||||
ErrorObject::owned(
|
||||
Error::RuntimeError.into(),
|
||||
"Unable to query fee details.",
|
||||
Some(e.to_string()),
|
||||
)
|
||||
})?;
|
||||
|
||||
let try_into_rpc_balance = |value: Balance| {
|
||||
value.try_into().map_err(|_| {
|
||||
ErrorObject::owned(
|
||||
ErrorCode::InvalidParams.code(),
|
||||
format!("{} doesn't fit in NumberOrHex representation", value),
|
||||
None::<()>,
|
||||
)
|
||||
})
|
||||
};
|
||||
|
||||
Ok(FeeDetails {
|
||||
inclusion_fee: if let Some(inclusion_fee) = fee_details.inclusion_fee {
|
||||
Some(InclusionFee {
|
||||
base_fee: try_into_rpc_balance(inclusion_fee.base_fee)?,
|
||||
len_fee: try_into_rpc_balance(inclusion_fee.len_fee)?,
|
||||
adjusted_weight_fee: try_into_rpc_balance(inclusion_fee.adjusted_weight_fee)?,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
},
|
||||
tip: Default::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
[package]
|
||||
name = "pezpallet-skip-feeless-payment"
|
||||
version = "3.0.0"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
description = "Pallet to skip payments for calls annotated with `feeless_if` if the respective conditions are satisfied."
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
# Bizinikiwi dependencies
|
||||
pezsp-runtime = { workspace = true }
|
||||
|
||||
pezframe-support = { workspace = true }
|
||||
pezframe-system = { workspace = true }
|
||||
|
||||
# Other dependencies
|
||||
codec = { features = ["derive"], workspace = true }
|
||||
scale-info = { features = ["derive"], workspace = true }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"codec/std",
|
||||
"pezframe-support/std",
|
||||
"pezframe-system/std",
|
||||
"scale-info/std",
|
||||
"pezsp-runtime/std",
|
||||
]
|
||||
runtime-benchmarks = [
|
||||
"pezframe-support/runtime-benchmarks",
|
||||
"pezframe-system/runtime-benchmarks",
|
||||
"pezsp-runtime/runtime-benchmarks",
|
||||
]
|
||||
try-runtime = [
|
||||
"pezframe-support/try-runtime",
|
||||
"pezframe-system/try-runtime",
|
||||
"pezsp-runtime/try-runtime",
|
||||
]
|
||||
@@ -0,0 +1,206 @@
|
||||
// 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.
|
||||
//
|
||||
//! # Skip Feeless Payment Pallet
|
||||
//!
|
||||
//! This pallet allows runtimes that include it to skip payment of transaction fees for
|
||||
//! dispatchables marked by
|
||||
//! [`#[pallet::feeless_if]`](pezframe_support::pezpallet_prelude::feeless_if).
|
||||
//!
|
||||
//! ## Overview
|
||||
//!
|
||||
//! It does this by wrapping an existing [`TransactionExtension`] implementation (e.g.
|
||||
//! [`pezpallet-transaction-payment`]) and checking if the dispatchable is feeless before applying the
|
||||
//! wrapped extension. If the dispatchable is indeed feeless, the extension is skipped and a custom
|
||||
//! event is emitted instead. Otherwise, the extension is applied as usual.
|
||||
//!
|
||||
//!
|
||||
//! ## Integration
|
||||
//!
|
||||
//! This pallet wraps an existing transaction payment pallet. This means you should both pallets
|
||||
//! in your [`construct_runtime`](pezframe_support::construct_runtime) macro and
|
||||
//! include this pallet's [`TransactionExtension`] ([`SkipCheckIfFeeless`]) that would accept the
|
||||
//! existing one as an argument.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
use codec::{Decode, DecodeWithMemTracking, Encode};
|
||||
use pezframe_support::{
|
||||
dispatch::{CheckIfFeeless, DispatchResult},
|
||||
pezpallet_prelude::TransactionSource,
|
||||
traits::{IsType, OriginTrait},
|
||||
weights::Weight,
|
||||
};
|
||||
use scale_info::{StaticTypeInfo, TypeInfo};
|
||||
use pezsp_runtime::{
|
||||
traits::{
|
||||
DispatchInfoOf, DispatchOriginOf, Implication, PostDispatchInfoOf, TransactionExtension,
|
||||
ValidateResult,
|
||||
},
|
||||
transaction_validity::TransactionValidityError,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod mock;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use pallet::*;
|
||||
|
||||
#[pezframe_support::pallet]
|
||||
pub mod pallet {
|
||||
use super::*;
|
||||
|
||||
#[pallet::config]
|
||||
pub trait Config: pezframe_system::Config {
|
||||
/// The overarching event type.
|
||||
#[allow(deprecated)]
|
||||
type RuntimeEvent: From<Event<Self>> + IsType<<Self as pezframe_system::Config>::RuntimeEvent>;
|
||||
}
|
||||
|
||||
#[pallet::pallet]
|
||||
pub struct Pallet<T>(_);
|
||||
|
||||
#[pallet::event]
|
||||
#[pallet::generate_deposit(pub(super) fn deposit_event)]
|
||||
pub enum Event<T: Config> {
|
||||
/// A transaction fee was skipped.
|
||||
FeeSkipped { origin: <T::RuntimeOrigin as OriginTrait>::PalletsOrigin },
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`TransactionExtension`] that skips the wrapped extension if the dispatchable is feeless.
|
||||
#[derive(Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq)]
|
||||
pub struct SkipCheckIfFeeless<T, S>(pub S, core::marker::PhantomData<T>);
|
||||
|
||||
// Make this extension "invisible" from the outside (ie metadata type information)
|
||||
impl<T, S: StaticTypeInfo> TypeInfo for SkipCheckIfFeeless<T, S> {
|
||||
type Identity = S;
|
||||
fn type_info() -> scale_info::Type {
|
||||
S::type_info()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S: Encode> core::fmt::Debug for SkipCheckIfFeeless<T, S> {
|
||||
#[cfg(feature = "std")]
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
|
||||
write!(f, "SkipCheckIfFeeless<{:?}>", self.0.encode())
|
||||
}
|
||||
#[cfg(not(feature = "std"))]
|
||||
fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> From<S> for SkipCheckIfFeeless<T, S> {
|
||||
fn from(s: S) -> Self {
|
||||
Self(s, core::marker::PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Intermediate<T, O> {
|
||||
/// The wrapped extension should be applied.
|
||||
Apply(T),
|
||||
/// The wrapped extension should be skipped.
|
||||
Skip(O),
|
||||
}
|
||||
use Intermediate::*;
|
||||
|
||||
impl<T: Config + Send + Sync, S: TransactionExtension<T::RuntimeCall>>
|
||||
TransactionExtension<T::RuntimeCall> for SkipCheckIfFeeless<T, S>
|
||||
where
|
||||
T::RuntimeCall: CheckIfFeeless<Origin = pezframe_system::pezpallet_prelude::OriginFor<T>>,
|
||||
{
|
||||
// From the outside this extension should be "invisible", because it just extends the wrapped
|
||||
// extension with an extra check in `pre_dispatch` and `post_dispatch`. Thus, we should forward
|
||||
// the identifier of the wrapped extension to let wallets see this extension as it would only be
|
||||
// the wrapped extension itself.
|
||||
const IDENTIFIER: &'static str = S::IDENTIFIER;
|
||||
type Implicit = S::Implicit;
|
||||
|
||||
fn metadata() -> alloc::vec::Vec<pezsp_runtime::traits::TransactionExtensionMetadata> {
|
||||
S::metadata()
|
||||
}
|
||||
|
||||
fn implicit(&self) -> Result<Self::Implicit, TransactionValidityError> {
|
||||
self.0.implicit()
|
||||
}
|
||||
type Val =
|
||||
Intermediate<S::Val, <DispatchOriginOf<T::RuntimeCall> as OriginTrait>::PalletsOrigin>;
|
||||
type Pre =
|
||||
Intermediate<S::Pre, <DispatchOriginOf<T::RuntimeCall> as OriginTrait>::PalletsOrigin>;
|
||||
|
||||
fn weight(&self, call: &T::RuntimeCall) -> pezframe_support::weights::Weight {
|
||||
self.0.weight(call)
|
||||
}
|
||||
|
||||
fn validate(
|
||||
&self,
|
||||
origin: DispatchOriginOf<T::RuntimeCall>,
|
||||
call: &T::RuntimeCall,
|
||||
info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
len: usize,
|
||||
self_implicit: S::Implicit,
|
||||
inherited_implication: &impl Implication,
|
||||
source: TransactionSource,
|
||||
) -> ValidateResult<Self::Val, T::RuntimeCall> {
|
||||
if call.is_feeless(&origin) {
|
||||
Ok((Default::default(), Skip(origin.caller().clone()), origin))
|
||||
} else {
|
||||
let (x, y, z) = self.0.validate(
|
||||
origin,
|
||||
call,
|
||||
info,
|
||||
len,
|
||||
self_implicit,
|
||||
inherited_implication,
|
||||
source,
|
||||
)?;
|
||||
Ok((x, Apply(y), z))
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare(
|
||||
self,
|
||||
val: Self::Val,
|
||||
origin: &DispatchOriginOf<T::RuntimeCall>,
|
||||
call: &T::RuntimeCall,
|
||||
info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
match val {
|
||||
Apply(val) => self.0.prepare(val, origin, call, info, len).map(Apply),
|
||||
Skip(origin) => Ok(Skip(origin)),
|
||||
}
|
||||
}
|
||||
|
||||
fn post_dispatch_details(
|
||||
pre: Self::Pre,
|
||||
info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
post_info: &PostDispatchInfoOf<T::RuntimeCall>,
|
||||
len: usize,
|
||||
result: &DispatchResult,
|
||||
) -> Result<Weight, TransactionValidityError> {
|
||||
match pre {
|
||||
Apply(pre) => S::post_dispatch_details(pre, info, post_info, len, result),
|
||||
Skip(origin) => {
|
||||
Pallet::<T>::deposit_event(Event::<T>::FeeSkipped { origin });
|
||||
Ok(Weight::zero())
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// 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_skip_feeless_payment;
|
||||
|
||||
use pezframe_support::{derive_impl, parameter_types};
|
||||
use pezframe_system as system;
|
||||
use pezsp_runtime::{
|
||||
traits::{DispatchOriginOf, TransactionExtension},
|
||||
transaction_validity::ValidTransaction,
|
||||
};
|
||||
|
||||
type Block = pezframe_system::mocking::MockBlock<Runtime>;
|
||||
|
||||
#[derive_impl(pezframe_system::config_preludes::TestDefaultConfig)]
|
||||
impl pezframe_system::Config for Runtime {
|
||||
type Block = Block;
|
||||
}
|
||||
|
||||
impl Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub static PrepareCount: u32 = 0;
|
||||
pub static ValidateCount: u32 = 0;
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq, Debug, Encode, Decode, DecodeWithMemTracking, TypeInfo)]
|
||||
pub struct DummyExtension;
|
||||
|
||||
impl TransactionExtension<RuntimeCall> for DummyExtension {
|
||||
const IDENTIFIER: &'static str = "DummyExtension";
|
||||
type Implicit = ();
|
||||
type Val = ();
|
||||
type Pre = ();
|
||||
|
||||
fn weight(&self, _: &RuntimeCall) -> Weight {
|
||||
Weight::zero()
|
||||
}
|
||||
|
||||
fn validate(
|
||||
&self,
|
||||
origin: DispatchOriginOf<RuntimeCall>,
|
||||
_call: &RuntimeCall,
|
||||
_info: &DispatchInfoOf<RuntimeCall>,
|
||||
_len: usize,
|
||||
_self_implicit: Self::Implicit,
|
||||
_inherited_implication: &impl Encode,
|
||||
_source: TransactionSource,
|
||||
) -> ValidateResult<Self::Val, RuntimeCall> {
|
||||
ValidateCount::mutate(|c| *c += 1);
|
||||
Ok((ValidTransaction::default(), (), origin))
|
||||
}
|
||||
|
||||
fn prepare(
|
||||
self,
|
||||
_val: Self::Val,
|
||||
_origin: &DispatchOriginOf<RuntimeCall>,
|
||||
_call: &RuntimeCall,
|
||||
_info: &DispatchInfoOf<RuntimeCall>,
|
||||
_len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
PrepareCount::mutate(|c| *c += 1);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[pezframe_support::pallet(dev_mode)]
|
||||
pub mod pezpallet_dummy {
|
||||
use pezframe_support::pezpallet_prelude::*;
|
||||
use pezframe_system::pezpallet_prelude::*;
|
||||
|
||||
#[pallet::pallet]
|
||||
pub struct Pallet<T>(_);
|
||||
|
||||
#[pallet::config]
|
||||
pub trait Config: pezframe_system::Config {}
|
||||
|
||||
#[pallet::call]
|
||||
impl<T: Config> Pallet<T> {
|
||||
#[pallet::feeless_if(|_origin: &OriginFor<T>, data: &u32| -> bool {
|
||||
*data == 0
|
||||
})]
|
||||
pub fn aux(_origin: OriginFor<T>, #[pallet::compact] _data: u32) -> DispatchResult {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl pezpallet_dummy::Config for Runtime {}
|
||||
|
||||
pezframe_support::construct_runtime!(
|
||||
pub enum Runtime {
|
||||
System: system,
|
||||
SkipFeeless: pezpallet_skip_feeless_payment,
|
||||
DummyPallet: pezpallet_dummy,
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,111 @@
|
||||
// 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::mock::{
|
||||
pezpallet_dummy::Call, DummyExtension, PrepareCount, Runtime, RuntimeCall, ValidateCount,
|
||||
};
|
||||
use pezframe_support::dispatch::DispatchInfo;
|
||||
use pezsp_runtime::{traits::DispatchTransaction, transaction_validity::TransactionSource};
|
||||
|
||||
#[test]
|
||||
fn skip_feeless_payment_works() {
|
||||
let call = RuntimeCall::DummyPallet(Call::<Runtime>::aux { data: 1 });
|
||||
SkipCheckIfFeeless::<Runtime, DummyExtension>::from(DummyExtension)
|
||||
.validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0, 0)
|
||||
.unwrap();
|
||||
assert_eq!(PrepareCount::get(), 1);
|
||||
|
||||
let call = RuntimeCall::DummyPallet(Call::<Runtime>::aux { data: 0 });
|
||||
SkipCheckIfFeeless::<Runtime, DummyExtension>::from(DummyExtension)
|
||||
.validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0, 0)
|
||||
.unwrap();
|
||||
assert_eq!(PrepareCount::get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_works() {
|
||||
assert_eq!(ValidateCount::get(), 0);
|
||||
|
||||
let call = RuntimeCall::DummyPallet(Call::<Runtime>::aux { data: 1 });
|
||||
SkipCheckIfFeeless::<Runtime, DummyExtension>::from(DummyExtension)
|
||||
.validate_only(
|
||||
Some(0).into(),
|
||||
&call,
|
||||
&DispatchInfo::default(),
|
||||
0,
|
||||
TransactionSource::External,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(ValidateCount::get(), 1);
|
||||
assert_eq!(PrepareCount::get(), 0);
|
||||
|
||||
let call = RuntimeCall::DummyPallet(Call::<Runtime>::aux { data: 0 });
|
||||
SkipCheckIfFeeless::<Runtime, DummyExtension>::from(DummyExtension)
|
||||
.validate_only(
|
||||
Some(0).into(),
|
||||
&call,
|
||||
&DispatchInfo::default(),
|
||||
0,
|
||||
TransactionSource::External,
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(ValidateCount::get(), 1);
|
||||
assert_eq!(PrepareCount::get(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_prepare_works() {
|
||||
assert_eq!(ValidateCount::get(), 0);
|
||||
|
||||
let call = RuntimeCall::DummyPallet(Call::<Runtime>::aux { data: 1 });
|
||||
SkipCheckIfFeeless::<Runtime, DummyExtension>::from(DummyExtension)
|
||||
.validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0, 0)
|
||||
.unwrap();
|
||||
assert_eq!(ValidateCount::get(), 1);
|
||||
assert_eq!(PrepareCount::get(), 1);
|
||||
|
||||
let call = RuntimeCall::DummyPallet(Call::<Runtime>::aux { data: 0 });
|
||||
SkipCheckIfFeeless::<Runtime, DummyExtension>::from(DummyExtension)
|
||||
.validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0, 0)
|
||||
.unwrap();
|
||||
assert_eq!(ValidateCount::get(), 1);
|
||||
assert_eq!(PrepareCount::get(), 1);
|
||||
|
||||
// Changes from previous prepare calls persist.
|
||||
let call = RuntimeCall::DummyPallet(Call::<Runtime>::aux { data: 1 });
|
||||
SkipCheckIfFeeless::<Runtime, DummyExtension>::from(DummyExtension)
|
||||
.validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0, 0)
|
||||
.unwrap();
|
||||
assert_eq!(ValidateCount::get(), 2);
|
||||
assert_eq!(PrepareCount::get(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_for_wrap_multiple_tx_ext() {
|
||||
let metadata = SkipCheckIfFeeless::<Runtime, (DummyExtension, DummyExtension)>::metadata();
|
||||
let mut expected_metadata = vec![];
|
||||
expected_metadata.extend(DummyExtension::metadata().into_iter());
|
||||
expected_metadata.extend(DummyExtension::metadata().into_iter());
|
||||
|
||||
assert_eq!(metadata.len(), expected_metadata.len());
|
||||
for i in 0..expected_metadata.len() {
|
||||
assert_eq!(metadata[i].identifier, expected_metadata[i].identifier);
|
||||
assert_eq!(metadata[i].ty, expected_metadata[i].ty);
|
||||
assert_eq!(metadata[i].implicit, expected_metadata[i].implicit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// 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 Transaction Payment Pallet's transaction extension
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
use super::*;
|
||||
use crate::Pallet;
|
||||
use pezframe_benchmarking::v2::*;
|
||||
use pezframe_support::dispatch::{DispatchInfo, PostDispatchInfo};
|
||||
use pezframe_system::{EventRecord, RawOrigin};
|
||||
use pezsp_runtime::traits::{AsTransactionAuthorizedOrigin, DispatchTransaction, Dispatchable};
|
||||
|
||||
fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
|
||||
let events = pezframe_system::Pallet::<T>::events();
|
||||
let system_event: <T as pezframe_system::Config>::RuntimeEvent = generic_event.into();
|
||||
// compare to the last event record
|
||||
let EventRecord { event, .. } = &events[events.len() - 1];
|
||||
assert_eq!(event, &system_event);
|
||||
}
|
||||
|
||||
#[benchmarks(where
|
||||
T: Config,
|
||||
T::RuntimeOrigin: AsTransactionAuthorizedOrigin,
|
||||
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
|
||||
)]
|
||||
mod benchmarks {
|
||||
use super::*;
|
||||
|
||||
#[benchmark]
|
||||
fn charge_transaction_payment() {
|
||||
let caller: T::AccountId = account("caller", 0, 0);
|
||||
let existential_deposit =
|
||||
<T::OnChargeTransaction as OnChargeTransaction<T>>::minimum_balance();
|
||||
|
||||
let (amount_to_endow, tip) = if existential_deposit.is_zero() {
|
||||
let min_tip: <<T as pallet::Config>::OnChargeTransaction as payment::OnChargeTransaction<T>>::Balance = 1_000_000_000u32.into();
|
||||
(min_tip * 1000u32.into(), min_tip)
|
||||
} else {
|
||||
(existential_deposit * 1000u32.into(), existential_deposit)
|
||||
};
|
||||
|
||||
<T::OnChargeTransaction as OnChargeTransaction<T>>::endow_account(&caller, amount_to_endow);
|
||||
|
||||
let ext: ChargeTransactionPayment<T> = ChargeTransactionPayment::from(tip);
|
||||
let inner = pezframe_system::Call::remark { remark: alloc::vec![] };
|
||||
let call = T::RuntimeCall::from(inner);
|
||||
let extension_weight = ext.weight(&call);
|
||||
let info = DispatchInfo {
|
||||
call_weight: Weight::from_parts(100, 0),
|
||||
extension_weight,
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
let mut 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, 10, 0, |_| Ok(
|
||||
post_info
|
||||
))
|
||||
.unwrap()
|
||||
.is_ok());
|
||||
}
|
||||
|
||||
post_info.actual_weight.as_mut().map(|w| w.saturating_accrue(extension_weight));
|
||||
let actual_fee = Pallet::<T>::compute_actual_fee(10, &info, &post_info, tip);
|
||||
assert_last_event::<T>(
|
||||
Event::<T>::TransactionFeePaid { who: caller, actual_fee, tip }.into(),
|
||||
);
|
||||
}
|
||||
|
||||
impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Runtime);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,148 @@
|
||||
// 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.
|
||||
|
||||
use super::*;
|
||||
use crate as pezpallet_transaction_payment;
|
||||
use pezframe_support::{
|
||||
derive_impl,
|
||||
dispatch::DispatchClass,
|
||||
parameter_types,
|
||||
traits::{fungible, Imbalance, OnUnbalanced},
|
||||
weights::{Weight, WeightToFee as WeightToFeeT},
|
||||
};
|
||||
use pezframe_system as system;
|
||||
use pezpallet_balances::Call as BalancesCall;
|
||||
|
||||
type Block = pezframe_system::mocking::MockBlock<Runtime>;
|
||||
|
||||
pezframe_support::construct_runtime!(
|
||||
pub struct Runtime
|
||||
{
|
||||
System: system,
|
||||
Balances: pezpallet_balances,
|
||||
TransactionPayment: pezpallet_transaction_payment::{Pallet, Storage, Event<T>},
|
||||
}
|
||||
);
|
||||
|
||||
pub(crate) const CALL: &<Runtime as pezframe_system::Config>::RuntimeCall =
|
||||
&RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: 2, value: 69 });
|
||||
|
||||
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;
|
||||
pub static OperationalFeeMultiplier: u8 = 5;
|
||||
}
|
||||
|
||||
#[derive_impl(pezframe_system::config_preludes::TestDefaultConfig)]
|
||||
impl pezframe_system::Config for Runtime {
|
||||
type BlockWeights = BlockWeights;
|
||||
type Block = Block;
|
||||
type AccountData = pezpallet_balances::AccountData<Self::AccountId>;
|
||||
}
|
||||
|
||||
#[derive_impl(pezpallet_balances::config_preludes::TestDefaultConfig)]
|
||||
impl pezpallet_balances::Config for Runtime {
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Weights used in testing.
|
||||
pub struct MockWeights;
|
||||
|
||||
impl WeightInfo for MockWeights {
|
||||
fn charge_transaction_payment() -> Weight {
|
||||
Weight::from_parts(10, 0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type OnChargeTransaction = FungibleAdapter<Balances, DealWithFees>;
|
||||
type OperationalFeeMultiplier = OperationalFeeMultiplier;
|
||||
type WeightToFee = WeightToFee;
|
||||
type LengthToFee = TransactionByteFee;
|
||||
type FeeMultiplierUpdate = ();
|
||||
type WeightInfo = MockWeights;
|
||||
}
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
pub fn new_test_ext() -> pezsp_io::TestExternalities {
|
||||
crate::tests::ExtBuilder::default()
|
||||
.base_weight(Weight::from_parts(100, 0))
|
||||
.byte_fee(10)
|
||||
.balance_factor(0)
|
||||
.build()
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
// 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.
|
||||
|
||||
/// ! Traits and default implementation for paying transaction fees.
|
||||
use crate::{Config, Pallet, TxPaymentCredit, LOG_TARGET};
|
||||
|
||||
use codec::{DecodeWithMemTracking, FullCodec, MaxEncodedLen};
|
||||
use core::marker::PhantomData;
|
||||
use pezframe_support::{
|
||||
traits::{
|
||||
fungible::{Balanced, Credit, Inspect},
|
||||
tokens::{Precision, WithdrawConsequence},
|
||||
Currency, ExistenceRequirement, Imbalance, NoDrop, OnUnbalanced, SuppressedDrop,
|
||||
WithdrawReasons,
|
||||
},
|
||||
unsigned::TransactionValidityError,
|
||||
};
|
||||
use scale_info::TypeInfo;
|
||||
use pezsp_runtime::{
|
||||
traits::{CheckedSub, DispatchInfoOf, PostDispatchInfoOf, Saturating, Zero},
|
||||
transaction_validity::InvalidTransaction,
|
||||
};
|
||||
|
||||
type NegativeImbalanceOf<C, T> =
|
||||
<C as Currency<<T as pezframe_system::Config>::AccountId>>::NegativeImbalance;
|
||||
|
||||
/// Handle withdrawing, refunding and depositing of transaction fees.
|
||||
pub trait OnChargeTransaction<T: Config>: TxCreditHold<T> {
|
||||
/// The underlying integer type in which fees are calculated.
|
||||
type Balance: pezframe_support::traits::tokens::Balance;
|
||||
|
||||
type LiquidityInfo: Default;
|
||||
|
||||
/// Before the transaction is executed the payment of the transaction fees
|
||||
/// need to be secured.
|
||||
///
|
||||
/// Returns the tip credit
|
||||
fn withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
call: &T::RuntimeCall,
|
||||
dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
fee_with_tip: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
) -> Result<Self::LiquidityInfo, TransactionValidityError>;
|
||||
|
||||
/// Check if the predicted fee from the transaction origin can be withdrawn.
|
||||
fn can_withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
call: &T::RuntimeCall,
|
||||
dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
fee_with_tip: 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`.
|
||||
fn correct_and_deposit_fee(
|
||||
who: &T::AccountId,
|
||||
dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
post_info: &PostDispatchInfoOf<T::RuntimeCall>,
|
||||
corrected_fee_with_tip: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
liquidity_info: Self::LiquidityInfo,
|
||||
) -> Result<(), TransactionValidityError>;
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
fn endow_account(who: &T::AccountId, amount: Self::Balance);
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
fn minimum_balance() -> Self::Balance;
|
||||
}
|
||||
|
||||
/// Needs to be implemented for every [`OnChargeTransaction`].
|
||||
///
|
||||
/// Cannot be added to `OnChargeTransaction` directly as this would
|
||||
/// cause cycles in trait resolution.
|
||||
pub trait TxCreditHold<T: Config> {
|
||||
/// The credit that is used to represent the withdrawn transaction fees.
|
||||
///
|
||||
/// The pallet will put this into a temporary storage item in order to
|
||||
/// make it available to other pallets during tx application.
|
||||
///
|
||||
/// Is only used within a transaction. Hence changes to the encoding of this
|
||||
/// type **won't** require a storage migration.
|
||||
///
|
||||
/// Set to `()` if your `OnChargeTransaction` impl does not store the credit.
|
||||
type Credit: FullCodec + DecodeWithMemTracking + MaxEncodedLen + TypeInfo + SuppressedDrop;
|
||||
}
|
||||
|
||||
/// Implements transaction payment for a pallet implementing the [`pezframe_support::traits::fungible`]
|
||||
/// trait (eg. pezpallet_balances) using an unbalance handler (implementing
|
||||
/// [`OnUnbalanced`]).
|
||||
///
|
||||
/// The unbalance handler is given 2 unbalanceds in [`OnUnbalanced::on_unbalanceds`]: `fee` and
|
||||
/// then `tip`.
|
||||
pub struct FungibleAdapter<F, OU>(PhantomData<(F, OU)>);
|
||||
|
||||
impl<T, F, OU> OnChargeTransaction<T> for FungibleAdapter<F, OU>
|
||||
where
|
||||
T: Config,
|
||||
T::OnChargeTransaction: TxCreditHold<T, Credit = NoDrop<Credit<T::AccountId, F>>>,
|
||||
F: Balanced<T::AccountId> + 'static,
|
||||
OU: OnUnbalanced<<Self::Credit as SuppressedDrop>::Inner>,
|
||||
{
|
||||
type LiquidityInfo = Option<<Self::Credit as SuppressedDrop>::Inner>;
|
||||
type Balance = <F as Inspect<<T as pezframe_system::Config>::AccountId>>::Balance;
|
||||
|
||||
fn withdraw_fee(
|
||||
who: &<T>::AccountId,
|
||||
_call: &<T>::RuntimeCall,
|
||||
_dispatch_info: &DispatchInfoOf<<T>::RuntimeCall>,
|
||||
fee_with_tip: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
) -> Result<Self::LiquidityInfo, TransactionValidityError> {
|
||||
if fee_with_tip.is_zero() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let credit = F::withdraw(
|
||||
who,
|
||||
fee_with_tip,
|
||||
Precision::Exact,
|
||||
pezframe_support::traits::tokens::Preservation::Preserve,
|
||||
pezframe_support::traits::tokens::Fortitude::Polite,
|
||||
)
|
||||
.map_err(|_| InvalidTransaction::Payment)?;
|
||||
|
||||
let (tip_credit, inclusion_fee) = credit.split(tip);
|
||||
|
||||
<Pallet<T>>::deposit_txfee(inclusion_fee);
|
||||
|
||||
Ok(Some(tip_credit))
|
||||
}
|
||||
|
||||
fn can_withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
_call: &T::RuntimeCall,
|
||||
_dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
fee_with_tip: Self::Balance,
|
||||
_tip: Self::Balance,
|
||||
) -> Result<(), TransactionValidityError> {
|
||||
if fee_with_tip.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
match F::can_withdraw(who, fee_with_tip) {
|
||||
WithdrawConsequence::Success => Ok(()),
|
||||
_ => Err(InvalidTransaction::Payment.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn correct_and_deposit_fee(
|
||||
who: &<T>::AccountId,
|
||||
_dispatch_info: &DispatchInfoOf<<T>::RuntimeCall>,
|
||||
_post_info: &PostDispatchInfoOf<<T>::RuntimeCall>,
|
||||
corrected_fee_with_tip: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
tip_credit: Self::LiquidityInfo,
|
||||
) -> Result<(), TransactionValidityError> {
|
||||
let corrected_fee = corrected_fee_with_tip.saturating_sub(tip);
|
||||
|
||||
let remaining_credit = <TxPaymentCredit<T>>::take()
|
||||
.map(|stored_credit| stored_credit.into_inner())
|
||||
.unwrap_or_default();
|
||||
|
||||
// If pallets take away too much it makes the transaction invalid. They need to make
|
||||
// sure that this does not happen. We do not invalide the transaction because we already
|
||||
// executed it and we rather collect too little fees than none at all.
|
||||
if remaining_credit.peek() < corrected_fee {
|
||||
log::error!(target: LOG_TARGET, "Not enough balance on hold to pay tx fees. This is a bug.");
|
||||
}
|
||||
|
||||
// skip refund if account was killed by the tx
|
||||
let fee_credit = if pezframe_system::Pallet::<T>::account_exists(who) {
|
||||
let (mut fee_credit, refund_credit) = remaining_credit.split(corrected_fee);
|
||||
// resolve might fail if refund is below the ed and account
|
||||
// is kept alive by other providers
|
||||
if !refund_credit.peek().is_zero() {
|
||||
if let Err(not_refunded) = F::resolve(who, refund_credit) {
|
||||
fee_credit.subsume(not_refunded);
|
||||
}
|
||||
}
|
||||
fee_credit
|
||||
} else {
|
||||
remaining_credit
|
||||
};
|
||||
|
||||
OU::on_unbalanceds(Some(fee_credit).into_iter().chain(tip_credit));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
fn endow_account(who: &T::AccountId, amount: Self::Balance) {
|
||||
let _ = F::deposit(who, amount, Precision::BestEffort);
|
||||
}
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
fn minimum_balance() -> Self::Balance {
|
||||
F::minimum_balance()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, OU> TxCreditHold<T> for FungibleAdapter<F, OU>
|
||||
where
|
||||
T: Config,
|
||||
F: Balanced<T::AccountId> + 'static,
|
||||
{
|
||||
type Credit = NoDrop<Credit<<T as pezframe_system::Config>::AccountId, F>>;
|
||||
}
|
||||
|
||||
/// Implements the transaction payment for a pallet implementing the [`Currency`]
|
||||
/// trait (eg. the pezpallet_balances) using an unbalance handler (implementing
|
||||
/// [`OnUnbalanced`]).
|
||||
///
|
||||
/// The unbalance handler is given 2 unbalanceds in [`OnUnbalanced::on_unbalanceds`]: `fee` and
|
||||
/// then `tip`.
|
||||
#[deprecated(
|
||||
note = "Please use the fungible trait and FungibleAdapter. This struct will be removed some time after March 2024."
|
||||
)]
|
||||
pub struct CurrencyAdapter<C, OU>(PhantomData<(C, OU)>);
|
||||
|
||||
/// Default implementation for a Currency and an OnUnbalanced handler.
|
||||
///
|
||||
/// The unbalance handler is given 2 unbalanceds in [`OnUnbalanced::on_unbalanceds`]: `fee` and
|
||||
/// then `tip`.
|
||||
#[allow(deprecated)]
|
||||
impl<T, C, OU> OnChargeTransaction<T> for CurrencyAdapter<C, OU>
|
||||
where
|
||||
T: Config,
|
||||
C: Currency<<T as pezframe_system::Config>::AccountId>,
|
||||
C::PositiveImbalance: Imbalance<
|
||||
<C as Currency<<T as pezframe_system::Config>::AccountId>>::Balance,
|
||||
Opposite = C::NegativeImbalance,
|
||||
>,
|
||||
C::NegativeImbalance: Imbalance<
|
||||
<C as Currency<<T as pezframe_system::Config>::AccountId>>::Balance,
|
||||
Opposite = C::PositiveImbalance,
|
||||
>,
|
||||
OU: OnUnbalanced<NegativeImbalanceOf<C, T>>,
|
||||
{
|
||||
type LiquidityInfo = Option<NegativeImbalanceOf<C, T>>;
|
||||
type Balance = <C as Currency<<T as pezframe_system::Config>::AccountId>>::Balance;
|
||||
|
||||
/// 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>,
|
||||
fee_with_tip: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
) -> Result<Self::LiquidityInfo, TransactionValidityError> {
|
||||
if fee_with_tip.is_zero() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let withdraw_reason = if tip.is_zero() {
|
||||
WithdrawReasons::TRANSACTION_PAYMENT
|
||||
} else {
|
||||
WithdrawReasons::TRANSACTION_PAYMENT | WithdrawReasons::TIP
|
||||
};
|
||||
|
||||
match C::withdraw(who, fee_with_tip, withdraw_reason, ExistenceRequirement::KeepAlive) {
|
||||
Ok(imbalance) => Ok(Some(imbalance)),
|
||||
Err(_) => Err(InvalidTransaction::Payment.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the predicted fee from the transaction origin can be withdrawn.
|
||||
///
|
||||
/// Note: The `fee` already includes the `tip`.
|
||||
fn can_withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
_call: &T::RuntimeCall,
|
||||
_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
fee_with_tip: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
) -> Result<(), TransactionValidityError> {
|
||||
if fee_with_tip.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let withdraw_reason = if tip.is_zero() {
|
||||
WithdrawReasons::TRANSACTION_PAYMENT
|
||||
} else {
|
||||
WithdrawReasons::TRANSACTION_PAYMENT | WithdrawReasons::TIP
|
||||
};
|
||||
|
||||
let new_balance = C::free_balance(who)
|
||||
.checked_sub(&fee_with_tip)
|
||||
.ok_or(InvalidTransaction::Payment)?;
|
||||
C::ensure_can_withdraw(who, fee_with_tip, withdraw_reason, new_balance)
|
||||
.map(|_| ())
|
||||
.map_err(|_| InvalidTransaction::Payment.into())
|
||||
}
|
||||
|
||||
/// Hand the fee and the tip over to the `[OnUnbalanced]` 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`.
|
||||
fn correct_and_deposit_fee(
|
||||
who: &T::AccountId,
|
||||
_dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
|
||||
_post_info: &PostDispatchInfoOf<T::RuntimeCall>,
|
||||
corrected_fee_with_tip: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
already_withdrawn: Self::LiquidityInfo,
|
||||
) -> Result<(), TransactionValidityError> {
|
||||
if let Some(paid) = already_withdrawn {
|
||||
// Calculate how much refund we should return
|
||||
let refund_amount = paid.peek().saturating_sub(corrected_fee_with_tip);
|
||||
// refund to the 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 refund_imbalance = C::deposit_into_existing(who, refund_amount)
|
||||
.unwrap_or_else(|_| C::PositiveImbalance::zero());
|
||||
// merge the imbalance caused by paying the fees and refunding parts of it again.
|
||||
let adjusted_paid = paid
|
||||
.offset(refund_imbalance)
|
||||
.same()
|
||||
.map_err(|_| TransactionValidityError::Invalid(InvalidTransaction::Payment))?;
|
||||
// Call someone else to 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(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
fn endow_account(who: &T::AccountId, amount: Self::Balance) {
|
||||
let _ = C::deposit_creating(who, amount);
|
||||
}
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
fn minimum_balance() -> Self::Balance {
|
||||
C::minimum_balance()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
impl<T: Config, C, OU> TxCreditHold<T> for CurrencyAdapter<C, OU> {
|
||||
type Credit = ();
|
||||
}
|
||||
@@ -0,0 +1,917 @@
|
||||
// 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.
|
||||
|
||||
use super::*;
|
||||
use crate as pezpallet_transaction_payment;
|
||||
|
||||
use codec::Encode;
|
||||
|
||||
use pezsp_runtime::{
|
||||
generic::UncheckedExtrinsic,
|
||||
traits::{DispatchTransaction, One},
|
||||
transaction_validity::{InvalidTransaction, TransactionSource::External},
|
||||
BuildStorage,
|
||||
};
|
||||
|
||||
use pezframe_support::{
|
||||
assert_ok,
|
||||
dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, PostDispatchInfo},
|
||||
traits::{Currency, OriginTrait},
|
||||
weights::Weight,
|
||||
};
|
||||
use pezframe_system as system;
|
||||
use mock::*;
|
||||
use pezpallet_balances::Call as BalancesCall;
|
||||
|
||||
pub struct ExtBuilder {
|
||||
balance_factor: u64,
|
||||
base_weight: Weight,
|
||||
byte_fee: u64,
|
||||
weight_to_fee: u64,
|
||||
initial_multiplier: Option<Multiplier>,
|
||||
}
|
||||
|
||||
impl Default for ExtBuilder {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
balance_factor: 1,
|
||||
base_weight: Weight::zero(),
|
||||
byte_fee: 1,
|
||||
weight_to_fee: 1,
|
||||
initial_multiplier: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtBuilder {
|
||||
pub fn base_weight(mut self, base_weight: Weight) -> Self {
|
||||
self.base_weight = base_weight;
|
||||
self
|
||||
}
|
||||
pub fn byte_fee(mut self, byte_fee: u64) -> Self {
|
||||
self.byte_fee = byte_fee;
|
||||
self
|
||||
}
|
||||
pub fn weight_fee(mut self, weight_to_fee: u64) -> Self {
|
||||
self.weight_to_fee = weight_to_fee;
|
||||
self
|
||||
}
|
||||
pub fn balance_factor(mut self, factor: u64) -> Self {
|
||||
self.balance_factor = factor;
|
||||
self
|
||||
}
|
||||
pub fn with_initial_multiplier(mut self, multiplier: Multiplier) -> Self {
|
||||
self.initial_multiplier = Some(multiplier);
|
||||
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();
|
||||
|
||||
if let Some(multiplier) = self.initial_multiplier {
|
||||
pallet::GenesisConfig::<Runtime> { multiplier, ..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 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() }
|
||||
}
|
||||
|
||||
type Ext = ChargeTransactionPayment<Runtime>;
|
||||
|
||||
#[test]
|
||||
fn transaction_extension_transaction_payment_work() {
|
||||
ExtBuilder::default()
|
||||
.balance_factor(10)
|
||||
.base_weight(Weight::from_parts(5, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
let mut info = info_from_weight(Weight::from_parts(5, 0));
|
||||
let ext = Ext::from(0);
|
||||
let ext_weight = ext.weight(CALL);
|
||||
info.extension_weight = ext_weight;
|
||||
ext.test_run(Some(1).into(), CALL, &info, 10, 0, |_| {
|
||||
assert_eq!(Balances::free_balance(1), 100 - 5 - 5 - 10 - 10);
|
||||
Ok(default_post_info())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(Balances::free_balance(1), 100 - 5 - 5 - 10 - 10);
|
||||
assert_eq!(FeeUnbalancedAmount::get(), 5 + 5 + 10 + 10);
|
||||
assert_eq!(TipUnbalancedAmount::get(), 0);
|
||||
|
||||
FeeUnbalancedAmount::mutate(|a| *a = 0);
|
||||
|
||||
let mut info = info_from_weight(Weight::from_parts(100, 0));
|
||||
info.extension_weight = ext_weight;
|
||||
Ext::from(5 /* tipped */)
|
||||
.test_run(Some(2).into(), CALL, &info, 10, 0, |_| {
|
||||
assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 10 - 5);
|
||||
Ok(post_info_from_weight(Weight::from_parts(50, 0)))
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 50 - 10 - 5);
|
||||
assert_eq!(FeeUnbalancedAmount::get(), 5 + 10 + 50 + 10);
|
||||
assert_eq!(TipUnbalancedAmount::get(), 5);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_extension_transaction_payment_multiplied_refund_works() {
|
||||
ExtBuilder::default()
|
||||
.balance_factor(10)
|
||||
.base_weight(Weight::from_parts(5, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
NextFeeMultiplier::<Runtime>::put(Multiplier::saturating_from_rational(3, 2));
|
||||
|
||||
let len = 10;
|
||||
let origin = Some(2).into();
|
||||
let mut info = info_from_weight(Weight::from_parts(100, 0));
|
||||
let ext = Ext::from(5 /* tipped */);
|
||||
let ext_weight = ext.weight(CALL);
|
||||
info.extension_weight = ext_weight;
|
||||
ext.test_run(origin, CALL, &info, len, 0, |_| {
|
||||
// 5 base fee, 10 byte fee, 3/2 * (100 call weight fee + 10 ext weight fee), 5
|
||||
// tip
|
||||
assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 165 - 5);
|
||||
Ok(post_info_from_weight(Weight::from_parts(50, 0)))
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
// 75 (3/2 of the returned 50 units of call weight, 0 returned of ext weight) is
|
||||
// refunded
|
||||
assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - (165 - 75) - 5);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_extension_transaction_payment_is_bounded() {
|
||||
ExtBuilder::default().balance_factor(1000).byte_fee(0).build().execute_with(|| {
|
||||
// maximum weight possible
|
||||
let info = info_from_weight(Weight::MAX);
|
||||
assert_ok!(Ext::from(0).validate_and_prepare(Some(1).into(), CALL, &info, 10, 0));
|
||||
// fee will be proportional to what is the actual maximum weight in the runtime.
|
||||
assert_eq!(
|
||||
Balances::free_balance(&1),
|
||||
(10000 - <Runtime as pezframe_system::Config>::BlockWeights::get().max_block.ref_time())
|
||||
as u64
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_extension_allows_free_transactions() {
|
||||
ExtBuilder::default()
|
||||
.base_weight(Weight::from_parts(100, 0))
|
||||
.balance_factor(0)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// 1 ain't have a penny.
|
||||
assert_eq!(Balances::free_balance(1), 0);
|
||||
|
||||
let len = 100;
|
||||
|
||||
// This is a completely free (and thus wholly insecure/DoS-ridden) transaction.
|
||||
let op_tx = DispatchInfo {
|
||||
call_weight: Weight::from_parts(0, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::No,
|
||||
};
|
||||
assert_ok!(Ext::from(0).validate_only(Some(1).into(), CALL, &op_tx, len, External, 0));
|
||||
|
||||
// like a InsecureFreeNormal
|
||||
let free_tx = DispatchInfo {
|
||||
call_weight: Weight::from_parts(0, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Normal,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
assert_eq!(
|
||||
Ext::from(0)
|
||||
.validate_only(Some(1).into(), CALL, &free_tx, len, External, 0)
|
||||
.unwrap_err(),
|
||||
TransactionValidityError::Invalid(InvalidTransaction::Payment),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_ext_length_fee_is_also_updated_per_congestion() {
|
||||
ExtBuilder::default()
|
||||
.base_weight(Weight::from_parts(5, 0))
|
||||
.balance_factor(10)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// all fees should be x1.5
|
||||
NextFeeMultiplier::<Runtime>::put(Multiplier::saturating_from_rational(3, 2));
|
||||
let len = 10;
|
||||
let info = info_from_weight(Weight::from_parts(3, 0));
|
||||
assert_ok!(Ext::from(10).validate_and_prepare(Some(1).into(), CALL, &info, len, 0));
|
||||
assert_eq!(
|
||||
Balances::free_balance(1),
|
||||
100 // original
|
||||
- 10 // tip
|
||||
- 5 // base
|
||||
- 10 // len
|
||||
- (3 * 3 / 2) // adjusted weight
|
||||
);
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_info_and_fee_details_works() {
|
||||
let call = RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: 2, value: 69 });
|
||||
let origin = 111111;
|
||||
let extra = ();
|
||||
let xt = UncheckedExtrinsic::new_signed(call.clone(), origin, (), extra);
|
||||
let info = xt.get_dispatch_info();
|
||||
let ext = xt.encode();
|
||||
let len = ext.len() as u32;
|
||||
|
||||
let unsigned_xt = UncheckedExtrinsic::<u64, _, (), ()>::new_bare(call);
|
||||
let unsigned_xt_info = unsigned_xt.get_dispatch_info();
|
||||
|
||||
ExtBuilder::default()
|
||||
.base_weight(Weight::from_parts(5, 0))
|
||||
.weight_fee(2)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// all fees should be x1.5
|
||||
NextFeeMultiplier::<Runtime>::put(Multiplier::saturating_from_rational(3, 2));
|
||||
|
||||
assert_eq!(
|
||||
TransactionPayment::query_info(xt.clone(), len),
|
||||
RuntimeDispatchInfo {
|
||||
weight: info.total_weight(),
|
||||
class: info.class,
|
||||
partial_fee: 5 * 2 /* base * weight_fee */
|
||||
+ len as u64 /* len * 1 */
|
||||
+ info.total_weight().min(BlockWeights::get().max_block).ref_time() as u64 * 2 * 3 / 2 /* weight */
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
TransactionPayment::query_info(unsigned_xt.clone(), len),
|
||||
RuntimeDispatchInfo {
|
||||
weight: unsigned_xt_info.call_weight,
|
||||
class: unsigned_xt_info.class,
|
||||
partial_fee: 0,
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
TransactionPayment::query_fee_details(xt, len),
|
||||
FeeDetails {
|
||||
inclusion_fee: Some(InclusionFee {
|
||||
base_fee: 5 * 2,
|
||||
len_fee: len as u64,
|
||||
adjusted_weight_fee: info
|
||||
.total_weight()
|
||||
.min(BlockWeights::get().max_block)
|
||||
.ref_time() as u64 * 2 * 3 / 2
|
||||
}),
|
||||
tip: 0,
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
TransactionPayment::query_fee_details(unsigned_xt, len),
|
||||
FeeDetails { inclusion_fee: None, tip: 0 },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_call_info_and_fee_details_works() {
|
||||
let call = RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest: 2, value: 69 });
|
||||
let info = call.get_dispatch_info();
|
||||
let encoded_call = call.encode();
|
||||
let len = encoded_call.len() as u32;
|
||||
|
||||
ExtBuilder::default()
|
||||
.base_weight(Weight::from_parts(5, 0))
|
||||
.weight_fee(2)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// all fees should be x1.5
|
||||
NextFeeMultiplier::<Runtime>::put(Multiplier::saturating_from_rational(3, 2));
|
||||
|
||||
assert_eq!(
|
||||
TransactionPayment::query_call_info(call.clone(), len),
|
||||
RuntimeDispatchInfo {
|
||||
weight: info.total_weight(),
|
||||
class: info.class,
|
||||
partial_fee: 5 * 2 /* base * weight_fee */
|
||||
+ len as u64 /* len * 1 */
|
||||
+ info.total_weight().min(BlockWeights::get().max_block).ref_time() as u64 * 2 * 3 / 2 /* weight */
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
TransactionPayment::query_call_fee_details(call, len),
|
||||
FeeDetails {
|
||||
inclusion_fee: Some(InclusionFee {
|
||||
base_fee: 5 * 2, /* base * weight_fee */
|
||||
len_fee: len as u64, /* len * 1 */
|
||||
adjusted_weight_fee: info
|
||||
.total_weight()
|
||||
.min(BlockWeights::get().max_block)
|
||||
.ref_time() as u64 * 2 * 3 / 2 /* weight * weight_fee * multipler */
|
||||
}),
|
||||
tip: 0,
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_fee_works_without_multiplier() {
|
||||
ExtBuilder::default()
|
||||
.base_weight(Weight::from_parts(100, 0))
|
||||
.byte_fee(10)
|
||||
.balance_factor(0)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// Next fee multiplier is zero
|
||||
assert_eq!(NextFeeMultiplier::<Runtime>::get(), Multiplier::one());
|
||||
|
||||
// Tip only, no fees works
|
||||
let dispatch_info = DispatchInfo {
|
||||
call_weight: Weight::from_parts(0, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::No,
|
||||
};
|
||||
assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 10), 10);
|
||||
// No tip, only base fee works
|
||||
let dispatch_info = DispatchInfo {
|
||||
call_weight: Weight::from_parts(0, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 0), 100);
|
||||
// Tip + base fee works
|
||||
assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 69), 169);
|
||||
// Len (byte fee) + base fee works
|
||||
assert_eq!(Pallet::<Runtime>::compute_fee(42, &dispatch_info, 0), 520);
|
||||
// Weight fee + base fee works
|
||||
let dispatch_info = DispatchInfo {
|
||||
call_weight: Weight::from_parts(1000, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 0), 1100);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_fee_works_with_multiplier() {
|
||||
ExtBuilder::default()
|
||||
.base_weight(Weight::from_parts(100, 0))
|
||||
.byte_fee(10)
|
||||
.balance_factor(0)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// Add a next fee multiplier. Fees will be x3/2.
|
||||
NextFeeMultiplier::<Runtime>::put(Multiplier::saturating_from_rational(3, 2));
|
||||
// Base fee is unaffected by multiplier
|
||||
let dispatch_info = DispatchInfo {
|
||||
call_weight: Weight::from_parts(0, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 0), 100);
|
||||
|
||||
// Everything works together :)
|
||||
let dispatch_info = DispatchInfo {
|
||||
call_weight: Weight::from_parts(123, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
// 123 weight, 456 length, 100 base
|
||||
assert_eq!(
|
||||
Pallet::<Runtime>::compute_fee(456, &dispatch_info, 789),
|
||||
100 + (3 * 123 / 2) + 4560 + 789,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_fee_works_with_negative_multiplier() {
|
||||
ExtBuilder::default()
|
||||
.base_weight(Weight::from_parts(100, 0))
|
||||
.byte_fee(10)
|
||||
.balance_factor(0)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// Add a next fee multiplier. All fees will be x1/2.
|
||||
NextFeeMultiplier::<Runtime>::put(Multiplier::saturating_from_rational(1, 2));
|
||||
|
||||
// Base fee is unaffected by multiplier.
|
||||
let dispatch_info = DispatchInfo {
|
||||
call_weight: Weight::from_parts(0, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
assert_eq!(Pallet::<Runtime>::compute_fee(0, &dispatch_info, 0), 100);
|
||||
|
||||
// Everything works together.
|
||||
let dispatch_info = DispatchInfo {
|
||||
call_weight: Weight::from_parts(123, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
// 123 weight, 456 length, 100 base
|
||||
assert_eq!(
|
||||
Pallet::<Runtime>::compute_fee(456, &dispatch_info, 789),
|
||||
100 + (123 / 2) + 4560 + 789,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_fee_does_not_overflow() {
|
||||
ExtBuilder::default()
|
||||
.base_weight(Weight::from_parts(100, 0))
|
||||
.byte_fee(10)
|
||||
.balance_factor(0)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// Overflow is handled
|
||||
let dispatch_info = DispatchInfo {
|
||||
call_weight: Weight::MAX,
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
assert_eq!(
|
||||
Pallet::<Runtime>::compute_fee(u32::MAX, &dispatch_info, u64::MAX),
|
||||
u64::MAX
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refund_does_not_recreate_account() {
|
||||
ExtBuilder::default()
|
||||
.balance_factor(10)
|
||||
.base_weight(Weight::from_parts(5, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// So events are emitted
|
||||
System::set_block_number(10);
|
||||
let info = info_from_weight(Weight::from_parts(100, 0));
|
||||
Ext::from(5 /* tipped */)
|
||||
.test_run(Some(2).into(), CALL, &info, 10, 0, |origin| {
|
||||
assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5);
|
||||
|
||||
// kill the account between pre and post dispatch
|
||||
assert_ok!(Balances::transfer_allow_death(
|
||||
origin,
|
||||
3,
|
||||
Balances::free_balance(2)
|
||||
));
|
||||
assert_eq!(Balances::free_balance(2), 0);
|
||||
|
||||
Ok(post_info_from_weight(Weight::from_parts(50, 0)))
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(Balances::free_balance(2), 0);
|
||||
// Transfer Event
|
||||
System::assert_has_event(RuntimeEvent::Balances(pezpallet_balances::Event::Transfer {
|
||||
from: 2,
|
||||
to: 3,
|
||||
amount: 80,
|
||||
}));
|
||||
// Killed Event
|
||||
System::assert_has_event(RuntimeEvent::System(system::Event::KilledAccount {
|
||||
account: 2,
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_weight_higher_than_max_refunds_nothing() {
|
||||
ExtBuilder::default()
|
||||
.balance_factor(10)
|
||||
.base_weight(Weight::from_parts(5, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
let info = info_from_weight(Weight::from_parts(100, 0));
|
||||
Ext::from(5 /* tipped */)
|
||||
.test_run(Some(2).into(), CALL, &info, 10, 0, |_| {
|
||||
assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5);
|
||||
Ok(post_info_from_weight(Weight::from_parts(101, 0)))
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_transfer_on_free_transaction() {
|
||||
ExtBuilder::default()
|
||||
.balance_factor(10)
|
||||
.base_weight(Weight::from_parts(5, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// So events are emitted
|
||||
System::set_block_number(10);
|
||||
let info = DispatchInfo {
|
||||
call_weight: Weight::from_parts(100, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
pays_fee: Pays::No,
|
||||
class: DispatchClass::Normal,
|
||||
};
|
||||
let user = 69;
|
||||
Ext::from(0)
|
||||
.test_run(Some(user).into(), CALL, &info, 10, 0, |_| {
|
||||
assert_eq!(Balances::total_balance(&user), 0);
|
||||
Ok(default_post_info())
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(Balances::total_balance(&user), 0);
|
||||
// TransactionFeePaid Event
|
||||
System::assert_has_event(RuntimeEvent::TransactionPayment(
|
||||
pezpallet_transaction_payment::Event::TransactionFeePaid {
|
||||
who: user,
|
||||
actual_fee: 0,
|
||||
tip: 0,
|
||||
},
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refund_consistent_with_actual_weight() {
|
||||
ExtBuilder::default()
|
||||
.balance_factor(10)
|
||||
.base_weight(Weight::from_parts(7, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
let mut info = info_from_weight(Weight::from_parts(100, 0));
|
||||
let tip = 5;
|
||||
let ext = Ext::from(tip);
|
||||
let ext_weight = ext.weight(CALL);
|
||||
info.extension_weight = ext_weight;
|
||||
let mut post_info = post_info_from_weight(Weight::from_parts(33, 0));
|
||||
let prev_balance = Balances::free_balance(2);
|
||||
let len = 10;
|
||||
|
||||
NextFeeMultiplier::<Runtime>::put(Multiplier::saturating_from_rational(5, 4));
|
||||
|
||||
let actual_post_info = ext
|
||||
.test_run(Some(2).into(), CALL, &info, len, 0, |_| Ok(post_info))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
post_info
|
||||
.actual_weight
|
||||
.as_mut()
|
||||
.map(|w| w.saturating_accrue(Ext::from(tip).weight(CALL)));
|
||||
assert_eq!(post_info, actual_post_info);
|
||||
|
||||
let refund_based_fee = prev_balance - Balances::free_balance(2);
|
||||
let actual_fee =
|
||||
Pallet::<Runtime>::compute_actual_fee(len as u32, &info, &actual_post_info, tip);
|
||||
|
||||
// 33 call weight, 10 ext weight, 10 length, 7 base, 5 tip
|
||||
assert_eq!(actual_fee, 7 + 10 + ((33 + 10) * 5 / 4) + 5);
|
||||
assert_eq!(refund_based_fee, actual_fee);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_alter_operational_priority() {
|
||||
let tip = 5;
|
||||
let len = 10;
|
||||
|
||||
ExtBuilder::default().balance_factor(100).build().execute_with(|| {
|
||||
let normal = DispatchInfo {
|
||||
call_weight: Weight::from_parts(100, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Normal,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
|
||||
let ext = Ext::from(tip);
|
||||
let priority = ext
|
||||
.validate_only(Some(2).into(), CALL, &normal, len, External, 0)
|
||||
.unwrap()
|
||||
.0
|
||||
.priority;
|
||||
assert_eq!(priority, 60);
|
||||
|
||||
let ext = Ext::from(2 * tip);
|
||||
let priority = ext
|
||||
.validate_only(Some(2).into(), CALL, &normal, len, External, 0)
|
||||
.unwrap()
|
||||
.0
|
||||
.priority;
|
||||
assert_eq!(priority, 110);
|
||||
});
|
||||
|
||||
ExtBuilder::default().balance_factor(100).build().execute_with(|| {
|
||||
let op = DispatchInfo {
|
||||
call_weight: Weight::from_parts(100, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
|
||||
let ext = Ext::from(tip);
|
||||
let priority = ext
|
||||
.validate_only(Some(2).into(), CALL, &op, len, External, 0)
|
||||
.unwrap()
|
||||
.0
|
||||
.priority;
|
||||
assert_eq!(priority, 5810);
|
||||
|
||||
let ext = Ext::from(2 * tip);
|
||||
let priority = ext
|
||||
.validate_only(Some(2).into(), CALL, &op, len, External, 0)
|
||||
.unwrap()
|
||||
.0
|
||||
.priority;
|
||||
assert_eq!(priority, 6110);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_tip_has_some_priority() {
|
||||
let tip = 0;
|
||||
let len = 10;
|
||||
|
||||
ExtBuilder::default().balance_factor(100).build().execute_with(|| {
|
||||
let normal = DispatchInfo {
|
||||
call_weight: Weight::from_parts(100, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Normal,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
let ext = Ext::from(tip);
|
||||
let priority = ext
|
||||
.validate_only(Some(2).into(), CALL, &normal, len, External, 0)
|
||||
.unwrap()
|
||||
.0
|
||||
.priority;
|
||||
assert_eq!(priority, 10);
|
||||
});
|
||||
|
||||
ExtBuilder::default().balance_factor(100).build().execute_with(|| {
|
||||
let op = DispatchInfo {
|
||||
call_weight: Weight::from_parts(100, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
let ext = Ext::from(tip);
|
||||
let priority = ext
|
||||
.validate_only(Some(2).into(), CALL, &op, len, External, 0)
|
||||
.unwrap()
|
||||
.0
|
||||
.priority;
|
||||
assert_eq!(priority, 5510);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn higher_tip_have_higher_priority() {
|
||||
let get_priorities = |tip: u64| {
|
||||
let mut pri1 = 0;
|
||||
let mut pri2 = 0;
|
||||
let len = 10;
|
||||
ExtBuilder::default().balance_factor(100).build().execute_with(|| {
|
||||
let normal = DispatchInfo {
|
||||
call_weight: Weight::from_parts(100, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Normal,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
let ext = Ext::from(tip);
|
||||
|
||||
pri1 = ext
|
||||
.validate_only(Some(2).into(), CALL, &normal, len, External, 0)
|
||||
.unwrap()
|
||||
.0
|
||||
.priority;
|
||||
});
|
||||
|
||||
ExtBuilder::default().balance_factor(100).build().execute_with(|| {
|
||||
let op = DispatchInfo {
|
||||
call_weight: Weight::from_parts(100, 0),
|
||||
extension_weight: Weight::zero(),
|
||||
class: DispatchClass::Operational,
|
||||
pays_fee: Pays::Yes,
|
||||
};
|
||||
let ext = Ext::from(tip);
|
||||
pri2 = ext
|
||||
.validate_only(Some(2).into(), CALL, &op, len, External, 0)
|
||||
.unwrap()
|
||||
.0
|
||||
.priority;
|
||||
});
|
||||
|
||||
(pri1, pri2)
|
||||
};
|
||||
|
||||
let mut prev_priorities = get_priorities(0);
|
||||
|
||||
for tip in 1..3 {
|
||||
let priorities = get_priorities(tip);
|
||||
assert!(prev_priorities.0 < priorities.0);
|
||||
assert!(prev_priorities.1 < priorities.1);
|
||||
prev_priorities = priorities;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_info_can_change_pays_fee() {
|
||||
ExtBuilder::default()
|
||||
.balance_factor(10)
|
||||
.base_weight(Weight::from_parts(7, 0))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
let info = info_from_weight(Weight::from_parts(100, 0));
|
||||
let post_info = post_info_from_pays(Pays::No);
|
||||
let prev_balance = Balances::free_balance(2);
|
||||
let len = 10;
|
||||
let tip = 5;
|
||||
|
||||
NextFeeMultiplier::<Runtime>::put(Multiplier::saturating_from_rational(5, 4));
|
||||
|
||||
let post_info = ChargeTransactionPayment::<Runtime>::from(tip)
|
||||
.test_run(Some(2).into(), CALL, &info, len, 0, |_| Ok(post_info))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let refund_based_fee = prev_balance - Balances::free_balance(2);
|
||||
let actual_fee =
|
||||
Pallet::<Runtime>::compute_actual_fee(len as u32, &info, &post_info, tip);
|
||||
|
||||
// Only 5 tip is paid
|
||||
assert_eq!(actual_fee, 5);
|
||||
assert_eq!(refund_based_fee, actual_fee);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn genesis_config_works() {
|
||||
ExtBuilder::default()
|
||||
.with_initial_multiplier(Multiplier::from_u32(100))
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
assert_eq!(
|
||||
NextFeeMultiplier::<Runtime>::get(),
|
||||
Multiplier::saturating_from_integer(100)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn genesis_default_works() {
|
||||
ExtBuilder::default().build().execute_with(|| {
|
||||
assert_eq!(NextFeeMultiplier::<Runtime>::get(), Multiplier::saturating_from_integer(1));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_fee_and_no_weight_for_other_origins() {
|
||||
ExtBuilder::default().build().execute_with(|| {
|
||||
let ext = Ext::from(0);
|
||||
|
||||
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(),
|
||||
};
|
||||
|
||||
<Ext as TransactionExtension<RuntimeCall>>::post_dispatch(
|
||||
pre,
|
||||
&info,
|
||||
&mut post_info,
|
||||
len,
|
||||
&pd_res,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(post_info.actual_weight, Some(info.call_weight));
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fungible_adapter_no_zero_refund_action() {
|
||||
type FungibleAdapterT = payment::FungibleAdapter<Balances, DealWithFees>;
|
||||
|
||||
ExtBuilder::default().balance_factor(10).build().execute_with(|| {
|
||||
System::set_block_number(10);
|
||||
|
||||
let dummy_acc = 1;
|
||||
let (actual_fee, no_tip) = (10, 0);
|
||||
let already_paid = <FungibleAdapterT as OnChargeTransaction<Runtime>>::withdraw_fee(
|
||||
&dummy_acc,
|
||||
CALL,
|
||||
&CALL.get_dispatch_info(),
|
||||
actual_fee,
|
||||
no_tip,
|
||||
).expect("Account must have enough funds.");
|
||||
|
||||
// Correction action with no expected side effect.
|
||||
assert!(<FungibleAdapterT as OnChargeTransaction<Runtime>>::correct_and_deposit_fee(
|
||||
&dummy_acc,
|
||||
&CALL.get_dispatch_info(),
|
||||
&default_post_info(),
|
||||
actual_fee,
|
||||
no_tip,
|
||||
already_paid,
|
||||
).is_ok());
|
||||
|
||||
// Ensure no zero amount deposit event is emitted.
|
||||
let events = System::events();
|
||||
assert!(!events
|
||||
.iter()
|
||||
.any(|record| matches!(record.event, RuntimeEvent::Balances(pezpallet_balances::Event::Deposit { amount, .. }) if amount.is_zero())),
|
||||
"No zero amount deposit amount event should be emitted.",
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// 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.
|
||||
|
||||
//! Types for transaction-payment RPC.
|
||||
|
||||
use codec::{Decode, Encode};
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use scale_info::TypeInfo;
|
||||
|
||||
use pezsp_runtime::traits::{AtLeast32BitUnsigned, Zero};
|
||||
|
||||
use pezframe_support::dispatch::DispatchClass;
|
||||
|
||||
/// The base fee and adjusted weight and length fees constitute the _inclusion fee_.
|
||||
#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
|
||||
pub struct InclusionFee<Balance> {
|
||||
/// This is the minimum amount a user pays for a transaction. It is declared
|
||||
/// as a base _weight_ in the runtime and converted to a fee using `WeightToFee`.
|
||||
pub base_fee: Balance,
|
||||
/// The length fee, the amount paid for the encoded length (in bytes) of the transaction.
|
||||
pub len_fee: Balance,
|
||||
///
|
||||
/// - `targeted_fee_adjustment`: This is a multiplier that can tune the final fee based on the
|
||||
/// congestion of the network.
|
||||
/// - `weight_fee`: This amount is computed based on the weight of the transaction. Weight
|
||||
/// accounts for the execution time of a transaction.
|
||||
///
|
||||
/// adjusted_weight_fee = targeted_fee_adjustment * weight_fee
|
||||
pub adjusted_weight_fee: Balance,
|
||||
}
|
||||
|
||||
impl<Balance: AtLeast32BitUnsigned + Copy> InclusionFee<Balance> {
|
||||
/// Returns the total of inclusion fee.
|
||||
///
|
||||
/// ```ignore
|
||||
/// inclusion_fee = base_fee + len_fee + adjusted_weight_fee
|
||||
/// ```
|
||||
pub fn inclusion_fee(&self) -> Balance {
|
||||
self.base_fee
|
||||
.saturating_add(self.len_fee)
|
||||
.saturating_add(self.adjusted_weight_fee)
|
||||
}
|
||||
}
|
||||
|
||||
/// The `FeeDetails` is composed of:
|
||||
/// - (Optional) `inclusion_fee`: Only the `Pays::Yes` transaction can have the inclusion fee.
|
||||
/// - `tip`: If included in the transaction, the tip will be added on top. Only signed
|
||||
/// transactions can have a tip.
|
||||
#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
|
||||
pub struct FeeDetails<Balance> {
|
||||
/// The minimum fee for a transaction to be included in a block.
|
||||
pub inclusion_fee: Option<InclusionFee<Balance>>,
|
||||
// Do not serialize and deserialize `tip` as we actually can not pass any tip to the RPC.
|
||||
#[cfg_attr(feature = "std", serde(skip))]
|
||||
pub tip: Balance,
|
||||
}
|
||||
|
||||
impl<Balance: AtLeast32BitUnsigned + Copy> FeeDetails<Balance> {
|
||||
/// Returns the final fee.
|
||||
///
|
||||
/// ```ignore
|
||||
/// final_fee = inclusion_fee + tip;
|
||||
/// ```
|
||||
pub fn final_fee(&self) -> Balance {
|
||||
self.inclusion_fee
|
||||
.as_ref()
|
||||
.map(|i| i.inclusion_fee())
|
||||
.unwrap_or_else(|| Zero::zero())
|
||||
.saturating_add(self.tip)
|
||||
}
|
||||
}
|
||||
|
||||
/// Information related to a dispatchable's class, weight, and fee that can be queried from the
|
||||
/// runtime.
|
||||
#[derive(Eq, PartialEq, Encode, Decode, Default, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize, Clone))]
|
||||
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
|
||||
#[cfg_attr(
|
||||
feature = "std",
|
||||
serde(bound(serialize = "Balance: std::fmt::Display, Weight: Serialize"))
|
||||
)]
|
||||
#[cfg_attr(
|
||||
feature = "std",
|
||||
serde(bound(deserialize = "Balance: std::str::FromStr, Weight: Deserialize<'de>"))
|
||||
)]
|
||||
pub struct RuntimeDispatchInfo<Balance, Weight = pezframe_support::weights::Weight> {
|
||||
/// Weight of this dispatch.
|
||||
pub weight: Weight,
|
||||
/// Class of this dispatch.
|
||||
pub class: DispatchClass,
|
||||
/// The inclusion fee of this dispatch.
|
||||
///
|
||||
/// This does not include a tip or anything else that
|
||||
/// depends on the signature (i.e. depends on a `TransactionExtension`).
|
||||
#[cfg_attr(feature = "std", serde(with = "serde_balance"))]
|
||||
pub partial_fee: Balance,
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
mod serde_balance {
|
||||
use serde::{Deserialize, Deserializer, Serializer};
|
||||
|
||||
pub fn serialize<S: Serializer, T: std::fmt::Display>(
|
||||
t: &T,
|
||||
serializer: S,
|
||||
) -> Result<S::Ok, S::Error> {
|
||||
serializer.serialize_str(&t.to_string())
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>, T: std::str::FromStr>(
|
||||
deserializer: D,
|
||||
) -> Result<T, D::Error> {
|
||||
let s = String::deserialize(deserializer)?;
|
||||
s.parse::<T>().map_err(|_| serde::de::Error::custom("Parse from string failed"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pezframe_support::weights::Weight;
|
||||
|
||||
#[test]
|
||||
fn should_serialize_and_deserialize_properly_with_string() {
|
||||
let info = RuntimeDispatchInfo {
|
||||
weight: Weight::from_parts(5, 0),
|
||||
class: DispatchClass::Normal,
|
||||
partial_fee: 1_000_000_u64,
|
||||
};
|
||||
|
||||
let json_str =
|
||||
r#"{"weight":{"ref_time":5,"proof_size":0},"class":"normal","partialFee":"1000000"}"#;
|
||||
|
||||
assert_eq!(serde_json::to_string(&info).unwrap(), json_str);
|
||||
assert_eq!(serde_json::from_str::<RuntimeDispatchInfo<u64>>(json_str).unwrap(), info);
|
||||
|
||||
// should not panic
|
||||
serde_json::to_value(&info).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_serialize_and_deserialize_properly_large_value() {
|
||||
let info = RuntimeDispatchInfo {
|
||||
weight: Weight::from_parts(5, 0),
|
||||
class: DispatchClass::Normal,
|
||||
partial_fee: u128::max_value(),
|
||||
};
|
||||
|
||||
let json_str = r#"{"weight":{"ref_time":5,"proof_size":0},"class":"normal","partialFee":"340282366920938463463374607431768211455"}"#;
|
||||
|
||||
assert_eq!(serde_json::to_string(&info).unwrap(), json_str);
|
||||
assert_eq!(serde_json::from_str::<RuntimeDispatchInfo<u128>>(json_str).unwrap(), info);
|
||||
|
||||
// should not panic
|
||||
serde_json::to_value(&info).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// 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_transaction_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_transaction_payment
|
||||
// --header=/__w/pezkuwi-sdk/pezkuwi-sdk/bizinikiwi/HEADER-APACHE2
|
||||
// --output=/__w/pezkuwi-sdk/pezkuwi-sdk/bizinikiwi/pezframe/transaction-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_transaction_payment`.
|
||||
pub trait WeightInfo {
|
||||
fn charge_transaction_payment() -> Weight;
|
||||
}
|
||||
|
||||
/// Weights for `pezpallet_transaction_payment` using the Bizinikiwi node and recommended hardware.
|
||||
pub struct BizinikiwiWeight<T>(PhantomData<T>);
|
||||
impl<T: pezframe_system::Config> WeightInfo for BizinikiwiWeight<T> {
|
||||
/// Storage: `System::Account` (r:1 w:1)
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
fn charge_transaction_payment() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `52`
|
||||
// Estimated: `3593`
|
||||
// Minimum execution time: 35_425_000 picoseconds.
|
||||
Weight::from_parts(35_979_000, 3593)
|
||||
.saturating_add(T::DbWeight::get().reads(1_u64))
|
||||
.saturating_add(T::DbWeight::get().writes(1_u64))
|
||||
}
|
||||
}
|
||||
|
||||
// For backwards compatibility and tests.
|
||||
impl WeightInfo for () {
|
||||
/// Storage: `System::Account` (r:1 w:1)
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
fn charge_transaction_payment() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `52`
|
||||
// Estimated: `3593`
|
||||
// Minimum execution time: 35_425_000 picoseconds.
|
||||
Weight::from_parts(35_979_000, 3593)
|
||||
.saturating_add(RocksDbWeight::get().reads(1_u64))
|
||||
.saturating_add(RocksDbWeight::get().writes(1_u64))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user