weight.rs 6.95 KB
Newer Older
Gavin Wood's avatar
Gavin Wood committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

17
use sp_std::{result::Result, marker::PhantomData, convert::TryInto};
Gavin Wood's avatar
Gavin Wood committed
18
use parity_scale_codec::Decode;
19
20
21
22
use xcm::v0::{Xcm, Order, MultiAsset, MultiLocation, Error};
use sp_runtime::traits::{Zero, Saturating, SaturatedConversion};
use frame_support::traits::{Get, OnUnbalanced as OnUnbalancedT, tokens::currency::Currency as CurrencyT};
use frame_support::weights::{Weight, GetDispatchInfo, WeightToFeePolynomial};
Gavin Wood's avatar
Gavin Wood committed
23
24
25
26
27
use xcm_executor::{Assets, traits::{WeightBounds, WeightTrader}};

pub struct FixedWeightBounds<T, C>(PhantomData<(T, C)>);
impl<T: Get<Weight>, C: Decode + GetDispatchInfo> WeightBounds<C> for FixedWeightBounds<T, C> {
	fn shallow(message: &mut Xcm<C>) -> Result<Weight, ()> {
28
		Ok(match message {
Gavin Wood's avatar
Gavin Wood committed
29
			Xcm::Transact { call, .. } => {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
30
				call.ensure_decoded()?.get_dispatch_info().weight.saturating_add(T::get())
Gavin Wood's avatar
Gavin Wood committed
31
			}
Shawn Tabrizi's avatar
Shawn Tabrizi committed
32
			Xcm::RelayedFrom { ref mut message, .. } => T::get().saturating_add(Self::shallow(message.as_mut())?),
Gavin Wood's avatar
Gavin Wood committed
33
34
			Xcm::WithdrawAsset { effects, .. }
			| Xcm::ReserveAssetDeposit { effects, .. }
35
36
			| Xcm::TeleportAsset { effects, .. }
			=> {
Gavin Wood's avatar
Gavin Wood committed
37
38
39
40
41
42
43
44
45
46
47
48
				let inner: Weight = effects.iter_mut()
					.map(|effect| match effect {
						Order::BuyExecution { .. } => {
							// On success, execution of this will result in more weight being consumed but
							// we don't count it here since this is only the *shallow*, non-negotiable weight
							// spend and doesn't count weight placed behind a `BuyExecution` since it will not
							// be definitely consumed from any existing weight credit if execution of the message
							// is attempted.
							T::get()
						},
						_ => T::get(),
					}).sum();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
49
				T::get().saturating_add(inner)
Gavin Wood's avatar
Gavin Wood committed
50
51
			}
			_ => T::get(),
52
		})
Gavin Wood's avatar
Gavin Wood committed
53
54
	}
	fn deep(message: &mut Xcm<C>) -> Result<Weight, ()> {
55
56
		Ok(match message {
			Xcm::RelayedFrom { ref mut message, .. } => Self::deep(message.as_mut())?,
Gavin Wood's avatar
Gavin Wood committed
57
58
			Xcm::WithdrawAsset { effects, .. }
			| Xcm::ReserveAssetDeposit { effects, .. }
59
60
61
			| Xcm::TeleportAsset { effects, .. }
			=> {
				let mut extra = 0;
Gavin Wood's avatar
Gavin Wood committed
62
63
64
65
				for effect in effects.iter_mut() {
					match effect {
						Order::BuyExecution { xcm, .. } => {
							for message in xcm.iter_mut() {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
66
								extra.saturating_accrue(Self::shallow(message)?.saturating_add(Self::deep(message)?));
Gavin Wood's avatar
Gavin Wood committed
67
68
69
70
71
							}
						},
						_ => {}
					}
				}
72
73
74
75
				extra
			},
			_ => 0,
		})
Gavin Wood's avatar
Gavin Wood committed
76
77
78
	}
}

79
80
81
82
83
84
85
86
87
88
89
90
/// Function trait for handling some revenue. Similar to a negative imbalance (credit) handler, but for a
/// `MultiAsset`. Sensible implementations will deposit the asset in some known treasury or block-author account.
pub trait TakeRevenue {
	/// Do something with the given `revenue`, which is a single non-wildcard `MultiAsset`.
	fn take_revenue(revenue: MultiAsset);
}

/// Null implementation just burns the revenue.
impl TakeRevenue for () {
	fn take_revenue(_revenue: MultiAsset) {}
}

Gavin Wood's avatar
Gavin Wood committed
91
92
93
94
/// Simple fee calculator that requires payment in a single concrete fungible at a fixed rate.
///
/// The constant `Get` type parameter should be the concrete fungible ID and the amount of it required for
/// one second of weight.
95
96
97
98
99
100
101
102
pub struct FixedRateOfConcreteFungible<
	T: Get<(MultiLocation, u128)>,
	R: TakeRevenue,
>(Weight, u128, PhantomData<(T, R)>);
impl<T: Get<(MultiLocation, u128)>, R: TakeRevenue> WeightTrader for FixedRateOfConcreteFungible<T, R> {
	fn new() -> Self { Self(0, 0, PhantomData) }

	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, Error> {
Gavin Wood's avatar
Gavin Wood committed
103
		let (id, units_per_second) = T::get();
104
105
		use frame_support::weights::constants::WEIGHT_PER_SECOND;
		let amount = units_per_second * (weight as u128) / (WEIGHT_PER_SECOND as u128);
Gavin Wood's avatar
Gavin Wood committed
106
		let required = MultiAsset::ConcreteFungible { amount, id };
107
		let (unused, _) = payment.less(required).map_err(|_| Error::TooExpensive)?;
Gavin Wood's avatar
Gavin Wood committed
108
		self.0 = self.0.saturating_add(weight);
109
110
		self.1 = self.1.saturating_add(amount);
		Ok(unused)
Gavin Wood's avatar
Gavin Wood committed
111
	}
112

Gavin Wood's avatar
Gavin Wood committed
113
114
	fn refund_weight(&mut self, weight: Weight) -> MultiAsset {
		let (id, units_per_second) = T::get();
115
		let weight = weight.min(self.0);
Gavin Wood's avatar
Gavin Wood committed
116
		let amount = units_per_second * (weight as u128) / 1_000_000_000_000u128;
117
118
		self.0 -= weight;
		self.1 = self.1.saturating_sub(amount);
Gavin Wood's avatar
Gavin Wood committed
119
120
121
122
		let result = MultiAsset::ConcreteFungible { amount, id };
		result
	}
}
123
124
125
126
127
128
129
130

impl<T: Get<(MultiLocation, u128)>, R: TakeRevenue> Drop for FixedRateOfConcreteFungible<T, R> {
	fn drop(&mut self) {
		let revenue = MultiAsset::ConcreteFungible { amount: self.1, id: T::get().0 };
		R::take_revenue(revenue);
	}
}

Denis_P's avatar
Denis_P committed
131
/// Weight trader which uses the `TransactionPayment` pallet to set the right price for weight and then
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/// places any weight bought into the right account.
pub struct UsingComponents<
	WeightToFee: WeightToFeePolynomial<Balance=Currency::Balance>,
	AssetId: Get<MultiLocation>,
	AccountId,
	Currency: CurrencyT<AccountId>,
	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
>(Weight, Currency::Balance, PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>);
impl<
	WeightToFee: WeightToFeePolynomial<Balance=Currency::Balance>,
	AssetId: Get<MultiLocation>,
	AccountId,
	Currency: CurrencyT<AccountId>,
	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
> WeightTrader for UsingComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced> {
	fn new() -> Self { Self(0, Zero::zero(), PhantomData) }

	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, Error> {
		let amount = WeightToFee::calc(&weight);
		let required = MultiAsset::ConcreteFungible {
			amount: amount.try_into().map_err(|_| Error::Overflow)?,
			id: AssetId::get(),
		};
		let (unused, _) = payment.less(required).map_err(|_| Error::TooExpensive)?;
		self.0 = self.0.saturating_add(weight);
		self.1 = self.1.saturating_add(amount);
		Ok(unused)
	}

	fn refund_weight(&mut self, weight: Weight) -> MultiAsset {
		let weight = weight.min(self.0);
		let amount = WeightToFee::calc(&weight);
		self.0 -= weight;
		self.1 = self.1.saturating_sub(amount);
		let result = MultiAsset::ConcreteFungible {
			amount: amount.saturated_into(),
			id: AssetId::get(),
		};
		result
	}

}
impl<
	WeightToFee: WeightToFeePolynomial<Balance=Currency::Balance>,
	AssetId: Get<MultiLocation>,
	AccountId,
	Currency: CurrencyT<AccountId>,
	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
> Drop for UsingComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced> {
	fn drop(&mut self) {
		OnUnbalanced::on_unbalanced(Currency::issue(self.1));
	}
}