@ocap/indexdb 1.30.26 → 1.31.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/backfill.d.mts +109 -0
- package/esm/backfill.mjs +252 -0
- package/esm/index.mjs +1 -1
- package/esm/main.d.mts +3 -2
- package/esm/main.mjs +3 -2
- package/esm/util.d.mts +15 -1
- package/esm/util.mjs +60 -5
- package/lib/backfill.cjs +258 -0
- package/lib/backfill.d.cts +109 -0
- package/lib/index.cjs +1 -1
- package/lib/main.cjs +7 -0
- package/lib/main.d.cts +3 -2
- package/lib/util.cjs +62 -5
- package/lib/util.d.cts +15 -1
- package/package.json +4 -4
|
@@ -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/esm/backfill.mjs
ADDED
|
@@ -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
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 { 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, 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, 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, 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, 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, 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
|
}>;
|
|
@@ -230,6 +235,15 @@ declare const createIndexedFactory: (factory: IAssetFactoryState & {
|
|
|
230
235
|
}, context: FactoryContext) => Record<string, unknown> & {
|
|
231
236
|
tokens: TokenWithBalance[];
|
|
232
237
|
};
|
|
238
|
+
/**
|
|
239
|
+
* Derive the signer-based sender. Only for rows that never got a getTxSender value (rejected-but-ledgered
|
|
240
|
+
* txs); normal rows keep getTxSender semantics ("whose asset has net loss", may be empty).
|
|
241
|
+
*/
|
|
242
|
+
declare const deriveTxSender: (tx?: Partial<TxData> | null, ctx?: Partial<FinalizedContext> | null) => string;
|
|
243
|
+
/**
|
|
244
|
+
* Derive transaction gas payer / sponsor address
|
|
245
|
+
*/
|
|
246
|
+
declare const deriveTxGasPayer: (tx?: Partial<TxData> | null, ctx?: Partial<FinalizedContext> | null) => string;
|
|
233
247
|
/**
|
|
234
248
|
* Create indexed transaction from transaction context
|
|
235
249
|
* These fields are used internally to filter transactions by some entity
|
|
@@ -371,4 +385,4 @@ declare const isDefaultTokenChanged: (tx: TxData, token: {
|
|
|
371
385
|
address: string;
|
|
372
386
|
}) => boolean;
|
|
373
387
|
//#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 };
|
|
388
|
+
export { 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, 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,57 @@ 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
|
+
* Derive the signer-based sender. Only for rows that never got a getTxSender value (rejected-but-ledgered
|
|
184
|
+
* txs); normal rows keep getTxSender semantics ("whose asset has net loss", may be empty).
|
|
185
|
+
*/
|
|
186
|
+
const deriveTxSender = (tx, ctx) => {
|
|
187
|
+
if (!tx) return "";
|
|
188
|
+
if (typeof tx.sender === "string" && tx.sender) return tx.sender;
|
|
189
|
+
const innerTx = tx.tx;
|
|
190
|
+
const firstInputOwner = (innerTx?.itxJson?.inputs?.[0])?.owner;
|
|
191
|
+
return innerTx?.from || innerTx?.delegator || firstInputOwner || ctx?.senderState?.address || "";
|
|
192
|
+
};
|
|
193
|
+
/**
|
|
194
|
+
* Derive transaction gas payer / sponsor address
|
|
195
|
+
*/
|
|
196
|
+
const deriveTxGasPayer = (tx, ctx) => {
|
|
197
|
+
if (!tx && !ctx) return "";
|
|
198
|
+
const innerTx = tx?.tx;
|
|
199
|
+
const explicitGasPayer = tx?.gasPayer || innerTx?.gasPayer;
|
|
200
|
+
if (typeof explicitGasPayer === "string" && explicitGasPayer) return explicitGasPayer;
|
|
201
|
+
if (Array.isArray(tx?.receipts)) for (const receipt of tx.receipts) {
|
|
202
|
+
if (!Array.isArray(receipt?.changes)) continue;
|
|
203
|
+
for (const change of receipt.changes) if (change?.action === "gas" && String(change.value || "").startsWith("-")) {
|
|
204
|
+
if (typeof receipt.address === "string" && receipt.address) return receipt.address;
|
|
205
|
+
const parts = String(change.target || "").split(".");
|
|
206
|
+
if (parts[0] === "account" && parts[1]) return parts[1];
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const typedCtx = ctx;
|
|
210
|
+
const gasStake = typedCtx?.gasStake;
|
|
211
|
+
const sponsorState = typedCtx?.sponsorState;
|
|
212
|
+
const isFailedPaymaster = Boolean(typedCtx?.isFailedTxGasCharge) || tx?.valid === false || Boolean(tx?.code) && tx?.code !== "OK";
|
|
213
|
+
if (gasStake?.valid === true && gasStake.sponsorAddress) return gasStake.sponsorAddress;
|
|
214
|
+
if (!isFailedPaymaster && sponsorState?.address) return sponsorState.address;
|
|
215
|
+
if (gasStake?.valid === true && gasStake.owner) return gasStake.owner;
|
|
216
|
+
return "";
|
|
217
|
+
};
|
|
177
218
|
/**
|
|
178
219
|
* Create indexed transaction from transaction context
|
|
179
220
|
* These fields are used internally to filter transactions by some entity
|
|
180
221
|
*/
|
|
181
222
|
const createIndexedTransaction = async (tx, ctx, indexdb) => {
|
|
223
|
+
if (isRejectedIndexRow(tx)) tx.sender = deriveTxSender(tx, ctx);
|
|
224
|
+
tx.gasPayer = deriveTxGasPayer(tx, ctx);
|
|
225
|
+
if (tx.gasPayer && tx.tx && typeof tx.tx === "object") tx.tx.gasPayer = tx.tx.gasPayer || tx.gasPayer;
|
|
182
226
|
tx.accounts = [
|
|
183
|
-
tx.tx
|
|
227
|
+
tx.tx?.from,
|
|
184
228
|
tx.sender,
|
|
185
229
|
tx.receiver
|
|
186
230
|
].filter(Boolean);
|
|
@@ -386,7 +430,11 @@ const formatTxBeforeInsert = (row) => {
|
|
|
386
430
|
const tx = { ...row };
|
|
387
431
|
tx.sender = tx.sender || "";
|
|
388
432
|
tx.receiver = tx.receiver || "";
|
|
433
|
+
tx.gasPayer = tx.gasPayer || "";
|
|
389
434
|
if (!tx.tx || !tx.tx.itxJson) return tx;
|
|
435
|
+
if (isRejectedIndexRow(tx)) tx.sender = deriveTxSender(tx);
|
|
436
|
+
tx.gasPayer = deriveTxGasPayer(tx);
|
|
437
|
+
if (tx.gasPayer) tx.tx.gasPayer = tx.tx.gasPayer || tx.gasPayer;
|
|
390
438
|
const itx = tx.tx.itxJson;
|
|
391
439
|
tx.assets = tx.assets || [];
|
|
392
440
|
if (["transfer", "transfer_v2"].includes(tx.type || "") && itx.assets) tx.assets.push(...itx.assets);
|
|
@@ -514,7 +562,8 @@ const formatNextPagination = (total, pagination) => {
|
|
|
514
562
|
* Check if a transaction changes the default token balance
|
|
515
563
|
*/
|
|
516
564
|
const isDefaultTokenChanged = (tx, token) => {
|
|
517
|
-
const itx = tx
|
|
565
|
+
const itx = tx?.tx?.itxJson;
|
|
566
|
+
if (!itx) return false;
|
|
518
567
|
if ([
|
|
519
568
|
"fg:t:transfer",
|
|
520
569
|
"fg:t:transfer_v2",
|
|
@@ -534,7 +583,13 @@ const isDefaultTokenChanged = (tx, token) => {
|
|
|
534
583
|
].includes(itx.type_url || "") === false) return false;
|
|
535
584
|
const ZERO = new BN(0);
|
|
536
585
|
const isDefaultToken = (id) => [token.address, ""].includes(id);
|
|
537
|
-
const isPositive = (v) =>
|
|
586
|
+
const isPositive = (v) => {
|
|
587
|
+
try {
|
|
588
|
+
return new BN(v || 0).gt(ZERO);
|
|
589
|
+
} catch {
|
|
590
|
+
return false;
|
|
591
|
+
}
|
|
592
|
+
};
|
|
538
593
|
const isChangedByInput = (input) => isPositive(input.value) || (input.tokens?.some((x) => isDefaultToken(x.address) && isPositive(x.value)) ?? false);
|
|
539
594
|
switch (itx.type_url) {
|
|
540
595
|
case "fg:t:transfer": return isPositive(itx.value);
|
|
@@ -559,4 +614,4 @@ const isDefaultTokenChanged = (tx, token) => {
|
|
|
559
614
|
};
|
|
560
615
|
|
|
561
616
|
//#endregion
|
|
562
|
-
export { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime };
|
|
617
|
+
export { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime };
|
package/lib/backfill.cjs
ADDED
|
@@ -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;
|
|
@@ -27,5 +33,6 @@ exports.formatTxAfterRead = require_util.formatTxAfterRead;
|
|
|
27
33
|
exports.formatTxBeforeInsert = require_util.formatTxBeforeInsert;
|
|
28
34
|
exports.isDefaultTokenChanged = require_util.isDefaultTokenChanged;
|
|
29
35
|
exports.parseDateTime = require_util.parseDateTime;
|
|
36
|
+
exports.planTxIndexBackfill = require_backfill.planTxIndexBackfill;
|
|
30
37
|
exports.rebuildIndexFromState = require_rebuild.rebuildIndexFromState;
|
|
31
38
|
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 { 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, 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, 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, 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,57 @@ 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
|
+
* Derive the signer-based sender. Only for rows that never got a getTxSender value (rejected-but-ledgered
|
|
189
|
+
* txs); normal rows keep getTxSender semantics ("whose asset has net loss", may be empty).
|
|
190
|
+
*/
|
|
191
|
+
const deriveTxSender = (tx, ctx) => {
|
|
192
|
+
if (!tx) return "";
|
|
193
|
+
if (typeof tx.sender === "string" && tx.sender) return tx.sender;
|
|
194
|
+
const innerTx = tx.tx;
|
|
195
|
+
const firstInputOwner = (innerTx?.itxJson?.inputs?.[0])?.owner;
|
|
196
|
+
return innerTx?.from || innerTx?.delegator || firstInputOwner || ctx?.senderState?.address || "";
|
|
197
|
+
};
|
|
198
|
+
/**
|
|
199
|
+
* Derive transaction gas payer / sponsor address
|
|
200
|
+
*/
|
|
201
|
+
const deriveTxGasPayer = (tx, ctx) => {
|
|
202
|
+
if (!tx && !ctx) return "";
|
|
203
|
+
const innerTx = tx?.tx;
|
|
204
|
+
const explicitGasPayer = tx?.gasPayer || innerTx?.gasPayer;
|
|
205
|
+
if (typeof explicitGasPayer === "string" && explicitGasPayer) return explicitGasPayer;
|
|
206
|
+
if (Array.isArray(tx?.receipts)) for (const receipt of tx.receipts) {
|
|
207
|
+
if (!Array.isArray(receipt?.changes)) continue;
|
|
208
|
+
for (const change of receipt.changes) if (change?.action === "gas" && String(change.value || "").startsWith("-")) {
|
|
209
|
+
if (typeof receipt.address === "string" && receipt.address) return receipt.address;
|
|
210
|
+
const parts = String(change.target || "").split(".");
|
|
211
|
+
if (parts[0] === "account" && parts[1]) return parts[1];
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const typedCtx = ctx;
|
|
215
|
+
const gasStake = typedCtx?.gasStake;
|
|
216
|
+
const sponsorState = typedCtx?.sponsorState;
|
|
217
|
+
const isFailedPaymaster = Boolean(typedCtx?.isFailedTxGasCharge) || tx?.valid === false || Boolean(tx?.code) && tx?.code !== "OK";
|
|
218
|
+
if (gasStake?.valid === true && gasStake.sponsorAddress) return gasStake.sponsorAddress;
|
|
219
|
+
if (!isFailedPaymaster && sponsorState?.address) return sponsorState.address;
|
|
220
|
+
if (gasStake?.valid === true && gasStake.owner) return gasStake.owner;
|
|
221
|
+
return "";
|
|
222
|
+
};
|
|
182
223
|
/**
|
|
183
224
|
* Create indexed transaction from transaction context
|
|
184
225
|
* These fields are used internally to filter transactions by some entity
|
|
185
226
|
*/
|
|
186
227
|
const createIndexedTransaction = async (tx, ctx, indexdb) => {
|
|
228
|
+
if (isRejectedIndexRow(tx)) tx.sender = deriveTxSender(tx, ctx);
|
|
229
|
+
tx.gasPayer = deriveTxGasPayer(tx, ctx);
|
|
230
|
+
if (tx.gasPayer && tx.tx && typeof tx.tx === "object") tx.tx.gasPayer = tx.tx.gasPayer || tx.gasPayer;
|
|
187
231
|
tx.accounts = [
|
|
188
|
-
tx.tx
|
|
232
|
+
tx.tx?.from,
|
|
189
233
|
tx.sender,
|
|
190
234
|
tx.receiver
|
|
191
235
|
].filter(Boolean);
|
|
@@ -391,7 +435,11 @@ const formatTxBeforeInsert = (row) => {
|
|
|
391
435
|
const tx = { ...row };
|
|
392
436
|
tx.sender = tx.sender || "";
|
|
393
437
|
tx.receiver = tx.receiver || "";
|
|
438
|
+
tx.gasPayer = tx.gasPayer || "";
|
|
394
439
|
if (!tx.tx || !tx.tx.itxJson) return tx;
|
|
440
|
+
if (isRejectedIndexRow(tx)) tx.sender = deriveTxSender(tx);
|
|
441
|
+
tx.gasPayer = deriveTxGasPayer(tx);
|
|
442
|
+
if (tx.gasPayer) tx.tx.gasPayer = tx.tx.gasPayer || tx.gasPayer;
|
|
395
443
|
const itx = tx.tx.itxJson;
|
|
396
444
|
tx.assets = tx.assets || [];
|
|
397
445
|
if (["transfer", "transfer_v2"].includes(tx.type || "") && itx.assets) tx.assets.push(...itx.assets);
|
|
@@ -519,7 +567,8 @@ const formatNextPagination = (total, pagination) => {
|
|
|
519
567
|
* Check if a transaction changes the default token balance
|
|
520
568
|
*/
|
|
521
569
|
const isDefaultTokenChanged = (tx, token) => {
|
|
522
|
-
const itx = tx
|
|
570
|
+
const itx = tx?.tx?.itxJson;
|
|
571
|
+
if (!itx) return false;
|
|
523
572
|
if ([
|
|
524
573
|
"fg:t:transfer",
|
|
525
574
|
"fg:t:transfer_v2",
|
|
@@ -539,7 +588,13 @@ const isDefaultTokenChanged = (tx, token) => {
|
|
|
539
588
|
].includes(itx.type_url || "") === false) return false;
|
|
540
589
|
const ZERO = new _ocap_util.BN(0);
|
|
541
590
|
const isDefaultToken = (id) => [token.address, ""].includes(id);
|
|
542
|
-
const isPositive = (v) =>
|
|
591
|
+
const isPositive = (v) => {
|
|
592
|
+
try {
|
|
593
|
+
return new _ocap_util.BN(v || 0).gt(ZERO);
|
|
594
|
+
} catch {
|
|
595
|
+
return false;
|
|
596
|
+
}
|
|
597
|
+
};
|
|
543
598
|
const isChangedByInput = (input) => isPositive(input.value) || (input.tokens?.some((x) => isDefaultToken(x.address) && isPositive(x.value)) ?? false);
|
|
544
599
|
switch (itx.type_url) {
|
|
545
600
|
case "fg:t:transfer": return isPositive(itx.value);
|
|
@@ -575,6 +630,8 @@ exports.createIndexedToken = createIndexedToken;
|
|
|
575
630
|
exports.createIndexedTokenDistribution = createIndexedTokenDistribution;
|
|
576
631
|
exports.createIndexedTokenFactory = createIndexedTokenFactory;
|
|
577
632
|
exports.createIndexedTransaction = createIndexedTransaction;
|
|
633
|
+
exports.deriveTxGasPayer = deriveTxGasPayer;
|
|
634
|
+
exports.deriveTxSender = deriveTxSender;
|
|
578
635
|
exports.formatDelegationAfterRead = formatDelegationAfterRead;
|
|
579
636
|
exports.formatNextPagination = formatNextPagination;
|
|
580
637
|
exports.formatPagination = formatPagination;
|
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
|
}>;
|
|
@@ -230,6 +235,15 @@ declare const createIndexedFactory: (factory: IAssetFactoryState & {
|
|
|
230
235
|
}, context: FactoryContext) => Record<string, unknown> & {
|
|
231
236
|
tokens: TokenWithBalance[];
|
|
232
237
|
};
|
|
238
|
+
/**
|
|
239
|
+
* Derive the signer-based sender. Only for rows that never got a getTxSender value (rejected-but-ledgered
|
|
240
|
+
* txs); normal rows keep getTxSender semantics ("whose asset has net loss", may be empty).
|
|
241
|
+
*/
|
|
242
|
+
declare const deriveTxSender: (tx?: Partial<TxData> | null, ctx?: Partial<FinalizedContext> | null) => string;
|
|
243
|
+
/**
|
|
244
|
+
* Derive transaction gas payer / sponsor address
|
|
245
|
+
*/
|
|
246
|
+
declare const deriveTxGasPayer: (tx?: Partial<TxData> | null, ctx?: Partial<FinalizedContext> | null) => string;
|
|
233
247
|
/**
|
|
234
248
|
* Create indexed transaction from transaction context
|
|
235
249
|
* These fields are used internally to filter transactions by some entity
|
|
@@ -371,4 +385,4 @@ declare const isDefaultTokenChanged: (tx: TxData, token: {
|
|
|
371
385
|
address: string;
|
|
372
386
|
}) => boolean;
|
|
373
387
|
//#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 };
|
|
388
|
+
export { 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, isDefaultTokenChanged, parseDateTime };
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "1.
|
|
6
|
+
"version": "1.31.1",
|
|
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.
|
|
56
|
-
"@ocap/types": "1.
|
|
57
|
-
"@ocap/util": "1.
|
|
55
|
+
"@ocap/state": "1.31.1",
|
|
56
|
+
"@ocap/types": "1.31.1",
|
|
57
|
+
"@ocap/util": "1.31.1",
|
|
58
58
|
"kareem": "^2.4.1",
|
|
59
59
|
"lodash": "^4.17.23"
|
|
60
60
|
}
|