Skip to content

Commit 871e514

Browse files
cosmrs: support coins with amount 0, empty denom (#479)
These can be used when the gas fee is zero, for example Fixes #477
1 parent c5db4e5 commit 871e514

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

cosmrs/src/base/coin.rs

+21-5
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
44
use std::fmt;
55

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

3737
fn try_from(proto: &proto::cosmos::base::v1beta1::Coin) -> Result<Coin> {
38-
Ok(Coin {
39-
denom: proto.denom.parse()?,
40-
amount: proto.amount.parse()?,
41-
})
38+
// Support an empty denom when the amount is `0`. See cosmos/cosmos-rust#477
39+
if proto.denom.is_empty() && proto.amount == "0" {
40+
Ok(Coin::default())
41+
} else {
42+
Ok(Coin {
43+
denom: proto.denom.parse()?,
44+
amount: proto.amount.parse()?,
45+
})
46+
}
4247
}
4348
}
4449

@@ -67,9 +72,20 @@ impl fmt::Display for Coin {
6772
#[cfg(test)]
6873
mod tests {
6974
use super::Coin;
75+
use crate::proto;
7076

7177
#[test]
7278
fn new() {
7379
Coin::new(1000, "uatom").unwrap();
7480
}
81+
82+
#[test]
83+
fn zero_value_coin_with_empty_denom() {
84+
let zero_proto = proto::cosmos::base::v1beta1::Coin::from(Coin::default());
85+
assert_eq!(&zero_proto.denom, "");
86+
assert_eq!(&zero_proto.amount, "0");
87+
88+
let zero_coin = Coin::try_from(zero_proto).unwrap();
89+
assert_eq!(zero_coin, Coin::default())
90+
}
7591
}

cosmrs/src/base/denom.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use serde::{de, de::Error as _, ser, Deserialize, Serialize};
33
use std::{fmt, str::FromStr};
44

55
/// Denomination.
6-
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
6+
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
77
pub struct Denom(String);
88

99
impl Denom {

0 commit comments

Comments
 (0)