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 client
const client = new RealmClient('https://api.realm.software');
// Generate or restore wallet
const wallet = await RealmWallet.generate();
// const wallet = await RealmWallet.fromSeed('0x...');
// Connect (authenticates all future requests)
await client.connect(wallet);
// Now you can call any method
const balance = await client.getBalance();
const positions = await client.getPositions();

Wallet Management

typescript
// Generate new wallet
const wallet = await RealmWallet.generate();
console.log('Address:', wallet.address);
console.log('Seed:', wallet.toSeed()); // Back this up!
// Restore from seed
const restored = await RealmWallet.fromSeed('0x...');
// Restore from secret key bytes
const fromKey = await RealmWallet.fromSecretKey(secretKeyBytes);
// Export for backup
const seed = wallet.toSeed(); // Hex string
const 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 check
const pong = await client.ping();
// Chain info
const info = await client.getChainInfo();
console.log('Block height:', info.blockHeight);
// List markets
const markets = await client.getMarkets();
// Get orderbook
const book = await client.getOrderbook('RLM-PERP', { depth: 20 });
console.log('Best bid:', book.bids[0]?.price);
// Recent trades
const trades = await client.getTrades('RLM-PERP', { limit: 50 });
// Funding rate
const funding = await client.getFundingRate('RLM-PERP');
// Mark price
const mark = await client.getMarkPrice('RLM-PERP');

Account Methods

Require client.connect(wallet) first:

typescript
// Requires authentication (client.connect())
// Get all balances
const 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 summary
const summary = await client.getAccountSummary();
// Open orders
const orders = await client.getOpenOrders();
const marketOrders = await client.getOpenOrders('RLM-PERP');
// Single order
const order = await client.getOrder('12345678');
// Order history
const history = await client.getOrderHistory({ limit: 100 });
// Positions
const positions = await client.getPositions();
const rlmPos = await client.getPositions('RLM-PERP');
// Fills
const fills = await client.getFills({ limit: 50 });
// Funding history
const fundingHistory = await client.getFundingHistory();
// Conditional orders (stop-loss, take-profit, etc.)
const conditionals = await client.getConditionalOrders();
// Portfolio margin status
const 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 accounts
await client.transfer({
token: 'USDC',
amount: 100,
toAddress: '0x...',
});
// Place limit order
const order = await client.placeOrder({
market: 'RLM-PERP',
side: 'buy',
type: 'limit',
price: 100.00,
size: 1.0,
timeInForce: 'GTC',
});
// Place market order
const marketOrder = await client.placeOrder({
market: 'RLM-PERP',
side: 'sell',
type: 'market',
size: 0.5,
});
// Stop-loss order
const stopLoss = await client.placeOrder({
market: 'RLM-PERP',
side: 'sell',
type: 'stop_market',
size: 1.0,
triggerPrice: 90.00,
triggerDirection: 'below',
reduceOnly: true,
});
// Take-profit order
const 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 order
await client.cancelOrder('12345678');
// Cancel all orders
await client.cancelAllOrders();
await client.cancelAllOrders('RLM-PERP'); // Specific market
// Cancel conditional order
await client.cancelConditionalOrder('87654321');
// Batch orders
await 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 updates
const stream = await client.subscribe({
markets: ['RLM-PERP'],
orderbook: true,
trades: true,
positions: true,
orders: true,
fills: true,
});
// Handle events
stream.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);
});
// Cleanup
stream.close();

TypeScript Types

All types are exported for use in your code:

typescript
// All types are exported
import type {
Balance,
Position,
Order,
OrderSide,
OrderType,
OrderStatus,
TimeInForce,
TriggerDirection,
Market,
Orderbook,
PriceLevel,
Trade,
Fill,
ConditionalOrder,
PortfolioMargin,
PlaceOrderParams,
AmendOrderParams,
DepositParams,
WithdrawParams,
} from '@empyrealm/sdk';
// Example usage
const 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.