Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error messages in Coins::sub() #10

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions src/balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,16 @@ impl ops::Sub<Coin> for NativeBalance {
fn sub(mut self, other: Coin) -> StdResult<Self> {
match self.find(&other.denom) {
Some((i, c)) => {
if c.amount < other.amount {
return Err(StdError::GenericErr {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's more advisable to use the StdError::generic_err constructor than constructing the variant directly. This code would fail to compile with the cosmwasm-std backtraces feature enabled.

msg: format!(
"Insufficient balance. Wanted: {}, Available: {}",
other.amount,
c.amount
)
});
}

let remainder = c.amount.checked_sub(other.amount)?;
if remainder.u128() == 0 {
self.0.remove(i);
Expand All @@ -156,11 +166,9 @@ impl ops::Sub<Coin> for NativeBalance {
}
// error if no tokens
None => {
return Err(StdError::overflow(OverflowError::new(
OverflowOperation::Sub,
0,
other.amount.u128(),
)))
return Err(StdError::GenericErr {
msg: format!("Insufficient balance. Wanted: {}, Available: 0", other.amount)
});
Comment on lines +169 to +171
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One small problem I see with this is that this makes it a bit more cumbersome to handle the error and makes an unnecessary allocation in that case.
With this change, you have to do something like:

if let Err(StdError::GenericErr { msg, .. }) = result {
    if msg.starts_with("Insufficient balance") {
        // handle
    }
}

as opposed to the current:

if let Err(StdError::Overflow { .. }) = result {
    // handle
}

But I think that's a bit of a niche case, so I am fine with this tradeoff for now.
Ideally, this would have it's own error type that converts into StdError (but that's a breaking change).

}
};
Ok(self)
Expand Down