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, SnowbridgeFeesAccount},
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
    tanssi_runtime_common::relay::ExporterFeeHandler,
48
    tp_bridge::{
49
        container_token_to_ethereum_message_exporter::ContainerEthereumBlobExporter,
50
        snowbridge_outbound_token_transfer::{EthereumBlobExporter, SnowbrigeTokenTransferRouter},
51
        snowbridge_outbound_token_transfer_v2::EthereumBlobExporterV2,
52
        EthereumLocationsConverterFor,
53
    },
54
    tp_xcm_commons::{EthereumAssetReserve, NativeAssetReserve},
55
    xcm::{
56
        latest::prelude::{AssetId as XcmAssetId, *},
57
        opaque::latest::WESTEND_GENESIS_HASH,
58
    },
59
    xcm_builder::{
60
        AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
61
        AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
62
        ChildParachainConvertsVia, ConvertedConcreteId, DescribeAllTerminal, DescribeFamily,
63
        FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter,
64
        HashedDescription, IsChildSystemParachain, IsConcrete, MintLocation, NoChecking,
65
        OriginToPluralityVoice, SendXcmFeeToAccount, SignedAccountId32AsNative,
66
        SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
67
        UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
68
        XcmFeeManagerFromComponents,
69
    },
70
    xcm_executor::XcmExecutor,
71
};
72

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

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

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

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

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

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

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

            
153
pub type PriceForChildParachainDelivery =
154
    ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, Dmp>;
155

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

            
167
parameter_types! {
168
    pub AssetHub: Location = Parachain(ASSET_HUB_ID).into_location();
169
    pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH);
170
    pub const MaxInstructions: u32 = 100;
171
    pub const MaxAssetsIntoHolding: u32 = 64;
172
}
173

            
174
pub struct OnlyParachains;
175
impl Contains<Location> for OnlyParachains {
176
    fn contains(loc: &Location) -> bool {
177
        matches!(loc.unpack(), (0, [Parachain(_)]))
178
    }
179
}
180

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

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

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

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

            
254
parameter_types! {
255
    pub const CollectiveBodyId: BodyId = BodyId::Unit;
256
    // StakingAdmin pluralistic body.
257
    pub const StakingAdminBodyId: BodyId = BodyId::Defense;
258
    // Fellows pluralistic body.
259
    pub const FellowsBodyId: BodyId = BodyId::Technical;
260
}
261

            
262
/// Type to convert an `Origin` type value into a `Location` value which represents an interior
263
/// location of this chain.
264
pub type LocalOriginToLocation = (
265
    // And a usual Signed origin to be used in XCM as a corresponding AccountId32
266
    SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
267
);
268

            
269
/// Type to convert the `StakingAdmin` origin to a Plurality `Location` value.
270
pub type StakingAdminToPlurality =
271
    OriginToPluralityVoice<RuntimeOrigin, StakingAdmin, StakingAdminBodyId>;
272

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

            
276
/// Type to convert a pallet `Origin` type value into a `Location` value which represents an
277
/// interior location of this chain for a destination chain.
278
pub type LocalPalletOriginToLocation = (
279
    // StakingAdmin origin to be used in XCM as a corresponding Plurality `Location` value.
280
    StakingAdminToPlurality,
281
    // Fellows origin to be used in XCM as a corresponding Plurality `Location` value.
282
    FellowsToPlurality,
283
);
284

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

            
317
parameter_types! {
318
    // TODO: revisit these values in the future
319
    pub const ForeignAssetsAssetDeposit: Balance = 0;
320
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
321
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
322
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
323
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
324
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
325
    pub CheckingAccount: AccountId = XcmPallet::check_account();
326
}
327

            
328
#[cfg(feature = "runtime-benchmarks")]
329
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
330
pub struct ForeignAssetBenchmarkHelper;
331
#[cfg(feature = "runtime-benchmarks")]
332
impl pallet_assets::BenchmarkHelper<AssetId> for ForeignAssetBenchmarkHelper {
333
    fn create_asset_id_parameter(id: u32) -> AssetId {
334
        id.try_into()
335
            .expect("number too large to create benchmarks")
336
    }
337
}
338

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

            
365
impl pallet_foreign_asset_creator::Config for Runtime {
366
    type ForeignAsset = Location;
367
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
368
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
369
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
370
    type Fungibles = ForeignAssets;
371
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
372
    type OnForeignAssetCreated = ();
373
    type OnForeignAssetDestroyed = ();
374
}
375

            
376
parameter_types! {
377
    pub SnowbridgeChannelInfo: Option<(ChannelId, AgentId)> =
378
        pallet_ethereum_token_transfers::CurrentChannelInfo::<Runtime>::get()
379
64
            .map(|x| (x.channel_id, x.agent_id));
380

            
381
    pub const MinV2Reward: u128 = 1u128;
382
    pub MinSnowbridgeV2Reward: Asset = (TokenLocation::get(), MinV2Reward::get()).into();
383
}
384

            
385
/// Exports message to the Ethereum Gateway contract.
386
pub type SnowbridgeExporter = EthereumBlobExporter<
387
    UniversalLocation,
388
    EthereumNetwork,
389
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
390
    EthereumSystem,
391
    SnowbridgeChannelInfo,
392
>;
393

            
394
/// Exports message to the Ethereum Gateway contract.
395
pub type SnowbridgeExporterv2 = EthereumBlobExporterV2<
396
    UniversalLocation,
397
    EthereumNetwork,
398
    snowbridge_pallet_outbound_queue_v2::Pallet<Runtime>,
399
    EthereumSystem,
400
    MinSnowbridgeV2Reward,
401
    SendXcmFeeToAccount<LocalAssetTransactor, SnowbridgeFeesAccount>,
402
>;
403

            
404
/// Exports message to the Ethereum Gateway contract.
405
pub type ContainerToSnowbridgeMessageExporter = ContainerEthereumBlobExporter<
406
    UniversalLocation,
407
    EthereumNetwork,
408
    EthereumLocation,
409
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
410
    EthereumSystem,
411
    SnowbridgeChannelInfo,
412
>;
413

            
414
/// Exports message to the Ethereum Gateway contract.
415
/// TODO:CHANGE
416
pub type ContainerToSnowbridgeMessageExporterV2 = ContainerEthereumBlobExporter<
417
    UniversalLocation,
418
    EthereumNetwork,
419
    EthereumLocation,
420
    snowbridge_pallet_outbound_queue_v2::Pallet<Runtime>,
421
    EthereumSystem,
422
    SnowbridgeChannelInfo,
423
>;