diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ca825bbc5b..4c14644676d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#6309](https://github.com/osmosis-labs/osmosis/pull/6309) Add Cosmwasm Pool Queries to Stargate Query * [#6493](https://github.com/osmosis-labs/osmosis/pull/6493) Add PoolManager Params query to Stargate Whitelist * [#6421](https://github.com/osmosis-labs/osmosis/pull/6421) Moves ValidatePermissionlessPoolCreationEnabled out of poolmanager module +* [#5967](https://github.com/osmosis-labs/osmosis/pull/5967) fix ValSet undelegate API out of sync with existing staking * [#6627](https://github.com/osmosis-labs/osmosis/pull/6627) Limit pow iterations in osmomath. * [#6586](https://github.com/osmosis-labs/osmosis/pull/6586) add auth.moduleaccounts to the stargate whitelist * [#6680](https://github.com/osmosis-labs/osmosis/pull/6680) Add Taker Fee query and add it to stargate whitelist diff --git a/proto/osmosis/valset-pref/v1beta1/tx.proto b/proto/osmosis/valset-pref/v1beta1/tx.proto index 3eff1c396aa..70adfc831cb 100644 --- a/proto/osmosis/valset-pref/v1beta1/tx.proto +++ b/proto/osmosis/valset-pref/v1beta1/tx.proto @@ -27,6 +27,13 @@ service Msg { rpc UndelegateFromValidatorSet(MsgUndelegateFromValidatorSet) returns (MsgUndelegateFromValidatorSetResponse); + // UndelegateFromRebalancedValidatorSet undelegates the proivded amount from + // the validator set, but takes into consideration the current delegations + // to the user's validator set to determine the weights assigned to each. + rpc UndelegateFromRebalancedValidatorSet( + MsgUndelegateFromRebalancedValidatorSet) + returns (MsgUndelegateFromRebalancedValidatorSetResponse); + // RedelegateValidatorSet takes the existing validator set and redelegates to // a new set. rpc RedelegateValidatorSet(MsgRedelegateValidatorSet) @@ -98,6 +105,27 @@ message MsgUndelegateFromValidatorSet { message MsgUndelegateFromValidatorSetResponse {} +message MsgUndelegateFromRebalancedValidatorSet { + option (amino.name) = "osmosis/MsgUndelegateFromRebalancedValidatorSet"; + + // delegator is the user who is trying to undelegate. + string delegator = 1 [ (gogoproto.moretags) = "yaml:\"delegator\"" ]; + + // the amount the user wants to undelegate + // For ex: Undelegate 50 osmo with validator-set {ValA -> 0.5, ValB -> 0.5} + // Our undelegate logic would first check the current delegation balance. + // If the user has 90 osmo delegated to ValA and 10 osmo delegated to ValB, + // the rebalanced validator set would be {ValA -> 0.9, ValB -> 0.1} + // So now the 45 osmo would be undelegated from ValA and 5 osmo would be + // undelegated from ValB. + cosmos.base.v1beta1.Coin coin = 2 [ + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin" + ]; +} + +message MsgUndelegateFromRebalancedValidatorSetResponse {} + message MsgRedelegateValidatorSet { option (amino.name) = "osmosis/MsgRedelegateValidatorSet"; diff --git a/x/valset-pref/README.md b/x/valset-pref/README.md index 38cb9e35190..1f129c1ab2d 100644 --- a/x/valset-pref/README.md +++ b/x/valset-pref/README.md @@ -25,15 +25,54 @@ How does this module work? - If the delegator has not set a validator-set preference list then the validator set, then it defaults to their current validator set. - If a user has no preference list and has not staked, then these messages / queries return errors. -## Calculations - -Staking Calculation - -- The user provides an amount to delegate and our `MsgDelegateToValidatorSet` divides the amount based on validator weight distribution. - For example: Stake 100osmo with validator-set {ValA -> 0.5, ValB -> 0.3, ValC -> 0.2} - our delegate logic will attempt to delegate (100 * 0.5) 50osmo for ValA , (100 * 0.3) 30osmo from ValB and (100 * 0.2) 20osmo from ValC. - -UnStaking Calculation +## Logic + +### Delegate to validator set + +This is pretty straight-forward, theres not really any edge cases here. + +The user provides an amount to delegate and our `MsgDelegateToValidatorSet` divides the amount based on validator weight distribution. + +For example: Stake 100osmo with validator-set {ValA -> 0.5, ValB -> 0.3, ValC -> 0.2} +our delegate logic will attempt to delegate (100 * 0.5) 50osmo for ValA , (100 * 0.3) 30osmo from ValB and (100 * 0.2) 20osmo from ValC. + +### Undelegate from validator set + +We can imagine describing undelegate from validator set in two cases: +- Users existing delegation distribution matches their validator-set preference distribution. +- Users existing delegation distribution does not match their validator-set preference distribution. + +Algorithm for undelegation; +unbond as true to valset ratios as possible. Undelegation should be possible. +Idea of what we should be doing for Undelegate(valset, amount): +1. Calculate the amount to undelegate from each validator under full valset usage +2. If all amounts are less than amount staked to validator, undelegate all +3. If any amount is greater than amount staked to validator (S,V), + fully unstake S from that validator. Recursively proceed with undelegating the + remaining amount from the remaining validators. + Undelegate(valset - V, amount - S) + +The above algorithm would take O(V^2) worst case, so we instead do something better +to be O(V). + +1. Calculate the amount to undelegate from each validator under full valset usage +2. For each validator, compute V.ratio = undelegate_amount / amount_staked_to_val +3. Sort validators by V_ratio descending. If V_ratio <= 1, there is no need to re-calculate amount to undelegate for each validator, undelegate and end algorithm. +4. If V_ratio <= 1, undelegate target amount from each validator. (happy path) +5. Set target_ratio = 1, amount_remaining_to_unbond = amount +6. While greatest V_ratio > target_ratio: + - Fully undelegate validator with greatest V_ratio. (Amount S) + - remove validator from list + - recalculate target_ratio = target_ratio * (1 - removed_V.target_percent) + - this works, because if you recalculated target ratio scaled to 1 + every val's ratio would just differ by the constant factor of 1 / (1 - removed_V.target_percent) + doing that would take O(V), hence we change the target. +7. Normal undelegate the remainder. + + +#### Case 1: Users existing delegation distribution matches their validator-set preference distribution + +{Old docs below} - The user provides an amount to undelegate and our `MsgUnDelegateToValidatorSet` divides the amount based on validator weight distribution. - Here, the user can either undelegate the entire amount or partial amount diff --git a/x/valset-pref/client/cli/tx.go b/x/valset-pref/client/cli/tx.go index 5842b260fc6..3852263a0a1 100644 --- a/x/valset-pref/client/cli/tx.go +++ b/x/valset-pref/client/cli/tx.go @@ -19,7 +19,10 @@ func GetTxCmd() *cobra.Command { txCmd := osmocli.TxIndexCmd(types.ModuleName) osmocli.AddTxCmd(txCmd, NewSetValSetCmd) osmocli.AddTxCmd(txCmd, NewDelValSetCmd) - osmocli.AddTxCmd(txCmd, NewUnDelValSetCmd) + // TODO: Uncomment when undelegate is implemented + // https://github.com/osmosis-labs/osmosis/issues/6686 + //osmocli.AddTxCmd(txCmd, NewUnDelValSetCmd) + osmocli.AddTxCmd(txCmd, NewUndelRebalancedValSetCmd) osmocli.AddTxCmd(txCmd, NewReDelValSetCmd) osmocli.AddTxCmd(txCmd, NewWithRewValSetCmd) return txCmd @@ -44,13 +47,25 @@ func NewDelValSetCmd() (*osmocli.TxCliDesc, *types.MsgDelegateToValidatorSet) { }, &types.MsgDelegateToValidatorSet{} } -func NewUnDelValSetCmd() (*osmocli.TxCliDesc, *types.MsgUndelegateFromValidatorSet) { +// TODO: Uncomment when undelegate is implemented +// https://github.com/osmosis-labs/osmosis/issues/6686 +// func NewUnDelValSetCmd() (*osmocli.TxCliDesc, *types.MsgUndelegateFromValidatorSet) { +// return &osmocli.TxCliDesc{ +// Use: "undelegate-valset", +// Short: "UnDelegate tokens from existing valset using delegatorAddress and tokenAmount.", +// Example: "osmosisd tx valset-pref undelegate-valset osmo1... 100stake", +// NumArgs: 2, +// }, &types.MsgUndelegateFromValidatorSet{} +// } + +func NewUndelRebalancedValSetCmd() (*osmocli.TxCliDesc, *types.MsgUndelegateFromRebalancedValidatorSet) { return &osmocli.TxCliDesc{ - Use: "undelegate-valset", - Short: "UnDelegate tokens from existing valset using delegatorAddress and tokenAmount.", - Example: "osmosisd tx valset-pref undelegate-valset osmo1... 100stake", + Use: "undelegate-rebalanced-valset", + Short: "Undelegate tokens from rebalanced valset using delegatorAddress and tokenAmount.", + Long: "Undelegates from an existing valset, but calculates the valset weights based on current user delegations.", + Example: "osmosisd tx valset-pref undelegate-rebalanced-valset osmo1... 100stake", NumArgs: 2, - }, &types.MsgUndelegateFromValidatorSet{} + }, &types.MsgUndelegateFromRebalancedValidatorSet{} } func NewReDelValSetCmd() (*osmocli.TxCliDesc, *types.MsgRedelegateValidatorSet) { diff --git a/x/valset-pref/export_test.go b/x/valset-pref/export_test.go index 599f141e8e4..4eef1188dda 100644 --- a/x/valset-pref/export_test.go +++ b/x/valset-pref/export_test.go @@ -2,9 +2,11 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/osmosis-labs/osmosis/osmomath" lockuptypes "github.com/osmosis-labs/osmosis/v20/x/lockup/types" + "github.com/osmosis-labs/osmosis/v20/x/valset-pref/types" ) type ( @@ -14,3 +16,12 @@ type ( func (k Keeper) ValidateLockForForceUnlock(ctx sdk.Context, lockID uint64, delegatorAddr string) (*lockuptypes.PeriodLock, osmomath.Int, error) { return k.validateLockForForceUnlock(ctx, lockID, delegatorAddr) } + +func (k Keeper) GetValsetRatios(ctx sdk.Context, delegator sdk.AccAddress, + prefs []types.ValidatorPreference, undelegateAmt osmomath.Int) ([]ValRatio, map[string]stakingtypes.Validator, osmomath.Dec, error) { + return k.getValsetRatios(ctx, delegator, prefs, undelegateAmt) +} + +func FormatToValPrefArr(delegations []stakingtypes.Delegation) []types.ValidatorPreference { + return formatToValPrefArr(delegations) +} diff --git a/x/valset-pref/keeper.go b/x/valset-pref/keeper.go index d3ecade30db..20eb0e05636 100644 --- a/x/valset-pref/keeper.go +++ b/x/valset-pref/keeper.go @@ -6,10 +6,11 @@ import ( "github.com/tendermint/tendermint/libs/log" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/osmosis-labs/osmosis/osmomath" "github.com/osmosis-labs/osmosis/v20/x/valset-pref/types" ) @@ -49,42 +50,63 @@ func (k Keeper) GetDelegationPreferences(ctx sdk.Context, delegator string) (typ if err != nil { return types.ValidatorSetPreferences{}, err } - existingDelsValSetFormatted, err := k.GetExistingStakingDelegations(ctx, delAddr) - if err != nil { - return types.ValidatorSetPreferences{}, err + existingDelegations := k.stakingKeeper.GetDelegatorDelegations(ctx, delAddr, math.MaxUint16) + if len(existingDelegations) == 0 { + return types.ValidatorSetPreferences{}, types.ErrNoDelegation } - return types.ValidatorSetPreferences{Preferences: existingDelsValSetFormatted}, nil + return types.ValidatorSetPreferences{Preferences: formatToValPrefArr(existingDelegations)}, nil } return valSet, nil } -// GetExistingStakingDelegations returns the existing delegation that's not valset. -// This function also formats the output into ValidatorSetPreference struct {valAddr, weight}. -// The weight is calculated based on (valDelegation / totalDelegations) for each validator. -// This method erros when given address does not have any existing delegations. -func (k Keeper) GetExistingStakingDelegations(ctx sdk.Context, delAddr sdk.AccAddress) ([]types.ValidatorPreference, error) { - var existingDelsValSetFormatted []types.ValidatorPreference +// GetValSetPreferencesWithDelegations fetches the delegator's validator set preferences +// considering their existing delegations. +// -If validator set preference does not exist and there are no existing delegations, it returns an error. +// -If validator set preference exists and there are no existing delegations, it returns the existing preference. +// -If there is any existing delegation: +// calculates the delegator's shares in each delegation +// as a ratio of the total shares and returns it as part of ValidatorSetPreferences. +func (k Keeper) GetValSetPreferencesWithDelegations(ctx sdk.Context, delegator string) (types.ValidatorSetPreferences, error) { + delAddr, err := sdk.AccAddressFromBech32(delegator) + if err != nil { + return types.ValidatorSetPreferences{}, err + } + valSet, exists := k.GetValidatorSetPreference(ctx, delegator) existingDelegations := k.stakingKeeper.GetDelegatorDelegations(ctx, delAddr, math.MaxUint16) - if len(existingDelegations) == 0 { - return nil, types.ErrNoDelegation + + // No existing delegations for a delegator when valSet does not exist + if !exists && len(existingDelegations) == 0 { + return types.ValidatorSetPreferences{}, fmt.Errorf("No Existing delegation to unbond from") } - existingTotalShares := osmomath.NewDec(0) - // calculate total shares that currently exists - for _, existingDelegation := range existingDelegations { - existingTotalShares = existingTotalShares.Add(existingDelegation.Shares) + // Returning existing valSet when there are no existing delegations + if exists && len(existingDelegations) == 0 { + return valSet, nil } - // for each delegation format it in types.ValidatorSetPreferences format - for _, existingDelegation := range existingDelegations { - existingDelsValSetFormatted = append(existingDelsValSetFormatted, types.ValidatorPreference{ - ValOperAddress: existingDelegation.ValidatorAddress, - Weight: existingDelegation.Shares.Quo(existingTotalShares), - }) + // when existing delegation exists, have it based upon the existing delegation + // regardless of the delegator having valset pref or not + return types.ValidatorSetPreferences{Preferences: formatToValPrefArr(existingDelegations)}, nil +} + +// formatToValPrefArr iterates over given delegations array, formats it into ValidatorPreference array. +// Used to calculate weights for the each delegation towards validator. +// CONTRACT: This method assumes no duplicated ValOperAddress exists in the given delegation. +func formatToValPrefArr(delegations []stakingtypes.Delegation) []types.ValidatorPreference { + totalShares := sdk.NewDec(0) + for _, existingDelegation := range delegations { + totalShares = totalShares.Add(existingDelegation.Shares) } - return existingDelsValSetFormatted, nil + valPrefs := make([]types.ValidatorPreference, len(delegations)) + for i, delegation := range delegations { + valPrefs[i] = types.ValidatorPreference{ + ValOperAddress: delegation.ValidatorAddress, + Weight: delegation.Shares.Quo(totalShares), + } + } + return valPrefs } diff --git a/x/valset-pref/keeper_test.go b/x/valset-pref/keeper_test.go index 98c84d1b3fc..720f8ea1ad5 100644 --- a/x/valset-pref/keeper_test.go +++ b/x/valset-pref/keeper_test.go @@ -196,6 +196,181 @@ func (s *KeeperTestSuite) TestGetDelegationPreference() { } } +func (s *KeeperTestSuite) TestGetValSetPreferencesWithDelegations() { + s.SetupTest() + + defaultDelegateAmt := sdk.NewInt(1000) + + tests := []struct { + name string + setPref bool + setDelegation bool + expectedErr bool + }{ + { + name: "valset preference exists, no existing delegation", + setPref: true, + }, + { + name: "no valset preference, no existing delegation", + expectedErr: true, + }, + { + name: "valset preference exists, existing delegation exists", + setPref: true, + setDelegation: true, + }, + } + + for _, test := range tests { + s.Run(test.name, func() { + s.Setup() + + delegator := s.TestAccs[0] + + // prepare existing delegations validators + valAddrs := s.SetupMultipleValidators(3) + defaultValPrefs := types.ValidatorSetPreferences{ + Preferences: []types.ValidatorPreference{ + { + ValOperAddress: valAddrs[0], + Weight: sdk.NewDecWithPrec(5, 1), // 0.5 + }, + { + ValOperAddress: valAddrs[1], + Weight: sdk.NewDecWithPrec(5, 1), // 0.5 + }, + }, + } + + var expectedValsetPref types.ValidatorSetPreferences + if test.setPref { + s.App.ValidatorSetPreferenceKeeper.SetValidatorSetPreferences(s.Ctx, delegator.String(), defaultValPrefs) + expectedValsetPref = defaultValPrefs + } + + // set two delegation with different weights to test delegation -> val set pref conversion + if test.setDelegation { + valAddr0, err := sdk.ValAddressFromBech32(valAddrs[0]) + s.Require().NoError(err) + validator0, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr0) + s.Require().True(found) + bondDenom := s.App.StakingKeeper.BondDenom(s.Ctx) + + s.FundAcc(delegator, sdk.NewCoins(sdk.NewCoin(bondDenom, defaultDelegateAmt))) + _, err = s.App.StakingKeeper.Delegate(s.Ctx, delegator, defaultDelegateAmt, stakingtypes.Unbonded, validator0, true) + s.Require().NoError(err) + + valAddr1, err := sdk.ValAddressFromBech32(valAddrs[1]) + s.Require().NoError(err) + validator1, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr1) + s.Require().True(found) + + s.FundAcc(delegator, sdk.NewCoins(sdk.NewCoin(bondDenom, defaultDelegateAmt.Mul(sdk.NewInt(2))))) + _, err = s.App.StakingKeeper.Delegate(s.Ctx, delegator, defaultDelegateAmt.Mul(sdk.NewInt(2)), stakingtypes.Unbonded, validator1, true) + s.Require().NoError(err) + + expectedValsetPref = types.ValidatorSetPreferences{ + Preferences: []types.ValidatorPreference{ + { + ValOperAddress: validator0.OperatorAddress, + Weight: sdk.MustNewDecFromStr("0.333333333333333333"), + }, + { + Weight: sdk.MustNewDecFromStr("0.666666666666666667"), + ValOperAddress: validator1.OperatorAddress, + }, + }, + } + } + + // system under test + valsetPref, err := s.App.ValidatorSetPreferenceKeeper.GetValSetPreferencesWithDelegations(s.Ctx, delegator.String()) + + if test.expectedErr { + s.Require().Error(err) + } else { + s.Require().NoError(err) + for _, valset := range valsetPref.Preferences { + for _, expectedvalSet := range expectedValsetPref.Preferences { + if valset.ValOperAddress == expectedvalSet.ValOperAddress { + s.Require().True(valset.Weight.Equal(expectedvalSet.Weight)) + } + } + } + } + }) + } +} + +func (s *KeeperTestSuite) TestFormatToValPrefArr() { + s.SetupTest() + + // prepare existing delegations validators + valAddrs := s.SetupMultipleValidators(3) + + tests := []struct { + name string + delegations []stakingtypes.Delegation + expectedValPrefs []types.ValidatorPreference + }{ + { + name: "Single delegation", + delegations: []stakingtypes.Delegation{ + { + ValidatorAddress: valAddrs[0], + Shares: sdk.NewDec(100), + }, + }, + expectedValPrefs: []types.ValidatorPreference{ + { + ValOperAddress: valAddrs[0], + Weight: sdk.NewDec(1), + }, + }, + }, + { + name: "Multiple Delegations", + delegations: []stakingtypes.Delegation{ + { + ValidatorAddress: valAddrs[0], + Shares: sdk.NewDec(100), + }, + { + ValidatorAddress: valAddrs[1], + Shares: sdk.NewDec(200), + }, + }, + expectedValPrefs: []types.ValidatorPreference{ + { + ValOperAddress: valAddrs[0], + Weight: sdk.MustNewDecFromStr("0.333333333333333333"), + }, + { + ValOperAddress: valAddrs[1], + Weight: sdk.MustNewDecFromStr("0.666666666666666667"), + }, + }, + }, + { + name: "No Delegation", + delegations: []stakingtypes.Delegation{}, + expectedValPrefs: []types.ValidatorPreference{}, + }, + } + + for _, test := range tests { + s.Run(test.name, func() { + s.Setup() + + // system under test + actualPrefArr := valPref.FormatToValPrefArr(test.delegations) + + s.Require().Equal(actualPrefArr, test.expectedValPrefs) + }) + } +} + // SetupValidatorsAndDelegations sets up existing delegation by creating a certain number of validators and delegating tokenAmt to them. func (s *KeeperTestSuite) SetupValidatorsAndDelegations() ([]string, []types.ValidatorPreference, sdk.Coins) { // prepare existing delegations validators diff --git a/x/valset-pref/msg_server.go b/x/valset-pref/msg_server.go index 53da7e7c0a4..d9302ee99ab 100644 --- a/x/valset-pref/msg_server.go +++ b/x/valset-pref/msg_server.go @@ -26,7 +26,7 @@ var _ types.MsgServer = msgServer{} func (server msgServer) SetValidatorSetPreference(goCtx context.Context, msg *types.MsgSetValidatorSetPreference) (*types.MsgSetValidatorSetPreferenceResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - preferences, err := server.keeper.SetValidatorSetPreference(ctx, msg.Delegator, msg.Preferences) + preferences, err := server.keeper.ValidateValidatorSetPreference(ctx, msg.Delegator, msg.Preferences) if err != nil { return nil, err } @@ -49,14 +49,27 @@ func (server msgServer) DelegateToValidatorSet(goCtx context.Context, msg *types // UndelegateFromValidatorSet undelegates {coin} amount from the validator set. func (server msgServer) UndelegateFromValidatorSet(goCtx context.Context, msg *types.MsgUndelegateFromValidatorSet) (*types.MsgUndelegateFromValidatorSetResponse, error) { + // ctx := sdk.UnwrapSDKContext(goCtx) + + // err := server.keeper.UndelegateFromValidatorSet(ctx, msg.Delegator, msg.Coin) + // if err != nil { + // return nil, err + // } + + return &types.MsgUndelegateFromValidatorSetResponse{}, fmt.Errorf("not implemented, utilize UndelegateFromRebalancedValidatorSet instead") +} + +// UndelegateFromRebalancedValidatorSet undelegates {coin} amount from the validator set, utilizing a user's current delegations +// to their validator set to determine the weights. +func (server msgServer) UndelegateFromRebalancedValidatorSet(goCtx context.Context, msg *types.MsgUndelegateFromRebalancedValidatorSet) (*types.MsgUndelegateFromRebalancedValidatorSetResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - err := server.keeper.UndelegateFromValidatorSet(ctx, msg.Delegator, msg.Coin) + err := server.keeper.UndelegateFromRebalancedValidatorSet(ctx, msg.Delegator, msg.Coin) if err != nil { return nil, err } - return &types.MsgUndelegateFromValidatorSetResponse{}, nil + return &types.MsgUndelegateFromRebalancedValidatorSetResponse{}, nil } // RedelegateValidatorSet allows delegators to set a new validator set and switch validators. @@ -75,7 +88,7 @@ func (server msgServer) RedelegateValidatorSet(goCtx context.Context, msg *types } // Message 1: override the validator set preference set entry - newPreferences, err := server.keeper.SetValidatorSetPreference(ctx, msg.Delegator, msg.Preferences) + newPreferences, err := server.keeper.ValidateValidatorSetPreference(ctx, msg.Delegator, msg.Preferences) if err != nil { return nil, err } @@ -110,7 +123,7 @@ func (server msgServer) DelegateBondedTokens(goCtx context.Context, msg *types.M // get the existingValSet if it exists, if not check existingStakingPosition and return it _, err := server.keeper.GetDelegationPreferences(ctx, msg.Delegator) if err != nil { - return nil, fmt.Errorf("user %s doesn't have validator set", msg.Delegator) + return nil, types.NoValidatorSetOrExistingDelegationsError{DelegatorAddr: msg.Delegator} } // Message 1: force unlock bonded osmo tokens. diff --git a/x/valset-pref/msg_server_test.go b/x/valset-pref/msg_server_test.go index 821ac8ac687..aaf45c7f698 100644 --- a/x/valset-pref/msg_server_test.go +++ b/x/valset-pref/msg_server_test.go @@ -1,7 +1,10 @@ package keeper_test import ( + "sort" + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/osmosis-labs/osmosis/osmomath" appParams "github.com/osmosis-labs/osmosis/v20/app/params" @@ -304,82 +307,393 @@ func (s *KeeperTestSuite) TestDelegateToValidatorSet() { } } -func (s *KeeperTestSuite) TestUnDelegateFromValidatorSet() { +// TODO: Re-enable +// https://github.com/osmosis-labs/osmosis/issues/6686 + +// func (s *KeeperTestSuite) TestUnDelegateFromValidatorSet() { +// s.SetupTest() + +// // prepare an extra validator +// extraValidator := s.SetupValidator(stakingtypes.Bonded) + +// // valset test setup +// valAddrs, preferences, amountToFund := s.SetupValidatorsAndDelegations() + +// tests := []struct { +// name string +// delegator sdk.AccAddress +// coinToStake sdk.Coin // stake with default weights of 0.2, 0.33, 0.12, 0.35 +// addToStakeCoins sdk.Coin +// coinToUnStake sdk.Coin +// expectedSharesToUndelegate []osmomath.Dec // expected shares to undelegate + +// addToNormalStake bool +// addToValSetStake bool +// setValSet bool +// setExistingDelegations bool +// expectPass bool +// }{ +// { +// name: "Unstake half from the ValSet", +// delegator: sdk.AccAddress([]byte("addr1---------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), // delegate 20osmo +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), // undelegate 10osmo +// expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(3_500_000), sdk.NewDec(3_300_000), sdk.NewDec(2_000_000), sdk.NewDec(1_200_000)}, + +// setValSet: true, +// expectPass: true, +// }, +// { +// name: "Unstake x amount from ValSet", +// delegator: sdk.AccAddress([]byte("addr2---------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), // delegate 20osmo +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(15_000_000)), // undelegate 15osmo +// expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(5_250_000), sdk.NewDec(4_950_000), sdk.NewDec(3_000_000), sdk.NewDec(1_800_000)}, // (weight * coinToUnstake) + +// setValSet: true, +// expectPass: true, +// }, +// { +// name: "Unstake everything", +// delegator: sdk.AccAddress([]byte("addr3---------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), +// expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(7_000_000), sdk.NewDec(6_600_000), sdk.NewDec(4_000_000), sdk.NewDec(2_400_000)}, // (weight * coinToUnstake) + +// setValSet: true, +// expectPass: true, +// }, +// { +// name: "UnDelegate x amount from existing staking position (non valSet) ", +// delegator: sdk.AccAddress([]byte("addr4---------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), +// expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(6_666_668), sdk.NewDec(6_666_666), sdk.NewDec(6_666_666)}, // (weight * coinToUnstake) + +// setExistingDelegations: true, +// expectPass: true, +// }, +// { +// name: "Undelegate extreme amounts to check truncation, large amount", +// delegator: sdk.AccAddress([]byte("addr5---------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100_000_000)), +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(87_461_351)), +// expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(30_611_472), sdk.NewDec(28_862_247), sdk.NewDec(17_492_270), sdk.NewDec(10_495_362)}, // (weight * coinToUnstake), for ex: (0.2 * 87_461_351) + +// setValSet: true, +// expectPass: true, +// }, +// { +// name: "Undelegate extreme amounts to check truncation, small amount", +// delegator: sdk.AccAddress([]byte("addr6---------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1234)), +// expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(431), sdk.NewDec(407), sdk.NewDec(248), sdk.NewDec(148)}, // (weight * coinToUnstake), + +// setValSet: true, +// expectPass: true, +// }, +// { +// name: "Delegate using Valset + normal delegate -> Undelegate ALL", +// delegator: sdk.AccAddress([]byte("addr7---------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), +// addToStakeCoins: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), +// expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(10_000_000), sdk.NewDec(3_500_000), sdk.NewDec(3_300_000), sdk.NewDec(2_000_000), sdk.NewDec(1_200_000)}, + +// addToNormalStake: true, +// setValSet: true, +// expectPass: true, +// }, +// { +// name: "Delegate using Valset + normal delegate -> Undelegate Partial", +// delegator: sdk.AccAddress([]byte("addr8---------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), // 0.2, 0.33, 0.12, 0.35 +// addToStakeCoins: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), +// expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(7_500_000), sdk.NewDec(2_625_000), sdk.NewDec(2_475_000), sdk.NewDec(1_500_000), sdk.NewDec(900_000)}, +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(15_000_000)), + +// addToNormalStake: true, +// setValSet: true, +// expectPass: true, +// }, + +// { +// name: "Delegate using Valset + normal delegate to same validator in valset -> Undelegate Partial", +// delegator: sdk.AccAddress([]byte("addr9---------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), // 0.2, 0.33, 0.12, 0.35 +// addToStakeCoins: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(15_000_000)), +// expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(9_000_000), sdk.NewDec(2_625_000), sdk.NewDec(2_475_000), sdk.NewDec(900_000)}, + +// addToValSetStake: true, +// setValSet: true, +// expectPass: true, +// }, + +// { +// name: "Delegate using Valset + normal delegate to same validator in valset -> Undelegate ALL", +// delegator: sdk.AccAddress([]byte("addr10--------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), // 0.2, 0.33, 0.12, 0.35 +// addToStakeCoins: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), +// expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(12_000_000), sdk.NewDec(3_500_000), sdk.NewDec(3_300_000), sdk.NewDec(1_200_000)}, + +// addToValSetStake: true, +// setValSet: true, +// expectPass: true, +// }, + +// // Error cases + +// { +// name: "Error Case: Unstake more amount than the staked amount", +// delegator: sdk.AccAddress([]byte("addr11--------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(40_000_000)), + +// setValSet: true, +// expectPass: false, +// }, + +// { +// name: "Error Case: No ValSet and No delegation", +// delegator: sdk.AccAddress([]byte("addr12--------------")), +// coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), +// coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(40_000_000)), + +// expectPass: false, +// }, +// } + +// for _, test := range tests { +// s.Run(test.name, func() { +// s.FundAcc(test.delegator, amountToFund) // 100 osmo + +// // setup message server +// msgServer := valPref.NewMsgServerImpl(s.App.ValidatorSetPreferenceKeeper) +// c := sdk.WrapSDKContext(s.Ctx) + +// if test.setValSet { +// // SetValidatorSetPreference sets a new list of val-set +// _, err := msgServer.SetValidatorSetPreference(c, types.NewMsgSetValidatorSetPreference(test.delegator, preferences)) +// s.Require().NoError(err) + +// // DelegateToValidatorSet delegate to existing val-set +// _, err = msgServer.DelegateToValidatorSet(c, types.NewMsgDelegateToValidatorSet(test.delegator, test.coinToStake)) +// s.Require().NoError(err) +// } + +// if test.setExistingDelegations { +// err := s.PrepareExistingDelegations(s.Ctx, valAddrs, test.delegator, test.coinToStake.Amount) +// s.Require().NoError(err) +// } + +// if test.addToNormalStake { +// validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, extraValidator) +// s.Require().True(found) + +// // Delegate more token to the validator, this means there is existing Valset delegation as well as regular staking delegation +// _, err := s.App.StakingKeeper.Delegate(s.Ctx, test.delegator, test.addToStakeCoins.Amount, stakingtypes.Unbonded, validator, true) +// s.Require().NoError(err) +// } + +// if test.addToValSetStake { +// valAddr, err := sdk.ValAddressFromBech32(preferences[0].ValOperAddress) +// s.Require().NoError(err) + +// validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) +// s.Require().True(found) + +// // Delegate more token to the validator, this means there is existing Valset delegation as well as regular staking delegation +// _, err = s.App.StakingKeeper.Delegate(s.Ctx, test.delegator, test.addToStakeCoins.Amount, stakingtypes.Unbonded, validator, true) +// s.Require().NoError(err) +// } + +// _, err := msgServer.UndelegateFromValidatorSet(c, types.NewMsgUndelegateFromValidatorSet(test.delegator, test.coinToUnStake)) +// if test.expectPass { +// s.Require().NoError(err) + +// // extra validator + valSets +// var vals []sdk.ValAddress +// if test.addToNormalStake { +// vals = []sdk.ValAddress{extraValidator} +// } +// for _, val := range preferences { +// vals = append(vals, sdk.ValAddress(val.ValOperAddress)) +// } + +// var unbondingDelsAmt []sdk.Dec +// unbondingDels := s.App.StakingKeeper.GetAllUnbondingDelegations(s.Ctx, test.delegator) +// for i := range unbondingDels { +// unbondingDelsAmt = append(unbondingDelsAmt, sdk.NewDec(unbondingDels[i].Entries[0].Balance.Int64())) +// } + +// sort.Slice(unbondingDelsAmt, func(i, j int) bool { +// return unbondingDelsAmt[i].GT(unbondingDelsAmt[j]) +// }) + +// s.Require().Equal(test.expectedSharesToUndelegate, unbondingDelsAmt) +// } else { +// s.Require().Error(err) +// } +// }) +// } +// } + +func (s *KeeperTestSuite) TestUnDelegateFromRebalancedValidatorSet() { s.SetupTest() + // prepare an extra validator + extraValidator := s.SetupValidator(stakingtypes.Bonded) + // valset test setup valAddrs, preferences, amountToFund := s.SetupValidatorsAndDelegations() tests := []struct { - name string - delegator sdk.AccAddress - coinToStake sdk.Coin - coinToUnStake sdk.Coin - expectedShares []osmomath.Dec // expected shares after undelegation + name string + delegator sdk.AccAddress + coinToStake sdk.Coin // stake with default weights of 0.2, 0.33, 0.12, 0.35 + addToStakeCoins sdk.Coin + coinToUnStake sdk.Coin + expectedSharesToUndelegate []osmomath.Dec // expected shares to undelegate + + addToNormalStake bool + addToValSetStake bool setValSet bool setExistingDelegations bool expectPass bool }{ { - name: "Unstake half from the ValSet", - delegator: sdk.AccAddress([]byte("addr1---------------")), - coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(20_000_000)), // delegate 20osmo - coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(10_000_000)), // undelegate 10osmo - expectedShares: []osmomath.Dec{osmomath.NewDec(2_000_000), osmomath.NewDec(3_300_000), osmomath.NewDec(1_200_000), osmomath.NewDec(3_500_000)}, - setValSet: true, - expectPass: true, - }, - { - name: "Unstake x amount from ValSet", - delegator: sdk.AccAddress([]byte("addr2---------------")), - coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(20_000_000)), // delegate 20osmo - coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(15_000_000)), // undelegate 15osmo - expectedShares: []osmomath.Dec{osmomath.NewDec(1_000_000), osmomath.NewDec(1_650_000), osmomath.NewDec(600_000), osmomath.NewDec(1_750_000)}, // validatorDelegatedShares - (weight * coinToUnstake) - setValSet: true, - expectPass: true, - }, - { - name: "Unstake everything", - delegator: sdk.AccAddress([]byte("addr3---------------")), - coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(20_000_000)), - coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(20_000_000)), - setValSet: true, - expectPass: true, - }, - { - name: "Unstake more amount than the staked amount", - delegator: sdk.AccAddress([]byte("addr4---------------")), - coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(20_000_000)), - coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(40_000_000)), - setValSet: true, - expectPass: false, - }, - { - name: "UnDelegate from existing staking position (non valSet) ", - delegator: sdk.AccAddress([]byte("addr5---------------")), - coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(10_000_000)), - coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(10_000_000)), - expectedShares: []osmomath.Dec{osmomath.NewDec(1_000_000), osmomath.NewDec(1_660_000), osmomath.NewDec(600_000), osmomath.NewDec(1_740_000)}, // validatorDelegatedShares - (weight * coinToUnstake) + name: "Unstake half from the ValSet", + delegator: sdk.AccAddress([]byte("addr1---------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), // delegate 20osmo + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), // undelegate 10osmo + expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(3_500_000), sdk.NewDec(3_300_000), sdk.NewDec(2_000_000), sdk.NewDec(1_200_000)}, + + setValSet: true, + expectPass: true, + }, + { + name: "Unstake x amount from ValSet", + delegator: sdk.AccAddress([]byte("addr2---------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), // delegate 20osmo + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(15_000_000)), // undelegate 15osmo + expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(5_250_000), sdk.NewDec(4_950_000), sdk.NewDec(3_000_000), sdk.NewDec(1_800_000)}, // (weight * coinToUnstake) + + setValSet: true, + expectPass: true, + }, + { + name: "Unstake everything", + delegator: sdk.AccAddress([]byte("addr3---------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), + expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(7_000_000), sdk.NewDec(6_600_000), sdk.NewDec(4_000_000), sdk.NewDec(2_400_000)}, // (weight * coinToUnstake) + + setValSet: true, + expectPass: true, + }, + { + name: "UnDelegate x amount from existing staking position (non valSet) ", + delegator: sdk.AccAddress([]byte("addr4---------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), + expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(6_666_668), sdk.NewDec(6_666_666), sdk.NewDec(6_666_666)}, // (weight * coinToUnstake) + setExistingDelegations: true, expectPass: true, }, { - name: "Undelegate extreme amounts to check truncation, large amount", - delegator: sdk.AccAddress([]byte("addr6---------------")), - coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(100_000_000)), - coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(87_461_351)), - expectedShares: []osmomath.Dec{osmomath.NewDec(2_507_730), osmomath.NewDec(4_137_755), osmomath.NewDec(1_504_638), osmomath.NewDec(4_388_526)}, // validatorDelegatedShares - (weight * coinToUnstake), for ex: 20_000_000 - (0.2 * 87_461_351) - setValSet: true, - expectPass: true, + name: "Undelegate extreme amounts to check truncation, large amount", + delegator: sdk.AccAddress([]byte("addr5---------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100_000_000)), + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(87_461_351)), + expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(30_611_472), sdk.NewDec(28_862_247), sdk.NewDec(17_492_270), sdk.NewDec(10_495_362)}, // (weight * coinToUnstake), for ex: (0.2 * 87_461_351) + + setValSet: true, + expectPass: true, + }, + { + name: "Undelegate extreme amounts to check truncation, small amount", + delegator: sdk.AccAddress([]byte("addr6---------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1234)), + expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(431), sdk.NewDec(407), sdk.NewDec(248), sdk.NewDec(148)}, // (weight * coinToUnstake), + + setValSet: true, + expectPass: true, + }, + { + name: "Delegate using Valset + normal delegate -> Undelegate ALL", + delegator: sdk.AccAddress([]byte("addr7---------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), + addToStakeCoins: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), + expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(10_000_000), sdk.NewDec(3_500_000), sdk.NewDec(3_300_000), sdk.NewDec(2_000_000), sdk.NewDec(1_200_000)}, + + addToNormalStake: true, + setValSet: true, + expectPass: true, + }, + { + name: "Delegate using Valset + normal delegate -> Undelegate Partial", + delegator: sdk.AccAddress([]byte("addr8---------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), // 0.2, 0.33, 0.12, 0.35 + addToStakeCoins: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), + expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(7_500_000), sdk.NewDec(2_625_000), sdk.NewDec(2_475_000), sdk.NewDec(1_500_000), sdk.NewDec(900_000)}, + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(15_000_000)), + + addToNormalStake: true, + setValSet: true, + expectPass: true, + }, + + { + name: "Delegate using Valset + normal delegate to same validator in valset -> Undelegate Partial", + delegator: sdk.AccAddress([]byte("addr9---------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), // 0.2, 0.33, 0.12, 0.35 + addToStakeCoins: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(15_000_000)), + expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(9_000_000), sdk.NewDec(2_625_000), sdk.NewDec(2_475_000), sdk.NewDec(900_000)}, + + addToValSetStake: true, + setValSet: true, + expectPass: true, + }, + + { + name: "Delegate using Valset + normal delegate to same validator in valset -> Undelegate ALL", + delegator: sdk.AccAddress([]byte("addr10--------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), // 0.2, 0.33, 0.12, 0.35 + addToStakeCoins: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), + expectedSharesToUndelegate: []sdk.Dec{sdk.NewDec(12_000_000), sdk.NewDec(3_500_000), sdk.NewDec(3_300_000), sdk.NewDec(1_200_000)}, + + addToValSetStake: true, + setValSet: true, + expectPass: true, }, + + // Error cases + { - name: "Undelegate extreme amounts to check truncation, small amount", - delegator: sdk.AccAddress([]byte("addr7---------------")), - coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(10_000_000)), - coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, osmomath.NewInt(1234)), - expectedShares: []osmomath.Dec{osmomath.NewDec(1_999_754), osmomath.NewDec(3_299_593), osmomath.NewDec(1_199_852), osmomath.NewDec(3_499_567)}, // validatorDelegatedShares - (weight * coinToUnstake), - setValSet: true, - expectPass: true, + name: "Error Case: Unstake more amount than the staked amount", + delegator: sdk.AccAddress([]byte("addr11--------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(40_000_000)), + + setValSet: true, + expectPass: false, + }, + + { + name: "Error Case: No ValSet and No delegation", + delegator: sdk.AccAddress([]byte("addr12--------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)), + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(40_000_000)), + + expectPass: false, }, } @@ -406,21 +720,51 @@ func (s *KeeperTestSuite) TestUnDelegateFromValidatorSet() { s.Require().NoError(err) } - _, err := msgServer.UndelegateFromValidatorSet(c, types.NewMsgUndelegateFromValidatorSet(test.delegator, test.coinToUnStake)) + if test.addToNormalStake { + validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, extraValidator) + s.Require().True(found) + + // Delegate more token to the validator, this means there is existing Valset delegation as well as regular staking delegation + _, err := s.App.StakingKeeper.Delegate(s.Ctx, test.delegator, test.addToStakeCoins.Amount, stakingtypes.Unbonded, validator, true) + s.Require().NoError(err) + } + + if test.addToValSetStake { + valAddr, err := sdk.ValAddressFromBech32(preferences[0].ValOperAddress) + s.Require().NoError(err) + + validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) + s.Require().True(found) + + // Delegate more token to the validator, this means there is existing Valset delegation as well as regular staking delegation + _, err = s.App.StakingKeeper.Delegate(s.Ctx, test.delegator, test.addToStakeCoins.Amount, stakingtypes.Unbonded, validator, true) + s.Require().NoError(err) + } + + _, err := msgServer.UndelegateFromRebalancedValidatorSet(c, types.NewMsgUndelegateFromRebalancedValidatorSet(test.delegator, test.coinToUnStake)) if test.expectPass { s.Require().NoError(err) - // check if the expectedShares matches after undelegation - for i, val := range preferences { - valAddr, err := sdk.ValAddressFromBech32(val.ValOperAddress) - s.Require().NoError(err) + // extra validator + valSets + var vals []sdk.ValAddress + if test.addToNormalStake { + vals = []sdk.ValAddress{extraValidator} + } + for _, val := range preferences { + vals = append(vals, sdk.ValAddress(val.ValOperAddress)) + } - // guarantees that the delegator exists because we check it in UnDelegateToValidatorSet - del, found := s.App.StakingKeeper.GetDelegation(s.Ctx, test.delegator, valAddr) - if found { - s.Require().Equal(test.expectedShares[i], del.GetShares()) - } + var unbondingDelsAmt []sdk.Dec + unbondingDels := s.App.StakingKeeper.GetAllUnbondingDelegations(s.Ctx, test.delegator) + for i := range unbondingDels { + unbondingDelsAmt = append(unbondingDelsAmt, sdk.NewDec(unbondingDels[i].Entries[0].Balance.Int64())) } + + sort.Slice(unbondingDelsAmt, func(i, j int) bool { + return unbondingDelsAmt[i].GT(unbondingDelsAmt[j]) + }) + + s.Require().Equal(test.expectedSharesToUndelegate, unbondingDelsAmt) } else { s.Require().Error(err) } diff --git a/x/valset-pref/types/errors.go b/x/valset-pref/types/errors.go index 0d2b988e047..941918bd4c2 100644 --- a/x/valset-pref/types/errors.go +++ b/x/valset-pref/types/errors.go @@ -1,7 +1,37 @@ package types -import "errors" +import ( + "errors" + fmt "fmt" + + "cosmossdk.io/math" +) var ( ErrNoDelegation = errors.New("No existing delegation") ) + +type UndelegateMoreThanDelegatedError struct { + TotalDelegatedAmt math.LegacyDec + UndelegationAmt math.Int +} + +func (e UndelegateMoreThanDelegatedError) Error() string { + return fmt.Sprintf("total tokenAmountToUndelegate more than delegated amount have %s got %s\n", e.TotalDelegatedAmt, e.UndelegationAmt) +} + +type NoValidatorSetOrExistingDelegationsError struct { + DelegatorAddr string +} + +func (e NoValidatorSetOrExistingDelegationsError) Error() string { + return fmt.Sprintf("user %s doesn't have validator set or existing delegations", e.DelegatorAddr) +} + +type ValsetRatioGreaterThanOneError struct { + ValsetRatio math.LegacyDec +} + +func (e ValsetRatioGreaterThanOneError) Error() string { + return fmt.Sprintf("valset ratio %s greater than one", e.ValsetRatio) +} diff --git a/x/valset-pref/types/msgs.go b/x/valset-pref/types/msgs.go index 93abfdcd7e6..9acdf257f42 100644 --- a/x/valset-pref/types/msgs.go +++ b/x/valset-pref/types/msgs.go @@ -156,6 +156,47 @@ func (m MsgUndelegateFromValidatorSet) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{delegator} } +// constants +const ( + TypeMsgUndelegateFromRebalancedValidatorSet = "undelegate_from_rebalanced_validator_set" +) + +var _ sdk.Msg = &MsgUndelegateFromRebalancedValidatorSet{} + +// NewMsgUndelegateFromRebalancedValidatorSet creates a msg to undelegated from a rebalanced validator set. +func NewMsgUndelegateFromRebalancedValidatorSet(delegator sdk.AccAddress, coin sdk.Coin) *MsgUndelegateFromRebalancedValidatorSet { + return &MsgUndelegateFromRebalancedValidatorSet{ + Delegator: delegator.String(), + Coin: coin, + } +} + +func (m MsgUndelegateFromRebalancedValidatorSet) Route() string { return RouterKey } +func (m MsgUndelegateFromRebalancedValidatorSet) Type() string { + return TypeMsgUndelegateFromRebalancedValidatorSet +} +func (m MsgUndelegateFromRebalancedValidatorSet) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(m.Delegator) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) + } + + if !m.Coin.IsValid() { + return fmt.Errorf("The stake coin is not valid") + } + + return nil +} + +func (m MsgUndelegateFromRebalancedValidatorSet) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +func (m MsgUndelegateFromRebalancedValidatorSet) GetSigners() []sdk.AccAddress { + delegator, _ := sdk.AccAddressFromBech32(m.Delegator) + return []sdk.AccAddress{delegator} +} + // constants const ( TypeMsgRedelegateValidatorSet = "redelegate_validator_set" diff --git a/x/valset-pref/types/tx.pb.go b/x/valset-pref/types/tx.pb.go index 305ef49b258..ceaf0def873 100644 --- a/x/valset-pref/types/tx.pb.go +++ b/x/valset-pref/types/tx.pb.go @@ -311,6 +311,108 @@ func (m *MsgUndelegateFromValidatorSetResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgUndelegateFromValidatorSetResponse proto.InternalMessageInfo +type MsgUndelegateFromRebalancedValidatorSet struct { + // delegator is the user who is trying to undelegate. + Delegator string `protobuf:"bytes,1,opt,name=delegator,proto3" json:"delegator,omitempty" yaml:"delegator"` + // the amount the user wants to undelegate + // For ex: Undelegate 50 osmo with validator-set {ValA -> 0.5, ValB -> 0.5} + // Our undelegate logic would first check the current delegation balance. + // If the user has 90 osmo delegated to ValA and 10 osmo delegated to ValB, + // the rebalanced validator set would be {ValA -> 0.9, ValB -> 0.1} + // So now the 45 osmo would be undelegated from ValA and 5 osmo would be + // undelegated from ValB. + Coin types.Coin `protobuf:"bytes,2,opt,name=coin,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coin" json:"coin"` +} + +func (m *MsgUndelegateFromRebalancedValidatorSet) Reset() { + *m = MsgUndelegateFromRebalancedValidatorSet{} +} +func (m *MsgUndelegateFromRebalancedValidatorSet) String() string { return proto.CompactTextString(m) } +func (*MsgUndelegateFromRebalancedValidatorSet) ProtoMessage() {} +func (*MsgUndelegateFromRebalancedValidatorSet) Descriptor() ([]byte, []int) { + return fileDescriptor_daa95be02b2fc560, []int{6} +} +func (m *MsgUndelegateFromRebalancedValidatorSet) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUndelegateFromRebalancedValidatorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUndelegateFromRebalancedValidatorSet.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 *MsgUndelegateFromRebalancedValidatorSet) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUndelegateFromRebalancedValidatorSet.Merge(m, src) +} +func (m *MsgUndelegateFromRebalancedValidatorSet) XXX_Size() int { + return m.Size() +} +func (m *MsgUndelegateFromRebalancedValidatorSet) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUndelegateFromRebalancedValidatorSet.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUndelegateFromRebalancedValidatorSet proto.InternalMessageInfo + +func (m *MsgUndelegateFromRebalancedValidatorSet) GetDelegator() string { + if m != nil { + return m.Delegator + } + return "" +} + +func (m *MsgUndelegateFromRebalancedValidatorSet) GetCoin() types.Coin { + if m != nil { + return m.Coin + } + return types.Coin{} +} + +type MsgUndelegateFromRebalancedValidatorSetResponse struct { +} + +func (m *MsgUndelegateFromRebalancedValidatorSetResponse) Reset() { + *m = MsgUndelegateFromRebalancedValidatorSetResponse{} +} +func (m *MsgUndelegateFromRebalancedValidatorSetResponse) String() string { + return proto.CompactTextString(m) +} +func (*MsgUndelegateFromRebalancedValidatorSetResponse) ProtoMessage() {} +func (*MsgUndelegateFromRebalancedValidatorSetResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_daa95be02b2fc560, []int{7} +} +func (m *MsgUndelegateFromRebalancedValidatorSetResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUndelegateFromRebalancedValidatorSetResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUndelegateFromRebalancedValidatorSetResponse.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 *MsgUndelegateFromRebalancedValidatorSetResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUndelegateFromRebalancedValidatorSetResponse.Merge(m, src) +} +func (m *MsgUndelegateFromRebalancedValidatorSetResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgUndelegateFromRebalancedValidatorSetResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUndelegateFromRebalancedValidatorSetResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUndelegateFromRebalancedValidatorSetResponse proto.InternalMessageInfo + type MsgRedelegateValidatorSet struct { // delegator is the user who is trying to create a validator-set. Delegator string `protobuf:"bytes,1,opt,name=delegator,proto3" json:"delegator,omitempty" yaml:"delegator"` @@ -322,7 +424,7 @@ func (m *MsgRedelegateValidatorSet) Reset() { *m = MsgRedelegateValidato func (m *MsgRedelegateValidatorSet) String() string { return proto.CompactTextString(m) } func (*MsgRedelegateValidatorSet) ProtoMessage() {} func (*MsgRedelegateValidatorSet) Descriptor() ([]byte, []int) { - return fileDescriptor_daa95be02b2fc560, []int{6} + return fileDescriptor_daa95be02b2fc560, []int{8} } func (m *MsgRedelegateValidatorSet) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -372,7 +474,7 @@ func (m *MsgRedelegateValidatorSetResponse) Reset() { *m = MsgRedelegate func (m *MsgRedelegateValidatorSetResponse) String() string { return proto.CompactTextString(m) } func (*MsgRedelegateValidatorSetResponse) ProtoMessage() {} func (*MsgRedelegateValidatorSetResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_daa95be02b2fc560, []int{7} + return fileDescriptor_daa95be02b2fc560, []int{9} } func (m *MsgRedelegateValidatorSetResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -412,7 +514,7 @@ func (m *MsgWithdrawDelegationRewards) Reset() { *m = MsgWithdrawDelegat func (m *MsgWithdrawDelegationRewards) String() string { return proto.CompactTextString(m) } func (*MsgWithdrawDelegationRewards) ProtoMessage() {} func (*MsgWithdrawDelegationRewards) Descriptor() ([]byte, []int) { - return fileDescriptor_daa95be02b2fc560, []int{8} + return fileDescriptor_daa95be02b2fc560, []int{10} } func (m *MsgWithdrawDelegationRewards) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -455,7 +557,7 @@ func (m *MsgWithdrawDelegationRewardsResponse) Reset() { *m = MsgWithdra func (m *MsgWithdrawDelegationRewardsResponse) String() string { return proto.CompactTextString(m) } func (*MsgWithdrawDelegationRewardsResponse) ProtoMessage() {} func (*MsgWithdrawDelegationRewardsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_daa95be02b2fc560, []int{9} + return fileDescriptor_daa95be02b2fc560, []int{11} } func (m *MsgWithdrawDelegationRewardsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -498,7 +600,7 @@ func (m *MsgDelegateBondedTokens) Reset() { *m = MsgDelegateBondedTokens func (m *MsgDelegateBondedTokens) String() string { return proto.CompactTextString(m) } func (*MsgDelegateBondedTokens) ProtoMessage() {} func (*MsgDelegateBondedTokens) Descriptor() ([]byte, []int) { - return fileDescriptor_daa95be02b2fc560, []int{10} + return fileDescriptor_daa95be02b2fc560, []int{12} } func (m *MsgDelegateBondedTokens) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -548,7 +650,7 @@ func (m *MsgDelegateBondedTokensResponse) Reset() { *m = MsgDelegateBond func (m *MsgDelegateBondedTokensResponse) String() string { return proto.CompactTextString(m) } func (*MsgDelegateBondedTokensResponse) ProtoMessage() {} func (*MsgDelegateBondedTokensResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_daa95be02b2fc560, []int{11} + return fileDescriptor_daa95be02b2fc560, []int{13} } func (m *MsgDelegateBondedTokensResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -584,6 +686,8 @@ func init() { proto.RegisterType((*MsgDelegateToValidatorSetResponse)(nil), "osmosis.valsetpref.v1beta1.MsgDelegateToValidatorSetResponse") proto.RegisterType((*MsgUndelegateFromValidatorSet)(nil), "osmosis.valsetpref.v1beta1.MsgUndelegateFromValidatorSet") proto.RegisterType((*MsgUndelegateFromValidatorSetResponse)(nil), "osmosis.valsetpref.v1beta1.MsgUndelegateFromValidatorSetResponse") + proto.RegisterType((*MsgUndelegateFromRebalancedValidatorSet)(nil), "osmosis.valsetpref.v1beta1.MsgUndelegateFromRebalancedValidatorSet") + proto.RegisterType((*MsgUndelegateFromRebalancedValidatorSetResponse)(nil), "osmosis.valsetpref.v1beta1.MsgUndelegateFromRebalancedValidatorSetResponse") proto.RegisterType((*MsgRedelegateValidatorSet)(nil), "osmosis.valsetpref.v1beta1.MsgRedelegateValidatorSet") proto.RegisterType((*MsgRedelegateValidatorSetResponse)(nil), "osmosis.valsetpref.v1beta1.MsgRedelegateValidatorSetResponse") proto.RegisterType((*MsgWithdrawDelegationRewards)(nil), "osmosis.valsetpref.v1beta1.MsgWithdrawDelegationRewards") @@ -597,51 +701,54 @@ func init() { } var fileDescriptor_daa95be02b2fc560 = []byte{ - // 699 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x56, 0x4b, 0x4f, 0xd4, 0x5e, - 0x14, 0x9f, 0x0b, 0x84, 0x7f, 0xb8, 0x6c, 0xfe, 0x36, 0x04, 0xa1, 0xd1, 0x0e, 0x54, 0x5e, 0x92, - 0xd0, 0x2b, 0x43, 0x8c, 0x8a, 0x31, 0xd1, 0x91, 0x98, 0xb8, 0x98, 0x44, 0x0b, 0x6a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, - 0x91, 0x5a, 0xbd, 0x61, 0x85, 0x6a, 0xe5, 0x4f, 0x64, 0xdc, 0x58, 0xf2, 0x79, 0x2c, 0x6a, 0x2c, - 0x29, 0xb2, 0xb0, 0xb1, 0x0a, 0x87, 0x50, 0x79, 0x8d, 0xf0, 0x48, 0xcf, 0x11, 0x5c, 0xfa, 0xc5, - 0xfe, 0xc8, 0x82, 0xd4, 0xdb, 0x25, 0x40, 0x5d, 0x2a, 0xf5, 0xc7, 0xfb, 0xc7, 0x1a, 0x3a, 0x38, - 0xd6, 0xd0, 0xd7, 0x63, 0x0d, 0xbd, 0xeb, 0x68, 0x95, 0x83, 0x8e, 0x56, 0xf9, 0xd2, 0xd1, 0x2a, - 0xcf, 0x6f, 0x64, 0x5e, 0x31, 0x69, 0x82, 0x05, 0xcf, 0x6a, 0x32, 0x22, 0x2e, 0x50, 0xb5, 0x6b, - 0x64, 0xf7, 0xcc, 0x35, 0x2a, 0x7e, 0xef, 0x34, 0x07, 0xe3, 0xfb, 0xd3, 0xd2, 0xcf, 0x00, 0x00, - 0x00, 0xff, 0xff, 0xc4, 0xeb, 0x36, 0xdf, 0x16, 0x0a, 0x00, 0x00, + // 751 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x56, 0xcd, 0x4f, 0xd4, 0x4c, + 0x18, 0xdf, 0x01, 0x42, 0x5e, 0x86, 0xcb, 0xfb, 0x36, 0x84, 0x17, 0x1a, 0xed, 0x42, 0x05, 0x16, + 0x49, 0xe8, 0xc8, 0xa2, 0x51, 0x31, 0x26, 0xba, 0x10, 0x13, 0x63, 0x36, 0xd1, 0x82, 0x9a, 0x78, + 0x30, 0x99, 0x6e, 0x87, 0xd2, 0xd0, 0x76, 0x36, 0x9d, 0xe1, 0xeb, 0xe0, 0xdd, 0x78, 0x30, 0xde, + 0x4c, 0xfc, 0x13, 0x3c, 0x79, 0xf4, 0xe4, 0x99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, 0xdc, 0x7b, 0x00, + 0xc7, 0x4e, 0x25, 0x9a, 0xf3, 0x3f, 0x55, 0x2b, 0x3d, 0x89, 0x7c, 0xef, 0x0c, 0x92, 0x1c, 0x1b, + 0x74, 0x86, 0x8c, 0x15, 0x0d, 0x3a, 0x3d, 0xac, 0x70, 0xd0, 0xf9, 0x62, 0x12, 0xee, 0x44, 0xb6, + 0x94, 0x14, 0xed, 0x44, 0x66, 0x64, 0xe1, 0x4e, 0x14, 0xea, 0x87, 0xf4, 0x1c, 0xc0, 0x81, 0x54, + 0xf5, 0x98, 0x3d, 0xe5, 0xd1, 0x4e, 0x06, 0xc9, 0x37, 0x4a, 0x04, 0x75, 0xa0, 0x34, 0x1e, 0x6c, + 0xef, 0x2b, 0x60, 0x67, 0x5f, 0x01, 0x9f, 0xf7, 0x15, 0xf0, 0xea, 0x40, 0xa9, 0xec, 0x1c, 0x28, + 0x95, 0x4f, 0x07, 0x4a, 0xe5, 0xc9, 0xd5, 0xc4, 0x8d, 0x19, 0x17, 0x98, 0x76, 0xb0, 0xc1, 0xc4, + 0xad, 0xb8, 0x5e, 0xbf, 0x84, 0x36, 0x8f, 0xbd, 0x2a, 0x87, 0xd7, 0xa8, 0xd1, 0x1b, 0xbe, 0x23, + 0xcf, 0xfe, 0x08, 0x00, 0x00, 0xff, 0xff, 0xa2, 0x40, 0x19, 0xbc, 0xfa, 0x0b, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -666,6 +773,10 @@ type MsgClient interface { // validator-set. The unbonding logic will follow the `Undelegate` logic from // the sdk. UndelegateFromValidatorSet(ctx context.Context, in *MsgUndelegateFromValidatorSet, opts ...grpc.CallOption) (*MsgUndelegateFromValidatorSetResponse, error) + // UndelegateFromRebalancedValidatorSet undelegates the proivded amount from + // the validator set, but takes into consideration the current delegations + // to the user's validator set to determine the weights assigned to each. + UndelegateFromRebalancedValidatorSet(ctx context.Context, in *MsgUndelegateFromRebalancedValidatorSet, opts ...grpc.CallOption) (*MsgUndelegateFromRebalancedValidatorSetResponse, error) // RedelegateValidatorSet takes the existing validator set and redelegates to // a new set. RedelegateValidatorSet(ctx context.Context, in *MsgRedelegateValidatorSet, opts ...grpc.CallOption) (*MsgRedelegateValidatorSetResponse, error) @@ -712,6 +823,15 @@ func (c *msgClient) UndelegateFromValidatorSet(ctx context.Context, in *MsgUndel return out, nil } +func (c *msgClient) UndelegateFromRebalancedValidatorSet(ctx context.Context, in *MsgUndelegateFromRebalancedValidatorSet, opts ...grpc.CallOption) (*MsgUndelegateFromRebalancedValidatorSetResponse, error) { + out := new(MsgUndelegateFromRebalancedValidatorSetResponse) + err := c.cc.Invoke(ctx, "/osmosis.valsetpref.v1beta1.Msg/UndelegateFromRebalancedValidatorSet", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *msgClient) RedelegateValidatorSet(ctx context.Context, in *MsgRedelegateValidatorSet, opts ...grpc.CallOption) (*MsgRedelegateValidatorSetResponse, error) { out := new(MsgRedelegateValidatorSetResponse) err := c.cc.Invoke(ctx, "/osmosis.valsetpref.v1beta1.Msg/RedelegateValidatorSet", in, out, opts...) @@ -751,6 +871,10 @@ type MsgServer interface { // validator-set. The unbonding logic will follow the `Undelegate` logic from // the sdk. UndelegateFromValidatorSet(context.Context, *MsgUndelegateFromValidatorSet) (*MsgUndelegateFromValidatorSetResponse, error) + // UndelegateFromRebalancedValidatorSet undelegates the proivded amount from + // the validator set, but takes into consideration the current delegations + // to the user's validator set to determine the weights assigned to each. + UndelegateFromRebalancedValidatorSet(context.Context, *MsgUndelegateFromRebalancedValidatorSet) (*MsgUndelegateFromRebalancedValidatorSetResponse, error) // RedelegateValidatorSet takes the existing validator set and redelegates to // a new set. RedelegateValidatorSet(context.Context, *MsgRedelegateValidatorSet) (*MsgRedelegateValidatorSetResponse, error) @@ -775,6 +899,9 @@ func (*UnimplementedMsgServer) DelegateToValidatorSet(ctx context.Context, req * func (*UnimplementedMsgServer) UndelegateFromValidatorSet(ctx context.Context, req *MsgUndelegateFromValidatorSet) (*MsgUndelegateFromValidatorSetResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method UndelegateFromValidatorSet not implemented") } +func (*UnimplementedMsgServer) UndelegateFromRebalancedValidatorSet(ctx context.Context, req *MsgUndelegateFromRebalancedValidatorSet) (*MsgUndelegateFromRebalancedValidatorSetResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UndelegateFromRebalancedValidatorSet not implemented") +} func (*UnimplementedMsgServer) RedelegateValidatorSet(ctx context.Context, req *MsgRedelegateValidatorSet) (*MsgRedelegateValidatorSetResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method RedelegateValidatorSet not implemented") } @@ -843,6 +970,24 @@ func _Msg_UndelegateFromValidatorSet_Handler(srv interface{}, ctx context.Contex return interceptor(ctx, in, info, handler) } +func _Msg_UndelegateFromRebalancedValidatorSet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUndelegateFromRebalancedValidatorSet) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).UndelegateFromRebalancedValidatorSet(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/osmosis.valsetpref.v1beta1.Msg/UndelegateFromRebalancedValidatorSet", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UndelegateFromRebalancedValidatorSet(ctx, req.(*MsgUndelegateFromRebalancedValidatorSet)) + } + return interceptor(ctx, in, info, handler) +} + func _Msg_RedelegateValidatorSet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MsgRedelegateValidatorSet) if err := dec(in); err != nil { @@ -913,6 +1058,10 @@ var _Msg_serviceDesc = grpc.ServiceDesc{ MethodName: "UndelegateFromValidatorSet", Handler: _Msg_UndelegateFromValidatorSet_Handler, }, + { + MethodName: "UndelegateFromRebalancedValidatorSet", + Handler: _Msg_UndelegateFromRebalancedValidatorSet_Handler, + }, { MethodName: "RedelegateValidatorSet", Handler: _Msg_RedelegateValidatorSet_Handler, @@ -1123,6 +1272,69 @@ func (m *MsgUndelegateFromValidatorSetResponse) MarshalToSizedBuffer(dAtA []byte return len(dAtA) - i, nil } +func (m *MsgUndelegateFromRebalancedValidatorSet) 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 *MsgUndelegateFromRebalancedValidatorSet) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUndelegateFromRebalancedValidatorSet) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Coin.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Delegator) > 0 { + i -= len(m.Delegator) + copy(dAtA[i:], m.Delegator) + i = encodeVarintTx(dAtA, i, uint64(len(m.Delegator))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUndelegateFromRebalancedValidatorSetResponse) 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 *MsgUndelegateFromRebalancedValidatorSetResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUndelegateFromRebalancedValidatorSetResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + func (m *MsgRedelegateValidatorSet) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -1388,6 +1600,30 @@ func (m *MsgUndelegateFromValidatorSetResponse) Size() (n int) { return n } +func (m *MsgUndelegateFromRebalancedValidatorSet) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Delegator) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.Coin.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgUndelegateFromRebalancedValidatorSetResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + func (m *MsgRedelegateValidatorSet) Size() (n int) { if m == nil { return 0 @@ -1965,6 +2201,171 @@ func (m *MsgUndelegateFromValidatorSetResponse) Unmarshal(dAtA []byte) error { } return nil } +func (m *MsgUndelegateFromRebalancedValidatorSet) 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: MsgUndelegateFromRebalancedValidatorSet: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUndelegateFromRebalancedValidatorSet: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Delegator", 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.Delegator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Coin", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Coin.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 *MsgUndelegateFromRebalancedValidatorSetResponse) 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: MsgUndelegateFromRebalancedValidatorSetResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUndelegateFromRebalancedValidatorSetResponse: 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 (m *MsgRedelegateValidatorSet) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 51f2710b5d6..6cbde97ff48 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -21,6 +21,14 @@ type valSet struct { Amount osmomath.Dec } +type ValRatio struct { + ValAddr sdk.ValAddress + Weight osmomath.Dec + DelegatedAmt osmomath.Int + UndelegateAmt osmomath.Int + VRatio osmomath.Dec +} + // SetValidatorSetPreferences sets a new valset position for a delegator in modules state. func (k Keeper) SetValidatorSetPreferences(ctx sdk.Context, delegator string, validators types.ValidatorSetPreferences) { store := ctx.KVStore(k.storeKey) @@ -44,9 +52,11 @@ func (k Keeper) GetValidatorSetPreference(ctx sdk.Context, delegator string) (ty return valsetPref, true } -// SetValidatorSetPreference creates or updates delegators validator set. +// ValidateValidatorSetPreference derives given validator set. +// It validates the list and formats the inputs such as rounding. // Errors when the given preference is the same as the existing preference in state. -func (k Keeper) SetValidatorSetPreference(ctx sdk.Context, delegator string, preferences []types.ValidatorPreference) (types.ValidatorSetPreferences, error) { +// NOTE: this function does not add valset to the state +func (k Keeper) ValidateValidatorSetPreference(ctx sdk.Context, delegator string, preferences []types.ValidatorPreference) (types.ValidatorSetPreferences, error) { existingValSet, found := k.GetValidatorSetPreference(ctx, delegator) if found { // check if the new preferences is the same as the existing preferences @@ -99,10 +109,9 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co tokenAmt = coin.Amount.Sub(totalDelAmt).ToLegacyDec().TruncateInt() } else { // tokenAmt takes the amount to delegate, calculated by {val_distribution_weight * tokenAmt} - tokenAmt = val.Weight.Mul(coin.Amount.ToLegacyDec()).TruncateInt() + tokenAmt = val.Weight.MulInt(coin.Amount).TruncateInt() totalDelAmt = totalDelAmt.Add(tokenAmt) } - // TODO: What happens here if validator unbonding // Delegate the unbonded tokens _, err = k.stakingKeeper.Delegate(ctx, delegator, tokenAmt, stakingtypes.Unbonded, validator, true) @@ -116,80 +125,239 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co // UndelegateFromValidatorSet undelegates {coin} amount from the validator set. // If the valset does not exist, it undelegates from existing staking position. -// For ex: userA has staked 10tokens with weight {Val->0.5, ValB->0.3, ValC->0.2} +// Ex: userA has staked 10tokens with weight {Val->0.5, ValB->0.3, ValC->0.2} // undelegate 6osmo with validator-set {ValA -> 0.5, ValB -> 0.3, ValC -> 0.2} // our undelegate logic would attempt to undelegate 3osmo from A, 1.8osmo from B, 1.2osmo from C -// nolint: staticcheck -func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string, coin sdk.Coin) error { - // get the existingValSet if it exists, if not check existingStakingPosition and return it - existingSet, err := k.GetDelegationPreferences(ctx, delegatorAddr) +// Truncation ensures we do not undelegate more than the user has staked with the validator set. +// NOTE: check README.md for more verbose description of the algorithm. +// TODO: This is currently disabled. +// Properly implement for vratio > 1 to hit steps 5-7, then re-enable +// https://github.com/osmosis-labs/osmosis/issues/6686 +func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string, undelegation sdk.Coin) error { + // TODO: Change to GetDelegationPreferences + existingSet, err := k.GetValSetPreferencesWithDelegations(ctx, delegatorAddr) if err != nil { - return fmt.Errorf("user %s doesn't have validator set", delegatorAddr) + return types.NoValidatorSetOrExistingDelegationsError{DelegatorAddr: delegatorAddr} } - delegator, err := sdk.AccAddressFromBech32(delegatorAddr) + delegator := sdk.MustAccAddressFromBech32(delegatorAddr) + + // Step 1,2: compute the total amount delegated and the amount to undelegate for each validator + // under valset-ratios. + valSetRatio, validators, totalDelegatedAmt, err := k.getValsetRatios(ctx, delegator, existingSet.Preferences, undelegation.Amount) if err != nil { return err } - // the total amount the user wants to undelegate - tokenAmt := osmomath.NewDec(coin.Amount.Int64()) + if undelegation.Amount.ToLegacyDec().GT(totalDelegatedAmt) { + return types.UndelegateMoreThanDelegatedError{TotalDelegatedAmt: totalDelegatedAmt, UndelegationAmt: undelegation.Amount} + } + + // Step 3: Sort validators in descending order of VRatio. + sort.Slice(valSetRatio, func(i, j int) bool { + return valSetRatio[i].VRatio.GT(valSetRatio[j].VRatio) + }) - err = k.CheckUndelegateTotalAmount(tokenAmt, existingSet.Preferences) - if err != nil { - return err + totalUnDelAmt := sdk.NewInt(0) + var amountToUnDelegate osmomath.Int + // Step 4: if largest V Ratio is under 1, happy path, simply + // undelegate target amount from each validator + if valSetRatio[0].VRatio.LTE(sdk.OneDec()) { + for index, val := range valSetRatio { + validator := validators[val.ValAddr.String()] + + // in the last valset iteration we don't calculate it from shares using decimals and trucation, + // we use whats remaining to get more accurate value + if len(existingSet.Preferences)-1 == index { + amountToUnDelegate = undelegation.Amount.Sub(totalUnDelAmt).ToLegacyDec().TruncateInt() + } else { + // Calculate the amount to undelegate based on the existing weightxs + amountToUnDelegate = val.UndelegateAmt + totalUnDelAmt = totalUnDelAmt.Add(amountToUnDelegate) + } + sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) + if err != nil { + return err + } + + _, err = k.stakingKeeper.Undelegate(ctx, delegator, val.ValAddr, sharesAmt) // this has to be shares amount + if err != nil { + return err + } + } + return nil } - // totalDelAmt is the amount that keeps running track of the amount of tokens undelegated - totalUnDelAmt := osmomath.NewInt(0) - amountToUnDelegate := osmomath.NewInt(0) + // Step 5 + // `targetRatio`: This is a threshold value that is used to decide how to unbond tokens from validators. + // It starts as 1 and is recalculated each time a validator is fully unbonded and removed from the unbonding process. + // By reducing the target ratio using the ratio of the removed validator, we adjust the proportions we are aiming for with the remaining validators. + targetRatio := sdk.OneDec() + amountRemaining := undelegation.Amount - for i, val := range existingSet.Preferences { - valAddr, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) + // Step 6 + for len(valSetRatio) > 0 && valSetRatio[0].VRatio.GT(targetRatio) { + _, err = k.stakingKeeper.Undelegate(ctx, delegator, valSetRatio[0].ValAddr, valSetRatio[0].DelegatedAmt.ToLegacyDec()) // this has to be shares amount if err != nil { return err } + amountRemaining = amountRemaining.Sub(valSetRatio[0].DelegatedAmt) + targetRatio = targetRatio.Mul(sdk.OneDec().Sub(valSetRatio[0].Weight)) + valSetRatio = valSetRatio[1:] + } - // in the last valset iteration we dont calculate it from shares using decimals and trucation, - // we use whats remaining to get more accurate value - if len(existingSet.Preferences)-1 == i { - amountToUnDelegate = coin.Amount.Sub(totalUnDelAmt).ToLegacyDec().TruncateInt() - } else { - // Calculate the amount to undelegate based on the existing weights - amountToUnDelegate = val.Weight.Mul(tokenAmt).TruncateInt() - totalUnDelAmt = totalUnDelAmt.Add(amountToUnDelegate) + // Step 7 + for _, val := range valSetRatio { + _, validator, err := k.getValAddrAndVal(ctx, val.ValAddr.String()) + if err != nil { + return err } - sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) + sharesAmt, err := validator.SharesFromTokens(val.UndelegateAmt) if err != nil { return err } - _, err = k.stakingKeeper.Undelegate(ctx, delegator, valAddr, sharesAmt) // this has to be shares amount + _, err = k.stakingKeeper.Undelegate(ctx, delegator, val.ValAddr, sharesAmt) // this has to be shares amount if err != nil { return err } } + return nil } -// CheckUndelegateTotalAmount checks if the tokenAmount equals the total amount calculated from valset weights. -func (k Keeper) CheckUndelegateTotalAmount(tokenAmt osmomath.Dec, existingSet []types.ValidatorPreference) error { - totalAmountFromWeights := osmomath.NewDec(0) - for _, val := range existingSet { - totalAmountFromWeights = totalAmountFromWeights.Add(val.Weight.Mul(tokenAmt)) +// UndelegateFromRebalancedValidatorSet undelegates a specified amount of tokens from a delegator's existing validator set, +// but takes into consideration the user's existing delegations to the validators in the set. +// The method first fetches the delegator's validator set preferences, checks their existing delegations, and +// returns a set with modified weights that consider their existing delegations. +// If there is no existing delegation, it returns an error. +// The method then computes the total amount delegated and the amount to undelegate for each validator under this +// newly calculated valset-ratio set. +// +// If the undelegation amount is greater than the total delegated amount, it returns an error. +// The validators are then sorted in descending order of VRatio. +// The method ensures that the largest VRatio is under 1. If it is greater than 1, it returns an error. +// Finally, the method undelegates the target amount from each validator. +// If an error occurs during the undelegation process, it is returned. +func (k Keeper) UndelegateFromRebalancedValidatorSet(ctx sdk.Context, delegatorAddr string, undelegation sdk.Coin) error { + // GetValSetPreferencesWithDelegations fetches the delegator's validator set preferences, but returns a set with + // modified weights that consider their existing delegations. If there is no existing delegation, it returns an error. + // The new weights based on the existing delegations is returned, but the original valset preferences + // are not modified. + // For example, if someone's valset is 50/50 between two validators, but they have 10 OSMO delegated to validator A, + // and 90 OSMO delegated to validator B, the returned valset preference weight will be 10/90. + + existingSet, err := k.GetValSetPreferencesWithDelegations(ctx, delegatorAddr) + if err != nil { + return types.NoValidatorSetOrExistingDelegationsError{DelegatorAddr: delegatorAddr} } - totalAmountFromWeights = totalAmountFromWeights.RoundInt().ToLegacyDec() - tokenAmt = tokenAmt.RoundInt().ToLegacyDec() + delegator := sdk.MustAccAddressFromBech32(delegatorAddr) + + // Step 1,2: compute the total amount delegated and the amount to undelegate for each validator + // under valset-ratios. + valSetRatio, validators, totalDelegatedAmt, err := k.getValsetRatios(ctx, delegator, existingSet.Preferences, undelegation.Amount) + if err != nil { + return err + } - if !totalAmountFromWeights.Equal(tokenAmt) { - return fmt.Errorf("The undelegate total do not add up with the amount calculated from weights expected %s got %s", tokenAmt, totalAmountFromWeights) + if undelegation.Amount.ToLegacyDec().GT(totalDelegatedAmt) { + return types.UndelegateMoreThanDelegatedError{TotalDelegatedAmt: totalDelegatedAmt, UndelegationAmt: undelegation.Amount} } + // Step 3: Sort validators in descending order of VRatio. + sort.Slice(valSetRatio, func(i, j int) bool { + return valSetRatio[i].VRatio.GT(valSetRatio[j].VRatio) + }) + + totalUnDelAmt := sdk.NewInt(0) + var amountToUnDelegate osmomath.Int + + // Ensure largest VRatio is under 1. + // Since we called GetValSetPreferencesWithDelegations, there should be no VRatio > 1 + if valSetRatio[0].VRatio.GT(sdk.OneDec()) { + return types.ValsetRatioGreaterThanOneError{ValsetRatio: valSetRatio[0].VRatio} + } + + // Step 4: Undelegate target amount from each validator + for index, val := range valSetRatio { + validator := validators[val.ValAddr.String()] + + // in the last valset iteration we don't calculate it from shares using decimals and truncation, + // we use whats remaining to get more accurate value + if len(existingSet.Preferences)-1 == index { + // Directly retrieve the delegation to the last validator + // Use the min between our undelegation amount calculated via iterations of undelegating + // and the amount actually delegated to the validator. This is done to prevent an error + // in the event some rounding issue increases our calculated undelegation amount. + delegation, found := k.stakingKeeper.GetDelegation(ctx, delegator, val.ValAddr) + if !found { + return fmt.Errorf("No delegation found for delegator %s to validator %s\n", delegator, val.ValAddr) + } + delegationToVal := delegation.Shares.TruncateInt() + calculatedUndelegationAmt := undelegation.Amount.Sub(totalUnDelAmt).ToLegacyDec().TruncateInt() + amountToUnDelegate = osmomath.MinInt(delegationToVal, calculatedUndelegationAmt) + } else { + // Calculate the amount to undelegate based on the existing weightxs + amountToUnDelegate = val.UndelegateAmt + totalUnDelAmt = totalUnDelAmt.Add(amountToUnDelegate) + } + sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) + if err != nil { + return err + } + + _, err = k.stakingKeeper.Undelegate(ctx, delegator, val.ValAddr, sharesAmt) // this has to be shares amount + if err != nil { + return err + } + } return nil } +// getValsetRatios returns the valRatio array calculated based on the given delegator, valset prefs, and undelegating amount. +// Errors when given delegator does not have delegation towards all of the validators given in the valsetPrefs +func (k Keeper) getValsetRatios(ctx sdk.Context, delegator sdk.AccAddress, + prefs []types.ValidatorPreference, undelegateAmt osmomath.Int) ([]ValRatio, map[string]stakingtypes.Validator, osmomath.Dec, error) { + // total amount user has delegated + totalDelegatedAmt := osmomath.ZeroDec() + var valSetRatios []ValRatio + validators := map[string]stakingtypes.Validator{} + + for _, val := range prefs { + amountToUnDelegate := val.Weight.MulInt(undelegateAmt).TruncateInt() + valAddr, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) + if err != nil { + return nil, map[string]stakingtypes.Validator{}, sdk.ZeroDec(), err + } + validators[valAddr.String()] = validator + + delegation, found := k.stakingKeeper.GetDelegation(ctx, delegator, valAddr) + if !found { + return nil, map[string]stakingtypes.Validator{}, sdk.ZeroDec(), fmt.Errorf("No delegation found for delegator %s to validator %s\n", delegator, valAddr) + } + + undelegateSharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) + if err != nil { + return nil, map[string]stakingtypes.Validator{}, sdk.ZeroDec(), err + } + + // vRatio = undelegating amount / total delegated shares + // vRatio equals to 1 when undelegating full amount + vRatio := undelegateSharesAmt.Quo(delegation.Shares) + totalDelegatedAmt = totalDelegatedAmt.AddMut(validator.TokensFromShares(delegation.Shares)) + valSetRatios = append(valSetRatios, ValRatio{ + ValAddr: valAddr, + UndelegateAmt: amountToUnDelegate, + VRatio: vRatio, + DelegatedAmt: delegation.Shares.TruncateInt(), + Weight: val.Weight, + }) + } + return valSetRatios, validators, totalDelegatedAmt, nil +} + // The redelegation command allows delegators to instantly switch validators. // Once the unbonding period has passed, the redelegation is automatically completed in the EndBlocker. // A redelegation object is created every time a redelegation occurs. To prevent "redelegation hopping" where delegatorA can redelegate @@ -308,7 +476,7 @@ func (k Keeper) WithdrawDelegationRewards(ctx sdk.Context, delegatorAddr string) // get the existingValSet if it exists, if not check existingStakingPosition and return it existingSet, err := k.GetDelegationPreferences(ctx, delegatorAddr) if err != nil { - return fmt.Errorf("user %s doesn't have validator set or existing delegations", delegatorAddr) + return types.NoValidatorSetOrExistingDelegationsError{DelegatorAddr: delegatorAddr} } delegator, err := sdk.AccAddressFromBech32(delegatorAddr) diff --git a/x/valset-pref/validator_set_test.go b/x/valset-pref/validator_set_test.go index dd67a8398d3..5ac6734294b 100644 --- a/x/valset-pref/validator_set_test.go +++ b/x/valset-pref/validator_set_test.go @@ -3,7 +3,10 @@ package keeper_test import ( sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/osmosis-labs/osmosis/osmomath" + valPref "github.com/osmosis-labs/osmosis/v20/x/valset-pref" "github.com/osmosis-labs/osmosis/v20/x/valset-pref/types" ) @@ -66,78 +69,6 @@ func (s *KeeperTestSuite) TestValidateLockForForceUnlock() { } } -func (s *KeeperTestSuite) TestCheckUndelegateTotalAmount() { - valAddrs := s.SetupMultipleValidators(3) - tests := []struct { - name string - tokenAmt osmomath.Dec - existingSet []types.ValidatorPreference - expectPass bool - }{ - { - name: "token amount matches with totalAmountFromWeights", - tokenAmt: osmomath.NewDec(122_312_231), - existingSet: []types.ValidatorPreference{ - { - ValOperAddress: valAddrs[0], - Weight: osmomath.NewDecWithPrec(17, 2), // 0.17 - }, - { - ValOperAddress: valAddrs[1], - Weight: osmomath.NewDecWithPrec(83, 2), // 0.83 - }, - }, - expectPass: true, - }, - { - name: "token decimal amount matches with totalAmountFromWeights", - tokenAmt: osmomath.MustNewDecFromStr("122312231.532"), - existingSet: []types.ValidatorPreference{ - { - ValOperAddress: valAddrs[0], - Weight: osmomath.NewDecWithPrec(17, 2), // 0.17 - }, - { - ValOperAddress: valAddrs[1], - Weight: osmomath.NewDecWithPrec(83, 2), // 0.83 - }, - }, - expectPass: true, - }, - { - name: "tokenAmt doesnot match with totalAmountFromWeights", - tokenAmt: osmomath.NewDec(122_312_231), - existingSet: []types.ValidatorPreference{ - { - ValOperAddress: valAddrs[0], - Weight: osmomath.NewDecWithPrec(17, 2), // 0.17 - }, - - { - ValOperAddress: valAddrs[1], - Weight: osmomath.NewDecWithPrec(83, 2), // 0.83 - }, - { - ValOperAddress: valAddrs[2], - Weight: osmomath.NewDecWithPrec(83, 2), // 0.83 - }, - }, - expectPass: false, - }, - } - - for _, test := range tests { - s.Run(test.name, func() { - err := s.App.ValidatorSetPreferenceKeeper.CheckUndelegateTotalAmount(test.tokenAmt, test.existingSet) - if test.expectPass { - s.Require().NoError(err) - } else { - s.Require().Error(err) - } - }) - } -} - func (s *KeeperTestSuite) TestIsValidatorSetEqual() { valAddrs := s.SetupMultipleValidators(3) valSetOne := []types.ValidatorPreference{ @@ -213,6 +144,350 @@ func (s *KeeperTestSuite) TestIsValidatorSetEqual() { } } +func (s *KeeperTestSuite) TestUndelegateFromValidatorSet() { + tests := []struct { + name string + delegateAmt []osmomath.Int + undelegateAmt osmomath.Int + noValset bool + expectedUndelegateAmt []osmomath.Int + expectedError error + }{ + { + name: "exit at step 4: undelegating amount is under existing delegation amount", + delegateAmt: []osmomath.Int{sdk.NewInt(100), sdk.NewInt(50)}, + undelegateAmt: sdk.NewInt(50), + expectedUndelegateAmt: []osmomath.Int{sdk.NewInt(33), sdk.NewInt(17)}, + }, + { + name: "error: attempt to undelegate more than delegated", + delegateAmt: []osmomath.Int{sdk.NewInt(100), sdk.NewInt(50)}, + undelegateAmt: sdk.NewInt(200), + expectedError: types.UndelegateMoreThanDelegatedError{TotalDelegatedAmt: sdk.NewDec(150), UndelegationAmt: sdk.NewInt(200)}, + }, + { + name: "error: user does not have val-set preference set", + delegateAmt: []osmomath.Int{sdk.NewInt(100), sdk.NewInt(50)}, + undelegateAmt: sdk.NewInt(100), + noValset: true, + expectedError: types.NoValidatorSetOrExistingDelegationsError{DelegatorAddr: s.TestAccs[0].String()}, + }, + } + for _, test := range tests { + s.Run(test.name, func() { + s.SetupTest() + valAddrs := s.SetupMultipleValidators(3) + defaultDelegator := s.TestAccs[0] + bondDenom := s.App.StakingKeeper.BondDenom(s.Ctx) + + // set val-set pref + valPreferences := []types.ValidatorPreference{ + { + ValOperAddress: valAddrs[0], + Weight: sdk.NewDecWithPrec(1, 1), + }, + { + ValOperAddress: valAddrs[1], + Weight: sdk.NewDecWithPrec(9, 1), + }, + } + + if !test.noValset { + s.App.ValidatorSetPreferenceKeeper.SetValidatorSetPreferences(s.Ctx, defaultDelegator.String(), types.ValidatorSetPreferences{ + Preferences: valPreferences, + }) + // delegate for each of the validators + for i, valsetPref := range valPreferences { + valAddr, err := sdk.ValAddressFromBech32(valsetPref.ValOperAddress) + s.Require().NoError(err) + validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) + s.Require().True(found) + + s.FundAcc(defaultDelegator, sdk.NewCoins(sdk.NewCoin(bondDenom, test.delegateAmt[i]))) + _, err = s.App.StakingKeeper.Delegate(s.Ctx, defaultDelegator, test.delegateAmt[i], stakingtypes.Unbonded, validator, true) + s.Require().NoError(err) + } + } + + // System Under Test + err := s.App.ValidatorSetPreferenceKeeper.UndelegateFromValidatorSet(s.Ctx, defaultDelegator.String(), sdk.NewCoin(bondDenom, test.undelegateAmt)) + + if test.expectedError != nil { + s.Require().Error(err) + s.Require().ErrorContains(err, test.expectedError.Error()) + return + } + s.Require().NoError(err) + + for i, valsetPref := range valPreferences { + valAddr, err := sdk.ValAddressFromBech32(valsetPref.ValOperAddress) + s.Require().NoError(err) + + delegation, found := s.App.StakingKeeper.GetUnbondingDelegation(s.Ctx, defaultDelegator, valAddr) + s.Require().True(found) + s.Require().Equal(delegation.Entries[0].Balance, test.expectedUndelegateAmt[i]) + } + }) + } +} + +func (s *KeeperTestSuite) TestUndelegateFromRebalancedValidatorSet() { + tests := []struct { + name string + delegateAmt []osmomath.Int + undelegateAmt osmomath.Int + noValset bool + expectedUndelegateAmt []osmomath.Int + expectedError error + }{ + { + name: "happy path: undelegate all, weights match the current delegations to valset", + delegateAmt: []osmomath.Int{sdk.NewInt(10), sdk.NewInt(90)}, + undelegateAmt: sdk.NewInt(100), + expectedUndelegateAmt: []osmomath.Int{sdk.NewInt(10), sdk.NewInt(90)}, + }, + { + name: "happy path: undelegate some, weights match the current delegations to valset", + delegateAmt: []osmomath.Int{sdk.NewInt(10), sdk.NewInt(90)}, + undelegateAmt: sdk.NewInt(50), + expectedUndelegateAmt: []osmomath.Int{sdk.NewInt(5), sdk.NewInt(45)}, + }, + { + name: "undelegate all, weights do not match the current delegations to valset", + delegateAmt: []osmomath.Int{sdk.NewInt(90), sdk.NewInt(10)}, + undelegateAmt: sdk.NewInt(100), + expectedUndelegateAmt: []osmomath.Int{sdk.NewInt(90), sdk.NewInt(10)}, + }, + { + name: "undelegate some, weights do not match the current delegations to valset", + delegateAmt: []osmomath.Int{sdk.NewInt(90), sdk.NewInt(10)}, + undelegateAmt: sdk.NewInt(50), + expectedUndelegateAmt: []osmomath.Int{sdk.NewInt(45), sdk.NewInt(5)}, + }, + { + name: "error: attempt to undelegate more than delegated", + delegateAmt: []osmomath.Int{sdk.NewInt(100), sdk.NewInt(50)}, + undelegateAmt: sdk.NewInt(200), + expectedError: types.UndelegateMoreThanDelegatedError{TotalDelegatedAmt: sdk.NewDec(150), UndelegationAmt: sdk.NewInt(200)}, + }, + { + name: "error: user does not have val-set preference set", + delegateAmt: []osmomath.Int{sdk.NewInt(100), sdk.NewInt(50)}, + undelegateAmt: sdk.NewInt(100), + noValset: true, + expectedError: types.NoValidatorSetOrExistingDelegationsError{DelegatorAddr: s.TestAccs[0].String()}, + }, + } + for _, test := range tests { + s.Run(test.name, func() { + s.SetupTest() + valAddrs := s.SetupMultipleValidators(3) + defaultDelegator := s.TestAccs[0] + bondDenom := s.App.StakingKeeper.BondDenom(s.Ctx) + + // set val-set pref + valPreferences := []types.ValidatorPreference{ + { + ValOperAddress: valAddrs[0], + Weight: sdk.NewDecWithPrec(1, 1), + }, + { + ValOperAddress: valAddrs[1], + Weight: sdk.NewDecWithPrec(9, 1), + }, + } + + if !test.noValset { + s.App.ValidatorSetPreferenceKeeper.SetValidatorSetPreferences(s.Ctx, defaultDelegator.String(), types.ValidatorSetPreferences{ + Preferences: valPreferences, + }) + // delegate for each of the validators + for i, valsetPref := range valPreferences { + valAddr, err := sdk.ValAddressFromBech32(valsetPref.ValOperAddress) + s.Require().NoError(err) + validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) + s.Require().True(found) + + s.FundAcc(defaultDelegator, sdk.NewCoins(sdk.NewCoin(bondDenom, test.delegateAmt[i]))) + _, err = s.App.StakingKeeper.Delegate(s.Ctx, defaultDelegator, test.delegateAmt[i], stakingtypes.Unbonded, validator, true) + s.Require().NoError(err) + } + } + + // System Under Test + err := s.App.ValidatorSetPreferenceKeeper.UndelegateFromRebalancedValidatorSet(s.Ctx, defaultDelegator.String(), sdk.NewCoin(bondDenom, test.undelegateAmt)) + + if test.expectedError != nil { + s.Require().Error(err) + s.Require().ErrorContains(err, test.expectedError.Error()) + return + } + s.Require().NoError(err) + + for i, valsetPref := range valPreferences { + valAddr, err := sdk.ValAddressFromBech32(valsetPref.ValOperAddress) + s.Require().NoError(err) + + delegation, found := s.App.StakingKeeper.GetUnbondingDelegation(s.Ctx, defaultDelegator, valAddr) + s.Require().True(found) + s.Require().Equal(delegation.Entries[0].Balance, test.expectedUndelegateAmt[i]) + } + }) + } +} + +func (s *KeeperTestSuite) TestGetValsetRatios() { + defaultDelegationAmt := sdk.NewInt(100) + tests := []struct { + name string + useSingleValPref bool + undelegateAmt osmomath.Int + expectedError bool + notDelegated bool + expectedValRatios []valPref.ValRatio + }{ + { + name: "single validator, undelegate full amount", + useSingleValPref: true, + undelegateAmt: sdk.NewInt(100), + expectedValRatios: []valPref.ValRatio{ + { + Weight: sdk.NewDec(1), + DelegatedAmt: defaultDelegationAmt, + UndelegateAmt: defaultDelegationAmt, + VRatio: sdk.NewDec(1), + }, + }, + }, + { + name: "single validator, undelegate partial amount", + useSingleValPref: true, + undelegateAmt: sdk.NewInt(50), + expectedValRatios: []valPref.ValRatio{ + { + Weight: sdk.NewDec(1), + DelegatedAmt: defaultDelegationAmt, + UndelegateAmt: defaultDelegationAmt.Quo(sdk.NewInt(2)), + // 0.5 since we are undelegating half amount + VRatio: sdk.NewDecWithPrec(5, 1), + }, + }, + }, + { + name: "multiple validator, undelegate full amount", + undelegateAmt: defaultDelegationAmt, + expectedValRatios: []valPref.ValRatio{ + { + Weight: sdk.MustNewDecFromStr("0.333333333333333333"), + DelegatedAmt: defaultDelegationAmt, + UndelegateAmt: sdk.NewInt(33), + VRatio: sdk.MustNewDecFromStr("0.33"), + }, + { + Weight: sdk.MustNewDecFromStr("0.666666666666666667"), + DelegatedAmt: defaultDelegationAmt, + UndelegateAmt: sdk.NewInt(66), + VRatio: sdk.MustNewDecFromStr("0.66"), + }, + }, + }, + { + name: "multiple validator, undelegate partial amount", + undelegateAmt: defaultDelegationAmt.Quo(sdk.NewInt(2)), + expectedValRatios: []valPref.ValRatio{ + { + Weight: sdk.MustNewDecFromStr("0.333333333333333333"), + DelegatedAmt: defaultDelegationAmt, + // 1/3 of undelegating amount(50) + UndelegateAmt: sdk.NewInt(16), + VRatio: sdk.MustNewDecFromStr("0.16"), + }, + { + Weight: sdk.MustNewDecFromStr("0.666666666666666667"), + DelegatedAmt: defaultDelegationAmt, + // 2/3 of undelegating amount(50) + UndelegateAmt: sdk.NewInt(33), + VRatio: sdk.MustNewDecFromStr("0.33"), + }, + }, + }, + { + name: "error: not delegated", + undelegateAmt: defaultDelegationAmt, + useSingleValPref: true, + notDelegated: true, + expectedError: true, + }, + } + for _, test := range tests { + s.Run(test.name, func() { + s.SetupTest() + valAddrs := s.SetupMultipleValidators(3) + defaultDelegator := s.TestAccs[0] + + var valsetPrefs []types.ValidatorPreference + if test.useSingleValPref { + valsetPrefs = []types.ValidatorPreference{ + { + ValOperAddress: valAddrs[0], + Weight: sdk.OneDec(), + }, + } + } else { // other cases, we assume we are using val set pref with mutiple validators + valsetPrefs = []types.ValidatorPreference{ + { + ValOperAddress: valAddrs[0], + Weight: sdk.MustNewDecFromStr("0.333333333333333333"), + }, + { + ValOperAddress: valAddrs[1], + Weight: sdk.MustNewDecFromStr("0.666666666666666667"), + }, + } + } + + // set up delegation for each of the valset prefs + expectedTotalDelegatedAmt := sdk.ZeroDec() + if !test.notDelegated { + for i, valsetPref := range valsetPrefs { + valAddr, err := sdk.ValAddressFromBech32(valsetPref.ValOperAddress) + s.Require().NoError(err) + validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) + s.Require().True(found) + bondDenom := s.App.StakingKeeper.BondDenom(s.Ctx) + + s.FundAcc(defaultDelegator, sdk.NewCoins(sdk.NewCoin(bondDenom, defaultDelegationAmt))) + _, err = s.App.StakingKeeper.Delegate(s.Ctx, defaultDelegator, defaultDelegationAmt, stakingtypes.Unbonded, validator, true) + s.Require().NoError(err) + + expectedTotalDelegatedAmt = expectedTotalDelegatedAmt.Add(defaultDelegationAmt.ToLegacyDec()) + test.expectedValRatios[i].ValAddr = valAddr + } + } + + // system under test + valRatios, validators, totalDelegatedAmt, err := s.App.ValidatorSetPreferenceKeeper.GetValsetRatios(s.Ctx, defaultDelegator, valsetPrefs, test.undelegateAmt) + if test.expectedError { + s.Require().Error(err) + return + } + + s.Require().NoError(err) + s.Require().True(totalDelegatedAmt.Equal(expectedTotalDelegatedAmt)) + // iterate over returned validators, make sure correct validators are returned in the map + for valAddr, val := range validators { + valAddr, err := sdk.ValAddressFromBech32(valAddr) + s.Require().NoError(err) + validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) + s.Require().True(found) + validator.Equal(&val) + } + + s.Require().Equal(valRatios, test.expectedValRatios) + }) + } +} + func (s *KeeperTestSuite) TestIsPreferenceValid() { valAddrs := s.SetupMultipleValidators(4) @@ -275,3 +550,132 @@ func (s *KeeperTestSuite) TestIsPreferenceValid() { }) } } + +// NOTE: this is the case that used to error. Fixed by this PR +func (s *KeeperTestSuite) TestUndelegateFromValSetErrorCase() { + s.SetupTest() + + valAddrs := s.SetupMultipleValidators(3) + valPreferences := []types.ValidatorPreference{ + { + ValOperAddress: valAddrs[0], + Weight: sdk.NewDecWithPrec(5, 1), // 0.5 + }, + { + ValOperAddress: valAddrs[1], + Weight: sdk.NewDecWithPrec(5, 1), // 0.5 + }, + } + + delegator := sdk.AccAddress([]byte("addr1---------------")) + coinToStake := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)) // delegate 10osmo using Valset now and 10 osmo using regular staking delegate + coinToUnStake := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)) // undelegate 20osmo + expectedShares := []osmomath.Dec{sdk.NewDec(15_000_000), sdk.NewDec(500_000)} + + s.FundAcc(delegator, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100_000_000)}) // 100 osmo + + // valset test setup + // SetValidatorSetPreference sets a new list of val-set + _, err := s.App.ValidatorSetPreferenceKeeper.ValidateValidatorSetPreference(s.Ctx, delegator.String(), valPreferences) + s.Require().NoError(err) + + s.App.ValidatorSetPreferenceKeeper.SetValidatorSetPreferences(s.Ctx, delegator.String(), types.ValidatorSetPreferences{ + Preferences: valPreferences, + }) + + // DelegateToValidatorSet delegate to existing val-set + err = s.App.ValidatorSetPreferenceKeeper.DelegateToValidatorSet(s.Ctx, delegator.String(), coinToStake) + s.Require().NoError(err) + + valAddr, err := sdk.ValAddressFromBech32(valAddrs[0]) + s.Require().NoError(err) + + validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) + s.Require().True(found) + + // Delegate more token to the validator. This will cause valset and regular staking to go out of sync + _, err = s.App.StakingKeeper.Delegate(s.Ctx, delegator, sdk.NewInt(10_000_000), stakingtypes.Unbonded, validator, true) + s.Require().NoError(err) + + err = s.App.ValidatorSetPreferenceKeeper.UndelegateFromValidatorSet(s.Ctx, delegator.String(), coinToUnStake) + s.Require().NoError(err) + + for i, val := range valPreferences { + valAddr, err := sdk.ValAddressFromBech32(val.ValOperAddress) + s.Require().NoError(err) + + // guarantees that the delegator exists because we check it in UnDelegateToValidatorSet + del, found := s.App.StakingKeeper.GetDelegation(s.Ctx, delegator, valAddr) + if found { + s.Require().Equal(expectedShares[i], del.GetShares()) + } + } + +} + +// NOTE: this is the case that used to error. Fixed by this PR +func (s *KeeperTestSuite) TestUndelegateFromValSetErrorCase1() { + s.SetupTest() + + valAddrs := s.SetupMultipleValidators(4) + valPreferences := []types.ValidatorPreference{ + { + ValOperAddress: valAddrs[0], + Weight: sdk.MustNewDecFromStr("0.05"), + }, + { + ValOperAddress: valAddrs[1], + Weight: sdk.MustNewDecFromStr("0.05"), + }, + { + ValOperAddress: valAddrs[2], + Weight: sdk.NewDecWithPrec(45, 2), // 0.45 + }, + { + ValOperAddress: valAddrs[3], + Weight: sdk.NewDecWithPrec(45, 2), // 0.45 + }, + } + + delegator := sdk.AccAddress([]byte("addr4---------------")) + coinToStake := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100_000_000)) // delegate 100osmo using Valset now and 10 osmo using regular staking delegate + coinToUnStake := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(200_000_000)) // undelegate 20osmo + + s.FundAcc(delegator, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 300_000_000)}) // 100 osmo + + // valset test setup + // SetValidatorSetPreference sets a new list of val-set + msgServer := valPref.NewMsgServerImpl(s.App.ValidatorSetPreferenceKeeper) + c := sdk.WrapSDKContext(s.Ctx) + + // SetValidatorSetPreference sets a new list of val-set + _, err := msgServer.SetValidatorSetPreference(c, types.NewMsgSetValidatorSetPreference(delegator, valPreferences)) + s.Require().NoError(err) + + // DelegateToValidatorSet delegate to existing val-set + err = s.App.ValidatorSetPreferenceKeeper.DelegateToValidatorSet(s.Ctx, delegator.String(), coinToStake) + s.Require().NoError(err) + + valAddr, err := sdk.ValAddressFromBech32(valAddrs[0]) + s.Require().NoError(err) + + validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) + s.Require().True(found) + + valAddr2, err := sdk.ValAddressFromBech32(valAddrs[1]) + s.Require().NoError(err) + + validator2, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr2) + s.Require().True(found) + + // Delegate more token to the validator. This will cause valset and regular staking to go out of sync + _, err = s.App.StakingKeeper.Delegate(s.Ctx, delegator, sdk.NewInt(50_000_000), stakingtypes.Unbonded, validator, true) + s.Require().NoError(err) + + _, err = s.App.StakingKeeper.Delegate(s.Ctx, delegator, sdk.NewInt(50_000_000), stakingtypes.Unbonded, validator2, true) + s.Require().NoError(err) + + err = s.App.ValidatorSetPreferenceKeeper.UndelegateFromValidatorSet(s.Ctx, delegator.String(), coinToUnStake) + s.Require().NoError(err) + +}