Add WalletProvider
This commit is contained in:
44
app/src/state/wallet.tsx
Normal file
44
app/src/state/wallet.tsx
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import type { JSX, PropsWithChildren } from "react";
|
||||||
|
import { createContext, useCallback, useContext, useMemo, useState } from "react";
|
||||||
|
|
||||||
|
export type WalletName = "phantom" | "solflare" | "backpack";
|
||||||
|
|
||||||
|
const WALLET_ADDRESSES: Record<WalletName, string> = {
|
||||||
|
phantom: "Gh9Z…k3mP",
|
||||||
|
solflare: "Bx3K…7pRq",
|
||||||
|
backpack: "Kx7P…2mJc",
|
||||||
|
};
|
||||||
|
|
||||||
|
interface WalletContextValue {
|
||||||
|
connected: boolean;
|
||||||
|
address: string | null;
|
||||||
|
connect: (wallet: WalletName) => void;
|
||||||
|
disconnect: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const WalletContext = createContext<WalletContextValue | null>(null);
|
||||||
|
|
||||||
|
export function WalletProvider({ children }: PropsWithChildren): JSX.Element {
|
||||||
|
const [address, setAddress] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const connect = useCallback((wallet: WalletName) => {
|
||||||
|
setAddress(WALLET_ADDRESSES[wallet]);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const disconnect = useCallback(() => {
|
||||||
|
setAddress(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const value = useMemo<WalletContextValue>(
|
||||||
|
() => ({ connected: address !== null, address, connect, disconnect }),
|
||||||
|
[address, connect, disconnect],
|
||||||
|
);
|
||||||
|
|
||||||
|
return <WalletContext.Provider value={value}>{children}</WalletContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useWallet(): WalletContextValue {
|
||||||
|
const ctx = useContext(WalletContext);
|
||||||
|
if (!ctx) throw new Error("useWallet must be used within a WalletProvider");
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user