forked from decred/dcrdex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrade.go
2472 lines (2249 loc) · 92 KB
/
trade.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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This code is available on the terms of the project LICENSE.md file,
// also available online at https://blueoakcouncil.org/license/1.0.0.
package core
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"math"
"strings"
"sync"
"sync/atomic"
"time"
"decred.org/dcrdex/client/asset"
"decred.org/dcrdex/client/db"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/calc"
"decred.org/dcrdex/dex/encode"
"decred.org/dcrdex/dex/msgjson"
"decred.org/dcrdex/dex/order"
"decred.org/dcrdex/dex/wait"
)
const confCheckTimeout = 2 * time.Second
// ExpirationErr indicates that the wait.TickerQueue has expired a waiter, e.g.
// a reported coin was not found before the set expiration time.
type ExpirationErr string
// Error satisfies the error interface for ExpirationErr.
func (err ExpirationErr) Error() string { return string(err) }
// Ensure matchTracker satisfies the Stringer interface.
var _ (fmt.Stringer) = (*matchTracker)(nil)
// A matchTracker is used to negotiate a match.
type matchTracker struct {
db.MetaMatch
// swapErr is an error set when we have given up hope on broadcasting a swap
// tx for a match. This can happen if 1) the swap has been attempted
// (repeatedly), but could not be successfully broadcast before the
// broadcast timeout, or 2) a match data was found to be in a nonsensical
// state during startup.
swapErr error
// tickGovernor can be set non-nil to prevent swaps or redeems from
// being attempted for a match. Typically, the *Timer comes from an
// AfterFunc that itself nils the tickGovernor.
tickGovernor *time.Timer
// swapErrCount counts the swap attempts. It is used in recovery.
swapErrCount int
// redeemErrCount counts the redeem attempts. It is used in recovery.
redeemErrCount int
// suspectSwap is a flag to indicate that there was a problem encountered
// trying to send a swap contract for this match. If suspectSwap is true,
// the match will not be grouped when attempting future swaps.
suspectSwap bool
// suspectRedeem is a flag to indicate that there was a problem encountered
// trying to redeem this match. If suspectRedeem is true, the match will not
// be grouped when attempting future redemptions.
suspectRedeem bool
// sendingInitAsync indicates if this match's init request is being sent to
// the server and awaiting a response. No attempts will be made to send
// another init request for this match while one is already active.
sendingInitAsync uint32 // atomic
// sendingRedeemAsync indicates if this match's redeem request is being sent
// to the server and awaiting a response. No attempts will be made to send
// another redeem request for this match while one is already active.
sendingRedeemAsync uint32 // atomic
// refundErr will be set to true if we attempt a refund and get a
// CoinNotFoundError, indicating there is nothing to refund. Prevents
// retries.
refundErr error
prefix *order.Prefix
trade *order.Trade
counterSwap *asset.AuditInfo
// cancelRedemptionSearch should be set when taker starts searching for
// maker's redemption. Required to cancel a find redemption attempt if
// taker successfully executes a refund.
cancelRedemptionSearch context.CancelFunc
// The following fields facilitate useful logging, while not being spammy.
// counterConfirms records the last known confirms of the counterparty swap.
// This is set in isSwappable for taker, isRedeemable for maker. -1 means
// the confirms have not yet been checked (or logged).
counterConfirms int64
swapConfirms int64
// lastExpireDur is the most recently logged time until expiry of the
// party's own contract. This may be negative if expiry has passed, but it
// is not yet refundable due to other consensus rules. This is set in
// isRefundable. Initialize this to a very large value to guarantee that it
// will be logged on the first check or when 0.
lastExpireDur time.Duration
// checkServerRevoke is set to make sure that a taker will not prematurely
// send an initialization until it is confirmed with the server that the
// match is not revoked.
checkServerRevoke bool
}
// matchTime returns the match's match time as a time.Time.
func (m *matchTracker) matchTime() time.Time {
return encode.UnixTimeMilli(int64(m.MetaData.Proof.Auth.MatchStamp)).UTC()
}
// trackedCancel is information necessary to track a cancel order. A
// trackedCancel is always associated with a trackedTrade.
type trackedCancel struct {
order.CancelOrder
preImg order.Preimage
csum dex.Bytes // the commitment checksum provided in the preimage request
matches struct {
maker *msgjson.Match
taker *msgjson.Match
}
}
// trackedTrade is an order (issued by this client), its matches, and its cancel
// order, if applicable. The trackedTrade has methods for handling requests
// from the DEX to progress match negotiation.
type trackedTrade struct {
// redeemFeeSuggestion is cached fee suggestion for redemption. We can't
// request a fee suggestion at redeem time because it would require making
// the full redemption routine async (TODO?). This fee suggestion is
// intentionally not stored as part of the db.OrderMetaData, and should
// be repopulated if the client is restarted.
// Used with atomic. Leave redeemFeeSuggestion as the first field in
// trackedTrade.
redeemFeeSuggestion uint64
order.Order
// mtx protects all read-write fields of the trackedTrade and the
// matchTrackers in the matches map.
mtx sync.RWMutex
metaData *db.OrderMetaData
dc *dexConnection
db db.DB
latencyQ *wait.TickerQueue
wallets *walletSet
preImg order.Preimage
csum dex.Bytes // the commitment checksum provided in the preimage request
mktID string
coins map[string]asset.Coin
coinsLocked bool
lockTimeTaker time.Duration
lockTimeMaker time.Duration
change asset.Coin
changeLocked bool
cancel *trackedCancel
matches map[order.MatchID]*matchTracker
notify func(Notification)
formatDetails func(Topic, ...interface{}) (string, string)
epochLen uint64
fromAssetID uint32
redemptionReserves uint64
}
// newTrackedTrade is a constructor for a trackedTrade.
func newTrackedTrade(dbOrder *db.MetaOrder, preImg order.Preimage, dc *dexConnection, epochLen uint64,
lockTimeTaker, lockTimeMaker time.Duration, db db.DB, latencyQ *wait.TickerQueue, wallets *walletSet,
coins asset.Coins, notify func(Notification), formatDetails func(Topic, ...interface{}) (string, string),
redemptionReserves uint64) *trackedTrade {
fromID := dbOrder.Order.Quote()
if dbOrder.Order.Trade().Sell {
fromID = dbOrder.Order.Base()
}
ord := dbOrder.Order
t := &trackedTrade{
Order: ord,
metaData: dbOrder.MetaData,
dc: dc,
db: db,
latencyQ: latencyQ,
wallets: wallets,
preImg: preImg,
mktID: marketName(ord.Base(), ord.Quote()),
coins: mapifyCoins(coins), // must not be nil even if empty
coinsLocked: len(coins) > 0,
lockTimeTaker: lockTimeTaker,
lockTimeMaker: lockTimeMaker,
matches: make(map[order.MatchID]*matchTracker),
notify: notify,
epochLen: epochLen,
fromAssetID: fromID,
formatDetails: formatDetails,
redemptionReserves: redemptionReserves,
}
return t
}
func (t *trackedTrade) accountRedeemer() (asset.AccountRedeemer, bool) {
ar, is := t.wallets.toWallet.Wallet.(asset.AccountRedeemer)
return ar, is
}
func (t *trackedTrade) isMarketBuy() bool {
trade := t.Trade()
if trade == nil {
return false
}
return t.Type() == order.MarketOrderType && !trade.Sell
}
func (t *trackedTrade) epochIdx() uint64 {
return encode.UnixMilliU(t.Prefix().ServerTime) / t.epochLen
}
// cancelEpochIdx gives the epoch index of any cancel associated cancel order.
// The mutex must be at least read locked.
func (t *trackedTrade) cancelEpochIdx() uint64 {
if t.cancel == nil {
return 0
}
return encode.UnixMilliU(t.cancel.Prefix().ServerTime) / t.epochLen
}
func (t *trackedTrade) verifyCSum(csum []byte, epochIdx uint64) error {
t.mtx.RLock()
defer t.mtx.RUnlock()
// First check the trade's recorded csum, if it is in this epoch.
if epochIdx == t.epochIdx() && !bytes.Equal(csum, t.csum) {
return fmt.Errorf("checksum %s != trade order preimage request checksum %s for trade order %v",
csum, t.csum, t.ID())
}
if t.cancel == nil {
return nil // no linked cancel order
}
// Check the linked cancel order if it is for this epoch.
if epochIdx == t.cancelEpochIdx() && !bytes.Equal(csum, t.cancel.csum) {
return fmt.Errorf("checksum %s != cancel order preimage request checksum %s for cancel order %v",
csum, t.cancel.csum, t.cancel.ID())
}
return nil // includes not in epoch
}
// rate returns the order's rate, or zero if a market or cancel order.
func (t *trackedTrade) rate() uint64 {
if ord, ok := t.Order.(*order.LimitOrder); ok {
return ord.Rate
}
return 0
}
// broadcastTimeout gets associated DEX's configured broadcast timeout. If the
// trade's dexConnection was unable to be established, 0 is returned.
func (t *trackedTrade) broadcastTimeout() time.Duration {
t.dc.cfgMtx.RLock()
defer t.dc.cfgMtx.RUnlock()
// If the dexConnection was never established, we have no config.
if t.dc.cfg == nil {
return 0
}
return time.Millisecond * time.Duration(t.dc.cfg.BroadcastTimeout)
}
// delayTicks sets the tickGovernor to prevent retrying too quickly after an
// error.
func (t *trackedTrade) delayTicks(m *matchTracker, waitTime time.Duration) {
m.tickGovernor = time.AfterFunc(waitTime, func() {
t.mtx.Lock()
defer t.mtx.Unlock()
m.tickGovernor = nil
})
}
// coreOrder constructs a *core.Order for the tracked order.Order. If the trade
// has a cancel order associated with it, the cancel order will be returned,
// otherwise the second returned *Order will be nil.
func (t *trackedTrade) coreOrder() *Order {
t.mtx.RLock()
defer t.mtx.RUnlock()
return t.coreOrderInternal()
}
// coreOrderInternal constructs a *core.Order for the tracked order.Order. If
// the trade has a cancel order associated with it, the cancel order will be
// returned, otherwise the second returned *Order will be nil. coreOrderInternal
// should be called with the mtx >= RLocked.
func (t *trackedTrade) coreOrderInternal() *Order {
corder := coreOrderFromTrade(t.Order, t.metaData)
corder.Epoch = t.dc.marketEpoch(t.mktID, t.Prefix().ServerTime)
corder.LockedAmt = t.lockedAmount()
for _, mt := range t.matches {
corder.Matches = append(corder.Matches, matchFromMetaMatchWithConfs(t,
&mt.MetaMatch, mt.swapConfirms, int64(t.wallets.fromAsset.SwapConf), mt.counterConfirms, int64(t.wallets.toAsset.SwapConf)))
}
return corder
}
// hasFundingCoins indicates if either funding or change coins are locked.
// This should be called with the mtx at least read locked.
func (t *trackedTrade) hasFundingCoins() bool {
return t.changeLocked || t.coinsLocked
}
// lockedAmount is the total value of all coins currently locked for this trade.
// Returns the value sum of the initial funding coins if no swap has been sent,
// otherwise, the value of the locked change coin is returned.
// NOTE: This amount only applies to the wallet from which swaps are sent. This
// is the BASE asset wallet for a SELL order and the QUOTE asset wallet for a
// BUY order.
// lockedAmount should be called with the mtx >= RLocked.
func (t *trackedTrade) lockedAmount() (locked uint64) {
if t.coinsLocked {
// This implies either no swap has been sent, or the trade has been
// resumed on restart after a swap that produced locked change (partial
// fill and still booked) since restarting loads into coins/coinsLocked.
for _, coin := range t.coins {
locked += coin.Value()
}
} else if t.changeLocked && t.change != nil { // change may be returned but unlocked if the last swap has been sent
locked = t.change.Value()
}
return
}
// token is a shortened representation of the order ID.
func (t *trackedTrade) token() string {
id := t.ID()
return hex.EncodeToString(id[:4])
}
// cancelTrade sets the cancellation data with the order and its preimage.
// cancelTrade must be called with the mtx write-locked.
func (t *trackedTrade) cancelTrade(co *order.CancelOrder, preImg order.Preimage) error {
t.cancel = &trackedCancel{
CancelOrder: *co,
preImg: preImg,
}
err := t.db.LinkOrder(t.ID(), co.ID())
if err != nil {
return fmt.Errorf("error linking cancel order %s for trade %s: %w", co.ID(), t.ID(), err)
}
t.metaData.LinkedOrder = co.ID()
return nil
}
// nomatch sets the appropriate order status and returns funding coins.
func (t *trackedTrade) nomatch(oid order.OrderID) (assetMap, error) {
assets := make(assetMap)
// Check if this is the cancel order.
t.mtx.Lock()
defer t.mtx.Unlock()
if t.ID() != oid {
if t.cancel == nil || t.cancel.ID() != oid {
return assets, newError(unknownOrderErr, "nomatch order ID %s does not match trade or cancel order", oid)
}
// This is a cancel order. Cancel status goes to executed, but the trade
// status will not be canceled. Remove the trackedCancel and remove the
// DB linked order from the trade, but not the cancel.
t.dc.log.Warnf("Cancel order %s targeting trade %s did not match.", oid, t.ID())
err := t.db.LinkOrder(t.ID(), order.OrderID{})
if err != nil {
t.dc.log.Errorf("DB error unlinking cancel order %s for trade %s: %v", oid, t.ID(), err)
}
// Clearing the trackedCancel allows this order to be canceled again.
t.cancel = nil
t.metaData.LinkedOrder = order.OrderID{}
subject, details := t.formatDetails(TopicMissedCancel, t.token())
t.notify(newOrderNote(TopicMissedCancel, subject, details, db.WarningLevel, t.coreOrderInternal()))
return assets, t.db.UpdateOrderStatus(oid, order.OrderStatusExecuted)
}
// This is the trade. Return coins and set status based on whether this is
// a standing limit order or not.
if t.metaData.Status != order.OrderStatusEpoch {
return assets, fmt.Errorf("nomatch sent for non-epoch order %s", oid)
}
if lo, ok := t.Order.(*order.LimitOrder); ok && lo.Force == order.StandingTiF {
t.dc.log.Infof("Standing order %s did not match and is now booked.", t.token())
t.metaData.Status = order.OrderStatusBooked
t.notify(newOrderNote(TopicOrderBooked, "", "", db.Data, t.coreOrderInternal()))
} else {
t.returnCoins()
if redeemer, is := t.accountRedeemer(); is {
redeemer.UnlockReserves(t.redemptionReserves)
}
assets.count(t.wallets.fromAsset.ID)
t.dc.log.Infof("Non-standing order %s did not match.", t.token())
t.metaData.Status = order.OrderStatusExecuted
t.notify(newOrderNote(TopicNoMatch, "", "", db.Data, t.coreOrderInternal()))
}
return assets, t.db.UpdateOrderStatus(t.ID(), t.metaData.Status)
}
// negotiate creates and stores matchTrackers for the []*msgjson.Match, and
// updates (UserMatch).Filled. Match negotiation can then be progressed by
// calling (*trackedTrade).tick when a relevant event occurs, such as a request
// from the DEX or a tip change.
func (t *trackedTrade) negotiate(msgMatches []*msgjson.Match) error {
trade := t.Trade()
// Validate matches and check if a cancel match is included.
// Non-cancel matches should be negotiated and are added to
// the newTrackers slice.
var cancelMatch *msgjson.Match
newTrackers := make([]*matchTracker, 0, len(msgMatches))
for _, msgMatch := range msgMatches {
if len(msgMatch.MatchID) != order.MatchIDSize {
return fmt.Errorf("match id of incorrect length. expected %d, got %d",
order.MatchIDSize, len(msgMatch.MatchID))
}
var oid order.OrderID
copy(oid[:], msgMatch.OrderID)
if oid != t.ID() {
return fmt.Errorf("negotiate called for wrong order. %s != %s", oid, t.ID())
}
var mid order.MatchID
copy(mid[:], msgMatch.MatchID)
// Do not process matches with existing matchTrackers. e.g. In case we
// start "extra" matches from the 'connect' response negotiating via
// authDEX>readConnectMatches, and a subsequent resent 'match' request
// leads us here again or vice versa. Or just duplicate match requests.
if t.matches[mid] != nil {
t.dc.log.Warnf("Skipping match %v that is already negotiating.", mid)
continue
}
// Check if this is a match with a cancel order, in which case the
// counterparty Address field would be empty. If the user placed a
// cancel order, that order will be recorded in t.cancel on cancel
// order creation via (*dexConnection).tryCancel or restored from DB
// via (*Core).dbTrackers.
if t.cancel != nil && msgMatch.Address == "" {
cancelMatch = msgMatch
continue
}
match := &matchTracker{
prefix: t.Prefix(),
trade: trade,
MetaMatch: *t.makeMetaMatch(msgMatch),
counterConfirms: -1,
lastExpireDur: 365 * 24 * time.Hour,
}
match.Status = order.NewlyMatched // these must be new matches
newTrackers = append(newTrackers, match)
}
// Record any cancel order Match and update order status.
if cancelMatch != nil {
t.dc.log.Infof("Maker notification for cancel order received for order %s. match id = %s",
t.ID(), cancelMatch.MatchID)
// Set this order status to Canceled and unlock any locked coins
// if there are no new matches and there's no need to send swap
// for any previous match.
t.metaData.Status = order.OrderStatusCanceled
if len(newTrackers) == 0 {
t.maybeReturnCoins()
}
t.cancel.matches.maker = cancelMatch // taker is stored via processCancelMatch before negotiate
// Set the order status for the cancel order.
err := t.db.UpdateOrderStatus(t.cancel.ID(), order.OrderStatusExecuted)
if err != nil {
t.dc.log.Errorf("Failed to update status of cancel order %v to executed: %v",
t.cancel.ID(), err)
// Try to store the match anyway.
}
// Store a completed maker cancel match in the DB.
makerCancelMeta := t.makeMetaMatch(cancelMatch)
makerCancelMeta.Status = order.MatchComplete
makerCancelMeta.Address = "" // not a trade match
err = t.db.UpdateMatch(makerCancelMeta)
if err != nil {
return fmt.Errorf("failed to update match in db: %w", err)
}
}
// Now that each Match in msgMatches has been validated, store them in the
// trackedTrade and the DB, and update the newFill amount.
var newFill uint64
for _, match := range newTrackers {
var qty uint64
if t.isMarketBuy() {
qty = calc.BaseToQuote(match.Rate, match.Quantity)
} else {
qty = match.Quantity
}
newFill += qty
if trade.Filled()+newFill > trade.Quantity {
t.dc.log.Errorf("Match %s would put order %s fill over quantity. Revoking the match.",
match, t.ID())
match.MetaData.Proof.SelfRevoked = true
}
// If this order has no funding coins, block swaps attempts on the new
// match. Do not revoke however since the user may be able to resolve
// wallet configuration issues and restart to restore funding coins.
// Otherwise the server will end up revoking these matches.
if !t.hasFundingCoins() {
t.dc.log.Errorf("Unable to begin swap negotiation for unfunded order %v", t.ID())
match.swapErr = errors.New("no funding coins for swap")
}
err := t.db.UpdateMatch(&match.MetaMatch)
if err != nil {
// Don't abandon other matches because of this error, attempt
// to negotiate the other matches.
t.dc.log.Errorf("failed to update match %s in db: %v", match, err)
continue
}
// Only add this match to the map if the db update succeeds, so
// funds don't get stuck if user restarts Core after sending a
// swap because negotiations will not be resumed for this match
// and auto-refund cannot be performed.
// TODO: Maybe allow? This match can be restored from the DEX's
// connect response on restart IF it is not revoked.
t.matches[match.MatchID] = match
t.dc.log.Infof("Starting negotiation for match %s for order %v with swap fee rate = %v, quantity = %v",
match, t.ID(), match.FeeRateSwap, qty)
}
// Calculate and set the new filled value for the order.
var filled uint64
for _, mt := range t.matches {
if t.isMarketBuy() {
filled += calc.BaseToQuote(mt.Rate, mt.Quantity)
} else {
filled += mt.Quantity
}
}
// If the order has been canceled, add that to filled and newFill.
if cancelMatch != nil {
filled += cancelMatch.Quantity
newFill += cancelMatch.Quantity
}
// The filled amount includes all of the trackedTrade's matches, so the
// filled amount must be set, not just increased.
trade.SetFill(filled)
// Before we update any order statuses, check if this is a market sell order
// which is now executed, in which case we can return redemption reserves
// associated with any remainder.
completedMarketSell := trade.Sell && t.Type() == order.MarketOrderType && t.metaData.Status < order.OrderStatusExecuted
// Set the order as executed depending on type and fill.
if t.metaData.Status != order.OrderStatusCanceled && t.metaData.Status != order.OrderStatusRevoked {
if lo, ok := t.Order.(*order.LimitOrder); ok && lo.Force == order.StandingTiF && filled < trade.Quantity {
t.metaData.Status = order.OrderStatusBooked
} else {
t.metaData.Status = order.OrderStatusExecuted
}
}
// If this is a market sell or a cancelled limit order, unlock redemption
// reserves.
if completedMarketSell || (cancelMatch != nil && t.Type() == order.LimitOrderType) {
// If this is a limit order, unlock remaining.
remain := t.Trade().Remaining()
if remain > 0 {
if redeemer, is := t.accountRedeemer(); is {
redeemer.UnlockReserves(applyFraction(remain, trade.Quantity, t.redemptionReserves))
}
}
}
// Send notifications.
corder := t.coreOrderInternal()
if cancelMatch != nil {
subject, details := t.formatDetails(TopicOrderCanceled,
strings.Title(sellString(trade.Sell)), unbip(t.Base()), unbip(t.Quote()), t.dc.acct.host, t.token())
t.notify(newOrderNote(TopicOrderCanceled, subject, details, db.Poke, corder))
// Also send out a data notification with the cancel order information.
t.notify(newOrderNote(TopicCancel, "", "", db.Data, corder))
}
if len(newTrackers) > 0 {
fillPct := 100 * float64(filled) / float64(trade.Quantity)
t.dc.log.Debugf("Trade order %v matched with %d orders: +%d filled, total fill %d / %d (%.1f%%)",
t.ID(), len(newTrackers), newFill, filled, trade.Quantity, fillPct)
// Match notifications.
for _, match := range newTrackers {
t.notify(newMatchNote(TopicNewMatch, "", "", db.Data, t, match))
}
// A single order notification.
subject, details := t.formatDetails(TopicMatchesMade,
strings.Title(sellString(trade.Sell)), unbip(t.Base()), unbip(t.Quote()), fillPct, t.token())
t.notify(newOrderNote(TopicMatchesMade, subject, details, db.Poke, corder))
}
err := t.db.UpdateOrder(t.metaOrder())
if err != nil {
return fmt.Errorf("failed to update order in db: %w", err)
}
return nil
}
func (t *trackedTrade) metaOrder() *db.MetaOrder {
return &db.MetaOrder{
MetaData: t.metaData,
Order: t.Order,
}
}
func (t *trackedTrade) makeMetaMatch(msgMatch *msgjson.Match) *db.MetaMatch {
// Contract txn asset: buy means quote, sell means base. NOTE: msgjson.Match
// could instead have just FeeRateSwap for the recipient, but the other fee
// rate could be of value for auditing the counter party's contract txn.
feeRateSwap := msgMatch.FeeRateQuote
if t.Trade().Sell {
feeRateSwap = msgMatch.FeeRateBase
}
// Consider: bump fee rate here based on a user setting in dexConnection.
// feeRateSwap = feeRateSwap * 11 / 10
// maxFeeRate := t.dc.assets[swapAssetID].MaxFeeRate // swapAssetID according to t.Trade().Sell and t.Base()/Quote()
// if feeRateSwap > maxFeeRate {
// feeRateSwap = maxFeeRate
// }
var oid order.OrderID
copy(oid[:], msgMatch.OrderID)
var mid order.MatchID
copy(mid[:], msgMatch.MatchID)
return &db.MetaMatch{
MetaData: &db.MatchMetaData{
Proof: db.MatchProof{
Auth: db.MatchAuth{
MatchSig: msgMatch.Sig,
MatchStamp: msgMatch.ServerTime,
},
},
DEX: t.dc.acct.host,
Base: t.Base(),
Quote: t.Quote(),
Stamp: msgMatch.ServerTime,
},
UserMatch: &order.UserMatch{
OrderID: oid,
MatchID: mid,
Quantity: msgMatch.Quantity,
Rate: msgMatch.Rate,
Address: msgMatch.Address,
Status: order.MatchStatus(msgMatch.Status),
Side: order.MatchSide(msgMatch.Side),
FeeRateSwap: feeRateSwap,
},
}
}
// processCancelMatch should be called with the message for the match on a
// cancel order.
func (t *trackedTrade) processCancelMatch(msgMatch *msgjson.Match) error {
var oid order.OrderID
copy(oid[:], msgMatch.OrderID)
var mid order.MatchID
copy(mid[:], msgMatch.MatchID)
t.mtx.Lock()
defer t.mtx.Unlock()
if t.cancel == nil {
return fmt.Errorf("no cancel order recorded for order %v", oid)
}
if oid != t.cancel.ID() {
return fmt.Errorf("negotiate called for wrong order. %s != %s", oid, t.cancel.ID())
}
t.dc.log.Infof("Taker notification for cancel order %v received. Match id = %s", oid, mid)
t.cancel.matches.taker = msgMatch
// Store the completed taker cancel match.
takerCancelMeta := t.makeMetaMatch(t.cancel.matches.taker)
takerCancelMeta.Status = order.MatchComplete
takerCancelMeta.Address = "" // not a trade match
err := t.db.UpdateMatch(takerCancelMeta)
if err != nil {
return fmt.Errorf("failed to update match in db: %w", err)
}
return nil
}
// Get the required and current confirmation count on the counterparty's swap
// contract transaction for the provided match. If the count has not changed
// since the previous check, changed will be false.
//
// This method accesses match fields and MUST be called with the trackedTrade
// mutex lock held for reads.
func (t *trackedTrade) counterPartyConfirms(ctx context.Context, match *matchTracker) (have, needed uint32, changed, spent bool) {
// Counter-party's swap is the "to" asset.
needed = t.wallets.toAsset.SwapConf
// Check the confirmations on the counter-party's swap. If counterSwap is
// not set, we shouldn't be here, but catch this just in case.
if match.counterSwap == nil {
t.dc.log.Warnf("counterPartyConfirms: No AuditInfo available to check!")
return
}
coin := match.counterSwap.Coin
var err error
have, spent, err = t.wallets.toWallet.SwapConfirmations(ctx, coin.ID(),
match.MetaData.Proof.CounterContract, match.MetaData.Stamp)
if err != nil {
t.dc.log.Errorf("Failed to get confirmations of the counter-party's swap %s (%s) for match %s, order %v: %v",
coin, t.wallets.toAsset.Symbol, match, t.UID(), err)
return
}
// Log the pending swap status at new heights only.
if match.counterConfirms != int64(have) {
match.counterConfirms = int64(have)
changed = true
t.notify(newMatchNote(TopicCounterConfirms, "", "", db.Data, t, match))
}
return
}
// deleteCancelOrder will clear any associated trackedCancel, and set the status
// of the cancel order as revoked in the DB so that it will not be loaded with
// other active orders on startup. The trackedTrade's OrderMetaData.LinkedOrder
// is also zeroed, but the caller is responsible for updating the trade's DB
// entry in a way that is appropriate for the caller (e.g. with LinkOrder,
// UpdateOrder, or UpdateOrderStatus).
//
// This is to be used in trade status resolution only, since normally the fate
// of cancel orders is determined by match/nomatch and status set to executed
// (see nomatch and negotiate)
//
// This method MUST be called with the trackedTrade mutex lock held for writes.
func (t *trackedTrade) deleteCancelOrder() {
if t.cancel == nil {
return
}
cid := t.cancel.ID()
err := t.db.UpdateOrderStatus(cid, order.OrderStatusRevoked) // could actually be OrderStatusExecuted
if err != nil {
t.dc.log.Errorf("Error updating status in db for cancel order %v to revoked: %v", cid, err)
}
// Unlink the cancel order from the trade.
t.cancel = nil
t.metaData.LinkedOrder = order.OrderID{} // NOTE: caller may wish to update the trades's DB entry
}
// deleteStaleCancelOrder checks if this trade has an associated cancel order,
// and deletes the cancel order if the cancel order stays at Epoch status for
// more than 2 epochs. Deleting the stale cancel order from this trade makes
// it possible for the client to re- attempt cancelling the order.
//
// NOTE:
// Stale cancel orders would be Executed if their preimage was sent or Revoked
// if their preimages was not sent. We cannot currently tell whether the cancel
// order's preimage was revealed, so assume that the cancel order is Executed
// but unmatched. Consider adding a order.PreimageRevealed field to ensure that
// the correct final status is set for the cancel order; or allow the server to
// check and return status of cancel orders.
//
// This method MUST be called with the trackedTrade mutex lock held for writes.
func (t *trackedTrade) deleteStaleCancelOrder() {
if t.cancel == nil || t.metaData.Status != order.OrderStatusBooked {
return
}
stamp := t.cancel.ServerTime
epoch := order.EpochID{Idx: encode.UnixMilliU(stamp) / t.epochLen, Dur: t.epochLen}
epochEnd := epoch.End()
if time.Since(epochEnd).Milliseconds() < int64(2*t.epochLen) {
return // not stuck, yet
}
t.dc.log.Infof("Cancel order %v in epoch status with server time stamp %v, epoch end %v (%v ago) considered executed and unmatched.",
t.cancel.ID(), t.cancel.ServerTime, epochEnd, time.Since(epochEnd))
// Clear the trackedCancel, allowing this order to be canceled again, and
// set the cancel order's status as revoked.
t.deleteCancelOrder()
err := t.db.LinkOrder(t.ID(), order.OrderID{})
if err != nil {
t.dc.log.Errorf("DB error unlinking cancel order %s for trade %s: %v", t.cancel.ID(), t.ID(), err)
}
subject, details := t.formatDetails(TopicFailedCancel, t.token())
t.notify(newOrderNote(TopicFailedCancel, subject, details, db.WarningLevel, t.coreOrderInternal()))
}
// isActive will be true if the trade is booked or epoch, or if any of the
// matches are still negotiating.
func (t *trackedTrade) isActive() bool {
t.mtx.RLock()
defer t.mtx.RUnlock()
// Status of the order itself.
if t.metaData.Status == order.OrderStatusBooked ||
t.metaData.Status == order.OrderStatusEpoch {
return true
}
// Status of all matches for the order.
for _, match := range t.matches {
proof := &match.MetaData.Proof
t.dc.log.Tracef("Checking match %s (%v) in status %v. "+
"Order: %v, Refund coin: %v, ContractData: %x, Revoked: %v", match,
match.Side, match.Status, t.ID(),
proof.RefundCoin, proof.ContractData, proof.IsRevoked())
if t.matchIsActive(match) {
return true
}
}
return false
}
// matchIsRevoked checks if the match is revoked, RLocking the trackedTrade.
func (t *trackedTrade) matchIsRevoked(match *matchTracker) bool {
t.mtx.RLock()
defer t.mtx.RUnlock()
return match.MetaData.Proof.IsRevoked()
}
// Matches are inactive if: (1) status is complete, (2) it is refunded, or (3)
// it is revoked and this side of the match requires no further action like
// refund or auto-redeem. This should not be applied to cancel order matches.
func (t *trackedTrade) matchIsActive(match *matchTracker) bool {
proof := &match.MetaData.Proof
isActive := db.MatchIsActive(match.UserMatch, proof)
if proof.IsRevoked() && !isActive {
t.dc.log.Tracef("Revoked match %s (%v) in status %v considered inactive.",
match, match.Side, match.Status)
}
return isActive
}
func (t *trackedTrade) activeMatches() []*matchTracker {
var actives []*matchTracker
t.mtx.RLock()
defer t.mtx.RUnlock()
for _, match := range t.matches {
if t.matchIsActive(match) {
actives = append(actives, match)
}
}
return actives
}
// unspentContractAmounts returns the total amount locked in unspent swaps.
// NOTE: This amount only applies to the wallet from which swaps are sent. This
// is the BASE asset wallet for a SELL order and the QUOTE asset wallet for a
// BUY order.
// unspentContractAmounts should be called with the mtx >= RLocked.
func (t *trackedTrade) unspentContractAmounts() (amount uint64) {
swapSentFromQuoteAsset := t.fromAssetID == t.Quote()
for _, match := range t.matches {
side, status := match.Side, match.Status
if status >= order.MakerRedeemed || len(match.MetaData.Proof.RefundCoin) != 0 {
// Any redemption or own refund implies our swap is spent.
// Even if we're Maker and our swap has not been redeemed
// by Taker, we should consider it spent.
continue
}
if (side == order.Maker && status >= order.MakerSwapCast) ||
(side == order.Taker && status == order.TakerSwapCast) {
swapAmount := match.Quantity
if swapSentFromQuoteAsset {
swapAmount = calc.BaseToQuote(match.Rate, match.Quantity)
}
amount += swapAmount
}
}
return
}
// isSwappable will be true if the match is ready for a swap transaction to be
// broadcast.
//
// This method accesses match fields and MUST be called with the trackedTrade
// mutex lock held for writes.
func (t *trackedTrade) isSwappable(ctx context.Context, match *matchTracker) bool {
if match.swapErr != nil || match.MetaData.Proof.IsRevoked() || match.tickGovernor != nil || match.checkServerRevoke {
t.dc.log.Tracef("Match %s not swappable: swapErr = %v, revoked = %v, metered = %t, checkServerRevoke = %v",
match, match.swapErr, match.MetaData.Proof.IsRevoked(), match.tickGovernor != nil, match.checkServerRevoke)
return false
}
wallet := t.wallets.fromWallet
// Just a quick check here. We'll perform a more thorough check if there are
// actually swappables.
if !wallet.locallyUnlocked() {
t.dc.log.Errorf("not checking if order %s, match %s is swappable because %s wallet is not unlocked",
t.ID(), match, unbip(wallet.AssetID))
return false
}
if match.Status == order.MakerSwapCast {
// Get the confirmation count on the maker's coin.
if match.Side == order.Taker {
toAssetID := t.wallets.toAsset.ID
t.dc.log.Tracef("Checking confirmations on COUNTERPARTY swap txn %v (%s)...",
coinIDString(toAssetID, match.MetaData.Proof.MakerSwap), unbip(toAssetID))
// If the maker is the counterparty, we can determine swappability
// based on the confirmations.
confs, req, changed, spent := t.counterPartyConfirms(ctx, match)
ready := confs >= req
if changed && !ready {
t.dc.log.Debugf("Match %s not yet swappable: current confs = %d, required confs = %d",
match, confs, req)
}
if spent {
t.dc.log.Errorf("Counter-party's swap is spent before we could broadcast our own")
match.MetaData.Proof.SelfRevoked = true
return false
}
return ready
}
// If we're the maker, check the confirmations anyway so we can notify.
t.dc.log.Tracef("Checking confirmations on our OWN swap txn %v (%s)...",
coinIDString(wallet.AssetID, match.MetaData.Proof.MakerSwap), unbip(wallet.AssetID))
confs, spent, err := wallet.SwapConfirmations(ctx, match.MetaData.Proof.MakerSwap,
match.MetaData.Proof.ContractData, match.MetaData.Stamp)
if err != nil {
t.dc.log.Errorf("error getting confirmation for our own swap transaction: %v", err)
}
if spent {
t.dc.log.Debugf("our (maker) swap for match %s is being reported as spent, "+
"but we have not seen the counter-party's redemption yet. This could just"+
" be network latency.", match)
}
match.swapConfirms = int64(confs)
t.notify(newMatchNote(TopicConfirms, "", "", db.Data, t, match))
return false
}
if match.Side == order.Maker && match.Status == order.NewlyMatched {
return true
}
return false
}
// isRedeemable will be true if the match is ready for our redemption to be
// broadcast.
//
// This method accesses match fields and MUST be called with the trackedTrade
// mutex lock held for reads.
func (t *trackedTrade) isRedeemable(ctx context.Context, match *matchTracker) bool {
if match.swapErr != nil || len(match.MetaData.Proof.RefundCoin) != 0 || match.tickGovernor != nil {
t.dc.log.Tracef("Match %s not redeemable: swapErr = %v, RefundCoin = %v, metered = %t",
match, match.swapErr, match.MetaData.Proof.RefundCoin, match.tickGovernor != nil)
return false
}
wallet := t.wallets.toWallet
// Just a quick check here. We'll perform a more thorough check if there are
// actually redeemables.
if !wallet.locallyUnlocked() {
t.dc.log.Errorf("not checking if order %s, match %s is redeemable because %s wallet is not unlocked",
t.ID(), match, unbip(wallet.AssetID))
return false
}
if match.Status == order.TakerSwapCast {
if match.Side == order.Maker {
// Check the confirmations on the taker's swap.
confs, req, changed, spent := t.counterPartyConfirms(ctx, match)
ready := confs >= req
if changed && !ready {
t.dc.log.Debugf("Match %s not yet redeemable: current confs = %d, required confs = %d",
match, confs, req)
}
if spent {
t.dc.log.Errorf("Order %s, match %s counter-party's swap is spent before we could redeem", t.ID(), match)
match.MetaData.Proof.SelfRevoked = true
return false
}
return ready
}
// If we're the taker, check the confirmations anyway so we can notify.
confs, spent, err := t.wallets.fromWallet.SwapConfirmations(ctx, match.MetaData.Proof.TakerSwap,
match.MetaData.Proof.ContractData, match.MetaData.Stamp)
if err != nil {
t.dc.log.Errorf("error getting confirmation for our own swap transaction: %v", err)
}
if spent {
t.dc.log.Debugf("our (taker) swap for match %s is being reported as spent, "+
"but we have not seen the counter-party's redemption yet. This could just"+
" be network latency.", match)
}
match.swapConfirms = int64(confs)
t.notify(newMatchNote(TopicConfirms, "", "", db.Data, t, match))
return false
}
if match.Side == order.Taker && match.Status == order.MakerRedeemed {
return true
}
return false
}