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, ForeignAssets,
27
        ForeignAssetsCreator, ParaId, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
28
        TransactionByteFee, Treasury, WeightToFee, XcmPallet,
29
    },
30
    crate::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
        SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation,
66
        TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds,
67
        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
/// Type to convert an `Origin` type value into a `Location` value which represents an interior
252
/// location of this chain.
253
pub type LocalOriginToLocation = (
254
    // And a usual Signed origin to be used in XCM as a corresponding AccountId32
255
    SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
256
);
257

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

            
290
parameter_types! {
291
    pub const ForeignAssetsAssetDeposit: Balance = 0;
292
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
293
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
294
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
295
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
296
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
297
    pub CheckingAccount: AccountId = XcmPallet::check_account();
298
}
299

            
300
#[cfg(feature = "runtime-benchmarks")]
301
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
302
pub struct ForeignAssetBenchmarkHelper;
303
#[cfg(feature = "runtime-benchmarks")]
304
impl pallet_assets::BenchmarkHelper<AssetId> for ForeignAssetBenchmarkHelper {
305
    fn create_asset_id_parameter(id: u32) -> AssetId {
306
        id.try_into()
307
            .expect("number too large to create benchmarks")
308
    }
309
}
310

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

            
337
impl pallet_foreign_asset_creator::Config for Runtime {
338
    type ForeignAsset = Location;
339
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
340
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
341
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
342
    type Fungibles = ForeignAssets;
343
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
344
    type OnForeignAssetCreated = ();
345
    type OnForeignAssetDestroyed = ();
346
}
347

            
348
parameter_types! {
349
    pub SnowbridgeChannelInfo: Option<(ChannelId, AgentId)> =
350
        pallet_ethereum_token_transfers::CurrentChannelInfo::<Runtime>::get()
351
64
            .map(|x| (x.channel_id, x.agent_id));
352
}
353

            
354
/// Exports message to the Ethereum Gateway contract.
355
pub type SnowbridgeExporter = EthereumBlobExporter<
356
    UniversalLocation,
357
    EthereumNetwork,
358
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
359
    EthereumSystem,
360
    SnowbridgeChannelInfo,
361
>;
362

            
363
/// Exports message to the Ethereum Gateway contract.
364
pub type ContainerToSnowbridgeMessageExporter = ContainerEthereumBlobExporter<
365
    UniversalLocation,
366
    EthereumNetwork,
367
    EthereumLocation,
368
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
369
    EthereumSystem,
370
    SnowbridgeChannelInfo,
371
>;