-
Notifications
You must be signed in to change notification settings - Fork 22
/
balancewatcher.ts
340 lines (318 loc) · 13.8 KB
/
balancewatcher.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
import { createModuleDebug } from './utils/debug';
import { ManagedResource } from './utils/resource';
import { EthereumClient } from './eth/client';
import { Output, OutputMessage } from './output';
import { BalanceWatcherConfig } from './config';
import { NodePlatformAdapter } from './platforms';
import { ABORT, AbortHandle } from './utils/abort';
import { linearBackoff, resolveWaitTime, retry, WaitTime } from './utils/retry';
import { Cache } from './utils/cache';
import { ContractInfo } from './abi/contract';
import { AggregateMetric } from './utils/stats';
import { blockNumber, ethBalance, ethCall, getBlock, getTransactionReceipt } from './eth/requests';
import { BlockRange, blockRangeSize, blockRangeToArray, chunkedBlockRanges, serializeBlockRange } from './blockrange';
import { parallel, sleep } from './utils/async';
import { RawBlockResponse, RawTransactionResponse } from './eth/responses';
import { bigIntToNumber } from './utils/bn';
import { formatBlock, formatHexToFloatingPoint } from './format';
import { parseBlockTime } from './blockwatcher';
import { BalanceMessage, FormattedBlock } from './msgs';
import { sha3 } from './abi/wasm';
import { Checkpoint } from './state';
const { debug, info, warn, error, trace } = createModuleDebug('balancewatcher');
const transferEventSignature = sha3('Transfer(address,address,uint256)')!;
const initialCounters = {
blocksProcessed: 0,
transfersProcessed: 0,
};
/**
* BalanceWatcher will watch the activity of a contract on chain, and keep track of all accounts transferring tokens.
*/
export class BalanceWatcher implements ManagedResource {
private active: boolean = true;
private ethClient: EthereumClient;
private checkpoint: Checkpoint;
private output: Output;
private config: BalanceWatcherConfig;
private nodePlatform: NodePlatformAdapter;
private abortHandle = new AbortHandle();
private endCallbacks: Array<() => void> = [];
private waitAfterFailure: WaitTime;
private chunkQueueMaxSize: number;
private counters = { ...initialCounters };
private aggregates = {
blockProcessTime: new AggregateMetric(),
txProcessTime: new AggregateMetric(),
eventProcessTime: new AggregateMetric(),
};
constructor({
ethClient,
checkpoint,
output,
config,
waitAfterFailure = linearBackoff({ min: 0, step: 2500, max: 120_000 }),
chunkQueueMaxSize = 1000,
nodePlatform,
}: {
ethClient: EthereumClient;
output: Output;
checkpoint: Checkpoint;
config: BalanceWatcherConfig;
waitAfterFailure?: WaitTime;
chunkQueueMaxSize?: number;
contractInfoCache?: Cache<string, Promise<ContractInfo>>;
nodePlatform: NodePlatformAdapter;
}) {
this.ethClient = ethClient;
this.checkpoint = checkpoint;
this.output = output;
this.config = config;
this.waitAfterFailure = waitAfterFailure;
this.chunkQueueMaxSize = chunkQueueMaxSize;
this.nodePlatform = nodePlatform;
}
async start(): Promise<void> {
debug('Starting balances watcher for %s', this.config.contractAddress);
const { ethClient, checkpoint } = this;
if (checkpoint.isEmpty()) {
if (typeof this.config.startAt === 'number') {
if (this.config.startAt < 0) {
const latestBlockNumber = await ethClient.request(blockNumber());
checkpoint.setInitialBlockNumber(Math.max(0, latestBlockNumber + this.config.startAt));
} else {
checkpoint.setInitialBlockNumber(this.config.startAt);
}
} else if (this.config.startAt === 'genesis') {
checkpoint.setInitialBlockNumber(0);
} else if (this.config.startAt === 'latest') {
const latestBlockNumber = await ethClient.request(blockNumber());
checkpoint.setInitialBlockNumber(latestBlockNumber);
} else {
throw new Error(`Invalid start block: ${JSON.stringify(this.config.startAt)}`);
}
info(
'Determined initial block number: %d from configured value %o',
checkpoint.getinitialBlockNumber(),
this.config.startAt
);
}
let failures = 0;
while (this.active) {
try {
let latestBlockNumber = await ethClient.request(blockNumber());
debug('Received latest block number: %d', latestBlockNumber);
const reachedEnd = this.config.endAt !== undefined && latestBlockNumber > this.config.endAt;
if (reachedEnd) {
latestBlockNumber = this.config.endAt as number;
debug('Processing up to end of range %d', latestBlockNumber);
}
const todo = checkpoint.getIncompleteRanges(latestBlockNumber);
debug('Found %d block ranges to process', todo.length);
if (todo.length) {
info(
'Latest block number is %d - processing remaining %d blocks',
latestBlockNumber,
todo.map(blockRangeSize).reduce((a, b) => a + b, 0)
);
}
if (reachedEnd && todo.length == 0) {
info('Completed collecting blocks from %o to %d', this.config.startAt, this.config.endAt);
this.active = false;
}
for (const range of todo) {
if (!this.active) {
throw ABORT;
}
await parallel(
chunkedBlockRanges(range, this.config.blocksMaxChunkSize, this.chunkQueueMaxSize).map(
chunk => async () => {
if (!this.active) {
return;
}
await retry(() => this.processChunk(chunk), {
attempts: 100,
waitBetween: this.waitAfterFailure,
taskName: `block range ${serializeBlockRange(chunk)}`,
abortHandle: this.abortHandle,
warnOnError: true,
onRetry: attempt =>
warn(
'Retrying to process block range %s (attempt %d)',
serializeBlockRange(chunk),
attempt
),
});
}
),
{ maxConcurrent: this.config.maxParallelChunks, abortHandle: this.abortHandle }
);
failures = 0;
}
} catch (e) {
if (e === ABORT) {
break;
}
error('Error in block watcher polling loop', e);
failures++;
const waitTime = resolveWaitTime(this.waitAfterFailure, failures);
if (waitTime > 0) {
warn('Waiting for %d ms after %d consecutive failures', waitTime, failures);
await this.abortHandle.race(sleep(waitTime));
}
}
if (this.active) {
try {
await this.abortHandle.race(sleep(this.config.pollInterval));
} catch (e) {
if (e === ABORT) {
break;
} else {
warn('Unexpected error while waiting for next polling loop iteration', e);
}
}
}
}
if (this.endCallbacks != null) {
this.endCallbacks.forEach(cb => cb());
}
info('Balances watcher stopped');
}
async processChunk(chunk: BlockRange) {
const startTime = Date.now();
info('Processing chunk %s', serializeBlockRange(chunk));
debug('Requesting block range', chunk);
const blockRequestStart = Date.now();
const blocks = await this.ethClient
.requestBatch(
blockRangeToArray(chunk)
.filter(blockNumber => this.checkpoint.isIncomplete(blockNumber))
.map(blockNumber => getBlock(blockNumber))
)
.catch(e =>
Promise.reject(new Error(`Failed to request batch of blocks ${serializeBlockRange(chunk)}: ${e}`))
);
debug('Received %d blocks in %d ms', blocks.length, Date.now() - blockRequestStart);
for (const block of blocks) {
await this.processBlock(block);
}
info(
'Completed %d blocks of chunk %s in %d ms',
blocks.length,
serializeBlockRange(chunk),
Date.now() - startTime
);
}
async processBlock(block: RawBlockResponse) {
if (block.number != null && !this.checkpoint.isIncomplete(bigIntToNumber(block.number))) {
warn('Skipping processing of block %d since it is marked complete in our checkpoint');
return;
}
const startTime = Date.now();
const formattedBlock = formatBlock(block);
if (formattedBlock.number == null) {
debug('Ignoring block %s without number', block.hash);
return;
}
const blockTime = parseBlockTime(formattedBlock.timestamp);
if (!this.active) {
return;
}
const outputMessages = await this.abortHandle.race(
Promise.all(block.transactions.map(tx => this.processTransaction(tx, blockTime, formattedBlock)))
);
outputMessages.forEach(msgs => msgs.forEach(msg => this.output.write(msg)));
this.checkpoint.markBlockComplete(formattedBlock.number);
this.counters.blocksProcessed++;
this.aggregates.blockProcessTime.push(Date.now() - startTime);
}
public async shutdown() {
info('Shutting down balances watcher for %s', this.config.contractAddress);
this.active = false;
this.abortHandle.abort();
await new Promise<void>(resolve => {
this.endCallbacks.push(resolve);
});
}
public flushStats() {
const stats = {
...this.counters,
...this.aggregates.blockProcessTime.flush('blockProcessTime'),
...this.aggregates.txProcessTime.flush('txProcessTime'),
...this.aggregates.eventProcessTime.flush('eventProcessTime'),
abortHandles: this.abortHandle.size,
};
this.counters = { ...initialCounters };
return stats;
}
async processTransaction(
rawTx: RawTransactionResponse | string,
blockTime: number,
formattedBlock: FormattedBlock
): Promise<OutputMessage[]> {
if (!this.active) {
return [];
}
if (typeof rawTx === 'string') {
warn('Received raw transaction as string from block %d', formattedBlock.number);
return [];
}
const startTime = Date.now();
trace('Processing transaction %s from block %d', rawTx.hash, formattedBlock.number);
const receipt = await this.ethClient.request(getTransactionReceipt(rawTx.hash));
let outputMessages = Array<OutputMessage>();
if (receipt != null && receipt.logs != null) {
const isDefined = (addr: string | undefined): addr is string => {
return !!addr;
};
const addresses = receipt.logs
?.map(log => {
if (this.config.contractAddress == log.address) {
if (log.topics[0] == transferEventSignature && log.topics.length == 3) {
const from = '0x' + log.topics[1].substr(26);
const to = '0x' + log.topics[2].substr(26);
return [from, to];
}
}
})
.flat()
.filter(isDefined);
if (addresses.length > 0) {
this.counters.transfersProcessed++;
outputMessages = await this.abortHandle.race(
Promise.all(addresses.map(addr => this.getBalance(addr, formattedBlock, blockTime)))
);
}
}
this.aggregates.txProcessTime.push(Date.now() - startTime);
trace('Completed processing transaction %s in %d ms', rawTx.hash, Date.now() - startTime);
return outputMessages;
}
async getBalance(address: string, formattedBlock: FormattedBlock, blockTime: number): Promise<BalanceMessage> {
const response = await this.ethClient.request(
ethCall(
this.config.contractAddress,
'balanceOf(address)',
['0'.repeat(24) + address.substr(2)],
formattedBlock.number!
)
);
const balance = formatHexToFloatingPoint(response, this.config.decimals);
let ethereumBalance = undefined;
if (this.config.logEthBalance) {
const ethereumBalanceHex = await this.ethClient.request(ethBalance(address, formattedBlock.number!));
ethereumBalance = formatHexToFloatingPoint(ethereumBalanceHex, 18);
}
return {
body: {
contract: this.config.contractAddress,
blockHash: formattedBlock.hash!,
blockNumber: formattedBlock.number!,
account: address,
balance: balance,
ethBalance: ethereumBalance,
},
time: blockTime,
type: 'balance',
};
}
}