@ocap/indexdb-sqlite 1.29.5

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 (42) hide show
  1. package/README.md +84 -0
  2. package/esm/_virtual/rolldown_runtime.mjs +21 -0
  3. package/esm/db/base.d.mts +76 -0
  4. package/esm/db/base.mjs +666 -0
  5. package/esm/db/index.d.mts +80 -0
  6. package/esm/db/index.mjs +551 -0
  7. package/esm/index.d.mts +3 -0
  8. package/esm/index.mjs +8 -0
  9. package/esm/interfaces.d.mts +328 -0
  10. package/esm/interfaces.mjs +1 -0
  11. package/esm/kysely.d.mts +43 -0
  12. package/esm/kysely.mjs +62 -0
  13. package/esm/migrations/001-genesis.d.mts +14 -0
  14. package/esm/migrations/001-genesis.mjs +107 -0
  15. package/esm/migrations/index.d.mts +16 -0
  16. package/esm/migrations/index.mjs +44 -0
  17. package/esm/package.mjs +70 -0
  18. package/esm/table/base.d.mts +107 -0
  19. package/esm/table/base.mjs +262 -0
  20. package/esm/table/transaction.d.mts +18 -0
  21. package/esm/table/transaction.mjs +22 -0
  22. package/lib/_virtual/rolldown_runtime.cjs +43 -0
  23. package/lib/db/base.cjs +670 -0
  24. package/lib/db/base.d.cts +76 -0
  25. package/lib/db/index.cjs +552 -0
  26. package/lib/db/index.d.cts +80 -0
  27. package/lib/index.cjs +10 -0
  28. package/lib/index.d.cts +3 -0
  29. package/lib/interfaces.cjs +0 -0
  30. package/lib/interfaces.d.cts +328 -0
  31. package/lib/kysely.cjs +63 -0
  32. package/lib/kysely.d.cts +43 -0
  33. package/lib/migrations/001-genesis.cjs +114 -0
  34. package/lib/migrations/001-genesis.d.cts +14 -0
  35. package/lib/migrations/index.cjs +46 -0
  36. package/lib/migrations/index.d.cts +16 -0
  37. package/lib/package.cjs +76 -0
  38. package/lib/table/base.cjs +265 -0
  39. package/lib/table/base.d.cts +107 -0
  40. package/lib/table/transaction.cjs +24 -0
  41. package/lib/table/transaction.d.cts +18 -0
  42. package/package.json +75 -0
@@ -0,0 +1,670 @@
1
+ Object.defineProperty(exports, '__esModule', { value: true });
2
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
+ let _ocap_indexdb = require("@ocap/indexdb");
4
+ let _arcblock_did_lib_type = require("@arcblock/did/lib/type");
5
+ let _ocap_util = require("@ocap/util");
6
+ let _ocap_util_lib_constant = require("@ocap/util/lib/constant");
7
+ let debug = require("debug");
8
+ debug = require_rolldown_runtime.__toESM(debug);
9
+ let lodash_omit = require("lodash/omit");
10
+ lodash_omit = require_rolldown_runtime.__toESM(lodash_omit);
11
+
12
+ //#region src/db/base.ts
13
+ const debug$1 = (0, debug.default)("@ocap/indexdb-sqlite");
14
+ const MAX_REQUEST_FACTORY_ADDRESS_SIZE = 100;
15
+ function buildPagingResult(total, pagination, itemCount) {
16
+ return {
17
+ cursor: String(pagination.cursor + itemCount),
18
+ next: itemCount >= pagination.size,
19
+ total
20
+ };
21
+ }
22
+ /**
23
+ * Base SQLite IndexDB implementation
24
+ * Contains all the list methods with SQL-based filtering
25
+ */
26
+ var SqliteBaseIndexDB = class extends _ocap_indexdb.BaseIndexDB {
27
+ /**
28
+ * List transactions with filtering and pagination
29
+ */
30
+ async listTransactions(params = {}) {
31
+ const { addressFilter = {}, paging = {}, timeFilter = {}, typeFilter = {}, assetFilter = {}, factoryFilter = {}, tokenFilter = {}, accountFilter = {}, validityFilter = {}, txFilter = {}, rollupFilter = {}, stakeFilter = {}, delegationFilter = {}, tokenFactoryFilter = {}, includeItxData = false } = params;
32
+ const { sender, receiver, direction = "UNION" } = addressFilter;
33
+ const { types = [] } = typeFilter;
34
+ const { factories = [] } = factoryFilter;
35
+ const { assets = [] } = assetFilter;
36
+ const { tokens = [] } = tokenFilter;
37
+ const { accounts = [] } = accountFilter;
38
+ const { txs = [] } = txFilter;
39
+ const { rollups = [] } = rollupFilter;
40
+ const { stakes = [] } = stakeFilter;
41
+ const { delegations = [] } = delegationFilter;
42
+ const { tokenFactories = [] } = tokenFactoryFilter;
43
+ const pagination = (0, _ocap_indexdb.formatPagination)({
44
+ paging,
45
+ defaultSortField: "time"
46
+ });
47
+ debug$1("listTransactions", {
48
+ sender,
49
+ receiver,
50
+ pagination,
51
+ types,
52
+ factories,
53
+ assets,
54
+ tokens,
55
+ accounts,
56
+ rollups,
57
+ stakes,
58
+ delegations,
59
+ includeItxData
60
+ });
61
+ let qb = this.db.selectFrom("tx").selectAll();
62
+ if (sender && receiver) if (direction === "MUTUAL") qb = qb.where((eb) => eb.or([eb.and([eb("sender", "=", sender), eb("receiver", "=", receiver)]), eb.and([eb("sender", "=", receiver), eb("receiver", "=", sender)])]));
63
+ else if (direction === "ONE_WAY") qb = qb.where("sender", "=", sender).where("receiver", "=", receiver);
64
+ else qb = qb.where((eb) => eb.or([eb("sender", "=", sender), eb("receiver", "=", receiver)]));
65
+ else if (sender) qb = qb.where("sender", "=", sender);
66
+ else if (receiver) qb = qb.where("receiver", "=", receiver);
67
+ if (types.length) qb = qb.where("type", "in", types);
68
+ if (txs.length) qb = qb.where("hash", "in", txs);
69
+ const { startDateTime, endDateTime } = timeFilter;
70
+ const parsedStart = (0, _ocap_indexdb.parseDateTime)(startDateTime);
71
+ const parsedEnd = (0, _ocap_indexdb.parseDateTime)(endDateTime);
72
+ if (parsedStart && parsedEnd) qb = qb.where("time", ">", parsedStart).where("time", "<=", parsedEnd);
73
+ else if (parsedStart) qb = qb.where("time", ">", parsedStart);
74
+ else if (parsedEnd) qb = qb.where("time", "<=", parsedEnd);
75
+ const { validity } = validityFilter;
76
+ if (validity === "VALID") qb = qb.where("valid", "=", 1);
77
+ else if (validity === "INVALID") qb = qb.where("valid", "=", 0);
78
+ if (factories.length) qb = qb.where((eb) => eb.exists(eb.selectFrom(eb.fn("json_each", [eb.ref("factories")]).as("je")).select("je.value").where("je.value", "in", factories)));
79
+ if (assets.length) qb = qb.where((eb) => eb.exists(eb.selectFrom(eb.fn("json_each", [eb.ref("assets")]).as("je")).select("je.value").where("je.value", "in", assets)));
80
+ if (tokens.length) qb = qb.where((eb) => eb.exists(eb.selectFrom(eb.fn("json_each", [eb.ref("tokens")]).as("je")).select("je.value").where("je.value", "in", tokens)));
81
+ if (accounts.length) qb = qb.where((eb) => eb.exists(eb.selectFrom(eb.fn("json_each", [eb.ref("accounts")]).as("je")).select("je.value").where("je.value", "in", accounts)));
82
+ if (rollups.length) qb = qb.where((eb) => eb.exists(eb.selectFrom(eb.fn("json_each", [eb.ref("rollups")]).as("je")).select("je.value").where("je.value", "in", rollups)));
83
+ if (stakes.length) qb = qb.where((eb) => eb.exists(eb.selectFrom(eb.fn("json_each", [eb.ref("stakes")]).as("je")).select("je.value").where("je.value", "in", stakes)));
84
+ if (delegations.length) qb = qb.where((eb) => eb.exists(eb.selectFrom(eb.fn("json_each", [eb.ref("delegations")]).as("je")).select("je.value").where("je.value", "in", delegations)));
85
+ if (tokenFactories.length) qb = qb.where((eb) => eb.exists(eb.selectFrom(eb.fn("json_each", [eb.ref("tokenFactories")]).as("je")).select("je.value").where("je.value", "in", tokenFactories)));
86
+ const total = (await qb.clearSelect().select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
87
+ const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
88
+ qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
89
+ let transactions = (await qb.execute()).map((row) => {
90
+ const tx = { ...row };
91
+ [
92
+ "receipts",
93
+ "tx",
94
+ "accounts",
95
+ "assets",
96
+ "tokens",
97
+ "tokenSymbols",
98
+ "factories",
99
+ "rollups",
100
+ "stakes",
101
+ "delegations",
102
+ "tokenFactories",
103
+ "data"
104
+ ].forEach((field) => {
105
+ if (typeof tx[field] === "string") try {
106
+ tx[field] = JSON.parse(tx[field]);
107
+ } catch {}
108
+ });
109
+ return tx;
110
+ });
111
+ if (!includeItxData) transactions = transactions.map((tx) => {
112
+ const row = tx;
113
+ if (row.tx && row.tx?.itxJson) return {
114
+ ...tx,
115
+ tx: {
116
+ ...row.tx,
117
+ itxJson: (0, lodash_omit.default)(row.tx.itxJson, ["data"])
118
+ }
119
+ };
120
+ return tx;
121
+ });
122
+ return {
123
+ transactions,
124
+ paging: buildPagingResult(total, pagination, transactions.length)
125
+ };
126
+ }
127
+ /**
128
+ * Get related addresses for account migration tracking
129
+ */
130
+ async getRelatedAddresses(address) {
131
+ let account = await this.account.get(address);
132
+ if (!account) return [];
133
+ const related = [address];
134
+ while (account?.migratedFrom && related.length <= 8) {
135
+ const migratedFrom = account.migratedFrom;
136
+ related.push(migratedFrom);
137
+ account = await this.account.get(migratedFrom);
138
+ }
139
+ return related.filter(Boolean);
140
+ }
141
+ /**
142
+ * List assets with filtering and pagination
143
+ */
144
+ async listAssets(params = {}) {
145
+ const { ownerAddress, factoryAddress, paging, timeFilter = {} } = params;
146
+ if (!ownerAddress && !factoryAddress) return {
147
+ assets: [],
148
+ account: null,
149
+ paging: {
150
+ cursor: "0",
151
+ next: false,
152
+ total: 0
153
+ }
154
+ };
155
+ const pagination = (0, _ocap_indexdb.formatPagination)({
156
+ paging,
157
+ defaultSortField: "renaissanceTime"
158
+ });
159
+ let qb = this.db.selectFrom("asset").selectAll();
160
+ if (ownerAddress) {
161
+ const possibleOwners = await this.getRelatedAddresses(ownerAddress);
162
+ if (possibleOwners.length) qb = qb.where("owner", "in", possibleOwners);
163
+ else return {
164
+ assets: [],
165
+ account: null,
166
+ paging: {
167
+ cursor: "0",
168
+ next: false,
169
+ total: 0
170
+ }
171
+ };
172
+ }
173
+ if (factoryAddress) qb = qb.where("parent", "=", factoryAddress);
174
+ const { startDateTime, endDateTime, field: rawField = "renaissanceTime" } = timeFilter;
175
+ const parsedStart = (0, _ocap_indexdb.parseDateTime)(startDateTime);
176
+ const parsedEnd = (0, _ocap_indexdb.parseDateTime)(endDateTime);
177
+ const timeField = [
178
+ "genesisTime",
179
+ "renaissanceTime",
180
+ "consumedTime"
181
+ ].includes(rawField) ? rawField : "renaissanceTime";
182
+ if (parsedStart && parsedEnd) qb = qb.where(timeField, ">", parsedStart).where(timeField, "<=", parsedEnd);
183
+ else if (parsedStart) qb = qb.where(timeField, ">", parsedStart);
184
+ else if (parsedEnd) qb = qb.where(timeField, "<=", parsedEnd);
185
+ debug$1("listAssets", {
186
+ ownerAddress,
187
+ factoryAddress,
188
+ timeFilter,
189
+ paging,
190
+ pagination
191
+ });
192
+ const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
193
+ qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
194
+ const assets = (await qb.execute()).map((row) => {
195
+ const asset = { ...row };
196
+ [
197
+ "display",
198
+ "tags",
199
+ "stake",
200
+ "data"
201
+ ].forEach((field) => {
202
+ if (typeof asset[field] === "string") try {
203
+ asset[field] = JSON.parse(asset[field]);
204
+ } catch {}
205
+ });
206
+ return asset;
207
+ });
208
+ const countConditions = {};
209
+ if (ownerAddress) countConditions.owner = { $in: await this.getRelatedAddresses(ownerAddress) };
210
+ if (factoryAddress) countConditions.parent = factoryAddress;
211
+ const total = await this.asset.count(Object.keys(countConditions).length ? countConditions : void 0);
212
+ return {
213
+ assets,
214
+ account: ownerAddress ? await this.account.get(ownerAddress) : null,
215
+ paging: (0, _ocap_indexdb.formatNextPagination)(total, pagination)
216
+ };
217
+ }
218
+ /**
219
+ * List top accounts by token balance
220
+ */
221
+ async listTopAccounts(params = {}) {
222
+ const { paging, tokenAddress } = params;
223
+ const pagination = (0, _ocap_indexdb.formatPagination)({
224
+ paging,
225
+ defaultSortField: "balance",
226
+ supportedSortFields: [
227
+ "genesisTime",
228
+ "renaissanceTime",
229
+ "balance"
230
+ ]
231
+ });
232
+ debug$1("listTopAccounts", {
233
+ tokenAddress,
234
+ paging,
235
+ pagination
236
+ });
237
+ let qb = this.db.selectFrom("account").selectAll();
238
+ if (pagination.order.field !== "balance") {
239
+ const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
240
+ qb = qb.orderBy(pagination.order.field, orderDir);
241
+ }
242
+ let accounts = (await qb.execute()).map((row) => {
243
+ const account = { ...row };
244
+ [
245
+ "stake",
246
+ "tokens",
247
+ "data"
248
+ ].forEach((field) => {
249
+ if (typeof account[field] === "string") try {
250
+ account[field] = JSON.parse(account[field]);
251
+ } catch {}
252
+ });
253
+ if (Array.isArray(account.tokens)) account.tokens = account.tokens?.map((token) => {
254
+ token.decimal = typeof token.decimal === "undefined" ? _ocap_util_lib_constant.DEFAULT_TOKEN_DECIMAL : token.decimal;
255
+ return token;
256
+ });
257
+ return account;
258
+ });
259
+ if (tokenAddress) accounts = accounts.filter((acc) => {
260
+ const tokens = acc.tokens;
261
+ if (!Array.isArray(tokens)) return false;
262
+ const owned = tokens.find((t) => t.address === tokenAddress);
263
+ return owned ? owned.balance > "0" : false;
264
+ });
265
+ if (pagination.order.field === "balance" && tokenAddress) {
266
+ const descending = pagination.order.type === "desc";
267
+ accounts.sort((a, b) => {
268
+ const tokensA = a.tokens;
269
+ const tokensB = b.tokens;
270
+ const tokenA = tokensA?.find((t) => t.address === tokenAddress);
271
+ const tokenB = tokensB?.find((t) => t.address === tokenAddress);
272
+ const balanceA = new _ocap_util.BN(tokenA ? tokenA.balance : "0");
273
+ const balanceB = new _ocap_util.BN(tokenB ? tokenB.balance : "0");
274
+ if (balanceB.gt(balanceA)) return descending ? 1 : -1;
275
+ if (balanceB.eq(balanceA)) return 0;
276
+ return descending ? -1 : 1;
277
+ });
278
+ }
279
+ const total = accounts.length;
280
+ accounts = accounts.slice(pagination.cursor, pagination.cursor + pagination.size);
281
+ return {
282
+ accounts,
283
+ paging: (0, _ocap_indexdb.formatNextPagination)(total, pagination)
284
+ };
285
+ }
286
+ /**
287
+ * List tokens with filtering and pagination
288
+ */
289
+ async listTokens(params = {}) {
290
+ const { issuerAddress, paging } = params;
291
+ const pagination = (0, _ocap_indexdb.formatPagination)({
292
+ paging,
293
+ defaultSortField: "renaissanceTime",
294
+ supportedSortFields: [
295
+ "genesisTime",
296
+ "renaissanceTime",
297
+ "issuer",
298
+ "symbol",
299
+ "totalSupply"
300
+ ]
301
+ });
302
+ debug$1("listTokens", {
303
+ issuerAddress,
304
+ paging,
305
+ pagination
306
+ });
307
+ let qb = this.db.selectFrom("token").selectAll();
308
+ if (issuerAddress) qb = qb.where("issuer", "=", issuerAddress);
309
+ const orderField = pagination.order.field === "totalSupply" ? "totalSupplyNum" : pagination.order.field;
310
+ const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
311
+ qb = qb.orderBy(orderField, orderDir).offset(pagination.cursor).limit(pagination.size);
312
+ return {
313
+ tokens: (await qb.execute()).map((row) => {
314
+ const token = { ...row };
315
+ [
316
+ "foreignToken",
317
+ "metadata",
318
+ "spenders",
319
+ "minters",
320
+ "data"
321
+ ].forEach((field) => {
322
+ if (typeof token[field] === "string") try {
323
+ token[field] = JSON.parse(token[field]);
324
+ } catch {}
325
+ });
326
+ const t = token;
327
+ t.decimal = typeof t.decimal === "undefined" ? _ocap_util_lib_constant.DEFAULT_TOKEN_DECIMAL : t.decimal;
328
+ return t;
329
+ }),
330
+ paging: (0, _ocap_indexdb.formatNextPagination)(await this.token.count(issuerAddress ? { issuer: issuerAddress } : void 0), pagination)
331
+ };
332
+ }
333
+ /**
334
+ * List token factories (bonding curve)
335
+ */
336
+ async listTokenFactories(params = {}) {
337
+ const { owner, reserveAddress, tokenAddress, paging } = params;
338
+ const pagination = (0, _ocap_indexdb.formatPagination)({
339
+ paging,
340
+ defaultSortField: "renaissanceTime",
341
+ supportedSortFields: [
342
+ "genesisTime",
343
+ "renaissanceTime",
344
+ "reserveBalance",
345
+ "currentSupply"
346
+ ]
347
+ });
348
+ debug$1("listTokenFactories", {
349
+ owner,
350
+ reserveAddress,
351
+ tokenAddress,
352
+ paging,
353
+ pagination
354
+ });
355
+ let qb = this.db.selectFrom("tokenFactory").selectAll();
356
+ if (owner) qb = qb.where("owner", "=", owner);
357
+ if (reserveAddress) qb = qb.where("reserveAddress", "=", reserveAddress);
358
+ if (tokenAddress) qb = qb.where("tokenAddress", "=", tokenAddress);
359
+ const orderField = pagination.order.field === "reserveBalance" ? "reserveBalanceNum" : pagination.order.field === "currentSupply" ? "currentSupplyNum" : pagination.order.field;
360
+ const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
361
+ qb = qb.orderBy(orderField, orderDir).offset(pagination.cursor).limit(pagination.size);
362
+ const tokenFactories = (await qb.execute()).map((row) => {
363
+ const tf = { ...row };
364
+ [
365
+ "curve",
366
+ "token",
367
+ "reserveToken",
368
+ "input",
369
+ "output",
370
+ "data"
371
+ ].forEach((field) => {
372
+ if (typeof tf[field] === "string") try {
373
+ tf[field] = JSON.parse(tf[field]);
374
+ } catch {}
375
+ });
376
+ return tf;
377
+ });
378
+ const conditions = {};
379
+ if (owner) conditions.owner = owner;
380
+ if (reserveAddress) conditions.reserveAddress = reserveAddress;
381
+ if (tokenAddress) conditions.tokenAddress = tokenAddress;
382
+ return {
383
+ tokenFactories,
384
+ paging: (0, _ocap_indexdb.formatNextPagination)(await this.tokenFactory.count(Object.keys(conditions).length ? conditions : void 0), pagination)
385
+ };
386
+ }
387
+ /**
388
+ * List asset factories
389
+ */
390
+ async listFactories(params = {}) {
391
+ const { ownerAddress, addressList, paging } = params;
392
+ const pagination = (0, _ocap_indexdb.formatPagination)({
393
+ paging,
394
+ defaultSortField: "renaissanceTime",
395
+ supportedSortFields: [
396
+ "genesisTime",
397
+ "renaissanceTime",
398
+ "owner",
399
+ "numMinted",
400
+ "limit",
401
+ "name"
402
+ ]
403
+ });
404
+ debug$1("listFactories", {
405
+ ownerAddress,
406
+ paging,
407
+ pagination
408
+ });
409
+ let qb = this.db.selectFrom("factory").selectAll();
410
+ if (ownerAddress) qb = qb.where("owner", "=", ownerAddress);
411
+ if (Array.isArray(addressList) && addressList.length > 0) {
412
+ if (addressList.length > MAX_REQUEST_FACTORY_ADDRESS_SIZE) throw new Error(`The length of 'addressList' cannot exceed the length of ${MAX_REQUEST_FACTORY_ADDRESS_SIZE}`);
413
+ qb = qb.where("address", "in", addressList);
414
+ }
415
+ const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
416
+ qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
417
+ const factories = (await qb.execute()).map((row) => {
418
+ const factory = { ...row };
419
+ [
420
+ "trustedIssuers",
421
+ "tokens",
422
+ "input",
423
+ "output",
424
+ "display",
425
+ "hooks",
426
+ "data"
427
+ ].forEach((field) => {
428
+ if (typeof factory[field] === "string") try {
429
+ factory[field] = JSON.parse(factory[field]);
430
+ } catch {}
431
+ });
432
+ return factory;
433
+ });
434
+ const conditions = {};
435
+ if (ownerAddress) conditions.owner = ownerAddress;
436
+ if (Array.isArray(addressList) && addressList.length) conditions.address = { $in: addressList };
437
+ return {
438
+ factories,
439
+ paging: (0, _ocap_indexdb.formatNextPagination)(await this.factory.count(Object.keys(conditions).length ? conditions : void 0), pagination)
440
+ };
441
+ }
442
+ /**
443
+ * List stakes
444
+ */
445
+ async listStakes(params = {}) {
446
+ const { addressFilter = {}, paging = {}, timeFilter = {}, assetFilter = {} } = params;
447
+ const { sender, receiver } = addressFilter;
448
+ const { assets = [] } = assetFilter;
449
+ const pagination = (0, _ocap_indexdb.formatPagination)({
450
+ paging,
451
+ defaultSortField: "renaissanceTime",
452
+ supportedSortFields: ["genesisTime", "renaissanceTime"]
453
+ });
454
+ let qb = this.db.selectFrom("stake").selectAll();
455
+ if (sender && receiver) qb = qb.where("sender", "=", sender).where("receiver", "=", receiver);
456
+ else if (sender) qb = qb.where("sender", "=", sender);
457
+ else if (receiver) qb = qb.where("receiver", "=", receiver);
458
+ const { startDateTime, endDateTime } = timeFilter;
459
+ const parsedStart = (0, _ocap_indexdb.parseDateTime)(startDateTime);
460
+ const parsedEnd = (0, _ocap_indexdb.parseDateTime)(endDateTime);
461
+ if (parsedStart && parsedEnd) qb = qb.where("renaissanceTime", ">", parsedStart).where("renaissanceTime", "<=", parsedEnd);
462
+ else if (parsedStart) qb = qb.where("renaissanceTime", ">", parsedStart);
463
+ else if (parsedEnd) qb = qb.where("renaissanceTime", "<=", parsedEnd);
464
+ if (assets.length) qb = qb.where((eb) => eb.exists(eb.selectFrom(eb.fn("json_each", [eb.ref("assets")]).as("je")).select("je.value").where("je.value", "in", assets)));
465
+ const total = (await qb.clearSelect().select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
466
+ const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
467
+ qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
468
+ const stakes = (await qb.execute()).map((row) => {
469
+ const stake = { ...row };
470
+ [
471
+ "tokens",
472
+ "revokedTokens",
473
+ "assets",
474
+ "revokedAssets",
475
+ "slashers",
476
+ "data"
477
+ ].forEach((field) => {
478
+ if (typeof stake[field] === "string") try {
479
+ stake[field] = JSON.parse(stake[field]);
480
+ } catch {}
481
+ });
482
+ return stake;
483
+ });
484
+ return {
485
+ stakes,
486
+ paging: buildPagingResult(total, pagination, stakes.length)
487
+ };
488
+ }
489
+ /**
490
+ * List rollups
491
+ */
492
+ async listRollups(params = {}) {
493
+ const { paging, tokenAddress = "", erc20TokenAddress = "", foreignTokenAddress = "" } = params;
494
+ const pagination = (0, _ocap_indexdb.formatPagination)({
495
+ paging,
496
+ defaultSortField: "renaissanceTime",
497
+ supportedSortFields: ["genesisTime", "renaissanceTime"]
498
+ });
499
+ let qb = this.db.selectFrom("rollup").selectAll();
500
+ if (tokenAddress) qb = qb.where("tokenAddress", "=", tokenAddress);
501
+ const foreignTokenAddr = foreignTokenAddress || erc20TokenAddress;
502
+ if (foreignTokenAddr) {
503
+ const checksumAddr = (0, _arcblock_did_lib_type.toChecksumAddress)(foreignTokenAddr);
504
+ const lowerAddr = foreignTokenAddr.toLowerCase();
505
+ qb = qb.where((eb) => eb.or([eb(eb.fn("json_extract", [eb.ref("foreignToken"), eb.val("$.contractAddress")]), "=", checksumAddr), eb(eb.fn("json_extract", [eb.ref("foreignToken"), eb.val("$.contractAddress")]), "=", lowerAddr)]));
506
+ }
507
+ debug$1("listRollups", {
508
+ paging,
509
+ pagination
510
+ });
511
+ const total = (await qb.clearSelect().select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
512
+ const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
513
+ qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
514
+ return {
515
+ rollups: (await qb.execute()).map((row) => {
516
+ const rollup = { ...row };
517
+ [
518
+ "seedValidators",
519
+ "validators",
520
+ "foreignToken",
521
+ "tokenInfo",
522
+ "migrateHistory",
523
+ "vaultHistory",
524
+ "data"
525
+ ].forEach((field) => {
526
+ if (typeof rollup[field] === "string") try {
527
+ rollup[field] = JSON.parse(rollup[field]);
528
+ } catch {}
529
+ });
530
+ return rollup;
531
+ }),
532
+ paging: (0, _ocap_indexdb.formatNextPagination)(total, pagination)
533
+ };
534
+ }
535
+ /**
536
+ * List rollup blocks
537
+ */
538
+ async listRollupBlocks(params = {}) {
539
+ const { paging = {}, rollupAddress = "", tokenAddress = "", proposer = "", height = "", timeFilter = {}, txFilter = {}, validatorFilter = {} } = params;
540
+ const { txs = [] } = txFilter;
541
+ const { validators = [] } = validatorFilter;
542
+ const pagination = (0, _ocap_indexdb.formatPagination)({
543
+ paging,
544
+ defaultSortField: "genesisTime",
545
+ supportedSortFields: ["genesisTime", "renaissanceTime"]
546
+ });
547
+ let qb = this.db.selectFrom("rollupBlock").selectAll();
548
+ if (rollupAddress) qb = qb.where("rollup", "=", rollupAddress);
549
+ if (Number(height) > 0) qb = qb.where("height", "=", Number(height));
550
+ if (proposer) qb = qb.where("proposer", "=", proposer);
551
+ const { startDateTime, endDateTime } = timeFilter;
552
+ const parsedStart = (0, _ocap_indexdb.parseDateTime)(startDateTime);
553
+ const parsedEnd = (0, _ocap_indexdb.parseDateTime)(endDateTime);
554
+ if (parsedStart && parsedEnd) qb = qb.where("genesisTime", ">", parsedStart).where("genesisTime", "<=", parsedEnd);
555
+ else if (parsedStart) qb = qb.where("genesisTime", ">", parsedStart);
556
+ else if (parsedEnd) qb = qb.where("genesisTime", "<=", parsedEnd);
557
+ if (txs.length) qb = qb.where((eb) => eb.exists(eb.selectFrom(eb.fn("json_each", [eb.ref("txs")]).as("je")).select("je.value").where("je.value", "in", txs)));
558
+ if (validators.length) qb = qb.where((eb) => eb.exists(eb.selectFrom(eb.fn("json_each", [eb.ref("validators")]).as("je")).select("je.value").where("je.value", "in", validators)));
559
+ if (tokenAddress) qb = qb.where((eb) => eb(eb.fn("json_extract", [eb.ref("tokenInfo"), eb.val("$.address")]), "=", tokenAddress));
560
+ const total = (await qb.clearSelect().select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
561
+ const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
562
+ qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
563
+ const blocks = (await qb.execute()).map((row) => {
564
+ const block = { ...row };
565
+ [
566
+ "signatures",
567
+ "txs",
568
+ "validators",
569
+ "tokenInfo",
570
+ "data"
571
+ ].forEach((field) => {
572
+ if (typeof block[field] === "string") try {
573
+ block[field] = JSON.parse(block[field]);
574
+ } catch {}
575
+ });
576
+ return block;
577
+ });
578
+ return {
579
+ blocks,
580
+ paging: buildPagingResult(total, pagination, blocks.length)
581
+ };
582
+ }
583
+ /**
584
+ * List rollup validators
585
+ */
586
+ async listRollupValidators(params = {}) {
587
+ const { paging = {}, rollupAddress = "" } = params;
588
+ const pagination = (0, _ocap_indexdb.formatPagination)({
589
+ paging,
590
+ defaultSortField: "genesisTime",
591
+ supportedSortFields: [
592
+ "joinTime",
593
+ "leaveTime",
594
+ "genesisTime",
595
+ "renaissanceTime"
596
+ ]
597
+ });
598
+ let qb = this.db.selectFrom("rollupValidator").selectAll();
599
+ let countQb = this.db.selectFrom("rollupValidator").select((eb) => eb.fn.countAll().as("count"));
600
+ if (rollupAddress) {
601
+ qb = qb.where("rollup", "=", rollupAddress);
602
+ countQb = countQb.where("rollup", "=", rollupAddress);
603
+ }
604
+ const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
605
+ qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
606
+ const [rawResults, countResult] = await Promise.all([qb.execute(), countQb.executeTakeFirst()]);
607
+ const validators = rawResults.map((row) => row);
608
+ return {
609
+ validators,
610
+ paging: buildPagingResult(Number(countResult?.count || 0), pagination, validators.length)
611
+ };
612
+ }
613
+ /**
614
+ * List delegations
615
+ */
616
+ async listDelegations(params = {}) {
617
+ const { from, to, paging = {}, timeFilter = {} } = params;
618
+ if (!from && !to) return {
619
+ delegations: [],
620
+ paging: {
621
+ cursor: "0",
622
+ next: false,
623
+ total: 0
624
+ }
625
+ };
626
+ const pagination = (0, _ocap_indexdb.formatPagination)({
627
+ paging,
628
+ defaultSortField: "renaissanceTime",
629
+ supportedSortFields: ["genesisTime", "renaissanceTime"]
630
+ });
631
+ let qb = this.db.selectFrom("delegation").selectAll();
632
+ if (from && to) qb = qb.where("from_", "=", from).where("to_", "=", to);
633
+ else if (from) qb = qb.where("from_", "=", from);
634
+ else if (to) qb = qb.where("to_", "=", to);
635
+ const { startDateTime, endDateTime } = timeFilter;
636
+ const parsedStart = (0, _ocap_indexdb.parseDateTime)(startDateTime);
637
+ const parsedEnd = (0, _ocap_indexdb.parseDateTime)(endDateTime);
638
+ if (parsedStart && parsedEnd) qb = qb.where("renaissanceTime", ">", parsedStart).where("renaissanceTime", "<=", parsedEnd);
639
+ else if (parsedStart) qb = qb.where("renaissanceTime", ">", parsedStart);
640
+ else if (parsedEnd) qb = qb.where("renaissanceTime", "<=", parsedEnd);
641
+ const total = (await qb.clearSelect().select(this.db.fn.countAll().as("count")).executeTakeFirst())?.count ?? 0;
642
+ const orderDir = pagination.order.type === "desc" ? "desc" : "asc";
643
+ qb = qb.orderBy(pagination.order.field, orderDir).offset(pagination.cursor).limit(pagination.size);
644
+ const delegations = (await qb.execute()).map((row) => {
645
+ const delegation = { ...row };
646
+ delegation.from = delegation.from_;
647
+ delegation.to = delegation.to_;
648
+ delete delegation.from_;
649
+ delete delegation.to_;
650
+ [
651
+ "ops",
652
+ "context",
653
+ "data"
654
+ ].forEach((field) => {
655
+ if (typeof delegation[field] === "string") try {
656
+ delegation[field] = JSON.parse(delegation[field]);
657
+ } catch {}
658
+ });
659
+ return (0, _ocap_indexdb.formatDelegationAfterRead)(delegation);
660
+ });
661
+ return {
662
+ delegations,
663
+ paging: buildPagingResult(total, pagination, delegations.length)
664
+ };
665
+ }
666
+ };
667
+ var base_default = SqliteBaseIndexDB;
668
+
669
+ //#endregion
670
+ exports.default = base_default;