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
253 changes: 253 additions & 0 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, fee, dest\]
TransferredMultiAssetWithFee(T::AccountId, MultiAsset, MultiAsset, MultiLocation),
}

#[pallet::error]
Expand Down Expand Up @@ -134,6 +138,11 @@ 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,
/// The fee amount was zero when the fee specification extrinsic is
/// being used.
FeeCannotBeZero,
}

#[pallet::hooks]
Expand Down Expand Up @@ -195,6 +204,89 @@ 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 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 subtracted form the callers
/// balance.
///
/// If `fee` is not high enough to cover for the execution costs in the
/// destination chain, then the assets will be trapped in the
/// destination chain
///
/// 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)?;
// Zero fee is an error
if fee.is_zero() {
return Err(Error::<T>::FeeCannotBeZero.into());
}

Self::do_transfer_with_fee(who, currency_id, amount, fee, dest, dest_weight)
}

/// 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 subtracted form the
/// callers balance For now we only accept fee and asset having the same
/// `MultiLocation` id.
///
/// If `fee` is not high enough to cover for the execution costs in the
/// destination chain, then the assets will be trapped in the
/// destination chain
///
/// 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)?;
// Zero fee is an error
if fungible_amount(&fee).is_zero() {
return Err(Error::<T>::FeeCannotBeZero.into());
}

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

impl<T: Config> Pallet<T> {
Expand All @@ -215,6 +307,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 +365,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() {
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 @@ -274,6 +444,27 @@ pub mod module {
]))
}

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, fee.clone()].into()),
DepositReserveAsset {
assets: All.into(),
max_assets: 1,
dest: dest.clone(),
xcm: Xcm(vec![
Self::buy_execution(fee, &dest, dest_weight)?,
Self::deposit_asset(recipient),
]),
},
]))
}

fn transfer_to_reserve(
asset: MultiAsset,
reserve: MultiLocation,
Expand All @@ -293,6 +484,26 @@ pub mod module {
]))
}

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, fee.clone()].into()),
InitiateReserveWithdraw {
assets: All.into(),
reserve: reserve.clone(),
xcm: Xcm(vec![
Self::buy_execution(fee, &reserve, dest_weight)?,
Self::deposit_asset(recipient),
]),
},
]))
}

fn transfer_to_non_reserve(
asset: MultiAsset,
reserve: MultiLocation,
Expand Down Expand Up @@ -334,6 +545,48 @@ pub mod module {
]))
}

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();
}
_ => {}
}
}

Ok(Xcm(vec![
WithdrawAsset(vec![asset, fee.clone()].into()),
InitiateReserveWithdraw {
assets: All.into(),
reserve: reserve.clone(),
xcm: Xcm(vec![
Self::buy_execution(half(&fee), &reserve, dest_weight)?,
DepositReserveAsset {
assets: All.into(),
max_assets: 1,
dest: reanchored_dest,
xcm: Xcm(vec![
Self::buy_execution(half(&fee), &dest, dest_weight)?,
Self::deposit_asset(recipient),
]),
},
]),
},
]))
}

fn deposit_asset(recipient: MultiLocation) -> Instruction<()> {
DepositAsset {
assets: All.into(),
Expand Down
4 changes: 2 additions & 2 deletions xtokens/src/mock/para.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,8 @@ impl Config for XcmConfig {
type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
type Trader = AllTokensAreCreatedEqualToWeight;
type ResponseHandler = ();
type AssetTrap = ();
type AssetClaims = ();
type AssetTrap = PolkadotXcm;
type AssetClaims = PolkadotXcm;
type SubscriptionService = PolkadotXcm;
}

Expand Down
Loading