added new components for sc

This commit is contained in:
ayomaska18
2024-10-26 10:33:51 +01:00
parent fd9d7b06d9
commit 372298b409
7 changed files with 209 additions and 47 deletions

View File

@@ -0,0 +1,119 @@
'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<number | null>(null);
const [transactionHash, setTransactionHash] = useState<string | null>(null);
const [isWalletConnected, setIsWalletConnected] = useState<boolean>(false);
const [walletAddress, setWalletAddress] = useState<string | null>(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 (
<div className="p-4">
<h2>Buy Ticket</h2>
{!isWalletConnected ? (
<button
onClick={handleConnectWallet}
className="bg-blue-500 text-white px-4 py-2 rounded mb-4"
>
Connect Wallet
</button>
) : (
<div>
<p>Connected Wallet: {walletAddress}</p>
<input
type="number"
placeholder="Enter Event ID"
value={eventId !== null ? eventId : ''}
onChange={(e) => setEventId(Number(e.target.value))}
className="border p-2 mb-2"
/>
<button
onClick={handleBuyTicket}
className="bg-purple-500 text-white px-4 py-2 rounded"
>
Buy Ticket
</button>
{transactionHash && (
<p className="mt-4">
Transaction successful! Hash: <strong>{transactionHash}</strong>
</p>
)}
</div>
)}
</div>
);
};
export default BuyTicket;

View File

@@ -14,11 +14,13 @@ const CreateEvent = () => {
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [capacity, setCapacity] = useState(0);
const [ticketPrice, setTicketPrice] = useState(0); // Price in FLR
const [ticketPrice, setTicketPrice] = useState(0);
const [eventDate, setEventDate] = useState('');
const [images, setImages] = useState<string[]>([]);
const [transactionHash, setTransactionHash] = useState('');
const [isWalletConnected, setIsWalletConnected] = useState(false);
const [walletAddress, setWalletAddress] = useState<string | null>(null); // Store the connected wallet address
const [eventId, setEventId] = useState<number | null>(null); // Store the created event ID
// Check if the wallet is connected on component mount
useEffect(() => {
@@ -29,6 +31,7 @@ const CreateEvent = () => {
});
if (accounts && accounts.length > 0) {
setIsWalletConnected(true); // Wallet is connected
setWalletAddress(accounts[0]); // Store the connected wallet address
} else {
setIsWalletConnected(false); // Wallet is not connected
}
@@ -48,6 +51,7 @@ const CreateEvent = () => {
});
if (accounts.length > 0) {
setIsWalletConnected(true);
setWalletAddress(accounts[0]); // Store the connected wallet address
console.log('Wallet connected:', accounts[0]);
}
}
@@ -75,19 +79,37 @@ const CreateEvent = () => {
const contract = getContract().connect(signer);
const unixEventDate = Math.floor(new Date(eventDate).getTime() / 1000); // Convert to Unix timestamp
const weiTicketPrice = ethers.utils.parseEther(ticketPrice.toString()); // Convert FLR to Wei
// Convert ticket price from dollars to cents
const centsTicketPrice = Math.round(ticketPrice * 100); // Assuming ticketPrice is entered in USD cents
// Call the `createEvent` function, which submits the transaction
const tx = await contract.createEvent(
name,
description,
capacity,
weiTicketPrice,
centsTicketPrice, // Now this is in cents, e.g storing as 500 cents == 5.00 usd
unixEventDate,
images
);
console.log('Transaction Submitted:', tx);
// Wait for the transaction to be mined
const receipt = await tx.wait();
setTransactionHash(receipt.transactionHash);
console.log('Event created successfully!');
// Extract the `eventId` from the event logs in the receipt
const eventId = receipt.events?.find(
(event: ethers.Event) => event.event === 'EventCreated'
)?.args?.[0];
if (eventId) {
setEventId(eventId.toNumber()); // Store the event ID if found
console.log('Event created successfully with ID:', eventId.toNumber());
} else {
console.log('Event ID not found in the logs.');
}
} catch (error) {
console.error('Error creating event:', error);
}
@@ -100,6 +122,8 @@ const CreateEvent = () => {
) : (
<div>
<h2>Create Event</h2>
<p>Connected Wallet: {walletAddress}</p>{' '}
{/* Display connected wallet address */}
<input
type="text"
placeholder="Event Name"
@@ -137,10 +161,10 @@ const CreateEvent = () => {
onChange={(e) => setImages(e.target.value.split(','))}
/>
<button onClick={handleCreateEvent}>Create Event</button>
{transactionHash && (
<p>Transaction successful! Hash: {transactionHash}</p>
)}
{eventId !== null && <p>Event ID: {eventId}</p>}
</div>
)}
</div>

View File

@@ -13,7 +13,7 @@ const GetEventPrice = () => {
if (eventId === null) return;
const contract = getContract();
const flrPrice = await contract.getEventPriceFlare(eventId);
const flrPrice = await contract.getEventPriceFlare(eventId); // flr price in usd cents e.g. return 36856 meaning 500 usd cents
setPriceInFlr(ethers.utils.formatEther(flrPrice.toString()));
} catch (error) {
console.error('Error fetching event price:', error);

View File

@@ -1,22 +1,39 @@
'use client';
import React, { useState } from 'react';
import { ethers } from 'ethers';
import { getContract } from '@/lib/ethers'; // Adjust the path to your ethers helper
const GetEventTickets = () => {
const [eventId, setEventId] = useState<number | null>(null);
const [tickets, setTickets] = useState<number[] | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const handleGetTickets = async () => {
setErrorMessage(null);
setTickets(null);
if (eventId === null) {
setErrorMessage('Please enter a valid Event ID.');
return;
}
try {
// Get the contract instance
const contract = getContract();
if (eventId === null) return;
// Fetch tickets for the given event ID
const eventTickets = await contract.getEventTickets(eventId);
setTickets(eventTickets);
// Convert BigNumbers to plain numbers for display
setTickets(
eventTickets.map((ticket: ethers.BigNumber) => ticket.toNumber())
);
} catch (error) {
console.error('Error fetching event tickets:', error);
setErrorMessage(
'Failed to fetch tickets. Please check the Event ID and try again.'
);
}
};
@@ -37,6 +54,8 @@ const GetEventTickets = () => {
Get Tickets
</button>
{errorMessage && <p className="text-red-500">{errorMessage}</p>}
{tickets && (
<div className="mt-4">
<h3>Tickets for Event {eventId}:</h3>