安装
npm i @drift-labs/sdk
开始
如果你是和"漂流"融合的话,从这里开始!
- 漂流 v2- 老师 + API Docs
- 在 Typescript 和 Python 中使用 SDK 的文档和示例
- 整合漂流时有用的概念和实例
- 为 Drift 的“ Data API” 提供文档
- 打印 API 文件
- JSDoc 漂流v2 Typescript SDK 的自动文档
- 漂移文件
- 漂流综合通用文件
下面是使用索拉纳和德利夫特的打字机sdk的轻快概览. 如果您想要综合文件, 并举例说明如何与漂流融合, 请使用 v2 教师文件。 。 。 .
为您的程序设置钱包
# 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
概念
BN / 精确度
漂流 SDK 使用 BigNum (BN), 使用 此软件包,以表示数值。 这是因为索拉纳令牌倾向于使用精度水平,而精度水平对于标准的Javascript浮点数来说过于精确而难以处理. BN中的所有数字都以整数表示,我们将经常表示 precision 中的数字,以便将其转换回正数.
Example:
a BigNum: 10,500,000, with precision 10^6, is equal to 10.5 because 10,500,000 / 10^6 = 10.5.
Drift SDK使用一些常见的精度,这些精度可以作为常数从SDK导入.
| 精密名称 | 数值 |
|---|---|
| 筹资 资金 资金 | 第10^3号 |
| 卡塔尔 棱镜 | 第10^6号 |
| 图片 | 第10^6号 |
| 定价 | 第10^6号 |
| (法语) | 第10^9号 |
| 贝斯-棱镜 | 第10^9号 |
BigNum 分区的重要说明
因为BN只支持整数,所以要注意除去时所使用的数字. BN在使用正则分函数时会返回地层;如果想要得到准确的分出,需要也添加两个数字的模组. 有一个助手函数 convertToNumber 在SDK里会为你做这个.
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
实例
设立账户和进行交易
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();
许可证
《漂流议定书》v2根据 Apache 2.0 (英语)。 。 。 .
除非您另有明确声明,否则有意提交的任何捐款 如Apache-2.0许可证所定义,由您列入漂流式SDK,应为 (b) 在不附加任何条件的情况下,获得上述许可.