'use client'; import React, { useState } from 'react'; import { ethers } from 'ethers'; import { getContract } from '@/lib/ethers'; declare global { interface Window { ethereum: ethers.providers.ExternalProvider; } } const BuyTicket = () => { const [eventId, setEventId] = useState(null); const [transactionHash, setTransactionHash] = useState(null); const [isWalletConnected, setIsWalletConnected] = useState(false); const [walletAddress, setWalletAddress] = useState(null); // Connect Wallet const handleConnectWallet = async () => { try { if (typeof window.ethereum !== 'undefined' && window.ethereum.request) { const accounts = await window.ethereum.request({ method: 'eth_requestAccounts', }); if (accounts.length > 0) { setIsWalletConnected(true); setWalletAddress(accounts[0]); console.log('Wallet connected:', accounts[0]); } } else { alert('Please install MetaMask or another Ethereum wallet'); } } catch (error) { console.error('Error connecting to wallet:', error); } }; // Handle buying a ticket for the event const handleBuyTicket = async () => { if (!eventId) { alert('Please enter a valid Event ID.'); return; } try { // Get the provider and signer const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner(); const contract = getContract().connect(signer); // Call `getEventPriceFlare` to get the ticket cost in FLR const ticketCost = await contract.getEventPriceFlare(eventId); console.log('Ticket cost in FLR:', ethers.utils.formatEther(ticketCost)); // Check wallet balance const balance = await provider.getBalance(await signer.getAddress()); console.log('Wallet balance in Wei:', balance.toString()); console.log('Wallet balance in FLR:', ethers.utils.formatEther(balance)); // Converts to FLR for readability if (balance.lt(ticketCost)) { alert('Insufficient balance to cover ticket cost and gas fees.'); return; } // Proceed with buying the ticket const tx = await contract.buyTicket(eventId, { value: ticketCost }); const receipt = await tx.wait(); setTransactionHash(receipt.transactionHash); console.log( 'Ticket bought successfully, transaction hash:', receipt.transactionHash ); } catch (error) { console.error('Error buying ticket:', error); } }; return (

Buy Ticket

{!isWalletConnected ? ( ) : (

Connected Wallet: {walletAddress}

setEventId(Number(e.target.value))} className="border p-2 mb-2" /> {transactionHash && (

Transaction successful! Hash: {transactionHash}

)}
)}
); }; export default BuyTicket;