File size: 2,192 Bytes
5bd4e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { describe, it, expect } from "vitest";
import { Ledger, LedgerError } from "../src/ledger.js";
import { MemoryStore } from "../src/memoryStore.js";
import { assertSafeEnv } from "../src/config.js";

const U = "00000000-0000-0000-0000-000000000001";

describe("ledger", () => {
  it("rejects unbalanced / bad postings", () => {
    expect(() => Ledger.validate([{ account_id: "a", amount: 100 }, { account_id: "b", amount: -99 }])).toThrow(LedgerError);
    expect(() => Ledger.validate([{ account_id: "a", amount: 0 }, { account_id: "b", amount: 0 }])).toThrow(LedgerError);
    expect(() => Ledger.validate([{ account_id: "a", amount: 1.5 }, { account_id: "b", amount: -1.5 }])).toThrow(LedgerError);
    expect(() => Ledger.validate([{ account_id: "a", amount: 5 }])).toThrow(LedgerError);
  });
  it("funding credits wallet and is idempotent", async () => {
    const store = new MemoryStore(); const l = new Ledger(store);
    await l.recordFunding(U, 2500, "usd", "pi_1");
    await l.recordFunding(U, 2500, "usd", "pi_1");
    expect(await l.walletBalance(U)).toBe(2500);
    expect(store.txs).toHaveLength(1);
    const sum = store.txs.flatMap((t) => t.postings).reduce((s, p) => s + p.amount, 0);
    expect(sum).toBe(0);
  });
  it("separates users and currencies", async () => {
    const l = new Ledger(new MemoryStore());
    await l.recordFunding(U, 1000, "usd", "pi_a");
    await l.recordFunding("u2", 700, "usd", "pi_b");
    await l.recordFunding(U, 300, "EUR", "pi_c");
    expect(await l.walletBalance(U, "usd")).toBe(1000);
    expect(await l.walletBalance(U, "eur")).toBe(300);
    expect(await l.walletBalance("u2")).toBe(700);
  });
});

describe("safety guards", () => {
  it("refuses live keys", () => expect(() => assertSafeEnv({ STRIPE_SECRET_KEY: "sk_live_x" })).toThrow(/live/));
  it("refuses non-test keys", () => expect(() => assertSafeEnv({ STRIPE_SECRET_KEY: "abc" })).toThrow());
  it("refuses Apple Pay creds", () => expect(() => assertSafeEnv({ STRIPE_SECRET_KEY: "sk_test_x", APPLE_PAY_MERCHANT_KEY: "x" })).toThrow(/Apple Pay/));
  it("accepts test key", () => expect(() => assertSafeEnv({ STRIPE_SECRET_KEY: "sk_test_x" })).not.toThrow());
});