@drift-labs/common
Version:
Common functions for Drift
251 lines ⢠11.1 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runCentralServerDriftExample = exports.runAllExamples = exports.settlePnlExample = exports.settleFundingExample = exports.depositWithdrawExample = exports.initializeCentralServerDrift = void 0;
const anchor = __importStar(require("@coral-xyz/anchor"));
const web3_js_1 = require("@solana/web3.js");
const sdk_1 = require("@drift-labs/sdk");
const CentralServerDrift_1 = require("./Drift/clients/CentralServerDrift");
const path = __importStar(require("path"));
// Load environment variables from .env file
const dotenv = require('dotenv');
dotenv.config({ path: path.resolve(__dirname, '.env') });
/**
* Example usage of CentralServerDrift client
*
* This file contains multiple examples demonstrating how to:
* 1. Set up an Anchor wallet with a private key
* 2. Initialize a CentralServerDrift instance
* 3. Create and execute various transaction types
*
* Prerequisites:
* - Create a .env file in the same directory as this example file with:
* ANCHOR_WALLET=[private key byte array]
* ENDPOINT=https://your-rpc-endpoint.com
*
* Usage:
* - Run all examples: ts-node example.ts
* - Run specific example: ts-node example.ts <example-name>
* Available examples: depositWithdraw, settleFunding, settlePnl
*/
// Shared configuration and setup
let centralServerDrift;
let wallet;
const userAccountPublicKey = new web3_js_1.PublicKey('11111111111111111111111111111111'); // enter the publickey for the drift account here
async function initializeCentralServerDrift() {
console.log('š Initializing CentralServerDrift...\n');
// Validate required environment variables
if (!process.env.ANCHOR_WALLET) {
throw new Error('ANCHOR_WALLET must be set');
}
if (!process.env.ENDPOINT) {
throw new Error('ENDPOINT environment variable must be set to your Solana RPC endpoint');
}
// Set up the wallet
wallet = new anchor.Wallet((0, sdk_1.loadKeypair)(process.env.ANCHOR_WALLET));
console.log(`ā
Wallet Public Key: ${wallet.publicKey.toString()}`);
console.log(`ā
RPC Endpoint: ${process.env.ENDPOINT}\n`);
// Initialize CentralServerDrift
console.log('šļø Initializing CentralServerDrift...');
centralServerDrift = new CentralServerDrift_1.CentralServerDrift({
solanaRpcEndpoint: process.env.ENDPOINT,
driftEnv: 'mainnet-beta', // Change to 'devnet' for devnet testing
supportedPerpMarkets: [0, 1, 2], // SOL, BTC, ETH
supportedSpotMarkets: [0, 1], // USDC, SOL
additionalDriftClientConfig: {
// Optional: Add additional DriftClient configuration
txVersion: 0,
txParams: {
computeUnits: 200000,
computeUnitsPrice: 1000,
},
},
});
console.log('ā
CentralServerDrift instance created successfully\n');
// Subscribe to market data
console.log('š” Subscribing to market data...');
await centralServerDrift.subscribe();
console.log('ā
Successfully subscribed to market data\n');
}
exports.initializeCentralServerDrift = initializeCentralServerDrift;
/**
* Reusable function to handle transaction signing and sending
*/
async function executeVersionedTransaction(txn, transactionType) {
console.log(`ā
${transactionType} transaction created successfully`);
console.log(`š Transaction Type: ${txn.constructor.name}`);
console.log('\nš Signing Transaction...');
// Sign with the wallet's keypair
txn.sign([wallet.payer]);
console.log('ā
Transaction signed successfully');
console.log(` Signatures Count After Signing: ${txn.signatures.length}`);
console.log(` First Signature Present: ${txn.signatures[0] && txn.signatures[0].length > 0}`);
console.log('\nš Sending transaction to the network...');
const txSig = await centralServerDrift.sendSignedTransaction(txn);
console.log('ā
Transaction sent successfully!');
console.log(`š Transaction Signature: ${txSig}`);
console.log(`š View on Solscan: https://solscan.io/tx/${txSig}`);
}
/**
* Example 1: Deposit and Withdraw transactions
*/
async function depositWithdrawExample() {
console.log('š Starting Deposit/Withdraw Example...\n');
// Configuration for this example
const amount = new sdk_1.BN(1000000); // 1 USDC (6 decimals)
const spotMarketIndex = 0; // USDC market index
// Example 1: Create a deposit transaction
console.log('--- š„ Creating Deposit Transaction ---');
try {
console.log(`š° Deposit Amount: ${amount.toString()} raw units`);
console.log(`šŖ Spot Market Index: ${spotMarketIndex}`);
const depositTxn = await centralServerDrift.getDepositTxn(userAccountPublicKey, amount, spotMarketIndex);
await executeVersionedTransaction(depositTxn, 'Deposit');
}
catch (error) {
console.error('ā Error during deposit transaction flow:', error);
}
// Example 2: Create a withdraw transaction
console.log('\n--- š¤ Creating Withdraw Transaction ---');
try {
console.log(`š° Withdraw Amount: ${amount.toString()} raw units`);
console.log(`šŖ Spot Market Index: ${spotMarketIndex}`);
const withdrawTxn = await centralServerDrift.getWithdrawTxn(userAccountPublicKey, amount, spotMarketIndex, {
isBorrow: false, // true = borrow, false = reduce-only withdraw
isMax: false, // true = withdraw maximum available
});
await executeVersionedTransaction(withdrawTxn, 'Withdraw');
}
catch (error) {
console.error('ā Error during withdraw transaction flow:', error);
}
}
exports.depositWithdrawExample = depositWithdrawExample;
/**
* Example 2: Settle Funding Payments
*/
async function settleFundingExample() {
console.log('š Starting Settle Funding Example...\n');
console.log('--- š° Creating Settle Funding Transaction ---');
try {
console.log(`š¤ User Account: ${userAccountPublicKey.toString()}`);
console.log('š Settling funding payments for all perp positions...');
const settleFundingTxn = await centralServerDrift.getSettleFundingTxn(userAccountPublicKey);
await executeVersionedTransaction(settleFundingTxn, 'Settle Funding');
}
catch (error) {
console.error('ā Error during settle funding transaction flow:', error);
}
}
exports.settleFundingExample = settleFundingExample;
/**
* Example 3: Settle PnL for Multiple Markets
*/
async function settlePnlExample() {
console.log('š Starting Settle PnL Example...\n');
// Configuration for this example
const marketIndexes = [1]; // BTC-PERP
console.log('--- š Creating Settle PnL Transaction ---');
try {
console.log(`š¤ User Account: ${userAccountPublicKey.toString()}`);
console.log(`š Market Indexes: ${marketIndexes.join(', ')}`);
const settlePnlTxn = await centralServerDrift.getSettlePnlTxn(userAccountPublicKey, marketIndexes);
await executeVersionedTransaction(settlePnlTxn, 'Settle PnL');
}
catch (error) {
console.error('ā Error during settle PnL transaction flow:', error);
}
}
exports.settlePnlExample = settlePnlExample;
/**
* Run all examples in sequence
*/
async function runAllExamples() {
console.log('š Running All CentralServerDrift Examples...\n');
await initializeCentralServerDrift();
console.log('='.repeat(50));
await depositWithdrawExample();
console.log('\n' + '='.repeat(50));
await settleFundingExample();
console.log('\n' + '='.repeat(50));
await settlePnlExample();
}
exports.runAllExamples = runAllExamples;
// Legacy export for backward compatibility
exports.runCentralServerDriftExample = runAllExamples;
// Helper functions for command line handling
function showUsage() {
console.log('š Usage: ts-node example.ts [example-name]');
console.log('\nAvailable examples:');
console.log(' depositWithdraw - Run deposit and withdraw transaction examples');
console.log(' settleFunding - Run settle funding payment transaction example');
console.log(' settlePnl - Run settle PnL transaction example');
console.log(' all - Run all examples in sequence (default)');
console.log('\nExamples:');
console.log(' ts-node example.ts # Run all examples');
console.log(' ts-node example.ts depositWithdraw # Run only deposit/withdraw example');
console.log(' ts-node example.ts settleFunding # Run only settle funding example');
console.log(' ts-node example.ts settlePnl # Run only settle PnL example');
}
async function runCliExample(exampleName) {
const availableExamples = {
depositWithdraw: () => initializeCentralServerDrift().then(() => depositWithdrawExample()),
settleFunding: () => initializeCentralServerDrift().then(() => settleFundingExample()),
settlePnl: () => initializeCentralServerDrift().then(() => settlePnlExample()),
all: runAllExamples,
};
if (exampleName === 'help' ||
exampleName === '--help' ||
exampleName === '-h') {
showUsage();
return;
}
const exampleToRun = exampleName
? availableExamples[exampleName]
: availableExamples['all'];
if (!exampleToRun) {
console.error(`ā Unknown example: ${exampleName}`);
console.error('');
showUsage();
process.exit(1);
}
console.log(`š Running example: ${exampleName || 'all'}\n`);
await exampleToRun();
}
// Command line argument handling
if (require.main === module) {
const args = process.argv.slice(2);
const exampleName = args[0];
runCliExample(exampleName)
.then(() => {
console.log('\n⨠Example execution completed successfully!');
process.exit(0);
})
.catch((error) => {
console.error('\nš„ Example execution failed:', error);
process.exit(1);
});
}
//# sourceMappingURL=example.js.map
;