referrerpolicy=no-referrer-when-downgrade

pallet_on_demand_para/
types.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Types used by this pallet.
19
20use crate::{
21	Config, Error, RelayBlockNumberOf, DEFAULT_BASE_FEE, DEFAULT_DRAIN_RATE_PER_BLOCK,
22	DEFAULT_ORDER_CAP, DEFAULT_PRICE_STEP,
23};
24use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
25use fp_coretime::TaskId;
26use frame_support::{
27	pallet_prelude::*,
28	traits::{fungible::Inspect, tokens::Balance},
29};
30use frame_system::Config as SConfig;
31use scale_info::TypeInfo;
32use sp_arithmetic::{
33	traits::{ensure_pow, One, Saturating},
34	FixedPointNumber, FixedU128, Perbill,
35};
36use sp_runtime::DispatchError;
37
38pub type BalanceOf<T> = <<T as Config>::Currency as Inspect<<T as SConfig>::AccountId>>::Balance;
39
40/// The parameters used for pricing on-demand orders.
41#[derive(
42	Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen,
43)]
44pub struct PriceParameters<Balance> {
45	/// The maximum number of outstanding orders beyond which we reject new orders.
46	pub order_cap: u32,
47	/// The number of outstanding orders assumed to be drained per Relay-chain block, per pool
48	/// core.
49	/// ATTENTION: If overestimated, it could lead to lost orders. (#13777)
50	pub drain_rate_per_block: u32,
51	/// The spot price increase per outstanding order in the queue.
52	pub price_step: Perbill,
53	/// The base spot price when the queue is empty.
54	pub base_fee: Balance,
55}
56
57impl<T> Default for PriceParameters<T>
58where
59	T: From<u32>,
60{
61	fn default() -> Self {
62		Self {
63			order_cap: DEFAULT_ORDER_CAP,
64			drain_rate_per_block: DEFAULT_DRAIN_RATE_PER_BLOCK,
65			price_step: Perbill::from_percent(DEFAULT_PRICE_STEP),
66			base_fee: T::from(DEFAULT_BASE_FEE),
67		}
68	}
69}
70
71impl<Balance> PriceParameters<Balance> {
72	pub(crate) fn validate<T>(&self) -> Result<(), Error<T>>
73	where
74		T: Config,
75		T::Currency: Inspect<<T as SConfig>::AccountId, Balance = Balance>,
76		Balance: frame_support::traits::tokens::Balance,
77	{
78		ensure!(
79			T::PricingProvider::spot_price(self, self.order_cap).is_ok(),
80			Error::<T>::OrderPriceCanOverflow
81		);
82		Ok(())
83	}
84}
85
86pub type PriceParametersOf<T> = PriceParameters<BalanceOf<T>>;
87
88/// Data about a placed on-demand order.
89#[derive(
90	Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen,
91)]
92pub struct EnqueuedOrder<RelayBlockNumber> {
93	/// The parachain the order was placed for.
94	pub para_id: TaskId,
95	/// The Relay-chain block number the order came in at.
96	pub ordered_at: RelayBlockNumber,
97}
98
99/// The locally tracked, estimated state of the Relay chain's on-demand order queue.
100#[derive(
101	Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen,
102)]
103pub struct QueueTracker<RelayBlockNumber> {
104	/// The current estimated number of outstanding orders.
105	pub outstanding_orders: u32,
106	/// When the queue state was last updated.
107	pub last_updated: RelayBlockNumber,
108}
109
110pub type QueueTrackerOf<T> = QueueTracker<RelayBlockNumberOf<T>>;
111
112/// Type for getting information about the on-demand pool capacity.
113pub trait PoolCapacityProvider {
114	/// Returns how many cores are dedicated to the on-demand pool.
115	fn pool_cores() -> u32;
116
117	/// Make sure that [`Self::pool_cores`] returns at least `cores`.
118	///
119	/// Used to set up the benchmarks, which need a non-empty pool to place orders in.
120	#[cfg(feature = "runtime-benchmarks")]
121	fn ensure_pool_cores(cores: u32);
122}
123
124/// Type for determining the prices of on-demand orders
125pub trait PricingProvider<T: Balance> {
126	/// Returns the current spot price of an on-demand order.
127	fn spot_price(price_config: &PriceParameters<T>, queue_depth: u32) -> Result<T, DispatchError>;
128}
129
130/// A type implementing the default algorithm for determining the order price.
131pub struct DefaultPricingProvider;
132
133impl<T: Balance> PricingProvider<T> for DefaultPricingProvider {
134	fn spot_price(price_config: &PriceParameters<T>, queue_depth: u32) -> Result<T, DispatchError> {
135		// Every order already outstanding raises the price by `price_step`.
136		let price_adjustment = ensure_pow(
137			FixedU128::one().saturating_add(FixedU128::from_perbill(price_config.price_step)),
138			queue_depth as usize,
139		)?;
140		Ok(price_adjustment.saturating_mul_int(price_config.base_fee))
141	}
142}