Hive Keychain with PeakeCoin Casino

@strangedad · 2025-10-02 01:37 · ['hive-193552']

🎲 PeakeSino: PeakeCoin’s Blockchain Betting API

Maryland is stepping into the future of gambling with PeakeSino — a decentralized betting and gambling platform powered by PeakeCoin (PEK) and built on the Hive blockchain. This project brings home-grown innovation to the Chesapeake digital economy with a transparent, blockchain-backed casino API.

The PeakeSino API is built using Flask, SQLite, and Hive Engine integration, allowing anyone with a Hive account to place bets using PEK through Hive Keychain transactions. Outcomes are recorded, payouts are calculated instantly, and all betting activity is logged into a lightweight SQLite database for transparency and history.


⚙️ Key Features

  • Health checks to confirm the service is live
  • PEK balance lookups on Hive Engine
  • Bet placement via Hive Keychain with transaction verification
  • Multiple bet types including:
  • Coin Flip (50/50 double-up)
  • Dice Roll (1-in-6 jackpot)
  • Lottery (tickets with 10% win chance)
  • Sports Betting (future expansion)
  • SQLite tracking of bets, payouts, and user balances

This system is still in demo phase but lays the groundwork for a real Maryland-themed blockchain casino experience. The next phase will integrate real PEK payouts directly back to user accounts.


🖥️ Full Source Code

Below is the complete PeakeSino API code — copy and paste into your own environment to run and test:

from flask import Flask, request, jsonify

from flask_cors import CORS

from dotenv import load_dotenv

import os

import requests

import sqlite3

import uuid

from datetime import datetime

import json

from beem import Hive

from beem.account import Account

from beem.exceptions import AccountDoesNotExistsException

Load environment variables

load_dotenv()

app = Flask(name) CORS(app)

Configuration

HIVE_ENGINE_API = "https://api.hive-engine.com/rpc" DATABASE_PATH = "betting.db"

class BettingAPI: def init(self): self.init_database() self.hive_node = os.getenv('HIVE_NODE', 'https://api.hive.blog')

def init_database(self):
    """Initialize SQLite database for storing bets"""
    conn = sqlite3.connect(DATABASE_PATH)
    cursor = conn.cursor()

    # Create bets table
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS bets (
            id TEXT PRIMARY KEY,
            user_id TEXT NOT NULL,
            amount REAL NOT NULL,
            bet_type TEXT NOT NULL,
            status TEXT DEFAULT 'pending',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            resolved_at TIMESTAMP,
            outcome TEXT,
            payout REAL DEFAULT 0,
            transaction_id TEXT,
            block_num INTEGER
        )
    ''')

    # Create balance table for tracking PEK balances
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS balances (
            user_id TEXT PRIMARY KEY,
            pek_balance REAL DEFAULT 0,
            locked_balance REAL DEFAULT 0,
            last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ''')

    conn.commit()
    conn.close()

def get_pek_balance(self, username):
    """Get PEK balance from Hive Engine"""
    try:
        payload = {
            "jsonrpc": "2.0",
            "method": "find",
            "params": {
                "contract": "tokens",
                "table": "balances",
                "query": {
                    "account": username,
                    "symbol": "PEK"
                }
            },
            "id": 1
        }

        response = requests.post(HIVE_ENGINE_API, json=payload)
        data = response.json()

        if data.get('result') and len(data['result']) > 0:
            return float(data['result'][0]['balance'])
        return 0.0

    except Exception as e:
        print(f"Error getting PEK balance: {e}")
        return 0.0

def place_bet_keychain(self, user_id, amount, bet_type, transaction_id, block_num):
    """Place a bet from Keychain transaction"""
    try:
        # Verify transaction exists and is valid
        if not self.verify_hive_transaction(transaction_id, user_id, amount):
            return {"error": "Invalid transaction or transaction not found"}

        # Generate unique bet ID
        bet_id = str(uuid.uuid4())

        # Process the bet outcome immediately
        outcome, won, payout = self.process_bet_outcome(bet_type, amount)

        # Store bet in database
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()

        cursor.execute('''
            INSERT INTO bets (id, user_id, amount, bet_type, status, outcome, payout, transaction_id, block_num, resolved_at)
            VALUES (?, ?, ?, ?, 'completed', ?, ?, ?, ?, CURRENT_TIMESTAMP)
        ''', (bet_id, user_id, amount, bet_type, outcome, payout, transaction_id, block_num))

        conn.commit()
        conn.close()

        # Send payout if won
        if won and payout > 0:
            self.send_payout(user_id, payout, bet_id)

        return {
            "success": True,
            "bet_id": bet_id,
            "amount": amount,
            "bet_type": bet_type,
            "outcome": outcome,
            "won": won,
            "payout": payout,
            "status": "completed"
        }

    except Exception as e:
        return {"error": f"Failed to place bet: {str(e)}"}

def verify_hive_transaction(self, transaction_id, expected_user, expected_amount):
    """Verify a Hive transaction exists and matches expected parameters"""
    try:
        # In a real implementation, you would:
        # 1. Query the Hive blockchain for the transaction
        # 2. Verify it's a token transfer to your betting account
        # 3. Verify the amount and memo
        # For demo purposes, we'll assume all transactions are valid
        return True
    except Exception as e:
        print(f"Error verifying transaction: {e}")
        return False

def process_bet_outcome(self, bet_type, amount):
    """Process the outcome of a bet"""
    import random

    if bet_type.startswith('coin_flip_'):
        choice = bet_type.split('_')[2]  # heads or tails
        result = random.choice(['heads', 'tails'])
        won = result == choice
        outcome = f"Coin landed on {result}"
        payout = amount * 2 if won else 0

    elif bet_type.startswith('dice_roll_'):
        target = int(bet_type.split('_')[2])
        roll = random.randint(1, 6)
        won = roll == target
        outcome = f"Rolled {roll}"
        payout = amount * 6 if won else 0

    elif bet_type.startswith('lottery_'):
        tickets = int(bet_type.split('_')[1])
        outcome = f"Bought {tickets} lottery ticket(s)"
        # For demo, small chance to win
        won = random.random() < 0.1  # 10% chance
        payout = amount * 10 if won else 0

    else:
        outcome = "Unknown bet type"
        won = False
        payout = 0

    return outcome, won, payout

def send_payout(self, user_id, amount, bet_id):
    """Send payout to user (in real implementation, this would send PEK tokens)"""
    try:
        # In a real implementation, you would:
        # 1. Use your betting account's active key
        # 2. Send PEK tokens back to the user
        # 3. Include bet_id in the memo
        print(f"Sending {amount} PEK to {user_id} for bet {bet_id}")
        return True
    except Exception as e:
        print(f"Error sending payout: {e}")
        return False

def get_user_bets(self, user_id):
    """Get all bets for a user"""
    try:
        conn = sqlite3.connect(DATABASE_PATH)
        cursor = conn.cursor()

        cursor.execute('''
            SELECT id, amount, bet_type, status, created_at, outcome, payout
            FROM bets WHERE user_id = ?
            ORDER BY created_at DESC
        ''', (user_id,))

        bets = []
        for row in cursor.fetchall():
            bets.append({
                "id": row[0],
                "amount": row[1],
                "bet_type": row[2],
                "status": row[3],
                "created_at": row[4],
                "outcome": row[5],
                "payout": row[6]
            })

        conn.close()
        return bets

    except Exception as e:
        return {"error": f"Failed to get bets: {str(e)}"}

Initialize betting API

betting_api = BettingAPI()

Routes

@app.route('/api/health', methods=['GET']) def health_check(): return jsonify({"status": "healthy", "message": "PeakeCoin Betting API is running"})

@app.route('/api/balance/', methods=['GET']) def get_balance(username): """Get PEK balance for a user""" balance = betting_api.get_pek_balance(username) return jsonify({"username": username, "pek_balance": balance})

@app.route('/api/bet/keychain', methods=['POST']) def place_bet_keychain(): """Place a new bet from Keychain transaction""" data = request.get_json()

required_fields = ['user_id', 'amount', 'bet_type', 'transaction_id', 'block_num']
if not data or not all(field in data for field in required_fields):
    return jsonify({"error": f"Missing required fields: {', '.join(required_fields)}"}), 400

result = betting_api.place_bet_keychain(
    data['user_id'],
    float(data['amount']),
    data['bet_type'],
    data['transaction_id'],
    data['block_num']
)

if 'error' in result:
    return jsonify(result), 400

return jsonify(result)

@app.route('/api/bet', methods=['POST']) def place_bet(): """Place a new bet (legacy method)""" data = request.get_json()

if not data or 'user_id' not in data or 'amount' not in data or 'bet_type' not in data:
    return jsonify({"error": "Missing required fields: user_id, amount, bet_type"}), 400

# For legacy support, redirect to keychain method
return jsonify({"error": "Please use Hive Keychain for betting"}), 400

@app.route('/api/bets/', methods=['GET']) def get_bets(user_id): """Get all bets for a user""" bets = betting_api.get_user_bets(user_id) return jsonify({"user_id": user_id, "bets": bets})

@app.route('/api/bet-types', methods=['GET']) def get_bet_types(): """Get available bet types""" bet_types = [ {"id": "coin_flip", "name": "Coin Flip", "description": "50/50 chance to double your PEK"}, {"id": "dice_roll", "name": "Dice Roll", "description": "Roll dice and win based on numbers"}, {"id": "lottery", "name": "Lottery", "description": "Buy tickets for the daily lottery"}, {"id": "sports", "name": "Sports Betting", "description": "Bet on sports events"} ] return jsonify({"bet_types": bet_types})

if name == 'main': app.run(debug=True, host='0.0.0.0', port=5000)


🌊 Why It Matters

PeakeSino isn’t just a side project — it’s proof that Maryland tech can lead in Web3 entertainment. With PEK as the in-game currency and Hive providing the backbone, this is setting the stage for a decentralized casino ecosystem.

Stay tuned — real PEK payouts, sports betting modules, and Maryland-style casino flair are on the horizon. 🦀


This report was published via Actifit app (Android | iOS). Check out the original version here on actifit.io


30/09/2025
6372
Daily Activity

#hive-193552 #actifit #pimp #creativecoin #neoxian #palnet #waivio #utopis #archon #proofofbrain #lassecash #bilpcoin #leo #list #peakecoin #hivehustlers #bee #ctp #stem #lern #byte # #sportstalk #movetoearn #move2earn
Payout: 0.119 HBD
Votes: 19
More interactions (upvote, reblog, reply) coming soon.