referrerpolicy=no-referrer-when-downgrade

pallet_contracts_mock_network/
parachain.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Substrate.
3
4// Substrate is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Substrate is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Substrate.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Parachain runtime mock.
18
19mod contracts_config;
20use crate::{
21	mocks::msg_queue::pallet as mock_msg_queue,
22	primitives::{AccountId, AssetIdForAssets, Balance},
23};
24use core::marker::PhantomData;
25use frame_support::{
26	construct_runtime, derive_impl, parameter_types,
27	traits::{
28		AsEnsureOriginWithArg, Contains, ContainsPair, Disabled, Everything, EverythingBut, Nothing,
29	},
30	weights::{
31		constants::{WEIGHT_PROOF_SIZE_PER_MB, WEIGHT_REF_TIME_PER_SECOND},
32		Weight,
33	},
34};
35use frame_system::{EnsureRoot, EnsureSigned};
36use pallet_xcm::XcmPassthrough;
37use sp_core::{ConstU32, ConstU64, H256};
38use sp_runtime::traits::{Get, IdentityLookup, MaybeEquivalence, TryConvertInto};
39
40use xcm::latest::prelude::*;
41use xcm_builder::{
42	AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom,
43	ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds,
44	FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, IsConcrete, NativeAsset,
45	NoChecking, ParentAsSuperuser, ParentIsPreset, SignedAccountId32AsNative, SignedToAccountId32,
46	SovereignSignedViaLocation, WithComputedOrigin,
47};
48use xcm_executor::{Config, XcmExecutor};
49
50pub type SovereignAccountOf =
51	(AccountId32Aliases<RelayNetwork, AccountId>, ParentIsPreset<AccountId>);
52
53#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
54impl frame_system::Config for Runtime {
55	type RuntimeOrigin = RuntimeOrigin;
56	type RuntimeCall = RuntimeCall;
57	type Nonce = u64;
58	type Block = Block;
59	type Hash = H256;
60	type Hashing = ::sp_runtime::traits::BlakeTwo256;
61	type AccountId = AccountId;
62	type Lookup = IdentityLookup<Self::AccountId>;
63	type RuntimeEvent = RuntimeEvent;
64	type BlockWeights = ();
65	type BlockLength = ();
66	type Version = ();
67	type PalletInfo = PalletInfo;
68	type AccountData = pallet_balances::AccountData<Balance>;
69	type OnNewAccount = ();
70	type OnKilledAccount = ();
71	type DbWeight = ();
72	type BaseCallFilter = Everything;
73	type SystemWeightInfo = ();
74	type SS58Prefix = ();
75	type OnSetCode = ();
76	type MaxConsumers = ConstU32<16>;
77}
78
79parameter_types! {
80	pub ExistentialDeposit: Balance = 1;
81	pub const MaxLocks: u32 = 50;
82	pub const MaxReserves: u32 = 50;
83}
84
85impl pallet_balances::Config for Runtime {
86	type AccountStore = System;
87	type Balance = Balance;
88	type DustRemoval = ();
89	type ExistentialDeposit = ExistentialDeposit;
90	type MaxLocks = MaxLocks;
91	type MaxReserves = MaxReserves;
92	type ReserveIdentifier = [u8; 8];
93	type RuntimeEvent = RuntimeEvent;
94	type RuntimeHoldReason = RuntimeHoldReason;
95	type RuntimeFreezeReason = RuntimeFreezeReason;
96	type WeightInfo = ();
97	type DoneSlashHandler = ();
98}
99
100parameter_types! {
101	pub const AssetDeposit: u128 = 1_000_000;
102	pub const MetadataDepositBase: u128 = 1_000_000;
103	pub const MetadataDepositPerByte: u128 = 100_000;
104	pub const AssetAccountDeposit: u128 = 1_000_000;
105	pub const ApprovalDeposit: u128 = 1_000_000;
106	pub const AssetsStringLimit: u32 = 50;
107	pub const RemoveItemsLimit: u32 = 50;
108}
109
110impl pallet_assets::Config for Runtime {
111	type RuntimeEvent = RuntimeEvent;
112	type Balance = Balance;
113	type AssetId = AssetIdForAssets;
114	type ReserveData = ();
115	type Currency = Balances;
116	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
117	type ForceOrigin = EnsureRoot<AccountId>;
118	type AssetDeposit = AssetDeposit;
119	type MetadataDepositBase = MetadataDepositBase;
120	type MetadataDepositPerByte = MetadataDepositPerByte;
121	type AssetAccountDeposit = AssetAccountDeposit;
122	type ApprovalDeposit = ApprovalDeposit;
123	type StringLimit = AssetsStringLimit;
124	type Holder = ();
125	type Freezer = ();
126	type Extra = ();
127	type WeightInfo = ();
128	type RemoveItemsLimit = RemoveItemsLimit;
129	type AssetIdParameter = AssetIdForAssets;
130	type CallbackHandle = ();
131	type AssetIdAllocator = ();
132	#[cfg(feature = "runtime-benchmarks")]
133	type BenchmarkHelper = ();
134}
135
136parameter_types! {
137	pub const ReservedXcmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0);
138	pub const ReservedDmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0);
139}
140
141parameter_types! {
142	pub const KsmLocation: Location = Location::parent();
143	pub const TokenLocation: Location = Here.into_location();
144	pub const RelayNetwork: NetworkId = ByGenesis([0; 32]);
145	pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::parachain_id().into())].into();
146}
147
148pub type XcmOriginToCallOrigin = (
149	SovereignSignedViaLocation<SovereignAccountOf, RuntimeOrigin>,
150	ParentAsSuperuser<RuntimeOrigin>,
151	SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
152	XcmPassthrough<RuntimeOrigin>,
153);
154
155parameter_types! {
156	pub const XcmInstructionWeight: Weight = Weight::from_parts(1_000, 1_000);
157	pub TokensPerSecondPerMegabyte: (AssetId, u128, u128) = (AssetId(Parent.into()), 1_000_000_000_000, 1024 * 1024);
158	pub const MaxInstructions: u32 = 100;
159	pub const MaxAssetsIntoHolding: u32 = 64;
160	pub ForeignPrefix: Location = (Parent,).into();
161	pub CheckingAccount: AccountId = PolkadotXcm::check_account();
162	pub TrustedLockPairs: (Location, AssetFilter) =
163	(Parent.into(), Wild(AllOf { id: AssetId(Parent.into()), fun: WildFungible }));
164}
165
166pub fn estimate_message_fee(number_of_instructions: u64) -> u128 {
167	let weight = estimate_weight(number_of_instructions);
168
169	estimate_fee_for_weight(weight)
170}
171
172pub fn estimate_weight(number_of_instructions: u64) -> Weight {
173	XcmInstructionWeight::get().saturating_mul(number_of_instructions)
174}
175
176pub fn estimate_fee_for_weight(weight: Weight) -> u128 {
177	let (_, units_per_second, units_per_mb) = TokensPerSecondPerMegabyte::get();
178
179	units_per_second * (weight.ref_time() as u128) / (WEIGHT_REF_TIME_PER_SECOND as u128) +
180		units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128)
181}
182
183pub type LocalBalancesTransactor =
184	FungibleAdapter<Balances, IsConcrete<TokenLocation>, SovereignAccountOf, AccountId, ()>;
185
186pub struct FromLocationToAsset<Location, AssetId>(PhantomData<(Location, AssetId)>);
187impl MaybeEquivalence<Location, AssetIdForAssets>
188	for FromLocationToAsset<Location, AssetIdForAssets>
189{
190	fn convert(value: &Location) -> Option<AssetIdForAssets> {
191		match value.unpack() {
192			(1, []) => Some(0 as AssetIdForAssets),
193			(1, [Parachain(para_id)]) => Some(*para_id as AssetIdForAssets),
194			_ => None,
195		}
196	}
197
198	fn convert_back(_id: &AssetIdForAssets) -> Option<Location> {
199		None
200	}
201}
202
203pub type ForeignAssetsTransactor = FungiblesAdapter<
204	Assets,
205	ConvertedConcreteId<
206		AssetIdForAssets,
207		Balance,
208		FromLocationToAsset<Location, AssetIdForAssets>,
209		TryConvertInto,
210	>,
211	SovereignAccountOf,
212	AccountId,
213	NoChecking,
214	CheckingAccount,
215>;
216
217/// Means for transacting assets on this chain
218pub type AssetTransactors = (LocalBalancesTransactor, ForeignAssetsTransactor);
219
220pub struct ParentRelay;
221impl Contains<Location> for ParentRelay {
222	fn contains(location: &Location) -> bool {
223		location.contains_parents_only(1)
224	}
225}
226pub struct ThisParachain;
227impl Contains<Location> for ThisParachain {
228	fn contains(location: &Location) -> bool {
229		matches!(location.unpack(), (0, [Junction::AccountId32 { .. }]))
230	}
231}
232
233pub type XcmRouter = crate::ParachainXcmRouter<MsgQueue>;
234
235pub type Barrier = (
236	xcm_builder::AllowUnpaidExecutionFrom<ThisParachain>,
237	WithComputedOrigin<
238		(AllowExplicitUnpaidExecutionFrom<ParentRelay>, AllowTopLevelPaidExecutionFrom<Everything>),
239		UniversalLocation,
240		ConstU32<1>,
241	>,
242);
243
244parameter_types! {
245	pub NftCollectionOne: AssetFilter
246		= Wild(AllOf { fun: WildNonFungible, id: AssetId((Parent, GeneralIndex(1)).into()) });
247	pub NftCollectionOneForRelay: (AssetFilter, Location)
248		= (NftCollectionOne::get(), Parent.into());
249	pub RelayNativeAsset: AssetFilter = Wild(AllOf { fun: WildFungible, id: AssetId((Parent, Here).into()) });
250	pub RelayNativeAssetForRelay: (AssetFilter, Location) = (RelayNativeAsset::get(), Parent.into());
251}
252pub type TrustedTeleporters =
253	(xcm_builder::Case<NftCollectionOneForRelay>, xcm_builder::Case<RelayNativeAssetForRelay>);
254pub type TrustedReserves = EverythingBut<xcm_builder::Case<NftCollectionOneForRelay>>;
255
256pub struct XcmConfig;
257impl Config for XcmConfig {
258	type RuntimeCall = RuntimeCall;
259	type XcmSender = XcmRouter;
260	type XcmEventEmitter = PolkadotXcm;
261	type AssetTransactor = AssetTransactors;
262	type OriginConverter = XcmOriginToCallOrigin;
263	type IsReserve = (NativeAsset, TrustedReserves);
264	type IsTeleporter = TrustedTeleporters;
265	type UniversalLocation = UniversalLocation;
266	type Barrier = Barrier;
267	type Weigher = FixedWeightBounds<XcmInstructionWeight, RuntimeCall, MaxInstructions>;
268	type Trader = FixedRateOfFungible<TokensPerSecondPerMegabyte, ()>;
269	type ResponseHandler = PolkadotXcm;
270	type AssetTrap = PolkadotXcm;
271	type AssetLocker = PolkadotXcm;
272	type AssetExchanger = ();
273	type SubscriptionService = PolkadotXcm;
274	type PalletInstancesInfo = AllPalletsWithSystem;
275	type FeeManager = ();
276	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
277	type MessageExporter = ();
278	type UniversalAliases = Nothing;
279	type CallDispatcher = RuntimeCall;
280	type SafeCallFilter = Everything;
281	type Aliasers = Nothing;
282	type TransactionalProcessor = FrameTransactionalProcessor;
283	type HrmpNewChannelOpenRequestHandler = ();
284	type HrmpChannelAcceptedHandler = ();
285	type HrmpChannelClosingHandler = ();
286	type XcmRecorder = PolkadotXcm;
287}
288
289impl mock_msg_queue::Config for Runtime {
290	type RuntimeEvent = RuntimeEvent;
291	type XcmExecutor = XcmExecutor<XcmConfig>;
292}
293
294pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
295
296pub struct TrustedLockerCase<T>(PhantomData<T>);
297impl<T: Get<(Location, AssetFilter)>> ContainsPair<Location, Asset> for TrustedLockerCase<T> {
298	fn contains(origin: &Location, asset: &Asset) -> bool {
299		let (o, a) = T::get();
300		a.matches(asset) && &o == origin
301	}
302}
303
304impl pallet_xcm::Config for Runtime {
305	type RuntimeEvent = RuntimeEvent;
306	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
307	type XcmRouter = XcmRouter;
308	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
309	type XcmExecuteFilter = Everything;
310	type XcmExecutor = XcmExecutor<XcmConfig>;
311	type XcmTeleportFilter = Nothing;
312	type XcmReserveTransferFilter = Everything;
313	type Weigher = FixedWeightBounds<XcmInstructionWeight, RuntimeCall, MaxInstructions>;
314	type UniversalLocation = UniversalLocation;
315	type RuntimeOrigin = RuntimeOrigin;
316	type RuntimeCall = RuntimeCall;
317	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
318	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
319	type Currency = Balances;
320	type CurrencyMatcher = IsConcrete<TokenLocation>;
321	type TrustedLockers = TrustedLockerCase<TrustedLockPairs>;
322	type SovereignAccountOf = SovereignAccountOf;
323	type MaxLockers = ConstU32<8>;
324	type MaxRemoteLockConsumers = ConstU32<0>;
325	type RemoteLockConsumerIdentifier = ();
326	type WeightInfo = pallet_xcm::TestWeightInfo;
327	type AdminOrigin = EnsureRoot<AccountId>;
328	// Aliasing is disabled: xcm_executor::Config::Aliasers is set to `Nothing`.
329	type AuthorizedAliasConsideration = Disabled;
330}
331
332type Block = frame_system::mocking::MockBlock<Runtime>;
333
334impl pallet_timestamp::Config for Runtime {
335	type Moment = u64;
336	type OnTimestampSet = ();
337	type MinimumPeriod = ConstU64<1>;
338	type WeightInfo = ();
339}
340
341construct_runtime!(
342	pub enum Runtime
343	{
344		System: frame_system,
345		Balances: pallet_balances,
346		Timestamp: pallet_timestamp,
347		MsgQueue: mock_msg_queue,
348		PolkadotXcm: pallet_xcm,
349		Contracts: pallet_contracts,
350		Assets: pallet_assets,
351	}
352);