@ocap/indexdb 1.31.0 → 1.31.2

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.
@@ -0,0 +1,109 @@
1
+ //#region src/backfill.d.ts
2
+ interface ITxIndexRowSnapshot {
3
+ hash: string;
4
+ sender?: string | null;
5
+ receiver?: string | null;
6
+ gasPayer?: string | null;
7
+ time?: string | null;
8
+ tx?: string | Record<string, unknown> | null;
9
+ receipts?: string | unknown[] | null;
10
+ accounts?: string | string[] | null;
11
+ }
12
+ interface ILedgerEntrySnapshot {
13
+ sequence?: number;
14
+ hash: string;
15
+ from?: string | null;
16
+ nonce?: number | string | null;
17
+ pk?: string | null;
18
+ signature?: string | null;
19
+ tx?: string | Record<string, unknown> | null;
20
+ txType?: string | null;
21
+ timestamp?: number | string | null;
22
+ chainId?: string | null;
23
+ txExtra?: string | Record<string, unknown> | null;
24
+ stateCommitHash?: string | null;
25
+ finalized?: number | boolean | null;
26
+ }
27
+ interface ITxIndexBackfillUpdate {
28
+ hash: string;
29
+ prevSender: string;
30
+ nextSender: string;
31
+ prevGasPayer: string;
32
+ nextGasPayer: string;
33
+ nextTxJson: string;
34
+ nextAccountsJson: string;
35
+ addedAccountRefs: string[];
36
+ time: string;
37
+ }
38
+ interface ITxIndexBackfillInsert {
39
+ hash: string;
40
+ type: string;
41
+ code: string;
42
+ valid: number;
43
+ time: string;
44
+ sender: string;
45
+ receiver: string;
46
+ gasPayer: string;
47
+ txJson: string;
48
+ receiptsJson: string;
49
+ tokenSymbolsJson: string;
50
+ accountsJson: string;
51
+ accountRefs: string[];
52
+ }
53
+ interface ITxIndexBackfillPlan {
54
+ requiresGasPayerColumn: boolean;
55
+ updates: ITxIndexBackfillUpdate[];
56
+ inserts: ITxIndexBackfillInsert[];
57
+ summary: {
58
+ scannedTxRows: number;
59
+ scannedLedgerRows: number;
60
+ updateCount: number;
61
+ insertCount: number;
62
+ };
63
+ planDigest: string;
64
+ }
65
+ interface ISqliteStatementLike {
66
+ all?: (...params: unknown[]) => unknown[];
67
+ run?: (...params: unknown[]) => unknown;
68
+ }
69
+ interface ISqliteDatabaseLike {
70
+ prepare(sql: string): ISqliteStatementLike;
71
+ exec(sql: string): unknown;
72
+ }
73
+ /**
74
+ * Compute deterministic SHA-256 digest of a backfill plan's canonical payload
75
+ */
76
+ declare function computeBackfillPlanDigest(plan: {
77
+ requiresGasPayerColumn: boolean;
78
+ updates: ITxIndexBackfillUpdate[];
79
+ inserts: ITxIndexBackfillInsert[];
80
+ }): string;
81
+ /**
82
+ * Pure deterministic planner for Issue #1362 historical tx index backfill
83
+ */
84
+ declare function buildTxIndexBackfillPlan(params: {
85
+ txRows: ITxIndexRowSnapshot[];
86
+ ledgerRows?: ILedgerEntrySnapshot[];
87
+ hasGasPayerColumn?: boolean;
88
+ }): ITxIndexBackfillPlan;
89
+ /**
90
+ * Read-only SQLite inspection & backfill plan builder (zero writes)
91
+ */
92
+ declare function planTxIndexBackfill(params: {
93
+ indexDb: ISqliteDatabaseLike;
94
+ ledgerDb?: ISqliteDatabaseLike | null;
95
+ }): ITxIndexBackfillPlan;
96
+ /**
97
+ * Digest-guarded atomic apply of a previously generated backfill plan
98
+ */
99
+ declare function applyTxIndexBackfill(params: {
100
+ indexDb: ISqliteDatabaseLike;
101
+ plan: ITxIndexBackfillPlan;
102
+ expectedPlanDigest: string;
103
+ }): {
104
+ updatedRows: number;
105
+ insertedRows: number;
106
+ planDigest: string;
107
+ };
108
+ //#endregion
109
+ export { ILedgerEntrySnapshot, ISqliteDatabaseLike, ISqliteStatementLike, ITxIndexBackfillInsert, ITxIndexBackfillPlan, ITxIndexBackfillUpdate, ITxIndexRowSnapshot, applyTxIndexBackfill, buildTxIndexBackfillPlan, computeBackfillPlanDigest, planTxIndexBackfill };
@@ -0,0 +1,252 @@
1
+ import { deriveTxGasPayer, deriveTxSender } from "./util.mjs";
2
+ import crypto from "node:crypto";
3
+ import uniq from "lodash/uniq.js";
4
+
5
+ //#region src/backfill.ts
6
+ function parseJsonObject(val) {
7
+ if (!val) return {};
8
+ if (typeof val === "object" && !Array.isArray(val)) return { ...val };
9
+ if (typeof val === "string") try {
10
+ const parsed = JSON.parse(val);
11
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
12
+ } catch {
13
+ return {};
14
+ }
15
+ return {};
16
+ }
17
+ function parseJsonArray(val) {
18
+ if (!val) return [];
19
+ if (Array.isArray(val)) return [...val];
20
+ if (typeof val === "string") try {
21
+ const parsed = JSON.parse(val);
22
+ if (Array.isArray(parsed)) return parsed;
23
+ } catch {
24
+ return [];
25
+ }
26
+ return [];
27
+ }
28
+ function normalizeIsoTime(timestamp) {
29
+ if (typeof timestamp === "string" && timestamp.trim()) {
30
+ const asNum = Number(timestamp);
31
+ if (Number.isFinite(asNum) && asNum > 0) {
32
+ const ms = asNum < 0xe8d4a51000 ? asNum * 1e3 : asNum;
33
+ return new Date(ms).toISOString();
34
+ }
35
+ const parsed = Date.parse(timestamp);
36
+ if (!Number.isNaN(parsed)) return new Date(parsed).toISOString();
37
+ }
38
+ if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {
39
+ const ms = timestamp < 0xe8d4a51000 ? timestamp * 1e3 : timestamp;
40
+ return new Date(ms).toISOString();
41
+ }
42
+ return (/* @__PURE__ */ new Date(0)).toISOString();
43
+ }
44
+ /**
45
+ * Compute deterministic SHA-256 digest of a backfill plan's canonical payload
46
+ */
47
+ function computeBackfillPlanDigest(plan) {
48
+ const canonicalUpdates = [...plan.updates || []].sort((a, b) => a.hash.localeCompare(b.hash));
49
+ const canonicalInserts = [...plan.inserts || []].sort((a, b) => a.hash.localeCompare(b.hash));
50
+ const canonicalPayload = JSON.stringify({
51
+ requiresGasPayerColumn: Boolean(plan.requiresGasPayerColumn),
52
+ updates: canonicalUpdates,
53
+ inserts: canonicalInserts
54
+ });
55
+ return crypto.createHash("sha256").update(canonicalPayload).digest("hex");
56
+ }
57
+ /**
58
+ * Pure deterministic planner for Issue #1362 historical tx index backfill
59
+ */
60
+ function buildTxIndexBackfillPlan(params) {
61
+ const { txRows = [], ledgerRows = [], hasGasPayerColumn = true } = params;
62
+ const requiresGasPayerColumn = !hasGasPayerColumn;
63
+ const existingHashes = /* @__PURE__ */ new Set();
64
+ const updates = [];
65
+ for (const row of txRows) {
66
+ const rawHash = String(row.hash || "").trim();
67
+ const canonicalHash = rawHash.toUpperCase();
68
+ if (!rawHash) continue;
69
+ existingHashes.add(canonicalHash);
70
+ const prevSender = String(row.sender || "");
71
+ const prevGasPayer = String(row.gasPayer || "");
72
+ const txObj = parseJsonObject(row.tx);
73
+ const receipts = parseJsonArray(row.receipts);
74
+ const existingAccounts = parseJsonArray(row.accounts).filter(Boolean);
75
+ const candidateTxData = {
76
+ hash: rawHash,
77
+ sender: prevSender,
78
+ receiver: String(row.receiver || ""),
79
+ gasPayer: prevGasPayer,
80
+ tx: txObj,
81
+ receipts
82
+ };
83
+ const nextSender = prevSender;
84
+ const nextGasPayer = prevGasPayer || deriveTxGasPayer(candidateTxData);
85
+ if (nextGasPayer && nextGasPayer !== prevGasPayer) updates.push({
86
+ hash: rawHash,
87
+ prevSender,
88
+ nextSender,
89
+ prevGasPayer,
90
+ nextGasPayer,
91
+ nextTxJson: typeof row.tx === "string" ? row.tx : JSON.stringify(txObj),
92
+ nextAccountsJson: JSON.stringify(existingAccounts),
93
+ addedAccountRefs: [],
94
+ time: String(row.time || "")
95
+ });
96
+ }
97
+ const inserts = [];
98
+ for (const entry of ledgerRows) {
99
+ const hash = String(entry.hash || "").trim().toUpperCase();
100
+ if (!hash || existingHashes.has(hash)) continue;
101
+ if (!(!entry.stateCommitHash || String(entry.stateCommitHash).trim() === "" || Number(entry.finalized ?? 1) === 0)) continue;
102
+ existingHashes.add(hash);
103
+ const parsedTx = parseJsonObject(entry.tx);
104
+ const txType = String(entry.txType || parsedTx.type || parsedTx.itx?.type_url || "");
105
+ const type = txType ? txType.split(":").pop() || "" : "";
106
+ const typeName = type ? `${type.split("_").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("")}Tx` : "";
107
+ const from = String(entry.from || parsedTx.from || "");
108
+ const delegator = String(parsedTx.delegator || "");
109
+ const itxJson = parseJsonObject(parsedTx.itxJson || parsedTx.itx);
110
+ if (txType && !itxJson.type_url) itxJson.type_url = txType;
111
+ if (typeName && !itxJson._type) itxJson._type = typeName;
112
+ const sender = deriveTxSender({ tx: {
113
+ from,
114
+ delegator,
115
+ itxJson
116
+ } });
117
+ const gasPayer = deriveTxGasPayer({
118
+ sender,
119
+ valid: false,
120
+ code: "REJECTED_UNPERSISTED",
121
+ tx: {
122
+ from,
123
+ delegator,
124
+ itxJson
125
+ }
126
+ });
127
+ const time = normalizeIsoTime(entry.timestamp);
128
+ const accountRefs = uniq([
129
+ from,
130
+ delegator,
131
+ sender,
132
+ gasPayer
133
+ ].filter(Boolean));
134
+ const txRecord = {
135
+ chainId: String(entry.chainId || parsedTx.chainId || ""),
136
+ from,
137
+ delegator,
138
+ nonce: entry.nonce ?? parsedTx.nonce ?? 0,
139
+ pk: String(entry.pk || parsedTx.pk || ""),
140
+ signature: String(entry.signature || parsedTx.signature || ""),
141
+ signaturesList: Array.isArray(parsedTx.signaturesList) ? parsedTx.signaturesList : [],
142
+ signatures: Array.isArray(parsedTx.signatures) ? parsedTx.signatures : [],
143
+ serviceFee: "0",
144
+ gasFee: "0",
145
+ gasPaid: "0",
146
+ gasPayer,
147
+ itx: {
148
+ typeUrl: txType,
149
+ ...typeName ? { __typename: typeName } : {}
150
+ },
151
+ itxJson
152
+ };
153
+ inserts.push({
154
+ hash,
155
+ type,
156
+ code: "REJECTED_UNPERSISTED",
157
+ valid: 0,
158
+ time,
159
+ sender,
160
+ receiver: "",
161
+ gasPayer,
162
+ txJson: JSON.stringify(txRecord),
163
+ receiptsJson: "[]",
164
+ tokenSymbolsJson: "[]",
165
+ accountsJson: JSON.stringify(accountRefs),
166
+ accountRefs
167
+ });
168
+ }
169
+ updates.sort((a, b) => a.hash.localeCompare(b.hash));
170
+ inserts.sort((a, b) => a.hash.localeCompare(b.hash));
171
+ const planDigest = computeBackfillPlanDigest({
172
+ requiresGasPayerColumn,
173
+ updates,
174
+ inserts
175
+ });
176
+ return {
177
+ requiresGasPayerColumn,
178
+ updates,
179
+ inserts,
180
+ summary: {
181
+ scannedTxRows: txRows.length,
182
+ scannedLedgerRows: ledgerRows.length,
183
+ updateCount: updates.length,
184
+ insertCount: inserts.length
185
+ },
186
+ planDigest
187
+ };
188
+ }
189
+ /**
190
+ * Read-only SQLite inspection & backfill plan builder (zero writes)
191
+ */
192
+ function planTxIndexBackfill(params) {
193
+ const { indexDb, ledgerDb } = params;
194
+ const pragmaRows = indexDb.prepare("PRAGMA table_info('tx')").all?.() || [];
195
+ const hasGasPayerColumn = new Set(pragmaRows.map((r) => r.name)).has("gasPayer");
196
+ const selectCols = hasGasPayerColumn ? "hash, sender, receiver, gasPayer, time, tx, receipts, accounts" : "hash, sender, receiver, NULL as gasPayer, time, tx, receipts, accounts";
197
+ const txRows = indexDb.prepare(`SELECT ${selectCols} FROM tx`).all?.() || [];
198
+ let ledgerRows = [];
199
+ if (ledgerDb) {
200
+ if ((ledgerDb.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'ledger_entries'").all?.() || []).length > 0) ledgerRows = ledgerDb.prepare("SELECT sequence, hash, \"from\", nonce, pk, signature, tx, txType, timestamp, chainId, txExtra, stateCommitHash, finalized FROM ledger_entries").all?.() || [];
201
+ }
202
+ return buildTxIndexBackfillPlan({
203
+ txRows,
204
+ ledgerRows,
205
+ hasGasPayerColumn
206
+ });
207
+ }
208
+ /**
209
+ * Digest-guarded atomic apply of a previously generated backfill plan
210
+ */
211
+ function applyTxIndexBackfill(params) {
212
+ const { indexDb, plan, expectedPlanDigest } = params;
213
+ const recomputedDigest = computeBackfillPlanDigest(plan);
214
+ if (!expectedPlanDigest || expectedPlanDigest !== plan.planDigest || recomputedDigest !== expectedPlanDigest) throw new Error(`PLAN_DIGEST_MISMATCH: expectedPlanDigest (${expectedPlanDigest || "empty"}) does not match computed plan digest (${recomputedDigest})`);
215
+ indexDb.exec("BEGIN IMMEDIATE");
216
+ try {
217
+ const pragmaRows = indexDb.prepare("PRAGMA table_info('tx')").all?.() || [];
218
+ const columnNames = new Set(pragmaRows.map((r) => r.name));
219
+ const hasTxRef = (indexDb.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'tx_ref'").all?.() || []).length > 0;
220
+ if (!columnNames.has("gasPayer")) indexDb.exec("ALTER TABLE tx ADD COLUMN gasPayer TEXT");
221
+ indexDb.exec("CREATE INDEX IF NOT EXISTS idx_tx_gasPayer ON tx(gasPayer)");
222
+ const updateStmt = indexDb.prepare("UPDATE tx SET sender = ?, gasPayer = ?, tx = ?, accounts = ? WHERE hash = ?");
223
+ const insertTxStmt = indexDb.prepare("INSERT OR IGNORE INTO tx (hash, type, code, valid, time, sender, receiver, gasPayer, tx, receipts, tokenSymbols, accounts) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
224
+ const insertRefStmt = hasTxRef ? indexDb.prepare("INSERT OR IGNORE INTO tx_ref (hash, type, value, time) VALUES (?, ?, ?, ?)") : null;
225
+ let updatedRows = 0;
226
+ for (const item of plan.updates) {
227
+ updateStmt.run?.(item.nextSender, item.nextGasPayer, item.nextTxJson, item.nextAccountsJson, item.hash);
228
+ if (insertRefStmt) for (const acc of item.addedAccountRefs) insertRefStmt.run?.(item.hash, "account", acc, item.time || "");
229
+ updatedRows += 1;
230
+ }
231
+ let insertedRows = 0;
232
+ for (const item of plan.inserts) {
233
+ insertTxStmt.run?.(item.hash, item.type, item.code, item.valid, item.time, item.sender, item.receiver, item.gasPayer, item.txJson, item.receiptsJson, item.tokenSymbolsJson, item.accountsJson);
234
+ if (insertRefStmt) for (const acc of item.accountRefs) insertRefStmt.run?.(item.hash, "account", acc, item.time || "");
235
+ insertedRows += 1;
236
+ }
237
+ indexDb.exec("COMMIT");
238
+ return {
239
+ updatedRows,
240
+ insertedRows,
241
+ planDigest: plan.planDigest
242
+ };
243
+ } catch (err) {
244
+ try {
245
+ indexDb.exec("ROLLBACK");
246
+ } catch {}
247
+ throw err;
248
+ }
249
+ }
250
+
251
+ //#endregion
252
+ export { applyTxIndexBackfill, buildTxIndexBackfillPlan, computeBackfillPlanDigest, planTxIndexBackfill };
package/esm/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { Ready } from "@ocap/util/lib/ready";
2
1
  import crypto from "node:crypto";
2
+ import { Ready } from "@ocap/util/lib/ready";
3
3
  import Kareem from "kareem";
4
4
  import omit from "lodash/omit.js";
5
5
 
package/esm/main.d.mts CHANGED
@@ -1,6 +1,7 @@
1
+ import { ILedgerEntrySnapshot, ISqliteDatabaseLike, ISqliteStatementLike, ITxIndexBackfillInsert, ITxIndexBackfillPlan, ITxIndexBackfillUpdate, ITxIndexRowSnapshot, applyTxIndexBackfill, buildTxIndexBackfillPlan, computeBackfillPlanDigest, planTxIndexBackfill } from "./backfill.mjs";
1
2
  import BaseIndexDB from "./db.mjs";
2
3
  import BaseIndex from "./index.mjs";
3
4
  import { SearchResultFormatOptions, formatSearchResult } from "./search-result.mjs";
4
- import { 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 } from "./util.mjs";
5
+ import { BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime } from "./util.mjs";
5
6
  import { clearIndexDB, rebuildIndexFromState, scanStateTable } from "./rebuild.mjs";
6
- export { BaseIndex, BaseIndexDB, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, clearIndexDB, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime, rebuildIndexFromState, scanStateTable };
7
+ export { BaseIndex, BaseIndexDB, BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, ILedgerEntrySnapshot, ISqliteDatabaseLike, ISqliteStatementLike, ITxIndexBackfillInsert, ITxIndexBackfillPlan, ITxIndexBackfillUpdate, ITxIndexRowSnapshot, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, applyTxIndexBackfill, buildTxIndexBackfillPlan, clearIndexDB, computeBackfillPlanDigest, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime, planTxIndexBackfill, rebuildIndexFromState, scanStateTable };
package/esm/main.mjs CHANGED
@@ -1,7 +1,8 @@
1
- import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime } from "./util.mjs";
1
+ import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime } from "./util.mjs";
2
+ import { applyTxIndexBackfill, buildTxIndexBackfillPlan, computeBackfillPlanDigest, planTxIndexBackfill } from "./backfill.mjs";
2
3
  import { clearIndexDB, rebuildIndexFromState, scanStateTable } from "./rebuild.mjs";
3
4
  import db_default from "./db.mjs";
4
5
  import src_default from "./index.mjs";
5
6
  import { formatSearchResult } from "./search-result.mjs";
6
7
 
7
- export { src_default as BaseIndex, db_default as BaseIndexDB, clearIndexDB, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime, rebuildIndexFromState, scanStateTable };
8
+ export { src_default as BaseIndex, db_default as BaseIndexDB, applyTxIndexBackfill, buildTxIndexBackfillPlan, clearIndexDB, computeBackfillPlanDigest, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime, planTxIndexBackfill, rebuildIndexFromState, scanStateTable };
package/esm/util.d.mts CHANGED
@@ -89,6 +89,8 @@ interface ItxJson {
89
89
  /** Decoded transaction structure */
90
90
  interface DecodedTx {
91
91
  from: string;
92
+ delegator?: string;
93
+ gasPayer?: string;
92
94
  itxJson: ItxJson;
93
95
  [key: string]: unknown;
94
96
  }
@@ -99,12 +101,15 @@ interface TxData {
99
101
  code?: string;
100
102
  sender?: string;
101
103
  receiver?: string;
104
+ gasPayer?: string;
102
105
  time?: string;
103
106
  valid?: boolean;
104
107
  tx: DecodedTx;
105
108
  receipts?: Array<{
109
+ address?: string;
106
110
  changes: Array<{
107
111
  target: string;
112
+ action?: string;
108
113
  value: string;
109
114
  }>;
110
115
  }>;
@@ -116,6 +121,7 @@ interface TxData {
116
121
  rollups?: string[];
117
122
  delegations?: string[];
118
123
  tokenFactories?: string[];
124
+ evidences?: string[];
119
125
  tokenSymbols?: Array<Partial<TTokenMeta>>;
120
126
  [key: string]: unknown;
121
127
  }
@@ -230,6 +236,33 @@ declare const createIndexedFactory: (factory: IAssetFactoryState & {
230
236
  }, context: FactoryContext) => Record<string, unknown> & {
231
237
  tokens: TokenWithBalance[];
232
238
  };
239
+ /** Fields of a release_bridge_token itx that identify the deposit or withdraw being settled */
240
+ interface BridgeReleaseEvidenceInput {
241
+ /** OCAP bridge (RollupState address) the release belongs to (bridge/docs/ocap-protocols.md §v2.4) */
242
+ bridge?: string;
243
+ kind?: number | string;
244
+ evidence?: string;
245
+ ordinal?: number | string;
246
+ }
247
+ /**
248
+ * Evidence lookup key of a release_bridge_token tx: `<bridge>:<kind>:<evidence lowercased>:<ordinal>`
249
+ * (kind and ordinal as decimal strings, bridge as given, trimmed: OCAP addresses are case-sensitive).
250
+ * Returns null unless bridge is a non-empty string without ':' or whitespace, kind is 1, 2 or 3, ordinal is a
251
+ * non-negative integer and evidence is a 0x-prefixed 32-byte hex string (after trim + lowercase).
252
+ * The key was `<kind>:<evidence>:<ordinal>` in the single-reserve model (#1479). The index is new and unused in
253
+ * production, so rows written with the old key are simply not found under the new one (no migration).
254
+ * Pass the same key in `txFilter.evidences` of listTransactions to find the release tx.
255
+ */
256
+ declare const getBridgeReleaseEvidenceKey: (itx?: BridgeReleaseEvidenceInput | null) => string | null;
257
+ /**
258
+ * Derive the signer-based sender. Only for rows that never got a getTxSender value (rejected-but-ledgered
259
+ * txs); normal rows keep getTxSender semantics ("whose asset has net loss", may be empty).
260
+ */
261
+ declare const deriveTxSender: (tx?: Partial<TxData> | null, ctx?: Partial<FinalizedContext> | null) => string;
262
+ /**
263
+ * Derive transaction gas payer / sponsor address
264
+ */
265
+ declare const deriveTxGasPayer: (tx?: Partial<TxData> | null, ctx?: Partial<FinalizedContext> | null) => string;
233
266
  /**
234
267
  * Create indexed transaction from transaction context
235
268
  * These fields are used internally to filter transactions by some entity
@@ -371,4 +404,4 @@ declare const isDefaultTokenChanged: (tx: TxData, token: {
371
404
  address: string;
372
405
  }) => boolean;
373
406
  //#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 };
407
+ export { BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime };
package/esm/util.mjs CHANGED
@@ -1,8 +1,8 @@
1
+ import uniq from "lodash/uniq.js";
1
2
  import { BN } from "@ocap/util";
2
3
  import { createSortedList } from "@ocap/util/lib/create-sorted-list";
3
4
  import get from "lodash/get.js";
4
5
  import pick from "lodash/pick.js";
5
- import uniq from "lodash/uniq.js";
6
6
  import uniqBy from "lodash/uniqBy.js";
7
7
 
8
8
  //#region src/util.ts
@@ -174,13 +174,80 @@ const createIndexedFactory = (factory, context) => {
174
174
  renaissanceTime: factory.context.renaissanceTime
175
175
  };
176
176
  };
177
+ /** Rejected-but-ledgered index rows (#1362) have no statedb tx and therefore no getTxSender value. */
178
+ const isRejectedIndexRow = (tx) => {
179
+ const valid = tx?.valid;
180
+ return valid === false || valid === 0;
181
+ };
182
+ /**
183
+ * Evidence lookup key of a release_bridge_token tx: `<bridge>:<kind>:<evidence lowercased>:<ordinal>`
184
+ * (kind and ordinal as decimal strings, bridge as given, trimmed: OCAP addresses are case-sensitive).
185
+ * Returns null unless bridge is a non-empty string without ':' or whitespace, kind is 1, 2 or 3, ordinal is a
186
+ * non-negative integer and evidence is a 0x-prefixed 32-byte hex string (after trim + lowercase).
187
+ * The key was `<kind>:<evidence>:<ordinal>` in the single-reserve model (#1479). The index is new and unused in
188
+ * production, so rows written with the old key are simply not found under the new one (no migration).
189
+ * Pass the same key in `txFilter.evidences` of listTransactions to find the release tx.
190
+ */
191
+ const getBridgeReleaseEvidenceKey = (itx) => {
192
+ const bridge = typeof itx?.bridge === "string" ? itx.bridge.trim() : "";
193
+ if (!bridge || /[:\s]/.test(bridge)) return null;
194
+ const evidence = typeof itx?.evidence === "string" ? itx.evidence.trim().toLowerCase() : "";
195
+ if (!/^0x[0-9a-f]{64}$/.test(evidence)) return null;
196
+ const kind = Number(itx?.kind);
197
+ const ordinal = Number(itx?.ordinal ?? 0);
198
+ if (![
199
+ 1,
200
+ 2,
201
+ 3
202
+ ].includes(kind) || !Number.isInteger(ordinal) || ordinal < 0) return null;
203
+ return `${bridge}:${kind}:${evidence}:${ordinal}`;
204
+ };
205
+ /**
206
+ * Derive the signer-based sender. Only for rows that never got a getTxSender value (rejected-but-ledgered
207
+ * txs); normal rows keep getTxSender semantics ("whose asset has net loss", may be empty).
208
+ */
209
+ const deriveTxSender = (tx, ctx) => {
210
+ if (!tx) return "";
211
+ if (typeof tx.sender === "string" && tx.sender) return tx.sender;
212
+ const innerTx = tx.tx;
213
+ const firstInputOwner = (innerTx?.itxJson?.inputs?.[0])?.owner;
214
+ return innerTx?.from || innerTx?.delegator || firstInputOwner || ctx?.senderState?.address || "";
215
+ };
216
+ /**
217
+ * Derive transaction gas payer / sponsor address
218
+ */
219
+ const deriveTxGasPayer = (tx, ctx) => {
220
+ if (!tx && !ctx) return "";
221
+ const innerTx = tx?.tx;
222
+ const explicitGasPayer = tx?.gasPayer || innerTx?.gasPayer;
223
+ if (typeof explicitGasPayer === "string" && explicitGasPayer) return explicitGasPayer;
224
+ if (Array.isArray(tx?.receipts)) for (const receipt of tx.receipts) {
225
+ if (!Array.isArray(receipt?.changes)) continue;
226
+ for (const change of receipt.changes) if (change?.action === "gas" && String(change.value || "").startsWith("-")) {
227
+ if (typeof receipt.address === "string" && receipt.address) return receipt.address;
228
+ const parts = String(change.target || "").split(".");
229
+ if (parts[0] === "account" && parts[1]) return parts[1];
230
+ }
231
+ }
232
+ const typedCtx = ctx;
233
+ const gasStake = typedCtx?.gasStake;
234
+ const sponsorState = typedCtx?.sponsorState;
235
+ const isFailedPaymaster = Boolean(typedCtx?.isFailedTxGasCharge) || tx?.valid === false || Boolean(tx?.code) && tx?.code !== "OK";
236
+ if (gasStake?.valid === true && gasStake.sponsorAddress) return gasStake.sponsorAddress;
237
+ if (!isFailedPaymaster && sponsorState?.address) return sponsorState.address;
238
+ if (gasStake?.valid === true && gasStake.owner) return gasStake.owner;
239
+ return "";
240
+ };
177
241
  /**
178
242
  * Create indexed transaction from transaction context
179
243
  * These fields are used internally to filter transactions by some entity
180
244
  */
181
245
  const createIndexedTransaction = async (tx, ctx, indexdb) => {
246
+ if (isRejectedIndexRow(tx)) tx.sender = deriveTxSender(tx, ctx);
247
+ tx.gasPayer = deriveTxGasPayer(tx, ctx);
248
+ if (tx.gasPayer && tx.tx && typeof tx.tx === "object") tx.tx.gasPayer = tx.tx.gasPayer || tx.gasPayer;
182
249
  tx.accounts = [
183
- tx.tx.from,
250
+ tx.tx?.from,
184
251
  tx.sender,
185
252
  tx.receiver
186
253
  ].filter(Boolean);
@@ -386,7 +453,11 @@ const formatTxBeforeInsert = (row) => {
386
453
  const tx = { ...row };
387
454
  tx.sender = tx.sender || "";
388
455
  tx.receiver = tx.receiver || "";
456
+ tx.gasPayer = tx.gasPayer || "";
389
457
  if (!tx.tx || !tx.tx.itxJson) return tx;
458
+ if (isRejectedIndexRow(tx)) tx.sender = deriveTxSender(tx);
459
+ tx.gasPayer = deriveTxGasPayer(tx);
460
+ if (tx.gasPayer) tx.tx.gasPayer = tx.tx.gasPayer || tx.gasPayer;
390
461
  const itx = tx.tx.itxJson;
391
462
  tx.assets = tx.assets || [];
392
463
  if (["transfer", "transfer_v2"].includes(tx.type || "") && itx.assets) tx.assets.push(...itx.assets);
@@ -421,6 +492,13 @@ const formatTxBeforeInsert = (row) => {
421
492
  else if (tx.type === "exchange_v2") tx.tokens.push(...(itx.sender?.tokens || []).map((x) => x.address), ...(itx.receiver?.tokens || []).map((x) => x.address));
422
493
  tx.accounts = tx.accounts || [];
423
494
  tx.stakes = tx.stakes || [];
495
+ tx.evidences = tx.evidences || [];
496
+ const isValidRow = tx.valid === true || tx.valid === 1;
497
+ if (tx.type === "release_bridge_token" && isValidRow && !isRejectedIndexRow(tx)) {
498
+ const evidenceKey = getBridgeReleaseEvidenceKey(itx);
499
+ if (evidenceKey) tx.evidences.push(evidenceKey);
500
+ }
501
+ tx.evidences = uniq(tx.evidences).filter(Boolean);
424
502
  tx.assets = uniq(tx.assets).filter(Boolean);
425
503
  tx.factories = uniq(tx.factories).filter(Boolean);
426
504
  tx.tokens = uniq(tx.tokens).filter(Boolean);
@@ -441,6 +519,7 @@ const formatTxAfterRead = (tx) => {
441
519
  delete tx.stakes;
442
520
  delete tx.rollups;
443
521
  delete tx.delegations;
522
+ delete tx.evidences;
444
523
  return tx;
445
524
  };
446
525
  /**
@@ -514,7 +593,8 @@ const formatNextPagination = (total, pagination) => {
514
593
  * Check if a transaction changes the default token balance
515
594
  */
516
595
  const isDefaultTokenChanged = (tx, token) => {
517
- const itx = tx.tx.itxJson;
596
+ const itx = tx?.tx?.itxJson;
597
+ if (!itx) return false;
518
598
  if ([
519
599
  "fg:t:transfer",
520
600
  "fg:t:transfer_v2",
@@ -534,7 +614,13 @@ const isDefaultTokenChanged = (tx, token) => {
534
614
  ].includes(itx.type_url || "") === false) return false;
535
615
  const ZERO = new BN(0);
536
616
  const isDefaultToken = (id) => [token.address, ""].includes(id);
537
- const isPositive = (v) => new BN(v || 0).gt(ZERO);
617
+ const isPositive = (v) => {
618
+ try {
619
+ return new BN(v || 0).gt(ZERO);
620
+ } catch {
621
+ return false;
622
+ }
623
+ };
538
624
  const isChangedByInput = (input) => isPositive(input.value) || (input.tokens?.some((x) => isDefaultToken(x.address) && isPositive(x.value)) ?? false);
539
625
  switch (itx.type_url) {
540
626
  case "fg:t:transfer": return isPositive(itx.value);
@@ -559,4 +645,4 @@ const isDefaultTokenChanged = (tx, token) => {
559
645
  };
560
646
 
561
647
  //#endregion
562
- export { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime };
648
+ export { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime };
@@ -0,0 +1,258 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const require_util = require('./util.cjs');
3
+ let node_crypto = require("node:crypto");
4
+ node_crypto = require_rolldown_runtime.__toESM(node_crypto);
5
+ let lodash_uniq = require("lodash/uniq");
6
+ lodash_uniq = require_rolldown_runtime.__toESM(lodash_uniq);
7
+
8
+ //#region src/backfill.ts
9
+ function parseJsonObject(val) {
10
+ if (!val) return {};
11
+ if (typeof val === "object" && !Array.isArray(val)) return { ...val };
12
+ if (typeof val === "string") try {
13
+ const parsed = JSON.parse(val);
14
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
15
+ } catch {
16
+ return {};
17
+ }
18
+ return {};
19
+ }
20
+ function parseJsonArray(val) {
21
+ if (!val) return [];
22
+ if (Array.isArray(val)) return [...val];
23
+ if (typeof val === "string") try {
24
+ const parsed = JSON.parse(val);
25
+ if (Array.isArray(parsed)) return parsed;
26
+ } catch {
27
+ return [];
28
+ }
29
+ return [];
30
+ }
31
+ function normalizeIsoTime(timestamp) {
32
+ if (typeof timestamp === "string" && timestamp.trim()) {
33
+ const asNum = Number(timestamp);
34
+ if (Number.isFinite(asNum) && asNum > 0) {
35
+ const ms = asNum < 0xe8d4a51000 ? asNum * 1e3 : asNum;
36
+ return new Date(ms).toISOString();
37
+ }
38
+ const parsed = Date.parse(timestamp);
39
+ if (!Number.isNaN(parsed)) return new Date(parsed).toISOString();
40
+ }
41
+ if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {
42
+ const ms = timestamp < 0xe8d4a51000 ? timestamp * 1e3 : timestamp;
43
+ return new Date(ms).toISOString();
44
+ }
45
+ return (/* @__PURE__ */ new Date(0)).toISOString();
46
+ }
47
+ /**
48
+ * Compute deterministic SHA-256 digest of a backfill plan's canonical payload
49
+ */
50
+ function computeBackfillPlanDigest(plan) {
51
+ const canonicalUpdates = [...plan.updates || []].sort((a, b) => a.hash.localeCompare(b.hash));
52
+ const canonicalInserts = [...plan.inserts || []].sort((a, b) => a.hash.localeCompare(b.hash));
53
+ const canonicalPayload = JSON.stringify({
54
+ requiresGasPayerColumn: Boolean(plan.requiresGasPayerColumn),
55
+ updates: canonicalUpdates,
56
+ inserts: canonicalInserts
57
+ });
58
+ return node_crypto.default.createHash("sha256").update(canonicalPayload).digest("hex");
59
+ }
60
+ /**
61
+ * Pure deterministic planner for Issue #1362 historical tx index backfill
62
+ */
63
+ function buildTxIndexBackfillPlan(params) {
64
+ const { txRows = [], ledgerRows = [], hasGasPayerColumn = true } = params;
65
+ const requiresGasPayerColumn = !hasGasPayerColumn;
66
+ const existingHashes = /* @__PURE__ */ new Set();
67
+ const updates = [];
68
+ for (const row of txRows) {
69
+ const rawHash = String(row.hash || "").trim();
70
+ const canonicalHash = rawHash.toUpperCase();
71
+ if (!rawHash) continue;
72
+ existingHashes.add(canonicalHash);
73
+ const prevSender = String(row.sender || "");
74
+ const prevGasPayer = String(row.gasPayer || "");
75
+ const txObj = parseJsonObject(row.tx);
76
+ const receipts = parseJsonArray(row.receipts);
77
+ const existingAccounts = parseJsonArray(row.accounts).filter(Boolean);
78
+ const candidateTxData = {
79
+ hash: rawHash,
80
+ sender: prevSender,
81
+ receiver: String(row.receiver || ""),
82
+ gasPayer: prevGasPayer,
83
+ tx: txObj,
84
+ receipts
85
+ };
86
+ const nextSender = prevSender;
87
+ const nextGasPayer = prevGasPayer || require_util.deriveTxGasPayer(candidateTxData);
88
+ if (nextGasPayer && nextGasPayer !== prevGasPayer) updates.push({
89
+ hash: rawHash,
90
+ prevSender,
91
+ nextSender,
92
+ prevGasPayer,
93
+ nextGasPayer,
94
+ nextTxJson: typeof row.tx === "string" ? row.tx : JSON.stringify(txObj),
95
+ nextAccountsJson: JSON.stringify(existingAccounts),
96
+ addedAccountRefs: [],
97
+ time: String(row.time || "")
98
+ });
99
+ }
100
+ const inserts = [];
101
+ for (const entry of ledgerRows) {
102
+ const hash = String(entry.hash || "").trim().toUpperCase();
103
+ if (!hash || existingHashes.has(hash)) continue;
104
+ if (!(!entry.stateCommitHash || String(entry.stateCommitHash).trim() === "" || Number(entry.finalized ?? 1) === 0)) continue;
105
+ existingHashes.add(hash);
106
+ const parsedTx = parseJsonObject(entry.tx);
107
+ const txType = String(entry.txType || parsedTx.type || parsedTx.itx?.type_url || "");
108
+ const type = txType ? txType.split(":").pop() || "" : "";
109
+ const typeName = type ? `${type.split("_").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("")}Tx` : "";
110
+ const from = String(entry.from || parsedTx.from || "");
111
+ const delegator = String(parsedTx.delegator || "");
112
+ const itxJson = parseJsonObject(parsedTx.itxJson || parsedTx.itx);
113
+ if (txType && !itxJson.type_url) itxJson.type_url = txType;
114
+ if (typeName && !itxJson._type) itxJson._type = typeName;
115
+ const sender = require_util.deriveTxSender({ tx: {
116
+ from,
117
+ delegator,
118
+ itxJson
119
+ } });
120
+ const gasPayer = require_util.deriveTxGasPayer({
121
+ sender,
122
+ valid: false,
123
+ code: "REJECTED_UNPERSISTED",
124
+ tx: {
125
+ from,
126
+ delegator,
127
+ itxJson
128
+ }
129
+ });
130
+ const time = normalizeIsoTime(entry.timestamp);
131
+ const accountRefs = (0, lodash_uniq.default)([
132
+ from,
133
+ delegator,
134
+ sender,
135
+ gasPayer
136
+ ].filter(Boolean));
137
+ const txRecord = {
138
+ chainId: String(entry.chainId || parsedTx.chainId || ""),
139
+ from,
140
+ delegator,
141
+ nonce: entry.nonce ?? parsedTx.nonce ?? 0,
142
+ pk: String(entry.pk || parsedTx.pk || ""),
143
+ signature: String(entry.signature || parsedTx.signature || ""),
144
+ signaturesList: Array.isArray(parsedTx.signaturesList) ? parsedTx.signaturesList : [],
145
+ signatures: Array.isArray(parsedTx.signatures) ? parsedTx.signatures : [],
146
+ serviceFee: "0",
147
+ gasFee: "0",
148
+ gasPaid: "0",
149
+ gasPayer,
150
+ itx: {
151
+ typeUrl: txType,
152
+ ...typeName ? { __typename: typeName } : {}
153
+ },
154
+ itxJson
155
+ };
156
+ inserts.push({
157
+ hash,
158
+ type,
159
+ code: "REJECTED_UNPERSISTED",
160
+ valid: 0,
161
+ time,
162
+ sender,
163
+ receiver: "",
164
+ gasPayer,
165
+ txJson: JSON.stringify(txRecord),
166
+ receiptsJson: "[]",
167
+ tokenSymbolsJson: "[]",
168
+ accountsJson: JSON.stringify(accountRefs),
169
+ accountRefs
170
+ });
171
+ }
172
+ updates.sort((a, b) => a.hash.localeCompare(b.hash));
173
+ inserts.sort((a, b) => a.hash.localeCompare(b.hash));
174
+ const planDigest = computeBackfillPlanDigest({
175
+ requiresGasPayerColumn,
176
+ updates,
177
+ inserts
178
+ });
179
+ return {
180
+ requiresGasPayerColumn,
181
+ updates,
182
+ inserts,
183
+ summary: {
184
+ scannedTxRows: txRows.length,
185
+ scannedLedgerRows: ledgerRows.length,
186
+ updateCount: updates.length,
187
+ insertCount: inserts.length
188
+ },
189
+ planDigest
190
+ };
191
+ }
192
+ /**
193
+ * Read-only SQLite inspection & backfill plan builder (zero writes)
194
+ */
195
+ function planTxIndexBackfill(params) {
196
+ const { indexDb, ledgerDb } = params;
197
+ const pragmaRows = indexDb.prepare("PRAGMA table_info('tx')").all?.() || [];
198
+ const hasGasPayerColumn = new Set(pragmaRows.map((r) => r.name)).has("gasPayer");
199
+ const selectCols = hasGasPayerColumn ? "hash, sender, receiver, gasPayer, time, tx, receipts, accounts" : "hash, sender, receiver, NULL as gasPayer, time, tx, receipts, accounts";
200
+ const txRows = indexDb.prepare(`SELECT ${selectCols} FROM tx`).all?.() || [];
201
+ let ledgerRows = [];
202
+ if (ledgerDb) {
203
+ if ((ledgerDb.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'ledger_entries'").all?.() || []).length > 0) ledgerRows = ledgerDb.prepare("SELECT sequence, hash, \"from\", nonce, pk, signature, tx, txType, timestamp, chainId, txExtra, stateCommitHash, finalized FROM ledger_entries").all?.() || [];
204
+ }
205
+ return buildTxIndexBackfillPlan({
206
+ txRows,
207
+ ledgerRows,
208
+ hasGasPayerColumn
209
+ });
210
+ }
211
+ /**
212
+ * Digest-guarded atomic apply of a previously generated backfill plan
213
+ */
214
+ function applyTxIndexBackfill(params) {
215
+ const { indexDb, plan, expectedPlanDigest } = params;
216
+ const recomputedDigest = computeBackfillPlanDigest(plan);
217
+ if (!expectedPlanDigest || expectedPlanDigest !== plan.planDigest || recomputedDigest !== expectedPlanDigest) throw new Error(`PLAN_DIGEST_MISMATCH: expectedPlanDigest (${expectedPlanDigest || "empty"}) does not match computed plan digest (${recomputedDigest})`);
218
+ indexDb.exec("BEGIN IMMEDIATE");
219
+ try {
220
+ const pragmaRows = indexDb.prepare("PRAGMA table_info('tx')").all?.() || [];
221
+ const columnNames = new Set(pragmaRows.map((r) => r.name));
222
+ const hasTxRef = (indexDb.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'tx_ref'").all?.() || []).length > 0;
223
+ if (!columnNames.has("gasPayer")) indexDb.exec("ALTER TABLE tx ADD COLUMN gasPayer TEXT");
224
+ indexDb.exec("CREATE INDEX IF NOT EXISTS idx_tx_gasPayer ON tx(gasPayer)");
225
+ const updateStmt = indexDb.prepare("UPDATE tx SET sender = ?, gasPayer = ?, tx = ?, accounts = ? WHERE hash = ?");
226
+ const insertTxStmt = indexDb.prepare("INSERT OR IGNORE INTO tx (hash, type, code, valid, time, sender, receiver, gasPayer, tx, receipts, tokenSymbols, accounts) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
227
+ const insertRefStmt = hasTxRef ? indexDb.prepare("INSERT OR IGNORE INTO tx_ref (hash, type, value, time) VALUES (?, ?, ?, ?)") : null;
228
+ let updatedRows = 0;
229
+ for (const item of plan.updates) {
230
+ updateStmt.run?.(item.nextSender, item.nextGasPayer, item.nextTxJson, item.nextAccountsJson, item.hash);
231
+ if (insertRefStmt) for (const acc of item.addedAccountRefs) insertRefStmt.run?.(item.hash, "account", acc, item.time || "");
232
+ updatedRows += 1;
233
+ }
234
+ let insertedRows = 0;
235
+ for (const item of plan.inserts) {
236
+ insertTxStmt.run?.(item.hash, item.type, item.code, item.valid, item.time, item.sender, item.receiver, item.gasPayer, item.txJson, item.receiptsJson, item.tokenSymbolsJson, item.accountsJson);
237
+ if (insertRefStmt) for (const acc of item.accountRefs) insertRefStmt.run?.(item.hash, "account", acc, item.time || "");
238
+ insertedRows += 1;
239
+ }
240
+ indexDb.exec("COMMIT");
241
+ return {
242
+ updatedRows,
243
+ insertedRows,
244
+ planDigest: plan.planDigest
245
+ };
246
+ } catch (err) {
247
+ try {
248
+ indexDb.exec("ROLLBACK");
249
+ } catch {}
250
+ throw err;
251
+ }
252
+ }
253
+
254
+ //#endregion
255
+ exports.applyTxIndexBackfill = applyTxIndexBackfill;
256
+ exports.buildTxIndexBackfillPlan = buildTxIndexBackfillPlan;
257
+ exports.computeBackfillPlanDigest = computeBackfillPlanDigest;
258
+ exports.planTxIndexBackfill = planTxIndexBackfill;
@@ -0,0 +1,109 @@
1
+ //#region src/backfill.d.ts
2
+ interface ITxIndexRowSnapshot {
3
+ hash: string;
4
+ sender?: string | null;
5
+ receiver?: string | null;
6
+ gasPayer?: string | null;
7
+ time?: string | null;
8
+ tx?: string | Record<string, unknown> | null;
9
+ receipts?: string | unknown[] | null;
10
+ accounts?: string | string[] | null;
11
+ }
12
+ interface ILedgerEntrySnapshot {
13
+ sequence?: number;
14
+ hash: string;
15
+ from?: string | null;
16
+ nonce?: number | string | null;
17
+ pk?: string | null;
18
+ signature?: string | null;
19
+ tx?: string | Record<string, unknown> | null;
20
+ txType?: string | null;
21
+ timestamp?: number | string | null;
22
+ chainId?: string | null;
23
+ txExtra?: string | Record<string, unknown> | null;
24
+ stateCommitHash?: string | null;
25
+ finalized?: number | boolean | null;
26
+ }
27
+ interface ITxIndexBackfillUpdate {
28
+ hash: string;
29
+ prevSender: string;
30
+ nextSender: string;
31
+ prevGasPayer: string;
32
+ nextGasPayer: string;
33
+ nextTxJson: string;
34
+ nextAccountsJson: string;
35
+ addedAccountRefs: string[];
36
+ time: string;
37
+ }
38
+ interface ITxIndexBackfillInsert {
39
+ hash: string;
40
+ type: string;
41
+ code: string;
42
+ valid: number;
43
+ time: string;
44
+ sender: string;
45
+ receiver: string;
46
+ gasPayer: string;
47
+ txJson: string;
48
+ receiptsJson: string;
49
+ tokenSymbolsJson: string;
50
+ accountsJson: string;
51
+ accountRefs: string[];
52
+ }
53
+ interface ITxIndexBackfillPlan {
54
+ requiresGasPayerColumn: boolean;
55
+ updates: ITxIndexBackfillUpdate[];
56
+ inserts: ITxIndexBackfillInsert[];
57
+ summary: {
58
+ scannedTxRows: number;
59
+ scannedLedgerRows: number;
60
+ updateCount: number;
61
+ insertCount: number;
62
+ };
63
+ planDigest: string;
64
+ }
65
+ interface ISqliteStatementLike {
66
+ all?: (...params: unknown[]) => unknown[];
67
+ run?: (...params: unknown[]) => unknown;
68
+ }
69
+ interface ISqliteDatabaseLike {
70
+ prepare(sql: string): ISqliteStatementLike;
71
+ exec(sql: string): unknown;
72
+ }
73
+ /**
74
+ * Compute deterministic SHA-256 digest of a backfill plan's canonical payload
75
+ */
76
+ declare function computeBackfillPlanDigest(plan: {
77
+ requiresGasPayerColumn: boolean;
78
+ updates: ITxIndexBackfillUpdate[];
79
+ inserts: ITxIndexBackfillInsert[];
80
+ }): string;
81
+ /**
82
+ * Pure deterministic planner for Issue #1362 historical tx index backfill
83
+ */
84
+ declare function buildTxIndexBackfillPlan(params: {
85
+ txRows: ITxIndexRowSnapshot[];
86
+ ledgerRows?: ILedgerEntrySnapshot[];
87
+ hasGasPayerColumn?: boolean;
88
+ }): ITxIndexBackfillPlan;
89
+ /**
90
+ * Read-only SQLite inspection & backfill plan builder (zero writes)
91
+ */
92
+ declare function planTxIndexBackfill(params: {
93
+ indexDb: ISqliteDatabaseLike;
94
+ ledgerDb?: ISqliteDatabaseLike | null;
95
+ }): ITxIndexBackfillPlan;
96
+ /**
97
+ * Digest-guarded atomic apply of a previously generated backfill plan
98
+ */
99
+ declare function applyTxIndexBackfill(params: {
100
+ indexDb: ISqliteDatabaseLike;
101
+ plan: ITxIndexBackfillPlan;
102
+ expectedPlanDigest: string;
103
+ }): {
104
+ updatedRows: number;
105
+ insertedRows: number;
106
+ planDigest: string;
107
+ };
108
+ //#endregion
109
+ export { ILedgerEntrySnapshot, ISqliteDatabaseLike, ISqliteStatementLike, ITxIndexBackfillInsert, ITxIndexBackfillPlan, ITxIndexBackfillUpdate, ITxIndexRowSnapshot, applyTxIndexBackfill, buildTxIndexBackfillPlan, computeBackfillPlanDigest, planTxIndexBackfill };
package/lib/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
3
- let _ocap_util_lib_ready = require("@ocap/util/lib/ready");
4
3
  let node_crypto = require("node:crypto");
5
4
  node_crypto = require_rolldown_runtime.__toESM(node_crypto);
5
+ let _ocap_util_lib_ready = require("@ocap/util/lib/ready");
6
6
  let kareem = require("kareem");
7
7
  kareem = require_rolldown_runtime.__toESM(kareem);
8
8
  let lodash_omit = require("lodash/omit");
package/lib/main.cjs CHANGED
@@ -1,4 +1,5 @@
1
1
  const require_util = require('./util.cjs');
2
+ const require_backfill = require('./backfill.cjs');
2
3
  const require_rebuild = require('./rebuild.cjs');
3
4
  const require_db = require('./db.cjs');
4
5
  const require_index = require('./index.cjs');
@@ -6,7 +7,10 @@ const require_search_result = require('./search-result.cjs');
6
7
 
7
8
  exports.BaseIndex = require_index.default;
8
9
  exports.BaseIndexDB = require_db.default;
10
+ exports.applyTxIndexBackfill = require_backfill.applyTxIndexBackfill;
11
+ exports.buildTxIndexBackfillPlan = require_backfill.buildTxIndexBackfillPlan;
9
12
  exports.clearIndexDB = require_rebuild.clearIndexDB;
13
+ exports.computeBackfillPlanDigest = require_backfill.computeBackfillPlanDigest;
10
14
  exports.createIndexedAccount = require_util.createIndexedAccount;
11
15
  exports.createIndexedAsset = require_util.createIndexedAsset;
12
16
  exports.createIndexedDelegation = require_util.createIndexedDelegation;
@@ -18,6 +22,8 @@ exports.createIndexedToken = require_util.createIndexedToken;
18
22
  exports.createIndexedTokenDistribution = require_util.createIndexedTokenDistribution;
19
23
  exports.createIndexedTokenFactory = require_util.createIndexedTokenFactory;
20
24
  exports.createIndexedTransaction = require_util.createIndexedTransaction;
25
+ exports.deriveTxGasPayer = require_util.deriveTxGasPayer;
26
+ exports.deriveTxSender = require_util.deriveTxSender;
21
27
  exports.formatDelegationAfterRead = require_util.formatDelegationAfterRead;
22
28
  exports.formatNextPagination = require_util.formatNextPagination;
23
29
  exports.formatPagination = require_util.formatPagination;
@@ -25,7 +31,9 @@ exports.formatSearchResult = require_search_result.formatSearchResult;
25
31
  exports.formatTokenMeta = require_util.formatTokenMeta;
26
32
  exports.formatTxAfterRead = require_util.formatTxAfterRead;
27
33
  exports.formatTxBeforeInsert = require_util.formatTxBeforeInsert;
34
+ exports.getBridgeReleaseEvidenceKey = require_util.getBridgeReleaseEvidenceKey;
28
35
  exports.isDefaultTokenChanged = require_util.isDefaultTokenChanged;
29
36
  exports.parseDateTime = require_util.parseDateTime;
37
+ exports.planTxIndexBackfill = require_backfill.planTxIndexBackfill;
30
38
  exports.rebuildIndexFromState = require_rebuild.rebuildIndexFromState;
31
39
  exports.scanStateTable = require_rebuild.scanStateTable;
package/lib/main.d.cts CHANGED
@@ -1,6 +1,7 @@
1
+ import { ILedgerEntrySnapshot, ISqliteDatabaseLike, ISqliteStatementLike, ITxIndexBackfillInsert, ITxIndexBackfillPlan, ITxIndexBackfillUpdate, ITxIndexRowSnapshot, applyTxIndexBackfill, buildTxIndexBackfillPlan, computeBackfillPlanDigest, planTxIndexBackfill } from "./backfill.cjs";
1
2
  import BaseIndexDB from "./db.cjs";
2
3
  import BaseIndex from "./index.cjs";
3
4
  import { SearchResultFormatOptions, formatSearchResult } from "./search-result.cjs";
4
- import { 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 } from "./util.cjs";
5
+ import { BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime } from "./util.cjs";
5
6
  import { clearIndexDB, rebuildIndexFromState, scanStateTable } from "./rebuild.cjs";
6
- export { BaseIndex, BaseIndexDB, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, clearIndexDB, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime, rebuildIndexFromState, scanStateTable };
7
+ export { BaseIndex, BaseIndexDB, BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, ILedgerEntrySnapshot, ISqliteDatabaseLike, ISqliteStatementLike, ITxIndexBackfillInsert, ITxIndexBackfillPlan, ITxIndexBackfillUpdate, ITxIndexRowSnapshot, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, applyTxIndexBackfill, buildTxIndexBackfillPlan, clearIndexDB, computeBackfillPlanDigest, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime, planTxIndexBackfill, rebuildIndexFromState, scanStateTable };
package/lib/util.cjs CHANGED
@@ -1,12 +1,12 @@
1
1
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let lodash_uniq = require("lodash/uniq");
3
+ lodash_uniq = require_rolldown_runtime.__toESM(lodash_uniq);
2
4
  let _ocap_util = require("@ocap/util");
3
5
  let _ocap_util_lib_create_sorted_list = require("@ocap/util/lib/create-sorted-list");
4
6
  let lodash_get = require("lodash/get");
5
7
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
6
8
  let lodash_pick = require("lodash/pick");
7
9
  lodash_pick = require_rolldown_runtime.__toESM(lodash_pick);
8
- let lodash_uniq = require("lodash/uniq");
9
- lodash_uniq = require_rolldown_runtime.__toESM(lodash_uniq);
10
10
  let lodash_uniqBy = require("lodash/uniqBy");
11
11
  lodash_uniqBy = require_rolldown_runtime.__toESM(lodash_uniqBy);
12
12
 
@@ -179,13 +179,80 @@ const createIndexedFactory = (factory, context) => {
179
179
  renaissanceTime: factory.context.renaissanceTime
180
180
  };
181
181
  };
182
+ /** Rejected-but-ledgered index rows (#1362) have no statedb tx and therefore no getTxSender value. */
183
+ const isRejectedIndexRow = (tx) => {
184
+ const valid = tx?.valid;
185
+ return valid === false || valid === 0;
186
+ };
187
+ /**
188
+ * Evidence lookup key of a release_bridge_token tx: `<bridge>:<kind>:<evidence lowercased>:<ordinal>`
189
+ * (kind and ordinal as decimal strings, bridge as given, trimmed: OCAP addresses are case-sensitive).
190
+ * Returns null unless bridge is a non-empty string without ':' or whitespace, kind is 1, 2 or 3, ordinal is a
191
+ * non-negative integer and evidence is a 0x-prefixed 32-byte hex string (after trim + lowercase).
192
+ * The key was `<kind>:<evidence>:<ordinal>` in the single-reserve model (#1479). The index is new and unused in
193
+ * production, so rows written with the old key are simply not found under the new one (no migration).
194
+ * Pass the same key in `txFilter.evidences` of listTransactions to find the release tx.
195
+ */
196
+ const getBridgeReleaseEvidenceKey = (itx) => {
197
+ const bridge = typeof itx?.bridge === "string" ? itx.bridge.trim() : "";
198
+ if (!bridge || /[:\s]/.test(bridge)) return null;
199
+ const evidence = typeof itx?.evidence === "string" ? itx.evidence.trim().toLowerCase() : "";
200
+ if (!/^0x[0-9a-f]{64}$/.test(evidence)) return null;
201
+ const kind = Number(itx?.kind);
202
+ const ordinal = Number(itx?.ordinal ?? 0);
203
+ if (![
204
+ 1,
205
+ 2,
206
+ 3
207
+ ].includes(kind) || !Number.isInteger(ordinal) || ordinal < 0) return null;
208
+ return `${bridge}:${kind}:${evidence}:${ordinal}`;
209
+ };
210
+ /**
211
+ * Derive the signer-based sender. Only for rows that never got a getTxSender value (rejected-but-ledgered
212
+ * txs); normal rows keep getTxSender semantics ("whose asset has net loss", may be empty).
213
+ */
214
+ const deriveTxSender = (tx, ctx) => {
215
+ if (!tx) return "";
216
+ if (typeof tx.sender === "string" && tx.sender) return tx.sender;
217
+ const innerTx = tx.tx;
218
+ const firstInputOwner = (innerTx?.itxJson?.inputs?.[0])?.owner;
219
+ return innerTx?.from || innerTx?.delegator || firstInputOwner || ctx?.senderState?.address || "";
220
+ };
221
+ /**
222
+ * Derive transaction gas payer / sponsor address
223
+ */
224
+ const deriveTxGasPayer = (tx, ctx) => {
225
+ if (!tx && !ctx) return "";
226
+ const innerTx = tx?.tx;
227
+ const explicitGasPayer = tx?.gasPayer || innerTx?.gasPayer;
228
+ if (typeof explicitGasPayer === "string" && explicitGasPayer) return explicitGasPayer;
229
+ if (Array.isArray(tx?.receipts)) for (const receipt of tx.receipts) {
230
+ if (!Array.isArray(receipt?.changes)) continue;
231
+ for (const change of receipt.changes) if (change?.action === "gas" && String(change.value || "").startsWith("-")) {
232
+ if (typeof receipt.address === "string" && receipt.address) return receipt.address;
233
+ const parts = String(change.target || "").split(".");
234
+ if (parts[0] === "account" && parts[1]) return parts[1];
235
+ }
236
+ }
237
+ const typedCtx = ctx;
238
+ const gasStake = typedCtx?.gasStake;
239
+ const sponsorState = typedCtx?.sponsorState;
240
+ const isFailedPaymaster = Boolean(typedCtx?.isFailedTxGasCharge) || tx?.valid === false || Boolean(tx?.code) && tx?.code !== "OK";
241
+ if (gasStake?.valid === true && gasStake.sponsorAddress) return gasStake.sponsorAddress;
242
+ if (!isFailedPaymaster && sponsorState?.address) return sponsorState.address;
243
+ if (gasStake?.valid === true && gasStake.owner) return gasStake.owner;
244
+ return "";
245
+ };
182
246
  /**
183
247
  * Create indexed transaction from transaction context
184
248
  * These fields are used internally to filter transactions by some entity
185
249
  */
186
250
  const createIndexedTransaction = async (tx, ctx, indexdb) => {
251
+ if (isRejectedIndexRow(tx)) tx.sender = deriveTxSender(tx, ctx);
252
+ tx.gasPayer = deriveTxGasPayer(tx, ctx);
253
+ if (tx.gasPayer && tx.tx && typeof tx.tx === "object") tx.tx.gasPayer = tx.tx.gasPayer || tx.gasPayer;
187
254
  tx.accounts = [
188
- tx.tx.from,
255
+ tx.tx?.from,
189
256
  tx.sender,
190
257
  tx.receiver
191
258
  ].filter(Boolean);
@@ -391,7 +458,11 @@ const formatTxBeforeInsert = (row) => {
391
458
  const tx = { ...row };
392
459
  tx.sender = tx.sender || "";
393
460
  tx.receiver = tx.receiver || "";
461
+ tx.gasPayer = tx.gasPayer || "";
394
462
  if (!tx.tx || !tx.tx.itxJson) return tx;
463
+ if (isRejectedIndexRow(tx)) tx.sender = deriveTxSender(tx);
464
+ tx.gasPayer = deriveTxGasPayer(tx);
465
+ if (tx.gasPayer) tx.tx.gasPayer = tx.tx.gasPayer || tx.gasPayer;
395
466
  const itx = tx.tx.itxJson;
396
467
  tx.assets = tx.assets || [];
397
468
  if (["transfer", "transfer_v2"].includes(tx.type || "") && itx.assets) tx.assets.push(...itx.assets);
@@ -426,6 +497,13 @@ const formatTxBeforeInsert = (row) => {
426
497
  else if (tx.type === "exchange_v2") tx.tokens.push(...(itx.sender?.tokens || []).map((x) => x.address), ...(itx.receiver?.tokens || []).map((x) => x.address));
427
498
  tx.accounts = tx.accounts || [];
428
499
  tx.stakes = tx.stakes || [];
500
+ tx.evidences = tx.evidences || [];
501
+ const isValidRow = tx.valid === true || tx.valid === 1;
502
+ if (tx.type === "release_bridge_token" && isValidRow && !isRejectedIndexRow(tx)) {
503
+ const evidenceKey = getBridgeReleaseEvidenceKey(itx);
504
+ if (evidenceKey) tx.evidences.push(evidenceKey);
505
+ }
506
+ tx.evidences = (0, lodash_uniq.default)(tx.evidences).filter(Boolean);
429
507
  tx.assets = (0, lodash_uniq.default)(tx.assets).filter(Boolean);
430
508
  tx.factories = (0, lodash_uniq.default)(tx.factories).filter(Boolean);
431
509
  tx.tokens = (0, lodash_uniq.default)(tx.tokens).filter(Boolean);
@@ -446,6 +524,7 @@ const formatTxAfterRead = (tx) => {
446
524
  delete tx.stakes;
447
525
  delete tx.rollups;
448
526
  delete tx.delegations;
527
+ delete tx.evidences;
449
528
  return tx;
450
529
  };
451
530
  /**
@@ -519,7 +598,8 @@ const formatNextPagination = (total, pagination) => {
519
598
  * Check if a transaction changes the default token balance
520
599
  */
521
600
  const isDefaultTokenChanged = (tx, token) => {
522
- const itx = tx.tx.itxJson;
601
+ const itx = tx?.tx?.itxJson;
602
+ if (!itx) return false;
523
603
  if ([
524
604
  "fg:t:transfer",
525
605
  "fg:t:transfer_v2",
@@ -539,7 +619,13 @@ const isDefaultTokenChanged = (tx, token) => {
539
619
  ].includes(itx.type_url || "") === false) return false;
540
620
  const ZERO = new _ocap_util.BN(0);
541
621
  const isDefaultToken = (id) => [token.address, ""].includes(id);
542
- const isPositive = (v) => new _ocap_util.BN(v || 0).gt(ZERO);
622
+ const isPositive = (v) => {
623
+ try {
624
+ return new _ocap_util.BN(v || 0).gt(ZERO);
625
+ } catch {
626
+ return false;
627
+ }
628
+ };
543
629
  const isChangedByInput = (input) => isPositive(input.value) || (input.tokens?.some((x) => isDefaultToken(x.address) && isPositive(x.value)) ?? false);
544
630
  switch (itx.type_url) {
545
631
  case "fg:t:transfer": return isPositive(itx.value);
@@ -575,11 +661,14 @@ exports.createIndexedToken = createIndexedToken;
575
661
  exports.createIndexedTokenDistribution = createIndexedTokenDistribution;
576
662
  exports.createIndexedTokenFactory = createIndexedTokenFactory;
577
663
  exports.createIndexedTransaction = createIndexedTransaction;
664
+ exports.deriveTxGasPayer = deriveTxGasPayer;
665
+ exports.deriveTxSender = deriveTxSender;
578
666
  exports.formatDelegationAfterRead = formatDelegationAfterRead;
579
667
  exports.formatNextPagination = formatNextPagination;
580
668
  exports.formatPagination = formatPagination;
581
669
  exports.formatTokenMeta = formatTokenMeta;
582
670
  exports.formatTxAfterRead = formatTxAfterRead;
583
671
  exports.formatTxBeforeInsert = formatTxBeforeInsert;
672
+ exports.getBridgeReleaseEvidenceKey = getBridgeReleaseEvidenceKey;
584
673
  exports.isDefaultTokenChanged = isDefaultTokenChanged;
585
674
  exports.parseDateTime = parseDateTime;
package/lib/util.d.cts CHANGED
@@ -89,6 +89,8 @@ interface ItxJson {
89
89
  /** Decoded transaction structure */
90
90
  interface DecodedTx {
91
91
  from: string;
92
+ delegator?: string;
93
+ gasPayer?: string;
92
94
  itxJson: ItxJson;
93
95
  [key: string]: unknown;
94
96
  }
@@ -99,12 +101,15 @@ interface TxData {
99
101
  code?: string;
100
102
  sender?: string;
101
103
  receiver?: string;
104
+ gasPayer?: string;
102
105
  time?: string;
103
106
  valid?: boolean;
104
107
  tx: DecodedTx;
105
108
  receipts?: Array<{
109
+ address?: string;
106
110
  changes: Array<{
107
111
  target: string;
112
+ action?: string;
108
113
  value: string;
109
114
  }>;
110
115
  }>;
@@ -116,6 +121,7 @@ interface TxData {
116
121
  rollups?: string[];
117
122
  delegations?: string[];
118
123
  tokenFactories?: string[];
124
+ evidences?: string[];
119
125
  tokenSymbols?: Array<Partial<TTokenMeta>>;
120
126
  [key: string]: unknown;
121
127
  }
@@ -230,6 +236,33 @@ declare const createIndexedFactory: (factory: IAssetFactoryState & {
230
236
  }, context: FactoryContext) => Record<string, unknown> & {
231
237
  tokens: TokenWithBalance[];
232
238
  };
239
+ /** Fields of a release_bridge_token itx that identify the deposit or withdraw being settled */
240
+ interface BridgeReleaseEvidenceInput {
241
+ /** OCAP bridge (RollupState address) the release belongs to (bridge/docs/ocap-protocols.md §v2.4) */
242
+ bridge?: string;
243
+ kind?: number | string;
244
+ evidence?: string;
245
+ ordinal?: number | string;
246
+ }
247
+ /**
248
+ * Evidence lookup key of a release_bridge_token tx: `<bridge>:<kind>:<evidence lowercased>:<ordinal>`
249
+ * (kind and ordinal as decimal strings, bridge as given, trimmed: OCAP addresses are case-sensitive).
250
+ * Returns null unless bridge is a non-empty string without ':' or whitespace, kind is 1, 2 or 3, ordinal is a
251
+ * non-negative integer and evidence is a 0x-prefixed 32-byte hex string (after trim + lowercase).
252
+ * The key was `<kind>:<evidence>:<ordinal>` in the single-reserve model (#1479). The index is new and unused in
253
+ * production, so rows written with the old key are simply not found under the new one (no migration).
254
+ * Pass the same key in `txFilter.evidences` of listTransactions to find the release tx.
255
+ */
256
+ declare const getBridgeReleaseEvidenceKey: (itx?: BridgeReleaseEvidenceInput | null) => string | null;
257
+ /**
258
+ * Derive the signer-based sender. Only for rows that never got a getTxSender value (rejected-but-ledgered
259
+ * txs); normal rows keep getTxSender semantics ("whose asset has net loss", may be empty).
260
+ */
261
+ declare const deriveTxSender: (tx?: Partial<TxData> | null, ctx?: Partial<FinalizedContext> | null) => string;
262
+ /**
263
+ * Derive transaction gas payer / sponsor address
264
+ */
265
+ declare const deriveTxGasPayer: (tx?: Partial<TxData> | null, ctx?: Partial<FinalizedContext> | null) => string;
233
266
  /**
234
267
  * Create indexed transaction from transaction context
235
268
  * These fields are used internally to filter transactions by some entity
@@ -371,4 +404,4 @@ declare const isDefaultTokenChanged: (tx: TxData, token: {
371
404
  address: string;
372
405
  }) => boolean;
373
406
  //#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 };
407
+ export { BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.31.0",
6
+ "version": "1.31.2",
7
7
  "type": "module",
8
8
  "description": "Defines the basic interface for OCAP IndexDB",
9
9
  "main": "./lib/main.cjs",
@@ -52,9 +52,9 @@
52
52
  "tsdown": "^0.18.4"
53
53
  },
54
54
  "dependencies": {
55
- "@ocap/state": "1.31.0",
56
- "@ocap/types": "1.31.0",
57
- "@ocap/util": "1.31.0",
55
+ "@ocap/state": "1.31.2",
56
+ "@ocap/types": "1.31.2",
57
+ "@ocap/util": "1.31.2",
58
58
  "kareem": "^2.4.1",
59
59
  "lodash": "^4.17.23"
60
60
  }