import { Hono } from "hono";
import { createB3Client } from "@b3dotfun/upside-sdk/server";
const app = new Hono();
app.post("/api/game/coin-flip", async c => {
const { prediction, betAmount } = await c.req.json();
try {
// Create B3Client from Hono context
// Automatically extracts auth token from Authorization header
const b3Client = createB3Client(c);
// Step 1: Place the bet (amount in wei)
const betResult = await b3Client.placeBet("coin-flip", betAmount);
if (!betResult.sessionId) {
return c.json({ error: "Failed to place bet" }, 400);
}
// Step 2: Game logic - flip coin
const coin = Math.random() < 0.5 ? "heads" : "tails";
const isWin = coin === prediction;
// Calculate payout: 50% profit on win (betAmount * 1.5, in wei)
const payout = isWin ? (BigInt(betAmount) * BigInt(150)) / BigInt(100) : "0";
// Step 3: Store game in your database (D1, etc.)
// await db.execute(
// "INSERT INTO games (sessionId, prediction, result, betAmount, payout) VALUES (?, ?, ?, ?, ?)",
// [betResult.sessionId, prediction, coin, betAmount, payout.toString()]
// );
// Step 4: Process payout
const payoutResult = await b3Client.processPayout("coin-flip", betResult.sessionId, payout.toString(), {
playerChoice: prediction,
result: coin,
outcome: isWin ? "win" : "loss",
});
// Step 5: Return result to frontend
return c.json({
sessionId: betResult.sessionId,
prediction,
result: coin,
outcome: isWin ? "win" : "loss",
payout: isWin ? payout.toString() : "0",
newBalance: payoutResult.newBalance,
});
} catch (error) {
console.error("Game error:", error);
return c.json({ error: error.message }, 500);
}
});
export default app;