Skip to content
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

Added test cases to test swap features #882

Merged
merged 6 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 43 additions & 18 deletions pallets/thea-executor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@

#![cfg_attr(not(feature = "std"), no_std)]

extern crate core;

use frame_support::pallet_prelude::Weight;
pub use pallet::*;

Expand All @@ -47,12 +49,16 @@ pub mod pallet {
use frame_support::{
pallet_prelude::*,
sp_runtime::SaturatedConversion,
traits::{fungible::Mutate, fungibles::Inspect, tokens::Preservation},
traits::{
fungible::Mutate,
fungibles::{Inspect, Mutate as OtherMutate},
tokens::Preservation,
},
transactional,
};
use frame_system::pallet_prelude::*;
use pallet_asset_conversion::Swap;
use polkadex_primitives::Resolver;
use polkadex_primitives::{AssetId, Resolver};
use sp_runtime::{traits::AccountIdConversion, Saturating};
use sp_std::vec::Vec;
use thea_primitives::{
Expand All @@ -67,7 +73,7 @@ pub mod pallet {

/// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config]
pub trait Config: frame_system::Config {
pub trait Config: frame_system::Config + pallet_asset_conversion::Config {
/// Because this pallet emits events, it depends on the Runtime's definition of an
/// event.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
Expand All @@ -86,6 +92,14 @@ pub mod pallet {
+ MaxEncodedLen
+ Into<<<Self as pallet::Config>::Assets as Inspect<Self::AccountId>>::AssetId>
+ From<u128>;
type MultiAssetIdAdapter: From<AssetId>
+ Into<<Self as pallet_asset_conversion::Config>::MultiAssetId>;

type AssetBalanceAdapter: Into<<Self as pallet_asset_conversion::Config>::AssetBalance>
+ Copy
+ From<<Self as pallet_asset_conversion::Config>::AssetBalance>
+ From<u128>
+ Into<u128>;
/// Asset Create/ Update Origin
type AssetCreateUpdateOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
/// Something that executes the payload
Expand All @@ -104,6 +118,9 @@ pub mod pallet {
/// Total Withdrawals
#[pallet::constant]
type WithdrawalSize: Get<u32>;
/// Total Withdrawals
serhii-temchenko marked this conversation as resolved.
Show resolved Hide resolved
#[pallet::constant]
type ExistentialDeposit: Get<u128>;
/// Para Id
type ParaId: Get<u32>;
/// Type representing the weight of this pallet
Expand Down Expand Up @@ -227,6 +244,7 @@ pub mod pallet {
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::withdraw(1))]
#[transactional]
pub fn withdraw(
origin: OriginFor<T>,
asset_id: u128,
Expand Down Expand Up @@ -371,6 +389,7 @@ pub mod pallet {
T::TheaPalletId::get().into_account_truncating()
}

#[transactional]
pub fn do_withdraw(
user: T::AccountId,
asset_id: u128,
Expand All @@ -382,10 +401,8 @@ pub mod pallet {
) -> Result<(), DispatchError> {
ensure!(beneficiary.len() <= 1000, Error::<T>::BeneficiaryTooLong);
ensure!(network != 0, Error::<T>::WrongNetwork);

let mut pending_withdrawals = <PendingWithdrawals<T>>::get(network);
let metadata = <Metadata<T>>::get(asset_id).ok_or(Error::<T>::AssetNotRegistered)?;

ensure!(
pending_withdrawals.len() < T::WithdrawalSize::get() as usize,
Error::<T>::WithdrawalNotAllowed
Expand All @@ -410,7 +427,6 @@ pub mod pallet {
polkadex_primitives::AssetId::Asset(asset_id),
polkadex_primitives::AssetId::Polkadex
];

let token_taken = T::Swap::swap_tokens_for_exact_tokens(
user.clone(),
path,
Expand All @@ -419,8 +435,8 @@ pub mod pallet {
Self::thea_account(),
false,
)?;

amount = amount.saturating_sub(token_taken.saturated_into());
ensure!(amount > 0, Error::<T>::AmountCannotBeZero);
} else {
// Pay the fees
<T as Config>::Currency::transfer(
Expand Down Expand Up @@ -490,6 +506,7 @@ pub mod pallet {
Ok(())
}

#[transactional]
pub fn execute_deposit(
deposit: Deposit<T::AccountId>,
recipient: &T::AccountId,
Expand All @@ -504,24 +521,32 @@ pub mod pallet {
polkadex_primitives::AssetId::Asset(deposit.asset_id),
polkadex_primitives::AssetId::Polkadex
];

let amount_out: T::AssetBalanceAdapter = T::ExistentialDeposit::get().into();
let asset1: T::MultiAssetIdAdapter =
polkadex_primitives::AssetId::Asset(deposit.asset_id).into();
let asset2: T::MultiAssetIdAdapter = polkadex_primitives::AssetId::Polkadex.into();
let fee_amount: T::AssetBalanceAdapter = pallet_asset_conversion::pallet::Pallet::<T>
::quote_price_tokens_for_exact_tokens(asset1.into(), asset2.into(), amount_out.into(), true)
.ok_or(Error::<T>::CannotSwapForFees)?.into();
let fee_amount: u128 = fee_amount.into();
ensure!(fee_amount <= deposit_amount, Error::<T>::AmountCannotBeZero);
Self::resolve_mint(&Self::thea_account(), deposit.asset_id.into(), fee_amount)?;
T::Swap::swap_tokens_for_exact_tokens(
Gauthamastro marked this conversation as resolved.
Show resolved Hide resolved
Self::thea_account(),
path,
amount_out.into(),
None,
recipient.clone(),
false,
)?;
Self::resolver_deposit(
deposit.asset_id.into(),
deposit_amount,
deposit_amount.saturating_sub(fee_amount),
recipient,
Self::thea_account(),
1u128,
Self::thea_account(),
)?;

T::Swap::swap_tokens_for_exact_tokens(
recipient.clone(),
path,
sp_runtime::traits::One::one(),
None,
recipient.clone(),
false,
)?;
} else {
Self::resolver_deposit(
deposit.asset_id.into(),
Expand Down
5 changes: 5 additions & 0 deletions pallets/thea-executor/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,10 @@ parameter_types! {
pub const PolkadexAssetId: u128 = 0;
pub const ParaId: u32 = 2040;
}
use polkadex_primitives::AssetId;
use sp_core::ConstU32;
use sp_runtime::Permill;

impl thea_executor::Config for Test {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
Expand All @@ -201,6 +203,9 @@ impl thea_executor::Config for Test {
type ParaId = ParaId;
type WeightInfo = crate::weights::WeightInfo<Test>;
type Swap = AssetConversion;
type MultiAssetIdAdapter = AssetId;
type AssetBalanceAdapter = u128;
type ExistentialDeposit = ExistentialDeposit;
}

impl<C> frame_system::offchain::SendTransactionTypes<C> for Test
Expand Down
139 changes: 139 additions & 0 deletions pallets/thea-executor/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,3 +341,142 @@ fn test_update_asset_metadata_full() {
assert_last_event::<Test>(Event::<Test>::AssetMetadataSet(md).into());
})
}

#[test]
fn test_resolve_deposit() {
new_test_ext().execute_with(|| {
let asset_id = 2000u128;
let admin = 1u64;
let recipient = 2u64;
Balances::set_balance(&admin, 1_000_000_000_000_000_000);
assert_ok!(Assets::create(
RuntimeOrigin::signed(admin),
parity_scale_codec::Compact(asset_id),
admin,
1u128
));
assert_ok!(TheaExecutor::update_asset_metadata(RuntimeOrigin::root(), asset_id, 12));
Balances::set_balance(&recipient, 1_000_000_000_000_000_000);
let deposit = Deposit {
id: Vec::new(),
recipient,
asset_id,
amount: 1_000_000_000_000_000_000u128,
extra: vec![],
};
assert_ok!(TheaExecutor::execute_deposit(deposit, &recipient));
})
}

#[test]
fn test_deposit_without_account() {
new_test_ext().execute_with(|| {
setup_pool();
let asset_id = 1u128;
let admin = 1u64;
let recipient = 2u64;
Balances::set_balance(&admin, 1_000_000_000_000_000_000);
assert_ok!(TheaExecutor::update_asset_metadata(RuntimeOrigin::root(), asset_id, 12));
Balances::set_balance(&TheaExecutor::thea_account(), 1_000_000_000_000_000_000);
let deposit = Deposit {
id: Vec::new(),
recipient,
asset_id,
amount: 1_000_000_000_000_000u128,
extra: vec![],
};
assert_ok!(TheaExecutor::execute_deposit(deposit, &recipient));
assert_eq!(Balances::free_balance(&recipient), 50);
assert_eq!(Assets::balance(asset_id, &recipient), 999_999_994_984_954u128);
assert_eq!(Assets::balance(asset_id, &TheaExecutor::thea_account()), 0u128);
assert_eq!(
Balances::free_balance(&TheaExecutor::thea_account()),
1_000_000_000_000_000_000
);
})
}

#[test]
fn test_do_withdrawal() {
new_test_ext().execute_with(|| {
setup_pool();
let sender = 2u64;
let asset_id = 1u128;
// Set asset balance
Balances::set_balance(&sender, 1_000_000_000_000_000_000);
Assets::mint_into(asset_id, &sender, 1_000_000_000_000_000_000);
// Set withdrawal Fee
assert_ok!(TheaExecutor::set_withdrawal_fee(RuntimeOrigin::root(), 1, 100));
assert_ok!(TheaExecutor::update_asset_metadata(RuntimeOrigin::root(), asset_id, 12));
assert_ok!(TheaExecutor::withdraw(
RuntimeOrigin::signed(sender),
asset_id,
1_000_000_000_000_000u128,
vec![1; 32],
true,
1,
true
));
assert_eq!(Balances::free_balance(&sender), 1_000_000_000_000_000_000);
assert_eq!(Assets::balance(asset_id, &sender), 999_000_000_000_000_000);
assert_eq!(Balances::free_balance(&TheaExecutor::thea_account()), 1_000u128);
})
}

#[test]
fn test_do_withdrawal_with_total_amount_consumed_returns_error() {
new_test_ext().execute_with(|| {
setup_pool();
let sender = 2u64;
let asset_id = 1u128;
// Set asset balance
Balances::set_balance(&sender, 1_000_000_000_000_000_000);
Assets::mint_into(asset_id, &sender, 100_300_903u128);
// Set withdrawal Fee
assert_ok!(TheaExecutor::set_withdrawal_fee(RuntimeOrigin::root(), 1, 100));
assert_ok!(TheaExecutor::update_asset_metadata(RuntimeOrigin::root(), asset_id, 12));
assert_noop!(
TheaExecutor::withdraw(
RuntimeOrigin::signed(sender),
asset_id,
1_000_000_000_000_000u128,
vec![1; 32],
true,
1,
true
),
sp_runtime::TokenError::FundsUnavailable
);
})
}

fn setup_pool() {
let asset_id = 1u128;
let admin = 1u64;
Balances::set_balance(&admin, 2_000_000_000_000_000_000_000_000_000_000u128);
assert_ok!(Assets::force_create(
RuntimeOrigin::root(),
parity_scale_codec::Compact(asset_id),
admin,
false,
1u128
));
// Mint tokens
Assets::mint_into(asset_id, &admin, 1_000_000_000_000_000_000_000_000_000u128).unwrap();
// Create pool
assert_ok!(AssetConversion::create_pool(
RuntimeOrigin::signed(admin),
polkadex_primitives::AssetId::Asset(asset_id),
polkadex_primitives::AssetId::Polkadex
));
assert_ok!(AssetConversion::add_liquidity(
RuntimeOrigin::signed(admin),
polkadex_primitives::AssetId::Asset(asset_id),
polkadex_primitives::AssetId::Polkadex,
1_000_000_000_000_000_000_000u128,
10_000_000_000_000_000u128,
1u128,
1u128,
admin
));
}
14 changes: 14 additions & 0 deletions primitives/polkadex/src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,19 @@ pub trait Resolver<
}
Ok(())
}

fn resolve_mint(
recipeint: &AccountId,
asset: AssetId,
amount: Balance,
) -> Result<(), DispatchError> {
if asset == NativeAssetId::get() {
return Err(DispatchError::Other("Cannot mint Native Asset"))
} else {
Others::mint_into(asset.into(), recipeint, amount.saturated_into())?;
}
Ok(())
}
}

/// Enumerated asset on chain
Expand All @@ -158,6 +171,7 @@ pub enum AssetId {
Asset(u128),
Polkadex,
}

use sp_runtime::traits::Zero;
impl From<u128> for AssetId {
fn from(value: u128) -> Self {
Expand Down
3 changes: 3 additions & 0 deletions runtimes/mainnet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1364,6 +1364,9 @@ impl thea_executor::Config for Runtime {
type ParaId = ParaId;
type WeightInfo = thea_executor::weights::WeightInfo<Runtime>;
type Swap = AssetConversion;
type MultiAssetIdAdapter = AssetId;
type AssetBalanceAdapter = u128;
type ExistentialDeposit = ExistentialDeposit;
}

#[cfg(feature = "runtime-benchmarks")]
Expand Down
Loading