Skip to content

Commit

Permalink
Follow TODO instruction to replace amount update with checked_add_signed
Browse files Browse the repository at this point in the history
  • Loading branch information
plaidfinch committed Aug 11, 2023
1 parent 562d52e commit 17f9833
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 34 deletions.
43 changes: 9 additions & 34 deletions crates/core/component/shielded-pool/src/component/supply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,43 +62,18 @@ pub trait SupplyWrite: StateWrite {
let key = state_key::token_supply(asset_id);
let current_supply: Amount = self.get_proto(&key).await?.unwrap_or(0u64).into();

// TODO: if the token was a staking token, update the total supply of staking tokens
// TODO: if the token was a delegation token, update the total supply of staking tokens
// using the correct exchange rate for that validator (via `unbonded_amount`)
// TODO: if the token was an unbonding token, update the total supply of staking tokens
// using a 1:1 exchange rate
let new_supply = current_supply.checked_add_signed(change).ok_or_else(|| {
anyhow::anyhow!(
"over-/under-flow updating token {} supply {} with delta {}",
asset_id,
current_supply,
change
)
})?;

// TODO: replace with a single checked_add_signed call when mixed_integer_ops lands in stable (1.66)
let new_supply: Amount = if change < 0 {
current_supply
.value()
.checked_sub(change.unsigned_abs())
.ok_or_else(|| {
anyhow::anyhow!(
"underflow updating token {} supply {} with delta {}",
asset_id,
current_supply,
change
)
})?
.into()
} else {
current_supply
.value()
.checked_add(change as u128)
.ok_or_else(|| {
anyhow::anyhow!(
"overflow updating token {} supply {} with delta {}",
asset_id,
current_supply,
change
)
})?
.into()
};
tracing::debug!(?current_supply, ?new_supply, ?change);

self.put(key, new_supply);

Ok(())
}
}
Expand Down
6 changes: 6 additions & 0 deletions crates/core/num/src/amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ impl Amount {
.map(|inner| Self { inner })
}

pub fn checked_add_signed(&self, rhs: i128) -> Option<Self> {
Some(Amount {
inner: self.inner.checked_add_signed(rhs)?,
})
}

pub fn saturating_add(&self, rhs: &Self) -> Self {
Self {
inner: self.inner.saturating_add(rhs.inner),
Expand Down

0 comments on commit 17f9833

Please sign in to comment.