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 ReserveData = ();
117	type Currency = Balances;
118	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
119	type ForceOrigin = EnsureRoot<AccountId>;
120	type AssetDeposit = AssetDeposit;
121	type MetadataDepositBase = MetadataDepositBase;
122	type MetadataDepositPerByte = MetadataDepositPerByte;
123	type AssetAccountDeposit = AssetAccountDeposit;
124	type ApprovalDeposit = ApprovalDeposit;
125	type StringLimit = AssetsStringLimit;
126	type Holder = ();
127	type Freezer = ();
128	type Extra = ();
129	type WeightInfo = ();
130	type RemoveItemsLimit = RemoveItemsLimit;
131	type AssetIdParameter = AssetIdForAssets;
132	type CallbackHandle = ();
133	#[cfg(feature = "runtime-benchmarks")]
134	type BenchmarkHelper = ();
135}
136
137parameter_types! {
138	pub const ReservedXcmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0);
139	pub const ReservedDmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0);
140}
141
142parameter_types! {
143	pub const KsmLocation: Location = Location::parent();
144	pub const TokenLocation: Location = Here.into_location();
145	pub const RelayNetwork: NetworkId = ByGenesis([0; 32]);
146	pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::parachain_id().into())].into();
147}
148
149pub type XcmOriginToCallOrigin = (
150	SovereignSignedViaLocation<SovereignAccountOf, RuntimeOrigin>,
151	ParentAsSuperuser<RuntimeOrigin>,
152	SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
153	XcmPassthrough<RuntimeOrigin>,
154);
155
156parameter_types! {
157	pub const XcmInstructionWeight: Weight = Weight::from_parts(1_000, 1_000);
158	pub TokensPerSecondPerMegabyte: (AssetId, u128, u128) = (AssetId(Parent.into()), 1_000_000_000_000, 1024 * 1024);
159	pub const MaxInstructions: u32 = 100;
160	pub const MaxAssetsIntoHolding: u32 = 64;
161	pub ForeignPrefix: Location = (Parent,).into();
162	pub CheckingAccount: AccountId = PolkadotXcm::check_account();
163	pub TrustedLockPairs: (Location, AssetFilter) =
164	(Parent.into(), Wild(AllOf { id: AssetId(Parent.into()), fun: WildFungible }));
165}
166
167pub fn estimate_message_fee(number_of_instructions: u64) -> u128 {
168	let weight = estimate_weight(number_of_instructions);
169
170	estimate_fee_for_weight(weight)
171}
172
173pub fn estimate_weight(number_of_instructions: u64) -> Weight {
174	XcmInstructionWeight::get().saturating_mul(number_of_instructions)
175}
176
177pub fn estimate_fee_for_weight(weight: Weight) -> u128 {
178	let (_, units_per_second, units_per_mb) = TokensPerSecondPerMegabyte::get();
179
180	units_per_second * (weight.ref_time() as u128) / (WEIGHT_REF_TIME_PER_SECOND as u128) +
181		units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128)
182}
183
184pub type LocalBalancesTransactor =
185	FungibleAdapter<Balances, IsConcrete<TokenLocation>, SovereignAccountOf, AccountId, ()>;
186
187pub struct FromLocationToAsset<Location, AssetId>(PhantomData<(Location, AssetId)>);
188impl MaybeEquivalence<Location, AssetIdForAssets>
189	for FromLocationToAsset<Location, AssetIdForAssets>
190{
191	fn convert(value: &Location) -> Option<AssetIdForAssets> {
192		match value.unpack() {
193			(1, []) => Some(0 as AssetIdForAssets),
194			(1, [Parachain(para_id)]) => Some(*para_id as AssetIdForAssets),
195			_ => None,
196		}
197	}
198
199	fn convert_back(_id: &AssetIdForAssets) -> Option<Location> {
200		None
201	}
202}
203
204pub type ForeignAssetsTransactor = FungiblesAdapter<
205	Assets,
206	ConvertedConcreteId<
207		AssetIdForAssets,
208		Balance,
209		FromLocationToAsset<Location, AssetIdForAssets>,
210		JustTry,
211	>,
212	SovereignAccountOf,
213	AccountId,
214	NoChecking,
215	CheckingAccount,
216>;
217
218/// Means for transacting assets on this chain
219pub type AssetTransactors = (LocalBalancesTransactor, ForeignAssetsTransactor);
220
221pub struct ParentRelay;
222impl Contains<Location> for ParentRelay {
223	fn contains(location: &Location) -> bool {
224		location.contains_parents_only(1)
225	}
226}
227pub struct ThisParachain;
228impl Contains<Location> for ThisParachain {
229	fn contains(location: &Location) -> bool {
230		matches!(location.unpack(), (0, [Junction::AccountId32 { .. }]))
231	}
232}
233
234pub type XcmRouter = crate::ParachainXcmRouter<MsgQueue>;
235
236pub type Barrier = (
237	xcm_builder::AllowUnpaidExecutionFrom<ThisParachain>,
238	WithComputedOrigin<
239		(AllowExplicitUnpaidExecutionFrom<ParentRelay>, AllowTopLevelPaidExecutionFrom<Everything>),
240		UniversalLocation,
241		ConstU32<1>,
242	>,
243);
244
245parameter_types! {
246	pub NftCollectionOne: AssetFilter
247		= Wild(AllOf { fun: WildNonFungible, id: AssetId((Parent, GeneralIndex(1)).into()) });
248	pub NftCollectionOneForRelay: (AssetFilter, Location)
249		= (NftCollectionOne::get(), Parent.into());
250	pub RelayNativeAsset: AssetFilter = Wild(AllOf { fun: WildFungible, id: AssetId((Parent, Here).into()) });
251	pub RelayNativeAssetForRelay: (AssetFilter, Location) = (RelayNativeAsset::get(), Parent.into());
252}
253pub type TrustedTeleporters =
254	(xcm_builder::Case<NftCollectionOneForRelay>, xcm_builder::Case<RelayNativeAssetForRelay>);
255pub type TrustedReserves = EverythingBut<xcm_builder::Case<NftCollectionOneForRelay>>;
256
257pub struct XcmConfig;
258impl Config for XcmConfig {
259	type RuntimeCall = RuntimeCall;
260	type XcmSender = XcmRouter;
261	type XcmEventEmitter = PolkadotXcm;
262	type AssetTransactor = AssetTransactors;
263	type OriginConverter = XcmOriginToCallOrigin;
264	type IsReserve = (NativeAsset, TrustedReserves);
265	type IsTeleporter = TrustedTeleporters;
266	type UniversalLocation = UniversalLocation;
267	type Barrier = Barrier;
268	type Weigher = FixedWeightBounds<XcmInstructionWeight, RuntimeCall, MaxInstructions>;
269	type Trader = FixedRateOfFungible<TokensPerSecondPerMegabyte, ()>;
270	type ResponseHandler = PolkadotXcm;
271	type AssetTrap = PolkadotXcm;
272	type AssetLocker = PolkadotXcm;
273	type AssetExchanger = ();
274	type AssetClaims = PolkadotXcm;
275	type SubscriptionService = PolkadotXcm;
276	type PalletInstancesInfo = AllPalletsWithSystem;
277	type FeeManager = ();
278	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
279	type MessageExporter = ();
280	type UniversalAliases = Nothing;
281	type CallDispatcher = RuntimeCall;
282	type SafeCallFilter = Everything;
283	type Aliasers = Nothing;
284	type TransactionalProcessor = FrameTransactionalProcessor;
285	type HrmpNewChannelOpenRequestHandler = ();
286	type HrmpChannelAcceptedHandler = ();
287	type HrmpChannelClosingHandler = ();
288	type XcmRecorder = PolkadotXcm;
289}
290
291impl mock_msg_queue::Config for Runtime {
292	type RuntimeEvent = RuntimeEvent;
293	type XcmExecutor = XcmExecutor<XcmConfig>;
294}
295
296pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
297
298pub struct TrustedLockerCase<T>(PhantomData<T>);
299impl<T: Get<(Location, AssetFilter)>> ContainsPair<Location, Asset> for TrustedLockerCase<T> {
300	fn contains(origin: &Location, asset: &Asset) -> bool {
301		let (o, a) = T::get();
302		a.matches(asset) && &o == origin
303	}
304}
305
306impl pallet_xcm::Config for Runtime {
307	type RuntimeEvent = RuntimeEvent;
308	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
309	type XcmRouter = XcmRouter;
310	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
311	type XcmExecuteFilter = Everything;
312	type XcmExecutor = XcmExecutor<XcmConfig>;
313	type XcmTeleportFilter = Nothing;
314	type XcmReserveTransferFilter = Everything;
315	type Weigher = FixedWeightBounds<XcmInstructionWeight, RuntimeCall, MaxInstructions>;
316	type UniversalLocation = UniversalLocation;
317	type RuntimeOrigin = RuntimeOrigin;
318	type RuntimeCall = RuntimeCall;
319	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
320	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
321	type Currency = Balances;
322	type CurrencyMatcher = IsConcrete<TokenLocation>;
323	type TrustedLockers = TrustedLockerCase<TrustedLockPairs>;
324	type SovereignAccountOf = SovereignAccountOf;
325	type MaxLockers = ConstU32<8>;
326	type MaxRemoteLockConsumers = ConstU32<0>;
327	type RemoteLockConsumerIdentifier = ();
328	type WeightInfo = pallet_xcm::TestWeightInfo;
329	type AdminOrigin = EnsureRoot<AccountId>;
330	// Aliasing is disabled: xcm_executor::Config::Aliasers is set to `Nothing`.
331	type AuthorizedAliasConsideration = Disabled;
332}
333
334type Block = frame_system::mocking::MockBlock<Runtime>;
335
336impl pallet_timestamp::Config for Runtime {
337	type Moment = u64;
338	type OnTimestampSet = ();
339	type MinimumPeriod = ConstU64<1>;
340	type WeightInfo = ();
341}
342
343construct_runtime!(
344	pub enum Runtime
345	{
346		System: frame_system,
347		Balances: pallet_balances,
348		Timestamp: pallet_timestamp,
349		MsgQueue: mock_msg_queue,
350		PolkadotXcm: pallet_xcm,
351		Contracts: pallet_contracts,
352		Assets: pallet_assets,
353	}
354);