UNPKG

@drift-labs/common

Version:

Common functions for Drift

251 lines • 11.1 kB
"use strict"; 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