Skip to content
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

R4R: Added IsValid to Coin #4558

Merged
merged 8 commits into from
Jun 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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