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 18 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
* (x/staking) [#16795](https://github.com/cosmos/cosmos-sdk/pull/16795) `DelegationToDelegationResponse`, `DelegationsToDelegationResponses`, `RedelegationsToRedelegationResponses` are no longer exported.
* [#16441](https://github.com/cosmos/cosmos-sdk/pull/16441) Params state is migrated to collections. `GetParams` has been removed
* [#16918](https://github.com/cosmos/cosmos-sdk/pull/16918) Remove `IntProto` and `DecProto`. Instead, `math.Int` and `math.LegacyDec` should be used respectively. Both types support `Marshal` and `Unmarshal` which should be used for binary marshaling.
* (x/staking) [#16958](https://github.com/cosmos/cosmos-sdk/pull/16958) DelegationI interface `GetDelegatorAddr` & `GetValidatorAddr` have been migrated to return string instead of sdk.AccAddress and sdk.ValAddress respectively. stakingtypes.NewDelegation takes a string instead of sdk.AccAddress and sdk.ValAddress.

## CLI Breaking Changes

Expand Down
4 changes: 2 additions & 2 deletions proto/cosmos/staking/v1beta1/staking.proto
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ message UnbondingDelegation {
string validator_address = 2 [(cosmos_proto.scalar) = "cosmos.ValidatorAddressString"];
tac0turtle marked this conversation as resolved.
Show resolved Hide resolved
// entries are the unbonding delegation entries.
repeated UnbondingDelegationEntry entries = 3
[(gogoproto.nullable) = false, (amino.dont_omitempty) = true]; // unbonding delegation entries
[(gogoproto.nullable) = false, (amino.dont_omitempty) = true]; // unbonding delegation entries
}

// UnbondingDelegationEntry defines an unbonding object with relevant metadata.
Expand Down Expand Up @@ -293,7 +293,7 @@ message Redelegation {
string validator_dst_address = 3 [(cosmos_proto.scalar) = "cosmos.ValidatorAddressString"];
// entries are the redelegation entries.
repeated RedelegationEntry entries = 4
[(gogoproto.nullable) = false, (amino.dont_omitempty) = true]; // redelegation entries
[(gogoproto.nullable) = false, (amino.dont_omitempty) = true]; // redelegation entries
}

// Params defines the parameters for the x/staking module.
Expand Down
2 changes: 1 addition & 1 deletion tests/e2e/distribution/grpc_query_suite.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ func (s *GRPCQueryTestSuite) TestQueryDelegatorRewardsGRPC() {
&types.QueryDelegationTotalRewardsResponse{},
&types.QueryDelegationTotalRewardsResponse{
Rewards: []types.DelegationDelegatorReward{
types.NewDelegationDelegatorReward(val.ValAddress, rewards),
types.NewDelegationDelegatorReward(val.ValAddress.String(), rewards),
},
Total: rewards,
},
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/distribution/keeper/grpc_query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ func TestGRPCDelegationRewards(t *testing.T) {
// setup delegation
delTokens := sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction)
validator, issuedShares := val.AddTokensFromDel(delTokens)
delegation := stakingtypes.NewDelegation(delAddr, f.valAddr, issuedShares)
delegation := stakingtypes.NewDelegation(delAddr.String(), f.valAddr.String(), issuedShares)
assert.NilError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, delegation))
assert.NilError(t, f.distrKeeper.DelegatorStartingInfo.Set(f.sdkCtx, collections.Join(validator.GetOperator(), delAddr), types.NewDelegatorStartingInfo(2, math.LegacyNewDec(initialStake), 20)))

Expand Down
2 changes: 1 addition & 1 deletion tests/integration/distribution/keeper/msg_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ func TestMsgWithdrawDelegatorReward(t *testing.T) {
// setup delegation
delTokens := sdk.TokensFromConsensusPower(2, sdk.DefaultPowerReduction)
validator, issuedShares := validator.AddTokensFromDel(delTokens)
delegation := stakingtypes.NewDelegation(delAddr, validator.GetOperator(), issuedShares)
delegation := stakingtypes.NewDelegation(delAddr.String(), validator.GetOperator().String(), issuedShares)
require.NoError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, delegation))
require.NoError(t, f.distrKeeper.DelegatorStartingInfo.Set(f.sdkCtx, collections.Join(validator.GetOperator(), delAddr), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 20)))
// setup validator rewards
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/staking/keeper/delegation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) {
assert.Assert(math.IntEq(t, startTokens, validator.BondedTokens()))
assert.Assert(t, validator.IsBonded())

delegation := types.NewDelegation(addrDel, addrVal, issuedShares)
delegation := types.NewDelegation(addrDel.String(), addrVal.String(), issuedShares)
assert.NilError(t, f.stakingKeeper.SetDelegation(ctx, delegation))

maxEntries, err := f.stakingKeeper.MaxEntries(ctx)
Expand Down
6 changes: 3 additions & 3 deletions tests/integration/staking/keeper/slash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func TestSlashRedelegation(t *testing.T) {
assert.NilError(t, f.stakingKeeper.SetRedelegation(f.sdkCtx, rd))

// set the associated delegation
del := types.NewDelegation(addrDels[0], addrVals[1], math.LegacyNewDec(10))
del := types.NewDelegation(addrDels[0].String(), addrVals[1].String(), math.LegacyNewDec(10))
assert.NilError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, del))

// started redelegating prior to the current height, stake didn't contribute to infraction
Expand Down Expand Up @@ -393,7 +393,7 @@ func TestSlashWithRedelegation(t *testing.T) {
assert.NilError(t, f.stakingKeeper.SetRedelegation(f.sdkCtx, rd))

// set the associated delegation
del := types.NewDelegation(addrDels[0], addrVals[1], math.LegacyNewDecFromInt(rdTokens))
del := types.NewDelegation(addrDels[0].String(), addrVals[1].String(), math.LegacyNewDecFromInt(rdTokens))
assert.NilError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, del))

// update bonded tokens
Expand Down Expand Up @@ -551,7 +551,7 @@ func TestSlashBoth(t *testing.T) {
assert.NilError(t, f.stakingKeeper.SetRedelegation(f.sdkCtx, rdA))

// set the associated delegation
delA := types.NewDelegation(addrDels[0], addrVals[1], math.LegacyNewDecFromInt(rdATokens))
delA := types.NewDelegation(addrDels[0].String(), addrVals[1].String(), math.LegacyNewDecFromInt(rdATokens))
assert.NilError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, delA))

// set an unbonding delegation with expiration timestamp (beyond which the
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/staking/keeper/unbonding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func SetupUnbondingTests(t *testing.T, f *fixture, hookCalled *bool, ubdeID *uin
assert.Assert(t, validator1.IsBonded())

// Create a delegator
delegation := types.NewDelegation(addrDels[0], addrVals[0], issuedShares1)
delegation := types.NewDelegation(addrDels[0].String(), addrVals[0].String(), issuedShares1)
assert.NilError(t, f.stakingKeeper.SetDelegation(f.sdkCtx, delegation))

// Create a validator to redelegate to
Expand Down
12 changes: 9 additions & 3 deletions tests/integration/staking/keeper/validator_bench_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package keeper_test

import (
"bytes"
"fmt"
"testing"

Expand Down Expand Up @@ -66,7 +67,7 @@ func BenchmarkGetValidatorDelegations(b *testing.B) {
if err != nil {
panic(err)
}
NewDel := types.NewDelegation(delegator, val, math.LegacyNewDec(int64(i)))
NewDel := types.NewDelegation(delegator.String(), val.String(), math.LegacyNewDec(int64(i)))

if err := f.stakingKeeper.SetDelegation(f.sdkCtx, NewDel); err != nil {
panic(err)
Expand Down Expand Up @@ -107,7 +108,7 @@ func BenchmarkGetValidatorDelegationsLegacy(b *testing.B) {
if err != nil {
panic(err)
}
NewDel := types.NewDelegation(delegator, val, math.LegacyNewDec(int64(i)))
NewDel := types.NewDelegation(delegator.String(), val.String(), math.LegacyNewDec(int64(i)))
if err := f.stakingKeeper.SetDelegation(f.sdkCtx, NewDel); err != nil {
panic(err)
}
Expand All @@ -131,7 +132,12 @@ func updateValidatorDelegationsLegacy(f *fixture, existingValAddr, newValAddr sd

for ; iterator.Valid(); iterator.Next() {
delegation := types.MustUnmarshalDelegation(cdc, iterator.Value())
if delegation.GetValidatorAddr().Equals(existingValAddr) {
valAddr, err := k.ValidatorAddressCodec().StringToBytes(delegation.GetValidatorAddr())
if err != nil {
panic(err)
}

if bytes.EqualFold(valAddr, existingValAddr) {
if err := k.RemoveDelegation(f.sdkCtx, delegation); err != nil {
panic(err)
}
Expand Down
6 changes: 3 additions & 3 deletions tests/integration/staking/simulation/operations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ func (s *SimTestSuite) TestSimulateMsgCancelUnbondingDelegation() {
delTokens := s.stakingKeeper.TokensFromConsensusPower(ctx, 2)
validator0, issuedShares := validator0.AddTokensFromDel(delTokens)
delegator := s.accounts[2]
delegation := types.NewDelegation(delegator.Address, validator0.GetOperator(), issuedShares)
delegation := types.NewDelegation(delegator.Address.String(), validator0.GetOperator().String(), issuedShares)
require.NoError(s.stakingKeeper.SetDelegation(ctx, delegation))
s.Require().NoError(s.distrKeeper.DelegatorStartingInfo.Set(ctx, collections.Join(validator0.GetOperator(), delegator.Address), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200)))

Expand Down Expand Up @@ -288,7 +288,7 @@ func (s *SimTestSuite) TestSimulateMsgUndelegate() {
delTokens := s.stakingKeeper.TokensFromConsensusPower(ctx, 2)
validator0, issuedShares := validator0.AddTokensFromDel(delTokens)
delegator := s.accounts[2]
delegation := types.NewDelegation(delegator.Address, validator0.GetOperator(), issuedShares)
delegation := types.NewDelegation(delegator.Address.String(), validator0.GetOperator().String(), issuedShares)
require.NoError(s.stakingKeeper.SetDelegation(ctx, delegation))
s.Require().NoError(s.distrKeeper.DelegatorStartingInfo.Set(ctx, collections.Join(validator0.GetOperator(), delegator.Address), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200)))

Expand Down Expand Up @@ -329,7 +329,7 @@ func (s *SimTestSuite) TestSimulateMsgBeginRedelegate() {

// setup accounts[3] as delegator
delegator := s.accounts[3]
delegation := types.NewDelegation(delegator.Address, validator0.GetOperator(), issuedShares)
delegation := types.NewDelegation(delegator.Address.String(), validator0.GetOperator().String(), issuedShares)
require.NoError(s.stakingKeeper.SetDelegation(ctx, delegation))
s.Require().NoError(s.distrKeeper.DelegatorStartingInfo.Set(ctx, collections.Join(validator0.GetOperator(), delegator.Address), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200)))

Expand Down
2 changes: 1 addition & 1 deletion testutil/sims/app_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ func GenesisStateWithValSet(
MinSelfDelegation: sdkmath.ZeroInt(),
}
validators = append(validators, validator)
delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdkmath.LegacyOneDec()))
delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress().String(), sdk.ValAddress(val.Address).String(), sdkmath.LegacyOneDec()))

}

Expand Down
44 changes: 33 additions & 11 deletions x/distribution/keeper/delegation.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,19 @@ 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
}

valAddr, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(del.GetValidatorAddr())
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(sdk.ValAddress(valAddr), sdk.AccAddress(delAddr)))
if err != nil && !errors.Is(err, collections.ErrNotFound) {
return sdk.DecCoins{}, err
}
Expand All @@ -109,7 +120,7 @@ func (k Keeper) CalculateDelegationRewards(ctx context.Context, val stakingtypes
// for them for the stake sanity check below.
endingHeight := uint64(sdkCtx.BlockHeight())
if endingHeight > startingHeight {
k.IterateValidatorSlashEventsBetween(ctx, del.GetValidatorAddr(), startingHeight, endingHeight,
k.IterateValidatorSlashEventsBetween(ctx, valAddr, startingHeight, endingHeight,
func(height uint64, event types.ValidatorSlashEvent) (stop bool) {
endingPeriod := event.ValidatorPeriod
if endingPeriod > startingPeriod {
Expand Down Expand Up @@ -178,8 +189,19 @@ 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
}

valAddr, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(del.GetValidatorAddr())
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(sdk.ValAddress(valAddr), sdk.AccAddress(delAddr)))
if err != nil {
return nil, err
}
Expand All @@ -199,7 +221,7 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val stakingtypes.
return nil, err
}

outstanding, err := k.GetValidatorOutstandingRewardsCoins(ctx, del.GetValidatorAddr())
outstanding, err := k.GetValidatorOutstandingRewardsCoins(ctx, sdk.ValAddress(valAddr))
if err != nil {
return nil, err
}
Expand All @@ -211,7 +233,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 +245,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 All @@ -236,7 +258,7 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val stakingtypes.

// update the outstanding rewards and the community pool only if the
// transaction was successful
err = k.ValidatorOutstandingRewards.Set(ctx, del.GetValidatorAddr(), types.ValidatorOutstandingRewards{Rewards: outstanding.Sub(rewards)})
err = k.ValidatorOutstandingRewards.Set(ctx, sdk.ValAddress(valAddr), types.ValidatorOutstandingRewards{Rewards: outstanding.Sub(rewards)})
if err != nil {
return nil, err
}
Expand All @@ -253,19 +275,19 @@ 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(sdk.ValAddress(valAddr), sdk.AccAddress(delAddr)))
if err != nil && !errors.Is(err, collections.ErrNotFound) {
return nil, err
}

startingPeriod := startingInfo.PreviousPeriod
err = k.decrementReferenceCount(ctx, del.GetValidatorAddr(), startingPeriod)
err = k.decrementReferenceCount(ctx, sdk.ValAddress(valAddr), startingPeriod)
if err != nil {
return nil, err
}

// remove delegator starting info
err = k.DelegatorStartingInfo.Remove(ctx, collections.Join(del.GetValidatorAddr(), del.GetDelegatorAddr()))
err = k.DelegatorStartingInfo.Remove(ctx, collections.Join(sdk.ValAddress(valAddr), sdk.AccAddress(delAddr)))
if err != nil {
return nil, err
}
Expand All @@ -287,7 +309,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
Loading