65 lines
1.5 KiB
TypeScript
65 lines
1.5 KiB
TypeScript
import { WalletType } from './types'
|
|
|
|
export interface WalletState {
|
|
connected: boolean
|
|
publicKey: string | null
|
|
type: WalletType | null
|
|
}
|
|
|
|
export interface WalletConfig {
|
|
type: WalletType
|
|
name: string
|
|
connect: () => Promise<{ publicKey: string } | null>
|
|
}
|
|
|
|
const connectSolflare = async (): Promise<{ publicKey: string } | null> => {
|
|
if (!window.solflare) return null
|
|
await window.solflare.connect()
|
|
return window.solflare.publicKey ? { publicKey: window.solflare.publicKey.toString() } : null
|
|
}
|
|
|
|
const connectPhantom = async (): Promise<{ publicKey: string } | null> => {
|
|
if (!window.phantom?.solana) return null
|
|
try {
|
|
const response = await window.phantom.solana.connect()
|
|
return response.publicKey ? { publicKey: response.publicKey.toString() } : null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
export const SUPPORTED_WALLETS: WalletConfig[] = [
|
|
{
|
|
type: 'solflare',
|
|
name: 'Solflare',
|
|
connect: connectSolflare
|
|
},
|
|
{
|
|
type: 'phantom',
|
|
name: 'Phantom',
|
|
connect: connectPhantom
|
|
}
|
|
]
|
|
|
|
export async function connectWallet(type: WalletType): Promise<WalletState> {
|
|
const wallet = SUPPORTED_WALLETS.find(w => w.type === type)
|
|
if (!wallet) throw new Error('Unsupported wallet')
|
|
|
|
try {
|
|
const result = await wallet.connect()
|
|
if (!result) throw new Error(`${wallet.name} not found`)
|
|
|
|
return {
|
|
connected: true,
|
|
publicKey: result.publicKey,
|
|
type: wallet.type
|
|
}
|
|
} catch (error) {
|
|
return {
|
|
connected: false,
|
|
publicKey: null,
|
|
type: null
|
|
}
|
|
}
|
|
}
|