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, EthereumSystem},
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
    snowbridge_core::{AgentId, ChannelId},
45
    sp_core::ConstU32,
46
    sp_runtime::traits::TryConvertInto,
47
    tp_bridge::{
48
        snowbridge_outbound_token_transfer::{EthereumBlobExporter, SnowbrigeTokenTransferRouter},
49
        EthereumLocationsConverterFor,
50
    },
51
    tp_xcm_commons::{EthereumAssetReserve, NativeAssetReserve},
52
    xcm::{
53
        latest::prelude::{AssetId as XcmAssetId, *},
54
        opaque::latest::WESTEND_GENESIS_HASH,
55
    },
56
    xcm_builder::{
57
        AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
58
        AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
59
        ChildParachainConvertsVia, ConvertedConcreteId, DescribeAllTerminal, DescribeFamily,
60
        FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter,
61
        HashedDescription, IsChildSystemParachain, IsConcrete, MintLocation, NoChecking,
62
        OriginToPluralityVoice, SendXcmFeeToAccount, SignedAccountId32AsNative,
63
        SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
64
        UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
65
        XcmFeeManagerFromComponents,
66
    },
67
    xcm_executor::XcmExecutor,
68
};
69

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

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

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

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

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

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

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

            
150
pub type PriceForChildParachainDelivery =
151
    ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, Dmp>;
152

            
153
/// The XCM router. When we want to send an XCM message, we use this type. It amalgamates all of our
154
/// individual routers.
155
pub type XcmRouter = WithUniqueTopic<(
156
    // Use DMP to communicate with child parachains.
157
    ChildParachainRouter<Runtime, XcmPallet, PriceForChildParachainDelivery>,
158
    // Send Ethereum-native tokens back to Ethereum.
159
    SnowbrigeTokenTransferRouter<SnowbridgeExporter, UniversalLocation>,
160
)>;
161

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

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

            
194
pub struct LocalPlurality;
195
impl Contains<Location> for LocalPlurality {
196
    fn contains(loc: &Location) -> bool {
197
        matches!(loc.unpack(), (0, [Plurality { .. }]))
198
    }
199
}
200

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

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

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

            
267
parameter_types! {
268
    pub const CollectiveBodyId: BodyId = BodyId::Unit;
269
    // StakingAdmin pluralistic body.
270
    pub const StakingAdminBodyId: BodyId = BodyId::Defense;
271
    // Fellows pluralistic body.
272
    pub const FellowsBodyId: BodyId = BodyId::Technical;
273
}
274

            
275
/// Type to convert an `Origin` type value into a `Location` value which represents an interior
276
/// location of this chain.
277
pub type LocalOriginToLocation = (
278
    // And a usual Signed origin to be used in XCM as a corresponding AccountId32
279
    SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
280
);
281

            
282
/// Type to convert the `StakingAdmin` origin to a Plurality `Location` value.
283
pub type StakingAdminToPlurality =
284
    OriginToPluralityVoice<RuntimeOrigin, StakingAdmin, StakingAdminBodyId>;
285

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

            
289
/// Type to convert a pallet `Origin` type value into a `Location` value which represents an
290
/// interior location of this chain for a destination chain.
291
pub type LocalPalletOriginToLocation = (
292
    // StakingAdmin origin to be used in XCM as a corresponding Plurality `Location` value.
293
    StakingAdminToPlurality,
294
    // Fellows origin to be used in XCM as a corresponding Plurality `Location` value.
295
    FellowsToPlurality,
296
);
297

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

            
330
parameter_types! {
331
    // TODO: revisit these values in the future
332
    pub const ForeignAssetsAssetDeposit: Balance = 0;
333
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
334
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
335
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
336
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
337
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
338
    pub CheckingAccount: AccountId = XcmPallet::check_account();
339
}
340

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

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

            
378
impl pallet_foreign_asset_creator::Config for Runtime {
379
    type RuntimeEvent = RuntimeEvent;
380
    type ForeignAsset = Location;
381
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
382
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
383
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
384
    type Fungibles = ForeignAssets;
385
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
386
    type OnForeignAssetCreated = ();
387
    type OnForeignAssetDestroyed = ();
388
}
389

            
390
parameter_types! {
391
    pub SnowbridgeChannelInfo: Option<(ChannelId, AgentId)> =
392
        pallet_ethereum_token_transfers::CurrentChannelInfo::<Runtime>::get()
393
4
            .map(|x| (x.channel_id, x.agent_id));
394
}
395

            
396
/// Exports message to the Ethereum Gateway contract.
397
pub type SnowbridgeExporter = EthereumBlobExporter<
398
    UniversalLocation,
399
    EthereumNetwork,
400
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
401
    EthereumSystem,
402
    SnowbridgeChannelInfo,
403
>;