add AddAmount/SubAmount methods to sdk.Coin (#9091)

Co-authored-by: Marko <marbar3778@yahoo.com>
Co-authored-by: Amaury <1293565+amaurym@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
Hanjun Kim
2021-04-13 15:01:21 +00:00
committed by GitHub
co-authored by Marko Amaury mergify[bot]
parent 56cea8c148
commit cf7b03efcd
3 changed files with 55 additions and 0 deletions
+15
View File
@@ -100,6 +100,11 @@ func (coin Coin) Add(coinB Coin) Coin {
return Coin{coin.Denom, coin.Amount.Add(coinB.Amount)}
}
// AddAmount adds an amount to the Coin.
func (coin Coin) AddAmount(amount Int) Coin {
return Coin{coin.Denom, coin.Amount.Add(amount)}
}
// Sub subtracts amounts of two coins with same denom. If the coins differ in denom
// then it panics.
func (coin Coin) Sub(coinB Coin) Coin {
@@ -115,6 +120,16 @@ func (coin Coin) Sub(coinB Coin) Coin {
return res
}
// SubAmount subtracts an amount from the Coin.
func (coin Coin) SubAmount(amount Int) Coin {
res := Coin{coin.Denom, coin.Amount.Sub(amount)}
if res.IsNegative() {
panic("negative coin amount")
}
return res
}
// IsPositive returns true if coin amount is positive.
//
// TODO: Remove once unsigned integers are used.
+39
View File
@@ -145,6 +145,21 @@ func (s *coinTestSuite) TestAddCoin() {
}
}
func (s *coinTestSuite) TestAddCoinAmount() {
cases := []struct {
coin sdk.Coin
amount sdk.Int
expected sdk.Coin
}{
{sdk.NewInt64Coin(testDenom1, 1), sdk.NewInt(1), sdk.NewInt64Coin(testDenom1, 2)},
{sdk.NewInt64Coin(testDenom1, 1), sdk.NewInt(0), sdk.NewInt64Coin(testDenom1, 1)},
}
for i, tc := range cases {
res := tc.coin.AddAmount(tc.amount)
s.Require().Equal(tc.expected, res, "result of addition is incorrect, tc #%d", i)
}
}
func (s *coinTestSuite) TestSubCoin() {
cases := []struct {
inputOne sdk.Coin
@@ -178,6 +193,30 @@ func (s *coinTestSuite) TestSubCoin() {
s.Require().Equal(tc.expected, res.Amount.Int64())
}
func (s *coinTestSuite) TestSubCoinAmount() {
cases := []struct {
coin sdk.Coin
amount sdk.Int
expected sdk.Coin
shouldPanic bool
}{
{sdk.NewInt64Coin(testDenom1, 2), sdk.NewInt(1), sdk.NewInt64Coin(testDenom1, 1), false},
{sdk.NewInt64Coin(testDenom1, 10), sdk.NewInt(1), sdk.NewInt64Coin(testDenom1, 9), false},
{sdk.NewInt64Coin(testDenom1, 5), sdk.NewInt(3), sdk.NewInt64Coin(testDenom1, 2), false},
{sdk.NewInt64Coin(testDenom1, 5), sdk.NewInt(0), sdk.NewInt64Coin(testDenom1, 5), false},
{sdk.NewInt64Coin(testDenom1, 1), sdk.NewInt(5), sdk.Coin{}, true},
}
for i, tc := range cases {
if tc.shouldPanic {
s.Require().Panics(func() { tc.coin.SubAmount(tc.amount) })
} else {
res := tc.coin.SubAmount(tc.amount)
s.Require().Equal(tc.expected, res, "result of subtraction is incorrect, tc #%d", i)
}
}
}
func (s *coinTestSuite) TestIsGTECoin() {
cases := []struct {
inputOne sdk.Coin