From fe7290ff7efd843a78cd6cae23a4be91f6c8c2ec Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sat, 5 Aug 2023 20:05:36 -0500 Subject: [PATCH 01/28] Add helper to get existing delegations along with valset pref --- x/valset-pref/README.md | 23 +++++++++++----- x/valset-pref/keeper.go | 49 ++++++++++++++++++++++++++++++++++ x/valset-pref/validator_set.go | 6 ++++- 3 files changed, 71 insertions(+), 7 deletions(-) diff --git a/x/valset-pref/README.md b/x/valset-pref/README.md index b537b2b43fc..2ea44ef5cff 100644 --- a/x/valset-pref/README.md +++ b/x/valset-pref/README.md @@ -25,15 +25,26 @@ 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 +## Logic -Staking Calculation +### Delegate to validator set -- 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. +This is pretty straight-forward, theres not really any edge cases here. -UnStaking 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. + +### 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. + +#### 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/keeper.go b/x/valset-pref/keeper.go index bbdfff2847e..c3e9c65a8cd 100644 --- a/x/valset-pref/keeper.go +++ b/x/valset-pref/keeper.go @@ -9,6 +9,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/osmosis-labs/osmosis/v17/x/valset-pref/types" ) @@ -60,6 +62,53 @@ func (k Keeper) GetDelegationPreferences(ctx sdk.Context, delegator string) (typ return valSet, nil } +// getValsetDelegationsAndPreferences retrieves the validator preferences and +// delegations for a given delegator. It returns the ValidatorSetPreferences, +// a slice of Delegations, and an error if any issues occur during the process. +// +// The function first retrieves the validator set preferences associated with the delegator. +// If preferences exist, it iterates over them and fetches each associated delegation, +// adding it to a slice of delegations. If no preferences exist, it gets all delegator +// delegations. +// +// Params: +// +// ctx - The sdk.Context representing the current context. +// delegator - The address (as a string) of the delegator whose preferences and +// delegations are to be fetched. +// +// Returns: +// +// The ValidatorSetPreferences object associated with the delegator. +// A slice of Delegation objects for the delegator. +// An error if any issues occur during the process. +func (k Keeper) getValsetDelegationsAndPreferences(ctx sdk.Context, delegator string) (types.ValidatorSetPreferences, []stakingtypes.Delegation, error) { + delAddr, err := sdk.AccAddressFromBech32(delegator) + if err != nil { + return types.ValidatorSetPreferences{}, nil, err + } + + valSet, exists := k.GetValidatorSetPreference(ctx, delegator) + var delegations []stakingtypes.Delegation + if exists { + for _, val := range valSet.Preferences { + del, found := k.stakingKeeper.GetDelegation(ctx, delAddr, sdk.ValAddress(val.ValOperAddress)) + if !found { + del = stakingtypes.Delegation{DelegatorAddress: delegator, ValidatorAddress: (val.ValOperAddress), Shares: sdk.ZeroDec()} + } + delegations = append(delegations, del) + } + } + if !exists { + delegations = k.stakingKeeper.GetDelegatorDelegations(ctx, delAddr, math.MaxUint16) + if len(delegations) == 0 { + return types.ValidatorSetPreferences{}, nil, fmt.Errorf("No Existing delegation to unbond from") + } + } + + return valSet, delegations, 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. diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 744171955ad..39abd439a11 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -119,7 +119,7 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co // For 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 +// Rounding logic ensures we do not undelegate more than the user has staked with the validator set 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) @@ -174,6 +174,10 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string } // CheckUndelegateTotalAmount checks if the tokenAmount equals the total amount calculated from valset weights. +// TODO: Do we need to be doing this? Its computing that +// sum_{v in ValSet} {v.Weight * tokenAmt} = tokenAmt +// So in infinite precision this is implied by sum v.Weight = 1 +// Its _technically_ doing something by testing with Mul's decimal rounding behavior. func (k Keeper) CheckUndelegateTotalAmount(tokenAmt sdk.Dec, existingSet []types.ValidatorPreference) error { totalAmountFromWeights := sdk.NewDec(0) for _, val := range existingSet { From fcdc961ad70b8a04f2299e795ea50cf55026599b Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sun, 6 Aug 2023 16:47:32 -0500 Subject: [PATCH 02/28] Lay out more of the logic nuance --- x/valset-pref/validator_set.go | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 39abd439a11..5a2a0ff1076 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -121,24 +121,34 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co // our undelegate logic would attempt to undelegate 3osmo from A, 1.8osmo from B, 1.2osmo from C // Rounding logic ensures we do not undelegate more than the user has staked with the validator set 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) + existingPref, delegations, err := k.getValsetDelegationsAndPreferences(ctx, delegatorAddr) if err != nil { - return fmt.Errorf("user %s doesn't have validator set", delegatorAddr) + return err } + // err already checked + delegator := sdk.MustAccAddressFromBech32(delegatorAddr) - delegator, err := sdk.AccAddressFromBech32(delegatorAddr) - if err != nil { - return err + // We first check determine what type of algorithm we need to run based on + // if total staked to valset-vals < unbond amount, fail + // if total staked to valset-vals == unbond amount, unbond all + // if total staked to valset-vals > unbond amount, unbond as true to valset ratios as possible. + + totalStaked := sdk.ZeroDec() + // get validators + validators := make([]stakingtypes.Validator, len(existingPref.Preferences)) + for i, val := range existingPref.Preferences { + _, validators[i], err = k.getValAddrAndVal(ctx, val.ValOperAddress) + if err != nil { + return err + } + // Add up total staked to validator. NOTE: This is using the full "decimal amount" staked form + totalStaked.AddMut(validators[i].TokensFromShares(delegations[i].Shares)) } // the total amount the user wants to undelegate tokenAmt := sdk.NewDec(coin.Amount.Int64()) - err = k.CheckUndelegateTotalAmount(tokenAmt, existingSet.Preferences) - if err != nil { - return err - } + stakedToValset := sdk.NewInt(0) // totalDelAmt is the amount that keeps running track of the amount of tokens undelegated totalUnDelAmt := sdk.NewInt(0) From 58792cc2a2b7b2e183c17c3a75ca9364db023b21 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sun, 6 Aug 2023 17:20:52 -0500 Subject: [PATCH 03/28] Add pseudo-code needed --- x/valset-pref/validator_set.go | 39 +++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 5a2a0ff1076..bb11d0b3cd5 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -130,7 +130,7 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string // We first check determine what type of algorithm we need to run based on // if total staked to valset-vals < unbond amount, fail - // if total staked to valset-vals == unbond amount, unbond all + // if round_down(total staked to valset-vals) == unbond amount, unbond all // if total staked to valset-vals > unbond amount, unbond as true to valset ratios as possible. totalStaked := sdk.ZeroDec() @@ -145,8 +145,41 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string totalStaked.AddMut(validators[i].TokensFromShares(delegations[i].Shares)) } - // the total amount the user wants to undelegate - tokenAmt := sdk.NewDec(coin.Amount.Int64()) + if totalStaked.LT(coin.Amount.ToDec()) { + return fmt.Errorf("cannot unbond more than staked to validator set") + } else if totalStaked.TruncateInt().Equal(coin.Amount) { + // unbond all + for i, val := range validators { + _, err = k.stakingKeeper.Undelegate(ctx, delegator, val.GetOperator(), delegations[i].Shares) + if err != nil { + return err + } + } + } + // 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. If no V_ratio > 1, undelegate taret amount from each validator. (happy path) + // 4. If a V_ratio > 1, sort validators by V_ratio descending + // 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) + // - you understand this, 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. stakedToValset := sdk.NewInt(0) From 2f8dea8f31925ab2fbae7fb531cd9faf20c2e7a3 Mon Sep 17 00:00:00 2001 From: stackman27 Date: Mon, 7 Aug 2023 21:37:43 +0000 Subject: [PATCH 04/28] algorithm v1 --- main.go | 70 +++++++++++++++ x/valset-pref/msg_server_test.go | 34 +++---- x/valset-pref/validator_set.go | 134 +++++++++++++++------------- x/valset-pref/validator_set_test.go | 54 +++++++++++ 4 files changed, 211 insertions(+), 81 deletions(-) create mode 100644 main.go diff --git a/main.go b/main.go new file mode 100644 index 00000000000..be3aaf9d549 --- /dev/null +++ b/main.go @@ -0,0 +1,70 @@ +package main + +import ( + "fmt" + "sort" +) + +// Define a struct for the validators +type Validator struct { + Name string + Staked float64 + RatioInValset float64 + UndelegateAmt float64 + VRatio float64 +} + +func main() { + // Initialize validators X and Y + validators := []Validator{ + {Name: "X", Staked: 15.0, RatioInValset: 0.5}, + {Name: "Y", Staked: 5.0, RatioInValset: 0.5}, + } + + amount := 20.0 + + // Step 1 and 2 + for i := range validators { + validators[i].UndelegateAmt = validators[i].RatioInValset * amount + validators[i].VRatio = validators[i].UndelegateAmt / validators[i].Staked + } + + // Step 3 + maxVRatio := validators[0].VRatio + for _, v := range validators { + if v.VRatio > maxVRatio { + maxVRatio = v.VRatio + } + } + + if maxVRatio <= 1 { + fmt.Println("All validators can undelegate normally, falling to happy path.") + return + } + + // Step 4 + sort.Slice(validators, func(i, j int) bool { + return validators[i].VRatio > validators[j].VRatio + }) + + // Step 5 + targetRatio := 1.0 + amountRemaining := amount + + // Step 6 + for len(validators) > 0 && validators[0].VRatio > targetRatio { + fmt.Printf("Undelegating fully from validator %s\n", validators[0].Name) + amountRemaining -= validators[0].Staked + targetRatio *= (1 - validators[0].RatioInValset) + validators = validators[1:] + + fmt.Println(validators) + } + + // Step 7 + fmt.Println("Distributing the remaining tokens normally amongst the remaining validators.") + for _, v := range validators { + undelegate := v.RatioInValset * amountRemaining + fmt.Printf("Undelegate %.2f from validator %s\n", undelegate, v.Name) + } +} diff --git a/x/valset-pref/msg_server_test.go b/x/valset-pref/msg_server_test.go index 4f8e678fbf8..9838586af6f 100644 --- a/x/valset-pref/msg_server_test.go +++ b/x/valset-pref/msg_server_test.go @@ -345,23 +345,23 @@ func (s *KeeperTestSuite) TestUnDelegateFromValidatorSet() { setValSet: true, expectPass: true, }, - { - name: "Unstake more amount than the staked amount", - delegator: sdk.AccAddress([]byte("addr4---------------")), - 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: "UnDelegate from existing staking position (non valSet) ", - delegator: sdk.AccAddress([]byte("addr5---------------")), - coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), - coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), - expectedShares: []sdk.Dec{sdk.NewDec(1_000_000), sdk.NewDec(1_660_000), sdk.NewDec(600_000), sdk.NewDec(1_740_000)}, // validatorDelegatedShares - (weight * coinToUnstake) - setExistingDelegations: true, - expectPass: true, - }, + // { + // name: "Unstake more amount than the staked amount", + // delegator: sdk.AccAddress([]byte("addr4---------------")), + // 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: "UnDelegate from existing staking position (non valSet) ", + // delegator: sdk.AccAddress([]byte("addr5---------------")), + // coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), + // coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), + // expectedShares: []sdk.Dec{sdk.NewDec(1_000_000), sdk.NewDec(1_660_000), sdk.NewDec(600_000), sdk.NewDec(1_740_000)}, // validatorDelegatedShares - (weight * coinToUnstake) + // setExistingDelegations: true, + // expectPass: true, + // }, { name: "Undelegate extreme amounts to check truncation, large amount", delegator: sdk.AccAddress([]byte("addr6---------------")), diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index bb11d0b3cd5..52d706be98a 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -21,6 +21,14 @@ type valSet struct { Amount sdk.Dec } +type ValRatio struct { + ValAddr sdk.ValAddress + Weight sdk.Dec + DelegatedAmt sdk.Int + UndelegateAmt sdk.Int + VRatio sdk.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) @@ -46,6 +54,7 @@ func (k Keeper) GetValidatorSetPreference(ctx sdk.Context, delegator string) (ty // SetValidatorSetPreference creates or updates delegators validator set. // Errors when the given preference is the same as the existing preference in state. +// NOTE: this function doesnot add valset to the state func (k Keeper) SetValidatorSetPreference(ctx sdk.Context, delegator string, preferences []types.ValidatorPreference) (types.ValidatorSetPreferences, error) { existingValSet, found := k.GetValidatorSetPreference(ctx, delegator) if found { @@ -121,98 +130,95 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co // our undelegate logic would attempt to undelegate 3osmo from A, 1.8osmo from B, 1.2osmo from C // Rounding logic ensures we do not undelegate more than the user has staked with the validator set func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string, coin sdk.Coin) error { - existingPref, delegations, err := k.getValsetDelegationsAndPreferences(ctx, delegatorAddr) + existingPref, _, err := k.getValsetDelegationsAndPreferences(ctx, delegatorAddr) if err != nil { return err } // err already checked delegator := sdk.MustAccAddressFromBech32(delegatorAddr) + // the total amount the user wants to undelegate + tokenAmt := sdk.NewDec(coin.Amount.Int64()) + + var valSetRatio []ValRatio + for _, val := range existingPref.Preferences { + amountToUnDelegate := val.Weight.Mul(tokenAmt).TruncateInt() + valAddr, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) + if err != nil { + return err + } - // We first check determine what type of algorithm we need to run based on - // if total staked to valset-vals < unbond amount, fail - // if round_down(total staked to valset-vals) == unbond amount, unbond all - // if total staked to valset-vals > unbond amount, unbond as true to valset ratios as possible. + delegation, found := k.stakingKeeper.GetDelegation(ctx, delegator, valAddr) + if found { + fmt.Println("DELEGATION: ", delegation) + } - totalStaked := sdk.ZeroDec() - // get validators - validators := make([]stakingtypes.Validator, len(existingPref.Preferences)) - for i, val := range existingPref.Preferences { - _, validators[i], err = k.getValAddrAndVal(ctx, val.ValOperAddress) + sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) if err != nil { return err } - // Add up total staked to validator. NOTE: This is using the full "decimal amount" staked form - totalStaked.AddMut(validators[i].TokensFromShares(delegations[i].Shares)) + + valShares := sharesAmt.Quo(delegation.Shares) + + valSetRatio = append(valSetRatio, ValRatio{ + ValAddr: valAddr, + UndelegateAmt: amountToUnDelegate, + VRatio: valShares, + DelegatedAmt: delegation.Shares.TruncateInt(), + Weight: val.Weight, + }) + } + + maxVRatio := valSetRatio[0].VRatio + for _, val := range valSetRatio { + if val.VRatio.GT(maxVRatio) { + maxVRatio = val.VRatio + } } - if totalStaked.LT(coin.Amount.ToDec()) { - return fmt.Errorf("cannot unbond more than staked to validator set") - } else if totalStaked.TruncateInt().Equal(coin.Amount) { - // unbond all - for i, val := range validators { - _, err = k.stakingKeeper.Undelegate(ctx, delegator, val.GetOperator(), delegations[i].Shares) + if maxVRatio.LTE(sdk.OneDec()) { + fmt.Println("All validators can undelegate normally, falling to happy path exit early") + for _, val := range valSetRatio { + _, err = k.stakingKeeper.Undelegate(ctx, delegator, val.ValAddr, val.UndelegateAmt.ToDec()) // this has to be shares amount if err != nil { return err } } + + return nil } - // 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. If no V_ratio > 1, undelegate taret amount from each validator. (happy path) - // 4. If a V_ratio > 1, sort validators by V_ratio descending - // 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) - // - you understand this, 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. - - stakedToValset := sdk.NewInt(0) - - // totalDelAmt is the amount that keeps running track of the amount of tokens undelegated - totalUnDelAmt := sdk.NewInt(0) - amountToUnDelegate := sdk.NewInt(0) - for i, val := range existingSet.Preferences { - valAddr, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) - if err != nil { - return err - } + // Step 4 + sort.Slice(valSetRatio, func(i, j int) bool { + return valSetRatio[i].VRatio.GT(valSetRatio[j].VRatio) + }) - // 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).ToDec().TruncateInt() - } else { - // Calculate the amount to undelegate based on the existing weights - amountToUnDelegate = val.Weight.Mul(tokenAmt).TruncateInt() - totalUnDelAmt = totalUnDelAmt.Add(amountToUnDelegate) - } + // Step 5 + targetRatio := sdk.OneDec() + amountRemaining := coin.Amount - sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) + // Step 6 + for len(valSetRatio) > 0 && valSetRatio[0].VRatio.GT(targetRatio) { + fmt.Printf("Undelegating fully from validator %s\n", valSetRatio[0].ValAddr.String()) + _, err = k.stakingKeeper.Undelegate(ctx, delegator, valSetRatio[0].ValAddr, valSetRatio[0].DelegatedAmt.ToDec()) // 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:] + } - _, err = k.stakingKeeper.Undelegate(ctx, delegator, valAddr, sharesAmt) // this has to be shares amount + // Step 7 + fmt.Println("Distributing the remaining tokens normally amongst the remaining validators.") + for _, v := range valSetRatio { + undelegateAmt := v.Weight.MulInt(amountRemaining) + fmt.Printf("Undelegate %.2f from validator %s\n", undelegateAmt, v.ValAddr.String()) + _, err = k.stakingKeeper.Undelegate(ctx, delegator, v.ValAddr, undelegateAmt) // this has to be shares amount if err != nil { return err } } + return nil } diff --git a/x/valset-pref/validator_set_test.go b/x/valset-pref/validator_set_test.go index 81c63581f28..1d5aff5349e 100644 --- a/x/valset-pref/validator_set_test.go +++ b/x/valset-pref/validator_set_test.go @@ -1,9 +1,13 @@ package keeper_test import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/osmosis-labs/osmosis/v17/x/valset-pref/types" + + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) func (s *KeeperTestSuite) TestValidateLockForForceUnlock() { @@ -274,3 +278,53 @@ func (s *KeeperTestSuite) TestIsPreferenceValid() { }) } } + +func (s *KeeperTestSuite) TestUndelegateError() { + s.SetupTest() + + valAddrs := s.SetupMultipleValidators(2) + 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 20osmo + coinToUnStake := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)) // undelegate 10osmo + + s.FundAcc(delegator, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100_000_000)}) // 100 osmo + + // valset test setup + + fmt.Println("PREFERENCES: ", valPreferences) + // SetValidatorSetPreference sets a new list of val-set + _, err := s.App.ValidatorSetPreferenceKeeper.SetValidatorSetPreference(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) + + _, 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) + +} From f4c0dab4903f15fac6582042c73b9f2e277e6fd0 Mon Sep 17 00:00:00 2001 From: stackman27 Date: Mon, 7 Aug 2023 23:35:05 +0000 Subject: [PATCH 05/28] added algorithm docs --- x/valset-pref/README.md | 15 +++++ x/valset-pref/msg_server_test.go | 52 ++++++++-------- x/valset-pref/validator_set.go | 62 ++++++------------- x/valset-pref/validator_set_test.go | 96 +++++------------------------ 4 files changed, 78 insertions(+), 147 deletions(-) diff --git a/x/valset-pref/README.md b/x/valset-pref/README.md index 2ea44ef5cff..e3de67633d3 100644 --- a/x/valset-pref/README.md +++ b/x/valset-pref/README.md @@ -42,6 +42,21 @@ 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. For each validator, compute V.ratio = undelegate_amount / amount_staked_to_val +// 3. Sort validators by V_ratio descending If V_ratio <= 1, undelegate taret amount from each validator. (happy path) +// 4. If V_ratio <= 1, undelegate taret 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) +// 7. Normal undelegate the remainder. + + #### Case 1: Users existing delegation distribution matches their validator-set preference distribution {Old docs below} diff --git a/x/valset-pref/msg_server_test.go b/x/valset-pref/msg_server_test.go index 9838586af6f..519fd99a934 100644 --- a/x/valset-pref/msg_server_test.go +++ b/x/valset-pref/msg_server_test.go @@ -319,32 +319,32 @@ func (s *KeeperTestSuite) TestUnDelegateFromValidatorSet() { 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 - expectedShares: []sdk.Dec{sdk.NewDec(2_000_000), sdk.NewDec(3_300_000), sdk.NewDec(1_200_000), sdk.NewDec(3_500_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 - expectedShares: []sdk.Dec{sdk.NewDec(1_000_000), sdk.NewDec(1_650_000), sdk.NewDec(600_000), sdk.NewDec(1_750_000)}, // validatorDelegatedShares - (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)), - setValSet: true, - expectPass: true, - }, + // { + // 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 + // expectedShares: []sdk.Dec{sdk.NewDec(2_000_000), sdk.NewDec(3_300_000), sdk.NewDec(1_200_000), sdk.NewDec(3_500_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 + // expectedShares: []sdk.Dec{sdk.NewDec(1_000_000), sdk.NewDec(1_650_000), sdk.NewDec(600_000), sdk.NewDec(1_750_000)}, // validatorDelegatedShares - (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)), + // setValSet: true, + // expectPass: true, + // }, // { // name: "Unstake more amount than the staked amount", // delegator: sdk.AccAddress([]byte("addr4---------------")), diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 52d706be98a..92000a8a6a1 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -128,19 +128,21 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co // For 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 -// Rounding logic ensures we do not undelegate more than the user has staked with the validator set +// Rounding logic 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. func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string, coin sdk.Coin) error { - existingPref, _, err := k.getValsetDelegationsAndPreferences(ctx, delegatorAddr) + existingSet, err := k.GetDelegationPreferences(ctx, delegatorAddr) if err != nil { - return err + return fmt.Errorf("user %s doesn't have validator set", delegatorAddr) } - // err already checked + delegator := sdk.MustAccAddressFromBech32(delegatorAddr) // the total amount the user wants to undelegate tokenAmt := sdk.NewDec(coin.Amount.Int64()) + // Step 1-2 var valSetRatio []ValRatio - for _, val := range existingPref.Preferences { + for _, val := range existingSet.Preferences { amountToUnDelegate := val.Weight.Mul(tokenAmt).TruncateInt() valAddr, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) if err != nil { @@ -148,8 +150,8 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string } delegation, found := k.stakingKeeper.GetDelegation(ctx, delegator, valAddr) - if found { - fmt.Println("DELEGATION: ", delegation) + if !found { + return fmt.Errorf("No delegation found for thie delegator %s to this validator %s\n", delegator, valAddr) } sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) @@ -158,7 +160,6 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string } valShares := sharesAmt.Quo(delegation.Shares) - valSetRatio = append(valSetRatio, ValRatio{ ValAddr: valAddr, UndelegateAmt: amountToUnDelegate, @@ -168,16 +169,16 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string }) } - maxVRatio := valSetRatio[0].VRatio - for _, val := range valSetRatio { - if val.VRatio.GT(maxVRatio) { - maxVRatio = val.VRatio - } - } + // Step 3 + sort.Slice(valSetRatio, func(i, j int) bool { + return valSetRatio[i].VRatio.GT(valSetRatio[j].VRatio) + }) - if maxVRatio.LTE(sdk.OneDec()) { + // Step 4 + if valSetRatio[0].VRatio.LTE(sdk.OneDec()) { fmt.Println("All validators can undelegate normally, falling to happy path exit early") for _, val := range valSetRatio { + fmt.Println("UNDELEGATED AMT: ", val.UndelegateAmt) _, err = k.stakingKeeper.Undelegate(ctx, delegator, val.ValAddr, val.UndelegateAmt.ToDec()) // this has to be shares amount if err != nil { return err @@ -187,18 +188,16 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string return nil } - // Step 4 - sort.Slice(valSetRatio, func(i, j int) bool { - return valSetRatio[i].VRatio.GT(valSetRatio[j].VRatio) - }) - // 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 := coin.Amount // Step 6 for len(valSetRatio) > 0 && valSetRatio[0].VRatio.GT(targetRatio) { - fmt.Printf("Undelegating fully from validator %s\n", valSetRatio[0].ValAddr.String()) + fmt.Printf("Undelegating fully from validator %s %s\n", valSetRatio[0].ValAddr.String(), valSetRatio[0].DelegatedAmt) _, err = k.stakingKeeper.Undelegate(ctx, delegator, valSetRatio[0].ValAddr, valSetRatio[0].DelegatedAmt.ToDec()) // this has to be shares amount if err != nil { return err @@ -222,27 +221,6 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string return nil } -// CheckUndelegateTotalAmount checks if the tokenAmount equals the total amount calculated from valset weights. -// TODO: Do we need to be doing this? Its computing that -// sum_{v in ValSet} {v.Weight * tokenAmt} = tokenAmt -// So in infinite precision this is implied by sum v.Weight = 1 -// Its _technically_ doing something by testing with Mul's decimal rounding behavior. -func (k Keeper) CheckUndelegateTotalAmount(tokenAmt sdk.Dec, existingSet []types.ValidatorPreference) error { - totalAmountFromWeights := sdk.NewDec(0) - for _, val := range existingSet { - totalAmountFromWeights = totalAmountFromWeights.Add(val.Weight.Mul(tokenAmt)) - } - - totalAmountFromWeights = totalAmountFromWeights.RoundInt().ToDec() - tokenAmt = tokenAmt.RoundInt().ToDec() - - 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) - } - - return 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 diff --git a/x/valset-pref/validator_set_test.go b/x/valset-pref/validator_set_test.go index 1d5aff5349e..622f605c9a6 100644 --- a/x/valset-pref/validator_set_test.go +++ b/x/valset-pref/validator_set_test.go @@ -1,8 +1,6 @@ package keeper_test import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/osmosis-labs/osmosis/v17/x/valset-pref/types" @@ -69,78 +67,6 @@ func (s *KeeperTestSuite) TestValidateLockForForceUnlock() { } } -func (s *KeeperTestSuite) TestCheckUndelegateTotalAmount() { - valAddrs := s.SetupMultipleValidators(3) - tests := []struct { - name string - tokenAmt sdk.Dec - existingSet []types.ValidatorPreference - expectPass bool - }{ - { - name: "token amount matches with totalAmountFromWeights", - tokenAmt: sdk.NewDec(122_312_231), - existingSet: []types.ValidatorPreference{ - { - ValOperAddress: valAddrs[0], - Weight: sdk.NewDecWithPrec(17, 2), // 0.17 - }, - { - ValOperAddress: valAddrs[1], - Weight: sdk.NewDecWithPrec(83, 2), // 0.83 - }, - }, - expectPass: true, - }, - { - name: "token decimal amount matches with totalAmountFromWeights", - tokenAmt: sdk.MustNewDecFromStr("122312231.532"), - existingSet: []types.ValidatorPreference{ - { - ValOperAddress: valAddrs[0], - Weight: sdk.NewDecWithPrec(17, 2), // 0.17 - }, - { - ValOperAddress: valAddrs[1], - Weight: sdk.NewDecWithPrec(83, 2), // 0.83 - }, - }, - expectPass: true, - }, - { - name: "tokenAmt doesnot match with totalAmountFromWeights", - tokenAmt: sdk.NewDec(122_312_231), - existingSet: []types.ValidatorPreference{ - { - ValOperAddress: valAddrs[0], - Weight: sdk.NewDecWithPrec(17, 2), // 0.17 - }, - - { - ValOperAddress: valAddrs[1], - Weight: sdk.NewDecWithPrec(83, 2), // 0.83 - }, - { - ValOperAddress: valAddrs[2], - Weight: sdk.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{ @@ -279,7 +205,8 @@ func (s *KeeperTestSuite) TestIsPreferenceValid() { } } -func (s *KeeperTestSuite) TestUndelegateError() { +// NOTE: this is the case that used to error. Fixed by this PR +func (s *KeeperTestSuite) TestUndelegateFromValSetErrorCase() { s.SetupTest() valAddrs := s.SetupMultipleValidators(2) @@ -295,14 +222,13 @@ func (s *KeeperTestSuite) TestUndelegateError() { } delegator := sdk.AccAddress([]byte("addr1---------------")) - coinToStake := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)) // delegate 20osmo - coinToUnStake := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(20_000_000)) // undelegate 10osmo + 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 := []sdk.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 - - fmt.Println("PREFERENCES: ", valPreferences) // SetValidatorSetPreference sets a new list of val-set _, err := s.App.ValidatorSetPreferenceKeeper.SetValidatorSetPreference(s.Ctx, delegator.String(), valPreferences) s.Require().NoError(err) @@ -321,10 +247,22 @@ func (s *KeeperTestSuite) TestUndelegateError() { 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()) + } + } + } From 144f0d14d570fde8ce89290e1cea589bba9334b0 Mon Sep 17 00:00:00 2001 From: stackman27 Date: Tue, 8 Aug 2023 00:03:08 +0000 Subject: [PATCH 06/28] fixed all test --- x/valset-pref/msg_server_test.go | 74 ++++++++++++++++---------------- x/valset-pref/validator_set.go | 44 ++++++++++++++++--- 2 files changed, 74 insertions(+), 44 deletions(-) diff --git a/x/valset-pref/msg_server_test.go b/x/valset-pref/msg_server_test.go index 519fd99a934..fc0e5ca560d 100644 --- a/x/valset-pref/msg_server_test.go +++ b/x/valset-pref/msg_server_test.go @@ -319,32 +319,32 @@ func (s *KeeperTestSuite) TestUnDelegateFromValidatorSet() { 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 - // expectedShares: []sdk.Dec{sdk.NewDec(2_000_000), sdk.NewDec(3_300_000), sdk.NewDec(1_200_000), sdk.NewDec(3_500_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 - // expectedShares: []sdk.Dec{sdk.NewDec(1_000_000), sdk.NewDec(1_650_000), sdk.NewDec(600_000), sdk.NewDec(1_750_000)}, // validatorDelegatedShares - (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)), - // setValSet: true, - // expectPass: true, - // }, + { + 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 + expectedShares: []sdk.Dec{sdk.NewDec(2_000_000), sdk.NewDec(3_300_000), sdk.NewDec(1_200_000), sdk.NewDec(3_500_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 + expectedShares: []sdk.Dec{sdk.NewDec(1_000_000), sdk.NewDec(1_650_000), sdk.NewDec(600_000), sdk.NewDec(1_750_000)}, // validatorDelegatedShares - (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)), + setValSet: true, + expectPass: true, + }, // { // name: "Unstake more amount than the staked amount", // delegator: sdk.AccAddress([]byte("addr4---------------")), @@ -353,21 +353,21 @@ func (s *KeeperTestSuite) TestUnDelegateFromValidatorSet() { // setValSet: true, // expectPass: false, // }, - // { - // name: "UnDelegate from existing staking position (non valSet) ", - // delegator: sdk.AccAddress([]byte("addr5---------------")), - // coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), - // coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), - // expectedShares: []sdk.Dec{sdk.NewDec(1_000_000), sdk.NewDec(1_660_000), sdk.NewDec(600_000), sdk.NewDec(1_740_000)}, // validatorDelegatedShares - (weight * coinToUnstake) - // setExistingDelegations: true, - // expectPass: true, - // }, + { + name: "UnDelegate from existing staking position (non valSet) ", + delegator: sdk.AccAddress([]byte("addr5---------------")), + coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), + coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), + expectedShares: []sdk.Dec{sdk.NewDec(1_000_000), sdk.NewDec(1_660_000), sdk.NewDec(600_000), sdk.NewDec(1_740_000)}, // validatorDelegatedShares - (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, sdk.NewInt(100_000_000)), coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(87_461_351)), - expectedShares: []sdk.Dec{sdk.NewDec(2_507_730), sdk.NewDec(4_137_755), sdk.NewDec(1_504_638), sdk.NewDec(4_388_526)}, // validatorDelegatedShares - (weight * coinToUnstake), for ex: 20_000_000 - (0.2 * 87_461_351) + expectedShares: []sdk.Dec{sdk.NewDec(2_507_730), sdk.NewDec(4_137_753), sdk.NewDec(1_504_638), sdk.NewDec(4_388_528)}, // validatorDelegatedShares - (weight * coinToUnstake), for ex: 20_000_000 - (0.2 * 87_461_351) setValSet: true, expectPass: true, }, @@ -376,7 +376,7 @@ func (s *KeeperTestSuite) TestUnDelegateFromValidatorSet() { delegator: sdk.AccAddress([]byte("addr7---------------")), coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1234)), - expectedShares: []sdk.Dec{sdk.NewDec(1_999_754), sdk.NewDec(3_299_593), sdk.NewDec(1_199_852), sdk.NewDec(3_499_567)}, // validatorDelegatedShares - (weight * coinToUnstake), + expectedShares: []sdk.Dec{sdk.NewDec(1_999_752), sdk.NewDec(3_299_593), sdk.NewDec(1_199_852), sdk.NewDec(3_499_569)}, // validatorDelegatedShares - (weight * coinToUnstake), setValSet: true, expectPass: true, }, diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 92000a8a6a1..0d3917a5b88 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -175,11 +175,31 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string }) // Step 4 + totalUnDelAmt, amountToUnDelegate := sdk.NewInt(0), sdk.NewInt(0) if valSetRatio[0].VRatio.LTE(sdk.OneDec()) { fmt.Println("All validators can undelegate normally, falling to happy path exit early") - for _, val := range valSetRatio { - fmt.Println("UNDELEGATED AMT: ", val.UndelegateAmt) - _, err = k.stakingKeeper.Undelegate(ctx, delegator, val.ValAddr, val.UndelegateAmt.ToDec()) // this has to be shares amount + for index, val := range valSetRatio { + _, validator, err := k.getValAddrAndVal(ctx, val.ValAddr.String()) + if err != nil { + return err + } + + // 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 == index { + amountToUnDelegate = coin.Amount.Sub(totalUnDelAmt).ToDec().TruncateInt() + } else { + // Calculate the amount to undelegate based on the existing weights + 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 } @@ -209,10 +229,20 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string // Step 7 fmt.Println("Distributing the remaining tokens normally amongst the remaining validators.") - for _, v := range valSetRatio { - undelegateAmt := v.Weight.MulInt(amountRemaining) - fmt.Printf("Undelegate %.2f from validator %s\n", undelegateAmt, v.ValAddr.String()) - _, err = k.stakingKeeper.Undelegate(ctx, delegator, v.ValAddr, undelegateAmt) // this has to be shares amount + for _, val := range valSetRatio { + undelegateAmt := val.Weight.MulInt(amountRemaining).TruncateInt() + fmt.Printf("Undelegate %.2f from validator %s\n", undelegateAmt, val.ValAddr.String()) + _, validator, err := k.getValAddrAndVal(ctx, val.ValAddr.String()) + if err != nil { + return err + } + + sharesAmt, err := validator.SharesFromTokens(undelegateAmt) + 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 } From 41cd2f63bed5e0083bb57bea0bf523ad7a1b6da8 Mon Sep 17 00:00:00 2001 From: stackman27 Date: Tue, 8 Aug 2023 00:03:51 +0000 Subject: [PATCH 07/28] removed unwanted files --- main.go | 70 --------------------------------------------------------- 1 file changed, 70 deletions(-) delete mode 100644 main.go diff --git a/main.go b/main.go deleted file mode 100644 index be3aaf9d549..00000000000 --- a/main.go +++ /dev/null @@ -1,70 +0,0 @@ -package main - -import ( - "fmt" - "sort" -) - -// Define a struct for the validators -type Validator struct { - Name string - Staked float64 - RatioInValset float64 - UndelegateAmt float64 - VRatio float64 -} - -func main() { - // Initialize validators X and Y - validators := []Validator{ - {Name: "X", Staked: 15.0, RatioInValset: 0.5}, - {Name: "Y", Staked: 5.0, RatioInValset: 0.5}, - } - - amount := 20.0 - - // Step 1 and 2 - for i := range validators { - validators[i].UndelegateAmt = validators[i].RatioInValset * amount - validators[i].VRatio = validators[i].UndelegateAmt / validators[i].Staked - } - - // Step 3 - maxVRatio := validators[0].VRatio - for _, v := range validators { - if v.VRatio > maxVRatio { - maxVRatio = v.VRatio - } - } - - if maxVRatio <= 1 { - fmt.Println("All validators can undelegate normally, falling to happy path.") - return - } - - // Step 4 - sort.Slice(validators, func(i, j int) bool { - return validators[i].VRatio > validators[j].VRatio - }) - - // Step 5 - targetRatio := 1.0 - amountRemaining := amount - - // Step 6 - for len(validators) > 0 && validators[0].VRatio > targetRatio { - fmt.Printf("Undelegating fully from validator %s\n", validators[0].Name) - amountRemaining -= validators[0].Staked - targetRatio *= (1 - validators[0].RatioInValset) - validators = validators[1:] - - fmt.Println(validators) - } - - // Step 7 - fmt.Println("Distributing the remaining tokens normally amongst the remaining validators.") - for _, v := range validators { - undelegate := v.RatioInValset * amountRemaining - fmt.Printf("Undelegate %.2f from validator %s\n", undelegate, v.Name) - } -} From 7403e063d5c45a8af6e01e090f90705fcc7bec8c Mon Sep 17 00:00:00 2001 From: stackman27 Date: Tue, 8 Aug 2023 00:04:44 +0000 Subject: [PATCH 08/28] remove more code --- x/valset-pref/keeper.go | 49 ----------------------------------------- 1 file changed, 49 deletions(-) diff --git a/x/valset-pref/keeper.go b/x/valset-pref/keeper.go index c3e9c65a8cd..bbdfff2847e 100644 --- a/x/valset-pref/keeper.go +++ b/x/valset-pref/keeper.go @@ -9,8 +9,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/osmosis-labs/osmosis/v17/x/valset-pref/types" ) @@ -62,53 +60,6 @@ func (k Keeper) GetDelegationPreferences(ctx sdk.Context, delegator string) (typ return valSet, nil } -// getValsetDelegationsAndPreferences retrieves the validator preferences and -// delegations for a given delegator. It returns the ValidatorSetPreferences, -// a slice of Delegations, and an error if any issues occur during the process. -// -// The function first retrieves the validator set preferences associated with the delegator. -// If preferences exist, it iterates over them and fetches each associated delegation, -// adding it to a slice of delegations. If no preferences exist, it gets all delegator -// delegations. -// -// Params: -// -// ctx - The sdk.Context representing the current context. -// delegator - The address (as a string) of the delegator whose preferences and -// delegations are to be fetched. -// -// Returns: -// -// The ValidatorSetPreferences object associated with the delegator. -// A slice of Delegation objects for the delegator. -// An error if any issues occur during the process. -func (k Keeper) getValsetDelegationsAndPreferences(ctx sdk.Context, delegator string) (types.ValidatorSetPreferences, []stakingtypes.Delegation, error) { - delAddr, err := sdk.AccAddressFromBech32(delegator) - if err != nil { - return types.ValidatorSetPreferences{}, nil, err - } - - valSet, exists := k.GetValidatorSetPreference(ctx, delegator) - var delegations []stakingtypes.Delegation - if exists { - for _, val := range valSet.Preferences { - del, found := k.stakingKeeper.GetDelegation(ctx, delAddr, sdk.ValAddress(val.ValOperAddress)) - if !found { - del = stakingtypes.Delegation{DelegatorAddress: delegator, ValidatorAddress: (val.ValOperAddress), Shares: sdk.ZeroDec()} - } - delegations = append(delegations, del) - } - } - if !exists { - delegations = k.stakingKeeper.GetDelegatorDelegations(ctx, delAddr, math.MaxUint16) - if len(delegations) == 0 { - return types.ValidatorSetPreferences{}, nil, fmt.Errorf("No Existing delegation to unbond from") - } - } - - return valSet, delegations, 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. From fbd4ba4b891518a814a79b62975e137fed12dc25 Mon Sep 17 00:00:00 2001 From: stackman27 Date: Tue, 8 Aug 2023 01:40:27 +0000 Subject: [PATCH 09/28] added more tests --- x/valset-pref/validator_set.go | 13 +++--- x/valset-pref/validator_set_test.go | 68 +++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 6 deletions(-) diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 0d3917a5b88..1e753343af2 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -95,6 +95,7 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co totalDelAmt := sdk.NewInt(0) tokenAmt := sdk.NewInt(0) + fmt.Println(existingSet.Preferences) // loop through the validatorSetPreference and delegate the proportion of the tokens based on weights for i, val := range existingSet.Preferences { _, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) @@ -108,10 +109,9 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co tokenAmt = coin.Amount.Sub(totalDelAmt).ToDec().TruncateInt() } else { // tokenAmt takes the amount to delegate, calculated by {val_distribution_weight * tokenAmt} - tokenAmt = val.Weight.Mul(coin.Amount.ToDec()).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) @@ -215,6 +215,7 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string targetRatio := sdk.OneDec() amountRemaining := coin.Amount + fmt.Println("VRATIO PRE: ", valSetRatio) // Step 6 for len(valSetRatio) > 0 && valSetRatio[0].VRatio.GT(targetRatio) { fmt.Printf("Undelegating fully from validator %s %s\n", valSetRatio[0].ValAddr.String(), valSetRatio[0].DelegatedAmt) @@ -228,16 +229,16 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string } // Step 7 - fmt.Println("Distributing the remaining tokens normally amongst the remaining validators.") + fmt.Println("Undelegating the remaining amount.") for _, val := range valSetRatio { - undelegateAmt := val.Weight.MulInt(amountRemaining).TruncateInt() - fmt.Printf("Undelegate %.2f from validator %s\n", undelegateAmt, val.ValAddr.String()) + // TestUndelegateFromValSetErrorCase1 specifically checks this logic + fmt.Printf("Undelegate %s from validator %s\n", val.UndelegateAmt, val.ValAddr.String()) _, validator, err := k.getValAddrAndVal(ctx, val.ValAddr.String()) if err != nil { return err } - sharesAmt, err := validator.SharesFromTokens(undelegateAmt) + sharesAmt, err := validator.SharesFromTokens(val.UndelegateAmt) if err != nil { return err } diff --git a/x/valset-pref/validator_set_test.go b/x/valset-pref/validator_set_test.go index 622f605c9a6..6022ae9fee8 100644 --- a/x/valset-pref/validator_set_test.go +++ b/x/valset-pref/validator_set_test.go @@ -3,6 +3,7 @@ package keeper_test import ( sdk "github.com/cosmos/cosmos-sdk/types" + valPref "github.com/osmosis-labs/osmosis/v17/x/valset-pref" "github.com/osmosis-labs/osmosis/v17/x/valset-pref/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -266,3 +267,70 @@ func (s *KeeperTestSuite) TestUndelegateFromValSetErrorCase() { } } + +// 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) + +} From 2f5caca388235186f5fdbf8400fc6349e20d294a Mon Sep 17 00:00:00 2001 From: devbot-wizard <141283918+devbot-wizard@users.noreply.github.com> Date: Tue, 8 Aug 2023 17:16:36 +0000 Subject: [PATCH 10/28] update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2066f4a0427..37f1b8029f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#5927] (https://github.com/osmosis-labs/osmosis/pull/5927) Add gas metering to x/tokenfactory trackBeforeSend hook * [#5890](https://github.com/osmosis-labs/osmosis/pull/5890) feat: CreateCLPool & LinkCFMMtoCL pool into one gov-prop * [#5964](https://github.com/osmosis-labs/osmosis/pull/5964) fix e2e test concurrency bugs +* [#5967](https://github.com/osmosis-labs/osmosis/pull/5967) fix ValSet undelegate API out of sync with existing staking ### Minor improvements & Bug Fixes From 90e9fb2fd747e95310c0b8c26bc518af76fe366e Mon Sep 17 00:00:00 2001 From: stackman27 Date: Tue, 8 Aug 2023 19:34:29 +0000 Subject: [PATCH 11/28] added test and addressed feedback --- x/valset-pref/README.md | 14 +++++++++++++- x/valset-pref/msg_server.go | 4 ++-- x/valset-pref/msg_server_test.go | 16 ++++++++-------- x/valset-pref/validator_set.go | 21 +++++++++++++++------ x/valset-pref/validator_set_test.go | 2 +- 5 files changed, 39 insertions(+), 18 deletions(-) diff --git a/x/valset-pref/README.md b/x/valset-pref/README.md index e3de67633d3..adb50f71c96 100644 --- a/x/valset-pref/README.md +++ b/x/valset-pref/README.md @@ -44,7 +44,16 @@ We can imagine describing undelegate from validator set in two cases: 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): +// 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, undelegate taret amount from each validator. (happy path) @@ -54,6 +63,9 @@ Algorithm for undelegation; // - Fully undelegate validator with greatest V_ratio. (Amount S) // - remove validator from list // - recalculate target_ratio = target_ratio * (1 - removed_V.target_percent) +// - you understand this, 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. diff --git a/x/valset-pref/msg_server.go b/x/valset-pref/msg_server.go index f555d168aa7..2f981324eec 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.DeriveValidatorSetPreference(ctx, msg.Delegator, msg.Preferences) if err != nil { return nil, err } @@ -75,7 +75,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.DeriveValidatorSetPreference(ctx, msg.Delegator, msg.Preferences) if err != nil { return nil, err } diff --git a/x/valset-pref/msg_server_test.go b/x/valset-pref/msg_server_test.go index fc0e5ca560d..c05c3791b65 100644 --- a/x/valset-pref/msg_server_test.go +++ b/x/valset-pref/msg_server_test.go @@ -345,14 +345,14 @@ func (s *KeeperTestSuite) TestUnDelegateFromValidatorSet() { setValSet: true, expectPass: true, }, - // { - // name: "Unstake more amount than the staked amount", - // delegator: sdk.AccAddress([]byte("addr4---------------")), - // 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: "Unstake more amount than the staked amount", + delegator: sdk.AccAddress([]byte("addr4---------------")), + 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: "UnDelegate from existing staking position (non valSet) ", delegator: sdk.AccAddress([]byte("addr5---------------")), diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 1e753343af2..81c0685d7e9 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -52,10 +52,11 @@ func (k Keeper) GetValidatorSetPreference(ctx sdk.Context, delegator string) (ty return valsetPref, true } -// SetValidatorSetPreference creates or updates delegators validator set. +// DeriveValidatorSetPreference 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. // NOTE: this function doesnot add valset to the state -func (k Keeper) SetValidatorSetPreference(ctx sdk.Context, delegator string, preferences []types.ValidatorPreference) (types.ValidatorSetPreferences, error) { +func (k Keeper) DeriveValidatorSetPreference(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 @@ -137,13 +138,15 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string } delegator := sdk.MustAccAddressFromBech32(delegatorAddr) - // the total amount the user wants to undelegate - tokenAmt := sdk.NewDec(coin.Amount.Int64()) + // total amount the user wants to undelegate + tokenAmtToUndelegate := sdk.NewDec(coin.Amount.Int64()) + // total amount user has delegated + totalDelegatedAmt := sdk.ZeroDec() // Step 1-2 var valSetRatio []ValRatio for _, val := range existingSet.Preferences { - amountToUnDelegate := val.Weight.Mul(tokenAmt).TruncateInt() + amountToUnDelegate := val.Weight.Mul(tokenAmtToUndelegate).TruncateInt() valAddr, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) if err != nil { return err @@ -160,6 +163,9 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string } valShares := sharesAmt.Quo(delegation.Shares) + tokenAmt := validator.TokensFromShares(delegation.Shares) + totalDelegatedAmt = totalDelegatedAmt.Add(tokenAmt) + valSetRatio = append(valSetRatio, ValRatio{ ValAddr: valAddr, UndelegateAmt: amountToUnDelegate, @@ -169,6 +175,10 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string }) } + if tokenAmtToUndelegate.GT(totalDelegatedAmt) { + return fmt.Errorf("Total tokenAmountToUndelegate more than delegated amount have %s got %s\n", totalDelegatedAmt, tokenAmtToUndelegate) + } + // Step 3 sort.Slice(valSetRatio, func(i, j int) bool { return valSetRatio[i].VRatio.GT(valSetRatio[j].VRatio) @@ -215,7 +225,6 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string targetRatio := sdk.OneDec() amountRemaining := coin.Amount - fmt.Println("VRATIO PRE: ", valSetRatio) // Step 6 for len(valSetRatio) > 0 && valSetRatio[0].VRatio.GT(targetRatio) { fmt.Printf("Undelegating fully from validator %s %s\n", valSetRatio[0].ValAddr.String(), valSetRatio[0].DelegatedAmt) diff --git a/x/valset-pref/validator_set_test.go b/x/valset-pref/validator_set_test.go index 6022ae9fee8..793f918f1a9 100644 --- a/x/valset-pref/validator_set_test.go +++ b/x/valset-pref/validator_set_test.go @@ -231,7 +231,7 @@ func (s *KeeperTestSuite) TestUndelegateFromValSetErrorCase() { // valset test setup // SetValidatorSetPreference sets a new list of val-set - _, err := s.App.ValidatorSetPreferenceKeeper.SetValidatorSetPreference(s.Ctx, delegator.String(), valPreferences) + _, err := s.App.ValidatorSetPreferenceKeeper.DeriveValidatorSetPreference(s.Ctx, delegator.String(), valPreferences) s.Require().NoError(err) s.App.ValidatorSetPreferenceKeeper.SetValidatorSetPreferences(s.Ctx, delegator.String(), types.ValidatorSetPreferences{ From b317a0eea55e25de2c5ea56ec4973a51ef0be643 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Tue, 8 Aug 2023 22:43:20 -0500 Subject: [PATCH 12/28] Update x/valset-pref/validator_set.go --- x/valset-pref/validator_set.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 81c0685d7e9..41b022b0021 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -55,7 +55,7 @@ func (k Keeper) GetValidatorSetPreference(ctx sdk.Context, delegator string) (ty // DeriveValidatorSetPreference 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. -// NOTE: this function doesnot add valset to the state +// NOTE: this function does not add valset to the state func (k Keeper) DeriveValidatorSetPreference(ctx sdk.Context, delegator string, preferences []types.ValidatorPreference) (types.ValidatorSetPreferences, error) { existingValSet, found := k.GetValidatorSetPreference(ctx, delegator) if found { From b1ece1b8b049eb8c4944a7b56a4ee5f69dec30ad Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Tue, 8 Aug 2023 22:43:25 -0500 Subject: [PATCH 13/28] Update x/valset-pref/validator_set.go --- x/valset-pref/validator_set.go | 1 - 1 file changed, 1 deletion(-) diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 41b022b0021..1da21bdc055 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -96,7 +96,6 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co totalDelAmt := sdk.NewInt(0) tokenAmt := sdk.NewInt(0) - fmt.Println(existingSet.Preferences) // loop through the validatorSetPreference and delegate the proportion of the tokens based on weights for i, val := range existingSet.Preferences { _, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) From 53a14d92efe2191c9b852568d8e2093a56cb42b9 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Tue, 8 Aug 2023 22:43:31 -0500 Subject: [PATCH 14/28] Update x/valset-pref/README.md --- x/valset-pref/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/valset-pref/README.md b/x/valset-pref/README.md index adb50f71c96..d341bba2ab4 100644 --- a/x/valset-pref/README.md +++ b/x/valset-pref/README.md @@ -57,7 +57,7 @@ Algorithm for undelegation; // 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, undelegate taret amount from each validator. (happy path) -// 4. If V_ratio <= 1, undelegate taret amount from each validator. (happy path) +// 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) From 11bc176c74aa99d52a29629b06a5a03f1be6ee1b Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sun, 13 Aug 2023 11:21:02 -0500 Subject: [PATCH 15/28] Minor cleanup --- x/valset-pref/README.md | 49 +++++++++++++++++----------------- x/valset-pref/validator_set.go | 5 ++-- 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/x/valset-pref/README.md b/x/valset-pref/README.md index d341bba2ab4..559af189347 100644 --- a/x/valset-pref/README.md +++ b/x/valset-pref/README.md @@ -43,30 +43,31 @@ We can imagine describing undelegate from validator set in two cases: - 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, undelegate taret amount from each validator. (happy path) -// 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) -// - you understand this, 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. +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, undelegate taret amount from each validator. (happy path) +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 diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 1da21bdc055..f4de488c561 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -138,11 +138,12 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string delegator := sdk.MustAccAddressFromBech32(delegatorAddr) // total amount the user wants to undelegate - tokenAmtToUndelegate := sdk.NewDec(coin.Amount.Int64()) + tokenAmtToUndelegate := coin.Amount.ToDec() // total amount user has delegated totalDelegatedAmt := sdk.ZeroDec() - // Step 1-2 + // Step 1-2, compute the total amount delegated and the amount to undelegate for each validator + // under valset-ratios. var valSetRatio []ValRatio for _, val := range existingSet.Preferences { amountToUnDelegate := val.Weight.Mul(tokenAmtToUndelegate).TruncateInt() From 3799111c69d354292255de0647ca17c0363a8054 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sun, 13 Aug 2023 11:23:00 -0500 Subject: [PATCH 16/28] re-use validator gets --- x/valset-pref/validator_set.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index f4de488c561..6d2e23cc4b3 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -145,12 +145,14 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string // Step 1-2, compute the total amount delegated and the amount to undelegate for each validator // under valset-ratios. var valSetRatio []ValRatio + validators := map[string]stakingtypes.Validator{} for _, val := range existingSet.Preferences { amountToUnDelegate := val.Weight.Mul(tokenAmtToUndelegate).TruncateInt() valAddr, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) if err != nil { return err } + validators[valAddr.String()] = validator delegation, found := k.stakingKeeper.GetDelegation(ctx, delegator, valAddr) if !found { @@ -189,10 +191,7 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string if valSetRatio[0].VRatio.LTE(sdk.OneDec()) { fmt.Println("All validators can undelegate normally, falling to happy path exit early") for index, val := range valSetRatio { - _, validator, err := k.getValAddrAndVal(ctx, val.ValAddr.String()) - if err != nil { - return err - } + validator := validators[val.ValAddr.String()] // in the last valset iteration we dont calculate it from shares using decimals and trucation, // we use whats remaining to get more accurate value From dcfc8062ac4e1cbc25f65506e8b87f02fbdb0179 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Mon, 14 Aug 2023 13:53:24 -0500 Subject: [PATCH 17/28] Refactor --- x/valset-pref/keeper.go | 37 +++++++++++++++ x/valset-pref/validator_set.go | 87 ++++++++++++++++++---------------- 2 files changed, 84 insertions(+), 40 deletions(-) diff --git a/x/valset-pref/keeper.go b/x/valset-pref/keeper.go index bbdfff2847e..abaa6b4bf23 100644 --- a/x/valset-pref/keeper.go +++ b/x/valset-pref/keeper.go @@ -9,6 +9,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/osmosis-labs/osmosis/v17/x/valset-pref/types" ) @@ -88,3 +90,38 @@ func (k Keeper) GetExistingStakingDelegations(ctx sdk.Context, delAddr sdk.AccAd return existingDelsValSetFormatted, nil } + +// getValsetDelegationsAndPreferences retrieves the validator preferences and +// delegations for a given delegator. It returns the ValidatorSetPreferences, +// a slice of Delegations, and an error if any issues occur during the process. +// +// The function first retrieves the validator set preferences associated with the delegator. +// If preferences exist, it iterates over them and fetches each associated delegation, +// adding it to a slice of delegations. If no preferences exist, it gets all delegator +// delegations. +func (k Keeper) getValsetDelegationsAndPreferences(ctx sdk.Context, delegator string) (types.ValidatorSetPreferences, []stakingtypes.Delegation, error) { + delAddr, err := sdk.AccAddressFromBech32(delegator) + if err != nil { + return types.ValidatorSetPreferences{}, nil, err + } + + valSet, exists := k.GetValidatorSetPreference(ctx, delegator) + var delegations []stakingtypes.Delegation + if exists { + for _, val := range valSet.Preferences { + del, found := k.stakingKeeper.GetDelegation(ctx, delAddr, sdk.ValAddress(val.ValOperAddress)) + if !found { + del = stakingtypes.Delegation{DelegatorAddress: delegator, ValidatorAddress: (val.ValOperAddress), Shares: sdk.ZeroDec()} + } + delegations = append(delegations, del) + } + } + if !exists { + delegations = k.stakingKeeper.GetDelegatorDelegations(ctx, delAddr, math.MaxUint16) + if len(delegations) == 0 { + return types.ValidatorSetPreferences{}, nil, fmt.Errorf("No Existing delegation to unbond from") + } + } + + return valSet, delegations, nil +} diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 6d2e23cc4b3..f57268419a5 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -130,55 +130,23 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co // our undelegate logic would attempt to undelegate 3osmo from A, 1.8osmo from B, 1.2osmo from C // Rounding logic 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. -func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string, coin sdk.Coin) error { +func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string, undelegation sdk.Coin) error { existingSet, err := k.GetDelegationPreferences(ctx, delegatorAddr) if err != nil { return fmt.Errorf("user %s doesn't have validator set", delegatorAddr) } delegator := sdk.MustAccAddressFromBech32(delegatorAddr) - // total amount the user wants to undelegate - tokenAmtToUndelegate := coin.Amount.ToDec() - // total amount user has delegated - totalDelegatedAmt := sdk.ZeroDec() // Step 1-2, compute the total amount delegated and the amount to undelegate for each validator // under valset-ratios. - var valSetRatio []ValRatio - validators := map[string]stakingtypes.Validator{} - for _, val := range existingSet.Preferences { - amountToUnDelegate := val.Weight.Mul(tokenAmtToUndelegate).TruncateInt() - valAddr, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) - if err != nil { - return err - } - validators[valAddr.String()] = validator - - delegation, found := k.stakingKeeper.GetDelegation(ctx, delegator, valAddr) - if !found { - return fmt.Errorf("No delegation found for thie delegator %s to this validator %s\n", delegator, valAddr) - } - - sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) - if err != nil { - return err - } - - valShares := sharesAmt.Quo(delegation.Shares) - tokenAmt := validator.TokensFromShares(delegation.Shares) - totalDelegatedAmt = totalDelegatedAmt.Add(tokenAmt) - - valSetRatio = append(valSetRatio, ValRatio{ - ValAddr: valAddr, - UndelegateAmt: amountToUnDelegate, - VRatio: valShares, - DelegatedAmt: delegation.Shares.TruncateInt(), - Weight: val.Weight, - }) + valSetRatio, validators, totalDelegatedAmt, err := k.getValsetRatios(ctx, delegator, existingSet.Preferences, undelegation.Amount) + if err != nil { + return err } - if tokenAmtToUndelegate.GT(totalDelegatedAmt) { - return fmt.Errorf("Total tokenAmountToUndelegate more than delegated amount have %s got %s\n", totalDelegatedAmt, tokenAmtToUndelegate) + if undelegation.Amount.ToDec().GT(totalDelegatedAmt) { + return fmt.Errorf("Total tokenAmountToUndelegate more than delegated amount have %s got %s\n", totalDelegatedAmt, undelegation.Amount) } // Step 3 @@ -196,7 +164,7 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string // 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 == index { - amountToUnDelegate = coin.Amount.Sub(totalUnDelAmt).ToDec().TruncateInt() + amountToUnDelegate = undelegation.Amount.Sub(totalUnDelAmt).ToDec().TruncateInt() } else { // Calculate the amount to undelegate based on the existing weights amountToUnDelegate = val.UndelegateAmt @@ -222,7 +190,7 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string // 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 := coin.Amount + amountRemaining := undelegation.Amount // Step 6 for len(valSetRatio) > 0 && valSetRatio[0].VRatio.GT(targetRatio) { @@ -260,6 +228,45 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string return nil } +func (k Keeper) getValsetRatios(ctx sdk.Context, delegator sdk.AccAddress, + prefs []types.ValidatorPreference, undelegateAmt sdk.Int) ([]ValRatio, map[string]stakingtypes.Validator, sdk.Dec, error) { + // total amount user has delegated + totalDelegatedAmt := sdk.ZeroDec() + var valSetRatio []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 valSetRatio, validators, totalDelegatedAmt, err + } + validators[valAddr.String()] = validator + + delegation, found := k.stakingKeeper.GetDelegation(ctx, delegator, valAddr) + if !found { + return valSetRatio, validators, totalDelegatedAmt, fmt.Errorf("No delegation found for thie delegator %s to this validator %s\n", delegator, valAddr) + } + + sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) + if err != nil { + return valSetRatio, validators, totalDelegatedAmt, err + } + + valShares := sharesAmt.Quo(delegation.Shares) + tokenAmt := validator.TokensFromShares(delegation.Shares) + totalDelegatedAmt = totalDelegatedAmt.Add(tokenAmt) + + valSetRatio = append(valSetRatio, ValRatio{ + ValAddr: valAddr, + UndelegateAmt: amountToUnDelegate, + VRatio: valShares, + DelegatedAmt: delegation.Shares.TruncateInt(), + Weight: val.Weight, + }) + } + return valSetRatio, 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 From d9891dd5d444280fba1716f2c918702b6d1f7dc5 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Mon, 14 Aug 2023 14:04:12 -0500 Subject: [PATCH 18/28] Highlight bug --- x/valset-pref/validator_set.go | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index f57268419a5..3b20068b238 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -131,7 +131,7 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co // Rounding logic 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. func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string, undelegation sdk.Coin) error { - existingSet, err := k.GetDelegationPreferences(ctx, delegatorAddr) + existingSet, delegations, err := k.getValsetDelegationsAndPreferences(ctx, delegatorAddr) if err != nil { return fmt.Errorf("user %s doesn't have validator set", delegatorAddr) } @@ -140,7 +140,7 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string // 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) + valSetRatio, validators, totalDelegatedAmt, err := k.getValsetRatios(ctx, existingSet.Preferences, delegations, undelegation.Amount) if err != nil { return err } @@ -228,13 +228,19 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string return nil } -func (k Keeper) getValsetRatios(ctx sdk.Context, delegator sdk.AccAddress, - prefs []types.ValidatorPreference, undelegateAmt sdk.Int) ([]ValRatio, map[string]stakingtypes.Validator, sdk.Dec, error) { +func (k Keeper) getValsetRatios(ctx sdk.Context, + prefs []types.ValidatorPreference, delegations []stakingtypes.Delegation, + undelegateAmt sdk.Int) ([]ValRatio, map[string]stakingtypes.Validator, sdk.Dec, error) { // total amount user has delegated totalDelegatedAmt := sdk.ZeroDec() var valSetRatio []ValRatio validators := map[string]stakingtypes.Validator{} - for _, val := range prefs { + for i, val := range prefs { + delegation := delegations[i] + if delegation.Shares.IsZero() { + // TODO: Define what we do + fmt.Println("currently undefined") + } amountToUnDelegate := val.Weight.MulInt(undelegateAmt).TruncateInt() valAddr, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) if err != nil { @@ -242,19 +248,13 @@ func (k Keeper) getValsetRatios(ctx sdk.Context, delegator sdk.AccAddress, } validators[valAddr.String()] = validator - delegation, found := k.stakingKeeper.GetDelegation(ctx, delegator, valAddr) - if !found { - return valSetRatio, validators, totalDelegatedAmt, fmt.Errorf("No delegation found for thie delegator %s to this validator %s\n", delegator, valAddr) - } - sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) if err != nil { return valSetRatio, validators, totalDelegatedAmt, err } valShares := sharesAmt.Quo(delegation.Shares) - tokenAmt := validator.TokensFromShares(delegation.Shares) - totalDelegatedAmt = totalDelegatedAmt.Add(tokenAmt) + totalDelegatedAmt = totalDelegatedAmt.AddMut(validator.TokensFromShares(delegation.Shares)) valSetRatio = append(valSetRatio, ValRatio{ ValAddr: valAddr, From 5ac4023eb034c2339e0b58243ba7c78d6f9a650a Mon Sep 17 00:00:00 2001 From: stackman27 Date: Tue, 22 Aug 2023 00:56:13 +0000 Subject: [PATCH 19/28] fixed the issue --- x/valset-pref/keeper.go | 82 ++++------ x/valset-pref/msg_server_test.go | 232 ++++++++++++++++++++-------- x/valset-pref/validator_set.go | 24 +-- x/valset-pref/validator_set_test.go | 6 +- 4 files changed, 217 insertions(+), 127 deletions(-) diff --git a/x/valset-pref/keeper.go b/x/valset-pref/keeper.go index abaa6b4bf23..f9e2a95869f 100644 --- a/x/valset-pref/keeper.go +++ b/x/valset-pref/keeper.go @@ -51,77 +51,53 @@ func (k Keeper) GetDelegationPreferences(ctx sdk.Context, delegator string) (typ 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{}, fmt.Errorf("No Existing delegation") } - return types.ValidatorSetPreferences{Preferences: existingDelsValSetFormatted}, nil + return types.ValidatorSetPreferences{Preferences: calculateSharesAndFormat(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 +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, fmt.Errorf("No Existing delegation") - } - existingTotalShares := sdk.NewDec(0) - // calculate total shares that currently exists - for _, existingDelegation := range existingDelegations { - existingTotalShares = existingTotalShares.Add(existingDelegation.Shares) + // 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") } - // 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), - }) + // Returning existing valSet when there are no existing delegations + if exists && len(existingDelegations) == 0 { + return valSet, nil } - return existingDelsValSetFormatted, nil + // this can either be valSet doesnot exist and existing delegations exist + // or valset exists and existing delegation exists + return types.ValidatorSetPreferences{Preferences: calculateSharesAndFormat(existingDelegations)}, nil } -// getValsetDelegationsAndPreferences retrieves the validator preferences and -// delegations for a given delegator. It returns the ValidatorSetPreferences, -// a slice of Delegations, and an error if any issues occur during the process. -// -// The function first retrieves the validator set preferences associated with the delegator. -// If preferences exist, it iterates over them and fetches each associated delegation, -// adding it to a slice of delegations. If no preferences exist, it gets all delegator -// delegations. -func (k Keeper) getValsetDelegationsAndPreferences(ctx sdk.Context, delegator string) (types.ValidatorSetPreferences, []stakingtypes.Delegation, error) { - delAddr, err := sdk.AccAddressFromBech32(delegator) - if err != nil { - return types.ValidatorSetPreferences{}, nil, err +func calculateSharesAndFormat(existingDelegations []stakingtypes.Delegation) []types.ValidatorPreference { + existingTotalShares := sdk.NewDec(0) + for _, existingDelegation := range existingDelegations { + existingTotalShares = existingTotalShares.Add(existingDelegation.Shares) } - valSet, exists := k.GetValidatorSetPreference(ctx, delegator) - var delegations []stakingtypes.Delegation - if exists { - for _, val := range valSet.Preferences { - del, found := k.stakingKeeper.GetDelegation(ctx, delAddr, sdk.ValAddress(val.ValOperAddress)) - if !found { - del = stakingtypes.Delegation{DelegatorAddress: delegator, ValidatorAddress: (val.ValOperAddress), Shares: sdk.ZeroDec()} - } - delegations = append(delegations, del) - } - } - if !exists { - delegations = k.stakingKeeper.GetDelegatorDelegations(ctx, delAddr, math.MaxUint16) - if len(delegations) == 0 { - return types.ValidatorSetPreferences{}, nil, fmt.Errorf("No Existing delegation to unbond from") + existingDelsValSetFormatted := make([]types.ValidatorPreference, len(existingDelegations)) + for i, existingDelegation := range existingDelegations { + existingDelsValSetFormatted[i] = types.ValidatorPreference{ + ValOperAddress: existingDelegation.ValidatorAddress, + Weight: existingDelegation.Shares.Quo(existingTotalShares), } } - - return valSet, delegations, nil + return existingDelsValSetFormatted } diff --git a/x/valset-pref/msg_server_test.go b/x/valset-pref/msg_server_test.go index c05c3791b65..8d21ca700b4 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" appParams "github.com/osmosis-labs/osmosis/v17/app/params" valPref "github.com/osmosis-labs/osmosis/v17/x/valset-pref" @@ -306,79 +309,156 @@ func (s *KeeperTestSuite) TestDelegateToValidatorSet() { 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 - coinToUnStake sdk.Coin - expectedShares []sdk.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 []sdk.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 - expectedShares: []sdk.Dec{sdk.NewDec(2_000_000), sdk.NewDec(3_300_000), sdk.NewDec(1_200_000), sdk.NewDec(3_500_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 - expectedShares: []sdk.Dec{sdk.NewDec(1_000_000), sdk.NewDec(1_650_000), sdk.NewDec(600_000), sdk.NewDec(1_750_000)}, // validatorDelegatedShares - (weight * coinToUnstake) - setValSet: true, - expectPass: true, + 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 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)), - 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 more amount than the staked amount", - delegator: sdk.AccAddress([]byte("addr4---------------")), - 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: "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 from existing staking position (non valSet) ", - delegator: sdk.AccAddress([]byte("addr5---------------")), - coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), - coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), - expectedShares: []sdk.Dec{sdk.NewDec(1_000_000), sdk.NewDec(1_660_000), sdk.NewDec(600_000), sdk.NewDec(1_740_000)}, // validatorDelegatedShares - (weight * coinToUnstake) + 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, sdk.NewInt(100_000_000)), - coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(87_461_351)), - expectedShares: []sdk.Dec{sdk.NewDec(2_507_730), sdk.NewDec(4_137_753), sdk.NewDec(1_504_638), sdk.NewDec(4_388_528)}, // 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: "Undelegate extreme amounts to check truncation, small amount", - delegator: sdk.AccAddress([]byte("addr7---------------")), - coinToStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(10_000_000)), - coinToUnStake: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1234)), - expectedShares: []sdk.Dec{sdk.NewDec(1_999_752), sdk.NewDec(3_299_593), sdk.NewDec(1_199_852), sdk.NewDec(3_499_569)}, // validatorDelegatedShares - (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, }, } @@ -405,21 +485,51 @@ func (s *KeeperTestSuite) TestUnDelegateFromValidatorSet() { 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) - // 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/validator_set.go b/x/valset-pref/validator_set.go index 3b20068b238..2c245a275ee 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -131,7 +131,7 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co // Rounding logic 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. func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string, undelegation sdk.Coin) error { - existingSet, delegations, err := k.getValsetDelegationsAndPreferences(ctx, delegatorAddr) + existingSet, err := k.GetValSetPreferencesWithDelegations(ctx, delegatorAddr) if err != nil { return fmt.Errorf("user %s doesn't have validator set", delegatorAddr) } @@ -140,7 +140,7 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string // 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, existingSet.Preferences, delegations, undelegation.Amount) + valSetRatio, validators, totalDelegatedAmt, err := k.getValsetRatios(ctx, delegator, existingSet.Preferences, undelegation.Amount) if err != nil { return err } @@ -166,7 +166,7 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string if len(existingSet.Preferences)-1 == index { amountToUnDelegate = undelegation.Amount.Sub(totalUnDelAmt).ToDec().TruncateInt() } else { - // Calculate the amount to undelegate based on the existing weights + // Calculate the amount to undelegate based on the existing weightxs amountToUnDelegate = val.UndelegateAmt totalUnDelAmt = totalUnDelAmt.Add(amountToUnDelegate) } @@ -228,19 +228,14 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string return nil } -func (k Keeper) getValsetRatios(ctx sdk.Context, - prefs []types.ValidatorPreference, delegations []stakingtypes.Delegation, - undelegateAmt sdk.Int) ([]ValRatio, map[string]stakingtypes.Validator, sdk.Dec, error) { +func (k Keeper) getValsetRatios(ctx sdk.Context, delegator sdk.AccAddress, + prefs []types.ValidatorPreference, undelegateAmt sdk.Int) ([]ValRatio, map[string]stakingtypes.Validator, sdk.Dec, error) { // total amount user has delegated totalDelegatedAmt := sdk.ZeroDec() var valSetRatio []ValRatio validators := map[string]stakingtypes.Validator{} - for i, val := range prefs { - delegation := delegations[i] - if delegation.Shares.IsZero() { - // TODO: Define what we do - fmt.Println("currently undefined") - } + + for _, val := range prefs { amountToUnDelegate := val.Weight.MulInt(undelegateAmt).TruncateInt() valAddr, validator, err := k.getValAddrAndVal(ctx, val.ValOperAddress) if err != nil { @@ -248,6 +243,11 @@ func (k Keeper) getValsetRatios(ctx sdk.Context, } validators[valAddr.String()] = validator + delegation, found := k.stakingKeeper.GetDelegation(ctx, delegator, valAddr) + if !found { + return valSetRatio, validators, totalDelegatedAmt, fmt.Errorf("No delegation found for thie delegator %s to this validator %s\n", delegator, valAddr) + } + sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) if err != nil { return valSetRatio, validators, totalDelegatedAmt, err diff --git a/x/valset-pref/validator_set_test.go b/x/valset-pref/validator_set_test.go index 793f918f1a9..b2db9e3a75d 100644 --- a/x/valset-pref/validator_set_test.go +++ b/x/valset-pref/validator_set_test.go @@ -1,6 +1,8 @@ package keeper_test import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" valPref "github.com/osmosis-labs/osmosis/v17/x/valset-pref" @@ -210,7 +212,7 @@ func (s *KeeperTestSuite) TestIsPreferenceValid() { func (s *KeeperTestSuite) TestUndelegateFromValSetErrorCase() { s.SetupTest() - valAddrs := s.SetupMultipleValidators(2) + valAddrs := s.SetupMultipleValidators(3) valPreferences := []types.ValidatorPreference{ { ValOperAddress: valAddrs[0], @@ -252,6 +254,8 @@ func (s *KeeperTestSuite) TestUndelegateFromValSetErrorCase() { _, err = s.App.StakingKeeper.Delegate(s.Ctx, delegator, sdk.NewInt(10_000_000), stakingtypes.Unbonded, validator, true) s.Require().NoError(err) + fmt.Println("3 validators: ", valAddrs[0], valAddrs[1], valAddrs[2]) + err = s.App.ValidatorSetPreferenceKeeper.UndelegateFromValidatorSet(s.Ctx, delegator.String(), coinToUnStake) s.Require().NoError(err) From 25cdc5f04d2f94c9001e45f22a5c4d47c27e4183 Mon Sep 17 00:00:00 2001 From: stackman27 Date: Tue, 22 Aug 2023 00:57:24 +0000 Subject: [PATCH 20/28] added comments --- x/valset-pref/keeper.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/x/valset-pref/keeper.go b/x/valset-pref/keeper.go index f9e2a95869f..776aa65ee33 100644 --- a/x/valset-pref/keeper.go +++ b/x/valset-pref/keeper.go @@ -62,6 +62,13 @@ func (k Keeper) GetDelegationPreferences(ctx sdk.Context, delegator string) (typ return valSet, nil } +// 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 a validator set preference and existing delegations, or existing delegations +// but no validator set preference, it 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 { From e27f258b6b499c3037d7361493fe9f802d0c1566 Mon Sep 17 00:00:00 2001 From: devbot-wizard <141283918+devbot-wizard@users.noreply.github.com> Date: Tue, 8 Aug 2023 17:16:36 +0000 Subject: [PATCH 21/28] update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2da9e98e1a1..110de636493 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -101,6 +101,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#5948] (https://github.com/osmosis-labs/osmosis/pull/5948) Parameterizing Pool Type Information in Protorev * [#5953] (https://github.com/osmosis-labs/osmosis/pull/5953) Supporting two pool routes in ProtoRev * [#6012](https://github.com/osmosis-labs/osmosis/pull/6012) chore: add autocomplete to makefile +* [#5967](https://github.com/osmosis-labs/osmosis/pull/5967) fix ValSet undelegate API out of sync with existing staking ### Minor improvements & Bug Fixes From 54b4decf64998b00fe3e3f157e9f70118bb1aadc Mon Sep 17 00:00:00 2001 From: stackman27 Date: Tue, 22 Aug 2023 00:56:13 +0000 Subject: [PATCH 22/28] fixed the issue --- x/valset-pref/keeper.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/x/valset-pref/keeper.go b/x/valset-pref/keeper.go index 9985d8d72c5..d4d80fdb493 100644 --- a/x/valset-pref/keeper.go +++ b/x/valset-pref/keeper.go @@ -50,6 +50,10 @@ func (k Keeper) GetDelegationPreferences(ctx sdk.Context, delegator string) (typ if err != nil { return types.ValidatorSetPreferences{}, err } +<<<<<<< HEAD +======= + +>>>>>>> d982e9b1d (fixed the issue) existingDelegations := k.stakingKeeper.GetDelegatorDelegations(ctx, delAddr, math.MaxUint16) if len(existingDelegations) == 0 { return types.ValidatorSetPreferences{}, fmt.Errorf("No Existing delegation") From 77a9655f8dbd82f25cf31325e6b8b965e8db2583 Mon Sep 17 00:00:00 2001 From: stackman27 Date: Tue, 22 Aug 2023 16:05:04 +0000 Subject: [PATCH 23/28] fixed go test --- x/valset-pref/keeper.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/valset-pref/keeper.go b/x/valset-pref/keeper.go index d4d80fdb493..2836c9c18b3 100644 --- a/x/valset-pref/keeper.go +++ b/x/valset-pref/keeper.go @@ -56,7 +56,7 @@ func (k Keeper) GetDelegationPreferences(ctx sdk.Context, delegator string) (typ >>>>>>> d982e9b1d (fixed the issue) existingDelegations := k.stakingKeeper.GetDelegatorDelegations(ctx, delAddr, math.MaxUint16) if len(existingDelegations) == 0 { - return types.ValidatorSetPreferences{}, fmt.Errorf("No Existing delegation") + return types.ValidatorSetPreferences{}, types.ErrNoDelegation } return types.ValidatorSetPreferences{Preferences: calculateSharesAndFormat(existingDelegations)}, nil From 324a281b2636974c763db88192d32106933b33db Mon Sep 17 00:00:00 2001 From: stackman27 Date: Tue, 22 Aug 2023 16:06:42 +0000 Subject: [PATCH 24/28] fixed test --- x/valset-pref/keeper.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/x/valset-pref/keeper.go b/x/valset-pref/keeper.go index 2836c9c18b3..666699dc9a8 100644 --- a/x/valset-pref/keeper.go +++ b/x/valset-pref/keeper.go @@ -50,10 +50,6 @@ func (k Keeper) GetDelegationPreferences(ctx sdk.Context, delegator string) (typ if err != nil { return types.ValidatorSetPreferences{}, err } -<<<<<<< HEAD -======= - ->>>>>>> d982e9b1d (fixed the issue) existingDelegations := k.stakingKeeper.GetDelegatorDelegations(ctx, delAddr, math.MaxUint16) if len(existingDelegations) == 0 { return types.ValidatorSetPreferences{}, types.ErrNoDelegation From 31e9008ba5286cfd3634f41335f87e30a174f741 Mon Sep 17 00:00:00 2001 From: roman Date: Wed, 27 Sep 2023 20:01:01 -0400 Subject: [PATCH 25/28] lint --- x/valset-pref/validator_set.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index a0954883a22..de16cf9141e 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -23,10 +23,10 @@ type valSet struct { type ValRatio struct { ValAddr sdk.ValAddress - Weight sdk.Dec - DelegatedAmt sdk.Int - UndelegateAmt sdk.Int - VRatio sdk.Dec + Weight osmomath.Dec + DelegatedAmt osmomath.Int + UndelegateAmt osmomath.Int + VRatio osmomath.Dec } // SetValidatorSetPreferences sets a new valset position for a delegator in modules state. @@ -155,7 +155,8 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string }) // Step 4 - totalUnDelAmt, amountToUnDelegate := sdk.NewInt(0), sdk.NewInt(0) + totalUnDelAmt := sdk.NewInt(0) + var amountToUnDelegate osmomath.Int if valSetRatio[0].VRatio.LTE(sdk.OneDec()) { fmt.Println("All validators can undelegate normally, falling to happy path exit early") for index, val := range valSetRatio { From 9e9829260f4c9fc8ce40ac861b89cbd938fd33d3 Mon Sep 17 00:00:00 2001 From: "Matt, Park" <45252226+mattverse@users.noreply.github.com> Date: Fri, 6 Oct 2023 02:20:04 +0900 Subject: [PATCH 26/28] Finish ValSet Pref Unbonding (#6630) * Add Test cases and fix * Update x/valset-pref/keeper.go * Adams comment * add error types and tidy test --------- Co-authored-by: Adam Tucker Co-authored-by: Adam Tucker --- x/valset-pref/README.md | 2 +- x/valset-pref/export_test.go | 11 ++ x/valset-pref/keeper.go | 35 ++-- x/valset-pref/keeper_test.go | 175 ++++++++++++++++++++ x/valset-pref/msg_server.go | 6 +- x/valset-pref/types/errors.go | 24 ++- x/valset-pref/validator_set.go | 55 +++---- x/valset-pref/validator_set_test.go | 247 +++++++++++++++++++++++++++- 8 files changed, 499 insertions(+), 56 deletions(-) diff --git a/x/valset-pref/README.md b/x/valset-pref/README.md index 2a72bc863ae..1f129c1ab2d 100644 --- a/x/valset-pref/README.md +++ b/x/valset-pref/README.md @@ -57,7 +57,7 @@ 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, undelegate taret amount from each validator. (happy path) +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: diff --git a/x/valset-pref/export_test.go b/x/valset-pref/export_test.go index ba5b1679c84..7972ac7915a 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/v19/x/lockup/types" + "github.com/osmosis-labs/osmosis/v19/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 2768d4b6ab6..0e4255d174d 100644 --- a/x/valset-pref/keeper.go +++ b/x/valset-pref/keeper.go @@ -55,7 +55,7 @@ func (k Keeper) GetDelegationPreferences(ctx sdk.Context, delegator string) (typ return types.ValidatorSetPreferences{}, types.ErrNoDelegation } - return types.ValidatorSetPreferences{Preferences: calculateSharesAndFormat(existingDelegations)}, nil + return types.ValidatorSetPreferences{Preferences: formatToValPrefArr(existingDelegations)}, nil } return valSet, nil @@ -65,8 +65,8 @@ func (k Keeper) GetDelegationPreferences(ctx sdk.Context, delegator string) (typ // 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 a validator set preference and existing delegations, or existing delegations -// but no validator set preference, it calculates the delegator's shares in each delegation +// -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) @@ -87,23 +87,26 @@ func (k Keeper) GetValSetPreferencesWithDelegations(ctx sdk.Context, delegator s return valSet, nil } - // this can either be valSet doesnot exist and existing delegations exist - // or valset exists and existing delegation exists - return types.ValidatorSetPreferences{Preferences: calculateSharesAndFormat(existingDelegations)}, nil + // 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 } -func calculateSharesAndFormat(existingDelegations []stakingtypes.Delegation) []types.ValidatorPreference { - existingTotalShares := sdk.NewDec(0) - for _, existingDelegation := range existingDelegations { - existingTotalShares = existingTotalShares.Add(existingDelegation.Shares) +// 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) } - existingDelsValSetFormatted := make([]types.ValidatorPreference, len(existingDelegations)) - for i, existingDelegation := range existingDelegations { - existingDelsValSetFormatted[i] = types.ValidatorPreference{ - ValOperAddress: existingDelegation.ValidatorAddress, - Weight: existingDelegation.Shares.Quo(existingTotalShares), + valPrefs := make([]types.ValidatorPreference, len(delegations)) + for i, delegation := range delegations { + valPrefs[i] = types.ValidatorPreference{ + ValOperAddress: delegation.ValidatorAddress, + Weight: delegation.Shares.Quo(totalShares), } } - return existingDelsValSetFormatted + return valPrefs } diff --git a/x/valset-pref/keeper_test.go b/x/valset-pref/keeper_test.go index d670afe4677..a1d79c6100e 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 e0b8cdb4206..cdeaa5418b6 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.DeriveValidatorSetPreference(ctx, msg.Delegator, msg.Preferences) + preferences, err := server.keeper.ValidateValidatorSetPreference(ctx, msg.Delegator, msg.Preferences) if err != nil { return nil, err } @@ -75,7 +75,7 @@ func (server msgServer) RedelegateValidatorSet(goCtx context.Context, msg *types } // Message 1: override the validator set preference set entry - newPreferences, err := server.keeper.DeriveValidatorSetPreference(ctx, msg.Delegator, msg.Preferences) + newPreferences, err := server.keeper.ValidateValidatorSetPreference(ctx, msg.Delegator, msg.Preferences) if err != nil { return nil, err } @@ -110,7 +110,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/types/errors.go b/x/valset-pref/types/errors.go index 0d2b988e047..0b64c639415 100644 --- a/x/valset-pref/types/errors.go +++ b/x/valset-pref/types/errors.go @@ -1,7 +1,29 @@ 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) +} diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index de16cf9141e..fed495f0049 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -52,11 +52,11 @@ func (k Keeper) GetValidatorSetPreference(ctx sdk.Context, delegator string) (ty return valsetPref, true } -// DeriveValidatorSetPreference derives given 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. // NOTE: this function does not add valset to the state -func (k Keeper) DeriveValidatorSetPreference(ctx sdk.Context, delegator string, preferences []types.ValidatorPreference) (types.ValidatorSetPreferences, error) { +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 @@ -125,20 +125,20 @@ 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 -// Rounding logic 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. +// 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. func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string, undelegation sdk.Coin) error { 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 := sdk.MustAccAddressFromBech32(delegatorAddr) - // Step 1-2, compute the total amount delegated and the amount to undelegate for each validator + // 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 { @@ -146,23 +146,23 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string } if undelegation.Amount.ToLegacyDec().GT(totalDelegatedAmt) { - return fmt.Errorf("Total tokenAmountToUndelegate more than delegated amount have %s got %s\n", totalDelegatedAmt, undelegation.Amount) + return types.UndelegateMoreThanDelegatedError{TotalDelegatedAmt: totalDelegatedAmt, UndelegationAmt: undelegation.Amount} } - // Step 3 + // 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) }) - // Step 4 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()) { - fmt.Println("All validators can undelegate normally, falling to happy path exit early") for index, val := range valSetRatio { validator := validators[val.ValAddr.String()] - // in the last valset iteration we dont calculate it from shares using decimals and trucation, + // 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() @@ -171,7 +171,6 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string amountToUnDelegate = val.UndelegateAmt totalUnDelAmt = totalUnDelAmt.Add(amountToUnDelegate) } - sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) if err != nil { return err @@ -182,7 +181,6 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string return err } } - return nil } @@ -195,7 +193,6 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string // Step 6 for len(valSetRatio) > 0 && valSetRatio[0].VRatio.GT(targetRatio) { - fmt.Printf("Undelegating fully from validator %s %s\n", valSetRatio[0].ValAddr.String(), valSetRatio[0].DelegatedAmt) _, err = k.stakingKeeper.Undelegate(ctx, delegator, valSetRatio[0].ValAddr, valSetRatio[0].DelegatedAmt.ToLegacyDec()) // this has to be shares amount if err != nil { return err @@ -206,10 +203,7 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string } // Step 7 - fmt.Println("Undelegating the remaining amount.") for _, val := range valSetRatio { - // TestUndelegateFromValSetErrorCase1 specifically checks this logic - fmt.Printf("Undelegate %s from validator %s\n", val.UndelegateAmt, val.ValAddr.String()) _, validator, err := k.getValAddrAndVal(ctx, val.ValAddr.String()) if err != nil { return err @@ -229,43 +223,46 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string 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 valSetRatio []ValRatio + 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 valSetRatio, validators, totalDelegatedAmt, err + return nil, map[string]stakingtypes.Validator{}, sdk.ZeroDec(), err } validators[valAddr.String()] = validator delegation, found := k.stakingKeeper.GetDelegation(ctx, delegator, valAddr) if !found { - return valSetRatio, validators, totalDelegatedAmt, fmt.Errorf("No delegation found for thie delegator %s to this validator %s\n", delegator, valAddr) + return nil, map[string]stakingtypes.Validator{}, sdk.ZeroDec(), fmt.Errorf("No delegation found for delegator %s to validator %s\n", delegator, valAddr) } - sharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) + undelegateSharesAmt, err := validator.SharesFromTokens(amountToUnDelegate) if err != nil { - return valSetRatio, validators, totalDelegatedAmt, err + return nil, map[string]stakingtypes.Validator{}, sdk.ZeroDec(), err } - valShares := sharesAmt.Quo(delegation.Shares) + // 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)) - - valSetRatio = append(valSetRatio, ValRatio{ + valSetRatios = append(valSetRatios, ValRatio{ ValAddr: valAddr, UndelegateAmt: amountToUnDelegate, - VRatio: valShares, + VRatio: vRatio, DelegatedAmt: delegation.Shares.TruncateInt(), Weight: val.Weight, }) } - return valSetRatio, validators, totalDelegatedAmt, nil + return valSetRatios, validators, totalDelegatedAmt, nil } // The redelegation command allows delegators to instantly switch validators. @@ -386,7 +383,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 7186ce2b5f8..8b5d2364629 100644 --- a/x/valset-pref/validator_set_test.go +++ b/x/valset-pref/validator_set_test.go @@ -1,8 +1,6 @@ package keeper_test import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" valPref "github.com/osmosis-labs/osmosis/v19/x/valset-pref" @@ -147,6 +145,245 @@ 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) 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) @@ -229,13 +466,13 @@ func (s *KeeperTestSuite) TestUndelegateFromValSetErrorCase() { 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 := []sdk.Dec{sdk.NewDec(15_000_000), sdk.NewDec(500_000)} + 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.DeriveValidatorSetPreference(s.Ctx, delegator.String(), valPreferences) + _, err := s.App.ValidatorSetPreferenceKeeper.ValidateValidatorSetPreference(s.Ctx, delegator.String(), valPreferences) s.Require().NoError(err) s.App.ValidatorSetPreferenceKeeper.SetValidatorSetPreferences(s.Ctx, delegator.String(), types.ValidatorSetPreferences{ @@ -256,8 +493,6 @@ func (s *KeeperTestSuite) TestUndelegateFromValSetErrorCase() { _, err = s.App.StakingKeeper.Delegate(s.Ctx, delegator, sdk.NewInt(10_000_000), stakingtypes.Unbonded, validator, true) s.Require().NoError(err) - fmt.Println("3 validators: ", valAddrs[0], valAddrs[1], valAddrs[2]) - err = s.App.ValidatorSetPreferenceKeeper.UndelegateFromValidatorSet(s.Ctx, delegator.String(), coinToUnStake) s.Require().NoError(err) From ce280e84f84d3ede6ccace8d9de6389a64c38151 Mon Sep 17 00:00:00 2001 From: Adam Tucker Date: Fri, 13 Oct 2023 12:46:51 -0600 Subject: [PATCH 27/28] feat: unbond with rebalanced val set weights (#6685) * initial push * add todo * msg server test * add godoc * custom error * update godoc * update proto and remove duplication * add more TODOs * use min when calculating amt to withdraw from last val --- proto/osmosis/valset-pref/v1beta1/tx.proto | 28 ++ x/valset-pref/client/cli/tx.go | 27 +- x/valset-pref/msg_server.go | 17 +- x/valset-pref/msg_server_test.go | 238 +++++++++- x/valset-pref/types/errors.go | 8 + x/valset-pref/types/msgs.go | 41 ++ x/valset-pref/types/tx.pb.go | 503 ++++++++++++++++++--- x/valset-pref/validator_set.go | 92 ++++ x/valset-pref/validator_set_test.go | 105 +++++ 9 files changed, 998 insertions(+), 61 deletions(-) diff --git a/proto/osmosis/valset-pref/v1beta1/tx.proto b/proto/osmosis/valset-pref/v1beta1/tx.proto index 126949e14ee..a5089a86d43 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/client/cli/tx.go b/x/valset-pref/client/cli/tx.go index dc44d395145..3d6bf130b82 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/msg_server.go b/x/valset-pref/msg_server.go index cdeaa5418b6..b6ac157a158 100644 --- a/x/valset-pref/msg_server.go +++ b/x/valset-pref/msg_server.go @@ -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. diff --git a/x/valset-pref/msg_server_test.go b/x/valset-pref/msg_server_test.go index 429c38feb7e..4bdd6592011 100644 --- a/x/valset-pref/msg_server_test.go +++ b/x/valset-pref/msg_server_test.go @@ -307,7 +307,241 @@ 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 @@ -507,7 +741,7 @@ func (s *KeeperTestSuite) TestUnDelegateFromValidatorSet() { s.Require().NoError(err) } - _, err := msgServer.UndelegateFromValidatorSet(c, types.NewMsgUndelegateFromValidatorSet(test.delegator, test.coinToUnStake)) + _, err := msgServer.UndelegateFromRebalancedValidatorSet(c, types.NewMsgUndelegateFromRebalancedValidatorSet(test.delegator, test.coinToUnStake)) if test.expectPass { s.Require().NoError(err) diff --git a/x/valset-pref/types/errors.go b/x/valset-pref/types/errors.go index 0b64c639415..941918bd4c2 100644 --- a/x/valset-pref/types/errors.go +++ b/x/valset-pref/types/errors.go @@ -27,3 +27,11 @@ type NoValidatorSetOrExistingDelegationsError struct { 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 961181c50ac..951e3ddd18e 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, 0x1b, 0x86, 0x18, 0x05, 0x63, 0xa2, 0x23, 0x31, 0x71, 0x31, 0x89, 0x16, 0xd4, 0xc4, 0x85, - 0x49, 0x67, 0x7a, 0x28, 0x0d, 0x6d, 0xef, 0xa4, 0xf7, 0xf2, 0x5a, 0xb8, 0x72, 0x63, 0x5c, 0x18, - 0x77, 0x26, 0x7e, 0x04, 0x57, 0x7e, 0x0c, 0x96, 0xec, 0x74, 0x05, 0x86, 0x49, 0x74, 0xe3, 0x8a, - 0x4f, 0x60, 0xfa, 0x98, 0x4b, 0x09, 0x73, 0x5b, 0x53, 0x1f, 0x9b, 0x99, 0xe9, 0x9c, 0xf3, 0x3b, - 0xe7, 0x77, 0x7f, 0xe7, 0xd1, 0x8b, 0xa7, 0x28, 0xf3, 0x29, 0x73, 0x19, 0xd9, 0xb1, 0x3c, 0x06, - 0x7c, 0xa1, 0x1d, 0xc2, 0x06, 0xd9, 0x59, 0x6c, 0x02, 0xb7, 0x16, 0x09, 0xdf, 0x33, 0xda, 0x21, - 0xe5, 0x54, 0x51, 0x53, 0x2f, 0x23, 0xf1, 0x8a, 0x9c, 0x8c, 0xd4, 0x49, 0x1d, 0x71, 0xa8, 0x43, - 0x63, 0x37, 0x12, 0xfd, 0x4a, 0x10, 0xea, 0x25, 0xcb, 0x77, 0x03, 0x4a, 0xe2, 0xcf, 0xf4, 0xaf, - 0xaa, 0x43, 0xa9, 0xe3, 0x01, 0x89, 0x9f, 0x9a, 0xdb, 0x1b, 0x84, 0xbb, 0x3e, 0x30, 0x6e, 0xf9, - 0xed, 0xd4, 0x41, 0x6b, 0xc5, 0x69, 0x48, 0xd3, 0x62, 0x20, 0x38, 0xb4, 0xa8, 0x1b, 0xa4, 0xf6, - 0xd9, 0x3c, 0xae, 0x8c, 0x5b, 0x1c, 0x12, 0x47, 0xfd, 0x07, 0xc2, 0x57, 0x1a, 0xcc, 0x59, 0x03, - 0xfe, 0xd4, 0xf2, 0x5c, 0xdb, 0xe2, 0x34, 0x5c, 0x03, 0xfe, 0x28, 0x84, 0x0d, 0x08, 0x21, 0x68, - 0x81, 0x52, 0xc3, 0x43, 0x36, 0x78, 0xe0, 0x44, 0x96, 0x31, 0x34, 0x81, 0xe6, 0x86, 0xea, 0x23, - 0xa7, 0x47, 0xd5, 0xff, 0xf7, 0x2d, 0xdf, 0x5b, 0xd1, 0x85, 0x49, 0x37, 0xcf, 0xdc, 0x14, 0x1f, - 0x0f, 0xb7, 0x45, 0x04, 0x36, 0xd6, 0x37, 0xd1, 0x3f, 0x37, 0x5c, 0x23, 0x86, 0x5c, 0x19, 0x43, - 0x24, 0x3f, 0xcb, 0x5c, 0x57, 0x0f, 0x8e, 0xaa, 0x95, 0xd3, 0xa3, 0xaa, 0x92, 0xa4, 0xca, 0x44, - 0xd4, 0xcd, 0x6c, 0xfc, 0x95, 0xeb, 0x6f, 0xbe, 0x7f, 0x9a, 0x17, 0xd5, 0xc9, 0x3b, 0x8d, 0x3e, - 0x83, 0xa7, 0xf2, 0xec, 0x26, 0xb0, 0x36, 0x0d, 0x18, 0xe8, 0x9f, 0x11, 0x1e, 0x6f, 0x30, 0x67, - 0x35, 0x39, 0x12, 0xac, 0xd3, 0xac, 0x7f, 0x29, 0x4d, 0x5e, 0xe0, 0x81, 0xa8, 0x3e, 0x63, 0x7d, - 0x13, 0x68, 0x6e, 0xb8, 0x36, 0x6e, 0x24, 0x05, 0x34, 0xa2, 0x02, 0x0a, 0x15, 0xee, 0x53, 0x37, - 0xa8, 0x93, 0xe8, 0xd8, 0x1f, 0x8f, 0xab, 0xb3, 0x8e, 0xcb, 0x37, 0xb7, 0x9b, 0x46, 0x8b, 0xfa, - 0x24, 0xad, 0x76, 0xf2, 0xb5, 0xc0, 0xec, 0x2d, 0xc2, 0xf7, 0xdb, 0xc0, 0x62, 0x80, 0x19, 0xc7, - 0x5d, 0x99, 0x89, 0x44, 0x98, 0xcc, 0x88, 0xd0, 0x9b, 0xbb, 0x7e, 0x0d, 0x4f, 0x4a, 0x8d, 0xe2, - 0xf8, 0xc7, 0x08, 0x5f, 0x6d, 0x30, 0xe7, 0x49, 0x90, 0xf2, 0x87, 0x07, 0x21, 0xf5, 0xff, 0x98, - 0x04, 0xfd, 0x7f, 0x49, 0x82, 0xf9, 0x48, 0x82, 0xe9, 0x8c, 0x04, 0x72, 0xfe, 0xfa, 0x2c, 0x9e, - 0xce, 0x75, 0x10, 0x52, 0x7c, 0x4b, 0x3a, 0xc1, 0x84, 0xae, 0xe7, 0x6f, 0xcb, 0xf0, 0x8f, 0xa7, - 0xe3, 0x42, 0x63, 0xf4, 0x3e, 0x4a, 0xda, 0x18, 0xbd, 0x8d, 0x42, 0x8d, 0x97, 0xf1, 0xb6, 0x78, - 0xe6, 0xf2, 0x4d, 0x3b, 0xb4, 0x76, 0xd3, 0x2e, 0x72, 0x69, 0x60, 0xc2, 0xae, 0x15, 0xda, 0xac, - 0x8c, 0x1e, 0x17, 0xc7, 0x57, 0x1a, 0x3e, 0x1d, 0x5f, 0xa9, 0x5d, 0xd0, 0x04, 0x7c, 0x39, 0xd3, - 0xe4, 0x75, 0x1a, 0xd8, 0x60, 0xaf, 0xd3, 0x2d, 0x08, 0x4a, 0x31, 0x54, 0x46, 0xf1, 0xa0, 0x47, - 0x5b, 0x5b, 0x0f, 0x57, 0xe3, 0xe9, 0x1d, 0x30, 0xd3, 0x27, 0x7d, 0x12, 0x57, 0x25, 0x69, 0xba, - 0x4c, 0x6a, 0xaf, 0xfe, 0xc3, 0xfd, 0x0d, 0xe6, 0x28, 0xef, 0x11, 0x1e, 0x97, 0x2f, 0xd9, 0x5b, - 0x79, 0xd5, 0xcf, 0x5b, 0x58, 0xea, 0xdd, 0xb2, 0xc8, 0x2e, 0x43, 0xe5, 0x2d, 0xc2, 0xa3, 0x92, - 0x3d, 0x77, 0xa3, 0x20, 0x78, 0x6f, 0x98, 0x7a, 0xa7, 0x14, 0x4c, 0x10, 0xfa, 0x80, 0xb0, 0x9a, - 0xb3, 0x79, 0x96, 0x0b, 0xa2, 0xcb, 0xa1, 0xea, 0xbd, 0xd2, 0xd0, 0x73, 0x6a, 0x49, 0x76, 0x41, - 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, 0x07, 0x27, 0x1a, 0x3a, 0x3c, - 0xd1, 0xd0, 0xd7, 0x13, 0x0d, 0xbd, 0xeb, 0x68, 0x95, 0xc3, 0x8e, 0x56, 0xf9, 0xd2, 0xd1, 0x2a, - 0xcf, 0x6f, 0x66, 0x5e, 0x31, 0x69, 0x82, 0x05, 0xcf, 0x6a, 0x32, 0x22, 0x2e, 0x50, 0x8b, 0xcb, - 0x64, 0xef, 0xdc, 0x35, 0x2a, 0x7e, 0xef, 0x34, 0x07, 0xe3, 0xfb, 0xd3, 0xd2, 0xcf, 0x00, 0x00, - 0x00, 0xff, 0xff, 0x5a, 0xd2, 0x4c, 0x56, 0x16, 0x0a, 0x00, 0x00, + // 749 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x56, 0x4d, 0x4f, 0xd4, 0x40, + 0x18, 0xde, 0x01, 0x42, 0x64, 0xb8, 0x68, 0x43, 0x10, 0x1a, 0xdd, 0x85, 0x0a, 0x2c, 0x92, 0xd0, + 0xc9, 0x2e, 0x1a, 0x05, 0x63, 0xa2, 0x0b, 0x31, 0x31, 0x66, 0x13, 0x2d, 0xa8, 0x89, 0x07, 0x93, + 0xe9, 0x76, 0x28, 0x0d, 0x6d, 0x67, 0xd3, 0x19, 0xbe, 0x0e, 0xde, 0x8d, 0x07, 0xe3, 0xcd, 0xc4, + 0x9f, 0xe0, 0xc9, 0xa3, 0x27, 0xcf, 0x1c, 0xb9, 0xe9, 0x09, 0x0c, 0x24, 0x7a, 0xf1, 0x84, 0x7f, + 0xc0, 0xf4, 0x63, 0x87, 0x12, 0xfa, 0x81, 0x15, 0x8d, 0x97, 0xdd, 0xed, 0xbe, 0x5f, 0xcf, 0xfb, + 0xbc, 0xf3, 0x3e, 0x53, 0x38, 0x46, 0x99, 0x43, 0x99, 0xc5, 0xd0, 0x3a, 0xb6, 0x19, 0xe1, 0xd3, + 0x6d, 0x8f, 0x2c, 0xa3, 0xf5, 0x9a, 0x4e, 0x38, 0xae, 0x21, 0xbe, 0xa9, 0xb6, 0x3d, 0xca, 0xa9, + 0x24, 0x47, 0x5e, 0x6a, 0xe8, 0xe5, 0x3b, 0xa9, 0x91, 0x93, 0x3c, 0x60, 0x52, 0x93, 0x06, 0x6e, + 0xc8, 0xff, 0x15, 0x46, 0xc8, 0x17, 0xb0, 0x63, 0xb9, 0x14, 0x05, 0x9f, 0xd1, 0x5f, 0x15, 0x93, + 0x52, 0xd3, 0x26, 0x28, 0x78, 0xd2, 0xd7, 0x96, 0x11, 0xb7, 0x1c, 0xc2, 0x38, 0x76, 0xda, 0x91, + 0x43, 0xb9, 0x15, 0x94, 0x41, 0x3a, 0x66, 0x44, 0x60, 0x68, 0x51, 0xcb, 0x8d, 0xec, 0xd5, 0x2c, + 0xac, 0x8c, 0x63, 0x4e, 0x42, 0x47, 0xe5, 0x07, 0x80, 0x97, 0x9a, 0xcc, 0x5c, 0x24, 0xfc, 0x09, + 0xb6, 0x2d, 0x03, 0x73, 0xea, 0x2d, 0x12, 0xfe, 0xd0, 0x23, 0xcb, 0xc4, 0x23, 0x6e, 0x8b, 0x48, + 0x75, 0xd8, 0x67, 0x10, 0x9b, 0x98, 0xbe, 0x65, 0x08, 0x8c, 0x80, 0xc9, 0xbe, 0xc6, 0xc0, 0xe1, + 0x6e, 0xe5, 0xfc, 0x16, 0x76, 0xec, 0x39, 0x45, 0x98, 0x14, 0xed, 0xc8, 0x4d, 0x72, 0x60, 0x7f, + 0x5b, 0x64, 0x60, 0x43, 0x5d, 0x23, 0xdd, 0x93, 0xfd, 0x75, 0xa4, 0xa6, 0x33, 0xa3, 0x8a, 0xe2, + 0x47, 0x95, 0x1b, 0xf2, 0xf6, 0x6e, 0xa5, 0x74, 0xb8, 0x5b, 0x91, 0xc2, 0x52, 0xb1, 0x8c, 0x8a, + 0x16, 0xcf, 0x3f, 0x77, 0xf5, 0xd5, 0xf7, 0x0f, 0x53, 0x62, 0x3a, 0x59, 0xdd, 0x28, 0x13, 0x70, + 0x2c, 0xcb, 0xae, 0x11, 0xd6, 0xa6, 0x2e, 0x23, 0xca, 0x67, 0x00, 0x87, 0x9b, 0xcc, 0x5c, 0x08, + 0x5b, 0x22, 0x4b, 0x34, 0xee, 0x5f, 0x88, 0x93, 0xe7, 0xb0, 0xc7, 0x9f, 0xcf, 0x50, 0xd7, 0x08, + 0x98, 0xec, 0xaf, 0x0f, 0xab, 0xe1, 0x00, 0x55, 0x7f, 0x80, 0x82, 0x85, 0x79, 0x6a, 0xb9, 0x0d, + 0xe4, 0xb7, 0xfd, 0x7e, 0xaf, 0x52, 0x35, 0x2d, 0xbe, 0xb2, 0xa6, 0xab, 0x2d, 0xea, 0xa0, 0x68, + 0xda, 0xe1, 0xd7, 0x34, 0x33, 0x56, 0x11, 0xdf, 0x6a, 0x13, 0x16, 0x04, 0x68, 0x41, 0xde, 0xb9, + 0x09, 0x9f, 0x84, 0xd1, 0x18, 0x09, 0xc9, 0xd8, 0x95, 0x2b, 0x70, 0x34, 0xd5, 0x28, 0xda, 0xdf, + 0x03, 0xf0, 0x72, 0x93, 0x99, 0x8f, 0xdd, 0x08, 0x3f, 0xb9, 0xe7, 0x51, 0xe7, 0xcc, 0x28, 0xe8, + 0xfe, 0x4b, 0x14, 0x4c, 0xf9, 0x14, 0x8c, 0xc7, 0x28, 0x48, 0xc7, 0xaf, 0x54, 0xe1, 0x78, 0xa6, + 0x83, 0xa0, 0xe2, 0x27, 0x80, 0xd5, 0x13, 0x9e, 0x1a, 0xd1, 0xb1, 0x8d, 0xdd, 0x16, 0x31, 0xfe, + 0xfb, 0x73, 0x71, 0xcd, 0x27, 0x05, 0xa5, 0x92, 0x92, 0xdc, 0x89, 0x52, 0x83, 0xa7, 0x75, 0x15, + 0x44, 0x7d, 0x0b, 0x57, 0x46, 0x23, 0x9d, 0x98, 0x3f, 0xa6, 0xe6, 0x1f, 0xcb, 0xc8, 0x89, 0x0d, + 0x4a, 0x6e, 0x25, 0xda, 0xa0, 0x64, 0xa3, 0x60, 0xe3, 0x45, 0x20, 0xab, 0x4f, 0x2d, 0xbe, 0x62, + 0x78, 0x78, 0x23, 0x5a, 0x37, 0x8b, 0xba, 0x1a, 0xd9, 0xc0, 0x9e, 0xc1, 0x8a, 0xf0, 0x71, 0x52, + 0xe7, 0x52, 0xd3, 0x47, 0x3a, 0x97, 0x6a, 0x17, 0x30, 0x09, 0xbc, 0x18, 0x53, 0x83, 0x06, 0x75, + 0x0d, 0x62, 0x2c, 0xd1, 0x55, 0xe2, 0x16, 0x42, 0x28, 0x0d, 0xc2, 0x5e, 0x9b, 0xb6, 0x56, 0xef, + 0x2f, 0x04, 0xc7, 0xb9, 0x47, 0x8b, 0x9e, 0x94, 0x51, 0x58, 0x49, 0x29, 0xd3, 0x41, 0x52, 0xff, + 0x74, 0x0e, 0x76, 0x37, 0x99, 0x29, 0xbd, 0x05, 0x70, 0x38, 0xfd, 0x36, 0xba, 0x99, 0x35, 0xfd, + 0x2c, 0x65, 0x97, 0xef, 0x14, 0x8d, 0xec, 0x20, 0x94, 0x5e, 0x03, 0x38, 0x98, 0x72, 0x21, 0x5c, + 0xcf, 0x49, 0x9e, 0x1c, 0x26, 0xdf, 0x2e, 0x14, 0x26, 0x00, 0xbd, 0x03, 0x50, 0xce, 0x90, 0xe8, + 0xd9, 0x9c, 0xec, 0xe9, 0xa1, 0xf2, 0xdd, 0xc2, 0xa1, 0x02, 0xdc, 0x47, 0x00, 0xc7, 0x4e, 0x25, + 0x9a, 0xf3, 0xbf, 0x55, 0x2b, 0x39, 0x89, 0xfc, 0xe0, 0x0c, 0x92, 0x1c, 0x1b, 0x74, 0x8a, 0x8c, + 0xe5, 0x0d, 0x3a, 0x39, 0x2c, 0x77, 0xd0, 0xd9, 0x62, 0x12, 0xec, 0x44, 0xba, 0x94, 0xe4, 0xed, + 0x44, 0x6a, 0x64, 0xee, 0x4e, 0xe4, 0xea, 0x87, 0xf4, 0x12, 0xc0, 0x81, 0x44, 0xf5, 0x98, 0x39, + 0xe5, 0xd1, 0x8e, 0x07, 0xc9, 0xb7, 0x0a, 0x04, 0x75, 0xa0, 0x34, 0x1e, 0x6d, 0xef, 0x97, 0xc1, + 0xce, 0x7e, 0x19, 0x7c, 0xdd, 0x2f, 0x83, 0x37, 0x07, 0xe5, 0xd2, 0xce, 0x41, 0xb9, 0xf4, 0xe5, + 0xa0, 0x5c, 0x7a, 0x76, 0x23, 0x76, 0x63, 0x46, 0x05, 0xa6, 0x6d, 0xac, 0x33, 0x71, 0x2b, 0xae, + 0xd7, 0x66, 0xd1, 0xe6, 0xb1, 0x57, 0xe5, 0xe0, 0x1a, 0xd5, 0x7b, 0x83, 0x77, 0xe4, 0x99, 0x5f, + 0x01, 0x00, 0x00, 0xff, 0xff, 0x3c, 0x79, 0x63, 0x35, 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 fed495f0049..6002f672e7c 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -130,7 +130,10 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co // our undelegate logic would attempt to undelegate 3osmo from A, 1.8osmo from B, 1.2osmo from C // 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: 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 types.NoValidatorSetOrExistingDelegationsError{DelegatorAddr: delegatorAddr} @@ -223,6 +226,95 @@ func (k Keeper) UndelegateFromValidatorSet(ctx sdk.Context, delegatorAddr string return nil } +// 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} + } + + 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 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, diff --git a/x/valset-pref/validator_set_test.go b/x/valset-pref/validator_set_test.go index 8b5d2364629..9dd5735ab35 100644 --- a/x/valset-pref/validator_set_test.go +++ b/x/valset-pref/validator_set_test.go @@ -232,6 +232,111 @@ func (s *KeeperTestSuite) TestUndelegateFromValidatorSet() { } } +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 { From 246d95eb16b6717e08db6fbae7a11cec2f030f55 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sat, 14 Oct 2023 00:38:16 +0530 Subject: [PATCH 28/28] Update x/valset-pref/validator_set.go --- x/valset-pref/validator_set.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x/valset-pref/validator_set.go b/x/valset-pref/validator_set.go index 8be2cb6a336..6cbde97ff48 100644 --- a/x/valset-pref/validator_set.go +++ b/x/valset-pref/validator_set.go @@ -130,7 +130,8 @@ func (k Keeper) DelegateToValidatorSet(ctx sdk.Context, delegatorAddr string, co // our undelegate logic would attempt to undelegate 3osmo from A, 1.8osmo from B, 1.2osmo from C // 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: Properly implement for vratio > 1 to hit steps 5-7, then re-enable +// 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