referrerpolicy=no-referrer-when-downgrade

pallet_revive/metering/
storage.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//! This module contains functions to meter the storage deposit.
19
20#[cfg(test)]
21mod tests;
22
23use super::{Nested, Root, State};
24use crate::{
25	AddressMapper, BalanceOf, Config, ExecConfig, ExecOrigin as Origin, HoldReason, LOG_TARGET,
26	Pallet, StorageDeposit as Deposit,
27	deposit_payment::Deposit as _,
28	metering::math::eip_150::{self, BalanceEip150, Peak},
29	storage::{AccountInfo, ContractInfo},
30};
31use alloc::vec::Vec;
32use core::{marker::PhantomData, mem};
33use frame_support::{
34	DebugNoBound, DefaultNoBound,
35	traits::{Defensive, Get},
36};
37use sp_arithmetic::MultiplyRational;
38use sp_runtime::{
39	DispatchError, Rounding,
40	traits::{Saturating, Zero},
41};
42
43#[cfg(test)]
44use num_traits::Bounded;
45
46/// Deposit that uses the native fungible's balance type.
47pub type DepositOf<T> = Deposit<BalanceOf<T>>;
48
49/// A production root storage meter that actually charges from its origin.
50pub type Meter<T> = RawMeter<T, ReservingExt, Root>;
51
52/// A production storage meter that actually charges from its origin.
53///
54/// This can be used where we want to be generic over the state (Root vs. Nested).
55pub type GenericMeter<T, S> = RawMeter<T, ReservingExt, S>;
56
57/// A trait that allows to decouple the metering from the charging of balance.
58///
59/// This mostly exists for testing so that the charging can be mocked.
60pub trait Ext<T: Config> {
61	/// This is called to inform the implementer that some balance should be charged due to
62	/// some interaction of the `origin` with a `contract`.
63	///
64	/// The balance transfer can either flow from `origin` to `contract` or the other way
65	/// around depending on whether `amount` constitutes a `Charge` or a `Refund`.
66	/// It will fail in case the `origin` has not enough balance to cover all storage deposits.
67	///
68	/// Returns the deposit that was transferred. A charge is always transferred in full. For a
69	/// refund this is the amount released from the contract's hold, which can be smaller than
70	/// `amount`: it is bounded by the deposit the contract holds above its base deposit, and the
71	/// deposit backend may release less than requested.
72	fn charge(
73		origin: &T::AccountId,
74		contract: &T::AccountId,
75		amount: &DepositOf<T>,
76		exec_config: &ExecConfig<T>,
77	) -> Result<DepositOf<T>, DispatchError>;
78}
79
80/// This [`Ext`] is used for actual on-chain execution when balance needs to be charged.
81///
82/// It uses [`frame_support::traits::fungible::Mutate`] in order to do accomplish the reserves.
83pub enum ReservingExt {}
84
85/// A type that allows the metering of consumed or freed storage of a single contract call stack.
86#[derive(DefaultNoBound, DebugNoBound)]
87pub struct RawMeter<T: Config, E, S: State> {
88	/// The limit of how much balance this meter is allowed to consume.
89	pub(crate) limit: Option<BalanceOf<T>>,
90	/// The amount of balance that was used in this meter and all of its already absorbed children.
91	total_deposit: DepositOf<T>,
92	/// The amount of storage changes that were recorded in this meter alone.
93	/// This has no meaning for Root meters and will always be Contribution::Checked(0)
94	own_contribution: Contribution<T>,
95	/// List of charges that should be applied at the end of a contract stack execution.
96	///
97	/// We only have one charge per contract hence the size of this vector is
98	/// limited by the maximum call depth.
99	charges: Vec<Charge<T>>,
100	/// The maximal consumed deposit that occurred at any point during the execution of this
101	/// storage deposit meter
102	max_charged: BalanceOf<T>,
103	/// The deposit the parent had consumed before it created this meter, as returned by
104	/// [`RawMeter::consumed`].
105	parent_consumed: DepositOf<T>,
106	/// True if this is the root meter.
107	///
108	/// Sometimes we cannot know at compile time.
109	pub(crate) is_root: bool,
110	/// EIP-150 63/64 peak deposit tracking for dry-run estimation.
111	eip_150_peak: Peak<BalanceEip150<T>>,
112	/// Type parameter only used in impls.
113	_phantom: PhantomData<(E, S)>,
114}
115
116/// This type is used to describe a storage change when charging from the meter.
117#[derive(Default, DebugNoBound)]
118pub struct Diff {
119	/// How many bytes were added to storage.
120	pub bytes_added: u32,
121	/// How many bytes were removed from storage.
122	pub bytes_removed: u32,
123	/// How many storage items were added to storage.
124	pub items_added: u32,
125	/// How many storage items were removed from storage.
126	pub items_removed: u32,
127}
128
129impl Diff {
130	/// Calculate how much of a charge or refund results from applying the diff and store it
131	/// in the passed `info` if any.
132	///
133	/// Added and removed storage are netted against each other before a rate is applied. A net
134	/// addition is charged at the current `DepositPerByte` and `DepositPerChildTrieItem`, a net
135	/// removal is refunded pro rata of the deposit the contract holds, which is its average
136	/// historical rate. Storage that is replaced within the same diff is therefore free, even
137	/// after a rate change. This is intended: `Diff` only carries counters, so a replacement
138	/// cannot be told apart from a key that was created and deleted again in the same frame.
139	///
140	/// # Note
141	///
142	/// In case `None` is passed for `info` only charges are calculated. This is because refunds
143	/// are calculated pro rata of the existing storage within a contract and hence need extract
144	/// this information from the passed `info`.
145	pub fn update_contract<T: Config>(&self, info: Option<&mut ContractInfo<T>>) -> DepositOf<T> {
146		let per_byte = T::DepositPerByte::get();
147		let per_item = T::DepositPerChildTrieItem::get();
148		let bytes_added = self.bytes_added.saturating_sub(self.bytes_removed);
149		let items_added = self.items_added.saturating_sub(self.items_removed);
150		let mut bytes_deposit = Deposit::Charge(per_byte.saturating_mul((bytes_added).into()));
151		let mut items_deposit = Deposit::Charge(per_item.saturating_mul((items_added).into()));
152
153		// Without any contract info we can only calculate diffs which add storage
154		let info = if let Some(info) = info {
155			info
156		} else {
157			return bytes_deposit.saturating_add(&items_deposit);
158		};
159
160		// Refunds are calculated pro rata based on the accumulated storage within the contract
161		let bytes_removed = self.bytes_removed.saturating_sub(self.bytes_added);
162		let items_removed = self.items_removed.saturating_sub(self.items_added);
163		bytes_deposit = bytes_deposit.saturating_add(&Deposit::Refund(
164			info.storage_byte_deposit
165				.multiply_rational(
166					bytes_removed.min(info.storage_bytes).into(),
167					info.storage_bytes.into(),
168					Rounding::Down,
169				)
170				.unwrap_or_default(),
171		));
172		items_deposit = items_deposit.saturating_add(&Deposit::Refund(
173			info.storage_item_deposit
174				.multiply_rational(
175					items_removed.min(info.storage_items).into(),
176					info.storage_items.into(),
177					Rounding::Down,
178				)
179				.unwrap_or_default(),
180		));
181
182		// We need to update the contract info structure with the new deposits
183		info.storage_bytes =
184			info.storage_bytes.saturating_add(bytes_added).saturating_sub(bytes_removed);
185		info.storage_items =
186			info.storage_items.saturating_add(items_added).saturating_sub(items_removed);
187		match &bytes_deposit {
188			Deposit::Charge(amount) => {
189				info.storage_byte_deposit = info.storage_byte_deposit.saturating_add(*amount)
190			},
191			Deposit::Refund(amount) => {
192				info.storage_byte_deposit = info.storage_byte_deposit.saturating_sub(*amount)
193			},
194		}
195		match &items_deposit {
196			Deposit::Charge(amount) => {
197				info.storage_item_deposit = info.storage_item_deposit.saturating_add(*amount)
198			},
199			Deposit::Refund(amount) => {
200				info.storage_item_deposit = info.storage_item_deposit.saturating_sub(*amount)
201			},
202		}
203
204		bytes_deposit.saturating_add(&items_deposit)
205	}
206}
207
208impl Diff {
209	fn saturating_add(&self, rhs: &Self) -> Self {
210		Self {
211			bytes_added: self.bytes_added.saturating_add(rhs.bytes_added),
212			bytes_removed: self.bytes_removed.saturating_add(rhs.bytes_removed),
213			items_added: self.items_added.saturating_add(rhs.items_added),
214			items_removed: self.items_removed.saturating_add(rhs.items_removed),
215		}
216	}
217}
218
219/// The state of a contract.
220#[derive(DebugNoBound, Clone, PartialEq, Eq)]
221pub enum ContractState<T: Config> {
222	Alive { amount: DepositOf<T> },
223	Terminated,
224}
225
226/// Records information to charge or refund a plain account.
227///
228/// All the charges are deferred to the end of a whole call stack. Reason is that by doing
229/// this we can do all the refunds before doing any charge. This way a plain account can use
230/// more deposit than it has balance as along as it is covered by a refund. This
231/// essentially makes the order of storage changes irrelevant with regard to the deposit system.
232/// The only exception is when a special (tougher) deposit limit is specified for a cross-contract
233/// call. In that case the limit is enforced once the call is returned, rolling it back if
234/// exhausted.
235#[derive(DebugNoBound, Clone)]
236struct Charge<T: Config> {
237	contract: T::AccountId,
238	state: ContractState<T>,
239}
240
241/// Records the storage changes of a storage meter.
242#[derive(DebugNoBound)]
243enum Contribution<T: Config> {
244	/// The contract the meter belongs to is alive and accumulates changes using a [`Diff`].
245	Alive(Diff),
246	/// The meter was checked against its limit using [`RawMeter::enforce_limit`] at the end of
247	/// its execution. In this process the [`Diff`] was converted into a [`Deposit`].
248	Checked(DepositOf<T>),
249}
250
251impl<T: Config> Contribution<T> {
252	/// See [`Diff::update_contract`].
253	fn update_contract(&self, info: Option<&mut ContractInfo<T>>) -> DepositOf<T> {
254		match self {
255			Self::Alive(diff) => diff.update_contract::<T>(info),
256			Self::Checked(deposit) => deposit.clone(),
257		}
258	}
259}
260
261impl<T: Config> Default for Contribution<T> {
262	fn default() -> Self {
263		Self::Alive(Default::default())
264	}
265}
266
267/// Functions that apply to all states.
268impl<T, E, S> RawMeter<T, E, S>
269where
270	T: Config,
271	E: Ext<T>,
272	S: State,
273{
274	/// Create a new child that has its `limit`.
275	///
276	/// This is called whenever a new subcall is initiated in order to track the storage
277	/// usage for this sub call separately. This is necessary because we want to exchange balance
278	/// with the current contract we are interacting with.
279	pub fn nested(&self, mut limit: Option<BalanceOf<T>>) -> RawMeter<T, E, Nested> {
280		if let (Some(new_limit), Some(old_limit)) = (limit, self.limit) {
281			limit = Some(new_limit.min(old_limit));
282		}
283
284		RawMeter { limit, parent_consumed: self.consumed(), ..Default::default() }
285	}
286
287	/// Absorb a child that was spawned to handle a sub call.
288	///
289	/// This should be called whenever a sub call comes to its end and it is **not** reverted.
290	/// This does the actual balance transfer from/to `origin` and `contract` based on the
291	/// overall storage consumption of the call. It also updates the supplied contract info.
292	///
293	/// In case a contract reverted the child meter should just be dropped in order to revert
294	/// any changes it recorded.
295	///
296	/// # Parameters
297	///
298	/// - `absorbed`: The child storage meter that should be absorbed.
299	/// - `origin`: The origin that spawned the original root meter.
300	/// - `contract`: The contract's account that this sub call belongs to.
301	/// - `info`: The info of the contract in question. `None` if the contract was terminated.
302	pub fn absorb(
303		&mut self,
304		absorbed: RawMeter<T, E, Nested>,
305		contract: &T::AccountId,
306		info: Option<&mut ContractInfo<T>>,
307	) {
308		self.update_eip_150_peak(&absorbed);
309
310		// We are now at the position to calculate the actual final net charge of `absorbed` as we
311		// now have the contract information `info`. Before that we only took net charges related to
312		// the contract storage into account but ignored net refunds.
313		// However, with this complete information there is no need to recalculate `max_charged` for
314		// `absorbed` here before we absorb it because the actual final net charge will not be more
315		// than the net charge we observed before (as we only ignored net refunds but not net
316		// charges).
317		self.max_charged = self.max_charged.max(
318			absorbed
319				.parent_consumed
320				.saturating_add(&absorbed.max_charged())
321				.charge_or_zero(),
322		);
323
324		let own_deposit = absorbed.own_contribution.update_contract(info);
325		self.total_deposit = self
326			.total_deposit
327			.saturating_add(&absorbed.total_deposit)
328			.saturating_add(&own_deposit);
329		self.charges.extend_from_slice(&absorbed.charges);
330
331		self.recalulculate_max_charged();
332
333		if !own_deposit.is_zero() {
334			self.charges.push(Charge {
335				contract: contract.clone(),
336				state: ContractState::Alive { amount: own_deposit },
337			});
338		}
339	}
340
341	/// Absorb only the maximum charge of the child meter.
342	///
343	/// This should be called whenever a sub call ends and reverts.
344	///
345	/// # Parameters
346	///
347	/// - `absorbed`: The child storage meter
348	pub fn absorb_only_max_charged(&mut self, absorbed: RawMeter<T, E, Nested>) {
349		self.update_eip_150_peak(&absorbed);
350
351		self.max_charged = self.max_charged.max(
352			absorbed
353				.parent_consumed
354				.saturating_add(&absorbed.max_charged())
355				.charge_or_zero(),
356		);
357	}
358
359	/// Record a charge that has taken place externally.
360	///
361	/// This will not perform a charge. It just records it to reflect it in the
362	/// total amount of storage required for a transaction.
363	pub fn record_charge(&mut self, amount: &DepositOf<T>) {
364		self.total_deposit = self.total_deposit.saturating_add(amount);
365		self.recalulculate_max_charged();
366	}
367
368	/// The amount of balance that this meter has consumed.
369	///
370	/// This disregards any refunds pending in the current frame. This is because we can calculate
371	/// refunds only when the frame ends, or, if the contract is reentered before that, when the
372	/// reentrant call returns without reverting.
373	pub fn consumed(&self) -> DepositOf<T> {
374		self.total_deposit.saturating_add(&self.own_contribution.update_contract(None))
375	}
376
377	/// Return the maximum consumed deposit at any point in the previous execution
378	pub fn max_charged(&self) -> DepositOf<T> {
379		Deposit::Charge(self.max_charged)
380	}
381
382	/// Recaluclate the max deposit value
383	fn recalulculate_max_charged(&mut self) {
384		self.max_charged = self.max_charged.max(self.consumed().charge_or_zero());
385	}
386
387	/// Returns the deposit required, including the part each caller keeps under the 63/64 rule.
388	pub fn deposit_required_with_eip_150(&self) -> DepositOf<T> {
389		Deposit::Charge(self.eip_150_peak.get()).max(self.max_charged())
390	}
391
392	/// Raises the 63/64 peak to the deposit this meter needed for `child`, if that is higher.
393	fn update_eip_150_peak(&mut self, child: &RawMeter<T, E, Nested>) {
394		// Without a deposit limit, the child can use a refund the caller received before the call.
395		// With a limit, a refund cannot raise the child's limit, which is capped at this meter's
396		// limit, so a net refund counts as zero.
397		let consumed_before_call = match self.limit {
398			Some(_) => Deposit::Charge(child.parent_consumed.charge_or_zero()),
399			None => child.parent_consumed.clone(),
400		};
401		let child_deposit_required = child.max_charged().charge_or_zero();
402		let child_deposit_overhead = child.eip_150_total_overhead(S::EIP_150_RULE);
403		let child_deposit_peak =
404			Deposit::Charge(child_deposit_required.saturating_add(child_deposit_overhead));
405		let current_deposit_peak =
406			consumed_before_call.saturating_add(&child_deposit_peak).charge_or_zero();
407		self.eip_150_peak.update(current_deposit_peak);
408	}
409
410	/// Returns the extra deposit the parent needs beyond `max_charged()` to cover the part each
411	/// caller keeps at and below this level.
412	///
413	/// `rule` must be the `State::EIP_150_RULE` of the meter that created this one.
414	fn eip_150_total_overhead(&self, rule: eip_150::Rule) -> BalanceOf<T> {
415		self.eip_150_peak
416			.total_overhead(self.max_charged().charge_or_zero(), rule, Zero::zero())
417	}
418
419	/// The amount of balance still available from the current meter.
420	///
421	/// This includes charges from the current frame but no refunds.
422	#[cfg(test)]
423	pub fn available(&self) -> BalanceOf<T> {
424		self.consumed()
425			.available(&self.limit.unwrap_or(BalanceOf::<T>::max_value()))
426			.unwrap_or_default()
427	}
428}
429
430/// Functions that only apply to the root state.
431impl<T, E> RawMeter<T, E, Root>
432where
433	T: Config,
434	E: Ext<T>,
435{
436	/// Create new storage limiting storage deposits to the passed `limit`.
437	///
438	/// If the limit is larger than what the origin can afford we will just fail
439	/// when collecting the deposits in `execute_postponed_deposits`.
440	pub fn new(limit: Option<BalanceOf<T>>) -> Self {
441		Self {
442			limit,
443			is_root: true,
444			own_contribution: Contribution::Checked(Default::default()),
445			..Default::default()
446		}
447	}
448
449	/// Pay the refunds accumulated in the whole contract stack.
450	///
451	/// This is the first half of settling the deposits and must be followed by
452	/// [`Self::execute_postponed_charges`]. Refunds are paid first so that the origin can pay
453	/// for the charges using the refunds.
454	///
455	/// The deposit consumed by this meter can rise here, so the caller must enforce its limit
456	/// again before any charge is paid. Coalescing drops the refunds recorded for a contract that
457	/// was terminated, since its termination already refunded its whole hold. A refund can also
458	/// be released from the contract's hold only in part: it is bounded by the deposit the
459	/// contract holds above its base deposit, and the deposit backend may release less than
460	/// requested, for example when the origin is not entitled to the part held in a particular
461	/// currency. The part that was not released is added to the deposit consumed.
462	pub fn execute_postponed_refunds(
463		&mut self,
464		origin: &Origin<T>,
465		exec_config: &ExecConfig<T>,
466	) -> Result<(), DispatchError> {
467		// Only refund or charge deposit if the origin is not root.
468		let origin = match origin {
469			Origin::Root => return Ok(()),
470			Origin::Signed(o) => o,
471		};
472
473		// Coalesce charges of the same contract
474		self.charges.sort_by(|a, b| a.contract.cmp(&b.contract));
475		self.charges = {
476			let mut coalesced: Vec<Charge<T>> = Vec::with_capacity(self.charges.len());
477			for mut ch in mem::take(&mut self.charges) {
478				if let Some(last) = coalesced.last_mut() {
479					if last.contract == ch.contract {
480						match (&mut last.state, &mut ch.state) {
481							(
482								ContractState::Alive { amount: last_amount },
483								ContractState::Alive { amount: ch_amount },
484							) => {
485								*last_amount = last_amount.saturating_add(&ch_amount);
486							},
487							(ContractState::Alive { amount }, ContractState::Terminated) |
488							(ContractState::Terminated, ContractState::Alive { amount }) => {
489								// undo all deposits made by a terminated contract
490								self.total_deposit = self.total_deposit.saturating_sub(&amount);
491								last.state = ContractState::Terminated;
492							},
493							(ContractState::Terminated, ContractState::Terminated) => {
494								debug_assert!(
495									false,
496									"We never emit two terminates for the same contract."
497								)
498							},
499						}
500						continue;
501					}
502				}
503				coalesced.push(ch);
504			}
505			coalesced
506		};
507
508		let mut unreleased: BalanceOf<T> = Zero::zero();
509		for charge in self.charges.iter() {
510			if let ContractState::Alive { amount: amount @ Deposit::Refund(_) } = &charge.state {
511				let released = E::charge(origin, &charge.contract, amount, exec_config)?;
512				unreleased =
513					unreleased.saturating_add(released.saturating_sub(amount).charge_or_zero());
514			}
515		}
516		// Account for the refunds that were released, not the ones that were requested.
517		if !unreleased.is_zero() {
518			self.total_deposit = self.total_deposit.saturating_add(&Deposit::Charge(unreleased));
519		}
520		self.recalulculate_max_charged();
521		Ok(())
522	}
523
524	/// Pay the charges accumulated in the whole contract stack.
525	///
526	/// Must be called after [`Self::execute_postponed_refunds`]. Returns the total amount of
527	/// deposit that changed hands as result of the execution that this meter was passed into.
528	pub fn execute_postponed_charges(
529		&mut self,
530		origin: &Origin<T>,
531		exec_config: &ExecConfig<T>,
532	) -> Result<DepositOf<T>, DispatchError> {
533		// Only refund or charge deposit if the origin is not root.
534		let origin = match origin {
535			Origin::Root => return Ok(Deposit::Charge(Zero::zero())),
536			Origin::Signed(o) => o,
537		};
538
539		for charge in self.charges.iter() {
540			if let ContractState::Alive { amount: amount @ Deposit::Charge(_) } = &charge.state {
541				E::charge(origin, &charge.contract, amount, exec_config)?;
542			}
543		}
544
545		Ok(self.total_deposit.clone())
546	}
547
548	/// Flag a `contract` as terminated.
549	///
550	/// This will signal to the meter to discard all charged and refunds incured by this
551	/// contract.
552	pub fn terminate(&mut self, contract: T::AccountId, refunded: BalanceOf<T>) {
553		self.total_deposit = self.total_deposit.saturating_add(&Deposit::Refund(refunded));
554		self.charges.push(Charge { contract, state: ContractState::Terminated });
555
556		// no need to recalculate max_charged here as the total consumed amount will just decrease
557		// with this extra refund
558	}
559}
560
561/// Functions that only apply to the nested state.
562impl<T: Config, E: Ext<T>> RawMeter<T, E, Nested> {
563	/// Charges `diff` from the meter.
564	pub fn charge(&mut self, diff: &Diff) {
565		match &mut self.own_contribution {
566			Contribution::Alive(own) => {
567				*own = own.saturating_add(diff);
568				self.recalulculate_max_charged();
569			},
570			_ => panic!("Charge is never called after termination; qed"),
571		};
572	}
573
574	/// Adds a charge without recording it in the contract info.
575	///
576	/// Use this method instead of [`Self::charge`] when the charge is not the result of a storage
577	/// change within the contract's child trie. This is the case when when the `code_hash` is
578	/// updated. [`Self::charge`] cannot be used here because we keep track of the deposit charge
579	/// separately from the storage charge.
580	///
581	/// If this functions is used the amount of the charge has to be stored by the caller somewhere
582	/// else in order to be able to refund it.
583	pub fn charge_deposit(&mut self, contract: T::AccountId, amount: DepositOf<T>) {
584		// will not fail in a nested meter
585		self.record_charge(&amount);
586		self.charges.push(Charge { contract, state: ContractState::Alive { amount } });
587	}
588
589	/// Determine the actual final charge from the own contributions
590	pub fn finalize_own_contributions(&mut self, info: Option<&mut ContractInfo<T>>) {
591		let deposit = self.own_contribution.update_contract(info);
592		self.own_contribution = Contribution::Checked(deposit);
593
594		// no need to recalculate max_charged here as the consumed amount cannot increase
595		// when taking removed bytes/items into account
596	}
597
598	/// Apply pending storage changes to a ContractInfo without finalizing the meter.
599	///
600	/// This is used before creating a nested frame to ensure the child frame can see
601	/// the parent's pending storage changes when calculating refunds.
602	///
603	/// Unlike [`Self::finalize_own_contributions`], this does not consume the pending diff,
604	/// allowing the meter to continue tracking changes after the nested call returns.
605	pub fn apply_pending_changes_to_contract(&self, info: &mut ContractInfo<T>) {
606		if let Contribution::Alive(diff) = &self.own_contribution {
607			// Apply the diff to update the ContractInfo's storage deposit fields.
608			// We don't care about the return value (the deposit amount) here,
609			// we just want to update the ContractInfo so child frames can see it.
610			let _ = diff.update_contract::<T>(Some(info));
611		}
612	}
613
614	/// Apply the pending diff to `info` and push its deposit as a final charge, then reset
615	/// `own_contribution` so finalize does not apply it a second time.
616	pub fn bank_pending_changes(&mut self, contract: T::AccountId, info: &mut ContractInfo<T>) {
617		if let Contribution::Alive(_) = &self.own_contribution {
618			let deposit = self.own_contribution.update_contract(Some(info));
619			self.own_contribution = Contribution::Alive(Default::default());
620			if !deposit.is_zero() {
621				self.charge_deposit(contract, deposit);
622			}
623		} else {
624			debug_assert!(
625				false,
626				"on-stack ancestor frames have not finalized yet, so own_contribution \
627				 should be Alive when banked; qed",
628			);
629		}
630	}
631}
632
633impl<T: Config> Ext<T> for ReservingExt {
634	fn charge(
635		origin: &T::AccountId,
636		contract: &T::AccountId,
637		amount: &DepositOf<T>,
638		exec_config: &ExecConfig<T>,
639	) -> Result<DepositOf<T>, DispatchError> {
640		match *amount {
641			Deposit::Charge(value) | Deposit::Refund(value) if value.is_zero() => {
642				Ok(amount.clone())
643			},
644			Deposit::Charge(value) => {
645				<Pallet<T>>::charge_deposit(
646					HoldReason::StorageDepositReserve,
647					origin,
648					contract,
649					value,
650					exec_config,
651				)?;
652				Ok(Deposit::Charge(value))
653			},
654			Deposit::Refund(value) => {
655				// The refund is derived from the item and byte deposits recorded in the contract
656				// info. Bound it by what the contract holds above its base deposit, so that the
657				// base deposit is only released when the contract is terminated. A contract
658				// instantiated by `Origin::Root` records a base deposit of zero, since none was
659				// placed on hold. A contract instantiated by `Origin::Root` on an older runtime can
660				// record a base deposit that is not held. Its refunds stay bounded by the deposit
661				// held above it.
662				//
663				// A refund is only recorded for a contract whose info was loaded during the call
664				// stack. That info is only removed by termination, and the charges of a
665				// terminated contract are never paid out. The info of a delegated EOA is written
666				// when its authorization is processed, before execution starts. The info
667				// therefore exists here. Should it be missing anyway, refund nothing: without it
668				// the base deposit is unknown.
669				let held = T::Deposit::total_on_hold(HoldReason::StorageDepositReserve, contract);
670				let refundable =
671					AccountInfo::<T>::load_contract(&T::AddressMapper::to_address(contract))
672						.map(|info| held.saturating_sub(info.storage_base_deposit()))
673						.defensive_unwrap_or_default();
674				if value > refundable {
675					log::debug!(
676						target: LOG_TARGET,
677						"Storage deposit refund of contract {contract:?} bounded by the deposit \
678						 held above the base deposit: requested={value:?}, bounded={refundable:?}",
679					);
680				}
681				<Pallet<T>>::refund_deposit(
682					HoldReason::StorageDepositReserve,
683					contract,
684					exec_config.funds(origin),
685					value.min(refundable),
686				)?;
687				// The deposit backend may release less than requested, for example when the
688				// origin is not entitled to the part held in a particular currency. Report the
689				// amount that was released from the hold.
690				let released = held.saturating_sub(T::Deposit::total_on_hold(
691					HoldReason::StorageDepositReserve,
692					contract,
693				));
694				Ok(Deposit::Refund(released))
695			},
696		}
697	}
698}