referrerpolicy=no-referrer-when-downgrade

pallet_revive/vm/
runtime_costs.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
18use crate::{
19	Config, H256,
20	access_list::{StorageOp, Warmth},
21	limits,
22	metering::Token,
23	weightinfo_extension::OnFinalizeBlockParts,
24	weights::WeightInfo,
25};
26use frame_support::{
27	traits::Get,
28	weights::{Weight, constants::WEIGHT_REF_TIME_PER_SECOND},
29};
30
31/// Current approximation of the gas/s consumption considering
32/// EVM execution over compiled WASM (on 4.4Ghz CPU).
33/// Given the 2000ms Weight, from which 75% only are used for transactions,
34/// the total EVM execution gas limit is: GAS_PER_SECOND * 2 * 0.75 ~= 60_000_000.
35const GAS_PER_SECOND: u64 = 40_000_000;
36
37/// Approximate ratio of the amount of Weight per Gas.
38/// u64 works for approximations because Weight is a very small unit compared to
39/// gas.
40const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
41
42/// Smallest init code length the `evm_instantiate*` benchmarks run at.
43pub const BENCH_MIN_EVM_INIT_CODE_LEN: u32 = 1;
44
45#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
46#[derive(Copy, Clone)]
47pub enum RuntimeCosts {
48	/// Base Weight of calling a host function.
49	HostFn,
50	/// Weight of exposing zeroed EVM memory and, when needed, allocating a replacement buffer.
51	/// Both sizes are in 32-byte words. Zero allocation words means the existing buffer is kept.
52	EvmMemoryGrow { words: u32, allocation_words: u32 },
53	/// Weight of allocating and copying EVM output data, in bytes.
54	EvmMemoryCopyOut(u32),
55	/// Per-byte weight of copying data into EVM memory; the op-code pays its fixed cost.
56	EvmCopyToContract(u32),
57	/// Weight charged for executing the extcodecopy instruction.
58	ExtCodeCopy(u32),
59	/// Weight charged for copying data from the sandbox.
60	CopyFromContract(u32),
61	/// Weight charged for copying data to the sandbox.
62	CopyToContract(u32),
63	/// Weight of calling `seal_call_data_load``.
64	CallDataLoad,
65	/// Weight of calling `seal_call_data_copy`.
66	CallDataCopy(u32),
67	/// Weight of calling `seal_caller`.
68	Caller,
69	/// Weight of calling `seal_call_data_size`.
70	CallDataSize,
71	/// Weight of calling `seal_return_data_size`.
72	ReturnDataSize,
73	/// Weight of calling `toAccountId` on the `System` pre-compile.
74	ToAccountId,
75	/// Weight of calling `seal_origin`.
76	Origin,
77	/// Weight of calling `seal_code_hash`.
78	CodeHash,
79	/// Weight of calling `ownCodeHash` on the `System` pre-compile.
80	OwnCodeHash,
81	/// Weight of calling `seal_code_size`.
82	CodeSize,
83	/// Weight of calling `callerIsOrigin` on the `System` pre-compile.
84	CallerIsOrigin,
85	/// Weight of calling `callerIsRoot` on the `System` pre-compile.
86	CallerIsRoot,
87	/// Weight of calling `originIsRoot` on the `System` pre-compile.
88	OriginIsRoot,
89	/// Weight of calling `seal_address`.
90	Address,
91	/// Weight of calling `seal_ref_time_left`.
92	RefTimeLeft,
93	/// Weight of calling `weightLeft` on the `System` pre-compile.
94	WeightLeft,
95	/// Weight of calling `seal_balance`.
96	Balance,
97	/// Weight of calling `seal_balance_of`.
98	BalanceOf,
99	/// Weight of calling `seal_value_transferred`.
100	ValueTransferred,
101	/// Weight of calling `minimumBalance` on the `System` pre-compile.
102	MinimumBalance,
103	/// Weight of calling `seal_block_number`.
104	BlockNumber,
105	/// Weight of calling `seal_block_hash`.
106	BlockHash,
107	/// Weight of calling `seal_block_author`.
108	BlockAuthor,
109	/// Weight of calling `seal_gas_price`.
110	GasPrice,
111	/// Weight of calling `seal_base_fee`.
112	BaseFee,
113	/// Weight of calling `seal_now`.
114	Now,
115	/// Weight of calling `seal_gas_limit`.
116	GasLimit,
117	/// Weight of calling `seal_terminate`.
118	Terminate { code_removed: bool },
119	/// Weight of calling `seal_deposit_event` with the given number of topics and event size.
120	///
121	/// `len` is the size of the data field. The per-byte charges for storing the event and adding
122	/// it to the receipt apply to the topic bytes (32 per topic) plus `len`, the byte count the
123	/// `on_finalize_per_event_data` benchmark measures. The topic count is clamped to
124	/// [`limits::NUM_EVENT_TOPICS`] for these charges. The event sink only accepts
125	/// [`ContractLogTopics`](crate::ContractLogTopics), which holds at most that many topics, so
126	/// no stored event has more topics than that. A caller that passes the number of topics it
127	/// stores as `num_topic` is charged for every stored topic byte.
128	DepositEvent { num_topic: u32, len: u32 },
129	/// Weight of `seal_set_storage` / `seal_set_transient_storage`. `kind` picks
130	/// the persistent (cold/hot) or transient bench.
131	SetStorage { new_bytes: u32, old_bytes: u32, kind: StorageAccessKind },
132	/// Weight of the `clearStorage` precompile / `seal_clear_transient_storage`.
133	ClearStorage { len: u32, kind: StorageAccessKind },
134	/// Weight of the `containsStorage` precompile / `seal_contains_transient_storage`.
135	ContainsStorage { len: u32, kind: StorageAccessKind },
136	/// Weight of `seal_get_storage` / `seal_get_transient_storage`.
137	GetStorage { len: u32, kind: StorageAccessKind },
138	/// Weight of the `takeStorage` precompile / `seal_take_transient_storage`.
139	TakeStorage { len: u32, kind: StorageAccessKind },
140	/// Base weight of calling `seal_call`.
141	CallBase,
142	/// Weight of calling `seal_delegate_call` for the given input size.
143	DelegateCallBase,
144	/// Weight of calling a precompile.
145	PrecompileBase,
146	/// Weight of calling a precompile that has a contract info.
147	PrecompileWithInfoBase,
148	/// Weight of reading and decoding the input to a precompile.
149	PrecompileDecode(u32),
150	/// Weight of the transfer performed during a call.
151	/// parameter `dust_transfer` indicates whether the transfer has a `dust` value.
152	CallTransferSurcharge { dust_transfer: bool },
153	/// Weight per byte that is cloned by supplying the `CLONE_INPUT` flag.
154	CallInputCloned(u32),
155	/// Weight of calling `seal_instantiate`.
156	Instantiate { input_data_len: u32, balance_transfer: bool, dust_transfer: bool },
157	/// Weight of calling `Create` opcode.
158	Create { init_code_len: u32, balance_transfer: bool, dust_transfer: bool },
159	/// Weight of calling `Ripemd160` precompile for the given input size.
160	Ripemd160(u32),
161	/// Weight of calling `Sha256` precompile for the given input size.
162	HashSha256(u32),
163	/// Weight of calling the `System::hashBlake256` precompile function for the given input
164	HashKeccak256(u32),
165	/// Weight of calling the `System::hash_blake2_256` precompile function for the given input
166	/// size.
167	HashBlake256(u32),
168	/// Weight of calling `System::hashBlake128` precompile function for the given input size.
169	HashBlake128(u32),
170	/// Weight of calling `ECERecover` precompile.
171	EcdsaRecovery,
172	/// Weight of calling `P256Verify` precompile.
173	P256Verify,
174	/// Weight of calling `seal_sr25519_verify` for the given input size.
175	Sr25519Verify(u32),
176	/// Weight charged by a precompile.
177	Precompile(Weight),
178	/// Weight of calling `ecdsa_to_eth_address`
179	EcdsaToEthAddress,
180	/// Weight of calling `get_immutable_dependency`
181	GetImmutableData(u32),
182	/// Weight of calling `set_immutable_dependency`
183	SetImmutableData(u32),
184	/// Weight of calling `Bn128Add` precompile
185	Bn128Add,
186	/// Weight of calling `Bn128Add` precompile
187	Bn128Mul,
188	/// Weight of calling `Bn128Pairing` precompile for the given number of input pairs.
189	Bn128Pairing(u32),
190	/// Weight of calling `Identity` precompile for the given number of input length.
191	Identity(u32),
192	/// Weight of calling `Blake2F` precompile for the given number of rounds.
193	Blake2F(u32),
194	/// Weight of calling `Modexp` precompile
195	Modexp(u64),
196	/// Weight of processing EIP-7702 authorization tuples.
197	///
198	/// `invalid_accounts` covers every tuple that produced no state change: those that
199	/// fail the chain-id check, fail signature recovery, or pass recovery but then fail
200	/// validation (bad nonce, non-EOA authority, etc.) or post-validation (set_delegation
201	/// error). All are billed at the signature-recovery cost — a conservative over-estimate
202	/// for the chain-id failures, which bail before recovery — and incur no
203	/// account creation/update work.
204	Delegations { new_accounts: u32, existing_accounts: u32, invalid_accounts: u32 },
205}
206
207/// How a storage access is priced.
208#[derive(Clone, Copy, Debug, Eq, PartialEq)]
209pub enum StorageAccessKind {
210	/// Persistent storage, priced by its access-list warmth.
211	Persistent(Warmth),
212	/// Transient storage, every access costs the same.
213	Transient,
214}
215
216impl StorageAccessKind {
217	/// Builds the storage access kind. `warmth` is called only for persistent storage.
218	pub fn new(transient: bool, warmth: impl FnOnce() -> Warmth) -> Self {
219		if transient { Self::Transient } else { Self::Persistent(warmth()) }
220	}
221}
222
223/// For functions that modify storage, benchmarks are performed with one item in the
224/// storage. To account for the worst-case scenario, the weight of the overhead of
225/// writing to or reading from full storage is included. For transient storage writes,
226/// the rollback weight is added to reflect the worst-case scenario for this operation.
227macro_rules! cost_storage {
228    (write_transient, $name:ident $(, $arg:expr )*) => {
229        T::WeightInfo::$name($( $arg ),*)
230            .saturating_add(T::WeightInfo::rollback_transient_storage())
231            .saturating_add(T::WeightInfo::set_transient_storage_full()
232            .saturating_sub(T::WeightInfo::set_transient_storage_empty()))
233    };
234
235    (read_transient, $name:ident $(, $arg:expr )*) => {
236        T::WeightInfo::$name($( $arg ),*)
237            .saturating_add(T::WeightInfo::get_transient_storage_full()
238            .saturating_sub(T::WeightInfo::get_transient_storage_empty()))
239    };
240
241    (write_cold, $name:ident $(, $arg:expr )*) => {
242        T::WeightInfo::$name($( $arg ),*)
243            .saturating_add(T::WeightInfo::set_storage_full()
244            .saturating_sub(T::WeightInfo::set_storage_empty()))
245    };
246
247    (read_cold, $name:ident $(, $arg:expr )*) => {
248        T::WeightInfo::$name($( $arg ),*)
249            .saturating_add(T::WeightInfo::get_storage_full()
250            .saturating_sub(T::WeightInfo::get_storage_empty()))
251    };
252}
253
254macro_rules! cost_args {
255	// cost_args!(name, a, b, c) -> T::WeightInfo::name(a, b, c).saturating_sub(T::WeightInfo::name(0, 0, 0))
256	($name:ident, $( $arg: expr ),+) => {
257		(T::WeightInfo::$name($( $arg ),+).saturating_sub(cost_args!(@call_zero $name, $( $arg ),+)))
258	};
259	// Transform T::WeightInfo::name(a, b, c) into T::WeightInfo::name(0, 0, 0)
260	(@call_zero $name:ident, $( $arg:expr ),*) => {
261		T::WeightInfo::$name($( cost_args!(@replace_token $arg) ),*)
262	};
263	// Replace the token with 0.
264	(@replace_token $_in:tt) => { 0 };
265}
266
267impl RuntimeCosts {
268	/// Extra ref_time a hot storage access pays to look up the block's overlay.
269	fn hot_storage_overlay_overhead<T: Config>() -> Weight {
270		let per_read = |weight_fn: fn(u32) -> Weight| weight_fn(1).saturating_sub(weight_fn(0));
271		per_read(T::WeightInfo::overlay_probe_full)
272			.saturating_sub(per_read(T::WeightInfo::overlay_probe_empty))
273	}
274
275	/// What a hot write pays on top of the cold read that warmed the slot:
276	/// re-hashing the slot's trie path when the block's storage root is
277	/// computed.
278	fn hot_write_surcharge<T: Config>() -> Weight {
279		let db = T::DbWeight::get();
280		db.writes(1).saturating_sub(db.reads(1))
281	}
282
283	/// Pick the matching storage bench for the access `kind`.
284	fn weight_for_storage_access<T: Config>(
285		op: StorageOp,
286		kind: StorageAccessKind,
287		cold: impl FnOnce() -> Weight,
288		hot: impl FnOnce() -> Weight,
289		transient: impl FnOnce() -> Weight,
290	) -> Weight {
291		match kind {
292			StorageAccessKind::Persistent(Warmth::Cold { revertible }) => {
293				let cost = cold()
294					.saturating_add(T::WeightInfo::access_list_touch_cold_full())
295					.saturating_sub(T::WeightInfo::access_list_touch_cold_empty());
296				if revertible {
297					cost.saturating_add(T::WeightInfo::access_list_rollback_amortization())
298				} else {
299					cost
300				}
301			},
302			StorageAccessKind::Persistent(Warmth::Hot { charged }) => hot()
303				.saturating_add(if charged.covers(op) {
304					Weight::zero()
305				} else {
306					Self::hot_write_surcharge::<T>()
307				})
308				.saturating_add(Self::hot_storage_overlay_overhead::<T>())
309				.saturating_add(T::WeightInfo::access_list_touch_hot_full())
310				.saturating_sub(T::WeightInfo::access_list_touch_hot_single_element()),
311			StorageAccessKind::Transient => transient(),
312		}
313	}
314}
315
316impl<T: Config> Token<T> for RuntimeCosts {
317	fn influence_lowest_weight_limit(&self) -> bool {
318		true
319	}
320
321	fn weight(&self) -> Weight {
322		use self::RuntimeCosts::*;
323		match *self {
324			HostFn => cost_args!(noop_host_fn, 1),
325			EvmMemoryGrow { words, allocation_words } => {
326				let grow = cost_args!(evm_memory_grow, words);
327				let allocate = if allocation_words == 0 {
328					Weight::zero()
329				} else {
330					T::WeightInfo::evm_memory_reallocate(allocation_words)
331				};
332				grow.saturating_add(allocate)
333			},
334			EvmMemoryCopyOut(len) => {
335				if len == 0 {
336					Weight::zero()
337				} else {
338					T::WeightInfo::evm_memory_copy_out(len)
339				}
340			},
341			// `extcodecopy` charges `CodeSize` separately; subtract it so its read isn't counted
342			// twice.
343			ExtCodeCopy(len) => {
344				T::WeightInfo::extcodecopy(len).saturating_sub(T::WeightInfo::seal_code_size())
345			},
346			CopyToContract(len) => T::WeightInfo::seal_copy_to_contract(len),
347			EvmCopyToContract(len) => cost_args!(seal_copy_to_contract, len),
348			CopyFromContract(len) => T::WeightInfo::seal_return(len),
349			CallDataSize => T::WeightInfo::seal_call_data_size(),
350			ReturnDataSize => T::WeightInfo::seal_return_data_size(),
351			CallDataLoad => T::WeightInfo::seal_call_data_load(),
352			CallDataCopy(len) => T::WeightInfo::seal_call_data_copy(len),
353			Caller => T::WeightInfo::seal_caller(),
354			Origin => T::WeightInfo::seal_origin(),
355			ToAccountId => T::WeightInfo::to_account_id(),
356			CodeHash => T::WeightInfo::seal_code_hash(),
357			CodeSize => T::WeightInfo::seal_code_size(),
358			OwnCodeHash => T::WeightInfo::own_code_hash(),
359			CallerIsOrigin => T::WeightInfo::caller_is_origin(),
360			CallerIsRoot => T::WeightInfo::caller_is_root(),
361			OriginIsRoot => T::WeightInfo::origin_is_root(),
362			Address => T::WeightInfo::seal_address(),
363			RefTimeLeft => T::WeightInfo::seal_ref_time_left(),
364			WeightLeft => T::WeightInfo::weight_left(),
365			Balance => T::WeightInfo::seal_balance(),
366			BalanceOf => T::WeightInfo::seal_balance_of(),
367			ValueTransferred => T::WeightInfo::seal_value_transferred(),
368			MinimumBalance => T::WeightInfo::minimum_balance(),
369			BlockNumber => T::WeightInfo::seal_block_number(),
370			BlockHash => T::WeightInfo::seal_block_hash(),
371			BlockAuthor => T::WeightInfo::seal_block_author(),
372			GasPrice => T::WeightInfo::seal_gas_price(),
373			BaseFee => T::WeightInfo::seal_base_fee(),
374			Now => T::WeightInfo::seal_now(),
375			GasLimit => T::WeightInfo::seal_gas_limit(),
376			Terminate { code_removed } => {
377				// logic only runs if code is removed
378				if code_removed {
379					T::WeightInfo::seal_terminate(code_removed.into())
380						.saturating_add(T::WeightInfo::seal_terminate_logic())
381				} else {
382					T::WeightInfo::seal_terminate(code_removed.into())
383				}
384			},
385			DepositEvent { num_topic, len } => {
386				let topic_bytes =
387					num_topic.min(limits::NUM_EVENT_TOPICS) * H256::len_bytes() as u32;
388				let event_bytes = len.saturating_add(topic_bytes);
389				T::WeightInfo::seal_deposit_event(num_topic, len)
390					.saturating_add(T::WeightInfo::on_finalize_block_per_event(event_bytes))
391					.saturating_add(Weight::from_parts(
392						limits::EXTRA_EVENT_CHARGE_PER_BYTE.saturating_mul(event_bytes.into()),
393						0,
394					))
395			},
396			SetStorage { new_bytes, old_bytes, kind } => Self::weight_for_storage_access::<T>(
397				StorageOp::Write,
398				kind,
399				|| cost_storage!(write_cold, seal_set_storage, new_bytes, old_bytes),
400				|| T::WeightInfo::seal_set_storage_hot(new_bytes, old_bytes),
401				|| cost_storage!(write_transient, seal_set_transient_storage, new_bytes, old_bytes),
402			),
403			ClearStorage { len, kind } => Self::weight_for_storage_access::<T>(
404				StorageOp::Write,
405				kind,
406				|| cost_storage!(write_cold, clear_storage, len),
407				|| T::WeightInfo::clear_storage_hot(len),
408				|| cost_storage!(write_transient, seal_clear_transient_storage, len),
409			),
410			ContainsStorage { len, kind } => Self::weight_for_storage_access::<T>(
411				StorageOp::Read,
412				kind,
413				|| cost_storage!(read_cold, contains_storage, len),
414				|| T::WeightInfo::contains_storage_hot(len),
415				|| cost_storage!(read_transient, seal_contains_transient_storage, len),
416			),
417			GetStorage { len, kind } => Self::weight_for_storage_access::<T>(
418				StorageOp::Read,
419				kind,
420				|| cost_storage!(read_cold, seal_get_storage, len),
421				|| T::WeightInfo::seal_get_storage_hot(len),
422				|| cost_storage!(read_transient, seal_get_transient_storage, len),
423			),
424			TakeStorage { len, kind } => Self::weight_for_storage_access::<T>(
425				StorageOp::Write,
426				kind,
427				|| cost_storage!(write_cold, take_storage, len),
428				|| T::WeightInfo::take_storage_hot(len),
429				|| cost_storage!(write_transient, seal_take_transient_storage, len),
430			),
431			CallBase => T::WeightInfo::seal_call(0),
432			DelegateCallBase => T::WeightInfo::seal_delegate_call(),
433			PrecompileBase => T::WeightInfo::seal_call_precompile(0, 0),
434			PrecompileWithInfoBase => T::WeightInfo::seal_call_precompile(1, 0),
435			PrecompileDecode(len) => cost_args!(seal_call_precompile, 0, len),
436			CallTransferSurcharge { dust_transfer } => {
437				// `Weight::max` is per dimension, so ref time and proof size can each be taken from
438				// either of the two benches.
439				T::WeightInfo::seal_call_transfer(dust_transfer.into())
440					.max(T::WeightInfo::seal_call_transfer_to_existing(dust_transfer.into()))
441					.saturating_sub(T::WeightInfo::seal_call(0))
442			},
443			CallInputCloned(len) => cost_args!(seal_call, len),
444			Instantiate { input_data_len, balance_transfer, dust_transfer } => {
445				let transfer = if balance_transfer || dust_transfer {
446					T::WeightInfo::seal_instantiate_transfer(dust_transfer.into())
447						.saturating_sub(T::WeightInfo::seal_instantiate(0))
448				} else {
449					Weight::zero()
450				};
451				T::WeightInfo::seal_instantiate(input_data_len).saturating_add(transfer)
452			},
453			Create { init_code_len, balance_transfer, dust_transfer } => {
454				let transfer = if balance_transfer || dust_transfer {
455					T::WeightInfo::evm_instantiate_transfer(dust_transfer.into())
456						.saturating_sub(T::WeightInfo::evm_instantiate(BENCH_MIN_EVM_INIT_CODE_LEN))
457				} else {
458					Weight::zero()
459				};
460				T::WeightInfo::evm_instantiate(init_code_len).saturating_add(transfer)
461			},
462			HashSha256(len) => T::WeightInfo::sha2_256(len),
463			Ripemd160(len) => T::WeightInfo::ripemd_160(len),
464			HashKeccak256(len) => T::WeightInfo::seal_hash_keccak_256(len),
465			HashBlake256(len) => T::WeightInfo::hash_blake2_256(len),
466			HashBlake128(len) => T::WeightInfo::hash_blake2_128(len),
467			EcdsaRecovery => T::WeightInfo::ecdsa_recover(),
468			P256Verify => T::WeightInfo::p256_verify(),
469			Sr25519Verify(len) => T::WeightInfo::seal_sr25519_verify(len),
470			Precompile(weight) => weight,
471			EcdsaToEthAddress => T::WeightInfo::seal_ecdsa_to_eth_address(),
472			GetImmutableData(len) => T::WeightInfo::seal_get_immutable_data(len),
473			SetImmutableData(len) => T::WeightInfo::seal_set_immutable_data(len),
474			Bn128Add => T::WeightInfo::bn128_add(),
475			Bn128Mul => T::WeightInfo::bn128_mul(),
476			Bn128Pairing(len) => T::WeightInfo::bn128_pairing(len),
477			Identity(len) => T::WeightInfo::identity(len),
478			Blake2F(rounds) => T::WeightInfo::blake2f(rounds),
479			Modexp(gas) => Weight::from_parts(gas.saturating_mul(WEIGHT_PER_GAS), 0),
480			Delegations { new_accounts, existing_accounts, invalid_accounts } => {
481				T::WeightInfo::process_new_account_authorization(new_accounts)
482					.saturating_add(T::WeightInfo::process_existing_account_authorization(
483						existing_accounts,
484					))
485					.saturating_add(T::WeightInfo::process_invalid_authorization(invalid_accounts))
486			},
487		}
488	}
489}
490
491#[cfg(test)]
492mod tests {
493	use super::*;
494	use crate::tests::Test;
495
496	#[test]
497	fn storage_pricing_by_access_kind() {
498		let len = 64u32;
499		let cold = StorageAccessKind::Persistent(Warmth::Cold { revertible: false });
500		let cold_revertible = StorageAccessKind::Persistent(Warmth::Cold { revertible: true });
501		let hot_kinds = [
502			StorageAccessKind::Persistent(Warmth::Hot { charged: StorageOp::Read }),
503			StorageAccessKind::Persistent(Warmth::Hot { charged: StorageOp::Write }),
504		];
505
506		let with_kind = |kind: StorageAccessKind| -> Vec<RuntimeCosts> {
507			vec![
508				RuntimeCosts::GetStorage { len, kind },
509				RuntimeCosts::SetStorage { new_bytes: len, old_bytes: len, kind },
510				RuntimeCosts::ClearStorage { len, kind },
511				RuntimeCosts::ContainsStorage { len, kind },
512				RuntimeCosts::TakeStorage { len, kind },
513			]
514		};
515
516		for hot in hot_kinds {
517			for (cold_cost, hot_cost) in with_kind(cold).into_iter().zip(with_kind(hot)) {
518				let cold_weight = <RuntimeCosts as Token<Test>>::weight(&cold_cost);
519				let hot_weight = <RuntimeCosts as Token<Test>>::weight(&hot_cost);
520				assert!(
521					cold_weight.ref_time() > hot_weight.ref_time(),
522					"expected cold > hot ref_time for {cold_cost:?}: \
523					 cold={cold_weight:?} hot={hot_weight:?}",
524				);
525				assert_eq!(
526					hot_weight.proof_size(),
527					0,
528					"hot proof_size {hot_cost:?}: {hot_weight:?}"
529				);
530				assert!(
531					cold_weight.proof_size() > 0,
532					"cold proof_size {cold_cost:?}: {cold_weight:?}",
533				);
534			}
535		}
536
537		for (rev_cost, non_rev_cost) in with_kind(cold_revertible).into_iter().zip(with_kind(cold))
538		{
539			let rev_weight = <RuntimeCosts as Token<Test>>::weight(&rev_cost);
540			let non_rev_weight = <RuntimeCosts as Token<Test>>::weight(&non_rev_cost);
541			assert!(
542				rev_weight.ref_time() > non_rev_weight.ref_time(),
543				"expected revertible > non-revertible ref_time for {rev_cost:?}: \
544				 rev={rev_weight:?} non={non_rev_weight:?}",
545			);
546			assert_eq!(
547				rev_weight.proof_size(),
548				non_rev_weight.proof_size(),
549				"proof_size differs {rev_cost:?}: rev={rev_weight:?} non={non_rev_weight:?}",
550			);
551		}
552
553		for transient_cost in with_kind(StorageAccessKind::Transient) {
554			let weight = <RuntimeCosts as Token<Test>>::weight(&transient_cost);
555			assert_eq!(
556				weight.proof_size(),
557				0,
558				"transient storage is priced without proof: {transient_cost:?}: {weight:?}"
559			);
560			assert!(
561				weight.ref_time() > 0,
562				"transient storage ref_time must be above zero: {transient_cost:?}: {weight:?}"
563			);
564		}
565	}
566
567	#[test]
568	fn the_first_hot_write_pays_the_surcharge() {
569		const LEN: u32 = 64;
570		let weight = |cost: &RuntimeCosts| <RuntimeCosts as Token<Test>>::weight(cost);
571
572		let surcharge = RuntimeCosts::hot_write_surcharge::<Test>();
573		let db = <Test as frame_system::Config>::DbWeight::get();
574		assert!(
575			surcharge.ref_time() > 0 && surcharge.ref_time() < db.writes(1).ref_time(),
576			"the surcharge is part of a write: above zero, below all of it: {surcharge:?}",
577		);
578		assert_eq!(surcharge.proof_size(), 0, "the surcharge adds no proof: {surcharge:?}");
579
580		let read_paid = StorageAccessKind::Persistent(Warmth::Hot { charged: StorageOp::Read });
581		let write_paid = StorageAccessKind::Persistent(Warmth::Hot { charged: StorageOp::Write });
582
583		let write_costs = |kind: StorageAccessKind| {
584			[
585				RuntimeCosts::SetStorage { new_bytes: LEN, old_bytes: LEN, kind },
586				RuntimeCosts::ClearStorage { len: LEN, kind },
587				RuntimeCosts::TakeStorage { len: LEN, kind },
588			]
589		};
590		for (write_to_read_paid_slot, write_to_write_paid_slot) in
591			write_costs(read_paid).into_iter().zip(write_costs(write_paid))
592		{
593			assert_eq!(
594				weight(&write_to_read_paid_slot).saturating_sub(weight(&write_to_write_paid_slot)),
595				surcharge,
596				"a write to a read-paid slot pays exactly the surcharge: \
597				 {write_to_read_paid_slot:?}",
598			);
599		}
600
601		let read_costs = |kind: StorageAccessKind| {
602			[
603				RuntimeCosts::GetStorage { len: LEN, kind },
604				RuntimeCosts::ContainsStorage { len: LEN, kind },
605			]
606		};
607		for (read_of_read_paid_slot, read_of_write_paid_slot) in
608			read_costs(read_paid).into_iter().zip(read_costs(write_paid))
609		{
610			assert_eq!(
611				weight(&read_of_read_paid_slot),
612				weight(&read_of_write_paid_slot),
613				"a read is covered at either paid level: {read_of_read_paid_slot:?}",
614			);
615		}
616	}
617
618	#[test]
619	fn a_transient_access_never_consults_the_access_list() {
620		assert_eq!(
621			StorageAccessKind::new(true, || unreachable!("transient storage has no warmth")),
622			StorageAccessKind::Transient,
623		);
624	}
625
626	#[test]
627	fn hot_storage_overlay_overhead_is_not_zero() {
628		let overhead = RuntimeCosts::hot_storage_overlay_overhead::<Test>();
629		assert!(
630			overhead.ref_time() > 0,
631			"the per-read cost of overlay_probe_full must stay above overlay_probe_empty",
632		);
633		assert_eq!(overhead.proof_size(), 0, "the overlay probe is in-memory only: {overhead:?}");
634	}
635
636	#[test]
637	fn value_transfers_pay_a_surcharge() {
638		let weight = |cost: RuntimeCosts| <RuntimeCosts as Token<Test>>::weight(&cost);
639
640		let call = |dust_transfer| weight(RuntimeCosts::CallTransferSurcharge { dust_transfer });
641		assert!(call(false).ref_time() > 0, "a call with value must pay for its transfer");
642		assert!(call(true).ref_time() > call(false).ref_time(), "a call with dust must cost more");
643
644		let instantiate: fn(bool, bool) -> RuntimeCosts = |balance_transfer, dust_transfer| {
645			RuntimeCosts::Instantiate { input_data_len: 0, balance_transfer, dust_transfer }
646		};
647		let create: fn(bool, bool) -> RuntimeCosts = |balance_transfer, dust_transfer| {
648			RuntimeCosts::Create { init_code_len: 0, balance_transfer, dust_transfer }
649		};
650
651		for (name, cost_of) in [("instantiate", instantiate), ("create", create)] {
652			let surcharge = |balance_transfer, dust_transfer| {
653				weight(cost_of(balance_transfer, dust_transfer))
654					.saturating_sub(weight(cost_of(false, false)))
655			};
656			assert!(
657				surcharge(true, false).ref_time() > 0,
658				"{name} with value must pay for its transfer",
659			);
660			assert!(
661				surcharge(true, true).ref_time() > surcharge(true, false).ref_time(),
662				"{name} with dust must cost more",
663			);
664			assert_eq!(
665				surcharge(false, true),
666				surcharge(true, true),
667				"{name} with only dust does the same work as with value and dust",
668			);
669		}
670	}
671}