Skip to content

Commit

Permalink
cosmrs: support coins with amount 0, empty denom
Browse files Browse the repository at this point in the history
These can be used when the gas fee is zero, for example

Fixes #477
  • Loading branch information
tony-iqlusion committed Aug 1, 2024
1 parent c5db4e5 commit 2f1b97c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
26 changes: 21 additions & 5 deletions cosmrs/src/base/coin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use std::fmt;

/// Coin defines a token with a denomination and an amount.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Coin {
/// Denomination
pub denom: Denom,
Expand Down Expand Up @@ -35,10 +35,15 @@ impl TryFrom<&proto::cosmos::base::v1beta1::Coin> for Coin {
type Error = ErrorReport;

fn try_from(proto: &proto::cosmos::base::v1beta1::Coin) -> Result<Coin> {
Ok(Coin {
denom: proto.denom.parse()?,
amount: proto.amount.parse()?,
})
// Support an empty denom when the amount is `0`. See cosmos/cosmos-rust#477
if proto.denom.is_empty() && proto.amount == "0" {
Ok(Coin::default())
} else {
Ok(Coin {
denom: proto.denom.parse()?,
amount: proto.amount.parse()?,
})
}
}
}

Expand Down Expand Up @@ -67,9 +72,20 @@ impl fmt::Display for Coin {
#[cfg(test)]
mod tests {
use super::Coin;
use crate::proto;

#[test]
fn new() {
Coin::new(1000, "uatom").unwrap();
}

#[test]
fn zero_value_coin_with_empty_denom() {
let zero_proto = proto::cosmos::base::v1beta1::Coin::from(Coin::default());
assert_eq!(&zero_proto.denom, "");
assert_eq!(&zero_proto.amount, "0");

let zero_coin = Coin::try_from(zero_proto).unwrap();
assert_eq!(zero_coin, Coin::default())
}
}
2 changes: 1 addition & 1 deletion cosmrs/src/base/denom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use serde::{de, de::Error as _, ser, Deserialize, Serialize};
use std::{fmt, str::FromStr};

/// Denomination.
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
pub struct Denom(String);

impl Denom {
Expand Down

0 comments on commit 2f1b97c

Please sign in to comment.