Skip to content

About

Polkadot Cookbook recipe: Cross-chain transaction example with XCM and Chopsticks

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

title XCM Example
description Replace with a short description.
pathway xcm

XCM Example

Replace with a short description.

Overview

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.

Prerequisites

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

What You'll Learn

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 Fundamentals

What is XCM?

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

XCM Message Flow

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 ------|

Step-by-Step Implementation

Step 1: Project Setup

Install all dependencies:

cd recipes/xcm-example
npm install

What'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

Step 2: Understanding the Project Structure

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

Step 3: Setting Up Chopsticks

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: latest

Why Chopsticks?

  • Test without spending real tokens
  • Fast execution (no block time delays)
  • Fork real chain state
  • Reset between tests

Start Chopsticks:

npm run chopsticks

Step 4: Understanding XCM Locations

Locations 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 system
  • parents: 1 - Parent consensus (relay chain)
  • interior - Path within the consensus system

Step 5: Transferring Assets to Relay Chain

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:

  1. dest - Target chain (relay chain = parents: 1)
  2. beneficiary - Account receiving assets
  3. assets - What to transfer and how much
  4. fee_asset_item - Which asset pays fees (index 0)
  5. weight_limit - Execution limit (Unlimited for simplicity)

Step 6: Transferring Assets Between Parachains

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: 1 to go up to relay, then down to sibling
  • Asset location depends on what's being transferred
  • Both chains must support the asset

Step 7: Transferring Foreign Assets

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
  • PalletInstance identifies the pallet managing assets
  • GeneralIndex is the specific asset ID

Step 8: Remote Execution

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:

  1. WithdrawAsset - Take assets from sender's account
  2. BuyExecution - Pay for execution on destination
  3. Transact - Execute the actual call

Step 9: Monitoring XCM Messages

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

Testing with Chopsticks

Running Tests

# Start Chopsticks network
npm run chopsticks

# In another terminal, run tests
npm test

Test Structure

Tests 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);
  });
});

Testing Best Practices

  1. Fork at specific blocks - Consistent state across tests
  2. Advance blocks - Simulate message propagation
  3. Check both chains - Verify sender and receiver state
  4. Test failure cases - Insufficient balance, invalid locations
  5. Clean up - Reset chains between tests

Advanced XCM Patterns

Pattern 1: Multi-Hop Transfers

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);
}

Pattern 2: Reserve Asset Transfers

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"
});

Pattern 3: Teleport Assets

For trusted relationships (relay <-> system parachains):

const teleport = api.tx.PolkadotXcm.limited_teleport_assets({
  dest,
  beneficiary,
  assets,
  fee_asset_item: 0,
  weight_limit: "Unlimited"
});

Error Handling

Common XCM Errors

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

Next Steps

Now that you've completed this tutorial, try:

  1. Advanced Asset Management

    • Handle NFTs with XCM
    • Implement custom asset transfer logic
    • Build cross-chain DEX functionality
  2. Complex Execution Patterns

    • Chain multiple XCM instructions
    • Implement error recovery
    • Build cross-chain governance
  3. Production Integration

    • Connect to real testnets
    • Implement proper fee estimation
    • Add transaction monitoring
  4. Build Applications

    • Cross-chain wallet
    • Multi-chain portfolio tracker
    • Cross-chain swap interface

Resources

License

MIT OR Apache-2.0

About

Polkadot Cookbook recipe: Cross-chain transaction example with XCM and Chopsticks

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages