-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathCacheService.ts
More file actions
372 lines (335 loc) · 10.1 KB
/
CacheService.ts
File metadata and controls
372 lines (335 loc) · 10.1 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
import { HexString } from "@hyperbridge/sdk"
import { getLogger } from "./Logger"
interface GasEstimateCache {
totalCostInSourceFeeToken: string
dispatchFee: string
nativeDispatchFee: string
callGasLimit: string
verificationGasLimit: string
preVerificationGas: string
maxFeePerGas: string
maxPriorityFeePerGas: string
nonce: string
totalGasCostWei: string
timestamp: number
}
interface SwapCall {
to: string
data: string
value: string
}
interface SwapOperationsCache {
calls: SwapCall[]
totalGasEstimate: string
timestamp: number
}
interface FillerOutputCache {
token: HexString
amount: string
}
interface FillerOutputsCache {
outputs: FillerOutputCache[]
timestamp: number
}
export interface CachedPairClassification {
inputIsStable: boolean
stableToken: string
exoticToken: string
}
interface PairClassificationsCache {
pairs: CachedPairClassification[]
timestamp: number
}
interface CacheData {
gasEstimates: Record<string, GasEstimateCache>
swapOperations: Record<string, SwapOperationsCache>
fillerOutputs: Record<string, FillerOutputsCache>
pairClassifications: Record<string, PairClassificationsCache>
feeTokens: Record<string, { address: HexString; decimals: number }>
perByteFees: Record<string, Record<string, bigint>>
tokenDecimals: Record<string, Record<HexString, number>>
solverSelection: Record<string, boolean>
}
export class CacheService {
private cacheData: CacheData
private readonly CACHE_EXPIRY_MS = 1 * 60 * 1000 // 1 minute
private logger = getLogger("cache-service")
constructor() {
this.cacheData = {
gasEstimates: {},
swapOperations: {},
fillerOutputs: {},
pairClassifications: {},
feeTokens: {},
perByteFees: {},
tokenDecimals: {},
solverSelection: {},
}
}
private isCacheValid(timestamp: number): boolean {
return Date.now() - timestamp < this.CACHE_EXPIRY_MS
}
private cleanupStaleData(): void {
// Clean up gas estimates
const staleGasEstimateIds = Object.entries(this.cacheData.gasEstimates)
.filter(([_, data]) => !this.isCacheValid(data.timestamp))
.map(([orderId]) => orderId)
staleGasEstimateIds.forEach((orderId) => {
delete this.cacheData.gasEstimates[orderId]
})
// Clean up swap operations
const staleSwapOperationIds = Object.entries(this.cacheData.swapOperations)
.filter(([_, data]) => !this.isCacheValid(data.timestamp))
.map(([orderId]) => orderId)
staleSwapOperationIds.forEach((orderId) => {
delete this.cacheData.swapOperations[orderId]
})
// Clean up filler outputs
const staleFillerOutputIds = Object.entries(this.cacheData.fillerOutputs)
.filter(([_, data]) => !this.isCacheValid(data.timestamp))
.map(([orderId]) => orderId)
staleFillerOutputIds.forEach((orderId) => {
delete this.cacheData.fillerOutputs[orderId]
})
// Clean up pair classifications
const stalePairIds = Object.entries(this.cacheData.pairClassifications)
.filter(([_, data]) => !this.isCacheValid(data.timestamp))
.map(([orderId]) => orderId)
stalePairIds.forEach((orderId) => {
delete this.cacheData.pairClassifications[orderId]
})
}
getGasEstimate(orderId: string): {
totalCostInSourceFeeToken: bigint
dispatchFee: bigint
nativeDispatchFee: bigint
callGasLimit: bigint
verificationGasLimit: bigint
preVerificationGas: bigint
maxFeePerGas: bigint
maxPriorityFeePerGas: bigint
nonce: bigint
totalGasCostWei: bigint
} | null {
try {
const cache = this.cacheData.gasEstimates[orderId]
if (cache && this.isCacheValid(cache.timestamp)) {
return {
totalCostInSourceFeeToken: BigInt(cache.totalCostInSourceFeeToken),
dispatchFee: BigInt(cache.dispatchFee),
nativeDispatchFee: BigInt(cache.nativeDispatchFee),
callGasLimit: BigInt(cache.callGasLimit),
verificationGasLimit: BigInt(cache.verificationGasLimit),
preVerificationGas: BigInt(cache.preVerificationGas),
maxFeePerGas: BigInt(cache.maxFeePerGas),
maxPriorityFeePerGas: BigInt(cache.maxPriorityFeePerGas),
nonce: BigInt(cache.nonce),
totalGasCostWei: BigInt(cache.totalGasCostWei),
}
}
return null
} catch (error) {
this.logger.error({ err: error }, "Error getting gas estimate")
return null
}
}
setGasEstimate(
orderId: string,
totalCostInSourceFeeToken: bigint,
dispatchFee: bigint,
nativeDispatchFee: bigint,
callGasLimit: bigint,
verificationGasLimit: bigint,
preVerificationGas: bigint,
maxFeePerGas: bigint,
maxPriorityFeePerGas: bigint,
nonce: bigint,
totalGasCostWei: bigint,
): void {
if (totalCostInSourceFeeToken <= 0n) {
throw new Error("Total cost in source fee token must be positive")
}
try {
this.cleanupStaleData()
this.cacheData.gasEstimates[orderId] = {
totalCostInSourceFeeToken: totalCostInSourceFeeToken.toString(),
dispatchFee: dispatchFee.toString(),
nativeDispatchFee: nativeDispatchFee.toString(),
callGasLimit: callGasLimit.toString(),
verificationGasLimit: verificationGasLimit.toString(),
preVerificationGas: preVerificationGas.toString(),
maxFeePerGas: maxFeePerGas.toString(),
maxPriorityFeePerGas: maxPriorityFeePerGas.toString(),
nonce: nonce.toString(),
totalGasCostWei: totalGasCostWei.toString(),
timestamp: Date.now(),
}
} catch (error) {
this.logger.error({ err: error }, "Error setting gas estimate")
throw error
}
}
getSwapOperations(orderId: string): { calls: SwapCall[]; totalGasEstimate: bigint } | null {
try {
const cache = this.cacheData.swapOperations[orderId]
if (cache && this.isCacheValid(cache.timestamp)) {
return {
calls: cache.calls,
totalGasEstimate: BigInt(cache.totalGasEstimate),
}
}
return null
} catch (error) {
this.logger.error({ err: error }, "Error getting swap operations")
return null
}
}
setSwapOperations(orderId: string, calls: SwapCall[], totalGasEstimate: bigint): void {
try {
this.cleanupStaleData()
this.cacheData.swapOperations[orderId] = {
calls,
totalGasEstimate: totalGasEstimate.toString(),
timestamp: Date.now(),
}
} catch (error) {
this.logger.error({ err: error }, "Error setting swap operations")
throw error
}
}
getFillerOutputs(orderId: string): { token: HexString; amount: bigint }[] | null {
try {
const cache = this.cacheData.fillerOutputs[orderId]
if (cache && this.isCacheValid(cache.timestamp)) {
return cache.outputs.map((o) => ({
token: o.token,
amount: BigInt(o.amount),
}))
}
return null
} catch (error) {
this.logger.error({ err: error }, "Error getting filler outputs")
return null
}
}
setFillerOutputs(orderId: string, outputs: { token: HexString; amount: bigint }[]): void {
try {
this.cleanupStaleData()
this.cacheData.fillerOutputs[orderId] = {
outputs: outputs.map((o) => ({
token: o.token,
amount: o.amount.toString(),
})),
timestamp: Date.now(),
}
} catch (error) {
this.logger.error({ err: error }, "Error setting filler outputs")
throw error
}
}
getPairClassifications(orderId: string): CachedPairClassification[] | null {
try {
const cache = this.cacheData.pairClassifications[orderId]
if (cache && this.isCacheValid(cache.timestamp)) {
return cache.pairs
}
return null
} catch (error) {
this.logger.error({ err: error }, "Error getting pair classifications")
return null
}
}
setPairClassifications(orderId: string, pairs: CachedPairClassification[]): void {
try {
this.cacheData.pairClassifications[orderId] = {
pairs,
timestamp: Date.now(),
}
} catch (error) {
this.logger.error({ err: error }, "Error setting pair classifications")
throw error
}
}
getFeeTokenWithDecimals(chain: string): { address: HexString; decimals: number } | null {
try {
const cache = this.cacheData.feeTokens[chain]
if (cache) {
return {
address: cache.address,
decimals: cache.decimals,
}
}
return null
} catch (error) {
this.logger.error({ err: error }, "Error getting fee token with decimals")
return null
}
}
setFeeTokenWithDecimals(chain: string, address: HexString, decimals: number): void {
try {
this.cleanupStaleData()
this.cacheData.feeTokens[chain] = { address, decimals }
} catch (error) {
this.logger.error({ chain: chain, err: error }, "Error setting fee token with decimals")
throw error
}
}
getPerByteFee(sourceChain: string, destChain: string): bigint | null {
try {
const sourceMap = this.cacheData.perByteFees[sourceChain]
if (sourceMap && sourceMap[destChain]) {
return sourceMap[destChain]
}
return null
} catch (error) {
this.logger.error({ err: error }, "Error getting per byte fee")
return null
}
}
setPerByteFee(sourceChain: string, destChain: string, perByteFee: bigint): void {
try {
this.cleanupStaleData()
if (!this.cacheData.perByteFees[sourceChain]) {
this.cacheData.perByteFees[sourceChain] = {}
}
this.cacheData.perByteFees[sourceChain][destChain] = perByteFee
} catch (error) {
this.logger.error(
{ sourceChain: sourceChain, destChain: destChain, err: error },
"Error setting per byte fee",
)
throw error
}
}
getTokenDecimals(chain: string, tokenAddress: HexString): number | null {
try {
const chainCache = this.cacheData.tokenDecimals[chain]
if (chainCache && chainCache[tokenAddress]) {
return chainCache[tokenAddress]
}
return null
} catch {
return null
}
}
setTokenDecimals(chain: string, tokenAddress: HexString, decimals: number): void {
try {
this.cleanupStaleData()
// Ensure the chain object exists before setting the token decimals
if (!this.cacheData.tokenDecimals[chain]) {
this.cacheData.tokenDecimals[chain] = {}
}
this.cacheData.tokenDecimals[chain][tokenAddress] = decimals
} catch (error) {
this.logger.error({ chain: chain, tokenAddress: tokenAddress, err: error }, "Error setting token decimals")
throw error
}
}
getSolverSelection(chain: string): boolean | null {
const cached = this.cacheData.solverSelection[chain]
return cached !== undefined ? cached : null
}
setSolverSelection(chain: string, active: boolean): void {
this.cacheData.solverSelection[chain] = active
}
}