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 (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.