Skip to content

Commit

Permalink
Breakdown internal/helpers into internal/sdk, internal/collections, a…
Browse files Browse the repository at this point in the history
…nd internal/rand.
  • Loading branch information
Taztingo committed May 31, 2024
1 parent 5d3ed55 commit e5177c4
Show file tree
Hide file tree
Showing 23 changed files with 165 additions and 146 deletions.
8 changes: 4 additions & 4 deletions app/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/staking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"

"github.com/provenance-io/provenance/internal/helpers"
internalsdk "github.com/provenance-io/provenance/internal/sdk"
markertypes "github.com/provenance-io/provenance/x/marker/types"
)

Expand Down Expand Up @@ -100,7 +100,7 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str

// withdraw all validator commission
ierr := app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
_, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, helpers.MustGetOperatorAddr(val))
_, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, internalsdk.MustGetOperatorAddr(val))
return false
})
if ierr != nil {
Expand Down Expand Up @@ -136,7 +136,7 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str
// reinitialize all validators
ierr = app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
// donate any unwithdrawn outstanding reward fraction tokens to the community pool
scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, helpers.MustGetOperatorAddr(val))
scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, internalsdk.MustGetOperatorAddr(val))
if err != nil {
panic(err)
}
Expand All @@ -150,7 +150,7 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str
panic(err)
}

if err = app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, helpers.MustGetOperatorAddr(val)); err != nil {
if err = app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, internalsdk.MustGetOperatorAddr(val)); err != nil {
panic(err)
}
return false
Expand Down
4 changes: 2 additions & 2 deletions app/upgrades_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"

"github.com/provenance-io/provenance/internal/helpers"
internalsdk "github.com/provenance-io/provenance/internal/sdk"
)

type UpgradeTestSuite struct {
Expand Down Expand Up @@ -265,7 +265,7 @@ func (s *UpgradeTestSuite) DelegateToValidator(valAddress sdk.ValAddress, delega
}

func (s *UpgradeTestSuite) GetOperatorAddr(val stakingtypes.ValidatorI) sdk.ValAddress {
addr, err := helpers.GetOperatorAddr(val)
addr, err := internalsdk.GetOperatorAddr(val)
s.Require().NoError(err, "GetOperatorAddr(%q)", val.GetOperator())
return addr
}
Expand Down
2 changes: 1 addition & 1 deletion internal/helpers/maps.go → internal/collections/maps.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package helpers
package collections

// This file houses functions that are in "golang.org/x/exp/maps" but not "maps", but that we want to use.
// If any show up in "maps", delete them from here and switch uses to the official ones.
Expand Down
4 changes: 2 additions & 2 deletions internal/handlers/msg_service_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ import (
"github.com/cosmos/gogoproto/proto"

"github.com/provenance-io/provenance/internal/antewrapper"
"github.com/provenance-io/provenance/internal/helpers"
"github.com/provenance-io/provenance/internal/protocompat"
internalsdk "github.com/provenance-io/provenance/internal/sdk"
msgfeeskeeper "github.com/provenance-io/provenance/x/msgfees/keeper"
)

Expand Down Expand Up @@ -169,7 +169,7 @@ func (msr *PioMsgServiceRouter) registerMsgServiceHandler(sd *grpc.ServiceDesc,
return handler(goCtx, req)
}

if err = helpers.ValidateBasic(req); err != nil {
if err = internalsdk.ValidateBasic(req); err != nil {
return nil, err
}

Expand Down
4 changes: 2 additions & 2 deletions internal/provwasm/message_encoders.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"

"github.com/provenance-io/provenance/internal/helpers"
internalsdk "github.com/provenance-io/provenance/internal/sdk"
)

// Encoder describes behavior for provenance smart contract message encoding.
Expand Down Expand Up @@ -65,7 +65,7 @@ func customEncoders(registry *EncoderRegistry, logger log.Logger) wasmkeeper.Cus
return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error())
}
for _, msg := range msgs {
if err := helpers.ValidateBasic(msg); err != nil {
if err := internalsdk.ValidateBasic(msg); err != nil {
logger.Error("message validation failed", "err", err)
return nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error())
}
Expand Down
12 changes: 12 additions & 0 deletions internal/rand/account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package rand

import (
"math/rand"

simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
)

// SelectAccounts selects count accounts from the ones provided.
func SelectAccounts(r *rand.Rand, accs []simtypes.Account, count int) ([]simtypes.Account, error) {
return SelectEntries(r, accs, count, "accounts")
}
8 changes: 8 additions & 0 deletions internal/rand/int.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package rand

import "math/rand"

// IntBetween generates a random number between min and max inclusive.
func IntBetween(r *rand.Rand, min, max int) int {
return r.Intn(max-min+1) + min
}
94 changes: 94 additions & 0 deletions internal/rand/int_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package rand

import (
"fmt"
"math/rand"
"slices"
"testing"

internalcollections "github.com/provenance-io/provenance/internal/collections"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestIntBetween(t *testing.T) {
tests := []struct {
min int
max int
expPanic bool
}{
{min: 0, max: 0},
{min: 0, max: 10},
{min: 1, max: 1},
{min: -1, max: -1},
{min: 1, max: 0, expPanic: true},
{min: 0, max: -1, expPanic: true},
{min: 1, max: -1, expPanic: true},
{min: 10, max: -20, expPanic: true},
{min: 10, max: -11, expPanic: true},
{min: 10, max: -10, expPanic: true},
{min: 10, max: -9, expPanic: true},
{min: 10, max: 9, expPanic: true},
{min: 10, max: 10},
{min: 10, max: 11},
{min: 10, max: 20},
{min: -10, max: -11, expPanic: true},
{min: -10, max: -10},
{min: -10, max: -9},
{min: -10, max: 9},
{min: -10, max: 10},
{min: -10, max: 11},
{min: -20, max: -1},
{min: -20, max: 0},
{min: -20, max: 1},
{min: 1001, max: 1100},
{min: -1778, max: -1670},
}

for _, tc := range tests {
name := fmt.Sprintf("RandIntBetween(%d, %d)", tc.min, tc.max)
if tc.expPanic {
name += " panics"
}

t.Run(name, func(t *testing.T) {
r := rand.New(rand.NewSource(1))
// Check for panic for the first try.
seen := make(map[int]bool)
testFunc := func() {
val := IntBetween(r, tc.min, tc.max)
seen[val] = true
}
if tc.expPanic {
require.PanicsWithValue(t, "invalid argument to Intn", testFunc)
return
}
require.NotPanics(t, testFunc)

count := tc.max - tc.min + 1
expected := make([]int, 0, count)
for i := tc.min; i <= tc.max; i++ {
expected = append(expected, i)
}

// Run it a bunch of times, trying to get it to return all possible values.
// I chose count*100 to essentially give each value 100 chances to be chosen, but be
// low enough to still finish pretty quickly if one or more values never gets returned.
for i := 0; i < count*100 && len(seen) < count; i++ {
testFunc()
}
// Make sure both the min and max were returned at some point.
assert.True(t, seen[tc.min], "minimum value %d in seen map", tc.min)
assert.True(t, seen[tc.max], "maximum value %d in seen map", tc.max)

seenVals := internalcollections.Keys(seen)
slices.Sort(seenVals)
// Make sure the smallest and largest are as expected.
assert.Equal(t, tc.min, seenVals[0], "smallest number generated")
assert.Equal(t, tc.max, seenVals[len(seenVals)-1], "largest number generated")
// Make sure all values were generated. This check technically covers the previous ones,
// but I've got them split out like this for friendlier test failure messages.
assert.Equal(t, expected, seenVals, "values generated")
})
}
}
18 changes: 3 additions & 15 deletions internal/helpers/rand.go → internal/rand/slices.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
package helpers
package rand

import (
"fmt"
"math/rand"

simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
)

// RandIntBetween generates a random number between min and max inclusive.
func RandIntBetween(r *rand.Rand, min, max int) int {
return r.Intn(max-min+1) + min
}

// SelectRandomEntries selects count entries from the ones provided.
// SelectEntries selects count entries from the ones provided.
// The entriesType string is used in the error message to describe the entries slice.
func SelectRandomEntries[E any](r *rand.Rand, entries []E, count int, entriesType string) ([]E, error) {
func SelectEntries[E any](r *rand.Rand, entries []E, count int, entriesType string) ([]E, error) {
if count == 0 {
return nil, nil
}
Expand All @@ -36,8 +29,3 @@ func SelectRandomEntries[E any](r *rand.Rand, entries []E, count int, entriesTyp
})
return randomized[:count], nil
}

// SelectRandomAccounts selects count accounts from the ones provided.
func SelectRandomAccounts(r *rand.Rand, accs []simtypes.Account, count int) ([]simtypes.Account, error) {
return SelectRandomEntries(r, accs, count, "accounts")
}
89 changes: 3 additions & 86 deletions internal/helpers/rand_test.go → internal/rand/slices_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package helpers
package rand

import (
"fmt"
"math/rand"
"slices"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -12,89 +11,7 @@ import (
"github.com/provenance-io/provenance/testutil/assertions"
)

func TestRandIntBetween(t *testing.T) {
tests := []struct {
min int
max int
expPanic bool
}{
{min: 0, max: 0},
{min: 0, max: 10},
{min: 1, max: 1},
{min: -1, max: -1},
{min: 1, max: 0, expPanic: true},
{min: 0, max: -1, expPanic: true},
{min: 1, max: -1, expPanic: true},
{min: 10, max: -20, expPanic: true},
{min: 10, max: -11, expPanic: true},
{min: 10, max: -10, expPanic: true},
{min: 10, max: -9, expPanic: true},
{min: 10, max: 9, expPanic: true},
{min: 10, max: 10},
{min: 10, max: 11},
{min: 10, max: 20},
{min: -10, max: -11, expPanic: true},
{min: -10, max: -10},
{min: -10, max: -9},
{min: -10, max: 9},
{min: -10, max: 10},
{min: -10, max: 11},
{min: -20, max: -1},
{min: -20, max: 0},
{min: -20, max: 1},
{min: 1001, max: 1100},
{min: -1778, max: -1670},
}

for _, tc := range tests {
name := fmt.Sprintf("RandIntBetween(%d, %d)", tc.min, tc.max)
if tc.expPanic {
name += " panics"
}

t.Run(name, func(t *testing.T) {
r := rand.New(rand.NewSource(1))
// Check for panic for the first try.
seen := make(map[int]bool)
testFunc := func() {
val := RandIntBetween(r, tc.min, tc.max)
seen[val] = true
}
if tc.expPanic {
require.PanicsWithValue(t, "invalid argument to Intn", testFunc)
return
}
require.NotPanics(t, testFunc)

count := tc.max - tc.min + 1
expected := make([]int, 0, count)
for i := tc.min; i <= tc.max; i++ {
expected = append(expected, i)
}

// Run it a bunch of times, trying to get it to return all possible values.
// I chose count*100 to essentially give each value 100 chances to be chosen, but be
// low enough to still finish pretty quickly if one or more values never gets returned.
for i := 0; i < count*100 && len(seen) < count; i++ {
testFunc()
}
// Make sure both the min and max were returned at some point.
assert.True(t, seen[tc.min], "minimum value %d in seen map", tc.min)
assert.True(t, seen[tc.max], "maximum value %d in seen map", tc.max)

seenVals := Keys(seen)
slices.Sort(seenVals)
// Make sure the smallest and largest are as expected.
assert.Equal(t, tc.min, seenVals[0], "smallest number generated")
assert.Equal(t, tc.max, seenVals[len(seenVals)-1], "largest number generated")
// Make sure all values were generated. This check technically covers the previous ones,
// but I've got them split out like this for friendlier test failure messages.
assert.Equal(t, expected, seenVals, "values generated")
})
}
}

func TestSelectRandomEntries(t *testing.T) {
func TestSelectEntries(t *testing.T) {
entries := make([]string, 3)
for i := range entries {
entries[i] = fmt.Sprintf("entry_%02d", i)
Expand Down Expand Up @@ -273,7 +190,7 @@ func TestSelectRandomEntries(t *testing.T) {
var actual []string
var err error
testFunc := func() {
actual, err = SelectRandomEntries(r, tc.entries, tc.count, tc.entriesType)
actual, err = SelectEntries(r, tc.entries, tc.count, tc.entriesType)
}
require.NotPanics(t, testFunc, "SelectRandomEntries")
assertions.AssertErrorValue(t, err, tc.expErr, "SelectRandomEntries error")
Expand Down
2 changes: 1 addition & 1 deletion internal/helpers/sdk.go → internal/sdk/validator.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package helpers
package sdk

import (
sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down
6 changes: 3 additions & 3 deletions x/exchange/client/cli/tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"

"github.com/provenance-io/provenance/internal/helpers"
internalcollections "github.com/provenance-io/provenance/internal/collections"
"github.com/provenance-io/provenance/x/exchange"
"github.com/provenance-io/provenance/x/exchange/client/cli"
)
Expand Down Expand Up @@ -1010,7 +1010,7 @@ func (s *CmdTestSuite) TestCmdTxMarketManagePermissions() {
}
}

addrOrder := helpers.Keys(expPerms)
addrOrder := internalcollections.Keys(expPerms)
sort.Slice(addrOrder, func(i, j int) bool {
return bytes.Compare(s.accountAddrs[addrOrder[i]], s.accountAddrs[addrOrder[j]]) < 0
})
Expand Down Expand Up @@ -1042,7 +1042,7 @@ func (s *CmdTestSuite) TestCmdTxMarketManagePermissions() {
3: {exchange.Permission_cancel, exchange.Permission_attributes},
}

addrOrder := helpers.Keys(expPerms)
addrOrder := internalcollections.Keys(expPerms)
sort.Slice(addrOrder, func(i, j int) bool {
return bytes.Compare(s.accountAddrs[addrOrder[i]], s.accountAddrs[addrOrder[j]]) < 0
})
Expand Down
Loading

0 comments on commit e5177c4

Please sign in to comment.