-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathservice.ts
More file actions
428 lines (379 loc) · 12.8 KB
/
service.ts
File metadata and controls
428 lines (379 loc) · 12.8 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
import {
BaseServiceV2,
StandardOptions,
ExpressRouter,
Gauge,
validators,
waitForProvider,
} from '@eth-optimism/common-ts'
import { sleep } from '@eth-optimism/core-utils'
import { Provider } from '@ethersproject/abstract-provider'
import { BigNumber, ethers } from 'ethers'
import { version } from '../../package.json'
import { LockupAbi } from '../../lib/abi/LockupAbi'
import { MockTokenAbi } from '../../lib/abi/MockTokenAbi'
type Options = {
rpcProvider: Provider
lockupProxyAddress: string
sleepTimeMs: number
lockupIndexingStartBlock: number
bufferBlockCount: number
}
type Metrics = {
nodeConnectionFailures: Gauge
lockupEventsCount: Gauge
claimEventsCount: Gauge
totalLockedAmount: Gauge
totalClaimedAmount: Gauge
invariantViolations: Gauge
lockupContractBalance: Gauge
}
type LockupEvent = {
id: number
token: string
recipient: string
amount: BigNumber
blockNumber: number
}
type ClaimEvent = {
id: number
token: string
recipient: string
amount: BigNumber
blockNumber: number
}
type TokenBalance = {
locked: BigNumber
claimed: BigNumber
lastUpdatedBlock: number
}
type State = {
lockupProxy: ethers.Contract
lockupEvents: LockupEvent[]
claimEvents: ClaimEvent[]
tokenBalances: Map<string, Map<string, TokenBalance>>
lastProcessedBlockNumber: number
isInitialSyncComplete: boolean
}
export class LockupMonitor extends BaseServiceV2<Options, Metrics, State> {
constructor(options?: Partial<Options & StandardOptions>) {
super({
version,
name: 'lockup-monitor',
loop: true,
options: {
loopIntervalMs: 60000, // Run every minute
bufferBlockCount: 5, // Default buffer of 5 blocks
...options,
},
optionsSpec: {
rpcProvider: {
validator: validators.provider,
desc: 'Provider for interacting with the network',
},
lockupProxyAddress: {
validator: validators.address,
desc: 'Address of the lockup proxy',
},
sleepTimeMs: {
validator: validators.num,
default: 15000,
desc: 'Time in ms to sleep when waiting for a node',
public: true,
},
lockupIndexingStartBlock: {
validator: validators.num,
default: 0,
desc: 'Block number to start indexing lockups from',
},
bufferBlockCount: {
validator: validators.num,
default: 5,
desc: 'Number of blocks to use as a buffer before checking invariants',
},
},
metricsSpec: {
nodeConnectionFailures: {
type: Gauge,
desc: 'Number of times node connection has failed',
labels: ['layer'],
},
lockupEventsCount: {
type: Gauge,
desc: 'Number of lockup events',
labels: ['token'],
},
claimEventsCount: {
type: Gauge,
desc: 'Number of claim events',
labels: ['token'],
},
totalLockedAmount: {
type: Gauge,
desc: 'Total locked amount per token',
labels: ['token'],
},
totalClaimedAmount: {
type: Gauge,
desc: 'Total claimed amount per token',
labels: ['token'],
},
invariantViolations: {
type: Gauge,
desc: 'Number of invariant violations (claimed > locked for token and recipient)',
labels: ['token', 'recipient'],
},
lockupContractBalance: {
type: Gauge,
desc: 'Balance of the lockup contract',
labels: ['token'],
},
},
})
}
async init(): Promise<void> {
await waitForProvider(this.options.rpcProvider, {
logger: this.logger,
name: 'L1',
})
this.state.lockupProxy = new ethers.Contract(
this.options.lockupProxyAddress,
LockupAbi,
this.options.rpcProvider
)
this.state.lockupEvents = []
this.state.claimEvents = []
this.state.tokenBalances = new Map()
this.state.lastProcessedBlockNumber =
this.options.lockupIndexingStartBlock - 1
this.state.isInitialSyncComplete = false
await this.indexPreviousEvents()
}
async routes(router: ExpressRouter): Promise<void> {
router.get('/healthz', async (req, res) => {
return res.status(200).json({
ok: true,
})
})
}
private async indexPreviousEvents(): Promise<void> {
console.log(
`Indexing previous events starting from block ${this.options.lockupIndexingStartBlock}...`
)
const latestBlock = await this.options.rpcProvider.getBlock('latest')
const lockupFilter = this.state.lockupProxy.filters.NewLockup()
const lockupEvents = await this.state.lockupProxy.queryFilter(
lockupFilter,
this.options.lockupIndexingStartBlock,
latestBlock.number
)
const claimFilter = this.state.lockupProxy.filters.LockupClaimed()
const claimEvents = await this.state.lockupProxy.queryFilter(
claimFilter,
this.options.lockupIndexingStartBlock,
latestBlock.number
)
console.log(
`Found ${lockupEvents.length} lockup events and ${claimEvents.length} claim events`
)
this.processEvents(lockupEvents, claimEvents)
this.state.lastProcessedBlockNumber = latestBlock.number
this.state.isInitialSyncComplete = true
console.log(
`Finished indexing previous events up to block ${latestBlock.number}`
)
// this.logAllBalances()
}
private processEvents(
lockupEvents: ethers.Event[],
claimEvents: ethers.Event[]
): void {
const allEvents = [...lockupEvents, ...claimEvents].sort((a, b) => {
if (a.blockNumber !== b.blockNumber) {
return a.blockNumber - b.blockNumber
}
return a.transactionIndex - b.transactionIndex
})
for (const event of allEvents) {
if (event.event === 'NewLockup') {
this.processLockupEvent(event)
} else if (event.event === 'LockupClaimed') {
this.processClaimEvent(event)
}
}
}
private processLockupEvent(event: ethers.Event): void {
const lockupInfo = event.args.l
const newLockup: LockupEvent = {
id: lockupInfo.id.toNumber(),
token: lockupInfo.token,
recipient: lockupInfo.recipient,
amount: lockupInfo.amount,
blockNumber: event.blockNumber,
}
this.state.lockupEvents.push(newLockup)
if (!this.state.tokenBalances.has(newLockup.token)) {
this.state.tokenBalances.set(newLockup.token, new Map())
}
const tokenBalances = this.state.tokenBalances.get(newLockup.token)!
const currentBalance = tokenBalances.get(newLockup.recipient) || {
locked: BigNumber.from(0),
claimed: BigNumber.from(0),
lastUpdatedBlock: 0,
}
const newBalance = {
locked: currentBalance.locked.add(newLockup.amount),
claimed: currentBalance.claimed,
lastUpdatedBlock: newLockup.blockNumber,
}
tokenBalances.set(newLockup.recipient, newBalance)
// console.log(`Processed lockup event:`)
// console.log(` ID: ${newLockup.id}`)
// console.log(` Token: ${newLockup.token}`)
// console.log(` Recipient: ${newLockup.recipient}`)
// console.log(` Amount: ${newLockup.amount.toString()}`)
// console.log(` Block: ${newLockup.blockNumber}`)
// console.log(` New Balance:`)
// console.log(` Locked: ${newBalance.locked.toString()}`)
// console.log(` Claimed: ${newBalance.claimed.toString()}`)
}
private processClaimEvent(event: ethers.Event): void {
const claimInfo = event.args.l
const newClaim: ClaimEvent = {
id: claimInfo.id.toNumber(),
token: claimInfo.token,
recipient: claimInfo.recipient,
amount: claimInfo.amount,
blockNumber: event.blockNumber,
}
this.state.claimEvents.push(newClaim)
if (!this.state.tokenBalances.has(newClaim.token)) {
this.state.tokenBalances.set(newClaim.token, new Map())
}
const tokenBalances = this.state.tokenBalances.get(newClaim.token)!
const currentBalance = tokenBalances.get(newClaim.recipient) || {
locked: BigNumber.from(0),
claimed: BigNumber.from(0),
lastUpdatedBlock: 0,
}
const newBalance = {
locked: currentBalance.locked, // Keep the locked amount as is
claimed: currentBalance.claimed.add(newClaim.amount),
lastUpdatedBlock: event.blockNumber,
}
tokenBalances.set(newClaim.recipient, newBalance)
}
private convertToDecimal(amount: BigNumber, decimals: number): number {
const amountString = ethers.utils.formatUnits(amount, decimals)
return parseFloat(amountString)
}
private async updateLockupBalanceMetrics(tokenAddress: string): Promise<void> {
const mockToken = new ethers.Contract(
tokenAddress,
MockTokenAbi,
this.options.rpcProvider
)
const balance = await mockToken.balanceOf(this.options.lockupProxyAddress)
this.metrics.lockupContractBalance.set(
{ token: tokenAddress },
this.convertToDecimal(balance, 18)
)
}
private async updateMetrics(currentBlockNumber: number): Promise<void> {
const lockupTokens = new Set(this.state.lockupEvents.map((e) => e.token))
for (const token of lockupTokens) {
const count = this.state.lockupEvents.filter(
(e) => e.token === token
).length
this.metrics.lockupEventsCount.set({ token }, count)
await this.updateLockupBalanceMetrics(token)
}
const claimTokens = new Set(this.state.claimEvents.map((e) => e.token))
for (const token of claimTokens) {
const count = this.state.claimEvents.filter(
(e) => e.token === token
).length
this.metrics.claimEventsCount.set({ token }, count)
await this.updateLockupBalanceMetrics(token)
}
for (const [token, balances] of this.state.tokenBalances) {
for (const [recipient, balance] of balances) {
this.metrics.totalLockedAmount.set(
{ token },
this.convertToDecimal(balance.locked, 18)
)
this.metrics.totalClaimedAmount.set(
{ token },
this.convertToDecimal(balance.claimed, 18)
)
if (
this.state.isInitialSyncComplete &&
currentBlockNumber >=
balance.lastUpdatedBlock + this.options.bufferBlockCount &&
balance.claimed.gt(balance.locked)
) {
this.metrics.invariantViolations.set({ token, recipient }, 1)
console.warn(`Invariant violation detected:`)
console.warn(` Token: ${token}`)
console.warn(` Recipient: ${recipient}`)
console.warn(` Locked: ${balance.locked.toString()}`)
console.warn(` Claimed: ${balance.claimed.toString()}`)
console.warn(` Last Updated Block: ${balance.lastUpdatedBlock}`)
console.warn(` Current Block: ${currentBlockNumber}`)
} else {
this.metrics.invariantViolations.set({ token, recipient }, 0)
}
}
}
}
private logAllBalances(): void {
console.log('Current state of all balances:')
for (const [token, balances] of this.state.tokenBalances) {
for (const [recipient, balance] of balances) {
console.log(`Token: ${token}, Recipient: ${recipient}`)
console.log(` Locked: ${balance.locked.toString()}`)
console.log(` Claimed: ${balance.claimed.toString()}`)
console.log(` Last Updated Block: ${balance.lastUpdatedBlock}`)
}
}
}
async main(): Promise<void> {
const latestBlock = await this.options.rpcProvider.getBlock('latest')
const fromBlock = Math.min(
this.state.lastProcessedBlockNumber + 1,
latestBlock.number
)
if (fromBlock > latestBlock.number) {
console.log(
`No new blocks to process. Current: ${this.state.lastProcessedBlockNumber}, Latest: ${latestBlock.number}`
)
await this.updateMetrics(latestBlock.number)
return sleep(this.options.sleepTimeMs)
}
console.log(`Processing blocks from ${fromBlock} to ${latestBlock.number}`)
const lockupFilter = this.state.lockupProxy.filters.NewLockup()
const newLockupEvents = await this.state.lockupProxy.queryFilter(
lockupFilter,
fromBlock,
latestBlock.number
)
const claimFilter = this.state.lockupProxy.filters.LockupClaimed()
const newClaimEvents = await this.state.lockupProxy.queryFilter(
claimFilter,
fromBlock,
latestBlock.number
)
this.processEvents(newLockupEvents, newClaimEvents)
this.state.lastProcessedBlockNumber = latestBlock.number
await this.updateMetrics(latestBlock.number)
console.log(
`Processed ${newLockupEvents.length} new lockup events and ${newClaimEvents.length} new claim events up to block ${latestBlock.number}`
)
// this.logAllBalances()
return sleep(this.options.sleepTimeMs)
}
}
if (require.main === module) {
const service = new LockupMonitor()
service.run()
}