referrerpolicy=no-referrer-when-downgrade

pallet_revive/
primitives.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//! A crate that hosts a common definitions that are relevant for the pallet-revive.
19
20use crate::{
21	BalanceOf, Config, H160, U256, deposit_payment::Funds, exec::MomentOf, mock::MockHandler,
22	storage::WriteOutcome, transient_storage::TransientStorage,
23};
24use alloc::{boxed::Box, fmt::Debug, string::String, vec::Vec};
25use codec::{Decode, Encode, MaxEncodedLen};
26use core::cell::RefCell;
27use frame_support::{DefaultNoBound, traits::tokens::Balance, weights::Weight};
28use pallet_revive_types::runtime_api::{
29	CodeV1, ContractResultV1, EthTransactInfoV1, ExecReturnValueV1, InstantiateReturnValueV1,
30	StorageDepositV1,
31};
32use pallet_revive_uapi::ReturnFlags;
33use scale_info::TypeInfo;
34use sp_core::Get;
35use sp_runtime::{
36	DispatchError,
37	traits::{One, Saturating, Zero},
38};
39
40/// Result type of a `bare_call` or `bare_instantiate` call as well as `ContractsApi::call` and
41/// `ContractsApi::instantiate`.
42///
43/// It contains the execution result together with some auxiliary information.
44///
45/// #Note
46///
47/// It has been extended to include `events` at the end of the struct while not bumping the
48/// `ContractsApi` version. Therefore when SCALE decoding a `ContractResult` its trailing data
49/// should be ignored to avoid any potential compatibility issues.
50#[derive(Clone, Eq, PartialEq, Debug)]
51pub struct ContractResult<R, Balance> {
52	/// How much weight was consumed during execution.
53	pub weight_consumed: Weight,
54	/// How much weight is required as weight limit in order to execute this call.
55	///
56	/// This value should be used to determine the weight limit for on-chain execution.
57	///
58	/// # Note
59	///
60	/// This can be higher than [`Self::weight_consumed`] in the following cases:
61	/// - Nested calls: under the EIP-150 63/64 rule, each caller keeps part of its remaining
62	///   weight, so the retained weight is added on top of what each nested call needs.
63	/// - Weight pre-charging: an operation charges its worst-case weight up front and refunds the
64	///   unused part once its actual cost is known.
65	/// - Call stipends: a call that gets a stipend counts the whole stipend as required, even if
66	///   the callee uses less.
67	pub weight_required: Weight,
68	/// How much balance was paid by the origin into the contract's deposit account in order to
69	/// pay for storage.
70	///
71	/// The storage deposit is never actually charged from the origin in case of [`Self::result`]
72	/// is `Err`. This is because on error all storage changes are rolled back including the
73	/// payment of the deposit.
74	pub storage_deposit: StorageDeposit<Balance>,
75	/// The maximal storage deposit amount required at any time during the execution.
76	///
77	/// This can be higher than [`Self::storage_deposit`] in the following cases:
78	/// - Nested calls: under the EIP-150 63/64 rule, each caller keeps part of its remaining
79	///   deposit, so the retained deposit is added on top of what each nested call needs.
80	/// - Refunds: deposit charged and then refunded during the execution.
81	/// - Reverted calls: deposit charged by a nested call that reverted, which discards its
82	///   storage changes.
83	///
84	/// This is always a `StorageDeposit::Charge(..)`.
85	pub max_storage_deposit: StorageDeposit<Balance>,
86	/// The amount of Ethereum gas that has been consumed during execution.
87	pub gas_consumed: Balance,
88	/// The execution result of the vm binary code.
89	pub result: Result<R, DispatchError>,
90}
91
92impl<R: Default, B: Balance> Default for ContractResult<R, B> {
93	fn default() -> Self {
94		Self {
95			weight_consumed: Default::default(),
96			weight_required: Default::default(),
97			storage_deposit: Default::default(),
98			max_storage_deposit: Default::default(),
99			gas_consumed: Default::default(),
100			result: Ok(Default::default()),
101		}
102	}
103}
104
105impl<R, RV1, Balance> From<ContractResult<R, Balance>> for ContractResultV1<RV1, Balance>
106where
107	RV1: From<R>,
108{
109	fn from(value: ContractResult<R, Balance>) -> Self {
110		Self {
111			weight_consumed: value.weight_consumed,
112			weight_required: value.weight_required,
113			storage_deposit: value.storage_deposit.into(),
114			max_storage_deposit: value.max_storage_deposit.into(),
115			gas_consumed: value.gas_consumed,
116			result: value.result.map(Into::into),
117		}
118	}
119}
120
121/// The result of the execution of a `eth_transact` call.
122#[derive(Clone, Eq, PartialEq, Default, Debug)]
123pub struct EthTransactInfo<Balance> {
124	/// The amount of weight that was necessary to execute the transaction.
125	///
126	/// This is [`ContractResult::weight_required`].
127	pub weight_required: Weight,
128	/// Final storage deposit charged.
129	pub storage_deposit: Balance,
130	/// Maximal storage deposit required at any time during execution.
131	///
132	/// This is [`ContractResult::max_storage_deposit`], or the worst-case deposit for the
133	/// transaction's authorizations if that is higher.
134	pub max_storage_deposit: Balance,
135	/// The weight and deposit equivalent in EVM Gas.
136	pub eth_gas: U256,
137	/// The execution return value.
138	pub data: Vec<u8>,
139}
140
141impl<Balance> From<EthTransactInfo<Balance>> for EthTransactInfoV1<Balance> {
142	fn from(value: EthTransactInfo<Balance>) -> Self {
143		Self {
144			weight_required: value.weight_required,
145			storage_deposit: value.storage_deposit,
146			max_storage_deposit: value.max_storage_deposit,
147			eth_gas: value.eth_gas,
148			data: value.data,
149		}
150	}
151}
152
153/// Error type of a `eth_transact` call.
154#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)]
155pub enum EthTransactError {
156	Data(Vec<u8>),
157	Message(String),
158}
159
160#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)]
161/// Error encountered while creating a BalanceWithDust from a U256 balance.
162pub enum BalanceConversionError {
163	/// Error encountered while creating the main balance value.
164	Value,
165	/// Error encountered while creating the dust value.
166	Dust,
167}
168
169/// A Balance amount along with some "dust" to represent the lowest decimals that can't be expressed
170/// in the native currency
171#[derive(Default, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Debug)]
172pub struct BalanceWithDust<Balance> {
173	/// The value expressed in the native currency
174	value: Balance,
175	/// The dust, representing up to 1 unit of the native currency.
176	/// The dust is bounded between 0 and `crate::Config::NativeToEthRatio`
177	dust: u32,
178}
179
180impl<Balance> From<Balance> for BalanceWithDust<Balance> {
181	fn from(value: Balance) -> Self {
182		Self { value, dust: 0 }
183	}
184}
185
186impl<Balance> BalanceWithDust<Balance> {
187	/// Deconstructs the `BalanceWithDust` into its components.
188	pub fn deconstruct(self) -> (Balance, u32) {
189		(self.value, self.dust)
190	}
191
192	/// Creates a new `BalanceWithDust` with the given value and dust.
193	pub fn new_unchecked<T: Config>(value: Balance, dust: u32) -> Self {
194		debug_assert!(dust < T::NativeToEthRatio::get());
195		Self { value, dust }
196	}
197
198	/// Creates a new `BalanceWithDust` from the given EVM value.
199	pub fn from_value<T: Config>(
200		value: U256,
201	) -> Result<BalanceWithDust<BalanceOf<T>>, BalanceConversionError> {
202		if value.is_zero() {
203			return Ok(Default::default());
204		}
205
206		let (quotient, remainder) = value.div_mod(T::NativeToEthRatio::get().into());
207		let value = quotient.try_into().map_err(|_| BalanceConversionError::Value)?;
208		let dust = remainder.try_into().map_err(|_| BalanceConversionError::Dust)?;
209
210		Ok(BalanceWithDust { value, dust })
211	}
212}
213
214impl<Balance: Zero + One + Saturating> BalanceWithDust<Balance> {
215	/// Returns true if both the value and dust are zero.
216	pub fn is_zero(&self) -> bool {
217		self.value.is_zero() && self.dust == 0
218	}
219
220	/// Returns the Balance rounded to the nearest whole unit if the dust is non-zero.
221	pub fn into_rounded_balance(self) -> Balance {
222		if self.dust == 0 { self.value } else { self.value.saturating_add(Balance::one()) }
223	}
224}
225
226/// Result type of a `bare_code_upload` call.
227pub type CodeUploadResult<Balance> = Result<CodeUploadReturnValue<Balance>, DispatchError>;
228
229/// Result type of a `get_storage` call.
230pub type GetStorageResult = Result<Option<Vec<u8>>, ContractAccessError>;
231
232/// Result type of a `set_storage` call.
233pub type SetStorageResult = Result<WriteOutcome, ContractAccessError>;
234
235/// The possible errors that can happen querying the storage of a contract.
236#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, MaxEncodedLen, Debug, TypeInfo)]
237pub enum ContractAccessError {
238	/// The given address doesn't point to a contract.
239	DoesntExist,
240	/// Storage key cannot be decoded from the provided input data.
241	KeyDecodingFailed,
242	/// Writing to storage failed.
243	StorageWriteFailed(DispatchError),
244}
245
246/// Output of a contract call or instantiation which ran to completion.
247#[derive(Clone, PartialEq, Eq, Debug, Default)]
248pub struct ExecReturnValue {
249	/// Flags passed along by `seal_return`. Empty when `seal_return` was never called.
250	pub flags: ReturnFlags,
251	/// Buffer passed along by `seal_return`. Empty when `seal_return` was never called.
252	pub data: Vec<u8>,
253}
254
255impl ExecReturnValue {
256	/// The contract did revert all storage changes.
257	pub fn did_revert(&self) -> bool {
258		self.flags.contains(ReturnFlags::REVERT)
259	}
260}
261
262impl From<ExecReturnValue> for ExecReturnValueV1 {
263	fn from(value: ExecReturnValue) -> Self {
264		Self { flags: value.flags, data: value.data }
265	}
266}
267
268/// The result of a successful contract instantiation.
269#[derive(Clone, PartialEq, Eq, Debug, Default)]
270pub struct InstantiateReturnValue {
271	/// The output of the called constructor.
272	pub result: ExecReturnValue,
273	/// The address of the new contract.
274	pub addr: H160,
275}
276
277impl From<InstantiateReturnValue> for InstantiateReturnValueV1 {
278	fn from(value: InstantiateReturnValue) -> Self {
279		Self { result: value.result.into(), addr: value.addr }
280	}
281}
282
283/// The result of successfully uploading a contract.
284#[derive(Clone, PartialEq, Eq, Encode, Decode, MaxEncodedLen, Debug, TypeInfo)]
285pub struct CodeUploadReturnValue<Balance> {
286	/// The key under which the new code is stored.
287	pub code_hash: sp_core::H256,
288	/// The deposit that was reserved at the caller. Is zero when the code already existed.
289	pub deposit: Balance,
290}
291
292impl<Balance> From<CodeUploadReturnValue<Balance>>
293	for pallet_revive_types::runtime_api::CodeUploadReturnValueV1<Balance>
294{
295	fn from(value: CodeUploadReturnValue<Balance>) -> Self {
296		Self { code_hash: value.code_hash, deposit: value.deposit }
297	}
298}
299
300/// Reference to an existing code hash or a new vm module.
301#[derive(Clone, Eq, PartialEq, Debug)]
302pub enum Code {
303	/// A vm module as raw bytes.
304	Upload(Vec<u8>),
305	/// The code hash of an on-chain vm binary blob.
306	Existing(sp_core::H256),
307}
308
309impl From<CodeV1> for Code {
310	fn from(value: CodeV1) -> Self {
311		match value {
312			CodeV1::Upload(code) => Self::Upload(code),
313			CodeV1::Existing(code_hash) => Self::Existing(code_hash),
314		}
315	}
316}
317
318/// The amount of balance that was either charged or refunded in order to pay for storage.
319#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
320pub enum StorageDeposit<Balance> {
321	/// The transaction reduced storage consumption.
322	///
323	/// This means that the specified amount of balance was transferred from the involved
324	/// deposit accounts to the origin.
325	Refund(Balance),
326	/// The transaction increased storage consumption.
327	///
328	/// This means that the specified amount of balance was transferred from the origin
329	/// to the involved deposit accounts.
330	Charge(Balance),
331}
332
333impl<Balance> From<StorageDeposit<Balance>> for StorageDepositV1<Balance> {
334	fn from(value: StorageDeposit<Balance>) -> Self {
335		match value {
336			StorageDeposit::Refund(amount) => Self::Refund(amount),
337			StorageDeposit::Charge(amount) => Self::Charge(amount),
338		}
339	}
340}
341
342impl<T, Balance> ContractResult<T, Balance> {
343	pub fn map_result<V>(self, map_fn: impl FnOnce(T) -> V) -> ContractResult<V, Balance> {
344		ContractResult {
345			weight_consumed: self.weight_consumed,
346			weight_required: self.weight_required,
347			storage_deposit: self.storage_deposit,
348			max_storage_deposit: self.max_storage_deposit,
349			gas_consumed: self.gas_consumed,
350			result: self.result.map(map_fn),
351		}
352	}
353}
354
355impl<Balance: Zero> Default for StorageDeposit<Balance> {
356	fn default() -> Self {
357		Self::Charge(Zero::zero())
358	}
359}
360
361impl<Balance: Zero + Copy> StorageDeposit<Balance> {
362	/// Returns how much balance is charged or `0` in case of a refund.
363	pub fn charge_or_zero(&self) -> Balance {
364		match self {
365			Self::Charge(amount) => *amount,
366			Self::Refund(_) => Zero::zero(),
367		}
368	}
369
370	pub fn is_zero(&self) -> bool {
371		match self {
372			Self::Charge(amount) => amount.is_zero(),
373			Self::Refund(amount) => amount.is_zero(),
374		}
375	}
376}
377
378impl<Balance> StorageDeposit<Balance>
379where
380	Balance: frame_support::traits::tokens::Balance + Saturating + Ord + Copy,
381{
382	/// This is essentially a saturating signed add.
383	pub fn saturating_add(&self, rhs: &Self) -> Self {
384		use StorageDeposit::*;
385		match (self, rhs) {
386			(Charge(lhs), Charge(rhs)) => Charge(lhs.saturating_add(*rhs)),
387			(Refund(lhs), Refund(rhs)) => Refund(lhs.saturating_add(*rhs)),
388			(Charge(lhs), Refund(rhs)) => {
389				if lhs >= rhs {
390					Charge(lhs.saturating_sub(*rhs))
391				} else {
392					Refund(rhs.saturating_sub(*lhs))
393				}
394			},
395			(Refund(lhs), Charge(rhs)) => {
396				if lhs > rhs {
397					Refund(lhs.saturating_sub(*rhs))
398				} else {
399					Charge(rhs.saturating_sub(*lhs))
400				}
401			},
402		}
403	}
404
405	/// This is essentially a saturating signed sub.
406	pub fn saturating_sub(&self, rhs: &Self) -> Self {
407		use StorageDeposit::*;
408		match (self, rhs) {
409			(Charge(lhs), Refund(rhs)) => Charge(lhs.saturating_add(*rhs)),
410			(Refund(lhs), Charge(rhs)) => Refund(lhs.saturating_add(*rhs)),
411			(Charge(lhs), Charge(rhs)) => {
412				if lhs >= rhs {
413					Charge(lhs.saturating_sub(*rhs))
414				} else {
415					Refund(rhs.saturating_sub(*lhs))
416				}
417			},
418			(Refund(lhs), Refund(rhs)) => {
419				if lhs > rhs {
420					Refund(lhs.saturating_sub(*rhs))
421				} else {
422					Charge(rhs.saturating_sub(*lhs))
423				}
424			},
425		}
426	}
427
428	/// If the amount of deposit (this type) is constrained by a `limit` this calculates how
429	/// much balance (if any) is still available from this limit.
430	///
431	/// # Note
432	///
433	/// In case of a refund the return value can be larger than `limit`.
434	pub fn available(&self, limit: &Balance) -> Option<Balance> {
435		use StorageDeposit::*;
436		match self {
437			Charge(amount) => limit.checked_sub(amount),
438			Refund(amount) => Some(limit.saturating_add(*amount)),
439		}
440	}
441}
442
443/// `Stack` wide configuration options.
444#[derive(DefaultNoBound)]
445pub struct ExecConfig<T: Config> {
446	/// Indicates whether the account nonce should be incremented after instantiating a new
447	/// contract.
448	///
449	/// In Substrate, where transactions can be batched, the account's nonce should be incremented
450	/// after each instantiation, ensuring that each instantiation uses a unique nonce.
451	///
452	/// For transactions sent from Ethereum wallets, which cannot be batched, the nonce should only
453	/// be incremented once. In these cases, set this to `false` to suppress an extra nonce
454	/// increment.
455	///
456	/// Note:
457	/// The origin's nonce is already incremented pre-dispatch by the `CheckNonce` transaction
458	/// extension.
459	///
460	/// This does not apply to contract initiated instantatiations. Those will always bump the
461	/// instantiating contract's nonce.
462	pub bump_nonce: bool,
463	/// Whether deposits will be withdrawn from the pallet_transaction_payment credit (`Some`)
464	/// free balance (`None`).
465	///
466	/// Contains the encoded_len + base weight.
467	pub collect_deposit_from_hold: Option<(u32, Weight)>,
468	/// The gas price that was chosen for this transaction.
469	///
470	/// It is determined when transforming `eth_transact` into a proper extrinsic.
471	pub effective_gas_price: Option<U256>,
472	/// Whether this configuration was created for a dry-run execution.
473	/// Use to enable logic that should only run in dry-run mode.
474	pub is_dry_run: Option<DryRunConfigurations<MomentOf<T>>>,
475	/// An optional mock handler that can be used to override certain behaviors.
476	/// This is primarily used for testing purposes and should be `None` in production
477	/// environments.
478	pub mock_handler: Option<Box<dyn MockHandler<T>>>,
479	/// Externally supplied transient storage.
480	///
481	/// This is only used for testing purposes and should be `None` in production
482	/// environments.
483	pub test_env_transient_storage: Option<RefCell<TransientStorage<T>>>,
484}
485
486impl<T: Config> ExecConfig<T> {
487	/// Create a default config appropriate when the call originated from a substrate tx.
488	pub fn new_substrate_tx() -> Self {
489		Self {
490			bump_nonce: true,
491			collect_deposit_from_hold: None,
492			effective_gas_price: None,
493			is_dry_run: None,
494			mock_handler: None,
495			test_env_transient_storage: None,
496		}
497	}
498
499	pub fn new_substrate_tx_without_bump() -> Self {
500		Self {
501			bump_nonce: false,
502			collect_deposit_from_hold: None,
503			effective_gas_price: None,
504			mock_handler: None,
505			is_dry_run: None,
506			test_env_transient_storage: None,
507		}
508	}
509
510	/// Create a default config appropriate when the call originated from a ethereum tx.
511	pub fn new_eth_tx(effective_gas_price: U256, encoded_len: u32, base_weight: Weight) -> Self {
512		Self {
513			bump_nonce: false,
514			collect_deposit_from_hold: Some((encoded_len, base_weight)),
515			effective_gas_price: Some(effective_gas_price),
516			mock_handler: None,
517			is_dry_run: None,
518			test_env_transient_storage: None,
519		}
520	}
521
522	/// Set this config to be a dry-run.
523	pub fn with_dry_run(mut self, timestamp_override: impl Into<Option<MomentOf<T>>>) -> Self {
524		self.is_dry_run =
525			Some(DryRunConfigurations { timestamp_override: timestamp_override.into() });
526		self
527	}
528
529	/// Classify `account` as a deposit source or refund destination based on
530	/// [`Self::collect_deposit_from_hold`]: [`Funds::TxFee`] under eth-tx dispatch (where
531	/// deposits flow through the tx fee pool), otherwise [`Funds::Balance`].
532	pub fn funds<'a>(&self, account: &'a T::AccountId) -> Funds<'a, T::AccountId> {
533		if self.collect_deposit_from_hold.is_some() {
534			Funds::TxFee(account)
535		} else {
536			Funds::Balance(account)
537		}
538	}
539
540	/// Almost clone for testing (does not clone mock_handler)
541	#[cfg(test)]
542	pub fn clone(&self) -> Self {
543		Self {
544			bump_nonce: self.bump_nonce,
545			collect_deposit_from_hold: self.collect_deposit_from_hold,
546			effective_gas_price: self.effective_gas_price,
547			is_dry_run: self.is_dry_run.clone(),
548			mock_handler: None,
549			test_env_transient_storage: None,
550		}
551	}
552}
553
554#[derive(Clone)]
555pub struct DryRunConfigurations<Moment> {
556	pub timestamp_override: Option<Moment>,
557}
558
559/// Indicates whether the code was removed after the last refcount was decremented.
560#[must_use = "You must handle whether the code was removed or not."]
561pub enum CodeRemoved {
562	/// The code was not removed. (refcount > 0)
563	No,
564	/// The code was removed. (refcount == 0)
565	Yes,
566}