/
keeper.go
326 lines (273 loc) · 9.65 KB
/
keeper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package keeper
import (
"fmt"
"github.com/tendermint/tendermint/libs/log"
"github.com/cosmos/cosmos-sdk/codec"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
sdkdistr "github.com/cosmos/cosmos-sdk/x/distribution/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/incubus-network/fanfury-sdk/v2/x/lsnative/distribution/types"
)
// Keeper of the distribution store
type Keeper struct {
storeKey storetypes.StoreKey
cdc codec.BinaryCodec
paramSpace paramtypes.Subspace
authKeeper types.AccountKeeper
bankKeeper types.BankKeeper
stakingKeeper types.StakingKeeper
feeCollectorName string // name of the FeeCollector ModuleAccount
}
// NewKeeper creates a new distribution Keeper instance
func NewKeeper(
cdc codec.BinaryCodec, key storetypes.StoreKey, paramSpace paramtypes.Subspace,
ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper,
feeCollectorName string,
) Keeper {
// ensure distribution module account is set
if addr := ak.GetModuleAddress(types.ModuleName); addr == nil {
panic(fmt.Sprintf("%s module account has not been set", types.ModuleName))
}
// set KeyTable if it has not already been set
if !paramSpace.HasKeyTable() {
paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable())
}
return Keeper{
storeKey: key,
cdc: cdc,
paramSpace: paramSpace,
authKeeper: ak,
bankKeeper: bk,
stakingKeeper: sk,
feeCollectorName: feeCollectorName,
}
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", "x/"+types.ModuleName)
}
// SetWithdrawAddr sets a new address that will receive the rewards upon withdrawal
func (k Keeper) SetWithdrawAddr(ctx sdk.Context, delegatorAddr sdk.AccAddress, withdrawAddr sdk.AccAddress) error {
if k.bankKeeper.BlockedAddr(withdrawAddr) {
return sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive external funds", withdrawAddr)
}
if !k.GetWithdrawAddrEnabled(ctx) {
return sdkdistr.ErrSetWithdrawAddrDisabled
}
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeSetWithdrawAddress,
sdk.NewAttribute(types.AttributeKeyWithdrawAddress, withdrawAddr.String()),
),
)
k.SetDelegatorWithdrawAddr(ctx, delegatorAddr, withdrawAddr)
return nil
}
// withdraw rewards from a delegation
func (k Keeper) WithdrawDelegationRewards(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (sdk.Coins, error) {
val := k.stakingKeeper.Validator(ctx, valAddr)
if val == nil {
return nil, sdkdistr.ErrNoValidatorDistInfo
}
del := k.stakingKeeper.Delegation(ctx, delAddr, valAddr)
if del == nil {
return nil, sdkdistr.ErrEmptyDelegationDistInfo
}
// withdraw rewards
rewards, err := k.withdrawDelegationRewards(ctx, val, del)
if err != nil {
return nil, err
}
if rewards.IsZero() {
baseDenom, _ := sdk.GetBaseDenom()
rewards = sdk.Coins{sdk.Coin{
Denom: baseDenom,
Amount: sdk.ZeroInt(),
}}
}
// reinitialize the delegation
k.initializeDelegation(ctx, valAddr, delAddr)
return rewards, nil
}
// withdraw validator commission
func (k Keeper) WithdrawValidatorCommission(ctx sdk.Context, valAddr sdk.ValAddress) (sdk.Coins, error) {
// fetch validator accumulated commission
accumCommission := k.GetValidatorAccumulatedCommission(ctx, valAddr)
if accumCommission.Commission.IsZero() {
return nil, sdkdistr.ErrNoValidatorCommission
}
commission, remainder := accumCommission.Commission.TruncateDecimal()
k.SetValidatorAccumulatedCommission(ctx, valAddr, types.ValidatorAccumulatedCommission{Commission: remainder}) // leave remainder to withdraw later
// update outstanding
outstanding := k.GetValidatorOutstandingRewards(ctx, valAddr).Rewards
k.SetValidatorOutstandingRewards(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: outstanding.Sub(sdk.NewDecCoinsFromCoins(commission...))})
if !commission.IsZero() {
accAddr := sdk.AccAddress(valAddr)
withdrawAddr := k.GetDelegatorWithdrawAddr(ctx, accAddr)
err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, withdrawAddr, commission)
if err != nil {
return nil, err
}
}
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeWithdrawCommission,
sdk.NewAttribute(sdk.AttributeKeyAmount, commission.String()),
),
)
return commission, nil
}
// GetTotalRewards returns the total amount of fee distribution rewards held in the store
func (k Keeper) GetTotalRewards(ctx sdk.Context) (totalRewards sdk.DecCoins) {
k.IterateValidatorOutstandingRewards(ctx,
func(_ sdk.ValAddress, rewards types.ValidatorOutstandingRewards) (stop bool) {
totalRewards = totalRewards.Add(rewards.Rewards...)
return false
},
)
return totalRewards
}
// FundCommunityPool allows an account to directly fund the community fund pool.
// The amount is first added to the distribution module account and then directly
// added to the pool. An error is returned if the amount cannot be sent to the
// module account.
func (k Keeper) FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error {
if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount); err != nil {
return err
}
feePool := k.GetFeePool(ctx)
feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...)
k.SetFeePool(ctx, feePool)
return nil
}
func (k Keeper) WithdrawSingleShareRecordReward(ctx sdk.Context, recordId uint64) error {
record, err := k.stakingKeeper.GetTokenizeShareRecord(ctx, recordId)
if err != nil {
return err
}
owner, err := sdk.AccAddressFromBech32(record.Owner)
if err != nil {
return err
}
valAddr, err := sdk.ValAddressFromBech32(record.Validator)
if err != nil {
return err
}
val := k.stakingKeeper.Validator(ctx, valAddr)
del := k.stakingKeeper.Delegation(ctx, record.GetModuleAddress(), valAddr)
if val != nil && del != nil {
// withdraw rewards into reward module account and send it to reward owner
cacheCtx, write := ctx.CacheContext()
_, err = k.WithdrawDelegationRewards(cacheCtx, record.GetModuleAddress(), valAddr)
if err != nil {
return err
}
write()
}
// apply changes when the module account has positive balance
balances := k.bankKeeper.GetAllBalances(ctx, record.GetModuleAddress())
if !balances.Empty() {
err = k.bankKeeper.SendCoins(ctx, record.GetModuleAddress(), owner, balances)
if err != nil {
return err
}
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeWithdrawTokenizeShareReward,
sdk.NewAttribute(types.AttributeKeyWithdrawAddress, owner.String()),
sdk.NewAttribute(sdk.AttributeKeyAmount, balances.String()),
),
)
}
return nil
}
// withdraw reward for owning TokenizeShareRecord
func (k Keeper) WithdrawTokenizeShareRecordReward(ctx sdk.Context, ownerAddr sdk.AccAddress, recordId uint64) (sdk.Coins, error) {
record, err := k.stakingKeeper.GetTokenizeShareRecord(ctx, recordId)
if err != nil {
return nil, err
}
if record.Owner != ownerAddr.String() {
return nil, types.ErrNotTokenizeShareRecordOwner
}
valAddr, err := sdk.ValAddressFromBech32(record.Validator)
if err != nil {
return nil, err
}
val := k.stakingKeeper.Validator(ctx, valAddr)
if val == nil {
return nil, err
}
del := k.stakingKeeper.Delegation(ctx, record.GetModuleAddress(), valAddr)
if del == nil {
return nil, err
}
// withdraw rewards into reward module account and send it to reward owner
_, err = k.WithdrawDelegationRewards(ctx, record.GetModuleAddress(), valAddr)
if err != nil {
return nil, err
}
// apply changes when the module account has positive balance
rewards := k.bankKeeper.GetAllBalances(ctx, record.GetModuleAddress())
if !rewards.Empty() {
err = k.bankKeeper.SendCoins(ctx, record.GetModuleAddress(), ownerAddr, rewards)
if err != nil {
return nil, err
}
}
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeWithdrawTokenizeShareReward,
sdk.NewAttribute(types.AttributeKeyWithdrawAddress, ownerAddr.String()),
sdk.NewAttribute(sdk.AttributeKeyAmount, rewards.String()),
),
)
return rewards, nil
}
// withdraw reward for all owning TokenizeShareRecord
func (k Keeper) WithdrawAllTokenizeShareRecordReward(ctx sdk.Context, ownerAddr sdk.AccAddress) (sdk.Coins, error) {
totalRewards := sdk.Coins{}
records := k.stakingKeeper.GetTokenizeShareRecordsByOwner(ctx, ownerAddr)
for _, record := range records {
valAddr, err := sdk.ValAddressFromBech32(record.Validator)
if err != nil {
return nil, err
}
val := k.stakingKeeper.Validator(ctx, valAddr)
if val == nil {
continue
}
del := k.stakingKeeper.Delegation(ctx, record.GetModuleAddress(), valAddr)
if del == nil {
continue
}
// withdraw rewards into reward module account and send it to reward owner
cacheCtx, write := ctx.CacheContext()
_, err = k.WithdrawDelegationRewards(cacheCtx, record.GetModuleAddress(), valAddr)
if err != nil {
k.Logger(ctx).Error(err.Error())
continue
}
// apply changes when the module account has positive balance
balances := k.bankKeeper.GetAllBalances(cacheCtx, record.GetModuleAddress())
if !balances.Empty() {
err = k.bankKeeper.SendCoins(cacheCtx, record.GetModuleAddress(), ownerAddr, balances)
if err != nil {
k.Logger(ctx).Error(err.Error())
continue
}
write()
totalRewards = totalRewards.Add(balances...)
}
}
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeWithdrawTokenizeShareReward,
sdk.NewAttribute(types.AttributeKeyWithdrawAddress, ownerAddr.String()),
sdk.NewAttribute(sdk.AttributeKeyAmount, totalRewards.String()),
),
)
return totalRewards, nil
}