Fetch open and my bets from blockchain
This commit is contained in:
parent
98d6c3bd80
commit
6a1580afa7
662
package-lock.json
generated
662
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
|
|
@ -12,7 +12,6 @@ import { PriceSelection } from "./PriceSelection";
|
|||
import { GameSelection } from "./GameSelection";
|
||||
import { CLUSTER_URL } from "@/data/shared";
|
||||
|
||||
const PROGRAM_ID = new PublicKey("HxsDuhD7wcPxcMsrYdteMYxkffuwff8HoxhZ7NuFtM37");
|
||||
// Change to Mainnet when deploying
|
||||
|
||||
interface GameModalProps {
|
||||
|
|
@ -103,9 +102,17 @@ export default function GameModal({ isOpen, onClose }: GameModalProps) {
|
|||
toast.success(`Bet created successfully! TX: ${txId}`);
|
||||
console.log(`Transaction ID: ${txId}`);
|
||||
onClose();
|
||||
} catch (error) {
|
||||
console.error("Error creating bet:", error);
|
||||
toast.error("Failed to create bet.");
|
||||
} catch (error:unknown) {
|
||||
|
||||
|
||||
const errorMessage = String(error); // Converts error to string safely
|
||||
|
||||
if (errorMessage.includes("already in use")) {
|
||||
toast.error("You can't make 2 bets for the same game.");
|
||||
} else {
|
||||
toast.error("Failed to create bet.");
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,41 +1,75 @@
|
|||
"use client";
|
||||
import { useEffect, useState } from "react";
|
||||
import Image from "next/image";
|
||||
import {games} from "../data/games";
|
||||
export default function OpenGames() {
|
||||
import { games } from "../data/games";
|
||||
import { useSolanaWallets } from "@privy-io/react-auth";
|
||||
import { fetchOpenBets } from "@/shared/solana_helpers";
|
||||
import {Bet} from "../types/Bet";
|
||||
export default function YourGames() {
|
||||
const { wallets, ready } = useSolanaWallets();
|
||||
const [openBets, setOpenBets] = useState<Bet[]>([]);
|
||||
const [myBets, setMyBets] = useState<Bet[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Function to fetch open bets
|
||||
const updateBets= async ()=>{
|
||||
const bets:Bet[] = await fetchOpenBets(wallets[0]);
|
||||
setMyBets(bets.filter((bet) => bet.owner !== wallets[0].address));
|
||||
setOpenBets(bets);
|
||||
setLoading(false);
|
||||
console.log(`Got ${bets.length} bets`);
|
||||
}
|
||||
// Auto-refresh every 10 seconds
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
updateBets();
|
||||
const interval = setInterval(updateBets, 10000); // Refresh every 10s
|
||||
|
||||
return () => clearInterval(interval); // Cleanup on unmount
|
||||
}, [ready]);
|
||||
|
||||
return (
|
||||
<section className="py-16 px-6">
|
||||
<h2 className="text-3xl font-bold text-white mb-6">Open Games</h2>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{games.map((game) => (
|
||||
<div
|
||||
key={game.id}
|
||||
className="relative group bg-[rgb(30,30,30)] rounded-2xl p-2 w-50 overflow-hidden cursor-pointer transition-all duration-300 hover:-translate-y-2"
|
||||
>
|
||||
{/* Game Thumbnail */}
|
||||
<div className="relative w-full h-40 overflow-hidden rounded-xl">
|
||||
<Image
|
||||
src={game.thumbnail}
|
||||
alt={game.name}
|
||||
layout="fill"
|
||||
objectFit="cover"
|
||||
className="transition-transform duration-300 group-hover:scale-110"
|
||||
/>
|
||||
|
||||
{/* Join Button - Centered inside Image */}
|
||||
<button className="absolute inset-0 flex items-center justify-center bg-black/60 text-white font-semibold rounded-xl opacity-0 transition-opacity duration-300 group-hover:opacity-100">
|
||||
Join Game
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Game Info - Left Aligned */}
|
||||
<div className="mt-4 px-3 text-left">
|
||||
<h3 className="text-lg font-semibold text-white py-2">{game.name}</h3>
|
||||
<p className="text-xs text-gray-400 font-mono py-1">Wager</p>
|
||||
<p className="text-xs text-white font-mono py-1">{game.entryFee}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{loading ? (
|
||||
<p className="text-gray-400">Loading Open games...</p>
|
||||
) :
|
||||
myBets.length === 0 ? <></> :(
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{myBets.map((bet) => {
|
||||
console.log(`Finding game for the id ${bet.id}`)
|
||||
const game = games.find((g) => g.id === bet.id); // Match game
|
||||
|
||||
if (!game) return null; // Skip unmatched bets
|
||||
|
||||
return (
|
||||
<div
|
||||
key={bet.id + bet.owner}
|
||||
className="relative group bg-[rgb(30,30,30)] rounded-2xl p-2 w-50 overflow-hidden cursor-pointer transition-all duration-300"
|
||||
>
|
||||
{/* Game Thumbnail */}
|
||||
<div className="relative w-full h-40 overflow-hidden rounded-xl">
|
||||
<Image
|
||||
src={game.thumbnail}
|
||||
alt={game.name}
|
||||
layout="fill"
|
||||
objectFit="cover"
|
||||
className="transition-transform duration-300 group-hover:scale-110"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Game Info */}
|
||||
<div className="mt-4 px-3 text-left">
|
||||
<h3 className="text-lg font-semibold text-white py-2">{game.name}</h3>
|
||||
<p className="text-xs text-gray-400 font-mono py-1">Wager</p>
|
||||
<p className="text-xs text-white font-mono py-1">{bet.wager} SOL</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
import { useState, useEffect, useRef } from "react";
|
||||
import { usePrivy, useSolanaWallets } from "@privy-io/react-auth";
|
||||
import { Connection, PublicKey } from "@solana/web3.js"; // Solana Web3.js imports
|
||||
import { toast, ToastContainer } from "react-toastify";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import "react-toastify/dist/ReactToastify.css";
|
||||
import { CLUSTER_URL } from "@/data/shared";
|
||||
|
||||
|
|
@ -161,18 +162,6 @@ export default function PrivyButton() {
|
|||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Toast container */}
|
||||
<ToastContainer
|
||||
position="top-right"
|
||||
autoClose={3000}
|
||||
hideProgressBar
|
||||
newestOnTop
|
||||
closeButton={false}
|
||||
pauseOnHover
|
||||
draggable
|
||||
pauseOnFocusLoss
|
||||
/>
|
||||
|
||||
{/* Animation */}
|
||||
<style jsx>{`
|
||||
@keyframes slide-down {
|
||||
|
|
|
|||
|
|
@ -2,73 +2,29 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import Image from "next/image";
|
||||
import { games } from "../data/games";
|
||||
import { Connection, PublicKey, LAMPORTS_PER_SOL } from "@solana/web3.js";
|
||||
import { AnchorProvider, Program } from "@coral-xyz/anchor";
|
||||
import { CLUSTER_URL } from "../data/shared";
|
||||
import { Bets } from "../idl/bets";
|
||||
import { FiTrash } from "react-icons/fi";
|
||||
import idl from "../idl/bets_idl.json";
|
||||
import { useSolanaWallets } from "@privy-io/react-auth";
|
||||
|
||||
import { fetchOpenBets } from "@/shared/solana_helpers";
|
||||
import {Bet} from "../types/Bet";
|
||||
export default function YourGames() {
|
||||
const { wallets, ready } = useSolanaWallets();
|
||||
const [openBets, setOpenBets] = useState<any[]>([]);
|
||||
const [openBets, setOpenBets] = useState<Bet[]>([]);
|
||||
const [myBets, setMyBets] = useState<Bet[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Function to fetch open bets
|
||||
const fetchOpenBets = async () => {
|
||||
try {
|
||||
if (!wallets[0]) return;
|
||||
|
||||
const connection = new Connection(CLUSTER_URL);
|
||||
const wallet = {
|
||||
publicKey: new PublicKey(wallets[0].address),
|
||||
signTransaction: wallets[0].signTransaction,
|
||||
signAllTransactions: wallets[0].signAllTransactions,
|
||||
};
|
||||
const provider = new AnchorProvider(connection, wallet, {
|
||||
preflightCommitment: "confirmed",
|
||||
});
|
||||
|
||||
const program = new Program<Bets>(idl, provider);
|
||||
const [bet_list_pda] = await PublicKey.findProgramAddress(
|
||||
[Buffer.from("bets_list")],
|
||||
program.programId
|
||||
);
|
||||
// Fetch all open bet accounts
|
||||
const bet_list = await program.account.betsList.fetch(bet_list_pda);
|
||||
|
||||
// Extract required bet data
|
||||
const formattedBets = await Promise.all(
|
||||
bet_list.bets.map(async (bet) => {
|
||||
const betAcc = await program.account.betVault.fetch(bet);
|
||||
console.log(betAcc.gameId);
|
||||
return {
|
||||
id: betAcc.gameId,
|
||||
owner: betAcc.owner.toBase58(),
|
||||
joiner: betAcc.joiner ? betAcc.joiner.toBase58() : "Open",
|
||||
wager: betAcc.wager.toNumber() / LAMPORTS_PER_SOL
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
console.log(`Got ${formattedBets.length} bets`);
|
||||
|
||||
setOpenBets(formattedBets);
|
||||
setLoading(false);
|
||||
} catch (error) {
|
||||
console.error("Error fetching open bets:", error);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const updateBets= async ()=>{
|
||||
const bets:Bet[] = await fetchOpenBets(wallets[0]);
|
||||
setMyBets(bets.filter((bet) => bet.owner === wallets[0].address));
|
||||
setOpenBets(bets);
|
||||
setLoading(false);
|
||||
console.log(`Got ${bets.length} bets`);
|
||||
}
|
||||
// Auto-refresh every 10 seconds
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
|
||||
fetchOpenBets(); // Initial fetch
|
||||
|
||||
const interval = setInterval(fetchOpenBets, 10000); // Refresh every 10s
|
||||
updateBets();
|
||||
const interval = setInterval(updateBets, 10000); // Refresh every 10s
|
||||
|
||||
return () => clearInterval(interval); // Cleanup on unmount
|
||||
}, [ready]);
|
||||
|
|
@ -78,11 +34,13 @@ export default function YourGames() {
|
|||
<h2 className="text-3xl font-bold text-white mb-6">Your Games</h2>
|
||||
|
||||
{loading ? (
|
||||
<p className="text-gray-400">Loading open games...</p>
|
||||
) : (
|
||||
<p className="text-gray-400">Loading your games...</p>
|
||||
) :
|
||||
myBets.length === 0 ? <></> :(
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{openBets.map((bet) => {
|
||||
const game = games.find((g) => g.id === bet.gameId); // Match game
|
||||
{myBets.map((bet) => {
|
||||
console.log(`Finding game for the id ${bet.id}`)
|
||||
const game = games.find((g) => g.id === bet.id); // Match game
|
||||
|
||||
if (!game) return null; // Skip unmatched bets
|
||||
|
||||
|
|
|
|||
53
src/shared/solana_helpers.ts
Normal file
53
src/shared/solana_helpers.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { CLUSTER_URL } from "@/data/shared";
|
||||
import { Bets } from "@/idl/bets";
|
||||
import { AnchorProvider, Program } from "@coral-xyz/anchor";
|
||||
import { ConnectedSolanaWallet } from "@privy-io/react-auth";
|
||||
import { Connection, LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js";
|
||||
import idl from "../idl/bets_idl.json";
|
||||
import { Bet } from "@/types/Bet";
|
||||
|
||||
|
||||
export const fetchOpenBets = async (wallets: ConnectedSolanaWallet): Promise<Bet[]> => {
|
||||
try {
|
||||
if (!wallets) return [];
|
||||
|
||||
const connection = new Connection(CLUSTER_URL);
|
||||
const wallet = {
|
||||
publicKey: new PublicKey(wallets.address),
|
||||
signTransaction: wallets.signTransaction,
|
||||
signAllTransactions: wallets.signAllTransactions,
|
||||
};
|
||||
const provider = new AnchorProvider(connection, wallet, {
|
||||
preflightCommitment: "confirmed",
|
||||
});
|
||||
|
||||
const program = new Program<Bets>(idl, provider);
|
||||
const [bet_list_pda] = await PublicKey.findProgramAddress(
|
||||
[Buffer.from("bets_list")],
|
||||
program.programId
|
||||
);
|
||||
// Fetch all open bet accounts
|
||||
const bet_list = await program.account.betsList.fetch(bet_list_pda);
|
||||
|
||||
// Extract required bet data
|
||||
const formattedBets = await Promise.all(
|
||||
bet_list.bets.map(async (bet) => {
|
||||
const betAcc = await program.account.betVault.fetch(bet);
|
||||
console.log(betAcc.gameId);
|
||||
return {
|
||||
id: betAcc.gameId,
|
||||
owner: betAcc.owner.toBase58(),
|
||||
joiner: betAcc.joiner ? betAcc.joiner.toBase58() : "Open",
|
||||
wager: betAcc.wager.toNumber() / LAMPORTS_PER_SOL
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
console.log(`Got ${formattedBets.length} bets`);
|
||||
|
||||
return formattedBets;
|
||||
} catch (error) {
|
||||
console.error("Error fetching open bets:", error);
|
||||
}
|
||||
return [];
|
||||
};
|
||||
6
src/types/Bet.ts
Normal file
6
src/types/Bet.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export interface Bet {
|
||||
id: string;
|
||||
owner: string;
|
||||
joiner: string;
|
||||
wager: number;
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user