-
Notifications
You must be signed in to change notification settings - Fork 50
/
proposal.go
688 lines (604 loc) · 24.8 KB
/
proposal.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
package keeper
import (
"encoding/binary"
"fmt"
"sort"
"time"
"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
vestexported "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
vesting "github.com/shentufoundation/shentu/v2/x/auth/types"
"github.com/shentufoundation/shentu/v2/x/shield/types"
)
// SecureCollaterals is called after a claim is submitted to secure
// the given amount of collaterals for the duration and adjust shield
// module states accordingly.
func (k Keeper) SecureCollaterals(ctx sdk.Context, poolID uint64, purchaser sdk.AccAddress, purchaseID uint64, loss sdk.Coins, duration time.Duration) error {
lossAmt := loss.AmountOf(k.sk.BondDenom(ctx))
// Verify shield.
pool, found := k.GetPool(ctx, poolID)
if !found {
return types.ErrNoPoolFound
}
if lossAmt.GT(pool.Shield) {
return types.ErrNotEnoughShield
}
// Verify collateral availability.
totalCollateral := k.GetTotalCollateral(ctx)
totalSecureAmt := k.GetTotalClaimed(ctx).Add(lossAmt)
if totalSecureAmt.GT(totalCollateral) {
panic("total secure amount surpassed total collateral")
}
// Verify purchase.
purchaseList, found := k.GetPurchaseList(ctx, poolID, purchaser)
if !found {
return types.ErrPurchaseNotFound
}
var index int
for i, entry := range purchaseList.Entries {
if entry.PurchaseId == purchaseID {
index = i
break
}
if i == len(purchaseList.Entries)-1 {
return types.ErrPurchaseNotFound
}
}
purchase := &purchaseList.Entries[index]
if lossAmt.GT(purchase.Shield) {
return types.ErrNotEnoughShield
}
// Secure the updated loss ratio from each provider to cover total claimed.
providers := k.GetAllProviders(ctx)
claimedRatio := sdk.NewDecFromInt(totalSecureAmt).Quo(sdk.NewDecFromInt(totalCollateral))
remaining := totalSecureAmt
for i := range providers {
secureAmt := sdk.MinInt(sdk.NewDecFromInt(providers[i].Collateral).Mul(claimedRatio).TruncateInt(), remaining)
// Require each provider to secure one more unit, if possible,
// so that the last provider does not have to cover combined
// truncated amounts.
if secureAmt.LT(remaining) && secureAmt.LT(providers[i].Collateral) {
secureAmt = secureAmt.Add(sdk.OneInt())
}
k.SecureFromProvider(ctx, providers[i], secureAmt, duration)
remaining = remaining.Sub(secureAmt)
}
// Update purchase states.
purchase.Shield = purchase.Shield.Sub(lossAmt)
votingEndTime := ctx.BlockTime().Add(duration)
if purchase.DeletionTime.Before(votingEndTime) {
purchase.DeletionTime = votingEndTime
}
k.SetPurchaseList(ctx, purchaseList)
// Update pool and global pool states.
pool.Shield = pool.Shield.Sub(lossAmt)
k.SetPool(ctx, pool)
totalShield := k.GetTotalShield(ctx)
totalShield = totalShield.Sub(lossAmt)
k.SetTotalShield(ctx, totalShield)
k.SetTotalClaimed(ctx, totalSecureAmt)
return nil
}
// SecureFromProvider secures the specified amount of collaterals from
// the provider for the duration. If necessary, it extends withdrawing
// collaterals and, if exist, their linked unbondings as well.
func (k Keeper) SecureFromProvider(ctx sdk.Context, provider types.Provider, amount math.Int, duration time.Duration) {
providerAddr, err := sdk.AccAddressFromBech32(provider.Address)
if err != nil {
panic(err)
}
// Lenient check:
// We are done if non-withdrawing, bonded delegation-backed
// collaterals can cover the amount.
if provider.Collateral.Sub(provider.Withdrawing).GTE(amount) && provider.DelegationBonded.GTE(amount) {
return
}
// Secure the given amount of collaterals until the end of the
// lock period by delaying withdrawals, if necessary.
// availableCollateralByEndTime = ProviderTotalCollateral - WithdrawnByEndTime
endTime := ctx.BlockTime().Add(duration)
availableCollateralByEndTime := provider.Collateral.Sub(k.ComputeWithdrawAmountByTime(ctx, provider.Address, endTime))
// Secure the given amount of staking (bonded or unbonding) until
// the end of the lock period by delaying unbondings, if necessary.
// availableDelegationByEndTime = Bonded + Unbonding - UnbondedByEndTime
availableDelegationByEndTime := provider.DelegationBonded.Add(k.ComputeTotalUnbondingAmount(ctx, providerAddr).Sub(k.ComputeUnbondingAmountByTime(ctx, providerAddr, endTime)))
// Collaterals that won't be withdrawn until the end time must be
// backed by staking that won't be unbonded until the end time.
if !availableCollateralByEndTime.LTE(availableDelegationByEndTime) {
panic("notWithdrawnSoon must be less than or equal to notUnbondedSoon")
}
if amount.GT(availableCollateralByEndTime) {
withdrawDelayAmt := amount.Sub(availableCollateralByEndTime)
k.DelayWithdraws(ctx, provider.Address, withdrawDelayAmt, endTime)
if amount.GT(availableDelegationByEndTime) {
unbondingDelayAmt := amount.Sub(availableDelegationByEndTime)
k.DelayUnbonding(ctx, providerAddr, unbondingDelayAmt, endTime)
}
}
}
// ClaimEnd ends a claim process by updating the total claimed amount.
func (k Keeper) ClaimEnd(ctx sdk.Context, id, poolID uint64, loss sdk.Coins) {
lossAmt := loss.AmountOf(k.sk.BondDenom(ctx))
totalClaimed := k.GetTotalClaimed(ctx).Sub(lossAmt)
k.SetTotalClaimed(ctx, totalClaimed)
}
// RestoreShield restores shield-related states as they were prior to
// the claim proposal submission.
func (k Keeper) RestoreShield(ctx sdk.Context, poolID uint64, purchaser sdk.AccAddress, id uint64, loss sdk.Coins) error {
lossAmt := loss.AmountOf(k.sk.BondDenom(ctx))
// Update the total shield.
totalShield := k.GetTotalShield(ctx).Add(lossAmt)
k.SetTotalShield(ctx, totalShield)
// Update shield of the pool.
pool, found := k.GetPool(ctx, poolID)
if !found {
return types.ErrNoPoolFound
}
pool.Shield = pool.Shield.Add(lossAmt)
k.SetPool(ctx, pool)
// Update shield of the purchase.
purchaseList, found := k.GetPurchaseList(ctx, poolID, purchaser)
if !found {
return types.ErrPurchaseNotFound
}
for i := range purchaseList.Entries {
if purchaseList.Entries[i].PurchaseId == id {
purchaseList.Entries[i].Shield = purchaseList.Entries[i].Shield.Add(lossAmt)
break
}
}
k.SetPurchaseList(ctx, purchaseList)
return nil
}
// SetReimbursement sets a reimbursement in store.
func (k Keeper) SetReimbursement(ctx sdk.Context, proposalID uint64, payout types.Reimbursement) {
store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshalLengthPrefixed(&payout)
store.Set(types.GetReimbursementKey(proposalID), bz)
}
// GetReimbursement get a reimbursement in store.
func (k Keeper) GetReimbursement(ctx sdk.Context, proposalID uint64) (types.Reimbursement, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.GetReimbursementKey(proposalID))
if bz != nil {
var reimbursement types.Reimbursement
k.cdc.MustUnmarshalLengthPrefixed(bz, &reimbursement)
return reimbursement, nil
}
return types.Reimbursement{}, types.ErrReimbursementNotFound
}
// DeleteReimbursement deletes a reimbursement.
func (k Keeper) DeleteReimbursement(ctx sdk.Context, proposalID uint64) error {
store := ctx.KVStore(k.storeKey)
if _, err := k.GetReimbursement(ctx, proposalID); err != nil {
return err
}
store.Delete(types.GetReimbursementKey(proposalID))
return nil
}
// IterateReimbursements iterates through all reimbursements.
func (k Keeper) IterateReimbursements(ctx sdk.Context, callback func(rmb types.Reimbursement) (stop bool)) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, types.ReimbursementKey)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var rmb types.Reimbursement
k.cdc.MustUnmarshalLengthPrefixed(iterator.Value(), &rmb)
if callback(rmb) {
break
}
}
}
// GetAllReimbursements retrieves all reimbursements.
func (k Keeper) GetAllReimbursements(ctx sdk.Context) (rmbs []types.Reimbursement) {
k.IterateReimbursements(ctx, func(rmb types.Reimbursement) bool {
rmbs = append(rmbs, rmb)
return false
})
return
}
// GetAllProposalIDReimbursementPairs retrieves all proposal ID and reimbursement pairs.
func (k Keeper) GetAllProposalIDReimbursementPairs(ctx sdk.Context) []types.ProposalIDReimbursementPair {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, types.ReimbursementKey)
var pRPairs []types.ProposalIDReimbursementPair
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
proposalID := binary.LittleEndian.Uint64(iterator.Key()[len(types.ReimbursementKey):])
var reimbursement types.Reimbursement
k.cdc.MustUnmarshalLengthPrefixed(iterator.Value(), &reimbursement)
pRPairs = append(pRPairs, types.NewProposalIDReimbursementPair(proposalID, reimbursement))
}
return pRPairs
}
// CreateReimbursement creates a reimbursement.
func (k Keeper) CreateReimbursement(ctx sdk.Context, proposalID uint64, amount sdk.Coins, beneficiary sdk.AccAddress) error {
bondDenom := k.BondDenom(ctx)
totalCollateral := k.GetTotalCollateral(ctx)
totalPurchased := k.GetTotalShield(ctx)
totalPayout := amount.AmountOf(bondDenom)
purchaseRatio := sdk.NewDecFromInt(totalPurchased).Quo(sdk.NewDecFromInt(totalCollateral))
payoutRatio := sdk.NewDecFromInt(totalPayout).Quo(sdk.NewDecFromInt(totalCollateral))
for _, provider := range k.GetAllProviders(ctx) {
if !totalPayout.IsPositive() {
break
}
providerAddr, err := sdk.AccAddressFromBech32(provider.Address)
if err != nil {
panic(err)
}
purchased := sdk.NewDecFromInt(provider.Collateral).Mul(purchaseRatio).TruncateInt()
if purchased.GT(totalPurchased) {
purchased = totalPurchased
}
payout := sdk.NewDecFromInt(provider.Collateral).Mul(payoutRatio).TruncateInt()
if payout.GT(totalPayout) {
payout = totalPayout
}
// Require providers to cover (purchased + 1) and (payout + 1) if it's possible,
// so that the last provider will not be asked to cover all truncated amount.
if purchased.LT(totalPurchased) && provider.Collateral.GT(payout.Add(purchased)) {
purchased = purchased.Add(sdk.OneInt())
}
if payout.LT(totalPayout) && provider.Collateral.GT(payout.Add(purchased)) {
payout = payout.Add(sdk.OneInt())
}
if err := k.UpdateProviderCollateralForPayout(ctx, providerAddr, purchased, payout); err != nil {
panic(err)
}
if err := k.MakePayoutByProviderDelegations(ctx, providerAddr, purchased, payout); err != nil {
panic(err)
}
totalPurchased = totalPurchased.Sub(purchased)
totalPayout = totalPayout.Sub(payout)
}
if totalPayout.IsPositive() {
panic("not enough payout made")
}
reimbursement := types.NewReimbursement(amount, beneficiary, ctx.BlockTime().Add(k.GetClaimProposalParams(ctx).PayoutPeriod))
k.SetReimbursement(ctx, proposalID, reimbursement)
totalCollateral = totalCollateral.Sub(amount.AmountOf(bondDenom))
totalClaimed := k.GetTotalClaimed(ctx)
totalClaimed = totalClaimed.Sub(amount.AmountOf(bondDenom))
k.SetTotalCollateral(ctx, totalCollateral)
k.SetTotalClaimed(ctx, totalClaimed)
return nil
}
// UpdateProviderCollateralForPayout updates a provider's collateral and withdraws according to the payout.
func (k Keeper) UpdateProviderCollateralForPayout(ctx sdk.Context, providerAddr sdk.AccAddress, purchased, payout math.Int) error {
provider, found := k.GetProvider(ctx, providerAddr)
if !found {
return types.ErrProviderNotFound
}
totalWithdrawing := k.GetTotalWithdrawing(ctx)
uncoveredPurchase := sdk.ZeroInt()
payoutFromCollateral := sdk.ZeroInt()
if provider.Collateral.Sub(provider.Withdrawing).GTE(purchased.Add(payout)) {
// If collateral - withdraw >= purchased + payout:
// purchased payout
// ----------------|--------|
// collateral - withdraw withdraw
// -------------------------------|---------------------------------
payoutFromCollateral = payout
} else if provider.Collateral.Sub(provider.Withdrawing).GTE(purchased) {
// If purchased <= collateral - withdraw < purchased + payout:
// purchased payout
// ----------------|--------|
// collateral - withdraw withdraw
// -------------------------------|---------------------------------
payoutFromCollateral = provider.Collateral.Sub(provider.Withdrawing).Sub(purchased)
} else {
// If collateral - withdraw < purchased:
// purchased payout
// ----------------|--------|
// collateral - withdraw withdraw
// -------------------------------|---------------------------------
uncoveredPurchase = purchased.Sub(provider.Collateral.Sub(provider.Withdrawing))
}
payoutFromWithdraw := payout.Sub(payoutFromCollateral)
// Update provider's collateral and total withdraw.
provider.Collateral = provider.Collateral.Sub(payoutFromCollateral)
provider.Withdrawing = provider.Withdrawing.Sub(payoutFromWithdraw)
totalWithdrawing = totalWithdrawing.Sub(payoutFromWithdraw)
// Update provider's withdraws from latest to oldest.
withdraws := k.GetWithdrawsByProvider(ctx, provider.Address)
for i := len(withdraws) - 1; i >= 0 && payoutFromWithdraw.IsPositive(); i-- {
// If purchased is not fully covered, cover purchased first.
remainingWithdraw := sdk.MaxInt(withdraws[i].Amount.Sub(uncoveredPurchase), sdk.ZeroInt())
uncoveredPurchase = sdk.MaxInt(uncoveredPurchase.Sub(withdraws[i].Amount), sdk.ZeroInt())
if remainingWithdraw.IsZero() {
continue
}
// Update the withdraw based on payout after purchased is fully covered.
payoutFromThisWithdraw := sdk.MinInt(payoutFromWithdraw, remainingWithdraw)
payoutFromWithdraw = payoutFromWithdraw.Sub(payoutFromThisWithdraw)
timeSlice := k.GetWithdrawQueueTimeSlice(ctx, withdraws[i].CompletionTime)
for j := range timeSlice {
if timeSlice[j].Address != withdraws[i].Address || !timeSlice[j].Amount.Equal(withdraws[i].Amount) {
continue
}
if withdraws[i].Amount.Equal(payoutFromThisWithdraw) {
if len(timeSlice) == 1 {
k.RemoveTimeSliceFromWithdrawQueue(ctx, withdraws[i].CompletionTime)
} else {
timeSlice = append(timeSlice[:j], timeSlice[j+1:]...)
k.SetWithdrawQueueTimeSlice(ctx, withdraws[i].CompletionTime, timeSlice)
}
} else {
timeSlice[j].Amount = withdraws[i].Amount.Sub(payoutFromThisWithdraw)
k.SetWithdrawQueueTimeSlice(ctx, withdraws[i].CompletionTime, timeSlice)
}
break
}
}
if !payoutFromWithdraw.IsZero() {
panic("exact payout was not made from withdrawals")
}
k.SetTotalWithdrawing(ctx, totalWithdrawing)
k.SetProvider(ctx, providerAddr, provider)
return nil
}
// MakePayoutByProviderDelegations undelegates the provider's delegations and transfers tokens from the staking module account to the shield module account.
func (k Keeper) MakePayoutByProviderDelegations(ctx sdk.Context, providerAddr sdk.AccAddress, purchased, payout math.Int) error {
provider, found := k.GetProvider(ctx, providerAddr)
if !found {
return types.ErrProviderNotFound
}
uncoveredPurchase := sdk.ZeroInt()
payoutFromDelegation := sdk.ZeroInt()
if provider.DelegationBonded.GTE(purchased.Add(payout)) {
// If delegation >= purchased + payout:
// purchased payout
// ----------------|--------|
// delegations unbondings
// -------------------------------|---------------------------------
payoutFromDelegation = payout
} else if provider.DelegationBonded.GTE(purchased) {
// If purchased <= delegation < purchased + payout:
// purchased payout
// ----------------|--------|
// delegations unbondings
// -------------------------------|---------------------------------
payoutFromDelegation = provider.DelegationBonded.Sub(purchased)
} else {
// If delegation < purchased:
// purchased payout
// ----------------|--------|
// delegations unbondings
// -------------------------------|---------------------------------
uncoveredPurchase = purchased.Sub(provider.DelegationBonded)
}
payoutFromUnbonding := payout.Sub(payoutFromDelegation)
if payoutFromDelegation.IsPositive() {
k.PayFromDelegation(ctx, providerAddr, payoutFromDelegation)
}
if payoutFromUnbonding.IsZero() {
return nil
}
unbondingDelegations := k.GetSortedUnbondingDelegations(ctx, providerAddr)
for _, ubd := range unbondingDelegations {
if !payoutFromUnbonding.IsPositive() {
break
}
entry := ubd.Entries[0]
// If purchased is not fully covered, cover purchased first.
remainingUbd := sdk.MaxInt(entry.Balance.Sub(uncoveredPurchase), sdk.ZeroInt())
uncoveredPurchase = sdk.MaxInt(uncoveredPurchase.Sub(entry.Balance), sdk.ZeroInt())
if remainingUbd.IsZero() {
continue
}
// Make payout after purchased is fully covered.
payoutFromThisUbd := sdk.MinInt(payoutFromUnbonding, remainingUbd)
k.PayFromUnbondings(ctx, ubd, payoutFromThisUbd)
payoutFromUnbonding = payoutFromUnbonding.Sub(payoutFromThisUbd)
}
if !payoutFromUnbonding.IsZero() {
panic("exact pay out was not made from unbondings")
}
return nil
}
// PayFromDelegation reduce provider's delegations and transfer tokens to the shield module account.
func (k Keeper) PayFromDelegation(ctx sdk.Context, delAddr sdk.AccAddress, payout math.Int) {
provider, found := k.GetProvider(ctx, delAddr)
if !found {
panic(types.ErrProviderNotFound)
}
totalDelAmount := provider.DelegationBonded
delegations := k.sk.GetAllDelegatorDelegations(ctx, delAddr)
payoutRatio := sdk.NewDecFromInt(payout).Quo(sdk.NewDecFromInt(totalDelAmount))
remaining := payout
for i := range delegations {
if !remaining.IsPositive() {
return
}
val, found := k.sk.GetValidator(ctx, delegations[i].GetValidatorAddr())
if !found {
panic("validator is not found")
}
delAmount := val.TokensFromShares(delegations[i].GetShares()).TruncateInt()
var ubdAmount math.Int
if i == len(delegations)-1 {
ubdAmount = remaining
} else {
ubdAmount = sdk.MinInt(payoutRatio.MulInt(delAmount).TruncateInt(), remaining)
if ubdAmount.LT(remaining) && ubdAmount.LT(delAmount) {
ubdAmount = ubdAmount.Add(sdk.OneInt())
}
remaining = remaining.Sub(ubdAmount)
}
ubdShares, err := val.SharesFromTokens(ubdAmount)
if err != nil {
panic(err)
}
delAddr, err := sdk.AccAddressFromBech32(delegations[i].DelegatorAddress)
if err != nil {
panic(err)
}
valAddr, err := sdk.ValAddressFromBech32(delegations[i].ValidatorAddress)
if err != nil {
panic(err)
}
k.UndelegateShares(ctx, delAddr, valAddr, ubdShares)
}
}
// PayFromUnbondings reduce provider's unbonding delegations and transfer tokens to the shield module account.
func (k Keeper) PayFromUnbondings(ctx sdk.Context, ubd stakingtypes.UnbondingDelegation, payout math.Int) {
delAddr, err := sdk.AccAddressFromBech32(ubd.DelegatorAddress)
if err != nil {
panic(err)
}
valAddr, err := sdk.ValAddressFromBech32(ubd.ValidatorAddress)
if err != nil {
panic(err)
}
unbonding, found := k.sk.GetUnbondingDelegation(ctx, delAddr, valAddr)
if !found {
panic("unbonding delegation is not found")
}
// Update unbonding delegations between the delegator and the validator.
for i := range unbonding.Entries {
if !unbonding.Entries[i].Balance.Equal(ubd.Entries[0].Balance) || !unbonding.Entries[i].CompletionTime.Equal(ubd.Entries[0].CompletionTime) {
continue
}
if unbonding.Entries[i].Balance.Equal(payout) {
// Update the unbonding queue and remove the entry.
timeSlice := k.sk.GetUBDQueueTimeSlice(ctx, unbonding.Entries[i].CompletionTime)
if len(timeSlice) > 1 {
for j, slice := range timeSlice {
if slice.DelegatorAddress == ubd.DelegatorAddress && slice.ValidatorAddress == ubd.ValidatorAddress {
timeSlice = append(timeSlice[:j], timeSlice[j+1:]...)
k.sk.SetUBDQueueTimeSlice(ctx, unbonding.Entries[i].CompletionTime, timeSlice)
break
}
}
} else {
k.sk.RemoveUBDQueue(ctx, unbonding.Entries[i].CompletionTime)
}
unbonding.RemoveEntry(int64(i))
} else {
unbonding.Entries[i].Balance = unbonding.Entries[i].Balance.Sub(payout)
}
if len(unbonding.Entries) == 0 {
k.sk.RemoveUnbondingDelegation(ctx, unbonding)
} else {
k.sk.SetUnbondingDelegation(ctx, unbonding)
}
break
}
// Transfer tokens from staking module's not bonded pool.
payoutCoins := sdk.NewCoins(sdk.NewCoin(k.sk.BondDenom(ctx), payout))
if err := k.UndelegateFromAccountToShieldModule(ctx, stakingtypes.NotBondedPoolName, delAddr, payoutCoins); err != nil {
panic(err)
}
}
// UndelegateShares undelegates delegations of a delegator to a validator by shares.
func (k Keeper) UndelegateShares(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, shares sdk.Dec) {
delegation, found := k.sk.GetDelegation(ctx, delAddr, valAddr)
if !found {
panic("delegation is not found")
}
k.sk.BeforeDelegationSharesModified(ctx, delAddr, valAddr)
// Undelegate coins from the staking module account to the shield module account.
validator, found := k.sk.GetValidator(ctx, valAddr)
if !found {
panic("validator is not found")
}
// Update delegation records.
delegation.Shares = delegation.Shares.Sub(shares)
isValidatorOperator := delegation.GetDelegatorAddr().Equals(validator.GetOperator())
if isValidatorOperator && !validator.Jailed && validator.TokensFromShares(delegation.Shares).TruncateInt().LT(validator.MinSelfDelegation) {
validator.Jailed = true
k.sk.SetValidator(ctx, validator)
k.sk.DeleteValidatorByPowerIndex(ctx, validator)
validator, found = k.sk.GetValidator(ctx, valAddr)
if !found {
panic(fmt.Sprintf("validator record not found for address: %X\n", valAddr))
}
}
if delegation.Shares.IsZero() {
k.sk.RemoveDelegation(ctx, delegation)
} else {
k.sk.SetDelegation(ctx, delegation)
k.sk.AfterDelegationModified(ctx, delegation.GetDelegatorAddr(), delegation.GetValidatorAddr())
}
validator, amount := k.sk.RemoveValidatorTokensAndShares(ctx, validator, shares)
if validator.DelegatorShares.IsZero() && validator.IsUnbonded() {
k.sk.RemoveValidator(ctx, validator.GetOperator())
}
coins := sdk.NewCoins(sdk.NewCoin(k.BondDenom(ctx), amount))
srcPool := stakingtypes.NotBondedPoolName
if validator.IsBonded() {
srcPool = stakingtypes.BondedPoolName
}
err := k.UndelegateFromAccountToShieldModule(ctx, srcPool, delAddr, coins)
if err != nil {
panic(err)
}
}
// UndelegateFromAccountToShieldModule performs undelegations from a delegator's staking to the shield module.
func (k Keeper) UndelegateFromAccountToShieldModule(ctx sdk.Context, senderModule string, delAddr sdk.AccAddress, amt sdk.Coins) error {
delAcc := k.ak.GetAccount(ctx, delAddr)
if delAcc == nil {
return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", delAddr)
}
if vacc, ok := delAcc.(vestexported.VestingAccount); ok {
originalDelegatedVesting := vacc.GetDelegatedVesting()
vacc.TrackUndelegation(amt)
updatedDelegatedVesting := vacc.GetDelegatedVesting()
updateAmt := originalDelegatedVesting.Sub(updatedDelegatedVesting...)
if mvacc, ok := delAcc.(*vesting.ManualVestingAccount); ok {
var unlockAmt sdk.Coins
if mvacc.OriginalVesting.Sub(mvacc.VestedCoins...).IsAllGT(updateAmt) {
unlockAmt = updateAmt
} else {
unlockAmt = mvacc.OriginalVesting.Sub(mvacc.VestedCoins...)
}
mvacc.VestedCoins = mvacc.VestedCoins.Add(unlockAmt...)
}
k.ak.SetAccount(ctx, delAcc)
}
if err := k.bk.SendCoinsFromModuleToModule(ctx, senderModule, types.ModuleName, amt); err != nil {
panic(err)
}
return nil
}
// GetSortedUnbondingDelegations gets unbonding delegations sorted by completion time from latest to earliest.
func (k Keeper) GetSortedUnbondingDelegations(ctx sdk.Context, delAddr sdk.AccAddress) []stakingtypes.UnbondingDelegation {
ubds := k.sk.GetAllUnbondingDelegations(ctx, delAddr)
var unbondingDelegations []stakingtypes.UnbondingDelegation
for _, ubd := range ubds {
for _, entry := range ubd.Entries {
unbondingDelegations = append(
unbondingDelegations,
types.NewUnbondingDelegation(ubd.DelegatorAddress, ubd.ValidatorAddress, entry),
)
}
}
sort.SliceStable(unbondingDelegations, func(i, j int) bool {
return unbondingDelegations[i].Entries[0].CompletionTime.After(unbondingDelegations[j].Entries[0].CompletionTime)
})
return unbondingDelegations
}
// WithdrawReimbursement withdraws a reimbursement made for a beneficiary.
func (k Keeper) WithdrawReimbursement(ctx sdk.Context, proposalID uint64, beneficiary sdk.AccAddress) (sdk.Coins, error) {
reimbursement, err := k.GetReimbursement(ctx, proposalID)
if err != nil {
return sdk.Coins{}, err
}
// check beneficiary and time
if reimbursement.Beneficiary != beneficiary.String() {
return sdk.Coins{}, types.ErrInvalidBeneficiary
}
if reimbursement.PayoutTime.After(ctx.BlockTime()) {
return sdk.Coins{}, types.ErrNotPayoutTime
}
if err := k.bk.SendCoinsFromModuleToAccount(ctx, types.ModuleName, beneficiary, reimbursement.Amount); err != nil {
return sdk.Coins{}, types.ErrNotPayoutTime
}
if err := k.DeleteReimbursement(ctx, proposalID); err != nil {
return sdk.Coins{}, err
}
return reimbursement.Amount, nil
}