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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
|
import { execSync } from "child_process";
import type { Browser, Page } from "@playwright/test";
import { expect } from "@playwright/test";
// --- Environment ---
export const arkWalletPassword = process.env.E2E_ARK_WALLET_PASSWORD || "testpw123";
export const aliceUsername = process.env.E2E_ALICE_USERNAME || "alice";
export const alicePassword = process.env.E2E_ALICE_PASSWORD || "pw";
export const bobUsername = process.env.E2E_BOB_USERNAME || "bob";
export const bobPassword = process.env.E2E_BOB_PASSWORD || "pw";
export const testSecret = process.env.E2E_TEST_SECRET;
export const apiBaseUrl = process.env.E2E_API_BASE_URL || "http://localhost:3119";
export const pauseAtEnd = process.env.E2E_PAUSE_AT_END === "true";
// --- Login helpers ---
export async function login(page: Page, username: string, password: string) {
for (let attempt = 0; attempt < 5; attempt++) {
if (attempt > 0) await page.waitForTimeout(2_000);
await page.goto("/login");
await page.waitForLoadState("networkidle");
await page.getByTestId("login-username").fill(username);
await page.locator('input[name="password"]').first().fill(password);
await page.getByTestId("login-submit").click();
const ok = await page
.waitForURL(new RegExp(`/${username}(?:[/?#]|$)`), { timeout: 15_000 })
.then(() => true)
.catch(() => false);
if (ok) return;
console.log(`[e2e] Login attempt ${attempt + 1} failed, retrying...`);
}
throw new Error(`Login failed for ${username} after 5 attempts`);
}
export async function loginNewContext(browser: Browser, username: string, password: string) {
const context = await browser.newContext();
const page = await context.newPage();
await login(page, username, password);
return { context, page };
}
export async function apiLogin(page: Page, username: string, password: string) {
const res = await page.request.post(`${apiBaseUrl}/login`, {
data: { username, password },
});
const data = await res.json();
return data.token as string;
}
export async function apiGetBalance(page: Page, token: string) {
const res = await page.request.get(`${apiBaseUrl}/me`, {
headers: { authorization: `Bearer ${token}` },
});
const data = await res.json();
return data.balance as number;
}
export async function apiGetInvoice(page: Page, invoiceId: string) {
const res = await page.request.get(`${apiBaseUrl}/invoice/${invoiceId}`);
return res.json();
}
// --- Invoice creation via UI ---
export async function createBitcoinInvoiceViaUI(page: Page, username: string) {
await page.goto(`/${username}/receive?address_type=bech32`);
await page.waitForURL(/\/invoice\/[^/?#]+/, { timeout: 15_000 });
const invoiceId = page.url().match(/\/invoice\/([^/?#]+)/)?.[1];
expect(invoiceId, "Should have invoice ID in URL").toBeTruthy();
const invoiceText = await page.getByTestId("invoice-text").first().innerText({ timeout: 10_000 });
const address = invoiceText.trim().replace(/\s+/g, "");
expect(
address.startsWith("bcrt1") || address.startsWith("bc1"),
`Expected bitcoin address, got: ${address}`,
).toBeTruthy();
return { invoiceId: invoiceId!, address };
}
export async function createLightningInvoiceViaUI(page: Page, username: string) {
await page.goto(`/${username}/receive`);
await page.waitForURL(/\/invoice\/[^/?#]+/, { timeout: 15_000 });
// Click "More options" then "Bolt 11" to switch invoice type
const moreOptions = page.getByText("More options");
if (await moreOptions.isVisible({ timeout: 3000 }).catch(() => false)) {
await moreOptions.click();
}
const bolt11Button = page.locator("button", { hasText: "Bolt 11" });
await expect(bolt11Button).toBeVisible({ timeout: 5000 });
await bolt11Button.click();
// Wait for invoice to regenerate
await page.waitForURL(/\/invoice\/[^/?#]+/, { timeout: 10_000 });
const invoiceId = page.url().match(/\/invoice\/([^/?#]+)/)?.[1];
expect(invoiceId).toBeTruthy();
const invoiceText = (
await page.getByTestId("invoice-text").first().innerText({ timeout: 10_000 })
).trim();
const bolt11 = invoiceText.replace(/\s+/g, "");
expect(
bolt11.toLowerCase().startsWith("lnbcrt") || bolt11.toLowerCase().startsWith("lnbc"),
`Expected bolt11, got: ${bolt11.substring(0, 30)}`,
).toBeTruthy();
return { invoiceId: invoiceId!, bolt11 };
}
export async function createArkInvoiceViaUI(page: Page, password: string) {
const arkCard = page.locator('[data-testid="account-card"][data-account-type="ark"]');
await expect(arkCard.first()).toBeVisible({ timeout: 10_000 });
const walletPassInput = page.getByTestId("walletpass-input");
let invoiceOpened = false;
const count = await arkCard.count();
for (let i = 0; i < count; i++) {
const card = arkCard.nth(i);
await card.scrollIntoViewIfNeeded();
const accountHref = await card.locator('a[href^="/account/"]').first().getAttribute("href");
const accountId = accountHref?.split("/account/")[1];
await card.locator('a[href="/invoice"]').first().click();
if (
await walletPassInput
.first()
.isVisible({ timeout: 2000 })
.catch(() => false)
) {
await walletPassInput.fill(password);
await page.getByTestId("walletpass-submit").click();
}
invoiceOpened = await page
.waitForURL(/\/invoice\/[^/?#]+/, { timeout: 5000 })
.then(() => true)
.catch(() => false);
if (!invoiceOpened && accountId) {
await page.evaluate((aid) => {
document.cookie = `aid=${aid}; path=/; max-age=86400`;
}, accountId);
await page.goto("/invoice");
invoiceOpened = await page
.waitForURL(/\/invoice\/[^/?#]+/, { timeout: 5000 })
.then(() => true)
.catch(() => false);
}
if (invoiceOpened) break;
if (
await page
.getByTestId("walletpass-cancel")
.isVisible()
.catch(() => false)
) {
await page.getByTestId("walletpass-cancel").click();
}
}
expect(invoiceOpened).toBeTruthy();
const invoiceText = (await page.getByTestId("invoice-text").first().innerText()).trim();
const addressMatch = invoiceText.match(/t?ark1[a-z0-9]+/i);
expect(addressMatch).toBeTruthy();
const invoiceId = page.url().split("/invoice/")[1]?.split(/[/?#]/)[0];
expect(invoiceId).toBeTruthy();
return { invoiceId: invoiceId!, address: addressMatch![0] };
}
export async function createVaultBitcoinInvoiceViaUI(page: Page) {
const vaultCard = page.locator('[data-testid="account-card"][data-account-type="bitcoin"]');
await expect(vaultCard.first()).toBeVisible({ timeout: 10_000 });
await vaultCard.first().getByTestId("account-receive").click();
await page.waitForURL(/\/invoice\/[^/?#]+/, { timeout: 10_000 });
const invoiceText = await page.getByTestId("invoice-text").first().innerText({ timeout: 10_000 });
const address = invoiceText.trim().replace(/\s+/g, "");
expect(
address.startsWith("bcrt1") || address.startsWith("bc1"),
`Expected bitcoin address, got: ${address}`,
).toBeTruthy();
const invoiceId = page.url().split("/invoice/")[1]?.split(/[/?#]/)[0];
expect(invoiceId).toBeTruthy();
return { invoiceId: invoiceId!, address };
}
// --- Send helpers ---
export async function pasteAndSend(page: Page, text: string) {
await page.goto("/send");
await page.waitForURL(/\/send/);
const textarea = page.locator('textarea[name="text"]');
await expect(textarea).toBeVisible({ timeout: 5_000 });
await textarea.fill(text);
await page.locator('button[type="submit"]').first().click();
// Wait for navigation away from /send
await page.waitForURL((url) => url.pathname !== "/send" && url.pathname !== "/send/", {
timeout: 15_000,
});
}
export async function fillNumpadAmount(page: Page, amount: number) {
const amountInput = page.locator('[aria-label="Amount input"]');
await expect(amountInput).toBeVisible({ timeout: 5_000 });
// Ensure sats mode: swap button shows lightning icon when in fiat mode
const swapButton = page.locator('[aria-label="Swap currency display"]');
if (await swapButton.isVisible({ timeout: 2_000 }).catch(() => false)) {
const hasLightning = await swapButton.locator('iconify-icon[icon="ph:lightning-fill"]').count();
if (hasLightning > 0) {
await swapButton.click();
await page.waitForTimeout(300);
}
}
await amountInput.click();
await page.keyboard.press("Control+a");
await page.keyboard.type(String(amount));
const nextButton = page.locator("button.btn-accent");
await expect(nextButton).toBeVisible({ timeout: 5_000 });
await nextButton.click();
}
export async function clickSendButton(page: Page) {
const sendButton = page.locator('button[type="submit"]');
await expect(sendButton).toBeVisible({ timeout: 5_000 });
await sendButton.click();
}
export async function waitForSentRedirect(page: Page, timeout = 15_000) {
await page.waitForURL(/\/sent\//, { timeout });
}
export async function waitForPaidRedirect(page: Page, invoiceId: string, timeout = 30_000) {
await page.waitForURL(new RegExp(`/invoice/${invoiceId}/paid(?:[/?#]|$)`), { timeout });
}
// --- Docker helpers ---
export function dockerExec(container: string, command: string): string {
return execSync(`docker exec ${container} ${command}`, {
encoding: "utf-8",
timeout: 30_000,
}).trim();
}
export function lightningPay(bolt11: string): string {
return dockerExec("clb", `lightning-cli pay ${bolt11}`);
}
export function lightningInvoice(amountMsat: number, label: string): string {
const result = dockerExec("clb", `lightning-cli invoice ${amountMsat} "${label}" "${label}"`);
return JSON.parse(result).bolt11 as string;
}
export function getBitcoinAddress(): string {
return dockerExec("bc", "bitcoin-cli -regtest -rpcwallet=external getnewaddress");
}
export function bitcoinSend(address: string, amountBtc: string): string {
return dockerExec(
"bc",
`bitcoin-cli -regtest -rpcwallet=coinos sendtoaddress "${address}" ${amountBtc}`,
);
}
export function mineBlocks(n: number): void {
const minerAddr = dockerExec("bc", "bitcoin-cli -regtest -rpcwallet=coinos getnewaddress");
dockerExec("bc", `bitcoin-cli -regtest -rpcwallet=coinos generatetoaddress ${n} "${minerAddr}"`);
}
// --- Polling helpers ---
export async function waitForInvoicePaid(
page: Page,
invoiceId: string,
amount: number,
{ interval = 1000, maxAttempts = 30 } = {},
) {
let status: any;
for (let i = 0; i < maxAttempts; i++) {
const res = await page.request.get(`${apiBaseUrl}/invoice/${invoiceId}`);
if (res.ok()) {
status = await res.json();
if ((status?.received || 0) >= amount || (status?.pending || 0) >= amount) {
return status;
}
}
await page.waitForTimeout(interval);
}
throw new Error(
`Invoice ${invoiceId} not paid after ${maxAttempts} attempts: ${JSON.stringify(status)}`,
);
}
// --- Ark helpers ---
export async function sendArkFromTestEndpoint(
page: Page,
address: string,
amount: number,
iid?: string,
) {
const sendResult = await page.evaluate(
async ({ address, testSecret, amount, iid }) => {
const body: any = { address, amount };
if (iid) body.iid = iid;
const res = await fetch("/api/test/ark/send", {
method: "POST",
headers: {
"content-type": "application/json",
"x-test-secret": testSecret,
},
body: JSON.stringify(body),
});
const text = await res.text();
return { ok: res.ok, status: res.status, text };
},
{ address, testSecret: testSecret!, amount, iid },
);
expect(
sendResult.ok,
`/test/ark/send failed (${sendResult.status}): ${sendResult.text}`,
).toBeTruthy();
return sendResult;
}
// --- Account helpers ---
export async function setActiveAccount(page: Page, accountId: string) {
await page.evaluate((aid) => {
document.cookie = `aid=${aid}; path=/; max-age=86400`;
}, accountId);
}
export async function ensureArkAccount(page: Page, password: string) {
await page.goto("/account/ark");
await page.waitForLoadState("networkidle");
// If redirected to dashboard, user already has an ark account
const url = page.url();
if (!url.includes("/account/ark")) {
console.log("[e2e] Ark account already exists, skipping creation");
return;
}
// Check if we're on the creation page (has key generation)
const revealButton = page.locator("button.btn-warning");
const hasReveal = await revealButton.isVisible({ timeout: 30_000 }).catch(() => false);
if (!hasReveal) {
console.log("[e2e] Ark account page loaded but no reveal button — account may already exist");
return;
}
// Click "Reveal Backup Key"
await revealButton.click();
// Click "I've Backed It Up"
const backedUpButton = page.locator("button.btn-accent");
await expect(backedUpButton).toBeVisible({ timeout: 5_000 });
await backedUpButton.click();
// Fill password and confirm password
const passwordInputs = page.locator('input[type="password"]');
await expect(passwordInputs.first()).toBeVisible({ timeout: 5_000 });
const count = await passwordInputs.count();
for (let i = 0; i < count; i++) {
await passwordInputs.nth(i).fill(password);
}
// Click "Create Wallet" submit
const submitButton = page.locator('button[type="submit"]');
await expect(submitButton).toBeVisible({ timeout: 5_000 });
await submitButton.click();
// Wait for redirect to dashboard (account created)
await page.waitForURL((u) => !u.pathname.includes("/account/ark"), { timeout: 30_000 });
console.log("[e2e] Ark account created successfully");
}
|