Skip to content

feat: asset registry #728

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

Merged
merged 4 commits into from
May 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions Cargo.dev.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
[workspace]
members = [
"asset-registry",
"auction",
"authority",
"bencher",
Expand Down
68 changes: 68 additions & 0 deletions asset-registry/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
[package]
name = "orml-asset-registry"
description = "Registry for (foreign) assets"
repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/asset-registry"
license = "Apache-2.0"
version = "0.4.1-dev"
authors = ["Interlay Ltd, etc"]
edition = "2021"

[dependencies]
scale-info = { version = "2.0.1", default-features = false, features = ["derive"] }
serde = { version = "1.0.136", optional = true }
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20", default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20", default-features = false }
frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20", default-features = false }
frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20", default-features = false }
orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false }
xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.20", default-features = false }
xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.20", default-features = false }
xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.20", default-features = false }

[dev-dependencies]
sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20", default-features = false }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20" }
pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20" }

# cumulus
cumulus-primitives-core = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.20" }
cumulus-pallet-dmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.20" }
cumulus-pallet-xcmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.20" }
cumulus-pallet-xcm = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.20" }
parachain-info = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.20" }

# polkadot
polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.20" }
xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.20" }
xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.20" }
xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.20" }
pallet-xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.20" }
polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.20" }
xcm-simulator = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.20"}

orml-tokens = { path = "../tokens" }
orml-xtokens = { path = "../xtokens" }
orml-xcm = { path = "../xcm" }
orml-xcm-support = { path = "../xcm-support", default-features = false }

[features]
default = ["std"]
std = [
"serde",
"codec/std",
"scale-info/std",
"sp-runtime/std",
"sp-std/std",
"frame-support/std",
"frame-system/std",
"orml-traits/std",
"xcm/std",
"xcm-builder/std",
"xcm-executor/std",
]
runtime-benchmarks = [
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
]
try-runtime = ["frame-support/try-runtime"]
10 changes: 10 additions & 0 deletions asset-registry/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Asset Registry Module

## Overview

This module provides functionality for storing asset metadata. For each asset, it stores the number of decimals, asset name, asset symbol, existential deposit and (optional) location. Additionally, it stores a value of a generic type that chains can use to store any other metadata that the parachain may need (such as the fee rate, for example). It is designed to be easy to integrate into xcm setups. Various default implementations are provided for this purpose.

The pallet only contains two extrinsics, `register_asset` and `update_asset`:

- `register_asset` creates a new asset
- `update_asset` modifies some (or all) of the fields of an existing asset
171 changes: 171 additions & 0 deletions asset-registry/src/impls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
use crate::{module::*, AssetMetadata};
use frame_support::{log, pallet_prelude::*, weights::constants::WEIGHT_PER_SECOND};
use orml_traits::{
asset_registry::{AssetProcessor, FixedConversionRateProvider, WeightToFeeConverter},
GetByKey,
};
use sp_runtime::FixedPointNumber;
use sp_runtime::{
traits::{AtLeast32BitUnsigned, Bounded, CheckedAdd, One},
ArithmeticError, FixedU128,
};
use sp_std::prelude::*;
use xcm::v2::prelude::*;
use xcm_builder::TakeRevenue;
use xcm_executor::{traits::WeightTrader, Assets};

/// Alias for AssetMetadata to improve readability (and to placate clippy)
pub type DefaultAssetMetadata<T> = AssetMetadata<<T as Config>::Balance, <T as Config>::CustomMetadata>;

/// An AssetProcessor that assigns a sequential ID
pub struct SequentialId<T>(PhantomData<T>);

impl<T> AssetProcessor<T::AssetId, DefaultAssetMetadata<T>> for SequentialId<T>
where
T: Config,
T::AssetId: AtLeast32BitUnsigned,
{
fn pre_register(
id: Option<T::AssetId>,
asset_metadata: DefaultAssetMetadata<T>,
) -> Result<(T::AssetId, DefaultAssetMetadata<T>), DispatchError> {
let next_id = LastAssetId::<T>::get()
.checked_add(&T::AssetId::one())
.ok_or(ArithmeticError::Overflow)?;

match id {
Some(explicit_id) if explicit_id != next_id => {
// we don't allow non-sequential ids
Err(Error::<T>::InvalidAssetId.into())
}
_ => {
LastAssetId::<T>::put(&next_id);
Ok((next_id, asset_metadata))
}
}
}
}

/// A default implementation for WeightToFeeConverter that takes a fixed
/// conversion rate.
pub struct FixedRateAssetRegistryTrader<P: FixedConversionRateProvider>(PhantomData<P>);
impl<P: FixedConversionRateProvider> WeightToFeeConverter for FixedRateAssetRegistryTrader<P> {
fn convert_weight_to_fee(location: &MultiLocation, weight: Weight) -> Option<u128> {
let fee_per_second = P::get_fee_per_second(location)?;
let weight_ratio = FixedU128::saturating_from_rational(weight as u128, WEIGHT_PER_SECOND as u128);
let amount = weight_ratio.saturating_mul_int(fee_per_second);
Some(amount)
}
}

/// Helper struct for the AssetRegistryTrader that stores the data about
/// bought weight.
pub struct BoughtWeight {
weight: Weight,
asset_location: MultiLocation,
amount: u128,
}

/// A WeightTrader implementation that tries to buy weight using a single
/// currency. It tries all assets in `payment` and uses the first asset that can
/// cover the weight. This asset is then "locked in" - later calls to
/// `buy_weight` in the same xcm message only try the same asset.
/// This is because only a single asset can be refunded due to the return type
/// of `refund_weight`. This implementation assumes that `WeightToFeeConverter`
/// implements a linear function, i.e. fee(x) + fee(y) = fee(x+y).
pub struct AssetRegistryTrader<W: WeightToFeeConverter, R: TakeRevenue> {
bought_weight: Option<BoughtWeight>,
_phantom: PhantomData<(W, R)>,
}

impl<W: WeightToFeeConverter, R: TakeRevenue> WeightTrader for AssetRegistryTrader<W, R> {
fn new() -> Self {
Self {
bought_weight: None,
_phantom: Default::default(),
}
}

fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
log::trace!(
target: "xcm::weight",
"AssetRegistryTrader::buy_weight weight: {:?}, payment: {:?}",
weight, payment,
);

for (asset, _) in payment.fungible.iter() {
if let AssetId::Concrete(ref location) = asset {
if matches!(self.bought_weight, Some(ref bought) if &bought.asset_location != location) {
// we already bought another asset - don't attempt to buy this one since
// we won't be able to refund it
continue;
}

if let Some(fee_increase) = W::convert_weight_to_fee(location, weight) {
if fee_increase == 0 {
// if the fee is set very low it could lead to zero fees, in which case
// constructing the fee asset item to subtract from payment would fail.
// Therefore, provide early exit
return Ok(payment);
}

if let Ok(unused) = payment.clone().checked_sub((asset.clone(), fee_increase).into()) {
let (existing_weight, existing_fee) = match self.bought_weight {
Some(ref x) => (x.weight, x.amount),
None => (0, 0),
};

self.bought_weight = Some(BoughtWeight {
amount: existing_fee.checked_add(fee_increase).ok_or(XcmError::Overflow)?,
weight: existing_weight.checked_add(weight).ok_or(XcmError::Overflow)?,
asset_location: location.clone(),
});
return Ok(unused);
}
}
}
}
Err(XcmError::TooExpensive)
}

fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {
log::trace!(target: "xcm::weight", "AssetRegistryTrader::refund_weight weight: {:?}", weight);

match self.bought_weight {
Some(ref mut bought) => {
let new_weight = bought.weight.saturating_sub(weight);
let new_amount = W::convert_weight_to_fee(&bought.asset_location, new_weight)?;
let refunded_amount = bought.amount.saturating_sub(new_amount);

bought.weight = new_weight;
bought.amount = new_amount;

Some((AssetId::Concrete(bought.asset_location.clone()), refunded_amount).into())
}
None => None, // nothing to refund
}
}
}

impl<W: WeightToFeeConverter, R: TakeRevenue> Drop for AssetRegistryTrader<W, R> {
fn drop(&mut self) {
if let Some(ref bought) = self.bought_weight {
R::take_revenue((AssetId::Concrete(bought.asset_location.clone()), bought.amount).into());
}
}
}

pub struct ExistentialDeposits<T: Config>(PhantomData<T>);

// Return Existential deposit of an asset. Implementing this trait allows the
// pallet to be used in the tokens::ExistentialDeposits config item
impl<T: Config> GetByKey<T::AssetId, T::Balance> for ExistentialDeposits<T> {
fn get(k: &T::AssetId) -> T::Balance {
if let Some(metadata) = Pallet::<T>::metadata(k) {
metadata.existential_deposit
} else {
// Asset does not exist - not supported
T::Balance::max_value()
}
}
}
Loading