Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,49 @@
run: bash ./scripts/check-bundle-size.sh
working-directory: frontend

frontend-e2e:
name: Frontend end-to-end
runs-on: ubuntu-latest
needs: changes
if: >-
github.event_name == 'push' ||
needs.changes.outputs.frontend == 'true'
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: "npm"
cache-dependency-path: package-lock.json

- name: Install dependencies
run: npm install --include=optional

# The suite runs the real page against in-process mock servers
# (playwright.config.ts webServer), so it needs only the browsers.
- name: Install Playwright browsers
run: npx playwright install --with-deps chromium firefox
working-directory: frontend

# Issue #1872: the config has been CI-aware (forbidOnly, retries, single
# worker) since it was written, and no workflow ran it.
- name: Run the end-to-end suite
run: npm run test:e2e
working-directory: frontend

- name: Upload the Playwright report
if: failure()
uses: actions/upload-artifact@v4
with:
name: playwright-report
path: frontend/playwright-report
retention-days: 7

backend:
name: Backend CI
runs-on: ubuntu-latest
Expand Down
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
node_modules
dist
target
.env
# Every env file, not just .env: .env.local and .env.production hold the same
# secrets and were committable. The example stays tracked.
.env*
!.env.example
.DS_Store
coverage
e2e-results
Expand Down
6 changes: 5 additions & 1 deletion backend/.gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
node_modules
# Keep environment variables out of version control
.env
# Every env file, not just .env (#1873). backend/.env.local and
# backend/.env.production were not ignored by any rule while .env.example
# documents the real JWT_SECRET and KEEPER_SECRET_KEY to put in them.
.env*
!.env.example

# Prisma
/src/generated/prisma
Expand Down
10 changes: 6 additions & 4 deletions backend/tests/soroban.service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ describe('Soroban Service', () => {
});

describe('chain reads', () => {
it.skip('verifies mock server is called', async () => {
it('verifies mock server is called', async () => {
const { getStreamFromChain } = await importService();
mocks.server.simulateTransaction.mockResolvedValue(
simulationSuccess(nativeToScVal(99n, { type: 'i128' }))
Expand All @@ -362,7 +362,7 @@ describe('Soroban Service', () => {
expect(mocks.server.simulateTransaction).toHaveBeenCalled();
});

it.skip('decodes getStreamFromChain response', async () => {
it('decodes getStreamFromChain response', async () => {
const { getStreamFromChain } = await importService();
const sender = Keypair.random().publicKey();
const recipient = Keypair.random().publicKey();
Expand All @@ -383,8 +383,10 @@ describe('Soroban Service', () => {
)
);

// The id comes back as the bigint it was asked for, not a number: a
// stream id is u64 and JS numbers lose precision above 2^53.
await expect(getStreamFromChain(7n)).resolves.toEqual({
streamId: 7,
streamId: 7n,
sender,
recipient,
tokenAddress,
Expand All @@ -406,7 +408,7 @@ describe('Soroban Service', () => {
await expect(getStreamFromChain(8n)).resolves.toBeNull();
});

it.skip('decodes getClaimableFromChain response', async () => {
it('decodes getClaimableFromChain response', async () => {
const { getClaimableFromChain } = await importService();

mocks.server.simulateTransaction.mockResolvedValue(
Expand Down
66 changes: 56 additions & 10 deletions frontend/e2e/mocks/api-server.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import http from "node:http";
import https from "node:https";
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { xdr, Keypair, TransactionBuilder, Networks } from "@stellar/stellar-sdk";
import { xdr, Keypair, StrKey, TransactionBuilder, Networks } from "@stellar/stellar-sdk";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CERT_DIR = path.join(__dirname, "..", ".e2e-certs");
Expand All @@ -22,7 +23,7 @@
const DEPOSITED_AMOUNT = "100000000000"; // 10,000 USDC
const WITHDRAW_BATCH = BigInt("100000000"); // 10 USDC per simulated withdrawal

const accountSequence = ["1"];

Check warning on line 26 in frontend/e2e/mocks/api-server.mjs

View workflow job for this annotation

GitHub Actions / Frontend CI

'accountSequence' is assigned a value but never used

const nowSec = () => Math.floor(Date.now() / 1000);

Expand Down Expand Up @@ -98,22 +99,45 @@
const accountEntry = new xdr.AccountEntry({
accountId: kp.xdrAccountId(),
balance: xdr.Int64.fromString("0"),
seqNum: new xdr.SequenceNumber(xdr.Int64.fromString(String(seq))),
seqNum: xdr.Int64.fromString(String(seq)),
numSubEntries: 0,
inflationDest: null,
flags: 0,
homeDomain: "",
thresholds: new Uint8Array(4),
signers: [],
ext: new xdr.AccountEntryExt(0),
ext: xdr.AccountEntryExt.v0(),
});
return xdr.LedgerEntryData.account(accountEntry);
}

function ledgerKeyXdr(publicKey) {

Check warning on line 114 in frontend/e2e/mocks/api-server.mjs

View workflow job for this annotation

GitHub Actions / Frontend CI

'ledgerKeyXdr' is defined but never used
const kp = Keypair.fromPublicKey(publicKey);
return xdr.LedgerKey.account(new xdr.LedgerKeyAccount({ accountId: kp.xdrPublicKey() }));
}

/**
* Public key a `getLedgerEntries` key belongs to.
*
* The SDK asks for the transaction's source account, which is not always the
* session wallet: the withdraw flow also loads the recipient. Answering every
* key with the session account made the SDK report "Account not found" for the
* other one, so resolve the key and serve that account's entry.
*/
function publicKeyOfLedgerKey(keyBase64) {
try {
const ledgerKey = xdr.LedgerKey.fromXDR(keyBase64, "base64");
if (ledgerKey.switch() !== xdr.LedgerEntryType.account()) return SESSION_PUBLIC_KEY;
const accountId = ledgerKey.account().accountId();
if (accountId.switch() !== xdr.PublicKeyType.publicKeyTypeEd25519()) {
return SESSION_PUBLIC_KEY;
}
return StrKey.encodeEd25519PublicKey(accountId.ed25519());
} catch {
return SESSION_PUBLIC_KEY;
}
}

function sorobanTransactionDataBase64() {
const footprint = new xdr.LedgerFootprint({ readOnly: [], readWrite: [] });
const resources = new xdr.SorobanResources({
Expand All @@ -125,7 +149,7 @@
const data = new xdr.SorobanTransactionData({
resources,
resourceFee: 0n,
ext: new xdr.SorobanTransactionDataExt(0),
ext: xdr.SorobanTransactionDataExt.v0(),
});
return data.toXDR("base64");
}
Expand Down Expand Up @@ -246,12 +270,12 @@
return new xdr.TransactionResult({
feeCharged: xdr.Int64.fromString("0"),
result: xdr.TransactionResultResult.txSuccess([]),
ext: new xdr.TransactionResultExt(0),
ext: xdr.TransactionResultExt.v0(),
}).toXDR("base64");
}

function zeroTxMetaBase64() {
return new xdr.TransactionMeta(0, []).toXDR("base64");
return xdr.TransactionMeta.operations([]).toXDR("base64");
}

function dummyEnvelopeBase64() {
Expand Down Expand Up @@ -318,7 +342,7 @@
const entries = keys.length
? keys.map((keyBase64) => ({
key: keyBase64,
xdr: accountEntryXdr(SESSION_PUBLIC_KEY, 1).toXDR("base64"),
xdr: accountEntryXdr(publicKeyOfLedgerKey(keyBase64), 1).toXDR("base64"),
lastModifiedLedgerSeq: 0,
}))
: [];
Expand Down Expand Up @@ -380,11 +404,33 @@
console.log(`[mock-api] rest+sse listening on http://localhost:${PORT}`);
});

if (!fs.existsSync(CERT_PATH) || !fs.existsSync(KEY_PATH)) {
console.error("[mock-api] missing TLS certs — run the pw global-setup first (playwright install)");
process.exit(1);
// Playwright starts webServer before it runs globalSetup, so a clean checkout
// (CI) reaches this point before e2e/global-setup.ts has made the certs. Create
// them here too instead of refusing to start; the global setup still reuses them.
function ensureTlsCerts() {
if (fs.existsSync(CERT_PATH) && fs.existsSync(KEY_PATH)) return;
fs.mkdirSync(CERT_DIR, { recursive: true });
try {
execFileSync(
"openssl",
[
"req", "-x509", "-newkey", "rsa:2048", "-nodes",
"-keyout", KEY_PATH,
"-out", CERT_PATH,
"-days", "3650",
"-subj", "/CN=localhost",
"-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1",
],
{ stdio: "pipe" },
);
} catch (err) {
console.error(`[mock-api] could not create the self-signed TLS certs: ${err.message}`);
process.exit(1);
}
}

ensureTlsCerts();

const rpcServer = https.createServer(
{ cert: fs.readFileSync(CERT_PATH), key: fs.readFileSync(KEY_PATH) },
handleRpc,
Expand Down
13 changes: 10 additions & 3 deletions frontend/e2e/stream-creation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,18 @@ test("single-screen /streams/create form validates input and submits a stream",

const amount = page.locator("#create-stream-amount");

await amount.fill("0");
await expect(page.getByText("Amount must be greater than 0")).toBeVisible();

await page.locator("#recipient").fill(RECIPIENT_PUBLIC_KEY);
await page.locator("#create-stream-token").selectOption("USDC");

// The other required fields are filled first because the browser's own
// `required` check blocks the submit (and therefore the app's validation)
// while one of them is empty. The form then validates on submit and renders
// the messages inline.
await amount.fill("0");
await page.getByRole("button", { name: "Start Streaming" }).click();
// The same message shows twice: inline under the field and as a toast.
await expect(page.getByText("Amount must be a positive number").first()).toBeVisible();

await amount.fill("10");
await page.locator("#create-stream-duration").fill("7");

Expand Down
11 changes: 7 additions & 4 deletions frontend/e2e/stream-lifecycle.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,23 @@ test("stream detail page shows stream state and reflects a withdrawal via mock e
}) => {
// Connect as the stream RECIPIENT so the Withdraw action is available.
await mockConnectedWallet(page, RECIPIENT_PUBLIC_KEY);

await page.goto("/streams/42");

const withdrawnCard = page.locator(".glass-card", { hasText: "Withdrawn" }).first();
const claimableCard = page.locator(".glass-card", { hasText: "Claimable" }).first();

await expect(withdrawnCard).toContainText("0 USDC", { timeout: 30_000 });
// Live claimable is capped at the deposited amount by the dashboard contract.
await expect(claimableCard).toContainText("10000 USDC", { timeout: 30_000 });
// The card shows the live claimable amount, which accrues with the stream's
// rate from its start time rather than showing the whole deposit.
await expect(claimableCard).toContainText(/[1-9][0-9.]* USDC/, { timeout: 30_000 });

const bump = await page.request.post(`${MOCK_API_URL}/__e2e/stream/42/withdraw`);
expect(bump.ok()).toBeTruthy();

await expect(withdrawnCard).toContainText("10 USDC", { timeout: 20_000 });
// The mock adds a 10 USDC withdrawal per call, and its state survives the
// retries of this test, so assert that the card moved to a withdrawn amount
// rather than one exact figure.
await expect(withdrawnCard).toContainText(/[1-9][0-9]* USDC/, { timeout: 20_000 });

const eventRow = page
.locator("div.flex.items-center.gap-4.py-3", { hasText: "Withdrawn" })
Expand Down
13 changes: 13 additions & 0 deletions frontend/e2e/utils/freighter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,24 @@ export async function seedWalletSession(
);
}

/**
* Selects the sandbox network, whose RPC URL comes from the environment
* (`NEXT_PUBLIC_SANDBOX_RPC_URL` in playwright.config.ts). The testnet config
* hardcodes the public testnet, so anything that signs a transaction has to run
* against this network to reach the in-process mock instead.
*/
export async function selectMockNetwork(page: Page): Promise<void> {
await page.addInitScript(() => {
window.localStorage.setItem("flowfi.network", "sandbox");
});
}

/** Sets up a mocked Freighter extension AND a persisted connected session. */
export async function mockConnectedWallet(
page: Page,
address: string = WALLET_PUBLIC_KEY,
): Promise<void> {
await installFreighterMock(page, address);
await seedWalletSession(page, address);
await selectMockNetwork(page);
}
10 changes: 7 additions & 3 deletions frontend/playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ export default defineConfig({
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: process.env.CI
? [["list"], ["html", { open: "never" }]]
: [["list"], ["html", { open: "never" }]],
reporter: [["list"], ["html", { open: "never" }]],
use: {
baseURL: `http://localhost:${APP_PORT}`,
ignoreHTTPSErrors: true,
Expand Down Expand Up @@ -42,6 +40,12 @@ export default defineConfig({
NEXT_PUBLIC_SOROBAN_RPC_URL: `https://localhost:${RPC_PORT}/soroban`,
NEXT_PUBLIC_NETWORK_PASSPHRASE: "Test SDF Network ; September 2015",
NEXT_PUBLIC_STREAM_CONTRACT_ID: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFCT4",
// The withdraw flow builds a real Soroban transaction; the sandbox
// network is the one whose RPC URL comes from the environment, so the
// specs can point it at the in-process mock instead of the testnet.
NEXT_PUBLIC_SANDBOX_RPC_URL: `https://localhost:${RPC_PORT}/soroban`,
NEXT_PUBLIC_SANDBOX_STREAM_CONTRACT_ID:
"CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFCT4",
},
},
],
Expand Down
Loading
Loading