/
transactions.go
751 lines (652 loc) · 21.3 KB
/
transactions.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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
package staking
import (
"fmt"
"github.com/oasisprotocol/oasis-core/go/common/errors"
"github.com/oasisprotocol/oasis-core/go/common/quantity"
"github.com/oasisprotocol/oasis-core/go/consensus/tendermint/api"
stakingState "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/apps/staking/state"
staking "github.com/oasisprotocol/oasis-core/go/staking/api"
)
func isTransferPermitted(params *staking.ConsensusParameters, fromAddr staking.Address) (permitted bool) {
permitted = true
if params.DisableTransfers {
permitted = false
if params.UndisableTransfersFrom != nil && params.UndisableTransfersFrom[fromAddr] {
permitted = true
}
}
return
}
func (app *stakingApplication) transfer(ctx *api.Context, state *stakingState.MutableState, xfer *staking.Transfer) (*staking.TransferResult, error) {
if ctx.IsCheckOnly() {
return nil, nil
}
// Charge gas for this transaction.
params, err := state.ConsensusParameters(ctx)
if err != nil {
return nil, fmt.Errorf("failed to fetch consensus parameters: %w", err)
}
if err = ctx.Gas().UseGas(1, staking.GasOpTransfer, params.GasCosts); err != nil {
return nil, err
}
// Return early for simulation as we only need gas accounting.
if ctx.IsSimulation() {
return nil, nil
}
// Check if sender provided at least a minimum amount.
if xfer.Amount.Cmp(¶ms.MinTransferAmount) < 0 {
return nil, staking.ErrUnderMinTransferAmount
}
fromAddr := ctx.CallerAddress()
if fromAddr.IsReserved() || !isTransferPermitted(params, fromAddr) {
return nil, staking.ErrForbidden
}
from, err := state.Account(ctx, fromAddr)
if err != nil {
return nil, fmt.Errorf("failed to fetch account: %w", err)
}
if fromAddr.Equal(xfer.To) {
// Handle transfer to self as just a balance check.
if from.General.Balance.Cmp(&xfer.Amount) < 0 {
err = staking.ErrInsufficientBalance
ctx.Logger().Error("Transfer: self-transfer greater than balance",
"err", err,
"from", fromAddr,
"to", xfer.To,
"amount", xfer.Amount,
)
return nil, err
}
} else {
// Source and destination MUST be separate accounts with how
// quantity.Move is implemented.
var to *staking.Account
to, err = state.Account(ctx, xfer.To)
if err != nil {
return nil, fmt.Errorf("failed to fetch account: %w", err)
}
if err = quantity.Move(&to.General.Balance, &from.General.Balance, &xfer.Amount); err != nil {
ctx.Logger().Error("Transfer: failed to move balance",
"err", err,
"from", fromAddr,
"to", xfer.To,
"amount", xfer.Amount,
)
return nil, err
}
// Check against minimum balance.
if from.General.Balance.Cmp(¶ms.MinTransactBalance) < 0 {
ctx.Logger().Error("after transfer source account balance too low",
"account_addr", fromAddr,
"account_balance", from.General.Balance,
"min_transact_balance", params.MinTransactBalance,
)
return nil, errors.WithContext(staking.ErrBalanceTooLow, "source account")
}
if to.General.Balance.Cmp(¶ms.MinTransactBalance) < 0 {
ctx.Logger().Error("after transfer dest account balance too low",
"account_addr", xfer.To,
"account_balance", to.General.Balance,
"min_transact_balance", params.MinTransactBalance,
)
return nil, errors.WithContext(staking.ErrBalanceTooLow, "dest account")
}
if err = state.SetAccount(ctx, xfer.To, to); err != nil {
return nil, fmt.Errorf("failed to set account: %w", err)
}
}
if err = state.SetAccount(ctx, fromAddr, from); err != nil {
return nil, fmt.Errorf("failed to fetch account: %w", err)
}
ctx.Logger().Debug("Transfer: executed transfer",
"from", fromAddr,
"to", xfer.To,
"amount", xfer.Amount,
)
ctx.EmitEvent(api.NewEventBuilder(app.Name()).TypedAttribute(&staking.TransferEvent{
From: fromAddr,
To: xfer.To,
Amount: xfer.Amount,
}))
return &staking.TransferResult{
From: fromAddr,
To: xfer.To,
Amount: xfer.Amount,
}, nil
}
func (app *stakingApplication) burn(ctx *api.Context, state *stakingState.MutableState, burn *staking.Burn) error {
if ctx.IsCheckOnly() {
return nil
}
// Charge gas for this transaction.
params, err := state.ConsensusParameters(ctx)
if err != nil {
return fmt.Errorf("failed to fetch consensus parameters: %w", err)
}
if err = ctx.Gas().UseGas(1, staking.GasOpBurn, params.GasCosts); err != nil {
return err
}
// Return early for simulation as we only need gas accounting.
if ctx.IsSimulation() {
return nil
}
// Check if sender provided at least a minimum amount.
if burn.Amount.Cmp(¶ms.MinTransferAmount) < 0 {
return staking.ErrUnderMinTransferAmount
}
fromAddr := ctx.CallerAddress()
if fromAddr.IsReserved() {
return staking.ErrForbidden
}
from, err := state.Account(ctx, fromAddr)
if err != nil {
return fmt.Errorf("failed to fetch account: %w", err)
}
if err = from.General.Balance.Sub(&burn.Amount); err != nil {
ctx.Logger().Error("Burn: failed to burn stake",
"err", err,
"from", fromAddr,
"amount", burn.Amount,
)
return err
}
// Check against minimum balance.
if from.General.Balance.Cmp(¶ms.MinTransactBalance) < 0 {
ctx.Logger().Error("after burn account balance too low",
"account_addr", fromAddr,
"account_balance", from.General.Balance,
"min_transact_balance", params.MinTransactBalance,
)
return staking.ErrBalanceTooLow
}
totalSupply, err := state.TotalSupply(ctx)
if err != nil {
return fmt.Errorf("failed to fetch total supply: %w", err)
}
_ = totalSupply.Sub(&burn.Amount)
if err = state.SetAccount(ctx, fromAddr, from); err != nil {
return fmt.Errorf("failed to set account: %w", err)
}
if err = state.SetTotalSupply(ctx, totalSupply); err != nil {
return fmt.Errorf("failed to set total supply: %w", err)
}
ctx.Logger().Debug("Burn: burnt stake",
"from", fromAddr,
"amount", burn.Amount,
)
ctx.EmitEvent(api.NewEventBuilder(app.Name()).TypedAttribute(&staking.BurnEvent{
Owner: fromAddr,
Amount: burn.Amount,
}))
return nil
}
func (app *stakingApplication) addEscrow(ctx *api.Context, state *stakingState.MutableState, escrow *staking.Escrow) (*staking.AddEscrowResult, error) {
if ctx.IsCheckOnly() {
return nil, nil
}
// Charge gas for this transaction.
params, err := state.ConsensusParameters(ctx)
if err != nil {
return nil, fmt.Errorf("failed to fetch consensus parameters: %w", err)
}
if err = ctx.Gas().UseGas(1, staking.GasOpAddEscrow, params.GasCosts); err != nil {
return nil, err
}
// Check if escrow messages are allowed.
if ctx.IsMessageExecution() && !params.AllowEscrowMessages {
return nil, staking.ErrForbidden
}
// Return early for simulation as we only need gas accounting.
if ctx.IsSimulation() {
return nil, nil
}
// Check if sender provided at least a minimum amount of stake.
if escrow.Amount.Cmp(¶ms.MinDelegationAmount) < 0 {
return nil, staking.ErrUnderMinDelegationAmount
}
fromAddr := ctx.CallerAddress()
if fromAddr.IsReserved() {
return nil, staking.ErrForbidden
}
from, err := state.Account(ctx, fromAddr)
if err != nil {
return nil, fmt.Errorf("failed to fetch account: %w", err)
}
// Fetch escrow account.
//
// NOTE: Could be the same account, so make sure to not have two duplicate
// copies of it and overwrite it later.
var to *staking.Account
if fromAddr.Equal(escrow.Account) {
to = from
} else {
if params.DisableDelegation {
return nil, staking.ErrForbidden
}
to, err = state.Account(ctx, escrow.Account)
if err != nil {
return nil, fmt.Errorf("failed to fetch account: %w", err)
}
}
// Fetch delegation.
delegation, err := state.Delegation(ctx, fromAddr, escrow.Account)
if err != nil {
return nil, fmt.Errorf("failed to fetch delegation: %w", err)
}
obtainedShares, err := to.Escrow.Active.Deposit(&delegation.Shares, &from.General.Balance, &escrow.Amount)
if err != nil {
ctx.Logger().Error("AddEscrow: failed to escrow stake",
"err", err,
"from", fromAddr,
"to", escrow.Account,
"amount", escrow.Amount,
)
return nil, err
}
// Check against minimum balance.
if from.General.Balance.Cmp(¶ms.MinTransactBalance) < 0 {
ctx.Logger().Error("after add escrow account balance too low",
"account_addr", fromAddr,
"account_balance", from.General.Balance,
"min_transact_balance", params.MinTransactBalance,
)
return nil, staking.ErrBalanceTooLow
}
// Commit accounts.
if err = state.SetAccount(ctx, fromAddr, from); err != nil {
return nil, fmt.Errorf("failed to set account: %w", err)
}
if !fromAddr.Equal(escrow.Account) {
if err = state.SetAccount(ctx, escrow.Account, to); err != nil {
return nil, fmt.Errorf("failed to set account: %w", err)
}
}
// Commit delegation descriptor.
if err = state.SetDelegation(ctx, fromAddr, escrow.Account, delegation); err != nil {
return nil, fmt.Errorf("failed to set delegation: %w", err)
}
ctx.Logger().Debug("AddEscrow: escrowed stake",
"from", fromAddr,
"to", escrow.Account,
"amount", escrow.Amount,
"obtained_shares", obtainedShares,
)
ctx.EmitEvent(api.NewEventBuilder(app.Name()).TypedAttribute(&staking.AddEscrowEvent{
Owner: fromAddr,
Escrow: escrow.Account,
Amount: escrow.Amount,
NewShares: *obtainedShares,
}))
return &staking.AddEscrowResult{
Owner: fromAddr,
Escrow: escrow.Account,
Amount: escrow.Amount,
NewShares: *obtainedShares,
}, nil
}
func (app *stakingApplication) reclaimEscrow(ctx *api.Context, state *stakingState.MutableState, reclaim *staking.ReclaimEscrow) (*staking.ReclaimEscrowResult, error) {
// No sense if there is nothing to reclaim.
if reclaim.Shares.IsZero() {
return nil, staking.ErrInvalidArgument
}
if ctx.IsCheckOnly() {
return nil, nil
}
// Charge gas for this transaction.
params, err := state.ConsensusParameters(ctx)
if err != nil {
return nil, fmt.Errorf("failed to fetch consensus parameters: %w", err)
}
if err = ctx.Gas().UseGas(1, staking.GasOpReclaimEscrow, params.GasCosts); err != nil {
return nil, err
}
// Check if escrow messages are allowed.
if ctx.IsMessageExecution() && !params.AllowEscrowMessages {
return nil, staking.ErrForbidden
}
// Return early for simulation as we only need gas accounting.
if ctx.IsSimulation() {
return nil, nil
}
toAddr := ctx.CallerAddress()
if toAddr.IsReserved() {
return nil, staking.ErrForbidden
}
to, err := state.Account(ctx, toAddr)
if err != nil {
return nil, fmt.Errorf("failed to fetch account: %w", err)
}
// Fetch escrow account.
//
// NOTE: Could be the same account, so make sure to not have two duplicate
// copies of it and overwrite it later.
var from *staking.Account
if toAddr.Equal(reclaim.Account) {
from = to
} else {
if params.DisableDelegation {
return nil, staking.ErrForbidden
}
from, err = state.Account(ctx, reclaim.Account)
if err != nil {
return nil, fmt.Errorf("failed to fetch account: %w", err)
}
}
// Fetch delegation.
delegation, err := state.Delegation(ctx, toAddr, reclaim.Account)
if err != nil {
return nil, fmt.Errorf("failed to fetch delegation: %w", err)
}
// Fetch debonding interval and current epoch.
debondingInterval, err := state.DebondingInterval(ctx)
if err != nil {
ctx.Logger().Error("ReclaimEscrow: failed to query debonding interval",
"err", err,
)
return nil, err
}
epoch, err := app.state.GetEpoch(ctx, ctx.BlockHeight()+1)
if err != nil {
return nil, err
}
deb := staking.DebondingDelegation{
DebondEndTime: epoch + debondingInterval,
}
var baseUnits quantity.Quantity
if err = from.Escrow.Active.Withdraw(&baseUnits, &delegation.Shares, &reclaim.Shares); err != nil {
ctx.Logger().Error("ReclaimEscrow: failed to redeem escrow shares",
"err", err,
"to", toAddr,
"from", reclaim.Account,
"shares", reclaim.Shares,
)
return nil, err
}
stakeAmount := baseUnits.Clone()
var debondingShares *quantity.Quantity
if debondingShares, err = from.Escrow.Debonding.Deposit(&deb.Shares, &baseUnits, stakeAmount); err != nil {
ctx.Logger().Error("ReclaimEscrow: failed to debond shares",
"err", err,
"to", toAddr,
"from", reclaim.Account,
"shares", reclaim.Shares,
"base_units", stakeAmount,
)
return nil, err
}
if !baseUnits.IsZero() {
ctx.Logger().Error("ReclaimEscrow: inconsistency in transferring stake from active escrow to debonding",
"remaining_base_units", baseUnits,
)
return nil, staking.ErrInvalidArgument
}
// Include the end time epoch as the disambiguator. If a debonding delegation for the same account
// and end time already exists, the delegations will be merged.
if err = state.SetDebondingDelegation(ctx, toAddr, reclaim.Account, deb.DebondEndTime, &deb); err != nil {
return nil, fmt.Errorf("failed to set debonding delegation: %w", err)
}
if err = state.SetDelegation(ctx, toAddr, reclaim.Account, delegation); err != nil {
return nil, fmt.Errorf("failed to set delegation: %w", err)
}
if err = state.SetAccount(ctx, toAddr, to); err != nil {
return nil, fmt.Errorf("failed to set account: %w", err)
}
if !toAddr.Equal(reclaim.Account) {
if err = state.SetAccount(ctx, reclaim.Account, from); err != nil {
return nil, fmt.Errorf("failed to set account: %w", err)
}
}
ctx.Logger().Debug("ReclaimEscrow: started debonding stake",
"from", reclaim.Account,
"to", toAddr,
"base_units", stakeAmount,
"active_shares", reclaim.Shares,
"debonding_shares", debondingShares,
"debond_end_time", deb.DebondEndTime,
)
ctx.EmitEvent(api.NewEventBuilder(app.Name()).TypedAttribute(&staking.DebondingStartEscrowEvent{
Owner: toAddr,
Escrow: reclaim.Account,
Amount: *stakeAmount,
ActiveShares: reclaim.Shares,
DebondingShares: *debondingShares,
DebondEndTime: deb.DebondEndTime,
}))
return &staking.ReclaimEscrowResult{
Owner: toAddr,
Escrow: reclaim.Account,
Amount: *stakeAmount,
DebondingShares: *debondingShares,
RemainingShares: delegation.Shares,
DebondEndTime: deb.DebondEndTime,
}, nil
}
func (app *stakingApplication) amendCommissionSchedule(
ctx *api.Context,
state *stakingState.MutableState,
amendCommissionSchedule *staking.AmendCommissionSchedule,
) error {
if ctx.IsCheckOnly() {
return nil
}
// Charge gas for this transaction.
params, err := state.ConsensusParameters(ctx)
if err != nil {
return fmt.Errorf("failed to fetch consensus parameters: %w", err)
}
if err = ctx.Gas().UseGas(1, staking.GasOpAmendCommissionSchedule, params.GasCosts); err != nil {
return err
}
// Return early for simulation as we only need gas accounting.
if ctx.IsSimulation() {
return nil
}
epoch, err := app.state.GetEpoch(ctx, ctx.BlockHeight()+1)
if err != nil {
return err
}
fromAddr := ctx.CallerAddress()
if fromAddr.IsReserved() {
return staking.ErrForbidden
}
from, err := state.Account(ctx, fromAddr)
if err != nil {
return fmt.Errorf("failed to fetch account: %w", err)
}
if err = from.Escrow.CommissionSchedule.AmendAndPruneAndValidate(&amendCommissionSchedule.Amendment, ¶ms.CommissionScheduleRules, epoch); err != nil {
ctx.Logger().Error("AmendCommissionSchedule: amendment not acceptable",
"err", err,
"from", fromAddr,
)
return err
}
if err = state.SetAccount(ctx, fromAddr, from); err != nil {
return fmt.Errorf("failed to set account: %w", err)
}
return nil
}
func (app *stakingApplication) allow(
ctx *api.Context,
state *stakingState.MutableState,
allow *staking.Allow,
) error {
if ctx.IsCheckOnly() {
return nil
}
// Charge gas for this transaction.
params, err := state.ConsensusParameters(ctx)
if err != nil {
return fmt.Errorf("failed to fetch consensus parameters: %w", err)
}
if err = ctx.Gas().UseGas(1, staking.GasOpAllow, params.GasCosts); err != nil {
return err
}
// Return early for simulation as we only need gas accounting.
if ctx.IsSimulation() {
return nil
}
// Allowances are disabled in case either max allowances is zero or if transfers are disabled.
if params.DisableTransfers || params.MaxAllowances == 0 {
return staking.ErrForbidden
}
// Validate addresses -- if either is reserved or both are equal, the method should fail.
addr := ctx.CallerAddress()
if addr.IsReserved() || allow.Beneficiary.IsReserved() {
return staking.ErrForbidden
}
if addr.Equal(allow.Beneficiary) {
return staking.ErrInvalidArgument
}
acct, err := state.Account(ctx, addr)
if err != nil {
return fmt.Errorf("failed to fetch account: %w", err)
}
if acct.General.Allowances == nil {
acct.General.Allowances = make(map[staking.Address]quantity.Quantity)
}
allowance := acct.General.Allowances[allow.Beneficiary]
var amountChange *quantity.Quantity
switch allow.Negative {
case false:
// Add.
if err = allowance.Add(&allow.AmountChange); err != nil {
return fmt.Errorf("failed to add allowance: %w", err)
}
amountChange = allow.AmountChange.Clone()
case true:
// Subtract.
if amountChange, err = allowance.SubUpTo(&allow.AmountChange); err != nil {
return fmt.Errorf("failed to subtract allowance: %w", err)
}
}
if allowance.IsZero() {
// In case the new allowance is equal to zero, remove it.
delete(acct.General.Allowances, allow.Beneficiary)
} else {
// Otherwise update the allowance.
acct.General.Allowances[allow.Beneficiary] = allowance
}
// If updating allowances would go past the maximum number of allowances, fail.
if uint32(len(acct.General.Allowances)) > params.MaxAllowances {
return staking.ErrTooManyAllowances
}
if err = state.SetAccount(ctx, addr, acct); err != nil {
return fmt.Errorf("failed to set account: %w", err)
}
ctx.EmitEvent(api.NewEventBuilder(app.Name()).TypedAttribute(&staking.AllowanceChangeEvent{
Owner: addr,
Beneficiary: allow.Beneficiary,
Allowance: allowance,
Negative: allow.Negative,
AmountChange: *amountChange,
}))
return nil
}
func (app *stakingApplication) withdraw(
ctx *api.Context,
state *stakingState.MutableState,
withdraw *staking.Withdraw,
) (*staking.WithdrawResult, error) {
if ctx.IsCheckOnly() {
return nil, nil
}
// Charge gas for this transaction.
params, err := state.ConsensusParameters(ctx)
if err != nil {
return nil, fmt.Errorf("failed to fetch consensus parameters: %w", err)
}
if err = ctx.Gas().UseGas(1, staking.GasOpWithdraw, params.GasCosts); err != nil {
return nil, err
}
// Return early for simulation as we only need gas accounting.
if ctx.IsSimulation() {
return nil, nil
}
// Check if sender provided at least a minimum amount.
if withdraw.Amount.Cmp(¶ms.MinTransferAmount) < 0 {
return nil, staking.ErrUnderMinTransferAmount
}
// Allowances are disabled in case either max allowances is zero or if transfers are disabled.
if params.DisableTransfers || params.MaxAllowances == 0 {
return nil, staking.ErrForbidden
}
// Validate addresses -- if either is reserved or both are equal, the method should fail.
toAddr := ctx.CallerAddress()
if toAddr.IsReserved() || withdraw.From.IsReserved() {
return nil, staking.ErrForbidden
}
if toAddr.Equal(withdraw.From) {
return nil, staking.ErrInvalidArgument
}
from, err := state.Account(ctx, withdraw.From)
if err != nil {
return nil, fmt.Errorf("failed to fetch account: %w", err)
}
var (
allowance quantity.Quantity
ok bool
)
if allowance, ok = from.General.Allowances[toAddr]; !ok {
// Fail early in case there is no allowance configured.
return nil, staking.ErrForbidden
}
if err = allowance.Sub(&withdraw.Amount); err != nil {
return nil, staking.ErrForbidden
}
if allowance.IsZero() {
// In case the new allowance is equal to zero, remove it.
delete(from.General.Allowances, toAddr)
} else {
// Otherwise update the allowance.
from.General.Allowances[toAddr] = allowance
}
// NOTE: Accounts cannot be the same as we fail above if this were the case.
to, err := state.Account(ctx, toAddr)
if err != nil {
return nil, fmt.Errorf("failed to fetch account: %w", err)
}
if err = quantity.Move(&to.General.Balance, &from.General.Balance, &withdraw.Amount); err != nil {
return nil, staking.ErrInsufficientBalance
}
// Check against minimum balance.
if from.General.Balance.Cmp(¶ms.MinTransactBalance) < 0 {
ctx.Logger().Error("after withdraw source account balance too low",
"account_addr", withdraw.From,
"account_balance", from.General.Balance,
"min_transact_balance", params.MinTransactBalance,
)
return nil, errors.WithContext(staking.ErrBalanceTooLow, "source account")
}
if to.General.Balance.Cmp(¶ms.MinTransactBalance) < 0 {
ctx.Logger().Error("after withdraw dest account balance too low",
"account_addr", toAddr,
"account_balance", to.General.Balance,
"min_transact_balance", params.MinTransactBalance,
)
return nil, errors.WithContext(staking.ErrBalanceTooLow, "dest account")
}
if err = state.SetAccount(ctx, toAddr, to); err != nil {
return nil, fmt.Errorf("failed to set account: %w", err)
}
if err = state.SetAccount(ctx, withdraw.From, from); err != nil {
return nil, fmt.Errorf("failed to set account: %w", err)
}
ctx.EmitEvent(api.NewEventBuilder(app.Name()).TypedAttribute(&staking.TransferEvent{
From: withdraw.From,
To: toAddr,
Amount: withdraw.Amount,
}))
ctx.EmitEvent(api.NewEventBuilder(app.Name()).TypedAttribute(&staking.AllowanceChangeEvent{
Owner: withdraw.From,
Beneficiary: toAddr,
Allowance: allowance,
Negative: true,
AmountChange: withdraw.Amount,
}))
return &staking.WithdrawResult{
Owner: withdraw.From,
Beneficiary: toAddr,
Allowance: allowance,
AmountChange: withdraw.Amount,
}, nil
}