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::{
56
        EthereumAssetReserve, EthereumAssetReserveForContainerAssets, NativeAssetReserve,
57
    },
58
    xcm::{
59
        latest::prelude::{AssetId as XcmAssetId, *},
60
        opaque::latest::WESTEND_GENESIS_HASH,
61
    },
62
    xcm_builder::{
63
        AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
64
        AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
65
        ChildParachainConvertsVia, ConvertedConcreteId, DescribeAllTerminal, DescribeFamily,
66
        FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter,
67
        HashedDescription, IsChildSystemParachain, IsConcrete, MintLocation, NoChecking,
68
        SendXcmFeeToAccount, SignedAccountId32AsNative, SignedToAccountId32,
69
        SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents,
70
        WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents,
71
    },
72
    xcm_executor::XcmExecutor,
73
};
74

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

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

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

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

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

            
136
/// The means that we convert an the XCM message origin location into a local dispatch origin.
137
type LocalOriginConverter = (
138
    // A `Signed` origin of the sovereign account that the original location controls.
139
    SovereignSignedViaLocation<LocationConverter, RuntimeOrigin>,
140
    // A child parachain, natively expressed, has the `Parachain` origin.
141
    ChildParachainAsNative<parachains_origin::Origin, RuntimeOrigin>,
142
    // The AccountId32 location type can be expressed natively as a `Signed` origin.
143
    SignedAccountId32AsNative<ThisNetwork, 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
        EthereumAssetReserveForContainerAssets<EthereumLocation>,
225
    );
226
    type IsTeleporter = ();
227
    type UniversalLocation = UniversalLocation;
228
    type Barrier = Barrier;
229
    type Weigher = XcmWeigher;
230
    type Trader =
231
        UsingComponents<WeightToFee, TokenLocation, AccountId, Balances, ToAuthor<Runtime>>;
232
    type ResponseHandler = XcmPallet;
233
    type AssetTrap = XcmPallet;
234
    type AssetLocker = ();
235
    type AssetExchanger = ();
236
    type AssetClaims = XcmPallet;
237
    type SubscriptionService = XcmPallet;
238
    type PalletInstancesInfo = AllPalletsWithSystem;
239
    type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
240
    type FeeManager = XcmFeeManagerFromComponents<
241
        WaivedLocations,
242
        ExporterFeeHandler<Self::AssetTransactor, SnowbridgeFeesAccount, TreasuryAccount>,
243
    >;
244
    type MessageExporter = (
245
        ContainerToSnowbridgeMessageExporterV2,
246
        ContainerToSnowbridgeMessageExporter,
247
    );
248
    type UniversalAliases = Nothing;
249
    type CallDispatcher = RuntimeCall;
250
    type SafeCallFilter = Everything;
251
    type Aliasers = Nothing;
252
    type TransactionalProcessor = FrameTransactionalProcessor;
253
    type HrmpNewChannelOpenRequestHandler = ();
254
    type HrmpChannelAcceptedHandler = ();
255
    type HrmpChannelClosingHandler = ();
256
    type XcmRecorder = ();
257
    type XcmEventEmitter = XcmPallet;
258
}
259

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

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

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

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

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

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

            
358
parameter_types! {
359
    pub SnowbridgeChannelInfo: Option<(ChannelId, AgentId)> =
360
        pallet_ethereum_token_transfers::CurrentChannelInfo::<Runtime>::get()
361
64
            .map(|x| (x.channel_id, x.agent_id));
362

            
363
    pub const MinV2Reward: u128 = 1u128;
364
    pub MinSnowbridgeV2Reward: Asset = (TokenLocation::get(), MinV2Reward::get()).into();
365
}
366

            
367
/// Exports message to the Ethereum Gateway contract.
368
pub type SnowbridgeExporter = EthereumBlobExporter<
369
    UniversalLocation,
370
    EthereumNetwork,
371
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
372
    EthereumSystem,
373
    SnowbridgeChannelInfo,
374
>;
375

            
376
/// Exports message to the Ethereum Gateway contract.
377
pub type SnowbridgeExporterv2 = EthereumBlobExporterV2<
378
    UniversalLocation,
379
    EthereumNetwork,
380
    snowbridge_pallet_outbound_queue_v2::Pallet<Runtime>,
381
    EthereumSystem,
382
    MinSnowbridgeV2Reward,
383
    SendXcmFeeToAccount<LocalAssetTransactor, SnowbridgeFeesAccount>,
384
>;
385

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

            
396
/// Exports message to the Ethereum Gateway contract using Snowbridge V2.
397
pub type ContainerToSnowbridgeMessageExporterV2 = ContainerEthereumBlobExporterV2<
398
    UniversalLocation,
399
    EthereumNetwork,
400
    EthereumLocation,
401
    snowbridge_pallet_outbound_queue_v2::Pallet<Runtime>,
402
    EthereumSystem,
403
    MinSnowbridgeV2Reward,
404
>;