|
| 1 | +use crate::{module::*, AssetMetadata}; |
| 2 | +use frame_support::{log, pallet_prelude::*, weights::constants::WEIGHT_PER_SECOND}; |
| 3 | +use orml_traits::{ |
| 4 | + asset_registry::{AssetProcessor, FixedConversionRateProvider, WeightToFeeConverter}, |
| 5 | + GetByKey, |
| 6 | +}; |
| 7 | +use sp_runtime::FixedPointNumber; |
| 8 | +use sp_runtime::{ |
| 9 | + traits::{AtLeast32BitUnsigned, Bounded, CheckedAdd, One}, |
| 10 | + ArithmeticError, FixedU128, |
| 11 | +}; |
| 12 | +use sp_std::prelude::*; |
| 13 | +use xcm::v2::prelude::*; |
| 14 | +use xcm_builder::TakeRevenue; |
| 15 | +use xcm_executor::{traits::WeightTrader, Assets}; |
| 16 | + |
| 17 | +/// Alias for AssetMetadata to improve readability (and to placate clippy) |
| 18 | +pub type DefaultAssetMetadata<T> = AssetMetadata<<T as Config>::Balance, <T as Config>::CustomMetadata>; |
| 19 | + |
| 20 | +/// An AssetProcessor that assigns a sequential ID |
| 21 | +pub struct SequentialId<T>(PhantomData<T>); |
| 22 | + |
| 23 | +impl<T> AssetProcessor<T::AssetId, DefaultAssetMetadata<T>> for SequentialId<T> |
| 24 | +where |
| 25 | + T: Config, |
| 26 | + T::AssetId: AtLeast32BitUnsigned, |
| 27 | +{ |
| 28 | + fn pre_register( |
| 29 | + id: Option<T::AssetId>, |
| 30 | + asset_metadata: DefaultAssetMetadata<T>, |
| 31 | + ) -> Result<(T::AssetId, DefaultAssetMetadata<T>), DispatchError> { |
| 32 | + let next_id = LastAssetId::<T>::get() |
| 33 | + .checked_add(&T::AssetId::one()) |
| 34 | + .ok_or(ArithmeticError::Overflow)?; |
| 35 | + |
| 36 | + match id { |
| 37 | + Some(explicit_id) if explicit_id != next_id => { |
| 38 | + // we don't allow non-sequential ids |
| 39 | + Err(Error::<T>::InvalidAssetId.into()) |
| 40 | + } |
| 41 | + _ => { |
| 42 | + LastAssetId::<T>::put(&next_id); |
| 43 | + Ok((next_id, asset_metadata)) |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +/// A default implementation for WeightToFeeConverter that takes a fixed |
| 50 | +/// conversion rate. |
| 51 | +pub struct FixedRateAssetRegistryTrader<P: FixedConversionRateProvider>(PhantomData<P>); |
| 52 | +impl<P: FixedConversionRateProvider> WeightToFeeConverter for FixedRateAssetRegistryTrader<P> { |
| 53 | + fn convert_weight_to_fee(location: &MultiLocation, weight: Weight) -> Option<u128> { |
| 54 | + let fee_per_second = P::get_fee_per_second(location)?; |
| 55 | + let weight_ratio = FixedU128::saturating_from_rational(weight as u128, WEIGHT_PER_SECOND as u128); |
| 56 | + let amount = weight_ratio.saturating_mul_int(fee_per_second); |
| 57 | + Some(amount) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +/// Helper struct for the AssetRegistryTrader that stores the data about |
| 62 | +/// bought weight. |
| 63 | +pub struct BoughtWeight { |
| 64 | + weight: Weight, |
| 65 | + asset_location: MultiLocation, |
| 66 | + amount: u128, |
| 67 | +} |
| 68 | + |
| 69 | +/// A WeightTrader implementation that tries to buy weight using a single |
| 70 | +/// currency. It tries all assets in `payment` and uses the first asset that can |
| 71 | +/// cover the weight. This asset is then "locked in" - later calls to |
| 72 | +/// `buy_weight` in the same xcm message only try the same asset. |
| 73 | +/// This is because only a single asset can be refunded due to the return type |
| 74 | +/// of `refund_weight`. This implementation assumes that `WeightToFeeConverter` |
| 75 | +/// implements a linear function, i.e. fee(x) + fee(y) = fee(x+y). |
| 76 | +pub struct AssetRegistryTrader<W: WeightToFeeConverter, R: TakeRevenue> { |
| 77 | + bought_weight: Option<BoughtWeight>, |
| 78 | + _phantom: PhantomData<(W, R)>, |
| 79 | +} |
| 80 | + |
| 81 | +impl<W: WeightToFeeConverter, R: TakeRevenue> WeightTrader for AssetRegistryTrader<W, R> { |
| 82 | + fn new() -> Self { |
| 83 | + Self { |
| 84 | + bought_weight: None, |
| 85 | + _phantom: Default::default(), |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> { |
| 90 | + log::trace!( |
| 91 | + target: "xcm::weight", |
| 92 | + "AssetRegistryTrader::buy_weight weight: {:?}, payment: {:?}", |
| 93 | + weight, payment, |
| 94 | + ); |
| 95 | + |
| 96 | + for (asset, _) in payment.fungible.iter() { |
| 97 | + if let AssetId::Concrete(ref location) = asset { |
| 98 | + if matches!(self.bought_weight, Some(ref bought) if &bought.asset_location != location) { |
| 99 | + // we already bought another asset - don't attempt to buy this one since |
| 100 | + // we won't be able to refund it |
| 101 | + continue; |
| 102 | + } |
| 103 | + |
| 104 | + if let Some(fee_increase) = W::convert_weight_to_fee(location, weight) { |
| 105 | + if fee_increase == 0 { |
| 106 | + // if the fee is set very low it could lead to zero fees, in which case |
| 107 | + // constructing the fee asset item to subtract from payment would fail. |
| 108 | + // Therefore, provide early exit |
| 109 | + return Ok(payment); |
| 110 | + } |
| 111 | + |
| 112 | + if let Ok(unused) = payment.clone().checked_sub((asset.clone(), fee_increase).into()) { |
| 113 | + let (existing_weight, existing_fee) = match self.bought_weight { |
| 114 | + Some(ref x) => (x.weight, x.amount), |
| 115 | + None => (0, 0), |
| 116 | + }; |
| 117 | + |
| 118 | + self.bought_weight = Some(BoughtWeight { |
| 119 | + amount: existing_fee.checked_add(fee_increase).ok_or(XcmError::Overflow)?, |
| 120 | + weight: existing_weight.checked_add(weight).ok_or(XcmError::Overflow)?, |
| 121 | + asset_location: location.clone(), |
| 122 | + }); |
| 123 | + return Ok(unused); |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + Err(XcmError::TooExpensive) |
| 129 | + } |
| 130 | + |
| 131 | + fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> { |
| 132 | + log::trace!(target: "xcm::weight", "AssetRegistryTrader::refund_weight weight: {:?}", weight); |
| 133 | + |
| 134 | + match self.bought_weight { |
| 135 | + Some(ref mut bought) => { |
| 136 | + let new_weight = bought.weight.saturating_sub(weight); |
| 137 | + let new_amount = W::convert_weight_to_fee(&bought.asset_location, new_weight)?; |
| 138 | + let refunded_amount = bought.amount.saturating_sub(new_amount); |
| 139 | + |
| 140 | + bought.weight = new_weight; |
| 141 | + bought.amount = new_amount; |
| 142 | + |
| 143 | + Some((AssetId::Concrete(bought.asset_location.clone()), refunded_amount).into()) |
| 144 | + } |
| 145 | + None => None, // nothing to refund |
| 146 | + } |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +impl<W: WeightToFeeConverter, R: TakeRevenue> Drop for AssetRegistryTrader<W, R> { |
| 151 | + fn drop(&mut self) { |
| 152 | + if let Some(ref bought) = self.bought_weight { |
| 153 | + R::take_revenue((AssetId::Concrete(bought.asset_location.clone()), bought.amount).into()); |
| 154 | + } |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +pub struct ExistentialDeposits<T: Config>(PhantomData<T>); |
| 159 | + |
| 160 | +// Return Existential deposit of an asset. Implementing this trait allows the |
| 161 | +// pallet to be used in the tokens::ExistentialDeposits config item |
| 162 | +impl<T: Config> GetByKey<T::AssetId, T::Balance> for ExistentialDeposits<T> { |
| 163 | + fn get(k: &T::AssetId) -> T::Balance { |
| 164 | + if let Some(metadata) = Pallet::<T>::metadata(k) { |
| 165 | + metadata.existential_deposit |
| 166 | + } else { |
| 167 | + // Asset does not exist - not supported |
| 168 | + T::Balance::max_value() |
| 169 | + } |
| 170 | + } |
| 171 | +} |
0 commit comments