Skip to main content

Api

HTTP client for the AnySwap server API.

The Driver takes this client as its ServerClient and makes the swap calls below itself; an app calls AnySwapClient.getInfo, AnySwapClient.getSwaps and AnySwapClient.signals.

The server is always the responder; the user always initiates. POST methods trigger server-side transitions and return an empty body - the resulting state is always read back via AnySwapClient.getSwap, never from the POST response. Track progress with AnySwapClient.subscribe: it nudges you on connect and on every transition, and you read the current state over HTTP (typically AnySwapClient.getSwaps) in response.

Swap-in (on-chain to Lightning)​

After creating a swap-in (AnySwapClient.createSwap with an on-chain source_chain and no destination), follow the status via AnySwapClient.getSwap:

AwaitOpeningTxConfirmation (deposit to the swap address; the server watches for it) -> PayInvoice -> AwaitClaimKeyRevealMessage (reveal the refund key via AnySwapClient.revealClaim for a cooperative keypath claim) -> AwaitClaimTxConfirmation -> Claimed.

AnySwapClient.cancel before a successful claim yields Canceled, where the server reveals source_claim_privkey for an immediate keypath refund.

Swap-out (Lightning to on-chain)​

After creating a swap-out (AnySwapClient.createSwap with a dest_chain and no source), follow the status via AnySwapClient.getSwap:

AwaitClaimInvoicePay (pay the held claim_invoice) -> OpeningTxBroadcast -> AwaitPreimageRevealed (claim cooperatively via AnySwapClient.revealPreimage then keypath spend, or unilaterally on-chain) -> Claimed.

If the user never claims, the server refunds after the CSV timeout (AwaitRefundTxConfirmation -> Refunded). There is no way to abort a swap-out once its opening tx is broadcast.

Classes​

AnySwapClient​

HTTP client for the AnySwap server API.

Constructors​

Constructor​
new AnySwapClient(url: string, options?: AnySwapClientOptions): AnySwapClient;
Parameters​
ParameterTypeDescription
urlstringBase URL of the swap server. Trailing slashes are stripped.
optionsAnySwapClientOptionsOptional fetch implementation and the wallet that signs protected swap endpoints.
Returns​

AnySwapClient

Methods​

cancel()​
cancel(swapId: string, body: CancelRequest): Promise<void>;

Requests swap cancellation. The outcome is observed via AnySwapClient.getSwap: Canceled reveals the server's claim privkey (swap-in) for an immediate keypath refund of any deposit.

Parameters​
ParameterType
swapIdstring
bodyCancelRequest
Returns​

Promise<void>

createSwap()​
createSwap(body: CreateSwapRequest): Promise<void>;

Initiates a swap. The server may cancel the swap right after creation; the actual state is discovered via AnySwapClient.getSwap.

An optional webhook is refused with a 400 when the server has webhooks off or the url breaks its rules; webhook on AnySwapClient.getInfo reports both.

Parameters​
ParameterType
bodyCreateSwapRequest
Returns​

Promise<void>

getInfo()​
getInfo(): Promise<InfoResponse>;

Fetches server info: the current policy, base-fee estimates, and a quote_id (valid for quote_ttl) locking them.

Returns​

Promise<InfoResponse>

getSwap()​
getSwap(swapId: string): Promise<SwapState>;

Reads the current state of a swap.

Parameters​
ParameterType
swapIdstring
Returns​

Promise<SwapState>

getSwaps()​
getSwaps(params: GetSwapsParams): Promise<SwapListResponse>;

Lists swaps for a user, newest first. Used during recovery to discover swap history after restoring a wallet from its mnemonic.

Parameters​
ParameterType
paramsGetSwapsParams
Returns​

Promise<SwapListResponse>

listSwaps()​
listSwaps(query: SwapListQuery): Promise<SwapListResponse>;

The listing over a raw SwapListQuery, the form the WASM driver's ServerClient calls; AnySwapClient.getSwaps is the typed one.

Parameters​
ParameterType
querySwapListQuery
Returns​

Promise<SwapListResponse>

revealClaim()​
revealClaim(swapId: string, body: RevealClaimRequest): Promise<void>;

Reveals the user's refund privkey after the claim invoice was paid (swap-in only), letting the server claim cooperatively via the keypath instead of the preimage script path.

Parameters​
ParameterType
swapIdstring
bodyRevealClaimRequest
Returns​

Promise<void>

revealPreimage()​
revealPreimage(swapId: string, body: RevealPreimageRequest): Promise<void>;

Reveals the preimage off-chain (swap-out only) instead of claiming via the script path. The server settles the held invoice and exposes its refund privkey, letting the user finish with a cheap cooperative keypath claim. Reveal only after the opening tx has the required confirmations.

Parameters​
ParameterType
swapIdstring
bodyRevealPreimageRequest
Returns​

Promise<void>

signals()​
signals(options?: SubscribeOptions): SwapSignals;

Wraps AnySwapClient.subscribe as the WASM driver's Signals: pass the result to Driver.withSignals. Every pushed swap id is queued until next takes it; the reconnect nudge carries none and is dropped, since the driver reads fresh state on every pass anyway.

Parameters​
ParameterType
optionsSubscribeOptions
Returns​

SwapSignals

subscribe()​
subscribe(onUpdate: (update?: SwapStateUpdate) => void, options?: SubscribeOptions): Subscription;

Subscribes to the wallet's swap-change signals over the server's WebSocket. onUpdate gets the { swap_id, status } signal per transition, or undefined on (re)connect and on an unparseable frame ("resync, swap unknown"). It is a nudge: read authoritative state over HTTP (AnySwapClient.getSwap / AnySwapClient.getSwaps) in response; do not trust the pushed status for safety-critical decisions. On a drop it reconnects with a freshly signed upgrade after a second, doubling to 30 seconds while attempts fail and back to a second once one opens, until the returned handle's stop() is called, and onConnectionChange hears of each drop and each return. The server pings every 30 seconds to keep the socket alive and allows 16 subscriptions per wallet; a browser tab holds one.

Requires a global WebSocket (browsers, Node >= 22).

Parameters​
ParameterType
onUpdate(update?: SwapStateUpdate) => void
optionsSubscribeOptions
Returns​

Subscription

a Subscription; call stop() to close it.

Interfaces​

AnySwapClientOptions​

Options for AnySwapClient.

Properties​

PropertyTypeDescription
fetchFn?(input: string | URL | Request, init?: RequestInit) => Promise<Response>Optional fetch implementation. Defaults to the global fetch.
wallet?WalletThe wallet whose identity key signs protected requests, inside the wasm module. Without one, only the public endpoints work.

GetSwapsParams​

Parameters for AnySwapClient.getSwaps.

Every field below offset is an optional filter. They combine with AND and apply before limit/offset, so pagination.total counts the swaps that matched rather than every swap the user owns. An omitted or empty filter is simply not applied.

Properties​

PropertyTypeDescription
createdAfter?numberKeeps swaps created at or after this unix timestamp, in seconds.
createdBefore?numberKeeps swaps created at or before this unix timestamp, in seconds.
errorType?SwapErrorCode[]Keeps swaps cancelled for any of these reasons, e.g. ["Timeout"]. Only a cancelled swap has one, so this drops every other swap too.
isActive?booleantrue returns only swaps still in flight, false only those that reached a terminal status (Claimed, Canceled, Refunded); omit for both.
limit?numberMaximum number of swaps to return, at most 100. Defaults to 20.
maxAmount?numberKeeps swaps whose received amount is at most this many sats.
minAmount?numberKeeps swaps whose received amount is at least this many sats.
offset?numberNumber of swaps to skip, newest first. Defaults to 0.
search?stringKeeps swaps where one of swapId, paymentHash, claimInvoice, sourceTxid, destTxid, or userClaimAddress equals this value. The match ignores case but is exact, so a prefix of a txid finds nothing.
status?SwapStatus[]Keeps swaps in any of these statuses, e.g. ["Claimed", "Refunded"].
swapType?SwapTypeKeeps only swaps of this type.
userIdstringUser identifier, typically !Wallet.userId | Wallet.userId.
withCreateRequest?booleantrue includes each swap's create_request_* fields, as getSwap does; a page omits them otherwise.

SubscribeOptions​

Options for AnySwapClient.subscribe and AnySwapClient.signals.

Properties​

PropertyTypeDescription
onConnectionChange?(connected: boolean) => voidCalled with false when the socket drops and true when one opens, once per change and never after stop(). It starts disconnected, so the first call is true.

Subscription​

A WebSocket subscription handle.

Extended by​

Methods​

stop()​
stop(): void;

Closes the subscription and stops reconnecting.

Returns​

void


SwapSignals​

The WASM driver's Signals, returned by AnySwapClient.signals: a push channel naming swaps worth reading sooner.

Extends​

Methods​

next()​
next(): Promise<string | undefined>;

Resolves with the id of the next swap the server reported, waiting for one when none is queued, and with undefined once stopped.

Returns​

Promise<string | undefined>

stop()​
stop(): void;

Closes the subscription and stops reconnecting.

Returns​

void

Inherited from​

Subscription.stop