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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 2 additions & 14 deletions components/wallet/wallet-settings-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
Bug,
Cable,
Coins,
Database,
Eye,
EyeOff,
Globe,
Expand All @@ -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";

Expand All @@ -48,7 +47,6 @@ export function WalletSettingsForm() {
disconnectExternalWallet,
chain,
} = useWalletToolbox();
const storageHost = walletStorageHost(chain);
const [isPrivacyModeEnabled, setIsPrivacyModeEnabled] =
useSettingsStorage<boolean>(PRIVACY_MODE_KEY, false);
const [currency, setCurrency] = useSettingsStorage<string>(
Expand Down Expand Up @@ -82,17 +80,7 @@ export function WalletSettingsForm() {
}
/>
) : (
<SettingsRow
icon={Database}
title="Wallet storage"
description={
<>
Using the wallet built into this browser. Active store:{" "}
<code className="break-all font-mono">{storageHost}</code>. A
copy in this browser is kept in sync as a backup.
</>
}
/>
<WalletStorageRow />
)}
{connectionMode === "built-in" && (
<SettingsRow icon={Inbox}>
Expand Down
218 changes: 218 additions & 0 deletions components/wallet/wallet-storage-row.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
"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,
storageUnreachable,
canChangeWalletStorage,
changeWalletStorage,
} = useWalletToolbox();
const [open, setOpen] = useState(false);
const [address, setAddress] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [retrying, setRetrying] = useState(false);
const [retryError, setRetryError] = useState<string | null>(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 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);
setError(null);
try {
await changeWalletStorage(address);
setOpen(false);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
};

return (
<>
<SettingsRow
icon={Database}
title="Wallet storage"
description={
<>
Your wallet's data is kept, and its transactions broadcast, by{" "}
<code className="break-all font-mono">{host}</code>. A copy in this
browser is kept in sync as a backup.
</>
}
control={
readOnly ? <Badge variant="outline">Read-only</Badge> : undefined
}
action={
canChangeWalletStorage ? (
<Button onClick={openDialog} variant="outline">
{moved ? "Add provider" : "Change"}
</Button>
) : undefined
}
/>
{storageUnreachable && canChangeWalletStorage && (
<div className="flex flex-col gap-3 py-3">
<Notice
tone="danger"
title={`Couldn't reach ${storageHostOf(storageUnreachable)}`}
>
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.
</Notice>
{retryError && <Notice tone="danger">{retryError}</Notice>}
<Button
className="self-start"
variant="outline"
onClick={() => void retry()}
disabled={retrying}
>
{retrying && (
<Loader2 className="animate-spin" data-icon="inline-start" />
)}
Try again
</Button>
</div>
)}
{moved && !storageUnreachable && (
<div className="py-3">
<Notice tone="warning" title="Your wallet moved on another device">
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.
</Notice>
</div>
)}
<Dialog open={open} onOpenChange={(next) => !busy && setOpen(next)}>
<DialogContent showCloseButton={!busy}>
<form className="flex flex-col gap-4" onSubmit={submit}>
<DialogHeader>
<DialogTitle>
{moved ? "Add your wallet's storage" : "Change wallet storage"}
</DialogTitle>
<DialogDescription>
{moved
? "Enter the storage provider address your other device uses."
: "Choose the server that keeps this wallet's data and broadcasts its transactions."}
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-2">
<Label htmlFor="wallet-storage-url">Provider address</Label>
<Input
id="wallet-storage-url"
inputMode="url"
autoComplete="off"
spellCheck={false}
placeholder="https://"
value={address}
onChange={(e) => setAddress(e.target.value)}
disabled={busy}
/>
{!moved && address.trim() !== defaultUrl && (
<Button
type="button"
variant="link"
className="self-start px-0"
onClick={() => setAddress(defaultUrl)}
disabled={busy}
>
Use the 1Sat default ({storageHostOf(defaultUrl)})
</Button>
)}
</div>
{!moved && (
<Notice tone="warning">
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.
</Notice>
)}
{error && <Notice tone="danger">{error}</Notice>}
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => setOpen(false)}
disabled={busy}
>
Cancel
</Button>
<Button
type="submit"
disabled={
busy ||
!address.trim() ||
(!moved && !readOnly && address.trim() === activeUrl)
}
>
{busy && (
<Loader2 className="animate-spin" data-icon="inline-start" />
)}
{moved ? "Add provider" : "Switch"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</>
);
}
97 changes: 97 additions & 0 deletions lib/wallet/storage-choice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/**
* 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);
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, normalized);
}
}
Loading
Loading