Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate xpallet-asset-registrar to pallet v2 #550

Merged
merged 25 commits into from
Jun 12, 2021
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
a098f47
migrate xpallets-asset-registrar
Jun 10, 2021
a6ff765
migrate xpallets-asset-registrar
Jun 10, 2021
9821aaf
migrate xpallets-asset-registrar pallet v2
VegeBun-csj Jun 10, 2021
41b9ac9
Merge branch 'develop' of https://github.com/VegeBun-csj/ChainX into …
VegeBun-csj Jun 10, 2021
87d0112
migrate pallet v2
VegeBun-csj Jun 10, 2021
47c2efd
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 10, 2021
743be74
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 10, 2021
ec7ee76
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 10, 2021
dc31c81
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 10, 2021
7068936
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 10, 2021
606fbdd
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 10, 2021
033f5cb
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 10, 2021
dd47b6f
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 10, 2021
d60d75a
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 10, 2021
f0fe96c
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 10, 2021
d5b45f1
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 11, 2021
4e83d04
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 11, 2021
c846024
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 11, 2021
18b0e5b
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 11, 2021
6ce29c1
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 11, 2021
c95c6a8
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 11, 2021
9a89c5f
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 12, 2021
c1103f7
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 12, 2021
96b562f
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 12, 2021
be5ad7c
migrate xpallets-assets-registrar pallet v2
VegeBun-csj Jun 12, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion runtime/chainx/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1076,7 +1076,7 @@ construct_runtime!(

// ChainX basics.
XSystem: xpallet_system::{Pallet, Call, Storage, Event<T>, Config} = 24,
XAssetsRegistrar: xpallet_assets_registrar::{Pallet, Call, Storage, Event, Config} = 25,
XAssetsRegistrar: xpallet_assets_registrar::{Pallet, Call, Storage, Event<T>, Config} = 25,
XAssets: xpallet_assets::{Pallet, Call, Storage, Event<T>, Config<T>} = 26,

// Mining, must be after XAssets.
Expand Down
2 changes: 1 addition & 1 deletion runtime/dev/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1086,7 +1086,7 @@ construct_runtime!(

// ChainX basics.
XSystem: xpallet_system::{Pallet, Call, Storage, Event<T>, Config},
XAssetsRegistrar: xpallet_assets_registrar::{Pallet, Call, Storage, Event, Config},
XAssetsRegistrar: xpallet_assets_registrar::{Pallet, Call, Storage, Event<T>, Config},
XAssets: xpallet_assets::{Pallet, Call, Storage, Event<T>, Config<T>},

// Mining, must be after XAssets.
Expand Down
2 changes: 1 addition & 1 deletion runtime/malan/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1080,7 +1080,7 @@ construct_runtime!(

// ChainX basics.
XSystem: xpallet_system::{Pallet, Call, Storage, Event<T>, Config} = 24,
XAssetsRegistrar: xpallet_assets_registrar::{Pallet, Call, Storage, Event, Config} = 25,
XAssetsRegistrar: xpallet_assets_registrar::{Pallet, Call, Storage, Event<T>, Config} = 25,
XAssets: xpallet_assets::{Pallet, Call, Storage, Event<T>, Config<T>} = 26,

// Mining, must be after XAssets.
Expand Down
9 changes: 4 additions & 5 deletions xpallets/assets-registrar/src/benchmarking.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Copyright 2019-2020 ChainX Project Authors. Licensed under GPL-3.0.

use frame_benchmarking::{benchmarks, impl_benchmark_test_suite};
use frame_support::StorageMap;
use frame_system::RawOrigin;

use chainx_primitives::AssetId;
Expand All @@ -26,15 +25,15 @@ benchmarks! {
let asset_info = b_asset_info_test_data::<T>();
}: _(RawOrigin::Root, ASSET_ID, asset_info.clone(), true, true)
verify {
assert_eq!(AssetInfoOf::get(ASSET_ID), Some(asset_info));
assert_eq!(AssetInfoOf::<T>::get(ASSET_ID), Some(asset_info));
}

deregister {
let asset_info = b_asset_info_test_data::<T>();
Pallet::<T>::register(RawOrigin::Root.into(), ASSET_ID, asset_info.clone(), true, true)?;
}: _(RawOrigin::Root, ASSET_ID)
verify {
assert!(!AssetOnline::get(ASSET_ID));
assert!(!AssetOnline::<T>::get(ASSET_ID));
}

recover {
Expand All @@ -43,7 +42,7 @@ benchmarks! {
Pallet::<T>::deregister(RawOrigin::Root.into(), ASSET_ID)?;
}: _(RawOrigin::Root, ASSET_ID, true)
verify {
assert!(AssetOnline::get(ASSET_ID));
assert!(AssetOnline::<T>::get(ASSET_ID));
}

update_asset_info {
Expand All @@ -61,7 +60,7 @@ benchmarks! {
new_asset_info.set_token(b"new_token".to_vec());
new_asset_info.set_token_name(b"new_token_name".to_vec());
new_asset_info.set_desc(b"new_desc".to_vec());
assert_eq!(AssetInfoOf::get(ASSET_ID).unwrap(), new_asset_info);
assert_eq!(AssetInfoOf::<T>::get(ASSET_ID).unwrap(), new_asset_info);
}
}

Expand Down
187 changes: 116 additions & 71 deletions xpallets/assets-registrar/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,53 +19,65 @@ pub mod weights;
use sp_std::prelude::*;

use frame_support::{
decl_error, decl_event, decl_module, decl_storage,
dispatch::{DispatchError, DispatchResult},
ensure,
log::info,
traits::Get,
IterableStorageMap,
};
use frame_system::ensure_root;

use chainx_primitives::{AssetId, Desc, Token};

#[cfg(feature = "std")]
use frame_support::traits::GenesisBuild;

pub use self::types::AssetInfo;
pub use self::weights::WeightInfo;
pub use xp_assets_registrar::{Chain, RegistrarHandler};

/// The module's config trait.
///
/// `frame_system::Config` should always be included in our implied traits.
pub trait Config: frame_system::Config {
/// The overarching event type.
type Event: From<Event> + Into<<Self as frame_system::Config>::Event>;
pub use pallet::*;

/// Native asset Id.
type NativeAssetId: Get<AssetId>;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;

/// Handler for doing stuff after the asset is registered/deregistered.
type RegistrarHandler: RegistrarHandler;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);

/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
}
#[pallet::config]
/// The module's config trait.
///
/// `frame_system::Trait` should always be included in our implied traits.
pub trait Config: frame_system::Config {
/// The overarching event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;

/// Native asset Id.
type NativeAssetId: Get<AssetId>;

/// Handler for doing stuff after the asset is registered/deregistered.
type RegistrarHandler: RegistrarHandler;

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

decl_event!(
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
/// Event for the XAssetRegistrar Module
pub enum Event {
pub enum Event<T: Config> {
/// A new asset was registered. [asset_id, has_mining_rights]
Registered(AssetId, bool),
/// A deregistered asset was recovered. [asset_id, has_mining_rights]
Recovered(AssetId, bool),
/// An asset was deregistered. [asset_id]
Deregistered(AssetId),
}
);

decl_error! {
#[pallet::error]
/// Error for the XAssetRegistrar Module
pub enum Error for Module<T: Config> {
pub enum Error<T> {
/// Token symbol length is zero or too long
InvalidAssetTokenSymbolLength,
/// Token symbol char is invalid, only allow ASCII alphanumeric character or '-', '.', '|', '~'
Expand All @@ -85,27 +97,50 @@ decl_error! {
/// The asset is invalid (not online).
AssetIsInvalid,
}
}

decl_storage! {
trait Store for Module<T: Config> as XAssetsRegistrar {
/// Asset id list for each Chain.
pub AssetIdsOf get(fn asset_ids_of): map hasher(twox_64_concat) Chain => Vec<AssetId>;

/// Asset info of each asset.
pub AssetInfoOf get(fn asset_info_of): map hasher(twox_64_concat) AssetId => Option<AssetInfo>;

/// The map of asset to the online state.
pub AssetOnline get(fn asset_online): map hasher(twox_64_concat) AssetId => bool;
/// Asset id list for each Chain.
#[pallet::storage]
#[pallet::getter(fn asset_ids_of)]
pub(super) type AssetIdsOf<T: Config> =
StorageMap<_, Twox64Concat, Chain, Vec<AssetId>, ValueQuery>;

/// Asset info of each asset.
#[pallet::storage]
#[pallet::getter(fn asset_info_of)]
pub(super) type AssetInfoOf<T: Config> =
StorageMap<_, Twox64Concat, AssetId, Option<AssetInfo>, ValueQuery>;

/// The map of asset to the online state.
#[pallet::storage]
#[pallet::getter(fn asset_online)]
pub(super) type AssetOnline<T: Config> = StorageMap<_, Twox64Concat, AssetId, bool, ValueQuery>;

/// The map of asset to the block number at which the asset was registered.
#[pallet::storage]
#[pallet::getter(fn registered_at)]
pub(super) type RegisteredAt<T: Config> =
StorageMap<_, Twox64Concat, AssetId, T::BlockNumber, ValueQuery>;

/// add_extra_genesis
#[pallet::genesis_config]
pub struct GenesisConfig {
pub assets: Vec<(AssetId, AssetInfo, bool, bool)>,
}

/// The map of asset to the block number at which the asset was registered.
pub RegisteredAt get(fn registered_at): map hasher(twox_64_concat) AssetId => T::BlockNumber;
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
Self {
assets: Default::default(),
}
}
}
add_extra_genesis {
config(assets): Vec<(AssetId, AssetInfo, bool, bool)>;
build(|config| {
for (id, asset, is_online, has_mining_rights) in &config.assets {
Module::<T>::register(

#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
for (id, asset, is_online, has_mining_rights) in &self.assets {
Pallet::<T>::register(
frame_system::RawOrigin::Root.into(),
*id,
asset.clone(),
Expand All @@ -114,23 +149,18 @@ decl_storage! {
)
.expect("asset registeration during the genesis can not fail");
}
})
}
}
}

decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin {
type Error = Error<T>;

fn deposit_event() = default;

#[pallet::call]
impl<T: Config> Pallet<T> {
/// Register a new foreign asset.
///
/// This is a root-only operation.
#[weight = T::WeightInfo::register()]
#[pallet::weight(T::WeightInfo::register())]
pub fn register(
origin,
#[compact] asset_id: AssetId,
origin: OriginFor<T>,
#[pallet::compact] asset_id: AssetId,
asset: AssetInfo,
is_online: bool,
has_mining_rights: bool,
Expand All @@ -141,7 +171,6 @@ decl_module! {
ensure!(!Self::exists(&asset_id), Error::<T>::AssetAlreadyExists);

info!(
target: "runtime::assets-registrar",
"[register_asset] id:{}, info:{:?}, is_online:{}, has_mining_rights:{}",
asset_id, asset, is_online, has_mining_rights
);
Expand All @@ -163,17 +192,16 @@ decl_module! {
/// This asset will be marked as invalid.
///
/// This is a root-only operation.
#[weight = T::WeightInfo::deregister()]
pub fn deregister(origin, #[compact] id: AssetId) -> DispatchResult {
#[pallet::weight(T::WeightInfo::deregister())]
pub fn deregister(origin: OriginFor<T>, #[pallet::compact] id: AssetId) -> DispatchResult {
ensure_root(origin)?;

ensure!(Self::is_valid(&id), Error::<T>::AssetIsInvalid);

AssetOnline::remove(id);
AssetOnline::<T>::remove(id);

Self::deposit_event(Event::Deregistered(id));
T::RegistrarHandler::on_deregister(&id)?;

Ok(())
}

Expand All @@ -182,14 +210,18 @@ decl_module! {
/// `RegistrarHandler::on_register()` will be triggered again during the recover process.
///
/// This is a root-only operation.
#[weight = T::WeightInfo::recover()]
pub fn recover(origin, #[compact] id: AssetId, has_mining_rights: bool) -> DispatchResult {
#[pallet::weight(T::WeightInfo::recover())]
pub fn recover(
origin: OriginFor<T>,
#[pallet::compact] id: AssetId,
has_mining_rights: bool,
) -> DispatchResult {
ensure_root(origin)?;

ensure!(Self::exists(&id), Error::<T>::AssetDoesNotExist);
ensure!(!Self::is_valid(&id), Error::<T>::AssetAlreadyValid);

AssetOnline::insert(id, true);
AssetOnline::<T>::insert(id, true);

Self::deposit_event(Event::Recovered(id, has_mining_rights));
T::RegistrarHandler::on_register(&id, has_mining_rights)?;
Expand All @@ -199,13 +231,13 @@ decl_module! {
/// Update the asset info, all the new fields are optional.
///
/// This is a root-only operation.
#[weight = T::WeightInfo::update_asset_info()]
#[pallet::weight(T::WeightInfo::update_asset_info())]
pub fn update_asset_info(
origin,
#[compact] id: AssetId,
origin: OriginFor<T>,
#[pallet::compact] id: AssetId,
token: Option<Token>,
token_name: Option<Token>,
desc: Option<Desc>
desc: Option<Desc>,
) -> DispatchResult {
ensure_root(origin)?;

Expand All @@ -219,13 +251,13 @@ decl_module! {
if let Some(desc) = desc {
info.set_desc(desc);
}
AssetInfoOf::insert(id, info);
AssetInfoOf::<T>::insert(id, Some(info));
Ok(())
}
}
}

impl<T: Config> Module<T> {
impl<T: Config> Pallet<T> {
/// Returns an iterator of all the asset ids of all chains so far.
#[inline]
pub fn asset_ids() -> impl Iterator<Item = AssetId> {
Expand All @@ -240,13 +272,13 @@ impl<T: Config> Module<T> {

/// Returns an iterator of tuple (AssetId, AssetInfo) of all assets.
#[inline]
pub fn asset_infos() -> impl Iterator<Item = (AssetId, AssetInfo)> {
AssetInfoOf::iter()
pub fn asset_infos() -> impl Iterator<Item = (AssetId, Option<AssetInfo>)> {
AssetInfoOf::<T>::iter()
}

/// Returns an iterator of tuple (AssetId, AssetInfo) of all valid assets.
#[inline]
pub fn valid_asset_infos() -> impl Iterator<Item = (AssetId, AssetInfo)> {
pub fn valid_asset_infos() -> impl Iterator<Item = (AssetId, Option<AssetInfo>)> {
Self::asset_infos().filter(|(id, _)| Self::is_valid(id))
}

Expand Down Expand Up @@ -300,17 +332,30 @@ impl<T: Config> Module<T> {
/// Actually register an asset.
fn apply_register(id: AssetId, asset: AssetInfo) -> DispatchResult {
let chain = asset.chain();
AssetIdsOf::mutate(chain, |ids| {
AssetIdsOf::<T>::mutate(chain, |ids| {
if !ids.contains(&id) {
ids.push(id);
}
});

AssetInfoOf::insert(&id, asset);
AssetOnline::insert(&id, true);
AssetInfoOf::<T>::insert(&id, Some(asset));
AssetOnline::<T>::insert(&id, true);

RegisteredAt::<T>::insert(&id, frame_system::Pallet::<T>::block_number());

Ok(())
}
}

#[cfg(feature = "std")]
impl GenesisConfig {
/// Direct implementation of `GenesisBuild::assimilate_storage`.
///
/// Kept in order not to break dependency.
pub fn assimilate_storage<T: Config>(
&self,
storage: &mut sp_runtime::Storage,
) -> Result<(), String> {
<Self as GenesisBuild<T>>::assimilate_storage(self, storage)
}
}
Loading