Skip to Content
Developers APIDaemon API

Daemon API

The TOS Network Daemon API provides comprehensive access to blockchain data and network operations. Built on the principle of “Don’t Trust, Verify it”, all data returned by the daemon can be cryptographically verified.

Overview

The Daemon API enables developers to:

  • Query Blockchain Data: Access blocks, transactions, and network state
  • Submit Transactions: Broadcast signed transactions to the network
  • Monitor Network: Subscribe to real-time events and updates
  • Manage Mining: Control mining operations and retrieve statistics
  • Verify Proofs: Validate cryptographic proofs and signatures

Connection Methods

HTTP JSON-RPC

Endpoint: https://node.tos.network/json_rpc (Mainnet) Endpoint: https://testnode.tos.network/json_rpc (Testnet)

// Basic HTTP connection const response = await fetch('https://node.tos.network/json_rpc', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ jsonrpc: '2.0', method: 'get_info', params: {}, id: 1 }) }); const result = await response.json();

WebSocket Connection

Endpoint: wss://node.tos.network/ws (Mainnet) Endpoint: wss://testnode.tos.network/ws (Testnet)

const ws = new WebSocket('wss://node.tos.network/ws'); ws.onopen = () => { // Send JSON-RPC request ws.send(JSON.stringify({ jsonrpc: '2.0', method: 'subscribe', params: { event: 'new_block' }, id: 1 })); }; ws.onmessage = (event) => { const data = JSON.parse(event.data); console.log('Received:', data); };

Authentication

API Key Authentication

// With API key for increased rate limits const response = await fetch('https://node.tos.network/json_rpc', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-api-key-here' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'get_info', params: {}, id: 1 }) });

Rate Limits

TierRequests/HourWebSocket Connections
Public1,0005
Authenticated10,00025
Premium100,000100

Core API Methods

Network Information

get_version

Get daemon version and network information.

// Request { "jsonrpc": "2.0", "method": "get_version", "params": {}, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "version": "1.2.0", "network": "mainnet", "protocol_version": 1, "api_version": "1.0", "build_commit": "a1b2c3d4", "build_date": "2024-01-15T10:30:00Z" }, "id": 1 }

get_info

Get current blockchain and network information.

// Request { "jsonrpc": "2.0", "method": "get_info", "params": {}, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "height": 1250000, "topoheight": 1250123, "stable_height": 1249990, "network": "mainnet", "difficulty": { "hashrate": "125500000000000", "difficulty": "0x1a2b3c4d5e6f", "ai_hashrate": "15500000000000", "ai_difficulty": "0x2b3c4d5e6f7a" }, "mempool_size": 156, "peer_count": 47, "average_block_time": 15200, "block_time_target": 15000, "total_supply": "21000000000000000", "circulating_supply": "8750000000000000", "staked_supply": "2100000000000000", "median_fee": "1000000", "pruned": false }, "id": 1 }

get_height

Get current blockchain height.

// Request { "jsonrpc": "2.0", "method": "get_height", "params": {}, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "height": 1250000, "topoheight": 1250123, "stable_height": 1249990 }, "id": 1 }

Block Operations

get_block_template

Get block template for mining.

// Request { "jsonrpc": "2.0", "method": "get_block_template", "params": { "address": "tos1miner-address...", "ai_mining": true }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "blocktemplate_blob": "0x1a2b3c4d...", "difficulty": "0x1a2b3c4d5e6f", "ai_difficulty": "0x2b3c4d5e6f7a", "height": 1250001, "previous_hash": "0xabcdef123456...", "timestamp": 1672531200, "blocksize_limit": 2097152, "blocksize_median": 1048576, "seed_hash": "0x987654321abc...", "next_seed_hash": "0xfedcba987654...", "ai_task_data": { "task_id": "ai_task_12345", "task_type": "optimization", "difficulty_multiplier": 1.5, "deadline": 1672531500 } }, "id": 1 }

submit_block

Submit mined block to the network.

// Request { "jsonrpc": "2.0", "method": "submit_block", "params": { "block_blob": "0x1a2b3c4d...", "nonce": 4294967295, "timestamp": 1672531200, "ai_solution": { "task_id": "ai_task_12345", "solution_data": "0xsolution_blob...", "quality_score": 87.5 } }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "status": "accepted", "block_hash": "0xnew_block_hash...", "height": 1250001, "reward": "5000000000000", "ai_bonus": "500000000000" }, "id": 1 }

get_block_by_hash

Get block information by hash.

// Request { "jsonrpc": "2.0", "method": "get_block_by_hash", "params": { "hash": "0xblock_hash...", "include_transactions": true }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "hash": "0xblock_hash...", "height": 1250000, "topoheight": 1250123, "timestamp": 1672531200, "previous_hash": "0xprevious_hash...", "tips": ["0xtip1...", "0xtip2..."], "nonce": 4294967295, "difficulty": "0x1a2b3c4d5e6f", "block_type": "normal", "miner": "tos1miner-address...", "reward": "5000000000000", "total_fees": "125000000", "total_size": 1048576, "transaction_count": 156, "transactions": ["0xtx1...", "0xtx2..."], "ai_mining_data": { "task_completed": true, "quality_score": 87.5, "bonus_reward": "500000000000" }, "cumulative_difficulty": "0x9f8e7d6c5b4a" }, "id": 1 }

get_block_by_height

Get block information by height.

// Request { "jsonrpc": "2.0", "method": "get_block_by_height", "params": { "height": 1250000, "include_transactions": false }, "id": 1 } // Response: Same as get_block_by_hash

get_blocks_range

Get multiple blocks in a range.

// Request { "jsonrpc": "2.0", "method": "get_blocks_range", "params": { "start_height": 1249950, "end_height": 1250000, "include_transactions": false }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "blocks": [ { "hash": "0xblock1...", "height": 1249950, // ... block data }, // ... more blocks ] }, "id": 1 }

Transaction Operations

get_transaction

Get transaction details by hash.

// Request { "jsonrpc": "2.0", "method": "get_transaction", "params": { "hash": "0xtx_hash..." }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "hash": "0xtx_hash...", "version": 1, "nonce": 42, "source": "tos1sender...", "fee": "1000000", "data": { "Transfer": { "destination": "tos1recipient...", "amount": "1000000000000", "extra_data": null } }, "range_proof": "0xproof...", "signature": "0xsignature...", "in_mempool": false, "first_seen": 1672531000, "executed_in_block": "0xblock_hash...", "block_height": 1250000, "block_topoheight": 1250123, "confirmations": 6, "privacy_level": "maximum", "energy_used": "50.5" }, "id": 1 }

submit_transaction

Submit signed transaction to the network.

// Request { "jsonrpc": "2.0", "method": "submit_transaction", "params": { "data": "0xsigned_transaction_data..." }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "status": "accepted", "tx_hash": "0xnew_tx_hash...", "fee_paid": "1000000", "energy_used": "50.5" }, "id": 1 }

get_mempool

Get pending transactions in mempool.

// Request { "jsonrpc": "2.0", "method": "get_mempool", "params": { "include_transactions": true, "limit": 100 }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "count": 156, "total_size": 524288, "transactions": [ { "hash": "0xtx1...", "fee": "1500000", "size": 1024, "first_seen": 1672531180, "priority": "high" } // ... more transactions ] }, "id": 1 }

Account Operations

get_balance

Get account balance (requires view key for private balances).

// Request { "jsonrpc": "2.0", "method": "get_balance", "params": { "address": "tos1address...", "view_key": "0xview_key..." // Optional for encrypted balance viewing }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "version": 0, "balance": "5000000000000", "encrypted_balance": "0xencrypted...", // If no view key provided "nonce": 42, "energy": { "available": "2500.5", "generating_rate": "500.5", "staked_amount": "10000000000000" } }, "id": 1 }

get_nonce

Get current nonce for address.

// Request { "jsonrpc": "2.0", "method": "get_nonce", "params": { "address": "tos1address..." }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "nonce": 42, "version": 0 }, "id": 1 }

get_account_history

Get transaction history for account.

// Request { "jsonrpc": "2.0", "method": "get_account_history", "params": { "address": "tos1address...", "minimum_topoheight": 1249000, "maximum_topoheight": 1250000, "limit": 50 }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "transactions": [ { "hash": "0xtx1...", "topoheight": 1249950, "block_hash": "0xblock...", "fee": "1000000", "nonce": 41 } // ... more transactions ] }, "id": 1 }

Mining Operations

get_mining_stats

Get mining statistics.

// Request { "jsonrpc": "2.0", "method": "get_mining_stats", "params": {}, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "network_hashrate": "125500000000000", "ai_hashrate": "15500000000000", "traditional_hashrate": "110000000000000", "difficulty": "0x1a2b3c4d5e6f", "ai_difficulty": "0x2b3c4d5e6f7a", "blocks_found_24h": 5760, "average_block_time": 15200, "ai_tasks_completed_24h": 1247, "total_miners": 2547, "ai_miners": 312 }, "id": 1 }

get_miner_work

Get mining work for specific miner.

// Request { "jsonrpc": "2.0", "method": "get_miner_work", "params": { "address": "tos1miner...", "work_type": "ai_mining" // "traditional" or "ai_mining" }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "work_id": "work_12345", "block_template": "0x1a2b3c4d...", "difficulty": "0x1a2b3c4d5e6f", "height": 1250001, "timestamp": 1672531200, "ai_task": { "task_id": "ai_task_67890", "task_type": "optimization", "input_data": "0xtask_data...", "expected_output_format": "json", "timeout": 300, "quality_threshold": 80.0 } }, "id": 1 }

Network Monitoring

get_peers

Get connected peer information.

// Request { "jsonrpc": "2.0", "method": "get_peers", "params": {}, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "peers": [ { "id": "peer_id_1", "address": "192.168.1.100:2080", "direction": "outbound", "uptime": 86400, "height": 1250000, "ping": 45, "version": "1.2.0", "user_agent": "TOS Node/1.2.0", "supports_ai_mining": true } // ... more peers ], "total_peers": 47, "max_peers": 50 }, "id": 1 }

get_network_stats

Get comprehensive network statistics.

// Request { "jsonrpc": "2.0", "method": "get_network_stats", "params": { "timeframe": "24h" // "1h", "24h", "7d", "30d" }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "timeframe": "24h", "transactions": { "total": 45672, "private_percentage": 89.4, "average_fee": "1250000", "energy_transactions": 30684 }, "blocks": { "total": 5760, "average_time": 15200, "orphan_rate": 0.83, "ai_mined_percentage": 12.0 }, "mining": { "total_hashrate": "125500000000000", "ai_hashrate": "15500000000000", "difficulty_change": "+2.3%", "unique_miners": 2547 }, "energy": { "total_staked": "2100000000000000", "daily_generation": "1150000000000", "utilization_rate": 67.2 } }, "id": 1 }

WebSocket Events

Event Subscription

subscribe

Subscribe to real-time events.

// Subscribe to new blocks { "jsonrpc": "2.0", "method": "subscribe", "params": { "event": "new_block" }, "id": 1 } // Subscribe to transactions for specific address { "jsonrpc": "2.0", "method": "subscribe", "params": { "event": "transaction", "address": "tos1address..." }, "id": 2 } // Subscribe to AI mining events { "jsonrpc": "2.0", "method": "subscribe", "params": { "event": "ai_mining_task" }, "id": 3 }

Event Types

New Block Event

// Event notification { "jsonrpc": "2.0", "method": "new_block", "params": { "hash": "0xnew_block...", "height": 1250001, "topoheight": 1250124, "timestamp": 1672531215, "miner": "tos1miner...", "reward": "5000000000000", "transaction_count": 187, "difficulty": "0x1a2b3c4d5e6f", "block_type": "normal", "ai_mined": true } }

Transaction Event

// Event notification { "jsonrpc": "2.0", "method": "transaction", "params": { "hash": "0xtx_hash...", "from": "tos1sender...", "to": "tos1recipient...", "amount": "1000000000000", "fee": "1000000", "confirmations": 1, "block_hash": "0xblock...", "status": "confirmed", "privacy_level": "maximum" } }

AI Mining Task Event

// Event notification { "jsonrpc": "2.0", "method": "ai_mining_task", "params": { "event_type": "task_published", // "task_published", "task_completed", "solution_submitted" "task_id": "ai_task_12345", "task_type": "optimization", "reward": "10000000000000", "deadline": 1672531500, "publisher": "tos1publisher...", "miner": "tos1miner..." // Only for solution_submitted/task_completed } }

Mempool Event

// Event notification { "jsonrpc": "2.0", "method": "mempool_transaction", "params": { "hash": "0xtx_hash...", "fee": "1500000", "size": 1024, "priority": "high", "estimated_confirmation_time": 45 } }

Smart Contract Integration

call_smart_contract

Call smart contract method (read-only).

// Request { "jsonrpc": "2.0", "method": "call_smart_contract", "params": { "contract_address": "tos1contract...", "method": "getBalance", "args": ["tos1user..."], "caller": "tos1caller..." }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "return_value": "5000000000000", "gas_used": 21000, "success": true }, "id": 1 }

get_contract_state

Get smart contract storage state.

// Request { "jsonrpc": "2.0", "method": "get_contract_state", "params": { "contract_address": "tos1contract...", "key": "balances", "subkey": "tos1user..." // Optional }, "id": 1 } // Response { "jsonrpc": "2.0", "result": { "value": "5000000000000", "type": "u64", "last_updated": 1250000 }, "id": 1 }

Error Handling

Error Response Format

{ "jsonrpc": "2.0", "error": { "code": -32001, "message": "Block not found", "data": { "requested_hash": "0xinvalid_hash...", "suggestion": "Check if hash is correct" } }, "id": 1 }

Error Codes

CodeMessageDescription
-32700Parse errorInvalid JSON
-32600Invalid RequestInvalid JSON-RPC
-32601Method not foundUnknown method
-32602Invalid paramsParameter error
-32603Internal errorServer error
-32001Block not foundBlock doesn’t exist
-32002Transaction not foundTransaction doesn’t exist
-32003Invalid addressAddress format error
-32004Insufficient balanceNot enough funds
-32005Invalid nonceNonce mismatch
-32006Transaction rejectedValidation failed
-32007Network congestionHigh network load
-32008Mining errorMining operation failed
-32009AI task errorAI mining task failed

Implementation Examples

Node.js Client

const WebSocket = require('ws'); class TOSDaemonClient { constructor(url, apiKey = null) { this.url = url; this.apiKey = apiKey; this.requestId = 0; this.ws = null; } async httpRequest(method, params = {}) { const headers = { 'Content-Type': 'application/json', }; if (this.apiKey) { headers['Authorization'] = `Bearer ${this.apiKey}`; } const response = await fetch(this.url + '/json_rpc', { method: 'POST', headers, body: JSON.stringify({ jsonrpc: '2.0', method, params, id: ++this.requestId }) }); const result = await response.json(); if (result.error) { throw new Error(`RPC Error ${result.error.code}: ${result.error.message}`); } return result.result; } connectWebSocket() { const wsUrl = this.url.replace('http', 'ws') + '/ws'; this.ws = new WebSocket(wsUrl); this.ws.on('open', () => { console.log('WebSocket connected'); }); this.ws.on('message', (data) => { const message = JSON.parse(data); this.handleWebSocketMessage(message); }); this.ws.on('error', (error) => { console.error('WebSocket error:', error); }); return this.ws; } subscribe(event, params = {}) { if (!this.ws) { throw new Error('WebSocket not connected'); } this.ws.send(JSON.stringify({ jsonrpc: '2.0', method: 'subscribe', params: { event, ...params }, id: ++this.requestId })); } handleWebSocketMessage(message) { if (message.method) { // Event notification console.log(`Event ${message.method}:`, message.params); } else if (message.result) { // Response to request console.log('Response:', message.result); } else if (message.error) { console.error('Error:', message.error); } } // Convenience methods async getNetworkInfo() { return this.httpRequest('get_info'); } async getBlock(hash) { return this.httpRequest('get_block_by_hash', { hash }); } async getTransaction(hash) { return this.httpRequest('get_transaction', { hash }); } async submitTransaction(data) { return this.httpRequest('submit_transaction', { data }); } async getBalance(address, viewKey = null) { const params = { address }; if (viewKey) params.view_key = viewKey; return this.httpRequest('get_balance', params); } } // Usage example const client = new TOSDaemonClient('https://node.tos.network', 'your-api-key'); async function example() { // HTTP requests const networkInfo = await client.getNetworkInfo(); console.log('Network info:', networkInfo); const balance = await client.getBalance('tos1address...'); console.log('Balance:', balance); // WebSocket events client.connectWebSocket(); client.subscribe('new_block'); client.subscribe('transaction', { address: 'tos1address...' }); }

Python Client

import asyncio import aiohttp import websockets import json class TOSDaemonClient: def __init__(self, url, api_key=None): self.url = url self.api_key = api_key self.request_id = 0 async def http_request(self, method, params=None): if params is None: params = {} headers = {'Content-Type': 'application/json'} if self.api_key: headers['Authorization'] = f'Bearer {self.api_key}' self.request_id += 1 payload = { 'jsonrpc': '2.0', 'method': method, 'params': params, 'id': self.request_id } async with aiohttp.ClientSession() as session: async with session.post( f'{self.url}/json_rpc', headers=headers, json=payload ) as response: result = await response.json() if 'error' in result: raise Exception(f"RPC Error {result['error']['code']}: {result['error']['message']}") return result['result'] async def websocket_listen(self, events): ws_url = self.url.replace('http', 'ws') + '/ws' async with websockets.connect(ws_url) as websocket: # Subscribe to events for event, params in events.items(): subscribe_msg = { 'jsonrpc': '2.0', 'method': 'subscribe', 'params': {'event': event, **params}, 'id': self.request_id + 1 } await websocket.send(json.dumps(subscribe_msg)) # Listen for messages async for message in websocket: data = json.loads(message) if 'method' in data: print(f"Event {data['method']}: {data['params']}") # Convenience methods async def get_network_info(self): return await self.http_request('get_info') async def get_block(self, hash_or_height): if isinstance(hash_or_height, int): return await self.http_request('get_block_by_height', {'height': hash_or_height}) else: return await self.http_request('get_block_by_hash', {'hash': hash_or_height}) async def get_balance(self, address, view_key=None): params = {'address': address} if view_key: params['view_key'] = view_key return await self.http_request('get_balance', params) # Usage example async def main(): client = TOSDaemonClient('https://node.tos.network', 'your-api-key') # HTTP requests network_info = await client.get_network_info() print('Network info:', network_info) balance = await client.get_balance('tos1address...') print('Balance:', balance) # WebSocket events events = { 'new_block': {}, 'transaction': {'address': 'tos1address...'} } await client.websocket_listen(events) if __name__ == '__main__': asyncio.run(main())

The TOS Network Daemon API provides comprehensive access to all blockchain functionality while maintaining the core principle of “Don’t Trust, Verify it.” All data can be cryptographically verified, ensuring maximum security and transparency for your applications.

Last updated on