Skip to content

Girazoki controlled fee specification #658

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
266 changes: 259 additions & 7 deletions xtokens/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,12 @@ pub mod module {
pub enum Event<T: Config> {
/// Transferred. \[sender, currency_id, amount, dest\]
Transferred(T::AccountId, T::CurrencyId, T::Balance, MultiLocation),
/// Transferred with fee. \[sender, currency_id, amount, fee, dest\]
TransferredWithFee(T::AccountId, T::CurrencyId, T::Balance, T::Balance, MultiLocation),
/// Transferred `MultiAsset`. \[sender, asset, dest\]
TransferredMultiAsset(T::AccountId, MultiAsset, MultiLocation),
/// Transferred `MultiAsset` with fee. \[sender, asset, dest\]
TransferredMultiAssetWithFee(T::AccountId, MultiAsset, MultiAsset, MultiLocation),
}

#[pallet::error]
Expand Down Expand Up @@ -134,6 +138,8 @@ pub mod module {
/// The version of the `Versioned` value used is not able to be
/// interpreted.
BadVersion,
/// The fee MultiAsset is of different type than the asset to transfer
DistincAssetAndFeeId,
}

#[pallet::hooks]
Expand Down Expand Up @@ -170,6 +176,38 @@ pub mod module {
Self::do_transfer(who, currency_id, amount, dest, dest_weight)
}

/// Transfer native currencies specifying the fee and amount as
/// separate.
///
/// `dest_weight` is the weight for XCM execution on the dest chain, and
/// it would be charged from the transferred assets. If set below
/// requirements, the execution may fail and assets wouldn't be
/// received.
///
/// `fee` is the amount to be spent to pay for execution in destination
/// chain Both fee and amount will be substracted form the callers
/// balance
///
/// It's a no-op if any error on local XCM execution or message sending.
/// Note sending assets out per se doesn't guarantee they would be
/// received. Receiving depends on if the XCM message could be delivered
/// by the network, and if the receiving chain would handle
/// messages correctly.
#[pallet::weight(Pallet::<T>::weight_of_transfer(currency_id.clone(), *amount, dest))]
#[transactional]
pub fn transfer_with_fee(
origin: OriginFor<T>,
currency_id: T::CurrencyId,
amount: T::Balance,
fee: T::Balance,
dest: Box<VersionedMultiLocation>,
dest_weight: Weight,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::<T>::BadVersion)?;
Self::do_transfer_with_fee(who, currency_id, amount, fee, dest, dest_weight)
}

/// Transfer `MultiAsset`.
///
/// `dest_weight` is the weight for XCM execution on the dest chain, and
Expand All @@ -195,6 +233,40 @@ pub mod module {
let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::<T>::BadVersion)?;
Self::do_transfer_multiasset(who, asset, dest, dest_weight, true)
}

/// Transfer `MultiAsset` specifying the fee and amount as separate.
///
/// `dest_weight` is the weight for XCM execution on the dest chain, and
/// it would be charged from the transferred assets. If set below
/// requirements, the execution may fail and assets wouldn't be
/// received.
///
/// `fee` is the multiasset to be spent to pay for execution in
/// destination chain Both fee and amount will be substracted form the
/// callers balance For now we only accept fee and asset having the same
/// multilocation id
///
/// It's a no-op if any error on local XCM execution or message sending.
/// Note sending assets out per se doesn't guarantee they would be
/// received. Receiving depends on if the XCM message could be delivered
/// by the network, and if the receiving chain would handle
/// messages correctly.
#[pallet::weight(Pallet::<T>::weight_of_transfer_multiasset(asset, dest))]
#[transactional]
pub fn transfer_multiasset_with_fee(
origin: OriginFor<T>,
asset: Box<VersionedMultiAsset>,
fee: Box<VersionedMultiAsset>,
dest: Box<VersionedMultiLocation>,
dest_weight: Weight,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let asset: MultiAsset = (*asset).try_into().map_err(|()| Error::<T>::BadVersion)?;
let fee: MultiAsset = (*fee).try_into().map_err(|()| Error::<T>::BadVersion)?;
let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::<T>::BadVersion)?;

Self::do_transfer_multiasset_with_fee(who, asset, fee, dest, dest_weight, true)
}
}

impl<T: Config> Pallet<T> {
Expand All @@ -215,6 +287,25 @@ pub mod module {
Ok(())
}

fn do_transfer_with_fee(
who: T::AccountId,
currency_id: T::CurrencyId,
amount: T::Balance,
fee: T::Balance,
dest: MultiLocation,
dest_weight: Weight,
) -> DispatchResult {
let location: MultiLocation = T::CurrencyIdConvert::convert(currency_id.clone())
.ok_or(Error::<T>::NotCrossChainTransferableCurrency)?;

let asset = (location.clone(), amount.into()).into();
let fee_asset: MultiAsset = (location, fee.into()).into();
Self::do_transfer_multiasset_with_fee(who.clone(), asset, fee_asset, dest.clone(), dest_weight, false)?;

Self::deposit_event(Event::<T>::TransferredWithFee(who, currency_id, amount, fee, dest));
Ok(())
}

fn do_transfer_multiasset(
who: T::AccountId,
asset: MultiAsset,
Expand Down Expand Up @@ -254,6 +345,65 @@ pub mod module {
Ok(())
}

fn do_transfer_multiasset_with_fee(
who: T::AccountId,
asset: MultiAsset,
fee: MultiAsset,
dest: MultiLocation,
dest_weight: Weight,
deposit_event: bool,
) -> DispatchResult {
if !asset.is_fungible(None) || !fee.is_fungible(None) {
return Err(Error::<T>::NotFungible.into());
}

if fungible_amount(&asset).is_zero() || fungible_amount(&fee).is_zero() {
return Ok(());
}

// For now fee and asset id should be identical
// We can relax this assumption in the future
ensure!(fee.id == asset.id, Error::<T>::DistincAssetAndFeeId);

let (transfer_kind, dest, reserve, recipient) = Self::transfer_kind(&asset, &dest)?;
let mut msg = match transfer_kind {
SelfReserveAsset => Self::transfer_self_reserve_asset_with_fee(
asset.clone(),
fee.clone(),
dest.clone(),
recipient,
dest_weight,
)?,
ToReserve => Self::transfer_to_reserve_with_fee(
asset.clone(),
fee.clone(),
dest.clone(),
recipient,
dest_weight,
)?,
ToNonReserve => Self::transfer_to_non_reserve_with_fee(
asset.clone(),
fee.clone(),
reserve,
dest.clone(),
recipient,
dest_weight,
)?,
};

let origin_location = T::AccountIdToMultiLocation::convert(who.clone());
let weight = T::Weigher::weight(&mut msg).map_err(|()| Error::<T>::UnweighableMessage)?;
T::XcmExecutor::execute_xcm_in_credit(origin_location, msg, weight, weight)
.ensure_complete()
.map_err(|_| Error::<T>::XcmExecutionFailed)?;

if deposit_event {
Self::deposit_event(Event::<T>::TransferredMultiAssetWithFee(who, asset, fee, dest));
}

Ok(())
}

fn transfer_self_reserve_asset(
asset: MultiAsset,
dest: MultiLocation,
Expand All @@ -268,7 +418,28 @@ pub mod module {
dest: dest.clone(),
xcm: Xcm(vec![
Self::buy_execution(asset, &dest, dest_weight)?,
Self::deposit_asset(recipient),
Self::deposit_asset(All.into(), &dest, recipient)?,
]),
},
]))
}

fn transfer_self_reserve_asset_with_fee(
asset: MultiAsset,
fee: MultiAsset,
dest: MultiLocation,
recipient: MultiLocation,
dest_weight: Weight,
) -> Result<Xcm<T::Call>, DispatchError> {
Ok(Xcm(vec![
WithdrawAsset(vec![asset.clone().into(), fee.clone().into()].into()),
DepositReserveAsset {
assets: All.into(),
max_assets: 1,
dest: dest.clone(),
xcm: Xcm(vec![
Self::buy_execution(fee, &dest, dest_weight)?,
Self::deposit_asset(asset.into(), &dest, recipient)?,
]),
},
]))
Expand All @@ -287,7 +458,27 @@ pub mod module {
reserve: reserve.clone(),
xcm: Xcm(vec![
Self::buy_execution(asset, &reserve, dest_weight)?,
Self::deposit_asset(recipient),
Self::deposit_asset(All.into(), &reserve, recipient)?,
]),
},
]))
}

fn transfer_to_reserve_with_fee(
asset: MultiAsset,
fee: MultiAsset,
reserve: MultiLocation,
recipient: MultiLocation,
dest_weight: Weight,
) -> Result<Xcm<T::Call>, DispatchError> {
Ok(Xcm(vec![
WithdrawAsset(vec![asset.clone().into(), fee.clone().into()].into()),
InitiateReserveWithdraw {
assets: All.into(),
reserve: reserve.clone(),
xcm: Xcm(vec![
Self::buy_execution(fee, &reserve, dest_weight)?,
Self::deposit_asset(asset.into(), &reserve, recipient)?,
]),
},
]))
Expand Down Expand Up @@ -326,20 +517,81 @@ pub mod module {
dest: reanchored_dest,
xcm: Xcm(vec![
Self::buy_execution(half(&asset), &dest, dest_weight)?,
Self::deposit_asset(recipient),
Self::deposit_asset(All.into(), &dest, recipient)?,
]),
},
]),
},
]))
}

fn transfer_to_non_reserve_with_fee(
asset: MultiAsset,
fee: MultiAsset,
reserve: MultiLocation,
dest: MultiLocation,
recipient: MultiLocation,
dest_weight: Weight,
) -> Result<Xcm<T::Call>, DispatchError> {
let mut reanchored_dest = dest.clone();
if reserve == MultiLocation::parent() {
match dest {
MultiLocation {
parents,
interior: X1(Parachain(id)),
} if parents == 1 => {
reanchored_dest = Parachain(id).into();
}
_ => {}
}
}

let reserve_inv_at =
T::LocationInverter::invert_location(&reserve).map_err(|()| Error::<T>::DestinationNotInvertible)?;

Ok(Xcm(vec![
WithdrawAsset(vec![asset.clone().into(), fee.clone().into()].into()),
InitiateReserveWithdraw {
assets: All.into(),
reserve: reserve.clone(),
xcm: Xcm(vec![
Self::buy_execution(half(&fee), &reserve, dest_weight)?,
DepositReserveAsset {
assets: vec![
half(&fee.clone())
.reanchored(&reserve_inv_at)
.map_err(|_| Error::<T>::CannotReanchor)?,
asset
.clone()
.reanchored(&reserve_inv_at)
.map_err(|_| Error::<T>::CannotReanchor)?,
]
.into(),
max_assets: 1,
dest: reanchored_dest,
xcm: Xcm(vec![
Self::buy_execution(half(&fee), &dest, dest_weight)?,
Self::deposit_asset(asset.into(), &dest, recipient)?,
]),
},
]),
},
]))
}

fn deposit_asset(recipient: MultiLocation) -> Instruction<()> {
DepositAsset {
assets: All.into(),
fn deposit_asset(
mut asset: MultiAssetFilter,
at: &MultiLocation,
recipient: MultiLocation,
) -> Result<Instruction<()>, DispatchError> {
let inv_at = T::LocationInverter::invert_location(at).map_err(|()| Error::<T>::DestinationNotInvertible)?;
asset.reanchor(&inv_at).map_err(|_| Error::<T>::CannotReanchor)?;

Ok(DepositAsset {
assets: asset,
max_assets: 1,
beneficiary: recipient,
}
})
}

fn buy_execution(
Expand Down
Loading