-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathserver.ts
More file actions
1450 lines (1254 loc) · 48.5 KB
/
Copy pathserver.ts
File metadata and controls
1450 lines (1254 loc) · 48.5 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
import { serve } from 'bun'
import type {
TTenderlyFundRequest,
TTenderlyIncreaseTimeRequest,
TTenderlyRevertRequest,
TTenderlySnapshotRequest
} from '../src/components/shared/types/tenderly'
import { ENSO_BALANCES_CACHE_CONTROL } from './enso/cache'
import type { TVaultListEntry, TVaultSnapshot } from './lib/aio'
import { buildSitemap, buildVaultMarkdown, buildVaultsMarkdown, KONG_REST_BASE, KONG_VAULT_LIST_URL } from './lib/aio'
import { getVercelCdnCacheHeaders } from './lib/cacheHeaders'
import {
clearUserCache,
getHistoricalHoldingsChart,
getHoldingsActivity,
getHoldingsActivityFacetResponse,
getHoldingsBreakdown,
getHoldingsProtocolReturnHistory,
getHoldingsTotalsCacheVersion,
type HoldingsActivityTypeFilter,
type HoldingsEventFetchType,
type HoldingsEventPaginationMode,
type HoldingsHistoryDenomination,
type HoldingsHistoryTimeframe,
initializeHoldingsStorage,
type VaultVersion,
validateConfig
} from './lib/holdings'
import {
createHoldingsDebugContext,
debugError,
debugLog,
isHoldingsDebugRequested,
withHoldingsDebugContext
} from './lib/holdings/services/debug'
import { getHoldingsProgress, startHoldingsProgress, updateHoldingsProgress } from './lib/holdings/services/progress'
import { getVaultDecimals } from './optimization/_lib/assetLogos'
import { fetchAlignedEvents } from './optimization/_lib/envio'
import { parseExplainMetadata } from './optimization/_lib/explain-parse'
import {
findVaultOptimization,
isRedisAuthenticationError,
isRedisConnectivityError,
REDIS_AUTHENTICATION_ERROR_MESSAGE,
REDIS_CONNECTIVITY_ERROR_MESSAGE,
readOptimizations
} from './optimization/_lib/redis'
import { fetchVaultOnChainState } from './optimization/_lib/rpc'
import {
buildTenderlyPanelStatus,
buildTenderlyRevertResponse,
buildTenderlySnapshotRecord,
requireTenderlyServerChain,
resolveTenderlyFundRpcRequest
} from './tenderly.helpers'
import {
buildTenderlyAdminAccessDeniedResponse,
buildTenderlyAdminCorsPreflightResponse,
withTenderlyAdminCors
} from './tenderlyAccess'
const ENSO_API_BASE = 'https://api.enso.finance'
const DEFAULT_API_PORT = 3001
const YVUSD_APR_SERVICE_API = (
process.env.YVUSD_APR_SERVICE_API || 'https://yearn-yvusd-apr-service.vercel.app/api/aprs'
).replace(/\/$/, '')
const YVUSD_APR_CDN_CACHE_CONTROL = 'public, s-maxage=30, stale-while-revalidate=120'
function isHistoryQueryEnabled(historyParam: string | null): boolean {
return historyParam === '1' || historyParam === 'true'
}
function resolveApiPort(env: NodeJS.ProcessEnv): number {
const rawPort = env.API_PORT?.trim() || env.API_SERVER_PORT?.trim() || String(DEFAULT_API_PORT)
const port = Number(rawPort)
if (!Number.isInteger(port) || port <= 0) {
throw new Error(`Invalid API port value: ${rawPort}`)
}
return port
}
const API_PORT = resolveApiPort(process.env)
type TTenderlyJsonRpcSuccess = {
id: string | number | null
jsonrpc: '2.0'
result: unknown
}
type TTenderlyJsonRpcError = {
id: string | number | null
jsonrpc: '2.0'
error: {
code: number
message: string
data?: unknown
}
}
async function handleYvUsdAprs(req: Request): Promise<Response> {
if (req.method !== 'GET') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
const requestUrl = new URL(req.url)
const upstreamUrl = new URL(YVUSD_APR_SERVICE_API)
requestUrl.searchParams.forEach((value, key) => {
upstreamUrl.searchParams.set(key, value)
})
try {
const response = await fetch(upstreamUrl.toString(), {
headers: {
Accept: 'application/json'
}
})
if (!response.ok) {
const details = await response.text()
return Response.json(
{ error: 'yvUSD APR upstream error', status: response.status, details },
{ status: response.status }
)
}
const data = await response.json()
return Response.json(data, {
headers: getVercelCdnCacheHeaders(YVUSD_APR_CDN_CACHE_CONTROL)
})
} catch (error) {
console.error('Error proxying yvUSD APR request:', error)
return Response.json({ error: 'Internal server error' }, { status: 500 })
}
}
const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
}
function withCors(response: Response): Response {
const newHeaders = new Headers(response.headers)
for (const [key, value] of Object.entries(CORS_HEADERS)) {
newHeaders.set(key, value)
}
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders
})
}
function handleCorsPreFlight(): Response {
return new Response(null, {
status: 204,
headers: CORS_HEADERS
})
}
function isTenderlyAdminPath(pathname: string): boolean {
return (
pathname === '/api/tenderly/snapshot' ||
pathname === '/api/tenderly/revert' ||
pathname === '/api/tenderly/increase-time' ||
pathname === '/api/tenderly/fund'
)
}
async function handleHoldingsProgress(req: Request): Promise<Response> {
const url = new URL(req.url)
const progress = await getHoldingsProgress(url.searchParams.get('id'))
if (!progress) {
return new Response(null, {
status: 204,
headers: {
'Cache-Control': 'no-store'
}
})
}
return Response.json(progress, {
headers: {
'Cache-Control': 'no-store'
}
})
}
function isValidAddress(address: string): boolean {
return /^0x[a-fA-F0-9]{40}$/.test(address)
}
function parseVaultFilters(url: URL): Array<{ chainId: number; vaultAddress: string }> | null | undefined {
const vaults = url.searchParams.get('vaults')
if (vaults !== null) {
const entries = vaults
.split(',')
.map((entry) => entry.trim())
.filter(Boolean)
const parsedEntries = entries.map((entry) => {
const [entryChainId, entryVaultAddress] = entry.split(':')
const parsedChainId = Number(entryChainId)
if (
!entryChainId ||
!entryVaultAddress ||
!Number.isInteger(parsedChainId) ||
!isValidAddress(entryVaultAddress)
) {
return null
}
return { chainId: parsedChainId, vaultAddress: entryVaultAddress }
})
if (parsedEntries.some((entry) => entry === null)) {
return null
}
return parsedEntries.filter((entry): entry is { chainId: number; vaultAddress: string } => entry !== null)
}
const vault = url.searchParams.get('vault')
if (vault === null) {
return undefined
}
const chainId = url.searchParams.get('chainId')
if (!isValidAddress(vault) || !chainId || !Number.isInteger(Number(chainId))) {
return null
}
return [{ chainId: Number(chainId), vaultAddress: vault }]
}
function parseHoldingsEventFetchType(value: string | null): HoldingsEventFetchType {
return value === 'parallel' ? 'parallel' : 'seq'
}
function parseHoldingsEventPaginationMode(value: string | null): HoldingsEventPaginationMode {
return value === 'all' ? 'all' : 'paged'
}
function parseHoldingsHistoryDenomination(value: string | null): HoldingsHistoryDenomination {
return value === 'eth' ? 'eth' : 'usd'
}
function parseHoldingsHistoryTimeframe(value: string | null): HoldingsHistoryTimeframe {
return value === 'all' ? 'all' : '1y'
}
function parseHoldingsActivityLimit(value: string | null): number {
const parsed = Number(value)
if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) {
return 10
}
return Math.min(Math.max(parsed, 1), 500)
}
function parseHoldingsActivityOffset(value: string | null): number {
const parsed = Number(value)
if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) {
return 0
}
return Math.max(parsed, 0)
}
function parseHoldingsActivityType(value: string | null): HoldingsActivityTypeFilter {
return value === 'deposit' ||
value === 'withdraw' ||
value === 'stake' ||
value === 'unstake' ||
value === 'transfer' ||
value === 'swap'
? value
: 'all'
}
function parseHoldingsActivityChainId(value: string | null): number | null {
const parsed = Number(value)
return Number.isInteger(parsed) && parsed > 0 ? parsed : null
}
function parseHoldingsActivityTimestamp(value: string | null): number | null {
if (!value) {
return null
}
const parsed = Number(value)
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null
}
function parseUtcDateParam(value: string | null): number | null {
if (!value) {
return null
}
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value)
if (!match) {
return null
}
const [, year, month, day] = match
const yearNumber = Number(year)
const monthNumber = Number(month)
const dayNumber = Number(day)
const utcDate = new Date(Date.UTC(yearNumber, monthNumber - 1, dayNumber))
if (
utcDate.getUTCFullYear() !== yearNumber ||
utcDate.getUTCMonth() !== monthNumber - 1 ||
utcDate.getUTCDate() !== dayNumber
) {
return null
}
const timestamp = Math.floor(utcDate.getTime() / 1000)
return Number.isFinite(timestamp) ? timestamp : null
}
async function parseJsonBody<T>(req: Request): Promise<T> {
try {
return (await req.json()) as T
} catch (_error) {
throw new Error('Invalid JSON body')
}
}
async function callTenderlyAdminRpc(canonicalChainId: number, method: string, params: unknown[]): Promise<unknown> {
const configuredChain = requireTenderlyServerChain(process.env, canonicalChainId)
const response = await fetch(configuredChain.adminRpcUri as string, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
id: 1,
jsonrpc: '2.0',
method,
params
})
})
if (!response.ok) {
const details = await response.text()
throw new Error(`Tenderly RPC request failed with status ${response.status}: ${details}`)
}
const payload = (await response.json()) as TTenderlyJsonRpcSuccess | TTenderlyJsonRpcError
if ('error' in payload) {
throw new Error(`${payload.error.message} (code ${payload.error.code})`)
}
return payload.result
}
function handleTenderlyStatus(req: Request): Response {
if (req.method !== 'GET') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
try {
return Response.json(buildTenderlyPanelStatus(process.env))
} catch (error) {
console.error('Error building Tenderly status:', error)
return Response.json(
{ error: error instanceof Error ? error.message : 'Failed to build Tenderly status' },
{ status: 500 }
)
}
}
async function handleTenderlySnapshot(req: Request): Promise<Response> {
if (req.method !== 'POST') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
try {
const body = await parseJsonBody<TTenderlySnapshotRequest>(req)
const configuredChain = requireTenderlyServerChain(process.env, body.canonicalChainId)
const snapshotId = await callTenderlyAdminRpc(body.canonicalChainId, 'evm_snapshot', [])
const snapshotRecord = buildTenderlySnapshotRecord({
canonicalChainId: body.canonicalChainId,
executionChainId: configuredChain.executionChainId,
snapshotId: String(snapshotId),
label: body.label,
isBaseline: body.isBaseline
})
return Response.json(snapshotRecord)
} catch (error) {
console.error('Error creating Tenderly snapshot:', error)
return Response.json(
{ error: error instanceof Error ? error.message : 'Failed to create Tenderly snapshot' },
{ status: 400 }
)
}
}
async function handleTenderlyRevert(req: Request): Promise<Response> {
if (req.method !== 'POST') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
try {
const body = await parseJsonBody<TTenderlyRevertRequest>(req)
const result = await callTenderlyAdminRpc(body.canonicalChainId, 'evm_revert', [body.snapshotId])
return Response.json(buildTenderlyRevertResponse(result, body.snapshotId))
} catch (error) {
console.error('Error reverting Tenderly snapshot:', error)
return Response.json(
{ error: error instanceof Error ? error.message : 'Failed to revert Tenderly snapshot' },
{ status: 400 }
)
}
}
async function handleTenderlyIncreaseTime(req: Request): Promise<Response> {
if (req.method !== 'POST') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
try {
const body = await parseJsonBody<TTenderlyIncreaseTimeRequest>(req)
if (!Number.isInteger(body.seconds) || body.seconds <= 0) {
throw new Error('seconds must be a positive integer')
}
const timeResult = await callTenderlyAdminRpc(body.canonicalChainId, 'evm_increaseTime', [
`0x${BigInt(body.seconds).toString(16)}`
])
const mineResult = body.mineBlock ? await callTenderlyAdminRpc(body.canonicalChainId, 'evm_mine', []) : undefined
return Response.json({
timeResult,
mineResult
})
} catch (error) {
console.error('Error increasing Tenderly time:', error)
return Response.json(
{ error: error instanceof Error ? error.message : 'Failed to increase Tenderly time' },
{ status: 400 }
)
}
}
async function handleTenderlyFund(req: Request): Promise<Response> {
if (req.method !== 'POST') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
try {
const body = await parseJsonBody<TTenderlyFundRequest>(req)
const { method, params } = resolveTenderlyFundRpcRequest(body)
const result = await callTenderlyAdminRpc(body.canonicalChainId, method, params)
return Response.json({
method,
result
})
} catch (error) {
console.error('Error funding Tenderly wallet:', error)
return Response.json(
{ error: error instanceof Error ? error.message : 'Failed to fund wallet on Tenderly' },
{ status: 400 }
)
}
}
async function handleSitemap(req: Request): Promise<Response> {
if (req.method !== 'GET' && req.method !== 'HEAD') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
try {
const upstream = await fetch(KONG_VAULT_LIST_URL, { headers: { Accept: 'application/json' } })
const vaults: TVaultListEntry[] = upstream.ok ? ((await upstream.json()) as TVaultListEntry[]) : []
return new Response(req.method === 'HEAD' ? null : buildSitemap(vaults), {
headers: {
'Content-Type': 'application/xml; charset=utf-8',
'Cache-Control': 'public, s-maxage=86400, stale-while-revalidate=3600'
}
})
} catch (error) {
console.error('Error generating sitemap:', error)
return new Response(
'<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>',
{
status: 500,
headers: { 'Content-Type': 'application/xml; charset=utf-8' }
}
)
}
}
async function handleVaultsMarkdown(req: Request): Promise<Response> {
if (req.method !== 'GET' && req.method !== 'HEAD') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
const chainIdParam = new URL(req.url).searchParams.get('chainId')
const chainId = chainIdParam && /^\d+$/.test(chainIdParam) ? Number(chainIdParam) : undefined
try {
const upstream = await fetch(KONG_VAULT_LIST_URL, { headers: { Accept: 'application/json' } })
if (!upstream.ok) return Response.json({ error: 'Failed to fetch vault list from upstream' }, { status: 502 })
const vaults = (await upstream.json()) as TVaultListEntry[]
return new Response(req.method === 'HEAD' ? null : buildVaultsMarkdown(vaults, chainId), {
headers: {
'Content-Type': 'text/markdown; charset=utf-8',
'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600'
}
})
} catch (error) {
console.error('Error generating vaults markdown:', error)
return Response.json({ error: 'Internal server error' }, { status: 500 })
}
}
async function handleVaultMarkdown(req: Request): Promise<Response> {
if (req.method !== 'GET' && req.method !== 'HEAD') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
const params = new URL(req.url).searchParams
const chainId = params.get('chainId')
const address = params.get('address')
if (!chainId || !address) return Response.json({ error: 'Missing chainId or address' }, { status: 400 })
if (!/^\d+$/.test(chainId)) return Response.json({ error: 'Invalid chainId' }, { status: 400 })
if (!/^0x[a-fA-F0-9]{40}$/.test(address)) return Response.json({ error: 'Invalid address' }, { status: 400 })
try {
const upstream = await fetch(`${KONG_REST_BASE}/snapshot/${chainId}/${address}`, {
headers: { Accept: 'application/json' }
})
if (!upstream.ok) {
return Response.json(
{ error: upstream.status === 404 ? 'Vault not found' : 'Upstream error' },
{ status: upstream.status === 404 ? 404 : 502 }
)
}
const snapshot = (await upstream.json()) as TVaultSnapshot
return new Response(req.method === 'HEAD' ? null : buildVaultMarkdown(snapshot, Number(chainId), address), {
headers: {
'Content-Type': 'text/markdown; charset=utf-8',
'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600'
}
})
} catch (error) {
console.error('Error generating vault markdown:', error)
return Response.json({ error: 'Internal server error' }, { status: 500 })
}
}
function handleEnsoStatus(): Response {
const apiKey = process.env.ENSO_API_KEY
return Response.json({ configured: !!apiKey })
}
async function handleEnsoRoute(req: Request): Promise<Response> {
const url = new URL(req.url)
const fromAddress = url.searchParams.get('fromAddress')
const chainId = url.searchParams.get('chainId')
const tokenIn = url.searchParams.get('tokenIn')
const tokenOut = url.searchParams.get('tokenOut')
const amountIn = url.searchParams.get('amountIn')
const slippage = url.searchParams.get('slippage') || '100'
const routingStrategy = url.searchParams.get('routingStrategy')
const destinationChainId = url.searchParams.get('destinationChainId')
const receiver = url.searchParams.get('receiver')
if (!fromAddress || !chainId || !tokenIn || !tokenOut || !amountIn) {
return Response.json({ error: 'Missing required parameters' }, { status: 400 })
}
const apiKey = process.env.ENSO_API_KEY
if (!apiKey) {
console.error('ENSO_API_KEY not configured')
return Response.json({ error: 'Enso API not configured' }, { status: 500 })
}
const params = new URLSearchParams({
fromAddress,
chainId,
tokenIn,
tokenOut,
amountIn,
slippage
})
if (destinationChainId) {
params.set('destinationChainId', destinationChainId)
}
if (receiver) {
params.set('receiver', receiver)
}
if (routingStrategy) {
params.set('routingStrategy', routingStrategy)
}
const ensoUrl = `${ENSO_API_BASE}/api/v1/shortcuts/route?${params}`
try {
const response = await fetch(ensoUrl, {
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
})
const data = await response.json()
if (!response.ok) {
return Response.json(data, { status: response.status })
}
return Response.json(data)
} catch (error) {
console.error('Error proxying Enso route request:', error)
return Response.json({ error: 'Internal server error' }, { status: 500 })
}
}
async function handleEnsoBalances(req: Request): Promise<Response> {
const url = new URL(req.url)
const eoaAddress = url.searchParams.get('eoaAddress')
const chainId = url.searchParams.get('chainId')
if (!eoaAddress) {
return Response.json({ error: 'Missing eoaAddress' }, { status: 400 })
}
const apiKey = process.env.ENSO_API_KEY
if (!apiKey) {
console.error('ENSO_API_KEY not configured')
return Response.json({ error: 'Enso API not configured' }, { status: 500 })
}
const params = new URLSearchParams({
eoaAddress,
useEoa: 'true',
chainId: chainId || 'all'
})
const ensoUrl = `${ENSO_API_BASE}/api/v1/wallet/balances?${params}`
try {
const response = await fetch(ensoUrl, {
headers: {
Authorization: `Bearer ${apiKey}`
}
})
if (!response.ok) {
const errorText = await response.text()
console.error(`Enso API error: ${response.status}`, errorText)
return Response.json(
{ error: 'Enso API error', status: response.status, details: errorText },
{ status: response.status }
)
}
const data = await response.json()
return Response.json(data, {
headers: {
'Cache-Control': ENSO_BALANCES_CACHE_CONTROL
}
})
} catch (error) {
console.error('Error proxying Enso request:', error)
return Response.json({ error: 'Internal server error' }, { status: 500 })
}
}
const CHANGE_CACHE_CONTROL = 'public, s-maxage=600, stale-while-revalidate=60'
const ALIGNMENT_CACHE_CONTROL = 'public, s-maxage=60, stale-while-revalidate=30'
const VAULT_STATE_CACHE_CONTROL = 'public, s-maxage=60, stale-while-revalidate=30'
const HOLDINGS_HISTORY_CACHE_CONTROL = 'public, s-maxage=300, stale-while-revalidate=600'
const HOLDINGS_ACTIVITY_CACHE_CONTROL = 'public, s-maxage=60, stale-while-revalidate=300'
const HOLDINGS_ACTIVITY_FACETS_CACHE_CONTROL = 'public, s-maxage=300, stale-while-revalidate=900'
async function handleOptimizationChange(req: Request): Promise<Response> {
if (req.method !== 'GET') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
try {
const optimizations = await readOptimizations()
if (!optimizations || optimizations.length === 0) {
return Response.json({ error: 'No optimization data available' }, { status: 404 })
}
const url = new URL(req.url)
const requestedVault = url.searchParams.get('vault')
if (requestedVault) {
if (isHistoryQueryEnabled(url.searchParams.get('history'))) {
const selectedHistory = optimizations.filter((optimization) => {
return optimization.vault.toLowerCase() === requestedVault.toLowerCase()
})
if (selectedHistory.length === 0) {
return Response.json({ error: `Vault not found in optimization payload: ${requestedVault}` }, { status: 404 })
}
return Response.json(selectedHistory, {
headers: getVercelCdnCacheHeaders(CHANGE_CACHE_CONTROL)
})
}
const selected = findVaultOptimization(optimizations, requestedVault)
if (!selected) {
return Response.json({ error: `Vault not found in optimization payload: ${requestedVault}` }, { status: 404 })
}
return Response.json(selected, {
headers: getVercelCdnCacheHeaders(CHANGE_CACHE_CONTROL)
})
}
return Response.json(optimizations, {
headers: getVercelCdnCacheHeaders(CHANGE_CACHE_CONTROL)
})
} catch (error) {
if (isRedisAuthenticationError(error)) {
return Response.json({ error: REDIS_AUTHENTICATION_ERROR_MESSAGE }, { status: 500 })
}
if (isRedisConnectivityError(error)) {
return Response.json({ error: REDIS_CONNECTIVITY_ERROR_MESSAGE }, { status: 503 })
}
const message = error instanceof Error ? error.message : String(error)
return Response.json({ error: message }, { status: 500 })
}
}
async function handleOptimizationAlignment(req: Request): Promise<Response> {
if (req.method !== 'GET') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
const url = new URL(req.url)
const vault = url.searchParams.get('vault')
if (!vault) {
return Response.json({ error: 'vault parameter required' }, { status: 400 })
}
const envioUrl = process.env.ENVIO_GRAPHQL_URL
if (!envioUrl) {
return Response.json({ error: 'ENVIO_GRAPHQL_URL not configured' }, { status: 503 })
}
try {
const optimizations = await readOptimizations()
if (!optimizations || optimizations.length === 0) {
return Response.json({ error: 'No optimization data available' }, { status: 404 })
}
const optimization = findVaultOptimization(optimizations, vault)
if (!optimization) {
return Response.json({ error: `Vault not found: ${vault}` }, { status: 404 })
}
const metadataChainId = optimization.source.chainId ? undefined : parseExplainMetadata(optimization.explain).chainId
const chainId = optimization.source.chainId ?? metadataChainId
if (!chainId) {
return Response.json({ error: 'Could not determine chain ID for vault' }, { status: 400 })
}
const timestampStr = optimization.source.latestMatchedTimestampUtc ?? optimization.source.timestampUtc
if (!timestampStr) {
return Response.json({ error: 'No timestamp available for vault snapshot' }, { status: 400 })
}
const fromTs = Math.floor(new Date(timestampStr.replace(' UTC', 'Z').replace(' ', 'T')).getTime() / 1000)
const numStrategies = optimization.strategyDebtRatios.length
const toTs = fromTs + numStrategies * 10 * 60 * 2
const decimals = getVaultDecimals(vault)
const events = await fetchAlignedEvents(
envioUrl,
vault,
chainId,
optimization.strategyDebtRatios,
fromTs,
toTs,
decimals
)
return Response.json(events, {
headers: getVercelCdnCacheHeaders(ALIGNMENT_CACHE_CONTROL)
})
} catch (error) {
if (isRedisAuthenticationError(error)) {
return Response.json({ error: REDIS_AUTHENTICATION_ERROR_MESSAGE }, { status: 500 })
}
if (isRedisConnectivityError(error)) {
return Response.json({ error: REDIS_CONNECTIVITY_ERROR_MESSAGE }, { status: 503 })
}
const message = error instanceof Error ? error.message : String(error)
return Response.json({ error: message }, { status: 500 })
}
}
async function handleOptimizationVaultState(req: Request): Promise<Response> {
if (req.method !== 'POST') {
return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
let body: unknown
try {
body = await req.json()
} catch {
return Response.json({ error: 'Invalid JSON body' }, { status: 400 })
}
const payload = body && typeof body === 'object' ? (body as Record<string, unknown>) : {}
const vault = typeof payload.vault === 'string' ? payload.vault : null
const chainId = typeof payload.chainId === 'number' ? payload.chainId : null
const strategies = Array.isArray(payload.strategies)
? payload.strategies.filter((strategy: unknown): strategy is string => typeof strategy === 'string')
: []
if (!vault || !isValidAddress(vault)) {
return Response.json({ error: 'Invalid vault address' }, { status: 400 })
}
if (chainId === null || !Number.isFinite(chainId)) {
return Response.json({ error: 'Invalid chainId' }, { status: 400 })
}
if (strategies.length === 0) {
return Response.json({ error: 'No strategy addresses provided' }, { status: 400 })
}
try {
const state = await fetchVaultOnChainState(chainId, vault, strategies)
const strategyDebts = Object.fromEntries(
[...state.strategyDebts].map(([strategyAddress, debt]) => [strategyAddress, debt.toString()])
)
return Response.json(
{
totalAssets: state.totalAssets.toString(),
strategyDebts,
unallocatedBps: state.unallocatedBps
},
{
headers: getVercelCdnCacheHeaders(VAULT_STATE_CACHE_CONTROL)
}
)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return Response.json({ error: message }, { status: 503 })
}
}
async function handleHoldingsHistory(req: Request): Promise<Response> {
const url = new URL(req.url)
const address = url.searchParams.get('address')
const versionParam = url.searchParams.get('version')
const fetchType = parseHoldingsEventFetchType(url.searchParams.get('fetchType'))
const paginationMode = parseHoldingsEventPaginationMode(url.searchParams.get('paginationMode'))
const denomination = parseHoldingsHistoryDenomination(url.searchParams.get('denomination'))
const timeframe = parseHoldingsHistoryTimeframe(url.searchParams.get('timeframe'))
const vaultFilters = parseVaultFilters(url)
const debugEnabled =
isHoldingsDebugRequested(url.searchParams.get('debug')) || isHoldingsDebugRequested(process.env.HOLDINGS_DEBUG)
const debugLotsEnabled = isHoldingsDebugRequested(url.searchParams.get('debugLots'))
const debugVault = url.searchParams.get('debugVault')
const debugTx = url.searchParams.get('debugTx')
const refreshParam = url.searchParams.get('refresh')
const progressId = url.searchParams.get('progressId')
const refresh = refreshParam === 'true' || refreshParam === '1'
if (!address) {
return Response.json({ error: 'Missing required parameter: address', status: 400 }, { status: 400 })
}
if (!isValidAddress(address)) {
return Response.json({ error: 'Invalid Ethereum address', status: 400 }, { status: 400 })
}
if (vaultFilters === null) {
return Response.json({ error: 'Invalid vault filter', status: 400 }, { status: 400 })
}
const version: VaultVersion = versionParam === 'v2' || versionParam === 'v3' ? versionParam : 'all'
try {
const activeProgressId = await startHoldingsProgress({
id: progressId,
route: 'history',
address,
message: 'Fetching historical user data'
})
await updateHoldingsProgress(activeProgressId, {
progress: 8,
message: 'Fetching historical user data',
detail: null
})
if (refresh) {
const cleared = await clearUserCache(address, getHoldingsTotalsCacheVersion(version))
console.log(`[Server] Cleared ${cleared} cached entries for ${address}`)
}
const holdings = await withHoldingsDebugContext(
createHoldingsDebugContext('history', address, debugEnabled, {
lotsEnabled: debugLotsEnabled,
vaultFilter: debugVault,
txFilter: debugTx,
progressId: activeProgressId
}),
async () => {
debugLog('route', 'started holdings history request', {
version,
fetchType,
paginationMode,
refresh,
debugLotsEnabled,
debugVault: debugVault?.toLowerCase() ?? null,
debugTx: debugTx?.toLowerCase() ?? null
})
try {
const response = await getHistoricalHoldingsChart(
address,
version,
fetchType,
paginationMode,
denomination,
timeframe,
vaultFilters
)
debugLog('route', 'completed holdings history request', {
version,
fetchType,
paginationMode,
denomination,
timeframe,
refresh,
points: response.dataPoints.length,
nonZeroPoints: response.dataPoints.filter((point) => point.value > 0).length
})
return response
} catch (error) {
debugError('route', 'holdings history request failed', error, { version, fetchType, paginationMode })
throw error
}
}
)
if (!holdings.hasActivity) {
await updateHoldingsProgress(activeProgressId, {
status: 'complete',
progress: 100,
message: 'No historical holdings found',
detail: null
})
return Response.json({ error: 'No holdings found for address', status: 404 }, { status: 404 })
}
await updateHoldingsProgress(activeProgressId, {
status: 'complete',
progress: 100,
message: 'Historical user data ready',
detail: `${holdings.dataPoints.length} chart points`
})
return Response.json(
{
address: holdings.address,
version,
denomination,
timeframe,
dataPoints: holdings.dataPoints.map((dp) => ({
date: dp.date,
value: dp.value
}))
},
{
headers: getVercelCdnCacheHeaders(HOLDINGS_HISTORY_CACHE_CONTROL)
}
)
} catch (error) {
await updateHoldingsProgress(progressId, {
status: 'error',
message: 'Failed to fetch historical user data',
detail: error instanceof Error ? error.message : String(error)
})
console.error('Error fetching holdings history:', error)
const message = error instanceof Error ? error.message : String(error)
const stack = error instanceof Error ? error.stack : undefined
return Response.json({ error: 'Failed to fetch historical holdings', message, stack, status: 502 }, { status: 502 })
}