This commit is contained in:
zramsay 2025-01-02 17:15:21 -05:00
parent af601f4bbf
commit 14d278510c
5 changed files with 150 additions and 70 deletions

View File

@ -5,53 +5,33 @@ import WalletHeader from '../components/WalletHeader'
import AIServiceCard from '../components/AIServiceCard'
import { generateChatResponse, ChatGenerationResult, CHAT_MODELS } from '../services/chatService'
import { processMTMPayment } from '../services/paymentService'
interface WalletState {
connected: boolean
publicKey: string | null
}
declare global {
interface Window {
solflare: any;
}
}
import { connectWallet, WalletState } from '../services/walletService'
import { WalletType } from '../services/types'
const Page: React.FC = (): React.ReactElement => {
const [walletState, setWalletState] = useState<WalletState>({
connected: false,
publicKey: null,
type: null
})
const connectWallet = async (): Promise<void> => {
const handleConnect = async (walletType: WalletType): Promise<void> => {
try {
if (typeof window === 'undefined' || !window.solflare) {
throw new Error('Solflare wallet not found! Please install it first.')
}
await window.solflare.connect()
if (!window.solflare.publicKey) {
throw new Error('Failed to connect to wallet')
}
const publicKey: string = window.solflare.publicKey.toString()
setWalletState({
connected: true,
publicKey,
})
const newWalletState = await connectWallet(walletType)
setWalletState(newWalletState)
} catch (error) {
console.error('Wallet connection error:', error)
setWalletState({
connected: false,
publicKey: null,
type: null
})
}
}
const handleChatGeneration = (modelId: string, cost: number) => {
return async (prompt: string): Promise<ChatGenerationResult> => {
if (!walletState.connected || !walletState.publicKey || !window.solflare) {
if (!walletState.connected || !walletState.publicKey) {
return { error: 'Wallet not connected' }
}
@ -59,7 +39,7 @@ const Page: React.FC = (): React.ReactElement => {
const paymentResult = await processMTMPayment(
walletState.publicKey,
cost,
window.solflare
walletState.type
)
if (!paymentResult.success) {
@ -84,10 +64,9 @@ const Page: React.FC = (): React.ReactElement => {
</p>
<WalletHeader
isConnected={walletState.connected}
publicKey={walletState.publicKey}
onConnect={connectWallet}
/>
walletState={walletState}
onConnect={handleConnect}
/>
</div>
{/* Chat Models Grid */}

View File

@ -1,30 +1,36 @@
'use client'
import React from 'react'
import { WalletState, SUPPORTED_WALLETS } from '../services/walletService'
import { WalletType } from '../services/types'
interface WalletHeaderProps {
isConnected: boolean
publicKey: string | null
onConnect: () => Promise<void>
walletState: WalletState
onConnect: (walletType: WalletType) => Promise<void>
}
const WalletHeader: React.FC<WalletHeaderProps> = ({ isConnected, publicKey, onConnect }) => {
const WalletHeader: React.FC<WalletHeaderProps> = ({ walletState, onConnect }) => {
return (
<div className="w-full bg-slate-900/50 backdrop-blur-lg rounded-xl shadow-lg border border-orange-800/50 mb-8 p-4">
{!isConnected ? (
<button
onClick={onConnect}
className="w-full bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600
text-white font-semibold py-3 px-6 rounded-lg transition-all duration-200
shadow-lg hover:shadow-orange-500/25"
>
Connect Solflare Wallet
</button>
{!walletState.connected ? (
<div className="grid grid-cols-2 gap-4">
{SUPPORTED_WALLETS.map((wallet) => (
<button
key={wallet.type}
onClick={() => onConnect(wallet.type)}
className="bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600
text-white font-semibold py-3 px-6 rounded-lg transition-all duration-200
shadow-lg hover:shadow-orange-500/25"
>
Connect {wallet.name}
</button>
))}
</div>
) : (
<div className="flex items-center justify-between">
<span className="text-slate-300">Connected Wallet</span>
<span className="px-3 py-1 bg-amber-500/20 rounded-full text-amber-200 text-sm">
{publicKey?.slice(0, 22)}...
{walletState.publicKey?.slice(0, 22)}...
</span>
</div>
)}

View File

@ -6,22 +6,19 @@ import {
createAssociatedTokenAccountInstruction,
ASSOCIATED_TOKEN_PROGRAM_ID
} from '@solana/spl-token'
import { WalletType } from './types'
// Constants
const MTM_TOKEN_MINT: string = '97RggLo3zV5kFGYW4yoQTxr4Xkz4Vg2WPHzNYXXWpump'
const PAYMENT_RECEIVER_ADDRESS: string = 'FFDx3SdAEeXrp6BTmStB4BDHpctGsaasZq4FFcowRobY'
// RPC Configuration
const SOLANA_RPC_URL: string = 'https://young-radial-orb.solana-mainnet.quiknode.pro/67612b364664616c29514e551bf5de38447ca3d4'
const SOLANA_WEBSOCKET_URL: string = 'wss://young-radial-orb.solana-mainnet.quiknode.pro/67612b364664616c29514e551bf5de38447ca3d4'
// Initialize connection with WebSocket support
const connection = new Connection(
SOLANA_RPC_URL,
{
commitment: 'confirmed',
wsEndpoint: SOLANA_WEBSOCKET_URL,
confirmTransactionInitialTimeout: 60000, // 60 seconds
confirmTransactionInitialTimeout: 60000,
}
)
@ -44,12 +41,28 @@ async function findAssociatedTokenAddress(
)[0]
}
interface WalletAdapter {
signAndSendTransaction(transaction: Transaction): Promise<{ signature: string }>
}
export async function processMTMPayment(
walletPublicKey: string,
tokenAmount: number,
solflareWallet: any
walletType: WalletType
): Promise<PaymentResult> {
try {
let wallet: WalletAdapter | null = null;
if (walletType === 'phantom') {
wallet = window.phantom?.solana || null;
} else if (walletType === 'solflare') {
wallet = window.solflare || null;
}
if (!wallet) {
throw new Error(`${walletType} wallet not found`)
}
const senderPublicKey = new PublicKey(walletPublicKey)
const mintPublicKey = new PublicKey(MTM_TOKEN_MINT)
const receiverPublicKey = new PublicKey(PAYMENT_RECEIVER_ADDRESS)
@ -60,7 +73,6 @@ export async function processMTMPayment(
receiver: receiverPublicKey.toBase58(),
})
// Find ATAs
const senderATA = await findAssociatedTokenAddress(
senderPublicKey,
mintPublicKey
@ -78,21 +90,19 @@ export async function processMTMPayment(
const transaction = new Transaction()
// Check if accounts exist
const [senderATAInfo, receiverATAInfo] = await Promise.all([
connection.getAccountInfo(senderATA),
connection.getAccountInfo(receiverATA),
])
// Create ATAs if they don't exist
if (!receiverATAInfo) {
console.log('Creating receiver token account')
transaction.add(
createAssociatedTokenAccountInstruction(
senderPublicKey, // payer
receiverATA, // ata
receiverPublicKey, // owner
mintPublicKey // mint
senderPublicKey,
receiverATA,
receiverPublicKey,
mintPublicKey
)
)
}
@ -101,21 +111,20 @@ export async function processMTMPayment(
console.log('Creating sender token account')
transaction.add(
createAssociatedTokenAccountInstruction(
senderPublicKey, // payer
senderATA, // ata
senderPublicKey, // owner
mintPublicKey // mint
senderPublicKey,
senderATA,
senderPublicKey,
mintPublicKey
)
)
}
// Add transfer instruction
transaction.add(
createTransferInstruction(
senderATA, // from
receiverATA, // to
senderPublicKey, // owner
BigInt(tokenAmount * (10 ** 6)) // amount
senderATA,
receiverATA,
senderPublicKey,
BigInt(tokenAmount * (10 ** 6))
)
)
@ -124,7 +133,7 @@ export async function processMTMPayment(
transaction.feePayer = senderPublicKey
console.log('Sending transaction...')
const { signature } = await solflareWallet.signAndSendTransaction(transaction)
const { signature } = await wallet.signAndSendTransaction(transaction)
console.log('Transaction sent:', signature)
const confirmation = await connection.confirmTransaction({
@ -147,3 +156,4 @@ export async function processMTMPayment(
}
}
}

20
src/services/types.ts Normal file
View File

@ -0,0 +1,20 @@
export type WalletType = 'solflare' | 'phantom'
declare global {
interface Window {
solflare?: {
connect(): Promise<void>
disconnect(): Promise<void>
publicKey?: { toString(): string }
signAndSendTransaction(transaction: any): Promise<{ signature: string }>
}
phantom?: {
solana?: {
connect(): Promise<{ publicKey: { toString(): string } }>
disconnect(): Promise<void>
signAndSendTransaction(transaction: any): Promise<{ signature: string }>
}
}
}
}

View File

@ -0,0 +1,65 @@
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
}
}
}