feat: initialize Kurdistan SDK - independent fork of Polkadot SDK

This commit is contained in:
Kurdistan Tech Ministry committed 2025-12-13 15:44:15 +03:00
commit e4778b4576
6838 files changed
+1847450

No files matched your search

@@ -0,0 +1,302 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Unit tests related to the `InitiateTransfer` instruction.
//!
//! See [Fellowship RFC 100](https://github.com/polkadot-fellows/rfCs/pull/100),
//! [Fellowship RFC 122](https://github.com/polkadot-fellows/rfCs/pull/122), and the
//! [specification](https://github.com/polkadot-fellows/xcm-format) for more information.
use codec::Encode;
use frame_support::BoundedVec;
use xcm::{latest::AssetTransferFilter, prelude::*};
use super::mock::*;
// The sender and recipient we use across these tests.
const SENDER: [u8; 32] = [0; 32];
const RECIPIENT: [u8; 32] = [1; 32];
const RECIPIENT2: [u8; 32] = [2; 32];
#[test]
fn clears_origin() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
let xcm_on_dest =
Xcm(vec![RefundSurplus, DepositAsset { assets: Wild(All), beneficiary: RECIPIENT.into() }]);
let assets: Assets = (Here, 90u128).into();
let xcm = Xcm::<TestCall>(vec![
WithdrawAsset((Here, 100u128).into()),
PayFees { asset: (Here, 10u128).into() },
InitiateTransfer {
destination: Parent.into(),
remote_fees: Some(AssetTransferFilter::ReserveDeposit(assets.into())),
preserve_origin: false,
assets: BoundedVec::new(),
remote_xcm: xcm_on_dest,
},
]);
let (mut vm, _) = instantiate_executor(SENDER, xcm.clone());
// Program runs successfully.
let res = vm.bench_process(xcm);
assert!(res.is_ok(), "execution error {:?}", res);
let (dest, sent_message) = sent_xcm().pop().unwrap();
assert_eq!(dest, Parent.into());
assert_eq!(sent_message.len(), 6);
let mut instr = sent_message.inner().iter();
assert!(matches!(instr.next().unwrap(), ReserveAssetDeposited(..)));
assert!(matches!(instr.next().unwrap(), PayFees { .. }));
assert!(matches!(instr.next().unwrap(), ClearOrigin));
assert!(matches!(instr.next().unwrap(), RefundSurplus));
assert!(matches!(instr.next().unwrap(), DepositAsset { .. }));
}
#[test]
fn preserves_origin() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
let xcm_on_dest =
Xcm(vec![RefundSurplus, DepositAsset { assets: Wild(All), beneficiary: RECIPIENT.into() }]);
let assets: Assets = (Here, 90u128).into();
let xcm = Xcm::<TestCall>(vec![
WithdrawAsset((Here, 100u128).into()),
PayFees { asset: (Here, 10u128).into() },
InitiateTransfer {
destination: Parent.into(),
remote_fees: Some(AssetTransferFilter::ReserveDeposit(assets.into())),
preserve_origin: true,
assets: BoundedVec::new(),
remote_xcm: xcm_on_dest,
},
]);
let (mut vm, _) = instantiate_executor(SENDER, xcm.clone());
// Program runs successfully.
let res = vm.bench_process(xcm);
assert!(res.is_ok(), "execution error {:?}", res);
let (dest, sent_message) = sent_xcm().pop().unwrap();
assert_eq!(dest, Parent.into());
assert_eq!(sent_message.len(), 6);
let mut instr = sent_message.inner().iter();
assert!(matches!(instr.next().unwrap(), ReserveAssetDeposited(..)));
assert!(matches!(instr.next().unwrap(), PayFees { .. }));
assert!(matches!(
instr.next().unwrap(),
AliasOrigin(origin) if matches!(origin.unpack(), (0, [Teyrchain(1000), AccountId32 { id: SENDER, network: None }]))
));
assert!(matches!(instr.next().unwrap(), RefundSurplus));
assert!(matches!(instr.next().unwrap(), DepositAsset { .. }));
}
#[test]
fn unpaid_execution_goes_after_origin_alteration() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
let xcm_on_destination =
Xcm::builder_unsafe().refund_surplus().deposit_asset(All, RECIPIENT).build();
let asset: Asset = (Here, 90u128).into();
let xcm = Xcm::builder()
.withdraw_asset((Here, 100u128))
.pay_fees((Here, 10u128))
.initiate_transfer(
Parent,
None, // We specify no remote fees.
true, // Preserve origin, necessary for `UnpaidExecution`.
vec![AssetTransferFilter::ReserveDeposit(asset.into())],
xcm_on_destination,
)
.build();
// We initialize the executor with the SENDER origin, which is not waived.
let (mut vm, _) = instantiate_executor(SENDER, xcm.clone());
// Program fails with `BadOrigin`.
let result = vm.bench_process(xcm);
assert!(result.is_ok(), "execution error {:?}", result);
let (destination, sent_message) = sent_xcm().pop().unwrap();
assert_eq!(destination, Parent.into());
assert_eq!(sent_message.len(), 6);
let mut instructions = sent_message.inner().iter();
assert!(matches!(instructions.next().unwrap(), ReserveAssetDeposited(..)));
assert!(matches!(
instructions.next().unwrap(),
AliasOrigin(origin) if matches!(origin.unpack(), (0, [Teyrchain(1000), AccountId32 { id: SENDER, network: None }]))
));
assert!(matches!(instructions.next().unwrap(), UnpaidExecution { .. }));
assert!(matches!(instructions.next().unwrap(), RefundSurplus));
assert!(matches!(instructions.next().unwrap(), DepositAsset { .. }));
}
#[test]
fn no_alias_origin_if_root() {
// Make sure the sender has enough funds to withdraw.
add_asset(Here, (Here, 100u128));
let xcm_on_destination =
Xcm::builder_unsafe().refund_surplus().deposit_asset(All, RECIPIENT).build();
let asset: Asset = (Here, 90u128).into();
let xcm = Xcm::builder()
.withdraw_asset((Here, 100u128))
.pay_fees((Here, 10u128))
.initiate_transfer(
Parent,
None, // We specify no remote fees.
true, // Preserve origin, necessary for `UnpaidExecution`.
vec![AssetTransferFilter::ReserveDeposit(asset.into())],
xcm_on_destination,
)
.build();
// We initialize the executor with the SENDER origin, which is not waived.
let (mut vm, _) = instantiate_executor(Here, xcm.clone());
// Program fails with `BadOrigin`.
let result = vm.bench_process(xcm);
assert!(result.is_ok(), "execution error {:?}", result);
let (destination, sent_message) = sent_xcm().pop().unwrap();
assert_eq!(destination, Parent.into());
assert_eq!(sent_message.len(), 5);
let mut instructions = sent_message.inner().iter();
assert!(matches!(instructions.next().unwrap(), ReserveAssetDeposited(..)));
assert!(matches!(instructions.next().unwrap(), UnpaidExecution { .. }));
assert!(matches!(instructions.next().unwrap(), RefundSurplus));
assert!(matches!(instructions.next().unwrap(), DepositAsset { .. }));
}
// We simulate going from one system teyrchain to another without
// having to pay remote fees.
#[test]
fn unpaid_transact() {
let to_another_system_para: Location = (Parent, Teyrchain(1001)).into();
// We want to execute some call in the receiving chain.
let xcm_on_destination = Xcm::builder_unsafe()
.transact(OriginKind::Superuser, None, b"".encode())
.build();
let xcm = Xcm::builder_unsafe()
.initiate_transfer(
to_another_system_para.clone(),
None, // We specify no remote fees.
true, // Preserve necessary for `UnpaidExecution`.
vec![], // No need for assets.
xcm_on_destination,
)
.build();
// We initialize the executor with the root origin, which is waived.
let (mut vm, _) = instantiate_executor(Here, xcm.clone());
// Program executes successfully.
let result = vm.bench_process(xcm.clone());
assert!(result.is_ok(), "execution error: {:?}", result);
let (destination, sent_message) = sent_xcm().pop().unwrap();
assert_eq!(destination, to_another_system_para);
assert_eq!(sent_message.len(), 3);
let mut instructions = sent_message.inner().iter();
assert!(matches!(instructions.next().unwrap(), UnpaidExecution { .. }));
assert!(matches!(instructions.next().unwrap(), Transact { .. }));
}
#[test]
fn deposit_assets_with_retry_burns_dust_and_deposits_rest() {
// fund sender
add_asset(SENDER, (Here, 200u128));
// dust amount (< ED=2)
let dust: Asset = (Here, 1u128).into();
// non-dust amount (> ED=2)
let legit: Asset = (Here, 100u128).into();
let xcm = Xcm::<TestCall>(vec![
WithdrawAsset((Here, 101u128).into()),
DepositAsset {
assets: Definite(Assets::from(vec![dust.clone()])),
beneficiary: RECIPIENT.into(),
},
DepositAsset {
assets: Definite(Assets::from(vec![legit.clone()])),
beneficiary: RECIPIENT.into(),
},
]);
let (mut vm, weight) = instantiate_executor(SENDER, xcm.clone());
let result = vm.bench_process(xcm);
assert!(result.is_ok(), "XCM execution must succeed even if one deposit is dust");
let outcome = vm.bench_post_process(weight);
assert!(matches!(outcome, Outcome::Complete { .. }), "Expected Complete, got {:?}", outcome);
let here_assets = asset_list(RECIPIENT);
assert_eq!(here_assets, vec![legit], "only the ≥ED asset (100) should end up in `Here`");
// dust is burned, so nothing lands in the trap account
let trapped = asset_list(TRAPPED_ASSETS);
assert!(trapped.is_empty(), "dust assets should be silently burned, not trapped");
}
#[test]
fn deposit_assets_with_retry_all_dust_are_burned() {
// fund sender
add_asset(SENDER, (Here, 20u128));
// two dust amounts, both < ED=2
let d1: Asset = (Here, 1u128).into();
let d2: Asset = (Here, 1u128).into();
let xcm = Xcm::<TestCall>(vec![
// withdraw 1+1 so it succeeds
WithdrawAsset((Here, (1u128 + 1u128)).into()),
DepositAsset {
assets: Definite(Assets::from(vec![d1.clone()])),
beneficiary: RECIPIENT.into(),
},
DepositAsset {
assets: Definite(Assets::from(vec![d2.clone()])),
beneficiary: RECIPIENT2.into(),
},
]);
let (mut vm, weight) = instantiate_executor(SENDER, xcm.clone());
let result = vm.bench_process(xcm);
assert!(result.is_ok(), "all-dust deposit must not abort");
let outcome = vm.bench_post_process(weight);
assert!(matches!(outcome, Outcome::Complete { .. }));
// none of the two dust deposits should land in either recipient
let received = asset_list(RECIPIENT);
assert!(received.is_empty(), "no ≥ED assets, so recipient must get nothing");
// none of the two dust deposits should land in either recipient
let received = asset_list(RECIPIENT2);
assert!(received.is_empty(), "no ≥ED assets, so recipient must get nothing");
// all dust is burned, trap account stays empty
let trapped = asset_list(TRAPPED_ASSETS);
assert!(trapped.is_empty(), "all dust assets must be burned, not trapped");
}
+331
View File
@@ -0,0 +1,331 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Mock types and XcmConfig for all executor unit tests.
use alloc::collections::btree_map::BTreeMap;
use codec::{Decode, DecodeWithMemTracking, Encode};
use core::cell::RefCell;
use frame_support::{
dispatch::{DispatchInfo, DispatchResultWithPostInfo, GetDispatchInfo, PostDispatchInfo},
parameter_types,
traits::{Everything, Nothing, ProcessMessageError},
weights::Weight,
};
use sp_runtime::traits::Dispatchable;
use xcm::prelude::*;
use crate::{
traits::{
DropAssets, FeeManager, ProcessTransaction, Properties, ShouldExecute, TransactAsset,
WeightBounds, WeightTrader,
},
AssetsInHolding, Config, FeeReason, XcmExecutor,
};
/// We create an XCVM instance instead of calling `XcmExecutor::<_>::prepare_and_execute` so we
/// can inspect its fields.
pub fn instantiate_executor(
origin: impl Into<Location>,
message: Xcm<<XcmConfig as Config>::RuntimeCall>,
) -> (XcmExecutor<XcmConfig>, Weight) {
let mut vm =
XcmExecutor::<XcmConfig>::new(origin, message.using_encoded(sp_io::hashing::blake2_256));
let weight = XcmExecutor::<XcmConfig>::prepare(message.clone(), Weight::MAX)
.unwrap()
.weight_of();
vm.message_weight = weight;
(vm, weight)
}
parameter_types! {
pub const MaxAssetsIntoHolding: u32 = 10;
pub const BaseXcmWeight: Weight = Weight::from_parts(1, 1);
pub const MaxInstructions: u32 = 10;
pub UniversalLocation: InteriorLocation = [GlobalConsensus(ByGenesis([0; 32])), Teyrchain(1000)].into();
/// Simulate the chain’s existential deposit.
pub const ExistentialDeposit: u128 = 2;
}
/// Test origin.
#[derive(Debug)]
pub struct TestOrigin;
/// Test call.
///
/// Doesn't dispatch anything, has an empty implementation of [`Dispatchable`] that
/// just returns `Ok` with an empty [`PostDispatchInfo`].
#[derive(
Debug, Encode, Decode, DecodeWithMemTracking, Eq, PartialEq, Clone, Copy, scale_info::TypeInfo,
)]
pub struct TestCall;
impl Dispatchable for TestCall {
type RuntimeOrigin = TestOrigin;
type Config = ();
type Info = ();
type PostInfo = PostDispatchInfo;
fn dispatch(self, _origin: Self::RuntimeOrigin) -> DispatchResultWithPostInfo {
Ok(PostDispatchInfo::default())
}
}
impl GetDispatchInfo for TestCall {
fn get_dispatch_info(&self) -> DispatchInfo {
DispatchInfo::default()
}
}
/// Test weigher that just returns a fixed weight for every program.
pub struct TestWeigher;
impl<C> WeightBounds<C> for TestWeigher {
fn weight(_message: &mut Xcm<C>, _weight_limit: Weight) -> Result<Weight, InstructionError> {
Ok(Weight::from_parts(2, 2))
}
fn instr_weight(_instruction: &mut Instruction<C>) -> Result<Weight, XcmError> {
Ok(Weight::from_parts(2, 2))
}
}
thread_local! {
pub static ASSETS: RefCell<BTreeMap<Location, AssetsInHolding>> = RefCell::new(BTreeMap::new());
pub static SENT_XCM: RefCell<Vec<(Location, Xcm<()>)>> = RefCell::new(Vec::new());
}
pub fn add_asset(who: impl Into<Location>, what: impl Into<Asset>) {
ASSETS.with(|a| {
a.borrow_mut()
.entry(who.into())
.or_insert(AssetsInHolding::new())
.subsume(what.into())
});
}
pub fn asset_list(who: impl Into<Location>) -> Vec<Asset> {
Assets::from(assets(who)).into_inner()
}
pub fn assets(who: impl Into<Location>) -> AssetsInHolding {
ASSETS.with(|a| a.borrow().get(&who.into()).cloned()).unwrap_or_default()
}
pub fn get_first_fungible(assets: &AssetsInHolding) -> Option<Asset> {
assets.fungible_assets_iter().next()
}
/// Test asset transactor that withdraws from and deposits to a thread local assets storage.
pub struct TestAssetTransactor;
impl TransactAsset for TestAssetTransactor {
fn deposit_asset(
what: &Asset,
who: &Location,
_context: Option<&XcmContext>,
) -> Result<(), XcmError> {
if let Fungibility::Fungible(amount) = what.fun {
// fail if below the configured existential deposit
if amount < ExistentialDeposit::get() {
return Err(XcmError::FailedToTransactAsset(
sp_runtime::TokenError::BelowMinimum.into(),
));
}
}
add_asset(who.clone(), what.clone());
Ok(())
}
fn withdraw_asset(
what: &Asset,
who: &Location,
_context: Option<&XcmContext>,
) -> Result<AssetsInHolding, XcmError> {
ASSETS.with(|a| {
a.borrow_mut()
.get_mut(who)
.ok_or(XcmError::NotWithdrawable)?
.try_take(what.clone().into())
.map_err(|_| XcmError::NotWithdrawable)
})
}
}
/// Test barrier that just lets everything through.
pub struct TestBarrier;
impl ShouldExecute for TestBarrier {
fn should_execute<Call>(
_origin: &Location,
_instructions: &mut [Instruction<Call>],
_max_weight: Weight,
_properties: &mut Properties,
) -> Result<(), ProcessMessageError> {
Ok(())
}
}
/// Test weight to fee that just multiplies `Weight.ref_time` and `Weight.proof_size`.
pub struct WeightToFee;
impl WeightToFee {
pub fn weight_to_fee(weight: &Weight) -> u128 {
weight.ref_time() as u128 * weight.proof_size() as u128
}
}
/// Test weight trader that just buys weight with the native asset (`Here`) and
/// uses the test `WeightToFee`.
pub struct TestTrader {
weight_bought_so_far: Weight,
}
impl WeightTrader for TestTrader {
fn new() -> Self {
Self { weight_bought_so_far: Weight::zero() }
}
fn buy_weight(
&mut self,
weight: Weight,
payment: AssetsInHolding,
_context: &XcmContext,
) -> Result<AssetsInHolding, XcmError> {
let amount = WeightToFee::weight_to_fee(&weight);
let required: Asset = (Here, amount).into();
let unused = payment.checked_sub(required).map_err(|_| XcmError::TooExpensive)?;
self.weight_bought_so_far.saturating_add(weight);
Ok(unused)
}
fn refund_weight(&mut self, weight: Weight, _context: &XcmContext) -> Option<Asset> {
let weight = weight.min(self.weight_bought_so_far);
let amount = WeightToFee::weight_to_fee(&weight);
self.weight_bought_so_far -= weight;
if amount > 0 {
Some((Here, amount).into())
} else {
None
}
}
}
/// Account where all dropped assets are deposited.
pub const TRAPPED_ASSETS: [u8; 32] = [255; 32];
/// Test asset trap that moves all dropped assets to the `TRAPPED_ASSETS` account.
pub struct TestAssetTrap;
impl DropAssets for TestAssetTrap {
fn drop_assets(_origin: &Location, assets: AssetsInHolding, _context: &XcmContext) -> Weight {
ASSETS.with(|a| {
a.borrow_mut()
.entry(TRAPPED_ASSETS.into())
.or_insert(AssetsInHolding::new())
.subsume_assets(assets)
});
Weight::zero()
}
}
/// Test sender that always succeeds and puts messages in a dummy queue.
///
/// It charges `1` for the delivery fee.
pub struct TestSender;
impl SendXcm for TestSender {
type Ticket = (Location, Xcm<()>);
fn validate(
destination: &mut Option<Location>,
message: &mut Option<Xcm<()>>,
) -> SendResult<Self::Ticket> {
let ticket = (destination.take().unwrap(), message.take().unwrap());
let delivery_fee: Asset = (Here, 1u128).into();
Ok((ticket, delivery_fee.into()))
}
fn deliver(ticket: Self::Ticket) -> Result<XcmHash, SendError> {
SENT_XCM.with(|q| q.borrow_mut().push(ticket));
Ok([0; 32])
}
}
/// Gets queued test messages.
pub fn sent_xcm() -> Vec<(Location, Xcm<()>)> {
SENT_XCM.with(|q| (*q.borrow()).clone())
}
/// A mock contract address that doesn't need to pay for fees.
pub const WAIVED_CONTRACT_ADDRESS: [u8; 20] = [128; 20];
/// Test fee manager that will waive the fee for some origins.
///
/// Doesn't do anything with the fee, which effectively burns it.
pub struct TestFeeManager;
impl FeeManager for TestFeeManager {
fn is_waived(origin: Option<&Location>, _: FeeReason) -> bool {
let Some(origin) = origin else { return false };
// Match the root origin and a particular smart contract account.
matches!(
origin.unpack(),
(0, []) | (0, [AccountKey20 { network: None, key: WAIVED_CONTRACT_ADDRESS }])
)
}
fn handle_fee(_: Assets, _: Option<&XcmContext>, _: FeeReason) {}
}
/// Dummy transactional processor that doesn't rollback storage changes, just
/// aims to rollback executor state.
pub struct TestTransactionalProcessor;
impl ProcessTransaction for TestTransactionalProcessor {
const IS_TRANSACTIONAL: bool = true;
fn process<F>(f: F) -> Result<(), XcmError>
where
F: FnOnce() -> Result<(), XcmError>,
{
f()
}
}
/// Test XcmConfig that uses all the test implementations in this file.
pub struct XcmConfig;
impl Config for XcmConfig {
type RuntimeCall = TestCall;
type XcmSender = TestSender;
type XcmEventEmitter = ();
type AssetTransactor = TestAssetTransactor;
type OriginConverter = ();
type IsReserve = ();
type IsTeleporter = ();
type UniversalLocation = UniversalLocation;
type Barrier = TestBarrier;
type Weigher = TestWeigher;
type Trader = TestTrader;
type ResponseHandler = ();
type AssetTrap = TestAssetTrap;
type AssetLocker = ();
type AssetExchanger = ();
type AssetClaims = ();
type SubscriptionService = ();
type PalletInstancesInfo = ();
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type FeeManager = TestFeeManager;
type MessageExporter = ();
type UniversalAliases = Nothing;
type CallDispatcher = Self::RuntimeCall;
type SafeCallFilter = Everything;
type Aliasers = Nothing;
type TransactionalProcessor = TestTransactionalProcessor;
type HrmpNewChannelOpenRequestHandler = ();
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type XcmRecorder = ();
}
+26
View File
@@ -0,0 +1,26 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Unit tests for the XCM executor.
//!
//! These exclude any cross-chain functionality. For those, look at the
//! `xcm-emulator` based tests in the cumulus folder.
//! These tests deal with internal state changes of the XCVM.
mod initiate_transfer;
mod mock;
mod pay_fees;
mod set_asset_claimer;
@@ -0,0 +1,346 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Unit tests related to the `fees` register and `PayFees` instruction.
//!
//! See [Fellowship RFC 105](https://github.com/polkadot-fellows/rfCs/pull/105)
//! and the [specification](https://github.com/polkadot-fellows/xcm-format) for more information.
use xcm::prelude::*;
use super::mock::*;
// The sender and recipient we use across these tests.
const SENDER: [u8; 32] = [0; 32];
const RECIPIENT: [u8; 32] = [1; 32];
// ===== Happy path =====
// This is a sort of backwards compatibility test.
// Since `PayFees` is a replacement for `BuyExecution`, we need to make sure it at least
// manages to do the same thing, paying for execution fees.
#[test]
fn works_for_execution_fees() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
// Build xcm.
let xcm = Xcm::<TestCall>::builder()
.withdraw_asset((Here, 100u128))
.pay_fees((Here, 10u128)) // 10% destined for fees, not more.
.deposit_asset(All, RECIPIENT)
.build();
let (mut vm, weight) = instantiate_executor(SENDER, xcm.clone());
// Program runs successfully.
assert!(vm.bench_process(xcm).is_ok());
// Nothing is left in the `holding` register.
assert_eq!(get_first_fungible(vm.holding()), None);
// Execution fees were 4, so we still have 6 left in the `fees` register.
assert_eq!(get_first_fungible(vm.fees()).unwrap(), (Here, 6u128).into());
// The recipient received all the assets in the holding register, so `100` that
// were withdrawn, minus the `10` that were destinated for fee payment.
assert_eq!(asset_list(RECIPIENT), [(Here, 90u128).into()]);
// Leftover fees get trapped.
assert!(vm.bench_post_process(weight).ensure_complete().is_ok());
assert_eq!(asset_list(TRAPPED_ASSETS), [(Here, 6u128).into()])
}
// This tests the new functionality provided by `PayFees`, being able to pay for
// delivery fees from the `fees` register.
#[test]
fn works_for_delivery_fees() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
// Information to send messages.
// We don't care about the specifics since we're not actually sending them.
let query_response_info =
QueryResponseInfo { destination: Parent.into(), query_id: 0, max_weight: Weight::zero() };
// Build xcm.
let xcm = Xcm::<TestCall>::builder()
.withdraw_asset((Here, 100u128))
// We load `10` plancks to pay for fees.
.pay_fees((Here, 10u128))
// Send a bunch of messages, each charging delivery fees.
.report_error(query_response_info.clone())
.report_error(query_response_info.clone())
.report_error(query_response_info)
.deposit_asset(All, RECIPIENT)
.build();
let (mut vm, _) = instantiate_executor(SENDER, xcm.clone());
// Program runs successfully.
assert!(vm.bench_process(xcm).is_ok());
// Nothing is left in the `holding` register.
assert_eq!(get_first_fungible(vm.holding()), None);
// Execution fees were 4, delivery were 3, so we are left with only 3 in the `fees` register.
assert_eq!(get_first_fungible(vm.fees()).unwrap(), (Here, 3u128).into());
// The recipient received all the assets in the holding register, so `100` that
// were withdrawn, minus the `10` that were destinated for fee payment.
assert_eq!(asset_list(RECIPIENT), [(Here, 90u128).into()]);
let querier: Location =
(Teyrchain(1000), AccountId32 { id: SENDER.into(), network: None }).into();
let sent_message = Xcm(vec![
QueryResponse {
query_id: 0,
response: Response::ExecutionResult(None),
max_weight: Weight::zero(),
querier: Some(querier),
},
SetTopic(vm.context.topic_or_message_id()),
]);
// The messages were "sent" successfully.
assert_eq!(
sent_xcm(),
vec![
(Parent.into(), sent_message.clone()),
(Parent.into(), sent_message.clone()),
(Parent.into(), sent_message.clone())
]
);
}
// Tests the support for `BuyExecution` while the ecosystem transitions to `PayFees`.
#[test]
fn buy_execution_works_as_before() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
// Build xcm.
let xcm = Xcm::<TestCall>::builder()
.withdraw_asset((Here, 100u128))
// We can put everything here, since excess will be returned to holding.
// We have to specify `Limited` here to actually work, it's normally
// set in the `AllowTopLevelPaidExecutionFrom` barrier.
.buy_execution((Here, 100u128), Limited(Weight::from_parts(2, 2)))
.deposit_asset(All, RECIPIENT)
.build();
let (mut vm, _) = instantiate_executor(SENDER, xcm.clone());
// Program runs successfully.
assert!(vm.bench_process(xcm).is_ok());
// Nothing is left in the `holding` register.
assert_eq!(get_first_fungible(vm.holding()), None);
// `BuyExecution` does not interact with the `fees` register.
assert_eq!(get_first_fungible(vm.fees()), None);
// The recipient received all the assets in the holding register, so `100` that
// were withdrawn, minus the `4` from paying the execution fees.
assert_eq!(asset_list(RECIPIENT), [(Here, 96u128).into()]);
}
// Tests the interaction between `PayFees` and `RefundSurplus`.
#[test]
fn fees_can_be_refunded() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
// Build xcm.
let xcm = Xcm::<TestCall>::builder()
.withdraw_asset((Here, 100u128))
.pay_fees((Here, 10u128)) // 10% destined for fees, not more.
.deposit_asset(All, RECIPIENT)
.refund_surplus()
.deposit_asset(All, SENDER)
.build();
let (mut vm, _) = instantiate_executor(SENDER, xcm.clone());
// Program runs successfully.
assert!(vm.bench_process(xcm).is_ok());
// Nothing is left in the `holding` register.
assert_eq!(get_first_fungible(vm.holding()), None);
// Nothing was left in the `fees` register since it was refunded.
assert_eq!(get_first_fungible(vm.fees()), None);
// The recipient received all the assets in the holding register, so `100` that
// were withdrawn, minus the `10` that were destinated for fee payment.
assert_eq!(asset_list(RECIPIENT), [(Here, 90u128).into()]);
// The sender got back `6` from unused assets.
assert_eq!(asset_list(SENDER), [(Here, 6u128).into()]);
}
// ===== Unhappy path =====
#[test]
fn putting_all_assets_in_pay_fees() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
// Build xcm.
let xcm = Xcm::<TestCall>::builder()
.withdraw_asset((Here, 100u128))
.pay_fees((Here, 100u128)) // 100% destined for fees, this is not going to end well...
.deposit_asset(All, RECIPIENT)
.build();
let (mut vm, _) = instantiate_executor(SENDER, xcm.clone());
// Program runs successfully.
assert!(vm.bench_process(xcm).is_ok());
// Nothing is left in the `holding` register.
assert_eq!(get_first_fungible(vm.holding()), None);
// We destined `100` for fee payment, after `4` for execution fees, we are left with `96`.
assert_eq!(get_first_fungible(vm.fees()).unwrap(), (Here, 96u128).into());
// The recipient received no assets since they were all destined for fee payment.
assert_eq!(asset_list(RECIPIENT), []);
}
#[test]
fn putting_more_than_available_fails() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
// Build xcm.
let xcm = Xcm::<TestCall>::builder()
.withdraw_asset((Here, 100u128))
.pay_fees((Here, 200u128)) // 200% destined for fees, there's not even that much!
.deposit_asset(All, RECIPIENT)
.build();
let (mut vm, weight) = instantiate_executor(SENDER, xcm.clone());
// Program fails.
assert!(vm.bench_process(xcm).is_err());
// Everything is left in the `holding` register.
assert_eq!(get_first_fungible(vm.holding()).unwrap(), (Here, 100u128).into());
// Nothing in the `fees` register.
assert_eq!(get_first_fungible(vm.fees()), None);
// The recipient received no assets since message failed.
assert_eq!(asset_list(RECIPIENT), []);
// Leftover assets get trapped.
assert!(vm.bench_post_process(weight).ensure_complete().is_ok());
assert_eq!(asset_list(TRAPPED_ASSETS), [(Here, 100u128).into()]);
}
#[test]
fn refunding_too_early() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
// Information to send messages.
// We don't care about the specifics since we're not actually sending them.
let query_response_info =
QueryResponseInfo { destination: Parent.into(), query_id: 0, max_weight: Weight::zero() };
// Build xcm.
let xcm = Xcm::<TestCall>::builder()
.withdraw_asset((Here, 100u128))
.pay_fees((Here, 10u128)) // 10% destined for fees, not more.
.deposit_asset(All, RECIPIENT)
.refund_surplus()
.deposit_asset(All, SENDER)
// `refund_surplus` cleared the `fees` register.
// `holding` is used as a fallback, but we also cleared that.
// The instruction will error and the message won't be sent :(.
.report_error(query_response_info)
.build();
let (mut vm, _) = instantiate_executor(SENDER, xcm.clone());
// Program fails to run.
assert!(vm.bench_process(xcm).is_err());
// Nothing is left in the `holding` register.
assert_eq!(get_first_fungible(vm.holding()), None);
// Nothing was left in the `fees` register since it was refunded.
assert_eq!(get_first_fungible(vm.fees()), None);
// The recipient received all the assets in the holding register, so `100` that
// were withdrawn, minus the `10` that were destinated for fee payment.
assert_eq!(asset_list(RECIPIENT), [(Here, 90u128).into()]);
// The sender got back `6` from unused assets.
assert_eq!(asset_list(SENDER), [(Here, 6u128).into()]);
// No messages were "sent".
assert_eq!(sent_xcm(), Vec::new());
}
#[test]
fn pay_fees_is_processed_only_once() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
let xcm = Xcm::<TestCall>::builder()
.withdraw_asset((Here, 100u128))
.pay_fees((Here, 10u128))
// Will both be a noop.
.pay_fees((Parent, 10u128))
.pay_fees((Here, 200u128))
.deposit_asset(All, RECIPIENT)
.build();
let (mut vm, weight) = instantiate_executor(SENDER, xcm.clone());
// Program runs successfully.
assert!(vm.bench_process(xcm).is_ok());
// Nothing left in the `holding` register.
assert_eq!(get_first_fungible(vm.holding()), None);
// Only the first `PayFees` was executed and execution fees are 4,
// so there are 6 fees left in the `fees` register.
assert_eq!(get_first_fungible(vm.fees()).unwrap(), (Here, 6u128).into());
// Leftover fees get trapped.
assert!(vm.bench_post_process(weight).ensure_complete().is_ok());
assert_eq!(asset_list(TRAPPED_ASSETS), [(Here, 6u128).into()]);
}
#[test]
fn already_paid_fees_rolls_back_on_error() {
// Make sure the sender has enough funds to withdraw.
add_asset(SENDER, (Here, 100u128));
let xcm = Xcm::<TestCall>::builder()
.withdraw_asset((Here, 100u128))
.pay_fees((Here, 200u128))
.deposit_asset(All, RECIPIENT)
.build();
let (mut vm, _) = instantiate_executor(SENDER, xcm.clone());
// Program fails.
assert!(vm.bench_process(xcm).is_err());
// Everything left in the `holding` register.
assert_eq!(get_first_fungible(vm.holding()).unwrap(), (Here, 100u128).into());
// Nothing in the `fees` register.
assert_eq!(get_first_fungible(vm.fees()), None);
// Already paid fees is false.
assert_eq!(vm.already_paid_fees(), false);
}
@@ -0,0 +1,142 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezkuwi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Unit tests related to the `fees` register and `PayFees` instruction.
//!
//! See [Fellowship RFC 105](https://github.com/polkadot-fellows/rfCs/pull/105)
//! and the [specification](https://github.com/polkadot-fellows/xcm-format) for more information.
use codec::Encode;
use xcm::prelude::*;
use super::mock::*;
use crate::XcmExecutor;
#[test]
fn set_asset_claimer() {
let sender = Location::new(0, [AccountId32 { id: [0; 32], network: None }]);
let bob = Location::new(0, [AccountId32 { id: [2; 32], network: None }]);
// Make sure the user has enough funds to withdraw.
add_asset(sender.clone(), (Here, 100u128));
// Build xcm.
let xcm = Xcm::<TestCall>::builder_unsafe()
// if withdrawing fails we're not missing any corner case.
.withdraw_asset((Here, 100u128))
.clear_origin()
.set_hints(vec![AssetClaimer { location: bob.clone() }])
.pay_fees((Here, 10u128)) // 10% destined for fees, not more.
.build();
// We create an XCVM instance instead of calling `XcmExecutor::<_>::prepare_and_execute` so we
// can inspect its fields.
let mut vm =
XcmExecutor::<XcmConfig>::new(sender, xcm.using_encoded(sp_io::hashing::blake2_256));
vm.message_weight =
XcmExecutor::<XcmConfig>::prepare(xcm.clone(), Weight::MAX).unwrap().weight_of();
let result = vm.bench_process(xcm);
assert!(result.is_ok());
assert_eq!(vm.asset_claimer(), Some(bob));
}
#[test]
fn do_not_set_asset_claimer_none() {
let sender = Location::new(0, [AccountId32 { id: [0; 32], network: None }]);
// Make sure the user has enough funds to withdraw.
add_asset(sender.clone(), (Here, 100u128));
// Build xcm.
let xcm = Xcm::<TestCall>::builder_unsafe()
// if withdrawing fails we're not missing any corner case.
.withdraw_asset((Here, 100u128))
.clear_origin()
.pay_fees((Here, 10u128)) // 10% destined for fees, not more.
.build();
// We create an XCVM instance instead of calling `XcmExecutor::<_>::prepare_and_execute` so we
// can inspect its fields.
let mut vm =
XcmExecutor::<XcmConfig>::new(sender, xcm.using_encoded(sp_io::hashing::blake2_256));
vm.message_weight =
XcmExecutor::<XcmConfig>::prepare(xcm.clone(), Weight::MAX).unwrap().weight_of();
let result = vm.bench_process(xcm);
assert!(result.is_ok());
assert_eq!(vm.asset_claimer(), None);
}
#[test]
fn trap_then_set_asset_claimer() {
let sender = Location::new(0, [AccountId32 { id: [0; 32], network: None }]);
let bob = Location::new(0, [AccountId32 { id: [2; 32], network: None }]);
// Make sure the user has enough funds to withdraw.
add_asset(sender.clone(), (Here, 100u128));
// Build xcm.
let xcm = Xcm::<TestCall>::builder_unsafe()
// if withdrawing fails we're not missing any corner case.
.withdraw_asset((Here, 100u128))
.clear_origin()
.trap(0u64)
.set_hints(vec![AssetClaimer { location: bob }])
.pay_fees((Here, 10u128)) // 10% destined for fees, not more.
.build();
// We create an XCVM instance instead of calling `XcmExecutor::<_>::prepare_and_execute` so we
// can inspect its fields.
let mut vm =
XcmExecutor::<XcmConfig>::new(sender, xcm.using_encoded(sp_io::hashing::blake2_256));
vm.message_weight =
XcmExecutor::<XcmConfig>::prepare(xcm.clone(), Weight::MAX).unwrap().weight_of();
let result = vm.bench_process(xcm);
assert!(result.is_err());
assert_eq!(vm.asset_claimer(), None);
}
#[test]
fn set_asset_claimer_then_trap() {
let sender = Location::new(0, [AccountId32 { id: [0; 32], network: None }]);
let bob = Location::new(0, [AccountId32 { id: [2; 32], network: None }]);
// Make sure the user has enough funds to withdraw.
add_asset(sender.clone(), (Here, 100u128));
// Build xcm.
let xcm = Xcm::<TestCall>::builder_unsafe()
// if withdrawing fails we're not missing any corner case.
.withdraw_asset((Here, 100u128))
.clear_origin()
.set_hints(vec![AssetClaimer { location: bob.clone() }])
.trap(0u64)
.pay_fees((Here, 10u128)) // 10% destined for fees, not more.
.build();
// We create an XCVM instance instead of calling `XcmExecutor::<_>::prepare_and_execute` so we
// can inspect its fields.
let mut vm =
XcmExecutor::<XcmConfig>::new(sender, xcm.using_encoded(sp_io::hashing::blake2_256));
vm.message_weight =
XcmExecutor::<XcmConfig>::prepare(xcm.clone(), Weight::MAX).unwrap().weight_of();
let result = vm.bench_process(xcm);
assert!(result.is_err());
assert_eq!(vm.asset_claimer(), Some(bob));
}