1#![cfg_attr(not(feature = "std"), no_std)]
43
44extern crate alloc;
45
46pub use pallet::*;
47
48mod benchmarking;
49mod types;
50mod weightinfo_extension;
51pub mod weights;
52
53#[cfg(test)]
54mod mock;
55#[cfg(test)]
56mod tests;
57
58use alloc::{collections::BTreeMap, vec::Vec};
59use fp_coretime::{TaskId, Timeslice};
60use frame_support::traits::EnsureOrigin;
61use sp_runtime::traits::BlockNumberProvider;
62
63pub use types::*;
64pub use weightinfo_extension::WeightInfoExt;
65pub use weights::WeightInfo;
66
67const LOG_TARGET: &str = "runtime::on-demand";
69
70const DEFAULT_ORDER_CAP: u32 = 100;
73
74const DEFAULT_DRAIN_RATE_PER_BLOCK: u32 = 1;
77
78const DEFAULT_PRICE_STEP: u32 = 3;
81
82const DEFAULT_BASE_FEE: u32 = 10_000_000;
85
86pub type RelayBlockNumberOf<T> =
88 <<T as Config>::RelayBlockNumberProvider as BlockNumberProvider>::BlockNumber;
89
90pub trait QueueOnDemandOrders<RelayBlockNumber> {
95 fn queue_batch(batch: Vec<(TaskId, RelayBlockNumber)>);
100
101 #[cfg(feature = "runtime-benchmarks")]
105 fn ensure_successful_delivery();
106}
107
108impl<RelayBlockNumber> QueueOnDemandOrders<RelayBlockNumber> for () {
109 fn queue_batch(_batch: Vec<(TaskId, RelayBlockNumber)>) {}
110
111 #[cfg(feature = "runtime-benchmarks")]
112 fn ensure_successful_delivery() {}
113}
114
115#[frame_support::pallet]
116pub mod pallet {
117 use super::*;
118 use fp_coretime::revenue::{OnDemandRevenue, RevenueClaim};
119 use frame_support::{
120 pallet_prelude::*,
121 traits::{
122 fungible::{Inspect, Mutate},
123 tokens::{Fortitude::Polite, Preservation::Preserve},
124 },
125 PalletId,
126 };
127 use frame_system::pallet_prelude::*;
128 use sp_arithmetic::traits::{SaturatedConversion, Saturating, Zero};
129 use sp_runtime::traits::AccountIdConversion;
130
131 const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);
132
133 #[pallet::pallet]
134 #[pallet::storage_version(STORAGE_VERSION)]
135 pub struct Pallet<T>(_);
136
137 #[pallet::config]
138 pub trait Config: frame_system::Config {
139 type WeightInfo: WeightInfo;
141
142 type Currency: Mutate<Self::AccountId>;
144
145 type AdminOrigin: EnsureOrigin<Self::RuntimeOrigin>;
147
148 type RelayBlockNumberProvider: BlockNumberProvider;
150
151 type PoolCapacityProvider: PoolCapacityProvider;
153
154 type PricingProvider: PricingProvider<BalanceOf<Self>>;
156
157 type OrderQueue: QueueOnDemandOrders<RelayBlockNumberOf<Self>>;
159
160 #[pallet::constant]
167 type MaxBatchSize: Get<u32>;
168
169 #[pallet::constant]
174 type TimeslicePeriod: Get<RelayBlockNumberOf<Self>>;
175
176 #[pallet::constant]
185 type MaxUnclaimedTimeslices: Get<u32>;
186
187 #[pallet::constant]
189 type PalletId: Get<PalletId>;
190 }
191
192 #[pallet::storage]
194 pub type PriceConfig<T> = StorageValue<_, PriceParametersOf<T>, ValueQuery>;
195
196 #[pallet::storage]
198 pub type QueueState<T> = StorageValue<_, QueueTrackerOf<T>, OptionQuery>;
199
200 #[pallet::storage]
202 pub type PendingBatch<T: Config> = StorageValue<
203 _,
204 BoundedVec<EnqueuedOrder<RelayBlockNumberOf<T>>, T::MaxBatchSize>,
205 ValueQuery,
206 >;
207
208 #[pallet::storage]
214 pub type Revenue<T: Config> = StorageValue<
215 _,
216 BoundedBTreeMap<Timeslice, BalanceOf<T>, T::MaxUnclaimedTimeslices>,
217 ValueQuery,
218 >;
219
220 #[pallet::storage]
227 pub type Enabled<T> = StorageValue<_, bool, ValueQuery>;
228
229 #[pallet::event]
230 #[pallet::generate_deposit(pub(super) fn deposit_event)]
231 pub enum Event<T: Config> {
232 OrderPlaced {
234 para_id: TaskId,
236 spot_price: BalanceOf<T>,
238 ordered_by: T::AccountId,
240 },
241 RevenueClaimed {
243 when: Timeslice,
245 amount: BalanceOf<T>,
247 beneficiary: T::AccountId,
249 },
250 UnexpectedLowFunds {
254 attempted_to_claim: BalanceOf<T>,
256 claimable: BalanceOf<T>,
258 paid_out: BalanceOf<T>,
260 },
261 Enabled,
263 }
264
265 #[pallet::error]
266 pub enum Error<T> {
267 QueueFull,
269 BatchFull,
271 SpotPriceHigherThanMaxAmount,
273 EmptyPool,
275 InsufficientFunds,
280 OrderPriceCanOverflow,
282 Disabled,
284 }
285
286 #[pallet::hooks]
287 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
288 fn on_initialize(_now: BlockNumberFor<T>) -> Weight {
289 T::WeightInfo::on_finalize_block_fixed()
290 }
291
292 fn integrity_test() {
293 assert!(
294 T::MaxUnclaimedTimeslices::get() > 1,
295 "`MaxUnclaimedTimeslices` must allow for the revenue of at least two timeslices"
296 );
297 assert!(
298 T::TimeslicePeriod::get() > 0u32.into(),
299 "The length of a timeslice cannot be 0"
300 );
301 }
302
303 fn on_finalize(_now: BlockNumberFor<T>) {
304 let batch = PendingBatch::<T>::take().into_inner();
305 if batch.is_empty() {
306 return;
307 }
308
309 T::OrderQueue::queue_batch(
310 batch.into_iter().map(|order| (order.para_id, order.ordered_at)).collect(),
311 );
312 }
313
314 #[cfg(feature = "try-runtime")]
315 fn try_state(_now: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
316 Self::do_try_state()
317 }
318 }
319
320 #[pallet::call(weight(<T as Config>::WeightInfo))]
321 impl<T: Config> Pallet<T> {
322 #[pallet::call_index(0)]
327 pub fn configure(
328 origin: OriginFor<T>,
329 config: PriceParametersOf<T>,
330 ) -> DispatchResultWithPostInfo {
331 T::AdminOrigin::ensure_origin_or_root(origin)?;
332 config.validate::<T>()?;
333 PriceConfig::<T>::put(config);
334 Ok(Pays::No.into())
335 }
336
337 #[pallet::call_index(1)]
346 #[pallet::weight(
347 <T as Config>::WeightInfo::place_order()
348 .saturating_add(T::WeightInfo::on_finalize_block_per_order())
349 )]
350 pub fn place_order(
351 origin: OriginFor<T>,
352 para_id: TaskId,
353 max_amount: BalanceOf<T>,
354 ) -> DispatchResult {
355 let who = ensure_signed(origin)?;
356 Self::do_place_order(who, para_id, max_amount)
358 }
359
360 #[pallet::call_index(2)]
369 pub fn enable(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
370 T::AdminOrigin::ensure_origin_or_root(origin)?;
371 if !Enabled::<T>::get() {
372 Enabled::<T>::put(true);
373 Self::deposit_event(Event::<T>::Enabled);
374 }
375 Ok(Pays::No.into())
376 }
377 }
378
379 #[cfg(any(feature = "try-runtime", test))]
380 impl<T: Config> Pallet<T> {
381 pub(crate) fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
383 let revenue = Revenue::<T>::get();
384
385 let now = T::RelayBlockNumberProvider::current_block_number();
387 let current: Timeslice = (now / T::TimeslicePeriod::get()).saturated_into();
388 ensure!(
389 revenue.last_key_value().map_or(true, |(&when, _)| when <= current),
390 "Revenue is booked against a timeslice which has not started yet"
391 );
392
393 let booked = revenue
396 .values()
397 .fold(BalanceOf::<T>::zero(), |booked, &amount| booked.saturating_add(amount));
398 let reducible = T::Currency::reducible_balance(&Self::account_id(), Preserve, Polite);
399 ensure!(reducible >= booked, "The pot holds less than can be paid out as revenue");
400
401 Ok(())
402 }
403 }
404
405 impl<T: Config> Pallet<T> {
406 pub fn account_id() -> T::AccountId {
408 T::PalletId::get().into_account_truncating()
409 }
410
411 pub(crate) fn do_place_order(
412 who: T::AccountId,
413 para_id: TaskId,
414 max_amount: BalanceOf<T>,
415 ) -> DispatchResult {
416 ensure!(Enabled::<T>::get(), Error::<T>::Disabled);
419 ensure!(
421 PendingBatch::<T>::decode_len().unwrap_or(0) < T::MaxBatchSize::get() as usize,
422 Error::<T>::BatchFull
423 );
424 ensure!(
426 T::Currency::reducible_balance(&who, Preserve, Polite) >= max_amount,
427 Error::<T>::InsufficientFunds
428 );
429
430 let pool_cores = T::PoolCapacityProvider::pool_cores();
431 ensure!(pool_cores > 0, Error::<T>::EmptyPool);
433
434 let now = T::RelayBlockNumberProvider::current_block_number();
435 let mut queue_state = QueueState::<T>::get()
436 .unwrap_or(QueueTracker { outstanding_orders: 0, last_updated: now });
437 let pricing_config = PriceConfig::<T>::get();
438
439 let elapsed = now.saturating_sub(queue_state.last_updated).saturated_into();
441
442 let drained_orders = pricing_config
443 .drain_rate_per_block
444 .saturating_mul(elapsed)
445 .saturating_mul(pool_cores);
446 let outstanding_orders = queue_state.outstanding_orders.saturating_sub(drained_orders);
447
448 ensure!(outstanding_orders < pricing_config.order_cap, Error::<T>::QueueFull);
449
450 let spot_price = T::PricingProvider::spot_price(&pricing_config, outstanding_orders)?;
451
452 ensure!(spot_price <= max_amount, Error::<T>::SpotPriceHigherThanMaxAmount);
453
454 T::Currency::transfer(&who, &Self::account_id(), spot_price, Preserve)?;
457 let when: Timeslice = (now / T::TimeslicePeriod::get()).saturated_into();
458 Self::book_revenue(when, spot_price);
459
460 PendingBatch::<T>::try_mutate(|batch| {
462 batch
463 .try_push(EnqueuedOrder { para_id, ordered_at: now })
464 .map_err(|_| Error::<T>::BatchFull)
467 })?;
468
469 queue_state.outstanding_orders = outstanding_orders.saturating_add(1);
470 queue_state.last_updated = now;
471 QueueState::<T>::put(queue_state);
472
473 Self::deposit_event(Event::<T>::OrderPlaced { para_id, spot_price, ordered_by: who });
474
475 Ok(())
476 }
477
478 fn book_revenue(when: Timeslice, amount: BalanceOf<T>) {
480 let booked = Revenue::<T>::get().try_mutate(|revenue| {
481 revenue.entry(when).or_insert_with(Zero::zero).saturating_accrue(amount);
482 if revenue.len() <= T::MaxUnclaimedTimeslices::get() as usize {
483 return;
484 }
485
486 let Some((overdue, overdue_amount)) = revenue.pop_first() else { return };
489 log::warn!(
490 target: LOG_TARGET,
491 "Unclaimed revenue of timeslice {overdue} merged into a later timeslice",
492 );
493 if let Some(mut oldest) = revenue.first_entry() {
497 oldest.get_mut().saturating_accrue(overdue_amount);
498 }
499 });
500 match booked {
501 Some(revenue) => Revenue::<T>::put(revenue),
502 None => {
504 frame_support::defensive!("Revenue could not be booked");
505 },
506 }
507 }
508 }
509
510 impl<T: Config> OnDemandRevenue<BalanceOf<T>, T::AccountId> for Pallet<T> {
511 fn is_enabled() -> bool {
512 Enabled::<T>::get()
513 }
514
515 fn claim_revenue(
516 up_to: Timeslice,
517 beneficiary: &T::AccountId,
518 ) -> RevenueClaim<BalanceOf<T>> {
519 let (paid, claimable) = Self::do_claim_revenue(up_to, beneficiary);
520 RevenueClaim { paid, weight: <T as Config>::WeightInfo::claim_revenue(claimable) }
521 }
522 }
523
524 impl<T: Config> Pallet<T> {
525 fn do_claim_revenue(
528 up_to: Timeslice,
529 beneficiary: &T::AccountId,
530 ) -> (BTreeMap<Timeslice, BalanceOf<T>>, u32) {
531 let mut revenue = Revenue::<T>::get().into_inner();
532 let pot = Self::account_id();
533 let maximum_transfer_amount = T::Currency::reducible_balance(&pot, Preserve, Polite);
534
535 let mut claimable_entries = 0u32;
536 let mut total = BalanceOf::<T>::zero();
537 let mut total_ignoring_max_transfer_amount = BalanceOf::<T>::zero();
538 let mut paid = BTreeMap::new();
539 let mut is_enough_funds_for_transfer = true;
540 for (&when, &amount) in revenue.range(..=up_to) {
541 claimable_entries += 1;
542
543 total_ignoring_max_transfer_amount =
544 total_ignoring_max_transfer_amount.saturating_add(amount);
545
546 if total_ignoring_max_transfer_amount > maximum_transfer_amount {
547 is_enough_funds_for_transfer = false;
548 }
549
550 if is_enough_funds_for_transfer {
551 total = total_ignoring_max_transfer_amount;
552 paid.insert(when, amount);
553 }
554 }
555
556 if claimable_entries == 0 {
559 return (BTreeMap::from([(up_to, Zero::zero())]), 0);
560 }
561
562 if is_enough_funds_for_transfer {
563 paid.entry(up_to).or_default();
564 } else {
565 log::error!(
566 target: LOG_TARGET,
567 "The pot holds less than the {:?} of revenue booked up to timeslice {}; paying \
568 out {:?} instead.",
569 total_ignoring_max_transfer_amount, up_to, total,
570 );
571 Self::deposit_event(Event::<T>::UnexpectedLowFunds {
572 attempted_to_claim: total_ignoring_max_transfer_amount,
573 claimable: maximum_transfer_amount,
574 paid_out: total,
575 });
576 }
577
578 if !total.is_zero() {
579 if let Err(err) = T::Currency::transfer(&pot, beneficiary, total, Preserve) {
580 log::error!(
581 target: LOG_TARGET,
582 "Paying out {total:?} of revenue failed: {err:?}",
583 );
584 return (BTreeMap::new(), claimable_entries);
585 }
586 }
587
588 if let Some((&last_paid, _)) = paid.last_key_value() {
590 revenue = revenue.split_off(&last_paid);
591 revenue.remove(&last_paid);
594 }
595 Revenue::<T>::put(
596 BoundedBTreeMap::try_from(revenue)
597 .expect("entries were only removed from a bounded map; qed"),
598 );
599
600 for (&when, &amount) in paid.iter().filter(|(_, amount)| !amount.is_zero()) {
601 Self::deposit_event(Event::<T>::RevenueClaimed {
602 when,
603 amount,
604 beneficiary: beneficiary.clone(),
605 });
606 }
607
608 (paid, claimable_entries)
609 }
610 }
611}