Files
wikideck/scripts/custody-db.ts
T
2026-10-20 15:21:47 -04:00

40 lines
2.4 KiB
TypeScript
Executable File

import { Pool } from 'pg';
import { open, unlink, mkdir } from 'node:fs/promises';
import { resolve, join } from 'node:path';
import { postgresConfig } from '../server/market/postgres-config.ts';
import { migrateCustody, grantCustodyRuntime } from '../server/market/postgres-schema.ts';
import { importSqliteCustody } from '../server/market/custody-import.ts';
import { PostgresCustody } from '../server/market/postgres-custody.ts';
import { IS_MAINNET } from '../shared/network.ts';
// Explicit operator task, never invoked by node startup. No passwords or database URLs printed.
if (IS_MAINNET) throw new Error('Only sandbox financial schema operations are implemented');
const [action, argument] = process.argv.slice(2);
if (!['migrate', 'grant-runtime', 'import-sqlite', 'audit'].includes(action)) throw new Error('Expected migrate, grant-runtime ROLE, import-sqlite DATA_DIR, or audit');
try {
const config = await postgresConfig();
if (action === 'audit') {
const market = await PostgresCustody.open(config, { feeBps: 250, card: () => undefined });
try { console.log(JSON.stringify(await market.audit())); } finally { await market.close(); }
} else {
const pool = new Pool(config);
try {
if (action === 'migrate') { await migrateCustody(pool); console.log('Custody PostgreSQL schema verified/migrated. No funds activated.'); }
if (action === 'grant-runtime') { await grantCustodyRuntime(pool, argument ?? ''); console.log('Runtime grants applied; no credentials printed.'); }
if (action === 'import-sqlite') {
if (!argument) throw new Error('Stopped source node DATA_DIR required');
const directory = resolve(argument);
await mkdir(directory, { recursive: true, mode: 0o700 });
const lockPath = join(directory, 'testnet-node.lock'), lock = await open(lockPath, 'wx', 0o600);
try {
await lock.writeFile(`custody-import:${process.pid}`);
console.log(JSON.stringify(await importSqliteCustody(join(directory, 'testnet', 'custody-sandbox.sqlite'), pool)));
} finally { await lock.close(); await unlink(lockPath); }
}
} finally { await pool.end(); }
}
} catch {
console.error('Custody database operation failed. Check configuration, schema, stopped-node lock and migration state privately. No automatic fallback/reset was performed.');
process.exitCode = 1;
}