File size: 2,075 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
42
43
import { describe, it, expect } from "vitest";
import { Ledger } from "../src/ledger.js";
import { MemoryStore } from "../src/memoryStore.js";
import { parseInvoiceQr, payInvoice } from "../src/routing.js";

const U = "u1";
const qr = JSON.stringify({ v: 1, invoice_id: "INV-1", merchant_id: "m1", merchant_name: "Shop", amount: 1200, currency: "USD" });

describe("invoice QR parsing", () => {
  it("parses JSON payload", () => expect(parseInvoiceQr(qr)).toMatchObject({ amount: 1200, currency: "usd" }));
  it("parses URI payload", () =>
    expect(parseInvoiceQr("projectos-invoice:?v=1&invoice_id=I2&merchant_id=m&amount=50&currency=usd")).toMatchObject({ invoice_id: "I2", amount: 50 }));
  it("rejects garbage and bad amounts", () => {
    expect(() => parseInvoiceQr("not json")).toThrow();
    expect(() => parseInvoiceQr(JSON.stringify({ v: 1, invoice_id: "x", merchant_id: "m", amount: -5, currency: "usd" }))).toThrow();
    expect(() => parseInvoiceQr(JSON.stringify({ v: 1, invoice_id: "x", merchant_id: "m", amount: 1.2, currency: "usd" }))).toThrow();
  });
});

describe("payInvoice", () => {
  it("pays from balance, idempotently", async () => {
    const l = new Ledger(new MemoryStore());
    await l.recordFunding(U, 2000, "usd", "pi_1");
    const inv = parseInvoiceQr(qr);
    const r1 = await payInvoice(l, U, inv);
    expect(r1.status).toBe("paid"); expect(r1.balance).toBe(800);
    const r2 = await payInvoice(l, U, inv);
    expect(r2.status).toBe("already_paid");
    expect(await l.walletBalance(U)).toBe(800);
  });
  it("rejects insufficient funds", async () => {
    const l = new Ledger(new MemoryStore());
    await l.recordFunding(U, 500, "usd", "pi_1");
    await expect(payInvoice(l, U, parseInvoiceQr(qr))).rejects.toThrow(/insufficient/);
    expect(await l.walletBalance(U)).toBe(500);
  });
  it("does not cross currencies", async () => {
    const l = new Ledger(new MemoryStore());
    await l.recordFunding(U, 5000, "eur", "pi_1");
    await expect(payInvoice(l, U, parseInvoiceQr(qr))).rejects.toThrow(/insufficient/);
  });
});