# Drift Protocol

> Complete Drift Protocol SDK for building perpetual futures, spot trading, and DeFi applications on Solana. Use when building trading bots, integrating Drift markets, managing positions, or working with vaults.

- **Type:** Skill
- **Install:** `agentstack add skill-eugenepyvovarov-mcpbundler-agent-skills-marketplace-drift-protocol`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [eugenepyvovarov](https://agentstack.voostack.com/s/eugenepyvovarov)
- **Installs:** 0
- **Category:** [Finance & Payments](https://agentstack.voostack.com/c/finance-and-payments)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [eugenepyvovarov](https://github.com/eugenepyvovarov)
- **Source:** https://github.com/eugenepyvovarov/mcpbundler-agent-skills-marketplace/tree/main/drift-protocol
- **Website:** https://mcp-bundler.com/skills-marketplace/

## Install

```sh
agentstack add skill-eugenepyvovarov-mcpbundler-agent-skills-marketplace-drift-protocol
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Drift Protocol SDK Development Guide

A comprehensive guide for building Solana applications with the Drift Protocol SDK - the leading perpetual futures and spot trading protocol on Solana.

## Overview

Drift Protocol is a decentralized exchange on Solana offering:
- **Perpetual Futures**: Up to 20x leverage on crypto assets
- **Spot Trading**: Borrow/lend and margin trading
- **Cross-Collateral**: Use multiple assets as collateral
- **Vaults**: Delegated trading pools
- **Jupiter Integration**: Direct spot swaps

## Quick Start

### Installation

```bash
npm install @drift-labs/sdk @solana/web3.js @coral-xyz/anchor
```

For Python:
```bash
pip install driftpy
```

### Basic Setup (TypeScript)

```typescript
import { Connection, Keypair } from '@solana/web3.js';
import { Wallet } from '@coral-xyz/anchor';
import {
  DriftClient,
  initialize,
  DriftEnv,
  BulkAccountLoader
} from '@drift-labs/sdk';

// 1. Setup connection and wallet
const connection = new Connection('https://api.mainnet-beta.solana.com');
const keypair = Keypair.fromSecretKey(/* your secret key */);
const wallet = new Wallet(keypair);

// 2. Initialize SDK
const sdkConfig = initialize({ env: 'mainnet-beta' as DriftEnv });

// 3. Create DriftClient
const driftClient = new DriftClient({
  connection,
  wallet,
  env: 'mainnet-beta',
  accountSubscription: {
    type: 'polling',
    accountLoader: new BulkAccountLoader(connection, 'confirmed', 1000),
  },
});

// 4. Subscribe to updates
await driftClient.subscribe();

// 5. Check if user account exists
const user = driftClient.getUser();
const userExists = await user.exists();

if (!userExists) {
  // Initialize user account (costs ~0.035 SOL rent)
  await driftClient.initializeUserAccount();
}
```

### Basic Setup (Python)

```python
import asyncio
from solana.rpc.async_api import AsyncClient
from solders.keypair import Keypair
from driftpy.drift_client import DriftClient
from driftpy.account_subscription_config import AccountSubscriptionConfig
from anchorpy import Wallet

async def main():
    connection = AsyncClient("https://api.mainnet-beta.solana.com")
    keypair = Keypair.from_bytes(secret_key_bytes)
    wallet = Wallet(keypair)

    drift_client = DriftClient(
        connection,
        wallet,
        "mainnet",
        account_subscription=AccountSubscriptionConfig("polling"),
    )

    await drift_client.subscribe()

    user = drift_client.get_user()
    if not await user.exists():
        await drift_client.initialize_user_account()

asyncio.run(main())
```

## Core Concepts

### 1. Precision and BN (BigNumber)

Drift uses BN.js for all numerical values due to token precision exceeding JavaScript float limits. All amounts are integers with designated precision levels.

**Key Precision Constants:**

| Constant | Value | Use Case |
|----------|-------|----------|
| `QUOTE_PRECISION` | 10^6 | USDC amounts |
| `BASE_PRECISION` | 10^9 | Perp base asset amounts |
| `PRICE_PRECISION` | 10^6 | Prices |
| `SPOT_MARKET_BALANCE_PRECISION` | 10^9 | Spot token balances |
| `FUNDING_RATE_PRECISION` | 10^9 | Funding rates |
| `MARGIN_PRECISION` | 10,000 | Margin ratios |
| `PEG_PRECISION` | 10^6 | AMM peg |
| `AMM_RESERVE_PRECISION` | 10^9 | AMM reserves |

**Conversion Helper:**
```typescript
import { convertToNumber } from '@drift-labs/sdk';

// BN division returns floor - use helper for precise division
const result = convertToNumber(new BN(10500), new BN(1000)); // = 10.5

// Converting amounts
const perpAmount = driftClient.convertToPerpPrecision(100);  // 100 base units
const spotAmount = driftClient.convertToSpotPrecision(0, 100); // 100 USDC
const price = driftClient.convertToPricePrecision(21.23);    // $21.23
```

### 2. Market Types

**Perpetual Markets** (`MarketType.PERP`):
- Derivatives with no expiry
- Positions tracked via `baseAssetAmount`
- Positive = Long, Negative = Short

**Spot Markets** (`MarketType.SPOT`):
- Real token deposits/borrows
- Positions tracked via `scaledBalance`
- `SpotBalanceType.DEPOSIT` or `SpotBalanceType.BORROW`

**Common Market Indexes:**
- `0` - USDC (quote asset)
- `1` - SOL
- Market indexes vary - query `getPerpMarketAccounts()` / `getSpotMarketAccounts()`

### 3. Order Types

```typescript
import { OrderType, PositionDirection, OrderTriggerCondition } from '@drift-labs/sdk';

// Available order types
OrderType.MARKET          // Immediate execution
OrderType.LIMIT           // Price-specific orders
OrderType.TRIGGER_MARKET  // Stop-loss/take-profit market
OrderType.TRIGGER_LIMIT   // Stop-loss/take-profit limit
OrderType.ORACLE          // Oracle-based pricing

// Position directions
PositionDirection.LONG    // Buy/bid
PositionDirection.SHORT   // Sell/ask

// Trigger conditions (for stop orders)
OrderTriggerCondition.ABOVE  // Trigger when price > threshold
OrderTriggerCondition.BELOW  // Trigger when price  {
  console.log('Event type:', event.eventType);
  console.log('Event data:', event);
});

// Get events by type
const depositEvents = eventSubscriber.getEventsReceived()
  .filter(e => e.eventType === 'DepositRecord');

// Unsubscribe
await eventSubscriber.unsubscribe();
```

## Jupiter Swaps

```typescript
import { JupiterClient } from '@drift-labs/sdk';

// Initialize Jupiter client
const jupiterClient = new JupiterClient({ connection });

// Get quote preview
const quote = await jupiterClient.getQuote({
  inputMint: /* USDC mint */,
  outputMint: /* SOL mint */,
  amount: driftClient.convertToSpotPrecision(0, 100),
  slippageBps: 50,
});

// Execute swap through Drift
const txSig = await driftClient.swap({
  jupiterClient,
  inMarketIndex: 0,   // USDC
  outMarketIndex: 1,  // SOL
  amount: driftClient.convertToSpotPrecision(0, 100),
  slippageBps: 50,
  onlyDirectRoutes: false,
});
```

## Sub-Accounts

```typescript
// Create new sub-account
const [txSig, userPubkey] = await driftClient.initializeUserAccount(
  1, // sub-account ID
  'SubAccount1' // name
);

// Switch active sub-account
await driftClient.switchActiveUser(1);

// Get user for specific sub-account
const user = driftClient.getUser(1);

// Delete sub-account (must have no positions)
await driftClient.deleteUser(1);

// Update delegate (allow another key to trade)
await driftClient.updateUserDelegate(delegatePublicKey, 0);
```

## Advanced: Swift Protocol (Orderless Trades)

Swift allows off-chain order signing without Solana transactions:

```typescript
// Sign order message
const orderMessage = {
  marketIndex: 0,
  marketType: MarketType.PERP,
  direction: PositionDirection.LONG,
  baseAssetAmount: driftClient.convertToPerpPrecision(1),
  price: driftClient.convertToPricePrecision(100),
};

const signature = driftClient.signSignedMsgOrderParamsMessage(orderMessage);

// Submit to Swift server
await axios.post('https://swift.drift.trade/orders', {
  market_index: 0,
  message: signature.message,
  signature: signature.signature,
  taker_authority: wallet.publicKey.toString(),
});
```

## Advanced: Builder Codes (DBC)

For platforms routing trades through Drift to earn fees:

```typescript
// Initialize as builder
await driftClient.initializeRevenueShare(builderAuthority);

// Initialize user's escrow
await driftClient.initializeRevenueShareEscrow(userAuthority, numOrders);

// Approve builder
await driftClient.changeApprovedBuilder(
  builderAuthority,
  maxFeeTenthBps, // max fee in tenth basis points
  true // add (false to remove)
);
```

## Error Handling

```typescript
try {
  await driftClient.placePerpOrder(orderParams);
} catch (error) {
  if (error.message.includes('InsufficientCollateral')) {
    console.error('Not enough collateral for this trade');
  } else if (error.message.includes('MaxLeverageExceeded')) {
    console.error('Would exceed maximum leverage');
  } else if (error.message.includes('OrderWouldCrossMaker')) {
    console.error('Post-only order would cross spread');
  } else {
    throw error;
  }
}
```

## Resources

- [Drift Protocol Docs](https://docs.drift.trade)
- [SDK Documentation](https://drift-labs.github.io/v2-teacher/)
- [TypeScript SDK](https://github.com/drift-labs/protocol-v2/tree/master/sdk)
- [Python SDK (DriftPy)](https://github.com/drift-labs/driftpy)
- [Keeper Bots Examples](https://github.com/drift-labs/keeper-bots-v2)

## Skill Structure

```
drift-protocol/
├── SKILL.md                          # This file
├── resources/
│   ├── precision-constants.md        # All precision constants
│   ├── types-reference.md            # TypeScript types and enums
│   ├── drift-client-api.md           # DriftClient method reference
│   └── user-api.md                   # User class method reference
├── examples/
│   ├── basic-setup/                  # Client initialization
│   ├── orders/                       # Order placement examples
│   ├── deposits-withdrawals/         # Collateral management
│   ├── positions/                    # Position queries
│   ├── jupiter-swaps/                # Swap integration
│   ├── vaults/                       # Vault management
│   └── events/                       # Event subscription
├── docs/
│   ├── vaults.md                     # Vault documentation
│   ├── market-making.md              # Market making guide
│   └── troubleshooting.md            # Common issues
└── templates/
    └── trading-bot-template.ts       # Copy-paste starter
```

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [eugenepyvovarov](https://github.com/eugenepyvovarov)
- **Source:** [eugenepyvovarov/mcpbundler-agent-skills-marketplace](https://github.com/eugenepyvovarov/mcpbundler-agent-skills-marketplace)
- **License:** MIT
- **Homepage:** https://mcp-bundler.com/skills-marketplace/

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-eugenepyvovarov-mcpbundler-agent-skills-marketplace-drift-protocol
- Seller: https://agentstack.voostack.com/s/eugenepyvovarov
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
