Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Everything to date; Concord's history begins 2026-10 with the commits below.

### Added

- Per-asset register freshness limits (#561): setting `registerMaxAgeDays` makes `assetSummary` report `registerStale: { ageDays }` once the latest register is older than that many days. Off unless set. Adds `assets.register_max_age_days` (migration v4).
- 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,
Expand Down
1 change: 1 addition & 0 deletions docs/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ One row per watched asset.
| `synced_at` | TEXT, null | Close time of that ledger. |
| `sync_error`, `sync_error_at` | TEXT, null | Why the last pass failed, and when. Cleared by a successful pass. |
| `ignore_addresses` | TEXT (JSON) | Array of address strings left out of reconciliation. Default `'[]'`. |
| `register_max_age_days` | INTEGER, null | Flag the latest register as stale once it is older than this many days. `NULL` (the default) turns the check off. |
| `created_by` | TEXT, null | Label of the actor who started watching (`cli:<user>` or a session's person). |
| `created_at` | TEXT | |

Expand Down
9 changes: 8 additions & 1 deletion services/api/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ export function createApi(tenants: Tenants, auth: Auth, options: ApiOptions): Ho
ignore?: string[];
decimals?: number;
fromLedger?: number;
registerMaxAgeDays?: number;
}>(c);
if (!isNetworkName(input.network)) throw new Invalid("network must be mainnet or testnet");
// Without fromLedger the service works out where to start. With one it replays from there, as
Expand All @@ -214,14 +215,20 @@ export function createApi(tenants: Tenants, auth: Auth, options: ApiOptions): Ho
...(input.ignore !== undefined ? { ignore: input.ignore } : {}),
...(input.decimals !== undefined ? { decimals: input.decimals } : {}),
...(input.fromLedger !== undefined ? { fromLedger: input.fromLedger } : {}),
...(input.registerMaxAgeDays !== undefined ? { registerMaxAgeDays: input.registerMaxAgeDays } : {}),
},
{ defer: true, actor },
);
return c.json(ws.assetSummary(asset), 201);
});
priv.get("/assets/:id", (c) => c.json(c.var.ws.assetSummary(c.var.ws.asset(id(c)))));
priv.patch("/assets/:id", async (c) =>
c.json(c.var.ws.updateAsset(id(c), await jsonBody<{ name?: string; ignore?: string[] }>(c))),
c.json(
c.var.ws.updateAsset(
id(c),
await jsonBody<{ name?: string; ignore?: string[]; registerMaxAgeDays?: number | null }>(c),
),
),
);
priv.delete("/assets/:id", async (c) => {
owner(c);
Expand Down
56 changes: 52 additions & 4 deletions services/api/src/concord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ export interface AssetRecord {
syncError?: string;
syncErrorAt?: string;
ignore: string[];
/** Flag the latest register once it is older than this many days. Unset means the check is off. */
registerMaxAgeDays?: number;
createdAt: string;
}

Expand All @@ -92,6 +94,8 @@ export interface WatchInput {
baseline?: boolean;
/** Addresses outside the register, e.g. the issuer's distribution account. */
ignore?: string[];
/** Flag the latest register once it is older than this many days. Omitted means the check is off. */
registerMaxAgeDays?: number;
}

export type ActionType = "dividend" | "split" | "redemption";
Expand Down Expand Up @@ -174,6 +178,15 @@ interface ActionResult {
const now = () => new Date().toISOString();
const sha256 = (text: string) => createHash("sha256").update(text).digest("hex");
const MAX_REGISTER_CLOCK_SKEW_MS = 5 * 60_000;
const DAY_MS = 86_400_000;

/** A register freshness limit: whole days, long enough to be meaningful and short enough to be sane. */
function maxAgeDays(value: number): number {
if (!Number.isInteger(value) || value < 1 || value > 3650) {
throw new Invalid("registerMaxAgeDays must be a whole number of days from 1 to 3650");
}
return value;
}

function isoTime(input: string, field: string): string {
const t = Date.parse(input);
Expand Down Expand Up @@ -272,6 +285,9 @@ function toAsset(row: Row): AssetRecord {
ignore: JSON.parse(String(row.ignore_addresses)) as string[],
createdAt: String(row.created_at),
};
if (row.register_max_age_days !== null && row.register_max_age_days !== undefined) {
asset.registerMaxAgeDays = Number(row.register_max_age_days);
}
if (row.issuer) asset.issuer = String(row.issuer);
if (row.start_ledger !== null) asset.startLedger = Number(row.start_ledger);
if (row.baseline_ledger !== null) asset.baselineLedger = Number(row.baseline_ledger);
Expand Down Expand Up @@ -314,10 +330,16 @@ export class Concord {
constructor(
readonly db: Db,
readonly networks: Networks,
/** Wall clock, in milliseconds. Tests inject one so register age is deterministic. */
private readonly options: { now?: () => number } = {},
) {
this.seenVersion = db.dataVersion();
}

private nowMs(): number {
return (this.options.now ?? Date.now)();
}

/** Forget cached holdings for an asset this instance just changed. */
private touch(assetId: string): void {
this.stateMemo.delete(assetId);
Expand Down Expand Up @@ -394,6 +416,8 @@ export class Concord {
throw new Invalid(`${resolved.code} is already watched`);
}
const ignore = addresses(input.ignore, "ignore");
const registerMaxAge =
input.registerMaxAgeDays === undefined ? undefined : maxAgeDays(input.registerMaxAgeDays);
let name = label(input.name, "name");
let decimals = input.decimals;
if (input.fromLedger !== undefined && (!Number.isInteger(input.fromLedger) || input.fromLedger < 1)) {
Expand Down Expand Up @@ -437,8 +461,8 @@ export class Concord {
}
try {
this.db.insert(
`INSERT INTO assets (id, network, code, issuer, name, decimals, start_mode, state, start_ledger, ignore_addresses, created_by, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, 'indexing', ?, ?, ?, ?)`,
`INSERT INTO assets (id, network, code, issuer, name, decimals, start_mode, state, start_ledger, ignore_addresses, register_max_age_days, created_by, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, 'indexing', ?, ?, ?, ?, ?)`,
resolved.id,
input.network,
resolved.code,
Expand All @@ -448,6 +472,7 @@ export class Concord {
startMode,
input.fromLedger ?? null,
JSON.stringify(ignore),
registerMaxAge ?? null,
options.actor?.label ?? null,
now(),
);
Expand Down Expand Up @@ -519,13 +544,20 @@ export class Concord {
return this.asset(asset.id);
}

updateAsset(ref: string, patch: { name?: string; ignore?: string[] }): AssetRecord {
updateAsset(
ref: string,
patch: { name?: string; ignore?: string[]; registerMaxAgeDays?: number | null },
): AssetRecord {
const asset = this.asset(ref);
const name = label(patch.name, "name");
let registerMaxAge = asset.registerMaxAgeDays ?? null;
if (patch.registerMaxAgeDays === null) registerMaxAge = null;
else if (patch.registerMaxAgeDays !== undefined) registerMaxAge = maxAgeDays(patch.registerMaxAgeDays);
this.db.write(
"UPDATE assets SET name = ?, ignore_addresses = ? WHERE id = ?",
"UPDATE assets SET name = ?, ignore_addresses = ?, register_max_age_days = ? WHERE id = ?",
name ?? asset.name,
JSON.stringify(patch.ignore === undefined ? asset.ignore : addresses(patch.ignore, "ignore")),
registerMaxAge,
asset.id,
);
return this.asset(asset.id);
Expand Down Expand Up @@ -1814,12 +1846,21 @@ export class Concord {
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;
const latestRegister = this.db.get<{ as_of: string }>(
"SELECT as_of FROM registers WHERE asset_id = ? ORDER BY as_of DESC, id DESC LIMIT 1",
asset.id,
);
return {
...asset,
supply: formatUnits(state.supply, asset.decimals),
holderCount: state.balances.size,
eventCount: events,
incomplete: state.incomplete.length > 0,
// A register nobody has refreshed is the attention item a timer-free service cannot raise itself.
registerStale:
asset.registerMaxAgeDays === undefined || !latestRegister
? null
: this.registerAge(latestRegister.as_of, asset.registerMaxAgeDays),
lastRun: run && { id: run.id, asOf: run.asOf, status: run.status, openBreaks: run.openBreaks },
openBreaks: {
reconciliation: run?.openBreaks ?? 0,
Expand All @@ -1829,6 +1870,13 @@ export class Concord {
};
}

/** How far past its limit a register is, or null while it is still fresh enough. */
private registerAge(asOf: string, limitDays: number): { ageDays: number } | null {
const ageMs = this.nowMs() - Date.parse(asOf);
if (!(ageMs > limitDays * DAY_MS)) return null;
return { ageDays: Math.floor(ageMs / DAY_MS) };
}

/** 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);
Expand Down
4 changes: 4 additions & 0 deletions services/api/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,10 @@ INSERT INTO break_note_history (asset_id, scope, key, fingerprint, status, note,
// v3: keep the recurring reconcileDue search off reconciled action rows.
`
CREATE INDEX actions_due ON actions (record_time) WHERE snapshot IS NULL;
`,
// v4: per-asset register freshness limit. NULL means the stale-register check is off.
`
ALTER TABLE assets ADD COLUMN register_max_age_days INTEGER;
`,
];

Expand Down
Binary file added services/api/test/fixtures/db/org-v4.db
Binary file not shown.
5 changes: 5 additions & 0 deletions services/api/test/fixtures/make-db-fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ build(join(outDir, "org-v3.db"), ORG_MIGRATIONS.slice(0, 3), (db) => {
db.exec("INSERT INTO meta (key, value) VALUES ('fixture', 'org-v3')");
});

// Freeze the v4 schema for future upgrade-compatibility checks.
build(join(outDir, "org-v4.db"), ORG_MIGRATIONS.slice(0, 4), (db) => {
db.exec("INSERT INTO meta (key, value) VALUES ('fixture', 'org-v4')");
});

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')`);
Expand Down
49 changes: 49 additions & 0 deletions services/api/test/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,55 @@ describe("Concord", () => {
expect(concord.registers("FUND")).toHaveLength(2);
});

it("flags a register only once it is older than the asset's registerMaxAgeDays", async () => {
const clock = { value: Date.parse("2026-10-10T00:00:00Z") };
const ws = new Concord(new Db(":memory:"), { testnet: { passphrase: PASSPHRASE, chain } }, { now: () => clock.value });
const asset = await ws.watchAsset({ network: "testnet", asset: `AGE:${issuer}`, fromLedger: 1, registerMaxAgeDays: 5 });
expect(asset.registerMaxAgeDays).toBe(5);

ws.importRegister("AGE", { csv: `holder_id,account,units\nA,${h1},90\n`, asOf: "2026-10-05T00:00:00Z" });

// Exactly five days old: the limit has not been exceeded, so there is nothing to flag.
expect(ws.assetSummary(ws.asset("AGE")).registerStale).toBeNull();

// One millisecond more is enough, and the injected clock is what decides it.
clock.value += 1;
expect(ws.assetSummary(ws.asset("AGE")).registerStale).toEqual({ ageDays: 5 });

clock.value = Date.parse("2026-10-12T00:00:00Z");
expect(ws.assetSummary(ws.asset("AGE")).registerStale).toEqual({ ageDays: 7 });
expect(ws.overview().assets.find((a) => a.code === "AGE")!.registerStale).toEqual({ ageDays: 7 });
});

it("leaves the stale-register check off by default and lets the limit be changed or cleared", async () => {
const clock = { value: Date.parse("2027-01-01T00:00:00Z") };
const ws = new Concord(new Db(":memory:"), { testnet: { passphrase: PASSPHRASE, chain } }, { now: () => clock.value });
const asset = await ws.watchAsset({ network: "testnet", asset: `AGE:${issuer}`, fromLedger: 1 });
expect(asset.registerMaxAgeDays).toBeUndefined();
// No register at all cannot be stale, and the check is off besides.
expect(ws.assetSummary(asset).registerStale).toBeNull();

ws.importRegister("AGE", { csv: `holder_id,account,units\nA,${h1},90\n`, asOf: "2026-10-05T00:00:00Z" });
// Default off: an old register is not flagged until a limit is set.
expect(ws.assetSummary(ws.asset("AGE")).registerStale).toBeNull();

expect(ws.updateAsset("AGE", { registerMaxAgeDays: 30 }).registerMaxAgeDays).toBe(30);
expect(ws.assetSummary(ws.asset("AGE")).registerStale).toEqual({ ageDays: 88 });

// null turns the check back off; the stored value stops being reported.
expect(ws.updateAsset("AGE", { registerMaxAgeDays: null }).registerMaxAgeDays).toBeUndefined();
expect(ws.assetSummary(ws.asset("AGE")).registerStale).toBeNull();

for (const bad of [0, -1, 1.5, 3651]) {
expect(() => ws.updateAsset("AGE", { registerMaxAgeDays: bad }), `limit ${bad}`).toThrow(Invalid);
}
await expect(
ws.watchAsset({ network: "testnet", asset: `BAD:${issuer}`, fromLedger: 1, registerMaxAgeDays: 0 }),
).rejects.toThrow(new Invalid("registerMaxAgeDays must be a whole number of days from 1 to 3650"));
// A refused setting leaves no asset behind.
expect(ws.assets().map((a) => a.code)).toEqual(["AGE"]);
});

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) });
Expand Down
1 change: 1 addition & 0 deletions services/api/test/tenancy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const ORG_MIGRATION_DIGESTS = [
"1a4f90d62ead1ba8254ab3244d04be0ca9f46646df78cd12f1ece6db41bd2387",
"2002f2e1b269939a38de8da3768a85787f98ce207246cf15134423ffdce6db72",
"ece8f3334de957d19e76585727af4790c2f6ba78f60407ade9a67e1edb25cd55",
"106dfc93f9440067a3f7b9045ce7389ea7409440490d9c059e00f90f596e1db5",
];
const CONTROL_MIGRATION_DIGESTS = ["ba25bc5419cfcc376d2e7ff027845b2da4b789d9c7e966424b70cdfbbb90a422"];

Expand Down
Loading