@fiderail/db 0.0.0-stage → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FideRail Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # @fiderail/db
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Storage abstraction and Ed25519 state-root signing for [FideRail](https://fiderail.com): monthly-partitioned PostgreSQL 16 primary repository (`NUMERIC(78,0)` amounts and SQL DDL), local SQLite WAL repository, lossless SQLite-to-PostgreSQL migrator, baseline snapshot loader, and Ed25519 Merkle `stateRoot` signer and verifier.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @fiderail/db
9
+ ```
10
+
11
+ ## Quick Usage
12
+
13
+ ```ts
14
+ import {
15
+ openFideRailRepository,
16
+ openSqliteRepository,
17
+ verifyStateRootEd25519,
18
+ } from "@fiderail/db";
19
+
20
+ // Uses PostgreSQL 16 when DATABASE_URL is set, else SQLite WAL (FIDERAIL_DB_PATH)
21
+ const repo = (await openFideRailRepository()) ?? openSqliteRepository(":memory:");
22
+ const latestRoot = await repo.getLatestStateRoot("base");
23
+
24
+ if (latestRoot && process.env.FIDERAIL_STATE_ROOT_PUBLIC_KEY_PEM) {
25
+ console.log(verifyStateRootEd25519(latestRoot, process.env.FIDERAIL_STATE_ROOT_PUBLIC_KEY_PEM));
26
+ }
27
+ await repo.close();
28
+ ```
29
+
30
+ ## Key Exports
31
+
32
+ - **Repositories**: `openFideRailRepository`, `openPostgresRepository`, `openSqliteRepository`, `getPostgresInitDdl`, `POSTGRES_DDL_PATH`
33
+ - **Migration & Baselines**: `migrateSqliteToRepository`, `loadBaselineSnapshots`, `DEFAULT_DATA_DIR`
34
+ - **Ed25519 State-Root Signing**: `STATE_ROOT_SIGNING_FORMAT`, `createStateRootSigningPayload`, `deriveStateRootPublicKey`, `signStateRootEd25519`, `verifyStateRootEd25519`
35
+
36
+ Includes PostgreSQL 16 schema initialization SQL at `sql/001_init_v2.sql`.
37
+
38
+ ## Runtime Requirements
39
+
40
+ Requires **Node.js `>= 22.13.0`** (uses built-in `node:sqlite` and `node:crypto`). PostgreSQL 16 is supported via `pg` when `DATABASE_URL` is configured.
41
+
42
+ ## Links
43
+
44
+ - Portal: [https://fiderail.com](https://fiderail.com)
45
+ - Documentation: [https://fiderail.com/docs](https://fiderail.com/docs)
46
+ - Source (GitLab): [https://gitlab.com/fiderail/fiderail](https://gitlab.com/fiderail/fiderail)
47
+ - Mirror (GitHub): [https://github.com/fiderail/fiderail](https://github.com/fiderail/fiderail)
48
+
49
+ ## License
50
+
51
+ [MIT](./LICENSE)
@@ -0,0 +1,4 @@
1
+ import { type BaselineSnapshots } from "@fiderail/core";
2
+ export declare const DEFAULT_DATA_DIR: string;
3
+ export declare function loadBaselineSnapshots(dataDir?: string): BaselineSnapshots;
4
+ //# sourceMappingURL=baseline.d.ts.map
@@ -0,0 +1,152 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { normalizeChainAddress } from "@fiderail/spec";
5
+ import { createEmptyBaselineSnapshots, deriveTrustTier, } from "@fiderail/core";
6
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
+ export const DEFAULT_DATA_DIR = path.resolve(__dirname, "..", "..", "..", "data");
8
+ function readJsonIfExists(filePath) {
9
+ if (!fs.existsSync(filePath))
10
+ return null;
11
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
12
+ }
13
+ export function loadBaselineSnapshots(dataDir = DEFAULT_DATA_DIR) {
14
+ const snapshots = createEmptyBaselineSnapshots();
15
+ const round2 = readJsonIfExists(path.join(dataDir, "crosschain-empirical-round2.json"));
16
+ const round1 = readJsonIfExists(path.join(dataDir, "x402-empirical-snapshot.json"));
17
+ snapshots.round2GeneratedAt = round2?.generatedAt || null;
18
+ snapshots.round1GeneratedAt = round1?.generatedAt || null;
19
+ snapshots.observedDailyBaseline = {
20
+ basePermit2ProxyTx24h: round2?.base?.permit2Proxy?.projectedTxPer24h ?? null,
21
+ baseEip3009Tx24h: round2?.base?.eip3009Usdc?.projectedTxPer24h ?? null,
22
+ solanaPayAiTx24h: round2?.solana?.facilitators
23
+ ? Number(round2.solana.facilitators
24
+ .reduce((s, f) => s + f.projectedTxPer24h, 0)
25
+ .toFixed(1))
26
+ : null,
27
+ };
28
+ const baseIndex = snapshots.profilesByChain.base;
29
+ const solanaIndex = snapshots.profilesByChain.solana;
30
+ if (round2?.base) {
31
+ const knownSet = new Set((round2.base.creditGraphKnownX402?.topPayees || []).map((p) => normalizeChainAddress("base", p.payee)));
32
+ for (const p of round2.base.creditGraphAll?.topPayees || []) {
33
+ const addr = normalizeChainAddress("base", p.payee);
34
+ const profile = {
35
+ chain: "base",
36
+ address: addr,
37
+ creditScore: p.creditScore,
38
+ tier: deriveTrustTier(p.creditScore, p.riskFlags || []),
39
+ channels: knownSet.has(addr) ? ["base_x402_permit2", "base_eip3009"] : ["base_eip3009"],
40
+ metrics: {
41
+ txCount: p.txCount,
42
+ totalUsdc: p.totalUsdc,
43
+ totalUsd: p.totalUsdc,
44
+ uniquePayers: p.uniquePayers,
45
+ medianTicketUsdc: p.medianTicketUsdc,
46
+ hhi: p.hhi,
47
+ top1PayerShare: p.top1PayerShare,
48
+ activeSpanHours: p.activeSpanHours ?? 0,
49
+ activeUtcDays: p.activeUtcDays ?? 1,
50
+ },
51
+ riskFlags: [...(p.riskFlags || [])],
52
+ erc8004Registered: false,
53
+ firstSeenAt: null,
54
+ lastSeenAt: null,
55
+ sourceSnapshot: round2.generatedAt || null,
56
+ source: "empirical_snapshot",
57
+ };
58
+ baseIndex.set(addr, profile);
59
+ }
60
+ for (const p of round2.base.creditGraphKnownX402?.topPayees || []) {
61
+ const addr = normalizeChainAddress("base", p.payee);
62
+ if (!baseIndex.has(addr)) {
63
+ baseIndex.set(addr, {
64
+ chain: "base",
65
+ address: addr,
66
+ creditScore: p.creditScore,
67
+ tier: deriveTrustTier(p.creditScore, p.riskFlags || []),
68
+ channels: ["base_x402_permit2"],
69
+ metrics: {
70
+ txCount: p.txCount,
71
+ totalUsdc: p.totalUsdc,
72
+ totalUsd: p.totalUsdc,
73
+ uniquePayers: p.uniquePayers,
74
+ medianTicketUsdc: p.medianTicketUsdc,
75
+ hhi: p.hhi,
76
+ top1PayerShare: p.top1PayerShare,
77
+ activeSpanHours: p.activeSpanHours ?? 0,
78
+ activeUtcDays: p.activeUtcDays ?? 1,
79
+ },
80
+ riskFlags: [...(p.riskFlags || [])],
81
+ erc8004Registered: false,
82
+ firstSeenAt: null,
83
+ lastSeenAt: null,
84
+ sourceSnapshot: round2.generatedAt || null,
85
+ source: "empirical_snapshot",
86
+ });
87
+ }
88
+ }
89
+ }
90
+ if (round2?.solana?.creditGraph?.topPayees) {
91
+ for (const p of round2.solana.creditGraph.topPayees) {
92
+ const addr = normalizeChainAddress("solana", p.payee);
93
+ solanaIndex.set(addr, {
94
+ chain: "solana",
95
+ address: addr,
96
+ creditScore: p.creditScore,
97
+ tier: deriveTrustTier(p.creditScore, p.riskFlags || []),
98
+ channels: ["solana_x402_payai"],
99
+ metrics: {
100
+ txCount: p.txCount,
101
+ totalUsdc: p.totalUsdc,
102
+ totalUsd: p.totalUsdc,
103
+ uniquePayers: p.uniquePayers,
104
+ medianTicketUsdc: p.medianTicketUsdc,
105
+ hhi: p.hhi,
106
+ top1PayerShare: p.top1PayerShare,
107
+ activeSpanHours: p.activeSpanHours ?? 0,
108
+ activeUtcDays: p.activeUtcDays ?? 1,
109
+ },
110
+ riskFlags: [...(p.riskFlags || [])],
111
+ erc8004Registered: false,
112
+ firstSeenAt: null,
113
+ lastSeenAt: null,
114
+ sourceSnapshot: round2.generatedAt || null,
115
+ source: "empirical_snapshot",
116
+ });
117
+ }
118
+ }
119
+ if (round1?.topPayees) {
120
+ for (const p of round1.topPayees) {
121
+ const addr = normalizeChainAddress("solana", p.payee);
122
+ if (!solanaIndex.has(addr)) {
123
+ solanaIndex.set(addr, {
124
+ chain: "solana",
125
+ address: addr,
126
+ creditScore: p.creditScore,
127
+ tier: deriveTrustTier(p.creditScore, p.riskFlags || []),
128
+ channels: ["solana_x402_round1"],
129
+ metrics: {
130
+ txCount: p.txCount,
131
+ totalUsdc: p.totalUsdc,
132
+ totalUsd: p.totalUsdc,
133
+ uniquePayers: p.uniquePayers,
134
+ medianTicketUsdc: p.medianTicketUsdc,
135
+ hhi: p.hhi,
136
+ top1PayerShare: p.top1PayerShare,
137
+ activeSpanHours: 0,
138
+ activeUtcDays: 1,
139
+ },
140
+ riskFlags: [...(p.riskFlags || [])],
141
+ erc8004Registered: false,
142
+ firstSeenAt: null,
143
+ lastSeenAt: null,
144
+ sourceSnapshot: round1.generatedAt || null,
145
+ source: "empirical_snapshot",
146
+ });
147
+ }
148
+ }
149
+ }
150
+ return snapshots;
151
+ }
152
+ //# sourceMappingURL=baseline.js.map
@@ -0,0 +1,20 @@
1
+ import type { FideRailRepository } from "@fiderail/core";
2
+ import { type PostgresRepositoryOptions } from "./postgres-repo.js";
3
+ export * from "./baseline.js";
4
+ export * from "./state-root-signer.js";
5
+ export * from "./sqlite-repo.js";
6
+ export * from "./postgres-repo.js";
7
+ export * from "./migrate-sqlite-to-pg.js";
8
+ export interface OpenRepositoryOptions {
9
+ databaseUrl?: string;
10
+ dbPath?: string;
11
+ postgresOptions?: Omit<PostgresRepositoryOptions, "connectionString">;
12
+ }
13
+ /**
14
+ * Unified storage factory:
15
+ * - Uses PostgreSQL 16 when `databaseUrl` (or `DATABASE_URL`) is configured;
16
+ * - Falls back to local SQLite WAL when `dbPath` (or `FIDERAIL_DB_PATH`) is configured;
17
+ * - Returns null when neither is provided (static snapshot mode).
18
+ */
19
+ export declare function openFideRailRepository(options?: OpenRepositoryOptions): Promise<FideRailRepository | null>;
20
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,28 @@
1
+ import { openPostgresRepository } from "./postgres-repo.js";
2
+ import { openSqliteRepository } from "./sqlite-repo.js";
3
+ export * from "./baseline.js";
4
+ export * from "./state-root-signer.js";
5
+ export * from "./sqlite-repo.js";
6
+ export * from "./postgres-repo.js";
7
+ export * from "./migrate-sqlite-to-pg.js";
8
+ /**
9
+ * Unified storage factory:
10
+ * - Uses PostgreSQL 16 when `databaseUrl` (or `DATABASE_URL`) is configured;
11
+ * - Falls back to local SQLite WAL when `dbPath` (or `FIDERAIL_DB_PATH`) is configured;
12
+ * - Returns null when neither is provided (static snapshot mode).
13
+ */
14
+ export async function openFideRailRepository(options = {}) {
15
+ const databaseUrl = options.databaseUrl ?? process.env.DATABASE_URL;
16
+ if (databaseUrl && databaseUrl.trim()) {
17
+ return openPostgresRepository({
18
+ connectionString: databaseUrl.trim(),
19
+ ...options.postgresOptions,
20
+ });
21
+ }
22
+ const dbPath = options.dbPath ?? process.env.FIDERAIL_DB_PATH;
23
+ if (dbPath && dbPath.trim()) {
24
+ return openSqliteRepository(dbPath.trim());
25
+ }
26
+ return null;
27
+ }
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=migrate-cli.d.ts.map
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env node
2
+ import { openPostgresRepository } from "./postgres-repo.js";
3
+ import { migrateSqliteToRepository } from "./migrate-sqlite-to-pg.js";
4
+ async function main() {
5
+ const sqlitePath = process.argv[2] || process.env.FIDERAIL_SQLITE_SOURCE_PATH || process.env.FIDERAIL_DB_PATH;
6
+ const databaseUrl = process.argv[3] || process.env.DATABASE_URL;
7
+ if (!sqlitePath || !databaseUrl) {
8
+ console.error("Usage: npm run migrate:sqlite-to-pg -- <sqlite_backup_path> <postgres_database_url>");
9
+ console.error("Or set FIDERAIL_SQLITE_SOURCE_PATH and DATABASE_URL env vars.");
10
+ process.exit(1);
11
+ }
12
+ console.log(`[FideRail Migrator] Source SQLite: ${sqlitePath}`);
13
+ const pgRepo = await openPostgresRepository({ connectionString: databaseUrl, autoInitSchema: true });
14
+ try {
15
+ const report = await migrateSqliteToRepository({
16
+ sqlitePath,
17
+ targetRepo: pgRepo,
18
+ onProgress: ({ stage, paymentsRead, paymentsInserted }) => {
19
+ console.log(`[FideRail Migrator] ${stage}: read=${paymentsRead ?? 0} inserted=${paymentsInserted ?? 0}`);
20
+ },
21
+ verifyTargetParity: async (chain) => {
22
+ const res = await pgRepo.executor.query(`SELECT COUNT(*)::text AS cnt, COALESCE(SUM(amount_usd), 0)::text AS total_usd
23
+ FROM payments WHERE chain_key = $1`, [chain]);
24
+ return {
25
+ count: Number(res.rows[0]?.cnt || 0),
26
+ totalUsd: Number(res.rows[0]?.total_usd || 0),
27
+ };
28
+ },
29
+ });
30
+ console.log(JSON.stringify(report, null, 2));
31
+ if (!report.parityPassed) {
32
+ console.error("[FideRail Migrator] ERROR: Parity verification FAILED!");
33
+ process.exit(2);
34
+ }
35
+ console.log("[FideRail Migrator] Parity verification PASSED 100%.");
36
+ }
37
+ finally {
38
+ await pgRepo.close();
39
+ }
40
+ }
41
+ main().catch((err) => {
42
+ console.error(`[FideRail Migrator] Fatal error: ${err.message}`);
43
+ process.exit(1);
44
+ });
45
+ //# sourceMappingURL=migrate-cli.js.map
@@ -0,0 +1,44 @@
1
+ import { type ChainKey } from "@fiderail/spec";
2
+ import type { FideRailRepository } from "@fiderail/core";
3
+ export interface MigrationChainParity {
4
+ chain: ChainKey;
5
+ sourcePayments: number;
6
+ targetPayments: number;
7
+ sourceTotalUsd: number;
8
+ targetTotalUsd: number;
9
+ matched: boolean;
10
+ }
11
+ export interface MigrationReport {
12
+ paymentsRead: number;
13
+ paymentsInserted: number;
14
+ identitiesMigrated: number;
15
+ capabilitiesMigrated: number;
16
+ livenessMigrated: number;
17
+ stateKeysMigrated: number;
18
+ recomputedChains: ChainKey[];
19
+ parityByChain: MigrationChainParity[];
20
+ parityPassed: boolean;
21
+ }
22
+ /**
23
+ * Lossless streaming migration from a SQLite database snapshot into any
24
+ * FideRailRepository target (PostgreSQL 16 in production, or an in-memory/test target).
25
+ *
26
+ * Streams rows via `stmt.iterate()` in bounded batches so 1M+ rows migrate with minimal RAM,
27
+ * then executes automated per-chain row-count & total-USD parity verification.
28
+ */
29
+ export declare function migrateSqliteToRepository(options: {
30
+ sqlitePath: string;
31
+ targetRepo: FideRailRepository;
32
+ batchSize?: number;
33
+ recomputeAfterMigration?: boolean;
34
+ onProgress?: (info: {
35
+ stage: string;
36
+ paymentsRead?: number;
37
+ paymentsInserted?: number;
38
+ }) => void;
39
+ verifyTargetParity?: (chain: ChainKey) => Promise<{
40
+ count: number;
41
+ totalUsd: number;
42
+ }>;
43
+ }): Promise<MigrationReport>;
44
+ //# sourceMappingURL=migrate-sqlite-to-pg.d.ts.map