use crate::Config;
use core::marker::PhantomData;
use sp_runtime::{
traits::{CheckedSub, DispatchInfoOf, PostDispatchInfoOf, Saturating, Zero},
transaction_validity::InvalidTransaction,
};
use frame_support::{
traits::{
fungible::{Balanced, Credit, Debt, Inspect},
tokens::{Precision, WithdrawConsequence},
Currency, ExistenceRequirement, Imbalance, OnUnbalanced, WithdrawReasons,
},
unsigned::TransactionValidityError,
};
type NegativeImbalanceOf<C, T> =
<C as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;
pub trait OnChargeTransaction<T: Config> {
type Balance: frame_support::traits::tokens::Balance;
type LiquidityInfo: Default;
fn withdraw_fee(
who: &T::AccountId,
call: &T::RuntimeCall,
dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
fee: Self::Balance,
tip: Self::Balance,
) -> Result<Self::LiquidityInfo, TransactionValidityError>;
fn can_withdraw_fee(
who: &T::AccountId,
call: &T::RuntimeCall,
dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
fee: Self::Balance,
tip: Self::Balance,
) -> Result<(), TransactionValidityError>;
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<(), TransactionValidityError>;
#[cfg(feature = "runtime-benchmarks")]
fn endow_account(who: &T::AccountId, amount: Self::Balance);
#[cfg(feature = "runtime-benchmarks")]
fn minimum_balance() -> Self::Balance;
}
pub struct FungibleAdapter<F, OU>(PhantomData<(F, OU)>);
impl<T, F, OU> OnChargeTransaction<T> for FungibleAdapter<F, OU>
where
T: Config,
F: Balanced<T::AccountId>,
OU: OnUnbalanced<Credit<T::AccountId, F>>,
{
type LiquidityInfo = Option<Credit<T::AccountId, F>>;
type Balance = <F as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
fn withdraw_fee(
who: &<T>::AccountId,
_call: &<T>::RuntimeCall,
_dispatch_info: &DispatchInfoOf<<T>::RuntimeCall>,
fee: Self::Balance,
_tip: Self::Balance,
) -> Result<Self::LiquidityInfo, TransactionValidityError> {
if fee.is_zero() {
return Ok(None)
}
match F::withdraw(
who,
fee,
Precision::Exact,
frame_support::traits::tokens::Preservation::Preserve,
frame_support::traits::tokens::Fortitude::Polite,
) {
Ok(imbalance) => Ok(Some(imbalance)),
Err(_) => Err(InvalidTransaction::Payment.into()),
}
}
fn can_withdraw_fee(
who: &T::AccountId,
_call: &T::RuntimeCall,
_dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
fee: Self::Balance,
_tip: Self::Balance,
) -> Result<(), TransactionValidityError> {
if fee.is_zero() {
return Ok(())
}
match F::can_withdraw(who, fee) {
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: Self::Balance,
tip: Self::Balance,
already_withdrawn: Self::LiquidityInfo,
) -> Result<(), TransactionValidityError> {
if let Some(paid) = already_withdrawn {
let refund_amount = paid.peek().saturating_sub(corrected_fee);
let refund_imbalance = if F::total_balance(who) > F::Balance::zero() {
F::deposit(who, refund_amount, Precision::BestEffort)
.unwrap_or_else(|_| Debt::<T::AccountId, F>::zero())
} else {
Debt::<T::AccountId, F>::zero()
};
let adjusted_paid: Credit<T::AccountId, F> = paid
.offset(refund_imbalance)
.same()
.map_err(|_| TransactionValidityError::Invalid(InvalidTransaction::Payment))?;
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 _ = F::deposit(who, amount, Precision::BestEffort);
}
#[cfg(feature = "runtime-benchmarks")]
fn minimum_balance() -> Self::Balance {
F::minimum_balance()
}
}
#[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)>);
#[allow(deprecated)]
impl<T, C, OU> OnChargeTransaction<T> for CurrencyAdapter<C, OU>
where
T: Config,
C: Currency<<T as frame_system::Config>::AccountId>,
C::PositiveImbalance: Imbalance<
<C as Currency<<T as frame_system::Config>::AccountId>>::Balance,
Opposite = C::NegativeImbalance,
>,
C::NegativeImbalance: Imbalance<
<C as Currency<<T as frame_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 frame_system::Config>::AccountId>>::Balance;
fn withdraw_fee(
who: &T::AccountId,
_call: &T::RuntimeCall,
_info: &DispatchInfoOf<T::RuntimeCall>,
fee: Self::Balance,
tip: Self::Balance,
) -> Result<Self::LiquidityInfo, TransactionValidityError> {
if fee.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, withdraw_reason, ExistenceRequirement::KeepAlive) {
Ok(imbalance) => Ok(Some(imbalance)),
Err(_) => Err(InvalidTransaction::Payment.into()),
}
}
fn can_withdraw_fee(
who: &T::AccountId,
_call: &T::RuntimeCall,
_info: &DispatchInfoOf<T::RuntimeCall>,
fee: Self::Balance,
tip: Self::Balance,
) -> Result<(), TransactionValidityError> {
if fee.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).ok_or(InvalidTransaction::Payment)?;
C::ensure_can_withdraw(who, fee, withdraw_reason, new_balance)
.map(|_| ())
.map_err(|_| InvalidTransaction::Payment.into())
}
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<(), TransactionValidityError> {
if let Some(paid) = already_withdrawn {
let refund_amount = paid.peek().saturating_sub(corrected_fee);
let refund_imbalance = C::deposit_into_existing(who, refund_amount)
.unwrap_or_else(|_| C::PositiveImbalance::zero());
let adjusted_paid = paid
.offset(refund_imbalance)
.same()
.map_err(|_| TransactionValidityError::Invalid(InvalidTransaction::Payment))?;
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()
}
}