> ## Documentation Index
> Fetch the complete documentation index at: https://spiceflow-docs.spicenet.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Recoverable wallet sign-in

> Keep access to the same embedded wallet after a browser session is lost

Use a recoverable login before accepting funds into an embedded wallet. A guest account alone
depends on local browser credentials. Reconnecting a wallet that funded a deposit does not link
that wallet to the guest account automatically.

This example uses Privy's public headless APIs in `@privy-io/react-auth@3.51.0`. Authentication
belongs to Privy and your app. Spice Flow continues to own balances, quotes, fees, funding,
execution and transaction recovery.

## Configure Privy

Enable wallet authentication and allow the exact origin in your Privy app. SIWE verifies a signed
message from the user's connected Ethereum wallet. It does not require a separate JWT login
server or Privy's login modal.

Follow [Installation](https://spiceflow-docs.spicenet.io/sdk/installation.md), but disable automatic embedded-wallet creation for
this reference:

```tsx theme={null}
<PrivyProvider
  appId="your-privy-app-id"
  config={{
    embeddedWallets: {
      ethereum: { createOnLogin: "off" },
    },
  }}
>
  {children}
</PrivyProvider>
```

Keep this setting off for every recovery entry point. `createOnLogin: "all-users"` could create
a missing embedded wallet during authentication, before the reference checks the account.
Existing guest wallets remain available. The reference preserves an accessible guest's wallet
and explicitly creates a wallet only when needed in the `"new"` path for an unfunded account.
The `"recover"` path never creates a replacement wallet.

For a new user, start with wallet sign-in through `prepare("new")` without first creating a
guest. The guest-upgrade path requires the original guest wallet to already exist.

## Use the reference

Copy the [reference files](#reference-files)
into your application. `useRecoverableWallet` accepts your actual connected external wallet,
including a function that reads its current address and a function that signs the requested
message. Do not select `wallets[0]`: it may be the embedded wallet.

```tsx theme={null}
import { useRecoverableWallet } from "./useRecoverableWallet";

// Build this adapter from the host's existing connected wallet/provider.
const session = useRecoverableWallet(externalWallet);

// A new deposit may authenticate a new user or secure an accessible guest.
await session.prepare("new");

// Render or enable the existing SDK funding flow only when session.canFund is true.
// Wait for React to publish that state and the matching embedded wallet connection.
```

For a returning user who needs recovery, call `session.prepare("recover")` instead. This sets
`disableSignup: true` on `loginWithSiwe`, so an unrecognized login cannot silently create a
different account. The provider and hook must remain mounted while the SDK uses that session.
Render authentication rejection or failure from the hook's `error` state; do not continue funding.

## Preserve an accessible guest

If the current user is a guest, keep that session authenticated and link the external wallet to
it. The reference uses `useLinkWithSiwe`, then awaits `useUser().refreshUser()` instead of reading
a stale React user value captured before linking. Before allowing funding, it verifies:

* The Privy user ID and original embedded Ethereum wallet address are unchanged.
* The external wallet is linked and the account is no longer a guest.
* The connected embedded wallet matches the current user's wallet metadata.

If the external wallet already belongs to another Privy account, preserve the guest session and
resolve the conflict. Do not log out, delete the guest, or try to merge its funded wallet into
the other account. Privy does not support that guest-account merge. `useLinkWithSiwe` is marked
experimental in this Privy version; verify the exact version used by your application.

## Return after losing a browser session

Sign in with the external wallet linked to the account. Privy should return the same user and
embedded wallet. The recovery path refuses to create a wallet if the existing one is missing.
After authentication, let the SDK read that account's authoritative balance and existing actions.

A successful login is not permission to replay an earlier deposit or payout. A submitted action
must still be reconciled through its existing SDK/backend recovery path. If an unpaid withdrawal
is canceled, its reserved balance becomes available in the same account; a subsequent withdrawal
requires a fresh authorized action. See [original-operation recovery](https://spiceflow-docs.spicenet.io/api-reference/endpoint/actions-get.md#recovering-the-original-operation).

If a guest's credentials are already lost and no recoverable login or other authorized recovery
method was established beforehand, this reference cannot restore that anonymous account.
Creating a new guest does not regain access to the old wallet. Privy documents a 30-day guest
session limit; normal short-lived token refresh is a separate mechanism.

## Verify the integration before accepting funds

Test the actual app origin and exact installed Privy package:

1. Link an accessible guest and confirm that its user ID and embedded wallet remain unchanged.
2. Close the browser context, then sign in from a clean context with the linked wallet.
3. Confirm the same embedded wallet can sign a harmless test message and the SDK reads its balance.
4. Reject an unrecognized recovery login, a rejected signature and a conflicting linked credential
   without creating another account or discarding the original guest.

The reference's offline authentication checks run with Node.js 22:

```bash theme={null}
node --experimental-strip-types --test examples/recoverable-wallet/sequence.test.mjs
```

Those checks do not establish the live app's authentication or financial acceptance. Also test
your complete funding, destination delivery and application finalization through the SDK.

## Reference files

Copy `sequence.ts` and `useRecoverableWallet.ts` into the same directory in your application.
The third tab contains the offline authentication tests.

```typescript sequence.ts theme={null}
export type SessionUser = {
  id: string;
  isGuest?: boolean;
  linkedAccounts: ReadonlyArray<{
    type: string;
    address?: string;
    chainType?: string;
    walletClientType?: string;
    connectorType?: string;
  }>;
};

export type ExternalWallet = {
  address: string;
  chainId: number;
  getAddress: () => Promise<string>;
  signMessage: (message: string) => Promise<string>;
};

export type AuthOperations = {
  refreshUser: () => Promise<SessionUser>;
  generateLinkMessage: (input: { address: string; chainId: string }) => Promise<string>;
  linkWithSiwe: (input: { message: string; signature: string; chainId: string }) => Promise<void>;
  generateLoginMessage: (input: { address: string; chainId: `eip155:${number}` }) => Promise<string>;
  loginWithSiwe: (input: { message: string; signature: string; disableSignup: boolean }) => Promise<SessionUser>;
  createWallet: () => Promise<{ address: string }>;
};

export type RecoverableWallet = {
  userId: string;
  embeddedAddress: string;
  externalAddress: string;
};

const sameAddress = (a: string | undefined, b: string | undefined) =>
  !!a && !!b && a.toLowerCase() === b.toLowerCase();

export function embeddedAddresses(user: SessionUser): string[] {
  return user.linkedAccounts
    .filter((account) => account.type === "wallet" && account.chainType === "ethereum" &&
      account.walletClientType === "privy" && account.connectorType === "embedded")
    .map((account) => account.address!)
    .filter(Boolean);
}

export function hasExternalWallet(user: SessionUser, address: string): boolean {
  return user.linkedAccounts.some((account) => account.type === "wallet" &&
    account.chainType === "ethereum" && account.connectorType !== "embedded" &&
    account.walletClientType !== "privy" && sameAddress(account.address, address));
}

/** Revalidate live server-account metadata as well as the connected wallet. */
export function isRecoverableWalletReady(input: {
  user: SessionUser | null;
  result: RecoverableWallet | null;
  externalAddress?: string;
  connectedEmbeddedAddress?: string;
}): boolean {
  const { user, result, externalAddress, connectedEmbeddedAddress } = input;
  if (!user || !result || user.id !== result.userId || user.isGuest !== false ||
    !sameAddress(externalAddress, result.externalAddress) ||
    !hasExternalWallet(user, result.externalAddress)) return false;
  const addresses = embeddedAddresses(user);
  return addresses.length === 1 && sameAddress(addresses[0], result.embeddedAddress) &&
    sameAddress(connectedEmbeddedAddress, result.embeddedAddress);
}

/** Auth only. Funding, quotes, transactions and pending-action recovery remain in Spice Flow. */
export async function prepareRecoverableWallet(input: {
  user: SessionUser | null;
  external: ExternalWallet;
  mode: "new" | "recover";
  operations: AuthOperations;
}): Promise<RecoverableWallet> {
  const { external, operations, mode } = input;
  const address = external.address;
  if (!/^0x[0-9a-fA-F]{40}$/.test(address) ||
    !Number.isSafeInteger(external.chainId) || external.chainId <= 0)
    throw new Error("Connect an Ethereum wallet before continuing.");

  const checkExternal = async () => {
    if (!sameAddress(await external.getAddress(), address))
      throw new Error("The connected wallet changed. Review the login again.");
  };
  await checkExternal();
  let user = input.user ? await operations.refreshUser() : null;
  if (input.user && user?.id !== input.user.id)
    throw new Error("The Privy account changed. Keep the existing session and try again.");

  if (user?.isGuest) {
    const originalId = user.id;
    const originalWallets = embeddedAddresses(user);
    if (originalWallets.length !== 1)
      throw new Error("Wait for the existing guest wallet before linking a login.");
    const originalWallet = originalWallets[0];
    const chainId = `eip155:${external.chainId}`;
    const message = await operations.generateLinkMessage({ address, chainId });
    await checkExternal();
    const signature = await external.signMessage(message);
    await checkExternal();
    const current = await operations.refreshUser();
    if (!current || current.id !== originalId || embeddedAddresses(current).length !== 1 ||
      !sameAddress(embeddedAddresses(current)[0], originalWallet))
      throw new Error("The guest account changed. Keep the existing session and try again.");

    // Link the authenticated guest. A fresh login could select a different account.
    await operations.linkWithSiwe({ message, signature, chainId });
    user = await operations.refreshUser();
    if (!user || user.id !== originalId || embeddedAddresses(user).length !== 1 ||
      !sameAddress(embeddedAddresses(user)[0], originalWallet))
      throw new Error("The original guest wallet was not preserved. Do not fund this session.");
  } else if (!user) {
    const message = await operations.generateLoginMessage({
      address,
      chainId: `eip155:${external.chainId}`,
    });
    await checkExternal();
    const signature = await external.signMessage(message);
    await checkExternal();
    user = await operations.loginWithSiwe({ message, signature, disableSignup: mode === "recover" });
  }

  if (!user || user.isGuest !== false || !hasExternalWallet(user, address))
    throw new Error("A verified wallet login is required before funding.");

  let addresses = embeddedAddresses(user);
  if (addresses.length === 0 && mode === "new") {
    // SIWE already linked an external wallet, so users-without-wallets does not create one.
    const current = await operations.refreshUser();
    if (!current || current.id !== user.id || current.isGuest !== false || !hasExternalWallet(current, address))
      throw new Error("The Privy account changed. Review the login again.");
    addresses = embeddedAddresses(current);
    if (addresses.length === 0) {
      await checkExternal();
      const created = await operations.createWallet();
      const refreshed = await operations.refreshUser();
      const refreshedAddresses = refreshed ? embeddedAddresses(refreshed) : [];
      if (!refreshed || refreshed.id !== user.id || refreshedAddresses.length !== 1 ||
        !sameAddress(refreshedAddresses[0], created.address))
        throw new Error("The created wallet could not be confirmed. Do not fund this session.");
      user = refreshed;
      addresses = refreshedAddresses;
    } else {
      user = current;
    }
  }
  if (addresses.length !== 1)
    throw new Error("The existing embedded wallet could not be recovered. Do not create a replacement.");
  if (user.isGuest !== false || !hasExternalWallet(user, address))
    throw new Error("A verified wallet login is required before funding.");
  await checkExternal();
  return { userId: user.id, embeddedAddress: addresses[0], externalAddress: address };
}
```

```typescript useRecoverableWallet.ts theme={null}
import { useCallback, useRef, useState } from "react";
import {
  useCreateWallet, useLinkWithSiwe, useLoginWithSiwe, usePrivy, useUser, useWallets,
} from "@privy-io/react-auth";
import {
  isRecoverableWalletReady, prepareRecoverableWallet,
  type ExternalWallet, type RecoverableWallet,
} from "./sequence";

/** The external address comes from the host's connected wallet, never wallets[0]. */
export function useRecoverableWallet(external: ExternalWallet | null) {
  const { ready, authenticated, user } = usePrivy();
  const { refreshUser } = useUser();
  const { wallets, ready: walletsReady } = useWallets();
  const link = useLinkWithSiwe();
  const login = useLoginWithSiwe();
  const { createWallet } = useCreateWallet();
  const inFlight = useRef(false);
  const session = useRef({ ready, authenticated, user });
  session.current = { ready, authenticated, user };
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<unknown>(null);
  const [result, setResult] = useState<RecoverableWallet | null>(null);

  const prepare = useCallback(async (mode: "new" | "recover") => {
    const current = session.current;
    if (!current.ready || !external || inFlight.current ||
      current.authenticated !== !!current.user)
      throw new Error("Wait for the current wallet session before continuing.");
    inFlight.current = true;
    setBusy(true);
    setError(null);
    setResult(null);
    try {
      const next = await prepareRecoverableWallet({
        user: current.user,
        external,
        mode,
        operations: {
          refreshUser,
          generateLinkMessage: link.generateSiweMessage,
          linkWithSiwe: link.linkWithSiwe,
          generateLoginMessage: login.generateSiweMessage,
          loginWithSiwe: login.loginWithSiwe,
          createWallet,
        },
      });
      setResult(next);
      return next;
    } catch (cause) {
      setError(cause);
      throw cause;
    } finally {
      inFlight.current = false;
      setBusy(false);
    }
  }, [external, refreshUser, link.generateSiweMessage, link.linkWithSiwe,
    login.generateSiweMessage, login.loginWithSiwe, createWallet]);

  const embeddedWallet = result && walletsReady
    ? wallets.find((wallet) => wallet.walletClientType === "privy" &&
      wallet.address.toLowerCase() === result.embeddedAddress.toLowerCase())
    : undefined;
  const canFund = ready && authenticated && walletsReady && !busy && !error &&
    isRecoverableWalletReady({
      user,
      result,
      externalAddress: external?.address,
      connectedEmbeddedAddress: embeddedWallet?.address,
    });

  return { prepare, busy, error, canFund, embeddedWallet };
}
```

```javascript sequence.test.mjs theme={null}
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);
});
```

## Privy references

* [Guest accounts and upgrade limits](https://docs.privy.io/authentication/user-authentication/login-methods/guest)
* [Headless wallet linking](https://docs.privy.io/user-management/users/whitelabel#linking-a-wallet)
* [Headless SIWE login](https://docs.privy.io/authentication/user-authentication/login-methods/wallet)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.