Buy + Sell
A complete buy/sell round-trip that validates your credentials work end-to-end.
git clone https://github.com/darkfibre-dev/darkfibre-examples.gitcd darkfibre-examples/02-buy-sellnpm installcp .env.example .envEdit .env with your credentials:
DARKFIBRE_API_KEY=your-api-keySOLANA_PRIVATE_KEY=your-base58-private-keyEdit index.ts to set the MINT constant to the token you want to trade.
npm startimport { DarkfibreSDK, APIError, ValidationError, SigningError } from '@darkfibre/sdk';import 'dotenv/config';
// Configurationconst MINT = 'YOUR_TOKEN_MINT_HERE'; // Token to tradeconst SOL_AMOUNT = 0.005; // SOL to spend on buyconst SLIPPAGE = 0.05; // 5% slippage toleranceconst PRIORITY = 'fast' as const; // Transaction priority
// Validate Environmentconst { DARKFIBRE_API_KEY, SOLANA_PRIVATE_KEY } = process.env;
if (!DARKFIBRE_API_KEY) { console.error('Missing DARKFIBRE_API_KEY in .env'); process.exit(1);}
if (!SOLANA_PRIVATE_KEY) { console.error('Missing SOLANA_PRIVATE_KEY in .env'); process.exit(1);}
// Mainconst sdk = new DarkfibreSDK({ apiKey: DARKFIBRE_API_KEY, privateKey: SOLANA_PRIVATE_KEY,});
try { // Buy console.log(`\n[BUY] Buying tokens with ${SOL_AMOUNT} SOL...`);
const buyResult = await sdk.buy({ mint: MINT, solAmount: SOL_AMOUNT, slippage: SLIPPAGE, priority: PRIORITY, });
console.log(`[BUY] Success!`); console.log(` Tokens received: ${buyResult.tradeResult.outputAmount}`); console.log(` SOL spent: ${buyResult.tradeResult.inputAmount}`); console.log(` Priority fee: ${buyResult.priorityCost} SOL`); console.log(` https://solscan.io/tx/${buyResult.signature}`);
// Wait await new Promise((resolve) => setTimeout(resolve, 1000));
// Sell console.log(`\n[SELL] Selling ${buyResult.tradeResult.outputAmount} tokens...`);
const sellResult = await sdk.sell({ mint: MINT, tokenAmount: buyResult.tradeResult.outputAmount, slippage: SLIPPAGE, priority: PRIORITY, });
console.log(`[SELL] Success!`); console.log(` Tokens sold: ${sellResult.tradeResult.inputAmount}`); console.log(` SOL received: ${sellResult.tradeResult.outputAmount}`); console.log(` Priority fee: ${sellResult.priorityCost} SOL`); console.log(` https://solscan.io/tx/${sellResult.signature}`);} catch (error) { if (error instanceof ValidationError) { console.error(`\n[ERROR] Validation: ${error.message}`); if (error.field) { console.error(` Field: ${error.field}`); } } else if (error instanceof SigningError) { console.error(`\n[ERROR] Signing: ${error.message}`); console.error(' Check that your private key is valid and in base58 format.'); } else if (error instanceof APIError) { console.error(`\n[ERROR] API [${error.code}]: ${error.message}`); } else { throw error; } process.exit(1);}What It Does
Section titled “What It Does”- Initializes the SDK with your credentials
- Buys tokens with SOL
- Waits 1 second
- Sells all tokens back for SOL
- Prints detailed transaction info with Solscan links
Configuration
Section titled “Configuration”Edit index.ts to change:
| Variable | Description | Default |
|---|---|---|
MINT | Token mint address to trade | - |
SOL_AMOUNT | Amount of SOL to spend on buy | 0.005 |
SLIPPAGE | Slippage tolerance (0.05 = 5%) | 0.05 |
PRIORITY | Transaction priority | 'fast' |
Error Handling
Section titled “Error Handling”This example demonstrates handling all SDK error types:
| Error Type | Description |
|---|---|
APIError | API failures (auth, validation, insufficient funds) |
ValidationError | Trade limit exceeded (maxPriceImpact, maxPriorityCost) |
SigningError | Transaction signing failures |
Expected Output
Section titled “Expected Output”[BUY] Buying tokens with 0.005 SOL...[BUY] Success! Tokens received: 1234567.89 SOL spent: 0.005 Priority fee: 0.0001 SOL https://solscan.io/tx/5xK7j...abc123
[SELL] Selling 1234567.89 tokens...[SELL] Success! Tokens sold: 1234567.89 SOL received: 0.00495 Priority fee: 0.0001 SOL https://solscan.io/tx/3mN8p...def456Related
Section titled “Related”- SDK Overview - Installation and setup
- buy() - Buy method documentation
- sell() - Sell method documentation
- Error Handling - Handle all error types