Files
pezkuwi-subxt/parachains/runtimes/assets/statemine/tests/tests.rs
T
Bastian Köcher 66887505e6 Fix runtime api import path (#2319)
This syncs the latest changes in Substrate and fixes the import path of the runtime api.
2023-03-14 23:09:33 +00:00

476 lines
15 KiB
Rust

use asset_test_utils::{ExtBuilder, RuntimeHelper};
use codec::Encode;
use cumulus_primitives_utility::ChargeWeightInFungibles;
use frame_support::{
assert_noop, assert_ok, sp_io,
weights::{Weight, WeightToFee as WeightToFeeT},
};
use parachains_common::{AccountId, AuraId, Balance};
use statemine_runtime::xcm_config::{
AssetFeeAsExistentialDepositMultiplierFeeCharger, KsmLocation, TrustBackedAssetsPalletLocation,
};
pub use statemine_runtime::{
constants::fee::WeightToFee, xcm_config::XcmConfig, Assets, Balances, ExistentialDeposit,
ReservedDmpWeight, Runtime, SessionKeys, System,
};
use xcm::latest::prelude::*;
use xcm_executor::{
traits::{Convert, WeightTrader},
XcmExecutor,
};
pub const ALICE: [u8; 32] = [1u8; 32];
type AssetIdForTrustBackedAssetsConvert =
assets_common::AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation>;
#[test]
fn test_asset_xcm_trader() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
// We need root origin to create a sufficient asset
let minimum_asset_balance = 3333333_u128;
let local_asset_id = 1;
assert_ok!(Assets::force_create(
RuntimeHelper::<Runtime>::root_origin(),
local_asset_id.into(),
AccountId::from(ALICE).into(),
true,
minimum_asset_balance
));
// We first mint enough asset for the account to exist for assets
assert_ok!(Assets::mint(
RuntimeHelper::<Runtime>::origin_of(AccountId::from(ALICE)),
local_asset_id.into(),
AccountId::from(ALICE).into(),
minimum_asset_balance
));
// get asset id as multilocation
let asset_multilocation =
AssetIdForTrustBackedAssetsConvert::reverse_ref(local_asset_id).unwrap();
// Set Alice as block author, who will receive fees
RuntimeHelper::<Runtime>::run_to_block(2, Some(AccountId::from(ALICE)));
// We are going to buy 4e9 weight
let bought = Weight::from_parts(4_000_000_000u64, 0);
// Lets calculate amount needed
let asset_amount_needed =
AssetFeeAsExistentialDepositMultiplierFeeCharger::charge_weight_in_fungibles(
local_asset_id,
bought,
)
.expect("failed to compute");
// Lets pay with: asset_amount_needed + asset_amount_extra
let asset_amount_extra = 100_u128;
let asset: MultiAsset =
(asset_multilocation.clone(), asset_amount_needed + asset_amount_extra).into();
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
// Lets buy_weight and make sure buy_weight does not return an error
match trader.buy_weight(bought, asset.into()) {
Ok(unused_assets) => {
// Check whether a correct amount of unused assets is returned
assert_ok!(unused_assets
.ensure_contains(&(asset_multilocation, asset_amount_extra).into()));
},
Err(e) => assert!(false, "Expected Ok(_). Got {:#?}", e),
}
// Drop trader
drop(trader);
// Make sure author(Alice) has received the amount
assert_eq!(
Assets::balance(local_asset_id, AccountId::from(ALICE)),
minimum_asset_balance + asset_amount_needed
);
// We also need to ensure the total supply increased
assert_eq!(
Assets::total_supply(local_asset_id),
minimum_asset_balance + asset_amount_needed
);
});
}
#[test]
fn test_asset_xcm_trader_with_refund() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
// We need root origin to create a sufficient asset
// We set existential deposit to be identical to the one for Balances first
assert_ok!(Assets::force_create(
RuntimeHelper::<Runtime>::root_origin(),
1.into(),
AccountId::from(ALICE).into(),
true,
ExistentialDeposit::get()
));
// We first mint enough asset for the account to exist for assets
assert_ok!(Assets::mint(
RuntimeHelper::<Runtime>::origin_of(AccountId::from(ALICE)),
1.into(),
AccountId::from(ALICE).into(),
ExistentialDeposit::get()
));
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
// Set Alice as block author, who will receive fees
RuntimeHelper::<Runtime>::run_to_block(2, Some(AccountId::from(ALICE)));
// We are going to buy 4e9 weight
let bought = Weight::from_parts(4_000_000_000u64, 0);
let asset_multilocation = AssetIdForTrustBackedAssetsConvert::reverse_ref(1).unwrap();
// lets calculate amount needed
let amount_bought = WeightToFee::weight_to_fee(&bought);
let asset: MultiAsset = (asset_multilocation.clone(), amount_bought).into();
// Make sure buy_weight does not return an error
assert_ok!(trader.buy_weight(bought, asset.clone().into()));
// Make sure again buy_weight does return an error
// This assert relies on the fact, that we use `TakeFirstAssetTrader` in `WeightTrader` tuple chain, which cannot be called twice
assert_noop!(trader.buy_weight(bought, asset.into()), XcmError::TooExpensive);
// We actually use half of the weight
let weight_used = bought / 2;
// Make sure refurnd works.
let amount_refunded = WeightToFee::weight_to_fee(&(bought - weight_used));
assert_eq!(
trader.refund_weight(bought - weight_used),
Some((asset_multilocation, amount_refunded).into())
);
// Drop trader
drop(trader);
// We only should have paid for half of the bought weight
let fees_paid = WeightToFee::weight_to_fee(&weight_used);
assert_eq!(
Assets::balance(1, AccountId::from(ALICE)),
ExistentialDeposit::get() + fees_paid
);
// We also need to ensure the total supply increased
assert_eq!(Assets::total_supply(1), ExistentialDeposit::get() + fees_paid);
});
}
#[test]
fn test_asset_xcm_trader_refund_not_possible_since_amount_less_than_ed() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
// We need root origin to create a sufficient asset
// We set existential deposit to be identical to the one for Balances first
assert_ok!(Assets::force_create(
RuntimeHelper::<Runtime>::root_origin(),
1.into(),
AccountId::from(ALICE).into(),
true,
ExistentialDeposit::get()
));
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
// Set Alice as block author, who will receive fees
RuntimeHelper::<Runtime>::run_to_block(2, Some(AccountId::from(ALICE)));
// We are going to buy small amount
let bought = Weight::from_parts(500_000_000u64, 0);
let asset_multilocation = AssetIdForTrustBackedAssetsConvert::reverse_ref(1).unwrap();
let amount_bought = WeightToFee::weight_to_fee(&bought);
assert!(
amount_bought < ExistentialDeposit::get(),
"we are testing what happens when the amount does not exceed ED"
);
let asset: MultiAsset = (asset_multilocation.clone(), amount_bought).into();
// Buy weight should return an error
assert_noop!(trader.buy_weight(bought, asset.into()), XcmError::TooExpensive);
// not credited since the ED is higher than this value
assert_eq!(Assets::balance(1, AccountId::from(ALICE)), 0);
// We also need to ensure the total supply did not increase
assert_eq!(Assets::total_supply(1), 0);
});
}
#[test]
fn test_that_buying_ed_refund_does_not_refund() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
// We need root origin to create a sufficient asset
// We set existential deposit to be identical to the one for Balances first
assert_ok!(Assets::force_create(
RuntimeHelper::<Runtime>::root_origin(),
1.into(),
AccountId::from(ALICE).into(),
true,
ExistentialDeposit::get()
));
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
// Set Alice as block author, who will receive fees
RuntimeHelper::<Runtime>::run_to_block(2, Some(AccountId::from(ALICE)));
// We are gonna buy ED
let bought = Weight::from_parts(ExistentialDeposit::get().try_into().unwrap(), 0);
let asset_multilocation = AssetIdForTrustBackedAssetsConvert::reverse_ref(1).unwrap();
let amount_bought = WeightToFee::weight_to_fee(&bought);
assert!(
amount_bought < ExistentialDeposit::get(),
"we are testing what happens when the amount does not exceed ED"
);
// We know we will have to buy at least ED, so lets make sure first it will
// fail with a payment of less than ED
let asset: MultiAsset = (asset_multilocation.clone(), amount_bought).into();
assert_noop!(trader.buy_weight(bought, asset.into()), XcmError::TooExpensive);
// Now lets buy ED at least
let asset: MultiAsset = (asset_multilocation.clone(), ExistentialDeposit::get()).into();
// Buy weight should work
assert_ok!(trader.buy_weight(bought, asset.into()));
// Should return None. We have a specific check making sure we dont go below ED for
// drop payment
assert_eq!(trader.refund_weight(bought), None);
// Drop trader
drop(trader);
// Make sure author(Alice) has received the amount
assert_eq!(Assets::balance(1, AccountId::from(ALICE)), ExistentialDeposit::get());
// We also need to ensure the total supply increased
assert_eq!(Assets::total_supply(1), ExistentialDeposit::get());
});
}
#[test]
fn test_asset_xcm_trader_not_possible_for_non_sufficient_assets() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
// Create a non-sufficient asset with specific existential deposit
let minimum_asset_balance = 1_000_000_u128;
assert_ok!(Assets::force_create(
RuntimeHelper::<Runtime>::root_origin(),
1.into(),
AccountId::from(ALICE).into(),
false,
minimum_asset_balance
));
// We first mint enough asset for the account to exist for assets
assert_ok!(Assets::mint(
RuntimeHelper::<Runtime>::origin_of(AccountId::from(ALICE)),
1.into(),
AccountId::from(ALICE).into(),
minimum_asset_balance
));
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
// Set Alice as block author, who will receive fees
RuntimeHelper::<Runtime>::run_to_block(2, Some(AccountId::from(ALICE)));
// We are going to buy 4e9 weight
let bought = Weight::from_parts(4_000_000_000u64, 0);
// lets calculate amount needed
let asset_amount_needed = WeightToFee::weight_to_fee(&bought);
let asset_multilocation = AssetIdForTrustBackedAssetsConvert::reverse_ref(1).unwrap();
let asset: MultiAsset = (asset_multilocation, asset_amount_needed).into();
// Make sure again buy_weight does return an error
assert_noop!(trader.buy_weight(bought, asset.into()), XcmError::TooExpensive);
// Drop trader
drop(trader);
// Make sure author(Alice) has NOT received the amount
assert_eq!(Assets::balance(1, AccountId::from(ALICE)), minimum_asset_balance);
// We also need to ensure the total supply NOT increased
assert_eq!(Assets::total_supply(1), minimum_asset_balance);
});
}
#[test]
fn test_assets_balances_api_works() {
use assets_common::runtime_api::runtime_decl_for_fungibles_api::FungiblesApi;
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
let local_asset_id = 1;
// check before
assert_eq!(Assets::balance(local_asset_id, AccountId::from(ALICE)), 0);
assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 0);
assert!(Runtime::query_account_balances(AccountId::from(ALICE)).unwrap().is_empty());
// Drip some balance
use frame_support::traits::fungible::Mutate;
let some_currency = ExistentialDeposit::get();
Balances::mint_into(&AccountId::from(ALICE), some_currency).unwrap();
// We need root origin to create a sufficient asset
let minimum_asset_balance = 3333333_u128;
assert_ok!(Assets::force_create(
RuntimeHelper::<Runtime>::root_origin(),
local_asset_id.into(),
AccountId::from(ALICE).into(),
true,
minimum_asset_balance
));
// We first mint enough asset for the account to exist for assets
assert_ok!(Assets::mint(
RuntimeHelper::<Runtime>::origin_of(AccountId::from(ALICE)),
local_asset_id.into(),
AccountId::from(ALICE).into(),
minimum_asset_balance
));
// check after
assert_eq!(
Assets::balance(local_asset_id, AccountId::from(ALICE)),
minimum_asset_balance
);
assert_eq!(Balances::free_balance(AccountId::from(ALICE)), some_currency);
let result = Runtime::query_account_balances(AccountId::from(ALICE)).unwrap();
assert_eq!(result.len(), 2);
// check currency
assert!(result.iter().any(|asset| asset.eq(
&assets_common::fungible_conversion::convert_balance::<KsmLocation, Balance>(
some_currency
)
.unwrap()
)));
// check trusted asset
assert!(result.iter().any(|asset| asset.eq(&(
AssetIdForTrustBackedAssetsConvert::reverse_ref(local_asset_id).unwrap(),
minimum_asset_balance
)
.into())));
});
}
#[test]
fn receive_teleported_asset_works() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
let xcm = Xcm(vec![
ReceiveTeleportedAsset(MultiAssets::from(vec![MultiAsset {
id: Concrete(MultiLocation { parents: 1, interior: Here }),
fun: Fungible(10000000000000),
}])),
ClearOrigin,
BuyExecution {
fees: MultiAsset {
id: Concrete(MultiLocation { parents: 1, interior: Here }),
fun: Fungible(10000000000000),
},
weight_limit: Limited(Weight::from_parts(303531000, 65536)),
},
DepositAsset {
assets: Wild(AllCounted(1)),
beneficiary: MultiLocation {
parents: 0,
interior: X1(AccountId32 {
network: None,
id: [
18, 153, 85, 112, 1, 245, 88, 21, 211, 252, 181, 60, 116, 70, 58,
203, 12, 246, 209, 77, 70, 57, 179, 64, 152, 44, 96, 135, 127, 56,
70, 9,
],
}),
},
},
]);
let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
let weight_limit = ReservedDmpWeight::get();
let outcome = XcmExecutor::<XcmConfig>::execute_xcm(Parent, xcm, hash, weight_limit);
assert_eq!(outcome.ensure_complete(), Ok(()));
})
}