Drift BET is not a separate chain, wallet standard, or SDK. It is a special class of Drift v2 perpetual market with contract_type = Prediction. If you are building an agent for Drift BET, you are really building one of three things:
- A read-only analysis agent using Drift’s market data APIs
- A trading agent using the Drift SDK to sign transactions directly
- An execution agent behind the self-hosted Drift Gateway, so your higher-level AI/automation layer talks HTTP while a signer handles Solana transactions safely
This guide covers all three paths with production-ready TypeScript examples.
How BET markets differ from standard perps
| Attribute | Standard Perp | BET Market |
|---|---|---|
| Price range | Unbounded | 0 to 1 |
| Funding | Active | Paused |
| Margin | Partial collateral | Fully collateralized |
| Short valuation | Standard | 1 - oracle price |
| Oracle | External feed (Pyth, Switchboard) | Mark TWAP (prelaunch-style) |
| Order validation | Standard | InvalidPredictionMarketOrder enforcement |
The practical consequence: a decision engine built for BTC/SOL perps will make bad assumptions if reused unchanged for BET-style markets. BET markets need their own risk rules.
The four integration surfaces
1. Data API — easiest entry point
Drift exposes a public REST and WebSocket surface at https://data.api.drift.trade and wss://data.api.drift.trade/ws. This is ideal for discovering markets, monitoring trades, pricing, candles, and order books without touching a wallet. The OpenAPI spec is publicly exposed.
Key precisions developers should not guess: base amounts are in 1e9 precision, quote amounts in 1e6 precision. The trades endpoint returns roughly the last 31 days of records, capped at 50 per request.
2. SDKs — primary stateful integration
Drift documents TypeScript, Python, and Rust support. The main interaction class in TypeScript is DriftClient. Drift’s examples repo recommends Node v20.18.0. The npm package @drift-labs/sdk shows a current beta line at 2.158.0-beta.3.
3. Gateway — best fit for agent architecture
Drift Gateway is a self-hosted HTTP layer that lets you create, modify, cancel, and query orders without forcing your AI/app layer to talk raw Solana transaction flows. It supports delegated operation and subaccounts.
The user account must already be initialized before Gateway can act on it — otherwise you get AccountNotFound.
4. DLOB / SWIFT / JIT — advanced execution
If you want market making, low-latency taker logic, or agent-assisted order flow:
- DLOB — Drift’s off-chain view of resting orders
- SWIFT — Signed off-chain taker flow, ~100-500ms before on-chain processing
- JIT — Just-in-time auctions as part of order execution priority
Drift’s order flow prioritizes: JIT auction → DLOB → AMM.
Recommended architecture
For a production agent, separate concerns aggressively:
┌──────────────┐ ┌──────────────────┐ ┌──────────────┐
│ Data API │───▶│ Decision Engine │───▶│ Risk Engine │
│ (Reader) │ │ (Strategy) │ │ (Limits) │
└──────────────┘ └──────────────────┘ └──────┬───────┘
│
┌───────▼───────┐
│ Executor │
│ (SDK/Gateway) │
└───────┬───────┘
│
┌───────▼───────┐
│ Signer │
│ (Isolated) │
└───────────────┘
- Reader — Only consumes Data API REST/WS and on-chain market/account state
- Decision engine — Turns market state into a desired action
- Risk engine — Enforces collateral, position, and pricing rules
- Executor — Talks to the Drift SDK directly or a private Gateway instance
- Signer — Isolated from the reasoning layer for autonomous safety
For most teams, the best pattern is: Data API for read-heavy workloads, private Gateway for execution, a dedicated delegate wallet for the executor, and one Drift subaccount per strategy or agent instance.
TypeScript setup
Install the SDK and dependencies:
npm install @drift-labs/sdk @coral-xyz/anchor @solana/web3.js @solana/spl-token
A minimal mainnet setup — initialize config, build a BulkAccountLoader, construct a DriftClient, subscribe, initialize a user if needed, then place orders:
import * as anchor from "@coral-xyz/anchor";
import { PublicKey } from "@solana/web3.js";
import { getAssociatedTokenAddress } from "@solana/spl-token";
import {
initialize,
DriftClient,
User,
BulkAccountLoader,
BN,
QUOTE_PRECISION,
BASE_PRECISION,
PositionDirection,
getMarketOrderParams,
} from "@drift-labs/sdk";
async function main() {
const env = "mainnet-beta";
const sdkConfig = initialize({ env });
const provider = anchor.AnchorProvider.local(
process.env.ANCHOR_PROVIDER_URL!,
{
commitment: "confirmed",
preflightCommitment: "confirmed",
skipPreflight: false,
}
);
const bulkAccountLoader = new BulkAccountLoader(
provider.connection,
"confirmed",
1000
);
const driftClient = new DriftClient({
connection: provider.connection,
wallet: provider.wallet,
programID: new PublicKey(sdkConfig.DRIFT_PROGRAM_ID),
accountSubscription: {
type: "polling",
accountLoader: bulkAccountLoader,
},
});
await driftClient.subscribe();
const user = new User({
driftClient,
userAccountPublicKey: await driftClient.getUserAccountPublicKey(),
accountSubscription: {
type: "polling",
accountLoader: bulkAccountLoader,
},
});
if (!(await user.exists())) {
const usdcAta = await getAssociatedTokenAddress(
new PublicKey(sdkConfig.USDC_MINT_ADDRESS),
provider.wallet.publicKey
);
await driftClient.initializeUserAccountAndDepositCollateral(
new BN(100).mul(QUOTE_PRECISION),
usdcAta
);
}
await user.subscribe();
// Replace with a dynamically discovered BET market index
const marketIndex = 0;
await driftClient.placePerpOrder(
getMarketOrderParams({
marketIndex,
direction: PositionDirection.LONG,
baseAssetAmount: new BN(1).mul(BASE_PRECISION),
})
);
}
main().catch(console.error);
User account initialization is not free — Drift’s docs note that creating a user account needs rent, around 0.035 SOL. Subaccount IDs are monotonic rather than arbitrary.
Dynamic market discovery
Do not hardcode BET market indexes. Drift’s SDK constants and changelog show historical prediction/BET markets (TRUMP-WIN-2024-BET, KAMALA-POPULAR-VOTE-2024-BET, etc.), but many are now marked DELISTED. Discover active markets dynamically:
type MarketStat = {
symbol: string;
marketIndex: number;
marketType: string;
status?: string;
oraclePrice?: number | string;
markPrice?: number | string;
};
async function getActiveBetMarkets(): Promise<MarketStat[]> {
const res = await fetch("https://data.api.drift.trade/stats/markets");
const json = await res.json();
const markets: MarketStat[] = json.markets ?? [];
return markets.filter((m) => {
const status = String(m.status ?? "").toLowerCase();
return (
m.marketType === "perp" &&
m.symbol.endsWith("-BET") &&
status !== "delisted"
);
});
}
The /stats/markets response includes symbol, marketIndex, marketType, status, oraclePrice, markPrice, open interest, volume, and more — enough to build a market-discovery and health layer for your agent.
Reading live BET market data
REST endpoints
// Recent trades
const trades = await fetch(
"https://data.api.drift.trade/trades?symbol=YOUR-BET-SYMBOL&limit=50"
).then((r) => r.json());
// Funding rates
const funding = await fetch(
"https://data.api.drift.trade/fundingRates?symbol=YOUR-BET-SYMBOL"
).then((r) => r.json());
WebSocket subscriptions
The /ws endpoint supports channels including candle, markets, pricing, orderbook, user, and notifications. For a trading agent, orderbook and pricing are the ones you usually want first:
const ws = new WebSocket("wss://data.api.drift.trade/ws");
ws.onopen = () => {
ws.send(
JSON.stringify({
type: "subscribe",
channelType: "orderbook",
symbol: "YOUR-BET-SYMBOL",
})
);
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data.toString());
console.log(msg);
};
Some Data API endpoints are protected and require signed headers (x-wallet-address, x-signature, x-signed-message). The OpenAPI spec documents a signed message shape with fields including action, ts, walletAddress, and optional delegation context.
Gateway: the best execution layer for agents
If your agent is an LLM, workflow engine, or orchestration service, the cleanest pattern is to hide Solana transaction-building behind Drift Gateway. It is a self-hosted API for Drift v2 interaction with endpoints for listing, placing, modifying, canceling, and cancel-and-replacing orders, plus swaps.
Endpoints
| Method | Endpoint | Action |
|---|---|---|
| GET | /v2/orders | List orders |
| POST | /v2/orders | Place order |
| PATCH | /v2/orders | Modify order |
| DELETE | /v2/orders | Cancel order(s) |
| POST | /v2/orders/cancelAndPlace | Atomic cancel + place |
| POST | /v2/swap | Swap |
Example: place a BET order
curl -X POST "http://localhost:8080/v2/orders" \
-H "Content-Type: application/json" \
-d '{
"marketType": "perp",
"marketName": "YOUR-BET-SYMBOL",
"direction": "long",
"baseAmount": 1,
"orderType": "market"
}'
Delegated mode
Delegated authorities can deposit, swap, place, and cancel orders, but cannot withdraw, borrow, close accounts, or change user settings. This is exactly what agent systems want: an execution key with bounded power. Gateway can be started with a --delegate flag tied to the main authority.
Subaccount routing
Gateway supports switching the active subaccount per request using ?subAccountId=..., which isolates one agent strategy from another without separate wallet stacks.
BET-specific pitfalls
1. Oracle behavior
Drift’s prediction/prelaunch markets can rely on mark TWAP rather than a normal external oracle, and prelaunch markets are treated as highly speculative with conservative open-interest limits and no external insurance-fund support.
2. Order validity
The dedicated program error InvalidPredictionMarketOrder means not every standard perp order pattern transfers cleanly to prediction markets. Validate your price ranges (0 to 1) and size logic before signing.
3. Execution stack differences
Drift’s order flow prioritizes JIT auction → DLOB → AMM for perps. A naive “post order and assume it matches like a centralized exchange” mental model is incomplete. If you are building a serious execution agent, inspect DLOB and JIT behavior rather than only looking at on-chain fills after the fact.
4. Delisted markets
Drift’s SDK constants and changelog show historical prediction/BET markets, but many entries are now marked DELISTED. Never hardcode market indexes. Always discover markets dynamically via the Data API.
Production advice
Use a paid RPC
Drift’s own Gateway docs warn that free Solana mainnet RPCs are not recommended because of rate limits and getProgramAccounts failures. Free RPCs often fall short for WebSockets and account scans.
Set resubscribe and resync intervals
For SDK subscribers, use a resubscribe timeout around 30,000 ms and a periodic resync interval around 300,000 ms because WebSocket silence can leave your local view stale even when nothing throws an obvious exception.
Budget compute units
For active execution, use a PriorityFeeSubscriber, explicitly set compute unit limits, and budget around 200k-400k compute units for place-and-make style flows. Use address lookup tables through fetchAllLookupTableAccounts() to stay under Solana transaction size limits.
SWIFT for low-latency execution
If you move into maker or latency-sensitive agent design, Drift exposes local DLOB components (OrderSubscriber, DLOBSubscriber, SlotSubscriber) and SWIFT as a way to send signed taker orders off-chain roughly 100-500 ms before on-chain processing.
The mental model
A Drift BET agent is not “an AI connecting to some special betting API.” It is a normal Drift/Solana integration where:
- BET markets are a special prediction-market flavor of Drift perp markets
- Market discovery should be dynamic
- Reads should lean on the Data API
- Execution should go through the SDK or a private Gateway
- Delegation and subaccounts are the right safety model for autonomous agents
- Prelaunch/prediction-market mechanics need their own risk rules
Related resources
- Drift BET Marketplace Listing — Quick reference for Drift BET as a platform
- Rain Protocol — Permissionless prediction market infrastructure on Arbitrum for comparison
- The Agent Betting Stack Explained — The four-layer framework
- Prediction Market API Reference 2026 — Compare Drift’s APIs with Polymarket and Kalshi
- Agent Wallet Comparison — Wallet options for Solana-based agents
- Cross-Market Arbitrage Guide — Exploit pricing differences across platforms
- Polymarket Bot Quickstart — Compare with the Polymarket integration path
- Build a Prediction Market Agent — General-purpose agent building guide
Last updated: March 20, 2026. Drift BET is in active development; market availability, SDK versions, and API endpoints change frequently. Verify against docs.drift.trade before production deployment.
