From 820a6f229fc614e0405af4c071bee973ea40d36b Mon Sep 17 00:00:00 2001 From: Robert Zaremba Date: Tue, 26 Mar 2024 14:58:07 +0100 Subject: [PATCH] feat(checkers): coin checker functions --- util/checkers/coin.go | 20 ++++++++++++++++++++ util/checkers/coin_test.go | 30 ++++++++++++++++++++++++++++++ util/checkers/helper_test.go | 13 +++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 util/checkers/coin.go create mode 100644 util/checkers/coin_test.go create mode 100644 util/checkers/helper_test.go diff --git a/util/checkers/coin.go b/util/checkers/coin.go new file mode 100644 index 0000000000..4fa2e5cb3b --- /dev/null +++ b/util/checkers/coin.go @@ -0,0 +1,20 @@ +package checkers + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// PositiveCoins checks if all coins are valida and amount is positive. +func PositiveCoins(note string, coins ...sdk.Coin) []error { + var errs []error + for i := range coins { + if err := coins[i].Validate(); err != nil { + errs = append(errs, fmt.Errorf("%s coin[%d]: %w", note, i, err)) + } else if !coins[i].Amount.IsPositive() { + errs = append(errs, fmt.Errorf("%s coin[%d] amount must be positive", note, i)) + } + } + return errs +} diff --git a/util/checkers/coin_test.go b/util/checkers/coin_test.go new file mode 100644 index 0000000000..2ae98cc64b --- /dev/null +++ b/util/checkers/coin_test.go @@ -0,0 +1,30 @@ +package checkers + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/assert" +) + +func TestCoinPositive(t *testing.T) { + assert := assert.New(t) + + c0 := sdk.NewInt64Coin("abc", 0) + cNeg := sdk.NewInt64Coin("abc", 0) + cPos := sdk.NewInt64Coin("abc", 1) + + assert.Empty(PositiveCoins("")) + assert.Empty(PositiveCoins("", cPos)) + assert.Empty(PositiveCoins("", cPos, cPos)) + + assert.Contains(errsToStr(PositiveCoins("", c0)), "coin[0]") + assert.Contains(errsToStr(PositiveCoins("", cNeg)), "coin[0]") + assert.Contains(errsToStr(PositiveCoins("", cPos, c0)), "coin[1]") + assert.Contains(errsToStr(PositiveCoins("", cPos, cNeg)), "coin[1]") + assert.NotContains(errsToStr(PositiveCoins("", cPos, cNeg)), "coin[0]") + + assert.Contains(errsToStr(PositiveCoins("", cPos, c0, cNeg)), "coin[1]") + assert.Contains(errsToStr(PositiveCoins("", cPos, c0, cNeg)), "coin[2]") + assert.NotContains(errsToStr(PositiveCoins("", cPos, c0, cNeg)), "coin[0]") +} diff --git a/util/checkers/helper_test.go b/util/checkers/helper_test.go new file mode 100644 index 0000000000..454a69782c --- /dev/null +++ b/util/checkers/helper_test.go @@ -0,0 +1,13 @@ +package checkers + +import ( + "strings" +) + +func errsToStr(errs []error) string { + strs := make([]string, len(errs)) + for i := range errs { + strs[i] = errs[i].Error() + } + return strings.Join(strs, " ") +}