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
// This file is part of Astar.

// Copyright (C) Stake Technologies Pte.Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later

// Astar is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Astar is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Astar. If not, see <http://www.gnu.org/licenses/>.

//! # Cross-chain Asset Config Pallet
//!
//! ## Overview
//!
//! This pallet provides mappings between local asset Id and remove asset location.
//! E.g. a multilocation like `{parents: 0, interior: X1::(Junction::Parachain(1000))}` could ba mapped to local asset Id `789`.
//!
//! The pallet ensures that the latest Location version is always used. Developers must ensure to properly migrate legacy versions
//! to newest when they become available.
//!
//! Additionally, it stores information whether a foreign asset is supported as a payment currency for execution on local network.
//!
//! ## Interface
//!
//! ### Dispatchable Function
//!
//! - `register_asset_location` - used to register mapping between local asset Id and remote asset location
//! - `set_asset_units_per_second` - registers asset as payment currency and sets the desired payment per second of execution time
//! - `change_existing_asset_location` - changes the remote location of an existing local asset Id
//! - `remove_payment_asset` - removes asset from the set of supported payment assets
//! - `remove_asset` - removes all information related to this asset
//!
//! User is encouraged to refer to specific function implementations for more comprehensive documentation.
//!
//! ### Other
//!
//! `AssetLocationGetter` interface for mapping asset Id to asset location and vice versa
//! - `get_xc_asset_location`
//! - `get_asset_id`
//!
//! `ExecutionPaymentRate` interface for fetching `units per second` if asset is supported payment asset
//! - `get_units_per_second`
//!
//! - `weight_to_fee` method is used to convert weight to fee based on units per second and weight.

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

use frame_support::pallet;
pub use pallet::*;

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

#[cfg(test)]
pub mod mock;
#[cfg(test)]
pub mod tests;

pub mod migrations;

pub mod weights;
pub use weights::WeightInfo;

#[pallet]
pub mod pallet {

    use crate::weights::WeightInfo;
    use frame_support::{
        pallet_prelude::*, traits::EnsureOrigin, weights::constants::WEIGHT_REF_TIME_PER_SECOND,
    };
    use frame_system::pallet_prelude::*;
    use parity_scale_codec::HasCompact;
    use sp_std::boxed::Box;
    use xcm::{v4::Location, VersionedLocation};

    const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);

    #[pallet::pallet]
    #[pallet::storage_version(STORAGE_VERSION)]
    #[pallet::without_storage_info]
    pub struct Pallet<T>(PhantomData<T>);

    /// Defines conversion between asset Id and cross-chain asset location
    pub trait XcAssetLocation<AssetId> {
        /// Get asset type from assetId
        fn get_xc_asset_location(asset_id: AssetId) -> Option<Location>;

        /// Get local asset Id from asset location
        fn get_asset_id(xc_asset_location: Location) -> Option<AssetId>;
    }

    /// Used to fetch `units per second` if cross-chain asset is applicable for local execution payment.
    pub trait ExecutionPaymentRate {
        /// returns units per second from asset type or `None` if asset type isn't a supported payment asset.
        fn get_units_per_second(asset_location: Location) -> Option<u128>;
    }

    impl<T: Config> XcAssetLocation<T::AssetId> for Pallet<T> {
        fn get_xc_asset_location(asset_id: T::AssetId) -> Option<Location> {
            AssetIdToLocation::<T>::get(asset_id).and_then(|x| x.try_into().ok())
        }

        fn get_asset_id(asset_location: Location) -> Option<T::AssetId> {
            AssetLocationToId::<T>::get(asset_location.into_versioned())
        }
    }

    impl<T: Config> ExecutionPaymentRate for Pallet<T> {
        fn get_units_per_second(asset_location: Location) -> Option<u128> {
            AssetLocationUnitsPerSecond::<T>::get(asset_location.into_versioned())
        }
    }

    impl<T: Config> Pallet<T> {
        /// Convert weight to fee based on units per second and weight.
        pub fn weight_to_fee(weight: Weight, units_per_second: u128) -> u128 {
            units_per_second.saturating_mul(weight.ref_time() as u128)
                / (WEIGHT_REF_TIME_PER_SECOND as u128)
        }
    }

    #[pallet::config]
    pub trait Config: frame_system::Config {
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

        /// The Asset Id. This will be used to create the asset and to associate it with
        /// a AssetLocation
        type AssetId: Member + Parameter + Default + Copy + HasCompact + MaxEncodedLen;

        /// The required origin for managing cross-chain asset configuration
        ///
        /// Should most likely be root.
        type ManagerOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;

        type WeightInfo: WeightInfo;
    }

    #[pallet::error]
    pub enum Error<T> {
        /// Asset is already registered.
        AssetAlreadyRegistered,
        /// Asset does not exist (hasn't been registered).
        AssetDoesNotExist,
        /// Failed to convert to latest versioned Location
        MultiLocationNotSupported,
    }

    #[pallet::event]
    #[pallet::generate_deposit(pub(crate) fn deposit_event)]
    pub enum Event<T: Config> {
        /// Registed mapping between asset type and asset Id.
        AssetRegistered {
            asset_location: VersionedLocation,
            asset_id: T::AssetId,
        },
        /// Changed the amount of units we are charging per execution second for an asset
        UnitsPerSecondChanged {
            asset_location: VersionedLocation,
            units_per_second: u128,
        },
        /// Changed the asset type mapping for a given asset id
        AssetLocationChanged {
            previous_asset_location: VersionedLocation,
            asset_id: T::AssetId,
            new_asset_location: VersionedLocation,
        },
        /// Supported asset type for fee payment removed.
        SupportedAssetRemoved { asset_location: VersionedLocation },
        /// Removed all information related to an asset Id
        AssetRemoved {
            asset_location: VersionedLocation,
            asset_id: T::AssetId,
        },
    }

    /// Mapping from an asset id to asset type.
    /// Can be used when receiving transaction specifying an asset directly,
    /// like transferring an asset from this chain to another.
    #[pallet::storage]
    pub type AssetIdToLocation<T: Config> =
        StorageMap<_, Twox64Concat, T::AssetId, VersionedLocation>;

    /// Mapping from an asset type to an asset id.
    /// Can be used when receiving a multilocation XCM message to retrieve
    /// the corresponding asset in which tokens should me minted.
    #[pallet::storage]
    pub type AssetLocationToId<T: Config> =
        StorageMap<_, Twox64Concat, VersionedLocation, T::AssetId>;

    /// Stores the units per second for local execution for a AssetLocation.
    /// This is used to know how to charge for XCM execution in a particular asset.
    ///
    /// Not all asset types are supported for payment. If value exists here, it means it is supported.
    #[pallet::storage]
    pub type AssetLocationUnitsPerSecond<T: Config> =
        StorageMap<_, Twox64Concat, VersionedLocation, u128>;

    #[pallet::call]
    impl<T: Config> Pallet<T> {
        /// Register new asset location to asset Id mapping.
        ///
        /// This makes the asset eligible for XCM interaction.
        #[pallet::call_index(0)]
        #[pallet::weight(T::WeightInfo::register_asset_location())]
        pub fn register_asset_location(
            origin: OriginFor<T>,
            asset_location: Box<VersionedLocation>,
            #[pallet::compact] asset_id: T::AssetId,
        ) -> DispatchResult {
            T::ManagerOrigin::ensure_origin(origin)?;

            // Ensure such an assetId does not exist
            ensure!(
                !AssetIdToLocation::<T>::contains_key(&asset_id),
                Error::<T>::AssetAlreadyRegistered
            );

            let v4_asset_loc = Location::try_from(*asset_location)
                .map_err(|_| Error::<T>::MultiLocationNotSupported)?;
            let asset_location = VersionedLocation::V4(v4_asset_loc);

            AssetIdToLocation::<T>::insert(&asset_id, asset_location.clone());
            AssetLocationToId::<T>::insert(&asset_location, asset_id);

            Self::deposit_event(Event::AssetRegistered {
                asset_location,
                asset_id,
            });
            Ok(())
        }

        /// Change the amount of units we are charging per execution second
        /// for a given AssetLocation.
        #[pallet::call_index(1)]
        #[pallet::weight(T::WeightInfo::set_asset_units_per_second())]
        pub fn set_asset_units_per_second(
            origin: OriginFor<T>,
            asset_location: Box<VersionedLocation>,
            #[pallet::compact] units_per_second: u128,
        ) -> DispatchResult {
            T::ManagerOrigin::ensure_origin(origin)?;

            let v4_asset_loc = Location::try_from(*asset_location)
                .map_err(|_| Error::<T>::MultiLocationNotSupported)?;
            let asset_location = VersionedLocation::V4(v4_asset_loc);

            ensure!(
                AssetLocationToId::<T>::contains_key(&asset_location),
                Error::<T>::AssetDoesNotExist
            );

            AssetLocationUnitsPerSecond::<T>::insert(&asset_location, units_per_second);

            Self::deposit_event(Event::UnitsPerSecondChanged {
                asset_location,
                units_per_second,
            });
            Ok(())
        }

        /// Change the xcm type mapping for a given asset Id.
        /// The new asset type will inherit old `units per second` value.
        #[pallet::call_index(2)]
        #[pallet::weight(T::WeightInfo::change_existing_asset_location())]
        pub fn change_existing_asset_location(
            origin: OriginFor<T>,
            new_asset_location: Box<VersionedLocation>,
            #[pallet::compact] asset_id: T::AssetId,
        ) -> DispatchResult {
            T::ManagerOrigin::ensure_origin(origin)?;

            let v4_asset_loc = Location::try_from(*new_asset_location)
                .map_err(|_| Error::<T>::MultiLocationNotSupported)?;
            let new_asset_location = VersionedLocation::V4(v4_asset_loc);

            let previous_asset_location =
                AssetIdToLocation::<T>::get(&asset_id).ok_or(Error::<T>::AssetDoesNotExist)?;

            // Insert new asset type info
            AssetIdToLocation::<T>::insert(&asset_id, new_asset_location.clone());
            AssetLocationToId::<T>::insert(&new_asset_location, asset_id);

            // Remove previous asset type info
            AssetLocationToId::<T>::remove(&previous_asset_location);

            // Change AssetLocationUnitsPerSecond
            if let Some(units) = AssetLocationUnitsPerSecond::<T>::take(&previous_asset_location) {
                AssetLocationUnitsPerSecond::<T>::insert(&new_asset_location, units);
            }

            Self::deposit_event(Event::AssetLocationChanged {
                previous_asset_location,
                asset_id,
                new_asset_location,
            });
            Ok(())
        }

        /// Removes asset from the set of supported payment assets.
        ///
        /// The asset can still be interacted with via XCM but it cannot be used to pay for execution time.
        #[pallet::call_index(3)]
        #[pallet::weight(T::WeightInfo::remove_payment_asset())]
        pub fn remove_payment_asset(
            origin: OriginFor<T>,
            asset_location: Box<VersionedLocation>,
        ) -> DispatchResult {
            T::ManagerOrigin::ensure_origin(origin)?;

            let v4_asset_loc = Location::try_from(*asset_location)
                .map_err(|_| Error::<T>::MultiLocationNotSupported)?;
            let asset_location = VersionedLocation::V4(v4_asset_loc);

            AssetLocationUnitsPerSecond::<T>::remove(&asset_location);

            Self::deposit_event(Event::SupportedAssetRemoved { asset_location });
            Ok(())
        }

        /// Removes all information related to asset, removing it from XCM support.
        #[pallet::call_index(4)]
        #[pallet::weight(T::WeightInfo::remove_asset())]
        pub fn remove_asset(
            origin: OriginFor<T>,
            #[pallet::compact] asset_id: T::AssetId,
        ) -> DispatchResult {
            T::ManagerOrigin::ensure_origin(origin)?;

            let asset_location =
                AssetIdToLocation::<T>::get(&asset_id).ok_or(Error::<T>::AssetDoesNotExist)?;

            AssetIdToLocation::<T>::remove(&asset_id);
            AssetLocationToId::<T>::remove(&asset_location);
            AssetLocationUnitsPerSecond::<T>::remove(&asset_location);

            Self::deposit_event(Event::AssetRemoved {
                asset_id,
                asset_location,
            });
            Ok(())
        }
    }
}