Skip to content

Commit

Permalink
refactor(types/coin): export func coins.isSorted (#18756)
Browse files Browse the repository at this point in the history
  • Loading branch information
levisyin authored Dec 15, 2023
1 parent 0268ff9 commit a5f1217
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
13 changes: 8 additions & 5 deletions types/coin.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,8 @@ func (coins Coins) Validate() error {
}
}

func (coins Coins) isSorted() bool {
// IsSorted returns true when coins are order ASC sorted with denoms.
func (coins Coins) IsSorted() bool {
for i := 1; i < len(coins); i++ {
if coins[i-1].Denom > coins[i].Denom {
return false
Expand Down Expand Up @@ -323,10 +324,10 @@ func (coins Coins) Add(coinsB ...Coin) Coins {
func (coins Coins) safeAdd(coinsB Coins) (coalesced Coins) {
// probably the best way will be to make Coins and interface and hide the structure
// definition (type alias)
if !coins.isSorted() {
if !coins.IsSorted() {
panic("Coins (self) must be sorted")
}
if !coinsB.isSorted() {
if !coinsB.IsSorted() {
panic("Wrong argument: coins must be sorted")
}

Expand Down Expand Up @@ -473,7 +474,7 @@ func (coins Coins) SafeQuoInt(x math.Int) (Coins, bool) {
// a.Add(b...).Equal(a.Min(b).Add(a.Max(b)...))
//
// E.g.
// {1A, 3B, 2C}.Max({4A, 2B, 2C} == {4A, 3B, 2C})
// {1A, 3B, 2C}.Max({4A, 2B, 2C}) == {4A, 3B, 2C}
// {2A, 3B}.Max({1B, 4C}) == {2A, 3B, 4C}
// {1A, 2B}.Max({}) == {1A, 2B}
func (coins Coins) Max(coinsB Coins) Coins {
Expand Down Expand Up @@ -519,7 +520,7 @@ func (coins Coins) Max(coinsB Coins) Coins {
// a.Add(b...).Equal(a.Min(b).Add(a.Max(b)...))
//
// E.g.
// {1A, 3B, 2C}.Min({4A, 2B, 2C} == {1A, 2B, 2C})
// {1A, 3B, 2C}.Min({4A, 2B, 2C}) == {1A, 2B, 2C}
// {2A, 3B}.Min({1B, 4C}) == {1B}
// {1A, 2B}.Min({3C}) == empty
//
Expand Down Expand Up @@ -683,13 +684,15 @@ func (coins Coins) Empty() bool {
}

// AmountOf returns the amount of a denom from coins
// CONTRACT: coins must be valid (sorted).
func (coins Coins) AmountOf(denom string) math.Int {
mustValidateDenom(denom)
return coins.AmountOfNoDenomValidation(denom)
}

// AmountOfNoDenomValidation returns the amount of a denom from coins
// without validating the denomination.
// CONTRACT: coins must be valid (sorted).
func (coins Coins) AmountOfNoDenomValidation(denom string) math.Int {
if ok, c := coins.Find(denom); ok {
return c.Amount
Expand Down
2 changes: 1 addition & 1 deletion types/coin_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@ func (s *coinInternalSuite) TestIsSorted() {
}
assert := s.Assert()
for i, tc := range cases {
assert.Equal(tc.expected, tc.coins.isSorted(), "testcase %d failed", i)
assert.Equal(tc.expected, tc.coins.IsSorted(), "testcase %d failed", i)
}
}

0 comments on commit a5f1217

Please sign in to comment.