referrerpolicy=no-referrer-when-downgrade

pallet_on_demand_para/
benchmarking.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#![cfg(feature = "runtime-benchmarks")]
19
20use super::*;
21
22use crate::{Pallet as OnDemand, DEFAULT_BASE_FEE, DEFAULT_PRICE_STEP};
23use alloc::collections::BTreeMap;
24use fp_coretime::revenue::OnDemandRevenue;
25use frame_benchmarking::v2::*;
26use frame_support::{
27	pallet_prelude::*,
28	traits::{
29		fungible::{Inspect, Mutate},
30		Hooks,
31	},
32};
33use frame_system::{pallet_prelude::*, Pallet as System, RawOrigin};
34use sp_runtime::{Perbill, Saturating};
35
36#[benchmarks]
37mod benches {
38	use super::*;
39	#[cfg(not(feature = "std"))]
40	use num_traits::float::FloatCore;
41
42	#[benchmark]
43	fn configure() -> Result<(), BenchmarkError> {
44		let config = PriceParameters {
45			order_cap: 80,
46			drain_rate_per_block: 2,
47			price_step: Perbill::from_percent(2),
48			base_fee: BalanceOf::<T>::from(1_000_000u32),
49		};
50
51		let origin =
52			T::AdminOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
53
54		#[extrinsic_call]
55		_(origin as T::RuntimeOrigin, config.clone());
56
57		assert_eq!(PriceConfig::<T>::get(), config);
58
59		Ok(())
60	}
61
62	#[benchmark]
63	fn enable() -> Result<(), BenchmarkError> {
64		let origin =
65			T::AdminOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
66
67		// Measure actually enabling on-demand Coretime, rather than the call doing nothing.
68		Enabled::<T>::kill();
69
70		#[extrinsic_call]
71		_(origin as T::RuntimeOrigin);
72
73		assert!(Enabled::<T>::get());
74
75		Ok(())
76	}
77
78	#[benchmark]
79	fn place_order() -> Result<(), BenchmarkError> {
80		let current_block = BlockNumberFor::<T>::from(1u32);
81		System::<T>::set_block_number(current_block);
82
83		let base_fee = BalanceOf::<T>::from(DEFAULT_BASE_FEE);
84
85		let caller: T::AccountId = whitelisted_caller();
86		T::Currency::set_balance(
87			&caller.clone(),
88			T::Currency::minimum_balance().saturating_add(base_fee),
89		);
90		// Store minimum balance in the pallet's account, so that small transfers to it don't fail
91		T::Currency::set_balance(&OnDemand::<T>::account_id(), T::Currency::minimum_balance());
92		// Orders can only be placed while the pool has some cores
93		T::PoolCapacityProvider::ensure_pool_cores(1);
94		// Orders can only be placed while on-demand Coretime is sold
95		Enabled::<T>::put(true);
96
97		// The order is booked against timeslice `max_unclaimed`, while the revenue of every
98		// older timeslice is still unclaimed. The history is full, so booking the order takes
99		// the longest path: a record is added for the new timeslice, and the oldest one is pushed
100		// out and merged into the next oldest.
101		let max_unclaimed = T::MaxUnclaimedTimeslices::get();
102		T::RelayBlockNumberProvider::set_block_number(
103			T::TimeslicePeriod::get().saturating_mul(max_unclaimed.into()),
104		);
105		let revenue: BTreeMap<_, _> = (0..max_unclaimed).map(|when| (when, base_fee)).collect();
106		Revenue::<T>::put(
107			BoundedBTreeMap::try_from(revenue).expect("bounded by MaxUnclaimedTimeslices; qed"),
108		);
109
110		let _ = OnDemand::<T>::on_initialize(current_block);
111
112		#[block]
113		{
114			OnDemand::<T>::place_order(
115				T::RuntimeOrigin::from(RawOrigin::Signed(caller.clone())),
116				2000,
117				base_fee,
118			)
119			.map_err(|_| BenchmarkError::Stop("place_order failed"))?;
120		}
121
122		let revenue = Revenue::<T>::get();
123		assert_eq!(revenue.len(), max_unclaimed as usize);
124		assert_eq!(revenue.last_key_value().map(|(&when, _)| when), Some(max_unclaimed));
125		// The oldest timeslice's revenue was merged into the next oldest one's.
126		assert_eq!(
127			revenue.first_key_value().map(|(&when, &amount)| (when, amount)),
128			Some((1, base_fee.saturating_mul(2u32.into())))
129		);
130
131		Ok(())
132	}
133
134	/// Benchmark the `on_finalize` hook scaling with number of orders.
135	///
136	/// This benchmark measures the marginal computational cost of adding orders
137	/// to a block during finalization.
138	///
139	/// We do not benchmark with zero orders, since that would skew the results by not generating an
140	/// outgoing message. We want the linear part to reflect the additional overhead of processing
141	/// more orders, and the fixed part to reflect sending a message - so we need all cases being
142	/// benchmarked to send exactly one message.
143	///
144	/// ## Parameters:
145	/// - `n`: Number of transactions in the block (1-100)
146	///
147	/// ## Test Setup:
148	/// - Initializes the account balance with enough funds to cover all orders.
149	/// - Places `n` orders.
150	#[benchmark(pov_mode = Measured)]
151	fn on_finalize_with_orders(n: Linear<1, 100>) -> Result<(), BenchmarkError> {
152		let current_block = BlockNumberFor::<T>::from(1u32);
153		System::<T>::set_block_number(current_block);
154
155		let base_fee = BalanceOf::<T>::from(DEFAULT_BASE_FEE);
156		let step = DEFAULT_PRICE_STEP as f32 / 100.0;
157
158		// k-th order's price will be base_fee * (1 + step)^k
159		// Thus, the cost of n orders will be the base_fee times 1 + x + x^2 + ... + x^(n-1),
160		// where x = 1 + step. Such a sum equals (x^n - 1) / (x - 1), which in our case gives
161		// ((1 + step)^n - 1) / step.
162		// We add n to account for possible rounding errors at each order.
163		let multiplier = ((1.0 + step).powi(n as i32) - 1.0) / step + n as f32;
164
165		let required_amount = base_fee
166			.checked_mul(&BalanceOf::<T>::from(multiplier.ceil() as u32))
167			.expect("the price of n orders should fit within the balance type");
168
169		let max_price = base_fee
170			.checked_mul(&BalanceOf::<T>::from((1.0 + step).powi(n as i32).ceil() as u32))
171			.expect("maximum price should fit within the balance type");
172
173		let caller: T::AccountId = whitelisted_caller();
174		T::Currency::set_balance(
175			&caller.clone(),
176			T::Currency::minimum_balance().saturating_add(required_amount),
177		);
178		// Store minimum balance in the pallet's account, so that small transfers to it don't fail
179		T::Currency::set_balance(&OnDemand::<T>::account_id(), T::Currency::minimum_balance());
180		// Orders can only be placed while the pool has some cores
181		T::PoolCapacityProvider::ensure_pool_cores(1);
182		// Orders can only be placed while on-demand Coretime is sold
183		Enabled::<T>::put(true);
184
185		// Pre-populate InflightTransactions with n transactions of fixed size
186		if n > 0 {
187			// Initialize block
188			let _ = OnDemand::<T>::on_initialize(current_block);
189
190			for _ in 0..n {
191				OnDemand::<T>::place_order(
192					T::RuntimeOrigin::from(RawOrigin::Signed(caller.clone())),
193					From::from(2000 + n),
194					max_price,
195				)
196				.map_err(|_| BenchmarkError::Stop("place_order failed"))?;
197			}
198		}
199
200		// Measure sending the batch, not failing to send it
201		T::OrderQueue::ensure_successful_delivery();
202
203		#[block]
204		{
205			// Measure only the finalization cost with n transactions of fixed size
206			let _ = OnDemand::<T>::on_finalize(current_block);
207		}
208
209		Ok(())
210	}
211
212	/// Benchmark claiming the revenue accumulated from on-demand sales of `n` timeslices.
213	///
214	/// The revenue history is always full, so the timeslices which are not claimed are still read
215	/// and written back.
216	#[benchmark]
217	fn claim_revenue(
218		n: Linear<0, { T::MaxUnclaimedTimeslices::get() }>,
219	) -> Result<(), BenchmarkError> {
220		let timeslices = T::MaxUnclaimedTimeslices::get();
221		let per_timeslice = BalanceOf::<T>::from(DEFAULT_BASE_FEE);
222		let total = per_timeslice.saturating_mul(timeslices.into());
223		let claimed = per_timeslice.saturating_mul(n.into());
224
225		// The pot holds the accumulated revenue on top of its existential deposit.
226		T::Currency::set_balance(
227			&OnDemand::<T>::account_id(),
228			T::Currency::minimum_balance().saturating_add(total),
229		);
230		let beneficiary: T::AccountId = account("beneficiary", 0, 0);
231		T::Currency::set_balance(&beneficiary, T::Currency::minimum_balance());
232
233		// Timeslices `1..=timeslices`, of which `1..=n` are claimed.
234		let revenue: BTreeMap<_, _> = (1..=timeslices).map(|when| (when, per_timeslice)).collect();
235		Revenue::<T>::put(
236			BoundedBTreeMap::try_from(revenue).expect("bounded by MaxUnclaimedTimeslices; qed"),
237		);
238
239		#[block]
240		{
241			<OnDemand<T> as OnDemandRevenue<_, _>>::claim_revenue(n, &beneficiary);
242		}
243
244		assert_eq!(Revenue::<T>::get().len() as u32, timeslices - n);
245		assert_eq!(T::Currency::balance(&beneficiary), T::Currency::minimum_balance() + claimed);
246
247		Ok(())
248	}
249
250	// Implements a test for each benchmark. Execute with:
251	// `cargo test -p pallet-on-demand-para --features runtime-benchmarks`.
252	impl_benchmark_test_suite!(OnDemand, crate::mock::new_test_ext(), crate::mock::Test);
253}