-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
delegation.go
662 lines (550 loc) · 22.8 KB
/
delegation.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
package keeper
import (
"bytes"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/stake/types"
)
// return a specific delegation
func (k Keeper) GetDelegation(ctx sdk.Context,
delAddr sdk.AccAddress, valAddr sdk.ValAddress) (
delegation types.Delegation, found bool) {
store := ctx.KVStore(k.storeKey)
key := GetDelegationKey(delAddr, valAddr)
value := store.Get(key)
if value == nil {
return delegation, false
}
delegation = types.MustUnmarshalDelegation(k.cdc, key, value)
return delegation, true
}
// return all delegations used during genesis dump
func (k Keeper) GetAllDelegations(ctx sdk.Context) (delegations []types.Delegation) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, DelegationKey)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Key(), iterator.Value())
delegations = append(delegations, delegation)
}
return delegations
}
// return all delegations to a specific validator. Useful for querier.
func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []types.Delegation) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, DelegationKey)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Key(), iterator.Value())
if delegation.GetValidatorAddr().Equals(valAddr) {
delegations = append(delegations, delegation)
}
}
return delegations
}
// return a given amount of all the delegations from a delegator
func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress,
maxRetrieve uint16) (delegations []types.Delegation) {
delegations = make([]types.Delegation, maxRetrieve)
store := ctx.KVStore(k.storeKey)
delegatorPrefixKey := GetDelegationsKey(delegator)
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey)
defer iterator.Close()
i := 0
for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() {
delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Key(), iterator.Value())
delegations[i] = delegation
i++
}
return delegations[:i] // trim if the array length < maxRetrieve
}
// set the delegation
func (k Keeper) SetDelegation(ctx sdk.Context, delegation types.Delegation) {
store := ctx.KVStore(k.storeKey)
b := types.MustMarshalDelegation(k.cdc, delegation)
store.Set(GetDelegationKey(delegation.DelegatorAddr, delegation.ValidatorAddr), b)
}
// remove a delegation from store
func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) {
k.OnDelegationRemoved(ctx, delegation.DelegatorAddr, delegation.ValidatorAddr)
store := ctx.KVStore(k.storeKey)
store.Delete(GetDelegationKey(delegation.DelegatorAddr, delegation.ValidatorAddr))
}
//_____________________________________________________________________________________
// return a given amount of all the delegator unbonding-delegations
func (k Keeper) GetUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddress,
maxRetrieve uint16) (unbondingDelegations []types.UnbondingDelegation) {
unbondingDelegations = make([]types.UnbondingDelegation, maxRetrieve)
store := ctx.KVStore(k.storeKey)
delegatorPrefixKey := GetUBDsKey(delegator)
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey)
defer iterator.Close()
i := 0
for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() {
unbondingDelegation := types.MustUnmarshalUBD(k.cdc, iterator.Key(), iterator.Value())
unbondingDelegations[i] = unbondingDelegation
i++
}
return unbondingDelegations[:i] // trim if the array length < maxRetrieve
}
// return a unbonding delegation
func (k Keeper) GetUnbondingDelegation(ctx sdk.Context,
delAddr sdk.AccAddress, valAddr sdk.ValAddress) (ubd types.UnbondingDelegation, found bool) {
store := ctx.KVStore(k.storeKey)
key := GetUBDKey(delAddr, valAddr)
value := store.Get(key)
if value == nil {
return ubd, false
}
ubd = types.MustUnmarshalUBD(k.cdc, key, value)
return ubd, true
}
// return all unbonding delegations from a particular validator
func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sdk.ValAddress) (ubds []types.UnbondingDelegation) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, GetUBDsByValIndexKey(valAddr))
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
key := GetUBDKeyFromValIndexKey(iterator.Key())
value := store.Get(key)
ubd := types.MustUnmarshalUBD(k.cdc, key, value)
ubds = append(ubds, ubd)
}
return ubds
}
// iterate through all of the unbonding delegations
func (k Keeper) IterateUnbondingDelegations(ctx sdk.Context, fn func(index int64, ubd types.UnbondingDelegation) (stop bool)) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, UnbondingDelegationKey)
defer iterator.Close()
for i := int64(0); iterator.Valid(); iterator.Next() {
ubd := types.MustUnmarshalUBD(k.cdc, iterator.Key(), iterator.Value())
if stop := fn(i, ubd); stop {
break
}
i++
}
}
// set the unbonding delegation and associated index
func (k Keeper) SetUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) {
store := ctx.KVStore(k.storeKey)
bz := types.MustMarshalUBD(k.cdc, ubd)
key := GetUBDKey(ubd.DelegatorAddr, ubd.ValidatorAddr)
store.Set(key, bz)
store.Set(GetUBDByValIndexKey(ubd.DelegatorAddr, ubd.ValidatorAddr), []byte{}) // index, store empty bytes
}
// remove the unbonding delegation object and associated index
func (k Keeper) RemoveUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDelegation) {
store := ctx.KVStore(k.storeKey)
key := GetUBDKey(ubd.DelegatorAddr, ubd.ValidatorAddr)
store.Delete(key)
store.Delete(GetUBDByValIndexKey(ubd.DelegatorAddr, ubd.ValidatorAddr))
}
// gets a specific unbonding queue timeslice. A timeslice is a slice of DVPairs corresponding to unbonding delegations
// that expire at a certain time.
func (k Keeper) GetUnbondingQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvPairs []types.DVPair) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(GetUnbondingDelegationTimeKey(timestamp))
if bz == nil {
return []types.DVPair{}
}
k.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &dvPairs)
return dvPairs
}
// Sets a specific unbonding queue timeslice.
func (k Keeper) SetUnbondingQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []types.DVPair) {
store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshalBinaryLengthPrefixed(keys)
store.Set(GetUnbondingDelegationTimeKey(timestamp), bz)
}
// Insert an unbonding delegation to the appropriate timeslice in the unbonding queue
func (k Keeper) InsertUnbondingQueue(ctx sdk.Context, ubd types.UnbondingDelegation) {
timeSlice := k.GetUnbondingQueueTimeSlice(ctx, ubd.MinTime)
dvPair := types.DVPair{ubd.DelegatorAddr, ubd.ValidatorAddr}
if len(timeSlice) == 0 {
k.SetUnbondingQueueTimeSlice(ctx, ubd.MinTime, []types.DVPair{dvPair})
} else {
timeSlice = append(timeSlice, dvPair)
k.SetUnbondingQueueTimeSlice(ctx, ubd.MinTime, timeSlice)
}
}
// Returns all the unbonding queue timeslices from time 0 until endTime
func (k Keeper) UnbondingQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator {
store := ctx.KVStore(k.storeKey)
return store.Iterator(UnbondingQueueKey, sdk.InclusiveEndBytes(GetUnbondingDelegationTimeKey(endTime)))
}
// Returns a concatenated list of all the timeslices before currTime, and deletes the timeslices from the queue
func (k Keeper) DequeueAllMatureUnbondingQueue(ctx sdk.Context, currTime time.Time) (matureUnbonds []types.DVPair) {
store := ctx.KVStore(k.storeKey)
// gets an iterator for all timeslices from time 0 until the current Blockheader time
unbondingTimesliceIterator := k.UnbondingQueueIterator(ctx, ctx.BlockHeader().Time)
for ; unbondingTimesliceIterator.Valid(); unbondingTimesliceIterator.Next() {
timeslice := []types.DVPair{}
k.cdc.MustUnmarshalBinaryLengthPrefixed(unbondingTimesliceIterator.Value(), ×lice)
matureUnbonds = append(matureUnbonds, timeslice...)
store.Delete(unbondingTimesliceIterator.Key())
}
return matureUnbonds
}
//_____________________________________________________________________________________
// return a given amount of all the delegator redelegations
func (k Keeper) GetRedelegations(ctx sdk.Context, delegator sdk.AccAddress,
maxRetrieve uint16) (redelegations []types.Redelegation) {
redelegations = make([]types.Redelegation, maxRetrieve)
store := ctx.KVStore(k.storeKey)
delegatorPrefixKey := GetREDsKey(delegator)
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey)
defer iterator.Close()
i := 0
for ; iterator.Valid() && i < int(maxRetrieve); iterator.Next() {
redelegation := types.MustUnmarshalRED(k.cdc, iterator.Key(), iterator.Value())
redelegations[i] = redelegation
i++
}
return redelegations[:i] // trim if the array length < maxRetrieve
}
// return a redelegation
func (k Keeper) GetRedelegation(ctx sdk.Context,
delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) (red types.Redelegation, found bool) {
store := ctx.KVStore(k.storeKey)
key := GetREDKey(delAddr, valSrcAddr, valDstAddr)
value := store.Get(key)
if value == nil {
return red, false
}
red = types.MustUnmarshalRED(k.cdc, key, value)
return red, true
}
// return all redelegations from a particular validator
func (k Keeper) GetRedelegationsFromValidator(ctx sdk.Context, valAddr sdk.ValAddress) (reds []types.Redelegation) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, GetREDsFromValSrcIndexKey(valAddr))
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
key := GetREDKeyFromValSrcIndexKey(iterator.Key())
value := store.Get(key)
red := types.MustUnmarshalRED(k.cdc, key, value)
reds = append(reds, red)
}
return reds
}
// check if validator is receiving a redelegation
func (k Keeper) HasReceivingRedelegation(ctx sdk.Context,
delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool {
store := ctx.KVStore(k.storeKey)
prefix := GetREDsByDelToValDstIndexKey(delAddr, valDstAddr)
iterator := sdk.KVStorePrefixIterator(store, prefix)
defer iterator.Close()
found := false
if iterator.Valid() {
found = true
}
return found
}
// set a redelegation and associated index
func (k Keeper) SetRedelegation(ctx sdk.Context, red types.Redelegation) {
store := ctx.KVStore(k.storeKey)
bz := types.MustMarshalRED(k.cdc, red)
key := GetREDKey(red.DelegatorAddr, red.ValidatorSrcAddr, red.ValidatorDstAddr)
store.Set(key, bz)
store.Set(GetREDByValSrcIndexKey(red.DelegatorAddr, red.ValidatorSrcAddr, red.ValidatorDstAddr), []byte{})
store.Set(GetREDByValDstIndexKey(red.DelegatorAddr, red.ValidatorSrcAddr, red.ValidatorDstAddr), []byte{})
}
// iterate through all redelegations
func (k Keeper) IterateRedelegations(ctx sdk.Context, fn func(index int64, red types.Redelegation) (stop bool)) {
store := ctx.KVStore(k.storeKey)
iterator := sdk.KVStorePrefixIterator(store, RedelegationKey)
defer iterator.Close()
for i := int64(0); iterator.Valid(); iterator.Next() {
red := types.MustUnmarshalRED(k.cdc, iterator.Key(), iterator.Value())
if stop := fn(i, red); stop {
break
}
i++
}
}
// remove a redelegation object and associated index
func (k Keeper) RemoveRedelegation(ctx sdk.Context, red types.Redelegation) {
store := ctx.KVStore(k.storeKey)
redKey := GetREDKey(red.DelegatorAddr, red.ValidatorSrcAddr, red.ValidatorDstAddr)
store.Delete(redKey)
store.Delete(GetREDByValSrcIndexKey(red.DelegatorAddr, red.ValidatorSrcAddr, red.ValidatorDstAddr))
store.Delete(GetREDByValDstIndexKey(red.DelegatorAddr, red.ValidatorSrcAddr, red.ValidatorDstAddr))
}
// Gets a specific redelegation queue timeslice. A timeslice is a slice of DVVTriplets corresponding to redelegations
// that expire at a certain time.
func (k Keeper) GetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvvTriplets []types.DVVTriplet) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(GetRedelegationTimeKey(timestamp))
if bz == nil {
return []types.DVVTriplet{}
}
k.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &dvvTriplets)
return dvvTriplets
}
// Sets a specific redelegation queue timeslice.
func (k Keeper) SetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys []types.DVVTriplet) {
store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshalBinaryLengthPrefixed(keys)
store.Set(GetRedelegationTimeKey(timestamp), bz)
}
// Insert an redelegation delegation to the appropriate timeslice in the redelegation queue
func (k Keeper) InsertRedelegationQueue(ctx sdk.Context, red types.Redelegation) {
timeSlice := k.GetRedelegationQueueTimeSlice(ctx, red.MinTime)
dvvTriplet := types.DVVTriplet{red.DelegatorAddr, red.ValidatorSrcAddr, red.ValidatorDstAddr}
if len(timeSlice) == 0 {
k.SetRedelegationQueueTimeSlice(ctx, red.MinTime, []types.DVVTriplet{dvvTriplet})
} else {
timeSlice = append(timeSlice, dvvTriplet)
k.SetRedelegationQueueTimeSlice(ctx, red.MinTime, timeSlice)
}
}
// Returns all the redelegation queue timeslices from time 0 until endTime
func (k Keeper) RedelegationQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator {
store := ctx.KVStore(k.storeKey)
return store.Iterator(RedelegationQueueKey, sdk.InclusiveEndBytes(GetRedelegationTimeKey(endTime)))
}
// Returns a concatenated list of all the timeslices before currTime, and deletes the timeslices from the queue
func (k Keeper) DequeueAllMatureRedelegationQueue(ctx sdk.Context, currTime time.Time) (matureRedelegations []types.DVVTriplet) {
store := ctx.KVStore(k.storeKey)
// gets an iterator for all timeslices from time 0 until the current Blockheader time
redelegationTimesliceIterator := k.RedelegationQueueIterator(ctx, ctx.BlockHeader().Time)
for ; redelegationTimesliceIterator.Valid(); redelegationTimesliceIterator.Next() {
timeslice := []types.DVVTriplet{}
k.cdc.MustUnmarshalBinaryLengthPrefixed(redelegationTimesliceIterator.Value(), ×lice)
matureRedelegations = append(matureRedelegations, timeslice...)
store.Delete(redelegationTimesliceIterator.Key())
}
return matureRedelegations
}
//_____________________________________________________________________________________
// Perform a delegation, set/update everything necessary within the store.
func (k Keeper) Delegate(ctx sdk.Context, delAddr sdk.AccAddress, bondAmt sdk.Coin,
validator types.Validator, subtractAccount bool) (newShares sdk.Dec, err sdk.Error) {
// In some situations, the exchange rate becomes invalid, e.g. if
// validator loses all tokens due to slashing. In this case,
// make all future delegations invalid.
if validator.DelegatorShareExRate().IsZero() {
return sdk.ZeroDec(), types.ErrDelegatorShareExRateInvalid(k.Codespace())
}
// Get or create the delegator delegation
delegation, found := k.GetDelegation(ctx, delAddr, validator.OperatorAddr)
if !found {
delegation = types.Delegation{
DelegatorAddr: delAddr,
ValidatorAddr: validator.OperatorAddr,
Shares: sdk.ZeroDec(),
}
}
// call the appropriate hook if present
if found {
k.OnDelegationSharesModified(ctx, delAddr, validator.OperatorAddr)
} else {
k.OnDelegationCreated(ctx, delAddr, validator.OperatorAddr)
}
if subtractAccount {
// Account new shares, save
_, _, err = k.bankKeeper.SubtractCoins(ctx, delegation.DelegatorAddr, sdk.Coins{bondAmt})
if err != nil {
return
}
}
validator, newShares = k.AddValidatorTokensAndShares(ctx, validator, bondAmt.Amount)
// Update delegation
delegation.Shares = delegation.Shares.Add(newShares)
k.SetDelegation(ctx, delegation)
return newShares, nil
}
// unbond the the delegation return
func (k Keeper) unbond(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress,
shares sdk.Dec) (amount sdk.Dec, err sdk.Error) {
// check if delegation has any shares in it unbond
delegation, found := k.GetDelegation(ctx, delAddr, valAddr)
if !found {
err = types.ErrNoDelegatorForAddress(k.Codespace())
return
}
k.OnDelegationSharesModified(ctx, delAddr, valAddr)
// retrieve the amount to remove
if delegation.Shares.LT(shares) {
err = types.ErrNotEnoughDelegationShares(k.Codespace(), delegation.Shares.String())
return
}
// get validator
validator, found := k.GetValidator(ctx, valAddr)
if !found {
err = types.ErrNoValidatorFound(k.Codespace())
return
}
// subtract shares from delegator
delegation.Shares = delegation.Shares.Sub(shares)
// remove the delegation
if delegation.Shares.IsZero() {
// if the delegation is the operator of the validator then
// trigger a jail validator
if bytes.Equal(delegation.DelegatorAddr, validator.OperatorAddr) && !validator.Jailed {
k.jailValidator(ctx, validator)
validator = k.mustGetValidator(ctx, validator.OperatorAddr)
}
k.RemoveDelegation(ctx, delegation)
} else {
// update the delegation
k.SetDelegation(ctx, delegation)
}
// remove the coins from the validator
validator, amount = k.RemoveValidatorTokensAndShares(ctx, validator, shares)
if validator.DelegatorShares.IsZero() && validator.Status == sdk.Unbonded {
// if not unbonded, we must instead remove validator in EndBlocker once it finishes its unbonding period
k.RemoveValidator(ctx, validator.OperatorAddr)
}
return amount, nil
}
//______________________________________________________________________________________________________
// get info for begin functions: MinTime and CreationHeight
func (k Keeper) getBeginInfo(ctx sdk.Context, valSrcAddr sdk.ValAddress) (
minTime time.Time, height int64, completeNow bool) {
validator, found := k.GetValidator(ctx, valSrcAddr)
switch {
case !found || validator.Status == sdk.Bonded:
// the longest wait - just unbonding period from now
minTime = ctx.BlockHeader().Time.Add(k.UnbondingTime(ctx))
height = ctx.BlockHeight()
return minTime, height, false
case validator.Status == sdk.Unbonded:
return minTime, height, true
case validator.Status == sdk.Unbonding:
minTime = validator.UnbondingMinTime
height = validator.UnbondingHeight
return minTime, height, false
default:
panic("unknown validator status")
}
}
// begin unbonding an unbonding record
func (k Keeper) BeginUnbonding(ctx sdk.Context,
delAddr sdk.AccAddress, valAddr sdk.ValAddress, sharesAmount sdk.Dec) (types.UnbondingDelegation, sdk.Error) {
// TODO quick fix, instead we should use an index, see https://github.com/cosmos/cosmos-sdk/issues/1402
_, found := k.GetUnbondingDelegation(ctx, delAddr, valAddr)
if found {
return types.UnbondingDelegation{}, types.ErrExistingUnbondingDelegation(k.Codespace())
}
// create the unbonding delegation
minTime, height, completeNow := k.getBeginInfo(ctx, valAddr)
returnAmount, err := k.unbond(ctx, delAddr, valAddr, sharesAmount)
if err != nil {
return types.UnbondingDelegation{}, err
}
rounded := returnAmount.TruncateInt()
balance := sdk.NewCoin(k.BondDenom(ctx), rounded)
change := returnAmount.Sub(sdk.NewDecFromInt(rounded))
// for now, change is just burned
pool := k.GetPool(ctx)
pool.LooseTokens = pool.LooseTokens.Sub(change)
k.SetPool(ctx, pool)
// no need to create the ubd object just complete now
if completeNow {
_, _, err := k.bankKeeper.AddCoins(ctx, delAddr, sdk.Coins{balance})
if err != nil {
return types.UnbondingDelegation{}, err
}
return types.UnbondingDelegation{MinTime: minTime}, nil
}
ubd := types.UnbondingDelegation{
DelegatorAddr: delAddr,
ValidatorAddr: valAddr,
CreationHeight: height,
MinTime: minTime,
Balance: balance,
InitialBalance: balance,
}
k.SetUnbondingDelegation(ctx, ubd)
k.InsertUnbondingQueue(ctx, ubd)
return ubd, nil
}
// complete unbonding an unbonding record
// CONTRACT: Expects unbonding passed in has finished the unbonding period
func (k Keeper) CompleteUnbonding(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) sdk.Error {
ubd, found := k.GetUnbondingDelegation(ctx, delAddr, valAddr)
if !found {
return types.ErrNoUnbondingDelegation(k.Codespace())
}
_, _, err := k.bankKeeper.AddCoins(ctx, ubd.DelegatorAddr, sdk.Coins{ubd.Balance})
if err != nil {
return err
}
k.RemoveUnbondingDelegation(ctx, ubd)
return nil
}
// begin unbonding / redelegation; create a redelegation record
func (k Keeper) BeginRedelegation(ctx sdk.Context, delAddr sdk.AccAddress,
valSrcAddr, valDstAddr sdk.ValAddress, sharesAmount sdk.Dec) (types.Redelegation, sdk.Error) {
if bytes.Equal(valSrcAddr, valDstAddr) {
return types.Redelegation{}, types.ErrSelfRedelegation(k.Codespace())
}
// check if there is already a redelgation in progress from src to dst
// TODO quick fix, instead we should use an index, see https://github.com/cosmos/cosmos-sdk/issues/1402
_, found := k.GetRedelegation(ctx, delAddr, valSrcAddr, valDstAddr)
if found {
return types.Redelegation{}, types.ErrConflictingRedelegation(k.Codespace())
}
// check if this is a transitive redelegation
if k.HasReceivingRedelegation(ctx, delAddr, valSrcAddr) {
return types.Redelegation{}, types.ErrTransitiveRedelegation(k.Codespace())
}
returnAmount, err := k.unbond(ctx, delAddr, valSrcAddr, sharesAmount)
if err != nil {
return types.Redelegation{}, err
}
rounded := returnAmount.TruncateInt()
if rounded.IsZero() { //TODO design consideration
return types.Redelegation{}, types.ErrVerySmallRedelegation(k.Codespace())
}
returnCoin := sdk.NewCoin(k.BondDenom(ctx), rounded)
change := returnAmount.Sub(sdk.NewDecFromInt(rounded))
// for now, change is just burned
pool := k.GetPool(ctx)
pool.LooseTokens = pool.LooseTokens.Sub(change)
k.SetPool(ctx, pool)
dstValidator, found := k.GetValidator(ctx, valDstAddr)
if !found {
return types.Redelegation{}, types.ErrBadRedelegationDst(k.Codespace())
}
sharesCreated, err := k.Delegate(ctx, delAddr, returnCoin, dstValidator, false)
if err != nil {
return types.Redelegation{}, err
}
// create the unbonding delegation
minTime, height, completeNow := k.getBeginInfo(ctx, valSrcAddr)
if completeNow { // no need to create the redelegation object
return types.Redelegation{MinTime: minTime}, nil
}
red := types.Redelegation{
DelegatorAddr: delAddr,
ValidatorSrcAddr: valSrcAddr,
ValidatorDstAddr: valDstAddr,
CreationHeight: height,
MinTime: minTime,
SharesDst: sharesCreated,
SharesSrc: sharesAmount,
Balance: returnCoin,
InitialBalance: returnCoin,
}
k.SetRedelegation(ctx, red)
k.InsertRedelegationQueue(ctx, red)
return red, nil
}
// complete unbonding an ongoing redelegation
func (k Keeper) CompleteRedelegation(ctx sdk.Context, delAddr sdk.AccAddress,
valSrcAddr, valDstAddr sdk.ValAddress) sdk.Error {
red, found := k.GetRedelegation(ctx, delAddr, valSrcAddr, valDstAddr)
if !found {
return types.ErrNoRedelegation(k.Codespace())
}
// ensure that enough time has passed
ctxTime := ctx.BlockHeader().Time
if red.MinTime.After(ctxTime) {
return types.ErrNotMature(k.Codespace(), "redelegation", "unit-time", red.MinTime, ctxTime)
}
k.RemoveRedelegation(ctx, red)
return nil
}