TypeScript SDK
Official TypeScript SDK for the Realm blockchain. 100% API coverage, full TypeScript types, works in Node.js and browsers.
Installation
bash
npm install @empyrealm/sdk
Requirements
Node.js 18+ required. The SDK uses ESM modules. TypeScript types are included — no separate
@types package needed.Quick Start
typescript
import { RealmClient, RealmWallet } from '@empyrealm/sdk';// Create clientconst client = new RealmClient('https://api.realm.software');// Generate or restore walletconst wallet = await RealmWallet.generate();// const wallet = await RealmWallet.fromSeed('0x...');// Connect (authenticates all future requests)await client.connect(wallet);// Now you can call any methodconst balance = await client.getBalance();const positions = await client.getPositions();
Wallet Management
typescript
// Generate new walletconst wallet = await RealmWallet.generate();console.log('Address:', wallet.address);console.log('Seed:', wallet.toSeed()); // Back this up!// Restore from seedconst restored = await RealmWallet.fromSeed('0x...');// Restore from secret key bytesconst fromKey = await RealmWallet.fromSecretKey(secretKeyBytes);// Export for backupconst seed = wallet.toSeed(); // Hex stringconst secretKey = wallet.secretKey; // Uint8Array (4032 bytes)const publicKey = wallet.publicKey; // Uint8Array (1952 bytes)
Security
Never share your seed or secret key. Store backups securely. The seed is all that's needed to restore full access to your account.
Public Methods
These don't require authentication:
typescript
// No authentication required for these// Health checkconst pong = await client.ping();// Chain infoconst info = await client.getChainInfo();console.log('Block height:', info.blockHeight);// List marketsconst markets = await client.getMarkets();// Get orderbookconst book = await client.getOrderbook('RLM-PERP', { depth: 20 });console.log('Best bid:', book.bids[0]?.price);// Recent tradesconst trades = await client.getTrades('RLM-PERP', { limit: 50 });// Funding rateconst funding = await client.getFundingRate('RLM-PERP');// Mark priceconst mark = await client.getMarkPrice('RLM-PERP');
Account Methods
Require client.connect(wallet) first:
typescript
// Requires authentication (client.connect())// Get all balancesconst balance = await client.getBalance();console.log('RLM L1:', balance.rlmL1);console.log('RLM Exchange:', balance.rlmExchange);console.log('USDC L1:', balance.usdcL1);console.log('USDC Exchange:', balance.usdcExchange);// Account summaryconst summary = await client.getAccountSummary();// Open ordersconst orders = await client.getOpenOrders();const marketOrders = await client.getOpenOrders('RLM-PERP');// Single orderconst order = await client.getOrder('12345678');// Order historyconst history = await client.getOrderHistory({ limit: 100 });// Positionsconst positions = await client.getPositions();const rlmPos = await client.getPositions('RLM-PERP');// Fillsconst fills = await client.getFills({ limit: 50 });// Funding historyconst fundingHistory = await client.getFundingHistory();// Conditional orders (stop-loss, take-profit, etc.)const conditionals = await client.getConditionalOrders();// Portfolio margin statusconst margin = await client.getPortfolioMargin();
Trading Methods
typescript
// Deposit (L1 → Exchange)await client.deposit({ token: 'RLM', amount: 1000 });await client.deposit({ token: 'USDC', amount: 5000 });// Withdraw (Exchange → L1)await client.withdraw({ token: 'RLM', amount: 500 });// Transfer between accountsawait client.transfer({token: 'USDC',amount: 100,toAddress: '0x...',});// Place limit orderconst order = await client.placeOrder({market: 'RLM-PERP',side: 'buy',type: 'limit',price: 100.00,size: 1.0,timeInForce: 'GTC',});// Place market orderconst marketOrder = await client.placeOrder({market: 'RLM-PERP',side: 'sell',type: 'market',size: 0.5,});// Stop-loss orderconst stopLoss = await client.placeOrder({market: 'RLM-PERP',side: 'sell',type: 'stop_market',size: 1.0,triggerPrice: 90.00,triggerDirection: 'below',reduceOnly: true,});// Take-profit orderconst takeProfit = await client.placeOrder({market: 'RLM-PERP',side: 'sell',type: 'take_profit',size: 1.0,triggerPrice: 120.00,triggerDirection: 'above',reduceOnly: true,});// Trailing stop (5% trail)const trailingStop = await client.placeOrder({market: 'RLM-PERP',side: 'sell',type: 'trailing_stop',size: 1.0,trailPercent: 5.0,reduceOnly: true,});// Amend order (change price/size)await client.amendOrder({orderId: '12345678',price: 101.00,size: 1.5,});// Cancel orderawait client.cancelOrder('12345678');// Cancel all ordersawait client.cancelAllOrders();await client.cancelAllOrders('RLM-PERP'); // Specific market// Cancel conditional orderawait client.cancelConditionalOrder('87654321');// Batch ordersawait client.batchOrders({place: [{ market: 'RLM-PERP', side: 'buy', type: 'limit', price: 99, size: 1 },{ market: 'RLM-PERP', side: 'buy', type: 'limit', price: 98, size: 1 },],cancel: ['12345678', '12345679'],});
Real-time Streaming
typescript
// Subscribe to real-time updatesconst stream = await client.subscribe({markets: ['RLM-PERP'],orderbook: true,trades: true,positions: true,orders: true,fills: true,});// Handle eventsstream.on('orderbook', (update) => {console.log('Orderbook:', update.bids.length, 'bids,', update.asks.length, 'asks');});stream.on('trade', (trade) => {console.log('Trade:', trade.price, 'x', trade.size);});stream.on('position', (position) => {console.log('Position:', position.side, position.size, 'PnL:', position.unrealizedPnl);});stream.on('order', (order) => {console.log('Order:', order.orderId, order.status);});stream.on('fill', (fill) => {console.log('Fill:', fill.price, 'x', fill.size, 'fee:', fill.fee);});stream.on('error', (error) => {console.error('Stream error:', error);});// Cleanupstream.close();
TypeScript Types
All types are exported for use in your code:
typescript
// All types are exportedimport type {Balance,Position,Order,OrderSide,OrderType,OrderStatus,TimeInForce,TriggerDirection,Market,Orderbook,PriceLevel,Trade,Fill,ConditionalOrder,PortfolioMargin,PlaceOrderParams,AmendOrderParams,DepositParams,WithdrawParams,} from '@empyrealm/sdk';// Example usageconst params: PlaceOrderParams = {market: 'RLM-PERP',side: 'buy',type: 'limit',price: 100.00,size: 1.0,};
Error Handling
The SDK throws errors with descriptive messages:
typescript
try {await client.placeOrder({ ... });} catch (error) {if (error.code === 'INSUFFICIENT_BALANCE') {console.log('Not enough funds');} else if (error.code === 'INVALID_ORDER') {console.log('Invalid order params:', error.message);} else {throw error;}}
Browser Usage
The SDK works in browsers automatically. It uses gRPC-Web via our Envoy proxy at api.realm.software.
typescript
// Works in React, Vue, Svelte, etc.import { RealmClient, RealmWallet } from '@empyrealm/sdk';const client = new RealmClient('https://api.realm.software');// Same API as Node.js
Complete API Reference
For detailed parameter documentation, see the API Reference.