@drift-labs/sdk

中文文档
2.163.0-beta.13发布于 2026/05/12Apache-2.0TypeScriptESM + CJS近 30 天下载 6.5万

SDK for Drift Protocol

原始使用文档
文档目录8 节
  1. Installation
  2. Getting Started
  3. Setting up a wallet for your program
  4. Concepts
  5. BN / Precision
  6. Examples
  7. Setting up an account and making a trade
  8. License

Drift Protocol v2

SDK npm package Docs Discord Chat License

Installation

npm i @drift-labs/sdk

Getting Started

Start here if you're integrating with Drift!

  • Drift v2-teacher + API Docs
    • Docs and examples for using the SDK in Typescript and Python
    • Useful concepts and examples when integrating Drift
    • Docs for Drift's "Data API"
  • Typescript API docs
    • JSDoc automated documentation for the Drift v2 Typescript SDK
  • Drift docs
    • Comprehensive universal docs for Drift

The below is a light overview of using Solana and Drift's typescript sdk. If you want comprehensive docs with examples of how to integrate with Drift you should use the v2-teacher docs.

Setting up a wallet for your program

# Generate a keypair
solana-keygen new

# Get the pubkey for the new wallet (You will need to send USDC to this address to Deposit into Drift (only on mainnet - devnet has a faucet for USDC))
solana address

# Put the private key into your .env to be used by your bot
cd {projectLocation}
echo BOT_PRIVATE_KEY=`cat ~/.config/solana/id.json` >> .env

Concepts

BN / Precision

The Drift SDK uses BigNum (BN), using this package, to represent numerical values. This is because Solana tokens tend to use levels of precision which are too precise for standard Javascript floating point numbers to handle. All numbers in BN are represented as integers, and we will often denote the precision of the number so that it can be converted back down to a regular number.

Example:
a BigNum: 10,500,000, with precision 10^6, is equal to 10.5 because 10,500,000 / 10^6 = 10.5.

The Drift SDK uses some common precisions, which are available as constants to import from the SDK.

Precision NameValue
FUNDING_RATE_BUFFER10^3
QUOTE_PRECISION10^6
PEG_PRECISION10^6
PRICE_PRECISION10^6
AMM_RESERVE_PRECISION10^9
BASE_PRECISION10^9

Important Note for BigNum division

Because BN only supports integers, you need to be conscious of the numbers you are using when dividing. BN will return the floor when using the regular division function; if you want to get the exact division, you need to add the modulus of the two numbers as well. There is a helper function convertToNumber in the SDK which will do this for you.

import {convertToNumber} from @drift-labs/sdk

// Gets the floor value
new BN(10500).div(new BN(1000)).toNumber(); // = 10

// Gets the exact value
new BN(10500).div(new BN(1000)).toNumber() + BN(10500).mod(new BN(1000)).toNumber(); // = 10.5

// Also gets the exact value
convertToNumber(new BN(10500), new BN(1000)); // = 10.5

Examples

Setting up an account and making a trade

import * as anchor from '@coral-xyz/anchor';
import { AnchorProvider } from '@coral-xyz/anchor';
import { getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from '@solana/spl-token';

import { Connection, Keypair, PublicKey } from '@solana/web3.js';
import {
    calculateReservePrice,
    DriftClient,
    User,
    initialize,
    PositionDirection,
    convertToNumber,
    calculateTradeSlippage,
    PRICE_PRECISION,
    QUOTE_PRECISION,
    Wallet,
    PerpMarkets,
    BASE_PRECISION,
    getMarketOrderParams,
    BulkAccountLoader,
    BN,
    calculateBidAskPrice,
    getMarketsAndOraclesForSubscription,
    calculateEstimatedPerpEntryPrice,
} from '../sdk';

export const getTokenAddress = (
    mintAddress: string,
    userPubKey: string
): Promise<PublicKey> => {
    return getAssociatedTokenAddress(
        new PublicKey(mintAddress),
        new PublicKey(userPubKey)
    );
};

const main = async () => {
    const env = 'devnet';
    // const env = 'mainnet-beta';

    // Initialize Drift SDK
    const sdkConfig = initialize({ env });

    // Set up the Wallet and Provider
    if (!process.env.ANCHOR_WALLET) {
        throw new Error('ANCHOR_WALLET env var must be set.');
    }

    if (!process.env.ANCHOR_PROVIDER_URL) {
        throw new Error('ANCHOR_PROVIDER_URL env var must be set.');
    }

    const provider = anchor.AnchorProvider.local(
        process.env.ANCHOR_PROVIDER_URL,
        {
            preflightCommitment: 'confirmed',
            skipPreflight: false,
            commitment: 'confirmed',
        }
    );
    // Check SOL Balance
    const lamportsBalance = await provider.connection.getBalance(
        provider.wallet.publicKey
    );
    console.log(
        provider.wallet.publicKey.toString(),
        env,
        'SOL balance:',
        lamportsBalance / 10 ** 9
    );

    // Misc. other things to set up
    const quoteTokenAddress = await getTokenAddress(
        sdkConfig.QUOTE_MINT_ADDRESS,
        provider.wallet.publicKey.toString()
    );

    // Set up the Drift Client
    const driftPublicKey = new PublicKey(sdkConfig.DRIFT_PROGRAM_ID);
    const bulkAccountLoader = new BulkAccountLoader(
        provider.connection,
        'confirmed',
        1000
    );
    const driftClient = new DriftClient({
        connection: provider.connection,
        wallet: provider.wallet,
        programID: driftPublicKey,
        accountSubscription: {
            type: 'polling',
            accountLoader: bulkAccountLoader,
        },
    });
    await driftClient.subscribe();

    console.log('subscribed to driftClient');

    // Set up user client
    const user = new User({
        driftClient: driftClient,
        userAccountPublicKey: await driftClient.getUserAccountPublicKey(),
        accountSubscription: {
            type: 'polling',
            accountLoader: bulkAccountLoader,
        },
    });

    //// Check if user account exists for the current wallet
    const userAccountExists = await user.exists();

    if (!userAccountExists) {
        console.log(
            'initializing to',
            env,
            ' drift account for',
            provider.wallet.publicKey.toString()
        );

        //// Create a Drift V2 account by Depositing some USDC ($10,000 in this case)
        const depositAmount = new BN(10000).mul(QUOTE_PRECISION);
        await driftClient.initializeUserAccountAndDepositCollateral(
            depositAmount,
            await getTokenAddress(
                usdcTokenAddress.toString(),
                provider.wallet.publicKey.toString()
            )
        );
    }

    await user.subscribe();

    // Get current price
    const solMarketInfo = PerpMarkets[env].find(
        (market) => market.baseAssetSymbol === 'SOL'
    );

    const marketIndex = solMarketInfo.marketIndex;

    // Get vAMM bid and ask price
    const [bid, ask] = calculateBidAskPrice(
        driftClient.getPerpMarketAccount(marketIndex).amm,
        driftClient.getOracleDataForPerpMarket(marketIndex)
    );

    const formattedBidPrice = convertToNumber(bid, PRICE_PRECISION);
    const formattedAskPrice = convertToNumber(ask, PRICE_PRECISION);

    console.log(
        env,
        `vAMM bid: $${formattedBidPrice} and ask: $${formattedAskPrice}`
    );

    const solMarketAccount = driftClient.getPerpMarketAccount(
        solMarketInfo.marketIndex
    );
    console.log(env, `Placing a 1 SOL-PERP LONG order`);

    const txSig = await driftClient.placePerpOrder(
        getMarketOrderParams({
            baseAssetAmount: new BN(1).mul(BASE_PRECISION),
            direction: PositionDirection.LONG,
            marketIndex: solMarketAccount.marketIndex,
        })
    );
    console.log(
        env,
        `Placed a 1 SOL-PERP LONG order. Tranaction signature: ${txSig}`
    );
};

main();

License

Drift Protocol v2 is licensed under Apache 2.0.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Drift SDK by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions.

版本与发布记录

@drift-labs/sdk 共发布 1,598 个版本,首次发布于 2021/11/05;过去 12 个月发布了 86 个版本。

版本发布日期距今
2.163.0-beta.13latest2026/05/126 个月前
2.163.0-beta.122026/05/066 个月前
2.163.0-beta.112026/05/056 个月前
2.163.0-beta.102026/04/286 个月前
2.163.0-beta.92026/04/286 个月前
2.163.0-beta.02026/04/027 个月前

其他发布通道:browser → 2.104.0-beta.20,alpha → 2.150.0-alpha.0,beta → 2.156.0-beta.4,stable → 2.156.0。

关于 @drift-labs/sdk 的常见问题

@drift-labs/sdk 是什么?

SDK for Drift Protocol

如何安装 @drift-labs/sdk?

在项目目录运行 npm install @drift-labs/sdk,或使用 pnpm add / yarn add / bun add。

@drift-labs/sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@drift-labs/sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@drift-labs/sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@drift-labs/sdk 可以商用吗?

@drift-labs/sdk 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@drift-labs/sdk 的下载量有多少?

根据 npm 官方下载统计,@drift-labs/sdk 在 2026/10/13 – 2026/11/11 这 30 天内被下载 64,846 次,日均约 2,162 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@drift-labs/sdk 还在维护吗?

最新版本 2.163.0-beta.13 发布于 2026/05/12(6 个月前);至今共发布 1598 个版本,其中过去 12 个月发布了 86 个;首次发布于 2021/11/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。