This example demonstrates how to perform a cross-chain crypto swap using XChainJS and THORChain.
It shows how to:
- work with standardized asset representations
- handle crypto amounts safely
- request and execute a swap using a unified TypeScript API
The example is fully runnable and available both on GitHub and CodeSandbox.
π Live Demo & Source Code
βΆ Live demo (CodeSandbox):
https://codesandbox.io/p/devbox/github/xchainjs/xchainjs-lib/tree/master/examples/do-swapπ¦ Source code (GitHub):
https://github.com/xchainjs/xchainjs-lib/tree/master/examples/do-swap
π What This Example Does
This project performs a cross-chain swap using THORChain liquidity pools.
It demonstrates:
- how to define input and output assets
- how to create and validate swap amounts
- how to interact with THORChain via XChainJS
- how to keep the code chain-agnostic
This example is useful for developers building:
- crypto wallets
- DeFi frontends
- swap aggregators
- backend swap services
- cross-chain dashboards
π§° Tech Stack
- TypeScript
- Node.js
- XChainJS
- THORChain
- @xchainjs/xchain-util
- @xchainjs/xchain-thorchain
π Project Location
Inside the XChainJS monorepo:
examples/
ββ do-swap/
π How the Swap Flow Works
Input Asset
β XChainJS Asset Utilities
β THORChain Client
β Swap Quote
β Transaction Execution
β Cross-Chain Swap
π§© Core Concepts
Asset Representation
Assets are represented using a standardized format:
.
Examples:
- BTC.BTC
- ETH.ETH
- THOR.RUNE
This format is parsed and validated using utilities from
@xchainjs/xchain-util.
Amount Handling
Crypto applications must correctly separate:
- human-readable amounts
- base-unit amounts
This example uses XChainJS utilities to avoid rounding and decimal errors,
which are common in DeFi applications.
βοΈ Installation
Clone the repository
git clone https://github.com/xchainjs/xchainjs-lib.git
cd xchainjs-lib/examples/do-swap
Install dependencies
npm install
Run the example
npm start
π Running in the Browser
You can also run this example instantly using CodeSandbox:
https://codesandbox.io/p/devbox/github/xchainjs/xchainjs-lib/tree/master/examples/do-swap
π§ͺ Code Example (Simplified)
import { assetFromString, assetAmount } from '@xchainjs/xchain-util'
const fromAsset = assetFromString('BTC.BTC')
const toAsset = assetFromString('ETH.ETH')
const amount = assetAmount(0.01)
if (!fromAsset || !toAsset) {
throw new Error('Invalid asset')
}
β Why Use XChainJS for Cross-Chain Swaps
- Chain-agnostic API
- TypeScript-first
- Battle-tested in production
- Modular design
π Related Resources
XChainJS GitHub
https://github.com/xchainjs/xchainjs-libXChainJS utilities
https://www.npmjs.com/package/@xchainjs/xchain-utilTHORChain official site
https://thorchain.org
π Summary
This example provides a practical, runnable reference for performing
cross-chain swaps using XChainJS and THORChain.
Top comments (0)