@ocap/indexdb 1.28.9 → 1.29.1

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.
package/lib/util.d.cts ADDED
@@ -0,0 +1,374 @@
1
+ import { FinalizedContext, IAccountState, IAssetFactoryState, IAssetState, IDelegateState, IIndexTable, IRollupBlock, IRollupState, IStakeState, ITokenFactoryState, ITokenState, TIndexedAccountState, TIndexedAssetState, TIndexedDelegationState, TIndexedTokenState, TPageInfo, TTokenDistribution, TTokenMeta } from "@ocap/types";
2
+
3
+ //#region src/util.d.ts
4
+
5
+ /**
6
+ * Token state with metadata for formatting
7
+ * Note: foreignToken type from ITokenState (IForeignToken) differs from TForeignToken,
8
+ * we use a flexible type here to accommodate both
9
+ */
10
+ interface TokenStateInfo {
11
+ address: string;
12
+ decimal?: number;
13
+ unit?: string;
14
+ symbol?: string;
15
+ icon?: string;
16
+ /** Foreign token info - may be IForeignToken from state or TForeignToken when indexed */
17
+ foreignToken?: {
18
+ type?: string;
19
+ contractAddress?: string;
20
+ chainType?: string;
21
+ chainName?: string;
22
+ chainId?: number;
23
+ } | null;
24
+ }
25
+ /** Token with address and optional balance */
26
+ interface TokenWithBalance {
27
+ address: string;
28
+ balance?: string;
29
+ value?: string;
30
+ [key: string]: unknown;
31
+ }
32
+ /** Minimal IndexDB interface for indexed transaction creation */
33
+ interface IndexDBForTx {
34
+ delegation?: IIndexTable<{
35
+ to: string;
36
+ address: string;
37
+ }>;
38
+ token?: IIndexTable<TokenStateInfo>;
39
+ }
40
+ /** Inner transaction JSON structure */
41
+ interface ItxJson {
42
+ type_url?: string;
43
+ value?: string | number;
44
+ to?: string;
45
+ token?: string;
46
+ assets?: string[];
47
+ tokens?: Array<{
48
+ address: string;
49
+ value?: string;
50
+ }>;
51
+ inputs?: Array<{
52
+ assets?: string[];
53
+ tokens?: Array<{
54
+ address: string;
55
+ value?: string;
56
+ }>;
57
+ }>;
58
+ outputs?: Array<{
59
+ assets?: string[];
60
+ tokens?: Array<{
61
+ address: string;
62
+ value?: string;
63
+ }>;
64
+ }>;
65
+ sender?: {
66
+ value?: string;
67
+ assets?: string[];
68
+ tokens?: Array<{
69
+ address: string;
70
+ value?: string;
71
+ }>;
72
+ };
73
+ receiver?: {
74
+ value?: string;
75
+ assets?: string[];
76
+ tokens?: Array<{
77
+ address: string;
78
+ value?: string;
79
+ }>;
80
+ };
81
+ address?: string;
82
+ factory?: string;
83
+ data?: {
84
+ type_url: string;
85
+ value: string;
86
+ };
87
+ [key: string]: unknown;
88
+ }
89
+ /** Decoded transaction structure */
90
+ interface DecodedTx {
91
+ from: string;
92
+ itxJson: ItxJson;
93
+ [key: string]: unknown;
94
+ }
95
+ /** Transaction data for indexing */
96
+ interface TxData {
97
+ hash?: string;
98
+ type?: string;
99
+ code?: string;
100
+ sender?: string;
101
+ receiver?: string;
102
+ time?: string;
103
+ valid?: boolean;
104
+ tx: DecodedTx;
105
+ receipts?: Array<{
106
+ changes: Array<{
107
+ target: string;
108
+ value: string;
109
+ }>;
110
+ }>;
111
+ accounts?: string[];
112
+ assets?: string[];
113
+ tokens?: string[];
114
+ factories?: string[];
115
+ stakes?: string[];
116
+ rollups?: string[];
117
+ delegations?: string[];
118
+ tokenFactories?: string[];
119
+ tokenSymbols?: Array<Partial<TTokenMeta>>;
120
+ [key: string]: unknown;
121
+ }
122
+ /** Context for creating indexed delegation */
123
+ interface DelegationContext {
124
+ senderState?: IAccountState;
125
+ receiverState?: IAccountState;
126
+ tx?: {
127
+ from: string;
128
+ };
129
+ itx?: {
130
+ to: string;
131
+ };
132
+ }
133
+ /** Context for creating indexed factory */
134
+ interface FactoryContext {
135
+ factoryTokens?: Array<{
136
+ address: string;
137
+ value: string;
138
+ }>;
139
+ tokenStates?: TokenStateInfo[];
140
+ }
141
+ /** Context for creating indexed token factory */
142
+ interface TokenFactoryContext {
143
+ itx?: {
144
+ token?: TokenStateInfo;
145
+ };
146
+ config?: {
147
+ token?: TokenStateInfo;
148
+ };
149
+ }
150
+ /** Context for creating indexed rollup */
151
+ interface RollupContext {
152
+ tokenStates?: TokenStateInfo[];
153
+ }
154
+ /** Context for creating indexed rollup block */
155
+ interface RollupBlockContext {
156
+ rollupState?: {
157
+ tokenAddress: string;
158
+ };
159
+ tokenStates?: TokenStateInfo[];
160
+ }
161
+ /**
162
+ * Format token with metadata from token states
163
+ * @param token - Token with address
164
+ * @param tokenStates - Array of token states for metadata lookup
165
+ * @param rest - Additional args for debug logging
166
+ */
167
+ declare const formatTokenMeta: (token: TokenWithBalance, tokenStates?: TokenStateInfo[] | null, ...rest: unknown[]) => TokenWithBalance;
168
+ /**
169
+ * Create indexed account from account state
170
+ */
171
+ declare const createIndexedAccount: (x: IAccountState & {
172
+ balance?: string;
173
+ migratedTo?: string[];
174
+ migratedFrom?: string[];
175
+ numAssets?: number;
176
+ numTxs?: number;
177
+ }, getTokenFn: (address: string) => Promise<TokenStateInfo | null>) => Promise<Omit<TIndexedAccountState, "balance" | "totalReceivedStakes" | "totalStakes" | "totalUnstakes" | "nonce" | "numAssets" | "numTxs"> & {
178
+ balance: string;
179
+ nonce: number | string;
180
+ numAssets: number | string;
181
+ numTxs: number | string;
182
+ }>;
183
+ /**
184
+ * Create indexed asset from asset state
185
+ * Note: display/endpoint/data types from IAssetState may differ from TIndexedAssetState,
186
+ * they are passed through without transformation
187
+ */
188
+ declare const createIndexedAsset: (x: IAssetState) => Omit<TIndexedAssetState, "display" | "endpoint" | "data"> & {
189
+ data?: IAssetState["data"];
190
+ display?: IAssetState["display"];
191
+ endpoint?: IAssetState["endpoint"];
192
+ };
193
+ /**
194
+ * Create indexed delegation from delegation state
195
+ */
196
+ declare const createIndexedDelegation: (x: IDelegateState, ctx: DelegationContext) => Partial<TIndexedDelegationState> & {
197
+ ops: unknown[];
198
+ };
199
+ /**
200
+ * Create indexed token from token state
201
+ * Note: foreignToken/metadata/data types from ITokenState may differ from TIndexedTokenState,
202
+ * they are passed through without transformation
203
+ */
204
+ declare const createIndexedToken: (x: ITokenState) => Omit<TIndexedTokenState, "foreignToken" | "metadata" | "data"> & {
205
+ foreignToken?: ITokenState["foreignToken"];
206
+ metadata?: ITokenState["metadata"];
207
+ data?: ITokenState["data"];
208
+ };
209
+ /**
210
+ * Create indexed token factory from token factory state
211
+ * Note: token/reserveToken may not have all TIndexedTokenInput fields filled,
212
+ * they are populated with available metadata from context
213
+ */
214
+ declare const createIndexedTokenFactory: (tokenFactory: ITokenFactoryState & {
215
+ tokenAddress: string;
216
+ reserveAddress: string;
217
+ }, context: TokenFactoryContext) => Record<string, unknown> & {
218
+ token: TokenWithBalance;
219
+ reserveToken: TokenWithBalance;
220
+ };
221
+ /**
222
+ * Create indexed factory from asset factory state
223
+ * Note: tokens array may not have all TTokenMeta fields filled,
224
+ * they are populated with available metadata from context
225
+ */
226
+ declare const createIndexedFactory: (factory: IAssetFactoryState & {
227
+ input?: {
228
+ tokens?: TokenWithBalance[];
229
+ };
230
+ }, context: FactoryContext) => Record<string, unknown> & {
231
+ tokens: TokenWithBalance[];
232
+ };
233
+ /**
234
+ * Create indexed transaction from transaction context
235
+ * These fields are used internally to filter transactions by some entity
236
+ */
237
+ declare const createIndexedTransaction: (tx: TxData, ctx: FinalizedContext, indexdb: IndexDBForTx) => Promise<TxData>;
238
+ /**
239
+ * Create indexed stake from stake state
240
+ * Note: tokens/revokedTokens arrays may not have all TTokenMeta fields filled,
241
+ * they are populated with available metadata from context
242
+ */
243
+ declare const createIndexedStake: (x: IStakeState, ctx: {
244
+ tokenStates?: TokenStateInfo[];
245
+ }, indexdb: {
246
+ token?: IIndexTable<TokenStateInfo>;
247
+ }) => Promise<Record<string, unknown> & {
248
+ tokens: TokenWithBalance[];
249
+ revokedTokens: TokenWithBalance[];
250
+ }>;
251
+ /**
252
+ * Create indexed rollup from rollup state
253
+ * Note: foreignToken from TokenStateInfo is passed through without transformation
254
+ */
255
+ declare const createIndexedRollup: (x: IRollupState & {
256
+ tokenAddress: string;
257
+ }, ctx: RollupContext) => Record<string, unknown> & {
258
+ tokenInfo?: TokenWithBalance;
259
+ foreignToken?: TokenStateInfo["foreignToken"];
260
+ };
261
+ /**
262
+ * Create indexed rollup block from rollup block state
263
+ * Note: tokenInfo may not have all TIndexedTokenInput fields filled,
264
+ * they are populated with available metadata from context
265
+ */
266
+ declare const createIndexedRollupBlock: (x: IRollupBlock & {
267
+ signaturesList?: Array<{
268
+ signer: string;
269
+ }>;
270
+ }, ctx: RollupBlockContext) => Record<string, unknown> & {
271
+ tokenInfo?: TokenWithBalance;
272
+ validators: string[];
273
+ };
274
+ /**
275
+ * Create indexed token distribution
276
+ */
277
+ declare const createIndexedTokenDistribution: (x: {
278
+ tokenAddress: string;
279
+ txTime: string;
280
+ account: {
281
+ toString: () => string;
282
+ };
283
+ gas: {
284
+ toString: () => string;
285
+ };
286
+ fee: {
287
+ toString: () => string;
288
+ };
289
+ slashedVault: {
290
+ toString: () => string;
291
+ };
292
+ stake: {
293
+ toString: () => string;
294
+ };
295
+ revokedStake: {
296
+ toString: () => string;
297
+ };
298
+ gasStake: {
299
+ toString: () => string;
300
+ };
301
+ }) => Partial<TTokenDistribution>;
302
+ /**
303
+ * Format transaction before inserting to index
304
+ */
305
+ declare const formatTxBeforeInsert: (row: TxData) => TxData;
306
+ /**
307
+ * Format transaction after reading from index (remove internal indexing fields)
308
+ */
309
+ declare const formatTxAfterRead: (tx: TxData) => TxData;
310
+ /**
311
+ * Format delegation after reading from index
312
+ */
313
+ declare const formatDelegationAfterRead: (delegation: {
314
+ ops: unknown[] | Record<string, unknown>;
315
+ }) => {
316
+ ops: Array<{
317
+ key: string;
318
+ value: unknown;
319
+ }>;
320
+ };
321
+ /**
322
+ * Parse date time string to ISO format
323
+ */
324
+ declare const parseDateTime: (str: unknown) => string;
325
+ /** Paging input parameters */
326
+ interface PagingInput {
327
+ size?: number | null;
328
+ cursor?: string | number;
329
+ order?: {
330
+ field?: string;
331
+ type?: string;
332
+ } | Array<{
333
+ field?: string;
334
+ type?: string;
335
+ }>;
336
+ }
337
+ /** Parameters for formatPagination */
338
+ interface FormatPaginationParams {
339
+ paging?: PagingInput | null;
340
+ defaultSortField: string;
341
+ supportedSortFields?: string[];
342
+ }
343
+ /** Formatted pagination result */
344
+ interface FormattedPagination {
345
+ size: number;
346
+ cursor: number;
347
+ order: {
348
+ field: string;
349
+ type: string;
350
+ };
351
+ }
352
+ /**
353
+ * Format pagination parameters with defaults
354
+ */
355
+ declare const formatPagination: ({
356
+ paging,
357
+ defaultSortField,
358
+ supportedSortFields
359
+ }: FormatPaginationParams) => FormattedPagination;
360
+ /**
361
+ * Format next pagination info for response
362
+ */
363
+ declare const formatNextPagination: (total: number, pagination: {
364
+ cursor: number;
365
+ size: number;
366
+ }) => TPageInfo;
367
+ /**
368
+ * Check if a transaction changes the default token balance
369
+ */
370
+ declare const isDefaultTokenChanged: (tx: TxData, token: {
371
+ address: string;
372
+ }) => boolean;
373
+ //#endregion
374
+ export { DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime };
package/package.json CHANGED
@@ -3,17 +3,41 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.28.9",
6
+ "version": "1.29.1",
7
+ "type": "module",
7
8
  "description": "Defines the basic interface for OCAP IndexDB",
8
- "main": "lib/main.js",
9
+ "main": "./lib/main.cjs",
10
+ "module": "./esm/main.mjs",
11
+ "types": "./esm/main.d.mts",
12
+ "sideEffects": false,
13
+ "exports": {
14
+ ".": {
15
+ "types": "./esm/main.d.mts",
16
+ "import": "./esm/main.mjs",
17
+ "default": "./lib/main.cjs"
18
+ },
19
+ "./lib/*.js": {
20
+ "types": "./esm/*.d.mts",
21
+ "import": "./esm/*.mjs",
22
+ "default": "./lib/*.cjs"
23
+ },
24
+ "./lib/*": {
25
+ "types": "./esm/*.d.mts",
26
+ "import": "./esm/*.mjs",
27
+ "default": "./lib/*.cjs"
28
+ }
29
+ },
9
30
  "files": [
10
- "lib"
31
+ "lib",
32
+ "esm"
11
33
  ],
12
34
  "scripts": {
13
35
  "lint": "biome check",
14
36
  "lint:fix": "biome check --write",
15
37
  "test": "bun test",
16
- "coverage": "npm run test -- --coverage"
38
+ "coverage": "npm run test -- --coverage",
39
+ "build": "tsdown",
40
+ "build:watch": "tsdown -w"
17
41
  },
18
42
  "keywords": [],
19
43
  "author": "wangshijun <wangshijun2010@gmail.com> (http://github.com/wangshijun)",
@@ -21,11 +45,16 @@
21
45
  "wangshijun <shijun@arcblock.io> (https://github.com/wangshijun)"
22
46
  ],
23
47
  "license": "MIT",
24
- "devDependencies": {},
48
+ "devDependencies": {
49
+ "@types/lodash": "^4.17.10",
50
+ "@types/node": "^22.7.5",
51
+ "tsdown": "^0.18.4"
52
+ },
25
53
  "dependencies": {
26
- "@ocap/state": "1.28.9",
27
- "@ocap/util": "1.28.9",
54
+ "@ocap/state": "1.29.1",
55
+ "@ocap/types": "1.29.1",
56
+ "@ocap/util": "1.29.1",
28
57
  "kareem": "^2.4.1",
29
- "lodash": "^4.17.21"
58
+ "lodash": "^4.17.23"
30
59
  }
31
60
  }
package/lib/db.js DELETED
@@ -1,61 +0,0 @@
1
- const { Ready } = require('@ocap/util/lib/ready');
2
- const { indexes } = require('@ocap/state');
3
-
4
- class BaseIndexDB extends Ready {
5
- constructor() {
6
- super();
7
-
8
- this.readyMarks = Object.fromEntries(indexes.map((x) => [x, false]));
9
- this.readyListenersAttached = false;
10
- }
11
-
12
- attachReadyListeners() {
13
- if (this.readyListenersAttached) {
14
- return;
15
- }
16
-
17
- for (const index of indexes) {
18
- if (typeof this[index] === 'undefined') {
19
- throw new Error(`Missing index ${index} in indexdb adapter: ${this.name}`);
20
- }
21
-
22
- this[index].onReady(() => this.markReady(index));
23
- }
24
-
25
- this.readyListenersAttached = true;
26
- }
27
-
28
- listTransactions({ _addressFilter = {}, _paging = {}, _timeFilter = {}, _typeFilter = {} } = {}) {
29
- throw new Error('listTransactions should be implemented in adapter');
30
- }
31
-
32
- listAssets({ _ownerAddress, _paging } = {}) {
33
- throw new Error('listAssets should be implemented in adapter');
34
- }
35
-
36
- listFactories({ _ownerAddress, _paging } = {}) {
37
- throw new Error('listFactories should be implemented in adapter');
38
- }
39
-
40
- listTopAccounts({ _paging, _tokenAddress } = {}) {
41
- throw new Error('listTopAccounts should be implemented in adapter');
42
- }
43
-
44
- listTokens({ _paging } = {}) {
45
- throw new Error('listTokens should be implemented in adapter');
46
- }
47
-
48
- listStakes({ _paging = {}, _addressFilter = {}, _timeFilter = {}, _assetFilter = {} } = {}) {
49
- throw new Error('listStakes should be implemented in adapter');
50
- }
51
-
52
- listBlocks() {
53
- return [];
54
- }
55
-
56
- listDelegations({ _from, _to, _paging = {}, _timeFilter = {} } = {}) {
57
- throw new Error('listDelegations should be implemented in adapter');
58
- }
59
- }
60
-
61
- module.exports = BaseIndexDB;
package/lib/index.js DELETED
@@ -1,79 +0,0 @@
1
- const crypto = require('node:crypto');
2
- const Kareem = require('kareem');
3
- const omit = require('lodash/omit');
4
- const { Ready } = require('@ocap/util/lib/ready');
5
-
6
- class BaseIndex extends Ready {
7
- constructor(name, uniqIndex) {
8
- super();
9
-
10
- this.name = name;
11
- this.ready = false;
12
- this.readyCallbacks = [];
13
- this.uniqIndex = uniqIndex;
14
- this.primaryKey = typeof uniqIndex === 'string' ? uniqIndex : 'id';
15
-
16
- const hooks = new Kareem();
17
-
18
- Object.defineProperty(this, 'pre', { value: (n, fn) => hooks.pre(n, fn) });
19
- Object.defineProperty(this, 'post', { value: (n, fn) => hooks.post(n, fn) });
20
-
21
- ['insert', 'get', 'update', 'reset'].forEach((x) => {
22
- Object.defineProperty(this, x, {
23
- value: async (...args) => {
24
- hooks.execPreSync(x, args);
25
- const result = await this[`_${x}`](...args);
26
- hooks.execPostSync(x, result);
27
-
28
- if (['insert', 'update'].includes(x)) {
29
- this.emit(x, omit(result, '$loki'));
30
- }
31
-
32
- return result;
33
- },
34
- });
35
- });
36
- }
37
-
38
- count() {
39
- throw new Error('`count` must be implemented in sub indexdb');
40
- }
41
-
42
- _insert(_attrs, _context) {
43
- throw new Error('`_insert` must be implemented in sub indexdb');
44
- }
45
-
46
- _get(_id, _context) {
47
- throw new Error('`_get` must be implemented in sub indexdb');
48
- }
49
-
50
- _update(_id, _updates, _context) {
51
- throw new Error('`_update` must be implemented in sub indexdb');
52
- }
53
-
54
- _reset(_context) {
55
- throw new Error('`_reset` must be implemented in sub indexdb');
56
- }
57
-
58
- /**
59
- * Generate an ID composed of multiple primary keys
60
- */
61
- generatePrimaryKey(doc) {
62
- if (typeof doc === 'string') {
63
- return doc;
64
- }
65
-
66
- // composite primary key
67
- if (Array.isArray(this.uniqIndex)) {
68
- const key = this.uniqIndex
69
- .map((id) => doc[id])
70
- .map((item) => (typeof item === 'object' ? JSON.stringify(item) : item))
71
- .join('-');
72
- return crypto.createHash('md5').update(key).digest('hex');
73
- }
74
-
75
- return doc[this.uniqIndex];
76
- }
77
- }
78
-
79
- module.exports = BaseIndex;
package/lib/main.js DELETED
@@ -1,4 +0,0 @@
1
- const BaseIndex = require('./index');
2
- const BaseIndexDB = require('./db');
3
-
4
- module.exports = { BaseIndex, BaseIndexDB };