-
Notifications
You must be signed in to change notification settings - Fork 302
/
Copy pathlib.rs
328 lines (273 loc) · 9.45 KB
/
lib.rs
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
#![cfg_attr(not(feature = "std"), no_std)]
// Older clippy versions give a false positive on the expansion of [pallet::call].
// This is fixed in https://github.com/rust-lang/rust-clippy/issues/8321
#![allow(clippy::large_enum_variant)]
#![allow(clippy::too_many_arguments)]
use frame_support::{pallet_prelude::*, traits::EnsureOriginWithArg};
use frame_system::pallet_prelude::*;
pub use orml_traits::asset_registry::AssetMetadata;
use orml_traits::asset_registry::AssetProcessor;
use scale_info::TypeInfo;
use sp_runtime::{
traits::{AtLeast32BitUnsigned, Member},
DispatchResult,
};
use sp_std::prelude::*;
use xcm::{v3::prelude::*, VersionedMultiLocation};
pub use impls::*;
pub use module::*;
pub use weights::WeightInfo;
mod impls;
mod weights;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
mod migrations;
pub use migrations::Migration;
#[frame_support::pallet]
pub mod module {
use super::*;
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Additional non-standard metadata to store for each asset
type CustomMetadata: Parameter + Member + TypeInfo;
/// The type used as a unique asset id,
type AssetId: Parameter + Member + Default + TypeInfo + MaybeSerializeDeserialize;
/// Checks that an origin has the authority to register/update an asset
type AuthorityOrigin: EnsureOriginWithArg<Self::RuntimeOrigin, Option<Self::AssetId>>;
/// A filter ran upon metadata registration that assigns an is and
/// potentially modifies the supplied metadata.
type AssetProcessor: AssetProcessor<Self::AssetId, AssetMetadata<Self::Balance, Self::CustomMetadata>>;
/// The balance type.
type Balance: Parameter + Member + AtLeast32BitUnsigned + Default + Copy;
/// Weight information for extrinsics in this module.
type WeightInfo: WeightInfo;
}
#[pallet::error]
pub enum Error<T> {
/// Asset was not found.
AssetNotFound,
/// The version of the `VersionedMultiLocation` value used is not able
/// to be interpreted.
BadVersion,
/// The asset id is invalid.
InvalidAssetId,
/// Another asset was already register with this location.
ConflictingLocation,
/// Another asset was already register with this asset id.
ConflictingAssetId,
}
#[pallet::event]
#[pallet::generate_deposit(pub(crate) fn deposit_event)]
pub enum Event<T: Config> {
RegisteredAsset {
asset_id: T::AssetId,
metadata: AssetMetadata<T::Balance, T::CustomMetadata>,
},
UpdatedAsset {
asset_id: T::AssetId,
metadata: AssetMetadata<T::Balance, T::CustomMetadata>,
},
}
/// The metadata of an asset, indexed by asset id.
#[pallet::storage]
#[pallet::getter(fn metadata)]
pub type Metadata<T: Config> =
StorageMap<_, Twox64Concat, T::AssetId, AssetMetadata<T::Balance, T::CustomMetadata>, OptionQuery>;
/// Maps a multilocation to an asset id - useful when processing xcm
/// messages.
#[pallet::storage]
#[pallet::getter(fn location_to_asset_id)]
pub type LocationToAssetId<T: Config> = StorageMap<_, Twox64Concat, MultiLocation, T::AssetId, OptionQuery>;
/// The last processed asset id - used when assigning a sequential id.
#[pallet::storage]
#[pallet::getter(fn last_asset_id)]
pub(crate) type LastAssetId<T: Config> = StorageValue<_, T::AssetId, ValueQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub assets: Vec<(T::AssetId, Vec<u8>)>,
pub last_asset_id: T::AssetId,
}
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self {
assets: vec![],
last_asset_id: Default::default(),
}
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
self.assets.iter().for_each(|(asset_id, metadata_encoded)| {
let metadata = AssetMetadata::decode(&mut &metadata_encoded[..]).expect("Error decoding AssetMetadata");
Pallet::<T>::do_register_asset_without_asset_processor(metadata, asset_id.clone())
.expect("Error registering Asset");
});
LastAssetId::<T>::set(self.last_asset_id.clone());
}
}
const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::storage_version(STORAGE_VERSION)]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
#[pallet::hooks]
impl<T: Config> Hooks<T::BlockNumber> for Pallet<T> {}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::register_asset())]
pub fn register_asset(
origin: OriginFor<T>,
metadata: AssetMetadata<T::Balance, T::CustomMetadata>,
asset_id: Option<T::AssetId>,
) -> DispatchResult {
T::AuthorityOrigin::ensure_origin(origin, &asset_id)?;
Self::do_register_asset(metadata, asset_id)
}
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::update_asset())]
pub fn update_asset(
origin: OriginFor<T>,
asset_id: T::AssetId,
decimals: Option<u32>,
name: Option<Vec<u8>>,
symbol: Option<Vec<u8>>,
existential_deposit: Option<T::Balance>,
location: Option<Option<VersionedMultiLocation>>,
additional: Option<T::CustomMetadata>,
) -> DispatchResult {
T::AuthorityOrigin::ensure_origin(origin, &Some(asset_id.clone()))?;
Self::do_update_asset(
asset_id,
decimals,
name,
symbol,
existential_deposit,
location,
additional,
)?;
Ok(())
}
}
}
impl<T: Config> Pallet<T> {
/// Register a new asset
pub fn do_register_asset(
metadata: AssetMetadata<T::Balance, T::CustomMetadata>,
asset_id: Option<T::AssetId>,
) -> DispatchResult {
let (asset_id, metadata) = T::AssetProcessor::pre_register(asset_id, metadata)?;
Self::do_register_asset_without_asset_processor(metadata.clone(), asset_id.clone())?;
T::AssetProcessor::post_register(asset_id, metadata)?;
Ok(())
}
/// Like do_register_asset, but without calling pre_register and
/// post_register hooks.
/// This function is useful in tests but it might also come in useful to
/// users.
pub fn do_register_asset_without_asset_processor(
metadata: AssetMetadata<T::Balance, T::CustomMetadata>,
asset_id: T::AssetId,
) -> DispatchResult {
Metadata::<T>::try_mutate(&asset_id, |maybe_metadata| -> DispatchResult {
// make sure this asset id has not been registered yet
ensure!(maybe_metadata.is_none(), Error::<T>::ConflictingAssetId);
*maybe_metadata = Some(metadata.clone());
if let Some(ref location) = metadata.location {
Self::do_insert_location(asset_id.clone(), location.clone())?;
}
Ok(())
})?;
Self::deposit_event(Event::<T>::RegisteredAsset { asset_id, metadata });
Ok(())
}
pub fn do_update_asset(
asset_id: T::AssetId,
decimals: Option<u32>,
name: Option<Vec<u8>>,
symbol: Option<Vec<u8>>,
existential_deposit: Option<T::Balance>,
location: Option<Option<VersionedMultiLocation>>,
additional: Option<T::CustomMetadata>,
) -> DispatchResult {
Metadata::<T>::try_mutate(&asset_id, |maybe_metadata| -> DispatchResult {
let metadata = maybe_metadata.as_mut().ok_or(Error::<T>::AssetNotFound)?;
if let Some(decimals) = decimals {
metadata.decimals = decimals;
}
if let Some(name) = name {
metadata.name = name;
}
if let Some(symbol) = symbol {
metadata.symbol = symbol;
}
if let Some(existential_deposit) = existential_deposit {
metadata.existential_deposit = existential_deposit;
}
if let Some(location) = location {
Self::do_update_location(asset_id.clone(), metadata.location.clone(), location.clone())?;
metadata.location = location;
}
if let Some(additional) = additional {
metadata.additional = additional;
}
Self::deposit_event(Event::<T>::UpdatedAsset {
asset_id: asset_id.clone(),
metadata: metadata.clone(),
});
Ok(())
})?;
Ok(())
}
pub fn fetch_metadata_by_location(
location: &MultiLocation,
) -> Option<AssetMetadata<T::Balance, T::CustomMetadata>> {
let asset_id = LocationToAssetId::<T>::get(location)?;
Metadata::<T>::get(asset_id)
}
pub fn multilocation(asset_id: &T::AssetId) -> Result<Option<MultiLocation>, DispatchError> {
Metadata::<T>::get(asset_id)
.and_then(|metadata| {
metadata
.location
.map(|location| location.try_into().map_err(|()| Error::<T>::BadVersion.into()))
})
.transpose()
}
/// update LocationToAssetId mapping if the location changed
fn do_update_location(
asset_id: T::AssetId,
old_location: Option<VersionedMultiLocation>,
new_location: Option<VersionedMultiLocation>,
) -> DispatchResult {
// Update `LocationToAssetId` only if location changed
if new_location != old_location {
// remove the old location lookup if it exists
if let Some(ref old_location) = old_location {
let location: MultiLocation = old_location.clone().try_into().map_err(|()| Error::<T>::BadVersion)?;
LocationToAssetId::<T>::remove(location);
}
// insert new location
if let Some(ref new_location) = new_location {
Self::do_insert_location(asset_id, new_location.clone())?;
}
}
Ok(())
}
/// insert location into the LocationToAssetId map
fn do_insert_location(asset_id: T::AssetId, location: VersionedMultiLocation) -> DispatchResult {
// if the metadata contains a location, set the LocationToAssetId
let location: MultiLocation = location.try_into().map_err(|()| Error::<T>::BadVersion)?;
LocationToAssetId::<T>::try_mutate(location, |maybe_asset_id| {
ensure!(maybe_asset_id.is_none(), Error::<T>::ConflictingLocation);
*maybe_asset_id = Some(asset_id);
Ok(())
})
}
}