@wallets-e2e/freighter 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +121 -2
- package/fixtures/wallet.ts +41 -0
- package/lib/fixtures/wallet.d.ts +15 -0
- package/lib/fixtures/wallet.d.ts.map +1 -0
- package/lib/fixtures/wallet.js +36 -0
- package/lib/fixtures/wallet.js.map +1 -0
- package/lib/src/extension.d.ts +27 -0
- package/lib/src/extension.d.ts.map +1 -0
- package/lib/src/extension.js +82 -0
- package/lib/src/extension.js.map +1 -0
- package/lib/src/index.d.ts +40 -0
- package/lib/src/index.d.ts.map +1 -0
- package/lib/src/index.js +56 -0
- package/lib/src/index.js.map +1 -0
- package/lib/src/networks.d.ts +14 -0
- package/lib/src/networks.d.ts.map +1 -0
- package/lib/src/networks.js +16 -0
- package/lib/src/networks.js.map +1 -0
- package/lib/src/onboarding.d.ts +40 -0
- package/lib/src/onboarding.d.ts.map +1 -0
- package/lib/src/onboarding.js +137 -0
- package/lib/src/onboarding.js.map +1 -0
- package/lib/src/prompts.d.ts +16 -0
- package/lib/src/prompts.d.ts.map +1 -0
- package/lib/src/prompts.js +41 -0
- package/lib/src/prompts.js.map +1 -0
- package/lib/src/selectors.d.ts +56 -0
- package/lib/src/selectors.d.ts.map +1 -0
- package/lib/src/selectors.js +50 -0
- package/lib/src/selectors.js.map +1 -0
- package/lib/src/test.d.ts +26 -0
- package/lib/src/test.d.ts.map +1 -0
- package/lib/src/test.js +36 -0
- package/lib/src/test.js.map +1 -0
- package/lib/src/utils.d.ts +14 -0
- package/lib/src/utils.d.ts.map +1 -0
- package/lib/src/utils.js +29 -0
- package/lib/src/utils.js.map +1 -0
- package/package.json +71 -3
- package/scripts/extension.mjs +111 -0
- package/scripts/prepare-extension.mjs +37 -0
- package/src/extension.ts +91 -0
- package/src/index.ts +103 -0
- package/src/networks.ts +26 -0
- package/src/onboarding.ts +144 -0
- package/src/prompts.ts +61 -0
- package/src/selectors.ts +54 -0
- package/src/test.ts +64 -0
- package/src/utils.ts +32 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fetches and verifies the pinned, official Freighter release build this package drives. The wallet
|
|
3
|
+
* has been named Varial since October 2026; its repository and release assets keep the old name.
|
|
4
|
+
*
|
|
5
|
+
* Plain JavaScript with no dependencies, because it runs in three places where the package's own
|
|
6
|
+
* compiled output may not exist yet: a consumer's `postinstall`, the `wallets-e2e-freighter` bin,
|
|
7
|
+
* and this monorepo's `build:extension`.
|
|
8
|
+
*
|
|
9
|
+
* The archive is checked against a pinned SHA-256 before it is unpacked: the release asset is the
|
|
10
|
+
* only thing between a consumer's test wallet and the code that holds its key.
|
|
11
|
+
*/
|
|
12
|
+
import { execFileSync } from 'node:child_process';
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
14
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
15
|
+
import { tmpdir } from 'node:os';
|
|
16
|
+
import { dirname, join } from 'node:path';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
|
|
19
|
+
export const FREIGHTER_VERSION = '5.53.1';
|
|
20
|
+
|
|
21
|
+
/** SHA-256 of `build-5.53.1.zip` as published on the stellar/freighter release of the same tag. */
|
|
22
|
+
export const FREIGHTER_ARCHIVE_SHA256 = 'fd6567de460e438989f5ea780cba8a37317347a47cacb930727015d797cef68f';
|
|
23
|
+
|
|
24
|
+
/** Set to point every consumer at an unpacked extension of their own. */
|
|
25
|
+
export const EXTENSION_PATH_ENV = 'FREIGHTER_EXTENSION_PATH';
|
|
26
|
+
|
|
27
|
+
const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Where the extension lives: an explicit override, else inside this package, so a consumer's
|
|
31
|
+
* repository never has to hold a copy or a download script of its own.
|
|
32
|
+
*/
|
|
33
|
+
export function extensionDir() {
|
|
34
|
+
const override = process.env[EXTENSION_PATH_ENV]?.trim();
|
|
35
|
+
return override ? override : join(packageRoot, 'dist');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The version actually unpacked at `dir`, or null when nothing usable is there. */
|
|
39
|
+
export function installedVersion(dir = extensionDir()) {
|
|
40
|
+
const manifestPath = join(dir, 'manifest.json');
|
|
41
|
+
if (!existsSync(manifestPath)) return null;
|
|
42
|
+
try {
|
|
43
|
+
const version = JSON.parse(readFileSync(manifestPath, 'utf8')).version;
|
|
44
|
+
return typeof version === 'string' ? version : null;
|
|
45
|
+
} catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function isExtensionReady(dir = extensionDir()) {
|
|
51
|
+
return installedVersion(dir) === FREIGHTER_VERSION;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The archive's URL on the release of the pinned tag. */
|
|
55
|
+
export function archiveUrl(version = FREIGHTER_VERSION) {
|
|
56
|
+
return `https://github.com/stellar/freighter/releases/download/${version}/build-${version}.zip`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Downloads, verifies and unpacks the pinned release into `dir`, replacing whatever is there.
|
|
61
|
+
*
|
|
62
|
+
* A stale or partial artifact is removed rather than kept, so a run can never silently exercise a
|
|
63
|
+
* different wallet UI than the one the driver's selectors were written against.
|
|
64
|
+
*/
|
|
65
|
+
export async function downloadExtension(dir = extensionDir(), log = console.error) {
|
|
66
|
+
const url = archiveUrl();
|
|
67
|
+
// Staged in a temp directory, not beside the target: the target may be inside a consumer's
|
|
68
|
+
// node_modules, and a half-written archive must never be left there.
|
|
69
|
+
const stagingDir = mkdtempSync(join(tmpdir(), 'wallets-e2e-freighter-'));
|
|
70
|
+
const zipPath = join(stagingDir, `build-${FREIGHTER_VERSION}.zip`);
|
|
71
|
+
|
|
72
|
+
log(`[wallets-e2e/freighter] Fetching pinned Freighter ${FREIGHTER_VERSION}`);
|
|
73
|
+
const response = await fetch(url, { redirect: 'follow' });
|
|
74
|
+
if (!response.ok) {
|
|
75
|
+
rmSync(stagingDir, { recursive: true, force: true });
|
|
76
|
+
throw new Error(`Download failed: HTTP ${response.status} ${url}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
try {
|
|
80
|
+
const archive = Buffer.from(await response.arrayBuffer());
|
|
81
|
+
const digest = createHash('sha256').update(archive).digest('hex');
|
|
82
|
+
if (digest !== FREIGHTER_ARCHIVE_SHA256) {
|
|
83
|
+
throw new Error(`Checksum mismatch for ${url}: got ${digest}, expected ${FREIGHTER_ARCHIVE_SHA256}.`);
|
|
84
|
+
}
|
|
85
|
+
writeFileSync(zipPath, archive);
|
|
86
|
+
|
|
87
|
+
rmSync(dir, { recursive: true, force: true });
|
|
88
|
+
mkdirSync(dir, { recursive: true });
|
|
89
|
+
execFileSync('unzip', ['-q', '-o', zipPath, '-d', dir], { stdio: 'inherit' });
|
|
90
|
+
} finally {
|
|
91
|
+
rmSync(stagingDir, { recursive: true, force: true });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const found = installedVersion(dir);
|
|
95
|
+
if (found !== FREIGHTER_VERSION) {
|
|
96
|
+
rmSync(dir, { recursive: true, force: true });
|
|
97
|
+
throw new Error(`Unexpected Freighter version ${String(found)}; expected ${FREIGHTER_VERSION}.`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
log(`[wallets-e2e/freighter] Freighter ${FREIGHTER_VERSION} ready at ${dir}`);
|
|
101
|
+
return dir;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Idempotent: downloads only when the pinned version is not already unpacked at `dir`. */
|
|
105
|
+
export async function ensureExtension(dir = extensionDir(), log = console.error) {
|
|
106
|
+
if (isExtensionReady(dir)) {
|
|
107
|
+
log(`[wallets-e2e/freighter] Freighter ${FREIGHTER_VERSION} already at ${dir}`);
|
|
108
|
+
return dir;
|
|
109
|
+
}
|
|
110
|
+
return downloadExtension(dir, log);
|
|
111
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* CLI around `extension.mjs`, used as this package's `postinstall`, as the `wallets-e2e-freighter`
|
|
4
|
+
* bin, and as the monorepo's `build:extension`.
|
|
5
|
+
*
|
|
6
|
+
* Usage: wallets-e2e-freighter [prepare] [--force] [--optional] [--dir <path>]
|
|
7
|
+
*
|
|
8
|
+
* `--optional` never fails the caller: an install behind a proxy, offline, or without `unzip` still
|
|
9
|
+
* succeeds, and the download is retried lazily on the first test run instead.
|
|
10
|
+
*/
|
|
11
|
+
import { downloadExtension, ensureExtension, extensionDir, FREIGHTER_VERSION } from './extension.mjs';
|
|
12
|
+
|
|
13
|
+
const argv = process.argv.slice(2).filter((arg) => arg !== 'prepare');
|
|
14
|
+
const force = argv.includes('--force');
|
|
15
|
+
const optional = argv.includes('--optional');
|
|
16
|
+
const dirFlag = argv.indexOf('--dir');
|
|
17
|
+
const dir = dirFlag === -1 ? extensionDir() : argv[dirFlag + 1];
|
|
18
|
+
|
|
19
|
+
if (!dir) {
|
|
20
|
+
console.error('[wallets-e2e/freighter] --dir needs a path.');
|
|
21
|
+
process.exit(1);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
await (force ? downloadExtension(dir) : ensureExtension(dir));
|
|
26
|
+
} catch (error) {
|
|
27
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
28
|
+
if (optional) {
|
|
29
|
+
console.error(
|
|
30
|
+
`[wallets-e2e/freighter] Could not prepare Freighter ${FREIGHTER_VERSION} now (${message}). ` +
|
|
31
|
+
`It will be downloaded on the first test run, or run \`npx wallets-e2e-freighter\` yourself.`,
|
|
32
|
+
);
|
|
33
|
+
process.exit(0);
|
|
34
|
+
}
|
|
35
|
+
console.error(`[wallets-e2e/freighter] ERROR: ${message}`);
|
|
36
|
+
process.exit(1);
|
|
37
|
+
}
|
package/src/extension.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
4
|
+
|
|
5
|
+
/** The only Freighter build this package's selectors are written against. */
|
|
6
|
+
export const FREIGHTER_VERSION = '5.53.1';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Freighter's background service worker, as its manifest names it. The driver finds its own
|
|
10
|
+
* extension by it, so another wallet loaded in the same browser is never mistaken for Freighter.
|
|
11
|
+
*/
|
|
12
|
+
export const FREIGHTER_SERVICE_WORKER = 'background.min.js';
|
|
13
|
+
|
|
14
|
+
/** Points the driver at an unpacked extension of your own instead of the packaged one. */
|
|
15
|
+
export const FREIGHTER_EXTENSION_PATH_ENV = 'FREIGHTER_EXTENSION_PATH';
|
|
16
|
+
|
|
17
|
+
/** Printed when the extension is missing, and runnable as-is. */
|
|
18
|
+
export const FREIGHTER_PREPARE_COMMAND = 'npx wallets-e2e-freighter';
|
|
19
|
+
|
|
20
|
+
interface ExtensionScript {
|
|
21
|
+
ensureExtension(dir?: string, log?: (message: string) => void): Promise<string>;
|
|
22
|
+
downloadExtension(dir?: string, log?: (message: string) => void): Promise<string>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Walks up from this module to the package it was published in. Resolved at runtime rather than
|
|
27
|
+
* written as a relative depth, because this file is imported both from `lib/src` (published) and
|
|
28
|
+
* from `src` (this monorepo, and consumers running the TypeScript sources directly).
|
|
29
|
+
*/
|
|
30
|
+
function packageRoot(): string {
|
|
31
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
32
|
+
for (let i = 0; i < 6; i++) {
|
|
33
|
+
const manifest = join(dir, 'package.json');
|
|
34
|
+
if (existsSync(manifest)) {
|
|
35
|
+
try {
|
|
36
|
+
if (JSON.parse(readFileSync(manifest, 'utf8')).name === '@wallets-e2e/freighter') return dir;
|
|
37
|
+
} catch {
|
|
38
|
+
// Unreadable package.json: keep walking rather than guessing.
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const parent = dirname(dir);
|
|
42
|
+
if (parent === dir) break;
|
|
43
|
+
dir = parent;
|
|
44
|
+
}
|
|
45
|
+
throw new Error('[@wallets-e2e/freighter] Could not locate the package root.');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Where the unpacked extension is, without touching the network: the `FREIGHTER_EXTENSION_PATH`
|
|
50
|
+
* override when set, else the copy inside this package. Safe to call at module scope — the
|
|
51
|
+
* directory does not have to exist yet.
|
|
52
|
+
*/
|
|
53
|
+
export function freighterExtensionPath(): string {
|
|
54
|
+
const override = process.env[FREIGHTER_EXTENSION_PATH_ENV]?.trim();
|
|
55
|
+
return override ? override : join(packageRoot(), 'dist');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function isFreighterExtensionReady(dir = freighterExtensionPath()): boolean {
|
|
59
|
+
const manifestPath = join(dir, 'manifest.json');
|
|
60
|
+
if (!existsSync(manifestPath)) return false;
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(readFileSync(manifestPath, 'utf8')).version === FREIGHTER_VERSION;
|
|
63
|
+
} catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function extensionScript(): Promise<ExtensionScript> {
|
|
69
|
+
const path = join(packageRoot(), 'scripts', 'extension.mjs');
|
|
70
|
+
return (await import(pathToFileURL(path).href)) as ExtensionScript;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Makes sure the pinned Freighter build is unpacked, downloading it when it is not, and returns its
|
|
75
|
+
* path. Idempotent and safe to call on every run.
|
|
76
|
+
*
|
|
77
|
+
* The install-time `postinstall` normally does this already; this is the fallback for the installs
|
|
78
|
+
* where it could not run — `--ignore-scripts`, an offline or proxied CI, a restored cache.
|
|
79
|
+
*/
|
|
80
|
+
export async function ensureFreighterExtension(dir = freighterExtensionPath()): Promise<string> {
|
|
81
|
+
if (isFreighterExtensionReady(dir)) return dir;
|
|
82
|
+
if (process.env[FREIGHTER_EXTENSION_PATH_ENV]?.trim()) {
|
|
83
|
+
// An explicit override is the caller's own build. Downloading over it would discard it.
|
|
84
|
+
throw new Error(
|
|
85
|
+
`[@wallets-e2e/freighter] ${FREIGHTER_EXTENSION_PATH_ENV} points at "${dir}", which holds no ` +
|
|
86
|
+
`Freighter ${FREIGHTER_VERSION} build. Unset it to use the packaged extension.`,
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
const { ensureExtension } = await extensionScript();
|
|
90
|
+
return ensureExtension(dir);
|
|
91
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { BrowserContext, WalletAccount, WalletDriver } from '@wallets-e2e/core';
|
|
2
|
+
import { DEFAULT_PROFILE_PASSWORD } from '../fixtures/wallet.js';
|
|
3
|
+
import type { StellarNetwork } from './networks.js';
|
|
4
|
+
import { activeNetwork, ensureNetwork, extensionPage, freighterExtensionId, importWallet, readStorage, type ImportOptions } from './onboarding.js';
|
|
5
|
+
import { cancelPrompt, confirmPrompt, openPrompt, type PromptOptions } from './prompts.js';
|
|
6
|
+
import { ROUTES, STORAGE_KEYS } from './selectors.js';
|
|
7
|
+
import { extensionUrl, STELLAR_ACCOUNT } from './utils.js';
|
|
8
|
+
|
|
9
|
+
export {
|
|
10
|
+
ensureFreighterExtension,
|
|
11
|
+
freighterExtensionPath,
|
|
12
|
+
isFreighterExtensionReady,
|
|
13
|
+
FREIGHTER_EXTENSION_PATH_ENV,
|
|
14
|
+
FREIGHTER_PREPARE_COMMAND,
|
|
15
|
+
FREIGHTER_SERVICE_WORKER,
|
|
16
|
+
FREIGHTER_VERSION,
|
|
17
|
+
} from './extension.js';
|
|
18
|
+
export { createFreighterTest, freighterExtraExtension, type CreateFreighterTestOptions } from './test.js';
|
|
19
|
+
export { STELLAR_NETWORKS, type StellarNetwork, type StellarNetworkInfo } from './networks.js';
|
|
20
|
+
export { freighterExtensionId } from './onboarding.js';
|
|
21
|
+
export type { PromptOptions } from './prompts.js';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Drives the real Freighter extension (named Varial in its own UI since October 2026) for a Stellar
|
|
25
|
+
* or Soroban dapp. Every selector was read off the pinned release build; see `selectors.ts`.
|
|
26
|
+
*
|
|
27
|
+
* What is covered: importing a recovery phrase, choosing the network, the connection prompt and the
|
|
28
|
+
* transaction prompt, each confirmed or cancelled. Message and auth-entry signing prompts are not
|
|
29
|
+
* driven yet.
|
|
30
|
+
*/
|
|
31
|
+
export interface FreighterDriver extends WalletDriver<StellarNetwork> {
|
|
32
|
+
/**
|
|
33
|
+
* Imports a 12- or 24-word recovery phrase and returns the wallet's first account, read from the
|
|
34
|
+
* wallet's own stored state. The wallet's usage-data sharing is turned off unless
|
|
35
|
+
* `shareUsageData` is true. Idempotent in a profile that already holds a wallet.
|
|
36
|
+
*/
|
|
37
|
+
importWallet(context: BrowserContext, seedPhrase: string, options?: Partial<ImportOptions>): Promise<WalletAccount>;
|
|
38
|
+
switchNetwork(context: BrowserContext, network: StellarNetwork): Promise<void>;
|
|
39
|
+
/** Approves the connection prompt `trigger` raises (picking the wallet in the dapp's wallet list). */
|
|
40
|
+
connectToDapp(context: BrowserContext, trigger: () => Promise<void>, options?: PromptOptions): Promise<void>;
|
|
41
|
+
/** Signs the transaction prompt `trigger` raises. */
|
|
42
|
+
confirmTransaction(context: BrowserContext, trigger: () => Promise<void>, options?: PromptOptions): Promise<void>;
|
|
43
|
+
/** Cancels the connection prompt `trigger` raises, as a user who declines does. */
|
|
44
|
+
rejectConnection(context: BrowserContext, trigger: () => Promise<void>, options?: PromptOptions): Promise<void>;
|
|
45
|
+
/** Cancels the transaction prompt `trigger` raises: the dapp gets the wallet's own "declined" answer. */
|
|
46
|
+
rejectTransaction(context: BrowserContext, trigger: () => Promise<void>, options?: PromptOptions): Promise<void>;
|
|
47
|
+
/** The `G…` account the wallet is using, or null before a wallet is imported. */
|
|
48
|
+
activeAccount(context: BrowserContext): Promise<string | null>;
|
|
49
|
+
/** The network the wallet is on, or null for a custom network. */
|
|
50
|
+
activeNetwork(context: BrowserContext): Promise<StellarNetwork | null>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const freighterDriver: FreighterDriver = {
|
|
54
|
+
importWallet(context, seedPhrase, options = {}) {
|
|
55
|
+
return importWallet(context, seedPhrase, { password: DEFAULT_PROFILE_PASSWORD, ...options });
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
switchNetwork(context, network) {
|
|
59
|
+
return ensureNetwork(context, network);
|
|
60
|
+
},
|
|
61
|
+
|
|
62
|
+
async switchToTestnetNetwork(context) {
|
|
63
|
+
await ensureNetwork(context, 'testnet');
|
|
64
|
+
},
|
|
65
|
+
|
|
66
|
+
async connectToDapp(context, trigger, options = {}) {
|
|
67
|
+
const extensionId = await freighterExtensionId(context);
|
|
68
|
+
const prompt = await openPrompt(context, extensionId, 'connect', trigger, options.timeoutMs);
|
|
69
|
+
await confirmPrompt(prompt, 'connect', options);
|
|
70
|
+
},
|
|
71
|
+
|
|
72
|
+
async confirmTransaction(context, trigger, options = {}) {
|
|
73
|
+
const extensionId = await freighterExtensionId(context);
|
|
74
|
+
const prompt = await openPrompt(context, extensionId, 'transaction', trigger, options.timeoutMs);
|
|
75
|
+
await confirmPrompt(prompt, 'transaction', options);
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
async rejectConnection(context, trigger, options = {}) {
|
|
79
|
+
const extensionId = await freighterExtensionId(context);
|
|
80
|
+
const prompt = await openPrompt(context, extensionId, 'connect', trigger, options.timeoutMs);
|
|
81
|
+
await cancelPrompt(prompt, options);
|
|
82
|
+
},
|
|
83
|
+
|
|
84
|
+
async rejectTransaction(context, trigger, options = {}) {
|
|
85
|
+
const extensionId = await freighterExtensionId(context);
|
|
86
|
+
const prompt = await openPrompt(context, extensionId, 'transaction', trigger, options.timeoutMs);
|
|
87
|
+
await cancelPrompt(prompt, options);
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
async activeAccount(context) {
|
|
91
|
+
const extensionId = await freighterExtensionId(context);
|
|
92
|
+
const { page, opened } = await extensionPage(context, extensionId);
|
|
93
|
+
if (opened) await page.goto(extensionUrl(extensionId, ROUTES.settings));
|
|
94
|
+
try {
|
|
95
|
+
const address = (await readStorage(page, [STORAGE_KEYS.lastUsedAccount]))[STORAGE_KEYS.lastUsedAccount];
|
|
96
|
+
return typeof address === 'string' && STELLAR_ACCOUNT.test(address) ? address : null;
|
|
97
|
+
} finally {
|
|
98
|
+
if (opened) await page.close().catch(() => undefined);
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
|
|
102
|
+
activeNetwork,
|
|
103
|
+
};
|
package/src/networks.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** The Stellar networks Freighter ships with. A custom network is added in the wallet's own settings. */
|
|
2
|
+
export type StellarNetwork = 'mainnet' | 'testnet';
|
|
3
|
+
|
|
4
|
+
export interface StellarNetworkInfo {
|
|
5
|
+
/** The option's label in the wallet's network select. */
|
|
6
|
+
label: string;
|
|
7
|
+
/** What the wallet stores as the selected network's `network`. */
|
|
8
|
+
storedName: string;
|
|
9
|
+
/** The passphrase every transaction on the network is signed for. */
|
|
10
|
+
passphrase: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const STELLAR_NETWORKS: Readonly<Record<StellarNetwork, StellarNetworkInfo>> = {
|
|
14
|
+
mainnet: { label: 'Main Net', storedName: 'PUBLIC', passphrase: 'Public Global Stellar Network ; September 2015' },
|
|
15
|
+
testnet: { label: 'Test Net', storedName: 'TESTNET', passphrase: 'Test SDF Network ; September 2015' },
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** The network a stored `network` object names, or null for one the driver does not know (a custom network). */
|
|
19
|
+
export function networkOfStored(stored: unknown): StellarNetwork | null {
|
|
20
|
+
if (typeof stored !== 'object' || stored === null) return null;
|
|
21
|
+
const { network, networkPassphrase } = stored as { network?: unknown; networkPassphrase?: unknown };
|
|
22
|
+
for (const [name, info] of Object.entries(STELLAR_NETWORKS) as [StellarNetwork, StellarNetworkInfo][]) {
|
|
23
|
+
if (networkPassphrase === info.passphrase || network === info.storedName) return name;
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import type { BrowserContext, Page } from '@playwright/test';
|
|
2
|
+
import { resolveExtensionId, type WalletAccount } from '@wallets-e2e/core';
|
|
3
|
+
import { FREIGHTER_SERVICE_WORKER } from './extension.js';
|
|
4
|
+
import { networkOfStored, STELLAR_NETWORKS, type StellarNetwork } from './networks.js';
|
|
5
|
+
import { ONBOARDING, ROUTES, SETTINGS, STORAGE_KEYS } from './selectors.js';
|
|
6
|
+
import { extensionUrl, phraseWords, STELLAR_ACCOUNT } from './utils.js';
|
|
7
|
+
|
|
8
|
+
/** The id of the Freighter extension in `context`, whatever other extension is loaded beside it. */
|
|
9
|
+
export function freighterExtensionId(context: BrowserContext): Promise<string> {
|
|
10
|
+
return resolveExtensionId(context, { serviceWorkerPath: FREIGHTER_SERVICE_WORKER });
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A page of the extension to work in. Freighter opens its welcome tab by itself on first load, but
|
|
15
|
+
* not reliably before the first driver call, so an open one is reused and one is opened otherwise.
|
|
16
|
+
*/
|
|
17
|
+
export async function extensionPage(context: BrowserContext, extensionId: string): Promise<{ page: Page; opened: boolean }> {
|
|
18
|
+
const prefix = `chrome-extension://${extensionId}/`;
|
|
19
|
+
const open = context.pages().find((page) => page.url().startsWith(prefix) && !page.url().includes(ROUTES.grantAccess) && !page.url().includes(ROUTES.signTransaction));
|
|
20
|
+
if (open) return { page: open, opened: false };
|
|
21
|
+
return { page: await context.newPage(), opened: true };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Reads the wallet's own `chrome.storage.local`, from one of its pages. */
|
|
25
|
+
export async function readStorage(page: Page, keys: readonly string[]): Promise<Record<string, unknown>> {
|
|
26
|
+
return page.evaluate((names) => chrome.storage.local.get(names) as Promise<Record<string, unknown>>, [...keys]);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ImportOptions {
|
|
30
|
+
/** The wallet's unlock password in this browser profile. */
|
|
31
|
+
password: string;
|
|
32
|
+
/**
|
|
33
|
+
* Whether the wallet may share usage data with its analytics providers. Freighter turns this on
|
|
34
|
+
* by default and it reports the wallet's public keys, so the driver turns it off unless told otherwise.
|
|
35
|
+
*/
|
|
36
|
+
shareUsageData?: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Imports a recovery phrase through the wallet's own onboarding and returns the account it produced.
|
|
41
|
+
*
|
|
42
|
+
* The address is not read off the screen: the wallet shows it shortened. It is read from the
|
|
43
|
+
* wallet's own persisted state (`lastUsedAccount`), which only exists once the import really
|
|
44
|
+
* created an account, so a flow that "completed" without one fails here.
|
|
45
|
+
*
|
|
46
|
+
* Idempotent: a profile that already holds a wallet is left as it is and its account is returned,
|
|
47
|
+
* so a worker-scoped browser can call this at the start of every test.
|
|
48
|
+
*/
|
|
49
|
+
export async function importWallet(context: BrowserContext, seedPhrase: string, options: ImportOptions): Promise<WalletAccount> {
|
|
50
|
+
const words = phraseWords(seedPhrase);
|
|
51
|
+
const extensionId = await freighterExtensionId(context);
|
|
52
|
+
const { page } = await extensionPage(context, extensionId);
|
|
53
|
+
await page.goto(extensionUrl(extensionId, ROUTES.welcome));
|
|
54
|
+
|
|
55
|
+
const existing = await readStorage(page, [STORAGE_KEYS.keyId, STORAGE_KEYS.lastUsedAccount]);
|
|
56
|
+
if (typeof existing[STORAGE_KEYS.keyId] === 'string' && existing[STORAGE_KEYS.keyId] !== '') {
|
|
57
|
+
const address = existing[STORAGE_KEYS.lastUsedAccount];
|
|
58
|
+
if (typeof address === 'string' && STELLAR_ACCOUNT.test(address)) {
|
|
59
|
+
await page.close().catch(() => undefined);
|
|
60
|
+
return { address };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
await page.getByRole('button', { name: ONBOARDING.importWalletButton }).click();
|
|
65
|
+
await page.getByTestId(ONBOARDING.passwordInput).fill(options.password);
|
|
66
|
+
await page.getByTestId(ONBOARDING.confirmPasswordInput).fill(options.password);
|
|
67
|
+
// The checkbox is drawn by a styled sibling that covers the input itself.
|
|
68
|
+
await page.getByTestId(ONBOARDING.termsCheckbox).check({ force: true });
|
|
69
|
+
await page.getByTestId(ONBOARDING.submitPassword).click();
|
|
70
|
+
|
|
71
|
+
// The phrase screen defaults to 12 words; a 24-word phrase needs the toggle first.
|
|
72
|
+
await page.locator(ONBOARDING.phraseWord(1)).waitFor({ state: 'visible', timeout: 30_000 });
|
|
73
|
+
if (words.length === 24) await page.getByText(ONBOARDING.twentyFourWords, { exact: true }).click();
|
|
74
|
+
// Each word goes into its own masked input; the phrase never appears on screen or in a log.
|
|
75
|
+
for (const [index, word] of words.entries()) await page.locator(ONBOARDING.phraseWord(index + 1)).fill(word);
|
|
76
|
+
await page.getByRole('button', { name: ONBOARDING.importButton, exact: true }).click();
|
|
77
|
+
|
|
78
|
+
const address = await waitForAccount(page);
|
|
79
|
+
if (options.shareUsageData !== true) await turnOffUsageDataSharing(page, extensionId);
|
|
80
|
+
await page.close().catch(() => undefined);
|
|
81
|
+
return { address };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Waits for the wallet to persist the imported account and returns it. */
|
|
85
|
+
async function waitForAccount(page: Page, timeoutMs = 60_000): Promise<string> {
|
|
86
|
+
const deadline = Date.now() + timeoutMs;
|
|
87
|
+
while (Date.now() < deadline) {
|
|
88
|
+
const stored = await readStorage(page, [STORAGE_KEYS.lastUsedAccount]).catch(() => ({}) as Record<string, unknown>);
|
|
89
|
+
const address = stored[STORAGE_KEYS.lastUsedAccount];
|
|
90
|
+
if (typeof address === 'string' && STELLAR_ACCOUNT.test(address)) return address;
|
|
91
|
+
await page.waitForTimeout(250);
|
|
92
|
+
}
|
|
93
|
+
throw new Error(
|
|
94
|
+
'[wallets/freighter] The wallet did not store an account after the import. ' +
|
|
95
|
+
'Check that the recovery phrase is a valid BIP-39 phrase of 12 or 24 words.',
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function turnOffUsageDataSharing(page: Page, extensionId: string): Promise<void> {
|
|
100
|
+
await page.goto(extensionUrl(extensionId, ROUTES.preferences));
|
|
101
|
+
const sharing = page.locator(SETTINGS.dataSharingCheckbox);
|
|
102
|
+
await sharing.waitFor({ state: 'attached', timeout: 30_000 });
|
|
103
|
+
// The input sits outside the viewport behind its styled switch: click it in the page itself.
|
|
104
|
+
if (await sharing.isChecked()) await sharing.evaluate((input) => (input as HTMLInputElement).click());
|
|
105
|
+
const deadline = Date.now() + 10_000;
|
|
106
|
+
while ((await sharing.isChecked()) && Date.now() < deadline) await page.waitForTimeout(100);
|
|
107
|
+
if (await sharing.isChecked()) throw new Error('[wallets/freighter] Could not turn off usage data sharing in the wallet.');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The network the wallet is on, or null for a custom one. */
|
|
111
|
+
export async function activeNetwork(context: BrowserContext): Promise<StellarNetwork | null> {
|
|
112
|
+
const extensionId = await freighterExtensionId(context);
|
|
113
|
+
const { page, opened } = await extensionPage(context, extensionId);
|
|
114
|
+
if (opened) await page.goto(extensionUrl(extensionId, ROUTES.settings));
|
|
115
|
+
try {
|
|
116
|
+
return networkOfStored((await readStorage(page, [STORAGE_KEYS.network]))[STORAGE_KEYS.network]);
|
|
117
|
+
} finally {
|
|
118
|
+
if (opened) await page.close().catch(() => undefined);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Puts the wallet on `network` through its own settings, and proves it from the wallet's stored state. */
|
|
123
|
+
export async function ensureNetwork(context: BrowserContext, network: StellarNetwork): Promise<void> {
|
|
124
|
+
const info = STELLAR_NETWORKS[network];
|
|
125
|
+
if (!info) throw new Error(`[wallets/freighter] Unknown Stellar network "${String(network)}". Use "testnet" or "mainnet".`);
|
|
126
|
+
const extensionId = await freighterExtensionId(context);
|
|
127
|
+
const { page, opened } = await extensionPage(context, extensionId);
|
|
128
|
+
try {
|
|
129
|
+
await page.goto(extensionUrl(extensionId, ROUTES.settings));
|
|
130
|
+
const stored = async () => networkOfStored((await readStorage(page, [STORAGE_KEYS.network]))[STORAGE_KEYS.network]);
|
|
131
|
+
if ((await stored()) === network) return;
|
|
132
|
+
await page.getByTestId(SETTINGS.networkLink).click();
|
|
133
|
+
await page.getByTestId(SETTINGS.networkSelect).selectOption({ label: info.label });
|
|
134
|
+
const deadline = Date.now() + 15_000;
|
|
135
|
+
while (Date.now() < deadline) {
|
|
136
|
+
if ((await stored()) === network) return;
|
|
137
|
+
await page.waitForTimeout(200);
|
|
138
|
+
}
|
|
139
|
+
throw new Error(`[wallets/freighter] The wallet did not switch to ${info.label}.`);
|
|
140
|
+
} finally {
|
|
141
|
+
if (opened) await page.close().catch(() => undefined);
|
|
142
|
+
else await page.goto(extensionUrl(extensionId, ROUTES.home)).catch(() => undefined);
|
|
143
|
+
}
|
|
144
|
+
}
|
package/src/prompts.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { BrowserContext, Locator, Page } from '@playwright/test';
|
|
2
|
+
import type { WalletPromptOptions } from '@wallets-e2e/core';
|
|
3
|
+
import { PROMPTS } from './selectors.js';
|
|
4
|
+
import { isPromptUrl } from './utils.js';
|
|
5
|
+
|
|
6
|
+
export type PromptKind = 'connect' | 'transaction';
|
|
7
|
+
|
|
8
|
+
export interface PromptOptions extends WalletPromptOptions {
|
|
9
|
+
/** How long to wait for the wallet's prompt after the trigger. Default 60 s. */
|
|
10
|
+
timeoutMs?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The wallet's prompt for `kind`, opened by `trigger`. Freighter raises each prompt in a window of
|
|
15
|
+
* its own, which is a page of this context: it is looked for among the context's pages rather than
|
|
16
|
+
* awaited as one event, so a prompt that opened before the listener was ready is still found.
|
|
17
|
+
*/
|
|
18
|
+
export async function openPrompt(
|
|
19
|
+
context: BrowserContext,
|
|
20
|
+
extensionId: string,
|
|
21
|
+
kind: PromptKind,
|
|
22
|
+
trigger: () => Promise<void>,
|
|
23
|
+
timeoutMs = 60_000,
|
|
24
|
+
): Promise<Page> {
|
|
25
|
+
const { route } = PROMPTS[kind];
|
|
26
|
+
const before = new Set(context.pages());
|
|
27
|
+
await trigger();
|
|
28
|
+
const deadline = Date.now() + timeoutMs;
|
|
29
|
+
while (Date.now() < deadline) {
|
|
30
|
+
const prompt = context.pages().find((page) => !before.has(page) && isPromptUrl(page.url(), extensionId, route));
|
|
31
|
+
if (prompt) {
|
|
32
|
+
await prompt.waitForLoadState('domcontentloaded');
|
|
33
|
+
return prompt;
|
|
34
|
+
}
|
|
35
|
+
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
36
|
+
}
|
|
37
|
+
const other = context.pages().filter((page) => !before.has(page)).map((page) => page.url().slice(0, 120)).join(', ') || 'none';
|
|
38
|
+
throw new Error(
|
|
39
|
+
`[wallets/freighter] The wallet opened no ${kind} prompt within ${timeoutMs} ms. Pages opened since the trigger: ${other}. ` +
|
|
40
|
+
(kind === 'connect'
|
|
41
|
+
? 'A dapp the wallet already trusts connects without a prompt.'
|
|
42
|
+
: 'A transaction the dapp refused before signing (a failed simulation) never reaches the wallet.'),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Presses `button` on a prompt and waits for the wallet to close it, which is how it says it took the answer. */
|
|
47
|
+
async function answer(prompt: Page, button: Locator, options: PromptOptions): Promise<void> {
|
|
48
|
+
await button.waitFor({ state: 'visible', timeout: 30_000 });
|
|
49
|
+
await options.beforeAnswer?.(prompt, button);
|
|
50
|
+
const closed = prompt.isClosed() ? Promise.resolve() : prompt.waitForEvent('close', { timeout: 30_000 }).catch(() => undefined);
|
|
51
|
+
await button.click();
|
|
52
|
+
await closed;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function confirmPrompt(prompt: Page, kind: PromptKind, options: PromptOptions = {}): Promise<void> {
|
|
56
|
+
return answer(prompt, prompt.getByTestId(PROMPTS[kind].confirm), options);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function cancelPrompt(prompt: Page, options: PromptOptions = {}): Promise<void> {
|
|
60
|
+
return answer(prompt, prompt.getByRole('button', { name: PROMPTS.cancelButton, exact: true }), options);
|
|
61
|
+
}
|
package/src/selectors.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every selector and route the driver relies on, read off the real Freighter 5.53.1 release build
|
|
3
|
+
* (named Varial in its own UI), not guessed. When an upstream release moves one of these, this is
|
|
4
|
+
* the only file to change, together with `FREIGHTER_VERSION`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export const ROUTES = {
|
|
8
|
+
welcome: '#/welcome',
|
|
9
|
+
home: '',
|
|
10
|
+
settings: '#/settings',
|
|
11
|
+
preferences: '#/settings/preferences',
|
|
12
|
+
/** The prompt a dapp's connection request opens, in a window of its own. */
|
|
13
|
+
grantAccess: '#/grant-access',
|
|
14
|
+
/** The prompt a transaction to sign opens, in a window of its own. */
|
|
15
|
+
signTransaction: '#/sign-transaction',
|
|
16
|
+
} as const;
|
|
17
|
+
|
|
18
|
+
export const ONBOARDING = {
|
|
19
|
+
importWalletButton: 'Import wallet',
|
|
20
|
+
passwordInput: 'account-creator-password-input',
|
|
21
|
+
confirmPasswordInput: 'account-creator-confirm-password-input',
|
|
22
|
+
termsCheckbox: 'account-creator-termsOfUse-input',
|
|
23
|
+
submitPassword: 'account-creator-submit',
|
|
24
|
+
/** The recovery phrase is one masked input per word, named `MnemonicPhrase-1` … `-12` (or `-24`). */
|
|
25
|
+
phraseWord: (index: number) => `input[name="MnemonicPhrase-${index}"]`,
|
|
26
|
+
twentyFourWords: '24 word',
|
|
27
|
+
importButton: 'Import',
|
|
28
|
+
/** On the home screen once an account exists. */
|
|
29
|
+
accountChip: 'account-chip',
|
|
30
|
+
} as const;
|
|
31
|
+
|
|
32
|
+
export const SETTINGS = {
|
|
33
|
+
networkLink: 'settings-network-link',
|
|
34
|
+
networkSelect: 'network-settings-select',
|
|
35
|
+
/** "Usage data sharing": on by default, and it reports the wallet's public keys. */
|
|
36
|
+
dataSharingCheckbox: 'input[name="isDataSharingAllowedValue"]',
|
|
37
|
+
} as const;
|
|
38
|
+
|
|
39
|
+
export const PROMPTS = {
|
|
40
|
+
connect: { route: ROUTES.grantAccess, confirm: 'grant-access-connect-button' },
|
|
41
|
+
transaction: { route: ROUTES.signTransaction, confirm: 'sign-transaction-sign' },
|
|
42
|
+
/** Both prompts carry the same plain "Cancel" button. */
|
|
43
|
+
cancelButton: 'Cancel',
|
|
44
|
+
} as const;
|
|
45
|
+
|
|
46
|
+
/** What the wallet keeps in `chrome.storage.local`, as far as the driver reads it. */
|
|
47
|
+
export const STORAGE_KEYS = {
|
|
48
|
+
/** The `G…` account in use: the independent proof that an import produced the expected account. */
|
|
49
|
+
lastUsedAccount: 'lastUsedAccount',
|
|
50
|
+
/** `{ network, networkName, networkPassphrase, … }` of the selected network. */
|
|
51
|
+
network: 'network',
|
|
52
|
+
/** Present once a wallet exists in this profile. */
|
|
53
|
+
keyId: 'keyId',
|
|
54
|
+
} as const;
|