From 90bddc78a2598d7630f334195c1f0d9e686525b5 Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Wed, 15 Dec 2021 12:02:41 +1300 Subject: [PATCH 01/13] Refactored event for the HomaLite module --- modules/homa-lite/src/lib.rs | 116 ++++++---- modules/homa-lite/src/tests.rs | 253 ++++++++++++++++----- modules/homa-lite/src/tests_no_fees.rs | 97 +++++--- runtime/integration-tests/src/homa_lite.rs | 20 +- 4 files changed, 347 insertions(+), 139 deletions(-) diff --git a/modules/homa-lite/src/lib.rs b/modules/homa-lite/src/lib.rs index 82a87b32b8..91c5a87b8c 100644 --- a/modules/homa-lite/src/lib.rs +++ b/modules/homa-lite/src/lib.rs @@ -177,48 +177,68 @@ pub mod module { #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { /// The user has Staked some currencies to mint Liquid Currency. - /// \[user, amount_staked, amount_minted\] - Minted(T::AccountId, Balance, Balance), + /// \[who, amount_staked, amount_minted\] + Minted { + who: T::AccountId, + amount_staked: Balance, + amount_minted: Balance, + }, /// The total amount of the staking currency on the relaychain has been /// set.\[total_staking_currency\] - TotalStakingCurrencySet(Balance), + TotalStakingCurrencySet { total_staking_currency: Balance }, /// The mint cap for Staking currency is updated.\[new_cap\] - StakingCurrencyMintCapUpdated(Balance), + StakingCurrencyMintCapUpdated { new_cap: Balance }, /// A new weight for XCM transfers has been set.\[new_weight\] - XcmDestWeightSet(Weight), + XcmDestWeightSet { new_weight: Weight }, /// The redeem request has been cancelled, and funds un-reserved. /// \[who, liquid_amount_unreserved\] - RedeemRequestCancelled(T::AccountId, Balance), + RedeemRequestCancelled { + who: T::AccountId, + liquid_amount_unreserved: Balance, + }, /// A new Redeem request has been registered. /// \[who, liquid_amount, extra_fee, withdraw_fee_paid\] - RedeemRequested(T::AccountId, Balance, Permill, Balance), + RedeemRequested { + who: T::AccountId, + liquid_amount: Balance, + extra_fee: Permill, + withdraw_fee_paid: Balance, + }, /// The user has redeemed some Liquid currency back to Staking currency. - /// \[user, staking_amount_redeemed, liquid_amount_deducted\] - Redeemed(T::AccountId, Balance, Balance), + /// \[who, staking_amount_redeemed, liquid_amount_deducted\] + Redeemed { + who: T::AccountId, + staking_amount_redeemed: Balance, + liquid_amount_deducted: Balance, + }, /// A new Unbond request added to the schedule. /// \[staking_amount, relaychain_blocknumber\] - ScheduledUnbondAdded(Balance, RelayChainBlockNumberOf), + ScheduledUnbondAdded { + staking_amount: Balance, + relaychain_blocknumber: RelayChainBlockNumberOf, + }, /// The ScheduledUnbond has been replaced. ScheduledUnbondReplaced, /// The scheduled Unbond has been withdrew from the RelayChain. ///\[staking_amount_added\] - ScheduledUnbondWithdrew(Balance), + ScheduledUnbondWithdrew { staking_amount_added: Balance }, /// Interest rate for TotalStakingCurrency is set - StakingInterestRatePerUpdateSet(Permill), + /// \[interest_rate\] + StakingInterestRatePerUpdateSet { interest_rate: Permill }, /// The amount of the staking currency available to be redeemed is set. /// \[total_available_staking_balance\] - AvailableStakingBalanceSet(Balance), + AvailableStakingBalanceSet { total_available_staking_balance: Balance }, } /// The total amount of the staking currency on the relaychain. @@ -430,7 +450,7 @@ pub mod module { T::GovernanceOrigin::ensure_origin(origin)?; StakingCurrencyMintCap::::put(new_cap); - Self::deposit_event(Event::::StakingCurrencyMintCapUpdated(new_cap)); + Self::deposit_event(Event::::StakingCurrencyMintCapUpdated { new_cap: new_cap }); Ok(()) } @@ -445,7 +465,9 @@ pub mod module { T::GovernanceOrigin::ensure_origin(origin)?; XcmDestWeight::::put(xcm_dest_weight); - Self::deposit_event(Event::::XcmDestWeightSet(xcm_dest_weight)); + Self::deposit_event(Event::::XcmDestWeightSet { + new_weight: xcm_dest_weight, + }); Ok(()) } @@ -490,7 +512,10 @@ pub mod module { let unreserved = T::Currency::unreserve(T::LiquidCurrencyId::get(), &who, request_amount); ensure!(unreserved.is_zero(), Error::::InsufficientReservedBalances); - Self::deposit_event(Event::::RedeemRequestCancelled(who, request_amount)); + Self::deposit_event(Event::::RedeemRequestCancelled { + who, + liquid_amount_unreserved: request_amount, + }); } return Ok(()); } @@ -541,12 +566,12 @@ pub mod module { // Set the new amount into storage. *request = Some((liquid_amount, additional_fee)); - Self::deposit_event(Event::::RedeemRequested( - who.clone(), - liquid_amount, - additional_fee, - base_withdraw_fee, - )); + Self::deposit_event(Event::::RedeemRequested { + who: who.clone(), + liquid_amount: liquid_amount, + extra_fee: additional_fee, + withdraw_fee_paid: base_withdraw_fee, + }); Ok(()) })?; @@ -579,7 +604,10 @@ pub mod module { ); ScheduledUnbond::::put(bounded_vec); - Self::deposit_event(Event::::ScheduledUnbondAdded(staking_amount, unbond_block)); + Self::deposit_event(Event::::ScheduledUnbondAdded { + staking_amount, + relaychain_blocknumber: unbond_block, + }); Ok(()) } @@ -650,7 +678,9 @@ pub mod module { } else { *current = current.saturating_sub(by_balance); } - Self::deposit_event(Event::::AvailableStakingBalanceSet(*current)); + Self::deposit_event(Event::::AvailableStakingBalanceSet { + total_available_staking_balance: *current, + }); }); // With new staking balance available, process pending redeem requests. @@ -672,7 +702,9 @@ pub mod module { StakingInterestRatePerUpdate::::put(interest_rate); - Self::deposit_event(Event::::StakingInterestRatePerUpdateSet(interest_rate)); + Self::deposit_event(Event::::StakingInterestRatePerUpdateSet { + interest_rate: interest_rate, + }); Ok(()) } @@ -753,11 +785,11 @@ pub mod module { // Transfer the reduced staking currency from Minter to Redeemer T::Currency::transfer(T::StakingCurrencyId::get(), minter, redeemer, staking_amount)?; - Self::deposit_event(Event::::Redeemed( - redeemer.clone(), - staking_amount, - actual_liquid_amount, - )); + Self::deposit_event(Event::::Redeemed { + who: redeemer.clone(), + staking_amount_redeemed: staking_amount, + liquid_amount_deducted: actual_liquid_amount, + }); // Update storage let new_amount = request_amount.saturating_sub(actual_liquid_amount); @@ -869,7 +901,11 @@ pub mod module { let actual_staked = amount.saturating_sub(staking_remaining); let actual_liquid = total_liquid_to_mint.saturating_sub(liquid_remaining); - Self::deposit_event(Event::::Minted(minter.clone(), actual_staked, actual_liquid)); + Self::deposit_event(Event::::Minted { + who: minter.clone(), + amount_staked: actual_staked, + amount_minted: actual_liquid, + }); Ok(()) } @@ -892,7 +928,9 @@ pub mod module { *current = current.saturating_add(staking_amount_unbonded); }); - Self::deposit_event(Event::::ScheduledUnbondWithdrew(staking_amount_unbonded)); + Self::deposit_event(Event::::ScheduledUnbondWithdrew { + staking_amount_added: staking_amount_unbonded, + }); Ok(()) } @@ -947,11 +985,11 @@ pub mod module { *current = current.saturating_sub(actual_staking_amount) }); - Self::deposit_event(Event::::Redeemed( - redeemer.clone(), - actual_staking_amount_deposited, - actual_liquid_amount, - )); + Self::deposit_event(Event::::Redeemed { + who: redeemer.clone(), + staking_amount_redeemed: actual_staking_amount_deposited, + liquid_amount_deducted: actual_liquid_amount, + }); // Update storage let new_amount = request_amount.saturating_sub(actual_liquid_amount); @@ -1008,7 +1046,9 @@ pub mod module { TotalStakingCurrency::::try_mutate(|current| { *current = f(*current)?; ensure!(!current.is_zero(), Error::::InvalidTotalStakingCurrency); - Self::deposit_event(Event::::TotalStakingCurrencySet(*current)); + Self::deposit_event(Event::::TotalStakingCurrencySet { + total_staking_currency: *current, + }); Ok(()) }) } diff --git a/modules/homa-lite/src/tests.rs b/modules/homa-lite/src/tests.rs index 1bc8f20c28..9cc119055a 100644 --- a/modules/homa-lite/src/tests.rs +++ b/modules/homa-lite/src/tests.rs @@ -59,7 +59,11 @@ fn mint_works() { let mut liquid = 9_899_901_000_000_000; assert_ok!(HomaLite::mint(Origin::signed(ALICE), amount)); assert_eq!(Currencies::free_balance(LKSM, &ALICE), liquid); - System::assert_last_event(Event::HomaLite(crate::Event::Minted(ALICE, amount, liquid))); + System::assert_last_event(Event::HomaLite(crate::Event::Minted { + who: ALICE, + amount_staked: amount, + amount_minted: liquid, + })); // The total staking currency is now increased. assert_eq!(TotalStakingCurrency::::get(), dollar(1000)); @@ -80,7 +84,11 @@ fn mint_works() { liquid = 4_949_950_500_000_000; assert_ok!(HomaLite::mint(Origin::signed(BOB), amount)); assert_eq!(Currencies::free_balance(LKSM, &BOB), liquid); - System::assert_last_event(Event::HomaLite(crate::Event::Minted(BOB, amount, liquid))); + System::assert_last_event(Event::HomaLite(crate::Event::Minted { + who: BOB, + amount_staked: amount, + amount_minted: liquid, + })); }); } @@ -116,7 +124,11 @@ fn repeated_mints_have_similar_exchange_rate() { // liquid = (1000 - 0.01) * 1004949.9505 / 201000 * 0.99 let liquid_2 = 4_949_703_990_002_433; // Actual amount is lower due to rounding loss assert_ok!(HomaLite::mint(Origin::signed(BOB), amount)); - System::assert_last_event(Event::HomaLite(crate::Event::Minted(BOB, amount, liquid_2))); + System::assert_last_event(Event::HomaLite(crate::Event::Minted { + who: BOB, + amount_staked: amount, + amount_minted: liquid_2, + })); assert_eq!(Currencies::free_balance(KSM, &BOB), 998_000_000_000_000_001); assert_eq!(Currencies::free_balance(LKSM, &BOB), 9_899_654_490_002_433); @@ -137,7 +149,11 @@ fn repeated_mints_have_similar_exchange_rate() { // liquid = (1000 - 0.01) * 1009899.654490002433 / 204020 * 0.99 let liquid_3 = 4_900_454_170_858_356; // Actual amount is lower due to rounding loss assert_ok!(HomaLite::mint(Origin::signed(BOB), amount)); - System::assert_last_event(Event::HomaLite(crate::Event::Minted(BOB, amount, liquid_3))); + System::assert_last_event(Event::HomaLite(crate::Event::Minted { + who: BOB, + amount_staked: amount, + amount_minted: liquid_3, + })); assert_eq!(Currencies::free_balance(KSM, &BOB), 997_000_000_000_000_002); assert_eq!(Currencies::free_balance(LKSM, &BOB), 14_800_108_660_860_789); @@ -189,7 +205,9 @@ fn cannot_set_total_staking_currency_to_zero() { ); assert_ok!(HomaLite::set_total_staking_currency(Origin::root(), 1)); assert_eq!(TotalStakingCurrency::::get(), 1); - System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet(1))); + System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet { + total_staking_currency: 1, + })); }); } @@ -207,12 +225,16 @@ fn can_adjust_total_staking_currency() { // Can adjust total_staking_currency with DAVE. assert_ok!(HomaLite::adjust_total_staking_currency(Origin::root(), 5000i128)); assert_eq!(HomaLite::total_staking_currency(), 5001); - System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet(5001))); + System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet { + total_staking_currency: 5001, + })); // Can decrease total_staking_currency. assert_ok!(HomaLite::adjust_total_staking_currency(Origin::root(), -5000i128)); assert_eq!(HomaLite::total_staking_currency(), 1); - System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet(1))); + System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet { + total_staking_currency: 1, + })); // overflow can be handled assert_ok!(HomaLite::set_total_staking_currency( @@ -247,7 +269,9 @@ fn can_adjust_available_staking_balance_with_no_matches() { // Can adjust available_staking_balance with DAVE. assert_ok!(HomaLite::adjust_available_staking_balance(Origin::root(), 5001i128, 10)); assert_eq!(HomaLite::available_staking_balance(), 5001); - System::assert_last_event(Event::HomaLite(crate::Event::AvailableStakingBalanceSet(5001))); + System::assert_last_event(Event::HomaLite(crate::Event::AvailableStakingBalanceSet { + total_available_staking_balance: 5001, + })); // Can decrease available_staking_balance. assert_ok!(HomaLite::adjust_available_staking_balance( @@ -256,7 +280,9 @@ fn can_adjust_available_staking_balance_with_no_matches() { 10 )); assert_eq!(HomaLite::total_staking_currency(), 0); - System::assert_last_event(Event::HomaLite(crate::Event::AvailableStakingBalanceSet(0))); + System::assert_last_event(Event::HomaLite(crate::Event::AvailableStakingBalanceSet { + total_available_staking_balance: 0, + })); // Underflow / overflow can be handled due to the use of saturating arithmetic assert_ok!(HomaLite::adjust_available_staking_balance( @@ -313,9 +339,9 @@ fn can_set_mint_cap() { // Cap should be set now. assert_eq!(StakingCurrencyMintCap::::get(), dollar(1_000)); - System::assert_last_event(Event::HomaLite(crate::Event::StakingCurrencyMintCapUpdated(dollar( - 1_000, - )))); + System::assert_last_event(Event::HomaLite(crate::Event::StakingCurrencyMintCapUpdated { + new_cap: dollar(1_000), + })); }); } @@ -334,7 +360,9 @@ fn can_set_xcm_dest_weight() { // Cap should be set now. assert_eq!(XcmDestWeight::::get(), 1_000_000); - System::assert_last_event(Event::HomaLite(crate::Event::XcmDestWeightSet(1_000_000))); + System::assert_last_event(Event::HomaLite(crate::Event::XcmDestWeightSet { + new_weight: 1_000_000, + })); }); } @@ -353,7 +381,10 @@ fn can_schedule_unbond() { // Storage should be updated now. assert_eq!(ScheduledUnbond::::get(), vec![(1_000_000, 100)]); - System::assert_last_event(Event::HomaLite(crate::Event::ScheduledUnbondAdded(1_000_000, 100))); + System::assert_last_event(Event::HomaLite(crate::Event::ScheduledUnbondAdded { + staking_amount: 1_000_000, + relaychain_blocknumber: 100, + })); // Schedule another unbond. assert_ok!(HomaLite::schedule_unbond(Origin::root(), 200, 80)); @@ -361,7 +392,10 @@ fn can_schedule_unbond() { // Storage should be updated now. assert_eq!(ScheduledUnbond::::get(), vec![(1_000_000, 100), (200, 80)]); - System::assert_last_event(Event::HomaLite(crate::Event::ScheduledUnbondAdded(200, 80))); + System::assert_last_event(Event::HomaLite(crate::Event::ScheduledUnbondAdded { + staking_amount: 200, + relaychain_blocknumber: 80, + })); }); } @@ -618,9 +652,20 @@ fn request_redeem_works() { events, vec![ // Redeem requested, with some withdraw fee deducted. - crate::Event::RedeemRequested(DAVE, dollar(99_900), Permill::zero(), dollar(100)), - crate::Event::TotalStakingCurrencySet(90_009_000_900_090_010), - crate::Event::Redeemed(DAVE, 9_989_999_099_909_990, dollar(99_900)) + crate::Event::RedeemRequested { + who: DAVE, + liquid_amount: dollar(99_900), + extra_fee: Permill::zero(), + withdraw_fee_paid: dollar(100) + }, + crate::Event::TotalStakingCurrencySet { + total_staking_currency: 90_009_000_900_090_010 + }, + crate::Event::Redeemed { + who: DAVE, + staking_amount_redeemed: 9_989_999_099_909_990, + liquid_amount_deducted: dollar(99_900) + } ] ); @@ -743,15 +788,20 @@ fn update_redeem_request_works() { vec![ // Reserve the newly added amount Event::Tokens(orml_tokens::Event::Reserved(LKSM, DAVE, amount_reserved)), - Event::HomaLite(crate::Event::RedeemRequested( - DAVE, - new_redeem_amount, - Permill::zero(), - withdraw_fee - )), + Event::HomaLite(crate::Event::RedeemRequested { + who: DAVE, + liquid_amount: new_redeem_amount, + extra_fee: Permill::zero(), + withdraw_fee_paid: withdraw_fee + }), // Unreserve the reduced amount Event::Tokens(orml_tokens::Event::Unreserved(LKSM, DAVE, 998_999_000_000_000)), - Event::HomaLite(crate::Event::RedeemRequested(DAVE, dollar(1000), Permill::zero(), 0)), + Event::HomaLite(crate::Event::RedeemRequested { + who: DAVE, + liquid_amount: dollar(1000), + extra_fee: Permill::zero(), + withdraw_fee_paid: 0 + }), ] ); @@ -974,9 +1024,22 @@ fn mint_can_handle_dust_redeem_requests() { assert_eq!( events, vec![ - crate::Event::RedeemRequested(ALICE, 1_000_000_100_000_000, Permill::zero(), 1_001_001_101_101), - crate::Event::Redeemed(ALICE, 100_100_100_100_098, 999_999_999_999_990), - crate::Event::Minted(BOB, 100_100_100_100_099, 999_999_999_999_990), + crate::Event::RedeemRequested { + who: ALICE, + liquid_amount: 1_000_000_100_000_000, + extra_fee: Permill::zero(), + withdraw_fee_paid: 1_001_001_101_101 + }, + crate::Event::Redeemed { + who: ALICE, + staking_amount_redeemed: 100_100_100_100_098, + liquid_amount_deducted: 999_999_999_999_990 + }, + crate::Event::Minted { + who: BOB, + amount_staked: 100_100_100_100_099, + amount_minted: 999_999_999_999_990 + }, ] ); }); @@ -1098,17 +1161,48 @@ fn mint_can_match_requested_redeem() { assert_eq!( events, vec![ - crate::Event::StakingCurrencyMintCapUpdated(1000000000000000000), + crate::Event::StakingCurrencyMintCapUpdated { + new_cap: dollar(1_000_000) + }, // Request redeem - crate::Event::RedeemRequested(DAVE, 99_900_000_000_000, Permill::zero(), 100_000_000_000), - crate::Event::RedeemRequested(ALICE, 199_800_000_000_000, Permill::zero(), 200_000_000_000), - crate::Event::RedeemRequested(BOB, 199_800_000_000_000, Permill::zero(), 200_000_000_000), + crate::Event::RedeemRequested { + who: DAVE, + liquid_amount: 99_900_000_000_000, + extra_fee: Permill::zero(), + withdraw_fee_paid: 100_000_000_000 + }, + crate::Event::RedeemRequested { + who: ALICE, + liquid_amount: 199_800_000_000_000, + extra_fee: Permill::zero(), + withdraw_fee_paid: 200_000_000_000 + }, + crate::Event::RedeemRequested { + who: BOB, + liquid_amount: 199_800_000_000_000, + extra_fee: Permill::zero(), + withdraw_fee_paid: 200_000_000_000 + }, // Redeemed - crate::Event::Redeemed(ALICE, 19_980_000_000_000, 199_800_000_000_000), - crate::Event::Redeemed(BOB, 19_980_000_000_000, 199_800_000_000_000), + crate::Event::Redeemed { + who: ALICE, + staking_amount_redeemed: 19_980_000_000_000, + liquid_amount_deducted: 199_800_000_000_000 + }, + crate::Event::Redeemed { + who: BOB, + staking_amount_redeemed: 19_980_000_000_000, + liquid_amount_deducted: 199_800_000_000_000 + }, // Mint via XCM: 600 LKSM - XCM fee - crate::Event::TotalStakingCurrencySet(60_040_000_000_000), - crate::Event::Minted(CHARLIE, 100000000000000, 993_897_000_000_000), + crate::Event::TotalStakingCurrencySet { + total_staking_currency: 60_040_000_000_000 + }, + crate::Event::Minted { + who: CHARLIE, + amount_staked: dollar(100), + amount_minted: 993_897_000_000_000 + }, ] ); }); @@ -1243,12 +1337,12 @@ fn redeem_can_handle_dust_available_staking_currency() { )); assert_eq!(HomaLite::redeem_requests(DAVE), Some((dollar(999), Permill::zero()))); - System::assert_last_event(Event::HomaLite(crate::Event::RedeemRequested( - DAVE, - dollar(999), - Permill::zero(), - dollar(1), - ))); + System::assert_last_event(Event::HomaLite(crate::Event::RedeemRequested { + who: DAVE, + liquid_amount: dollar(999), + extra_fee: Permill::zero(), + withdraw_fee_paid: dollar(1), + })); }); } @@ -1281,9 +1375,9 @@ fn total_staking_currency_update_periodically() { Origin::root(), Permill::from_percent(1) )); - System::assert_last_event(Event::HomaLite(crate::Event::StakingInterestRatePerUpdateSet( - Permill::from_percent(1), - ))); + System::assert_last_event(Event::HomaLite(crate::Event::StakingInterestRatePerUpdateSet { + interest_rate: Permill::from_percent(1), + })); for i in 101..200 { assert_eq!(HomaLite::on_initialize(i), on_initialize_without_work_weight); @@ -1291,9 +1385,9 @@ fn total_staking_currency_update_periodically() { assert_eq!(HomaLite::on_initialize(200), on_initialize_weight); // Inflate by 1%: 1_000_000 * 1.01 assert_eq!(TotalStakingCurrency::::get(), dollar(1_010_000)); - System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet(dollar( - 1_010_000, - )))); + System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet { + total_staking_currency: dollar(1_010_000), + })); for i in 201..300 { assert_eq!(HomaLite::on_initialize(i), on_initialize_without_work_weight); @@ -1301,9 +1395,9 @@ fn total_staking_currency_update_periodically() { assert_eq!(HomaLite::on_initialize(300), on_initialize_weight); // 1_010_000 * 1.01 assert_eq!(TotalStakingCurrency::::get(), dollar(1_020_100)); - System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet(dollar( - 1_020_100, - )))); + System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet { + total_staking_currency: dollar(1_020_100), + })); for i in 301..400 { assert_eq!(HomaLite::on_initialize(i), on_initialize_without_work_weight); @@ -1311,9 +1405,9 @@ fn total_staking_currency_update_periodically() { assert_eq!(HomaLite::on_initialize(400), on_initialize_weight); //1_020_100 * 1.01 assert_eq!(TotalStakingCurrency::::get(), dollar(1_030_301)); - System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet(dollar( - 1_030_301, - )))); + System::assert_last_event(Event::HomaLite(crate::Event::TotalStakingCurrencySet { + total_staking_currency: dollar(1_030_301), + })); }); } @@ -1661,9 +1755,17 @@ fn available_staking_balances_can_handle_rounding_error_dust() { assert_eq!( events, vec![ - crate::Event::ScheduledUnbondWithdrew(999_999_999_999), - crate::Event::TotalStakingCurrencySet(999_237_000_000_002), - crate::Event::Redeemed(ALICE, 0, 9_987_632_930_985), + crate::Event::ScheduledUnbondWithdrew { + staking_amount_added: 999_999_999_999 + }, + crate::Event::TotalStakingCurrencySet { + total_staking_currency: 999_237_000_000_002 + }, + crate::Event::Redeemed { + who: ALICE, + staking_amount_redeemed: 0, + liquid_amount_deducted: 9_987_632_930_985 + }, ] ); }); @@ -1738,12 +1840,37 @@ fn mint_can_handle_rounding_error_dust() { assert_eq!( events, vec![ - crate::Event::TotalStakingCurrencySet(1_000_237_000_000_000), - crate::Event::RedeemRequested(ALICE, dollar(4_995), Permill::zero(), dollar(5)), - crate::Event::RedeemRequested(BOB, dollar(1_998), Permill::zero(), dollar(2)), - crate::Event::RedeemRequested(DAVE, dollar(2_997), Permill::zero(), dollar(3)), - crate::Event::Redeemed(ALICE, 999_999_999_998, 9_987_632_930_985), - crate::Event::Minted(DAVE, 999_999_999_999, 9_987_632_930_985) + crate::Event::TotalStakingCurrencySet { + total_staking_currency: 1_000_237_000_000_000 + }, + crate::Event::RedeemRequested { + who: ALICE, + liquid_amount: dollar(4_995), + extra_fee: Permill::zero(), + withdraw_fee_paid: dollar(5) + }, + crate::Event::RedeemRequested { + who: BOB, + liquid_amount: dollar(1_998), + extra_fee: Permill::zero(), + withdraw_fee_paid: dollar(2) + }, + crate::Event::RedeemRequested { + who: DAVE, + liquid_amount: dollar(2_997), + extra_fee: Permill::zero(), + withdraw_fee_paid: dollar(3) + }, + crate::Event::Redeemed { + who: ALICE, + staking_amount_redeemed: 999_999_999_998, + liquid_amount_deducted: 9_987_632_930_985 + }, + crate::Event::Minted { + who: DAVE, + amount_staked: 999_999_999_999, + amount_minted: 9_987_632_930_985 + } ] ); }); diff --git a/modules/homa-lite/src/tests_no_fees.rs b/modules/homa-lite/src/tests_no_fees.rs index 9e76a8caec..3aa22b3802 100644 --- a/modules/homa-lite/src/tests_no_fees.rs +++ b/modules/homa-lite/src/tests_no_fees.rs @@ -44,20 +44,20 @@ fn no_fee_runtime_has_no_fees() { HomaLite::get_exchange_rate(), ExchangeRate::saturating_from_rational(1, 10) ); - System::assert_last_event(Event::HomaLite(crate::Event::Minted( - ALICE, - dollar(1_000), - dollar(10_000), - ))); + System::assert_last_event(Event::HomaLite(crate::Event::Minted { + who: ALICE, + amount_staked: dollar(1_000), + amount_minted: dollar(10_000), + })); assert_eq!(Currencies::free_balance(KSM, &ALICE), dollar(999_000)); assert_eq!(Currencies::free_balance(LKSM, &ALICE), dollar(10_000)); assert_ok!(HomaLite::mint(Origin::signed(BOB), dollar(5_000))); - System::assert_last_event(Event::HomaLite(crate::Event::Minted( - BOB, - dollar(5_000), - dollar(50_000), - ))); + System::assert_last_event(Event::HomaLite(crate::Event::Minted { + who: BOB, + amount_staked: dollar(5_000), + amount_minted: dollar(50_000), + })); assert_eq!(Currencies::free_balance(KSM, &BOB), dollar(995_000)); assert_eq!(Currencies::free_balance(LKSM, &BOB), dollar(50_000)); @@ -67,12 +67,12 @@ fn no_fee_runtime_has_no_fees() { dollar(50_000), Permill::zero() )); - System::assert_last_event(Event::HomaLite(crate::Event::RedeemRequested( - BOB, - dollar(50_000), - Permill::zero(), - 0, - ))); + System::assert_last_event(Event::HomaLite(crate::Event::RedeemRequested { + who: BOB, + liquid_amount: dollar(50_000), + extra_fee: Permill::zero(), + withdraw_fee_paid: 0, + })); assert_ok!(HomaLite::mint(Origin::signed(ALICE), dollar(5_000))); assert_eq!(Currencies::free_balance(KSM, &ALICE), dollar(994_000)); @@ -106,18 +106,59 @@ fn no_fee_runtime_has_no_fees() { assert_eq!( events, vec![ - crate::Event::TotalStakingCurrencySet(dollar(101_000)), - crate::Event::Minted(ALICE, dollar(1_000), dollar(10_000)), - crate::Event::TotalStakingCurrencySet(dollar(106_000)), - crate::Event::Minted(BOB, dollar(5_000), dollar(50_000)), - crate::Event::RedeemRequested(BOB, dollar(50_000), Permill::zero(), 0), - crate::Event::Redeemed(BOB, dollar(5000), dollar(50000)), - crate::Event::Minted(ALICE, dollar(5000), dollar(50000)), - crate::Event::ScheduledUnbondAdded(dollar(50_000), 0), - crate::Event::ScheduledUnbondWithdrew(dollar(50_000)), - crate::Event::RedeemRequested(DAVE, dollar(100_000), Permill::zero(), 0), - crate::Event::TotalStakingCurrencySet(dollar(96_000)), - crate::Event::Redeemed(DAVE, dollar(10_000), dollar(100_000)), + crate::Event::TotalStakingCurrencySet { + total_staking_currency: dollar(101_000) + }, + crate::Event::Minted { + who: ALICE, + amount_staked: dollar(1_000), + amount_minted: dollar(10_000) + }, + crate::Event::TotalStakingCurrencySet { + total_staking_currency: dollar(106_000) + }, + crate::Event::Minted { + who: BOB, + amount_staked: dollar(5_000), + amount_minted: dollar(50_000) + }, + crate::Event::RedeemRequested { + who: BOB, + liquid_amount: dollar(50_000), + extra_fee: Permill::zero(), + withdraw_fee_paid: 0 + }, + crate::Event::Redeemed { + who: BOB, + staking_amount_redeemed: dollar(5000), + liquid_amount_deducted: dollar(50000) + }, + crate::Event::Minted { + who: ALICE, + amount_staked: dollar(5000), + amount_minted: dollar(50000) + }, + crate::Event::ScheduledUnbondAdded { + staking_amount: dollar(50_000), + relaychain_blocknumber: 0 + }, + crate::Event::ScheduledUnbondWithdrew { + staking_amount_added: dollar(50_000) + }, + crate::Event::RedeemRequested { + who: DAVE, + liquid_amount: dollar(100_000), + extra_fee: Permill::zero(), + withdraw_fee_paid: 0 + }, + crate::Event::TotalStakingCurrencySet { + total_staking_currency: dollar(96_000) + }, + crate::Event::Redeemed { + who: DAVE, + staking_amount_redeemed: dollar(10_000), + liquid_amount_deducted: dollar(100_000) + }, ] ); }); diff --git a/runtime/integration-tests/src/homa_lite.rs b/runtime/integration-tests/src/homa_lite.rs index 4aaff885b8..5dfd9b189d 100644 --- a/runtime/integration-tests/src/homa_lite.rs +++ b/runtime/integration-tests/src/homa_lite.rs @@ -62,11 +62,11 @@ fn homa_lite_mint_works() { assert_ok!(HomaLite::mint(Origin::signed(alice()), amount)); assert_eq!(Currencies::free_balance(LIQUID_CURRENCY, &alice()), liquid_amount_1); - System::assert_last_event(Event::HomaLite(module_homa_lite::Event::Minted( - alice(), - amount, - liquid_amount_1, - ))); + System::assert_last_event(Event::HomaLite(module_homa_lite::Event::Minted { + who: alice(), + amount_staked: amount, + amount_minted: liquid_amount_1, + })); // Total issuance for liquid currnecy increased. let new_liquid_issuance = Currencies::total_issuance(LIQUID_CURRENCY); @@ -86,11 +86,11 @@ fn homa_lite_mint_works() { let liquid_amount_2 = 49_974_865_639_397; assert_ok!(HomaLite::mint(Origin::signed(alice()), amount)); - System::assert_last_event(Event::HomaLite(module_homa_lite::Event::Minted( - alice(), - amount, - liquid_amount_2, - ))); + System::assert_last_event(Event::HomaLite(module_homa_lite::Event::Minted { + who: alice(), + amount_staked: amount, + amount_minted: liquid_amount_2, + })); #[cfg(feature = "with-karura-runtime")] assert_eq!( Currencies::free_balance(LIQUID_CURRENCY, &alice()), From 40521450b470aecc0f8e9e6dbd0ecded6b920d01 Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Wed, 15 Dec 2021 13:19:52 +1300 Subject: [PATCH 02/13] Refactored the event for asset-registry, auction manager and the cdp engine --- modules/asset-registry/src/lib.rs | 30 ++++-- modules/asset-registry/src/tests.rs | 18 ++-- modules/auction-manager/src/lib.rs | 67 ++++++++----- modules/auction-manager/src/tests.rs | 60 +++++++---- modules/cdp-engine/src/lib.rs | 127 ++++++++++++++++-------- modules/cdp-engine/src/tests.rs | 113 +++++++++++---------- modules/homa-lite/src/lib.rs | 14 +-- runtime/integration-tests/src/honzon.rs | 37 +++---- 8 files changed, 281 insertions(+), 185 deletions(-) diff --git a/modules/asset-registry/src/lib.rs b/modules/asset-registry/src/lib.rs index e4fb7216f0..2668e290af 100644 --- a/modules/asset-registry/src/lib.rs +++ b/modules/asset-registry/src/lib.rs @@ -111,10 +111,17 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] pub enum Event { - /// The foreign asset registered. \[ForeignAssetId, AssetMetadata\] - ForeignAssetRegistered(ForeignAssetId, MultiLocation, AssetMetadata>), - /// The foreign asset updated. \[AssetMetadata\] - ForeignAssetUpdated(MultiLocation, AssetMetadata>), + /// The foreign asset registered. + ForeignAssetRegistered { + asset_id: ForeignAssetId, + asset_address: MultiLocation, + metadata: AssetMetadata>, + }, + /// The foreign asset updated. + ForeignAssetUpdated { + asset_address: MultiLocation, + metadata: AssetMetadata>, + }, } /// Next available Foreign AssetId ID. @@ -172,11 +179,11 @@ pub mod module { let location: MultiLocation = (*location).try_into().map_err(|()| Error::::BadLocation)?; let foreign_asset_id = Self::do_register_foreign_asset(&location, &metadata)?; - Self::deposit_event(Event::::ForeignAssetRegistered( - foreign_asset_id, - location, - *metadata, - )); + Self::deposit_event(Event::::ForeignAssetRegistered { + asset_id: foreign_asset_id, + asset_address: location, + metadata: *metadata, + }); Ok(()) } @@ -193,7 +200,10 @@ pub mod module { let location: MultiLocation = (*location).try_into().map_err(|()| Error::::BadLocation)?; Self::do_update_foreign_asset(foreign_asset_id, &location, &metadata)?; - Self::deposit_event(Event::::ForeignAssetUpdated(location, *metadata)); + Self::deposit_event(Event::::ForeignAssetUpdated { + asset_address: location, + metadata: *metadata, + }); Ok(()) } } diff --git a/modules/asset-registry/src/tests.rs b/modules/asset-registry/src/tests.rs index 2b1901fe4f..b4fb0d2ee1 100644 --- a/modules/asset-registry/src/tests.rs +++ b/modules/asset-registry/src/tests.rs @@ -83,16 +83,16 @@ fn register_foreign_asset_work() { )); let location: MultiLocation = v0_location.try_into().unwrap(); - System::assert_last_event(Event::AssetRegistry(crate::Event::ForeignAssetRegistered( - 0, - location.clone(), - AssetMetadata { + System::assert_last_event(Event::AssetRegistry(crate::Event::ForeignAssetRegistered { + asset_id: 0, + asset_address: location.clone(), + metadata: AssetMetadata { name: b"Token Name".to_vec(), symbol: b"TN".to_vec(), decimals: 12, minimal_balance: 1, }, - ))); + })); assert_eq!(ForeignAssetLocations::::get(0), Some(location.clone())); assert_eq!( @@ -188,15 +188,15 @@ fn update_foreign_asset_work() { )); let location: MultiLocation = v0_location.try_into().unwrap(); - System::assert_last_event(Event::AssetRegistry(crate::Event::ForeignAssetUpdated( - location.clone(), - AssetMetadata { + System::assert_last_event(Event::AssetRegistry(crate::Event::ForeignAssetUpdated { + asset_address: location.clone(), + metadata: AssetMetadata { name: b"New Token Name".to_vec(), symbol: b"NTN".to_vec(), decimals: 13, minimal_balance: 2, }, - ))); + })); assert_eq!( AssetMetadatas::::get(0), diff --git a/modules/auction-manager/src/lib.rs b/modules/auction-manager/src/lib.rs index b783e65651..2701c89b7b 100644 --- a/modules/auction-manager/src/lib.rs +++ b/modules/auction-manager/src/lib.rs @@ -203,17 +203,30 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// Collateral auction created. \[auction_id, collateral_type, - /// collateral_amount, target_bid_price\] - NewCollateralAuction(AuctionId, CurrencyId, Balance, Balance), - /// Active auction cancelled. \[auction_id\] - CancelAuction(AuctionId), - /// Collateral auction dealt. \[auction_id, collateral_type, - /// collateral_amount, winner, payment_amount\] - CollateralAuctionDealt(AuctionId, CurrencyId, Balance, T::AccountId, Balance), - /// Dex take collateral auction. \[auction_id, collateral_type, - /// collateral_amount, turnover\] - DEXTakeCollateralAuction(AuctionId, CurrencyId, Balance, Balance), + /// Collateral auction created. + NewCollateralAuction { + auction_id: AuctionId, + collateral_type: CurrencyId, + collateral_amount: Balance, + target_bid_price: Balance, + }, + /// Active auction cancelled. + CancelAuction { auction_id: AuctionId }, + /// Collateral auction dealt. + CollateralAuctionDealt { + auction_id: AuctionId, + collateral_type: CurrencyId, + collateral_amount: Balance, + winner: T::AccountId, + payment_amount: Balance, + }, + /// Dex take collateral auction. + DEXTakeCollateralAuction { + auction_id: AuctionId, + collateral_type: CurrencyId, + collateral_amount: Balance, + turnover: Balance, + }, } /// Mapping from auction id to collateral auction info @@ -282,7 +295,7 @@ pub mod module { ensure_none(origin)?; ensure!(T::EmergencyShutdown::is_shutdown(), Error::::MustAfterShutdown); >::cancel_auction(id)?; - Self::deposit_event(Event::CancelAuction(id)); + Self::deposit_event(Event::CancelAuction { auction_id: id }); Ok(()) } } @@ -663,13 +676,12 @@ impl Pallet { debug_assert!(false); } } - - Self::deposit_event(Event::DEXTakeCollateralAuction( + Self::deposit_event(Event::DEXTakeCollateralAuction { auction_id, - collateral_auction.currency_id, - collateral_auction.amount, - stable_amount, - )); + collateral_type: collateral_auction.currency_id, + collateral_amount: collateral_auction.amount, + turnover: stable_amount, + }); // break loop. break; @@ -698,13 +710,13 @@ impl Pallet { } let payment_amount = collateral_auction.payment_amount(bid_price); - Self::deposit_event(Event::CollateralAuctionDealt( + Self::deposit_event(Event::CollateralAuctionDealt { auction_id, - collateral_auction.currency_id, - collateral_auction.amount, - bidder, - payment_amount, - )); + collateral_type: collateral_auction.currency_id, + collateral_amount: collateral_auction.amount, + winner: bidder, + payment_amount: payment_amount, + }); } // decrement recipient account reference @@ -826,7 +838,12 @@ impl AuctionManager for Pallet { ); } - Self::deposit_event(Event::NewCollateralAuction(auction_id, currency_id, amount, target)); + Self::deposit_event(Event::NewCollateralAuction { + auction_id, + collateral_type: currency_id, + collateral_amount: amount, + target_bid_price: target, + }); Ok(()) } diff --git a/modules/auction-manager/src/tests.rs b/modules/auction-manager/src/tests.rs index 72bc5d76a7..c9270f1251 100644 --- a/modules/auction-manager/src/tests.rs +++ b/modules/auction-manager/src/tests.rs @@ -89,9 +89,12 @@ fn new_collateral_auction_work() { ); assert_ok!(AuctionManagerModule::new_collateral_auction(&ALICE, BTC, 10, 100)); - System::assert_last_event(Event::AuctionManagerModule(crate::Event::NewCollateralAuction( - 0, BTC, 10, 100, - ))); + System::assert_last_event(Event::AuctionManagerModule(crate::Event::NewCollateralAuction { + auction_id: 0, + collateral_type: BTC, + collateral_amount: 10, + target_bid_price: 100, + })); assert_eq!(AuctionManagerModule::total_collateral_in_auction(BTC), 10); assert_eq!(AuctionManagerModule::total_target_in_auction(), 100); @@ -201,9 +204,12 @@ fn collateral_auction_end_handler_without_bid() { assert!(AuctionManagerModule::collateral_auctions(0).is_some()); AuctionManagerModule::on_auction_ended(0, None); - System::assert_last_event(Event::AuctionManagerModule(crate::Event::DEXTakeCollateralAuction( - 0, BTC, 100, 500, - ))); + System::assert_last_event(Event::AuctionManagerModule(crate::Event::DEXTakeCollateralAuction { + auction_id: 0, + collateral_type: BTC, + collateral_amount: 100, + turnover: 500, + })); assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (200, 500)); assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 0); @@ -252,9 +258,12 @@ fn collateral_auction_end_handler_without_bid_and_swap_by_alternative_path() { assert_eq!(Tokens::free_balance(AUSD, &ALICE), 1000); AuctionManagerModule::on_auction_ended(0, None); - System::assert_last_event(Event::AuctionManagerModule(crate::Event::DEXTakeCollateralAuction( - 0, BTC, 100, 333, - ))); + System::assert_last_event(Event::AuctionManagerModule(crate::Event::DEXTakeCollateralAuction { + auction_id: 0, + collateral_type: BTC, + collateral_amount: 100, + turnover: 333, + })); assert_eq!(DEXModule::get_liquidity_pool(BTC, DOT), (200, 500)); assert_eq!(DEXModule::get_liquidity_pool(DOT, AUSD), (1500, 667)); @@ -282,9 +291,13 @@ fn collateral_auction_end_handler_in_reverse_stage() { assert!(AuctionManagerModule::collateral_auctions(0).is_some()); AuctionManagerModule::on_auction_ended(0, Some((BOB, 400))); - System::assert_last_event(Event::AuctionManagerModule(crate::Event::CollateralAuctionDealt( - 0, BTC, 50, BOB, 200, - ))); + System::assert_last_event(Event::AuctionManagerModule(crate::Event::CollateralAuctionDealt { + auction_id: 0, + collateral_type: BTC, + collateral_amount: 50, + winner: BOB, + payment_amount: 200, + })); assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 0); assert_eq!(AuctionManagerModule::collateral_auctions(0), None); @@ -320,9 +333,13 @@ fn collateral_auction_end_handler_by_dealing_which_target_not_zero() { assert!(AuctionManagerModule::collateral_auctions(0).is_some()); AuctionManagerModule::on_auction_ended(0, Some((BOB, 100))); - System::assert_last_event(Event::AuctionManagerModule(crate::Event::CollateralAuctionDealt( - 0, BTC, 100, BOB, 100, - ))); + System::assert_last_event(Event::AuctionManagerModule(crate::Event::CollateralAuctionDealt { + auction_id: 0, + collateral_type: BTC, + collateral_amount: 100, + winner: BOB, + payment_amount: 100, + })); assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 0); assert_eq!(AuctionManagerModule::collateral_auctions(0), None); @@ -370,9 +387,12 @@ fn collateral_auction_end_handler_by_dex_which_target_not_zero() { assert!(AuctionManagerModule::collateral_auctions(0).is_some()); AuctionManagerModule::on_auction_ended(0, Some((BOB, 20))); - System::assert_last_event(Event::AuctionManagerModule(crate::Event::DEXTakeCollateralAuction( - 0, BTC, 100, 500, - ))); + System::assert_last_event(Event::AuctionManagerModule(crate::Event::DEXTakeCollateralAuction { + auction_id: 0, + collateral_type: BTC, + collateral_amount: 100, + turnover: 500, + })); assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 0); assert_eq!(AuctionManagerModule::collateral_auctions(0), None); @@ -465,7 +485,9 @@ fn cancel_collateral_auction_work() { mock_shutdown(); assert_ok!(AuctionManagerModule::cancel(Origin::none(), 0)); - System::assert_last_event(Event::AuctionManagerModule(crate::Event::CancelAuction(0))); + System::assert_last_event(Event::AuctionManagerModule(crate::Event::CancelAuction { + auction_id: 0, + })); assert_eq!(Tokens::free_balance(AUSD, &BOB), 1000); assert_eq!(AuctionManagerModule::total_collateral_in_auction(BTC), 0); diff --git a/modules/cdp-engine/src/lib.rs b/modules/cdp-engine/src/lib.rs index 0f403c7a82..ffbe07be9b 100644 --- a/modules/cdp-engine/src/lib.rs +++ b/modules/cdp-engine/src/lib.rs @@ -231,33 +231,54 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// Liquidate the unsafe CDP. \[collateral_type, owner, - /// collateral_amount, bad_debt_value, liquidation_strategy\] - LiquidateUnsafeCDP(CurrencyId, T::AccountId, Balance, Balance, LiquidationStrategy), - /// Settle the CDP has debit. [collateral_type, owner] - SettleCDPInDebit(CurrencyId, T::AccountId), + /// Liquidate the unsafe CDP. + LiquidateUnsafeCDP { + collateral_type: CurrencyId, + owner: T::AccountId, + collateral_amount: Balance, + bad_debt_value: Balance, + liquidation_strategy: LiquidationStrategy, + }, + /// Settle the CDP has debit. + SettleCDPInDebit { + collateral_type: CurrencyId, + owner: T::AccountId, + }, /// Directly close CDP has debit by handle debit with DEX. - /// \[collateral_type, owner, sold_collateral_amount, - /// refund_collateral_amount, debit_value\] - CloseCDPInDebitByDEX(CurrencyId, T::AccountId, Balance, Balance, Balance), + CloseCDPInDebitByDEX { + collateral_type: CurrencyId, + owner: T::AccountId, + sold_collateral_amount: Balance, + refund_collateral_amount: Balance, + debit_value: Balance, + }, /// The interest rate per sec for specific collateral type updated. - /// \[collateral_type, new_interest_rate_per_sec\] - InterestRatePerSecUpdated(CurrencyId, Option), + InterestRatePerSecUpdated { + collateral_type: CurrencyId, + new_interest_rate_per_sec: Option, + }, /// The liquidation fee for specific collateral type updated. - /// \[collateral_type, new_liquidation_ratio\] - LiquidationRatioUpdated(CurrencyId, Option), + LiquidationRatioUpdated { + collateral_type: CurrencyId, + new_liquidation_ratio: Option, + }, /// The liquidation penalty rate for specific collateral type updated. - /// \[collateral_type, new_liquidation_panelty\] - LiquidationPenaltyUpdated(CurrencyId, Option), - /// The required collateral penalty rate for specific collateral type - /// updated. \[collateral_type, new_required_collateral_ratio\] - RequiredCollateralRatioUpdated(CurrencyId, Option), - /// The hard cap of total debit value for specific collateral type - /// updated. \[collateral_type, new_total_debit_value\] - MaximumTotalDebitValueUpdated(CurrencyId, Balance), - /// The global interest rate per sec for all types of collateral - /// updated. \[new_global_interest_rate_per_sec\] - GlobalInterestRatePerSecUpdated(Rate), + LiquidationPenaltyUpdated { + collateral_type: CurrencyId, + new_liquidation_penalty: Option, + }, + /// The required collateral penalty rate for specific collateral type updated. + RequiredCollateralRatioUpdated { + collateral_type: CurrencyId, + new_required_collateral_ratio: Option, + }, + /// The hard cap of total debit value for specific collateral type updated. + MaximumTotalDebitValueUpdated { + collateral_type: CurrencyId, + new_total_debit_value: Balance, + }, + /// The global interest rate per sec for all types of collateral updated. + GlobalInterestRatePerSecUpdated { new_global_interest_rate_per_sec: Rate }, } /// Mapping from collateral type to its exchange rate of debit units and @@ -432,7 +453,9 @@ pub mod module { pub fn set_global_params(origin: OriginFor, global_interest_rate_per_sec: Rate) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; GlobalInterestRatePerSec::::put(global_interest_rate_per_sec); - Self::deposit_event(Event::GlobalInterestRatePerSecUpdated(global_interest_rate_per_sec)); + Self::deposit_event(Event::GlobalInterestRatePerSecUpdated { + new_global_interest_rate_per_sec: global_interest_rate_per_sec, + }); Ok(()) } @@ -471,23 +494,38 @@ pub mod module { let mut collateral_params = Self::collateral_params(currency_id); if let Change::NewValue(update) = interest_rate_per_sec { collateral_params.interest_rate_per_sec = update; - Self::deposit_event(Event::InterestRatePerSecUpdated(currency_id, update)); + Self::deposit_event(Event::InterestRatePerSecUpdated { + collateral_type: currency_id, + new_interest_rate_per_sec: update, + }); } if let Change::NewValue(update) = liquidation_ratio { collateral_params.liquidation_ratio = update; - Self::deposit_event(Event::LiquidationRatioUpdated(currency_id, update)); + Self::deposit_event(Event::LiquidationRatioUpdated { + collateral_type: currency_id, + new_liquidation_ratio: update, + }); } if let Change::NewValue(update) = liquidation_penalty { collateral_params.liquidation_penalty = update; - Self::deposit_event(Event::LiquidationPenaltyUpdated(currency_id, update)); + Self::deposit_event(Event::LiquidationPenaltyUpdated { + collateral_type: currency_id, + new_liquidation_penalty: update, + }); } if let Change::NewValue(update) = required_collateral_ratio { collateral_params.required_collateral_ratio = update; - Self::deposit_event(Event::RequiredCollateralRatioUpdated(currency_id, update)); + Self::deposit_event(Event::RequiredCollateralRatioUpdated { + collateral_type: currency_id, + new_required_collateral_ratio: update, + }); } if let Change::NewValue(val) = maximum_total_debit_value { collateral_params.maximum_total_debit_value = val; - Self::deposit_event(Event::MaximumTotalDebitValueUpdated(currency_id, val)); + Self::deposit_event(Event::MaximumTotalDebitValueUpdated { + collateral_type: currency_id, + new_total_debit_value: val, + }); } CollateralParams::::insert(currency_id, collateral_params); Ok(()) @@ -817,7 +855,10 @@ impl Pallet { // confiscate collateral and all debit >::confiscate_collateral_and_debit(&who, currency_id, confiscate_collateral_amount, debit)?; - Self::deposit_event(Event::SettleCDPInDebit(currency_id, who)); + Self::deposit_event(Event::SettleCDPInDebit { + collateral_type: currency_id, + owner: who, + }); Ok(()) } @@ -888,13 +929,13 @@ impl Pallet { .expect("swap succecced means collateral >= actual_supply_collateral; qed"); ::CDPTreasury::withdraw_collateral(&who, currency_id, refund_collateral_amount)?; - Self::deposit_event(Event::CloseCDPInDebitByDEX( - currency_id, - who, - actual_supply_collateral, - refund_collateral_amount, + Self::deposit_event(Event::CloseCDPInDebitByDEX { + collateral_type: currency_id, + owner: who, + sold_collateral_amount: actual_supply_collateral, + refund_collateral_amount: refund_collateral_amount, debit_value, - )); + }); Ok(()) } @@ -973,13 +1014,13 @@ impl Pallet { }) })()?; - Self::deposit_event(Event::LiquidateUnsafeCDP( - currency_id, - who, - collateral, - bad_debt_value, - liquidation_strategy.clone(), - )); + Self::deposit_event(Event::LiquidateUnsafeCDP { + collateral_type: currency_id, + owner: who, + collateral_amount: collateral, + bad_debt_value: bad_debt_value, + liquidation_strategy: liquidation_strategy.clone(), + }); match liquidation_strategy { LiquidationStrategy::Auction { auction_count } => Ok(T::WeightInfo::liquidate_by_auction(auction_count)), LiquidationStrategy::Exchange => Ok(T::WeightInfo::liquidate_by_dex()), diff --git a/modules/cdp-engine/src/tests.rs b/modules/cdp-engine/src/tests.rs index a8fd1e3689..80f42e5249 100644 --- a/modules/cdp-engine/src/tests.rs +++ b/modules/cdp-engine/src/tests.rs @@ -152,9 +152,9 @@ fn set_global_params_work() { Origin::signed(1), Rate::saturating_from_rational(1, 10000), )); - System::assert_last_event(Event::CDPEngineModule(crate::Event::GlobalInterestRatePerSecUpdated( - Rate::saturating_from_rational(1, 10000), - ))); + System::assert_last_event(Event::CDPEngineModule(crate::Event::GlobalInterestRatePerSecUpdated { + new_global_interest_rate_per_sec: Rate::saturating_from_rational(1, 10000), + })); assert_eq!( CDPEngineModule::global_interest_rate_per_sec(), Rate::saturating_from_rational(1, 10000) @@ -200,25 +200,26 @@ fn set_collateral_params_work() { Change::NewValue(Some(Ratio::saturating_from_rational(9, 5))), Change::NewValue(10000), )); - System::assert_has_event(Event::CDPEngineModule(crate::Event::InterestRatePerSecUpdated( - BTC, - Some(Rate::saturating_from_rational(1, 100000)), - ))); - System::assert_has_event(Event::CDPEngineModule(crate::Event::LiquidationRatioUpdated( - BTC, - Some(Ratio::saturating_from_rational(3, 2)), - ))); - System::assert_has_event(Event::CDPEngineModule(crate::Event::LiquidationPenaltyUpdated( - BTC, - Some(Rate::saturating_from_rational(2, 10)), - ))); - System::assert_has_event(Event::CDPEngineModule(crate::Event::RequiredCollateralRatioUpdated( - BTC, - Some(Ratio::saturating_from_rational(9, 5)), - ))); - System::assert_has_event(Event::CDPEngineModule(crate::Event::MaximumTotalDebitValueUpdated( - BTC, 10000, - ))); + System::assert_has_event(Event::CDPEngineModule(crate::Event::InterestRatePerSecUpdated { + collateral_type: BTC, + new_interest_rate_per_sec: Some(Rate::saturating_from_rational(1, 100000)), + })); + System::assert_has_event(Event::CDPEngineModule(crate::Event::LiquidationRatioUpdated { + collateral_type: BTC, + new_liquidation_ratio: Some(Ratio::saturating_from_rational(3, 2)), + })); + System::assert_has_event(Event::CDPEngineModule(crate::Event::LiquidationPenaltyUpdated { + collateral_type: BTC, + new_liquidation_penalty: Some(Rate::saturating_from_rational(2, 10)), + })); + System::assert_has_event(Event::CDPEngineModule(crate::Event::RequiredCollateralRatioUpdated { + collateral_type: BTC, + new_required_collateral_ratio: Some(Ratio::saturating_from_rational(9, 5)), + })); + System::assert_has_event(Event::CDPEngineModule(crate::Event::MaximumTotalDebitValueUpdated { + collateral_type: BTC, + new_total_debit_value: 10000, + })); assert_ok!(CDPEngineModule::set_collateral_params( Origin::signed(1), @@ -457,13 +458,14 @@ fn liquidate_unsafe_cdp_by_collateral_auction() { Change::NoChange, )); assert_ok!(CDPEngineModule::liquidate_unsafe_cdp(ALICE, BTC)); - System::assert_last_event(Event::CDPEngineModule(crate::Event::LiquidateUnsafeCDP( - BTC, - ALICE, - 100, - 50, - LiquidationStrategy::Auction { auction_count: 1 }, - ))); + + System::assert_last_event(Event::CDPEngineModule(crate::Event::LiquidateUnsafeCDP { + collateral_type: BTC, + owner: ALICE, + collateral_amount: 100, + bad_debt_value: 50, + liquidation_strategy: LiquidationStrategy::Auction { auction_count: 1 }, + })); assert_eq!(CDPTreasuryModule::debit_pool(), 50); assert_eq!(Currencies::free_balance(BTC, &ALICE), 900); assert_eq!(Currencies::free_balance(AUSD, &ALICE), 50); @@ -523,13 +525,13 @@ fn liquidate_unsafe_cdp_by_collateral_auction_when_limited_by_slippage() { assert_eq!(DEXModule::get_swap_supply_amount(&[BTC, AUSD], 60), Some(99)); assert_eq!(DEXModule::get_swap_target_amount(&[BTC, AUSD], 100), Some(60)); assert_ok!(CDPEngineModule::liquidate_unsafe_cdp(ALICE, BTC)); - System::assert_last_event(Event::CDPEngineModule(crate::Event::LiquidateUnsafeCDP( - BTC, - ALICE, - 100, - 50, - LiquidationStrategy::Auction { auction_count: 1 }, - ))); + System::assert_last_event(Event::CDPEngineModule(crate::Event::LiquidateUnsafeCDP { + collateral_type: BTC, + owner: ALICE, + collateral_amount: 100, + bad_debt_value: 50, + liquidation_strategy: LiquidationStrategy::Auction { auction_count: 1 }, + })); assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (100, 121)); assert_eq!(CDPTreasuryModule::debit_pool(), 50); @@ -581,13 +583,13 @@ fn liquidate_unsafe_cdp_by_swap() { )); assert_ok!(CDPEngineModule::liquidate_unsafe_cdp(ALICE, BTC)); - System::assert_last_event(Event::CDPEngineModule(crate::Event::LiquidateUnsafeCDP( - BTC, - ALICE, - 100, - 50, - LiquidationStrategy::Exchange, - ))); + System::assert_last_event(Event::CDPEngineModule(crate::Event::LiquidateUnsafeCDP { + collateral_type: BTC, + owner: ALICE, + collateral_amount: 100, + bad_debt_value: 50, + liquidation_strategy: LiquidationStrategy::Exchange, + })); assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (199, 61)); assert_eq!(CDPTreasuryModule::debit_pool(), 50); @@ -771,7 +773,10 @@ fn settle_cdp_has_debit_work() { assert_eq!(CDPTreasuryModule::debit_pool(), 0); assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 0); assert_ok!(CDPEngineModule::settle_cdp_has_debit(ALICE, BTC)); - System::assert_last_event(Event::CDPEngineModule(crate::Event::SettleCDPInDebit(BTC, ALICE))); + System::assert_last_event(Event::CDPEngineModule(crate::Event::SettleCDPInDebit { + collateral_type: BTC, + owner: ALICE, + })); assert_eq!(LoansModule::positions(BTC, ALICE).debit, 0); assert_eq!(CDPTreasuryModule::debit_pool(), 50); assert_eq!(CDPTreasuryModule::total_collaterals(BTC), 50); @@ -862,9 +867,13 @@ fn close_cdp_has_debit_by_dex_work() { assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (100, 1000)); assert_ok!(CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 6, None)); - System::assert_last_event(Event::CDPEngineModule(crate::Event::CloseCDPInDebitByDEX( - BTC, ALICE, 6, 94, 50, - ))); + System::assert_last_event(Event::CDPEngineModule(crate::Event::CloseCDPInDebitByDEX { + collateral_type: BTC, + owner: ALICE, + sold_collateral_amount: 6, + refund_collateral_amount: 94, + debit_value: 50, + })); assert_eq!(DEXModule::get_liquidity_pool(BTC, AUSD), (106, 950)); assert_eq!(Currencies::free_balance(BTC, &ALICE), 994); @@ -928,9 +937,13 @@ fn close_cdp_has_debit_by_swap_on_alternative_path() { Change::NoChange, )); assert_ok!(CDPEngineModule::close_cdp_has_debit_by_dex(ALICE, BTC, 100, None)); - System::assert_last_event(Event::CDPEngineModule(crate::Event::CloseCDPInDebitByDEX( - BTC, ALICE, 6, 94, 50, - ))); + System::assert_last_event(Event::CDPEngineModule(crate::Event::CloseCDPInDebitByDEX { + collateral_type: BTC, + owner: ALICE, + sold_collateral_amount: 6, + refund_collateral_amount: 94, + debit_value: 50, + })); assert_eq!(DEXModule::get_liquidity_pool(BTC, ACA), (106, 947)); assert_eq!(DEXModule::get_liquidity_pool(ACA, AUSD), (1053, 950)); diff --git a/modules/homa-lite/src/lib.rs b/modules/homa-lite/src/lib.rs index 91c5a87b8c..f56f64b8ee 100644 --- a/modules/homa-lite/src/lib.rs +++ b/modules/homa-lite/src/lib.rs @@ -184,25 +184,22 @@ pub mod module { amount_minted: Balance, }, - /// The total amount of the staking currency on the relaychain has been - /// set.\[total_staking_currency\] + /// The total amount of the staking currency on the relaychain has been set. TotalStakingCurrencySet { total_staking_currency: Balance }, - /// The mint cap for Staking currency is updated.\[new_cap\] + /// The mint cap for Staking currency is updated. StakingCurrencyMintCapUpdated { new_cap: Balance }, - /// A new weight for XCM transfers has been set.\[new_weight\] + /// A new weight for XCM transfers has been set. XcmDestWeightSet { new_weight: Weight }, /// The redeem request has been cancelled, and funds un-reserved. - /// \[who, liquid_amount_unreserved\] RedeemRequestCancelled { who: T::AccountId, liquid_amount_unreserved: Balance, }, /// A new Redeem request has been registered. - /// \[who, liquid_amount, extra_fee, withdraw_fee_paid\] RedeemRequested { who: T::AccountId, liquid_amount: Balance, @@ -211,7 +208,6 @@ pub mod module { }, /// The user has redeemed some Liquid currency back to Staking currency. - /// \[who, staking_amount_redeemed, liquid_amount_deducted\] Redeemed { who: T::AccountId, staking_amount_redeemed: Balance, @@ -219,7 +215,6 @@ pub mod module { }, /// A new Unbond request added to the schedule. - /// \[staking_amount, relaychain_blocknumber\] ScheduledUnbondAdded { staking_amount: Balance, relaychain_blocknumber: RelayChainBlockNumberOf, @@ -229,15 +224,12 @@ pub mod module { ScheduledUnbondReplaced, /// The scheduled Unbond has been withdrew from the RelayChain. - ///\[staking_amount_added\] ScheduledUnbondWithdrew { staking_amount_added: Balance }, /// Interest rate for TotalStakingCurrency is set - /// \[interest_rate\] StakingInterestRatePerUpdateSet { interest_rate: Permill }, /// The amount of the staking currency available to be redeemed is set. - /// \[total_available_staking_balance\] AvailableStakingBalanceSet { total_available_staking_balance: Balance }, } diff --git a/runtime/integration-tests/src/honzon.rs b/runtime/integration-tests/src/honzon.rs index 4537ef7802..47070348b8 100644 --- a/runtime/integration-tests/src/honzon.rs +++ b/runtime/integration-tests/src/honzon.rs @@ -183,13 +183,13 @@ fn liquidate_cdp() { RELAY_CHAIN_CURRENCY )); - let liquidate_alice_xbtc_cdp_event = Event::CdpEngine(module_cdp_engine::Event::LiquidateUnsafeCDP( - RELAY_CHAIN_CURRENCY, - AccountId::from(ALICE), - 50 * dollar(RELAY_CHAIN_CURRENCY), - 250_000 * dollar(USD_CURRENCY), - LiquidationStrategy::Auction { auction_count: 1 }, - )); + let liquidate_alice_xbtc_cdp_event = Event::CdpEngine(module_cdp_engine::Event::LiquidateUnsafeCDP { + collateral_type: RELAY_CHAIN_CURRENCY, + owner: AccountId::from(ALICE), + collateral_amount: 50 * dollar(RELAY_CHAIN_CURRENCY), + bad_debt_value: 250_000 * dollar(USD_CURRENCY), + liquidation_strategy: LiquidationStrategy::Auction { auction_count: 1 }, + }); assert!(System::events() .iter() @@ -208,13 +208,14 @@ fn liquidate_cdp() { RELAY_CHAIN_CURRENCY )); - let liquidate_bob_xbtc_cdp_event = Event::CdpEngine(module_cdp_engine::Event::LiquidateUnsafeCDP( - RELAY_CHAIN_CURRENCY, - AccountId::from(BOB), - dollar(RELAY_CHAIN_CURRENCY), - 5_000 * dollar(USD_CURRENCY), - LiquidationStrategy::Exchange, - )); + let liquidate_bob_xbtc_cdp_event = Event::CdpEngine(module_cdp_engine::Event::LiquidateUnsafeCDP { + collateral_type: RELAY_CHAIN_CURRENCY, + owner: AccountId::from(BOB), + collateral_amount: dollar(RELAY_CHAIN_CURRENCY), + bad_debt_value: 5_000 * dollar(USD_CURRENCY), + liquidation_strategy: LiquidationStrategy::Exchange, + }); + assert!(System::events() .iter() .any(|record| record.event == liquidate_bob_xbtc_cdp_event)); @@ -420,10 +421,10 @@ fn test_cdp_engine_module() { RELAY_CHAIN_CURRENCY )); - let settle_cdp_in_debit_event = Event::CdpEngine(module_cdp_engine::Event::SettleCDPInDebit( - RELAY_CHAIN_CURRENCY, - AccountId::from(ALICE), - )); + let settle_cdp_in_debit_event = Event::CdpEngine(module_cdp_engine::Event::SettleCDPInDebit { + collateral_type: RELAY_CHAIN_CURRENCY, + owner: AccountId::from(ALICE), + }); assert!(System::events() .iter() .any(|record| record.event == settle_cdp_in_debit_event)); From ec0f1e6cdf8bd68e7d9151625ab5c666bcb1c059 Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Thu, 16 Dec 2021 18:30:48 +1300 Subject: [PATCH 03/13] refactored events for: asset-registry cdp-treasury collator-selection currencies dex emergency-shutdown evm-accounts evm-bridge evm example homa-validator-list honzon idle-scheduler incentives --- modules/asset-registry/src/mock.rs | 10 +- modules/cdp-treasury/src/lib.rs | 14 +- modules/cdp-treasury/src/tests.rs | 5 +- modules/collator-selection/src/lib.rs | 41 ++-- modules/currencies/src/lib.rs | 79 +++++-- modules/currencies/src/mock.rs | 10 +- modules/currencies/src/tests.rs | 48 ++-- modules/dex/src/lib.rs | 145 +++++++----- modules/dex/src/tests.rs | 146 ++++++------ modules/emergency-shutdown/src/lib.rs | 26 +- modules/emergency-shutdown/src/tests.rs | 8 +- modules/evm-accounts/src/lib.rs | 15 +- modules/evm-accounts/src/tests.rs | 8 +- modules/evm-bridge/src/mock.rs | 10 +- modules/evm/src/lib.rs | 78 +++--- modules/evm/src/runner/stack.rs | 74 +++--- modules/evm/src/tests.rs | 25 +- modules/example/src/lib.rs | 4 +- modules/homa-validator-list/src/lib.rs | 72 ++++-- modules/homa-validator-list/src/tests.rs | 110 ++++----- modules/honzon/src/lib.rs | 32 ++- modules/honzon/src/tests.rs | 16 +- modules/idle-scheduler/src/lib.rs | 7 +- modules/incentives/src/lib.rs | 81 +++++-- modules/incentives/src/tests.rs | 222 +++++++++--------- runtime/integration-tests/src/dex.rs | 16 +- runtime/integration-tests/src/evm.rs | 51 ++-- .../src/benchmarking/collator_selection.rs | 12 +- runtime/mandala/src/benchmarking/dex.rs | 10 +- runtime/mandala/src/benchmarking/evm.rs | 10 +- 30 files changed, 842 insertions(+), 543 deletions(-) diff --git a/modules/asset-registry/src/mock.rs b/modules/asset-registry/src/mock.rs index 6a93478f71..aab81bc686 100644 --- a/modules/asset-registry/src/mock.rs +++ b/modules/asset-registry/src/mock.rs @@ -179,10 +179,10 @@ pub fn deploy_contracts() { let code = from_hex(include!("../../evm-bridge/src/erc20_demo_contract")).unwrap(); assert_ok!(EVM::create(Origin::signed(alice()), code, 0, 2_100_000, 10000)); - System::assert_last_event(Event::EVM(module_evm::Event::Created( - alice_evm_addr(), - erc20_address(), - vec![module_evm::Log { + System::assert_last_event(Event::EVM(module_evm::Event::Created { + from: alice_evm_addr(), + contract: erc20_address(), + logs: vec![module_evm::Log { address: H160::from_str("0x5dddfce53ee040d9eb21afbc0ae1bb4dbb0ba643").unwrap(), topics: vec![ H256::from_str("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef").unwrap(), @@ -191,7 +191,7 @@ pub fn deploy_contracts() { ], data: H256::from_low_u64_be(10000).as_bytes().to_vec(), }], - ))); + })); assert_ok!(EVM::deploy_free(Origin::signed(CouncilAccount::get()), erc20_address())); } diff --git a/modules/cdp-treasury/src/lib.rs b/modules/cdp-treasury/src/lib.rs index eb06b77b45..b41b8cf860 100644 --- a/modules/cdp-treasury/src/lib.rs +++ b/modules/cdp-treasury/src/lib.rs @@ -104,9 +104,12 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] pub enum Event { - /// The expected amount size for per lot collateral auction of specific - /// collateral type updated. \[collateral_type, new_size\] - ExpectedCollateralAuctionSizeUpdated(CurrencyId, Balance), + /// The expected amount size for per lot collateral auction of specific collateral type + /// updated. + ExpectedCollateralAuctionSizeUpdated { + collateral_type: CurrencyId, + new_size: Balance, + }, } /// The expected amount size for per lot collateral auction of specific @@ -205,7 +208,10 @@ pub mod module { ) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; ExpectedCollateralAuctionSize::::insert(currency_id, size); - Self::deposit_event(Event::ExpectedCollateralAuctionSizeUpdated(currency_id, size)); + Self::deposit_event(Event::ExpectedCollateralAuctionSizeUpdated { + collateral_type: currency_id, + new_size: size, + }); Ok(()) } } diff --git a/modules/cdp-treasury/src/tests.rs b/modules/cdp-treasury/src/tests.rs index 7d0dd77767..e16e122ce9 100644 --- a/modules/cdp-treasury/src/tests.rs +++ b/modules/cdp-treasury/src/tests.rs @@ -406,7 +406,10 @@ fn set_expected_collateral_auction_size_work() { 200 )); System::assert_last_event(Event::CDPTreasuryModule( - crate::Event::ExpectedCollateralAuctionSizeUpdated(BTC, 200), + crate::Event::ExpectedCollateralAuctionSizeUpdated { + collateral_type: BTC, + new_size: 200, + }, )); }); } diff --git a/modules/collator-selection/src/lib.rs b/modules/collator-selection/src/lib.rs index ca4d9e55e6..8a40e948bc 100644 --- a/modules/collator-selection/src/lib.rs +++ b/modules/collator-selection/src/lib.rs @@ -260,16 +260,16 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// Invulnurable was updated. \[new_invulnerables\] - NewInvulnerables(Vec), - /// Desired candidates was updated. \[new_desired_candidates\] - NewDesiredCandidates(u32), - /// Candidacy bond was updated. \[new_candidacy_bond\] - NewCandidacyBond(BalanceOf), - /// A candidate was added. \[who, bond\] - CandidateAdded(T::AccountId, BalanceOf), - /// A candidate was removed. \[who\] - CandidateRemoved(T::AccountId), + /// Invulnurable was updated. + NewInvulnerables { new_invulnerables: Vec }, + /// Desired candidates was updated. + NewDesiredCandidates { new_desired_candidates: u32 }, + /// Candidacy bond was updated. + NewCandidacyBond { new_candidacy_bond: BalanceOf }, + /// A candidate was added. + CandidateAdded { who: T::AccountId, bond: BalanceOf }, + /// A candidate was removed. + CandidateRemoved { who: T::AccountId }, } // Errors inform users that something went wrong. @@ -301,7 +301,9 @@ pub mod pallet { let bounded_new: BoundedVec = new.try_into().map_err(|_| Error::::MaxInvulnerablesExceeded)?; >::put(&bounded_new); - Self::deposit_event(Event::NewInvulnerables(bounded_new.into_inner())); + Self::deposit_event(Event::NewInvulnerables { + new_invulnerables: bounded_new.into_inner(), + }); Ok(()) } @@ -312,7 +314,9 @@ pub mod pallet { Err(Error::::MaxCandidatesExceeded)?; } >::put(&max); - Self::deposit_event(Event::NewDesiredCandidates(max)); + Self::deposit_event(Event::NewDesiredCandidates { + new_desired_candidates: max, + }); Ok(()) } @@ -320,7 +324,9 @@ pub mod pallet { pub fn set_candidacy_bond(origin: OriginFor, #[pallet::compact] bond: BalanceOf) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; >::put(&bond); - Self::deposit_event(Event::NewCandidacyBond(bond)); + Self::deposit_event(Event::NewCandidacyBond { + new_candidacy_bond: bond, + }); Ok(()) } @@ -337,7 +343,7 @@ pub mod pallet { let deposit = Self::candidacy_bond(); let bounded_candidates_len = Self::do_register_candidate(&who, deposit)?; - Self::deposit_event(Event::CandidateAdded(who, deposit)); + Self::deposit_event(Event::CandidateAdded { who, bond: deposit }); Ok(Some(T::WeightInfo::register_as_candidate(bounded_candidates_len as u32)).into()) } @@ -348,7 +354,10 @@ pub mod pallet { let bounded_candidates_len = Self::do_register_candidate(&new_candidate, Zero::zero())?; - Self::deposit_event(Event::CandidateAdded(new_candidate, Zero::zero())); + Self::deposit_event(Event::CandidateAdded { + who: new_candidate, + bond: Zero::zero(), + }); Ok(Some(T::WeightInfo::register_candidate(bounded_candidates_len as u32)).into()) } @@ -396,7 +405,7 @@ pub mod pallet { candidates.take(who).ok_or(Error::::NotCandidate)?; Ok(candidates.len()) })?; - Self::deposit_event(Event::CandidateRemoved(who.clone())); + Self::deposit_event(Event::CandidateRemoved { who: who.clone() }); Ok(current_count) } diff --git a/modules/currencies/src/lib.rs b/modules/currencies/src/lib.rs index 1f87b6f6e3..f0d36fe350 100644 --- a/modules/currencies/src/lib.rs +++ b/modules/currencies/src/lib.rs @@ -113,16 +113,37 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// Currency transfer success. \[currency_id, from, to, amount\] - Transferred(CurrencyIdOf, T::AccountId, T::AccountId, BalanceOf), - /// Update balance success. \[currency_id, who, amount\] - BalanceUpdated(CurrencyIdOf, T::AccountId, AmountOf), - /// Deposit success. \[currency_id, who, amount\] - Deposited(CurrencyIdOf, T::AccountId, BalanceOf), - /// Withdraw success. \[currency_id, who, amount\] - Withdrawn(CurrencyIdOf, T::AccountId, BalanceOf), - /// Dust swept. \[currency_id, who, amount\] - DustSwept(CurrencyIdOf, T::AccountId, BalanceOf), + /// Currency transfer success. + Transferred { + currency_id: CurrencyIdOf, + from: T::AccountId, + to: T::AccountId, + amount: BalanceOf, + }, + /// Update balance success. + BalanceUpdated { + currency_id: CurrencyIdOf, + who: T::AccountId, + amount: AmountOf, + }, + /// Deposit success. + Deposited { + currency_id: CurrencyIdOf, + who: T::AccountId, + amount: BalanceOf, + }, + /// Withdraw success. + Withdrawn { + currency_id: CurrencyIdOf, + who: T::AccountId, + amount: BalanceOf, + }, + /// Dust swept. + DustSwept { + currency_id: CurrencyIdOf, + who: T::AccountId, + amount: BalanceOf, + }, } #[pallet::pallet] @@ -164,7 +185,12 @@ pub mod module { let to = T::Lookup::lookup(dest)?; T::NativeCurrency::transfer(&from, &to, amount)?; - Self::deposit_event(Event::Transferred(T::GetNativeCurrencyId::get(), from, to, amount)); + Self::deposit_event(Event::Transferred { + currency_id: T::GetNativeCurrencyId::get(), + from, + to, + amount, + }); Ok(()) } @@ -205,7 +231,11 @@ pub mod module { } if free_balance < Self::minimum_balance(currency_id) { T::OnDust::on_dust(&account, currency_id, free_balance); - Self::deposit_event(Event::DustSwept(currency_id, account, free_balance)); + Self::deposit_event(Event::DustSwept { + currency_id, + who: account, + amount: free_balance, + }); } } Ok(()) @@ -325,7 +355,12 @@ impl MultiCurrency for Pallet { _ => T::MultiCurrency::transfer(currency_id, from, to, amount)?, } - Self::deposit_event(Event::Transferred(currency_id, from.clone(), to.clone(), amount)); + Self::deposit_event(Event::Transferred { + currency_id, + from: from.clone(), + to: to.clone(), + amount, + }); Ok(()) } @@ -338,7 +373,11 @@ impl MultiCurrency for Pallet { id if id == T::GetNativeCurrencyId::get() => T::NativeCurrency::deposit(who, amount)?, _ => T::MultiCurrency::deposit(currency_id, who, amount)?, } - Self::deposit_event(Event::Deposited(currency_id, who.clone(), amount)); + Self::deposit_event(Event::Deposited { + currency_id, + who: who.clone(), + amount, + }); Ok(()) } @@ -351,7 +390,11 @@ impl MultiCurrency for Pallet { id if id == T::GetNativeCurrencyId::get() => T::NativeCurrency::withdraw(who, amount)?, _ => T::MultiCurrency::withdraw(currency_id, who, amount)?, } - Self::deposit_event(Event::Withdrawn(currency_id, who.clone(), amount)); + Self::deposit_event(Event::Withdrawn { + currency_id, + who: who.clone(), + amount, + }); Ok(()) } @@ -381,7 +424,11 @@ impl MultiCurrencyExtended for Pallet { id if id == T::GetNativeCurrencyId::get() => T::NativeCurrency::update_balance(who, by_amount)?, _ => T::MultiCurrency::update_balance(currency_id, who, by_amount)?, } - Self::deposit_event(Event::BalanceUpdated(currency_id, who.clone(), by_amount)); + Self::deposit_event(Event::BalanceUpdated { + currency_id, + who: who.clone(), + amount: by_amount, + }); Ok(()) } } diff --git a/modules/currencies/src/mock.rs b/modules/currencies/src/mock.rs index 56e0243e31..abfe994830 100644 --- a/modules/currencies/src/mock.rs +++ b/modules/currencies/src/mock.rs @@ -254,10 +254,10 @@ pub fn deploy_contracts() { let code = from_hex(include!("../../evm-bridge/src/erc20_demo_contract")).unwrap(); assert_ok!(EVM::create(Origin::signed(alice()), code, 0, 2_100_000, 10000)); - System::assert_last_event(Event::EVM(module_evm::Event::Created( - alice_evm_addr(), - erc20_address(), - vec![module_evm::Log { + System::assert_last_event(Event::EVM(module_evm::Event::Created { + from: alice_evm_addr(), + contract: erc20_address(), + logs: vec![module_evm::Log { address: H160::from_str("0x5dddfce53ee040d9eb21afbc0ae1bb4dbb0ba643").unwrap(), topics: vec![ H256::from_str("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef").unwrap(), @@ -266,7 +266,7 @@ pub fn deploy_contracts() { ], data: H256::from_low_u64_be(10000).as_bytes().to_vec(), }], - ))); + })); assert_ok!(EVM::deploy_free(Origin::signed(CouncilAccount::get()), erc20_address())); } diff --git a/modules/currencies/src/tests.rs b/modules/currencies/src/tests.rs index 8577e92a5a..502a528450 100644 --- a/modules/currencies/src/tests.rs +++ b/modules/currencies/src/tests.rs @@ -299,12 +299,12 @@ fn call_event_should_work() { assert_ok!(Currencies::transfer(Some(alice()).into(), bob(), X_TOKEN_ID, 50)); assert_eq!(Currencies::free_balance(X_TOKEN_ID, &alice()), 50); assert_eq!(Currencies::free_balance(X_TOKEN_ID, &bob()), 150); - System::assert_last_event(Event::Currencies(crate::Event::Transferred( - X_TOKEN_ID, - alice(), - bob(), - 50, - ))); + System::assert_last_event(Event::Currencies(crate::Event::Transferred { + currency_id: X_TOKEN_ID, + from: alice(), + to: bob(), + amount: 50, + })); assert_ok!(>::transfer( X_TOKEN_ID, @@ -314,12 +314,12 @@ fn call_event_should_work() { )); assert_eq!(Currencies::free_balance(X_TOKEN_ID, &alice()), 40); assert_eq!(Currencies::free_balance(X_TOKEN_ID, &bob()), 160); - System::assert_last_event(Event::Currencies(crate::Event::Transferred( - X_TOKEN_ID, - alice(), - bob(), - 10, - ))); + System::assert_last_event(Event::Currencies(crate::Event::Transferred { + currency_id: X_TOKEN_ID, + from: alice(), + to: bob(), + amount: 10, + })); assert_ok!(>::deposit( X_TOKEN_ID, @@ -327,7 +327,11 @@ fn call_event_should_work() { 100 )); assert_eq!(Currencies::free_balance(X_TOKEN_ID, &alice()), 140); - System::assert_last_event(Event::Currencies(crate::Event::Deposited(X_TOKEN_ID, alice(), 100))); + System::assert_last_event(Event::Currencies(crate::Event::Deposited { + currency_id: X_TOKEN_ID, + who: alice(), + amount: 100, + })); assert_ok!(>::withdraw( X_TOKEN_ID, @@ -335,7 +339,11 @@ fn call_event_should_work() { 20 )); assert_eq!(Currencies::free_balance(X_TOKEN_ID, &alice()), 120); - System::assert_last_event(Event::Currencies(crate::Event::Withdrawn(X_TOKEN_ID, alice(), 20))); + System::assert_last_event(Event::Currencies(crate::Event::Withdrawn { + currency_id: X_TOKEN_ID, + who: alice(), + amount: 20, + })); }); } @@ -890,7 +898,11 @@ fn sweep_dust_tokens_works() { DOT, accounts )); - System::assert_last_event(Event::Currencies(crate::Event::DustSwept(DOT, bob(), 1))); + System::assert_last_event(Event::Currencies(crate::Event::DustSwept { + currency_id: DOT, + who: bob(), + amount: 1, + })); // bob's account is gone assert_eq!(tokens::Accounts::::contains_key(bob(), DOT), false); @@ -965,7 +977,11 @@ fn sweep_dust_native_currency_works() { NATIVE_CURRENCY_ID, accounts )); - System::assert_last_event(Event::Currencies(crate::Event::DustSwept(NATIVE_CURRENCY_ID, bob(), 1))); + System::assert_last_event(Event::Currencies(crate::Event::DustSwept { + currency_id: NATIVE_CURRENCY_ID, + who: bob(), + amount: 1, + })); // bob's account is gone assert_eq!(System::account_exists(&bob()), false); diff --git a/modules/dex/src/lib.rs b/modules/dex/src/lib.rs index 748b6c7583..9026593e1f 100644 --- a/modules/dex/src/lib.rs +++ b/modules/dex/src/lib.rs @@ -173,28 +173,51 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// add provision success \[who, currency_id_0, contribution_0, - /// currency_id_1, contribution_1\] - AddProvision(T::AccountId, CurrencyId, Balance, CurrencyId, Balance), - /// Add liquidity success. \[who, currency_id_0, pool_0_increment, - /// currency_id_1, pool_1_increment, share_increment\] - AddLiquidity(T::AccountId, CurrencyId, Balance, CurrencyId, Balance, Balance), - /// Remove liquidity from the trading pool success. \[who, - /// currency_id_0, pool_0_decrement, currency_id_1, pool_1_decrement, - /// share_decrement\] - RemoveLiquidity(T::AccountId, CurrencyId, Balance, CurrencyId, Balance, Balance), - /// Use supply currency to swap target currency. \[trader, trading_path, - /// liquidity_change_list\] - Swap(T::AccountId, Vec, Vec), - /// Enable trading pair. \[trading_pair\] - EnableTradingPair(TradingPair), - /// List provisioning trading pair. \[trading_pair\] - ListProvisioning(TradingPair), - /// Disable trading pair. \[trading_pair\] - DisableTradingPair(TradingPair), - /// Provisioning trading pair convert to Enabled. \[trading_pair, - /// pool_0_amount, pool_1_amount, total_share_amount\] - ProvisioningToEnabled(TradingPair, Balance, Balance, Balance), + /// add provision success + AddProvision { + who: T::AccountId, + currency_0: CurrencyId, + contribution_0: Balance, + currency_1: CurrencyId, + contribution_1: Balance, + }, + /// Add liquidity success. + AddLiquidity { + who: T::AccountId, + currency_0: CurrencyId, + pool_0: Balance, + currency_1: CurrencyId, + pool_1: Balance, + share_increment: Balance, + }, + /// Remove liquidity from the trading pool success. + RemoveLiquidity { + who: T::AccountId, + currency_0: CurrencyId, + pool_0: Balance, + currency_1: CurrencyId, + pool_1: Balance, + share_decrement: Balance, + }, + /// Use supply currency to swap target currency. + Swap { + trader: T::AccountId, + path: Vec, + liquidity_changes: Vec, + }, + /// Enable trading pair. + EnableTradingPair { trading_pair: TradingPair }, + /// List provisioning trading pair. + ListProvisioning { trading_pair: TradingPair }, + /// Disable trading pair. + DisableTradingPair { trading_pair: TradingPair }, + /// Provisioning trading pair convert to Enabled. + ProvisioningToEnabled { + trading_pair: TradingPair, + pool_0: Balance, + pool_1: Balance, + share_amount: Balance, + }, } /// Liquidity pool for TradingPair. @@ -514,7 +537,9 @@ pub mod module { not_before, }), ); - Self::deposit_event(Event::ListProvisioning(trading_pair)); + Self::deposit_event(Event::ListProvisioning { + trading_pair: trading_pair, + }); Ok(()) } @@ -629,12 +654,12 @@ pub mod module { (share_exchange_rate_0, share_exchange_rate_1), ); - Self::deposit_event(Event::ProvisioningToEnabled( + Self::deposit_event(Event::ProvisioningToEnabled { trading_pair, - total_provision_0, - total_provision_1, - total_shares_to_issue, - )); + pool_0: total_provision_0, + pool_1: total_provision_1, + share_amount: total_shares_to_issue, + }); } _ => return Err(Error::::MustBeProvisioning.into()), } @@ -668,7 +693,9 @@ pub mod module { } TradingPairStatuses::::insert(trading_pair, TradingPairStatus::Enabled); - Self::deposit_event(Event::EnableTradingPair(trading_pair)); + Self::deposit_event(Event::EnableTradingPair { + trading_pair: trading_pair, + }); Ok(()) } @@ -692,7 +719,7 @@ pub mod module { ); TradingPairStatuses::::insert(trading_pair, TradingPairStatus::Disabled); - Self::deposit_event(Event::DisableTradingPair(trading_pair)); + Self::deposit_event(Event::DisableTradingPair { trading_pair }); Ok(()) } } @@ -813,13 +840,13 @@ impl Pallet { TradingPairStatus::<_, _>::Provisioning(provision_parameters), ); - Self::deposit_event(Event::AddProvision( - who.clone(), - trading_pair.first(), - contribution_0, - trading_pair.second(), - contribution_1, - )); + Self::deposit_event(Event::AddProvision { + who: who.clone(), + currency_0: trading_pair.first(), + contribution_0: contribution_0, + currency_1: trading_pair.second(), + contribution_1: contribution_1, + }); Ok(()) }) } @@ -926,14 +953,14 @@ impl Pallet { T::DEXIncentives::do_deposit_dex_share(who, dex_share_currency_id, share_increment)?; } - Self::deposit_event(Event::AddLiquidity( - who.clone(), - trading_pair.first(), - pool_0_increment, - trading_pair.second(), - pool_1_increment, - share_increment, - )); + Self::deposit_event(Event::AddLiquidity { + who: who.clone(), + currency_0: trading_pair.first(), + pool_0: pool_0_increment, + currency_1: trading_pair.second(), + pool_1: pool_1_increment, + share_increment: share_increment, + }); Ok(()) }) } @@ -983,14 +1010,14 @@ impl Pallet { *pool_0 = pool_0.checked_sub(pool_0_decrement).ok_or(ArithmeticError::Underflow)?; *pool_1 = pool_1.checked_sub(pool_1_decrement).ok_or(ArithmeticError::Underflow)?; - Self::deposit_event(Event::RemoveLiquidity( - who.clone(), - trading_pair.first(), - pool_0_decrement, - trading_pair.second(), - pool_1_decrement, - remove_share, - )); + Self::deposit_event(Event::RemoveLiquidity { + who: who.clone(), + currency_0: trading_pair.first(), + pool_0: pool_0_decrement, + currency_1: trading_pair.second(), + pool_1: pool_1_decrement, + share_decrement: remove_share, + }); Ok(()) }) } @@ -1191,7 +1218,11 @@ impl Pallet { Self::_swap_by_path(path, &amounts)?; T::Currency::transfer(path[path.len() - 1], &module_account_id, who, actual_target_amount)?; - Self::deposit_event(Event::Swap(who.clone(), path.to_vec(), amounts)); + Self::deposit_event(Event::Swap { + trader: who.clone(), + path: path.to_vec(), + liquidity_changes: amounts, + }); Ok(actual_target_amount) } @@ -1212,7 +1243,11 @@ impl Pallet { Self::_swap_by_path(path, &amounts)?; T::Currency::transfer(path[path.len() - 1], &module_account_id, who, target_amount)?; - Self::deposit_event(Event::Swap(who.clone(), path.to_vec(), amounts)); + Self::deposit_event(Event::Swap { + trader: who.clone(), + path: path.to_vec(), + liquidity_changes: amounts, + }); Ok(actual_supply_amount) } } diff --git a/modules/dex/src/tests.rs b/modules/dex/src/tests.rs index dd03d26460..d79fcaf91e 100644 --- a/modules/dex/src/tests.rs +++ b/modules/dex/src/tests.rs @@ -71,7 +71,9 @@ fn list_provisioning_work() { not_before: 10, }) ); - System::assert_last_event(Event::DexModule(crate::Event::ListProvisioning(AUSDDOTPair::get()))); + System::assert_last_event(Event::DexModule(crate::Event::ListProvisioning { + trading_pair: AUSDDOTPair::get(), + })); assert_noop!( DexModule::list_provisioning( @@ -201,7 +203,9 @@ fn enable_diabled_trading_pair_work() { DexModule::trading_pair_statuses(AUSDDOTPair::get()), TradingPairStatus::<_, _>::Enabled ); - System::assert_last_event(Event::DexModule(crate::Event::EnableTradingPair(AUSDDOTPair::get()))); + System::assert_last_event(Event::DexModule(crate::Event::EnableTradingPair { + trading_pair: AUSDDOTPair::get(), + })); assert_noop!( DexModule::enable_trading_pair(Origin::signed(ListingOrigin::get()), DOT, AUSD), @@ -261,7 +265,9 @@ fn enable_provisioning_without_provision_work() { DexModule::trading_pair_statuses(AUSDDOTPair::get()), TradingPairStatus::<_, _>::Enabled ); - System::assert_last_event(Event::DexModule(crate::Event::EnableTradingPair(AUSDDOTPair::get()))); + System::assert_last_event(Event::DexModule(crate::Event::EnableTradingPair { + trading_pair: AUSDDOTPair::get(), + })); assert_noop!( DexModule::enable_trading_pair(Origin::signed(ListingOrigin::get()), AUSD, BTC), @@ -344,12 +350,12 @@ fn end_provisioning_trading_work() { AUSD, BTC )); - System::assert_last_event(Event::DexModule(crate::Event::ProvisioningToEnabled( - AUSDBTCPair::get(), - 1_000_000_000_000u128, - 2_000_000_000_000u128, - 2_000_000_000_000u128, - ))); + System::assert_last_event(Event::DexModule(crate::Event::ProvisioningToEnabled { + trading_pair: AUSDBTCPair::get(), + pool_0: 1_000_000_000_000u128, + pool_1: 2_000_000_000_000u128, + share_amount: 2_000_000_000_000u128, + })); assert_eq!( DexModule::trading_pair_statuses(AUSDBTCPair::get()), TradingPairStatus::<_, _>::Enabled @@ -402,7 +408,9 @@ fn disable_trading_pair_work() { DexModule::trading_pair_statuses(AUSDDOTPair::get()), TradingPairStatus::<_, _>::Disabled ); - System::assert_last_event(Event::DexModule(crate::Event::DisableTradingPair(AUSDDOTPair::get()))); + System::assert_last_event(Event::DexModule(crate::Event::DisableTradingPair { + trading_pair: AUSDDOTPair::get(), + })); assert_noop!( DexModule::disable_trading_pair(Origin::signed(ListingOrigin::get()), AUSD, DOT), @@ -509,13 +517,13 @@ fn add_provision_work() { assert_eq!(Tokens::free_balance(DOT, &DexModule::account_id()), 0); let alice_ref_count_1 = System::consumers(&ALICE); assert_eq!(alice_ref_count_1, alice_ref_count_0 + 1); - System::assert_last_event(Event::DexModule(crate::Event::AddProvision( - ALICE, - AUSD, - 5_000_000_000_000u128, - DOT, - 0, - ))); + System::assert_last_event(Event::DexModule(crate::Event::AddProvision { + who: ALICE, + currency_0: AUSD, + contribution_0: 5_000_000_000_000u128, + currency_1: DOT, + contribution_1: 0, + })); }); } @@ -829,14 +837,14 @@ fn add_liquidity_work() { 0, false, )); - System::assert_last_event(Event::DexModule(crate::Event::AddLiquidity( - ALICE, - AUSD, - 5_000_000_000_000, - DOT, - 1_000_000_000_000, - 10_000_000_000_000, - ))); + System::assert_last_event(Event::DexModule(crate::Event::AddLiquidity { + who: ALICE, + currency_0: AUSD, + pool_0: 5_000_000_000_000, + currency_1: DOT, + pool_1: 1_000_000_000_000, + share_increment: 10_000_000_000_000, + })); assert_eq!( DexModule::get_liquidity(AUSD, DOT), (5_000_000_000_000, 1_000_000_000_000) @@ -891,14 +899,14 @@ fn add_liquidity_work() { 80_000_000_000_000, true, )); - System::assert_last_event(Event::DexModule(crate::Event::AddLiquidity( - BOB, - AUSD, - 40_000_000_000_000, - DOT, - 8_000_000_000_000, - 80_000_000_000_000, - ))); + System::assert_last_event(Event::DexModule(crate::Event::AddLiquidity { + who: BOB, + currency_0: AUSD, + pool_0: 40_000_000_000_000, + currency_1: DOT, + pool_1: 8_000_000_000_000, + share_increment: 80_000_000_000_000, + })); assert_eq!( DexModule::get_liquidity(AUSD, DOT), (45_000_000_000_000, 9_000_000_000_000) @@ -994,14 +1002,14 @@ fn remove_liquidity_work() { 800_000_000_000, false, )); - System::assert_last_event(Event::DexModule(crate::Event::RemoveLiquidity( - ALICE, - AUSD, - 4_000_000_000_000, - DOT, - 800_000_000_000, - 8_000_000_000_000, - ))); + System::assert_last_event(Event::DexModule(crate::Event::RemoveLiquidity { + who: ALICE, + currency_0: AUSD, + pool_0: 4_000_000_000_000, + currency_1: DOT, + pool_1: 800_000_000_000, + share_decrement: 8_000_000_000_000, + })); assert_eq!( DexModule::get_liquidity(AUSD, DOT), (1_000_000_000_000, 200_000_000_000) @@ -1024,14 +1032,14 @@ fn remove_liquidity_work() { 0, false, )); - System::assert_last_event(Event::DexModule(crate::Event::RemoveLiquidity( - ALICE, - AUSD, - 1_000_000_000_000, - DOT, - 200_000_000_000, - 2_000_000_000_000, - ))); + System::assert_last_event(Event::DexModule(crate::Event::RemoveLiquidity { + who: ALICE, + currency_0: AUSD, + pool_0: 1_000_000_000_000, + currency_1: DOT, + pool_1: 200_000_000_000, + share_decrement: 2_000_000_000_000, + })); assert_eq!(DexModule::get_liquidity(AUSD, DOT), (0, 0)); assert_eq!(Tokens::free_balance(AUSD, &DexModule::account_id()), 0); assert_eq!(Tokens::free_balance(DOT, &DexModule::account_id()), 0); @@ -1143,11 +1151,11 @@ fn do_swap_with_exact_supply_work() { 100_000_000_000_000, 200_000_000_000_000, )); - System::assert_last_event(Event::DexModule(crate::Event::Swap( - BOB, - vec![DOT, AUSD], - vec![100_000_000_000_000, 248_743_718_592_964], - ))); + System::assert_last_event(Event::DexModule(crate::Event::Swap { + trader: BOB, + path: vec![DOT, AUSD], + liquidity_changes: vec![100_000_000_000_000, 248_743_718_592_964], + })); assert_eq!( DexModule::get_liquidity(AUSD, DOT), (251_256_281_407_036, 200_000_000_000_000) @@ -1172,11 +1180,11 @@ fn do_swap_with_exact_supply_work() { 200_000_000_000_000, 1, )); - System::assert_last_event(Event::DexModule(crate::Event::Swap( - BOB, - vec![DOT, AUSD, BTC], - vec![200_000_000_000_000, 124_996_843_514_053, 5_530_663_837], - ))); + System::assert_last_event(Event::DexModule(crate::Event::Swap { + trader: BOB, + path: vec![DOT, AUSD, BTC], + liquidity_changes: vec![200_000_000_000_000, 124_996_843_514_053, 5_530_663_837], + })); assert_eq!( DexModule::get_liquidity(AUSD, DOT), (126_259_437_892_983, 400_000_000_000_000) @@ -1266,11 +1274,11 @@ fn do_swap_with_exact_target_work() { 250_000_000_000_000, 200_000_000_000_000, )); - System::assert_last_event(Event::DexModule(crate::Event::Swap( - BOB, - vec![DOT, AUSD], - vec![101_010_101_010_102, 250_000_000_000_000], - ))); + System::assert_last_event(Event::DexModule(crate::Event::Swap { + trader: BOB, + path: vec![DOT, AUSD], + liquidity_changes: vec![101_010_101_010_102, 250_000_000_000_000], + })); assert_eq!( DexModule::get_liquidity(AUSD, DOT), (250_000_000_000_000, 201_010_101_010_102) @@ -1295,11 +1303,11 @@ fn do_swap_with_exact_target_work() { 5_000_000_000, 2_000_000_000_000_000, )); - System::assert_last_event(Event::DexModule(crate::Event::Swap( - BOB, - vec![DOT, AUSD, BTC], - vec![137_654_580_386_993, 101_010_101_010_102, 5_000_000_000], - ))); + System::assert_last_event(Event::DexModule(crate::Event::Swap { + trader: BOB, + path: vec![DOT, AUSD, BTC], + liquidity_changes: vec![137_654_580_386_993, 101_010_101_010_102, 5_000_000_000], + })); assert_eq!( DexModule::get_liquidity(AUSD, DOT), (148_989_898_989_898, 338_664_681_397_095) diff --git a/modules/emergency-shutdown/src/lib.rs b/modules/emergency-shutdown/src/lib.rs index c83f24d743..6de2d660c3 100644 --- a/modules/emergency-shutdown/src/lib.rs +++ b/modules/emergency-shutdown/src/lib.rs @@ -94,11 +94,15 @@ pub mod module { #[pallet::generate_deposit(fn deposit_event)] pub enum Event { /// Emergency shutdown occurs. \[block_number\] - Shutdown(T::BlockNumber), + Shutdown { block_number: T::BlockNumber }, /// The final redemption opened. \[block_number\] - OpenRefund(T::BlockNumber), - /// Refund info. \[caller, stable_coin_amount, refund_list\] - Refund(T::AccountId, Balance, Vec<(CurrencyId, Balance)>), + OpenRefund { block_number: T::BlockNumber }, + /// Refund info. \[who, stable_coin_amount, refund_list\] + Refund { + who: T::AccountId, + stable_coin_amount: Balance, + refund_list: Vec<(CurrencyId, Balance)>, + }, } /// Emergency shutdown flag @@ -142,7 +146,9 @@ pub mod module { } IsShutdown::::put(true); - Self::deposit_event(Event::Shutdown(>::block_number())); + Self::deposit_event(Event::Shutdown { + block_number: >::block_number(), + }); Ok(()) } @@ -175,7 +181,9 @@ pub mod module { // Open refund stage CanRefund::::put(true); - Self::deposit_event(Event::OpenRefund(>::block_number())); + Self::deposit_event(Event::OpenRefund { + block_number: >::block_number(), + }); Ok(()) } @@ -208,7 +216,11 @@ pub mod module { } } - Self::deposit_event(Event::Refund(who, amount, refund_assets)); + Self::deposit_event(Event::Refund { + who, + stable_coin_amount: amount, + refund_list: refund_assets, + }); Ok(()) } } diff --git a/modules/emergency-shutdown/src/tests.rs b/modules/emergency-shutdown/src/tests.rs index 6de91e0172..bb5f0ba80a 100644 --- a/modules/emergency-shutdown/src/tests.rs +++ b/modules/emergency-shutdown/src/tests.rs @@ -35,7 +35,9 @@ fn emergency_shutdown_work() { BadOrigin, ); assert_ok!(EmergencyShutdownModule::emergency_shutdown(Origin::signed(1))); - System::assert_last_event(Event::EmergencyShutdownModule(crate::Event::Shutdown(1))); + System::assert_last_event(Event::EmergencyShutdownModule(crate::Event::Shutdown { + block_number: 1, + })); assert!(EmergencyShutdownModule::is_shutdown()); assert_noop!( EmergencyShutdownModule::emergency_shutdown(Origin::signed(1)), @@ -66,7 +68,9 @@ fn open_collateral_refund_work() { BadOrigin, ); assert_ok!(EmergencyShutdownModule::open_collateral_refund(Origin::signed(1))); - System::assert_last_event(Event::EmergencyShutdownModule(crate::Event::OpenRefund(1))); + System::assert_last_event(Event::EmergencyShutdownModule(crate::Event::OpenRefund { + block_number: 1, + })); assert!(EmergencyShutdownModule::can_refund()); }); } diff --git a/modules/evm-accounts/src/lib.rs b/modules/evm-accounts/src/lib.rs index f5760b6e81..fdad44fa5e 100644 --- a/modules/evm-accounts/src/lib.rs +++ b/modules/evm-accounts/src/lib.rs @@ -83,7 +83,10 @@ pub mod module { pub enum Event { /// Mapping between Substrate accounts and EVM accounts /// claim account. \[account_id, evm_address\] - ClaimAccount(T::AccountId, EvmAddress), + ClaimAccount { + account_id: T::AccountId, + evm_address: EvmAddress, + }, } /// Error for evm accounts module. @@ -159,7 +162,10 @@ pub mod module { Accounts::::insert(eth_address, &who); EvmAddresses::::insert(&who, eth_address); - Self::deposit_event(Event::ClaimAccount(who, eth_address)); + Self::deposit_event(Event::ClaimAccount { + account_id: who, + evm_address: eth_address, + }); Ok(()) } @@ -176,7 +182,10 @@ pub mod module { let eth_address = T::AddressMapping::get_or_create_evm_address(&who); - Self::deposit_event(Event::ClaimAccount(who, eth_address)); + Self::deposit_event(Event::ClaimAccount { + account_id: who, + evm_address: eth_address, + }); Ok(()) } diff --git a/modules/evm-accounts/src/tests.rs b/modules/evm-accounts/src/tests.rs index 452b041968..1478bd88f9 100644 --- a/modules/evm-accounts/src/tests.rs +++ b/modules/evm-accounts/src/tests.rs @@ -33,10 +33,10 @@ fn claim_account_work() { EvmAccountsModule::eth_address(&alice()), EvmAccountsModule::eth_sign(&alice(), &ALICE.encode(), &[][..]) )); - System::assert_last_event(Event::EvmAccountsModule(crate::Event::ClaimAccount( - ALICE, - EvmAccountsModule::eth_address(&alice()), - ))); + System::assert_last_event(Event::EvmAccountsModule(crate::Event::ClaimAccount { + account_id: ALICE, + evm_address: EvmAccountsModule::eth_address(&alice()), + })); assert!( Accounts::::contains_key(EvmAccountsModule::eth_address(&alice())) && EvmAddresses::::contains_key(ALICE) diff --git a/modules/evm-bridge/src/mock.rs b/modules/evm-bridge/src/mock.rs index eff3400add..6f6276b37b 100644 --- a/modules/evm-bridge/src/mock.rs +++ b/modules/evm-bridge/src/mock.rs @@ -191,10 +191,10 @@ pub fn deploy_contracts() { let code = from_hex(include!("./erc20_demo_contract")).unwrap(); assert_ok!(EVM::create(Origin::signed(alice()), code, 0, 2_100_000, 10000)); - System::assert_last_event(Event::EVM(module_evm::Event::Created( - alice_evm_addr(), - erc20_address(), - vec![module_evm::Log { + System::assert_last_event(Event::EVM(module_evm::Event::Created { + from: alice_evm_addr(), + contract: erc20_address(), + logs: vec![module_evm::Log { address: erc20_address(), topics: vec![ H256::from_str("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef").unwrap(), @@ -203,7 +203,7 @@ pub fn deploy_contracts() { ], data: H256::from_low_u64_be(10000).as_bytes().to_vec(), }], - ))); + })); assert_ok!(EVM::deploy_free(Origin::signed(CouncilAccount::get()), erc20_address())); } diff --git a/modules/evm/src/lib.rs b/modules/evm/src/lib.rs index 086df11813..7f8f75b515 100644 --- a/modules/evm/src/lib.rs +++ b/modules/evm/src/lib.rs @@ -422,28 +422,49 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// A contract has been created at given \[from, address, logs\]. - Created(EvmAddress, EvmAddress, Vec), + /// A contract has been created at given + Created { + from: EvmAddress, + contract: EvmAddress, + logs: Vec, + }, /// A contract was attempted to be created, but the execution failed. - /// \[from, contract, exit_reason, logs\] - CreatedFailed(EvmAddress, EvmAddress, ExitReason, Vec), - /// A contract has been executed successfully with states applied. \[from, contract, logs\] - Executed(EvmAddress, EvmAddress, Vec), + CreatedFailed { + from: EvmAddress, + contract: EvmAddress, + exit_reason: ExitReason, + logs: Vec, + }, + /// A contract has been executed successfully with states applied. + Executed { + from: EvmAddress, + contract: EvmAddress, + logs: Vec, + }, /// A contract has been executed with errors. States are reverted with - /// only gas fees applied. \[from, contract, exit_reason, output, logs\] - ExecutedFailed(EvmAddress, EvmAddress, ExitReason, Vec, Vec), - /// Transferred maintainer. \[contract, address\] - TransferredMaintainer(EvmAddress, EvmAddress), - /// Enabled contract development. \[who\] - ContractDevelopmentEnabled(T::AccountId), - /// Disabled contract development. \[who\] - ContractDevelopmentDisabled(T::AccountId), - /// Deployed contract. \[contract\] - ContractDeployed(EvmAddress), - /// Set contract code. \[contract\] - ContractSetCode(EvmAddress), - /// Selfdestructed contract code. \[contract\] - ContractSelfdestructed(EvmAddress), + /// only gas fees applied. + ExecutedFailed { + from: EvmAddress, + contract: EvmAddress, + exit_reason: ExitReason, + output: Vec, + logs: Vec, + }, + /// Transferred maintainer. + TransferredMaintainer { + contract: EvmAddress, + new_maintainer: EvmAddress, + }, + /// Enabled contract development. + ContractDevelopmentEnabled { who: T::AccountId }, + /// Disabled contract development. + ContractDevelopmentDisabled { who: T::AccountId }, + /// Deployed contract. + ContractDeployed { contract: EvmAddress }, + /// Set contract code. + ContractSetCode { contract: EvmAddress }, + /// Selfdestructed contract code. + ContractSelfdestructed { contract: EvmAddress }, } #[pallet::error] @@ -770,7 +791,10 @@ pub mod module { let who = ensure_signed(origin)?; Self::do_transfer_maintainer(who, contract, new_maintainer)?; - Pallet::::deposit_event(Event::::TransferredMaintainer(contract, new_maintainer)); + Pallet::::deposit_event(Event::::TransferredMaintainer { + contract, + new_maintainer: new_maintainer, + }); Ok(().into()) } @@ -791,7 +815,7 @@ pub mod module { ExistenceRequirement::AllowDeath, )?; Self::mark_deployed(contract, Some(address))?; - Pallet::::deposit_event(Event::::ContractDeployed(contract)); + Pallet::::deposit_event(Event::::ContractDeployed { contract }); Ok(().into()) } @@ -804,7 +828,7 @@ pub mod module { pub fn deploy_free(origin: OriginFor, contract: EvmAddress) -> DispatchResultWithPostInfo { T::FreeDeploymentOrigin::ensure_origin(origin)?; Self::mark_deployed(contract, None)?; - Pallet::::deposit_event(Event::::ContractDeployed(contract)); + Pallet::::deposit_event(Event::::ContractDeployed { contract }); Ok(().into()) } @@ -819,7 +843,7 @@ pub mod module { Error::::ContractDevelopmentAlreadyEnabled ); T::Currency::ensure_reserved_named(&RESERVE_ID_DEVELOPER_DEPOSIT, &who, T::DeveloperDeposit::get())?; - Pallet::::deposit_event(Event::::ContractDevelopmentEnabled(who)); + Pallet::::deposit_event(Event::::ContractDevelopmentEnabled { who }); Ok(().into()) } @@ -834,7 +858,7 @@ pub mod module { Error::::ContractDevelopmentNotEnabled ); T::Currency::unreserve_all_named(&RESERVE_ID_DEVELOPER_DEPOSIT, &who); - Pallet::::deposit_event(Event::::ContractDevelopmentDisabled(who)); + Pallet::::deposit_event(Event::::ContractDevelopmentDisabled { who }); Ok(().into()) } @@ -848,7 +872,7 @@ pub mod module { let root_or_signed = Self::ensure_root_or_signed(origin)?; Self::do_set_code(root_or_signed, contract, code)?; - Pallet::::deposit_event(Event::::ContractSetCode(contract)); + Pallet::::deposit_event(Event::::ContractSetCode { contract }); Ok(().into()) } @@ -863,7 +887,7 @@ pub mod module { let caller = T::AddressMapping::get_evm_address(&who).ok_or(Error::::AddressNotMapped)?; Self::do_selfdestruct(&caller, &contract)?; - Pallet::::deposit_event(Event::::ContractSelfdestructed(contract)); + Pallet::::deposit_event(Event::::ContractSelfdestructed { contract }); Ok(().into()) } diff --git a/modules/evm/src/runner/stack.rs b/modules/evm/src/runner/stack.rs index 6cad910bfe..55a31fbc21 100644 --- a/modules/evm/src/runner/stack.rs +++ b/modules/evm/src/runner/stack.rs @@ -235,15 +235,19 @@ impl RunnerT for Runner { })?; if info.exit_reason.is_succeed() { - Pallet::::deposit_event(Event::::Executed(source, target, info.logs.clone())); + Pallet::::deposit_event(Event::::Executed { + from: source, + contract: target, + logs: info.logs.clone(), + }); } else { - Pallet::::deposit_event(Event::::ExecutedFailed( - source, - target, - info.exit_reason.clone(), - info.value.clone(), - info.logs.clone(), - )); + Pallet::::deposit_event(Event::::ExecutedFailed { + from: source, + contract: target, + exit_reason: info.exit_reason.clone(), + output: info.value.clone(), + logs: info.logs.clone(), + }); } Ok(info) @@ -270,14 +274,18 @@ impl RunnerT for Runner { })?; if info.exit_reason.is_succeed() { - Pallet::::deposit_event(Event::::Created(source, info.value, info.logs.clone())); + Pallet::::deposit_event(Event::::Created { + from: source, + contract: info.value, + logs: info.logs.clone(), + }); } else { - Pallet::::deposit_event(Event::::CreatedFailed( - source, - info.value, - info.exit_reason.clone(), - info.logs.clone(), - )); + Pallet::::deposit_event(Event::::CreatedFailed { + from: source, + contract: info.value, + exit_reason: info.exit_reason.clone(), + logs: info.logs.clone(), + }); } Ok(info) @@ -310,14 +318,18 @@ impl RunnerT for Runner { })?; if info.exit_reason.is_succeed() { - Pallet::::deposit_event(Event::::Created(source, info.value, info.logs.clone())); + Pallet::::deposit_event(Event::::Created { + from: source, + contract: info.value, + logs: info.logs.clone(), + }); } else { - Pallet::::deposit_event(Event::::CreatedFailed( - source, - info.value, - info.exit_reason.clone(), - info.logs.clone(), - )); + Pallet::::deposit_event(Event::::CreatedFailed { + from: source, + contract: info.value, + exit_reason: info.exit_reason.clone(), + logs: info.logs.clone(), + }); } Ok(info) @@ -342,14 +354,18 @@ impl RunnerT for Runner { })?; if info.exit_reason.is_succeed() { - Pallet::::deposit_event(Event::::Created(source, info.value, info.logs.clone())); + Pallet::::deposit_event(Event::::Created { + from: source, + contract: info.value, + logs: info.logs.clone(), + }); } else { - Pallet::::deposit_event(Event::::CreatedFailed( - source, - info.value, - info.exit_reason.clone(), - info.logs.clone(), - )); + Pallet::::deposit_event(Event::::CreatedFailed { + from: source, + contract: info.value, + exit_reason: info.exit_reason.clone(), + logs: info.logs.clone(), + }); } Ok(info) diff --git a/modules/evm/src/tests.rs b/modules/evm/src/tests.rs index 8e07939c77..22cb66a8e7 100644 --- a/modules/evm/src/tests.rs +++ b/modules/evm/src/tests.rs @@ -740,11 +740,11 @@ fn create_network_contract_works() { Pallet::::account_basic(&NetworkContractSource::get()).nonce, 2.into() ); - System::assert_last_event(Event::EVM(crate::Event::Created( - NetworkContractSource::get(), - MIRRORED_TOKENS_ADDRESS_START | H160::from_low_u64_be(MIRRORED_NFT_ADDRESS_START), - vec![], - ))); + System::assert_last_event(Event::EVM(crate::Event::Created { + from: NetworkContractSource::get(), + contract: MIRRORED_TOKENS_ADDRESS_START | H160::from_low_u64_be(MIRRORED_NFT_ADDRESS_START), + logs: vec![], + })); assert_eq!(EVM::network_contract_index(), MIRRORED_NFT_ADDRESS_START + 1); }); } @@ -806,11 +806,11 @@ fn create_predeploy_contract_works() { assert_eq!(Pallet::::is_account_empty(&addr), false); - System::assert_last_event(Event::EVM(crate::Event::Created( - NetworkContractSource::get(), - addr, - vec![], - ))); + System::assert_last_event(Event::EVM(crate::Event::Created { + from: NetworkContractSource::get(), + contract: addr, + logs: vec![], + })); assert_noop!( EVM::create_predeploy_contract( @@ -889,7 +889,10 @@ fn should_transfer_maintainer() { contract_address, bob() )); - System::assert_last_event(Event::EVM(crate::Event::TransferredMaintainer(contract_address, bob()))); + System::assert_last_event(Event::EVM(crate::Event::TransferredMaintainer { + contract: contract_address, + new_maintainer: bob(), + })); assert_eq!(balance(bob()), INITIAL_BALANCE); assert_noop!( diff --git a/modules/example/src/lib.rs b/modules/example/src/lib.rs index 438e5e6861..6c02816674 100644 --- a/modules/example/src/lib.rs +++ b/modules/example/src/lib.rs @@ -54,7 +54,7 @@ pub mod module { #[pallet::generate_deposit(fn deposit_event)] pub enum Event { /// Dummy event, just here so there's a generic type that's used. - Dummy(T::Balance), + Dummy { name: T::Balance }, } #[pallet::type_value] @@ -129,7 +129,7 @@ pub mod module { ensure_root(origin)?; Dummy::::put(&new_value); - Self::deposit_event(Event::Dummy(new_value)); + Self::deposit_event(Event::Dummy { name: new_value }); Ok(()) } diff --git a/modules/homa-validator-list/src/lib.rs b/modules/homa-validator-list/src/lib.rs index c6852d6d07..7246a794dd 100644 --- a/modules/homa-validator-list/src/lib.rs +++ b/modules/homa-validator-list/src/lib.rs @@ -209,12 +209,32 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - FreezeValidator(T::RelaychainAccountId), - ThawValidator(T::RelaychainAccountId), - BondGuarantee(T::AccountId, T::RelaychainAccountId, Balance), - UnbondGuarantee(T::AccountId, T::RelaychainAccountId, Balance), - WithdrawnGuarantee(T::AccountId, T::RelaychainAccountId, Balance), - SlashGuarantee(T::AccountId, T::RelaychainAccountId, Balance), + FreezeValidator { + validator: T::RelaychainAccountId, + }, + ThawValidator { + validator: T::RelaychainAccountId, + }, + BondGuarantee { + who: T::AccountId, + validator: T::RelaychainAccountId, + bond: Balance, + }, + UnbondGuarantee { + who: T::AccountId, + validator: T::RelaychainAccountId, + bond: Balance, + }, + WithdrawnGuarantee { + who: T::AccountId, + validator: T::RelaychainAccountId, + bond: Balance, + }, + SlashGuarantee { + who: T::AccountId, + validator: T::RelaychainAccountId, + bond: Balance, + }, } /// The slash guarantee deposits for relaychain validators. @@ -282,7 +302,11 @@ pub mod module { guarantee.bonded >= T::MinBondAmount::get(), Error::::BelowMinBondAmount ); - Self::deposit_event(Event::BondGuarantee(guarantor.clone(), validator.clone(), amount)); + Self::deposit_event(Event::BondGuarantee { + who: guarantor.clone(), + validator: validator.clone(), + bond: amount, + }); Ok(()) })?; } @@ -316,7 +340,11 @@ pub mod module { let expired_block = T::BlockNumberProvider::current_block_number() + T::BondingDuration::get(); guarantee.unbonding = Some((amount, expired_block)); - Self::deposit_event(Event::UnbondGuarantee(guarantor.clone(), validator.clone(), amount)); + Self::deposit_event(Event::UnbondGuarantee { + who: guarantor.clone(), + validator: validator.clone(), + bond: amount, + }); Ok(()) })?; } @@ -365,11 +393,11 @@ pub mod module { .saturating_add(guarantee.unbonding.unwrap_or_default().0); if old_total != new_total { guarantee.total = new_total; - Self::deposit_event(Event::WithdrawnGuarantee( - guarantor.clone(), - validator.clone(), - old_total.saturating_sub(new_total), - )); + Self::deposit_event(Event::WithdrawnGuarantee { + who: guarantor.clone(), + validator: validator.clone(), + bond: old_total.saturating_sub(new_total), + }); } Ok(()) })?; @@ -389,7 +417,9 @@ pub mod module { let mut v = maybe_validator.take().unwrap_or_default(); if !v.is_frozen { v.is_frozen = true; - Self::deposit_event(Event::FreezeValidator(validator.clone())); + Self::deposit_event(Event::FreezeValidator { + validator: validator.clone(), + }); } *maybe_validator = Some(v); }); @@ -412,7 +442,9 @@ pub mod module { let mut v = maybe_validator.take().unwrap_or_default(); if v.is_frozen { v.is_frozen = false; - Self::deposit_event(Event::ThawValidator(validator.clone())); + Self::deposit_event(Event::ThawValidator { + validator: validator.clone(), + }); } *maybe_validator = Some(v); }); @@ -451,11 +483,11 @@ pub mod module { let gap = T::LiquidTokenCurrency::slash(&guarantor, should_slashing); let actual_slashing = should_slashing.saturating_sub(gap); *guarantee = guarantee.slash(actual_slashing); - Self::deposit_event(Event::SlashGuarantee( - guarantor.clone(), - validator.clone(), - actual_slashing, - )); + Self::deposit_event(Event::SlashGuarantee { + who: guarantor.clone(), + validator: validator.clone(), + bond: actual_slashing, + }); actual_total_slashing = actual_total_slashing.saturating_add(actual_slashing); Ok(()) }); diff --git a/modules/homa-validator-list/src/tests.rs b/modules/homa-validator-list/src/tests.rs index f47a3e1013..22efed52a9 100644 --- a/modules/homa-validator-list/src/tests.rs +++ b/modules/homa-validator-list/src/tests.rs @@ -125,15 +125,15 @@ fn freeze_work() { .is_frozen ); - System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::FreezeValidator( - VALIDATOR_1, - ))); - System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::FreezeValidator( - VALIDATOR_2, - ))); - System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::FreezeValidator( - VALIDATOR_3, - ))); + System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::FreezeValidator { + validator: VALIDATOR_1, + })); + System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::FreezeValidator { + validator: VALIDATOR_2, + })); + System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::FreezeValidator { + validator: VALIDATOR_3, + })); }); } @@ -184,12 +184,12 @@ fn thaw_work() { .unwrap_or_default() .is_frozen ); - System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::ThawValidator( - VALIDATOR_1, - ))); - System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::ThawValidator( - VALIDATOR_2, - ))); + System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::ThawValidator { + validator: VALIDATOR_1, + })); + System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::ThawValidator { + validator: VALIDATOR_2, + })); }); } @@ -224,11 +224,11 @@ fn bond_work() { assert_eq!(SHARES.with(|v| *v.borrow().get(&(ALICE, VALIDATOR_1)).unwrap_or(&0)), 0); assert_ok!(HomaValidatorListModule::bond(Origin::signed(ALICE), VALIDATOR_1, 100)); - System::assert_last_event(mock::Event::HomaValidatorListModule(crate::Event::BondGuarantee( - ALICE, - VALIDATOR_1, - 100, - ))); + System::assert_last_event(mock::Event::HomaValidatorListModule(crate::Event::BondGuarantee { + who: ALICE, + validator: VALIDATOR_1, + bond: 100, + })); assert_eq!( HomaValidatorListModule::guarantees(VALIDATOR_1, ALICE).unwrap_or_default(), Guarantee { @@ -275,11 +275,11 @@ fn bond_work() { assert_eq!(SHARES.with(|v| *v.borrow().get(&(BOB, VALIDATOR_1)).unwrap_or(&0)), 0); assert_ok!(HomaValidatorListModule::bond(Origin::signed(BOB), VALIDATOR_1, 300)); - System::assert_last_event(mock::Event::HomaValidatorListModule(crate::Event::BondGuarantee( - BOB, - VALIDATOR_1, - 300, - ))); + System::assert_last_event(mock::Event::HomaValidatorListModule(crate::Event::BondGuarantee { + who: BOB, + validator: VALIDATOR_1, + bond: 300, + })); assert_eq!( HomaValidatorListModule::guarantees(VALIDATOR_1, BOB).unwrap_or_default(), Guarantee { @@ -323,11 +323,11 @@ fn bond_work() { assert_eq!(SHARES.with(|v| *v.borrow().get(&(BOB, VALIDATOR_2)).unwrap_or(&0)), 0); assert_ok!(HomaValidatorListModule::bond(Origin::signed(BOB), VALIDATOR_2, 200)); - System::assert_last_event(mock::Event::HomaValidatorListModule(crate::Event::BondGuarantee( - BOB, - VALIDATOR_2, - 200, - ))); + System::assert_last_event(mock::Event::HomaValidatorListModule(crate::Event::BondGuarantee { + who: BOB, + validator: VALIDATOR_2, + bond: 200, + })); assert_eq!( HomaValidatorListModule::guarantees(VALIDATOR_2, BOB).unwrap_or_default(), Guarantee { @@ -388,11 +388,11 @@ fn unbond_work() { ); assert_ok!(HomaValidatorListModule::unbond(Origin::signed(ALICE), VALIDATOR_1, 100)); - System::assert_last_event(mock::Event::HomaValidatorListModule(crate::Event::UnbondGuarantee( - ALICE, - VALIDATOR_1, - 100, - ))); + System::assert_last_event(mock::Event::HomaValidatorListModule(crate::Event::UnbondGuarantee { + who: ALICE, + validator: VALIDATOR_1, + bond: 100, + })); assert_eq!( HomaValidatorListModule::guarantees(VALIDATOR_1, ALICE).unwrap_or_default(), Guarantee { @@ -553,11 +553,11 @@ fn withdraw_unbonded_work() { Origin::signed(ALICE), VALIDATOR_1 )); - System::assert_last_event(mock::Event::HomaValidatorListModule(crate::Event::WithdrawnGuarantee( - ALICE, - VALIDATOR_1, - 100, - ))); + System::assert_last_event(mock::Event::HomaValidatorListModule(crate::Event::WithdrawnGuarantee { + who: ALICE, + validator: VALIDATOR_1, + bond: 100, + })); assert_eq!( HomaValidatorListModule::guarantees(VALIDATOR_1, ALICE).unwrap_or_default(), Guarantee { @@ -686,21 +686,21 @@ fn slash_work() { }, ] )); - System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::SlashGuarantee( - ALICE, - VALIDATOR_1, - 59, - ))); - System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::SlashGuarantee( - BOB, - VALIDATOR_1, - 119, - ))); - System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::SlashGuarantee( - BOB, - VALIDATOR_2, - 100, - ))); + System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::SlashGuarantee { + who: ALICE, + validator: VALIDATOR_1, + bond: 59, + })); + System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::SlashGuarantee { + who: BOB, + validator: VALIDATOR_1, + bond: 119, + })); + System::assert_has_event(mock::Event::HomaValidatorListModule(crate::Event::SlashGuarantee { + who: BOB, + validator: VALIDATOR_2, + bond: 100, + })); assert_eq!( HomaValidatorListModule::validator_backings(VALIDATOR_1) .unwrap_or_default() diff --git a/modules/honzon/src/lib.rs b/modules/honzon/src/lib.rs index dc9bd579c7..ab0af20d34 100644 --- a/modules/honzon/src/lib.rs +++ b/modules/honzon/src/lib.rs @@ -87,13 +87,19 @@ pub mod module { #[pallet::generate_deposit(fn deposit_event)] pub enum Event { /// Authorize someone to operate the loan of specific collateral. - /// \[authorizer, authorizee, collateral_type\] - Authorization(T::AccountId, T::AccountId, CurrencyId), + Authorization { + authorizer: T::AccountId, + authorizee: T::AccountId, + collateral_type: CurrencyId, + }, /// Cancel the authorization of specific collateral for someone. - /// \[authorizer, authorizee, collateral_type\] - UnAuthorization(T::AccountId, T::AccountId, CurrencyId), - /// Cancel all authorization. \[authorizer\] - UnAuthorizationAll(T::AccountId), + UnAuthorization { + authorizer: T::AccountId, + authorizee: T::AccountId, + collateral_type: CurrencyId, + }, + /// Cancel all authorization. + UnAuthorizationAll { authorizer: T::AccountId }, } /// The authorization relationship map from @@ -221,7 +227,11 @@ pub mod module { let reserve_amount = T::DepositPerAuthorization::get(); ::Currency::reserve_named(&RESERVE_ID, &from, reserve_amount)?; *maybe_reserved = Some(reserve_amount); - Self::deposit_event(Event::Authorization(from.clone(), to.clone(), currency_id)); + Self::deposit_event(Event::Authorization { + authorizer: from.clone(), + authorizee: to.clone(), + collateral_type: currency_id, + }); Ok(()) } else { Err(Error::::AlreadyAuthorized.into()) @@ -246,7 +256,11 @@ pub mod module { let reserved = Authorization::::take(&from, (currency_id, &to)).ok_or(Error::::AuthorizationNotExists)?; ::Currency::unreserve_named(&RESERVE_ID, &from, reserved); - Self::deposit_event(Event::UnAuthorization(from, to, currency_id)); + Self::deposit_event(Event::UnAuthorization { + authorizer: from, + authorizee: to, + collateral_type: currency_id, + }); Ok(()) } @@ -257,7 +271,7 @@ pub mod module { let from = ensure_signed(origin)?; Authorization::::remove_prefix(&from, None); ::Currency::unreserve_all_named(&RESERVE_ID, &from); - Self::deposit_event(Event::UnAuthorizationAll(from)); + Self::deposit_event(Event::UnAuthorizationAll { authorizer: from }); Ok(()) } } diff --git a/modules/honzon/src/tests.rs b/modules/honzon/src/tests.rs index e5bf1a0d38..22e6f72adc 100644 --- a/modules/honzon/src/tests.rs +++ b/modules/honzon/src/tests.rs @@ -34,7 +34,11 @@ fn authorize_should_work() { assert_eq!(PalletBalances::reserved_balance(ALICE), 0); assert_ok!(HonzonModule::authorize(Origin::signed(ALICE), BTC, BOB)); assert_eq!(PalletBalances::reserved_balance(ALICE), DepositPerAuthorization::get()); - System::assert_last_event(Event::HonzonModule(crate::Event::Authorization(ALICE, BOB, BTC))); + System::assert_last_event(Event::HonzonModule(crate::Event::Authorization { + authorizer: ALICE, + authorizee: BOB, + collateral_type: BTC, + })); assert_ok!(HonzonModule::check_authorization(&ALICE, &BOB, BTC)); assert_noop!( HonzonModule::authorize(Origin::signed(ALICE), BTC, BOB), @@ -53,7 +57,11 @@ fn unauthorize_should_work() { assert_ok!(HonzonModule::unauthorize(Origin::signed(ALICE), BTC, BOB)); assert_eq!(PalletBalances::reserved_balance(ALICE), 0); - System::assert_last_event(Event::HonzonModule(crate::Event::UnAuthorization(ALICE, BOB, BTC))); + System::assert_last_event(Event::HonzonModule(crate::Event::UnAuthorization { + authorizer: ALICE, + authorizee: BOB, + collateral_type: BTC, + })); assert_noop!( HonzonModule::check_authorization(&ALICE, &BOB, BTC), Error::::NoPermission @@ -74,7 +82,9 @@ fn unauthorize_all_should_work() { assert_eq!(PalletBalances::reserved_balance(ALICE), 200); assert_ok!(HonzonModule::unauthorize_all(Origin::signed(ALICE))); assert_eq!(PalletBalances::reserved_balance(ALICE), 0); - System::assert_last_event(Event::HonzonModule(crate::Event::UnAuthorizationAll(ALICE))); + System::assert_last_event(Event::HonzonModule(crate::Event::UnAuthorizationAll { + authorizer: ALICE, + })); assert_noop!( HonzonModule::check_authorization(&ALICE, &BOB, BTC), diff --git a/modules/idle-scheduler/src/lib.rs b/modules/idle-scheduler/src/lib.rs index 715614170a..1709973708 100644 --- a/modules/idle-scheduler/src/lib.rs +++ b/modules/idle-scheduler/src/lib.rs @@ -65,7 +65,7 @@ pub mod module { pub enum Event { /// A task has been dispatched on_idle. /// \[TaskId, DispatchResult\] - TaskDispatched(Nonce, DispatchResult), + TaskDispatched { task_id: Nonce, result: DispatchResult }, } /// Some documentation @@ -138,7 +138,10 @@ impl Pallet { // Deposit event and remove completed tasks. for (id, result) in completed_tasks { - Self::deposit_event(Event::::TaskDispatched(id, result.result)); + Self::deposit_event(Event::::TaskDispatched { + dispatch_id: id, + result: result.result, + }); Tasks::::remove(id); } diff --git a/modules/incentives/src/lib.rs b/modules/incentives/src/lib.rs index 66d9ed0d20..efeeb20078 100644 --- a/modules/incentives/src/lib.rs +++ b/modules/incentives/src/lib.rs @@ -132,19 +132,36 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// Deposit DEX share. \[who, dex_share_type, deposit_amount\] - DepositDexShare(T::AccountId, CurrencyId, Balance), - /// Withdraw DEX share. \[who, dex_share_type, withdraw_amount\] - WithdrawDexShare(T::AccountId, CurrencyId, Balance), - /// Claim rewards. \[who, pool_id, reward_currency_id, actual_amount, deduction_amount\] - ClaimRewards(T::AccountId, PoolId, CurrencyId, Balance, Balance), - /// Incentive reward amount updated. \[pool_id, reward_currency_id, - /// reward_amount_per_period\] - IncentiveRewardAmountUpdated(PoolId, CurrencyId, Balance), + /// Deposit DEX share. + DepositDexShare { + who: T::AccountId, + dex_share_type: CurrencyId, + deposit: Balance, + }, + /// Withdraw DEX share. + WithdrawDexShare { + who: T::AccountId, + dex_share_type: CurrencyId, + withdraw: Balance, + }, + /// Claim rewards. + ClaimRewards { + who: T::AccountId, + pool: PoolId, + reward_currency_id: CurrencyId, + actual_amount: Balance, + deduction_amount: Balance, + }, + /// Incentive reward amount updated. + IncentiveRewardAmountUpdated { + pool: PoolId, + reward_currency_id: CurrencyId, + reward_amount_per_period: Balance, + }, /// Saving reward rate updated. \[pool_id, reward_rate_per_period\] - SavingRewardRateUpdated(PoolId, Rate), + SavingRewardRateUpdated { pool: PoolId, reward_rate_per_period: Rate }, /// Payout deduction rate updated. \[pool_id, deduction_rate\] - ClaimRewardDeductionRateUpdated(PoolId, Rate), + ClaimRewardDeductionRateUpdated { pool: PoolId, deduction_rate: Rate }, } /// Mapping from pool to its fixed incentive amounts of multi currencies per period. @@ -296,13 +313,13 @@ pub mod module { // be rewarded, there will not increase user balance. T::Currency::transfer(currency_id, &Self::account_id(), &who, actual_amount)?; - Self::deposit_event(Event::ClaimRewards( - who.clone(), - pool_id, - currency_id, - actual_amount, - deduction_amount, - )); + Self::deposit_event(Event::ClaimRewards { + who: who.clone(), + pool: pool_id, + reward_currency_id: currency_id, + actual_amount: actual_amount, + deduction_amount: deduction_amount, + }); } Ok(()) @@ -332,7 +349,11 @@ pub mod module { let mut v = maybe_amount.unwrap_or_default(); if amount != v { v = amount; - Self::deposit_event(Event::IncentiveRewardAmountUpdated(pool_id, currency_id, amount)); + Self::deposit_event(Event::IncentiveRewardAmountUpdated { + pool: pool_id, + reward_currency_id: currency_id, + reward_amount_per_period: amount, + }); } if v.is_zero() { @@ -366,7 +387,10 @@ pub mod module { let mut v = maybe_rate.unwrap_or_default(); if rate != v { v = rate; - Self::deposit_event(Event::SavingRewardRateUpdated(pool_id, rate)); + Self::deposit_event(Event::SavingRewardRateUpdated { + pool: pool_id, + reward_rate_per_period: rate, + }); } if v.is_zero() { @@ -400,7 +424,10 @@ pub mod module { let mut v = maybe_rate.unwrap_or_default(); if deduction_rate != v { v = deduction_rate; - Self::deposit_event(Event::ClaimRewardDeductionRateUpdated(pool_id, deduction_rate)); + Self::deposit_event(Event::ClaimRewardDeductionRateUpdated { + pool: pool_id, + deduction_rate: deduction_rate, + }); } if v.is_zero() { @@ -518,7 +545,11 @@ impl DEXIncentives for Pallet { T::Currency::transfer(lp_currency_id, who, &Self::account_id(), amount)?; >::add_share(who, &PoolId::Dex(lp_currency_id), amount.unique_saturated_into()); - Self::deposit_event(Event::DepositDexShare(who.clone(), lp_currency_id, amount)); + Self::deposit_event(Event::DepositDexShare { + who: who.clone(), + dex_share_type: lp_currency_id, + deposit: amount, + }); Ok(()) } @@ -532,7 +563,11 @@ impl DEXIncentives for Pallet { T::Currency::transfer(lp_currency_id, &Self::account_id(), who, amount)?; >::remove_share(who, &PoolId::Dex(lp_currency_id), amount.unique_saturated_into()); - Self::deposit_event(Event::WithdrawDexShare(who.clone(), lp_currency_id, amount)); + Self::deposit_event(Event::WithdrawDexShare { + who: who.clone(), + dex_share_type: lp_currency_id, + withdraw: amount, + }); Ok(()) } } diff --git a/modules/incentives/src/tests.rs b/modules/incentives/src/tests.rs index c85dfe895c..73974e61cb 100644 --- a/modules/incentives/src/tests.rs +++ b/modules/incentives/src/tests.rs @@ -49,11 +49,11 @@ fn deposit_dex_share_works() { BTC_AUSD_LP, 10000 )); - System::assert_last_event(Event::IncentivesModule(crate::Event::DepositDexShare( - ALICE::get(), - BTC_AUSD_LP, - 10000, - ))); + System::assert_last_event(Event::IncentivesModule(crate::Event::DepositDexShare { + who: ALICE::get(), + dex_share_type: BTC_AUSD_LP, + deposit: 10000, + })); assert_eq!(TokensModule::free_balance(BTC_AUSD_LP, &ALICE::get()), 0); assert_eq!( TokensModule::free_balance(BTC_AUSD_LP, &IncentivesModule::account_id()), @@ -111,11 +111,11 @@ fn withdraw_dex_share_works() { BTC_AUSD_LP, 8000 )); - System::assert_last_event(Event::IncentivesModule(crate::Event::WithdrawDexShare( - ALICE::get(), - BTC_AUSD_LP, - 8000, - ))); + System::assert_last_event(Event::IncentivesModule(crate::Event::WithdrawDexShare { + who: ALICE::get(), + dex_share_type: BTC_AUSD_LP, + withdraw: 8000, + })); assert_eq!(TokensModule::free_balance(BTC_AUSD_LP, &ALICE::get()), 8000); assert_eq!( TokensModule::free_balance(BTC_AUSD_LP, &IncentivesModule::account_id()), @@ -165,21 +165,21 @@ fn update_incentive_rewards_works() { (PoolId::Loans(DOT), vec![(ACA, 500)]), ], )); - System::assert_has_event(Event::IncentivesModule(crate::Event::IncentiveRewardAmountUpdated( - PoolId::Dex(DOT_AUSD_LP), - ACA, - 1000, - ))); - System::assert_has_event(Event::IncentivesModule(crate::Event::IncentiveRewardAmountUpdated( - PoolId::Dex(DOT_AUSD_LP), - DOT, - 100, - ))); - System::assert_has_event(Event::IncentivesModule(crate::Event::IncentiveRewardAmountUpdated( - PoolId::Loans(DOT), - ACA, - 500, - ))); + System::assert_has_event(Event::IncentivesModule(crate::Event::IncentiveRewardAmountUpdated { + pool: PoolId::Dex(DOT_AUSD_LP), + reward_currency_id: ACA, + reward_amount_per_period: 1000, + })); + System::assert_has_event(Event::IncentivesModule(crate::Event::IncentiveRewardAmountUpdated { + pool: PoolId::Dex(DOT_AUSD_LP), + reward_currency_id: DOT, + reward_amount_per_period: 100, + })); + System::assert_has_event(Event::IncentivesModule(crate::Event::IncentiveRewardAmountUpdated { + pool: PoolId::Loans(DOT), + reward_currency_id: ACA, + reward_amount_per_period: 500, + })); assert_eq!( IncentivesModule::incentive_reward_amounts(PoolId::Dex(DOT_AUSD_LP), ACA), 1000 @@ -201,16 +201,16 @@ fn update_incentive_rewards_works() { (PoolId::Loans(DOT), vec![(ACA, 500)]), ], )); - System::assert_has_event(Event::IncentivesModule(crate::Event::IncentiveRewardAmountUpdated( - PoolId::Dex(DOT_AUSD_LP), - ACA, - 200, - ))); - System::assert_has_event(Event::IncentivesModule(crate::Event::IncentiveRewardAmountUpdated( - PoolId::Dex(DOT_AUSD_LP), - DOT, - 0, - ))); + System::assert_has_event(Event::IncentivesModule(crate::Event::IncentiveRewardAmountUpdated { + pool: PoolId::Dex(DOT_AUSD_LP), + reward_currency_id: ACA, + reward_amount_per_period: 200, + })); + System::assert_has_event(Event::IncentivesModule(crate::Event::IncentiveRewardAmountUpdated { + pool: PoolId::Dex(DOT_AUSD_LP), + reward_currency_id: DOT, + reward_amount_per_period: 0, + })); assert_eq!( IncentivesModule::incentive_reward_amounts(PoolId::Dex(DOT_AUSD_LP), ACA), 200 @@ -269,14 +269,14 @@ fn update_dex_saving_rewards_works() { (PoolId::Dex(BTC_AUSD_LP), Rate::saturating_from_rational(2, 100)) ] )); - System::assert_has_event(Event::IncentivesModule(crate::Event::SavingRewardRateUpdated( - PoolId::Dex(DOT_AUSD_LP), - Rate::saturating_from_rational(1, 100), - ))); - System::assert_has_event(Event::IncentivesModule(crate::Event::SavingRewardRateUpdated( - PoolId::Dex(BTC_AUSD_LP), - Rate::saturating_from_rational(2, 100), - ))); + System::assert_has_event(Event::IncentivesModule(crate::Event::SavingRewardRateUpdated { + pool: PoolId::Dex(DOT_AUSD_LP), + reward_rate_per_period: Rate::saturating_from_rational(1, 100), + })); + System::assert_has_event(Event::IncentivesModule(crate::Event::SavingRewardRateUpdated { + pool: PoolId::Dex(BTC_AUSD_LP), + reward_rate_per_period: Rate::saturating_from_rational(2, 100), + })); assert_eq!( IncentivesModule::dex_saving_reward_rates(PoolId::Dex(DOT_AUSD_LP)), Rate::saturating_from_rational(1, 100) @@ -297,14 +297,14 @@ fn update_dex_saving_rewards_works() { (PoolId::Dex(BTC_AUSD_LP), Rate::zero()) ] )); - System::assert_has_event(Event::IncentivesModule(crate::Event::SavingRewardRateUpdated( - PoolId::Dex(DOT_AUSD_LP), - Rate::saturating_from_rational(5, 100), - ))); - System::assert_has_event(Event::IncentivesModule(crate::Event::SavingRewardRateUpdated( - PoolId::Dex(BTC_AUSD_LP), - Rate::zero(), - ))); + System::assert_has_event(Event::IncentivesModule(crate::Event::SavingRewardRateUpdated { + pool: PoolId::Dex(DOT_AUSD_LP), + reward_rate_per_period: Rate::saturating_from_rational(5, 100), + })); + System::assert_has_event(Event::IncentivesModule(crate::Event::SavingRewardRateUpdated { + pool: PoolId::Dex(BTC_AUSD_LP), + reward_rate_per_period: Rate::zero(), + })); assert_eq!( IncentivesModule::dex_saving_reward_rates(PoolId::Dex(DOT_AUSD_LP)), Rate::saturating_from_rational(5, 100) @@ -359,14 +359,14 @@ fn update_claim_reward_deduction_rates_works() { (PoolId::Dex(BTC_AUSD_LP), Rate::saturating_from_rational(2, 100)) ] )); - System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewardDeductionRateUpdated( - PoolId::Dex(DOT_AUSD_LP), - Rate::saturating_from_rational(1, 100), - ))); - System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewardDeductionRateUpdated( - PoolId::Dex(BTC_AUSD_LP), - Rate::saturating_from_rational(2, 100), - ))); + System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewardDeductionRateUpdated { + pool: PoolId::Dex(DOT_AUSD_LP), + deduction_rate: Rate::saturating_from_rational(1, 100), + })); + System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewardDeductionRateUpdated { + pool: PoolId::Dex(BTC_AUSD_LP), + deduction_rate: Rate::saturating_from_rational(2, 100), + })); assert_eq!( IncentivesModule::claim_reward_deduction_rates(PoolId::Dex(DOT_AUSD_LP)), Rate::saturating_from_rational(1, 100) @@ -387,14 +387,14 @@ fn update_claim_reward_deduction_rates_works() { (PoolId::Dex(BTC_AUSD_LP), Rate::zero()) ] )); - System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewardDeductionRateUpdated( - PoolId::Dex(DOT_AUSD_LP), - Rate::saturating_from_rational(5, 100), - ))); - System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewardDeductionRateUpdated( - PoolId::Dex(BTC_AUSD_LP), - Rate::zero(), - ))); + System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewardDeductionRateUpdated { + pool: PoolId::Dex(DOT_AUSD_LP), + deduction_rate: Rate::saturating_from_rational(5, 100), + })); + System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewardDeductionRateUpdated { + pool: PoolId::Dex(BTC_AUSD_LP), + deduction_rate: Rate::zero(), + })); assert_eq!( IncentivesModule::claim_reward_deduction_rates(PoolId::Dex(DOT_AUSD_LP)), Rate::saturating_from_rational(5, 100) @@ -566,20 +566,22 @@ fn claim_rewards_works() { Origin::signed(ALICE::get()), PoolId::Loans(BTC) )); - System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards( - ALICE::get(), - PoolId::Loans(BTC), - ACA, - 200, - 1800, - ))); - System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards( - ALICE::get(), - PoolId::Loans(BTC), - LDOT, - 25, - 225, - ))); + + System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards { + who: ALICE::get(), + pool: PoolId::Loans(BTC), + reward_currency_id: ACA, + actual_amount: 200, + deduction_amount: 1800, + })); + System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards { + who: ALICE::get(), + pool: PoolId::Loans(BTC), + reward_currency_id: LDOT, + actual_amount: 25, + deduction_amount: 225, + })); + assert_eq!( RewardsModule::pool_infos(PoolId::Loans(BTC)), PoolInfo { @@ -606,20 +608,21 @@ fn claim_rewards_works() { Origin::signed(BOB::get()), PoolId::Loans(BTC) )); - System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards( - BOB::get(), - PoolId::Loans(BTC), - ACA, - 90, - 810, - ))); - System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards( - BOB::get(), - PoolId::Loans(BTC), - LDOT, - 37, - 325, - ))); + + System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards { + who: BOB::get(), + pool: PoolId::Loans(BTC), + reward_currency_id: ACA, + actual_amount: 90, + deduction_amount: 810, + })); + System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards { + who: BOB::get(), + pool: PoolId::Loans(BTC), + reward_currency_id: LDOT, + actual_amount: 37, + deduction_amount: 325, + })); assert_eq!( RewardsModule::pool_infos(PoolId::Loans(BTC)), PoolInfo { @@ -683,20 +686,21 @@ fn claim_rewards_works() { Origin::signed(ALICE::get()), PoolId::Dex(BTC_AUSD_LP) )); - System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards( - ALICE::get(), - PoolId::Dex(BTC_AUSD_LP), - ACA, - 250, - 250, - ))); - System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards( - ALICE::get(), - PoolId::Dex(BTC_AUSD_LP), - AUSD, - 500, - 500, - ))); + System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards { + who: ALICE::get(), + pool: PoolId::Dex(BTC_AUSD_LP), + reward_currency_id: ACA, + actual_amount: 250, + deduction_amount: 250, + })); + System::assert_has_event(Event::IncentivesModule(crate::Event::ClaimRewards { + who: ALICE::get(), + pool: PoolId::Dex(BTC_AUSD_LP), + reward_currency_id: AUSD, + actual_amount: 500, + deduction_amount: 500, + })); + assert_eq!( RewardsModule::pool_infos(PoolId::Dex(BTC_AUSD_LP)), PoolInfo { diff --git a/runtime/integration-tests/src/dex.rs b/runtime/integration-tests/src/dex.rs index 02f3a0ff53..0d91981ded 100644 --- a/runtime/integration-tests/src/dex.rs +++ b/runtime/integration-tests/src/dex.rs @@ -74,14 +74,14 @@ fn test_dex_module() { false, )); - let add_liquidity_event = Event::Dex(module_dex::Event::AddLiquidity( - AccountId::from(ALICE), - USD_CURRENCY, - 10_000_000 * dollar(USD_CURRENCY), - RELAY_CHAIN_CURRENCY, - 10_000 * dollar(RELAY_CHAIN_CURRENCY), - 20_000_000 * dollar(USD_CURRENCY), - )); + let add_liquidity_event = Event::Dex(module_dex::Event::AddLiquidity { + who: AccountId::from(ALICE), + currency_0: USD_CURRENCY, + pool_0: 10_000_000 * dollar(USD_CURRENCY), + currency_1: RELAY_CHAIN_CURRENCY, + pool_1: 10_000 * dollar(RELAY_CHAIN_CURRENCY), + share_increment: 20_000_000 * dollar(USD_CURRENCY), + }); assert!(System::events() .iter() .any(|record| record.event == add_liquidity_event)); diff --git a/runtime/integration-tests/src/evm.rs b/runtime/integration-tests/src/evm.rs index 50e792d66e..61085009f6 100644 --- a/runtime/integration-tests/src/evm.rs +++ b/runtime/integration-tests/src/evm.rs @@ -55,10 +55,10 @@ pub fn deploy_erc20_contracts() { let code = from_hex(include!("../../../modules/evm-bridge/src/erc20_demo_contract")).unwrap(); assert_ok!(EVM::create(Origin::signed(alice()), code.clone(), 0, 2100_000, 100000)); - System::assert_last_event(Event::EVM(module_evm::Event::Created( - EvmAddress::from_str("0xbf0b5a4099f0bf6c8bc4252ebec548bae95602ea").unwrap(), - erc20_address_0(), - vec![module_evm::Log { + System::assert_last_event(Event::EVM(module_evm::Event::Created { + from: EvmAddress::from_str("0xbf0b5a4099f0bf6c8bc4252ebec548bae95602ea").unwrap(), + contract: erc20_address_0(), + logs: vec![module_evm::Log { address: erc20_address_0(), topics: vec![ H256::from_str("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef").unwrap(), @@ -67,16 +67,16 @@ pub fn deploy_erc20_contracts() { ], data: H256::from_low_u64_be(10000).as_bytes().to_vec(), }], - ))); + })); assert_ok!(EVM::deploy_free(Origin::root(), erc20_address_0())); assert_ok!(EVM::create(Origin::signed(alice()), code, 0, 2100_000, 100000)); - System::assert_last_event(Event::EVM(module_evm::Event::Created( - EvmAddress::from_str("0xbf0b5a4099f0bf6c8bc4252ebec548bae95602ea").unwrap(), - erc20_address_1(), - vec![module_evm::Log { + System::assert_last_event(Event::EVM(module_evm::Event::Created { + from: EvmAddress::from_str("0xbf0b5a4099f0bf6c8bc4252ebec548bae95602ea").unwrap(), + contract: erc20_address_1(), + logs: vec![module_evm::Log { address: erc20_address_1(), topics: vec![ H256::from_str("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef").unwrap(), @@ -85,7 +85,7 @@ pub fn deploy_erc20_contracts() { ], data: H256::from_low_u64_be(10000).as_bytes().to_vec(), }], - ))); + })); assert_ok!(EVM::deploy_free(Origin::root(), erc20_address_1())); } @@ -107,7 +107,12 @@ fn deploy_contract(account: AccountId) -> Result { EVM::create(Origin::signed(account), contract, 0, 1000000000, 100000).map_or_else(|e| Err(e.error), |_| Ok(()))?; - if let Event::EVM(module_evm::Event::::Created(_, address, _)) = System::events().last().unwrap().event { + if let Event::EVM(module_evm::Event::::Created { + from: _, + contract: address, + logs: _, + }) = System::events().last().unwrap().event + { Ok(address) } else { Err("deploy_contract failed".into()) @@ -297,13 +302,17 @@ fn test_evm_module() { let bob_address = EvmAccounts::eth_address(&bob_key()); let contract = deploy_contract(alice()).unwrap(); - System::assert_last_event(Event::EVM(module_evm::Event::Created(alice_address, contract, vec![]))); + System::assert_last_event(Event::EVM(module_evm::Event::Created { + from: alice_address, + contract, + logs: vec![], + })); assert_ok!(EVM::transfer_maintainer(Origin::signed(alice()), contract, bob_address)); - System::assert_last_event(Event::EVM(module_evm::Event::TransferredMaintainer( + System::assert_last_event(Event::EVM(module_evm::Event::TransferredMaintainer { contract, - bob_address, - ))); + new_maintainer: bob_address, + })); // test EvmAccounts Lookup #[cfg(feature = "with-mandala-runtime")] @@ -485,7 +494,7 @@ fn should_not_kill_contract_on_transfer_all() { assert_ok!(EVM::create(Origin::signed(alice()), code, convert_decimals_to_evm(2 * dollar(NATIVE_CURRENCY)), 1000000000, 100000)); - let contract = if let Event::EVM(module_evm::Event::Created(_, address, _)) = System::events().last().unwrap().event { + let contract = if let Event::EVM(module_evm::Event::Created{from: _, contract: address, logs: _}) = System::events().last().unwrap().event { address } else { panic!("deploy contract failed"); @@ -548,7 +557,7 @@ fn should_not_kill_contract_on_transfer_all_tokens() { let code = hex_literal::hex!("608060405260848060116000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c806341c0e1b514602d575b600080fd5b60336035565b005b600073ffffffffffffffffffffffffffffffffffffffff16fffea265627a7a72315820ed64a7551098c4afc823bee1663309079d9cb8798a6bdd71be2cd3ccee52d98e64736f6c63430005110032").to_vec(); assert_ok!(EVM::create(Origin::signed(alice()), code, 0, 1000000000, 100000)); - let contract = if let Event::EVM(module_evm::Event::Created(_, address, _)) = System::events().last().unwrap().event { + let contract = if let Event::EVM(module_evm::Event::Created{from: _, contract: address, logs: _}) = System::events().last().unwrap().event { address } else { panic!("deploy contract failed"); @@ -619,10 +628,10 @@ fn test_evm_accounts_module() { EvmAccounts::eth_address(&alice_key()), EvmAccounts::eth_sign(&alice_key(), &AccountId::from(ALICE).encode(), &[][..]) )); - System::assert_last_event(Event::EvmAccounts(module_evm_accounts::Event::ClaimAccount( - AccountId::from(ALICE), - EvmAccounts::eth_address(&alice_key()), - ))); + System::assert_last_event(Event::EvmAccounts(module_evm_accounts::Event::ClaimAccount { + account_id: AccountId::from(ALICE), + evm_address: EvmAccounts::eth_address(&alice_key()), + })); // claim another eth address assert_noop!( diff --git a/runtime/mandala/src/benchmarking/collator_selection.rs b/runtime/mandala/src/benchmarking/collator_selection.rs index def576e15d..75b0678b93 100644 --- a/runtime/mandala/src/benchmarking/collator_selection.rs +++ b/runtime/mandala/src/benchmarking/collator_selection.rs @@ -73,7 +73,7 @@ runtime_benchmarks! { ); } verify { - assert_last_event(module_collator_selection::Event::NewInvulnerables(new_invulnerables).into()); + assert_last_event(module_collator_selection::Event::NewInvulnerables{new_invulnerables: new_invulnerables}.into()); } set_desired_candidates { @@ -84,7 +84,7 @@ runtime_benchmarks! { ); } verify { - assert_last_event(module_collator_selection::Event::NewDesiredCandidates(max).into()); + assert_last_event(module_collator_selection::Event::NewDesiredCandidates{new_desired_candidates: max}.into()); } set_candidacy_bond { @@ -95,7 +95,7 @@ runtime_benchmarks! { ); } verify { - assert_last_event(module_collator_selection::Event::NewCandidacyBond(bond).into()); + assert_last_event(module_collator_selection::Event::NewCandidacyBond{new_candidacy_bond: bond}.into()); } // worse case is when we have all the max-candidate slots filled except one, and we fill that @@ -115,7 +115,7 @@ runtime_benchmarks! { Session::set_keys(RawOrigin::Signed(caller.clone()).into(), SessionKeys::default(), vec![]).unwrap(); }: _(RawOrigin::Signed(caller.clone())) verify { - assert_last_event(module_collator_selection::Event::CandidateAdded(caller, bond.checked_div(2u32.into()).unwrap()).into()); + assert_last_event(module_collator_selection::Event::CandidateAdded{who: caller, bond: bond.checked_div(2u32.into()).unwrap()}.into()); } register_candidate { @@ -132,7 +132,7 @@ runtime_benchmarks! { Session::set_keys(RawOrigin::Signed(caller.clone()).into(), SessionKeys::default(), vec![]).unwrap(); }: _(RawOrigin::Root, caller.clone()) verify { - assert_last_event(module_collator_selection::Event::CandidateAdded(caller, 0).into()); + assert_last_event(module_collator_selection::Event::CandidateAdded{who: caller, bond: 0}.into()); } // worse case is the last candidate leaving. @@ -147,7 +147,7 @@ runtime_benchmarks! { whitelist_account!(leaving); }: _(RawOrigin::Signed(leaving.clone())) verify { - assert_last_event(module_collator_selection::Event::CandidateRemoved(leaving).into()); + assert_last_event(module_collator_selection::Event::CandidateRemoved{who: leaving}.into()); } withdraw_bond { diff --git a/runtime/mandala/src/benchmarking/dex.rs b/runtime/mandala/src/benchmarking/dex.rs index 8b10f3b245..2c42026240 100644 --- a/runtime/mandala/src/benchmarking/dex.rs +++ b/runtime/mandala/src/benchmarking/dex.rs @@ -90,7 +90,7 @@ runtime_benchmarks! { } }: _(RawOrigin::Root, trading_pair.first(), trading_pair.second()) verify { - assert_last_event(module_dex::Event::EnableTradingPair(trading_pair).into()); + assert_last_event(module_dex::Event::EnableTradingPair{trading_pair: trading_pair}.into()); } // disable a Enabled trading pair @@ -101,7 +101,7 @@ runtime_benchmarks! { } }: _(RawOrigin::Root, trading_pair.first(), trading_pair.second()) verify { - assert_last_event(module_dex::Event::DisableTradingPair(trading_pair).into()); + assert_last_event(module_dex::Event::DisableTradingPair{trading_pair}.into()); } // list a Provisioning trading pair @@ -112,7 +112,7 @@ runtime_benchmarks! { } }: _(RawOrigin::Root, trading_pair.first(), trading_pair.second(), dollar(trading_pair.first()), dollar(trading_pair.second()), dollar(trading_pair.first()), dollar(trading_pair.second()), 10) verify { - assert_last_event(module_dex::Event::ListProvisioning(trading_pair).into()); + assert_last_event(module_dex::Event::ListProvisioning{trading_pair: trading_pair}.into()); } // update parameters of a Provisioning trading pair @@ -165,7 +165,7 @@ runtime_benchmarks! { )?; }: _(RawOrigin::Signed(founder), trading_pair.first(), trading_pair.second()) verify { - assert_last_event(module_dex::Event::ProvisioningToEnabled(trading_pair, 100 * dollar(trading_pair.first()), 100 * dollar(trading_pair.second()), 200 * dollar(trading_pair.first())).into()) + assert_last_event(module_dex::Event::ProvisioningToEnabled{trading_pair, pool_0: 100 * dollar(trading_pair.first()), pool_1: 100 * dollar(trading_pair.second()), share_amount: 200 * dollar(trading_pair.first())}.into()) } add_provision { @@ -190,7 +190,7 @@ runtime_benchmarks! { >::update_balance(trading_pair.second(), &founder, (10 * dollar(trading_pair.second())).unique_saturated_into())?; }: _(RawOrigin::Signed(founder.clone()), trading_pair.first(), trading_pair.second(), dollar(trading_pair.first()), dollar(trading_pair.second())) verify{ - assert_last_event(module_dex::Event::AddProvision(founder, trading_pair.first(), dollar(trading_pair.first()), trading_pair.second(), dollar(trading_pair.second())).into()); + assert_last_event(module_dex::Event::AddProvision{who: founder, currency_0: trading_pair.first(), contribution_0: dollar(trading_pair.first()), currency_1: trading_pair.second(), contribution_1: dollar(trading_pair.second())}.into()); } claim_dex_share { diff --git a/runtime/mandala/src/benchmarking/evm.rs b/runtime/mandala/src/benchmarking/evm.rs index ec279b1052..00017addfb 100644 --- a/runtime/mandala/src/benchmarking/evm.rs +++ b/runtime/mandala/src/benchmarking/evm.rs @@ -61,11 +61,11 @@ fn deploy_contract(caller: AccountId) -> Result { EVM::create(Origin::signed(caller.clone()), contract, 0, 1000000000, 1000000000) .map_or_else(|e| Err(e.error), |_| Ok(()))?; - System::assert_last_event(Event::EVM(module_evm::Event::Created( - module_evm_accounts::EvmAddressMapping::::get_evm_address(&caller).unwrap(), - contract_addr(), - vec![], - ))); + System::assert_last_event(Event::EVM(module_evm::Event::Created { + from: module_evm_accounts::EvmAddressMapping::::get_evm_address(&caller).unwrap(), + contract: contract_addr(), + logs: vec![], + })); Ok(contract_addr()) } From 622200b9d67531512e70f32f4e59d73d4d5352df Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Fri, 17 Dec 2021 12:31:56 +1300 Subject: [PATCH 04/13] Refactored the events in the module folder. --- modules/emergency-shutdown/src/lib.rs | 6 +- modules/evm-accounts/src/lib.rs | 2 +- modules/homa-lite/src/lib.rs | 1 - modules/idle-scheduler/src/lib.rs | 1 - modules/incentives/src/lib.rs | 4 +- modules/loans/src/lib.rs | 55 +++++++----- modules/loans/src/tests.rs | 22 +++-- modules/nft/src/lib.rs | 83 +++++++++++++++---- modules/nft/src/tests.rs | 70 +++++++++------- modules/nominees-election/src/lib.rs | 5 +- modules/nominees-election/src/tests.rs | 5 +- modules/prices/src/lib.rs | 18 ++-- modules/prices/src/tests.rs | 18 ++-- modules/session-manager/src/lib.rs | 18 ++-- modules/session-manager/src/tests.rs | 18 +++- modules/staking-pool/src/lib.rs | 80 +++++++++++------- modules/staking-pool/src/tests.rs | 56 +++++++++---- modules/transaction-pause/src/lib.rs | 24 ++++-- modules/transaction-pause/src/tests.rs | 16 ++-- .../src/benchmarking/session_manager.rs | 2 +- 20 files changed, 333 insertions(+), 171 deletions(-) diff --git a/modules/emergency-shutdown/src/lib.rs b/modules/emergency-shutdown/src/lib.rs index 6de2d660c3..247e0d72cb 100644 --- a/modules/emergency-shutdown/src/lib.rs +++ b/modules/emergency-shutdown/src/lib.rs @@ -93,11 +93,11 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] pub enum Event { - /// Emergency shutdown occurs. \[block_number\] + /// Emergency shutdown occurs. Shutdown { block_number: T::BlockNumber }, - /// The final redemption opened. \[block_number\] + /// The final redemption opened. OpenRefund { block_number: T::BlockNumber }, - /// Refund info. \[who, stable_coin_amount, refund_list\] + /// Refund info. Refund { who: T::AccountId, stable_coin_amount: Balance, diff --git a/modules/evm-accounts/src/lib.rs b/modules/evm-accounts/src/lib.rs index fdad44fa5e..8e61c1d201 100644 --- a/modules/evm-accounts/src/lib.rs +++ b/modules/evm-accounts/src/lib.rs @@ -82,7 +82,7 @@ pub mod module { #[pallet::generate_deposit(fn deposit_event)] pub enum Event { /// Mapping between Substrate accounts and EVM accounts - /// claim account. \[account_id, evm_address\] + /// claim account. ClaimAccount { account_id: T::AccountId, evm_address: EvmAddress, diff --git a/modules/homa-lite/src/lib.rs b/modules/homa-lite/src/lib.rs index f56f64b8ee..50153ba89c 100644 --- a/modules/homa-lite/src/lib.rs +++ b/modules/homa-lite/src/lib.rs @@ -177,7 +177,6 @@ pub mod module { #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { /// The user has Staked some currencies to mint Liquid Currency. - /// \[who, amount_staked, amount_minted\] Minted { who: T::AccountId, amount_staked: Balance, diff --git a/modules/idle-scheduler/src/lib.rs b/modules/idle-scheduler/src/lib.rs index 1709973708..8cf299e492 100644 --- a/modules/idle-scheduler/src/lib.rs +++ b/modules/idle-scheduler/src/lib.rs @@ -64,7 +64,6 @@ pub mod module { #[pallet::generate_deposit(pub fn deposit_event)] pub enum Event { /// A task has been dispatched on_idle. - /// \[TaskId, DispatchResult\] TaskDispatched { task_id: Nonce, result: DispatchResult }, } diff --git a/modules/incentives/src/lib.rs b/modules/incentives/src/lib.rs index efeeb20078..870bb4fceb 100644 --- a/modules/incentives/src/lib.rs +++ b/modules/incentives/src/lib.rs @@ -158,9 +158,9 @@ pub mod module { reward_currency_id: CurrencyId, reward_amount_per_period: Balance, }, - /// Saving reward rate updated. \[pool_id, reward_rate_per_period\] + /// Saving reward rate updated. SavingRewardRateUpdated { pool: PoolId, reward_rate_per_period: Rate }, - /// Payout deduction rate updated. \[pool_id, deduction_rate\] + /// Payout deduction rate updated. ClaimRewardDeductionRateUpdated { pool: PoolId, deduction_rate: Rate }, } diff --git a/modules/loans/src/lib.rs b/modules/loans/src/lib.rs index 79433394ba..604a0e5b60 100644 --- a/modules/loans/src/lib.rs +++ b/modules/loans/src/lib.rs @@ -96,15 +96,26 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// Position updated. \[owner, collateral_type, collateral_adjustment, - /// debit_adjustment\] - PositionUpdated(T::AccountId, CurrencyId, Amount, Amount), - /// Confiscate CDP's collateral assets and eliminate its debit. \[owner, - /// collateral_type, confiscated_collateral_amount, - /// deduct_debit_amount\] - ConfiscateCollateralAndDebit(T::AccountId, CurrencyId, Balance, Balance), - /// Transfer loan. \[from, to, currency_id\] - TransferLoan(T::AccountId, T::AccountId, CurrencyId), + /// Position updated. + PositionUpdated { + owner: T::AccountId, + collateral_type: CurrencyId, + collateral_adjustment: Amount, + debit_adjustment: Amount, + }, + /// Confiscate CDP's collateral assets and eliminate its debit. + ConfiscateCollateralAndDebit { + owner: T::AccountId, + collateral_type: CurrencyId, + confiscated_collateral_amount: Balance, + deduct_debit_amount: Balance, + }, + /// Transfer loan. + TransferLoan { + from: T::AccountId, + to: T::AccountId, + currency_id: CurrencyId, + }, } /// The collateralized debit positions, map from @@ -168,12 +179,12 @@ impl Pallet { debit_adjustment.saturating_neg(), )?; - Self::deposit_event(Event::ConfiscateCollateralAndDebit( - who.clone(), - currency_id, - collateral_confiscate, - debit_decrease, - )); + Self::deposit_event(Event::ConfiscateCollateralAndDebit { + owner: who.clone(), + collateral_type: currency_id, + confiscated_collateral_amount: collateral_confiscate, + deduct_debit_amount: debit_decrease, + }); Ok(()) } @@ -222,12 +233,12 @@ impl Pallet { collateral_adjustment.is_negative() || debit_adjustment.is_positive(), )?; - Self::deposit_event(Event::PositionUpdated( - who.clone(), - currency_id, + Self::deposit_event(Event::PositionUpdated { + owner: who.clone(), + collateral_type: currency_id, collateral_adjustment, debit_adjustment, - )); + }); Ok(()) } @@ -262,7 +273,11 @@ impl Pallet { )?; Self::update_loan(to, currency_id, collateral_adjustment, debit_adjustment)?; - Self::deposit_event(Event::TransferLoan(from.clone(), to.clone(), currency_id)); + Self::deposit_event(Event::TransferLoan { + from: from.clone(), + to: to.clone(), + currency_id, + }); Ok(()) } diff --git a/modules/loans/src/tests.rs b/modules/loans/src/tests.rs index c6ecdabeea..3b5b0461de 100644 --- a/modules/loans/src/tests.rs +++ b/modules/loans/src/tests.rs @@ -106,7 +106,12 @@ fn adjust_position_should_work() { assert_eq!(LoansModule::positions(BTC, &ALICE).debit, 300); assert_eq!(LoansModule::positions(BTC, &ALICE).collateral, 500); assert_eq!(Currencies::free_balance(AUSD, &ALICE), 150); - System::assert_last_event(Event::LoansModule(crate::Event::PositionUpdated(ALICE, BTC, 500, 300))); + System::assert_last_event(Event::LoansModule(crate::Event::PositionUpdated { + owner: ALICE, + collateral_type: BTC, + collateral_adjustment: 500, + debit_adjustment: 300, + })); // collateral_adjustment is negatives assert_eq!(Currencies::total_balance(BTC, &LoansModule::account_id()), 500); @@ -173,7 +178,11 @@ fn transfer_loan_should_work() { assert_eq!(LoansModule::positions(BTC, &ALICE).collateral, 0); assert_eq!(LoansModule::positions(BTC, &BOB).debit, 1100); assert_eq!(LoansModule::positions(BTC, &BOB).collateral, 500); - System::assert_last_event(Event::LoansModule(crate::Event::TransferLoan(ALICE, BOB, BTC))); + System::assert_last_event(Event::LoansModule(crate::Event::TransferLoan { + from: ALICE, + to: BOB, + currency_id: BTC, + })); }); } @@ -198,9 +207,12 @@ fn confiscate_collateral_and_debit_work() { assert_eq!(CDPTreasuryModule::debit_pool(), 100); assert_eq!(LoansModule::positions(BTC, &ALICE).debit, 100); assert_eq!(LoansModule::positions(BTC, &ALICE).collateral, 200); - System::assert_last_event(Event::LoansModule(crate::Event::ConfiscateCollateralAndDebit( - ALICE, BTC, 300, 200, - ))); + System::assert_last_event(Event::LoansModule(crate::Event::ConfiscateCollateralAndDebit { + owner: ALICE, + collateral_type: BTC, + confiscated_collateral_amount: 300, + deduct_debit_amount: 200, + })); }); } diff --git a/modules/nft/src/lib.rs b/modules/nft/src/lib.rs index c400b02efa..9031882f33 100644 --- a/modules/nft/src/lib.rs +++ b/modules/nft/src/lib.rs @@ -196,18 +196,43 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// Created NFT class. \[owner, class_id\] - CreatedClass(T::AccountId, ClassIdOf), - /// Minted NFT token. \[from, to, class_id, quantity\] - MintedToken(T::AccountId, T::AccountId, ClassIdOf, u32), - /// Transferred NFT token. \[from, to, class_id, token_id\] - TransferredToken(T::AccountId, T::AccountId, ClassIdOf, TokenIdOf), - /// Burned NFT token. \[owner, class_id, token_id\] - BurnedToken(T::AccountId, ClassIdOf, TokenIdOf), - /// Burned NFT token with remark. \[owner, class_id, token_id, remark_hash\] - BurnedTokenWithRemark(T::AccountId, ClassIdOf, TokenIdOf, T::Hash), - /// Destroyed NFT class. \[owner, class_id\] - DestroyedClass(T::AccountId, ClassIdOf), + /// Created NFT class. + CreatedClass { + owner: T::AccountId, + class_id: ClassIdOf, + }, + /// Minted NFT token. + MintedToken { + from: T::AccountId, + to: T::AccountId, + class_id: ClassIdOf, + quantity: u32, + }, + /// Transferred NFT token. + TransferredToken { + from: T::AccountId, + to: T::AccountId, + class_id: ClassIdOf, + token_id: TokenIdOf, + }, + /// Burned NFT token. + BurnedToken { + owner: T::AccountId, + class_id: ClassIdOf, + token_id: TokenIdOf, + }, + /// Burned NFT token with remark. + BurnedTokenWithRemark { + owner: T::AccountId, + class_id: ClassIdOf, + token_id: TokenIdOf, + remark_hash: T::Hash, + }, + /// Destroyed NFT class. + DestroyedClass { + owner: T::AccountId, + class_id: ClassIdOf, + }, } #[pallet::pallet] @@ -255,7 +280,10 @@ pub mod module { }; orml_nft::Pallet::::create_class(&owner, metadata, data)?; - Self::deposit_event(Event::CreatedClass(owner, next_id)); + Self::deposit_event(Event::CreatedClass { + owner, + class_id: next_id, + }); Ok(().into()) } @@ -358,7 +386,7 @@ pub mod module { AllowDeath, )?; - Self::deposit_event(Event::DestroyedClass(who, class_id)); + Self::deposit_event(Event::DestroyedClass { owner: who, class_id }); Ok(().into()) } @@ -411,7 +439,12 @@ impl Pallet { ::Currency::transfer(from, to, token_info.data.deposit, AllowDeath)?; ::Currency::reserve_named(&RESERVE_ID, to, token_info.data.deposit)?; - Self::deposit_event(Event::TransferredToken(from.clone(), to.clone(), token.0, token.1)); + Self::deposit_event(Event::TransferredToken { + from: from.clone(), + to: to.clone(), + class_id: token.0, + token_id: token.1, + }); Ok(()) } @@ -447,7 +480,12 @@ impl Pallet { orml_nft::Pallet::::mint(&to, class_id, metadata.clone(), data.clone())?; } - Self::deposit_event(Event::MintedToken(who, to, class_id, quantity)); + Self::deposit_event(Event::MintedToken { + from: who, + to, + class_id, + quantity, + }); Ok(()) } @@ -468,9 +506,18 @@ impl Pallet { if let Some(remark) = remark { let hash = T::Hashing::hash(&remark[..]); - Self::deposit_event(Event::BurnedTokenWithRemark(who, token.0, token.1, hash)); + Self::deposit_event(Event::BurnedTokenWithRemark { + owner: who, + class_id: token.0, + token_id: token.1, + remark_hash: hash, + }); } else { - Self::deposit_event(Event::BurnedToken(who, token.0, token.1)); + Self::deposit_event(Event::BurnedToken { + owner: who, + class_id: token.0, + token_id: token.1, + }); } Ok(()) diff --git a/modules/nft/src/tests.rs b/modules/nft/src/tests.rs index 1f60bc08a6..45900a439d 100644 --- a/modules/nft/src/tests.rs +++ b/modules/nft/src/tests.rs @@ -60,10 +60,10 @@ fn create_class_should_work() { Default::default(), test_attr(1), )); - System::assert_last_event(Event::NFTModule(crate::Event::CreatedClass( - class_id_account(), - CLASS_ID, - ))); + System::assert_last_event(Event::NFTModule(crate::Event::CreatedClass { + owner: class_id_account(), + class_id: CLASS_ID, + })); let cls_deposit = CreateClassDeposit::get() + DataDepositPerByte::get() * ((metadata.len() as u128) + TEST_ATTR_LEN); @@ -124,10 +124,10 @@ fn mint_should_work() { Properties(ClassProperty::Transferable | ClassProperty::Burnable | ClassProperty::Mintable), test_attr(1), )); - System::assert_last_event(Event::NFTModule(crate::Event::CreatedClass( - class_id_account(), - CLASS_ID, - ))); + System::assert_last_event(Event::NFTModule(crate::Event::CreatedClass { + owner: class_id_account(), + class_id: CLASS_ID, + })); assert_ok!(Balances::deposit_into_existing( &class_id_account(), 2 * (CreateTokenDeposit::get() + ((metadata_2.len() as u128 + TEST_ATTR_LEN) * DataDepositPerByte::get())) @@ -140,12 +140,12 @@ fn mint_should_work() { test_attr(2), 2 )); - System::assert_last_event(Event::NFTModule(crate::Event::MintedToken( - class_id_account(), - BOB, - CLASS_ID, - 2, - ))); + System::assert_last_event(Event::NFTModule(crate::Event::MintedToken { + from: class_id_account(), + to: BOB, + class_id: CLASS_ID, + quantity: 2, + })); assert_eq!( reserved_balance(&class_id_account()), CreateClassDeposit::get() @@ -308,9 +308,12 @@ fn transfer_should_work() { ); assert_ok!(NFTModule::transfer(Origin::signed(BOB), ALICE, (CLASS_ID, TOKEN_ID))); - System::assert_last_event(Event::NFTModule(crate::Event::TransferredToken( - BOB, ALICE, CLASS_ID, TOKEN_ID, - ))); + System::assert_last_event(Event::NFTModule(crate::Event::TransferredToken { + from: BOB, + to: ALICE, + class_id: CLASS_ID, + token_id: TOKEN_ID, + })); assert_eq!( reserved_balance(&BOB), 1 * (CreateTokenDeposit::get() + DataDepositPerByte::get()) @@ -321,9 +324,12 @@ fn transfer_should_work() { ); assert_ok!(NFTModule::transfer(Origin::signed(ALICE), BOB, (CLASS_ID, TOKEN_ID))); - System::assert_last_event(Event::NFTModule(crate::Event::TransferredToken( - ALICE, BOB, CLASS_ID, TOKEN_ID, - ))); + System::assert_last_event(Event::NFTModule(crate::Event::TransferredToken { + from: ALICE, + to: BOB, + class_id: CLASS_ID, + token_id: TOKEN_ID, + })); assert_eq!( reserved_balance(&BOB), 2 * (CreateTokenDeposit::get() + DataDepositPerByte::get()) @@ -418,7 +424,11 @@ fn burn_should_work() { 1 )); assert_ok!(NFTModule::burn(Origin::signed(BOB), (CLASS_ID, TOKEN_ID))); - System::assert_last_event(Event::NFTModule(crate::Event::BurnedToken(BOB, CLASS_ID, TOKEN_ID))); + System::assert_last_event(Event::NFTModule(crate::Event::BurnedToken { + owner: BOB, + class_id: CLASS_ID, + token_id: TOKEN_ID, + })); assert_eq!( reserved_balance(&class_id_account()), CreateClassDeposit::get() + Proxy::deposit(1u32) + DataDepositPerByte::get() * (metadata.len() as u128) @@ -524,12 +534,12 @@ fn burn_with_remark_should_work() { (CLASS_ID, TOKEN_ID), remark )); - System::assert_last_event(Event::NFTModule(crate::Event::BurnedTokenWithRemark( - BOB, - CLASS_ID, - TOKEN_ID, + System::assert_last_event(Event::NFTModule(crate::Event::BurnedTokenWithRemark { + owner: BOB, + class_id: CLASS_ID, + token_id: TOKEN_ID, remark_hash, - ))); + })); assert_eq!( reserved_balance(&class_id_account()), @@ -575,10 +585,10 @@ fn destroy_class_should_work() { CLASS_ID, ALICE )); - System::assert_last_event(Event::NFTModule(crate::Event::DestroyedClass( - class_id_account(), - CLASS_ID, - ))); + System::assert_last_event(Event::NFTModule(crate::Event::DestroyedClass { + owner: class_id_account(), + class_id: CLASS_ID, + })); assert_eq!(free_balance(&class_id_account()), 0); assert_eq!(reserved_balance(&class_id_account()), 0); assert_eq!(free_balance(&ALICE), 100000); diff --git a/modules/nominees-election/src/lib.rs b/modules/nominees-election/src/lib.rs index f3602eb9be..1b9c925954 100644 --- a/modules/nominees-election/src/lib.rs +++ b/modules/nominees-election/src/lib.rs @@ -171,8 +171,7 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event, I: 'static = ()> { - /// rebond. \[who, amount\] - Rebond(T::AccountId, Balance), + Rebond { who: T::AccountId, amount: Balance }, } /// The nominations for nominators. @@ -296,7 +295,7 @@ pub mod module { Self::update_votes(old_active, &old_nominations, ledger.active, &old_nominations); Self::update_ledger(&who, &ledger); - Self::deposit_event(Event::Rebond(who, amount)); + Self::deposit_event(Event::Rebond { who, amount }); let removed_len = old_ledger_unlocking - ledger.unlocking.len(); Ok(Some(T::WeightInfo::rebond(removed_len as u32)).into()) } diff --git a/modules/nominees-election/src/tests.rs b/modules/nominees-election/src/tests.rs index 250a40dbbd..f6473ea66e 100644 --- a/modules/nominees-election/src/tests.rs +++ b/modules/nominees-election/src/tests.rs @@ -127,7 +127,10 @@ fn rebond_work() { assert_eq!(NomineesElectionModule::ledger(&ALICE).active, 700); assert_eq!(NomineesElectionModule::ledger(&ALICE).unlocking.len(), 3); assert_ok!(NomineesElectionModule::rebond(Origin::signed(ALICE), 150)); - System::assert_last_event(mock::Event::NomineesElectionModule(crate::Event::Rebond(ALICE, 150))); + System::assert_last_event(mock::Event::NomineesElectionModule(crate::Event::Rebond { + who: ALICE, + amount: 150, + })); assert_eq!(NomineesElectionModule::ledger(&ALICE).total, 1000); assert_eq!(NomineesElectionModule::ledger(&ALICE).active, 850); assert_eq!(NomineesElectionModule::ledger(&ALICE).unlocking.len(), 2); diff --git a/modules/prices/src/lib.rs b/modules/prices/src/lib.rs index 94287ee3a9..8163ccb467 100644 --- a/modules/prices/src/lib.rs +++ b/modules/prices/src/lib.rs @@ -103,10 +103,13 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// Lock price. \[currency_id, locked_price\] - LockPrice(CurrencyId, Price), - /// Unlock price. \[currency_id\] - UnlockPrice(CurrencyId), + /// Lock price. + LockPrice { + currency_id: CurrencyId, + locked_price: Price, + }, + /// Unlock price. + UnlockPrice { currency_id: CurrencyId }, } /// Mapping from currency id to it's locked price @@ -200,14 +203,17 @@ impl LockablePrice for Pallet { fn lock_price(currency_id: CurrencyId) -> DispatchResult { let price = Self::access_price(currency_id).ok_or(Error::::AccessPriceFailed)?; LockedPrice::::insert(currency_id, price); - Pallet::::deposit_event(Event::LockPrice(currency_id, price)); + Pallet::::deposit_event(Event::LockPrice { + currency_id, + locked_price: price, + }); Ok(()) } /// Unlock the locked price fn unlock_price(currency_id: CurrencyId) -> DispatchResult { let _ = LockedPrice::::take(currency_id).ok_or(Error::::NoLockedPrice)?; - Pallet::::deposit_event(Event::UnlockPrice(currency_id)); + Pallet::::deposit_event(Event::UnlockPrice { currency_id }); Ok(()) } } diff --git a/modules/prices/src/tests.rs b/modules/prices/src/tests.rs index aaa8c47615..754ad1098f 100644 --- a/modules/prices/src/tests.rs +++ b/modules/prices/src/tests.rs @@ -245,10 +245,10 @@ fn lock_price_work() { ); assert_eq!(PricesModule::locked_price(BTC), None); assert_ok!(PricesModule::lock_price(Origin::signed(1), BTC)); - System::assert_last_event(Event::PricesModule(crate::Event::LockPrice( - BTC, - Price::saturating_from_integer(500000000000000u128), - ))); + System::assert_last_event(Event::PricesModule(crate::Event::LockPrice { + currency_id: BTC, + locked_price: Price::saturating_from_integer(500000000000000u128), + })); assert_eq!( PricesModule::locked_price(BTC), Some(Price::saturating_from_integer(500000000000000u128)) @@ -272,10 +272,10 @@ fn lock_price_work() { ); assert_eq!(PricesModule::locked_price(KSM), None); assert_ok!(PricesModule::lock_price(Origin::signed(1), KSM)); - System::assert_last_event(Event::PricesModule(crate::Event::LockPrice( - KSM, - Price::saturating_from_integer(200000000u128), - ))); + System::assert_last_event(Event::PricesModule(crate::Event::LockPrice { + currency_id: KSM, + locked_price: Price::saturating_from_integer(200000000u128), + })); assert_eq!( PricesModule::locked_price(KSM), Some(Price::saturating_from_integer(200000000u128)) @@ -302,7 +302,7 @@ fn unlock_price_work() { Some(Price::saturating_from_integer(500000000000000u128)) ); assert_ok!(PricesModule::unlock_price(Origin::signed(1), BTC)); - System::assert_last_event(Event::PricesModule(crate::Event::UnlockPrice(BTC))); + System::assert_last_event(Event::PricesModule(crate::Event::UnlockPrice { currency_id: BTC })); assert_eq!(PricesModule::locked_price(BTC), None); }); } diff --git a/modules/session-manager/src/lib.rs b/modules/session-manager/src/lib.rs index 2cbe0a438c..2079f8382b 100644 --- a/modules/session-manager/src/lib.rs +++ b/modules/session-manager/src/lib.rs @@ -70,8 +70,12 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] pub enum Event { - /// Scheduled session duration. \[block_number, session_index, session_duration\] - ScheduledSessionDuration(T::BlockNumber, SessionIndex, T::BlockNumber), + /// Scheduled session duration. + ScheduledSessionDuration { + block_number: T::BlockNumber, + session_index: SessionIndex, + session_duration: T::BlockNumber, + }, } /// The current session duration. @@ -157,11 +161,11 @@ pub mod module { let target_block_number = Self::do_schedule_session_duration(start_session, duration)?; - Self::deposit_event(Event::ScheduledSessionDuration( - target_block_number, - start_session, - duration, - )); + Self::deposit_event(Event::ScheduledSessionDuration { + block_number: target_block_number, + session_index: start_session, + session_duration: duration, + }); Ok(()) } } diff --git a/modules/session-manager/src/tests.rs b/modules/session-manager/src/tests.rs index 88f8e03584..af2d5bc143 100644 --- a/modules/session-manager/src/tests.rs +++ b/modules/session-manager/src/tests.rs @@ -41,9 +41,17 @@ fn schedule_session_duration_work() { ); assert_ok!(SessionManager::schedule_session_duration(Origin::root(), 1, 10)); - System::assert_last_event(Event::SessionManager(crate::Event::ScheduledSessionDuration(1, 1, 10))); + System::assert_last_event(Event::SessionManager(crate::Event::ScheduledSessionDuration { + block_number: 1, + session_index: 1, + session_duration: 10, + })); assert_ok!(SessionManager::schedule_session_duration(Origin::root(), 1, 11)); - System::assert_last_event(Event::SessionManager(crate::Event::ScheduledSessionDuration(10, 1, 11))); + System::assert_last_event(Event::SessionManager(crate::Event::ScheduledSessionDuration { + block_number: 10, + session_index: 1, + session_duration: 11, + })); SessionDuration::::put(0); assert_noop!( @@ -61,7 +69,11 @@ fn on_initialize_work() { assert_eq!(SessionManager::duration_offset(), 0); assert_ok!(SessionManager::schedule_session_duration(Origin::root(), 1, 11)); - System::assert_last_event(Event::SessionManager(crate::Event::ScheduledSessionDuration(10, 1, 11))); + System::assert_last_event(Event::SessionManager(crate::Event::ScheduledSessionDuration { + block_number: 10, + session_index: 1, + session_duration: 11, + })); assert_eq!(SessionDurationChanges::::iter().count(), 1); SessionManager::on_initialize(9); diff --git a/modules/staking-pool/src/lib.rs b/modules/staking-pool/src/lib.rs index acdc50639f..5c7758a60e 100644 --- a/modules/staking-pool/src/lib.rs +++ b/modules/staking-pool/src/lib.rs @@ -204,22 +204,36 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// Deposit staking currency(DOT) to staking pool and issue liquid - /// currency(LDOT). \[who, staking_amount_deposited, - /// liquid_amount_issued\] - MintLiquid(T::AccountId, Balance, Balance), + /// Deposit staking currency(DOT) to staking pool and issue liquid currency(LDOT). + MintLiquid { + who: T::AccountId, + staking_amount_deposited: Balance, + liquid_amount_issued: Balance, + }, /// Burn liquid currency(LDOT) and redeem staking currency(DOT) by - /// waiting for complete unbond eras. \[who, liquid_amount_burned, - /// staking_amount_redeemed\] - RedeemByUnbond(T::AccountId, Balance, Balance), + /// waiting for complete unbond eras. + RedeemByUnbond { + who: T::AccountId, + liquid_amount_burned: Balance, + staking_amount_redeemed: Balance, + }, /// Burn liquid currency(LDOT) and redeem staking currency(DOT) by free - /// pool immediately. \[who, fee_in_staking, liquid_amount_burned, - /// staking_amount_redeemed\] - RedeemByFreeUnbonded(T::AccountId, Balance, Balance, Balance), + /// pool immediately. + RedeemByFreeUnbonded { + who: T::AccountId, + fee_in_staking: Balance, + liquid_amount_burned: Balance, + staking_amount_redeemed: Balance, + }, /// Burn liquid currency(LDOT) and redeem staking currency(DOT) by claim - /// the unbonding_to_free of specific era. \[who, target_era, - /// fee_in_staking, liquid_amount_burned, staking_amount_redeemed\] - RedeemByClaimUnbonding(T::AccountId, EraIndex, Balance, Balance, Balance), + /// the unbonding_to_free of specific era. + RedeemByClaimUnbonding { + who: T::AccountId, + target_era: EraIndex, + fee_in_staking: Balance, + liquid_amount_burned: Balance, + staking_amount_redeemed: Balance, + }, } /// Current era index on Relaychain. @@ -742,7 +756,11 @@ impl HomaProtocol for Pallet { ledger.free_pool = ledger.free_pool.saturating_add(amount); - Self::deposit_event(Event::MintLiquid(who.clone(), amount, liquid_amount_to_issue)); + Self::deposit_event(Event::MintLiquid { + who: who.clone(), + staking_amount_deposited: amount, + liquid_amount_issued: liquid_amount_to_issue, + }); Ok(liquid_amount_to_issue) }) } @@ -789,11 +807,11 @@ impl HomaProtocol for Pallet { claimed_unbond.saturating_add(staking_amount_to_unbond), ); - Self::deposit_event(Event::RedeemByUnbond( - who.clone(), - liquid_amount_to_burn, - staking_amount_to_unbond, - )); + Self::deposit_event(Event::RedeemByUnbond { + who: who.clone(), + liquid_amount_burned: liquid_amount_to_burn, + staking_amount_redeemed: staking_amount_to_unbond, + }); } Ok(()) @@ -864,12 +882,12 @@ impl HomaProtocol for Pallet { ledger.free_pool = ledger.free_pool.saturating_sub(staking_amount_to_retrieve); - Self::deposit_event(Event::RedeemByFreeUnbonded( - who.clone(), - liquid_amount_to_burn, - staking_amount_to_retrieve, - fee_in_staking, - )); + Self::deposit_event(Event::RedeemByFreeUnbonded { + who: who.clone(), + fee_in_staking: liquid_amount_to_burn, + liquid_amount_burned: staking_amount_to_retrieve, + staking_amount_redeemed: fee_in_staking, + }); } Ok(()) @@ -948,13 +966,13 @@ impl HomaProtocol for Pallet { }); ledger.unbonding_to_free = ledger.unbonding_to_free.saturating_sub(staking_amount_to_claim); - Self::deposit_event(Event::RedeemByClaimUnbonding( - who.clone(), + Self::deposit_event(Event::RedeemByClaimUnbonding { + who: who.clone(), target_era, - liquid_amount_to_burn, - staking_amount_to_claim, - fee_in_staking, - )); + fee_in_staking: liquid_amount_to_burn, + liquid_amount_burned: staking_amount_to_claim, + staking_amount_redeemed: fee_in_staking, + }); } Ok(()) diff --git a/modules/staking-pool/src/tests.rs b/modules/staking-pool/src/tests.rs index 0a1492b650..7eeb2e0d82 100644 --- a/modules/staking-pool/src/tests.rs +++ b/modules/staking-pool/src/tests.rs @@ -780,7 +780,11 @@ fn mint_work() { to_unbond_next_era: (0, 0) } ); - System::assert_last_event(Event::StakingPoolModule(crate::Event::MintLiquid(ALICE, 500, 5000))); + System::assert_last_event(Event::StakingPoolModule(crate::Event::MintLiquid { + who: ALICE, + staking_amount_deposited: 500, + liquid_amount_issued: 5000, + })); RebalancePhase::::put(Phase::Started); assert_noop!( @@ -850,7 +854,11 @@ fn redeem_by_unbond_work() { assert_eq!(StakingPoolModule::next_era_unbonds(&ALICE), 0); assert_ok!(StakingPoolModule::redeem_by_unbond(&ALICE, 1000)); - System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByUnbond(ALICE, 1000, 100))); + System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByUnbond { + who: ALICE, + liquid_amount_burned: 1000, + staking_amount_redeemed: 100, + })); assert_eq!(CurrenciesModule::total_issuance(LDOT), 9000); assert_eq!(CurrenciesModule::free_balance(LDOT, &ALICE), 0); assert_eq!( @@ -869,7 +877,11 @@ fn redeem_by_unbond_work() { assert_eq!(StakingPoolModule::next_era_unbonds(&BOB), 0); assert_ok!(StakingPoolModule::redeem_by_unbond(&BOB, 9000)); - System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByUnbond(BOB, 4000, 400))); + System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByUnbond { + who: BOB, + liquid_amount_burned: 4000, + staking_amount_redeemed: 400, + })); assert_eq!(CurrenciesModule::total_issuance(LDOT), 5000); assert_eq!(CurrenciesModule::free_balance(LDOT, &BOB), 5000); assert_eq!( @@ -922,9 +934,12 @@ fn redeem_by_free_unbonded_work() { assert_eq!(CurrenciesModule::total_issuance(LDOT), 10000); assert_ok!(StakingPoolModule::redeem_by_free_unbonded(&ALICE, 1000)); - System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByFreeUnbonded( - ALICE, 1000, 80, 20, - ))); + System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByFreeUnbonded { + who: ALICE, + fee_in_staking: 1000, + liquid_amount_burned: 80, + staking_amount_redeemed: 20, + })); assert_eq!(StakingPoolModule::staking_pool_ledger().free_pool, 420); assert_eq!( CurrenciesModule::free_balance(DOT, &StakingPoolModule::account_id()), @@ -938,9 +953,12 @@ fn redeem_by_free_unbonded_work() { // when overflow available assert_ok!(StakingPoolModule::redeem_by_free_unbonded(&BOB, 9000)); - System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByFreeUnbonded( - BOB, 3662, 300, 74, - ))); + System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByFreeUnbonded { + who: BOB, + fee_in_staking: 3662, + liquid_amount_burned: 300, + staking_amount_redeemed: 74, + })); assert_eq!(StakingPoolModule::staking_pool_ledger().free_pool, 120); assert_eq!( CurrenciesModule::free_balance(DOT, &StakingPoolModule::account_id()), @@ -998,9 +1016,13 @@ fn redeem_by_claim_unbonding_work() { ); assert_ok!(StakingPoolModule::redeem_by_claim_unbonding(&ALICE, 1000, 4)); - System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByClaimUnbonding( - ALICE, 4, 1000, 80, 20, - ))); + System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByClaimUnbonding { + who: ALICE, + target_era: 4, + fee_in_staking: 1000, + liquid_amount_burned: 80, + staking_amount_redeemed: 20, + })); assert_eq!( StakingPoolModule::staking_pool_ledger(), Ledger { @@ -1017,9 +1039,13 @@ fn redeem_by_claim_unbonding_work() { // when overflow available assert_ok!(StakingPoolModule::redeem_by_claim_unbonding(&BOB, 10000, 4)); - System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByClaimUnbonding( - BOB, 4, 3910, 316, 79, - ))); + System::assert_last_event(Event::StakingPoolModule(crate::Event::RedeemByClaimUnbonding { + who: BOB, + target_era: 4, + fee_in_staking: 3910, + liquid_amount_burned: 316, + staking_amount_redeemed: 79, + })); assert_eq!( StakingPoolModule::staking_pool_ledger(), Ledger { diff --git a/modules/transaction-pause/src/lib.rs b/modules/transaction-pause/src/lib.rs index 17cc7343b1..83a5c8ef3f 100644 --- a/modules/transaction-pause/src/lib.rs +++ b/modules/transaction-pause/src/lib.rs @@ -62,10 +62,16 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] pub enum Event { - /// Paused transaction . \[pallet_name_bytes, function_name_bytes\] - TransactionPaused(Vec, Vec), - /// Unpaused transaction . \[pallet_name_bytes, function_name_bytes\] - TransactionUnpaused(Vec, Vec), + /// Paused transaction + TransactionPaused { + pallet_name_bytes: Vec, + function_name_bytes: Vec, + }, + /// Unpaused transaction + TransactionUnpaused { + pallet_name_bytes: Vec, + function_name_bytes: Vec, + }, } /// The paused transaction map @@ -98,7 +104,10 @@ pub mod module { PausedTransactions::::mutate_exists((pallet_name.clone(), function_name.clone()), |maybe_paused| { if maybe_paused.is_none() { *maybe_paused = Some(()); - Self::deposit_event(Event::TransactionPaused(pallet_name, function_name)); + Self::deposit_event(Event::TransactionPaused { + pallet_name_bytes: pallet_name, + function_name_bytes: function_name, + }); } }); Ok(()) @@ -113,7 +122,10 @@ pub mod module { ) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; if PausedTransactions::::take((&pallet_name, &function_name)).is_some() { - Self::deposit_event(Event::TransactionUnpaused(pallet_name, function_name)); + Self::deposit_event(Event::TransactionUnpaused { + pallet_name_bytes: pallet_name, + function_name_bytes: function_name, + }); }; Ok(()) } diff --git a/modules/transaction-pause/src/tests.rs b/modules/transaction-pause/src/tests.rs index 3a3cd7c780..104f5fda50 100644 --- a/modules/transaction-pause/src/tests.rs +++ b/modules/transaction-pause/src/tests.rs @@ -52,10 +52,10 @@ fn pause_transaction_work() { b"Balances".to_vec(), b"transfer".to_vec() )); - System::assert_last_event(Event::TransactionPause(crate::Event::TransactionPaused( - b"Balances".to_vec(), - b"transfer".to_vec(), - ))); + System::assert_last_event(Event::TransactionPause(crate::Event::TransactionPaused { + pallet_name_bytes: b"Balances".to_vec(), + function_name_bytes: b"transfer".to_vec(), + })); assert_eq!( TransactionPause::paused_transactions((b"Balances".to_vec(), b"transfer".to_vec())), Some(()) @@ -110,10 +110,10 @@ fn unpause_transaction_work() { b"Balances".to_vec(), b"transfer".to_vec() )); - System::assert_last_event(Event::TransactionPause(crate::Event::TransactionUnpaused( - b"Balances".to_vec(), - b"transfer".to_vec(), - ))); + System::assert_last_event(Event::TransactionPause(crate::Event::TransactionUnpaused { + pallet_name_bytes: b"Balances".to_vec(), + function_name_bytes: b"transfer".to_vec(), + })); assert_eq!( TransactionPause::paused_transactions((b"Balances".to_vec(), b"transfer".to_vec())), None diff --git a/runtime/mandala/src/benchmarking/session_manager.rs b/runtime/mandala/src/benchmarking/session_manager.rs index 72e7fcf28a..2d19cc371e 100644 --- a/runtime/mandala/src/benchmarking/session_manager.rs +++ b/runtime/mandala/src/benchmarking/session_manager.rs @@ -41,7 +41,7 @@ runtime_benchmarks! { ); } verify { - assert_last_event(module_session_manager::Event::ScheduledSessionDuration(10,1,100).into()); + assert_last_event(module_session_manager::Event::ScheduledSessionDuration{block_number: 10, session_index: 1, session_duration: 100}.into()); } on_initialize_skip { From 7c1ed1c364eeeebb75e5bffba530c6a834a5d6cc Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Fri, 17 Dec 2021 14:58:22 +1300 Subject: [PATCH 05/13] Refactored events in ecosystem and stable-asset --- ecosystem-modules/compound-cash/src/lib.rs | 12 ++- ecosystem-modules/ren/renvm-bridge/src/lib.rs | 26 +++-- ecosystem-modules/stable-asset | 2 +- ecosystem-modules/starport/src/lib.rs | 56 +++++++---- ecosystem-modules/starport/src/tests.rs | 95 +++++++++++++++---- runtime/integration-tests/src/authority.rs | 16 ++-- 6 files changed, 154 insertions(+), 53 deletions(-) diff --git a/ecosystem-modules/compound-cash/src/lib.rs b/ecosystem-modules/compound-cash/src/lib.rs index 29788e08bc..2d2f21598f 100644 --- a/ecosystem-modules/compound-cash/src/lib.rs +++ b/ecosystem-modules/compound-cash/src/lib.rs @@ -56,7 +56,11 @@ pub mod module { #[pallet::generate_deposit(pub fn deposit_event)] pub enum Event { /// Set the future yield for the Cash asset. - FutureYieldSet(Balance, CashYieldIndex, Moment), + FutureYieldSet { + yield_amount: Balance, + index: CashYieldIndex, + timestamp: Moment, + }, } /// Stores a history of yields that have already been consumed. @@ -102,7 +106,11 @@ impl Pallet { ); FutureYield::::insert(yield_index, (next_cash_yield, timestamp_effective)); - + Self::deposit_event(Event::FutureYieldSet { + yield_amount: next_cash_yield, + index: yield_index, + timestamp: timestamp_effective, + }); Ok(()) } } diff --git a/ecosystem-modules/ren/renvm-bridge/src/lib.rs b/ecosystem-modules/ren/renvm-bridge/src/lib.rs index 291a055a5b..c515c9f690 100644 --- a/ecosystem-modules/ren/renvm-bridge/src/lib.rs +++ b/ecosystem-modules/ren/renvm-bridge/src/lib.rs @@ -90,12 +90,16 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] pub enum Event { - /// Asset minted. \[owner, amount\] - Minted(T::AccountId, Balance), - /// Asset burnt in this chain \[owner, dest, amount\] - Burnt(T::AccountId, DestAddress, Balance), - /// Rotated key \[new_key\] - RotatedKey(PublicKey), + /// Asset minted. + Minted { owner: T::AccountId, amount: Balance }, + /// Asset burnt in this chain. + Burnt { + owner: T::AccountId, + dest: DestAddress, + amount: Balance, + }, + /// Rotated key + RotatedKey { key: PublicKey }, } /// The RenVM split public key @@ -185,7 +189,7 @@ pub mod module { Pays::Yes, DispatchClass::Normal, ); - Self::deposit_event(Event::Minted(who, amount)); + Self::deposit_event(Event::Minted { owner: who, amount }); Ok(()) } @@ -201,7 +205,11 @@ pub mod module { T::BridgedTokenCurrency::withdraw(&sender, amount)?; BurnEvents::::insert(this_id, (frame_system::Pallet::::block_number(), &to, amount)); - Self::deposit_event(Event::Burnt(sender, to, amount)); + Self::deposit_event(Event::Burnt { + owner: sender, + dest: to, + amount, + }); Ok(()) })?; @@ -218,7 +226,7 @@ pub mod module { pub fn rotate_key(origin: OriginFor, new_key: PublicKey, sig: EcdsaSignature) -> DispatchResult { ensure_none(origin)?; Self::do_rotate_key(new_key, sig); - Self::deposit_event(Event::RotatedKey(new_key)); + Self::deposit_event(Event::RotatedKey { key: new_key }); Ok(()) } diff --git a/ecosystem-modules/stable-asset b/ecosystem-modules/stable-asset index 1d42c49791..0f5950493e 160000 --- a/ecosystem-modules/stable-asset +++ b/ecosystem-modules/stable-asset @@ -1 +1 @@ -Subproject commit 1d42c49791ab5244a30c123c58799740fb7281ab +Subproject commit 0f5950493e8a6a57ea854fbf64be8df9ace20cc6 diff --git a/ecosystem-modules/starport/src/lib.rs b/ecosystem-modules/starport/src/lib.rs index fb3a397be0..9a10870de0 100644 --- a/ecosystem-modules/starport/src/lib.rs +++ b/ecosystem-modules/starport/src/lib.rs @@ -112,21 +112,32 @@ pub mod module { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// User has locked some asset and uploaded them into Compound. [currency_id, amount, user] - AssetLockedTo(CurrencyId, Balance, T::AccountId), + /// User has locked some asset and uploaded them into Compound. + AssetLockedTo { + currency_id: CurrencyId, + amount: Balance, + user: T::AccountId, + }, - /// The user has unlocked some asset and downloaded them back into Acala. [currency_id, - /// amount, user] - AssetUnlocked(CurrencyId, Balance, T::AccountId), + /// The user has unlocked some asset and downloaded them back into Acala. + AssetUnlocked { + currency_id: CurrencyId, + amount: Balance, + user: T::AccountId, + }, /// The list of authorities has been updated. GatewayAuthoritiesChanged, - /// The supply cap for an asset has been updated. [currency_id, new_cap] - SupplyCapSet(CurrencyId, Balance), + /// The supply cap for an asset has been updated. + SupplyCapSet { currency_id: CurrencyId, new_cap: Balance }, - /// The future yield for CASH is set. [yield, yield_index, timestamp] - FutureYieldSet(Balance, CashYieldIndex, Moment), + /// The future yield for CASH is set. + FutureYieldSet { + yield_amount: Balance, + index: CashYieldIndex, + timestamp: Moment, + }, } #[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq, TypeInfo)] @@ -308,7 +319,10 @@ pub mod module { match notice.payload { GatewayNoticePayload::SetSupplyCap(currency_id, amount) => { SupplyCaps::::insert(¤cy_id, amount); - Self::deposit_event(Event::::SupplyCapSet(currency_id, amount)); + Self::deposit_event(Event::::SupplyCapSet { + currency_id, + new_cap: amount, + }); Ok(()) } GatewayNoticePayload::ChangeAuthorities(new_authorities) => { @@ -334,11 +348,11 @@ pub mod module { next_cash_yield_start, } => { T::Cash::set_future_yield(next_cash_yield, next_cash_yield_index, next_cash_yield_start)?; - Self::deposit_event(Event::::FutureYieldSet( - next_cash_yield, - next_cash_yield_index, - next_cash_yield_start, - )); + Self::deposit_event(Event::::FutureYieldSet { + yield_amount: next_cash_yield, + index: next_cash_yield_index, + timestamp: next_cash_yield_start, + }); Ok(()) } }?; @@ -383,7 +397,11 @@ impl Pallet { SupplyCaps::::insert(¤cy_id, current_supply_cap - locked_amount); // emit an event - Self::deposit_event(Event::::AssetLockedTo(currency_id, locked_amount, to)); + Self::deposit_event(Event::::AssetLockedTo { + currency_id: currency_id, + amount: locked_amount, + user: to, + }); Ok(()) } @@ -406,7 +424,11 @@ impl Pallet { }?; // emit an event - Self::deposit_event(Event::::AssetUnlocked(currency_id, unlock_amount, to)); + Self::deposit_event(Event::::AssetUnlocked { + currency_id, + amount: unlock_amount, + user: to, + }); Ok(()) } diff --git a/ecosystem-modules/starport/src/tests.rs b/ecosystem-modules/starport/src/tests.rs index 2f9e1078b1..1d3acb5dac 100644 --- a/ecosystem-modules/starport/src/tests.rs +++ b/ecosystem-modules/starport/src/tests.rs @@ -60,7 +60,11 @@ fn lock_works() { // Verify the event deposited for Gateway is correct. assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::AssetLockedTo(ACALA, INITIAL_BALANCE, ALICE)) + Event::Starport(crate::Event::AssetLockedTo { + currency_id: ACALA, + amount: INITIAL_BALANCE, + user: ALICE + }) ); // Locked CASH assets are burned instead @@ -79,7 +83,11 @@ fn lock_works() { // Verify the event deposited for Gateway is correct. assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::AssetLockedTo(CASH, INITIAL_BALANCE, ALICE)) + Event::Starport(crate::Event::AssetLockedTo { + currency_id: CASH, + amount: INITIAL_BALANCE, + user: ALICE + }) ) }); } @@ -105,7 +113,11 @@ fn lock_to_works() { // Verify the event deposited for Gateway is correct. assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::AssetLockedTo(ACALA, INITIAL_BALANCE, BOB)) + Event::Starport(crate::Event::AssetLockedTo { + currency_id: ACALA, + amount: INITIAL_BALANCE, + user: BOB + }) ); }); } @@ -153,7 +165,11 @@ fn invoke_can_set_supply_cap() { // Verify the event deposited for Gateway is correct. assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::AssetLockedTo(ACALA, 100, ALICE)) + Event::Starport(crate::Event::AssetLockedTo { + currency_id: ACALA, + amount: 100, + user: ALICE + }) ); // Lock fails due to insufficient Market cap @@ -171,14 +187,21 @@ fn invoke_can_set_supply_cap() { )); assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::SupplyCapSet(ACALA, 100)) + Event::Starport(crate::Event::SupplyCapSet { + currency_id: ACALA, + new_cap: 100 + }) ); // Lock will now work assert_ok!(Starport::lock(Origin::signed(ALICE), ACALA, 100)); assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::AssetLockedTo(ACALA, 100, ALICE)) + Event::Starport(crate::Event::AssetLockedTo { + currency_id: ACALA, + amount: 100, + user: ALICE + }) ); }); } @@ -194,7 +217,11 @@ fn invoke_can_set_authorities() { // Verify the event deposited for Gateway is correct. assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::AssetLockedTo(ACALA, 100, ALICE)) + Event::Starport(crate::Event::AssetLockedTo { + currency_id: ACALA, + amount: 100, + user: ALICE + }) ); let new_authorities = vec![AccountId::new([0xA0; 32]), AccountId::new([0xA1; 32])]; @@ -267,7 +294,11 @@ fn invoke_can_unlock_asset() { // Verify the event deposited for Gateway is correct. assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::AssetLockedTo(ACALA, 500, ALICE)) + Event::Starport(crate::Event::AssetLockedTo { + currency_id: ACALA, + amount: 500, + user: ALICE + }) ); // Unlock the locked asset @@ -286,7 +317,11 @@ fn invoke_can_unlock_asset() { )); assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::AssetUnlocked(ACALA, 500, ALICE)) + Event::Starport(crate::Event::AssetUnlocked { + currency_id: ACALA, + amount: 500, + user: ALICE + }) ); // Unlock will fail with insufficient asset @@ -329,7 +364,11 @@ fn invoke_can_unlock_asset() { )); assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::AssetUnlocked(CASH, 100000, ALICE)) + Event::Starport(crate::Event::AssetUnlocked { + currency_id: CASH, + amount: 100000, + user: ALICE + }) ); }); } @@ -352,7 +391,11 @@ fn invoke_can_set_future_cash_yield() { )); assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::FutureYieldSet(1000, 0, 0)) + Event::Starport(crate::Event::FutureYieldSet { + yield_amount: 1000, + index: 0, + timestamp: 0 + }) ); }); } @@ -375,7 +418,11 @@ fn notices_cannot_be_invoked_twice() { )); assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::FutureYieldSet(1000, 0, 0)) + Event::Starport(crate::Event::FutureYieldSet { + yield_amount: 1000, + index: 0, + timestamp: 0 + }) ); assert_noop!( @@ -403,7 +450,11 @@ fn notices_are_invoked_by_any_account() { )); assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::FutureYieldSet(1000, 0, 0)) + Event::Starport(crate::Event::FutureYieldSet { + yield_amount: 1000, + index: 0, + timestamp: 0 + }) ); notice.id = 1; @@ -414,7 +465,11 @@ fn notices_are_invoked_by_any_account() { )); assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::FutureYieldSet(1000, 0, 0)) + Event::Starport(crate::Event::FutureYieldSet { + yield_amount: 1000, + index: 0, + timestamp: 0 + }) ); notice.id = 2; @@ -425,7 +480,11 @@ fn notices_are_invoked_by_any_account() { )); assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::FutureYieldSet(1000, 0, 0)) + Event::Starport(crate::Event::FutureYieldSet { + yield_amount: 1000, + index: 0, + timestamp: 0 + }) ); }); } @@ -452,7 +511,11 @@ fn notices_can_only_be_invoked_with_enough_signatures() { )); assert_eq!( System::events().iter().last().unwrap().event, - Event::Starport(crate::Event::FutureYieldSet(1000, 0, 0)) + Event::Starport(crate::Event::FutureYieldSet { + yield_amount: 1000, + index: 0, + timestamp: 0 + }) ); // 1 signer is insufficient authorisation diff --git a/runtime/integration-tests/src/authority.rs b/runtime/integration-tests/src/authority.rs index fd7baeed17..ef36ef6872 100644 --- a/runtime/integration-tests/src/authority.rs +++ b/runtime/integration-tests/src/authority.rs @@ -251,13 +251,13 @@ fn test_authority_module() { let pallets_origin = Box::new(schedule_origin.caller().clone()); assert_ok!(Authority::cancel_scheduled_dispatch(Origin::root(), pallets_origin, 5)); - System::assert_last_event(Event::Authority(orml_authority::Event::Cancelled( - OriginCaller::Authority(DelayedOrigin { + System::assert_last_event(Event::Authority(orml_authority::Event::Cancelled { + origin: OriginCaller::Authority(DelayedOrigin { delay: 1, origin: Box::new(OriginCaller::system(RawOrigin::Root)), }), - 5, - ))); + index: 5, + })); assert_ok!(Authority::schedule_dispatch( Origin::root(), @@ -276,9 +276,9 @@ fn test_authority_module() { Box::new(frame_system::RawOrigin::Root.into()), 6 )); - System::assert_last_event(Event::Authority(orml_authority::Event::Cancelled( - OriginCaller::system(RawOrigin::Root), - 6, - ))); + System::assert_last_event(Event::Authority(orml_authority::Event::Cancelled { + origin: OriginCaller::system(RawOrigin::Root), + index: 6, + })); }); } From 149e108d9d44beb6db91320e44fe898c2c79bef5 Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Fri, 17 Dec 2021 14:59:33 +1300 Subject: [PATCH 06/13] updated stable asset ref --- ecosystem-modules/stable-asset | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ecosystem-modules/stable-asset b/ecosystem-modules/stable-asset index 0f5950493e..d04b525e68 160000 --- a/ecosystem-modules/stable-asset +++ b/ecosystem-modules/stable-asset @@ -1 +1 @@ -Subproject commit 0f5950493e8a6a57ea854fbf64be8df9ace20cc6 +Subproject commit d04b525e6858b52a99b4c00db9260eda90362e35 From 0a17fc3915dd54ad0d25c4d5ee3f46990264b620 Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Fri, 17 Dec 2021 19:32:43 +1300 Subject: [PATCH 07/13] Fixed a broken test --- modules/idle-scheduler/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/idle-scheduler/src/lib.rs b/modules/idle-scheduler/src/lib.rs index 8cf299e492..2d13d62b99 100644 --- a/modules/idle-scheduler/src/lib.rs +++ b/modules/idle-scheduler/src/lib.rs @@ -138,7 +138,7 @@ impl Pallet { // Deposit event and remove completed tasks. for (id, result) in completed_tasks { Self::deposit_event(Event::::TaskDispatched { - dispatch_id: id, + task_id: id, result: result.result, }); Tasks::::remove(id); From a0b23296770fe48edd2b26c0d1ce7fc1b8d12993 Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Mon, 20 Dec 2021 09:31:40 +1300 Subject: [PATCH 08/13] Merged event refactor in stable-asset --- Cargo.lock | 120 ++++----------------- ecosystem-modules/stable-asset | 2 +- modules/example/src/lib.rs | 4 +- modules/example/src/tests.rs | 2 +- runtime/integration-tests/src/authority.rs | 32 +++--- 5 files changed, 43 insertions(+), 117 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 551ece2805..58bb340eb3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -778,6 +778,15 @@ dependencies = [ "sp-std", ] +[[package]] +name = "bencher-procedural" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "bimap" version = "0.6.1" @@ -1207,20 +1216,6 @@ dependencies = [ "serde", ] -[[package]] -name = "cargo_metadata" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "081e3f0755c1f380c2d010481b6fa2e02973586d5f2b24eebb7a2a1d98b143d8" -dependencies = [ - "camino", - "cargo-platform", - "semver 0.11.0", - "semver-parser 0.10.2", - "serde", - "serde_json", -] - [[package]] name = "cargo_metadata" version = "0.14.1" @@ -1357,42 +1352,12 @@ dependencies = [ "ansi_term", "atty", "bitflags", - "strsim 0.8.0", - "textwrap 0.11.0", + "strsim", + "textwrap", "unicode-width", "vec_map", ] -[[package]] -name = "clap" -version = "3.0.0-rc.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "098d281b47bf725a0bddd829e0070ee76560faab8af123050a86c440d7f0a1fd" -dependencies = [ - "atty", - "bitflags", - "clap_derive", - "indexmap", - "lazy_static", - "os_str_bytes", - "strsim 0.10.0", - "termcolor", - "textwrap 0.14.2", -] - -[[package]] -name = "clap_derive" -version = "3.0.0-rc.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26de8102ffb96701066cea36f9a104285b67fbcc302a520640289d476c15ed8a" -dependencies = [ - "heck", - "proc-macro-error", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "cloudabi" version = "0.0.3" @@ -2757,7 +2722,7 @@ dependencies = [ "chrono", "frame-benchmarking", "frame-support", - "handlebars 4.1.5", + "handlebars", "linked-hash-map", "log", "parity-scale-codec", @@ -3243,20 +3208,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "handlebars" -version = "3.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4498fc115fa7d34de968184e473529abb40eeb6be8bc5f7faba3d08c316cb3e3" -dependencies = [ - "log", - "pest", - "pest_derive", - "quick-error 2.0.1", - "serde", - "serde_json", -] - [[package]] name = "handlebars" version = "4.1.5" @@ -6434,11 +6385,14 @@ name = "orml-bencher" version = "0.4.1-dev" dependencies = [ "ansi_term", + "bencher-procedural", "build-helper", - "cargo_metadata 0.13.1", + "cargo_metadata", "frame-benchmarking", + "hash-db", "linregress", "parity-scale-codec", + "parking_lot 0.11.2", "paste", "rand 0.8.4", "sc-client-db", @@ -6447,11 +6401,13 @@ dependencies = [ "serde", "serde_json", "sp-core", + "sp-externalities", "sp-io", "sp-maybe-compressed-blob", "sp-runtime-interface", "sp-state-machine", "sp-std", + "sp-storage", "tempfile", "toml", "walkdir", @@ -6681,7 +6637,6 @@ version = "0.4.1-dev" dependencies = [ "frame-support", "frame-system", - "orml-bencher", "pallet-balances", "parity-scale-codec", "scale-info", @@ -6689,7 +6644,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-std", - "spin 0.7.1", "weight-meter-procedural", ] @@ -6752,15 +6706,6 @@ dependencies = [ "xcm-simulator", ] -[[package]] -name = "os_str_bytes" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" -dependencies = [ - "memchr", -] - [[package]] name = "owning_ref" version = "0.4.1" @@ -9703,7 +9648,7 @@ dependencies = [ "cc", "libc", "once_cell", - "spin 0.5.2", + "spin", "untrusted", "web-sys", "winapi 0.3.9", @@ -11269,7 +11214,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" dependencies = [ "semver-parser 0.10.2", - "serde", ] [[package]] @@ -12271,12 +12215,6 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" -[[package]] -name = "spin" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13287b4da9d1207a4f4929ac390916d64eacfe236a487e9a9f5b3be392be5162" - [[package]] name = "ss58-registry" version = "1.8.1" @@ -12347,19 +12285,13 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - [[package]] name = "structopt" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40b9788f4202aa75c240ecc9c15c65185e6a39ccdeb0fd5d008b98825464c87c" dependencies = [ - "clap 2.34.0", + "clap", "lazy_static", "structopt-derive", ] @@ -12549,7 +12481,7 @@ source = "git+https://github.com/paritytech//substrate?rev=fcc54a72973d03afe7bf9 dependencies = [ "ansi_term", "build-helper", - "cargo_metadata 0.14.1", + "cargo_metadata", "sp-maybe-compressed-blob", "tempfile", "toml", @@ -12680,12 +12612,6 @@ dependencies = [ "unicode-width", ] -[[package]] -name = "textwrap" -version = "0.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0066c8d12af8b5acd21e00547c3797fde4e8677254a7ee429176ccebbe93dd80" - [[package]] name = "thiserror" version = "1.0.30" @@ -13634,8 +13560,8 @@ dependencies = [ name = "weight-gen" version = "0.4.1-dev" dependencies = [ - "clap 3.0.0-rc.3", - "handlebars 3.5.5", + "clap", + "handlebars", "serde", "serde_json", ] diff --git a/ecosystem-modules/stable-asset b/ecosystem-modules/stable-asset index d04b525e68..3e12b10758 160000 --- a/ecosystem-modules/stable-asset +++ b/ecosystem-modules/stable-asset @@ -1 +1 @@ -Subproject commit d04b525e6858b52a99b4c00db9260eda90362e35 +Subproject commit 3e12b10758ad757934ae4260f5d111ac2376b039 diff --git a/modules/example/src/lib.rs b/modules/example/src/lib.rs index 6c02816674..d71b5e7555 100644 --- a/modules/example/src/lib.rs +++ b/modules/example/src/lib.rs @@ -54,7 +54,7 @@ pub mod module { #[pallet::generate_deposit(fn deposit_event)] pub enum Event { /// Dummy event, just here so there's a generic type that's used. - Dummy { name: T::Balance }, + Dummy { value: T::Balance }, } #[pallet::type_value] @@ -129,7 +129,7 @@ pub mod module { ensure_root(origin)?; Dummy::::put(&new_value); - Self::deposit_event(Event::Dummy { name: new_value }); + Self::deposit_event(Event::Dummy { value: new_value }); Ok(()) } diff --git a/modules/example/src/tests.rs b/modules/example/src/tests.rs index 9920649dcd..63ac81facb 100644 --- a/modules/example/src/tests.rs +++ b/modules/example/src/tests.rs @@ -29,7 +29,7 @@ fn set_dummy_work() { assert_eq!(Example::dummy(), None); assert_ok!(Example::set_dummy(Origin::root(), 20)); assert_eq!(Example::dummy(), Some(20)); - System::assert_last_event(Event::Example(crate::Event::Dummy(20))); + System::assert_last_event(Event::Example(crate::Event::Dummy { value: 20 })); }); } diff --git a/runtime/integration-tests/src/authority.rs b/runtime/integration-tests/src/authority.rs index ef36ef6872..941cdf03ad 100644 --- a/runtime/integration-tests/src/authority.rs +++ b/runtime/integration-tests/src/authority.rs @@ -104,13 +104,13 @@ fn test_authority_module() { true, Box::new(call.clone()) )); - System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled( - OriginCaller::Authority(DelayedOrigin { + System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled { + origin: OriginCaller::Authority(DelayedOrigin { delay: one_day_later - 1, origin: Box::new(OriginCaller::system(RawOrigin::Root)), }), - 1, - ))); + index: 1, + })); run_to_block(one_day_later); @@ -185,10 +185,10 @@ fn test_authority_module() { false, Box::new(call.clone()) )); - System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled( - OriginCaller::system(RawOrigin::Root), - 3, - ))); + System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled { + origin: OriginCaller::system(RawOrigin::Root), + index: 3, + })); run_to_block(seven_days_later + 1); System::assert_last_event(Event::Scheduler(pallet_scheduler::Event::::Dispatched( @@ -229,13 +229,13 @@ fn test_authority_module() { true, Box::new(call.clone()) )); - System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled( - OriginCaller::Authority(DelayedOrigin { + System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled { + origin: OriginCaller::Authority(DelayedOrigin { delay: 1, origin: Box::new(OriginCaller::system(RawOrigin::Root)), }), - 5, - ))); + index: 5, + })); let schedule_origin = { let origin: ::Origin = From::from(Origin::root()); @@ -266,10 +266,10 @@ fn test_authority_module() { false, Box::new(call.clone()) )); - System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled( - OriginCaller::system(RawOrigin::Root), - 6, - ))); + System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled { + origin: OriginCaller::system(RawOrigin::Root), + index: 6, + })); assert_ok!(Authority::cancel_scheduled_dispatch( Origin::root(), From 56606a55cfd60cc65946f29ac058c2990e023641 Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Mon, 20 Dec 2021 10:19:25 +1300 Subject: [PATCH 09/13] Increased the call size test --- runtime/acala/src/lib.rs | 5 +++-- runtime/karura/src/lib.rs | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/runtime/acala/src/lib.rs b/runtime/acala/src/lib.rs index 20df39c8a1..abbb4ff50d 100644 --- a/runtime/acala/src/lib.rs +++ b/runtime/acala/src/lib.rs @@ -2306,9 +2306,10 @@ mod tests { #[test] fn check_call_size() { + println!("{:?}", core::mem::size_of::()); assert!( - core::mem::size_of::() <= 230, - "size of Call is more than 230 bytes: some calls have too big arguments, use Box to \ + core::mem::size_of::() <= 240, + "size of Call is more than 240 bytes: some calls have too big arguments, use Box to \ reduce the size of Call. If the limit is too strong, maybe consider increasing the limit", ); diff --git a/runtime/karura/src/lib.rs b/runtime/karura/src/lib.rs index a89930423f..530ee90950 100644 --- a/runtime/karura/src/lib.rs +++ b/runtime/karura/src/lib.rs @@ -2419,8 +2419,8 @@ mod tests { #[test] fn check_call_size() { assert!( - core::mem::size_of::() <= 230, - "size of Call is more than 230 bytes: some calls have too big arguments, use Box to \ + core::mem::size_of::() <= 240, + "size of Call is more than 240 bytes: some calls have too big arguments, use Box to \ reduce the size of Call. If the limit is too strong, maybe consider increasing the limit", ); From ede516147432f713d7f548094632ceb563f8edb6 Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Mon, 20 Dec 2021 18:28:48 +1300 Subject: [PATCH 10/13] Refactored event in orml. --- Cargo.lock | 120 +++++--------------------- ecosystem-modules/stable-asset | 2 +- ecosystem-modules/starport/src/lib.rs | 2 +- modules/auction-manager/src/lib.rs | 2 +- modules/cdp-engine/src/lib.rs | 4 +- modules/dex/src/lib.rs | 14 ++- modules/evm/src/lib.rs | 2 +- modules/homa-lite/src/lib.rs | 8 +- modules/homa-lite/src/tests.rs | 36 ++++++-- modules/incentives/src/lib.rs | 6 +- orml | 2 +- 11 files changed, 69 insertions(+), 129 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c9a99e1572..58bb340eb3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -778,6 +778,15 @@ dependencies = [ "sp-std", ] +[[package]] +name = "bencher-procedural" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "bimap" version = "0.6.1" @@ -1207,20 +1216,6 @@ dependencies = [ "serde", ] -[[package]] -name = "cargo_metadata" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "081e3f0755c1f380c2d010481b6fa2e02973586d5f2b24eebb7a2a1d98b143d8" -dependencies = [ - "camino", - "cargo-platform", - "semver 0.11.0", - "semver-parser 0.10.2", - "serde", - "serde_json", -] - [[package]] name = "cargo_metadata" version = "0.14.1" @@ -1357,42 +1352,12 @@ dependencies = [ "ansi_term", "atty", "bitflags", - "strsim 0.8.0", - "textwrap 0.11.0", + "strsim", + "textwrap", "unicode-width", "vec_map", ] -[[package]] -name = "clap" -version = "3.0.0-rc.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9468f8012246b0836c6fd11725102b0844254985f2462b6c637d50040ef49df0" -dependencies = [ - "atty", - "bitflags", - "clap_derive", - "indexmap", - "lazy_static", - "os_str_bytes", - "strsim 0.10.0", - "termcolor", - "textwrap 0.14.2", -] - -[[package]] -name = "clap_derive" -version = "3.0.0-rc.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b72e1af32a4de4d21a43d26de33fe69c00e895371bd8b1523d674f011b610467" -dependencies = [ - "heck", - "proc-macro-error", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "cloudabi" version = "0.0.3" @@ -2757,7 +2722,7 @@ dependencies = [ "chrono", "frame-benchmarking", "frame-support", - "handlebars 4.1.5", + "handlebars", "linked-hash-map", "log", "parity-scale-codec", @@ -3243,20 +3208,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "handlebars" -version = "3.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4498fc115fa7d34de968184e473529abb40eeb6be8bc5f7faba3d08c316cb3e3" -dependencies = [ - "log", - "pest", - "pest_derive", - "quick-error 2.0.1", - "serde", - "serde_json", -] - [[package]] name = "handlebars" version = "4.1.5" @@ -6434,11 +6385,14 @@ name = "orml-bencher" version = "0.4.1-dev" dependencies = [ "ansi_term", + "bencher-procedural", "build-helper", - "cargo_metadata 0.13.1", + "cargo_metadata", "frame-benchmarking", + "hash-db", "linregress", "parity-scale-codec", + "parking_lot 0.11.2", "paste", "rand 0.8.4", "sc-client-db", @@ -6447,11 +6401,13 @@ dependencies = [ "serde", "serde_json", "sp-core", + "sp-externalities", "sp-io", "sp-maybe-compressed-blob", "sp-runtime-interface", "sp-state-machine", "sp-std", + "sp-storage", "tempfile", "toml", "walkdir", @@ -6681,7 +6637,6 @@ version = "0.4.1-dev" dependencies = [ "frame-support", "frame-system", - "orml-bencher", "pallet-balances", "parity-scale-codec", "scale-info", @@ -6689,7 +6644,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-std", - "spin 0.7.1", "weight-meter-procedural", ] @@ -6752,15 +6706,6 @@ dependencies = [ "xcm-simulator", ] -[[package]] -name = "os_str_bytes" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" -dependencies = [ - "memchr", -] - [[package]] name = "owning_ref" version = "0.4.1" @@ -9703,7 +9648,7 @@ dependencies = [ "cc", "libc", "once_cell", - "spin 0.5.2", + "spin", "untrusted", "web-sys", "winapi 0.3.9", @@ -11269,7 +11214,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" dependencies = [ "semver-parser 0.10.2", - "serde", ] [[package]] @@ -12271,12 +12215,6 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" -[[package]] -name = "spin" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13287b4da9d1207a4f4929ac390916d64eacfe236a487e9a9f5b3be392be5162" - [[package]] name = "ss58-registry" version = "1.8.1" @@ -12347,19 +12285,13 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - [[package]] name = "structopt" version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40b9788f4202aa75c240ecc9c15c65185e6a39ccdeb0fd5d008b98825464c87c" dependencies = [ - "clap 2.34.0", + "clap", "lazy_static", "structopt-derive", ] @@ -12549,7 +12481,7 @@ source = "git+https://github.com/paritytech//substrate?rev=fcc54a72973d03afe7bf9 dependencies = [ "ansi_term", "build-helper", - "cargo_metadata 0.14.1", + "cargo_metadata", "sp-maybe-compressed-blob", "tempfile", "toml", @@ -12680,12 +12612,6 @@ dependencies = [ "unicode-width", ] -[[package]] -name = "textwrap" -version = "0.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0066c8d12af8b5acd21e00547c3797fde4e8677254a7ee429176ccebbe93dd80" - [[package]] name = "thiserror" version = "1.0.30" @@ -13634,8 +13560,8 @@ dependencies = [ name = "weight-gen" version = "0.4.1-dev" dependencies = [ - "clap 3.0.0-rc.7", - "handlebars 3.5.5", + "clap", + "handlebars", "serde", "serde_json", ] diff --git a/ecosystem-modules/stable-asset b/ecosystem-modules/stable-asset index 3e12b10758..35535695c2 160000 --- a/ecosystem-modules/stable-asset +++ b/ecosystem-modules/stable-asset @@ -1 +1 @@ -Subproject commit 3e12b10758ad757934ae4260f5d111ac2376b039 +Subproject commit 35535695c2b78657d41828f7d7659977a68cc4eb diff --git a/ecosystem-modules/starport/src/lib.rs b/ecosystem-modules/starport/src/lib.rs index 9a10870de0..ce70ac2af3 100644 --- a/ecosystem-modules/starport/src/lib.rs +++ b/ecosystem-modules/starport/src/lib.rs @@ -398,7 +398,7 @@ impl Pallet { // emit an event Self::deposit_event(Event::::AssetLockedTo { - currency_id: currency_id, + currency_id, amount: locked_amount, user: to, }); diff --git a/modules/auction-manager/src/lib.rs b/modules/auction-manager/src/lib.rs index d174316fd2..102c7a81ee 100644 --- a/modules/auction-manager/src/lib.rs +++ b/modules/auction-manager/src/lib.rs @@ -674,7 +674,7 @@ impl Pallet { collateral_type: collateral_auction.currency_id, collateral_amount: collateral_auction.amount, winner: bidder, - payment_amount: payment_amount, + payment_amount, }); } diff --git a/modules/cdp-engine/src/lib.rs b/modules/cdp-engine/src/lib.rs index 518edd673f..7c4fa4644a 100644 --- a/modules/cdp-engine/src/lib.rs +++ b/modules/cdp-engine/src/lib.rs @@ -886,7 +886,7 @@ impl Pallet { collateral_type: currency_id, owner: who, sold_collateral_amount: actual_supply_collateral, - refund_collateral_amount: refund_collateral_amount, + refund_collateral_amount, debit_value, }); Ok(()) @@ -959,7 +959,7 @@ impl Pallet { collateral_type: currency_id, owner: who, collateral_amount: collateral, - bad_debt_value: bad_debt_value, + bad_debt_value, liquidation_strategy: liquidation_strategy.clone(), }); match liquidation_strategy { diff --git a/modules/dex/src/lib.rs b/modules/dex/src/lib.rs index df1ac3f5be..3ebf73c3e1 100644 --- a/modules/dex/src/lib.rs +++ b/modules/dex/src/lib.rs @@ -537,9 +537,7 @@ pub mod module { not_before, }), ); - Self::deposit_event(Event::ListProvisioning { - trading_pair: trading_pair, - }); + Self::deposit_event(Event::ListProvisioning { trading_pair }); Ok(()) } @@ -693,9 +691,7 @@ pub mod module { } TradingPairStatuses::::insert(trading_pair, TradingPairStatus::Enabled); - Self::deposit_event(Event::EnableTradingPair { - trading_pair: trading_pair, - }); + Self::deposit_event(Event::EnableTradingPair { trading_pair }); Ok(()) } @@ -843,9 +839,9 @@ impl Pallet { Self::deposit_event(Event::AddProvision { who: who.clone(), currency_0: trading_pair.first(), - contribution_0: contribution_0, + contribution_0, currency_1: trading_pair.second(), - contribution_1: contribution_1, + contribution_1, }); Ok(()) }) @@ -959,7 +955,7 @@ impl Pallet { pool_0: pool_0_increment, currency_1: trading_pair.second(), pool_1: pool_1_increment, - share_increment: share_increment, + share_increment, }); Ok(()) }) diff --git a/modules/evm/src/lib.rs b/modules/evm/src/lib.rs index 10e8a13012..c9d0fea08a 100644 --- a/modules/evm/src/lib.rs +++ b/modules/evm/src/lib.rs @@ -793,7 +793,7 @@ pub mod module { Pallet::::deposit_event(Event::::TransferredMaintainer { contract, - new_maintainer: new_maintainer, + new_maintainer, }); Ok(().into()) diff --git a/modules/homa-lite/src/lib.rs b/modules/homa-lite/src/lib.rs index 50153ba89c..c248ea119f 100644 --- a/modules/homa-lite/src/lib.rs +++ b/modules/homa-lite/src/lib.rs @@ -441,7 +441,7 @@ pub mod module { T::GovernanceOrigin::ensure_origin(origin)?; StakingCurrencyMintCap::::put(new_cap); - Self::deposit_event(Event::::StakingCurrencyMintCapUpdated { new_cap: new_cap }); + Self::deposit_event(Event::::StakingCurrencyMintCapUpdated { new_cap }); Ok(()) } @@ -559,7 +559,7 @@ pub mod module { Self::deposit_event(Event::::RedeemRequested { who: who.clone(), - liquid_amount: liquid_amount, + liquid_amount, extra_fee: additional_fee, withdraw_fee_paid: base_withdraw_fee, }); @@ -693,9 +693,7 @@ pub mod module { StakingInterestRatePerUpdate::::put(interest_rate); - Self::deposit_event(Event::::StakingInterestRatePerUpdateSet { - interest_rate: interest_rate, - }); + Self::deposit_event(Event::::StakingInterestRatePerUpdateSet { interest_rate }); Ok(()) } diff --git a/modules/homa-lite/src/tests.rs b/modules/homa-lite/src/tests.rs index 9cc119055a..d0c4f5fe7d 100644 --- a/modules/homa-lite/src/tests.rs +++ b/modules/homa-lite/src/tests.rs @@ -773,12 +773,24 @@ fn update_redeem_request_works() { .into_iter() .filter_map(|e| match e.event { Event::HomaLite(x) => Some(Event::HomaLite(x)), - Event::Tokens(orml_tokens::Event::Unreserved(currency, who, amount)) => { - Some(Event::Tokens(orml_tokens::Event::Unreserved(currency, who, amount))) - } - Event::Tokens(orml_tokens::Event::Reserved(currency, who, amount)) => { - Some(Event::Tokens(orml_tokens::Event::Reserved(currency, who, amount))) - } + Event::Tokens(orml_tokens::Event::Unreserved { + currency_id: currency, + who, + amount, + }) => Some(Event::Tokens(orml_tokens::Event::Unreserved { + currency_id: currency, + who, + amount, + })), + Event::Tokens(orml_tokens::Event::Reserved { + currency_id: currency, + who, + amount, + }) => Some(Event::Tokens(orml_tokens::Event::Reserved { + currency_id: currency, + who, + amount, + })), _ => None, }) .collect::>(); @@ -787,7 +799,11 @@ fn update_redeem_request_works() { events, vec![ // Reserve the newly added amount - Event::Tokens(orml_tokens::Event::Reserved(LKSM, DAVE, amount_reserved)), + Event::Tokens(orml_tokens::Event::Reserved { + currency_id: LKSM, + who: DAVE, + amount: amount_reserved + }), Event::HomaLite(crate::Event::RedeemRequested { who: DAVE, liquid_amount: new_redeem_amount, @@ -795,7 +811,11 @@ fn update_redeem_request_works() { withdraw_fee_paid: withdraw_fee }), // Unreserve the reduced amount - Event::Tokens(orml_tokens::Event::Unreserved(LKSM, DAVE, 998_999_000_000_000)), + Event::Tokens(orml_tokens::Event::Unreserved { + currency_id: LKSM, + who: DAVE, + amount: 998_999_000_000_000 + }), Event::HomaLite(crate::Event::RedeemRequested { who: DAVE, liquid_amount: dollar(1000), diff --git a/modules/incentives/src/lib.rs b/modules/incentives/src/lib.rs index 870bb4fceb..f6f31702c2 100644 --- a/modules/incentives/src/lib.rs +++ b/modules/incentives/src/lib.rs @@ -317,8 +317,8 @@ pub mod module { who: who.clone(), pool: pool_id, reward_currency_id: currency_id, - actual_amount: actual_amount, - deduction_amount: deduction_amount, + actual_amount, + deduction_amount, }); } @@ -426,7 +426,7 @@ pub mod module { v = deduction_rate; Self::deposit_event(Event::ClaimRewardDeductionRateUpdated { pool: pool_id, - deduction_rate: deduction_rate, + deduction_rate, }); } diff --git a/orml b/orml index 1c80da43a7..d4114b63fa 160000 --- a/orml +++ b/orml @@ -1 +1 @@ -Subproject commit 1c80da43a720d1b957e1ba12238e4d98b2ee8cf9 +Subproject commit d4114b63faa14e3a844046218d3d16cacab631d0 From 094cbbcee4706a91a224a06a2afa201cf6485e33 Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Mon, 20 Dec 2021 18:31:51 +1300 Subject: [PATCH 11/13] updated orml reference --- orml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/orml b/orml index d4114b63fa..1e36199be5 160000 --- a/orml +++ b/orml @@ -1 +1 @@ -Subproject commit d4114b63faa14e3a844046218d3d16cacab631d0 +Subproject commit 1e36199be5efb5a267e46c407d7a2ded82e81677 From ef4456808fe116a4ddd7d82d2290c243f170636a Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Wed, 22 Dec 2021 11:05:49 +1300 Subject: [PATCH 12/13] FIxed broken integration test. Merged orml change to Master. --- orml | 2 +- runtime/integration-tests/src/authority.rs | 48 +++++++++++----------- runtime/integration-tests/src/setup.rs | 2 + 3 files changed, 27 insertions(+), 25 deletions(-) diff --git a/orml b/orml index 1e36199be5..8d07637284 160000 --- a/orml +++ b/orml @@ -1 +1 @@ -Subproject commit 1e36199be5efb5a267e46c407d7a2ded82e81677 +Subproject commit 8d076372849a4dced5468f0f14db96b7145160ee diff --git a/runtime/integration-tests/src/authority.rs b/runtime/integration-tests/src/authority.rs index fd7baeed17..941cdf03ad 100644 --- a/runtime/integration-tests/src/authority.rs +++ b/runtime/integration-tests/src/authority.rs @@ -104,13 +104,13 @@ fn test_authority_module() { true, Box::new(call.clone()) )); - System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled( - OriginCaller::Authority(DelayedOrigin { + System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled { + origin: OriginCaller::Authority(DelayedOrigin { delay: one_day_later - 1, origin: Box::new(OriginCaller::system(RawOrigin::Root)), }), - 1, - ))); + index: 1, + })); run_to_block(one_day_later); @@ -185,10 +185,10 @@ fn test_authority_module() { false, Box::new(call.clone()) )); - System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled( - OriginCaller::system(RawOrigin::Root), - 3, - ))); + System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled { + origin: OriginCaller::system(RawOrigin::Root), + index: 3, + })); run_to_block(seven_days_later + 1); System::assert_last_event(Event::Scheduler(pallet_scheduler::Event::::Dispatched( @@ -229,13 +229,13 @@ fn test_authority_module() { true, Box::new(call.clone()) )); - System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled( - OriginCaller::Authority(DelayedOrigin { + System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled { + origin: OriginCaller::Authority(DelayedOrigin { delay: 1, origin: Box::new(OriginCaller::system(RawOrigin::Root)), }), - 5, - ))); + index: 5, + })); let schedule_origin = { let origin: ::Origin = From::from(Origin::root()); @@ -251,13 +251,13 @@ fn test_authority_module() { let pallets_origin = Box::new(schedule_origin.caller().clone()); assert_ok!(Authority::cancel_scheduled_dispatch(Origin::root(), pallets_origin, 5)); - System::assert_last_event(Event::Authority(orml_authority::Event::Cancelled( - OriginCaller::Authority(DelayedOrigin { + System::assert_last_event(Event::Authority(orml_authority::Event::Cancelled { + origin: OriginCaller::Authority(DelayedOrigin { delay: 1, origin: Box::new(OriginCaller::system(RawOrigin::Root)), }), - 5, - ))); + index: 5, + })); assert_ok!(Authority::schedule_dispatch( Origin::root(), @@ -266,19 +266,19 @@ fn test_authority_module() { false, Box::new(call.clone()) )); - System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled( - OriginCaller::system(RawOrigin::Root), - 6, - ))); + System::assert_last_event(Event::Authority(orml_authority::Event::Scheduled { + origin: OriginCaller::system(RawOrigin::Root), + index: 6, + })); assert_ok!(Authority::cancel_scheduled_dispatch( Origin::root(), Box::new(frame_system::RawOrigin::Root.into()), 6 )); - System::assert_last_event(Event::Authority(orml_authority::Event::Cancelled( - OriginCaller::system(RawOrigin::Root), - 6, - ))); + System::assert_last_event(Event::Authority(orml_authority::Event::Cancelled { + origin: OriginCaller::system(RawOrigin::Root), + index: 6, + })); }); } diff --git a/runtime/integration-tests/src/setup.rs b/runtime/integration-tests/src/setup.rs index b08af22e52..e647922dac 100644 --- a/runtime/integration-tests/src/setup.rs +++ b/runtime/integration-tests/src/setup.rs @@ -154,7 +154,9 @@ const ORACLE3: [u8; 32] = [2u8; 32]; const ORACLE4: [u8; 32] = [3u8; 32]; const ORACLE5: [u8; 32] = [4u8; 32]; +#[allow(dead_code)] pub const DEFAULT: [u8; 32] = [0u8; 32]; + pub const ALICE: [u8; 32] = [4u8; 32]; pub const BOB: [u8; 32] = [5u8; 32]; pub const CHARLIE: [u8; 32] = [6u8; 32]; From 629bebf5776fba2883d1d29ced5e314098ce8e9a Mon Sep 17 00:00:00 2001 From: Roy Yang Date: Wed, 22 Dec 2021 13:20:07 +1300 Subject: [PATCH 13/13] Added back a test deleted by mistake --- runtime/integration-tests/src/authority.rs | 59 ++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/runtime/integration-tests/src/authority.rs b/runtime/integration-tests/src/authority.rs index 941cdf03ad..bc3761a922 100644 --- a/runtime/integration-tests/src/authority.rs +++ b/runtime/integration-tests/src/authority.rs @@ -282,3 +282,62 @@ fn test_authority_module() { })); }); } + +#[test] +fn cancel_schedule_test() { + ExtBuilder::default().build().execute_with(|| { + assert_ok!(FinancialCouncil::set_members( + Origin::root(), + vec![AccountId::from(ALICE), AccountId::from(BOB), AccountId::from(CHARLIE)], + None, + 5, + )); + let council_call = Call::CdpEngine(module_cdp_engine::Call::set_global_params { + global_interest_rate_per_sec: Rate::from(10), + }); + + assert_ok!(Authority::schedule_dispatch( + OriginCaller::FinancialCouncil(pallet_collective::RawOrigin::Members(2, 3)).into(), + DispatchTime::At(2), + 0, + false, + Box::new(council_call.clone()), + )); + + // canceling will not work if yes vote is less than the scheduled call + assert_noop!( + Authority::cancel_scheduled_dispatch( + OriginCaller::FinancialCouncil(pallet_collective::RawOrigin::Members(1, 3)).into(), + Box::new(OriginCaller::FinancialCouncil(pallet_collective::RawOrigin::Members( + 2, 3 + ))), + 0, + ), + BadOrigin + ); + // canceling works when yes vote is greater than the scheduled call + assert_ok!(Authority::cancel_scheduled_dispatch( + OriginCaller::FinancialCouncil(pallet_collective::RawOrigin::Members(3, 3)).into(), + Box::new(OriginCaller::FinancialCouncil(pallet_collective::RawOrigin::Members( + 2, 3 + ))), + 0, + )); + + assert_ok!(Authority::schedule_dispatch( + OriginCaller::FinancialCouncil(pallet_collective::RawOrigin::Members(2, 3)).into(), + DispatchTime::At(2), + 0, + false, + Box::new(council_call.clone()), + )); + // canceling works when yes vote is equal to the scheduled call + assert_ok!(Authority::cancel_scheduled_dispatch( + OriginCaller::FinancialCouncil(pallet_collective::RawOrigin::Members(2, 3)).into(), + Box::new(OriginCaller::FinancialCouncil(pallet_collective::RawOrigin::Members( + 2, 3 + ))), + 1, + )); + }); +}