From 4910933003e6fa7c3ecacfd3ed5a44f2b3dbf9a0 Mon Sep 17 00:00:00 2001 From: Glorious21 <184563826+Glorious21@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:38:23 +0100 Subject: [PATCH] feat(api): store per-asset headline figures for the overview The dashboard polls the overview every few seconds, and each call replayed events, rebuilt the controls log and re-read every action and run per asset. An asset_stats row now holds supply, holder and event counts, incompleteness, the latest run and the open-break counts. overview() and assetSummary() read it; a missing row is recomputed and stored. The row is rewritten at the end of every change that can move a figure: a sync pass (including one that adds nothing, since the controls log runs to the read-through time, and one that fails after committing pages), a rebuild, a reconciliation, a deleted register, a sign-off, an instructions import, a corporate action's reconciliation and an asset settings change (its matching windows decide which controls break). An asset that was never synced is always recomputed. ORG_MIGRATIONS v6 adds the table, with the org-v6 fixture, upgrade tests, the pinned digest, the cascade test row and docs. Closes #575 --- CHANGELOG.md | 4 + docs/schema.md | 26 +++- services/api/src/concord.ts | 84 ++++++++++++- services/api/src/schema.ts | 17 +++ services/api/test/fixtures/db/org-v6.db | Bin 0 -> 131072 bytes .../api/test/fixtures/make-db-fixtures.ts | 10 ++ services/api/test/migrations.test.ts | 16 +++ services/api/test/schema.test.ts | 5 + services/api/test/service.test.ts | 111 ++++++++++++++++++ services/api/test/tenancy.test.ts | 1 + 10 files changed, 271 insertions(+), 3 deletions(-) create mode 100644 services/api/test/fixtures/db/org-v6.db diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e3a6fc5..6667f204 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,10 @@ Everything to date; Concord's history begins 2026-10 with the commits below. - A per-asset reconciliation `tolerance` (smallest units): a holder whose chain and register balances differ by no more than it is treated as matched. Schema: `ORG_MIGRATIONS` v5 adds `assets.tolerance` (#564). +- Stored headline figures per asset (#575): the overview and `GET /api/assets/:id` read each + asset's supply, holder and event counts and open-break counts from one row, rewritten after + every change that moves them, so a poll no longer replays events or rebuilds the controls + log. Schema: `ORG_MIGRATIONS` entry 6 adds the `asset_stats` table. - CSV templates can include one illustrative example row with `?example=1` or `?example=true` (#200). - The accounting core (`feat(core)`, `c402eae`): holdings replay from CAP-67 events, position and movement reconciliation with typed breaks, corporate-action entitlements (dividend, diff --git a/docs/schema.md b/docs/schema.md index de113c7f..f1fa3bb9 100644 --- a/docs/schema.md +++ b/docs/schema.md @@ -46,13 +46,14 @@ erDiagram assets ||--o{ runs : "asset_id" assets ||--o{ actions : "asset_id" assets ||--o{ break_notes : "asset_id" + assets ||--o| asset_stats : "asset_id" registers ||--o{ register_positions : "register_id" registers ||--o{ runs : "register_id" ``` Every arrow is `ON DELETE CASCADE`. Deleting an asset therefore deletes its events, opening balances, registers (and through them their positions and runs), journal, instructions, corporate -actions and break notes. Deleting a register deletes its positions *and the runs made from it*. +actions, break notes and stored figures. Deleting a register deletes its positions *and the runs made from it*. `meta` stands alone. ### `meta` @@ -263,6 +264,29 @@ existed). One row per `setNote` call: `id`, `asset_id`, `scope`, `key`, `fingerp `note`, `author`, `author_id`, `at`. It is what the audit pack lists as `signoffHistory` and what `GET /api/assets/:id/notes/history?scope=&key=` returns, oldest first. +### `asset_stats` + +Each asset's headline figures (added in migration 6), so the dashboard's polled +`GET /api/overview` and `GET /api/assets/:id` read one row instead of replaying events and +rebuilding the controls log. Primary key `asset_id`. Derived data: a missing row is recomputed +and stored on the next read (`Concord.assetSummary`, `services/api/src/concord.ts`). + +| Column | Type | Notes | +|---|---|---| +| `asset_id` | TEXT | → `assets.id` | +| `supply` | TEXT | Current supply in whole units, formatted as the overview shows it. | +| `holder_count` | INTEGER | Addresses with a non-zero balance. | +| `event_count` | INTEGER | Indexed events. | +| `incomplete` | INTEGER | `1` when some holder's derived balance is negative (history missing). | +| `last_run` | TEXT (JSON), null | `{ id, asOf, status, openBreaks }` of the latest reconciliation. | +| `open_reconciliation`, `open_controls`, `open_actions` | INTEGER | Open breaks in the latest run, the controls log, and all corporate actions. | +| `updated_at` | TEXT | | + +The row is rewritten at the end of every change that can move a figure (`Concord.refreshStats`): +a sync pass (also one that adds nothing, since the controls log runs to the read-through time), +a rebuild, a reconciliation, a deleted register, a sign-off, an instructions import and a +corporate action's reconciliation. An asset that has never been synced is always recomputed. + ## Control database (`control.db`) ```mermaid diff --git a/services/api/src/concord.ts b/services/api/src/concord.ts index bf1be603..c4911c78 100644 --- a/services/api/src/concord.ts +++ b/services/api/src/concord.ts @@ -367,6 +367,31 @@ function toEvent(row: Row): AssetEvent { return ev; } +/** An asset's headline figures, as the overview shows them and `asset_stats` stores them. */ +interface AssetStats { + supply: string; + holderCount: number; + eventCount: number; + incomplete: boolean; + lastRun: { id: number; asOf: string; status: "clean" | "breaks"; openBreaks: number } | null; + openBreaks: { reconciliation: number; controls: number; actions: number }; +} + +function statsFromRow(row: Row): AssetStats { + return { + supply: String(row.supply), + holderCount: Number(row.holder_count), + eventCount: Number(row.event_count), + incomplete: Number(row.incomplete) === 1, + lastRun: row.last_run ? (JSON.parse(String(row.last_run)) as AssetStats["lastRun"]) : null, + openBreaks: { + reconciliation: Number(row.open_reconciliation), + controls: Number(row.open_controls), + actions: Number(row.open_actions), + }, + }; +} + /** * One workspace: every operation the API and the CLI expose over a single database. * Reads the chain, never writes it. @@ -631,6 +656,8 @@ export class Concord { movementWindowHours, asset.id, ); + // The matching windows decide which controls break, and so the stored open-break count. + this.refreshStats(asset.id); return this.asset(asset.id); } @@ -670,6 +697,8 @@ export class Concord { ); }); this.touch(asset.id); + // The history is gone until the next pass; a deferred rebuild must not keep showing it. + this.refreshStats(asset.id); if (options.defer) void this.sync(asset.id).catch(() => {}); else await this.sync(asset.id); return this.asset(asset.id); @@ -744,9 +773,17 @@ export class Concord { if (asset.syncError) { this.db.write("UPDATE assets SET sync_error = NULL, sync_error_at = NULL WHERE id = ?", asset.id); } + // Even a pass that added nothing moved the read-through time the controls log runs to. + this.refreshStats(asset.id); return out; } catch (err) { if (this.removing.has(asset.id)) throw err; + // Pages written before the failure are committed; the figures must include them. + try { + this.refreshStats(asset.id); + } catch { + // The sync failure below is the one to report. + } this.db.write( "UPDATE assets SET sync_error = ?, sync_error_at = ? WHERE id = ?", describeFailure(err), @@ -1024,6 +1061,8 @@ export class Concord { )?.count ?? 0; const removed = this.db.write("DELETE FROM registers WHERE id = ? AND asset_id = ?", registerId, asset.id); if (removed === 0) throw new NotFound("no such register for this asset"); + // Its runs went with it, and the latest run may have been one of them. + this.refreshStats(asset.id); return { runs }; } @@ -1319,6 +1358,7 @@ export class Concord { } } }); + this.refreshStats(asset.id); return { instructions: parsed.instructions.length, added, replaced, removed, issues: parsed.issues }; } @@ -1499,6 +1539,7 @@ export class Concord { now(), JSON.stringify(result), ); + this.refreshStats(asset.id); return this.run(id); } @@ -1843,6 +1884,7 @@ ul { margin: 6px 0 0; padding-left: 20px; } at, ); }); + this.refreshStats(asset.id); return { ok: true }; } @@ -2046,6 +2088,7 @@ ul { margin: 6px 0 0; padding-left: 20px; } breaks: [], }; this.db.write("UPDATE actions SET result = ?, reconciled_at = ? WHERE id = ?", JSON.stringify(result), now(), id); + this.refreshStats(asset.id); return this.action(id); } @@ -2226,6 +2269,7 @@ ul { margin: 6px 0 0; padding-left: 20px; } ...(cashFlowResult ? { cashInLieu: cashFlowResult } : {}), }; this.db.write("UPDATE actions SET result = ?, reconciled_at = ? WHERE id = ?", JSON.stringify(result), now(), id); + this.refreshStats(asset.id); return this.action(id); } @@ -2442,15 +2486,26 @@ ul { margin: 6px 0 0; padding-left: 20px; } }; } - /** One asset with the headline figures the dashboard lists. */ + /** + * One asset with the headline figures the dashboard lists. The figures come from the + * asset's `asset_stats` row, which every change that can move them rewrites (`refreshStats`), + * so a poll reads one row however long the history is. + */ assetSummary(asset: AssetRecord) { + // Never indexed: the controls log runs up to the clock, and there is nothing to replay. + const row = asset.syncedAt ? this.db.get("SELECT * FROM asset_stats WHERE asset_id = ?", asset.id) : undefined; + const stats = row ? statsFromRow(row) : this.refreshStats(asset.id); + return { ...asset, ...stats }; + } + + /** The headline figures recomputed from the data, ignoring any stored row. */ + private computeStats(asset: AssetRecord): AssetStats { const state = this.state(asset); const run = this.latestRun(asset.id); const controls = this.controls(asset.id); const actions = this.actions(asset.id); const events = this.db.get<{ n: number }>("SELECT COUNT(*) AS n FROM events WHERE asset_id = ?", asset.id)!.n; return { - ...asset, supply: formatUnits(state.supply, asset.decimals), holderCount: state.balances.size, eventCount: events, @@ -2464,6 +2519,31 @@ ul { margin: 6px 0 0; padding-left: 20px; } }; } + /** + * Recompute and store an asset's headline figures. Called at the end of every change that can + * move them: a sync pass, a rebuild, a reconciliation or a deleted register, a sign-off, an + * instructions import and a corporate action's reconciliation. + */ + private refreshStats(assetId: string): AssetStats { + const asset = this.asset(assetId); + const stats = this.computeStats(asset); + this.db.write( + `INSERT OR REPLACE INTO asset_stats (asset_id, supply, holder_count, event_count, incomplete, last_run, + open_reconciliation, open_controls, open_actions, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + asset.id, + stats.supply, + stats.holderCount, + stats.eventCount, + stats.incomplete ? 1 : 0, + stats.lastRun ? JSON.stringify(stats.lastRun) : null, + stats.openBreaks.reconciliation, + stats.openBreaks.controls, + stats.openBreaks.actions, + now(), + ); + return stats; + } + /** Everything an auditor needs for a period, with a digest over the content. */ auditExport(ref: string, period: { from?: string; to?: string } = {}) { const asset = this.asset(ref); diff --git a/services/api/src/schema.ts b/services/api/src/schema.ts index 5014acc0..5bf8121e 100644 --- a/services/api/src/schema.ts +++ b/services/api/src/schema.ts @@ -174,6 +174,23 @@ ALTER TABLE assets ADD COLUMN movement_window_hours INTEGER NOT NULL DEFAULT 24; `, // v5: per-asset reconciliation tolerance (smallest units as TEXT to preserve bigint precision). `ALTER TABLE assets ADD COLUMN tolerance TEXT;`, + // v6: each asset's headline figures, so the dashboard's polled overview reads one row instead + // of replaying events and rebuilding the controls log. Derived data: a missing row is + // recomputed on the next read. + ` +CREATE TABLE asset_stats ( + asset_id TEXT PRIMARY KEY REFERENCES assets (id) ON DELETE CASCADE, + supply TEXT NOT NULL, + holder_count INTEGER NOT NULL, + event_count INTEGER NOT NULL, + incomplete INTEGER NOT NULL, + last_run TEXT, + open_reconciliation INTEGER NOT NULL, + open_controls INTEGER NOT NULL, + open_actions INTEGER NOT NULL, + updated_at TEXT NOT NULL +); +`, ]; /** Identity: who may sign in, and which workspace each session is bound to. */ diff --git a/services/api/test/fixtures/db/org-v6.db b/services/api/test/fixtures/db/org-v6.db new file mode 100644 index 0000000000000000000000000000000000000000..11b4d495ea2dccf6ac62bdba10a7ace814e9748d GIT binary patch literal 131072 zcmeI*?Qa{$odF;ZTI7RFtCxmjKPF^d=H4%RY(1*$I5x6}gf& zB6pdcrELW`TqVo*;)(+b^i|P!eb<-wXS6RaxK{_M8a z*e^zAl`oZ_6~5_})L@3)zmZjoGfLC4>*jN}ZFAi<4=wJQuJ|xh+0oXk8r$5yt36_g zX!c-R2C&8O1l_8aHm+yYAI>ONCpm+2(-UXjNT(&^Itj^-l*$sLl+J#9EvL@RDCfFo z>^Dr2g7~=}q*7h~$(9ymAkXLo%41dgSleL_cQ)^@?>uJrw8w0Hulitfn@+i}ZC97* zxbPCJsy(W*?FaO;x3$G~w2!nMZM&lF`bTiKNLdg$yQ^(!1W;Mut*qbGL=v&$M%V0> zP;hA-P|3t>cgQ$}vvhL@Iw;NsI`O?{)D>?PnE#upUM9PFiNVBu1^~wC%2IbgV)Qx)Gjfgxa`MJX%^%+qs-gEuP z;78GE7s@Udvg-O=KiR-UF9&a~oMxwUYNf24-txziU{umu4!2|@?hI6^sLKI&Fl?pb zqf_PBlZs9bX=h`Xa%#D(ytv~JM5)8Wj^4@IbfUV`@v`Ql;Mmype;r4ToJQSrY3NK> zc@SkAO}{;edW(0nWbaB;FZT?u?f1HT>8DdU_4a~tI+~~suFDP-mW5yHDIXja*QQai z)Ai&qSbCVxs<&?|k0o=^^|<+Y+q7$D*T<;@a98A_DC-iPNkiadPF+|~&esxE$D{1# z6X`_3vVLOK5^vYv#+1@$8sIdB)Oz${eq^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pQ2wCcMh zCzx={S8qAolF!CE&p(6R;!f1%#LRQSsqu~O&gsb~rDtQ8+pZnBTY=M_A;qU(k315P$##AOHafKmY;|fB*y_0D=Ajxc~2OgBS=v00Izz00bZa0SG_<0uX?}pa_V6 z|F0DOJwxC4f&c^{009U<00Izz00bZa0SG|gJ0Y;5Ox>JOl!?s5~bC literal 0 HcmV?d00001 diff --git a/services/api/test/fixtures/make-db-fixtures.ts b/services/api/test/fixtures/make-db-fixtures.ts index 772dab7a..fe0abcc9 100644 --- a/services/api/test/fixtures/make-db-fixtures.ts +++ b/services/api/test/fixtures/make-db-fixtures.ts @@ -78,6 +78,16 @@ build(join(outDir, "org-v5.db"), ORG_MIGRATIONS.slice(0, 5), (db) => { VALUES ('usd-mainnet', 'mainnet', 'USD', 'GISSUER1', 'US Dollar', 7, 'baseline', 'ready', '5', '2024-01-01T00:00:00Z')`); }); +// v6 adds each asset's stored headline figures; one row proves the table survives later upgrades. +build(join(outDir, "org-v6.db"), ORG_MIGRATIONS.slice(0, 6), (db) => { + db.exec("INSERT INTO meta (key, value) VALUES ('fixture', 'org-v6')"); + db.exec(`INSERT INTO assets (id, network, code, issuer, name, decimals, start_mode, state, created_at) + VALUES ('usd-mainnet', 'mainnet', 'USD', 'GISSUER1', 'US Dollar', 7, 'baseline', 'ready', '2024-01-01T00:00:00Z')`); + db.exec(`INSERT INTO asset_stats (asset_id, supply, holder_count, event_count, incomplete, last_run, + open_reconciliation, open_controls, open_actions, updated_at) + VALUES ('usd-mainnet', '1000', 2, 5, 0, NULL, 0, 1, 0, '2024-01-02T00:00:00Z')`); +}); + build(join(outDir, "control-v1.db"), CONTROL_MIGRATIONS.slice(0, 1), (db) => { db.exec(`INSERT INTO users (id, email, name, email_verified, created_at) VALUES ('u1', 'alice@example.org', 'Alice', 1, '2024-01-01T00:00:00Z')`); diff --git a/services/api/test/migrations.test.ts b/services/api/test/migrations.test.ts index 606b8695..62f3e0cf 100644 --- a/services/api/test/migrations.test.ts +++ b/services/api/test/migrations.test.ts @@ -77,6 +77,22 @@ describe("databases written by earlier builds", () => { }); }); + it("adds an empty asset_stats table to a v5 workspace database", () => { + upgraded("org-v5.db", ORG_MIGRATIONS, (db) => { + expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM asset_stats")?.n).toBe(0); + }); + }); + + it("opens the v6 workspace database and keeps its stored asset figures", () => { + upgraded("org-v6.db", ORG_MIGRATIONS, (db) => { + expect(db.get<{ value: string }>("SELECT value FROM meta WHERE key = 'fixture'")?.value).toBe("org-v6"); + expect(db.get("SELECT supply, open_controls FROM asset_stats WHERE asset_id = 'usd-mainnet'")).toEqual({ + supply: "1000", + open_controls: 1, + }); + }); + }); + it("opens the v1 control database with the current migrations and keeps its rows", () => { upgraded("control-v1.db", CONTROL_MIGRATIONS, (db) => { expect(db.get<{ name: string }>("SELECT name FROM users WHERE id = 'u1'")?.name).toBe("Alice"); diff --git a/services/api/test/schema.test.ts b/services/api/test/schema.test.ts index 43318599..3b72c1c9 100644 --- a/services/api/test/schema.test.ts +++ b/services/api/test/schema.test.ts @@ -84,6 +84,11 @@ describe("schema cascade deletion", () => { INSERT INTO break_note_history (asset_id, scope, key, fingerprint, status, note, at) VALUES ('A', 'scope', 'kA', 'fp', 'open', 'note', '2026-01-01'), ('B', 'scope', 'kB', 'fp', 'open', 'note', '2026-01-01'); + + INSERT INTO asset_stats (asset_id, supply, holder_count, event_count, incomplete, open_reconciliation, + open_controls, open_actions, updated_at) + VALUES ('A', '100', 1, 1, 0, 0, 0, 0, '2026-01-01'), + ('B', '100', 1, 1, 0, 0, 0, 0, '2026-01-01'); `); // Verify before deletion: each child table has 2 rows (one for A, one for B) diff --git a/services/api/test/service.test.ts b/services/api/test/service.test.ts index 81d3e96b..2c1bad15 100644 --- a/services/api/test/service.test.ts +++ b/services/api/test/service.test.ts @@ -572,6 +572,117 @@ describe("Concord", () => { expect(() => concord.diffRegisters("FUND", mine.registerId, 99_999)).toThrow(new NotFound("no register 99999")); }); + it("keeps the overview's stored figures equal to a full recompute after every kind of change", async () => { + /** The overview as served, then as recomputed from scratch with the stored rows gone. */ + const expectCurrent = (step: string) => { + const served = concord.overview(); + concord.db.write("DELETE FROM asset_stats"); + expect(served, `after ${step}`).toEqual(concord.overview()); + return served.assets.find((a) => a.id === assetId)!; + }; + + await concord.sync("FUND"); + expect(expectCurrent("first sync")).toMatchObject({ eventCount: 7, holderCount: 3, supply: "1144" }); + // Served from the row the sync stored, not recomputed. + expect(concord.db.get("SELECT event_count FROM asset_stats WHERE asset_id = ?", assetId)).toEqual({ + event_count: 7, + }); + + chain.advance(5); + await concord.sync("FUND"); + expectCurrent("a sync that added nothing"); + + chain.push(assetId, "mint", 107, { to: h3, amount: u(4) }); + chain.push(assetId, "set_authorized", 108, { from: h3, authorized: false }); + chain.advance(5); + await concord.sync("FUND"); + expect(expectCurrent("a sync with new events")).toMatchObject({ eventCount: 9, supply: "1148" }); + + // Issued 100 minutes before h2's freeze at ledger 20: inside the default matching window. + concord.importInstructions("FUND", `ref,type,account,units,issued_at\nI1,freeze,${h2},,${at(-80)}\n`); + const controlsBefore = expectCurrent("an instructions import").openBreaks.controls; + + // A one-hour window no longer pairs I1 with the freeze, so more controls break. + concord.updateAsset("FUND", { instructionWindowHours: 1 }); + expect(expectCurrent("a narrower instruction window").openBreaks.controls).toBeGreaterThan( + controlsBefore, + ); + concord.updateAsset("FUND", { instructionWindowHours: 72 }); + expect(expectCurrent("the window restored").openBreaks.controls).toBe(controlsBefore); + + const reg = concord.importRegister("FUND", { + csv: `holder_id,account,units\nA,${h1},90\nB,${h2},50\n`, + asOf: at(40), + }); + const run = await concord.reconcile("FUND", reg.registerId); + const reconciled = expectCurrent("a reconciliation"); + expect(reconciled.lastRun).toMatchObject({ id: run.id, status: "breaks" }); + expect(reconciled.openBreaks.reconciliation).toBe(run.breaks.length); + + const recon = run.breaks[0]!; + concord.setNote("FUND", "recon", recon.key, { fingerprint: recon.fingerprint, status: "resolved", note: "ok" }); + expect(expectCurrent("a reconciliation sign-off").openBreaks.reconciliation).toBe(run.breaks.length - 1); + + const control = concord.controls("FUND").breaks[0]!; + concord.setNote("FUND", "controls", control.key, { + fingerprint: control.fingerprint, + status: "acknowledged", + note: "seen", + }); + expect(expectCurrent("a controls sign-off").openBreaks.controls).toBe(controlsBefore - 1); + + const action = await concord.createAction("FUND", { type: "dividend", recordTime: at(5), ratePerUnit: "0.1" }); + const withAction = expectCurrent("a corporate action"); + expect(withAction.openBreaks.actions).toBe(action.openBreaks); + expect(action.openBreaks).toBeGreaterThan(0); + const missing = action.result!.breaks[0]!; + concord.setNote("FUND", `action:${action.id}`, missing.key, { + fingerprint: missing.fingerprint, + status: "resolved", + note: "paid off-chain", + }); + expect(expectCurrent("an action sign-off").openBreaks.actions).toBe(action.openBreaks - 1); + + // A scheduled action that the indexer later reconciles on its own. + const later = await concord.createAction("FUND", { type: "split", recordTime: at(150), num: "2", den: "1" }); + expect(later.state).toBe("scheduled"); + chain.advance(100); + await concord.sync("FUND"); + expect(await concord.reconcileDue()).toBeGreaterThan(0); + expectCurrent("an action reconciled after a sync"); + + concord.deleteRegister("FUND", reg.registerId); + expect(expectCurrent("a deleted register").lastRun).toBeNull(); + + await concord.rebuild("FUND", { defer: true }).catch(() => {}); + expectCurrent("a deferred rebuild"); + await concord.sync("FUND").catch(() => {}); + expectCurrent("the sync after a rebuild"); + }); + + it("serves a poll of the overview without reading events, runs, actions or the controls log", async () => { + for (let i = 0; i < 10_000; i++) chain.push(assetId, "mint", 40 + (i % 50), { to: h3, amount: 1n }); + await concord.sync("FUND"); + concord.overview(); + + const statements: string[] = []; + const { all, get } = { all: concord.db.all.bind(concord.db), get: concord.db.get.bind(concord.db) }; + concord.db.all = ((sql: string, ...params: Parameters[1][]) => { + statements.push(sql); + return all(sql, ...params); + }) as Db["all"]; + concord.db.get = ((sql: string, ...params: Parameters[1][]) => { + statements.push(sql); + return get(sql, ...params); + }) as Db["get"]; + const fund = concord.overview().assets.find((a) => a.id === assetId)!; + expect(fund.eventCount).toBe(10_007); + expect(statements.length).toBeGreaterThan(0); + for (const sql of statements) { + expect(sql).not.toMatch(/\b(events|runs|actions|instructions|break_notes|openings)\b/); + } + }); + it("rounds holder shares half up to four decimals so two thirds and one third add to 100", async () => { const asset = await concord.watchAsset({ network: "testnet", asset: `THIRDS:${key()}`, fromLedger: 1 }); chain.push(asset.id, "mint", 3, { to: h1, amount: u(2) }); diff --git a/services/api/test/tenancy.test.ts b/services/api/test/tenancy.test.ts index 0b68212e..d2c83e5e 100644 --- a/services/api/test/tenancy.test.ts +++ b/services/api/test/tenancy.test.ts @@ -28,6 +28,7 @@ const ORG_MIGRATION_DIGESTS = [ "ece8f3334de957d19e76585727af4790c2f6ba78f60407ade9a67e1edb25cd55", "d440cffcfb710a703cdb8c0b02c4704aeaf366b2c254ffd5e7789e25898f6174", "b7413e3d4eee55f419c70db885e1866b95c8c1a2b7d7f68eea4e44ecac93e611", + "28743caac6abe8fc9008e045261e93007d585bfe550744169f8ee906c9f722fa", ]; const CONTROL_MIGRATION_DIGESTS = ["ba25bc5419cfcc376d2e7ff027845b2da4b789d9c7e966424b70cdfbbb90a422"];