-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbtcindexer.helpers.test.ts
More file actions
365 lines (319 loc) · 10.5 KB
/
btcindexer.helpers.test.ts
File metadata and controls
365 lines (319 loc) · 10.5 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
import { Miniflare } from "miniflare";
import { Block, type Transaction } from "bitcoinjs-lib";
import { expect } from "bun:test";
import type { D1Database, KVNamespace, Service } from "@cloudflare/workers-types";
import type { WorkerEntrypoint } from "cloudflare:workers";
import { BtcNet, type BlockQueueRecord } from "@gonative-cc/lib/nbtc";
import { toSuiNet, type SuiNet } from "@gonative-cc/lib/nsui";
import { D1Storage } from "@gonative-cc/sui-indexer/storage";
import {
type SuiIndexerRpc,
RedeemRequestStatus,
type FinalizeRedeemTx,
} from "@gonative-cc/lib/rpc-types";
import { dropTables, initDb } from "@gonative-cc/lib/test-helpers/init_db";
import { Indexer } from "./btcindexer";
import { CFStorage } from "./cf-storage";
import type { SuiClientI } from "./sui_client";
import type { NbtcPkgCfg, NbtcDepositAddrsMap } from "./models";
import { MintTxStatus } from "./models";
import { mkElectrsServiceMock } from "./electrs.test";
import { MockSuiClient } from "./sui_client-mock";
import type { Electrs } from "./electrs";
export const SUI_FALLBACK_ADDRESS = "0xFALLBACK";
export const TEST_PACKAGE_CONFIG: NbtcPkgCfg = {
id: 1,
btc_network: BtcNet.REGTEST,
sui_network: "testnet",
nbtc_pkg: "0xPACKAGE",
nbtc_contract: "0xNBTC",
lc_contract: "0xLIGHTCLIENT",
lc_pkg: "0xLC_PKG",
nbtc_fallback_addr: SUI_FALLBACK_ADDRESS,
is_active: true,
};
export interface TxInfo {
id: string;
suiAddr: string;
amount: number;
}
export interface TestBlock {
depositAddr: string;
height: number;
hash: string;
rawBlockHex: string;
txs: Record<string, TxInfo>;
}
export type TestBlocks = Record<number, TestBlock>;
interface SetupOptions {
depositAddresses?: string[];
packageConfig?: NbtcPkgCfg;
confirmationDepth?: number;
maxRetries?: number;
customSuiClient?: MockSuiClient;
testData?: TestBlocks;
}
export interface TestIndexerHelper {
indexer: Indexer;
db: D1Database;
blocksKV: KVNamespace;
txsKV: KVNamespace;
storage: CFStorage;
mockSuiClient: MockSuiClient;
mockElectrs: Electrs;
cleanupDB(): Promise<D1ExecResult>;
setupBlock: (height: number) => Promise<void>;
getBlock: (height: number) => Block;
getTx: (
height: number,
txIndex: number,
) => {
blockData: TestBlock;
block: Block;
targetTx: Transaction;
txInfo: TxInfo;
};
createBlockQueueRecord: (
height: number,
options?: Partial<BlockQueueRecord>,
) => BlockQueueRecord;
mockElectrsSender: (address: string) => void;
mockElectrsError: (error: Error) => void;
mockSuiMintBatch: (result: [boolean, string] | null) => void;
insertTx: (options: {
txId: string;
status: MintTxStatus | string;
retryCount?: number;
blockHeight?: number;
blockHash?: string;
suiRecipient?: string;
amount?: number;
depositAddress?: string;
sender?: string;
vout?: number;
}) => Promise<void>;
expectMintingCount: (count: number) => Promise<void>;
expectSenderCount: (count: number, expectedAddress?: string) => Promise<void>;
expectTxStatus: (txId: string, expectedStatus: MintTxStatus | string) => Promise<void>;
}
// test suite helper functions constructor.
export async function setupTestIndexerSuite(
mf: Miniflare,
options: SetupOptions = {},
): Promise<TestIndexerHelper> {
const testData = options.testData || {};
const db = await mf.getD1Database("DB");
await initDb(db);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const env = (await mf.getBindings()) as any;
const storage = new CFStorage(env.DB, env.BtcBlocks, env.nbtc_txs);
const blocksKV = env.BtcBlocks as KVNamespace;
const txsKV = env.nbtc_txs as KVNamespace;
const packageConfig: NbtcPkgCfg = options.packageConfig || TEST_PACKAGE_CONFIG;
await db
.prepare(
`INSERT INTO setups (
id, btc_network, sui_network, nbtc_pkg, nbtc_contract,
lc_pkg, lc_contract,
nbtc_fallback_addr, is_active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.bind(
packageConfig.id,
packageConfig.btc_network,
packageConfig.sui_network,
packageConfig.nbtc_pkg,
packageConfig.nbtc_contract,
packageConfig.lc_pkg,
packageConfig.lc_contract,
packageConfig.nbtc_fallback_addr,
packageConfig.is_active,
)
.run();
const nbtcAddressesMap: NbtcDepositAddrsMap = new Map();
const depositAddresses = options.depositAddresses || [];
for (const addr of depositAddresses) {
await db
.prepare(
`INSERT INTO nbtc_deposit_addresses (setup_id, deposit_address, is_active)
VALUES (?, ?, 1)`,
)
.bind(packageConfig.id, addr)
.run();
nbtcAddressesMap.set(addr, {
setup_id: packageConfig.id,
is_active: true,
});
}
const suiClients = new Map<SuiNet, SuiClientI>();
const mockSuiClient = options.customSuiClient || new MockSuiClient();
suiClients.set(toSuiNet(packageConfig.sui_network), mockSuiClient);
const electrsClients = new Map<BtcNet, Electrs>();
const mockElectrs = mkElectrsServiceMock();
electrsClients.set(BtcNet.REGTEST, mockElectrs);
const indexerStorage = new D1Storage(db);
const mockSuiIndexerService = {
getBroadcastedRedeemTxIds: (network: string) =>
indexerStorage.getBroadcastedBtcRedeemTxIds(network),
confirmRedeem: (txIds: string[], blockHeight: number, blockHash: string) =>
indexerStorage.confirmRedeem(txIds, blockHeight, blockHash),
finalizeRedeems: async (requests: FinalizeRedeemTx[]) => {
await Promise.all(requests.map((r) => indexerStorage.setRedeemFinalized(r.redeemId)));
},
putRedeemTx: () => Promise.resolve(),
getConfirmingRedeems: (network: string) => indexerStorage.getConfirmingRedeems(network),
updateRedeemStatus: (redeemId: number, status: RedeemRequestStatus) =>
indexerStorage.updateRedeemStatus(redeemId, status),
updateRedeemStatuses: (redeemIds: number[], status: RedeemRequestStatus) =>
indexerStorage.updateRedeemStatuses(redeemIds, status),
} as unknown as Service<SuiIndexerRpc & WorkerEntrypoint>;
const indexer = new Indexer(
storage,
[packageConfig],
suiClients,
nbtcAddressesMap,
options.confirmationDepth || 8,
options.maxRetries || 2,
electrsClients,
mockSuiIndexerService,
);
//
// Interface functions
//
const cleanupDB = () => dropTables(db);
const setupBlock = async (height: number): Promise<void> => {
const blockData = testData[height];
if (!blockData) throw new Error(`Block ${height} not found in test data`);
await blocksKV.put(blockData.hash, Buffer.from(blockData.rawBlockHex, "hex").buffer);
};
const getBlock = (height: number): Block => {
const blockData = testData[height];
if (!blockData) throw new Error(`Block ${height} not found in test data`);
return Block.fromHex(blockData.rawBlockHex);
};
const getTx = (height: number, txIndex: number) => {
const blockData = testData[height];
if (!blockData) throw new Error(`Block ${height} not found in test data`);
const block = Block.fromHex(blockData.rawBlockHex);
const txInfo = blockData.txs[txIndex];
if (!txInfo) throw new Error(`Tx ${txIndex} not found in block ${height}`);
const targetTx = block.transactions?.find((tx) => tx.getId() === txInfo.id);
if (!targetTx) throw new Error(`Transaction ${txInfo.id} not found in block`);
return { blockData, block, targetTx, txInfo };
};
const createBlockQueueRecord = (
height: number,
options?: Partial<BlockQueueRecord>,
): BlockQueueRecord => {
const blockData = testData[height];
if (!blockData) throw new Error(`Block ${height} not found in test data`);
return {
hash: options?.hash || blockData.hash,
height: options?.height || blockData.height,
network: options?.network || BtcNet.REGTEST,
timestamp_ms: options?.timestamp_ms || Date.now(),
};
};
const mockElectrsSender = (address: string): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(mockElectrs.getTx as any).mockResolvedValue(
new Response(
JSON.stringify({
vout: [{ scriptpubkey_address: address }],
}),
),
);
};
const mockElectrsError = (error: Error): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(mockElectrs.getTx as any).mockRejectedValue(error);
};
const mockSuiMintBatch = (result: [boolean, string] | null): void => {
mockSuiClient.tryMintNbtcBatch.mockResolvedValue(result);
};
const insertTx = async (args: {
txId: string;
status: MintTxStatus | string;
retryCount?: number;
blockHeight?: number;
blockHash?: string;
suiRecipient?: string;
amount?: number;
depositAddress?: string;
sender?: string;
vout?: number;
}): Promise<void> => {
const defaultBlock = testData[329] || testData[327] || Object.values(testData)[0];
if (!defaultBlock) throw new Error("No test data available for default values");
const depositAddr = args.depositAddress || defaultBlock.depositAddr;
await db
.prepare(
`INSERT INTO nbtc_minting (tx_id, address_id, sender, vout, block_hash, block_height, sui_recipient, amount, status, created_at, updated_at, retry_count)
VALUES (
?,
(SELECT id FROM nbtc_deposit_addresses WHERE deposit_address = ?),
?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.bind(
args.txId,
depositAddr,
args.sender || "sender_address",
args.vout ?? 0,
args.blockHash || defaultBlock.hash,
args.blockHeight || defaultBlock.height,
args.suiRecipient || "0xtest_recipient",
args.amount || 10000,
args.status,
Date.now(),
Date.now(),
args.retryCount || 0,
)
.run();
};
const expectMintingCount = async (count: number): Promise<void> => {
const { results } = await db.prepare("SELECT * FROM nbtc_minting").all();
expect(results.length).toEqual(count);
};
const expectSenderCount = async (count: number, expectedAddress?: string): Promise<void> => {
const { results } = await db.prepare("SELECT * FROM nbtc_minting").all();
const recordsWithSender = results.filter((r) => r.sender && r.sender !== "");
expect(recordsWithSender.length).toEqual(count);
if (expectedAddress && recordsWithSender[0]) {
expect(recordsWithSender[0].sender).toEqual(expectedAddress);
}
};
const expectTxStatus = async (
txId: string,
expectedStatus: MintTxStatus | string,
): Promise<void> => {
const { results } = await db
.prepare("SELECT status FROM nbtc_minting WHERE tx_id = ?")
.bind(txId)
.all();
expect(results.length).toEqual(1);
expect(results[0]).toBeDefined();
expect(results[0]!.status).toEqual(expectedStatus);
};
return {
indexer,
db,
blocksKV,
txsKV,
storage,
mockSuiClient,
mockElectrs,
// functions
cleanupDB,
setupBlock,
getBlock,
getTx,
createBlockQueueRecord,
mockElectrsSender,
mockElectrsError,
mockSuiMintBatch,
insertTx,
expectMintingCount,
expectSenderCount,
expectTxStatus,
};
}