Skip to content

Latest commit

Β 

History

History
463 lines (351 loc) Β· 12.5 KB

File metadata and controls

463 lines (351 loc) Β· 12.5 KB

πŸ”„ POLLUXCHESS ROLLBACK & CURRENT STATE - February 4, 2026

πŸ“ CURRENT STATUS

Last Working Commit: 6984f2f (February 3, 2026)
Branch: main
Deployment: Vercel (xmerch-polluxchess.vercel.app)
Network: Xahau Testnet (NetworkID 21337)


🎯 WHAT WORKS NOW

βœ… Desktop Login Flow

  1. User clicks "Connect with Xaman"
  2. QR popup opens
  3. User scans with Xaman mobile app
  4. Signs in successfully
  5. Popup closes
  6. User logged in, playerID saved to localStorage

Status: βœ… FULLY WORKING

βœ… Desktop Payment Processing

  1. User selects tournament fee (e.g., 10 XAH)
  2. Clicks Submit
  3. Xaman QR popup opens
  4. User scans and signs payment
  5. WebSocket detects tesSUCCESS
  6. Webhook fires successfully
  7. Player added to tournament_players table in Supabase

Status: βœ… PAYMENT PROCESSING WORKS

βœ… Network Configuration

  • Testnet NetworkID: 21337 βœ…
  • Mainnet NetworkID: 21338 βœ…
  • Hook Address (Testnet): rpbvh5LmrV17BVCu5fAc1ybKev1pFa8evh βœ…

Status: βœ… NETWORK IDS CORRECT


❌ CRITICAL BUG - NOT WORKING

πŸ› PROBLEM: Cannot Enter Waiting Room After Payment

Symptom:

  • Payment succeeds
  • Webhook adds player to tournament
  • Join API returns 409 "Player already in tournament" with tournamentId
  • BUT: Page does NOT redirect to waiting room
  • User stuck on /chess page
  • If manually navigating to waiting room: "Security error: unable to verify wallet"

Console Logs Show:

πŸ“‘ Join API response status: 409
⚠️ Player already in tournament: 9fc71e42-4f12-4627-9a3b-773ff4bae6bb
[No redirect happens - page stays on /chess]

Expected Behavior: Should redirect to: /waiting-room?tournamentId=9fc71e42-4f12-4627-9a3b-773ff4bae6bb&uuid=6f2b07c2-e12c-4aa8-bff7-61ca06e38e93

Root Cause: The 409 handler in the desktop payment flow is logging the message but NOT executing the redirect.


πŸ“ KEY FILES & THEIR STATE

Frontend - Payment Flow

File: app/chess/page.tsx (1400+ lines)

Desktop Payment Handler (around line 1100-1200):

// After payment succeeds via WebSocket:
console.log("βœ… Payment confirmed ON LEDGER - now joining tournament...")

const joinRes = await fetch('/api/tournaments/join', {...})
console.log("πŸ“‘ Join API response status:", joinRes.status)

// βœ… Handle 409 "already in tournament" BEFORE checking ok status
if (joinRes.status === 409) {
  const joinData = await joinRes.json()
  if (joinData.tournamentId) {
    console.log("⚠️ Player already in tournament:", joinData.tournamentId)
    alert("You're already in a tournament!\n\nRedirecting...")
    // 🚨 THIS REDIRECT IS NOT EXECUTING:
    window.location.href = `/waiting-room?tournamentId=${joinData.tournamentId}`
    return
  }
}

Status: Code looks correct but redirect fails. Unknown blocker.


Supabase Edge Functions

1. xaman-signinPayload/index.ts

  • NetworkID: βœ… Correct (testnet=21337, mainnet=21338)
  • Status: βœ… WORKING

2. xaman-createPayload/index.ts

  • NetworkID: βœ… Correct (testnet=21337, mainnet=21338)
  • Return URL: βœ… Includes web + app properties
  • Status: βœ… WORKING

3. xaman-webhook/index.ts

  • Processes payments successfully
  • Adds players to tournament_players table
  • Status: βœ… WORKING

4. xaman-getPayload/index.ts

  • Returns full payload data for verification
  • Status: βœ… WORKING (but not being used effectively)

Waiting Room Verification

File: app/waiting-room/page.tsx

Current Verification Logic:

async function verifyWallet() {
  // 1. Checks tournament_players table (5 retries, 800ms delay)
  // 2. Falls back to Xaman payload status if uuid provided
  // 3. If both fail: "Security error: unable to verify wallet"
}

Problem:

  • User never reaches waiting room (redirect blocked)
  • If manually navigating, verification fails because:
    • No uuid in URL (wasn't passed in redirect)
    • DB query racing (might be too fast)

Status: ❌ NOT WORKING due to upstream redirect issue


πŸ—„οΈ DATABASE STATE

Supabase Tables

tournament_players

  • Contains stuck entries with status="joined"
  • Player: rhAaDqi8tqd2f4HJbAwqUHs6VdQrktppmh
  • Tournament ID: 9fc71e42-4f12-4627-9a3b-773ff4bae6bb

tournaments

  • Status: "waiting"
  • Tournament size: 2
  • Entry fee: 10 XAH

Problem: Data is correct in database, but frontend can't access waiting room.


πŸ”§ APPLIED FIXES (From Previous Session)

Fix #1-2: Network IDs βœ…

  • Fixed in both Supabase functions
  • Deployed to Supabase

Fix #3: Callback Syntax βœ…

// Before: addDebug`URL: ...`)
// After:  addDebug(`URL: ...`)

Fix #4: Desktop Payment Delay βœ…

  • Increased from 1000ms to 2000ms
  • Added "Waiting for database to commit..." log

Fix #5: Mobile Redirect Timing βœ…

  • Removed unreachable setTimeout after redirect

Fix #6: Payment Return URL βœ…

  • Now defaults to /chess instead of /waiting-room
  • Includes both web + app properties

Fix #7: Created Missing API Route βœ…

  • /app/api/auth/xaman/get-payload/xahau-payload/route.ts

Fix #8: Line 466 Syntax Error βœ…

// Before: reject(new Error`...`)
// After:  throw new Error(`...`)

Fix #9: GoTrueClient Warning βœ…

  • Replaced direct createClient() calls with singleton getSupabaseClient()
  • Updated: app/chess/page.tsx, lib/auth/session-manager.ts

Fix #10: Mobile 409 Handling βœ…

  • Added 409 check before !ok check in both mobile join blocks

Fix #11: Waiting Room UUID Verification ⚠️ ATTEMPTED

  • Added uuid parameter to waiting-room redirects
  • Added Xaman payload status verification fallback
  • Status: Not working because redirect never happens

🚨 THE CORE ISSUE

The 409 redirect is being blocked or ignored.

Possible causes:

  1. JavaScript execution blocked by alert()?
  2. React state update preventing navigation?
  3. Event handler not completing?
  4. Window.location.href being overridden?
  5. Page remounting after alert clears?

Need to investigate:

if (joinRes.status === 409) {
  const joinData = await joinRes.json()
  if (joinData.tournamentId) {
    console.log("⚠️ Player already in tournament:", joinData.tournamentId)
    alert("You're already in a tournament!\n\nRedirecting...")  // ← Does this block?
    window.location.href = `/waiting-room?tournamentId=${joinData.tournamentId}`  // ← Never executes
    return
  }
}

πŸ”¬ DEBUGGING STEPS FOR NEXT AI

Step 1: Check if redirect code is reached

Add more logging:

if (joinRes.status === 409) {
  console.log("πŸ” [DEBUG] Entered 409 handler")
  const joinData = await joinRes.json()
  console.log("πŸ” [DEBUG] Join data:", joinData)
  if (joinData.tournamentId) {
    console.log("πŸ” [DEBUG] About to show alert")
    alert("You're already in a tournament!\n\nRedirecting...")
    console.log("πŸ” [DEBUG] Alert dismissed, about to redirect")
    const redirectUrl = `/waiting-room?tournamentId=${joinData.tournamentId}`
    console.log("πŸ” [DEBUG] Redirect URL:", redirectUrl)
    window.location.href = redirectUrl
    console.log("πŸ” [DEBUG] Redirect called")
    return
  }
}

Step 2: Try alternative redirect methods

// Option A: Remove alert, try immediate redirect
window.location.href = `/waiting-room?tournamentId=${joinData.tournamentId}`

// Option B: Use replace instead of href
window.location.replace(`/waiting-room?tournamentId=${joinData.tournamentId}`)

// Option C: Use Next.js router
// (would need to pass router instance to function)
router.push(`/waiting-room?tournamentId=${joinData.tournamentId}`)

Step 3: Check for React state issues

Look for:

  • Any state updates after the redirect call
  • useEffect hooks that might remount component
  • Error boundaries catching navigation

Step 4: Simplify 409 handler

Remove alert completely:

if (joinRes.status === 409) {
  const joinData = await joinRes.json()
  if (joinData.tournamentId) {
    console.log("βœ… Tournament found, redirecting immediately...")
    window.location.replace(`/waiting-room?tournamentId=${joinData.tournamentId}&uuid=${paymentUuid}`)
    return
  }
}

πŸ“¦ ROLLBACK PROCEDURE

If new AI breaks things, rollback to this commit:

# Rollback frontend code
git checkout 6984f2f

# Verify commit
git log --oneline -1

# Should show:
# 6984f2f fix: correct Error constructor syntax on line 466

# Rebuild
pnpm build

# Deploy
git push origin main --force  # Only if needed

Supabase Functions Status: Already deployed with correct Network IDs. No rollback needed unless you modify them.


πŸ§ͺ TESTING CHECKLIST

Before considering any fix "working":

Desktop Payment Flow:

  • Login works
  • Payment QR opens
  • Sign in Xaman
  • Payment succeeds (check console: "tesSUCCESS")
  • Join API called (check console: "Sending join request")
  • CRITICAL: Page redirects to /waiting-room?tournamentId=...
  • Waiting room loads without security error
  • Player sees "Waiting for opponent" message

Database Verification:

  • Check tournament_players - player row exists with status="joined"
  • Check tournaments - tournament exists with status="waiting"
  • Check hook_logs - payment logged with correct amount

URL Verification:

  • Waiting room URL includes tournamentId parameter
  • Waiting room URL includes uuid parameter (optional but helpful)

πŸ› οΈ ENVIRONMENT VARIABLES

Frontend (.env.local)

NEXT_PUBLIC_BASE_URL=https://xmerch-polluxchess.vercel.app
NEXT_PUBLIC_SUPABASE_URL=https://kijlhftinrufbuigostz.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGc...
NEXT_PUBLIC_XAHAU_NETWORK_ID=21337  # Testnet
NEXT_PUBLIC_HOOK_ADDRESS_MAINNET=rYOUR_MAINNET_HOOK

Supabase Secrets

XUMM_API_KEY=your-xaman-api-key
XUMM_API_SECRET=your-xaman-api-secret
XAH_DESTINATION_TESTNET=rpbvh5LmrV17BVCu5fAc1ybKev1pFa8evh
XAH_DESTINATION_MAINNET=rYOUR_MAINNET_HOOK
SB_URL=https://kijlhftinrufbuigostz.supabase.co
SB_SERVICE_ROLE_KEY=your-service-role-key
NEXT_PUBLIC_SITE_URL=https://xmerch-polluxchess.vercel.app

πŸ“ SQL CLEANUP (Before Fresh Testing)

-- Clean test data
DELETE FROM tournament_players 
WHERE player_address = 'rhAaDqi8tqd2f4HJbAwqUHs6VdQrktppmh';

DELETE FROM tournaments 
WHERE id IN (
  SELECT DISTINCT tournament_id 
  FROM tournament_players 
  WHERE player_address = 'rhAaDqi8tqd2f4HJbAwqUHs6VdQrktppmh'
);

-- Verify cleanup
SELECT * FROM tournament_players WHERE player_address = 'rhAaDqi8tqd2f4HJbAwqUHs6VdQrktppmh';
-- Should return 0 rows

🎯 GOAL FOR NEXT AI

Single objective: Fix the 409 redirect so users can enter the waiting room after successful payment.

Success criteria:

  1. Payment succeeds βœ… (already works)
  2. Join API returns 409 βœ… (already works)
  3. Page redirects to waiting room ❌ (BROKEN - FIX THIS)
  4. Waiting room verification succeeds ⚠️ (blocked by #3)

Focus area: app/chess/page.tsx lines ~1150-1170 (desktop payment 409 handler)

Do NOT:

  • Change Network IDs (already correct)
  • Modify webhook logic (working fine)
  • Refactor unrelated code
  • Change database schema

DO:

  • Debug why window.location.href isn't executing
  • Test alternative redirect methods
  • Add comprehensive logging
  • Remove alert if it's blocking navigation

πŸ“š REFERENCE DOCUMENTATION

Previous README: READMExamandocs.md
Fix Instructions: CLINE_FIX_INSTRUCTIONS.md
Xaman Integration: All 50+ docs read and applied

Key Xaman Patterns Used:

  • WebSocket for transaction monitoring βœ…
  • Return URLs for mobile redirect βœ…
  • NetworkID in payload βœ…
  • Webhook for server-side verification βœ…

πŸš€ QUICK START FOR NEW AI

  1. Read this file completely
  2. Read READMExamandocs.md for architecture context
  3. Focus on the 409 redirect bug (lines 1150-1170 in app/chess/page.tsx)
  4. Add debug logging first - don't change logic yet
  5. Test on desktop (easier to debug than mobile)
  6. Verify redirect happens before touching waiting room logic

Last Updated: February 4, 2026
Status: Payment works, redirect broken, waiting for fix
Priority: HIGH - blocking users from playing games


πŸ†˜ IF EVERYTHING BREAKS

# Nuclear option - full rollback
git reset --hard 6984f2f
git clean -fd
pnpm install
pnpm build

# Redeploy Supabase functions (just in case)
cd supabase/functions
supabase functions deploy xaman-signinPayload
supabase functions deploy xaman-createPayload
supabase functions deploy xaman-webhook

This should restore to the "payment works but no redirect" state.

END OF ROLLBACK README