-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUniverse.ts
1223 lines (1109 loc) · 36.8 KB
/
Universe.ts
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
import { ethers } from 'ethers'
import {
findTradeSize,
type BaseAction as Action,
} from './action/Action'
import { LPToken } from './action/LPToken'
import { Address } from './base/Address'
import { DefaultMap } from './base/DefaultMap'
import {
SimulateZapTransactionFunction,
createSimulateZapTransactionUsingProvider,
type Config,
} from './configuration/ChainConfiguration'
import {
Token,
type TokenQuantity,
} from './entities/Token'
import { TokenLoader, makeTokenLoader } from './entities/makeTokenLoader'
import { Graph } from './exchange-graph/Graph'
import { PriceOracle } from './oracles/PriceOracle'
import { ApprovalsStore } from './searcher/ApprovalsStore'
import EventEmitter from 'events'
import winston from 'winston'
import { CompoundV2Deployment } from './action/CTokens'
import { LidoDeployment } from './action/Lido'
import { RTokenDeployment } from './action/RTokens'
import { TradingVenue } from './aggregators/DexAggregator'
import { BlockCache } from './base/BlockBasedCache'
import {
GAS_TOKEN_ADDRESS,
USD_ADDRESS,
simulationUrls,
} from './base/constants'
import { AaveV2Deployment } from './configuration/setupAaveV2'
import { AaveV3Deployment } from './configuration/setupAaveV3'
import { CompoundV3Deployment } from './configuration/setupCompV3'
import { ReserveConvex } from './configuration/setupConvexStakingWrappers'
import { CurveIntegration } from './configuration/setupCurve'
import { ZapperExecutor__factory } from './contracts'
import { TokenType, isAsset } from './entities/TokenClass'
import { ZapperTokenQuantityPrice } from './oracles/ZapperAggregatorOracle'
import { PerformanceMonitor } from './searcher/PerformanceMonitor'
import { SwapPath } from './searcher/Swap'
import { ToTransactionArgs } from './searcher/ToTransactionArgs'
import { Contract } from './tx-gen/Planner'
import { TxGen, TxGenOptions } from './searcher/TxGen'
import { ITokenFlowGraphRegistry, InMemoryTokenFlowGraphRegistry, TokenFlowGraph, TokenFlowGraphSearcher } from './searcher/TokenFlowGraph'
import { FolioContext } from './action/Folio'
import { DeployFolioConfig, DeployFolioConfigJson } from './action/DeployFolioConfig'
import { optimiseTrades } from './searcher/optimiseTrades'
import { DexLiquidtyPriceStore } from './searcher/DexLiquidtyPriceStore'
import { reachableTokens } from './exchange-graph/BFS'
type TokenList<T> = {
[K in keyof T]: Token
}
export type Integrations = Partial<{
aaveV3: AaveV3Deployment
aaveV2: AaveV2Deployment
fluxFinance: CompoundV2Deployment
compoundV2: CompoundV2Deployment
compoundV3: CompoundV3Deployment
uniswapV3: TradingVenue
curve: CurveIntegration
rocketpool: TradingVenue
aerodrome: TradingVenue
lido: LidoDeployment
convex: ReserveConvex
}>
export class Universe<const UniverseConf extends Config = Config> {
public readonly folioContext: FolioContext
private emitter = new EventEmitter()
private yieldPositionZaps: Map<Token, Token[]> = new Map();
public defineYieldPositionZap(yieldPosition: Token, rTokenInput: Token) {
let value = this.yieldPositionZaps.get(yieldPosition) || []
value = [...value.filter((token) => token.address.address !== rTokenInput.address.address), rTokenInput]
this.yieldPositionZaps.set(yieldPosition, value)
}
public readonly underlyingToken = new DefaultMap<Token, Promise<Token>>(async (token: Token): Promise<Token> => {
if (token === this.nativeToken || token === this.wrappedNativeToken) {
return this.wrappedNativeToken
}
const tokenType = await this.tokenType.get(token);
if (tokenType === TokenType.LPToken) {
return token
}
if (tokenType === TokenType.ETHLST || isAsset(tokenType)) {
return token
}
if (this.mintableTokens.has(token)) {
const mint = this.getMintAction(token)!;
if (mint.inputToken.length === 1) {
return this.underlyingToken.get(mint.inputToken[0])
}
}
for(const [tok, base] of this.yieldPositionZaps.entries()) {
if (tok === token) {
return this.underlyingToken.get(base[0])
}
}
return token
})
public readonly tokenType = new DefaultMap<Token, Promise<TokenType>>(async token => {
if (token === this.nativeToken || token === this.wrappedNativeToken) {
return TokenType.Asset
}
if (this.rTokensInfo.tokens.has(token)) {
return TokenType.RToken
}
if (this.lpTokens.has(token)) {
return TokenType.LPToken
}
const cls = await this.tokenClass.get(token)
if (cls === this.nativeToken) {
return TokenType.ETHLST
}
if (this.mintableTokens.has(token)) {
return TokenType.OtherMintable
}
if (cls === this.usd) {
return TokenType.Asset
}
return TokenType.Asset
})
public readonly tokenClass = new DefaultMap<Token, Promise<Token>>(async (token: Token): Promise<Token> => {
if (this.wrappedNativeToken === token || this.nativeToken === token) {
return this.wrappedNativeToken
}
if (this.rTokensInfo.tokens.has(token)) {
const basketTokenClasses = await Promise.all(this.rTokenDeployments.get(token)!.basket.map(t => this.tokenClass.get(t)));
if (basketTokenClasses.every(t => t === basketTokenClasses[0])) {
return basketTokenClasses[0]
}
return token;
}
if (this.mintableTokens.has(token)) {
const classes = await Promise.all(this.getMintAction(token)!.inputToken.map(t => this.tokenClass.get(t)))
if (classes.every(t => t === classes[0])) {
return classes[0]
}
return token;
}
const tokenPrice = (await token.price)?.asNumber() ?? 0;
if (tokenPrice == 0) {
throw new Error(`Failed to classify ${token}: Unable to price it`)
}
if (this.lpTokens.has(token)) {
const poolTokens = (await this.lpTokens.get(token)!.lpRedeem(token.one)).map(i => i.token)
const classes = await Promise.all(poolTokens.map(t => this.tokenClass.get(t)))
if (classes.every(t => t === classes[0])) {
return classes[0]
}
return token;
}
if (Math.abs(1 - tokenPrice) < 0.05) {
return await this.getToken(this.config.addresses.usdc)
}
const ethPrice = (await this.fairPrice(this.wrappedNativeToken.one))?.asNumber() ?? 0;
if (ethPrice == 0) {
throw new Error(`Failed to get eth price for ${token}`)
}
if (Math.abs(ethPrice - tokenPrice) < ethPrice * 0.15) {
return this.wrappedNativeToken
}
return token
})
public readonly zeroBeforeApproval = new Set<Token>()
public _finishResolving: () => void = () => { }
public initialized: Promise<void> = new Promise((resolve) => {
this._finishResolving = resolve
})
get chainId(): UniverseConf['chainId'] {
return this.config.chainId
}
private readonly caches: BlockCache<any, any>[] = []
public readonly perf = new PerformanceMonitor()
public prettyPrintPerfs(addContext = false) {
this.logger.info('Performance Stats')
for (const [_, value] of this.perf.stats.entries()) {
this.logger.info(' ' + value.toString())
if (addContext) {
for (const context of value.contextStats) {
this.logger.info(' ' + context.toString())
}
}
}
}
public createCache<Input, Result, Key = Input>(
fetch: (key: Input) => Promise<Result>,
ttl: number = (12000 / this.config.requoteTolerance),
keyFn?: (key: Input) => Key
): BlockCache<Input, Result, Key> {
if (ttl < 100) {
ttl = 12000 / ttl
}
const cache = new BlockCache<Input, Result, Key>(fetch, ttl, Date.now(), keyFn as any)
this.caches.push(cache)
return cache
}
public createCachedProducer<Result>(
fetch: () => Promise<Result>,
ttl: number = (12000 / this.config.requoteTolerance)
): () => Promise<Result> {
let lastFetch: number = 0
if (ttl < 100) {
ttl = 12000 / ttl
}
let lastResult: Promise<Result> | null = null
return async () => {
if (lastResult == null || Date.now() - lastFetch > ttl) {
lastFetch = Date.now()
lastResult = fetch()
void lastResult.catch(e => {
lastResult = null
throw e
});
}
return await lastResult
}
}
public readonly tokens = new Map<Address, Token>()
public readonly lpTokens = new Map<Token, LPToken>()
private _gasTokenPrice: TokenQuantity | null = null
public get gasTokenPrice() {
return this._gasTokenPrice ?? this.usd.from(3000)
}
public isTokenMintable(token: Token) {
if (token === this.nativeToken || token === this.wrappedNativeToken) {
return false
}
try {
this.getMintAction(token)
return true
} catch (e) {
return false
}
}
public isTokenBurnable(token: Token) {
if (token === this.nativeToken || token === this.wrappedNativeToken) {
return false
}
try {
const wrappable = this.wrappedTokens.get(token)
if (wrappable?.burn) {
return true
}
return false
} catch (e) {
return false
}
}
public getMintAction(token: Token) {
const mint = this.mintableTokens.get(token)
if (mint == null) {
const wrappable = this.wrappedTokens.get(token)
if (wrappable) {
return wrappable.mint
}
throw new Error(`No mint action found for ${token}`)
}
return mint
}
public getBurnAction(token: Token) {
const burn = this.wrappedTokens.get(token)?.burn
if (burn == null) {
throw new Error(`No burn action found for ${token}`)
}
return burn
}
public async underlyingTokens(token: Token): Promise<Token[]> {
if (this.rTokenDeployments.has(token)) {
const rTokenDeployment = this.rTokenDeployments.get(token)!
const out: Token[] = []
for (const basketToken of rTokenDeployment.basket) {
const underlying = await this.underlyingTokens(basketToken)
if (underlying.length === 0) {
underlying.push(basketToken)
}
out.push(...underlying)
}
return out
} else if (this.lpTokens.has(token)) {
const lpToken = this.lpTokens.get(token)!
const out: Token[] = []
for (const tok of lpToken.poolTokens) {
const underlying = await this.underlyingTokens(tok)
if (underlying.length === 0) {
underlying.push(tok)
}
out.push(...underlying)
}
return out
}
const underlying = await this.underlyingToken.get(token)
if (underlying !== token) {
const underlyingTokens = await this.underlyingTokens(underlying)
if (underlyingTokens.length === 0) {
return [underlying]
} else {
return underlyingTokens
}
}
return []
}
public async quoteGas(units: bigint) {
if (this._gasTokenPrice == null) {
this._gasTokenPrice = await this.fairPrice(this.nativeToken.one)
}
const txFee = this.nativeToken.from(units * this.gasPrice)
const txFeeUsd = txFee.into(this.usd).mul(this.gasTokenPrice)
return {
units,
txFee,
txFeeUsd,
}
}
public readonly actions = new DefaultMap<Address, Action[]>(() => [])
private readonly allActions = new Set<Action>()
public readonly tokenTradeSpecialCases = new Map<
Token,
(amount: TokenQuantity, destination: Address) => Promise<SwapPath | null>
>()
public readonly tokenFromTradeSpecialCases = new Map<
Token,
(amount: TokenQuantity, output: Token) => Promise<SwapPath | null>
>()
// The GAS token for the EVM chain, set by the StaticConfig
public readonly nativeToken: Token
public readonly wrappedNativeToken: Token
// 'Virtual' token used for pricing things
public readonly usd: Token = Token.createToken(
this,
Address.fromHexString(USD_ADDRESS),
'USD',
'USD Dollar',
8
)
private fairPriceCache: BlockCache<TokenQuantity, TokenQuantity, string>
public readonly graph: Graph = new Graph()
public readonly wrappedTokens = new Map<
Token,
{ mint: Action; burn: Action; allowAggregatorSearcher: boolean }
>()
public readonly mintableTokens = new Map<
Token,
Action
>()
public readonly oracles: PriceOracle[] = []
private tradeVenues: TradingVenue[] = []
private readonly tradingVenuesSupportingDynamicInput: TradingVenue[] = []
public addTradeVenue(venue: TradingVenue) {
if (venue.supportsDynamicInput) {
this.tradingVenuesSupportingDynamicInput.push(venue)
this.tradeVenues.push(venue)
} else {
this.tradeVenues = [venue, ...this.tradeVenues]
}
}
public getTradingVenues(input: TokenQuantity, output: Token) {
const venues = this.tradeVenues
const out = venues.filter((venue) =>
venue.router.supportsSwap(input, output)
)
if (out.length !== 0) {
return out
}
throw new Error(
`Failed to find any trading venues for ${input.token} -> ${output}`
)
}
public async swap(
input: TokenQuantity,
output: Token,
opts?: {
slippage: bigint
dynamicInput: boolean
abort: AbortSignal
}
) {
const out: SwapPath[] = []
await this.swaps(
input,
output,
async (res) => {
out.push(res)
},
{
...opts,
slippage: this.config.defaultInternalTradeSlippage,
dynamicInput: true,
abort: AbortSignal.timeout(this.config.routerDeadline),
}
)
out.sort((l, r) => l.compare(r))
return out[0]
}
public async swaps(
input: TokenQuantity,
output: Token,
onResult: (result: SwapPath) => Promise<void>,
opts: {
slippage: bigint
dynamicInput: boolean
abort: AbortSignal
}
) {
const tradeSize = await this.fairPrice(input)
const wrapper = this.wrappedTokens.get(input.token)
if (wrapper?.allowAggregatorSearcher === false) {
return
}
const aggregators = this.getTradingVenues(input, output)
const tradeName = `${input.token} -> ${output}`
const stopSearch = new AbortController()
const stopWork = new Promise((resolve) => {
stopSearch.signal.addEventListener('abort', () => {
resolve(null)
})
})
let results = 0;
const start = Date.now()
const tradeValue = tradeSize?.asNumber() ?? 0;
const work = Promise.all(
shuffle(aggregators).map(async (venue) => {
try {
let inp = input
if (
opts.dynamicInput && !venue.supportsDynamicInput
) {
inp = inp.mul(inp.token.from(0.99999))
}
const res = await this.perf.measurePromise(
venue.name,
venue.router.swap(opts.abort, inp, output, opts.slippage),
tradeName
)
const outValue = res.outputValue.asNumber();
if (outValue >= tradeValue * 0.96) {
// IF trade does not loose more than 4% value, count the result
results += 1;
}
// For small trades, allow us to bail before the timeout
if (tradeSize && tradeSize.amount < 50000_00000000n) {
if (results >= this.config.routerMinResults) {
const delta = Date.now() - start
// We're essentially
const toWait = delta > 2500 ? 500 : (2500 - delta) / 2 + 500;
setTimeout(() => {
if (!stopSearch.signal.aborted) {
stopSearch.abort()
}
}, toWait)
}
}
if (stopSearch.signal.aborted || opts.abort.aborted) {
return;
}
// this.logger.info(`${venue.name} ok: ${res.steps[0].action.toString()}`)
await onResult(res)
} catch (e: any) {
// this.logger.info(`${venue.name} failed for case: ${tradeName}`)
// this.logger.info(e.message)
}
})
)
await Promise.race([work, stopWork])
}
// Sentinel token used for pricing things
public readonly rTokens = {} as TokenList<
UniverseConf['addresses']['rTokens']
>
public readonly commonTokens = {} as TokenList<
UniverseConf['addresses']['commonTokens']
>
private commonTokensSet_: Set<Token> | null = null
public get commonTokensInfo() {
if (this.commonTokensSet_ == null) {
this.commonTokensSet_ = new Set(Object.values(this.commonTokens))
}
return {
addresses: new Set([...this.commonTokensSet_].map((i) => i.address)),
tokens: this.commonTokensSet_,
}
}
private rTokensSet_: Set<Token> | null = null
public get rTokensInfo() {
if (this.rTokensSet_ == null) {
this.rTokensSet_ = new Set(Object.values(this.rTokens))
}
return {
addresses: new Set([...this.rTokensSet_].map((i) => i.address)),
tokens: this.rTokensSet_,
}
}
public preferredRTokenInputToken = new DefaultMap<Token, Set<Token>>(() => new Set())
public preferredToken = new Map<Token, Token>()
public addPreferredRTokenInputToken(token: Token, inputToken: Token) {
this.preferredRTokenInputToken.get(token).add(inputToken)
if (!this.preferredToken.has(token)) {
this.preferredToken.set(token, inputToken)
}
}
public readonly integrations: Integrations = {}
private readonly rTokenDeployments = new Map<Token, RTokenDeployment>()
public async defineRToken(rTokenAddress: Address) {
const rToken = await this.getToken(rTokenAddress)
if (this.rTokenDeployments.has(rToken)) {
throw new Error(`RToken ${rToken} already defined`)
}
let facade = this.config.addresses.facadeAddress
if (facade === Address.ZERO) {
facade = Address.from(this.config.addresses.oldFacadeAddress)
}
const rtokenDeployment = await RTokenDeployment.load(this, facade, rToken)
this.rTokenDeployments.set(rToken, rtokenDeployment)
this.rTokensInfo.addresses.add(rToken.address)
this.rTokensInfo.tokens.add(rToken)
return rToken
}
public getRTokenDeployment(token: Token) {
const out = this.rTokenDeployments.get(token)
if (out == null) {
throw new Error(`${token} is not a known RToken`)
}
return out
}
public addIntegration<K extends keyof Integrations>(
key: K,
value: Integrations[K]
) {
if (this.integrations[key] != null) {
throw new Error(`Integration ${key} already defined`)
}
this.integrations[key] = value
return value!
}
public async balanceOf(token: Token, account: Address) {
return await this.approvalsStore.queryBalance(token, account)
}
private readonly blockState = {
currentBlock: 0,
gasPrice: 0n,
}
/**
* This method try to price a given token in USD.
* It will first try and see if there is an canonical way to mint/burn the token,
* if there is, it will recursively unwrap the token until it finds a what the token consists of.
*
* Once the token is fully unwrapped, it will query the oracles to find the price of each underlying
* quantity, and sum them up.
*
* @param qty quantity to price
* @returns The price of the qty in USD, or null if the price cannot be determined
*/
public readonly oracle: ZapperTokenQuantityPrice
public readonly singleTokenPriceOracles = new DefaultMap<Token, PriceOracle[]>(() => [])
public async addSingleTokenPriceOracle(opts: {
token: Token
oracleAddress: Address
priceToken: Token
}) {
const { token, oracleAddress, priceToken = this.usd } = opts;
const oracle = await PriceOracle.createSingleTokenOracleChainLinkLike(
this,
token,
oracleAddress,
priceToken
)
this.singleTokenPriceOracles.get(token).push(oracle)
// this.oracles.push(oracle)
return oracle
}
public addSingleTokenPriceSource(opts: {
token: Token
priceFn: () => Promise<TokenQuantity>
}) {
const { token, priceFn } = opts;
const oracle = PriceOracle.createSingleTokenOracle(
this,
token,
priceFn
)
this.singleTokenPriceOracles.get(token).push(oracle)
return oracle
}
async fairPrice(qty: TokenQuantity): Promise<TokenQuantity | null> {
if (qty.token === this.nativeToken) {
return await this.fairPrice(qty.into(this.wrappedNativeToken))
}
const perfStart = this.perf.begin('fairPrice', qty.token.symbol)
let out: TokenQuantity | null = await this.fairPriceCache.get(qty)
if (out.amount === 0n) {
out = null
}
perfStart()
return out
}
async quoteIn(qty: TokenQuantity, tokenToQuoteWith: Token) {
return this.oracle?.quoteIn(qty, tokenToQuoteWith).catch(() => null) ?? null
}
get currentBlock() {
return this.blockState.currentBlock
}
get gasPrice() {
return this.blockState.gasPrice
}
public async getToken(address: Address|string): Promise<Token> {
if (typeof address === 'string') {
address = Address.from(address)
}
let previous = this.tokens.get(address)
if (previous == null) {
const data = await this.loadToken(address)
previous = Token.createToken(
this,
address,
data.symbol,
data.symbol,
data.decimals
)
this.tokens.set(address, previous)
}
return previous
}
public createToken(
address: Address,
symbol: string,
name: string,
decimals: number
) {
const token = Token.createToken(
this,
address,
symbol,
name,
decimals,
)
return token
}
private actionById = new Map<string, Action>()
public actionExists(id: string) {
return this.actionById.has(id)
}
public getAction(id: string) {
const action = this.actionById.get(id)
if (action == null) {
throw new Error(`Action ${id} not found`)
}
return action
}
public addAction(action: Action, actionAddress?: Address) {
const id = action.actionId;
if (this.actionById.has(id)) {
this.logger.warn(`Duplicate action: ${id}`)
return this
}
this.actionById.set(id, action)
if (this.allActions.has(action)) {
return this
}
this.allActions.add(action)
if (actionAddress != null) {
this.actions.get(actionAddress).push(action)
} else {
this.actions.get(action.address).push(action)
}
this.graph.addEdge(action);
return this
}
public async defineLPToken(
lpToken: Token,
burn: (a: TokenQuantity) => Promise<TokenQuantity[]>,
mint: (a: TokenQuantity[]) => Promise<TokenQuantity>) {
const underlyingPrLP = await burn(lpToken.one)
const positionTokens = underlyingPrLP.map(i => i.token);
const inst = new LPToken(
lpToken,
positionTokens,
burn,
mint
)
this.addSingleTokenPriceSource({
token: lpToken,
priceFn: async () => {
const underlyings = (await burn(lpToken.one))
const prices = await Promise.all(
underlyings.map(async (i) => {
const p = await this.fairPrice(i)
if (p == null) {
throw new Error(`Cannot price ${lpToken}: Failed to price ${i}`)
}
return p
})
)
return prices.reduce((l, r) => l.add(r), this.usd.zero)
},
})
this.lpTokens.set(lpToken, inst)
}
public weirollZapperExec
public weirollZapperExecContract
findBurnActions(token: Token) {
const out = this.actions
.get(token.address)
.filter((i) => i.inputToken.length === 1 && i.inputToken[0] === token)
return [...out]
}
get execAddress() {
if (this.config.useNewZapperContract && this.config.addresses.executorAddress2 != null) {
return this.config.addresses.executorAddress2
}
return this.config.addresses.executorAddress
}
get zapperAddress() {
if (this.config.useNewZapperContract && this.config.addresses.zapper2Address != null) {
return this.config.addresses.zapper2Address
}
return this.config.addresses.zapperAddress
}
public defineMintable(
mint: Action,
burn: Action,
allowAggregatorSearcher = false
) {
if (mint.outputToken.length === 1) {
this.mintableTokens.set(mint.outputToken[0], mint)
}
const output = mint.outputToken[0]
if (
!mint.outputToken.every((i, index) => burn.inputToken[index] === i) ||
!burn.outputToken.every((i, index) => mint.inputToken[index] === i)
) {
throw new Error(
`Invalid mintable: mint: (${mint.inputToken.join(
', '
)}) -> ${mint} -> (${mint.outputToken.join(
', '
)}), burn: (${burn.inputToken.join(
', '
)}) -> ${burn} -> (${burn.outputToken.join(', ')})`
)
}
if (this.wrappedTokens.has(output)) {
throw new Error('Token already mintable')
}
this.addAction(mint)
this.addAction(burn)
const out = {
mint,
burn,
allowAggregatorSearcher,
}
this.wrappedTokens.set(output, out)
return out
}
public simulateZapFn: SimulateZapTransactionFunction
public mintRate: BlockCache<Token, TokenQuantity>;
public mintRateProviders = new Map<Token, () => Promise<TokenQuantity>>()
public midPrices: BlockCache<Action, TokenQuantity>;
private _maxTradeSizes: DefaultMap<Action, Promise<BlockCache<number, TokenQuantity>>> = new DefaultMap(async edge => {
if (!edge.is1to1) {
throw new Error(
`${edge}: is not 1-to-1`
)
}
const inputToken = edge.inputToken[0]
const liquidity = (await edge.liquidity()) * 0.5
if (!isFinite(liquidity)) {
throw new Error(
`${edge}: has infinite liquidity`
)
}
const inputTokenPrice = (await inputToken.price).asNumber()
const maxSize = inputToken.from(liquidity / inputTokenPrice)
return this.createCache(
async (limit: number) => {
// const inputTokenPrice = (await inputToken.price).asNumber()
// const outputTokenPrice = (await edge.outputToken[0].price).asNumber()
// const txFeePrice = (await this.nativeToken.from(edge.gasEstimate() * this.gasPrice).price()).asNumber()
return inputToken.from(
await findTradeSize(edge, maxSize, limit)
)
}
)
})
public async getMaxTradeSize(edge: Action, limit: number) {
return (await this._maxTradeSizes.get(edge)).get(limit)
}
private constructor(
public readonly provider: ethers.providers.JsonRpcProvider,
public readonly config: UniverseConf,
public readonly approvalsStore: ApprovalsStore,
public readonly loadToken: TokenLoader,
private readonly simulateZapFn_: SimulateZapTransactionFunction,
public readonly logger: winston.Logger = winston.createLogger({
level: process.env.LOG_LEVEL ?? "info",
format: winston.format.json(),
silent: process.env.DEV !== '1',
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
})
]
}),
private readonly tfgReg: ITokenFlowGraphRegistry = new InMemoryTokenFlowGraphRegistry(this)
) {
this.tfgSearcher = new TokenFlowGraphSearcher(this, this.tfgReg)
this.folioContext = new FolioContext(this)
const nativeToken = config.nativeToken
this.nativeToken = Token.createToken(
this,
Address.fromHexString(GAS_TOKEN_ADDRESS),
nativeToken.symbol,
nativeToken.name,
nativeToken.decimals
)
this.midPrices = this.createCache(async (edge: Action) => {
try {
if (!edge.is1to1) {
throw new Error(`${edge} is not 1to1`)
}
const inputToken = edge.inputToken[0]
const outputToken = edge.outputToken[0]
const outputSize = (await edge.quote([inputToken.one.scalarMul(10n)]))[0]
return outputToken.from(outputSize.asNumber() / 10)
} catch (e) {
this.logger.info(`Error finding mid price for ${edge}: ${e}`)
throw e
}
}, 12000)
this.wrappedNativeToken = Token.createToken(
this,
config.addresses.wrappedNative,
'W' + nativeToken.symbol,
'Wrapped ' + nativeToken.name,
nativeToken.decimals
)
this.weirollZapperExec = Contract.createLibrary(
ZapperExecutor__factory.connect(
this.execAddress.address,
this.provider
)
)
this.weirollZapperExecContract = Contract.createContract(
ZapperExecutor__factory.connect(
this.execAddress.address,
this.provider
)
)
this.oracle = new ZapperTokenQuantityPrice(this)
this.fairPriceCache = this.createCache<TokenQuantity, TokenQuantity, string>(
async (qty: TokenQuantity) => {
if (qty.token === this.usd) {
return qty
}
const out = await this.oracle.quote(qty)
return out
},
60000,
i => i.toString()
)
this.simulateZapFn = this.simulateZapFn_
const native = this.nativeToken
const wrappedNative = this.wrappedNativeToken
this.mintRate = this.createCache(async (token: Token) => {
if (this.mintRateProviders.has(token)) {
return await this.mintRateProviders.get(token)!()
}
if (token === wrappedNative) {
return native.one
}
if (!this.mintableTokens.has(token)) {
throw new Error(`${token} is not mintable`)
}
const mint = this.mintableTokens.get(token)!
if (mint.inputToken.length !== 1) {
if (this.rTokenDeployments.has(token)) {
const deployment = this.rTokenDeployments.get(token)!
return await deployment.exchangeRate()
}
const underlying = await mint.inputProportions()
const outToken = await this.tokenClass.get(token)
let sum = 0.0
while(underlying.length !== 0) {
const rate = underlying.pop()!
if (this.mintableTokens.has(rate.token)) {
const newRate = await this.mintRate.get(rate.token)
underlying.push(newRate.mul(rate.into(newRate.token)))
} else {
sum += rate.asNumber()
}
}
return outToken.from(sum)
}
const out = await mint.quote([mint.inputToken[0].one])
if (out.length !== 1) {
throw new Error(`${mint} returned ${out.length} outputs, expected 1`)
}
const outN = 1 / out[0].asNumber()
const rate = mint.inputToken[0].from(outN)
const ratePrice = (await rate.price()).asNumber()
const inputTokenPrice = (await mint.inputToken[0].price).asNumber()
return mint.inputToken[0].from(1/(ratePrice/inputTokenPrice))
},
1000 * 60 * 10,
)
}
public readonly dexLiquidtyPriceStore = new DexLiquidtyPriceStore(this)
private hasDexMarkets_ = new DefaultMap<Token, boolean>(token => {
for (const [tokenIn, edges] of this.graph.vertices.get(token).incomingEdges) {
for (const edge of edges) {
if (edge.is1to1 && edge.isTrade) {
return true