-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsmartRouteAlgorithms.js
More file actions
1678 lines (1574 loc) · 47.4 KB
/
smartRouteAlgorithms.js
File metadata and controls
1678 lines (1574 loc) · 47.4 KB
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
const { default: Big } = require('big.js')
//const { poolList } = require('./testPoolsData.js')
Big.DP = 40
Big.NE = -40
Big.PE = 40
// Is any configuration needed to do floor or enforce the number of decimal places?
function getBetaForRoute(route, path) {
if (!route.length) {
route = [route]
}
if (route.length == 1) {
let p = route[0]
var beta = new Big(p.reserves[path[0]])
} else if (route.length == 2) {
let p1 = route[0]
let p2 = route[1]
var beta = new Big(p1.reserves[path[0]]).times(
new Big(p2.reserves[path[1]]),
)
}
return beta
}
function getEpsilonForRoute(route, path) {
if (!route.length) {
route = [route]
}
if (route.length == 1) {
// Single Hop case
let p = route[0]
let gamma = new Big(10000).minus(new Big(p.fee)).div(new Big(10000))
var epsilon = Big(gamma)
} else if (route.length == 2) {
//Double Hop Case
let p1 = route[0]
let p2 = route[1]
let gamma1 = new Big(10000).minus(new Big(p1.fee)).div(new Big(10000))
let gamma2 = new Big(10000).minus(new Big(p2.fee)).div(Big(10000))
var epsilon = new Big(p2.reserves[path[1]])
.times(new Big(gamma1))
.plus(new Big(p1.reserves[path[1]]).times(gamma1).times(gamma2))
}
return epsilon
}
function getAlphaForRoute(route, path) {
if (!route.length) {
route = [route]
}
if (route.length == 1) {
//console.log('single hop')
let p = route[0]
let inputToken = path[0]
let outputToken = path[1]
let gamma = new Big(10000).minus(new Big(p.fee)).div(new Big(10000))
let key1 = p.token1Id
let key2 = p.token2Id
let val1 = p.token1Supply
let val2 = p.token2Supply
p['reserves'] = { [key1]: val1, [key2]: val2 }
var alpha = new Big(p.reserves[inputToken]).times(
new Big(p.reserves[outputToken]).times(new Big(gamma)),
)
} else if (route.length == 2) {
//console.log('double hop')
let p1 = route[0]
let p2 = route[1]
let key11 = p1.token1Id
let key12 = p1.token2Id
let val11 = p1.token1Supply
let val12 = p1.token2Supply
p1['reserves'] = { [key11]: val11, [key12]: val12 }
let key21 = p2.token1Id
let key22 = p2.token2Id
let val21 = p2.token1Supply
let val22 = p2.token2Supply
p2['reserves'] = { [key21]: val21, [key22]: val22 }
let inputToken = path[0]
let middleToken = path[1]
let outputToken = path[2]
let gamma1 = new Big(10000).minus(Big(p1.fee)).div(new Big(10000))
let gamma2 = new Big(10000).minus(new Big(p2.fee)).div(new Big(10000))
let alpha1 = new Big(p1.reserves[inputToken])
.times(new Big(p1.reserves[middleToken]))
.times(gamma1)
let alpha2 = new Big(p2.reserves[middleToken])
.times(new Big(p2.reserves[outputToken]))
.times(gamma2)
var alpha = alpha1.times(alpha2)
}
return alpha
}
function getAlphaSumFromRoutes(routes, nodeRoutes) {
let alphaSum = new Big(0)
for (var i in routes) {
let route = routes[i]
let nodeRoute = nodeRoutes[i]
let alpha = getAlphaForRoute(route, nodeRoute)
let radical = new Big(alpha).sqrt()
let epsilon = getEpsilonForRoute(route, nodeRoute)
let denom = new Big(epsilon)
alphaSum = alphaSum.plus(radical.div(denom))
}
return alphaSum
}
function getBetaSumFromRoutes(routes, nodeRoutes) {
let betaSum = new Big(0)
for (var i in routes) {
let route = routes[i]
let nodeRoute = nodeRoutes[i]
let num = new Big(getBetaForRoute(route, nodeRoute))
let denom = new Big(getEpsilonForRoute(route, nodeRoute))
betaSum = betaSum.plus(num.div(denom))
}
return betaSum
}
function getPhiFromRoutes(routes, nodeRoutes, totalInput) {
let alphaSum = getAlphaSumFromRoutes(routes, nodeRoutes)
let betaSum = getBetaSumFromRoutes(routes, nodeRoutes)
let phi = new Big(totalInput).plus(betaSum).div(alphaSum)
return phi
}
function getAllocationForRoute(phi, route, path) {
let alpha = getAlphaForRoute(route, path)
let beta = getBetaForRoute(route, path)
let epsilon = getEpsilonForRoute(route, path)
let allocation = new Big(phi)
.abs()
.times(new Big(alpha).sqrt())
.minus(beta)
.div(epsilon)
return allocation
}
function getAllocationVectorForRoutes(phi, routes, nodeRoutes) {
let allocationVec = []
for (var i in routes) {
allocationVec.push(getAllocationForRoute(phi, routes[i], nodeRoutes[i]))
}
return allocationVec
}
function getOptimalAllocationForRoutes(routes, nodeRoutes, totalInput) {
var totalInput = new Big(totalInput)
let phi = getPhiFromRoutes(routes, nodeRoutes, totalInput)
let allocations = getAllocationVectorForRoutes(phi, routes, nodeRoutes)
if (allocations.every((item) => item.lt(new Big(0)))) {
allocations = allocations.map((item) => item.times(new Big(-1.0)))
}
if (allocations.some((item) => item.lt(new Big(0)))) {
allocations = reduceRoutes(routes, nodeRoutes, allocations, totalInput)
}
let sumAllocations = allocations.reduce((a, b) => a.plus(b), new Big(0))
let normalizedAllocations = allocations.map((a) =>
a.div(sumAllocations).times(new Big(totalInput)),
)
return normalizedAllocations
}
function reduceRoutes(routes, nodeRoutes, allocationVec, totalInput) {
var totalInput = new Big(totalInput)
let goodIndices = []
for (var i in allocationVec) {
let dx = allocationVec[i]
if (dx.gt(new Big(0))) {
goodIndices.push(i)
}
}
let newRoutes = []
let newNodeRoutes = []
for (var i in goodIndices) {
let goodIndex = goodIndices[i]
newRoutes.push(routes[goodIndex])
newNodeRoutes.push(nodeRoutes[goodIndex])
}
allocationVec = getOptimalAllocationForRoutes(
newRoutes,
newNodeRoutes,
totalInput,
)
let allocationDict = {}
for (var i in goodIndices) {
allocationDict[goodIndices[i]] = allocationVec[i]
}
var allocationVecNew = []
for (var i in routes) {
if (goodIndices.includes(i)) {
allocationVecNew.push(allocationDict[i])
} else {
let zeroAllocation = new Big(0)
allocationVecNew.push(zeroAllocation)
}
}
return allocationVecNew
}
function getNodeRoutesFromPathsAndPoolChains(paths, poolChains) {
let multiplicity = []
for (var i in poolChains) {
let pc = poolChains[i]
let mul = pc
.map((item) => item.length)
.reduce((elem1, elem2) => elem1 * elem2, 1)
multiplicity.push(mul)
}
let nodeRoutes = []
for (var j in paths) {
let path = paths[j]
let m = multiplicity[j]
for (var k = 0; k < m; k++) {
nodeRoutes.push(path)
}
}
return nodeRoutes
}
function getPoolChainFromPaths(paths, pools, threshold = 0.001) {
let poolChains = []
for (var pathInd in paths) {
let path = paths[pathInd]
let chain = []
let pairs = []
for (var i = 0; i < path.length - 1; i++) {
pairs.push([path[i], path[i + 1]])
}
for (var pairInd in pairs) {
let pair = pairs[pairInd]
let tokenPools = getPoolsByToken1ANDToken2(pools, pair[0], pair[1])
chain.push(tokenPools)
}
poolChains.push(chain)
}
// return poolChains;
let culledPoolChains = getCulledPoolChains(poolChains, threshold)
return culledPoolChains
}
function getCulledPoolChains(poolChains, threshold = 0.001) {
let newChains = []
for (var pathInd in poolChains) {
let path = poolChains[pathInd]
let newPath = []
for (var legInd in path) {
let leg = path[legInd]
let culledPath = cullPoolsWithInsufficientLiquidity(leg, threshold)
newPath.push(culledPath)
}
newChains.push(newPath)
}
return newChains
}
function getRoutesFromPoolChain(poolChains) {
let routes = []
for (var pci in poolChains) {
let poolChain = poolChains[pci]
//get cartesian product of each pool chain to get the list of routes.
let newRoutes = cartesianProduct(poolChain)
routes.push(...newRoutes)
}
return routes
}
function getOutputSingleHop(pool, inputToken, outputToken, totalInput) {
var totalInput = new Big(totalInput)
// check if pool is forward or backward for inputToken/outputToken cf. token1Id/token2Id
if (inputToken === pool.token1Id && outputToken === pool.token2Id) {
// forward Pool
var reserves = {
[inputToken]: new Big(pool.token1Supply),
[outputToken]: new Big(pool.token2Supply),
}
} else if (inputToken === pool.token2Id && outputToken === pool.token1Id) {
// reverse pool
var reserves = {
[outputToken]: new Big(pool.token1Supply),
[inputToken]: new Big(pool.token2Supply),
}
} else {
//got the wrong pool.
console.log(
`INPUT TOKENS ${inputToken} and ${outputToken} DO NOT EXIST IN THIS POOL, which contains ${pool.token1Id} and ${pool.token2Id}`,
)
return new Big(0)
}
let gamma = new Big(10000).minus(new Big(pool.fee)).div(new Big(10000))
let num = totalInput.times(gamma).times(reserves[outputToken])
let denom = reserves[inputToken].plus(gamma.times(totalInput))
return num.div(denom)
}
function getOutputDoubleHop(
pools,
inputToken,
middleToken,
outputToken,
totalInput,
) {
var totalInput = new Big(totalInput)
for (var poolIndex in pools) {
let p = pools[poolIndex]
p['gamma'] = new Big(10000).minus(new Big(p.fee)).div(new Big(10000))
}
let p1 = pools[0]
let p2 = pools[1]
if (inputToken === p1.token1Id && middleToken === p1.token2Id) {
// forward Pool
p1['reserves'] = {
inputToken: new Big(p1.token1Supply),
middleToken: new Big(p1.token2Supply),
}
} else if (middleToken === p1.token1Id && inputToken === p1.token2Id) {
//reverse pool
p1['reserves'] = {
middleToken: new Big(p1.token1Supply),
inputToken: new Big(p1.token2Supply),
}
}
if (middleToken === p2.token1Id && outputToken === p2.token2Id) {
// forward Pool
p2['reserves'] = {
middleToken: new Big(p2.token1Supply),
outputToken: new Big(p2.token2Supply),
}
} else if (outputToken === p2.token1Id && middleToken === p2.token2Id) {
//reverse pool
p2['reserves'] = {
outputToken: new Big(p2.token1Supply),
middleToken: new Big(p2.token2Supply),
}
}
let c1 = new Big(p1.reserves.middleToken)
let a1 = new Big(p1.reserves.inputToken)
let c2 = new Big(p2.reserves.middleToken)
let b2 = new Big(p2.reserves.outputToken)
let gamma1 = p1.gamma
let gamma2 = p2.gamma
let num = totalInput.times(c1).times(b2).times(gamma1).times(gamma2)
let denom = c2
.times(a1)
.plus(
totalInput.times(c2.times(gamma1).plus(c1.times(gamma1).times(gamma2))),
)
// denom = c2*a1 + totalInput * (c2*gamma1 + c1*gamma1*gamma2)
return num.div(denom)
}
function getOutputFromRoute(route, nodeRoute, allocation) {
if (new Big(allocation).eq(new Big(0))) {
return new Big(0)
} else {
var allocation = new Big(allocation)
}
if (!route.length) {
route = [route]
}
if (route.length == 1) {
// single hop
let inputToken = nodeRoute[0]
let outputToken = nodeRoute[1]
let pool = route[0]
var output = getOutputSingleHop(pool, inputToken, outputToken, allocation)
} else if (route.length == 2) {
// DOUBLE HOP
let inputToken = nodeRoute[0]
let middleToken = nodeRoute[1]
let outputToken = nodeRoute[2]
let pools = route
var output = getOutputDoubleHop(
pools,
inputToken,
middleToken,
outputToken,
allocation,
)
}
return output
}
function getOptOutputVec(routes, nodeRoutes, totalInput) {
let allocations = getOptimalAllocationForRoutes(
routes,
nodeRoutes,
totalInput,
)
let result = []
for (var i in routes) {
let route = routes[i]
let nodeRoute = nodeRoutes[i]
let allocation = allocations[i]
let output = getOutputFromRoute(route, nodeRoute, allocation)
result.push(output)
}
return {
result: result,
allocations: allocations,
}
//NOTE -- I made this return an object instead of the tuple returned in python. need to check the places it is called, and specify
// result field instead of tuple 0 position, and allocations field instead of tuple 1 position.
}
function getBestOptOutput(routes, nodeRoutes, totalInput) {
let outputRefined = getOptOutputVecRefined(routes, nodeRoutes, totalInput)
.result
let outputRaw = getOptOutputVec(routes, nodeRoutes, totalInput).result
let res1 = new Big(0)
let res2 = new Big(0)
for (var n in outputRefined) {
res1 = res1.plus(outputRefined[n])
}
for (var nn in outputRaw) {
res2 = res2.plus(outputRaw[nn])
}
if (res1.gt(res2)) {
return res1
} else {
return res2
}
}
function getBestOptInput(routes, nodeRoutes, totalInput) {
let refDict = getOptOutputVecRefined(routes, nodeRoutes, totalInput)
let outputRefined = refDict.result
let inputRefined = refDict.allocations
inputRefined = checkIntegerSumOfAllocations(inputRefined, totalInput)
let rawDict = getOptOutputVec(routes, nodeRoutes, totalInput)
let outputRaw = rawDict.result
let inputRaw = rawDict.allocations
inputRaw = checkIntegerSumOfAllocations(inputRaw, totalInput)
let res1 = new Big(0)
let res2 = new Big(0)
for (var n in outputRefined) {
res1 = res1.plus(outputRefined[n])
}
for (var nn in outputRaw) {
res2 = res2.plus(outputRaw[nn])
}
if (res1.gt(res2)) {
return inputRefined
} else {
return inputRaw
}
}
function getOptOutputVecRefined(routes, nodeRoutes, totalInput) {
let initLengthRoutes = routes.length
let directRouteInds = []
for (var routeInd in routes) {
let route = routes[routeInd]
if (!route.length) {
route = [route]
}
if (route.length == 1) {
directRouteInds.push(routeInd)
}
}
if (directRouteInds.length < 1) {
var allocations = getOptimalAllocationForRoutes(
routes,
nodeRoutes,
totalInput,
)
var result = []
for (var i in routes) {
let r = routes[i]
let nr = nodeRoutes[i]
let a = allocations[i]
let output = getOutputFromRoute(r, nr, a)
result.push(output)
}
} else {
// console.log('DOING SINGLE HOP ONLY')
let droutes = []
let dnodeRoutes = []
for (var dri in directRouteInds) {
let ind = directRouteInds[dri]
droutes.push(routes[ind])
dnodeRoutes.push(nodeRoutes[ind])
}
let dallocations = getOptimalAllocationForRoutes(
droutes,
dnodeRoutes,
totalInput,
)
let dallocDict = {}
for (var dd in dallocations) {
dallocDict[directRouteInds[dd]] = dallocations[dd]
}
var allocations = []
for (var ii = 0; ii < initLengthRoutes; ii++) {
if (directRouteInds.includes(ii.toString())) {
//console.log('ADDING ALLOCATION FOR SINGLE ROUTE')
allocations.push(dallocDict[ii])
} else {
allocations.push(new Big(0))
}
}
var result = []
for (var j in routes) {
let route = routes[j]
let nodeRoute = nodeRoutes[j]
let allocation = allocations[j]
let output = getOutputFromRoute(route, nodeRoute, allocation)
result.push(output)
}
}
return {
result: result,
allocations: allocations,
}
}
// async function getBestOptimalAllocationsAndOutputs(
function getBestOptimalAllocationsAndOutputs(
pools,
inputToken,
outputToken,
totalInput,
) {
var totalInput = new Big(totalInput)
let paths = getPathsFromPools(pools, inputToken, outputToken)
let poolChains = getPoolChainFromPaths(paths, pools)
let routes = getRoutesFromPoolChain(poolChains)
let nodeRoutes = getNodeRoutesFromPathsAndPoolChains(paths, poolChains)
let allocations = getBestOptInput(routes, nodeRoutes, totalInput)
// fix integer rounding for allocations:
allocations = checkIntegerSumOfAllocations(allocations, totalInput)
let outputs = getBestOptOutput(routes, nodeRoutes, totalInput)
let result = {
allocations: allocations,
outputs: outputs,
routes: routes,
nodeRoutes: nodeRoutes,
}
// console.log('RESULT IS...\n\n\n')
// console.log(result)
return result
}
function getHopsFromRoutes(routes, nodeRoutes, allocations) {
let hops = []
for (var i in routes) {
var route = routes[i]
var nodeRoute = nodeRoutes[i]
var allocation = allocations[i]
if (!route.length) {
route = [route]
}
if (!route[0]) {
continue
}
let hop = {
pool: route[0],
allocation: allocation,
inputToken: nodeRoute[0],
outputToken: nodeRoute[1],
}
hops.push(hop)
}
return hops
}
function distillHopsByPool(hops) {
let distilledHops = []
let poolIds = []
let poolId2allocation = {}
for (var i in hops) {
let hop = hops[i]
if (hop.allocation === '0') {
continue
}
console.log(`HOP ${i} IS...`)
console.log(hop)
let poolId = hop.pool['id']
if (poolIds.includes(poolId)) {
poolId2allocation[poolId] = new Big(poolId2allocation[poolId])
.plus(new Big(hop.allocation))
.toString()
} else {
poolId2allocation[poolId] = new Big(hop.allocation).toString()
poolIds.push(poolId)
}
}
// let poolsWithOrder = [...new Set(...hops.map((item) => item.pool))]
let keys = Object.keys(poolId2allocation)
for (var j in keys) {
let poolId = keys[j]
let hop = hops.filter(
(item) => item.pool.id.toString() === poolId.toString(),
)[0]
let distilledHop = {
pool: hop.pool,
allocation: poolId2allocation[poolId],
inputToken: hop.inputToken,
outputToken: hop.outputToken,
}
distilledHops.push(distilledHop)
}
return distilledHops
}
function getDistilledHopActions(distilledHops, slippageTolerance) {
let actions = []
for (var i in distilledHops) {
let hop = distilledHops[i]
let expectedAmountOut = getOutputSingleHop(
hop.pool,
hop.inputToken,
hop.outputToken,
hop.allocation,
)
let minimumAmountOut = new Big(expectedAmountOut)
.times(new Big(1).minus(new Big(slippageTolerance).div(100)))
.round()
.toString() //Here, assume slippage tolerance is a percentage. So 1% would be 1.0
let action = {
pool_id: hop.pool.id,
token_in: hop.inputToken,
token_out: hop.outputToken,
amount_in: hop.allocation,
min_amount_out: minimumAmountOut,
}
actions.push(action)
}
return actions
}
function getMiddleTokenTotalsFromFirstHopActions(firstHopActions) {
let middleTokens = [...new Set(firstHopActions.map((item) => item.token_out))]
let middleTokenTotals = {}
for (var i in middleTokens) {
let middleToken = middleTokens[i]
let mtActions = firstHopActions.filter(
(item) => item.token_out === middleToken,
)
let mtTotal = mtActions
.map((item) => new Big(item.min_amount_out))
.reduce((a, b) => a.plus(b), new Big(0))
.toString()
middleTokenTotals[middleToken] = mtTotal
}
return middleTokenTotals
}
function getRoutesAndAllocationsForMiddleToken(
routes,
nodeRoutes,
allocations,
middleToken,
middleTokenTotal,
) {
// get routes that use middle token.
// (input route alloction) /sum(input allocations of routes with middle token) * (total_middleToken)
let mask = []
for (var i in nodeRoutes) {
if (nodeRoutes[i][1] === middleToken) {
mask.push(true)
} else {
mask.push(false)
}
}
let froutes = []
let fallocations = []
let fnoderoutes = []
for (var i in routes) {
if (mask[i]) {
froutes.push(routes[i])
fallocations.push(allocations[i])
fnoderoutes.push(nodeRoutes[i])
}
}
let sumfallocations = fallocations.reduce(
(a, b) => new Big(a).plus(new Big(b)),
new Big(0),
)
let middleAllocations = fallocations.map((item) =>
new Big(item).div(sumfallocations).times(new Big(middleTokenTotal)),
)
let secondHopRoutes = froutes.map((item) => [item[1]])
let secondHopNodeRoutes = fnoderoutes.map((item) => [item[1], item[2]])
middleAllocations = checkIntegerSumOfAllocations(
middleAllocations,
middleTokenTotal,
)
return {
routes: secondHopRoutes,
nodeRoutes: secondHopNodeRoutes,
allocations: middleAllocations,
}
}
function getActionListFromRoutesAndAllocations(
routes,
nodeRoutes,
allocations,
slippageTolerance,
) {
var actions = []
let firstHops = getHopsFromRoutes(routes, nodeRoutes, allocations)
let distilledFirstHops = distillHopsByPool(firstHops)
let firstHopActions = getDistilledHopActions(
distilledFirstHops,
slippageTolerance,
)
actions.push(...firstHopActions)
let middleTokenTotals = getMiddleTokenTotalsFromFirstHopActions(
firstHopActions,
)
let middleTokens = Object.keys(middleTokenTotals)
for (var tokenIndex in middleTokens) {
let middleToken = middleTokens[tokenIndex]
let middleTokenTotal = middleTokenTotals[middleToken]
let middleTokenRoutesWithAllocations = getRoutesAndAllocationsForMiddleToken(
routes,
nodeRoutes,
allocations,
middleToken,
middleTokenTotal,
)
let middleTokenRoutes = middleTokenRoutesWithAllocations.routes
let middleTokenAllocations = middleTokenRoutesWithAllocations.allocations
let middleTokenNodeRoutes = middleTokenRoutesWithAllocations.nodeRoutes
let secondHops = getHopsFromRoutes(
middleTokenRoutes,
middleTokenNodeRoutes,
middleTokenAllocations,
)
let distilledSecondHopsForToken = distillHopsByPool(secondHops)
let secondHopActionsForToken = getDistilledHopActions(
distilledSecondHopsForToken,
slippageTolerance,
)
actions.push(...secondHopActionsForToken)
}
// loop over middle tokens. check routes that use middle token.
//use ratio (input route alloction) /sum(input allocations of routes with middle token) * (total_middleToken)
// to get 2nd hop allocations.
// distilled2ndHopsForToken = distillHopsByPool(secondHopAllocationForToken)
// secondHopActionsForToken = getDistilledHopActions(distilled2ndHopsForToken)
//TODO: NEED TO RUN INTEGER ROUNDING FUNCTION ON MIDDLE TOKEN ALLOCATIONS
return actions
}
function getActionListFromRoutesAndAllocationsORIG(
routes,
nodeRoutes,
allocations,
slippageTolerance,
) {
let actions = []
for (var i in routes) {
let route = routes[i]
let nodeRoute = nodeRoutes[i]
let allocation = new Big(allocations[i])
if (allocation.eq(new Big(0))) {
continue
}
if (!route.length) {
route = [route]
}
if (route.length === 1) {
//single hop. only one action.
let pool = route[0]
let poolId = pool.id
let inputToken = nodeRoute[0]
let outputToken = nodeRoute[1]
let expectedAmountOut = getOutputSingleHop(
pool,
inputToken,
outputToken,
allocation,
)
let minimumAmountOut = expectedAmountOut
.times(new Big(1).minus(new Big(slippageTolerance).div(100)))
.round()
.toString() //Here, assume slippage tolerance is a percentage. So 1% would be 1.0
let action = {
pool_id: poolId,
token_in: inputToken,
token_out: outputToken,
amount_in: allocation.round().toString(),
min_amount_out: minimumAmountOut.toString(),
}
actions.push(action)
} else if (route.length === 2) {
// double hop. two actions.
let pool1 = route[0]
let pool2 = route[1]
let pool1Id = pool1.id
let pool2Id = pool2.id
let inputToken = nodeRoute[0]
let middleToken = nodeRoute[1]
let outputToken = nodeRoute[2]
let expectedAmountOutFirstHop = getOutputSingleHop(
pool1,
inputToken,
middleToken,
allocation,
)
let minimumAmountOutFirstHop = expectedAmountOutFirstHop
.times(new Big(1).minus(new Big(slippageTolerance).div(100)))
.round()
.toString() //Here, assume slippage tolerance is a percentage. So 1% would be 1.0
let action1 = {
pool_id: pool1Id,
token_in: inputToken,
token_out: middleToken,
amount_in: allocation.round().toString(),
min_amount_out: minimumAmountOutFirstHop,
}
let expectedFinalAmountOut = getOutputSingleHop(
pool2,
middleToken,
outputToken,
minimumAmountOutFirstHop,
)
let minimumAMountOutSecondHop = expectedFinalAmountOut
.times(new Big(1).minus(new Big(slippageTolerance).div(100)))
.round()
.toString()
let action2 = {
pool_id: pool2Id,
token_in: middleToken,
token_out: outputToken,
amount_in: minimumAmountOutFirstHop,
min_amount_out: minimumAMountOutSecondHop,
}
actions.push(action1)
actions.push(action2)
}
}
return actions
}
// #middleTokenTotals = getMiddleTokenTotals(routes,nodeRoutes,allocations)
// #TODO: complete this function with middle token checks.
// #consider all routes of length 2 with non-zero allocation. (double-hops)
// # among these, check for parallel swaps. That is, check for common node routes
// # for first hop. Then check for common node routes on second hop.
// # when common node routes occur for the first hop:
// # 1. Calculate the total expected output of intermediate token.
// # 2.
// # when common node routes occur for the second hop:
// # 1. get a ratio of the input allocations of the full routes associated with
// # these common node routes. allocate the total intermediate token output
// # toward these 2nd hop routes in the same ratio as their route input allocations.
function getSmartRouteSwapActions(
pools,
inputToken,
outputToken,
totalInput,
slippageTolerance,
) {
if (!totalInput) {
return []
}
var totalInput = new Big(totalInput)
let resDict = getBestOptimalAllocationsAndOutputs(
// let resDict = await getBestOptimalAllocationsAndOutputs(
pools,
inputToken,
outputToken,
totalInput,
)
let allocations = resDict.allocations
// let outputs = resDict.outputs;
let routes = resDict.routes
let nodeRoutes = resDict.nodeRoutes
let actions = getActionListFromRoutesAndAllocations(
routes,
nodeRoutes,
allocations,
slippageTolerance,
)
let distilledActions = distillCommonPoolActions(
actions,
pools,
slippageTolerance,
)
return distilledActions
}
function distillCommonPoolActions(actions, pools, slippageTolerance) {
// #Note, if there are multiple transactions for a single pool, it might lead to sub-optimal
// #returns. This is due to the fact that the routes are treated as independent, where
// #here, if one transaction goes through in a pool, it changes the price of the asset
// #before the second transaction can occur.
// #combine same-pool transactions into single transaction:
let poolsUsedPerAction = actions.map((item) => item.pool_id)
let axnSet = []
let repeats = false
for (var i in poolsUsedPerAction) {
if (axnSet.includes(poolsUsedPerAction[i])) {
repeats = true
break
} else {
axnSet.push(poolsUsedPerAction[i])
}
}
if (repeats) {
var pid = {}
for (var ai in actions) {
let a = actions[ai]
let currentPoolId = a.pool_id
if (Object.keys(pid).includes(currentPoolId)) {
pid.currentPoolId.push(a)
} else {
pid[currentPoolId] = [a]
}
}
var newActions = []
var poolIds = Object.keys(pid)
for (var pi in poolIds) {
let poolId = poolIds[pi]
let actionList = pid[poolId]
if (actionList.length == 1) {
var poolTotalInput = new Big(actionList[0].amount_in)
} else {
var poolTotalInput = actionList.reduce(
(a, b) => new Big(a.amount_in) + new Big(b.amount_in),
new Big(0),
)
}
let inputToken = actionList[0].token_in
let outputToken = actionList[0].token_out
let pool = pools.filter((item) => item.id.toString() === poolId)[0]
let expectedMinimumOutput = getOutputSingleHop(
pool,
inputToken,
outputToken,
poolTotalInput,
).times(new Big(1).minus(new Big(slippageTolerance).div(100)))
let newAction = {
pool_id: poolId,
token_in: inputToken,
token_out: outputToken,
amount_in: poolTotalInput.round().toString(),
min_amount_out: expectedMinimumOutput.round().toString(),
}
newActions.push(newAction)
}
} else {
var newActions = actions
}
return newActions
}
// pool =
// {"id": 19,
// "token1Id": "wrap.near",
// "token2Id": "a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48.factory.bridge.near",
// "token1Supply": "458507706848275237144751",
// "token2Supply": "4773827",
// "fee": 20,
// "shares": "1433530386500514261296380",
// "update_time": 1643427419,
// "token0_price": "0"}
//////////////////////////////////////////////////////////////
// UTILITIES
//////////////////////////////////////////////////////////////
function getPoolsByToken1ORToken2(pools, token1, token2) {
let filteredPools = pools.filter(
(item) =>
item.token1Id === token1 ||
item.token2Id === token1 ||
item.token1Id === token2 ||
item.token2Id === token2,
)
return filteredPools
}
function getPoolsByToken1ANDToken2(
pools,
token1,
token2,
cullZeroLiquidityPools = true,
) {
let filteredPools = pools.filter(
(item) =>
(item.token1Id === token1 && item.token2Id === token2) ||
(item.token1Id === token2 && item.token2Id === token1),
)