-
Notifications
You must be signed in to change notification settings - Fork 0
/
order_processor.go
632 lines (605 loc) · 31.9 KB
/
order_processor.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
package tomox
import (
"github.com/tomochain/tomochain/consensus"
"math/big"
"strconv"
"time"
"fmt"
"github.com/tomochain/tomochain/common"
"github.com/tomochain/tomochain/core/state"
"github.com/tomochain/tomochain/log"
"github.com/tomochain/tomochain/tomox/tomox_state"
)
func (tomox *TomoX) CommitOrder(coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
tomoxSnap := tomoXstatedb.Snapshot()
dbSnap := statedb.Snapshot()
trades, rejects, err := tomox.ApplyOrder(coinbase, chain, statedb, tomoXstatedb, orderBook, order)
if err != nil {
tomoXstatedb.RevertToSnapshot(tomoxSnap)
statedb.RevertToSnapshot(dbSnap)
return nil, nil, err
}
return trades, rejects, err
}
func (tomox *TomoX) ApplyOrder(coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
var (
rejects []*tomox_state.OrderItem
trades []map[string]string
err error
)
nonce := tomoXstatedb.GetNonce(order.UserAddress.Hash())
log.Debug("ApplyOrder", "addr", order.UserAddress, "statenonce", nonce, "ordernonce", order.Nonce)
if big.NewInt(int64(nonce)).Cmp(order.Nonce) == -1 {
return nil, nil, ErrNonceTooHigh
} else if big.NewInt(int64(nonce)).Cmp(order.Nonce) == 1 {
return nil, nil, ErrNonceTooLow
}
if order.Status == OrderStatusCancelled {
err, reject := tomox.ProcessCancelOrder(tomoXstatedb, statedb, chain, coinbase, orderBook, order)
if err != nil {
return nil, nil, err
}
if reject {
rejects = append(rejects, order)
}
log.Debug("Exchange add user nonce:", "address", order.UserAddress, "status", order.Status, "nonce", nonce+1)
tomoXstatedb.SetNonce(order.UserAddress.Hash(), nonce+1)
return trades, rejects, nil
}
if order.Type != tomox_state.Market {
if order.Price.Sign() == 0 || common.BigToHash(order.Price).Big().Cmp(order.Price) != 0 {
log.Debug("Reject order price invalid", "price", order.Price)
rejects = append(rejects, order)
tomoXstatedb.SetNonce(order.UserAddress.Hash(), nonce+1)
return trades, rejects, nil
}
}
if order.Quantity.Sign() == 0 || common.BigToHash(order.Quantity).Big().Cmp(order.Quantity) != 0 {
log.Debug("Reject order quantity invalid", "quantity", order.Quantity)
rejects = append(rejects, order)
tomoXstatedb.SetNonce(order.UserAddress.Hash(), nonce+1)
return trades, rejects, nil
}
orderType := order.Type
// if we do not use auto-increment orderid, we must set price slot to avoid conflict
if orderType == tomox_state.Market {
log.Debug("Process maket order", "side", order.Side, "quantity", order.Quantity, "price", order.Price)
trades, rejects, err = tomox.processMarketOrder(coinbase, chain, statedb, tomoXstatedb, orderBook, order)
if err != nil {
return nil, nil, err
}
} else {
log.Debug("Process limit order", "side", order.Side, "quantity", order.Quantity, "price", order.Price)
trades, rejects, err = tomox.processLimitOrder(coinbase, chain, statedb, tomoXstatedb, orderBook, order)
if err != nil {
return nil, nil, err
}
}
log.Debug("Exchange add user nonce:", "address", order.UserAddress, "status", order.Status, "nonce", nonce+1)
tomoXstatedb.SetNonce(order.UserAddress.Hash(), nonce+1)
return trades, rejects, nil
}
// processMarketOrder : process the market order
func (tomox *TomoX) processMarketOrder(coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
var (
trades []map[string]string
newTrades []map[string]string
rejects []*tomox_state.OrderItem
newRejects []*tomox_state.OrderItem
err error
)
quantityToTrade := order.Quantity
side := order.Side
// speedup the comparison, do not assign because it is pointer
zero := tomox_state.Zero
if side == tomox_state.Bid {
bestPrice, volume := tomoXstatedb.GetBestAskPrice(orderBook)
log.Debug("processMarketOrder ", "side", side, "bestPrice", bestPrice, "quantityToTrade", quantityToTrade, "volume", volume)
for quantityToTrade.Cmp(zero) > 0 && bestPrice.Cmp(zero) > 0 {
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, chain, statedb, tomoXstatedb, tomox_state.Ask, orderBook, bestPrice, quantityToTrade, order)
if err != nil {
return nil, nil, err
}
trades = append(trades, newTrades...)
rejects = append(rejects, newRejects...)
bestPrice, volume = tomoXstatedb.GetBestAskPrice(orderBook)
log.Debug("processMarketOrder ", "side", side, "bestPrice", bestPrice, "quantityToTrade", quantityToTrade, "volume", volume)
}
} else {
bestPrice, volume := tomoXstatedb.GetBestBidPrice(orderBook)
log.Debug("processMarketOrder ", "side", side, "bestPrice", bestPrice, "quantityToTrade", quantityToTrade, "volume", volume)
for quantityToTrade.Cmp(zero) > 0 && bestPrice.Cmp(zero) > 0 {
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, chain, statedb, tomoXstatedb, tomox_state.Bid, orderBook, bestPrice, quantityToTrade, order)
if err != nil {
return nil, nil, err
}
trades = append(trades, newTrades...)
rejects = append(rejects, newRejects...)
bestPrice, volume = tomoXstatedb.GetBestBidPrice(orderBook)
log.Debug("processMarketOrder ", "side", side, "bestPrice", bestPrice, "quantityToTrade", quantityToTrade, "volume", volume)
}
}
return trades, newRejects, nil
}
// processLimitOrder : process the limit order, can change the quote
// If not care for performance, we should make a copy of quote to prevent further reference problem
func (tomox *TomoX) processLimitOrder(coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, orderBook common.Hash, order *tomox_state.OrderItem) ([]map[string]string, []*tomox_state.OrderItem, error) {
var (
trades []map[string]string
newTrades []map[string]string
rejects []*tomox_state.OrderItem
newRejects []*tomox_state.OrderItem
err error
)
quantityToTrade := order.Quantity
side := order.Side
price := order.Price
// speedup the comparison, do not assign because it is pointer
zero := tomox_state.Zero
if side == tomox_state.Bid {
minPrice, volume := tomoXstatedb.GetBestAskPrice(orderBook)
log.Debug("processLimitOrder ", "side", side, "minPrice", minPrice, "orderPrice", price, "volume", volume)
for quantityToTrade.Cmp(zero) > 0 && price.Cmp(minPrice) >= 0 && minPrice.Cmp(zero) > 0 {
log.Debug("Min price in asks tree", "price", minPrice.String())
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, chain, statedb, tomoXstatedb, tomox_state.Ask, orderBook, minPrice, quantityToTrade, order)
if err != nil {
return nil, nil, err
}
trades = append(trades, newTrades...)
rejects = append(rejects, newRejects...)
log.Debug("New trade found", "newTrades", newTrades, "quantityToTrade", quantityToTrade)
minPrice, volume = tomoXstatedb.GetBestAskPrice(orderBook)
log.Debug("processLimitOrder ", "side", side, "minPrice", minPrice, "orderPrice", price, "volume", volume)
}
} else {
maxPrice, volume := tomoXstatedb.GetBestBidPrice(orderBook)
log.Debug("processLimitOrder ", "side", side, "maxPrice", maxPrice, "orderPrice", price, "volume", volume)
for quantityToTrade.Cmp(zero) > 0 && price.Cmp(maxPrice) <= 0 && maxPrice.Cmp(zero) > 0 {
log.Debug("Max price in bids tree", "price", maxPrice.String())
quantityToTrade, newTrades, newRejects, err = tomox.processOrderList(coinbase, chain, statedb, tomoXstatedb, tomox_state.Bid, orderBook, maxPrice, quantityToTrade, order)
if err != nil {
return nil, nil, err
}
trades = append(trades, newTrades...)
rejects = append(rejects, newRejects...)
log.Debug("New trade found", "newTrades", newTrades, "quantityToTrade", quantityToTrade)
maxPrice, volume = tomoXstatedb.GetBestBidPrice(orderBook)
log.Debug("processLimitOrder ", "side", side, "maxPrice", maxPrice, "orderPrice", price, "volume", volume)
}
}
if quantityToTrade.Cmp(zero) > 0 {
orderId := tomoXstatedb.GetNonce(orderBook)
order.OrderID = orderId + 1
order.Quantity = quantityToTrade
tomoXstatedb.SetNonce(orderBook, orderId+1)
orderIdHash := common.BigToHash(new(big.Int).SetUint64(order.OrderID))
tomoXstatedb.InsertOrderItem(orderBook, orderIdHash, *order)
log.Debug("After matching, order (unmatched part) is now added to tree", "side", order.Side, "order", order)
}
return trades, rejects, nil
}
// processOrderList : process the order list
func (tomox *TomoX) processOrderList(coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, tomoXstatedb *tomox_state.TomoXStateDB, side string, orderBook common.Hash, price *big.Int, quantityStillToTrade *big.Int, order *tomox_state.OrderItem) (*big.Int, []map[string]string, []*tomox_state.OrderItem, error) {
quantityToTrade := tomox_state.CloneBigInt(quantityStillToTrade)
log.Debug("Process matching between order and orderlist", "quantityToTrade", quantityToTrade)
var (
trades []map[string]string
rejects []*tomox_state.OrderItem
)
for quantityToTrade.Sign() > 0 {
orderId, amount, _ := tomoXstatedb.GetBestOrderIdAndAmount(orderBook, price, side)
var oldestOrder tomox_state.OrderItem
if amount.Sign() > 0 {
oldestOrder = tomoXstatedb.GetOrder(orderBook, orderId)
}
log.Debug("found order ", "orderId ", orderId, "side", oldestOrder.Side, "amount", amount)
if oldestOrder.Quantity == nil || oldestOrder.Quantity.Sign() == 0 && amount.Sign() == 0 {
break
}
var (
tradedQuantity *big.Int
maxTradedQuantity *big.Int
)
if quantityToTrade.Cmp(amount) <= 0 {
maxTradedQuantity = tomox_state.CloneBigInt(quantityToTrade)
} else {
maxTradedQuantity = tomox_state.CloneBigInt(amount)
}
var quotePrice *big.Int
if oldestOrder.QuoteToken.String() != common.TomoNativeAddress {
quotePrice = tomoXstatedb.GetPrice(tomox_state.GetOrderBookHash(oldestOrder.QuoteToken, common.HexToAddress(common.TomoNativeAddress)))
log.Debug("TryGet quotePrice QuoteToken/TOMO", "quotePrice", quotePrice)
if (quotePrice == nil || quotePrice.Sign() == 0) && oldestOrder.BaseToken.String() != common.TomoNativeAddress {
inversePrice := tomoXstatedb.GetPrice(tomox_state.GetOrderBookHash(common.HexToAddress(common.TomoNativeAddress), oldestOrder.QuoteToken))
quoteTokenDecimal, err := tomox.GetTokenDecimal(chain, statedb, coinbase, oldestOrder.QuoteToken)
if err != nil || quoteTokenDecimal.Sign() == 0 {
return nil, nil, nil, fmt.Errorf("Fail to get tokenDecimal. Token: %v . Err: %v", oldestOrder.QuoteToken.String(), err)
}
log.Debug("TryGet inversePrice TOMO/QuoteToken", "inversePrice", inversePrice)
if inversePrice != nil && inversePrice.Sign() > 0 {
quotePrice = new(big.Int).Div(common.BasePrice, inversePrice)
quotePrice = new(big.Int).Mul(quotePrice, quoteTokenDecimal)
log.Debug("TryGet quotePrice after get inversePrice TOMO/QuoteToken", "quotePrice", quotePrice, "quoteTokenDecimal", quoteTokenDecimal)
}
}
}
tradedQuantity, rejectMaker, err := tomox.getTradeQuantity(quotePrice, coinbase, chain, statedb, order, &oldestOrder, maxTradedQuantity)
if err != nil && err == tomox_state.ErrQuantityTradeTooSmall {
if tradedQuantity.Cmp(maxTradedQuantity) == 0 {
if quantityToTrade.Cmp(amount) == 0 { // reject Taker & maker
rejects = append(rejects, order)
quantityToTrade = tomox_state.Zero
rejects = append(rejects, &oldestOrder)
err = tomoXstatedb.CancelOrder(orderBook, &oldestOrder)
if err != nil {
return nil, nil, nil, err
}
break
} else if quantityToTrade.Cmp(amount) < 0 { // reject Taker
rejects = append(rejects, order)
quantityToTrade = tomox_state.Zero
break
} else { // reject maker
rejects = append(rejects, &oldestOrder)
err = tomoXstatedb.CancelOrder(orderBook, &oldestOrder)
if err != nil {
return nil, nil, nil, err
}
continue
}
} else {
if rejectMaker { // reject maker
rejects = append(rejects, &oldestOrder)
err = tomoXstatedb.CancelOrder(orderBook, &oldestOrder)
if err != nil {
return nil, nil, nil, err
}
continue
} else { // reject Taker
rejects = append(rejects, order)
quantityToTrade = tomox_state.Zero
break
}
}
} else if err != nil {
return nil, nil, nil, err
}
if tradedQuantity.Sign() == 0 && !rejectMaker {
log.Debug("Reject order Taker ", "tradedQuantity", tradedQuantity, "rejectMaker", rejectMaker)
rejects = append(rejects, order)
quantityToTrade = tomox_state.Zero
break
}
if tradedQuantity.Sign() > 0 {
quantityToTrade = tomox_state.Sub(quantityToTrade, tradedQuantity)
tomoXstatedb.SubAmountOrderItem(orderBook, orderId, price, tradedQuantity, side)
tomoXstatedb.SetPrice(orderBook, price)
log.Debug("Update quantity for orderId", "orderId", orderId.Hex())
log.Debug("TRADE", "orderBook", orderBook, "Taker price", price, "maker price", order.Price, "Amount", tradedQuantity, "orderId", orderId, "side", side)
tradeRecord := make(map[string]string)
tradeRecord[TradeTakerOrderHash] = order.Hash.Hex()
tradeRecord[TradeMakerOrderHash] = oldestOrder.Hash.Hex()
tradeRecord[TradeTimestamp] = strconv.FormatInt(time.Now().Unix(), 10)
tradeRecord[TradeQuantity] = tradedQuantity.String()
tradeRecord[TradeMakerExchange] = oldestOrder.ExchangeAddress.String()
tradeRecord[TradeMaker] = oldestOrder.UserAddress.String()
tradeRecord[TradeBaseToken] = oldestOrder.BaseToken.String()
tradeRecord[TradeQuoteToken] = oldestOrder.QuoteToken.String()
// maker price is actual price
// Taker price is offer price
// tradedPrice is always actual price
tradeRecord[TradePrice] = oldestOrder.Price.String()
tradeRecord[MakerOrderType] = oldestOrder.Type
trades = append(trades, tradeRecord)
}
if rejectMaker {
rejects = append(rejects, &oldestOrder)
err := tomoXstatedb.CancelOrder(orderBook, &oldestOrder)
if err != nil {
return nil, nil, nil, err
}
}
}
return quantityToTrade, trades, rejects, nil
}
func (tomox *TomoX) getTradeQuantity(quotePrice *big.Int, coinbase common.Address, chain consensus.ChainContext, statedb *state.StateDB, takerOrder *tomox_state.OrderItem, makerOrder *tomox_state.OrderItem, quantityToTrade *big.Int) (*big.Int, bool, error) {
baseTokenDecimal, err := tomox.GetTokenDecimal(chain, statedb, coinbase, makerOrder.BaseToken)
if err != nil || baseTokenDecimal.Sign() == 0 {
return tomox_state.Zero, false, fmt.Errorf("Fail to get tokenDecimal. Token: %v . Err: %v", makerOrder.BaseToken.String(), err)
}
quoteTokenDecimal, err := tomox.GetTokenDecimal(chain, statedb, coinbase, makerOrder.QuoteToken)
if err != nil || quoteTokenDecimal.Sign() == 0 {
return tomox_state.Zero, false, fmt.Errorf("Fail to get tokenDecimal. Token: %v . Err: %v", makerOrder.QuoteToken.String(), err)
}
if makerOrder.QuoteToken.String() == common.TomoNativeAddress {
quotePrice = quoteTokenDecimal
}
if takerOrder.ExchangeAddress.String() == makerOrder.ExchangeAddress.String() {
if err := tomox_state.CheckRelayerFee(takerOrder.ExchangeAddress, new(big.Int).Mul(common.RelayerFee, big.NewInt(2)), statedb); err != nil {
log.Debug("Reject order Taker Exchnage = Maker Exchange , relayer not enough fee ", "err", err)
return tomox_state.Zero, false, nil
}
} else {
if err := tomox_state.CheckRelayerFee(takerOrder.ExchangeAddress, common.RelayerFee, statedb); err != nil {
log.Debug("Reject order Taker , relayer not enough fee ", "err", err)
return tomox_state.Zero, false, nil
}
if err := tomox_state.CheckRelayerFee(makerOrder.ExchangeAddress, common.RelayerFee, statedb); err != nil {
log.Debug("Reject order maker , relayer not enough fee ", "err", err)
return tomox_state.Zero, true, nil
}
}
takerFeeRate := tomox_state.GetExRelayerFee(takerOrder.ExchangeAddress, statedb)
makerFeeRate := tomox_state.GetExRelayerFee(makerOrder.ExchangeAddress, statedb)
var takerBalance, makerBalance *big.Int
switch takerOrder.Side {
case tomox_state.Bid:
takerBalance = tomox_state.GetTokenBalance(takerOrder.UserAddress, makerOrder.QuoteToken, statedb)
makerBalance = tomox_state.GetTokenBalance(makerOrder.UserAddress, makerOrder.BaseToken, statedb)
case tomox_state.Ask:
takerBalance = tomox_state.GetTokenBalance(takerOrder.UserAddress, makerOrder.BaseToken, statedb)
makerBalance = tomox_state.GetTokenBalance(makerOrder.UserAddress, makerOrder.QuoteToken, statedb)
default:
takerBalance = big.NewInt(0)
makerBalance = big.NewInt(0)
}
quantity, rejectMaker := GetTradeQuantity(takerOrder.Side, takerFeeRate, takerBalance, makerOrder.Price, makerFeeRate, makerBalance, baseTokenDecimal, quantityToTrade)
log.Debug("GetTradeQuantity", "side", takerOrder.Side, "takerBalance", takerBalance, "makerBalance", makerBalance, "BaseToken", makerOrder.BaseToken, "QuoteToken", makerOrder.QuoteToken, "quantity", quantity, "rejectMaker", rejectMaker, "quotePrice", quotePrice)
if quantity.Sign() > 0 {
// Apply Match Order
settleBalanceResult, err := tomox_state.GetSettleBalance(quotePrice, takerOrder.Side, takerFeeRate, makerOrder.BaseToken, makerOrder.QuoteToken, makerOrder.Price, makerFeeRate, baseTokenDecimal, quoteTokenDecimal, quantity)
log.Debug("GetSettleBalance", "settleBalanceResult", settleBalanceResult, "err", err)
if err == nil {
err = DoSettleBalance(coinbase, takerOrder, makerOrder, settleBalanceResult, statedb)
}
return quantity, rejectMaker, err
}
return quantity, rejectMaker, nil
}
func GetTradeQuantity(takerSide string, takerFeeRate *big.Int, takerBalance *big.Int, makerPrice *big.Int, makerFeeRate *big.Int, makerBalance *big.Int, baseTokenDecimal *big.Int, quantityToTrade *big.Int) (*big.Int, bool) {
if takerSide == tomox_state.Bid {
// maker InQuantity quoteTokenQuantity=(quantityToTrade*maker.Price/baseTokenDecimal)
quoteTokenQuantity := new(big.Int).Mul(quantityToTrade, makerPrice)
quoteTokenQuantity = quoteTokenQuantity.Div(quoteTokenQuantity, baseTokenDecimal)
// Fee
// charge on the token he/she has before the trade, in this case: quoteToken
// charge on the token he/she has before the trade, in this case: baseToken
// takerFee = quoteTokenQuantity*takerFeeRate/baseFee=(quantityToTrade*maker.Price/baseTokenDecimal) * makerFeeRate/baseFee
takerFee := big.NewInt(0).Mul(quoteTokenQuantity, takerFeeRate)
takerFee = big.NewInt(0).Div(takerFee, common.TomoXBaseFee)
//takerOutTotal= quoteTokenQuantity + takerFee = quantityToTrade*maker.Price/baseTokenDecimal + quantityToTrade*maker.Price/baseTokenDecimal * takerFeeRate/baseFee
// = quantityToTrade * maker.Price/baseTokenDecimal ( 1 + takerFeeRate/baseFee)
// = quantityToTrade * maker.Price * (baseFee + takerFeeRate ) / ( baseTokenDecimal * baseFee)
takerOutTotal := new(big.Int).Add(quoteTokenQuantity, takerFee)
makerOutTotal := quantityToTrade
if takerBalance.Cmp(takerOutTotal) >= 0 && makerBalance.Cmp(makerOutTotal) >= 0 {
return quantityToTrade, false
} else if takerBalance.Cmp(takerOutTotal) < 0 && makerBalance.Cmp(makerOutTotal) >= 0 {
newQuantityTrade := new(big.Int).Mul(takerBalance, baseTokenDecimal)
newQuantityTrade = newQuantityTrade.Mul(newQuantityTrade, common.TomoXBaseFee)
newQuantityTrade = newQuantityTrade.Div(newQuantityTrade, new(big.Int).Add(common.TomoXBaseFee, takerFeeRate))
newQuantityTrade = newQuantityTrade.Div(newQuantityTrade, makerPrice)
if newQuantityTrade.Sign() == 0 {
log.Debug("Reject order Taker , not enough balance ", "takerSide", takerSide, "takerBalance", takerBalance, "takerOutTotal", takerOutTotal)
}
return newQuantityTrade, false
} else if takerBalance.Cmp(takerOutTotal) >= 0 && makerBalance.Cmp(makerOutTotal) < 0 {
log.Debug("Reject order maker , not enough balance ", "makerBalance", makerBalance, " makerOutTotal", makerOutTotal)
return makerBalance, true
} else {
// takerBalance.Cmp(takerOutTotal) < 0 && makerBalance.Cmp(makerOutTotal) < 0
newQuantityTrade := new(big.Int).Mul(takerBalance, baseTokenDecimal)
newQuantityTrade = newQuantityTrade.Mul(newQuantityTrade, common.TomoXBaseFee)
newQuantityTrade = newQuantityTrade.Div(newQuantityTrade, new(big.Int).Add(common.TomoXBaseFee, takerFeeRate))
newQuantityTrade = newQuantityTrade.Div(newQuantityTrade, makerPrice)
if newQuantityTrade.Cmp(makerBalance) <= 0 {
if newQuantityTrade.Sign() == 0 {
log.Debug("Reject order Taker , not enough balance ", "takerSide", takerSide, "takerBalance", takerBalance, "makerBalance", makerBalance, " newQuantityTrade ", newQuantityTrade)
}
return newQuantityTrade, false
}
log.Debug("Reject order maker , not enough balance ", "takerSide", takerSide, "takerBalance", takerBalance, "makerBalance", makerBalance, " newQuantityTrade ", newQuantityTrade)
return makerBalance, true
}
} else {
// Taker InQuantity
// quoteTokenQuantity = quantityToTrade * makerPrice / baseTokenDecimal
quoteTokenQuantity := new(big.Int).Mul(quantityToTrade, makerPrice)
quoteTokenQuantity = quoteTokenQuantity.Div(quoteTokenQuantity, baseTokenDecimal)
// maker InQuantity
// Fee
// charge on the token he/she has before the trade, in this case: baseToken
// makerFee = quoteTokenQuantity * makerFeeRate / baseFee = quantityToTrade * makerPrice / baseTokenDecimal * makerFeeRate / baseFee
// charge on the token he/she has before the trade, in this case: quoteToken
makerFee := new(big.Int).Mul(quoteTokenQuantity, makerFeeRate)
makerFee = makerFee.Div(makerFee, common.TomoXBaseFee)
takerOutTotal := quantityToTrade
// makerOutTotal = quoteTokenQuantity + makerFee = quantityToTrade * makerPrice / baseTokenDecimal + quantityToTrade * makerPrice / baseTokenDecimal * makerFeeRate / baseFee
// = quantityToTrade * makerPrice / baseTokenDecimal * (1+makerFeeRate / baseFee)
// = quantityToTrade * makerPrice * (baseFee + makerFeeRate) / ( baseTokenDecimal * baseFee )
makerOutTotal := new(big.Int).Add(quoteTokenQuantity, makerFee)
if takerBalance.Cmp(takerOutTotal) >= 0 && makerBalance.Cmp(makerOutTotal) >= 0 {
return quantityToTrade, false
} else if takerBalance.Cmp(takerOutTotal) < 0 && makerBalance.Cmp(makerOutTotal) >= 0 {
if takerBalance.Sign() == 0 {
log.Debug("Reject order Taker , not enough balance ", "takerSide", takerSide, "takerBalance", takerBalance, "takerOutTotal", takerOutTotal)
}
return takerBalance, false
} else if takerBalance.Cmp(takerOutTotal) >= 0 && makerBalance.Cmp(makerOutTotal) < 0 {
newQuantityTrade := new(big.Int).Mul(makerBalance, baseTokenDecimal)
newQuantityTrade = newQuantityTrade.Mul(newQuantityTrade, common.TomoXBaseFee)
newQuantityTrade = newQuantityTrade.Div(newQuantityTrade, new(big.Int).Add(common.TomoXBaseFee, makerFeeRate))
newQuantityTrade = newQuantityTrade.Div(newQuantityTrade, makerPrice)
log.Debug("Reject order maker , not enough balance ", "makerBalance", makerBalance, " makerOutTotal", makerOutTotal)
return newQuantityTrade, true
} else {
// takerBalance.Cmp(takerOutTotal) < 0 && makerBalance.Cmp(makerOutTotal) < 0
newQuantityTrade := new(big.Int).Mul(makerBalance, baseTokenDecimal)
newQuantityTrade = newQuantityTrade.Mul(newQuantityTrade, common.TomoXBaseFee)
newQuantityTrade = newQuantityTrade.Div(newQuantityTrade, new(big.Int).Add(common.TomoXBaseFee, makerFeeRate))
newQuantityTrade = newQuantityTrade.Div(newQuantityTrade, makerPrice)
if newQuantityTrade.Cmp(takerBalance) <= 0 {
log.Debug("Reject order maker , not enough balance ", "takerSide", takerSide, "takerBalance", takerBalance, "makerBalance", makerBalance, " newQuantityTrade ", newQuantityTrade)
return newQuantityTrade, true
}
if takerBalance.Sign() == 0 {
log.Debug("Reject order Taker , not enough balance ", "takerSide", takerSide, "takerBalance", takerBalance, "makerBalance", makerBalance, " newQuantityTrade ", newQuantityTrade)
}
return takerBalance, false
}
}
}
func DoSettleBalance(coinbase common.Address, takerOrder, makerOrder *tomox_state.OrderItem, settleBalance *tomox_state.SettleBalance, statedb *state.StateDB) error {
takerExOwner := tomox_state.GetRelayerOwner(takerOrder.ExchangeAddress, statedb)
makerExOwner := tomox_state.GetRelayerOwner(makerOrder.ExchangeAddress, statedb)
matchingFee := big.NewInt(0)
// masternodes charges fee of both 2 relayers. If maker and Taker are on same relayer, that relayer is charged fee twice
matchingFee = matchingFee.Add(matchingFee, common.RelayerFee)
matchingFee = matchingFee.Add(matchingFee, common.RelayerFee)
if common.EmptyHash(takerExOwner.Hash()) || common.EmptyHash(makerExOwner.Hash()) {
return fmt.Errorf("Echange owner empty , Taker: %v , maker : %v ", takerExOwner, makerExOwner)
}
mapBalances := map[common.Address]map[common.Address]*big.Int{}
//Checking balance
newTakerInTotal, err := tomox_state.CheckAddTokenBalance(takerOrder.UserAddress, settleBalance.Taker.InTotal, settleBalance.Taker.InToken, statedb, mapBalances)
if err != nil {
return err
}
if mapBalances[settleBalance.Taker.InToken] == nil {
mapBalances[settleBalance.Taker.InToken] = map[common.Address]*big.Int{}
}
mapBalances[settleBalance.Taker.InToken][takerOrder.UserAddress] = newTakerInTotal
newTakerOutTotal, err := tomox_state.CheckSubTokenBalance(takerOrder.UserAddress, settleBalance.Taker.OutTotal, settleBalance.Taker.OutToken, statedb, mapBalances)
if err != nil {
return err
}
if mapBalances[settleBalance.Taker.OutToken] == nil {
mapBalances[settleBalance.Taker.OutToken] = map[common.Address]*big.Int{}
}
mapBalances[settleBalance.Taker.OutToken][takerOrder.UserAddress] = newTakerOutTotal
newMakerInTotal, err := tomox_state.CheckAddTokenBalance(makerOrder.UserAddress, settleBalance.Maker.InTotal, settleBalance.Maker.InToken, statedb, mapBalances)
if err != nil {
return err
}
if mapBalances[settleBalance.Maker.InToken] == nil {
mapBalances[settleBalance.Maker.InToken] = map[common.Address]*big.Int{}
}
mapBalances[settleBalance.Maker.InToken][makerOrder.UserAddress] = newMakerInTotal
newMakerOutTotal, err := tomox_state.CheckSubTokenBalance(makerOrder.UserAddress, settleBalance.Maker.OutTotal, settleBalance.Maker.OutToken, statedb, mapBalances)
if err != nil {
return err
}
if mapBalances[settleBalance.Maker.OutToken] == nil {
mapBalances[settleBalance.Maker.OutToken] = map[common.Address]*big.Int{}
}
mapBalances[settleBalance.Maker.OutToken][makerOrder.UserAddress] = newMakerOutTotal
newTakerFee, err := tomox_state.CheckAddTokenBalance(takerExOwner, settleBalance.Taker.Fee, makerOrder.QuoteToken, statedb, mapBalances)
if err != nil {
return err
}
if mapBalances[makerOrder.QuoteToken] == nil {
mapBalances[makerOrder.QuoteToken] = map[common.Address]*big.Int{}
}
mapBalances[makerOrder.QuoteToken][takerExOwner] = newTakerFee
newMakerFee, err := tomox_state.CheckAddTokenBalance(makerExOwner, settleBalance.Maker.Fee, makerOrder.QuoteToken, statedb, mapBalances)
if err != nil {
return err
}
mapBalances[makerOrder.QuoteToken][makerExOwner] = newMakerFee
mapRelayerFee := map[common.Address]*big.Int{}
newRelayerTakerFee, err := tomox_state.CheckSubRelayerFee(takerOrder.ExchangeAddress, common.RelayerFee, statedb, mapRelayerFee)
if err != nil {
return err
}
mapRelayerFee[takerOrder.ExchangeAddress] = newRelayerTakerFee
newRelayerMakerFee, err := tomox_state.CheckSubRelayerFee(makerOrder.ExchangeAddress, common.RelayerFee, statedb, mapRelayerFee)
if err != nil {
return err
}
mapRelayerFee[makerOrder.ExchangeAddress] = newRelayerMakerFee
tomox_state.SetSubRelayerFee(takerOrder.ExchangeAddress, newRelayerTakerFee, common.RelayerFee, statedb)
tomox_state.SetSubRelayerFee(makerOrder.ExchangeAddress, newRelayerMakerFee, common.RelayerFee, statedb)
masternodeOwner := statedb.GetOwner(coinbase)
statedb.AddBalance(masternodeOwner, matchingFee)
tomox_state.SetTokenBalance(takerOrder.UserAddress, newTakerInTotal, settleBalance.Taker.InToken, statedb)
tomox_state.SetTokenBalance(takerOrder.UserAddress, newTakerOutTotal, settleBalance.Taker.OutToken, statedb)
tomox_state.SetTokenBalance(makerOrder.UserAddress, newMakerInTotal, settleBalance.Maker.InToken, statedb)
tomox_state.SetTokenBalance(makerOrder.UserAddress, newMakerOutTotal, settleBalance.Maker.OutToken, statedb)
// add balance for relayers
//log.Debug("ApplyTomoXMatchedTransaction settle fee for relayers",
// "takerRelayerOwner", takerExOwner,
// "takerFeeToken", quoteToken, "takerFee", settleBalanceResult[takerAddr][tomox.Fee].(*big.Int),
// "makerRelayerOwner", makerExOwner,
// "makerFeeToken", quoteToken, "makerFee", settleBalanceResult[makerAddr][tomox.Fee].(*big.Int))
// takerFee
tomox_state.SetTokenBalance(takerExOwner, newTakerFee, makerOrder.QuoteToken, statedb)
tomox_state.SetTokenBalance(makerExOwner, newMakerFee, makerOrder.QuoteToken, statedb)
return nil
}
func (tomox *TomoX) ProcessCancelOrder(tomoXstatedb *tomox_state.TomoXStateDB, statedb *state.StateDB, chain consensus.ChainContext, coinbase common.Address, orderBook common.Hash, order *tomox_state.OrderItem) (error, bool) {
if err := tomox_state.CheckRelayerFee(order.ExchangeAddress, common.RelayerCancelFee, statedb); err != nil {
log.Debug("Relayer not enough fee when cancel order", "err", err)
return nil, true
}
baseTokenDecimal, err := tomox.GetTokenDecimal(chain, statedb, coinbase, order.BaseToken)
if err != nil || baseTokenDecimal.Sign() == 0 {
log.Debug("Fail to get tokenDecimal ", "Token", order.BaseToken.String(), "err", err)
return err, false
}
originOrder := tomoXstatedb.GetOrder(orderBook, common.BigToHash(new(big.Int).SetUint64(order.OrderID)))
var tokenBalance *big.Int
switch originOrder.Side {
case tomox_state.Ask:
tokenBalance = tomox_state.GetTokenBalance(order.UserAddress, order.BaseToken, statedb)
case tomox_state.Bid:
tokenBalance = tomox_state.GetTokenBalance(order.UserAddress, order.QuoteToken, statedb)
default:
log.Debug("Not found order side", "Side", originOrder.Side)
return nil, false
}
log.Debug("ProcessCancelOrder", "baseToken", order.BaseToken, "quoteToken", order.QuoteToken)
feeRate := tomox_state.GetExRelayerFee(order.ExchangeAddress, statedb)
tokenCancelFee := getCancelFee(baseTokenDecimal, feeRate, order)
if tokenBalance.Cmp(tokenCancelFee) < 0 {
log.Debug("User not enough balance when cancel order", "Side", originOrder.Side, "balance", tokenBalance, "fee", tokenCancelFee)
return nil, true
}
err = tomoXstatedb.CancelOrder(orderBook, order)
if err != nil {
log.Debug("Error when cancel order", "order", order)
return err, false
}
tomox_state.SubRelayerFee(order.ExchangeAddress, common.RelayerCancelFee, statedb)
switch originOrder.Side {
case tomox_state.Ask:
tomox_state.SubTokenBalance(order.UserAddress, tokenCancelFee, order.BaseToken, statedb)
case tomox_state.Bid:
tomox_state.SubTokenBalance(order.UserAddress, tokenCancelFee, order.QuoteToken, statedb)
default:
}
masternodeOwner := statedb.GetOwner(coinbase)
statedb.AddBalance(masternodeOwner, common.RelayerCancelFee)
return nil, false
}
func getCancelFee(baseTokenDecimal *big.Int, feeRate *big.Int, order *tomox_state.OrderItem) *big.Int {
cancelFee := big.NewInt(0)
if order.Side == tomox_state.Ask {
// SELL 1 BTC => TOMO ,,
// order.Quantity =1 && fee rate =2
// ==> cancel fee = 2/10000
baseTokenQuantity := new(big.Int).Mul(order.Quantity, baseTokenDecimal)
cancelFee = new(big.Int).Mul(baseTokenQuantity, feeRate)
cancelFee = new(big.Int).Div(cancelFee, common.TomoXBaseCancelFee)
} else {
// BUY 1 BTC => TOMO with Price : 10000
// quoteTokenQuantity = 10000 && fee rate =2
// => cancel fee =2
quoteTokenQuantity := new(big.Int).Mul(order.Quantity, order.Price)
quoteTokenQuantity = quoteTokenQuantity.Div(quoteTokenQuantity, baseTokenDecimal)
// Fee
// makerFee = quoteTokenQuantity * feeRate / baseFee = quantityToTrade * makerPrice / baseTokenDecimal * feeRate / baseFee
cancelFee = new(big.Int).Mul(quoteTokenQuantity, feeRate)
cancelFee = new(big.Int).Div(quoteTokenQuantity, common.TomoXBaseCancelFee)
}
return cancelFee
}