diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f81dee2543..7c1aa90e52 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -379,6 +379,6 @@ jobs: # Run specific tests doing XCM between hydradx and other parachains yarn install - yarn test --no-file-parallelism packages/hydration/tests/xcm.test.ts packages/hydration/tests/dca.test.ts + yarn test --no-file-parallelism packages/hydration/tests/xcm.test.ts env: HYDRADX_RUNTIME_WASM_PATH: ${{ env.HYDRADX_RUNTIME_WASM_PATH }} diff --git a/Cargo.lock b/Cargo.lock index e7aa2184ca..cce5cb7571 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1770,7 +1770,7 @@ dependencies = [ [[package]] name = "cerebro-hydration" -version = "0.1.0" +version = "0.1.1" dependencies = [ "cerebro-core", "fp-evm", @@ -1786,7 +1786,6 @@ dependencies = [ "pallet-asset-registry", "pallet-balances", "pallet-currencies", - "pallet-dca", "pallet-ema-oracle", "pallet-evm", "pallet-evm-accounts", @@ -5733,7 +5732,7 @@ dependencies = [ [[package]] name = "hydradx" -version = "15.9.1" +version = "15.9.2" dependencies = [ "amm-simulator", "async-trait", @@ -5843,10 +5842,9 @@ dependencies = [ [[package]] name = "hydradx-adapters" -version = "2.0.1" +version = "3.0.0" dependencies = [ "cumulus-pallet-parachain-system", - "cumulus-primitives-core", "ethabi", "evm", "frame-support", @@ -5901,7 +5899,7 @@ dependencies = [ [[package]] name = "hydradx-runtime" -version = "461.0.0" +version = "462.0.0" dependencies = [ "alloy-primitives 0.7.7", "alloy-sol-types 0.7.7", @@ -5965,7 +5963,6 @@ dependencies = [ "pallet-conviction-voting", "pallet-currencies", "pallet-currencies-rpc-runtime-api", - "pallet-dca", "pallet-dispatcher", "pallet-dispenser", "pallet-duster", @@ -6258,7 +6255,7 @@ dependencies = [ [[package]] name = "ice-support" -version = "1.7.0" +version = "2.0.0" dependencies = [ "frame-support", "hydra-dx-math", @@ -9340,49 +9337,6 @@ dependencies = [ "sp-std", ] -[[package]] -name = "pallet-dca" -version = "2.0.1" -dependencies = [ - "cumulus-pallet-parachain-system", - "cumulus-primitives-core", - "frame-benchmarking", - "frame-support", - "frame-system", - "hydra-dx-math", - "hydradx-adapters", - "hydradx-traits", - "ice-support", - "lazy_static", - "log", - "orml-tokens", - "orml-traits", - "pallet-balances", - "pallet-broadcast", - "pallet-currencies", - "pallet-dispatcher", - "pallet-ema-oracle", - "pallet-evm", - "pallet-omnipool", - "pallet-route-executor", - "pallet-xyk", - "parity-scale-codec", - "pretty_assertions", - "primitive-types 0.13.1", - "primitives", - "rand 0.8.5", - "scale-info", - "smallvec", - "sp-api", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "sp-tracing", - "test-case", - "test-utils", -] - [[package]] name = "pallet-delegated-staking" version = "8.0.0" @@ -10007,7 +9961,7 @@ dependencies = [ [[package]] name = "pallet-ice" -version = "1.15.0" +version = "1.15.1" dependencies = [ "amm-simulator", "frame-benchmarking", @@ -10102,7 +10056,7 @@ dependencies = [ [[package]] name = "pallet-intent" -version = "1.13.1" +version = "1.14.0" dependencies = [ "frame-benchmarking", "frame-support", @@ -14256,7 +14210,7 @@ checksum = "48fd7bd8a6377e15ad9d42a8ec25371b94ddc67abe7c8b9127bec79bebaaae18" [[package]] name = "runtime-integration-tests" -version = "1.128.4" +version = "1.129.0" dependencies = [ "amm-simulator", "cerebro-core", @@ -14314,7 +14268,6 @@ dependencies = [ "pallet-conviction-voting", "pallet-currencies", "pallet-currencies-rpc-runtime-api", - "pallet-dca", "pallet-dispatcher", "pallet-duster", "pallet-duster-rpc-runtime-api", diff --git a/Cargo.toml b/Cargo.toml index 86eeb2e62d..f8e43d389f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,6 @@ members = [ 'node/cerebro-core/hydration', 'runtime/hydradx', 'pallets/omnipool', - 'pallets/dca', 'primitives', 'utils/build-script-utils', 'integration-tests', @@ -151,7 +150,6 @@ pallet-collator-rewards = { path = "pallets/collator-rewards", default-features pallet-collator-rotation = { path = "pallets/collator-rotation", default-features = false } pallet-currencies = { path = "pallets/currencies", default-features = false } pallet-currencies-rpc-runtime-api = { path = "pallets/currencies/rpc/runtime-api", default-features = false } -pallet-dca = { path = "pallets/dca", default-features = false } pallet-dispatcher = { path = "pallets/dispatcher", default-features = false } pallet-duster = { path = "pallets/duster", default-features = false } pallet-duster-rpc-runtime-api = { path = "pallets/duster/rpc/runtime-api", default-features = false } diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index 102aa86870..3ea7de592f 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runtime-integration-tests" -version = "1.128.4" +version = "1.129.0" description = "Integration tests" authors = ["GalacticCouncil"] edition = "2021" @@ -39,7 +39,6 @@ pallet-otc = { workspace = true } pallet-otc-settlements = { workspace = true } pallet-relaychain-info = { workspace = true } pallet-route-executor = { workspace = true } -pallet-dca = { workspace = true } pallet-dynamic-fees = { workspace = true } pallet-dynamic-evm-fee = { workspace = true } pallet-staking = { workspace = true } diff --git a/integration-tests/README.md b/integration-tests/README.md index cc1ea67a21..b266e37a27 100644 --- a/integration-tests/README.md +++ b/integration-tests/README.md @@ -35,7 +35,7 @@ This produces `integration-tests/-snapshot/SNAPSHOT_`. ### 4. Write a test that loads the snapshot -Use `hydra_live_ext` to spin up the runtime against the snapshot. Canonical example: `src/dca.rs:4872`. +Use `hydra_live_ext` to spin up the runtime against the snapshot. Canonical example: `src/aave_simulator.rs:27`. ```rust const PATH_TO_SNAPSHOT: &str = "-snapshot/SNAPSHOT_"; diff --git a/integration-tests/dca-snapshot/SNAPSHOT_12309734 b/integration-tests/dca-snapshot/SNAPSHOT_12309734 deleted file mode 100644 index 79273039b2..0000000000 Binary files a/integration-tests/dca-snapshot/SNAPSHOT_12309734 and /dev/null differ diff --git a/integration-tests/dca-snapshot/SNAPSHOT_13260776 b/integration-tests/dca-snapshot/SNAPSHOT_13260776 deleted file mode 100644 index 0497c20d1d..0000000000 Binary files a/integration-tests/dca-snapshot/SNAPSHOT_13260776 and /dev/null differ diff --git a/integration-tests/src/aave_router.rs b/integration-tests/src/aave_router.rs index 1404d37846..7fe6194cea 100644 --- a/integration-tests/src/aave_router.rs +++ b/integration-tests/src/aave_router.rs @@ -1,7 +1,5 @@ #![cfg(test)] -use crate::dca::create_schedule; -use crate::dca::schedule_fake_with_sell_order; use crate::liquidation::{borrow, supply}; use crate::polkadot_test_net::*; use crate::utils::accounts::*; @@ -10,7 +8,7 @@ use frame_support::assert_ok; use frame_support::pallet_prelude::DispatchError::Other; use frame_support::pallet_prelude::ValidateUnsigned; use frame_support::storage::with_transaction; -use frame_support::traits::{ExistenceRequirement, OnInitialize}; +use frame_support::traits::ExistenceRequirement; use frame_support::{assert_noop, BoundedVec}; use hex_literal::hex; use hydradx_runtime::evm::aave_trade_executor::AaveTradeExecutor; @@ -779,46 +777,6 @@ fn router_should_set_on_chain_route() { }) } -#[test] -fn dca_schedule_buying_atokens_should_be_created() { - with_aave(|| { - create_schedule( - ALICE, - schedule_fake_with_sell_order(ALICE, Aave, 10 * ONE, DOT, ADOT, ONE), - ); - }) -} - -#[test] -fn dca_schedule_selling_atokens_should_be_created() { - with_aave(|| { - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - hydradx_runtime::RuntimeOrigin::root(), - ADOT, - FixedU128::from_rational(1, 100000), - )); - hydradx_runtime::MultiTransactionPayment::on_initialize(0); - assert_ok!(Router::buy( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - DOT, - ADOT, - 1000 * ONE, - 1000 * ONE + 2, - vec![Trade { - pool: Aave, - asset_in: DOT, - asset_out: ADOT, - }] - .try_into() - .unwrap() - )); - create_schedule( - ALICE, - schedule_fake_with_sell_order(ALICE, Aave, 10 * ONE, ADOT, DOT, ONE), - ); - }) -} - #[test] fn buy_adot_from_stablepool() { with_stablepool(|pool| { diff --git a/integration-tests/src/cerebro_diff.rs b/integration-tests/src/cerebro_diff.rs index da1ef9ee56..cc07770a7d 100644 --- a/integration-tests/src/cerebro_diff.rs +++ b/integration-tests/src/cerebro_diff.rs @@ -9,7 +9,7 @@ use cerebro_core::model::StateDelta; use cerebro_core::value::Usd6; use cerebro_core::BlockHash; use cerebro_hydration::balance::call_output; -use cerebro_hydration::decode::map_records; +use cerebro_hydration::decode::{map_records, Record}; use cerebro_hydration::guard::{ self, candidate_of, is_candidate, read_oracle, read_point, with_state, Accumulators, GuardCtx, InconclusiveReason, Judgement, Thresholds, Verdict, POST, PRE, @@ -167,7 +167,11 @@ fn guarded(signer: Option<[u8; 32]>, call: impl FnOnce()) -> Guarded { .filter(|k| before.get(*k) != after.get(*k)) .map(|k| (k.clone(), (before.get(k).cloned(), after.get(k).cloned()))) .collect(); - let records = ext.execute_with(System::events); + let records: Vec<_> = ext + .execute_with(System::events) + .into_iter() + .map(Record::Runtime) + .collect(); let t = ExtTransport(RefCell::new(&mut ext)); let protocol = accounts::fetch(&t, H256(POST)).expect("protocol accounts read"); diff --git a/integration-tests/src/dca.rs b/integration-tests/src/dca.rs deleted file mode 100644 index 2553ef5c56..0000000000 --- a/integration-tests/src/dca.rs +++ /dev/null @@ -1,6223 +0,0 @@ -#![cfg(test)] - -use crate::count_dca_event; -use crate::polkadot_test_net::*; -use crate::{assert_balance, assert_reserved_balance}; -use frame_support::assert_noop; -use frame_support::assert_ok; -use frame_support::storage::with_transaction; -use frame_system::RawOrigin; -use hydradx_runtime::NamedReserveId; -use hydradx_runtime::DOT_ASSET_LOCATION; -use hydradx_runtime::XYK; -use hydradx_runtime::{ - AssetRegistry, Balances, Currencies, FeeProcessor, Omnipool, Router, Runtime, RuntimeEvent, RuntimeOrigin, - Stableswap, System, Tokens, Treasury, DCA, -}; -use hydradx_traits::registry::{AssetKind, Create}; -use hydradx_traits::router::AssetPair; -use hydradx_traits::router::PoolType; -use hydradx_traits::router::Trade; -use hydradx_traits::stableswap::AssetAmount; -use orml_traits::MultiCurrency; -use orml_traits::MultiReservableCurrency; -use orml_traits::NamedMultiReservableCurrency; -use pallet_broadcast::types::*; -use pallet_dca::types::{Order, Schedule, ScheduleId}; -use pallet_omnipool::types::Tradability; -use pallet_route_executor::MAX_NUMBER_OF_TRADES; -use pallet_stableswap::MAX_ASSETS_IN_POOL; -use primitives::{AssetId, Balance, EvmAddress}; -use sp_runtime::traits::ConstU32; -use sp_runtime::DispatchError; -use sp_runtime::Permill; -use sp_runtime::{BoundedVec, FixedU128}; -use sp_runtime::{DispatchResult, TransactionOutcome}; -use xcm_emulator::TestExt; - -const TREASURY_ACCOUNT_INIT_BALANCE: Balance = 1000 * UNITS; - -mod omnipool { - use super::*; - use frame_support::assert_ok; - use hydradx_runtime::{Balances, Currencies, Treasury, DCA}; - use hydradx_traits::router::{PoolType, Trade}; - use hydradx_traits::AssetKind; - use pallet_broadcast::types::Destination; - use sp_runtime::{FixedU128, TransactionOutcome}; - - #[test] - fn create_schedule_should_work() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let block_id = 11; - go_to_block(block_id); - - let budget = 1000 * UNITS; - let schedule1 = schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, budget, HDX, DAI, 100 * UNITS); - - //Act - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE.into()), - schedule1.clone(), - None - )); - - //Assert - let schedule_id = 0; - let schedule = DCA::schedules(schedule_id); - assert!(schedule.is_some()); - - let next_block_id = block_id + 2; - let schedule = DCA::schedule_ids_per_block(next_block_id); - assert!(!schedule.is_empty()); - expect_hydra_last_events(vec![pallet_dca::Event::Scheduled { - id: 0, - who: ALICE.into(), - period: schedule1.period, - total_amount: schedule1.total_amount, - order: schedule1.order, - } - .into()]); - }); - } - - #[test] - fn create_schedule_should_fail_when_order_is_buy() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - go_to_block(11); - - let budget = 1000 * UNITS; - let schedule1 = schedule_fake_with_buy_order(PoolType::Omnipool, HDX, DAI, 100 * UNITS, budget); - - //Act and assert - assert_noop!( - DCA::schedule(RuntimeOrigin::signed(ALICE.into()), schedule1, None), - pallet_dca::Error::::NoLongerSupported - ); - assert!(DCA::schedules(0).is_none()); - }); - } - - #[test] - fn create_schedule_should_work_when_asset_in_is_not_an_accepted_fee_currency() { - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - hydradx_runtime::AssetRegistry::set_location(DOT, DOT_ASSET_LOCATION).unwrap(); - - init_omnipool_with_oracle_for_block_10(); - add_dot_as_payment_currency(); - - let name = b"INSUF1".to_vec(); - let insufficient_asset = AssetRegistry::register_insufficient_asset( - None, - Some(name.try_into().unwrap()), - AssetKind::External, - Some(1_000), - None, - None, - None, - None, - ) - .unwrap(); - //An (X, DOT) pool no longer makes X payable; only `AcceptedCurrencies` does. - create_xyk_pool(insufficient_asset, 10000 * UNITS, DAI, 20000 * UNITS); - create_xyk_pool(insufficient_asset, 1000000 * UNITS, DOT, 1200000 * UNITS); - assert_ok!(hydradx_runtime::EmaOracle::add_oracle( - RuntimeOrigin::root(), - primitives::constants::chain::XYK_SOURCE, - (DOT, insufficient_asset) - )); - - let block_id = 11; - go_to_block(block_id); - - let budget = 50000 * UNITS; - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::XYK, budget, insufficient_asset, DOT, 1000 * UNITS); - - assert_ok!(Currencies::update_balance( - RawOrigin::Root.into(), - ALICE.into(), - insufficient_asset, - 50000 * UNITS as i128, - )); - - //Act - selling an asset that cannot pay fees is still allowed; the execution fee - //is charged in the owner's own fee currency instead. - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE.into()), - schedule1.clone(), - None - )); - - //Assert - assert!(DCA::schedules::(0).is_some()); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn buy_schedule_execution_should_work_when_block_is_initialized() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let dca_budget = 1000 * UNITS; - - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - - let amount_out = 100 * UNITS; - let schedule1 = schedule_fake_with_buy_order(PoolType::Omnipool, HDX, DAI, amount_out, dca_budget); - insert_schedule_into_storage(ALICE, schedule1, None); - - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - assert!(fee > 0, "Treasury got rugged"); - - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE + amount_out); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - dca_budget); - let reserved_budget = Currencies::reserved_balance(LRNA, &ALICE.into()); - assert!(reserved_budget < dca_budget); - }); - } - - #[test] - fn buy_schedule_execution_should_emit_swapped_events() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let dca_budget = 1000 * UNITS; - let amount_out = 100 * UNITS; - let schedule_id = 0; - let schedule1 = schedule_fake_with_buy_order(PoolType::Omnipool, HDX, DAI, amount_out, dca_budget); - insert_schedule_into_storage(ALICE, schedule1, None); - - //Act - run_to_block(11, 12); - - //Assert - let swapped_events = get_last_swapped_events(); - let last_two_swapped_events = &swapped_events[swapped_events.len() - 2..]; - pretty_assertions::assert_eq!( - last_two_swapped_events, - vec![ - pallet_broadcast::Event::Swapped3 { - swapper: ALICE.into(), - filler: Omnipool::protocol_account(), - filler_type: pallet_broadcast::types::Filler::Omnipool, - operation: pallet_broadcast::types::TradeOperation::ExactOut, - inputs: vec![Asset::new(HDX, 140421094366889)], - outputs: vec![Asset::new(LRNA, 70210545436637)], - fees: vec![Fee::new( - LRNA, - 35105272718, - Destination::Account(Omnipool::protocol_account()) - )], - operation_stack: vec![ - ExecutionType::DCA(schedule_id, 0), - ExecutionType::Router(1), - ExecutionType::Omnipool(2) - ] - }, - pallet_broadcast::Event::Swapped3 { - swapper: ALICE.into(), - filler: Omnipool::protocol_account(), - filler_type: pallet_broadcast::types::Filler::Omnipool, - operation: pallet_broadcast::types::TradeOperation::ExactOut, - inputs: vec![Asset::new(LRNA, 70175440163919)], - outputs: vec![Asset::new(DAI, amount_out)], - fees: vec![ - Fee::new(DAI, 137844611530, Destination::Account(Omnipool::protocol_account())), - Fee::new(DAI, 112781954887, Destination::Account(FeeProcessor::pot_account_id())), - ], - operation_stack: vec![ - ExecutionType::DCA(schedule_id, 0), - ExecutionType::Router(1), - ExecutionType::Omnipool(2) - ], - } - ] - ); - - run_to_block(13, 12 + hydradx_runtime::MinimalPeriod::get()); - - let swapped_events = get_last_swapped_events(); - let last_two_swapped_events = &swapped_events[swapped_events.len() - 2..]; - pretty_assertions::assert_eq!( - last_two_swapped_events, - vec![ - pallet_broadcast::Event::Swapped3 { - swapper: ALICE.into(), - filler: Omnipool::protocol_account(), - filler_type: pallet_broadcast::types::Filler::Omnipool, - operation: pallet_broadcast::types::TradeOperation::ExactOut, - inputs: vec![Asset::new(HDX, 140421134429889)], - outputs: vec![Asset::new(LRNA, 70210554484824)], - fees: vec![Fee::new( - LRNA, - 35105277242, - Destination::Account(Omnipool::protocol_account()) - )], - operation_stack: vec![ - ExecutionType::DCA(schedule_id, 9), - ExecutionType::Router(10), - ExecutionType::Omnipool(11) - ], - }, - pallet_broadcast::Event::Swapped3 { - swapper: ALICE.into(), - filler: Omnipool::protocol_account(), - filler_type: pallet_broadcast::types::Filler::Omnipool, - operation: pallet_broadcast::types::TradeOperation::ExactOut, - inputs: vec![Asset::new(LRNA, 70175449207582)], - outputs: vec![Asset::new(DAI, amount_out)], - fees: vec![ - Fee::new(DAI, 137844611530, Destination::Account(Omnipool::protocol_account())), - Fee::new(DAI, 112781954887, Destination::Account(FeeProcessor::pot_account_id())), - ], - operation_stack: vec![ - ExecutionType::DCA(schedule_id, 9), - ExecutionType::Router(10), - ExecutionType::Omnipool(11) - ], - } - ] - ); - }); - } - - #[test] - fn buy_schedule_execution_should_work_without_route() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let dca_budget = 1000 * UNITS; - - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - - let amount_out = 100 * UNITS; - let no_route = vec![]; - let schedule1 = schedule_fake_with_buy_order_with_route(HDX, DAI, amount_out, dca_budget, no_route); - insert_schedule_into_storage(ALICE, schedule1, None); - - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - assert!(fee > 0, "Treasury got rugged"); - - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE + amount_out); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - dca_budget); - let reserved_budget = Currencies::reserved_balance(LRNA, &ALICE.into()); - assert!(reserved_budget < dca_budget); - }); - } - - #[test] - fn buy_schedule_should_be_retried_multiple_times_then_terminated() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let dca_budget = 1000 * UNITS; - - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - - let amount_out = 100 * UNITS; - let schedule1 = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(5)), - order: Order::Buy { - asset_in: HDX, - asset_out: DAI, - amount_out, - max_amount_in: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: DAI, - }]), - }, - }; - insert_schedule_into_storage(ALICE, schedule1, None); - - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - - //Act and assert - let schedule_id = 0; - let retry_1 = retry_block(12, 0); - let retry_2 = retry_block(retry_1, 1); - let retry_3 = retry_block(retry_2, 2); - go_to_block(12); - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - dca_budget); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - fee); - assert_eq!(DCA::retries_on_error(schedule_id), 1); - - go_to_block(retry_1); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - dca_budget); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - 2 * fee); - assert_eq!(DCA::retries_on_error(schedule_id), 2); - - go_to_block(retry_2); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - dca_budget); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - 3 * fee); - assert_eq!(DCA::retries_on_error(schedule_id), 3); - - //After this retry we terminate - go_to_block(retry_3); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - 4 * fee); - assert_reserved_balance!(&ALICE.into(), HDX, 0); - assert_eq!(DCA::retries_on_error(schedule_id), 0); - let schedule = DCA::schedules(schedule_id); - assert!(schedule.is_none()); - }); - } - - #[test] - fn buy_schedule_execution_should_work_when_asset_in_is_hub_asset() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let alice_init_hub_balance = 5000 * UNITS; - set_alice_lrna_balance(alice_init_hub_balance); - - let dca_budget = 2500 * UNITS; - - let amount_out = 100 * UNITS; - let schedule1 = schedule_fake_with_buy_order(PoolType::Omnipool, LRNA, DAI, amount_out, dca_budget); - insert_schedule_into_storage(ALICE, schedule1, None); - - assert_balance!(ALICE.into(), LRNA, alice_init_hub_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), LRNA, dca_budget); - assert_balance!(&Treasury::account_id(), LRNA, 0); - - //Act - go_to_block(12); - - //Assert - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE + amount_out); - assert_balance!(ALICE.into(), LRNA, alice_init_hub_balance - dca_budget); - let reserved_budget = Currencies::reserved_balance(LRNA, &ALICE.into()); - assert!(reserved_budget < dca_budget); - - let treasury_balance = Currencies::free_balance(LRNA, &Treasury::account_id()); - assert!(treasury_balance > 0); - }); - } - - #[test] - fn buy_schedule_and_direct_buy_and_router_should_yield_same_result_when_selling_native_asset() { - let amount_out = 100 * UNITS; - - //DCA - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let dca_budget = 1000 * UNITS; - - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - - let schedule1 = schedule_fake_with_buy_order(PoolType::Omnipool, HDX, DAI, amount_out, dca_budget); - insert_schedule_into_storage(ALICE, schedule1, None); - - //Act - go_to_block(12); - - //Assert - let reserved_budget = Currencies::reserved_balance(LRNA, &ALICE.into()); - assert!(reserved_budget < dca_budget); - - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE + amount_out); - }); - - //Direct Omnipool - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - - //Act - assert_ok!(Omnipool::buy( - RuntimeOrigin::signed(ALICE.into()), - DAI, - HDX, - amount_out, - Balance::MAX, - )); - - //Assert - assert_balance!(ALICE.into(), HDX, 859578905568959); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE + amount_out); - }); - - //Router - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - - //Act - let trade = vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: DAI, - }]; - assert_ok!(Router::buy( - RuntimeOrigin::signed(ALICE.into()), - HDX, - DAI, - amount_out, - Balance::MAX, - trade.try_into().unwrap() - )); - - //Assert - assert_balance!(ALICE.into(), HDX, 859578905568959); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE + amount_out); - }); - } - - #[test] - fn buy_schedule_and_direct_buy_and_router_should_yield_same_result_when_asset_in_is_hub_asset() { - let amount_out = 100 * UNITS; - - //DCA - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - let alice_init_lrna_balance = 5000 * UNITS; - set_alice_lrna_balance(alice_init_lrna_balance); - - init_omnipool_with_oracle_for_block_10(); - - let dca_budget = 1000 * UNITS; - - assert_balance!(ALICE.into(), LRNA, alice_init_lrna_balance); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - - let schedule1 = schedule_fake_with_buy_order(PoolType::Omnipool, LRNA, DAI, amount_out, dca_budget); - insert_schedule_into_storage(ALICE, schedule1, None); - - //Act - go_to_block(12); - - //Assert - let reserved_budget = Currencies::reserved_balance(LRNA, &ALICE.into()); - assert!(reserved_budget < dca_budget); - - assert_balance!(ALICE.into(), DAI, 2100000000000000); - }); - - //Direct Omnipool - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - let alice_init_lrna_balance = 5000 * UNITS; - set_alice_lrna_balance(alice_init_lrna_balance); - - init_omnipool_with_oracle_for_block_10(); - - assert_balance!(ALICE.into(), LRNA, alice_init_lrna_balance); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - - //Act - assert_ok!(Omnipool::buy( - RuntimeOrigin::signed(ALICE.into()), - DAI, - LRNA, - amount_out, - Balance::MAX, - )); - - //Assert - assert_balance!(ALICE.into(), LRNA, 4929824559916281); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE + amount_out); - }); - - //Router - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - let alice_init_lrna_balance = 5000 * UNITS; - set_alice_lrna_balance(alice_init_lrna_balance); - - init_omnipool_with_oracle_for_block_10(); - - assert_balance!(ALICE.into(), LRNA, alice_init_lrna_balance); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - - //Act - let trade = vec![Trade { - pool: PoolType::Omnipool, - asset_in: LRNA, - asset_out: DAI, - }]; - assert_ok!(Router::buy( - RuntimeOrigin::signed(ALICE.into()), - LRNA, - DAI, - amount_out, - Balance::MAX, - trade.try_into().unwrap() - )); - - //Assert - assert_balance!(ALICE.into(), LRNA, 4929824559916281); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE + amount_out); - }); - } - - #[test] - fn full_buy_dca_should_be_executed_then_completed() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let dca_budget = 1000 * UNITS; - let schedule1 = schedule_fake_with_buy_order(PoolType::Omnipool, HDX, DAI, 100 * UNITS, dca_budget); - insert_schedule_into_storage(ALICE, schedule1, None); - - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - - //Act - run_to_block(11, 12 + 7 * hydradx_runtime::MinimalPeriod::get()); - - //Assert - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE + 700 * UNITS); - - //Because the last trade is not enough for a whole trade, it is returned to the user - let amount_in = 140_421_094_431_120; - let alice_new_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - assert!(alice_new_hdx_balance < amount_in); - assert!(alice_new_hdx_balance > 0); - - assert_reserved_balance!(&ALICE.into(), HDX, 0); - - let schedule = DCA::schedules(0); - assert!(schedule.is_none()); - }); - } - - #[test] - #[allow(clippy::needless_borrows_for_generic_args)] - fn rolling_buy_dca_should_continue_until_funds_are_spent() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let balance = 20000 * UNITS; - let trade_size = 500 * UNITS; - let dca_budget = 0; // rolling - Balances::force_set_balance(RuntimeOrigin::root(), ALICE.into(), balance).unwrap(); - insert_schedule_into_storage( - ALICE, - schedule_fake_with_buy_order(PoolType::Omnipool, HDX, DAI, trade_size, dca_budget), - None, - ); - let reserved = Balances::reserved_balance(&ALICE.into()); - assert!(Balances::free_balance(&ALICE.into()) <= balance - reserved); - let dai_balance = Currencies::free_balance(DAI, &ALICE.into()); - - //Act - run_to_block(11, 12 + 32 * hydradx_runtime::MinimalPeriod::get()); - - //Assert - assert!(Balances::free_balance(&ALICE.into()) > reserved); - assert!(Currencies::free_balance(DAI, &ALICE.into()) > dai_balance); - assert!(DCA::schedules(0).is_none()); - }); - } - - #[test] - fn rolling_buy_dca_should_complete_gracefully_when_user_runs_out_of_funds() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let balance = 5000 * UNITS; - let trade_size = 500 * UNITS; // amount_out to buy - let dca_budget = 0; // rolling DCA - Balances::force_set_balance(RuntimeOrigin::root(), ALICE.into(), balance).unwrap(); - insert_schedule_into_storage( - ALICE, - schedule_fake_with_buy_order(PoolType::Omnipool, HDX, DAI, trade_size, dca_budget), - None, - ); - let dai_balance = Currencies::free_balance(DAI, &ALICE.into()); - - //Act - run until user runs out of funds - run_to_block(11, 100); - - //Assert - assert!(DCA::schedules(0).is_none()); - assert!(Currencies::free_balance(DAI, &ALICE.into()) > dai_balance); - assert_reserved_balance!(&ALICE.into(), HDX, 0); - check_if_dcas_completed_without_failed_or_terminated_events(); - }); - } - - #[test] - fn rolling_sell_dca_should_complete_gracefully_when_user_runs_out_of_funds() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let balance = 5000 * UNITS; - let trade_size = 500 * UNITS; - let dca_budget = 0; // rolling DCA - takes all available balance - Balances::force_set_balance(RuntimeOrigin::root(), ALICE.into(), balance).unwrap(); - - let sell_schedule = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, trade_size); - let fee = DCA::get_transaction_fee(&sell_schedule.order, None).unwrap(); - - let default_reserved_amount_for_rolling_dca = 2 * (trade_size + fee); - let not_enough_leftover_in_the_end = balance - 9 * (trade_size + fee); - - create_schedule(ALICE, sell_schedule); - assert_reserved_balance!(&ALICE.into(), HDX, default_reserved_amount_for_rolling_dca); - - let dai_balance = Currencies::free_balance(DAI, &ALICE.into()); - - //Act - run until user runs out of funds - run_to_block(11, 12 + 12 * hydradx_runtime::MinimalPeriod::get()); - - //Assert - assert!(DCA::schedules(0).is_none()); - assert!(Currencies::free_balance(DAI, &ALICE.into()) > dai_balance); - //The initial reserved amount + the last trade size minus for rolling DCA should be returned to free balance as it failed with FundsUnavailable error - let fee_in_last_failing_round = fee; - assert_eq!( - Currencies::free_balance(HDX, &ALICE.into()), - default_reserved_amount_for_rolling_dca + not_enough_leftover_in_the_end - fee_in_last_failing_round - ); - assert_reserved_balance!(&ALICE.into(), HDX, 0); - check_if_dcas_completed_without_failed_or_terminated_events(); - }); - } - - #[test] - fn sell_schedule_execution_should_work_when_block_is_initialized() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - assert!(fee > 0, "Treasury got rugged"); - - assert_balance!(ALICE.into(), DAI, 2071214372591672); - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - amount_to_sell - fee); - }); - } - - #[test] - fn sell_schedule_execution_should_emit_swapped_event() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule_id = 0; - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - create_schedule(ALICE, schedule1); - - //Act - run_to_block(11, 12); - - //Assert - let swapped_events = get_last_swapped_events(); - let last_two_swapped_events = &swapped_events[swapped_events.len() - 2..]; - pretty_assertions::assert_eq!( - last_two_swapped_events, - vec![ - pallet_broadcast::Event::Swapped3 { - swapper: ALICE.into(), - filler: Omnipool::protocol_account(), - filler_type: pallet_broadcast::types::Filler::Omnipool, - operation: pallet_broadcast::types::TradeOperation::ExactIn, - inputs: vec![Asset::new(HDX, amount_to_sell)], - outputs: vec![Asset::new(LRNA, 49999999160157)], - fees: vec![Fee::new( - LRNA, - 24999999580, - Destination::Account(Omnipool::protocol_account()) - )], - operation_stack: vec![ - ExecutionType::DCA(schedule_id, 0), - ExecutionType::Router(1), - ExecutionType::Omnipool(2) - ], - }, - pallet_broadcast::Event::Swapped3 { - swapper: ALICE.into(), - filler: Omnipool::protocol_account(), - filler_type: pallet_broadcast::types::Filler::Omnipool, - operation: pallet_broadcast::types::TradeOperation::ExactIn, - inputs: vec![Asset::new(LRNA, 49974999160577)], - outputs: vec![Asset::new(DAI, 71214372624206)], - fees: vec![ - Fee::new(DAI, 98165175298, Destination::Account(Omnipool::protocol_account())), - Fee::new(DAI, 80316961605, Destination::Account(FeeProcessor::pot_account_id())), - ], - operation_stack: vec![ - ExecutionType::DCA(schedule_id, 0), - ExecutionType::Router(1), - ExecutionType::Omnipool(2) - ], - } - ] - ); - - run_to_block(13, 12 + hydradx_runtime::MinimalPeriod::get()); - - let swapped_events = get_last_swapped_events(); - let last_two_swapped_events = &swapped_events[swapped_events.len() - 2..]; - pretty_assertions::assert_eq!( - last_two_swapped_events, - vec![ - pallet_broadcast::Event::Swapped3 { - swapper: ALICE.into(), - filler: Omnipool::protocol_account(), - filler_type: pallet_broadcast::types::Filler::Omnipool, - operation: pallet_broadcast::types::TradeOperation::ExactIn, - inputs: vec![Asset::new(HDX, amount_to_sell)], - outputs: vec![Asset::new(LRNA, 49999997760919)], - fees: vec![Fee::new( - LRNA, - 24999998880, - Destination::Account(Omnipool::protocol_account()) - )], - operation_stack: vec![ - ExecutionType::DCA(schedule_id, 3), - ExecutionType::Router(4), - ExecutionType::Omnipool(5) - ], - }, - pallet_broadcast::Event::Swapped3 { - swapper: ALICE.into(), - filler: Omnipool::protocol_account(), - filler_type: pallet_broadcast::types::Filler::Omnipool, - operation: pallet_broadcast::types::TradeOperation::ExactIn, - inputs: vec![Asset::new(LRNA, 49974997762039)], - outputs: vec![Asset::new(DAI, 71214367987201)], - fees: vec![ - Fee::new(DAI, 98165168906, Destination::Account(Omnipool::protocol_account())), - Fee::new(DAI, 80316956376, Destination::Account(FeeProcessor::pot_account_id())), - ], - operation_stack: vec![ - ExecutionType::DCA(schedule_id, 3), - ExecutionType::Router(4), - ExecutionType::Omnipool(5) - ], - } - ] - ); - }); - } - - #[test] - fn sell_schedule_be_retried_when_route_is_invalid() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - BOB.into(), - ETH, - 1_000 * UNITS as i128, - )); - let position_id = hydradx_runtime::Omnipool::next_position_id(); - - assert_ok!(hydradx_runtime::Omnipool::add_token( - hydradx_runtime::RuntimeOrigin::root(), - ETH, - FixedU128::from_rational(3, 10), - Permill::from_percent(60), - BOB.into(), - )); - - rococo_run_to_block(12); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, ETH, amount_to_sell); - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - //Remove ETH token resulting invalid route - - assert_ok!(hydradx_runtime::Omnipool::set_asset_tradable_state( - hydradx_runtime::RuntimeOrigin::root(), - ETH, - Tradability::ADD_LIQUIDITY | Tradability::REMOVE_LIQUIDITY - )); - let position = - pallet_omnipool::Pallet::::load_position(position_id, BOB.into()).unwrap(); - assert_ok!(hydradx_runtime::Omnipool::remove_liquidity( - hydradx_runtime::RuntimeOrigin::signed(BOB.into()), - position_id, - position.shares, - )); - - assert_ok!(hydradx_runtime::Omnipool::set_asset_tradable_state( - hydradx_runtime::RuntimeOrigin::root(), - ETH, - Tradability::FROZEN - )); - assert_ok!(hydradx_runtime::Omnipool::remove_token( - hydradx_runtime::RuntimeOrigin::root(), - ETH, - BOB.into(), - )); - rococo_run_to_block(14); - - //Assert - let schedule_id = 0; - let schedule = DCA::schedules(schedule_id); - assert!(schedule.is_some()); - assert_eq!(DCA::retries_on_error(schedule_id), 1); - }); - } - - #[test] - fn create_schedule_should_work_when_asset_in_has_no_pool_at_all() { - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - hydradx_runtime::AssetRegistry::set_location(DOT, DOT_ASSET_LOCATION).unwrap(); - - init_omnipool_with_oracle_for_block_10(); - add_dot_as_payment_currency(); - - let name = b"INSUF1".to_vec(); - let insufficient_asset = AssetRegistry::register_insufficient_asset( - None, - Some(name.try_into().unwrap()), - AssetKind::External, - Some(1_000), - None, - None, - None, - None, - ) - .unwrap(); - - //Arrange - let block_id = 11; - go_to_block(block_id); - - let budget = 5000 * UNITS; - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::XYK, budget, insufficient_asset, DOT, 100 * UNITS); - - //Act - assert_ok!(Currencies::update_balance( - RawOrigin::Root.into(), - ALICE.into(), - insufficient_asset, - 5000 * UNITS as i128, - )); - //The sold asset has no pool and no price at all, which is fine - the protocol never - //needs to price it, because the fee is charged in the owner's fee currency. - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE.into()), - schedule1.clone(), - None - )); - - assert!(DCA::schedules::(0).is_some()); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn sell_schedule_execution_should_work_without_route() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let dca_budget = 1000 * UNITS; - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance); - - let amount_in = 100 * UNITS; - let no_route = vec![]; - let schedule1 = schedule_fake_with_sell_order_with_route(ALICE, dca_budget, HDX, DAI, amount_in, no_route); - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - assert!(fee > 0, "Treasury got rugged"); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, 2071214372591672); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - amount_in - fee); - }); - } - - #[test] - fn sell_schedule_should_be_terminated_after_retries() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule1 = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(1)), - order: Order::Sell { - asset_in: HDX, - asset_out: DAI, - amount_in: amount_to_sell, - min_amount_out: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: DAI, - }]), - }, - }; - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - - //Act and Assert - let schedule_id = 0; - let retry_1 = retry_block(12, 0); - let retry_2 = retry_block(retry_1, 1); - let retry_3 = retry_block(retry_2, 2); - - go_to_block(12); - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - fee); - - assert_eq!(DCA::retries_on_error(schedule_id), 1); - - go_to_block(retry_1); - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - 2 * fee); - assert_eq!(DCA::retries_on_error(schedule_id), 2); - - go_to_block(retry_2); - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - 3 * fee); - assert_eq!(DCA::retries_on_error(schedule_id), 3); - - //At this point, the schedule will be terminated as retries max number of times - go_to_block(retry_3); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - 4 * fee); - assert_reserved_balance!(&ALICE.into(), HDX, 0); - assert_eq!(DCA::retries_on_error(schedule_id), 0); - let schedule = DCA::schedules(schedule_id); - assert!(schedule.is_none()); - }); - } - - #[test] - fn sell_schedule_execution_should_work_when_hub_asset_is_sold() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let alice_init_hub_balance = 5000 * UNITS; - set_alice_lrna_balance(alice_init_hub_balance); - - let dca_budget = 2500 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, LRNA, DAI, amount_to_sell); - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), LRNA, alice_init_hub_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), LRNA, dca_budget); - assert_balance!(&Treasury::account_id(), LRNA, 0); - - //Act - go_to_block(12); - - //Assert - let treasury_balance = Currencies::free_balance(LRNA, &Treasury::account_id()); - assert!(treasury_balance > 0); - - assert_balance!(ALICE.into(), DAI, 2142499995765714); - assert_balance!(ALICE.into(), LRNA, alice_init_hub_balance - dca_budget); - let reserved_budget = Currencies::reserved_balance(LRNA, &ALICE.into()); - assert!(reserved_budget < dca_budget); - }); - } - - #[test] - fn sell_schedule_and_direct_omnipool_sell_and_router_should_yield_same_result_when_native_asset_sold() { - let amount_to_sell = 100 * UNITS; - - //DCA - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let dca_budget = 1100 * UNITS; - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - amount_to_sell - fee); - - assert_balance!(ALICE.into(), DAI, 2071214372591672); - }); - - //Direct Omnipool - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - //Act - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(ALICE.into()), - HDX, - DAI, - amount_to_sell, - 0, - )); - - //Assert - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - amount_to_sell); - assert_balance!(ALICE.into(), DAI, 2071214372591672); - }); - - //Router - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - //Act - let trade = vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: DAI, - }]; - assert_ok!(Router::sell( - RuntimeOrigin::signed(ALICE.into()), - HDX, - DAI, - amount_to_sell, - 0, - trade.try_into().unwrap() - )); - - //Assert - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - amount_to_sell); - assert_balance!(ALICE.into(), DAI, 2071214372591672); - }); - } - - #[test] - fn sell_schedule_and_direct_omnipool_sell_and_router_should_yield_same_result_when_hub_asset_sold() { - let amount_to_sell = 100 * UNITS; - - //DCA - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let alice_init_lrna_balance = 5000 * UNITS; - set_alice_lrna_balance(alice_init_lrna_balance); - - let dca_budget = 1100 * UNITS; - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, LRNA, DAI, amount_to_sell); - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), LRNA, alice_init_lrna_balance - dca_budget); - assert_reserved_balance!(&ALICE.into(), LRNA, dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(LRNA, &Treasury::account_id()); - assert_reserved_balance!(&ALICE.into(), LRNA, dca_budget - amount_to_sell - fee); - - assert_balance!(ALICE.into(), DAI, 2142499995765714); - }); - - //Direct omnipool - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let alice_init_lrna_balance = 5000 * UNITS; - set_alice_lrna_balance(alice_init_lrna_balance); - - assert_balance!(ALICE.into(), LRNA, alice_init_lrna_balance); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - - //Act - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(ALICE.into()), - LRNA, - DAI, - amount_to_sell, - 0, - )); - - //Assert - assert_balance!(ALICE.into(), LRNA, alice_init_lrna_balance - amount_to_sell); - assert_balance!(ALICE.into(), DAI, 2142499995765714); - }); - - //Router - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let alice_init_lrna_balance = 5000 * UNITS; - set_alice_lrna_balance(alice_init_lrna_balance); - - //Act - let trade = vec![Trade { - pool: PoolType::Omnipool, - asset_in: LRNA, - asset_out: DAI, - }]; - assert_ok!(Router::sell( - RuntimeOrigin::signed(ALICE.into()), - LRNA, - DAI, - amount_to_sell, - 0, - trade.try_into().unwrap() - )); - - //Assert - assert_balance!(ALICE.into(), LRNA, alice_init_lrna_balance - amount_to_sell); - assert_balance!(ALICE.into(), DAI, 2142499995765714); - }); - } - - #[test] - fn full_sell_dca_should_be_executed_then_completed() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - init_omnipool_with_oracle_for_block_10(); - - let amount_to_sell = 200 * UNITS; - let dca_budget = 1200 * UNITS; - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - - //Act - run_to_block(11, 12 + 16 * hydradx_runtime::MinimalPeriod::get()); - - //Assert - let new_dai_balance = Currencies::free_balance(DAI, &ALICE.into()); - assert!(new_dai_balance > ALICE_INITIAL_DAI_BALANCE); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_reserved_balance!(&ALICE.into(), HDX, 0); - - let schedule = DCA::schedules(0); - assert!(schedule.is_none()); - - check_if_dcas_completed_without_failed_or_terminated_events(); - }); - } - - #[test] - fn full_sell_dca_should_be_executed_then_completed_for_multiple_users() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let bob_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - BOB.into(), - bob_init_hdx_balance, - )); - - init_omnipool_with_oracle_for_block_10(); - - let amount_to_sell = 200 * UNITS; - let dca_budget = 1000 * UNITS; - let dca_budget_for_bob = 1200 * UNITS; - - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - let schedule2 = - schedule_fake_with_sell_order(BOB, PoolType::Omnipool, dca_budget_for_bob, HDX, DAI, amount_to_sell); - create_schedule(ALICE, schedule1); - create_schedule(BOB, schedule2); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_balance!(BOB.into(), HDX, bob_init_hdx_balance - dca_budget_for_bob); - assert_balance!(BOB.into(), DAI, BOB_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_reserved_balance!(&BOB.into(), HDX, dca_budget_for_bob); - - //Act - run_to_block(11, 12 + 16 * hydradx_runtime::MinimalPeriod::get()); - - //Assert - check_if_no_failed_events(); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(BOB.into(), HDX, bob_init_hdx_balance - dca_budget_for_bob); - assert_reserved_balance!(&ALICE.into(), HDX, 0); - assert_reserved_balance!(&BOB.into(), HDX, 0); - - let schedule = DCA::schedules(0); - assert!(schedule.is_none()); - - let schedule = DCA::schedules(1); - assert!(schedule.is_none()); - - check_if_dcas_completed_without_failed_or_terminated_events(); - }); - } - - #[test] - fn multiple_full_sell_dca_should_be_executed_then_completed_for_same_user() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - let alice_init_hdx_balance = 50000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - init_omnipool_with_oracle_for_block_10(); - - //Trade 1 - let amount_to_sell1 = 200 * UNITS; - let dca_budget1 = 1000 * UNITS; - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget1, HDX, DAI, amount_to_sell1); - create_schedule(ALICE, schedule1); - - //Trade 2 - let amount_to_sell2 = 220 * UNITS; - let dca_budget2 = 1500 * UNITS; - let schedule2 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget2, HDX, DAI, amount_to_sell2); - create_schedule(ALICE, schedule2); - - //Trade 3 - let amount_to_sell3 = 800 * UNITS; - let dca_budget3 = 2000 * UNITS; - let schedule3 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget3, HDX, DAI, amount_to_sell3); - create_schedule(ALICE, schedule3); - - let budget_for_all_trades = dca_budget1 + dca_budget2 + dca_budget3; - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - budget_for_all_trades); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, budget_for_all_trades); - - //Act - run_to_block(11, 12 + 16 * hydradx_runtime::MinimalPeriod::get()); - - //Assert - assert_reserved_balance!(&ALICE.into(), HDX, 0); - - let schedule = DCA::schedules(0); - assert!(schedule.is_none()); - - let schedule = DCA::schedules(1); - assert!(schedule.is_none()); - - let schedule = DCA::schedules(2); - assert!(schedule.is_none()); - - check_if_dcas_completed_without_failed_or_terminated_events(); - }); - } - - #[test] - fn schedules_should_be_ordered_based_on_random_number_when_executed_in_a_block() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - let native_amount = 100000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - HDX, - native_amount as i128, - )); - - init_omnipool_with_oracle_for_block_10(); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - let schedule2 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - let schedule3 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - let schedule4 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - let schedule5 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - let schedule6 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - - create_schedule(ALICE, schedule1); - create_schedule(ALICE, schedule2); - create_schedule(ALICE, schedule3); - create_schedule(ALICE, schedule4); - create_schedule(ALICE, schedule5); - create_schedule(ALICE, schedule6); - - //Act - run_to_block(11, 12); - - //Assert - //We check if the schedules are processed not in the order they were created, - // ensuring that they are sorted based on randomness - assert_ne!( - vec![0, 1, 2, 3, 4, 5], - get_last_schedule_ids_from_trade_executed_events() - ) - }); - } - - #[test] - fn sell_schedule_should_work_when_user_has_left_less_than_existential_deposit() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let amount_to_sell = 1000 * UNITS; - let fee = DCA::get_transaction_fee( - &Order::Sell { - asset_in: HDX, - asset_out: DAI, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: DAI, - }]), - }, - None, - ) - .unwrap(); - - let alice_init_hdx_balance = 2 * (1000 * UNITS + fee) + 1; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let dca_budget = 2 * (1000 * UNITS + fee); - let schedule1 = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, dca_budget, HDX, DAI, amount_to_sell); - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - run_to_block(11, 12 + hydradx_runtime::MinimalPeriod::get()); - - //Assert - check_if_no_failed_events(); - assert_reserved_balance!(&ALICE.into(), HDX, 0); - assert_balance!(ALICE.into(), HDX, 0); - }); - } - - #[test] - fn sell_schedule_should_use_slippage_limit_when_min_amount_out_is_zero() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - - // Create sell schedule with min_amount_out = 0 - // This means last_block_slippage_min_limit will be used as the effective limit - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(5)), - order: Order::Sell { - asset_in: HDX, - asset_out: DAI, - amount_in: amount_to_sell, - min_amount_out: 0, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: DAI, - }]), - }, - }; - create_schedule(ALICE, schedule); - - let alice_dai_before = Currencies::free_balance(DAI, &ALICE.into()); - - //Act - go_to_block(12); - - //Assert - DCA executed successfully and schedule is still alive - let alice_dai_after = Currencies::free_balance(DAI, &ALICE.into()); - assert!( - alice_dai_after > alice_dai_before, - "ALICE should have received DAI from the trade" - ); - - let schedule = DCA::schedules(0); - assert!(schedule.is_some(), "DCA schedule should still be alive after execution"); - }); - } -} - -mod stableswap { - use super::*; - - #[test] - fn sell_should_work_when_two_stableassets_swapped() { - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, asset_a, asset_b) = init_stableswap().unwrap(); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - asset_a, - FixedU128::from_rational(88, 100), - )); - - let alice_init_asset_a_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - asset_a, - alice_init_asset_a_balance as i128, - )); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - asset_a, - 5000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - asset_a, - asset_b, - 100 * UNITS, - 0u128, - )); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule1 = schedule_fake_with_sell_order( - ALICE, - PoolType::Stableswap(pool_id), - dca_budget, - asset_a, - asset_b, - amount_to_sell, - ); - go_to_block(10); - - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, 0); - assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget); - assert_balance!(&Treasury::account_id(), asset_a, 0); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(asset_a, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, 98999999706917); - assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget - amount_to_sell - fee); - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn two_stableswap_asssets_should_be_swapped_when_they_have_different_decimals() { - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, asset_a, asset_b) = - init_stableswap_with_three_assets_having_different_decimals().unwrap(); - - //Populate oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - asset_b, - 5000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - asset_a, - asset_b, - 10_000_000, - 0u128, - )); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - asset_a, - FixedU128::from_rational(88, 100), - )); - - let alice_init_asset_a_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - asset_a, - alice_init_asset_a_balance as i128, - )); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule1 = schedule_fake_with_sell_order( - ALICE, - PoolType::Stableswap(pool_id), - dca_budget, - asset_a, - asset_b, - amount_to_sell, - ); - go_to_block(10); - - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, 0); - assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget); - assert_balance!(&Treasury::account_id(), asset_a, 0); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(asset_a, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, 93176719400532); - assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget - amount_to_sell - fee); - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn sell_should_work_with_omnipool_and_stable_trades() { - let amount_to_sell = 200 * UNITS; - let amount_to_receive = 198401944835214; - //With DCA - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 10000 * UNITS, - 0, - )); - - init_omnipol(); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 30_000_000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - - go_to_block(10); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - ]; - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Sell { - asset_in: HDX, - asset_out: stable_asset_1, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(trades), - }, - }; - - create_schedule(ALICE, schedule); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, 0); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, amount_to_receive); - - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - amount_to_sell - fee); - - let treasury_balance = Currencies::free_balance(HDX, &Treasury::account_id()); - assert!(treasury_balance > TREASURY_ACCOUNT_INIT_BALANCE); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - - //Do the same in with pool trades - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 10000 * UNITS, - 0, - )); - - init_omnipol(); - - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 30_000_000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - - go_to_block(10); - - //Act - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(ALICE.into()), - HDX, - pool_id, - amount_to_sell, - 0, - )); - - let pool_id_balance = Currencies::free_balance(pool_id, &AccountId::from(ALICE)); - - assert_ok!(Stableswap::remove_liquidity_one_asset( - RuntimeOrigin::signed(ALICE.into()), - pool_id, - stable_asset_1, - pool_id_balance, - 0 - )); - - //Assert - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - amount_to_sell); - assert_balance!(ALICE.into(), stable_asset_1, amount_to_receive); - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - - //Do the same with plain router - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 10000 * UNITS, - 0, - )); - - init_omnipol(); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 30_000_000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - - go_to_block(10); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - ]; - - assert_ok!(Router::sell( - RuntimeOrigin::signed(ALICE.into()), - HDX, - stable_asset_1, - amount_to_sell, - 0, - trades.try_into().unwrap() - )); - - //Assert - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - amount_to_sell); - assert_balance!(ALICE.into(), stable_asset_1, amount_to_receive); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn sell_should_work_with_stable_trades_and_omnipool() { - let amount_to_sell = 100 * UNITS; - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - //To populate stableswap oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 100 * UNITS, - 0, - )); - - //Set stable asset 1 as accepted payment currency - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_rational(50, 100), - )); - - //Init omnipool and add pool id as token - init_omnipol(); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - //Populate oracle with omnipool source - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - CHARLIE.into(), - pool_id, - 1000 * UNITS - )); - - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - HDX, - 500 * UNITS, - Balance::MIN - )); - - go_to_block(1000); - - let alice_init_stable1_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance as i128, - )); - - let trades = vec![ - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Omnipool, - asset_in: pool_id, - asset_out: HDX, - }, - ]; - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Sell { - asset_in: stable_asset_1, - asset_out: HDX, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(trades), - }, - }; - - create_schedule(ALICE, schedule); - - assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - assert_reserved_balance!(&ALICE.into(), stable_asset_1, dca_budget); - assert_balance!(&Treasury::account_id(), stable_asset_1, 0); - - //Act - go_to_block(1002); - - //Assert - let fee = Currencies::free_balance(stable_asset_1, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); - assert_balance!(ALICE.into(), HDX, 1070726325505236); - - assert_reserved_balance!(&ALICE.into(), stable_asset_1, dca_budget - amount_to_sell - fee); - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - - //Do the same in with pool trades - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - //To populate stableswap oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 100 * UNITS, - 0, - )); - - init_omnipol(); - - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - - //Populate oracle with omnipool source - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - CHARLIE.into(), - pool_id, - 1000 * UNITS - )); - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - HDX, - 500 * UNITS, - Balance::MIN - )); - - let alice_init_stable1_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance as i128, - )); - - assert_balance!(ALICE.into(), pool_id, 0); - - go_to_block(10); - - //Act - assert_ok!(Stableswap::add_assets_liquidity( - RuntimeOrigin::signed(ALICE.into()), - pool_id, - BoundedVec::truncate_from(vec![AssetAmount { - asset_id: stable_asset_1, - amount: amount_to_sell, - }]), - Balance::zero(), - )); - let alice_pool_id_balance = Currencies::free_balance(pool_id, &AccountId::from(ALICE)); - - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(ALICE.into()), - pool_id, - HDX, - alice_pool_id_balance, - 0, - )); - - //Assert - assert_balance!( - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance - amount_to_sell - ); - assert_balance!(ALICE.into(), HDX, 1070726325505236); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - - //Do the same with plain router - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - //To populate stableswap oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 100 * UNITS, - 0, - )); - - init_omnipol(); - - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - - //Populate oracle with omnipool source - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - CHARLIE.into(), - pool_id, - 1000 * UNITS - )); - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - HDX, - 500 * UNITS, - Balance::MIN - )); - - let alice_init_stable1_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance as i128, - )); - - assert_balance!(ALICE.into(), pool_id, 0); - - go_to_block(10); - - //Act - let trades = vec![ - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Omnipool, - asset_in: pool_id, - asset_out: HDX, - }, - ]; - assert_ok!(Router::sell( - RuntimeOrigin::signed(ALICE.into()), - stable_asset_1, - HDX, - amount_to_sell, - 0, - trades.try_into().unwrap() - )); - - //Assert - assert_balance!( - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance - amount_to_sell - ); - assert_balance!(ALICE.into(), HDX, 1070726325505236); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn buy_should_work_with_omnipool_and_stable_trades() { - let amount_to_buy = 200 * UNITS; - //With DCA - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - //To populate stableswap oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 3000 * UNITS, - 0, - )); - - init_omnipol(); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - set_zero_reward_for_referrals(pool_id); - - go_to_block(10); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - ]; - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Buy { - asset_in: HDX, - asset_out: stable_asset_1, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(trades), - }, - }; - - insert_schedule_into_storage(ALICE, schedule, None); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, 0); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, amount_to_buy); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn buy_should_work_when_two_stableassets_swapped() { - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, asset_a, asset_b) = init_stableswap().unwrap(); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - asset_a, - FixedU128::from_rational(88, 100), - )); - - let alice_init_asset_a_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - asset_a, - alice_init_asset_a_balance as i128, - )); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - asset_a, - 5000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - asset_a, - asset_b, - 100 * UNITS, - 0u128, - )); - - let dca_budget = 1100 * UNITS; - let amount_to_buy = 100 * UNITS; - let schedule1 = schedule_fake_with_buy_order( - PoolType::Stableswap(pool_id), - asset_a, - asset_b, - amount_to_buy, - dca_budget, - ); - go_to_block(12); - - insert_schedule_into_storage(ALICE, schedule1, None); - - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, 0); - assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget); - assert_balance!(&Treasury::account_id(), asset_a, 0); - - //Act - go_to_block(14); - - //Assert - let fee = Currencies::free_balance(asset_a, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, amount_to_buy); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn buy_should_work_with_stable_trades_and_omnipool() { - let amount_to_buy = 100 * UNITS; - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - //Set stable asset 1 as accepted payment currency - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_rational(50, 100), - )); - - //For populating oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 5000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 1000 * UNITS, - 0u128, - )); - - //Init omnipool and add pool id as token - init_omnipol(); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - do_trade_to_populate_oracle(pool_id, HDX, 100 * UNITS); - - go_to_block(10); - - let alice_init_stable1_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance as i128, - )); - - let trades = vec![ - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Omnipool, - asset_in: pool_id, - asset_out: HDX, - }, - ]; - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(70)), - order: Order::Buy { - asset_in: stable_asset_1, - asset_out: HDX, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(trades), - }, - }; - - insert_schedule_into_storage(ALICE, schedule, None); - - assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - assert_reserved_balance!(&ALICE.into(), stable_asset_1, dca_budget); - assert_balance!(&Treasury::account_id(), stable_asset_1, 0); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(stable_asset_1, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE + amount_to_buy); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn dca_buy_fails_when_circuit_breaker_deposit_limit_is_set_on_share_asset() { - TestNet::reset(); - - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_rational(50, 100), - )); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 5000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 1000 * UNITS, - 0u128, - )); - - //Init omnipool and add pool id as token - init_omnipol(); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - do_trade_to_populate_oracle(pool_id, HDX, 100 * UNITS); - - go_to_block(10); - - let deposit_limit = 50 * UNITS; - crate::deposit_limiter::update_deposit_limit(pool_id, deposit_limit).unwrap(); - - let alice_init_stable1_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance as i128, - )); - - // First leg mints pool shares, which will be limited by circuit breaker - let trades = vec![ - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Omnipool, - asset_in: pool_id, - asset_out: HDX, - }, - ]; - - let amount_to_buy = 100 * UNITS; - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(100)), - order: Order::Buy { - asset_in: stable_asset_1, - asset_out: HDX, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(trades), - }, - }; - - insert_schedule_into_storage(ALICE, schedule, None); - - let alice_hdx_before = Currencies::free_balance(HDX, &ALICE.into()); - assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); - assert_reserved_balance!(&ALICE.into(), stable_asset_1, dca_budget); - - //Act - Execute DCA - go_to_block(12); - - let alice_hdx_after = Currencies::free_balance(HDX, &ALICE.into()); - let router_reserved_pool_id = Currencies::reserved_balance(pool_id, &Router::router_account()); - - assert_eq!( - alice_hdx_after, alice_hdx_before, - "DCA should fail when circuit breaker deposit limit is set on share asset" - ); - - assert_eq!( - router_reserved_pool_id, 0, - "No shares should be reserved since DCA didn't execute" - ); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - /// It fails because stable share is locked in an intermediary trade, - /// and in the next hop the user has not enough balance to continue the trade - #[test] - fn buy_should_be_retried_when_circuit_breaker_triggers_on_intermediate_shares_trade() { - TestNet::reset(); - - Hydra::execute_with(|| { - let _ = with_transaction(|| { - // Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_rational(50, 100), - )); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 5000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 1000 * UNITS, - 0u128, - )); - - init_omnipol(); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - do_trade_to_populate_oracle(pool_id, HDX, 100 * UNITS); - - go_to_block(10); - - let deposit_limit = 50 * UNITS; - crate::deposit_limiter::update_deposit_limit(pool_id, deposit_limit).unwrap(); - - let alice_init_stable1_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance as i128, - )); - - let trades = vec![ - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Omnipool, - asset_in: pool_id, - asset_out: HDX, - }, - ]; - - let amount_to_buy = 100 * UNITS; - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(70)), - order: Order::Buy { - asset_in: stable_asset_1, - asset_out: HDX, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(trades), - }, - }; - - insert_schedule_into_storage(ALICE, schedule, None); - - let alice_hdx_before = Currencies::free_balance(HDX, &ALICE.into()); - - // Act - go_to_block(12); - - // Assert - DCA should be retried (not terminated) because lockdown is temporary - let terminated = count_terminated_trade_events(); - assert_eq!( - terminated, 0, - "DCA should not be terminated when circuit breaker triggers on intermediate shares" - ); - - let schedule_id = 0; - assert_eq!( - DCA::retries_on_error(schedule_id), - 1, - "DCA retry count should be incremented" - ); - - let alice_hdx_after = Currencies::free_balance(HDX, &ALICE.into()); - assert_eq!( - alice_hdx_after, alice_hdx_before, - "Alice HDX balance should be unchanged" - ); - - let alice_shares = Currencies::free_balance(pool_id, &ALICE.into()); - assert_eq!(alice_shares, 0, "Alice should have zero stableshare balance"); - - let router_reserved_shares = Currencies::reserved_balance(pool_id, &Router::router_account()); - assert_eq!(router_reserved_shares, 0, "Router should have zero reserved shares"); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn dca_buy_fails_when_deposit_limit_exceeded_in_router_context() { - TestNet::reset(); - - Hydra::execute_with(|| { - let _ = with_transaction(|| { - // Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_rational(50, 100), - )); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 5000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 1000 * UNITS, - 0u128, - )); - - // Init omnipool and add stable_asset_1 as token - init_omnipol(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - stable_asset_1, - 3000 * UNITS as i128, - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(stable_asset_1); - do_trade_to_populate_oracle(stable_asset_1, HDX, 100 * UNITS); - - go_to_block(10); - - let deposit_limit = 50 * UNITS; - crate::deposit_limiter::update_deposit_limit(pool_id, deposit_limit).unwrap(); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - HDX, - 5000 * UNITS as i128, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: stable_asset_1, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, // Minting shares at the END - }, - ]; - - let amount_to_buy = 100 * UNITS; - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(70)), - order: Order::Buy { - asset_in: HDX, - asset_out: pool_id, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(trades), - }, - }; - - insert_schedule_into_storage(ALICE, schedule, None); - - let alice_pool_id_before = Currencies::free_balance(pool_id, &ALICE.into()); - assert_eq!(alice_pool_id_before, 0, "ALICE should start with 0 pool_id shares"); - - // Act - Execute DCA - go_to_block(12); - - // Assert - let alice_stable_shares_after = Currencies::free_balance(pool_id, &ALICE.into()); - let router_reserved_shares = Currencies::reserved_balance(pool_id, &Router::router_account()); - - assert_eq!( - alice_stable_shares_after, 0, - "User should have 0 pool shares since DCA execution failed. Got {alice_stable_shares_after}" - ); - - assert_eq!( - router_reserved_shares, 0, - "Router should have 0 reserved shares. Got {router_reserved_shares}" - ); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - /// It fails because stable share is locked in an intermediary trade, - /// and in the next hop the user has not enough balance to continue the trade - #[test] - fn sell_should_be_retried_when_stableshare_is_in_lockdown() { - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - // Arrange - let (pool_id, stable_asset_1, _stable_asset_2) = init_stableswap().unwrap(); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_rational(88, 100), - )); - - let alice_init_stable_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable_balance as i128, - )); - - // Trigger lockdown on the stableshare (pool_id) by adding liquidity that mints - // more shares than the deposit limit - let deposit_limit = UNITS; - crate::deposit_limiter::update_deposit_limit(pool_id, deposit_limit).unwrap(); - let bob_liquidity = 10_000_000_000_000_000_000u128; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - BOB.into(), - stable_asset_1, - bob_liquidity as i128, - )); - assert_ok!(Stableswap::add_assets_liquidity( - RuntimeOrigin::signed(BOB.into()), - pool_id, - BoundedVec::truncate_from(vec![AssetAmount::new(stable_asset_1, bob_liquidity)]), - Balance::zero(), - )); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule = schedule_fake_with_sell_order( - ALICE, - PoolType::Stableswap(pool_id), - dca_budget, - stable_asset_1, - pool_id, - amount_to_sell, - ); - - go_to_block(10); - create_schedule(ALICE, schedule); - - // Act - go_to_block(12); - - // Assert - DCA should be retried (not terminated) because lockdown is temporary - let terminated = count_terminated_trade_events(); - assert_eq!( - terminated, 0, - "DCA should not be terminated when stableshare is in lockdown" - ); - - let schedule_id = 0; - assert_eq!( - DCA::retries_on_error(schedule_id), - 1, - "DCA retry count should be incremented" - ); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn sell_should_succeed_after_lockdown_is_lifted() { - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - // Arrange - let (pool_id, stable_asset_1, _stable_asset_2) = init_stableswap().unwrap(); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_rational(88, 100), - )); - - let alice_init_stable_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable_balance as i128, - )); - - // Trigger lockdown on the stableshare (pool_id) by adding liquidity that mints - // more shares than the deposit limit - let deposit_limit = UNITS; - crate::deposit_limiter::update_deposit_limit(pool_id, deposit_limit).unwrap(); - let bob_liquidity = 10_000_000_000_000_000_000u128; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - BOB.into(), - stable_asset_1, - bob_liquidity as i128, - )); - assert_ok!(Stableswap::add_assets_liquidity( - RuntimeOrigin::signed(BOB.into()), - pool_id, - BoundedVec::truncate_from(vec![AssetAmount::new(stable_asset_1, bob_liquidity)]), - Balance::zero(), - )); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule = schedule_fake_with_sell_order( - ALICE, - PoolType::Stableswap(pool_id), - dca_budget, - stable_asset_1, - pool_id, - amount_to_sell, - ); - - go_to_block(10); - create_schedule(ALICE, schedule); - - // Act - first execution fails due to lockdown - go_to_block(12); - - let schedule_id = 0; - assert_eq!(DCA::retries_on_error(schedule_id), 1); - assert_eq!(count_terminated_trade_events(), 0); - - // Lift the lockdown and raise the deposit limit so the retry trade can go through - assert_ok!(hydradx_runtime::CircuitBreaker::force_lift_lockdown( - RuntimeOrigin::root(), - pool_id, - )); - crate::deposit_limiter::update_deposit_limit(pool_id, 1_000_000 * UNITS).unwrap(); - - go_to_block(retry_block(12, 0)); - - // Assert - assert_eq!( - DCA::retries_on_error(schedule_id), - 0, - "Retry count should reset after successful trade" - ); - assert_eq!(count_terminated_trade_events(), 0, "DCA should not be terminated"); - assert!( - Currencies::free_balance(pool_id, &AccountId::from(ALICE)) > 0, - "Alice should have received stableshares" - ); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } -} - -mod xyk { - use super::*; - - #[test] - fn sell_should_work_for_xyk() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - BOB.into(), - 5000 * UNITS, - )); - - assert_ok!(Tokens::set_balance( - RawOrigin::Root.into(), - BOB.into(), - DAI, - 5000 * UNITS, - 0, - )); - - assert_ok!(XYK::create_pool( - RuntimeOrigin::signed(BOB.into()), - HDX, - 1000 * UNITS, - DAI, - 2000 * UNITS, - )); - - //For populating oracle - assert_ok!(XYK::sell( - RuntimeOrigin::signed(BOB.into()), - HDX, - DAI, - 100 * UNITS, - 0, - false - )); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - go_to_block(10); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule1 = schedule_fake_with_sell_order(ALICE, PoolType::XYK, dca_budget, HDX, DAI, amount_to_sell); - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - let treasury_init_balance = Balances::free_balance(Treasury::account_id()); - - //Act - go_to_block(12); - - //Assert - let amount_out = 151105924242426; - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - treasury_init_balance; - - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE + amount_out); - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - amount_to_sell - fee); - }); - } - #[test] - fn buy_should_work_for_xyk() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - create_xyk_pool(HDX, 1000 * UNITS, DAI, 2000 * UNITS); - - //For populating oracle - assert_ok!(Currencies::update_balance( - RawOrigin::Root.into(), - BOB.into(), - HDX, - 200 * UNITS as i128, - )); - assert_ok!(XYK::sell( - RuntimeOrigin::signed(BOB.into()), - HDX, - DAI, - 100 * UNITS, - 0, - false - )); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_init_hdx_balance, - )); - - go_to_block(10); - - let dca_budget = 1100 * UNITS; - let amount_to_buy = 150 * UNITS; - let schedule1 = schedule_fake_with_buy_order(PoolType::XYK, HDX, DAI, amount_to_buy, dca_budget); - insert_schedule_into_storage(ALICE, schedule1, None); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - - //Act - go_to_block(12); - - //Assert - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE + amount_to_buy); - }); - } -} - -mod all_pools { - use super::*; - - #[test] - fn sell_should_work_with_3_different_pools() { - let amount_to_sell = 200 * UNITS; - - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - //Create stableswap and populate oracle - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 1000 * UNITS, - 0, - )); - - //Create omnipool and populate oracle - init_omnipol(); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 1000000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - - //Create xyk and populate oracle - create_xyk_pool(stable_asset_1, 10000 * UNITS, DAI, 20000 * UNITS); - assert_ok!(Currencies::update_balance( - RawOrigin::Root.into(), - BOB.into(), - stable_asset_1, - 200 * UNITS as i128, - )); - assert_ok!(XYK::sell( - RuntimeOrigin::signed(BOB.into()), - stable_asset_1, - DAI, - 100 * UNITS, - 0, - false - )); - - go_to_block(10); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - Trade { - pool: PoolType::XYK, - asset_in: stable_asset_1, - asset_out: DAI, - }, - ]; - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(15)), - order: Order::Sell { - asset_in: HDX, - asset_out: DAI, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(trades), - }, - }; - - create_schedule(ALICE, schedule); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, ALICE_INITIAL_DAI_BALANCE); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - //The insufficient-asset deposit is held on the payer now, so the treasury is untouched. - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - go_to_block(12); - - //Assert - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), DAI, 2380286185085611); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } -} - -fn create_xyk_pool(asset_a: AssetId, amount_a: Balance, asset_b: AssetId, amount_b: Balance) { - //Arrange - assert_ok!(Currencies::update_balance( - RawOrigin::Root.into(), - DAVE.into(), - asset_a, - amount_a as i128, - )); - - assert_ok!(Currencies::update_balance( - RawOrigin::Root.into(), - DAVE.into(), - asset_b, - amount_b as i128, - )); - - assert_ok!(XYK::create_pool( - RuntimeOrigin::signed(DAVE.into()), - asset_a, - amount_a, - asset_b, - amount_b, - )); -} - -mod with_onchain_route { - use super::*; - use frame_support::pallet_prelude::DispatchResult; - use hydradx_traits::router::PoolType; - - #[test] - fn buy_should_work_with_omnipool_and_stable_with_onchain_routes() { - let amount_to_buy = 200 * UNITS; - //With DCA - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - //To populate stableswap oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 3000 * UNITS, - 0, - )); - - init_omnipol(); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 300_000_000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - - go_to_block(10); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - ]; - - let asset_pair = AssetPair::new(HDX, stable_asset_1); - assert_ok!(Router::set_route( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - asset_pair, - trades.clone().try_into().unwrap() - )); - assert_eq!(Router::route(asset_pair).unwrap(), trades); - - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Buy { - asset_in: HDX, - asset_out: stable_asset_1, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(vec![]), - }, - }; - - insert_schedule_into_storage(ALICE, schedule, None); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, 0); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - go_to_block(12); - - //Assert - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, amount_to_buy); - - assert_balance!(Router::router_account(), HDX, 0); - assert_balance!(Router::router_account(), stable_asset_1, 0); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn sell_should_work_with_omnipool_and_stable_trades_with_onchain_routes() { - let amount_to_sell = 200 * UNITS; - let amount_to_receive = 198403134650839u128; - - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 10000 * UNITS, - 0, - )); - - init_omnipol(); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 300_000_000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - - go_to_block(10); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - ]; - - let asset_pair = AssetPair::new(HDX, stable_asset_1); - assert_ok!(Router::set_route( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - asset_pair, - trades.clone().try_into().unwrap() - )); - assert_eq!(Router::route(asset_pair).unwrap(), trades); - - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Sell { - asset_in: HDX, - asset_out: stable_asset_1, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![]), - }, - }; - - create_schedule(ALICE, schedule); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, 0); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, amount_to_receive); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - amount_to_sell - fee); - - assert_balance!(Router::router_account(), HDX, 0); - assert_balance!(Router::router_account(), stable_asset_1, 0); - - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn schedule_should_work_when_fee_asset_is_nonnative_omni_asset() { - let amount_to_sell = 2000 * UNITS; - - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipol(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - DOT, - 1_000_000 * UNITS as i128, - )); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - hydradx_runtime::RuntimeOrigin::root(), - DOT, - FixedU128::from_rational(50, 100), - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - DOT, - FixedU128::from_rational(10, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(DOT); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - DOT, - 50000 * UNITS as i128, - )); - let alice_init_dot_balance = 50000 * UNITS + ALICE_INITIAL_DOT_BALANCE; - - go_to_block(10); - - let dca_budget = 10000 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Sell { - asset_in: DOT, - asset_out: HDX, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![]), - }, - }; - - //We verify the price diff between hdx and stable asset. - //If we sell 3703744780645, we receive 18462849173515, - // so something like 5x more, so fee should be 5x than normal HDX - let _dot_amount = with_transaction::<_, _, _>(|| { - let amount_to_sell = 3703744780645; - assert_ok!(Router::sell( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - HDX, - DOT, - amount_to_sell, - 0, - BoundedVec::new() - )); - let alice_received_dot = - Currencies::free_balance(DOT, &AccountId::from(ALICE)) - alice_init_dot_balance; - - TransactionOutcome::Rollback(Ok::(alice_received_dot)) - }) - .unwrap(); - - assert_balance!(ALICE.into(), DOT, alice_init_dot_balance); - - create_schedule(ALICE, schedule); - - assert_balance!(ALICE.into(), DOT, alice_init_dot_balance - dca_budget); - assert_reserved_balance!(&ALICE.into(), DOT, dca_budget); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(DOT, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - - assert_balance!(ALICE.into(), DOT, alice_init_dot_balance - dca_budget); - assert_balance!(ALICE.into(), HDX, 1398004528624518); - - assert_reserved_balance!(&ALICE.into(), DOT, dca_budget - amount_to_sell - fee); - }); - } - - #[test] - fn schedule_should_work_when_stable_asset_used_as_fee_asset() { - let amount_to_sell = 200 * UNITS; - - TestNet::reset(); - Hydra::execute_with(|| { - let _ = with_transaction(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - hydradx_runtime::RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_rational(50, 100), - )); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 10000 * UNITS, - 0, - )); - - init_omnipol(); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(BOB.into()), - Omnipool::protocol_account(), - pool_id, - 300_000_000 * UNITS - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - set_zero_reward_for_referrals(pool_id); - do_trade_to_populate_oracle(pool_id, HDX, 10000000 * UNITS); - - go_to_block(10); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let alice_init_stable_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable_balance as i128, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - ]; - - let asset_pair = AssetPair::new(HDX, stable_asset_1); - assert_ok!(Router::set_route( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - asset_pair, - trades.clone().try_into().unwrap() - )); - assert_eq!(Router::route(asset_pair).unwrap(), trades); - - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Sell { - asset_in: stable_asset_1, - asset_out: HDX, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![]), - }, - }; - - //We verify the price diff between hdx and stable asset. - //If we sell 6503744780645, we receive 5385180382312 - //So fee should be like 0.8x normal HDX fee - let _stable_amount = with_transaction::<_, _, _>(|| { - let amount_to_sell = 6503744780645; - assert_ok!(Router::sell( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - HDX, - stable_asset_1, - amount_to_sell, - 0, - BoundedVec::new() - )); - let alice_received_stable = - Currencies::free_balance(stable_asset_1, &AccountId::from(ALICE)) - alice_init_stable_balance; - - TransactionOutcome::Rollback(Ok::(alice_received_stable)) - }) - .unwrap(); - - create_schedule(ALICE, schedule); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(stable_asset_1, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - - assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable_balance - dca_budget); - assert!(Currencies::free_balance(HDX, &ALICE.into()) > alice_init_hdx_balance); - - assert_reserved_balance!(&ALICE.into(), stable_asset_1, dca_budget - amount_to_sell - fee); - TransactionOutcome::Commit(DispatchResult::Ok(())) - }); - }); - } - - #[test] - fn schedule_should_work_when_xyk_asset_used_as_fee_asset() { - let amount_to_sell = 200 * UNITS; - - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipol(); - - do_trade_to_populate_oracle(DAI, HDX, 10000000 * UNITS); - - create_xyk_pool_with_amounts(DAI, 10000000000 * UNITS, DOT, 10000000000 * UNITS); - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - hydradx_runtime::RuntimeOrigin::root(), - DOT, - FixedU128::from_rational(50, 100), - )); - - //Populate xyk - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - DAVE.into(), - DAI, - 10000000 * UNITS as i128, - )); - assert_ok!(XYK::sell( - RuntimeOrigin::signed(DAVE.into()), - DAI, - DOT, - 10000000 * UNITS, - u128::MIN, - false - )); - - go_to_block(10); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - ALICE.into(), - alice_init_hdx_balance, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: DAI, - }, - Trade { - pool: PoolType::XYK, - asset_in: DAI, - asset_out: DOT, - }, - ]; - - let asset_pair = AssetPair::new(HDX, DOT); - assert_ok!(Router::set_route( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - asset_pair, - trades.clone().try_into().unwrap() - )); - assert_eq!(Router::route(asset_pair).unwrap(), trades); - - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Sell { - asset_in: DOT, - asset_out: HDX, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![]), - }, - }; - - //Just to verify the price difference between HDX and DOT - //Selling 3795361512418 HDX results 2694204333872 DOT - //So fee should be 0.7x normal HDX fee - let _dot_amount_out = with_transaction::<_, _, _>(|| { - let fee_in_hdx = 3795361512418; - assert_ok!(Router::sell( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - HDX, - DOT, - fee_in_hdx, - 0, - BoundedVec::new() - )); - let alice_received_dot = - Currencies::free_balance(DOT, &AccountId::from(ALICE)) - ALICE_INITIAL_DOT_BALANCE; - - TransactionOutcome::Rollback(Ok::(alice_received_dot)) - }) - .unwrap(); - - create_schedule(ALICE, schedule); - - //Act - go_to_block(12); - - //Assert - let fee = Currencies::free_balance(DOT, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - - assert_balance!(ALICE.into(), HDX, 5264995050009313); - assert_reserved_balance!(&ALICE.into(), DOT, dca_budget - amount_to_sell - fee); - }); - } -} - -#[test] -fn terminate_should_work_for_freshly_created_dca() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let block_id = 11; - go_to_block(block_id); - - let budget = 1000 * UNITS; - let schedule1 = schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, budget, HDX, DAI, 100 * UNITS); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE.into()), - schedule1.clone(), - None - )); - - let schedule_id = 0; - let schedule = DCA::schedules(schedule_id); - assert!(schedule.is_some()); - - //Act - assert_ok!(DCA::terminate(RuntimeOrigin::signed(ALICE.into()), schedule_id, None)); - - //Assert - let schedule = DCA::schedules(schedule_id); - assert!(schedule.is_none()); - }); -} - -#[test] -fn unlock_should_not_work_when_user_has_active_schedule() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let block_id = 11; - go_to_block(block_id); - - let budget = 1000 * UNITS; - let schedule1 = schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, budget, HDX, DAI, 100 * UNITS); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE.into()), - schedule1.clone(), - None - )); - - let schedule_id = 0; - let schedule = DCA::schedules(schedule_id); - assert!(schedule.is_some()); - - //Act - assert_noop!( - DCA::unlock_reserves(RuntimeOrigin::signed(ALICE.into()), ALICE.into(), HDX), - pallet_dca::Error::::HasActiveSchedules - ); - }); -} - -#[test] -fn unclock_should_work_when_user_has_leftover() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - let block_id = 11; - go_to_block(block_id); - - assert_ok!(Currencies::reserve_named( - &NamedReserveId::get(), - DOT, - &ALICE.into(), - 21323213213 - )); - - assert_reserved_balance!(ALICE.into(), DOT, 21323213213); - - //Act - assert_ok!(DCA::unlock_reserves( - RuntimeOrigin::signed(ALICE.into()), - ALICE.into(), - DOT - ),); - - //Assert - assert_reserved_balance!(&ALICE.into(), DOT, 0); - }); -} - -/// Guards `insert_schedule_into_storage` against drift from the `schedule` extrinsic: an order the -/// extrinsic still accepts must land in identical state either way. -mod storage_injection_fidelity { - use super::*; - - #[test] - fn storage_injected_schedule_should_match_extrinsic_created_schedule() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - go_to_block(11); - fund_alice_for_two_schedules(); - - let schedule = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, 1000 * UNITS, HDX, DAI, 100 * UNITS); - - //Act - create_schedule(ALICE, schedule.clone()); - let reserved_by_extrinsic = Currencies::reserved_balance(HDX, &ALICE.into()); - let injected_id = insert_schedule_into_storage(ALICE, schedule, None); - - //Assert - assert_schedules_are_identical(0, injected_id, HDX, reserved_by_extrinsic); - }); - } - - #[test] - fn storage_injected_rolling_schedule_should_match_extrinsic_created_schedule() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - go_to_block(11); - fund_alice_for_two_schedules(); - - let rolling_budget = 0; - let schedule = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, rolling_budget, HDX, DAI, 500 * UNITS); - - //Act - create_schedule(ALICE, schedule.clone()); - let reserved_by_extrinsic = Currencies::reserved_balance(HDX, &ALICE.into()); - let injected_id = insert_schedule_into_storage(ALICE, schedule, None); - - //Assert - assert_schedules_are_identical(0, injected_id, HDX, reserved_by_extrinsic); - }); - } - - #[test] - fn storage_injected_schedule_should_match_extrinsic_created_schedule_when_start_block_is_given() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - go_to_block(11); - fund_alice_for_two_schedules(); - - let schedule = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, 1000 * UNITS, HDX, DAI, 100 * UNITS); - let start_execution_block = 22; - - //Act - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE.into()), - schedule.clone(), - Some(start_execution_block) - )); - let reserved_by_extrinsic = Currencies::reserved_balance(HDX, &ALICE.into()); - let injected_id = insert_schedule_into_storage(ALICE, schedule, Some(start_execution_block)); - - //Assert - assert_eq!(DCA::schedule_execution_block(injected_id), Some(25)); - assert_schedules_are_identical(0, injected_id, HDX, reserved_by_extrinsic); - }); - } - - /// Both schedules reserve the full budget, which exceeds ALICE's default balance. - fn fund_alice_for_two_schedules() { - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - 20_000 * UNITS - )); - } - - fn assert_schedules_are_identical( - extrinsic_id: ScheduleId, - injected_id: ScheduleId, - reserve_asset: AssetId, - reserved_by_extrinsic: Balance, - ) { - assert_eq!(injected_id, extrinsic_id + 1); - assert_eq!(DCA::schedules(injected_id), DCA::schedules(extrinsic_id)); - assert_eq!( - DCA::owner_of(AccountId::from(ALICE), injected_id), - DCA::owner_of(AccountId::from(ALICE), extrinsic_id) - ); - assert_eq!( - DCA::remaining_amounts(injected_id), - DCA::remaining_amounts(extrinsic_id) - ); - assert_eq!(DCA::retries_on_error(injected_id), DCA::retries_on_error(extrinsic_id)); - assert_eq!( - DCA::schedule_extra_gas(injected_id), - DCA::schedule_extra_gas(extrinsic_id) - ); - - let execution_block = DCA::schedule_execution_block(extrinsic_id).unwrap(); - assert_eq!(DCA::schedule_execution_block(injected_id), Some(execution_block)); - assert_eq!( - DCA::schedule_ids_per_block(execution_block).to_vec(), - vec![extrinsic_id, injected_id] - ); - - assert_reserved_balance!(&AccountId::from(ALICE), reserve_asset, 2 * reserved_by_extrinsic); - - let events = last_hydra_events(10); - assert!(events - .iter() - .any(|e| matches!(e, RuntimeEvent::DCA(pallet_dca::Event::Scheduled { id, .. }) if *id == injected_id))); - assert!(events.iter().any( - |e| matches!(e, RuntimeEvent::DCA(pallet_dca::Event::ExecutionPlanned { id, block, .. }) - if *id == injected_id && *block == execution_block) - )); - } -} - -mod aave_atoken { - use super::*; - use hydradx_runtime::DCA; - - // Snapshot at block 12309734, produced with: - // - // ./target/release/scraper save-storage --slim \ - // --uri wss://hydration.dotters.network \ - // --at 0x5bfd245dd5612800f2291cef550a5e3f76b569e6de4d52d1c6cb122e674d838e \ - // --pallet Omnipool Stableswap AssetRegistry EVM DynamicFees EmaOracle \ - // MultiTransactionPayment Tokens Balances EVMAccounts Ethereum \ - // EVMChainId HSM Router System Aura Timestamp DCA \ - // --path integration-tests/dca-snapshot - const PATH_TO_SNAPSHOT: &str = "dca-snapshot/SNAPSHOT_12309734"; - - //Ignored as snapshot too big - //To verify locally, download snapshot with command `./target/release/scraper save-storage --uri wss://paseo-rpc.play.hydration.cloud --at 0x3db005212a4ae320a2808c6813880b583dacbf7df60b0314420e88f4f2dfe989` - #[ignore] - #[test] - fn dca_should_work_when_atoken_is_sold() { - TestNet::reset(); - - hydra_live_ext(PATH_TO_SNAPSHOT).execute_with(|| { - //Arrange - assert_eq!(hydradx_runtime::System::block_number(), 5336); - - //Act - let schedule_id = 13883; - let schedule = DCA::schedules(schedule_id); - assert!(schedule.is_some()); - - hydradx_run_to_next_block(); - - //Assert that the DCA still alive - so not terminated - let schedule = DCA::schedules(schedule_id); - assert!(schedule.is_some()); - }); - } - - use frame_support::traits::OnInitialize; - - #[test] - fn dca_should_succeed_after_retry_when_insufficient_balance_error_due_to_off_by_one_error() { - TestNet::reset(); - - hydra_live_ext(PATH_TO_SNAPSHOT).execute_with(|| { - //Arrange - assert_eq!(hydradx_runtime::System::block_number(), 12309734); - let schedule_id = 30972; - assert!(DCA::schedules(schedule_id).is_some()); - - //Act 1: first attempt fails with InsufficientBalance and is retried - DCA::on_initialize(12309735); - assert_trade_failed_with_omnipool_insufficient_balance(schedule_id); - assert_eq!( - DCA::retries_on_error(schedule_id), - 1, - "first attempt should have been retried" - ); - let retry_block = - DCA::schedule_execution_block(schedule_id).expect("schedule should be replanned to a retry block"); - - //Act 2: simulate elapsed time so aave liquidity index drifts (rounding boundary moves) - let now = hydradx_runtime::Timestamp::get(); - hydradx_runtime::Timestamp::set_timestamp(now + 240_000); - - //Act 3: run DCA at the retry block - DCA::on_initialize(retry_block); - - //Assert: schedule still alive and retry counter reset (= the trade succeeded) - assert!(DCA::schedules(schedule_id).is_some(), "schedule must survive retry"); - assert_eq!( - DCA::retries_on_error(schedule_id), - 0, - "retry should have succeeded and reset the counter" - ); - }); - } - - #[test] - fn router_trading_limit_reached_should_be_retriable() { - use frame_support::traits::Contains; - assert!(hydradx_runtime::RetryOnErrorForDca::contains( - &pallet_route_executor::Error::::TradingLimitReached.into() - )); - } - - // Snapshot at block 13260776, produced with the same scraper command as above, - // --at 0x798bc20aeb759a30dd97aafdab03346ff463cbc17e776216d171a8b3ad6411d6 - const PATH_TO_HSM_WINDDOWN_SNAPSHOT: &str = "dca-snapshot/SNAPSHOT_13260776"; - - // replays mainnet block 13260777: hsm wind-down schedule 33794 (sUSDe->HOLLAR->aUSDT) failed - // with router TradingLimitReached and was terminated instead of retried - #[test] - fn dca_should_retry_when_router_trading_limit_reached() { - TestNet::reset(); - - hydra_live_ext(PATH_TO_HSM_WINDDOWN_SNAPSHOT).execute_with(|| { - //Arrange - assert_eq!(hydradx_runtime::System::block_number(), 13260776); - let schedule_id = 33794; - assert!(DCA::schedules(schedule_id).is_some()); - // on mainnet the timestamp inherent runs after on_initialize — keep the parent timestamp - hydradx_runtime::System::set_block_number(13260777); - - // the slim snapshot strips schedule 33812's owner, so replay its trade by hand: - // the aave hop moves pool-111 shares out of the aHUSDT contract account, then the - // stableswap hop removes liquidity from pool 111 right before 33794 executes - let ahusdt: sp_runtime::AccountId32 = - hex_literal::hex!("455448001806860d27ee903c1ec7586d4f7d598d7591f1240000000000000000").into(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ahusdt, - 111, - -22_133_969_015_170_432_881i128, - )); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - BOB.into(), - 111, - 22_133_969_015_170_432_881i128, - )); - assert_ok!(Router::sell( - RuntimeOrigin::signed(BOB.into()), - 111, - 222, - 22_133_969_015_170_432_881u128, - 0, - vec![Trade { - pool: PoolType::Stableswap(111), - asset_in: 111, - asset_out: 222, - }] - .try_into() - .unwrap(), - )); - // exact hollar amount of the mainnet swap — the replayed state matches - assert_eq!(Currencies::free_balance(222, &BOB.into()), 22_567_968_483_370_805_906); - - //Act - DCA::on_initialize(13260777); - - //Assert: trade failed exactly like mainnet, but got retried instead of terminated - assert_trade_failed_with_router_trading_limit_reached(schedule_id); - assert!( - DCA::schedules(schedule_id).is_some(), - "schedule must be retried, not terminated" - ); - assert_eq!(DCA::retries_on_error(schedule_id), 1); - }); - } - - fn assert_trade_failed_with_router_trading_limit_reached(schedule_id: u32) { - let expected: sp_runtime::DispatchError = pallet_route_executor::Error::::TradingLimitReached.into(); - let events = last_hydra_events(20); - let found = events.iter().any(|e| { - matches!( - e, - RuntimeEvent::DCA(pallet_dca::Event::TradeFailed { id, error, .. }) - if *id == schedule_id && *error == expected - ) - }); - assert!( - found, - "expected TradeFailed event with router::TradingLimitReached for schedule {schedule_id}" - ); - } - - fn assert_trade_failed_with_omnipool_insufficient_balance(schedule_id: u32) { - let expected: sp_runtime::DispatchError = pallet_omnipool::Error::::InsufficientBalance.into(); - let events = last_hydra_events(20); - let found = events.iter().any(|e| { - matches!( - e, - RuntimeEvent::DCA(pallet_dca::Event::TradeFailed { id, error, .. }) - if *id == schedule_id && *error == expected - ) - }); - assert!( - found, - "expected TradeFailed event with omnipool::InsufficientBalance for schedule {schedule_id}" - ); - } -} - -fn create_xyk_pool_with_amounts(asset_a: u32, amount_a: u128, asset_b: u32, amount_b: u128) { - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - DAVE.into(), - asset_a, - amount_a as i128, - )); - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - DAVE.into(), - asset_b, - amount_b as i128, - )); - - assert_ok!(XYK::create_pool( - RuntimeOrigin::signed(DAVE.into()), - asset_a, - amount_a, - asset_b, - amount_b, - )); -} - -pub fn create_schedule(owner: [u8; 32], schedule1: Schedule) { - assert_ok!(DCA::schedule(RuntimeOrigin::signed(owner.into()), schedule1, None)); -} - -/// Stores a schedule by writing exactly the state the `schedule` extrinsic writes. -/// -/// Buy orders can no longer be scheduled, but buy schedules stored before that restriction keep -/// executing, so their execution still needs coverage. Fidelity against the extrinsic is pinned by -/// `storage_injected_schedule_should_match_extrinsic_created_schedule`. -pub fn insert_schedule_into_storage( - owner: [u8; 32], - schedule: Schedule, - start_execution_block: Option, -) -> ScheduleId { - let who: AccountId = owner.into(); - assert_eq!(schedule.owner, who, "owner must match the schedule owner"); - - let asset_in = schedule.order.get_asset_in(); - let route = schedule.order.get_route_or_default::(); - let amount_in = match schedule.order { - Order::Sell { amount_in, .. } => amount_in, - Order::Buy { amount_out, .. } => Router::calculate_expected_amount_in(&route, amount_out).unwrap(), - }; - let transaction_fee = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - - let reserve_amount = if schedule.is_rolling() { - amount_in.saturating_add(transaction_fee).saturating_mul(2) - } else { - schedule.total_amount - }; - - let schedule_id = pallet_dca::ScheduleIdSequencer::::mutate(|current_id| { - let schedule_id = *current_id; - *current_id += 1; - schedule_id - }); - - pallet_dca::Schedules::::insert(schedule_id, &schedule); - pallet_dca::ScheduleOwnership::::insert(&who, schedule_id, ()); - pallet_dca::RemainingAmounts::::insert(schedule_id, reserve_amount); - pallet_dca::RetriesOnError::::insert(schedule_id, 0); - - assert_ok!(Currencies::reserve_named( - &NamedReserveId::get(), - asset_in, - &who, - reserve_amount - )); - - let execution_block = first_execution_block(start_execution_block); - pallet_dca::ScheduleIdsPerBlock::::mutate(execution_block, |schedule_ids| { - schedule_ids.try_push(schedule_id).expect("execution block is full"); - }); - pallet_dca::ScheduleExecutionBlock::::insert(schedule_id, execution_block); - - System::deposit_event(RuntimeEvent::DCA(pallet_dca::Event::Scheduled { - id: schedule_id, - who: who.clone(), - period: schedule.period, - total_amount: schedule.total_amount, - order: schedule.order, - })); - System::deposit_event(RuntimeEvent::DCA(pallet_dca::Event::ExecutionPlanned { - id: schedule_id, - who, - block: execution_block, - })); - - schedule_id -} - -/// Mirrors `pallet_dca::Pallet::get_first_execution_block`. -fn first_execution_block(start_execution_block: Option) -> BlockNumber { - let next_block = System::block_number().saturating_add(2); - match start_execution_block { - Some(block) => { - let number = next_block.max(block); - match number % 5 { - 0 => number, - remainder => number.saturating_add(5 - remainder), - } - } - None => next_block, - } -} - -fn schedule_fake_with_buy_order( - pool: PoolType, - asset_in: AssetId, - asset_out: AssetId, - amount: Balance, - budget: Balance, -) -> Schedule { - Schedule { - owner: AccountId::from(ALICE), - period: 5u32, - total_amount: budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Buy { - asset_in, - asset_out, - amount_out: amount, - max_amount_in: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool, - asset_in, - asset_out, - }]), - }, - } -} -fn schedule_fake_with_buy_order_with_route( - asset_in: AssetId, - asset_out: AssetId, - amount: Balance, - budget: Balance, - route: Vec>, -) -> Schedule { - Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Buy { - asset_in, - asset_out, - amount_out: amount, - max_amount_in: Balance::MAX, - route: create_bounded_vec(route), - }, - } -} - -pub fn schedule_fake_with_sell_order( - owner: [u8; 32], - pool: PoolType, - total_amount: Balance, - asset_in: AssetId, - asset_out: AssetId, - amount: Balance, -) -> Schedule { - schedule_fake_with_sell_order_with_route( - owner, - total_amount, - asset_in, - asset_out, - amount, - vec![Trade { - pool, - asset_in, - asset_out, - }], - ) -} - -fn schedule_fake_with_sell_order_with_route( - owner: [u8; 32], - total_amount: Balance, - asset_in: AssetId, - asset_out: AssetId, - amount: Balance, - route: Vec>, -) -> Schedule { - Schedule { - owner: AccountId::from(owner), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(15)), - order: Order::Sell { - asset_in, - asset_out, - amount_in: amount, - min_amount_out: Balance::MIN, - route: create_bounded_vec(route), - }, - } -} - -fn set_alice_lrna_balance(alice_init_lrna_balance: Balance) { - assert_ok!(Tokens::set_balance( - RawOrigin::Root.into(), - ALICE.into(), - LRNA, - alice_init_lrna_balance, - 0 - )); -} - -pub fn create_bounded_vec( - trades: Vec>, -) -> BoundedVec, ConstU32<{ MAX_NUMBER_OF_TRADES }>> { - let bounded_vec: BoundedVec, sp_runtime::traits::ConstU32<{ MAX_NUMBER_OF_TRADES }>> = - trades.try_into().unwrap(); - bounded_vec -} - -pub fn init_omnipol() { - let native_price = FixedU128::from_float(0.5); - let stable_price = FixedU128::from_float(0.7); - let acc = Omnipool::protocol_account(); - - let stable_amount: Balance = 5_000_000_000_000_000_000_000u128; - let native_amount: Balance = 5_000_000_000_000_000_000_000u128; - assert_ok!(Tokens::set_balance( - RawOrigin::Root.into(), - acc.clone(), - DAI, - stable_amount, - 0 - )); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - acc, - HDX, - native_amount as i128, - )); - - assert_ok!(hydradx_runtime::Omnipool::add_token( - hydradx_runtime::RuntimeOrigin::root(), - HDX, - native_price, - Permill::from_percent(60), - hydradx_runtime::Omnipool::protocol_account(), - )); - - assert_ok!(hydradx_runtime::Omnipool::add_token( - hydradx_runtime::RuntimeOrigin::root(), - DAI, - stable_price, - Permill::from_percent(60), - hydradx_runtime::Omnipool::protocol_account(), - )); - - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - Treasury::account_id(), - TREASURY_ACCOUNT_INIT_BALANCE, - )); - - set_zero_reward_for_referrals(HDX); - set_zero_reward_for_referrals(DAI); -} - -pub fn init_omnipool_with_oracle_for_block_10() { - init_omnipol(); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - go_to_block(10); - do_trade_to_populate_oracle(DAI, HDX, UNITS); -} - -fn do_trade_to_populate_oracle(asset_1: AssetId, asset_2: AssetId, amount: Balance) { - assert_ok!(Tokens::set_balance( - RawOrigin::Root.into(), - CHARLIE.into(), - LRNA, - 1000000000000 * UNITS, - 0, - )); - - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(CHARLIE.into()), - LRNA, - asset_1, - amount, - Balance::MIN - )); - - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(CHARLIE.into()), - LRNA, - asset_2, - amount, - Balance::MIN - )); -} - -pub fn run_to_block(from: BlockNumber, to: BlockNumber) { - for b in from..=to { - do_trade_to_populate_oracle(DAI, HDX, UNITS); - go_to_block(b); - } -} - -fn retry_block(current_block: BlockNumber, retries_before: u32) -> BlockNumber { - current_block + hydradx_traits::oracle::OraclePeriod::Short.as_period() as BlockNumber * 2u32.pow(retries_before) -} - -pub fn check_if_no_failed_events() { - let failed_events = count_failed_trade_events(); - assert_eq!(0, failed_events); -} - -pub fn check_if_dcas_completed_without_failed_or_terminated_events() { - let failed_events = count_failed_trade_events(); - let terminated_events = count_terminated_trade_events(); - let completed_events = count_completed_event(); - assert_eq!( - 0, failed_events, - "There has been some dca::TradeFailed events, but not expected" - ); - assert_eq!( - 0, terminated_events, - "There has been some dca::Terminated events, but not expected" - ); - assert!(completed_events > 0, "There has been no dca::Completed events"); -} - -pub fn get_last_schedule_ids_from_trade_executed_events() -> Vec { - let last_events: Vec = last_hydra_events(1000); - let mut schedule_ids = vec![]; - - for event in last_events { - let e = event.clone(); - if let RuntimeEvent::DCA(pallet_dca::Event::TradeExecuted { id, .. }) = e { - schedule_ids.push(id); - } - } - - schedule_ids -} - -pub fn count_failed_trade_events() -> u32 { - count_dca_event!(pallet_dca::Event::TradeFailed { .. }) -} - -pub fn count_trade_executed_events() -> u32 { - count_dca_event!(pallet_dca::Event::TradeExecuted { .. }) -} - -pub fn count_terminated_trade_events() -> u32 { - count_dca_event!(pallet_dca::Event::Terminated { .. }) -} - -pub fn count_completed_event() -> u32 { - count_dca_event!(pallet_dca::Event::Completed { .. }) -} -#[macro_export] -macro_rules! count_dca_event { - ($pattern:pat) => {{ - let last_events: Vec = last_hydra_events(100000); - - let mut counter: u32 = 0; - for event in last_events { - let e = event.clone(); - if matches!(e, RuntimeEvent::DCA($pattern)) { - counter += 1; - } - } - - counter - }}; -} - -pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { - let initial_liquidity = 1_000_000_000_000_000_000_000u128; - - let mut initial: Vec::AssetId>> = vec![]; - let mut asset_ids: Vec<::AssetId> = Vec::new(); - for idx in 0u32..MAX_ASSETS_IN_POOL { - let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = AssetRegistry::register_sufficient_asset( - None, - Some(name.try_into().unwrap()), - AssetKind::Token, - 1u128, - Some(b"xDUM".to_vec().try_into().unwrap()), - Some(18u8), - None, - None, - )?; - - asset_ids.push(asset_id); - Currencies::update_balance( - RuntimeOrigin::root(), - AccountId::from(BOB), - asset_id, - initial_liquidity as i128, - )?; - initial.push(AssetAmount::new(asset_id, initial_liquidity)); - } - let pool_id = AssetRegistry::register_sufficient_asset( - None, - Some(b"pool".to_vec().try_into().unwrap()), - AssetKind::Token, - 1u128, - None, - None, - None, - None, - )?; - - let amplification = 100u16; - let fee = Permill::from_percent(1); - - let asset_in: AssetId = *asset_ids.last().unwrap(); - let asset_out: AssetId = *asset_ids.first().unwrap(); - - Stableswap::create_pool( - RuntimeOrigin::root(), - pool_id, - BoundedVec::truncate_from(asset_ids), - amplification, - fee, - )?; - - Stableswap::add_assets_liquidity( - RuntimeOrigin::signed(BOB.into()), - pool_id, - BoundedVec::truncate_from(initial), - Balance::zero(), - )?; - - Ok((pool_id, asset_in, asset_out)) -} - -pub fn init_stableswap_with_three_assets_having_different_decimals( -) -> Result<(AssetId, AssetId, AssetId), DispatchError> { - let initial_liquidity = 1_000_000_000_000_000u128; - let liquidity_added = 300_000_000_000_000u128; - - let mut initial: Vec::AssetId>> = vec![]; - let mut added_liquidity: Vec::AssetId>> = vec![]; - - let mut asset_ids: Vec<::AssetId> = Vec::new(); - let decimals_for_each_asset = [12u8, 6u8, 6u8]; - for idx in 0u32..3 { - let name: Vec = idx.to_ne_bytes().to_vec(); - - let asset_id = AssetRegistry::register_sufficient_asset( - None, - Some(name.try_into().unwrap()), - AssetKind::Token, - 1u128, - Some(b"xDUM".to_vec().try_into().unwrap()), - Some(decimals_for_each_asset[idx as usize]), - None, - None, - )?; - - asset_ids.push(asset_id); - Currencies::update_balance( - RuntimeOrigin::root(), - AccountId::from(BOB), - asset_id, - 1_000_000_000_000_000i128, - )?; - Currencies::update_balance( - RuntimeOrigin::root(), - AccountId::from(CHARLIE), - asset_id, - 1_000_000_000_000_000_000_000i128, - )?; - initial.push(AssetAmount::new(asset_id, initial_liquidity)); - added_liquidity.push(AssetAmount::new(asset_id, liquidity_added)); - } - let pool_id = AssetRegistry::register_sufficient_asset( - None, - Some(b"pool".to_vec().try_into().unwrap()), - AssetKind::Token, - 1u128, - None, - None, - None, - None, - )?; - - let amplification = 100u16; - let fee = Permill::from_percent(1); - - let asset_in: AssetId = asset_ids[1]; - let asset_out: AssetId = asset_ids[2]; - - Stableswap::create_pool( - RuntimeOrigin::root(), - pool_id, - BoundedVec::truncate_from(asset_ids), - amplification, - fee, - )?; - - Stableswap::add_assets_liquidity( - RuntimeOrigin::signed(BOB.into()), - pool_id, - BoundedVec::truncate_from(initial), - Balance::zero(), - )?; - - Ok((pool_id, asset_in, asset_out)) -} - -pub fn add_dot_as_payment_currency() { - add_dot_as_payment_currency_with_details(1000 * UNITS, FixedU128::from_rational(10, 100)); -} - -fn add_dot_as_payment_currency_with_details(amount: Balance, price: FixedU128) { - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - DOT, - amount as i128, - )); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - hydradx_runtime::RuntimeOrigin::root(), - DOT, - FixedU128::from_rational(1, 100000), - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - DOT, - price, - Permill::from_percent(100), - AccountId::from(BOB), - )); - - //crate::dca::do_trade_to_populate_oracle(DOT, HDX, UNITS); -} - -pub(crate) mod extra_gas_erc20 { - use super::*; - - use hydradx_runtime::{FixedU128, MultiTransactionPayment, Router}; - - use frame_support::assert_ok; - use hydradx_runtime::EmaOracle; - use hydradx_runtime::{Currencies, Dispatcher, EVMAccounts, Runtime, RuntimeEvent, RuntimeOrigin, DCA}; - use primitives::constants::chain::OMNIPOOL_SOURCE; - use primitives::Balance; - use sp_runtime::Permill; - - #[test] - fn dca_succeeds_after_extra_gas_increased_due_to_out_of_gas_error() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - - let evm_address = EVMAccounts::evm_address(&Router::router_account()); - let contract = deploy_conditional_gas_eater(evm_address, 400_000, crate::erc20::deployer()); - let erc20 = crate::erc20::bind_erc20(contract); - assert_ok!(EmaOracle::add_oracle( - RuntimeOrigin::root(), - OMNIPOOL_SOURCE, - (LRNA, erc20) - )); - - //Add new erc20 to omnipool - let bal = Currencies::free_balance(erc20, &ALICE.into()); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(ALICE.into()), - pallet_omnipool::Pallet::::protocol_account(), - erc20, - bal / 10, - )); - assert_ok!(pallet_omnipool::Pallet::::add_token( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200), - Permill::from_percent(30), - ALICE.into(), - )); - - assert_ok!(MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200) - )); - - hydradx_run_to_block(11); - - let schedule_id = create_schedule_with_onchain_route(erc20, 0, 200000 * UNITS, 0, Some(3)); - - let alice_init_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - hydradx_run_to_block(13); - - // Assert that extra gas was increased in one retry - assert_eq!(DCA::retries_on_error(schedule_id), 1); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 333_333); - trade_failed_with_evm_out_of_gas_error(schedule_id); - assert_eq!(1, count_failed_trade_events()); - assert_eq!(0, count_trade_executed_events()); - let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - assert_eq!(alice_init_hdx_balance, alice_hdx_balance); - - let retry_1 = retry_block(13, 0); - hydradx_run_to_block(retry_1); - assert_eq!(Dispatcher::extra_gas(), 0); - - //Assert that trade finally succeeded - assert_eq!(DCA::retries_on_error(schedule_id), 0); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 333_333); - assert_trade_executed_succesfully(schedule_id); - assert_eq!(1, count_failed_trade_events()); - assert_eq!(1, count_trade_executed_events()); - let alice_hdx_balance_after_retry = Currencies::free_balance(HDX, &ALICE.into()); - assert!(alice_hdx_balance_after_retry > alice_hdx_balance); - - hydradx_run_to_block(retry_1 + hydradx_runtime::MinimalPeriod::get()); - assert_eq!(Dispatcher::extra_gas(), 0); - - //Assert that trade succeeded in the next run too - assert_eq!(DCA::retries_on_error(schedule_id), 0); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 333_333); - assert_eq!(1, count_failed_trade_events()); - assert_eq!(2, count_trade_executed_events()); - let alice_final_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - assert!(alice_final_hdx_balance > alice_hdx_balance_after_retry); - }); - } - - #[test] - fn dca_retry_includes_extra_gas_in_fee_with_evm_token() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - - let evm_address = EVMAccounts::evm_address(&Router::router_account()); - let contract = deploy_conditional_gas_eater(evm_address, 400_000, crate::erc20::deployer()); - let erc20 = crate::erc20::bind_erc20(contract); - assert_ok!(EmaOracle::add_oracle( - RuntimeOrigin::root(), - OMNIPOOL_SOURCE, - (LRNA, erc20) - )); - - //Add new erc20 to omnipool - let bal = Currencies::free_balance(erc20, &ALICE.into()); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(ALICE.into()), - pallet_omnipool::Pallet::::protocol_account(), - erc20, - bal / 10, - )); - assert_ok!(pallet_omnipool::Pallet::::add_token( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200), - Permill::from_percent(30), - ALICE.into(), - )); - - assert_ok!(MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200) - )); - - hydradx_run_to_block(11); - - let sell_amount = 200000 * UNITS; - let schedule_id = create_schedule_with_onchain_route(erc20, 0, sell_amount, 0, Some(3)); - - // Get the schedule to access the order - let schedule = DCA::schedules(schedule_id).expect("Schedule should exist"); - - let alice_init_balance = Currencies::free_balance(erc20, &ALICE.into()); - - // Run to block 13 - first execution fails with out of gas - hydradx_run_to_block(13); - - assert_eq!(DCA::retries_on_error(schedule_id), 1); - let expected_extra_gas = 333_333; // MAX_EXTRA_GAS / 3 - assert_eq!(DCA::schedule_extra_gas(schedule_id), expected_extra_gas); - - let base_fee = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - let fee_with_extra = DCA::get_transaction_fee(&schedule.order, Some(schedule_id)).unwrap(); - - assert!( - fee_with_extra > base_fee, - "Fee with extra gas ({fee_with_extra}) should be > base fee ({base_fee})" - ); - - // The first attempt charged base fee (before extra gas was added) - let balance_after_first_attempt = Currencies::free_balance(erc20, &ALICE.into()); - let first_fee_charged = alice_init_balance - balance_after_first_attempt; - assert_eq!(first_fee_charged, base_fee); - - let alice_balance_before_retry = Currencies::free_balance(erc20, &ALICE.into()); - - hydradx_run_to_block(retry_block(13, 0)); - - let fee_with_extra = DCA::get_transaction_fee(&schedule.order, Some(schedule_id)).unwrap(); - - // Verify - assert_eq!(DCA::retries_on_error(schedule_id), 0); - assert_trade_executed_succesfully(schedule_id); - assert_eq!(DCA::schedule_extra_gas(schedule_id), expected_extra_gas); - - // The retry should charge fee with extra gas - let balance_after_retry = Currencies::free_balance(erc20, &ALICE.into()); - let total_fees_charged = alice_balance_before_retry - balance_after_retry - sell_amount; - assert_eq!(fee_with_extra, total_fees_charged); - }); - } - - #[test] - fn extra_gas_keep_incrementing_multiple_times_till_successfull() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - - let evm_address = EVMAccounts::evm_address(&Router::router_account()); - let contract = deploy_conditional_gas_eater(evm_address, 800_000, crate::erc20::deployer()); - let erc20 = crate::erc20::bind_erc20(contract); - assert_ok!(EmaOracle::add_oracle( - RuntimeOrigin::root(), - OMNIPOOL_SOURCE, - (LRNA, erc20) - )); - - //Add new erc20 to omnipool - let bal = Currencies::free_balance(erc20, &ALICE.into()); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(ALICE.into()), - pallet_omnipool::Pallet::::protocol_account(), - erc20, - bal / 10, - )); - assert_ok!(pallet_omnipool::Pallet::::add_token( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200), - Permill::from_percent(30), - ALICE.into(), - )); - - assert_ok!(MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200) - )); - - hydradx_run_to_block(11); - - let schedule_id = create_schedule_with_onchain_route(erc20, 0, 200000 * UNITS, 0, Some(3)); - - let alice_init_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - hydradx_run_to_block(13); - - // Assert that extra gas was increased in one retry - assert_eq!(DCA::retries_on_error(schedule_id), 1); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 333_333); - trade_failed_with_evm_out_of_gas_error(schedule_id); - assert_eq!(1, count_failed_trade_events()); - assert_eq!(0, count_trade_executed_events()); - let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - assert_eq!(alice_init_hdx_balance, alice_hdx_balance); - - let retry_1 = retry_block(13, 0); - hydradx_run_to_block(retry_1); - - //It fails again as the gas increased was still not enough - assert_eq!(DCA::retries_on_error(schedule_id), 2); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 666_666); - assert_eq!(2, count_failed_trade_events()); - assert_eq!(0, count_trade_executed_events()); - let alice_hdx_balance_after_retry = Currencies::free_balance(HDX, &ALICE.into()); - assert_eq!(alice_hdx_balance_after_retry, alice_init_hdx_balance); - - hydradx_run_to_block(retry_block(retry_1, 1)); - - //Assert that trade succeeded in the next run - assert_eq!(DCA::retries_on_error(schedule_id), 0); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 666_666); - assert_trade_executed_succesfully(schedule_id); - assert_eq!(2, count_failed_trade_events()); - assert_eq!(1, count_trade_executed_events()); - let alice_final_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - assert!(alice_final_hdx_balance > alice_hdx_balance_after_retry); - }); - } - - #[test] - fn dca_with_extra_gas_should_completed_and_clear_up() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - - let evm_address = EVMAccounts::evm_address(&Router::router_account()); - let contract = deploy_conditional_gas_eater(evm_address, 400_000, crate::erc20::deployer()); - let erc20 = crate::erc20::bind_erc20(contract); - assert_ok!(EmaOracle::add_oracle( - RuntimeOrigin::root(), - OMNIPOOL_SOURCE, - (LRNA, erc20) - )); - - //Add new erc20 to omnipool - let bal = Currencies::free_balance(erc20, &ALICE.into()); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(ALICE.into()), - pallet_omnipool::Pallet::::protocol_account(), - erc20, - bal / 10, - )); - assert_ok!(pallet_omnipool::Pallet::::add_token( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200), - Permill::from_percent(30), - ALICE.into(), - )); - - assert_ok!(MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200) - )); - - hydradx_run_to_block(11); - let _amount_in = 200000 * UNITS; - let schedule_id = create_schedule_with_onchain_route(erc20, 0, 200000 * UNITS, 500000 * UNITS, Some(3)); - - let alice_init_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - hydradx_run_to_block(13); - - // Assert that extra gas was increased in one retry - assert_eq!(DCA::retries_on_error(schedule_id), 1); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 333_333); - trade_failed_with_evm_out_of_gas_error(schedule_id); - assert_eq!(1, count_failed_trade_events()); - assert_eq!(0, count_trade_executed_events()); - let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - assert_eq!(alice_init_hdx_balance, alice_hdx_balance); - - let retry_1 = retry_block(13, 0); - hydradx_run_to_block(retry_1); - - //Assert that trade finally succeeded - assert_eq!(DCA::retries_on_error(schedule_id), 0); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 333_333); - assert_trade_executed_succesfully(schedule_id); - assert_eq!(1, count_failed_trade_events()); - assert_eq!(1, count_trade_executed_events()); - let alice_hdx_balance_after_retry = Currencies::free_balance(HDX, &ALICE.into()); - assert!(alice_hdx_balance_after_retry > alice_hdx_balance); - - hydradx_run_to_block(retry_1 + hydradx_runtime::MinimalPeriod::get()); - - //Assert that trade succeeded in the next run too - assert_eq!(DCA::retries_on_error(schedule_id), 0); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 333_333); - assert_eq!(1, count_failed_trade_events()); - assert_eq!(2, count_trade_executed_events()); - let alice_hdx_balance_after_2nd_run = Currencies::free_balance(HDX, &ALICE.into()); - assert!(alice_hdx_balance_after_2nd_run > alice_hdx_balance_after_retry); - - hydradx_run_to_block(retry_1 + 2 * hydradx_runtime::MinimalPeriod::get()); - - //Assert that trade succeeded in the next run too - assert_eq!(DCA::retries_on_error(schedule_id), 0); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 0); - assert_eq!(1, count_failed_trade_events()); - assert_eq!(3, count_trade_executed_events()); - let alice_final_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - assert!(alice_final_hdx_balance > alice_hdx_balance_after_2nd_run); - assert_eq!(1, count_completed_event()); - }); - } - - #[test] - fn subcall_gas_exhaustion_should_be_detected_and_retried() { - // This test reproduces the AAVE scenario where: - // 1. Main contract makes subcall to helper contract - // 2. Subcall gets 63/64 of gas (EIP-150) - // 3. Subcall runs out of gas and returns false - // 4. Main contract detects failure and reverts with empty message - // 5. Our detector should catch this as OutOfGas (gas_used > 90%) - - TestNet::reset(); - - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - - let evm_address = EVMAccounts::evm_address(&Router::router_account()); - - // Deploy contract with subcall that will exhaust gas - // Use 400_000 gas to ensure we hit >90% threshold - let gas_to_waste: u64 = 400_000; - let contract = deploy_subcall_gas_exhaustion_token(evm_address, gas_to_waste, crate::erc20::deployer()); - let erc20 = crate::erc20::bind_erc20(contract); - - // Add to omnipool with oracle - assert_ok!(EmaOracle::add_oracle( - hydradx_runtime::RuntimeOrigin::root(), - OMNIPOOL_SOURCE, - (LRNA, erc20), - )); - - //Add new erc20 to omnipool - let bal = Currencies::free_balance(erc20, &ALICE.into()); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(ALICE.into()), - pallet_omnipool::Pallet::::protocol_account(), - erc20, - bal / 10, - )); - assert_ok!(pallet_omnipool::Pallet::::add_token( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200), - Permill::from_percent(30), - ALICE.into(), - )); - - assert_ok!(MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200) - )); - - hydradx_run_to_block(11); - - let amount_in = 200000 * UNITS; - let schedule_id = create_schedule_with_onchain_route( - erc20, - HDX, - amount_in, - 500000 * UNITS, - Some(3), // Allow retries - ); - - // First execution attempt - should fail with subcall gas exhaustion - hydradx_run_to_block(13); - - //Assert - assert_eq!( - DCA::retries_on_error(schedule_id), - 1, - "Should have 1 retry after subcall gas exhaustion" - ); - assert_eq!( - DCA::schedule_extra_gas(schedule_id), - 333_333, - "Extra gas should be increased after first failure" - ); - - trade_failed_with_evm_out_of_gas_error(schedule_id); - assert_eq!(count_failed_trade_events(), 1); - assert_eq!(count_trade_executed_events(), 0); - - // Retry with extra gas - should succeed - let retry_1 = retry_block(13, 0); - hydradx_run_to_block(retry_1); - - //Assert - assert_eq!( - DCA::retries_on_error(schedule_id), - 0, - "Retries should reset to 0 after success" - ); - assert_eq!( - DCA::schedule_extra_gas(schedule_id), - 333_333, - "Extra gas should persist for future executions" - ); - - assert_trade_executed_succesfully(schedule_id); - assert_eq!( - count_failed_trade_events(), - 1, - "Should still have 1 failed event from first attempt" - ); - assert_eq!( - count_trade_executed_events(), - 1, - "Should have 1 successful trade after retry" - ); - - // Act - Next scheduled trade - should execute successfully without retries - hydradx_run_to_block(retry_1 + hydradx_runtime::MinimalPeriod::get()); - - //Assert - assert_eq!( - count_trade_executed_events(), - 2, - "Should have 2 successful trades total" - ); - }); - } - - #[test] - fn dca_retries_when_fee_payment_fails_with_out_of_gas() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - - // Deploy ConditionalGasEater with FeeReceiver address (not router) - // This makes fee transfers trigger gas eating - let fee_receiver = ::FeeReceiver::get(); - let fee_receiver_evm = EVMAccounts::evm_address(&fee_receiver); - let contract = deploy_conditional_gas_eater(fee_receiver_evm, 400_000, crate::erc20::deployer()); - let erc20 = crate::erc20::bind_erc20(contract); - - assert_ok!(EmaOracle::add_oracle( - RuntimeOrigin::root(), - OMNIPOOL_SOURCE, - (LRNA, erc20) - )); - - // Add new erc20 to omnipool - let bal = Currencies::free_balance(erc20, &ALICE.into()); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(ALICE.into()), - pallet_omnipool::Pallet::::protocol_account(), - erc20, - bal / 10, - )); - assert_ok!(pallet_omnipool::Pallet::::add_token( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200), - Permill::from_percent(30), - ALICE.into(), - )); - - // Add as transaction fee currency (fees go through transfer path) - assert_ok!(MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - erc20, - FixedU128::from_rational(1, 200) - )); - - hydradx_run_to_block(11); - - let schedule_id = create_schedule_with_onchain_route(erc20, HDX, 200000 * UNITS, 0, Some(3)); - - let alice_init_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - hydradx_run_to_block(13); - - // Assert: fee payment failed with EvmOutOfGas, extra gas increased, schedule retried - assert_eq!(DCA::retries_on_error(schedule_id), 1); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 333_333); - trade_failed_with_evm_out_of_gas_error(schedule_id); - assert_eq!(1, count_failed_trade_events()); - assert_eq!(0, count_trade_executed_events()); - - // Balance unchanged because fee payment failed before trade - let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - assert_eq!(alice_init_hdx_balance, alice_hdx_balance); - - // Retry with extra gas - should succeed - hydradx_run_to_block(retry_block(13, 0)); - - // Assert: trade finally succeeded - assert_eq!(DCA::retries_on_error(schedule_id), 0); - assert_eq!(DCA::schedule_extra_gas(schedule_id), 333_333); - assert_trade_executed_succesfully(schedule_id); - assert_eq!(1, count_failed_trade_events()); - assert_eq!(1, count_trade_executed_events()); - let alice_hdx_balance_after_retry = Currencies::free_balance(HDX, &ALICE.into()); - assert!(alice_hdx_balance_after_retry > alice_hdx_balance); - }); - } - - fn create_schedule_with_onchain_route( - asset_in: AssetId, - asset_out: AssetId, - amount_in: Balance, - total_amount: Balance, - max_retries: Option, - ) -> u32 { - use hydradx_runtime::Router; - use hydradx_traits::router::{AssetPair, RouteProvider}; - - let route = Router::get_route(AssetPair { asset_in, asset_out }); - - let schedule = Schedule { - owner: ALICE.into(), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount, - max_retries, - stability_threshold: None, - slippage: Some(Permill::from_percent(90)), - order: Order::Sell { - asset_in, - asset_out, - amount_in, - min_amount_out: Balance::MIN, - route, // Use the BoundedVec directly from Router - }, - }; - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE.into()), schedule, None)); - 0 // schedule_id - } - - /// Deploy ConditionalGasEater contract with constructor parameters - /// - /// # Arguments - /// * `router_address` - EVM address of the router pallet account - /// * `gas_to_waste` - Amount of gas to waste on transfers to the router - /// * `deployer` - EVM address of the contract deployer - /// - /// # Returns - /// The deployed contract's EVM address - pub(crate) fn deploy_conditional_gas_eater( - router_address: EvmAddress, - gas_to_waste: u64, - deployer: EvmAddress, - ) -> EvmAddress { - use ethabi::{encode, Token}; - - // Get base bytecode from compiled artifact - let mut bytecode = crate::utils::contracts::get_contract_bytecode("ConditionalGasEater"); - - // Encode constructor parameters: (address _routerAddress, uint256 _gasToWaste) - let constructor_params = encode(&[Token::Address(router_address), Token::Uint(gas_to_waste.into())]); - - // Append encoded constructor params to bytecode - bytecode.extend(constructor_params); - - // Deploy contract with complete bytecode - crate::utils::contracts::deploy_contract_code(bytecode, deployer) - } - - fn trade_failed_with_evm_out_of_gas_error(schedule_id: u32) { - let events = last_hydra_events(20); - let has_out_of_gas_event = events.iter().any(|e| { - matches!(e, - RuntimeEvent::DCA(pallet_dca::Event::TradeFailed { id, error, .. }) - if *id == schedule_id && *error == pallet_dispatcher::Error::::EvmOutOfGas.into() - ) - }); - assert!( - has_out_of_gas_event, - "Expected TradeFailed event with EvmOutOfGas error" - ); - } - - fn assert_trade_executed_succesfully(schedule_id: u32) { - let events = last_hydra_events(20); - let has_trade_executed = events.iter().any(|e| { - matches!(e, - RuntimeEvent::DCA(pallet_dca::Event::TradeExecuted { id, .. }) - if *id == schedule_id - ) - }); - assert!(has_trade_executed, "Expected TradeExecuted event after retry"); - } - - /// Deploy SubcallGasExhaustionToken contract with constructor parameters - /// - /// This contract mimics AAVE's behavior where: - /// - Main contract makes subcall to helper GasWaster contract - /// - Subcall gets 63/64 of remaining gas (EIP-150) - /// - When subcall exhausts gas, main contract reverts with empty message - /// - /// # Arguments - /// * `router_address` - EVM address of the router pallet account - /// * `gas_to_waste` - Amount of gas to waste in the subcall - /// * `deployer` - EVM address of the contract deployer - /// - /// # Returns - /// The deployed contract's EVM address - fn deploy_subcall_gas_exhaustion_token( - router_address: EvmAddress, - gas_to_waste: u64, - deployer: EvmAddress, - ) -> EvmAddress { - use ethabi::{encode, Token}; - - // Get base bytecode from compiled artifact - let mut bytecode = crate::utils::contracts::get_contract_bytecode("SubcallGasExhaustionToken"); - - // Encode constructor parameters: (address _routerAddress, uint256 _gasToWaste) - let constructor_params = encode(&[Token::Address(router_address), Token::Uint(gas_to_waste.into())]); - - // Append encoded constructor params to bytecode - bytecode.extend(constructor_params); - - // Deploy contract with complete bytecode - crate::utils::contracts::deploy_contract_code(bytecode, deployer) - } -} - -#[test] -fn rolling_buy_dca_completes_prematurely_when_price_increases() { - TestNet::reset(); - Hydra::execute_with(|| { - //Arrange - init_omnipool_with_oracle_for_block_10(); - - // Give ALICE a lot of HDX so she will NOT run out of funds - let alice_balance = 10_000_000_000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - ALICE.into(), - alice_balance, - )); - - let trade_size = 500 * UNITS; // amount_out: 500 DAI to buy each period - - // Create rolling buy DCA at the current (normal) price - // Use high max_retries so DCA survives oracle instability after the price move - let rolling_buy_schedule = Schedule { - owner: AccountId::from(ALICE), - period: hydradx_runtime::MinimalPeriod::get(), - total_amount: 0, // rolling - max_retries: Some(100), - stability_threshold: Some(Permill::from_percent(5)), - slippage: Some(Permill::from_percent(50)), - order: Order::Buy { - asset_in: HDX, - asset_out: DAI, - amount_out: trade_size, - max_amount_in: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: DAI, - }]), - }, - }; - - insert_schedule_into_storage(ALICE, rolling_buy_schedule, None); - - let schedule_id = 0; - assert_ok!(hydradx_runtime::CircuitBreaker::set_trade_volume_limit( - RuntimeOrigin::root(), - HDX, - (10_000, 10_000), - )); - assert_ok!(hydradx_runtime::CircuitBreaker::set_trade_volume_limit( - RuntimeOrigin::root(), - DAI, - (10_000, 10_000), - )); - go_to_block(11); - - // Now move the price AFTER DCA creation: BOB sells a massive amount of HDX for DAI, - // making DAI much more expensive in HDX terms (~3x price increase). - // The omnipool has ~5 billion UNITS of each asset, so we need billions to move the price. - // This does NOT affect remaining_amount which is already stored. - let bob_balance = 5_000_000_000 * UNITS; - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - BOB.into(), - bob_balance, - )); - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(BOB.into()), - HDX, - DAI, - 1_500_000_000 * UNITS, - 0, - )); - - //Act - run enough blocks for oracle to stabilize and DCA to execute - // Retry delays grow exponentially, so we need many blocks - run_to_block(12, 600); - - //Assert - // Rolling DCA should NOT be terminated just because the price moved - assert!( - DCA::schedules(schedule_id).is_some(), - "Rolling DCA should still be active after price increase" - ); - }); -} - -// Interaction between a `ghdxlock` balance lock and a named reserve. The Router -// (fungible API) treats the spendable floor as `frozen - reserved`, whereas -// `reserve`/locks treat them independently — so reserved HDX lets the Router -// move otherwise-locked HDX. -mod gigahdx_lock_reserve { - use super::*; - use frame_support::traits::tokens::fungible::Inspect as FungibleInspect; - use frame_support::traits::tokens::{Fortitude, Preservation}; - use frame_support::traits::{LockIdentifier, LockableCurrency, WithdrawReasons}; - use sp_runtime::TokenError; - - // Same id a gigahdx stake installs via `set_lock`. - const GHDX_LOCK: LockIdentifier = *b"ghdxlock"; - - fn omnipool_route() -> BoundedVec, ConstU32<{ MAX_NUMBER_OF_TRADES }>> { - vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: DAI, - }] - .try_into() - .unwrap() - } - - fn reducible_hdx(who: &AccountId) -> Balance { - >::reducible_balance(who, Preservation::Expendable, Fortitude::Polite) - } - - // With a 600 reserve, the fungible floor drops to `frozen - reserved = 0`, so - // the Router can sell HDX otherwise held by the 400 lock. - #[test] - fn router_sell_should_drain_ghdxlock_locked_hdx_when_account_holds_a_reserve() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - let alice: AccountId = ALICE.into(); - - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - alice.clone(), - 1000 * UNITS - )); - // Reserve under the DCA id, then lock the remaining free (free == frozen == 400). - assert_ok!(Currencies::reserve_named( - &NamedReserveId::get(), - HDX, - &alice, - 600 * UNITS - )); - Balances::set_lock(GHDX_LOCK, &alice, 400 * UNITS, WithdrawReasons::all()); - - // Reducible is the whole free balance, not `free - frozen`. - assert_balance!(alice.clone(), HDX, 400 * UNITS); - assert_reserved_balance!(alice.clone(), HDX, 600 * UNITS); - assert_eq!(reducible_hdx(&alice), 400 * UNITS); - - assert_ok!(Router::sell( - RuntimeOrigin::signed(alice.clone()), - HDX, - DAI, - 300 * UNITS, - 0, - omnipool_route(), - )); - - // Free HDX drops below the 400 lock; the reserve is untouched. - assert_balance!(alice.clone(), HDX, 100 * UNITS); - assert_reserved_balance!(alice.clone(), HDX, 600 * UNITS); - assert!( - Currencies::free_balance(HDX, &alice) < 400 * UNITS, - "free HDX dropped below the lock" - ); - }); - } - - // Same lock, no reserve: reducible is 0 and the Router sell is refused. - #[test] - fn router_sell_should_fail_to_touch_ghdxlock_when_no_reserve() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - let alice: AccountId = ALICE.into(); - - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - alice.clone(), - 400 * UNITS - )); - Balances::set_lock(GHDX_LOCK, &alice, 400 * UNITS, WithdrawReasons::all()); - - assert_eq!(reducible_hdx(&alice), 0); - - assert_noop!( - Router::sell( - RuntimeOrigin::signed(alice.clone()), - HDX, - DAI, - 300 * UNITS, - 0, - omnipool_route(), - ), - TokenError::FundsUnavailable - ); - - assert_balance!(alice.clone(), HDX, 400 * UNITS); - }); - } - - // A real `DCA::schedule` parks the reserve; the Router then sells locked HDX - // while the DCA budget stays intact. - #[test] - fn dca_reserve_should_enable_selling_ghdxlock_locked_hdx() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - go_to_block(11); - let alice: AccountId = ALICE.into(); - - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - alice.clone(), - 2000 * UNITS - )); - - // Non-rolling sell schedule reserves its full 1200 HDX budget under - // NamedReserveId (dca/src/lib.rs: `reserve_amount = total_amount`). - let schedule = - schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, 1200 * UNITS, HDX, DAI, 100 * UNITS); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(alice.clone()), schedule, None)); - assert_reserved_balance!(alice.clone(), HDX, 1200 * UNITS); - assert_balance!(alice.clone(), HDX, 800 * UNITS); - - // Lock the remaining 800 free HDX (free == frozen == 800). - Balances::set_lock(GHDX_LOCK, &alice, 800 * UNITS, WithdrawReasons::all()); - assert_eq!(reducible_hdx(&alice), 800 * UNITS); - - assert_ok!(Router::sell( - RuntimeOrigin::signed(alice.clone()), - HDX, - DAI, - 600 * UNITS, - 0, - omnipool_route(), - )); - - assert_balance!(alice.clone(), HDX, 200 * UNITS); - assert!( - Currencies::free_balance(HDX, &alice) < 800 * UNITS, - "free HDX dropped below the lock" - ); - // DCA budget untouched. - assert_reserved_balance!(alice.clone(), HDX, 1200 * UNITS); - }); - } - - // Free can be pushed down only to `frozen - reserved`, so with reserve 200 < - // lock 600 exactly 200 of locked HDX is sellable and the next unit is refused. - #[test] - fn locked_hdx_sellable_is_capped_at_the_reserved_amount() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - let alice: AccountId = ALICE.into(); - - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - alice.clone(), - 1000 * UNITS - )); - // Stake/lock 600, then park a 200 reserve (< stake). - Balances::set_lock(GHDX_LOCK, &alice, 600 * UNITS, WithdrawReasons::all()); - assert_ok!(Currencies::reserve_named( - &NamedReserveId::get(), - HDX, - &alice, - 200 * UNITS - )); - - // free 800, frozen 600, reserved 200 -> reducible = 800 - (600 - 200) = 400. - assert_balance!(alice.clone(), HDX, 800 * UNITS); - assert_eq!(reducible_hdx(&alice), 400 * UNITS); - - // Sell the full reducible: 200 above the lock + 200 below it. - assert_ok!(Router::sell( - RuntimeOrigin::signed(alice.clone()), - HDX, - DAI, - 400 * UNITS, - 0, - omnipool_route(), - )); - - // free == `frozen - reserved`; the floor is reached, one more unit is refused. - assert_balance!(alice.clone(), HDX, 400 * UNITS); - assert_eq!(reducible_hdx(&alice), 0); - assert_noop!( - Router::sell( - RuntimeOrigin::signed(alice.clone()), - HDX, - DAI, - UNITS, - 0, - omnipool_route(), - ), - TokenError::FundsUnavailable - ); - }); - } - - // Reserve >= lock zeroes the floor, so the whole free balance is sellable: - // free drains to 0 while the full lock remains. - #[test] - fn whole_stake_becomes_sellable_when_reserve_at_least_matches_stake() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - let alice: AccountId = ALICE.into(); - - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - alice.clone(), - 1000 * UNITS - )); - // Stake/lock 400, then park a 500 reserve (>= stake). - Balances::set_lock(GHDX_LOCK, &alice, 400 * UNITS, WithdrawReasons::all()); - assert_ok!(Currencies::reserve_named( - &NamedReserveId::get(), - HDX, - &alice, - 500 * UNITS - )); - - // free 500, frozen 400, reserved 500 -> floor 0, whole free is reducible. - assert_balance!(alice.clone(), HDX, 500 * UNITS); - assert_eq!(reducible_hdx(&alice), 500 * UNITS); - - assert_ok!(Router::sell( - RuntimeOrigin::signed(alice.clone()), - HDX, - DAI, - 500 * UNITS, - 0, - omnipool_route(), - )); - - // Free fully drained; the 400 lock remains, reserve untouched. - assert_balance!(alice.clone(), HDX, 0); - assert_reserved_balance!(alice.clone(), HDX, 500 * UNITS); - }); - } - // End to end with a reserve == lock. The reserve needs `free - budget >= - // frozen`, so it comes from unlocked HDX (account carries 2X); once it matches - // the lock the floor is 0 and a plain `transfer_allow_death` moves the locked X. - #[test] - fn user_scenario_stake_then_reserve_via_dca_then_transfer_out_the_whole_stake() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - go_to_block(11); - let alice: AccountId = ALICE.into(); - let bob: AccountId = BOB.into(); - - // X = 1000 (>= DCA `MinBudgetInNativeCurrency`). Alice needs 2X. - let x = 1000 * UNITS; - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - alice.clone(), - 2 * x - )); - let bob_before = Currencies::free_balance(HDX, &bob); - - // Lock X (stake). - Balances::set_lock(GHDX_LOCK, &alice, x, WithdrawReasons::all()); - assert_balance!(alice.clone(), HDX, 2 * x); - - // Schedule a DCA to sell X: reserves X under `dcaorder`. - let schedule = schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, x, HDX, DAI, 100 * UNITS); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(alice.clone()), schedule, None)); - assert_reserved_balance!(alice.clone(), HDX, x); - assert_balance!(alice.clone(), HDX, x); - assert_eq!(reducible_hdx(&alice), x); - - // A plain transfer moves the whole locked X to Bob. - assert_ok!(Balances::transfer_allow_death( - RuntimeOrigin::signed(alice.clone()), - bob.clone(), - x - )); - - // Free HDX 0 behind the live X lock; DCA budget untouched; Bob got X. - assert_balance!(alice.clone(), HDX, 0); - assert_reserved_balance!(alice.clone(), HDX, x); - assert_eq!(Currencies::free_balance(HDX, &bob), bob_before + x); - }); - } - - // With free 0, reserved X, frozen X, each unreserved unit is immediately - // re-frozen (reducible 0), so the DCA's own trade leg fails and the schedule - // terminates without selling. - #[test] - fn dca_cannot_trade_after_the_backing_is_transferred_out() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - go_to_block(11); - let alice: AccountId = ALICE.into(); - let bob: AccountId = BOB.into(); - let x = 1000 * UNITS; - - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - alice.clone(), - 2 * x - )); - - // Reserve X via a real DCA schedule, lock X, then move X out. - let schedule = schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, x, HDX, DAI, 100 * UNITS); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(alice.clone()), schedule, None)); - Balances::set_lock(GHDX_LOCK, &alice, x, WithdrawReasons::all()); - assert_ok!(Balances::transfer_allow_death( - RuntimeOrigin::signed(alice.clone()), - bob.clone(), - x - )); - assert_balance!(alice.clone(), HDX, 0); - assert_reserved_balance!(alice.clone(), HDX, x); - - // The DCA's internal trade leg — a Router::sell — now fails outright. - assert_noop!( - Router::sell( - RuntimeOrigin::signed(alice.clone()), - HDX, - DAI, - 100 * UNITS, - 0, - omnipool_route(), - ), - sp_runtime::TokenError::FundsUnavailable - ); - - // Drive the scheduler: the DCA fails its trade and terminates, selling nothing. - let dai_before = Currencies::free_balance(DAI, &alice); - run_to_block(12, 20); - assert!(DCA::schedules(0).is_none(), "DCA terminated"); - assert_balance!(alice.clone(), DAI, dai_before); - - // The refunded budget is re-frozen by the live lock (reducible 0). - assert_balance!(alice.clone(), HDX, x); - assert_reserved_balance!(alice.clone(), HDX, 0); - assert_eq!(reducible_hdx(&alice), 0); - }); - } - - // `Router::sell_all` sizes to `reducible_balance(.., Polite)`, which the reserve - // inflates to the full free balance — so one call sells all the locked HDX. The - // reserve stays trapped behind the lock afterwards. - #[test] - fn sell_all_drains_the_entire_locked_stake_in_one_call() { - TestNet::reset(); - Hydra::execute_with(|| { - init_omnipool_with_oracle_for_block_10(); - go_to_block(11); - let alice: AccountId = ALICE.into(); - let x = 1000 * UNITS; - - assert_ok!(Balances::force_set_balance( - RawOrigin::Root.into(), - alice.clone(), - 2 * x - )); - - // Park the reserve via a real DCA schedule, then lock X. - let schedule = schedule_fake_with_sell_order(ALICE, PoolType::Omnipool, x, HDX, DAI, 100 * UNITS); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(alice.clone()), schedule, None)); - Balances::set_lock(GHDX_LOCK, &alice, x, WithdrawReasons::all()); - assert_balance!(alice.clone(), HDX, x); - assert_reserved_balance!(alice.clone(), HDX, x); - assert_eq!(reducible_hdx(&alice), x); - - let dai_before = Currencies::free_balance(DAI, &alice); - - // One call, no amount: sizes to the full free balance. - assert_ok!(Router::sell_all( - RuntimeOrigin::signed(alice.clone()), - HDX, - DAI, - 0, - omnipool_route(), - )); - - // All the locked HDX was sold; the DCA budget is untouched. - assert_balance!(alice.clone(), HDX, 0); - assert_eq!(Currencies::free_balance(DAI, &alice) - dai_before, 712_143_506_239_384); - assert_reserved_balance!(alice.clone(), HDX, x); - - // Unreserving the budget re-freezes it behind the lock. - assert_eq!(Currencies::unreserve_named(&NamedReserveId::get(), HDX, &alice, x), 0); - assert_balance!(alice.clone(), HDX, x); - assert_reserved_balance!(alice.clone(), HDX, 0); - assert_eq!(reducible_hdx(&alice), 0); - }); - } -} diff --git a/integration-tests/src/dca_retirement.rs b/integration-tests/src/dca_retirement.rs new file mode 100644 index 0000000000..e6ee998cfb --- /dev/null +++ b/integration-tests/src/dca_retirement.rs @@ -0,0 +1,1159 @@ +//! Legacy DCA state is planted through the migration's own storage aliases: the pallet crate is gone. + +use crate::driver::HydrationTestDriver; +use crate::ice::PATH_TO_SNAPSHOT; +use crate::polkadot_test_net::{hydradx_run_to_next_block, Hydra, TestNet, ALICE, BOB, CHARLIE, DOT, HDX, LRNA, UNITS}; +use amm_simulator::HydrationSimulator; +use codec::Decode; +use frame_support::traits::OnRuntimeUpgrade; +use frame_support::weights::Weight; +use frame_support::{assert_ok, storage_alias, Blake2_128Concat, Twox64Concat}; +use hydradx_runtime::migrations::dca::{ + LegacyOrder, LegacySchedule, MigrateDcaToIntents, RemainingAmounts, ScheduleIdsPerBlock, Schedules, DCA_RESERVE_ID, + MAX_DCA_KEYS, MAX_SCHEDULES, +}; +use hydradx_runtime::{AssetRegistry, Currencies, Runtime, RuntimeOrigin, System, Tokens, Treasury}; +use hydradx_traits::amm::{SimulatorConfig, SimulatorSet}; +use hydradx_traits::registry::Inspect; +use hydradx_traits::router::{PoolType, Trade}; +use ice_solver::v4::Solver as IceSolver; +use ice_support::{DcaData, IntentData, IntentId, Solution}; +use orml_traits::{MultiCurrency, MultiReservableCurrency, NamedMultiReservableCurrency}; +use pallet_transaction_pause::{BoundedName, PausedTransactions}; +use primitives::{AccountId, AssetId, Balance}; +use sp_runtime::{Permill, StateVersion}; +use xcm_emulator::{Network, TestExt}; + +const INTENT_RESERVE_ID: [u8; 8] = *b"ICE_int#"; +const START_BLOCK: u32 = 10_000; +const PERIOD: u32 = 600; +const ENDOWMENT: Balance = 1_000 * UNITS; +const SLIPPAGE: Permill = Permill::from_percent(3); +const HOLLAR: AssetId = 222; +const ONE_HOLLAR: Balance = 1_000_000_000_000_000_000; +const BNC: AssetId = 14; +/// HOLLAR held by `ReserveAccount` in the `mainnet_apr` snapshot. +const SNAPSHOT_CUSTODY_HOLLAR: Balance = 27_967_822_764_337_836_667_721; + +#[storage_alias(verbatim)] +type ScheduleOwnership = StorageDoubleMap; + +#[storage_alias(verbatim)] +type ScheduleExecutionBlock = StorageMap; + +#[storage_alias(verbatim)] +type ScheduleIdSequencer = StorageValue; + +type CombinedSimulatorState = + <::Simulators as SimulatorSet>::State; +type Solver = IceSolver>; + +fn sell(owner: AccountId, asset_in: AssetId, asset_out: AssetId, amount_in: Balance, total: Balance) -> LegacySchedule { + LegacySchedule { + owner, + period: PERIOD, + total_amount: total, + max_retries: None, + stability_threshold: None, + slippage: Some(SLIPPAGE), + order: LegacyOrder::Sell { + asset_in, + asset_out, + amount_in, + min_amount_out: 0, + route: vec![], + }, + } +} + +/// `remaining: None` plants an orphan: a bare `Schedules` entry. +fn plant(id: u32, schedule: LegacySchedule, remaining: Option, planned: Option) { + if let Some(remaining) = remaining { + RemainingAmounts::insert(id, remaining); + ScheduleOwnership::insert(&schedule.owner, id, ()); + } + if let Some(block) = planned { + ScheduleIdsPerBlock::mutate(block, |ids| ids.get_or_insert_with(Vec::new).push(id)); + ScheduleExecutionBlock::insert(id, block); + } + ScheduleIdSequencer::put(id + 1); + Schedules::insert(id, schedule); +} + +/// Holds nothing at genesis, so balances can be asserted exactly. +fn owner() -> AccountId { + AccountId::from([0xa1; 32]) +} + +fn reserve_legacy(owner: &AccountId, asset: AssetId, amount: Balance) { + assert_ok!(Currencies::reserve_named(&DCA_RESERVE_ID, asset, owner, amount)); +} + +fn endow(owner: &AccountId, asset: AssetId, amount: Balance) { + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + owner.clone(), + asset, + amount as i128, + )); +} + +fn reserved(id: &[u8; 8], asset: AssetId, owner: &AccountId) -> Balance { + Currencies::reserved_balance_named(id, asset, owner) +} + +fn ed(asset: AssetId) -> Balance { + ::existential_deposit(asset).expect("asset is registered") +} + +fn migrate_unchecked() { + MigrateDcaToIntents::on_runtime_upgrade(); +} + +/// Also asserts what `post_upgrade` checks, which only runs under try-runtime. +fn migrate() { + migrate_unchecked(); + + let prefix = dca_prefix(); + assert_eq!( + sp_io::storage::next_key(&prefix).filter(|key| key.starts_with(&prefix)), + None + ); + let native: Vec<_> = pallet_balances::Reserves::::iter() + .filter(|(_, reserves)| reserves.iter().any(|r| r.id == DCA_RESERVE_ID && r.amount > 0)) + .map(|(owner, _)| owner) + .collect(); + assert_eq!(native, vec![]); + let tokens: Vec<_> = orml_tokens::Reserves::::iter() + .filter(|(_, _, reserves)| reserves.iter().any(|r| r.id == DCA_RESERVE_ID && r.amount > 0)) + .map(|(owner, asset, _)| (owner, asset)) + .collect(); + assert_eq!(tokens, vec![]); + assert!(!PausedTransactions::::contains_key(pause_key( + "DCA", "schedule" + ))); +} + +fn pause_key(pallet: &str, call: &str) -> (BoundedName, BoundedName) { + ( + BoundedName::truncate_from(pallet.as_bytes().to_vec()), + BoundedName::truncate_from(call.as_bytes().to_vec()), + ) +} + +fn dca_intents_of(owner: &AccountId) -> Vec<(IntentId, DcaData)> { + let mut intents: Vec<_> = pallet_intent::AccountIntents::::iter_prefix(owner) + .filter_map(|(id, ())| match pallet_intent::Intents::::get(id)?.data { + IntentData::Dca(dca) => Some((id, dca)), + _ => None, + }) + .collect(); + intents.sort_by_key(|(id, _)| *id); + intents +} + +fn offered(id: IntentId) -> bool { + pallet_intent::Pallet::::get_valid_intents() + .iter() + .any(|(offered, _)| *offered == id) +} + +fn dca_prefix() -> Vec { + sp_io::hashing::twox_128(b"DCA").to_vec() +} + +fn genesis(f: impl FnOnce()) { + TestNet::reset(); + Hydra::execute_with(|| { + System::set_block_number(START_BLOCK); + f(); + }); +} + +fn snapshot(f: impl FnOnce()) { + TestNet::reset(); + HydrationTestDriver::with_snapshot(PATH_TO_SNAPSHOT).execute(|| { + // The slim snapshot keeps `dcaorder` reserves of accounts it does not carry; nothing backs them. + for owner in pallet_balances::Reserves::::iter_keys().collect::>() { + if Currencies::reserved_balance(HDX, &owner) == 0 { + pallet_balances::Reserves::::mutate(&owner, |reserves| { + reserves.retain(|r| r.id != DCA_RESERVE_ID) + }); + } + } + for (owner, asset) in orml_tokens::Reserves::::iter_keys().collect::>() { + if orml_tokens::Accounts::::get(&owner, asset).reserved == 0 { + orml_tokens::Reserves::::mutate(&owner, asset, |reserves| { + reserves.retain(|r| r.id != DCA_RESERVE_ID) + }); + } + } + f(); + }); +} + +fn run_solver_and_submit() -> Solution { + let call = pallet_ice::Pallet::::run( + System::block_number(), + |intents: Vec, limits: Vec<(IntentId, Balance)>, state: CombinedSimulatorState| { + Solver::solve_with_limits( + intents, + limits.into_iter().collect(), + state, + pallet_ice::ProtocolFee::::get(), + ) + .ok() + }, + ) + .expect("solver should produce a solution"); + let pallet_ice::Call::submit_solution { solution, .. } = call else { + panic!("expected submit_solution"); + }; + hydradx_run_to_next_block(); + assert_ok!(pallet_ice::Pallet::::submit_solution( + RuntimeOrigin::none(), + solution.clone() + )); + solution +} + +#[test] +fn migration_should_convert_fixed_schedule_when_it_sells_an_orml_token() { + genesis(|| { + let alice = owner(); + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, 50 * UNITS); + plant( + 1, + sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS), + Some(50 * UNITS), + None, + ); + + migrate(); + + let intents = dca_intents_of(&alice); + assert_eq!(intents.len(), 1); + assert_eq!( + intents[0].1, + DcaData { + asset_in: DOT, + asset_out: HDX, + amount_in: 5 * UNITS, + amount_out: ed(HDX), + slippage: SLIPPAGE, + budget: Some(50 * UNITS), + remaining_budget: 50 * UNITS, + period: PERIOD, + last_execution_block: START_BLOCK - PERIOD, + } + ); + assert_eq!(reserved(&DCA_RESERVE_ID, DOT, &alice), 0); + assert_eq!(reserved(&INTENT_RESERVE_ID, DOT, &alice), 50 * UNITS); + assert_eq!(Currencies::free_balance(DOT, &alice), ENDOWMENT - 50 * UNITS); + }); +} + +#[test] +fn migration_should_reserve_twice_amount_in_and_free_the_excess_when_schedule_is_rolling() { + genesis(|| { + let alice = owner(); + let legacy_reserve = 10 * UNITS + 3 * UNITS / 10; + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, legacy_reserve); + plant( + 1, + sell(alice.clone(), DOT, HDX, 5 * UNITS, 0), + Some(legacy_reserve), + None, + ); + + migrate(); + + let intents = dca_intents_of(&alice); + assert_eq!(intents.len(), 1); + assert_eq!(intents[0].1.budget, None); + assert_eq!(intents[0].1.remaining_budget, 10 * UNITS); + assert_eq!(reserved(&DCA_RESERVE_ID, DOT, &alice), 0); + assert_eq!(reserved(&INTENT_RESERVE_ID, DOT, &alice), 10 * UNITS); + assert_eq!(Currencies::free_balance(DOT, &alice), ENDOWMENT - 10 * UNITS); + }); +} + +#[test] +fn migration_should_convert_schedule_when_it_sells_native_hdx() { + genesis(|| { + let alice = owner(); + endow(&alice, HDX, ENDOWMENT); + reserve_legacy(&alice, HDX, 50 * UNITS); + plant( + 1, + sell(alice.clone(), HDX, DOT, 5 * UNITS, 100 * UNITS), + Some(50 * UNITS), + None, + ); + + migrate(); + + let intents = dca_intents_of(&alice); + assert_eq!(intents.len(), 1); + assert_eq!(intents[0].1.asset_in, HDX); + assert_eq!(intents[0].1.amount_out, ed(DOT)); + assert_eq!(intents[0].1.remaining_budget, 50 * UNITS); + assert_eq!(reserved(&DCA_RESERVE_ID, HDX, &alice), 0); + assert_eq!(reserved(&INTENT_RESERVE_ID, HDX, &alice), 50 * UNITS); + assert_eq!(Currencies::free_balance(HDX, &alice), ENDOWMENT - 50 * UNITS); + }); +} + +#[test] +fn migration_should_delete_orphan_schedule_when_it_has_no_remaining_amount() { + genesis(|| { + let alice = owner(); + endow(&alice, DOT, ENDOWMENT); + let intents_before = pallet_intent::Intents::::iter().count(); + plant(1, sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS), None, None); + + migrate(); + + assert_eq!(Schedules::get(1), None); + assert_eq!(pallet_intent::Intents::::iter().count(), intents_before); + assert_eq!(Currencies::free_balance(DOT, &alice), ENDOWMENT); + assert_eq!(Currencies::reserved_balance(DOT, &alice), 0); + }); +} + +#[test] +fn migration_should_cancel_and_refund_when_fixed_budget_is_below_one_trade() { + genesis(|| { + let alice = owner(); + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, 4 * UNITS); + plant( + 1, + sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS), + Some(4 * UNITS), + None, + ); + + migrate(); + + assert_eq!(dca_intents_of(&alice), vec![]); + assert_eq!(reserved(&DCA_RESERVE_ID, DOT, &alice), 0); + assert_eq!(Currencies::free_balance(DOT, &alice), ENDOWMENT); + }); +} + +#[test] +fn migration_should_cancel_and_refund_when_order_is_buy() { + genesis(|| { + let alice = owner(); + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, 50 * UNITS); + let schedule = LegacySchedule { + order: LegacyOrder::Buy { + asset_in: DOT, + asset_out: HDX, + amount_out: UNITS, + max_amount_in: 5 * UNITS, + route: vec![], + }, + ..sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS) + }; + plant(1, schedule, Some(50 * UNITS), None); + + migrate(); + + assert_eq!(dca_intents_of(&alice), vec![]); + assert_eq!(reserved(&DCA_RESERVE_ID, DOT, &alice), 0); + assert_eq!(Currencies::free_balance(DOT, &alice), ENDOWMENT); + }); +} + +#[test] +fn migration_should_cancel_and_refund_when_intent_rejects_the_period() { + genesis(|| { + let alice = owner(); + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, 50 * UNITS); + let schedule = LegacySchedule { + period: 10, + ..sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS) + }; + plant(1, schedule, Some(50 * UNITS), None); + + migrate(); + + assert_eq!(dca_intents_of(&alice), vec![]); + assert_eq!(reserved(&DCA_RESERVE_ID, DOT, &alice), 0); + assert_eq!(reserved(&INTENT_RESERVE_ID, DOT, &alice), 0); + assert_eq!(Currencies::free_balance(DOT, &alice), ENDOWMENT); + }); +} + +#[test] +fn migration_should_release_whole_legacy_reserve_when_it_exceeds_remaining_amount() { + genesis(|| { + let alice = owner(); + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, 57 * UNITS); + plant( + 1, + sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS), + Some(50 * UNITS), + None, + ); + + migrate(); + + assert_eq!(reserved(&DCA_RESERVE_ID, DOT, &alice), 0); + assert_eq!(reserved(&INTENT_RESERVE_ID, DOT, &alice), 50 * UNITS); + assert_eq!(Currencies::free_balance(DOT, &alice), ENDOWMENT - 50 * UNITS); + }); +} + +#[test] +fn migration_should_leave_legacy_reserve_when_owner_has_no_schedule() { + genesis(|| { + let stranger = owner(); + endow(&stranger, DOT, ENDOWMENT); + reserve_legacy(&stranger, DOT, 7 * UNITS); + + migrate_unchecked(); + + assert_eq!(reserved(&DCA_RESERVE_ID, DOT, &stranger), 7 * UNITS); + }); +} + +#[test] +fn migration_should_remove_only_dca_pause_entry_when_transactions_are_paused() { + genesis(|| { + PausedTransactions::::insert(pause_key("DCA", "schedule"), ()); + PausedTransactions::::insert(pause_key("Stableswap", "buy"), ()); + + migrate(); + + assert!(!PausedTransactions::::contains_key(pause_key( + "DCA", "schedule" + ))); + assert!(PausedTransactions::::contains_key(pause_key( + "Stableswap", + "buy" + ))); + }); +} + +#[test] +fn migrated_intent_should_first_be_offered_at_legacy_planned_block_when_it_is_in_the_future() { + genesis(|| { + let alice = owner(); + let planned = START_BLOCK + 40; + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, 50 * UNITS); + let schedule = LegacySchedule { + period: 30, + ..sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS) + }; + plant(1, schedule, Some(50 * UNITS), Some(planned)); + + migrate(); + + let (id, dca) = dca_intents_of(&alice).remove(0); + // Offered at P - 1, so it settles in P, where the schedule traded. + assert_eq!(dca.last_execution_block, planned - 1 - 30); + // Beyond the early window (min(150, period / 2) = 15 blocks) nothing can offer it. + System::set_block_number(planned - 1 - 16); + assert!(!offered(id)); + System::set_block_number(planned - 1); + assert!(offered(id)); + }); +} + +#[test] +fn migrated_intent_should_be_offered_immediately_when_legacy_planned_block_is_in_the_past() { + genesis(|| { + let alice = owner(); + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, 50 * UNITS); + plant( + 1, + sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS), + Some(50 * UNITS), + Some(START_BLOCK - 5), + ); + + migrate(); + + let (id, dca) = dca_intents_of(&alice).remove(0); + assert_eq!(dca.last_execution_block, START_BLOCK - PERIOD); + assert!(offered(id)); + }); +} + +#[test] +fn migrated_intent_should_be_offered_immediately_when_schedule_has_no_planned_block() { + genesis(|| { + let alice = owner(); + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, 50 * UNITS); + plant( + 1, + sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS), + Some(50 * UNITS), + None, + ); + + migrate(); + + let (id, dca) = dca_intents_of(&alice).remove(0); + assert_eq!(dca.last_execution_block, START_BLOCK - PERIOD); + assert!(offered(id)); + }); +} + +#[test] +fn migration_should_convert_both_schedules_when_owner_has_two_in_the_same_asset() { + genesis(|| { + let alice = owner(); + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, 80 * UNITS); + plant( + 1, + sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS), + Some(50 * UNITS), + None, + ); + plant( + 2, + sell(alice.clone(), DOT, HDX, 3 * UNITS, 30 * UNITS), + Some(30 * UNITS), + None, + ); + + migrate(); + + let budgets: Vec<_> = dca_intents_of(&alice) + .into_iter() + .map(|(_, dca)| (dca.amount_in, dca.remaining_budget)) + .collect(); + assert_eq!(budgets, vec![(5 * UNITS, 50 * UNITS), (3 * UNITS, 30 * UNITS)]); + assert_eq!(reserved(&DCA_RESERVE_ID, DOT, &alice), 0); + assert_eq!(reserved(&INTENT_RESERVE_ID, DOT, &alice), 80 * UNITS); + }); +} + +#[test] +fn migration_should_leave_no_key_under_dca_prefix_when_complete() { + genesis(|| { + let alice = owner(); + let bob = AccountId::from([0xb0; 32]); + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, 50 * UNITS); + plant( + 1, + sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS), + Some(50 * UNITS), + Some(START_BLOCK + 7), + ); + plant(2, sell(bob, DOT, HDX, 5 * UNITS, 100 * UNITS), None, None); + let prefix = dca_prefix(); + assert!(sp_io::storage::next_key(&prefix).is_some_and(|key| key.starts_with(&prefix))); + + migrate(); + + assert_eq!( + sp_io::storage::next_key(&prefix).filter(|key| key.starts_with(&prefix)), + None + ); + }); +} + +#[test] +fn migration_should_change_nothing_when_run_twice() { + genesis(|| { + let alice = owner(); + endow(&alice, DOT, ENDOWMENT); + reserve_legacy(&alice, DOT, 50 * UNITS); + plant( + 1, + sell(alice.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS), + Some(50 * UNITS), + None, + ); + migrate(); + assert_eq!(dca_intents_of(&alice).len(), 1); + let root = sp_io::storage::root(StateVersion::V1); + + migrate(); + + assert_eq!(sp_io::storage::root(StateVersion::V1), root); + }); +} + +fn numbered_owner(i: u32) -> AccountId { + let mut raw = [0xa2; 32]; + raw[..4].copy_from_slice(&i.to_le_bytes()); + AccountId::from(raw) +} + +fn plant_convertible(count: u32) -> Vec { + (0..count) + .map(|i| { + let owner = numbered_owner(i); + endow(&owner, DOT, ENDOWMENT); + reserve_legacy(&owner, DOT, 50 * UNITS); + plant( + i + 1, + sell(owner.clone(), DOT, HDX, 5 * UNITS, 100 * UNITS), + Some(50 * UNITS), + None, + ); + owner + }) + .collect() +} + +fn assert_migration_changes_nothing() { + let root = sp_io::storage::root(StateVersion::V1); + + migrate_unchecked(); + + assert_eq!(sp_io::storage::root(StateVersion::V1), root); +} + +#[test] +fn migration_should_convert_every_schedule_when_exactly_max_schedules_exist() { + genesis(|| { + let owners = plant_convertible(MAX_SCHEDULES as u32); + + migrate(); + + let intents: usize = owners.iter().map(|owner| dca_intents_of(owner).len()).sum(); + assert_eq!(intents, MAX_SCHEDULES); + }); +} + +#[test] +fn migration_should_change_nothing_when_more_than_max_schedules_exist() { + genesis(|| { + plant_convertible(MAX_SCHEDULES as u32 + 1); + PausedTransactions::::insert(pause_key("DCA", "schedule"), ()); + + assert_migration_changes_nothing(); + }); +} + +#[test] +fn migration_should_change_nothing_when_more_than_max_schedules_planned_blocks_exist() { + genesis(|| { + plant_convertible(1); + for block in 0..=MAX_SCHEDULES as u32 { + ScheduleIdsPerBlock::insert(START_BLOCK + block, vec![1]); + } + PausedTransactions::::insert(pause_key("DCA", "schedule"), ()); + + assert_migration_changes_nothing(); + }); +} + +/// Raw mainnet values at block 17306764. +#[test] +fn legacy_aliases_should_decode_mainnet_values_when_read_at_their_keys() { + const RAW: [(&str, &str); 10] = [ + ("0x100f0c53fa332d4d9712c66fd92efcb6347d9208c3a12dab846866426727fa0ba76891f6c00e9fc6ffb2c09ef26e8c84960e0000", "0xcc542bfb6f31dccac106a6e5700ff1cf06a4c9f4c4740f538dcfb521285ab113928824000000f2052a01000000000000000000000105000130750000000500000000000000242932a90200000000000000000000000000000000000000000000000000000000"), + ("0x100f0c53fa332d4d9712c66fd92efcb6347d9208c3a12dab846866426727fa0ba3576662fc6df0485a78100d9f2fde8966660000", "0x58c21ff21fad655af9af8412a1dae595dd9250a40c4b8c5966dda68b36765054201c0000000070820dfb4669a81f0000000000000105000130750000001e00000016000000300cef59cc76287b60000000000000000000000000000000000000000000000000"), + ("0x100f0c53fa332d4d9712c66fd92efcb6347d9208c3a12dab846866426727fa0b20393ec6a46313d9e079b62877fa4f8b98750000", "0x6d6f646c70792f747273727900000000000000000000000000000000000000001e00000000000000000000000000000000000000010900011027000000010000000000000000a0d424f200000000000000000000000000000000000000000000000000000004030100000000000000"), + ("0x100f0c53fa332d4d9712c66fd92efcb6347d9208c3a12dab846866426727fa0bc4b38e1da411970b040d6fcae036c65ed6920000", "0x41ddf2ded434f3b236eca63124ea45b9034a03249dec7b072c2b4efa8efa3eaec0a800000000000000000000000000000000000001050001307500000056040000450000000000d8620897a0720300000000000000000000000000000000000000000000001404560400006e000000026e0000006e000000de00000006b80b0000de000000e903000002b2020000e9030000b202000004b202000045000000"), + ("0x100f0c53fa332d4d9712c66fd92efcb6ffc5d4b9530f9c21bd976ef7a9775515a76891f6c00e9fc6ffb2c09ef26e8c84960e0000", "0xd96680caf90000000000000000000000"), + ("0x100f0c53fa332d4d9712c66fd92efcb6ffc5d4b9530f9c21bd976ef7a977551520393ec6a46313d9e079b62877fa4f8b98750000", "0x3cccfd6be40100000000000000000000"), + ("0x100f0c53fa332d4d9712c66fd92efcb6ffc5d4b9530f9c21bd976ef7a9775515c4b38e1da411970b040d6fcae036c65ed6920000", "0x30da599bdc0334e90600000000000000"), + ("0x100f0c53fa332d4d9712c66fd92efcb6fbfce3131283f440b44ebe1a6e6d97f6351af555a4a0e61d43c4266594eecf611b162101", "0x04960e0000"), + ("0x100f0c53fa332d4d9712c66fd92efcb6fbfce3131283f440b44ebe1a6e6d97f6dcb949e68771ad3542e3dba035c5f797a6140801", "0x0498750000"), + ("0x100f0c53fa332d4d9712c66fd92efcb6fbfce3131283f440b44ebe1a6e6d97f61498dfafd9a7c7a74da7f325e29c1dba378d0801", "0x04d6920000"), + ]; + fn account(hex: &str) -> AccountId { + AccountId::decode(&mut &hex::decode(hex).expect("valid hex")[..]).expect("32 bytes") + } + fn trade(pool: PoolType, asset_in: AssetId, asset_out: AssetId) -> Trade { + Trade { + pool, + asset_in, + asset_out, + } + } + + genesis(|| { + for (key, value) in RAW { + let decode = |h: &str| hex::decode(h.trim_start_matches("0x")).expect("valid hex"); + sp_io::storage::set(&decode(key), &decode(value)); + } + + assert_eq!( + Schedules::get(3734), + Some(LegacySchedule { + owner: account("cc542bfb6f31dccac106a6e5700ff1cf06a4c9f4c4740f538dcfb521285ab113"), + period: 2_394_258, + total_amount: 1_280_000_000_000, + max_retries: Some(5), + stability_threshold: None, + slippage: Some(Permill::from_parts(30_000)), + order: LegacyOrder::Sell { + asset_in: 5, + asset_out: 0, + amount_in: 11_428_571_428, + min_amount_out: 0, + route: vec![], + }, + }) + ); + assert_eq!( + Schedules::get(26214), + Some(LegacySchedule { + owner: account("58c21ff21fad655af9af8412a1dae595dd9250a40c4b8c5966dda68b36765054"), + period: 7_200, + total_amount: 149_500_000_000_000_000_000_000, + max_retries: Some(5), + stability_threshold: None, + slippage: Some(Permill::from_parts(30_000)), + order: LegacyOrder::Sell { + asset_in: 30, + asset_out: 22, + amount_in: 1_779_761_904_761_904_761_904, + min_amount_out: 0, + route: vec![], + }, + }) + ); + assert_eq!( + Schedules::get(30104), + Some(LegacySchedule { + owner: hydradx_runtime::Treasury::account_id(), + period: 30, + total_amount: 0, + max_retries: Some(9), + stability_threshold: None, + slippage: Some(Permill::from_parts(10_000)), + order: LegacyOrder::Sell { + asset_in: 1, + asset_out: 0, + amount_in: 1_040_000_000_000, + min_amount_out: 0, + route: vec![trade(PoolType::Omnipool, 1, 0)], + }, + }) + ); + assert_eq!( + Schedules::get(37590), + Some(LegacySchedule { + owner: account("41ddf2ded434f3b236eca63124ea45b9034a03249dec7b072c2b4efa8efa3eae"), + period: 43_200, + total_amount: 0, + max_retries: Some(5), + stability_threshold: None, + slippage: Some(Permill::from_parts(30_000)), + order: LegacyOrder::Sell { + asset_in: 1110, + asset_out: 69, + amount_in: 63_600_000_000_000_000_000, + min_amount_out: 0, + route: vec![ + trade(PoolType::Aave, 1110, 110), + trade(PoolType::Stableswap(110), 110, 222), + trade(PoolType::UniswapV3(3000), 222, 1001), + trade(PoolType::Stableswap(690), 1001, 690), + trade(PoolType::Aave, 690, 69), + ], + }, + }) + ); + assert_eq!(RemainingAmounts::get(3734), Some(1_072_844_269_273)); + assert_eq!(RemainingAmounts::get(30104), Some(2_080_575_966_268)); + assert_eq!(RemainingAmounts::get(37590), Some(127_484_524_797_917_518_384)); + assert_eq!(RemainingAmounts::get(26214), None); + assert_eq!(ScheduleIdsPerBlock::get(18_945_563), Some(vec![3734])); + assert_eq!(ScheduleIdsPerBlock::get(17_306_790), Some(vec![30104])); + assert_eq!(ScheduleIdsPerBlock::get(17_337_655), Some(vec![37590])); + }); +} + +#[test] +fn migration_should_convert_rolling_schedule_when_it_sells_a_bound_erc20() { + snapshot(|| { + let owner: AccountId = CHARLIE.into(); + assert!(::contract_address(HOLLAR).is_some()); + assert_ok!(Currencies::transfer( + RuntimeOrigin::signed(Treasury::account_id()), + owner.clone(), + HOLLAR, + 50 * ONE_HOLLAR, + )); + let legacy_reserve = 20 * ONE_HOLLAR + 4 * ONE_HOLLAR / 10; + reserve_legacy(&owner, HOLLAR, legacy_reserve); + plant( + u32::MAX - 1, + sell(owner.clone(), HOLLAR, HDX, 10 * ONE_HOLLAR, 0), + Some(legacy_reserve), + None, + ); + + migrate(); + + let intents = dca_intents_of(&owner); + assert_eq!(intents.len(), 1); + assert_eq!(intents[0].1.remaining_budget, 20 * ONE_HOLLAR); + assert_eq!(reserved(&DCA_RESERVE_ID, HOLLAR, &owner), 0); + assert_eq!(reserved(&INTENT_RESERVE_ID, HOLLAR, &owner), 20 * ONE_HOLLAR); + assert_eq!(Currencies::free_balance(HOLLAR, &owner), 30 * ONE_HOLLAR); + }); +} + +fn custody() -> AccountId { + ::ReserveAccount::get() +} + +/// Grows the `dcaorder` receipt past what custody holds, so the erc20 transfer back reverts. +fn reserve_hollar_beyond_custody(owner: &AccountId) { + assert_eq!(Currencies::free_balance(HOLLAR, &custody()), SNAPSHOT_CUSTODY_HOLLAR); + assert_ok!(Currencies::transfer( + RuntimeOrigin::signed(Treasury::account_id()), + owner.clone(), + HOLLAR, + 50 * ONE_HOLLAR, + )); + reserve_legacy(owner, HOLLAR, 20 * ONE_HOLLAR); + let excess = SNAPSHOT_CUSTODY_HOLLAR + ONE_HOLLAR; + assert_ok!(>::deposit(HOLLAR, owner, excess)); + assert_ok!(>::reserve_named( + &DCA_RESERVE_ID, + HOLLAR, + owner, + excess + )); + plant( + u32::MAX - 2, + sell(owner.clone(), HOLLAR, HDX, 10 * ONE_HOLLAR, 0), + None, + None, + ); +} + +fn plant_healthy_hdx_schedule(owner: &AccountId) { + endow(owner, HDX, ENDOWMENT); + reserve_legacy(owner, HDX, 50 * UNITS); + plant( + u32::MAX - 1, + sell(owner.clone(), HDX, BNC, 5 * UNITS, 100 * UNITS), + Some(50 * UNITS), + None, + ); +} + +#[test] +fn migration_should_keep_legacy_reserve_record_when_bound_erc20_release_fails() { + snapshot(|| { + let owner: AccountId = CHARLIE.into(); + reserve_hollar_beyond_custody(&owner); + + migrate_unchecked(); + + assert_eq!( + reserved(&DCA_RESERVE_ID, HOLLAR, &owner), + SNAPSHOT_CUSTODY_HOLLAR + 21 * ONE_HOLLAR + ); + }); +} + +#[test] +fn migration_should_keep_tokens_in_reserve_account_custody_when_bound_erc20_release_fails() { + snapshot(|| { + let owner: AccountId = CHARLIE.into(); + reserve_hollar_beyond_custody(&owner); + + migrate_unchecked(); + + assert_eq!( + Currencies::free_balance(HOLLAR, &custody()), + SNAPSHOT_CUSTODY_HOLLAR + 20 * ONE_HOLLAR + ); + assert_eq!(Currencies::free_balance(HOLLAR, &owner), 30 * ONE_HOLLAR); + }); +} + +#[test] +fn migration_should_convert_schedule_of_another_owner_when_bound_erc20_release_fails() { + snapshot(|| { + let alice: AccountId = ALICE.into(); + plant_healthy_hdx_schedule(&alice); + reserve_hollar_beyond_custody(&CHARLIE.into()); + + migrate_unchecked(); + + let intents = dca_intents_of(&alice); + assert_eq!(intents.len(), 1); + assert_eq!(intents[0].1.remaining_budget, 50 * UNITS); + assert_eq!(reserved(&DCA_RESERVE_ID, HDX, &alice), 0); + assert_eq!(reserved(&INTENT_RESERVE_ID, HDX, &alice), 50 * UNITS); + }); +} + +#[test] +fn migration_should_keep_dca_pause_entry_when_bound_erc20_release_fails() { + snapshot(|| { + plant_healthy_hdx_schedule(&ALICE.into()); + reserve_hollar_beyond_custody(&CHARLIE.into()); + PausedTransactions::::insert(pause_key("DCA", "schedule"), ()); + + migrate_unchecked(); + + assert!(PausedTransactions::::contains_key(pause_key( + "DCA", "schedule" + ))); + }); +} + +#[test] +fn migration_should_keep_keys_under_dca_prefix_when_bound_erc20_release_fails() { + snapshot(|| { + plant_healthy_hdx_schedule(&ALICE.into()); + reserve_hollar_beyond_custody(&CHARLIE.into()); + + migrate_unchecked(); + + // Both `Schedules`, `ScheduleOwnership` and `ScheduleIdSequencer`. + assert_eq!(dca_key_count(), 4); + }); +} + +#[test] +fn migration_should_release_legacy_reserve_when_run_again_after_bound_erc20_release_failed() { + snapshot(|| { + let owner: AccountId = CHARLIE.into(); + reserve_hollar_beyond_custody(&owner); + migrate_unchecked(); + assert_ok!(Currencies::transfer( + RuntimeOrigin::signed(Treasury::account_id()), + custody(), + HOLLAR, + ONE_HOLLAR, + )); + + migrate(); + + assert_eq!(reserved(&DCA_RESERVE_ID, HOLLAR, &owner), 0); + assert_eq!( + Currencies::free_balance(HOLLAR, &owner), + SNAPSHOT_CUSTODY_HOLLAR + 51 * ONE_HOLLAR + ); + assert_eq!(Currencies::free_balance(HOLLAR, &custody()), 0); + }); +} + +#[test] +fn migration_should_not_convert_schedule_again_when_run_again_after_unfinished_run() { + snapshot(|| { + let alice: AccountId = ALICE.into(); + plant_healthy_hdx_schedule(&alice); + reserve_hollar_beyond_custody(&CHARLIE.into()); + migrate_unchecked(); + + migrate_unchecked(); + + assert_eq!(dca_intents_of(&alice).len(), 1); + }); +} + +fn dca_key_count() -> usize { + let prefix = dca_prefix(); + let mut at = prefix.clone(); + let mut count = 0; + while let Some(next) = sp_io::storage::next_key(&at).filter(|key| key.starts_with(&prefix)) { + count += 1; + at = next; + } + count +} + +#[test] +fn migration_should_change_nothing_when_more_than_max_dca_keys_exist() { + genesis(|| { + plant_convertible(1); + for id in 0..=MAX_DCA_KEYS { + ScheduleExecutionBlock::insert(id, START_BLOCK); + } + PausedTransactions::::insert(pause_key("DCA", "schedule"), ()); + + assert_migration_changes_nothing(); + }); +} + +#[test] +fn migration_should_charge_proof_size_per_read_when_retiring_an_orphan_schedule() { + genesis(|| { + plant(1, sell(owner(), DOT, HDX, 5 * UNITS, 100 * UNITS), None, None); + + let weight = MigrateDcaToIntents::on_runtime_upgrade(); + + // Five reads (schedule, two DCA keys, remaining amount, reserve) and two writes; `clear_prefix` counts + // only backend keys, and these sit in the overlay. + assert_eq!(weight, Weight::from_parts(325_000_000, 2_560)); + }); +} + +/// Like mainnet's indebted aToken sellers: the transfer runs Aave's health-factor check, over 400k gas. +#[test] +fn migration_should_convert_atoken_schedule_when_owner_borrows_against_many_collateral_reserves() { + use crate::liquidation::{borrow, supply}; + use amm_simulator::aave::Simulator as AaveSimulator; + use hydradx_runtime::evm::precompiles::erc20_mapping::HydraErc20Mapping; + use hydradx_runtime::evm::Executor; + use hydradx_runtime::{ice_simulator_provider, EVMAccounts}; + use hydradx_traits::amm::AmmSimulator; + use hydradx_traits::evm::{CallContext, Erc20Encoding, InspectEvmAccounts, EVM}; + use hydradx_traits::BoundErc20; + use sp_core::{H256, U256}; + + const ADOT: AssetId = 1001; + const SNAPSHOT_DOT: AssetId = 5; + + snapshot(|| { + let owner = AccountId::from([0xdc; 32]); + let evm = EVMAccounts::evm_address(&owner); + let pool = pallet_liquidation::BorrowingContract::::get(); + assert_ok!(EVMAccounts::approve_contract(RuntimeOrigin::root(), pool)); + endow(&owner, HDX, 1_000 * UNITS); + assert_ok!(EVMAccounts::bind_evm_address(RuntimeOrigin::signed(owner.clone()))); + + let pairs = AaveSimulator::>::snapshot().pairs; + let mut collateral = 0; + for (underlying, atoken) in pairs { + if AssetRegistry::contract_address(underlying).is_some() + || AssetRegistry::contract_address(atoken).is_none() + { + continue; + } + let unit = 10u128.pow(ed(underlying).checked_ilog10().unwrap_or(6) + 2); + let supplied = frame_support::storage::with_transaction(|| { + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + endow(&owner, underlying, 20_000 * unit); + supply( + pool, + evm, + HydraErc20Mapping::encode_evm_address(underlying), + 10_000 * unit, + ); + })); + match outcome { + Ok(()) => sp_runtime::TransactionOutcome::Commit(Ok::<_, sp_runtime::DispatchError>(true)), + Err(_) => sp_runtime::TransactionOutcome::Rollback(Ok(false)), + } + }) + .unwrap_or(false); + collateral += u32::from(supplied); + } + assert!( + collateral >= 6, + "only {collateral} collateral reserves could be supplied" + ); + + let legacy_reserve = Currencies::free_balance(ADOT, &owner) / 4; + reserve_legacy(&owner, ADOT, legacy_reserve); + borrow( + pool, + evm, + HydraErc20Mapping::encode_evm_address(SNAPSHOT_DOT), + 100 * 10u128.pow(10), + ); + + // Guard: without extra gas this owner cannot move aDOT into custody at all. + let contract = AssetRegistry::contract_address(ADOT).expect("aDOT is bound"); + let custody = EVMAccounts::evm_address(&::ReserveAccount::get()); + let mut data = sp_io::hashing::keccak_256(b"transfer(address,uint256)")[..4].to_vec(); + data.extend_from_slice(H256::from(custody).as_bytes()); + data.extend_from_slice(&U256::from(legacy_reserve).to_big_endian()); + let at_base_limit = frame_support::storage::with_transaction(|| { + let call = Executor::::call(CallContext::new_call(contract, evm), data, U256::zero(), 400_000); + sp_runtime::TransactionOutcome::Rollback(Ok::<_, sp_runtime::DispatchError>(call.exit_reason)) + }) + .expect("rollback"); + assert!(!matches!(at_base_limit, pallet_evm::ExitReason::Succeed(_))); + + plant( + u32::MAX - 1, + sell(owner.clone(), ADOT, HDX, legacy_reserve / 4, legacy_reserve), + Some(legacy_reserve), + None, + ); + + migrate(); + + let intents = dca_intents_of(&owner); + assert_eq!(intents.len(), 1); + assert_eq!(intents[0].1.remaining_budget, legacy_reserve); + assert_eq!(reserved(&DCA_RESERVE_ID, ADOT, &owner), 0); + assert_eq!(reserved(&INTENT_RESERVE_ID, ADOT, &owner), legacy_reserve); + }); +} + +#[test] +fn migrated_intent_should_settle_through_ice_when_its_period_has_elapsed() { + snapshot(|| { + let alice: AccountId = ALICE.into(); + assert_ok!(hydradx_runtime::Omnipool::set_slip_fee( + RuntimeOrigin::root(), + Some(pallet_omnipool::types::SlipFeeConfig { + max_slip_fee: Permill::from_percent(5), + }) + )); + endow(&alice, HDX, 10_000 * UNITS); + reserve_legacy(&alice, HDX, 4_000 * UNITS); + plant( + u32::MAX - 1, + LegacySchedule { + period: 15, + slippage: Some(Permill::from_percent(10)), + ..sell(alice.clone(), HDX, BNC, 200 * UNITS, 4_000 * UNITS) + }, + Some(4_000 * UNITS), + None, + ); + + migrate(); + let (id, _) = dca_intents_of(&alice).remove(0); + let bnc_before = Currencies::total_balance(BNC, &alice); + + let solution = run_solver_and_submit(); + + assert!(solution.resolved_intents.iter().any(|resolved| resolved.id == id)); + assert_eq!(Currencies::total_balance(BNC, &alice) - bnc_before, 13_487_774_062_934); + assert_eq!(dca_intents_of(&alice)[0].1.remaining_budget, 3_800 * UNITS); + }); +} + +#[test] +fn migrated_hub_asset_intent_should_settle_through_ice_when_schedule_sells_h2o() { + snapshot(|| { + let bob: AccountId = BOB.into(); + let amount_in = 1_040_000_000_000; + endow(&bob, LRNA, 100 * UNITS); + reserve_legacy(&bob, LRNA, 2 * amount_in); + plant( + u32::MAX - 1, + LegacySchedule { + period: 30, + slippage: Some(Permill::from_percent(1)), + ..sell(bob.clone(), LRNA, HDX, amount_in, 0) + }, + Some(2 * amount_in), + None, + ); + + migrate(); + let (id, _) = dca_intents_of(&bob).remove(0); + let hdx_before = Currencies::total_balance(HDX, &bob); + + let solution = run_solver_and_submit(); + + assert!(solution.resolved_intents.iter().any(|resolved| resolved.id == id)); + assert_eq!(Currencies::total_balance(HDX, &bob) - hdx_before, 3_700_798_942_397_350); + }); +} diff --git a/integration-tests/src/gigahdx.rs b/integration-tests/src/gigahdx.rs index 5e6cafc723..9b9cd2c823 100644 --- a/integration-tests/src/gigahdx.rs +++ b/integration-tests/src/gigahdx.rs @@ -28,6 +28,8 @@ use primitives::{AccountId, AssetId, Balance, EvmAddress}; use sp_core::{H160, H256, U256}; use xcm_emulator::Network; +const TEST_RESERVE_ID: [u8; 8] = *b"test_res"; + pub const PATH_TO_SNAPSHOT: &str = "snapshots/gigahdx/gigahdx"; #[allow(dead_code)] @@ -4007,12 +4009,7 @@ fn gigahdx_liquidation_e2e_should_seize_from_reserved_backing() { let liq_evm = e2e_provision_liq_account(&liq_account, main_mm); // Move the stake backing into `reserved`, leaving free at 0 behind the lock. - assert_ok!(Currencies::reserve_named( - &hydradx_runtime::NamedReserveId::get(), - HDX, - &alice, - stake_amount - )); + assert_ok!(Currencies::reserve_named(&TEST_RESERVE_ID, HDX, &alice, stake_amount)); assert_ok!(Balances::force_set_balance(RawOrigin::Root.into(), alice.clone(), 0)); assert_eq!(Balances::free_balance(&alice), 0); assert_eq!(Currencies::reserved_balance(HDX, &alice), stake_amount); @@ -4790,7 +4787,6 @@ fn full_unstake_should_reap_record_when_rate_causes_rounding() { // `set_lock`). mod reserve_leak { use super::*; - use hydradx_runtime::NamedReserveId; use orml_traits::NamedMultiReservableCurrency; // With a reserve of X parked, a plain `transfer_allow_death` moves the whole @@ -4823,8 +4819,8 @@ mod reserve_leak { ); let total_locked_before = pallet_gigahdx::TotalLocked::::get(); - // Park a reserve of X (as DCA::schedule does). - assert_ok!(Currencies::reserve_named(&NamedReserveId::get(), HDX, &alice, x)); + // Park a reserve of X. + assert_ok!(Currencies::reserve_named(&TEST_RESERVE_ID, HDX, &alice, x)); assert_eq!(Balances::free_balance(&alice), x); assert_ok!(Balances::transfer_allow_death( @@ -4870,7 +4866,7 @@ mod reserve_leak { assert_ok!(GigaHdx::giga_stake(RuntimeOrigin::signed(alice.clone()), x)); let atoken_after_first = Currencies::free_balance(GIGAHDX, &alice); - assert_ok!(Currencies::reserve_named(&NamedReserveId::get(), HDX, &alice, x)); + assert_ok!(Currencies::reserve_named(&TEST_RESERVE_ID, HDX, &alice, x)); // Raw free is now X, but the existing stake already claims X. assert_noop!( @@ -4904,7 +4900,7 @@ mod reserve_leak { assert_ok!(GigaHdx::giga_stake(RuntimeOrigin::signed(alice.clone()), x)); let atoken = Currencies::free_balance(GIGAHDX, &alice); - assert_ok!(Currencies::reserve_named(&NamedReserveId::get(), HDX, &alice, x)); + assert_ok!(Currencies::reserve_named(&TEST_RESERVE_ID, HDX, &alice, x)); assert_ok!(Balances::transfer_allow_death( RuntimeOrigin::signed(alice.clone()), bob.clone(), @@ -4933,7 +4929,6 @@ mod reserve_recovery_trace { use super::*; use frame_support::traits::tokens::fungible::Inspect as FungibleInspect; use frame_support::traits::tokens::{Fortitude, Preservation}; - use hydradx_runtime::NamedReserveId; use orml_traits::NamedMultiReservableCurrency; fn snap(who: &AccountId) -> (Balance, Balance, Balance, Balance, Balance) { @@ -4974,10 +4969,10 @@ mod reserve_recovery_trace { dump("step 1: giga_stake(100)", a1, snap(&bob)); assert_eq!(a1, (2 * x, 0, x, x, x)); // free 200, reserved 0, frozen 100, lock 100, spendable 100 - // Step 2: reserve X (exactly what DCA::schedule does). - assert_ok!(Currencies::reserve_named(&NamedReserveId::get(), HDX, &alice, x)); + // Step 2: reserve X. + assert_ok!(Currencies::reserve_named(&TEST_RESERVE_ID, HDX, &alice, x)); let a2 = snap(&alice); - dump("step 2: reserve 100 (DCA budget)", a2, snap(&bob)); + dump("step 2: reserve 100", a2, snap(&bob)); assert_eq!(a2, (x, x, x, x, x)); // free 100, reserved 100, frozen 100, lock 100, spendable 100 (!) // Step 3: move the entire (locked) stake HDX out to Bob. @@ -4989,7 +4984,7 @@ mod reserve_recovery_trace { assert_eq!(b3.0, x); // Bob got the 100 backing, fully spendable // Step 4: unreserve -> back to free, but the lock (still 100) re-freezes it. - let leftover = Currencies::unreserve_named(&NamedReserveId::get(), HDX, &alice, x); + let leftover = Currencies::unreserve_named(&TEST_RESERVE_ID, HDX, &alice, x); assert_eq!(leftover, 0, "whole reserve returned to free"); let a4 = snap(&alice); dump("step 4: unreserve 100", a4, snap(&bob)); @@ -5009,7 +5004,6 @@ mod reserve_recovery_trace { mod liquidation_seize { use super::*; use crate::assert_reserved_balance; - use hydradx_runtime::NamedReserveId; use hydradx_traits::gigahdx::Seize; use orml_traits::{MultiReservableCurrency, NamedMultiReservableCurrency}; @@ -5034,7 +5028,7 @@ mod liquidation_seize { // ends up entirely in `reserved`. assert_ok!(GigaHdx::giga_stake(RuntimeOrigin::signed(alice.clone()), x)); let atoken = Currencies::free_balance(GIGAHDX, &alice); - assert_ok!(Currencies::reserve_named(&NamedReserveId::get(), HDX, &alice, x)); + assert_ok!(Currencies::reserve_named(&TEST_RESERVE_ID, HDX, &alice, x)); assert_ok!(Balances::transfer_allow_death( RuntimeOrigin::signed(alice.clone()), bob.clone(), @@ -5057,3 +5051,292 @@ mod liquidation_seize { }); } } + +// A named reserve lowers the fungible floor to `frozen - reserved`, so HDX held by +// the `ghdxlock` becomes sellable/transferable up to the reserved amount. +mod gigahdx_lock_reserve { + use super::*; + use crate::polkadot_test_net::{go_to_block, Hydra, DAI}; + use crate::utils::pools::init_omnipool_with_oracle_for_block_10; + use crate::{assert_balance, assert_reserved_balance}; + use frame_support::traits::tokens::fungible::Inspect as FungibleInspect; + use frame_support::traits::tokens::{Fortitude, Preservation}; + use frame_support::traits::{LockIdentifier, LockableCurrency, WithdrawReasons}; + use hydradx_runtime::Router; + use hydradx_traits::router::{PoolType, Trade}; + use orml_traits::{MultiReservableCurrency, NamedMultiReservableCurrency}; + use pallet_route_executor::MAX_NUMBER_OF_TRADES; + use sp_runtime::traits::ConstU32; + use sp_runtime::{BoundedVec, TokenError}; + use xcm_emulator::TestExt; + + // Same id a gigahdx stake installs via `set_lock`. + const GHDX_LOCK: LockIdentifier = *b"ghdxlock"; + + fn omnipool_route() -> BoundedVec, ConstU32<{ MAX_NUMBER_OF_TRADES }>> { + vec![Trade { + pool: PoolType::Omnipool, + asset_in: HDX, + asset_out: DAI, + }] + .try_into() + .unwrap() + } + + fn reducible_hdx(who: &AccountId) -> Balance { + >::reducible_balance(who, Preservation::Expendable, Fortitude::Polite) + } + + // With a 600 reserve, the fungible floor drops to `frozen - reserved = 0`, so + // the Router can sell HDX otherwise held by the 400 lock. + #[test] + fn router_sell_should_drain_ghdxlock_locked_hdx_when_account_holds_a_reserve() { + TestNet::reset(); + Hydra::execute_with(|| { + init_omnipool_with_oracle_for_block_10(); + let alice: AccountId = ALICE.into(); + + assert_ok!(Balances::force_set_balance( + RawOrigin::Root.into(), + alice.clone(), + 1000 * UNITS + )); + // Reserve, then lock the remaining free (free == frozen == 400). + assert_ok!(Currencies::reserve_named(&TEST_RESERVE_ID, HDX, &alice, 600 * UNITS)); + Balances::set_lock(GHDX_LOCK, &alice, 400 * UNITS, WithdrawReasons::all()); + + // Reducible is the whole free balance, not `free - frozen`. + assert_balance!(alice.clone(), HDX, 400 * UNITS); + assert_reserved_balance!(alice.clone(), HDX, 600 * UNITS); + assert_eq!(reducible_hdx(&alice), 400 * UNITS); + + assert_ok!(Router::sell( + RuntimeOrigin::signed(alice.clone()), + HDX, + DAI, + 300 * UNITS, + 0, + omnipool_route(), + )); + + // Free HDX drops below the 400 lock; the reserve is untouched. + assert_balance!(alice.clone(), HDX, 100 * UNITS); + assert_reserved_balance!(alice.clone(), HDX, 600 * UNITS); + assert!( + Currencies::free_balance(HDX, &alice) < 400 * UNITS, + "free HDX dropped below the lock" + ); + }); + } + + // Same lock, no reserve: reducible is 0 and the Router sell is refused. + #[test] + fn router_sell_should_fail_to_touch_ghdxlock_when_no_reserve() { + TestNet::reset(); + Hydra::execute_with(|| { + init_omnipool_with_oracle_for_block_10(); + let alice: AccountId = ALICE.into(); + + assert_ok!(Balances::force_set_balance( + RawOrigin::Root.into(), + alice.clone(), + 400 * UNITS + )); + Balances::set_lock(GHDX_LOCK, &alice, 400 * UNITS, WithdrawReasons::all()); + + assert_eq!(reducible_hdx(&alice), 0); + + assert_noop!( + Router::sell( + RuntimeOrigin::signed(alice.clone()), + HDX, + DAI, + 300 * UNITS, + 0, + omnipool_route(), + ), + TokenError::FundsUnavailable + ); + + assert_balance!(alice.clone(), HDX, 400 * UNITS); + }); + } + + // Free can be pushed down only to `frozen - reserved`, so with reserve 200 < + // lock 600 exactly 200 of locked HDX is sellable and the next unit is refused. + #[test] + fn router_sell_should_cap_sellable_locked_hdx_at_reserved_amount_when_reserve_is_below_lock() { + TestNet::reset(); + Hydra::execute_with(|| { + init_omnipool_with_oracle_for_block_10(); + let alice: AccountId = ALICE.into(); + + assert_ok!(Balances::force_set_balance( + RawOrigin::Root.into(), + alice.clone(), + 1000 * UNITS + )); + // Stake/lock 600, then park a 200 reserve (< stake). + Balances::set_lock(GHDX_LOCK, &alice, 600 * UNITS, WithdrawReasons::all()); + assert_ok!(Currencies::reserve_named(&TEST_RESERVE_ID, HDX, &alice, 200 * UNITS)); + + // free 800, frozen 600, reserved 200 -> reducible = 800 - (600 - 200) = 400. + assert_balance!(alice.clone(), HDX, 800 * UNITS); + assert_eq!(reducible_hdx(&alice), 400 * UNITS); + + // Sell the full reducible: 200 above the lock + 200 below it. + assert_ok!(Router::sell( + RuntimeOrigin::signed(alice.clone()), + HDX, + DAI, + 400 * UNITS, + 0, + omnipool_route(), + )); + + // free == `frozen - reserved`; the floor is reached, one more unit is refused. + assert_balance!(alice.clone(), HDX, 400 * UNITS); + assert_eq!(reducible_hdx(&alice), 0); + assert_noop!( + Router::sell( + RuntimeOrigin::signed(alice.clone()), + HDX, + DAI, + UNITS, + 0, + omnipool_route(), + ), + TokenError::FundsUnavailable + ); + }); + } + + // Reserve >= lock zeroes the floor, so the whole free balance is sellable: + // free drains to 0 while the full lock remains. + #[test] + fn router_sell_should_drain_whole_free_balance_when_reserve_at_least_matches_lock() { + TestNet::reset(); + Hydra::execute_with(|| { + init_omnipool_with_oracle_for_block_10(); + let alice: AccountId = ALICE.into(); + + assert_ok!(Balances::force_set_balance( + RawOrigin::Root.into(), + alice.clone(), + 1000 * UNITS + )); + // Stake/lock 400, then park a 500 reserve (>= stake). + Balances::set_lock(GHDX_LOCK, &alice, 400 * UNITS, WithdrawReasons::all()); + assert_ok!(Currencies::reserve_named(&TEST_RESERVE_ID, HDX, &alice, 500 * UNITS)); + + // free 500, frozen 400, reserved 500 -> floor 0, whole free is reducible. + assert_balance!(alice.clone(), HDX, 500 * UNITS); + assert_eq!(reducible_hdx(&alice), 500 * UNITS); + + assert_ok!(Router::sell( + RuntimeOrigin::signed(alice.clone()), + HDX, + DAI, + 500 * UNITS, + 0, + omnipool_route(), + )); + + // Free fully drained; the 400 lock remains, reserve untouched. + assert_balance!(alice.clone(), HDX, 0); + assert_reserved_balance!(alice.clone(), HDX, 500 * UNITS); + }); + } + // End to end with a reserve == lock. The reserve needs `free - budget >= + // frozen`, so it comes from unlocked HDX (account carries 2X); once it matches + // the lock the floor is 0 and a plain `transfer_allow_death` moves the locked X. + #[test] + fn transfer_allow_death_should_move_whole_locked_stake_when_reserve_matches_lock() { + TestNet::reset(); + Hydra::execute_with(|| { + init_omnipool_with_oracle_for_block_10(); + go_to_block(11); + let alice: AccountId = ALICE.into(); + let bob: AccountId = BOB.into(); + + // Alice needs 2X. + let x = 1000 * UNITS; + assert_ok!(Balances::force_set_balance( + RawOrigin::Root.into(), + alice.clone(), + 2 * x + )); + let bob_before = Currencies::free_balance(HDX, &bob); + + // Lock X (stake). + Balances::set_lock(GHDX_LOCK, &alice, x, WithdrawReasons::all()); + assert_balance!(alice.clone(), HDX, 2 * x); + + assert_ok!(Currencies::reserve_named(&TEST_RESERVE_ID, HDX, &alice, x)); + assert_reserved_balance!(alice.clone(), HDX, x); + assert_balance!(alice.clone(), HDX, x); + assert_eq!(reducible_hdx(&alice), x); + + // A plain transfer moves the whole locked X to Bob. + assert_ok!(Balances::transfer_allow_death( + RuntimeOrigin::signed(alice.clone()), + bob.clone(), + x + )); + + // Free HDX 0 behind the live X lock; reserve untouched; Bob got X. + assert_balance!(alice.clone(), HDX, 0); + assert_reserved_balance!(alice.clone(), HDX, x); + assert_eq!(Currencies::free_balance(HDX, &bob), bob_before + x); + }); + } + + // `Router::sell_all` sizes to `reducible_balance(.., Polite)`, which the reserve + // inflates to the full free balance — so one call sells all the locked HDX. The + // reserve stays trapped behind the lock afterwards. + #[test] + fn router_sell_all_should_drain_entire_locked_stake_when_reserve_matches_lock() { + TestNet::reset(); + Hydra::execute_with(|| { + init_omnipool_with_oracle_for_block_10(); + go_to_block(11); + let alice: AccountId = ALICE.into(); + let x = 1000 * UNITS; + + assert_ok!(Balances::force_set_balance( + RawOrigin::Root.into(), + alice.clone(), + 2 * x + )); + + // Park the reserve, then lock X. + assert_ok!(Currencies::reserve_named(&TEST_RESERVE_ID, HDX, &alice, x)); + Balances::set_lock(GHDX_LOCK, &alice, x, WithdrawReasons::all()); + assert_balance!(alice.clone(), HDX, x); + assert_reserved_balance!(alice.clone(), HDX, x); + assert_eq!(reducible_hdx(&alice), x); + + let dai_before = Currencies::free_balance(DAI, &alice); + + // One call, no amount: sizes to the full free balance. + assert_ok!(Router::sell_all( + RuntimeOrigin::signed(alice.clone()), + HDX, + DAI, + 0, + omnipool_route(), + )); + + // All the locked HDX was sold; the reserve is untouched. + assert_balance!(alice.clone(), HDX, 0); + assert_eq!(Currencies::free_balance(DAI, &alice) - dai_before, 712_143_506_239_384); + assert_reserved_balance!(alice.clone(), HDX, x); + + // Unreserving re-freezes it behind the lock. + assert_eq!(Currencies::unreserve_named(&TEST_RESERVE_ID, HDX, &alice, x), 0); + assert_balance!(alice.clone(), HDX, x); + assert_reserved_balance!(alice.clone(), HDX, 0); + assert_eq!(reducible_hdx(&alice), 0); + }); + } +} diff --git a/integration-tests/src/ice/dca_migration.rs b/integration-tests/src/ice/dca_migration.rs deleted file mode 100644 index 8730385aae..0000000000 --- a/integration-tests/src/ice/dca_migration.rs +++ /dev/null @@ -1,1405 +0,0 @@ -//! Integration coverage for the DCA -> DCA-intent migration (`ICE_DCA_MIGRATION_PLAN.md` §7.2). -//! -//! Runs against the `mainnet_apr` snapshot with the real v4 solver. Old-style schedules are created -//! through `DCA::schedule` before the flag flip; buy schedules are planted directly because the -//! extrinsic no longer accepts them. - -use crate::polkadot_test_net::{hydradx_run_to_next_block, TestNet, ALICE, BOB}; -use amm_simulator::HydrationSimulator; -use frame_support::traits::{Get, Time}; -use frame_support::{assert_noop, assert_ok}; -use hydradx_runtime::{Currencies, Runtime, RuntimeEvent, RuntimeOrigin, DCA}; -use hydradx_traits::amm::{SimulatorConfig, SimulatorSet}; -use hydradx_traits::registry::Inspect; -use hydradx_traits::router::{PoolType, Trade}; -use ice_solver::v4::Solver as IceSolver; -use ice_support::Solution; -use orml_traits::{MultiCurrency, NamedMultiReservableCurrency}; -use pallet_dca::types::{CancelReason, Order, Schedule}; -use pallet_omnipool::types::SlipFeeConfig; -use primitives::constants::currency::UNITS; -use primitives::AccountId; -use sp_runtime::traits::ConstU32; -use sp_runtime::{BoundedVec, Permill}; -use xcm_emulator::Network; - -use super::PATH_TO_SNAPSHOT; - -const HDX: u32 = 0; -const BNC: u32 = 14; - -/// 20x the snapshot's DCA transaction fee (~0.99 HDX) clears `MinTradeAmountNotReached`. -const AMOUNT_IN: u128 = 200 * UNITS; -/// `MinBudgetInNativeCurrency` is 1000 HDX, so a fixed budget has to clear that. -const BUDGET: u128 = 4_000 * UNITS; -/// A rolling schedule reserves `(amount_in + fee) * 2`, which has to clear the 1000 HDX -/// `MinBudgetInNativeCurrency`. -const ROLLING_AMOUNT_IN: u128 = 600 * UNITS; -/// Existential deposit of BNC — the floor `add_intent` enforces on `amount_out`. -const MIN_OUT_BNC: u128 = 68_795_189_840; -const PERIOD: u32 = 15; -const DCA_SLIPPAGE: Permill = Permill::from_percent(10); - -const DCA_RESERVE_ID: [u8; 8] = *b"dcaorder"; -const INTENT_RESERVE_ID: [u8; 8] = *b"ICE_int#"; - -type CombinedSimulatorState = - <::Simulators as SimulatorSet>::State; -type Solver = IceSolver>; -type DcaSchedule = Schedule; - -fn enable_slip_fees() { - assert_ok!(hydradx_runtime::Omnipool::set_slip_fee( - RuntimeOrigin::root(), - Some(SlipFeeConfig { - max_slip_fee: Permill::from_percent(5), - }) - )); -} - -fn run_solver_and_submit() -> Solution { - let block = hydradx_runtime::System::block_number(); - let call = pallet_ice::Pallet::::run( - block, - |intents: Vec, - limits: Vec<(ice_support::IntentId, ice_support::Balance)>, - state: CombinedSimulatorState| { - Solver::solve_with_limits( - intents, - limits.into_iter().collect(), - state, - pallet_ice::ProtocolFee::::get(), - ) - .ok() - }, - ) - .expect("Solver should produce a solution"); - - let pallet_ice::Call::submit_solution { solution, .. } = call else { - panic!("Expected submit_solution call"); - }; - let solution_clone = solution.clone(); - - hydradx_run_to_next_block(); - assert_ok!(pallet_ice::Pallet::::submit_solution( - RuntimeOrigin::none(), - solution, - )); - - solution_clone -} - -/// `hydradx_run_to_block` trips the Aura consensus hook on a snapshot; only -/// `hydradx_run_to_next_block` clears `CurrentSlot` between blocks. -fn run_to(target: u32) { - while hydradx_runtime::System::block_number() < target { - hydradx_run_to_next_block(); - } -} - -fn advance_and_solve(n: u32) -> Solution { - for _ in 0..n { - hydradx_run_to_next_block(); - } - run_solver_and_submit() -} - -fn route(asset_in: u32, asset_out: u32) -> BoundedVec, ConstU32<9>> { - BoundedVec::truncate_from(vec![Trade { - pool: PoolType::Omnipool, - asset_in, - asset_out, - }]) -} - -fn sell_schedule(owner: AccountId, total_amount: u128, amount_in: u128, min_amount_out: u128) -> DcaSchedule { - Schedule { - owner, - period: PERIOD, - total_amount, - max_retries: None, - stability_threshold: None, - slippage: Some(DCA_SLIPPAGE), - order: Order::Sell { - asset_in: HDX, - asset_out: BNC, - amount_in, - min_amount_out, - route: route(HDX, BNC), - }, - } -} - -fn default_sell_schedule(owner: AccountId) -> DcaSchedule { - sell_schedule(owner, BUDGET, AMOUNT_IN, MIN_OUT_BNC) -} - -fn buy_schedule(owner: AccountId) -> DcaSchedule { - Schedule { - owner, - period: PERIOD, - total_amount: BUDGET, - max_retries: None, - stability_threshold: None, - slippage: Some(DCA_SLIPPAGE), - order: Order::Buy { - asset_in: HDX, - asset_out: BNC, - amount_out: MIN_OUT_BNC * 10, - max_amount_in: AMOUNT_IN, - route: route(HDX, BNC), - }, - } -} - -/// Creates an old-style schedule through the extrinsic; returns its id and planned block. -fn schedule_dca(who: AccountId, schedule: DcaSchedule) -> (u32, u32) { - let id = DCA::next_schedule_id(); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(who), schedule, None)); - let block = pallet_dca::ScheduleExecutionBlock::::get(id).expect("schedule must be planned"); - (id, block) -} - -/// Writes the state the `schedule` extrinsic would write. Needed for buy orders, which the -/// extrinsic rejects (`NoLongerSupported`) but which still exist on chain from before that change. -fn plant_schedule(schedule: DcaSchedule, execution_block: u32) -> u32 { - let owner = schedule.owner.clone(); - let asset_in = schedule.order.get_asset_in(); - let reserve = if schedule.is_rolling() { - let amount_in = match schedule.order { - Order::Sell { amount_in, .. } => amount_in, - Order::Buy { max_amount_in, .. } => max_amount_in, - }; - let fee = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - (amount_in + fee) * 2 - } else { - schedule.total_amount - }; - - let id = pallet_dca::ScheduleIdSequencer::::mutate(|current| { - let id = *current; - *current += 1; - id - }); - - pallet_dca::Schedules::::insert(id, &schedule); - pallet_dca::ScheduleOwnership::::insert(&owner, id, ()); - pallet_dca::RemainingAmounts::::insert(id, reserve); - pallet_dca::RetriesOnError::::insert(id, 0); - pallet_dca::ScheduleExecutionBlock::::insert(id, execution_block); - pallet_dca::ScheduleIdsPerBlock::::mutate(execution_block, |ids| { - ids.try_push(id).expect("execution block is full"); - }); - - assert_ok!(Currencies::reserve_named(&DCA_RESERVE_ID, asset_in, &owner, reserve)); - - id -} - -fn enable_migration() { - assert_ok!(DCA::set_migration_enabled(RuntimeOrigin::root(), true)); -} - -/// The snapshot carries the real chain's events, and the test harness's `on_initialize` does not -/// clear them, so every event assertion has to be scoped to what happened after this mark. -fn event_mark() -> usize { - frame_system::Pallet::::events().len() -} - -fn dca_events_since(mark: usize) -> Vec> { - frame_system::Pallet::::events() - .into_iter() - .skip(mark) - .map(|record| record.event) - .filter_map(|e| match e { - RuntimeEvent::DCA(inner) => Some(inner), - _ => None, - }) - .collect() -} - -/// The intent a schedule became, taken from its `Migrated` event - the only record kept of the -/// id change. -fn migrated_intent_id(schedule_id: u32) -> u128 { - find_migrated_intent_id(schedule_id).expect("schedule should have been migrated") -} - -fn find_migrated_intent_id(schedule_id: u32) -> Option { - dca_events_since(0).into_iter().find_map(|e| match e { - pallet_dca::Event::Migrated { id, intent_id, .. } if id == schedule_id => Some(intent_id), - _ => None, - }) -} - -fn dca_data(intent_id: u128) -> ice_support::DcaData { - match pallet_intent::Intents::::get(intent_id) - .expect("intent should exist") - .data - { - ice_support::IntentData::Dca(dca) => dca, - _ => panic!("expected a DCA intent"), - } -} - -fn assert_schedule_gone(owner: &AccountId, id: u32) { - assert!(pallet_dca::Schedules::::get(id).is_none(), "Schedules"); - assert!( - pallet_dca::ScheduleOwnership::::get(owner, id).is_none(), - "ScheduleOwnership" - ); - assert!( - pallet_dca::RemainingAmounts::::get(id).is_none(), - "RemainingAmounts" - ); - assert!( - pallet_dca::ScheduleExecutionBlock::::get(id).is_none(), - "ScheduleExecutionBlock" - ); - assert_eq!(pallet_dca::RetriesOnError::::get(id), 0, "RetriesOnError"); - assert_eq!(pallet_dca::ScheduleExtraGas::::get(id), 0, "ScheduleExtraGas"); -} - -fn driver_with_funded_alice() -> crate::driver::HydrationTestDriver { - let alice: AccountId = ALICE.into(); - let driver = crate::driver::HydrationTestDriver::with_snapshot(PATH_TO_SNAPSHOT); - driver.endow_account(alice, HDX, 10 * BUDGET); - driver -} - -// === A. Conversion across pool topologies === - -#[test] -fn migration_should_convert_and_fill_when_pair_routes_through_omnipool() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - enable_migration(); - - run_to(block); - let intent_id = migrated_intent_id(id); - println!("TEMP protocol fee {:?}", pallet_ice::ProtocolFee::::get()); - - let bnc_before = Currencies::total_balance(BNC, &alice); - let solution = advance_and_solve(PERIOD); - - assert_eq!(solution.resolved_intents.len(), 1); - assert_eq!(solution.resolved_intents[0].id, intent_id); - assert!(Currencies::total_balance(BNC, &alice) > bnc_before); - assert_eq!(dca_data(intent_id).remaining_budget, BUDGET - AMOUNT_IN); - }); -} - -#[test] -fn migration_should_drop_stored_route_when_schedule_carries_one() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - // A route through a pool that is not the one the solver would pick still converts: the - // intent carries no route at all, the solver rediscovers it. - let mut schedule = default_sell_schedule(alice.clone()); - if let Order::Sell { ref mut route, .. } = schedule.order { - *route = BoundedVec::truncate_from(vec![]); - } - - let (id, block) = schedule_dca(alice.clone(), schedule); - enable_migration(); - run_to(block); - - let intent_id = migrated_intent_id(id); - let bnc_before = Currencies::total_balance(BNC, &alice); - let solution = advance_and_solve(PERIOD); - assert_eq!(solution.resolved_intents[0].id, intent_id); - assert!(Currencies::total_balance(BNC, &alice) > bnc_before); - }); -} - -#[test] -fn migration_should_convert_and_fill_when_pair_routes_through_stableswap() { - use amm_simulator::stableswap::Simulator as StableswapSimulator; - use hydradx_runtime::{ice_simulator_provider, AssetRegistry, Router}; - use hydradx_traits::amm::AmmSimulator; - use hydradx_traits::router::{AssetPair, RouteProvider}; - use hydradx_traits::BoundErc20; - - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - crate::driver::HydrationTestDriver::with_snapshot(PATH_TO_SNAPSHOT).execute(|| { - enable_slip_fees(); - - // Same selection as `ice::dca::dca_through_stableswap_single_hop`: a pool whose first two - // assets are non-contract and both routable to HDX. - let snapshot = StableswapSimulator::>::snapshot(); - let selected = snapshot.pools.iter().find_map(|(_, pool)| { - if pool.assets.len() < 2 { - return None; - } - let (a, b) = (pool.assets[0], pool.assets[1]); - if AssetRegistry::contract_address(a).is_some() || AssetRegistry::contract_address(b).is_some() { - return None; - } - if Router::get_onchain_route(AssetPair::new(a, HDX)).is_some() - && Router::get_onchain_route(AssetPair::new(b, HDX)).is_some() - { - Some((a, b, pool.reserves[0].decimals, pool.reserves[1].decimals)) - } else { - None - } - }); - let Some((asset_in, asset_out, decimals_in, decimals_out)) = selected else { - println!("SKIPPED: no suitable stableswap pool in snapshot"); - return; - }; - - let amount_in = 100 * 10u128.pow(decimals_in as u32); - let min_out = 10u128.pow(decimals_out as u32); - let budget = 100 * amount_in; - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - alice.clone(), - asset_in, - (budget * 10) as i128, - )); - - let schedule = Schedule { - owner: alice.clone(), - period: PERIOD, - total_amount: budget, - max_retries: None, - stability_threshold: None, - slippage: Some(DCA_SLIPPAGE), - order: Order::Sell { - asset_in, - asset_out, - amount_in, - min_amount_out: min_out, - route: BoundedVec::truncate_from(vec![]), - }, - }; - - let (id, block) = schedule_dca(alice.clone(), schedule); - enable_migration(); - run_to(block); - - let intent_id = migrated_intent_id(id); - assert_eq!(dca_data(intent_id).asset_out, asset_out); - - let out_before = Currencies::total_balance(asset_out, &alice); - advance_and_solve(PERIOD); - assert!( - Currencies::total_balance(asset_out, &alice) > out_before, - "migrated stableswap DCA should fill" - ); - }); -} - -#[test] -fn migration_should_convert_and_fill_when_pair_is_aave() { - use amm_simulator::aave::Simulator as AaveSimulator; - use hydradx_runtime::ice_simulator_provider; - use hydradx_traits::amm::AmmSimulator; - - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - crate::driver::HydrationTestDriver::with_snapshot(PATH_TO_SNAPSHOT).execute(|| { - enable_slip_fees(); - - let aave_snapshot = AaveSimulator::>::snapshot(); - let picked = aave_snapshot.pairs.iter().find_map(|(a, b)| { - let ed_in = as Inspect>::existential_deposit(*a)?; - let ed_out = as Inspect>::existential_deposit(*b)?; - Some((*a, *b, ed_in, ed_out)) - }); - let Some((asset_in, asset_out, ed_in, ed_out)) = picked else { - println!("SKIPPED: snapshot has no aave pairs"); - return; - }; - - let amount_in = ed_in.saturating_mul(1_000); - let budget = 100 * amount_in; - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - alice.clone(), - asset_in, - (budget * 10) as i128, - )); - - let schedule = Schedule { - owner: alice.clone(), - period: PERIOD, - total_amount: budget, - max_retries: None, - stability_threshold: None, - slippage: Some(DCA_SLIPPAGE), - order: Order::Sell { - asset_in, - asset_out, - amount_in, - min_amount_out: ed_out, - route: BoundedVec::truncate_from(vec![]), - }, - }; - - let (id, block) = schedule_dca(alice.clone(), schedule); - enable_migration(); - run_to(block); - - let intent_id = migrated_intent_id(id); - assert_eq!(dca_data(intent_id).asset_in, asset_in); - assert_eq!(dca_data(intent_id).asset_out, asset_out); - - let out_before = Currencies::total_balance(asset_out, &alice); - advance_and_solve(PERIOD); - assert!( - Currencies::total_balance(asset_out, &alice) > out_before, - "migrated aave DCA should fill" - ); - }); -} - -// === B. Timing and cadence === - -#[test] -fn migration_should_not_execute_trade_when_conversion_happens() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - enable_migration(); - - let hdx_free_before = Currencies::free_balance(HDX, &alice); - let bnc_before = Currencies::total_balance(BNC, &alice); - - let mark = event_mark(); - run_to(block); - - // No trade, no transaction fee, no execution events. - assert_eq!(Currencies::total_balance(BNC, &alice), bnc_before); - assert_eq!(Currencies::free_balance(HDX, &alice), hdx_free_before); - let events = dca_events_since(mark); - assert!( - !events.iter().any(|e| matches!( - e, - pallet_dca::Event::TradeExecuted { .. } - | pallet_dca::Event::TradeFailed { .. } - | pallet_dca::Event::ExecutionStarted { .. } - | pallet_dca::Event::ExecutionPlanned { .. } - )), - "no execution events at the conversion block, got {events:?}" - ); - assert!(events.iter().any(|e| matches!(e, pallet_dca::Event::Migrated { .. }))); - assert!(find_migrated_intent_id(id).is_some()); - }); -} - -#[test] -fn migrated_intent_should_be_eligible_at_the_conversion_block() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - enable_migration(); - run_to(block); - - let intent_id = migrated_intent_id(id); - assert_eq!(dca_data(intent_id).last_execution_block, block - PERIOD); - assert_eq!( - pallet_intent::Pallet::::get_valid_intents().len(), - 1, - "eligible at the conversion block, not one period later" - ); - - // The cadence then runs from the first fill, which lands in the next block. - run_solver_and_submit(); - let first_fill = hydradx_runtime::System::block_number(); - assert_eq!(dca_data(intent_id).last_execution_block, first_fill); - - for _ in 0..PERIOD - 1 { - hydradx_run_to_next_block(); - assert!( - pallet_intent::Pallet::::get_valid_intents().is_empty(), - "eligible too early at block {}", - hydradx_runtime::System::block_number() - ); - } - - hydradx_run_to_next_block(); - assert_eq!( - pallet_intent::Pallet::::get_valid_intents().len(), - 1, - "eligible exactly one period after the first fill" - ); - }); -} - -#[test] -fn migrated_intent_should_keep_period_cadence_over_three_fills() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - enable_migration(); - run_to(block); - let intent_id = migrated_intent_id(id); - - let mut expected_remaining = BUDGET; - for _ in 0..3 { - advance_and_solve(PERIOD); - expected_remaining -= AMOUNT_IN; - assert_eq!(dca_data(intent_id).remaining_budget, expected_remaining); - } - }); -} - -#[test] -fn schedule_should_not_trade_between_flag_flip_and_its_planned_block() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let mut schedule = default_sell_schedule(alice.clone()); - schedule.period = 100; - let (id, block) = schedule_dca(alice.clone(), schedule); - enable_migration(); - - let bnc_before = Currencies::total_balance(BNC, &alice); - run_to(block - 1); - - // Still on the old pallet, still untouched. - assert!(pallet_dca::Schedules::::get(id).is_some()); - assert_eq!(Currencies::total_balance(BNC, &alice), bnc_before); - - run_to(block); - assert_schedule_gone(&alice, id); - assert_eq!(Currencies::total_balance(BNC, &alice), bnc_before); - }); -} - -#[test] -fn migration_should_convert_when_price_stability_check_would_have_failed() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - // A zero threshold makes `prepare_schedule` reject any price movement. The migration - // branch runs before that check, so conversion must not care. - let mut schedule = default_sell_schedule(alice.clone()); - schedule.stability_threshold = Some(Permill::zero()); - - let (id, block) = schedule_dca(alice.clone(), schedule); - enable_migration(); - run_to(block); - - assert!(find_migrated_intent_id(id).is_some()); - }); -} - -#[test] -fn migration_should_convert_when_schedule_has_pending_retries() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - pallet_dca::RetriesOnError::::insert(id, 2); - enable_migration(); - run_to(block); - - assert!(find_migrated_intent_id(id).is_some()); - assert_schedule_gone(&alice, id); - }); -} - -// === C. Cancellation === - -#[test] -fn migration_should_cancel_and_refund_when_order_is_buy() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let block = hydradx_runtime::System::block_number() + 2; - let id = plant_schedule(buy_schedule(alice.clone()), block); - let free_before = Currencies::free_balance(HDX, &alice); - enable_migration(); - - let mark = event_mark(); - run_to(block); - - assert_eq!(Currencies::free_balance(HDX, &alice), free_before + BUDGET); - assert_eq!(Currencies::reserved_balance_named(&DCA_RESERVE_ID, HDX, &alice), 0); - assert_schedule_gone(&alice, id); - assert!(find_migrated_intent_id(id).is_none()); - assert!(dca_events_since(mark).iter().any(|e| matches!( - e, - pallet_dca::Event::MigrationCancelled { - reason: CancelReason::BuyOrder, - .. - } - ))); - }); -} - -#[test] -fn migration_should_cancel_when_remaining_budget_is_below_one_trade() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - // Simulate a nearly-spent schedule: less than one trade left. - let leftover = AMOUNT_IN / 2; - pallet_dca::RemainingAmounts::::insert(id, leftover); - let free_before = Currencies::free_balance(HDX, &alice); - enable_migration(); - - let mark = event_mark(); - run_to(block); - - assert_eq!(Currencies::free_balance(HDX, &alice), free_before + leftover); - assert_schedule_gone(&alice, id); - assert!(dca_events_since(mark).iter().any(|e| matches!( - e, - pallet_dca::Event::MigrationCancelled { - reason: CancelReason::BudgetBelowTrade, - .. - } - ))); - }); -} - -// === D. Reserve conservation === - -#[test] -fn migration_should_move_reserve_exactly_when_budget_is_fixed() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - let free_before = Currencies::free_balance(HDX, &alice); - enable_migration(); - - run_to(block); - - assert_eq!(Currencies::reserved_balance_named(&DCA_RESERVE_ID, HDX, &alice), 0); - assert_eq!( - Currencies::reserved_balance_named(&INTENT_RESERVE_ID, HDX, &alice), - BUDGET - ); - assert_eq!(Currencies::free_balance(HDX, &alice), free_before); - assert_eq!(dca_data(migrated_intent_id(id)).remaining_budget, BUDGET); - }); -} - -#[test] -fn migration_should_release_excess_reserve_when_schedule_is_rolling() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca( - alice.clone(), - sell_schedule(alice.clone(), 0, ROLLING_AMOUNT_IN, MIN_OUT_BNC), - ); - let dca_reserve = pallet_dca::RemainingAmounts::::get(id).unwrap(); - let free_before = Currencies::free_balance(HDX, &alice); - enable_migration(); - - run_to(block); - - // The intent pallet reserves 2x the trade amount for a rolling DCA; the old pallet also - // reserved the transaction fee, and that difference goes back to the owner. - let intent_reserve = ROLLING_AMOUNT_IN * 2; - assert_eq!( - Currencies::reserved_balance_named(&INTENT_RESERVE_ID, HDX, &alice), - intent_reserve - ); - assert_eq!(Currencies::reserved_balance_named(&DCA_RESERVE_ID, HDX, &alice), 0); - assert_eq!( - Currencies::free_balance(HDX, &alice), - free_before + dca_reserve - intent_reserve - ); - assert_eq!(dca_data(migrated_intent_id(id)).budget, None); - }); -} - -#[test] -fn conservation_should_hold_when_mixed_batch_migrates_and_cancels() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let block = hydradx_runtime::System::block_number() + 2; - let sell_id = plant_schedule(default_sell_schedule(alice.clone()), block); - let buy_id = plant_schedule(buy_schedule(alice.clone()), block); - - let free_before = Currencies::free_balance(HDX, &alice); - let dca_before = Currencies::reserved_balance_named(&DCA_RESERVE_ID, HDX, &alice); - let intent_before = Currencies::reserved_balance_named(&INTENT_RESERVE_ID, HDX, &alice); - - enable_migration(); - run_to(block); - - let free_after = Currencies::free_balance(HDX, &alice); - let dca_after = Currencies::reserved_balance_named(&DCA_RESERVE_ID, HDX, &alice); - let intent_after = Currencies::reserved_balance_named(&INTENT_RESERVE_ID, HDX, &alice); - - assert_eq!( - free_before + dca_before + intent_before, - free_after + dca_after + intent_after, - "nothing created or destroyed" - ); - assert!(find_migrated_intent_id(sell_id).is_some()); - assert!(find_migrated_intent_id(buy_id).is_none()); - }); -} - -// === E. Interaction with the rest of the runtime === - -#[test] -fn solution_should_include_migrated_dca_and_organic_intent_together() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - let bob: AccountId = BOB.into(); - - let driver = driver_with_funded_alice(); - driver.endow_account(bob.clone(), HDX, 10 * BUDGET); - driver.execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - enable_migration(); - run_to(block); - let migrated = migrated_intent_id(id); - - // Bob submits a plain swap intent that becomes eligible immediately. - for _ in 0..PERIOD { - hydradx_run_to_next_block(); - } - assert_ok!(hydradx_runtime::Intent::submit_intent( - RuntimeOrigin::signed(bob.clone()), - pallet_intent::types::IntentInput { - data: ice_support::IntentDataInput::Swap(ice_support::SwapParams { - asset_in: HDX, - asset_out: BNC, - amount_in: AMOUNT_IN, - amount_out: MIN_OUT_BNC, - partial: false, - }), - deadline: Some( - ::TimestampProvider::now() + 1_000_000, - ), - on_resolved: None, - } - )); - - let solution = run_solver_and_submit(); - assert_eq!(solution.resolved_intents.len(), 2, "both intents in one solution"); - assert!(solution.resolved_intents.iter().any(|r| r.id == migrated)); - }); -} - -#[test] -fn migration_should_handle_a_full_block_of_schedules() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let block = hydradx_runtime::System::block_number() + 2; - let max = ::MaxSchedulePerBlock::get(); - - let mut ids = vec![]; - for i in 0..max { - // Mix converts and cancels in the same block. - let schedule = if i % 2 == 0 { - default_sell_schedule(alice.clone()) - } else { - buy_schedule(alice.clone()) - }; - ids.push((i % 2 == 0, plant_schedule(schedule, block))); - } - - enable_migration(); - run_to(block); - - for (should_migrate, id) in ids { - assert_schedule_gone(&alice, id); - assert_eq!(find_migrated_intent_id(id).is_some(), should_migrate, "schedule {id}"); - } - assert!(pallet_dca::ScheduleIdsPerBlock::::get(block).is_empty()); - }); -} - -#[test] -fn migration_should_bypass_cap_when_owner_is_at_max_intents_per_account() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - - // Pretend the owner already holds the maximum number of intents. - let cap: u32 = ::MaxIntentsPerAccount::get(); - pallet_intent::AccountIntentCount::::insert(&alice, cap); - - enable_migration(); - run_to(block); - - assert!(find_migrated_intent_id(id).is_some(), "cap must not block a migration"); - }); -} - -#[test] -fn schedule_should_fail_when_migration_is_enabled() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - enable_migration(); - - assert_noop!( - DCA::schedule( - RuntimeOrigin::signed(alice.clone()), - default_sell_schedule(alice.clone()), - None - ), - pallet_dca::Error::::MigrationInProgress - ); - }); -} - -#[test] -fn terminate_should_refund_normally_when_called_after_flag_flip() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, _) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - let free_before = Currencies::free_balance(HDX, &alice); - enable_migration(); - - assert_ok!(DCA::terminate(RuntimeOrigin::signed(alice.clone()), id, None)); - - assert_eq!(Currencies::free_balance(HDX, &alice), free_before + BUDGET); - assert_schedule_gone(&alice, id); - }); -} - -// === F. Termination and drain === - -#[test] -fn all_schedules_should_be_gone_when_the_longest_period_has_elapsed() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let start = hydradx_runtime::System::block_number(); - let longest_period = 40u32; - - let mut sells = vec![]; - for period in [PERIOD, 20, longest_period] { - let mut schedule = default_sell_schedule(alice.clone()); - schedule.period = period; - let (id, _) = schedule_dca(alice.clone(), schedule); - sells.push(id); - } - let buy_id = plant_schedule(buy_schedule(alice.clone()), start + longest_period); - - enable_migration(); - run_to(start + longest_period + 1); - - assert_eq!( - pallet_dca::Schedules::::iter().count(), - 0, - "every schedule resolves within one longest-period window" - ); - for id in sells { - assert!(find_migrated_intent_id(id).is_some()); - } - assert!(find_migrated_intent_id(buy_id).is_none()); - }); -} - -#[test] -fn schedule_should_be_migrated_exactly_once_when_slot_is_visited() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - enable_migration(); - - let mark = event_mark(); - run_to(block + 3 * PERIOD); - - assert_eq!(pallet_intent::Intents::::iter().count(), 1, "one intent only"); - assert_eq!( - dca_events_since(mark) - .iter() - .filter(|e| matches!(e, pallet_dca::Event::Migrated { .. })) - .count(), - 1 - ); - assert!(find_migrated_intent_id(id).is_some()); - }); -} - -#[test] -fn force_cancel_should_remove_schedule_when_it_has_no_planned_block() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - // Orphan it: reachable in `Schedules` but never visited by `on_initialize`. - pallet_dca::ScheduleIdsPerBlock::::remove(block); - pallet_dca::ScheduleExecutionBlock::::remove(id); - - enable_migration(); - - let mark = event_mark(); - run_to(block + 1); - assert!( - pallet_dca::Schedules::::get(id).is_some(), - "orphan survives the drain" - ); - - let free_before = Currencies::free_balance(HDX, &alice); - assert_ok!(DCA::force_cancel_schedules(RuntimeOrigin::root(), vec![id])); - - assert_eq!(Currencies::free_balance(HDX, &alice), free_before + BUDGET); - assert_schedule_gone(&alice, id); - assert!(dca_events_since(mark).iter().any(|e| matches!( - e, - pallet_dca::Event::MigrationCancelled { - reason: CancelReason::ForceCancelled, - .. - } - ))); - }); -} - -#[test] -fn old_execution_should_resume_when_flag_is_disabled_again() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - enable_migration(); - assert_ok!(DCA::set_migration_enabled(RuntimeOrigin::root(), false)); - - let bnc_before = Currencies::total_balance(BNC, &alice); - run_to(block); - - // Flag off: the schedule traded on the old path and replanned. - assert!(find_migrated_intent_id(id).is_none()); - assert!(Currencies::total_balance(BNC, &alice) > bnc_before); - let next_block = pallet_dca::ScheduleExecutionBlock::::get(id).expect("replanned"); - - // Flag back on: the next slot converts it. - enable_migration(); - run_to(next_block); - assert!(find_migrated_intent_id(id).is_some()); - }); -} - -// === G. Events and the indexer contract === - -#[test] -fn migrated_event_should_carry_schedule_and_intent_id() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - enable_migration(); - - let mark = event_mark(); - run_to(block); - - let intent_id = migrated_intent_id(id); - let migrated = dca_events_since(mark) - .into_iter() - .find_map(|e| match e { - pallet_dca::Event::Migrated { - id: schedule_id, - who, - intent_id, - } => Some((schedule_id, who, intent_id)), - _ => None, - }) - .expect("Migrated event"); - - assert_eq!(migrated, (id, alice.clone(), intent_id)); - assert!(pallet_intent::Intents::::get(intent_id).is_some()); - }); -} - -#[test] -fn cancelled_event_should_carry_reason_and_refund_amount() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let block = hydradx_runtime::System::block_number() + 2; - let id = plant_schedule(buy_schedule(alice.clone()), block); - enable_migration(); - - let mark = event_mark(); - run_to(block); - - let cancelled = dca_events_since(mark) - .into_iter() - .find_map(|e| match e { - pallet_dca::Event::MigrationCancelled { - id, - who, - asset, - refunded, - reason, - } => Some((id, who, asset, refunded, reason)), - _ => None, - }) - .expect("MigrationCancelled event"); - - assert_eq!(cancelled, (id, alice.clone(), HDX, BUDGET, CancelReason::BuyOrder)); - }); -} - -// === H. Post-migration intent semantics === - -#[test] -fn migrated_intent_should_carry_original_slippage_and_limits() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let slippage = Permill::from_percent(7); - let mut schedule = default_sell_schedule(alice.clone()); - schedule.slippage = Some(slippage); - - let (id, block) = schedule_dca(alice.clone(), schedule); - enable_migration(); - run_to(block); - - let dca = dca_data(migrated_intent_id(id)); - assert_eq!(dca.slippage, slippage); - assert_eq!(dca.asset_in, HDX); - assert_eq!(dca.asset_out, BNC); - assert_eq!(dca.amount_in, AMOUNT_IN); - assert_eq!(dca.amount_out, MIN_OUT_BNC); - assert_eq!(dca.period, PERIOD); - assert_eq!(dca.budget, Some(BUDGET)); - assert_eq!(dca.remaining_budget, BUDGET); - assert_eq!(dca.last_execution_block, block - PERIOD); - }); -} - -#[test] -fn migrated_intent_should_clamp_amount_out_to_existential_deposit_when_schedule_limit_is_dust() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - // Old-DCA users routinely leave `min_amount_out` at dust; the conversion lifts it to the ED - // rather than cancelling the schedule. - let ed_out = as Inspect>::existential_deposit(BNC).unwrap(); - let (id, block) = schedule_dca(alice.clone(), sell_schedule(alice.clone(), BUDGET, AMOUNT_IN, 1)); - enable_migration(); - run_to(block); - - let intent_id = migrated_intent_id(id); - assert_eq!(dca_data(intent_id).amount_out, ed_out); - - let bnc_before = Currencies::total_balance(BNC, &alice); - let solution = advance_and_solve(PERIOD); - assert_eq!(solution.resolved_intents.len(), 1); - assert_eq!(solution.resolved_intents[0].id, intent_id); - assert_eq!(dca_data(intent_id).remaining_budget, BUDGET - AMOUNT_IN); - - // The clamped hard limit is not what bound the fill - the oracle floor is far above it, and - // the trade cleared that floor. - let floor = pallet_intent::Pallet::::compute_dca_effective_limit(&dca_data(intent_id)); - let received = Currencies::total_balance(BNC, &alice) - bnc_before; - assert!( - floor > ed_out, - "oracle floor {floor} should dominate the ED clamp {ed_out}" - ); - assert!( - received >= floor, - "fill {received} paid less than the oracle floor {floor}" - ); - }); -} - -#[test] -fn migrated_intent_should_complete_when_budget_is_below_one_trade() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - // Two trades' worth of budget, so the intent closes after the second fill. - let budget = 2 * AMOUNT_IN; - let (id, block) = schedule_dca( - alice.clone(), - sell_schedule(alice.clone(), budget.max(1_000 * UNITS), AMOUNT_IN, MIN_OUT_BNC), - ); - enable_migration(); - run_to(block); - let intent_id = migrated_intent_id(id); - - let budget = dca_data(intent_id).remaining_budget; - let fills = (budget / AMOUNT_IN) as u32; - for _ in 0..fills { - advance_and_solve(PERIOD); - } - - let leftover = budget - u128::from(fills) * AMOUNT_IN; - assert!(leftover < AMOUNT_IN); - assert!( - pallet_intent::Intents::::get(intent_id).is_none(), - "intent closes once the budget cannot fund another trade" - ); - assert_eq!( - Currencies::reserved_balance_named(&INTENT_RESERVE_ID, HDX, &alice), - 0, - "reserve fully released" - ); - }); -} - -#[test] -fn dormant_intent_should_refund_when_owner_removes_it() { - TestNet::reset(); - let alice: AccountId = ALICE.into(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - enable_migration(); - run_to(block); - let intent_id = migrated_intent_id(id); - - let free_before = Currencies::free_balance(HDX, &alice); - assert_ok!(hydradx_runtime::Intent::remove_intent( - RuntimeOrigin::signed(alice.clone()), - intent_id - )); - - assert_eq!(Currencies::free_balance(HDX, &alice), free_before + BUDGET); - assert_eq!(Currencies::reserved_balance_named(&INTENT_RESERVE_ID, HDX, &alice), 0); - }); -} - -// === I. Old path vs. migrated path === - -/// The outcome of running one schedule to `n` fills, measured on whichever path produced it. -#[derive(Default, Debug, Clone, Copy)] -struct Fills { - first_block: u32, - last_block: u32, - amount_out: u128, - /// What the fills took out of the schedule's budget. - budget_spent: u128, - /// What they cost the owner overall - budget plus anything the path charged elsewhere. - hdx_spent: u128, -} - -impl Fills { - /// BNC received per HDX the owner actually parted with, scaled to survive integer division. - fn price(&self) -> u128 { - self.amount_out.saturating_mul(UNITS) / self.hdx_spent - } -} - -/// Runs the schedule on the old DCA path until it has executed `count` times, first at `first_block`. -/// -/// The schedule is planted rather than scheduled so the caller can line the first execution up with -/// the migrated path's first fill, putting both against the same pool state. -fn old_dca_fills(first_block: u32, count: u32) -> Fills { - let alice: AccountId = ALICE.into(); - let mut fills = Fills::default(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let id = plant_schedule(default_sell_schedule(alice.clone()), first_block); - let bnc_before = Currencies::total_balance(BNC, &alice); - let hdx_before = Currencies::total_balance(HDX, &alice); - - run_to(first_block + (count - 1) * PERIOD); - assert_eq!( - pallet_dca::ScheduleExecutionBlock::::get(id), - Some(first_block + count * PERIOD), - "schedule should have executed exactly {count} times" - ); - - fills = Fills { - first_block, - last_block: hydradx_runtime::System::block_number(), - amount_out: Currencies::total_balance(BNC, &alice) - bnc_before, - budget_spent: BUDGET - pallet_dca::RemainingAmounts::::get(id).unwrap_or_default(), - hdx_spent: hdx_before - Currencies::total_balance(HDX, &alice), - }; - }); - - fills -} - -/// Migrates the same schedule and lets the solver fill it `count` times. -fn migrated_intent_fills(count: u32) -> Fills { - let alice: AccountId = ALICE.into(); - let mut fills = Fills::default(); - - driver_with_funded_alice().execute(|| { - enable_slip_fees(); - - let (id, block) = schedule_dca(alice.clone(), default_sell_schedule(alice.clone())); - enable_migration(); - run_to(block); - let intent_id = migrated_intent_id(id); - - let bnc_before = Currencies::total_balance(BNC, &alice); - let hdx_before = Currencies::total_balance(HDX, &alice); - - let mut first_block = 0; - for fill in 0..count { - advance_and_solve(PERIOD); - if fill == 0 { - first_block = hydradx_runtime::System::block_number(); - } - } - - fills = Fills { - first_block, - last_block: hydradx_runtime::System::block_number(), - amount_out: Currencies::total_balance(BNC, &alice) - bnc_before, - budget_spent: BUDGET - dca_data(intent_id).remaining_budget, - hdx_spent: hdx_before - Currencies::total_balance(HDX, &alice), - }; - }); - - fills -} - -/// Asserts the two paths bought within `tolerance_bps` of each other and that the migrated one is -/// not the worse deal per HDX spent. -fn assert_comparable(old: Fills, new: Fills, tolerance_bps: u128) { - println!("old {old:?} price {}", old.price()); - println!("new {new:?} price {}", new.price()); - - let gap = old.amount_out.abs_diff(new.amount_out); - assert!( - gap.saturating_mul(10_000) <= old.amount_out.saturating_mul(tolerance_bps), - "amount out differs by more than {tolerance_bps} bps: old {} vs new {}", - old.amount_out, - new.amount_out - ); - - assert!( - new.price() >= old.price(), - "migrated fill priced worse: old {} vs new {}", - old.price(), - new.price() - ); -} - -/// The same sell, executed at the same height against the same pool state, on both paths. -#[test] -fn migrated_intent_should_fill_like_old_dca_on_a_single_execution() { - TestNet::reset(); - - let new = migrated_intent_fills(1); - let old = old_dca_fills(new.first_block, 1); - assert_eq!( - old.last_block, new.last_block, - "comparison is only fair at equal height" - ); - - // The solver executes marginally better than the router, then hands back 0.02% as the ICE - // protocol fee, so the output lands about a basis point under the old path's. - assert_comparable(old, new, 10); - - // The old path takes a per-execution transaction fee out of the budget; the intent path - // charges nothing beyond the trade itself. - assert_eq!(new.budget_spent, AMOUNT_IN); - assert_eq!(new.hdx_spent, AMOUNT_IN); - assert!(old.hdx_spent > AMOUNT_IN, "old path takes an execution fee"); -} - -/// Three fills on each path. Only the first is height-aligned - the solver needs a block of its -/// own per fill - so this checks that the gap stays flat rather than compounding. -#[test] -fn migrated_intent_should_fill_like_old_dca_over_three_executions() { - TestNet::reset(); - - let new = migrated_intent_fills(3); - let old = old_dca_fills(new.first_block, 3); - - assert_comparable(old, new, 10); - assert_eq!(new.budget_spent, 3 * AMOUNT_IN); - assert!(old.budget_spent > 3 * AMOUNT_IN); -} diff --git a/integration-tests/src/ice/mod.rs b/integration-tests/src/ice/mod.rs index e1441821bd..4ed55a7eda 100644 --- a/integration-tests/src/ice/mod.rs +++ b/integration-tests/src/ice/mod.rs @@ -4,7 +4,6 @@ pub const PATH_TO_SNAPSHOT: &str = "snapshots/ice/mainnet_apr"; mod cross_pair; mod dca; mod dca_early; -mod dca_migration; mod forward; pub(crate) mod harness; mod match_first; diff --git a/integration-tests/src/ice/solver.rs b/integration-tests/src/ice/solver.rs index 7dc1db498d..f0332fcfe9 100644 --- a/integration-tests/src/ice/solver.rs +++ b/integration-tests/src/ice/solver.rs @@ -7467,12 +7467,8 @@ fn solver_v2_cross_atoken_trades_with_matching() { }); } -/// Same setup as DCA's `dca_succeeds_after_extra_gas_increased_due_to_out_of_gas_error`: -/// deploy a ConditionalGasEater ERC20 contract, add it to the omnipool, then try to -/// sell it for HDX via an ICE intent instead of DCA. -/// -/// The DCA test fails with out-of-gas on the first trade attempt. This test checks -/// whether the same trade via ICE/intent also hits out-of-gas or not. +/// Deploys a ConditionalGasEater ERC20, adds it to the omnipool, then sells it for HDX via an +/// ICE intent to check whether the trade hits out-of-gas. #[test] fn ice_intent_with_evm_gas_eater_token() { use crate::polkadot_test_net::{hydradx_run_to_block, HDX, LRNA, UNITS}; @@ -7486,13 +7482,13 @@ fn ice_intent_with_evm_gas_eater_token() { TestNet::reset(); Hydra::execute_with(|| { // ============================================================ - // SETUP: same as the DCA out-of-gas test + // SETUP // ============================================================ - crate::dca::init_omnipool_with_oracle_for_block_10(); + crate::utils::pools::init_omnipool_with_oracle_for_block_10(); let evm_address = EVMAccounts::evm_address(&Router::router_account()); let contract = - crate::dca::extra_gas_erc20::deploy_conditional_gas_eater(evm_address, 400_000, crate::erc20::deployer()); + crate::utils::contracts::deploy_conditional_gas_eater(evm_address, 400_000, crate::erc20::deployer()); let erc20 = crate::erc20::bind_erc20(contract); assert_ok!(EmaOracle::add_oracle( RuntimeOrigin::root(), @@ -7531,7 +7527,7 @@ fn ice_intent_with_evm_gas_eater_token() { ); // ============================================================ - // INTENT: sell the gas-eater ERC20 for HDX (same trade as DCA) + // INTENT: sell the gas-eater ERC20 for HDX // ============================================================ let sell_amount = 200_000 * UNITS; let ts = hydradx_runtime::Timestamp::now(); diff --git a/integration-tests/src/lib.rs b/integration-tests/src/lib.rs index 08c3387273..a1014f1e71 100644 --- a/integration-tests/src/lib.rs +++ b/integration-tests/src/lib.rs @@ -1,5 +1,5 @@ #![cfg(test)] -// DCA pallet uses dummy router for benchmarks and some tests fail when benchmarking feature is enabled +// Benchmark builds wire dummy routers and price providers into the runtime, which breaks these tests #![cfg(not(feature = "runtime-benchmarks"))] mod aave_router; mod aave_simulator; @@ -10,7 +10,7 @@ mod cerebro_diff; mod circuit_breaker; mod contracts; mod cross_chain_transfer; -mod dca; +mod dca_retirement; mod deposit_limiter; mod dispatcher; mod driver; diff --git a/integration-tests/src/multi_payment.rs b/integration-tests/src/multi_payment.rs index b262b61ca7..45da3579e9 100644 --- a/integration-tests/src/multi_payment.rs +++ b/integration-tests/src/multi_payment.rs @@ -30,8 +30,8 @@ fn set_currency_should_fail_when_insufficient_asset_has_xyk_dot_pool() { hydradx_runtime::AssetRegistry::set_location(DOT, DOT_ASSET_LOCATION).unwrap(); //Arrange - crate::dca::init_omnipool_with_oracle_for_block_10(); - crate::dca::add_dot_as_payment_currency(); + crate::utils::pools::init_omnipool_with_oracle_for_block_10(); + crate::utils::pools::add_dot_as_payment_currency(); let name = b"INSUF1".to_vec(); let insufficient_asset = AssetRegistry::register_insufficient_asset( @@ -80,8 +80,8 @@ fn insufficient_asset_should_not_be_set_as_currency_when_pool_doesnt_exist() { hydradx_runtime::AssetRegistry::set_location(DOT, DOT_ASSET_LOCATION).unwrap(); //Arrange - crate::dca::init_omnipool_with_oracle_for_block_10(); - //crate::dca::add_dot_as_payment_currency(); + crate::utils::pools::init_omnipool_with_oracle_for_block_10(); + //crate::utils::pools::add_dot_as_payment_currency(); let name = b"INSUF1".to_vec(); let insufficient_asset = AssetRegistry::register_insufficient_asset( @@ -117,8 +117,8 @@ fn set_currency_should_fail_when_sufficient_asset_is_not_accepted() { hydradx_runtime::AssetRegistry::set_location(DOT, DOT_ASSET_LOCATION).unwrap(); //Arrange - crate::dca::init_omnipool_with_oracle_for_block_10(); - crate::dca::add_dot_as_payment_currency(); + crate::utils::pools::init_omnipool_with_oracle_for_block_10(); + crate::utils::pools::add_dot_as_payment_currency(); let name = b"INSUF1".to_vec(); let sufficient_but_not_accepted_asset = AssetRegistry::register_sufficient_asset( @@ -224,7 +224,7 @@ fn set_currency_in_batch_should_fail_for_unaccepted_asset_with_oracle_price() { let _ = with_transaction(|| { // Arrange let dot = DOT; - crate::dca::init_omnipool_with_oracle_for_block_10(); + crate::utils::pools::init_omnipool_with_oracle_for_block_10(); assert_ok!(Currencies::update_balance( hydradx_runtime::RuntimeOrigin::root(), Omnipool::protocol_account(), diff --git a/integration-tests/src/otc.rs b/integration-tests/src/otc.rs index 8abb69a7ea..c7e9836d24 100644 --- a/integration-tests/src/otc.rs +++ b/integration-tests/src/otc.rs @@ -153,9 +153,8 @@ fn settle_otc_order_should_not_over_mint_shares_when_maker_underpays_for_stables TestNet::reset(); Hydra::execute_with(|| { let _ = with_transaction(|| { - // StableSwap pool set up the same way as the router/DCA integration tests. `pool_id` is the - // pool's share token; `asset_b` is one of the pooled stablecoins. - let (pool_id, _asset_a, asset_b) = crate::dca::init_stableswap().unwrap(); + // `pool_id` is the pool's share token; `asset_b` is one of the pooled stablecoins. + let (pool_id, _asset_a, asset_b) = crate::utils::pools::init_stableswap().unwrap(); // The route the settlement buys shares through: depositing `asset_b` into the pool. It is an // add-liquidity because the output asset is the share token `pool_id`. diff --git a/integration-tests/src/polkadot_test_net.rs b/integration-tests/src/polkadot_test_net.rs index b1f5106868..f078eb224f 100644 --- a/integration-tests/src/polkadot_test_net.rs +++ b/integration-tests/src/polkadot_test_net.rs @@ -854,7 +854,6 @@ pub fn go_to_block(number: BlockNumber) { hydradx_runtime::TransactionPayment::on_finalize(current_block); hydradx_runtime::MultiTransactionPayment::on_finalize(current_block); hydradx_runtime::CircuitBreaker::on_finalize(current_block); - hydradx_runtime::DCA::on_finalize(current_block); hydradx_runtime::Dispatcher::on_finalize(current_block); hydradx_runtime::EmaOracle::on_finalize(current_block); hydradx_runtime::EVM::on_finalize(current_block); @@ -914,7 +913,6 @@ pub fn go_to_block(number: BlockNumber) { hydradx_runtime::MultiTransactionPayment::on_initialize(number); hydradx_runtime::CircuitBreaker::on_initialize(number); hydradx_runtime::DynamicEvmFee::on_initialize(number); - hydradx_runtime::DCA::on_initialize(number); hydradx_runtime::EmaOracle::on_initialize(number); hydradx_runtime::EVM::on_initialize(number); hydradx_runtime::Ethereum::on_initialize(number); @@ -948,29 +946,6 @@ pub fn hydradx_finalize_block() { hydradx_runtime::MultiTransactionPayment::on_finalize(b); } -pub fn rococo_run_to_block(to: BlockNumber) { - use frame_support::traits::OnFinalize; - - while hydradx_runtime::System::block_number() < to { - let b = hydradx_runtime::System::block_number(); - - hydradx_runtime::System::on_finalize(b); - hydradx_runtime::MultiTransactionPayment::on_finalize(b); - hydradx_runtime::CircuitBreaker::on_finalize(b); - hydradx_runtime::DCA::on_finalize(b); - hydradx_runtime::EmaOracle::on_finalize(b); - - hydradx_runtime::System::on_initialize(b + 1); - hydradx_runtime::MultiTransactionPayment::on_initialize(b + 1); - hydradx_runtime::CircuitBreaker::on_initialize(b + 1); - hydradx_runtime::DynamicEvmFee::on_initialize(b + 1); - hydradx_runtime::DCA::on_initialize(b + 1); - hydradx_runtime::EmaOracle::on_initialize(b + 1); - - hydradx_runtime::System::set_block_number(b + 1); - } -} - /// Opt every Aave reserve on the snapshot into the solver's routing. /// /// Aave is opt-in like XYK and Uniswap, so without this the solver sees no wrap and @@ -1030,6 +1005,8 @@ pub fn hydra_live_ext( let mut p = builder.build().await.unwrap(); p.execute_with(|| { + // Snapshot events of retired pallets (e.g. DCA) no longer decode and would empty `System::events()`. + hydradx_runtime::System::reset_events(); hydradx_runtime::Parameters::set_relay_parent_offset_override(true); pallet_ema_oracle::migrations::v1::MigrateV0ToV1::::on_runtime_upgrade(); pallet_stableswap::migrations::v2::MigrateV1ToV2::::on_runtime_upgrade(); diff --git a/integration-tests/src/uniswap_v3_router.rs b/integration-tests/src/uniswap_v3_router.rs index e53032009d..e16b3da6fb 100644 --- a/integration-tests/src/uniswap_v3_router.rs +++ b/integration-tests/src/uniswap_v3_router.rs @@ -1,6 +1,5 @@ #![cfg(test)] -use crate::dca::schedule_fake_with_sell_order; use crate::polkadot_test_net::*; use frame_support::assert_noop; use frame_support::assert_ok; @@ -8,7 +7,7 @@ use hex_literal::hex; use hydradx_runtime::evm::uniswap_v3_trade_executor::UniswapV3; use hydradx_runtime::{ AssetId, AssetRegistry, Currencies, Dispatcher, Parameters, Router, Runtime, RuntimeCall, RuntimeEvent, - RuntimeOrigin, System, Treasury, DCA, + RuntimeOrigin, System, Treasury, }; use hydradx_traits::router::{ExecutorError, PoolType, Trade}; use hydradx_traits::OraclePeriod; @@ -45,10 +44,6 @@ const FEE_TIER: u32 = 3000; const SELL_AMOUNT: Balance = 1_000_000_000; /// 100 aDOT — well inside what the treasury holds in the snapshot (~361). const FUND_ASSET_IN: Balance = 1_000_000_000_000; -/// DCA enforces `amount_in >= transaction_fee * 20` and a total budget of at -/// least `MinBudgetInNativeCurrency` (1000 HDX), both converted into the sold -/// asset — so a DCA leg needs far more than `SELL_AMOUNT`. 5 aDOT per trade. -const DCA_SELL_AMOUNT: Balance = 50_000_000_000; /// 100 HOLLAR (18 decimals). const FUND_ASSET_OUT: Balance = 100_000_000_000_000_000_000; const FUND_GAS: Balance = 1_000_000_000_000_000_000; @@ -292,9 +287,8 @@ fn router_sell_should_emit_uniswap_v3_filler_event() { /// A swap through a v3 pool must leave an EMA-oracle entry behind it. /// /// Without one, `OraclePriceProvider` has nothing to return for a `UniswapV3` leg and -/// every consumer reads that as failure: `pallet-dca` treats it as "price unstable" -/// and terminates the schedule, and `route-executor::set_route` rejects the route with -/// `RouteHasNoOracle`. Reading a live `slot0` price instead would satisfy both callers +/// every consumer reads that as failure: `route-executor::set_route` rejects the route with +/// `RouteHasNoOracle`. Reading a live `slot0` price instead would satisfy its callers /// while quietly removing the manipulation resistance they exist to provide, so the /// executor reports to the oracle and this is the test that it does. #[test] @@ -333,117 +327,6 @@ fn swap_should_feed_the_ema_oracle_under_the_uniswap_v3_source() { }); } -/// The whole point of the oracle wiring: a DCA schedule routed through a v3 pool has to -/// survive execution. Before the `UniswapV3` arm existed it was terminated after -/// `MaxNumberOfRetriesOnError` retries, reporting `PriceUnstable` — which was never true, -/// the price simply could not be looked up. -#[test] -fn dca_should_execute_through_a_uniswap_v3_leg_once_the_pool_has_oracle_history() { - with_uniswap_v3(|| { - // Prime the oracle: a DCA leg cannot be priced until the pair has traded. - assert_ok!(Router::sell( - RuntimeOrigin::signed(ALICE.into()), - ASSET_IN, - ASSET_OUT, - SELL_AMOUNT, - 0, - uniswap_route().try_into().unwrap(), - )); - hydradx_run_to_next_block(); - - let budget = DCA_SELL_AMOUNT * 10; - let schedule = schedule_fake_with_sell_order( - ALICE, - PoolType::UniswapV3(FEE_TIER), - budget, - ASSET_IN, - ASSET_OUT, - DCA_SELL_AMOUNT, - ); - // A mainnet snapshot already carries schedules, so id 0 is not ours. - let schedule_id = DCA::next_schedule_id(); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE.into()), schedule, None)); - - // A mainnet snapshot's near-term blocks are already full of real schedules, - // so the first execution can be pushed well past the next block. Take the - // planned block from the event rather than guessing how long to run. - let planned_at = System::events() - .into_iter() - .find_map(|record| match record.event { - RuntimeEvent::DCA(pallet_dca::Event::ExecutionPlanned { id, block, .. }) if id == schedule_id => { - Some(block) - } - _ => None, - }) - .expect("schedule should have been planned"); - - let before = Currencies::free_balance(ASSET_OUT, &ALICE.into()); - // Step block by block: `hydradx_run_to_block` jumps straight to the target, - // which skips `on_initialize` for every block in between — including the one - // the execution was planned for. - while System::block_number() <= planned_at { - hydradx_run_to_next_block(); - } - let after = Currencies::free_balance(ASSET_OUT, &ALICE.into()); - - // Executed at least once, and the schedule was not terminated. - assert!(after > before, "DCA should have executed through the v3 leg"); - assert!( - DCA::schedules(schedule_id).is_some(), - "schedule should still exist — it used to be terminated with PriceUnstable" - ); - }); -} - -#[test] -fn dca_should_retry_when_uniswap_v3_pool_cannot_take_the_full_amount() { - with_uniswap_v3(|| { - assert_ok!(alice_sells_hollar(1_000_000_000_000_000_000)); - hydradx_run_to_next_block(); - - let per_trade = oversized_hollar_sell() / 2; - fund_alice_from_treasury(ASSET_OUT, per_trade * 3); - let mut schedule = schedule_fake_with_sell_order( - ALICE, - PoolType::UniswapV3(FEE_TIER), - per_trade * 3, - ASSET_OUT, - ASSET_IN, - per_trade, - ); - schedule.slippage = Some(sp_runtime::Permill::from_percent(100)); - let schedule_id = DCA::next_schedule_id(); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE.into()), schedule, None)); - let planned_at = System::events() - .into_iter() - .find_map(|record| match record.event { - RuntimeEvent::DCA(pallet_dca::Event::ExecutionPlanned { id, block, .. }) if id == schedule_id => { - Some(block) - } - _ => None, - }) - .expect("schedule should have been planned"); - - while System::block_number() < planned_at { - hydradx_run_to_next_block(); - } - - let trade_error = System::events().into_iter().find_map(|record| match record.event { - RuntimeEvent::DCA(pallet_dca::Event::TradeFailed { id, error, .. }) if id == schedule_id => Some(error), - _ => None, - }); - assert_eq!( - trade_error, - Some(pallet_dispatcher::Error::::UniswapV3InsufficientLiquidity.into()) - ); - assert!( - DCA::schedules(schedule_id).is_some(), - "schedule was terminated instead of retried" - ); - assert_eq!(DCA::retries_on_error(schedule_id), 1); - }); -} - /// `get_liquidity_depth` must report the IN-RANGE liquidity, not the pool's balance. /// /// `route-executor::set_route` sizes its reference trade at 1% of this figure, so a diff --git a/integration-tests/src/utils/contracts.rs b/integration-tests/src/utils/contracts.rs index 464965ca84..afff211008 100644 --- a/integration-tests/src/utils/contracts.rs +++ b/integration-tests/src/utils/contracts.rs @@ -46,3 +46,15 @@ pub fn deploy_contract_code(code: Vec, deployer: EvmAddress) -> EvmAddress { pub fn deploy_contract(name: &str, deployer: EvmAddress) -> EvmAddress { deploy_contract_code(get_contract_bytecode(name), deployer) } + +/// ERC20 that burns `gas_to_waste` gas on every transfer to `router_address`. +pub fn deploy_conditional_gas_eater(router_address: EvmAddress, gas_to_waste: u64, deployer: EvmAddress) -> EvmAddress { + use ethabi::{encode, Token}; + + let mut bytecode = get_contract_bytecode("ConditionalGasEater"); + bytecode.extend(encode(&[ + Token::Address(router_address), + Token::Uint(gas_to_waste.into()), + ])); + deploy_contract_code(bytecode, deployer) +} diff --git a/integration-tests/src/utils/mod.rs b/integration-tests/src/utils/mod.rs index df21b1d966..eb08f9a250 100644 --- a/integration-tests/src/utils/mod.rs +++ b/integration-tests/src/utils/mod.rs @@ -1,3 +1,4 @@ pub(crate) mod accounts; pub(crate) mod contracts; pub(crate) mod executive; +pub(crate) mod pools; diff --git a/integration-tests/src/utils/pools.rs b/integration-tests/src/utils/pools.rs new file mode 100644 index 0000000000..5f2a2fa3a0 --- /dev/null +++ b/integration-tests/src/utils/pools.rs @@ -0,0 +1,179 @@ +use crate::polkadot_test_net::*; +use frame_support::assert_ok; +use hydradx_runtime::{ + AssetRegistry, Balances, Currencies, MultiTransactionPayment, Omnipool, Runtime, RuntimeOrigin, Stableswap, Tokens, + Treasury, +}; +use hydradx_traits::registry::{AssetKind, Create}; +use hydradx_traits::stableswap::AssetAmount; +use pallet_stableswap::MAX_ASSETS_IN_POOL; +use sp_runtime::{BoundedVec, DispatchError, FixedU128, Permill}; + +const TREASURY_ACCOUNT_INIT_BALANCE: Balance = 1000 * UNITS; + +/// HDX + DAI omnipool with a funded treasury and zero referral rewards. +pub fn init_omnipol() { + let native_price = FixedU128::from_float(0.5); + let stable_price = FixedU128::from_float(0.7); + let acc = Omnipool::protocol_account(); + + let stable_amount: Balance = 5_000_000_000_000_000_000_000u128; + let native_amount: Balance = 5_000_000_000_000_000_000_000u128; + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + acc.clone(), + DAI, + stable_amount, + 0 + )); + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + acc, + HDX, + native_amount as i128, + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + HDX, + native_price, + Permill::from_percent(60), + Omnipool::protocol_account(), + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + DAI, + stable_price, + Permill::from_percent(60), + Omnipool::protocol_account(), + )); + + assert_ok!(Balances::force_set_balance( + RawOrigin::Root.into(), + Treasury::account_id(), + TREASURY_ACCOUNT_INIT_BALANCE, + )); + + set_zero_reward_for_referrals(HDX); + set_zero_reward_for_referrals(DAI); +} + +pub fn init_omnipool_with_oracle_for_block_10() { + init_omnipol(); + do_trade_to_populate_oracle(DAI, HDX, UNITS); + go_to_block(10); + do_trade_to_populate_oracle(DAI, HDX, UNITS); +} + +fn do_trade_to_populate_oracle(asset_1: AssetId, asset_2: AssetId, amount: Balance) { + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + CHARLIE.into(), + LRNA, + 1000000000000 * UNITS, + 0, + )); + + assert_ok!(Omnipool::sell( + RuntimeOrigin::signed(CHARLIE.into()), + LRNA, + asset_1, + amount, + Balance::MIN + )); + + assert_ok!(Omnipool::sell( + RuntimeOrigin::signed(CHARLIE.into()), + LRNA, + asset_2, + amount, + Balance::MIN + )); +} + +pub fn add_dot_as_payment_currency() { + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + Omnipool::protocol_account(), + DOT, + (1000 * UNITS) as i128, + )); + + assert_ok!(MultiTransactionPayment::add_currency( + RuntimeOrigin::root(), + DOT, + FixedU128::from_rational(1, 100000), + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + DOT, + FixedU128::from_rational(10, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); +} + +/// A `MAX_ASSETS_IN_POOL`-asset stableswap pool funded by BOB. Returns `(pool_id, asset_in, asset_out)`. +pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { + let initial_liquidity = 1_000_000_000_000_000_000_000u128; + + let mut initial: Vec::AssetId>> = vec![]; + let mut asset_ids: Vec<::AssetId> = Vec::new(); + for idx in 0u32..MAX_ASSETS_IN_POOL { + let name: Vec = idx.to_ne_bytes().to_vec(); + let asset_id = AssetRegistry::register_sufficient_asset( + None, + Some(name.try_into().unwrap()), + AssetKind::Token, + 1u128, + Some(b"xDUM".to_vec().try_into().unwrap()), + Some(18u8), + None, + None, + )?; + + asset_ids.push(asset_id); + Currencies::update_balance( + RuntimeOrigin::root(), + AccountId::from(BOB), + asset_id, + initial_liquidity as i128, + )?; + initial.push(AssetAmount::new(asset_id, initial_liquidity)); + } + let pool_id = AssetRegistry::register_sufficient_asset( + None, + Some(b"pool".to_vec().try_into().unwrap()), + AssetKind::Token, + 1u128, + None, + None, + None, + None, + )?; + + let amplification = 100u16; + let fee = Permill::from_percent(1); + + let asset_in: AssetId = *asset_ids.last().unwrap(); + let asset_out: AssetId = *asset_ids.first().unwrap(); + + Stableswap::create_pool( + RuntimeOrigin::root(), + pool_id, + BoundedVec::truncate_from(asset_ids), + amplification, + fee, + )?; + + Stableswap::add_assets_liquidity( + RuntimeOrigin::signed(BOB.into()), + pool_id, + BoundedVec::truncate_from(initial), + Balance::zero(), + )?; + + Ok((pool_id, asset_in, asset_out)) +} diff --git a/node/Cargo.toml b/node/Cargo.toml index 6457d358b9..b731025ec1 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx" -version = "15.9.1" +version = "15.9.2" description = "Hydration node" authors = ["GalacticCouncil"] edition = "2021" diff --git a/node/cerebro-core/hydration/Cargo.toml b/node/cerebro-core/hydration/Cargo.toml index 9bb495edc6..22c8ef272b 100644 --- a/node/cerebro-core/hydration/Cargo.toml +++ b/node/cerebro-core/hydration/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "cerebro-hydration" -version = "0.1.0" +version = "0.1.1" edition = "2021" license = "Apache-2.0" description = "Hydration chain adapter: runtime-event decode, storage plumbing, reader-trait impls" @@ -19,7 +19,6 @@ pallet-xyk = { workspace = true, features = ["std"] } pallet-omnipool-liquidity-mining = { workspace = true, features = ["std"] } pallet-xyk-liquidity-mining = { workspace = true, features = ["std"] } pallet-route-executor = { workspace = true, features = ["std"] } -pallet-dca = { workspace = true, features = ["std"] } pallet-currencies = { workspace = true, features = ["std"] } pallet-staking = { workspace = true, features = ["std"] } pallet-otc = { workspace = true, features = ["std"] } diff --git a/node/cerebro-core/hydration/src/decode.rs b/node/cerebro-core/hydration/src/decode.rs index f0cb8fc007..c52fa0209c 100644 --- a/node/cerebro-core/hydration/src/decode.rs +++ b/node/cerebro-core/hydration/src/decode.rs @@ -4,7 +4,7 @@ use cerebro_core::model::{ChainEvent, DebtLeg, Notable, Phase, Trade, TransferLeg}; use cerebro_core::{AssetId, EvmAddress, NATIVE_ASSET}; -use codec::Decode; +use codec::{Compact, Decode}; use hydradx_runtime::RuntimeEvent; use primitives::AccountId; use sp_core::{H160, H256}; @@ -28,28 +28,68 @@ pub struct RawDebtLeg { /// `ChainEvent::AavePosition` with `asset` filled by the caller (see `map_block`). pub fn decode_events(events_raw: &[u8]) -> Result, String> { let mut input = events_raw; - let records: Vec = Decode::decode(&mut input).map_err(|e| format!("decode System.Events: {e}"))?; + let len = Compact::::decode(&mut input).map_err(|e| format!("decode System.Events: {e}"))?; + let records = (0..len.0) + .map(|_| decode_record(&mut input)) + .collect::, _>>()?; Ok(map_records(&records)) } +// Unboxed: boxing would allocate per record on the guard's hot path. +#[allow(clippy::large_enum_variant)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Record { + Runtime(EventRecord), + LegacyDca(frame_system::Phase, ChainEvent), +} + +impl Record { + pub fn phase(&self) -> &frame_system::Phase { + match self { + Record::Runtime(record) => &record.phase, + Record::LegacyDca(phase, _) => phase, + } + } +} + +fn decode_record(input: &mut &[u8]) -> Result { + if let Some(record) = legacy_dca::decode_record(input)? { + return Ok(record); + } + EventRecord::decode(input) + .map(Record::Runtime) + .map_err(|e| format!("decode EventRecord: {e}")) +} + +fn phase_of(phase: &frame_system::Phase) -> Phase { + match phase { + frame_system::Phase::ApplyExtrinsic(i) => Phase::ApplyExtrinsic(*i), + _ => Phase::Hook, + } +} + /// Decode records stored back to back with no length prefix, e.g. a suffix of `System.Events`. /// Every byte must belong to a whole record. -pub fn decode_record_stream(mut bytes: &[u8]) -> Result, String> { +pub fn decode_record_stream(mut bytes: &[u8]) -> Result, String> { let mut out = Vec::new(); while !bytes.is_empty() { - out.push(EventRecord::decode(&mut bytes).map_err(|e| format!("decode EventRecord: {e}"))?); + out.push(decode_record(&mut bytes)?); } Ok(out) } /// [`decode_events`] over already decoded records. -pub fn map_records(records: &[EventRecord]) -> Vec { +pub fn map_records(records: &[Record]) -> Vec { let mut out = Vec::new(); for rec in records { - let phase = match rec.phase { - frame_system::Phase::ApplyExtrinsic(i) => Phase::ApplyExtrinsic(i), - _ => Phase::Hook, + let rec = match rec { + Record::Runtime(rec) => rec, + Record::LegacyDca(phase, event) => { + out.push((phase_of(phase), event.clone(), None)); + continue; + } }; + let phase = phase_of(&rec.phase); let mapped = chain_events(&rec.event); let debt = raw_debt_leg(&rec.event); // Every EventRecord must touch its extrinsic's per_ext entry so `n_ext` counts it (matching @@ -137,23 +177,6 @@ fn chain_events(ev: &RuntimeEvent) -> Vec { ChainEvent::Notable(Notable::Reward { venue: "xyk-lm" }), ]; } - // DCA lifecycle boundaries. - if let RuntimeEvent::DCA(e) = ev { - use pallet_dca::Event as E; - match e { - E::ExecutionStarted { id, .. } => return vec![ChainEvent::DcaStarted { schedule_id: *id }], - E::TradeExecuted { id, who, .. } - | E::TradeFailed { id, who, .. } - | E::Terminated { id, who, .. } - | E::Completed { id, who } => { - return vec![ChainEvent::DcaClosed { - schedule_id: *id, - owner: acc(who), - }] - } - _ => {} - } - } // Trades (router = whole route, direct = a single hop). Emit the Trade (for the price graph) // and a Notable (for labels). if let Some(t) = trade_of(ev) { @@ -463,3 +486,182 @@ fn u128_word(data: &[u8], word_index: usize) -> u128 { fn acc(a: &AccountId) -> cerebro_core::AccountId { a.clone().into() } + +/// Event layout of the retired DCA pallet (index 66), kept so older blocks still decode. +#[allow(dead_code)] +mod legacy_dca { + use super::{acc, Record}; + use cerebro_core::model::ChainEvent; + use codec::Decode; + use hydradx_traits::router::Trade; + use primitives::AccountId; + use sp_core::H256; + use sp_runtime::DispatchError; + + const PALLET_INDEX: u8 = 66; + + #[derive(Decode)] + enum Order { + Sell { + asset_in: u32, + asset_out: u32, + amount_in: u128, + min_amount_out: u128, + route: Vec>, + }, + Buy { + asset_in: u32, + asset_out: u32, + amount_out: u128, + max_amount_in: u128, + route: Vec>, + }, + } + + #[derive(Decode)] + enum CancelReason { + BuyOrder, + BudgetBelowTrade, + UnreserveRemainder, + IntentCreationFailed(DispatchError), + ForceCancelled, + } + + #[derive(Decode)] + enum Event { + ExecutionStarted { + id: u32, + block: u32, + }, + Scheduled { + id: u32, + who: AccountId, + period: u32, + total_amount: u128, + order: Order, + }, + ExecutionPlanned { + id: u32, + who: AccountId, + block: u32, + }, + TradeExecuted { + id: u32, + who: AccountId, + amount_in: u128, + amount_out: u128, + }, + TradeFailed { + id: u32, + who: AccountId, + error: DispatchError, + }, + Terminated { + id: u32, + who: AccountId, + error: DispatchError, + }, + Completed { + id: u32, + who: AccountId, + }, + RandomnessGenerationFailed { + block: u32, + error: DispatchError, + }, + ReserveUnlocked { + who: AccountId, + asset_id: u32, + }, + Migrated { + id: u32, + who: AccountId, + intent_id: u128, + }, + MigrationCancelled { + id: u32, + who: AccountId, + asset: u32, + refunded: u128, + reason: CancelReason, + }, + MigrationEnabledSet { + enabled: bool, + }, + } + + /// `None` leaves `input` untouched. + pub(super) fn decode_record(input: &mut &[u8]) -> Result, String> { + let mut rest = *input; + let phase = frame_system::Phase::decode(&mut rest).map_err(|e| format!("decode EventRecord: {e}"))?; + let Some((&PALLET_INDEX, mut rest)) = rest.split_first() else { + return Ok(None); + }; + let event = Event::decode(&mut rest).map_err(|e| format!("decode legacy DCA event: {e}"))?; + Vec::::decode(&mut rest).map_err(|e| format!("decode EventRecord topics: {e}"))?; + *input = rest; + let mapped = match event { + Event::ExecutionStarted { id, .. } => ChainEvent::DcaStarted { schedule_id: id }, + Event::TradeExecuted { id, who, .. } + | Event::TradeFailed { id, who, .. } + | Event::Terminated { id, who, .. } + | Event::Completed { id, who } => ChainEvent::DcaClosed { + schedule_id: id, + owner: acc(&who), + }, + _ => ChainEvent::Inert, + }; + Ok(Some(Record::LegacyDca(phase, mapped))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use codec::Encode; + + fn legacy_dca_record_then_runtime_record() -> Vec { + let mut raw = frame_system::Phase::Initialization.encode(); + raw.extend([66u8, 0u8]); + raw.extend((7u32, 9u32).encode()); + raw.extend(Vec::::new().encode()); + raw.extend( + EventRecord { + phase: frame_system::Phase::ApplyExtrinsic(1), + event: RuntimeEvent::System(frame_system::Event::ExtrinsicSuccess { + dispatch_info: Default::default(), + }), + topics: vec![], + } + .encode(), + ); + raw + } + + #[test] + fn decode_events_should_map_retired_dca_record_when_it_precedes_a_runtime_event() { + let mut raw = Compact(2u32).encode(); + raw.extend(legacy_dca_record_then_runtime_record()); + + assert_started_then_inert(&decode_events(&raw).expect("decodes")); + } + + #[test] + fn decode_record_stream_should_map_retired_dca_record_when_it_precedes_a_runtime_event() { + let records = decode_record_stream(&legacy_dca_record_then_runtime_record()).expect("decodes"); + + assert_started_then_inert(&map_records(&records)); + } + + fn assert_started_then_inert(decoded: &[Decoded]) { + assert_eq!(decoded.len(), 2); + assert!(matches!( + decoded[0], + (Phase::Hook, ChainEvent::DcaStarted { schedule_id: 7 }, None) + )); + assert!(matches!( + decoded[1], + (Phase::ApplyExtrinsic(1), ChainEvent::Inert, None) + )); + } +} diff --git a/node/src/cerebro_guard/events.rs b/node/src/cerebro_guard/events.rs index 8f798c20f3..fc27bbd338 100644 --- a/node/src/cerebro_guard/events.rs +++ b/node/src/cerebro_guard/events.rs @@ -1,7 +1,7 @@ //! Incremental reader of `System.Events` for the block under construction: per extrinsic it reads //! only the records appended since the last committed one, so a full block costs O(n), not O(n²). -use cerebro_hydration::decode::{decode_record_stream, EventRecord}; +use cerebro_hydration::decode::{decode_record_stream, Record}; use codec::{Compact, Decode}; use frame_system::Phase; use sp_storage::well_known_keys::EXTRINSIC_INDEX; @@ -35,9 +35,9 @@ pub struct Mark { #[derive(Debug)] pub struct Applied { pub ext_index: u32, - pub records: Vec, + pub records: Vec, /// Everything else in the block so far, when the whole value was decoded. - pub earlier: Option>, + pub earlier: Option>, pub mark: Mark, } @@ -112,7 +112,7 @@ impl EventsReader { let Ok(records) = decode_record_stream(&suffix) else { return Err(self.desync()); }; - if records.is_empty() || records.iter().any(|r| r.phase != Phase::ApplyExtrinsic(ext_index)) { + if records.is_empty() || records.iter().any(|r| *r.phase() != Phase::ApplyExtrinsic(ext_index)) { return Err(self.desync()); } Ok(Applied { @@ -148,7 +148,7 @@ impl EventsReader { } let (records, earlier) = records .into_iter() - .partition(|r| r.phase == Phase::ApplyExtrinsic(ext_index)); + .partition(|r| *r.phase() == Phase::ApplyExtrinsic(ext_index)); Ok(Applied { ext_index, records, @@ -182,6 +182,7 @@ impl EventsReader { #[cfg(test)] mod tests { use super::*; + use cerebro_hydration::decode::EventRecord; use codec::Encode; use hydradx_runtime::RuntimeEvent; use sp_core::H256; @@ -277,15 +278,18 @@ mod tests { assert_eq!( first.earlier, Some(vec![ - record(Phase::Initialization, 0), - record(Phase::ApplyExtrinsic(0), 0), - record(Phase::ApplyExtrinsic(0), 1) + Record::Runtime(record(Phase::Initialization, 0)), + Record::Runtime(record(Phase::ApplyExtrinsic(0), 0)), + Record::Runtime(record(Phase::ApplyExtrinsic(0), 1)) ]) ); assert_eq!(second.earlier, None); assert_eq!( second.records, - vec![record(Phase::ApplyExtrinsic(2), 0), record(Phase::ApplyExtrinsic(2), 1)] + vec![ + Record::Runtime(record(Phase::ApplyExtrinsic(2), 0)), + Record::Runtime(record(Phase::ApplyExtrinsic(2), 1)) + ] ); assert_eq!(reader.resyncs, 0); } @@ -339,7 +343,7 @@ mod tests { assert_eq!(crossing.records.len(), 3, "boundary {boundary}"); assert_eq!( after.records, - vec![record(Phase::ApplyExtrinsic(2), 0)], + vec![Record::Runtime(record(Phase::ApplyExtrinsic(2), 0))], "boundary {boundary}" ); assert_eq!(reader.width, width_before * 2, "boundary {boundary}"); diff --git a/node/src/cerebro_guard/mod.rs b/node/src/cerebro_guard/mod.rs index 37b7335d16..1a5edd0012 100644 --- a/node/src/cerebro_guard/mod.rs +++ b/node/src/cerebro_guard/mod.rs @@ -623,7 +623,7 @@ struct CandidateRead { /// Trades of everything already in the block, when pass 1 decoded the whole events value. type Rebuilt = Option>; -fn trades_of(records: &[cerebro_hydration::decode::EventRecord]) -> Vec { +fn trades_of(records: &[cerebro_hydration::decode::Record]) -> Vec { map_records(records) .into_iter() .filter_map(|(_, e, _)| match e { diff --git a/pallets/dca/Cargo.toml b/pallets/dca/Cargo.toml deleted file mode 100644 index bd6bc075cf..0000000000 --- a/pallets/dca/Cargo.toml +++ /dev/null @@ -1,95 +0,0 @@ -[package] -name = 'pallet-dca' -version = "2.0.1" -description = 'A pallet to manage DCA scheduling' -authors = ['GalacticCouncil'] -edition = '2021' -license = 'Apache 2.0' -repository = "https://github.com/galacticcouncil/warehouse/tree/master/route-executor" - -[dependencies] - -log = { workspace = true } -rand = { workspace = true } - -# parity -scale-info = { workspace = true } -codec = { workspace = true } - -# primitives -sp-runtime = { workspace = true } -sp-std = { workspace = true } - -# FRAME -frame-support = { workspace = true } -frame-system = { workspace = true } - -#cumumlus -cumulus-primitives-core = { workspace = true } -cumulus-pallet-parachain-system = { workspace = true } - -# HydraDX dependencies -pallet-xyk = { workspace = true } -pallet-omnipool = { workspace = true } -pallet-dispatcher = { workspace = true } -pallet-evm = { workspace = true } -hydradx-traits = { workspace = true } -ice-support = { workspace = true } -hydradx-adapters = { workspace = true } -pallet-ema-oracle = { workspace = true } -pallet-broadcast = { workspace = true } - -hydra-dx-math = { workspace = true } - -# ORML dependencies -orml-traits = { workspace = true } - -# Optional imports for benchmarking -frame-benchmarking = { workspace = true, optional = true } -sp-core = { workspace = true, optional = true } -sp-io = { workspace = true, optional = true } - -primitives = { path = "../../primitives", default-features = false } - - -[dev-dependencies] -pallet-route-executor = { workspace = true } -smallvec = { workspace = true } -pallet-balances = { workspace = true } -pallet-currencies = { workspace = true, features = ["std"] } -lazy_static = { workspace = true } -sp-api = { workspace = true } -sp-tracing = { workspace = true } -orml-tokens = { workspace = true } -pretty_assertions = { workspace = true } -test-utils = { workspace = true } -test-case = { workspace = true } -primitive-types = { workspace = true } - -[features] -default = ["std"] -std = [ - "codec/std", - "frame-support/std", - "frame-system/std", - "sp-runtime/std", - "sp-std/std", - "sp-core/std", - "sp-io/std", - "scale-info/std", - "orml-tokens/std", - "hydradx-traits/std", - "ice-support/std", - "hydradx-adapters/std", - "pallet-omnipool/std", - "pallet-ema-oracle/std", - "pallet-dispatcher/std", - "pallet-evm/std", -] - -runtime-benchmarks = [ - "frame-benchmarking", - "frame-support/runtime-benchmarks", - "frame-system/runtime-benchmarks", -] -try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/dca/README.md b/pallets/dca/README.md deleted file mode 100644 index d538130d4b..0000000000 --- a/pallets/dca/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# DCA Pallet - -## Overview - -The DCA pallet provides dollar-cost averaging functionality, allowing users to perform repeating orders. -This pallet enables the creation, execution and termination of schedules. - -## Creating a Schedule - -Users can create a DCA schedule, which is planned to execute in a specific block. -If the block is not specified, the execution is planned for the next block. -In case the given block is full, the execution will be scheduled for the subsequent block. - -Upon creating a schedule, the user specifies a budget (`total_amount`) that will be reserved. -The currency of this reservation is the sold (`amount_in`) currency. - -### Executing a Schedule - -Orders are executed during block initialization and are sorted based on randomness derived from the relay chain block -hash. - -A trade is executed and replanned as long as there is remaining budget from the initial allocation. - -For both successful and failed trades, a fee is deducted from the schedule owner. -The fee is deducted in the sold (`amount_in`) currency. - -In case of insufficient asset as `asset_in`, the fee is still taken from the sold currency, -but the amount is swapped for DOT as we don't want to accumulate insufficient assets in treasury. - -A trade can fail due to two main reasons: - -1. Price Stability Error: If the price difference between the short oracle price and the last block oracle price - exceeds the specified threshold. The user can customize this threshold, - or the default value from the pallet configuration will be used. -2. Slippage Error: If the minimum amount out (sell) or maximum amount in (buy) slippage limits are not reached. - These limits are calculated based on the last block's oracle price and the user-specified slippage. - If no slippage is specified, the default value from the pallet configuration will be used. - -If a trade fails due to these errors, the trade will be retried. -If the number of retries reaches the maximum number of retries, the schedule will be permanently terminated. -In the case of a successful trade, the retry counter is reset. - -If a trade fails due to other types of errors, the order is terminated without any retry logic. - -## Terminating a Schedule - -Both users and technical origin can terminate a DCA schedule. However, users can only terminate schedules that they own. - -Once a schedule is terminated, it is completely and permanently removed from the blockchain. \ No newline at end of file diff --git a/pallets/dca/src/lib.rs b/pallets/dca/src/lib.rs deleted file mode 100644 index 1cd330386a..0000000000 --- a/pallets/dca/src/lib.rs +++ /dev/null @@ -1,1566 +0,0 @@ -// This file is part of HydraDX-node - -// Copyright (C) 2020-2023 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! # DCA pallet -//! -//! ## Overview -//! -//! The DCA pallet provides dollar-cost averaging functionality, allowing users to perform repeating orders. -//! This pallet enables the creation, execution and termination of schedules. -//! -//! ## Creating a Schedule -//! -//! Users can create a DCA schedule, which is planned to execute in a specific block. -//! If the block is not specified, the execution is planned for the next block. -//! In case the given block is full, the execution will be scheduled for the subsequent block. -//! -//! Upon creating a schedule, the user specifies a budget (`total_amount`) that will be reserved. -//! `total_amount` can be zero, in which case the schedule will be executed until it is terminated. -//! The currency of this reservation is the sold (`amount_in`) currency. -//! -//! ### Executing a Schedule -//! -//! Orders are executed during block initialization and are sorted based on randomness derived from the relay chain block hash. -//! -//! When the `total_amount` is not zero, trades are executed as long as there is budget remaining from the initial allocation. -//! -//! For both successful and failed trades, a fee is deducted from the schedule owner. -//! The fee is deducted in the sold (`amount_in`) currency. -//! -//! A trade can fail due to two main reasons: -//! -//! 1. Price Stability Error: If the price difference between the short oracle price and the current price -//! exceeds the specified threshold. The user can customize this threshold, -//! or the default value from the pallet configuration will be used. -//! 2. Slippage Error: If the minimum amount out (sell) or maximum amount in (buy) slippage limits are not reached. -//! These limits are calculated based on the last block's oracle price and the user-specified slippage. -//! If no slippage is specified, the default value from the pallet configuration will be used. -//! -//! If a trade fails due to these errors, the trade will be retried. -//! If the number of retries reaches the maximum number of retries, the schedule will be permanently terminated. -//! In the case of a successful trade, the retry counter is reset. -//! -//! If a trade fails due to other types of errors, the order is terminated without any retry logic. -//! -//! ## Terminating a Schedule -//! -//! Both users and TerminateOrigin can terminate a DCA schedule. However, users can only terminate schedules that they own themselves -//! -//! Once a schedule is terminated, it is completely and permanently removed from the blockchain. - -#![cfg_attr(not(feature = "std"), no_std)] -#![allow(clippy::manual_inspect)] - -use frame_support::traits::DefensiveOption; -use frame_support::{ - ensure, - pallet_prelude::*, - traits::{ExistenceRequirement, Get, Len}, - transactional, - weights::WeightToFee as FrameSupportWeight, -}; -use frame_system::{ - ensure_signed, - pallet_prelude::{BlockNumberFor, OriginFor}, - Origin, -}; -use hydradx_traits::evm::ExtraGasSupport; -use orml_traits::{arithmetic::CheckedAdd, MultiCurrency, NamedMultiReservableCurrency}; -use rand::rngs::StdRng; -use rand::{Rng, SeedableRng}; -use sp_runtime::helpers_128bit::multiply_by_rational_with_rounding; -use sp_runtime::traits::CheckedMul; -use sp_runtime::traits::Zero; -use sp_runtime::SaturatedConversion; -use sp_runtime::{ - traits::{BlockNumberProvider, Saturating}, - ArithmeticError, BoundedVec, DispatchError, FixedPointNumber, FixedU128, Percent, Permill, Rounding, -}; -use sp_std::cmp::min; -use sp_std::vec::Vec; - -use hydradx_adapters::RelayChainBlockHashProvider; -use hydradx_traits::router::{inverse_route, AmmTradeWeights, AmountInAndOut, RouteProvider, RouterT, Trade}; -use hydradx_traits::{AccountFeeCurrency, NativePriceOracle, OraclePeriod, PriceOracle}; -use ice_support::{DcaParams, IntentId, IntentMigrator}; -use pallet_broadcast::types::ExecutionType; -use pallet_evm::GasWeightMapping; -pub use weights::WeightInfo; - -#[cfg(test)] -mod tests; - -pub mod migrations; -pub mod types; -pub mod weights; - -// Re-export pallet items so that they can be accessed from the crate namespace. -use crate::types::*; -pub use pallet::*; - -pub const MAX_NUMBER_OF_RETRY_FOR_RESCHEDULING: u32 = 10; -pub const FEE_MULTIPLIER_FOR_MIN_TRADE_LIMIT: Balance = 20; -pub const MAX_EXTRA_GAS: u64 = 1_000_000; - -#[frame_support::pallet] -pub mod pallet { - use frame_support::traits::Contains; - use frame_support::weights::WeightToFee; - use frame_system::ensure_signed_or_root; - use frame_system::pallet_prelude::OriginFor; - use orml_traits::NamedMultiReservableCurrency; - use sp_runtime::Percent; - - use hydra_dx_math::ema::EmaPrice; - use hydradx_traits::{NativePriceOracle, PriceOracle}; - - use super::*; - - const STORAGE_VERSION: StorageVersion = StorageVersion::new(3); - - #[pallet::pallet] - #[pallet::storage_version(STORAGE_VERSION)] - pub struct Pallet(_); - - #[pallet::hooks] - impl Hooks> for Pallet { - fn on_initialize(current_blocknumber: BlockNumberFor) -> Weight { - let mut weight = ::WeightInfo::on_initialize_with_empty_block(); - - let mut randomness_generator = Self::get_randomness_generator(current_blocknumber, None); - - let mut schedule_ids: Vec = ScheduleIdsPerBlock::::take(current_blocknumber).to_vec(); - - schedule_ids.sort_by_cached_key(|_| randomness_generator.gen::()); - let migration_enabled = MigrationEnabled::::get(); - - for schedule_id in schedule_ids { - let Some(schedule) = Schedules::::get(schedule_id) else { - //We cant terminate here as there is no schedule information to do so - Self::deposit_event(Event::ExecutionStarted { - id: schedule_id, - block: current_blocknumber, - }); - continue; - }; - - // Conversion and cancellation both do strictly less work than an execution - neither - // touches the router - so the trade weight bounds them until they are benchmarked. - let weight_for_single_execution = Self::get_trade_weight(&schedule.order, Some(schedule_id)); - weight.saturating_accrue(weight_for_single_execution); - - if migration_enabled { - Self::migrate_or_cancel(schedule_id, &schedule); - continue; - } - - Self::deposit_event(Event::ExecutionStarted { - id: schedule_id, - block: current_blocknumber, - }); - - if let Err(e) = Self::prepare_schedule( - current_blocknumber, - weight_for_single_execution, - schedule_id, - &schedule, - &mut randomness_generator, - ) { - if e == Error::::PriceUnstable.into() - || e == Error::::Bumped.into() - || e == T::ExtraGasSupport::out_of_gas_error() - { - continue; - } else { - Self::terminate_schedule(schedule_id, &schedule, e); - continue; - } - }; - - match Self::execute_trade(schedule_id, &schedule) { - Ok(amounts) => { - if let Err(err) = Self::replan_or_complete( - schedule_id, - &schedule, - current_blocknumber, - amounts, - &mut randomness_generator, - ) { - Self::terminate_schedule(schedule_id, &schedule, err); - } - } - Err(error) => { - if schedule.is_rolling() && error == sp_runtime::TokenError::FundsUnavailable.into() { - Self::complete_schedule(schedule_id, &schedule); - continue; - } - - Self::deposit_event(Event::TradeFailed { - id: schedule_id, - who: schedule.owner.clone(), - error, - }); - - // If it fails with out of gas then we need to increase gas for next execution - if error == T::ExtraGasSupport::out_of_gas_error() { - Self::increment_extra_gas(schedule_id, &schedule); - } - - if error != Error::::TradeLimitReached.into() - && error != Error::::SlippageLimitReached.into() - && !T::RetryOnError::contains(&error) - { - Self::terminate_schedule(schedule_id, &schedule, error); - } else if let Err(retry_error) = - Self::retry_schedule(schedule_id, &schedule, current_blocknumber, &mut randomness_generator) - { - Self::terminate_schedule(schedule_id, &schedule, retry_error); - } - } - } - } - - weight - } - } - - #[pallet::config] - pub trait Config: frame_system::Config + pallet_broadcast::Config { - /// Asset id type - type AssetId: Parameter + Member + Copy + MaybeSerializeDeserialize + MaxEncodedLen + Into; - - /// Creates DCA intents for schedules converted by the migration. - type IntentMigrator: IntentMigrator; - - /// Origin able to terminate schedules - type TerminateOrigin: EnsureOrigin; - - ///For named-reserving user's assets - type Currencies: NamedMultiReservableCurrency< - Self::AccountId, - ReserveIdentifier = NamedReserveIdentifier, - CurrencyId = Self::AssetId, - Balance = Balance, - >; - - ///Relay chain block hash provider for randomness - type RelayChainBlockHashProvider: RelayChainBlockHashProvider; - - ///Randomness provider to be used to sort the DCA schedules when they are executed in a block - type RandomnessProvider: RandomnessProvider; - - ///Oracle price provider to get the price between two assets - type OraclePriceProvider: PriceOracle; - - ///Native price provider to get the price of assets that are accepted as fees - type NativePriceOracle: NativePriceOracle; - - ///Resolves an account's configured fee currency, and whether an asset can pay fees at all. - ///Used when the sold asset is not itself a fee currency. - type AccountFeeCurrency: AccountFeeCurrency; - - ///Router implementation - type RouteExecutor: RouterT< - Self::RuntimeOrigin, - Self::AssetId, - Balance, - Trade, - AmountInAndOut, - >; - - ///Spot price provider to get the current price between two asset - type RouteProvider: RouteProvider; - - ///Errors we want to explicitly retry on, in case of failing DCA - type RetryOnError: Contains; - - type ExtraGasSupport: ExtraGasSupport; - - type GasWeightMapping: GasWeightMapping; - - ///Max price difference allowed between blocks - #[pallet::constant] - type MaxPriceDifferenceBetweenBlocks: Get; - - ///Max configurable price difference allowed between blocks - #[pallet::constant] - type MaxConfigurablePriceDifferenceBetweenBlocks: Get; - - ///The number of max schedules to be executed per block - #[pallet::constant] - type MaxSchedulePerBlock: Get; - - ///The number of max retries in case of trade limit error - #[pallet::constant] - type MaxNumberOfRetriesOnError: Get; - - ///Minimal period between executions - #[pallet::constant] - type MinimalPeriod: Get; - - ///Chance of the random rescheduling - #[pallet::constant] - type BumpChance: Get; - - /// Minimum trading limit for a single trade - #[pallet::constant] - type MinimumTradingLimit: Get; - - /// Native Asset Id - #[pallet::constant] - type NativeAssetId: Get; - - ///Minimum budget to be able to schedule a DCA, specified in native currency - #[pallet::constant] - type MinBudgetInNativeCurrency: Get; - - ///The fee receiver for transaction fees - #[pallet::constant] - type FeeReceiver: Get; - - /// Named reserve identifier to store named reserves for orders of each users - #[pallet::constant] - type NamedReserveId: Get; - - /// Convert a weight value into a deductible fee - type WeightToFee: WeightToFee; - - /// AMMs trade weight information. - type AmmTradeWeights: AmmTradeWeights>; - - /// Weight information for the extrinsics. - type WeightInfo: WeightInfo; - } - - #[pallet::event] - #[pallet::generate_deposit(pub(crate) fn deposit_event)] - pub enum Event { - ///The DCA execution is started - ExecutionStarted { id: ScheduleId, block: BlockNumberFor }, - ///The DCA is scheduled for next execution - Scheduled { - id: ScheduleId, - who: T::AccountId, - period: BlockNumberFor, - total_amount: Balance, - order: Order, - }, - ///The DCA is planned for blocknumber - ExecutionPlanned { - id: ScheduleId, - who: T::AccountId, - block: BlockNumberFor, - }, - /// The DCA trade is successfully executed - TradeExecuted { - id: ScheduleId, - who: T::AccountId, - amount_in: Balance, - amount_out: Balance, - }, - ///The DCA trade execution is failed - TradeFailed { - id: ScheduleId, - who: T::AccountId, - error: DispatchError, - }, - ///The DCA is terminated and completely removed from the chain - Terminated { - id: ScheduleId, - who: T::AccountId, - error: DispatchError, - }, - ///The DCA is completed and completely removed from the chain - Completed { id: ScheduleId, who: T::AccountId }, - ///Randomness generation failed possibly coming from missing data about relay chain - RandomnessGenerationFailed { - block: BlockNumberFor, - error: DispatchError, - }, - ///DCA reserve for the given asset have been unlocked for a user - ReserveUnlocked { who: T::AccountId, asset_id: T::AssetId }, - ///The DCA schedule has been converted into a DCA intent - Migrated { - id: ScheduleId, - who: T::AccountId, - intent_id: IntentId, - }, - ///The DCA schedule has been cancelled by the migration and its reserve refunded - MigrationCancelled { - id: ScheduleId, - who: T::AccountId, - asset: T::AssetId, - refunded: Balance, - reason: CancelReason, - }, - ///The migration switch has been flipped - MigrationEnabledSet { enabled: bool }, - } - - #[pallet::error] - pub enum Error { - ///Schedule not exist - ScheduleNotFound, - ///The min trade amount is not reached - MinTradeAmountNotReached, - ///Forbidden as the user is not the owner of the schedule - Forbidden, - ///The next execution block number is not in the future - BlockNumberIsNotInFuture, - ///Price is unstable as price change from oracle data is bigger than max allowed - PriceUnstable, - ///Order was randomly rescheduled to next block - Bumped, - ///Error occurred when calculating price - CalculatingPriceError, - ///The total amount to be reserved is smaller than min budget - TotalAmountIsSmallerThanMinBudget, - ///The budget is too low for executing at least two orders - BudgetTooLow, - ///There is no free block found to plan DCA execution - NoFreeBlockFound, - ///The DCA schedule has been manually terminated - ManuallyTerminated, - ///Max number of retries reached for schedule - MaxRetryReached, - ///Absolutely trade limit reached, leading to retry - TradeLimitReached, - ///Slippage limit calculated from oracle is reached, leading to retry - SlippageLimitReached, - ///No parent hash has been found from relay chain - NoParentHashFound, - ///Error that should not really happen only in case of invalid state of the schedule storage entries - InvalidState, - ///Period should be longer than 5 blocks - PeriodTooShort, - ///Stability threshold cannot be higher than `MaxConfigurablePriceDifferenceBetweenBlock` - StabilityThresholdTooHigh, - ///User still has active DCA schedules and cannot unlock reserves - HasActiveSchedules, - ///No reserves are locked for the user for the given asset - NoReservesLocked, - ///Buy orders can no longer be scheduled. Existing buy schedules keep executing. - NoLongerSupported, - ///Schedules cannot be created while they are being migrated to DCA intents - MigrationInProgress, - } - - /// Id sequencer for schedules - #[pallet::storage] - #[pallet::getter(fn next_schedule_id)] - pub type ScheduleIdSequencer = StorageValue<_, ScheduleId, ValueQuery>; - - /// Storing schedule details - #[pallet::storage] - #[pallet::getter(fn schedules)] - pub type Schedules = - StorageMap<_, Blake2_128Concat, ScheduleId, Schedule>, OptionQuery>; - - /// Storing schedule ownership - #[pallet::storage] - #[pallet::getter(fn owner_of)] - pub type ScheduleOwnership = - StorageDoubleMap<_, Blake2_128Concat, T::AccountId, Twox64Concat, ScheduleId, (), OptionQuery>; - - /// Keep tracking the remaining amounts to spend for DCA schedules - #[pallet::storage] - #[pallet::getter(fn remaining_amounts)] - pub type RemainingAmounts = StorageMap<_, Blake2_128Concat, ScheduleId, Balance, OptionQuery>; - - /// Keep tracking the retry on error flag for DCA schedules - #[pallet::storage] - #[pallet::getter(fn retries_on_error)] - pub type RetriesOnError = StorageMap<_, Blake2_128Concat, ScheduleId, u8, ValueQuery>; - - /// Keep tracking the blocknumber when the schedule is planned to be executed - #[pallet::storage] - #[pallet::getter(fn schedule_execution_block)] - pub type ScheduleExecutionBlock = - StorageMap<_, Blake2_128Concat, ScheduleId, BlockNumberFor, OptionQuery>; - - /// Keep tracking of the schedule ids to be executed in the block - #[pallet::storage] - #[pallet::getter(fn schedule_ids_per_block)] - pub type ScheduleIdsPerBlock = - StorageMap<_, Blake2_128Concat, BlockNumberFor, BoundedVec, ValueQuery>; - - /// Stores the current extra gas value for each schedule. - /// Initialized to 0, increments on EvmOutOfGas, persists after successful execution. - /// Cleaned up when schedule terminates or completes. - #[pallet::storage] - #[pallet::getter(fn schedule_extra_gas)] - pub type ScheduleExtraGas = StorageMap<_, Blake2_128Concat, ScheduleId, u64, ValueQuery>; - - /// Whether schedules convert into DCA intents when their execution slot arrives. - #[pallet::storage] - #[pallet::getter(fn migration_enabled)] - pub type MigrationEnabled = StorageValue<_, bool, ValueQuery>; - - #[pallet::call] - impl Pallet { - /// Creates a new DCA (Dollar-Cost Averaging) schedule and plans the next execution - /// for the specified block. - /// - /// Only `Order::Sell` schedules can be created. Buy orders are rejected with - /// `NoLongerSupported`; buy schedules already stored keep executing until they complete - /// or are terminated. - /// - /// If the block is not specified, the execution is planned for the next block. - /// If the given block is full, the execution will be planned in the subsequent block. - /// - /// Once the schedule is created, the specified `total_amount` will be reserved for DCA. - /// The reservation currency will be the `amount_in` currency of the order. - /// - /// Trades are executed as long as there is budget remaining - /// from the initial `total_amount` allocation, unless `total_amount` is 0, then trades - /// are executed until schedule is terminated. - /// - /// If a trade fails due to slippage limit or price stability errors, it will be retried. - /// If the number of retries reaches the maximum allowed, - /// the schedule will be terminated permanently. - /// In the case of a successful trade, the retry counter is reset. - /// - /// Parameters: - /// - `origin`: schedule owner - /// - `schedule`: schedule details - /// - `start_execution_block`: first possible execution block for the schedule - /// - /// Emits `Scheduled` and `ExecutionPlanned` event when successful. - /// - #[pallet::call_index(0)] - #[pallet::weight(::WeightInfo::schedule())] - #[transactional] - pub fn schedule( - origin: OriginFor, - schedule: Schedule>, - start_execution_block: Option>, - ) -> DispatchResult { - let who = ensure_signed(origin)?; - ensure!(!MigrationEnabled::::get(), Error::::MigrationInProgress); - ensure!(who == schedule.owner, Error::::Forbidden); - // Buy execution stays live for schedules stored before this restriction, so the - // benchmarks that measure it still need to create one. - #[cfg(not(feature = "runtime-benchmarks"))] - ensure!( - matches!(schedule.order, Order::Sell { .. }), - Error::::NoLongerSupported - ); - - // The minimum budget is native-denominated, so it can only be expressed in the sold - // asset when that asset has a price. A schedule selling an unpriceable asset still pays - // a real fee in the owner's fee currency on every execution, which is what bounds spam. - let min_budget = if T::AccountFeeCurrency::is_payment_currency(schedule.order.get_asset_in()).is_ok() { - Some(Self::convert_native_amount_to_currency( - schedule.order.get_asset_in(), - T::MinBudgetInNativeCurrency::get(), - )?) - } else { - None - }; - ensure!( - schedule.period >= BlockNumberFor::::from(T::MinimalPeriod::get()), - Error::::PeriodTooShort - ); - ensure!( - match schedule.stability_threshold { - Some(threshold) => threshold <= T::MaxConfigurablePriceDifferenceBetweenBlocks::get(), - None => true, - }, - Error::::StabilityThresholdTooHigh - ); - - let transaction_fee = Self::budget_transaction_fee(&schedule.order, None)?; - - let amount_in = match schedule.order { - Order::Sell { amount_in, .. } => amount_in, - Order::Buy { amount_out, .. } => { - let route = schedule.order.get_route_or_default::(); - Self::get_amount_in_for_buy(&amount_out, &route)? - } - }; - let min_trade_amount_in_from_fee = transaction_fee.saturating_mul(FEE_MULTIPLIER_FOR_MIN_TRADE_LIMIT); - ensure!( - amount_in >= min_trade_amount_in_from_fee, - Error::::MinTradeAmountNotReached - ); - ensure!( - amount_in >= T::MinimumTradingLimit::get(), - Error::::MinTradeAmountNotReached - ); - - let amount_in_with_transaction_fee = amount_in.saturating_add(transaction_fee).saturating_mul(2); - let reserve_amount = if schedule.is_rolling() { - if let Some(min_budget) = min_budget { - ensure!( - amount_in_with_transaction_fee >= min_budget, - Error::::MinTradeAmountNotReached - ); - } - amount_in_with_transaction_fee - } else { - if let Some(min_budget) = min_budget { - ensure!( - schedule.total_amount >= min_budget, - Error::::TotalAmountIsSmallerThanMinBudget - ); - } - ensure!( - amount_in_with_transaction_fee <= schedule.total_amount, - Error::::BudgetTooLow - ); - schedule.total_amount - }; - - let next_schedule_id = - ScheduleIdSequencer::::try_mutate(|current_id| -> Result { - let schedule_id = *current_id; - *current_id = current_id.checked_add(1).ok_or(ArithmeticError::Overflow)?; - Ok(schedule_id) - })?; - - Schedules::::insert(next_schedule_id, &schedule); - ScheduleOwnership::::insert(who.clone(), next_schedule_id, ()); - RemainingAmounts::::insert(next_schedule_id, reserve_amount); - RetriesOnError::::insert(next_schedule_id, 0); - - T::Currencies::reserve_named( - &T::NamedReserveId::get(), - schedule.order.get_asset_in(), - &who, - reserve_amount, - )?; - - let blocknumber_for_first_schedule_execution = Self::get_first_execution_block(start_execution_block)?; - - let mut randomness_generator = Self::get_randomness_generator( - frame_system::Pallet::::current_block_number(), - Some(next_schedule_id), - ); - Self::plan_schedule_for_block( - &who, - blocknumber_for_first_schedule_execution, - next_schedule_id, - &mut randomness_generator, - )?; - - Self::deposit_event(Event::Scheduled { - id: next_schedule_id, - who, - period: schedule.period, - total_amount: schedule.total_amount, - order: schedule.order, - }); - - Ok(()) - } - - /// Terminates a DCA schedule and remove it completely from the chain. - /// - /// This can be called by both schedule owner or the configured `T::TerminateOrigin` - /// - /// Parameters: - /// - `origin`: schedule owner - /// - `schedule_id`: schedule id - /// - `next_execution_block`: block number where the schedule is planned. - /// - /// Emits `Terminated` event when successful. - /// - #[pallet::call_index(1)] - #[pallet::weight(::WeightInfo::terminate())] - #[transactional] - pub fn terminate( - origin: OriginFor, - schedule_id: ScheduleId, - next_execution_block: Option>, - ) -> DispatchResult { - let schedule = Schedules::::get(schedule_id).ok_or(Error::::ScheduleNotFound)?; - - if T::TerminateOrigin::ensure_origin(origin.clone()).is_err() { - let who = ensure_signed(origin)?; - ensure!(who == schedule.owner, Error::::Forbidden); - } - - Self::try_unreserve_all(schedule_id, &schedule); - - let next_execution_block = next_execution_block - .or(Self::schedule_execution_block(schedule_id)) - .ok_or(Error::::ScheduleNotFound)?; - - //Remove schedule id from next execution block - ScheduleIdsPerBlock::::try_mutate_exists( - next_execution_block, - |maybe_schedule_ids| -> DispatchResult { - let schedule_ids = maybe_schedule_ids.as_mut().ok_or(Error::::ScheduleNotFound)?; - - let idx = schedule_ids - .iter() - .position(|x| *x == schedule_id) - .ok_or(Error::::ScheduleNotFound)?; - schedule_ids.remove(idx); - - if schedule_ids.is_empty() { - *maybe_schedule_ids = None; - } - Ok(()) - }, - )?; - - Self::remove_schedule_from_storages(&schedule.owner, schedule_id); - - Self::deposit_event(Event::Terminated { - id: schedule_id, - who: schedule.owner, - error: Error::::ManuallyTerminated.into(), - }); - - Ok(()) - } - - /// Unlocks DCA reserves of provided asset for the caller if they have no active schedules. - /// - /// This is a utility function to help users recover their reserved funds in case - /// a DCA schedule was terminated but left some reserved amounts. - /// - /// This can only be called when the user has no active DCA schedules. - /// - /// Parameters: - /// - `origin`: The account to unlock reserves for (must be signed) - /// - `asset_id`: The asset ID for which reserves should be unlocked. - /// - /// Emits `ReserveUnlocked` event when successful. - /// - #[pallet::call_index(2)] - #[pallet::weight(::WeightInfo::unlock_reserves())] - #[transactional] - pub fn unlock_reserves(origin: OriginFor, who: T::AccountId, asset_id: T::AssetId) -> DispatchResult { - let _ = ensure_signed_or_root(origin)?; - - ensure!( - ScheduleOwnership::::iter_prefix(who.clone()).next().is_none(), - Error::::HasActiveSchedules - ); - - let named_reserve_id = T::NamedReserveId::get(); - let reserved_balance = T::Currencies::reserved_balance_named(&named_reserve_id, asset_id, &who); - - ensure!(!reserved_balance.is_zero(), Error::::NoReservesLocked); - - let remaining_unreserved = - T::Currencies::unreserve_named(&named_reserve_id, asset_id, &who, reserved_balance); - - // Sanity check to ensure that all reserved balance has been unreserved. - // It should never be triggered as we should unreserve the exact reserved balance - ensure!(remaining_unreserved.is_zero(), Error::::InvalidState); - - Self::deposit_event(Event::ReserveUnlocked { who, asset_id }); - - Ok(()) - } - - /// Enables or disables the conversion of DCA schedules into DCA intents. - /// - /// While enabled, a schedule is converted - or cancelled and refunded when it cannot be - /// converted - as soon as its execution slot arrives, instead of being traded. That - /// execution is skipped: the resulting intent trades one period later. Creating new - /// schedules is blocked for as long as the flag is set. - /// - /// Parameters: - /// - `origin`: Must be `T::TerminateOrigin` - /// - `enabled`: whether schedules convert when their execution slot arrives - /// - /// Emits `MigrationEnabledSet` event when successful. - /// - #[pallet::call_index(3)] - #[pallet::weight(::WeightInfo::set_migration_enabled())] - #[transactional] - pub fn set_migration_enabled(origin: OriginFor, enabled: bool) -> DispatchResult { - T::TerminateOrigin::ensure_origin(origin)?; - - MigrationEnabled::::put(enabled); - Self::deposit_event(Event::MigrationEnabledSet { enabled }); - - Ok(()) - } - - /// Cancels the given schedules and refunds their reserves. - /// - /// Escape hatch for schedules the migration cannot reach - an entry left without a planned - /// execution block never comes up in `on_initialize` and would otherwise keep the old - /// pallet alive indefinitely. Unknown ids are skipped rather than rejected. - /// - /// Parameters: - /// - `origin`: Must be `T::TerminateOrigin` - /// - `schedule_ids`: the schedules to cancel - /// - /// Emits `MigrationCancelled` event for each cancelled schedule. - /// - #[pallet::call_index(4)] - #[pallet::weight(::WeightInfo::terminate().saturating_mul(schedule_ids.len() as u64))] - #[transactional] - pub fn force_cancel_schedules(origin: OriginFor, schedule_ids: Vec) -> DispatchResult { - T::TerminateOrigin::ensure_origin(origin)?; - - for schedule_id in schedule_ids { - let Some(schedule) = Schedules::::get(schedule_id) else { - continue; - }; - - Self::cancel_for_migration(schedule_id, &schedule, CancelReason::ForceCancelled); - } - - Ok(()) - } - } -} - -impl Pallet { - fn get_randomness_generator(current_blocknumber: BlockNumberFor, salt: Option) -> StdRng { - match T::RandomnessProvider::generator(salt) { - Ok(generator) => generator, - Err(err) => { - Self::deposit_event(Event::RandomnessGenerationFailed { - block: current_blocknumber, - error: err, - }); - - StdRng::seed_from_u64(0) - } - } - } - - fn get_first_execution_block( - start_execution_block: Option>, - ) -> Result, DispatchError> { - let current_block_number = frame_system::Pallet::::current_block_number(); - let blocknumber_for_first_schedule_execution = match start_execution_block { - Some(blocknumber) => { - let number = current_block_number.saturating_add(2u32.into()).max(blocknumber); - let remainder: u32 = (number.into() % 5).as_u32(); - let diff = if remainder == 0 { 0 } else { 5u32 - remainder }; - Ok(number.saturating_add(diff.into())) - } - None => { - let next_block_number = current_block_number - .checked_add(&BlockNumberFor::::from(2u32)) - .ok_or(ArithmeticError::Overflow)?; - - Ok::, ArithmeticError>(next_block_number) - } - }?; - - Ok(blocknumber_for_first_schedule_execution) - } - - fn prepare_schedule( - current_blocknumber: BlockNumberFor, - weight_for_dca_execution: Weight, - schedule_id: ScheduleId, - schedule: &Schedule>, - randomness_generator: &mut StdRng, - ) -> DispatchResult { - if Percent::from_percent(randomness_generator.gen_range(0..100)) <= T::BumpChance::get() { - let next_block = current_blocknumber.saturating_add(1u32.into()); - Self::plan_schedule_for_block(&schedule.owner, next_block, schedule_id, randomness_generator)?; - return Err(Error::::Bumped.into()); - } - - if let Err(e) = Self::take_transaction_fee_from_user(schedule_id, schedule, weight_for_dca_execution) { - if e == T::ExtraGasSupport::out_of_gas_error() { - Self::increment_extra_gas(schedule_id, schedule); - Self::deposit_event(Event::TradeFailed { - id: schedule_id, - who: schedule.owner.clone(), - error: e, - }); - Self::retry_schedule(schedule_id, schedule, current_blocknumber, randomness_generator)?; - return Err(e); - } - return Err(e); - } - - if Self::is_price_unstable(schedule) { - Self::deposit_event(Event::TradeFailed { - id: schedule_id, - who: schedule.owner.clone(), - error: Error::::PriceUnstable.into(), - }); - Self::retry_schedule(schedule_id, schedule, current_blocknumber, randomness_generator)?; - - return Err(Error::::PriceUnstable.into()); - } - - Ok(()) - } - - #[transactional] - pub fn execute_trade( - schedule_id: ScheduleId, - schedule: &Schedule>, - ) -> Result, DispatchError> { - // Set extra gas for evm execution when previous dca failed with out of gas - let extra_gas = ScheduleExtraGas::::get(schedule_id); - T::ExtraGasSupport::set_extra_gas(extra_gas); - - pallet_broadcast::Pallet::::add_to_context(|id| ExecutionType::DCA(schedule_id, id))?; - - let origin: OriginFor = Origin::::Signed(schedule.owner.clone()).into(); - let trade_result = match &schedule.order { - Order::Sell { - asset_in, - asset_out, - amount_in, - min_amount_out, - .. - } => { - let route = &schedule.order.get_route_or_default::(); - let remaining_amount = - RemainingAmounts::::get(schedule_id).defensive_ok_or(Error::::InvalidState)?; - let amount_to_sell = min(remaining_amount, *amount_in); - - Self::unallocate_amount(schedule_id, schedule, amount_to_sell)?; - - let route_for_slippage = inverse_route(route.clone()); - let (estimated_amount_out, slippage_amount) = - Self::calculate_last_block_slippage(&route_for_slippage, amount_to_sell, schedule.slippage)?; - let last_block_slippage_min_limit = estimated_amount_out - .checked_sub(slippage_amount) - .ok_or(ArithmeticError::Overflow)?; - - let trade_amounts = T::RouteExecutor::calculate_sell_trade_amounts(route, amount_to_sell)?; - let last_trade = trade_amounts.last().defensive_ok_or(Error::::InvalidState)?; - let amount_out = last_trade.amount_out; - - let effective_min_limit = if *min_amount_out > last_block_slippage_min_limit { - ensure!(amount_out >= *min_amount_out, Error::::TradeLimitReached); - amount_out - } else { - ensure!( - amount_out >= last_block_slippage_min_limit, - Error::::SlippageLimitReached - ); - // Use slippage limit to mainly absorb aToken rounding errors - last_block_slippage_min_limit - }; - - T::RouteExecutor::sell( - origin, - *asset_in, - *asset_out, - amount_to_sell, - effective_min_limit, - route.clone(), - )?; - - Ok(AmountInAndOut { - amount_in: amount_to_sell, - amount_out, - }) - } - Order::Buy { - asset_in, - asset_out, - amount_out, - max_amount_in, - .. - } => { - let route = schedule.order.get_route_or_default::(); - let amount_in = Self::get_amount_in_for_buy(amount_out, &route)?; - - Self::unallocate_amount(schedule_id, schedule, amount_in)?; - - let (estimated_amount_in, slippage_amount) = - Self::calculate_last_block_slippage(&route, *amount_out, schedule.slippage)?; - let last_block_slippage_max_limit = estimated_amount_in - .checked_add(slippage_amount) - .ok_or(ArithmeticError::Overflow)?; - - if *max_amount_in < last_block_slippage_max_limit { - ensure!(amount_in <= *max_amount_in, Error::::TradeLimitReached); - } else { - ensure!( - amount_in <= last_block_slippage_max_limit, - Error::::SlippageLimitReached - ); - }; - - T::RouteExecutor::buy(origin, *asset_in, *asset_out, *amount_out, amount_in, route)?; - - Ok(AmountInAndOut { - amount_in, - amount_out: *amount_out, - }) - } - }; - - pallet_broadcast::Pallet::::remove_from_context()?; - - T::ExtraGasSupport::clear_extra_gas(); - - trade_result - } - - fn replan_or_complete( - schedule_id: ScheduleId, - schedule: &Schedule>, - current_blocknumber: BlockNumberFor, - amounts: AmountInAndOut, - randomness_generator: &mut StdRng, - ) -> DispatchResult { - Self::deposit_event(Event::TradeExecuted { - id: schedule_id, - who: schedule.owner.clone(), - amount_in: amounts.amount_in, - amount_out: amounts.amount_out, - }); - - RetriesOnError::::remove(schedule_id); - - let remaining_amount: Balance = - RemainingAmounts::::get(schedule_id).defensive_ok_or(Error::::InvalidState)?; - let transaction_fee = Self::budget_transaction_fee(&schedule.order, Some(schedule_id))?; - let min_amount_for_replanning = transaction_fee.saturating_mul(FEE_MULTIPLIER_FOR_MIN_TRADE_LIMIT); - if remaining_amount < min_amount_for_replanning || remaining_amount < T::MinimumTradingLimit::get() { - Self::complete_schedule(schedule_id, schedule); - return Ok(()); - } - - //In buy we complete with returning leftover, in sell we sell the leftover in the next trade - if let Order::Buy { amount_out, .. } = &schedule.order { - if !schedule.is_rolling() { - let route = schedule.order.get_route_or_default::(); - let amount_to_unreserve: Balance = Self::get_amount_in_for_buy(amount_out, &route)?; - - let amount_for_next_trade: Balance = amount_to_unreserve - .checked_add(transaction_fee) - .ok_or(ArithmeticError::Overflow)?; - - if remaining_amount < amount_for_next_trade { - Self::complete_schedule(schedule_id, schedule); - return Ok(()); - } - } - } - - let next_execution_block = current_blocknumber - .checked_add(&schedule.period) - .ok_or(ArithmeticError::Overflow)?; - - Self::plan_schedule_for_block(&schedule.owner, next_execution_block, schedule_id, randomness_generator)?; - - Ok(()) - } - - fn retry_schedule( - schedule_id: ScheduleId, - schedule: &Schedule>, - current_blocknumber: BlockNumberFor, - randomness_generator: &mut StdRng, - ) -> DispatchResult { - let number_of_retries = Self::retries_on_error(schedule_id); - - let max_retries = schedule.max_retries.unwrap_or_else(T::MaxNumberOfRetriesOnError::get); - ensure!(number_of_retries < max_retries, Error::::MaxRetryReached); - - RetriesOnError::::mutate(schedule_id, |retry| -> DispatchResult { - retry.saturating_inc(); - Ok(()) - })?; - - let retry_period = OraclePeriod::Short.as_period() as u32; - - let retry_multiplier = 2u32 - .checked_pow(number_of_retries.into()) - .ok_or(ArithmeticError::Overflow)?; - let retry_delay = retry_period - .checked_mul(retry_multiplier) - .ok_or(ArithmeticError::Overflow)?; - let next_execution_block = current_blocknumber - .checked_add(&retry_delay.into()) - .ok_or(ArithmeticError::Overflow)?; - - Self::plan_schedule_for_block(&schedule.owner, next_execution_block, schedule_id, randomness_generator)?; - - Ok(()) - } - - fn is_price_unstable(schedule: &Schedule>) -> bool { - let route = &schedule.order.get_route_or_default::(); - - let Ok(last_block_price) = Self::get_price_from_last_block_oracle(route) else { - return true; - }; - - let Ok(price_from_short_oracle) = Self::get_price_from_short_oracle(route) else { - return true; - }; - - let max_allowed_diff = schedule - .stability_threshold - .unwrap_or_else(T::MaxPriceDifferenceBetweenBlocks::get); - - let max_allowed = FixedU128::from(max_allowed_diff); - - let Some(price_sum) = last_block_price.checked_add(&price_from_short_oracle) else { - return true; - }; - - let Ok(max_allowed_difference) = max_allowed.checked_mul(&price_sum).ok_or(ArithmeticError::Overflow) else { - return true; - }; - - let diff = if last_block_price > price_from_short_oracle { - last_block_price.saturating_sub(price_from_short_oracle) - } else { - price_from_short_oracle.saturating_sub(last_block_price) - }; - - let Some(diff) = diff.checked_mul(&FixedU128::from(2)) else { - return true; - }; - - diff > max_allowed_difference - } - - fn get_amount_in_for_buy(amount_out: &Balance, route: &[Trade]) -> Result { - let trade_amounts = T::RouteExecutor::calculate_buy_trade_amounts(route, *amount_out)?; - - let first_trade = trade_amounts.last().defensive_ok_or(Error::::InvalidState)?; - - Ok(first_trade.amount_in) - } - - pub fn get_transaction_fee( - order: &Order, - schedule_id: Option, - ) -> Result { - Self::convert_weight_to_fee(Self::get_trade_weight(order, schedule_id), order.get_asset_in()) - } - - /// Execution fee taken out of the schedule's reserved budget, denominated in the sold asset. - /// - /// Zero when the sold asset is not a fee currency: the fee is then charged in the owner's own - /// fee currency and never touches the budget, so every budget-sizing calculation must treat it - /// as costing the budget nothing. - fn budget_transaction_fee( - order: &Order, - schedule_id: Option, - ) -> Result { - if T::AccountFeeCurrency::is_payment_currency(order.get_asset_in()).is_err() { - return Ok(Balance::zero()); - } - - Self::get_transaction_fee(order, schedule_id) - } - - fn unallocate_amount( - schedule_id: ScheduleId, - schedule: &Schedule>, - amount_to_unreserve: Balance, - ) -> DispatchResult { - if schedule.is_rolling() { - return Ok(()); - }; - - RemainingAmounts::::try_mutate_exists(schedule_id, |maybe_remaining_amount| -> DispatchResult { - let remaining_amount = maybe_remaining_amount - .as_mut() - .defensive_ok_or(Error::::InvalidState)?; - - ensure!(amount_to_unreserve <= *remaining_amount, Error::::InvalidState); - - *remaining_amount = remaining_amount - .checked_sub(amount_to_unreserve) - .ok_or(ArithmeticError::Underflow)?; - - Ok(()) - })?; - - let sold_currency = schedule.order.get_asset_in(); - - let remaining_amount_if_insufficient_balance = T::Currencies::unreserve_named( - &T::NamedReserveId::get(), - sold_currency, - &schedule.owner, - amount_to_unreserve, - ); - ensure!(remaining_amount_if_insufficient_balance == 0, Error::::InvalidState); - - Ok(()) - } - - #[transactional] - fn take_transaction_fee_from_user( - schedule_id: ScheduleId, - schedule: &Schedule>, - weight_to_charge: Weight, - ) -> DispatchResult { - // Set extra gas for evm execution when previous dca failed with out of gas - let extra_gas = ScheduleExtraGas::::get(schedule_id); - T::ExtraGasSupport::set_extra_gas(extra_gas); - - let asset_in = schedule.order.get_asset_in(); - - if T::AccountFeeCurrency::is_payment_currency(asset_in).is_ok() { - // The sold asset pays for itself, straight out of the reserved budget. - let fee = Self::convert_weight_to_fee(weight_to_charge, asset_in)?; - - Self::unallocate_amount(schedule_id, schedule, fee)?; - - T::Currencies::transfer( - asset_in, - &schedule.owner, - &T::FeeReceiver::get(), - fee, - ExistenceRequirement::AllowDeath, - )?; - } else { - // The sold asset is not a fee currency, so the protocol will not price it. Charge the - // owner's own fee currency from their free balance instead and leave the budget whole - - // it is denominated in the asset we are refusing to price. - let fee_currency = T::AccountFeeCurrency::get(&schedule.owner); - let fee = Self::convert_weight_to_fee(weight_to_charge, fee_currency)?; - - // `KeepAlive`: failing to pay terminates the schedule and returns the budget, which is - // a better outcome for the owner than being reaped to cover an execution fee. - T::Currencies::transfer( - fee_currency, - &schedule.owner, - &T::FeeReceiver::get(), - fee, - ExistenceRequirement::KeepAlive, - )?; - } - - T::ExtraGasSupport::clear_extra_gas(); - - Ok(()) - } - - fn terminate_schedule( - schedule_id: ScheduleId, - schedule: &Schedule>, - error: DispatchError, - ) { - Self::try_unreserve_all(schedule_id, schedule); - - Self::remove_schedule_from_storages(&schedule.owner, schedule_id); - - Self::deposit_event(Event::Terminated { - id: schedule_id, - who: schedule.owner.clone(), - error, - }); - } - - fn complete_schedule(schedule_id: ScheduleId, schedule: &Schedule>) { - Self::try_unreserve_all(schedule_id, schedule); - - Self::remove_schedule_from_storages(&schedule.owner, schedule_id); - - Self::deposit_event(Event::Completed { - id: schedule_id, - who: schedule.owner.clone(), - }); - } - - fn try_unreserve_all(schedule_id: ScheduleId, schedule: &Schedule>) { - let sold_currency = schedule.order.get_asset_in(); - - let Some(remaining_amount) = RemainingAmounts::::get(schedule_id) else { - //Invalid state, we ignore as we terminate the whole DCA anyway - return; - }; - - T::Currencies::unreserve_named( - &T::NamedReserveId::get(), - sold_currency, - &schedule.owner, - remaining_amount, - ); - } - - fn weight_to_fee(weight: Weight) -> Balance { - // cap the weight to the maximum defined in runtime, otherwise it will be the - // `Bounded` maximum of its data type, which is not desired. - let capped_weight: Weight = weight.min(T::BlockWeights::get().max_block); - ::WeightToFee::weight_to_fee(&capped_weight) - } - - fn plan_schedule_for_block( - who: &T::AccountId, - blocknumber: BlockNumberFor, - schedule_id: ScheduleId, - randomness_generator: &mut StdRng, - ) -> DispatchResult { - let current_block_number = frame_system::Pallet::::current_block_number(); - ensure!(blocknumber > current_block_number, Error::::BlockNumberIsNotInFuture); - - let next_free_block = Self::find_next_free_block(blocknumber, randomness_generator)?; - - ScheduleIdsPerBlock::::try_mutate(next_free_block, |schedule_ids| -> DispatchResult { - schedule_ids - .try_push(schedule_id) - .map_err(|_| Error::::InvalidState)?; - Ok(()) - })?; - - ScheduleExecutionBlock::::insert(schedule_id, next_free_block); - - Self::deposit_event(Event::ExecutionPlanned { - id: schedule_id, - who: who.clone(), - block: next_free_block, - }); - Ok(()) - } - - fn find_next_free_block( - blocknumber: BlockNumberFor, - randomness_generator: &mut StdRng, - ) -> Result, DispatchError> { - let mut next_execution_block = blocknumber; - - for i in 0..=MAX_NUMBER_OF_RETRY_FOR_RESCHEDULING { - let schedule_ids = ScheduleIdsPerBlock::::get(next_execution_block); - if schedule_ids.len() < T::MaxSchedulePerBlock::get() as usize { - return Ok(next_execution_block); - } - - let lower_bound = 2u32.saturating_pow(i); - let upper_bound = 2u32.saturating_pow(i.saturating_add(1)).saturating_sub(1); - - let delay_with = randomness_generator.gen_range(lower_bound..=upper_bound); - next_execution_block = next_execution_block.saturating_add(delay_with.into()); - } - - Err(Error::::NoFreeBlockFound.into()) - } - - fn calculate_last_block_slippage( - route: &[Trade], - amount: Balance, - slippage: Option, - ) -> Result<(Balance, Balance), DispatchError> { - let price = Self::get_price_from_last_block_oracle(route)?; - - let estimated_amount = price.checked_mul_int(amount).ok_or(ArithmeticError::Overflow)?; - - let slippage_limit = slippage.unwrap_or_else(T::MaxPriceDifferenceBetweenBlocks::get); - let slippage_amount = slippage_limit.mul_floor(estimated_amount); - - Ok((estimated_amount, slippage_amount)) - } - - fn convert_weight_to_fee(weight: Weight, fee_currency: T::AssetId) -> Result { - let fee_amount_in_native = Self::weight_to_fee(weight); - let fee_amount_in_sold_asset = Self::convert_native_amount_to_currency(fee_currency, fee_amount_in_native)?; - - Ok(fee_amount_in_sold_asset) - } - - fn get_trade_weight(order: &Order, schedule_id: Option) -> Weight { - let route = &order.get_route_or_default::(); - let base_weight = match order { - Order::Sell { .. } => ::WeightInfo::on_initialize_with_sell_trade() - .saturating_add(T::AmmTradeWeights::sell_and_calculate_sell_trade_amounts_weight(route)), - Order::Buy { .. } => ::WeightInfo::on_initialize_with_buy_trade() - .saturating_add(T::AmmTradeWeights::buy_and_calculate_buy_trade_amounts_weight(route)), - }; - - if let Some(id) = schedule_id { - let extra_gas = ScheduleExtraGas::::get(id); - if extra_gas > 0 { - // Convert extra gas to weight without base weight because we already account for that - let extra_weight = T::GasWeightMapping::gas_to_weight(extra_gas, false); - return base_weight.saturating_add(extra_weight); - } - } - - base_weight - } - - fn convert_native_amount_to_currency( - asset_id: T::AssetId, - native_asset_amount: Balance, - ) -> Result { - let amount = if asset_id == T::NativeAssetId::get() { - native_asset_amount - } else { - let price = T::NativePriceOracle::price(asset_id).ok_or(Error::::CalculatingPriceError)?; - - multiply_by_rational_with_rounding(native_asset_amount, price.n, price.d, Rounding::Up) - .ok_or(ArithmeticError::Overflow)? - }; - - Ok(amount) - } - - fn get_price_from_last_block_oracle(route: &[Trade]) -> Result { - let price = - T::OraclePriceProvider::price(route, OraclePeriod::LastBlock).ok_or(Error::::CalculatingPriceError)?; - - let price_from_rational = - FixedU128::checked_from_rational(price.n, price.d).ok_or(ArithmeticError::Overflow)?; - - Ok(price_from_rational) - } - - fn get_price_from_short_oracle(route: &[Trade]) -> Result { - let price = - T::OraclePriceProvider::price(route, OraclePeriod::Short).ok_or(Error::::CalculatingPriceError)?; - - let price_from_rational = - FixedU128::checked_from_rational(price.n, price.d).ok_or(ArithmeticError::Overflow)?; - - Ok(price_from_rational) - } - - /// Increments extra gas for a schedule for the case when EvmOutOfGas error occurs. - /// Uses linear increment: MAX_EXTRA_GAS / max_retries, capped at MAX_EXTRA_GAS. - fn increment_extra_gas(schedule_id: ScheduleId, schedule: &Schedule>) { - ScheduleExtraGas::::mutate(schedule_id, |extra_gas| { - let max_retries = schedule - .max_retries - .map(|r| r as u64) - .unwrap_or_else(|| T::MaxNumberOfRetriesOnError::get() as u64); - - let Some(gas_increment) = MAX_EXTRA_GAS.checked_div(max_retries) else { - log::error!("Gas increment calculation overflowed for schedule_id: {schedule_id:?}",); - return; - }; - - let new_gas = extra_gas.saturating_add(gas_increment); - *extra_gas = new_gas.min(MAX_EXTRA_GAS); - }); - } - - /// Converts a schedule into a DCA intent, or cancels and refunds it when it cannot be converted. - fn migrate_or_cancel(schedule_id: ScheduleId, schedule: &Schedule>) { - let Order::Sell { - asset_in, - asset_out, - amount_in, - min_amount_out, - .. - } = schedule.order - else { - Self::cancel_for_migration(schedule_id, schedule, CancelReason::BuyOrder); - return; - }; - - let remaining_amount = RemainingAmounts::::get(schedule_id).unwrap_or_default(); - // A rolling schedule has no budget; its reserve is the intent pallet's own 2x buffer. - let budget = (!schedule.is_rolling()).then_some(remaining_amount); - - if budget.is_some() && remaining_amount < amount_in { - Self::cancel_for_migration(schedule_id, schedule, CancelReason::BudgetBelowTrade); - return; - } - - let params = DcaParams { - asset_in: asset_in.into(), - asset_out: asset_out.into(), - amount_in, - amount_out: min_amount_out, - slippage: schedule - .slippage - .unwrap_or_else(T::MaxPriceDifferenceBetweenBlocks::get), - budget, - period: schedule.period.saturated_into(), - }; - - match Self::convert_schedule(schedule_id, schedule, remaining_amount, params) { - Ok(intent_id) => Self::deposit_event(Event::Migrated { - id: schedule_id, - who: schedule.owner.clone(), - intent_id, - }), - Err(reason) => Self::cancel_for_migration(schedule_id, schedule, reason), - } - } - - #[transactional] - fn convert_schedule( - schedule_id: ScheduleId, - schedule: &Schedule>, - remaining_amount: Balance, - params: DcaParams, - ) -> Result { - let remainder = T::Currencies::unreserve_named( - &T::NamedReserveId::get(), - schedule.order.get_asset_in(), - &schedule.owner, - remaining_amount, - ); - // The intent pallet takes its own reserve, so anything left here would be reserved twice. - ensure!(remainder.is_zero(), CancelReason::UnreserveRemainder); - - Self::remove_schedule_from_storages(&schedule.owner, schedule_id); - - Ok(T::IntentMigrator::add_migrated_intent(schedule.owner.clone(), params)?) - } - - /// Removes a schedule and returns its remaining budget to the owner's free balance. - fn cancel_for_migration( - schedule_id: ScheduleId, - schedule: &Schedule>, - reason: CancelReason, - ) { - let refunded = RemainingAmounts::::get(schedule_id).unwrap_or_default(); - - Self::try_unreserve_all(schedule_id, schedule); - Self::remove_schedule_from_storages(&schedule.owner, schedule_id); - - Self::deposit_event(Event::MigrationCancelled { - id: schedule_id, - who: schedule.owner.clone(), - asset: schedule.order.get_asset_in(), - refunded, - reason, - }); - } - - fn remove_schedule_from_storages(owner: &T::AccountId, schedule_id: ScheduleId) { - Schedules::::remove(schedule_id); - ScheduleOwnership::::remove(owner, schedule_id); - RemainingAmounts::::remove(schedule_id); - RetriesOnError::::remove(schedule_id); - ScheduleExecutionBlock::::remove(schedule_id); - ScheduleExtraGas::::remove(schedule_id); - } -} - -pub trait RandomnessProvider { - fn generator(salt: Option) -> Result; -} - -impl RandomnessProvider for Pallet { - fn generator(salt: Option) -> Result { - let hash_value = T::RelayChainBlockHashProvider::parent_hash().ok_or(Error::::NoParentHashFound)?; - let hash_bytes = hash_value.as_fixed_bytes(); - let mut seed_arr = [0u8; 8]; - let max_len = hash_bytes.len().min(seed_arr.len()); // Ensure we don't copy more bytes, preventing potential panics - seed_arr[..max_len].copy_from_slice(&hash_bytes[..max_len]); - - let seed = match salt { - Some(salt) => u64::from_le_bytes(seed_arr).wrapping_add(salt.into()), - None => u64::from_le_bytes(seed_arr), - }; - - Ok(rand::rngs::StdRng::seed_from_u64(seed)) - } -} diff --git a/pallets/dca/src/migrations.rs b/pallets/dca/src/migrations.rs deleted file mode 100644 index 3979e66e71..0000000000 --- a/pallets/dca/src/migrations.rs +++ /dev/null @@ -1,121 +0,0 @@ -use crate::pallet; -use frame_support::traits::{Get, GetStorageVersion, OnRuntimeUpgrade, StorageVersion}; -use sp_runtime::Saturating; - -const MAX_SCHEDULES: u64 = 150; - -// This migration multiplies the periods of schedules by 3 to account for 3x faster block times -// when moving from 6s to 2s blocks. -pub struct MultiplySchedulesPeriodBy3(sp_std::marker::PhantomData); -impl OnRuntimeUpgrade for MultiplySchedulesPeriodBy3 { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { - assert_eq!( - StorageVersion::get::>(), - StorageVersion::new(2), - "DCA storage version must be v2 before multiplying schedule periods" - ); - - Ok(sp_std::vec::Vec::new()) - } - - fn on_runtime_upgrade() -> frame_support::weights::Weight { - let mut reads = 0u64; - let mut writes = 0u64; - - let on_chain_version = StorageVersion::get::>(); - let in_code_version = crate::Pallet::::in_code_storage_version(); - reads.saturating_inc(); - - if on_chain_version >= in_code_version { - // Already migrated - return T::DbWeight::get().reads(reads); - } - - if on_chain_version != StorageVersion::new(2) { - log::warn!("DCA schedule period migration skipped: expected storage version 2, got {on_chain_version:?}"); - return T::DbWeight::get().reads(reads); - } - - let schedules: sp_std::vec::Vec<_> = crate::Schedules::::iter().collect(); - let schedules_len = schedules.len() as u64; - reads.saturating_accrue(schedules_len); - - log::info!("MultiplySchedulesPeriodBy3 found schedules: {schedules_len:?}, processing cap: {MAX_SCHEDULES:?}",); - - if schedules_len > MAX_SCHEDULES { - log::error!( - "MultiplySchedulesPeriodBy3 skipped because Schedules has {schedules_len:?} entries, cap: {MAX_SCHEDULES:?}", - ); - return T::DbWeight::get().reads(reads); - } - - for (key, mut schedule) in schedules { - schedule.period = schedule.period.saturating_mul(3u32.into()); - crate::Schedules::::insert(key, schedule); - writes.saturating_inc(); - } - - // Increase on-chain StorageVersion - StorageVersion::new(3).put::>(); - writes.saturating_inc(); - - log::info!("MultiplySchedulesPeriodBy3 processed schedules: {schedules_len:?}"); - T::DbWeight::get().reads_writes(reads, writes) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_: sp_std::vec::Vec) -> Result<(), sp_runtime::TryRuntimeError> { - assert_eq!( - StorageVersion::get::>(), - StorageVersion::new(3), - "DCA storage version must be v3 after multiplying schedule periods" - ); - - Ok(()) - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::tests::mock::{RuntimeOrigin, Test, ALICE, DCA}; - use crate::tests::schedule::set_block_number; - use crate::tests::{ - mock::{ExtBuilder, HDX, ONE}, - ScheduleBuilder, - }; - use frame_support::assert_ok; - - #[test] - fn multiply_schedules_period_by_3_works() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - // Arrange - let schedule = ScheduleBuilder::new().build(); - set_block_number(500); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - - let stored_schedule = DCA::schedules(0).unwrap(); - assert_eq!(stored_schedule.period, 100); - StorageVersion::new(2).put::(); - - // Act - MultiplySchedulesPeriodBy3::::on_runtime_upgrade(); - let updated_schedule = DCA::schedules(0).unwrap(); - - // Assert - assert_eq!(updated_schedule.period, 300); - - // Storage version has been updated - let on_chain_version = StorageVersion::get::(); - assert_eq!(on_chain_version, StorageVersion::new(3)); - }); - } -} diff --git a/pallets/dca/src/tests/migration.rs b/pallets/dca/src/tests/migration.rs deleted file mode 100644 index e8a9b314de..0000000000 --- a/pallets/dca/src/tests/migration.rs +++ /dev/null @@ -1,564 +0,0 @@ -// This file is part of HydraDX. - -// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::tests::on_initialize::{proceed_to_blocknumber, set_to_blocknumber}; -use crate::tests::*; -use crate::{ - assert_balance, assert_number_of_executed_sell_trades, assert_that_schedule_has_been_removed_from_storages, - CancelReason, Error, Event as DcaEvent, Order, -}; -use frame_support::{assert_noop, assert_ok}; -use orml_traits::MultiCurrency; -use pretty_assertions::assert_eq; -use sp_runtime::DispatchError; -use std::borrow::Borrow; - -const START_BLOCK: BlockNumber = 500; -const EXECUTION_BLOCK: BlockNumber = 502; - -fn enable_migration() { - assert_ok!(DCA::set_migration_enabled(RuntimeOrigin::root(), true)); -} - -fn sell_order(amount_in: Balance, min_amount_out: Balance) -> Order { - Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in, - min_amount_out, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - } -} - -fn buy_order(amount_out: Balance, max_amount_in: Balance) -> Order { - Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out, - max_amount_in, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - } -} - -fn migrated_intent() -> (AccountId, ice_support::DcaParams) { - MIGRATED_INTENTS.with(|v| { - let intents = v.borrow(); - assert_eq!(intents.len(), 1, "exactly one intent should have been created"); - intents[0].clone() - }) -} - -#[test] -fn migration_should_convert_schedule_into_intent_when_execution_slot_arrives() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_period(ONE_HUNDRED_BLOCKS) - .with_slippage(Some(Permill::from_percent(3))) - .with_order(sell_order(10 * ONE, 5 * ONE)) - .build(); - let schedule_id = insert_schedule_into_storage(ALICE, schedule, None); - let remaining = DCA::remaining_amounts(schedule_id).unwrap(); - - enable_migration(); - - //Act - set_to_blocknumber(EXECUTION_BLOCK); - - //Assert - let (owner, params) = migrated_intent(); - assert_eq!(owner, ALICE); - assert_eq!(params.asset_in, HDX); - assert_eq!(params.asset_out, BTC); - assert_eq!(params.amount_in, 10 * ONE); - assert_eq!(params.amount_out, 5 * ONE); - assert_eq!(params.slippage, Permill::from_percent(3)); - assert_eq!(params.budget, Some(remaining)); - assert_eq!(params.period, ONE_HUNDRED_BLOCKS as u32); - - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - - expect_events(vec![DcaEvent::Migrated { - id: schedule_id, - who: ALICE, - intent_id: 1, - } - .into()]); - }); -} - -#[test] -fn migration_should_not_execute_trade_when_schedule_converts() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_order(sell_order(10 * ONE, 0)) - .build(); - insert_schedule_into_storage(ALICE, schedule, None); - enable_migration(); - - //Act - set_to_blocknumber(EXECUTION_BLOCK); - - //Assert - assert_number_of_executed_sell_trades!(0); - }); -} - -#[test] -fn migration_should_move_whole_reserve_to_intent_when_budget_is_fixed() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_order(sell_order(10 * ONE, 0)) - .build(); - let schedule_id = insert_schedule_into_storage(ALICE, schedule, None); - let remaining = DCA::remaining_amounts(schedule_id).unwrap(); - let free_before = Currencies::free_balance(HDX, &ALICE); - - enable_migration(); - - //Act - set_to_blocknumber(EXECUTION_BLOCK); - - //Assert - assert_eq!( - Currencies::reserved_balance_named(&NamedReserveId::get(), HDX, &ALICE), - 0 - ); - assert_eq!( - Currencies::reserved_balance_named(&INTENT_NAMED_RESERVE_ID, HDX, &ALICE), - remaining - ); - assert_balance!(ALICE, HDX, free_before); - }); -} - -#[test] -fn migration_should_release_excess_reserve_when_schedule_is_rolling() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let amount_in = 10 * ONE; - let schedule = ScheduleBuilder::new() - .with_total_amount(0) - .with_order(sell_order(amount_in, 0)) - .build(); - let schedule_id = insert_schedule_into_storage(ALICE, schedule, None); - let dca_reserve = DCA::remaining_amounts(schedule_id).unwrap(); - let free_before = Currencies::free_balance(HDX, &ALICE); - - enable_migration(); - - //Act - set_to_blocknumber(EXECUTION_BLOCK); - - //Assert - let (_, params) = migrated_intent(); - assert_eq!(params.budget, None, "rolling schedule must stay rolling"); - - let intent_reserve = amount_in.saturating_mul(2); - assert_eq!( - Currencies::reserved_balance_named(&INTENT_NAMED_RESERVE_ID, HDX, &ALICE), - intent_reserve - ); - // The old pallet reserved the transaction fee on top of the trade amount; the intent - // pallet does not, so the difference goes back to the owner. - assert_balance!(ALICE, HDX, free_before + dca_reserve - intent_reserve); - }); -} - -#[test] -fn migration_should_cancel_and_refund_when_order_is_buy() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_slippage(Some(Permill::from_percent(20))) - .with_order(buy_order(ONE, 50 * ONE)) - .build(); - let schedule_id = insert_schedule_into_storage(ALICE, schedule, None); - let remaining = DCA::remaining_amounts(schedule_id).unwrap(); - let free_before = Currencies::free_balance(HDX, &ALICE); - - enable_migration(); - - //Act - set_to_blocknumber(EXECUTION_BLOCK); - - //Assert - assert_number_of_executed_sell_trades!(0); - assert_balance!(ALICE, HDX, free_before + remaining); - assert_eq!( - Currencies::reserved_balance_named(&NamedReserveId::get(), HDX, &ALICE), - 0 - ); - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - - expect_events(vec![DcaEvent::MigrationCancelled { - id: schedule_id, - who: ALICE, - asset: HDX, - refunded: remaining, - reason: CancelReason::BuyOrder, - } - .into()]); - }); -} - -#[test] -fn migration_should_cancel_when_remaining_budget_is_below_one_trade() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_order(sell_order(10 * ONE, 0)) - .build(); - let schedule_id = insert_schedule_into_storage(ALICE, schedule, None); - RemainingAmounts::::insert(schedule_id, ONE); - - enable_migration(); - - //Act - set_to_blocknumber(EXECUTION_BLOCK); - - //Assert - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - expect_events(vec![DcaEvent::MigrationCancelled { - id: schedule_id, - who: ALICE, - asset: HDX, - refunded: ONE, - reason: CancelReason::BudgetBelowTrade, - } - .into()]); - }); -} - -#[test] -fn migration_should_cancel_and_refund_when_intent_creation_fails() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_order(sell_order(10 * ONE, 0)) - .build(); - let schedule_id = insert_schedule_into_storage(ALICE, schedule, None); - let remaining = DCA::remaining_amounts(schedule_id).unwrap(); - let free_before = Currencies::free_balance(HDX, &ALICE); - - enable_migration(); - MIGRATOR_SHOULD_FAIL.with(|v| *v.borrow_mut() = true); - - //Act - set_to_blocknumber(EXECUTION_BLOCK); - - //Assert - assert_balance!(ALICE, HDX, free_before + remaining); - assert_eq!( - Currencies::reserved_balance_named(&NamedReserveId::get(), HDX, &ALICE), - 0 - ); - assert_eq!( - Currencies::reserved_balance_named(&INTENT_NAMED_RESERVE_ID, HDX, &ALICE), - 0 - ); - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - - expect_events(vec![DcaEvent::MigrationCancelled { - id: schedule_id, - who: ALICE, - asset: HDX, - refunded: remaining, - reason: CancelReason::IntentCreationFailed(sp_runtime::TokenError::FundsUnavailable.into()), - } - .into()]); - }); -} - -#[test] -fn schedule_should_execute_normally_when_migration_is_disabled() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_order(sell_order(ONE, Balance::MIN)) - .build(); - insert_schedule_into_storage(ALICE, schedule, None); - - //Act - set_to_blocknumber(EXECUTION_BLOCK); - - //Assert - assert_number_of_executed_sell_trades!(1); - MIGRATED_INTENTS.with(|v| assert!(v.borrow().is_empty())); - }); -} - -#[test] -fn schedule_should_fail_when_migration_is_enabled() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - enable_migration(); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_order(sell_order(10 * ONE, 0)) - .build(); - - //Act and assert - assert_noop!( - DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, None), - Error::::MigrationInProgress - ); - }); -} - -/// The deploy-time default. Nothing writes `MigrationEnabled` — the pallet has no -/// `GenesisConfig` and no migration sets it — so the flag is absent on a fresh -/// runtime and `ValueQuery` must resolve it to `false`. If this ever flipped, a -/// runtime upgrade would start converting schedules the moment it went live. -#[test] -fn migration_enabled_should_be_false_when_never_set() { - ExtBuilder::default().build().execute_with(|| { - assert!(!crate::MigrationEnabled::::exists()); - assert!(!DCA::migration_enabled()); - }); -} - -#[test] -fn set_migration_enabled_should_unblock_scheduling_when_set_back_to_false() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - enable_migration(); - - //Act - assert_ok!(DCA::set_migration_enabled(RuntimeOrigin::root(), false)); - - //Assert - assert!(!DCA::migration_enabled()); - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_order(sell_order(10 * ONE, 0)) - .build(); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, None)); - }); -} - -#[test] -fn set_migration_enabled_should_fail_when_origin_is_not_terminate_origin() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - DCA::set_migration_enabled(RuntimeOrigin::signed(ALICE), true), - DispatchError::BadOrigin - ); - }); -} - -#[test] -fn force_cancel_should_remove_schedule_and_refund_when_called_by_terminate_origin() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_order(sell_order(10 * ONE, 0)) - .build(); - let schedule_id = insert_schedule_into_storage(ALICE, schedule, None); - let remaining = DCA::remaining_amounts(schedule_id).unwrap(); - let free_before = Currencies::free_balance(HDX, &ALICE); - - //Act - assert_ok!(DCA::force_cancel_schedules(RuntimeOrigin::root(), vec![schedule_id])); - - //Assert - assert_balance!(ALICE, HDX, free_before + remaining); - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - expect_events(vec![DcaEvent::MigrationCancelled { - id: schedule_id, - who: ALICE, - asset: HDX, - refunded: remaining, - reason: CancelReason::ForceCancelled, - } - .into()]); - }); -} - -#[test] -fn force_cancel_should_skip_unknown_ids_when_schedule_does_not_exist() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(DCA::force_cancel_schedules(RuntimeOrigin::root(), vec![42])); - }); -} - -#[test] -fn migration_should_convert_schedule_when_min_amount_out_is_dust() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_order(sell_order(10 * ONE, 1)) - .build(); - let schedule_id = insert_schedule_into_storage(ALICE, schedule, None); - - enable_migration(); - - //Act - set_to_blocknumber(EXECUTION_BLOCK); - - //Assert - let (_, params) = migrated_intent(); - assert_eq!(params.amount_out, INTENT_ED); - - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - expect_events(vec![DcaEvent::Migrated { - id: schedule_id, - who: ALICE, - intent_id: 1, - } - .into()]); - }); -} - -#[test] -fn migration_should_cancel_when_amount_in_is_below_existential_deposit() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_order(sell_order(INTENT_ED - 1, 5 * ONE)) - .build(); - let schedule_id = insert_schedule_into_storage(ALICE, schedule, None); - let remaining = DCA::remaining_amounts(schedule_id).unwrap(); - - enable_migration(); - - //Act - set_to_blocknumber(EXECUTION_BLOCK); - - //Assert - MIGRATED_INTENTS.with(|v| assert!(v.borrow().is_empty())); - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - expect_events(vec![DcaEvent::MigrationCancelled { - id: schedule_id, - who: ALICE, - asset: HDX, - refunded: remaining, - reason: CancelReason::IntentCreationFailed(INTENT_BELOW_ED), - } - .into()]); - }); -} - -#[test] -fn migration_should_use_default_slippage_when_schedule_has_none() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, START_BLOCK); - - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_slippage(None) - .with_order(sell_order(10 * ONE, 0)) - .build(); - insert_schedule_into_storage(ALICE, schedule, None); - enable_migration(); - - //Act - set_to_blocknumber(EXECUTION_BLOCK); - - //Assert - let (_, params) = migrated_intent(); - assert_eq!(params.slippage, OmnipoolMaxAllowedPriceDifference::get()); - }); -} diff --git a/pallets/dca/src/tests/mock.rs b/pallets/dca/src/tests/mock.rs deleted file mode 100644 index 0195c6e4da..0000000000 --- a/pallets/dca/src/tests/mock.rs +++ /dev/null @@ -1,1219 +0,0 @@ -// This file is part of HydraDX. - -// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate as dca; -use crate::{Config, Error, RandomnessProvider, RelayChainBlockHashProvider}; -use cumulus_primitives_core::relay_chain::Hash; -use frame_support::traits::{Everything, Nothing}; -use frame_support::weights::constants::ExtrinsicBaseWeight; -use frame_support::weights::WeightToFeeCoefficient; -use frame_support::weights::{IdentityFee, Weight}; -use frame_support::PalletId; - -use frame_support::BoundedVec; -use frame_support::{assert_ok, parameter_types}; -use frame_system as system; -use frame_system::{ensure_signed, EnsureRoot}; -use hydradx_traits::{registry::Inspect as InspectRegistry, AssetKind, NativePriceOracle, OraclePeriod, PriceOracle}; -use ice_support::{DcaParams, IntentId, IntentMigrator}; -use orml_traits::parameter_type_with_key; -use orml_traits::NamedMultiReservableCurrency; -use pallet_currencies::{BasicCurrencyAdapter, MockBoundErc20, MockErc20Currency}; -use primitive_types::U128; -use sp_core::H256; -use sp_runtime::traits::{AccountIdConversion, BlockNumberProvider, ConstU32}; -use sp_runtime::Permill; -use sp_runtime::{ - traits::{BlakeTwo256, IdentityLookup, One}, - BuildStorage, DispatchError, -}; -use sp_runtime::{Perbill, Percent}; - -use hydra_dx_math::support::rational::{round_to_rational, Rounding}; -use sp_runtime::traits::Zero; -use sp_runtime::{DispatchResult, FixedU128}; -use std::cell::RefCell; -use std::collections::HashMap; - -type Block = frame_system::mocking::MockBlock; - -pub type Balance = u128; -pub type BlockNumber = u64; -pub type AssetId = u32; -type NamedReserveIdentifier = [u8; 8]; - -pub const HDX: AssetId = 0; -pub const LRNA: AssetId = 1; -pub const DAI: AssetId = 2; -pub const BTC: AssetId = 3; -pub const FORBIDDEN_ASSET: AssetId = 4; -pub const RETRY_ON_ERROR_ASSET: AssetId = 6; -pub const REGISTERED_ASSET: AssetId = 1000; -pub const ONE_HUNDRED_BLOCKS: BlockNumber = 100; - -//Since we always use the same parent hash in the tests, the generated radiuses are always the same -pub const GENERATED_SEARCH_RADIUSES: [u64; 10] = [1, 3, 6, 10, 28, 34, 114, 207, 504, 947]; - -pub const ONE: Balance = 1_000_000_000_000; - -frame_support::construct_runtime!( - pub enum Test - { - System: frame_system, - DCA: dca, - Tokens: orml_tokens, - RouteExecutor: pallet_route_executor, - Omnipool: pallet_omnipool, - Balances: pallet_balances, - Currencies: pallet_currencies, - EmaOracle: pallet_ema_oracle, - Broadcast: pallet_broadcast, - } -); - -lazy_static::lazy_static! { - pub static ref ORIGINAL_MIN_BUDGET_IN_NATIVE: Balance = 2_000_000; - pub static ref ORIGINAL_MAX_PRICE_DIFFERENCE: Permill = Permill::from_percent(10); - pub static ref AMOUNT_OUT_FOR_OMNIPOOL_SELL: Balance = 20 * ONE; -} - -thread_local! { - pub static POSITIONS: RefCell> = RefCell::new(HashMap::default()); - pub static REGISTERED_ASSETS: RefCell> = RefCell::new(HashMap::default()); - pub static ASSET_WEIGHT_CAP: RefCell = const { RefCell::new(Permill::from_percent(100)) }; - pub static ASSET_FEE: RefCell = const { RefCell::new(Permill::from_percent(0)) }; - pub static PROTOCOL_FEE: RefCell = const { RefCell::new(Permill::from_percent(0)) }; - pub static MIN_ADDED_LIQUDIITY: RefCell = const { RefCell::new(1000u128) }; - pub static MIN_TRADE_AMOUNT: RefCell = const { RefCell::new(1000u128) }; - pub static MAX_IN_RATIO: RefCell = const { RefCell::new(1u128) }; - pub static MAX_OUT_RATIO: RefCell = const { RefCell::new(1u128) }; - pub static FEE_ASSET: RefCell> = RefCell::new(vec![(ALICE,HDX)]); - pub static MIN_BUDGET: RefCell = RefCell::new(*ORIGINAL_MIN_BUDGET_IN_NATIVE); - pub static BUY_EXECUTIONS: RefCell> = const { RefCell::new(vec![]) }; - pub static MIGRATOR_SHOULD_FAIL: RefCell = const { RefCell::new(false) }; - pub static MIGRATED_INTENTS: RefCell> = const { RefCell::new(vec![]) }; - pub static NEXT_INTENT_ID: RefCell = const { RefCell::new(1) }; - pub static SELL_EXECUTIONS: RefCell> = const { RefCell::new(vec![]) }; - pub static SET_OMNIPOOL_ON: RefCell = const { RefCell::new(true) }; - pub static MAX_PRICE_DIFFERENCE: RefCell = RefCell::new(*ORIGINAL_MAX_PRICE_DIFFERENCE); - pub static WITHDRAWAL_ADJUSTMENT: RefCell<(u32,u32, bool)> = const { RefCell::new((0u32,0u32, false)) }; - pub static CALCULATED_AMOUNT_OUT_FOR_SELL: RefCell = RefCell::new(*AMOUNT_OUT_FOR_OMNIPOOL_SELL); - pub static USE_PROD_RANDOMNESS: RefCell = const { RefCell::new(false) }; - pub static PARENT_HASH: RefCell> = RefCell::new(Some([ - 14, 87, 81, 192, 38, 229, 67, 178, 232, 171, 46, 176, 96, 153, 218, 161, 209, 229, 223, 71, 119, 143, 119, - 135, 250, 171, 69, 205, 241, 47, 227, 168, - ] - .into())); - -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct BuyExecution { - pub asset_in: AssetId, - pub asset_out: AssetId, - pub amount_out: Balance, - pub max_sell_amount: Balance, -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct SellExecution { - pub asset_in: AssetId, - pub asset_out: AssetId, - pub amount_in: Balance, - pub min_buy_amount: Balance, -} - -//NOTE: oracle is only used for benchmarking to have price from it -use pallet_ema_oracle::MAX_PERIODS; - -parameter_types! { - pub static MockBlockNumberProvider: u64 = 0; - pub SupportedPeriods: BoundedVec> = BoundedVec::truncate_from(vec![ - OraclePeriod::LastBlock, OraclePeriod::Short, OraclePeriod::TenMinutes]); -} - -impl pallet_ema_oracle::Config for Test { - type AuthorityOrigin = EnsureRoot; - type BlockNumberProvider = MockBlockNumberProvider; - type SupportedPeriods = SupportedPeriods; - type OracleWhitelist = Everything; - type InternalSources = Everything; - type MaxUniqueEntries = ConstU32<20>; - type LocationToAssetIdConversion = (); - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); - type WeightInfo = (); -} - -impl BlockNumberProvider for MockBlockNumberProvider { - type BlockNumber = BlockNumber; - - fn current_block_number() -> Self::BlockNumber { - System::block_number() - } -} - -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const SS58Prefix: u8 = 63; -} - -impl system::Config for Test { - type BaseCallFilter = Everything; - type BlockWeights = (); - type BlockLength = (); - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = RuntimeTask; - type Nonce = u64; - type Block = Block; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = u64; - type Lookup = IdentityLookup; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = BlockHashCount; - type DbWeight = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = SS58Prefix; - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); - type ExtensionsWeightInfo = (); -} - -pub type Amount = i128; - -parameter_type_with_key! { - pub ExistentialDeposits: |_currency_id: AssetId| -> Balance { - One::one() - }; -} - -impl orml_tokens::Config for Test { - type Balance = Balance; - type Amount = Amount; - type CurrencyId = AssetId; - type WeightInfo = (); - type ExistentialDeposits = ExistentialDeposits; - type MaxLocks = (); - type DustRemovalWhitelist = Nothing; - type ReserveIdentifier = NamedReserveIdentifier; - type MaxReserves = MaxReserves; - type CurrencyHooks = (); -} - -parameter_types! { - pub const HDXAssetId: AssetId = HDX; - pub const LRNAAssetId: AssetId = LRNA; - pub const PosiitionCollectionId: u32= 1000; - - pub const ExistentialDeposit: u128 = 500; - pub const MaxReserves: u32 = 50; - pub ProtocolFee: Permill = PROTOCOL_FEE.with(|v| *v.borrow()); - pub AssetFee: Permill = ASSET_FEE.with(|v| *v.borrow()); - pub BurnFee: Permill = Permill::zero(); - pub AssetWeightCap: Permill =ASSET_WEIGHT_CAP.with(|v| *v.borrow()); - pub MinAddedLiquidity: Balance = MIN_ADDED_LIQUDIITY.with(|v| *v.borrow()); - pub MinTradeAmount: Balance = MIN_TRADE_AMOUNT.with(|v| *v.borrow()); - pub MaxInRatio: Balance = MAX_IN_RATIO.with(|v| *v.borrow()); - pub MaxOutRatio: Balance = MAX_OUT_RATIO.with(|v| *v.borrow()); - pub const TVLCap: Balance = Balance::MAX; - - pub const TransactionByteFee: Balance = 10 * ONE / 100_000; - - pub const TreasuryPalletId: PalletId = PalletId(*b"aca/trsy"); - pub TreasuryAccount: AccountId = TreasuryPalletId::get().into_account_truncating(); -} - -impl pallet_omnipool::Config for Test { - type AssetId = AssetId; - type PositionItemId = u32; - type Currency = Currencies; - type HubAssetId = LRNAAssetId; - type WeightInfo = (); - type HdxAssetId = HDXAssetId; - type NFTCollectionId = PosiitionCollectionId; - type NFTHandler = DummyNFT; - type AssetRegistry = DummyRegistry; - type MinimumTradingLimit = MinTradeAmount; - type MinimumPoolLiquidity = MinAddedLiquidity; - type UpdateTradabilityOrigin = EnsureRoot; - type MaxInRatio = MaxInRatio; - type MaxOutRatio = MaxOutRatio; - type CollectionId = u32; - type AuthorityOrigin = EnsureRoot; - type OmnipoolHooks = (); - type PriceBarrier = (); - type MinWithdrawalFee = (); - type ExternalPriceOracle = WithdrawFeePriceOracle; - type Fee = FeeProvider; - type BaseFeeOnly = frame_support::traits::Nothing; - type BurnProtocolFee = BurnFee; -} - -pub struct WithdrawFeePriceOracle; - -impl ExternalPriceProvider for WithdrawFeePriceOracle { - type Error = DispatchError; - - fn get_price(asset_a: AssetId, asset_b: AssetId) -> Result { - assert_eq!(asset_a, LRNA); - let asset_state = Omnipool::load_asset_state(asset_b)?; - let price = EmaPrice::new(asset_state.hub_reserve, asset_state.reserve); - - let adjusted_price = WITHDRAWAL_ADJUSTMENT.with(|v| { - let (n, d, neg) = *v.borrow(); - let adjustment = EmaPrice::new(price.n * n as u128, price.d * d as u128); - if neg { - saturating_sub(price, adjustment) - } else { - saturating_add(price, adjustment) - } - }); - - Ok(adjusted_price) - } - - fn get_price_weight() -> Weight { - todo!() - } -} - -pub struct WeightToFee; - -impl WeightToFeePolynomial for WeightToFee { - type Balance = Balance; - - /// Handles converting a weight scalar to a fee value, based on the scale and granularity of the - /// node's balance type. - /// - /// This should typically create a mapping between the following ranges: - /// - [0, MAXIMUM_BLOCK_WEIGHT] - /// - [Balance::min, Balance::max] - /// - /// Yet, it can be used for any other sort of change to weight-fee. Some examples being: - /// - Setting it to `0` will essentially disable the weight fee. - /// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged. - fn polynomial() -> WeightToFeeCoefficients { - // extrinsic base weight (smallest non-zero weight) is mapped to 1/10 CENT - let p = ONE; // 1_000_000_000_000 - let q = 10 * Balance::from(ExtrinsicBaseWeight::get().ref_time()); // 7_919_840_000 - smallvec![WeightToFeeCoefficient { - degree: 1, - negative: false, - coeff_frac: Perbill::from_rational(p % q, q), - coeff_integer: p / q, // 124 - }] - } -} - -impl pallet_balances::Config for Test { - type MaxLocks = (); - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Pallet; - type WeightInfo = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = NamedReserveIdentifier; - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); - type DoneSlashHandler = (); -} - -impl pallet_currencies::Config for Test { - type MultiCurrency = Tokens; - type NativeCurrency = BasicCurrencyAdapter; - type Erc20Currency = MockErc20Currency; - type BoundErc20 = MockBoundErc20; - type ReserveAccount = TreasuryAccount; - type GetNativeCurrencyId = NativeCurrencyId; - type RegistryInspect = MockBoundErc20; - type EgressHandler = pallet_currencies::MockEgressHandler; - type WeightInfo = (); -} - -pub const ASSET_PAIR_ACCOUNT: AccountId = 12; - -parameter_types! { - pub MaxNumberOfTrades: u8 = 3; - pub DefaultRoutePoolType: PoolType = PoolType::Omnipool; - pub const RouteValidationOraclePeriod: OraclePeriod = OraclePeriod::TenMinutes; - -} - -impl pallet_broadcast::Config for Test {} - -type Pools = (OmniPool, Xyk); - -impl pallet_route_executor::Config for Test { - type AssetId = AssetId; - type Balance = Balance; - type NativeAssetId = NativeCurrencyId; - type Currency = FungibleCurrencies; - type AMM = Pools; - type DefaultRoutePoolType = DefaultRoutePoolType; - type ForceInsertOrigin = EnsureRoot; - type OraclePriceProvider = PriceProviderMock; - type OraclePeriod = RouteValidationOraclePeriod; - type WeightInfo = (); -} - -pub struct PriceProviderMock {} - -impl PriceOracle for crate::tests::mock::PriceProviderMock { - type Price = Ratio; - - fn price(_: &[Trade], period: OraclePeriod) -> Option { - if period == OraclePeriod::Short { - return Some(Ratio::new(80, 100)); - } - Some(Ratio::new(88, 100)) - } -} - -type OriginForRuntime = OriginFor; -pub const INVALID_CALCULATION_AMOUNT: Balance = 999; -pub const CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY: Balance = 10 * ONE; - -pub struct OmniPool; -pub struct Xyk; - -impl TradeExecution for OmniPool { - type Error = DispatchError; - - fn calculate_out_given_in( - pool_type: PoolType, - _asset_in: AssetId, - _asset_out: AssetId, - amount_in: Balance, - ) -> Result> { - if !matches!(pool_type, PoolType::Omnipool) { - return Err(ExecutorError::NotSupported); - } - - if amount_in == INVALID_CALCULATION_AMOUNT { - return Err(ExecutorError::Error(DispatchError::Other("Some error happened"))); - } - - let amount_out = CALCULATED_AMOUNT_OUT_FOR_SELL.with(|v| *v.borrow()); - Ok(amount_out) - } - - fn calculate_in_given_out( - pool_type: PoolType, - _asset_in: AssetId, - _asset_out: AssetId, - amount_out: Balance, - ) -> Result> { - if !matches!(pool_type, PoolType::Omnipool) { - return Err(ExecutorError::NotSupported); - } - - if amount_out == INVALID_CALCULATION_AMOUNT { - return Err(ExecutorError::Error(DispatchError::Other("Some error happened"))); - } - - Ok(CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY) - } - - fn execute_sell( - who: OriginForRuntime, - pool_type: PoolType, - asset_in: AssetId, - asset_out: AssetId, - amount_in: Balance, - min_limit: Balance, - ) -> Result<(), ExecutorError> { - if !matches!(pool_type, PoolType::Omnipool) { - return Err(ExecutorError::NotSupported); - } - - if asset_in == FORBIDDEN_ASSET { - return Err(ExecutorError::Error(pallet_omnipool::Error::::NotAllowed.into())); - } - - if asset_in == RETRY_ON_ERROR_ASSET { - return Err(ExecutorError::Error( - pallet_route_executor::Error::::TradingLimitReached.into(), - )); - } - - SELL_EXECUTIONS.with(|v| { - let mut m = v.borrow_mut(); - m.push(SellExecution { - asset_in, - asset_out, - amount_in, - min_buy_amount: min_limit, - }); - }); - - let Ok(who) = ensure_signed(who) else { - return Err(ExecutorError::Error(Error::::InvalidState.into())); - }; - let amount_out = CALCULATED_AMOUNT_OUT_FOR_SELL.with(|v| *v.borrow()); - - Currencies::transfer(RuntimeOrigin::signed(ASSET_PAIR_ACCOUNT), who, asset_out, amount_out) - .map_err(ExecutorError::Error)?; - Currencies::transfer(RuntimeOrigin::signed(who), ASSET_PAIR_ACCOUNT, asset_in, amount_in) - .map_err(ExecutorError::Error)?; - - Ok(()) - } - - fn execute_buy( - origin: OriginForRuntime, - pool_type: PoolType, - asset_in: AssetId, - asset_out: AssetId, - amount_out: Balance, - max_limit: Balance, - ) -> Result<(), ExecutorError> { - if !matches!(pool_type, PoolType::Omnipool) { - return Err(ExecutorError::NotSupported); - } - - BUY_EXECUTIONS.with(|v| { - let mut m = v.borrow_mut(); - m.push(BuyExecution { - asset_in, - asset_out, - amount_out, - max_sell_amount: max_limit, - }); - }); - - let Ok(who) = ensure_signed(origin) else { - return Err(ExecutorError::Error(Error::::InvalidState.into())); - }; - let amount_in = CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY; - - Currencies::transfer(RuntimeOrigin::signed(ASSET_PAIR_ACCOUNT), who, asset_out, amount_out) - .map_err(ExecutorError::Error)?; - Currencies::transfer(RuntimeOrigin::signed(who), ASSET_PAIR_ACCOUNT, asset_in, amount_in) - .map_err(ExecutorError::Error)?; - - Ok(()) - } - - fn get_liquidity_depth( - _pool_type: PoolType, - _asset_a: AssetId, - _asset_b: AssetId, - ) -> Result> { - todo!("Not implemented as not used directly within DCA context") - } - - fn calculate_spot_price_with_fee( - _pool_type: PoolType, - _asset_a: AssetId, - _asset_b: AssetId, - ) -> Result> { - todo!("No need to implement it as this is not used directly in DCA") - } -} - -pub const XYK_SELL_CALCULATION_RESULT: Balance = ONE * 5 / 4; -pub const XYK_BUY_CALCULATION_RESULT: Balance = ONE / 3; - -impl TradeExecution for Xyk { - type Error = DispatchError; - - fn calculate_out_given_in( - pool_type: PoolType, - _asset_in: AssetId, - _asset_out: AssetId, - _: Balance, - ) -> Result> { - if !matches!(pool_type, PoolType::XYK) { - return Err(ExecutorError::NotSupported); - } - - Ok(XYK_SELL_CALCULATION_RESULT) - } - - fn calculate_in_given_out( - pool_type: PoolType, - _asset_in: AssetId, - _asset_out: AssetId, - _: Balance, - ) -> Result> { - if !matches!(pool_type, PoolType::XYK) { - return Err(ExecutorError::NotSupported); - } - - Ok(XYK_BUY_CALCULATION_RESULT) - } - - fn execute_sell( - _who: OriginForRuntime, - pool_type: PoolType, - asset_in: AssetId, - asset_out: AssetId, - amount_in: Balance, - min_limit: Balance, - ) -> Result<(), ExecutorError> { - if !matches!(pool_type, PoolType::XYK) { - return Err(ExecutorError::NotSupported); - } - - SELL_EXECUTIONS.with(|v| { - let mut m = v.borrow_mut(); - m.push(SellExecution { - asset_in, - asset_out, - amount_in, - min_buy_amount: min_limit, - }); - }); - - let amount_out = XYK_SELL_CALCULATION_RESULT; - - Currencies::transfer(RuntimeOrigin::signed(ASSET_PAIR_ACCOUNT), ALICE, asset_out, amount_out) - .map_err(ExecutorError::Error)?; - Currencies::transfer(RuntimeOrigin::signed(ALICE), ASSET_PAIR_ACCOUNT, asset_in, amount_in) - .map_err(ExecutorError::Error)?; - - Ok(()) - } - - fn execute_buy( - _who: OriginForRuntime, - pool_type: PoolType, - asset_in: AssetId, - asset_out: AssetId, - amount_out: Balance, - max_limit: Balance, - ) -> Result<(), ExecutorError> { - if !matches!(pool_type, PoolType::XYK) { - return Err(ExecutorError::NotSupported); - } - - let who = ensure_signed(_who).unwrap(); - - BUY_EXECUTIONS.with(|v| { - let mut m = v.borrow_mut(); - m.push(BuyExecution { - asset_in, - asset_out, - amount_out, - max_sell_amount: max_limit, - }); - }); - - let amount_in = XYK_BUY_CALCULATION_RESULT; - - Currencies::transfer(RuntimeOrigin::signed(ASSET_PAIR_ACCOUNT), who, asset_out, amount_out) - .map_err(ExecutorError::Error)?; - Currencies::transfer(RuntimeOrigin::signed(who), ASSET_PAIR_ACCOUNT, asset_in, amount_in) - .map_err(ExecutorError::Error)?; - - Ok(()) - } - - fn get_liquidity_depth( - _pool_type: PoolType, - _asset_a: AssetId, - _asset_b: AssetId, - ) -> Result> { - todo!("No need to implement it as this is not used directly in DCA") - } - - fn calculate_spot_price_with_fee( - _pool_type: PoolType, - _asset_a: AssetId, - _asset_b: AssetId, - ) -> Result> { - todo!("No need to implement it as this is not used directly in DCA") - } -} - -parameter_types! { - pub NativeCurrencyId: AssetId = HDX; - pub MinBudgetInNativeCurrency: Balance= MIN_BUDGET.with(|v| *v.borrow()); - pub MaxSchedulePerBlock: u32 = 20; - pub OmnipoolMaxAllowedPriceDifference: Permill = MAX_PRICE_DIFFERENCE.with(|v| *v.borrow()); - pub MaxConfigurablePriceDifference: Permill = Permill::from_percent(20); - pub MinimalPeriod: u32 = 5; - pub BumpChance: Percent = Percent::from_percent(0); - pub NamedReserveId: NamedReserveIdentifier = *b"dcaorder"; - pub MaxNumberOfRetriesOnError: u8 = 3; - pub ExchangeFeeRate: (u32, u32) = (3, 1000); -} - -pub struct RandomnessProviderMock {} - -impl RandomnessProvider for RandomnessProviderMock { - fn generator(salt: Option) -> Result { - let use_prod_randomness = USE_PROD_RANDOMNESS.with(|v| *v.borrow()); - - if use_prod_randomness { - DCA::generator(salt) - } else { - Ok(StdRng::seed_from_u64(0)) - } - } -} - -/// Stand-in for `pallet-intent`. Mirrors the reserve it would take, and the existential-deposit -/// contract of `do_add_migrated_intent` — `amount_out` clamped up, sub-ED `amount_in` rejected — -/// so the migration tests stay meaningful. -pub struct IntentMigratorMock; - -pub const INTENT_NAMED_RESERVE_ID: NamedReserveIdentifier = *b"ICE_int#"; -/// Existential deposit the stand-in reports for every asset. -pub const INTENT_ED: Balance = ONE / 1_000; -/// What the stand-in returns for a sub-ED `amount_in`. Not `DispatchError::Other` — its message is -/// dropped by the SCALE round-trip the `CancelReason` makes through the event. -pub const INTENT_BELOW_ED: DispatchError = DispatchError::Token(sp_runtime::TokenError::BelowMinimum); - -impl IntentMigrator for IntentMigratorMock { - fn add_migrated_intent(owner: AccountId, mut params: DcaParams) -> Result { - if MIGRATOR_SHOULD_FAIL.with(|v| *v.borrow()) { - return Err(sp_runtime::TokenError::FundsUnavailable.into()); - } - - frame_support::ensure!(params.amount_in >= INTENT_ED, INTENT_BELOW_ED); - params.amount_out = params.amount_out.max(INTENT_ED); - - let reserve_amount = params.budget.unwrap_or_else(|| params.amount_in.saturating_mul(2)); - Currencies::reserve_named(&INTENT_NAMED_RESERVE_ID, params.asset_in, &owner, reserve_amount)?; - - MIGRATED_INTENTS.with(|v| v.borrow_mut().push((owner, params))); - - Ok(NEXT_INTENT_ID.with(|v| { - let mut id = v.borrow_mut(); - let current = *id; - *id = id.saturating_add(1); - current - })) - } -} - -impl Config for Test { - type AssetId = AssetId; - type Currencies = Currencies; - type IntentMigrator = IntentMigratorMock; - type RandomnessProvider = RandomnessProviderMock; - type MinBudgetInNativeCurrency = MinBudgetInNativeCurrency; - type MaxSchedulePerBlock = MaxSchedulePerBlock; - type NativeAssetId = NativeCurrencyId; - type FeeReceiver = TreasuryAccount; - type WeightToFee = IdentityFee; - type WeightInfo = (); - type OraclePriceProvider = PriceProviderMock; - type RouteExecutor = RouteExecutor; - type RouteProvider = DefaultRouteProvider; - type MaxPriceDifferenceBetweenBlocks = OmnipoolMaxAllowedPriceDifference; - type MaxConfigurablePriceDifferenceBetweenBlocks = MaxConfigurablePriceDifference; - type MinimalPeriod = MinimalPeriod; - type BumpChance = BumpChance; - type NamedReserveId = NamedReserveId; - type MaxNumberOfRetriesOnError = MaxNumberOfRetriesOnError; - type TerminateOrigin = EnsureRoot; - type RelayChainBlockHashProvider = ParentHashGetterMock; - type AmmTradeWeights = (); - type MinimumTradingLimit = MinTradeAmount; - type NativePriceOracle = NativePriceOracleMock; - type AccountFeeCurrency = AccountFeeCurrencyMock; - type RetryOnError = RetryOnErrorMock; - type ExtraGasSupport = ExtraGasSetterMock; - type GasWeightMapping = MockGasWeightMapping; -} - -pub struct RetryOnErrorMock; - -impl frame_support::traits::Contains for RetryOnErrorMock { - fn contains(t: &DispatchError) -> bool { - *t == pallet_route_executor::Error::::TradingLimitReached.into() - } -} - -pub struct ExtraGasSetterMock; - -impl ExtraGasSupport for ExtraGasSetterMock { - fn set_extra_gas(_gas: u64) {} - - fn clear_extra_gas() {} - - fn out_of_gas_error() -> DispatchError { - DispatchError::Other("Out of gas") - } -} - -pub struct MockGasWeightMapping; -impl pallet_evm::GasWeightMapping for MockGasWeightMapping { - fn gas_to_weight(gas: u64, _without_base_weight: bool) -> Weight { - // Convert gas to weight with a simple ratio: 1 gas = 1 weight unit - // This ensures extra gas actually affects the weight calculation in tests - Weight::from_parts(gas, 0) - } - fn weight_to_gas(weight: Weight) -> u64 { - weight.ref_time() - } -} - -thread_local! { - /// Assets that can pay fees. Empty means "everything", which is what most DCA tests assume. - pub static NON_FEE_ASSETS: RefCell> = const { RefCell::new(Vec::new()) }; - /// Fee currency reported for every account. - pub static ACCOUNT_FEE_CURRENCY: RefCell = const { RefCell::new(HDX) }; -} - -pub struct AccountFeeCurrencyMock; - -impl AccountFeeCurrency for AccountFeeCurrencyMock { - type AssetId = AssetId; - - fn get(_who: &AccountId) -> Self::AssetId { - ACCOUNT_FEE_CURRENCY.with(|v| *v.borrow()) - } - - fn set(_who: &AccountId, _asset_id: Self::AssetId) -> DispatchResult { - Ok(()) - } - - fn is_payment_currency(asset_id: Self::AssetId) -> DispatchResult { - if NON_FEE_ASSETS.with(|v| v.borrow().contains(&asset_id)) { - return Err(DispatchError::Other("NotAFeeCurrency")); - } - Ok(()) - } -} - -pub struct NativePriceOracleMock; - -impl NativePriceOracle for NativePriceOracleMock { - fn price(_: AssetId) -> Option { - Some(EmaPrice::from((88, 100))) - } -} - -pub struct DefaultRouteProvider; - -impl RouteProvider for DefaultRouteProvider {} - -pub struct ParentHashGetterMock {} - -impl RelayChainBlockHashProvider for ParentHashGetterMock { - fn parent_hash() -> Option { - PARENT_HASH.with(|v| *v.borrow()) - } -} - -use frame_support::traits::tokens::nonfungibles::{Create, Inspect, Mutate}; -use frame_support::weights::{WeightToFeeCoefficients, WeightToFeePolynomial}; -use frame_system::pallet_prelude::OriginFor; -use hydra_dx_math::ema::EmaPrice; -use hydra_dx_math::to_u128_wrapper; -use hydra_dx_math::types::Ratio; -use hydradx_traits::evm::ExtraGasSupport; -use hydradx_traits::fee::GetDynamicFee; -use hydradx_traits::router::{ExecutorError, PoolType, RouteProvider, Trade, TradeExecution}; -use hydradx_traits::AccountFeeCurrency; -use pallet_currencies::fungibles::FungibleCurrencies; -use pallet_omnipool::traits::ExternalPriceProvider; -use rand::prelude::StdRng; -use rand::SeedableRng; -use smallvec::smallvec; - -pub struct DummyNFT; - -impl> Inspect for DummyNFT { - type ItemId = u32; - type CollectionId = u32; - - fn owner(_class: &Self::CollectionId, instance: &Self::ItemId) -> Option { - let mut owner: Option = None; - - POSITIONS.with(|v| { - if let Some(o) = v.borrow().get(instance) { - owner = Some((*o).into()); - } - }); - owner - } -} - -impl> Create for DummyNFT { - fn create_collection(_class: &Self::CollectionId, _who: &AccountId, _admin: &AccountId) -> DispatchResult { - Ok(()) - } -} - -impl + Into + Copy> Mutate for DummyNFT { - fn mint_into(_class: &Self::CollectionId, _instance: &Self::ItemId, _who: &AccountId) -> DispatchResult { - POSITIONS.with(|v| { - let mut m = v.borrow_mut(); - m.insert(*_instance, (*_who).into()); - }); - Ok(()) - } - - fn burn( - _class: &Self::CollectionId, - instance: &Self::ItemId, - _maybe_check_owner: Option<&AccountId>, - ) -> DispatchResult { - POSITIONS.with(|v| { - let mut m = v.borrow_mut(); - m.remove(instance); - }); - Ok(()) - } -} - -pub struct DummyRegistry(sp_std::marker::PhantomData); - -impl InspectRegistry for DummyRegistry -where - T::AssetId: Into + From, -{ - type AssetId = AssetId; - type Location = u8; - - fn asset_type(_id: Self::AssetId) -> Option { - unimplemented!() - } - - fn is_sufficient(id: Self::AssetId) -> bool { - id <= 2000 - } - - fn decimals(_id: Self::AssetId) -> Option { - unimplemented!() - } - - fn exists(asset_id: AssetId) -> bool { - let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id)).copied()); - asset.is_some() - } - - fn is_banned(_id: Self::AssetId) -> bool { - unimplemented!() - } - - fn asset_name(_id: Self::AssetId) -> Option> { - unimplemented!() - } - - fn asset_symbol(_id: Self::AssetId) -> Option> { - unimplemented!() - } - - fn existential_deposit(_id: Self::AssetId) -> Option { - unimplemented!() - } -} - -pub type AccountId = u64; - -pub const ALICE: AccountId = 1; -pub const BOB: AccountId = 2; - -pub struct ExtBuilder { - endowed_accounts: Vec<(u64, AssetId, Balance)>, - registered_assets: Vec, - asset_weight_cap: Permill, - register_stable_asset: bool, - init_pool: Option<(FixedU128, FixedU128)>, - pool_tokens: Vec<(AssetId, FixedU128, AccountId, Balance)>, - max_price_difference: Permill, - min_trading_limit: Balance, -} - -impl Default for ExtBuilder { - fn default() -> Self { - // If eg. tests running on one thread only, this thread local is shared. - // let's make sure that it is empty for each test case - // or set to original default value - REGISTERED_ASSETS.with(|v| { - v.borrow_mut().clear(); - }); - POSITIONS.with(|v| { - v.borrow_mut().clear(); - }); - - Self { - endowed_accounts: vec![(Omnipool::protocol_account(), DAI, 1000 * ONE)], - asset_weight_cap: Permill::from_percent(100), - registered_assets: vec![], - init_pool: None, - register_stable_asset: true, - pool_tokens: vec![], - max_price_difference: Permill::from_percent(10), - min_trading_limit: 1000, - } - } -} - -impl ExtBuilder { - pub fn with_endowed_accounts(mut self, accounts: Vec<(u64, AssetId, Balance)>) -> Self { - self.endowed_accounts = accounts; - self - } - - pub fn with_max_price_difference(mut self, price_diff: Permill) -> Self { - self.max_price_difference = price_diff; - self - } - - pub fn with_min_trading_limit(mut self, limit: Balance) -> Self { - self.min_trading_limit = limit; - self - } - - pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); - // Add DAi and HDX as pre-registered assets - REGISTERED_ASSETS.with(|v| { - if self.register_stable_asset { - v.borrow_mut().insert(DAI, DAI); - } - v.borrow_mut().insert(HDX, HDX); - v.borrow_mut().insert(REGISTERED_ASSET, REGISTERED_ASSET); - self.registered_assets.iter().for_each(|asset| { - v.borrow_mut().insert(*asset, *asset); - }); - }); - - MAX_PRICE_DIFFERENCE.with(|v| { - *v.borrow_mut() = self.max_price_difference; - }); - - MIGRATOR_SHOULD_FAIL.with(|v| *v.borrow_mut() = false); - MIGRATED_INTENTS.with(|v| v.borrow_mut().clear()); - NEXT_INTENT_ID.with(|v| *v.borrow_mut() = 1); - - MIN_TRADE_AMOUNT.with(|v| { - *v.borrow_mut() = self.min_trading_limit; - }); - - let mut initial_native_accounts: Vec<(AccountId, Balance)> = vec![(ASSET_PAIR_ACCOUNT, 10000 * ONE)]; - let additional_accounts: Vec<(AccountId, Balance)> = self - .endowed_accounts - .iter() - .filter(|a| a.1 == HDX) - .flat_map(|(x, _, amount)| vec![(*x, *amount)]) - .collect::<_>(); - - initial_native_accounts.extend(additional_accounts); - - pallet_balances::GenesisConfig:: { - balances: initial_native_accounts, - dev_accounts: None, - } - .assimilate_storage(&mut t) - .unwrap(); - - let mut initial_accounts = vec![ - (ASSET_PAIR_ACCOUNT, LRNA, 10000 * ONE), - (ASSET_PAIR_ACCOUNT, DAI, 10000 * ONE), - (ASSET_PAIR_ACCOUNT, BTC, 100000000 * ONE), - ]; - - initial_accounts.extend(self.endowed_accounts); - - orml_tokens::GenesisConfig:: { - balances: initial_accounts, - } - .assimilate_storage(&mut t) - .unwrap(); - - let mut r: sp_io::TestExternalities = t.into(); - - if let Some((stable_price, native_price)) = self.init_pool { - r.execute_with(|| { - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - HDXAssetId::get(), - native_price, - Permill::from_percent(100), - Omnipool::protocol_account(), - )); - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - DAI, - stable_price, - Permill::from_percent(100), - Omnipool::protocol_account(), - )); - - for (asset_id, price, owner, amount) in self.pool_tokens { - assert_ok!(Tokens::transfer( - RuntimeOrigin::signed(owner), - Omnipool::protocol_account(), - asset_id, - amount - )); - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - asset_id, - price, - self.asset_weight_cap, - owner - )); - } - }); - } - - r - } -} - -pub fn set_max_price_diff(diff: Permill) { - MAX_PRICE_DIFFERENCE.with(|v| { - *v.borrow_mut() = diff; - }); -} - -pub fn set_sell_amount_out(balance: Balance) { - CALCULATED_AMOUNT_OUT_FOR_SELL.with(|v| { - *v.borrow_mut() = balance; - }); -} - -pub fn use_prod_randomness() { - USE_PROD_RANDOMNESS.with(|v| { - *v.borrow_mut() = true; - }); -} - -pub fn set_parent_hash(hash: Option) { - PARENT_HASH.with(|v| { - *v.borrow_mut() = hash; - }); -} - -pub fn expect_events(e: Vec) { - test_utils::expect_events::(e); -} - -pub fn expect_dca_events(e: Vec) { - let last_events = test_utils::last_events::(e.len()); - - let mut dca_events = vec![]; - - for event in &last_events { - let e = event.clone(); - if matches!( - e, - RuntimeEvent::DCA(crate::Event::::ExecutionStarted { .. }) - | RuntimeEvent::DCA(crate::Event::::Scheduled { .. }) - | RuntimeEvent::DCA(crate::Event::::ExecutionPlanned { .. }) - | RuntimeEvent::DCA(crate::Event::::TradeExecuted { .. }) - | RuntimeEvent::DCA(crate::Event::::TradeFailed { .. }) - | RuntimeEvent::DCA(crate::Event::::Terminated { .. }) - | RuntimeEvent::DCA(crate::Event::::Completed { .. }) - ) { - dca_events.push(e); - } - } - - pretty_assertions::assert_eq!(dca_events, e); -} - -#[macro_export] -macro_rules! assert_executed_sell_trades { - ($expected_trades:expr) => {{ - SELL_EXECUTIONS.borrow().with(|v| { - let trades = v.borrow().clone(); - assert_eq!(trades, $expected_trades); - }); - }}; -} - -#[macro_export] -macro_rules! assert_executed_buy_trades { - ($expected_trades:expr) => {{ - BUY_EXECUTIONS.borrow().with(|v| { - let trades = v.borrow().clone(); - assert_eq!(trades, $expected_trades); - }); - }}; -} - -#[macro_export] -macro_rules! assert_number_of_executed_buy_trades { - ($number_of_trades:expr) => {{ - BUY_EXECUTIONS.borrow().with(|v| { - let trades = v.borrow().clone(); - assert_eq!(trades.len(), $number_of_trades); - }); - }}; -} - -#[macro_export] -macro_rules! assert_number_of_executed_sell_trades { - ($number_of_trades:expr) => {{ - SELL_EXECUTIONS.borrow().with(|v| { - let trades = v.borrow().clone(); - assert_eq!(trades.len(), $number_of_trades); - }); - }}; -} - -pub(super) fn saturating_add(l: EmaPrice, r: EmaPrice) -> EmaPrice { - if l.n.is_zero() || r.n.is_zero() { - return EmaPrice::new(l.n, l.d); - } - let (l_n, l_d, r_n, r_d) = to_u128_wrapper!(l.n, l.d, r.n, r.d); - // n = l.n * r.d - r.n * l.d - let n = l_n.full_mul(r_d).saturating_add(r_n.full_mul(l_d)); - // d = l.d * r.d - let d = l_d.full_mul(r_d); - round_to_rational((n, d), Rounding::Nearest).into() -} - -pub(super) fn saturating_sub(l: EmaPrice, r: EmaPrice) -> EmaPrice { - if l.n.is_zero() || r.n.is_zero() { - return EmaPrice::new(l.n, l.d); - } - let (l_n, l_d, r_n, r_d) = to_u128_wrapper!(l.n, l.d, r.n, r.d); - // n = l.n * r.d - r.n * l.d - let n = l_n.full_mul(r_d).saturating_sub(r_n.full_mul(l_d)); - // d = l.d * r.d - let d = l_d.full_mul(r_d); - round_to_rational((n, d), Rounding::Nearest).into() -} - -pub struct FeeProvider; - -impl GetDynamicFee<(AssetId, Balance)> for FeeProvider { - type Fee = (Permill, Permill); - fn get(_: (AssetId, Balance)) -> Self::Fee { - (ASSET_FEE.with(|v| *v.borrow()), PROTOCOL_FEE.with(|v| *v.borrow())) - } - - fn get_and_store(key: (AssetId, Balance)) -> Self::Fee { - Self::get(key) - } -} diff --git a/pallets/dca/src/tests/mod.rs b/pallets/dca/src/tests/mod.rs deleted file mode 100644 index edf2effef0..0000000000 --- a/pallets/dca/src/tests/mod.rs +++ /dev/null @@ -1,225 +0,0 @@ -use crate::tests::mock::*; -use crate::{ - Balance, Event, Order, RemainingAmounts, RetriesOnError, Schedule, ScheduleExecutionBlock, ScheduleId, - ScheduleIdSequencer, ScheduleIdsPerBlock, ScheduleOwnership, Schedules, -}; -use frame_support::assert_ok; -use hydradx_traits::router::PoolType; -use hydradx_traits::router::RouterT; -use hydradx_traits::router::Trade; -use orml_traits::NamedMultiReservableCurrency; -use sp_runtime::traits::ConstU32; -use sp_runtime::{BoundedVec, Permill}; - -pub mod migration; -pub mod mock; -pub mod on_initialize; -pub mod schedule; -pub mod storage_injection_fidelity; -pub mod terminate; -pub mod unlock_reserves; - -#[macro_export] -macro_rules! assert_balance { - ( $x:expr, $y:expr, $z:expr) => {{ - assert_eq!(Currencies::free_balance($y, &$x), $z); - }}; -} - -pub struct ScheduleBuilder { - pub owner: Option, - pub period: Option, - pub order: Option>, - pub total_amount: Option, - pub max_retries: Option>, - pub slippage: Option>, - pub stability_threshold: Option>, -} - -impl ScheduleBuilder { - pub fn new() -> ScheduleBuilder { - ScheduleBuilder { - owner: Some(ALICE), - period: Some(ONE_HUNDRED_BLOCKS), - stability_threshold: Some(None), - slippage: Some(None), - total_amount: Some(1000 * ONE), - max_retries: Some(None), - order: Some(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: 10 * ONE, - min_amount_out: 0, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }), - } - } - - fn with_owner(mut self, owner: AccountId) -> ScheduleBuilder { - self.owner = Some(owner); - self - } - - fn with_period(mut self, period: BlockNumber) -> ScheduleBuilder { - self.period = Some(period); - self - } - - fn with_order(mut self, buy_order: Order) -> ScheduleBuilder { - self.order = Some(buy_order); - self - } - - fn with_total_amount(mut self, total_amount: Balance) -> ScheduleBuilder { - self.total_amount = Some(total_amount); - self - } - - fn with_price_stability_threshold(mut self, treshold: Option) -> ScheduleBuilder { - self.stability_threshold = Some(treshold); - self - } - - fn with_slippage(mut self, slippage: Option) -> ScheduleBuilder { - self.slippage = Some(slippage); - self - } - - fn with_max_retries(mut self, max_retries: Option) -> ScheduleBuilder { - self.max_retries = Some(max_retries); - self - } - - pub fn build(self) -> Schedule { - Schedule { - owner: self.owner.unwrap(), - period: self.period.unwrap(), - stability_threshold: self.stability_threshold.unwrap(), - slippage: self.slippage.unwrap(), - total_amount: self.total_amount.unwrap(), - max_retries: self.max_retries.unwrap(), - order: self.order.unwrap(), - } - } -} - -/// Stores a schedule by writing exactly the state the `schedule` extrinsic writes. -/// -/// Buy orders can no longer be scheduled, but buy schedules stored before that restriction keep -/// executing, so their execution still needs coverage. Fidelity against the extrinsic is pinned by -/// the tests in `storage_injection_fidelity`. -pub fn insert_schedule_into_storage( - who: AccountId, - schedule: Schedule, - start_execution_block: Option, -) -> ScheduleId { - assert_eq!(schedule.owner, who, "owner must match the schedule owner"); - - let asset_in = schedule.order.get_asset_in(); - let route = schedule.order.get_route_or_default::(); - let amount_in = match schedule.order { - Order::Sell { amount_in, .. } => amount_in, - Order::Buy { amount_out, .. } => { - RouteExecutor::calculate_buy_trade_amounts(&route, amount_out) - .unwrap() - .last() - .unwrap() - .amount_in - } - }; - let transaction_fee = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - - let reserve_amount = if schedule.is_rolling() { - amount_in.saturating_add(transaction_fee).saturating_mul(2) - } else { - schedule.total_amount - }; - - let schedule_id = ScheduleIdSequencer::::mutate(|current_id| { - let schedule_id = *current_id; - *current_id += 1; - schedule_id - }); - - Schedules::::insert(schedule_id, &schedule); - ScheduleOwnership::::insert(who, schedule_id, ()); - RemainingAmounts::::insert(schedule_id, reserve_amount); - RetriesOnError::::insert(schedule_id, 0); - - assert_ok!(Currencies::reserve_named( - &NamedReserveId::get(), - asset_in, - &who, - reserve_amount - )); - - let execution_block = first_execution_block(start_execution_block); - ScheduleIdsPerBlock::::mutate(execution_block, |schedule_ids| { - schedule_ids.try_push(schedule_id).expect("execution block is full"); - }); - ScheduleExecutionBlock::::insert(schedule_id, execution_block); - - System::deposit_event(RuntimeEvent::DCA(Event::Scheduled { - id: schedule_id, - who, - period: schedule.period, - total_amount: schedule.total_amount, - order: schedule.order, - })); - System::deposit_event(RuntimeEvent::DCA(Event::ExecutionPlanned { - id: schedule_id, - who, - block: execution_block, - })); - - schedule_id -} - -/// Mirrors `crate::Pallet::get_first_execution_block`. -fn first_execution_block(start_execution_block: Option) -> BlockNumber { - let next_block = System::block_number().saturating_add(2); - match start_execution_block { - Some(block) => { - let number = next_block.max(block); - match number % 5 { - 0 => number, - remainder => number.saturating_add(5 - remainder), - } - } - None => next_block, - } -} - -pub fn create_bounded_vec(trades: Vec>) -> BoundedVec, ConstU32<9>> { - let bounded_vec: BoundedVec, sp_runtime::traits::ConstU32<9>> = trades.try_into().unwrap(); - bounded_vec -} - -pub fn create_bounded_vec_with_schedule_ids(schedule_ids: Vec) -> BoundedVec> { - let bounded_vec: BoundedVec> = schedule_ids.try_into().unwrap(); - bounded_vec -} -#[macro_export] -macro_rules! assert_scheduled_ids { - ($block:expr, $expected_schedule_ids:expr) => { - let actual_schedule_ids = DCA::schedule_ids_per_block($block); - assert!(!DCA::schedule_ids_per_block($block).is_empty()); - let expected_scheduled_ids_for_next_block = create_bounded_vec_with_schedule_ids($expected_schedule_ids); - assert_eq!(actual_schedule_ids, expected_scheduled_ids_for_next_block); - }; -} - -#[macro_export] -macro_rules! assert_that_schedule_has_been_removed_from_storages { - ($owner:expr,$schedule_id:expr) => { - assert!(DCA::schedules($schedule_id).is_none()); - assert!(DCA::owner_of($owner, $schedule_id).is_none()); - assert!(DCA::remaining_amounts($schedule_id).is_none()); - assert!(DCA::schedule_execution_block($schedule_id).is_none()); - assert_eq!(DCA::retries_on_error($schedule_id), 0); - }; -} diff --git a/pallets/dca/src/tests/on_initialize.rs b/pallets/dca/src/tests/on_initialize.rs deleted file mode 100644 index 07e2eaeaff..0000000000 --- a/pallets/dca/src/tests/on_initialize.rs +++ /dev/null @@ -1,2958 +0,0 @@ -// This file is part of HydraDX. - -// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::tests::schedule::get_fee_for_sell_in_hdx; -use crate::tests::*; -use crate::{ - assert_balance, assert_executed_buy_trades, assert_executed_sell_trades, assert_number_of_executed_buy_trades, - assert_number_of_executed_sell_trades, assert_scheduled_ids, assert_that_schedule_has_been_removed_from_storages, - Error, Event as DcaEvent, Order, Permill, ScheduleId, -}; -use frame_support::assert_ok; -use frame_support::traits::OnInitialize; -use hydradx_traits::router::PoolType; -use hydradx_traits::router::PoolType::Omnipool; -use hydradx_traits::OraclePeriod; -use orml_traits::MultiCurrency; -use orml_traits::MultiReservableCurrency; -use orml_traits::NamedMultiReservableCurrency; -use pretty_assertions::assert_eq; -use sp_runtime::DispatchError; -use std::borrow::Borrow; -use std::ops::RangeInclusive; - -fn retry_block(current_block: u64, retries_before: u32) -> u64 { - current_block + OraclePeriod::Short.as_period() * 2_u64.pow(retries_before) -} - -#[test] -fn successful_sell_dca_execution_should_emit_trade_executed_event() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 5 * ONE; - let amount_to_sell = ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act - set_to_blocknumber(502); - - //Assert - let schedule_id = 0; - expect_events(vec![ - DcaEvent::TradeExecuted { - id: schedule_id, - who: ALICE, - amount_in: amount_to_sell, - amount_out: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - } - .into(), - DcaEvent::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: 602, - } - .into(), - ]); - }); -} - -#[test] -fn successful_buy_dca_execution_should_emit_trade_executed_event() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 50 * ONE; - let amount_to_buy = 10 * ONE; - let max_limit = 50 * ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_slippage(Some(Permill::from_percent(20))) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: amount_to_buy, - max_amount_in: max_limit, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule, Option::None); - - //Act - set_to_blocknumber(502); - - //Assert - let schedule_id = 0; - expect_events(vec![ - DcaEvent::TradeExecuted { - id: schedule_id, - who: ALICE, - amount_in: CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY, - amount_out: amount_to_buy, - } - .into(), - DcaEvent::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: 602, - } - .into(), - ]); - }); -} - -#[test] -fn one_sell_dca_execution_should_unreserve_amount_in() { - let initial_alice_hdx_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, initial_alice_hdx_balance)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 5 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - set_to_blocknumber(502); - - //Assert - let remaining_named_reserve = total_amount - amount_to_sell - get_fee_for_sell_in_hdx(); - assert_executed_sell_trades!(vec![SellExecution { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_buy_amount: 0, - }]); - - assert_eq!(remaining_named_reserve, Currencies::reserved_balance(HDX, &ALICE)); - - let schedule_id = 0; - expect_events(vec![ - DcaEvent::TradeExecuted { - id: schedule_id, - who: ALICE, - amount_in: amount_to_sell, - amount_out: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - } - .into(), - DcaEvent::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: 602, - } - .into(), - ]) - }); -} - -#[test] -fn sell_schedule_should_sell_remaining_when_there_is_not_enough_left() { - let initial_alice_hdx_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, initial_alice_hdx_balance)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = *AMOUNT_OUT_FOR_OMNIPOOL_SELL * 5 / 2; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - set_to_blocknumber(502); - set_to_blocknumber(602); - - //Assert - assert_number_of_executed_sell_trades!(2); - - set_to_blocknumber(702); - - //Assert - let fee_in_native = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - assert_executed_sell_trades!(vec![ - SellExecution { - asset_in: HDX, - asset_out: BTC, - amount_in: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - min_buy_amount: 0, - }, - SellExecution { - asset_in: HDX, - asset_out: BTC, - amount_in: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - min_buy_amount: 0, - }, - SellExecution { - asset_in: HDX, - asset_out: BTC, - amount_in: total_amount - 2 * (amount_to_sell + fee_in_native) - fee_in_native, - min_buy_amount: 0, - } - ]); - - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - assert_that_dca_is_completed(ALICE, 0); - }); -} - -#[test] -fn sell_schedule_should_continue_when_there_is_exact_amount_in_left_as_remaining() { - let initial_alice_hdx_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, initial_alice_hdx_balance)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - let sell_dca_fee = get_fee_for_sell_in_hdx(); - - let total_amount = 3 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL * 2 + sell_dca_fee; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(5) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - set_to_blocknumber(502); - set_to_blocknumber(504); - - //Assert - assert_executed_sell_trades!(vec![SellExecution { - asset_in: HDX, - asset_out: BTC, - amount_in: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - min_buy_amount: 0, - }]); - - assert!(DCA::schedules(0).is_some()); - }); -} - -#[test] -fn one_buy_dca_execution_should_unreserve_exact_amount_in() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 50 * ONE; - let amount_to_buy = 10 * ONE; - let max_limit = 50 * ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_slippage(Some(Permill::from_percent(20))) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: amount_to_buy, - max_amount_in: max_limit, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule.clone(), Option::None); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - set_to_blocknumber(502); - - //Assert - let buy_fee_in_native = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - assert_executed_buy_trades!(vec![BuyExecution { - asset_in: HDX, - asset_out: BTC, - amount_out: amount_to_buy, - max_sell_amount: CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY, - }]); - - assert_eq!( - total_amount - CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY - buy_fee_in_native, - Currencies::reserved_balance(HDX, &ALICE) - ); - }); -} - -#[test] -fn one_buy_dca_execution_should_calculate_exact_amount_in_when_multiple_pools_involved() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 50 * ONE; - let amount_to_buy = 10 * ONE; - let max_limit = 50 * ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_slippage(Some(Permill::from_percent(20))) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: amount_to_buy, - max_amount_in: max_limit, - route: create_bounded_vec(vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: DAI, - }, - Trade { - pool: PoolType::XYK, - asset_in: DAI, - asset_out: BTC, - }, - ]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule.clone(), Option::None); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - set_to_blocknumber(502); - - //Assert - assert_executed_buy_trades!(vec![ - BuyExecution { - asset_in: HDX, - asset_out: DAI, - amount_out: XYK_BUY_CALCULATION_RESULT, - max_sell_amount: CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY, - }, - BuyExecution { - asset_in: DAI, - asset_out: BTC, - amount_out: amount_to_buy, - max_sell_amount: XYK_BUY_CALCULATION_RESULT, - } - ]); - - let buy_fee_in_native = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - assert_eq!( - total_amount - CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY - buy_fee_in_native, - Currencies::reserved_balance(HDX, &ALICE) - ); - }); -} - -#[test] -fn full_sell_dca_should_be_completed_with_selling_leftover_in_last_trade() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 3 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL + *AMOUNT_OUT_FOR_OMNIPOOL_SELL / 2; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - proceed_to_blocknumber(502, 802); - - //Assert - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - - assert_number_of_executed_sell_trades!(4); - - let schedule_id = 0; - assert_that_dca_is_completed(ALICE, schedule_id); - }); -} - -#[test] -fn full_sell_dca_should_be_completed_when_default_routes_used() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 3 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - proceed_to_blocknumber(501, 801); - - //Assert - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - - assert_number_of_executed_sell_trades!(3); - - let schedule_id = 0; - assert_that_dca_is_completed(ALICE, schedule_id); - }); -} - -#[test] -fn full_sell_dca_should_be_completed_when_some_successful_dca_execution_happened_but_less_than_fee_left() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let sell_dca_fee = get_fee_for_sell_in_hdx(); - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - let total_amount = 2 * (amount_to_sell + sell_dca_fee) + sell_dca_fee / 2; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - proceed_to_blocknumber(501, 801); - - //Assert - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - - assert_number_of_executed_sell_trades!(2); - assert_balance!(ALICE, BTC, 2 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL); - - let schedule_id = 0; - assert_that_dca_is_completed(ALICE, schedule_id); - }); -} - -#[test] -fn full_buy_should_be_completed_when_with_default_routes() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 3 * CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY; - let amount_to_buy = 10 * ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_slippage(Some(Permill::from_percent(20))) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(vec![]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule, Option::None); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - proceed_to_blocknumber(501, 1001); - - //Assert - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - - assert_number_of_executed_buy_trades!(2); - assert_balance!(ALICE, BTC, 2 * CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY); - - let schedule_id = 0; - assert_that_dca_is_completed(ALICE, schedule_id); - }); -} - -#[test] -fn full_buy_dca_should_be_completed_when_some_successful_dca_execution_happened_but_less_than_fee_left() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let amount_to_buy = 10 * ONE; - - let order = Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }; - let buy_fee_in_native = DCA::get_transaction_fee(&order, None).unwrap(); - let total_amount = 2 * (CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY + buy_fee_in_native) + buy_fee_in_native / 2; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_slippage(Some(Permill::from_percent(20))) - .with_order(order) - .build(); - - insert_schedule_into_storage(ALICE, schedule, Option::None); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - proceed_to_blocknumber(502, 802); - - //Assert - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - - assert_number_of_executed_buy_trades!(2); - assert_balance!(ALICE, BTC, 2 * CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY); - - let schedule_id = 0; - assert_that_dca_is_completed(ALICE, schedule_id); - }); -} - -#[test] -fn full_sell_dca_should_be_completed_for_multiple_users() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE), (BOB, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 3 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL + *AMOUNT_OUT_FOR_OMNIPOOL_SELL / 2; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule_for_alice = ScheduleBuilder::new() - .with_owner(ALICE) - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - let schedule_for_bob = ScheduleBuilder::new() - .with_owner(BOB) - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule_for_alice, - Option::None - )); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(BOB), - schedule_for_bob, - Option::None - )); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &BOB)); - - //Act - proceed_to_blocknumber(502, 802); - - //Assert - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - assert_eq!(0, Currencies::reserved_balance(HDX, &BOB)); - - assert_number_of_executed_sell_trades!(8); - - let schedule_id = 0; - let schedule_id_2 = 1; - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - assert_that_schedule_has_been_removed_from_storages!(BOB, schedule_id_2); - }); -} - -#[test] -fn multiple_sell_dca_should_be_completed_for_one_user() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE), (BOB, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 3 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL + *AMOUNT_OUT_FOR_OMNIPOOL_SELL / 2; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule = ScheduleBuilder::new() - .with_owner(ALICE) - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - assert_eq!(total_amount + total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - proceed_to_blocknumber(502, 802); - - //Assert - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - - assert_number_of_executed_sell_trades!(8); - - let schedule_id = 0; - let schedule_id_2 = 1; - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id_2); - }); -} - -#[test] -fn full_sell_dca_should_be_completed_when_exact_total_amount_specified_for_the_trades() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let fee = get_fee_for_sell_in_hdx(); - let total_amount = 3 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL + 3 * fee; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - proceed_to_blocknumber(501, 801); - - //Assert - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - assert_number_of_executed_sell_trades!(3); - - let schedule_id = 0; - assert_that_dca_is_completed(ALICE, schedule_id); - }); -} - -#[test] -fn rolling_dca_should_end_when_account_has_no_balance() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 100 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule = ScheduleBuilder::new() - .with_total_amount(0) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_eq!(schedule.is_rolling(), true); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, None)); - assert_eq!( - (*AMOUNT_OUT_FOR_OMNIPOOL_SELL + get_fee_for_sell_in_hdx()).saturating_mul(2), - Currencies::reserved_balance(HDX, &ALICE) - ); - - //Act - proceed_to_blocknumber(501, 801); - - //Assert - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - assert_number_of_executed_sell_trades!(2); - - let schedule_id = 0; - assert_that_dca_is_completed(ALICE, schedule_id); - }); -} - -#[test] -fn full_buy_dca_should_be_completed_when_some_execution_is_successful_but_not_enough_balance() { - let alice_init_hdx_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, alice_init_hdx_balance)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 50 * ONE; //We spend 10 in each trade but also the fee is taken, so it won't be enough for 5th trade - let amount_to_buy = 10 * ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_slippage(Some(Permill::from_percent(20))) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule, Option::None); - assert_balance!(ALICE, HDX, alice_init_hdx_balance - total_amount); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - proceed_to_blocknumber(501, 2001); - - //Assert - assert_number_of_executed_buy_trades!(4); - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - - let left_over_which_is_not_enough_for_last_trade = 9994516532000; - - assert_balance!( - ALICE, - HDX, - alice_init_hdx_balance - total_amount + left_over_which_is_not_enough_for_last_trade - ); - - let schedule_id = 0; - assert_that_dca_is_completed(ALICE, schedule_id); - }); -} - -#[test] -fn full_buy_dca_should_be_completed_without_leftover_fees_are_included_in_budget() { - let alice_init_hdx_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, alice_init_hdx_balance)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let amount_to_buy = 10 * ONE; - let order = Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }; - let buy_fee_in_native = DCA::get_transaction_fee(&order, None).unwrap(); - - let total_amount = 50 * ONE + 5 * buy_fee_in_native; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_slippage(Some(Permill::from_percent(20))) - .with_order(order) - .build(); - - insert_schedule_into_storage(ALICE, schedule, Option::None); - assert_balance!(ALICE, HDX, alice_init_hdx_balance - total_amount); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - proceed_to_blocknumber(501, 2001); - - //Assert - assert_number_of_executed_buy_trades!(5); - assert_eq!(0, Currencies::reserved_balance(HDX, &ALICE)); - assert_balance!(ALICE, HDX, alice_init_hdx_balance - total_amount); - - let schedule_id = 0; - assert_that_dca_is_completed(ALICE, schedule_id); - }); -} - -#[test] -fn one_buy_dca_execution_should_use_default_max_price_diff_for_max_limit_calculation() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .with_max_price_difference(Permill::from_percent(25)) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 50 * ONE; - let amount_to_buy = 10 * ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule, Option::None); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - set_to_blocknumber(502); - - //Assert - assert_number_of_executed_buy_trades!(1); - }); -} - -#[test] -fn nothing_should_happen_when_no_schedule_in_storage_for_block() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Act - proceed_to_blocknumber(1, 500); - - //Assert - let schedule_id = 1; - assert!(DCA::schedules(schedule_id).is_none()); - }); -} - -#[test] -fn schedule_is_planned_with_period_when_block_has_already_planned_schedule() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let total_amount = 3 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - let schedule_id = 0; - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::Some(601) - )); - - proceed_to_blocknumber(1, 500); - let schedule_id_2 = 1; - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(501))); - - //Act - set_to_blocknumber(505); - - //Assert - assert_scheduled_ids!(605, vec![schedule_id, schedule_id_2]); - }); -} - -#[test] -fn buy_dca_schedule_should_be_retried_when_trade_limit_error_happens() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 1000 * ONE; - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY, - max_amount_in: 5 * ONE, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule, Option::None); - - set_to_blocknumber(502); - - assert_number_of_executed_buy_trades!(0); - - let schedule_id = 0; - - assert_scheduled_ids!(retry_block(502, 0), vec![schedule_id]); - let retries = DCA::retries_on_error(schedule_id); - assert_eq!(1, retries); - expect_dca_events(vec![ - DcaEvent::TradeFailed { - id: schedule_id, - who: ALICE, - error: Error::::TradeLimitReached.into(), - } - .into(), - DcaEvent::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: retry_block(502, 0), - } - .into(), - ]); - }); -} - -#[test] -fn sell_dca_schedule_should_be_retried_when_trade_limit_error_happens() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 1000 * ONE; - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - min_amount_out: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - set_to_blocknumber(502); - - assert_number_of_executed_sell_trades!(0); - - let schedule_id = 0; - assert_scheduled_ids!(retry_block(502, 0), vec![schedule_id]); - let retries = DCA::retries_on_error(schedule_id); - assert_eq!(1, retries); - expect_dca_events(vec![ - DcaEvent::TradeFailed { - id: schedule_id, - who: ALICE, - error: Error::::TradeLimitReached.into(), - } - .into(), - DcaEvent::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: retry_block(502, 0), - } - .into(), - ]); - }); -} - -#[test] -fn dca_schedule_should_terminate_when_error_is_not_configured_to_continue_on() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, FORBIDDEN_ASSET, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: FORBIDDEN_ASSET, - asset_out: BTC, - amount_in: ONE, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: FORBIDDEN_ASSET, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act - set_to_blocknumber(502); - - //Assert - let schedule_id = 0; - - assert_number_of_executed_sell_trades!(0); - assert!(DCA::schedule_ids_per_block(602).is_empty()); - assert_that_dca_is_terminated(ALICE, schedule_id, pallet_omnipool::Error::::NotAllowed.into()); - }); -} - -#[test] -fn dca_schedule_should_retry_when_error_is_configured_to_retry_on() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, RETRY_ON_ERROR_ASSET, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: RETRY_ON_ERROR_ASSET, - asset_out: BTC, - amount_in: ONE, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: RETRY_ON_ERROR_ASSET, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act and assert - let schedule_id = 0; - let retry_1 = retry_block(502, 0); - let retry_2 = retry_block(retry_1, 1); - let retry_3 = retry_block(retry_2, 2); - - set_to_blocknumber(502); - assert!(DCA::schedules(schedule_id).is_some()); - assert_eq!(DCA::retries_on_error(schedule_id), 1); - assert_scheduled_ids!(retry_1, vec![schedule_id]); - - set_to_blocknumber(retry_1); - assert_eq!(DCA::retries_on_error(schedule_id), 2); - assert_scheduled_ids!(retry_2, vec![schedule_id]); - - set_to_blocknumber(retry_2); - assert_eq!(DCA::retries_on_error(schedule_id), 3); - assert_scheduled_ids!(retry_3, vec![schedule_id]); - - set_to_blocknumber(retry_3); - assert_number_of_executed_sell_trades!(0); - assert_that_dca_is_terminated(ALICE, schedule_id, Error::::MaxRetryReached.into()); - }); -} - -#[test] -fn buy_dca_schedule_should_continue_on_slippage_error() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY, - max_amount_in: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule, Option::None); - - //Act and assert - let schedule_id = 0; - set_to_blocknumber(502); - assert_scheduled_ids!(retry_block(502, 0), vec![schedule_id]); - let retries = DCA::retries_on_error(schedule_id); - assert_eq!(1, retries); - }); -} - -#[test] -fn sell_dca_schedule_continue_on_slippage_error() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 50 * ONE; - let amount_to_sell = ONE; - - set_sell_amount_out(ONE / 10); - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act and assert - let schedule_id = 0; - set_to_blocknumber(502); - assert_scheduled_ids!(retry_block(502, 0), vec![schedule_id]); - let retries = DCA::retries_on_error(schedule_id); - assert_eq!(1, retries); - }); -} - -#[test] -fn dca_schedule_retry_should_be_reset_when_successful_trade_after_failed_ones() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE)]) - .with_max_price_difference(Permill::from_percent(9)) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 5 * ONE; - let amount_to_sell = ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act and assert - let schedule_id = 0; - let retry_1 = retry_block(502, 0); - let retry_2 = retry_block(retry_1, 1); - - set_to_blocknumber(502); - assert_scheduled_ids!(retry_1, vec![schedule_id]); - - set_to_blocknumber(retry_1); - assert_scheduled_ids!(retry_2, vec![schedule_id]); - - set_max_price_diff(Permill::from_percent(10)); - - set_to_blocknumber(retry_2); - assert_scheduled_ids!(retry_2 + ONE_HUNDRED_BLOCKS, vec![schedule_id]); - assert_number_of_executed_sell_trades!(1); - - let retries = DCA::retries_on_error(schedule_id); - assert_eq!(0, retries); - }); -} - -#[test] -fn execution_fee_should_be_taken_from_user_in_sold_currency_in_case_of_successful_sell_trade() { - let alice_init_native_balance = 5000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, alice_init_native_balance), (ALICE, DAI, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let amount_in = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let budget = 1000 * ONE; - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_total_amount(budget) - .with_order(Order::Sell { - asset_in: DAI, - asset_out: BTC, - amount_in, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: DAI, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - - //Act - assert_balance!(TreasuryAccount::get(), DAI, 0); - - set_to_blocknumber(502); - - //Assert - let sell_fee_in_dai = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - assert_balance!(TreasuryAccount::get(), DAI, sell_fee_in_dai); - assert_eq!( - Currencies::reserved_balance(DAI, &ALICE), - budget - amount_in - sell_fee_in_dai - ); - assert_balance!(ALICE, BTC, *AMOUNT_OUT_FOR_OMNIPOOL_SELL); - assert_number_of_executed_sell_trades!(1); - }); -} - -#[test] -fn sell_dca_native_execution_fee_should_be_taken_and_sent_to_treasury() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 3 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - assert_balance!(TreasuryAccount::get(), HDX, 0); - - //Act - set_to_blocknumber(502); - - //Assert - let sell_fee_in_native = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - assert_balance!(TreasuryAccount::get(), HDX, sell_fee_in_native); - assert_eq!( - Currencies::reserved_balance(HDX, &ALICE), - total_amount - *AMOUNT_OUT_FOR_OMNIPOOL_SELL - sell_fee_in_native - ); - assert_balance!(ALICE, BTC, *AMOUNT_OUT_FOR_OMNIPOOL_SELL); - assert_number_of_executed_sell_trades!(1); - }); -} - -#[test] -fn sell_dca_should_be_completed_when_last_trade_amount_is_total_budget_plus_fee() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - let total_amount = 2 * (amount_to_sell + get_fee_for_sell_in_hdx()); - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - assert_balance!(TreasuryAccount::get(), HDX, 0); - - //Act - set_to_blocknumber(502); - set_to_blocknumber(602); - - //Assert - assert_number_of_executed_sell_trades!(2); - assert_that_dca_is_completed(ALICE, 0); - }); -} - -#[test] -fn buy_dca_native_execution_fee_should_be_taken_and_sent_to_treasury() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 1500 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let budget = 1000 * ONE; - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_slippage(Some(Permill::from_percent(20))) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: 10 * ONE, - max_amount_in: 10 * ONE, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule.clone(), Option::None); - assert_eq!(budget, Currencies::reserved_balance(HDX, &ALICE)); - assert_balance!(TreasuryAccount::get(), HDX, 0); - - //Act - set_to_blocknumber(502); - - //Assert - let buy_fee_in_native = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - - assert_balance!(TreasuryAccount::get(), HDX, buy_fee_in_native); - assert_eq!( - Currencies::reserved_balance(HDX, &ALICE), - budget - CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY - buy_fee_in_native - ); - assert_balance!(ALICE, BTC, CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY); - assert_number_of_executed_buy_trades!(1); - }); -} - -#[test] -fn slippage_limit_should_be_used_for_buy_dca_when_it_is_smaller_than_specified_trade_max_limit() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - assert_balance!(ALICE, BTC, 0); - - let buy_amount = 10 * ONE; - - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_slippage(Some(Permill::from_percent(1))) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: DAI, - amount_out: buy_amount, - max_amount_in: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: DAI, - }]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule, Option::None); - - //Act - set_to_blocknumber(502); - - //Assert - //No trade happens because slippage limit is too small - assert_number_of_executed_buy_trades!(0); - let retries = DCA::retries_on_error(0); - assert_eq!(1, retries); - }); -} - -#[test] -fn one_sell_dca_execution_should_be_rescheduled_when_price_diff_is_more_than_max_allowed() { - let initial_alice_hdx_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, initial_alice_hdx_balance)]) - .with_max_price_difference(Permill::from_percent(9)) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 5 * ONE; - let amount_to_sell = ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule.clone(), None)); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - set_to_blocknumber(502); - - //Assert - let fee_in_native = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - assert_executed_sell_trades!(vec![]); - assert_eq!(total_amount - fee_in_native, Currencies::reserved_balance(HDX, &ALICE)); - - let schedule_id = 0; - assert_scheduled_ids!(retry_block(502, 0), vec![schedule_id]); - expect_dca_events(vec![ - DcaEvent::TradeFailed { - id: schedule_id, - who: ALICE, - error: Error::::PriceUnstable.into(), - } - .into(), - DcaEvent::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: retry_block(502, 0), - } - .into(), - ]); - }); -} - -#[test] -fn one_sell_dca_execution_should_be_rescheduled_when_price_diff_is_more_than_user_specified_treshold() { - let initial_alice_hdx_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, initial_alice_hdx_balance)]) - .with_max_price_difference(Permill::from_percent(15)) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 5 * ONE; - let amount_to_sell = ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_price_stability_threshold(Some(Permill::from_percent(9))) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, None)); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - set_to_blocknumber(502); - - //Assert - assert_executed_sell_trades!(vec![]); - assert_eq!( - total_amount - get_fee_for_sell_in_hdx(), - Currencies::reserved_balance(HDX, &ALICE) - ); - - let schedule_id = 0; - assert_scheduled_ids!(retry_block(502, 0), vec![schedule_id]); - expect_dca_events(vec![ - DcaEvent::TradeFailed { - id: schedule_id, - who: ALICE, - error: Error::::PriceUnstable.into(), - } - .into(), - DcaEvent::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: retry_block(502, 0), - } - .into(), - ]); - }); -} - -#[test] -fn dca_should_be_terminated_when_dca_cannot_be_planned_due_to_not_free_blocks() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 5 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule_id = 0; - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(5) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(995))); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - for _ in RangeInclusive::new(1, 220) { - let schedule = ScheduleBuilder::new().build(); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule, - Option::Some(1000) - )); - } - - //Act - set_to_blocknumber(995); - - //Assert - assert_executed_sell_trades!(vec![SellExecution { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_buy_amount: 0, - }]); - - assert_that_dca_is_terminated(ALICE, schedule_id, Error::::NoFreeBlockFound.into()); - }); -} - -#[test] -fn dca_should_be_terminated_when_price_change_is_big_but_no_free_blocks_to_replan() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000000 * ONE)]) - .with_max_price_difference(Permill::from_percent(9)) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 5 * *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule_id = 0; - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(5) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(995))); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - for _ in RangeInclusive::new(1, 220) { - let schedule = ScheduleBuilder::new().build(); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule, - Option::Some(retry_block(995, 0)) - )); - } - - //Act - set_to_blocknumber(995); - - //Assert - assert_executed_sell_trades!(vec![]); - assert_that_dca_is_terminated(ALICE, schedule_id, Error::::NoFreeBlockFound.into()); - }); -} - -#[test] -fn dca_should_be_executed_and_replanned_through_multiple_blocks_when_all_consquent_blocks_are_planned_fully() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000000000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 3000 * ONE; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(100) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - for _ in RangeInclusive::new(1, 220) { - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Some(1000) - )); - } - - //Check if first block is fully filled - let mut execution_block = 1000; - let actual_schedule_ids = DCA::schedule_ids_per_block(execution_block); - assert_eq!(20, actual_schedule_ids.len()); - - //Check if all blocks found within radius are filled - for delay in GENERATED_SEARCH_RADIUSES { - execution_block += delay; - let actual_schedule_ids = DCA::schedule_ids_per_block(execution_block); - assert_eq!(20, actual_schedule_ids.len()); - } - - //Act - proceed_to_blocknumber(1000, 2000); - - //Assert - assert_number_of_executed_sell_trades!(1740); - - //Assert if none of the schedule is terminated - for schedule_id in RangeInclusive::new(0, 119) { - assert!(DCA::schedules(schedule_id).is_some()); - } - }); -} - -#[test] -fn dca_sell_schedule_should_be_terminated_when_schedule_allocation_is_more_than_reserved_funds() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let amount_in = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - let order = Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in, - min_amount_out: 5 * ONE, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }; - let fee_in_native = DCA::get_transaction_fee(&order, None).unwrap(); - let total_amount = 2 * (amount_in + fee_in_native); - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_total_amount(total_amount) - .with_order(order) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - Currencies::unreserve_named(&NamedReserveId::get(), HDX, &ALICE, 5000 * ONE); - - //Act - set_to_blocknumber(502); - - //Assert - let schedule_id = 0; - assert_number_of_executed_sell_trades!(0); - assert_that_dca_is_terminated(ALICE, schedule_id, Error::::InvalidState.into()); - }); -} - -#[test] -fn sell_schedule_should_be_completed_when_remainder_is_less_than_20_transaction_fee() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let sell_fee = get_fee_for_sell_in_hdx(); - - let remainder = 20 * sell_fee - 1; - let total_amount = 2 * (ONE + sell_fee) + remainder; - let amount_to_sell = ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act - set_to_blocknumber(502); - set_to_blocknumber(602); - - //Assert - let schedule_id = 0; - assert_that_dca_is_completed(ALICE, schedule_id); - }); -} - -#[test] -fn schedules_are_purged_when_the_block_is_over() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 5 * ONE; - let amount_to_sell = ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act - set_to_blocknumber(502); - assert_number_of_executed_sell_trades!(3); - set_to_blocknumber(503); - - //Assert - let scheduled_ids_for_next_block = DCA::schedule_ids_per_block(502); - assert_eq!( - scheduled_ids_for_next_block, - create_bounded_vec_with_schedule_ids(vec![]) - ); - }); -} - -#[test] -fn sell_schedule_should_be_replanned_when_remainder_is_equal_to_20_transaction_fee() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let remainder = 20 * get_fee_for_sell_in_hdx(); - let total_amount = 2 * (ONE + get_fee_for_sell_in_hdx()) + remainder; - let amount_to_sell = ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act - set_to_blocknumber(502); - set_to_blocknumber(602); - - //Assert - let schedule_id = 0; - expect_events(vec![DcaEvent::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: 702, - } - .into()]); - }); -} - -#[test] -fn sell_schedule_should_be_replanned_when_more_than_20_transaction_fee_left_for_next_trade() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let remainder = 20 * get_fee_for_sell_in_hdx() + 1; - let total_amount = 2 * (ONE + get_fee_for_sell_in_hdx()) + remainder; - let amount_to_sell = ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act - set_to_blocknumber(502); - set_to_blocknumber(602); - - //Assert - let schedule_id = 0; - expect_events(vec![DcaEvent::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: 702, - } - .into()]); - }); -} - -#[test] -fn dca_should_complete_when_remainder_is_smaller_than_min_trading_limit() { - let min_trade_limit = ONE / 10; - - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .with_min_trading_limit(min_trade_limit) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let fee = get_fee_for_sell_in_hdx(); - let remainder = min_trade_limit - 1; - let total_amount = 2 * (ONE + fee) + remainder; - let amount_to_sell = ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act - set_to_blocknumber(502); - set_to_blocknumber(602); - - //Assert - let schedule_id = 0; - assert_that_dca_is_completed(ALICE, schedule_id); - }); -} -#[test] -fn dca_should_continue_when_remainder_is_equal_to_min_trading_limit() { - let min_trade_limit = ONE / 10; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .with_min_trading_limit(min_trade_limit) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let amount_to_sell = ONE; - let order = Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }; - let fee_in_native = DCA::get_transaction_fee(&order, None).unwrap(); - let total_amount = 2 * (ONE + fee_in_native) + min_trade_limit; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(order) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act - set_to_blocknumber(502); - set_to_blocknumber(602); - - //Assert - let schedule_id = 0; - expect_events(vec![DcaEvent::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: 702, - } - .into()]); - }); -} - -#[test] -fn execution_is_still_successful_when_no_parent_hash_present() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 5 * ONE; - let amount_to_sell = ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - set_parent_hash(None); - - //Act - set_to_blocknumber(502); - - //Assert - let schedule_id = 0; - expect_events(vec![ - DcaEvent::TradeExecuted { - id: schedule_id, - who: ALICE, - amount_in: amount_to_sell, - amount_out: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - } - .into(), - DcaEvent::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: 602, - } - .into(), - ]); - }); -} - -#[test] -fn dca_should_include_extra_gas_in_fee_calculation_on_retry() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - // Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 1000 * ONE; - let amount_to_sell = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_max_retries(Some(3)) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - let schedule_id = 0; - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule.clone(), None)); - - let fee_without_extra_gas = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - - // Simulate that extra gas was incremented after an out-of-gas error - let expected_gas_increment = crate::MAX_EXTRA_GAS / 3; // max_retries = 3 - crate::ScheduleExtraGas::::insert(schedule_id, expected_gas_increment); - - let fee_with_extra_gas = DCA::get_transaction_fee(&schedule.order, Some(schedule_id)).unwrap(); - - assert!( - fee_with_extra_gas > fee_without_extra_gas, - "Fee with extra gas ({fee_with_extra_gas}) should be higher than base fee ({fee_without_extra_gas})", - ); - - // Act - set_to_blocknumber(502); - - //Assert - assert_number_of_executed_sell_trades!(1); - - // Verify the fee charged included the extra gas - let expected_reserved = total_amount - amount_to_sell - fee_with_extra_gas; - assert_eq!( - Currencies::reserved_balance(HDX, &ALICE), - expected_reserved, - "Reserved balance should reflect fee with extra gas was charged" - ); - }); -} - -#[test] -fn schedule_is_planned_for_next_block_when_one_execution_finished() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_slippage(Some(Permill::from_percent(20))) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: ONE, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act - set_to_blocknumber(502); - - //Assert - assert_number_of_executed_sell_trades!(1); - - let schedule_id = 0; - assert_scheduled_ids!(602, vec![schedule_id]); - }); -} - -#[test] -fn dca_trade_unallocation_should_be_rolled_back_when_trade_fails() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 1000 * ONE; - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - min_amount_out: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - let schedule_id = 0; - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - assert_eq!(Currencies::reserved_balance(HDX, &ALICE), total_amount); - assert_eq!(DCA::remaining_amounts(schedule_id).unwrap(), total_amount); - - set_to_blocknumber(502); - - assert_number_of_executed_sell_trades!(0); - assert_scheduled_ids!(retry_block(502, 0), vec![schedule_id]); - - let fee_in_native = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - assert_eq!(Currencies::reserved_balance(HDX, &ALICE), total_amount - fee_in_native); - assert_eq!( - DCA::remaining_amounts(schedule_id).unwrap(), - total_amount - fee_in_native - ); - }); -} - -#[test] -fn dca_schedule_should_continue_on_multiple_failures_then_terminated() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - min_amount_out: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act and assert - let schedule_id = 0; - let retry_1 = retry_block(502, 0); - let retry_2 = retry_block(retry_1, 1); - let retry_3 = retry_block(retry_2, 2); - set_to_blocknumber(502); - assert_scheduled_ids!(retry_1, vec![schedule_id]); - - set_to_blocknumber(retry_1); - assert_scheduled_ids!(retry_2, vec![schedule_id]); - - set_to_blocknumber(retry_2); - assert_scheduled_ids!(retry_3, vec![schedule_id]); - - set_to_blocknumber(retry_3); - assert!(DCA::schedules(schedule_id).is_none()); - assert_number_of_executed_sell_trades!(0); - }); -} - -#[test] -fn dca_schedule_should_use_specified_max_retry_count() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - let max_retries = Some(5); - - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_max_retries(max_retries) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - min_amount_out: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act and assert - let schedule_id = 0; - let retry_1 = retry_block(502, 0); - let retry_2 = retry_block(retry_1, 1); - let retry_3 = retry_block(retry_2, 2); - let retry_4 = retry_block(retry_3, 3); - let retry_5 = retry_block(retry_4, 4); - set_to_blocknumber(502); - assert_scheduled_ids!(retry_1, vec![schedule_id]); - - set_to_blocknumber(retry_1); - assert_scheduled_ids!(retry_2, vec![schedule_id]); - - set_to_blocknumber(retry_2); - assert_scheduled_ids!(retry_3, vec![schedule_id]); - - set_to_blocknumber(retry_3); - assert_scheduled_ids!(retry_4, vec![schedule_id]); - let retries = DCA::retries_on_error(schedule_id); - assert_eq!(4, retries); - - set_to_blocknumber(retry_4); - assert_scheduled_ids!(retry_5, vec![schedule_id]); - let retries = DCA::retries_on_error(schedule_id); - assert_eq!(5, retries); - - set_to_blocknumber(retry_5); - assert!(DCA::schedules(schedule_id).is_none()); - assert_number_of_executed_sell_trades!(0); - }); -} - -#[test] -fn execution_fee_should_be_taken_from_user_in_sold_currency_in_case_of_successful_buy_trade() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE), (ALICE, DAI, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let budget = 1000 * ONE; - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_total_amount(budget) - .with_slippage(Some(Permill::from_percent(20))) - .with_order(Order::Buy { - asset_in: DAI, - asset_out: BTC, - amount_out: 10 * ONE, - max_amount_in: 50 * ONE, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: DAI, - asset_out: BTC, - }]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule.clone(), Option::None); - - //Act - assert_balance!(TreasuryAccount::get(), DAI, 0); - set_to_blocknumber(502); - - //Assert - let buy_fee_in_dai = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - assert_balance!(TreasuryAccount::get(), DAI, buy_fee_in_dai); - assert_number_of_executed_buy_trades!(1); - assert_eq!( - Currencies::reserved_balance(DAI, &ALICE), - budget - CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY - buy_fee_in_dai - ); - assert_balance!(ALICE, BTC, CALCULATED_AMOUNT_IN_FOR_OMNIPOOL_BUY); - }); -} - -#[test] -fn execution_fee_should_be_still_taken_from_user_in_sold_currency_in_case_of_failed_trade() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE), (ALICE, DAI, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let budget = 1000 * ONE; - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_total_amount(budget) - .with_order(Order::Sell { - asset_in: DAI, - asset_out: BTC, - amount_in: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - min_amount_out: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: DAI, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - - //Act - assert_balance!(TreasuryAccount::get(), DAI, 0); - assert_balance!(ALICE, BTC, 0); - - set_to_blocknumber(502); - - //Assert - let fee_in_dai = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - assert_balance!(TreasuryAccount::get(), DAI, fee_in_dai); - assert_number_of_executed_sell_trades!(0); - assert_eq!(Currencies::reserved_balance(DAI, &ALICE), budget - fee_in_dai); - }); -} - -#[test] -fn one_buy_dca_execution_should_be_rescheduled_when_price_diff_is_more_than_max_allowed() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .with_max_price_difference(Permill::from_percent(9)) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 50 * ONE; - let amount_to_buy = 10 * ONE; - let max_limit = 20 * ONE; - - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: amount_to_buy, - max_amount_in: max_limit, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - insert_schedule_into_storage(ALICE, schedule.clone(), Option::None); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - set_to_blocknumber(502); - - let buy_fee_in_native = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - //Assert - assert_executed_buy_trades!(vec![]); - assert_eq!( - total_amount - buy_fee_in_native, - Currencies::reserved_balance(HDX, &ALICE) - ); - - let schedule_id = 0; - assert_scheduled_ids!(retry_block(502, 0), vec![schedule_id]); - }); -} - -#[test] -fn specified_slippage_should_be_used_in_circuit_breaker_price_check() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let total_amount = 50 * ONE; - - // Short oracle prices the sell of ONE at 0.8 * ONE, so the limit is 0.728 * ONE at the - // schedule's 9% and 0.72 * ONE at the pallet default. 0.725 * ONE sits between the two: - // it only fails if the specified slippage is the one being applied. - set_sell_amount_out(ONE * 725 / 1000); - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_period(ONE_HUNDRED_BLOCKS) - .with_slippage(Some(Permill::from_percent(9))) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: ONE, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - assert_eq!(total_amount, Currencies::reserved_balance(HDX, &ALICE)); - - //Act - set_to_blocknumber(502); - - //Assert - let fee_in_native = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - assert_executed_sell_trades!(vec![]); - assert_eq!(total_amount - fee_in_native, Currencies::reserved_balance(HDX, &ALICE)); - - let schedule_id = 0; - assert_scheduled_ids!(retry_block(502, 0), vec![schedule_id]); - - let retries = DCA::retries_on_error(schedule_id); - assert_eq!(1, retries); - }); -} - -#[test] -fn dca_schedule_should_still_take_fee_when_order_fails() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 5000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - proceed_to_blocknumber(1, 500); - - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - min_amount_out: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - - //Act and assert - let fee_in_native = DCA::get_transaction_fee(&schedule.order, None).unwrap(); - set_to_blocknumber(502); - assert_number_of_executed_sell_trades!(0); - assert_balance!(TreasuryAccount::get(), HDX, fee_in_native); - }); -} - -pub fn proceed_to_blocknumber(from: u64, to: u64) { - for block_number in RangeInclusive::new(from, to) { - System::set_block_number(block_number); - DCA::on_initialize(block_number); - } -} - -pub fn set_to_blocknumber(to: u64) { - System::set_block_number(to); - DCA::on_initialize(to); -} - -fn assert_that_dca_is_completed(owner: AccountId, schedule_id: ScheduleId) { - assert_that_schedule_has_been_removed_from_storages!(owner, schedule_id); - - expect_events(vec![DcaEvent::Completed { - id: schedule_id, - who: owner, - } - .into()]); -} - -fn assert_that_dca_is_terminated(owner: AccountId, schedule_id: ScheduleId, error: DispatchError) { - assert_that_schedule_has_been_removed_from_storages!(owner, schedule_id); - - expect_events(vec![DcaEvent::Terminated { - id: schedule_id, - who: owner, - error, - } - .into()]); -} - -#[test] -fn fee_should_be_charged_in_account_fee_currency_when_asset_in_is_not_a_fee_currency() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE), (ALICE, DAI, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - the sold asset cannot pay fees, so the owner's fee currency (HDX) is charged. - NON_FEE_ASSETS.with(|v| v.borrow_mut().push(DAI)); - proceed_to_blocknumber(1, 500); - - let amount_in = *AMOUNT_OUT_FOR_OMNIPOOL_SELL; - let budget = 1000 * ONE; - - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_total_amount(budget) - .with_order(Order::Sell { - asset_in: DAI, - asset_out: BTC, - amount_in, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: DAI, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - - let alice_hdx_before = Currencies::free_balance(HDX, &ALICE); - let treasury_hdx_before = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_balance!(TreasuryAccount::get(), DAI, 0); - - //Act - set_to_blocknumber(502); - - //Assert - assert_number_of_executed_sell_trades!(1); - - let fee = get_fee_for_sell_in_hdx(); - assert_eq!(Currencies::free_balance(HDX, &ALICE), alice_hdx_before - fee); - assert_eq!( - Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_before + fee - ); - - //The budget paid for the trade only - the fee never touched it, and the treasury - //received no DAI. - assert_eq!(Currencies::reserved_balance(DAI, &ALICE), budget - amount_in); - assert_balance!(TreasuryAccount::get(), DAI, 0); - }); -} - -#[test] -fn schedule_should_be_terminated_when_fee_currency_is_drained_and_asset_in_is_not_a_fee_currency() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE), (ALICE, DAI, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - NON_FEE_ASSETS.with(|v| v.borrow_mut().push(DAI)); - proceed_to_blocknumber(1, 500); - - let budget = 1000 * ONE; - let schedule = ScheduleBuilder::new() - .with_period(ONE_HUNDRED_BLOCKS) - .with_total_amount(budget) - .with_order(Order::Sell { - asset_in: DAI, - asset_out: BTC, - amount_in: *AMOUNT_OUT_FOR_OMNIPOOL_SELL, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: Omnipool, - asset_in: DAI, - asset_out: BTC, - }]), - }) - .build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - assert_eq!(Currencies::reserved_balance(DAI, &ALICE), budget); - - let alice_hdx = Currencies::free_balance(HDX, &ALICE); - assert_ok!(Currencies::transfer( - RuntimeOrigin::signed(ALICE), - BOB, - HDX, - alice_hdx - 1000 - )); - let treasury_hdx_before = Currencies::free_balance(HDX, &TreasuryAccount::get()); - - //Act - set_to_blocknumber(502); - - //Assert - assert_number_of_executed_sell_trades!(0); - assert_that_dca_is_terminated(ALICE, 0, sp_runtime::TokenError::FundsUnavailable.into()); - assert_eq!(Currencies::free_balance(HDX, &ALICE), 1000); - assert_eq!( - Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_before - ); - assert_eq!(Currencies::reserved_balance(DAI, &ALICE), 0); - assert_eq!(Currencies::free_balance(DAI, &ALICE), 10000 * ONE); - }); -} diff --git a/pallets/dca/src/tests/schedule.rs b/pallets/dca/src/tests/schedule.rs deleted file mode 100644 index 28b94f8d5f..0000000000 --- a/pallets/dca/src/tests/schedule.rs +++ /dev/null @@ -1,869 +0,0 @@ -// This file is part of HydraDX. - -// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::assert_scheduled_ids; -use crate::tests::create_bounded_vec_with_schedule_ids; -use crate::tests::mock::*; -use crate::tests::{create_bounded_vec, ScheduleBuilder}; -use crate::{Error, Event, Order}; -use frame_support::{assert_noop, assert_ok}; -use hydradx_traits::router::{PoolType, Trade}; -use orml_traits::NamedMultiReservableCurrency; -use pretty_assertions::assert_eq; -use sp_runtime::DispatchError::BadOrigin; -use std::ops::RangeInclusive; - -#[test] -fn schedule_should_reserve_all_total_amount_as_named_reserve() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - - let total_amount = 100 * ONE; - let schedule = ScheduleBuilder::new().with_total_amount(total_amount).build(); - //Act - set_block_number(500); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Assert - assert_eq!( - total_amount, - Currencies::reserved_balance_named(&NamedReserveId::get(), HDX, &ALICE) - ); - }); -} - -#[test] -fn schedule_should_store_total_amounts_in_storage() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - - let total_amount = 100 * ONE; - let schedule = ScheduleBuilder::new().with_total_amount(total_amount).build(); - //Act - set_block_number(500); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Assert - let schedule_id = 0; - assert_eq!(DCA::remaining_amounts(schedule_id).unwrap(), total_amount); - }); -} - -#[test] -fn schedule_should_compound_named_reserve_for_multiple_schedules() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 1000000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - - let total_amount = 10000 * ONE; - let schedule = ScheduleBuilder::new().with_total_amount(total_amount).build(); - - let total_amount_2 = 20000 * ONE; - let schedule_2 = ScheduleBuilder::new().with_total_amount(total_amount_2).build(); - - //Act - set_block_number(500); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule_2, Option::None)); - - //Assert - assert_eq!( - total_amount + total_amount_2, - Currencies::reserved_balance_named(&NamedReserveId::get(), HDX, &ALICE) - ); - let schedule_id = 0; - assert_eq!(DCA::remaining_amounts(schedule_id).unwrap(), total_amount); - - let schedule_id_2 = 1; - assert_eq!(DCA::remaining_amounts(schedule_id_2).unwrap(), total_amount_2); - }); -} - -#[test] -fn schedule_should_store_schedule_with_2_blocks_delay_when_no_blocknumber_specified() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - - //Act - set_block_number(500); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Assert - let schedule_id = 0; - let stored_schedule = DCA::schedules(schedule_id).unwrap(); - assert_eq!(stored_schedule, ScheduleBuilder::new().build()); - - //Check if schedule ids are stored - let schedule_ids = DCA::schedule_ids_per_block(502); - assert!(!DCA::schedule_ids_per_block(502).is_empty()); - let expected_scheduled_ids_for_next_block = create_bounded_vec_with_schedule_ids(vec![schedule_id]); - assert_eq!(schedule_ids, expected_scheduled_ids_for_next_block); - - //Check if schedule ownership is created - assert!(DCA::owner_of(ALICE, schedule_id).is_some()); - }); -} - -#[test] -fn schedule_should_work_when_multiple_schedules_stored() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - - //Act - set_block_number(500); - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Assert - let schedule_id = 0; - let schedule_id_2 = 1; - assert!(DCA::schedules(schedule_id).is_some()); - assert!(DCA::schedules(schedule_id_2).is_some()); - - let scheduled_ids_for_next_block = DCA::schedule_ids_per_block(502); - - let expected_scheduled_ids_for_next_block = - create_bounded_vec_with_schedule_ids(vec![schedule_id, schedule_id_2]); - assert_eq!(scheduled_ids_for_next_block, expected_scheduled_ids_for_next_block); - }); -} - -#[test] -fn schedule_should_work_when_block_is_specified_by_user() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - - //Act - set_block_number(500); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::Some(600) - )); - - //Assert - let schedule_id = 0; - let stored_schedule = DCA::schedules(schedule_id).unwrap(); - assert_eq!(stored_schedule, schedule); - - //Check if schedule ids are stored - let schedule_ids = DCA::schedule_ids_per_block(600); - assert!(!DCA::schedule_ids_per_block(600).is_empty()); - let expected_scheduled_ids_for_next_block = create_bounded_vec_with_schedule_ids(vec![schedule_id]); - assert_eq!(schedule_ids, expected_scheduled_ids_for_next_block); - - //Check if schedule ownership is created - assert!(DCA::owner_of(ALICE, schedule_id).is_some()); - }); -} - -#[test] -fn schedule_should_emit_necessary_events() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - - //Act - set_block_number(500); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - - //Assert - let schedule_id = 0; - expect_events(vec![ - Event::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: 502, - } - .into(), - Event::Scheduled { - id: schedule_id, - who: ALICE, - period: schedule.period, - total_amount: schedule.total_amount, - order: schedule.order, - } - .into(), - ]); - }); -} - -#[test] -fn schedule_first_execution_cannot_be_next_block_manually() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - - //Act - set_block_number(500); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule.clone(), Some(501))); - - //Assert - expect_events(vec![ - Event::ExecutionPlanned { - id: 0, - who: ALICE, - block: 505, - } - .into(), - Event::Scheduled { - id: 0, - who: ALICE, - period: schedule.period, - total_amount: schedule.total_amount, - order: schedule.order, - } - .into(), - ]); - }); -} - -#[test] -fn schedule_should_emit_necessary_events_when_multiple_schedules_are_created() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - let schedule2 = ScheduleBuilder::new().build(); - - //Act and assert - set_block_number(500); - - let schedule_id = 0; - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - expect_events(vec![ - Event::ExecutionPlanned { - id: schedule_id, - who: ALICE, - block: 502, - } - .into(), - Event::Scheduled { - id: schedule_id, - who: ALICE, - period: schedule.period, - total_amount: schedule.total_amount, - order: schedule.order, - } - .into(), - ]); - - let schedule_id2 = 1; - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule2.clone(), - Option::Some(1000) - )); - expect_events(vec![ - Event::ExecutionPlanned { - id: schedule_id2, - who: ALICE, - block: 1000, - } - .into(), - Event::Scheduled { - id: schedule_id2, - who: ALICE, - period: schedule2.period, - total_amount: schedule2.total_amount, - order: schedule2.order, - } - .into(), - ]); - }); -} - -#[test] -fn schedule_should_throw_error_when_user_has_not_enough_balance() { - let total_amount_to_be_taken = 100 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, total_amount_to_be_taken - 1)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().with_total_amount(100 * ONE).build(); - - //Act - set_block_number(500); - assert_noop!( - DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None), - pallet_balances::Error::::InsufficientBalance - ); - }); -} - -#[test] -fn sell_schedule_should_throw_error_when_total_budget_is_smaller_than_amount_to_sell_plus_fee() { - let budget = 5 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 100 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let sell_fee = get_fee_for_sell_in_hdx(); - let schedule = ScheduleBuilder::new() - .with_total_amount(budget) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: budget + sell_fee, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - //Act - set_block_number(500); - - //Assert - assert_noop!( - DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None), - Error::::BudgetTooLow - ); - }); -} - -#[test] -fn schedule_should_fail_when_order_is_buy() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new() - .with_total_amount(100 * ONE) - .with_period(ONE_HUNDRED_BLOCKS) - .with_order(Order::Buy { - asset_in: HDX, - asset_out: BTC, - amount_out: 10 * ONE, - max_amount_in: 50 * ONE, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - //Act - set_block_number(500); - - //Assert - assert_noop!( - DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None), - Error::::NoLongerSupported - ); - }); -} - -#[test] -fn schedule_should_fail_when_not_called_by_user() { - ExtBuilder::default().build().execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - - //Act and assert - assert_noop!(DCA::schedule(RuntimeOrigin::none(), schedule, Option::None), BadOrigin); - }); -} - -#[test] -fn schedule_should_schedule_for_consequent_block_when_specified_block_is_full() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 1000000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - - for _ in RangeInclusive::new(1, 20) { - let schedule = ScheduleBuilder::new().build(); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule, - Option::Some(1000) - )); - } - - //Act - let schedule = ScheduleBuilder::new().build(); - let schedule_id = 20; - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule, - Option::Some(1000) - )); - - //Assert - let actual_schedule_ids = DCA::schedule_ids_per_block(1000); - assert_eq!(20, actual_schedule_ids.len()); - - assert_scheduled_ids!(1001, vec![schedule_id]); - }); -} - -#[test] -fn schedule_should_schedule_for_after_consequent_block_when_both_next_block_and_consquent_block_is_full() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 1000000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - - for _ in RangeInclusive::new(1, 40) { - let schedule = ScheduleBuilder::new().build(); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule, - Option::Some(1000) - )); - } - - //Act - let schedule = ScheduleBuilder::new().build(); - let schedule_id = 40; - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule, - Option::Some(1000) - )); - - //Assert - let block = 1000; - let actual_schedule_ids = DCA::schedule_ids_per_block(block); - assert_eq!(20, actual_schedule_ids.len()); - - let actual_schedule_ids = DCA::schedule_ids_per_block(block + GENERATED_SEARCH_RADIUSES[0]); - assert_eq!(20, actual_schedule_ids.len()); - - assert_scheduled_ids!( - block + GENERATED_SEARCH_RADIUSES[0] + GENERATED_SEARCH_RADIUSES[1], - vec![schedule_id] - ); - }); -} - -#[test] -fn schedule_should_fail_when_there_is_no_free_consquent_blocks() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 1000000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - - for _ in RangeInclusive::new(1, 220) { - let schedule = ScheduleBuilder::new().build(); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule, - Option::Some(1000) - )); - } - - //Check if all the blocks within radiuses are fully filled - let next_block = 1000; - let mut next_block_with_radius = next_block; - for radius in GENERATED_SEARCH_RADIUSES { - next_block_with_radius += radius; - let actual_schedule_ids = DCA::schedule_ids_per_block(next_block_with_radius); - assert_eq!(20, actual_schedule_ids.len()); - } - - //Act and assert - let schedule = ScheduleBuilder::new().build(); - assert_noop!( - DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(1000)), - Error::::NoFreeBlockFound - ); - }); -} - -#[test] -fn schedule_should_fail_when_total_amount_is_smaller_than_min_budget_and_sold_currency_is_native() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - - let schedule = ScheduleBuilder::new() - .with_total_amount(*ORIGINAL_MIN_BUDGET_IN_NATIVE - 1) - .build(); - - //Act and Assert - set_block_number(500); - - assert_noop!( - DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None), - Error::::TotalAmountIsSmallerThanMinBudget - ); - }); -} - -#[test] -fn schedule_should_fail_when_total_amount_in_non_native_currency_is_smaller_than_min_budget_in_native() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE), (ALICE, DAI, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - - let schedule = ScheduleBuilder::new() - .with_total_amount(*ORIGINAL_MIN_BUDGET_IN_NATIVE / 3) - .with_order(Order::Sell { - asset_in: DAI, - asset_out: HDX, - amount_in: 10 * ONE, - min_amount_out: 0, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - - //Act and Assert - set_block_number(500); - - assert_noop!( - DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None), - Error::::TotalAmountIsSmallerThanMinBudget - ); - }); -} - -#[test] -fn schedule_should_work_when_sell_amount_is_equal_to_20_times_fee() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let fee_in_native = get_fee_for_sell_in_hdx(); - let total_amount = 100 * ONE; - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: fee_in_native * 20, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - //Act - set_block_number(500); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None),); - }); -} -#[test] -fn schedule_should_fail_when_trade_amount_is_less_than_20x_fee() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let sell_dca_fee = get_fee_for_sell_in_hdx(); - let total_amount = 100 * ONE; - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: sell_dca_fee * 20 - 1, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - //Act - set_block_number(500); - - //Assert - assert_noop!( - DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None), - Error::::MinTradeAmountNotReached - ); - }); -} - -#[test] -fn schedule_should_fail_when_trade_amount_is_less_than_min_trading_limit() { - let min_trading_limit = ONE / 10; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .with_min_trading_limit(min_trading_limit) - .build() - .execute_with(|| { - //Arrange - let total_amount = 100 * ONE; - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: min_trading_limit - 1, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - //Act - set_block_number(500); - - //Assert - assert_noop!( - DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None), - Error::::MinTradeAmountNotReached - ); - }); -} - -#[test] -fn sell_schedule_should_work_when_total_amount_is_equal_to_2times_amount_in_plus_fee() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let amount_in = ONE; - let order = Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }; - - let fee_in_native = DCA::get_transaction_fee(&order, None).unwrap(); - let total_amount = 2 * (amount_in + fee_in_native); - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_order(order) - .build(); - - //Act and Assert - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - }); -} - -#[test] -fn schedule_should_init_retries_to_zero() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - - let total_amount = 100 * ONE; - let schedule = ScheduleBuilder::new().with_total_amount(total_amount).build(); - //Act - set_block_number(500); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Assert - let schedule_id = 0; - let retries = DCA::retries_on_error(schedule_id); - assert_eq!(0, retries); - }); -} - -#[test] -fn schedule_should_fail_when_wrong_user_is_specified_in_schedule() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let total_amount = 100 * ONE; - let schedule = ScheduleBuilder::new() - .with_owner(BOB) - .with_total_amount(total_amount) - .build(); - - set_block_number(500); - - //Act and assert - assert_noop!( - DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None), - Error::::Forbidden - ); - }); -} - -#[test] -fn schedule_should_be_created_when_no_routes_specified() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - - let total_amount = 100 * ONE; - let schedule = ScheduleBuilder::new() - .with_total_amount(total_amount) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: 10 * ONE, - min_amount_out: 0, - route: create_bounded_vec(vec![]), - }) - .build(); - - //Act and assert - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - }); -} - -#[test] -fn thousands_of_dcas_can_be_scheduled_on_a_specific_block_because_of_salt_added_to_block_search_randomness() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 100000000000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let total_amount = 100 * ONE; - let schedule = ScheduleBuilder::new().with_total_amount(total_amount).build(); - - use_prod_randomness(); - - //Act and assert - set_block_number(500); - for _ in RangeInclusive::new(1, 10000) { - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - } - }); -} - -pub fn set_block_number(n: u64) { - System::set_block_number(n); -} - -pub fn get_fee_for_sell_in_hdx() -> Balance { - let order = Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: ONE, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }; - - DCA::get_transaction_fee(&order, None).unwrap() -} - -#[test] -fn schedule_should_be_accepted_when_asset_in_is_not_a_fee_currency() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, DAI, 10000 * ONE), (ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - DAI cannot pay fees, but must still be sellable via DCA. - NON_FEE_ASSETS.with(|v| v.borrow_mut().push(DAI)); - - let schedule = ScheduleBuilder::new() - .with_order(Order::Sell { - asset_in: DAI, - asset_out: BTC, - amount_in: 10 * ONE, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: DAI, - asset_out: BTC, - }]), - }) - .build(); - - //Act & assert - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - }); -} diff --git a/pallets/dca/src/tests/storage_injection_fidelity.rs b/pallets/dca/src/tests/storage_injection_fidelity.rs deleted file mode 100644 index 7ae34b144e..0000000000 --- a/pallets/dca/src/tests/storage_injection_fidelity.rs +++ /dev/null @@ -1,152 +0,0 @@ -// This file is part of HydraDX. - -// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Guards `insert_schedule_into_storage` against drift from the `schedule` extrinsic: an order the -//! extrinsic still accepts must land in identical state either way. - -use crate::assert_scheduled_ids; -use crate::tests::schedule::set_block_number; -use crate::tests::*; -use crate::{Event as DcaEvent, ScheduleId}; -use frame_support::assert_ok; -use orml_traits::MultiReservableCurrency; -use pretty_assertions::assert_eq; - -#[test] -fn storage_injected_schedule_should_match_extrinsic_created_schedule() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10_000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let schedule = ScheduleBuilder::new().with_total_amount(1000 * ONE).build(); - - //Act - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - let reserved_by_extrinsic = Currencies::reserved_balance(HDX, &ALICE); - let injected_id = insert_schedule_into_storage(ALICE, schedule.clone(), Option::None); - - //Assert - assert_schedules_are_identical(0, injected_id, &schedule, reserved_by_extrinsic); - }); -} - -#[test] -fn storage_injected_rolling_schedule_should_match_extrinsic_created_schedule() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10_000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let rolling_budget = 0; - let schedule = ScheduleBuilder::new().with_total_amount(rolling_budget).build(); - - //Act - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::None - )); - let reserved_by_extrinsic = Currencies::reserved_balance(HDX, &ALICE); - let injected_id = insert_schedule_into_storage(ALICE, schedule.clone(), Option::None); - - //Assert - assert_schedules_are_identical(0, injected_id, &schedule, reserved_by_extrinsic); - }); -} - -#[test] -fn storage_injected_schedule_should_match_extrinsic_created_schedule_when_start_block_is_given() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10_000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let schedule = ScheduleBuilder::new().with_total_amount(1000 * ONE).build(); - let start_execution_block = 511; - - //Act - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule.clone(), - Option::Some(start_execution_block) - )); - let reserved_by_extrinsic = Currencies::reserved_balance(HDX, &ALICE); - let injected_id = - insert_schedule_into_storage(ALICE, schedule.clone(), Option::Some(start_execution_block)); - - //Assert - assert_eq!(DCA::schedule_execution_block(injected_id), Some(515)); - assert_schedules_are_identical(0, injected_id, &schedule, reserved_by_extrinsic); - }); -} - -fn assert_schedules_are_identical( - extrinsic_id: ScheduleId, - injected_id: ScheduleId, - schedule: &Schedule, - reserved_by_extrinsic: Balance, -) { - assert_eq!(injected_id, extrinsic_id + 1); - assert_eq!(DCA::schedules(injected_id), DCA::schedules(extrinsic_id)); - assert_eq!( - DCA::owner_of(schedule.owner, injected_id), - DCA::owner_of(schedule.owner, extrinsic_id) - ); - assert_eq!( - DCA::remaining_amounts(injected_id), - DCA::remaining_amounts(extrinsic_id) - ); - assert_eq!(DCA::retries_on_error(injected_id), DCA::retries_on_error(extrinsic_id)); - assert_eq!( - DCA::schedule_extra_gas(injected_id), - DCA::schedule_extra_gas(extrinsic_id) - ); - - let execution_block = DCA::schedule_execution_block(extrinsic_id).unwrap(); - assert_eq!(DCA::schedule_execution_block(injected_id), Some(execution_block)); - assert_scheduled_ids!(execution_block, vec![extrinsic_id, injected_id]); - - assert_eq!( - Currencies::reserved_balance(schedule.order.get_asset_in(), &schedule.owner), - 2 * reserved_by_extrinsic - ); - - expect_events(vec![ - DcaEvent::Scheduled { - id: injected_id, - who: schedule.owner, - period: schedule.period, - total_amount: schedule.total_amount, - order: schedule.order.clone(), - } - .into(), - DcaEvent::ExecutionPlanned { - id: injected_id, - who: schedule.owner, - block: execution_block, - } - .into(), - ]); -} diff --git a/pallets/dca/src/tests/terminate.rs b/pallets/dca/src/tests/terminate.rs deleted file mode 100644 index b11fab0937..0000000000 --- a/pallets/dca/src/tests/terminate.rs +++ /dev/null @@ -1,477 +0,0 @@ -// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::tests::mock::*; -use crate::tests::*; -use crate::{assert_scheduled_ids, assert_that_schedule_has_been_removed_from_storages}; -use crate::{Error, Event}; -use frame_support::traits::Hooks; -use frame_support::{assert_noop, assert_ok}; -use orml_traits::NamedMultiReservableCurrency; -use pretty_assertions::assert_eq; -use sp_runtime::DispatchError::BadOrigin; - -#[test] -fn terminate_should_remove_schedule_from_storage() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let schedule = ScheduleBuilder::new().build(); - let schedule_id = 0; - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(600))); - - //Act - assert_ok!(DCA::terminate(RuntimeOrigin::root(), schedule_id, Some(600))); - - //Assert - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - - expect_events(vec![Event::Terminated { - id: 0, - who: ALICE, - error: Error::::ManuallyTerminated.into(), - } - .into()]); - }); -} - -#[test] -fn terminate_should_unreserve_all_named_reserved() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let total_amount = 100 * ONE; - let schedule = ScheduleBuilder::new().with_total_amount(total_amount).build(); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(600))); - - let schedule_id = 0; - assert_eq!( - total_amount, - Currencies::reserved_balance_named(&NamedReserveId::get(), HDX, &ALICE) - ); - - //Act - assert_ok!(DCA::terminate(RuntimeOrigin::root(), schedule_id, Some(600))); - - //Assert - assert_eq!( - 0, - Currencies::reserved_balance_named(&NamedReserveId::get(), HDX, &ALICE) - ); - }); -} - -#[test] -fn terminate_should_unreserve_all_named_reserved_only_for_single_dca_when_there_are_multiple() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let total_amount = 100 * ONE; - let schedule = ScheduleBuilder::new().with_total_amount(total_amount).build(); - let schedule2 = ScheduleBuilder::new().with_total_amount(total_amount).build(); - let total_reserved = total_amount * 2; - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(600))); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule2, - Option::Some(700) - )); - - let schedule_id = 0; - assert_eq!( - total_reserved, - Currencies::reserved_balance_named(&NamedReserveId::get(), HDX, &ALICE) - ); - - //Act - assert_ok!(DCA::terminate(RuntimeOrigin::root(), schedule_id, Some(600))); - - //Assert - assert_eq!( - total_reserved / 2, - Currencies::reserved_balance_named(&NamedReserveId::get(), HDX, &ALICE) - ); - }); -} - -#[test] -fn terminate_should_remove_planned_execution_when_there_is_only_single_execution_on_block() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let schedule = ScheduleBuilder::new().build(); - let schedule_id = 0; - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(600))); - - //Act - assert_ok!(DCA::terminate(RuntimeOrigin::root(), schedule_id, Some(600))); - - //Assert - assert!(DCA::schedule_ids_per_block(600).is_empty()); - }); -} - -#[test] -fn terminate_should_remove_planned_execution_when_there_are_multiple_planned_executions_on_block() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let schedule = ScheduleBuilder::new().build(); - let schedule2 = ScheduleBuilder::new().build(); - let schedule_id = 0; - let block = 600; - - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule, - Option::Some(block) - )); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule2, - Option::Some(block) - )); - - //Act - assert_ok!(DCA::terminate(RuntimeOrigin::root(), schedule_id, Some(block))); - - //Assert - assert_scheduled_ids!(block, vec![1]); - }); -} - -#[test] -fn terminate_should_pass_when_called_by_owner() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - set_block_number(500); - let schedule_id = 0; - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act and assert - assert_ok!(DCA::terminate(RuntimeOrigin::signed(ALICE), schedule_id, Some(502))); - }); -} - -#[test] -fn terminate_should_fail_when_called_by_non_owner() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - set_block_number(500); - let schedule_id = 0; - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act and assert - assert_noop!( - DCA::terminate(RuntimeOrigin::signed(BOB), schedule_id, Some(501)), - Error::::Forbidden - ); - }); -} - -#[test] -fn terminate_should_fail_when_called_by_non_signed() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - set_block_number(500); - let schedule_id = 0; - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act and assert - assert_noop!(DCA::terminate(RuntimeOrigin::none(), schedule_id, Some(501)), BadOrigin); - }); -} - -#[test] -fn terminate_should_pass_when_called_by_technical_origin() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - set_block_number(500); - let schedule_id = 0; - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act and assert - assert_ok!(DCA::terminate(RuntimeOrigin::root(), schedule_id, Some(502))); - }); -} - -#[test] -fn terminate_should_fail_when_no_planned_execution_in_block() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - set_block_number(500); - let schedule_id = 0; - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::None)); - - //Act and assert - assert_noop!( - DCA::terminate(RuntimeOrigin::root(), schedule_id, Some(9999)), - Error::::ScheduleNotFound - ); - }); -} - -#[test] -fn terminate_should_fail_when_there_is_planned_execution_in_block_not_not_for_schedule() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - let schedule = ScheduleBuilder::new().build(); - let schedule2 = ScheduleBuilder::new().build(); - set_block_number(500); - let schedule_id = 0; - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule, - Option::Some(1000) - )); - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule2, Option::None)); - - //Act and assert - assert_noop!( - DCA::terminate(RuntimeOrigin::root(), schedule_id, Some(501)), - Error::::ScheduleNotFound - ); - }); -} - -#[test] -fn terminate_should_fail_when_with_nonexisting_schedule() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Act and assert - assert_noop!( - DCA::terminate(RuntimeOrigin::root(), 999, Some(501)), - Error::::ScheduleNotFound - ); - }); -} - -#[test] -fn terminate_should_work_when_no_block_specified() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let schedule = ScheduleBuilder::new().with_period(300).build(); - let schedule_id = 0; - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(600))); - set_block_number(600); - - //Act - assert_ok!(DCA::terminate(RuntimeOrigin::root(), schedule_id, None)); - - //Assert - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - - expect_events(vec![Event::Terminated { - id: 0, - who: ALICE, - error: Error::::ManuallyTerminated.into(), - } - .into()]); - }); -} - -#[test] -fn terminate_should_work_when_no_block_specified_and_schedule_eeceuted_multiple_times() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let schedule = ScheduleBuilder::new().with_period(300).build(); - let schedule_id = 0; - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(600))); - set_block_number(600); - set_block_number(900); - - //Act - assert_ok!(DCA::terminate(RuntimeOrigin::root(), schedule_id, None)); - - //Assert - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - - expect_events(vec![Event::Terminated { - id: 0, - who: ALICE, - error: Error::::ManuallyTerminated.into(), - } - .into()]); - }); -} - -#[test] -fn terminate_should_work_with_no_blocknumber_when_just_scheduled() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let schedule = ScheduleBuilder::new().with_period(300).build(); - let schedule_id = 0; - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(600))); - - //Act - assert_ok!(DCA::terminate(RuntimeOrigin::root(), schedule_id, None)); - - //Assert - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id); - - expect_events(vec![Event::Terminated { - id: 0, - who: ALICE, - error: Error::::ManuallyTerminated.into(), - } - .into()]); - }); -} - -#[test] -fn terminate_should_not_depend_on_schedule_ids_per_block_ordering() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE), (BOB, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - let (block_600, schedule_id_0, schedule_id_1) = arrange_unsorted_schedule_ids_per_block_600(); - - let reserved_before = Currencies::reserved_balance_named(&NamedReserveId::get(), HDX, &ALICE); - assert!(reserved_before > 0); - - assert_ok!(DCA::terminate(RuntimeOrigin::signed(ALICE), schedule_id_1, None)); - - assert_that_schedule_has_been_removed_from_storages!(ALICE, schedule_id_1); - assert_eq!(DCA::schedule_ids_per_block(block_600).to_vec(), vec![schedule_id_0]); - assert_eq!( - Currencies::reserved_balance_named(&NamedReserveId::get(), HDX, &ALICE), - 0 - ); - }); -} - -fn arrange_unsorted_schedule_ids_per_block_600() -> (u64, ScheduleId, ScheduleId) { - // Builds `ScheduleIdsPerBlock[600] == [1, 0]` via normal flow. - let block_502 = 502u64; - let block_600 = 600u64; - let schedule_id_0: ScheduleId = 0; - let schedule_id_1: ScheduleId = 1; - - set_block_number(500); - - let schedule_replans_into_block_600 = ScheduleBuilder::new() - .with_owner(BOB) - .with_period(98) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: ONE, - min_amount_out: 0, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(BOB), - schedule_replans_into_block_600, - None - )); - assert!(DCA::schedules(schedule_id_0).is_some()); - - let schedule_planned_for_block_600 = ScheduleBuilder::new() - .with_total_amount(0) - .with_order(Order::Sell { - asset_in: HDX, - asset_out: BTC, - amount_in: ONE, - min_amount_out: 0, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: BTC, - }]), - }) - .build(); - assert_ok!(DCA::schedule( - RuntimeOrigin::signed(ALICE), - schedule_planned_for_block_600, - Some(block_600) - )); - assert!(DCA::schedules(schedule_id_1).is_some()); - - set_block_number(block_502); - - assert!(DCA::schedules(schedule_id_1).is_some()); - assert_eq!(DCA::schedule_execution_block(schedule_id_1), Some(block_600)); - assert_eq!( - DCA::schedule_ids_per_block(block_600).to_vec(), - vec![schedule_id_1, schedule_id_0] - ); - assert!(DCA::schedule_ids_per_block(block_600).contains(&schedule_id_1)); - - (block_600, schedule_id_0, schedule_id_1) -} - -pub fn set_block_number(to: u64) { - System::set_block_number(to); - DCA::on_initialize(to); -} diff --git a/pallets/dca/src/tests/unlock_reserves.rs b/pallets/dca/src/tests/unlock_reserves.rs deleted file mode 100644 index 8aaa8f235f..0000000000 --- a/pallets/dca/src/tests/unlock_reserves.rs +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::tests::mock::*; -use crate::tests::*; -use crate::{assert_balance, Error, Event}; -use frame_support::{assert_noop, assert_ok, traits::Hooks}; -use orml_traits::{MultiCurrency, NamedMultiReservableCurrency}; -use pretty_assertions::assert_eq; - -#[test] -fn unlock_should_not_work_when_user_has_active_schedule() { - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, 10000 * ONE)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - let schedule = ScheduleBuilder::new().build(); - assert_ok!(Currencies::reserve_named(&NamedReserveId::get(), HDX, &ALICE, 10 * ONE)); - - assert_ok!(DCA::schedule(RuntimeOrigin::signed(ALICE), schedule, Option::Some(600))); - - //Act - assert_noop!( - DCA::unlock_reserves(RuntimeOrigin::signed(ALICE), ALICE, HDX), - Error::::HasActiveSchedules - ); - }); -} - -#[test] -fn unlock_should_unreserve_when_user_has_leftover() { - let init_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, init_balance)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - - let leftover = 10 * ONE; - assert_ok!(Currencies::reserve_named(&NamedReserveId::get(), HDX, &ALICE, 10 * ONE)); - - assert_balance!(ALICE, HDX, init_balance - leftover); - - //Act - assert_ok!(DCA::unlock_reserves(RuntimeOrigin::signed(ALICE), ALICE, HDX)); - - //Assert - assert_balance!(ALICE, HDX, init_balance); - expect_events(vec![Event::ReserveUnlocked { - who: ALICE, - asset_id: HDX, - } - .into()]); - }); -} - -#[test] -fn unlock_should_work_when_called_by_root() { - let init_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, init_balance)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - - let leftover = 10 * ONE; - assert_ok!(Currencies::reserve_named(&NamedReserveId::get(), HDX, &ALICE, 10 * ONE)); - - assert_balance!(ALICE, HDX, init_balance - leftover); - - //Act - assert_ok!(DCA::unlock_reserves(RuntimeOrigin::root(), ALICE, HDX)); - - //Assert - assert_balance!(ALICE, HDX, init_balance); - }); -} - -#[test] -fn unlock_should_work_when_called_by_other_user() { - let init_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, init_balance)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - - let leftover = 10 * ONE; - assert_ok!(Currencies::reserve_named(&NamedReserveId::get(), HDX, &ALICE, 10 * ONE)); - - assert_balance!(ALICE, HDX, init_balance - leftover); - - //Act - assert_ok!(DCA::unlock_reserves(RuntimeOrigin::signed(BOB), ALICE, HDX)); - - //Assert - assert_balance!(ALICE, HDX, init_balance); - }); -} - -#[test] -fn unlock_should_not_work_when_nothing_is_reserved() { - let init_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, init_balance)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - - //Act - assert_noop!( - DCA::unlock_reserves(RuntimeOrigin::signed(ALICE), ALICE, HDX), - Error::::NoReservesLocked - ); - }); -} - -#[test] -fn unlock_should_fail_when_asset_doesnt_exist() { - let init_balance = 10000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![(ALICE, HDX, init_balance)]) - .build() - .execute_with(|| { - //Arrange - set_block_number(500); - - //Act - assert_noop!( - DCA::unlock_reserves(RuntimeOrigin::signed(ALICE), ALICE, 9999), - Error::::NoReservesLocked - ); - }); -} - -pub fn set_block_number(to: u64) { - System::set_block_number(to); - DCA::on_initialize(to); -} diff --git a/pallets/dca/src/types.rs b/pallets/dca/src/types.rs deleted file mode 100644 index 72d5d4bda5..0000000000 --- a/pallets/dca/src/types.rs +++ /dev/null @@ -1,113 +0,0 @@ -use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen}; -use hydradx_traits::router::{AssetPair, Route, RouteProvider, Trade}; -use scale_info::TypeInfo; -use sp_runtime::traits::ConstU32; -use sp_runtime::{BoundedVec, DispatchError, Permill}; - -pub type Balance = u128; -pub type ScheduleId = u32; -pub type NamedReserveIdentifier = [u8; 8]; - -const MAX_NUMBER_OF_TRADES: u32 = 9; - -/// DCA schedule containing information to execute repeating orders. -#[derive(Encode, Decode, DecodeWithMemTracking, Debug, Eq, PartialEq, Clone, TypeInfo, MaxEncodedLen)] -pub struct Schedule { - /// The owner of the schedule. - pub owner: AccountId, - /// The time period (in blocks) between two schedule executions. - pub period: BlockNumber, - /// The total amount (budget) the user wants to spend on the whole DCA. - /// Can be set to zero, in which case the schedule will run indefinitely. - /// Its currency is the sold (amount_in) currency specified in `order`. - pub total_amount: Balance, - /// The maximum number of retries in case of failing schedules. - /// If not specified, the default pallet configuration `MaxPriceDifferenceBetweenBlocks` is used. - pub max_retries: Option, - /// The price stability threshold used to check if the price is stable. - /// The check is performed by comparing the spot price and short oracle price. - /// If not specified, the default pallet configuration `MaxPriceDifferenceBetweenBlocks` is used. - pub stability_threshold: Option, - /// The slippage limit used to calculate the `min_amount_out` and `max_amount_in` trade limits. - pub slippage: Option, - /// The order containing information to execute a specific trade by the router. - pub order: Order, -} - -impl Schedule { - pub fn is_rolling(&self) -> bool { - self.total_amount == 0 - } -} - -#[derive(Encode, Decode, DecodeWithMemTracking, Debug, Eq, PartialEq, Clone, TypeInfo, MaxEncodedLen)] -pub enum Order { - Sell { - asset_in: AssetId, - asset_out: AssetId, - amount_in: Balance, - min_amount_out: Balance, - route: BoundedVec, ConstU32>, - }, - Buy { - asset_in: AssetId, - asset_out: AssetId, - amount_out: Balance, - max_amount_in: Balance, - route: BoundedVec, ConstU32>, - }, -} - -impl Order -where - AssetId: Copy, -{ - pub fn get_asset_in(&self) -> AssetId { - let asset_in = match &self { - Order::Sell { asset_in, .. } => asset_in, - Order::Buy { asset_in, .. } => asset_in, - }; - *asset_in - } - - pub fn get_asset_out(&self) -> AssetId { - let asset_out = match &self { - Order::Sell { asset_out, .. } => asset_out, - Order::Buy { asset_out, .. } => asset_out, - }; - *asset_out - } - - pub fn get_route_or_default>(&self) -> Route { - let route = match &self { - Order::Sell { route, .. } => route, - Order::Buy { route, .. } => route, - }; - if route.is_empty() { - Provider::get_route(AssetPair::new(self.get_asset_in(), self.get_asset_out())) - } else { - route.clone() - } - } -} - -/// Why the migration cancelled a schedule instead of converting it into a DCA intent. -#[derive(Encode, Decode, DecodeWithMemTracking, Debug, Eq, PartialEq, Clone, TypeInfo, MaxEncodedLen)] -pub enum CancelReason { - /// Buy orders have no intent equivalent — intents are sell-only. - BuyOrder, - /// The remaining budget no longer covers a single trade. - BudgetBelowTrade, - /// Releasing the schedule's reserve left a remainder, so the reserve was inconsistent. - UnreserveRemainder, - /// The intent pallet rejected the converted schedule. - IntentCreationFailed(DispatchError), - /// Cancelled by governance through `force_cancel_schedules`. - ForceCancelled, -} - -impl From for CancelReason { - fn from(error: DispatchError) -> Self { - CancelReason::IntentCreationFailed(error) - } -} diff --git a/pallets/dca/src/weights.rs b/pallets/dca/src/weights.rs deleted file mode 100644 index 498421fa8d..0000000000 --- a/pallets/dca/src/weights.rs +++ /dev/null @@ -1,162 +0,0 @@ -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(missing_docs)] - -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; - -/// Weight functions needed for pallet_dca. -pub trait WeightInfo { - fn on_initialize_with_buy_trade() -> Weight; - fn on_initialize_with_sell_trade() -> Weight; - fn on_initialize_with_empty_block() -> Weight; - fn schedule() -> Weight; - fn terminate() -> Weight; - fn unlock_reserves() -> Weight; - fn set_migration_enabled() -> Weight; -} - -/// Weights for pallet_dca using the hydraDX node and recommended hardware. -impl WeightInfo for () { - /// Storage: `DCA::ScheduleIdsPerBlock` (r:12 w:2) - /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(101), added: 2576, mode: `MaxEncodedLen`) - /// Storage: `DCA::Schedules` (r:1 w:0) - /// Proof: `DCA::Schedules` (`max_values`: None, `max_size`: Some(191), added: 2666, mode: `MaxEncodedLen`) - /// Storage: `DCA::RemainingAmounts` (r:1 w:1) - /// Proof: `DCA::RemainingAmounts` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `DCA::RetriesOnError` (r:0 w:1) - /// Proof: `DCA::RetriesOnError` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - fn on_initialize_with_buy_trade() -> Weight { - // Proof Size summary in bytes: - // Measured: `54972` - // Estimated: `31902` - // Minimum execution time: 244_057_000 picoseconds. - Weight::from_parts(245_867_000, 31902) - .saturating_add(RocksDbWeight::get().reads(17_u64)) - .saturating_add(RocksDbWeight::get().writes(7_u64)) - } - /// Storage: `DCA::ScheduleIdsPerBlock` (r:12 w:2) - /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(101), added: 2576, mode: `MaxEncodedLen`) - /// Storage: `DCA::Schedules` (r:1 w:0) - /// Proof: `DCA::Schedules` (`max_values`: None, `max_size`: Some(191), added: 2666, mode: `MaxEncodedLen`) - /// Storage: `DCA::RemainingAmounts` (r:1 w:1) - /// Proof: `DCA::RemainingAmounts` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `DCA::RetriesOnError` (r:0 w:1) - /// Proof: `DCA::RetriesOnError` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - fn on_initialize_with_sell_trade() -> Weight { - // Proof Size summary in bytes: - // Measured: `54720` - // Estimated: `31902` - // Minimum execution time: 242_907_000 picoseconds. - Weight::from_parts(247_259_000, 31902) - .saturating_add(RocksDbWeight::get().reads(17_u64)) - .saturating_add(RocksDbWeight::get().writes(7_u64)) - } - /// Storage: `DCA::ScheduleIdsPerBlock` (r:1 w:0) - /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(101), added: 2576, mode: `MaxEncodedLen`) - fn on_initialize_with_empty_block() -> Weight { - // Proof Size summary in bytes: - // Measured: `1113` - // Estimated: `3566` - // Minimum execution time: 19_461_000 picoseconds. - Weight::from_parts(19_757_000, 3566) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - } - /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:2 w:0) - /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::NextAssetId` (r:1 w:0) - /// Proof: `AssetRegistry::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::LocationAssets` (r:1 w:0) - /// Proof: `AssetRegistry::LocationAssets` (`max_values`: None, `max_size`: Some(622), added: 3097, mode: `MaxEncodedLen`) - /// Storage: `Router::Routes` (r:1 w:0) - /// Proof: `Router::Routes` (`max_values`: None, `max_size`: Some(90), added: 2565, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:3 w:1) - /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleIdSequencer` (r:1 w:1) - /// Proof: `DCA::ScheduleIdSequencer` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Reserves` (r:1 w:1) - /// Proof: `Tokens::Reserves` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleIdsPerBlock` (r:11 w:1) - /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(101), added: 2576, mode: `MaxEncodedLen`) - /// Storage: `DCA::RetriesOnError` (r:0 w:1) - /// Proof: `DCA::RetriesOnError` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `DCA::Schedules` (r:0 w:1) - /// Proof: `DCA::Schedules` (`max_values`: None, `max_size`: Some(191), added: 2666, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleOwnership` (r:0 w:1) - /// Proof: `DCA::ScheduleOwnership` (`max_values`: None, `max_size`: Some(60), added: 2535, mode: `MaxEncodedLen`) - /// Storage: `DCA::RemainingAmounts` (r:0 w:1) - /// Proof: `DCA::RemainingAmounts` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - fn schedule() -> Weight { - // Proof Size summary in bytes: - // Measured: `53355` - // Estimated: `29326` - // Minimum execution time: 234_203_000 picoseconds. - Weight::from_parts(237_715_000, 29326) - .saturating_add(RocksDbWeight::get().reads(23_u64)) - .saturating_add(RocksDbWeight::get().writes(8_u64)) - } - /// Storage: `DCA::Schedules` (r:1 w:1) - /// Proof: `DCA::Schedules` (`max_values`: None, `max_size`: Some(191), added: 2666, mode: `MaxEncodedLen`) - /// Storage: `DCA::RemainingAmounts` (r:1 w:1) - /// Proof: `DCA::RemainingAmounts` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleIdsPerBlock` (r:1 w:1) - /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(101), added: 2576, mode: `MaxEncodedLen`) - /// Storage: `DCA::RetriesOnError` (r:0 w:1) - /// Proof: `DCA::RetriesOnError` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleOwnership` (r:0 w:1) - /// Proof: `DCA::ScheduleOwnership` (`max_values`: None, `max_size`: Some(60), added: 2535, mode: `MaxEncodedLen`) - fn terminate() -> Weight { - // Proof Size summary in bytes: - // Measured: `2530` - // Estimated: `4714` - // Minimum execution time: 86_873_000 picoseconds. - Weight::from_parts(88_015_000, 4714) - .saturating_add(RocksDbWeight::get().reads(5_u64)) - .saturating_add(RocksDbWeight::get().writes(7_u64)) - } - - /// Storage: `DCA::ScheduleOwnership` (r:1 w:0) - /// Proof: `DCA::ScheduleOwnership` (`max_values`: None, `max_size`: Some(60), added: 2535, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn unlock_reserves() -> Weight { - // Proof Size summary in bytes: - // Measured: `1959` - // Estimated: `4714` - // Minimum execution time: 36_000_000 picoseconds. - Weight::from_parts(40_000_000, 4714) - .saturating_add(RocksDbWeight::get().reads(3_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } - - /// Storage: `DCA::MigrationEnabled` (r:0 w:1) - /// Proof: `DCA::MigrationEnabled` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) - fn set_migration_enabled() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 5_000_000 picoseconds. - Weight::from_parts(5_000_000, 0) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } -} diff --git a/pallets/ice/Cargo.toml b/pallets/ice/Cargo.toml index d32939345a..4238f0143c 100644 --- a/pallets/ice/Cargo.toml +++ b/pallets/ice/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-ice" -version = "1.15.0" +version = "1.15.1" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/ice/support/Cargo.toml b/pallets/ice/support/Cargo.toml index 4eacf61c24..789f0a439c 100644 --- a/pallets/ice/support/Cargo.toml +++ b/pallets/ice/support/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ice-support" -version = "1.7.0" +version = "2.0.0" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/ice/support/src/lib.rs b/pallets/ice/support/src/lib.rs index 827a9b1dec..959524e07d 100644 --- a/pallets/ice/support/src/lib.rs +++ b/pallets/ice/support/src/lib.rs @@ -4,7 +4,7 @@ use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen}; use frame_support::pallet_prelude::{ConstU32, Get, RuntimeDebug, TypeInfo}; use frame_support::sp_runtime::traits::CheckedConversion; -use frame_support::sp_runtime::{DispatchError, Permill}; +use frame_support::sp_runtime::Permill; use frame_support::BoundedVec; use hydra_dx_math::types::Ratio; use hydradx_traits::router::Route; @@ -379,16 +379,6 @@ impl DcaParams { } } -/// Creates a DCA intent for an account whose old-pallet DCA schedule is being converted. -/// -/// Implementations must bypass the per-account intent cap: the schedule already existed and the old -/// pallet releases its reserve before this is called, so refusing here would strand the user's funds. -/// Deliberately not implemented for `()` — a runtime that forgets to wire it must fail to compile -/// rather than silently cancel every schedule it was supposed to migrate. -pub trait IntentMigrator { - fn add_migrated_intent(owner: AccountId, params: DcaParams) -> Result; -} - #[derive(Clone, DecodeWithMemTracking, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)] pub struct DcaData { /// Asset being sold per trade diff --git a/pallets/intent/Cargo.toml b/pallets/intent/Cargo.toml index b900036f66..414329c4b0 100644 --- a/pallets/intent/Cargo.toml +++ b/pallets/intent/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-intent" -version = "1.13.1" +version = "1.14.0" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/intent/src/lib.rs b/pallets/intent/src/lib.rs index 4c40b2c39b..c21363bce8 100644 --- a/pallets/intent/src/lib.rs +++ b/pallets/intent/src/lib.rs @@ -499,19 +499,24 @@ impl Pallet { Error::::MaxIntentsReached ); - Self::do_add_intent(owner, input) + Self::do_add_intent(owner, input, 0) } - /// Creates a DCA intent for a schedule converted from `pallet-dca`. + /// Creates a DCA intent for a converted legacy DCA schedule, first offered to the solver at + /// `max(first_eligible_block, current block)`. /// - /// The per-account cap is not enforced here — see `IntentMigrator`. + /// The per-account cap is not enforced: refusing would strand the already released reserve. /// /// A sub-ED `amount_out` is lifted to the ED instead of rejected: it is only the user's hard /// floor, and the enforced minimum stays `max(hard limit, oracle floor)` /// (`compute_dca_effective_limit`), so lifting it cannot execute the schedule any worse. /// `amount_in` is deliberately not clamped — raising the spend side would change the schedule. #[require_transactional] - pub fn do_add_migrated_intent(owner: T::AccountId, mut params: DcaParams) -> Result { + pub fn do_add_migrated_intent( + owner: T::AccountId, + mut params: DcaParams, + first_eligible_block: u32, + ) -> Result { if let Some(ed_out) = T::RegistryHandler::existential_deposit(params.asset_out) { params.amount_out = params.amount_out.max(ed_out); } @@ -528,6 +533,7 @@ impl Pallet { deadline: None, on_resolved: None, }, + first_eligible_block, ) } @@ -540,7 +546,11 @@ impl Pallet { } #[require_transactional] - fn do_add_intent(owner: T::AccountId, input: IntentInput) -> Result { + fn do_add_intent( + owner: T::AccountId, + input: IntentInput, + first_eligible_block: u32, + ) -> Result { let now = T::TimestampProvider::now(); if let Some(deadline) = input.deadline { log::debug!(target: OCW_LOG_TARGET, "{:?}: add_intent(), deadline: {:?}, now: {:?}, max_deadline: {:?}", @@ -602,9 +612,10 @@ impl Pallet { // Back-dated by one period so the first trade is due immediately: `period` is the gap // between trades, not a delay before the first one. `resolve_dca_intent` stamps // `max(last + period, current)`, so an early fill consumes its slot and the cadence stays exact. + let first_eligible = current_block.max(first_eligible_block); IntentData::Dca( data.clone() - .into_data(reserve_amount, current_block.saturating_sub(data.period)), + .into_data(reserve_amount, first_eligible.saturating_sub(data.period)), ) } IntentDataInput::MatchFirstSwap { ref swap, match_window } => { @@ -1333,9 +1344,3 @@ impl Pallet { (deadline as u128) << 64 | incremental_id as u128 } } - -impl ice_support::IntentMigrator for Pallet { - fn add_migrated_intent(owner: T::AccountId, params: DcaParams) -> Result { - Self::do_add_migrated_intent(owner, params) - } -} diff --git a/pallets/intent/src/tests/dca_intent.rs b/pallets/intent/src/tests/dca_intent.rs index 54d81df4e2..e4b49b90a1 100644 --- a/pallets/intent/src/tests/dca_intent.rs +++ b/pallets/intent/src/tests/dca_intent.rs @@ -801,7 +801,7 @@ fn do_add_migrated_intent_should_clamp_amount_out_when_below_existential_deposit .build() .execute_with(|| { let _ = with_transaction(|| { - let id = crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ONE_HDX, ED - 1)) + let id = crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ONE_HDX, ED - 1), 0) .expect("should work"); assert_eq!(stored_dca(id).amount_out, ED); @@ -818,7 +818,7 @@ fn do_add_migrated_intent_should_clamp_amount_out_when_amount_out_is_zero() { .build() .execute_with(|| { let _ = with_transaction(|| { - let id = crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ONE_HDX, 0)) + let id = crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ONE_HDX, 0), 0) .expect("should work"); assert_eq!(stored_dca(id).amount_out, ED); @@ -835,10 +835,11 @@ fn do_add_migrated_intent_should_keep_amount_out_when_at_or_above_existential_de .build() .execute_with(|| { let _ = with_transaction(|| { - let at_ed = crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ONE_HDX, ED)) - .expect("should work"); - let above_ed = crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ONE_HDX, ONE_DOT)) + let at_ed = crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ONE_HDX, ED), 0) .expect("should work"); + let above_ed = + crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ONE_HDX, ONE_DOT), 0) + .expect("should work"); assert_eq!(stored_dca(at_ed).amount_out, ED); assert_eq!(stored_dca(above_ed).amount_out, ONE_DOT); @@ -856,7 +857,7 @@ fn do_add_migrated_intent_should_fail_when_amount_in_is_below_existential_deposi .execute_with(|| { let _ = with_transaction(|| { assert_noop!( - crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ED - 1, ONE_DOT)), + crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ED - 1, ONE_DOT), 0), Error::::InvalidIntent ); @@ -959,7 +960,7 @@ fn do_add_migrated_intent_should_clamp_slippage_when_it_exceeds_the_cap() { let mut params = migrated_params(ONE_HDX, ONE_DOT); params.slippage = Permill::from_percent(80); - let id = crate::Pallet::::do_add_migrated_intent(ALICE, params).expect("must not be refused"); + let id = crate::Pallet::::do_add_migrated_intent(ALICE, params, 0).expect("must not be refused"); assert_eq!(stored_dca(id).slippage, MaxDcaSlippage::get()); @@ -978,7 +979,7 @@ fn do_add_migrated_intent_should_keep_slippage_when_within_the_cap() { let mut params = migrated_params(ONE_HDX, ONE_DOT); params.slippage = Permill::from_percent(2); - let id = crate::Pallet::::do_add_migrated_intent(ALICE, params).expect("should work"); + let id = crate::Pallet::::do_add_migrated_intent(ALICE, params, 0).expect("should work"); assert_eq!(stored_dca(id).slippage, Permill::from_percent(2)); @@ -986,3 +987,39 @@ fn do_add_migrated_intent_should_keep_slippage_when_within_the_cap() { }); }); } + +#[test] +fn do_add_migrated_intent_should_first_be_eligible_at_given_block_when_it_is_in_the_future() { + ExtBuilder::default() + .with_endowed_accounts(vec![(ALICE, HDX, 100 * ONE_HDX)]) + .build() + .execute_with(|| { + set_block_number(100); + let _ = with_transaction(|| { + let id = crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ONE_HDX, ONE_DOT), 250) + .expect("should work"); + + assert_eq!(stored_dca(id).last_execution_block, 240); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} + +#[test] +fn do_add_migrated_intent_should_be_eligible_immediately_when_given_block_is_in_the_past() { + ExtBuilder::default() + .with_endowed_accounts(vec![(ALICE, HDX, 100 * ONE_HDX)]) + .build() + .execute_with(|| { + set_block_number(100); + let _ = with_transaction(|| { + let id = crate::Pallet::::do_add_migrated_intent(ALICE, migrated_params(ONE_HDX, ONE_DOT), 50) + .expect("should work"); + + assert_eq!(stored_dca(id).last_execution_block, 90); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} diff --git a/pallets/intent/src/tests/submit_intent.rs b/pallets/intent/src/tests/submit_intent.rs index d086877c7d..de01f19468 100644 --- a/pallets/intent/src/tests/submit_intent.rs +++ b/pallets/intent/src/tests/submit_intent.rs @@ -449,7 +449,7 @@ fn migration_should_still_convert_when_settlement_is_disabled() { }; let _ = frame_support::storage::with_transaction(|| { - assert_ok!(crate::Pallet::::do_add_migrated_intent(ALICE, params.clone())); + assert_ok!(crate::Pallet::::do_add_migrated_intent(ALICE, params.clone(), 0)); assert_eq!(Intents::::iter().count(), 1); sp_runtime::TransactionOutcome::Commit(sp_runtime::DispatchResult::Ok(())) }); diff --git a/runtime/adapters/Cargo.toml b/runtime/adapters/Cargo.toml index 9e050f6a58..8958502f64 100644 --- a/runtime/adapters/Cargo.toml +++ b/runtime/adapters/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-adapters" -version = "2.0.1" +version = "3.0.0" description = "Structs and other generic types for building runtimes." authors = ["GalacticCouncil"] edition = "2021" @@ -60,7 +60,6 @@ xcm-executor = { workspace = true } # Cumulus dependencies cumulus-pallet-parachain-system = { workspace = true } -cumulus-primitives-core = { workspace = true } # ORML dependencies orml-xcm-support = { workspace = true } @@ -99,7 +98,6 @@ runtime-benchmarks = [ "frame-system/runtime-benchmarks", "sp-runtime/runtime-benchmarks", "cumulus-pallet-parachain-system/runtime-benchmarks", - "cumulus-primitives-core/runtime-benchmarks", "orml-vesting/runtime-benchmarks", "orml-tokens/runtime-benchmarks", "pallet-balances/runtime-benchmarks", diff --git a/runtime/adapters/src/lib.rs b/runtime/adapters/src/lib.rs index 5588b2db83..694559720f 100644 --- a/runtime/adapters/src/lib.rs +++ b/runtime/adapters/src/lib.rs @@ -18,7 +18,6 @@ #![cfg_attr(not(feature = "std"), no_std)] use codec::{EncodeLike, FullCodec}; -use cumulus_primitives_core::relay_chain::Hash; use frame_support::{ sp_runtime::{ traits::{AtLeast32BitUnsigned, Convert, Get, MaybeSerializeDeserialize, Saturating, Zero}, @@ -286,45 +285,6 @@ impl BlockNumberProvider for RelayChainBlockNumberProvi } } -pub trait RelayChainBlockHashProvider { - fn parent_hash() -> Option; -} -// The reason why there is difference between PROD and benchmark is that it is not possible -// to set validation data in parachain system pallet in the benchmarks. -// So for benchmarking, we mock it out and return some hardcoded parent hash -pub struct RelayChainBlockHashProviderAdapter(sp_std::marker::PhantomData); - -#[cfg(not(feature = "runtime-benchmarks"))] -impl RelayChainBlockHashProvider for RelayChainBlockHashProviderAdapter -where - Runtime: cumulus_pallet_parachain_system::Config, -{ - fn parent_hash() -> Option { - let validation_data = cumulus_pallet_parachain_system::ValidationData::::get(); - match validation_data { - Some(data) => Some(data.parent_head.hash()), - None => None, - } - } -} - -#[cfg(feature = "runtime-benchmarks")] -impl RelayChainBlockHashProvider for RelayChainBlockHashProviderAdapter -where - Runtime: cumulus_pallet_parachain_system::Config, -{ - fn parent_hash() -> Option { - // We use the same hash as for integration tests - // so the integration tests don't fail when they are run with 'runtime-benchmark' feature - let hash = [ - 14, 87, 81, 192, 38, 229, 67, 178, 232, 171, 46, 176, 96, 153, 218, 161, 209, 229, 223, 71, 119, 143, 119, - 135, 250, 171, 69, 205, 241, 47, 227, 168, - ] - .into(); - Some(hash) - } -} - /// Passes on trade and liquidity data from the omnipool to the oracle. pub struct OmnipoolHookAdapter( PhantomData<(Origin, NativeAsset, Lrna, Runtime, MC, ProtocolFeeRecipient)>, @@ -622,8 +582,8 @@ where // executed swap, under their own source. Reading that (rather than the pool's // live `slot0` price) is what keeps this provider manipulation-resistant: a // spot-price arm would make the `LastBlock` and `Short` periods identical, which - // silently disables pallet-dca's price-stability check and would let a walkable - // AMM price reach `set_route` and everything priced off a default route. + // would let a walkable AMM price reach `set_route` and everything priced off a + // default route. // A pool with no oracle history yet returns `None`, same as any cold pair. PoolType::UniswapV3(_) => { let price_result = AggregatedPriceGetter::get_price(asset_a, asset_b, period, UNISWAPV3_SOURCE); diff --git a/runtime/hydradx/Cargo.toml b/runtime/hydradx/Cargo.toml index 4c745217e1..63459a2bcf 100644 --- a/runtime/hydradx/Cargo.toml +++ b/runtime/hydradx/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-runtime" -version = "461.0.0" +version = "462.0.0" authors = ["GalacticCouncil"] edition = "2021" license = "Apache 2.0" @@ -35,7 +35,6 @@ pallet-genesis-history = { workspace = true } pallet-omnipool = { workspace = true } pallet-circuit-breaker = { workspace = true } pallet-omnipool-liquidity-mining = { workspace = true } -pallet-dca = { workspace = true } hydra-dx-math = { workspace = true } pallet-dynamic-fees = { workspace = true } pallet-dynamic-evm-fee = { workspace = true } @@ -242,7 +241,6 @@ runtime-benchmarks = [ "pallet-omnipool-liquidity-mining/runtime-benchmarks", "pallet-otc/runtime-benchmarks", "pallet-otc-settlements/runtime-benchmarks", - "pallet-dca/runtime-benchmarks", "pallet-route-executor/runtime-benchmarks", "pallet-ethereum/runtime-benchmarks", "pallet-evm/runtime-benchmarks", @@ -338,7 +336,6 @@ std = [ "pallet-omnipool/std", "pallet-circuit-breaker/std", "pallet-transaction-pause/std", - "pallet-dca/std", "pallet-ema-oracle/std", "pallet-otc/std", "pallet-otc-settlements/std", @@ -454,7 +451,6 @@ try-runtime = [ "pallet-transaction-multi-payment/try-runtime", "pallet-relaychain-info/try-runtime", "pallet-omnipool/try-runtime", - "pallet-dca/try-runtime", "pallet-collator-rewards/try-runtime", "pallet-collator-rotation/try-runtime", "pallet-genesis-history/try-runtime", diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 00bdcac49d..b99124fb2a 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -27,7 +27,6 @@ use frame_support::{ sp_runtime::traits::{One, PhantomData}, sp_runtime::{ app_crypto::sp_core::crypto::UncheckedFrom, traits::Zero, DispatchError, DispatchResult, FixedPointNumber, - Percent, }, sp_runtime::{FixedU128, Perbill, Permill}, traits::{ @@ -40,8 +39,7 @@ use frame_system::{EnsureRoot, RawOrigin}; use hydradx_adapters::{ stableswap_peg_oracle::PegOracle, AssetFeeOraclePriceProvider, EmaOraclePriceAdapter, FreezableNFT, MultiCurrencyLockedBalance, OmnipoolHookAdapter, OmnipoolRawOracleAssetVolumeProvider, OraclePriceProvider, - PriceAdjustmentAdapter, RelayChainBlockHashProvider, RelayChainBlockNumberProvider, StableswapHooksAdapter, - VestingInfo, + PriceAdjustmentAdapter, RelayChainBlockNumberProvider, StableswapHooksAdapter, VestingInfo, }; #[cfg(feature = "runtime-benchmarks")] use hydradx_traits::evm::CallContext; @@ -71,7 +69,6 @@ use pallet_omnipool::{ traits::{EnsurePriceWithin, OmnipoolHooks}, weights::WeightInfo as OmnipoolWeights, }; -use pallet_otc::NamedReserveIdentifier; use pallet_route_executor::{weights::WeightInfo as RouterWeights, AmmTradeWeights}; use pallet_stableswap::weights::WeightInfo as StableswapWeights; use sp_runtime::{traits::Verify, MultiSignature}; @@ -672,53 +669,11 @@ impl pallet_xyk_liquidity_mining::Config for Runtime { type WeightInfo = weights::pallet_xyk_liquidity_mining::HydraWeight; } -// The reason why there is difference between PROD and benchmark is that it is not possible -// to set validation data in parachain system pallet in the benchmarks. -// So for benchmarking, we mock it out and return some hardcoded parent hash -pub struct RelayChainBlockHashProviderAdapter(sp_std::marker::PhantomData); - -#[cfg(not(feature = "runtime-benchmarks"))] -impl RelayChainBlockHashProvider for RelayChainBlockHashProviderAdapter -where - Runtime: cumulus_pallet_parachain_system::Config, -{ - fn parent_hash() -> Option { - let validation_data = cumulus_pallet_parachain_system::ValidationData::::get(); - match validation_data { - Some(data) => Some(data.parent_head.hash()), - None => None, - } - } -} - -#[cfg(feature = "runtime-benchmarks")] -impl RelayChainBlockHashProvider for RelayChainBlockHashProviderAdapter -where - Runtime: cumulus_pallet_parachain_system::Config, -{ - fn parent_hash() -> Option { - None - } -} - use hydradx_traits::pools::SpotPriceProvider; -#[cfg(feature = "runtime-benchmarks")] -use hydradx_traits::PriceOracle; #[cfg(feature = "runtime-benchmarks")] use hydra_dx_math::ema::EmaPrice; -#[cfg(feature = "runtime-benchmarks")] -pub struct DummyOraclePriceProvider; -#[cfg(feature = "runtime-benchmarks")] -impl PriceOracle for DummyOraclePriceProvider { - type Price = EmaPrice; - - fn price(_route: &[Trade], _period: OraclePeriod) -> Option { - Some(EmaPrice::one()) - } -} - #[cfg(feature = "runtime-benchmarks")] pub struct DummySpotPriceProvider; #[cfg(feature = "runtime-benchmarks")] @@ -742,14 +697,7 @@ impl frame_system::offchain::SigningTypes for Runtime { } parameter_types! { - pub MinBudgetInNativeCurrency: Balance = 1000 * UNITS; - pub MaxSchedulesPerBlock: u32 = 6; - pub MaxPriceDifference: Permill = Permill::from_rational(15u32, 1000u32); - pub MaxConfigurablePriceDifference: Permill = Permill::from_percent(5); pub MinimalPeriod: u32 = 15; - pub BumpChance: Percent = Percent::from_percent(17); - pub NamedReserveId: NamedReserveIdentifier = *b"dcaorder"; - pub MaxNumberOfRetriesOnError: u8 = 3; pub ShortOraclePeriod: OraclePeriod = OraclePeriod::Short; } @@ -762,76 +710,6 @@ pub type FeePriceOracle = AssetFeeOraclePriceProvider< ShortOraclePeriod, >; -pub struct RetryOnErrorForDca; - -impl Contains for RetryOnErrorForDca { - fn contains(t: &DispatchError) -> bool { - let errors: Vec = vec![ - pallet_omnipool::Error::::AssetNotFound.into(), - pallet_omnipool::Error::::NotAllowed.into(), - // Off-by-one rounding on aToken balanceOf can trip the omnipool's - // pre-trade ensure_can_withdraw. Retry on a later block — the aave - // liquidity index is timestamp-dependent, so the rounding boundary - // shifts and a later attempt may pass. - pallet_omnipool::Error::::InsufficientBalance.into(), - // same class as dca's own retriable TradeLimitReached — erc20/aToken rounding - // can undershoot the dry-run output passed as router min limit - pallet_route_executor::Error::::TradingLimitReached.into(), - pallet_dispatcher::Error::::EvmOutOfGas.into(), - pallet_dispatcher::Error::::UniswapV3InsufficientLiquidity.into(), - pallet_circuit_breaker::Error::::DepositLimitExceededForWhitelistedAccount.into(), - ]; - errors.contains(t) - } -} - -impl pallet_dca::Config for Runtime { - type AssetId = AssetId; - type TerminateOrigin = EitherOf, EitherOf>; - type Currencies = Currencies; - type RelayChainBlockHashProvider = RelayChainBlockHashProviderAdapter; - type RandomnessProvider = DCA; - type IntentMigrator = Intent; - #[cfg(not(feature = "runtime-benchmarks"))] - type OraclePriceProvider = OraclePriceProvider; - #[cfg(feature = "runtime-benchmarks")] - type OraclePriceProvider = DummyOraclePriceProvider; - #[cfg(not(feature = "runtime-benchmarks"))] - type RouteExecutor = Router; - #[cfg(feature = "runtime-benchmarks")] - type RouteExecutor = pallet_route_executor::DummyRouter; - type RouteProvider = Router; - type MaxPriceDifferenceBetweenBlocks = MaxPriceDifference; - type MaxConfigurablePriceDifferenceBetweenBlocks = MaxConfigurablePriceDifference; - type MinimalPeriod = MinimalPeriod; - type BumpChance = BumpChance; - type MaxSchedulePerBlock = MaxSchedulesPerBlock; - type MaxNumberOfRetriesOnError = MaxNumberOfRetriesOnError; - type NativeAssetId = NativeAssetId; - type MinBudgetInNativeCurrency = MinBudgetInNativeCurrency; - type MinimumTradingLimit = MinTradingLimit; - type FeeReceiver = TreasuryAccount; - type NamedReserveId = NamedReserveId; - type WeightToFee = WeightToFee; - type AmmTradeWeights = RouterWeightInfo; - type WeightInfo = weights::pallet_dca::HydraWeight; - #[cfg(not(feature = "runtime-benchmarks"))] - type NativePriceOracle = FeePriceOracle; - #[cfg(feature = "runtime-benchmarks")] - type NativePriceOracle = AssetFeeOraclePriceProvider< - NativeAssetId, - MultiTransactionPayment, - Router, - DummyOraclePriceProvider, - MultiTransactionPayment, - ShortOraclePeriod, - >; - type RetryOnError = RetryOnErrorForDca; - type AccountFeeCurrency = MultiTransactionPayment; - type ExtraGasSupport = Dispatcher; - type GasWeightMapping = evm::FixedHydraGasWeightMapping; -} - // Provides weight info for the router. Router extrinsics can be executed with different AMMs, so we split the router weights into two parts: // the router extrinsic overhead and the AMM weight. pub struct RouterWeightInfo; @@ -966,7 +844,7 @@ impl AmmTradeWeights> for RouterWeightInfo { weight } - // Used in DCA::schedule extrinsic, which calls Router::calculate_buy_trade_amounts + // Router::calculate_buy_trade_amounts fn calculate_buy_trade_amounts_weight(route: &[Trade]) -> Weight { let mut weight = Weight::zero(); let c = 1; // number of times AMM::calculate_buy is executed @@ -999,7 +877,7 @@ impl AmmTradeWeights> for RouterWeightInfo { weight } - // Used in DCA::on_initialize for Order::Sell, which calls Router::calculate_sell_trade_amounts and Router::sell. + // Router::calculate_sell_trade_amounts and Router::sell. fn sell_and_calculate_sell_trade_amounts_weight(route: &[Trade]) -> Weight { let mut weight = Weight::zero(); let c = 1; // number of times AMM::calculate_sell is executed @@ -1031,7 +909,7 @@ impl AmmTradeWeights> for RouterWeightInfo { weight } - // Used in DCA::on_initialize for Order::Buy, which calls 2 * Router::calculate_buy_trade_amounts and Router::buy. + // 2 * Router::calculate_buy_trade_amounts and Router::buy. fn buy_and_calculate_buy_trade_amounts_weight(route: &[Trade]) -> Weight { let mut weight = Weight::zero(); let c = 3; // number of times AMM::calculate_buy is executed diff --git a/runtime/hydradx/src/benchmarking/dca.rs b/runtime/hydradx/src/benchmarking/dca.rs deleted file mode 100644 index ca373fb660..0000000000 --- a/runtime/hydradx/src/benchmarking/dca.rs +++ /dev/null @@ -1,572 +0,0 @@ -// This file is part of HydraDX-node - -// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -#![allow(unused_assignments)] // At test `on_initialize_with_empty_block` it does not recognize the assignment in the Act block - -use crate::{ - AccountId, AssetId, Balance, BlockNumber, Currencies, MaxSchedulesPerBlock, MinimalPeriod, NamedReserveId, Runtime, - DCA, XYK, -}; -use pallet_dca::ScheduleExtraGas; - -use crate::benchmarking::{register_asset, set_period, setup_accepted_external_asset}; -use frame_benchmarking::account; -use frame_benchmarking::BenchmarkError; -use frame_support::{ - assert_ok, - traits::{Hooks, Len}, - weights::Weight, - BoundedVec, -}; -use frame_system::RawOrigin; -use hydradx_traits::router::PoolType; -use hydradx_traits::router::MAX_NUMBER_OF_TRADES; -use orml_benchmarking::runtime_benchmarks; -use orml_traits::{MultiCurrency, MultiCurrencyExtended, NamedMultiReservableCurrency}; -use pallet_dca::types::{Order, Schedule, ScheduleId}; -use pallet_dca::{ScheduleIdsPerBlock, Schedules}; -use pallet_route_executor::Trade; -use scale_info::prelude::vec::Vec; -use sp_runtime::traits::ConstU32; -use sp_runtime::DispatchResult; -use sp_runtime::{DispatchError, Permill}; -use sp_std::vec; - -pub const HDX: AssetId = 0; -pub const DAI: AssetId = 2; - -pub const ONE: Balance = 1_000_000_000_000; - -// This is the sum of all "randomly" generated radiuses. -// In tests the radiuses are always the same as we use a fixed parent hash for generation, -// so it will always generate the same values -pub const DELAY_AFTER_LAST_RADIUS: u32 = 1854; - -pub const RETRY_TO_SEARCH_FOR_FREE_BLOCK: u32 = 10; - -fn minimum_schedule_period() -> BlockNumber { - MinimalPeriod::get() -} - -fn schedule_fake( - owner: AccountId, - asset_in: AssetId, - asset_out: AssetId, - amount: Balance, -) -> Schedule { - let schedule1: Schedule = Schedule { - owner, - period: minimum_schedule_period(), - total_amount: 1100 * ONE, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(15)), - order: Order::Sell { - asset_in, - asset_out, - amount_in: amount, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in, - asset_out, - }]), - }, - }; - schedule1 -} - -fn get_named_reseve_balance(token_id: AssetId, seller: AccountId) -> Balance { - Currencies::reserved_balance_named(&NamedReserveId::get(), token_id, &seller) -} - -fn schedule_buy_fake( - owner: AccountId, - asset_in: AssetId, - asset_out: AssetId, - amount: Balance, -) -> Schedule { - let schedule1: Schedule = Schedule { - owner, - period: minimum_schedule_period(), - total_amount: 2000 * ONE, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(15)), - order: Order::Buy { - asset_in, - asset_out, - amount_out: amount, - max_amount_in: Balance::MAX, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in, - asset_out, - }]), - }, - }; - schedule1 -} - -fn schedule_sell_fake( - owner: AccountId, - asset_in: AssetId, - asset_out: AssetId, - amount: Balance, -) -> Schedule { - let schedule1: Schedule = Schedule { - owner, - period: minimum_schedule_period(), - total_amount: 2000 * ONE, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(100)), - order: Order::Sell { - asset_in, - asset_out, - amount_in: amount, - min_amount_out: Balance::MIN, - route: create_bounded_vec(vec![Trade { - pool: PoolType::Omnipool, - asset_in, - asset_out, - }]), - }, - }; - schedule1 -} - -//TODO: make it global - -pub fn create_bounded_vec( - trades: Vec>, -) -> BoundedVec, ConstU32<{ pallet_route_executor::MAX_NUMBER_OF_TRADES }>> { - let bounded_vec: BoundedVec, ConstU32<{ pallet_route_executor::MAX_NUMBER_OF_TRADES }>> = - trades.try_into().unwrap(); - bounded_vec -} - -fn create_account_with_native_balance() -> Result { - let caller: AccountId = account("provider", 1, 1); - let token_amount = 200 * ONE; - >::update_balance(0u32, &caller, token_amount as i128)?; - - Ok(caller) -} - -fn fund_treasury() -> DispatchResult { - let treasury = ::FeeReceiver::get(); - >::update_balance(HDX, &treasury, 500_000_000_000_000i128)?; - - Ok(()) -} - -fn fund_treasury_with(asset: AssetId) -> DispatchResult { - let treasury = ::FeeReceiver::get(); - >::update_balance(asset, &treasury, 500_000_000_000_000i128)?; - - Ok(()) -} - -fn create_funded_account(name: &'static str, index: u32, assets: &[AssetId]) -> AccountId { - let account: AccountId = account(name, index, 0); - //Necessary to pay ED for insufficient assets. - >::update_balance( - 0, - &account, - crate::benchmarking::route_executor::INITIAL_BALANCE as i128, - ) - .unwrap(); - - for asset in assets { - assert_ok!(>::update_balance( - *asset, - &account, - INITIAL_BALANCE.try_into().unwrap(), - )); - } - account -} - -pub type MultiPaymentPallet = pallet_transaction_multi_payment::Pallet; -runtime_benchmarks! { - {Runtime, pallet_dca} - - on_initialize_with_buy_trade{ - set_period(1000); - - let amount_buy = 200 * ONE; - - let asset_in = HDX; - - let seller: AccountId = create_funded_account("seller", 3, &[asset_in]); - let other_seller: AccountId = create_funded_account("seller", 3, &[asset_in]); - - //Fund treasury with some HDX to prevent BelowMinimum issue due to low fee - fund_treasury()?; - fund_treasury_with(asset_in)?; - - let schedule1 = schedule_buy_fake(seller.clone(), asset_in, DAI, amount_buy); - let schedule_2 = schedule_buy_fake(seller.clone(), HDX, DAI, amount_buy); - let execution_block = 1005u32; - - let schedule_id = DCA::next_schedule_id() + 1; - assert_ok!(DCA::schedule(RawOrigin::Signed(seller.clone()).into(), schedule1.clone(), Option::Some(execution_block))); - ScheduleExtraGas::::insert(schedule_id, 1_000_000);//We add some extra gas to make sure we cover the worst case - - assert_eq!(Currencies::free_balance(DAI, &seller),0); - let reserved_balance = get_named_reseve_balance(asset_in, seller.clone()); - - let init_reserved_balance = 2000 * ONE; - assert_eq!(init_reserved_balance, reserved_balance); - - assert_eq!(Currencies::free_balance(DAI, &seller), 0); - - //Make sure that we have other schedules planned in the block where the benchmark schedule is planned, leading to worst case - //We leave only one slot - let schedule_period = minimum_schedule_period(); - let next_block_to_replan = execution_block + schedule_period; - let number_of_all_schedules = MaxSchedulesPerBlock::get() + MaxSchedulesPerBlock::get() * RETRY_TO_SEARCH_FOR_FREE_BLOCK - 1; - for i in 0..number_of_all_schedules { - assert_ok!(DCA::schedule(RawOrigin::Signed(other_seller.clone()).into(), schedule_2.clone(), Option::Some(next_block_to_replan))); - } - - assert_eq!((MaxSchedulesPerBlock::get() - 1) as usize, >::get::(next_block_to_replan + DELAY_AFTER_LAST_RADIUS).len()); - }: { - DCA::on_initialize(execution_block); - } - verify { - assert_eq!((MaxSchedulesPerBlock::get()) as usize, >::get::(next_block_to_replan + DELAY_AFTER_LAST_RADIUS).len()); - } - - on_initialize_with_sell_trade{ - set_period(1000); - let seller: AccountId = account("seller", 3, 1); - let other_seller: AccountId = account("seller", 3, 1); - - let amount_sell = 100 * ONE; - - >::update_balance(HDX, &seller, 20_000_000_000_000_000i128)?; - >::update_balance(HDX, &other_seller, 20_000_000_000_000_000_000_000i128)?; - fund_treasury()?; //Fund treasury with some HDX to prevent BelowMinimum issue due to low fee - - fund_treasury()?; //Fund treasury with some HDX to prevent BelowMinimum issue due to low fee - let schedule1 = schedule_sell_fake(seller.clone(), HDX, DAI, amount_sell); - let execution_block = 1005u32; - - let schedule_id = DCA::next_schedule_id() + 1; - assert_ok!(DCA::schedule(RawOrigin::Signed(seller.clone()).into(), schedule1.clone(), Option::Some(execution_block))); - ScheduleExtraGas::::insert(schedule_id, 1_000_000); - - assert_eq!(Currencies::free_balance(DAI, &seller),0); - let reserved_balance = get_named_reseve_balance(HDX, seller.clone()); - - let init_reserved_balance = 2000 * ONE; - assert_eq!(init_reserved_balance, reserved_balance); - - assert_eq!(Currencies::free_balance(DAI, &seller), 0); - - //Make sure that we have other schedules planned in the block where the benchmark schedule is planned, leading to worst case - //We leave only one slot - let schedule_period = minimum_schedule_period(); - let next_block_to_replan = execution_block + schedule_period; - let number_of_all_schedules = MaxSchedulesPerBlock::get() + MaxSchedulesPerBlock::get() * RETRY_TO_SEARCH_FOR_FREE_BLOCK - 1; - for i in 0..number_of_all_schedules { - assert_ok!(DCA::schedule(RawOrigin::Signed(other_seller.clone()).into(), schedule1.clone(), Option::Some(next_block_to_replan))); - } - assert_eq!((MaxSchedulesPerBlock::get() - 1) as usize, >::get::(next_block_to_replan + DELAY_AFTER_LAST_RADIUS).len()); - }: { - DCA::on_initialize(execution_block); - } - verify { - assert_eq!((MaxSchedulesPerBlock::get()) as usize, >::get::(next_block_to_replan + DELAY_AFTER_LAST_RADIUS).len()); - } - - on_initialize_with_empty_block{ - let seller: AccountId = account("seller", 3, 1); - fund_treasury()?; //Fund treasury with some HDX to prevent BelowMinimum issue due to low fee - - let execution_block = 100u32; - assert_eq!(DCA::schedules::(execution_block), None); - let r = DCA::schedules::(execution_block); - let mut weight = Weight::zero(); - }: { - weight = DCA::on_initialize(execution_block); - } - verify { - assert!(weight.ref_time() > 0u64); - } - - - schedule{ - let caller: AccountId = create_account_with_native_balance()?; - fund_treasury()?; //Fund treasury with some HDX to prevent BelowMinimum issue due to low fee - - let asset_in = setup_accepted_external_asset()?; - fund_treasury_with(asset_in)?; - - let asset_1 = asset_in; - let asset_2 = register_asset(b"AS2".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - let asset_3 = register_asset(b"AS3".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - let asset_4 = register_asset(b"AS4".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - let asset_5 = register_asset(b"AS5".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - let asset_6 = register_asset(b"AS6".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - let asset_7 = register_asset(b"AS7".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - let asset_8 = register_asset(b"AS8".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - let asset_9 = register_asset(b"AS9".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - create_xyk_pool(asset_1, asset_2); - create_xyk_pool(asset_2, asset_3); - create_xyk_pool(asset_3, asset_4); - create_xyk_pool(asset_4, asset_5); - create_xyk_pool(asset_5, asset_6); - create_xyk_pool(asset_6, asset_7); - create_xyk_pool(asset_7, asset_8); - create_xyk_pool(asset_8, asset_9); - create_xyk_pool(asset_9, HDX); - - set_period(minimum_schedule_period()); - - let route = vec![ - Trade { - pool: PoolType::XYK, - asset_in: asset_1, - asset_out: asset_2, - }, - Trade { - pool: PoolType::XYK, - asset_in: asset_2, - asset_out: asset_3, - }, - Trade { - pool: PoolType::XYK, - asset_in: asset_3, - asset_out: asset_4, - }, - Trade { - pool: PoolType::XYK, - asset_in: asset_4, - asset_out: asset_5, - }, - Trade { - pool: PoolType::XYK, - asset_in: asset_5, - asset_out: asset_6, - }, - Trade { - pool: PoolType::XYK, - asset_in: asset_6, - asset_out: asset_7, - }, - Trade { - pool: PoolType::XYK, - asset_in: asset_7, - asset_out: asset_8, - }, - Trade { - pool: PoolType::XYK, - asset_in: asset_8, - asset_out: asset_9, - }, - Trade { - pool: PoolType::XYK, - asset_in: asset_9, - asset_out: HDX, - } - ]; - - assert_eq!(route.len(),MAX_NUMBER_OF_TRADES as usize, "Route length should be as big as max number of trades allowed"); - - >::update_balance(HDX, &caller, 100_000_000_000_000_000_000_000i128)?; - >::update_balance(asset_1, &caller, 100_000_000_000_000_000_000_000i128)?; - let amount_sell = 200 * ONE; - - let schedule1: Schedule = Schedule { - owner:caller.clone() , - period: minimum_schedule_period(), - total_amount: 1100 * ONE, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(15)), - order: Order::Sell { - asset_in: asset_1, - asset_out: DAI, - amount_in: amount_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(route), - }, - }; - - let execution_block = 105u32; - - //We fill blocks with schedules leaving only one place - let schedule_2 = schedule_fake(caller.clone(), HDX, DAI, amount_sell); - let number_of_all_schedules = MaxSchedulesPerBlock::get() + MaxSchedulesPerBlock::get() * RETRY_TO_SEARCH_FOR_FREE_BLOCK - 1; - for i in 0..number_of_all_schedules { - assert_ok!(DCA::schedule(RawOrigin::Signed(caller.clone()).into(), schedule_2.clone(), Option::Some(execution_block))); - } - - let schedule_id : ScheduleId = number_of_all_schedules; - - assert_eq!((MaxSchedulesPerBlock::get() - 1) as usize, >::get::(execution_block + DELAY_AFTER_LAST_RADIUS).len()); - - }: _(RawOrigin::Signed(caller.clone()), schedule1, Option::Some(execution_block)) - verify { - assert!(>::get::(schedule_id).is_some()); - - assert_eq!((MaxSchedulesPerBlock::get()) as usize, >::get::(execution_block + DELAY_AFTER_LAST_RADIUS).len()); - } - - terminate { - let caller: AccountId = create_account_with_native_balance()?; - fund_treasury()?; //Fund treasury with some HDX to prevent BelowMinimum issue due to low fee - - >::update_balance(HDX, &caller, 100_000_000_000_000_000i128)?; - - let amount_sell = 200 * ONE; - let schedule1 = schedule_fake(caller.clone(), HDX, DAI, amount_sell); - - set_period(99); - - let execution_block = 105u32; - - // Fill block with MaxSchedulesPerBlock schedules to test worst case for linear search - for _ in 0..MaxSchedulesPerBlock::get() { - assert_ok!(DCA::schedule(RawOrigin::Signed(caller.clone()).into(), schedule1.clone(), Option::Some(execution_block))); - } - - // Terminate the last schedule which is at the last index in ScheduleIdsPerBlock - // This is worst case for linear search - must iterate through all elements - let schedule_id: ScheduleId = MaxSchedulesPerBlock::get() - 1; - ScheduleExtraGas::::insert(schedule_id, 1_000_000); - - }: _(RawOrigin::Root, schedule_id, None) - verify { - assert!(>::get::(schedule_id).is_none()); - assert_eq!((MaxSchedulesPerBlock::get() - 1) as usize, >::get::(execution_block).len()); - } - - unlock_reserves { - let caller: AccountId = create_account_with_native_balance()?; - fund_treasury()?; //Fund treasury with some HDX to prevent BelowMinimum issue due to low fee - - >::update_balance(HDX, &caller.clone(), 100_000_000_000_000_000i128)?; - - >::reserve_named( - &NamedReserveId::get(), - HDX, - &caller.clone(), - ONE - )?; - }: _(RawOrigin::Signed(caller.clone()), caller.clone(), HDX) - verify { - let reserved_balance = >::reserved_balance_named( - &NamedReserveId::get(), - HDX, - &caller.clone(), - ); - - assert_eq!(reserved_balance, 0); - } - - set_migration_enabled { - assert!(!DCA::migration_enabled()); - }: _(RawOrigin::Root, true) - verify { - assert!(DCA::migration_enabled()); - } - -} - -pub const INITIAL_BALANCE: Balance = 10_000_000 * ONE; - -pub fn create_xyk_pool(asset_a: u32, asset_b: u32) { - let caller: AccountId = create_funded_account("caller", 0, &[asset_a, asset_b]); - - assert_ok!(Currencies::update_balance( - RawOrigin::Root.into(), - caller.clone(), - 0, - 10 * ONE as i128, - )); - - let amount = 100000 * ONE; - assert_ok!(Currencies::update_balance( - RawOrigin::Root.into(), - caller.clone(), - asset_a, - amount as i128, - )); - - assert_ok!(Currencies::update_balance( - RawOrigin::Root.into(), - caller.clone(), - asset_b, - amount as i128, - )); - - assert_ok!(XYK::create_pool( - RawOrigin::Signed(caller.clone()).into(), - asset_a, - amount, - asset_b, - amount, - )); - - assert_ok!(XYK::sell( - RawOrigin::Signed(caller).into(), - asset_a, - asset_b, - 10 * ONE, - 0u128, - false, - )); -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::NativeExistentialDeposit; - use orml_benchmarking::impl_benchmark_test_suite; - use sp_runtime::BuildStorage; - - fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default() - .build_storage() - .unwrap(); - - pallet_asset_registry::GenesisConfig:: { - registered_assets: vec![( - Some(DAI), - Some(b"DAI".to_vec().try_into().unwrap()), - 1_000u128, - None, - None, - None, - false, - )], - native_asset_name: b"HDX".to_vec().try_into().unwrap(), - native_existential_deposit: NativeExistentialDeposit::get(), - native_decimals: 12, - native_symbol: b"HDX".to_vec().try_into().unwrap(), - } - .assimilate_storage(&mut t) - .unwrap(); - - sp_io::TestExternalities::new(t) - } - - impl_benchmark_test_suite!(new_test_ext(),); -} diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index 4f089ddddc..8fcff4f8b7 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -1,7 +1,6 @@ #![cfg(feature = "runtime-benchmarks")] pub mod currencies; -pub mod dca; pub mod duster; pub mod dynamic_evm_fee; pub mod ema_oracle; @@ -183,7 +182,7 @@ pub fn set_period(to: u32) { fn setup_accepted_external_asset() -> Result { let asset = register_external_asset(b"FCA".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - crate::benchmarking::dca::MultiPaymentPallet::::add_currency( + pallet_transaction_multi_payment::Pallet::::add_currency( RawOrigin::Root.into(), asset, FixedU128::from(1), diff --git a/runtime/hydradx/src/benchmarking/route_executor.rs b/runtime/hydradx/src/benchmarking/route_executor.rs index 2d53bc62f1..bca122c5f2 100644 --- a/runtime/hydradx/src/benchmarking/route_executor.rs +++ b/runtime/hydradx/src/benchmarking/route_executor.rs @@ -23,7 +23,6 @@ use crate::{ }; use super::*; -use crate::benchmarking::dca::{DAI, HDX}; use crate::Omnipool; use frame_benchmarking::{account, BenchmarkError}; use frame_support::dispatch::DispatchResult; @@ -40,6 +39,9 @@ use primitives::constants::currency::UNITS; use primitives::BlockNumber; use sp_std::vec; +const HDX: AssetId = 0; +const DAI: AssetId = 2; + pub const INITIAL_BALANCE: Balance = 10_000_000 * UNITS; fn funded_account(name: &'static str, index: u32, assets: &[AssetId]) -> AccountId { diff --git a/runtime/hydradx/src/evm/erc20_currency.rs b/runtime/hydradx/src/evm/erc20_currency.rs index bdee19cf0b..75528a3104 100644 --- a/runtime/hydradx/src/evm/erc20_currency.rs +++ b/runtime/hydradx/src/evm/erc20_currency.rs @@ -21,7 +21,7 @@ use sp_runtime::{DispatchError, SaturatedConversion}; use sp_std::vec::Vec; /// Execution gas limit. -const GAS_LIMIT: u64 = 400_000; +pub(crate) const GAS_LIMIT: u64 = 400_000; #[module_evm_utility_macro::generate_function_selector] #[derive(RuntimeDebug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive)] diff --git a/runtime/hydradx/src/evm/mod.rs b/runtime/hydradx/src/evm/mod.rs index 34a4a96e08..2b29b57058 100644 --- a/runtime/hydradx/src/evm/mod.rs +++ b/runtime/hydradx/src/evm/mod.rs @@ -52,7 +52,7 @@ use sp_core::{crypto::AccountId32, Get, U256}; pub mod aave_trade_executor; mod accounts_conversion; -mod erc20_currency; +pub(crate) mod erc20_currency; pub mod event_logs; pub mod evm_error_decoder; mod evm_fee; diff --git a/runtime/hydradx/src/evm/uniswap_v3_trade_executor.rs b/runtime/hydradx/src/evm/uniswap_v3_trade_executor.rs index 2bd3398614..566ebb6f1d 100644 --- a/runtime/hydradx/src/evm/uniswap_v3_trade_executor.rs +++ b/runtime/hydradx/src/evm/uniswap_v3_trade_executor.rs @@ -441,9 +441,8 @@ where /// Report an executed swap to the EMA oracle under `UNISWAPV3_SOURCE`. /// /// Without this a v3 pool has no oracle history at all, and every consumer of - /// `OraclePriceProvider` treats that as a hard failure: `pallet-dca` reads it as - /// "price unstable" and terminates the schedule after its retries, and - /// `route-executor::set_route` rejects the route with `RouteHasNoOracle`. + /// `OraclePriceProvider` treats that as a hard failure: `route-executor::set_route` + /// rejects the route with `RouteHasNoOracle`. /// /// Called after the swap has settled, so `slot0` and both balances are post-trade — /// matching what pallet-xyk reports. Errors propagate: `Router::sell`/`buy` are @@ -459,16 +458,16 @@ where // The oracle DISCARDS entries for pairs it does not track, and returns `Ok` doing // it (see `pallet_ema_oracle::Pallet::on_entry` — internal sources take that // branch, and `UNISWAPV3_SOURCE` is one). So a swap on an untracked pair looks - // entirely successful while leaving the pool unpriceable: DCA keeps reporting - // `PriceUnstable` and `set_route` keeps rejecting the route, with no error, event - // or log anywhere to explain it. We do not fail the trade over this — the swap - // itself is legitimate — but the lost receipt must not be silent. + // entirely successful while leaving the pool unpriceable: `set_route` keeps + // rejecting the route, with no error, event or log anywhere to explain it. We do + // not fail the trade over this — the swap itself is legitimate — but the lost + // receipt must not be silent. let pair = ordered_pair(asset_in, asset_out); if !::OracleWhitelist::contains(&(UNISWAPV3_SOURCE, pair.0, pair.1)) { log::warn!( target: "uniswapv3", "pair ({}, {}) is not oracle-whitelisted: this trade will not be recorded, so \ - DCA and set_route through this pool will keep failing. Fix with \ + set_route through this pool will keep failing. Fix with \ emaOracle.add_oracle(UNISWAPV3_SOURCE, ({}, {})), or check both assets are sufficient.", pair.0, pair.1, pair.0, pair.1 ); diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index 04f13a10c5..bc570f986d 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -29,7 +29,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); mod tests; mod benchmarking; -mod migrations; +pub mod migrations; pub mod weights; mod assets; @@ -133,7 +133,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: Cow::Borrowed("hydradx"), impl_name: Cow::Borrowed("hydradx"), authoring_version: 1, - spec_version: 461, + spec_version: 462, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -229,9 +229,7 @@ construct_runtime!( XYKWarehouseLM: warehouse_liquidity_mining:: = 96, RelayChainInfo: pallet_relaychain_info = 201, - //NOTE: DCA pallet should be declared before ParachainSystem pallet, - //otherwise there is no data about relay chain parent hash - DCA: pallet_dca = 66, + // NOTE 66 is retired (was used by DCA), must not be reused //NOTE: Scheduler must be before ParachainSystem otherwise RelayChainBlockNumberProvider //will return 0 as current block number when used with Scheduler(democracy). Scheduler: pallet_scheduler = 5, @@ -385,7 +383,6 @@ mod benches { [pallet_duster, benchmarking::duster::Benchmark] [pallet_omnipool, benchmarking::omnipool::Benchmark] [pallet_route_executor, benchmarking::route_executor::Benchmark] - [pallet_dca, benchmarking::dca::Benchmark] [pallet_fee_processor, benchmarking::fee_processor::Benchmark] [pallet_xyk, benchmarking::xyk::Benchmark] [pallet_dynamic_evm_fee, benchmarking::dynamic_evm_fee::Benchmark] diff --git a/runtime/hydradx/src/migrations/dca.rs b/runtime/hydradx/src/migrations/dca.rs new file mode 100644 index 0000000000..571c28cc0f --- /dev/null +++ b/runtime/hydradx/src/migrations/dca.rs @@ -0,0 +1,395 @@ +// Copyright (C) 2020-2026 Intergalactic, Limited (GIB). +// SPDX-License-Identifier: Apache-2.0 + +//! Retires legacy DCA (`DCA`, index 66): schedules become DCA intents or are refunded, `dcaorder` +//! reserves are released and the `DCA` prefix is cleared. The pallet crate is gone, so the old +//! storage is read through aliases. + +use crate::evm::erc20_currency::GAS_LIMIT as ERC20_GAS_LIMIT; +use crate::{AccountId, AssetRegistry, Balance, Currencies, Dispatcher, Intent, Runtime}; +use codec::{Decode, Encode}; +use frame_support::{ + storage::{unhashed, with_transaction, KeyPrefixIterator}, + storage_alias, + traits::OnRuntimeUpgrade, + weights::Weight, + Blake2_128Concat, +}; +use hydradx_traits::{evm::ExtraGasSupport, router::Trade, BoundErc20}; +use ice_support::DcaParams; +use orml_traits::NamedMultiReservableCurrency; +use pallet_evm::GasWeightMapping; +use pallet_transaction_pause::{BoundedName, PausedTransactions}; +use primitives::AssetId; +use sp_runtime::{DispatchError, Permill, TransactionOutcome}; +use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet}; +use sp_std::vec::Vec; + +pub const DCA_RESERVE_ID: [u8; 8] = *b"dcaorder"; +/// Above this the migration aborts; mainnet holds about half. +pub const MAX_SCHEDULES: usize = 30; +pub const MAX_DCA_KEYS: u32 = 1_000; +/// Upper estimate for one entry's key, value and trie nodes. +const PROOF_SIZE_PER_READ: u64 = 512; +/// Legacy `MaxPriceDifferenceBetweenBlocks`, applied when a schedule set no slippage. +const DEFAULT_SLIPPAGE: Permill = Permill::from_parts(15_000); +/// Moving an indebted owner's aToken runs Aave's health-factor check: ~600k gas against the 400k limit. +const EXTRA_GAS: u64 = 1_000_000; +const LOG_TARGET: &str = "runtime::migration"; + +#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] +pub struct LegacySchedule { + pub owner: AccountId, + pub period: u32, + pub total_amount: Balance, + pub max_retries: Option, + pub stability_threshold: Option, + pub slippage: Option, + pub order: LegacyOrder, +} + +// `Vec` where legacy had `BoundedVec`: same encoding, and an over-bound value still decodes. +#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] +pub enum LegacyOrder { + Sell { + asset_in: AssetId, + asset_out: AssetId, + amount_in: Balance, + min_amount_out: Balance, + route: Vec>, + }, + Buy { + asset_in: AssetId, + asset_out: AssetId, + amount_out: Balance, + max_amount_in: Balance, + route: Vec>, + }, +} + +impl LegacyOrder { + fn asset_in(&self) -> AssetId { + match self { + LegacyOrder::Sell { asset_in, .. } | LegacyOrder::Buy { asset_in, .. } => *asset_in, + } + } +} + +#[storage_alias(verbatim)] +pub type Schedules = StorageMap; + +#[storage_alias(verbatim)] +pub type RemainingAmounts = StorageMap; + +/// What legacy `on_initialize` executed from. +#[storage_alias(verbatim)] +pub type ScheduleIdsPerBlock = StorageMap>; + +pub struct MigrateDcaToIntents; + +#[derive(Default)] +struct Meter { + reads: u64, + writes: u64, + gas: u64, +} + +impl MigrateDcaToIntents { + fn migrate(meter: &mut Meter) { + let mut schedules: Vec<_> = Schedules::iter().take(MAX_SCHEDULES + 1).collect(); + meter.reads += schedules.len() as u64; + if schedules.len() > MAX_SCHEDULES { + log::error!(target: LOG_TARGET, "DCA retirement aborted: more than {MAX_SCHEDULES} schedules, nothing changed"); + return; + } + let planned_blocks: Vec<_> = ScheduleIdsPerBlock::iter().take(MAX_SCHEDULES + 1).collect(); + meter.reads += planned_blocks.len() as u64; + if planned_blocks.len() > MAX_SCHEDULES { + log::error!(target: LOG_TARGET, "DCA retirement aborted: more than {MAX_SCHEDULES} planned blocks, nothing changed"); + return; + } + let prefix = sp_io::hashing::twox_128(b"DCA").to_vec(); + let dca_keys = KeyPrefixIterator::new(prefix.clone(), prefix, |_| Ok(())) + .take(MAX_DCA_KEYS as usize + 1) + .count(); + meter.reads += dca_keys as u64; + if dca_keys > MAX_DCA_KEYS as usize { + log::error!(target: LOG_TARGET, "DCA retirement aborted: more than {MAX_DCA_KEYS} DCA keys, nothing changed"); + return; + } + + let mut planned = BTreeMap::::new(); + for (block, ids) in planned_blocks { + for id in ids { + planned.entry(id).and_modify(|b| *b = (*b).min(block)).or_insert(block); + } + } + + let legacy: BTreeSet<_> = schedules + .iter() + .map(|(_, schedule)| (schedule.owner.clone(), schedule.order.asset_in())) + .collect(); + schedules.sort_by_key(|(id, _)| *id); + for (id, schedule) in schedules { + Self::migrate_schedule(id, &schedule, planned.get(&id).copied(), meter); + // The `Schedules` entry stays, so a re-run sees an orphan and still retries its reserve. + RemainingAmounts::remove(id); + meter.writes += 1; + } + + if !Self::release_legacy_reserves(legacy, meter) { + log::error!(target: LOG_TARGET, "DCA retirement not finalised: dcaorder reserves may remain, run the migration again"); + return; + } + + PausedTransactions::::remove(dca_pause_key()); + meter.writes += 1; + + let cleared = unhashed::clear_prefix(&sp_io::hashing::twox_128(b"DCA"), Some(MAX_DCA_KEYS), None); + meter.writes += cleared.unique as u64; + if cleared.maybe_cursor.is_some() { + log::error!(target: LOG_TARGET, "DCA keys remain after removing {MAX_DCA_KEYS}, run the migration again"); + } + log::info!(target: LOG_TARGET, "DCA retired: {} keys removed", cleared.unique); + } + + fn migrate_schedule(id: u32, schedule: &LegacySchedule, planned: Option, meter: &mut Meter) { + meter.reads += 1; + let Some(remaining) = RemainingAmounts::get(id) else { + log::info!(target: LOG_TARGET, "DCA schedule {id}: orphan without remaining amount, skipped"); + return; + }; + + let LegacyOrder::Sell { + asset_in, + asset_out, + amount_in, + min_amount_out, + .. + } = schedule.order + else { + return Self::cancel(id, schedule, remaining, "buy order", meter); + }; + let budget = (schedule.total_amount != 0).then_some(remaining); + if budget.is_some() && remaining < amount_in { + return Self::cancel(id, schedule, remaining, "budget below one trade", meter); + } + let params = DcaParams { + asset_in, + asset_out, + amount_in, + amount_out: min_amount_out, + slippage: schedule.slippage.unwrap_or(DEFAULT_SLIPPAGE), + budget, + period: schedule.period, + }; + // A schedule planned at P traded in P; an intent offered at P - 1 settles in P. + let first_eligible = planned.map_or(0, |block| block.saturating_sub(1)); + + let (result, extra_gas) = Self::with_extra_gas(asset_in, 2, meter, || { + let left = Currencies::unreserve_named(&DCA_RESERVE_ID, asset_in, &schedule.owner, remaining); + if left != 0 { + return Err(DispatchError::Other("legacy reserve below remaining amount")); + } + Intent::do_add_migrated_intent(schedule.owner.clone(), params, first_eligible) + }); + match result { + Ok(intent_id) => { + meter.reads += 8; + meter.writes += 8; + log::info!(target: LOG_TARGET, "DCA schedule {id} -> intent {intent_id} (extra gas used: {extra_gas})"); + } + Err(error) => Self::cancel(id, schedule, remaining, error, meter), + } + } + + fn cancel( + id: u32, + schedule: &LegacySchedule, + remaining: Balance, + reason: impl core::fmt::Debug, + meter: &mut Meter, + ) { + let asset = schedule.order.asset_in(); + let (left, extra_gas) = Self::with_extra_gas(asset, 1, meter, || { + Ok(Currencies::unreserve_named( + &DCA_RESERVE_ID, + asset, + &schedule.owner, + remaining, + )) + }); + let refunded = remaining.saturating_sub(left.unwrap_or(remaining)); + log::info!(target: LOG_TARGET, "DCA schedule {id} cancelled ({reason:?}): refunded {refunded} of asset {asset} (extra gas used: {extra_gas})"); + } + + /// Returns whether every `dcaorder` reserve was released. + fn release_legacy_reserves(legacy: BTreeSet<(AccountId, AssetId)>, meter: &mut Meter) -> bool { + let mut clean = true; + for (owner, asset) in legacy { + meter.reads += 1; + let reserved = Currencies::reserved_balance_named(&DCA_RESERVE_ID, asset, &owner); + if reserved == 0 { + continue; + } + let (left, _) = Self::with_extra_gas(asset, 1, meter, || { + Ok(Currencies::unreserve_named(&DCA_RESERVE_ID, asset, &owner, reserved)) + }); + let left = left.unwrap_or(reserved); + if left != 0 { + clean = false; + log::error!(target: LOG_TARGET, "DCA reserve could not be released: {left} of asset {asset} stays reserved under dcaorder for {owner:?}"); + } + } + clean + } + + /// Runs `f` in a storage layer with `EXTRA_GAS`; the gas used is read before a rollback erases it. + fn with_extra_gas( + asset: AssetId, + evm_calls: u64, + meter: &mut Meter, + f: impl FnOnce() -> Result, + ) -> (Result, u64) { + if AssetRegistry::contract_address(asset).is_some() { + meter.gas += evm_calls * ERC20_GAS_LIMIT; + } + Dispatcher::set_extra_gas(EXTRA_GAS); + let mut extra_used = 0; + let result = with_transaction(|| { + let result = f(); + extra_used = EXTRA_GAS.saturating_sub(Dispatcher::extra_gas()); + if result.is_ok() { + TransactionOutcome::Commit(result) + } else { + TransactionOutcome::Rollback(result) + } + }); + Dispatcher::clear_extra_gas(); + meter.gas += extra_used; + meter.reads += 6; + meter.writes += 6; + (result, extra_used) + } +} + +impl OnRuntimeUpgrade for MigrateDcaToIntents { + fn on_runtime_upgrade() -> Weight { + let mut meter = Meter::default(); + Self::migrate(&mut meter); + let weight = ::DbWeight::get() + .reads_writes(meter.reads, meter.writes) + .saturating_add(::GasWeightMapping::gas_to_weight( + meter.gas, false, + )) + .saturating_add(Weight::from_parts(0, meter.reads.saturating_mul(PROOF_SIZE_PER_READ))); + log::info!(target: LOG_TARGET, "DCA retirement weight: {weight:?} (gas charged: {})", meter.gas); + weight + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + let current = frame_system::Pallet::::block_number(); + let mut planned = BTreeMap::::new(); + for (block, ids) in ScheduleIdsPerBlock::iter() { + for id in ids { + planned.entry(id).and_modify(|b| *b = (*b).min(block)).or_insert(block); + } + } + let convertible: Vec = Schedules::iter() + .filter_map(|(id, schedule)| { + let remaining = RemainingAmounts::get(id)?; + let LegacyOrder::Sell { + asset_in, + asset_out, + amount_in, + .. + } = schedule.order + else { + return None; + }; + let rolling = schedule.total_amount == 0; + if !rolling && remaining < amount_in { + return None; + } + let first_eligible = planned.get(&id).map_or(0, |block| block.saturating_sub(1)); + Some(( + schedule.owner, + asset_in, + asset_out, + amount_in, + (!rolling).then_some(remaining), + current.max(first_eligible).saturating_sub(schedule.period), + )) + }) + .collect(); + let intents: Vec = pallet_intent::Intents::::iter_keys().collect(); + Ok((intents, convertible).encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(state: Vec) -> Result<(), sp_runtime::TryRuntimeError> { + use frame_support::ensure; + let (before, mut convertible) = <(Vec, Vec)>::decode(&mut &state[..]) + .map_err(|_| "invalid DCA migration snapshot")?; + + ensure!( + !unhashed::contains_prefixed_key(&sp_io::hashing::twox_128(b"DCA")), + "DCA storage remains" + ); + ensure!( + !pallet_balances::Reserves::::iter_values() + .any(|reserves| reserves.iter().any(|r| r.id == DCA_RESERVE_ID && r.amount > 0)), + "native balance still reserved under dcaorder" + ); + ensure!( + !orml_tokens::Reserves::::iter_values() + .any(|reserves| reserves.iter().any(|r| r.id == DCA_RESERVE_ID && r.amount > 0)), + "token balance still reserved under dcaorder" + ); + ensure!( + !PausedTransactions::::contains_key(dca_pause_key()), + "DCA schedule is still paused" + ); + + let mut converted = 0usize; + for (id, intent) in pallet_intent::Intents::::iter() { + if before.contains(&id) { + continue; + } + let ice_support::IntentData::Dca(dca) = intent.data else { + return Err("migration created a non-DCA intent".into()); + }; + let owner = Intent::intent_owner(id).ok_or("intent without owner")?; + let key = ( + owner, + dca.asset_in, + dca.asset_out, + dca.amount_in, + dca.budget, + dca.last_execution_block, + ); + let index = convertible + .iter() + .position(|expected| *expected == key) + .ok_or("intent does not match a convertible schedule")?; + convertible.swap_remove(index); + converted += 1; + } + for (owner, asset_in, ..) in &convertible { + log::warn!(target: LOG_TARGET, "convertible DCA schedule of {owner:?} selling {asset_in} was cancelled instead"); + } + log::info!(target: LOG_TARGET, "DCA retirement created {converted} intents, one per converted schedule"); + Ok(()) + } +} + +fn dca_pause_key() -> (BoundedName, BoundedName) { + ( + BoundedName::truncate_from(b"DCA".to_vec()), + BoundedName::truncate_from(b"schedule".to_vec()), + ) +} + +#[cfg(feature = "try-runtime")] +type Expected = (AccountId, AssetId, AssetId, Balance, Option, u32); diff --git a/runtime/hydradx/src/migrations/mod.rs b/runtime/hydradx/src/migrations/mod.rs index 8f34eb331a..447fb9399f 100644 --- a/runtime/hydradx/src/migrations/mod.rs +++ b/runtime/hydradx/src/migrations/mod.rs @@ -17,6 +17,7 @@ use crate::Runtime; pub mod circuit_breaker; pub mod conviction_voting; +pub mod dca; pub mod democracy; pub mod dynamic_fees; pub mod referenda; @@ -24,7 +25,7 @@ pub mod scheduler; pub mod stableswap; // New migrations which need to be cleaned up after every Runtime upgrade -pub type UnreleasedSingleBlockMigrations = (democracy::RemoveDemocracy,); +pub type UnreleasedSingleBlockMigrations = (dca::MigrateDcaToIntents,); // These migrations can run on every runtime upgrade pub type PermanentSingleBlockMigrations = pallet_xcm::migration::MigrateToLatestXcmVersion; diff --git a/runtime/hydradx/src/weights/mod.rs b/runtime/hydradx/src/weights/mod.rs index 3c16e5a76a..0c344f66fd 100644 --- a/runtime/hydradx/src/weights/mod.rs +++ b/runtime/hydradx/src/weights/mod.rs @@ -15,7 +15,6 @@ pub mod pallet_collective_council; pub mod pallet_collective_technical_committee; pub mod pallet_conviction_voting; pub mod pallet_currencies; -pub mod pallet_dca; pub mod pallet_dispatcher; pub mod pallet_dispenser; pub mod pallet_duster; diff --git a/runtime/hydradx/src/weights/pallet_dca.rs b/runtime/hydradx/src/weights/pallet_dca.rs deleted file mode 100644 index 130f5b774b..0000000000 --- a/runtime/hydradx/src/weights/pallet_dca.rs +++ /dev/null @@ -1,232 +0,0 @@ -// This file is part of HydraDX. - -// Copyright (C) 2020-2024 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - -//! Autogenerated weights for `pallet_dca` -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 49.1.0 -//! DATE: 2026-10-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `None`, DB CACHE: `1024` - -// Executed Command: -// ./target/release/hydradx -// benchmark -// pallet -// --wasm-execution=compiled -// --pallet -// pallet_dca -// --extrinsic -// * -// --heap-pages -// 4096 -// --steps -// 50 -// --repeat -// 20 -// --template -// scripts/pallet-weight-template.hbs -// --output -// runtime/hydradx/src/weights/pallet_dca.rs -// --quiet - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(missing_docs)] - -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; -use core::marker::PhantomData; -use crate::*; - -/// Weights for `pallet_dca`. -pub struct WeightInfo(PhantomData); - -/// Weights for `pallet_dca` using the HydraDX node and recommended hardware. -pub struct HydraWeight(PhantomData); -impl pallet_dca::WeightInfo for HydraWeight { - /// Storage: `DCA::ScheduleIdsPerBlock` (r:12 w:2) - /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(45), added: 2520, mode: `MaxEncodedLen`) - /// Storage: `DCA::MigrationEnabled` (r:1 w:0) - /// Proof: `DCA::MigrationEnabled` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) - /// Storage: `DCA::Schedules` (r:1 w:0) - /// Proof: `DCA::Schedules` (`max_values`: None, `max_size`: Some(243), added: 2718, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleExtraGas` (r:1 w:0) - /// Proof: `DCA::ScheduleExtraGas` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) - /// Storage: `DCA::RemainingAmounts` (r:1 w:1) - /// Proof: `DCA::RemainingAmounts` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `CircuitBreaker::EgressAccounts` (r:2 w:0) - /// Proof: `CircuitBreaker::EgressAccounts` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) - /// Storage: `CircuitBreaker::GlobalAssetOverrides` (r:1 w:0) - /// Proof: `CircuitBreaker::GlobalAssetOverrides` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) - /// Storage: `Broadcast::IncrementalId` (r:1 w:1) - /// Proof: `Broadcast::IncrementalId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `DCA::RetriesOnError` (r:0 w:1) - /// Proof: `DCA::RetriesOnError` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleExecutionBlock` (r:0 w:1) - /// Proof: `DCA::ScheduleExecutionBlock` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) - fn on_initialize_with_buy_trade() -> Weight { - // Proof Size summary in bytes: - // Measured: `20604` - // Estimated: `31230` - // Minimum execution time: 263_133_000 picoseconds. - Weight::from_parts(264_822_000, 31230) - .saturating_add(T::DbWeight::get().reads(24_u64)) - .saturating_add(T::DbWeight::get().writes(9_u64)) - } - /// Storage: `DCA::ScheduleIdsPerBlock` (r:12 w:2) - /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(45), added: 2520, mode: `MaxEncodedLen`) - /// Storage: `DCA::MigrationEnabled` (r:1 w:0) - /// Proof: `DCA::MigrationEnabled` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) - /// Storage: `DCA::Schedules` (r:1 w:0) - /// Proof: `DCA::Schedules` (`max_values`: None, `max_size`: Some(243), added: 2718, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleExtraGas` (r:1 w:0) - /// Proof: `DCA::ScheduleExtraGas` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) - /// Storage: `DCA::RemainingAmounts` (r:1 w:1) - /// Proof: `DCA::RemainingAmounts` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `CircuitBreaker::EgressAccounts` (r:2 w:0) - /// Proof: `CircuitBreaker::EgressAccounts` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) - /// Storage: `CircuitBreaker::GlobalAssetOverrides` (r:1 w:0) - /// Proof: `CircuitBreaker::GlobalAssetOverrides` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) - /// Storage: `Broadcast::IncrementalId` (r:1 w:1) - /// Proof: `Broadcast::IncrementalId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `DCA::RetriesOnError` (r:0 w:1) - /// Proof: `DCA::RetriesOnError` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleExecutionBlock` (r:0 w:1) - /// Proof: `DCA::ScheduleExecutionBlock` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) - fn on_initialize_with_sell_trade() -> Weight { - // Proof Size summary in bytes: - // Measured: `20352` - // Estimated: `31230` - // Minimum execution time: 266_853_000 picoseconds. - Weight::from_parts(269_653_000, 31230) - .saturating_add(T::DbWeight::get().reads(24_u64)) - .saturating_add(T::DbWeight::get().writes(9_u64)) - } - /// Storage: `DCA::ScheduleIdsPerBlock` (r:1 w:0) - /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(45), added: 2520, mode: `MaxEncodedLen`) - /// Storage: `DCA::MigrationEnabled` (r:1 w:0) - /// Proof: `DCA::MigrationEnabled` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) - fn on_initialize_with_empty_block() -> Weight { - // Proof Size summary in bytes: - // Measured: `1113` - // Estimated: `3510` - // Minimum execution time: 20_655_000 picoseconds. - Weight::from_parts(21_107_000, 3510) - .saturating_add(T::DbWeight::get().reads(2_u64)) - } - /// Storage: `DCA::MigrationEnabled` (r:1 w:0) - /// Proof: `DCA::MigrationEnabled` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) - /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) - /// Storage: `Router::Routes` (r:1 w:0) - /// Proof: `Router::Routes` (`max_values`: None, `max_size`: Some(142), added: 2617, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleIdSequencer` (r:1 w:1) - /// Proof: `DCA::ScheduleIdSequencer` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Reserves` (r:1 w:1) - /// Proof: `Tokens::Reserves` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:1 w:1) - /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleIdsPerBlock` (r:11 w:1) - /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(45), added: 2520, mode: `MaxEncodedLen`) - /// Storage: `DCA::RetriesOnError` (r:0 w:1) - /// Proof: `DCA::RetriesOnError` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `DCA::Schedules` (r:0 w:1) - /// Proof: `DCA::Schedules` (`max_values`: None, `max_size`: Some(243), added: 2718, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleOwnership` (r:0 w:1) - /// Proof: `DCA::ScheduleOwnership` (`max_values`: None, `max_size`: Some(60), added: 2535, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleExecutionBlock` (r:0 w:1) - /// Proof: `DCA::ScheduleExecutionBlock` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) - /// Storage: `DCA::RemainingAmounts` (r:0 w:1) - /// Proof: `DCA::RemainingAmounts` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - fn schedule() -> Weight { - // Proof Size summary in bytes: - // Measured: `18268` - // Estimated: `28710` - // Minimum execution time: 175_767_000 picoseconds. - Weight::from_parts(177_196_000, 28710) - .saturating_add(T::DbWeight::get().reads(18_u64)) - .saturating_add(T::DbWeight::get().writes(9_u64)) - } - /// Storage: `DCA::Schedules` (r:1 w:1) - /// Proof: `DCA::Schedules` (`max_values`: None, `max_size`: Some(243), added: 2718, mode: `MaxEncodedLen`) - /// Storage: `DCA::RemainingAmounts` (r:1 w:1) - /// Proof: `DCA::RemainingAmounts` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleExecutionBlock` (r:1 w:1) - /// Proof: `DCA::ScheduleExecutionBlock` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleIdsPerBlock` (r:1 w:1) - /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(45), added: 2520, mode: `MaxEncodedLen`) - /// Storage: `DCA::RetriesOnError` (r:0 w:1) - /// Proof: `DCA::RetriesOnError` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleExtraGas` (r:0 w:1) - /// Proof: `DCA::ScheduleExtraGas` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) - /// Storage: `DCA::ScheduleOwnership` (r:0 w:1) - /// Proof: `DCA::ScheduleOwnership` (`max_values`: None, `max_size`: Some(60), added: 2535, mode: `MaxEncodedLen`) - fn terminate() -> Weight { - // Proof Size summary in bytes: - // Measured: `4072` - // Estimated: `4714` - // Minimum execution time: 100_321_000 picoseconds. - Weight::from_parts(101_127_000, 4714) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(9_u64)) - } - /// Storage: `DCA::ScheduleOwnership` (r:1 w:0) - /// Proof: `DCA::ScheduleOwnership` (`max_values`: None, `max_size`: Some(60), added: 2535, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn unlock_reserves() -> Weight { - // Proof Size summary in bytes: - // Measured: `1992` - // Estimated: `4714` - // Minimum execution time: 61_367_000 picoseconds. - Weight::from_parts(61_886_000, 4714) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } - /// Storage: `DCA::MigrationEnabled` (r:0 w:1) - /// Proof: `DCA::MigrationEnabled` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) - fn set_migration_enabled() -> Weight { - // Proof Size summary in bytes: - // Measured: `1012` - // Estimated: `0` - // Minimum execution time: 21_851_000 picoseconds. - Weight::from_parts(22_159_000, 0) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } -} \ No newline at end of file diff --git a/scripts/dca-monitor/README.md b/scripts/dca-monitor/README.md deleted file mode 100644 index 25881d5a7c..0000000000 --- a/scripts/dca-monitor/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# dca-monitor - -Drives a Chopsticks fork forward by N blocks and prints a per-schedule timeline of DCA events. Use this to verify a DCA fix on a forked chain *before* deploying the runtime upgrade. - -## Typical flow: verify a DCA fix on a fork - -1. Fork prod with Chopsticks at (or shortly before) the problematic block. -2. Apply your runtime upgrade to the fork. -3. Run `dca-monitor` against the fork — it forces 150 blocks of progress and surfaces every relevant event grouped by schedule ID. -4. Confirm the previously-failing schedule now executes as expected. - -## Setup - -```bash -cd scripts/dca-monitor -npm install -``` - -Chopsticks fork must be reachable at `ws://localhost:8000` (the default endpoint hardcoded in `index.js`; edit `ENDPOINT` to change). `BLOCK_COUNT` controls how many blocks the script drives (default 150). - -## Run - -```bash -node index.js -``` - -The script signs `system.remark` extrinsics with `//Alice` to force block production, then reads `system.events` at each new block. - -## What it tracks - -Grouped per-schedule: -- Schedule executions and outcomes. -- DCA failures and the decoded error. -- Randomness failures. -- Reserve unlocks. - -Plus global trackers: -- Extrinsic failures. -- Router executions and swap events. -- Dust loss events. diff --git a/scripts/dca-monitor/index.js b/scripts/dca-monitor/index.js deleted file mode 100644 index 21c585e361..0000000000 --- a/scripts/dca-monitor/index.js +++ /dev/null @@ -1,296 +0,0 @@ -import {ApiPromise, WsProvider, Keyring} from "@polkadot/api"; - -const ENDPOINT = 'ws://localhost:8000'; -const BLOCK_COUNT = 150; - -async function main() { - console.log(`Connecting to ${ENDPOINT}...`); - const provider = new WsProvider(ENDPOINT); - const api = await ApiPromise.create({ - provider, - throwOnConnect: false, - throwOnError: false, - }); - - const chain = await api.rpc.system.chain(); - console.log(`Connected to ${chain}`); - - const keyring = new Keyring({type: 'sr25519'}); - const alice = keyring.addFromUri('//Alice'); - console.log(`Using account: ${alice.address}`); - - // Per-schedule tracker: Map - const schedules = new Map(); - const randomnessFailures = []; - const reserveUnlocks = []; - - // Non-DCA event trackers - const extrinsicFailures = []; - const routerExecutions = []; - const swaps = []; - const dustLost = []; - - const getSchedule = (id) => { - if (!schedules.has(id)) { - schedules.set(id, { - events: [], - status: 'active', - failureDetails: [], - who: null, - }); - } - return schedules.get(id); - }; - - const truncate = (addr) => { - if (!addr) return 'N/A'; - const s = addr.toString(); - return s.length > 16 ? `${s.slice(0, 8)}...${s.slice(-6)}` : s; - }; - - const decodeError = (dispatchError) => { - if (dispatchError.isModule) { - const decoded = api.registry.findMetaError(dispatchError.asModule); - return `${decoded.section}.${decoded.method}`; - } - return dispatchError.toString(); - }; - - let nonce = (await api.rpc.system.accountNextIndex(alice.address)).toNumber(); - - console.log(`\nProducing ${BLOCK_COUNT} blocks and monitoring DCA events...\n`); - - for (let i = 0; i < BLOCK_COUNT; i++) { - const blockHash = await new Promise((resolve, reject) => { - api.tx.system.remark('dca-monitor').signAndSend(alice, {nonce: nonce++}, (receipt) => { - if (receipt.status.isInBlock) { - resolve(receipt.status.asInBlock); - } - }).catch(reject); - }); - - const blockNumber = (await api.rpc.chain.getHeader(blockHash)).number.toNumber(); - - // Query ALL block events (DCA fires in on_initialize, not in extrinsic receipts) - const events = await api.query.system.events.at(blockHash); - - let dcaCount = 0; - let otherCount = 0; - for (const record of events) { - const {event} = record; - const section = event.section; - const method = event.method; - const data = event.data; - - if (section === 'dca') { - dcaCount++; - switch (method) { - case 'ExecutionStarted': { - const id = data[0].toString(); - const schedule = getSchedule(id); - schedule.events.push({method, block: blockNumber}); - break; - } - case 'Scheduled': { - const id = data[0].toString(); - const who = data[1].toString(); - const schedule = getSchedule(id); - schedule.who = who; - schedule.events.push({method, block: blockNumber}); - break; - } - case 'ExecutionPlanned': { - const id = data[0].toString(); - const who = data[1].toString(); - const schedule = getSchedule(id); - schedule.who = schedule.who || who; - schedule.events.push({method, block: blockNumber}); - break; - } - case 'TradeExecuted': { - const id = data[0].toString(); - const who = data[1].toString(); - const amountIn = data[2].toString(); - const amountOut = data[3].toString(); - const schedule = getSchedule(id); - schedule.who = schedule.who || who; - schedule.events.push({method, block: blockNumber, amountIn, amountOut}); - break; - } - case 'TradeFailed': { - const id = data[0].toString(); - const who = data[1].toString(); - const error = decodeError(data[2]); - const schedule = getSchedule(id); - schedule.who = schedule.who || who; - schedule.events.push({method, block: blockNumber, error}); - schedule.failureDetails.push({block: blockNumber, error}); - break; - } - case 'Terminated': { - const id = data[0].toString(); - const who = data[1].toString(); - const error = decodeError(data[2]); - const schedule = getSchedule(id); - schedule.who = schedule.who || who; - schedule.status = 'terminated'; - schedule.events.push({method, block: blockNumber, error}); - schedule.failureDetails.push({block: blockNumber, error: `TERMINATED: ${error}`}); - break; - } - case 'Completed': { - const id = data[0].toString(); - const who = data[1].toString(); - const schedule = getSchedule(id); - schedule.who = schedule.who || who; - schedule.status = 'completed'; - schedule.events.push({method, block: blockNumber}); - break; - } - case 'RandomnessGenerationFailed': { - const block = data[0].toString(); - const error = decodeError(data[1]); - randomnessFailures.push({block: blockNumber, error}); - break; - } - case 'ReserveUnlocked': { - const who = data[0].toString(); - const assetId = data[1].toString(); - reserveUnlocks.push({who, assetId, block: blockNumber}); - break; - } - default: - console.log(` Unknown DCA event: ${method}`); - } - } else if (section === 'system' && method === 'ExtrinsicFailed') { - otherCount++; - const dispatchError = data[0]; - extrinsicFailures.push({block: blockNumber, error: decodeError(dispatchError)}); - } else if (section === 'router' && method === 'Executed') { - otherCount++; - routerExecutions.push({ - block: blockNumber, - assetIn: data[0].toString(), - assetOut: data[1].toString(), - amountIn: data[2].toString(), - amountOut: data[3].toString(), - }); - } else if (section === 'broadcast' && method === 'Swapped3') { - otherCount++; - swaps.push({block: blockNumber, swapper: data[0].toString()}); - } else if (section === 'tokens' && method === 'DustLost') { - otherCount++; - dustLost.push({ - block: blockNumber, - who: data[0].toString(), - assetId: data[1].toString(), - amount: data[2].toString(), - }); - } - } - - const parts = []; - if (dcaCount > 0) parts.push(`${dcaCount} DCA`); - if (otherCount > 0) parts.push(`${otherCount} other`); - console.log(`Block #${blockNumber} (${i + 1}/${BLOCK_COUNT}): ${parts.length > 0 ? parts.join(', ') : 'no tracked events'}`); - } - - // === Output Summary === - console.log('\n' + '='.repeat(80)); - console.log('DCA MONITOR SUMMARY'); - console.log('='.repeat(80)); - - if (schedules.size === 0) { - console.log('\nNo DCA schedule events detected in the monitored blocks.'); - } else { - const tableData = []; - for (const [id, info] of schedules) { - const executions = info.events.filter(e => e.method === 'ExecutionStarted').length; - const tradesOk = info.events.filter(e => e.method === 'TradeExecuted').length; - const tradesFailed = info.events.filter(e => e.method === 'TradeFailed').length; - const lastTrade = [...info.events].reverse().find(e => e.method === 'TradeExecuted' || e.method === 'TradeFailed'); - tableData.push({ - 'Schedule ID': id, - 'Owner': truncate(info.who), - 'Executions': executions, - 'Trades OK': tradesOk, - 'Trades Failed': tradesFailed, - 'Last Trade': lastTrade ? (lastTrade.method === 'TradeExecuted' ? 'OK' : 'FAILED') : '-', - 'Status': info.status, - }); - } - console.log('\nSchedule Summary:'); - console.table(tableData); - - // Print failure details - const allFailures = []; - for (const [id, info] of schedules) { - for (const f of info.failureDetails) { - allFailures.push({'Schedule ID': id, 'Block': f.block, 'Error': f.error}); - } - } - if (allFailures.length > 0) { - console.log('\nFailure Details:'); - console.table(allFailures); - } - } - - if (randomnessFailures.length > 0) { - console.log('\nRandomness Generation Failures:'); - console.table(randomnessFailures); - } - - if (reserveUnlocks.length > 0) { - console.log('\nReserve Unlocks:'); - console.table(reserveUnlocks.map(r => ({ - 'Owner': truncate(r.who), - 'Asset ID': r.assetId, - 'Block': r.block, - }))); - } - - // === Non-DCA Events === - console.log('\n' + '='.repeat(80)); - console.log('OTHER EVENTS'); - console.log('='.repeat(80)); - - console.log(`\nRouter Executions: ${routerExecutions.length}`); - console.log(`Broadcast Swaps: ${swaps.length}`); - console.log(`Extrinsic Failures: ${extrinsicFailures.length}`); - console.log(`Dust Lost: ${dustLost.length}`); - - if (extrinsicFailures.length > 0) { - console.log('\nExtrinsic Failure Details:'); - console.table(extrinsicFailures); - } - - if (dustLost.length > 0) { - console.log('\nDust Lost Details:'); - console.table(dustLost.map(d => ({ - 'Block': d.block, - 'Who': truncate(d.who), - 'Asset ID': d.assetId, - 'Amount': d.amount, - }))); - } - - // Final verdict - const totalSchedules = schedules.size; - const terminatedSchedules = [...schedules.values()].filter(s => s.status === 'terminated').length; - const withTradeFailures = [...schedules.values()].filter(s => s.failureDetails.length > 0 && s.status !== 'terminated').length; - - console.log('\n' + '='.repeat(80)); - console.log('VERDICT'); - console.log('='.repeat(80)); - console.log(`DCA schedules: ${totalSchedules} observed — ${terminatedSchedules} terminated, ${withTradeFailures} with trade failures`); - console.log(`Extrinsic failures: ${extrinsicFailures.length}`); - console.log(`Dust lost events: ${dustLost.length}`); - console.log('='.repeat(80)); - - await api.disconnect(); - console.log('Disconnected.'); -} - -main() - .catch(console.error) - .finally(() => process.exit(0));