Skip to main content
Drift Common provides comprehensive error definitions for both Drift Protocol and Jupiter integration errors. This guide covers error handling patterns and error types.

Error Code Files

Drift Common includes auto-generated error code mappings:
  • constants/autogenerated/driftErrors.json - Drift Protocol errors
  • constants/autogenerated/jup-v6-error-codes.json - Jupiter v6 swap errors
  • constants/autogenerated/jup-v4-error-codes.json - Jupiter v4 swap errors (legacy)

Drift Protocol Errors

Error Structure

Each Drift error contains:
interface DriftError {
  code: number;        // Error code (e.g., 6000)
  name: string;        // Error name (e.g., "InsufficientCollateral")
  msg: string;         // Error message
  toast?: {            // Optional UI toast configuration
    message?: string;
    description?: string;
    url?: string;
  };
}

Common Drift Errors

Insufficient Collateral (6003)

{
  "code": 6003,
  "name": "InsufficientCollateral",
  "msg": "Insufficient collateral",
  "toast": {
    "description": "You don't have enough collateral, try using less leverage or deposit more collateral."
  }
}
When it occurs: User attempts to open a position without sufficient collateral. How to handle:
try {
  await driftClient.openPosition(params);
} catch (error) {
  if (error.code === 6003) {
    // Prompt user to deposit more collateral
    showError("Insufficient collateral", 
      "Deposit more funds or reduce position size");
  }
}

Max Number of Positions (6005)

{
  "code": 6005,
  "name": "MaxNumberOfPositions",
  "msg": "Max number of positions taken",
  "toast": {
    "message": "Maximum Positions Exceeded",
    "description": "Close a position then try again or open it in another subaccount."
  }
}
When it occurs: User has reached the maximum number of open positions. How to handle:
if (error.code === 6005) {
  showError(
    "Maximum positions exceeded",
    "Close an existing position or use a different subaccount"
  );
}

Slippage Outside Limit (6015)

{
  "code": 6015,
  "name": "SlippageOutsideLimit",
  "msg": "Slippage Outside Limit Price",
  "toast": {
    "message": "Slippage limit exceeded."
  }
}
When it occurs: Trade execution price exceeds slippage tolerance. How to handle:
if (error.code === 6015) {
  // Suggest increasing slippage tolerance
  showError(
    "Slippage exceeded",
    "Increase slippage tolerance or try again"
  );
}

Order Size Too Small (6016)

{
  "code": 6016,
  "name": "OrderSizeTooSmall",
  "msg": "Order Size Too Small",
  "toast": {
    "message": "Order size is too small."
  }
}

Max Number of Orders (6060)

{
  "code": 6060,
  "name": "MaxNumberOfOrders",
  "msg": "Max number of orders taken",
  "toast": {
    "message": "This SubAccount has already has Max Number of Open Orders (32)",
    "description": "Cancelled orders to place more or create a new subaccount."
  }
}

No Spot Position Available (6084)

{
  "code": 6084,
  "name": "NoSpotPositionAvailable",
  "msg": "NoSpotPositionAvailable",
  "toast": {
    "message": "No Spot Positions Available",
    "description": "You can hold up to 7 non-USDC spot positions plus 1 USDC position (reserved for perp PnL). Try fully withdrawing an asset or closing an open borrow to free up a position slot."
  }
}

Exchange Paused (6024)

{
  "code": 6024,
  "name": "ExchangePaused",
  "msg": "Exchange is paused",
  "toast": {
    "message": "The Exchange is currently paused."
  }
}

User Bankrupt (6125)

{
  "code": 6125,
  "name": "UserBankrupt",
  "msg": "UserBankrupt",
  "toast": {
    "message": "Bankrupt",
    "description": "Couldn't complete action because the user is currently bankrupt"
  }
}

Can’t Pay User Init Fee (6256)

{
  "code": 6256,
  "name": "CantPayUserInitFee",
  "msg": "CantPayUserInitFee",
  "toast": {
    "message": "Not enough SOL",
    "description": "The transaction failed because your wallet did not have enough SOL to cover the user initialization fee. You can learn more about account creation fees in the Drift Docs.",
    "url": "https://docs.drift.trade/getting-started/managing-subaccount"
  }
}

Jupiter Swap Errors

Jupiter Error Structure

interface JupiterError {
  code: number;
  name: string;
  msg: string;
}

Common Jupiter Errors

Slippage Tolerance Exceeded (6001)

{
  "code": 6001,
  "name": "SlippageToleranceExceeded",
  "msg": "Slippage tolerance exceeded"
}
How to handle:
try {
  await executeJupiterSwap(params);
} catch (error) {
  if (error.code === 6001) {
    showError(
      "Swap failed",
      "Price moved too much. Increase slippage or try again."
    );
  }
}

Empty Route (6000)

{
  "code": 6000,
  "name": "EmptyRoute",
  "msg": "Empty route"
}

Invalid Calculation (6002)

{
  "code": 6002,
  "name": "InvalidCalculation",
  "msg": "Invalid calculation"
}

Swap Not Supported (6016)

{
  "code": 6016,
  "name": "SwapNotSupported",
  "msg": "Swap not supported"
}

Custom Error Classes

GeoBlockError

Thrown when a user is geographically restricted:
import { GeoBlockError } from '@drift-labs/common';

try {
  await driftClient.placeOrder(params);
} catch (error) {
  if (error instanceof GeoBlockError) {
    showError(
      "Service Unavailable",
      "This service is not available in your region."
    );
  }
}
Creating the error:
throw new GeoBlockError('placeOrder');
// Error message: "Method 'placeOrder' is not available due to geographical restrictions."

NoTopMakersError

Thrown when no top makers are found, but includes fallback order params:
import { NoTopMakersError } from '@drift-labs/common';

try {
  const makers = await getTopMakers();
} catch (error) {
  if (error instanceof NoTopMakersError) {
    // Use fallback order params
    const fallbackParams = error.orderParams;
    await placeOrder(fallbackParams);
  }
}
Creating the error:
throw new NoTopMakersError(
  'No makers available for this market',
  fallbackOrderParams
);

Error Handling Patterns

Error Code Lookup

import driftErrors from '@drift-labs/common/constants/autogenerated/driftErrors.json';

function getDriftErrorByCode(code: number) {
  const errorName = driftErrors.errorCodesMap[code.toString()];
  return driftErrors.errorsList[errorName];
}

const error = getDriftErrorByCode(6003);
console.log(error.toast?.description);

Error Code Mapping

const ERROR_CODES = {
  INSUFFICIENT_COLLATERAL: 6003,
  MAX_POSITIONS: 6005,
  SLIPPAGE_EXCEEDED: 6015,
  ORDER_TOO_SMALL: 6016,
  MAX_ORDERS: 6060,
  NO_SPOT_POSITION: 6084,
} as const;

if (error.code === ERROR_CODES.INSUFFICIENT_COLLATERAL) {
  // Handle insufficient collateral
}

Toast Integration

function showDriftError(error: any) {
  const driftError = getDriftErrorByCode(error.code);
  
  if (driftError?.toast) {
    showToast({
      title: driftError.toast.message || driftError.name,
      description: driftError.toast.description || driftError.msg,
      link: driftError.toast.url,
      type: 'error'
    });
  } else {
    showToast({
      title: 'Transaction Failed',
      description: error.message || 'An unknown error occurred',
      type: 'error'
    });
  }
}

Retry Logic

async function executeWithRetry<T>(
  fn: () => Promise<T>,
  maxRetries = 3
): Promise<T> {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      // Don't retry on user errors
      if (error.code === 6003 || error.code === 6005) {
        throw error;
      }
      
      // Don't retry on last attempt
      if (i === maxRetries - 1) {
        throw error;
      }
      
      // Wait before retry
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
    }
  }
  throw new Error('Max retries exceeded');
}

Error Logging

import { logger } from '@drift-labs/common';

try {
  await driftClient.placeOrder(params);
} catch (error) {
  logger.error('Order placement failed', {
    errorCode: error.code,
    errorName: error.name,
    userAccount: userAccount.toString(),
    orderParams: params
  });
  
  throw error;
}

Best Practices

1. Always Handle Known Errors

const RECOVERABLE_ERRORS = [6015, 6001]; // Slippage errors

try {
  await executeTrade();
} catch (error) {
  if (RECOVERABLE_ERRORS.includes(error.code)) {
    // Let user retry with adjusted params
    return { success: false, retry: true };
  }
  throw error;
}

2. Provide User-Friendly Messages

const ERROR_MESSAGES = {
  6003: "You need more collateral to open this position.",
  6005: "You've reached the maximum number of positions.",
  6015: "Price moved too quickly. Please try again.",
};

function getUserMessage(errorCode: number): string {
  return ERROR_MESSAGES[errorCode] || "An error occurred. Please try again.";
}

3. Log Errors for Debugging

function handleError(error: any, context: string) {
  logger.error(`Error in ${context}`, {
    code: error.code,
    name: error.name,
    message: error.message,
    stack: error.stack
  });
  
  showUserError(error);
}

4. Type-Safe Error Handling

type DriftErrorCode = 6003 | 6005 | 6015 | 6016 | 6060 | 6084;

function isDriftError(error: any): error is { code: DriftErrorCode } {
  return typeof error.code === 'number' && error.code >= 6000;
}

if (isDriftError(error)) {
  // TypeScript knows error.code is DriftErrorCode
  handleDriftError(error);
}

Environment Configuration

Configure endpoints and network settings

Testing Guide

Test error handling in your application

Build docs developers (and LLMs) love