Skip to content
Open
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
59 changes: 59 additions & 0 deletions src/hooks/useWallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"use client";

import { useCallback, useEffect, useState } from "react";

export type WalletState = {
address: string | null;
network: string | null;
connecting: boolean;
error: string | null;
};

/** Freighter / browser wallet hook (issue #5). */
export function useWallet() {
const [state, setState] = useState<WalletState>({
address: null,
network: null,
connecting: false,
error: null,
});

const refresh = useCallback(async () => {
try {
const freighter = (window as any)?.freighterApi || (window as any)?.freighter;
if (!freighter) {
setState((s) => ({ ...s, error: "Wallet extension not found" }));
return;
}
const address = await freighter.getPublicKey?.() || await freighter.getAddress?.();
const network = await freighter.getNetwork?.();
setState({
address: address || null,
network: typeof network === "string" ? network : network?.network || null,
connecting: false,
error: null,
});
} catch (e) {
setState((s) => ({
...s,
connecting: false,
error: e instanceof Error ? e.message : String(e),
}));
}
}, []);

const connect = useCallback(async () => {
setState((s) => ({ ...s, connecting: true, error: null }));
await refresh();
}, [refresh]);

const disconnect = useCallback(() => {
setState({ address: null, network: null, connecting: false, error: null });
}, []);

useEffect(() => {
refresh();
}, [refresh]);

return { ...state, connect, disconnect, refresh };
}