-
Notifications
You must be signed in to change notification settings - Fork 12
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 { | ||
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); | ||
|
@@ -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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. 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. |
||
} | ||
}; | ||
Ok(self) | ||
|
There was a problem hiding this comment.
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-stdbacktraces
feature enabled.