aboutsummaryrefslogtreecommitdiffstats
path: root/test/forward.test.ts
blob: 1e0cd5665b996e2a06ba25f1322f862e4ba0cce6 (plain) (blame)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import { describe, test, expect, beforeEach } from "bun:test";

// Mocks are loaded via test/preload.ts (bunfig.toml [test].preload)
// Access the mock functions we need for assertions
import { tbCredit } from "$lib/tb";
import { warn } from "$lib/logging";
import { callWebhook } from "$lib/webhooks";
import ln from "$lib/ln";

const mockTbCredit = tbCredit as any;
const mockWarn = warn as any;
const mockCallWebhook = callWebhook as any;
const mockLnXpay = ln.xpay as any;

import { completePayment } from "$lib/payments";
import routes from "$routes/payments";

// =====================================================================
// Helpers
// =====================================================================

const store = () => globalThis.__testStore;

const custodialUid = "custodial-uid";
const arkAccountId = "ark-account-123";
const bolt11 = "lnbcrt10u1pntestqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq";

const makeUser = (overrides = {}) => ({
  id: custodialUid,
  username: "testuser",
  currency: "USD",
  language: "en",
  autowithdraw: false,
  threshold: 0,
  reserve: 0,
  destination: "",
  ...overrides,
});

const makeInvoice = (overrides: any = {}) => ({
  id: "inv-001",
  uid: custodialUid,
  aid: custodialUid,
  type: "ark",
  currency: "USD",
  amount: 1000,
  received: 0,
  pending: 0,
  rate: 50000,
  forward: null as string | null,
  forwarded: false,
  hash: "inv-hash-001",
  memo: "",
  tip: null,
  webhook: null,
  secret: null,
  ...overrides,
});

const seedInvoice = (inv: any) => {
  store().kvStore[`invoice:${inv.id}`] = JSON.stringify(inv);
  store().kvStore[`invoice:${inv.hash}`] = inv.id;
};

const seedUser = (user: any) => {
  store().kvStore[`user:${user.username}`] = JSON.stringify(user);
  store().kvStore[`user:${user.id}`] = JSON.stringify(user);
};

const resetAll = () => {
  const s = store();
  for (const k of Object.keys(s.kvStore)) delete s.kvStore[k];
  for (const k of Object.keys(s.listStore)) delete s.listStore[k];
  for (const k of Object.keys(s.setStore)) delete s.setStore[k];

  mockTbCredit.mockClear();
  mockWarn.mockClear();
  mockCallWebhook.mockClear();
  mockLnXpay.mockClear();

  mockLnXpay.mockImplementation(async () => ({
    amount_sent_msat: 1_000_000,
    payment_preimage: "preimage-abc123",
  }));

  // Seed rates and limits
  s.kvStore["rates"] = JSON.stringify({ USD: 50000, CAD: 68000 });
  s.kvStore["limit"] = JSON.stringify(100_000_000);
  s.kvStore["lightning:limit"] = JSON.stringify(100_000_000);
  s.kvStore["internal:limit"] = JSON.stringify(100_000_000);
  s.kvStore["freeze"] = JSON.stringify(false);
  s.kvStore["hardfreeze"] = JSON.stringify(false);

  seedUser(makeUser());
};

const makeRes = () => {
  let sent: any;
  return {
    send: (data: any) => { sent = data; },
    code: (code: number) => ({
      send: (data: any) => { sent = data; },
    }),
    getSent: () => sent,
  };
};

// =====================================================================
// Tests: completePayment forward logic
// =====================================================================

describe("completePayment", () => {
  beforeEach(resetAll);

  test("forwards payment and debit stays in custodial", async () => {
    const user = makeUser();
    const inv = makeInvoice({ aid: arkAccountId, forward: bolt11 });
    const p = { amount: 1000, confirmed: true, type: "ark", uid: custodialUid, created: Date.now() };

    await completePayment(inv, p, user);

    expect(mockLnXpay).toHaveBeenCalled();
    expect(inv.forwarded).toBe(true);
    expect(mockCallWebhook).toHaveBeenCalled();
  });

  test("forwards and debit stays in custodial when aid matches user", async () => {
    const user = makeUser();
    const inv = makeInvoice({ aid: custodialUid, forward: bolt11 });
    const p = { amount: 1000, confirmed: true, type: "ark", uid: custodialUid, created: Date.now() };

    await completePayment(inv, p, user);

    expect(mockLnXpay).toHaveBeenCalled();
    expect(inv.forwarded).toBe(true);
  });

  test("handles forward failure gracefully", async () => {
    const user = makeUser();
    const inv = makeInvoice({ aid: arkAccountId, forward: bolt11 });
    const p = { amount: 1000, confirmed: true, type: "ark", uid: custodialUid, created: Date.now() };

    mockLnXpay.mockImplementationOnce(async () => { throw new Error("route not found"); });

    const w = await completePayment(inv, p, user);

    expect(w).toBeUndefined();
    expect(mockWarn).toHaveBeenCalled();
    expect(mockWarn.mock.calls.some((c: any[]) => c.includes("forward failed"))).toBe(true);
  });

  test("skips forward when already forwarded", async () => {
    const user = makeUser();
    const inv = makeInvoice({ aid: arkAccountId, forward: bolt11, forwarded: true });
    const p = { amount: 1000, confirmed: true, type: "ark", uid: custodialUid, created: Date.now() };

    const w = await completePayment(inv, p, user);

    expect(w).toBeUndefined();
    expect(mockLnXpay).not.toHaveBeenCalled();
  });

  test("skips forward when payment not confirmed", async () => {
    const user = makeUser();
    const inv = makeInvoice({ aid: arkAccountId, forward: bolt11 });
    const p = { amount: 1000, confirmed: false, type: "ark", uid: custodialUid, created: Date.now() };

    const w = await completePayment(inv, p, user);

    expect(w).toBeUndefined();
    expect(mockLnXpay).not.toHaveBeenCalled();
  });
});

// =====================================================================
// Tests: arkReceive route handler
// =====================================================================

describe("arkReceive", () => {
  beforeEach(resetAll);

  test("credits custodial and forwards to Lightning", async () => {
    const inv = makeInvoice({ aid: arkAccountId, forward: bolt11 });
    seedInvoice(inv);

    const req = {
      body: { iid: inv.id, amount: 1000, hash: "ark-txid-999" },
      user: makeUser(),
    };
    const res = makeRes();

    await routes.arkReceive(req as any, res as any);
    const sent = (res as any).getSent();

    // Response is the custodial credit record
    expect(sent).toBeTruthy();
    expect(sent.amount).toBe(1000);
    expect(sent.aid).toBe(custodialUid);

    // tbCredit called for deposit
    expect(mockTbCredit).toHaveBeenCalledWith(custodialUid, custodialUid, inv.type, 1000, false);

    // Ark txid mapped for dedup
    expect(store().kvStore[`payment:${arkAccountId}:ark-txid-999`]).toBeTruthy();

    // Credit record in custodial list
    expect(store().listStore[`${custodialUid}:payments`] ?? []).toContain(sent.id);

    // Forward triggered Lightning send
    expect(mockLnXpay).toHaveBeenCalled();
  });

  test("credits custodial without forward", async () => {
    const inv = makeInvoice({ aid: arkAccountId });
    seedInvoice(inv);

    const req = {
      body: { iid: inv.id, amount: 1000, hash: "ark-txid-888" },
      user: makeUser(),
    };
    const res = makeRes();

    await routes.arkReceive(req as any, res as any);
    const sent = (res as any).getSent();

    expect(sent).toBeTruthy();
    expect(sent.amount).toBe(1000);
    expect(sent.aid).toBe(custodialUid);

    // Always credits custodial TB
    expect(mockTbCredit).toHaveBeenCalledWith(custodialUid, custodialUid, inv.type, 1000, false);
    // Record in custodial list
    expect(store().listStore[`${custodialUid}:payments`] ?? []).toContain(sent.id);
  });

  test("credits custodial even when forward fails", async () => {
    const inv = makeInvoice({ aid: arkAccountId, forward: bolt11 });
    seedInvoice(inv);

    mockLnXpay.mockImplementationOnce(async () => { throw new Error("no route"); });

    const req = {
      body: { iid: inv.id, amount: 1000, hash: "ark-txid-777" },
      user: makeUser(),
    };
    const res = makeRes();

    await routes.arkReceive(req as any, res as any);
    const sent = (res as any).getSent();

    // Credit still lands in custodial even though forward failed
    expect(sent).toBeTruthy();
    expect(sent.amount).toBe(1000);
    expect(sent.aid).toBe(custodialUid);

    expect(mockTbCredit).toHaveBeenCalledWith(custodialUid, custodialUid, inv.type, 1000, false);
    expect(store().listStore[`${custodialUid}:payments`] ?? []).toContain(sent.id);
  });

  test("rejects invalid amount", async () => {
    const inv = makeInvoice();
    seedInvoice(inv);

    const req = {
      body: { iid: inv.id, amount: 0, hash: "ark-txid-000" },
      user: makeUser(),
    };
    const res = makeRes();

    await routes.arkReceive(req as any, res as any);
    // Should error - check that send wasn't called with a valid payment
    const sent = (res as any).getSent();
    expect(sent).toBeDefined();
  });

  test("rejects unauthorized user", async () => {
    const inv = makeInvoice({ uid: "other-user-id" });
    seedInvoice(inv);

    const req = {
      body: { iid: inv.id, amount: 1000, hash: "ark-txid-666" },
      user: makeUser(),
    };
    const res = makeRes();

    await routes.arkReceive(req as any, res as any);
    const sent = (res as any).getSent();
    expect(sent).toBeDefined();
  });
});

// =====================================================================
// Tests: arkSync skips change VTXOs
// =====================================================================

describe("arkSync", () => {
  beforeEach(resetAll);

  test("records received VTXOs (positive amounts)", async () => {
    const req = {
      body: {
        aid: arkAccountId,
        transactions: [
          { hash: "recv-vtxo-hash", amount: 9000, settled: true, createdAt: Date.now() },
        ],
      },
      user: makeUser(),
    };
    const res = makeRes();

    await routes.arkSync(req as any, res as any);
    const sent = (res as any).getSent();

    expect(sent.synced).toBe(1);
    expect(sent.received).toBe(9000);
    expect(store().listStore[`${arkAccountId}:payments`] ?? []).toHaveLength(1);
  });

  test("records sent transactions (negative amounts)", async () => {
    const req = {
      body: {
        aid: arkAccountId,
        transactions: [
          { hash: "send-tx-hash", amount: -1000, settled: true, createdAt: Date.now() },
        ],
      },
      user: makeUser(),
    };
    const res = makeRes();

    await routes.arkSync(req as any, res as any);
    const sent = (res as any).getSent();

    expect(sent.synced).toBe(1);
    expect((store().listStore[`${arkAccountId}:payments`] ?? []).length).toBe(1);
  });

  test("deduplicates known transactions", async () => {
    // Pre-store a known tx hash and its sync lock
    store().kvStore[`arksync:${arkAccountId}:known-hash`] = "1";
    store().kvStore[`payment:${arkAccountId}:known-hash`] = JSON.stringify("existing-id");
    store().kvStore["payment:existing-id"] = JSON.stringify({ id: "existing-id", confirmed: false });

    const req = {
      body: {
        aid: arkAccountId,
        transactions: [
          { hash: "known-hash", amount: -1000, settled: true, createdAt: Date.now() },
        ],
      },
      user: makeUser(),
    };
    const res = makeRes();

    await routes.arkSync(req as any, res as any);
    const sent = (res as any).getSent();

    expect(sent.synced).toBe(0);
    // Existing record should be updated to confirmed
    const updated = JSON.parse(store().kvStore["payment:existing-id"]);
    expect(updated.confirmed).toBe(true);
  });
});