Code Examples
Real-world examples and code snippets for common use cases
Code Examples
Ready-to-use code examples for integrating with Cap Bet.
Create a Market
import { CapBetClient } from '@capbet/sdk';
const client = new CapBetClient({
apiKey: process.env.CAPBET_API_KEY,
cluster: 'devnet',
});
// Create a new betting market
const market = await client.markets.create({
title: 'Will Solana reach $200 by end of 2024?',
description: 'Resolves YES if SOL price hits $200 USD before 2025',
lockTime: new Date('2024-12-31T23:59:59Z'),
minBetAmount: 0.1,
maxBetAmount: 100,
category: 'crypto',
});
console.log('Market created:', market.id);Place a Bet
// Take a position on a market
const position = await client.positions.create({
marketId: 'market_123',
side: 'yes',
amount: 10, // 10 SOL
});
console.log('Position created:', position.id);Query Markets
// Get all active markets
const markets = await client.markets.getAll({
status: 'active',
category: 'crypto',
sortBy: 'volume',
limit: 20,
});
for (const market of markets) {
console.log(`${market.title} - Volume: ${market.totalVolume} SOL`);
}WebSocket Real-time Updates
import { CapBetWebSocket } from '@capbet/sdk';
const ws = new CapBetWebSocket({
url: 'wss://api.cap.bet/ws',
apiKey: process.env.API_KEY,
});
// Subscribe to all market updates
ws.subscribe('markets', (data) => {
if (data.type === 'market:created') {
console.log('New market:', data.market.title);
}
if (data.type === 'market:position') {
console.log('New position:', data.amount, 'SOL on', data.side);
}
});
await ws.connect();Monitor Positions
// Get all user positions
const positions = await client.positions.getUserPositions(
'YOUR_PUBLIC_KEY'
);
for (const position of positions) {
const market = await client.markets.getById(position.marketId);
console.log(`Market: ${market.title}`);
console.log(`Side: ${position.side}`);
console.log(`Amount: ${position.amount} SOL`);
console.log(`Status: ${position.status}`);
}Claim Winnings
// Claim winnings from resolved market
const result = await client.positions.claim({
positionId: 'position_123',
});
console.log(`Claimed ${result.amount} SOL`);Direct Smart Contract Interaction
import { AnchorProvider, Program } from '@coral-xyz/anchor';
import { Connection, Keypair } from '@solana/web3.js';
import idl from '@capbet/sdk/idl.json';
const connection = new Connection('https://api.devnet.solana.com');
const wallet = Keypair.fromSecretKey(
Buffer.from(process.env.WALLET_PRIVATE_KEY, 'base64')
);
const provider = new AnchorProvider(connection, wallet, {});
const program = new Program(idl, provider);
// Create market using smart contract
const tx = await program.methods
.createMarket(
"Will BTC hit $100k?",
new BN(Date.now() / 1000 + 86400 * 30),
new BN(0.1 * LAMPORTS_PER_SOL),
new BN(1000 * LAMPORTS_PER_SOL),
)
.accounts({
market: marketKeypair.publicKey,
creator: wallet.publicKey,
systemProgram: SystemProgram.programId,
})
.rpc();AI Agent Integration
import { CapBetMCPClient } from '@capbet/mcp-client';
import Anthropic from '@anthropic-ai/sdk';
const capbet = new CapBetMCPClient({
apiKey: process.env.CAPBET_API_KEY,
});
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
async function analyzeMarket(marketId: string) {
// Get market data
const market = await capbet.tools.getMarket({ marketId });
// AI analyzes the market
const response = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
messages: [{
role: 'user',
content: `Analyze this betting market and recommend a position:
Title: ${market.title}
Description: ${market.description}
Current odds: ${market.odds}
Volume: ${market.totalVolume} SOL`,
}],
});
console.log('AI Analysis:', response.content);
// Place bet based on AI recommendation
if (response.content.includes('recommend YES')) {
await capbet.tools.placeBet({
marketId,
side: 'yes',
amount: 5,
});
}
}Error Handling
try {
const position = await client.positions.create({
marketId: 'market_123',
side: 'yes',
amount: 1000,
});
} catch (error) {
if (error.code === 'INSUFFICIENT_FUNDS') {
console.error('Not enough SOL in wallet');
} else if (error.code === 'MARKET_LOCKED') {
console.error('Market is locked');
} else if (error.code === 'INVALID_AMOUNT') {
console.error('Bet amount out of range');
} else {
console.error('Unknown error:', error);
}
}Complete Bot Example
See Bot Integration Guide for a complete trading bot implementation.
Next Steps
- Explore the API Reference
- Read about Smart Contracts
- Learn about MCP Integration