This repository has been archived by the owner on Mar 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
query.ts
388 lines (337 loc) · 11 KB
/
query.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
const newrelic = require("newrelic");
import { Hash } from "@ckb-lumos/base";
import {
Block,
Transaction,
Log,
DBBlock,
DBTransaction,
DBLog,
} from "./types";
import Knex, { knex, Knex as KnexType } from "knex";
import { envConfig } from "../base/env-config";
import { LATEST_MEDIAN_GAS_PRICE } from "./constant";
import {
formatDecimal,
toBigIntOpt,
formatBlock,
formatTransaction,
formatLog,
buildQueryLogAddress,
bufferToHex,
hexToBuffer,
getDatabaseRateLimitingConfiguration,
buildQueryLogTopics,
buildQueryLogBlock,
buildQueryLogId,
} from "./helpers";
import { LimitExceedError } from "../methods/error";
import { FilterParams } from "../base/filter";
import KnexTimeoutError = knex.KnexTimeoutError;
import { logger } from "../base/logger";
const poolMax = envConfig.pgPoolMax || 20;
const GLOBAL_KNEX = Knex({
client: "postgresql",
connection: {
connectionString: envConfig.databaseUrl,
keepAlive: true,
},
pool: { min: 2, max: +poolMax },
});
export class Query {
private knex: KnexType;
constructor() {
this.knex = GLOBAL_KNEX;
}
async isConnected() {
try {
await this.knex.raw("SELECT 1");
return true;
} catch (error: any) {
logger.error(error.message);
return false;
}
}
async getEthTxHashByGwTxHash(gwTxHash: Hash): Promise<Hash | undefined> {
const ethTxHash = await this.knex<DBTransaction>("transactions")
.select("eth_tx_hash")
.where({
hash: hexToBuffer(gwTxHash),
})
.first();
if (ethTxHash == null) {
return undefined;
}
return bufferToHex(ethTxHash.eth_tx_hash);
}
async getGwTxHashByEthTxHash(ethTxHash: Hash): Promise<Hash | undefined> {
const gwTxHash = await this.knex<DBTransaction>("transactions")
.select("hash")
.where({
eth_tx_hash: hexToBuffer(ethTxHash),
})
.first();
if (gwTxHash == null) {
return undefined;
}
return bufferToHex(gwTxHash.hash);
}
async getTipBlockNumber(): Promise<bigint | undefined> {
const blockData = await this.knex<DBBlock>("blocks")
.select("number")
.orderBy("number", "desc")
.first();
return toBigIntOpt(blockData?.number);
}
async getTipBlock(): Promise<Block | undefined> {
const block = await this.knex<DBBlock>("blocks")
.orderBy("number", "desc")
.first();
if (!block) {
return undefined;
}
return formatBlock(block);
}
async getBlockByHash(blockHash: Hash): Promise<Block | undefined> {
return await this.getBlock({
hash: hexToBuffer(blockHash),
});
}
async getBlockByNumber(blockNumber: bigint): Promise<Block | undefined> {
return await this.getBlock({
number: blockNumber.toString(),
});
}
private async getBlock(
params: Readonly<Partial<KnexType.MaybeRawRecord<DBBlock>>>
): Promise<Block | undefined> {
const block = await this.knex<DBBlock>("blocks").where(params).first();
if (!block) {
return undefined;
}
return formatBlock(block);
}
// exclude min & include max;
async getBlocksByNumbers(
minBlockNumber: bigint,
maxBlockNumber: bigint
): Promise<Block[]> {
if (minBlockNumber >= maxBlockNumber) {
return [];
}
const blocks = await this.knex<DBBlock>("blocks")
.where("number", ">", minBlockNumber.toString())
.andWhere("number", "<=", maxBlockNumber.toString())
.orderBy("number", "asc");
return blocks.map((block) => formatBlock(block));
}
async getBlockHashesAndNumbersAfterBlockNumber(
number: bigint,
order: "desc" | "asc" = "desc"
): Promise<{ hash: Hash; number: bigint }[]> {
const arrayOfHashAndNumber = await this.knex<{
hash: Buffer;
number: bigint;
}>("blocks")
.select("hash", "number")
.where("number", ">", number.toString())
.orderBy("number", order);
return arrayOfHashAndNumber.map((hn) => {
return { hash: bufferToHex(hn.hash), number: BigInt(hn.number) };
});
}
async getTransactionsByBlockHash(blockHash: Hash): Promise<Transaction[]> {
return await this.getTransactions({ block_hash: hexToBuffer(blockHash) });
}
async getTransactionsByBlockNumber(
blockNumber: bigint
): Promise<Transaction[]> {
return await this.getTransactions({ block_number: blockNumber.toString() });
}
private async getTransactions(
params: Readonly<Partial<KnexType.MaybeRawRecord<DBTransaction>>>
): Promise<Transaction[]> {
const transactions = await this.knex<DBTransaction>("transactions").where(
params
);
return transactions.map((tx) => formatTransaction(tx));
}
async getTransactionByHash(hash: Hash): Promise<Transaction | undefined> {
return await this.getTransaction({
hash: hexToBuffer(hash),
});
}
async getTransactionByEthTxHash(
eth_tx_hash: Hash
): Promise<Transaction | undefined> {
return await this.getTransaction({
eth_tx_hash: hexToBuffer(eth_tx_hash),
});
}
async getTransactionByBlockHashAndIndex(
blockHash: Hash,
index: number
): Promise<Transaction | undefined> {
return await this.getTransaction({
block_hash: hexToBuffer(blockHash),
transaction_index: index,
});
}
async getTransactionByBlockNumberAndIndex(
blockNumber: bigint,
index: number
): Promise<Transaction | undefined> {
return await this.getTransaction({
block_number: blockNumber.toString(),
transaction_index: index,
});
}
private async getTransaction(
params: Readonly<Partial<KnexType.MaybeRawRecord<DBTransaction>>>
): Promise<Transaction | undefined> {
const transaction = await this.knex<DBTransaction>("transactions")
.where(params)
.first();
if (transaction == null) {
return undefined;
}
return formatTransaction(transaction);
}
async getTransactionHashesByBlockHash(blockHash: Hash): Promise<Hash[]> {
return await this.getTransactionHashes({
block_hash: hexToBuffer(blockHash),
});
}
async getTransactionHashesByBlockNumber(
blockNumber: bigint
): Promise<Hash[]> {
return await this.getTransactionHashes({
block_number: blockNumber.toString(),
});
}
private async getTransactionHashes(
params: Readonly<Partial<KnexType.MaybeRawRecord<DBTransaction>>>
): Promise<Hash[]> {
const transactionHashes = await this.knex<DBTransaction>("transactions")
.select("hash")
.where(params);
return transactionHashes.map((tx) => bufferToHex(tx.hash));
}
async getTransactionEthHashesByBlockHash(blockHash: Hash): Promise<Hash[]> {
return await this.getTransactionEthHashes({
block_hash: hexToBuffer(blockHash),
});
}
async getTransactionEthHashesByBlockNumber(
blockNumber: bigint
): Promise<Hash[]> {
return await this.getTransactionEthHashes({
block_number: blockNumber.toString(),
});
}
private async getTransactionEthHashes(
params: Readonly<Partial<KnexType.MaybeRawRecord<DBTransaction>>>
): Promise<Hash[]> {
const transactionHashes = await this.knex<DBTransaction>("transactions")
.select("eth_tx_hash")
.where(params);
return transactionHashes.map((tx) => bufferToHex(tx.eth_tx_hash));
}
// undefined means not found
async getBlockTransactionCountByHash(blockHash: Hash): Promise<number> {
return await this.getBlockTransactionCount({
block_hash: hexToBuffer(blockHash),
});
}
async getBlockTransactionCountByNumber(blockNumber: bigint): Promise<number> {
return await this.getBlockTransactionCount({
block_number: blockNumber.toString(),
});
}
private async getBlockTransactionCount(
params: Readonly<Partial<KnexType.MaybeRawRecord<DBTransaction>>>
): Promise<number> {
const data = await this.knex<DBTransaction>("transactions")
.where(params)
.count();
const count: number = +data[0].count;
return count;
}
async getTransactionAndLogsByHash(
txHash: Hash
): Promise<[Transaction, Log[]] | undefined> {
const tx = await this.knex<DBTransaction>("transactions")
.where({ hash: hexToBuffer(txHash) })
.first();
if (!tx) {
return undefined;
}
const logs = await this.knex<DBLog>("logs").where({
transaction_hash: hexToBuffer(txHash),
});
return [formatTransaction(tx), logs.map((log) => formatLog(log))];
}
async getTipLog() {
let log = await this.knex<DBLog>("logs").orderBy("id", "desc").first();
if (log != null) {
return formatLog(log);
}
return null;
}
/**
* @throws LimitExceedError - the number of queried results are over `MAX_QUERY_NUMBER`.
*/
async getLogsByFilter(
{ addresses, topics, fromBlock, toBlock, blockHash }: FilterParams,
lastPollId: bigint = BigInt(-1)
): Promise<Log[]> {
const { MAX_QUERY_NUMBER, MAX_QUERY_TIME_MILSECS } =
getDatabaseRateLimitingConfiguration();
// NOTE: In this SQL, there is no `ORDER BY id` as combining `ORDER BY` and `LIMIT` consumes too much time when the
// results are large. Instead, logs are sorted outside the database:
// - When the number of query results exceeds $MAX_QUERY_NUMBER, an error is returned.
// - When the queried results are less than or equal to $MAX_QUERY_NUMBER, sorting takes only a short time
//
// NOTE: Using CTE to SELECT "logs" then JOIN "transactions" is more efficient than directly SELECT JOIN
let selectLogs = this.knex<DBLog>("logs")
.modify(buildQueryLogAddress, addresses)
.modify(buildQueryLogTopics, topics)
.modify(buildQueryLogBlock, fromBlock, toBlock, blockHash)
.modify(buildQueryLogId, lastPollId)
.limit(MAX_QUERY_NUMBER + 1);
let selectLogsJoinTransactions = this.knex<DBLog>("transactions")
.with("logs", selectLogs)
.select("logs.*", "transactions.eth_tx_hash")
.join("logs", { "logs.transaction_hash": "transactions.hash" });
let logs: DBLog[] = await selectLogsJoinTransactions
.timeout(MAX_QUERY_TIME_MILSECS, { cancel: true })
.catch((knexError: any) => {
if (knexError instanceof KnexTimeoutError) {
throw new LimitExceedError(`query timeout exceeded`);
}
throw knexError;
});
if (logs.length > MAX_QUERY_NUMBER) {
throw new LimitExceedError(
`query returned more than ${MAX_QUERY_NUMBER} results`
);
}
return logs
.map((log) => formatLog(log))
.sort((aLog, bLog) => Number(aLog.id - bLog.id));
}
// Latest ${LATEST_MEDIAN_GAS_PRICE} transactions median gas_price
async getMedianGasPrice(): Promise<bigint> {
const sql = `SELECT (PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY gas_price)) AS median FROM (SELECT gas_price FROM transactions ORDER BY id DESC LIMIT ?) AS gas_price;`;
const result = await newrelic.startSegment(
"getMedianGasPrice",
true,
async () => this.knex.raw(sql, [LATEST_MEDIAN_GAS_PRICE])
);
const median = result.rows[0]?.median;
if (median == null) {
return BigInt(0);
}
return formatDecimal(median.toString());
}
}