pallet-revive 0.15.0

FRAME pallet for PolkaVM contracts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A crate that hosts a common definitions that are relevant for the pallet-revive.

use crate::{
	BalanceOf, Config, H160, Time, U256, deposit_payment::Funds, evm::DryRunConfig,
	mock::MockHandler, storage::WriteOutcome, transient_storage::TransientStorage,
};
use alloc::{boxed::Box, fmt::Debug, string::String, vec::Vec};
use codec::{Decode, Encode, MaxEncodedLen};
use core::cell::RefCell;
use frame_support::{DefaultNoBound, traits::tokens::Balance, weights::Weight};
use pallet_revive_uapi::ReturnFlags;
use scale_info::TypeInfo;
use sp_core::Get;
use sp_runtime::{
	DispatchError,
	traits::{One, Saturating, Zero},
};

/// Result type of a `bare_call` or `bare_instantiate` call as well as `ContractsApi::call` and
/// `ContractsApi::instantiate`.
///
/// It contains the execution result together with some auxiliary information.
///
/// #Note
///
/// It has been extended to include `events` at the end of the struct while not bumping the
/// `ContractsApi` version. Therefore when SCALE decoding a `ContractResult` its trailing data
/// should be ignored to avoid any potential compatibility issues.
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)]
pub struct ContractResult<R, Balance> {
	/// How much weight was consumed during execution.
	pub weight_consumed: Weight,
	/// How much weight is required as weight limit in order to execute this call.
	///
	/// This value should be used to determine the weight limit for on-chain execution.
	///
	/// # Note
	///
	/// This can only be different from [`Self::weight_consumed`] when weight pre charging
	/// is used. Currently, only `seal_call_runtime` makes use of pre charging.
	/// Additionally, any `seal_call` or `seal_instantiate` makes use of pre-charging
	/// when a non-zero `weight_limit` argument is supplied.
	pub weight_required: Weight,
	/// How much balance was paid by the origin into the contract's deposit account in order to
	/// pay for storage.
	///
	/// The storage deposit is never actually charged from the origin in case of [`Self::result`]
	/// is `Err`. This is because on error all storage changes are rolled back including the
	/// payment of the deposit.
	pub storage_deposit: StorageDeposit<Balance>,
	/// The maximal storage deposit amount that occured at any time during the execution.
	/// This can be higher than the final storage_deposit due to refunds
	/// This is always a StorageDeposit::Charge(..)
	pub max_storage_deposit: StorageDeposit<Balance>,
	/// The amount of Ethereum gas that has been consumed during execution.
	pub gas_consumed: Balance,
	/// The execution result of the vm binary code.
	pub result: Result<R, DispatchError>,
}

impl<R: Default, B: Balance> Default for ContractResult<R, B> {
	fn default() -> Self {
		Self {
			weight_consumed: Default::default(),
			weight_required: Default::default(),
			storage_deposit: Default::default(),
			max_storage_deposit: Default::default(),
			gas_consumed: Default::default(),
			result: Ok(Default::default()),
		}
	}
}

/// The result of the execution of a `eth_transact` call.
#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, Debug, TypeInfo)]
pub struct EthTransactInfo<Balance> {
	/// The amount of weight that was necessary to execute the transaction.
	pub weight_required: Weight,
	/// Final storage deposit charged.
	pub storage_deposit: Balance,
	/// Maximal storage deposit charged at any time during execution.
	pub max_storage_deposit: Balance,
	/// The weight and deposit equivalent in EVM Gas.
	pub eth_gas: U256,
	/// The execution return value.
	pub data: Vec<u8>,
}

/// Error type of a `eth_transact` call.
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)]
pub enum EthTransactError {
	Data(Vec<u8>),
	Message(String),
}

#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)]
/// Error encountered while creating a BalanceWithDust from a U256 balance.
pub enum BalanceConversionError {
	/// Error encountered while creating the main balance value.
	Value,
	/// Error encountered while creating the dust value.
	Dust,
}

/// A Balance amount along with some "dust" to represent the lowest decimals that can't be expressed
/// in the native currency
#[derive(Default, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Debug)]
pub struct BalanceWithDust<Balance> {
	/// The value expressed in the native currency
	value: Balance,
	/// The dust, representing up to 1 unit of the native currency.
	/// The dust is bounded between 0 and `crate::Config::NativeToEthRatio`
	dust: u32,
}

impl<Balance> From<Balance> for BalanceWithDust<Balance> {
	fn from(value: Balance) -> Self {
		Self { value, dust: 0 }
	}
}

impl<Balance> BalanceWithDust<Balance> {
	/// Deconstructs the `BalanceWithDust` into its components.
	pub fn deconstruct(self) -> (Balance, u32) {
		(self.value, self.dust)
	}

	/// Creates a new `BalanceWithDust` with the given value and dust.
	pub fn new_unchecked<T: Config>(value: Balance, dust: u32) -> Self {
		debug_assert!(dust < T::NativeToEthRatio::get());
		Self { value, dust }
	}

	/// Creates a new `BalanceWithDust` from the given EVM value.
	pub fn from_value<T: Config>(
		value: U256,
	) -> Result<BalanceWithDust<BalanceOf<T>>, BalanceConversionError> {
		if value.is_zero() {
			return Ok(Default::default());
		}

		let (quotient, remainder) = value.div_mod(T::NativeToEthRatio::get().into());
		let value = quotient.try_into().map_err(|_| BalanceConversionError::Value)?;
		let dust = remainder.try_into().map_err(|_| BalanceConversionError::Dust)?;

		Ok(BalanceWithDust { value, dust })
	}
}

impl<Balance: Zero + One + Saturating> BalanceWithDust<Balance> {
	/// Returns true if both the value and dust are zero.
	pub fn is_zero(&self) -> bool {
		self.value.is_zero() && self.dust == 0
	}

	/// Returns the Balance rounded to the nearest whole unit if the dust is non-zero.
	pub fn into_rounded_balance(self) -> Balance {
		if self.dust == 0 { self.value } else { self.value.saturating_add(Balance::one()) }
	}
}

/// Result type of a `bare_code_upload` call.
pub type CodeUploadResult<Balance> = Result<CodeUploadReturnValue<Balance>, DispatchError>;

/// Result type of a `get_storage` call.
pub type GetStorageResult = Result<Option<Vec<u8>>, ContractAccessError>;

/// Result type of a `set_storage` call.
pub type SetStorageResult = Result<WriteOutcome, ContractAccessError>;

/// The possible errors that can happen querying the storage of a contract.
#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, MaxEncodedLen, Debug, TypeInfo)]
pub enum ContractAccessError {
	/// The given address doesn't point to a contract.
	DoesntExist,
	/// Storage key cannot be decoded from the provided input data.
	KeyDecodingFailed,
	/// Writing to storage failed.
	StorageWriteFailed(DispatchError),
}

/// Output of a contract call or instantiation which ran to completion.
#[derive(Clone, PartialEq, Eq, Encode, Decode, Debug, TypeInfo, Default)]
pub struct ExecReturnValue {
	/// Flags passed along by `seal_return`. Empty when `seal_return` was never called.
	pub flags: ReturnFlags,
	/// Buffer passed along by `seal_return`. Empty when `seal_return` was never called.
	pub data: Vec<u8>,
}

impl ExecReturnValue {
	/// The contract did revert all storage changes.
	pub fn did_revert(&self) -> bool {
		self.flags.contains(ReturnFlags::REVERT)
	}
}

/// The result of a successful contract instantiation.
#[derive(Clone, PartialEq, Eq, Encode, Decode, Debug, TypeInfo, Default)]
pub struct InstantiateReturnValue {
	/// The output of the called constructor.
	pub result: ExecReturnValue,
	/// The address of the new contract.
	pub addr: H160,
}

/// The result of successfully uploading a contract.
#[derive(Clone, PartialEq, Eq, Encode, Decode, MaxEncodedLen, Debug, TypeInfo)]
pub struct CodeUploadReturnValue<Balance> {
	/// The key under which the new code is stored.
	pub code_hash: sp_core::H256,
	/// The deposit that was reserved at the caller. Is zero when the code already existed.
	pub deposit: Balance,
}

/// Reference to an existing code hash or a new vm module.
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)]
pub enum Code {
	/// A vm module as raw bytes.
	Upload(Vec<u8>),
	/// The code hash of an on-chain vm binary blob.
	Existing(sp_core::H256),
}

/// The amount of balance that was either charged or refunded in order to pay for storage.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, MaxEncodedLen, Debug, TypeInfo)]
pub enum StorageDeposit<Balance> {
	/// The transaction reduced storage consumption.
	///
	/// This means that the specified amount of balance was transferred from the involved
	/// deposit accounts to the origin.
	Refund(Balance),
	/// The transaction increased storage consumption.
	///
	/// This means that the specified amount of balance was transferred from the origin
	/// to the involved deposit accounts.
	Charge(Balance),
}

impl<T, Balance> ContractResult<T, Balance> {
	pub fn map_result<V>(self, map_fn: impl FnOnce(T) -> V) -> ContractResult<V, Balance> {
		ContractResult {
			weight_consumed: self.weight_consumed,
			weight_required: self.weight_required,
			storage_deposit: self.storage_deposit,
			max_storage_deposit: self.max_storage_deposit,
			gas_consumed: self.gas_consumed,
			result: self.result.map(map_fn),
		}
	}
}

impl<Balance: Zero> Default for StorageDeposit<Balance> {
	fn default() -> Self {
		Self::Charge(Zero::zero())
	}
}

impl<Balance: Zero + Copy> StorageDeposit<Balance> {
	/// Returns how much balance is charged or `0` in case of a refund.
	pub fn charge_or_zero(&self) -> Balance {
		match self {
			Self::Charge(amount) => *amount,
			Self::Refund(_) => Zero::zero(),
		}
	}

	pub fn is_zero(&self) -> bool {
		match self {
			Self::Charge(amount) => amount.is_zero(),
			Self::Refund(amount) => amount.is_zero(),
		}
	}
}

impl<Balance> StorageDeposit<Balance>
where
	Balance: frame_support::traits::tokens::Balance + Saturating + Ord + Copy,
{
	/// This is essentially a saturating signed add.
	pub fn saturating_add(&self, rhs: &Self) -> Self {
		use StorageDeposit::*;
		match (self, rhs) {
			(Charge(lhs), Charge(rhs)) => Charge(lhs.saturating_add(*rhs)),
			(Refund(lhs), Refund(rhs)) => Refund(lhs.saturating_add(*rhs)),
			(Charge(lhs), Refund(rhs)) => {
				if lhs >= rhs {
					Charge(lhs.saturating_sub(*rhs))
				} else {
					Refund(rhs.saturating_sub(*lhs))
				}
			},
			(Refund(lhs), Charge(rhs)) => {
				if lhs > rhs {
					Refund(lhs.saturating_sub(*rhs))
				} else {
					Charge(rhs.saturating_sub(*lhs))
				}
			},
		}
	}

	/// This is essentially a saturating signed sub.
	pub fn saturating_sub(&self, rhs: &Self) -> Self {
		use StorageDeposit::*;
		match (self, rhs) {
			(Charge(lhs), Refund(rhs)) => Charge(lhs.saturating_add(*rhs)),
			(Refund(lhs), Charge(rhs)) => Refund(lhs.saturating_add(*rhs)),
			(Charge(lhs), Charge(rhs)) => {
				if lhs >= rhs {
					Charge(lhs.saturating_sub(*rhs))
				} else {
					Refund(rhs.saturating_sub(*lhs))
				}
			},
			(Refund(lhs), Refund(rhs)) => {
				if lhs > rhs {
					Refund(lhs.saturating_sub(*rhs))
				} else {
					Charge(rhs.saturating_sub(*lhs))
				}
			},
		}
	}

	/// If the amount of deposit (this type) is constrained by a `limit` this calculates how
	/// much balance (if any) is still available from this limit.
	///
	/// # Note
	///
	/// In case of a refund the return value can be larger than `limit`.
	pub fn available(&self, limit: &Balance) -> Option<Balance> {
		use StorageDeposit::*;
		match self {
			Charge(amount) => limit.checked_sub(amount),
			Refund(amount) => Some(limit.saturating_add(*amount)),
		}
	}
}

/// `Stack` wide configuration options.
#[derive(DefaultNoBound)]
pub struct ExecConfig<T: Config> {
	/// Indicates whether the account nonce should be incremented after instantiating a new
	/// contract.
	///
	/// In Substrate, where transactions can be batched, the account's nonce should be incremented
	/// after each instantiation, ensuring that each instantiation uses a unique nonce.
	///
	/// For transactions sent from Ethereum wallets, which cannot be batched, the nonce should only
	/// be incremented once. In these cases, set this to `false` to suppress an extra nonce
	/// increment.
	///
	/// Note:
	/// The origin's nonce is already incremented pre-dispatch by the `CheckNonce` transaction
	/// extension.
	///
	/// This does not apply to contract initiated instantatiations. Those will always bump the
	/// instantiating contract's nonce.
	pub bump_nonce: bool,
	/// Whether deposits will be withdrawn from the pallet_transaction_payment credit (`Some`)
	/// free balance (`None`).
	///
	/// Contains the encoded_len + base weight.
	pub collect_deposit_from_hold: Option<(u32, Weight)>,
	/// The gas price that was chosen for this transaction.
	///
	/// It is determined when transforming `eth_transact` into a proper extrinsic.
	pub effective_gas_price: Option<U256>,
	/// Whether this configuration was created for a dry-run execution.
	/// Use to enable logic that should only run in dry-run mode.
	pub is_dry_run: Option<DryRunConfig<<<T as Config>::Time as Time>::Moment>>,
	/// An optional mock handler that can be used to override certain behaviors.
	/// This is primarily used for testing purposes and should be `None` in production
	/// environments.
	pub mock_handler: Option<Box<dyn MockHandler<T>>>,
	/// Externally supplied transient storage.
	///
	/// This is only used for testing purposes and should be `None` in production
	/// environments.
	pub test_env_transient_storage: Option<RefCell<TransientStorage<T>>>,
}

impl<T: Config> ExecConfig<T> {
	/// Create a default config appropriate when the call originated from a substrate tx.
	pub fn new_substrate_tx() -> Self {
		Self {
			bump_nonce: true,
			collect_deposit_from_hold: None,
			effective_gas_price: None,
			is_dry_run: None,
			mock_handler: None,
			test_env_transient_storage: None,
		}
	}

	pub fn new_substrate_tx_without_bump() -> Self {
		Self {
			bump_nonce: false,
			collect_deposit_from_hold: None,
			effective_gas_price: None,
			mock_handler: None,
			is_dry_run: None,
			test_env_transient_storage: None,
		}
	}

	/// Create a default config appropriate when the call originated from a ethereum tx.
	pub fn new_eth_tx(effective_gas_price: U256, encoded_len: u32, base_weight: Weight) -> Self {
		Self {
			bump_nonce: false,
			collect_deposit_from_hold: Some((encoded_len, base_weight)),
			effective_gas_price: Some(effective_gas_price),
			mock_handler: None,
			is_dry_run: None,
			test_env_transient_storage: None,
		}
	}

	/// Set this config to be a dry-run.
	pub fn with_dry_run(
		mut self,
		dry_run_config: DryRunConfig<<<T as Config>::Time as Time>::Moment>,
	) -> Self {
		self.is_dry_run = Some(dry_run_config);
		self
	}

	/// Classify `account` as a deposit source or refund destination based on
	/// [`Self::collect_deposit_from_hold`]: [`Funds::TxFee`] under eth-tx dispatch (where
	/// deposits flow through the tx fee pool), otherwise [`Funds::Balance`].
	pub fn funds<'a>(&self, account: &'a T::AccountId) -> Funds<'a, T::AccountId> {
		if self.collect_deposit_from_hold.is_some() {
			Funds::TxFee(account)
		} else {
			Funds::Balance(account)
		}
	}

	/// Almost clone for testing (does not clone mock_handler)
	#[cfg(test)]
	pub fn clone(&self) -> Self {
		Self {
			bump_nonce: self.bump_nonce,
			collect_deposit_from_hold: self.collect_deposit_from_hold,
			effective_gas_price: self.effective_gas_price,
			is_dry_run: self.is_dry_run.clone(),
			mock_handler: None,
			test_env_transient_storage: None,
		}
	}
}

/// Indicates whether the code was removed after the last refcount was decremented.
#[must_use = "You must handle whether the code was removed or not."]
pub enum CodeRemoved {
	/// The code was not removed. (refcount > 0)
	No,
	/// The code was removed. (refcount == 0)
	Yes,
}