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 Starlight.
18

            
19
use crate::SnowbridgeFeesAccount;
20
use tanssi_runtime_common::relay::ExporterFeeHandler;
21
use tp_bridge::ContainerEthereumBlobExporter;
22
use {
23
    super::{
24
        parachains_origin,
25
        weights::{self, xcm::XcmWeight},
26
        AccountId, AllPalletsWithSystem, Balance, Balances, Dmp, Fellows, ForeignAssets,
27
        ForeignAssetsCreator, ParaId, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
28
        TransactionByteFee, Treasury, WeightToFee, XcmPallet,
29
    },
30
    crate::{governance::StakingAdmin, EthereumSystem},
31
    frame_support::{
32
        parameter_types,
33
        traits::{Contains, Disabled, Equals, Everything, Nothing},
34
        weights::Weight,
35
    },
36
    frame_system::EnsureRoot,
37
    runtime_common::{
38
        xcm_sender::{ChildParachainRouter, ExponentialPrice},
39
        ToAuthor,
40
    },
41
    snowbridge_core::{AgentId, ChannelId},
42
    sp_core::ConstU32,
43
    sp_runtime::traits::TryConvertInto,
44
    starlight_runtime_constants::{
45
        currency::CENTS,
46
        snowbridge::{EthereumLocation, EthereumNetwork},
47
        system_parachain::*,
48
        TANSSI_GENESIS_HASH,
49
    },
50
    tp_bridge::{
51
        snowbridge_outbound_token_transfer::{EthereumBlobExporter, SnowbrigeTokenTransferRouter},
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, SignedAccountId32AsNative, SignedToAccountId32,
66
        SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents,
67
        WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents,
68
    },
69
    xcm_executor::XcmExecutor,
70
};
71

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
251
parameter_types! {
252
    pub const CollectiveBodyId: BodyId = BodyId::Unit;
253
    // StakingAdmin pluralistic body.
254
    pub const StakingAdminBodyId: BodyId = BodyId::Defense;
255
    // Fellows pluralistic body.
256
    pub const FellowsBodyId: BodyId = BodyId::Technical;
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
/// Type to convert the `StakingAdmin` origin to a Plurality `Location` value.
267
pub type StakingAdminToPlurality =
268
    OriginToPluralityVoice<RuntimeOrigin, StakingAdmin, StakingAdminBodyId>;
269

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

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

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

            
314
parameter_types! {
315
    pub const ForeignAssetsAssetDeposit: Balance = 0;
316
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
317
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
318
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
319
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
320
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
321
    pub CheckingAccount: AccountId = XcmPallet::check_account();
322
}
323

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

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

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

            
372
parameter_types! {
373
    pub SnowbridgeChannelInfo: Option<(ChannelId, AgentId)> =
374
        pallet_ethereum_token_transfers::CurrentChannelInfo::<Runtime>::get()
375
64
            .map(|x| (x.channel_id, x.agent_id));
376
}
377

            
378
/// Exports message to the Ethereum Gateway contract.
379
pub type SnowbridgeExporter = EthereumBlobExporter<
380
    UniversalLocation,
381
    EthereumNetwork,
382
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
383
    EthereumSystem,
384
    SnowbridgeChannelInfo,
385
>;
386

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