Api

JSON-RPC Interface

Complete JSON-RPC API reference for Hydra

JSON-RPC Interface

The Hydra App provides a complete JSON-RPC 2.0 interface alongside the gRPC-Web API. This allows you to interact with Hydra using standard HTTP requests, making it accessible from any programming language or tool that supports HTTP.

Overview

  • Protocol: JSON-RPC 2.0
  • Transport: HTTP POST
  • Default Port: 5000
  • Default URL: http://127.0.0.1:5000
  • Content-Type: application/json

The JSON-RPC interface exposes the same functionality as the gRPC-Web API, but with a simpler request/response format that doesn't require protobuf code generation.

Quick Start

Making Your First Request

TypeScript
async function callJsonRpc(method: string, params: any = {}) {
  const response = await fetch('http://127.0.0.1:5000', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method,
      params,
    }),
  })

  const data = await response.json()
  if (data.error) {
    throw new Error(data.error.message)
  }
  return data.result
}

// Example: Get networks
const networks = await callJsonRpc('app_getNetworks')
console.log('Networks:', networks)

// Example: Get assets for a network
const assets = await callJsonRpc('asset_getAssets', {
  network: { protocol: 0, id: '0a03cf40' }
})
console.log('Assets:', assets)
Python
import requests
import json

def call_json_rpc(method, params=None):
    payload = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": method,
        "params": params or {}
    }

    response = requests.post(
        'http://127.0.0.1:5000',
        headers={'Content-Type': 'application/json'},
        data=json.dumps(payload)
    )

    data = response.json()
    if 'error' in data:
        raise Exception(data['error']['message'])
    return data['result']

# Example: Get networks
networks = call_json_rpc('app_getNetworks')
print('Networks:', networks)

# Example: Get assets for a network
assets = call_json_rpc('asset_getAssets', {
    'network': {'protocol': 0, 'id': '0a03cf40'}
})
print('Assets:', assets)
cURL
# Get networks
curl -X POST http://127.0.0.1:5000 \\
  -H "Content-Type: application/json" \\
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "app_getNetworks",
    "params": {}
  }'

# Get assets for Bitcoin network
curl -X POST http://127.0.0.1:5000 \\
  -H "Content-Type: application/json" \\
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "asset_getAssets",
    "params": {
      "network": {
        "protocol": 0,
        "id": "0a03cf40"
      }
    }
  }'

Method Discovery

You can discover all available methods using the rpc.discover method, which returns the full OpenRPC specification:

curl -X POST http://127.0.0.1:5000 \\
  -H "Content-Type: application/json" \\
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "rpc.discover"
  }'

Method Reference

All methods follow the naming convention service_methodName. Below is a complete reference organized by service.

App Service

Methods for general application information.

app_getNetworks

Get the list of supported networks.

Parameters: None

Returns: GetNetworksResponse

Example
const result = await callJsonRpc('app_getNetworks')
// Returns: { networks: [{ protocol: 0, id: '0a03cf40' }, ...] }

app_getPublicKey

Get the node's public key.

Parameters: None

Returns: GetPublicKeyResponse

Example
const result = await callJsonRpc('app_getPublicKey')
// Returns: { publicKey: 'base64-encoded-public-key' }

Asset Service

Methods for managing assets and tokens.

asset_getAssets

Get all assets for a specific network.

Parameters: GetAssetsRequest

  • network: Network object (protocol + id)

Returns: GetAssetsResponse

Example
const result = await callJsonRpc('asset_getAssets', {
  network: { protocol: 0, id: '0a03cf40' }
})
// Returns: { assets: [{ id: '0x...', symbol: 'BTC', ... }, ...] }

asset_getAsset

Get information about a specific asset.

Parameters: GetAssetRequest

  • network: Network object
  • assetId: Asset ID string

Returns: GetAssetResponse

asset_getNativeAsset

Get the native asset for a network (e.g., BTC for Bitcoin, ETH for Ethereum).

Parameters: GetNativeAssetRequest

  • network: Network object

Returns: GetAssetResponse

asset_addToken

Add a token to the wallet.

Parameters: AddTokenRequest

  • network: Network object
  • tokenId: Token contract address

Returns: AddTokenResponse


Blockchain Service

Methods for interacting with blockchain networks.

blockchain_getBlockNumber

Get the current block number for a network.

Parameters: GetBlockNumberRequest

  • network: Network object

Returns: GetBlockNumberResponse

Example
const result = await callJsonRpc('blockchain_getBlockNumber', {
  network: { protocol: 1, id: '11155111' } // Ethereum Sepolia
})
// Returns: { blockNumber: 1234567 }

blockchain_getBlockHeader

Get block header information for a specific block.

Parameters: GetBlockHeaderRequest

  • network: Network object
  • blockNumber: Block number (uint64)

Returns: GetBlockHeaderResponse

blockchain_getFeeEstimates

Get current fee estimates for transactions on a network.

Parameters: GetFeeEstimatesRequest

  • network: Network object

Returns: GetFeeEstimatesResponse

Example
const result = await callJsonRpc('blockchain_getFeeEstimates', {
  network: { protocol: 0, id: '0a03cf40' }
})
// Returns fee estimates with low, medium, high options

blockchain_getTokenAllowance

Get the token allowance for a spender.

Parameters: GetTokenAllowanceRequest

  • network: Network object
  • tokenId: Token contract address
  • owner: Owner address
  • spender: Spender address

Returns: GetTokenAllowanceResponse


Client Service

Methods for client wallet operations.

client_getDepositAddress

Get the deposit address for receiving funds.

Parameters: GetDepositAddressRequest

  • network: Network object

Returns: GetDepositAddressResponse

Example
const result = await callJsonRpc('client_getDepositAddress', {
  network: { protocol: 0, id: '0a03cf40' }
})
// Returns: { address: 'tb1q...' }

client_sendTransaction

Send a transaction on-chain.

Parameters: SendTransactionRequest

  • network: Network object
  • toAddress: Recipient address
  • amount: SendAmount object
  • feeOption: FeeOption (low/medium/high)

Returns: SendTransactionResponse

Example
const result = await callJsonRpc('client_sendTransaction', {
  network: { protocol: 0, id: '0a03cf40' },
  toAddress: 'tb1q...',
  amount: { value: '10000' },
  feeOption: { medium: {} }
})
// Returns: { txid: '...' }

client_bumpTransaction

Bump the fee of an existing transaction (RBF).

Parameters: BumpTransactionRequest

  • network: Network object
  • txid: Transaction ID
  • feeOption: New fee option

Returns: BumpTransactionResponse

client_sendTokenTransaction

Send a token transaction.

Parameters: SendTokenTransactionRequest

  • network: Network object
  • toAddress: Recipient address
  • tokenId: Token contract address
  • amount: SendAmount object
  • feeOption: FeeOption

Returns: SendTokenTransactionResponse

client_setTokenAllowance

Set token allowance for a spender.

Parameters: SetTokenAllowanceRequest

  • network: Network object
  • spender: Spender address
  • allowance: SetAllowance object
  • feeOption: FeeOption

Returns: SetTokenAllowanceResponse


Event Service

Methods for subscribing to real-time events (streaming).

event_subscribeClientEvents

Subscribe to client wallet events (streaming).

Parameters: SubscribeClientEventsRequest

  • network: Network object

Returns: Stream of ClientEvent

event_subscribeNodeEvents

Subscribe to node events (streaming).

Parameters: SubscribeNodeEventsRequest

  • network: Network object

Returns: Stream of NodeEvent

Note: Streaming methods require WebSocket support or server-sent events (SSE). Check your client library documentation.


Node Service

Methods for Lightning Network node operations.

node_connectToPeer

Connect to a Lightning Network peer.

Parameters: ConnectToPeerRequest

  • network: Network object
  • peerUrl: Peer connection string (pubkey@host:port)

Returns: ConnectToPeerResponse

Example
const result = await callJsonRpc('node_connectToPeer', {
  network: { protocol: 0, id: '0a03cf40' },
  peerUrl: '03abc...@127.0.0.1:9735'
})

node_disconnectFromPeer

Disconnect from a peer.

Parameters: DisconnectFromPeerRequest

  • network: Network object
  • nodeId: Peer node ID

Returns: DisconnectFromPeerResponse

node_getConnectedPeers

Get list of connected peers.

Parameters: GetConnectedPeersRequest

  • network: Network object

Returns: GetConnectedPeersResponse

node_estimateOpenChannelFee

Estimate the fee for opening a channel.

Parameters: EstimateOpenChannelFeeRequest

  • network: Network object
  • nodeId: Peer node ID
  • assetAmounts: Map of asset ID to SendAmount
  • feeRate: FeeRate object

Returns: EstimateOpenChannelFeeResponse

node_openChannel

Open a Lightning channel with a peer.

Parameters: OpenChannelRequest

  • network: Network object
  • nodeId: Peer node ID
  • assetAmounts: Map of asset ID to SendAmount
  • feeRate: FeeRate object

Returns: OpenChannelResponse

Example
const result = await callJsonRpc('node_openChannel', {
  network: { protocol: 0, id: '0a03cf40' },
  nodeId: '03abc...',
  assetAmounts: {
    '0x0000...': { value: '100000' }
  },
  feeRate: {
    maxTipFeePerUnit: { value: '1000000000' },
    maxFeePerUnit: { value: '2000000000' }
  }
})
// Returns: { txid: '...', channelId: '...' }

node_estimateDepositChannelFee

Estimate fee for depositing to a channel.

node_depositChannel

Deposit additional funds to an existing channel.

node_estimateWithdrawChannelFee

Estimate fee for withdrawing from a channel.

node_withdrawChannel

Withdraw funds from a channel.

node_estimateCloseChannelFee

Estimate fee for closing a channel.

node_closeChannel

Close a Lightning channel cooperatively.

node_estimateForceCloseChannelFee

Estimate fee for force-closing a channel.

node_forceCloseChannel

Force-close a channel (non-cooperative).

node_estimateRedeemClosedChannelFee

Estimate fee for redeeming a closed channel.

node_redeemClosedChannel

Redeem funds from a closed channel.

node_waitForActiveAssetChannel

Wait for a channel to become active for a specific asset.

node_sendChannelPayment

Send a payment directly through a specific channel.

Parameters: SendChannelPaymentRequest

  • network: Network object
  • channelId: Channel ID
  • assetAmounts: Map of asset ID to SendAmount
  • hashlock: Optional hashlock
  • expiryTimeoutSecs: Optional expiry timeout

Returns: SendChannelPaymentResponse

node_estimateSendPaymentFee

Estimate routing fees for a payment.

node_sendPayment

Send a Lightning payment to a node (routing).

Parameters: SendPaymentRequest

  • network: Network object
  • recipientNodeId: Recipient node public key
  • assetAmounts: Map of asset ID to SendAmount
  • hashlock: Optional hashlock
  • expiryTimeoutSecs: Optional expiry timeout

Returns: SendPaymentResponse

node_createInvoice

Create a Lightning invoice for receiving payments.

Parameters: CreateInvoiceRequest

  • network: Network object
  • assetId: Asset ID
  • amount: Optional amount (for non-zero invoices)
  • hashlock: Optional hashlock
  • expiryTimeoutSecs: Optional expiry timeout

Returns: CreateInvoiceResponse

Example
const result = await callJsonRpc('node_createInvoice', {
  network: { protocol: 0, id: '0a03cf40' },
  assetId: '0x0000...',
  amount: { value: '50000' },
  expiryTimeoutSecs: 3600
})
// Returns: { invoice: { paymentRequest: 'lnbc...', ... } }

node_decodeInvoice

Decode a Lightning invoice to see its details.

Parameters: DecodeInvoiceRequest

  • network: Network object
  • paymentRequest: Lightning invoice string

Returns: DecodeInvoiceResponse

node_estimatePayInvoiceFee

Estimate routing fees for paying an invoice.

node_payInvoice

Pay a Lightning invoice.

Parameters: PayInvoiceRequest

  • network: Network object
  • paymentRequest: Lightning invoice string

Returns: PayInvoiceResponse

node_estimatePayEmptyInvoiceFee

Estimate fees for paying a zero-amount invoice.

node_payEmptyInvoice

Pay a zero-amount invoice with a specific amount.

Parameters: PayEmptyInvoiceRequest

  • network: Network object
  • paymentRequest: Lightning invoice string
  • amount: SendAmount to pay

Returns: PayEmptyInvoiceResponse

node_resolveHashlockPayment

Resolve a hashlocked payment with the preimage.

node_rejectPayment

Reject an incoming payment.

node_allowDualFundedChannel

Allow a peer to open a dual-funded channel.


Orderbook Service

Methods for DEX orderbook operations.

orderbook_initMarket

Initialize a new trading market.

Parameters: InitMarketRequest

  • firstCurrency: OrderbookCurrency
  • otherCurrency: OrderbookCurrency

Returns: InitMarketResponse

orderbook_getInitializedMarkets

Get list of initialized markets.

orderbook_getMarketsInfo

Get information about all markets.

orderbook_getMarketInfo

Get information about a specific market.

orderbook_getOrderbookBalances

Get orderbook balances for all currencies.

orderbook_getOrderbook

Get the current orderbook for a market.

Parameters: GetOrderbookRequest

  • base: OrderbookCurrency
  • quote: OrderbookCurrency

Returns: GetOrderbookResponse

orderbook_estimateOrder

Estimate the result of an order without placing it.

Parameters: EstimateOrderRequest

  • orderVariant: Order details

Returns: EstimateOrderResponse

orderbook_createOrder

Create a new order on the orderbook.

Parameters: CreateOrderRequest

  • orderVariant: Order details (limit/market order)

Returns: CreateOrderResponse

Example: Market Buy Order
const result = await callJsonRpc('orderbook_createOrder', {
  orderVariant: {
    marketBuy: {
      base: { network: { protocol: 0, id: '0a03cf40' }, assetId: '0x...' },
      quote: { network: { protocol: 1, id: '11155111' }, assetId: '0x...' },
      quoteAmount: { value: '1000000' }
    }
  }
})
// Returns: { orderId: '...' }

orderbook_cancelOrder

Cancel an existing order.

Parameters: CancelOrderRequest

  • orderId: Order ID to cancel

Returns: CancelOrderResponse

orderbook_cancelAllOrders

Cancel all active orders.

orderbook_getAllOwnOrders

Get all your active orders across all markets.

orderbook_getOwnOrders

Get your active orders for a specific market.

orderbook_getOrder

Get details of a specific order.

orderbook_getTradeHistory

Get trade history for a market.

orderbook_getAllMarketTrades

Get all your market trades.

orderbook_getPairMarketTrades

Get your trades for a specific market pair.

orderbook_getAllSwapTrades

Get all your swap trades.

orderbook_getPairSwapTrades

Get swap trades for a specific currency pair.

orderbook_subscribeMarketEvents

Subscribe to market events (streaming).

orderbook_subscribeDexEvents

Subscribe to DEX events (streaming).


Pricing Service

Methods for asset price information.

pricing_getAssetFiatPrice

Get the fiat price of an asset.

Parameters: GetAssetFiatPriceRequest

  • network: Network object
  • assetId: Asset ID
  • fiatCurrency: Fiat currency (e.g., USD, EUR)

Returns: GetAssetFiatPriceResponse

Example
const result = await callJsonRpc('pricing_getAssetFiatPrice', {
  network: { protocol: 0, id: '0a03cf40' },
  assetId: '0x0000...',
  fiatCurrency: 'USD'
})
// Returns: { price: { value: '50000.50' } }

pricing_getAssetFiatPriceBySymbol

Get fiat price using asset symbol instead of ID.

Parameters: GetAssetFiatPriceBySymbolRequest

  • assetSymbol: Asset symbol (e.g., 'BTC', 'ETH')
  • fiatCurrency: Fiat currency

Returns: GetAssetFiatPriceBySymbolResponse


Rental Service

Methods for channel rental operations.

rental_getRentalNodeInfo

Get information about the rental node configuration.

Returns: GetRentalNodeInfoResponse

rental_getRentableAssetInfo

Get rental information for a specific asset.

Parameters: GetRentableAssetInfoRequest

  • network: Network object
  • assetId: Asset ID

Returns: GetRentableAssetInfoResponse

rental_estimateRentChannelFee

Estimate fees for renting a channel.

Parameters: EstimateRentChannelFeeRequest

  • network: Network object
  • assetId: Asset ID
  • lifetimeSeconds: Rental duration
  • amount: Liquidity amount
  • rentalOption: RentalOption (payment details)

Returns: EstimateRentChannelFeeResponse

rental_rentChannel

Rent an inbound liquidity channel.

Parameters: RentChannelRequest

  • network: Network object
  • assetId: Asset ID
  • lifetimeSeconds: Rental duration
  • amount: Liquidity amount
  • rentalOption: RentalOption (payment details)

Returns: RentChannelResponse

Example
const result = await callJsonRpc('rental_rentChannel', {
  network: { protocol: 0, id: '0a03cf40' },
  assetId: '0x0000...',
  lifetimeSeconds: 86400, // 24 hours
  amount: { value: '1000000' },
  rentalOption: {
    payment: {
      rentalTxFeeRate: {
        maxTipFeePerUnit: { value: '1000000000' },
        maxFeePerUnit: { value: '2000000000' }
      },
      paymentNetwork: { protocol: 0, id: '0a03cf40' },
      paymentAssetId: '0x0000...',
      paymentMethod: 'ONCHAIN'
    }
  }
})
// Returns: { rentalTxid: '...', rentedChannelId: '...', rentalPayment: {...} }

Signer Service

Methods for cryptographic signing operations.

signer_signMessage

Sign a message with the client key.

Parameters: SignMessageRequest

  • network: Network object
  • message: Message object to sign

Returns: SignMessageResponse

signer_nodeSignMessage

Sign a message with the node key.

signer_verifySignature

Verify a signature.

Parameters: VerifySignatureRequest

  • network: Network object
  • message: Message object
  • publicKey: Public key string
  • signature: Signature bytes

Returns: VerifySignatureResponse


Swap Service

Methods for atomic swap operations.

swap_estimateSwap

Estimate a swap between two currencies.

Parameters: EstimateSwapRequest

  • sendingCurrency: OrderbookCurrency
  • receivingCurrency: OrderbookCurrency
  • amount: SwapAmount

Returns: EstimateSwapResponse

swap_swap

Execute a swap.

Parameters: SwapRequest

  • sendingCurrency: OrderbookCurrency
  • receivingCurrency: OrderbookCurrency
  • amount: SwapAmount

Returns: SwapResponse

swap_estimateSimpleSwap

Estimate a simple swap with auto-setup.

Parameters: EstimateSimpleSwapRequest

  • sendingCurrency: OrderbookCurrency
  • receivingCurrency: OrderbookCurrency
  • amount: SwapAmount
  • priceChangeTolerance: Max price slippage
  • withdrawSendingFunds: Boolean
  • withdrawReceivingFunds: Boolean

Returns: EstimateSimpleSwapResponse

swap_simpleSwap

Execute a simple swap with automatic channel setup.

Parameters: SimpleSwapRequest

  • sendingCurrency: OrderbookCurrency
  • receivingCurrency: OrderbookCurrency
  • amount: SwapAmount
  • priceChangeTolerance: Max price slippage
  • withdrawSendingFunds: Boolean
  • withdrawReceivingFunds: Boolean

Returns: SimpleSwapResponse

Example
const result = await callJsonRpc('swap_simpleSwap', {
  sendingCurrency: {
    network: { protocol: 0, id: '0a03cf40' },
    assetId: '0x0000...'
  },
  receivingCurrency: {
    network: { protocol: 1, id: '11155111' },
    assetId: '0x0000...'
  },
  amount: {
    sendExact: { value: '1000000' }
  },
  priceChangeTolerance: { value: '0.01' }, // 1%
  withdrawSendingFunds: false,
  withdrawReceivingFunds: false
})

swap_subscribeSimpleSwaps

Subscribe to simple swap updates (streaming).


Wallet Service

Methods for wallet balance and transaction queries.

wallet_getBalances

Get all balances for a network.

Parameters: GetBalancesRequest

  • network: Network object

Returns: GetBalancesResponse

Example
const result = await callJsonRpc('wallet_getBalances', {
  network: { protocol: 0, id: '0a03cf40' }
})
// Returns: { balances: { '0x...': { onchain: {...}, offchain: {...} } } }

wallet_getBalance

Get balance for a specific asset.

Parameters: GetBalanceRequest

  • network: Network object
  • assetId: Asset ID

Returns: GetBalanceResponse

wallet_getTransactions

Get all transactions for a network.

Parameters: GetTransactionsRequest

  • network: Network object

Returns: GetTransactionsResponse

wallet_getTransaction

Get a specific transaction by ID.

Parameters: GetTransactionRequest

  • network: Network object
  • txid: Transaction ID

Returns: GetTransactionResponse


Watch-Only Node Service

Methods for querying node information without signing capabilities.

watchOnlyNode_getNodeId

Get the node ID for a network.

Parameters: GetNodeIdRequest

  • network: Network object

Returns: GetNodeIdResponse

watchOnlyNode_getChannels

Get all channels for the node.

Parameters: GetChannelsRequest

  • network: Network object

Returns: GetChannelsResponse

watchOnlyNode_getChannelsWithCounterparty

Get channels with a specific counterparty.

watchOnlyNode_getChannel

Get details of a specific channel.

Parameters: GetChannelRequest

  • network: Network object
  • channelId: Channel ID

Returns: GetChannelResponse

watchOnlyNode_getPayments

Get all payments.

watchOnlyNode_getPayment

Get details of a specific payment.


Error Handling

JSON-RPC errors follow the JSON-RPC 2.0 specification:

{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32600,
    "message": "Invalid Request",
    "data": "Additional error information"
  }
}

Common error codes:

  • -32700: Parse error
  • -32600: Invalid Request
  • -32601: Method not found
  • -32602: Invalid params
  • -32603: Internal error
  • -32000 to -32099: Server errors (application-specific)

Best Practices

1. Use Request IDs

Always include unique request IDs to match responses with requests, especially when making concurrent requests:

let requestId = 0

async function callJsonRpc(method: string, params: any = {}) {
  const id = ++requestId
  const response = await fetch('http://127.0.0.1:5000', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ jsonrpc: '2.0', id, method, params }),
  })
  return response.json()
}

2. Handle Errors Gracefully

try {
  const result = await callJsonRpc('wallet_getBalances', { network })
  console.log('Balances:', result)
} catch (error) {
  if (error.code === -32601) {
    console.error('Method not found')
  } else {
    console.error('RPC Error:', error.message)
  }
}

3. Use Type Definitions

For TypeScript projects, generate types from the OpenRPC specification or define them manually:

interface Network {
  protocol: number
  id: string
}

interface GetBalancesRequest {
  network: Network
}

interface Balance {
  onchain: {
    total: { value: string }
    confirmed: { value: string }
    unconfirmed: { value: string }
  }
  offchain: {
    sendable: { value: string }
    receivable: { value: string }
  }
}

interface GetBalancesResponse {
  balances: Record<string, Balance>
}

4. Batch Requests

JSON-RPC 2.0 supports batching multiple requests in a single HTTP call:

const batchRequest = [
  { jsonrpc: '2.0', id: 1, method: 'app_getNetworks', params: {} },
  { jsonrpc: '2.0', id: 2, method: 'app_getPublicKey', params: {} }
]

const responses = await fetch('http://127.0.0.1:5000', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(batchRequest)
}).then(r => r.json())

// responses is an array of results matching the request IDs

Complete Example: Trading Bot

Here's a complete example of a simple trading bot using the JSON-RPC interface:

TypeScript Trading Bot
class HydraJsonRpcClient {
  private requestId = 0

  constructor(private url: string = 'http://127.0.0.1:5000') {}

  async call(method: string, params: any = {}) {
    const response = await fetch(this.url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: ++this.requestId,
        method,
        params,
      }),
    })

    const data = await response.json()
    if (data.error) throw new Error(data.error.message)
    return data.result
  }
}

async function main() {
  const client = new HydraJsonRpcClient()

  // Get networks
  const { networks } = await client.call('app_getNetworks')
  const btcNetwork = networks.find((n: any) => n.protocol === 0)
  const ethNetwork = networks.find((n: any) => n.protocol === 1)

  console.log('Networks:', { btcNetwork, ethNetwork })

  // Get balances
  const btcBalances = await client.call('wallet_getBalances', {
    network: btcNetwork
  })
  console.log('BTC Balances:', btcBalances)

  // Get orderbook
  const orderbook = await client.call('orderbook_getOrderbook', {
    base: { network: btcNetwork, assetId: '0x0000...' },
    quote: { network: ethNetwork, assetId: '0x0000...' }
  })
  console.log('Orderbook:', orderbook)

  // Estimate a market buy
  const estimate = await client.call('orderbook_estimateOrder', {
    orderVariant: {
      marketBuy: {
        base: { network: btcNetwork, assetId: '0x0000...' },
        quote: { network: ethNetwork, assetId: '0x0000...' },
        quoteAmount: { value: '1000000' }
      }
    }
  })
  console.log('Order estimate:', estimate)

  // Create the order if estimate looks good
  if (estimate.orderMatch) {
    const order = await client.call('orderbook_createOrder', {
      orderVariant: {
        marketBuy: {
          base: { network: btcNetwork, assetId: '0x0000...' },
          quote: { network: ethNetwork, assetId: '0x0000...' },
          quoteAmount: { value: '1000000' }
        }
      }
    })
    console.log('Order created:', order.orderId)
  }
}

main().catch(console.error)

See Also


Copyright © 2025