diff --git a/pallets/lend-market/src/mock.rs b/pallets/lend-market/src/mock.rs index 5f53011455..4bb03a75cb 100644 --- a/pallets/lend-market/src/mock.rs +++ b/pallets/lend-market/src/mock.rs @@ -22,10 +22,6 @@ use frame_support::{ use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy}; pub use node_primitives::*; use orml_traits::{DataFeeder, DataProvider, DataProviderExtended}; -use pallet_traits::{ - DecimalProvider, ExchangeRateProvider, LiquidStakingCurrenciesProvider, - VaultTokenCurrenciesFilter, VaultTokenExchangeRateProvider, -}; use sp_core::H256; use sp_runtime::{testing::Header, traits::IdentityLookup, AccountId32}; use sp_std::vec::Vec; @@ -222,55 +218,6 @@ impl DataFeeder for MockDataProvider { } } -pub struct LiquidStakingExchangeRateProvider; -impl ExchangeRateProvider for LiquidStakingExchangeRateProvider { - fn get_exchange_rate(_: &CurrencyId) -> Option { - Some(Rate::saturating_from_rational(150, 100)) - } -} - -pub struct Decimal; -impl DecimalProvider for Decimal { - fn get_decimal(asset_id: &CurrencyId) -> Option { - match *asset_id { - KSM | VKSM => Some(12), - BNC => Some(12), - DOT_U => Some(12), - _ => Some(12), - } - } -} - -pub struct LiquidStaking; -impl LiquidStakingCurrenciesProvider for LiquidStaking { - fn get_staking_currency() -> Option { - Some(KSM) - } - fn get_liquid_currency() -> Option { - Some(VKSM) - } -} - -impl ExchangeRateProvider for LiquidStaking { - fn get_exchange_rate(_: &CurrencyId) -> Option { - Some(Rate::saturating_from_rational(150, 100)) - } -} - -pub struct TokenExchangeRateProvider; -impl VaultTokenExchangeRateProvider for TokenExchangeRateProvider { - fn get_exchange_rate(_: &CurrencyId, _: Rate) -> Option { - Some(Rate::saturating_from_rational(100, 150)) - } -} - -pub struct TokenCurrenciesFilter; -impl VaultTokenCurrenciesFilter for TokenCurrenciesFilter { - fn contains(_asset_id: &CurrencyId) -> bool { - return false; - } -} - pub struct VaultLoansRateProvider; impl LoansMarketDataProvider for VaultLoansRateProvider { fn get_full_interest_rate(_asset_id: CurrencyId) -> Option { diff --git a/pallets/prices/src/mock.rs b/pallets/prices/src/mock.rs index 5df8a0e4b7..3a73e58aae 100644 --- a/pallets/prices/src/mock.rs +++ b/pallets/prices/src/mock.rs @@ -115,20 +115,6 @@ impl DataFeeder for MockDataProvider { } } -pub struct LiquidStakingExchangeRateProvider; -impl ExchangeRateProvider for LiquidStakingExchangeRateProvider { - fn get_exchange_rate(_: &CurrencyId) -> Option { - Some(Rate::saturating_from_rational(150, 100)) - } -} - -pub struct TokenExchangeRateProvider; -impl VaultTokenExchangeRateProvider for TokenExchangeRateProvider { - fn get_exchange_rate(_: &CurrencyId, _: Rate) -> Option { - Some(Rate::saturating_from_rational(100, 150)) - } -} - ord_parameter_types! { pub const One: AccountId = 1; } diff --git a/pallets/prices/src/tests.rs b/pallets/prices/src/tests.rs index c68c2ce188..184539442b 100644 --- a/pallets/prices/src/tests.rs +++ b/pallets/prices/src/tests.rs @@ -163,25 +163,7 @@ fn reset_price_call_work() { } #[test] -fn get_liquid_price_work() { - new_test_ext().execute_with(|| { - assert_eq!( - Prices::get_price(&DOT), - Some((Price::from_inner(10_000_000_000 * PRICE_ONE), 0)) - ); - - assert_eq!( - Prices::get_price(&VDOT), - LiquidStakingExchangeRateProvider::get_exchange_rate(&VDOT) - .unwrap() - .checked_mul_int(10_000_000_000 * PRICE_ONE) - .map(|i| (Price::from_inner(i), 0)) - ); - }); -} - -#[test] -fn get_ctoken_price_work() { +fn get_token_price_work() { new_test_ext().execute_with(|| { assert_eq!( Prices::get_price(&DOT), @@ -196,7 +178,7 @@ fn get_ctoken_price_work() { } #[test] -fn get_foreign_ctoken_price_work() { +fn get_foreign_token_price_work() { new_test_ext().execute_with(|| { assert_eq!( Prices::get_price(&DOT), diff --git a/pallets/traits/src/lib.rs b/pallets/traits/src/lib.rs index e81ef4bf51..e17747f4ef 100644 --- a/pallets/traits/src/lib.rs +++ b/pallets/traits/src/lib.rs @@ -1,17 +1,9 @@ #![cfg_attr(not(feature = "std"), no_std)] -use codec::{Decode, Encode, MaxEncodedLen}; -use frame_support::{dispatch::DispatchError, traits::tokens::Balance as BalanceT}; use num_bigint::{BigUint, ToBigUint}; -use scale_info::TypeInfo; -use sp_runtime::{traits::Zero, RuntimeDebug}; -use sp_std::prelude::*; - -use primitives::{CurrencyId, DerivativeIndex, PriceDetail, Rate, Timestamp}; +use primitives::{CurrencyId, PriceDetail}; pub mod loans; -pub mod ump; -// pub mod xcm; pub use loans::*; pub trait EmergencyCallFilter { @@ -22,169 +14,11 @@ pub trait PriceFeeder { fn get_price(asset_id: &CurrencyId) -> Option; } -pub trait DecimalProvider { - fn get_decimal(asset_id: &CurrencyId) -> Option; -} - pub trait EmergencyPriceFeeder { fn set_emergency_price(asset_id: CurrencyId, price: Price); fn reset_emergency_price(asset_id: CurrencyId); } -pub trait ExchangeRateProvider { - fn get_exchange_rate(asset_id: &CurrencyId) -> Option; -} - -pub trait LiquidStakingConvert { - fn staking_to_liquid(amount: Balance) -> Option; - fn liquid_to_staking(liquid_amount: Balance) -> Option; -} - -pub trait LiquidStakingCurrenciesProvider { - fn get_staking_currency() -> Option; - fn get_liquid_currency() -> Option; -} - -pub trait VaultTokenExchangeRateProvider { - fn get_exchange_rate(asset_id: &CurrencyId, init_rate: Rate) -> Option; -} - -pub trait LPVaultTokenExchangeRateProvider { - fn get_exchange_rate(lp_asset_id: &CurrencyId) -> Option; -} - -pub trait VaultTokenCurrenciesFilter { - fn contains(asset_id: &CurrencyId) -> bool; -} - -pub trait LPVaultTokenCurrenciesFilter { - fn contains(lp_asset_id: &CurrencyId) -> bool; -} - -#[derive( - Encode, - Decode, - Eq, - PartialEq, - Copy, - Clone, - RuntimeDebug, - PartialOrd, - Ord, - TypeInfo, - MaxEncodedLen, -)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -pub struct Pool { - pub base_amount: Balance, - pub quote_amount: Balance, - pub base_amount_last: Balance, - pub quote_amount_last: Balance, - pub lp_token_id: CurrencyId, - pub block_timestamp_last: BlockNumber, - pub price_0_cumulative_last: Balance, - pub price_1_cumulative_last: Balance, -} - -impl Pool { - pub fn new(lp_token_id: CurrencyId) -> Self { - Self { - base_amount: Zero::zero(), - quote_amount: Zero::zero(), - base_amount_last: Zero::zero(), - quote_amount_last: Zero::zero(), - lp_token_id, - block_timestamp_last: Zero::zero(), - price_0_cumulative_last: Zero::zero(), - price_1_cumulative_last: Zero::zero(), - } - } - - pub fn is_empty(&self) -> bool { - self.base_amount.is_zero() && self.quote_amount.is_zero() - } -} - -/// Exported traits from our AMM pallet. These functions are to be used -/// by the router to enable multi route token swaps -pub trait AMM { - /// Based on the path specified and the available pool balances - /// this will return the amounts outs when trading the specified - /// amount in - fn get_amounts_out( - amount_in: Balance, - path: Vec, - ) -> Result, DispatchError>; - - /// Based on the path specified and the available pool balances - /// this will return the amounts in needed to produce the specified - /// amount out - fn get_amounts_in( - amount_out: Balance, - path: Vec, - ) -> Result, DispatchError>; - - /// Handles a "swap" on the AMM side for "who". - /// This will move the `amount_in` funds to the AMM PalletId, - /// trade `pair.0` to `pair.1` and return a result with the amount - /// of currency that was sent back to the user. - fn swap( - who: &AccountId, - pair: (CurrencyId, CurrencyId), - amount_in: Balance, - ) -> Result<(), DispatchError>; - - /// Iterate keys of asset pair in AMM Pools - fn get_pools() -> Result, DispatchError>; - - /// Returns pool by lp_asset - fn get_pool_by_lp_asset( - asset_id: CurrencyId, - ) -> Option<(CurrencyId, CurrencyId, Pool)>; - - /// Returns pool by asset pair - fn get_pool_by_asset_pair( - pair: (CurrencyId, CurrencyId), - ) -> Option>; -} - -/// Exported traits from StableSwap pallet. These functions are to be used -/// by the router. -pub trait StableSwap { - /// Based on the path specified and the available pool balances - /// this will return the amounts outs when trading the specified - /// amount in - fn get_amounts_out( - amount_in: Balance, - path: Vec, - ) -> Result, DispatchError>; - - /// Based on the path specified and the available pool balances - /// this will return the amounts in needed to produce the specified - /// amount out - fn get_amounts_in( - amount_out: Balance, - path: Vec, - ) -> Result, DispatchError>; - - /// Handles a "swap" on the AMM side for "who". - /// This will move the `amount_in` funds to the AMM PalletId, - /// trade `pair.0` to `pair.1` and return a result with the amount - /// of currency that was sent back to the user. - fn swap( - who: &AccountId, - pair: (CurrencyId, CurrencyId), - amount_in: Balance, - ) -> Result<(), DispatchError>; - - fn get_pools() -> Result, DispatchError>; - - fn get_reserves( - asset_in: CurrencyId, - asset_out: CurrencyId, - ) -> Result<(Balance, Balance), DispatchError>; -} - pub trait ConvertToBigUint { fn get_big_uint(&self) -> BigUint; } @@ -195,56 +29,6 @@ impl ConvertToBigUint for u128 { } } -/// Get relaychain validation data -// pub trait ValidationDataProvider { -// fn validation_data() -> Option; -// } - -/// Distribute liquidstaking asset to multi-accounts -pub trait DistributionStrategy { - fn get_bond_distributions( - bonded_amounts: Vec<(DerivativeIndex, Balance, Balance)>, - input: Balance, - cap: Balance, - min_nominator_bond: Balance, - ) -> Vec<(DerivativeIndex, Balance)>; - fn get_unbond_distributions( - active_bonded_amounts: Vec<(DerivativeIndex, Balance)>, - input: Balance, - min_nominator_bond: Balance, - ) -> Vec<(DerivativeIndex, Balance)>; - fn get_rebond_distributions( - unbonding_amounts: Vec<(DerivativeIndex, Balance)>, - input: Balance, - ) -> Vec<(DerivativeIndex, Balance)>; -} - -pub trait Streaming { - fn create( - sender: AccountId, - recipient: AccountId, - deposit: Balance, - asset_id: CurrencyId, - start_time: Timestamp, - end_time: Timestamp, - cancellable: bool, - ) -> Result<(), DispatchError>; -} - -impl Streaming for () { - fn create( - _sender: AccountId, - _recipient: AccountId, - _deposit: Balance, - _asset_id: CurrencyId, - _start_time: Timestamp, - _end_time: Timestamp, - _cancellable: bool, - ) -> Result<(), DispatchError> { - Ok(()) - } -} - pub trait OnExchangeRateChange { fn on_exchange_rate_change(currency_id: &CurrencyId); } diff --git a/pallets/traits/src/ump.rs b/pallets/traits/src/ump.rs deleted file mode 100644 index c25ca97c40..0000000000 --- a/pallets/traits/src/ump.rs +++ /dev/null @@ -1,341 +0,0 @@ -use codec::{Decode, Encode, MaxEncodedLen}; -use frame_support::pallet_prelude::Weight; -use frame_system::Config; -use primitives::{AccountId, Balance, BlockNumber, ParaId}; -use scale_info::TypeInfo; -use sp_runtime::{traits::StaticLookup, MultiSignature, RuntimeDebug}; -use sp_std::{boxed::Box, vec::Vec}; -use xcm::latest::MultiLocation; - -/// A destination account for payment. -#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub enum RewardDestination { - /// Pay into the stash account, increasing the amount at stake accordingly. - Staked, - /// Pay into the stash account, not increasing the amount at stake. - Stash, - /// Pay into the controller account. - Controller, - /// Pay into a specified account. - Account(AccountId), - /// Receive no reward. - None, -} - -/// Relaychain staking.bond call arguments -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct StakingBondCall { - /// Controller account - pub controller: ::Source, - /// Bond amount - #[codec(compact)] - pub value: u128, - /// A destination account for payment. - pub payee: RewardDestination, -} - -/// Relaychain staking.bond_extra call arguments -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct StakingBondExtraCall { - /// Rebond amount - #[codec(compact)] - pub value: u128, -} - -/// Relaychain staking.unbond call arguments -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct StakingUnbondCall { - /// Unbond amount - #[codec(compact)] - pub value: u128, -} - -/// Relaychain staking.rebond call arguments -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct StakingRebondCall { - /// Rebond amount - #[codec(compact)] - pub value: u128, -} - -/// Relaychain staking.withdraw_unbonded call arguments -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct StakingWithdrawUnbondedCall { - /// Withdraw amount - pub num_slashing_spans: u32, -} - -/// Relaychain staking.nominate call arguments -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct StakingNominateCall { - /// List of nominate `targets` - pub targets: Vec<::Source>, -} - -/// Relaychain staking.payout_stakers call arguments -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct StakingPayoutStakersCall { - /// Stash account of validator - pub validator_stash: T::AccountId, - /// EraIndex - pub era: u32, -} - -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] -pub enum StakingCall { - #[codec(index = 0)] - Bond(StakingBondCall), - #[codec(index = 1)] - BondExtra(StakingBondExtraCall), - #[codec(index = 2)] - Unbond(StakingUnbondCall), - #[codec(index = 3)] - WithdrawUnbonded(StakingWithdrawUnbondedCall), - #[codec(index = 5)] - Nominate(StakingNominateCall), - #[codec(index = 18)] - PayoutStakers(StakingPayoutStakersCall), - #[codec(index = 19)] - Rebond(StakingRebondCall), -} - -/// Relaychain balances.transfer_keep_alive call arguments -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct BalancesTransferKeepAliveCall { - /// dest account - pub dest: ::Source, - /// transfer amount - #[codec(compact)] - pub value: u128, -} - -/// Relaychain balances.transfer_all call arguments -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct BalancesTransferAllCall { - /// dest account - pub dest: ::Source, - pub keep_alive: bool, -} - -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] -pub enum BalancesCall { - #[codec(index = 3)] - TransferKeepAlive(BalancesTransferKeepAliveCall), - #[codec(index = 4)] - TransferAll(BalancesTransferAllCall), -} - -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct CrowdloansContributeCall { - /// - `crowdloan`: The crowdloan who you are contributing to - #[codec(compact)] - pub index: ParaId, - /// - `value`: The amount of tokens you want to contribute to a parachain. - #[codec(compact)] - pub value: u128, - // `signature`: The signature if the fund has a verifier - pub signature: Option, -} - -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct CrowdloansWithdrawCall { - /// - `who`: The account whose contribution should be withdrawn. - pub who: T::AccountId, - /// - `index`: The parachain to whose crowdloan the contribution was made. - #[codec(compact)] - pub index: ParaId, -} - -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct CrowdloansAddMemoCall { - /// - `index`: The parachain to whose crowdloan the contribution was made. - pub index: ParaId, - pub memo: Vec, -} - -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub enum CrowdloansCall { - #[codec(index = 1)] - Contribute(CrowdloansContributeCall), - #[codec(index = 2)] - Withdraw(CrowdloansWithdrawCall), - #[codec(index = 6)] - AddMemo(CrowdloansAddMemoCall), -} - -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct SystemRemarkCall { - pub remark: Vec, -} - -#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub enum SystemCall { - #[codec(index = 1)] - Remark(SystemRemarkCall), -} - -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct ProxyProxyCall { - pub real: AccountId, - pub force_proxy_type: Option, - pub call: RelaychainCall, -} - -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct ProxyAddProxyCall { - pub delegate: AccountId, - pub proxy_type: Option, - pub delay: BlockNumber, -} - -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct ProxyRemoveProxyCall { - pub delegate: AccountId, - pub proxy_type: Option, - pub delay: BlockNumber, -} - -/// The type used to represent the kinds of proxying allowed. -#[derive( - Copy, - Clone, - Eq, - PartialEq, - Ord, - PartialOrd, - Encode, - Decode, - RuntimeDebug, - MaxEncodedLen, - TypeInfo, -)] -pub enum ProxyType { - Any = 0_isize, - NonTransfer = 1_isize, - Governance = 2_isize, - Staking = 3_isize, -} - -impl Default for ProxyType { - fn default() -> Self { - Self::Any - } -} - -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] -pub enum ProxyCall { - #[codec(index = 0)] - Proxy(ProxyProxyCall), - #[codec(index = 1)] - AddProxy(ProxyAddProxyCall), - #[codec(index = 2)] - RemoveProxy(ProxyRemoveProxyCall), -} - -/// Relaychain utility.as_derivative call arguments -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct UtilityAsDerivativeCall { - /// derivative index - pub index: u16, - /// call - pub call: RelaychainCall, -} - -/// Relaychain utility.batch_all call arguments -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct UtilityBatchAllCall { - /// calls - pub calls: Vec, -} - -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] -pub enum UtilityCall { - #[codec(index = 1)] - AsDerivative(UtilityAsDerivativeCall), - #[codec(index = 2)] - BatchAll(UtilityBatchAllCall), -} - -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] -pub enum KusamaCall { - #[codec(index = 0)] - System(SystemCall), - #[codec(index = 4)] - Balances(BalancesCall), - #[codec(index = 6)] - Staking(StakingCall), - #[codec(index = 22)] - Proxy(Box>), - #[codec(index = 24)] - Utility(Box>), - #[codec(index = 73)] - Crowdloans(CrowdloansCall), -} - -#[derive(Encode, Decode, RuntimeDebug, TypeInfo)] -pub enum PolkadotCall { - #[codec(index = 0)] - System(SystemCall), - #[codec(index = 5)] - Balances(BalancesCall), - #[codec(index = 7)] - Staking(StakingCall), - #[codec(index = 26)] - Utility(Box>), - #[codec(index = 29)] - Proxy(Box>), - #[codec(index = 73)] - Crowdloans(CrowdloansCall), -} - -#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] -pub struct XcmWeightFeeMisc { - pub weight: Weight, - pub fee: Balance, -} - -impl Default for XcmWeightFeeMisc { - fn default() -> Self { - let default_weight = 20_000_000_000u64; - let default_fee = 15_000_000_000; - let default_proof_size: u64 = 64 * 1024; - XcmWeightFeeMisc { - weight: Weight::from_parts(default_weight, default_proof_size), - fee: default_fee, - } - } -} - -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub enum XcmCall { - Bond, - BondExtra, - Unbond, - Rebond, - WithdrawUnbonded, - Nominate, - Contribute, - Withdraw, - AddMemo, - TransferToSiblingchain(Box), - Proxy, - AddProxy, - RemoveProxy, -} - -#[macro_export] -macro_rules! switch_relay { - ({ $( $code:tt )* }) => { - if ::RelayNetwork::get() == NetworkId::Polkadot { - use pallet_traits::ump::PolkadotCall as RelaychainCall; - - $( $code )* - } else if ::RelayNetwork::get() == NetworkId::Kusama { - use pallet_traits::ump::KusamaCall as RelaychainCall; - - $( $code )* - } else { - unreachable!() - } - } -} diff --git a/pallets/traits/src/xcm.rs b/pallets/traits/src/xcm.rs deleted file mode 100644 index 20549ae409..0000000000 --- a/pallets/traits/src/xcm.rs +++ /dev/null @@ -1,628 +0,0 @@ -// // Copyright 2021 Parallel Finance Developer. -// // This file is part of Parallel Finance. - -// // Licensed under the Apache License, Version 2.0 (the "License"); -// // you may not use this file except in compliance with the License. -// // You may obtain a copy of the License at -// // http://www.apache.org/licenses/LICENSE-2.0 - -// // Unless required by applicable law or agreed to in writing, software -// // distributed under the License is distributed on an "AS IS" BASIS, -// // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// // See the License for the specific language governing permissions and -// // limitations under the License. - -// use crate::CurrencyId; - -// use codec::{Decode, Encode}; -// use frame_support::{ -// traits::{ -// tokens::{ -// fungibles::{Inspect, Mutate}, -// BalanceConversion, -// }, -// Get, -// }, -// weights::constants::WEIGHT_REF_TIME_PER_SECOND, -// }; -// use primitives::ParaId; -// use scale_info::TypeInfo; -// use sp_core::H256; -// use sp_runtime::traits::{BlakeTwo256, Convert, Hash as THash, SaturatedConversion, Zero}; -// use sp_std::{borrow::Borrow, marker::PhantomData, result}; -// use xcm::latest::{ -// prelude::*, AssetId as xcmAssetId, Error as XcmError, Fungibility, Junction::AccountId32, -// MultiLocation, Weight, -// }; -// use xcm_builder::TakeRevenue; -// use xcm_executor::traits::{ -// Convert as MoreConvert, MatchesFungible, MatchesFungibles, TransactAsset, WeightTrader, -// }; - -// /// Converter struct implementing `AssetIdConversion` converting a numeric asset ID -// /// (must be `TryFrom/TryInto`) into a MultiLocation Value and Viceversa through -// /// an intermediate generic type AssetType. -// /// The trait bounds enforce is that the AssetTypeGetter trait is also implemented for -// /// AssetIdInfoGetter -// pub struct AsAssetType( -// PhantomData<(AssetId, AssetType, AssetIdInfoGetter)>, -// ); -// impl xcm_executor::traits::Convert -// for AsAssetType -// where -// AssetId: Clone, -// AssetType: From + Into> + Clone, -// AssetIdInfoGetter: AssetTypeGetter, -// { -// fn convert_ref(id: impl Borrow) -> Result { -// if let Some(asset_id) = AssetIdInfoGetter::get_asset_id((*id.borrow()).into()) { -// Ok(asset_id) -// } else { -// Err(()) -// } -// } - -// fn reverse_ref(what: impl Borrow) -> Result { -// if let Some(asset_type) = AssetIdInfoGetter::get_asset_type(what.borrow().clone()) { -// if let Some(location) = asset_type.into() { -// Ok(location) -// } else { -// Err(()) -// } -// } else { -// Err(()) -// } -// } -// } - -// /// Instructs how to convert accountId into a MultiLocation -// pub struct AccountIdToMultiLocation(sp_std::marker::PhantomData); -// impl sp_runtime::traits::Convert -// for AccountIdToMultiLocation -// where -// AccountId: Into<[u8; 32]>, -// { -// fn convert(account: AccountId) -> MultiLocation { -// MultiLocation { -// parents: 0, -// interior: X1(AccountId32 { network: None, id: account.into() }), -// } -// } -// } - -// // We need to know how to charge for incoming assets -// // This takes the first fungible asset, and takes whatever UnitPerSecondGetter establishes -// // UnitsToWeightRatio trait, which needs to be implemented by AssetIdInfoGetter -// pub struct FirstAssetTrader< -// AssetType: From + Clone, -// AssetIdInfoGetter: UnitsToWeightRatio, -// R: TakeRevenue, -// >(Weight, Option<(MultiLocation, u128, u128)>, PhantomData<(AssetType, AssetIdInfoGetter, R)>); -// impl< -// AssetType: From + Clone, -// AssetIdInfoGetter: UnitsToWeightRatio, -// R: TakeRevenue, -// > WeightTrader for FirstAssetTrader -// { -// fn new() -> Self { -// FirstAssetTrader(Weight::zero(), None, PhantomData) -// } - -// fn buy_weight( -// &mut self, -// weight: Weight, -// payment: xcm_executor::Assets, -// ) -> Result { -// let first_asset = payment.fungible_assets_iter().next().ok_or(XcmError::TooExpensive)?; - -// // We are only going to check first asset for now. This should be sufficient for simple -// // token transfers. We will see later if we change this. -// match (first_asset.id, first_asset.fun) { -// (xcmAssetId::Concrete(id), Fungibility::Fungible(_)) => { -// let asset_type: AssetType = id.into(); -// // Shortcut if we know the asset is not supported -// // This involves the same db read per block, mitigating any attack based on -// // non-supported assets -// if !AssetIdInfoGetter::payment_is_supported(asset_type.clone()) { -// return Err(XcmError::TooExpensive); -// } - -// let units_per_second = AssetIdInfoGetter::get_units_per_second(asset_type) -// .ok_or(XcmError::TooExpensive)?; -// // TODO handle proof size payment -// let amount = units_per_second.saturating_mul(weight.ref_time() as u128) / -// (WEIGHT_REF_TIME_PER_SECOND as u128); - -// // We dont need to proceed if the amount is 0 -// // For cases (specially tests) where the asset is very cheap with respect -// // to the weight needed -// if amount.is_zero() { -// log::trace!( -// target: "xcm::buy_weight::payment", -// "asset_type: {:?}", -// id, -// ); -// return Ok(payment); -// } - -// let required = -// MultiAsset { fun: Fungibility::Fungible(amount), id: xcmAssetId::Concrete(id) }; -// let unused = payment.checked_sub(required).map_err(|_| XcmError::TooExpensive)?; -// self.0 = self.0.saturating_add(weight); - -// // In case the asset matches the one the trader already stored before, add -// // to later refund - -// // Else we are always going to subtract the weight if we can, but we latter do -// // not refund it - -// // In short, we only refund on the asset the trader first successfully was able -// // to pay for an execution -// log::trace!( -// target: "xcm::buy_weight::unused", -// "asset_type: {:?}", -// id, -// ); -// let new_asset = match self.1 { -// Some((prev_id, prev_amount, units_per_second)) => -// if prev_id == id { -// Some((id, prev_amount.saturating_add(amount), units_per_second)) -// } else { -// None -// }, -// None => Some((id, amount, units_per_second)), -// }; - -// // Due to the trait bound, we can only refund one asset. -// if let Some(new_asset) = new_asset { -// self.0 = self.0.saturating_add(weight); -// self.1 = Some(new_asset); -// }; -// Ok(unused) -// }, -// _ => Err(XcmError::TooExpensive), -// } -// } - -// fn refund_weight(&mut self, weight: Weight) -> Option { -// if let Some((id, prev_amount, units_per_second)) = self.1 { -// let weight = weight.min(self.0); -// self.0 -= weight; -// let amount = units_per_second * (weight.ref_time() as u128) / -// (WEIGHT_REF_TIME_PER_SECOND as u128); -// self.1 = Some((id, prev_amount.saturating_sub(amount), units_per_second)); -// log::trace!( -// target: "xcm::refund_weight", -// "id: {:?}", -// id, -// ); -// Some(MultiAsset { fun: Fungibility::Fungible(amount), id: xcmAssetId::Concrete(id) }) -// } else { -// None -// } -// } -// } - -// /// Deal with spent fees, deposit them as dictated by R -// impl< -// AssetType: From + Clone, -// AssetIdInfoGetter: UnitsToWeightRatio, -// R: TakeRevenue, -// > Drop for FirstAssetTrader -// { -// fn drop(&mut self) { -// if let Some((id, amount, _)) = self.1 { -// R::take_revenue((id, amount).into()); -// } -// } -// } - -// // Defines the trait to obtain a generic AssetType from a generic AssetId and viceversa -// pub trait AssetTypeGetter { -// // Get asset type from assetId -// fn get_asset_type(asset_id: AssetId) -> Option; - -// // Get assetId from assetType -// fn get_asset_id(asset_type: AssetType) -> Option; -// } - -// // Defines the trait to obtain the units per second of a give asset_type for local execution -// // This parameter will be used to charge for fees upon asset_type deposit -// pub trait UnitsToWeightRatio { -// // Whether payment in a particular asset_type is suppotrted -// fn payment_is_supported(asset_type: AssetType) -> bool; -// // Get units per second from asset type -// fn get_units_per_second(asset_type: AssetType) -> Option; -// } - -// /// XCM fee depositor to which we implement the TakeRevenue trait -// /// It receives a fungibles::Mutate implemented argument, a matcher to convert MultiAsset into -// /// AssetId and amount, and the fee receiver account -// pub struct XcmFeesToAccount( -// PhantomData<(Assets, Matcher, AccountId, ReceiverAccount)>, -// ); -// impl< -// Assets: Mutate, -// Matcher: MatchesFungibles, -// AccountId: Clone, -// ReceiverAccount: Get, -// > TakeRevenue for XcmFeesToAccount -// { -// fn take_revenue(revenue: MultiAsset) { -// match Matcher::matches_fungibles(&revenue) { -// Ok((asset_id, amount)) => -// if !amount.is_zero() { -// Assets::mint_into(asset_id, &ReceiverAccount::get(), amount).unwrap_or_else( -// |e| { -// log::error!( -// target: "xcm::take_revenue", -// "currency_id: {:?}, amount: {:?}, err: {:?}", -// asset_id, -// amount, -// e -// ) -// }, -// ); -// }, -// Err(_) => log::error!( -// target: "xcm", -// "take revenue failed matching fungible" -// ), -// } -// } -// } - -// // Our AssetType. For now we only handle Xcm Assets -// #[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)] -// pub enum AssetType { -// Xcm(MultiLocation), -// } - -// impl Default for AssetType { -// fn default() -> Self { -// Self::Xcm(MultiLocation::here()) -// } -// } - -// impl From for AssetType { -// fn from(location: MultiLocation) -> Self { -// Self::Xcm(location) -// } -// } - -// impl From for Option { -// fn from(asset: AssetType) -> Option { -// match asset { -// AssetType::Xcm(location) => Some(location), -// } -// } -// } - -// // Implementation on how to retrieve the AssetId from an AssetType -// // We simply hash the AssetType and take the lowest 32 bits -// impl From for CurrencyId { -// fn from(asset: AssetType) -> CurrencyId { -// match asset { -// AssetType::Xcm(id) => { -// let mut result: [u8; 4] = [0u8; 4]; -// let hash: H256 = id.using_encoded(BlakeTwo256::hash); -// result.copy_from_slice(&hash.as_fixed_bytes()[0..4]); -// u32::from_le_bytes(result) -// }, -// } -// } -// } - -// pub struct MultiCurrencyAdapter< -// MultiCurrency, -// Match, -// AccountId, -// Balance, -// AccountIdConvert, -// CurrencyIdConvert, -// NativeCurrencyId, -// ExistentialDeposit, -// GiftAccount, -// GiftConvert, -// >( -// PhantomData<( -// MultiCurrency, -// Match, -// AccountId, -// Balance, -// AccountIdConvert, -// CurrencyIdConvert, -// NativeCurrencyId, -// ExistentialDeposit, -// GiftAccount, -// GiftConvert, -// )>, -// ); - -// enum Error { -// /// `MultiLocation` to `AccountId` Conversion failed. -// AccountIdConversionFailed, -// /// `CurrencyId` conversion failed. -// CurrencyIdConversionFailed, -// } - -// impl From for XcmError { -// fn from(e: Error) -> Self { -// match e { -// Error::AccountIdConversionFailed => -// XcmError::FailedToTransactAsset("AccountIdConversionFailed"), -// Error::CurrencyIdConversionFailed => -// XcmError::FailedToTransactAsset("CurrencyIdConversionFailed"), -// } -// } -// } - -// impl< -// MultiCurrency: Inspect + Mutate, -// Match: MatchesFungible, -// AccountId: sp_std::fmt::Debug + Clone, -// Balance: frame_support::traits::tokens::Balance, -// AccountIdConvert: MoreConvert, -// CurrencyIdConvert: Convert>, -// NativeCurrencyId: Get, -// ExistentialDeposit: Get, -// GiftAccount: Get, -// GiftConvert: BalanceConversion, -// > TransactAsset -// for MultiCurrencyAdapter< -// MultiCurrency, -// Match, -// AccountId, -// Balance, -// AccountIdConvert, -// CurrencyIdConvert, -// NativeCurrencyId, -// ExistentialDeposit, -// GiftAccount, -// GiftConvert, -// > -// { -// fn deposit_asset( -// asset: &MultiAsset, -// location: &MultiLocation, -// _context: &XcmContext, -// ) -> XcmResult { -// match ( -// AccountIdConvert::convert_ref(location), -// CurrencyIdConvert::convert(asset.clone()), -// Match::matches_fungible(asset), -// ) { -// // known asset -// (Ok(who), Some(currency_id), Some(amount)) => { -// if let MultiAsset { -// id: AssetId::Concrete(MultiLocation { parents: 1, interior: Here }), -// .. -// } = asset -// { -// let gift_account = GiftAccount::get(); -// let native_currency_id = NativeCurrencyId::get(); -// let gift_amount = -// GiftConvert::to_asset_balance(amount.saturated_into(), currency_id) -// .unwrap_or_else(|_| Zero::zero()); -// let beneficiary_native_balance = -// MultiCurrency::reducible_balance(native_currency_id, &who, true); -// let reducible_balance = -// MultiCurrency::reducible_balance(native_currency_id, &gift_account, false); - -// if !gift_amount.is_zero() && -// reducible_balance >= gift_amount && -// beneficiary_native_balance < gift_amount -// { -// let diff = gift_amount - beneficiary_native_balance; -// if let Err(e) = MultiCurrency::transfer( -// native_currency_id, -// &gift_account, -// &who, -// diff, -// false, -// ) { -// log::error!( -// target: "xcm::deposit_asset", -// "who: {:?}, currency_id: {:?}, amount: {:?}, native_currency_id: {:?}, gift_amount: {:?}, err: {:?}", -// who, -// currency_id, -// amount, -// native_currency_id, -// diff, -// e -// ); -// } -// } -// } - -// MultiCurrency::mint_into(currency_id, &who, amount).map_err(|e| { -// log::error!( -// target: "xcm::deposit_asset", -// "who: {:?}, currency_id: {:?}, amount: {:?}, err: {:?}", -// who, -// currency_id, -// amount, -// e -// ); -// XcmError::FailedToTransactAsset(e.into()) -// }) -// }, -// _ => Err(XcmError::AssetNotFound), -// } -// } - -// fn withdraw_asset( -// asset: &MultiAsset, -// location: &MultiLocation, -// _maybe_context: Option<&XcmContext>, -// ) -> result::Result { -// // throw AssetNotFound error here if not match in order to reach the next foreign transact -// // in tuple -// let amount: MultiCurrency::Balance = -// Match::matches_fungible(asset).ok_or(XcmError::AssetNotFound)?.saturated_into(); -// let who = AccountIdConvert::convert_ref(location) -// .map_err(|_| XcmError::from(Error::AccountIdConversionFailed))?; -// let currency_id = CurrencyIdConvert::convert(asset.clone()) -// .ok_or_else(|| XcmError::from(Error::CurrencyIdConversionFailed))?; -// MultiCurrency::burn_from(currency_id, &who, amount).map_err(|e| { -// log::error!( -// target: "xcm::withdraw_asset", -// "who: {:?}, currency_id: {:?}, amount: {:?}, err: {:?}", -// who, -// currency_id, -// amount, -// e -// ); -// XcmError::FailedToTransactAsset(e.into()) -// })?; - -// Ok(asset.clone().into()) -// } - -// fn internal_transfer_asset( -// asset: &MultiAsset, -// from: &MultiLocation, -// to: &MultiLocation, -// _context: &XcmContext, -// ) -> result::Result { -// let from_account = AccountIdConvert::convert_ref(from) -// .map_err(|_| XcmError::from(Error::AccountIdConversionFailed))?; -// let to_account = AccountIdConvert::convert_ref(to) -// .map_err(|_| XcmError::from(Error::AccountIdConversionFailed))?; -// let currency_id = CurrencyIdConvert::convert(asset.clone()) -// .ok_or_else(|| XcmError::from(Error::CurrencyIdConversionFailed))?; -// let amount: MultiCurrency::Balance = -// Match::matches_fungible(asset).ok_or(XcmError::AssetNotFound)?.saturated_into(); -// MultiCurrency::transfer(currency_id, &from_account, &to_account, amount, true).map_err( -// |e| { -// log::error!( -// target: "xcm::internal_transfer_asset", -// "currency_id: {:?}, source: {:?}, dest: {:?}, amount: {:?}, err: {:?}", -// currency_id, -// from_account, -// to_account, -// amount, -// e -// ); -// XcmError::FailedToTransactAsset(e.into()) -// }, -// )?; - -// Ok(asset.clone().into()) -// } -// } - -// pub struct CurrencyIdConvert(PhantomData); -// impl> -// Convert> for CurrencyIdConvert -// { -// fn convert(id: CurrencyId) -> Option { -// let multi_location = -// AsAssetType::::reverse_ref(id).ok(); -// log::trace!( -// target: "xcm::convert", -// "currency_id: {:?}, multi_location: {:?}", -// id, -// multi_location, -// ); -// multi_location -// } -// } - -// impl> -// Convert> for CurrencyIdConvert -// { -// fn convert(location: MultiLocation) -> Option { -// let currency_id = -// AsAssetType::::convert_ref(location).ok(); -// log::trace!( -// target: "xcm::convert", -// "multi_location: {:?}. currency_id: {:?}", -// location, -// currency_id, -// ); -// currency_id -// } -// } - -// impl> -// Convert> for CurrencyIdConvert -// { -// fn convert(a: MultiAsset) -> Option { -// if let MultiAsset { id: xcmAssetId::Concrete(id), fun: _ } = a { -// Self::convert(id) -// } else { -// None -// } -// } -// } - -// // Multilocation stores in Pallet AssetRegistry start with parent 1 -// // And due to `assets.reanchored` in xcm-executor, -// // So manually convert here, then query currency_id - -// // Consider optimizing under this issue -// // https://github.com/paritytech/polkadot/issues/4489 -// pub struct XcmAssetRegistry( -// PhantomData<(AssetId, AssetType, AssetIdInfoGetter, ParachainId)>, -// ); - -// impl -// XcmAssetRegistry -// where -// AssetType: From + Into> + Clone, -// ParachainId: Get, -// { -// fn convert(asset_type: AssetType) -> AssetType { -// if let Some(location) = asset_type.clone().into() { -// if location.parents != 0 { -// return asset_type; -// } -// let mut new_location = location; -// new_location.parents = 1; -// new_location = new_location -// .pushed_front_with_interior(Parachain(ParachainId::get().into())) -// .unwrap_or(location); -// log::trace!( -// target: "xcm::asset_registry_convert", -// "old_location: {:?}, new_location: {:?}", -// location, -// new_location, -// ); -// return new_location.into(); -// } - -// asset_type -// } -// } - -// impl AssetTypeGetter -// for XcmAssetRegistry -// where -// AssetType: From + Into> + Clone, -// AssetIdInfoGetter: AssetTypeGetter, -// ParachainId: Get, -// { -// fn get_asset_type(asset_id: AssetId) -> Option { -// AssetIdInfoGetter::get_asset_type(asset_id) -// } - -// fn get_asset_id(asset_type: AssetType) -> Option { -// AssetIdInfoGetter::get_asset_id(Self::convert(asset_type)) -// } -// } - -// impl UnitsToWeightRatio -// for XcmAssetRegistry -// where -// AssetType: From + Into> + Clone, -// AssetIdInfoGetter: UnitsToWeightRatio, -// ParachainId: Get, -// { -// fn payment_is_supported(asset_type: AssetType) -> bool { -// AssetIdInfoGetter::payment_is_supported(Self::convert(asset_type)) -// } -// fn get_units_per_second(asset_type: AssetType) -> Option { -// AssetIdInfoGetter::get_units_per_second(Self::convert(asset_type)) -// } -// }