import { randomUUID } from "node:crypto"; import type { AccountKind, LedgerStore, Posting, Transaction } from "./types.js"; export class LedgerError extends Error {} /** * Double-entry ledger. Sign convention: wallet balance = -(sum of postings) on the * user_wallet account (liability, credit-normal). Every transaction sums to zero. */ export class Ledger { constructor(private store: LedgerStore) {} static validate(postings: Posting[]): void { if (postings.length < 2) throw new LedgerError("transaction needs >= 2 postings"); for (const p of postings) { if (!Number.isSafeInteger(p.amount) || p.amount === 0) throw new LedgerError("amounts must be non-zero integers (minor units)"); } const sum = postings.reduce((s, p) => s + p.amount, 0); if (sum !== 0) throw new LedgerError(`unbalanced transaction (sum=${sum})`); } account(userId: string, kind: AccountKind, currency = "usd") { return this.store.getOrCreateAccount(userId, kind, currency.toLowerCase()); } async walletBalance(userId: string, currency = "usd"): Promise { const acct = await this.account(userId, "user_wallet", currency); return -(await this.store.balance(acct.id)); } async post(input: Omit): Promise { Ledger.validate(input.postings); const existing = await this.store.findTransactionByKey(input.user_id, input.idempotency_key); if (existing) return existing; const tx: Transaction = { ...input, id: randomUUID(), created_at: new Date().toISOString() }; await this.store.insertTransaction(tx); return tx; } /** Credit wallet from a confirmed Stripe TEST payment. */ async recordFunding(userId: string, amount: number, currency: string, stripeRef: string) { if (amount <= 0) throw new LedgerError("funding amount must be positive"); const clearing = await this.account(userId, "stripe_clearing", currency); const wallet = await this.account(userId, "user_wallet", currency); return this.post({ user_id: userId, kind: "funding", idempotency_key: `stripe:${stripeRef}`, memo: "Stripe test funding", postings: [{ account_id: clearing.id, amount }, { account_id: wallet.id, amount: -amount }], }); } /** TEST-mode only: simulated deposit so the wallet is usable before Stripe keys exist. */ async recordTestCredit(userId: string, amount: number, currency = "usd") { if (!Number.isSafeInteger(amount) || amount < 1 || amount > 100_000) throw new LedgerError("test credit must be 1..100000 minor units"); const clearing = await this.account(userId, "stripe_clearing", currency); const wallet = await this.account(userId, "user_wallet", currency); return this.post({ user_id: userId, kind: "funding", idempotency_key: `test-credit:${randomUUID()}`, memo: "Test credit (simulated, no Stripe)", postings: [{ account_id: clearing.id, amount }, { account_id: wallet.id, amount: -amount }], }); } list(userId: string, limit = 50) { return this.store.listTransactions(userId, limit); } }