### Install and Run Next.js App Source: https://github.com/britelink/aurum/blob/main/README.md Commands to install project dependencies and start the development server for a Next.js application. Assumes project files are already cloned. ```bash npm install npm run dev ``` -------------------------------- ### Create Next.js + Convex Auth Project Source: https://github.com/britelink/aurum/blob/main/README.md Command to create a new project using the 'nextjs-convexauth' template with `npm create convex`. This command initializes a new project with the specified template. ```bash npm create convex@latest -- -t nextjs-convexauth ``` -------------------------------- ### POST /api/payment/create-session Source: https://context7.com/britelink/aurum/llms.txt Initializes a deposit checkout session with the EFT PAY payment gateway. This endpoint is used to start the process of adding funds to a user's account. ```APIDOC ## POST /api/payment/create-session ### Description Initializes a deposit checkout session with the EFT PAY payment gateway. ### Method POST ### Endpoint /api/payment/create-session ### Parameters #### Request Body - **amount** (number) - Required - The amount to deposit. - **currency** (string) - Required - The currency for the deposit (e.g., 'USD', 'ZWG'). - **paymentMethod** (string) - Required - The payment method to use (e.g., 'card-usd', 'zimswitch-usd', 'zimswitch-zwg', 'ecocash-usd', 'ecocash-zwg'). - **userId** (string) - Required - The ID of the user making the deposit. - **email** (string) - Required - The email address of the user. ### Request Example ```json { "amount": 50.00, "currency": "USD", "paymentMethod": "card-usd", "userId": "ks72xyybrjx4pt5qe4wbsanzf17bg56z", "email": "user@example.com" } ``` ### Response #### Success Response (200) - **checkoutId** (string) - The ID of the created checkout session. - **paymentBrand** (string) - The payment brand associated with the session (e.g., 'VISA MASTER'). #### Response Example ```json { "checkoutId": "8AC7A4CA87EB6BE001234", "paymentBrand": "VISA MASTER" } ``` ``` -------------------------------- ### Configure EFT PAY Payment Gateway Environment Variables Source: https://github.com/britelink/aurum/blob/main/PAYMENT_SETUP.md This snippet shows how to configure the EFT PAY payment gateway by adding necessary credentials and entity IDs to the .env.local file. It includes the payment authorization bearer, API URL, and specific entity IDs for different payment methods. Ensure these are kept secure and not committed to version control. ```env # Payment Gateway Configuration PAYMENT_AUTH_BEARER=OGFjN2E0Yzc5ODU4MzE3MzAxOTg1YjdjZGE0MzA0NzZ8a3I/NSNiamhmcktGS3FEaUF6bTk= PAYMENT_API_URL=https://eu-test.oppwa.com # Entity IDs ZIMSWITCH_USD_ENTITY_ID=8ac7a4c79858317301985b7e52f8047f ZIMSWITCH_ZWG_ENTITY_ID=8ac7a4c79858317301985b7ee21f0483 CARD_USD_ENTITY_ID=8ac7a4c79858317301985b7dcc27047a ``` -------------------------------- ### TypeScript/React: Initialize Three.js Scene and Components Source: https://github.com/britelink/aurum/blob/main/app/(demo)/components/Bird.md Initializes a Three.js scene for the bird race game. It sets up the scene, camera, renderer, lighting, and basic geometric shapes like water, a tree, and a bird. This setup is crucial for the 3D visualization of the race. ```typescript //@ts-nocheck import React, { useEffect, useState, useRef } from "react"; import * as THREE from "three"; // Game interfaces interface Cloud { left: number; top: number; size: number; opacity: number; } interface Player { id: string; position: string; amount: number; } interface RaceResult { winningPosition?: string; isTie?: boolean; userWon?: boolean; userProfit?: number; failureOccurred?: boolean; failureReason?: string; } const BirdRaceBetting = () => { // State management const [balance, setBalance] = useState(1000); const [betAmount, setBetAmount] = useState(1); const [isRacing, setIsRacing] = useState(false); // Bird starts perched, not flying const [bettingOpen, setBettingOpen] = useState(true); const [countdown, setCountdown] = useState(10); const [birdPosition, setBirdPosition] = useState(80); // Start higher (on branch) const [birdXPosition, setBirdXPosition] = useState(15); // Start from left (15% across) const [birdDirection, setBirdDirection] = useState(0); const [sessionPlayers, setSessionPlayers] = useState([]); const [betImbalance, setBetImbalance] = useState("equal"); const [raceResult, setRaceResult] = useState(null); const [playerCount, setPlayerCount] = useState(0); const [upBets, setUpBets] = useState(0); const [downBets, setDownBets] = useState(0); const [userId] = useState( `user-${Math.random().toString(36).substring(2, 9)}`, ); const [trajectoryPath, setTrajectoryPath] = useState([]); const [flightProgress, setFlightProgress] = useState(0); // 0-100% const [flightFailed, setFlightFailed] = useState(false); const [failureChance, setFailureChance] = useState(15); // 15% base chance const [windStrength, setWindStrength] = useState(0); // Wind effect // Refs const raceTrackRef = useRef(null); const threeContainerRef = useRef(null); const rendererRef = useRef(null); const sceneRef = useRef(null); const cameraRef = useRef(null); const birdModelRef = useRef(null); // Generate clouds in background const [clouds, setClouds] = useState([]); // Initialize Three.js scene useEffect(() => { if (!threeContainerRef.current) return; // Create scene const scene = new THREE.Scene(); sceneRef.current = scene; scene.background = new THREE.Color(0x87ceeb); // Sky blue // Create camera const camera = new THREE.PerspectiveCamera( 75, threeContainerRef.current.clientWidth / threeContainerRef.current.clientHeight, 0.1, 1000, ); cameraRef.current = camera; camera.position.z = 5; camera.position.y = 1; // Create renderer const renderer = new THREE.WebGLRenderer({ antialias: true }); rendererRef.current = renderer; renderer.setSize( threeContainerRef.current.clientWidth, threeContainerRef.current.clientHeight, ); threeContainerRef.current.appendChild(renderer.domElement); // Add lighting const ambientLight = new THREE.AmbientLight(0xffffff, 0.6); scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8); directionalLight.position.set(5, 5, 5); scene.add(directionalLight); // Create water surface const waterGeometry = new THREE.PlaneGeometry(20, 10); const waterMaterial = new THREE.MeshPhongMaterial({ color: 0x4682b4, transparent: true, opacity: 0.8, shininess: 100, }); const water = new THREE.Mesh(waterGeometry, waterMaterial); water.rotation.x = -Math.PI / 2; water.position.y = -1; scene.add(water); // Create tree trunk const trunkGeometry = new THREE.CylinderGeometry(0.2, 0.3, 2, 8); const trunkMaterial = new THREE.MeshLambertMaterial({ color: 0x8b4513 }); const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial); trunk.position.set(-7, 0, 0); scene.add(trunk); // Create tree foliage const foliageGeometry = new THREE.ConeGeometry(1.5, 3, 8); const foliageMaterial = new THREE.MeshLambertMaterial({ color: 0x228b22 }); const foliage = new THREE.Mesh(foliageGeometry, foliageMaterial); foliage.position.set(-7, 2, 0); scene.add(foliage); // Create branch const branchGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 6); const branchMaterial = new THREE.MeshLambertMaterial({ color: 0x8b4513 }); const branch = new THREE.Mesh(branchGeometry, branchMaterial); branch.rotation.z = Math.PI / 4; branch.position.set(-6, 0.5, 0); scene.add(branch); // Create the bird (simple for now) const birdGeometry = new THREE.SphereGeometry(0.3, 16, 16); const birdMaterial = new THREE.MeshLambertMaterial({ color: 0x1e90ff }); const bird = new THREE.Mesh(birdGeometry, birdMaterial); bird.position.set(-6, 0.8, 0); // Start on branch birdModelRef.current = bird; scene.add(bird); const animate = () => { requestAnimationFrame(animate); if (rendererRef.current && sceneRef.current && cameraRef.current) { rendererRef.current.render(sceneRef.current, cameraRef.current); } }; animate(); const handleResize = () => { if (threeContainerRef.current && cameraRef.current && rendererRef.current) { cameraRef.current.aspect = threeContainerRef.current.clientWidth / threeContainerRef.current.clientHeight; cameraRef.current.updateProjectionMatrix(); rendererRef.current.setSize( threeContainerRef.current.clientWidth, threeContainerRef.current.clientHeight, ); } }; window.addEventListener("resize", handleResize); handleResize(); // Initial size set return () => { window.removeEventListener("resize", handleResize); if (threeContainerRef.current && rendererRef.current) { threeContainerRef.current.removeChild(rendererRef.current.domElement); } if (rendererRef.current) { rendererRef.current.dispose(); } }; }, []); // Game logic functions would go here return (

Balance: ${balance}

Bet Amount: ${betAmount}

Countdown: {countdown}

Players: {playerCount}

Bet Imbalance: {betImbalance}

{/* Other race elements like betting UI, player list, etc. would be overlaid here */}
{raceResult && (

Race Result

{raceResult.failureOccurred ? (

Failure: {raceResult.failureReason}

) : ( <>

Winning Position: {raceResult.winningPosition}

{raceResult.isTie &&

It's a tie!

} {raceResult.userWon &&

You won!

} {raceResult.userProfit !== undefined && (

Your Profit: ${raceResult.userProfit}

)} )}
)}
); }; export default BirdRaceBetting; ``` -------------------------------- ### Get User Transactions Source: https://context7.com/britelink/aurum/llms.txt Fetches all transactions for the authenticated user in descending order. ```APIDOC ## GET /api/aurum/getUserTransactions ### Description Fetches all transactions for the authenticated user, ordered by timestamp in descending order. ### Method GET ### Endpoint /api/aurum/getUserTransactions ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - An array of transaction objects, each containing: - **_id** (string) - The transaction ID. - **userId** (string) - The ID of the user associated with the transaction. - **amount** (number) - The transaction amount. - **type** (string) - The type of transaction (e.g., 'deposit', 'withdrawal', 'win', 'loss', 'fee'). - **status** (string) - The status of the transaction (e.g., 'completed', 'pending', 'failed'). - **paymentMethod** (string) - The payment method used. - **timestamp** (number) - The Unix timestamp of the transaction. - **fee** (number | undefined) - Any associated fee. #### Response Example ```json [ { "_id": "k72trans123", "userId": "ks72xyybrjx4pt5qe4wbsanzf17bg56z", "amount": 50.00, "type": "deposit", "status": "completed", "paymentMethod": "card-usd", "timestamp": 1703001234567, "fee": undefined } ] ``` ``` -------------------------------- ### Place Bet on Open Session (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Creates a new bet on an open session and updates session volumes. It requires a valid sessionId, amount, and direction. The session must exist and be open, and the user must be authenticated. The bet status starts as 'pending'. ```typescript import { useConvex, useMutation } from "convex/react"; import { api } from "@/convex/_generated/api"; const placeBet = useMutation(api.aurum.placeBet); // Place a bet on current session const betId = await placeBet({ sessionId: 'k72sess123456789', amount: 2, // 1 or 2 only direction: 'up' // or 'down' }); // Validation: // - Session must exist and be open // - User must be authenticated // - Updates totalBuyVolume (for 'up') or totalSellVolume (for 'down') // - Bet starts with 'pending' status ``` -------------------------------- ### Get Current Session Source: https://context7.com/britelink/aurum/llms.txt Retrieves the active betting session or the most recent closed session. ```APIDOC ## GET /api/session/getCurrentSession ### Description Retrieves the currently active betting session or the most recently closed session if no active session exists. ### Method GET ### Endpoint /api/session/getCurrentSession ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **_id** (string) - The session ID. - **startTime** (number) - The Unix timestamp when the session started. - **endTime** (number) - The Unix timestamp when the session ended. - **processingEndTime** (number) - The Unix timestamp when session processing concluded. - **neutralAxis** (number) - The neutral axis value for the session. - **totalBuyVolume** (number) - The total volume of 'up' bets. - **totalSellVolume** (number) - The total volume of 'down' bets. - **status** (string) - The current status of the session ('open', 'processing', 'closed', 'pending'). - **finalPrice** (number | undefined) - The final price of the asset, set when the session is closed. - **winner** (string | undefined) - Indicates the winning side ('buyers', 'sellers', or 'neutral'). #### Response Example ```json { "_id": "k72sess123456789", "startTime": 1703001234567, "endTime": 1703001264567, "processingEndTime": 1703001294567, "neutralAxis": 45.67, "totalBuyVolume": 15, "totalSellVolume": 23, "status": "open", "finalPrice": undefined, "winner": undefined } ``` ``` -------------------------------- ### Get Current Betting Session Data (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Retrieves data for the currently active betting session or the most recently closed session. The returned object includes session details such as start and end times, processing end time, neutral axis price, total buy/sell volumes, status, and final price/winner if applicable. ```typescript import { useQuery } from "convex/react"; import { api } from "@/convex/_generated/api"; const session = useQuery(api.session.getCurrentSession); // Returns: // { // _id: 'k72sess123456789', // startTime: 1703001234567, // endTime: 1703001264567, // startTime + 30 seconds // processingEndTime: 1703001294567, // endTime + 30 seconds // neutralAxis: 45.67, // totalBuyVolume: 15, // totalSellVolume: 23, // status: 'open', // or 'processing', 'closed', 'pending' // finalPrice: undefined, // set when closed // winner: undefined // 'buyers', 'sellers', or 'neutral' // } ``` -------------------------------- ### Sessions Table Schema Definition (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Defines the schema for the 'Sessions' table, used to track betting sessions, including their timing, volume, and outcomes. It captures start and end times, bet volumes, and session status. ```typescript // Schema definition { startTime: number, // Unix timestamp endTime: number, // startTime + 30000ms processingEndTime: number, // endTime + 30000ms neutralAxis: number, // Random 0-100 totalBuyVolume: number, // Total bet on 'up' totalSellVolume: number, // Total bet on 'down' finalPrice?: number, // Set when processing status: 'open' | 'processing' | 'closed' | 'pending', winner?: 'buyers' | 'sellers' | 'neutral' } // Indexes: by_status ``` -------------------------------- ### Get Current User Source: https://context7.com/britelink/aurum/llms.txt Retrieves the authenticated user's profile and balance information. Returns null if the user is not authenticated. ```APIDOC ## GET /api/aurum/getCurrentUser ### Description Retrieves the authenticated user's profile and balance. Returns null if the user is not authenticated. ### Method GET ### Endpoint /api/aurum/getCurrentUser ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **_id** (string) - The user's unique identifier. - **name** (string) - The user's name. - **email** (string) - The user's email address. - **balance** (number) - The user's current balance. - **walletBalance** (number) - The user's wallet balance. - **role** (string) - The user's role (e.g., 'player', 'admin', 'agent'). #### Response Example ```json { "_id": "ks72xyybrjx4pt5qe4wbsanzf17bg56z", "name": "John Doe", "email": "john@example.com", "balance": 125.50, "walletBalance": 0, "role": "player" } ``` ``` -------------------------------- ### Process EFT PAY Payment Status (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Handles payment verification and balance updates after EFT PAY payment completion, triggered by a redirect from EFT PAY. Verifies payment, updates the Convex database, and redirects the user. This is an internal processing example. ```typescript // POST /api/payment/process (called by EFT PAY redirect) // User is redirected here after payment with resourcePath in form data // Automatically verifies payment, updates user balance, and redirects to /play // Example payment flow: // 1. User completes payment on EFT PAY widget // 2. EFT PAY redirects to /api/payment/process?resourcePath=/v1/checkouts/{id}/payment // 3. Backend verifies payment status // 4. Updates Convex database with deposit // 5. Redirects to /play on success // Internal processing: const statusResponse = await paymentService.checkPaymentStatus(resourcePath); if (statusResponse.success) { await convex.mutation(api.aurum.adminDepositFunds, { userId: extractedUserId, amount: normalizedAmount, paymentMethod: 'card-usd' }); // Redirects to /play } ``` -------------------------------- ### Start Bird Racing Logic Source: https://github.com/britelink/aurum/blob/main/app/(demo)/components/Bird.md Initiates the racing state by setting various game-related states like `isRacing`, `flightProgress`, `flightFailed`, and initial bird positions. It also adjusts the `failureChance` based on bet imbalances, ensuring the game logic reflects player activity. ```javascript const startFlight = () => { setIsRacing(true); setFlightProgress(0); setFlightFailed(false); setBirdPosition(60); // Branch height setBirdXPosition(15); // Branch position setTrajectoryPath([]); // Adjust failure chance based on bet imbalance let adjustedFailureChance = failureChance; if (betImbalance === "up") { // If more bets on UP, increase chance of failing downward adjustedFailureChance += 10; } else if (betImbalance === "down") { // If more bets on DOWN, decrease chance of failing downward adjustedFailureChance -= 5; } // Clamp between 5% and 30% adjustedFailureChance = Math.max(5, Math.min(30, adjustedFailureChance)); setFailureChance(adjustedFailureChance); // Update 3D bird position if (birdModelRef.current) { birdModelRef.current.position.set(-6, 0.8, 0); } }; ``` -------------------------------- ### Get Current Authenticated User Profile (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Retrieves the profile and balance information for the currently authenticated user. If the user is not authenticated, it returns null. The returned object includes details like user ID, name, email, balance, wallet balance, and role. ```typescript import { useQuery } from "convex/react"; import { api } from "@/convex/_generated/api"; const user = useQuery(api.aurum.getCurrentUser); // Returns: // { // _id: 'ks72xyybrjx4pt5qe4wbsanzf17bg56z', // name: 'John Doe', // email: 'john@example.com', // balance: 125.50, // walletBalance: 0, // role: 'player' // or 'admin', 'agent' // } // Returns null if not authenticated ``` -------------------------------- ### Get User Transaction History (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Fetches all transactions associated with the authenticated user, ordered in descending chronological order. The returned array contains transaction objects, each detailing the ID, user ID, amount, type, status, payment method, timestamp, and optional fee. ```typescript import { useQuery } from "convex/react"; import { api } from "@/convex/_generated/api"; const transactions = useQuery(api.aurum.getUserTransactions); // Returns array: // [ // { // _id: 'k72trans123', // userId: 'ks72xyybrjx4pt5qe4wbsanzf17bg56z', // amount: 50.00, // type: 'deposit', // or 'withdrawal', 'win', 'loss', 'fee' // status: 'completed', // or 'pending', 'failed' // paymentMethod: 'card-usd', // timestamp: 1703001234567, // fee: undefined // }, // // ... more transactions // ] ``` -------------------------------- ### Payment Gateway Credentials Configuration (.env.local) Source: https://context7.com/britelink/aurum/llms.txt Environment variables for configuring the EFT PAY payment gateway. Includes authentication bearer token, API URL, and entity IDs for various payment methods like Zimswitch and Ecocash. ```env # .env.local # Payment Gateway Configuration PAYMENT_AUTH_BEARER=OGFjOWE0Yzc5ODdlYjZiZTAxOThjNjM0YmYxMDE4Zjd8TXhqSGRQUGdtbVchUFk1a0BuelI= PAYMENT_API_URL=https://eu-prod.oppwa.com # Entity IDs for different payment methods ZIMSWITCH_USD_ENTITY_ID=8ac9a4c7987eb6be0198c6359a1c1900 ZIMSWITCH_ZWG_ENTITY_ID=8ac9a4c7987eb6be0198c63e049e1944 CARD_USD_ENTITY_ID=8ac9a4c7987eb6be0198c63659ef1909 ECOCASH_USD_ENTITY_ID=8ac9a4c7987eb6be0198c63659ef1909 ECOCASH_ZWG_ENTITY_ID=8ac9a4c7987eb6be0198c63659ef1909 # Convex Backend NEXT_PUBLIC_CONVEX_URL=https://your-project.convex.cloud ``` -------------------------------- ### Create Betting Session with Convex Source: https://context7.com/britelink/aurum/llms.txt Creates a new betting session using Convex's useMutation hook. It automatically manages session cleanup by retaining the newest 5 sessions if more than 25 exist. The session is initialized with a 30-second betting period, a 30-second processing period, a random neutral axis, zero initial volumes, and an 'open' status. ```typescript import { useMutation } from "convex/react"; import { api } from "@/convex/_generated/api"; const createSession = useMutation(api.session.createSession); // Create new session const sessionId = await createSession(); // Automatic cleanup: // - If 25+ sessions exist, keeps newest 5 and deletes rest // - Creates session with: // - 30-second betting period // - 30-second processing period // - Random neutral axis (0-100) // - Initial volumes at 0 // - Status 'open' ``` -------------------------------- ### Create EFT PAY Payment Session (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Initializes a deposit checkout session with the EFT PAY payment gateway. Requires amount, currency, payment method, user ID, and email. Returns a checkout ID and payment brand. ```typescript // POST /api/payment/create-session const response = await fetch('/api/payment/create-session', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ amount: 50.00, currency: 'USD', paymentMethod: 'card-usd', // or 'zimswitch-usd', 'zimswitch-zwg', 'ecocash-usd', 'ecocash-zwg' userId: 'ks72xyybrjx4pt5qe4wbsanzf17bg56z', email: 'user@example.com' }) }); const data = await response.json(); // Response: { checkoutId: '8AC7A4CA87EB6BE001234', paymentBrand: 'VISA MASTER' } ``` -------------------------------- ### Initialize Three.js Scene and Add Objects Source: https://github.com/britelink/aurum/blob/main/app/(demo)/components/Bird.md Sets up the Three.js scene, adds a bird model, creates a shore with specified geometry and material, and positions it within the scene. This is a foundational step for rendering the 3D environment. ```javascript scene.add(bird); birdModelRef.current = bird; // Create shore on the right side const shoreGeometry = new THREE.BoxGeometry(3, 0.5, 10); const shoreMaterial = new THREE.MeshLambertMaterial({ color: 0xc2b280 }); const shore = new THREE.Mesh(shoreGeometry, shoreMaterial);shore.position.set(8, -0.75, 0); scene.add(shore); ``` -------------------------------- ### Payment Methods Configuration (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt TypeScript constants defining payment gateway credentials, including entity IDs, payment brands, and test modes for different payment methods like Zimswitch and Ecocash. ```typescript // lib/payment/constants.ts const PAYMENT_CREDENTIALS = { 'zimswitch-usd': { entityId: '8ac9a4c7987eb6be0198c6359a1c1900', paymentBrand: 'PRIVATE_LABEL', testMode: 'EXTERNAL' }, 'zimswitch-zwg': { entityId: '8ac9a4c7987eb6be0198c63e049e1944', paymentBrand: 'PRIVATE_LABEL', testMode: 'EXTERNAL' }, 'card-usd': { entityId: '8ac9a4c7987eb6be0198c63659ef1909', paymentBrand: 'VISA MASTER', testMode: 'INTERNAL' }, 'ecocash-usd': { entityId: '8ac9a4c7987eb6be0198c63659ef1909', paymentBrand: 'PRIVATE_LABEL', testMode: 'INTERNAL' }, 'ecocash-zwg': { entityId: '8ac9a4c7987eb6be0198c63659ef1909', paymentBrand: 'PRIVATE_LABEL', testMode: 'INTERNAL' } }; ``` -------------------------------- ### Place Bet Source: https://context7.com/britelink/aurum/llms.txt Creates a new bet on an open session and updates session volumes. Requires session ID, bet amount, and direction. ```APIDOC ## POST /api/aurum/placeBet ### Description Creates a new bet on an open session and updates session volumes. The bet starts with a 'pending' status. ### Method POST ### Endpoint /api/aurum/placeBet ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **sessionId** (string) - Required - The ID of the session to bet on. - **amount** (number) - Required - The amount to bet. Must be 1 or 2. - **direction** (string) - Required - The direction of the bet ('up' or 'down'). ### Request Example ```json { "sessionId": "k72sess123456789", "amount": 2, "direction": "up" } ``` ### Response #### Success Response (200) - **betId** (string) - The ID of the newly created bet. #### Response Example ```json { "betId": "someBetId123" } ``` ``` -------------------------------- ### Prepare Deposit Checkout Session with PaymentService Source: https://context7.com/britelink/aurum/llms.txt Initializes a checkout session for deposits using the PaymentService. This method validates the request, creates a unique transaction ID, and interacts with EFT PAY to prepare the deposit. It automatically selects the correct entity ID and payment brand based on the provided details. ```typescript import { PaymentService } from '@/lib/payment/service'; const paymentService = new PaymentService(); const checkoutResponse = await paymentService.prepareDeposit({ amount: 50.00, currency: 'USD', paymentMethod: 'card-usd', userId: 'ks72xyybrjx4pt5qe4wbsanzf17bg56z', email: 'user@example.com' }); // Response: // { // id: '8AC7A4CA87EB6BE001234', // ndc: 'EFT_PAY_SESSION_NDC', // timestamp: '2024-01-01T12:00:00Z', // result: { // code: '000.200.100', // description: 'successfully created checkout' // }, // paymentBrand: 'VISA MASTER' // } // Automatically selects correct entity ID and payment brand // Validates request before submission // Creates unique merchantTransactionId: {userId}-{timestamp} ``` -------------------------------- ### Initiate Withdrawal Request (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Initiates a withdrawal request, deducting funds from the user's balance. Requires amount, payment method, and user ID. Includes validation for minimum/maximum withdrawal amounts and sufficient balance. ```typescript // POST /api/withdrawal/create const response = await fetch('/api/withdrawal/create', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ amount: 100.00, paymentMethod: 'card-usd', userId: 'ks72xyybrjx4pt5qe4wbsanzf17bg56z' }) }); const data = await response.json(); // Response: { // success: true, // checkoutId: '8AC7A4CA87EB6BE001234', // transactionId: 'k72xyy123456789', // message: 'Withdrawal initiated successfully' // } // Validation: // - Minimum withdrawal: $10 // - Maximum withdrawal: $1000 // - Sufficient balance required ``` -------------------------------- ### JavaScript Betting Round Timer Logic Source: https://github.com/britelink/aurum/blob/main/app/(demo)/components/Bird.md Implements a timer for betting rounds. It manages countdowns for when betting is open and when it's closed, initiating the next betting round or starting the flight sequence accordingly. The timer interval is set to one second, and it resets after each action. This logic is designed for a React environment using the useEffect hook. ```javascript // Betting round timer useEffect(() => { if (bettingOpen) { const timer = setInterval(() => { setCountdown((prev) => { if (prev <= 1) { clearInterval(timer); startBettingRound(); return 10; // Reset to 10 seconds for next round } return prev - 1; }); }, 1000); return () => clearInterval(timer); } else { // If betting is closed, count down to the result const timer = setInterval(() => { setCountdown((prev) => { if (prev <= 1) { clearInterval(timer); if (!isRacing) { startFlight(); // Start the flight } return 10; // Reset to 10 seconds for next round } return prev - 1; }); }, 1000); return () => clearInterval(timer); } }, [bettingOpen, isRacing]); // Start a new betting round const startBettingRound = () => { setBettingOpen(false); setCountdown(10); }; ``` -------------------------------- ### Session Manager Loop with Convex Source: https://context7.com/britelink/aurum/llms.txt An automated background process using Convex's useAction hook to manage the betting session lifecycle. Triggered by a cron job every second, it handles automatic state transitions: moving sessions from 'open' to 'processing' when the betting period ends, then to 'processed' after the processing period, and initiating results processing. If no session exists, it creates the first one. It also schedules itself to run again after one second. ```typescript import { useAction } from "convex/react"; import { api } from "@/convex/_generated/api"; // Triggered by cron job every second const sessionManagerLoop = useAction(api.session.sessionManagerLoop); // Automatic state transitions: // 1. If session 'open' and past endTime -> set to 'processing' // 2. If session 'processing' and past processingEndTime -> process results // 3. If no session exists -> create first session // 4. Schedules itself to run again in 1 second // Started by: convex/crons.ts scheduled action ``` -------------------------------- ### Handle Window Resize for 3D Canvas Source: https://github.com/britelink/aurum/blob/main/app/(demo)/components/Bird.md Sets up an event listener for window resize events. When the window is resized, it updates the Three.js renderer's size and the camera's aspect ratio to match the container's dimensions, ensuring the 3D scene scales correctly. ```javascript useEffect(() => { const handleResize = () => { if ( !threeContainerRef.current || !rendererRef.current || !cameraRef.current ) return; const width = threeContainerRef.current.clientWidth; const height = threeContainerRef.current.clientHeight; rendererRef.current.setSize(width, height); cameraRef.current.aspect = width / height; cameraRef.current.updateProjectionMatrix(); }; window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []); ``` -------------------------------- ### POST /api/withdrawal/create Source: https://context7.com/britelink/aurum/llms.txt Initiates a withdrawal request from a user's account. This endpoint deducts funds from the user's balance and records the withdrawal transaction. ```APIDOC ## POST /api/withdrawal/create ### Description Initiates a withdrawal request with balance deduction. ### Method POST ### Endpoint /api/withdrawal/create ### Parameters #### Request Body - **amount** (number) - Required - The amount to withdraw. Minimum: $10, Maximum: $1000. - **paymentMethod** (string) - Required - The payment method for the withdrawal (e.g., 'card-usd'). - **userId** (string) - Required - The ID of the user initiating the withdrawal. ### Request Example ```json { "amount": 100.00, "paymentMethod": "card-usd", "userId": "ks72xyybrjx4pt5qe4wbsanzf17bg56z" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the withdrawal request was successful. - **checkoutId** (string) - The ID for the checkout session, if applicable. - **transactionId** (string) - The unique identifier for the withdrawal transaction. - **message** (string) - A message confirming the withdrawal initiation. #### Response Example ```json { "success": true, "checkoutId": "8AC7A4CA87EB6BE001234", "transactionId": "k72xyy123456789", "message": "Withdrawal initiated successfully" } ``` ``` -------------------------------- ### Prepare Withdrawal Checkout Session with PaymentService Source: https://context7.com/britelink/aurum/llms.txt Initializes a payout checkout session using the PaymentService for withdrawals via EFT PAY. This function uses the 'PA' payment type for payouts, similar to deposits, and enforces minimum ($10) and maximum ($1000) withdrawal limits. The response structure is identical to that of the deposit preparation. ```typescript import { PaymentService } from '@/lib/payment/service'; const paymentService = new PaymentService(); const checkoutResponse = await paymentService.prepareWithdrawal({ amount: 100.00, currency: 'USD', paymentMethod: 'card-usd', userId: 'ks72xyybrjx4pt5qe4wbsanzf17bg56z' }); // Uses paymentType: 'PA' (payout) instead of 'DB' (debit) // Same response structure as deposit // Minimum: $10, Maximum: $1000 (enforced by route handler) ``` -------------------------------- ### POST /api/payment/process Source: https://context7.com/britelink/aurum/llms.txt Handles payment verification and balance updates after a payment is completed via the EFT PAY redirect. This endpoint is automatically called by the EFT PAY system. ```APIDOC ## POST /api/payment/process ### Description Handles payment verification and balance update after EFT PAY payment completion. This endpoint is automatically called by EFT PAY upon redirect. ### Method POST ### Endpoint /api/payment/process ### Parameters #### Query Parameters - **resourcePath** (string) - Required - The path provided by EFT PAY for payment verification. ### Request Example (This endpoint is called by EFT PAY redirect, typically with query parameters) `/api/payment/process?resourcePath=/v1/checkouts/{id}/payment` ### Response #### Success Response (200) Typically redirects to '/play' on successful verification and balance update. #### Response Example (No direct JSON response, usually a redirect) Redirect to: `/play` ``` -------------------------------- ### Generate Random Clouds and Wind Strength Source: https://github.com/britelink/aurum/blob/main/app/(demo)/components/Bird.md Initializes random cloud data (position, size, opacity) and sets a random wind strength value. This effect is applied once when the component mounts to provide varied environmental conditions for each race. ```javascript useEffect(() => { // Generate random clouds const newClouds = []; for (let i = 0; i < 5; i++) { newClouds.push({ left: Math.random() * 80 + 10, top: Math.random() * 40 + 5, size: Math.random() * 30 + 30, opacity: Math.random() * 0.4 + 0.1, }); } setClouds(newClouds); // Random wind strength setWindStrength((Math.random() * 2 - 1) * 0.5); }, []); ``` -------------------------------- ### Admin Deposit Funds to Any User Account (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Allows an administrator to directly credit any user's account. This function bypasses standard authentication checks and is intended for payment processing or administrative adjustments. It requires the target userId, amount, and payment method. ```typescript import { useMutation } from "convex/react"; import { api } from "@/convex/_generated/api"; const adminDeposit = useMutation(api.aurum.adminDepositFunds); // Admin adds funds to user account const transactionId = await adminDeposit({ userId: 'ks72xyybrjx4pt5qe4wbsanzf17bg56z', amount: 100.00, paymentMethod: 'cash' }); // No authentication check - intended for payment processing ``` -------------------------------- ### Users Table Schema Definition (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Defines the structure for the 'Users' table, which stores user profiles, authentication details, and financial balances. It includes fields for name, email, phone, roles, and various balance types. ```typescript // Schema definition { name: string, image?: string, email?: string, emailVerificationTime?: number, phone?: string, phoneVerificationTime?: number, isAnonymous?: boolean, balance?: number, // Real money balance walletBalance?: number, // In-game currency balance ecoUsdAddress?: string, role?: 'player' | 'admin' | 'agent', referralCode?: string } // Indexes: email ``` -------------------------------- ### Admin Deposit Funds Source: https://context7.com/britelink/aurum/llms.txt Admin function to credit any user's account directly. Requires user ID, amount, and payment method. ```APIDOC ## POST /api/aurum/adminDepositFunds ### Description Admin function to credit any user's account directly. This endpoint does not perform authentication checks. ### Method POST ### Endpoint /api/aurum/adminDepositFunds ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **userId** (string) - Required - The ID of the user whose account will be credited. - **amount** (number) - Required - The amount to deposit. - **paymentMethod** (string) - Required - The payment method used (e.g., 'cash'). ### Request Example ```json { "userId": "ks72xyybrjx4pt5qe4wbsanzf17bg56z", "amount": 100.00, "paymentMethod": "cash" } ``` ### Response #### Success Response (200) - **transactionId** (string) - The ID of the completed transaction. #### Response Example ```json { "transactionId": "someAdminTransactionId789" } ``` ``` -------------------------------- ### Bets Table Schema Definition (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Defines the schema for the 'Bets' table, recording individual user bets within specific sessions. It includes user and session IDs, bet amount, direction, status, and payout information. ```typescript // Schema definition { userId: Id<'users'>, sessionId: Id<'sessions'>, amount: 1 | 2, // Only 1 or 2 allowed direction: 'up' | 'down', status: 'pending' | 'won' | 'lost', payout?: number, // Total return if won sessionOutcome?: 'won' | 'lost' | 'void' } // Indexes: by_session ``` -------------------------------- ### Add Funds to House Account (TypeScript) Source: https://context7.com/britelink/aurum/llms.txt Adds funds to the house account for liquidity management. Requires the amount to be credited. Uses a fixed house account ID. ```typescript // POST /api/house/credit const response = await fetch('/api/house/credit', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ amount: 500.00 }) }); const data = await response.json(); // Response: { success: true } // Fixed house account: ks72m74heawkx1p7n524fbtnt97mj6y1 ``` -------------------------------- ### POST /api/house/credit Source: https://context7.com/britelink/aurum/llms.txt Adds funds to the house account. This is used for liquidity management by administrators. ```APIDOC ## POST /api/house/credit ### Description Adds funds to the house account for liquidity management. ### Method POST ### Endpoint /api/house/credit ### Parameters #### Request Body - **amount** (number) - Required - The amount to credit to the house account. ### Request Example ```json { "amount": 500.00 } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ```