Skip to content

Commit 3a02f57

Browse files
authored
fix: optimize mempool transaction reads and writes (#1781)
* fix: change mempool_digest into a table * fix: change digest to be last updated timestamp * fix: build * fix: update count on reconcile * test: mempool renconcile
1 parent e8cccdd commit 3a02f57

File tree

7 files changed

+191
-174
lines changed

7 files changed

+191
-174
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/* eslint-disable camelcase */
2+
3+
exports.shorthands = undefined;
4+
5+
exports.up = pgm => {
6+
pgm.addColumn('chain_tip', {
7+
mempool_tx_count: {
8+
type: 'int',
9+
default: 0,
10+
},
11+
mempool_updated_at: {
12+
type: 'timestamptz',
13+
default: pgm.func('(NOW())'),
14+
},
15+
});
16+
pgm.sql(`
17+
UPDATE chain_tip SET
18+
mempool_tx_count = (SELECT COUNT(*)::int FROM mempool_txs WHERE pruned = FALSE),
19+
mempool_updated_at = NOW()
20+
`);
21+
pgm.alterColumn('chain_tip', 'mempool_tx_count', { notNull: true });
22+
pgm.alterColumn('chain_tip', 'mempool_updated_at', { notNull: true });
23+
};
24+
25+
exports.down = pgm => {
26+
pgm.dropColumn('chain_tip', ['mempool_tx_count', 'mempool_updated_at']);
27+
};

src/datastore/pg-store.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1474,12 +1474,13 @@ export class PgStore extends BasePgStore {
14741474
const unanchoredTxs: string[] = !includeUnanchored
14751475
? (await this.getUnanchoredTxsInternal(sql)).txs.map(tx => tx.tx_id)
14761476
: [];
1477+
// If caller is not filtering by any param, get the tx count from the `chain_tip` table.
1478+
const count =
1479+
senderAddress || recipientAddress || address
1480+
? sql`(COUNT(*) OVER())::int AS count`
1481+
: sql`(SELECT mempool_tx_count FROM chain_tip) AS count`;
14771482
const resultQuery = await sql<(MempoolTxQueryResult & { count: number })[]>`
1478-
SELECT ${unsafeCols(sql, [
1479-
...MEMPOOL_TX_COLUMNS,
1480-
abiColumn('mempool_txs'),
1481-
'(COUNT(*) OVER())::INTEGER AS count',
1482-
])}
1483+
SELECT ${unsafeCols(sql, [...MEMPOOL_TX_COLUMNS, abiColumn('mempool_txs')])}, ${count}
14831484
FROM mempool_txs
14841485
WHERE ${
14851486
address
@@ -1523,7 +1524,9 @@ export class PgStore extends BasePgStore {
15231524
* @returns `FoundOrNot` object with a possible `digest` string.
15241525
*/
15251526
async getMempoolTxDigest(): Promise<FoundOrNot<{ digest: string }>> {
1526-
const result = await this.sql<{ digest: string }[]>`SELECT digest FROM mempool_digest`;
1527+
const result = await this.sql<{ digest: string }[]>`
1528+
SELECT date_part('epoch', mempool_updated_at)::text AS digest FROM chain_tip
1529+
`;
15271530
if (result.length === 0) {
15281531
return { found: false } as const;
15291532
}

0 commit comments

Comments
 (0)