From bbddc78c0c4a54698bfdbc86e2fa26400ff04132 Mon Sep 17 00:00:00 2001 From: Satchmo Date: Wed, 25 Nov 2026 18:47:01 +0000 Subject: [PATCH 1/2] Let users choose the wallet's storage provider The built-in wallet's storage provider keeps its data and broadcasts its transactions. Settings now shows it, lets the user move the wallet to another provider, and asks for the provider's address when the wallet was moved on another device, so it follows rather than undoes the move. The choice is kept per chain and identity key in this browser. Switching appears only once @1sat/wallet-browser reports getStorageStatus. --- components/wallet/wallet-settings-form.tsx | 16 +- components/wallet/wallet-storage-row.tsx | 178 +++++++++++++++++++++ lib/wallet/storage-choice.ts | 93 +++++++++++ lib/wallet/storage-endpoint.ts | 39 +++-- providers/wallet-toolbox-provider.tsx | 136 +++++++++++++++- tests/wallet-storage-choice.test.ts | 76 +++++++++ tests/wallet-storage-endpoint.test.ts | 41 ++++- 7 files changed, 547 insertions(+), 32 deletions(-) create mode 100644 components/wallet/wallet-storage-row.tsx create mode 100644 lib/wallet/storage-choice.ts create mode 100644 tests/wallet-storage-choice.test.ts diff --git a/components/wallet/wallet-settings-form.tsx b/components/wallet/wallet-settings-form.tsx index 509e5b3..08b1ce1 100644 --- a/components/wallet/wallet-settings-form.tsx +++ b/components/wallet/wallet-settings-form.tsx @@ -4,7 +4,6 @@ import { Bug, Cable, Coins, - Database, Eye, EyeOff, Globe, @@ -30,10 +29,10 @@ import { import { Switch } from "@/components/ui/switch"; import { MessageboxReceiving } from "@/components/wallet/messagebox-receiving"; import { TestnetBadge } from "@/components/wallet/testnet-badge"; +import { WalletStorageRow } from "@/components/wallet/wallet-storage-row"; import { useSound } from "@/hooks/use-sound"; import { isRouteAvailableOn } from "@/lib/chain-surfaces"; import { CURRENCY_KEY, PRIVACY_MODE_KEY } from "@/lib/constants"; -import { walletStorageHost } from "@/lib/wallet/storage-endpoint"; import { useSettingsStorage } from "@/lib/wallet-storage"; import { useWalletToolbox } from "@/providers/wallet-toolbox-provider"; @@ -48,7 +47,6 @@ export function WalletSettingsForm() { disconnectExternalWallet, chain, } = useWalletToolbox(); - const storageHost = walletStorageHost(chain); const [isPrivacyModeEnabled, setIsPrivacyModeEnabled] = useSettingsStorage(PRIVACY_MODE_KEY, false); const [currency, setCurrency] = useSettingsStorage( @@ -82,17 +80,7 @@ export function WalletSettingsForm() { } /> ) : ( - - Using the wallet built into this browser. Active store:{" "} - {storageHost}. A - copy in this browser is kept in sync as a backup. - - } - /> + )} {connectionMode === "built-in" && ( diff --git a/components/wallet/wallet-storage-row.tsx b/components/wallet/wallet-storage-row.tsx new file mode 100644 index 0000000..e679d05 --- /dev/null +++ b/components/wallet/wallet-storage-row.tsx @@ -0,0 +1,178 @@ +"use client"; + +import { Database, Loader2 } from "lucide-react"; +import { type FormEvent, useState } from "react"; +import { SettingsRow } from "@/components/settings/settings-row"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Notice } from "@/components/ui/notice"; +import { + defaultWalletStorageUrl, + storageHostOf, + walletStorageHost, +} from "@/lib/wallet/storage-endpoint"; +import { useWalletToolbox } from "@/providers/wallet-toolbox-provider"; + +/** + * The built-in wallet's storage provider: the server that keeps its data and + * broadcasts its transactions. Shows the active provider and lets the user + * move the wallet to another one, or follow a move made on another device. + */ +export function WalletStorageRow() { + const { + chain, + identityKey, + storageStatus, + canChangeWalletStorage, + changeWalletStorage, + } = useWalletToolbox(); + const [open, setOpen] = useState(false); + const [address, setAddress] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const defaultUrl = defaultWalletStorageUrl(chain); + const activeUrl = storageStatus ? storageStatus.activeRemoteUrl : undefined; + const host = storageStatus + ? activeUrl + ? storageHostOf(activeUrl) + : "this browser" + : walletStorageHost(chain, identityKey ?? undefined); + const moved = Boolean(storageStatus?.movedTo); + const readOnly = storageStatus ? !storageStatus.writable : false; + + const openDialog = () => { + setAddress(moved ? "" : (activeUrl ?? defaultUrl)); + setError(null); + setOpen(true); + }; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + await changeWalletStorage(address); + setOpen(false); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + return ( + <> + + Your wallet's data is kept, and its transactions broadcast, by{" "} + {host}. A copy in this + browser is kept in sync as a backup. + + } + control={ + readOnly ? Read-only : undefined + } + action={ + canChangeWalletStorage ? ( + + ) : undefined + } + /> + {moved && ( +
+ + It now uses a storage provider this browser doesn't know. Until you + add it here, balances may be out of date and sending is off. + +
+ )} + !busy && setOpen(next)}> + +
+ + + {moved ? "Add your wallet's storage" : "Change wallet storage"} + + + {moved + ? "Enter the storage provider address your other device uses." + : "Choose the server that keeps this wallet's data and broadcasts its transactions."} + + +
+ + setAddress(e.target.value)} + disabled={busy} + /> + {!moved && address.trim() !== defaultUrl && ( + + )} +
+ {!moved && ( + + The provider you pick holds your wallet's history and sends your + transactions, so only use one you trust. Your keys stay in this + browser. Your other devices follow the move when they next open. + + )} + {error && {error}} + + + + +
+
+
+ + ); +} diff --git a/lib/wallet/storage-choice.ts b/lib/wallet/storage-choice.ts new file mode 100644 index 0000000..e6e59f6 --- /dev/null +++ b/lib/wallet/storage-choice.ts @@ -0,0 +1,93 @@ +/** + * The storage provider a built-in wallet uses as its active store, as chosen + * on this browser. Kept per chain and identity key, because each account has + * its own store. No entry means the hosted 1Sat storage. + * + * This is only where this browser looks first. The store's own user record + * (`activeStorage`) decides which store the wallet writes to, so a move made + * on another device is followed, never undone. + */ + +export interface StorageChoiceStore { + getItem(key: string): string | null; + setItem(key: string, value: string): void; + removeItem(key: string): void; +} + +function choiceKey(chain: string, identityKey: string): string { + return `1sat.walletStorage.${chain}.${identityKey}`; +} + +function storeOf(store?: StorageChoiceStore): StorageChoiceStore | null { + if (store) return store; + if (typeof window === "undefined") return null; + return window.localStorage; +} + +/** + * Normalizes a storage provider address the user typed. Throws when it is not + * an https URL with a host; an `http://localhost` address is allowed for + * development. + */ +export function normalizeStorageUrl(input: string): string { + const trimmed = input.trim(); + let url: URL; + try { + url = new URL(trimmed); + } catch { + throw new Error( + "Enter the provider's full address, starting with https://", + ); + } + const local = + url.protocol === "http:" && + (url.hostname === "localhost" || url.hostname === "127.0.0.1"); + if (url.protocol !== "https:" && !local) { + throw new Error("The provider's address must start with https://"); + } + if (url.username || url.password || url.search || url.hash) { + throw new Error("Enter the provider's address without a login or query"); + } + return `${url.origin}${url.pathname}`.replace(/\/+$/, ""); +} + +/** The saved provider for this account, or null for the hosted default. */ +export function loadStorageChoice( + chain: string, + identityKey: string, + store?: StorageChoiceStore, +): string | null { + const s = storeOf(store); + if (!s) return null; + const saved = s.getItem(choiceKey(chain, identityKey)); + if (!saved) return null; + try { + return normalizeStorageUrl(saved); + } catch { + return null; + } +} + +/** + * Saves the provider for this account. Saving the hosted default, or null, + * removes the entry. + */ +export function saveStorageChoice( + chain: string, + identityKey: string, + url: string | null, + defaultUrl: string, + store?: StorageChoiceStore, +): void { + const s = storeOf(store); + if (!s) return; + const key = choiceKey(chain, identityKey); + if ( + url === null || + normalizeStorageUrl(url) === normalizeStorageUrl(defaultUrl) + ) { + s.removeItem(key); + } else { + s.setItem(key, normalizeStorageUrl(url)); + } +} diff --git a/lib/wallet/storage-endpoint.ts b/lib/wallet/storage-endpoint.ts index a5ecc30..2a6ddf8 100644 --- a/lib/wallet/storage-endpoint.ts +++ b/lib/wallet/storage-endpoint.ts @@ -1,29 +1,42 @@ import { type Chain, endpointsOf } from "@/lib/chain-endpoints"; +import { loadStorageChoice } from "@/lib/wallet/storage-choice"; /** - * The remote storage the built-in wallet uses as its active store. The local - * IndexedDB store is registered beside it as a backup. The chain is the - * account's own, fixed at create or import, so an account has exactly one - * active store. - * - * A wallet has one active storage, and the same keys must never point at two - * storages, or they diverge. So every chain uses its hosted 1Sat storage, the - * same one Yours and the iOS app use. NEXT_PUBLIC_WALLET_STORAGE_URL is a - * mainnet deploy setting and never applies to testnet. + * The hosted 1Sat storage, the same one Yours and the iOS app use by + * default. NEXT_PUBLIC_WALLET_STORAGE_URL is a mainnet deploy setting and + * never applies to testnet. */ -export function walletStorageUrl(chain: Chain): string { +export function defaultWalletStorageUrl(chain: Chain): string { if (chain === "main" && process.env.NEXT_PUBLIC_WALLET_STORAGE_URL) { return process.env.NEXT_PUBLIC_WALLET_STORAGE_URL; } return endpointsOf(chain).storage; } -/** The host to show for the active store. */ -export function walletStorageHost(chain: Chain): string { - const url = walletStorageUrl(chain); +/** + * The remote storage the built-in wallet opens as its active store: the + * provider chosen for this account on this browser, or the hosted default. + * The local IndexedDB store is registered beside it as a backup. + * + * A wallet has one active store at a time. The store's user record names it, + * every other store is a backup synced from it, and a move made on another + * device is followed when the wallet opens (see `getStorageStatus`). + */ +export function walletStorageUrl(chain: Chain, identityKey?: string): string { + const chosen = identityKey ? loadStorageChoice(chain, identityKey) : null; + return chosen ?? defaultWalletStorageUrl(chain); +} + +/** The host of a storage address, for display. */ +export function storageHostOf(url: string): string { try { return new URL(url).host; } catch { return url; } } + +/** The host to show for the active store. */ +export function walletStorageHost(chain: Chain, identityKey?: string): string { + return storageHostOf(walletStorageUrl(chain, identityKey)); +} diff --git a/providers/wallet-toolbox-provider.tsx b/providers/wallet-toolbox-provider.tsx index 828d6bf..9a9c935 100644 --- a/providers/wallet-toolbox-provider.tsx +++ b/providers/wallet-toolbox-provider.tsx @@ -97,7 +97,15 @@ import { surfaceForConnection, } from "@/lib/wallet/provider-capabilities"; import { isRateLimited, withRateLimitRetry } from "@/lib/wallet/rate-limit"; -import { walletStorageUrl } from "@/lib/wallet/storage-endpoint"; +import { + normalizeStorageUrl, + saveStorageChoice, +} from "@/lib/wallet/storage-choice"; +import { + defaultWalletStorageUrl, + storageHostOf, + walletStorageUrl, +} from "@/lib/wallet/storage-endpoint"; import { hasStoredWallet, readWalletChain, @@ -255,6 +263,32 @@ export type WalletEvent = message: string; }; +/** + * The built-in wallet's storage, as `@1sat/wallet` reports it: which store is + * active, whether it takes writes, and the key of a store the wallet moved to + * on another device that this browser has no address for. + */ +export interface WalletStorageState { + activeRemoteUrl: string | undefined; + activeStorageKey: string | undefined; + writable: boolean; + movedTo: string | undefined; +} + +/** + * `getStorageStatus` arrived after @1sat/wallet-browser 0.1.2, which also + * reclaims the active store on every open. Switching stays hidden until the + * installed wallet reports its status, so an older wallet never switches. + */ +function storageStatusOf( + result: WebWalletResult | null, +): WalletStorageState | null { + const read = ( + result as { getStorageStatus?: () => WalletStorageState } | null + )?.getStorageStatus; + return typeof read === "function" ? read() : null; +} + interface WalletToolboxContextValue { wallet: WalletInterface | null; permissionsManager: WalletPermissionsManager | null; @@ -318,6 +352,18 @@ interface WalletToolboxContextValue { disconnectExternalWallet: () => Promise; destroyWallet: () => Promise; refreshBalance: () => void; + + /** The built-in wallet's storage; null for an external wallet or an older SDK. */ + storageStatus: WalletStorageState | null; + /** True when the built-in wallet can move to another storage provider. */ + canChangeWalletStorage: boolean; + /** + * Makes `url` the built-in wallet's active storage provider, the one that + * keeps its data and broadcasts its transactions. When the wallet was moved + * on another device, `url` must be that store. Throws when the provider + * can't be reached or doesn't end up as the writable active store. + */ + changeWalletStorage: (url: string) => Promise; } const WalletToolboxContext = createContext< @@ -365,6 +411,9 @@ export function WalletToolboxProvider({ useState("no-wallet"); const [providerType, setProviderType] = useState(null); const walletResultRef = useRef(null); + const [storageStatus, setStorageStatus] = useState( + null, + ); // The built-in wallet's manager and overlay, kept beside walletResultRef so // switching back from an external wallet restores them. const localPermissionsRef = useRef<{ @@ -666,6 +715,7 @@ export function WalletToolboxProvider({ setColorOverlay(null); setServices(null); setIdentityKey(null); + setStorageStatus(null); setConnectionMode("none"); setConnectionStatus(status); setProviderType(null); @@ -859,6 +909,7 @@ export function WalletToolboxProvider({ setServices(externalServices); setPermissionsManager(null); setIdentityKey(result.identityKey); + setStorageStatus(null); setDepositAddress(addresses[0] ?? null); setReceiveAddresses(addresses); setTrackedAddresses(addresses); @@ -1065,7 +1116,7 @@ export function WalletToolboxProvider({ const storageIdentityKey = await loadOrCreateWalletStorageIdentity(chain); - const activeRemote = walletStorageUrl(chain); + const activeRemote = walletStorageUrl(chain, newIdentityKey); // The wallet server rate-limits; a busy moment shouldn't fail the open. // Stops once the wallet is locked or reopened meanwhile. const result = await withRateLimitRetry( @@ -1163,6 +1214,7 @@ export function WalletToolboxProvider({ setPermissionsManager(wpm); setColorOverlay(color?.overlay ?? null); setIdentityKey(newIdentityKey); + setStorageStatus(storageStatusOf(result)); setConnectionMode("built-in"); setConnectionStatus("ready"); setProviderType("1sat-web"); @@ -1284,6 +1336,7 @@ export function WalletToolboxProvider({ addressManagerRef.current = addressManager; receiveStateRef.current = state; setIdentityKey(localReceive.identityKey); + setStorageStatus(storageStatusOf(local)); setReceiveAddressIndex(state.currentIndex); setDepositAddress(getDepositAddress(addressManager, state) || null); setReceiveAddresses(getActiveReceiveAddresses(addressManager, state)); @@ -1343,6 +1396,7 @@ export function WalletToolboxProvider({ setServices(externalServices); setPermissionsManager(null); setIdentityKey(result.identityKey); + setStorageStatus(null); setDepositAddress(addresses[0] ?? null); setReceiveAddresses(addresses); setTrackedAddresses(addresses); @@ -1435,6 +1489,78 @@ export function WalletToolboxProvider({ isInitializing || balanceSyncStatus.isSyncing || syncEngineActive; // -- Context value -- + const changeWalletStorage = useCallback( + async (input: string) => { + const result = walletResultRef.current; + const before = storageStatusOf(result); + if (!result || !before || connectionMode !== "built-in" || !identityKey) { + throw new Error("Open your built-in wallet to change its storage."); + } + const url = normalizeStorageUrl(input); + const provider = storageHostOf(url); + const mode = before.movedTo ? "follow" : "switch"; + reportDiagnostic({ + category: "provider", + code: "provider.state", + operation: "wallet.storage.change", + recoverable: true, + context: { status: "requested", mode, provider }, + }); + try { + // After a move made on another device, add the store the wallet + // moved to and follow it; switching here would undo that move. + if (before.movedTo) await result.addRemote(url); + else await result.setActiveStorage(url); + } catch (error) { + setStorageStatus(storageStatusOf(result)); + reportFailure( + { + category: "provider", + code: "provider.failed", + operation: "wallet.storage.change", + recoverable: true, + context: { mode, provider }, + }, + error, + ); + throw new Error( + `Couldn't switch to ${provider}. Check the address and try again.`, + ); + } + const after = storageStatusOf(result); + setStorageStatus(after); + if (!after?.writable || after.activeRemoteUrl !== url) { + reportDiagnostic({ + category: "provider", + code: "provider.failed", + operation: "wallet.storage.change", + recoverable: true, + context: { status: "not-active", mode, provider }, + }); + throw new Error( + before.movedTo + ? "That isn't the storage your wallet moved to. Check the address used on your other device." + : "The new storage provider didn't take over the wallet. Check the address and try again.", + ); + } + saveStorageChoice( + chain, + identityKey, + url, + defaultWalletStorageUrl(chain), + ); + reportDiagnostic({ + category: "provider", + code: "provider.state", + operation: "wallet.storage.change", + recoverable: true, + context: { status: "active", mode, provider }, + }); + refreshBalance(); + }, + [chain, connectionMode, identityKey, refreshBalance], + ); + const value = useMemo( () => ({ wallet, @@ -1482,6 +1608,10 @@ export function WalletToolboxProvider({ disconnectExternalWallet, destroyWallet, refreshBalance: refreshBalance, + storageStatus, + canChangeWalletStorage: + connectionMode === "built-in" && storageStatus !== null, + changeWalletStorage, }), [ wallet, @@ -1528,6 +1658,8 @@ export function WalletToolboxProvider({ disconnectExternalWallet, destroyWallet, refreshBalance, + storageStatus, + changeWalletStorage, ], ); diff --git a/tests/wallet-storage-choice.test.ts b/tests/wallet-storage-choice.test.ts new file mode 100644 index 0000000..08c26eb --- /dev/null +++ b/tests/wallet-storage-choice.test.ts @@ -0,0 +1,76 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + loadStorageChoice, + normalizeStorageUrl, + type StorageChoiceStore, + saveStorageChoice, +} from "@/lib/wallet/storage-choice"; + +function memoryStore(): StorageChoiceStore & { data: Map } { + const data = new Map(); + return { + data, + getItem: (k) => data.get(k) ?? null, + setItem: (k, v) => void data.set(k, v), + removeItem: (k) => void data.delete(k), + }; +} + +const DEFAULT = "https://wallet.1sat.app"; + +describe("normalizeStorageUrl", () => { + it("keeps https addresses and drops a trailing slash", () => { + assert.equal( + normalizeStorageUrl(" https://store.example/ "), + "https://store.example", + ); + assert.equal( + normalizeStorageUrl("https://store.example/v1/"), + "https://store.example/v1", + ); + }); + + it("allows http only for localhost", () => { + assert.equal( + normalizeStorageUrl("http://localhost:8110"), + "http://localhost:8110", + ); + assert.throws(() => normalizeStorageUrl("http://store.example")); + }); + + it("refuses non-URLs, logins and queries", () => { + assert.throws(() => normalizeStorageUrl("store.example")); + assert.throws(() => normalizeStorageUrl("https://u:p@store.example")); + assert.throws(() => normalizeStorageUrl("https://store.example/?token=1")); + }); +}); + +describe("storage choice", () => { + it("is saved per chain and identity key", () => { + const store = memoryStore(); + saveStorageChoice("main", "02aa", "https://store.example/", DEFAULT, store); + assert.equal( + loadStorageChoice("main", "02aa", store), + "https://store.example", + ); + assert.equal(loadStorageChoice("test", "02aa", store), null); + assert.equal(loadStorageChoice("main", "02bb", store), null); + }); + + it("saving the hosted default clears the entry", () => { + const store = memoryStore(); + saveStorageChoice("main", "02aa", "https://store.example", DEFAULT, store); + saveStorageChoice("main", "02aa", `${DEFAULT}/`, DEFAULT, store); + assert.equal(store.data.size, 0); + saveStorageChoice("main", "02aa", "https://store.example", DEFAULT, store); + saveStorageChoice("main", "02aa", null, DEFAULT, store); + assert.equal(store.data.size, 0); + }); + + it("ignores a saved value that is no longer a valid address", () => { + const store = memoryStore(); + store.setItem("1sat.walletStorage.main.02aa", "http://store.example"); + assert.equal(loadStorageChoice("main", "02aa", store), null); + }); +}); diff --git a/tests/wallet-storage-endpoint.test.ts b/tests/wallet-storage-endpoint.test.ts index 75c7c1f..1b95216 100644 --- a/tests/wallet-storage-endpoint.test.ts +++ b/tests/wallet-storage-endpoint.test.ts @@ -43,10 +43,45 @@ describe("wallet storage endpoint", () => { it("is the one config the wallet and Settings both read", () => { const provider = read("providers/wallet-toolbox-provider.tsx"); - assert.match(provider, /const activeRemote = walletStorageUrl\(chain\);/); + assert.match( + provider, + /const activeRemote = walletStorageUrl\(chain, newIdentityKey\);/, + ); assert.doesNotMatch(provider, /https:\/\/wallet\.1sat\.app/); const settings = read("components/wallet/wallet-settings-form.tsx"); - assert.match(settings, /walletStorageHost\(chain\)/); - assert.match(settings, /Wallet storage/); + assert.match(settings, //); + const row = read("components/wallet/wallet-storage-row.tsx"); + assert.match(row, /walletStorageHost\(chain, identityKey/); + assert.match(row, /Wallet storage/); + }); + + it("uses the provider chosen for an account, and only that account", () => { + const saved = process.env.NEXT_PUBLIC_WALLET_STORAGE_URL; + const realWindow = (globalThis as { window?: unknown }).window; + const items = new Map(); + (globalThis as { window?: unknown }).window = { + localStorage: { + getItem: (k: string) => items.get(k) ?? null, + setItem: (k: string, v: string) => items.set(k, v), + removeItem: (k: string) => items.delete(k), + }, + }; + try { + delete process.env.NEXT_PUBLIC_WALLET_STORAGE_URL; + items.set("1sat.walletStorage.main.02aa", "https://store.example"); + assert.equal(walletStorageUrl("main", "02aa"), "https://store.example"); + assert.equal(walletStorageHost("main", "02aa"), "store.example"); + assert.equal(walletStorageUrl("main", "02bb"), "https://wallet.1sat.app"); + assert.equal( + walletStorageUrl("test", "02aa"), + "https://testnet.wallet.1sat.app", + ); + assert.equal(walletStorageUrl("main"), "https://wallet.1sat.app"); + } finally { + (globalThis as { window?: unknown }).window = realWindow; + if (saved === undefined) + delete process.env.NEXT_PUBLIC_WALLET_STORAGE_URL; + else process.env.NEXT_PUBLIC_WALLET_STORAGE_URL = saved; + } }); }); From e47e1c293c4ef3289a747571a9325447f266e02f Mon Sep 17 00:00:00 2001 From: Satchmo Date: Wed, 25 Nov 2026 18:58:48 +0000 Subject: [PATCH 2/2] Open read-only when the chosen storage is down, and guard a switch When the provider chosen for a wallet can't be reached at open, the wallet opens on the 1Sat storage read-only instead of failing, and Settings names the provider and offers to try again. A switch that finishes after the wallet was locked no longer writes its state, a read-only wallet can pick its current provider again, and the default address is normalized so switching back matches its store. --- components/wallet/wallet-storage-row.tsx | 44 ++++++++- lib/wallet/storage-choice.ts | 14 +-- lib/wallet/storage-endpoint.ts | 16 +++- providers/wallet-toolbox-provider.tsx | 108 +++++++++++++++++++---- tests/wallet-storage-choice.test.ts | 16 ++++ tests/wallet-storage-endpoint.test.ts | 5 +- 6 files changed, 175 insertions(+), 28 deletions(-) diff --git a/components/wallet/wallet-storage-row.tsx b/components/wallet/wallet-storage-row.tsx index e679d05..b48b6ff 100644 --- a/components/wallet/wallet-storage-row.tsx +++ b/components/wallet/wallet-storage-row.tsx @@ -33,6 +33,7 @@ export function WalletStorageRow() { chain, identityKey, storageStatus, + storageUnreachable, canChangeWalletStorage, changeWalletStorage, } = useWalletToolbox(); @@ -40,6 +41,8 @@ export function WalletStorageRow() { const [address, setAddress] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); + const [retrying, setRetrying] = useState(false); + const [retryError, setRetryError] = useState(null); const defaultUrl = defaultWalletStorageUrl(chain); const activeUrl = storageStatus ? storageStatus.activeRemoteUrl : undefined; @@ -57,6 +60,19 @@ export function WalletStorageRow() { setOpen(true); }; + const retry = async () => { + if (!storageUnreachable) return; + setRetrying(true); + setRetryError(null); + try { + await changeWalletStorage(storageUnreachable); + } catch (e) { + setRetryError(e instanceof Error ? e.message : String(e)); + } finally { + setRetrying(false); + } + }; + const submit = async (event: FormEvent) => { event.preventDefault(); setBusy(true); @@ -94,7 +110,31 @@ export function WalletStorageRow() { ) : undefined } /> - {moved && ( + {storageUnreachable && canChangeWalletStorage && ( +
+ + That's the storage provider this wallet uses. It opened from the + 1Sat storage instead, read-only, so balances may be out of date and + sending is off until the provider is back. + + {retryError && {retryError}} + +
+ )} + {moved && !storageUnreachable && (
It now uses a storage provider this browser doesn't know. Until you @@ -161,7 +201,7 @@ export function WalletStorageRow() { disabled={ busy || !address.trim() || - (!moved && address.trim() === activeUrl) + (!moved && !readOnly && address.trim() === activeUrl) } > {busy && ( diff --git a/lib/wallet/storage-choice.ts b/lib/wallet/storage-choice.ts index e6e59f6..0bc2782 100644 --- a/lib/wallet/storage-choice.ts +++ b/lib/wallet/storage-choice.ts @@ -82,12 +82,16 @@ export function saveStorageChoice( const s = storeOf(store); if (!s) return; const key = choiceKey(chain, identityKey); - if ( - url === null || - normalizeStorageUrl(url) === normalizeStorageUrl(defaultUrl) - ) { + const normalized = url === null ? null : normalizeStorageUrl(url); + let defaultNormalized = defaultUrl; + try { + defaultNormalized = normalizeStorageUrl(defaultUrl); + } catch { + // A development default (plain http) still compares as written. + } + if (normalized === null || normalized === defaultNormalized) { s.removeItem(key); } else { - s.setItem(key, normalizeStorageUrl(url)); + s.setItem(key, normalized); } } diff --git a/lib/wallet/storage-endpoint.ts b/lib/wallet/storage-endpoint.ts index 2a6ddf8..8b434f1 100644 --- a/lib/wallet/storage-endpoint.ts +++ b/lib/wallet/storage-endpoint.ts @@ -1,5 +1,8 @@ import { type Chain, endpointsOf } from "@/lib/chain-endpoints"; -import { loadStorageChoice } from "@/lib/wallet/storage-choice"; +import { + loadStorageChoice, + normalizeStorageUrl, +} from "@/lib/wallet/storage-choice"; /** * The hosted 1Sat storage, the same one Yours and the iOS app use by @@ -7,8 +10,15 @@ import { loadStorageChoice } from "@/lib/wallet/storage-choice"; * never applies to testnet. */ export function defaultWalletStorageUrl(chain: Chain): string { - if (chain === "main" && process.env.NEXT_PUBLIC_WALLET_STORAGE_URL) { - return process.env.NEXT_PUBLIC_WALLET_STORAGE_URL; + const override = process.env.NEXT_PUBLIC_WALLET_STORAGE_URL; + if (chain === "main" && override) { + // Normalized like a chosen address, so the two compare equal (a + // trailing slash would otherwise read as a different store). + try { + return normalizeStorageUrl(override); + } catch { + return override; + } } return endpointsOf(chain).storage; } diff --git a/providers/wallet-toolbox-provider.tsx b/providers/wallet-toolbox-provider.tsx index 9a9c935..e3ba3b9 100644 --- a/providers/wallet-toolbox-provider.tsx +++ b/providers/wallet-toolbox-provider.tsx @@ -355,6 +355,11 @@ interface WalletToolboxContextValue { /** The built-in wallet's storage; null for an external wallet or an older SDK. */ storageStatus: WalletStorageState | null; + /** + * The provider chosen for this wallet that could not be reached when it + * opened. The wallet then opened read-only on the 1Sat storage. + */ + storageUnreachable: string | null; /** True when the built-in wallet can move to another storage provider. */ canChangeWalletStorage: boolean; /** @@ -414,6 +419,11 @@ export function WalletToolboxProvider({ const [storageStatus, setStorageStatus] = useState( null, ); + // The saved provider that could not be reached at open, when the wallet + // opened on the 1Sat storage instead. + const [storageUnreachable, setStorageUnreachable] = useState( + null, + ); // The built-in wallet's manager and overlay, kept beside walletResultRef so // switching back from an external wallet restores them. const localPermissionsRef = useRef<{ @@ -716,6 +726,7 @@ export function WalletToolboxProvider({ setServices(null); setIdentityKey(null); setStorageStatus(null); + setStorageUnreachable(null); setConnectionMode("none"); setConnectionStatus(status); setProviderType(null); @@ -1116,23 +1127,58 @@ export function WalletToolboxProvider({ const storageIdentityKey = await loadOrCreateWalletStorageIdentity(chain); - const activeRemote = walletStorageUrl(chain, newIdentityKey); + const chosenRemote = walletStorageUrl(chain, newIdentityKey); + const defaultRemote = defaultWalletStorageUrl(chain); // The wallet server rate-limits; a busy moment shouldn't fail the open. // Stops once the wallet is locked or reopened meanwhile. - const result = await withRateLimitRetry( - "wallet.initialize", - () => - createWebWallet({ - privateKey: rootKey, - chain, - activeRemote, - storageIdentityKey, - }), - { - shouldContinue: () => - generation === connectionGenerationRef.current, - }, - ); + const open = (activeRemote: string) => + withRateLimitRetry( + "wallet.initialize", + () => + createWebWallet({ + privateKey: rootKey, + chain, + activeRemote, + storageIdentityKey, + }), + { + shouldContinue: () => + generation === connectionGenerationRef.current, + }, + ); + let unreachable: string | null = null; + let result: WebWalletResult; + try { + result = await open(chosenRemote); + } catch (error) { + // A provider the user chose is down: open on the 1Sat storage + // instead of locking them out. Its row names the chosen store, + // so the wallet comes up read-only (the move is followed, not + // undone) and Settings offers to reconnect. Only a saved choice + // falls back; the default failing is still an open failure. + if ( + chosenRemote === defaultRemote || + isRateLimited(error) || + generation !== connectionGenerationRef.current + ) { + throw error; + } + reportFailure( + { + category: "provider", + code: "provider.failed", + operation: "wallet.initialize.storage", + recoverable: true, + context: { + mode: "built-in", + provider: storageHostOf(chosenRemote), + }, + }, + error, + ); + unreachable = chosenRemote; + result = await open(defaultRemote); + } pendingResult = result; if (generation !== connectionGenerationRef.current) { await result.destroy(); @@ -1215,6 +1261,7 @@ export function WalletToolboxProvider({ setColorOverlay(color?.overlay ?? null); setIdentityKey(newIdentityKey); setStorageStatus(storageStatusOf(result)); + setStorageUnreachable(unreachable); setConnectionMode("built-in"); setConnectionStatus("ready"); setProviderType("1sat-web"); @@ -1506,13 +1553,22 @@ export function WalletToolboxProvider({ recoverable: true, context: { status: "requested", mode, provider }, }); + // A lock or another account opening meanwhile replaces the wallet; + // its state is no longer this one's to set. + const stillOpen = () => walletResultRef.current === result; try { // After a move made on another device, add the store the wallet // moved to and follow it; switching here would undo that move. if (before.movedTo) await result.addRemote(url); else await result.setActiveStorage(url); } catch (error) { - setStorageStatus(storageStatusOf(result)); + if (!stillOpen()) { + throw new Error( + "Your wallet was locked. Open it to check its storage.", + ); + } + const now = storageStatusOf(result); + setStorageStatus(now); reportFailure( { category: "provider", @@ -1523,8 +1579,23 @@ export function WalletToolboxProvider({ }, error, ); + const message = error instanceof Error ? error.message : ""; + if (before.movedTo || /moved to storage/.test(message)) { + throw new Error( + /not the one/.test(message) + ? "That isn't the storage your wallet moved to. Check the address used on your other device." + : now?.movedTo && before.movedTo + ? `Couldn't reach ${provider}. Check the address and try again.` + : "Your wallet was moved on another device. Add the provider it uses there first.", + ); + } + throw new Error( + `Couldn't switch to ${provider}. Your wallet stays where it was.`, + ); + } + if (!stillOpen()) { throw new Error( - `Couldn't switch to ${provider}. Check the address and try again.`, + "Your wallet was locked. Open it to check its storage.", ); } const after = storageStatusOf(result); @@ -1549,6 +1620,7 @@ export function WalletToolboxProvider({ url, defaultWalletStorageUrl(chain), ); + setStorageUnreachable(null); reportDiagnostic({ category: "provider", code: "provider.state", @@ -1609,6 +1681,7 @@ export function WalletToolboxProvider({ destroyWallet, refreshBalance: refreshBalance, storageStatus, + storageUnreachable, canChangeWalletStorage: connectionMode === "built-in" && storageStatus !== null, changeWalletStorage, @@ -1659,6 +1732,7 @@ export function WalletToolboxProvider({ destroyWallet, refreshBalance, storageStatus, + storageUnreachable, changeWalletStorage, ], ); diff --git a/tests/wallet-storage-choice.test.ts b/tests/wallet-storage-choice.test.ts index 08c26eb..a5f0221 100644 --- a/tests/wallet-storage-choice.test.ts +++ b/tests/wallet-storage-choice.test.ts @@ -73,4 +73,20 @@ describe("storage choice", () => { store.setItem("1sat.walletStorage.main.02aa", "http://store.example"); assert.equal(loadStorageChoice("main", "02aa", store), null); }); + + it("saves a choice even when the default is a development address", () => { + const store = memoryStore(); + const devDefault = "http://wallet.dev.internal"; + saveStorageChoice( + "main", + "02aa", + "https://store.example", + devDefault, + store, + ); + assert.equal( + loadStorageChoice("main", "02aa", store), + "https://store.example", + ); + }); }); diff --git a/tests/wallet-storage-endpoint.test.ts b/tests/wallet-storage-endpoint.test.ts index 1b95216..488787d 100644 --- a/tests/wallet-storage-endpoint.test.ts +++ b/tests/wallet-storage-endpoint.test.ts @@ -25,6 +25,9 @@ describe("wallet storage endpoint", () => { "https://storage.example:8443/wallet", ); assert.equal(walletStorageHost("main"), "storage.example:8443"); + process.env.NEXT_PUBLIC_WALLET_STORAGE_URL = "https://storage.example/"; + // Normalized, so switching back to the default matches its store. + assert.equal(walletStorageUrl("main"), "https://storage.example"); // The override holds a mainnet URL; testnet keys must never use it. assert.equal(walletStorageUrl("test"), "https://testnet.wallet.1sat.app"); assert.equal(walletStorageHost("test"), "testnet.wallet.1sat.app"); @@ -45,7 +48,7 @@ describe("wallet storage endpoint", () => { const provider = read("providers/wallet-toolbox-provider.tsx"); assert.match( provider, - /const activeRemote = walletStorageUrl\(chain, newIdentityKey\);/, + /const chosenRemote = walletStorageUrl\(chain, newIdentityKey\);/, ); assert.doesNotMatch(provider, /https:\/\/wallet\.1sat\.app/); const settings = read("components/wallet/wallet-settings-form.tsx");