1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! # Rings Pallet
//!
//! - [`Config`]
//! - [`Call`]
//! - [`Pallet`]
//!
//! ## Overview
//! This pallet provides a XCM abstraction layer for INV4 Cores, allowing them to manage assets easily across multiple chains.
//!
//! The module [`traits`] contains traits that provide an abstraction on top of XCM [`MultiLocation`] and has to be correctly implemented in the runtime.
//!
//! ## Dispatchable Functions
//!
//! - `set_maintenance_status` - Sets the maintenance status of a chain, requires the origin to be authorized as a `MaintenanceOrigin`.
//! - `send_call` - Allows a core to send a XCM call to a destination chain.
//! - `transfer_assets` - Allows a core to transfer fungible assets to another account in the destination chain.
//! - `bridge_assets` - Allows a core to bridge fungible assets to another chain having either a third party account or
//!    the core account as beneficiary in the destination chain.

#![cfg_attr(not(feature = "std"), no_std)]

use frame_support::traits::Get;
use sp_std::convert::TryInto;

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;

#[cfg(test)]
mod tests;

mod traits;
pub mod weights;

pub use pallet::*;
pub use traits::{ChainAssetsList, ChainList};
pub use weights::WeightInfo;

#[frame_support::pallet]
pub mod pallet {
    use super::*;
    use frame_support::pallet_prelude::*;
    use frame_system::pallet_prelude::OriginFor;
    use pallet_inv4::origin::{ensure_multisig, INV4Origin};
    use sp_std::{vec, vec::Vec};
    use xcm::{
        v3::{prelude::*, MultiAsset, Weight, WildMultiAsset},
        DoubleEncoded,
    };

    #[pallet::pallet]
    pub struct Pallet<T>(_);

    #[pallet::config]
    pub trait Config: frame_system::Config + pallet_inv4::Config + pallet_xcm::Config {
        /// The overarching event type.
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

        /// Higher level type providing an abstraction over a chain's asset and location.
        type Chains: ChainList;

        /// Max length of an XCM call.
        #[pallet::constant]
        type MaxXCMCallLength: Get<u32>;

        /// Origin that can set maintenance status.
        type MaintenanceOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;

        /// Weight information for extrinsics in this pallet.
        type WeightInfo: WeightInfo;
    }

    /// Maps chain's and their maintenance status.
    #[pallet::storage]
    #[pallet::getter(fn is_under_maintenance)]
    pub type ChainsUnderMaintenance<T: Config> =
        StorageMap<_, Blake2_128Concat, MultiLocation, bool>;

    #[pallet::error]
    pub enum Error<T> {
        /// Failed to send XCM.
        SendingFailed,
        /// Weight exceeds `MaxXCMCallLength`.
        WeightTooHigh,
        /// Failed to calculate XCM fee.
        FailedToCalculateXcmFee,
        /// Failed to reanchor asset.
        FailedToReanchorAsset,
        /// Failed to invert location.
        FailedToInvertLocation,
        /// Asset is not supported in the destination chain.
        DifferentChains,
        /// Chain is under maintenance.
        ChainUnderMaintenance,
    }

    #[pallet::event]
    #[pallet::generate_deposit(fn deposit_event)]
    pub enum Event<T: Config> {
        /// A XCM call was sent.
        CallSent {
            sender: <T as pallet_inv4::Config>::CoreId,
            destination: <T as pallet::Config>::Chains,
            call: Vec<u8>,
        },

        /// Assets were transferred.
        AssetsTransferred {
            chain: <<<T as pallet::Config>::Chains as ChainList>::ChainAssets as ChainAssetsList>::Chains,
            asset: <<T as pallet::Config>::Chains as ChainList>::ChainAssets,
            amount: u128,
            from: <T as pallet_inv4::Config>::CoreId,
            to: <T as frame_system::Config>::AccountId,
        },

        /// Assets were bridged.
        AssetsBridged {
            origin_chain_asset: <<T as pallet::Config>::Chains as ChainList>::ChainAssets,
            amount: u128,
            from: <T as pallet_inv4::Config>::CoreId,
            to: Option<<T as frame_system::Config>::AccountId>,
        },

        /// A Chain's maintenance status changed.
        ChainMaintenanceStatusChanged {
            chain: <T as Config>::Chains,
            under_maintenance: bool,
        }
    }

    #[pallet::call]
    impl<T: Config> Pallet<T>
    where
        Result<INV4Origin<T>, <T as frame_system::Config>::RuntimeOrigin>:
            From<<T as frame_system::Config>::RuntimeOrigin>,

        <T as pallet_inv4::Config>::CoreId: Into<u32>,

        [u8; 32]: From<<T as frame_system::Config>::AccountId>,
        <T as frame_system::Config>::AccountId: From<[u8; 32]>,
    {
        /// Set the maintenance status of a chain.
        ///
        /// The origin has to be `MaintenanceOrigin`.
        ///
        /// - `chain`: referred chain.
        /// - `under_maintenance`: maintenance status.
        #[pallet::call_index(0)]
        #[pallet::weight((<T as Config>::WeightInfo::set_maintenance_status(), Pays::No))]
        pub fn set_maintenance_status(
            origin: OriginFor<T>,
            chain: <T as Config>::Chains,
            under_maintenance: bool,
        ) -> DispatchResult {
            T::MaintenanceOrigin::ensure_origin(origin)?;

            ChainsUnderMaintenance::<T>::insert(chain.get_location(), under_maintenance);

            Self::deposit_event(Event::<T>::ChainMaintenanceStatusChanged {
                chain,
                under_maintenance,
            });

            Ok(())
        }

        /// Send a XCM call to a destination chain.
        ///
        /// The origin has to be a core.
        ///
        /// - `destination`: destination chain.
        /// - `weight`: weight of the call.
        /// - `fee_asset`: asset used to pay the fee.
        /// - `fee`: fee amount.
        /// - `call`: XCM call.
        #[pallet::call_index(1)]
        #[pallet::weight(
            <T as Config>::WeightInfo::send_call(call.len() as u32)
        )]
        pub fn send_call(
            origin: OriginFor<T>,
            destination: <T as pallet::Config>::Chains,
            weight: Weight,
            fee_asset: <<T as pallet::Config>::Chains as ChainList>::ChainAssets,
            fee: u128,
            call: BoundedVec<u8, T::MaxXCMCallLength>,
        ) -> DispatchResult {
            let core = ensure_multisig::<T, OriginFor<T>>(origin)?;
            let core_id = core.id.into();

            let dest = destination.get_location();

            ensure!(
                !Self::is_under_maintenance(dest).unwrap_or(false),
                Error::<T>::ChainUnderMaintenance
            );

            let descend_interior = Junction::Plurality {
                id: BodyId::Index(core_id),
                part: BodyPart::Voice,
            };

            let fee_asset_location = fee_asset.get_asset_location();

            let mut core_multilocation: MultiLocation = MultiLocation {
                parents: 1,
                interior: Junctions::X2(
                    Junction::Parachain(<T as pallet_inv4::Config>::ParaId::get()),
                    descend_interior,
                ),
            };

            mutate_if_relay(&mut core_multilocation, &dest);

            let fee_multiasset = MultiAsset {
                id: AssetId::Concrete(fee_asset_location),
                fun: Fungibility::Fungible(fee),
            };

            let message = Xcm(vec![
                Instruction::WithdrawAsset(fee_multiasset.clone().into()),
                Instruction::BuyExecution {
                    fees: fee_multiasset,
                    weight_limit: WeightLimit::Unlimited,
                },
                Instruction::Transact {
                    origin_kind: OriginKind::SovereignAccount,
                    require_weight_at_most: weight,
                    call: <DoubleEncoded<_> as From<Vec<u8>>>::from(call.clone().to_vec()),
                },
                Instruction::RefundSurplus,
                Instruction::DepositAsset {
                    assets: MultiAssetFilter::Wild(WildMultiAsset::AllCounted(1)),
                    beneficiary: core_multilocation,
                },
            ]);

            pallet_xcm::Pallet::<T>::send_xcm(descend_interior, dest, message)
                .map_err(|_| Error::<T>::SendingFailed)?;

            Self::deposit_event(Event::CallSent {
                sender: core.id,
                destination,
                call: call.to_vec(),
            });

            Ok(())
        }

        /// Transfer fungible assets to another account in the destination chain.
        ///
        /// Both asset and fee_asset have to be in the same chain.
        ///
        /// The origin has to be a core.
        ///
        /// - `asset`: asset to transfer.
        /// - `amount`: amount to transfer.
        /// - `to`: account receiving the asset.
        /// - `fee_asset`: asset used to pay the fee.
        /// - `fee`: fee amount.
        #[pallet::call_index(2)]
        #[pallet::weight(<T as Config>::WeightInfo::transfer_assets())]
        pub fn transfer_assets(
            origin: OriginFor<T>,
            asset: <<T as pallet::Config>::Chains as ChainList>::ChainAssets,
            amount: u128,
            to: <T as frame_system::Config>::AccountId,
            fee_asset: <<T as pallet::Config>::Chains as ChainList>::ChainAssets,
            fee: u128,
        ) -> DispatchResult {
            let core = ensure_multisig::<T, OriginFor<T>>(origin)?;
            let core_id = core.id.into();

            let chain = asset.get_chain();
            let dest = chain.get_location();

            ensure!(
                !Self::is_under_maintenance(dest).unwrap_or(false),
                Error::<T>::ChainUnderMaintenance
            );

            ensure!(chain == fee_asset.get_chain(), Error::<T>::DifferentChains);

            let descend_interior = Junction::Plurality {
                id: BodyId::Index(core_id),
                part: BodyPart::Voice,
            };

            let asset_location = asset.get_asset_location();

            let multi_asset = MultiAsset {
                id: AssetId::Concrete(asset_location),
                fun: Fungibility::Fungible(amount),
            };

            let beneficiary: MultiLocation = MultiLocation {
                parents: 0,
                interior: Junctions::X1(Junction::AccountId32 {
                    network: None,
                    id: to.clone().into(),
                }),
            };

            let mut core_multilocation: MultiLocation = MultiLocation {
                parents: 1,
                interior: Junctions::X2(
                    Junction::Parachain(<T as pallet_inv4::Config>::ParaId::get()),
                    descend_interior,
                ),
            };

            mutate_if_relay(&mut core_multilocation, &dest);

            let fee_multiasset = MultiAsset {
                id: AssetId::Concrete(fee_asset.get_asset_location()),
                fun: Fungibility::Fungible(fee),
            };

            let message = Xcm(vec![
                // Pay execution fees
                Instruction::WithdrawAsset(fee_multiasset.clone().into()),
                Instruction::BuyExecution {
                    fees: fee_multiasset,
                    weight_limit: WeightLimit::Unlimited,
                },
                // Actual transfer instruction
                Instruction::TransferAsset {
                    assets: multi_asset.into(),
                    beneficiary,
                },
                // Refund unused fees
                Instruction::RefundSurplus,
                Instruction::DepositAsset {
                    assets: MultiAssetFilter::Wild(WildMultiAsset::AllCounted(1)),
                    beneficiary: core_multilocation,
                },
            ]);

            pallet_xcm::Pallet::<T>::send_xcm(descend_interior, dest, message)
                .map_err(|_| Error::<T>::SendingFailed)?;

            Self::deposit_event(Event::AssetsTransferred {
                chain,
                asset,
                amount,
                from: core.id,
                to,
            });

            Ok(())
        }

        /// Bridge fungible assets to another chain.
        ///
        /// The origin has to be a core.
        ///
        /// - `asset`: asset to bridge and the chain to bridge from.
        /// - `destination`: destination chain.
        /// - `fee`: fee amount.
        /// - `amount`: amount to bridge.
        /// - `to`: account receiving the asset, None defaults to core account.
        #[pallet::call_index(3)]
        #[pallet::weight(<T as Config>::WeightInfo::bridge_assets())]
        pub fn bridge_assets(
            origin: OriginFor<T>,
            asset: <<T as pallet::Config>::Chains as ChainList>::ChainAssets,
            destination: <<<T as pallet::Config>::Chains as ChainList>::ChainAssets as ChainAssetsList>::Chains,
            fee: u128,
            amount: u128,
            to: Option<<T as frame_system::Config>::AccountId>,
        ) -> DispatchResult {
            let core = ensure_multisig::<T, OriginFor<T>>(origin)?;

            let core_id = core.id.into();

            let from_chain = asset.get_chain();
            let from_chain_location = from_chain.get_location();

            let dest = destination.get_location();

            ensure!(
                !(Self::is_under_maintenance(from_chain_location).unwrap_or(false)
                    || Self::is_under_maintenance(dest).unwrap_or(false)),
                Error::<T>::ChainUnderMaintenance
            );

            let descend_interior = Junction::Plurality {
                id: BodyId::Index(core_id),
                part: BodyPart::Voice,
            };

            let asset_location = asset.get_asset_location();

            let inverted_destination = dest
                .reanchored(&from_chain_location, *from_chain_location.interior())
                .map(|inverted| {
                    if let (ml, Some(Junction::OnlyChild) | None) = inverted.split_last_interior() {
                        ml
                    } else {
                        inverted
                    }
                })
                .map_err(|_| Error::<T>::FailedToInvertLocation)?;

            let multiasset = MultiAsset {
                id: AssetId::Concrete(asset_location),
                fun: Fungibility::Fungible(amount),
            };

            let fee_multiasset = MultiAsset {
                id: AssetId::Concrete(asset_location),
                fun: Fungibility::Fungible(fee),
            };

            let reanchored_multiasset = multiasset
                .clone()
                .reanchored(&dest, *from_chain_location.interior())
                .map(|mut reanchored| {
                    if let AssetId::Concrete(ref mut m) = reanchored.id {
                        if let (ml, Some(Junction::OnlyChild) | None) = (*m).split_last_interior() {
                            *m = ml;
                        }
                    }
                    reanchored
                })
                .map_err(|_| Error::<T>::FailedToReanchorAsset)?;

            let mut core_multilocation: MultiLocation = MultiLocation {
                parents: 1,
                interior: Junctions::X2(
                    Junction::Parachain(<T as pallet_inv4::Config>::ParaId::get()),
                    descend_interior,
                ),
            };

            let beneficiary: MultiLocation = match to.clone() {
                Some(to_inner) => MultiLocation {
                    parents: 0,
                    interior: Junctions::X1(Junction::AccountId32 {
                        network: None,
                        id: to_inner.into(),
                    }),
                },
                None => {
                    let mut dest_core_multilocation = core_multilocation;

                    mutate_if_relay(&mut dest_core_multilocation, &dest);

                    dest_core_multilocation
                }
            };

            mutate_if_relay(&mut core_multilocation, &dest);

            // If the asset originates from the destination chain, we need to reverse the reserve-transfer.
            let message = if asset_location.starts_with(&dest) {
                Xcm(vec![
                    WithdrawAsset(vec![fee_multiasset.clone(), multiasset.clone()].into()),
                    // Core pays for the execution fee incurred on sending the XCM.
                    Instruction::BuyExecution {
                        fees: fee_multiasset,
                        weight_limit: WeightLimit::Unlimited,
                    },
                    InitiateReserveWithdraw {
                        assets: multiasset.into(),
                        reserve: inverted_destination,
                        xcm: Xcm(vec![
                            // the beneficiary buys execution fee in the destination chain for the deposit.
                            Instruction::BuyExecution {
                                fees: reanchored_multiasset,
                                weight_limit: WeightLimit::Unlimited,
                            },
                            Instruction::DepositAsset {
                                assets: AllCounted(1).into(),
                                beneficiary,
                            },
                            Instruction::RefundSurplus,
                            // Refunds the beneficiary the surplus of the execution fees in the destination chain.
                            Instruction::DepositAsset {
                                assets: AllCounted(1).into(),
                                beneficiary,
                            },
                        ]),
                    },
                    Instruction::RefundSurplus,
                    // Refunds the core the surplus of the execution fees incurred on sending the XCM.
                    Instruction::DepositAsset {
                        assets: AllCounted(1).into(),
                        beneficiary: core_multilocation,
                    },
                ])
            } else {
                Xcm(vec![
                    // Pay execution fees
                    Instruction::WithdrawAsset(fee_multiasset.clone().into()),
                    Instruction::BuyExecution {
                        fees: fee_multiasset,
                        weight_limit: WeightLimit::Unlimited,
                    },
                    // Actual reserve transfer instruction
                    Instruction::TransferReserveAsset {
                        assets: multiasset.into(),
                        dest: inverted_destination,
                        xcm: Xcm(vec![
                            Instruction::BuyExecution {
                                fees: reanchored_multiasset,
                                weight_limit: WeightLimit::Unlimited,
                            },
                            Instruction::DepositAsset {
                                assets: MultiAssetFilter::Wild(WildMultiAsset::AllCounted(1)),
                                beneficiary,
                            },
                        ]),
                    },
                    // Refund unused fees
                    Instruction::RefundSurplus,
                    Instruction::DepositAsset {
                        assets: MultiAssetFilter::Wild(WildMultiAsset::AllCounted(1)),
                        beneficiary: core_multilocation,
                    },
                ])
            };

            pallet_xcm::Pallet::<T>::send_xcm(descend_interior, from_chain_location, message)
                .map_err(|_| Error::<T>::SendingFailed)?;

            Self::deposit_event(Event::AssetsBridged {
                origin_chain_asset: asset,
                from: core.id,
                amount,
                to,
            });

            Ok(())
        }
    }

    pub fn mutate_if_relay(origin: &mut MultiLocation, dest: &MultiLocation) {
        if dest.contains_parents_only(1) {
            origin.dec_parent();
        }
    }
}