1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi 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
// Tanssi 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 Tanssi.  If not, see <http://www.gnu.org/licenses/>
16

            
17
use {
18
    super::{
19
        currency::MICROUNIT,
20
        precompiles::FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
21
        weights::{self, xcm::XcmWeight as XcmGenericWeights},
22
        AccountId, AllPalletsWithSystem, AssetRate, Balance, Balances, EthereumLocation,
23
        EthereumNetwork, ForeignAssetsCreator, MaintenanceMode, MessageQueue, ParachainInfo,
24
        ParachainSystem, PolkadotXcm, Runtime, RuntimeBlockWeights, RuntimeCall, RuntimeEvent,
25
        RuntimeOrigin, TransactionByteFee, WeightToFee, XcmpQueue,
26
    },
27
    alloc::vec::Vec,
28
    ccp_xcm::SignedToAccountKey20,
29
    cumulus_primitives_core::{AggregateMessageOrigin, ParaId},
30
    frame_support::{
31
        parameter_types,
32
        traits::{Disabled, Equals, Everything, Get, Nothing, PalletInfoAccess, TransformOrigin},
33
        weights::Weight,
34
    },
35
    frame_system::EnsureRoot,
36
    pallet_foreign_asset_creator::{
37
        AssetBalance, AssetId as AssetIdOf, ForeignAssetCreatedHook, ForeignAssetDestroyedHook,
38
    },
39
    pallet_xcm::XcmPassthrough,
40
    pallet_xcm_executor_utils::{
41
        filters::{IsReserveFilter, IsTeleportFilter},
42
        DefaultTrustPolicy,
43
    },
44
    parachains_common::{
45
        message_queue::{NarrowOriginToSibling, ParaIdToSibling},
46
        xcm_config::AssetFeeAsExistentialDepositMultiplier,
47
    },
48
    polkadot_runtime_common::xcm_sender::ExponentialPrice,
49
    sp_core::{ConstU32, H160},
50
    sp_runtime::Perbill,
51
    tanssi_runtime_common::universal_aliases::CommonUniversalAliases,
52
    tp_container_chain::{
53
        sovereign_paid_remote_exporter::SovereignPaidRemoteExporter,
54
        ContainerChainEthereumLocationConverter,
55
    },
56
    tp_xcm_commons::EthereumAssetReserveFromParent,
57
    xcm::latest::prelude::*,
58
    xcm_builder::{
59
        AccountKey20Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom,
60
        AllowTopLevelPaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, FungibleAdapter,
61
        IsConcrete, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
62
        SiblingParachainConvertsVia, SignedAccountKey20AsNative, SovereignSignedViaLocation,
63
        TakeWeightCredit, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
64
        XcmFeeManagerFromComponents,
65
    },
66
    xcm_executor::XcmExecutor,
67
    xcm_primitives::AccountIdAssetIdConversion,
68
};
69

            
70
parameter_types! {
71
    // Self Reserve location, defines the multilocation identifiying the self-reserve currency
72
    // This is used to match it also against our Balances pallet when we receive such
73
    // a Location: (Self Balances pallet index)
74
    // We use the RELATIVE multilocation
75
    pub SelfReserve: Location = Location {
76
        parents:0,
77
        interior: [
78
            PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
79
        ].into()
80
    };
81

            
82
    // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate.
83
    pub UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
84
}
85

            
86
parameter_types! {
87
    // The relay chain Origin type
88
    pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
89

            
90
    pub const MaxAssetsIntoHolding: u32 = 64;
91

            
92
    /// Maximum number of instructions in a single XCM fragment. A sanity check against
93
    /// weight caculations getting too crazy.
94
    pub MaxInstructions: u32 = 100;
95

            
96
    // Dynamic RelayNetwork parameter - configurable via pallet_parameters
97
    pub RelayNetwork: NetworkId = crate::dynamic_params::xcm_config::RelayNetwork::get();
98

            
99
    // The universal location within the global consensus system
100
    pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into();
101

            
102
    pub const BaseDeliveryFee: u128 = 100 * MICROUNIT;
103
    pub RootLocation: Location = Location::here();
104

            
105
    // TODO: Revisit later
106
    pub const ContainerToEthTransferFee: u128 = 2_700_000_000_000u128;
107
}
108

            
109
#[cfg(feature = "runtime-benchmarks")]
110
parameter_types! {
111
    pub ReachableDest: Option<Location> = Some(Parent.into());
112
}
113

            
114
pub type XcmBarrier = (
115
    // Weight that is paid for may be consumed.
116
    TakeWeightCredit,
117
    // Expected responses are OK.
118
    AllowKnownQueryResponses<PolkadotXcm>,
119
    WithComputedOrigin<
120
        (
121
            // If the message is one that immediately attemps to pay for execution, then allow it.
122
            AllowTopLevelPaidExecutionFrom<Everything>,
123
            // Subscriptions for version tracking are OK.
124
            AllowSubscriptionsFrom<Everything>,
125
        ),
126
        UniversalLocation,
127
        ConstU32<8>,
128
    >,
129
);
130

            
131
// For benchmarking, we cannot use the describeFamily
132
// the benchmark is written to be able to convert an AccountId32, but describeFamily prevents this
133
#[cfg(not(feature = "runtime-benchmarks"))]
134
type Descriptor = xcm_builder::DescribeFamily<xcm_builder::DescribeAllTerminal>;
135
#[cfg(feature = "runtime-benchmarks")]
136
type Descriptor = xcm_builder::DescribeAllTerminal;
137

            
138
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
139
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
140
/// `Transact` in order to determine the dispatch Origin.
141
pub type LocationToAccountId = (
142
    // The parent (Relay-chain) origin converts to the default `AccountId`.
143
    ParentIsPreset<AccountId>,
144
    // Sibling parachain origins convert to AccountId via the `ParaId::into`.
145
    SiblingParachainConvertsVia<polkadot_parachain_primitives::primitives::Sibling, AccountId>,
146
    // If we receive a Location of type AccountKey20, just generate a native account
147
    AccountKey20Aliases<RelayNetwork, AccountId>,
148
    // Generate remote accounts according to polkadot standards
149
    xcm_builder::HashedDescription<AccountId, Descriptor>,
150
    // Ethereum contract sovereign account.
151
    // (Used to convert ethereum contract locations to sovereign account)
152
    ContainerChainEthereumLocationConverter<AccountId>,
153
);
154

            
155
/// Local origins on this chain are allowed to dispatch XCM sends/executions.
156
pub type LocalOriginToLocation = SignedToAccountKey20<RuntimeOrigin, AccountId, RelayNetwork>;
157

            
158
/// Means for transacting the native currency on this chain.
159
pub type CurrencyTransactor = FungibleAdapter<
160
    // Use this currency:
161
    Balances,
162
    // Use this currency when it is a fungible asset matching the given location or name:
163
    IsConcrete<SelfReserve>,
164
    // Convert an XCM Location into a local account id:
165
    LocationToAccountId,
166
    // Our chain's account ID type (we can't get away without mentioning it explicitly):
167
    AccountId,
168
    // We don't track any teleports of `Balances`.
169
    (),
170
>;
171

            
172
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
173
/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
174
/// biases the kind of local `Origin` it will become.
175
pub type XcmOriginToTransactDispatchOrigin = (
176
    // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
177
    // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
178
    // foreign chains who want to have a local sovereign account on this chain which they control.
179
    SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
180
    // Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when
181
    // recognised.
182
    RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
183
    // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
184
    // recognised.
185
    SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
186
    // Native signed account converter; this just converts an `AccountId32` origin into a normal
187
    // `RuntimeOrigin::Signed` origin of the same 32-byte value.
188
    SignedAccountKey20AsNative<RelayNetwork, RuntimeOrigin>,
189
    // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
190
    XcmPassthrough<RuntimeOrigin>,
191
);
192

            
193
/// Means for transacting assets on this chain.
194
pub type AssetTransactors = (CurrencyTransactor, ForeignFungiblesTransactor);
195
pub type XcmWeigher =
196
    WeightInfoBounds<XcmGenericWeights<RuntimeCall>, RuntimeCall, MaxInstructions>;
197

            
198
pub type UmpRouter =
199
    cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>;
200

            
201
/// The means for routing XCM messages which are not for local execution into the right message
202
/// queues.
203
pub type XcmRouter = WithUniqueTopic<(
204
    // Two routers - use UMP to communicate with the relay chain:
205
    UmpRouter,
206
    // ..and XCMP to communicate with the sibling chains.
207
    XcmpQueue,
208
    SovereignPaidRemoteExporter<
209
        UmpRouter,
210
        UniversalLocation,
211
        crate::EthereumNetwork,
212
        ContainerToEthTransferFee,
213
        ParachainInfo,
214
    >,
215
)>;
216

            
217
pub struct XcmConfig;
218
impl xcm_executor::Config for XcmConfig {
219
    type RuntimeCall = RuntimeCall;
220
    type XcmSender = XcmRouter;
221
    type AssetTransactor = AssetTransactors;
222
    type OriginConverter = XcmOriginToTransactDispatchOrigin;
223
    // We admit as reserves:
224
    // - Native assets 'AllNative'
225
    // - Ethereum assets with ethereum or relay origin
226
    type IsReserve = (
227
        IsReserveFilter<Runtime>,
228
        EthereumAssetReserveFromParent<EthereumLocation, EthereumNetwork>,
229
    );
230
    type IsTeleporter = IsTeleportFilter<Runtime>;
231
    type UniversalLocation = UniversalLocation;
232
    type Barrier = XcmBarrier;
233
    type Weigher = XcmWeigher;
234
    type Trader = (
235
        UsingComponents<WeightToFee, SelfReserve, AccountId, Balances, ()>,
236
        cumulus_primitives_utility::TakeFirstAssetTrader<
237
            AccountId,
238
            AssetRateAsMultiplier,
239
            // Use this currency when it is a fungible asset matching the given location or name:
240
            (ConvertedConcreteId<AssetId, Balance, ForeignAssetsCreator, JustTry>,),
241
            ForeignAssets,
242
            (),
243
        >,
244
    );
245
    type ResponseHandler = PolkadotXcm;
246
    type AssetTrap = PolkadotXcm;
247
    type AssetClaims = PolkadotXcm;
248
    type SubscriptionService = PolkadotXcm;
249
    type PalletInstancesInfo = AllPalletsWithSystem;
250
    type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
251
    type AssetLocker = ();
252
    type AssetExchanger = ();
253
    type FeeManager = XcmFeeManagerFromComponents<Equals<RootLocation>, ()>;
254
    type MessageExporter = ();
255
    type UniversalAliases = CommonUniversalAliases;
256
    type CallDispatcher = RuntimeCall;
257
    type SafeCallFilter = Everything;
258
    type Aliasers = Nothing;
259
    type TransactionalProcessor = xcm_builder::FrameTransactionalProcessor;
260
    type HrmpNewChannelOpenRequestHandler = ();
261
    type HrmpChannelAcceptedHandler = ();
262
    type HrmpChannelClosingHandler = ();
263
    type XcmRecorder = ();
264
    type XcmEventEmitter = PolkadotXcm;
265
}
266

            
267
impl pallet_xcm::Config for Runtime {
268
    type RuntimeEvent = RuntimeEvent;
269
    type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
270
    type XcmRouter = XcmRouter;
271
    type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
272
    type XcmExecuteFilter = Everything;
273
    type XcmExecutor = XcmExecutor<XcmConfig>;
274
    type XcmTeleportFilter = Nothing;
275
    type XcmReserveTransferFilter = Everything;
276
    type Weigher = XcmWeigher;
277
    type UniversalLocation = UniversalLocation;
278
    type RuntimeOrigin = RuntimeOrigin;
279
    type RuntimeCall = RuntimeCall;
280
    const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
281
    type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
282
    type Currency = Balances;
283
    type CurrencyMatcher = ();
284
    type TrustedLockers = ();
285
    type SovereignAccountOf = LocationToAccountId;
286
    type MaxLockers = ConstU32<8>;
287
    type MaxRemoteLockConsumers = ConstU32<0>;
288
    type RemoteLockConsumerIdentifier = ();
289
    type WeightInfo = weights::pallet_xcm::SubstrateWeight<Runtime>;
290
    type AdminOrigin = EnsureRoot<AccountId>;
291
    type AuthorizedAliasConsideration = Disabled;
292
}
293

            
294
pub type PriceForSiblingParachainDelivery =
295
    ExponentialPrice<SelfReserve, BaseDeliveryFee, TransactionByteFee, XcmpQueue>;
296

            
297
pub type PriceForParentDelivery =
298
    ExponentialPrice<SelfReserve, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
299

            
300
impl cumulus_pallet_xcmp_queue::Config for Runtime {
301
    type RuntimeEvent = RuntimeEvent;
302
    type ChannelInfo = ParachainSystem;
303
    type VersionWrapper = PolkadotXcm;
304
    type ControllerOrigin = EnsureRoot<AccountId>;
305
    type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
306
    type WeightInfo = weights::cumulus_pallet_xcmp_queue::SubstrateWeight<Runtime>;
307
    type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
308
    type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
309
    type MaxInboundSuspended = sp_core::ConstU32<1_000>;
310
    type MaxActiveOutboundChannels = ConstU32<128>;
311
    type MaxPageSize = ConstU32<{ 103 * 1024 }>;
312
}
313

            
314
impl cumulus_pallet_xcm::Config for Runtime {
315
    type RuntimeEvent = RuntimeEvent;
316
    type XcmExecutor = XcmExecutor<XcmConfig>;
317
}
318

            
319
parameter_types! {
320
    pub MessageQueueServiceWeight: Weight = Perbill::from_percent(25) * RuntimeBlockWeights::get().max_block;
321
}
322

            
323
impl pallet_message_queue::Config for Runtime {
324
    type RuntimeEvent = RuntimeEvent;
325
    type WeightInfo = weights::pallet_message_queue::SubstrateWeight<Self>;
326
    #[cfg(feature = "runtime-benchmarks")]
327
    type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<
328
        cumulus_primitives_core::AggregateMessageOrigin,
329
    >;
330
    #[cfg(not(feature = "runtime-benchmarks"))]
331
    type MessageProcessor =
332
        xcm_builder::ProcessXcmMessage<AggregateMessageOrigin, XcmExecutor<XcmConfig>, RuntimeCall>;
333
    type Size = u32;
334
    // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
335
    type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
336
    // NarrowOriginToSibling calls XcmpQueue's is_pause if Origin is sibling. Allows all other origins
337
    type QueuePausedQuery = (MaintenanceMode, NarrowOriginToSibling<XcmpQueue>);
338
    type HeapSize = sp_core::ConstU32<{ 64 * 1024 }>;
339
    type MaxStale = sp_core::ConstU32<8>;
340
    type ServiceWeight = MessageQueueServiceWeight;
341
    type IdleMaxServiceWeight = MessageQueueServiceWeight;
342
}
343

            
344
parameter_types! {
345
    // we just reuse the same deposits
346
    pub const ForeignAssetsAssetDeposit: Balance = 0;
347
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
348
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
349
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
350
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
351
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
352
    pub CheckingAccount: AccountId = PolkadotXcm::check_account();
353
}
354

            
355
#[cfg(feature = "runtime-benchmarks")]
356
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
357
pub struct ForeignAssetBenchmarkHelper;
358
#[cfg(feature = "runtime-benchmarks")]
359
impl pallet_assets::BenchmarkHelper<AssetId> for ForeignAssetBenchmarkHelper {
360
    fn create_asset_id_parameter(id: u32) -> AssetId {
361
        id.try_into()
362
            .expect("number too large to create benchmarks")
363
    }
364
}
365
#[cfg(feature = "runtime-benchmarks")]
366
impl pallet_asset_rate::AssetKindFactory<AssetId> for ForeignAssetBenchmarkHelper {
367
    fn create_asset_kind(id: u32) -> AssetId {
368
        id.try_into()
369
            .expect("number too large to create benchmarks")
370
    }
371
}
372

            
373
// Instruct how to go from an H160 to an AssetID
374
// We just take the lowest 2 bytes
375
impl AccountIdAssetIdConversion<AccountId, AssetId> for Runtime {
376
    /// The way to convert an account to assetId is by ensuring that the prefix is [0xFF, 18]
377
    /// and by taking the lowest 2 bytes as the assetId
378
    fn account_to_asset_id(account: AccountId) -> Option<(Vec<u8>, AssetId)> {
379
        let h160_account: H160 = account.into();
380
        let mut data = [0u8; 2];
381
        let (prefix_part, id_part) = h160_account.as_fixed_bytes().split_at(18);
382
        if prefix_part == FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX {
383
            data.copy_from_slice(id_part);
384
            let asset_id: AssetId = u16::from_be_bytes(data);
385
            Some((prefix_part.to_vec(), asset_id))
386
        } else {
387
            None
388
        }
389
    }
390

            
391
    // The opposite conversion
392
93
    fn asset_id_to_account(prefix: &[u8], asset_id: AssetId) -> AccountId {
393
93
        let mut data = [0u8; 20];
394
93
        data[0..18].copy_from_slice(prefix);
395
93
        data[18..20].copy_from_slice(&asset_id.to_be_bytes());
396
93
        AccountId::from(data)
397
93
    }
398
}
399

            
400
pub type AssetId = u16;
401
pub type ForeignAssetsInstance = pallet_assets::Instance1;
402
impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
403
    type RuntimeEvent = RuntimeEvent;
404
    type Balance = Balance;
405
    type AssetId = AssetId;
406
    type AssetIdParameter = AssetId;
407
    type Currency = Balances;
408
    type CreateOrigin = frame_support::traits::NeverEnsureOrigin<AccountId>;
409
    type ForceOrigin = EnsureRoot<AccountId>;
410
    type AssetDeposit = ForeignAssetsAssetDeposit;
411
    type MetadataDepositBase = ForeignAssetsMetadataDepositBase;
412
    type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte;
413
    type ApprovalDeposit = ForeignAssetsApprovalDeposit;
414
    type StringLimit = ForeignAssetsAssetsStringLimit;
415
    type Freezer = ();
416
    type Extra = ();
417
    type WeightInfo = weights::pallet_assets::SubstrateWeight<Runtime>;
418
    type CallbackHandle = ();
419
    type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit;
420
    type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
421
    type Holder = ();
422
    #[cfg(feature = "runtime-benchmarks")]
423
    type BenchmarkHelper = ForeignAssetBenchmarkHelper;
424
}
425

            
426
pub struct RevertCodePrecompileHook;
427

            
428
impl ForeignAssetCreatedHook<Location, AssetIdOf<Runtime>, AssetBalance<Runtime>>
429
    for RevertCodePrecompileHook
430
{
431
88
    fn on_asset_created(
432
88
        _foreign_asset: &Location,
433
88
        asset_id: &AssetIdOf<Runtime>,
434
88
        _min_balance: &AssetBalance<Runtime>,
435
88
    ) {
436
88
        let revert_bytecode = [0x60, 0x00, 0x60, 0x00, 0xFD].to_vec();
437
88
        let prefix_slice = [255u8; 18];
438
88
        let account_id = Runtime::asset_id_to_account(prefix_slice.as_slice(), *asset_id);
439

            
440
88
        let _ = pallet_evm::Pallet::<Runtime>::create_account(
441
88
            account_id.into(),
442
88
            revert_bytecode.clone(),
443
88
            None,
444
88
        );
445
88
    }
446
}
447

            
448
impl ForeignAssetDestroyedHook<Location, AssetIdOf<Runtime>> for RevertCodePrecompileHook {
449
    fn on_asset_destroyed(_foreign_asset: &Location, asset_id: &AssetIdOf<Runtime>) {
450
        let prefix_slice = [255u8; 18];
451
        let account_id = Runtime::asset_id_to_account(prefix_slice.as_slice(), *asset_id);
452

            
453
        pallet_evm::Pallet::<Runtime>::remove_account(&account_id.into());
454
    }
455
}
456

            
457
impl pallet_foreign_asset_creator::Config for Runtime {
458
    type ForeignAsset = Location;
459
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
460
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
461
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
462
    type Fungibles = ForeignAssets;
463
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
464
    type OnForeignAssetCreated = RevertCodePrecompileHook;
465
    type OnForeignAssetDestroyed = RevertCodePrecompileHook;
466
}
467

            
468
impl pallet_asset_rate::Config for Runtime {
469
    type CreateOrigin = EnsureRoot<AccountId>;
470
    type RemoveOrigin = EnsureRoot<AccountId>;
471
    type UpdateOrigin = EnsureRoot<AccountId>;
472
    type Currency = Balances;
473
    type AssetKind = AssetId;
474
    type RuntimeEvent = RuntimeEvent;
475
    type WeightInfo = weights::pallet_asset_rate::SubstrateWeight<Runtime>;
476
    #[cfg(feature = "runtime-benchmarks")]
477
    type BenchmarkHelper = ForeignAssetBenchmarkHelper;
478
}
479

            
480
parameter_types! {
481
    pub const TrustPolicyMaxAssets: u32 = 10;
482
    pub const AllNativeTrustPolicy: DefaultTrustPolicy = DefaultTrustPolicy::AllNative;
483
    pub const AllNeverTrustPolicy: DefaultTrustPolicy = DefaultTrustPolicy::Never;
484
}
485
impl pallet_xcm_executor_utils::Config for Runtime {
486
    type TrustPolicyMaxAssets = TrustPolicyMaxAssets;
487
    type ReserveDefaultTrustPolicy = AllNativeTrustPolicy;
488
    type SetReserveTrustOrigin = EnsureRoot<AccountId>;
489
    type TeleportDefaultTrustPolicy = AllNeverTrustPolicy;
490
    type SetTeleportTrustOrigin = EnsureRoot<AccountId>;
491
    type WeightInfo = weights::pallet_xcm_executor_utils::SubstrateWeight<Runtime>;
492
}
493

            
494
use {
495
    crate::ForeignAssets,
496
    xcm_builder::{FungiblesAdapter, NoChecking},
497
    xcm_executor::traits::JustTry,
498
};
499

            
500
/// Means for transacting foreign assets from different global consensus.
501
pub type ForeignFungiblesTransactor = FungiblesAdapter<
502
    // Use this fungibles implementation:
503
    ForeignAssets,
504
    // Use this currency when it is a fungible asset matching the given location or name:
505
    (ConvertedConcreteId<AssetId, Balance, ForeignAssetsCreator, JustTry>,),
506
    // Convert an XCM Location into a local account id:
507
    LocationToAccountId,
508
    // Our chain's account ID type (we can't get away without mentioning it explicitly):
509
    AccountId,
510
    // We dont need to check teleports here.
511
    NoChecking,
512
    // The account to use for tracking teleports.
513
    CheckingAccount,
514
>;
515

            
516
/// Multiplier used for dedicated `TakeFirstAssetTrader` with `ForeignAssets` instance.
517
pub type AssetRateAsMultiplier =
518
    AssetFeeAsExistentialDepositMultiplier<Runtime, WeightToFee, AssetRate, ForeignAssetsInstance>;
519

            
520
#[test]
521
1
fn test_asset_id_to_account_conversion() {
522
1
    let prefix_slice = [255u8].repeat(18);
523
1
    let asset_ids_to_check = vec![0u16, 123u16, 3453u16, 10000u16, 65535u16];
524
6
    for current_asset_id in asset_ids_to_check {
525
5
        let account_id = Runtime::asset_id_to_account(prefix_slice.as_slice(), current_asset_id);
526
5
        assert_eq!(
527
5
            account_id.to_string().to_lowercase(),
528
5
            String::from("0xffffffffffffffffffffffffffffffffffff")
529
5
                + format!("{:04x}", current_asset_id).as_str()
530
        );
531
    }
532
1
}