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
//! XCM configuration for Dancelight.
18

            
19
use {
20
    super::{
21
        parachains_origin,
22
        weights::{self, xcm::XcmWeight},
23
        AccountId, AllPalletsWithSystem, Balance, Balances, Dmp, Fellows, ForeignAssets,
24
        ForeignAssetsCreator, ParaId, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
25
        TransactionByteFee, Treasury, WeightToFee, XcmPallet,
26
    },
27
    crate::governance::StakingAdmin,
28
    dancelight_runtime_constants::{
29
        currency::CENTS,
30
        snowbridge::{EthereumLocation, EthereumNetwork},
31
        system_parachain::*,
32
        DANCELIGHT_GENESIS_HASH,
33
    },
34
    frame_support::{
35
        parameter_types,
36
        traits::{Contains, Disabled, Equals, Everything, Nothing},
37
        weights::Weight,
38
    },
39
    frame_system::EnsureRoot,
40
    runtime_common::{
41
        xcm_sender::{ChildParachainRouter, ExponentialPrice},
42
        ToAuthor,
43
    },
44
    sp_core::ConstU32,
45
    sp_runtime::traits::TryConvertInto,
46
    tp_bridge::EthereumLocationsConverterFor,
47
    tp_xcm_commons::{EthereumAssetReserve, NativeAssetReserve},
48
    xcm::{
49
        latest::prelude::{AssetId as XcmAssetId, *},
50
        opaque::latest::WESTEND_GENESIS_HASH,
51
    },
52
    xcm_builder::{
53
        AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
54
        AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
55
        ChildParachainConvertsVia, ConvertedConcreteId, DescribeAllTerminal, DescribeFamily,
56
        FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter,
57
        HashedDescription, IsChildSystemParachain, IsConcrete, MintLocation, NoChecking,
58
        OriginToPluralityVoice, SendXcmFeeToAccount, SignedAccountId32AsNative,
59
        SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
60
        UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
61
        XcmFeeManagerFromComponents,
62
    },
63
    xcm_executor::XcmExecutor,
64
};
65

            
66
parameter_types! {
67
    pub TokenLocation: Location = Here.into_location();
68
    pub RootLocation: Location = Location::here();
69
    pub const ThisNetwork: NetworkId = NetworkId::ByGenesis(DANCELIGHT_GENESIS_HASH);
70
    pub UniversalLocation: InteriorLocation = ThisNetwork::get().into();
71
    pub CheckAccount: AccountId = XcmPallet::check_account();
72
    pub LocalCheckAccount: (AccountId, MintLocation) = (CheckAccount::get(), MintLocation::Local);
73
    pub TreasuryAccount: AccountId = Treasury::account_id();
74
}
75

            
76
#[cfg(feature = "runtime-benchmarks")]
77
parameter_types! {
78
    // Universal location for benchmarks that need to run through a para-id scenario
79
    pub UniversalLocationForParaIdBenchmarks: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(2000u32)].into();
80
}
81

            
82
pub type LocationConverter = (
83
    // We can convert a child parachain using the standard `AccountId` conversion.
84
    ChildParachainConvertsVia<ParaId, AccountId>,
85
    // We can directly alias an `AccountId32` into a local account.
86
    AccountId32Aliases<ThisNetwork, AccountId>,
87
    // Foreign locations alias into accounts according to a hash of their standard description.
88
    HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
89
    // Ethereum contract sovereign account.
90
    // (Used to convert ethereum contract locations to sovereign account)
91
    EthereumLocationsConverterFor<AccountId>,
92
);
93

            
94
/// Our asset transactor. This is what allows us to interest with the runtime facilities from the
95
/// point of view of XCM-only concepts like `Location` and `Asset`.
96
///
97
/// Ours is only aware of the Balances pallet, which is mapped to `StarLocation`.
98
pub type LocalAssetTransactor = FungibleAdapter<
99
    // Use this currency:
100
    Balances,
101
    // Use this currency when it is a fungible asset matching the given location or name:
102
    IsConcrete<TokenLocation>,
103
    // We can convert the Locations with our converter above:
104
    LocationConverter,
105
    // Our chain's account ID type (we can't get away without mentioning it explicitly):
106
    AccountId,
107
    // We track our teleports in/out to keep total issuance correct.
108
    LocalCheckAccount,
109
>;
110

            
111
/// Means for transacting foreign assets from different global consensus.
112
pub type ForeignFungiblesTransactor = FungiblesAdapter<
113
    // Use this fungibles implementation:
114
    ForeignAssets,
115
    // Use this currency when it is a fungible asset matching the given location or name:
116
    (ConvertedConcreteId<AssetId, Balance, ForeignAssetsCreator, TryConvertInto>,),
117
    // Convert an XCM Location into a local account id:
118
    LocationConverter,
119
    // Our chain's account ID type (we can't get away without mentioning it explicitly):
120
    AccountId,
121
    // We dont need to check teleports here.
122
    NoChecking,
123
    // The account to use for tracking teleports.
124
    CheckingAccount,
125
>;
126

            
127
/// The means that we convert an the XCM message origin location into a local dispatch origin.
128
type LocalOriginConverter = (
129
    // A `Signed` origin of the sovereign account that the original location controls.
130
    SovereignSignedViaLocation<LocationConverter, RuntimeOrigin>,
131
    // A child parachain, natively expressed, has the `Parachain` origin.
132
    ChildParachainAsNative<parachains_origin::Origin, RuntimeOrigin>,
133
    // The AccountId32 location type can be expressed natively as a `Signed` origin.
134
    SignedAccountId32AsNative<ThisNetwork, RuntimeOrigin>,
135
);
136

            
137
parameter_types! {
138
    /// The amount of weight an XCM operation takes. This is a safe overestimate.
139
    pub const BaseXcmWeight: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
140
    /// The asset ID for the asset that we use to pay for message delivery fees.
141
    pub FeeAssetId: XcmAssetId = XcmAssetId(TokenLocation::get());
142
    /// The base fee for the message delivery fees.
143
    pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
144
}
145

            
146
pub type PriceForChildParachainDelivery =
147
    ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, Dmp>;
148

            
149
/// The XCM router. When we want to send an XCM message, we use this type. It amalgamates all of our
150
/// individual routers.
151
pub type XcmRouter = WithUniqueTopic<
152
    // Only one router so far - use DMP to communicate with child parachains.
153
    ChildParachainRouter<Runtime, XcmPallet, PriceForChildParachainDelivery>,
154
>;
155

            
156
parameter_types! {
157
    pub Star: AssetFilter = Wild(AllOf { fun: WildFungible, id: XcmAssetId(TokenLocation::get()) });
158
    pub AssetHub: Location = Parachain(ASSET_HUB_ID).into_location();
159
    pub Contracts: Location = Parachain(CONTRACTS_ID).into_location();
160
    pub Encointer: Location = Parachain(ENCOINTER_ID).into_location();
161
    pub BridgeHub: Location = Parachain(BRIDGE_HUB_ID).into_location();
162
    pub People: Location = Parachain(PEOPLE_ID).into_location();
163
    pub Broker: Location = Parachain(BROKER_ID).into_location();
164
    pub Tick: Location = Parachain(100).into_location();
165
    pub Trick: Location = Parachain(110).into_location();
166
    pub Track: Location = Parachain(120).into_location();
167
    pub StarForTick: (AssetFilter, Location) = (Star::get(), Tick::get());
168
    pub StarForTrick: (AssetFilter, Location) = (Star::get(), Trick::get());
169
    pub StarForTrack: (AssetFilter, Location) = (Star::get(), Track::get());
170
    pub StarForAssetHub: (AssetFilter, Location) = (Star::get(), AssetHub::get());
171
    pub StarForContracts: (AssetFilter, Location) = (Star::get(), Contracts::get());
172
    pub StarForEncointer: (AssetFilter, Location) = (Star::get(), Encointer::get());
173
    pub StarForBridgeHub: (AssetFilter, Location) = (Star::get(), BridgeHub::get());
174
    pub StarForPeople: (AssetFilter, Location) = (Star::get(), People::get());
175
    pub StarForBroker: (AssetFilter, Location) = (Star::get(), Broker::get());
176
    pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH);
177
    pub const MaxInstructions: u32 = 100;
178
    pub const MaxAssetsIntoHolding: u32 = 64;
179
}
180

            
181
pub struct OnlyParachains;
182
impl Contains<Location> for OnlyParachains {
183
    fn contains(loc: &Location) -> bool {
184
        matches!(loc.unpack(), (0, [Parachain(_)]))
185
    }
186
}
187

            
188
pub struct LocalPlurality;
189
impl Contains<Location> for LocalPlurality {
190
    fn contains(loc: &Location) -> bool {
191
        matches!(loc.unpack(), (0, [Plurality { .. }]))
192
    }
193
}
194

            
195
/// The barriers one of which must be passed for an XCM message to be executed.
196
pub type Barrier = TrailingSetTopicAsId<(
197
    // Weight that is paid for may be consumed.
198
    TakeWeightCredit,
199
    // Expected responses are OK.
200
    AllowKnownQueryResponses<XcmPallet>,
201
    WithComputedOrigin<
202
        (
203
            // If the message is one that immediately attempts to pay for execution, then allow it.
204
            AllowTopLevelPaidExecutionFrom<Everything>,
205
            // Messages coming from system parachains need not pay for execution.
206
            AllowExplicitUnpaidExecutionFrom<IsChildSystemParachain<ParaId>>,
207
            // Subscriptions for version tracking are OK.
208
            AllowSubscriptionsFrom<OnlyParachains>,
209
        ),
210
        UniversalLocation,
211
        ConstU32<8>,
212
    >,
213
)>;
214

            
215
/// Locations that will not be charged fees in the executor, neither for execution nor delivery.
216
/// We only waive fees for system functions, which these locations represent.
217
pub type WaivedLocations = Equals<RootLocation>;
218
pub type XcmWeigher = WeightInfoBounds<XcmWeight<RuntimeCall>, RuntimeCall, MaxInstructions>;
219

            
220
pub struct XcmConfig;
221
impl xcm_executor::Config for XcmConfig {
222
    type RuntimeCall = RuntimeCall;
223
    type XcmSender = XcmRouter;
224
    type AssetTransactor = (LocalAssetTransactor, ForeignFungiblesTransactor);
225
    type OriginConverter = LocalOriginConverter;
226
    type IsReserve = (
227
        NativeAssetReserve,
228
        EthereumAssetReserve<EthereumLocation, EthereumNetwork>,
229
    );
230
    type IsTeleporter = ();
231
    type UniversalLocation = UniversalLocation;
232
    type Barrier = Barrier;
233
    type Weigher = XcmWeigher;
234
    type Trader =
235
        UsingComponents<WeightToFee, TokenLocation, AccountId, Balances, ToAuthor<Runtime>>;
236
    type ResponseHandler = XcmPallet;
237
    type AssetTrap = XcmPallet;
238
    type AssetLocker = ();
239
    type AssetExchanger = ();
240
    type AssetClaims = XcmPallet;
241
    type SubscriptionService = XcmPallet;
242
    type PalletInstancesInfo = AllPalletsWithSystem;
243
    type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
244
    type FeeManager = XcmFeeManagerFromComponents<
245
        WaivedLocations,
246
        SendXcmFeeToAccount<Self::AssetTransactor, TreasuryAccount>,
247
    >;
248
    type MessageExporter = ();
249
    type UniversalAliases = Nothing;
250
    type CallDispatcher = RuntimeCall;
251
    type SafeCallFilter = Everything;
252
    type Aliasers = Nothing;
253
    type TransactionalProcessor = FrameTransactionalProcessor;
254
    type HrmpNewChannelOpenRequestHandler = ();
255
    type HrmpChannelAcceptedHandler = ();
256
    type HrmpChannelClosingHandler = ();
257
    type XcmRecorder = ();
258
    type XcmEventEmitter = XcmPallet;
259
}
260

            
261
parameter_types! {
262
    pub const CollectiveBodyId: BodyId = BodyId::Unit;
263
    // StakingAdmin pluralistic body.
264
    pub const StakingAdminBodyId: BodyId = BodyId::Defense;
265
    // Fellows pluralistic body.
266
    pub const FellowsBodyId: BodyId = BodyId::Technical;
267
}
268

            
269
/// Type to convert an `Origin` type value into a `Location` value which represents an interior
270
/// location of this chain.
271
pub type LocalOriginToLocation = (
272
    // And a usual Signed origin to be used in XCM as a corresponding AccountId32
273
    SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
274
);
275

            
276
/// Type to convert the `StakingAdmin` origin to a Plurality `Location` value.
277
pub type StakingAdminToPlurality =
278
    OriginToPluralityVoice<RuntimeOrigin, StakingAdmin, StakingAdminBodyId>;
279

            
280
/// Type to convert the Fellows origin to a Plurality `Location` value.
281
pub type FellowsToPlurality = OriginToPluralityVoice<RuntimeOrigin, Fellows, FellowsBodyId>;
282

            
283
/// Type to convert a pallet `Origin` type value into a `Location` value which represents an
284
/// interior location of this chain for a destination chain.
285
pub type LocalPalletOriginToLocation = (
286
    // StakingAdmin origin to be used in XCM as a corresponding Plurality `Location` value.
287
    StakingAdminToPlurality,
288
    // Fellows origin to be used in XCM as a corresponding Plurality `Location` value.
289
    FellowsToPlurality,
290
);
291

            
292
impl pallet_xcm::Config for Runtime {
293
    type RuntimeEvent = RuntimeEvent;
294
    // Note that this configuration of `SendXcmOrigin` is different from the one present in
295
    // production.
296
    type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
297
    type XcmRouter = XcmRouter;
298
    // Anyone can execute XCM messages locally.
299
    type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
300
    type XcmExecuteFilter = Everything;
301
    type XcmExecutor = XcmExecutor<XcmConfig>;
302
    type XcmTeleportFilter = Nothing;
303
    // Anyone is able to use reserve transfers regardless of who they are and what they want to
304
    // transfer.
305
    type XcmReserveTransferFilter = Everything;
306
    type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
307
    type UniversalLocation = UniversalLocation;
308
    type RuntimeOrigin = RuntimeOrigin;
309
    type RuntimeCall = RuntimeCall;
310
    const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
311
    type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
312
    type Currency = Balances;
313
    type CurrencyMatcher = IsConcrete<TokenLocation>;
314
    type TrustedLockers = ();
315
    type SovereignAccountOf = LocationConverter;
316
    type MaxLockers = ConstU32<8>;
317
    type MaxRemoteLockConsumers = ConstU32<0>;
318
    type RemoteLockConsumerIdentifier = ();
319
    type WeightInfo = weights::pallet_xcm::SubstrateWeight<Runtime>;
320
    type AdminOrigin = EnsureRoot<AccountId>;
321
    type AuthorizedAliasConsideration = Disabled;
322
}
323

            
324
parameter_types! {
325
    // TODO: revisit these values in the future
326
    pub const ForeignAssetsAssetDeposit: Balance = 0;
327
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
328
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
329
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
330
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
331
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
332
    pub CheckingAccount: AccountId = XcmPallet::check_account();
333
}
334

            
335
#[cfg(feature = "runtime-benchmarks")]
336
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
337
pub struct ForeignAssetBenchmarkHelper;
338
#[cfg(feature = "runtime-benchmarks")]
339
impl pallet_assets::BenchmarkHelper<AssetId> for ForeignAssetBenchmarkHelper {
340
    fn create_asset_id_parameter(id: u32) -> AssetId {
341
        id.try_into()
342
            .expect("number too large to create benchmarks")
343
    }
344
}
345

            
346
pub type AssetId = u16;
347
pub type ForeignAssetsInstance = pallet_assets::Instance1;
348
impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
349
    type RuntimeEvent = RuntimeEvent;
350
    type Balance = Balance;
351
    type AssetId = AssetId;
352
    type AssetIdParameter = AssetId;
353
    type Currency = Balances;
354
    type CreateOrigin = frame_support::traits::NeverEnsureOrigin<AccountId>;
355
    type ForceOrigin = EnsureRoot<AccountId>;
356
    type AssetDeposit = ForeignAssetsAssetDeposit;
357
    type MetadataDepositBase = ForeignAssetsMetadataDepositBase;
358
    type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte;
359
    type ApprovalDeposit = ForeignAssetsApprovalDeposit;
360
    type StringLimit = ForeignAssetsAssetsStringLimit;
361
    type Freezer = ();
362
    type Extra = ();
363
    type WeightInfo = weights::pallet_assets::SubstrateWeight<Runtime>;
364
    type CallbackHandle = ();
365
    type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit;
366
    type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
367
    type Holder = ();
368
    #[cfg(feature = "runtime-benchmarks")]
369
    type BenchmarkHelper = ForeignAssetBenchmarkHelper;
370
}
371

            
372
impl pallet_foreign_asset_creator::Config for Runtime {
373
    type RuntimeEvent = RuntimeEvent;
374
    type ForeignAsset = Location;
375
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
376
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
377
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
378
    type Fungibles = ForeignAssets;
379
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
380
    type OnForeignAssetCreated = ();
381
    type OnForeignAssetDestroyed = ();
382
}