referrerpolicy=no-referrer-when-downgrade

pallet_revive/metering/
mod.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
18mod gas;
19mod math;
20mod storage;
21mod weight;
22
23#[cfg(test)]
24mod tests;
25
26use crate::{
27	BalanceOf, Config, Error, ExecConfig, ExecOrigin as Origin, LOG_TARGET, StorageDeposit,
28	evm::fees::InfoT, exec::CallResources, storage::ContractInfo, vm::evm::Halt,
29};
30
31pub use gas::SignedGas;
32pub use storage::Diff;
33pub use weight::{ChargedAmount, EngineMeter, Token, slope};
34
35/// The gas of one iteration of the benchmarks that derive the ref time per gas.
36///
37/// Only `benchmarking` and the benchmark contracts in `call_builder` need them outside of
38/// `weight`.
39#[cfg(feature = "runtime-benchmarks")]
40pub use weight::{INDIRECT_JUMP_GAS, LOAD_CHAIN_GAS};
41
42use frame_support::{DebugNoBound, DefaultNoBound};
43use num_traits::Zero;
44
45use core::{fmt::Debug, marker::PhantomData, ops::ControlFlow};
46use math::eip_150::Rule;
47use sp_runtime::{FixedPointNumber, Weight};
48use storage::{DepositOf, GenericMeter as GenericStorageMeter, Meter as RootStorageMeter};
49use weight::WeightMeter;
50
51use sp_runtime::{DispatchError, DispatchResult, FixedU128, SaturatedConversion};
52
53/// A type-state pattern ensuring that meters can only be used in valid states (root vs nested).
54///
55/// It is sealed and cannot be implemented outside of this module.
56pub trait State: private::Sealed + Default + Debug {
57	/// Whether the EIP-150 63/64 rule applies to the frames a meter in this state creates.
58	const EIP_150_RULE: Rule;
59}
60
61/// Root state for transaction-level resource metering.
62///
63/// Represents the top-level accounting of a transaction's resource usage.
64#[derive(Default, Debug)]
65pub struct Root;
66
67/// Nested state for frame-level resource metering.
68///
69/// Represents resource accounting for a single call frame.
70#[derive(Default, Debug)]
71pub struct Nested;
72
73impl State for Root {
74	const EIP_150_RULE: Rule = Rule::Skip;
75}
76impl State for Nested {
77	const EIP_150_RULE: Rule = Rule::Apply;
78}
79
80mod private {
81	pub trait Sealed {}
82	impl Sealed for super::Root {}
83	impl Sealed for super::Nested {}
84}
85
86/// The type of resource meter used at the root level for transactions as a whole.
87pub type TransactionMeter<T> = ResourceMeter<T, Root>;
88/// The type of resource meter used for an execution frame.
89pub type FrameMeter<T> = ResourceMeter<T, Nested>;
90
91/// Snapshot of a [`ResourceMeter`]'s consumption at a point in time.
92///
93/// Produced by [`ResourceMeter::snapshot`] and consumed by [`ResourceMeter::delta_since`].
94pub struct MeterSnapshot<T: Config> {
95	weight: Weight,
96	gas: SignedGas<T>,
97}
98
99/// Resource meter tracking weight and storage deposit consumption.
100#[derive(DefaultNoBound)]
101pub struct ResourceMeter<T: Config, S: State> {
102	/// The weight meter. Tracks consumed weight and weight limits.
103	weight: WeightMeter<T>,
104
105	/// The deposit meter. Tracks consumed storage deposit and storage deposit limits.
106	deposit: GenericStorageMeter<T, S>,
107
108	/// This is the maximum total consumable gas.
109	///
110	/// It is the sum of a) the total consumed gas (i.e., including all previous frames) at the
111	/// time the frame started and b) the gas limit of the frame. We don't store the gas limit of
112	/// the frame separately, it can be derived from `max_total_gas` by subtracting the total gas
113	/// at the beginning of the frame.
114	///
115	/// `max_total_gas` is only required for Ethereum execution, it is always zero for Substrate
116	/// executions.
117	max_total_gas: SignedGas<T>,
118
119	/// The total consumed weight at the time the frame started.
120	total_consumed_weight_before: Weight,
121
122	/// The total consumed storage deposit at the time the frame started.
123	total_consumed_deposit_before: DepositOf<T>,
124
125	/// The limits defined for the transaction. This determines whether this transaction uses the
126	/// Ethereum or Substrate execution mode.
127	transaction_limits: TransactionLimits<T>,
128
129	_phantom: PhantomData<S>,
130}
131
132/// Parameters required to construct a root [`TransactionMeter`].
133///
134/// Despite the name, the `EthereumGas` variant carries more than just limits: it also bundles
135/// the gas-conversion context (`eth_tx_info`) and any deposit already consumed before contract
136/// execution (`authorization_deposit`). It is the full set of inputs needed to build the root
137/// meter for an ethereum-style transaction, not a pure cap descriptor.
138///
139/// Represents the two supported resource accounting modes:
140/// - EthereumGas: Single gas limit
141/// - WeightAndDeposit: Explicit limits for both computational weight and storage deposit
142#[derive(DebugNoBound, Clone)]
143pub enum TransactionLimits<T: Config> {
144	/// Ethereum execution mode: the transaction only specifies a gas limit.
145	EthereumGas {
146		/// The Ethereum gas limit
147		eth_gas_limit: BalanceOf<T>,
148		/// The weight limit for this transaction. This ensures that execution will not exhaust
149		/// weight limit. This is required for eth_transact extrinsic execution to ensure that the
150		/// max extrinsic weights is not overstepped.
151		weight_limit: Weight,
152		/// Some extra information about the transaction that is required to calculate gas usage.
153		eth_tx_info: EthTxInfo<T>,
154		/// Net deposit movement caused by EIP-7702 authorization processing before contract
155		/// execution begins. Not a cap: applied to the meter at creation so the available deposit
156		/// budget reflects either a pre-charge (auths net to a charge) or a pre-credit (auths net
157		/// to a refund — e.g. pure-revoke). Only relevant at root meter construction; nested
158		/// frames do not see it.
159		authorization_deposit: StorageDeposit<BalanceOf<T>>,
160	},
161	/// Substrate execution mode: the transaction specifies a weight limit and a storage deposit
162	/// limit
163	WeightAndDeposit { weight_limit: Weight, deposit_limit: BalanceOf<T> },
164}
165
166impl<T: Config> Default for TransactionLimits<T> {
167	fn default() -> Self {
168		Self::WeightAndDeposit {
169			weight_limit: Default::default(),
170			deposit_limit: Default::default(),
171		}
172	}
173}
174
175impl<T: Config, S: State> ResourceMeter<T, S> {
176	/// Creates a nested meter with limits derived from `limit` and this meter's remaining
177	/// resources.
178	///
179	/// Except for the transaction's first call, the EIP-150 63/64 rule applies: with `r` the
180	/// remaining resources and `s` the call stipend (zero without one), the nested meter gets at
181	/// most `63/64 * (r - s) + s`.
182	pub fn new_nested(&self, limit: &CallResources<T>) -> Result<FrameMeter<T>, DispatchError> {
183		log::trace!(
184			target: LOG_TARGET,
185			"Creating nested meter from parent: \
186				limit={limit:?}, \
187				eip_150_rule={:?}, \
188				weight_left={:?}, \
189				deposit_left={:?}, \
190				weight_consumed={:?}, \
191				deposit_consumed={:?}",
192			S::EIP_150_RULE,
193			self.weight_left(),
194			self.deposit_left(),
195			self.weight_consumed(),
196			self.deposit_consumed(),
197		);
198
199		let mut new_meter = match &self.transaction_limits {
200			TransactionLimits::EthereumGas { eth_tx_info, .. } => {
201				math::ethereum_execution::new_nested_meter(self, limit, eth_tx_info)
202			},
203			TransactionLimits::WeightAndDeposit { .. } => {
204				math::substrate_execution::new_nested_meter(self, limit)
205			},
206		}?;
207
208		new_meter.adjust_effective_weight_limit()?;
209
210		log::trace!(
211			target: LOG_TARGET,
212			"Creating nested meter done: \
213				weight_left={:?}, \
214				deposit_left={:?}, \
215				weight_consumed={:?}, \
216				deposit_consumed={:?}",
217			new_meter.weight_left(),
218			new_meter.deposit_left(),
219			new_meter.weight_consumed(),
220			new_meter.deposit_consumed(),
221		);
222
223		Ok(new_meter)
224	}
225
226	/// Returns the weight and deposit this frame consumed, and the transaction's totals so far.
227	fn consumed_resources(&self) -> (Weight, DepositOf<T>, Weight, DepositOf<T>) {
228		let self_weight = self.weight.weight_consumed();
229		let self_deposit = self.deposit.consumed();
230		let total_weight = self.total_consumed_weight_before.saturating_add(self_weight);
231		let total_deposit = self.total_consumed_deposit_before.saturating_add(&self_deposit);
232		(self_weight, self_deposit, total_weight, total_deposit)
233	}
234
235	/// Absorb only the weight consumption from a nested frame meter.
236	pub fn absorb_weight_meter_only(&mut self, other: FrameMeter<T>) {
237		log::trace!(
238			target: LOG_TARGET,
239			"Absorb weight meter only: \
240				parent_weight_left={:?}, \
241				parent_deposit_left={:?}, \
242				parent_weight_consumed={:?}, \
243				parent_deposit_consumed={:?}, \
244				parent_weight_required={:?}, \
245				parent_deposit_required={:?}, \
246				child_weight_left={:?}, \
247				child_deposit_left={:?}, \
248				child_weight_consumed={:?}, \
249				child_deposit_consumed={:?}, \
250				child_weight_required={:?}, \
251				child_deposit_required={:?}",
252			self.weight_left(),
253			self.deposit_left(),
254			self.weight_consumed(),
255			self.deposit_consumed(),
256			self.weight_required(),
257			self.deposit_required(),
258			other.weight_left(),
259			other.deposit_left(),
260			other.weight_consumed(),
261			other.deposit_consumed(),
262			other.weight_required(),
263			other.deposit_required(),
264		);
265
266		self.weight.absorb_nested(other.weight, S::EIP_150_RULE);
267		self.deposit.absorb_only_max_charged(other.deposit);
268
269		log::trace!(
270			target: LOG_TARGET,
271			"Absorb weight meter done: \
272				parent_weight_left={:?}, \
273				parent_deposit_left={:?}, \
274				parent_weight_consumed={:?}, \
275				parent_deposit_consumed={:?}, \
276				parent_weight_required={:?}, \
277				parent_deposit_required={:?}",
278			self.weight_left(),
279			self.deposit_left(),
280			self.weight_consumed(),
281			self.deposit_consumed(),
282			self.weight_required(),
283			self.deposit_required(),
284		);
285	}
286
287	/// Absorb all resource consumption from a nested frame meter.
288	pub fn absorb_all_meters(
289		&mut self,
290		other: FrameMeter<T>,
291		contract: &T::AccountId,
292		info: Option<&mut ContractInfo<T>>,
293	) {
294		log::trace!(
295			target: LOG_TARGET,
296			"Absorb all meters: \
297				parent_weight_left={:?}, \
298				parent_deposit_left={:?}, \
299				parent_weight_consumed={:?}, \
300				parent_deposit_consumed={:?}, \
301				parent_weight_required={:?}, \
302				parent_deposit_required={:?}, \
303				child_weight_left={:?}, \
304				child_deposit_left={:?}, \
305				child_weight_consumed={:?}, \
306				child_deposit_consumed={:?}, \
307				child_weight_required={:?}, \
308				child_deposit_required={:?}",
309			self.weight_left(),
310			self.deposit_left(),
311			self.weight_consumed(),
312			self.deposit_consumed(),
313			self.weight_required(),
314			self.deposit_required(),
315			other.weight_left(),
316			other.deposit_left(),
317			other.weight_consumed(),
318			other.deposit_consumed(),
319			other.weight_required(),
320			other.deposit_required(),
321		);
322
323		self.weight.absorb_nested(other.weight, S::EIP_150_RULE);
324		self.deposit.absorb(other.deposit, contract, info);
325
326		let result = self.adjust_effective_weight_limit();
327		debug_assert!(result.is_ok(), "Absorbing nested meters should not exceed limits");
328
329		log::trace!(
330			target: LOG_TARGET,
331			"Absorb all meters done: \
332				parent_weight_left={:?}, \
333				parent_deposit_left={:?}, \
334				parent_weight_consumed={:?}, \
335				parent_deposit_consumed={:?}, \
336				parent_weight_required={:?}, \
337				parent_deposit_required={:?}",
338			self.weight_left(),
339			self.deposit_left(),
340			self.weight_consumed(),
341			self.deposit_consumed(),
342			self.weight_required(),
343			self.deposit_required(),
344		);
345	}
346
347	/// Charge a weight token against this meter's remaining weight limit.
348	///
349	/// Returns `Err(Error::OutOfGas)` if the weight limit would be exceeded.
350	#[inline]
351	pub fn charge_weight_token<Tok: Token<T>>(
352		&mut self,
353		token: Tok,
354	) -> Result<ChargedAmount, DispatchError> {
355		self.weight.charge(token)
356	}
357
358	/// Try to charge a weight token or halt if not enough weight is left.
359	#[inline]
360	pub fn charge_or_halt<Tok: Token<T>>(
361		&mut self,
362		token: Tok,
363	) -> ControlFlow<Halt, ChargedAmount> {
364		self.weight.charge_or_halt(token)
365	}
366
367	/// Adjust an earlier weight charge with the actual weight consumed.
368	pub fn adjust_weight<Tok: Token<T>>(&mut self, charged_amount: ChargedAmount, token: Tok) {
369		self.weight.adjust_weight(charged_amount, token);
370	}
371
372	/// Synchronize meter state with PolkaVM executor's fuel consumption.
373	///
374	/// Maps the VM's internal fuel accounting to weight consumption:
375	/// - Converts engine fuel units to weight units
376	/// - Updates meter state to match actual VM resource usage
377	pub fn sync_from_executor(&mut self, engine_fuel: polkavm::Gas) -> Result<(), DispatchError> {
378		self.weight.sync_from_executor(engine_fuel)
379	}
380
381	/// Convert meter state to PolkaVM executor fuel units.
382	///
383	/// Prepares for VM execution by:
384	/// - Computing remaining available weight
385	/// - Converting weight units to VM fuel units and return
386	pub fn sync_to_executor(&mut self) -> polkavm::Gas {
387		self.weight.sync_to_executor()
388	}
389
390	/// Consume all remaining weight in the meter.
391	pub fn consume_all_weight(&mut self) {
392		self.weight.consume_all();
393	}
394
395	/// Record a storage deposit charge against this meter.
396	pub fn charge_deposit(&mut self, deposit: &DepositOf<T>) -> DispatchResult {
397		log::trace!(
398			target: LOG_TARGET,
399			"Charge deposit: \
400				deposit={:?}, \
401				deposit_left={:?}, \
402				deposit_consumed={:?}, \
403				max_charged={:?}",
404			deposit,
405			self.deposit_left(),
406			self.deposit_consumed(),
407			self.deposit.max_charged(),
408		);
409
410		if let StorageDeposit::Charge(amount) = deposit {
411			if self.deposit.is_root && self.deposit_left().map_or(true, |left| left < *amount) {
412				return Err(<Error<T>>::StorageDepositLimitExhausted.into());
413			}
414		}
415
416		self.deposit.record_charge(deposit);
417		self.adjust_effective_weight_limit()
418	}
419
420	/// Get remaining ethereum gas equivalent.
421	///
422	/// Converts remaining resources to ethereum gas units:
423	/// - For ethereum mode: computes directly from gas accounting
424	/// - For substrate mode: converts weight+deposit to gas equivalent
425	/// Returns None if resources are exhausted or conversion fails.
426	pub fn eth_gas_left(&self) -> Option<BalanceOf<T>> {
427		let gas_left = match &self.transaction_limits {
428			TransactionLimits::EthereumGas { eth_tx_info, .. } => {
429				math::ethereum_execution::gas_left(self, eth_tx_info)
430			},
431			TransactionLimits::WeightAndDeposit { .. } => math::substrate_execution::gas_left(self),
432		}?;
433
434		gas_left.to_ethereum_gas()
435	}
436
437	/// Get remaining weight available.
438	///
439	/// Computes remaining computational capacity:
440	/// - For ethereum mode: converts from gas to weight units
441	/// - For substrate mode: subtracts consumed from weight limit
442	/// Returns None if resources are exhausted.
443	pub fn weight_left(&self) -> Option<Weight> {
444		match &self.transaction_limits {
445			TransactionLimits::EthereumGas { eth_tx_info, .. } => {
446				math::ethereum_execution::weight_left(self, eth_tx_info)
447			},
448			TransactionLimits::WeightAndDeposit { .. } => {
449				math::substrate_execution::weight_left(self)
450			},
451		}
452	}
453
454	/// Get remaining deposit available.
455	///
456	/// Computes remaining storage deposit allowance:
457	/// - For ethereum mode: converts from gas to deposit units
458	/// - For substrate mode: subtracts consumed from deposit limit
459	/// Returns None if resources are exhausted.
460	pub fn deposit_left(&self) -> Option<BalanceOf<T>> {
461		match &self.transaction_limits {
462			TransactionLimits::EthereumGas { eth_tx_info, .. } => {
463				math::ethereum_execution::deposit_left(self, eth_tx_info)
464			},
465			TransactionLimits::WeightAndDeposit { .. } => {
466				math::substrate_execution::deposit_left(self)
467			},
468		}
469	}
470
471	/// Calculate total gas consumed so far.
472	///
473	/// Computes the ethereum-gas equivalent of all resource usage:
474	/// - Converts weight and deposit consumption to gas units
475	/// - For ethereum mode: uses direct gas accounting
476	/// - For substrate mode: synthesizes from weight+deposit usage
477	pub fn total_consumed_gas(&self) -> BalanceOf<T> {
478		let signed_gas = match &self.transaction_limits {
479			TransactionLimits::EthereumGas { eth_tx_info, .. } => {
480				math::ethereum_execution::total_consumed_gas(self, eth_tx_info)
481			},
482			TransactionLimits::WeightAndDeposit { .. } => {
483				math::substrate_execution::total_consumed_gas(self)
484			},
485		};
486
487		signed_gas.to_ethereum_gas().unwrap_or_default()
488	}
489
490	/// Get total weight consumed
491	pub fn weight_consumed(&self) -> Weight {
492		self.weight.weight_consumed()
493	}
494
495	/// Get total weight required including the EIP-150 63/64 overhead for nested calls.
496	///
497	/// This is at least the maximum amount of weight consumption that occurred during execution so
498	/// far. This is relevant because consumed weight can decrease in case it is adjusted a
499	/// posteriori for some operations.
500	pub fn weight_required(&self) -> Weight {
501		self.weight.weight_required_with_eip_150()
502	}
503
504	/// Get total storage deposit consumed in the current frame.
505	///
506	/// Returns the net storage deposit change from this frame,
507	pub fn deposit_consumed(&self) -> DepositOf<T> {
508		self.deposit.consumed()
509	}
510
511	/// Get maximum storage deposit required at any point including the EIP-150 63/64 overhead for
512	/// nested calls.
513	///
514	/// Returns the highest deposit amount needed during execution,
515	/// accounting for temporary storage spikes before later refunds.
516	pub fn deposit_required(&self) -> DepositOf<T> {
517		self.deposit.deposit_required_with_eip_150()
518	}
519
520	/// Get the Ethereum gas that has been consumed during the lifetime of this meter
521	pub fn eth_gas_consumed(&self) -> BalanceOf<T> {
522		self.eth_gas_consumed_signed().to_ethereum_gas().unwrap_or_default()
523	}
524
525	/// Same as [`Self::eth_gas_consumed`] but returns the unrounded [`SignedGas`].
526	///
527	/// Prefer this when computing a delta across two snapshots: subtracting in [`SignedGas`] form
528	/// avoids the double ceil-rounding that [`Self::eth_gas_consumed`] performs at each call.
529	pub fn eth_gas_consumed_signed(&self) -> SignedGas<T> {
530		match &self.transaction_limits {
531			TransactionLimits::EthereumGas { eth_tx_info, .. } => {
532				math::ethereum_execution::eth_gas_consumed(self, eth_tx_info)
533			},
534			TransactionLimits::WeightAndDeposit { .. } => {
535				math::substrate_execution::eth_gas_consumed(self)
536			},
537		}
538	}
539
540	/// Take a snapshot of the meter's current consumption for later use with
541	/// [`Self::delta_since`].
542	pub fn snapshot(&self) -> MeterSnapshot<T> {
543		MeterSnapshot { weight: self.weight_consumed(), gas: self.eth_gas_consumed_signed() }
544	}
545
546	/// Ethereum gas and weight consumed since `snapshot` was taken.
547	///
548	/// Gas subtraction happens in [`SignedGas`] form so that the ceil-rounding inside
549	/// `to_ethereum_gas` is applied once to the delta, not to each snapshot.
550	pub fn delta_since(&self, snapshot: &MeterSnapshot<T>) -> (u64, Weight) {
551		let gas = self
552			.eth_gas_consumed_signed()
553			.saturating_sub(&snapshot.gas)
554			.to_ethereum_gas()
555			.unwrap_or_default()
556			.try_into()
557			.unwrap_or(u64::MAX);
558		let weight = self.weight_consumed().saturating_sub(snapshot.weight);
559		(gas, weight)
560	}
561
562	/// Determine and set the new effective weight limit of the weight meter.
563	///
564	/// This function needs to be called whenever there is a change in the deposit meter. It is a
565	/// function of `ResourceMeter` instead of `WeightMeter` because its outcome also depends on the
566	/// consumed storage deposits.
567	fn adjust_effective_weight_limit(&mut self) -> DispatchResult {
568		if matches!(self.transaction_limits, TransactionLimits::WeightAndDeposit { .. }) {
569			return Ok(());
570		}
571
572		if let Some(weight_left) = self.weight_left() {
573			let new_effective_limit = self.weight.weight_consumed().saturating_add(weight_left);
574			self.weight.set_effective_weight_limit(new_effective_limit);
575			Ok(())
576		} else {
577			Err(<Error<T>>::OutOfGas.into())
578		}
579	}
580}
581
582impl<T: Config> TransactionMeter<T> {
583	/// Create a new transaction-level meter with the specified resource limits.
584	///
585	/// Initializes either:
586	/// - An ethereum-style gas-based meter or
587	/// - A substrate-style meter with explicit weight and deposit limits
588	pub fn new(transaction_limits: TransactionLimits<T>) -> Result<Self, DispatchError> {
589		log::debug!(
590			target: LOG_TARGET,
591			"Start new meter: transaction_limits={transaction_limits:?}",
592		);
593
594		let mut transaction_meter = match transaction_limits {
595			TransactionLimits::EthereumGas {
596				eth_gas_limit,
597				weight_limit,
598				eth_tx_info,
599				authorization_deposit,
600			} => {
601				let mut meter =
602					math::ethereum_execution::new_root(eth_gas_limit, weight_limit, eth_tx_info)?;
603				if !authorization_deposit.is_zero() {
604					meter.deposit.record_charge(&authorization_deposit);
605				}
606				meter
607			},
608			TransactionLimits::WeightAndDeposit { weight_limit, deposit_limit } => {
609				math::substrate_execution::new_root(weight_limit, deposit_limit)?
610			},
611		};
612
613		transaction_meter.adjust_effective_weight_limit()?;
614
615		log::trace!(
616			target: LOG_TARGET,
617			"New meter done: \
618				weight_left={:?}, \
619				deposit_left={:?}, \
620				weight_consumed={:?}, \
621				deposit_consumed={:?}",
622			transaction_meter.weight_left(),
623			transaction_meter.deposit_left(),
624			transaction_meter.weight_consumed(),
625			transaction_meter.deposit_consumed(),
626		);
627
628		Ok(transaction_meter)
629	}
630
631	/// Convenience constructor for substrate-style weight+deposit limits.
632	pub fn new_from_limits(
633		weight_limit: Weight,
634		deposit_limit: BalanceOf<T>,
635	) -> Result<Self, DispatchError> {
636		Self::new(TransactionLimits::WeightAndDeposit { weight_limit, deposit_limit })
637	}
638
639	/// Execute all postponed storage deposit operations.
640	///
641	/// Returns `Err(Error::StorageDepositNotEnoughFunds)` if deposit limit would be exceeded. The
642	/// limit is checked again after the refunds, since paying them can raise the deposit consumed.
643	pub fn execute_postponed_deposits(
644		&mut self,
645		origin: &Origin<T>,
646		exec_config: &ExecConfig<T>,
647	) -> Result<DepositOf<T>, DispatchError> {
648		log::debug!(
649			target: LOG_TARGET,
650			"Transaction meter finishes: \
651				weight_left={:?}, \
652				deposit_left={:?}, \
653				weight_consumed={:?}, \
654				deposit_consumed={:?}, \
655				eth_gas_consumed={:?}",
656			self.weight_left(),
657			self.deposit_left(),
658			self.weight_consumed(),
659			self.deposit_consumed(),
660			self.eth_gas_consumed(),
661		);
662
663		if self.deposit_left().is_none() {
664			// Deposit limit exceeded
665			return Err(<Error<T>>::StorageDepositNotEnoughFunds.into());
666		}
667
668		// Paying the refunds can increase the deposit consumed: the refunds recorded for a
669		// terminated contract are dropped and a refund can be released only in part. Check the
670		// limit again before any charge is paid.
671		self.deposit.execute_postponed_refunds(origin, exec_config)?;
672		if self.deposit_left().is_none() {
673			return Err(<Error<T>>::StorageDepositNotEnoughFunds.into());
674		}
675
676		self.deposit.execute_postponed_charges(origin, exec_config)
677	}
678
679	/// Mark a contract as terminated
680	///
681	/// This will signal to the meter to discard all charged and refunds incured by this
682	/// contract. Furthermore it will record that there was a refund of `refunded` and adapt the
683	/// total deposit accordingly
684	pub fn terminate(&mut self, contract_account: T::AccountId, refunded: BalanceOf<T>) {
685		self.deposit.terminate(contract_account, refunded);
686	}
687}
688
689impl<T: Config> FrameMeter<T> {
690	/// Record a contract's storage deposit and schedule the transfer.
691	///
692	/// Updates the frame's deposit accounting and schedules the actual token transfer
693	/// for later execution – at the end of the transaction execution.
694	pub fn charge_contract_deposit_and_transfer(
695		&mut self,
696		contract: T::AccountId,
697		amount: DepositOf<T>,
698	) -> DispatchResult {
699		log::trace!(
700			target: LOG_TARGET,
701			"Charge deposit and transfer: \
702				amount={:?}, \
703				deposit_left={:?}, \
704				deposit_consumed={:?}, \
705				max_charged={:?}",
706			amount,
707			self.deposit_left(),
708			self.deposit_consumed(),
709			self.deposit.max_charged(),
710		);
711
712		self.deposit.charge_deposit(contract, amount);
713		self.adjust_effective_weight_limit()
714	}
715
716	/// Record storage changes of a contract.
717	pub fn record_contract_storage_changes(&mut self, diff: &Diff) -> DispatchResult {
718		log::trace!(
719			target: LOG_TARGET,
720			"Charge contract storage: \
721				diff={:?}, \
722				deposit_left={:?}, \
723				deposit_consumed={:?}, \
724				max_charged={:?}",
725			diff,
726			self.deposit_left(),
727			self.deposit_consumed(),
728			self.deposit.max_charged(),
729		);
730
731		self.deposit.charge(diff);
732		self.adjust_effective_weight_limit()
733	}
734
735	/// [`Self::charge_contract_deposit_and_transfer`] and [`Self::record_contract_storage_changes`]
736	/// does not enforce the storage limit since we want to do this check as late as possible to
737	/// allow later refunds to offset earlier charges.
738	pub fn finalize(&mut self, info: Option<&mut ContractInfo<T>>) -> DispatchResult {
739		self.deposit.finalize_own_contributions(info);
740
741		if self.deposit_left().is_none() {
742			return Err(<Error<T>>::StorageDepositLimitExhausted.into());
743		}
744
745		Ok(())
746	}
747
748	/// Apply pending storage changes to a ContractInfo without finalizing the meter.
749	///
750	/// This is used before creating a nested frame to ensure the child frame can see
751	/// the parent's pending storage changes when calculating refunds. This fixes the issue
752	/// where storage deposit refunds fail in subframes because the parent's pending
753	/// charges haven't been committed to ContractInfo yet.
754	///
755	/// See: <https://github.com/paritytech/contract-issues/issues/213>
756	pub fn apply_pending_storage_changes(&self, info: &mut ContractInfo<T>) {
757		self.deposit.apply_pending_changes_to_contract(info);
758	}
759
760	/// See [`storage::RawMeter::bank_pending_changes`].
761	pub fn bank_pending_storage_changes(
762		&mut self,
763		contract: T::AccountId,
764		info: &mut ContractInfo<T>,
765	) {
766		self.deposit.bank_pending_changes(contract, info);
767	}
768}
769
770/// Ethereum transaction context for gas conversions.
771///
772/// Contains the parameters needed to convert between ethereum gas and substrate resources
773/// (weight/deposit)
774#[derive(DebugNoBound, Clone)]
775pub struct EthTxInfo<T: Config> {
776	/// The encoding length of the extrinsic
777	pub encoded_len: u32,
778	/// The extra weight of the transaction. The total weight of the extrinsic is `extra_weight` +
779	/// the weight consumed during smart contract execution.
780	pub extra_weight: Weight,
781	_phantom: PhantomData<T>,
782}
783
784impl<T: Config> EthTxInfo<T> {
785	/// Create a new ethereum transaction context with the given parameters.
786	pub fn new(encoded_len: u32, extra_weight: Weight) -> Self {
787		Self { encoded_len, extra_weight, _phantom: PhantomData }
788	}
789
790	/// Calculate total gas consumed by weight and storage operations.
791	pub fn gas_consumption(
792		&self,
793		consumed_weight: &Weight,
794		consumed_deposit: &DepositOf<T>,
795	) -> SignedGas<T> {
796		self.deposit_and_fixed_fee_gas(consumed_deposit)
797			.saturating_add(&self.weight_gas_consumption(consumed_weight))
798	}
799
800	/// Returns the gas that `consumed_deposit` and the transaction's fixed fee cost.
801	fn deposit_and_fixed_fee_gas(&self, consumed_deposit: &DepositOf<T>) -> SignedGas<T> {
802		let fixed_fee = T::FeeInfo::fixed_fee(self.encoded_len);
803		let deposit_and_fixed_fee =
804			consumed_deposit.saturating_add(&DepositOf::<T>::Charge(fixed_fee));
805		SignedGas::from_adjusted_deposit_charge(&deposit_and_fixed_fee)
806	}
807
808	/// Returns the gas that `consumed_weight` and the transaction's extra weight cost.
809	fn weight_gas_consumption(&self, consumed_weight: &Weight) -> SignedGas<T> {
810		SignedGas::from_weight_fee(T::FeeInfo::weight_to_fee(
811			&consumed_weight.saturating_add(self.extra_weight),
812		))
813	}
814
815	/// Compute the maximum deposit available from a gas budget assuming zero execution weight
816	/// and zero deposit consumed. This is the upper bound on how much deposit the transaction
817	/// could ever spend.
818	pub fn max_deposit(&self, eth_gas_limit: BalanceOf<T>) -> BalanceOf<T> {
819		let max_gas = SignedGas::<T>::from_ethereum_gas(eth_gas_limit);
820		let overhead_gas =
821			self.gas_consumption(&Weight::zero(), &DepositOf::<T>::Charge(Zero::zero()));
822		let remaining = max_gas.saturating_sub(&overhead_gas);
823		remaining.to_adjusted_deposit_charge().unwrap_or_default()
824	}
825
826	/// Calculate maximal possible remaining weight that can be consumed given a particular gas
827	/// limit.
828	///
829	/// Returns None if remaining gas would not allow any more weight consumption.
830	pub fn weight_remaining(
831		&self,
832		max_total_gas: &SignedGas<T>,
833		total_weight_consumption: &Weight,
834		total_deposit_consumption: &DepositOf<T>,
835	) -> Option<Weight> {
836		self.weight_remaining_with_deposit_and_fixed_fee_gas(
837			max_total_gas,
838			total_weight_consumption,
839			&self.deposit_and_fixed_fee_gas(total_deposit_consumption),
840		)
841	}
842
843	/// Returns what `weight_remaining` returns, given the gas that the consumed deposit and the
844	/// fixed fee cost.
845	fn weight_remaining_with_deposit_and_fixed_fee_gas(
846		&self,
847		max_total_gas: &SignedGas<T>,
848		total_weight_consumption: &Weight,
849		deposit_and_fixed_fee_gas: &SignedGas<T>,
850	) -> Option<Weight> {
851		let consumable_fee =
852			max_total_gas.saturating_sub(deposit_and_fixed_fee_gas).to_weight_fee()?;
853
854		T::FeeInfo::fee_to_weight(consumable_fee)
855			.checked_sub(&total_weight_consumption.saturating_add(self.extra_weight))
856	}
857}