referrerpolicy=no-referrer-when-downgrade

pallet_contracts/
lib.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//! # Contracts Pallet
19//!
20//! The Contracts module provides functionality for the runtime to deploy and execute WebAssembly
21//! smart-contracts.
22//!
23//! - [`Config`]
24//! - [`Call`]
25//!
26//! ## Overview
27//!
28//! This module extends accounts based on the [`frame_support::traits::fungible`] traits to have
29//! smart-contract functionality. It can be used with other modules that implement accounts based on
30//! the [`frame_support::traits::fungible`] traits. These "smart-contract accounts" have the ability
31//! to instantiate smart-contracts and make calls to other contract and non-contract accounts.
32//!
33//! The smart-contract code is stored once, and later retrievable via its hash.
34//! This means that multiple smart-contracts can be instantiated from the same hash, without
35//! replicating the code each time.
36//!
37//! When a smart-contract is called, its associated code is retrieved via the code hash and gets
38//! executed. This call can alter the storage entries of the smart-contract account, instantiate new
39//! smart-contracts, or call other smart-contracts.
40//!
41//! Finally, when an account is reaped, its associated code and storage of the smart-contract
42//! account will also be deleted.
43//!
44//! ### Weight
45//!
46//! Senders must specify a [`Weight`] limit with every call, as all instructions invoked by the
47//! smart-contract require weight. Unused weight is refunded after the call, regardless of the
48//! execution outcome.
49//!
50//! If the weight limit is reached, then all calls and state changes (including balance transfers)
51//! are only reverted at the current call's contract level. For example, if contract A calls B and B
52//! runs out of gas mid-call, then all of B's calls are reverted. Assuming correct error handling by
53//! contract A, A's other calls and state changes still persist.
54//!
55//! ### Notable Scenarios
56//!
57//! Contract call failures are not always cascading. When failures occur in a sub-call, they do not
58//! "bubble up", and the call will only revert at the specific contract level. For example, if
59//! contract A calls contract B, and B fails, A can decide how to handle that failure, either
60//! proceeding or reverting A's changes.
61//!
62//! ## Interface
63//!
64//! ### Dispatchable functions
65//!
66//! * [`Pallet::instantiate_with_code`] - Deploys a new contract from the supplied Wasm binary,
67//! optionally transferring
68//! some balance. This instantiates a new smart contract account with the supplied code and
69//! calls its constructor to initialize the contract.
70//! * [`Pallet::instantiate`] - The same as `instantiate_with_code` but instead of uploading new
71//! code an existing `code_hash` is supplied.
72//! * [`Pallet::call`] - Makes a call to an account, optionally transferring some balance.
73//! * [`Pallet::upload_code`] - Uploads new code without instantiating a contract from it.
74//! * [`Pallet::remove_code`] - Removes the stored code and refunds the deposit to its owner. Only
75//!   allowed to code owner.
76//! * [`Pallet::set_code`] - Changes the code of an existing contract. Only allowed to `Root`
77//!   origin.
78//! * [`Pallet::migrate`] - Runs migration steps of current multi-block migration in priority,
79//!   before [`Hooks::on_idle`][frame_support::traits::Hooks::on_idle] activates.
80//!
81//! ## Usage
82//!
83//! * [`ink!`](https://use.ink) is language that enables writing Wasm-based smart contracts in plain
84//!   Rust.
85
86#![allow(rustdoc::private_intra_doc_links)]
87#![cfg_attr(not(feature = "std"), no_std)]
88#![cfg_attr(feature = "runtime-benchmarks", recursion_limit = "1024")]
89
90extern crate alloc;
91mod address;
92mod benchmarking;
93mod exec;
94mod gas;
95mod primitives;
96pub use primitives::*;
97
98mod schedule;
99mod storage;
100mod transient_storage;
101mod wasm;
102
103pub mod chain_extension;
104pub mod debug;
105pub mod migration;
106pub mod test_utils;
107pub mod weights;
108
109#[cfg(test)]
110mod tests;
111use crate::{
112	exec::{
113		AccountIdOf, ErrorOrigin, ExecError, Executable, Ext, Key, MomentOf, Stack as ExecStack,
114	},
115	gas::GasMeter,
116	storage::{meter::Meter as StorageMeter, ContractInfo, DeletionQueueManager},
117	wasm::{CodeInfo, RuntimeCosts, WasmBlob},
118};
119use codec::{Codec, Decode, DecodeWithMemTracking, Encode, HasCompact, MaxEncodedLen};
120use core::fmt::Debug;
121use environmental::*;
122use frame_support::{
123	dispatch::{GetDispatchInfo, Pays, PostDispatchInfo, RawOrigin, WithPostDispatchInfo},
124	ensure,
125	traits::{
126		fungible::{Inspect, Mutate, MutateHold},
127		ConstU32, Contains, Get, Randomness, Time,
128	},
129	weights::{Weight, WeightMeter},
130	BoundedVec, DefaultNoBound, RuntimeDebugNoBound,
131};
132use frame_system::{
133	ensure_signed,
134	pallet_prelude::{BlockNumberFor, OriginFor},
135	EventRecord, Pallet as System,
136};
137use scale_info::TypeInfo;
138use smallvec::Array;
139use sp_runtime::{
140	traits::{BadOrigin, Convert, Dispatchable, Saturating, StaticLookup, Zero},
141	DispatchError, RuntimeDebug,
142};
143
144pub use crate::{
145	address::{AddressGenerator, DefaultAddressGenerator},
146	debug::Tracing,
147	exec::Frame,
148	migration::{MigrateSequence, Migration, NoopMigration},
149	pallet::*,
150	schedule::{InstructionWeights, Limits, Schedule},
151	wasm::Determinism,
152};
153pub use weights::WeightInfo;
154
155#[cfg(doc)]
156pub use crate::wasm::api_doc;
157
158type CodeHash<T> = <T as frame_system::Config>::Hash;
159type TrieId = BoundedVec<u8, ConstU32<128>>;
160type BalanceOf<T> =
161	<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
162type CodeVec<T> = BoundedVec<u8, <T as Config>::MaxCodeLen>;
163type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
164type DebugBufferVec<T> = BoundedVec<u8, <T as Config>::MaxDebugBufferLen>;
165type EventRecordOf<T> =
166	EventRecord<<T as frame_system::Config>::RuntimeEvent, <T as frame_system::Config>::Hash>;
167
168/// The old weight type.
169///
170/// This is a copy of the [`frame_support::weights::OldWeight`] type since the contracts pallet
171/// needs to support it indefinitely.
172type OldWeight = u64;
173
174/// Used as a sentinel value when reading and writing contract memory.
175///
176/// It is usually used to signal `None` to a contract when only a primitive is allowed
177/// and we don't want to go through encoding a full Rust type. Using `u32::Max` is a safe
178/// sentinel because contracts are never allowed to use such a large amount of resources
179/// that this value makes sense for a memory location or length.
180const SENTINEL: u32 = u32::MAX;
181
182/// The target that is used for the log output emitted by this crate.
183///
184/// Hence you can use this target to selectively increase the log level for this crate.
185///
186/// Example: `RUST_LOG=runtime::contracts=debug my_code --dev`
187const LOG_TARGET: &str = "runtime::contracts";
188
189/// Wrapper around `PhantomData` to prevent it being filtered by `scale-info`.
190///
191/// `scale-info` filters out `PhantomData` fields because usually we are only interested
192/// in sized types. However, when trying to communicate **types** as opposed to **values**
193/// we want to have those zero sized types be included.
194#[derive(Encode, Decode, DefaultNoBound, TypeInfo)]
195#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
196pub struct EnvironmentType<T>(PhantomData<T>);
197
198/// List of all runtime configurable types that are used in the communication between
199/// `pallet-contracts` and any given contract.
200///
201/// Since those types are configurable they can vary between
202/// chains all using `pallet-contracts`. Hence we need a mechanism to communicate those types
203/// in a way that can be consumed by offchain tooling.
204///
205/// This type only exists in order to appear in the metadata where it can be read by
206/// offchain tooling.
207#[derive(Encode, Decode, DefaultNoBound, TypeInfo)]
208#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
209#[scale_info(skip_type_params(T))]
210pub struct Environment<T: Config> {
211	account_id: EnvironmentType<AccountIdOf<T>>,
212	balance: EnvironmentType<BalanceOf<T>>,
213	hash: EnvironmentType<<T as frame_system::Config>::Hash>,
214	hasher: EnvironmentType<<T as frame_system::Config>::Hashing>,
215	timestamp: EnvironmentType<MomentOf<T>>,
216	block_number: EnvironmentType<BlockNumberFor<T>>,
217}
218
219/// Defines the current version of the HostFn APIs.
220/// This is used to communicate the available APIs in pallet-contracts.
221///
222/// The version is bumped any time a new HostFn is added or stabilized.
223#[derive(Encode, Decode, TypeInfo)]
224pub struct ApiVersion(u16);
225impl Default for ApiVersion {
226	fn default() -> Self {
227		Self(4)
228	}
229}
230
231#[test]
232fn api_version_is_up_to_date() {
233	assert_eq!(
234		111,
235		crate::wasm::STABLE_API_COUNT,
236		"Stable API count has changed. Bump the returned value of ApiVersion::default() and update the test."
237	);
238}
239
240#[frame_support::pallet]
241pub mod pallet {
242	use super::*;
243	use crate::debug::Debugger;
244	use frame_support::pallet_prelude::*;
245	use frame_system::pallet_prelude::*;
246	use sp_runtime::Perbill;
247
248	/// The in-code storage version.
249	pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(16);
250
251	#[pallet::pallet]
252	#[pallet::storage_version(STORAGE_VERSION)]
253	pub struct Pallet<T>(_);
254
255	#[pallet::config(with_default)]
256	pub trait Config: frame_system::Config {
257		/// The time implementation used to supply timestamps to contracts through `seal_now`.
258		type Time: Time;
259
260		/// The generator used to supply randomness to contracts through `seal_random`.
261		///
262		/// # Deprecated
263		///
264		/// Codes using the randomness functionality cannot be uploaded. Neither can contracts
265		/// be instantiated from existing codes that use this deprecated functionality. It will
266		/// be removed eventually. Hence for new `pallet-contracts` deployments it is okay
267		/// to supply a dummy implementation for this type (because it is never used).
268		#[pallet::no_default_bounds]
269		type Randomness: Randomness<Self::Hash, BlockNumberFor<Self>>;
270
271		/// The fungible in which fees are paid and contract balances are held.
272		#[pallet::no_default]
273		type Currency: Inspect<Self::AccountId>
274			+ Mutate<Self::AccountId>
275			+ MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>;
276
277		/// The overarching event type.
278		#[pallet::no_default_bounds]
279		#[allow(deprecated)]
280		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
281
282		/// The overarching call type.
283		#[pallet::no_default_bounds]
284		type RuntimeCall: Dispatchable<RuntimeOrigin = Self::RuntimeOrigin, PostInfo = PostDispatchInfo>
285			+ GetDispatchInfo
286			+ codec::Decode
287			+ IsType<<Self as frame_system::Config>::RuntimeCall>;
288
289		/// Overarching hold reason.
290		#[pallet::no_default_bounds]
291		type RuntimeHoldReason: From<HoldReason>;
292
293		/// Filter that is applied to calls dispatched by contracts.
294		///
295		/// Use this filter to control which dispatchables are callable by contracts.
296		/// This is applied in **addition** to [`frame_system::Config::BaseCallFilter`].
297		/// It is recommended to treat this as a whitelist.
298		///
299		/// # Stability
300		///
301		/// The runtime **must** make sure that all dispatchables that are callable by
302		/// contracts remain stable. In addition [`Self::RuntimeCall`] itself must remain stable.
303		/// This means that no existing variants are allowed to switch their positions.
304		///
305		/// # Note
306		///
307		/// Note that dispatchables that are called via contracts do not spawn their
308		/// own wasm instance for each call (as opposed to when called via a transaction).
309		/// Therefore please make sure to be restrictive about which dispatchables are allowed
310		/// in order to not introduce a new DoS vector like memory allocation patterns that can
311		/// be exploited to drive the runtime into a panic.
312		///
313		/// This filter does not apply to XCM transact calls. To impose restrictions on XCM transact
314		/// calls, you must configure them separately within the XCM pallet itself.
315		#[pallet::no_default_bounds]
316		type CallFilter: Contains<<Self as frame_system::Config>::RuntimeCall>;
317
318		/// Used to answer contracts' queries regarding the current weight price. This is **not**
319		/// used to calculate the actual fee and is only for informational purposes.
320		#[pallet::no_default_bounds]
321		type WeightPrice: Convert<Weight, BalanceOf<Self>>;
322
323		/// Describes the weights of the dispatchables of this module and is also used to
324		/// construct a default cost schedule.
325		type WeightInfo: WeightInfo;
326
327		/// Type that allows the runtime authors to add new host functions for a contract to call.
328		#[pallet::no_default_bounds]
329		type ChainExtension: chain_extension::ChainExtension<Self> + Default;
330
331		/// Cost schedule and limits.
332		#[pallet::constant]
333		#[pallet::no_default]
334		type Schedule: Get<Schedule<Self>>;
335
336		/// The type of the call stack determines the maximum nesting depth of contract calls.
337		///
338		/// The allowed depth is `CallStack::size() + 1`.
339		/// Therefore a size of `0` means that a contract cannot use call or instantiate.
340		/// In other words only the origin called "root contract" is allowed to execute then.
341		///
342		/// This setting along with [`MaxCodeLen`](#associatedtype.MaxCodeLen) directly affects
343		/// memory usage of your runtime.
344		#[pallet::no_default]
345		type CallStack: Array<Item = Frame<Self>>;
346
347		/// The amount of balance a caller has to pay for each byte of storage.
348		///
349		/// # Note
350		///
351		/// Changing this value for an existing chain might need a storage migration.
352		#[pallet::constant]
353		#[pallet::no_default_bounds]
354		type DepositPerByte: Get<BalanceOf<Self>>;
355
356		/// Fallback value to limit the storage deposit if it's not being set by the caller.
357		#[pallet::constant]
358		#[pallet::no_default_bounds]
359		type DefaultDepositLimit: Get<BalanceOf<Self>>;
360
361		/// The amount of balance a caller has to pay for each storage item.
362		///
363		/// # Note
364		///
365		/// Changing this value for an existing chain might need a storage migration.
366		#[pallet::constant]
367		#[pallet::no_default_bounds]
368		type DepositPerItem: Get<BalanceOf<Self>>;
369
370		/// The percentage of the storage deposit that should be held for using a code hash.
371		/// Instantiating a contract, or calling [`chain_extension::Ext::lock_delegate_dependency`]
372		/// protects the code from being removed. In order to prevent abuse these actions are
373		/// protected with a percentage of the code deposit.
374		#[pallet::constant]
375		type CodeHashLockupDepositPercent: Get<Perbill>;
376
377		/// The address generator used to generate the addresses of contracts.
378		#[pallet::no_default_bounds]
379		type AddressGenerator: AddressGenerator<Self>;
380
381		/// The maximum length of a contract code in bytes.
382		///
383		/// The value should be chosen carefully taking into the account the overall memory limit
384		/// your runtime has, as well as the [maximum allowed callstack
385		/// depth](#associatedtype.CallStack). Look into the `integrity_test()` for some insights.
386		#[pallet::constant]
387		type MaxCodeLen: Get<u32>;
388
389		/// The maximum allowable length in bytes for storage keys.
390		#[pallet::constant]
391		type MaxStorageKeyLen: Get<u32>;
392
393		/// The maximum size of the transient storage in bytes.
394		/// This includes keys, values, and previous entries used for storage rollback.
395		#[pallet::constant]
396		type MaxTransientStorageSize: Get<u32>;
397
398		/// The maximum number of delegate_dependencies that a contract can lock with
399		/// [`chain_extension::Ext::lock_delegate_dependency`].
400		#[pallet::constant]
401		type MaxDelegateDependencies: Get<u32>;
402
403		/// Make contract callable functions marked as `#[unstable]` available.
404		///
405		/// Contracts that use `#[unstable]` functions won't be able to be uploaded unless
406		/// this is set to `true`. This is only meant for testnets and dev nodes in order to
407		/// experiment with new features.
408		///
409		/// # Warning
410		///
411		/// Do **not** set to `true` on productions chains.
412		#[pallet::constant]
413		type UnsafeUnstableInterface: Get<bool>;
414
415		/// The maximum length of the debug buffer in bytes.
416		#[pallet::constant]
417		type MaxDebugBufferLen: Get<u32>;
418
419		/// Origin allowed to upload code.
420		///
421		/// By default, it is safe to set this to `EnsureSigned`, allowing anyone to upload contract
422		/// code.
423		#[pallet::no_default_bounds]
424		type UploadOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = Self::AccountId>;
425
426		/// Origin allowed to instantiate code.
427		///
428		/// # Note
429		///
430		/// This is not enforced when a contract instantiates another contract. The
431		/// [`Self::UploadOrigin`] should make sure that no code is deployed that does unwanted
432		/// instantiations.
433		///
434		/// By default, it is safe to set this to `EnsureSigned`, allowing anyone to instantiate
435		/// contract code.
436		#[pallet::no_default_bounds]
437		type InstantiateOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = Self::AccountId>;
438
439		/// The sequence of migration steps that will be applied during a migration.
440		///
441		/// # Examples
442		/// ```
443		/// use pallet_contracts::migration::{v10, v11};
444		/// # struct Runtime {};
445		/// # struct Currency {};
446		/// type Migrations = (v10::Migration<Runtime, Currency>, v11::Migration<Runtime>);
447		/// ```
448		///
449		/// If you have a single migration step, you can use a tuple with a single element:
450		/// ```
451		/// use pallet_contracts::migration::v10;
452		/// # struct Runtime {};
453		/// # struct Currency {};
454		/// type Migrations = (v10::Migration<Runtime, Currency>,);
455		/// ```
456		type Migrations: MigrateSequence;
457
458		/// # Note
459		/// For most production chains, it's recommended to use the `()` implementation of this
460		/// trait. This implementation offers additional logging when the log target
461		/// "runtime::contracts" is set to trace.
462		#[pallet::no_default_bounds]
463		type Debug: Debugger<Self>;
464
465		/// Type that bundles together all the runtime configurable interface types.
466		///
467		/// This is not a real config. We just mention the type here as constant so that
468		/// its type appears in the metadata. Only valid value is `()`.
469		#[pallet::constant]
470		#[pallet::no_default_bounds]
471		type Environment: Get<Environment<Self>>;
472
473		/// The version of the HostFn APIs that are available in the runtime.
474		///
475		/// Only valid value is `()`.
476		#[pallet::constant]
477		#[pallet::no_default_bounds]
478		type ApiVersion: Get<ApiVersion>;
479
480		/// A type that exposes XCM APIs, allowing contracts to interact with other parachains, and
481		/// execute XCM programs.
482		#[pallet::no_default_bounds]
483		type Xcm: xcm_builder::Controller<
484			OriginFor<Self>,
485			<Self as frame_system::Config>::RuntimeCall,
486			BlockNumberFor<Self>,
487		>;
488	}
489
490	/// Container for different types that implement [`DefaultConfig`]` of this pallet.
491	pub mod config_preludes {
492		use super::*;
493		use frame_support::{
494			derive_impl,
495			traits::{ConstBool, ConstU32},
496		};
497		use frame_system::EnsureSigned;
498		use sp_core::parameter_types;
499
500		type AccountId = sp_runtime::AccountId32;
501		type Balance = u64;
502		const UNITS: Balance = 10_000_000_000;
503		const CENTS: Balance = UNITS / 100;
504
505		const fn deposit(items: u32, bytes: u32) -> Balance {
506			items as Balance * 1 * CENTS + (bytes as Balance) * 1 * CENTS
507		}
508
509		parameter_types! {
510			pub const DepositPerItem: Balance = deposit(1, 0);
511			pub const DepositPerByte: Balance = deposit(0, 1);
512			pub const DefaultDepositLimit: Balance = deposit(1024, 1024 * 1024);
513			pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0);
514			pub const MaxDelegateDependencies: u32 = 32;
515		}
516
517		/// A type providing default configurations for this pallet in testing environment.
518		pub struct TestDefaultConfig;
519
520		impl<Output, BlockNumber> Randomness<Output, BlockNumber> for TestDefaultConfig {
521			fn random(_subject: &[u8]) -> (Output, BlockNumber) {
522				unimplemented!("No default `random` implementation in `TestDefaultConfig`, provide a custom `T::Randomness` type.")
523			}
524		}
525
526		impl Time for TestDefaultConfig {
527			type Moment = u64;
528			fn now() -> Self::Moment {
529				unimplemented!("No default `now` implementation in `TestDefaultConfig` provide a custom `T::Time` type.")
530			}
531		}
532
533		impl<T: From<u64>> Convert<Weight, T> for TestDefaultConfig {
534			fn convert(w: Weight) -> T {
535				w.ref_time().into()
536			}
537		}
538
539		#[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
540		impl frame_system::DefaultConfig for TestDefaultConfig {}
541
542		#[frame_support::register_default_impl(TestDefaultConfig)]
543		impl DefaultConfig for TestDefaultConfig {
544			#[inject_runtime_type]
545			type RuntimeEvent = ();
546
547			#[inject_runtime_type]
548			type RuntimeHoldReason = ();
549
550			#[inject_runtime_type]
551			type RuntimeCall = ();
552
553			type AddressGenerator = DefaultAddressGenerator;
554			type CallFilter = ();
555			type ChainExtension = ();
556			type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
557			type DefaultDepositLimit = DefaultDepositLimit;
558			type DepositPerByte = DepositPerByte;
559			type DepositPerItem = DepositPerItem;
560			type MaxCodeLen = ConstU32<{ 123 * 1024 }>;
561			type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>;
562			type MaxDelegateDependencies = MaxDelegateDependencies;
563			type MaxStorageKeyLen = ConstU32<128>;
564			type MaxTransientStorageSize = ConstU32<{ 1 * 1024 * 1024 }>;
565			type Migrations = ();
566			type Time = Self;
567			type Randomness = Self;
568			type UnsafeUnstableInterface = ConstBool<true>;
569			type UploadOrigin = EnsureSigned<AccountId>;
570			type InstantiateOrigin = EnsureSigned<AccountId>;
571			type WeightInfo = ();
572			type WeightPrice = Self;
573			type Debug = ();
574			type Environment = ();
575			type ApiVersion = ();
576			type Xcm = ();
577		}
578	}
579
580	#[pallet::hooks]
581	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
582		fn on_idle(_block: BlockNumberFor<T>, limit: Weight) -> Weight {
583			use migration::MigrateResult::*;
584			let mut meter = WeightMeter::with_limit(limit);
585
586			loop {
587				match Migration::<T>::migrate(&mut meter) {
588					// There is not enough weight to perform a migration.
589					// We can't do anything more, so we return the used weight.
590					NoMigrationPerformed | InProgress { steps_done: 0 } => return meter.consumed(),
591					// Migration is still in progress, we can start the next step.
592					InProgress { .. } => continue,
593					// Either no migration is in progress, or we are done with all migrations, we
594					// can do some more other work with the remaining weight.
595					Completed | NoMigrationInProgress => break,
596				}
597			}
598
599			ContractInfo::<T>::process_deletion_queue_batch(&mut meter);
600			meter.consumed()
601		}
602
603		fn integrity_test() {
604			Migration::<T>::integrity_test();
605
606			// Total runtime memory limit
607			let max_runtime_mem: u32 = T::Schedule::get().limits.runtime_memory;
608			// Memory limits for a single contract:
609			// Value stack size: 1Mb per contract, default defined in wasmi
610			const MAX_STACK_SIZE: u32 = 1024 * 1024;
611			// Heap limit is normally 16 mempages of 64kb each = 1Mb per contract
612			let max_heap_size = T::Schedule::get().limits.max_memory_size();
613			// Max call depth is CallStack::size() + 1
614			let max_call_depth = u32::try_from(T::CallStack::size().saturating_add(1))
615				.expect("CallStack size is too big");
616			// Transient storage uses a BTreeMap, which has overhead compared to the raw size of
617			// key-value data. To ensure safety, a margin of 2x the raw key-value size is used.
618			let max_transient_storage_size = T::MaxTransientStorageSize::get()
619				.checked_mul(2)
620				.expect("MaxTransientStorageSize is too large");
621			// Check that given configured `MaxCodeLen`, runtime heap memory limit can't be broken.
622			//
623			// In worst case, the decoded Wasm contract code would be `x16` times larger than the
624			// encoded one. This is because even a single-byte wasm instruction has 16-byte size in
625			// wasmi. This gives us `MaxCodeLen*16` safety margin.
626			//
627			// Next, the pallet keeps the Wasm blob for each
628			// contract, hence we add up `MaxCodeLen` to the safety margin.
629			//
630			// The inefficiencies of the freeing-bump allocator
631			// being used in the client for the runtime memory allocations, could lead to possible
632			// memory allocations for contract code grow up to `x4` times in some extreme cases,
633			// which gives us total multiplier of `17*4` for `MaxCodeLen`.
634			//
635			// That being said, for every contract executed in runtime, at least `MaxCodeLen*17*4`
636			// memory should be available. Note that maximum allowed heap memory and stack size per
637			// each contract (stack frame) should also be counted.
638			//
639			// The pallet holds transient storage with a size up to `max_transient_storage_size`.
640			//
641			// Finally, we allow 50% of the runtime memory to be utilized by the contracts call
642			// stack, keeping the rest for other facilities, such as PoV, etc.
643			//
644			// This gives us the following formula:
645			//
646			// `(MaxCodeLen * 17 * 4 + MAX_STACK_SIZE + max_heap_size) * max_call_depth +
647			// max_transient_storage_size < max_runtime_mem/2`
648			//
649			// Hence the upper limit for the `MaxCodeLen` can be defined as follows:
650			let code_len_limit = max_runtime_mem
651				.saturating_div(2)
652				.saturating_sub(max_transient_storage_size)
653				.saturating_div(max_call_depth)
654				.saturating_sub(max_heap_size)
655				.saturating_sub(MAX_STACK_SIZE)
656				.saturating_div(17 * 4);
657
658			assert!(
659				T::MaxCodeLen::get() < code_len_limit,
660				"Given `CallStack` height {:?}, `MaxCodeLen` should be set less than {:?} \
661				 (current value is {:?}), to avoid possible runtime oom issues.",
662				max_call_depth,
663				code_len_limit,
664				T::MaxCodeLen::get(),
665			);
666
667			// Debug buffer should at least be large enough to accommodate a simple error message
668			const MIN_DEBUG_BUF_SIZE: u32 = 256;
669			assert!(
670				T::MaxDebugBufferLen::get() > MIN_DEBUG_BUF_SIZE,
671				"Debug buffer should have minimum size of {} (current setting is {})",
672				MIN_DEBUG_BUF_SIZE,
673				T::MaxDebugBufferLen::get(),
674			);
675
676			// Validators are configured to be able to use more memory than block builders. This is
677			// because in addition to `max_runtime_mem` they need to hold additional data in
678			// memory: PoV in multiple copies (1x encoded + 2x decoded) and all storage which
679			// includes emitted events. The assumption is that storage/events size
680			// can be a maximum of half of the validator runtime memory - max_runtime_mem.
681			let max_block_ref_time = T::BlockWeights::get()
682				.get(DispatchClass::Normal)
683				.max_total
684				.unwrap_or_else(|| T::BlockWeights::get().max_block)
685				.ref_time();
686			let max_payload_size = T::Schedule::get().limits.payload_len;
687			let max_key_size =
688				Key::<T>::try_from_var(alloc::vec![0u8; T::MaxStorageKeyLen::get() as usize])
689					.expect("Key of maximal size shall be created")
690					.hash()
691					.len() as u32;
692
693			// We can use storage to store items using the available block ref_time with the
694			// `set_storage` host function.
695			let max_storage_size: u32 = ((max_block_ref_time /
696				(<RuntimeCosts as gas::Token<T>>::weight(&RuntimeCosts::SetStorage {
697					new_bytes: max_payload_size,
698					old_bytes: 0,
699				})
700				.ref_time()))
701			.saturating_mul(max_payload_size.saturating_add(max_key_size) as u64))
702			.try_into()
703			.expect("Storage size too big");
704
705			let max_validator_runtime_mem: u32 = T::Schedule::get().limits.validator_runtime_memory;
706			let storage_size_limit = max_validator_runtime_mem.saturating_sub(max_runtime_mem) / 2;
707
708			assert!(
709				max_storage_size < storage_size_limit,
710				"Maximal storage size {} exceeds the storage limit {}",
711				max_storage_size,
712				storage_size_limit
713			);
714
715			// We can use storage to store events using the available block ref_time with the
716			// `deposit_event` host function. The overhead of stored events, which is around 100B,
717			// is not taken into account to simplify calculations, as it does not change much.
718			let max_events_size: u32 = ((max_block_ref_time /
719				(<RuntimeCosts as gas::Token<T>>::weight(&RuntimeCosts::DepositEvent {
720					num_topic: 0,
721					len: max_payload_size,
722				})
723				.ref_time()))
724			.saturating_mul(max_payload_size as u64))
725			.try_into()
726			.expect("Events size too big");
727
728			assert!(
729				max_events_size < storage_size_limit,
730				"Maximal events size {} exceeds the events limit {}",
731				max_events_size,
732				storage_size_limit
733			);
734		}
735	}
736
737	#[pallet::call]
738	impl<T: Config> Pallet<T>
739	where
740		<BalanceOf<T> as HasCompact>::Type: Clone + Eq + PartialEq + Debug + TypeInfo + Encode,
741	{
742		/// Deprecated version if [`Self::call`] for use in an in-storage `Call`.
743		#[pallet::call_index(0)]
744		#[pallet::weight(T::WeightInfo::call().saturating_add(<Pallet<T>>::compat_weight_limit(*gas_limit)))]
745		#[allow(deprecated)]
746		#[deprecated(note = "1D weight is used in this extrinsic, please migrate to `call`")]
747		pub fn call_old_weight(
748			origin: OriginFor<T>,
749			dest: AccountIdLookupOf<T>,
750			#[pallet::compact] value: BalanceOf<T>,
751			#[pallet::compact] gas_limit: OldWeight,
752			storage_deposit_limit: Option<<BalanceOf<T> as codec::HasCompact>::Type>,
753			data: Vec<u8>,
754		) -> DispatchResultWithPostInfo {
755			Self::call(
756				origin,
757				dest,
758				value,
759				<Pallet<T>>::compat_weight_limit(gas_limit),
760				storage_deposit_limit,
761				data,
762			)
763		}
764
765		/// Deprecated version if [`Self::instantiate_with_code`] for use in an in-storage `Call`.
766		#[pallet::call_index(1)]
767		#[pallet::weight(
768			T::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32)
769			.saturating_add(<Pallet<T>>::compat_weight_limit(*gas_limit))
770		)]
771		#[allow(deprecated)]
772		#[deprecated(
773			note = "1D weight is used in this extrinsic, please migrate to `instantiate_with_code`"
774		)]
775		pub fn instantiate_with_code_old_weight(
776			origin: OriginFor<T>,
777			#[pallet::compact] value: BalanceOf<T>,
778			#[pallet::compact] gas_limit: OldWeight,
779			storage_deposit_limit: Option<<BalanceOf<T> as codec::HasCompact>::Type>,
780			code: Vec<u8>,
781			data: Vec<u8>,
782			salt: Vec<u8>,
783		) -> DispatchResultWithPostInfo {
784			Self::instantiate_with_code(
785				origin,
786				value,
787				<Pallet<T>>::compat_weight_limit(gas_limit),
788				storage_deposit_limit,
789				code,
790				data,
791				salt,
792			)
793		}
794
795		/// Deprecated version if [`Self::instantiate`] for use in an in-storage `Call`.
796		#[pallet::call_index(2)]
797		#[pallet::weight(
798			T::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(<Pallet<T>>::compat_weight_limit(*gas_limit))
799		)]
800		#[allow(deprecated)]
801		#[deprecated(note = "1D weight is used in this extrinsic, please migrate to `instantiate`")]
802		pub fn instantiate_old_weight(
803			origin: OriginFor<T>,
804			#[pallet::compact] value: BalanceOf<T>,
805			#[pallet::compact] gas_limit: OldWeight,
806			storage_deposit_limit: Option<<BalanceOf<T> as codec::HasCompact>::Type>,
807			code_hash: CodeHash<T>,
808			data: Vec<u8>,
809			salt: Vec<u8>,
810		) -> DispatchResultWithPostInfo {
811			Self::instantiate(
812				origin,
813				value,
814				<Pallet<T>>::compat_weight_limit(gas_limit),
815				storage_deposit_limit,
816				code_hash,
817				data,
818				salt,
819			)
820		}
821
822		/// Upload new `code` without instantiating a contract from it.
823		///
824		/// If the code does not already exist a deposit is reserved from the caller
825		/// and unreserved only when [`Self::remove_code`] is called. The size of the reserve
826		/// depends on the size of the supplied `code`.
827		///
828		/// If the code already exists in storage it will still return `Ok` and upgrades
829		/// the in storage version to the current
830		/// [`InstructionWeights::version`](InstructionWeights).
831		///
832		/// - `determinism`: If this is set to any other value but [`Determinism::Enforced`] then
833		///   the only way to use this code is to delegate call into it from an offchain execution.
834		///   Set to [`Determinism::Enforced`] if in doubt.
835		///
836		/// # Note
837		///
838		/// Anyone can instantiate a contract from any uploaded code and thus prevent its removal.
839		/// To avoid this situation a constructor could employ access control so that it can
840		/// only be instantiated by permissioned entities. The same is true when uploading
841		/// through [`Self::instantiate_with_code`].
842		///
843		/// Use [`Determinism::Relaxed`] exclusively for non-deterministic code. If the uploaded
844		/// code is deterministic, specifying [`Determinism::Relaxed`] will be disregarded and
845		/// result in higher gas costs.
846		#[pallet::call_index(3)]
847		#[pallet::weight(
848			match determinism {
849				Determinism::Enforced => T::WeightInfo::upload_code_determinism_enforced(code.len() as u32),
850				Determinism::Relaxed => T::WeightInfo::upload_code_determinism_relaxed(code.len() as u32),
851			}
852		)]
853		pub fn upload_code(
854			origin: OriginFor<T>,
855			code: Vec<u8>,
856			storage_deposit_limit: Option<<BalanceOf<T> as codec::HasCompact>::Type>,
857			determinism: Determinism,
858		) -> DispatchResult {
859			Migration::<T>::ensure_migrated()?;
860			let origin = T::UploadOrigin::ensure_origin(origin)?;
861			Self::bare_upload_code(origin, code, storage_deposit_limit.map(Into::into), determinism)
862				.map(|_| ())
863		}
864
865		/// Remove the code stored under `code_hash` and refund the deposit to its owner.
866		///
867		/// A code can only be removed by its original uploader (its owner) and only if it is
868		/// not used by any contract.
869		#[pallet::call_index(4)]
870		#[pallet::weight(T::WeightInfo::remove_code())]
871		pub fn remove_code(
872			origin: OriginFor<T>,
873			code_hash: CodeHash<T>,
874		) -> DispatchResultWithPostInfo {
875			Migration::<T>::ensure_migrated()?;
876			let origin = ensure_signed(origin)?;
877			<WasmBlob<T>>::remove(&origin, code_hash)?;
878			// we waive the fee because removing unused code is beneficial
879			Ok(Pays::No.into())
880		}
881
882		/// Privileged function that changes the code of an existing contract.
883		///
884		/// This takes care of updating refcounts and all other necessary operations. Returns
885		/// an error if either the `code_hash` or `dest` do not exist.
886		///
887		/// # Note
888		///
889		/// This does **not** change the address of the contract in question. This means
890		/// that the contract address is no longer derived from its code hash after calling
891		/// this dispatchable.
892		#[pallet::call_index(5)]
893		#[pallet::weight(T::WeightInfo::set_code())]
894		pub fn set_code(
895			origin: OriginFor<T>,
896			dest: AccountIdLookupOf<T>,
897			code_hash: CodeHash<T>,
898		) -> DispatchResult {
899			Migration::<T>::ensure_migrated()?;
900			ensure_root(origin)?;
901			let dest = T::Lookup::lookup(dest)?;
902			<ContractInfoOf<T>>::try_mutate(&dest, |contract| {
903				let contract = if let Some(contract) = contract {
904					contract
905				} else {
906					return Err(<Error<T>>::ContractNotFound.into())
907				};
908				<ExecStack<T, WasmBlob<T>>>::increment_refcount(code_hash)?;
909				<ExecStack<T, WasmBlob<T>>>::decrement_refcount(contract.code_hash);
910				Self::deposit_event(Event::ContractCodeUpdated {
911					contract: dest.clone(),
912					new_code_hash: code_hash,
913					old_code_hash: contract.code_hash,
914				});
915				contract.code_hash = code_hash;
916				Ok(())
917			})
918		}
919
920		/// Makes a call to an account, optionally transferring some balance.
921		///
922		/// # Parameters
923		///
924		/// * `dest`: Address of the contract to call.
925		/// * `value`: The balance to transfer from the `origin` to `dest`.
926		/// * `gas_limit`: The gas limit enforced when executing the constructor.
927		/// * `storage_deposit_limit`: The maximum amount of balance that can be charged from the
928		///   caller to pay for the storage consumed.
929		/// * `data`: The input data to pass to the contract.
930		///
931		/// * If the account is a smart-contract account, the associated code will be
932		/// executed and any value will be transferred.
933		/// * If the account is a regular account, any value will be transferred.
934		/// * If no account exists and the call value is not less than `existential_deposit`,
935		/// a regular account will be created and any value will be transferred.
936		#[pallet::call_index(6)]
937		#[pallet::weight(T::WeightInfo::call().saturating_add(*gas_limit))]
938		pub fn call(
939			origin: OriginFor<T>,
940			dest: AccountIdLookupOf<T>,
941			#[pallet::compact] value: BalanceOf<T>,
942			gas_limit: Weight,
943			storage_deposit_limit: Option<<BalanceOf<T> as codec::HasCompact>::Type>,
944			data: Vec<u8>,
945		) -> DispatchResultWithPostInfo {
946			Migration::<T>::ensure_migrated()?;
947			let common = CommonInput {
948				origin: Origin::from_runtime_origin(origin)?,
949				value,
950				data,
951				gas_limit: gas_limit.into(),
952				storage_deposit_limit: storage_deposit_limit.map(Into::into),
953				debug_message: None,
954			};
955			let dest = T::Lookup::lookup(dest)?;
956			let mut output =
957				CallInput::<T> { dest, determinism: Determinism::Enforced }.run_guarded(common);
958			if let Ok(retval) = &output.result {
959				if retval.did_revert() {
960					output.result = Err(<Error<T>>::ContractReverted.into());
961				}
962			}
963			output.gas_meter.into_dispatch_result(output.result, T::WeightInfo::call())
964		}
965
966		/// Instantiates a new contract from the supplied `code` optionally transferring
967		/// some balance.
968		///
969		/// This dispatchable has the same effect as calling [`Self::upload_code`] +
970		/// [`Self::instantiate`]. Bundling them together provides efficiency gains. Please
971		/// also check the documentation of [`Self::upload_code`].
972		///
973		/// # Parameters
974		///
975		/// * `value`: The balance to transfer from the `origin` to the newly created contract.
976		/// * `gas_limit`: The gas limit enforced when executing the constructor.
977		/// * `storage_deposit_limit`: The maximum amount of balance that can be charged/reserved
978		///   from the caller to pay for the storage consumed.
979		/// * `code`: The contract code to deploy in raw bytes.
980		/// * `data`: The input data to pass to the contract constructor.
981		/// * `salt`: Used for the address derivation. See [`Pallet::contract_address`].
982		///
983		/// Instantiation is executed as follows:
984		///
985		/// - The supplied `code` is deployed, and a `code_hash` is created for that code.
986		/// - If the `code_hash` already exists on the chain the underlying `code` will be shared.
987		/// - The destination address is computed based on the sender, code_hash and the salt.
988		/// - The smart-contract account is created at the computed address.
989		/// - The `value` is transferred to the new account.
990		/// - The `deploy` function is executed in the context of the newly-created account.
991		#[pallet::call_index(7)]
992		#[pallet::weight(
993			T::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32, salt.len() as u32)
994			.saturating_add(*gas_limit)
995		)]
996		pub fn instantiate_with_code(
997			origin: OriginFor<T>,
998			#[pallet::compact] value: BalanceOf<T>,
999			gas_limit: Weight,
1000			storage_deposit_limit: Option<<BalanceOf<T> as codec::HasCompact>::Type>,
1001			code: Vec<u8>,
1002			data: Vec<u8>,
1003			salt: Vec<u8>,
1004		) -> DispatchResultWithPostInfo {
1005			Migration::<T>::ensure_migrated()?;
1006
1007			// These two origins will usually be the same; however, we treat them as separate since
1008			// it is possible for the `Success` value of `UploadOrigin` and `InstantiateOrigin` to
1009			// differ.
1010			let upload_origin = T::UploadOrigin::ensure_origin(origin.clone())?;
1011			let instantiate_origin = T::InstantiateOrigin::ensure_origin(origin)?;
1012
1013			let code_len = code.len() as u32;
1014
1015			let (module, upload_deposit) = Self::try_upload_code(
1016				upload_origin,
1017				code,
1018				storage_deposit_limit.clone().map(Into::into),
1019				Determinism::Enforced,
1020				None,
1021			)?;
1022
1023			// Reduces the storage deposit limit by the amount that was reserved for the upload.
1024			let storage_deposit_limit =
1025				storage_deposit_limit.map(|limit| limit.into().saturating_sub(upload_deposit));
1026
1027			let data_len = data.len() as u32;
1028			let salt_len = salt.len() as u32;
1029			let common = CommonInput {
1030				origin: Origin::from_account_id(instantiate_origin),
1031				value,
1032				data,
1033				gas_limit,
1034				storage_deposit_limit,
1035				debug_message: None,
1036			};
1037
1038			let mut output =
1039				InstantiateInput::<T> { code: WasmCode::Wasm(module), salt }.run_guarded(common);
1040			if let Ok(retval) = &output.result {
1041				if retval.1.did_revert() {
1042					output.result = Err(<Error<T>>::ContractReverted.into());
1043				}
1044			}
1045
1046			output.gas_meter.into_dispatch_result(
1047				output.result.map(|(_address, output)| output),
1048				T::WeightInfo::instantiate_with_code(code_len, data_len, salt_len),
1049			)
1050		}
1051
1052		/// Instantiates a contract from a previously deployed wasm binary.
1053		///
1054		/// This function is identical to [`Self::instantiate_with_code`] but without the
1055		/// code deployment step. Instead, the `code_hash` of an on-chain deployed wasm binary
1056		/// must be supplied.
1057		#[pallet::call_index(8)]
1058		#[pallet::weight(
1059			T::WeightInfo::instantiate(data.len() as u32, salt.len() as u32).saturating_add(*gas_limit)
1060		)]
1061		pub fn instantiate(
1062			origin: OriginFor<T>,
1063			#[pallet::compact] value: BalanceOf<T>,
1064			gas_limit: Weight,
1065			storage_deposit_limit: Option<<BalanceOf<T> as codec::HasCompact>::Type>,
1066			code_hash: CodeHash<T>,
1067			data: Vec<u8>,
1068			salt: Vec<u8>,
1069		) -> DispatchResultWithPostInfo {
1070			Migration::<T>::ensure_migrated()?;
1071			let origin = T::InstantiateOrigin::ensure_origin(origin)?;
1072			let data_len = data.len() as u32;
1073			let salt_len = salt.len() as u32;
1074			let common = CommonInput {
1075				origin: Origin::from_account_id(origin),
1076				value,
1077				data,
1078				gas_limit,
1079				storage_deposit_limit: storage_deposit_limit.map(Into::into),
1080				debug_message: None,
1081			};
1082			let mut output = InstantiateInput::<T> { code: WasmCode::CodeHash(code_hash), salt }
1083				.run_guarded(common);
1084			if let Ok(retval) = &output.result {
1085				if retval.1.did_revert() {
1086					output.result = Err(<Error<T>>::ContractReverted.into());
1087				}
1088			}
1089			output.gas_meter.into_dispatch_result(
1090				output.result.map(|(_address, output)| output),
1091				T::WeightInfo::instantiate(data_len, salt_len),
1092			)
1093		}
1094
1095		/// When a migration is in progress, this dispatchable can be used to run migration steps.
1096		/// Calls that contribute to advancing the migration have their fees waived, as it's helpful
1097		/// for the chain. Note that while the migration is in progress, the pallet will also
1098		/// leverage the `on_idle` hooks to run migration steps.
1099		#[pallet::call_index(9)]
1100		#[pallet::weight(T::WeightInfo::migrate().saturating_add(*weight_limit))]
1101		pub fn migrate(origin: OriginFor<T>, weight_limit: Weight) -> DispatchResultWithPostInfo {
1102			use migration::MigrateResult::*;
1103			ensure_signed(origin)?;
1104
1105			let weight_limit = weight_limit.saturating_add(T::WeightInfo::migrate());
1106			let mut meter = WeightMeter::with_limit(weight_limit);
1107			let result = Migration::<T>::migrate(&mut meter);
1108
1109			match result {
1110				Completed => Ok(PostDispatchInfo {
1111					actual_weight: Some(meter.consumed()),
1112					pays_fee: Pays::No,
1113				}),
1114				InProgress { steps_done, .. } if steps_done > 0 => Ok(PostDispatchInfo {
1115					actual_weight: Some(meter.consumed()),
1116					pays_fee: Pays::No,
1117				}),
1118				InProgress { .. } => Ok(PostDispatchInfo {
1119					actual_weight: Some(meter.consumed()),
1120					pays_fee: Pays::Yes,
1121				}),
1122				NoMigrationInProgress | NoMigrationPerformed => {
1123					let err: DispatchError = <Error<T>>::NoMigrationPerformed.into();
1124					Err(err.with_weight(meter.consumed()))
1125				},
1126			}
1127		}
1128	}
1129
1130	#[pallet::event]
1131	pub enum Event<T: Config> {
1132		/// Contract deployed by address at the specified address.
1133		Instantiated { deployer: T::AccountId, contract: T::AccountId },
1134
1135		/// Contract has been removed.
1136		///
1137		/// # Note
1138		///
1139		/// The only way for a contract to be removed and emitting this event is by calling
1140		/// `seal_terminate`.
1141		Terminated {
1142			/// The contract that was terminated.
1143			contract: T::AccountId,
1144			/// The account that received the contracts remaining balance
1145			beneficiary: T::AccountId,
1146		},
1147
1148		/// Code with the specified hash has been stored.
1149		CodeStored { code_hash: T::Hash, deposit_held: BalanceOf<T>, uploader: T::AccountId },
1150
1151		/// A custom event emitted by the contract.
1152		ContractEmitted {
1153			/// The contract that emitted the event.
1154			contract: T::AccountId,
1155			/// Data supplied by the contract. Metadata generated during contract compilation
1156			/// is needed to decode it.
1157			data: Vec<u8>,
1158		},
1159
1160		/// A code with the specified hash was removed.
1161		CodeRemoved { code_hash: T::Hash, deposit_released: BalanceOf<T>, remover: T::AccountId },
1162
1163		/// A contract's code was updated.
1164		ContractCodeUpdated {
1165			/// The contract that has been updated.
1166			contract: T::AccountId,
1167			/// New code hash that was set for the contract.
1168			new_code_hash: T::Hash,
1169			/// Previous code hash of the contract.
1170			old_code_hash: T::Hash,
1171		},
1172
1173		/// A contract was called either by a plain account or another contract.
1174		///
1175		/// # Note
1176		///
1177		/// Please keep in mind that like all events this is only emitted for successful
1178		/// calls. This is because on failure all storage changes including events are
1179		/// rolled back.
1180		Called {
1181			/// The caller of the `contract`.
1182			caller: Origin<T>,
1183			/// The contract that was called.
1184			contract: T::AccountId,
1185		},
1186
1187		/// A contract delegate called a code hash.
1188		///
1189		/// # Note
1190		///
1191		/// Please keep in mind that like all events this is only emitted for successful
1192		/// calls. This is because on failure all storage changes including events are
1193		/// rolled back.
1194		DelegateCalled {
1195			/// The contract that performed the delegate call and hence in whose context
1196			/// the `code_hash` is executed.
1197			contract: T::AccountId,
1198			/// The code hash that was delegate called.
1199			code_hash: CodeHash<T>,
1200		},
1201
1202		/// Some funds have been transferred and held as storage deposit.
1203		StorageDepositTransferredAndHeld {
1204			from: T::AccountId,
1205			to: T::AccountId,
1206			amount: BalanceOf<T>,
1207		},
1208
1209		/// Some storage deposit funds have been transferred and released.
1210		StorageDepositTransferredAndReleased {
1211			from: T::AccountId,
1212			to: T::AccountId,
1213			amount: BalanceOf<T>,
1214		},
1215	}
1216
1217	#[pallet::error]
1218	pub enum Error<T> {
1219		/// Invalid schedule supplied, e.g. with zero weight of a basic operation.
1220		InvalidSchedule,
1221		/// Invalid combination of flags supplied to `seal_call` or `seal_delegate_call`.
1222		InvalidCallFlags,
1223		/// The executed contract exhausted its gas limit.
1224		OutOfGas,
1225		/// The output buffer supplied to a contract API call was too small.
1226		OutputBufferTooSmall,
1227		/// Performing the requested transfer failed. Probably because there isn't enough
1228		/// free balance in the sender's account.
1229		TransferFailed,
1230		/// Performing a call was denied because the calling depth reached the limit
1231		/// of what is specified in the schedule.
1232		MaxCallDepthReached,
1233		/// No contract was found at the specified address.
1234		ContractNotFound,
1235		/// The code supplied to `instantiate_with_code` exceeds the limit specified in the
1236		/// current schedule.
1237		CodeTooLarge,
1238		/// No code could be found at the supplied code hash.
1239		CodeNotFound,
1240		/// No code info could be found at the supplied code hash.
1241		CodeInfoNotFound,
1242		/// A buffer outside of sandbox memory was passed to a contract API function.
1243		OutOfBounds,
1244		/// Input passed to a contract API function failed to decode as expected type.
1245		DecodingFailed,
1246		/// Contract trapped during execution.
1247		ContractTrapped,
1248		/// The size defined in `T::MaxValueSize` was exceeded.
1249		ValueTooLarge,
1250		/// Termination of a contract is not allowed while the contract is already
1251		/// on the call stack. Can be triggered by `seal_terminate`.
1252		TerminatedWhileReentrant,
1253		/// `seal_call` forwarded this contracts input. It therefore is no longer available.
1254		InputForwarded,
1255		/// The subject passed to `seal_random` exceeds the limit.
1256		RandomSubjectTooLong,
1257		/// The amount of topics passed to `seal_deposit_events` exceeds the limit.
1258		TooManyTopics,
1259		/// The chain does not provide a chain extension. Calling the chain extension results
1260		/// in this error. Note that this usually  shouldn't happen as deploying such contracts
1261		/// is rejected.
1262		NoChainExtension,
1263		/// Failed to decode the XCM program.
1264		XCMDecodeFailed,
1265		/// A contract with the same AccountId already exists.
1266		DuplicateContract,
1267		/// A contract self destructed in its constructor.
1268		///
1269		/// This can be triggered by a call to `seal_terminate`.
1270		TerminatedInConstructor,
1271		/// A call tried to invoke a contract that is flagged as non-reentrant.
1272		/// The only other cause is that a call from a contract into the runtime tried to call back
1273		/// into `pallet-contracts`. This would make the whole pallet reentrant with regard to
1274		/// contract code execution which is not supported.
1275		ReentranceDenied,
1276		/// A contract attempted to invoke a state modifying API while being in read-only mode.
1277		StateChangeDenied,
1278		/// Origin doesn't have enough balance to pay the required storage deposits.
1279		StorageDepositNotEnoughFunds,
1280		/// More storage was created than allowed by the storage deposit limit.
1281		StorageDepositLimitExhausted,
1282		/// Code removal was denied because the code is still in use by at least one contract.
1283		CodeInUse,
1284		/// The contract ran to completion but decided to revert its storage changes.
1285		/// Please note that this error is only returned from extrinsics. When called directly
1286		/// or via RPC an `Ok` will be returned. In this case the caller needs to inspect the flags
1287		/// to determine whether a reversion has taken place.
1288		ContractReverted,
1289		/// The contract's code was found to be invalid during validation.
1290		///
1291		/// The most likely cause of this is that an API was used which is not supported by the
1292		/// node. This happens if an older node is used with a new version of ink!. Try updating
1293		/// your node to the newest available version.
1294		///
1295		/// A more detailed error can be found on the node console if debug messages are enabled
1296		/// by supplying `-lruntime::contracts=debug`.
1297		CodeRejected,
1298		/// An indeterministic code was used in a context where this is not permitted.
1299		Indeterministic,
1300		/// A pending migration needs to complete before the extrinsic can be called.
1301		MigrationInProgress,
1302		/// Migrate dispatch call was attempted but no migration was performed.
1303		NoMigrationPerformed,
1304		/// The contract has reached its maximum number of delegate dependencies.
1305		MaxDelegateDependenciesReached,
1306		/// The dependency was not found in the contract's delegate dependencies.
1307		DelegateDependencyNotFound,
1308		/// The contract already depends on the given delegate dependency.
1309		DelegateDependencyAlreadyExists,
1310		/// Can not add a delegate dependency to the code hash of the contract itself.
1311		CannotAddSelfAsDelegateDependency,
1312		/// Can not add more data to transient storage.
1313		OutOfTransientStorage,
1314	}
1315
1316	/// A reason for the pallet contracts placing a hold on funds.
1317	#[pallet::composite_enum]
1318	pub enum HoldReason {
1319		/// The Pallet has reserved it for storing code on-chain.
1320		CodeUploadDepositReserve,
1321		/// The Pallet has reserved it for storage deposit.
1322		StorageDepositReserve,
1323	}
1324
1325	/// A mapping from a contract's code hash to its code.
1326	#[pallet::storage]
1327	pub(crate) type PristineCode<T: Config> = StorageMap<_, Identity, CodeHash<T>, CodeVec<T>>;
1328
1329	/// A mapping from a contract's code hash to its code info.
1330	#[pallet::storage]
1331	pub(crate) type CodeInfoOf<T: Config> = StorageMap<_, Identity, CodeHash<T>, CodeInfo<T>>;
1332
1333	/// This is a **monotonic** counter incremented on contract instantiation.
1334	///
1335	/// This is used in order to generate unique trie ids for contracts.
1336	/// The trie id of a new contract is calculated from hash(account_id, nonce).
1337	/// The nonce is required because otherwise the following sequence would lead to
1338	/// a possible collision of storage:
1339	///
1340	/// 1. Create a new contract.
1341	/// 2. Terminate the contract.
1342	/// 3. Immediately recreate the contract with the same account_id.
1343	///
1344	/// This is bad because the contents of a trie are deleted lazily and there might be
1345	/// storage of the old instantiation still in it when the new contract is created. Please
1346	/// note that we can't replace the counter by the block number because the sequence above
1347	/// can happen in the same block. We also can't keep the account counter in memory only
1348	/// because storage is the only way to communicate across different extrinsics in the
1349	/// same block.
1350	///
1351	/// # Note
1352	///
1353	/// Do not use it to determine the number of contracts. It won't be decremented if
1354	/// a contract is destroyed.
1355	#[pallet::storage]
1356	pub(crate) type Nonce<T: Config> = StorageValue<_, u64, ValueQuery>;
1357
1358	/// The code associated with a given account.
1359	///
1360	/// TWOX-NOTE: SAFE since `AccountId` is a secure hash.
1361	#[pallet::storage]
1362	pub(crate) type ContractInfoOf<T: Config> =
1363		StorageMap<_, Twox64Concat, T::AccountId, ContractInfo<T>>;
1364
1365	/// Evicted contracts that await child trie deletion.
1366	///
1367	/// Child trie deletion is a heavy operation depending on the amount of storage items
1368	/// stored in said trie. Therefore this operation is performed lazily in `on_idle`.
1369	#[pallet::storage]
1370	pub(crate) type DeletionQueue<T: Config> = StorageMap<_, Twox64Concat, u32, TrieId>;
1371
1372	/// A pair of monotonic counters used to track the latest contract marked for deletion
1373	/// and the latest deleted contract in queue.
1374	#[pallet::storage]
1375	pub(crate) type DeletionQueueCounter<T: Config> =
1376		StorageValue<_, DeletionQueueManager<T>, ValueQuery>;
1377
1378	/// A migration can span across multiple blocks. This storage defines a cursor to track the
1379	/// progress of the migration, enabling us to resume from the last completed position.
1380	#[pallet::storage]
1381	pub(crate) type MigrationInProgress<T: Config> =
1382		StorageValue<_, migration::Cursor, OptionQuery>;
1383}
1384
1385/// The type of origins supported by the contracts pallet.
1386#[derive(
1387	Clone, Encode, Decode, DecodeWithMemTracking, PartialEq, TypeInfo, RuntimeDebugNoBound,
1388)]
1389pub enum Origin<T: Config> {
1390	Root,
1391	Signed(T::AccountId),
1392}
1393
1394impl<T: Config> Origin<T> {
1395	/// Creates a new Signed Caller from an AccountId.
1396	pub fn from_account_id(account_id: T::AccountId) -> Self {
1397		Origin::Signed(account_id)
1398	}
1399	/// Creates a new Origin from a `RuntimeOrigin`.
1400	pub fn from_runtime_origin(o: OriginFor<T>) -> Result<Self, DispatchError> {
1401		match o.into() {
1402			Ok(RawOrigin::Root) => Ok(Self::Root),
1403			Ok(RawOrigin::Signed(t)) => Ok(Self::Signed(t)),
1404			_ => Err(BadOrigin.into()),
1405		}
1406	}
1407	/// Returns the AccountId of a Signed Origin or an error if the origin is Root.
1408	pub fn account_id(&self) -> Result<&T::AccountId, DispatchError> {
1409		match self {
1410			Origin::Signed(id) => Ok(id),
1411			Origin::Root => Err(DispatchError::RootNotAllowed),
1412		}
1413	}
1414}
1415
1416/// Context of a contract invocation.
1417struct CommonInput<'a, T: Config> {
1418	origin: Origin<T>,
1419	value: BalanceOf<T>,
1420	data: Vec<u8>,
1421	gas_limit: Weight,
1422	storage_deposit_limit: Option<BalanceOf<T>>,
1423	debug_message: Option<&'a mut DebugBufferVec<T>>,
1424}
1425
1426/// Input specific to a call into contract.
1427struct CallInput<T: Config> {
1428	dest: T::AccountId,
1429	determinism: Determinism,
1430}
1431
1432/// Reference to an existing code hash or a new wasm module.
1433enum WasmCode<T: Config> {
1434	Wasm(WasmBlob<T>),
1435	CodeHash(CodeHash<T>),
1436}
1437
1438/// Input specific to a contract instantiation invocation.
1439struct InstantiateInput<T: Config> {
1440	code: WasmCode<T>,
1441	salt: Vec<u8>,
1442}
1443
1444/// Determines whether events should be collected during execution.
1445#[derive(
1446	Copy, Clone, PartialEq, Eq, RuntimeDebug, Decode, Encode, MaxEncodedLen, scale_info::TypeInfo,
1447)]
1448pub enum CollectEvents {
1449	/// Collect events.
1450	///
1451	/// # Note
1452	///
1453	/// Events should only be collected when called off-chain, as this would otherwise
1454	/// collect all the Events emitted in the block so far and put them into the PoV.
1455	///
1456	/// **Never** use this mode for on-chain execution.
1457	UnsafeCollect,
1458	/// Skip event collection.
1459	Skip,
1460}
1461
1462/// Determines whether debug messages will be collected.
1463#[derive(
1464	Copy, Clone, PartialEq, Eq, RuntimeDebug, Decode, Encode, MaxEncodedLen, scale_info::TypeInfo,
1465)]
1466pub enum DebugInfo {
1467	/// Collect debug messages.
1468	/// # Note
1469	///
1470	/// This should only ever be set to `UnsafeDebug` when executing as an RPC because
1471	/// it adds allocations and could be abused to drive the runtime into an OOM panic.
1472	UnsafeDebug,
1473	/// Skip collection of debug messages.
1474	Skip,
1475}
1476
1477/// Return type of private helper functions.
1478struct InternalOutput<T: Config, O> {
1479	/// The gas meter that was used to execute the call.
1480	gas_meter: GasMeter<T>,
1481	/// The storage deposit used by the call.
1482	storage_deposit: StorageDeposit<BalanceOf<T>>,
1483	/// The result of the call.
1484	result: Result<O, ExecError>,
1485}
1486
1487// Set up a global reference to the boolean flag used for the re-entrancy guard.
1488environmental!(executing_contract: bool);
1489
1490/// Helper trait to wrap contract execution entry points into a single function
1491/// [`Invokable::run_guarded`].
1492trait Invokable<T: Config>: Sized {
1493	/// What is returned as a result of a successful invocation.
1494	type Output;
1495
1496	/// Single entry point to contract execution.
1497	/// Downstream execution flow is branched by implementations of [`Invokable`] trait:
1498	///
1499	/// - [`InstantiateInput::run`] runs contract instantiation,
1500	/// - [`CallInput::run`] runs contract call.
1501	///
1502	/// We enforce a re-entrancy guard here by initializing and checking a boolean flag through a
1503	/// global reference.
1504	fn run_guarded(self, common: CommonInput<T>) -> InternalOutput<T, Self::Output> {
1505		let gas_limit = common.gas_limit;
1506
1507		// Check whether the origin is allowed here. The logic of the access rules
1508		// is in the `ensure_origin`, this could vary for different implementations of this
1509		// trait. For example, some actions might not allow Root origin as they could require an
1510		// AccountId associated with the origin.
1511		if let Err(e) = self.ensure_origin(common.origin.clone()) {
1512			return InternalOutput {
1513				gas_meter: GasMeter::new(gas_limit),
1514				storage_deposit: Default::default(),
1515				result: Err(ExecError { error: e.into(), origin: ErrorOrigin::Caller }),
1516			}
1517		}
1518
1519		executing_contract::using_once(&mut false, || {
1520			executing_contract::with(|f| {
1521				// Fail if already entered contract execution
1522				if *f {
1523					return Err(())
1524				}
1525				// We are entering contract execution
1526				*f = true;
1527				Ok(())
1528			})
1529			.expect("Returns `Ok` if called within `using_once`. It is syntactically obvious that this is the case; qed")
1530			.map_or_else(
1531				|_| InternalOutput {
1532					gas_meter: GasMeter::new(gas_limit),
1533					storage_deposit: Default::default(),
1534					result: Err(ExecError {
1535						error: <Error<T>>::ReentranceDenied.into(),
1536						origin: ErrorOrigin::Caller,
1537					}),
1538				},
1539				// Enter contract call.
1540				|_| self.run(common, GasMeter::new(gas_limit)),
1541			)
1542		})
1543	}
1544
1545	/// Method that does the actual call to a contract. It can be either a call to a deployed
1546	/// contract or a instantiation of a new one.
1547	///
1548	/// Called by dispatchables and public functions through the [`Invokable::run_guarded`].
1549	fn run(self, common: CommonInput<T>, gas_meter: GasMeter<T>)
1550		-> InternalOutput<T, Self::Output>;
1551
1552	/// This method ensures that the given `origin` is allowed to invoke the current `Invokable`.
1553	///
1554	/// Called by dispatchables and public functions through the [`Invokable::run_guarded`].
1555	fn ensure_origin(&self, origin: Origin<T>) -> Result<(), DispatchError>;
1556}
1557
1558impl<T: Config> Invokable<T> for CallInput<T> {
1559	type Output = ExecReturnValue;
1560
1561	fn run(
1562		self,
1563		common: CommonInput<T>,
1564		mut gas_meter: GasMeter<T>,
1565	) -> InternalOutput<T, Self::Output> {
1566		let CallInput { dest, determinism } = self;
1567		let CommonInput { origin, value, data, debug_message, .. } = common;
1568		let mut storage_meter =
1569			match StorageMeter::new(&origin, common.storage_deposit_limit, common.value) {
1570				Ok(meter) => meter,
1571				Err(err) =>
1572					return InternalOutput {
1573						result: Err(err.into()),
1574						gas_meter,
1575						storage_deposit: Default::default(),
1576					},
1577			};
1578		let schedule = T::Schedule::get();
1579		let result = ExecStack::<T, WasmBlob<T>>::run_call(
1580			origin.clone(),
1581			dest.clone(),
1582			&mut gas_meter,
1583			&mut storage_meter,
1584			&schedule,
1585			value,
1586			data.clone(),
1587			debug_message,
1588			determinism,
1589		);
1590
1591		match storage_meter.try_into_deposit(&origin) {
1592			Ok(storage_deposit) => InternalOutput { gas_meter, storage_deposit, result },
1593			Err(err) => InternalOutput {
1594				gas_meter,
1595				storage_deposit: Default::default(),
1596				result: Err(err.into()),
1597			},
1598		}
1599	}
1600
1601	fn ensure_origin(&self, _origin: Origin<T>) -> Result<(), DispatchError> {
1602		Ok(())
1603	}
1604}
1605
1606impl<T: Config> Invokable<T> for InstantiateInput<T> {
1607	type Output = (AccountIdOf<T>, ExecReturnValue);
1608
1609	fn run(
1610		self,
1611		common: CommonInput<T>,
1612		mut gas_meter: GasMeter<T>,
1613	) -> InternalOutput<T, Self::Output> {
1614		let mut storage_deposit = Default::default();
1615		let try_exec = || {
1616			let schedule = T::Schedule::get();
1617			let InstantiateInput { salt, .. } = self;
1618			let CommonInput { origin: contract_origin, .. } = common;
1619			let origin = contract_origin.account_id()?;
1620
1621			let executable = match self.code {
1622				WasmCode::Wasm(module) => module,
1623				WasmCode::CodeHash(code_hash) => WasmBlob::from_storage(code_hash, &mut gas_meter)?,
1624			};
1625
1626			let contract_origin = Origin::from_account_id(origin.clone());
1627			let mut storage_meter =
1628				StorageMeter::new(&contract_origin, common.storage_deposit_limit, common.value)?;
1629			let CommonInput { value, data, debug_message, .. } = common;
1630			let result = ExecStack::<T, WasmBlob<T>>::run_instantiate(
1631				origin.clone(),
1632				executable,
1633				&mut gas_meter,
1634				&mut storage_meter,
1635				&schedule,
1636				value,
1637				data.clone(),
1638				&salt,
1639				debug_message,
1640			);
1641
1642			storage_deposit = storage_meter.try_into_deposit(&contract_origin)?;
1643			result
1644		};
1645		InternalOutput { result: try_exec(), gas_meter, storage_deposit }
1646	}
1647
1648	fn ensure_origin(&self, origin: Origin<T>) -> Result<(), DispatchError> {
1649		match origin {
1650			Origin::Signed(_) => Ok(()),
1651			Origin::Root => Err(DispatchError::RootNotAllowed),
1652		}
1653	}
1654}
1655
1656macro_rules! ensure_no_migration_in_progress {
1657	() => {
1658		if Migration::<T>::in_progress() {
1659			return ContractResult {
1660				gas_consumed: Zero::zero(),
1661				gas_required: Zero::zero(),
1662				storage_deposit: Default::default(),
1663				debug_message: Vec::new(),
1664				result: Err(Error::<T>::MigrationInProgress.into()),
1665				events: None,
1666			}
1667		}
1668	};
1669}
1670
1671impl<T: Config> Pallet<T> {
1672	/// Perform a call to a specified contract.
1673	///
1674	/// This function is similar to [`Self::call`], but doesn't perform any address lookups
1675	/// and better suitable for calling directly from Rust.
1676	///
1677	/// # Note
1678	///
1679	/// If `debug` is set to `DebugInfo::UnsafeDebug` it returns additional human readable debugging
1680	/// information.
1681	///
1682	/// If `collect_events` is set to `CollectEvents::UnsafeCollect` it collects all the Events
1683	/// emitted in the block so far and the ones emitted during the execution of this contract.
1684	pub fn bare_call(
1685		origin: T::AccountId,
1686		dest: T::AccountId,
1687		value: BalanceOf<T>,
1688		gas_limit: Weight,
1689		storage_deposit_limit: Option<BalanceOf<T>>,
1690		data: Vec<u8>,
1691		debug: DebugInfo,
1692		collect_events: CollectEvents,
1693		determinism: Determinism,
1694	) -> ContractExecResult<BalanceOf<T>, EventRecordOf<T>> {
1695		ensure_no_migration_in_progress!();
1696
1697		let mut debug_message = if matches!(debug, DebugInfo::UnsafeDebug) {
1698			Some(DebugBufferVec::<T>::default())
1699		} else {
1700			None
1701		};
1702		let origin = Origin::from_account_id(origin);
1703		let common = CommonInput {
1704			origin,
1705			value,
1706			data,
1707			gas_limit,
1708			storage_deposit_limit,
1709			debug_message: debug_message.as_mut(),
1710		};
1711		let output = CallInput::<T> { dest, determinism }.run_guarded(common);
1712		let events = if matches!(collect_events, CollectEvents::UnsafeCollect) {
1713			Some(System::<T>::read_events_no_consensus().map(|e| *e).collect())
1714		} else {
1715			None
1716		};
1717
1718		ContractExecResult {
1719			result: output.result.map_err(|r| r.error),
1720			gas_consumed: output.gas_meter.gas_consumed(),
1721			gas_required: output.gas_meter.gas_required(),
1722			storage_deposit: output.storage_deposit,
1723			debug_message: debug_message.unwrap_or_default().to_vec(),
1724			events,
1725		}
1726	}
1727
1728	/// Instantiate a new contract.
1729	///
1730	/// This function is similar to [`Self::instantiate`], but doesn't perform any address lookups
1731	/// and better suitable for calling directly from Rust.
1732	///
1733	/// It returns the execution result, account id and the amount of used weight.
1734	///
1735	/// # Note
1736	///
1737	/// If `debug` is set to `DebugInfo::UnsafeDebug` it returns additional human readable debugging
1738	/// information.
1739	///
1740	/// If `collect_events` is set to `CollectEvents::UnsafeCollect` it collects all the Events
1741	/// emitted in the block so far.
1742	pub fn bare_instantiate(
1743		origin: T::AccountId,
1744		value: BalanceOf<T>,
1745		gas_limit: Weight,
1746		mut storage_deposit_limit: Option<BalanceOf<T>>,
1747		code: Code<CodeHash<T>>,
1748		data: Vec<u8>,
1749		salt: Vec<u8>,
1750		debug: DebugInfo,
1751		collect_events: CollectEvents,
1752	) -> ContractInstantiateResult<T::AccountId, BalanceOf<T>, EventRecordOf<T>> {
1753		ensure_no_migration_in_progress!();
1754
1755		let mut debug_message = if debug == DebugInfo::UnsafeDebug {
1756			Some(DebugBufferVec::<T>::default())
1757		} else {
1758			None
1759		};
1760		// collect events if CollectEvents is UnsafeCollect
1761		let events = || {
1762			if collect_events == CollectEvents::UnsafeCollect {
1763				Some(System::<T>::read_events_no_consensus().map(|e| *e).collect())
1764			} else {
1765				None
1766			}
1767		};
1768
1769		let (code, upload_deposit): (WasmCode<T>, BalanceOf<T>) = match code {
1770			Code::Upload(code) => {
1771				let result = Self::try_upload_code(
1772					origin.clone(),
1773					code,
1774					storage_deposit_limit.map(Into::into),
1775					Determinism::Enforced,
1776					debug_message.as_mut(),
1777				);
1778
1779				let (module, deposit) = match result {
1780					Ok(result) => result,
1781					Err(error) =>
1782						return ContractResult {
1783							gas_consumed: Zero::zero(),
1784							gas_required: Zero::zero(),
1785							storage_deposit: Default::default(),
1786							debug_message: debug_message.unwrap_or(Default::default()).into(),
1787							result: Err(error),
1788							events: events(),
1789						},
1790				};
1791
1792				storage_deposit_limit =
1793					storage_deposit_limit.map(|l| l.saturating_sub(deposit.into()));
1794				(WasmCode::Wasm(module), deposit)
1795			},
1796			Code::Existing(hash) => (WasmCode::CodeHash(hash), Default::default()),
1797		};
1798
1799		let common = CommonInput {
1800			origin: Origin::from_account_id(origin),
1801			value,
1802			data,
1803			gas_limit,
1804			storage_deposit_limit,
1805			debug_message: debug_message.as_mut(),
1806		};
1807
1808		let output = InstantiateInput::<T> { code, salt }.run_guarded(common);
1809		ContractInstantiateResult {
1810			result: output
1811				.result
1812				.map(|(account_id, result)| InstantiateReturnValue { result, account_id })
1813				.map_err(|e| e.error),
1814			gas_consumed: output.gas_meter.gas_consumed(),
1815			gas_required: output.gas_meter.gas_required(),
1816			storage_deposit: output
1817				.storage_deposit
1818				.saturating_add(&StorageDeposit::Charge(upload_deposit)),
1819			debug_message: debug_message.unwrap_or_default().to_vec(),
1820			events: events(),
1821		}
1822	}
1823
1824	/// Upload new code without instantiating a contract from it.
1825	///
1826	/// This function is similar to [`Self::upload_code`], but doesn't perform any address lookups
1827	/// and better suitable for calling directly from Rust.
1828	pub fn bare_upload_code(
1829		origin: T::AccountId,
1830		code: Vec<u8>,
1831		storage_deposit_limit: Option<BalanceOf<T>>,
1832		determinism: Determinism,
1833	) -> CodeUploadResult<CodeHash<T>, BalanceOf<T>> {
1834		Migration::<T>::ensure_migrated()?;
1835		let (module, deposit) =
1836			Self::try_upload_code(origin, code, storage_deposit_limit, determinism, None)?;
1837		Ok(CodeUploadReturnValue { code_hash: *module.code_hash(), deposit })
1838	}
1839
1840	/// Uploads new code and returns the Wasm blob and deposit amount collected.
1841	fn try_upload_code(
1842		origin: T::AccountId,
1843		code: Vec<u8>,
1844		storage_deposit_limit: Option<BalanceOf<T>>,
1845		determinism: Determinism,
1846		mut debug_message: Option<&mut DebugBufferVec<T>>,
1847	) -> Result<(WasmBlob<T>, BalanceOf<T>), DispatchError> {
1848		let schedule = T::Schedule::get();
1849		let mut module =
1850			WasmBlob::from_code(code, &schedule, origin, determinism).map_err(|(err, msg)| {
1851				debug_message.as_mut().map(|d| d.try_extend(msg.bytes()));
1852				err
1853			})?;
1854		let deposit = module.store_code()?;
1855		if let Some(storage_deposit_limit) = storage_deposit_limit {
1856			ensure!(storage_deposit_limit >= deposit, <Error<T>>::StorageDepositLimitExhausted);
1857		}
1858
1859		Ok((module, deposit))
1860	}
1861
1862	/// Query storage of a specified contract under a specified key.
1863	pub fn get_storage(address: T::AccountId, key: Vec<u8>) -> GetStorageResult {
1864		if Migration::<T>::in_progress() {
1865			return Err(ContractAccessError::MigrationInProgress)
1866		}
1867		let contract_info =
1868			ContractInfoOf::<T>::get(&address).ok_or(ContractAccessError::DoesntExist)?;
1869
1870		let maybe_value = contract_info.read(
1871			&Key::<T>::try_from_var(key)
1872				.map_err(|_| ContractAccessError::KeyDecodingFailed)?
1873				.into(),
1874		);
1875		Ok(maybe_value)
1876	}
1877
1878	/// Determine the address of a contract.
1879	///
1880	/// This is the address generation function used by contract instantiation. See
1881	/// [`DefaultAddressGenerator`] for the default implementation.
1882	pub fn contract_address(
1883		deploying_address: &T::AccountId,
1884		code_hash: &CodeHash<T>,
1885		input_data: &[u8],
1886		salt: &[u8],
1887	) -> T::AccountId {
1888		T::AddressGenerator::contract_address(deploying_address, code_hash, input_data, salt)
1889	}
1890
1891	/// Returns the code hash of the contract specified by `account` ID.
1892	pub fn code_hash(account: &AccountIdOf<T>) -> Option<CodeHash<T>> {
1893		ContractInfo::<T>::load_code_hash(account)
1894	}
1895
1896	/// Store code for benchmarks which does not validate the code.
1897	#[cfg(feature = "runtime-benchmarks")]
1898	fn store_code_raw(
1899		code: Vec<u8>,
1900		owner: T::AccountId,
1901	) -> frame_support::dispatch::DispatchResult {
1902		let schedule = T::Schedule::get();
1903		WasmBlob::<T>::from_code_unchecked(code, &schedule, owner)?.store_code()?;
1904		Ok(())
1905	}
1906
1907	/// Deposit a pallet contracts event.
1908	fn deposit_event(event: Event<T>) {
1909		<frame_system::Pallet<T>>::deposit_event(<T as Config>::RuntimeEvent::from(event))
1910	}
1911
1912	/// Deposit a pallet contracts indexed event.
1913	fn deposit_indexed_event(topics: Vec<T::Hash>, event: Event<T>) {
1914		<frame_system::Pallet<T>>::deposit_event_indexed(
1915			&topics,
1916			<T as Config>::RuntimeEvent::from(event).into(),
1917		)
1918	}
1919
1920	/// Return the existential deposit of [`Config::Currency`].
1921	fn min_balance() -> BalanceOf<T> {
1922		<T::Currency as Inspect<AccountIdOf<T>>>::minimum_balance()
1923	}
1924
1925	/// Convert gas_limit from 1D Weight to a 2D Weight.
1926	///
1927	/// Used by backwards compatible extrinsics. We cannot just set the proof_size weight limit to
1928	/// zero or an old `Call` will just fail with OutOfGas.
1929	fn compat_weight_limit(gas_limit: OldWeight) -> Weight {
1930		Weight::from_parts(gas_limit, u64::from(T::MaxCodeLen::get()) * 2)
1931	}
1932}
1933
1934sp_api::decl_runtime_apis! {
1935	/// The API used to dry-run contract interactions.
1936	#[api_version(2)]
1937	pub trait ContractsApi<AccountId, Balance, BlockNumber, Hash, EventRecord> where
1938		AccountId: Codec,
1939		Balance: Codec,
1940		BlockNumber: Codec,
1941		Hash: Codec,
1942		EventRecord: Codec,
1943	{
1944		/// Perform a call from a specified account to a given contract.
1945		///
1946		/// See [`crate::Pallet::bare_call`].
1947		fn call(
1948			origin: AccountId,
1949			dest: AccountId,
1950			value: Balance,
1951			gas_limit: Option<Weight>,
1952			storage_deposit_limit: Option<Balance>,
1953			input_data: Vec<u8>,
1954		) -> ContractExecResult<Balance, EventRecord>;
1955
1956		/// Instantiate a new contract.
1957		///
1958		/// See `[crate::Pallet::bare_instantiate]`.
1959		fn instantiate(
1960			origin: AccountId,
1961			value: Balance,
1962			gas_limit: Option<Weight>,
1963			storage_deposit_limit: Option<Balance>,
1964			code: Code<Hash>,
1965			data: Vec<u8>,
1966			salt: Vec<u8>,
1967		) -> ContractInstantiateResult<AccountId, Balance, EventRecord>;
1968
1969		/// Upload new code without instantiating a contract from it.
1970		///
1971		/// See [`crate::Pallet::bare_upload_code`].
1972		fn upload_code(
1973			origin: AccountId,
1974			code: Vec<u8>,
1975			storage_deposit_limit: Option<Balance>,
1976			determinism: Determinism,
1977		) -> CodeUploadResult<Hash, Balance>;
1978
1979		/// Query a given storage key in a given contract.
1980		///
1981		/// Returns `Ok(Some(Vec<u8>))` if the storage value exists under the given key in the
1982		/// specified account and `Ok(None)` if it doesn't. If the account specified by the address
1983		/// doesn't exist, or doesn't have a contract then `Err` is returned.
1984		fn get_storage(
1985			address: AccountId,
1986			key: Vec<u8>,
1987		) -> GetStorageResult;
1988	}
1989}