@tofound/billing 0.0.0-stage → 0.1.0

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE +3 -0
  3. package/README.md +34 -2
  4. package/dist/domain/errors.d.ts +14 -0
  5. package/dist/domain/errors.js +21 -0
  6. package/dist/domain/money.d.ts +21 -0
  7. package/dist/domain/money.js +77 -0
  8. package/dist/domain/types.d.ts +165 -0
  9. package/dist/domain/types.js +18 -0
  10. package/dist/drizzle/index.d.ts +3 -0
  11. package/dist/drizzle/index.js +3 -0
  12. package/dist/drizzle/schema-factory.d.ts +586 -0
  13. package/dist/drizzle/schema-factory.js +206 -0
  14. package/dist/drizzle/store.d.ts +20 -0
  15. package/dist/drizzle/store.js +124 -0
  16. package/dist/inbox/apply.d.ts +48 -0
  17. package/dist/inbox/apply.js +299 -0
  18. package/dist/inbox/conformance.d.ts +20 -0
  19. package/dist/inbox/conformance.js +254 -0
  20. package/dist/inbox/drizzle.d.ts +14 -0
  21. package/dist/inbox/drizzle.js +203 -0
  22. package/dist/inbox/ingest.d.ts +108 -0
  23. package/dist/inbox/ingest.js +404 -0
  24. package/dist/inbox/memory.d.ts +13 -0
  25. package/dist/inbox/memory.js +172 -0
  26. package/dist/inbox/ports.d.ts +150 -0
  27. package/dist/inbox/ports.js +1 -0
  28. package/dist/inbox/redact.d.ts +2 -0
  29. package/dist/inbox/redact.js +47 -0
  30. package/dist/inbox/schema.d.ts +1158 -0
  31. package/dist/inbox/schema.js +90 -0
  32. package/dist/inbox/watermark.d.ts +13 -0
  33. package/dist/inbox/watermark.js +6 -0
  34. package/dist/index.d.ts +20 -0
  35. package/dist/index.js +18 -0
  36. package/dist/ledger/ledger.d.ts +47 -0
  37. package/dist/ledger/ledger.js +224 -0
  38. package/dist/ports/index.d.ts +2 -0
  39. package/dist/ports/index.js +1 -0
  40. package/dist/ports/ledger-store.d.ts +53 -0
  41. package/dist/ports/ledger-store.js +1 -0
  42. package/dist/ports/runtime.d.ts +9 -0
  43. package/dist/ports/runtime.js +1 -0
  44. package/dist/providers/port.d.ts +201 -0
  45. package/dist/providers/port.js +30 -0
  46. package/dist/providers/sepay/index.d.ts +34 -0
  47. package/dist/providers/sepay/index.js +241 -0
  48. package/dist/providers/sepay/order.d.ts +32 -0
  49. package/dist/providers/sepay/order.js +69 -0
  50. package/dist/providers/sepay/signature.d.ts +8 -0
  51. package/dist/providers/sepay/signature.js +51 -0
  52. package/dist/quote/conformance.d.ts +16 -0
  53. package/dist/quote/conformance.js +39 -0
  54. package/dist/quote/index.d.ts +3 -0
  55. package/dist/quote/index.js +3 -0
  56. package/dist/quote/steps.d.ts +54 -0
  57. package/dist/quote/steps.js +103 -0
  58. package/dist/quote/waterfall.d.ts +98 -0
  59. package/dist/quote/waterfall.js +82 -0
  60. package/dist/stores/conformance.d.ts +22 -0
  61. package/dist/stores/conformance.js +269 -0
  62. package/dist/stores/memory.d.ts +19 -0
  63. package/dist/stores/memory.js +137 -0
  64. package/dist/stores/testing.d.ts +11 -0
  65. package/dist/stores/testing.js +11 -0
  66. package/docs/API.md +198 -0
  67. package/docs/SCHEMA.md +108 -0
  68. package/package.json +75 -4
@@ -0,0 +1,269 @@
1
+ import { isBillingError } from '../domain/errors.js';
2
+ import { createLedger } from '../ledger/ledger.js';
3
+ /** Checks I1, I2, I6 and seq contiguity for one account; throws on violation. */
4
+ export async function assertLedgerInvariants(store, accountId) {
5
+ const reader = store.reader();
6
+ const account = await reader.getAccount(accountId);
7
+ const entries = (await reader.listEntries(accountId, { limit: 1_000_000 })).reverse();
8
+ let balance = 0;
9
+ entries.forEach((entry, i) => {
10
+ check(entry.seq === i + 1, `seq ${entry.seq} at position ${i + 1} (I1 contiguity)`);
11
+ balance += entry.delta;
12
+ check(entry.balanceAfter === balance, `entry ${entry.seq} balanceAfter ${entry.balanceAfter} ≠ running Σ ${balance} (I1)`);
13
+ check(entry.balanceAfter >= 0, `entry ${entry.seq} balanceAfter ${entry.balanceAfter} < 0 (I2)`);
14
+ });
15
+ const expected = account?.balance ?? 0;
16
+ check(expected === balance, `account balance ${expected} ≠ Σ delta ${balance} (I6)`);
17
+ check((account?.seq ?? 0) === entries.length, `account seq ${account?.seq} ≠ entry count ${entries.length}`);
18
+ }
19
+ function check(ok, message) {
20
+ if (!ok)
21
+ throw new Error(`ledger conformance: ${message}`);
22
+ }
23
+ function equal(actual, expected, what) {
24
+ check(Object.is(actual, expected) || actual === expected, `${what}: expected ${String(expected)}, got ${String(actual)}`);
25
+ }
26
+ async function rejects(promise, code, what) {
27
+ try {
28
+ await promise;
29
+ }
30
+ catch (error) {
31
+ check(isBillingError(error, code), `${what}: expected ${code}, got ${error instanceof Error ? error.message : String(error)}`);
32
+ return error.details;
33
+ }
34
+ throw new Error(`ledger conformance: ${what}: expected ${code}, but it resolved`);
35
+ }
36
+ const ROLLBACK = new Error('conformance rollback');
37
+ export const ledgerConformanceCases = [
38
+ {
39
+ name: 'credits and debits keep balance = last balanceAfter = Σ delta with contiguous seq',
40
+ async run({ store, newAccountId }) {
41
+ const ledger = createLedger({ store });
42
+ const a = newAccountId();
43
+ await ledger.credit({ accountId: a, kind: 'topup', amount: 1_000, idempotencyKey: `t:${a}:1` });
44
+ await ledger.debit({ accountId: a, kind: 'spend', amount: 300, idempotencyKey: `t:${a}:2`, reason: 'job', source: { type: 'job', id: 'j1' } });
45
+ const last = await ledger.credit({ accountId: a, kind: 'grant', amount: 50, idempotencyKey: `t:${a}:3`, meta: { note: 'welcome' } });
46
+ equal(last.entry.seq, 3, 'seq');
47
+ equal(last.entry.balanceAfter, 750, 'balanceAfter');
48
+ equal(await ledger.balance(a), 750, 'balance');
49
+ const page = await ledger.entries(a);
50
+ equal(page.entries.length, 3, 'entries');
51
+ equal(page.entries[1]?.sourceType, 'job', 'sourceType round-trip');
52
+ equal(page.entries[1]?.reason, 'job', 'reason round-trip');
53
+ equal(page.entries[0]?.meta?.note, 'welcome', 'meta round-trip');
54
+ await assertLedgerInvariants(store, a);
55
+ },
56
+ },
57
+ {
58
+ name: 'the same key with the same intent replays the original entry (I3)',
59
+ async run({ store, newAccountId }) {
60
+ const ledger = createLedger({ store });
61
+ const a = newAccountId();
62
+ const first = await ledger.credit({ accountId: a, kind: 'topup', amount: 500, idempotencyKey: `r:${a}` });
63
+ const again = await ledger.credit({ accountId: a, kind: 'topup', amount: 500, idempotencyKey: `r:${a}` });
64
+ equal(again.replayed, true, 'replayed');
65
+ equal(again.entry.id, first.entry.id, 'entry id');
66
+ equal(again.events.length, 0, 'replay events');
67
+ equal(await ledger.balance(a), 500, 'balance after replay');
68
+ await assertLedgerInvariants(store, a);
69
+ },
70
+ },
71
+ {
72
+ name: 'the same key with a different account, amount or kind fails idempotency_mismatch (I3)',
73
+ async run({ store, newAccountId }) {
74
+ const ledger = createLedger({ store });
75
+ const a = newAccountId();
76
+ const b = newAccountId();
77
+ const key = `m:${a}`;
78
+ await ledger.credit({ accountId: a, kind: 'topup', amount: 500, idempotencyKey: key });
79
+ await rejects(ledger.credit({ accountId: a, kind: 'topup', amount: 501, idempotencyKey: key }), 'idempotency_mismatch', 'amount');
80
+ await rejects(ledger.credit({ accountId: b, kind: 'topup', amount: 500, idempotencyKey: key }), 'idempotency_mismatch', 'account');
81
+ await rejects(ledger.credit({ accountId: a, kind: 'grant', amount: 500, idempotencyKey: key }), 'idempotency_mismatch', 'kind');
82
+ await rejects(ledger.debit({ accountId: a, kind: 'topup', amount: 500, idempotencyKey: key }), 'idempotency_mismatch', 'direction');
83
+ equal(await ledger.balance(b), 0, 'other account untouched');
84
+ await assertLedgerInvariants(store, a);
85
+ },
86
+ },
87
+ {
88
+ name: 'a debit never overdraws: insufficient_credits carries balance, required, shortfall (I2)',
89
+ async run({ store, newAccountId }) {
90
+ const ledger = createLedger({ store });
91
+ const a = newAccountId();
92
+ await ledger.credit({ accountId: a, kind: 'topup', amount: 100, idempotencyKey: `o:${a}:1` });
93
+ const details = await rejects(ledger.debit({ accountId: a, kind: 'spend', amount: 130, idempotencyKey: `o:${a}:2` }), 'insufficient_credits', 'overdraft');
94
+ equal(details['balance'], 100, 'details.balance');
95
+ equal(details['required'], 130, 'details.required');
96
+ equal(details['shortfall'], 30, 'details.shortfall');
97
+ equal(await ledger.balance(a), 100, 'balance unchanged');
98
+ equal(await store.reader().findEntryByKey(`o:${a}:2`), null, 'no entry written');
99
+ // A fresh account cannot go negative either.
100
+ await rejects(ledger.debit({ accountId: newAccountId(), kind: 'spend', amount: 1, idempotencyKey: `o:${a}:3` }), 'insufficient_credits', 'empty account');
101
+ await assertLedgerInvariants(store, a);
102
+ },
103
+ },
104
+ {
105
+ name: 'debitUpTo posts min(balance, amount), records the shortfall and replays',
106
+ async run({ store, newAccountId }) {
107
+ const ledger = createLedger({ store });
108
+ const a = newAccountId();
109
+ await ledger.credit({ accountId: a, kind: 'topup', amount: 30, idempotencyKey: `u:${a}:1` });
110
+ const r = await ledger.debitUpTo({ accountId: a, kind: 'refund', amount: 50, idempotencyKey: `u:${a}:2` });
111
+ equal(r.entry.delta, -30, 'posted');
112
+ equal(r.shortfall, 20, 'shortfall');
113
+ equal((r.entry.meta?.['debitUpTo']).shortfall, 20, 'recorded shortfall');
114
+ const again = await ledger.debitUpTo({ accountId: a, kind: 'refund', amount: 50, idempotencyKey: `u:${a}:2` });
115
+ equal(again.replayed, true, 'replayed');
116
+ equal(again.shortfall, 20, 'replayed shortfall');
117
+ await rejects(ledger.debitUpTo({ accountId: a, kind: 'refund', amount: 60, idempotencyKey: `u:${a}:2` }), 'idempotency_mismatch', 'different request');
118
+ const empty = await ledger.debitUpTo({ accountId: a, kind: 'refund', amount: 10, idempotencyKey: `u:${a}:3` });
119
+ equal(empty.entry.delta, 0, 'zero posting at balance 0');
120
+ equal(empty.shortfall, 10, 'full shortfall');
121
+ equal(empty.events.length, 0, 'no event for a zero posting');
122
+ await assertLedgerInvariants(store, a);
123
+ },
124
+ },
125
+ {
126
+ name: 'reverse posts one counter-entry of at most |original| (I5)',
127
+ async run({ store, newAccountId }) {
128
+ const ledger = createLedger({ store });
129
+ const a = newAccountId();
130
+ const top = await ledger.credit({ accountId: a, kind: 'topup', amount: 200, idempotencyKey: `v:${a}:1` });
131
+ const spend = await ledger.debit({ accountId: a, kind: 'spend', amount: 80, idempotencyKey: `v:${a}:2` });
132
+ await rejects(ledger.reverse({ entryId: spend.entry.id, amount: 81, idempotencyKey: `v:${a}:x` }), 'reversal_exceeds_original', 'too much');
133
+ const back = await ledger.reverse({ entryId: spend.entry.id, idempotencyKey: `v:${a}:3` });
134
+ equal(back.entry.delta, 80, 'refunds the spend');
135
+ equal(back.entry.kind, 'reversal', 'kind');
136
+ equal(back.entry.reversesId, spend.entry.id, 'reversesId');
137
+ const replay = await ledger.reverse({ entryId: spend.entry.id, idempotencyKey: `v:${a}:3` });
138
+ equal(replay.replayed, true, 'replayed reversal');
139
+ await rejects(ledger.reverse({ entryId: spend.entry.id, idempotencyKey: `v:${a}:4` }), 'already_reversed', 'second reversal');
140
+ const partial = await ledger.reverse({ entryId: top.entry.id, amount: 150, idempotencyKey: `v:${a}:5` });
141
+ equal(partial.entry.delta, -150, 'partial claw-back');
142
+ await rejects(ledger.reverse({ entryId: 'missing-entry', idempotencyKey: `v:${a}:6` }), 'entry_not_found', 'unknown entry');
143
+ equal(await ledger.balance(a), 50, 'balance');
144
+ const b = newAccountId();
145
+ const big = await ledger.credit({ accountId: b, kind: 'topup', amount: 100, idempotencyKey: `v:${b}:1` });
146
+ await ledger.debit({ accountId: b, kind: 'spend', amount: 90, idempotencyKey: `v:${b}:2` });
147
+ await rejects(ledger.reverse({ entryId: big.entry.id, idempotencyKey: `v:${b}:3` }), 'insufficient_credits', 'claw-back past zero');
148
+ await assertLedgerInvariants(store, a);
149
+ await assertLedgerInvariants(store, b);
150
+ },
151
+ },
152
+ {
153
+ name: 'a posting inside a host transaction rolls back with it',
154
+ async run({ store, newAccountId }) {
155
+ const ledger = createLedger({ store });
156
+ const a = newAccountId();
157
+ let events = [];
158
+ try {
159
+ await store.transaction(async (tx) => {
160
+ const r = await ledger.in(tx).credit({ accountId: a, kind: 'topup', amount: 100, idempotencyKey: `h:${a}` });
161
+ events = r.events;
162
+ equal(await ledger.in(tx).balance(a), 100, 'visible inside the transaction');
163
+ throw ROLLBACK;
164
+ });
165
+ }
166
+ catch (error) {
167
+ if (error !== ROLLBACK)
168
+ throw error;
169
+ }
170
+ equal(events.length, 1, 'in(tx) returns its events to the host');
171
+ equal(await ledger.balance(a), 0, 'balance after rollback');
172
+ equal(await store.reader().findEntryByKey(`h:${a}`), null, 'entry after rollback');
173
+ const ok = await store.transaction((tx) => ledger.in(tx).credit({ accountId: a, kind: 'topup', amount: 100, idempotencyKey: `h:${a}` }));
174
+ equal(ok.replayed, false, 'key reusable after rollback');
175
+ await assertLedgerInvariants(store, a);
176
+ },
177
+ },
178
+ {
179
+ name: 'concurrent spends never double-debit',
180
+ async run({ store, newAccountId }) {
181
+ const ledger = createLedger({ store });
182
+ const a = newAccountId();
183
+ await ledger.credit({ accountId: a, kind: 'topup', amount: 100, idempotencyKey: `c:${a}:0` });
184
+ const results = await Promise.allSettled(Array.from({ length: 20 }, (_, i) => ledger.debit({ accountId: a, kind: 'spend', amount: 15, idempotencyKey: `c:${a}:${i + 1}` })));
185
+ const ok = results.filter((r) => r.status === 'fulfilled').length;
186
+ const short = results.filter((r) => r.status === 'rejected' && isBillingError(r.reason, 'insufficient_credits')).length;
187
+ equal(ok, 6, 'successful spends');
188
+ equal(short, 14, 'insufficient spends');
189
+ equal(await ledger.balance(a), 10, 'balance');
190
+ await assertLedgerInvariants(store, a);
191
+ },
192
+ },
193
+ {
194
+ name: 'concurrent posts of one key write one entry',
195
+ async run({ store, newAccountId }) {
196
+ const ledger = createLedger({ store });
197
+ const a = newAccountId();
198
+ const results = await Promise.all(Array.from({ length: 10 }, () => ledger.credit({ accountId: a, kind: 'topup', amount: 70, idempotencyKey: `k:${a}` })));
199
+ equal(new Set(results.map((r) => r.entry.id)).size, 1, 'one entry id');
200
+ equal(results.filter((r) => !r.replayed).length, 1, 'one original');
201
+ equal(await ledger.balance(a), 70, 'balance');
202
+ await assertLedgerInvariants(store, a);
203
+ },
204
+ },
205
+ {
206
+ name: 'a key raced across two accounts is written once',
207
+ async run({ store, newAccountId }) {
208
+ const ledger = createLedger({ store });
209
+ const a = newAccountId();
210
+ const b = newAccountId();
211
+ const key = `x:${a}`;
212
+ const results = await Promise.allSettled([
213
+ ledger.credit({ accountId: a, kind: 'topup', amount: 10, idempotencyKey: key }),
214
+ ledger.credit({ accountId: b, kind: 'topup', amount: 10, idempotencyKey: key }),
215
+ ]);
216
+ equal(results.filter((r) => r.status === 'fulfilled').length, 1, 'one winner');
217
+ const loser = results.find((r) => r.status === 'rejected');
218
+ check(loser?.status === 'rejected' && isBillingError(loser.reason, 'idempotency_mismatch'), 'loser fails idempotency_mismatch');
219
+ equal((await ledger.balance(a)) + (await ledger.balance(b)), 10, 'credited once in total');
220
+ await assertLedgerInvariants(store, a);
221
+ await assertLedgerInvariants(store, b);
222
+ },
223
+ },
224
+ {
225
+ name: 'invalid postings are rejected before anything is written',
226
+ async run({ store, newAccountId }) {
227
+ const ledger = createLedger({ store });
228
+ const a = newAccountId();
229
+ for (const amount of [0, -5, 1.5, Number.MAX_SAFE_INTEGER + 2, Number.NaN]) {
230
+ await rejects(ledger.credit({ accountId: a, kind: 'topup', amount, idempotencyKey: `i:${a}:${amount}` }), 'invalid_amount', `amount ${amount}`);
231
+ }
232
+ await rejects(ledger.credit({ accountId: a, kind: 'reversal', amount: 1, idempotencyKey: `i:${a}:k` }), 'invalid_input', 'reversal via post');
233
+ await rejects(ledger.credit({ accountId: a, kind: 'bogus', amount: 1, idempotencyKey: `i:${a}:k` }), 'invalid_input', 'unknown kind');
234
+ await rejects(ledger.credit({ accountId: a, kind: 'topup', amount: 1, idempotencyKey: '' }), 'invalid_input', 'missing key');
235
+ await ledger.credit({ accountId: a, kind: 'topup', amount: Number.MAX_SAFE_INTEGER, idempotencyKey: `i:${a}:max` });
236
+ await rejects(ledger.credit({ accountId: a, kind: 'topup', amount: 1, idempotencyKey: `i:${a}:over` }), 'balance_overflow', 'overflow');
237
+ await assertLedgerInvariants(store, a);
238
+ },
239
+ },
240
+ {
241
+ name: 'entries page newest first by seq',
242
+ async run({ store, newAccountId }) {
243
+ const ledger = createLedger({ store });
244
+ const a = newAccountId();
245
+ for (let i = 1; i <= 5; i++)
246
+ await ledger.credit({ accountId: a, kind: 'grant', amount: i, idempotencyKey: `p:${a}:${i}` });
247
+ const first = await ledger.entries(a, { limit: 2 });
248
+ equal(first.entries.map((e) => e.seq).join(','), '5,4', 'page 1');
249
+ const second = await ledger.entries(a, { limit: 2, beforeSeq: first.nextBeforeSeq ?? 0 });
250
+ equal(second.entries.map((e) => e.seq).join(','), '3,2', 'page 2');
251
+ const third = await ledger.entries(a, { limit: 2, beforeSeq: second.nextBeforeSeq ?? 0 });
252
+ equal(third.entries.map((e) => e.seq).join(','), '1', 'page 3');
253
+ equal(third.nextBeforeSeq, null, 'exhausted');
254
+ },
255
+ },
256
+ {
257
+ name: 'the event sink hears committed postings only',
258
+ async run({ store, newAccountId }) {
259
+ const heard = [];
260
+ const ledger = createLedger({ store, events: (e) => void heard.push(e) });
261
+ const a = newAccountId();
262
+ await ledger.credit({ accountId: a, kind: 'topup', amount: 40, idempotencyKey: `e:${a}:1` });
263
+ await ledger.debit({ accountId: a, kind: 'spend', amount: 15, idempotencyKey: `e:${a}:2` });
264
+ await ledger.debit({ accountId: a, kind: 'spend', amount: 15, idempotencyKey: `e:${a}:2` });
265
+ await rejects(ledger.debit({ accountId: a, kind: 'spend', amount: 99, idempotencyKey: `e:${a}:3` }), 'insufficient_credits', 'failed');
266
+ equal(heard.map((e) => e.type).join(','), 'credited,debited', 'events');
267
+ },
268
+ },
269
+ ];
@@ -0,0 +1,19 @@
1
+ import type { AccountId, LedgerEntry } from '../domain/types.js';
2
+ import type { LedgerStore } from '../ports/ledger-store.js';
3
+ /**
4
+ * An open memory transaction. Writes are staged and applied on commit, so a
5
+ * throw anywhere in the host's callback leaves the store untouched.
6
+ */
7
+ export interface MemoryTx {
8
+ readonly id: number;
9
+ }
10
+ export interface MemoryLedgerStore extends LedgerStore<MemoryTx> {
11
+ /** Committed entries of one account, oldest first (test inspection). */
12
+ dump(accountId: AccountId): LedgerEntry[];
13
+ }
14
+ /**
15
+ * In-process `LedgerStore` for tests and hosts' unit suites. Transactions are
16
+ * serialized by one store-wide mutex — the memory analogue of the account row
17
+ * lock — and pass the same conformance suite as the Postgres store.
18
+ */
19
+ export declare function createMemoryLedgerStore(): MemoryLedgerStore;
@@ -0,0 +1,137 @@
1
+ /**
2
+ * In-process `LedgerStore` for tests and hosts' unit suites. Transactions are
3
+ * serialized by one store-wide mutex — the memory analogue of the account row
4
+ * lock — and pass the same conformance suite as the Postgres store.
5
+ */
6
+ export function createMemoryLedgerStore() {
7
+ const accounts = new Map();
8
+ const entries = new Map();
9
+ const byKey = new Map();
10
+ const byReversal = new Map();
11
+ const byAccount = new Map();
12
+ let tail = Promise.resolve();
13
+ let nextTx = 1;
14
+ const clone = (value) => structuredClone(value);
15
+ const committed = {
16
+ async getAccount(accountId) {
17
+ const a = accounts.get(accountId);
18
+ return a ? { ...a } : null;
19
+ },
20
+ async getEntry(id) {
21
+ const e = entries.get(id);
22
+ return e ? clone(e) : null;
23
+ },
24
+ async findEntryByKey(key) {
25
+ const id = byKey.get(key);
26
+ return id ? clone(entries.get(id)) : null;
27
+ },
28
+ async listEntries(accountId, options) {
29
+ return list(byAccount.get(accountId) ?? [], options);
30
+ },
31
+ };
32
+ function list(rows, options) {
33
+ return rows
34
+ .filter((e) => options.beforeSeq === undefined || e.seq < options.beforeSeq)
35
+ .sort((a, b) => b.seq - a.seq)
36
+ .slice(0, options.limit)
37
+ .map(clone);
38
+ }
39
+ function staged(tx) {
40
+ const s = tx;
41
+ if (!s.open)
42
+ throw new Error('memory ledger transaction is closed');
43
+ return s;
44
+ }
45
+ function bind(tx) {
46
+ const own = (id) => staged(tx).entries.find((e) => e.id === id);
47
+ return {
48
+ async getAccount(accountId) {
49
+ const s = staged(tx).accounts.get(accountId);
50
+ return s ? { ...s } : committed.getAccount(accountId);
51
+ },
52
+ async getEntry(id) {
53
+ const e = own(id);
54
+ return e ? clone(e) : committed.getEntry(id);
55
+ },
56
+ async findEntryByKey(key) {
57
+ const e = staged(tx).entries.find((x) => x.idempotencyKey === key);
58
+ return e ? clone(e) : committed.findEntryByKey(key);
59
+ },
60
+ async listEntries(accountId, options) {
61
+ const rows = [...(byAccount.get(accountId) ?? []), ...staged(tx).entries.filter((e) => e.accountId === accountId)];
62
+ return list(rows, options);
63
+ },
64
+ async lockAccount(accountId) {
65
+ const s = staged(tx);
66
+ const current = s.accounts.get(accountId) ?? accounts.get(accountId) ?? { accountId, balance: 0, seq: 0 };
67
+ s.accounts.set(accountId, { ...current });
68
+ return { ...current };
69
+ },
70
+ async findReversalOf(entryId) {
71
+ const e = staged(tx).entries.find((x) => x.reversesId === entryId);
72
+ if (e)
73
+ return clone(e);
74
+ const id = byReversal.get(entryId);
75
+ return id ? clone(entries.get(id)) : null;
76
+ },
77
+ async appendEntry(entry) {
78
+ const s = staged(tx);
79
+ const clash = (e) => e.idempotencyKey === entry.idempotencyKey ||
80
+ (entry.reversesId !== null && e.reversesId === entry.reversesId) ||
81
+ (e.accountId === entry.accountId && e.seq === entry.seq) ||
82
+ e.id === entry.id;
83
+ if (s.entries.some(clash) ||
84
+ byKey.has(entry.idempotencyKey) ||
85
+ entries.has(entry.id) ||
86
+ (entry.reversesId !== null && byReversal.has(entry.reversesId)) ||
87
+ // Committed seqs are contiguous 1..n, so a clash is any seq ≤ the last.
88
+ entry.seq <= (byAccount.get(entry.accountId)?.at(-1)?.seq ?? 0)) {
89
+ return { inserted: false };
90
+ }
91
+ if (entry.balanceAfter < 0)
92
+ throw new Error('check constraint: balance_after must be >= 0');
93
+ s.entries.push(clone(entry));
94
+ return { inserted: true };
95
+ },
96
+ async setAccountState(state) {
97
+ if (state.balance < 0)
98
+ throw new Error('check constraint: balance must be >= 0');
99
+ staged(tx).accounts.set(state.accountId, { ...state });
100
+ },
101
+ };
102
+ }
103
+ function commit(s) {
104
+ for (const [id, state] of s.accounts)
105
+ accounts.set(id, state);
106
+ for (const entry of s.entries) {
107
+ entries.set(entry.id, entry);
108
+ byKey.set(entry.idempotencyKey, entry.id);
109
+ if (entry.reversesId)
110
+ byReversal.set(entry.reversesId, entry.id);
111
+ const rows = byAccount.get(entry.accountId) ?? [];
112
+ rows.push(entry);
113
+ byAccount.set(entry.accountId, rows);
114
+ }
115
+ }
116
+ return {
117
+ async transaction(fn) {
118
+ let release;
119
+ const turn = tail;
120
+ tail = new Promise((resolve) => (release = resolve));
121
+ await turn;
122
+ const s = { id: nextTx++, accounts: new Map(), entries: [], open: true };
123
+ try {
124
+ const result = await fn(s);
125
+ commit(s);
126
+ return result;
127
+ }
128
+ finally {
129
+ s.open = false;
130
+ release();
131
+ }
132
+ },
133
+ bind,
134
+ reader: () => committed,
135
+ dump: (accountId) => (byAccount.get(accountId) ?? []).map(clone),
136
+ };
137
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `@tofound/billing/testing` — the kit hosts use to prove their own stores
3
+ * and charge paths: the store conformance suite, the ledger invariant check,
4
+ * the quote/settle conformance assertion, the ingest store conformance suite
5
+ * and the memory stores.
6
+ */
7
+ export { assertLedgerInvariants, ledgerConformanceCases, type ConformanceCase, type LedgerConformanceTarget, } from './conformance.js';
8
+ export { createMemoryLedgerStore, type MemoryLedgerStore, type MemoryTx } from './memory.js';
9
+ export { assertQuoteMatchesSettlement, type ObservedSettlement } from '../quote/conformance.js';
10
+ export { ingestConformanceCases, type IngestConformanceCase, type IngestConformanceTarget } from '../inbox/conformance.js';
11
+ export { createMemoryIngestStore, type MemoryIngestStore } from '../inbox/memory.js';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `@tofound/billing/testing` — the kit hosts use to prove their own stores
3
+ * and charge paths: the store conformance suite, the ledger invariant check,
4
+ * the quote/settle conformance assertion, the ingest store conformance suite
5
+ * and the memory stores.
6
+ */
7
+ export { assertLedgerInvariants, ledgerConformanceCases, } from './conformance.js';
8
+ export { createMemoryLedgerStore } from './memory.js';
9
+ export { assertQuoteMatchesSettlement } from '../quote/conformance.js';
10
+ export { ingestConformanceCases } from '../inbox/conformance.js';
11
+ export { createMemoryIngestStore } from '../inbox/memory.js';
package/docs/API.md ADDED
@@ -0,0 +1,198 @@
1
+ # @tofound/billing — API (0.1)
2
+
3
+ Part of the `billing.public-api` contract with `src/index.ts` and
4
+ `src/domain/types.ts`. 0.x minors are additive; the declaration snapshot in
5
+ `test/contract/public-api.test.ts` fails on any change to these exports.
6
+
7
+ | Entry | Contents |
8
+ |---|---|
9
+ | `@tofound/billing` | domain types, money helpers, `BillingError`, `createLedger`, ports, `createMemoryLedgerStore`, waterfall + steps, provider port, `createIngest`, `createMemoryIngestStore` |
10
+ | `@tofound/billing/drizzle` | `createBillingTables`, `billingTableBuilder`, `checkAdditiveDdl`, `createDrizzleLedgerStore`, `createIngestTables`, `createDrizzleIngestStore` (peer `drizzle-orm ^0.45`) |
11
+ | `@tofound/billing/providers/sepay` | `createSepayAdapter`, `respondSepay`, `signCheckoutFields`, `parseSepayOrder` |
12
+ | `@tofound/billing/testing` | `ledgerConformanceCases`, `assertLedgerInvariants`, `assertQuoteMatchesSettlement`, `ingestConformanceCases`, memory stores |
13
+
14
+ The library reads no env, logs nothing and has no runtime dependencies. Every
15
+ amount is an integer in minor units — a safe-integer `number` in TS, `bigint`
16
+ in Postgres.
17
+
18
+ ## Money and units
19
+
20
+ - `CreditUnit {code, exponent}`: Lohi `{code:'LT', exponent:0}`, 2Novel
21
+ `{code:'credit', exponent:2}` (100 đ = 1 credit, so 1 minor unit = 1 đ).
22
+ `creditUnit(code, exponent)` validates and freezes one.
23
+ - `Money {currency:'VND'|'USD', amountMinor}`; `CURRENCY_EXPONENT` = VND 0, USD 2.
24
+ - `divRound(n, d, mode)` / `mulDivRound(a, n, d, mode)` round explicitly
25
+ (`floor` | `ceil` | `half_up`) in bigint, so `a × n` never overflows. Grants
26
+ and refunds round toward the customer.
27
+ - `formatMinor(amount, exponent)` → plain decimal string; display copy is the host's.
28
+
29
+ ## Ledger
30
+
31
+ ```ts
32
+ const ledger = createLedger({ store, clock?, ids?, events? })
33
+
34
+ await ledger.credit({ accountId, kind: 'topup', amount, idempotencyKey: `topup:${checkoutId}` })
35
+ await ledger.debit({ accountId, kind: 'spend', amount, idempotencyKey: `job:${jobId}:charge`, reason, source })
36
+ await ledger.debitUpTo({ accountId, kind: 'refund', amount, idempotencyKey }) // → {shortfall}
37
+ await ledger.reverse({ entryId, amount?, idempotencyKey })
38
+ await ledger.balance(accountId)
39
+ await ledger.findByKey(idempotencyKey) // the entry posted under a key, or null
40
+ await ledger.entries(accountId, { limit, beforeSeq }) // newest first
41
+ await db.transaction((tx) => ledger.in(tx).debit({ … })) // inside the host transaction
42
+ ```
43
+
44
+ Invariants every store upholds (design §4.3):
45
+
46
+ | | |
47
+ |---|---|
48
+ | I1 | `balanceAfter = previous balanceAfter + delta`; `seq` contiguous per account |
49
+ | I2 | No negative balance: `debit` throws `insufficient_credits {balance, required, shortfall}` and writes nothing |
50
+ | I3 | Same key + same intent (account, kind, requested amount, reversed entry) → the original entry, `replayed: true`, no events. Anything else → `idempotency_mismatch` |
51
+ | I4 | Entries are append-only |
52
+ | I5 | An entry is reversed at most once, by at most `|delta|` (`reversal_exceeds_original`, `already_reversed`) |
53
+ | I6 | Account balance = last `balanceAfter` = Σ delta |
54
+
55
+ - Posting order: lock the account (insert-or-lock `FOR UPDATE`, taken **last**,
56
+ after host, inbox, purchase and term rows) → look the key up → append →
57
+ update balance and seq. Concurrent spends serialize on the account row; a
58
+ key raced across accounts is settled by the unique index, never written twice.
59
+ - `debitUpTo` posts `min(balance, amount)` (possibly 0) and records
60
+ `meta.debitUpTo = {requested, shortfall}`.
61
+ - `reverse` posts kind `reversal` with `reversesId`, the opposite sign of the
62
+ original; clawing back a credit past zero throws `insufficient_credits`
63
+ (use `debitUpTo` for clawbacks that must record a shortfall).
64
+ - Kinds: `topup`, `grant`, `spend`, `refund`, `plan_purchase`, `plan_renewal`,
65
+ `plan_refund`, `reversal` (only via `reverse`), `conversion`, `resync`, `adjustment`.
66
+ - Events (`credited` / `debited`; none for a zero or replayed posting) go to
67
+ `events` after commit when the ledger opened the transaction. That delivery
68
+ is at most once: the posting is already durable, so a throwing sink never
69
+ fails it — the error goes to `onEventError(error, event)` and the remaining
70
+ events are still delivered. Under `ledger.in(tx)` the events come back in
71
+ the result for the host to emit after its own commit (or to write to its
72
+ outbox in the same transaction, for guaranteed delivery).
73
+ - `createLedger<TTx>` returns `Ledger<TTx>`: `in(tx)` accepts only the
74
+ store's transaction type.
75
+ - Errors are `BillingError {code, details}`; map `code` to HTTP and copy in the host:
76
+
77
+ | `code` | Thrown when | `details` |
78
+ |---|---|---|
79
+ | `insufficient_credits` | a debit or a credit's reversal would go below zero | `{balance, required, shortfall}` |
80
+ | `idempotency_mismatch` | the key was posted with another account, kind, amount or reversed entry | `{idempotencyKey, entryId}` |
81
+ | `invalid_amount` | an amount is not a positive safe integer | `{amount}` (or the named field) |
82
+ | `invalid_input` | missing account/key, unknown or `reversal` kind, non-integer paging, reversing a zero entry | the offending field |
83
+ | `entry_not_found` | `reverse` names an unknown entry | `{entryId}` |
84
+ | `reversal_exceeds_original` | `reverse` amount > \|original delta\| | `{entryId, amount, original}` |
85
+ | `already_reversed` | the entry already has its reversal | `{entryId, reversalId?}` |
86
+ | `balance_overflow` | a result leaves the safe-integer range | — |
87
+
88
+ A plain `Error` (not `BillingError`) signals a broken store or host setup,
89
+ e.g. a repeating `IdGenerator`; it is never an expected outcome.
90
+ - Stores assume READ COMMITTED. Do not call the top-level methods of a memory
91
+ store's ledger from inside that store's open transaction (it serializes).
92
+
93
+ ## Ports (`billing.ports`)
94
+
95
+ `LedgerStore<TTx>` = `transaction(fn)`, `bind(tx) → LedgerTx`, `reader()`.
96
+ `LedgerTx` adds `lockAccount`, `findReversalOf`, `appendEntry` (unique
97
+ conflict → `{inserted:false}`, never a thrown/aborted transaction) and
98
+ `setAccountState`. `Clock`, `IdGenerator`, `BillingEventSink`. A host adapter
99
+ (Lohi P4, over `user_wallets` / `wallet_transactions`) implements the same
100
+ port and must pass `ledgerConformanceCases`.
101
+
102
+ ## Quote and charge: one waterfall
103
+
104
+ ```ts
105
+ const w = createWaterfall<State, Tx>({
106
+ currency: 'credit',
107
+ price: (s) => s.price,
108
+ balance: (s) => s.balance,
109
+ steps: [
110
+ freeStep({ id: 'byok', when: (s) => s.byok, reason: { code: 'byok' } }),
111
+ quotaStep({ id: 'included', unit: 'credit_pool', pool: (s) => s.pool, reason: { code: 'included_pool' }, consume }),
112
+ creditsStep({ ledger }),
113
+ ],
114
+ })
115
+ w.quote(state) // read-only → Quote
116
+ await w.settle(tx, lockedState, { accountId, idempotencyKey }) // same steps, commits each line → {settled, replayed, quote, entries, events}
117
+ ```
118
+
119
+ - `Quote` mirrors Lohi's wire: `originalPrice`, `price` (what the wallet is
120
+ debited), `currency`, `reason {code, label?, detail?}`, `funding[]
121
+ {source, unit, amount, remainingBefore, remainingAfter, label?}`,
122
+ `settlement 'free'|'quota'|'wallet'|'blocked'`, `canSettle`, `shortfall?`,
123
+ `balance`, `upsell?`, `expiresInSec` (default 60). The host labels codes.
124
+ - Steps run in order while price remains. `freeStep` covers everything;
125
+ `quotaStep` spends `ceil(remaining / unitValue)` pool units (capped) and may
126
+ fund part; `creditsStep` debits the rest or blocks with the exact
127
+ `shortfall` — it never funds partially. Price left after every step blocks
128
+ with `not_covered`. A line's `unit` is the credit unit code exactly when it
129
+ settles from the wallet, so a pool counting credits uses its own unit name
130
+ (`included_credit`); the waterfall throws otherwise.
131
+ - `settle` re-walks on the locked state; a blocked walk writes nothing. If
132
+ the balance moved between the read and the account lock, the debit throws
133
+ `insufficient_credits` and the host transaction rolls back.
134
+ - `settle` first asks each step whether the key was already charged
135
+ (`creditsStep` looks the debit up): a repeat returns `{settled: true,
136
+ replayed: true}` with the original entry and runs nothing, even if the
137
+ drained balance no longer covers the price. A charge funded by quota alone
138
+ posts no ledger entry, so a host still makes the whole charge once-only the
139
+ way it already does — a stamp on the job/unlock row checked under its lock
140
+ before `settle` (2Novel's `cost_dong`, Lohi's unlock row).
141
+ - `Settled.events` carries the ledger events of the charge for the host to
142
+ emit after its commit (the sink is not called inside a host transaction).
143
+ - `assertQuoteMatchesSettlement(quote, {settled, walletDelta, meterDeltas})`
144
+ is the conformance check every host runs against real charges.
145
+
146
+ ## Provider ingest (`billing.provider-port`)
147
+
148
+ ```ts
149
+ const sepay = createSepayAdapter({ environment: 'production', webhookKeys: [current, next?], merchantId, secretKey })
150
+ const ingest = createIngest({ adapters: [sepay], store, ledger, events?, policy?, onUnmatched? })
151
+
152
+ const { session, redirect } = await ingest.createCheckout({ provider: 'sepay', accountId, amount, credits, productRef, description, successUrl, errorUrl, cancelUrl })
153
+ const r = await ingest.handle('sepay', { headers, rawBody, url, receivedAt }) // → reply with r.response
154
+ await ingest.confirm('sepay', { invoice: session.id }) // poll; same event id as the IPN
155
+ await ingest.closeCheckout(session.id, 'expired') // a later capture still credits
156
+ await ingest.replay('sepay', eventId) // re-opens needs_review / dead
157
+ await ingest.sweep() // cron: due failed + abandoned received rows
158
+ ```
159
+
160
+ - An adapter (`ProviderAdapter` in `src/providers/port.ts`) owns
161
+ `verify → normalize → respond`; the ingest owns the inbox, the checkout
162
+ sessions, the purchases and the ledger postings, in one store transaction.
163
+ Lock order: inbox row → session → purchase → account (last).
164
+ - `verify` throws `VerifyError('unauthorized' | 'malformed')` → 401 / 400 and
165
+ nothing is stored. Every verified delivery is one inbox row (unique
166
+ provider + event id), its payload redacted (`redactPayload`) before storage.
167
+ - Outcomes: `applied`, `ignored`, `duplicate` (row already final), `needs_review`
168
+ (`BillingError` or a refusal such as `amount_mismatch` — permanent, alerted),
169
+ `failed` (any other error: 5xx so the provider redelivers, retried by `sweep`
170
+ with `policy.backoff`), `dead` after `policy.maxAttempts` (alerted, acked).
171
+ - A purchase credits once: `topup:<sessionId>`, exact amount match against the
172
+ server-priced session. A reversal claws back through `ledger.reverse`
173
+ (`reversal:<provider>:<externalId>:<n>`), recording any spent part as
174
+ `shortfall`; a reinstatement re-credits (`reinstate:…`). Provider watermarks
175
+ (`isNewer`) drop stale events, and any delivery order of capture / reversal /
176
+ reinstatement converges to the same purchase state and balance.
177
+ - `confirm` credits the session's own account, whoever asks; a host route
178
+ that forwards a client's invoice still checks the caller owns that session
179
+ before it spends a provider API call on it.
180
+ - `sweep` lists only rows of the providers this ingest has adapters for, and
181
+ a row it cannot even record stays due without stopping the rows behind it.
182
+ - `onUnmatched` receives deliveries no session matches (e.g. another product's
183
+ SePay invoice) and may answer for them; a throw answers 5xx.
184
+ - SePay: `environment` is required (no default), and test credentials in
185
+ production or live ones in sandbox are refused. `x-secret-key` is compared in
186
+ constant time against every key in `webhookKeys`. Checkout form fields are
187
+ signed byte-for-byte as `sepay-pg-node@1.0.0`. An order lookup failure is
188
+ `unknown`, never `cancelled`.
189
+ - Events: `billing.webhook {provider, eventType, eventId, outcome, reason}`,
190
+ `billing.alert {alert: inbox_dead | inbox_needs_review}`, `refund_applied`,
191
+ plus the ledger's `credited` / `debited` — all after commit; a throwing sink
192
+ never fails the delivery.
193
+
194
+ ## Drizzle
195
+
196
+ See [SCHEMA.md](SCHEMA.md). `createDrizzleLedgerStore({ db, tables })` works
197
+ with any Drizzle Postgres driver; `ledger.in(tx)` takes the host's Drizzle
198
+ transaction.