Api

Swap API

Direct swaps and automated swaps

The Swap API exposes Hydra App's SwapService — cross-chain atomic swaps, either against balances you already hold off-chain (Swap) or with the channels set up for you first (SimpleSwap).

JSON-RPC namespace: swap

Endpoints


Estimate Swap

Estimate a swap between two currencies using existing offchain balance.

Method: EstimateSwap

Requirements:

  • Must have sufficient offchain balance for both sending and receiving currencies
  • Use Simple Swap if you don't have channels set up

Parameters:

NameTypeRequiredDescription
sending_currencyOrderbookCurrencyYESCurrency to send
receiving_currencyOrderbookCurrencyYESCurrency to receive
amountSwapAmountYESAmount to swap (sending or receiving)

SwapAmount Object (one of):

FieldTypeDescription
from{ amount: DecimalString }Amount to send, on the first hop's sending grid
to{ amount: DecimalString }Amount to receive, net of the taker fee, on the last hop's receiving grid

⚠️ The amount must sit on the market's grid

(2026-08-29) Whichever variant you set must carry no more decimal places than the orderbook market side it names allows — from is measured on the first hop's sending side, to on the last hop's receiving side. The limit is that market's base_precision where the currency is its base; where it is its quote, the quote currency's decimals, or base_precision + quote_precision where that is fewer, and never more than 12 (see Amounts and prices).

An over-precise amount is rejected, not rounded. The direction to round in is yours to choose, so the orderbook refuses rather than guessing. Quantise before you send: truncate toward zero when you are sizing a send, and away from zero when you are sizing a receive, or you can end up asking for fractionally more than you meant.

to is defined net of the taker fee. The match is the fewest whole lots that bring it: a filled order delivers at least that figure, and more by under the worth of one lot. At least is to within the rounding of its fills: one unit of the currency per fill where the currency is the market's base, and two units of a quote amount's last decimal place per fill where it is the quote (two millionths of a USDC per fill on a USDC market). Otherwise it delivers less only where the books do not hold it — see unmatched_amount — and, through two markets, where several fills of the first market pay for one fill of the last: each pays for whole lots on its own, and the swap can deliver up to a lot of the last market less for each of them. A swap that leases receiving capacity sizes the lease for what the match can deliver, not for the bare figure.

Response:

FieldTypeDescription
order_matchOrderMatchEstimated execution (optional - null if no liquidity)

Example Request:

TypeScript
import { SwapServiceClient, EstimateSwapRequest } from './proto/SwapServiceClientPb'

const client = new SwapServiceClient('http://localhost:5003')

const request = new EstimateSwapRequest()
request.setSendingCurrency({
  network: { protocol: 1, id: '0a03cf40' },
  assetId: '0x0000000000000000000000000000000000000000000000000000000000000000'
})
request.setReceivingCurrency({
  network: { protocol: 2, id: '11155111' },
  assetId: '0x0000000000000000000000000000000000000000'
})
request.setAmount({
  from: { amount: { value: '1000000' } } // 0.01 BTC
})

const response = await client.estimateSwap(request, {})
const match = response.getOrderMatch()

if (match) {
  console.log('Sending:', match.getSendingAmount())
  console.log('Receiving:', match.getReceivingAmount())
  console.log('Price:', match.getPrice())
} else {
  console.log('No liquidity available')
}
Go
import (
    "context"
    "log"
    pb "your-package/proto"
)

client := pb.NewSwapServiceClient(conn)

req := &pb.EstimateSwapRequest{
    SendingCurrency: &pb.OrderbookCurrency{
        Network: &pb.Network{
            Protocol: pb.Protocol_PROTOCOL_BITCOIN,
            Id:       "0a03cf40",
        },
        AssetId: "0x0000000000000000000000000000000000000000000000000000000000000000",
    },
    ReceivingCurrency: &pb.OrderbookCurrency{
        Network: &pb.Network{
            Protocol: pb.Protocol_PROTOCOL_EVM,
            Id:       "11155111",
        },
        AssetId: "0x0000000000000000000000000000000000000000",
    },
    Amount: &pb.SwapAmount{
        Amount: &pb.SwapAmount_From_{
            From: &pb.SwapAmount_From{Amount: &pb.DecimalString{Value: "0.01"}},
        },
    },
}

resp, err := client.EstimateSwap(context.Background(), req)
if err != nil {
    log.Fatalf("Error: %v", err)
}

if match := resp.GetOrderMatch(); match != nil {
    log.Printf("Sending: %s", match.GetSendingAmount())
    log.Printf("Receiving: %s", match.GetReceivingAmount())
    log.Printf("Price: %s", match.GetPrice())
} else {
    log.Println("No liquidity available")
}
Rust
use tonic::Request;
use your_package::swap_service_client::SwapServiceClient;
use your_package::{EstimateSwapRequest, OrderbookCurrency, Network, SwapAmount, DecimalString};

let mut client = SwapServiceClient::connect("http://localhost:5003").await?;

let request = Request::new(EstimateSwapRequest {
    sending_currency: Some(OrderbookCurrency {
        network: Some(Network {
            protocol: Protocol::Bitcoin as i32,
            id: "0a03cf40".to_string(),
        }),
        asset_id: "0x0000000000000000000000000000000000000000000000000000000000000000".to_string(),
    }),
    receiving_currency: Some(OrderbookCurrency {
        network: Some(Network {
            protocol: Protocol::Evm as i32,
            id: "11155111".to_string(),
        }),
        asset_id: "0x0000000000000000000000000000000000000000".to_string(),
    }),
    amount: Some(SwapAmount {
        amount: Some(your_package::swap_amount::Amount::From(your_package::swap_amount::From {
            amount: Some(DecimalString { value: "0.01".to_string() }),
        })),
    }),
});

let response = client.estimate_swap(request).await?.into_inner();

if let Some(match_) = response.order_match {
    println!("Sending: {}", match_.sending_amount);
    println!("Receiving: {}", match_.receiving_amount);
    println!("Price: {}", match_.price);
} else {
    println!("No liquidity available");
}

Example Response:

{
  "order_match": {
    "sending_amount": "1000000",
    "receiving_amount": "28500000000000000000",
    "price": "28.5"
  }
}

Swap

Execute a swap between two currencies using existing offchain balance.

Method: Swap

Requirements:

  • Must have sufficient offchain balance for both sending and receiving currencies
  • Channels must be active for both currencies
  • Use Simple Swap for automatic channel setup

Parameters:

NameTypeRequiredDescription
sending_currencyOrderbookCurrencyYESCurrency to send
receiving_currencyOrderbookCurrencyYESCurrency to receive
amountSwapAmountYESAmount to swap
settlementOrderSettlementNOAdded 2026-06-11. Per-leg channel-vs-on-chain settlement, signed into the order. Absent = channel-only (the previous behavior). Opting a leg on-chain lets you swap a currency you hold on-chain without opening a channel for it. See the settlement model and the orderbook's On-chain settlement field reference.

Response:

FieldTypeDescription
order_idstringSwap order identifier

Example Request:

TypeScript
const request = new SwapRequest()
request.setSendingCurrency({
  network: { protocol: 1, id: '0a03cf40' },
  assetId: '0x0000000000000000000000000000000000000000000000000000000000000000'
})
request.setReceivingCurrency({
  network: { protocol: 2, id: '11155111' },
  assetId: '0x0000000000000000000000000000000000000000'
})
request.setAmount({
  from: { amount: { value: '1000000' } }
})

const response = await client.swap(request, {})
const orderId = response.getOrderId()
console.log('Swap order created:', orderId)
Go
req := &pb.SwapRequest{
    SendingCurrency: &pb.OrderbookCurrency{
        Network: &pb.Network{
            Protocol: pb.Protocol_PROTOCOL_BITCOIN,
            Id:       "0a03cf40",
        },
        AssetId: "0x0000000000000000000000000000000000000000000000000000000000000000",
    },
    ReceivingCurrency: &pb.OrderbookCurrency{
        Network: &pb.Network{
            Protocol: pb.Protocol_PROTOCOL_EVM,
            Id:       "11155111",
        },
        AssetId: "0x0000000000000000000000000000000000000000",
    },
    Amount: &pb.SwapAmount{
        Amount: &pb.SwapAmount_From_{From: &pb.SwapAmount_From{Amount: &pb.DecimalString{Value: "1000000"}}},
    },
}

resp, err := client.Swap(context.Background(), req)
if err != nil {
    log.Fatalf("Error: %v", err)
}

orderId := resp.GetOrderId()
log.Printf("Swap order created: %s", orderId)
Rust
let request = Request::new(SwapRequest {
    sending_currency: Some(OrderbookCurrency {
        network: Some(Network {
            protocol: Protocol::Bitcoin as i32,
            id: "0a03cf40".to_string(),
        }),
        asset_id: "0x0000000000000000000000000000000000000000000000000000000000000000".to_string(),
    }),
    receiving_currency: Some(OrderbookCurrency {
        network: Some(Network {
            protocol: Protocol::Evm as i32,
            id: "11155111".to_string(),
        }),
        asset_id: "0x0000000000000000000000000000000000000000".to_string(),
    }),
    amount: Some(SwapAmount {
        amount: Some(your_package::swap_amount::Amount::From(swap_amount::From { amount: Some(DecimalString { value: "1000000".to_string() }) })),
    }),
});

let response = client.swap(request).await?.into_inner();
let order_id = response.order_id;
println!("Swap order created: {}", order_id);

Estimate Simple Swap

Estimate a swap with automatic channel setup. This calculates all fees including channel opening, deposits, and rentals.

Method: EstimateSimpleSwap

Benefits:

  • No need for existing channels
  • Automatic balance management
  • One-click cross-chain swaps
  • Optional auto-withdrawal

Parameters:

NameTypeRequiredDescription
sending_currencyOrderbookCurrencyYESCurrency to send
receiving_currencyOrderbookCurrencyYESCurrency to receive
amountSwapAmountYESAmount to swap
price_change_toleranceDecimalStringYESMax price slippage (e.g., "0.01" = 1%). (2026-11-17) How far the whole swap may move against this estimate, every fee charged in its two currencies counted: a from swap delivers at least (1 − this) of what its plan delivers, a to swap sends at most (1 + this) of what its plan sends. The estimate states it as limit_amount. In [0, 1). See Price Change Tolerance
withdraw_sending_fundsboolYESAuto-withdraw sent funds after swap
withdraw_receiving_fundsboolYESAuto-withdraw received funds after swap
fee_priorityFeePriorityNO(2026-10-29) How fast the swap's on-chain transactions are to confirm; the estimate prices their fees at it. Unset reads as FEE_PRIORITY_MEDIUM

Response:

FieldTypeDescription
estimateSimpleSwapEstimateEstimate details (one of multiple variants)

SimpleSwapEstimate Variants:

Instant

Ready to swap immediately - you have sufficient offchain balance.

(2026-11-17) A receive into a channel that holds too little takes on-demand capacity where the hub sells it, both legs settle in channels and the proceeds stay in the channel: the estimate stays Instant, with the fee in capacity_fee. Otherwise the receive is leased first. A swap sized by what it receives (to) delivers the amount it names: it sends more by the fee, and the estimate's match shows what moves. See Receiving on demand.

FieldTypeDescription
order_matchOrderMatchExpected execution
sending_withdrawal_feeWithdrawalFeeFee to withdraw sent funds (optional)
receiving_withdrawal_feeWithdrawalFeeFee to withdraw received funds (optional)
capacity_feeDecimalString(2026-11-17) The fee of the JIT channel the hub sells for the receive, in the receiving currency, out of what is received (optional). Set when the receive is more than the receiving channel holds: the swap buys on-demand capacity instead of leasing a channel first. A swap sized by what it receives (to) sends more by the fee instead, and order_match shows what moves. A to swap pays exactly the fee of the hub's quote it starts with. A from swap pays the hub's fee when its order matches, held with the rest of the swap to limit_amount
limit_amountDecimalString(2026-11-17) The worst this plan accepts, on the side its amount leaves open: for a swap sized by what it sends (from), the least it delivers, in the receiving currency, rounded down to its grid; for one sized by what it receives (to), the most it sends, in the sending currency, rounded up to its grid. That is what this plan delivers or sends, every fee charged in the swap's two currencies counted, moved by its price_change_tolerance share. A to plan that receives less than its amount states what it would send for the whole amount at its rate, and a swap that receives part of its amount is held to the same share of it. Fees paid in a network's native asset are not in it. Pass it to SimpleSwap as limit_amount. Set on every estimate; unset in a SimpleSwapContinueQuote
onchain_feeDecimalString(2026-11-17) What the venue charges this plan's swaps for the hub's on-chain steps of a leg that settles on chain, in the receiving currency, as the venue quotes it now: one charge per swap the route settles as, ClientSwapTrade.onchain_fee once traded (optional). A from swap delivers that much less. A to swap is matched for its amount and one swap's charge, and sends more by that; a route that settles as several swaps delivers the other swaps' charges less than its amount. Counted in limit_amount. Unset when both legs settle in channels, and in a SimpleSwapContinueQuote
estimated_completion_min_secsuint64(2026-11-17) A fast case for how long the swap of this plan takes from its start until it completes, in seconds: every step timed at the pace one such step in ten beats. It counts the confirmations each step waits for at the depth that gates it, a network's finality where a step waits for it, and the step's requests to the counterparty, the venue and the liquidity service at the pace of the swaps this node completed (before its first, at a round trip to the venue timed as the estimate is made). In a SimpleSwapContinueQuote, from now for what is left. Unset while an input of a step's chain wait is not known, while the venue does not answer, and for a leg that settles on chain (optional)
estimated_completion_max_secsuint64(2026-11-17) A slow case: every step timed at the pace nine such steps in ten meet. Not a deadline: a broadcast that misses the next block, and a counterparty that waits a deeper step of its confirmation tiers, take longer and are not counted. Show the two as a range, min–max, or as one figure when they are within a few seconds of each other, and never use max as a timeout. Unset with estimated_completion_min_secs (optional)

Deferred

Need to set up channels via deposits / leases first.

FieldTypeDescription
order_matchOrderMatchExpected execution
sending_channel_depositSendingChannelDepositRequired deposit (optional)
receiving_channel_leaseReceivingChannelLeaseRequired lease (optional)
sending_withdrawal_feeWithdrawalFeeWithdrawal fee (optional)
receiving_withdrawal_feeWithdrawalFeeWithdrawal fee (optional)
token_approval_feeDecimalStringNative-asset fee for the token approval tx (optional, EVM only)
limit_amountDecimalString(2026-11-17) The worst this plan accepts, as on Instant: the channel setup's fees are counted in it
onchain_feeDecimalString(2026-11-17) What the venue charges this plan's swaps for the hub's on-chain steps, as on Instant (optional)
estimated_completion_min_secs / estimated_completion_max_secsuint64(2026-11-17) A fast and a slow case for how long the swap of this plan takes, as on Instant, the channel setup's confirmations counted: a range, not a deadline (optional)

SendingChannelDeposit: { amount, unspendable_reserve, fee, fee_payment_currency, counterparty, deposit_channel_id?, rail }. ReceivingChannelLease: { amount, unspendable_reserve, lease_fee, pay_with_sending }.

unspendable_reserve is the part of amount that does not become usable (2026-11-17): of a deposit, what does not become spendable; of a lease, what does not become receivable. It is the reserve the funding adds on that side and, on a new channel, what its funder holds back for fees. It reads "0" where the funding releases more reserve than it adds, as where a Lightning channel's reserve at open gives way to the splice rule. DualFundDeposit's unspendable_self_reserve and unspendable_counterparty_reserve read the same way for each side's amount.

A lease goes into your channel with the hub (2026-11-17), as a deposit, wherever one payment over the channel can then carry all the lease adds. It opens a new channel only where the channel's receive_ceiling, fixed below its total, would cut what the lease adds.

An absent deposit_channel_id means a fresh channel is opened — either because no channel existed, or because (2026-08-29) every candidate's per-payment ceiling already binds and growing one cannot raise what a single payment carries. Don't read "no channel id" as "no channel exists"; read it as "this deposit will not reuse one". The ceiling in question is the same one max_sendable reports.

DualFundDeferred

Need to dual-fund a channel.

FieldTypeDescription
order_matchOrderMatchExpected execution
dual_fund_depositDualFundDepositRequired dual-fund deposit
sending_withdrawal_feeWithdrawalFeeWithdrawal fee (optional)
receiving_withdrawal_feeWithdrawalFeeWithdrawal fee (optional)
token_approval_feeDecimalStringNative-asset fee for the token approval tx (optional, EVM only)
limit_amountDecimalString(2026-11-17) The worst this plan accepts, as on Instant: the dual funding's fees are counted in it
estimated_completion_min_secs / estimated_completion_max_secsuint64(2026-11-17) A fast and a slow case for how long the swap of this plan takes, as on Instant, the dual funding's confirmations counted: a range, not a deadline (optional)

FeesHigherThanAmount

The fees needed to set up channels would exceed the swap amount — the swap is uneconomical and won't be performed.

FieldTypeDescription
sending_feeDecimalStringTotal fee in sending currency
receiving_feeDecimalStringTotal fee in receiving currency

LeaseTooBig

The receiving lease needed exceeds available liquidity or the provider's max capacity.

FieldTypeDescription
needed_leaseDecimalStringRequired lease amount
available_lease_liquidityDecimalStringCurrently available
max_lease_capacityDecimalStringProvider's maximum

NoLiquidity

No liquidity in the orderbook for this pair (empty payload). This means the market can't serve the pair.

InsufficientSendingBalance

The wallet has nothing to send — no active channel and no usable on-chain balance for the sending asset after fees. Distinct from NoLiquidity (where the market is the problem; here the market is fine).

FieldTypeDescription
availableDecimalStringThe spendable balance the wallet does have for the sending asset

Added 2026-04-27. If you match / switch on the estimate one-of, add a branch for InsufficientSendingBalance — otherwise it falls through your default case and you'll misreport "no liquidity" when the real problem is an empty wallet.

InsufficientNativeBalance

Added 2026-09-11.

The wallet holds the sending asset but cannot pay, in the sending network's native asset, the fee of the funding transaction the swap needs.

FieldTypeDescription
requiredDecimalStringNative-asset amount the funding transactions need, including the broadcast envelope the chain's admission check reserves on top of the effective fee
availableDecimalStringNative-asset balance currently usable on the sending network

Gas and the sending asset are separate resources

This is neither InsufficientSendingBalance (the wallet has plenty of the asset) nor NoLiquidity (the market is fine). It is the specific case of holding, say, USDC on Arbitrum with no ETH to move it. Fund the wallet with required of the native asset and estimate again.

required is above the raw fee on purpose: an EVM node admits a transaction only when the sender can cover gas × max_fee_per_gas, so a balance that merely equals the expected fee is still rejected. Topping up to exactly required is what clears it.

When it can and cannot fire

Only a funded deposit or channel open raises it. A swap served entirely from existing channel balances signs nothing on chain and needs no gas, so it never appears there. And a swap whose sending asset is itself the native asset cannot produce it either — a wallet short of gas is then short of what it is selling, which is InsufficientSendingBalance. In practice you meet this variant on a token send that needs a channel funded.

The alternative to topping up is the liquidity-service deposit rail — see Deposit rails — which has the hub pay the gas out of the deposit instead.

Older versions of these docs documented a NotEnoughBalance and RentalTooBig variant. Those names no longer exist — they were renamed to FeesHigherThanAmount and LeaseTooBig respectively when the rental flow was rewritten as the Lease flow.

Deposit rails

Added 2026-09-11. Carried as rail on SendingChannelDeposit.

DepositRail says who broadcasts the sending side's channel funding and pays its gas — the entry-side counterpart of ExitRail.

ValueConstantMeaning
0DEPOSIT_RAIL_UNSPECIFIEDTreated as DEPOSIT_RAIL_LOCAL
1DEPOSIT_RAIL_LOCALYour node broadcasts the funding transaction and pays gas from its on-chain native balance
2DEPOSIT_RAIL_LIQUIDITY_SERVICEThe liquidity-service hub broadcasts the funding transaction and pays gas. Your wallet authorises the token pull with a signed permit, or with an allowance it already granted — never with an approval transaction of its own — and pays the hub's quoted fee out of the deposit itself, folded into the swap totals

The liquidity-service rail makes the entry gasless for you: it is what lets a wallet holding only a token — no native asset at all — still fund a sending channel. It is the entry-side answer to InsufficientNativeBalance.

When the sending side takes this rail, the swap stream emits funding_sending_channel_via_liquidity_service alongside the ordinary funding milestones. The same mechanism outside a swap is SponsoredDepositFeePayment on the Lease API.

The rail is chosen for you. There is no field to request one: it is reported on the estimate and on the swap output. Read it to know what the user is actually agreeing to — a fee taken out of the deposit is not the same trade as gas paid from their own balance.

On the liquidity-service rail, SendingChannelDeposit.fee is charged in the sending asset, never in the native asset — so fee_payment_currency on such a deposit is never FEE_PAYMENT_CURRENCY_NATIVE. The same holds for WithdrawalFee on the EXIT_RAIL_LIQUIDITY_SERVICE rail.

WithdrawalFee — the cost of exiting a channel

Carried by sending_withdrawal_fee / receiving_withdrawal_fee on the Instant, Deferred, and DualFundDeferred variants. Present only when that side's funds would be withdrawn from the channel after the swap.

FieldTypeDescription
feeDecimalStringThe fee amount
fee_payment_currencyFeePaymentCurrencyWhich asset pays it: ..._SENDING (1), ..._RECEIVING (2), or ..._NATIVE (3)
exit_railExitRail(added 2026-07-23) Which rail broadcasts this side's exit — see below

ExitRail — who broadcasts and pays gas

Added 2026-07-23.

ValueConstantMeaning
0EXIT_RAIL_UNSPECIFIEDTreated as EXIT_RAIL_LOCAL
1EXIT_RAIL_LOCALYour node broadcasts the exit transaction and pays gas from its on-chain native balance
2EXIT_RAIL_LIQUIDITY_SERVICEThe liquidity-service hub broadcasts and pays the gas; the fee is folded into the swap totals

The liquidity-service rail makes the exit gasless for you — it is what lets a wallet with no native balance still withdraw from a channel after a swap. When a side takes it, the swap stream emits withdrawing_funds_via_liquidity_service instead of the ordinary local-withdrawal milestones.

Why a rail can go to the service when the quoted fee looks affordable

(2026-09-13) A chain admits a transaction against units × max_fee_per_unit, while the quote prices those same units at the live effective rate — on EVM the two can be a factor of two apart. Both rail decisions — this one and the deposit rail — are made against the cap, not the quote.

So a wallet holding more than the quoted fee but less than the cap is put on the service rail. That is deliberate: deciding on the quote is what used to put such a wallet on the local rail and then park it, waiting for gas the service's rail would never have asked for.

The quoted fees are unchanged — WithdrawalFee.fee and SendingChannelDeposit.fee are still what to show the user. Only the choice of rail reads the cap.

Example Request:

import {
  EstimateSimpleSwapRequest,
} from './proto/swap_pb'

const request = new EstimateSimpleSwapRequest()
request.setSendingCurrency({
  protocol: 1, networkId: '0a03cf40', assetId: '0x0000000000000000000000000000000000000000000000000000000000000000'
})
request.setReceivingCurrency({
  protocol: 2, networkId: '11155111',
  assetId: '0x0000000000000000000000000000000000000000'
})
// Amounts are human-readable. "0.1" means 0.1 BTC, not 0.1 sats.
request.setAmount({ from: { amount: { value: '0.1' } } })
request.setPriceChangeTolerance({ value: '0.01' }) // 1 %
request.setWithdrawSendingFunds(false)
request.setWithdrawReceivingFunds(true)

const response = await swap.estimateSimpleSwap(request, {})
const estimate = response.getEstimate()

if (estimate.hasInstant()) {
  const instant = estimate.getInstant()
  console.log('Ready instantly. Will receive:',
    instant.getOrderMatch()?.getReceivingAmount()?.getValue())
}

if (estimate.hasDeferred()) {
  const deferred = estimate.getDeferred()
  if (deferred.hasSendingChannelDeposit()) {
    const dep = deferred.getSendingChannelDeposit()
    console.log('Sending-channel deposit:', dep?.getAmount()?.getValue(),
      'fee:', dep?.getFee()?.getValue())
  }
  if (deferred.hasReceivingChannelLease()) {
    const lease = deferred.getReceivingChannelLease()
    console.log('Receiving-channel lease:', lease?.getAmount()?.getValue(),
      'lease_fee:', lease?.getLeaseFee()?.getValue())
  }
}

if (estimate.hasDualFundDeferred()) {
  const dfd = estimate.getDualFundDeferred()
  console.log('Dual-fund deposit needed:',
    dfd?.getDualFundDeposit()?.getSelfAmount()?.getValue())
}

if (estimate.hasFeesHigherThanAmount()) {
  const fhta = estimate.getFeesHigherThanAmount()
  console.error('Fees exceed swap amount:',
    'sending fee', fhta?.getSendingFee()?.getValue(),
    'receiving fee', fhta?.getReceivingFee()?.getValue())
}

if (estimate.hasLeaseTooBig()) {
  const ltb = estimate.getLeaseTooBig()
  console.error('Lease unavailable:',
    'needed', ltb?.getNeededLease()?.getValue(),
    'available', ltb?.getAvailableLeaseLiquidity()?.getValue())
}

if (estimate.hasNoLiquidity()) {
  console.error('No market liquidity for this pair')
}

Example Response (Instant):

{
  "estimate": {
    "instant": {
      "order_match": {
        "sending_amount": "0.1",
        "receiving_amount": "285",
        "price": "2850"
      },
      "receiving_withdrawal_fee": {
        "fee": "0.0005",
        "fee_payment_currency": "FEE_PAYMENT_CURRENCY_RECEIVING"
      }
    }
  }
}

Example Response (Deferred):

{
  "estimate": {
    "deferred": {
      "order_match": {
        "sending_amount": "0.1",
        "receiving_amount": "285",
        "price": "2850"
      },
      "sending_channel_deposit": {
        "amount": "0.1",
        "unspendable_reserve": "0.00000546",
        "fee": "0.000025",
        "fee_payment_currency": "FEE_PAYMENT_CURRENCY_SENDING",
        "counterparty": "02abc123..."
      },
      "receiving_channel_lease": {
        "amount": "285",
        "unspendable_reserve": "0.001",
        "lease_fee": "0.3",
        "pay_with_sending": true
      }
    }
  }
}

Simple Swap

Execute a swap with automatic channel setup.

Method: SimpleSwap

Features:

  • Automatically opens/deposits channels if needed
  • Rents inbound liquidity if required
  • Performs the swap when channels are ready
  • Optionally withdraws funds back onchain

Parameters:

NameTypeRequiredDescription
sending_currencyOrderbookCurrencyYESCurrency to send
receiving_currencyOrderbookCurrencyYESCurrency to receive
amountSwapAmountYESAmount to swap
price_change_toleranceDecimalStringYESMax price slippage. (2026-11-17) On the whole swap, every fee charged in its two currencies counted, as on EstimateSimpleSwap
withdraw_sending_fundsboolYESAuto-withdraw sent funds
withdraw_receiving_fundsboolYESAuto-withdraw received funds
fee_priorityFeePriorityNO(2026-10-29) How fast the swap's on-chain transactions are to confirm. Unset reads as FEE_PRIORITY_MEDIUM. The swap records it, and SimpleSwapInfo.fee_priority reports it
limit_amountDecimalStringNO(2026-11-17) The worst the swap accepts, as the estimate's limit_amount gives it: for a from swap, the least it delivers, in the receiving currency; for a to swap, the most it sends, in the sending currency. A swap that would do worse trades nothing: see Holding a swap to its limit. Absent: the limit is set from the swap's plan at its start, at price_change_tolerance. At or below zero, or finer than the asset divides into: INVALID_ARGUMENT
plan_shapeSimpleSwapPlanShapeNO(2026-11-17) The plan the swap was confirmed on, as the estimate's case names it: SIMPLE_SWAP_PLAN_SHAPE_INSTANT, SIMPLE_SWAP_PLAN_SHAPE_DEFERRED or SIMPLE_SWAP_PLAN_SHAPE_DUAL_FUND_DEFERRED. The swap starts only if its plan at its start has exactly this shape. Unset: any plan. SIMPLE_SWAP_PLAN_SHAPE_UNSPECIFIED names no shape: set, INVALID_ARGUMENT

Response:

FieldTypeDescription
outputSimpleSwapOutputExecution details

SimpleSwapOutput:

FieldTypeDescription
simple_swap_idstringUnique swap identifier
instant or deferred or dual_fund_deferred-Execution type

(2026-10-29) The node records the swap from its first step that moves funds, and GetSimpleSwap reads it by its simple_swap_id from then on, across restarts. A swap that cannot go on pauses rather than fails: see Recovering a simple swap.

An instant swap places its order before SimpleSwap answers, so two refusals are its own:

  • FAILURE_REASON_SIMPLE_SWAP_ORDER_UNCONFIRMED, with DEADLINE_EXCEEDED and outcome_unknown set: the order went out and no answer came back. The swap is recorded and paused under the simple_swap_id in the error's metadata. Do not send the swap again: continue, return or keep that one.
  • FAILURE_REASON_SIMPLE_SWAP_STOPPED: a cancel, or this node shutting down, stopped the swap before its order. It traded nothing and leaves no record.

(2026-11-17) Any swap is refused at its start, with nothing moved and no record kept, when its plan then is not the one confirmed:

  • FAILURE_REASON_SIMPLE_SWAP_LIMIT_UNMET: the plan would do worse than limit_amount. Metadata: currency, the currency of the side the limit bounds, limit and got, what the plan would deliver or send. Estimate again.
  • FAILURE_REASON_SIMPLE_SWAP_PLAN_CHANGED: the plan is not of the shape plan_shape names. Metadata: plan_shape, the shape of the plan now. Estimate again.

An instant swap whose order the venue would fill past the order's limit is refused with FAILURE_REASON_VENUE_SWAP_LIMIT_UNMET, nothing moved: see Holding a swap to its limit.

Holding a swap to its limit

(2026-11-17) A simple swap is held to one limit on the whole swap: what it delivers, for a from swap, or what it sends, for a to swap, every fee charged in its two currencies counted — the venue's trading fee, its charge for the hub's on-chain steps, what the receive pays for capacity on demand, and the setup and exit fees. Fees paid in a network's native asset are not in it.

Pass the estimate's limit_amount, and its case as plan_shape, to hold the swap to what the user confirmed. Without them the swap sets its limit from its plan at its start, at price_change_tolerance. SimpleSwapInfo.limit_amount reports the limit it runs under.

WhenWhat the swap checksPast the limit
At its startIts plan thenRefused with FAILURE_REASON_SIMPLE_SWAP_LIMIT_UNMET, nothing moved, no record
Before a step that spends: a deposit, a lease, a dual fundingThe book and that step's fee, read againPauses with PRICE_MOVED, the funds where the step would have taken them from
At each orderThe venue holds the order to the limit (SwapOrder.limit_amount)The venue refuses the order whole with swap_limit_unmet (FAILURE_REASON_VENUE_SWAP_LIMIT_UNMET), nothing matched: an instant swap is refused, a later order pauses the swap with PRICE_MOVED
Before a withdrawal on EXIT_RAIL_LIQUIDITY_SERVICEThe exit's fee, quoted again, each channel's after the ones before it were billedThe exit is not made, and the swap pauses with PRICE_MOVED

A withdrawal on EXIT_RAIL_LOCAL, which this node broadcasts, a Lightning close among them, pays the network's fee at the time and is not held to the limit. An order that fills part of the swap is held to the same share of the limit.

The order's own limit is the swap's limit with what the swap does apart from the order: the fees it pays outside the order and what its earlier orders traded. The figures in a swap_limit_unmet refusal are the venue's, for the order.

Worked example. A from swap of 0.01 BTC into USDC, at a tolerance of 0.01. Its plan delivers 1,000.00 USDC, every fee counted: the order receives 1,002.00 USDC, net of everything the venue charges it, and the exit through the liquidity service costs 2.00 USDC. The estimate's limit_amount is 990.00 (1,000.00 × 0.99). The order goes out with a limit_amount of 992.00: the swap's 990.00 plus the 2.00 the exit takes after it.

  • The venue would fill the order for 991.50 USDC: it refuses the order whole, with limit=992.00 got=991.50.
  • The order fills for 995.00 USDC, and the exit is quoted again at 4.00 USDC: the swap would deliver 991.00, within its limit, and the exit is made.
  • The exit is quoted again at 6.00 USDC: the swap would deliver 989.00, so the exit is not made and the swap pauses with PRICE_MOVED, the 995.00 USDC in its channel. Continuing makes the exit once it fits the limit; a higher price_change_tolerance loosens the limit.

Example Request:

TypeScript
const request = new SimpleSwapRequest()
request.setSendingCurrency({
  network: { protocol: 1, id: '0a03cf40' },
  assetId: '0x0000000000000000000000000000000000000000000000000000000000000000'
})
request.setReceivingCurrency({
  network: { protocol: 2, id: '11155111' },
  assetId: '0x0000000000000000000000000000000000000000'
})
request.setAmount({
  from: { amount: { value: '10000000' } }
})
request.setPriceChangeTolerance('0.01')
request.setWithdrawSendingFunds(false)
request.setWithdrawReceivingFunds(true)

const response = await client.simpleSwap(request, {})
const output = response.getOutput()
const swapId = output.getSimpleSwapId()

console.log('Simple swap started:', swapId)

if (output.hasInstant()) {
  const instant = output.getInstant()
  console.log('Swap order:', instant.getOrderId())
}

if (output.hasDeferred()) {
  console.log('Setting up channels...')
  console.log('Subscribe to updates with SubscribeSimpleSwaps')
}
Go
req := &pb.SimpleSwapRequest{
    SendingCurrency: &pb.OrderbookCurrency{
        Network: &pb.Network{
            Protocol: pb.Protocol_PROTOCOL_BITCOIN,
            Id:       "0a03cf40",
        },
        AssetId: "0x0000000000000000000000000000000000000000000000000000000000000000",
    },
    ReceivingCurrency: &pb.OrderbookCurrency{
        Network: &pb.Network{
            Protocol: pb.Protocol_PROTOCOL_EVM,
            Id:       "11155111",
        },
        AssetId: "0x0000000000000000000000000000000000000000",
    },
    Amount: &pb.SwapAmount{
        Amount: &pb.SwapAmount_From_{From: &pb.SwapAmount_From{Amount: &pb.DecimalString{Value: "10000000"}}},
    },
    PriceChangeTolerance:   "0.01",
    WithdrawSendingFunds:   false,
    WithdrawReceivingFunds: true,
}

resp, err := client.SimpleSwap(context.Background(), req)
if err != nil {
    log.Fatalf("Error: %v", err)
}

output := resp.GetOutput()
swapId := output.GetSimpleSwapId()

log.Printf("Simple swap started: %s", swapId)

if instant := output.GetInstant(); instant != nil {
    log.Printf("Swap order: %s", instant.GetOrderId())
}

if output.GetDeferred() != nil {
    log.Println("Setting up channels...")
    log.Println("Subscribe to updates with SubscribeSimpleSwaps")
}
Rust
let request = Request::new(SimpleSwapRequest {
    sending_currency: Some(OrderbookCurrency {
        network: Some(Network {
            protocol: Protocol::Bitcoin as i32,
            id: "0a03cf40".to_string(),
        }),
        asset_id: "0x0000000000000000000000000000000000000000000000000000000000000000".to_string(),
    }),
    receiving_currency: Some(OrderbookCurrency {
        network: Some(Network {
            protocol: Protocol::Evm as i32,
            id: "11155111".to_string(),
        }),
        asset_id: "0x0000000000000000000000000000000000000000".to_string(),
    }),
    amount: Some(SwapAmount {
        amount: Some(your_package::swap_amount::Amount::From(swap_amount::From { amount: Some(DecimalString { value: "10000000".to_string() }) })),
    }),
    price_change_tolerance: "0.01".to_string(),
    withdraw_sending_funds: false,
    withdraw_receiving_funds: true,
});

let response = client.simple_swap(request).await?.into_inner();
let output = response.output.unwrap();
let swap_id = output.simple_swap_id;

println!("Simple swap started: {}", swap_id);

match output.output {
    Some(Output::Instant(instant)) => {
        println!("Swap order: {}", instant.order_id);
    }
    Some(Output::Deferred(_)) => {
        println!("Setting up channels...");
        println!("Subscribe to updates with SubscribeSimpleSwaps");
    }
    _ => {}
}

Estimate Simple Swappable Amounts

Added 2026-04-29.

Returns the smallest and largest amounts that can currently be simple-swapped between two currencies, given the user's wallet balances, current orderbook liquidity, and the LP's leaseable capacity, and names which of these sets the largest.

Use this to populate slider/min-max bounds in a UI, or to sanity-check an amount before calling SimpleSwap.

Method: EstimateSimpleSwappableAmounts

Parameters:

NameTypeRequiredDescription
sending_currencyOrderbookCurrencyYESCurrency to sell
receiving_currencyOrderbookCurrencyYESCurrency to buy
price_change_toleranceDecimalStringYESSame semantic as on EstimateSimpleSwapRequest
withdraw_sending_fundsboolYESWhether the eventual swap will withdraw sent funds on-chain
withdraw_receiving_fundsboolYESWhether the eventual swap will withdraw received funds on-chain

Response: EstimateSimpleSwappableAmountsResponse

FieldTypeDescription
amountsSimpleSwappableAmountsChanged 2026-06-03 — now always present. When no feasible swap exists, all four amounts collapse to "0" and max_limit names why.

SimpleSwappableAmounts:

FieldTypeDescription
min_sendingDecimalStringSmallest sending amount the user can swap
min_receivingDecimalStringReceiving amount when sending min_sending
max_sendingDecimalStringLargest sending amount the user can swap
max_receivingDecimalStringReceiving amount when sending max_sending
max_limitSwappableMaxLimitWhat limits max_sending and the max_receiving it buys, or why all four amounts are zero (2026-10-29)

SwappableMaxLimit Enum (2026-10-29):

ValueDescription
BALANCE (1)The sending balance: what the sending channels can move in one payment plus what the wallet can deposit, after fees and reserves. Zero when nothing is spendable
PAYMENT_CEILING (2)A sending channel's single-payment ceiling, below the balance the channel holds: one payment cannot move all of it
ORDERBOOK_DEPTH (3)The resting orders on the route fill no more. Zero when the side of the book the swap takes holds nothing it can fill
RECEIVING_LEASE (4)The receiving capacity the liquidity provider can lease. Zero when no lease it can open receives the smallest swap the book fills
BELOW_MINIMUM (5)Nothing is swappable: the largest swap in reach is below the venue's minimum order
FEES (6)Nothing is swappable: fees take the whole amount at every size
NO_ROUTE (7)Nothing is swappable: no market connects the two currencies, directly or through one intermediate currency
MARKET_CLOSED (8)Nothing is swappable: every market on the routes between the two currencies refuses a swap in its current state
UNSETTLEABLE_LEG (9)Nothing is swappable: a leg settles on-chain on a network where the venue settles nothing on-chain
ON_DEMAND_RECEIVING (10)(2026-11-17) What the receiving channel can take plus what the hub can add on demand (on_demand_receiving)

A max below the balance is not an error. With ORDERBOOK_DEPTH, the orders resting on the book are all a swap can sell into right now: swapping more needs more orders, not more balance. Selling that max walks the whole book, so check the quote's price before taking it.

Example Request:

import { EstimateSimpleSwappableAmountsRequest } from './proto/swap_pb'

// OrderbookCurrency.assetId form (verified against a live orderbook):
//   • native asset  → zero-padded 32-byte hex: 0x0000…0000
//   • ERC-20 token   → "erc20:<lowercase-contract-address>"
// NOT the ticker ("BTC") and NOT mixed-case ("ERC20:0xAbC…").
const request = new EstimateSimpleSwappableAmountsRequest()
request.setSendingCurrency({
  protocol: 1, networkId: '0a03cf40',
  assetId: '0x0000000000000000000000000000000000000000000000000000000000000000'
})
request.setReceivingCurrency({
  protocol: 2, networkId: '11155111',
  assetId: 'erc20:0x8cd0da3d001b013336918b8bc4e56d9dda1347e0'
})
request.setPriceChangeTolerance({ value: '0.01' })
request.setWithdrawSendingFunds(false)
request.setWithdrawReceivingFunds(true)

const response = await swap.estimateSimpleSwappableAmounts(request, {})
// As of 2026-06-03 `amounts` is always present; check max_sending=="0"
// instead of branching on absence.
const a = response.getAmounts()!
if (a.getMaxSending()?.getValue() === '0') {
  console.log('No feasible swap right now (no liquidity, fees exceed balance, or solver infeasible)')
} else {
  console.log(`Swappable: ${a.getMinSending()?.getValue()} – ${a.getMaxSending()?.getValue()} BTC`)
}

Example Response:

{
  "amounts": {
    "min_sending":   "0.0001",
    "min_receiving": "0.285",
    "max_sending":   "1.64",
    "max_receiving": "4674"
  }
}

Cancel Simple Swap

Cancels an ongoing simple swap operation.

  • Before the swap places its order, it stops where it is. Channels it has already opened, deposited into or leased stay yours, and so do their fees. (2026-10-29) It stops at its next safe step, never inside a step that moves funds, and pauses as stopped: SimpleSwapError with kind STOPPED. It then offers its recovery actions. An instant swap, one that trades from channels it already holds, has moved nothing before its order and leaves nothing to recover: stopped this way, it ends there, its SimpleSwap call fails with FAILURE_REASON_SIMPLE_SWAP_STOPPED, and no record of it is kept.
  • Once the order is placed, the trade completes regardless. The cancel skips what would follow it, moving the swapped funds on-chain (withdraw_sending_funds, withdraw_receiving_funds), unless that has begun. Keep following Subscribe Simple Swaps: the swap reports to its last update, SimpleSwapCompleted, or SimpleSwapError when the order traded nothing. (2026-10-29) SimpleSwapCompleted then comes with cancelled set: the swap ended where it was, what it holds stays in its channels, and it still offers RETURN_FUNDS. An order that traded nothing pauses the swap with kind NOT_EXECUTED.
  • (2026-10-29) While the swap returns its funds, the cancel stops the return until its first exit, and the swap pauses. From the first exit on, the return runs to its end.

(2026-10-29) A paused swap, like one that has ended, answers NOT_FOUND with FAILURE_REASON_SIMPLE_SWAP_NOT_FOUND: nothing is running to cancel.

Method: CancelSimpleSwap

Parameters:

NameTypeRequiredDescription
simple_swap_idstringYESID returned from SimpleSwap

Response: Empty.

Example Request:

import { CancelSimpleSwapRequest } from './proto/swap_pb'

const request = new CancelSimpleSwapRequest()
request.setSimpleSwapId('ss_abc123')

await client.cancelSimpleSwap(request, {})
console.log('Simple swap cancelled')

Example Response:

{}

Subscribe Simple Swaps

Subscribe to real-time updates for all simple swap operations.

(2026-10-29) The stream carries every simple swap of the node, whichever call started, continued or returned it, from the moment you subscribe. It replays nothing: after subscribing again, read where each swap stands with ListSimpleSwaps.

Method: SubscribeSimpleSwaps

Parameters: None

Response: Stream of SimpleSwapUpdate

SimpleSwapUpdate:

FieldTypeDescription
timestampTimestampUpdate time
simple_swap_idstringSwap identifier
update-Update type (one of many variants)

Update Types

Listed in roughly the order a swap emits them. Every payload is shown; an update with no payload shown is an empty marker.

UpdateDescription
waiting_for_depositThe on-chain balance is short for the channel deposit — the user must send funds. { deposit_address, current_balance, needed_amount }. The swap parks here until it is covered
deposit_receivedThe on-chain deposit arrived and the balance is now sufficient
waiting_for_native_asset_depositThe native balance is short for the on-chain fees — the user must send the native asset. { deposit_address, current_balance, needed_amount }
native_asset_deposit_receivedThe native-asset deposit arrived
setting_token_allowanceA token approval was broadcast because the current allowance did not cover the upcoming deposit or dual-fund — { asset_id, amount, txid }
token_allowance_setThe token approval confirmed
funding_sending_channelSending channel being funded, by opening or depositing — { txid, channel_id, amount, is_opening }
leasing_receiving_channelReceiving channel being leased — { txid, channel_id, amount }
dual_funding_channelChannel being dual-funded — { txid, channel_id, self_amount, counterparty_amount, is_opening }
sending_channel_confirming(2026-11-17) The deposit into the sending channel is in a block, gaining confirmations, and not yet relied on — { channel_id, txid, confirmations, expected_depth?, expected_depth_in_secs?, next_depth?, next_depth_in_secs?, bound_depth? }. Sent again on each new block that changes it; sending_channel_ready ends it. See Confirmation updates
receiving_channel_confirming(2026-11-17) The same for the lease of the receiving channel, on the receiving network; receiving_channel_ready ends it
dual_fund_channel_confirming(2026-11-17) The same for a dual funding; dual_fund_channel_ready ends it
sending_channel_readySending channel active — { channel_id }
receiving_channel_readyReceiving channel active — { channel_id }
dual_fund_channel_readyDual-funded channel active — { channel_id }
waiting_for_balancesWaiting for balances to be usable — { needed_sending, needed_receiving }
balances_readyBalances sufficient
order_createdSwap order placed — { order_id }
order_completedSwap executed — { order_id, sent_amount, received_amount }. (2026-11-17) received_amount is what arrived: net of the trading fee and of what the venue charged the receive apart from it, the on-chain fee of a leg that settles on chain and the capacity bought on demand
withdrawing_sending_fundsWithdrawing sent funds — { txids[], self_amount, counterparty_amount }
withdrawing_receiving_fundsWithdrawing received funds — { txids[], self_amount, counterparty_amount }
withdrawing_dual_funded_fundsWithdrawing dual-fund — { txids[], sending_self_amount, sending_counterparty_amount, receiving_self_amount, receiving_counterparty_amount }
sending_funds_withdrawnSend withdrawal complete
receiving_funds_withdrawnReceive withdrawal complete
dual_funded_funds_withdrawnDual-fund withdrawal complete
simple_swap_completedThe swap ended completed: its orders traded, and its funds left their channels as the swap was asked to, or, when cancelled, stayed where they were — { cancelled }. (2026-10-29) cancelled is set when the user cancelled the swap once its order had traded: it ended where it was, its withdrawal skipped, and what it holds stays in its channels, RETURN_FUNDS still offered
simple_swap_errorError occurred — { error, kind, stage }. (2026-10-29) The swap is paused where the error left it, not ended: kind (SimpleSwapFailureKind) says why and stage (SimpleSwapStage) which step it was on. Read its actions with GetSimpleSwap. error is for support, not for display
simple_swap_continued(2026-10-29) A paused swap was picked up again with ContinueSimpleSwap and is running
simple_swap_returning_funds(2026-10-29) The swap, called off with ReturnSimpleSwapFunds, is sending the funds it put into channels back on-chain. The withdrawing_*_funds and *_funds_withdrawn updates of its exits follow
simple_swap_funds_returned(2026-10-29) The return is done, every exit at its network's trusted depth: the swap reads RETURNED. Its last update
simple_swap_funds_kept(2026-10-29) The swap was called off with KeepSimpleSwapFunds, its funds left where they are: it reads KEPT. Its last update. (2026-11-03) A completed swap kept that way stays COMPLETED: what it held in its channels stays there
locking_onchain_htlc(2026-06-24) Sending leg's on-chain HTLC lock tx broadcast — { txid }
onchain_htlc_locked(2026-06-24) Sending leg's on-chain lock reported and watched
counterparty_lock_confirming(2026-06-24) Counterparty's inbound on-chain lock gaining confirmations — { txid, current, required }
counterparty_lock_observed(2026-06-24) Counterparty's inbound on-chain lock observed and confirmed
claiming_onchain_htlc(2026-06-24) Receiving leg's on-chain claim tx broadcast — { txid }
onchain_htlc_claimed(2026-06-24) Receiving leg's on-chain claim observed
refunding_onchain_htlc(2026-06-24) Sending leg's on-chain HTLC refunded after timeout — { txid }
withdrawing_funds_via_liquidity_service(2026-07-23) One side's exit fee is being settled off-chain with the liquidity service, which broadcasts the withdrawal and pays the gas — { is_sending_side, fee, fee_payment_currency }. Appears instead of the local withdrawing_*_funds milestone when that side's exit_rail is EXIT_RAIL_LIQUIDITY_SERVICE.
funding_sending_channel_via_liquidity_service(2026-09-11) The sending channel is being funded by the liquidity service, which submits the wallet's signed permit and the funding transaction and pays the gas — { fee, fee_payment_currency }. Emitted when the deposit's rail is DEPOSIT_RAIL_LIQUIDITY_SERVICE; the fee comes out of the deposit in the sending asset.

The two waiting_for_* updates are the ones that need a UI

Every other milestone is progress you can render passively. These two are the swap telling you it cannot continue until the user acts — it is parked, not working — and each carries the address to send to and how much is still missing. A client that ignores them shows a swap that appears to hang forever.

The *_onchain_htlc / *_lock_* variants appear only when a swap leg settles on-chain (opted via SwapRequest.settlement) rather than through a channel. Channel-only swaps never emit them. See the settlement model.

Example:

TypeScript
const request = new SubscribeSimpleSwapsRequest()
const stream = client.subscribeSimpleSwaps(request, {})

stream.on('data', (update) => {
  const timestamp = update.getTimestamp()
  const swapId = update.getSimpleSwapId()

  if (update.hasFundingSendingChannel()) {
    const funding = update.getFundingSendingChannel()
    console.log(`[${swapId}] Funding channel ${funding.getChannelId()}`)
    console.log(`  TX: ${funding.getTxid()}`)
    console.log(`  Amount: ${funding.getAmount()}`)
  }

  if (update.hasLeasingReceivingChannel()) {
    const renting = update.getLeasingReceivingChannel()
    console.log(`[${swapId}] Renting channel ${renting.getChannelId()}`)
    console.log(`  TX: ${renting.getTxid()}`)
  }

  if (update.hasSendingChannelReady()) {
    console.log(`[${swapId}] Sending channel ready`)
  }

  if (update.hasReceivingChannelReady()) {
    console.log(`[${swapId}] Receiving channel ready`)
  }

  if (update.hasWaitingForBalances()) {
    const waiting = update.getWaitingForBalances()
    console.log(`[${swapId}] Waiting for balances...`)
    console.log(`  Need sending: ${waiting.getNeededSending()}`)
    console.log(`  Need receiving: ${waiting.getNeededReceiving()}`)
  }

  if (update.hasBalancesReady()) {
    console.log(`[${swapId}] Balances ready!`)
  }

  if (update.hasOrderCreated()) {
    const order = update.getOrderCreated()
    console.log(`[${swapId}] Order created: ${order.getOrderId()}`)
  }

  if (update.hasOrderCompleted()) {
    const completed = update.getOrderCompleted()
    console.log(`[${swapId}] Order completed!`)
    console.log(`  Sent: ${completed.getSentAmount()}`)
    console.log(`  Received: ${completed.getReceivedAmount()}`)
  }

  if (update.hasWithdrawingReceivingFunds()) {
    const withdrawing = update.getWithdrawingReceivingFunds()
    console.log(`[${swapId}] Withdrawing funds...`)
    console.log(`  TXs: ${withdrawing.getTxidsList()}`)
  }

  if (update.hasSimpleSwapCompleted()) {
    console.log(`[${swapId}] ✓ Swap completed successfully!`)
  }

  if (update.hasSimpleSwapError()) {
    const error = update.getSimpleSwapError()
    console.error(`[${swapId}] ✗ Error: ${error.getError()}`)
  }
})

stream.on('error', (err) => console.error('Stream error:', err))
Go
req := &pb.SubscribeSimpleSwapsRequest{}
stream, err := client.SubscribeSimpleSwaps(context.Background(), req)
if err != nil {
    log.Fatalf("Error: %v", err)
}

for {
    update, err := stream.Recv()
    if err != nil {
        log.Printf("Stream error: %v", err)
        break
    }

    swapId := update.GetSimpleSwapId()

    if funding := update.GetFundingSendingChannel(); funding != nil {
        log.Printf("[%s] Funding channel %s", swapId, funding.GetChannelId())
        log.Printf("  TX: %s", funding.GetTxid())
        log.Printf("  Amount: %s", funding.GetAmount())
    }

    if renting := update.GetLeasingReceivingChannel(); renting != nil {
        log.Printf("[%s] Renting channel %s", swapId, renting.GetChannelId())
        log.Printf("  TX: %s", renting.GetTxid())
    }

    if update.GetSendingChannelReady() != nil {
        log.Printf("[%s] Sending channel ready", swapId)
    }

    if update.GetReceivingChannelReady() != nil {
        log.Printf("[%s] Receiving channel ready", swapId)
    }

    if waiting := update.GetWaitingForBalances(); waiting != nil {
        log.Printf("[%s] Waiting for balances...", swapId)
        log.Printf("  Need sending: %s", waiting.GetNeededSending())
        log.Printf("  Need receiving: %s", waiting.GetNeededReceiving())
    }

    if update.GetBalancesReady() != nil {
        log.Printf("[%s] Balances ready!", swapId)
    }

    if order := update.GetOrderCreated(); order != nil {
        log.Printf("[%s] Order created: %s", swapId, order.GetOrderId())
    }

    if completed := update.GetOrderCompleted(); completed != nil {
        log.Printf("[%s] Order completed!", swapId)
        log.Printf("  Sent: %s", completed.GetSentAmount())
        log.Printf("  Received: %s", completed.GetReceivedAmount())
    }

    if withdrawing := update.GetWithdrawingReceivingFunds(); withdrawing != nil {
        log.Printf("[%s] Withdrawing funds...", swapId)
        log.Printf("  TXs: %v", withdrawing.GetTxids())
    }

    if update.GetSimpleSwapCompleted() != nil {
        log.Printf("[%s] Swap completed successfully!", swapId)
    }

    if swapError := update.GetSimpleSwapError(); swapError != nil {
        log.Printf("[%s] Error: %s", swapId, swapError.GetError())
    }
}
Rust
let request = Request::new(SubscribeSimpleSwapsRequest {});
let mut stream = client.subscribe_simple_swaps(request).await?.into_inner();

while let Some(update) = stream.message().await? {
    let swap_id = &update.simple_swap_id;

    if let Some(funding) = &update.funding_sending_channel {
        println!("[{}] Funding channel {}", swap_id, funding.channel_id);
        println!("  TX: {}", funding.txid);
        println!("  Amount: {}", funding.amount);
    }

    if let Some(renting) = &update.leasing_receiving_channel {
        println!("[{}] Renting channel {}", swap_id, renting.channel_id);
        println!("  TX: {}", renting.txid);
    }

    if update.sending_channel_ready.is_some() {
        println!("[{}] Sending channel ready", swap_id);
    }

    if update.receiving_channel_ready.is_some() {
        println!("[{}] Receiving channel ready", swap_id);
    }

    if let Some(waiting) = &update.waiting_for_balances {
        println!("[{}] Waiting for balances...", swap_id);
        println!("  Need sending: {}", waiting.needed_sending);
        println!("  Need receiving: {}", waiting.needed_receiving);
    }

    if update.balances_ready.is_some() {
        println!("[{}] Balances ready!", swap_id);
    }

    if let Some(order) = &update.order_created {
        println!("[{}] Order created: {}", swap_id, order.order_id);
    }

    if let Some(completed) = &update.order_completed {
        println!("[{}] Order completed!", swap_id);
        println!("  Sent: {}", completed.sent_amount);
        println!("  Received: {}", completed.received_amount);
    }

    if let Some(withdrawing) = &update.withdrawing_receiving_funds {
        println!("[{}] Withdrawing funds...", swap_id);
        println!("  TXs: {:?}", withdrawing.txids);
    }

    if update.simple_swap_completed.is_some() {
        println!("[{}] Swap completed successfully!", swap_id);
    }

    if let Some(error) = &update.simple_swap_error {
        eprintln!("[{}] Error: {}", swap_id, error.error);
    }
}

Recovering a simple swap

(2026-10-29) The node records a simple swap from its first step that moves funds, so the record survives a restart. A swap that cannot go on is not dropped: it pauses with its funds where its last step left them, says why, and waits. Nothing resumes on its own. The node takes no action on a paused swap, at a restart or at any other time, until the user picks one of its three ways out.

A paused swap holds nothing back: its funds are free for anything else, a new swap included, and continuing plans again from what is there.

Why a swap pauses

SimpleSwapInfo.failure.kind, and kind on the simple_swap_error update that announced the pause, say why (SimpleSwapFailureKind):

KindThe swap paused because
INTERRUPTEDThe app stopped, or its order book connection was replaced, while the swap was running. See After a restart
STOPPEDThe user cancelled it before its order
PRICE_MOVEDThe price moved against the swap past its tolerance. (2026-11-17) The price or the swap's fees moved past its limit: before a step that spends, before its order, or before its withdrawal. The funds stay where that step would have taken them from. See Holding a swap to its limit
NO_LIQUIDITYThe orderbook has nothing to fill it against
NOT_EXECUTEDIts order ended without trading
PARTIALLY_FILLEDIts order traded part of what was left, and the rest is at least the smallest order the hub places on that market. A smaller rest completes the swap instead. (2026-11-17) Where your node can carry the rest on by itself, the swap places its next order instead of pausing: both networks are served by their channel nodes, every peer of the swap's channels is connected, and the rest plans within the swap's limit with no deposit from the wallet and no token approval
LEGS_FAILEDSome of its order's payments failed
ORDER_OUTCOME_UNKNOWNWhether the hub took its order, or what the order traded, cannot be told yet. See An order whose outcome is not known
CHANNEL_SETUPA channel could not be opened, funded or leased
BALANCES_UNAVAILABLEThe balances its order needs did not become available
WITHDRAWALFunds could not be moved out of a channel, after the order or in a return
SERVICE_UNAVAILABLEA service the swap needs is not available
OTHERA failure none of the others describes. Read a kind your client does not know as OTHER
NOT_RECEIVED(2026-11-25) Its order traded, but a payment owed to you was not claimed before its deadline, so that part of what it bought never arrived. unclaimed_amount says how much; it is not in received_amount

failure.message says what went wrong, for support; it is not meant to be shown as is.

Three ways out

SimpleSwapInfo.available_actions lists what a swap offers now. It is empty while the node works on the swap.

ActionCallOfferedWhat it does
SIMPLE_SWAP_ACTION_CONTINUEContinueSimpleSwapOn a paused swap, unless the hub could not tell what an order of it tradedSettles what the swap left open, then plans what is left afresh against the current balances and prices and carries on, on the channels it already set up. It withdraws the proceeds at the end when the swap was asked to. (2026-11-17) The whole swap is still held to its limit: a swap paused before its withdrawal makes it once it fits the limit, and a higher price_change_tolerance loosens the limit
SIMPLE_SWAP_ACTION_RETURN_FUNDSReturnSimpleSwapFundsOn a paused swap, and on a completed one that still holds funds in its channels. (2026-11-03) A completed swap that kept them offers it no more. The call also takes a running swap, which it stops firstCalls the swap off: settles a live order, then moves what the swap put into its channels back on-chain, with what it bought when it was asked for its proceeds on-chain. Costs the exit fees the estimate lists; what the setup cost stays paid. (2026-11-17) A swap paused before its withdrawal withdraws at the fee its return plan states
SIMPLE_SWAP_ACTION_KEEP_FUNDSKeepSimpleSwapFundsOn a paused swap, unless an order it placed may still be on the book or settling: continue or return it to settle that order first. (2026-11-03) On a completed swap, beside RETURN_FUNDS, while it holds funds in its channelsCalls the swap off and leaves its funds where they are, in its channels. (2026-11-03) A completed swap stays COMPLETED and offers nothing more. (2026-11-17) A swap paused before its withdrawal leaves the funds in the channel

An action on offer can still be impossible at the moment, while a channel of the swap is still opening, say. EstimateSimpleSwapRecovery tells, with a typed reason for continuing and for returning. ContinueSimpleSwap and ReturnSimpleSwapFunds are refused, with nothing changed, while the hub has not answered for an order of the swap (FAILURE_REASON_VENUE_RESTARTING) or the peer of a channel they need is not connected (FAILURE_REASON_PEER_NOT_CONNECTED): ask again then.

Where a swap stands

SimpleSwapInfo.status (SimpleSwapStatus):

StatusMeansMoves on to
RUNNINGThe node is working on the swapCOMPLETED; PAUSED; RETURNING when its funds are returned while it runs
PAUSEDThe swap waits for the user; failure says whyRUNNING on Continue, RETURNING on Return, KEPT on Keep
RETURNINGThe node is sending the swap's funds back on-chainRETURNED; PAUSED when a cancel stops it before its first exit, a restart interrupts it, or it leaves something behind
COMPLETEDThe swap finished. One that still holds some of what it put into its channels, or of what it bought when it was asked for its proceeds on-chain, still offers RETURN_FUNDSRETURNING on Return
RETURNEDThe swap was called off and its funds are back on-chain—
KEPTThe swap was called off with its funds left where they were—

COMPLETED, RETURNED and KEPT are terminal: nothing moves a swap out of them on its own. A swap reads RUNNING or RETURNING only while the node works on it; one a run left in either state reads PAUSED, with kind INTERRUPTED.

stage (SimpleSwapStage) is the step the swap is on, or stopped at: PREPARING, FUNDING_SENDING_CHANNEL, LEASING_RECEIVING_CHANNEL, DUAL_FUNDING, PLACING_ORDER, SWAPPING (the order is live or its payments are settling), WITHDRAWING, RETURNING, and DONE.

After a restart

(2026-10-29) A restart pauses every swap the node was working on, with kind INTERRUPTED, at the stage it had reached. Nothing resumes on its own: after a restart, read the swaps with ListSimpleSwaps and offer each paused one's actions.

Whichever action the user takes starts from what the channels, the liquidity service and the hub show: a step whose answer was lost, a channel funding or an order, is read back before anything else is done.

An order whose outcome is not known

(2026-10-29) A swap's order goes out under a client_order_id of its own, and the swap never counts an order as unfilled for want of an answer. When the answer to the placement is lost, the connection dropping as the order goes out say, the swap pauses with ORDER_OUTCOME_UNKNOWN; on the instant path, SimpleSwap fails with FAILURE_REASON_SIMPLE_SWAP_ORDER_UNCONFIRMED instead. When the node stops while the order is live, the swap pauses with INTERRUPTED. Either way, Continue and Return first ask the hub by that id:

The hub answersThe swap
The order is liveWaits for it to end, then goes on from what it traded
The order ended, with what it executedRecords that trade and goes on: nothing is placed again
No order under the id, less than its retention period after the order was first sentTakes the order as never placed: Continue checks the swap's price, then sends the same order under the same id
The order ended with no record of what it traded; or no order under an id the hub had already answered for, or one sent longer ago than its retention periodCannot tell what the order traded. Continue is no longer offered; Return and Keep are, and a return takes out what the swap's own channels hold
Nothing yet: it is restarting, or out of reachChanges nothing. The call is refused with UNAVAILABLE and FAILURE_REASON_VENUE_RESTARTING: send it again

The hub keeps an order's client_order_id for its retention period after the order ends, 24 hours by default (see Create Order), and restores the orders a swap places when it restarts.

Worked example: an order whose answer was lost

(2026-10-29) The amounts in this example are illustrative. A swap sells 0.01 BTC for USDC, with withdraw_receiving_funds set, at FEE_PRIORITY_MEDIUM. It funds its Bitcoin channel with 0.00999845 BTC, the deposit's 155 sats paid out of the 0.01, and at 10:00:00 places its order. The hub restarts as the order goes out, and no answer comes back.

  1. The swap cannot tell whether the hub took the order, so it counts nothing as traded and pauses: simple_swap_error with kind ORDER_OUTCOME_UNKNOWN and stage PLACING_ORDER. GetSimpleSwap reads it as the example shows: PAUSED, sent_amount 0, sending_held 0.00999845, offering CONTINUE, RETURN_FUNDS and KEEP_FUNDS.
  2. At 10:00:20, while the hub is still starting, EstimateSimpleSwapRecovery is refused with UNAVAILABLE and FAILURE_REASON_VENUE_RESTARTING, its metadata naming the swap and the order's client_order_id. Nothing was decided or changed.
  3. At 10:01:00 the hub answers, and so does the estimate: continue_after_reconciling, since continuing reads what the order did first, and a return_plan listing the exits returning would make.
  4. The user continues. ContinueSimpleSwap with fee_priority unset keeps MEDIUM. The swap reports simple_swap_continued, asks the hub by the order's id, and hears that the order ended at 10:00:41, having sold the 0.00999845 BTC for 817.99 USDC net of the trading fee. It records that trade and places nothing. Nothing is left to swap, so it withdraws the USDC on-chain at MEDIUM: withdrawing_receiving_funds, then receiving_funds_withdrawn once the withdrawal is at its network's trusted depth, then simple_swap_completed.

Had the hub answered that it knows no order under that id, less than its retention period after the order was first sent, the order was never placed: Continue checks the swap's price against the rate accepted at the start and sends the same order under the same id. Had it answered that the order ended with no record of what it traded, the swap would pause again without CONTINUE: return or keep it.


List Simple Swaps

(2026-10-29) Lists the simple swaps the node has recorded, newest first: every swap that has not reached a terminal status or still offers an action, and every other one the node's history retention keeps. That retention is settings.auto_prune: with it set, the node drops at startup the ended swaps that offer nothing more and were last updated longer than max_age_secs ago, or fall past the max_entries newest. Without it, every record stays.

Method: ListSimpleSwaps

Parameters: None

Response: { simple_swaps: SimpleSwapInfo[] }

SimpleSwapInfo:

FieldTypeDescription
simple_swap_idstringSwap identifier
created_at / updated_atTimestampWhen the swap started / when its record last changed
sending_currency / receiving_currencyOrderbookCurrencyWhat the swap sells / buys
amountSwapAmountWhat the swap was asked to move
price_change_toleranceDecimalStringThe tolerance it was started with
withdraw_sending_funds / withdraw_receiving_fundsboolWhether its funds leave their channels at the end
statusSimpleSwapStatusSee Where a swap stands
stageSimpleSwapStageThe step it is on, or stopped at
failureSimpleSwapFailure?{ kind, message }: why it is paused, see Why a swap pauses. Set exactly when status is PAUSED
sent_amount / received_amountDecimalStringWhat its orders sold / bought so far, bought net of the trading fee. (2026-11-17) Bought net, too, of what the venue charged the receives apart from it: the on-chain fee of a leg that settles on chain and the capacity bought on demand. (2026-11-25) What was bought but never arrived is not in received_amount: see unclaimed_amount
sending_heldDecimalStringWhat of the sending currency it put into its channels and still holds there: not traded, spent on fees or sent back
receiving_heldDecimalStringWhat of the receiving currency it bought and still holds in its channels
sending_fees_paid / receiving_fees_paidDecimalStringFees it paid in its sending / receiving currency
available_actionsSimpleSwapAction[]What it offers now, see Three ways out. Empty while the node works on it
fee_priorityFeePriorityThe tier its on-chain transactions confirm at: the one it was started at, or last continued or returned at
limit_amountDecimalString(2026-11-17) The limit the swap runs under, as SimpleSwapRequest.limit_amount reads it: as given at the start, or as set from its plan then. Unset on a swap recorded before this field (optional)
unclaimed_amountDecimalString(2026-11-25) What its orders bought that was paid to you and not claimed before its deadline: none of it arrived, and none of it is in received_amount. 0 when everything arrived. An order that leaves some pauses the swap with NOT_RECEIVED
stepsSimpleSwapStep[](2026-11-25) The steps that move the swap's funds, in the order the swap asked for them
order_idsstring[](2026-11-25) The order book's ids of the orders the swap placed, in the order it placed them. The swap's trades are the ClientSwapTrades and ClientMarketTrades whose order_id is one of them. An order the order book has not answered for is not listed

Over JSON-RPC a field that is not optional is present at its default too, false and an empty list among them, enums are sent by name, and every DecimalString is an object { "value": "…" }. See Wire encoding.

Example Response (the swap of the worked example, paused):

{
  "simpleSwaps": [
    {
      "simpleSwapId": "8f7c0e1a-3b7e-4a51-9d0c-2f1e6b9a4c11",
      "createdAt": "2026-10-20T09:58:12Z",
      "updatedAt": "2026-10-20T10:00:10Z",
      "sendingCurrency": { "protocol": "PROTOCOL_BITCOIN", "networkId": "0a03cf40", "assetId": "0x0000000000000000000000000000000000000000000000000000000000000000" },
      "receivingCurrency": { "protocol": "PROTOCOL_EVM", "networkId": "11155111", "assetId": "erc20:0x8cd0da3d001b013336918b8bc4e56d9dda1347e0" },
      "amount": { "from": { "amount": { "value": "0.01" } } },
      "priceChangeTolerance": { "value": "0.01" },
      "withdrawSendingFunds": false,
      "withdrawReceivingFunds": true,
      "status": "SIMPLE_SWAP_STATUS_PAUSED",
      "stage": "SIMPLE_SWAP_STAGE_PLACING_ORDER",
      "failure": {
        "kind": "SIMPLE_SWAP_FAILURE_KIND_ORDER_OUTCOME_UNKNOWN",
        "message": "Whether the venue took the swap's order is not known: …"
      },
      "sentAmount": { "value": "0" },
      "receivedAmount": { "value": "0" },
      "sendingHeld": { "value": "0.00999845" },
      "receivingHeld": { "value": "0" },
      "sendingFeesPaid": { "value": "0.00000155" },
      "receivingFeesPaid": { "value": "0" },
      "availableActions": [
        "SIMPLE_SWAP_ACTION_CONTINUE",
        "SIMPLE_SWAP_ACTION_RETURN_FUNDS",
        "SIMPLE_SWAP_ACTION_KEEP_FUNDS"
      ],
      "feePriority": "FEE_PRIORITY_MEDIUM",
      "unclaimedAmount": { "value": "0" },
      "steps": [
        {
          "requestedAt": "2026-10-20T09:58:13Z",
          "state": { "landed": { "txid": "4f6b0c…e21a" } },
          "deposit": { "amount": { "value": "0.00999845" } }
        }
      ],
      "orderIds": []
    }
  ]
}

orderIds is empty: the hub has not answered for the swap's order. Once Continue hears that the order ended, its id is listed, and the order's trades are the swap's.

SimpleSwapStep

(2026-11-25) One step of a simple swap that moves funds, as the node journaled it: requested_at (1, Timestamp), when the swap asked for it; state (2), where it stands; and one action, what it does. Amounts are in whole units of the asset of the step's side: the swap's sending currency on its sending channel, its receiving currency on its receiving channel.

actionFieldsThe step
open_channel (3)amountOpens a sending channel with the wallet's own funds
deposit (4)amountDeposits the wallet's own funds into an existing sending channel
sponsored_deposit (5)amount, client_request_idHas the liquidity service fund the sending channel from the wallet
lease (6)amount, client_request_idLeases receiving capacity from the liquidity service: amount is the capacity, in the receiving asset
dual_fund (7)amount, client_request_idHas the liquidity service dual-fund one channel for both sides: amount is what the wallet puts in
withdraw_own (8)side, amount, client_request_id?Moves this wallet's side of a channel on chain, keeping the channel
withdraw_counterparty (9)side, amount, client_request_id?Moves the counterparty's side of a channel on chain, keeping the channel
close (10)side, own_side, amount, client_request_id?Closes an asset channel, paying both sides out: amount is what it pays this wallet's side when own_side is true, the counterparty's when it is false

side (SimpleSwapSide) is the side of the swap whose channel the step takes funds out of. A step the liquidity service carries out names its request in client_request_id: GetLiquidityRequests on the network of the step's side lists the request under that id, with its fee, how the fee was paid and the transactions it made. An exit without one is one this node broadcast itself.

state (SimpleSwapStepState) — exactly one arm is set:

ArmThe step
requested (1)Asked for; nothing is known of its outcome yet
unresolved (2)The request ended without telling whether the step took effect. The swap reads its channels and the liquidity service before it moves again
landed (3)Took effect. txid (optional) is the transaction that carried it out, the id GetTransactions reports it under on the network of the step's side; absent when the node did not learn it
not_landed (4)Did not take effect, and never will
outcome_not_recorded (5)Took effect or never will, and the record, kept before the node recorded which, does not say

A step's fee is on the record it names. A step this node broadcast paid its network fee, which its transaction carries (effective_fee); a step the liquidity service carried out paid the service's fee, which its liquidity request carries. The swap's totals are sending_fees_paid and receiving_fees_paid.


Get Simple Swap

(2026-10-29) Returns one recorded simple swap.

Method: GetSimpleSwap

Parameters:

NameTypeRequiredDescription
simple_swap_idstringYESID returned from SimpleSwap

Response: { simple_swap?: SimpleSwapInfo }, the SimpleSwapInfo of the swap. Absent when the node holds no record of it. An id that is not a UUID is refused with INVALID_ARGUMENT and FAILURE_REASON_MALFORMED_REQUEST.


Estimate Simple Swap Recovery

(2026-10-29) Estimates what continuing and returning the funds would do for a swap, without doing either.

Method: EstimateSimpleSwapRecovery

Parameters:

NameTypeRequiredDescription
simple_swap_idstringYESThe swap
fee_priorityFeePriorityNOThe tier to price the on-chain steps at. Unset keeps the swap's own, SimpleSwapInfo.fee_priority

Response: exactly one continue_* field and exactly one return_* field.

FieldTypeDescription
continue_quoteSimpleSwapContinueQuoteContinuing trades what is left under this plan
continue_finishSimpleSwapContinueFinishWhat is left is too small to trade: continuing only moves the swap's funds out of its channels as it was asked to
continue_unavailableSimpleSwapContinueUnavailable{ reason, detail }: why continuing is not possible now, see below
continue_after_reconcilingSimpleSwapContinueAfterReconcilingA step of the swap, an order among them, ended without an answer. Continuing reads what it did first, then plans what is left and checks its price as a quote would. No amounts are known before then
return_planSimpleSwapReturnPlan{ exits: SimpleSwapReturnExit[] }: the exits returning would make, in the order it makes them. Empty when the swap holds nothing in its channels
return_unavailableSimpleSwapReturnUnavailable{ reason, detail }: why returning is not possible now, see below
return_after_reconcilingSimpleSwapReturnAfterReconcilingA step of the swap ended without an answer. Returning reads what it did first; its exits and their fees are known once it has

detail is for support, not for display. The call is refused with FAILURE_REASON_SIMPLE_SWAP_IN_PROGRESS while the node works on the swap, FAILURE_REASON_SIMPLE_SWAP_NOT_FOUND for a swap it holds no record of, FAILURE_REASON_VENUE_RESTARTING while the hub has not answered for an order of the swap, FAILURE_REASON_SIMPLE_SWAP_ORDER_OPEN while an order of it may still trade, and FAILURE_REASON_CHANNEL_NODE_REQUIRED while a side of it needs a network's channel node this node does not serve it with.

SimpleSwapContinueQuote:

FieldTypeDescription
remaining_amountSwapAmountWhat is left to swap
instant / deferred / dual_fund_deferredplanThe plan for what is left, as EstimateSimpleSwap gives it. Exactly one is set
from_amount / to_amountDecimalStringWhat continuing parts with / brings in, every fee of the plan included
required_toleranceDecimalStringThe tolerance continuing needs: how far the whole swap's rate, counting what it already traded and paid, lies below the rate accepted at the start, as a fraction of it. The swap's own tolerance covers it when it is not larger. Always below 1. (2026-11-17) For a swap started with a limit, the rate accepted at the start is the rate that limit allows before its tolerance

Why continuing is not possible

SimpleSwapContinueUnavailableReason:

ReasonMeaning
NOT_OFFEREDThe swap does not offer to continue in its state
SETTLINGA channel of the swap is still being opened or updated. Ask again once it has settled
NO_LIQUIDITYThe orderbook has nothing to fill what is left against
INSUFFICIENT_SENDING_BALANCEThe wallet cannot pay what continuing needs in the sending currency
INSUFFICIENT_NATIVE_BALANCEThe wallet cannot pay the sending network's gas
LEASE_TOO_BIGThe receiving capacity continuing needs exceeds what can be leased
NO_ACCEPTABLE_PRICEThe whole swap would get nothing for what it gives, so no tolerance covers continuing
ESTIMATE_FAILEDThe plan could not be estimated
ORDER_OUTCOME_UNKNOWNWhether the hub took an order of the swap, or what it traded, cannot be told, and the order cannot be sent again under its id without risking a second order. Returning the funds or keeping the swap stays offered
PEER_NOT_CONNECTEDThe peer of one of the swap's channels is not connected, and a plan made without that channel would fund the swap again. Ask again once the peer is connected

Why returning is not possible

SimpleSwapReturnUnavailableReason:

ReasonMeaning
NOT_OFFEREDThe swap does not offer to return its funds in its state
SETTLINGA channel holding the swap's funds is still being opened or updated. Ask again once it has settled
FUNDS_UNREACHABLESome of the swap's funds sit in a channel only a close would empty, and that channel may not be closed
TOO_SMALL (2026-11-03)What the swap holds in a channel is too small to return: its network fee cannot be paid out of it. KEEP_FUNDS leaves the funds where they are
ESTIMATE_FAILEDThe exits could not be estimated
PEER_NOT_CONNECTEDThe peer of a channel holding the swap's funds is not connected, and the exit out of that channel needs it. Ask again once the peer is connected

SimpleSwapReturnExit:

FieldTypeDescription
sideSimpleSwapSideSENDING or RECEIVING: the side of the swap the exit takes funds out of
channel_idstringThe channel
amountDecimalStringWhat the exit moves out of the channel
feeDecimalStringWhat the exit costs
fee_payment_currencyFeePaymentCurrencyWhat the fee is paid in, named against the swap's own currencies
railExitRailWho broadcasts the exit
closes_channelboolWhether the exit closes the channel

How a return takes funds out

  • A channel the swap opened is closed: all of the wallet's side there is the swap's.
  • Any other channel, leased, deposited into or holding the asset before the swap, is withdrawn from (spliced out of, on Lightning) while a withdrawal takes out what is owed, and closed when the channel's reserve holds part of it back.
  • A channel another swap still uses is only ever withdrawn from, never closed. What a withdrawal cannot take out of it stays there: the estimate says FUNDS_UNREACHABLE, and a return pauses with WITHDRAWAL for the rest.
  • While an order's outcome is not known, a return takes out only what the swap's own channels hold: the wallet's whole side of a channel it opened or leased, and at most what it deposited into any other.

Show the user every exit, and in particular each one with closes_channel set.


Continue Simple Swap

(2026-10-29) Continues a paused swap from where it stopped. The call returns once the swap is running again; progress follows on SubscribeSimpleSwaps under the same simple_swap_id, starting with simple_swap_continued.

The swap first settles what it left open: it reads back what a step whose answer was lost did, and asks the hub what became of its orders (see An order whose outcome is not known). It then finishes when nothing is left to trade, or plans what is left afresh, as EstimateSimpleSwap would, and runs that plan on the channels it already set up. Where the plan cannot run, the swap pauses again with its reason.

Continuing is measured against the rate accepted at the start. The price check is on the whole swap: everything it received over everything it gave, the fees of every order and step included, against its rate when it started. When continuing would need more than the swap's tolerance, pass the quote's required_tolerance as price_change_tolerance to accept it. Without it, the swap pauses again with PRICE_MOVED.

Method: ContinueSimpleSwap

Parameters:

NameTypeRequiredDescription
simple_swap_idstringYESThe paused swap
price_change_toleranceDecimalStringNOThe tolerance to continue at, on the whole swap's rate against the rate accepted at the start. Absent keeps the swap's own. In [0, 1). (2026-11-17) For a swap started with a limit, the rate accepted at the start is the rate that limit allows before its tolerance
fee_priorityFeePriorityNOThe tier continuing's on-chain steps confirm at, which the swap records. Unset keeps the swap's own

Response: Empty. Refused, with nothing changed:

  • NOT_FOUND, FAILURE_REASON_SIMPLE_SWAP_NOT_FOUND: the node holds no record of the swap.
  • FAILED_PRECONDITION, FAILURE_REASON_SIMPLE_SWAP_IN_PROGRESS: the node is working on the swap. Ask again once it has paused.
  • FAILED_PRECONDITION, FAILURE_REASON_SIMPLE_SWAP_ACTION_NOT_OFFERED: the swap does not offer to continue. It has ended, or the hub could not tell what an order of it traded.
  • INVALID_ARGUMENT, FAILURE_REASON_TOLERANCE_OUT_OF_RANGE: a tolerance outside [0, 1).
  • UNAVAILABLE, FAILURE_REASON_VENUE_RESTARTING: the hub has not answered yet for an order of the swap. Send it again.
  • UNAVAILABLE, FAILURE_REASON_PEER_NOT_CONNECTED: the peer of one of the swap's channels is not connected. Send it again once it is.
  • UNAVAILABLE, FAILURE_REASON_SIMPLE_SWAP_ORDER_OPEN: an order of the swap may still trade. Send it again once the order has ended.
  • FAILED_PRECONDITION, FAILURE_REASON_CHANNEL_NODE_REQUIRED: a side of the swap needs its network's channel node, which this node does not serve that network with now. Ask again once it does.

Example Request:

import { ContinueSimpleSwapRequest } from './proto/swap_pb'
import { DecimalString } from './proto/primitives_pb'

const request = new ContinueSimpleSwapRequest()
request.setSimpleSwapId(simpleSwapId)
request.setPriceChangeTolerance(new DecimalString().setValue(requiredTolerance))

await client.continueSimpleSwap(request, {})

Return Simple Swap Funds

(2026-10-29) Calls a swap off and sends the funds it put into channels back on-chain, with what it bought when it was asked for its proceeds on-chain. It settles a live order first, cancelling what is left of it, then makes the exits EstimateSimpleSwapRecovery lists, by its rules. It marks the swap RETURNED only once every exit is at its network's trusted depth.

A running swap is stopped first. On a swap already returning its funds, fee_priority confirms the exits it has not sent yet, and those it sent keep theirs. A later CancelSimpleSwap stops the return until its first exit, and the swap pauses; from the first exit on, the return runs to its end.

Progress on SubscribeSimpleSwaps:

  1. simple_swap_returning_funds when the return begins.
  2. withdrawing_sending_funds / withdrawing_receiving_funds with the exits' transactions, then sending_funds_withdrawn / receiving_funds_withdrawn as they reach their depth.
  3. simple_swap_funds_returned at the end, when the swap reads RETURNED.

A return that cannot take everything out, because an exit failed or no allowed exit reaches some of the funds, pauses the swap again with WITHDRAWAL. Ask for it again.

Method: ReturnSimpleSwapFunds

Parameters:

NameTypeRequiredDescription
simple_swap_idstringYESThe swap
fee_priorityFeePriorityNOThe tier the exits confirm at, which the swap records. Unset keeps the swap's own

Response: Empty. Refused, with nothing changed:

  • NOT_FOUND, FAILURE_REASON_SIMPLE_SWAP_NOT_FOUND: the node holds no record of the swap.
  • FAILED_PRECONDITION, FAILURE_REASON_SIMPLE_SWAP_ACTION_NOT_OFFERED: the swap does not offer to return. It was returned or kept already, or it completed with nothing left in its channels.
  • FAILED_PRECONDITION, FAILURE_REASON_SIMPLE_SWAP_IN_PROGRESS: a return the user stopped is still stopping. Ask again once the swap reads PAUSED.
  • UNAVAILABLE, FAILURE_REASON_VENUE_RESTARTING: the hub has not answered yet for an order of the swap. Send it again.
  • UNAVAILABLE, FAILURE_REASON_PEER_NOT_CONNECTED: the peer of a channel holding the swap's funds is not connected. Send it again once it is.
  • UNAVAILABLE, FAILURE_REASON_SIMPLE_SWAP_ORDER_OPEN: an order of the swap may still trade. Send it again once the order has ended.
  • FAILED_PRECONDITION, FAILURE_REASON_CHANNEL_NODE_REQUIRED: a side of the swap needs its network's channel node, which this node does not serve that network with now. Ask again once it does.

Keep Simple Swap Funds

(2026-10-29) Calls a paused swap off and leaves its funds where they are, in its channels. The swap ends KEPT, announced by simple_swap_funds_kept. What it leaves there is then like any other balance of those channels. (2026-11-03) On a completed swap that still holds funds in its channels, it leaves those where they are: the swap stays COMPLETED, simple_swap_funds_kept announces it, and it offers nothing more. A paused swap that does not list KEEP_FUNDS, because an order it placed may still be on the book or settling, can still be asked: the call first asks the hub what became of the swap's orders, and keeps the funds once they have all ended.

Method: KeepSimpleSwapFunds

Parameters:

NameTypeRequiredDescription
simple_swap_idstringYESThe paused swap, (2026-11-03) or a completed one that still holds funds in its channels

Response: Empty. Refused, with nothing changed:

  • NOT_FOUND, FAILURE_REASON_SIMPLE_SWAP_NOT_FOUND: the node holds no record of the swap.
  • FAILED_PRECONDITION, FAILURE_REASON_SIMPLE_SWAP_IN_PROGRESS: the node is working on the swap. Ask again once it has paused.
  • FAILED_PRECONDITION, FAILURE_REASON_SIMPLE_SWAP_ACTION_NOT_OFFERED: the swap is not paused (2026-11-03) or completed with funds in its channels.
  • UNAVAILABLE, FAILURE_REASON_SIMPLE_SWAP_ORDER_OPEN: an order of the swap may still trade. Send it again once the order has ended.
  • UNAVAILABLE, FAILURE_REASON_VENUE_RESTARTING: the hub has not answered yet for an order of the swap. Send it again.
  • FAILED_PRECONDITION, FAILURE_REASON_CHANNEL_NODE_REQUIRED: a side of the swap needs its network's channel node, which this node does not serve that network with now. Ask again once it does.

Common Workflows

One-click cross-chain swap

TypeScript
async function oneClickSwap(
  client: SwapServiceClient,
  fromCurrency: OrderbookCurrency,
  toCurrency: OrderbookCurrency,
  amount: string,
  withdrawToWallet: boolean = true
) {
  // 1. Estimate
  const estimateReq = new EstimateSimpleSwapRequest()
  estimateReq.setSendingCurrency(fromCurrency)
  estimateReq.setReceivingCurrency(toCurrency)
  estimateReq.setAmount({ sending: { value: amount } })
  estimateReq.setPriceChangeTolerance('0.02') // 2% max slippage
  estimateReq.setWithdrawSendingFunds(false)
  estimateReq.setWithdrawReceivingFunds(withdrawToWallet)

  const estimate = await client.estimateSimpleSwap(estimateReq, {})

  if (estimate.getEstimate().hasNoLiquidity()) {
    throw new Error('No liquidity available')
  }
  if (estimate.getEstimate().hasFeesHigherThanAmount()) {
    throw new Error('Setup fees would exceed the swap amount')
  }
  if (estimate.getEstimate().hasLeaseTooBig()) {
    const ltb = estimate.getEstimate().getLeaseTooBig()
    throw new Error(
      `Lease unavailable — needed ${ltb?.getNeededLease()?.getValue()}, ` +
      `have ${ltb?.getAvailableLeaseLiquidity()?.getValue()}`
    )
  }

  // 2. Execute
  const swapReq = new SimpleSwapRequest()
  swapReq.setSendingCurrency(fromCurrency)
  swapReq.setReceivingCurrency(toCurrency)
  swapReq.setAmount({ sending: { value: amount } })
  swapReq.setPriceChangeTolerance('0.02')
  swapReq.setWithdrawSendingFunds(false)
  swapReq.setWithdrawReceivingFunds(withdrawToWallet)

  const response = await client.simpleSwap(swapReq, {})
  return response.getOutput().getSimpleSwapId()
}

// Example usage
const swapId = await oneClickSwap(
  client,
  btcCurrency,
  ethCurrency,
  '10000000', // 0.1 BTC
  true // Auto-withdraw ETH to wallet
)

console.log('Swap started:', swapId)
console.log('Monitor progress with SubscribeSimpleSwaps')
Go
func oneClickSwap(
    client pb.SwapServiceClient,
    fromCurrency *pb.OrderbookCurrency,
    toCurrency *pb.OrderbookCurrency,
    amount string,
    withdrawToWallet bool,
) (string, error) {
    // 1. Estimate
    estimateReq := &pb.EstimateSimpleSwapRequest{
        SendingCurrency:   fromCurrency,
        ReceivingCurrency: toCurrency,
        Amount: &pb.SwapAmount{
            Amount: &pb.SwapAmount_From_{From: &pb.SwapAmount_From{Amount: &pb.DecimalString{Value: amount}}},
        },
        PriceChangeTolerance:   "0.02", // 2% max slippage
        WithdrawSendingFunds:   false,
        WithdrawReceivingFunds: withdrawToWallet,
    }

    estimate, err := client.EstimateSimpleSwap(context.Background(), estimateReq)
    if err != nil {
        return "", err
    }

    if estimate.GetEstimate().GetNoLiquidity() != nil {
        return "", fmt.Errorf("no liquidity available")
    }
    if estimate.GetEstimate().GetFeesHigherThanAmount() != nil {
        return "", fmt.Errorf("setup fees would exceed the swap amount")
    }
    if ltb := estimate.GetEstimate().GetLeaseTooBig(); ltb != nil {
        return "", fmt.Errorf("lease unavailable — needed %s, have %s",
            ltb.GetNeededLease().GetValue(),
            ltb.GetAvailableLeaseLiquidity().GetValue())
    }

    // 2. Execute
    swapReq := &pb.SimpleSwapRequest{
        SendingCurrency:        fromCurrency,
        ReceivingCurrency:      toCurrency,
        Amount: &pb.SwapAmount{
            Amount: &pb.SwapAmount_From_{From: &pb.SwapAmount_From{Amount: &pb.DecimalString{Value: amount}}},
        },
        PriceChangeTolerance:   "0.02",
        WithdrawSendingFunds:   false,
        WithdrawReceivingFunds: withdrawToWallet,
    }

    response, err := client.SimpleSwap(context.Background(), swapReq)
    if err != nil {
        return "", err
    }

    return response.GetOutput().GetSimpleSwapId(), nil
}

// Example usage
swapId, err := oneClickSwap(
    client,
    btcCurrency,
    ethCurrency,
    "10000000", // 0.1 BTC
    true,       // Auto-withdraw ETH to wallet
)
if err != nil {
    log.Fatalf("Error: %v", err)
}

log.Printf("Swap started: %s", swapId)
log.Println("Monitor progress with SubscribeSimpleSwaps")
Rust
async fn one_click_swap(
    client: &mut SwapServiceClient<Channel>,
    from_currency: OrderbookCurrency,
    to_currency: OrderbookCurrency,
    amount: String,
    withdraw_to_wallet: bool,
) -> Result<String, Box<dyn std::error::Error>> {
    // 1. Estimate
    let estimate_req = Request::new(EstimateSimpleSwapRequest {
        sending_currency: Some(from_currency.clone()),
        receiving_currency: Some(to_currency.clone()),
        amount: Some(SwapAmount {
            amount: Some(your_package::swap_amount::Amount::From(swap_amount::From { amount: Some(DecimalString { value: amount.clone().to_string() }) })),
        }),
        price_change_tolerance: "0.02".to_string(), // 2% max slippage
        withdraw_sending_funds: false,
        withdraw_receiving_funds: withdraw_to_wallet,
    });

    let estimate = client.estimate_simple_swap(estimate_req).await?.into_inner();

    match &estimate.estimate.as_ref().unwrap().estimate {
        Some(Estimate::NoLiquidity(_)) => {
            return Err("No liquidity available".into());
        }
        Some(Estimate::FeesHigherThanAmount(_)) => {
            return Err("Setup fees would exceed the swap amount".into());
        }
        Some(Estimate::LeaseTooBig(ltb)) => {
            return Err(format!(
                "Lease unavailable — needed {}, have {}",
                ltb.needed_lease.as_ref().unwrap().value,
                ltb.available_lease_liquidity.as_ref().unwrap().value
            ).into());
        }
        _ => {}
    }

    // 2. Execute
    let swap_req = Request::new(SimpleSwapRequest {
        sending_currency: Some(from_currency),
        receiving_currency: Some(to_currency),
        amount: Some(SwapAmount {
            amount: Some(your_package::swap_amount::Amount::From(swap_amount::From { amount: Some(DecimalString { value: amount.to_string() }) })),
        }),
        price_change_tolerance: "0.02".to_string(),
        withdraw_sending_funds: false,
        withdraw_receiving_funds: withdraw_to_wallet,
    });

    let response = client.simple_swap(swap_req).await?.into_inner();
    Ok(response.output.unwrap().simple_swap_id)
}

// Example usage
let swap_id = one_click_swap(
    &mut client,
    btc_currency,
    eth_currency,
    "10000000".to_string(), // 0.1 BTC
    true,                    // Auto-withdraw ETH to wallet
).await?;

println!("Swap started: {}", swap_id);
println!("Monitor progress with SubscribeSimpleSwaps");

Monitor swap progress

TypeScript
async function waitForSwap(
  client: SwapServiceClient,
  swapId: string
): Promise<SimpleSwapUpdate.SimpleSwapError | undefined> {
  return new Promise((resolve, reject) => {
    const stream = client.subscribeSimpleSwaps(new SubscribeSimpleSwapsRequest(), {})

    stream.on('data', (update) => {
      if (update.getSimpleSwapId() !== swapId) return

      if (update.hasSimpleSwapCompleted()) {
        stream.cancel()
        resolve(undefined)
      }

      if (update.hasSimpleSwapError()) {
        stream.cancel()
        resolve(update.getSimpleSwapError())
      }
    })

    stream.on('error', (err) => reject(err))
  })
}

async function offerRecovery(client: SwapServiceClient, swapId: string): Promise<void> {
  const estimate = await client.estimateSimpleSwapRecovery(
    new EstimateSimpleSwapRecoveryRequest().setSimpleSwapId(swapId), {})
  const swap = (await client.getSimpleSwap(
    new GetSimpleSwapRequest().setSimpleSwapId(swapId), {})).getSimpleSwap()
  const labels = {
    [SimpleSwapAction.SIMPLE_SWAP_ACTION_CONTINUE]: 'Continue',
    [SimpleSwapAction.SIMPLE_SWAP_ACTION_RETURN_FUNDS]: 'Return funds',
    [SimpleSwapAction.SIMPLE_SWAP_ACTION_KEEP_FUNDS]: 'Keep',
  }
  console.log('What continuing and returning would do:', estimate.toObject())
  console.log('Offer:', swap?.getAvailableActionsList().map((action) => labels[action]))
}

// Usage
const paused = await waitForSwap(client, swapId)
if (paused) {
  console.log(`Swap paused: kind ${paused.getKind()}, stage ${paused.getStage()}`)
  await offerRecovery(client, swapId)
} else {
  console.log('Swap completed')
}
Go
func waitForSwap(
    client pb.SwapServiceClient,
    swapId string,
) (*pb.SimpleSwapUpdate_SimpleSwapError, error) {
    req := &pb.SubscribeSimpleSwapsRequest{}
    stream, err := client.SubscribeSimpleSwaps(context.Background(), req)
    if err != nil {
        return nil, err
    }

    for {
        update, err := stream.Recv()
        if err != nil {
            return nil, err
        }

        if update.GetSimpleSwapId() != swapId {
            continue
        }

        if update.GetSimpleSwapCompleted() != nil {
            return nil, nil
        }

        if paused := update.GetSimpleSwapError(); paused != nil {
            return paused, nil
        }
    }
}

func offerRecovery(client pb.SwapServiceClient, swapId string) error {
    ctx := context.Background()
    estimate, err := client.EstimateSimpleSwapRecovery(ctx, &pb.EstimateSimpleSwapRecoveryRequest{SimpleSwapId: swapId})
    if err != nil {
        return err
    }
    swap, err := client.GetSimpleSwap(ctx, &pb.GetSimpleSwapRequest{SimpleSwapId: swapId})
    if err != nil {
        return err
    }
    labels := map[pb.SimpleSwapAction]string{
        pb.SimpleSwapAction_SIMPLE_SWAP_ACTION_CONTINUE:     "Continue",
        pb.SimpleSwapAction_SIMPLE_SWAP_ACTION_RETURN_FUNDS: "Return funds",
        pb.SimpleSwapAction_SIMPLE_SWAP_ACTION_KEEP_FUNDS:   "Keep",
    }
    log.Printf("What continuing and returning would do: %v", estimate)
    for _, action := range swap.GetSimpleSwap().GetAvailableActions() {
        log.Printf("Offer: %s", labels[action])
    }
    return nil
}

// Usage
paused, err := waitForSwap(client, swapId)
switch {
case err != nil:
    log.Printf("Stream failed: %v", err)
case paused != nil:
    log.Printf("Swap paused: kind %s, stage %s", paused.GetKind(), paused.GetStage())
    if err := offerRecovery(client, swapId); err != nil {
        log.Printf("Recovery estimate failed: %v", err)
    }
default:
    log.Println("Swap completed")
}
Rust
async fn wait_for_swap(
    client: &mut SwapServiceClient<Channel>,
    swap_id: String,
) -> Result<Option<simple_swap_update::SimpleSwapError>, Box<dyn std::error::Error>> {
    use simple_swap_update::Update;

    let request = Request::new(SubscribeSimpleSwapsRequest {});
    let mut stream = client.subscribe_simple_swaps(request).await?.into_inner();

    while let Some(update) = stream.message().await? {
        if update.simple_swap_id != swap_id {
            continue;
        }

        match update.update {
            Some(Update::SimpleSwapCompleted(_)) => return Ok(None),
            Some(Update::SimpleSwapError(paused)) => return Ok(Some(paused)),
            _ => {}
        }
    }

    Err("Stream ended unexpectedly".into())
}

async fn offer_recovery(
    client: &mut SwapServiceClient<Channel>,
    simple_swap_id: String,
) -> Result<(), Box<dyn std::error::Error>> {
    let estimate = client
        .estimate_simple_swap_recovery(EstimateSimpleSwapRecoveryRequest {
            simple_swap_id: simple_swap_id.clone(),
            ..Default::default()
        })
        .await?
        .into_inner();
    let swap = client
        .get_simple_swap(GetSimpleSwapRequest { simple_swap_id })
        .await?
        .into_inner()
        .simple_swap
        .ok_or("no record of the swap")?;

    println!("What continuing and returning would do: {estimate:?}");
    for action in swap.available_actions() {
        let label = match action {
            SimpleSwapAction::Continue => "Continue",
            SimpleSwapAction::ReturnFunds => "Return funds",
            SimpleSwapAction::KeepFunds => "Keep",
            SimpleSwapAction::Unspecified => continue,
        };
        println!("Offer: {label}");
    }
    Ok(())
}

// Usage
match wait_for_swap(&mut client, swap_id.clone()).await? {
    Some(paused) => {
        println!("Swap paused: kind {:?}, stage {:?}", paused.kind(), paused.stage());
        offer_recovery(&mut client, swap_id).await?;
    }
    None => println!("Swap completed"),
}

Price Change Tolerance

The price_change_tolerance parameter protects you from excessive slippage:

TypeScript
// Formula: (max_tolerated_price - intended_price) / intended_price

// Example: BTC/ETH at 28.5 ETH per BTC
// With 1% tolerance (0.01):
// - Max buy price: 28.5 * 1.01 = 28.785 ETH/BTC
// - Min sell price: 28.5 * 0.99 = 28.215 ETH/BTC

request.setPriceChangeTolerance('0.01') // 1% tolerance
Go
// Formula: (max_tolerated_price - intended_price) / intended_price

// Example: BTC/ETH at 28.5 ETH per BTC
// With 1% tolerance (0.01):
// - Max buy price: 28.5 * 1.01 = 28.785 ETH/BTC
// - Min sell price: 28.5 * 0.99 = 28.215 ETH/BTC

request.PriceChangeTolerance = "0.01" // 1% tolerance
Rust
// Formula: (max_tolerated_price - intended_price) / intended_price

// Example: BTC/ETH at 28.5 ETH per BTC
// With 1% tolerance (0.01):
// - Max buy price: 28.5 * 1.01 = 28.785 ETH/BTC
// - Min sell price: 28.5 * 0.99 = 28.215 ETH/BTC

request.price_change_tolerance = "0.01".to_string(); // 1% tolerance

(2026-11-17) The tolerance bounds the whole swap, not the order's price. Every fee charged in the swap's two currencies counts against it: the venue's trading fee, its charge for the hub's on-chain steps, what the receive pays for capacity on demand, and the setup and exit fees. A from swap delivers at least (1 − tolerance) of what its plan delivers; a to swap sends at most (1 + tolerance) of what its plan sends. The estimate states that bound as limit_amount, and Holding a swap to its limit says where the swap checks it. Fees paid in a network's native asset are not counted.

For a from swap whose plan delivers 1,000.00 USDC, a tolerance of 0.01 gives a limit_amount of 990.00 USDC. For a to swap of 1,000.00 USDC whose plan sends 0.0100 BTC, it gives 0.0101 BTC.

Recommended values:

  • 0.005 (0.5%) - Very tight, may fail in volatile markets
  • 0.01 (1%) - Standard for most swaps
  • 0.02 (2%) - More lenient for illiquid pairs
  • 0.05 (5%) - Very lenient, use with caution

Fee Priority

(2026-10-29) fee_priority (FeePriority, in fee.proto) sets how fast a simple swap's on-chain transactions confirm: its deposits, channel opens, token approvals and withdrawals, and the gas reserves its estimate holds back for them. Each tier reads the network's own fee estimate at its level, the low, medium or high that GetFeeEstimates reports:

FeePriorityTierBitcoinEVM networksTron
FEE_PRIORITY_LOWSlowlow: the 144-block targetlow: medium's tip and fee cap at 70%medium's
FEE_PRIORITY_MEDIUMAveragemedium: the 6-block targetmedium: the network's EIP-1559 estimate of tip and fee capThe network's resource prices
FEE_PRIORITY_HIGHFasthigh: the next-block targethigh: medium's tip and fee cap at 150%medium's

Bitcoin pays at least 1 sat/vB at every tier, so in a quiet mempool LOW often costs what MEDIUM does. The base fee is the same at every EVM tier, so where the tip is near zero the three cost the same. Tron's resource prices are network constants: its three tiers are one.

Example. A swap of 0.01 BTC for USDC on Arbitrum, its proceeds withdrawn on-chain, makes one Bitcoin deposit, a one-input channel funding of about 153 vB, and one Arbitrum withdrawal. With Bitcoin's estimates at 0.633, 1.01 and 1.198 sat/vB, the 1 sat/vB floor lifts low to 1.0, and the deposit costs 153 sats at LOW, 155 at MEDIUM and 183 at HIGH. With Arbitrum's tip at 0, the withdrawal costs the same at all three. Estimate the swap at each tier to show the user what each costs before they choose.


Best Practices

  1. Always estimate first. EstimateSimpleSwap is what tells you which of the setup paths a swap will take, and what it will cost.
  2. Branch on every estimate variant, not just the three success ones — see Error Handling.
  3. Set a realistic price_change_tolerance — 1–2% for liquid pairs, more for illiquid ones. Too tight and the execute fails after the setup transactions have already been paid for. (2026-11-17) Pass the estimate's limit_amount and its case as plan_shape, so the swap trades only on the plan the user confirmed.
  4. Read the rails, not just the fees. rail and exit_rail decide whether the user pays gas from their own balance or a fee out of the swap. Show which one applies.
  5. Quantise amounts to the market grid before sending. The orderbook rejects an over-precise amount rather than rounding it.
  6. Follow the swap with SubscribeSimpleSwaps. A simple swap is many on-chain steps; the stream is the only view of where it is.
  7. Cancel deliberately. CancelSimpleSwap stops a swap that has not yet committed — it does not unwind transactions already broadcast. (2026-10-29) The swap pauses, or ends where it is once its order has traded; returning its funds is what takes them back on-chain.
  8. Use Swap only when both channels already hold funds. It does no setup; SimpleSwap is the path that arranges liquidity for you.
  9. (2026-10-29) Offer every paused swap's actions, after a restart too. ListSimpleSwaps holds them, and nothing moves a paused swap's funds until the user picks one of its ways out.

Error Handling

Most "failures" of a simple swap are not errors: they are variants of the SimpleSwapEstimate one-of, returned by a successful EstimateSimpleSwap call. Branch on them explicitly — a switch that only handles instant / deferred / dual_fund_deferred will misreport every one of these.

Estimate variantWhat it meansWhat to do
no_liquidityThe market cannot serve this pairTry another amount or pair, or wait
fees_higher_than_amountChannel-setup fees exceed the amount being swappedSwap more, or pick a pair that needs less setup
lease_too_bigThe receiving lease exceeds the provider's available or maximum capacityReduce the amount, wait for liquidity, or open the receiving channel yourself via the Node API
insufficient_sending_balanceThe wallet has nothing to sendFund the sending asset
insufficient_native_balanceThe wallet holds the asset but cannot pay gasTop up the native asset to required

Genuine RPC errors follow the usual status codes. The two you will meet most:

ErrorDescriptionSolution
FAILED_PRECONDITIONPrice moved past price_change_tolerance between estimate and execute, or a channel was no longer usable. (2026-11-17) FAILURE_REASON_SIMPLE_SWAP_LIMIT_UNMET, FAILURE_REASON_SIMPLE_SWAP_PLAN_CHANGED and FAILURE_REASON_VENUE_SWAP_LIMIT_UNMET name a plan, or an order, past the swap's limit or of another shapeRe-estimate and retry; widen the tolerance if the pair is volatile
INVALID_ARGUMENTAn amount carries more decimals than the market side allowsQuantise first — to base_precision for a base amount, to a quote amount's decimal places for a quote amount (see Amounts and prices); the orderbook rejects rather than rounds

(2026-10-29) A paused swap is not an error of the call that started it: it arrives as simple_swap_error on the stream, and the swap waits for its recovery actions. The recovery calls, and an instant SimpleSwap, answer with reasons of their own: FAILURE_REASON_SIMPLE_SWAP_IN_PROGRESS, FAILURE_REASON_SIMPLE_SWAP_ACTION_NOT_OFFERED, FAILURE_REASON_SIMPLE_SWAP_STOPPED, FAILURE_REASON_SIMPLE_SWAP_ORDER_UNCONFIRMED and FAILURE_REASON_VENUE_RESTARTING. Reasons says what to do with each.


← Back to API Reference | Next: Node API →


Copyright © 2025