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 {
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
    frame_support::{
29
        parameter_types,
30
        traits::{Contains, Disabled, Equals, Everything, Nothing},
31
        weights::Weight,
32
    },
33
    frame_system::EnsureRoot,
34
    runtime_common::{
35
        xcm_sender::{ChildParachainRouter, ExponentialPrice},
36
        ToAuthor,
37
    },
38
    snowbridge_core::{AgentId, ChannelId},
39
    sp_core::ConstU32,
40
    sp_runtime::traits::TryConvertInto,
41
    starlight_runtime_constants::{
42
        currency::CENTS,
43
        snowbridge::{EthereumLocation, EthereumNetwork},
44
        system_parachain::*,
45
        TANSSI_GENESIS_HASH,
46
    },
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(TANSSI_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
    // Only one router so far - 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 AssetHub: Location = Parachain(ASSET_HUB_ID).into_location();
164
    pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH);
165
    pub const MaxInstructions: u32 = 100;
166
    pub const MaxAssetsIntoHolding: u32 = 64;
167
}
168

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

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

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

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

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

            
249
parameter_types! {
250
    pub const CollectiveBodyId: BodyId = BodyId::Unit;
251
    // StakingAdmin pluralistic body.
252
    pub const StakingAdminBodyId: BodyId = BodyId::Defense;
253
    // Fellows pluralistic body.
254
    pub const FellowsBodyId: BodyId = BodyId::Technical;
255
}
256

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

            
264
/// Type to convert the `StakingAdmin` origin to a Plurality `Location` value.
265
pub type StakingAdminToPlurality =
266
    OriginToPluralityVoice<RuntimeOrigin, StakingAdmin, StakingAdminBodyId>;
267

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

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

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

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

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

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

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

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

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