@rosen-bridge/abstract-extractor 0.3.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/ergo/AbstractErgoExtractor.d.ts +30 -5
  3. package/dist/ergo/AbstractErgoExtractor.d.ts.map +1 -1
  4. package/dist/ergo/AbstractErgoExtractor.js +72 -7
  5. package/dist/ergo/AbstractErgoExtractorAction.d.ts +37 -10
  6. package/dist/ergo/AbstractErgoExtractorAction.d.ts.map +1 -1
  7. package/dist/ergo/AbstractErgoExtractorAction.js +134 -1
  8. package/dist/ergo/AbstractErgoExtractorEntity.d.ts +11 -0
  9. package/dist/ergo/AbstractErgoExtractorEntity.d.ts.map +1 -0
  10. package/dist/ergo/AbstractErgoExtractorEntity.js +57 -0
  11. package/dist/ergo/index.d.ts +1 -0
  12. package/dist/ergo/index.d.ts.map +1 -1
  13. package/dist/ergo/index.js +2 -1
  14. package/dist/ergo/initializable/AbstractInitializable.d.ts +4 -3
  15. package/dist/ergo/initializable/AbstractInitializable.d.ts.map +1 -1
  16. package/dist/ergo/initializable/AbstractInitializable.js +9 -5
  17. package/dist/ergo/initializable/AbstractInitializableAction.d.ts +7 -2
  18. package/dist/ergo/initializable/AbstractInitializableAction.d.ts.map +1 -1
  19. package/dist/ergo/initializable/AbstractInitializableAction.js +11 -1
  20. package/dist/ergo/interfaces.d.ts +20 -1
  21. package/dist/ergo/interfaces.d.ts.map +1 -1
  22. package/dist/ergo/interfaces.js +8 -1
  23. package/lib/ergo/AbstractErgoExtractor.ts +105 -12
  24. package/lib/ergo/AbstractErgoExtractorAction.ts +185 -18
  25. package/lib/ergo/AbstractErgoExtractorEntity.ts +28 -0
  26. package/lib/ergo/index.ts +1 -0
  27. package/lib/ergo/initializable/AbstractInitializable.ts +22 -9
  28. package/lib/ergo/initializable/AbstractInitializableAction.ts +19 -3
  29. package/lib/ergo/interfaces.ts +24 -1
  30. package/package.json +6 -2
  31. package/tests/{AbstractExtractor.mock.ts → AbstractErgoExtractor.mock.ts} +11 -4
  32. package/tests/AbstractErgoExtractor.spec.ts +281 -0
  33. package/tests/AbstractErgoExtractorAction.mock.ts +45 -0
  34. package/tests/AbstractErgoExtractorAction.spec.ts +269 -0
  35. package/tests/initializable/AbstractInitializable.mock.ts +14 -3
  36. package/tests/initializable/AbstractInitializable.spec.ts +37 -5
  37. package/tests/initializable/AbstractInitializableAction.mock.ts +45 -0
  38. package/tests/initializable/AbstractInitializableAction.spec.ts +65 -0
  39. package/tests/testData.ts +38 -0
  40. package/tests/testUtils.ts +22 -0
  41. package/tsconfig.build.tsbuildinfo +1 -1
  42. package/dist/ergo/initializable/InitializableByAddress.d.ts +0 -19
  43. package/dist/ergo/initializable/InitializableByAddress.d.ts.map +0 -1
  44. package/dist/ergo/initializable/InitializableByAddress.js +0 -30
  45. package/dist/ergo/initializable/InitializableByToken.d.ts +0 -19
  46. package/dist/ergo/initializable/InitializableByToken.d.ts.map +0 -1
  47. package/dist/ergo/initializable/InitializableByToken.js +0 -30
  48. package/dist/tsconfig.tsbuildinfo +0 -1
  49. package/tests/AbstractExtractor.spec.ts +0 -102
@@ -0,0 +1,28 @@
1
+ import { Column, PrimaryGeneratedColumn, Unique } from 'typeorm';
2
+
3
+ @Unique(['boxId', 'extractor'])
4
+ export abstract class AbstractErgoExtractorEntity {
5
+ @PrimaryGeneratedColumn()
6
+ id: number;
7
+
8
+ @Column({ type: 'varchar' })
9
+ boxId: string;
10
+
11
+ @Column({ type: 'varchar' })
12
+ block: string;
13
+
14
+ @Column({ type: 'int' })
15
+ height: number;
16
+
17
+ @Column({ nullable: true, type: 'varchar' })
18
+ spendBlock?: string | null;
19
+
20
+ @Column({ nullable: true, type: 'int' })
21
+ spendHeight?: number | null;
22
+
23
+ @Column({ type: 'varchar' })
24
+ extractor: string;
25
+
26
+ @Column({ type: 'varchar' })
27
+ serialized: string;
28
+ }
package/lib/ergo/index.ts CHANGED
@@ -6,3 +6,4 @@ export * from './network/NodeNetwork';
6
6
  export * from './network/AbstractNetwork';
7
7
  export * from './initializable';
8
8
  export * from './utils';
9
+ export * from './AbstractErgoExtractorEntity';
@@ -1,6 +1,8 @@
1
1
  import { AbstractLogger } from '@rosen-bridge/abstract-logger';
2
+ import { groupBy, sortBy } from 'lodash-es';
3
+
2
4
  import {
3
- ErgoExtractedData,
5
+ AbstractBoxData,
4
6
  ErgoNetworkType,
5
7
  ExtendedTransaction,
6
8
  } from '../interfaces';
@@ -10,14 +12,18 @@ import { AbstractInitializableErgoExtractorAction } from './AbstractInitializabl
10
12
  import { BlockInfo } from '../../interfaces';
11
13
  import { ExplorerNetwork } from '../network/ExplorerNetwork';
12
14
  import { NodeNetwork } from '../network/NodeNetwork';
13
- import { groupBy, sortBy } from 'lodash-es';
15
+ import { AbstractErgoExtractorEntity } from '../AbstractErgoExtractorEntity';
14
16
 
15
17
  export abstract class AbstractInitializableErgoExtractor<
16
- ExtractedData extends ErgoExtractedData
17
- > extends AbstractErgoExtractor<ExtractedData> {
18
+ ExtractedData extends AbstractBoxData,
19
+ ExtractorEntity extends AbstractErgoExtractorEntity
20
+ > extends AbstractErgoExtractor<ExtractedData, ExtractorEntity> {
18
21
  protected initialize: boolean;
19
22
  private address: string;
20
- protected abstract actions: AbstractInitializableErgoExtractorAction<ExtractedData>;
23
+ protected abstract actions: AbstractInitializableErgoExtractorAction<
24
+ ExtractedData,
25
+ ExtractorEntity
26
+ >;
21
27
 
22
28
  private network: ExplorerNetwork | NodeNetwork;
23
29
 
@@ -112,14 +118,15 @@ export abstract class AbstractInitializableErgoExtractor<
112
118
  */
113
119
  private initializeWithNode = async (initialBlock: BlockInfo) => {
114
120
  const txCountBeforeInit = await this.getTotalTxCount();
121
+ let offset = 0,
122
+ total = 1,
123
+ round = 1;
115
124
  await this.initWithRetrial(async () => {
116
125
  // Repeat the whole process twice to cover all spent boxes
117
126
  // After round 1 all boxes have been saved and processed once
118
127
  // After round 2 spending information of all stored boxes are updated successfully
119
- for (let round = 0; round <= 1; round++) {
128
+ while (round <= 2) {
120
129
  this.logger.debug(`Starting round ${round} of initialization`);
121
- let offset = 0,
122
- total = 1;
123
130
  while (offset < total) {
124
131
  const response = await (
125
132
  this.network as NodeNetwork
@@ -138,6 +145,8 @@ export abstract class AbstractInitializableErgoExtractor<
138
145
  if (txs.length > 0) await this.processTransactionBatch(txs);
139
146
  offset += API_LIMIT;
140
147
  }
148
+ round++;
149
+ offset = 0; // next round initial offset
141
150
  }
142
151
  });
143
152
  const txCountAfterInit = await this.getTotalTxCount();
@@ -167,7 +176,11 @@ export abstract class AbstractInitializableErgoExtractor<
167
176
  this.logger.debug(
168
177
  `Processing transactions at height ${blockTxs[0].inclusionHeight}`
169
178
  );
170
- await this.processTransactions(blockTxs, block);
179
+ const success = await this.processTransactions(blockTxs, block);
180
+ if (!success)
181
+ throw Error(
182
+ `Processing transactions failed at height ${blockTxs[0].inclusionHeight}`
183
+ );
171
184
  }
172
185
  };
173
186
 
@@ -1,11 +1,27 @@
1
+ import { DataSource, EntityTarget } from 'typeorm';
2
+ import { AbstractLogger } from '@rosen-bridge/abstract-logger';
3
+
1
4
  import { AbstractErgoExtractorAction } from '../AbstractErgoExtractorAction';
5
+ import { AbstractBoxData } from '../interfaces';
6
+ import { AbstractErgoExtractorEntity } from '../AbstractErgoExtractorEntity';
2
7
 
3
8
  export abstract class AbstractInitializableErgoExtractorAction<
4
- ExtractedData
5
- > extends AbstractErgoExtractorAction<ExtractedData> {
9
+ ExtractedData extends AbstractBoxData,
10
+ ExtractorEntity extends AbstractErgoExtractorEntity
11
+ > extends AbstractErgoExtractorAction<ExtractedData, ExtractorEntity> {
12
+ constructor(
13
+ dataSource: DataSource,
14
+ repo: EntityTarget<ExtractorEntity>,
15
+ logger?: AbstractLogger
16
+ ) {
17
+ super(dataSource, repo, logger);
18
+ }
19
+
6
20
  /**
7
21
  * remove all existing data for the extractor
8
22
  * @param extractorId
9
23
  */
10
- abstract removeAllData: (extractorId: string) => Promise<void>;
24
+ removeAllData = async (extractorId: string) => {
25
+ await this.repository.delete({ extractor: extractorId } as any);
26
+ };
11
27
  }
@@ -65,6 +65,29 @@ export interface SpendInfo {
65
65
  extras?: string[];
66
66
  }
67
67
 
68
- export interface ErgoExtractedData {
68
+ export interface AbstractBoxData {
69
69
  boxId: string;
70
+ serialized: string;
70
71
  }
72
+
73
+ export enum CallbackType {
74
+ Insert = 'insert',
75
+ Update = 'update',
76
+ Spend = 'spend',
77
+ Delete = 'delete',
78
+ }
79
+
80
+ export interface BoxInfo {
81
+ boxId: string;
82
+ }
83
+
84
+ export type CallbackDataMap<ExtractedData extends AbstractBoxData> = {
85
+ [CallbackType.Update]: BoxInfo[];
86
+ [CallbackType.Insert]: ExtractedData[];
87
+ [CallbackType.Delete]: ExtractedData[];
88
+ [CallbackType.Spend]: BoxInfo[];
89
+ };
90
+
91
+ export type CallbackMap<ExtractedData extends AbstractBoxData> = {
92
+ [K in CallbackType]: (data: CallbackDataMap<ExtractedData>[K]) => void;
93
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosen-bridge/abstract-extractor",
3
- "version": "0.3.1",
3
+ "version": "1.0.0",
4
4
  "description": "Rosen Bridge extractor interfaces to work with scanner",
5
5
  "repository": "",
6
6
  "license": "GPL-3.0",
@@ -20,9 +20,11 @@
20
20
  "devDependencies": {
21
21
  "@types/lodash-es": "^4.17.12",
22
22
  "@types/node": "^20.11.9",
23
+ "@types/uuid": "^10.0.0",
23
24
  "@typescript-eslint/eslint-plugin": "^6.19.1",
24
25
  "@typescript-eslint/parser": "^6.19.1",
25
26
  "@vitest/coverage-istanbul": "^1.2.2",
27
+ "await-semaphore": "^0.1.3",
26
28
  "eslint": "^8.56.0",
27
29
  "eslint-config-prettier": "^9.1.0",
28
30
  "extensionless": "^1.9.6",
@@ -38,6 +40,8 @@
38
40
  "@rosen-bridge/json-bigint": "^0.1.0",
39
41
  "@rosen-clients/ergo-explorer": "^1.1.2",
40
42
  "@rosen-clients/ergo-node": "^1.1.1",
41
- "lodash-es": "^4.17.21"
43
+ "lodash-es": "^4.17.21",
44
+ "typeorm": "^0.3.20",
45
+ "uuid": "^9.0.0"
42
46
  }
43
47
  }
@@ -3,12 +3,19 @@ import {
3
3
  AbstractErgoExtractor,
4
4
  BlockInfo,
5
5
  OutputBox,
6
- ErgoExtractedData,
6
+ AbstractBoxData,
7
7
  AbstractErgoExtractorAction,
8
+ AbstractErgoExtractorEntity,
8
9
  } from '../lib';
9
10
 
10
- export class MockedErgoExtractor extends AbstractErgoExtractor<ErgoExtractedData> {
11
- actions: AbstractErgoExtractorAction<ErgoExtractedData>;
11
+ export class MockedErgoExtractor extends AbstractErgoExtractor<
12
+ AbstractBoxData,
13
+ AbstractErgoExtractorEntity
14
+ > {
15
+ actions: AbstractErgoExtractorAction<
16
+ AbstractBoxData,
17
+ AbstractErgoExtractorEntity
18
+ >;
12
19
 
13
20
  getId = () => 'Test';
14
21
 
@@ -18,7 +25,7 @@ export class MockedErgoExtractor extends AbstractErgoExtractor<ErgoExtractedData
18
25
 
19
26
  extractBoxData = (
20
27
  box: V1.OutputInfo | OutputBox
21
- ): ErgoExtractedData | undefined => {
28
+ ): AbstractBoxData | undefined => {
22
29
  return undefined;
23
30
  };
24
31
  }
@@ -0,0 +1,281 @@
1
+ import { V1 } from '@rosen-clients/ergo-explorer';
2
+ import { describe, it, expect, vitest } from 'vitest';
3
+
4
+ import {
5
+ OutputBox,
6
+ AbstractBoxData,
7
+ AbstractErgoExtractorAction,
8
+ CallbackType,
9
+ AbstractErgoExtractorEntity,
10
+ } from '../lib';
11
+ import { block, extractedData, tx } from './testData';
12
+ import { MockedErgoExtractor } from './AbstractErgoExtractor.mock';
13
+
14
+ describe('AbstractErgoExtractor', () => {
15
+ describe('processTransactions', () => {
16
+ /**
17
+ * @target processTransactions should initialize extractor with specified id and insert status into db
18
+ * @dependencies
19
+ * @scenario
20
+ * - mock extractor
21
+ * - mock `hasData` to return true for one box
22
+ * - spy `extractBoxData` and `storeBoxes`
23
+ * - run test (call `processTransactions`)
24
+ * @expected
25
+ * - to call `extractBoxData` for the specific box
26
+ * - to insert the extracted box to database
27
+ * - to return true when total procedure is successful
28
+ * - to trigger `INSERT` callbacks with correct data
29
+ */
30
+ it('should process boxes with data and insert data into database', async () => {
31
+ const extractor = new MockedErgoExtractor();
32
+ const triggerCallbacks = vitest.fn();
33
+ extractor['triggerCallbacks'] = triggerCallbacks;
34
+ extractor.hasData = (box: V1.OutputInfo | OutputBox) => {
35
+ if (box.boxId == tx.outputs[0].boxId) return true;
36
+ return false;
37
+ };
38
+ const extractSpy = vitest.fn().mockReturnValue(extractedData);
39
+ extractor.extractBoxData = extractSpy;
40
+ const storeSpy = vitest.fn().mockResolvedValue(true);
41
+ const spendSpy = vitest.fn().mockResolvedValue([]);
42
+ extractor['actions'] = {
43
+ storeBoxes: storeSpy,
44
+ spendBoxes: spendSpy,
45
+ } as unknown as AbstractErgoExtractorAction<
46
+ AbstractBoxData,
47
+ AbstractErgoExtractorEntity
48
+ >;
49
+ const result = await extractor.processTransactions([tx], block);
50
+
51
+ expect(extractSpy).toBeCalledTimes(1);
52
+ expect(extractSpy).toBeCalledWith(tx.outputs[0]);
53
+ expect(storeSpy).toBeCalledWith([extractedData], block, 'Test');
54
+ expect(result).toEqual(true);
55
+ expect(triggerCallbacks).toBeCalledWith(CallbackType.Insert, [
56
+ extractedData,
57
+ ]);
58
+ });
59
+
60
+ /**
61
+ * @target processTransactions should extract spending information of all input boxes
62
+ * @dependencies
63
+ * @scenario
64
+ * - mock extractor (hasData returns false as default)
65
+ * - spy `extractBoxData`, `storeBoxes` and `spendBoxes`
66
+ * - run test (call `processTransactions`)
67
+ * @expected
68
+ * - not to call `extractBoxData` and `storeBoxes` when there is not any box with data
69
+ * - to extractor spend info of input boxes and call `spendBoxes`
70
+ * - to return true when total procedure is successful
71
+ * - to trigger `SPEND` callbacks with correct data
72
+ */
73
+ it('should extract spending information of all input boxes', async () => {
74
+ const extractor = new MockedErgoExtractor();
75
+ const triggerCallbacks = vitest.fn();
76
+ extractor['triggerCallbacks'] = triggerCallbacks;
77
+ const extractSpy = vitest.fn();
78
+ extractor.extractBoxData = extractSpy;
79
+ const storeSpy = vitest.fn().mockResolvedValue(true);
80
+ const spendSpy = vitest
81
+ .fn()
82
+ .mockResolvedValue([
83
+ { boxId: tx.inputs[0].boxId },
84
+ { boxId: tx.inputs[1].boxId },
85
+ ]);
86
+ extractor['actions'] = {
87
+ storeBoxes: storeSpy,
88
+ spendBoxes: spendSpy,
89
+ } as unknown as AbstractErgoExtractorAction<
90
+ AbstractBoxData,
91
+ AbstractErgoExtractorEntity
92
+ >;
93
+ const result = await extractor.processTransactions([tx], block);
94
+
95
+ expect(extractSpy).not.toBeCalled();
96
+ expect(storeSpy).not.toBeCalled();
97
+ expect(spendSpy).toBeCalledWith(
98
+ [
99
+ { boxId: tx.inputs[0].boxId, txId: tx.id, index: 1 },
100
+ { boxId: tx.inputs[1].boxId, txId: tx.id, index: 2 },
101
+ ],
102
+ block,
103
+ 'Test'
104
+ );
105
+ expect(result).toEqual(true);
106
+ expect(triggerCallbacks).toBeCalledWith(CallbackType.Spend, [
107
+ { boxId: tx.inputs[0].boxId },
108
+ { boxId: tx.inputs[1].boxId },
109
+ ]);
110
+ });
111
+
112
+ /**
113
+ * @target processTransactions should return false if data insertion fails
114
+ * @dependencies
115
+ * @scenario
116
+ * - mock extractor
117
+ * - mock `hasData` to return true for one box
118
+ * - spy `extractBoxData` and `storeBoxes`
119
+ * - run test (call `processTransactions`)
120
+ * @expected
121
+ * - to return false when `insertBoxes` returns false
122
+ * - not to call `spendBoxes` if data insertion fails
123
+ */
124
+ it('should return false if data insertion fails', async () => {
125
+ const extractor = new MockedErgoExtractor();
126
+ extractor.hasData = (box: V1.OutputInfo | OutputBox) => {
127
+ if (box.boxId == tx.outputs[0].boxId) return true;
128
+ return false;
129
+ };
130
+ const extractSpy = vitest.fn().mockReturnValue(extractedData);
131
+ extractor.extractBoxData = extractSpy;
132
+ const storeSpy = vitest.fn().mockResolvedValue(false);
133
+ const spendSpy = vitest.fn();
134
+ extractor['actions'] = {
135
+ storeBoxes: storeSpy,
136
+ spendBoxes: spendSpy,
137
+ } as unknown as AbstractErgoExtractorAction<
138
+ AbstractBoxData,
139
+ AbstractErgoExtractorEntity
140
+ >;
141
+ const result = await extractor.processTransactions([tx], block);
142
+
143
+ expect(result).toEqual(false);
144
+ expect(spendSpy).not.toBeCalled();
145
+ });
146
+ });
147
+
148
+ describe('forkBlock', () => {
149
+ /**
150
+ * @target forkBlock should remove all data extracted from the specified block
151
+ * @dependencies
152
+ * @scenario
153
+ * - mock extractor
154
+ * - spy `deleteBlockBoxes`
155
+ * - run test (call `forkBlock`)
156
+ * @expected
157
+ * - to call `deleteBlockBoxes` for the specific box
158
+ * - to trigger `DELETE` callbacks for the deleted box
159
+ * - to trigger `UPDATE` callbacks for the spent box
160
+ */
161
+ it('should remove all data extracted from the specified block', async () => {
162
+ const extractor = new MockedErgoExtractor();
163
+ const removeSpy = vitest.fn().mockResolvedValue({
164
+ deletedData: [{ boxId: 'box1' }],
165
+ updatedData: [{ boxId: 'box2' }],
166
+ });
167
+ extractor['actions'] = {
168
+ deleteBlockBoxes: removeSpy,
169
+ } as unknown as AbstractErgoExtractorAction<
170
+ AbstractBoxData,
171
+ AbstractErgoExtractorEntity
172
+ >;
173
+ const triggerCallbackSpy = vitest.fn().mockClear();
174
+ extractor['triggerCallbacks'] = triggerCallbackSpy;
175
+ await extractor.forkBlock(block.hash);
176
+ expect(removeSpy).toBeCalledWith(block.hash, 'Test');
177
+ expect(triggerCallbackSpy).toBeCalledWith(CallbackType.Delete, [
178
+ { boxId: 'box1' },
179
+ ]);
180
+ expect(triggerCallbackSpy).toBeCalledWith(CallbackType.Update, [
181
+ { boxId: 'box2' },
182
+ ]);
183
+ });
184
+ });
185
+
186
+ describe('hook', () => {
187
+ /**
188
+ * @target hook should hook a new callback on insert with the new id
189
+ * @dependencies
190
+ * @scenario
191
+ * - mock extractor
192
+ * - mock a callback for insert
193
+ * - run test (call `hook`)
194
+ * @expected
195
+ * - hook the callback with the specified id
196
+ * - return true
197
+ */
198
+ it('should hook a new callback on insert with the new id', async () => {
199
+ const extractor = new MockedErgoExtractor();
200
+ const insertCallback = vitest.fn();
201
+ const id = await extractor.hook(CallbackType.Insert, insertCallback);
202
+ expect(extractor['callbacks'][CallbackType.Insert]).toEqual(
203
+ new Map().set(id, insertCallback)
204
+ );
205
+ });
206
+ });
207
+
208
+ describe('unhook', () => {
209
+ /**
210
+ * @target unhook should unhook the callback on insert with the specified id
211
+ * @dependencies
212
+ * @scenario
213
+ * - mock extractor
214
+ * - mock a callback for insert
215
+ * - hook the callback
216
+ * - run test (call `unhook`)
217
+ * @expected
218
+ * - unhook the callback with the specified id
219
+ * - return true
220
+ */
221
+ it('should unhook the callback on insert with the specified id', async () => {
222
+ const extractor = new MockedErgoExtractor();
223
+ const insertCallback = vitest.fn();
224
+ const id = await extractor.hook(CallbackType.Insert, insertCallback);
225
+ const result = await extractor.unhook(CallbackType.Insert, id);
226
+ expect(result).toBeTruthy();
227
+ expect(extractor['callbacks'][CallbackType.Insert].get(id)).toEqual(
228
+ undefined
229
+ );
230
+ });
231
+
232
+ /**
233
+ * @target unhook should not unhook callbacks with the same id on other types
234
+ * @dependencies
235
+ * @scenario
236
+ * - mock extractor
237
+ * - mock two callbacks for insert
238
+ * - hook the first callback
239
+ * - run test (call `unhook` with the same id for second callback)
240
+ * @expected
241
+ * - not to change hooked callbacks when the callback with the id
242
+ * doesn't exists on the specified type
243
+ * - return false
244
+ */
245
+ it('should not unhook callbacks with the same id on other types', async () => {
246
+ const extractor = new MockedErgoExtractor();
247
+ const insertCallback = vitest.fn();
248
+ const id = await extractor.hook(CallbackType.Insert, insertCallback);
249
+ const result = await extractor.unhook(CallbackType.Update, id);
250
+ expect(result).toBeFalsy();
251
+ expect(extractor['callbacks'][CallbackType.Insert].get(id)).toEqual(
252
+ insertCallback
253
+ );
254
+ expect(extractor['callbacks'][CallbackType.Update].get(id)).toEqual(
255
+ undefined
256
+ );
257
+ });
258
+ });
259
+
260
+ describe('triggerCallbacks', () => {
261
+ /**
262
+ * @target triggerCallbacks should trigger all callbacks hooked on a type
263
+ * @dependencies
264
+ * @scenario
265
+ * - mock extractor
266
+ * - mock a callback for insert
267
+ * - hook the callback
268
+ * - run test (call `triggerCallbacks` for insert type)
269
+ * @expected
270
+ * - trigger all callbacks with the specified id
271
+ */
272
+ it('should trigger all callbacks hooked on a type', async () => {
273
+ const extractor = new MockedErgoExtractor();
274
+ const insertCallback = vitest.fn();
275
+ await extractor.hook(CallbackType.Insert, insertCallback);
276
+ const insertedData = [{ boxId: 'boxId', serialized: 'serialized' }];
277
+ await extractor['triggerCallbacks'](CallbackType.Insert, insertedData);
278
+ expect(insertCallback).toBeCalledWith(insertedData);
279
+ });
280
+ });
281
+ });
@@ -0,0 +1,45 @@
1
+ import { DataSource } from 'typeorm';
2
+ import { pick } from 'lodash-es';
3
+
4
+ import {
5
+ AbstractErgoExtractorAction,
6
+ AbstractErgoExtractorEntity,
7
+ BlockInfo,
8
+ AbstractBoxData,
9
+ } from '../lib';
10
+ import { TestEntity } from './testUtils';
11
+
12
+ export class TestErgoExtractorAction extends AbstractErgoExtractorAction<
13
+ AbstractBoxData,
14
+ AbstractErgoExtractorEntity
15
+ > {
16
+ constructor(dataSource: DataSource) {
17
+ super(dataSource, TestEntity);
18
+ }
19
+
20
+ /**
21
+ * create the test database entity from data and block information
22
+ */
23
+ createEntity = (
24
+ boxes: AbstractBoxData[],
25
+ block: BlockInfo,
26
+ extractor: string
27
+ ): Omit<AbstractErgoExtractorEntity, 'id'>[] => {
28
+ return boxes.map((box) => ({
29
+ boxId: box.boxId,
30
+ block: block.hash,
31
+ height: block.height,
32
+ serialized: box.serialized,
33
+ extractor: extractor,
34
+ }));
35
+ };
36
+
37
+ /**
38
+ * convert the database entity back to raw data
39
+ */
40
+ convertEntityToData = (
41
+ entities: AbstractErgoExtractorEntity[]
42
+ ): AbstractBoxData[] => {
43
+ return entities.map((data) => pick(data, ['boxId', 'serialized']));
44
+ };
45
+ }