diff --git a/indexer/packages/v4-protos/src/codegen/dydxprotocol/bundle.ts b/indexer/packages/v4-protos/src/codegen/dydxprotocol/bundle.ts index fcbccb4917..66e00ab551 100644 --- a/indexer/packages/v4-protos/src/codegen/dydxprotocol/bundle.ts +++ b/indexer/packages/v4-protos/src/codegen/dydxprotocol/bundle.ts @@ -126,16 +126,17 @@ import * as _136 from "./bridge/tx.rpc.msg"; import * as _137 from "./clob/tx.rpc.msg"; import * as _138 from "./delaymsg/tx.rpc.msg"; import * as _139 from "./feetiers/tx.rpc.msg"; -import * as _140 from "./perpetuals/tx.rpc.msg"; -import * as _141 from "./prices/tx.rpc.msg"; -import * as _142 from "./ratelimit/tx.rpc.msg"; -import * as _143 from "./rewards/tx.rpc.msg"; -import * as _144 from "./sending/tx.rpc.msg"; -import * as _145 from "./stats/tx.rpc.msg"; -import * as _146 from "./vest/tx.rpc.msg"; -import * as _147 from "./lcd"; -import * as _148 from "./rpc.query"; -import * as _149 from "./rpc.tx"; +import * as _140 from "./govplus/tx.rpc.msg"; +import * as _141 from "./perpetuals/tx.rpc.msg"; +import * as _142 from "./prices/tx.rpc.msg"; +import * as _143 from "./ratelimit/tx.rpc.msg"; +import * as _144 from "./rewards/tx.rpc.msg"; +import * as _145 from "./sending/tx.rpc.msg"; +import * as _146 from "./stats/tx.rpc.msg"; +import * as _147 from "./vest/tx.rpc.msg"; +import * as _148 from "./lcd"; +import * as _149 from "./rpc.query"; +import * as _150 from "./rpc.tx"; export namespace dydxprotocol { export const assets = { ..._5, ..._6, @@ -215,7 +216,8 @@ export namespace dydxprotocol { export const govplus = { ..._49, ..._50, ..._51, - ..._126 + ..._126, + ..._140 }; export namespace indexer { export const events = { ..._52 @@ -243,7 +245,7 @@ export namespace dydxprotocol { ..._64, ..._112, ..._127, - ..._140 + ..._141 }; export const prices = { ..._65, ..._66, @@ -252,7 +254,7 @@ export namespace dydxprotocol { ..._69, ..._113, ..._128, - ..._141 + ..._142 }; export const ratelimit = { ..._70, ..._71, @@ -261,7 +263,7 @@ export namespace dydxprotocol { ..._74, ..._114, ..._129, - ..._142 + ..._143 }; export const rewards = { ..._75, ..._76, @@ -270,14 +272,14 @@ export namespace dydxprotocol { ..._79, ..._115, ..._130, - ..._143 + ..._144 }; export const sending = { ..._80, ..._81, ..._82, ..._83, ..._131, - ..._144 + ..._145 }; export const stats = { ..._84, ..._85, @@ -286,7 +288,7 @@ export namespace dydxprotocol { ..._88, ..._116, ..._132, - ..._145 + ..._146 }; export const subaccounts = { ..._89, ..._90, @@ -302,10 +304,10 @@ export namespace dydxprotocol { ..._97, ..._118, ..._134, - ..._146 + ..._147 }; - export const ClientFactory = { ..._147, - ..._148, - ..._149 + export const ClientFactory = { ..._148, + ..._149, + ..._150 }; } \ No newline at end of file diff --git a/indexer/packages/v4-protos/src/codegen/dydxprotocol/govplus/tx.rpc.msg.ts b/indexer/packages/v4-protos/src/codegen/dydxprotocol/govplus/tx.rpc.msg.ts new file mode 100644 index 0000000000..1db348b3dc --- /dev/null +++ b/indexer/packages/v4-protos/src/codegen/dydxprotocol/govplus/tx.rpc.msg.ts @@ -0,0 +1,27 @@ +import { Rpc } from "../../helpers"; +import * as _m0 from "protobufjs/minimal"; +import { MsgSlashValidator, MsgSlashValidatorResponse } from "./tx"; +/** Msg defines the Msg service. */ + +export interface Msg { + /** + * SlashValidator is exposed to allow slashing of a misbehaving validator via + * governance. + */ + slashValidator(request: MsgSlashValidator): Promise; +} +export class MsgClientImpl implements Msg { + private readonly rpc: Rpc; + + constructor(rpc: Rpc) { + this.rpc = rpc; + this.slashValidator = this.slashValidator.bind(this); + } + + slashValidator(request: MsgSlashValidator): Promise { + const data = MsgSlashValidator.encode(request).finish(); + const promise = this.rpc.request("dydxprotocol.govplus.Msg", "SlashValidator", data); + return promise.then(data => MsgSlashValidatorResponse.decode(new _m0.Reader(data))); + } + +} \ No newline at end of file diff --git a/indexer/packages/v4-protos/src/codegen/dydxprotocol/govplus/tx.ts b/indexer/packages/v4-protos/src/codegen/dydxprotocol/govplus/tx.ts index 693da49fc4..574ecdccee 100644 --- a/indexer/packages/v4-protos/src/codegen/dydxprotocol/govplus/tx.ts +++ b/indexer/packages/v4-protos/src/codegen/dydxprotocol/govplus/tx.ts @@ -1 +1,201 @@ -export {} \ No newline at end of file +import * as _m0 from "protobufjs/minimal"; +import { DeepPartial } from "../../helpers"; +/** MsgSlashValidator is the Msg/SlashValidator request type. */ + +export interface MsgSlashValidator { + authority: string; + /** Consensus address of the validator to slash */ + + validatorAddress: string; + /** + * Colloquially, the height at which the validator is deemed to have + * misbehaved. In practice, this is the height used to determine the targets + * of the slash. For example, undelegating after this height will not escape + * slashing. This height should be set to a recent height at the time of the + * proposal to prevent delegators from undelegating during the vote period. + * i.e. infraction_height <= proposal submission height. + * + * NB: At the time this message is applied, this height must have occured + * equal to or less than an unbonding period in the past in order for the + * slash to be effective. + * i.e. time(proposal pass height) - time(infraction_height) < unbonding + * period + */ + + infractionHeight: number; + /** + * Tokens of the validator at the specified height. Used to compute the slash + * amount. The x/staking HistoricalInfo query endpoint can be used to find + * this. + */ + + tokensAtInfractionHeight: Uint8Array; + /** + * Multiplier for how much of the validator's stake should be slashed. + * slash_factor * tokens_at_infraction_height = tokens slashed + */ + + slashFactor: string; +} +/** MsgSlashValidator is the Msg/SlashValidator request type. */ + +export interface MsgSlashValidatorSDKType { + authority: string; + /** Consensus address of the validator to slash */ + + validator_address: string; + /** + * Colloquially, the height at which the validator is deemed to have + * misbehaved. In practice, this is the height used to determine the targets + * of the slash. For example, undelegating after this height will not escape + * slashing. This height should be set to a recent height at the time of the + * proposal to prevent delegators from undelegating during the vote period. + * i.e. infraction_height <= proposal submission height. + * + * NB: At the time this message is applied, this height must have occured + * equal to or less than an unbonding period in the past in order for the + * slash to be effective. + * i.e. time(proposal pass height) - time(infraction_height) < unbonding + * period + */ + + infraction_height: number; + /** + * Tokens of the validator at the specified height. Used to compute the slash + * amount. The x/staking HistoricalInfo query endpoint can be used to find + * this. + */ + + tokens_at_infraction_height: Uint8Array; + /** + * Multiplier for how much of the validator's stake should be slashed. + * slash_factor * tokens_at_infraction_height = tokens slashed + */ + + slash_factor: string; +} +/** MsgSlashValidatorResponse is the Msg/SlashValidator response type. */ + +export interface MsgSlashValidatorResponse {} +/** MsgSlashValidatorResponse is the Msg/SlashValidator response type. */ + +export interface MsgSlashValidatorResponseSDKType {} + +function createBaseMsgSlashValidator(): MsgSlashValidator { + return { + authority: "", + validatorAddress: "", + infractionHeight: 0, + tokensAtInfractionHeight: new Uint8Array(), + slashFactor: "" + }; +} + +export const MsgSlashValidator = { + encode(message: MsgSlashValidator, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.authority !== "") { + writer.uint32(10).string(message.authority); + } + + if (message.validatorAddress !== "") { + writer.uint32(18).string(message.validatorAddress); + } + + if (message.infractionHeight !== 0) { + writer.uint32(24).uint32(message.infractionHeight); + } + + if (message.tokensAtInfractionHeight.length !== 0) { + writer.uint32(34).bytes(message.tokensAtInfractionHeight); + } + + if (message.slashFactor !== "") { + writer.uint32(42).string(message.slashFactor); + } + + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): MsgSlashValidator { + const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseMsgSlashValidator(); + + while (reader.pos < end) { + const tag = reader.uint32(); + + switch (tag >>> 3) { + case 1: + message.authority = reader.string(); + break; + + case 2: + message.validatorAddress = reader.string(); + break; + + case 3: + message.infractionHeight = reader.uint32(); + break; + + case 4: + message.tokensAtInfractionHeight = reader.bytes(); + break; + + case 5: + message.slashFactor = reader.string(); + break; + + default: + reader.skipType(tag & 7); + break; + } + } + + return message; + }, + + fromPartial(object: DeepPartial): MsgSlashValidator { + const message = createBaseMsgSlashValidator(); + message.authority = object.authority ?? ""; + message.validatorAddress = object.validatorAddress ?? ""; + message.infractionHeight = object.infractionHeight ?? 0; + message.tokensAtInfractionHeight = object.tokensAtInfractionHeight ?? new Uint8Array(); + message.slashFactor = object.slashFactor ?? ""; + return message; + } + +}; + +function createBaseMsgSlashValidatorResponse(): MsgSlashValidatorResponse { + return {}; +} + +export const MsgSlashValidatorResponse = { + encode(_: MsgSlashValidatorResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): MsgSlashValidatorResponse { + const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseMsgSlashValidatorResponse(); + + while (reader.pos < end) { + const tag = reader.uint32(); + + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + + return message; + }, + + fromPartial(_: DeepPartial): MsgSlashValidatorResponse { + const message = createBaseMsgSlashValidatorResponse(); + return message; + } + +}; \ No newline at end of file diff --git a/indexer/packages/v4-protos/src/codegen/dydxprotocol/rpc.tx.ts b/indexer/packages/v4-protos/src/codegen/dydxprotocol/rpc.tx.ts index a76b1b51e9..1fd6591912 100644 --- a/indexer/packages/v4-protos/src/codegen/dydxprotocol/rpc.tx.ts +++ b/indexer/packages/v4-protos/src/codegen/dydxprotocol/rpc.tx.ts @@ -10,6 +10,7 @@ export const createRPCMsgClient = async ({ clob: new (await import("./clob/tx.rpc.msg")).MsgClientImpl(rpc), delaymsg: new (await import("./delaymsg/tx.rpc.msg")).MsgClientImpl(rpc), feetiers: new (await import("./feetiers/tx.rpc.msg")).MsgClientImpl(rpc), + govplus: new (await import("./govplus/tx.rpc.msg")).MsgClientImpl(rpc), perpetuals: new (await import("./perpetuals/tx.rpc.msg")).MsgClientImpl(rpc), prices: new (await import("./prices/tx.rpc.msg")).MsgClientImpl(rpc), ratelimit: new (await import("./ratelimit/tx.rpc.msg")).MsgClientImpl(rpc), diff --git a/proto/dydxprotocol/govplus/tx.proto b/proto/dydxprotocol/govplus/tx.proto index 3c509230ce..42280bef0d 100644 --- a/proto/dydxprotocol/govplus/tx.proto +++ b/proto/dydxprotocol/govplus/tx.proto @@ -1,7 +1,62 @@ syntax = "proto3"; package dydxprotocol.govplus; +import "cosmos_proto/cosmos.proto"; +import "cosmos/msg/v1/msg.proto"; +import "gogoproto/gogo.proto"; +import "amino/amino.proto"; + option go_package = "github.com/dydxprotocol/v4-chain/protocol/x/govplus/types"; // Msg defines the Msg service. -service Msg {} +service Msg { + // SlashValidator is exposed to allow slashing of a misbehaving validator via + // governance. + rpc SlashValidator(MsgSlashValidator) returns (MsgSlashValidatorResponse); +} + +// MsgSlashValidator is the Msg/SlashValidator request type. +message MsgSlashValidator { + // The address that controls the module (the gov module account). + option (cosmos.msg.v1.signer) = "authority"; + string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; + + // Consensus address of the validator to slash + string validator_address = 2 + [ (cosmos_proto.scalar) = "cosmos.ValidatorAddressString" ]; + + // Colloquially, the height at which the validator is deemed to have + // misbehaved. In practice, this is the height used to determine the targets + // of the slash. For example, undelegating after this height will not escape + // slashing. This height should be set to a recent height at the time of the + // proposal to prevent delegators from undelegating during the vote period. + // i.e. infraction_height <= proposal submission height. + // + // NB: At the time this message is applied, this height must have occured + // equal to or less than an unbonding period in the past in order for the + // slash to be effective. + // i.e. time(proposal pass height) - time(infraction_height) < unbonding + // period + uint32 infraction_height = 3; + + // Tokens of the validator at the specified height. Used to compute the slash + // amount. The x/staking HistoricalInfo query endpoint can be used to find + // this. + bytes tokens_at_infraction_height = 4 [ + (gogoproto.customtype) = + "github.com/dydxprotocol/v4-chain/protocol/dtypes.SerializableInt", + (gogoproto.nullable) = false + ]; + + // Multiplier for how much of the validator's stake should be slashed. + // slash_factor * tokens_at_infraction_height = tokens slashed + string slash_factor = 5 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; +} + +// MsgSlashValidatorResponse is the Msg/SlashValidator response type. +message MsgSlashValidatorResponse {} diff --git a/protocol/app/app.go b/protocol/app/app.go index 76121e047a..1527c783fe 100644 --- a/protocol/app/app.go +++ b/protocol/app/app.go @@ -391,6 +391,7 @@ func New( sendingmoduletypes.StoreKey, delaymsgmoduletypes.StoreKey, epochsmoduletypes.StoreKey, + govplusmoduletypes.StoreKey, ) tkeys := storetypes.NewTransientStoreKeys( paramstypes.TStoreKey, @@ -1012,6 +1013,7 @@ func New( app.GovPlusKeeper = *govplusmodulekeeper.NewKeeper( appCodec, + app.StakingKeeper, keys[govplusmoduletypes.StoreKey], []string{ lib.GovModuleAddress.String(), diff --git a/protocol/app/basic_manager/basic_manager.go b/protocol/app/basic_manager/basic_manager.go index 63869cba75..8368247bdf 100644 --- a/protocol/app/basic_manager/basic_manager.go +++ b/protocol/app/basic_manager/basic_manager.go @@ -28,6 +28,7 @@ import ( clobmodule "github.com/dydxprotocol/v4-chain/protocol/x/clob" epochsmodule "github.com/dydxprotocol/v4-chain/protocol/x/epochs" feetiersmodule "github.com/dydxprotocol/v4-chain/protocol/x/feetiers" + govplusmodule "github.com/dydxprotocol/v4-chain/protocol/x/govplus" perpetualsmodule "github.com/dydxprotocol/v4-chain/protocol/x/perpetuals" pricesmodule "github.com/dydxprotocol/v4-chain/protocol/x/prices" ratelimitmodule "github.com/dydxprotocol/v4-chain/protocol/x/ratelimit" @@ -89,5 +90,6 @@ var ( sendingmodule.AppModuleBasic{}, epochsmodule.AppModuleBasic{}, ratelimitmodule.AppModuleBasic{}, + govplusmodule.AppModuleBasic{}, ) ) diff --git a/protocol/app/msgs/all_msgs.go b/protocol/app/msgs/all_msgs.go index 295aad2ce9..7aa23aa9cf 100644 --- a/protocol/app/msgs/all_msgs.go +++ b/protocol/app/msgs/all_msgs.go @@ -190,6 +190,10 @@ var ( "/dydxprotocol.feetiers.MsgUpdatePerpetualFeeParams": {}, "/dydxprotocol.feetiers.MsgUpdatePerpetualFeeParamsResponse": {}, + // govplus + "/dydxprotocol.govplus.MsgSlashValidator": {}, + "/dydxprotocol.govplus.MsgSlashValidatorResponse": {}, + // perpetuals "/dydxprotocol.perpetuals.MsgAddPremiumVotes": {}, "/dydxprotocol.perpetuals.MsgAddPremiumVotesResponse": {}, diff --git a/protocol/app/msgs/internal_msgs.go b/protocol/app/msgs/internal_msgs.go index 72dfd7856a..f728967eef 100644 --- a/protocol/app/msgs/internal_msgs.go +++ b/protocol/app/msgs/internal_msgs.go @@ -21,6 +21,7 @@ import ( clob "github.com/dydxprotocol/v4-chain/protocol/x/clob/types" delaymsg "github.com/dydxprotocol/v4-chain/protocol/x/delaymsg/types" feetiers "github.com/dydxprotocol/v4-chain/protocol/x/feetiers/types" + govplus "github.com/dydxprotocol/v4-chain/protocol/x/govplus/types" perpetuals "github.com/dydxprotocol/v4-chain/protocol/x/perpetuals/types" prices "github.com/dydxprotocol/v4-chain/protocol/x/prices/types" ratelimit "github.com/dydxprotocol/v4-chain/protocol/x/ratelimit/types" @@ -135,6 +136,10 @@ var ( "/dydxprotocol.feetiers.MsgUpdatePerpetualFeeParams": &feetiers.MsgUpdatePerpetualFeeParams{}, "/dydxprotocol.feetiers.MsgUpdatePerpetualFeeParamsResponse": nil, + // govplus + "/dydxprotocol.govplus.MsgSlashValidator": &govplus.MsgSlashValidator{}, + "/dydxprotocol.govplus.MsgSlashValidatorResponse": nil, + // perpetuals "/dydxprotocol.perpetuals.MsgCreatePerpetual": &perpetuals.MsgCreatePerpetual{}, "/dydxprotocol.perpetuals.MsgCreatePerpetualResponse": nil, diff --git a/protocol/app/msgs/internal_msgs_test.go b/protocol/app/msgs/internal_msgs_test.go index f958bece28..cd4b7f5aad 100644 --- a/protocol/app/msgs/internal_msgs_test.go +++ b/protocol/app/msgs/internal_msgs_test.go @@ -97,6 +97,10 @@ func TestInternalMsgSamples_Gov_Key(t *testing.T) { "/dydxprotocol.feetiers.MsgUpdatePerpetualFeeParams", "/dydxprotocol.feetiers.MsgUpdatePerpetualFeeParamsResponse", + // govplus + "/dydxprotocol.govplus.MsgSlashValidator", + "/dydxprotocol.govplus.MsgSlashValidatorResponse", + // perpeutals "/dydxprotocol.perpetuals.MsgCreatePerpetual", "/dydxprotocol.perpetuals.MsgCreatePerpetualResponse", diff --git a/protocol/app/simulation_test.go b/protocol/app/simulation_test.go index eec316ba64..81825fcd72 100644 --- a/protocol/app/simulation_test.go +++ b/protocol/app/simulation_test.go @@ -9,9 +9,6 @@ import ( "testing" "time" - dbm "github.com/cosmos/cosmos-db" - icatypes "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/types" - "cosmossdk.io/log" "cosmossdk.io/math" "cosmossdk.io/store" @@ -19,6 +16,7 @@ import ( feegranttypes "cosmossdk.io/x/feegrant" tmjson "github.com/cometbft/cometbft/libs/json" tmtypes "github.com/cometbft/cometbft/types" + dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" @@ -44,6 +42,7 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" + icatypes "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/types" ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" exportedtypes "github.com/cosmos/ibc-go/v8/modules/core/exported" "github.com/dydxprotocol/v4-chain/protocol/app" diff --git a/protocol/lib/ante/internal_msg.go b/protocol/lib/ante/internal_msg.go index 43de69bb02..652985b16d 100644 --- a/protocol/lib/ante/internal_msg.go +++ b/protocol/lib/ante/internal_msg.go @@ -20,6 +20,7 @@ import ( clob "github.com/dydxprotocol/v4-chain/protocol/x/clob/types" delaymsg "github.com/dydxprotocol/v4-chain/protocol/x/delaymsg/types" feetiers "github.com/dydxprotocol/v4-chain/protocol/x/feetiers/types" + govplus "github.com/dydxprotocol/v4-chain/protocol/x/govplus/types" perpetuals "github.com/dydxprotocol/v4-chain/protocol/x/perpetuals/types" prices "github.com/dydxprotocol/v4-chain/protocol/x/prices/types" ratelimit "github.com/dydxprotocol/v4-chain/protocol/x/ratelimit/types" @@ -88,6 +89,9 @@ func IsInternalMsg(msg sdk.Msg) bool { // feetiers *feetiers.MsgUpdatePerpetualFeeParams, + // govplus + *govplus.MsgSlashValidator, + // perpetuals *perpetuals.MsgCreatePerpetual, *perpetuals.MsgSetLiquidityTier, diff --git a/protocol/testutil/app/app.go b/protocol/testutil/app/app.go index 7c8d12138b..ba50113f77 100644 --- a/protocol/testutil/app/app.go +++ b/protocol/testutil/app/app.go @@ -55,6 +55,7 @@ import ( delaymsgtypes "github.com/dydxprotocol/v4-chain/protocol/x/delaymsg/types" epochstypes "github.com/dydxprotocol/v4-chain/protocol/x/epochs/types" feetiertypes "github.com/dydxprotocol/v4-chain/protocol/x/feetiers/types" + govplus "github.com/dydxprotocol/v4-chain/protocol/x/govplus/types" perptypes "github.com/dydxprotocol/v4-chain/protocol/x/perpetuals/types" pricestypes "github.com/dydxprotocol/v4-chain/protocol/x/prices/types" ratelimittypes "github.com/dydxprotocol/v4-chain/protocol/x/ratelimit/types" @@ -198,7 +199,8 @@ type GenesisStates interface { delaymsgtypes.GenesisState | bridgetypes.GenesisState | govtypesv1.GenesisState | - ratelimittypes.GenesisState + ratelimittypes.GenesisState | + govplus.GenesisState } // UpdateGenesisDocWithAppStateForModule updates the supplied genesis doc using the provided function. The function @@ -250,6 +252,8 @@ func UpdateGenesisDocWithAppStateForModule[T GenesisStates](genesisDoc *types.Ge moduleName = govtypes.ModuleName case ratelimittypes.GenesisState: moduleName = ratelimittypes.ModuleName + case govplus.GenesisState: + moduleName = govplus.ModuleName default: panic(fmt.Errorf("Unsupported type %T", t)) } diff --git a/protocol/x/govplus/keeper/keeper.go b/protocol/x/govplus/keeper/keeper.go index 558859fa89..aa5a33b41e 100644 --- a/protocol/x/govplus/keeper/keeper.go +++ b/protocol/x/govplus/keeper/keeper.go @@ -13,21 +13,24 @@ import ( type ( Keeper struct { - cdc codec.BinaryCodec - storeKey storetypes.StoreKey - authorities map[string]struct{} + cdc codec.BinaryCodec + stakingKeeper types.StakingKeeper + storeKey storetypes.StoreKey + authorities map[string]struct{} } ) func NewKeeper( cdc codec.BinaryCodec, + stakingKeeper types.StakingKeeper, storeKey storetypes.StoreKey, authorities []string, ) *Keeper { return &Keeper{ - cdc: cdc, - storeKey: storeKey, - authorities: lib.UniqueSliceToSet(authorities), + cdc: cdc, + stakingKeeper: stakingKeeper, + storeKey: storeKey, + authorities: lib.UniqueSliceToSet(authorities), } } diff --git a/protocol/x/govplus/keeper/keeper_test.go b/protocol/x/govplus/keeper/keeper_test.go deleted file mode 100644 index 8806127133..0000000000 --- a/protocol/x/govplus/keeper/keeper_test.go +++ /dev/null @@ -1,851 +0,0 @@ -package keeper_test - -import ( - "math/big" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - - cometbfttypes "github.com/cometbft/cometbft/types" - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/dydxprotocol/v4-chain/protocol/dtypes" - testapp "github.com/dydxprotocol/v4-chain/protocol/testutil/app" - big_testutil "github.com/dydxprotocol/v4-chain/protocol/testutil/big" - blocktimetypes "github.com/dydxprotocol/v4-chain/protocol/x/blocktime/types" - "github.com/dydxprotocol/v4-chain/protocol/x/ratelimit/types" - "github.com/stretchr/testify/require" -) - -const ( - testDenom = "ibc/xxx" - testDenom2 = "testdenom2" - testAddress1 = "dydx16h7p7f4dysrgtzptxx2gtpt5d8t834g9dj830z" - testAddress2 = "dydx168pjt8rkru35239fsqvz7rzgeclakp49zx3aum" - testAddress3 = "dydx1fjg6zp6vv8t9wvy4lps03r5l4g7tkjw9wvmh70" -) - -func TestSetGetDenomCapacity(t *testing.T) { - tApp := testapp.NewTestAppBuilder(t).Build() - ctx := tApp.InitChain() - k := tApp.App.RatelimitKeeper - - capacityList := []dtypes.SerializableInt{ - dtypes.NewInt(123_456_789), - dtypes.NewInt(500_000_000), - } - denomCapacity := types.DenomCapacity{ - Denom: testDenom, - CapacityList: capacityList, - } - - // Test SetDenomCapacity - k.SetDenomCapacity(ctx, denomCapacity) - - // Test GetDenomCapacity - gotDenomCapacity := k.GetDenomCapacity(ctx, testDenom) - require.Equal(t, denomCapacity, gotDenomCapacity, "retrieved DenomCapacity does not match the set value") - - k.SetDenomCapacity(ctx, types.DenomCapacity{ - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{}, // Empty list, results in deletion of the key. - }) - - // Check that the key is deleted under `DenomCapacity` storage. - require.Equal(t, - types.DenomCapacity{ - Denom: testDenom, - CapacityList: nil, - }, - k.GetDenomCapacity(ctx, testDenom), - "retrieved LimitParams do not match the set value", - ) -} - -func TestSetGetLimitParams_Success(t *testing.T) { - // Run tests. - tests := map[string]struct { - denom string - balances []banktypes.Balance - limiters []types.Limiter - expectedCapacityList []dtypes.SerializableInt - }{ - "0 TVL, capactiy correctly initialized as minimum baseline": { - denom: testDenom, - limiters: []types.Limiter{ - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 10_000, // 1% - }, - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1m tokens (assuming 6 decimals) - BaselineTvlPpm: 100_000, // 10% - }, - }, - expectedCapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(100_000_000_000), - dtypes.NewInt(1_000_000_000_000), - }, - }, - "50m TVL, capactiy correctly initialized to 1% and 10%": { - denom: testDenom, - limiters: []types.Limiter{ - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 10_000, // 1% - }, - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1m tokens (assuming 6 decimals) - BaselineTvlPpm: 100_000, // 10% - }, - }, - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(25_000_000_000_000), // 25M token - }, - }, - }, - { - Address: testAddress2, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(25_000_000_000_000), // 25M token - }, - }, - }, - }, - expectedCapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(500_000_000_000), // 500k tokens (1% of 50m) - dtypes.NewInt(5_000_000_000_000), // 5m tokens (10% of 50m) - }, - }, - "50m TVL, capactiy correctly initialized to 5% and 20% (rounds down)": { - denom: testDenom, - limiters: []types.Limiter{ - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 50_000, // 5% - }, - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1m tokens (assuming 6 decimals) - BaselineTvlPpm: 200_000, // 20% - }, - }, - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(25_123_450_000_000), // 25M token - }, - }, - }, - { - Address: testAddress2, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(25_000_000_000_000), // 25M token - }, - }, - }, - }, - expectedCapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(2_506_172_500_000), // ~2.5M tokens (5% of ~50m) - dtypes.NewInt(10_024_690_000_000), // ~5m tokens (20% of 50m) - }, - }, - "50m TVL, capactiy correctly initialized to 10% and 100%": { - denom: testDenom, - limiters: []types.Limiter{ - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 100_000, // 10% - }, - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1m tokens (assuming 6 decimals) - BaselineTvlPpm: 1_000_000, // 100% - }, - }, - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(25_000_000_000_000), // 25M token - }, - }, - }, - { - Address: testAddress2, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(25_000_000_000_000), // 25M token - }, - }, - }, - }, - expectedCapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(5_000_000_000_000), // 5m tokens (10% of 50m) - dtypes.NewInt(50_000_000_000_000), // 50m tokens (100% of 50m) - }, - }, - } - - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - tApp := testapp.NewTestAppBuilder(t).WithGenesisDocFn(func() (genesis cometbfttypes.GenesisDoc) { - genesis = testapp.DefaultGenesis() - // Set up treasury account balance in genesis state - testapp.UpdateGenesisDocWithAppStateForModule( - &genesis, - func(genesisState *banktypes.GenesisState) { - genesisState.Balances = append(genesisState.Balances, tc.balances...) - }, - ) - return genesis - }).Build() - ctx := tApp.InitChain() - k := tApp.App.RatelimitKeeper - - limitParams := types.LimitParams{ - Denom: tc.denom, - Limiters: tc.limiters, - } - - // Test SetLimitParams - err := k.SetLimitParams(ctx, limitParams) - require.NoError(t, err) - - // Test GetLimitParams - gotLimitParams := k.GetLimitParams(ctx, tc.denom) - require.Equal(t, limitParams, gotLimitParams, "retrieved LimitParams do not match the set value") - - // Query for `DenomCapacity` of `testDenom`. - gotDenomCapacity := k.GetDenomCapacity(ctx, tc.denom) - // Expected `DenomCapacity` is initialized such that each capacity is equal to the baseline. - expectedDenomCapacity := types.DenomCapacity{ - Denom: tc.denom, - CapacityList: tc.expectedCapacityList, - } - require.Equal(t, expectedDenomCapacity, gotDenomCapacity, "retrieved DenomCapacity does not match the set value") - - // Set empty `LimitParams` for `testDenom`. - err = k.SetLimitParams(ctx, types.LimitParams{ - Denom: tc.denom, - Limiters: []types.Limiter{}, // Empty list, results in deletion of the key. - }) - require.NoError(t, err) - - // Check that the key is deleted under `LimitParams` storage. - require.Equal(t, - types.LimitParams{ - Denom: tc.denom, - Limiters: nil, - }, - k.GetLimitParams(ctx, tc.denom), - "retrieved LimitParams do not match the set value") - - // Check that the key is deleted under `DenomCapacity` storage. - require.Equal(t, - types.DenomCapacity{ - Denom: tc.denom, - CapacityList: nil, - }, - k.GetDenomCapacity(ctx, tc.denom), - "retrieved LimitParams do not match the set value") - }) - } -} - -func TestUpdateAllCapacitiesEndBlocker(t *testing.T) { - tests := map[string]struct { - balances []banktypes.Balance // For initializing the current supply - limitParamsList []types.LimitParams - prevBlockTime time.Time - blockTime time.Time - initDenomCapacityList []types.DenomCapacity - expectedDenomCapacityList []types.DenomCapacity - }{ - "One denom, prev capacity equals baseline": { - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(25_000_000_000_000), // 25M token (assuming 6 decimals) - }, - }, - }, - }, - limitParamsList: []types.LimitParams{ - { - Denom: testDenom, - Limiters: []types.Limiter{ - // baseline = 25M * 1% = 250k tokens - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 10_000, // 1% - }, - // baseline = 25M * 10% = 2.5M tokens - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1M tokens (assuming 6 decimals) - BaselineTvlPpm: 100_000, // 10% - }, - }, - }, - }, - prevBlockTime: time.Unix(1000, 0).In(time.UTC), - blockTime: time.Unix(1001, 0).In(time.UTC), - initDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(250_000_000_000), // 250k tokens, which equals baseline - dtypes.NewInt(2_500_000_000_000), // 2.5M tokens, which equals baseline - }, - }, - }, - expectedDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(250_000_000_000), // 250k tokens - dtypes.NewInt(2_500_000_000_000), // 2.5M tokens - }, - }, - }, - }, - "One denom, prev capacity < baseline": { - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(25_000_000_000_000), // 25M token (assuming 6 decimals) - }, - }, - }, - }, - limitParamsList: []types.LimitParams{ - { - Denom: testDenom, - Limiters: []types.Limiter{ - // baseline = 25M * 1% = 250k tokens - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 10_000, // 1% - }, - // baseline = 25M * 10% = 2.5M tokens - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1M tokens (assuming 6 decimals) - BaselineTvlPpm: 100_000, // 10% - }, - }, - }, - }, - prevBlockTime: time.Unix(1000, 0).In(time.UTC), - blockTime: time.Unix(1001, 0).In(time.UTC), - initDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(99_000_000_000), // 99k tokens, < baseline (250k) - dtypes.NewInt(990_000_000_000), // 0.99M tokens, < baseline (2.5M) - }, - }, - }, - expectedDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(99_069_444_444), // recovered by 1/3600 * 250k = 69.4444 tokens - dtypes.NewInt(990_028_935_185), // recovered by 1/86400 * 2.5M = 28.9351 tokens - }, - }, - }, - }, - "One denom, prev capacity < baseline, 18 decimals": { - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewIntFromBigInt( - big_testutil.Int64MulPow10(25, 24), // 25M tokens (assuming 18 decimals) - ), - }, - }, - }, - }, - limitParamsList: []types.LimitParams{ - { - Denom: testDenom, - Limiters: []types.Limiter{ - // baseline = 25M * 1% = 250k tokens - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewIntFromBigInt( - big_testutil.Int64MulPow10(100_000, 18), // 100k tokens(assuming 18 decimals) - ), - BaselineTvlPpm: 10_000, // 1% - }, - // baseline = 25M * 10% = 2.5M tokens - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewIntFromBigInt( - big_testutil.Int64MulPow10(1_000_000, 18), // 1M tokens(assuming 18 decimals) - ), - BaselineTvlPpm: 100_000, // 10% - }, - }, - }, - }, - prevBlockTime: time.Unix(1000, 0).In(time.UTC), - blockTime: time.Unix(1001, 0).In(time.UTC), - initDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewIntFromBigInt( - big_testutil.Int64MulPow10(99_000, 18), - ), // 99k tokens < baseline (250k) - dtypes.NewIntFromBigInt( - big_testutil.Int64MulPow10(990_000, 18), - ), // 0.99M tokens, < baseline (2.5M) - }, - }, - }, - expectedDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewIntFromBigInt( - big_testutil.MustFirst(new(big.Int).SetString("99069444444444444444444", 10)), - ), // recovered by 1/3600 * 250k ~= 69.4444 tokens - dtypes.NewIntFromBigInt( - big_testutil.MustFirst(new(big.Int).SetString("990028935185185185185185", 10)), - ), // recovered by 1/86400 * 2.5M ~= 28.9351 tokens - }, - }, - }, - }, - "One denom, prev capacity = 0": { - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(1_000_000_000_000), // 1M token (assuming 6 decimals) - }, - }, - }, - }, - limitParamsList: []types.LimitParams{ - { - Denom: testDenom, - Limiters: []types.Limiter{ - // baseline = baseline minimum = 100k tokens - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 10_000, // 1% - }, - // baseline = baseline minimum = 1M tokens - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1M tokens (assuming 6 decimals) - BaselineTvlPpm: 100_000, // 10% - }, - }, - }, - }, - prevBlockTime: time.Unix(1000, 0).In(time.UTC), - blockTime: time.Unix(1001, 0).In(time.UTC), - initDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(0), // 0 Capacity - dtypes.NewInt(0), // 0 Capacity - }, - }, - }, - expectedDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(27_777_777), // recovered by 1/3600 * 100k ~= 27.7778 tokens - dtypes.NewInt(11_574_074), // recovered by 1/86400 * 1M ~= 11.5741 tokens - }, - }, - }, - }, - "One denom, baseline < prev capacity < 2 * baseline": { - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(20_000_000_000_000), // 20M token (assuming 6 decimals) - }, - }, - }, - }, - limitParamsList: []types.LimitParams{ - { - Denom: testDenom, - Limiters: []types.Limiter{ - // baseline = 20M * 1% = 200k tokens - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 10_000, // 1% - }, - // baseline = 20M * 10% = 2M tokens - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1M tokens (assuming 6 decimals) - BaselineTvlPpm: 100_000, // 10% - }, - }, - }, - }, - prevBlockTime: time.Unix(1000, 0).In(time.UTC), - blockTime: time.Unix(1001, 0).In(time.UTC), - initDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(329_000_000_000), - dtypes.NewInt(3_500_000_000_000), - }, - }, - }, - expectedDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(328_944_444_445), // recovered by 1/3600 * 200k ~= 55.5555555556 - dtypes.NewInt(3_499_976_851_852), // recovered by 1/86400 * 2M ~= 23.1481481482 - }, - }, - }, - }, - "One denom, prev capacity > 2 * baseline": { - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(20_000_000_000_000), // 20M token (assuming 6 decimals) - }, - }, - }, - }, - limitParamsList: []types.LimitParams{ - { - Denom: testDenom, - Limiters: []types.Limiter{ - // baseline = 20M * 1% = 200k tokens - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 10_000, // 1% - }, - // baseline = 20M * 10% = 2M tokens - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1M tokens (assuming 6 decimals) - BaselineTvlPpm: 100_000, // 10% - }, - }, - }, - }, - prevBlockTime: time.Unix(1000, 0).In(time.UTC), - blockTime: time.Unix(1001, 0).In(time.UTC), - initDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(529_000_000_000), // 529k tokens > 2 * baseline (200k) - dtypes.NewInt(4_500_000_000_000), // 4.5M tokens > 2 * baseline (2) - }, - }, - }, - expectedDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(528_908_611_112), // recovered by 1/3600 * (529k - 200k) ~= 91.389 - dtypes.NewInt(4_499_971_064_815), // recovered by 1/86400 * (4.5M - 2M) ~= 28.935 - }, - }, - }, - }, - "Two denoms, mix of values from above cases": { - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(20_000_000_000_000), // 20M token (assuming 6 decimals) - }, - { - Denom: testDenom2, - Amount: sdkmath.NewInt(25_000_000_000_000), // 20M token (assuming 6 decimals) - }, - }, - }, - }, - limitParamsList: []types.LimitParams{ - { - Denom: testDenom, - Limiters: []types.Limiter{ - // baseline = 20M * 1% = 200k tokens - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 10_000, // 1% - }, - // baseline = 20M * 10% = 2M tokens - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1M tokens (assuming 6 decimals) - BaselineTvlPpm: 100_000, // 10% - }, - }, - }, - { - Denom: testDenom2, - Limiters: []types.Limiter{ - // baseline = 25M * 1% = 250k tokens - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 10_000, // 1% - }, - // baseline = 25M * 10% = 2.5M tokens - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1M tokens (assuming 6 decimals) - BaselineTvlPpm: 100_000, // 10% - }, - }, - }, - }, - prevBlockTime: time.Unix(1000, 0).In(time.UTC), - blockTime: time.Unix(1001, 0).In(time.UTC), - initDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(529_000_000_000), // 529k tokens > 2 * baseline (200k) - dtypes.NewInt(4_500_000_000_000), // 4.5M tokens > 2 * baseline (2) - }, - }, - { - Denom: testDenom2, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(99_000_000_000), // 99k tokens, < baseline (250k) - dtypes.NewInt(990_000_000_000), // 0.99M tokens, < baseline (2.5M) - }, - }, - }, - expectedDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(528_908_611_112), // recovered by 1/3600 * (529k - 200k) ~= 91.389 - dtypes.NewInt(4_499_971_064_815), // recovered by 1/86400 * (4.5M - 2M) ~= 28.935 - }, - }, - { - Denom: testDenom2, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(99_069_444_444), // recovered by 1/3600 * 250k = 69.4444 tokens - dtypes.NewInt(990_028_935_185), // recovered by 1/86400 * 2.5M = 28.9351 tokens - }, - }, - }, - }, - "(Error) one denom, current block time = prev block time, no changes applied": { - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(25_000_000_000_000), // 25M token (assuming 6 decimals) - }, - }, - }, - }, - limitParamsList: []types.LimitParams{ - { - Denom: testDenom, - Limiters: []types.Limiter{ - // baseline = 25M * 1% = 250k tokens - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 10_000, // 1% - }, - // baseline = 25M * 10% = 2.5M tokens - { - Period: 86_400 * time.Second, - BaselineMinimum: dtypes.NewInt(1_000_000_000_000), // 1M tokens (assuming 6 decimals) - BaselineTvlPpm: 100_000, // 10% - }, - }, - }, - }, - prevBlockTime: time.Unix(1000, 0).In(time.UTC), - blockTime: time.Unix(1000, 0).In(time.UTC), // same as prev block time (should not happen in practice) - initDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(99_000_000_000), // 99k tokens, < baseline (250k) - dtypes.NewInt(990_000_000_000), // 0.99M tokens, < baseline (2.5M) - }, - }, - }, - expectedDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(99_000_000_000), // 99k tokens (unchanged) - dtypes.NewInt(990_000_000_000), // 0.99M tokens (unchanged) - }, - }, - }, - }, - "(Error) one denom, len(limiters) != len(capacityList)": { - balances: []banktypes.Balance{ - { - Address: testAddress1, - Coins: sdk.Coins{ - { - Denom: testDenom, - Amount: sdkmath.NewInt(25_000_000_000_000), // 25M token (assuming 6 decimals) - }, - }, - }, - }, - limitParamsList: []types.LimitParams{ - { - Denom: testDenom, - Limiters: []types.Limiter{ - // baseline = 25M * 1% = 250k tokens - { - Period: 3_600 * time.Second, - BaselineMinimum: dtypes.NewInt(100_000_000_000), // 100k tokens (assuming 6 decimals) - BaselineTvlPpm: 10_000, // 1% - }, - }, - }, - }, - prevBlockTime: time.Unix(1000, 0).In(time.UTC), - blockTime: time.Unix(1001, 0).In(time.UTC), // same as prev block time (should not happen in practice) - initDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(99_000_000_000), // 99k tokens, < baseline (250k) - dtypes.NewInt(990_000_000_000), // 0.99M tokens, < baseline (2.5M) - }, - }, - }, - expectedDenomCapacityList: []types.DenomCapacity{ - { - Denom: testDenom, - CapacityList: []dtypes.SerializableInt{ - dtypes.NewInt(99_000_000_000), // 99k tokens (unchanged) - dtypes.NewInt(990_000_000_000), // 0.99M tokens (unchanged) - }, - }, - }, - }, - } - - // Run tests. - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - tApp := testapp.NewTestAppBuilder(t).WithGenesisDocFn(func() (genesis cometbfttypes.GenesisDoc) { - genesis = testapp.DefaultGenesis() - // Set up treasury account balance in genesis state - testapp.UpdateGenesisDocWithAppStateForModule( - &genesis, - func(genesisState *banktypes.GenesisState) { - genesisState.Balances = append(genesisState.Balances, tc.balances...) - }, - ) - return genesis - }).Build() - - ctx := tApp.InitChain() - - // Set previous block time - tApp.App.BlockTimeKeeper.SetPreviousBlockInfo(ctx, &blocktimetypes.BlockInfo{ - Timestamp: tc.prevBlockTime, - }) - - k := tApp.App.RatelimitKeeper - - // Initialize limit params - for _, limitParams := range tc.limitParamsList { - err := k.SetLimitParams(ctx, limitParams) - require.NoError(t, err) - } - - // Initialize denom capacity - for _, denomCapacity := range tc.initDenomCapacityList { - k.SetDenomCapacity(ctx, denomCapacity) - } - - // Run the function being tested - k.UpdateAllCapacitiesEndBlocker(ctx.WithBlockTime(tc.blockTime)) - - // Check results - for _, expectedDenomCapacity := range tc.expectedDenomCapacityList { - gotDenomCapacity := k.GetDenomCapacity(ctx, expectedDenomCapacity.Denom) - require.Equal(t, - expectedDenomCapacity, - gotDenomCapacity, - "expected denom capacity: %+v, got: %+v", - expectedDenomCapacity, - gotDenomCapacity, - ) - } - }) - } -} diff --git a/protocol/x/govplus/keeper/msg_server.go b/protocol/x/govplus/keeper/msg_server.go index 7c01192b85..b75ad7df5a 100644 --- a/protocol/x/govplus/keeper/msg_server.go +++ b/protocol/x/govplus/keeper/msg_server.go @@ -1,6 +1,13 @@ package keeper import ( + "context" + + errorsmod "cosmossdk.io/errors" + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/dydxprotocol/v4-chain/protocol/lib/log" "github.com/dydxprotocol/v4-chain/protocol/x/govplus/types" ) @@ -15,3 +22,40 @@ func NewMsgServerImpl(keeper Keeper) types.MsgServer { } var _ types.MsgServer = msgServer{} + +func (k msgServer) SlashValidator( + goCtx context.Context, + msg *types.MsgSlashValidator, +) (*types.MsgSlashValidatorResponse, error) { + if !k.HasAuthority(msg.Authority) { + return nil, errorsmod.Wrapf( + govtypes.ErrInvalidSigner, + "invalid authority %s", + msg.Authority, + ) + } + + consAddr, err := sdk.ConsAddressFromBech32(msg.ValidatorAddress) + if err != nil { + return nil, types.ErrValidatorAddress + } + + ctx := sdk.UnwrapSDKContext(goCtx) + _, err = k.stakingKeeper.Slash( + ctx, + consAddr, + int64(msg.InfractionHeight), // Casting from uint32 + sdk.TokensToConsensusPower( + sdkmath.NewIntFromBigInt(msg.TokensAtInfractionHeight.BigInt()), sdk.DefaultPowerReduction), + msg.SlashFactor, + ) + if err != nil { + log.ErrorLogWithError( + ctx, + "error occurred when slashing validator", + err, + ) + return nil, err + } + return &types.MsgSlashValidatorResponse{}, nil +} diff --git a/protocol/x/govplus/keeper/msg_server_test.go b/protocol/x/govplus/keeper/msg_server_test.go index c5997406e3..fc48bc7ca5 100644 --- a/protocol/x/govplus/keeper/msg_server_test.go +++ b/protocol/x/govplus/keeper/msg_server_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/dydxprotocol/v4-chain/protocol/lib" testapp "github.com/dydxprotocol/v4-chain/protocol/testutil/app" "github.com/dydxprotocol/v4-chain/protocol/x/govplus/keeper" "github.com/dydxprotocol/v4-chain/protocol/x/govplus/types" @@ -24,3 +25,44 @@ func TestMsgServer(t *testing.T) { require.NotNil(t, ms) require.NotNil(t, ctx) } + +func TestSlashValidator(t *testing.T) { + _, ms, ctx := setupMsgServer(t) + + testCases := []struct { + name string + input *types.MsgSlashValidator + expErr bool + expErrMsg string + }{ + { + name: "invalid authority", + input: &types.MsgSlashValidator{ + Authority: "invalid", + }, + expErr: true, + expErrMsg: "invalid authority", + }, + { + name: "bad address", + input: &types.MsgSlashValidator{ + Authority: lib.GovModuleAddress.String(), + ValidatorAddress: "asdfasdfasdfaf", + }, + expErr: true, + expErrMsg: "Could not convert validator consensus address", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + _, err := ms.SlashValidator(ctx, tc.input) + if tc.expErr { + require.Error(t, err) + require.Contains(t, err.Error(), tc.expErrMsg) + } else { + require.NoError(t, err) + } + }) + } +} diff --git a/protocol/x/govplus/types/errors.go b/protocol/x/govplus/types/errors.go new file mode 100644 index 0000000000..8d52282c5a --- /dev/null +++ b/protocol/x/govplus/types/errors.go @@ -0,0 +1,28 @@ +package types + +// DONTCOVER + +import errorsmod "cosmossdk.io/errors" + +var ( + ErrValidatorAddress = errorsmod.Register( + ModuleName, + 400, + "Could not convert validator consensus address from bech32", + ) + ErrInvalidAuthority = errorsmod.Register( + ModuleName, + 401, + "Authority is invalid", + ) + ErrInvalidSlashFactor = errorsmod.Register( + ModuleName, + 402, + "slash_factor must be between 0 and 1 inclusive", + ) + ErrInvalidTokensAtInfractionHeight = errorsmod.Register( + ModuleName, + 403, + "tokens_at_infraction_height must be positive", + ) +) diff --git a/protocol/x/govplus/types/expected_keepers.go b/protocol/x/govplus/types/expected_keepers.go new file mode 100644 index 0000000000..82afb3571e --- /dev/null +++ b/protocol/x/govplus/types/expected_keepers.go @@ -0,0 +1,19 @@ +package types + +import ( + context "context" + + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// StatsKeeper defines the expected stats keeper +type StakingKeeper interface { + Slash( + ctx context.Context, + consAddr sdk.ConsAddress, + infractionHeight, + power int64, + slashFactor math.LegacyDec, + ) (math.Int, error) +} diff --git a/protocol/x/govplus/types/keys.go b/protocol/x/govplus/types/keys.go index 1ca0eff668..118fe83409 100644 --- a/protocol/x/govplus/types/keys.go +++ b/protocol/x/govplus/types/keys.go @@ -6,5 +6,7 @@ const ( ModuleName = "govplus" // StoreKey defines the primary module store key - StoreKey = ModuleName + // This is not govplus because then StoreKey gov (from x/gov) would be a prefix of it, + // and that is not allowed. + StoreKey = "dydxgovplus" ) diff --git a/protocol/x/govplus/types/keys_test.go b/protocol/x/govplus/types/keys_test.go index 22527901f8..e2f31546f2 100644 --- a/protocol/x/govplus/types/keys_test.go +++ b/protocol/x/govplus/types/keys_test.go @@ -9,5 +9,5 @@ import ( func TestModuleKeys(t *testing.T) { require.Equal(t, "govplus", types.ModuleName) - require.Equal(t, "govplus", types.StoreKey) + require.Equal(t, "dydxgovplus", types.StoreKey) } diff --git a/protocol/x/govplus/types/tx.go b/protocol/x/govplus/types/tx.go new file mode 100644 index 0000000000..430bde6276 --- /dev/null +++ b/protocol/x/govplus/types/tx.go @@ -0,0 +1,45 @@ +package types + +import ( + "fmt" + "math/big" + + errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (msg *MsgSlashValidator) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { + return errorsmod.Wrap( + ErrInvalidAuthority, + fmt.Sprintf( + "authority '%s' must be a valid bech32 address, but got error '%v'", + msg.Authority, + err.Error(), + ), + ) + } + + _, err := sdk.ConsAddressFromBech32(msg.ValidatorAddress) + if err != nil { + return errorsmod.Wrap( + ErrValidatorAddress, + fmt.Sprintf( + "got error when converting consensus address %s from bech32 '%v'", + msg.ValidatorAddress, + err.Error(), + ), + ) + } + + if msg.TokensAtInfractionHeight.BigInt().Cmp(big.NewInt(0)) != 1 { + return ErrInvalidTokensAtInfractionHeight + } + + if msg.SlashFactor.IsNegative() || msg.SlashFactor.GT(math.LegacyNewDec(1)) { + return ErrInvalidSlashFactor + } + + return nil +} diff --git a/protocol/x/govplus/types/tx.pb.go b/protocol/x/govplus/types/tx.pb.go index 6ba74ba284..9150ba0a75 100644 --- a/protocol/x/govplus/types/tx.pb.go +++ b/protocol/x/govplus/types/tx.pb.go @@ -5,11 +5,21 @@ package types import ( context "context" + cosmossdk_io_math "cosmossdk.io/math" fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/types/msgservice" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" proto "github.com/cosmos/gogoproto/proto" + github_com_dydxprotocol_v4_chain_protocol_dtypes "github.com/dydxprotocol/v4-chain/protocol/dtypes" grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" math "math" + math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. @@ -23,19 +33,164 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +// MsgSlashValidator is the Msg/SlashValidator request type. +type MsgSlashValidator struct { + Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` + // Consensus address of the validator to slash + ValidatorAddress string `protobuf:"bytes,2,opt,name=validator_address,json=validatorAddress,proto3" json:"validator_address,omitempty"` + // Colloquially, the height at which the validator is deemed to have + // misbehaved. In practice, this is the height used to determine the targets + // of the slash. For example, undelegating after this height will not escape + // slashing. This height should be set to a recent height at the time of the + // proposal to prevent delegators from undelegating during the vote period. + // i.e. infraction_height <= proposal submission height. + // + // NB: At the time this message is applied, this height must have occured + // equal to or less than an unbonding period in the past in order for the + // slash to be effective. + // i.e. time(proposal pass height) - time(infraction_height) < unbonding + // period + InfractionHeight uint32 `protobuf:"varint,3,opt,name=infraction_height,json=infractionHeight,proto3" json:"infraction_height,omitempty"` + // Tokens of the validator at the specified height. Used to compute the slash + // amount. The x/staking HistoricalInfo query endpoint can be used to find + // this. + TokensAtInfractionHeight github_com_dydxprotocol_v4_chain_protocol_dtypes.SerializableInt `protobuf:"bytes,4,opt,name=tokens_at_infraction_height,json=tokensAtInfractionHeight,proto3,customtype=github.com/dydxprotocol/v4-chain/protocol/dtypes.SerializableInt" json:"tokens_at_infraction_height"` + // Multiplier for how much of the validator's stake should be slashed. + // slash_factor * tokens_at_infraction_height = tokens slashed + SlashFactor cosmossdk_io_math.LegacyDec `protobuf:"bytes,5,opt,name=slash_factor,json=slashFactor,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"slash_factor"` +} + +func (m *MsgSlashValidator) Reset() { *m = MsgSlashValidator{} } +func (m *MsgSlashValidator) String() string { return proto.CompactTextString(m) } +func (*MsgSlashValidator) ProtoMessage() {} +func (*MsgSlashValidator) Descriptor() ([]byte, []int) { + return fileDescriptor_9394a0d94676770f, []int{0} +} +func (m *MsgSlashValidator) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSlashValidator) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSlashValidator.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgSlashValidator) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSlashValidator.Merge(m, src) +} +func (m *MsgSlashValidator) XXX_Size() int { + return m.Size() +} +func (m *MsgSlashValidator) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSlashValidator.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSlashValidator proto.InternalMessageInfo + +func (m *MsgSlashValidator) GetAuthority() string { + if m != nil { + return m.Authority + } + return "" +} + +func (m *MsgSlashValidator) GetValidatorAddress() string { + if m != nil { + return m.ValidatorAddress + } + return "" +} + +func (m *MsgSlashValidator) GetInfractionHeight() uint32 { + if m != nil { + return m.InfractionHeight + } + return 0 +} + +// MsgSlashValidatorResponse is the Msg/SlashValidator response type. +type MsgSlashValidatorResponse struct { +} + +func (m *MsgSlashValidatorResponse) Reset() { *m = MsgSlashValidatorResponse{} } +func (m *MsgSlashValidatorResponse) String() string { return proto.CompactTextString(m) } +func (*MsgSlashValidatorResponse) ProtoMessage() {} +func (*MsgSlashValidatorResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_9394a0d94676770f, []int{1} +} +func (m *MsgSlashValidatorResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSlashValidatorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSlashValidatorResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgSlashValidatorResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSlashValidatorResponse.Merge(m, src) +} +func (m *MsgSlashValidatorResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgSlashValidatorResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSlashValidatorResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSlashValidatorResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgSlashValidator)(nil), "dydxprotocol.govplus.MsgSlashValidator") + proto.RegisterType((*MsgSlashValidatorResponse)(nil), "dydxprotocol.govplus.MsgSlashValidatorResponse") +} + func init() { proto.RegisterFile("dydxprotocol/govplus/tx.proto", fileDescriptor_9394a0d94676770f) } var fileDescriptor_9394a0d94676770f = []byte{ - // 131 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4d, 0xa9, 0x4c, 0xa9, - 0x28, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0xce, 0xcf, 0xd1, 0x4f, 0xcf, 0x2f, 0x2b, 0xc8, 0x29, 0x2d, - 0xd6, 0x2f, 0xa9, 0xd0, 0x03, 0x8b, 0x09, 0x89, 0x20, 0x4b, 0xeb, 0x41, 0xa5, 0x8d, 0x58, 0xb9, - 0x98, 0x7d, 0x8b, 0xd3, 0x9d, 0x82, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, - 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, - 0xca, 0x32, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0x1f, 0xc5, 0x82, 0x32, - 0x13, 0xdd, 0xe4, 0x8c, 0xc4, 0xcc, 0x3c, 0x7d, 0xb8, 0x48, 0x05, 0xc2, 0xd2, 0xca, 0x82, 0xd4, - 0xe2, 0x24, 0x36, 0xb0, 0x8c, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xc4, 0xf7, 0x6b, 0x7e, 0x99, - 0x00, 0x00, 0x00, + // 483 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x53, 0xbf, 0x6f, 0xd3, 0x4e, + 0x1c, 0xcd, 0x7d, 0xf3, 0x05, 0xa9, 0x47, 0xa9, 0x1a, 0x2b, 0x12, 0x6e, 0xa2, 0xba, 0xa1, 0x0b, + 0x51, 0x51, 0x7c, 0xe2, 0x87, 0x2a, 0xc1, 0x44, 0xa3, 0x0a, 0xb5, 0x12, 0x65, 0x70, 0x24, 0x24, + 0x58, 0xac, 0xcb, 0xf9, 0x7a, 0x3e, 0x6a, 0xfb, 0x13, 0x7c, 0x17, 0x2b, 0x61, 0x64, 0x61, 0xe5, + 0xcf, 0x60, 0xec, 0x90, 0x95, 0xbd, 0x63, 0x95, 0x09, 0x31, 0x54, 0x28, 0x19, 0xfa, 0x6f, 0xa0, + 0x9c, 0xdd, 0x86, 0x26, 0x0c, 0x5d, 0x6c, 0xdf, 0x7b, 0x9f, 0xf7, 0x9e, 0xf5, 0x3e, 0x36, 0xde, + 0x0c, 0x86, 0xc1, 0xa0, 0x97, 0x82, 0x06, 0x06, 0x11, 0x11, 0x90, 0xf5, 0xa2, 0xbe, 0x22, 0x7a, + 0xe0, 0x1a, 0xcc, 0xaa, 0xfe, 0x4d, 0xbb, 0x05, 0x5d, 0xdb, 0x60, 0xa0, 0x62, 0x50, 0xbe, 0x21, + 0x48, 0x7e, 0xc8, 0x05, 0xb5, 0x07, 0xf9, 0x89, 0xc4, 0x4a, 0x90, 0xec, 0xc9, 0xec, 0x56, 0x10, + 0x55, 0x01, 0x02, 0x72, 0xc1, 0xec, 0xa9, 0x40, 0x2b, 0x34, 0x96, 0x09, 0x10, 0x73, 0xcd, 0xa1, + 0xed, 0x1f, 0x65, 0x5c, 0x39, 0x52, 0xa2, 0x13, 0x51, 0x15, 0xbe, 0xa3, 0x91, 0x0c, 0xa8, 0x86, + 0xd4, 0xda, 0xc5, 0x2b, 0xb4, 0xaf, 0x43, 0x48, 0xa5, 0x1e, 0xda, 0xa8, 0x81, 0x9a, 0x2b, 0x6d, + 0x7b, 0x3c, 0x6a, 0x55, 0x8b, 0xf0, 0xbd, 0x20, 0x48, 0xb9, 0x52, 0x1d, 0x9d, 0xca, 0x44, 0x78, + 0xf3, 0x51, 0xeb, 0x2d, 0xae, 0x64, 0x57, 0x26, 0x3e, 0xcd, 0xa7, 0xec, 0xff, 0x8c, 0xfe, 0xe1, + 0x78, 0xd4, 0xda, 0x2c, 0xf4, 0xd7, 0x41, 0x37, 0x8d, 0xd6, 0xb3, 0x05, 0xdc, 0x7a, 0x8c, 0x2b, + 0x32, 0x39, 0x4e, 0x29, 0xd3, 0x12, 0x12, 0x3f, 0xe4, 0x52, 0x84, 0xda, 0x2e, 0x37, 0x50, 0xf3, + 0xbe, 0xb7, 0x3e, 0x27, 0x0e, 0x0c, 0x6e, 0x7d, 0x45, 0xb8, 0xae, 0xe1, 0x84, 0x27, 0xca, 0xa7, + 0xda, 0x5f, 0xd6, 0xfd, 0xdf, 0x40, 0xcd, 0xd5, 0xf6, 0xc1, 0xd9, 0xc5, 0x56, 0xe9, 0xd7, 0xc5, + 0xd6, 0x2b, 0x21, 0x75, 0xd8, 0xef, 0xba, 0x0c, 0x62, 0x72, 0x63, 0x2b, 0xd9, 0xf3, 0x16, 0x0b, + 0xa9, 0x4c, 0xc8, 0x35, 0x12, 0xe8, 0x61, 0x8f, 0x2b, 0xb7, 0xc3, 0x53, 0x49, 0x23, 0xf9, 0x99, + 0x76, 0x23, 0x7e, 0x98, 0x68, 0xcf, 0xce, 0xc3, 0xf6, 0xf4, 0xe1, 0xe2, 0x9b, 0xbc, 0xc7, 0xab, + 0x6a, 0x56, 0xa8, 0x7f, 0x4c, 0x99, 0x86, 0xd4, 0xbe, 0x63, 0x1a, 0xd8, 0x2d, 0x92, 0xeb, 0x79, + 0x0b, 0x2a, 0x38, 0x71, 0x25, 0x90, 0x98, 0xea, 0xd0, 0x7d, 0xc3, 0x05, 0x65, 0xc3, 0x7d, 0xce, + 0xc6, 0xa3, 0x16, 0x2e, 0x4a, 0xda, 0xe7, 0xec, 0xfb, 0xe5, 0xe9, 0x0e, 0xf2, 0xee, 0x19, 0xaf, + 0xd7, 0xc6, 0xea, 0xe5, 0xda, 0x97, 0xcb, 0xd3, 0x9d, 0x79, 0xe3, 0xdb, 0x75, 0xbc, 0xb1, 0xb4, + 0x3e, 0x8f, 0xab, 0x1e, 0x24, 0x8a, 0x3f, 0xfd, 0x84, 0xcb, 0x47, 0x4a, 0x58, 0x1f, 0xf1, 0xda, + 0xc2, 0x7e, 0x1f, 0xb9, 0xff, 0xfa, 0xd2, 0xdc, 0x25, 0xa7, 0x1a, 0xb9, 0xe5, 0xe0, 0x55, 0x64, + 0xbb, 0x73, 0x36, 0x71, 0xd0, 0xf9, 0xc4, 0x41, 0xbf, 0x27, 0x0e, 0xfa, 0x36, 0x75, 0x4a, 0xe7, + 0x53, 0xa7, 0xf4, 0x73, 0xea, 0x94, 0x3e, 0xbc, 0xb8, 0x7d, 0xe1, 0x83, 0xf9, 0xaf, 0x31, 0x6b, + 0xbe, 0x7b, 0xd7, 0x30, 0xcf, 0xfe, 0x04, 0x00, 0x00, 0xff, 0xff, 0xf7, 0x95, 0xbe, 0x42, 0x3f, + 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -50,6 +205,9 @@ const _ = grpc.SupportPackageIsVersion4 // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type MsgClient interface { + // SlashValidator is exposed to allow slashing of a misbehaving validator via + // governance. + SlashValidator(ctx context.Context, in *MsgSlashValidator, opts ...grpc.CallOption) (*MsgSlashValidatorResponse, error) } type msgClient struct { @@ -60,22 +218,531 @@ func NewMsgClient(cc grpc1.ClientConn) MsgClient { return &msgClient{cc} } +func (c *msgClient) SlashValidator(ctx context.Context, in *MsgSlashValidator, opts ...grpc.CallOption) (*MsgSlashValidatorResponse, error) { + out := new(MsgSlashValidatorResponse) + err := c.cc.Invoke(ctx, "/dydxprotocol.govplus.Msg/SlashValidator", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // MsgServer is the server API for Msg service. type MsgServer interface { + // SlashValidator is exposed to allow slashing of a misbehaving validator via + // governance. + SlashValidator(context.Context, *MsgSlashValidator) (*MsgSlashValidatorResponse, error) } // UnimplementedMsgServer can be embedded to have forward compatible implementations. type UnimplementedMsgServer struct { } +func (*UnimplementedMsgServer) SlashValidator(ctx context.Context, req *MsgSlashValidator) (*MsgSlashValidatorResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SlashValidator not implemented") +} + func RegisterMsgServer(s grpc1.Server, srv MsgServer) { s.RegisterService(&_Msg_serviceDesc, srv) } +func _Msg_SlashValidator_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgSlashValidator) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).SlashValidator(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/dydxprotocol.govplus.Msg/SlashValidator", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).SlashValidator(ctx, req.(*MsgSlashValidator)) + } + return interceptor(ctx, in, info, handler) +} + var _Msg_serviceDesc = grpc.ServiceDesc{ ServiceName: "dydxprotocol.govplus.Msg", HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{}, - Metadata: "dydxprotocol/govplus/tx.proto", + Methods: []grpc.MethodDesc{ + { + MethodName: "SlashValidator", + Handler: _Msg_SlashValidator_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "dydxprotocol/govplus/tx.proto", +} + +func (m *MsgSlashValidator) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgSlashValidator) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSlashValidator) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.SlashFactor.Size() + i -= size + if _, err := m.SlashFactor.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + { + size := m.TokensAtInfractionHeight.Size() + i -= size + if _, err := m.TokensAtInfractionHeight.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if m.InfractionHeight != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.InfractionHeight)) + i-- + dAtA[i] = 0x18 + } + if len(m.ValidatorAddress) > 0 { + i -= len(m.ValidatorAddress) + copy(dAtA[i:], m.ValidatorAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.ValidatorAddress))) + i-- + dAtA[i] = 0x12 + } + if len(m.Authority) > 0 { + i -= len(m.Authority) + copy(dAtA[i:], m.Authority) + i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgSlashValidatorResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgSlashValidatorResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSlashValidatorResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil } + +func encodeVarintTx(dAtA []byte, offset int, v uint64) int { + offset -= sovTx(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgSlashValidator) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Authority) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.ValidatorAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.InfractionHeight != 0 { + n += 1 + sovTx(uint64(m.InfractionHeight)) + } + l = m.TokensAtInfractionHeight.Size() + n += 1 + l + sovTx(uint64(l)) + l = m.SlashFactor.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgSlashValidatorResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovTx(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTx(x uint64) (n int) { + return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *MsgSlashValidator) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgSlashValidator: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSlashValidator: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Authority = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorAddress", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field InfractionHeight", wireType) + } + m.InfractionHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.InfractionHeight |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TokensAtInfractionHeight", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.TokensAtInfractionHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SlashFactor", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SlashFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgSlashValidatorResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgSlashValidatorResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSlashValidatorResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTx(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTx + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTx + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTx + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") +) diff --git a/protocol/x/govplus/types/tx_test.go b/protocol/x/govplus/types/tx_test.go new file mode 100644 index 0000000000..43c37f91fa --- /dev/null +++ b/protocol/x/govplus/types/tx_test.go @@ -0,0 +1,64 @@ +package types_test + +import ( + "testing" + + "cosmossdk.io/math" + "github.com/dydxprotocol/v4-chain/protocol/dtypes" + "github.com/dydxprotocol/v4-chain/protocol/lib" + types "github.com/dydxprotocol/v4-chain/protocol/x/govplus/types" + "github.com/stretchr/testify/require" +) + +var ( + validConsensusAddress = "cosmosvalcons1ntk8eualewuprz0gamh8hnvcem2nrcdsgz563h" +) + +func TestValidateBasic(t *testing.T) { + tests := map[string]struct { + msg types.MsgSlashValidator + expectedErr error + }{ + "invalid authority": { + msg: types.MsgSlashValidator{ + Authority: "invalid", + }, + expectedErr: types.ErrInvalidAuthority, + }, + "bad address": { + msg: types.MsgSlashValidator{ + Authority: lib.GovModuleAddress.String(), + ValidatorAddress: "asdfasdfasdfaf", + }, + expectedErr: types.ErrValidatorAddress, + }, + "bad tokens at infraction height": { + msg: types.MsgSlashValidator{ + Authority: lib.GovModuleAddress.String(), + ValidatorAddress: validConsensusAddress, + TokensAtInfractionHeight: dtypes.NewInt(-10), + SlashFactor: math.LegacyMustNewDecFromStr("0.5"), + }, + expectedErr: types.ErrInvalidTokensAtInfractionHeight, + }, + "bad slash factor": { + msg: types.MsgSlashValidator{ + Authority: lib.GovModuleAddress.String(), + ValidatorAddress: validConsensusAddress, + TokensAtInfractionHeight: dtypes.NewInt(100), + SlashFactor: math.LegacyMustNewDecFromStr("1.1"), + }, + expectedErr: types.ErrInvalidSlashFactor, + }, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + err := tc.msg.ValidateBasic() + if tc.expectedErr == nil { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, tc.expectedErr) + } + }) + } +}