Skip to content

Commit

Permalink
Reintroduce Coin.IsValid() (#4558)
Browse files Browse the repository at this point in the history
Closes #4556
  • Loading branch information
colin-axner authored and Alessio Treglia committed Jun 18, 2019
1 parent 1e7c4dd commit 314af42
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 4 deletions.
1 change: 1 addition & 0 deletions .pending/improvements/sdk/4556-Added-IsValid-f
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#4556 Added IsValid function to Coin
28 changes: 24 additions & 4 deletions types/coin.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,8 @@ type Coin struct {
// NewCoin returns a new coin with a denomination and amount. It will panic if
// the amount is negative.
func NewCoin(denom string, amount Int) Coin {
mustValidateDenom(denom)

if amount.LT(ZeroInt()) {
panic(fmt.Errorf("negative coin amount: %v", amount))
if err := validate(denom, amount); err != nil {
panic(err)
}

return Coin{
Expand All @@ -51,6 +49,28 @@ func (coin Coin) String() string {
return fmt.Sprintf("%v%v", coin.Amount, coin.Denom)
}

// validate returns an error if the Coin has a negative amount or if
// the denom is invalid.
func validate(denom string, amount Int) error {
if err := validateDenom(denom); err != nil {
return err
}

if amount.LT(ZeroInt()) {
return fmt.Errorf("negative coin amount: %v", amount)
}

return nil
}

// IsValid returns true if the Coin has a non-negative amount and the denom is vaild.
func (coin Coin) IsValid() bool {
if err := validate(coin.Denom, coin.Amount); err != nil {
return false
}
return true
}

// IsZero returns if this represents no money
func (coin Coin) IsZero() bool {
return coin.Amount.IsZero()
Expand Down
20 changes: 20 additions & 0 deletions types/coin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,26 @@ func TestIsEqualCoin(t *testing.T) {
}
}

func TestCoinIsValid(t *testing.T) {
cases := []struct {
coin Coin
expectPass bool
}{
{Coin{testDenom1, NewInt(-1)}, false},
{Coin{testDenom1, NewInt(0)}, true},
{Coin{testDenom1, NewInt(1)}, true},
{Coin{"Atom", NewInt(1)}, false},
{Coin{"a", NewInt(1)}, false},
{Coin{"a very long coin denom", NewInt(1)}, false},
{Coin{"atOm", NewInt(1)}, false},
{Coin{" ", NewInt(1)}, false},
}

for i, tc := range cases {
require.Equal(t, tc.expectPass, tc.coin.IsValid(), "unexpected result for IsValid, tc #%d", i)
}
}

func TestAddCoin(t *testing.T) {
cases := []struct {
inputOne Coin
Expand Down

0 comments on commit 314af42

Please sign in to comment.