import { ParentProvider, useParentContext } from "@b3dotfun/upside-sdk";
export default function CoinFlipGame() {
return (
<ParentProvider>
<CoinFlipContent />
</ParentProvider>
);
}
function CoinFlipContent() {
const { token, balance, playerId } = useParentContext();
const [gameState, setGameState] = useState("ready"); // ready, playing, won, lost
const [prediction, setPrediction] = useState(null);
const [result, setResult] = useState(null);
const [earnings, setEarnings] = useState(0);
const playGame = async playerPrediction => {
setPrediction(playerPrediction);
setGameState("playing");
try {
// Call your backend
const response = await fetch("/api/game/coin-flip", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
playerId,
prediction: playerPrediction,
betAmount: "100000000000000000", // 1 token in wei
}),
});
const data = await response.json();
if (data.outcome === "win") {
setGameState("won");
setEarnings(data.payout);
} else {
setGameState("lost");
setEarnings(0);
}
setResult(data.result);
} catch (error) {
console.error("Game error:", error);
setGameState("error");
}
};
return (
<div style={{ textAlign: "center", padding: "40px" }}>
<h1>Coin Flip</h1>
<p>Balance: {(balance / 1e18).toFixed(2)} WIN</p>
{gameState === "ready" && (
<div>
<button onClick={() => playGame("heads")}>Predict Heads</button>
<button onClick={() => playGame("tails")}>Predict Tails</button>
</div>
)}
{gameState === "playing" && <p>Flipping...</p>}
{gameState === "won" && (
<div>
<p>🎉 You won! Coin landed on {result}</p>
<p>+{(earnings / 1e18).toFixed(2)} WIN</p>
</div>
)}
{gameState === "lost" && (
<div>
<p>❌ You lost! Coin landed on {result}</p>
<p>Better luck next time</p>
</div>
)}
{gameState !== "ready" && <button onClick={() => setGameState("ready")}>Play Again</button>}
</div>
);
}