From 077abd6c0dd01cda83838c87e4214a1b5af5e708 Mon Sep 17 00:00:00 2001 From: William Freudenberger Date: Thu, 21 Sep 2023 17:38:52 +0200 Subject: [PATCH] feat: short circuit zero collections --- pallets/foreign-investments/src/impls/mod.rs | 28 +++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/pallets/foreign-investments/src/impls/mod.rs b/pallets/foreign-investments/src/impls/mod.rs index 15b45ae918..8ff180b510 100644 --- a/pallets/foreign-investments/src/impls/mod.rs +++ b/pallets/foreign-investments/src/impls/mod.rs @@ -1054,16 +1054,19 @@ impl Pallet { collected: CollectedAmount, ) -> DispatchResult { // Increment by previously stored amounts (via `CollectedInvestmentHook`) - CollectedInvestment::::mutate(who, investment_id, |collected_before| { - collected_before - .amount_collected + let nothing_collect = CollectedInvestment::::mutate(who, investment_id, |c| { + c.amount_collected .ensure_add_assign(collected.amount_collected)?; - collected_before - .amount_payment + c.amount_payment .ensure_add_assign(collected.amount_payment)?; - Ok::<(), DispatchError>(()) + Ok::(c.amount_collected.is_zero() && c.amount_payment.is_zero()) })?; + // No need to transition if nothing was collected + if nothing_collect { + return Ok(()); + } + // Update invest state to decrease the unprocessed investing amount let investing_amount = T::Investment::investment(who, investment_id)?; let pre_state = InvestmentState::::get(who, investment_id); @@ -1098,14 +1101,19 @@ impl Pallet { .expect("Impossible to collect redemption for non existing pool at this point"); // Increment by previously stored amounts (via `CollectedInvestmentHook`) - CollectedRedemption::::mutate(who, investment_id, |old| { - old.amount_collected + let nothing_collect = CollectedRedemption::::mutate(who, investment_id, |c| { + c.amount_collected .ensure_add_assign(collected.amount_collected)?; - old.amount_payment + c.amount_payment .ensure_add_assign(collected.amount_payment)?; - Ok::<(), DispatchError>(()) + Ok::(c.amount_collected.is_zero() && c.amount_payment.is_zero()) })?; + // No need to transition if nothing was collected + if nothing_collect { + return Ok(()); + } + // Transition state to initiate swap from pool to foreign currency let pre_state = RedemptionState::::get(who, investment_id); let amount_unprocessed_redemption = T::Investment::redemption(who, investment_id)?;