Skip to content

Commit

Permalink
change(pallet-assets-holder): fast exit for set_balance_on_hold.
Browse files Browse the repository at this point in the history
  • Loading branch information
pandres95 committed Sep 5, 2024
1 parent 548eee1 commit 5d7d874
Showing 1 changed file with 35 additions and 24 deletions.
59 changes: 35 additions & 24 deletions substrate/frame/assets-holder/src/impl_fungibles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,46 +181,57 @@ impl<T: Config<I>, I: 'static> UnbalancedHold<T::AccountId> for Pallet<T, I> {
amount: Self::Balance,
) -> DispatchResult {
let mut holds = Holds::<T, I>::get(asset.clone(), who);
let amount_on_hold =
BalancesOnHold::<T, I>::get(asset.clone(), who).unwrap_or_else(Zero::zero);

let (increase, delta) = if let Some(pos) = holds.iter().position(|x| &x.id == reason) {
let item = &mut holds[pos];
let (increase, delta) =
(amount > item.amount, item.amount.max(amount) - item.amount.min(amount));
let amount_on_hold = if amount.is_zero() {
if let Some(pos) = holds.iter().position(|x| &x.id == reason) {
let item = &mut holds[pos];
let amount = item.amount;

item.amount = amount;
if item.amount.is_zero() {
holds.swap_remove(pos);
amount_on_hold.checked_sub(&amount).ok_or(ArithmeticError::Underflow)?
} else {
amount_on_hold
}

(increase, delta)
} else {
if !amount.is_zero() {
let (increase, delta) = if let Some(pos) = holds.iter().position(|x| &x.id == reason) {
let item = &mut holds[pos];
let (increase, delta) =
(amount > item.amount, item.amount.max(amount) - item.amount.min(amount));

item.amount = amount;
if item.amount.is_zero() {
holds.swap_remove(pos);
}

(increase, delta)
} else {
holds
.try_push(IdAmount { id: *reason, amount })
.map_err(|_| Error::<T, I>::TooManyHolds)?;
}
(true, amount)
};
(true, amount)
};

let amount_on_hold =
BalancesOnHold::<T, I>::get(asset.clone(), who).unwrap_or_else(Zero::zero);
let amount_on_hold = if increase {
amount_on_hold.checked_add(&delta).ok_or(ArithmeticError::Overflow)?
} else {
amount_on_hold.checked_sub(&delta).ok_or(ArithmeticError::Underflow)?
};

let amount_on_hold = if increase {
amount_on_hold.checked_add(&delta).ok_or(ArithmeticError::Overflow)?
} else {
amount_on_hold.checked_sub(&delta).ok_or(ArithmeticError::Underflow)?
amount_on_hold
};

if amount_on_hold.is_zero() {
BalancesOnHold::<T, I>::remove(asset.clone(), who);
if !holds.is_empty() {
Holds::<T, I>::insert(asset.clone(), who, holds);
} else {
BalancesOnHold::<T, I>::insert(asset.clone(), who, amount_on_hold);
Holds::<T, I>::remove(asset.clone(), who);
}

if !holds.is_empty() {
Holds::<T, I>::insert(asset, who, holds);
if amount_on_hold.is_zero() {
BalancesOnHold::<T, I>::remove(asset.clone(), who);
} else {
Holds::<T, I>::remove(asset, who);
BalancesOnHold::<T, I>::insert(asset.clone(), who, amount_on_hold);
}

Ok(())
Expand Down

0 comments on commit 5d7d874

Please sign in to comment.