Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(staking): use validator & address codecs in staking #16958

Merged
merged 20 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions x/distribution/keeper/delegation.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,14 @@ func (k Keeper) calculateDelegationRewardsBetween(ctx context.Context, val staki

// calculate the total rewards accrued by a delegation
func (k Keeper) CalculateDelegationRewards(ctx context.Context, val stakingtypes.ValidatorI, del stakingtypes.DelegationI, endingPeriod uint64) (rewards sdk.DecCoins, err error) {
addrCodec := k.authKeeper.AddressCodec()
delAddr, err := addrCodec.StringToBytes(del.GetDelegatorAddr())
if err != nil {
return sdk.DecCoins{}, err
}

// fetch starting info for delegation
startingInfo, err := k.DelegatorStartingInfo.Get(ctx, collections.Join(del.GetValidatorAddr(), del.GetDelegatorAddr()))
startingInfo, err := k.DelegatorStartingInfo.Get(ctx, collections.Join(del.GetValidatorAddr(), sdk.AccAddress(delAddr)))
if err != nil && !errors.Is(err, collections.ErrNotFound) {
return sdk.DecCoins{}, err
}
Expand Down Expand Up @@ -178,8 +184,13 @@ func (k Keeper) CalculateDelegationRewards(ctx context.Context, val stakingtypes
}

func (k Keeper) withdrawDelegationRewards(ctx context.Context, val stakingtypes.ValidatorI, del stakingtypes.DelegationI) (sdk.Coins, error) {
addrCodec := k.authKeeper.AddressCodec()
delAddr, err := addrCodec.StringToBytes(del.GetDelegatorAddr())
if err != nil {
return nil, err
}
// check existence of delegator starting info
hasInfo, err := k.DelegatorStartingInfo.Has(ctx, collections.Join(del.GetValidatorAddr(), del.GetDelegatorAddr()))
hasInfo, err := k.DelegatorStartingInfo.Has(ctx, collections.Join(del.GetValidatorAddr(), sdk.AccAddress(delAddr)))
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -211,7 +222,7 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val stakingtypes.
logger := k.Logger(ctx)
logger.Info(
"rounding error withdrawing rewards from validator",
"delegator", del.GetDelegatorAddr().String(),
"delegator", del.GetDelegatorAddr(),
"validator", val.GetOperator().String(),
"got", rewards.String(),
"expected", rewardsRaw.String(),
Expand All @@ -223,7 +234,7 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val stakingtypes.

// add coins to user account
if !finalRewards.IsZero() {
withdrawAddr, err := k.GetDelegatorWithdrawAddr(ctx, del.GetDelegatorAddr())
withdrawAddr, err := k.GetDelegatorWithdrawAddr(ctx, delAddr)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -253,7 +264,7 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val stakingtypes.
}

// decrement reference count of starting period
startingInfo, err := k.DelegatorStartingInfo.Get(ctx, collections.Join(del.GetValidatorAddr(), del.GetDelegatorAddr()))
startingInfo, err := k.DelegatorStartingInfo.Get(ctx, collections.Join(del.GetValidatorAddr(), sdk.AccAddress(delAddr)))
if err != nil && !errors.Is(err, collections.ErrNotFound) {
return nil, err
}
Expand All @@ -265,7 +276,7 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val stakingtypes.
}

// remove delegator starting info
err = k.DelegatorStartingInfo.Remove(ctx, collections.Join(del.GetValidatorAddr(), del.GetDelegatorAddr()))
err = k.DelegatorStartingInfo.Remove(ctx, collections.Join(del.GetValidatorAddr(), sdk.AccAddress(delAddr)))
if err != nil {
return nil, err
}
Expand All @@ -287,7 +298,7 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val stakingtypes.
types.EventTypeWithdrawRewards,
sdk.NewAttribute(sdk.AttributeKeyAmount, finalRewards.String()),
sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator().String()),
sdk.NewAttribute(types.AttributeKeyDelegator, del.GetDelegatorAddr().String()),
sdk.NewAttribute(types.AttributeKeyDelegator, del.GetDelegatorAddr()),
),
)

Expand Down
10 changes: 7 additions & 3 deletions x/distribution/keeper/invariants.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,19 @@ func CanWithdrawInvariant(k Keeper) sdk.Invariant {

var remaining sdk.DecCoins

valDelegationAddrs := make(map[string][]sdk.AccAddress)
valDelegationAddrs := make(map[string][][]byte)
allDelegations, err := k.stakingKeeper.GetAllSDKDelegations(ctx)
if err != nil {
panic(err)
}

for _, del := range allDelegations {
valAddr := del.GetValidatorAddr().String()
valDelegationAddrs[valAddr] = append(valDelegationAddrs[valAddr], del.GetDelegatorAddr())
delAddr, err := k.authKeeper.AddressCodec().StringToBytes(del.GetDelegatorAddr())
if err != nil {
panic(err)
}
valAddr := del.GetValidatorAddr()
valDelegationAddrs[valAddr] = append(valDelegationAddrs[valAddr], delAddr)
}

// iterate over all validators
Expand Down
4 changes: 2 additions & 2 deletions x/distribution/types/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ func (res QueryDelegatorTotalRewardsResponse) String() string {
}

// NewDelegationDelegatorReward constructs a DelegationDelegatorReward.
func NewDelegationDelegatorReward(valAddr sdk.ValAddress, reward sdk.DecCoins) DelegationDelegatorReward {
return DelegationDelegatorReward{ValidatorAddress: valAddr.String(), Reward: reward}
func NewDelegationDelegatorReward(valAddr string, reward sdk.DecCoins) DelegationDelegatorReward {
return DelegationDelegatorReward{ValidatorAddress: valAddr, Reward: reward}
}
2 changes: 1 addition & 1 deletion x/gov/keeper/tally.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (keeper Keeper) Tally(ctx context.Context, proposal v1.Proposal) (passes, b

// iterate over all delegations from voter, deduct from any delegated-to validators
err = keeper.sk.IterateDelegations(ctx, voter, func(index int64, delegation stakingtypes.DelegationI) (stop bool) {
valAddrStr := delegation.GetValidatorAddr().String()
valAddrStr := delegation.GetValidatorAddr()

if val, ok := currValidators[valAddrStr]; ok {
// There is no need to handle the special case that validator address equal to voter address.
Expand Down
35 changes: 28 additions & 7 deletions x/staking/keeper/delegation.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,15 +129,20 @@ func (k Keeper) SetDelegation(ctx context.Context, delegation types.Delegation)
return err
}

valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())
if err != nil {
return err
}

store := k.storeService.OpenKVStore(ctx)
b := types.MustMarshalDelegation(k.cdc, delegation)
err = store.Set(types.GetDelegationKey(delegatorAddress, delegation.GetValidatorAddr()), b)
err = store.Set(types.GetDelegationKey(delegatorAddress, valAddr), b)
if err != nil {
return err
}

// set the delegation in validator delegator index
return store.Set(types.GetDelegationsByValKey(delegation.GetValidatorAddr(), delegatorAddress), []byte{})
return store.Set(types.GetDelegationsByValKey(valAddr, delegatorAddress), []byte{})
}

// RemoveDelegation removes a delegation
Expand All @@ -147,18 +152,23 @@ func (k Keeper) RemoveDelegation(ctx context.Context, delegation types.Delegatio
return err
}

valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())
if err != nil {
return err
}

// TODO: Consider calling hooks outside of the store wrapper functions, it's unobvious.
if err := k.Hooks().BeforeDelegationRemoved(ctx, delegatorAddress, delegation.GetValidatorAddr()); err != nil {
if err := k.Hooks().BeforeDelegationRemoved(ctx, delegatorAddress, valAddr); err != nil {
return err
}

store := k.storeService.OpenKVStore(ctx)
err = store.Delete(types.GetDelegationKey(delegatorAddress, delegation.GetValidatorAddr()))
err = store.Delete(types.GetDelegationKey(delegatorAddress, valAddr))
if err != nil {
return err
}

return store.Delete(types.GetDelegationsByValKey(delegation.GetValidatorAddr(), delegatorAddress))
return store.Delete(types.GetDelegationsByValKey(valAddr, delegatorAddress))
}

// GetUnbondingDelegations returns a given amount of all the delegator unbonding-delegations.
Expand Down Expand Up @@ -946,8 +956,13 @@ func (k Keeper) Delegate(
return newShares, err
}

valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())
if err != nil {
return math.LegacyDec{}, err
}

// Call the after-modification hook
if err := k.Hooks().AfterDelegationModified(ctx, delegatorAddress, delegation.GetValidatorAddr()); err != nil {
if err := k.Hooks().AfterDelegationModified(ctx, delegatorAddress, valAddr); err != nil {
return newShares, err
}

Expand Down Expand Up @@ -1009,8 +1024,14 @@ func (k Keeper) Unbond(
if err = k.SetDelegation(ctx, delegation); err != nil {
return amount, err
}

valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())
if err != nil {
return amount, err
}

// call the after delegation modification hook
err = k.Hooks().AfterDelegationModified(ctx, delegatorAddress, delegation.GetValidatorAddr())
err = k.Hooks().AfterDelegationModified(ctx, delegatorAddress, valAddr)
Fixed Show fixed Hide fixed
}

if err != nil {
Expand Down
9 changes: 7 additions & 2 deletions x/staking/keeper/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,14 @@ func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) (res
panic(fmt.Errorf("invalid delegator address: %s", err))
}

valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())
if err != nil {
panic(err)
}

// Call the before-creation hook if not exported
if !data.Exported {
if err := k.Hooks().BeforeDelegationCreated(ctx, delegatorAddress, delegation.GetValidatorAddr()); err != nil {
if err := k.Hooks().BeforeDelegationCreated(ctx, delegatorAddress, valAddr); err != nil {
panic(err)
}
}
Expand All @@ -97,7 +102,7 @@ func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) (res

// Call the after-modification hook if not exported
if !data.Exported {
if err := k.Hooks().AfterDelegationModified(ctx, delegatorAddress, delegation.GetValidatorAddr()); err != nil {
if err := k.Hooks().AfterDelegationModified(ctx, delegatorAddress, valAddr); err != nil {
panic(err)
}
}
Expand Down
21 changes: 16 additions & 5 deletions x/staking/keeper/grpc_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,13 @@ func (k Querier) getValidatorDelegationsLegacy(ctx context.Context, req *types.Q

valStore := prefix.NewStore(store, types.DelegationKey)
return query.GenericFilteredPaginate(k.cdc, valStore, req.Pagination, func(key []byte, delegation *types.Delegation) (*types.Delegation, error) {
valAddr, err := sdk.ValAddressFromBech32(req.ValidatorAddr)

_, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)
if err != nil {
return nil, err
}

if !delegation.GetValidatorAddr().Equals(valAddr) {
if !strings.EqualFold(delegation.GetValidatorAddr(), req.ValidatorAddr) {
return nil, nil
}

Expand Down Expand Up @@ -452,7 +453,12 @@ func (k Querier) DelegatorValidators(ctx context.Context, req *types.QueryDelega
return err
}

validator, err := k.GetValidator(ctx, delegation.GetValidatorAddr())
valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())
if err != nil {
return err
}

validator, err := k.GetValidator(ctx, valAddr)
if err != nil {
return err
}
Expand Down Expand Up @@ -565,7 +571,12 @@ func queryAllRedelegations(store storetypes.KVStore, k Querier, req *types.Query
// util

func delegationToDelegationResponse(ctx context.Context, k *Keeper, del types.Delegation) (types.DelegationResponse, error) {
val, err := k.GetValidator(ctx, del.GetValidatorAddr())
valAddr, err := k.validatorAddressCodec.StringToBytes(del.GetValidatorAddr())
if err != nil {
return types.DelegationResponse{}, err
}

val, err := k.GetValidator(ctx, valAddr)
if err != nil {
return types.DelegationResponse{}, err
}
Expand All @@ -582,7 +593,7 @@ func delegationToDelegationResponse(ctx context.Context, k *Keeper, del types.De

return types.NewDelegationResp(
delegatorAddress,
del.GetValidatorAddr(),
valAddr,
del.Shares,
sdk.NewCoin(bondDenom, val.TokensFromShares(del.Shares).TruncateInt()),
), nil
Expand Down
2 changes: 1 addition & 1 deletion x/staking/keeper/invariants.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ func DelegatorSharesInvariant(k *Keeper) sdk.Invariant {
}

for _, delegation := range delegations {
delegationValidatorAddr := delegation.GetValidatorAddr().String()
delegationValidatorAddr := delegation.GetValidatorAddr()
validatorDelegationShares := validatorsDelegationShares[delegationValidatorAddr]
validatorsDelegationShares[delegationValidatorAddr] = validatorDelegationShares.Add(delegation.Shares)
}
Expand Down
14 changes: 12 additions & 2 deletions x/staking/keeper/query_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ func (k Keeper) GetDelegatorValidators(
for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() {
delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value())

validator, err := k.GetValidator(ctx, delegation.GetValidatorAddr())
valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())
if err != nil {
return nil, err
}

validator, err := k.GetValidator(ctx, valAddr)
if err != nil {
return nil, err
}
Expand All @@ -48,7 +53,12 @@ func (k Keeper) GetDelegatorValidator(
return validator, err
}

return k.GetValidator(ctx, delegation.GetValidatorAddr())
valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr())
if err != nil {
return validator, err
}

return k.GetValidator(ctx, valAddr)
}

// GetAllDelegatorDelegations returns all delegations of a delegator
Expand Down
Loading