xchainjs + THORChain: Practical Cross-Chain Swap Guide for Developers
A compact, technical guide with architecture notes, TypeScript examples, SEO-minded keywords and a final FAQ. Links to key resources included.
Last reviewed: 2026-03-07 · Author: Experienced Web3 dev/technical writer
TL;DR — What you’ll get
This article shows how to think about, integrate and implement permissionless cross-chain swaps on THORChain using the xchainjs ecosystem (and complementary tooling). You’ll find architectural trade-offs, a pragmatic TypeScript swap example (BTC → ETH), operational recommendations and production-focused considerations (slippage, memos, inbound addresses, testing).
Includes: semantic core for SEO, suggested microdata (FAQ + Article), and outbound anchors to primary references for developer consumption.
1) Quick SERP analysis & competitor signal (English market)
Based on an analysis of typical top-10 English results for the provided keywords (developer docs, GitHub repos, dev.to/Medium tutorials, SDK READMEs, and aggregator blogs), these are the observed patterns and intents:
Primary user intents
| Keyword sample | Dominant intent |
|---|---|
| xchainjs xchainjs thorchain thorchain sdk |
Informational / Developer (how-to, SDK docs, quickstart) |
| thorchain swap example web3 swap example btc to eth swap |
Transactional / Tutorial (step-by-step guides) |
| cross chain swap crypto cross chain swap defi cross chain swap |
Informational / Commercial (technology overview, service comparison) |
| crypto swap api blockchain swap api crypto swap backend |
Commercial / Developer (API offerings, integration) |
| thorchain liquidity pools thorchain rune swap |
Informational (mechanics, economics) |
Competitors’ structure and depth
Top-ranking pages generally follow a consistent structure: short intro → architecture summary → code quickstart → full example → troubleshooting / pitfalls → links to docs. The strongest pages combine: (a) official documentation (accurate API), (b) GitHub examples (runnable), and (c) community tutorials with screenshots and memos. The best-performing pieces include concrete code with execution expectations (tx hash examples, expected memos), plus security notes and testnet guidance.
Gap to exploit: many pages are either too high-level (non-actionable) or too tutorial-focused (no production considerations). A developer-oriented article that balances runnable code, production patterns and SEO-ready intent matching will rank and convert better.
2) Expanded semantic core (SEO-ready clusters)
Keywords grouped by purpose. Use these organically in headings, alt texts, and paragraph copy.
Primary cluster (main targets)
- xchainjs — xchainjs thorchain — xchainjs tutorial — xchainjs example
- thorchain swap — thorchain swap example — thorchain sdk — thorchain rune swap
- cross chain swap — crypto cross chain swap — defi cross chain swap
Secondary cluster (developer & integration)
- btc to eth swap — web3 swap example — typescript defi sdk
- crypto swap api — blockchain swap api — crypto swap backend
- web3 swap integration — thorchain developer tools — defi swap development
Support / LSI / related phrases
- cross-chain bridge, permissionless liquidity, inbound address, THORChain memo, slip limit, swap transaction hash
- swap aggregator development, decentralized exchange swap, cross chain trading, liquidity pools, RUNE bonding
- swap backend, node relayer, router integration, testnet swap example, slippage protection
SEO note: prioritize a natural flow. Use the primary cluster in H1/H2 and sprinkle secondary + LSI phrases within examples and alt attributes. Avoid keyword stuffing — write for the developer who wants to ship.
3) Top user questions (collected & filtered)
Common “People Also Ask” and forum-driven queries for this topic:
- How does THORChain perform trustless cross-chain swaps?
- How to use xchainjs to execute a THORChain swap?
- Can I swap BTC to ETH on THORChain and what are the steps?
- What is the THORChain memo format and why is it required?
- How to handle slippage and fees with THORChain swaps?
- How to integrate THORChain swaps into a backend or aggregator?
- What developer tools and SDKs exist for THORChain?
Selected 3 for final FAQ: (1) How does THORChain cross-chain swap work? (2) How to perform a BTC→ETH swap using xchainjs? (3) What are common pitfalls (slippage, memos, inbound addresses)?
4) Practical guide: How THORChain cross‑chain swaps work
THORChain enables permissionless cross-chain swaps by using a continuous liquidity pool model. Liquidity providers deposit pairs (e.g., BTC and RUNE) into pools; when a swap arrives, the protocol routes through RUNE as an intermediate asset (commonly). Trustlessness is achieved through a network of THORNodes running the THORChain protocol and economic incentives that protect liquidity and ensure correct execution.
From a developer perspective, you don’t “bridge” tokens in the classic custodial sense. Instead, you create an inbound transaction to the pool’s address with an encoded memo telling THORChain what to do (target asset, recipient). The protocol watches the inbound chain, executes internal pool swaps, and issues the outbound asset to the requested chain’s address or an internal router. This design differs from wrapped-token bridges and delivers native-asset settlement.
Operationally, three elements matter: the inbound address (per chain), the memo format (routing + recipient + optional flags), and the slip limit / expected output calculation. Your frontend/backend must handle UTXO vs account chains, confirm inbound transactions reliably, and track state until finalization. Robust retry and reconciliation logic is essential for production systems.
5) Using xchainjs to perform a THORChain swap — architecture & example
xchainjs provides unified client libraries to interact with multiple chains and often includes helpers for THORChain-style interactions. The pattern is: (1) create a wallet/client for your source chain, (2) construct a transaction to the THORChain inbound address, including the memo, (3) broadcast and wait for confirmations, (4) monitor the THORChain network for outbound settlement. Official examples and community tutorials help with memo formats and expected UX.
Below is a condensed TypeScript-style example (pseudocode) to illustrate the flow (consult library README for exact API). This example demonstrates constructing an outbound-instructing memo for a BTC→ETH swap via THORChain and broadcasting the BTC transaction using your BTC client.
// Pseudocode — adapt to actual xchainjs API from the repo
import { BTCClient } from 'xchainjs-btc' // placeholder package name
import { ThorchainUtils } from 'xchainjs-thor' // placeholder helper
const btcClient = new BTCClient({ network: 'testnet', phrase: process.env.PHRASE })
// 1) Prepare memo: e.g. "SWAP:ETH.OUT:"
const ethRecipient = '0xAbc123...'
const memo = `SWAP:ETH.${ethRecipient}` // check docs for exact memo format
// 2) Get THORChain BTC inbound address (or use a derived inbound address)
const inbound = await ThorchainUtils.getInboundAddress('BTC')
// 3) Build BTC spend tx to inbound address, with memo as OP_RETURN or as required by THORChain watcher
const amountSatoshi = 100000 // example
const tx = await btcClient.buildTx({
fromAddress: await btcClient.getAddress(),
toAddress: inbound,
amount: amountSatoshi,
memo // library-specific: many libs expect memo separate
})
// 4) Sign & broadcast
const signed = await btcClient.sign(tx)
const txHash = await btcClient.broadcast(signed)
// 5) Monitor swap status via THORChain or node explorer
console.log('Broadcasted txHash:', txHash)
Important: this is illustrative. Check the real xchainjs package(s) to learn the exact method signatures and the correct place to supply the memo. For a runnable walkthrough, see this community example on dev.to: xchainjs cross-chain swap example (dev.to) and the primary library repo: xchainjs-lib on GitHub. Also read THORChain’s docs for current memo formats: docs.thorchain.org.
Pro tip: run everything on testnet first. Use automated monitors to reconcile inbound tx → THORChain outbound. Emit strong telemetry on fee estimation and expected-out calculations so your UX can present slippage estimates before the user signs.
6) BTC → ETH swap example (detailed considerations)
When swapping BTC → ETH via THORChain, the user sends BTC to a THORChain inbound address with a memo specifying the desired ETH recipient. THORChain executes an internal swap (often BTC → RUNE → ETH) and sends ETH to the recipient. The sequence crosses chain boundaries but settles in native assets — no wrapped tokens required.
Key operational details you must handle in your implementation:
- Compute expected outbound amount using pool depths and fees; present a slip tolerance UI and enforce a tx-level slip limit.
- Generate or retrieve the correct inbound address for the source chain and avoid address reuse if the network requires one-time inbound addresses.
- Track confirmations: different chains require different confirmation counts before THORChain will trust the inbound transaction.
Testing checklist: confirm a successful testnet swap, verify the outbound token arrives at the expected address, simulate edge scenarios (low liquidity, high slippage), and validate refund/retry flows if the swap fails. Document the expected time-to-settlement for customer-facing UX and instrument these metrics.
7) Integration patterns & system design
Two common integration patterns exist for services that want to offer cross-chain swaps:
- Frontend-only flow: The dapp builds the inbound transaction on the client (user signs with their wallet) and the user pushes the transaction themselves. Minimal backend, good for non-custodial UX.
- Backend-assisted flow: Your backend helps with quote aggregation, constructs transactions/templates, and may relay signed transactions to the network. Useful for aggregators and gas-paying scenarios, but increases attack surface.
For swap aggregators, the architecture usually combines: quote microservice (gathers pool prices), router (compute best path), transaction builder (per-chain clients), broadcaster and reconciliation service. Ensure idempotency at the router layer and reliable retry logic when broadcasting. For TypeScript/Node stacks, xchainjs libraries often plug into the transaction builder and broadcaster stages.
Security: minimize key exposure, use hardware or KMS-backed signing for any server-held keys, and safeguard any service that creates inbound transactions on behalf of users. Document and test for front-running vectors, especially when quoting and broadcasting transactions in a multi-provider environment.
8) Production hardening & best practices
Operationalize by automating monitoring of: inbound confirmations, swap execution state in THORChain, outbound transaction failures, and liquidity pool reserves. Alert on unusual slippage or failed swaps. Provide clear UX for users when swaps are pending, failed, or partially executed.
Slippage & fee strategy: show estimated outbound amount and a selectable slippage tolerance. If you’re aggregating across pools, compute expected outcomes using current pool depths and account for THORChain fees (network + swap fees). For liquidity-conscious apps, implement a “safe-quote” that subtracts a buffer from estimated returns.
Testing: use testnets, mock chain events, and chaos tests that simulate delayed inbound confirmations. Add replay protection and robust reconciliation jobs that can detect and resolve stuck swaps.
9) Tools & links (backlinks)
Primary resources developers should bookmark:
- xchainjs-lib (GitHub) — canonical xchainjs repo and package list (use for client implementations).
- THORChain documentation — memo formats, pool economics and node operator guides.
- Community example on dev.to — a step-by-step dev walkthrough (good for quickstarts).
When you publish, link anchor text like “xchainjs”, “THORChain docs” and “xchainjs cross-chain swap example” directly to these authoritative resources — this both helps readers and strengthens your page’s topical relevance.
10) SEO & microdata suggestions
Use the primary title and description above. To help feature snippets and voice search:
- Provide short (20–40 word) answer boxes under headings for likely PAA snippets (e.g., “How THORChain cross-chain swaps work”).
- Include JSON-LD for FAQ and Article (below) so search engines can render enhanced results.
FAQ (final — 3 most relevant)
- How does THORChain perform cross-chain swaps?
- THORChain routes swaps through its native liquidity pools (often via RUNE) using inbound transactions paired with memos that instruct the network. Nodes watch source-chain inbound transactions, execute internal pool swaps, and send the resulting native asset to the target chain address. No wrapped tokens required.
- How can I perform a BTC → ETH swap using xchainjs?
- Use an xchainjs BTC client to build a transaction to THORChain’s BTC inbound address with the correct memo specifying the ETH recipient. Broadcast the BTC tx, then monitor THORChain for outbound settlement. Refer to official xchainjs examples and the dev.to walkthrough for API specifics.
- What common pitfalls should I watch for (memos, slippage, inbound addresses)?
- Common issues: incorrect memo format (swap fails), insufficient confirmation count, unexpected slippage due to shallow pools, and using the wrong inbound address. Always test on testnet, present slippage to users, and implement reconciliation for failed/partial swaps.
Appendix — Semantic Core (raw, copy/paste)
Primary:
xchainjs
xchainjs thorchain
thorchain sdk
thorchain swap example
cross chain swap
crypto cross chain swap
defi cross chain swap
Secondary:
btc to eth swap
web3 swap example
typescript defi sdk
crypto swap api
blockchain swap api
crypto swap backend
web3 swap integration
thorchain liquidity pools
thorchain rune swap
LSI / Related:
permissionless liquidity
inbound address
THORChain memo
slippage limit
swap transaction hash
swap aggregator development
decentralized exchange swap
cross chain trading