Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Commit

Permalink
avoided AssetConversionAdapter, now using Swap trait
Browse files Browse the repository at this point in the history
  • Loading branch information
PatricioNapoli committed Jul 14, 2023
1 parent 1da4278 commit 8374ba0
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 94 deletions.
11 changes: 2 additions & 9 deletions parachains/runtimes/assets/asset-hub-westend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,11 @@ use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use frame_support::{construct_runtime, dispatch::DispatchClass, ord_parameter_types, parameter_types, traits::{
tokens::nonfungibles_v2::Inspect, AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32,
ConstU64, ConstU8, InstanceFilter,
}, weights::{ConstantMultiplier, Weight}, BoundedVec, PalletId, RuntimeDebug, ensure};
use frame_support::traits::fungible;
use frame_support::traits::tokens::ConversionToAssetBalance;
}, weights::{ConstantMultiplier, Weight}, BoundedVec, PalletId, RuntimeDebug};
use frame_system::{
limits::{BlockLength, BlockWeights},
EnsureRoot, EnsureSigned, EnsureSignedBy,
};
use pallet_asset_conversion::MultiAssetIdConverter;
use pallet_asset_conversion_tx_payment::AssetConversionAdapter;
use pallet_asset_conversion_tx_payment::InitialPayment::Asset;
use pallet_assets::ConversionError;
use pallet_nfts::PalletFeatures;
pub use parachains_common as common;
use parachains_common::{
Expand All @@ -56,7 +50,7 @@ use parachains_common::{
};
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::{create_runtime_str, generic, impl_opaque_keys, traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Verify}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, Permill, FixedPointOperand, FixedU128, FixedPointNumber};
use sp_runtime::{create_runtime_str, generic, impl_opaque_keys, traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Verify}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, Permill};
use sp_std::prelude::*;
#[cfg(feature = "std")]
use sp_version::NativeVersion;
Expand All @@ -75,7 +69,6 @@ use assets_common::{
foreign_creators::ForeignCreators, matching::FromSiblingParachain, MultiLocationForAssetId,
};
use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
use sp_runtime::traits::Zero;
use xcm_executor::XcmExecutor;

use crate::xcm_config::ForeignCreatorsSovereignAccountOf;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use super::{
ParachainSystem, PolkadotXcm, PoolAssets, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
TrustBackedAssetsInstance, WeightToFee, XcmpQueue,
};
use crate::{ForeignAssets};
use crate::ForeignAssets;
use assets_common::matching::{
FromSiblingParachain, IsForeignConcreteAsset, StartsWith, StartsWithExplicitGlobalConsensus,
};
Expand All @@ -27,7 +27,6 @@ use frame_support::{
traits::{ConstU32, Contains, Everything, Nothing, PalletInfoAccess},
};
use frame_system::EnsureRoot;
use pallet_asset_conversion_tx_payment::AssetConversionAdapter;
use pallet_xcm::XcmPassthrough;
use parachains_common::{impls::ToStakingPot, xcm_config::AssetFeeAsExistentialDepositMultiplier};
use polkadot_parachain::primitives::Sibling;
Expand Down Expand Up @@ -443,12 +442,10 @@ impl xcm_executor::Config for XcmConfig {
type Trader = (
UsingComponents<WeightToFee, WestendLocation, AccountId, Balances, ToStakingPot<Runtime>>,
cumulus_primitives_utility::SwapFirstAssetTrader<
AccountId,
LocationToAccountId,
Balance,
Runtime,
LocationToAccountId,
pallet_asset_conversion::Pallet<Runtime>,
WeightToFee,
AssetConversionAdapter<Balance, AssetConversion>,
MultiAssetsConvertedConcreteId,
LocalAndForeignAssets<Assets, ForeignAssets, TrustBackedAssetsPalletLocation>,
cumulus_primitives_utility::XcmFeesTo32ByteAccount<
Expand Down
3 changes: 2 additions & 1 deletion primitives/utility/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ log = { version = "0.4.19", default-features = false }

# Substrate
frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
pallet-asset-conversion-tx-payment = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
pallet-asset-conversion = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
Expand All @@ -30,6 +30,7 @@ default = [ "std" ]
std = [
"codec/std",
"frame-support/std",
"pallet-asset-conversion/std",
"sp-runtime/std",
"sp-std/std",
"sp-io/std",
Expand Down
114 changes: 36 additions & 78 deletions primitives/utility/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ use frame_support::{
},
weights::Weight,
};
use pallet_asset_conversion_tx_payment::OnChargeAssetTransaction;
use frame_support::traits::fungibles::SwapNative;
use pallet_asset_conversion::{Swap, Config, MultiAssetIdConverter};
use polkadot_runtime_common::xcm_sender::ConstantPrice;
use sp_runtime::{traits::Saturating, SaturatedConversion};
use sp_std::{marker::PhantomData, prelude::*};
Expand Down Expand Up @@ -280,31 +279,28 @@ struct SwapAssetTraderRefunder {
}

pub struct SwapFirstAssetTrader<
AccountId,
AccountIdConverter: ConvertLocation<AccountId>,
Balance,
Runtime: pallet_asset_conversion_tx_payment::Config,
WeightToFee: frame_support::weights::WeightToFee<Balance = Balance>,
ChargeAssetTransaction: OnChargeAssetTransaction<Runtime>,
T: Config,
AccountIdConverter: ConvertLocation<T::AccountId>,
SWP: Swap<T::AccountId, T::HigherPrecisionBalance, T::MultiAssetId>,
WeightToFee: frame_support::weights::WeightToFee<Balance = T::Balance>,
Matcher: MatchesFungibles<ConcreteAssets::AssetId, ConcreteAssets::Balance>,
ConcreteAssets: fungibles::Mutate<AccountId> + fungibles::Balanced<AccountId>,
ConcreteAssets: fungibles::Mutate<T::AccountId> + fungibles::Balanced<T::AccountId>,
HandleRefund: TakeRevenue,
>(
Option<SwapAssetTraderRefunder>,
PhantomData<(AccountId, AccountIdConverter, Balance, Runtime, WeightToFee, ChargeAssetTransaction, Matcher, ConcreteAssets, HandleRefund)>,
PhantomData<(T, AccountIdConverter, SWP, WeightToFee, Matcher, ConcreteAssets, HandleRefund)>,
);

impl<
AccountId,
AccountIdConverter: ConvertLocation<AccountId>,
Balance,
Runtime: pallet_asset_conversion_tx_payment::Config,
WeightToFee: frame_support::weights::WeightToFee<Balance = Balance>,
ChargeAssetTransaction: OnChargeAssetTransaction<Runtime>,
T: Config,
AccountIdConverter: ConvertLocation<T::AccountId>,
SWP: Swap<T::AccountId, T::HigherPrecisionBalance, T::MultiAssetId>,
WeightToFee: frame_support::weights::WeightToFee<Balance = T::Balance>,
Matcher: MatchesFungibles<ConcreteAssets::AssetId, ConcreteAssets::Balance>,
ConcreteAssets: fungibles::Mutate<AccountId> + fungibles::Balanced<AccountId>,
ConcreteAssets: fungibles::Mutate<T::AccountId> + fungibles::Balanced<T::AccountId>,
HandleRefund: TakeRevenue,
> WeightTrader
for SwapFirstAssetTrader<AccountId, AccountIdConverter, Balance, Runtime, WeightToFee, ChargeAssetTransaction, Matcher, ConcreteAssets, HandleRefund>
for SwapFirstAssetTrader<T, AccountIdConverter, SWP, WeightToFee, Matcher, ConcreteAssets, HandleRefund>
{
fn new() -> Self {
Self(None, PhantomData)
Expand Down Expand Up @@ -342,82 +338,44 @@ for SwapFirstAssetTrader<AccountId, AccountIdConverter, Balance, Runtime, Weight

let acc = AccountIdConverter::convert_location(&ctx.origin.unwrap()).unwrap();

// Call ChargeAssetTransaction::withdraw_fee
// ...
// TODO
//
let (_, native_asset_acquired, asset_consumed) = ChargeAssetTransaction::withdraw_fee(
acc,
// Downstream functions IGNORE this runtime call argument, what is a proper value?
<MockRuntimeCall>,
// Downstream functions IGNORE this runtime dispatch info argument, what is a proper value?
<MockDispatchInfo>,
local_asset_id,
fee,
0
).unwrap();
// let (asset_balance) = SWP::swap_exact_tokens_for_tokens(
// acc,
// vec![first, T::MultiAssetIdConverter::get_native()],
// payment,
// Some(fee),
// acc,
// true
// ).map_err(|_| XcmError::AssetNotFound)?;

// Convert to the same kind of multiasset, with the required fungible balance
let required = first.id.into_multiasset(asset_balance.into());
// let required = first.id.into_multiasset(asset_balance.into());

// Substract payment
let unused = payment.checked_sub(required.clone()).map_err(|_| XcmError::TooExpensive)?;
// let unused = payment.checked_sub(required.clone()).map_err(|_| XcmError::TooExpensive)?;

// record weight and multiasset
self.0 = Some(SwapAssetTraderRefunder {
outstanding_concrete_asset: required,
});
// self.0 = Some(SwapAssetTraderRefunder {
// outstanding_concrete_asset: required,
// });

Ok(unused)
Err(XcmError::AssetNotFound)
}

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

if let Some(SwapAssetTraderRefunder {
outstanding_concrete_asset: MultiAsset { id, fun },
}) = self.0.clone()
{
// Get the local asset id in which we can refund fees
let (local_asset_id, outstanding_balance) =
Matcher::matches_fungibles(&(id, fun).into()).ok()?;

// Re-calculate asset swap from native to MultiAsset provided
// ...
// TODO

// Convert balances into u128
let outstanding_minus_substracted: u128 =
outstanding_minus_substracted.saturated_into();
let asset_balance: u128 = asset_balance.saturated_into();

// Construct outstanding_concrete_asset with the same location id and substracted balance
let outstanding_concrete_asset: MultiAsset = (id, outstanding_minus_substracted).into();

// Override SwapAssetTraderRefunder
self.0 = Some(SwapAssetTraderRefunder { outstanding_concrete_asset });

// Only refund if positive
if asset_balance > 0 {
return Some((id, asset_balance).into())
}
}

None
}
}

impl<
AccountId,
AccountIdConverter: ConvertLocation<AccountId>,
Balance,
Runtime: pallet_asset_conversion_tx_payment::Config,
WeightToFee: frame_support::weights::WeightToFee<Balance = Balance>,
ChargeAssetTransaction: OnChargeAssetTransaction<Runtime>,
T: Config,
AccountIdConverter: ConvertLocation<T::AccountId>,
SWP: Swap<T::AccountId, T::HigherPrecisionBalance, T::MultiAssetId>,
WeightToFee: frame_support::weights::WeightToFee<Balance = T::Balance>,
Matcher: MatchesFungibles<ConcreteAssets::AssetId, ConcreteAssets::Balance>,
ConcreteAssets: fungibles::Mutate<AccountId> + fungibles::Balanced<AccountId>,
ConcreteAssets: fungibles::Mutate<T::AccountId> + fungibles::Balanced<T::AccountId>,
HandleRefund: TakeRevenue,
> Drop for SwapFirstAssetTrader<AccountId, AccountIdConverter, Balance, Runtime, WeightToFee, ChargeAssetTransaction, Matcher, ConcreteAssets, HandleRefund>
> Drop for SwapFirstAssetTrader<T, AccountIdConverter, SWP, WeightToFee, Matcher, ConcreteAssets, HandleRefund>
{
fn drop(&mut self) {
if let Some(asset_trader) = self.0.clone() {
Expand Down Expand Up @@ -692,9 +650,9 @@ mod tests {
let weight_to_buy = Weight::from_parts(1_000, 1_000);

// lets do first call (success)
assert_ok!(trader.buy_weight(weight_to_buy, payment.clone()));
assert_ok!(trader.buy_weight(&XcmContext::with_message_id([0; 32]), weight_to_buy, payment.clone()));

// lets do second call (error)
assert_eq!(trader.buy_weight(weight_to_buy, payment), Err(XcmError::NotWithdrawable));
assert_eq!(trader.buy_weight(&XcmContext::with_message_id([0; 32]), weight_to_buy, payment), Err(XcmError::NotWithdrawable));
}
}

0 comments on commit 8374ba0

Please sign in to comment.