import { test } from "node:test";
import assert from "node:assert/strict";
import { isRecoverableWalletReady, prepareRecoverableWallet } from "./sequence.ts";
const EXTERNAL = "0x1111111111111111111111111111111111111111";
const OTHER = "0x2222222222222222222222222222222222222222";
const EMBEDDED = "0x3333333333333333333333333333333333333333";
const REPLACEMENT = "0x4444444444444444444444444444444444444444";
const embedded = (address) => ({ type: "wallet", chainType: "ethereum", address,
walletClientType: "privy", connectorType: "embedded" });
const externalAccount = (address) => ({ type: "wallet", chainType: "ethereum", address,
walletClientType: "metamask", connectorType: "injected" });
const guest = () => ({ id: "guest-original", isGuest: true, linkedAccounts: [embedded(EMBEDDED)] });
const full = (address = EMBEDDED) => ({ id: "guest-original", isGuest: false,
linkedAccounts: [externalAccount(EXTERNAL), ...(address ? [embedded(address)] : [])] });
function fixture(initial, options = {}) {
const state = { user: initial, selected: EXTERNAL, refreshes: 0 };
const calls = [];
const operations = {
async refreshUser() {
calls.push("refresh"); state.refreshes++;
return structuredClone(options.refresh ? options.refresh(state) : state.user);
},
async generateLinkMessage(input) { calls.push("link-message"); assert.equal(input.address, EXTERNAL); return "link challenge"; },
async linkWithSiwe(input) {
calls.push("link"); assert.equal(input.message, "link challenge");
if (options.link) return options.link(state);
state.user = full();
},
async generateLoginMessage(input) { calls.push("login-message"); assert.equal(input.address, EXTERNAL); return "login challenge"; },
async loginWithSiwe(input) {
calls.push(input.disableSignup ? "login-no-signup" : "login-with-signup");
assert.equal(input.message, "login challenge");
if (options.login) return options.login(state, input);
state.user = structuredClone(options.loginUser ?? full());
return structuredClone(state.user);
},
async createWallet() {
calls.push("create-wallet");
if (options.create) return options.create(state);
state.user.linkedAccounts.push(embedded(EMBEDDED));
return { address: EMBEDDED };
},
async logout() { calls.push("logout"); },
async deleteGuest() { calls.push("delete-guest"); },
};
const external = {
address: EXTERNAL, chainId: 99901,
getAddress: async () => state.selected,
async signMessage(message) {
calls.push("signature");
if (options.sign) return options.sign(state, message);
return "fixture signature";
},
};
return { state, calls, operations, external,
run: (mode = "recover", user = initial) => prepareRecoverableWallet({ user, external, operations, mode }) };
}
test("links the accessible guest and preserves its user ID and embedded address", async () => {
const f = fixture(guest());
assert.deepEqual(await f.run(), { userId: "guest-original", embeddedAddress: EMBEDDED, externalAddress: EXTERNAL });
assert.equal(f.state.user.isGuest, false);
assert.equal(f.calls.filter((x) => x === "link").length, 1);
assert.ok(!f.calls.some((x) => /login-|create-wallet|logout|delete/.test(x)));
});
test("rejects a changed user ID returned after guest linking", async () => {
const f = fixture(guest(), { link: (state) => { state.user = { ...full(), id: "different-account" }; } });
await assert.rejects(f.run(), /original guest wallet was not preserved/);
assert.ok(!f.calls.includes("create-wallet"));
});
test("rejects a replacement embedded wallet returned after linking", async () => {
const f = fixture(guest(), { link: (state) => { state.user = full(REPLACEMENT); } });
await assert.rejects(f.run(), /original guest wallet was not preserved/);
});
test("a rejected wallet signature submits neither linking nor login", async () => {
const rejection = new Error("User rejected the signature");
const f = fixture(guest(), { sign: () => { throw rejection; } });
await assert.rejects(f.run(), (error) => error === rejection);
assert.deepEqual(f.state.user, guest());
assert.ok(!f.calls.some((x) => /^(link|login-no-signup|login-with-signup|create-wallet)$/.test(x)));
});
test("credential conflict preserves the guest and never logs out, deletes, creates or falls back to login", async () => {
const conflict = new Error("Wallet is already linked to another account");
const f = fixture(guest(), { link: () => { throw conflict; } });
await assert.rejects(f.run(), (error) => error === conflict);
assert.deepEqual(f.state.user, guest());
assert.ok(!f.calls.some((x) => /login-|create-wallet|logout|delete/.test(x)));
});
test("a clean returning session uses no-signup login and recovers the same embedded address", async () => {
const f = fixture(null);
assert.deepEqual(await f.run(), { userId: "guest-original", embeddedAddress: EMBEDDED, externalAddress: EXTERNAL });
assert.ok(f.calls.includes("login-no-signup"));
assert.ok(!f.calls.includes("create-wallet"));
});
test("unknown recovery credential cannot sign up or create a replacement wallet", async () => {
const f = fixture(null, { login: (_state, input) => {
assert.equal(input.disableSignup, true);
throw new Error("No account exists for this credential");
} });
await assert.rejects(f.run(), /No account exists/);
assert.ok(!f.calls.includes("login-with-signup"));
assert.ok(!f.calls.includes("create-wallet"));
});
test("recovery login with no existing embedded wallet fails without creating one", async () => {
const f = fixture(null, { loginUser: full(null) });
await assert.rejects(f.run(), /existing embedded wallet could not be recovered/);
assert.ok(!f.calls.includes("create-wallet"));
});
test("a new unfunded SIWE account creates and confirms one embedded wallet explicitly", async () => {
const f = fixture(null, { loginUser: full(null) });
assert.equal((await f.run("new")).embeddedAddress, EMBEDDED);
assert.equal(f.calls.filter((x) => x === "create-wallet").length, 1);
assert.ok(f.calls.includes("login-with-signup"));
});
test("an uncertain wallet-creation result is not retried automatically and a later refresh reuses the original", async () => {
const f = fixture(null, { loginUser: full(null), create: (state) => {
state.user.linkedAccounts.push(embedded(EMBEDDED));
throw new Error("Wallet creation response was lost");
} });
await assert.rejects(f.run("new"), /response was lost/);
assert.equal(f.calls.filter((x) => x === "create-wallet").length, 1);
assert.equal((await f.run("new", full(null))).embeddedAddress, EMBEDDED);
assert.equal(f.calls.filter((x) => x === "create-wallet").length, 1);
});
test("an accessible guest without its original embedded wallet is not replaced", async () => {
const f = fixture({ ...guest(), linkedAccounts: [] });
await assert.rejects(f.run("new"), /Wait for the existing guest wallet/);
assert.ok(!f.calls.includes("create-wallet"));
assert.ok(!f.calls.includes("link"));
});
test("an external account change during signing stops before linking", async () => {
const f = fixture(guest(), { sign: (state) => { state.selected = OTHER; return "fixture signature"; } });
await assert.rejects(f.run(), /connected wallet changed/);
assert.ok(!f.calls.includes("link"));
});
test("a Privy account change during signing stops before linking", async () => {
const f = fixture(guest(), { refresh: (state) => state.refreshes === 2
? { ...guest(), id: "other-guest" } : state.user });
await assert.rejects(f.run(), /guest account changed/);
assert.ok(!f.calls.includes("link"));
});
test("an authenticated account belonging to a different external wallet is not silently switched", async () => {
const f = fixture({ ...full(), linkedAccounts: [externalAccount(OTHER), embedded(EMBEDDED)] });
await assert.rejects(f.run(), /verified wallet login is required/);
assert.ok(!f.calls.some((x) => /login-|logout|delete|create-wallet|link-message/.test(x)));
});
test("ambiguous embedded wallets fail instead of choosing an arbitrary signer", async () => {
const f = fixture({ ...guest(), linkedAccounts: [embedded(EMBEDDED), embedded(REPLACEMENT)] });
await assert.rejects(f.run(), /Wait for the existing guest wallet/);
assert.ok(!f.calls.includes("link"));
});
test("a stale wallet connection cannot authorize funding after embedded metadata is removed or replaced", async () => {
const f = fixture(guest());
const result = await f.run();
const gate = (user) => isRecoverableWalletReady({ user, result,
externalAddress: EXTERNAL, connectedEmbeddedAddress: EMBEDDED });
assert.equal(gate(full()), true);
assert.equal(gate(full(null)), false);
assert.equal(gate(full(REPLACEMENT)), false);
assert.equal(gate({ ...full(), linkedAccounts: [...full().linkedAccounts, embedded(REPLACEMENT)] }), false);
});
test("funding readiness is revoked when the external account, current user or connected wallet changes", async () => {
const f = fixture(guest());
const result = await f.run();
const ready = { user: full(), result, externalAddress: EXTERNAL, connectedEmbeddedAddress: EMBEDDED };
assert.equal(isRecoverableWalletReady(ready), true);
assert.equal(isRecoverableWalletReady({ ...ready, externalAddress: OTHER }), false);
assert.equal(isRecoverableWalletReady({ ...ready, user: { ...full(), id: "other-user" } }), false);
assert.equal(isRecoverableWalletReady({ ...ready, user: guest() }), false);
assert.equal(isRecoverableWalletReady({ ...ready, connectedEmbeddedAddress: REPLACEMENT }), false);
assert.equal(isRecoverableWalletReady({ ...ready, connectedEmbeddedAddress: undefined }), false);
});