@wenrwa/trading-sdk
v0.2.0
Published
TypeScript SDK for the Wenrwa Trading API — swap, transfer, quote, and manage Solana wallets via API key auth
Maintainers
Readme
@wenrwa/trading-sdk
TypeScript SDK for the Wenrwa Trading API — swap tokens, transfer funds, manage wallets, and execute batch trades on Solana via API key auth.
Install
npm install @wenrwa/trading-sdkZero runtime dependencies — pure TypeScript using native fetch.
Quick Start
import { TradingClient } from '@wenrwa/trading-sdk';
// 1. Register and get an API key
const client = new TradingClient({ apiUrl: 'https://app.wenrwa.com/api/v1' });
const { apiKey, publicKey, secretKey } = await client.register({
mainWalletPubkey: 'YourSolanaWalletPublicKey...',
});
// 2. Use the API key for all subsequent requests
const authedClient = new TradingClient({
apiUrl: 'https://app.wenrwa.com/api/v1',
apiKey,
});
// 3. Swap SOL → USDC
const swap = await authedClient.swap({
inputMint: 'So11111111111111111111111111111111111111112',
outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
amount: '100000000', // 0.1 SOL in lamports
walletSecretKey: secretKey,
});
console.log(`Swapped! Tx: ${swap.signature}`);
// 4. Check balances
const balance = await authedClient.getBalance();
console.log(balance.balances); // [{ symbol: 'SOL', uiAmount: 0.9 }, { symbol: 'USDC', uiAmount: 5.23 }]Constructor
const client = new TradingClient({
apiUrl: 'https://app.wenrwa.com/api/v1', // Required
apiKey: 'your-api-key', // Optional (sent as X-API-Key header)
timeout: 30000, // Optional (ms, default: 30000)
});API Reference
Registration
// Register a new trading account (generates a custodial trading wallet)
const result = await client.register({
mainWalletPubkey: 'YourMainWallet...',
name: 'My Trading Bot', // Optional
});
// Returns: { apiKey, publicKey, secretKey, tradingWalletId }
// Register with an existing wallet (proof-of-ownership via signature)
await client.registerExisting({
mainWalletPubkey: '...',
tradingWalletPubkey: '...',
signature: '...',
timestamp: Date.now(),
});Account
// Get account details (API key info, wallet, webhook config)
const account = await client.getAccount();
// Set webhook URL for trade notifications
await client.setWebhook({ url: 'https://my-server.com/webhook' });
// Returns: { webhookUrl, webhookSecret }
// Delete webhook
await client.deleteWebhook();
// Send a test webhook event
await client.testWebhook();Swap
Three modes for swapping tokens:
// All-in-one: build + sign + submit (simplest)
const result = await client.swap({
inputMint: 'So11111111111111111111111111111111111111112',
outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
amount: '100000000',
walletSecretKey: '...', // Trading wallet secret key
slippageBps: 50, // Optional (default: server-side)
maxSlippageBps: 300, // Optional
priorityLevel: 'medium', // Optional: 'low' | 'medium' | 'high'
});
// Returns: { signature, status, inputAmount, outputAmount, routePlan, feeAmount }
// Build-only: get unsigned transaction for external signing
const built = await client.buildSwap({
inputMint: '...',
outputMint: '...',
amount: '100000000',
});
// Returns: { transaction, quote, lastValidBlockHeight }
// Submit a pre-signed transaction
const submitted = await client.submitSwap({
signedTransaction: '...', // Base64-encoded signed transaction
});
// Returns: { signature, status }Transfer
const result = await client.transfer({
mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
recipientAddress: 'RecipientWallet...',
amount: '1000000', // 1 USDC (6 decimals)
walletSecretKey: '...',
priorityLevel: 'medium', // Optional
});
// Returns: { signature, status, amountSent, feeAmount }Quote
const quote = await client.getQuote({
inputMint: 'So11111111111111111111111111111111111111112',
outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
amount: '100000000',
slippageBps: 50, // Optional
});
// Returns: { inputAmount, outputAmount, priceImpact, platformFeeBps, routePlan }Balance
// Primary trading wallet balance
const balance = await client.getBalance();
// Specific wallet balance (by wallet ID)
const balance2 = await client.getBalanceByWalletId(2);
// Returns: { walletPubkey, balances: [{ mint, symbol, amount, uiAmount, decimals }] }Tokens
// Search tokens by name or symbol
const results = await client.searchTokens('USDC');
// Returns: { tokens: [{ mint, symbol, name, decimals, logoURI, isVerified }] }
// Get info for a specific token mint
const info = await client.getTokenInfo('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
// Returns: { token: { mint, symbol, name, decimals, ... } }Transactions
// List recent transactions
const txs = await client.getTransactions({ limit: 20, offset: 0 });
// Returns: { transactions: [{ id, type, signature, status, inputMint, outputMint, ... }], total }
// Get status of a specific transaction
const status = await client.getTransactionStatus('5xYz...');
// Returns: { signature, status }Wallets
// Create additional trading wallet
const wallet = await client.createWallet({ name: 'Arbitrage Bot' });
// Returns: { publicKey, secretKey, tradingWalletId }
// List all wallets
const wallets = await client.listWallets();
// Returns: { wallets: [{ tradingWalletId, publicKey, name, type, createdAt }] }Keys
// Generate a new API key for a specific trading wallet
const key = await client.generateKey({
tradingWalletId: 1,
name: 'Read-only key', // Optional
permissions: ['read'], // Optional
});
// Returns: { apiKey, keyId, prefix }Cart (Batch Swaps)
Queue multiple swaps and execute them in a single batch:
// Add items to cart
await client.addCartItem({
inputMint: 'So11111111111111111111111111111111111111112',
outputMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
amount: '100000000',
slippageBps: 50,
});
await client.addCartItem({
inputMint: 'So11111111111111111111111111111111111111112',
outputMint: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263', // BONK
amount: '50000000',
});
// View cart
const cart = await client.getCart();
// Update an item
await client.updateCartItem(cart.items[0].id, { amount: '200000000' });
// Remove an item
await client.removeCartItem(cart.items[1].id);
// Clear entire cart
await client.clearCart();
// Execute all cart items
const results = await client.executeCart({
walletSecretKey: '...',
continueOnError: true, // Optional: continue if one swap fails
});
// Returns: { results: [...], totalExecuted, totalSucceeded, totalFailed }Error Handling
All errors are normalized to TradingError:
import { TradingError } from '@wenrwa/trading-sdk';
try {
await client.swap({ ... });
} catch (err) {
if (err instanceof TradingError) {
console.log(err.code); // 'INSUFFICIENT_BALANCE', 'TIMEOUT', etc.
console.log(err.statusCode); // HTTP status (408 for timeout, 0 for network)
console.log(err.message); // Human-readable message
}
}Internal error codes: TIMEOUT (408), NETWORK_ERROR (0), UNKNOWN_ERROR (pass-through from server).
Webhook Events
If you configure a webhook URL, the server sends POST requests for trade events:
type WebhookEventType = 'transaction.confirmed' | 'transaction.failed' | 'test';
interface WebhookPayload {
event: WebhookEventType;
timestamp: string;
data: {
txId?: number;
type?: string;
status?: string;
signature?: string;
inputMint?: string;
outputMint?: string;
inputAmount?: string;
outputAmount?: string;
feeAmount?: string;
error?: string;
};
}Verify webhook authenticity using the webhookSecret returned from setWebhook().
License
MIT
