pallet-asset-conversion: Decoupling Native Currency Dependancy (#2031)

closes https://github.com/paritytech/polkadot-sdk/issues/1842

Decoupling Pallet from the Concept of Native Currency

Currently, the pallet is intrinsically linked with the concept of native
currency, requiring users to provide implementations of the
`fungible::*` and `fungibles::*` traits to interact with native and non
native assets. This incapsulates some non-related to the pallet
complexity and makes it less adaptable in contexts where the native
currency concept is absent.

With this PR, the dependence on `fungible::*` for liquidity-supplying
assets has been removed. Instead, the native and non-native currencies'
handling is now overseen by a single type that implements the
`fungibles::*` traits. To simplify this integration, types have been
introduced to facilitate the creation of a union between `fungible::*`
and `fungibles::*` implementations, producing a unified `fungibles::*`
type.

One of the reasons driving these changes is the ambition to create a
more user-friendly API for the `SwapCredit` implementation. Given that
it interacts with two distinct credit types from `fungible` and
`fungibles`, a unified type was introduced. Clients now manage potential
conversion failures for those credit types. In certain contexts, it's
vital to guarantee that operations are fail-safe, like in this impl -
[PR](https://github.com/paritytech/polkadot-sdk/pull/1845), place in
[code](https://github.com/paritytech/polkadot-sdk/blob/20b85a5fada8f55c98ba831964f5866ffeadf4da/cumulus/primitives/utility/src/lib.rs#L429).

Additional Updates:
- abstracted the pool ID and its account derivation logic via trait
bounds, along with common implementation offerings;
- removed `inc_providers` on a pool creation for the pool account;
- benchmarks:
-- swap complexity is N, not const;
-- removed `From<u128> + Into<u128>` bound from `T::Balance`;
-- removed swap/liquidity/.. amount constants, resolve them dynamically
based on pallet configuration;
-- migrated to v2 API;
- `OnUnbalanced` handler for the pool creation fee, replacing direct
transfers to a specified account ID;
- renamed `MultiAssetId` to `AssetKind` aligning with naming across
frame crates;

related PRs:
- (depends) https://github.com/paritytech/polkadot-sdk/pull/1677
- (caused) https://github.com/paritytech/polkadot-sdk/pull/2033
- (caused) https://github.com/paritytech/polkadot-sdk/pull/1876

---------

Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com>
Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
This commit is contained in:
Muharem
2023-12-20 13:57:26 +01:00
committed by GitHub
parent d32f66fb8f
commit 4f832ea865
26 changed files with 1750 additions and 4571 deletions
@@ -29,7 +29,7 @@ pub mod xcm_config;
use assets_common::{
foreign_creators::ForeignCreators,
local_and_foreign_assets::{LocalAndForeignAssets, MultiLocationConverter},
local_and_foreign_assets::{LocalFromLeft, TargetFromLeft},
matching::FromSiblingParachain,
AssetIdForTrustBackedAssetsConvert, MultiLocationForAssetId,
};
@@ -57,8 +57,9 @@ use frame_support::{
genesis_builder_helper::{build_config, create_default_config},
ord_parameter_types, parameter_types,
traits::{
AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, EitherOfDiverse,
Equals, InstanceFilter, TransformOrigin,
fungible, fungibles, tokens::imbalance::ResolveAssetTo, AsEnsureOriginWithArg, ConstBool,
ConstU128, ConstU32, ConstU64, ConstU8, EitherOfDiverse, Equals, InstanceFilter,
TransformOrigin,
},
weights::{ConstantMultiplier, Weight},
BoundedVec, PalletId,
@@ -82,8 +83,9 @@ use parachains_common::{
use sp_runtime::{Perbill, RuntimeDebug};
use xcm::opaque::v3::MultiLocation;
use xcm_config::{
ForeignAssetsConvertedConcreteId, GovernanceLocation, PoolAssetsConvertedConcreteId,
TokenLocation, TrustBackedAssetsConvertedConcreteId,
ForeignAssetsConvertedConcreteId, ForeignCreatorsSovereignAccountOf, GovernanceLocation,
PoolAssetsConvertedConcreteId, TokenLocation, TrustBackedAssetsConvertedConcreteId,
TrustBackedAssetsPalletLocation,
};
#[cfg(any(feature = "std", test))]
@@ -94,10 +96,6 @@ use pallet_xcm::{EnsureXcm, IsVoiceOfBody};
use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
use xcm::latest::prelude::*;
use crate::xcm_config::{
ForeignCreatorsSovereignAccountOf, LocalAndForeignAssetsMultiLocationMatcher,
TrustBackedAssetsPalletLocation,
};
use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
impl_opaque_keys! {
@@ -279,8 +277,6 @@ impl pallet_assets::Config<TrustBackedAssetsInstance> for Runtime {
parameter_types! {
pub const AssetConversionPalletId: PalletId = PalletId(*b"py/ascon");
pub const AllowMultiAssetPools: bool = false;
// should be non-zero if AllowMultiAssetPools is true, otherwise can be zero
pub const LiquidityWithdrawalFee: Permill = Permill::from_percent(0);
}
@@ -315,35 +311,50 @@ impl pallet_assets::Config<PoolAssetsInstance> for Runtime {
type BenchmarkHelper = ();
}
/// Union fungibles implementation for `Assets`` and `ForeignAssets`.
pub type LocalAndForeignAssets = fungibles::UnionOf<
Assets,
ForeignAssets,
LocalFromLeft<
AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation>,
AssetIdForTrustBackedAssets,
>,
MultiLocation,
AccountId,
>;
impl pallet_asset_conversion::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Balance = Balance;
type HigherPrecisionBalance = sp_core::U256;
type Currency = Balances;
type AssetId = MultiLocation;
type Assets = LocalAndForeignAssets<
Assets,
AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation>,
ForeignAssets,
type AssetKind = MultiLocation;
type Assets = fungible::UnionOf<
Balances,
LocalAndForeignAssets,
TargetFromLeft<TokenLocation>,
Self::AssetKind,
Self::AccountId,
>;
type PoolAssets = PoolAssets;
type PoolId = (Self::AssetKind, Self::AssetKind);
type PoolLocator =
pallet_asset_conversion::WithFirstAsset<TokenLocation, AccountId, Self::AssetKind>;
type PoolAssetId = u32;
type PoolAssets = PoolAssets;
type PoolSetupFee = ConstU128<0>; // Asset class deposit fees are sufficient to prevent spam
type PoolSetupFeeReceiver = AssetConversionOrigin;
// should be non-zero if `AllowMultiAssetPools` is true, otherwise can be zero.
type PoolSetupFeeAsset = TokenLocation;
type PoolSetupFeeTarget = ResolveAssetTo<AssetConversionOrigin, Self::Assets>;
type LiquidityWithdrawalFee = LiquidityWithdrawalFee;
type LPFee = ConstU32<3>;
type PalletId = AssetConversionPalletId;
type AllowMultiAssetPools = AllowMultiAssetPools;
type MaxSwapPathLength = ConstU32<4>;
type MultiAssetId = MultiLocation;
type MultiAssetIdConverter =
MultiLocationConverter<TokenLocation, LocalAndForeignAssetsMultiLocationMatcher>;
type MaxSwapPathLength = ConstU32<3>;
type MintMinLiquidity = ConstU128<100>;
type WeightInfo = weights::pallet_asset_conversion::WeightInfo<Runtime>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper =
crate::xcm_config::BenchmarkMultiLocationConverter<parachain_info::Pallet<Runtime>>;
type BenchmarkHelper = assets_common::benchmarks::AssetPairFactory<
TokenLocation,
parachain_info::Pallet<Runtime>,
xcm_config::AssetsPalletIndex,
>;
}
parameter_types! {
@@ -733,12 +744,9 @@ impl pallet_collator_selection::Config for Runtime {
impl pallet_asset_conversion_tx_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Fungibles = LocalAndForeignAssets<
Assets,
AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation>,
ForeignAssets,
>;
type OnChargeAssetTransaction = AssetConversionAdapter<Balances, AssetConversion>;
type Fungibles = LocalAndForeignAssets;
type OnChargeAssetTransaction =
AssetConversionAdapter<Balances, AssetConversion, TokenLocation>;
}
parameter_types! {
@@ -1154,7 +1162,7 @@ impl_runtime_apis! {
}
fn get_reserves(asset1: MultiLocation, asset2: MultiLocation) -> Option<(Balance, Balance)> {
AssetConversion::get_reserves(&asset1, &asset2).ok()
AssetConversion::get_reserves(asset1, asset2).ok()
}
}
@@ -17,25 +17,23 @@
//! Autogenerated weights for `pallet_asset_conversion`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2023-07-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! DATE: 2023-10-30, STEPS: `20`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz`
//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-rococo-dev")`, DB CACHE: 1024
//! HOSTNAME: `cob`, CPU: `<UNKNOWN>`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-rococo-dev")`, DB CACHE: 1024
// Executed Command:
// target/production/polkadot-parachain
// ./target/debug/polkadot-parachain
// benchmark
// pallet
// --steps=50
// --repeat=20
// --chain=asset-hub-rococo-dev
// --steps=20
// --repeat=2
// --pallet=pallet-asset-conversion
// --extrinsic=*
// --wasm-execution=compiled
// --heap-pages=4096
// --json-file=/builds/parity/mirrors/cumulus/.git/.artifacts/bench.json
// --pallet=pallet_asset_conversion
// --chain=asset-hub-rococo-dev
// --header=./file_header.txt
// --output=./parachains/runtimes/assets/asset-hub-rococo/src/weights/
// --output=./cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_asset_conversion.rs
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
@@ -50,9 +48,7 @@ pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_asset_conversion::WeightInfo for WeightInfo<T> {
/// Storage: `AssetConversion::Pools` (r:1 w:1)
/// Proof: `AssetConversion::Pools` (`max_values`: None, `max_size`: Some(1224), added: 3699, mode: `MaxEncodedLen`)
/// Storage: UNKNOWN KEY `0x76a2c49709deec21d9c05f96c1f47351` (r:1 w:0)
/// Proof: UNKNOWN KEY `0x76a2c49709deec21d9c05f96c1f47351` (r:1 w:0)
/// Storage: `System::Account` (r:2 w:1)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// Storage: `ForeignAssets::Account` (r:1 w:1)
/// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`)
@@ -66,22 +62,22 @@ impl<T: frame_system::Config> pallet_asset_conversion::WeightInfo for WeightInfo
/// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`)
fn create_pool() -> Weight {
// Proof Size summary in bytes:
// Measured: `480`
// Estimated: `6196`
// Minimum execution time: 88_484_000 picoseconds.
Weight::from_parts(92_964_000, 0)
.saturating_add(Weight::from_parts(0, 6196))
.saturating_add(T::DbWeight::get().reads(9))
// Measured: `408`
// Estimated: `4689`
// Minimum execution time: 906_000_000 picoseconds.
Weight::from_parts(945_000_000, 0)
.saturating_add(Weight::from_parts(0, 4689))
.saturating_add(T::DbWeight::get().reads(7))
.saturating_add(T::DbWeight::get().writes(7))
}
/// Storage: `AssetConversion::Pools` (r:1 w:0)
/// Proof: `AssetConversion::Pools` (`max_values`: None, `max_size`: Some(1224), added: 3699, mode: `MaxEncodedLen`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// Storage: `ForeignAssets::Asset` (r:1 w:1)
/// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`)
/// Storage: `ForeignAssets::Account` (r:2 w:2)
/// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// Storage: `PoolAssets::Asset` (r:1 w:1)
/// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`)
/// Storage: `PoolAssets::Account` (r:2 w:2)
@@ -90,34 +86,32 @@ impl<T: frame_system::Config> pallet_asset_conversion::WeightInfo for WeightInfo
// Proof Size summary in bytes:
// Measured: `1117`
// Estimated: `7404`
// Minimum execution time: 153_015_000 picoseconds.
Weight::from_parts(157_018_000, 0)
// Minimum execution time: 1_609_000_000 picoseconds.
Weight::from_parts(1_631_000_000, 0)
.saturating_add(Weight::from_parts(0, 7404))
.saturating_add(T::DbWeight::get().reads(8))
.saturating_add(T::DbWeight::get().writes(7))
}
/// Storage: `AssetConversion::Pools` (r:1 w:0)
/// Proof: `AssetConversion::Pools` (`max_values`: None, `max_size`: Some(1224), added: 3699, mode: `MaxEncodedLen`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// Storage: `ForeignAssets::Asset` (r:1 w:1)
/// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`)
/// Storage: `ForeignAssets::Account` (r:2 w:2)
/// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// Storage: `PoolAssets::Asset` (r:1 w:1)
/// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`)
/// Storage: UNKNOWN KEY `0x2433d831722b1f4aeb1666953f1c0e77` (r:1 w:0)
/// Proof: UNKNOWN KEY `0x2433d831722b1f4aeb1666953f1c0e77` (r:1 w:0)
/// Storage: `PoolAssets::Account` (r:1 w:1)
/// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`)
fn remove_liquidity() -> Weight {
// Proof Size summary in bytes:
// Measured: `1106`
// Estimated: `7404`
// Minimum execution time: 141_726_000 picoseconds.
Weight::from_parts(147_865_000, 0)
// Minimum execution time: 1_480_000_000 picoseconds.
Weight::from_parts(1_506_000_000, 0)
.saturating_add(Weight::from_parts(0, 7404))
.saturating_add(T::DbWeight::get().reads(8))
.saturating_add(T::DbWeight::get().reads(7))
.saturating_add(T::DbWeight::get().writes(6))
}
/// Storage: `ForeignAssets::Asset` (r:2 w:2)
@@ -126,15 +120,19 @@ impl<T: frame_system::Config> pallet_asset_conversion::WeightInfo for WeightInfo
/// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`)
/// Storage: `System::Account` (r:2 w:2)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn swap_exact_tokens_for_tokens() -> Weight {
/// The range of component `n` is `[2, 3]`.
fn swap_exact_tokens_for_tokens(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `1148`
// Estimated: `13818`
// Minimum execution time: 168_619_000 picoseconds.
Weight::from_parts(174_283_000, 0)
.saturating_add(Weight::from_parts(0, 13818))
.saturating_add(T::DbWeight::get().reads(8))
.saturating_add(T::DbWeight::get().writes(8))
// Measured: `0 + n * (557 ±0)`
// Estimated: `7404 + n * (393 ±73)`
// Minimum execution time: 933_000_000 picoseconds.
Weight::from_parts(950_000_000, 0)
.saturating_add(Weight::from_parts(0, 7404))
// Standard Error: 18_792_550
.saturating_add(Weight::from_parts(46_683_673, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(4))
.saturating_add(T::DbWeight::get().writes(4))
.saturating_add(Weight::from_parts(0, 393).saturating_mul(n.into()))
}
/// Storage: `System::Account` (r:2 w:2)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
@@ -142,14 +140,18 @@ impl<T: frame_system::Config> pallet_asset_conversion::WeightInfo for WeightInfo
/// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`)
/// Storage: `ForeignAssets::Account` (r:4 w:4)
/// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`)
fn swap_tokens_for_exact_tokens() -> Weight {
/// The range of component `n` is `[2, 3]`.
fn swap_tokens_for_exact_tokens(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `1148`
// Estimated: `13818`
// Minimum execution time: 171_565_000 picoseconds.
Weight::from_parts(173_702_000, 0)
.saturating_add(Weight::from_parts(0, 13818))
.saturating_add(T::DbWeight::get().reads(8))
.saturating_add(T::DbWeight::get().writes(8))
// Measured: `0 + n * (557 ±0)`
// Estimated: `7404 + n * (393 ±180)`
// Minimum execution time: 936_000_000 picoseconds.
Weight::from_parts(954_000_000, 0)
.saturating_add(Weight::from_parts(0, 7404))
// Standard Error: 15_942_881
.saturating_add(Weight::from_parts(39_755_102, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(4))
.saturating_add(T::DbWeight::get().writes(4))
.saturating_add(Weight::from_parts(0, 393).saturating_mul(n.into()))
}
}
@@ -56,9 +56,6 @@ use xcm_builder::{
};
use xcm_executor::{traits::WithOriginFilter, XcmExecutor};
#[cfg(feature = "runtime-benchmarks")]
use cumulus_primitives_core::ParaId;
parameter_types! {
pub const TokenLocation: MultiLocation = MultiLocation::parent();
pub const RelayNetwork: NetworkId = NetworkId::Rococo;
@@ -66,8 +63,8 @@ parameter_types! {
pub UniversalLocation: InteriorMultiLocation =
X2(GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into()));
pub UniversalLocationNetworkId: NetworkId = UniversalLocation::get().global_consensus().unwrap();
pub TrustBackedAssetsPalletLocation: MultiLocation =
PalletInstance(<Assets as PalletInfoAccess>::index() as u8).into();
pub AssetsPalletIndex: u32 = <Assets as PalletInfoAccess>::index() as u32;
pub TrustBackedAssetsPalletLocation: MultiLocation = PalletInstance(AssetsPalletIndex::get() as u8).into();
pub ForeignAssetsPalletLocation: MultiLocation =
PalletInstance(<ForeignAssets as PalletInfoAccess>::index() as u8).into();
pub PoolAssetsPalletLocation: MultiLocation =
@@ -672,32 +669,6 @@ impl pallet_assets::BenchmarkHelper<MultiLocation> for XcmBenchmarkHelper {
}
}
#[cfg(feature = "runtime-benchmarks")]
pub struct BenchmarkMultiLocationConverter<SelfParaId> {
_phantom: sp_std::marker::PhantomData<SelfParaId>,
}
#[cfg(feature = "runtime-benchmarks")]
impl<SelfParaId> pallet_asset_conversion::BenchmarkHelper<MultiLocation, MultiLocation>
for BenchmarkMultiLocationConverter<SelfParaId>
where
SelfParaId: frame_support::traits::Get<ParaId>,
{
fn asset_id(asset_id: u32) -> MultiLocation {
MultiLocation {
parents: 1,
interior: X3(
Parachain(SelfParaId::get().into()),
PalletInstance(<Assets as PalletInfoAccess>::index() as u8),
GeneralIndex(asset_id.into()),
),
}
}
fn multiasset_id(asset_id: u32) -> MultiLocation {
Self::asset_id(asset_id)
}
}
/// All configuration related to bridging
pub mod bridging {
use super::*;