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 (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.