@ocap/statedb-sqlite 1.30.26 → 1.31.0
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/db.d.mts +2 -0
- package/esm/db.mjs +52 -36
- package/esm/index.d.mts +2 -1
- package/esm/index.mjs +2 -1
- package/esm/migrations/003-token-charter-assets.d.mts +14 -0
- package/esm/migrations/003-token-charter-assets.mjs +116 -0
- package/esm/migrations/index.d.mts +2 -1
- package/esm/migrations/index.mjs +6 -3
- package/esm/package.mjs +2 -0
- package/esm/reconcile.d.mts +82 -0
- package/esm/reconcile.mjs +833 -0
- package/esm/table/balance.mjs +35 -16
- package/esm/table/base.mjs +24 -17
- package/lib/db.cjs +52 -36
- package/lib/db.d.cts +2 -0
- package/lib/index.cjs +5 -1
- package/lib/index.d.cts +2 -1
- package/lib/migrations/003-token-charter-assets.cjs +123 -0
- package/lib/migrations/003-token-charter-assets.d.cts +14 -0
- package/lib/migrations/index.cjs +12 -3
- package/lib/migrations/index.d.cts +2 -1
- package/lib/package.cjs +2 -0
- package/lib/reconcile.cjs +836 -0
- package/lib/reconcile.d.cts +82 -0
- package/lib/table/balance.cjs +35 -16
- package/lib/table/base.cjs +24 -17
- package/package.json +8 -6
package/esm/table/balance.mjs
CHANGED
|
@@ -78,12 +78,13 @@ var BalanceTable = class extends base_default {
|
|
|
78
78
|
* @returns Updated token balances
|
|
79
79
|
*/
|
|
80
80
|
async updateBalance({ address, tokens, context = {} }, ctx) {
|
|
81
|
-
if (!Object.keys(tokens).length) return {};
|
|
82
81
|
const normalizedAddress = ensureChecksumAddress(address);
|
|
83
82
|
const tokenBalances = await this.getBalance(normalizedAddress, ctx);
|
|
83
|
+
const removedTokens = Object.keys(tokenBalances).filter((token) => !(token in tokens));
|
|
84
84
|
const updatedTokens = Object.keys(tokens).filter((token) => tokenBalances[token] && tokenBalances[token] !== "0" || tokens[token] && tokens[token] !== "0").filter((token) => tokenBalances[token] !== tokens[token]);
|
|
85
|
-
if (updatedTokens.length === 0) return tokens;
|
|
85
|
+
if (updatedTokens.length === 0 && removedTokens.length === 0) return { ...tokens };
|
|
86
86
|
const batchRows = [];
|
|
87
|
+
const pendingOps = [];
|
|
87
88
|
for (const tokenAddress of updatedTokens) {
|
|
88
89
|
const key = {
|
|
89
90
|
address: normalizedAddress,
|
|
@@ -99,22 +100,40 @@ var BalanceTable = class extends base_default {
|
|
|
99
100
|
enumerable: false,
|
|
100
101
|
configurable: true
|
|
101
102
|
});
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
103
|
+
const insertAttrs = {
|
|
104
|
+
...payload,
|
|
105
|
+
...key
|
|
106
|
+
};
|
|
107
|
+
batchRows.push(this.serializeForDb(insertAttrs));
|
|
108
|
+
pendingOps.push({
|
|
109
|
+
isUpdate: Boolean(tokenBalances[tokenAddress]),
|
|
110
|
+
key,
|
|
111
|
+
payload,
|
|
112
|
+
tokenAddress
|
|
113
|
+
});
|
|
105
114
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
115
|
+
const sqlContext = ctx;
|
|
116
|
+
const executor = this.getExecutor(sqlContext);
|
|
117
|
+
if (removedTokens.length > 0) await executor.deleteFrom("balance").where("address", "=", normalizedAddress).where("tokenAddress", "in", removedTokens).execute();
|
|
118
|
+
if (batchRows.length > 0) for (let i = 0; i < batchRows.length; i += UPSERT_BATCH_SIZE) {
|
|
119
|
+
const batch = batchRows.slice(i, i + UPSERT_BATCH_SIZE);
|
|
120
|
+
await executor.insertInto("balance").values(batch).onConflict((oc) => oc.columns(["address", "tokenAddress"]).doUpdateSet((eb) => ({
|
|
121
|
+
balance: eb.ref("excluded.balance"),
|
|
122
|
+
context: eb.ref("excluded.context")
|
|
123
|
+
}))).execute();
|
|
124
|
+
}
|
|
125
|
+
const noopCollector = [];
|
|
126
|
+
for (const op of pendingOps) {
|
|
127
|
+
Object.defineProperty(op.payload, BATCH_COLLECTOR, {
|
|
128
|
+
value: noopCollector,
|
|
129
|
+
enumerable: false,
|
|
130
|
+
configurable: true
|
|
131
|
+
});
|
|
132
|
+
if (op.isUpdate) await this.update(op.key, op.payload, ctx);
|
|
133
|
+
else await this.create(op.key, op.payload, ctx);
|
|
134
|
+
tokenBalances[op.tokenAddress] = tokens[op.tokenAddress];
|
|
116
135
|
}
|
|
117
|
-
return tokens;
|
|
136
|
+
return { ...tokens };
|
|
118
137
|
}
|
|
119
138
|
};
|
|
120
139
|
var balance_default = BalanceTable;
|
package/esm/table/base.mjs
CHANGED
|
@@ -124,11 +124,14 @@ var SqliteTable = class SqliteTable extends StateDBTable {
|
|
|
124
124
|
if (this.syncBalance) delete insertAttrs.tokens;
|
|
125
125
|
const serialized = this.serializeForDb(insertAttrs);
|
|
126
126
|
await executor.insertInto(this.name).values(serialized).execute();
|
|
127
|
-
if (this.syncBalance && attrs.tokens
|
|
128
|
-
|
|
129
|
-
tokens
|
|
130
|
-
|
|
131
|
-
|
|
127
|
+
if (this.syncBalance && attrs.tokens !== void 0) {
|
|
128
|
+
const rawTokens = attrs.tokens || {};
|
|
129
|
+
insertAttrs.tokens = Object.keys(rawTokens).length ? await this.balanceTable.updateBalance({
|
|
130
|
+
address: insertAttrs.address || (typeof key === "string" ? key : ""),
|
|
131
|
+
tokens: rawTokens,
|
|
132
|
+
context: attrs.context
|
|
133
|
+
}, context) : {};
|
|
134
|
+
}
|
|
132
135
|
return insertAttrs;
|
|
133
136
|
}
|
|
134
137
|
async _get(key, context) {
|
|
@@ -147,7 +150,8 @@ var SqliteTable = class SqliteTable extends StateDBTable {
|
|
|
147
150
|
const result = await qb.executeTakeFirst();
|
|
148
151
|
const deserialized = this.deserializeFromDb(result);
|
|
149
152
|
if (deserialized && this.syncBalance) {
|
|
150
|
-
const
|
|
153
|
+
const balanceAddr = deserialized.address || (typeof key === "string" ? key : "");
|
|
154
|
+
const balance = await this.balanceTable.getBalance(balanceAddr, context);
|
|
151
155
|
deserialized.tokens = {
|
|
152
156
|
...deserialized.tokens || {},
|
|
153
157
|
...balance
|
|
@@ -197,17 +201,20 @@ var SqliteTable = class SqliteTable extends StateDBTable {
|
|
|
197
201
|
if (!existingRow) throw new Error(`${this.name} does not exist: ${JSON.stringify(key)}`);
|
|
198
202
|
merged = this.deserializeFromDb(existingRow);
|
|
199
203
|
}
|
|
200
|
-
if (this.syncBalance)
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
204
|
+
if (this.syncBalance) {
|
|
205
|
+
const balanceAddr = merged.address || (typeof key === "string" ? key : "");
|
|
206
|
+
if (updates.tokens !== void 0) merged.tokens = await this.balanceTable.updateBalance({
|
|
207
|
+
address: balanceAddr,
|
|
208
|
+
tokens: updates.tokens || {},
|
|
209
|
+
context: updates.context
|
|
210
|
+
}, context);
|
|
211
|
+
else {
|
|
212
|
+
const balance = await this.balanceTable.getBalance(balanceAddr, context);
|
|
213
|
+
merged.tokens = {
|
|
214
|
+
...merged.tokens || {},
|
|
215
|
+
...balance
|
|
216
|
+
};
|
|
217
|
+
}
|
|
211
218
|
}
|
|
212
219
|
return merged;
|
|
213
220
|
}
|
package/lib/db.cjs
CHANGED
|
@@ -213,13 +213,13 @@ var SqliteStateDB = class extends _ocap_statedb.StateDB {
|
|
|
213
213
|
async initialize() {
|
|
214
214
|
this.closed = false;
|
|
215
215
|
if (this.initialized) {
|
|
216
|
-
if (this.trustedStorage && !this.trustedInitialized) await this.ensureTrustedStorageInitialized();
|
|
216
|
+
if (this.trustedStorage && !this.trustedInitialized) await this.ensureTrustedStorageInitialized(true);
|
|
217
217
|
this.startWalCheckpointWorker();
|
|
218
218
|
return;
|
|
219
219
|
}
|
|
220
220
|
await require_migrations_index.runMigrations(this.db);
|
|
221
221
|
this.initialized = true;
|
|
222
|
-
if (this.trustedStorage) await this.ensureTrustedStorageInitialized();
|
|
222
|
+
if (this.trustedStorage) await this.ensureTrustedStorageInitialized(true);
|
|
223
223
|
this.startWalCheckpointWorker();
|
|
224
224
|
}
|
|
225
225
|
/**
|
|
@@ -286,7 +286,7 @@ var SqliteStateDB = class extends _ocap_statedb.StateDB {
|
|
|
286
286
|
`.execute(this.db);
|
|
287
287
|
this.stateCommitTableReady = true;
|
|
288
288
|
}
|
|
289
|
-
async ensureTrustedStorageInitialized() {
|
|
289
|
+
async ensureTrustedStorageInitialized(allowForwardRecovery = false) {
|
|
290
290
|
if (!this.trustedStorage || this.trustedInitialized) return;
|
|
291
291
|
await this.ensureStateCommitTable();
|
|
292
292
|
if (typeof this.trustedStorage.initStorage === "function") await this.trustedStorage.initStorage();
|
|
@@ -294,7 +294,7 @@ var SqliteStateDB = class extends _ocap_statedb.StateDB {
|
|
|
294
294
|
const { currentHash } = await this.getCommitHash();
|
|
295
295
|
const newTrustedHash = await this.trustedStorage.createHash(currentHash);
|
|
296
296
|
await this.trustedStorage.writeHash(newTrustedHash);
|
|
297
|
-
} else await this.verifyTrustedHashInternal();
|
|
297
|
+
} else await this.verifyTrustedHashInternal(allowForwardRecovery);
|
|
298
298
|
this.trustedInitialized = true;
|
|
299
299
|
}
|
|
300
300
|
/**
|
|
@@ -311,17 +311,24 @@ var SqliteStateDB = class extends _ocap_statedb.StateDB {
|
|
|
311
311
|
async getCommitHash(executor = this.db) {
|
|
312
312
|
if (!this.stateCommitTableReady) await this.ensureStateCommitTable();
|
|
313
313
|
const row = (await kysely.sql`
|
|
314
|
-
SELECT "current_hash", "prev_hash" FROM "_state_commit" WHERE "id" = 1
|
|
314
|
+
SELECT "current_hash", "prev_hash", "seq", "msg" FROM "_state_commit" WHERE "id" = 1
|
|
315
315
|
`.execute(executor)).rows[0];
|
|
316
316
|
return {
|
|
317
317
|
currentHash: row?.current_hash || "GENESIS",
|
|
318
|
-
prevHash: row?.prev_hash || ""
|
|
318
|
+
prevHash: row?.prev_hash || "",
|
|
319
|
+
seq: Number(row?.seq || 0),
|
|
320
|
+
msg: row?.msg || ""
|
|
319
321
|
};
|
|
320
322
|
}
|
|
321
|
-
async verifyTrustedHashInternal() {
|
|
323
|
+
async verifyTrustedHashInternal(allowForwardRecovery = false) {
|
|
322
324
|
if (!this.trustedStorage) return;
|
|
323
|
-
const { currentHash } = await this.getCommitHash();
|
|
325
|
+
const { currentHash, prevHash, seq = 0 } = await this.getCommitHash();
|
|
324
326
|
if (!await this.trustedStorage.compare(currentHash)) {
|
|
327
|
+
const isValidSha256Hex = /^[0-9a-f]{64}$/i.test(currentHash);
|
|
328
|
+
if (allowForwardRecovery && prevHash && seq > 0 && currentHash !== prevHash && isValidSha256Hex && await this.trustedStorage.compare(prevHash)) {
|
|
329
|
+
await this.trustedStorage.updateHash(currentHash, prevHash);
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
325
332
|
const err = /* @__PURE__ */ new Error("Trusted hash verification failed");
|
|
326
333
|
err.code = "INVALID_HASH";
|
|
327
334
|
throw err;
|
|
@@ -333,8 +340,8 @@ var SqliteStateDB = class extends _ocap_statedb.StateDB {
|
|
|
333
340
|
async verifyTrustedHash() {
|
|
334
341
|
if (!this.trustedStorage) return;
|
|
335
342
|
await this.enqueueCommit(async () => {
|
|
336
|
-
await this.ensureTrustedStorageInitialized();
|
|
337
|
-
await this.verifyTrustedHashInternal();
|
|
343
|
+
await this.ensureTrustedStorageInitialized(true);
|
|
344
|
+
await this.verifyTrustedHashInternal(true);
|
|
338
345
|
});
|
|
339
346
|
}
|
|
340
347
|
enqueueCommit(task) {
|
|
@@ -356,50 +363,59 @@ var SqliteStateDB = class extends _ocap_statedb.StateDB {
|
|
|
356
363
|
}
|
|
357
364
|
async executeRunAsLambda(fn, options = {}) {
|
|
358
365
|
const { retryLimit = 2, verifyHash = false, commitMessage } = options;
|
|
366
|
+
if (!this.stateCommitTableReady) await this.ensureStateCommitTable();
|
|
359
367
|
if (this.trustedStorage) {
|
|
360
368
|
await this.ensureTrustedStorageInitialized();
|
|
361
|
-
if (verifyHash) await this.verifyTrustedHashInternal();
|
|
369
|
+
if (verifyHash) await this.verifyTrustedHashInternal(false);
|
|
362
370
|
}
|
|
363
371
|
let result;
|
|
364
372
|
let committedHash;
|
|
365
373
|
let previousHash;
|
|
366
374
|
let lastError;
|
|
367
375
|
let committed = false;
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
376
|
+
const opCtx = options.context;
|
|
377
|
+
for (let attempt = 0; attempt <= retryLimit; attempt++) {
|
|
378
|
+
const savedEvents = Array.isArray(opCtx?.events) ? [...opCtx.events] : void 0;
|
|
379
|
+
const savedTimerCounters = opCtx?.timer?.stateDbCounters && typeof opCtx.timer.stateDbCounters === "object" ? { ...opCtx.timer.stateDbCounters } : void 0;
|
|
372
380
|
try {
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
381
|
+
committedHash = void 0;
|
|
382
|
+
previousHash = void 0;
|
|
383
|
+
this._activeLambdaCount++;
|
|
384
|
+
try {
|
|
385
|
+
result = await this.db.transaction().execute(async (txn) => {
|
|
386
|
+
const txResult = await fn(txn);
|
|
376
387
|
const row = (await kysely.sql`
|
|
377
|
-
|
|
378
|
-
|
|
388
|
+
SELECT "current_hash", "seq" FROM "_state_commit" WHERE "id" = 1
|
|
389
|
+
`.execute(txn)).rows[0];
|
|
379
390
|
const prevHash = row?.current_hash || "GENESIS";
|
|
380
391
|
const nextSeq = Number(row?.seq || 0) + 1;
|
|
381
392
|
const msg = commitMessage || txResult?.hash || "commit";
|
|
382
393
|
const nextHash = node_crypto.default.createHash("sha256").update(`${prevHash}:${nextSeq}:${msg}`).digest("hex");
|
|
383
394
|
await kysely.sql`
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
395
|
+
UPDATE "_state_commit"
|
|
396
|
+
SET "current_hash" = ${nextHash}, "prev_hash" = ${prevHash}, "seq" = ${nextSeq}, "msg" = ${msg}
|
|
397
|
+
WHERE "id" = 1
|
|
398
|
+
`.execute(txn);
|
|
388
399
|
previousHash = prevHash;
|
|
389
400
|
committedHash = nextHash;
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
|
|
401
|
+
return txResult;
|
|
402
|
+
});
|
|
403
|
+
} finally {
|
|
404
|
+
this._activeLambdaCount--;
|
|
405
|
+
}
|
|
406
|
+
committed = true;
|
|
407
|
+
break;
|
|
408
|
+
} catch (err) {
|
|
409
|
+
if (opCtx && savedEvents !== void 0 && Array.isArray(opCtx.events)) {
|
|
410
|
+
opCtx.events.length = 0;
|
|
411
|
+
opCtx.events.push(...savedEvents);
|
|
412
|
+
}
|
|
413
|
+
if (opCtx?.timer?.stateDbCounters && savedTimerCounters !== void 0) Object.assign(opCtx.timer.stateDbCounters, savedTimerCounters);
|
|
414
|
+
lastError = err;
|
|
415
|
+
const code = err?.code;
|
|
416
|
+
if (!SQLITE_BUSY_CODES.includes(code)) throw err;
|
|
417
|
+
if (attempt < retryLimit) await new Promise((r) => setTimeout(r, 10 * 2 ** attempt));
|
|
395
418
|
}
|
|
396
|
-
committed = true;
|
|
397
|
-
break;
|
|
398
|
-
} catch (err) {
|
|
399
|
-
lastError = err;
|
|
400
|
-
const code = err?.code;
|
|
401
|
-
if (!SQLITE_BUSY_CODES.includes(code)) throw err;
|
|
402
|
-
if (attempt < retryLimit) await new Promise((r) => setTimeout(r, 10 * 2 ** attempt));
|
|
403
419
|
}
|
|
404
420
|
if (!committed) throw lastError;
|
|
405
421
|
if (this.trustedStorage && committedHash) await this.trustedStorage.updateHash(committedHash, previousHash);
|
package/lib/db.d.cts
CHANGED
|
@@ -103,6 +103,8 @@ declare class SqliteStateDB extends StateDB implements IStateDB {
|
|
|
103
103
|
getCommitHash(executor?: Kysely<Database> | Transaction<Database>): Promise<{
|
|
104
104
|
currentHash: string;
|
|
105
105
|
prevHash: string;
|
|
106
|
+
seq?: number;
|
|
107
|
+
msg?: string;
|
|
106
108
|
}>;
|
|
107
109
|
private verifyTrustedHashInternal;
|
|
108
110
|
/**
|
package/lib/index.cjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
2
2
|
const require_kysely = require('./kysely.cjs');
|
|
3
3
|
const require_db = require('./db.cjs');
|
|
4
|
+
const require_reconcile = require('./reconcile.cjs');
|
|
4
5
|
|
|
5
6
|
//#region src/index.ts
|
|
6
7
|
var src_default = require_db.default;
|
|
@@ -8,6 +9,9 @@ var src_default = require_db.default;
|
|
|
8
9
|
//#endregion
|
|
9
10
|
exports.DurableObjectSqliteDialect = require_kysely.DurableObjectSqliteDialect;
|
|
10
11
|
exports.SqliteStateDB = require_db.default;
|
|
12
|
+
exports.assertSqliteStateDb = require_reconcile.assertSqliteStateDb;
|
|
11
13
|
exports.createKysely = require_kysely.createKysely;
|
|
12
14
|
exports.default = src_default;
|
|
13
|
-
exports.getRawDatabase = require_kysely.getRawDatabase;
|
|
15
|
+
exports.getRawDatabase = require_kysely.getRawDatabase;
|
|
16
|
+
exports.reconcileChainState = require_reconcile.reconcileChainState;
|
|
17
|
+
exports.verifyChainStateInvariants = require_reconcile.verifyChainStateInvariants;
|
package/lib/index.d.cts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Database, SqliteOperationContext } from "./interfaces.cjs";
|
|
2
2
|
import { DurableObjectSqliteDialect, DurableObjectSqliteDialectConfig, IDurableObjectSqlStorage, IDurableObjectSqlStorageCursor, SqliteConfig, createKysely, getRawDatabase } from "./kysely.cjs";
|
|
3
3
|
import SqliteStateDB from "./db.cjs";
|
|
4
|
-
|
|
4
|
+
import { ChainStateAuditReport, InvariantSeverity, InvariantViolation, ReconcileAction, ReconcileOptions, ReconcileResult, assertSqliteStateDb, reconcileChainState, verifyChainStateInvariants } from "./reconcile.cjs";
|
|
5
|
+
export { type ChainStateAuditReport, type Database, DurableObjectSqliteDialect, type DurableObjectSqliteDialectConfig, type IDurableObjectSqlStorage, type IDurableObjectSqlStorageCursor, type InvariantSeverity, type InvariantViolation, type ReconcileAction, type ReconcileOptions, type ReconcileResult, type SqliteConfig, type SqliteOperationContext, SqliteStateDB, SqliteStateDB as default, assertSqliteStateDb, createKysely, getRawDatabase, reconcileChainState, verifyChainStateInvariants };
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let kysely = require("kysely");
|
|
3
|
+
let _arcblock_did = require("@arcblock/did");
|
|
4
|
+
let _ocap_state = require("@ocap/state");
|
|
5
|
+
let _ocap_util = require("@ocap/util");
|
|
6
|
+
|
|
7
|
+
//#region src/migrations/003-token-charter-assets.ts
|
|
8
|
+
var _003_token_charter_assets_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
|
|
9
|
+
down: () => down,
|
|
10
|
+
up: () => up
|
|
11
|
+
});
|
|
12
|
+
function parseJsonField(val, fallback) {
|
|
13
|
+
if (val === null || val === void 0 || val === "") return fallback;
|
|
14
|
+
if (typeof val === "object") return val;
|
|
15
|
+
if (typeof val === "string") try {
|
|
16
|
+
return JSON.parse(val);
|
|
17
|
+
} catch {
|
|
18
|
+
return fallback;
|
|
19
|
+
}
|
|
20
|
+
return fallback;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Migration 003: Backfill companion Master Charter `AssetState` rows in `asset`
|
|
24
|
+
* for all existing Fungible Tokens in `token` (Token-as-an-Asset unification).
|
|
25
|
+
*/
|
|
26
|
+
async function up(db) {
|
|
27
|
+
const tokenRows = (await kysely.sql`SELECT * FROM "token"`.execute(db)).rows || [];
|
|
28
|
+
if (tokenRows.length === 0) return;
|
|
29
|
+
const factoryOwnerMap = /* @__PURE__ */ new Map();
|
|
30
|
+
try {
|
|
31
|
+
const factoryRowsResult = await kysely.sql`
|
|
32
|
+
SELECT "address", "owner" FROM "tokenFactory"
|
|
33
|
+
`.execute(db);
|
|
34
|
+
for (const row of factoryRowsResult.rows || []) if (row?.address && row?.owner) factoryOwnerMap.set(row.address, row.owner);
|
|
35
|
+
} catch {}
|
|
36
|
+
for (const row of tokenRows) {
|
|
37
|
+
const rawAddress = String(row.address || "").trim();
|
|
38
|
+
if (!rawAddress) continue;
|
|
39
|
+
const address = (0, _ocap_util.toAddress)(rawAddress);
|
|
40
|
+
if (!(0, _arcblock_did.isValid)(address)) continue;
|
|
41
|
+
const tokenFactoryAddress = String(row.tokenFactoryAddress || "");
|
|
42
|
+
const tokenState = (0, _ocap_state.normalizeLegacyTokenStateForUpdate)({
|
|
43
|
+
address,
|
|
44
|
+
name: String(row.name || row.symbol || "Token"),
|
|
45
|
+
description: String(row.description || "Fungible token charter state"),
|
|
46
|
+
symbol: String(row.symbol || "TKN"),
|
|
47
|
+
unit: String(row.unit || "unit"),
|
|
48
|
+
decimal: Number(row.decimal ?? 18),
|
|
49
|
+
icon: row.icon ? String(row.icon) : "",
|
|
50
|
+
totalSupply: String(row.totalSupply || "0"),
|
|
51
|
+
initialSupply: String(row.initialSupply || "0"),
|
|
52
|
+
maxTotalSupply: row.maxTotalSupply ? String(row.maxTotalSupply) : "",
|
|
53
|
+
foreignToken: parseJsonField(row.foreignToken, null),
|
|
54
|
+
issuer: row.issuer ? String(row.issuer) : "",
|
|
55
|
+
website: row.website ? String(row.website) : "",
|
|
56
|
+
metadata: parseJsonField(row.metadata, null),
|
|
57
|
+
tokenFactoryAddress,
|
|
58
|
+
spenders: parseJsonField(row.spenders, null),
|
|
59
|
+
minters: parseJsonField(row.minters, null),
|
|
60
|
+
type: row.type ? String(row.type) : "Token",
|
|
61
|
+
data: parseJsonField(row.data, null),
|
|
62
|
+
context: parseJsonField(row.context, {
|
|
63
|
+
genesisTime: "2020-01-15T00:00:00.000Z",
|
|
64
|
+
genesisTx: "",
|
|
65
|
+
renaissanceTime: "2020-01-15T00:00:00.000Z",
|
|
66
|
+
renaissanceTx: ""
|
|
67
|
+
})
|
|
68
|
+
});
|
|
69
|
+
const ownerOverride = tokenFactoryAddress ? factoryOwnerMap.get(tokenFactoryAddress) : void 0;
|
|
70
|
+
let charter;
|
|
71
|
+
try {
|
|
72
|
+
charter = (0, _ocap_state.buildTokenCharterAssetState)(tokenState, void 0, ownerOverride);
|
|
73
|
+
} catch {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
await kysely.sql`
|
|
77
|
+
INSERT OR IGNORE INTO "asset" (
|
|
78
|
+
"address",
|
|
79
|
+
"owner",
|
|
80
|
+
"moniker",
|
|
81
|
+
"readonly",
|
|
82
|
+
"transferrable",
|
|
83
|
+
"ttl",
|
|
84
|
+
"consumedTime",
|
|
85
|
+
"issuer",
|
|
86
|
+
"parent",
|
|
87
|
+
"endpoint",
|
|
88
|
+
"display",
|
|
89
|
+
"tags",
|
|
90
|
+
"data",
|
|
91
|
+
"context"
|
|
92
|
+
) VALUES (
|
|
93
|
+
${charter.address},
|
|
94
|
+
${charter.owner},
|
|
95
|
+
${charter.moniker},
|
|
96
|
+
${charter.readonly ? 1 : 0},
|
|
97
|
+
${charter.transferrable ? 1 : 0},
|
|
98
|
+
${charter.ttl ?? 0},
|
|
99
|
+
${charter.consumedTime || ""},
|
|
100
|
+
${charter.issuer || ""},
|
|
101
|
+
${charter.parent || ""},
|
|
102
|
+
${charter.endpoint ? JSON.stringify(charter.endpoint) : null},
|
|
103
|
+
${charter.display ? JSON.stringify(charter.display) : null},
|
|
104
|
+
${JSON.stringify(charter.tags || [])},
|
|
105
|
+
${JSON.stringify(charter.data ?? null)},
|
|
106
|
+
${JSON.stringify(charter.context ?? null)}
|
|
107
|
+
)
|
|
108
|
+
`.execute(db);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
async function down(db) {
|
|
112
|
+
await kysely.sql`DELETE FROM "asset" WHERE "tags" LIKE '%"token:charter"%'`.execute(db);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
//#endregion
|
|
116
|
+
Object.defineProperty(exports, '_003_token_charter_assets_exports', {
|
|
117
|
+
enumerable: true,
|
|
118
|
+
get: function () {
|
|
119
|
+
return _003_token_charter_assets_exports;
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
exports.down = down;
|
|
123
|
+
exports.up = up;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Kysely } from "kysely";
|
|
2
|
+
|
|
3
|
+
//#region src/migrations/003-token-charter-assets.d.ts
|
|
4
|
+
declare namespace _003_token_charter_assets_d_exports {
|
|
5
|
+
export { down, up };
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Migration 003: Backfill companion Master Charter `AssetState` rows in `asset`
|
|
9
|
+
* for all existing Fungible Tokens in `token` (Token-as-an-Asset unification).
|
|
10
|
+
*/
|
|
11
|
+
declare function up(db: Kysely<unknown>): Promise<void>;
|
|
12
|
+
declare function down(db: Kysely<unknown>): Promise<void>;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { _003_token_charter_assets_d_exports, down, up };
|
package/lib/migrations/index.cjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_migrations_001_genesis = require('./001-genesis.cjs');
|
|
3
3
|
const require_migrations_002_delegation_extensions = require('./002-delegation-extensions.cjs');
|
|
4
|
+
const require_migrations_003_token_charter_assets = require('./003-token-charter-assets.cjs');
|
|
4
5
|
let kysely = require("kysely");
|
|
5
6
|
|
|
6
7
|
//#region src/migrations/index.ts
|
|
@@ -33,7 +34,8 @@ async function runMigrations(db) {
|
|
|
33
34
|
db,
|
|
34
35
|
provider: new InMemoryMigrationProvider({
|
|
35
36
|
"001-genesis": require_migrations_001_genesis._001_genesis_exports,
|
|
36
|
-
"002-delegation-extensions": require_migrations_002_delegation_extensions._002_delegation_extensions_exports
|
|
37
|
+
"002-delegation-extensions": require_migrations_002_delegation_extensions._002_delegation_extensions_exports,
|
|
38
|
+
"003-token-charter-assets": require_migrations_003_token_charter_assets._003_token_charter_assets_exports
|
|
37
39
|
})
|
|
38
40
|
}).migrateToLatest();
|
|
39
41
|
results?.forEach((it) => {
|
|
@@ -53,7 +55,8 @@ async function rollbackMigrations(db) {
|
|
|
53
55
|
db,
|
|
54
56
|
provider: new InMemoryMigrationProvider({
|
|
55
57
|
"001-genesis": require_migrations_001_genesis._001_genesis_exports,
|
|
56
|
-
"002-delegation-extensions": require_migrations_002_delegation_extensions._002_delegation_extensions_exports
|
|
58
|
+
"002-delegation-extensions": require_migrations_002_delegation_extensions._002_delegation_extensions_exports,
|
|
59
|
+
"003-token-charter-assets": require_migrations_003_token_charter_assets._003_token_charter_assets_exports
|
|
57
60
|
})
|
|
58
61
|
});
|
|
59
62
|
let hasMore = true;
|
|
@@ -66,4 +69,10 @@ async function rollbackMigrations(db) {
|
|
|
66
69
|
|
|
67
70
|
//#endregion
|
|
68
71
|
exports.rollbackMigrations = rollbackMigrations;
|
|
69
|
-
exports.runMigrations = runMigrations;
|
|
72
|
+
exports.runMigrations = runMigrations;
|
|
73
|
+
Object.defineProperty(exports, 'tokenCharterAssets', {
|
|
74
|
+
enumerable: true,
|
|
75
|
+
get: function () {
|
|
76
|
+
return require_migrations_003_token_charter_assets._003_token_charter_assets_exports;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _003_token_charter_assets_d_exports } from "./003-token-charter-assets.cjs";
|
|
1
2
|
import { Kysely } from "kysely";
|
|
2
3
|
|
|
3
4
|
//#region src/migrations/index.d.ts
|
|
@@ -21,4 +22,4 @@ declare function runMigrations(db: Kysely<unknown>): Promise<void>;
|
|
|
21
22
|
*/
|
|
22
23
|
declare function rollbackMigrations(db: Kysely<unknown>): Promise<void>;
|
|
23
24
|
//#endregion
|
|
24
|
-
export { rollbackMigrations, runMigrations };
|
|
25
|
+
export { rollbackMigrations, runMigrations, _003_token_charter_assets_d_exports as tokenCharterAssets };
|
package/lib/package.cjs
CHANGED