Trade SOL on pump.fun token graduation outcomes. Predict which tokens will graduate to PumpSwap within 1 hour.
Network: Solana mainnet-betaAPI:https://pumpbet-mainnet.up.railway.appWebSocket:wss://pumpbet-mainnet.up.railway.appProgram ID:3mNbBV3Xc3rNJ4E87pSFzW7VhUZySHQDQVyd4MP2VFG6IDL:https://pumpmarket.fun/skill.jsonTreasury:4iFYGzxKGH2SAeVaR5AxPiCfLCSQD9fdPK8tsDBbmx3fNaming: Brand is PumpMarket. On-chain program name is pumpbets (legacy). API host pumpbet-* retains the original name.
This is mainnet. Bets use real SOL. The program is deployed (100 markets, 290 bets on-chain), the treasury is funded (9.29 SOL), and the keeper authority is operational (0.12 SOL). All addresses, API URLs, and code examples target Solana mainnet-beta.
PumpMarket is a parimutuel prediction market for pump.fun token graduations on Solana. Users bet SOL on whether a pump.fun token will "graduate" (complete its bonding curve and migrate to PumpSwap DEX) within approximately 1 hour.
How it works:
A user creates a market for a pump.fun token, choosing YES or NO and staking SOL
Other users bet YES (token will graduate) or NO (it won't) within the ~1-hour window
An automated keeper resolves the market based on on-chain data
Winners split the total pool proportionally (minus 4.5% fees)
Market outcomes:
YES wins — token graduated (bonding curve hit 100%, migrated to PumpSwap)
NO wins — token did not graduate within the deadline (timeout or rug)
VOIDED — one-sided pool (all bets on the same side) or oracle void — full refunds, zero fees
2. First-Run Setup
Before an agent can trade, it needs:
Wallet
A Solana wallet with a keypair (e.g., Keypair.fromSecretKey(...))
Connected to mainnet-beta RPC (e.g., https://api.mainnet-beta.solana.com or a Helius/Quicknode endpoint)
Funded with SOL for bets and transaction fees
RPC Endpoint
The public https://api.mainnet-beta.solana.com is rate-limited. For production agents, use a dedicated RPC provider (Helius, Quicknode, Triton, etc.).
Terms Acceptance (Required Once)
PumpMarket requires users to accept terms before their activity is fully tracked. This is a one-time operation:
Get the message to sign:text
GET https://pumpbet-mainnet.up.railway.app/api/users/{wallet}/terms/message
Response:
json
{ "message": "PumpMarket Terms of Service\nI agree to the terms at https://pumpmarket.fun/terms\nWallet: ...\nTimestamp: ...", "timestamp": 1772413074485, "wallet": "..." }
Sign the message string with your wallet and encode as base58:typescript
import nacl from 'tweetnacl';
import bs58 from 'bs58';
const sig = nacl.sign.detached(new TextEncoder().encode(message), keypair.secretKey);
const signatureBase58 = bs58.encode(sig);
Submit the signed acceptance:text
POST https://pumpbet-mainnet.up.railway.app/api/users/{wallet}/terms
Body: { "signature": "<base58 signature>", "timestamp": <timestamp from step 1> }
Verify acceptance:text
GET https://pumpbet-mainnet.up.railway.app/api/users/{wallet}/terms
→ { "wallet": "...", "termsAccepted": true }
Dependencies
bash
npm install @coral-xyz/anchor @solana/web3.js
The @pumpmarket/sdk npm package is not published (internal monorepo only). All code examples in this document use raw @coral-xyz/anchor and @solana/web3.js. You need the program IDL, which is provided in Section 6.
Keypair Security
Never hardcode private keys in source code or commit them to repositories.
import bs58 from 'bs58';
const keypair = Keypair.fromSecretKey(bs58.decode(process.env.PRIVATE_KEY!));
Best practices:
Store keys in environment variables or encrypted keyfiles — never in source code
Set keyfile permissions to 600 (chmod 600 keyfile.json)
Add *.json keypair paths to .gitignore
Use a dedicated betting wallet with limited funds — not your main wallet
For production agents, consider a secrets manager (e.g. AWS Secrets Manager, Doppler)
Testing Without Real SOL
This skill targets mainnet-beta where bets use real SOL. To test transaction construction without spending:
Dry-run simulation: See Appendix: Dry-Run Simulation — builds and simulates transactions on-chain without submitting them.
Devnet: PumpMarket has a devnet deployment (beta.pumpmarket.fun) used for internal testing. The devnet program ID is 3mNbBV3Xc3rNJ4E87pSFzW7VhUZySHQDQVyd4MP2VFG6 (same binary, different state). Devnet is not guaranteed to be stable or have active markets.
Start small: If testing on mainnet, budget at least 0.2 SOL per bet (0.1 SOL bet + 0.1 SOL market creation fee). Bets below 0.1 SOL are likely unprofitable after fees.
3. On-Chain Parameters
All values verified against the Anchor smart contract at packages/contracts/programs/pumpbets/src/constants.rs.
Parameter
Value
Lamports
On-Chain Enforcement
Market Creation Fee
0.1 SOL
100,000,000
createMarket — transferred to treasury
Min Bet
0.01 SOL
10,000,000
createMarket + placeBet
Max Bet
10 SOL
10,000,000,000
createMarket + placeBet
Platform Fee
3.5%
350 BPS
resolveMarket — from total pool to treasury
Creator Fee
1.0%
100 BPS
resolveMarket — from total pool to creator
Total Fee
4.5%
450 BPS
Combined (platform + creator)
Market Duration
~1 hour
9,000 slots
createMarket — resolution_slot = current + 9000
Max Bonding Progress
< 95
—
Strict < check: 0–94 accepted, 95+ rejected
Rug Threshold
$4,500 USD
—
Off-chain keeper checks (constants defined on-chain)
Rug Duration
~5 minutes
750 slots
Must sustain below threshold continuously
Claim Period
~7 days
1,512,000 slots
Vault can be closed (rent reclaimed) after this
Emergency Delay
~1 day
216,000 slots
Only treasury can emergency withdraw after this
Mainnet Activity (Indexer snapshot — 2026-03-02)
Metric
Value
Program accounts
490 (100 markets, 290 bets, 100 vaults)
Markets resolved
53 (47 voided)
Total volume
76.14 SOL
Treasury balance
9.29 SOL
Keeper balance
0.12 SOL
These values are from PumpMarket's internal indexer at the timestamp above and may differ from current on-chain state.
Verify Mainnet Deployment
bash
# Verify API is healthy
curl -s https://pumpbet-mainnet.up.railway.app/api/health | python3 -m json.tool
# Verify program on-chain (requires solana CLI)
solana program show 3mNbBV3Xc3rNJ4E87pSFzW7VhUZySHQDQVyd4MP2VFG6 --url mainnet-beta
# Verify treasury is funded
solana balance 4iFYGzxKGH2SAeVaR5AxPiCfLCSQD9fdPK8tsDBbmx3f --url mainnet-beta
# Verify active markets exist
curl -s https://pumpbet-mainnet.up.railway.app/api/stats | python3 -m json.tool
Reproduce Account Counts via RPC
Estimate on-chain account counts by querying program-owned accounts by data size. Account sizes: BettingMarket = 123 bytes, UserBet = 91 bytes, Vault = 41 bytes.
Some public RPCs rate-limit getProgramAccounts. Use a paid RPC if needed.
All endpoints are public with no authentication — no API keys, no wallet signatures, no headers required. The only exception is POST /api/users/:wallet/terms which requires a wallet signature (one-time terms acceptance).
{ "valid": false, "bondingProgress": 97, "reason": "Token is at 97% bonding progress..." }
Markets
Method
Endpoint
Description
GET
/api/markets
Active (unresolved) markets only
GET
/api/markets/resolved
Resolved/voided/pending markets (filterable)
GET
/api/markets/graduated
Alias for resolved with filter=resolved
GET
/api/markets/:address
Single market — full details, odds, delta
GET
/api/markets/:address/bets
Paginated bets for a market
GET
/api/markets/:address/can-bet
Check if market accepts bets
POST
/api/markets/:address/check-graduation
Trigger manual graduation check
GET
/api/markets/by-creator/:wallet
Markets created by a wallet
GET /api/markets returns active/unresolved markets only. No pagination — returns all active markets at once. No status filter. For historical data, use /api/markets/resolved.
GET /api/markets Response — verified from source (routes/markets.ts:119-147):
Note: The active list uses address (same as single market). creator is truncated. Includes live bondingProgress, marketCapUsd, priceUsd in the token object, and computed odds/delta. No nextCursor — all active markets returned in one response.
Type caveat:bondingProgress inside the token object on market endpoints is a string (e.g. "45.20"). On /api/tokens it's a number. Always parseFloat() before arithmetic (e.g. delta = parseFloat(token.bondingProgress) - yesImplied).
GET /api/markets/resolved Response — verified live:
Beware: The resolved list uses marketAddress (not address like the active list and single market endpoints). It also uses creatorWallet instead of creator. No odds/delta fields — those are only on active markets and the single market endpoint.
GET /api/markets/resolved Query Parameters:
Param
Values
Default
filter
all, resolved, pending, voided
all
cursor
string
—
limit
1–100
20
includeHolders
true
—
Single Market Response (/api/markets/:address) — verified live:
Note: The single market endpoint uses address (not marketAddress), and odds uses yes/no (decimal odds, not yesOdds/noOdds). Includes a summary field with bet counts. Full wallet addresses only appear here — list endpoints truncate to "Xxxx...xxxx".
GET /api/markets/:address/can-bet Response — verified live:
Important:totalVolume and totalProfit are lamport strings (not SOL floats). Divide by 1e9 to get SOL. This differs from leaderboard endpoints which return SOL floats.
GET /api/users/:wallet/bets Response — verified live:
Sync bet from chain to DB (optional — background service catches up)
POST
/api/bets/sync-market
Sync all bets for a market (optional)
POST
/api/bets/sync-user
Sync all bets for a user (optional)
POST
/api/bets/claim/:betAddress
Record on-chain claim in DB (optional)
There is no GET /api/bets list endpoint. Use /api/users/:wallet/bets or /api/markets/:address/bets.
All sync/claim POST endpoints are optional DB convenience calls. Bets exist on-chain regardless. A background sync service runs continuously and will pick up unsynced bets within minutes. Calling sync immediately after a transaction makes the bet visible in the API/UI sooner.
POST /api/bets/sync:{ "betAddress": "<on-chain bet PDA>" } — returns 400 if betAddress missing
POST /api/bets/sync-market:{ "marketAddress": "...", "userWallet": "<optional>" }POST /api/bets/sync-user:{ "userWallet": "...", "fullSync": false } — returns { "success": true, "synced": N, "skipped": N, "total": N }POST /api/bets/claim/:betAddress:{ "signature": "<tx sig>", "amount": <lamports>, "userWallet": "..." }
GET /api/bets/:betAddress Response — verified live:
WebSocket URLs use the same host as the API, with wss:// protocol.
Path
URL
Purpose
/prices
wss://pumpbet-mainnet.up.railway.app/prices
Real-time token price updates
/live-trades
wss://pumpbet-mainnet.up.railway.app/live-trades
Live $1000+ pump.fun trades
/user-events
wss://pumpbet-mainnet.up.railway.app/user-events
User-specific bet/market notifications
/activity
wss://pumpbet-mainnet.up.railway.app/activity
Platform-wide activity stream
Ping/Pong (All Endpoints)
Server sends { "type": "ping" } every 30 seconds. You must respond with { "type": "pong" } or the connection will be dropped. Use text-frame JSON pings — Railway's proxy does not support binary WebSocket ping frames.
Reconnection
Use exponential backoff: base 3s delay, 1.5x multiplier, max 10 attempts.
Stateless agents: If your agent cannot maintain persistent connections between turns, prefer polling GET /api/markets and GET /api/tokens on a 30-second interval instead of WebSockets. The polling approach misses real-time graduation events but is simpler for request-response agent architectures.
/prices — Live Price Stream
On connect: Receives { "type": "connected", "timestamp": "..." } followed by the full price cache.
A valid wallet address (32–44 chars) is sufficient — no cryptographic signature is required. This means anyone who knows your wallet address can subscribe to your events. Do not treat this channel as private or access-controlled. All bet and market data is on-chain and publicly observable regardless.
Since @pumpmarket/sdk is not published to npm, agents must construct transactions using @coral-xyz/anchor and @solana/web3.js directly.
Constants
typescript
import { PublicKey } from '@solana/web3.js';
import { BN } from '@coral-xyz/anchor';
const PROGRAM_ID = new PublicKey('3mNbBV3Xc3rNJ4E87pSFzW7VhUZySHQDQVyd4MP2VFG6');
const TREASURY = new PublicKey('4iFYGzxKGH2SAeVaR5AxPiCfLCSQD9fdPK8tsDBbmx3f');
const LAMPORTS_PER_SOL = 1_000_000_000;
const MIN_BET_LAMPORTS = 10_000_000; // 0.01 SOL
const MAX_BET_LAMPORTS = 10_000_000_000; // 10 SOL
const CREATION_FEE_LAMPORTS = 100_000_000; // 0.1 SOL
Deployment constants (single source of truth).PROGRAM_ID and TREASURY above MUST match the on-chain program deployment. If you switch environments (devnet/mainnet), update them everywhere. If your transaction fails with error 6019 InvalidTreasury, your client is using the wrong treasury address for this deployment.
import { Program, AnchorProvider, web3 } from '@coral-xyz/anchor';
// Fetch IDL: https://pumpmarket.fun/skill.json
// Or direct: https://pumpmarket.fun/pumpbets.json
import IDL from './pumpbets.json';
const connection = new web3.Connection('https://api.mainnet-beta.solana.com', 'confirmed');
const provider = new AnchorProvider(connection, wallet, { commitment: 'confirmed' });
const program = new Program(IDL as any, PROGRAM_ID, provider);
bondingProgress is caller-supplied — there is no on-chain oracle. The value you pass is stored as-is; the program does not independently verify it against the bonding curve. Always call POST /api/tokens/{mint}/validate-bonding immediately before building your transaction and pass the returned integer. This keeps your bet's metadata accurate and avoids betting on stale data (e.g. a token that already graduated).
Integer rule: The on-chain argument is u8 (integer 0–100). Always use the integer from validate-bonding for transactions. Never pass the float/string from market endpoints (e.g. "45.20") as the on-chain argument — it will fail or truncate silently.
Create Market
typescript
const tokenMint = new PublicKey('YOUR_TOKEN_MINT');
const [marketPDA] = findMarketAddress(tokenMint);
const [vaultPDA] = findVaultAddress(marketPDA);
const [creatorBetPDA] = findUserBetAddress(marketPDA, wallet.publicKey, 0);
// Step 1: Get bonding progress from validate-bonding API
const validation = await fetch(
`https://pumpbet-mainnet.up.railway.app/api/tokens/${tokenMint.toBase58()}/validate-bonding`,
{ method: 'POST' }
).then(r => r.json());
if (!validation.valid) throw new Error(`Token not valid: ${validation.reason}`);
// Step 2: Pass bondingProgress integer as the third argument
const tx = await program.methods
.createMarket(
true, // prediction: true=YES, false=NO
new BN(10_000_000), // amount: 0.01 SOL (minimum bet) in lamports
validation.bondingProgress // bonding_progress: integer from validate-bonding response
)
.accounts({
market: marketPDA,
creatorBet: creatorBetPDA,
creator: wallet.publicKey,
vault: vaultPDA,
tokenMint: tokenMint,
treasury: TREASURY,
systemProgram: web3.SystemProgram.programId,
})
.transaction();
// Step 3: Sign and send (see "Sign and Send" helper below)
const sig = await signAndSend(connection, tx, wallet);
Place Bet
typescript
const marketPDA = new PublicKey('MARKET_ADDRESS');
const [vaultPDA] = findVaultAddress(marketPDA);
// Step 1: Get bonding progress from validate-bonding API
const tokenMint = 'TOKEN_MINT_ADDRESS';
const validation = await fetch(
`https://pumpbet-mainnet.up.railway.app/api/tokens/${tokenMint}/validate-bonding`,
{ method: 'POST' }
).then(r => r.json());
if (!validation.valid) throw new Error(`Token not valid: ${validation.reason}`);
// Step 2: Fetch current totalBets from chain for bet index
const marketAccount = await program.account.bettingMarket.fetch(marketPDA);
const betIndex = marketAccount.totalBets;
const [userBetPDA] = findUserBetAddress(marketPDA, wallet.publicKey, betIndex);
// Step 3: Pass bondingProgress integer as the third argument
const tx = await program.methods
.placeBet(
true, // prediction: true=YES, false=NO
new BN(50_000_000), // amount: 0.05 SOL
validation.bondingProgress // bonding_progress: integer from validate-bonding response
)
.accounts({
market: marketPDA,
userBet: userBetPDA,
user: wallet.publicKey,
vault: vaultPDA,
systemProgram: web3.SystemProgram.programId,
})
.transaction();
// Step 4: Sign and send (see "Sign and Send" helper below)
const sig = await signAndSend(connection, tx, wallet);
Claim Payout
typescript
// betAddress and marketAddress from /api/users/{wallet}/claimable/details are base58 strings
const marketPDA = new PublicKey('MARKET_ADDRESS'); // from claimable bet's marketAddress
const userBetPDA = new PublicKey('BET_ADDRESS'); // from claimable bet's betAddress
const [vaultPDA] = findVaultAddress(marketPDA);
const tx = await program.methods
.claimPayout()
.accounts({
market: marketPDA,
userBet: userBetPDA,
user: wallet.publicKey,
vault: vaultPDA,
systemProgram: web3.SystemProgram.programId,
})
.transaction();
const sig = await signAndSend(connection, tx, wallet);
If you use AnchorProvider with a wallet adapter, program.methods.xxx().rpc() handles this automatically. The .transaction() + signAndSend() pattern above is for agents using raw Keypair without a provider wallet adapter.
slotsUntilResolution and estimatedResolutionMinutes only appear in GET /api/markets/resolved for pending status markets.
Pool Sizes (pools.yes, pools.no): Imbalanced pools offer better odds for the minority side. Fully one-sided pools (0 on one side) will be voided.
SOL Reserves (solReserves): Higher = more bonding curve liquidity = healthier token.
Recommended Loop — Event-Driven + Polling Hybrid
For maximum efficiency, use the /prices WebSocket for real-time bonding updates and graduation events, and only poll /api/markets and /api/users/{wallet}/claimable/details on a 30-second interval.
text
On startup:
Connect to wss://pumpbet-mainnet.up.railway.app/prices
Subscribe: { "type": "subscribe_all" }
On each WebSocket price update (real-time):
Track bondingProgress per mint in local state
On graduation event → mark token as graduated, skip future bets
Every 30 seconds (polling):
1. GET /api/markets
→ Get all active markets (includes pools, odds, delta)
2. For each active market:
a. Compare delta, local bondingProgress, time remaining, pool balance
b. If actionable signal:
- POST /api/tokens/{mint}/validate-bonding
- If valid: place bet
3. GET /api/users/{wallet}/claimable/details
→ Claim any unclaimed winnings or refunds
The WebSocket delivers bonding progress and graduation events in real-time (up to 5 updates/token/sec), eliminating the need to poll /api/tokens. The 30-second poll covers market discovery and claims.
Good Citizen Patterns
Cache token metadata (name, symbol, image) — it never changes
Batch price lookups via POST /api/prices/live (up to 50 mints) instead of individual GETs
Use /prices WebSocket for live bonding progress instead of polling /api/tokens
Listen for graduation events on the WebSocket instead of polling validate-bonding
9. Resolution Logic
Markets are resolved by a fully automated keeper service. Agents cannot trigger resolution — only the hardcoded keeper authority wallet can call resolveMarket.
1,000 req/min = ~16.6 req/s. An agent polling 50 markets every 30s uses ~100 req/min — well within limits.
Best Practices
Prefer WebSockets over polling for prices and market updates
Cache immutable data — token name/symbol/image never changes
Batch price requests — POST /api/prices/live with up to 50 mints per call
Always validate bonding before any on-chain transaction — saves wasted tx fees
Handle bet index collisions — refetch totalBets, rebuild PDA, retry
Sync bets after placing — POST /api/bets/sync for immediate API visibility (optional)
Reconnect WebSockets with exponential backoff (3s base, 1.5x, max 10 attempts)
Respond to WebSocket pings — { "type": "pong" } within 30 seconds
External Data Dependencies
PumpMarket relies on three external data providers. All are off-chain — if they fail, the platform degrades but on-chain funds remain safe.
Data
Provider
Used For
Failure Impact
Bonding progress
Bitquery
validate-bonding, market creation
Cannot create markets or validate bets; keeper retries resolution up to 3× at 5-min intervals
Graduation detection
Bitquery
YES resolution trigger
Resolution delayed until Bitquery recovers; markets stay open longer
Token prices
Birdeye
/prices/live, rug detection
Stale prices may delay rug-based NO resolution
Token metadata
Helius
Token names, images, DAS
Display-only — no impact on betting or resolution
What this means for agents:
If validate-bonding returns an error or timeout, do not guess a bondingProgress value — wait and retry
If /prices/live returns stale data, rug detection may lag — factor this into NO-side risk
On-chain funds (vaults, bets) are never at risk from API downtime — only resolution timing is affected
12. FAQ & Gotchas
Can agents trigger market resolution?
No. Only the keeper authority wallet (3cHDNTUqsqV4XSDdzuinvzaENKaUTKmud9m8enWFMfTh) can call resolveMarket. Resolution is fully automated.
What if I skip the sync/claim API calls?
Everything still works on-chain. The POST /api/bets/sync and POST /api/bets/claim/:betAddress endpoints only update the database for API/UI visibility. A background service syncs untracked bets within minutes. Your on-chain SOL is never affected.
Can the same user bet multiple times on one market?
Yes. Each bet gets a unique index from market.totalBets, creating a unique PDA. You can bet multiple times, even on opposite sides (YES and NO).
What is the 95% bonding rule exactly?
The on-chain check is bonding_progress < 95 (strict less-than). Values 0–94 are accepted. 95 and above are rejected. This is enforced in BOTH createMarket and placeBet instructions, AND server-side via the validate-bonding endpoint.
When does the 1-hour countdown start?
At market creation. resolution_slot = current_slot + 9,000 (~60 minutes at 400ms/slot). There is no way to extend or reset it.
Can a market be created for a graduated token?
No. The validate-bonding endpoint checks migration status, and the on-chain bonding check (< 95%) catches near-graduation tokens.
What's the minimum SOL to participate?
Action
Cost
Create market
0.1 SOL (fee) + 0.01 SOL (min bet) + ~0.003 SOL (rent/tx) = ~0.113 SOL
Place bet
0.01 SOL (min bet) + ~0.003 SOL (rent/tx) = ~0.013 SOL
Claim payout/refund
~0.000005 SOL (tx fee only)
Are wallet addresses truncated?
List endpoints (leaderboard, markets/resolved) truncate to "Xxxx...xxxx". Use /api/markets/:address for the full creator wallet. Use /api/bets/:betAddress for full bet details.
Calculated off-chain from Bitquery/Helius data and passed to on-chain instructions. The API's validate-bonding endpoint verifies against fresh Bitquery data — always use it.
Normalizing across endpoints
Market list and single-market endpoints use different field names for the same data. Use this pattern to normalize:
Yes. Parimutuel integer math may leave small amounts (< 1 lamport per bet) in the vault after all winners claim. This is recovered via closeVault after the 7-day claim period.
What infrastructure runs PumpMarket?
Frontend: Vercel (Next.js) at pumpmarket.fun
Backend: Railway (Express.js) at pumpbet-mainnet.up.railway.app
Development tool. Use this to verify your transaction construction is correct before spending real SOL. This simulates the transaction on-chain and returns success/failure without submitting.
Verify end-to-end integration without spending SOL. This script fetches an active market, builds a placeBet transaction, and simulates it on-chain.
typescript
import { Connection, PublicKey, Transaction } from '@solana/web3.js';
import { Program, AnchorProvider, BN, web3 } from '@coral-xyz/anchor';
import IDL from './pumpbets.json';
const PROGRAM_ID = new PublicKey('3mNbBV3Xc3rNJ4E87pSFzW7VhUZySHQDQVyd4MP2VFG6');
const API = 'https://pumpbet-mainnet.up.railway.app';
async function dryRun(wallet: web3.Keypair) {
const connection = new Connection('https://api.mainnet-beta.solana.com', 'confirmed');
const provider = new AnchorProvider(
connection,
{ publicKey: wallet.publicKey, signTransaction: async (tx) => { tx.sign(wallet); return tx; }, signAllTransactions: async (txs) => { txs.forEach(tx => tx.sign(wallet)); return txs; } },
{ commitment: 'confirmed' }
);
const program = new Program(IDL as any, PROGRAM_ID, provider);
// 1. Fetch active markets
const res = await fetch(`${API}/api/markets`);
const data = await res.json();
if (!data.markets?.length) { console.log('No active markets — nothing to simulate.'); return; }
const market = data.markets[0];
console.log(`Simulating placeBet on market: ${market.address} (${market.token?.symbol})`);
const marketPDA = new PublicKey(market.address);
const [vaultPDA] = PublicKey.findProgramAddressSync(
[Buffer.from('vault'), marketPDA.toBuffer()], PROGRAM_ID
);
// 2. Determine bet index from on-chain market account
const marketAccount = await program.account.bettingMarket.fetch(marketPDA);
const betIndex = marketAccount.totalBets;
const [userBetPDA] = PublicKey.findProgramAddressSync(
[Buffer.from('bet'), marketPDA.toBuffer(), wallet.publicKey.toBuffer(), new BN(betIndex).toArrayLike(Buffer, 'le', 4)],
PROGRAM_ID
);
// 3. Build transaction (0.01 SOL YES bet, bonding_progress = 50 placeholder — simulation only)
const ix = await program.methods
.placeBet(true, new BN(10_000_000), 50)
.accounts({
market: marketPDA,
userBet: userBetPDA,
user: wallet.publicKey,
vault: vaultPDA,
systemProgram: web3.SystemProgram.programId,
})
.instruction();
const tx = new Transaction().add(ix);
tx.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
tx.feePayer = wallet.publicKey;
// 4. Simulate — does NOT send or spend SOL
const sim = await connection.simulateTransaction(tx, [wallet]);
if (sim.value.err) {
console.error('Simulation FAILED:', JSON.stringify(sim.value.err));
console.error('Logs:', sim.value.logs?.join('\n'));
} else {
console.log('Simulation SUCCESS — transaction would execute correctly.');
console.log('Logs:', sim.value.logs?.join('\n'));
}
}
// Usage: dryRun(yourKeypair);
Note: Simulation uses bonding_progress = 50 as a placeholder. In production, always fetch the real value from POST /api/tokens/{mint}/validate-bonding. Simulation does not debit your wallet.