Skip to content

Commit

Permalink
fix: ballot sorting (#1851)
Browse files Browse the repository at this point in the history
* fix: ballot sorting

* test sorting
  • Loading branch information
robert-zaremba committed Feb 20, 2023
1 parent 0f23dbc commit 9ba9310
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
8 changes: 7 additions & 1 deletion x/oracle/types/ballot.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,13 @@ func (pb ExchangeRateBallot) Len() int {
// Less reports whether the element with
// index i should sort before the element with index j.
func (pb ExchangeRateBallot) Less(i, j int) bool {
return pb[i].ExchangeRate.LT(pb[j].ExchangeRate)
if pb[i].ExchangeRate.LT(pb[j].ExchangeRate) {
return true
}
if pb[i].ExchangeRate.Equal(pb[j].ExchangeRate) {
return bytes.Compare(pb[i].Voter, pb[j].Voter) < 0
}
return false
}

// Swap implements sort.Interface.
Expand Down
28 changes: 28 additions & 0 deletions x/oracle/types/ballot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ package types
import (
"fmt"
"math"
"sort"
"strconv"
"testing"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto/secp256k1"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"gotest.tools/v3/assert"
)

func TestToMap(t *testing.T) {
Expand Down Expand Up @@ -376,3 +378,29 @@ func TestClaimMapToSlice(t *testing.T) {
})
require.Equal(t, []Claim{claim, claim}, claimSlice)
}

func TestExchangeRateBallotSort(t *testing.T) {
v1 := VoteForTally{ExchangeRate: sdk.MustNewDecFromStr("0.2"), Voter: sdk.ValAddress{0, 1}}
v1Cpy := VoteForTally{ExchangeRate: sdk.MustNewDecFromStr("0.2"), Voter: sdk.ValAddress{0, 1}}
v2 := VoteForTally{ExchangeRate: sdk.MustNewDecFromStr("0.1"), Voter: sdk.ValAddress{0, 1, 1}}
v3 := VoteForTally{ExchangeRate: sdk.MustNewDecFromStr("0.1"), Voter: sdk.ValAddress{0, 1}}
v4 := VoteForTally{ExchangeRate: sdk.MustNewDecFromStr("0.5"), Voter: sdk.ValAddress{1}}

tcs := []struct {
got ExchangeRateBallot
expected ExchangeRateBallot
}{
{got: ExchangeRateBallot{v1, v2, v3, v4},
expected: ExchangeRateBallot{v3, v2, v1, v4}},
{got: ExchangeRateBallot{v1},
expected: ExchangeRateBallot{v1}},
{got: ExchangeRateBallot{v1, v1Cpy},
expected: ExchangeRateBallot{v1, v1Cpy}},
}
for i, tc := range tcs {
t.Run(fmt.Sprint(i), func(t *testing.T) {
sort.Sort(tc.got)
assert.DeepEqual(t, tc.expected, tc.got)
})
}
}

0 comments on commit 9ba9310

Please sign in to comment.