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};
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::{traits::JustTry, 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 FreezeIdentifier = ();
91	type MaxFreezes = ConstU32<0>;
92	type MaxLocks = MaxLocks;
93	type MaxReserves = MaxReserves;
94	type ReserveIdentifier = [u8; 8];
95	type RuntimeEvent = RuntimeEvent;
96	type RuntimeHoldReason = RuntimeHoldReason;
97	type RuntimeFreezeReason = RuntimeFreezeReason;
98	type WeightInfo = ();
99	type DoneSlashHandler = ();
100}
101
102parameter_types! {
103	pub const AssetDeposit: u128 = 1_000_000;
104	pub const MetadataDepositBase: u128 = 1_000_000;
105	pub const MetadataDepositPerByte: u128 = 100_000;
106	pub const AssetAccountDeposit: u128 = 1_000_000;
107	pub const ApprovalDeposit: u128 = 1_000_000;
108	pub const AssetsStringLimit: u32 = 50;
109	pub const RemoveItemsLimit: u32 = 50;
110}
111
112impl pallet_assets::Config for Runtime {
113	type RuntimeEvent = RuntimeEvent;
114	type Balance = Balance;
115	type AssetId = AssetIdForAssets;
116	type Currency = Balances;
117	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
118	type ForceOrigin = EnsureRoot<AccountId>;
119	type AssetDeposit = AssetDeposit;
120	type MetadataDepositBase = MetadataDepositBase;
121	type MetadataDepositPerByte = MetadataDepositPerByte;
122	type AssetAccountDeposit = AssetAccountDeposit;
123	type ApprovalDeposit = ApprovalDeposit;
124	type StringLimit = AssetsStringLimit;
125	type Holder = ();
126	type Freezer = ();
127	type Extra = ();
128	type WeightInfo = ();
129	type RemoveItemsLimit = RemoveItemsLimit;
130	type AssetIdParameter = AssetIdForAssets;
131	type CallbackHandle = ();
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		JustTry,
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 AssetClaims = PolkadotXcm;
274	type SubscriptionService = PolkadotXcm;
275	type PalletInstancesInfo = AllPalletsWithSystem;
276	type FeeManager = ();
277	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
278	type MessageExporter = ();
279	type UniversalAliases = Nothing;
280	type CallDispatcher = RuntimeCall;
281	type SafeCallFilter = Everything;
282	type Aliasers = Nothing;
283	type TransactionalProcessor = FrameTransactionalProcessor;
284	type HrmpNewChannelOpenRequestHandler = ();
285	type HrmpChannelAcceptedHandler = ();
286	type HrmpChannelClosingHandler = ();
287	type XcmRecorder = PolkadotXcm;
288}
289
290impl mock_msg_queue::Config for Runtime {
291	type RuntimeEvent = RuntimeEvent;
292	type XcmExecutor = XcmExecutor<XcmConfig>;
293}
294
295pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
296
297pub struct TrustedLockerCase<T>(PhantomData<T>);
298impl<T: Get<(Location, AssetFilter)>> ContainsPair<Location, Asset> for TrustedLockerCase<T> {
299	fn contains(origin: &Location, asset: &Asset) -> bool {
300		let (o, a) = T::get();
301		a.matches(asset) && &o == origin
302	}
303}
304
305impl pallet_xcm::Config for Runtime {
306	type RuntimeEvent = RuntimeEvent;
307	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
308	type XcmRouter = XcmRouter;
309	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
310	type XcmExecuteFilter = Everything;
311	type XcmExecutor = XcmExecutor<XcmConfig>;
312	type XcmTeleportFilter = Nothing;
313	type XcmReserveTransferFilter = Everything;
314	type Weigher = FixedWeightBounds<XcmInstructionWeight, RuntimeCall, MaxInstructions>;
315	type UniversalLocation = UniversalLocation;
316	type RuntimeOrigin = RuntimeOrigin;
317	type RuntimeCall = RuntimeCall;
318	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
319	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
320	type Currency = Balances;
321	type CurrencyMatcher = IsConcrete<TokenLocation>;
322	type TrustedLockers = TrustedLockerCase<TrustedLockPairs>;
323	type SovereignAccountOf = SovereignAccountOf;
324	type MaxLockers = ConstU32<8>;
325	type MaxRemoteLockConsumers = ConstU32<0>;
326	type RemoteLockConsumerIdentifier = ();
327	type WeightInfo = pallet_xcm::TestWeightInfo;
328	type AdminOrigin = EnsureRoot<AccountId>;
329	// Aliasing is disabled: xcm_executor::Config::Aliasers is set to `Nothing`.
330	type AuthorizedAliasConsideration = Disabled;
331}
332
333type Block = frame_system::mocking::MockBlock<Runtime>;
334
335impl pallet_timestamp::Config for Runtime {
336	type Moment = u64;
337	type OnTimestampSet = ();
338	type MinimumPeriod = ConstU64<1>;
339	type WeightInfo = ();
340}
341
342construct_runtime!(
343	pub enum Runtime
344	{
345		System: frame_system,
346		Balances: pallet_balances,
347		Timestamp: pallet_timestamp,
348		MsgQueue: mock_msg_queue,
349		PolkadotXcm: pallet_xcm,
350		Contracts: pallet_contracts,
351		Assets: pallet_assets,
352	}
353);