Parachains & XCM

Understanding Parachains and Cross-Chain Messaging

Parachains in Polkadot

Parachains are independent blockchains that run in parallel and are secured by the Polkadot relay chain. They can have their own tokens, governance systems, and specialized functionality while benefiting from the shared security of the Polkadot network.

Parachain Architecture

Understanding how parachains work is crucial for building on Polkadot:

Parachain Components

  • • Collator nodes
  • • Parachain runtime
  • • State transition function
  • • Cross-chain messaging
  • • Shared security

Benefits

  • • Customizable functionality
  • • Shared security
  • • Interoperability
  • • Scalability
  • • Governance autonomy

Cross-Chain Message Format (XCM)

XCM is the standard for cross-chain communication in Polkadot. It defines how different chains can send messages to each other:

XCM Features:

  • Versioned: Supports multiple versions for evolution
  • Extensible: Can be extended with new instructions
  • Secure: Built-in security mechanisms
  • Flexible: Supports various message types
  • Standardized: Common format across all chains

XCM Instructions

XCM messages are composed of instructions that define what actions to take:

Transfer Instructions

Instructions for transferring assets between chains.

  • • WithdrawAsset
  • • DepositAsset
  • • TransferAsset
  • • ReserveAssetDeposited

Execution Instructions

Instructions for executing operations on the destination chain.

  • • Transact
  • • BuyExecution
  • • RefundSurplus
  • • SetErrorHandler

Control Instructions

Instructions for controlling message execution flow.

  • • ClearOrigin
  • • DescendOrigin
  • • SetAppendix
  • • ClearError

HRMP (Horizontal Relay-routed Message Passing)

HRMP is the current implementation of parachain-to-parachain communication:

// HRMP operations with Polkadot.js API
import { ApiPromise, WsProvider } from '@polkadot/api';

const api = await ApiPromise.create({ provider: new WsProvider('wss://rpc.polkadot.io') });

// 1. Open HRMP channel
const openChannelTx = api.tx.hrmp.hrmpInitOpenChannel(
  2000, // target parachain ID
  1000, // max capacity
  1000  // max message size
);

// 2. Accept HRMP channel
const acceptChannelTx = api.tx.hrmp.hrmpAcceptOpenChannel(2000);

// 3. Close HRMP channel
const closeChannelTx = api.tx.hrmp.hrmpCloseChannel({
  sender: 2000,
  recipient: 1000
});

// 4. Send XCM message
const xcmMessage = {
  V2: [
    {
      WithdrawAsset: [{
        id: { Concrete: { parents: 0, interior: 'Here' } },
        fun: { Fungible: 1000000000000 }
      }]
    },
    {
      BuyExecution: {
        fees: {
          id: { Concrete: { parents: 0, interior: 'Here' } },
          fun: { Fungible: 1000000000000 }
        },
        weightLimit: { Limited: 1000000 }
      }
    },
    {
      DepositAsset: {
        assets: { Wild: 'All' },
        maxAssets: 1,
        beneficiary: {
          parents: 0,
          interior: {
            X1: {
              AccountId32: {
                network: 'Any',
                id: '0x1234567890123456789012345678901234567890123456789012345678901234'
              }
            }
          }
        }
      }
    }
  ]
};

const sendXcmTx = api.tx.xcmPallet.send(
  { V1: { parents: 1, interior: { X1: { Parachain: 2000 } } } }, // destination
  { V1: xcmMessage.V2 } // message
);

Parachain Development

Building a parachain involves several key considerations:

Technical Requirements

  • • Substrate-based runtime
  • • Collator implementation
  • • XCM integration
  • • State transition logic
  • • Consensus mechanism

Economic Considerations

  • • Parachain slot auction
  • • Crowdloan campaigns
  • • Token economics
  • • Governance design
  • • Sustainability planning

Parachain Slot Auctions

Parachains are allocated through a candle auction mechanism:

// Parachain slot auction operations
// 1. Bid in parachain slot auction
const bidTx = api.tx.auctions.bid(
  0, // auction index
  0, // first slot
  1, // last slot
  1000000000000 // bid amount
);

// 2. Contribute to crowdloan
const contributeTx = api.tx.crowdloan.contribute(
  2000, // parachain ID
  1000000000000, // contribution amount
  null // signature (optional)
);

// 3. Withdraw crowdloan contribution
const withdrawTx = api.tx.crowdloan.withdraw(
  '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', // contributor
  2000 // parachain ID
);

// 4. Get auction information
const auctionInfo = await api.query.auctions.auctionInfo();
const crowdloanInfo = await api.query.crowdloan.funds(2000);
console.log('Auction info:', auctionInfo.toHuman());
console.log('Crowdloan info:', crowdloanInfo.toHuman());

Cross-Chain Use Cases

XCM enables various cross-chain use cases:

Cross-Chain Use Cases:

  • Asset Transfers: Move tokens between chains
  • Cross-Chain DeFi: Use assets from one chain in DeFi on another
  • Governance: Vote on governance proposals across chains
  • Data Sharing: Share data and state between chains
  • Function Calls: Execute functions on remote chains
  • Asset Swaps: Exchange assets between different chains

Best Practices

Parachain Development Best Practices:

  • Design for Interoperability: Plan for cross-chain communication
  • Implement XCM: Support cross-chain messaging
  • Optimize Performance: Ensure efficient state transitions
  • Plan Economics: Design sustainable token economics
  • Test Thoroughly: Test on testnets before mainnet
  • Community Building: Build a strong community for crowdloans
  • Security First: Prioritize security in all implementations

Summary

In this chapter, we've explored parachains and XCM:

  • • Parachains are independent blockchains with shared security
  • • XCM provides standardized cross-chain communication
  • • HRMP enables parachain-to-parachain messaging
  • • Parachain slot auctions allocate network resources
  • • Cross-chain use cases enable new possibilities
  • • Proper planning and testing are essential for success

In the next chapter, we'll dive into Substrate runtime development, learning how to build the core logic that powers parachains and other Substrate-based chains.