|
| 1 | +import Sqlite from "better-sqlite3"; |
| 2 | +import { BlockCache, Block } from "../blockCache.js"; |
| 3 | + |
| 4 | +const defaultTableName = "blocks"; |
| 5 | + |
| 6 | +export type Options = |
| 7 | + | { |
| 8 | + dbPath: string; |
| 9 | + tableName?: string; |
| 10 | + } |
| 11 | + | { db: Sqlite.Database; tableName?: string }; |
| 12 | + |
| 13 | +interface Row { |
| 14 | + chainId: number; |
| 15 | + blockNumber: string; |
| 16 | + timestamp: number; |
| 17 | +} |
| 18 | + |
| 19 | +type UninitializedState = { state: "uninitialized" }; |
| 20 | +type InitializedState = { |
| 21 | + state: "initialized"; |
| 22 | + db: Sqlite.Database; |
| 23 | + getTimestampByBlockNumberStmt: Sqlite.Statement; |
| 24 | + getBlockNumberByTimestampStmt: Sqlite.Statement; |
| 25 | + saveBlockStmt: Sqlite.Statement; |
| 26 | + getBeforeStmt: Sqlite.Statement; |
| 27 | + getAfterStmt: Sqlite.Statement; |
| 28 | +}; |
| 29 | +type State = UninitializedState | InitializedState; |
| 30 | + |
| 31 | +export function createSqliteBlockCache(opts: Options): BlockCache { |
| 32 | + let dbState: State = { state: "uninitialized" }; |
| 33 | + |
| 34 | + if (opts.tableName !== undefined && /[^a-zA-Z0-9_]/.test(opts.tableName)) { |
| 35 | + throw new Error(`Table name ${opts.tableName} has invalid characters.`); |
| 36 | + } |
| 37 | + |
| 38 | + const tableName = opts.tableName ?? defaultTableName; |
| 39 | + |
| 40 | + return { |
| 41 | + async init(): Promise<void> { |
| 42 | + if (dbState.state === "initialized") { |
| 43 | + throw new Error("Already initialized"); |
| 44 | + } |
| 45 | + |
| 46 | + const db = "db" in opts ? opts.db : new Sqlite(opts.dbPath); |
| 47 | + |
| 48 | + db.exec("PRAGMA journal_mode = WAL;"); |
| 49 | + |
| 50 | + // TODO: Add proper migrations, with Kysely? |
| 51 | + db.exec( |
| 52 | + `CREATE TABLE IF NOT EXISTS ${tableName} ( |
| 53 | + chainId INTEGER, |
| 54 | + blockNumber TEXT, |
| 55 | + timestamp INTEGER, |
| 56 | + PRIMARY KEY (chainId, blockNumber) |
| 57 | + )` |
| 58 | + ); |
| 59 | + |
| 60 | + db.exec( |
| 61 | + `CREATE INDEX IF NOT EXISTS idx_chainId_timestamp_blockNumber |
| 62 | + ON ${tableName} (chainId, timestamp, blockNumber DESC);` |
| 63 | + ); |
| 64 | + |
| 65 | + dbState = { |
| 66 | + state: "initialized", |
| 67 | + db, |
| 68 | + getTimestampByBlockNumberStmt: db.prepare( |
| 69 | + `SELECT * FROM ${tableName} WHERE chainId = ? AND blockNumber = ?` |
| 70 | + ), |
| 71 | + getBlockNumberByTimestampStmt: db.prepare( |
| 72 | + `SELECT * FROM ${tableName} WHERE chainId = ? AND timestamp = ?` |
| 73 | + ), |
| 74 | + saveBlockStmt: db.prepare( |
| 75 | + `INSERT OR REPLACE INTO ${tableName} (chainId, blockNumber, timestamp) VALUES (?, ?, ?)` |
| 76 | + ), |
| 77 | + getBeforeStmt: db.prepare( |
| 78 | + `SELECT * FROM ${tableName} WHERE chainId = ? AND timestamp < ? ORDER BY timestamp DESC, blockNumber DESC LIMIT 1` |
| 79 | + ), |
| 80 | + getAfterStmt: db.prepare( |
| 81 | + `SELECT * FROM ${tableName} WHERE chainId = ? AND timestamp >= ? ORDER BY timestamp ASC, blockNumber ASC LIMIT 1` |
| 82 | + ), |
| 83 | + }; |
| 84 | + |
| 85 | + return Promise.resolve(); |
| 86 | + }, |
| 87 | + |
| 88 | + async getTimestampByBlockNumber( |
| 89 | + chainId, |
| 90 | + blockNumber |
| 91 | + ): Promise<number | null> { |
| 92 | + if (dbState.state === "uninitialized") { |
| 93 | + throw new Error("SQLite database not initialized"); |
| 94 | + } |
| 95 | + |
| 96 | + const row = dbState.getTimestampByBlockNumberStmt.get( |
| 97 | + chainId, |
| 98 | + blockNumber.toString() |
| 99 | + ) as Row | undefined; |
| 100 | + |
| 101 | + return Promise.resolve(row ? row.timestamp : null); |
| 102 | + }, |
| 103 | + |
| 104 | + async getBlockNumberByTimestamp( |
| 105 | + chainId, |
| 106 | + timestamp |
| 107 | + ): Promise<bigint | null> { |
| 108 | + if (dbState.state === "uninitialized") { |
| 109 | + throw new Error("SQLite database not initialized"); |
| 110 | + } |
| 111 | + |
| 112 | + const row = dbState.getBlockNumberByTimestampStmt.get( |
| 113 | + chainId, |
| 114 | + timestamp |
| 115 | + ) as Row | undefined; |
| 116 | + |
| 117 | + return Promise.resolve(row ? BigInt(row.blockNumber) : null); |
| 118 | + }, |
| 119 | + |
| 120 | + async saveBlock(block: Block): Promise<void> { |
| 121 | + if (dbState.state === "uninitialized") { |
| 122 | + throw new Error("SQLite database not initialized"); |
| 123 | + } |
| 124 | + |
| 125 | + dbState.saveBlockStmt.run( |
| 126 | + block.chainId, |
| 127 | + block.blockNumber.toString(), |
| 128 | + block.timestampInSecs |
| 129 | + ); |
| 130 | + |
| 131 | + return Promise.resolve(); |
| 132 | + }, |
| 133 | + |
| 134 | + async getClosestBoundsForTimestamp( |
| 135 | + chainId, |
| 136 | + timestamp |
| 137 | + ): Promise<{ before: Block | null; after: Block | null }> { |
| 138 | + if (dbState.state === "uninitialized") { |
| 139 | + throw new Error("SQLite database not initialized"); |
| 140 | + } |
| 141 | + |
| 142 | + const before = dbState.getBeforeStmt.get(chainId, timestamp) as |
| 143 | + | Row |
| 144 | + | undefined; |
| 145 | + |
| 146 | + const after = dbState.getAfterStmt.get(chainId, timestamp) as |
| 147 | + | Row |
| 148 | + | undefined; |
| 149 | + |
| 150 | + return Promise.resolve({ |
| 151 | + before: before |
| 152 | + ? { |
| 153 | + chainId: before.chainId, |
| 154 | + timestampInSecs: before.timestamp, |
| 155 | + blockNumber: BigInt(before.blockNumber), |
| 156 | + } |
| 157 | + : null, |
| 158 | + after: after |
| 159 | + ? { |
| 160 | + chainId: after.chainId, |
| 161 | + timestampInSecs: after.timestamp, |
| 162 | + blockNumber: BigInt(after.blockNumber), |
| 163 | + } |
| 164 | + : null, |
| 165 | + }); |
| 166 | + }, |
| 167 | + }; |
| 168 | +} |
0 commit comments