referrerpolicy=no-referrer-when-downgrade

pallet_on_demand_para/
lib.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//! # On-demand Coretime pallet
19//!
20//! Sale of on-demand Coretime from the Coretime chain.
21//!
22//! The Relay chain owns the actual on-demand order queue; this pallet is a front-end for it which
23//! lives alongside [`pallet-broker`](https://docs.rs/pallet-broker) on the Coretime chain:
24//!
25//! - Users call [`Pallet::place_order`] here and pay the spot price in the local currency.
26//! - Because the real queue is one hop away, the spot price cannot be read directly. Instead the
27//!   pallet keeps a local estimate of the queue's depth ([`QueueState`]) which grows with every
28//!   order placed and shrinks by an assumed drain rate per Relay-chain block. The spot price is
29//!   derived from that estimate using [`PriceParameters`].
30//! - Orders accepted within a block are accumulated in [`PendingBatch`] and forwarded to the Relay
31//!   chain in one go on finalization, via [`QueueOnDemandOrders`].
32//! - The spot prices paid are collected in the pallet's pot and booked as [`Revenue`] against the
33//!   timeslice the order was placed in. `pallet-broker` claims the revenue of each timeslice once
34//!   it has ended, along with that of any earlier timeslice which could not be paid out before,
35//!   through [`fp_coretime::revenue::OnDemandRevenue`], and pays it out to the contributors to the
36//!   Instantaneous Coretime Pool.
37//!
38//!   NOTE: It is important to make sure that this pallet is ordered before `ParachainSystem` in the
39//!   runtime - otherwise the messages will not be sent in the block in which they are created,
40//!   introducing additional latency.
41
42#![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
67/// The logging target of this pallet.
68const LOG_TARGET: &str = "runtime::on-demand";
69
70/// The default maximum number of outstanding on-demand orders beyond which new orders will be
71/// rejected.
72const DEFAULT_ORDER_CAP: u32 = 100;
73
74/// The default number of orders assumed to be drained out of the order queue per Relay-chain
75/// block.
76const DEFAULT_DRAIN_RATE_PER_BLOCK: u32 = 1;
77
78/// The default percentage by which every additional on-demand order in the queue increases
79/// the spot price for new orders.
80const DEFAULT_PRICE_STEP: u32 = 3;
81
82/// The default base fee for an on-demand order, which will be the spot price when the queue
83/// is empty.
84const DEFAULT_BASE_FEE: u32 = 10_000_000;
85
86/// The Relay-chain block number, as seen by this pallet.
87pub type RelayBlockNumberOf<T> =
88	<<T as Config>::RelayBlockNumberProvider as BlockNumberProvider>::BlockNumber;
89
90/// Instructs the Relay chain to enqueue a batch of on-demand orders.
91///
92/// On the Coretime chain this is implemented by sending an XCM `Transact` to the Relay chain's
93/// coretime pallet.
94pub trait QueueOnDemandOrders<RelayBlockNumber> {
95	/// Enqueue `batch` on the Relay chain.
96	///
97	/// Each entry is the parachain the order was placed for and the Relay-chain block number it was
98	/// ordered at.
99	fn queue_batch(batch: Vec<(TaskId, RelayBlockNumber)>);
100
101	/// Make sure that the batches queued afterwards reach the Relay chain.
102	///
103	/// Used to set up the benchmarks, so that they measure a successful delivery.
104	#[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		/// Weight information for all calls of this pallet.
140		type WeightInfo: WeightInfo;
141
142		/// Currency used to pay for on-demand Coretime.
143		type Currency: Mutate<Self::AccountId>;
144
145		/// The origin for administrating this pallet.
146		type AdminOrigin: EnsureOrigin<Self::RuntimeOrigin>;
147
148		/// Provider of the current Relay-chain block number.
149		type RelayBlockNumberProvider: BlockNumberProvider;
150
151		/// Provider of the on-demand pool capacity.
152		type PoolCapacityProvider: PoolCapacityProvider;
153
154		/// Provider of the order pricing algorithm.
155		type PricingProvider: PricingProvider<BalanceOf<Self>>;
156
157		/// Used to instruct the Relay chain to enqueue the orders placed here.
158		type OrderQueue: QueueOnDemandOrders<RelayBlockNumberOf<Self>>;
159
160		/// Maximum pending batch size.
161		/// NOTE: Since we don't do chunking, this number of pending orders needs to fit within a
162		/// single XCM message. This way `on_finalize` will never send more than one message.
163		/// Since this pallet is intended to be a temporary solution, and current (as of September
164		/// 2026) usage of the on-demand feature is low to moderate, it is expected not to be
165		/// necessary to extend this functionality to allow more orders in a single block.
166		#[pallet::constant]
167		type MaxBatchSize: Get<u32>;
168
169		/// The number of Relay-chain blocks in a timeslice.
170		///
171		/// Revenue is booked against the timeslice an order was placed in, so this must match the
172		/// `TimeslicePeriod` of the `pallet-broker` instance claiming it.
173		#[pallet::constant]
174		type TimeslicePeriod: Get<RelayBlockNumberOf<Self>>;
175
176		/// The maximum number of timeslices whose unclaimed revenue is kept apart.
177		///
178		/// Normally only the revenue of the current timeslice and of the one which has just ended
179		/// is unclaimed, but more builds up while the revenue cannot be paid out. Once this many
180		/// timeslices have unclaimed revenue, the revenue of the oldest one is merged into the
181		/// next oldest one, so it is never lost, but is attributed to a later timeslice. This may
182		/// cause the revenue to be paid to a different set of contributors, which is why this
183		/// number should be big enough to minimize the probability of that happening.
184		#[pallet::constant]
185		type MaxUnclaimedTimeslices: Get<u32>;
186
187		/// Identifier from which the internal Pot is generated.
188		#[pallet::constant]
189		type PalletId: Get<PalletId>;
190	}
191
192	/// The configuration used for pricing on-demand Coretime orders.
193	#[pallet::storage]
194	pub type PriceConfig<T> = StorageValue<_, PriceParametersOf<T>, ValueQuery>;
195
196	/// The local estimate of the Relay chain's on-demand order queue.
197	#[pallet::storage]
198	pub type QueueState<T> = StorageValue<_, QueueTrackerOf<T>, OptionQuery>;
199
200	/// Orders placed in the current block, forwarded to the Relay chain on finalization.
201	#[pallet::storage]
202	pub type PendingBatch<T: Config> = StorageValue<
203		_,
204		BoundedVec<EnqueuedOrder<RelayBlockNumberOf<T>>, T::MaxBatchSize>,
205		ValueQuery,
206	>;
207
208	/// Revenue from on-demand sales which has not been claimed yet, by the timeslice the orders
209	/// were placed in.
210	///
211	/// The funds themselves sit in the pallet's pot until they are claimed through
212	/// [`OnDemandRevenue::claim_revenue`].
213	#[pallet::storage]
214	pub type Revenue<T: Config> = StorageValue<
215		_,
216		BoundedBTreeMap<Timeslice, BalanceOf<T>, T::MaxUnclaimedTimeslices>,
217		ValueQuery,
218	>;
219
220	/// Whether on-demand Coretime is sold here.
221	///
222	/// Orders are only accepted once it is, as the revenue from them is only claimed through
223	/// [`OnDemandRevenue::claim_revenue`] once it is; otherwise it would never be distributed.
224	///
225	/// It is `false` until enabled with [`Pallet::enable`], and stays `true` from then on.
226	#[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		/// An on-demand order was placed at `spot_price` by `ordered_by`.
233		OrderPlaced {
234			/// The parachain the order was placed for.
235			para_id: TaskId,
236			/// The spot price that was paid for the order.
237			spot_price: BalanceOf<T>,
238			/// The account that placed and paid for the order.
239			ordered_by: T::AccountId,
240		},
241		/// Revenue from on-demand sales was claimed and paid out to `beneficiary`.
242		RevenueClaimed {
243			/// The timeslice the orders the revenue came from were placed in.
244			when: Timeslice,
245			/// The amount that was paid out.
246			amount: BalanceOf<T>,
247			/// The account the revenue was paid out to.
248			beneficiary: T::AccountId,
249		},
250		/// The funds in pot were unexpectedly too low to handle a revenue claim. The revenue of
251		/// the oldest timeslices was paid out as far as the funds allowed; the rest stays booked
252		/// until the pot is topped up.
253		UnexpectedLowFunds {
254			/// The amount that was being claimed.
255			attempted_to_claim: BalanceOf<T>,
256			/// The claimable amount in the pot.
257			claimable: BalanceOf<T>,
258			/// The amount that was actually paid out.
259			paid_out: BalanceOf<T>,
260		},
261		/// On-demand Coretime sales were enabled.
262		Enabled,
263	}
264
265	#[pallet::error]
266	pub enum Error<T> {
267		/// The estimated on-demand order queue has reached its order cap.
268		QueueFull,
269		/// The batch of orders pending to be sent to the Relay chain is full.
270		BatchFull,
271		/// The spot price was higher than the maximum amount declared in `place_order`.
272		SpotPriceHigherThanMaxAmount,
273		/// The on-demand pool has no cores assigned.
274		EmptyPool,
275		/// The funds in the account submitting the order were not sufficient to cover the declared
276		/// `max_amount`.
277		/// Note: this can be returned even if the funds are sufficient to cover the actual spot
278		/// price.
279		InsufficientFunds,
280		/// The price parameters allow the price to overflow with too many outstanding orders.
281		OrderPriceCanOverflow,
282		/// On-demand Coretime sales are disabled.
283		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		/// Configure the pallet.
323		///
324		/// - `origin`: Must be Root or pass `AdminOrigin`.
325		/// - `config`: The configuration for this pallet.
326		#[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		/// Place an on-demand Coretime order for `para_id`.
338		///
339		/// The caller is charged the current estimated spot price, which must not exceed
340		/// `max_amount`. The order is forwarded to the Relay chain at the end of the block.
341		///
342		/// - `origin`: Must be a signed account with enough funds to pay the spot price.
343		/// - `para_id`: The parachain to schedule.
344		/// - `max_amount`: The maximum spot price the caller is willing to pay.
345		#[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			// TODO(ahm-v2): add a check that the para_id is valid
357			Self::do_place_order(who, para_id, max_amount)
358		}
359
360		/// Enable on-demand Coretime sales.
361		///
362		/// Until they are enabled, no orders are accepted. Once they are, they cannot be disabled
363		/// again, and calling this does nothing.
364		///
365		/// This should be called after the AHM v2 migration is completed.
366		///
367		/// - `origin`: Must be Root or pass `AdminOrigin`.
368		#[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		/// Check the invariants of the pallet's storage.
382		pub(crate) fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
383			let revenue = Revenue::<T>::get();
384
385			// No revenue is booked for the future.
386			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			// The pot holds the revenue booked. If it does not, the revenue is held back until the
394			// pot is topped up.
395			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		/// The account holding the revenue from on-demand Coretime sales.
407		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			// Fail early if the parachain does not yet accept orders (so the migration is not yet
417			// complete).
418			ensure!(Enabled::<T>::get(), Error::<T>::Disabled);
419			// Fail early if the batch is already full.
420			ensure!(
421				PendingBatch::<T>::decode_len().unwrap_or(0) < T::MaxBatchSize::get() as usize,
422				Error::<T>::BatchFull
423			);
424			// Fail early if the account can't cover the declared max_amount.
425			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			// Fail early if the pool is empty.
432			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			// Assume the Relay chain has drained part of the queue since we last looked at it.
440			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			// Charge the sending account the spot price. The funds stay in the pot until the
455			// revenue they represent is claimed.
456			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			// Add the order to the batch that gets sent to the Relay chain on finalization.
461			PendingBatch::<T>::try_mutate(|batch| {
462				batch
463					.try_push(EnqueuedOrder { para_id, ordered_at: now })
464					// should not happen (we check if it's full at the start), but won't hurt to
465					// handle the error
466					.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		/// Book `amount` of revenue against timeslice `when`.
479		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				// The revenue of the oldest timeslice has not been claimed for too long; keep it
487				// with the next oldest one.
488				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				// This will never lose revenue: if we had to remove an entry above, the number of
494				// entries must have been over the limit, which is at least 2. So there are at least
495				// two entries left at this point, and first_entry will never return None.
496				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				// At most one timeslice too many is booked, and then the oldest one is merged away.
503				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		/// Implements [`OnDemandRevenue::claim_revenue`], returning the paid out revenue and the
526		/// number of timeslices whose revenue was claimable.
527		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			// Early return when nothing to be claimed: everything up to `up_to` is already paid
557			// out, so it is settled even without revenue.
558			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			// Everything up to the last timeslice paid out has been claimed, so drop it.
589			if let Some((&last_paid, _)) = paid.last_key_value() {
590				revenue = revenue.split_off(&last_paid);
591				// In the unlikely case that last_paid is Timeslice::MAX, doing this separately
592				// instead of splitting at last_paid + 1 avoids an overflow.
593				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}