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, ForeignAssets,
24
        ForeignAssetsCreator, ParaId, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
25
        TransactionByteFee, Treasury, WeightToFee, XcmPallet,
26
    },
27
    crate::{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
        container_token_to_ethereum_message_exporter_v2::ContainerEthereumBlobExporterV2,
51
        snowbridge_outbound_token_transfer::{EthereumBlobExporter, SnowbrigeTokenTransferRouter},
52
        snowbridge_outbound_token_transfer_v2::EthereumBlobExporterV2,
53
        EthereumLocationsConverterFor,
54
    },
55
    tp_xcm_commons::{EthereumAssetReserve, NativeAssetReserve},
56
    xcm::{
57
        latest::prelude::{AssetId as XcmAssetId, *},
58
        opaque::latest::WESTEND_GENESIS_HASH,
59
    },
60
    xcm_builder::{
61
        AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
62
        AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
63
        ChildParachainConvertsVia, ConvertedConcreteId, DescribeAllTerminal, DescribeFamily,
64
        FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter,
65
        HashedDescription, IsChildSystemParachain, IsConcrete, MintLocation, NoChecking,
66
        SendXcmFeeToAccount, SignedAccountId32AsNative, SignedToAccountId32,
67
        SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents,
68
        WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, 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
    // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
143
    pallet_xcm::XcmPassthrough<RuntimeOrigin>,
144
);
145

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

            
155
pub type PriceForChildParachainDelivery =
156
    ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, Dmp>;
157

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

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

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

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

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

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

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

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

            
266
impl pallet_xcm::Config for Runtime {
267
    type RuntimeEvent = RuntimeEvent;
268
    // Note that this configuration of `SendXcmOrigin` is different from the one present in
269
    // production.
270
    type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
271
    type XcmRouter = XcmRouter;
272
    // Anyone can execute XCM messages locally.
273
    type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
274
    type XcmExecuteFilter = Everything;
275
    type XcmExecutor = XcmExecutor<XcmConfig>;
276
    type XcmTeleportFilter = Nothing;
277
    // Anyone is able to use reserve transfers regardless of who they are and what they want to
278
    // transfer.
279
    type XcmReserveTransferFilter = Everything;
280
    type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
281
    type UniversalLocation = UniversalLocation;
282
    type RuntimeOrigin = RuntimeOrigin;
283
    type RuntimeCall = RuntimeCall;
284
    const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
285
    type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
286
    type Currency = Balances;
287
    type CurrencyMatcher = IsConcrete<TokenLocation>;
288
    type TrustedLockers = ();
289
    type SovereignAccountOf = LocationConverter;
290
    type MaxLockers = ConstU32<8>;
291
    type MaxRemoteLockConsumers = ConstU32<0>;
292
    type RemoteLockConsumerIdentifier = ();
293
    type WeightInfo = weights::pallet_xcm::SubstrateWeight<Runtime>;
294
    type AdminOrigin = EnsureRoot<AccountId>;
295
    type AuthorizedAliasConsideration = Disabled;
296
}
297

            
298
parameter_types! {
299
    // TODO: revisit these values in the future
300
    pub const ForeignAssetsAssetDeposit: Balance = 0;
301
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
302
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
303
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
304
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
305
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
306
    pub CheckingAccount: AccountId = XcmPallet::check_account();
307
}
308

            
309
#[cfg(feature = "runtime-benchmarks")]
310
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
311
pub struct ForeignAssetBenchmarkHelper;
312
#[cfg(feature = "runtime-benchmarks")]
313
impl pallet_assets::BenchmarkHelper<AssetId> for ForeignAssetBenchmarkHelper {
314
    fn create_asset_id_parameter(id: u32) -> AssetId {
315
        id.try_into()
316
            .expect("number too large to create benchmarks")
317
    }
318
}
319

            
320
pub type AssetId = u16;
321
pub type ForeignAssetsInstance = pallet_assets::Instance1;
322
impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
323
    type RuntimeEvent = RuntimeEvent;
324
    type Balance = Balance;
325
    type AssetId = AssetId;
326
    type AssetIdParameter = AssetId;
327
    type Currency = Balances;
328
    type CreateOrigin = frame_support::traits::NeverEnsureOrigin<AccountId>;
329
    type ForceOrigin = EnsureRoot<AccountId>;
330
    type AssetDeposit = ForeignAssetsAssetDeposit;
331
    type MetadataDepositBase = ForeignAssetsMetadataDepositBase;
332
    type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte;
333
    type ApprovalDeposit = ForeignAssetsApprovalDeposit;
334
    type StringLimit = ForeignAssetsAssetsStringLimit;
335
    type Freezer = ();
336
    type Extra = ();
337
    type WeightInfo = weights::pallet_assets::SubstrateWeight<Runtime>;
338
    type CallbackHandle = ();
339
    type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit;
340
    type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
341
    type Holder = ();
342
    #[cfg(feature = "runtime-benchmarks")]
343
    type BenchmarkHelper = ForeignAssetBenchmarkHelper;
344
}
345

            
346
impl pallet_foreign_asset_creator::Config for Runtime {
347
    type ForeignAsset = Location;
348
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
349
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
350
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
351
    type Fungibles = ForeignAssets;
352
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
353
    type OnForeignAssetCreated = ();
354
    type OnForeignAssetDestroyed = ();
355
}
356

            
357
parameter_types! {
358
    /// LayerZero hub contract address on Ethereum (placeholder - to be configured)
359
    pub const LayerZeroHubAddress: sp_core::H160 = sp_core::H160([0u8; 20]);
360
    /// Minimum reward for outbound LayerZero messages
361
    pub const MinLzOutboundReward: u128 = 1;
362
}
363

            
364
impl pallet_lz_router::Config for Runtime {
365
    type MaxWhitelistedSenders = ConstU32<100>;
366
    type ContainerChainOrigin = pallet_xcm::EnsureXcm<OnlyParachains>;
367
    type OutboundQueueV2 = crate::EthereumOutboundQueueV2;
368
    type LayerZeroHubAddress = LayerZeroHubAddress;
369
    type MinOutboundReward = MinLzOutboundReward;
370
    type LocationHashOf = tp_bridge::TanssiAgentIdOf;
371
    type EthereumLocation = EthereumLocation;
372
    type UniversalLocation = UniversalLocation;
373
    type Currency = Balances;
374
    type FeesAccount = SnowbridgeFeesAccount;
375
    type LocationToAccountId = LocationConverter;
376
}
377

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

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

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

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

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

            
416
/// Exports message to the Ethereum Gateway contract using Snowbridge V2.
417
pub type ContainerToSnowbridgeMessageExporterV2 = ContainerEthereumBlobExporterV2<
418
    UniversalLocation,
419
    EthereumNetwork,
420
    EthereumLocation,
421
    snowbridge_pallet_outbound_queue_v2::Pallet<Runtime>,
422
    EthereumSystem,
423
    MinSnowbridgeV2Reward,
424
>;