TypeScript SDK

The Omne TypeScript SDK provides a comprehensive, type-safe interface for building applications on the Omne blockchain. Perfect for Node.js backends and browser applications.

Installation

Package Manager

# Install via npm npm install @omne/sdk # Install via yarn yarn add @omne/sdk # Install via pnpm pnpm add @omne/sdk

TypeScript Configuration

tsconfig.jsonjson
{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "lib": ["ES2020", "DOM"], "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true } }

Browser Support

The SDK works in both Node.js and browser environments. For browser usage, ensure your bundler supports ES modules and includes necessary polyfills.

Quick Start

Basic Setup

import { OmneClient, Network } from '@omne/sdk' // Initialize client const client = new OmneClient({ network: Network.TESTNET, endpoint: 'https://testnet-rpc.omne.foundation', timeout: 30000 // Optional: request timeout in ms }) // Check connection async function checkConnection() { try { const status = await client.getNetworkStatus() console.log('Connected to:', status.networkId) console.log('Latest block:', status.latestBlock) } catch (error) { console.error('Connection failed:', error) } }

Account Management

import { Account, Wallet } from '@omne/sdk' // Create new account const account = await Account.generate() console.log('Address:', account.address) console.log('Public key:', account.publicKey) // Import from private key const importedAccount = Account.fromPrivateKey('your-private-key-hex') // Create wallet for multiple accounts const wallet = new Wallet() wallet.addAccount(account) wallet.addAccount(importedAccount) // Get account by address const foundAccount = wallet.getAccount('omne1...')

Core Features

✨ Type Safety

  • • Full TypeScript definitions
  • • IntelliSense support
  • • Compile-time error checking
  • • Auto-completion for all methods

🚀 Async/Await

  • • Promise-based API
  • • Modern async/await syntax
  • • Error handling with try/catch
  • • Cancellable operations

🔄 Real-time Events

  • • WebSocket subscriptions
  • • Event emitter patterns
  • • Auto-reconnection
  • • Filtered event streams

🛡️ Error Handling

  • • Detailed error types
  • • Network error recovery
  • • Transaction validation
  • • Retry mechanisms

Working with Transactions

Simple Transfer

import { TransferTransaction } from '@omne/sdk' async function sendTransfer() { const tx = new TransferTransaction({ from: account.address, to: 'omne1recipient-address', amount: '1000000', // 1 OMNE in micro-OMNE fee: 'auto', // Auto fee estimation memo: 'Payment for services' // Optional memo }) // Sign transaction const signedTx = await account.sign(tx) // Broadcast to network const result = await client.broadcast(signedTx) console.log('Transaction hash:', result.hash) // Wait for confirmation const receipt = await client.waitForTransaction(result.hash) console.log('Confirmed in block:', receipt.blockNumber) return receipt }

Batch Transactions

import { BatchTransaction } from '@omne/sdk' async function sendBatch() { const batch = new BatchTransaction() // Add multiple transfers batch.addTransfer({ to: 'omne1recipient1', amount: '500000' }) batch.addTransfer({ to: 'omne1recipient2', amount: '300000' }) // Sign and broadcast const signedBatch = await account.sign(batch) const result = await client.broadcast(signedBatch) return result }

Transaction Monitoring

// Monitor transaction status async function monitorTransaction(txHash: string) { const tx = await client.getTransaction(txHash) console.log('Status:', tx.status) console.log('Block:', tx.blockNumber) console.log('Confirmations:', tx.confirmations) console.log('Gas used:', tx.gasUsed) if (tx.status === 'failed') { console.error('Error:', tx.error) } } // Subscribe to account transactions client.onTransaction(account.address, (tx) => { console.log('New transaction:', tx.hash) console.log('Amount:', tx.amount) console.log('Direction:', tx.direction) // 'in' or 'out' })

Smart Contracts

Contract Deployment

import { Contract } from '@omne/sdk' async function deployContract() { const contract = new Contract({ bytecode: contractBytecode, abi: contractABI, constructorArgs: ['initial_value', 1000] }) const deployment = await contract.deploy(account) console.log('Contract address:', deployment.address) return deployment }

Contract Interaction

// Connect to existing contract const contract = new Contract({ address: 'omne1contract-address', abi: contractABI }) // Read contract state (free) const balance = await contract.call('getBalance', ['omne1user-address']) console.log('Balance:', balance) // Write contract state (requires transaction) const result = await contract.execute( account, 'transfer', ['omne1recipient', '1000000'], { fee: 'auto' } ) console.log('Transaction hash:', result.hash)

Event Listening

// Listen to contract events contract.onEvent('Transfer', (event) => { console.log('Transfer event:') console.log('From:', event.from) console.log('To:', event.to) console.log('Amount:', event.amount) }) // Listen to specific events with filters contract.onEvent('Transfer', (event) => { console.log('Transfer to my address:', event) }, { filter: { to: account.address } })

Querying the Blockchain

Account Information

// Get account balance const balance = await client.getBalance('omne1address') console.log('Balance:', balance.amount, balance.denom) // Get account details const accountInfo = await client.getAccount('omne1address') console.log('Sequence:', accountInfo.sequence) console.log('Account number:', accountInfo.accountNumber) // Get transaction history const history = await client.getTransactionHistory('omne1address', { limit: 20, offset: 0, direction: 'both' // 'in', 'out', or 'both' }) history.transactions.forEach(tx => { console.log(`${tx.hash}: ${tx.amount} OMNE`) })

Network Information

// Get network status const status = await client.getNetworkStatus() console.log('Network ID:', status.networkId) console.log('Latest block:', status.latestBlock) console.log('Total validators:', status.totalValidators) // Get block information const block = await client.getBlock(12345) console.log('Block hash:', block.hash) console.log('Timestamp:', block.timestamp) console.log('Transactions:', block.transactions.length) // Get validator set const validators = await client.getValidators() validators.forEach(v => { console.log(`${v.address}: ${v.votingPower} voting power`) })

Real-time Features

WebSocket Subscriptions

// Subscribe to new blocks client.onNewBlock((block) => { console.log('New block:', block.height) console.log('Transactions:', block.transactions.length) }) // Subscribe to new transactions client.onNewTransaction((tx) => { console.log('New transaction:', tx.hash) console.log('Fee:', tx.fee) }) // Subscribe to validator set changes client.onValidatorSetChange((validators) => { console.log('Validator set updated') console.log('Active validators:', validators.length) })

Connection Management

// Handle connection events client.on('connected', () => { console.log('Connected to Omne network') }) client.on('disconnected', () => { console.log('Disconnected from network') }) client.on('reconnecting', (attempt) => { console.log(`Reconnecting... attempt ${attempt}`) }) // Manual connection control await client.connect() await client.disconnect() // Check connection status if (client.isConnected()) { console.log('Client is connected') }

Advanced Configuration

Client Options

import { OmneClient, Network } from '@omne/sdk' const client = new OmneClient({ // Network configuration network: Network.MAINNET, endpoint: 'https://rpc.omne.foundation', // Request configuration timeout: 30000, retries: 3, retryDelay: 1000, // WebSocket configuration wsEndpoint: 'wss://ws.omne.foundation', wsReconnect: true, wsReconnectDelay: 5000, // Fee configuration defaultFee: '1000', feeMultiplier: 1.2, // Gas configuration defaultGas: 200000, gasMultiplier: 1.5, // HTTP headers headers: { 'User-Agent': 'MyApp/1.0.0' } })

Custom Network

// Define custom network const customNetwork = { networkId: 'omne-devnet-1', chainId: 'omne-devnet', rpcEndpoint: 'http://localhost:26657', wsEndpoint: 'ws://localhost:26657/websocket', addressPrefix: 'omne', coinType: 118, gasPrice: '0.001', feeDenom: 'uomne' } const client = new OmneClient({ network: customNetwork, endpoint: customNetwork.rpcEndpoint })

Error Handling

Error Types

import { OmneError, NetworkError, TransactionError, ValidationError } from '@omne/sdk' try { const result = await client.transfer({ from: account.address, to: 'invalid-address', amount: '1000000' }) } catch (error) { if (error instanceof ValidationError) { console.error('Validation failed:', error.message) console.error('Field:', error.field) } else if (error instanceof NetworkError) { console.error('Network error:', error.message) console.error('Status code:', error.statusCode) } else if (error instanceof TransactionError) { console.error('Transaction failed:', error.message) console.error('Code:', error.code) } else { console.error('Unknown error:', error) } }

Retry Logic

async function robustTransfer(params: TransferParams) { const maxRetries = 3 let lastError: Error for (let attempt = 1; attempt <= maxRetries; attempt++) { try { return await client.transfer(params) } catch (error) { lastError = error if (error instanceof NetworkError && attempt < maxRetries) { console.log(`Attempt ${attempt} failed, retrying...`) await new Promise(resolve => setTimeout(resolve, 1000 * attempt)) continue } throw error } } throw lastError }

Complete Examples

Payment Processor

import { OmneClient, Account, Network } from '@omne/sdk' class PaymentProcessor { private client: OmneClient private account: Account constructor(privateKey: string) { this.client = new OmneClient({ network: Network.MAINNET, endpoint: 'https://rpc.omne.foundation' }) this.account = Account.fromPrivateKey(privateKey) } async processPayment(to: string, amount: string, orderId: string) { try { // Create payment transaction const tx = await this.client.transfer({ from: this.account.address, to, amount, memo: `Order: ${orderId}` }) // Sign and broadcast const signedTx = await this.account.sign(tx) const result = await this.client.broadcast(signedTx) // Wait for confirmation const receipt = await this.client.waitForTransaction(result.hash) return { success: true, txHash: result.hash, blockNumber: receipt.blockNumber, orderId } } catch (error) { return { success: false, error: error.message, orderId } } } async getBalance(): Promise<string> { const balance = await this.client.getBalance(this.account.address) return balance.amount } }

Next Steps

API Reference

Complete TypeScript API documentation with all methods and types.

View API docs →

Examples

Real-world examples and implementation patterns.

Browse examples →

GitHub

Source code, issues, and contributions welcome.

View on GitHub →