@ocap/statedb-sqlite 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.
Files changed (43) hide show
  1. package/esm/db.d.mts +11 -0
  2. package/esm/db.mjs +45 -9
  3. package/esm/index.d.mts +5 -1
  4. package/esm/index.mjs +5 -1
  5. package/esm/migrations/002-delegation-extensions.mjs +9 -2
  6. package/esm/migrations/004-rollup-reserves.d.mts +20 -0
  7. package/esm/migrations/004-rollup-reserves.mjs +39 -0
  8. package/esm/migrations/index.mjs +30 -15
  9. package/esm/table/account.d.mts +4 -3
  10. package/esm/table/account.mjs +31 -7
  11. package/esm/table/balance.mjs +31 -4
  12. package/esm/table/base.d.mts +8 -1
  13. package/esm/table/base.mjs +72 -28
  14. package/esm/table/rollup.d.mts +5 -2
  15. package/esm/table/rollup.mjs +38 -5
  16. package/esm/table/token.d.mts +9 -0
  17. package/esm/table/token.mjs +14 -0
  18. package/esm/tombstone-cleanup.d.mts +59 -0
  19. package/esm/tombstone-cleanup.mjs +207 -0
  20. package/esm/write-set.d.mts +66 -0
  21. package/esm/write-set.mjs +339 -0
  22. package/lib/db.cjs +45 -10
  23. package/lib/db.d.cts +11 -0
  24. package/lib/index.cjs +26 -0
  25. package/lib/index.d.cts +5 -1
  26. package/lib/migrations/002-delegation-extensions.cjs +9 -2
  27. package/lib/migrations/004-rollup-reserves.cjs +47 -0
  28. package/lib/migrations/004-rollup-reserves.d.cts +20 -0
  29. package/lib/migrations/index.cjs +30 -15
  30. package/lib/table/account.cjs +31 -7
  31. package/lib/table/account.d.cts +4 -3
  32. package/lib/table/balance.cjs +31 -4
  33. package/lib/table/base.cjs +72 -28
  34. package/lib/table/base.d.cts +8 -1
  35. package/lib/table/rollup.cjs +38 -5
  36. package/lib/table/rollup.d.cts +5 -2
  37. package/lib/table/token.cjs +14 -0
  38. package/lib/table/token.d.cts +9 -0
  39. package/lib/tombstone-cleanup.cjs +213 -0
  40. package/lib/tombstone-cleanup.d.cts +59 -0
  41. package/lib/write-set.cjs +351 -0
  42. package/lib/write-set.d.cts +66 -0
  43. package/package.json +8 -8
@@ -0,0 +1,213 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let kysely = require("kysely");
3
+ let _ocap_util = require("@ocap/util");
4
+ let node_crypto = require("node:crypto");
5
+
6
+ //#region src/tombstone-cleanup.ts
7
+ const CANONICAL_UINT_REGEX = /^(?:0|[1-9]\d*)$/;
8
+ const SHA256_HEX_REGEX = /^[a-f0-9]{64}$/i;
9
+ function parseJsonValue(raw, fallback) {
10
+ if (raw === null || raw === void 0 || raw === "") return fallback;
11
+ if (typeof raw === "object") return raw;
12
+ if (typeof raw !== "string") return fallback;
13
+ try {
14
+ return JSON.parse(raw) ?? fallback;
15
+ } catch {
16
+ return fallback;
17
+ }
18
+ }
19
+ function extractContextUpdatedAt(rawContext) {
20
+ const ctx = parseJsonValue(rawContext, {});
21
+ if (!ctx || typeof ctx !== "object") return "";
22
+ const candidate = ctx.renaissanceTime || ctx.updatedAt || ctx.genesisTime || "";
23
+ return typeof candidate === "string" ? candidate.trim() : String(candidate ?? "").trim();
24
+ }
25
+ function compareUpdatedAtTimestamps(a, b) {
26
+ const normA = a.trim();
27
+ const normB = b.trim();
28
+ if (normA === normB) return 0;
29
+ if (!normA) return -1;
30
+ if (!normB) return 1;
31
+ if (/^-?\d+(?:\.\d+)?$/.test(normA) && /^-?\d+(?:\.\d+)?$/.test(normB)) {
32
+ const numA = Number(normA);
33
+ const numB = Number(normB);
34
+ if (Number.isFinite(numA) && Number.isFinite(numB) && numA !== numB) return numA < numB ? -1 : 1;
35
+ }
36
+ const msA = Date.parse(normA);
37
+ const msB = Date.parse(normB);
38
+ if (Number.isFinite(msA) && Number.isFinite(msB)) {
39
+ if (msA !== msB) return msA < msB ? -1 : 1;
40
+ return 0;
41
+ }
42
+ return normA < normB ? -1 : 1;
43
+ }
44
+ function isBalanceTimestampNotAfterAccount(balanceUpdatedAt, accountUpdatedAt) {
45
+ const balTs = balanceUpdatedAt.trim();
46
+ const accTs = accountUpdatedAt.trim();
47
+ if (!balTs) return true;
48
+ if (!accTs) return false;
49
+ return compareUpdatedAtTimestamps(balTs, accTs) <= 0;
50
+ }
51
+ function compareTombstoneRows(a, b) {
52
+ if (a.accountAddress !== b.accountAddress) return a.accountAddress < b.accountAddress ? -1 : 1;
53
+ if (a.tokenAddress !== b.tokenAddress) return a.tokenAddress < b.tokenAddress ? -1 : 1;
54
+ return 0;
55
+ }
56
+ function computeTombstoneCleanupPlanDigest(rows) {
57
+ const canonical = [...rows].sort(compareTombstoneRows).map((r) => [
58
+ r.accountAddress,
59
+ r.tokenAddress,
60
+ r.balance,
61
+ r.balanceUpdatedAt
62
+ ]);
63
+ return (0, node_crypto.createHash)("sha256").update(JSON.stringify(canonical)).digest("hex");
64
+ }
65
+ function buildPerTokenSummaries(rows) {
66
+ const byToken = /* @__PURE__ */ new Map();
67
+ for (const row of rows) {
68
+ const balBn = CANONICAL_UINT_REGEX.test(row.balance) ? new _ocap_util.BN(row.balance, 10) : new _ocap_util.BN(0);
69
+ const existing = byToken.get(row.tokenAddress);
70
+ if (existing) {
71
+ existing.sum = existing.sum.add(balBn);
72
+ existing.rowCount += 1;
73
+ existing.accounts.add(row.accountAddress);
74
+ } else byToken.set(row.tokenAddress, {
75
+ sum: balBn,
76
+ rowCount: 1,
77
+ accounts: new Set([row.accountAddress])
78
+ });
79
+ }
80
+ const sortedTokenAddresses = Array.from(byToken.keys()).sort();
81
+ const result = {};
82
+ for (const tokenAddress of sortedTokenAddresses) {
83
+ const entry = byToken.get(tokenAddress);
84
+ result[tokenAddress] = {
85
+ tokenAddress,
86
+ staleBalanceSum: entry.sum.toString(10),
87
+ rowCount: entry.rowCount,
88
+ accountCount: entry.accounts.size
89
+ };
90
+ }
91
+ return result;
92
+ }
93
+ function isSqliteStateDB(dbOrKysely) {
94
+ const candidate = dbOrKysely;
95
+ return Boolean(candidate && typeof candidate === "object" && typeof candidate.getKysely === "function" && typeof candidate.runAsLambda === "function");
96
+ }
97
+ function resolveKyselyExecutor(dbOrKysely) {
98
+ if (isSqliteStateDB(dbOrKysely)) return dbOrKysely.getKysely();
99
+ return dbOrKysely;
100
+ }
101
+ /**
102
+ * Produce a read-only, deterministic cleanup plan for stale `balance` rows attached to
103
+ * migrated tombstone accounts (`json_array_length(account.migratedTo) > 0` and `balance.updatedAt <= account.updatedAt`).
104
+ */
105
+ async function planTombstoneBalanceCleanup(dbOrKysely) {
106
+ const rawRows = await resolveKyselyExecutor(dbOrKysely).selectFrom("balance as b").innerJoin("account as a", "b.address", "a.address").where("a.migratedTo", "is not", null).where(kysely.sql`CASE WHEN json_valid(a.migratedTo) THEN json_array_length(a.migratedTo) > 0 ELSE 0 END`).select([
107
+ "b.address as accountAddress",
108
+ "b.tokenAddress as tokenAddress",
109
+ "b.balance as balance",
110
+ "b.context as balanceContext",
111
+ "a.migratedTo as migratedTo",
112
+ "a.context as accountContext"
113
+ ]).execute();
114
+ const eligibleRows = [];
115
+ const skippedPostMigrationRows = [];
116
+ for (const raw of rawRows) {
117
+ const migratedToRaw = parseJsonValue(raw.migratedTo, []);
118
+ if (!Array.isArray(migratedToRaw)) continue;
119
+ const migratedTo = migratedToRaw.map((x) => String(x ?? "").trim()).filter((x) => x.length > 0);
120
+ if (migratedTo.length === 0) continue;
121
+ const accountAddress = String(raw.accountAddress ?? "");
122
+ const tokenAddress = String(raw.tokenAddress ?? "");
123
+ const balance = String(raw.balance ?? "0");
124
+ const balanceUpdatedAt = extractContextUpdatedAt(raw.balanceContext);
125
+ const accountUpdatedAt = extractContextUpdatedAt(raw.accountContext);
126
+ const row = {
127
+ accountAddress,
128
+ tokenAddress,
129
+ balance,
130
+ balanceUpdatedAt,
131
+ accountUpdatedAt,
132
+ migratedTo
133
+ };
134
+ if (isBalanceTimestampNotAfterAccount(balanceUpdatedAt, accountUpdatedAt)) eligibleRows.push(row);
135
+ else skippedPostMigrationRows.push(row);
136
+ }
137
+ eligibleRows.sort(compareTombstoneRows);
138
+ skippedPostMigrationRows.sort(compareTombstoneRows);
139
+ const perTokenTotals = buildPerTokenSummaries(eligibleRows);
140
+ const uniqueAccounts = new Set(eligibleRows.map((r) => r.accountAddress));
141
+ const planDigest = computeTombstoneCleanupPlanDigest(eligibleRows);
142
+ return {
143
+ mode: "plan",
144
+ totalRows: eligibleRows.length,
145
+ totalAccounts: uniqueAccounts.size,
146
+ totalTokens: Object.keys(perTokenTotals).length,
147
+ perTokenTotals,
148
+ rows: eligibleRows,
149
+ skippedPostMigrationRows,
150
+ planDigest
151
+ };
152
+ }
153
+ /**
154
+ * Execute digest-guarded deletion of stale tombstone `balance` rows inside an atomic transaction.
155
+ * Recomputes the plan inside the transaction and aborts if `planDigest !== expectedPlanDigest`.
156
+ */
157
+ async function applyTombstoneBalanceCleanup(dbOrKysely, options) {
158
+ if (!options || options.apply !== true) throw new Error("applyTombstoneBalanceCleanup requires explicit { apply: true }");
159
+ const expectedDigest = String(options.expectedPlanDigest ?? "").trim().toLowerCase();
160
+ if (!SHA256_HEX_REGEX.test(expectedDigest)) throw new Error("applyTombstoneBalanceCleanup requires a valid 64-character SHA-256 expectedPlanDigest");
161
+ const executeInTxn = async (txn) => {
162
+ const freshPlan = await planTombstoneBalanceCleanup(txn);
163
+ if (freshPlan.planDigest.toLowerCase() !== expectedDigest) throw new Error(`PLAN_DIGEST_MISMATCH: expected planDigest "${options.expectedPlanDigest}", but current state produced "${freshPlan.planDigest}"`);
164
+ if (freshPlan.rows.length === 0) return {
165
+ mode: "apply",
166
+ applied: false,
167
+ deletedRows: 0,
168
+ deletedAccounts: 0,
169
+ perTokenDeletedTotals: {},
170
+ rows: [],
171
+ planDigest: freshPlan.planDigest
172
+ };
173
+ let deletedRows = 0;
174
+ const deletedAccountSet = /* @__PURE__ */ new Set();
175
+ for (const row of freshPlan.rows) {
176
+ const accountRow = await txn.selectFrom("account").where("address", "=", row.accountAddress).where("migratedTo", "is not", null).where(kysely.sql`CASE WHEN json_valid(migratedTo) THEN json_array_length(migratedTo) > 0 ELSE 0 END`).select([
177
+ "address",
178
+ "context",
179
+ "tokens"
180
+ ]).executeTakeFirst();
181
+ if (!accountRow) throw new Error(`TOMBSTONE_STATE_CHANGED: account "${row.accountAddress}" is no longer a migrated tombstone during apply`);
182
+ const currentAccountUpdatedAt = extractContextUpdatedAt(accountRow.context);
183
+ if (!isBalanceTimestampNotAfterAccount(row.balanceUpdatedAt, currentAccountUpdatedAt)) throw new Error(`TOMBSTONE_TIMESTAMP_CHANGED: balance row (${row.accountAddress}, ${row.tokenAddress}) post-dates account timestamp during apply`);
184
+ const delResult = await txn.deleteFrom("balance").where("address", "=", row.accountAddress).where("tokenAddress", "=", row.tokenAddress).where("balance", "=", row.balance).executeTakeFirst();
185
+ const count = Number(delResult.numDeletedRows ?? 0n);
186
+ if (count !== 1) throw new Error(`TOMBSTONE_ROW_CONCURRENT_MODIFICATION: expected to delete 1 balance row for (${row.accountAddress}, ${row.tokenAddress}), deleted ${count}`);
187
+ deletedRows += count;
188
+ deletedAccountSet.add(row.accountAddress);
189
+ if (accountRow.tokens !== null && accountRow.tokens !== void 0 && accountRow.tokens !== "{}") await txn.updateTable("account").set({ tokens: "{}" }).where("address", "=", row.accountAddress).execute();
190
+ }
191
+ return {
192
+ mode: "apply",
193
+ applied: deletedRows > 0,
194
+ deletedRows,
195
+ deletedAccounts: deletedAccountSet.size,
196
+ perTokenDeletedTotals: freshPlan.perTokenTotals,
197
+ rows: freshPlan.rows,
198
+ planDigest: freshPlan.planDigest
199
+ };
200
+ };
201
+ if (isSqliteStateDB(dbOrKysely)) return dbOrKysely.runAsLambda((txn) => executeInTxn(txn));
202
+ const kysely$1 = resolveKyselyExecutor(dbOrKysely);
203
+ if ("transaction" in kysely$1 && typeof kysely$1.transaction === "function") return kysely$1.transaction().execute((txn) => executeInTxn(txn));
204
+ return executeInTxn(kysely$1);
205
+ }
206
+
207
+ //#endregion
208
+ exports.applyTombstoneBalanceCleanup = applyTombstoneBalanceCleanup;
209
+ exports.compareUpdatedAtTimestamps = compareUpdatedAtTimestamps;
210
+ exports.computeTombstoneCleanupPlanDigest = computeTombstoneCleanupPlanDigest;
211
+ exports.extractContextUpdatedAt = extractContextUpdatedAt;
212
+ exports.isBalanceTimestampNotAfterAccount = isBalanceTimestampNotAfterAccount;
213
+ exports.planTombstoneBalanceCleanup = planTombstoneBalanceCleanup;
@@ -0,0 +1,59 @@
1
+ import { Database } from "./interfaces.cjs";
2
+ import SqliteStateDB from "./db.cjs";
3
+ import { Kysely, Transaction } from "kysely";
4
+
5
+ //#region src/tombstone-cleanup.d.ts
6
+ interface TombstoneBalanceRow {
7
+ accountAddress: string;
8
+ tokenAddress: string;
9
+ balance: string;
10
+ balanceUpdatedAt: string;
11
+ accountUpdatedAt: string;
12
+ migratedTo: string[];
13
+ }
14
+ interface TombstoneTokenSummary {
15
+ tokenAddress: string;
16
+ staleBalanceSum: string;
17
+ rowCount: number;
18
+ accountCount: number;
19
+ }
20
+ interface TombstoneCleanupPlan {
21
+ mode: 'plan';
22
+ totalRows: number;
23
+ totalAccounts: number;
24
+ totalTokens: number;
25
+ perTokenTotals: Record<string, TombstoneTokenSummary>;
26
+ rows: TombstoneBalanceRow[];
27
+ skippedPostMigrationRows: TombstoneBalanceRow[];
28
+ planDigest: string;
29
+ }
30
+ interface ApplyTombstoneCleanupOptions {
31
+ apply: boolean;
32
+ expectedPlanDigest: string;
33
+ }
34
+ interface TombstoneCleanupApplyResult {
35
+ mode: 'apply';
36
+ applied: boolean;
37
+ deletedRows: number;
38
+ deletedAccounts: number;
39
+ perTokenDeletedTotals: Record<string, TombstoneTokenSummary>;
40
+ rows: TombstoneBalanceRow[];
41
+ planDigest: string;
42
+ }
43
+ declare function extractContextUpdatedAt(rawContext: unknown): string;
44
+ declare function compareUpdatedAtTimestamps(a: string, b: string): number;
45
+ declare function isBalanceTimestampNotAfterAccount(balanceUpdatedAt: string, accountUpdatedAt: string): boolean;
46
+ declare function computeTombstoneCleanupPlanDigest(rows: ReadonlyArray<Pick<TombstoneBalanceRow, 'accountAddress' | 'tokenAddress' | 'balance' | 'balanceUpdatedAt'>>): string;
47
+ type KyselyExecutor = Kysely<Database> | Transaction<Database>;
48
+ /**
49
+ * Produce a read-only, deterministic cleanup plan for stale `balance` rows attached to
50
+ * migrated tombstone accounts (`json_array_length(account.migratedTo) > 0` and `balance.updatedAt <= account.updatedAt`).
51
+ */
52
+ declare function planTombstoneBalanceCleanup(dbOrKysely: SqliteStateDB | KyselyExecutor): Promise<TombstoneCleanupPlan>;
53
+ /**
54
+ * Execute digest-guarded deletion of stale tombstone `balance` rows inside an atomic transaction.
55
+ * Recomputes the plan inside the transaction and aborts if `planDigest !== expectedPlanDigest`.
56
+ */
57
+ declare function applyTombstoneBalanceCleanup(dbOrKysely: SqliteStateDB | KyselyExecutor, options: ApplyTombstoneCleanupOptions): Promise<TombstoneCleanupApplyResult>;
58
+ //#endregion
59
+ export { ApplyTombstoneCleanupOptions, TombstoneBalanceRow, TombstoneCleanupApplyResult, TombstoneCleanupPlan, TombstoneTokenSummary, applyTombstoneBalanceCleanup, compareUpdatedAtTimestamps, computeTombstoneCleanupPlanDigest, extractContextUpdatedAt, isBalanceTimestampNotAfterAccount, planTombstoneBalanceCleanup };
@@ -0,0 +1,351 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let node_crypto = require("node:crypto");
3
+ node_crypto = require_rolldown_runtime.__toESM(node_crypto);
4
+
5
+ //#region src/write-set.ts
6
+ const STATE_COMMIT_DOMAIN_V2 = "ocap:state-commit:v2:";
7
+ function codeUnitCompare(a, b) {
8
+ return a < b ? -1 : a > b ? 1 : 0;
9
+ }
10
+ function sha256Hex(utf8Input) {
11
+ return node_crypto.default.createHash("sha256").update(utf8Input, "utf8").digest("hex");
12
+ }
13
+ function bytesToHexLower(bytes) {
14
+ let out = "";
15
+ for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
16
+ return out;
17
+ }
18
+ /**
19
+ * Recursively normalize an arbitrary JS value into a deterministic JSON-serializable structure
20
+ * with lexicographically sorted object keys (code-unit order).
21
+ * Bit-for-bit identical to `@arcblock/ledger-core` `canonicalizeStateValue`.
22
+ */
23
+ function canonicalizeStateValue(value, seen = /* @__PURE__ */ new WeakSet()) {
24
+ if (value === null || value === void 0) return null;
25
+ if (typeof value === "boolean" || typeof value === "string") return value;
26
+ if (typeof value === "number") {
27
+ if (!Number.isFinite(value)) return null;
28
+ return Object.is(value, -0) ? 0 : value;
29
+ }
30
+ if (typeof value === "bigint") return { $bigint: value.toString(10) };
31
+ if (value instanceof ArrayBuffer) return { $bytes: bytesToHexLower(new Uint8Array(value)) };
32
+ if (ArrayBuffer.isView(value)) return { $bytes: bytesToHexLower(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };
33
+ if (Array.isArray(value)) {
34
+ if (seen.has(value)) throw new TypeError("Cannot canonicalize circular state array");
35
+ seen.add(value);
36
+ try {
37
+ return value.map((item) => canonicalizeStateValue(item, seen));
38
+ } finally {
39
+ seen.delete(value);
40
+ }
41
+ }
42
+ if (typeof value === "object") {
43
+ if (seen.has(value)) throw new TypeError("Cannot canonicalize circular state object");
44
+ seen.add(value);
45
+ try {
46
+ const proto = Object.getPrototypeOf(value);
47
+ if (!(proto === Object.prototype || proto === null) && typeof value.toJSON === "function") return canonicalizeStateValue(value.toJSON(), seen);
48
+ const record = value;
49
+ const sortedKeys = Object.keys(record).sort(codeUnitCompare);
50
+ const normalized = Object.create(null);
51
+ for (const k of sortedKeys) {
52
+ const v = record[k];
53
+ if (v !== void 0) Object.defineProperty(normalized, k, {
54
+ value: canonicalizeStateValue(v, seen),
55
+ enumerable: true,
56
+ writable: true,
57
+ configurable: true
58
+ });
59
+ }
60
+ return normalized;
61
+ } finally {
62
+ seen.delete(value);
63
+ }
64
+ }
65
+ return String(value);
66
+ }
67
+ function canonicalizeStateJson(value) {
68
+ return JSON.stringify(canonicalizeStateValue(value));
69
+ }
70
+ /**
71
+ * Collapse an ordered sequence of intra-transaction state writes into a canonical, deterministic tuple array
72
+ * and hash it with SHA-256 (64 lowercase hex chars).
73
+ * Bit-for-bit identical to `@arcblock/ledger-core` `computeStateWriteSetDigest`.
74
+ */
75
+ function computeStateWriteSetDigest(writes) {
76
+ const tables = /* @__PURE__ */ new Map();
77
+ const rawOps = [];
78
+ const ensureTable = (table) => {
79
+ let entry = tables.get(table);
80
+ if (!entry) {
81
+ entry = {
82
+ reset: false,
83
+ rows: /* @__PURE__ */ new Map()
84
+ };
85
+ tables.set(table, entry);
86
+ }
87
+ return entry;
88
+ };
89
+ for (const w of writes) {
90
+ if (!w || typeof w !== "object") continue;
91
+ if (w.op === "reset") {
92
+ const t = ensureTable(String(w.table));
93
+ t.reset = true;
94
+ t.rows.clear();
95
+ } else if (w.op === "put") ensureTable(String(w.table)).rows.set(String(w.key), {
96
+ op: "put",
97
+ value: canonicalizeStateValue(w.value)
98
+ });
99
+ else if (w.op === "delete") ensureTable(String(w.table)).rows.set(String(w.key), { op: "delete" });
100
+ else if (w.op === "raw") rawOps.push({
101
+ sql: String(w.sql),
102
+ parameters: Array.isArray(w.parameters) ? w.parameters.map((p) => canonicalizeStateValue(p)) : []
103
+ });
104
+ }
105
+ const normalizedEntries = [];
106
+ const sortedTables = Array.from(tables.keys()).sort(codeUnitCompare);
107
+ for (const table of sortedTables) {
108
+ const t = tables.get(table);
109
+ if (t.reset) normalizedEntries.push(["reset", table]);
110
+ const sortedKeys = Array.from(t.rows.keys()).sort(codeUnitCompare);
111
+ for (const key of sortedKeys) {
112
+ const row = t.rows.get(key);
113
+ if (row.op === "delete") normalizedEntries.push([
114
+ "delete",
115
+ table,
116
+ key
117
+ ]);
118
+ else normalizedEntries.push([
119
+ "put",
120
+ table,
121
+ key,
122
+ row.value
123
+ ]);
124
+ }
125
+ }
126
+ for (const raw of rawOps) normalizedEntries.push([
127
+ "raw",
128
+ raw.sql,
129
+ raw.parameters
130
+ ]);
131
+ return sha256Hex(JSON.stringify(normalizedEntries));
132
+ }
133
+ /**
134
+ * Compute v2 state commit hash binding `(prevHash, seq, msg, writeSetDigest)` with unambiguous JSON framing.
135
+ * Bit-for-bit identical to `@arcblock/ledger-core` `computeStateCommitHash`.
136
+ */
137
+ function computeStateCommitHash(params) {
138
+ const { prevHash, seq, msg, writeSetDigest } = params;
139
+ if (!Number.isSafeInteger(seq) || seq < 1) throw new Error(`Invalid state commit sequence: ${seq}`);
140
+ if (typeof writeSetDigest !== "string" || !/^[0-9a-f]{64}$/i.test(writeSetDigest)) throw new Error("Invalid writeSetDigest: expected 64-char hex SHA-256");
141
+ return sha256Hex(`${STATE_COMMIT_DOMAIN_V2}${JSON.stringify([
142
+ String(prevHash),
143
+ seq,
144
+ String(msg),
145
+ writeSetDigest.toLowerCase()
146
+ ])}`);
147
+ }
148
+ /**
149
+ * Format a table's primary key into an unambiguous canonical string key.
150
+ * Single-column PKs serialize as `String(val)`; composite PKs serialize as a JSON string tuple.
151
+ */
152
+ function formatCanonicalPrimaryKey(uniqIndex, keyOrDoc) {
153
+ if (Array.isArray(uniqIndex)) {
154
+ const obj = keyOrDoc || {};
155
+ return JSON.stringify(uniqIndex.map((col) => obj[col]));
156
+ }
157
+ if (typeof keyOrDoc === "object" && keyOrDoc !== null) return String(keyOrDoc[uniqIndex]);
158
+ return String(keyOrDoc);
159
+ }
160
+ const TOP_LEVEL_MUTATING_STMT_RE = /^(?:INSERT|UPDATE|DELETE|REPLACE|ALTER|DROP|CREATE|ATTACH|DETACH|VACUUM|REINDEX|ANALYZE|PRAGMA)\b/i;
161
+ const CTE_MUTATING_TAIL_RE = /^WITH\b[\s\S]*?\b(?:INSERT|UPDATE|DELETE|REPLACE)\b/i;
162
+ function scanTopLevelSqlStatements(sqlText) {
163
+ const statements = [];
164
+ let current = "";
165
+ let depth = 0;
166
+ const len = sqlText.length;
167
+ let i = 0;
168
+ while (i < len) {
169
+ const ch = sqlText[i];
170
+ const next = i + 1 < len ? sqlText[i + 1] : "";
171
+ if (ch === "-" && next === "-") {
172
+ i += 2;
173
+ while (i < len && sqlText[i] !== "\n" && sqlText[i] !== "\r") i++;
174
+ if (depth === 0) current += " ";
175
+ continue;
176
+ }
177
+ if (ch === "/" && next === "*") {
178
+ i += 2;
179
+ while (i < len && !(sqlText[i] === "*" && sqlText[i + 1] === "/")) i++;
180
+ i = i < len ? i + 2 : len;
181
+ if (depth === 0) current += " ";
182
+ continue;
183
+ }
184
+ if (ch === "'" || ch === "\"" || ch === "`") {
185
+ const quote = ch;
186
+ i++;
187
+ while (i < len) {
188
+ if (sqlText[i] === quote) {
189
+ if (sqlText[i + 1] === quote) {
190
+ i += 2;
191
+ continue;
192
+ }
193
+ i++;
194
+ break;
195
+ }
196
+ i++;
197
+ }
198
+ if (depth === 0) current += " ";
199
+ continue;
200
+ }
201
+ if (ch === "[") {
202
+ i++;
203
+ while (i < len && sqlText[i] !== "]") i++;
204
+ if (i < len) i++;
205
+ if (depth === 0) current += " ";
206
+ continue;
207
+ }
208
+ if (ch === "(") {
209
+ if (depth === 0) current += " ";
210
+ depth++;
211
+ i++;
212
+ continue;
213
+ }
214
+ if (ch === ")") {
215
+ if (depth > 0) depth--;
216
+ if (depth === 0) current += " ";
217
+ i++;
218
+ continue;
219
+ }
220
+ if (ch === ";" && depth === 0) {
221
+ const trimmed = current.trim();
222
+ if (trimmed.length > 0) statements.push(trimmed);
223
+ current = "";
224
+ i++;
225
+ continue;
226
+ }
227
+ if (depth === 0) current += ch;
228
+ i++;
229
+ }
230
+ const tail = current.trim();
231
+ if (tail.length > 0) statements.push(tail);
232
+ return statements;
233
+ }
234
+ function isTrackedRawMutatingSql(sqlText) {
235
+ for (const stmt of scanTopLevelSqlStatements(sqlText)) if (TOP_LEVEL_MUTATING_STMT_RE.test(stmt) || CTE_MUTATING_TAIL_RE.test(stmt)) return true;
236
+ return false;
237
+ }
238
+ var WriteSetTracker = class {
239
+ constructor() {
240
+ this.writes = [];
241
+ }
242
+ recordPut(table, key, value) {
243
+ this.writes.push({
244
+ op: "put",
245
+ table,
246
+ key,
247
+ value
248
+ });
249
+ }
250
+ recordDelete(table, key) {
251
+ this.writes.push({
252
+ op: "delete",
253
+ table,
254
+ key
255
+ });
256
+ }
257
+ recordReset(table) {
258
+ this.writes.push({
259
+ op: "reset",
260
+ table
261
+ });
262
+ }
263
+ recordRaw(sqlText, parameters) {
264
+ this.writes.push({
265
+ op: "raw",
266
+ sql: sqlText,
267
+ parameters
268
+ });
269
+ }
270
+ getWrites() {
271
+ return this.writes;
272
+ }
273
+ computeDigest() {
274
+ return computeStateWriteSetDigest(this.writes);
275
+ }
276
+ };
277
+ var WriteSetRawDmlPlugin = class {
278
+ constructor(rawTxn, tracker, basePlugins) {
279
+ this.pendingByQueryId = /* @__PURE__ */ new WeakMap();
280
+ this.rawTxn = rawTxn;
281
+ this.tracker = tracker;
282
+ this.basePlugins = basePlugins;
283
+ }
284
+ transformQuery(args) {
285
+ try {
286
+ const compiled = this.rawTxn.getExecutor().compileQuery(args.node, args.queryId);
287
+ if (isTrackedRawMutatingSql(compiled.sql)) this.pendingByQueryId.set(args.queryId, {
288
+ sql: compiled.sql,
289
+ parameters: compiled.parameters
290
+ });
291
+ } catch {}
292
+ return args.node;
293
+ }
294
+ async transformResult(args) {
295
+ const key = args.queryId;
296
+ const pending = this.pendingByQueryId.get(key);
297
+ if (pending) {
298
+ this.pendingByQueryId.delete(key);
299
+ this.tracker.recordRaw(pending.sql, pending.parameters);
300
+ }
301
+ return args.result;
302
+ }
303
+ };
304
+ const TXN_TRACKER_MAP = /* @__PURE__ */ new WeakMap();
305
+ const RAW_TXN_MAP = /* @__PURE__ */ new WeakMap();
306
+ function attachWriteSetTracker(rawTxn, tracker) {
307
+ const basePlugins = rawTxn.getExecutor().plugins;
308
+ const plugin = new WriteSetRawDmlPlugin(rawTxn, tracker, basePlugins);
309
+ const wrappedTxn = rawTxn.withPlugin(plugin);
310
+ TXN_TRACKER_MAP.set(rawTxn, tracker);
311
+ TXN_TRACKER_MAP.set(wrappedTxn, tracker);
312
+ RAW_TXN_MAP.set(wrappedTxn, rawTxn);
313
+ return wrappedTxn;
314
+ }
315
+ function getWriteSetTracker(txn) {
316
+ if (!txn || typeof txn !== "object") return void 0;
317
+ const direct = TXN_TRACKER_MAP.get(txn);
318
+ if (direct) return direct;
319
+ const plugins = txn.getExecutor?.()?.plugins;
320
+ if (Array.isArray(plugins)) {
321
+ for (const p of plugins) if (p instanceof WriteSetRawDmlPlugin) return p.tracker;
322
+ }
323
+ }
324
+ function unwrapTableTransaction(txn) {
325
+ const direct = RAW_TXN_MAP.get(txn);
326
+ if (direct) return direct;
327
+ const plugins = txn.getExecutor?.()?.plugins;
328
+ if (Array.isArray(plugins)) {
329
+ const found = plugins.find((p) => p instanceof WriteSetRawDmlPlugin);
330
+ if (found) {
331
+ let stripped = txn.withoutPlugins();
332
+ for (const bp of found.basePlugins) stripped = stripped.withPlugin(bp);
333
+ RAW_TXN_MAP.set(txn, stripped);
334
+ return stripped;
335
+ }
336
+ }
337
+ return txn;
338
+ }
339
+
340
+ //#endregion
341
+ exports.STATE_COMMIT_DOMAIN_V2 = STATE_COMMIT_DOMAIN_V2;
342
+ exports.WriteSetTracker = WriteSetTracker;
343
+ exports.attachWriteSetTracker = attachWriteSetTracker;
344
+ exports.canonicalizeStateJson = canonicalizeStateJson;
345
+ exports.canonicalizeStateValue = canonicalizeStateValue;
346
+ exports.computeStateCommitHash = computeStateCommitHash;
347
+ exports.computeStateWriteSetDigest = computeStateWriteSetDigest;
348
+ exports.formatCanonicalPrimaryKey = formatCanonicalPrimaryKey;
349
+ exports.getWriteSetTracker = getWriteSetTracker;
350
+ exports.isTrackedRawMutatingSql = isTrackedRawMutatingSql;
351
+ exports.unwrapTableTransaction = unwrapTableTransaction;
@@ -0,0 +1,66 @@
1
+ import { Database } from "./interfaces.cjs";
2
+ import { Transaction } from "kysely";
3
+
4
+ //#region src/write-set.d.ts
5
+ declare const STATE_COMMIT_DOMAIN_V2 = "ocap:state-commit:v2:";
6
+ type IStateWriteRecord = {
7
+ op: 'put';
8
+ table: string;
9
+ key: string;
10
+ value: unknown;
11
+ } | {
12
+ op: 'delete';
13
+ table: string;
14
+ key: string;
15
+ } | {
16
+ op: 'reset';
17
+ table: string;
18
+ } | {
19
+ op: 'raw';
20
+ sql: string;
21
+ parameters?: readonly unknown[];
22
+ };
23
+ interface IStateCommitStepInput {
24
+ prevHash: string;
25
+ seq: number;
26
+ msg: string;
27
+ writeSetDigest: string;
28
+ }
29
+ /**
30
+ * Recursively normalize an arbitrary JS value into a deterministic JSON-serializable structure
31
+ * with lexicographically sorted object keys (code-unit order).
32
+ * Bit-for-bit identical to `@arcblock/ledger-core` `canonicalizeStateValue`.
33
+ */
34
+ declare function canonicalizeStateValue(value: unknown, seen?: WeakSet<object>): unknown;
35
+ declare function canonicalizeStateJson(value: unknown): string;
36
+ /**
37
+ * Collapse an ordered sequence of intra-transaction state writes into a canonical, deterministic tuple array
38
+ * and hash it with SHA-256 (64 lowercase hex chars).
39
+ * Bit-for-bit identical to `@arcblock/ledger-core` `computeStateWriteSetDigest`.
40
+ */
41
+ declare function computeStateWriteSetDigest(writes: Iterable<IStateWriteRecord>): string;
42
+ /**
43
+ * Compute v2 state commit hash binding `(prevHash, seq, msg, writeSetDigest)` with unambiguous JSON framing.
44
+ * Bit-for-bit identical to `@arcblock/ledger-core` `computeStateCommitHash`.
45
+ */
46
+ declare function computeStateCommitHash(params: IStateCommitStepInput): string;
47
+ /**
48
+ * Format a table's primary key into an unambiguous canonical string key.
49
+ * Single-column PKs serialize as `String(val)`; composite PKs serialize as a JSON string tuple.
50
+ */
51
+ declare function formatCanonicalPrimaryKey(uniqIndex: string | string[], keyOrDoc: unknown): string;
52
+ declare function isTrackedRawMutatingSql(sqlText: string): boolean;
53
+ declare class WriteSetTracker {
54
+ private readonly writes;
55
+ recordPut(table: string, key: string, value: unknown): void;
56
+ recordDelete(table: string, key: string): void;
57
+ recordReset(table: string): void;
58
+ recordRaw(sqlText: string, parameters?: readonly unknown[]): void;
59
+ getWrites(): readonly IStateWriteRecord[];
60
+ computeDigest(): string;
61
+ }
62
+ declare function attachWriteSetTracker(rawTxn: Transaction<Database>, tracker: WriteSetTracker): Transaction<Database>;
63
+ declare function getWriteSetTracker(txn: Transaction<Database> | undefined): WriteSetTracker | undefined;
64
+ declare function unwrapTableTransaction(txn: Transaction<Database>): Transaction<Database>;
65
+ //#endregion
66
+ export { IStateCommitStepInput, IStateWriteRecord, STATE_COMMIT_DOMAIN_V2, WriteSetTracker, attachWriteSetTracker, canonicalizeStateJson, canonicalizeStateValue, computeStateCommitHash, computeStateWriteSetDigest, formatCanonicalPrimaryKey, getWriteSetTracker, isTrackedRawMutatingSql, unwrapTableTransaction };