DEV Community

Cover image for # XChainJS Cross-Chain Swap Example (THORChain)
Fabricio Viskor
Fabricio Viskor

Posted on

# XChainJS Cross-Chain Swap Example (THORChain)

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


πŸ“Œ 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')
}
Enter fullscreen mode Exit fullscreen mode

βœ… Why Use XChainJS for Cross-Chain Swaps

  • Chain-agnostic API
  • TypeScript-first
  • Battle-tested in production
  • Modular design

πŸ”— Related Resources


πŸ“ Summary

This example provides a practical, runnable reference for performing
cross-chain swaps using XChainJS and THORChain.

Top comments (0)