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