Skip to content

Commit

Permalink
Check for missing amount when parsing Coin
Browse files Browse the repository at this point in the history
  • Loading branch information
chipshort committed May 15, 2023
1 parent bba7a96 commit 66d026b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
24 changes: 20 additions & 4 deletions packages/std/src/coin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ impl FromStr for Coin {
.ok_or(CoinFromStrError::MissingDenom)?;
let (amount, denom) = s.split_at(pos);

if amount.is_empty() {
return Err(CoinFromStrError::MissingAmount);
}

Ok(Coin {
amount: amount.parse::<u128>()?.into(),
denom: denom.to_string(),
Expand Down Expand Up @@ -205,12 +209,24 @@ mod tests {
CoinFromStrError::MissingDenom
);
assert_eq!(
Coin::from_str("ucosm").unwrap_err().to_string(),
"Invalid amount: cannot parse integer from empty string"
Coin::from_str("ucosm").unwrap_err(), // no amount
CoinFromStrError::MissingAmount
);
assert_eq!(
Coin::from_str("-123ucosm").unwrap_err(), // negative amount
CoinFromStrError::MissingAmount
);
assert_eq!(
Coin::from_str("").unwrap_err(), // empty input
CoinFromStrError::MissingDenom
);
assert_eq!(
Coin::from_str(" 1ucosm").unwrap_err(), // unsupported whitespace
CoinFromStrError::MissingAmount
);
assert_eq!(
Coin::from_str("-123ucosm").unwrap_err().to_string(),
"Invalid amount: cannot parse integer from empty string"
Coin::from_str("�1ucosm").unwrap_err(), // other broken data
CoinFromStrError::MissingAmount
);
assert_eq!(
Coin::from_str("340282366920938463463374607431768211456ucosm")
Expand Down
2 changes: 2 additions & 0 deletions packages/std/src/errors/std_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,8 @@ pub struct RoundUpOverflowError;
pub enum CoinFromStrError {
#[error("Missing denominator")]
MissingDenom,
#[error("Missing amount or non-digit characters in amount")]
MissingAmount,
#[error("Invalid amount: {0}")]
InvalidAmount(std::num::ParseIntError),
}
Expand Down

0 comments on commit 66d026b

Please sign in to comment.