1mod 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#[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
53pub trait State: private::Sealed + Default + Debug {
57 const EIP_150_RULE: Rule;
59}
60
61#[derive(Default, Debug)]
65pub struct Root;
66
67#[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
86pub type TransactionMeter<T> = ResourceMeter<T, Root>;
88pub type FrameMeter<T> = ResourceMeter<T, Nested>;
90
91pub struct MeterSnapshot<T: Config> {
95 weight: Weight,
96 gas: SignedGas<T>,
97}
98
99#[derive(DefaultNoBound)]
101pub struct ResourceMeter<T: Config, S: State> {
102 weight: WeightMeter<T>,
104
105 deposit: GenericStorageMeter<T, S>,
107
108 max_total_gas: SignedGas<T>,
118
119 total_consumed_weight_before: Weight,
121
122 total_consumed_deposit_before: DepositOf<T>,
124
125 transaction_limits: TransactionLimits<T>,
128
129 _phantom: PhantomData<S>,
130}
131
132#[derive(DebugNoBound, Clone)]
143pub enum TransactionLimits<T: Config> {
144 EthereumGas {
146 eth_gas_limit: BalanceOf<T>,
148 weight_limit: Weight,
152 eth_tx_info: EthTxInfo<T>,
154 authorization_deposit: StorageDeposit<BalanceOf<T>>,
160 },
161 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 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 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 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 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 #[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 #[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 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 pub fn sync_from_executor(&mut self, engine_fuel: polkavm::Gas) -> Result<(), DispatchError> {
378 self.weight.sync_from_executor(engine_fuel)
379 }
380
381 pub fn sync_to_executor(&mut self) -> polkavm::Gas {
387 self.weight.sync_to_executor()
388 }
389
390 pub fn consume_all_weight(&mut self) {
392 self.weight.consume_all();
393 }
394
395 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 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 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 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 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 pub fn weight_consumed(&self) -> Weight {
492 self.weight.weight_consumed()
493 }
494
495 pub fn weight_required(&self) -> Weight {
501 self.weight.weight_required_with_eip_150()
502 }
503
504 pub fn deposit_consumed(&self) -> DepositOf<T> {
508 self.deposit.consumed()
509 }
510
511 pub fn deposit_required(&self) -> DepositOf<T> {
517 self.deposit.deposit_required_with_eip_150()
518 }
519
520 pub fn eth_gas_consumed(&self) -> BalanceOf<T> {
522 self.eth_gas_consumed_signed().to_ethereum_gas().unwrap_or_default()
523 }
524
525 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 pub fn snapshot(&self) -> MeterSnapshot<T> {
543 MeterSnapshot { weight: self.weight_consumed(), gas: self.eth_gas_consumed_signed() }
544 }
545
546 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 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 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 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 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 return Err(<Error<T>>::StorageDepositNotEnoughFunds.into());
666 }
667
668 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 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 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 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 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 pub fn apply_pending_storage_changes(&self, info: &mut ContractInfo<T>) {
757 self.deposit.apply_pending_changes_to_contract(info);
758 }
759
760 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#[derive(DebugNoBound, Clone)]
775pub struct EthTxInfo<T: Config> {
776 pub encoded_len: u32,
778 pub extra_weight: Weight,
781 _phantom: PhantomData<T>,
782}
783
784impl<T: Config> EthTxInfo<T> {
785 pub fn new(encoded_len: u32, extra_weight: Weight) -> Self {
787 Self { encoded_len, extra_weight, _phantom: PhantomData }
788 }
789
790 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 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 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 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 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 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}