Skip to main content

Overview

This guide will walk you through setting up a basic Drift application using both the core utilities and React components.
1

Install Dependencies

First, install the required packages and their peer dependencies:
npm install @drift-labs/common @drift-labs/react @drift-labs/sdk @solana/web3.js react react-dom
See the Installation page for detailed instructions.
2

Initialize the SDK

Initialize the Drift SDK configuration for your target environment:
import { Initialize } from '@drift-labs/common';

// Initialize for mainnet
const sdkConfig = Initialize('mainnet-beta');

// Or for devnet
// const sdkConfig = Initialize('devnet');
The Initialize function sets up market configurations and returns the SDK config object. This must be called before using other Drift utilities.
3

Use Environment Constants

Access RPC endpoints and server URLs for different environments:
import { EnvironmentConstants } from '@drift-labs/common';

// Get mainnet RPC endpoints
const mainnetRpcs = EnvironmentConstants.rpcs.mainnet;
console.log(mainnetRpcs[0].value); // RPC URL
console.log(mainnetRpcs[0].wsValue); // WebSocket URL

// Get server URLs
const dlobUrl = EnvironmentConstants.dlobServerHttpUrl.mainnet;
const dataUrl = EnvironmentConstants.dataServerUrl.mainnet;
4

Use Core Utilities

Leverage the utility functions from @drift-labs/common:
import { 
  getTokenAddress,
  getTokenAddressForDepositAndWithdraw,
  COMMON_MATH 
} from '@drift-labs/common';
import { PublicKey } from '@solana/web3.js';
import { WRAPPED_SOL_MINT } from '@drift-labs/sdk';

// Get associated token address
const tokenAddress = await getTokenAddress(
  'MINT_ADDRESS_HERE',
  'USER_PUBKEY_HERE'
);

// Get token address for deposits/withdrawals
const depositAddress = await getTokenAddressForDepositAndWithdraw(
  new PublicKey('MINT_ADDRESS'),
  new PublicKey('AUTHORITY_PUBKEY')
);

// Use math utilities for orderbook calculations
const { bestBidPrice, bestAskPrice, markPrice, spreadPct } = 
  COMMON_MATH.calculateSpreadBidAskMark(l2OrderBook, oraclePrice);

React Integration

For React applications, use the @drift-labs/react package to access hooks, components, and providers.
1

Set Up Providers

Wrap your application with the DriftProvider:
App.tsx
import { DriftProvider } from '@drift-labs/react';
import { WalletAdapter } from '@solana/wallet-adapter-base';

// Define your screen breakpoints
const breakpoints = {
  mobile: 640,
  tablet: 768,
  desktop: 1024,
  wide: 1280,
};

function App() {
  // Optional: configure wallet adapters
  const wallets: WalletAdapter[] = [
    // Add your wallet adapters here
  ];

  return (
    <DriftProvider
      wallets={wallets}
      breakpoints={breakpoints}
      disableAutoconnect={false}
    >
      <YourApp />
    </DriftProvider>
  );
}
The DriftProvider handles:
  • Wallet connection and state management
  • Drift client initialization
  • SOL balance monitoring
  • Screen size tracking
  • Geo-blocking checks
2

Use Wallet Context

Access wallet state and functionality in your components:
WalletButton.tsx
import { useWalletContext, useWallet } from '@drift-labs/react';

function WalletButton() {
  const walletContext = useWalletContext();
  const wallet = useWallet();

  const handleConnect = async () => {
    if (walletContext.wallet) {
      await walletContext.connect();
    }
  };

  const handleDisconnect = async () => {
    await walletContext.disconnect();
  };

  return (
    <div>
      {walletContext.connected ? (
        <>
          <p>Connected: {walletContext.publicKey?.toBase58()}</p>
          <button onClick={handleDisconnect}>Disconnect</button>
        </>
      ) : (
        <button onClick={handleConnect}>Connect Wallet</button>
      )}
    </div>
  );
}
3

Monitor SOL Balance

Use the useSolBalance hook to track the user’s SOL balance:
Balance.tsx
import { useSolBalance } from '@drift-labs/react';

function Balance() {
  // The hook is already set up by DriftProvider
  // Access balance from the common store
  const { useCommonDriftStore } = require('@drift-labs/react');
  const solBalance = useCommonDriftStore((s) => s.solBalance);

  return (
    <div>
      <p>SOL Balance: {solBalance?.toString() ?? 'Loading...'}</p>
    </div>
  );
}
4

Use Drift Client Status

Check if the Drift client is ready before performing operations:
DriftStatus.tsx
import { useDriftClientIsReady } from '@drift-labs/react';

function DriftStatus() {
  const isReady = useDriftClientIsReady();

  if (!isReady) {
    return <div>Initializing Drift client...</div>;
  }

  return <div>Drift client is ready!</div>;
}
5

Use Common Drift Actions

Access common Drift operations through the actions hook:
DriftActions.tsx
import { useCommonDriftActions } from '@drift-labs/react';

function DriftActions() {
  const actions = useCommonDriftActions();

  // Actions are available for common Drift operations
  // such as deposits, withdrawals, and trading

  return (
    <div>
      <button onClick={() => {
        // Use actions here
      }}>
        Perform Action
      </button>
    </div>
  );
}

Using Icons

The icons package provides React components for Drift’s design system:
IconExample.tsx
import { Account, Add, AlertTriangle, Balance } from '@drift-labs/icons';

function IconExample() {
  return (
    <div>
      <Account width={24} height={24} />
      <Add width={24} height={24} />
      <AlertTriangle width={24} height={24} />
      <Balance width={24} height={24} />
    </div>
  );
}

Complete Example

Here’s a complete example putting it all together:
import React from 'react';
import { DriftProvider } from '@drift-labs/react';
import { Initialize } from '@drift-labs/common';
import WalletStatus from './WalletStatus';

// Initialize SDK
Initialize('mainnet-beta');

const breakpoints = {
  mobile: 640,
  tablet: 768,
  desktop: 1024,
  wide: 1280,
};

function App() {
  return (
    <DriftProvider
      breakpoints={breakpoints}
      disableAutoconnect={false}
    >
      <div className="app">
        <h1>My Drift App</h1>
        <WalletStatus />
      </div>
    </DriftProvider>
  );
}

export default App;

Advanced Configuration

Custom Drift Client Config

You can provide additional Drift client configuration:
import { DriftProvider } from '@drift-labs/react';
import { DriftClientConfig } from '@drift-labs/sdk';

const additionalConfig: Partial<DriftClientConfig> = {
  // Add your custom config here
};

function App() {
  return (
    <DriftProvider
      breakpoints={breakpoints}
      additionalDriftClientConfig={additionalConfig}
    >
      {/* Your app */}
    </DriftProvider>
  );
}

Disable Specific Features

You can disable specific features of the DriftProvider:
<DriftProvider
  breakpoints={breakpoints}
  disable={{
    idlePollingRateSwitcher: false,
    emulation: false,
    geoblocking: false,
    initConnection: false,
    subscribeSolBalance: false,
  }}
>
  {/* Your app */}
</DriftProvider>

Next Steps

Core Utilities

Explore all utilities in @drift-labs/common

React Hooks

Learn about available React hooks

Components

Browse UI components

Icons

View available icons

Build docs developers (and LLMs) love