| title | XCM Example |
|---|---|
| description | Replace with a short description. |
| pathway | xcm |
Replace with a short description.
This tutorial teaches you Cross-Consensus Messaging (XCM) - Polkadot's powerful protocol for cross-chain communication. You'll learn to transfer assets between parachains, execute remote calls, and build cross-chain applications using Polkadot API and Chopsticks for local testing.
Before starting, ensure you have:
- Node.js 20+ installed
- Completion of basic Polkadot API tutorial (recommended)
- Understanding of Polkadot's architecture (relay chain, parachains)
- Basic knowledge of TypeScript/JavaScript and async patterns
By completing this tutorial, you will understand:
- XCM fundamentals and architecture
- How to transfer assets between parachains
- How to execute cross-chain transactions
- How to test XCM interactions locally with Chopsticks
- How to handle different asset types (native, foreign, relay chain)
- How to monitor and debug cross-chain operations
XCM (Cross-Consensus Messaging) is a language for communicating intentions between consensus systems. It's not a protocol but a format for messages that can be executed across different chains.
Key concepts:
- Location - Identifies chains and assets using a relative path system
- Assets - Represents fungible and non-fungible items
- Instructions - Actions to be performed (transfer, execute, etc.)
- Weight - Computational cost of operations
Source Chain Destination Chain
| |
| 1. Withdraw Assets |
| 2. Initialize Transfer |
| 3. Send XCM Message -------->|
| | 4. Receive Message
| | 5. Deposit Assets
| | 6. Execute Instructions
|<----- 7. Confirm Result ------|
Install all dependencies:
cd recipes/xcm-example
npm installWhat's installed:
- polkadot-api - Type-safe blockchain interactions
- @acala-network/chopsticks - Local chain fork for testing
- @acala-network/chopsticks-testing - Testing utilities
- Vitest - Testing framework
src/
├── xcm/
│ ├── transfer.ts # Asset transfer logic
│ ├── execute.ts # Remote execution logic
│ └── utils.ts # XCM helper functions
tests/
├── transfer.test.ts # Transfer tests
├── execute.test.ts # Execution tests
chopsticks.yml # Local network configuration
Key components:
- src/xcm/ - Core XCM implementation
- chopsticks.yml - Configures local test chains
- tests/ - XCM test scenarios
Chopsticks creates local chain forks for testing. Configuration in chopsticks.yml:
relay_chain:
endpoint: wss://paseo-rpc.dwellir.com
block: latest
parachains:
- id: 1000
endpoint: wss://paseo-asset-hub-rpc.dwellir.com
block: latest
- id: 1002
endpoint: wss://paseo-bridge-hub-rpc.dwellir.com
block: latestWhy Chopsticks?
- Test without spending real tokens
- Fast execution (no block time delays)
- Fork real chain state
- Reset between tests
Start Chopsticks:
npm run chopsticksLocations in XCM are hierarchical addresses:
// Relay chain from parachain perspective
const relayChain = {
parents: 1,
interior: "Here"
};
// Parachain 1000 from relay chain
const parachain1000 = {
parents: 0,
interior: {
X1: { Parachain: 1000 }
}
};
// Parachain 1002 from parachain 1000 (sibling)
const sibling1002 = {
parents: 1,
interior: {
X1: { Parachain: 1002 }
}
};
// Account on another chain
const account = {
parents: 0,
interior: {
X1: {
AccountId32: {
id: accountBytes,
network: null
}
}
}
};Location rules:
parents: 0- Same consensus systemparents: 1- Parent consensus (relay chain)interior- Path within the consensus system
Transfer tokens from parachain to relay chain:
import { api } from "./client";
async function transferToRelayChain(
amount: bigint,
beneficiary: string
) {
// Define relay chain destination
const dest = {
V4: {
parents: 1,
interior: "Here"
}
};
// Define beneficiary account on relay chain
const beneficiaryLocation = {
V4: {
parents: 0,
interior: {
X1: {
AccountId32: {
id: decodeAddress(beneficiary),
network: null
}
}
}
}
};
// Define assets to transfer
const assets = {
V4: [
{
id: {
parents: 0,
interior: "Here"
},
fun: {
Fungible: amount
}
}
]
};
// Execute transfer
const tx = api.tx.PolkadotXcm.transfer_assets({
dest,
beneficiary: beneficiaryLocation,
assets,
fee_asset_item: 0,
weight_limit: "Unlimited"
});
return await tx.signAndSubmit(signer);
}Breaking it down:
- dest - Target chain (relay chain = parents: 1)
- beneficiary - Account receiving assets
- assets - What to transfer and how much
- fee_asset_item - Which asset pays fees (index 0)
- weight_limit - Execution limit (Unlimited for simplicity)
Transfer tokens between sibling parachains:
async function transferToSibling(
targetParaId: number,
amount: bigint,
beneficiary: string
) {
// Sibling parachain destination
const dest = {
V4: {
parents: 1,
interior: {
X1: { Parachain: targetParaId }
}
}
};
// Beneficiary on target chain
const beneficiaryLocation = {
V4: {
parents: 0,
interior: {
X1: {
AccountId32: {
id: decodeAddress(beneficiary),
network: null
}
}
}
}
};
// Native assets
const assets = {
V4: [
{
id: {
parents: 1,
interior: "Here" // Relay chain native token
},
fun: {
Fungible: amount
}
}
]
};
const tx = api.tx.PolkadotXcm.transfer_assets({
dest,
beneficiary: beneficiaryLocation,
assets,
fee_asset_item: 0,
weight_limit: "Unlimited"
});
return await tx.signAndSubmit(signer);
}Sibling transfer specifics:
- Destination uses
parents: 1to go up to relay, then down to sibling - Asset location depends on what's being transferred
- Both chains must support the asset
Handle assets that originated from another chain:
async function transferForeignAsset(
assetId: number,
targetParaId: number,
amount: bigint,
beneficiary: string
) {
const dest = {
V4: {
parents: 1,
interior: {
X1: { Parachain: targetParaId }
}
}
};
const beneficiaryLocation = {
V4: {
parents: 0,
interior: {
X1: {
AccountId32: {
id: decodeAddress(beneficiary),
network: null
}
}
}
}
};
// Foreign asset location
const assets = {
V4: [
{
id: {
parents: 0,
interior: {
X2: [
{ PalletInstance: 50 }, // Assets pallet
{ GeneralIndex: assetId }
]
}
},
fun: {
Fungible: amount
}
}
]
};
const tx = api.tx.PolkadotXcm.transfer_assets({
dest,
beneficiary: beneficiaryLocation,
assets,
fee_asset_item: 0,
weight_limit: "Unlimited"
});
return await tx.signAndSubmit(signer);
}Foreign asset notes:
- Assets are identified by their origin location
PalletInstanceidentifies the pallet managing assetsGeneralIndexis the specific asset ID
Execute calls on remote chains via XCM:
async function remoteExecute(
targetParaId: number,
call: any,
maxWeight: bigint
) {
// Build XCM message
const message = {
V4: [
{
WithdrawAsset: {
assets: [
{
id: { parents: 1, interior: "Here" },
fun: { Fungible: maxWeight }
}
]
}
},
{
BuyExecution: {
fees: {
id: { parents: 1, interior: "Here" },
fun: { Fungible: maxWeight }
},
weight_limit: "Unlimited"
}
},
{
Transact: {
origin_kind: "SovereignAccount",
require_weight_at_most: {
ref_time: maxWeight,
proof_size: 0
},
call: {
encoded: call
}
}
}
]
};
const dest = {
V4: {
parents: 1,
interior: {
X1: { Parachain: targetParaId }
}
}
};
const tx = api.tx.PolkadotXcm.send({
dest,
message
});
return await tx.signAndSubmit(signer);
}XCM Instructions:
- WithdrawAsset - Take assets from sender's account
- BuyExecution - Pay for execution on destination
- Transact - Execute the actual call
Track XCM message execution:
async function monitorXcmTransfer(txHash: string) {
// Subscribe to XCM events
const unsubscribe = api.query.System.Events.watchValue((events) => {
for (const event of events) {
// Transfer initiated
if (event.type === "PolkadotXcm.Sent") {
console.log("XCM message sent:", event.data);
}
// Assets trapped (error condition)
if (event.type === "PolkadotXcm.AssetsTrapped") {
console.warn("Assets trapped:", event.data);
}
// Execution outcome on destination
if (event.type === "XcmpQueue.Success") {
console.log("XCM executed successfully:", event.data);
}
if (event.type === "XcmpQueue.Fail") {
console.error("XCM execution failed:", event.data);
}
}
});
return unsubscribe;
}Important events:
- Sent - XCM message dispatched
- AssetsTrapped - Assets couldn't be deposited
- Success/Fail - Execution outcome
# Start Chopsticks network
npm run chopsticks
# In another terminal, run tests
npm testTests use Chopsticks to simulate multi-chain scenarios:
import { describe, it, expect, beforeAll } from "vitest";
import { setupChains } from "@acala-network/chopsticks-testing";
describe("XCM Transfers", () => {
let relayChain, assetHub, sibling;
beforeAll(async () => {
// Setup test chains
const chains = await setupChains({
relaychain: "paseo",
parachains: [
{ paraId: 1000, chain: "paseo-asset-hub" },
{ paraId: 1002, chain: "westend-collectives" }
]
});
relayChain = chains.relaychain;
assetHub = chains.parachains[0];
sibling = chains.parachains[1];
});
it("transfers assets to relay chain", async () => {
const initialBalance = await getBalance(relayChain, account);
await transferToRelayChain(1000000000n, account);
// Progress chain to process XCM
await assetHub.newBlock();
await relayChain.newBlock();
const finalBalance = await getBalance(relayChain, account);
expect(finalBalance).toBeGreaterThan(initialBalance);
});
});- Fork at specific blocks - Consistent state across tests
- Advance blocks - Simulate message propagation
- Check both chains - Verify sender and receiver state
- Test failure cases - Insufficient balance, invalid locations
- Clean up - Reset chains between tests
Transfer through intermediate chains:
// Transfer from ParaA -> RelayChain -> ParaB
async function multiHopTransfer(sourceApi, amount, finalDest) {
// First leg: ParaA to RelayChain
await transferToRelayChain(amount, relayAccount);
// Second leg: RelayChain to ParaB
await transferFromRelay(finalDest, amount, beneficiary);
}Use a chain as a reserve for asset transfers:
// When Asset Hub is the reserve for an asset
const reserveTransfer = api.tx.PolkadotXcm.limited_reserve_transfer_assets({
dest,
beneficiary,
assets,
fee_asset_item: 0,
weight_limit: "Unlimited"
});For trusted relationships (relay <-> system parachains):
const teleport = api.tx.PolkadotXcm.limited_teleport_assets({
dest,
beneficiary,
assets,
fee_asset_item: 0,
weight_limit: "Unlimited"
});try {
await transferToSibling(1000, amount, beneficiary);
} catch (error) {
// Check specific XCM errors
if (error.message.includes("NotHoldingFees")) {
console.error("Insufficient assets to pay fees");
} else if (error.message.includes("AssetNotFound")) {
console.error("Asset not registered on destination");
} else if (error.message.includes("TooExpensive")) {
console.error("Operation exceeds weight limits");
}
}Common issues:
- NotHoldingFees - Not enough assets for execution
- AssetNotFound - Asset not recognized on destination
- TooExpensive - Exceeds weight/fee limits
- InvalidLocation - Malformed location
- Trapped - Assets couldn't be deposited
Now that you've completed this tutorial, try:
-
Advanced Asset Management
- Handle NFTs with XCM
- Implement custom asset transfer logic
- Build cross-chain DEX functionality
-
Complex Execution Patterns
- Chain multiple XCM instructions
- Implement error recovery
- Build cross-chain governance
-
Production Integration
- Connect to real testnets
- Implement proper fee estimation
- Add transaction monitoring
-
Build Applications
- Cross-chain wallet
- Multi-chain portfolio tracker
- Cross-chain swap interface
MIT OR Apache-2.0