diff --git a/.golangci.yml b/.golangci.yml index 3ed11ffc0aad..bbce526a7dc3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,7 +10,6 @@ linters: - deadcode - depguard - dogsled - # - errcheck - exportloopref - goconst - gocritic @@ -32,7 +31,6 @@ linters: - unconvert - unparam - unused - # - wsl issues: exclude-rules: diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e5401ef2efa..0df6f2ae0bc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,7 +50,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (x/staking) [#12102](https://github.com/cosmos/cosmos-sdk/pull/12102) Staking keeper now is passed by reference instead of copy. Keeper's SetHooks no longer returns keeper. It updates the keeper in place instead. ### Bug Fixes - +* (linting) [#12132](https://github.com/cosmos/cosmos-sdk/pull/12132) Change sdk.Int to math.Int, run `gofumpt -w -l .`, and `golangci-lint run ./... --fix` * (cli) [#12127](https://github.com/cosmos/cosmos-sdk/pull/12127) Fix the CLI not always taking into account `--fee-payer` and `--fee-granter` flags. * (migrations) [#12028](https://github.com/cosmos/cosmos-sdk/pull/12028) Fix v0.45->v0.46 in-place store migrations. * (baseapp) [#12089](https://github.com/cosmos/cosmos-sdk/pull/12089) Include antehandler and runMsgs events in SimulateTx. diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 6908101862d8..34f62c7b075f 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -11,7 +11,6 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/cosmos/cosmos-sdk/codec/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/snapshots" "github.com/cosmos/cosmos-sdk/store" @@ -54,7 +53,7 @@ type BaseApp struct { // nolint: maligned queryRouter sdk.QueryRouter // router for redirecting query calls grpcQueryRouter *GRPCQueryRouter // router for redirecting gRPC query calls msgServiceRouter *MsgServiceRouter // router for redirecting Msg service messages - interfaceRegistry types.InterfaceRegistry + interfaceRegistry codectypes.InterfaceRegistry txDecoder sdk.TxDecoder // unmarshal []byte into sdk.Tx anteHandler sdk.AnteHandler // ante handler for fee and auth diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 8d67a7a5f001..5be9331b6260 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -1294,7 +1294,6 @@ func TestTxGasLimits(t *testing.T) { return newCtx, nil }) - } routerOpt := func(bapp *BaseApp) { diff --git a/client/cmd.go b/client/cmd.go index ce6faba09e06..77b404bcb575 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -268,7 +268,7 @@ func readTxCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, err isAux, _ := flagSet.GetBool(flags.FlagAux) clientCtx = clientCtx.WithAux(isAux) if isAux { - // If the user didn't explicity set an --output flag, use JSON by + // If the user didn't explicitly set an --output flag, use JSON by // default. if clientCtx.OutputFormat == "" || !flagSet.Changed(cli.OutputFlag) { clientCtx = clientCtx.WithOutputFormat("json") diff --git a/client/grpc/tmservice/block.go b/client/grpc/tmservice/block.go index 6f3b1e556993..f941c9093a83 100644 --- a/client/grpc/tmservice/block.go +++ b/client/grpc/tmservice/block.go @@ -27,7 +27,7 @@ func GetProtoBlock(ctx context.Context, clientCtx client.Context, height *int64) if err != nil { return tmproto.BlockID{}, nil, err } - protoBlockId := block.BlockID.ToProto() + protoBlockID := block.BlockID.ToProto() - return protoBlockId, protoBlock, nil + return protoBlockID, protoBlock, nil } diff --git a/client/grpc_query.go b/client/grpc_query.go index dd0f5ab11335..a5b348ca1058 100644 --- a/client/grpc_query.go +++ b/client/grpc_query.go @@ -156,7 +156,7 @@ func (f failingInterfaceRegistry) UnpackAny(any *types.Any, iface interface{}) e return errCodecNotSet } -func (f failingInterfaceRegistry) Resolve(typeUrl string) (proto.Message, error) { +func (f failingInterfaceRegistry) Resolve(typeURL string) (proto.Message, error) { return nil, errCodecNotSet } diff --git a/client/keys/add.go b/client/keys/add.go index 76d15b8b9a9e..13b58018b5f2 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -298,7 +298,7 @@ func printCreate(cmd *cobra.Command, k *keyring.Record, showMnemonic bool, mnemo // print mnemonic unless requested not to. if showMnemonic { - if _, err := fmt.Fprintln(cmd.ErrOrStderr(), fmt.Sprintf("\n**Important** write this mnemonic phrase in a safe place.\nIt is the only way to recover your account if you ever forget your password.\n\n%s\n", mnemonic)); err != nil { + if _, err := fmt.Fprintf(cmd.ErrOrStderr(), fmt.Sprintf("\n**Important** write this mnemonic phrase in a safe place.\nIt is the only way to recover your account if you ever forget your password.\n\n%s\n", mnemonic)); err != nil { return fmt.Errorf("failed to print mnemonic: %v", err) } } diff --git a/core/appconfig/config.go b/core/appconfig/config.go index b77330bb4440..6aabcfcec957 100644 --- a/core/appconfig/config.go +++ b/core/appconfig/config.go @@ -80,7 +80,6 @@ func Compose(appConfig *appv1alpha1.Config) depinject.Config { config := init.ConfigProtoMessage.ProtoReflect().Type().New().Interface() err = anypb.UnmarshalTo(module.Config, config, proto.UnmarshalOptions{}) if err != nil { - return depinject.Error(err) } diff --git a/crypto/keyring/keyring_test.go b/crypto/keyring/keyring_test.go index 235a66d2687e..66c326598b71 100644 --- a/crypto/keyring/keyring_test.go +++ b/crypto/keyring/keyring_test.go @@ -157,7 +157,7 @@ func TestKeyManagementKeyRing(t *testing.T) { // create some random directory inside the keyring directory to check migrate ignores // all files other than *.info newPath := filepath.Join(tempDir, "random") - require.NoError(t, os.Mkdir(newPath, 0755)) + require.NoError(t, os.Mkdir(newPath, 0o755)) items, err := os.ReadDir(tempDir) require.GreaterOrEqual(t, len(items), 2) keyS, err = kb.List() diff --git a/crypto/keys/secp256k1/internal/secp256k1/curve.go b/crypto/keys/secp256k1/internal/secp256k1/curve.go index b5c80b23ad62..d83bf62ca2fe 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/curve.go +++ b/crypto/keys/secp256k1/internal/secp256k1/curve.go @@ -79,28 +79,28 @@ type BitCurve struct { BitSize int // the size of the underlying field } -func (BitCurve *BitCurve) Params() *elliptic.CurveParams { +func (bitCurve *BitCurve) Params() *elliptic.CurveParams { return &elliptic.CurveParams{ - P: BitCurve.P, - N: BitCurve.N, - B: BitCurve.B, - Gx: BitCurve.Gx, - Gy: BitCurve.Gy, - BitSize: BitCurve.BitSize, + P: bitCurve.P, + N: bitCurve.N, + B: bitCurve.B, + Gx: bitCurve.Gx, + Gy: bitCurve.Gy, + BitSize: bitCurve.BitSize, } } // IsOnCurve returns true if the given (x,y) lies on the BitCurve. -func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { +func (bitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { // y² = x³ + b y2 := new(big.Int).Mul(y, y) // y² - y2.Mod(y2, BitCurve.P) // y²%P + y2.Mod(y2, bitCurve.P) // y²%P x3 := new(big.Int).Mul(x, x) // x² x3.Mul(x3, x) // x³ - x3.Add(x3, BitCurve.B) // x³+B - x3.Mod(x3, BitCurve.P) //(x³+B)%P + x3.Add(x3, bitCurve.B) // x³+B + x3.Mod(x3, bitCurve.P) // (x³+B)%P return x3.Cmp(y2) == 0 } @@ -108,24 +108,24 @@ func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { // TODO: double check if the function is okay // affineFromJacobian reverses the Jacobian transform. See the comment at the // top of the file. -func (BitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) { +func (bitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) { if z.Sign() == 0 { return new(big.Int), new(big.Int) } - zinv := new(big.Int).ModInverse(z, BitCurve.P) + zinv := new(big.Int).ModInverse(z, bitCurve.P) zinvsq := new(big.Int).Mul(zinv, zinv) xOut = new(big.Int).Mul(x, zinvsq) - xOut.Mod(xOut, BitCurve.P) + xOut.Mod(xOut, bitCurve.P) zinvsq.Mul(zinvsq, zinv) yOut = new(big.Int).Mul(y, zinvsq) - yOut.Mod(yOut, BitCurve.P) + yOut.Mod(yOut, bitCurve.P) return } // Add returns the sum of (x1,y1) and (x2,y2) -func (BitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { +func (bitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { // If one point is at infinity, return the other point. // Adding the point at infinity to any point will preserve the other point. if x1.Sign() == 0 && y1.Sign() == 0 { @@ -136,9 +136,9 @@ func (BitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { } z := new(big.Int).SetInt64(1) if x1.Cmp(x2) == 0 && y1.Cmp(y2) == 0 { - return BitCurve.affineFromJacobian(BitCurve.doubleJacobian(x1, y1, z)) + return bitCurve.affineFromJacobian(bitCurve.doubleJacobian(x1, y1, z)) } - return BitCurve.affineFromJacobian(BitCurve.addJacobian(x1, y1, z, x2, y2, z)) + return bitCurve.affineFromJacobian(bitCurve.addJacobian(x1, y1, z, x2, y2, z)) } // addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and @@ -222,9 +222,9 @@ func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, c := new(big.Int).Mul(b, b) // B² d := new(big.Int).Add(x, b) // X1+B - d.Mul(d, d) //(X1+B)² - d.Sub(d, a) //(X1+B)²-A - d.Sub(d, c) //(X1+B)²-A-C + d.Mul(d, d) // (X1+B)² + d.Sub(d, a) // (X1+B)²-A + d.Sub(d, c) // (X1+B)²-A-C d.Mul(d, big.NewInt(2)) // 2*((X1+B)²-A-C) e := new(big.Int).Mul(big.NewInt(3), a) // 3*A @@ -254,8 +254,8 @@ func (BitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { // Marshal converts a point into the form specified in section 4.3.6 of ANSI // X9.62. -func (BitCurve *BitCurve) Marshal(x, y *big.Int) []byte { - byteLen := (BitCurve.BitSize + 7) >> 3 +func (bitCurve *BitCurve) Marshal(x, y *big.Int) []byte { + byteLen := (bitCurve.BitSize + 7) >> 3 ret := make([]byte, 1+2*byteLen) ret[0] = 4 // uncompressed point flag readBits(x, ret[1:1+byteLen]) @@ -265,8 +265,8 @@ func (BitCurve *BitCurve) Marshal(x, y *big.Int) []byte { // Unmarshal converts a point, serialised by Marshal, into an x, y pair. On // error, x = nil. -func (BitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) { - byteLen := (BitCurve.BitSize + 7) >> 3 +func (bitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) { + byteLen := (bitCurve.BitSize + 7) >> 3 if len(data) != 1+2*byteLen { return } diff --git a/depinject/debug.go b/depinject/debug.go index 473076f28a84..820354426aa4 100644 --- a/depinject/debug.go +++ b/depinject/debug.go @@ -236,7 +236,7 @@ func (c *debugConfig) enableLogVisualizer() { func (c *debugConfig) addFileVisualizer(filename string) { c.visualizers = append(c.visualizers, func(_ string) { dotStr := c.graph.String() - err := os.WriteFile(filename, []byte(dotStr), 0644) + err := os.WriteFile(filename, []byte(dotStr), 0o644) if err != nil { c.logf("Error saving graphviz file %s: %+v", filename, err) } else { diff --git a/pruning/manager.go b/pruning/manager.go index 8e7c61cc9ef6..ac1172ebb86e 100644 --- a/pruning/manager.go +++ b/pruning/manager.go @@ -13,7 +13,7 @@ import ( ) // Manager is an abstraction to handle the logic needed for -// determinging when to prune old heights of the store +// determining when to prune old heights of the store // based on the strategy described by the pruning options. type Manager struct { db dbm.DB diff --git a/runtime/app.go b/runtime/app.go index 8802337fe6a2..504e26b1ef8b 100644 --- a/runtime/app.go +++ b/runtime/app.go @@ -106,13 +106,13 @@ func (a *App) Load(loadLatest bool) error { } // BeginBlocker application updates every begin block -func (app *App) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - return app.ModuleManager.BeginBlock(ctx, req) +func (a *App) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { + return a.ModuleManager.BeginBlock(ctx, req) } // EndBlocker application updates every end block -func (app *App) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - return app.ModuleManager.EndBlock(ctx, req) +func (a *App) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { + return a.ModuleManager.EndBlock(ctx, req) } // InitChainer initializes the chain. diff --git a/runtime/module.go b/runtime/module.go index ac053b1f6310..399e9ad2c0b6 100644 --- a/runtime/module.go +++ b/runtime/module.go @@ -43,7 +43,8 @@ func provideCodecs(moduleBasics map[string]AppModuleBasicWrapper) ( codec.Codec, *codec.LegacyAmino, appWrapper, - codec.ProtoCodecMarshaler) { + codec.ProtoCodecMarshaler, +) { interfaceRegistry := codectypes.NewInterfaceRegistry() amino := codec.NewLegacyAmino() diff --git a/server/mock/tx.go b/server/mock/tx.go index 0cb79c28986f..3c93ffb83410 100644 --- a/server/mock/tx.go +++ b/server/mock/tx.go @@ -21,8 +21,10 @@ func (msg kvstoreTx) Reset() {} func (msg kvstoreTx) String() string { return "TODO" } func (msg kvstoreTx) ProtoMessage() {} -var _ sdk.Tx = kvstoreTx{} -var _ sdk.Msg = kvstoreTx{} +var ( + _ sdk.Tx = kvstoreTx{} + _ sdk.Msg = kvstoreTx{} +) func NewTx(key, value string) kvstoreTx { bytes := fmt.Sprintf("%s=%s", key, value) diff --git a/server/rosetta/converter.go b/server/rosetta/converter.go index 54c154579861..a58927207ab5 100644 --- a/server/rosetta/converter.go +++ b/server/rosetta/converter.go @@ -6,6 +6,7 @@ import ( "fmt" "reflect" + "cosmossdk.io/math" "github.com/btcsuite/btcd/btcec" rosettatypes "github.com/coinbase/rosetta-sdk-go/types" abci "github.com/tendermint/tendermint/abci/types" @@ -408,7 +409,7 @@ func sdkEventToBalanceOperations(status string, event abci.Event) (operations [] // Amounts converts []sdk.Coin to rosetta amounts func (c converter) Amounts(ownedCoins []sdk.Coin, availableCoins sdk.Coins) []*rosettatypes.Amount { amounts := make([]*rosettatypes.Amount, len(availableCoins)) - ownedCoinsMap := make(map[string]sdk.Int, len(availableCoins)) + ownedCoinsMap := make(map[string]math.Int, len(availableCoins)) for _, ownedCoin := range ownedCoins { ownedCoinsMap[ownedCoin.Denom] = ownedCoin.Amount diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 6cc63850ff74..a664131894cf 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -165,7 +165,6 @@ func makeKeyMigrateCmd() *cobra.Command { ID: dbctx, Config: config, }) - if err != nil { return fmt.Errorf("constructing database handle: %w", err) } @@ -178,7 +177,6 @@ func makeKeyMigrateCmd() *cobra.Command { if dbctx == "blockstore" { if err := scmigrate.Migrate(ctx, db); err != nil { return fmt.Errorf("running seen commit migration: %w", err) - } } } diff --git a/simapp/app.go b/simapp/app.go index 51cfbaf7ff03..02d711bf1e83 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -346,11 +346,13 @@ func NewSimApp( // NOTE: Capability module must occur first so that it can initialize any capabilities // so that other modules that want to create or claim capabilities afterwards in InitChain // can do so safely. - genesisModuleOrder := []string{capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, + genesisModuleOrder := []string{ + capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, stakingtypes.ModuleName, slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName, feegrant.ModuleName, nft.ModuleName, group.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, - vestingtypes.ModuleName} + vestingtypes.ModuleName, + } app.ModuleManager.SetOrderInitGenesis(genesisModuleOrder...) app.ModuleManager.SetOrderExportGenesis(genesisModuleOrder...) @@ -434,7 +436,6 @@ func (app *SimApp) setAnteHandler(txConfig client.TxConfig, indexEventsStr []str SigGasConsumer: ante.DefaultSigVerificationGasConsumer, }, ) - if err != nil { panic(err) } diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 3c9beddc7ca7..c336bd5fa56a 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -6,8 +6,6 @@ import ( "encoding/hex" "encoding/json" "fmt" - "github.com/cosmos/cosmos-sdk/depinject" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "strconv" "testing" "time" @@ -21,6 +19,9 @@ import ( dbm "github.com/tendermint/tm-db" bam "github.com/cosmos/cosmos-sdk/baseapp" + "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/depinject" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/cosmos/cosmos-sdk/client" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" @@ -306,7 +307,7 @@ func createIncrementalAccounts(accNum int) []sdk.AccAddress { } // AddTestAddrsFromPubKeys adds the addresses into the SimApp providing only the public keys. -func AddTestAddrsFromPubKeys(app *SimApp, ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt sdk.Int) { +func AddTestAddrsFromPubKeys(app *SimApp, ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt math.Int) { initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt)) for _, pk := range pubKeys { @@ -316,17 +317,17 @@ func AddTestAddrsFromPubKeys(app *SimApp, ctx sdk.Context, pubKeys []cryptotypes // AddTestAddrs constructs and returns accNum amount of accounts with an // initial balance of accAmt in random order -func AddTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sdk.AccAddress { +func AddTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt math.Int) []sdk.AccAddress { return addTestAddrs(app, ctx, accNum, accAmt, createRandomAccounts) } // AddTestAddrsIncremental constructs and returns accNum amount of accounts with an // initial balance of accAmt in random order -func AddTestAddrsIncremental(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sdk.AccAddress { +func AddTestAddrsIncremental(app *SimApp, ctx sdk.Context, accNum int, accAmt math.Int) []sdk.AccAddress { return addTestAddrs(app, ctx, accNum, accAmt, createIncrementalAccounts) } -func addTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int, strategy GenerateAccountStrategy) []sdk.AccAddress { +func addTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt math.Int, strategy GenerateAccountStrategy) []sdk.AccAddress { testAddrs := strategy(accNum) initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt)) diff --git a/snapshots/types/util.go b/snapshots/types/util.go index 125ea6fb4610..348b5057682d 100644 --- a/snapshots/types/util.go +++ b/snapshots/types/util.go @@ -4,7 +4,7 @@ import ( protoio "github.com/gogo/protobuf/io" ) -// WriteExtensionItem writes an item payload for current extention snapshotter. +// WriteExtensionItem writes an item payload for current extension snapshotter. func WriteExtensionItem(protoWriter protoio.Writer, item []byte) error { return protoWriter.WriteMsg(&SnapshotItem{ Item: &SnapshotItem_ExtensionPayload{ diff --git a/store/streaming/constructor_test.go b/store/streaming/constructor_test.go index 79051d16500a..1b0479cc7d51 100644 --- a/store/streaming/constructor_test.go +++ b/store/streaming/constructor_test.go @@ -81,7 +81,6 @@ func TestLoadStreamingServices(t *testing.T) { require.Equal(t, tc.activeStreamersLen, len(activeStreamers)) }) } - } type streamingAppOptions struct { diff --git a/store/v2alpha1/smt/ics23.go b/store/v2alpha1/smt/ics23.go index 31d78f993dc0..3c4299227298 100644 --- a/store/v2alpha1/smt/ics23.go +++ b/store/v2alpha1/smt/ics23.go @@ -104,7 +104,7 @@ func convertInnerOps(path []byte, sideNodes [][]byte) []*ics23.InnerOp { Hash: ics23.HashOp_SHA256, Prefix: []byte{1}, } - if getBitAtFromMSB(path[:], depth-1-i) == 1 { + if getBitAtFromMSB(path, depth-1-i) == 1 { // right child is on path op.Prefix = append(op.Prefix, sideNodes[i]...) } else { diff --git a/testutil/network/network.go b/testutil/network/network.go index b4675a769f7c..815117cca1a9 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -24,6 +24,7 @@ import ( dbm "github.com/tendermint/tm-db" "google.golang.org/grpc" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" @@ -84,9 +85,9 @@ type Config struct { Mnemonics []string // custom user-provided validator operator mnemonics BondDenom string // the staking bond denomination MinGasPrices string // the minimum gas prices each validator will accept - AccountTokens sdk.Int // the amount of unique validator tokens (e.g. 1000node0) - StakingTokens sdk.Int // the amount of tokens each validator has available to stake - BondedTokens sdk.Int // the amount of tokens each validator stakes + AccountTokens math.Int // the amount of unique validator tokens (e.g. 1000node0) + StakingTokens math.Int // the amount of tokens each validator has available to stake + BondedTokens math.Int // the amount of tokens each validator stakes PruningStrategy string // the pruning strategy each validator will have EnableTMLogging bool // enable Tendermint logging to STDOUT CleanupDir bool // remove base temporary directory during cleanup diff --git a/types/address.go b/types/address.go index 3da2bffdfd38..5e28d1e9f295 100644 --- a/types/address.go +++ b/types/address.go @@ -285,7 +285,7 @@ func (aa AccAddress) String() string { } // Format implements the fmt.Formatter interface. -// nolint: errcheck + func (aa AccAddress) Format(s fmt.State, verb rune) { switch verb { case 's': @@ -435,7 +435,7 @@ func (va ValAddress) String() string { } // Format implements the fmt.Formatter interface. -// nolint: errcheck + func (va ValAddress) Format(s fmt.State, verb rune) { switch verb { case 's': @@ -614,7 +614,7 @@ func MustBech32ifyAddressBytes(prefix string, bs []byte) string { } // Format implements the fmt.Formatter interface. -// nolint: errcheck + func (ca ConsAddress) Format(s fmt.State, verb rune) { switch verb { case 's': diff --git a/types/coin.go b/types/coin.go index c5bf96aeac04..142476f4b390 100644 --- a/types/coin.go +++ b/types/coin.go @@ -411,7 +411,7 @@ func (coins Coins) SafeSub(coinsB ...Coin) (Coins, bool) { } // MulInt performs the scalar multiplication of coins with a `multiplier` -// All coins are multipled by x +// All coins are multiplied by x // e.g. // {2A, 3B} * 2 = {4A, 6B} // {2A} * 0 panics diff --git a/types/kv/list.go b/types/kv/list.go index 2b0793d343cd..f038ccfa0ec0 100644 --- a/types/kv/list.go +++ b/types/kv/list.go @@ -113,7 +113,6 @@ func (l *List) remove(e *Element) *Element { } // move moves e to next to at and returns e. -// nolint: unparam func (l *List) move(e, at *Element) *Element { if e == at { return e diff --git a/types/simulation/rand_util.go b/types/simulation/rand_util.go index ce64bd7e8645..cc62fd7e89fd 100644 --- a/types/simulation/rand_util.go +++ b/types/simulation/rand_util.go @@ -7,6 +7,7 @@ import ( "time" "unsafe" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -39,10 +40,10 @@ func RandStringOfLength(r *rand.Rand, n int) string { return *(*string)(unsafe.Pointer(&b)) } -// RandPositiveInt get a rand positive sdk.Int -func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { +// RandPositiveInt get a rand positive math.Int +func RandPositiveInt(r *rand.Rand, max math.Int) (math.Int, error) { if !max.GTE(sdk.OneInt()) { - return sdk.Int{}, errors.New("max too small") + return math.Int{}, errors.New("max too small") } max = max.Sub(sdk.OneInt()) @@ -52,7 +53,7 @@ func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { // RandomAmount generates a random amount // Note: The range of RandomAmount includes max, and is, in fact, biased to return max as well as 0. -func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int { +func RandomAmount(r *rand.Rand, max math.Int) math.Int { randInt := big.NewInt(0) switch r.Intn(10) { diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 6ff5532a4386..1e6f8ace5bcd 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -511,7 +511,6 @@ func (suite *AnteTestSuite) TestAnteHandlerFees() { for _, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { - suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() tc.malleate() diff --git a/x/auth/ante/basic_test.go b/x/auth/ante/basic_test.go index 4a8cb830fdf6..761e7a2b8e88 100644 --- a/x/auth/ante/basic_test.go +++ b/x/auth/ante/basic_test.go @@ -168,10 +168,8 @@ func (suite *AnteTestSuite) TestConsumeGasForTxSize() { // require that antehandler passes and does not underestimate decorator cost suite.Require().Nil(err, "ConsumeTxSizeGasDecorator returned error: %v", err) suite.Require().True(consumedSimGas >= expectedGas, "Simulate mode underestimates gas on AnteDecorator. Simulated cost: %d, expected cost: %d", consumedSimGas, expectedGas) - }) } - } func (suite *AnteTestSuite) TestTxHeightTimeoutDecorator() { diff --git a/x/auth/ante/setup.go b/x/auth/ante/setup.go index 6d6d4344c0c3..4e9ffe862b9c 100644 --- a/x/auth/ante/setup.go +++ b/x/auth/ante/setup.go @@ -8,9 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) -var ( - _ GasTx = (*legacytx.StdTx)(nil) // assert StdTx implements GasTx -) +var _ GasTx = (*legacytx.StdTx)(nil) // assert StdTx implements GasTx // GasTx defines a Tx with a GetGas() method which is needed to use SetUpContextDecorator type GasTx interface { diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index c77632a7d020..7363307af12b 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -425,7 +425,6 @@ func ConsumeMultisignatureVerificationGas( meter sdk.GasMeter, sig *signing.MultiSignatureData, pubkey multisig.PubKey, params types.Params, accSeq uint64, ) error { - size := sig.BitArray.Count() sigIndex := 0 diff --git a/x/auth/client/testutil/suite.go b/x/auth/client/testutil/suite.go index 86da20fb8be5..90a02685d8a2 100644 --- a/x/auth/client/testutil/suite.go +++ b/x/auth/client/testutil/suite.go @@ -14,6 +14,7 @@ import ( "github.com/stretchr/testify/suite" tmcli "github.com/tendermint/tendermint/libs/cli" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" @@ -1827,7 +1828,7 @@ func (s *IntegrationTestSuite) createBankMsg(val *network.Validator, toAddr sdk. return bankcli.MsgSendExec(val.ClientCtx, val.Address, toAddr, amount, flags...) } -func (s *IntegrationTestSuite) getBalances(clientCtx client.Context, addr sdk.AccAddress, denom string) sdk.Int { +func (s *IntegrationTestSuite) getBalances(clientCtx client.Context, addr sdk.AccAddress, denom string) math.Int { resp, err := bankcli.QueryBalancesExec(clientCtx, addr) s.Require().NoError(err) diff --git a/x/auth/module.go b/x/auth/module.go index dd68ec62da80..feec8ccaccea 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -219,8 +219,8 @@ func provideModule( config *modulev1.Module, key *store.KVStoreKey, cdc codec.Codec, - subspace paramtypes.Subspace) authOutputs { - + subspace paramtypes.Subspace, +) authOutputs { maccPerms := map[string][]string{} for _, permission := range config.ModuleAccountPermissions { maccPerms[permission.Account] = permission.Permissions diff --git a/x/auth/tx/builder.go b/x/auth/tx/builder.go index 052da8785ee8..ab875867107c 100644 --- a/x/auth/tx/builder.go +++ b/x/auth/tx/builder.go @@ -34,12 +34,12 @@ type wrapper struct { } var ( - _ authsigning.Tx = &wrapper{} - _ client.TxBuilder = &wrapper{} - _ tx.TipTx = &wrapper{} + _ authsigning.Tx = &wrapper{} + _ client.TxBuilder = &wrapper{} + _ tx.TipTx = &wrapper{} _ ante.HasExtensionOptionsTx = &wrapper{} - _ ExtensionOptionsTxBuilder = &wrapper{} - _ tx.TipTx = &wrapper{} + _ ExtensionOptionsTxBuilder = &wrapper{} + _ tx.TipTx = &wrapper{} ) // ExtensionOptionsTxBuilder defines a TxBuilder that can also set extensions. diff --git a/x/authz/module/abci.go b/x/authz/module/abci.go index c9e6fef5e7a6..c1015abae841 100644 --- a/x/authz/module/abci.go +++ b/x/authz/module/abci.go @@ -5,7 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/authz/keeper" ) -// BeginBlocker is called at the begining of every block +// BeginBlocker is called at the beginning of every block func BeginBlocker(ctx sdk.Context, keeper keeper.Keeper) { // delete all the mature grants if err := keeper.DequeueAndDeleteExpiredGrants(ctx); err != nil { diff --git a/x/bank/client/testutil/suite.go b/x/bank/client/testutil/suite.go index 4afad13f5b3c..73201fd5dacb 100644 --- a/x/bank/client/testutil/suite.go +++ b/x/bank/client/testutil/suite.go @@ -5,6 +5,7 @@ import ( "io/ioutil" "os" + "cosmossdk.io/math" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" tmcli "github.com/tendermint/tendermint/libs/cli" @@ -658,7 +659,7 @@ func (s *IntegrationTestSuite) TestNewMultiSendTxCmd() { } } -func NewCoin(denom string, amount sdk.Int) *sdk.Coin { +func NewCoin(denom string, amount math.Int) *sdk.Coin { coin := sdk.NewCoin(denom, amount) return &coin } diff --git a/x/bank/keeper/grpc_query.go b/x/bank/keeper/grpc_query.go index 2afc4c585f70..a4df106ab7cd 100644 --- a/x/bank/keeper/grpc_query.go +++ b/x/bank/keeper/grpc_query.go @@ -3,6 +3,8 @@ package keeper import ( "context" + "cosmossdk.io/math" + "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -60,7 +62,7 @@ func (k BaseKeeper) AllBalances(ctx context.Context, req *types.QueryAllBalances accountStore := k.getAccountStore(sdkCtx, addr) pageRes, err := query.Paginate(accountStore, req.Pagination, func(key, value []byte) error { - var amount sdk.Int + var amount math.Int if err := amount.Unmarshal(value); err != nil { return err } diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index e25d8b809097..c7f308d8c54d 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -3,6 +3,7 @@ package keeper import ( "fmt" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/internal/conv" "github.com/cosmos/cosmos-sdk/store/prefix" @@ -70,7 +71,7 @@ func (k BaseKeeper) GetPaginatedTotalSupply(ctx sdk.Context, pagination *query.P supply := sdk.NewCoins() pageRes, err := query.Paginate(supplyStore, pagination, func(key, value []byte) error { - var amount sdk.Int + var amount math.Int err := amount.Unmarshal(value) if err != nil { return fmt.Errorf("unable to convert amount string to Int %v", err) @@ -228,7 +229,7 @@ func (k BaseKeeper) GetSupply(ctx sdk.Context, denom string) sdk.Coin { } } - var amount sdk.Int + var amount math.Int err := amount.Unmarshal(bz) if err != nil { panic(fmt.Errorf("unable to unmarshal supply value %v", err)) @@ -532,7 +533,7 @@ func (k BaseViewKeeper) IterateTotalSupply(ctx sdk.Context, cb func(sdk.Coin) bo defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - var amount sdk.Int + var amount math.Int err := amount.Unmarshal(iterator.Value()) if err != nil { panic(fmt.Errorf("unable to unmarshal supply value %v", err)) diff --git a/x/bank/keeper/view.go b/x/bank/keeper/view.go index cf66c1962002..5fc3446c2da5 100644 --- a/x/bank/keeper/view.go +++ b/x/bank/keeper/view.go @@ -3,6 +3,7 @@ package keeper import ( "fmt" + "cosmossdk.io/math" "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/codec" @@ -121,7 +122,7 @@ func (k BaseViewKeeper) IterateAccountBalances(ctx sdk.Context, addr sdk.AccAddr defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - var amount sdk.Int + var amount math.Int if err := amount.Unmarshal(iterator.Value()); err != nil { panic(err) } @@ -151,7 +152,7 @@ func (k BaseViewKeeper) IterateAllBalances(ctx sdk.Context, cb func(sdk.AccAddre panic(err) } - var amount sdk.Int + var amount math.Int if err := amount.Unmarshal(iterator.Value()); err != nil { panic(err) } diff --git a/x/bank/module.go b/x/bank/module.go index e8b5266f6ace..687f1a39d55f 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "fmt" + "math/rand" + "time" modulev1 "cosmossdk.io/api/cosmos/bank/module/v1" "github.com/cosmos/cosmos-sdk/depinject" @@ -11,9 +13,6 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/tendermint/tendermint/crypto" - "math/rand" - "time" - "cosmossdk.io/core/appmodule" gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index 8800d2d79eca..6c5d9be5a673 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -12,7 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) diff --git a/x/gov/keeper/querier.go b/x/gov/keeper/querier.go index 14e8bc83b2b4..d528f33cf7ec 100644 --- a/x/gov/keeper/querier.go +++ b/x/gov/keeper/querier.go @@ -75,7 +75,6 @@ func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper K } } -// nolint: unparam func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -96,7 +95,6 @@ func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryDepositParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -113,7 +111,6 @@ func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryVoteParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -130,7 +127,6 @@ func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Kee return bz, nil } -// nolint: unparam func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -151,7 +147,6 @@ func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -188,7 +183,6 @@ func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke return bz, nil } -// nolint: unparam func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalVotesParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) diff --git a/x/gov/migrations/v046/convert.go b/x/gov/migrations/v046/convert.go index a3f383006b5c..54ff7d4911ad 100644 --- a/x/gov/migrations/v046/convert.go +++ b/x/gov/migrations/v046/convert.go @@ -6,7 +6,7 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) diff --git a/x/gov/types/expected_keepers.go b/x/gov/types/expected_keepers.go index a6e521647f31..556387c62ac4 100644 --- a/x/gov/types/expected_keepers.go +++ b/x/gov/types/expected_keepers.go @@ -1,6 +1,7 @@ package types import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -19,7 +20,7 @@ type StakingKeeper interface { sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool), ) - TotalBondedTokens(sdk.Context) sdk.Int // total bonded tokens within the validator set + TotalBondedTokens(sdk.Context) math.Int // total bonded tokens within the validator set IterateDelegations( ctx sdk.Context, delegator sdk.AccAddress, fn func(index int64, delegation stakingtypes.DelegationI) (stop bool), diff --git a/x/gov/types/v1/proposal.go b/x/gov/types/v1/proposal.go index 63982fef0432..cb04be0d45a5 100644 --- a/x/gov/types/v1/proposal.go +++ b/x/gov/types/v1/proposal.go @@ -106,7 +106,7 @@ func (status *ProposalStatus) Unmarshal(data []byte) error { } // Format implements the fmt.Formatter interface. -// nolint: errcheck + func (status ProposalStatus) Format(s fmt.State, verb rune) { switch verb { case 's': diff --git a/x/gov/types/v1/tally.go b/x/gov/types/v1/tally.go index 6613f640f6e5..7a09625737ce 100644 --- a/x/gov/types/v1/tally.go +++ b/x/gov/types/v1/tally.go @@ -1,20 +1,21 @@ package v1 import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ) // ValidatorGovInfo used for tallying type ValidatorGovInfo struct { Address sdk.ValAddress // address of the validator operator - BondedTokens sdk.Int // Power of a Validator + BondedTokens math.Int // Power of a Validator DelegatorShares sdk.Dec // Total outstanding delegator shares DelegatorDeductions sdk.Dec // Delegator deductions from validator's delegators voting independently Vote WeightedVoteOptions // Vote of the validator } // NewValidatorGovInfo creates a ValidatorGovInfo instance -func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegatorShares, +func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens math.Int, delegatorShares, delegatorDeductions sdk.Dec, options WeightedVoteOptions, ) ValidatorGovInfo { return ValidatorGovInfo{ @@ -27,7 +28,7 @@ func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegator } // NewTallyResult creates a new TallyResult instance -func NewTallyResult(yes, abstain, no, noWithVeto sdk.Int) TallyResult { +func NewTallyResult(yes, abstain, no, noWithVeto math.Int) TallyResult { return TallyResult{ YesCount: yes.String(), AbstainCount: abstain.String(), diff --git a/x/gov/types/v1beta1/proposal.go b/x/gov/types/v1beta1/proposal.go index 6946a40216c4..09b6db0041e5 100644 --- a/x/gov/types/v1beta1/proposal.go +++ b/x/gov/types/v1beta1/proposal.go @@ -149,7 +149,7 @@ func (status *ProposalStatus) Unmarshal(data []byte) error { } // Format implements the fmt.Formatter interface. -// nolint: errcheck + func (status ProposalStatus) Format(s fmt.State, verb rune) { switch verb { case 's': diff --git a/x/gov/types/v1beta1/proposals_test.go b/x/gov/types/v1beta1/proposals_test.go index 2a29fda28753..6f3bee6092f6 100644 --- a/x/gov/types/v1beta1/proposals_test.go +++ b/x/gov/types/v1beta1/proposals_test.go @@ -54,5 +54,4 @@ func TestContentFromProposalType(t *testing.T) { require.NotNil(t, content) require.Equal(t, test.expectedType, content.ProposalType()) } - } diff --git a/x/gov/types/v1beta1/tally.go b/x/gov/types/v1beta1/tally.go index 616ca6b7bb7c..cf44f59b6c69 100644 --- a/x/gov/types/v1beta1/tally.go +++ b/x/gov/types/v1beta1/tally.go @@ -1,6 +1,7 @@ package v1beta1 import ( + "cosmossdk.io/math" "sigs.k8s.io/yaml" sdk "github.com/cosmos/cosmos-sdk/types" @@ -9,14 +10,14 @@ import ( // ValidatorGovInfo used for tallying type ValidatorGovInfo struct { Address sdk.ValAddress // address of the validator operator - BondedTokens sdk.Int // Power of a Validator + BondedTokens math.Int // Power of a Validator DelegatorShares sdk.Dec // Total outstanding delegator shares DelegatorDeductions sdk.Dec // Delegator deductions from validator's delegators voting independently Vote WeightedVoteOptions // Vote of the validator } // NewValidatorGovInfo creates a ValidatorGovInfo instance -func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegatorShares, +func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens math.Int, delegatorShares, delegatorDeductions sdk.Dec, options WeightedVoteOptions, ) ValidatorGovInfo { return ValidatorGovInfo{ @@ -29,7 +30,7 @@ func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegator } // NewTallyResult creates a new TallyResult instance -func NewTallyResult(yes, abstain, no, noWithVeto sdk.Int) TallyResult { +func NewTallyResult(yes, abstain, no, noWithVeto math.Int) TallyResult { return TallyResult{ Yes: yes, Abstain: abstain, diff --git a/x/group/client/testutil/tx.go b/x/group/client/testutil/tx.go index 1458dc4fd338..879c7baef22c 100644 --- a/x/group/client/testutil/tx.go +++ b/x/group/client/testutil/tx.go @@ -213,7 +213,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroup() { val := s.network.Validators[0] clientCtx := val.ClientCtx - validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "1", @@ -366,7 +365,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupAdmin() { clientCtx := val.ClientCtx require := s.Require() - groupIDs := make([]string, 2) for i := 0; i < 2; i++ { validMembers := fmt.Sprintf(`{"members": [{ @@ -487,7 +485,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupMetadata() { val := s.network.Validators[0] clientCtx := val.ClientCtx - testCases := []struct { name string args []string @@ -568,7 +565,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupMembers() { val := s.network.Validators[0] clientCtx := val.ClientCtx - weights := []string{"1", "1", "1"} accounts := s.createAccounts(3) @@ -691,9 +687,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroupWithPolicy() { val := s.network.Validators[0] clientCtx := val.ClientCtx - - - validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "1", @@ -899,7 +892,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroupPolicy() { wrongAdmin := s.network.Validators[1].Address clientCtx := val.ClientCtx - groupID := s.group.Id testCases := []struct { @@ -1067,7 +1059,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyAdmin() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[3] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1168,7 +1159,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[2] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1314,7 +1304,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyMetadata() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[2] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1428,7 +1417,6 @@ func (s *IntegrationTestSuite) TestTxSubmitProposal() { val := s.network.Validators[0] clientCtx := val.ClientCtx - testCases := []struct { name string args []string @@ -1617,7 +1605,6 @@ func (s *IntegrationTestSuite) TestTxVote() { val := s.network.Validators[0] clientCtx := val.ClientCtx - ids := make([]string, 4) weights := []string{"1", "1", "1"} accounts := s.createAccounts(3) @@ -1811,7 +1798,6 @@ func (s *IntegrationTestSuite) TestTxWithdrawProposal() { val := s.network.Validators[0] clientCtx := val.ClientCtx - ids := make([]string, 2) for i := 0; i < 2; i++ { @@ -1954,7 +1940,6 @@ func (s *IntegrationTestSuite) TestTxExec() { clientCtx := val.ClientCtx require := s.Require() - var proposalIDs []string // create proposals and vote for i := 0; i < 2; i++ { @@ -2428,10 +2413,8 @@ func (s *IntegrationTestSuite) TestExecProposalsWhenMemberLeavesOrIsUpdated() { if tc.expectLogErr { s.Require().Contains(execResp.RawLog, tc.errMsg) } - }) } - } func (s *IntegrationTestSuite) getGroupIDFromTxResponse(txResp sdk.TxResponse) string { @@ -2551,7 +2534,7 @@ func (s *IntegrationTestSuite) createGroupThresholdPolicyWithBalance(adminAddres s.commonFlags..., ), ) - var txResp = sdk.TxResponse{} + txResp := sdk.TxResponse{} s.Require().NoError(err, out.String()) s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) s.Require().Equal(uint32(0), txResp.Code, out.String()) diff --git a/x/group/keeper/keeper_test.go b/x/group/keeper/keeper_test.go index 84ee34bcdf81..c82ad1b1e49b 100644 --- a/x/group/keeper/keeper_test.go +++ b/x/group/keeper/keeper_test.go @@ -2829,7 +2829,6 @@ func (s *TestSuite) TestLeaveGroup() { } } - func (s *TestSuite) TestPruneProposals() { addrs := s.addrs expirationTime := time.Hour * 24 * 15 // 15 days diff --git a/x/group/keeper/msg_server.go b/x/group/keeper/msg_server.go index 6a25c5dce3f1..b732e958cab6 100644 --- a/x/group/keeper/msg_server.go +++ b/x/group/keeper/msg_server.go @@ -161,7 +161,7 @@ func (k Keeper) UpdateGroupMembers(goCtx context.Context, req *group.MsgUpdateGr if err != nil { return err } - // Substract previous weight from the group total weight. + // Subtract previous weight from the group total weight. totalWeight, err = math.SubNonNegative(totalWeight, previousMemberWeight) if err != nil { return err diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index fd064ff7b4d6..51ade6abef63 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -1,6 +1,7 @@ package keeper import ( + "cosmossdk.io/math" "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/codec" @@ -83,7 +84,7 @@ func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { // StakingTokenSupply implements an alias call to the underlying staking keeper's // StakingTokenSupply to be used in BeginBlocker. -func (k Keeper) StakingTokenSupply(ctx sdk.Context) sdk.Int { +func (k Keeper) StakingTokenSupply(ctx sdk.Context) math.Int { return k.stakingKeeper.StakingTokenSupply(ctx) } diff --git a/x/mint/types/expected_keepers.go b/x/mint/types/expected_keepers.go index 85b6d776c5c5..68fb5765bf6d 100644 --- a/x/mint/types/expected_keepers.go +++ b/x/mint/types/expected_keepers.go @@ -1,13 +1,14 @@ package types // noalias import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" ) // StakingKeeper defines the expected staking keeper type StakingKeeper interface { - StakingTokenSupply(ctx sdk.Context) sdk.Int + StakingTokenSupply(ctx sdk.Context) math.Int BondedRatio(ctx sdk.Context) sdk.Dec } diff --git a/x/mint/types/minter.go b/x/mint/types/minter.go index 3285d6ddf0e8..8f2353217536 100644 --- a/x/mint/types/minter.go +++ b/x/mint/types/minter.go @@ -3,6 +3,8 @@ package types import ( "fmt" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -68,7 +70,7 @@ func (m Minter) NextInflationRate(params Params, bondedRatio sdk.Dec) sdk.Dec { // NextAnnualProvisions returns the annual provisions based on current total // supply and inflation rate. -func (m Minter) NextAnnualProvisions(_ Params, totalSupply sdk.Int) sdk.Dec { +func (m Minter) NextAnnualProvisions(_ Params, totalSupply math.Int) sdk.Dec { return m.Inflation.MulInt(totalSupply) } diff --git a/x/params/module.go b/x/params/module.go index 6df8b234d3df..87c463883bc6 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -174,7 +174,6 @@ func provideModule( cdc codec.Codec, amino *codec.LegacyAmino, ) (keeper.Keeper, runtime.AppModuleWrapper, runtime.BaseAppOption) { - k := keeper.NewKeeper(cdc, amino, kvStoreKey, transientStoreKey) m := NewAppModule(k) baseappOpt := func(app *baseapp.BaseApp) { diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index cd792659bd15..973f6d0fbd4a 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -319,7 +319,6 @@ Comment: %s`, } } -// nolint: errcheck func runQueuedOperations(queueOps map[int][]simulation.Operation, height int, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account, logWriter LogWriter, diff --git a/x/slashing/types/expected_keepers.go b/x/slashing/types/expected_keepers.go index 5f9a4fee8c72..9e15820dc418 100644 --- a/x/slashing/types/expected_keepers.go +++ b/x/slashing/types/expected_keepers.go @@ -3,6 +3,7 @@ package types import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" auth "github.com/cosmos/cosmos-sdk/x/auth/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" @@ -42,7 +43,7 @@ type StakingKeeper interface { ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI // get a particular validator by consensus address // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction - Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) sdk.Int + Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) math.Int Jail(sdk.Context, sdk.ConsAddress) // jail a validator Unjail(sdk.Context, sdk.ConsAddress) // unjail a validator diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 6426df2f31fe..b70b0b120700 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -6,6 +6,8 @@ import ( "strconv" "strings" + "cosmossdk.io/math" + "github.com/spf13/cobra" flag "github.com/spf13/pflag" @@ -121,7 +123,7 @@ func NewEditValidatorCmd() *cobra.Command { newRate = &rate } - var newMinSelfDelegation *sdk.Int + var newMinSelfDelegation *math.Int minSelfDelegationString, _ := cmd.Flags().GetString(FlagMinSelfDelegation) if minSelfDelegationString != "" { diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 4c99e4adaedb..51eb0e17d062 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -5,6 +5,7 @@ import ( "fmt" "time" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -186,7 +187,7 @@ func (k Keeper) IterateUnbondingDelegations(ctx sdk.Context, fn func(index int64 } // GetDelegatorUnbonding returns the total amount a delegator has unbonding. -func (k Keeper) GetDelegatorUnbonding(ctx sdk.Context, delegator sdk.AccAddress) sdk.Int { +func (k Keeper) GetDelegatorUnbonding(ctx sdk.Context, delegator sdk.AccAddress) math.Int { unbonding := sdk.ZeroInt() k.IterateDelegatorUnbondingDelegations(ctx, delegator, func(ubd types.UnbondingDelegation) bool { for _, entry := range ubd.Entries { @@ -213,7 +214,7 @@ func (k Keeper) IterateDelegatorUnbondingDelegations(ctx sdk.Context, delegator } // GetDelegatorBonded returs the total amount a delegator has bonded. -func (k Keeper) GetDelegatorBonded(ctx sdk.Context, delegator sdk.AccAddress) sdk.Int { +func (k Keeper) GetDelegatorBonded(ctx sdk.Context, delegator sdk.AccAddress) math.Int { bonded := sdk.ZeroDec() k.IterateDelegatorDelegations(ctx, delegator, func(delegation types.Delegation) bool { @@ -311,7 +312,7 @@ func (k Keeper) RemoveUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDe // the given addresses. It creates the unbonding delegation if it does not exist. func (k Keeper) SetUnbondingDelegationEntry( ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, - creationHeight int64, minTime time.Time, balance sdk.Int, + creationHeight int64, minTime time.Time, balance math.Int, ) types.UnbondingDelegation { ubd, found := k.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr) if found { @@ -496,7 +497,7 @@ func (k Keeper) SetRedelegation(ctx sdk.Context, red types.Redelegation) { func (k Keeper) SetRedelegationEntry(ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress, creationHeight int64, - minTime time.Time, balance sdk.Int, + minTime time.Time, balance math.Int, sharesSrc, sharesDst sdk.Dec, ) types.Redelegation { red, found := k.GetRedelegation(ctx, delegatorAddr, validatorSrcAddr, validatorDstAddr) @@ -626,7 +627,7 @@ func (k Keeper) DequeueAllMatureRedelegationQueue(ctx sdk.Context, currTime time // Delegate performs a delegation, set/update everything necessary within the store. // tokenSrc indicates the bond status of the incoming funds. func (k Keeper) Delegate( - ctx sdk.Context, delAddr sdk.AccAddress, bondAmt sdk.Int, tokenSrc types.BondStatus, + ctx sdk.Context, delAddr sdk.AccAddress, bondAmt math.Int, tokenSrc types.BondStatus, validator types.Validator, subtractAccount bool, ) (newShares sdk.Dec, err error) { // In some situations, the exchange rate becomes invalid, e.g. if @@ -716,7 +717,7 @@ func (k Keeper) Delegate( // Unbond unbonds a particular delegation and perform associated store operations. func (k Keeper) Unbond( ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, shares sdk.Dec, -) (amount sdk.Int, err error) { +) (amount math.Int, err error) { // check if a delegation object exists in the store delegation, found := k.GetDelegation(ctx, delAddr, valAddr) if !found { @@ -991,7 +992,7 @@ func (k Keeper) CompleteRedelegation( // valied based on upon the converted shares. If the amount is valid, the total // amount of respective shares is returned, otherwise an error is returned. func (k Keeper) ValidateUnbondAmount( - ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amt sdk.Int, + ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amt math.Int, ) (shares sdk.Dec, err error) { validator, found := k.GetValidator(ctx, valAddr) if !found { diff --git a/x/staking/keeper/params.go b/x/staking/keeper/params.go index 498576fea53f..7e816f353143 100644 --- a/x/staking/keeper/params.go +++ b/x/staking/keeper/params.go @@ -3,6 +3,8 @@ package keeper import ( "time" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -43,7 +45,7 @@ func (k Keeper) BondDenom(ctx sdk.Context) (res string) { // Currently, this returns a global variable that the app developer can tweak. // TODO: we might turn this into an on-chain param: // https://github.com/cosmos/cosmos-sdk/issues/8365 -func (k Keeper) PowerReduction(ctx sdk.Context) sdk.Int { +func (k Keeper) PowerReduction(ctx sdk.Context) math.Int { return sdk.DefaultPowerReduction } diff --git a/x/staking/keeper/pool.go b/x/staking/keeper/pool.go index b281b45784dc..06d87422da44 100644 --- a/x/staking/keeper/pool.go +++ b/x/staking/keeper/pool.go @@ -1,6 +1,7 @@ package keeper import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -17,7 +18,7 @@ func (k Keeper) GetNotBondedPool(ctx sdk.Context) (notBondedPool authtypes.Modul } // bondedTokensToNotBonded transfers coins from the bonded to the not bonded pool within staking -func (k Keeper) bondedTokensToNotBonded(ctx sdk.Context, tokens sdk.Int) { +func (k Keeper) bondedTokensToNotBonded(ctx sdk.Context, tokens math.Int) { coins := sdk.NewCoins(sdk.NewCoin(k.BondDenom(ctx), tokens)) if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.BondedPoolName, types.NotBondedPoolName, coins); err != nil { panic(err) @@ -25,7 +26,7 @@ func (k Keeper) bondedTokensToNotBonded(ctx sdk.Context, tokens sdk.Int) { } // notBondedTokensToBonded transfers coins from the not bonded to the bonded pool within staking -func (k Keeper) notBondedTokensToBonded(ctx sdk.Context, tokens sdk.Int) { +func (k Keeper) notBondedTokensToBonded(ctx sdk.Context, tokens math.Int) { coins := sdk.NewCoins(sdk.NewCoin(k.BondDenom(ctx), tokens)) if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.NotBondedPoolName, types.BondedPoolName, coins); err != nil { panic(err) @@ -33,7 +34,7 @@ func (k Keeper) notBondedTokensToBonded(ctx sdk.Context, tokens sdk.Int) { } // burnBondedTokens removes coins from the bonded pool module account -func (k Keeper) burnBondedTokens(ctx sdk.Context, amt sdk.Int) error { +func (k Keeper) burnBondedTokens(ctx sdk.Context, amt math.Int) error { if !amt.IsPositive() { // skip as no coins need to be burned return nil @@ -45,7 +46,7 @@ func (k Keeper) burnBondedTokens(ctx sdk.Context, amt sdk.Int) error { } // burnNotBondedTokens removes coins from the not bonded pool module account -func (k Keeper) burnNotBondedTokens(ctx sdk.Context, amt sdk.Int) error { +func (k Keeper) burnNotBondedTokens(ctx sdk.Context, amt math.Int) error { if !amt.IsPositive() { // skip as no coins need to be burned return nil @@ -57,13 +58,13 @@ func (k Keeper) burnNotBondedTokens(ctx sdk.Context, amt sdk.Int) error { } // TotalBondedTokens total staking tokens supply which is bonded -func (k Keeper) TotalBondedTokens(ctx sdk.Context) sdk.Int { +func (k Keeper) TotalBondedTokens(ctx sdk.Context) math.Int { bondedPool := k.GetBondedPool(ctx) return k.bankKeeper.GetBalance(ctx, bondedPool.GetAddress(), k.BondDenom(ctx)).Amount } // StakingTokenSupply staking tokens from the total supply -func (k Keeper) StakingTokenSupply(ctx sdk.Context) sdk.Int { +func (k Keeper) StakingTokenSupply(ctx sdk.Context) math.Int { return k.bankKeeper.GetSupply(ctx, k.BondDenom(ctx)).Amount } diff --git a/x/staking/keeper/power_reduction.go b/x/staking/keeper/power_reduction.go index d979228b36fa..abed52d12f4c 100644 --- a/x/staking/keeper/power_reduction.go +++ b/x/staking/keeper/power_reduction.go @@ -1,15 +1,16 @@ package keeper import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ) // TokensToConsensusPower - convert input tokens to potential consensus-engine power -func (k Keeper) TokensToConsensusPower(ctx sdk.Context, tokens sdk.Int) int64 { +func (k Keeper) TokensToConsensusPower(ctx sdk.Context, tokens math.Int) int64 { return sdk.TokensToConsensusPower(tokens, k.PowerReduction(ctx)) } // TokensFromConsensusPower - convert input power to tokens -func (k Keeper) TokensFromConsensusPower(ctx sdk.Context, power int64) sdk.Int { +func (k Keeper) TokensFromConsensusPower(ctx sdk.Context, power int64) math.Int { return sdk.TokensFromConsensusPower(power, k.PowerReduction(ctx)) } diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index d09fb56c270f..ff2ace8f8627 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -3,6 +3,8 @@ package keeper import ( "fmt" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" types "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -21,7 +23,7 @@ import ( // CONTRACT: // Infraction was committed at the current height or at a past height, // not at a height in the future -func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeight int64, power int64, slashFactor sdk.Dec) sdk.Int { +func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeight int64, power int64, slashFactor sdk.Dec) math.Int { logger := k.Logger(ctx) if slashFactor.IsNegative() { @@ -166,7 +168,7 @@ func (k Keeper) Unjail(ctx sdk.Context, consAddr sdk.ConsAddress) { // insufficient stake remaining) func (k Keeper) SlashUnbondingDelegation(ctx sdk.Context, unbondingDelegation types.UnbondingDelegation, infractionHeight int64, slashFactor sdk.Dec, -) (totalSlashAmount sdk.Int) { +) (totalSlashAmount math.Int) { now := ctx.BlockHeader().Time totalSlashAmount = sdk.ZeroInt() burnedAmount := sdk.ZeroInt() @@ -220,7 +222,7 @@ func (k Keeper) SlashUnbondingDelegation(ctx sdk.Context, unbondingDelegation ty // NOTE this is only slashing for prior infractions from the source validator func (k Keeper) SlashRedelegation(ctx sdk.Context, srcValidator types.Validator, redelegation types.Redelegation, infractionHeight int64, slashFactor sdk.Dec, -) (totalSlashAmount sdk.Int) { +) (totalSlashAmount math.Int) { now := ctx.BlockHeader().Time totalSlashAmount = sdk.ZeroInt() bondedBurnedAmount, notBondedBurnedAmount := sdk.ZeroInt(), sdk.ZeroInt() diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index 9b51577c5a06..556280575e86 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -6,6 +6,7 @@ import ( gogotypes "github.com/gogo/protobuf/types" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -96,7 +97,7 @@ func (k Keeper) SetNewValidatorByPowerIndex(ctx sdk.Context, validator types.Val // Update the tokens of an existing validator, update the validators power index key func (k Keeper) AddValidatorTokensAndShares(ctx sdk.Context, validator types.Validator, - tokensToAdd sdk.Int, + tokensToAdd math.Int, ) (valOut types.Validator, addedShares sdk.Dec) { k.DeleteValidatorByPowerIndex(ctx, validator) validator, addedShares = validator.AddTokensFromDel(tokensToAdd) @@ -109,7 +110,7 @@ func (k Keeper) AddValidatorTokensAndShares(ctx sdk.Context, validator types.Val // Update the tokens of an existing validator, update the validators power index key func (k Keeper) RemoveValidatorTokensAndShares(ctx sdk.Context, validator types.Validator, sharesToRemove sdk.Dec, -) (valOut types.Validator, removedTokens sdk.Int) { +) (valOut types.Validator, removedTokens math.Int) { k.DeleteValidatorByPowerIndex(ctx, validator) validator, removedTokens = validator.RemoveDelShares(sharesToRemove) k.SetValidator(ctx, validator) @@ -120,7 +121,7 @@ func (k Keeper) RemoveValidatorTokensAndShares(ctx sdk.Context, validator types. // Update the tokens of an existing validator, update the validators power index key func (k Keeper) RemoveValidatorTokens(ctx sdk.Context, - validator types.Validator, tokensToRemove sdk.Int, + validator types.Validator, tokensToRemove math.Int, ) types.Validator { k.DeleteValidatorByPowerIndex(ctx, validator) validator = validator.RemoveTokens(tokensToRemove) diff --git a/x/staking/teststaking/helper.go b/x/staking/teststaking/helper.go index e6bf1d1dcc8f..b5457ea01eb7 100644 --- a/x/staking/teststaking/helper.go +++ b/x/staking/teststaking/helper.go @@ -5,6 +5,7 @@ import ( "testing" "time" + "cosmossdk.io/math" "github.com/stretchr/testify/require" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -33,14 +34,14 @@ func NewHelper(t *testing.T, ctx sdk.Context, k *keeper.Keeper) *Helper { } // CreateValidator calls staking module `MsgServer/CreateValidator` to create a new validator -func (sh *Helper) CreateValidator(addr sdk.ValAddress, pk cryptotypes.PubKey, stakeAmount sdk.Int, ok bool) { +func (sh *Helper) CreateValidator(addr sdk.ValAddress, pk cryptotypes.PubKey, stakeAmount math.Int, ok bool) { coin := sdk.NewCoin(sh.Denom, stakeAmount) sh.createValidator(addr, pk, coin, ok) } // CreateValidatorWithValPower calls staking module `MsgServer/CreateValidator` to create a new validator with zero // commission -func (sh *Helper) CreateValidatorWithValPower(addr sdk.ValAddress, pk cryptotypes.PubKey, valPower int64, ok bool) sdk.Int { +func (sh *Helper) CreateValidatorWithValPower(addr sdk.ValAddress, pk cryptotypes.PubKey, valPower int64, ok bool) math.Int { amount := sh.k.TokensFromConsensusPower(sh.Ctx, valPower) coin := sdk.NewCoin(sh.Denom, amount) sh.createValidator(addr, pk, coin, ok) @@ -48,7 +49,7 @@ func (sh *Helper) CreateValidatorWithValPower(addr sdk.ValAddress, pk cryptotype } // CreateValidatorMsg returns a message used to create validator in this service. -func (sh *Helper) CreateValidatorMsg(addr sdk.ValAddress, pk cryptotypes.PubKey, stakeAmount sdk.Int) *stakingtypes.MsgCreateValidator { +func (sh *Helper) CreateValidatorMsg(addr sdk.ValAddress, pk cryptotypes.PubKey, stakeAmount math.Int) *stakingtypes.MsgCreateValidator { coin := sdk.NewCoin(sh.Denom, stakeAmount) msg, err := stakingtypes.NewMsgCreateValidator(addr, pk, coin, stakingtypes.Description{}, sh.Commission, sdk.OneInt()) require.NoError(sh.t, err) @@ -74,7 +75,7 @@ func (sh *Helper) createValidator(addr sdk.ValAddress, pk cryptotypes.PubKey, co } // Delegate calls staking module staking module `MsgServer/Delegate` to delegate stake for a validator -func (sh *Helper) Delegate(delegator sdk.AccAddress, val sdk.ValAddress, amount sdk.Int) { +func (sh *Helper) Delegate(delegator sdk.AccAddress, val sdk.ValAddress, amount math.Int) { coin := sdk.NewCoin(sh.Denom, amount) msg := stakingtypes.NewMsgDelegate(delegator, val, coin) res, err := sh.msgSrvr.Delegate(sdk.WrapSDKContext(sh.Ctx), msg) @@ -92,7 +93,7 @@ func (sh *Helper) DelegateWithPower(delegator sdk.AccAddress, val sdk.ValAddress } // Undelegate calls staking module `MsgServer/Undelegate` to unbound some stake from a validator. -func (sh *Helper) Undelegate(delegator sdk.AccAddress, val sdk.ValAddress, amount sdk.Int, ok bool) { +func (sh *Helper) Undelegate(delegator sdk.AccAddress, val sdk.ValAddress, amount math.Int, ok bool) { unbondAmt := sdk.NewCoin(sh.Denom, amount) msg := stakingtypes.NewMsgUndelegate(delegator, val, unbondAmt) res, err := sh.msgSrvr.Undelegate(sdk.WrapSDKContext(sh.Ctx), msg) diff --git a/x/staking/teststaking/tm.go b/x/staking/teststaking/tm.go index e927c0e0387a..2d1ee1beee89 100644 --- a/x/staking/teststaking/tm.go +++ b/x/staking/teststaking/tm.go @@ -1,11 +1,11 @@ package teststaking import ( + "cosmossdk.io/math" tmcrypto "github.com/tendermint/tendermint/crypto" tmtypes "github.com/tendermint/tendermint/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -20,7 +20,7 @@ func GetTmConsPubKey(v types.Validator) (tmcrypto.PubKey, error) { } // ToTmValidator casts an SDK validator to a tendermint type Validator. -func ToTmValidator(v types.Validator, r sdk.Int) (*tmtypes.Validator, error) { +func ToTmValidator(v types.Validator, r math.Int) (*tmtypes.Validator, error) { tmPk, err := GetTmConsPubKey(v) if err != nil { return nil, err @@ -30,7 +30,7 @@ func ToTmValidator(v types.Validator, r sdk.Int) (*tmtypes.Validator, error) { } // ToTmValidators casts all validators to the corresponding tendermint type. -func ToTmValidators(v types.Validators, r sdk.Int) ([]*tmtypes.Validator, error) { +func ToTmValidators(v types.Validators, r math.Int) ([]*tmtypes.Validator, error) { validators := make([]*tmtypes.Validator, len(v)) var err error for i, val := range v { diff --git a/x/staking/types/delegation.go b/x/staking/types/delegation.go index 07438c4f40af..d644ee8047ad 100644 --- a/x/staking/types/delegation.go +++ b/x/staking/types/delegation.go @@ -6,10 +6,10 @@ import ( "strings" "time" - "sigs.k8s.io/yaml" - + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "sigs.k8s.io/yaml" ) // Implements Delegation interface @@ -93,7 +93,7 @@ func (d Delegations) String() (out string) { return strings.TrimSpace(out) } -func NewUnbondingDelegationEntry(creationHeight int64, completionTime time.Time, balance sdk.Int) UnbondingDelegationEntry { +func NewUnbondingDelegationEntry(creationHeight int64, completionTime time.Time, balance math.Int) UnbondingDelegationEntry { return UnbondingDelegationEntry{ CreationHeight: creationHeight, CompletionTime: completionTime, @@ -117,7 +117,7 @@ func (e UnbondingDelegationEntry) IsMature(currentTime time.Time) bool { //nolint:interfacer func NewUnbondingDelegation( delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, - creationHeight int64, minTime time.Time, balance sdk.Int, + creationHeight int64, minTime time.Time, balance math.Int, ) UnbondingDelegation { return UnbondingDelegation{ DelegatorAddress: delegatorAddr.String(), @@ -129,7 +129,7 @@ func NewUnbondingDelegation( } // AddEntry - append entry to the unbonding delegation -func (ubd *UnbondingDelegation) AddEntry(creationHeight int64, minTime time.Time, balance sdk.Int) { +func (ubd *UnbondingDelegation) AddEntry(creationHeight int64, minTime time.Time, balance math.Int) { entry := NewUnbondingDelegationEntry(creationHeight, minTime, balance) ubd.Entries = append(ubd.Entries, entry) } @@ -188,7 +188,7 @@ func (ubds UnbondingDelegations) String() (out string) { return strings.TrimSpace(out) } -func NewRedelegationEntry(creationHeight int64, completionTime time.Time, balance sdk.Int, sharesDst sdk.Dec) RedelegationEntry { +func NewRedelegationEntry(creationHeight int64, completionTime time.Time, balance math.Int, sharesDst sdk.Dec) RedelegationEntry { return RedelegationEntry{ CreationHeight: creationHeight, CompletionTime: completionTime, @@ -211,7 +211,7 @@ func (e RedelegationEntry) IsMature(currentTime time.Time) bool { //nolint:interfacer func NewRedelegation( delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress, - creationHeight int64, minTime time.Time, balance sdk.Int, sharesDst sdk.Dec, + creationHeight int64, minTime time.Time, balance math.Int, sharesDst sdk.Dec, ) Redelegation { return Redelegation{ DelegatorAddress: delegatorAddr.String(), @@ -224,7 +224,7 @@ func NewRedelegation( } // AddEntry - append entry to the unbonding delegation -func (red *Redelegation) AddEntry(creationHeight int64, minTime time.Time, balance sdk.Int, sharesDst sdk.Dec) { +func (red *Redelegation) AddEntry(creationHeight int64, minTime time.Time, balance math.Int, sharesDst sdk.Dec) { entry := NewRedelegationEntry(creationHeight, minTime, balance, sharesDst) red.Entries = append(red.Entries, entry) } @@ -351,7 +351,7 @@ func NewRedelegationResponse( // NewRedelegationEntryResponse creates a new RedelegationEntryResponse instance. func NewRedelegationEntryResponse( - creationHeight int64, completionTime time.Time, sharesDst sdk.Dec, initialBalance, balance sdk.Int, + creationHeight int64, completionTime time.Time, sharesDst sdk.Dec, initialBalance, balance math.Int, ) RedelegationEntryResponse { return RedelegationEntryResponse{ RedelegationEntry: NewRedelegationEntry(creationHeight, completionTime, initialBalance, sharesDst), diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index 785a969f36e4..4eb85458179b 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -1,6 +1,7 @@ package types import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -55,11 +56,11 @@ type ValidatorSet interface { Validator(sdk.Context, sdk.ValAddress) ValidatorI // get a particular validator by operator address ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) ValidatorI // get a particular validator by consensus address - TotalBondedTokens(sdk.Context) sdk.Int // total bonded tokens within the validator set - StakingTokenSupply(sdk.Context) sdk.Int // total staking token supply + TotalBondedTokens(sdk.Context) math.Int // total bonded tokens within the validator set + StakingTokenSupply(sdk.Context) math.Int // total staking token supply // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction - Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) sdk.Int + Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) math.Int Jail(sdk.Context, sdk.ConsAddress) // jail a validator Unjail(sdk.Context, sdk.ConsAddress) // unjail a validator diff --git a/x/staking/types/exported.go b/x/staking/types/exported.go index 9599da100d20..60e16e55d7fc 100644 --- a/x/staking/types/exported.go +++ b/x/staking/types/exported.go @@ -1,6 +1,7 @@ package types import ( + "cosmossdk.io/math" tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -16,25 +17,25 @@ type DelegationI interface { // ValidatorI expected validator functions type ValidatorI interface { - IsJailed() bool // whether the validator is jailed - GetMoniker() string // moniker of the validator - GetStatus() BondStatus // status of the validator - IsBonded() bool // check if has a bonded status - IsUnbonded() bool // check if has status unbonded - IsUnbonding() bool // check if has status unbonding - GetOperator() sdk.ValAddress // operator address to receive/return validators coins - ConsPubKey() (cryptotypes.PubKey, error) // validation consensus pubkey (cryptotypes.PubKey) - TmConsPublicKey() (tmprotocrypto.PublicKey, error) // validation consensus pubkey (Tendermint) - GetConsAddr() (sdk.ConsAddress, error) // validation consensus address - GetTokens() sdk.Int // validation tokens - GetBondedTokens() sdk.Int // validator bonded tokens - GetConsensusPower(sdk.Int) int64 // validation power in tendermint - GetCommission() sdk.Dec // validator commission rate - GetMinSelfDelegation() sdk.Int // validator minimum self delegation - GetDelegatorShares() sdk.Dec // total outstanding delegator shares - TokensFromShares(sdk.Dec) sdk.Dec // token worth of provided delegator shares - TokensFromSharesTruncated(sdk.Dec) sdk.Dec // token worth of provided delegator shares, truncated - TokensFromSharesRoundUp(sdk.Dec) sdk.Dec // token worth of provided delegator shares, rounded up - SharesFromTokens(amt sdk.Int) (sdk.Dec, error) // shares worth of delegator's bond - SharesFromTokensTruncated(amt sdk.Int) (sdk.Dec, error) // truncated shares worth of delegator's bond + IsJailed() bool // whether the validator is jailed + GetMoniker() string // moniker of the validator + GetStatus() BondStatus // status of the validator + IsBonded() bool // check if has a bonded status + IsUnbonded() bool // check if has status unbonded + IsUnbonding() bool // check if has status unbonding + GetOperator() sdk.ValAddress // operator address to receive/return validators coins + ConsPubKey() (cryptotypes.PubKey, error) // validation consensus pubkey (cryptotypes.PubKey) + TmConsPublicKey() (tmprotocrypto.PublicKey, error) // validation consensus pubkey (Tendermint) + GetConsAddr() (sdk.ConsAddress, error) // validation consensus address + GetTokens() math.Int // validation tokens + GetBondedTokens() math.Int // validator bonded tokens + GetConsensusPower(math.Int) int64 // validation power in tendermint + GetCommission() sdk.Dec // validator commission rate + GetMinSelfDelegation() math.Int // validator minimum self delegation + GetDelegatorShares() sdk.Dec // total outstanding delegator shares + TokensFromShares(sdk.Dec) sdk.Dec // token worth of provided delegator shares + TokensFromSharesTruncated(sdk.Dec) sdk.Dec // token worth of provided delegator shares, truncated + TokensFromSharesRoundUp(sdk.Dec) sdk.Dec // token worth of provided delegator shares, rounded up + SharesFromTokens(amt math.Int) (sdk.Dec, error) // shares worth of delegator's bond + SharesFromTokensTruncated(amt math.Int) (sdk.Dec, error) // truncated shares worth of delegator's bond } diff --git a/x/staking/types/historical_info.go b/x/staking/types/historical_info.go index 447a559bda7b..fb1030f6c8c3 100644 --- a/x/staking/types/historical_info.go +++ b/x/staking/types/historical_info.go @@ -3,18 +3,19 @@ package types import ( "sort" + "cosmossdk.io/math" + "github.com/gogo/protobuf/proto" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) // NewHistoricalInfo will create a historical information struct from header and valset // it will first sort valset before inclusion into historical info -func NewHistoricalInfo(header tmproto.Header, valSet Validators, powerReduction sdk.Int) HistoricalInfo { +func NewHistoricalInfo(header tmproto.Header, valSet Validators, powerReduction math.Int) HistoricalInfo { // Must sort in the same way that tendermint does sort.SliceStable(valSet, func(i, j int) bool { return ValidatorsByVotingPower(valSet).Less(i, j, powerReduction) diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go index 74d73bf19c7e..ca0023d71080 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -7,6 +7,8 @@ import ( "strconv" "time" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" "github.com/cosmos/cosmos-sdk/types/kv" @@ -78,7 +80,7 @@ func AddressFromLastValidatorPowerKey(key []byte) []byte { // Power index is the key used in the power-store, and represents the relative // power ranking of the validator. // VALUE: validator operator address ([]byte) -func GetValidatorsByPowerIndexKey(validator Validator, powerReduction sdk.Int) []byte { +func GetValidatorsByPowerIndexKey(validator Validator, powerReduction math.Int) []byte { // NOTE the address doesn't need to be stored because counter bytes must always be different // NOTE the larger values are of higher value diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index a1ae89d15751..4cacc16ca6c8 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -1,6 +1,7 @@ package types import ( + "cosmossdk.io/math" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -32,7 +33,7 @@ var ( // Delegator address and validator address are the same. func NewMsgCreateValidator( valAddr sdk.ValAddress, pubKey cryptotypes.PubKey, //nolint:interfacer - selfDelegation sdk.Coin, description Description, commission CommissionRates, minSelfDelegation sdk.Int, + selfDelegation sdk.Coin, description Description, commission CommissionRates, minSelfDelegation math.Int, ) (*MsgCreateValidator, error) { var pkAny *codectypes.Any if pubKey != nil { @@ -139,7 +140,7 @@ func (msg MsgCreateValidator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) // NewMsgEditValidator creates a new MsgEditValidator instance //nolint:interfacer -func NewMsgEditValidator(valAddr sdk.ValAddress, description Description, newRate *sdk.Dec, newMinSelfDelegation *sdk.Int) *MsgEditValidator { +func NewMsgEditValidator(valAddr sdk.ValAddress, description Description, newRate *sdk.Dec, newMinSelfDelegation *math.Int) *MsgEditValidator { return &MsgEditValidator{ Description: description, CommissionRate: newRate, diff --git a/x/staking/types/params.go b/x/staking/types/params.go index 191b66e4c809..46405e3ad308 100644 --- a/x/staking/types/params.go +++ b/x/staking/types/params.go @@ -6,6 +6,7 @@ import ( "strings" "time" + "cosmossdk.io/math" "sigs.k8s.io/yaml" "github.com/cosmos/cosmos-sdk/codec" @@ -204,7 +205,7 @@ func validateBondDenom(i interface{}) error { } func ValidatePowerReduction(i interface{}) error { - v, ok := i.(sdk.Int) + v, ok := i.(math.Int) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } diff --git a/x/staking/types/pool.go b/x/staking/types/pool.go index c71d1684f9aa..79f24d33705c 100644 --- a/x/staking/types/pool.go +++ b/x/staking/types/pool.go @@ -1,7 +1,7 @@ package types import ( - sdk "github.com/cosmos/cosmos-sdk/types" + "cosmossdk.io/math" ) // names used as root for pool module accounts: @@ -15,7 +15,7 @@ const ( ) // NewPool creates a new Pool instance used for queries -func NewPool(notBonded, bonded sdk.Int) Pool { +func NewPool(notBonded, bonded math.Int) Pool { return Pool{ NotBondedTokens: notBonded, BondedTokens: bonded, diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 4296181ec9b5..afcec7e168a1 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -7,6 +7,7 @@ import ( "strings" "time" + "cosmossdk.io/math" abci "github.com/tendermint/tendermint/abci/types" tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" "sigs.k8s.io/yaml" @@ -123,7 +124,7 @@ type ValidatorsByVotingPower []Validator func (valz ValidatorsByVotingPower) Len() int { return len(valz) } -func (valz ValidatorsByVotingPower) Less(i, j int, r sdk.Int) bool { +func (valz ValidatorsByVotingPower) Less(i, j int, r math.Int) bool { if valz[i].ConsensusPower(r) == valz[j].ConsensusPower(r) { addrI, errI := valz[i].GetConsAddr() addrJ, errJ := valz[j].GetConsAddr() @@ -264,7 +265,7 @@ func (d Description) EnsureLength() (Description, error) { // ABCIValidatorUpdate returns an abci.ValidatorUpdate from a staking validator type // with the full validator power -func (v Validator) ABCIValidatorUpdate(r sdk.Int) abci.ValidatorUpdate { +func (v Validator) ABCIValidatorUpdate(r math.Int) abci.ValidatorUpdate { tmProtoPk, err := v.TmConsPublicKey() if err != nil { panic(err) @@ -327,7 +328,7 @@ func (v Validator) TokensFromSharesRoundUp(shares sdk.Dec) sdk.Dec { // SharesFromTokens returns the shares of a delegation given a bond amount. It // returns an error if the validator has no tokens. -func (v Validator) SharesFromTokens(amt sdk.Int) (sdk.Dec, error) { +func (v Validator) SharesFromTokens(amt math.Int) (sdk.Dec, error) { if v.Tokens.IsZero() { return sdk.ZeroDec(), ErrInsufficientShares } @@ -337,7 +338,7 @@ func (v Validator) SharesFromTokens(amt sdk.Int) (sdk.Dec, error) { // SharesFromTokensTruncated returns the truncated shares of a delegation given // a bond amount. It returns an error if the validator has no tokens. -func (v Validator) SharesFromTokensTruncated(amt sdk.Int) (sdk.Dec, error) { +func (v Validator) SharesFromTokensTruncated(amt math.Int) (sdk.Dec, error) { if v.Tokens.IsZero() { return sdk.ZeroDec(), ErrInsufficientShares } @@ -346,7 +347,7 @@ func (v Validator) SharesFromTokensTruncated(amt sdk.Int) (sdk.Dec, error) { } // get the bonded tokens which the validator holds -func (v Validator) BondedTokens() sdk.Int { +func (v Validator) BondedTokens() math.Int { if v.IsBonded() { return v.Tokens } @@ -356,7 +357,7 @@ func (v Validator) BondedTokens() sdk.Int { // ConsensusPower gets the consensus-engine power. Aa reduction of 10^6 from // validator tokens is applied -func (v Validator) ConsensusPower(r sdk.Int) int64 { +func (v Validator) ConsensusPower(r math.Int) int64 { if v.IsBonded() { return v.PotentialConsensusPower(r) } @@ -365,7 +366,7 @@ func (v Validator) ConsensusPower(r sdk.Int) int64 { } // PotentialConsensusPower returns the potential consensus-engine power. -func (v Validator) PotentialConsensusPower(r sdk.Int) int64 { +func (v Validator) PotentialConsensusPower(r math.Int) int64 { return sdk.TokensToConsensusPower(v.Tokens, r) } @@ -377,7 +378,7 @@ func (v Validator) UpdateStatus(newStatus BondStatus) Validator { } // AddTokensFromDel adds tokens to a validator -func (v Validator) AddTokensFromDel(amount sdk.Int) (Validator, sdk.Dec) { +func (v Validator) AddTokensFromDel(amount math.Int) (Validator, sdk.Dec) { // calculate the shares to issue var issuedShares sdk.Dec if v.DelegatorShares.IsZero() { @@ -399,7 +400,7 @@ func (v Validator) AddTokensFromDel(amount sdk.Int) (Validator, sdk.Dec) { } // RemoveTokens removes tokens from a validator -func (v Validator) RemoveTokens(tokens sdk.Int) Validator { +func (v Validator) RemoveTokens(tokens math.Int) Validator { if tokens.IsNegative() { panic(fmt.Sprintf("should not happen: trying to remove negative tokens %v", tokens)) } @@ -416,10 +417,10 @@ func (v Validator) RemoveTokens(tokens sdk.Int) Validator { // RemoveDelShares removes delegator shares from a validator. // NOTE: because token fractions are left in the valiadator, // the exchange rate of future shares of this validator can increase. -func (v Validator) RemoveDelShares(delShares sdk.Dec) (Validator, sdk.Int) { +func (v Validator) RemoveDelShares(delShares sdk.Dec) (Validator, math.Int) { remainingShares := v.DelegatorShares.Sub(delShares) - var issuedTokens sdk.Int + var issuedTokens math.Int if remainingShares.IsZero() { // last delegation share gets any trimmings issuedTokens = v.Tokens @@ -510,14 +511,14 @@ func (v Validator) GetConsAddr() (sdk.ConsAddress, error) { return sdk.ConsAddress(pk.Address()), nil } -func (v Validator) GetTokens() sdk.Int { return v.Tokens } -func (v Validator) GetBondedTokens() sdk.Int { return v.BondedTokens() } -func (v Validator) GetConsensusPower(r sdk.Int) int64 { +func (v Validator) GetTokens() math.Int { return v.Tokens } +func (v Validator) GetBondedTokens() math.Int { return v.BondedTokens() } +func (v Validator) GetConsensusPower(r math.Int) int64 { return v.ConsensusPower(r) } -func (v Validator) GetCommission() sdk.Dec { return v.Commission.Rate } -func (v Validator) GetMinSelfDelegation() sdk.Int { return v.MinSelfDelegation } -func (v Validator) GetDelegatorShares() sdk.Dec { return v.DelegatorShares } +func (v Validator) GetCommission() sdk.Dec { return v.Commission.Rate } +func (v Validator) GetMinSelfDelegation() math.Int { return v.MinSelfDelegation } +func (v Validator) GetDelegatorShares() sdk.Dec { return v.DelegatorShares } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces func (v Validator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { diff --git a/x/upgrade/module.go b/x/upgrade/module.go index e4e2ad5a006e..2bece77259a0 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -101,7 +101,10 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterQueryServer(cfg.QueryServer(), am.keeper) m := keeper.NewMigrator(am.keeper) - cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2) + err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2) + if err != nil { + panic(err) + } } // InitGenesis is ignored, no sense in serializing future upgrades