🛡️ Protocol

This skill provides expert MultiversX protocol insights on sharding, cross-shard execution, ESDT standards, and async patterns to design robust dApps.

QUICK INSTALL
npx playbooks add skill michavie/mx-ai-skills --skill protocol

Protocol instructions

MultiversX Protocol Expert

This skill encapsulates the deep theoretical and practical knowledge of the MultiversX network architecture. It is essential for architectural decisions, debugging complex failures, and understanding "why" things work the way they do.

Core Concepts

  1. Adaptive State Sharding
  • Intra-shard vs. Cross-shard: Transactions within the same shard are atomic and fast (6s). Cross-shard transactions are asynchronous and take longer (metadata + execution).
  • Account Location: An address's shard is determined by the last bits of its public key.
  • Gas Implications: Cross-shard calls consume more gas and require careful handling of intermediate states.
  1. ESDT (Elrond Standard Digital Token)
  • Native Tokens: Tokens are first-class citizens, not smart contracts (unlike ERC-20).
  • Storage: Token balances are stored directly in the user's account trie.
  • Roles: ESDTRoleLocalMint, ESDTRoleLocalBurn allow contracts to manage supply without centralized minters.
  1. Smart Contract Execution
  • Arwen VM: A high-performance WASM virtual machine.
  • Statelessness: Contracts is stateless during execution until storage updates are committed (at the end).
  • Async Calls: async_call does NOT return immediately. It schedules a call for a future block.

🛠️ Critical Knowledge & "Sharp Edges"

1. The Async Model

  • Problem: You cannot get the result of a cross-shard call in the same transaction.
  • Solution: Use Callbacks (#[callback]) to handle the result (success or failure) of an async operation.
  • Warning: State changes made before an async call are committed even if the remote call fails (unless you revert explicitly in the callback).

2. Gas Schedule

  • Storage is Expensive: Writing to storage is the highest cost.
  • Bytes Matter: The number of bytes in inputs and outputs directly affects gas cost.

3. Network Configuration

  • Devnet / Testnet / Mainnet: Distinct IDs (D, T, 1).
  • Epochs & Rounds: Understanding finality time (approx 64s for full finality across shards).

📚 Expert Resources (Deep Dive)

  • Protocol Experts: skills/expert/multiversx-protocol-experts/SKILL.md
  • Sharp Edges: skills/expert/mvx_sharp_edges/SKILL.md
  • Consult Docs: skills/expert/consult_mvx_docs/SKILL.md

⚡ Key Constants

| Parameter | Value | Note |
| :--- | :--- | :--- |
| Block Time | 6 seconds | Per shard |
| Max Gas/Block | 1.5B | Target is lower |
| Min Transaction Gas | 50,000 | Basic transfer |
| ESDT Transfer Gas | ~300,000 | Depends on data |

Design Rule: Always assume your contract will be called from another shard. Design for asynchrony.

Protocol Experts

---
name: multiversx-protocol-experts
description: Deep protocol knowledge for MultiversX architecture including sharding, consensus, ESDT standards, and cross-shard transactions. Use when reviewing protocol-level code, designing complex dApp architectures, or troubleshooting cross-shard issues.
---

MultiversX Protocol Expertise

Deep technical knowledge of the MultiversX protocol architecture, utilized for reviewing protocol-level changes, designing complex dApp architectures involving cross-shard logic, and sovereign chain integrations.

When to Use

  • Reviewing protocol-level code changes
  • Designing cross-shard smart contract interactions
  • Troubleshooting async transaction issues
  • Understanding token standard implementations
  • Working with sovereign chain integrations
  • Optimizing for sharded architecture

1. Core Architecture: Adaptive State Sharding

Sharding Overview

MultiversX implements three types of sharding simultaneously:

| Sharding Type | Description | Implication |
|--------------|-------------|-------------|
| Network | Nodes distributed into shards | Each shard has subset of validators |
| Transaction | TXs processed by sender's shard | TX execution location is deterministic |
| State | Each shard maintains portion of state | Account data is shard-specific |

Shard Assignment

Accounts are assigned to shards based on address:

Shard = last_byte_of_address % num_shards

Practical implication: Contract address determines which shard processes its transactions.

The Metachain

The Metachain is a special coordinator shard that:

  • Handles validator shuffling between shards
  • Processes epoch transitions
  • Manages system smart contracts (Staking, ESDT issuance)
  • Notarizes shard block headers

Important: The Metachain does NOT execute general smart contracts.

// System contracts live on Metachain:
// - Staking contract
// - ESDT system smart contract
// - Delegation manager
// - Governance

// Regular contracts execute on shard determined by their address

2. Cross-Shard Transactions

Transaction Flow

When sender and receiver are on different shards:

1. Sender Shard: Process TX, generate Smart Contract Result (SCR)
2. Metachain: Notarize sender block, relay SCR
3. Receiver Shard: Execute SCR, finalize transaction

Atomicity Guarantees

Key Property: Cross-shard transactions are atomic but asynchronous.

// This cross-shard call is atomic
self.tx()
    .to(&other_contract)  // May be on different shard
    .typed(other_contract_proxy::OtherContractProxy)
    .some_endpoint(args)
    .async_call_and_exit();

// Either BOTH sides succeed, or BOTH sides revert
// But there's a delay between sender execution and receiver execution

Callback Handling

#[endpoint]
fn cross_shard_call(&self) {
    // State changes HERE happen immediately (sender shard)
    self.pending_calls().set(true);

    self.tx()
        .to(&other_contract)
        .typed(proxy::Proxy)
        .remote_function()
        .callback(self.callbacks().on_result())
        .async_call_and_exit();
}

#[callback]
fn on_result(&self, #[call_result] result: ManagedAsyncCallResult<BigUint>) {
    // This executes LATER, back on sender shard
    // AFTER receiver shard has processed

    match result {
        ManagedAsyncCallResult::Ok(value) => {
            // Remote call succeeded
            self.pending_calls().set(false);
        },
        ManagedAsyncCallResult::Err(_) => {
            // Remote call failed
            // Original state changes are NOT auto-reverted!
            // Must manually handle rollback
            self.pending_calls().set(false);
            self.handle_failure();
        }
    }
}

3. Consensus: Secure Proof of Stake (SPoS)

Validator Selection

Selection factors:
- Stake amount
- Validator rating (performance history)
- Random seed (from previous block)

Result: Deterministic but unpredictable validator selection

Block Production

| Phase | Duration | Description |
|-------|----------|-------------|
| Propose | ~1s | Leader proposes block |
| Validate | ~1s | Validators verify and sign |
| Commit | ~1s | Block committed with BLS multi-sig |

Finality

  • Intra-shard: Instant finality (~6 seconds)
  • Cross-shard: Finality after receiver shard processes (~12-18 seconds)

4. Token Standards (ESDT)

Native Implementation

Unlike ERC-20, ESDT tokens are protocol-level, not smart contracts:

// ERC-20 (Ethereum): Contract tracks balances
mapping(address => uint256) balances;

// ESDT (MultiversX): Protocol tracks balances
// No contract needed for basic token operations
// Balances stored directly in account state

ESDT Properties

| Property | Description | Security Implication |
|----------|-------------|---------------------|
| CanFreeze | Protocol can freeze assets | Emergency response capability |
| CanWipe | Protocol can wipe assets | Regulatory compliance |
| CanPause | Protocol can pause transfers | Circuit breaker |
| CanMint | Address can mint new tokens | Inflation control |
| CanBurn | Address can burn tokens | Supply control |
| CanChangeOwner | Ownership transferable | Admin key rotation |
| CanUpgrade | Properties can be modified | Flexibility vs immutability |

ESDT Roles

// Roles are assigned per address per token
ESDTRoleLocalMint    // Can mint tokens
ESDTRoleLocalBurn    // Can burn tokens
ESDTRoleNFTCreate    // Can create NFT/SFT nonces
ESDTRoleNFTBurn      // Can burn NFT/SFT
ESDTRoleNFTAddQuantity   // Can add SFT quantity
ESDTRoleNFTUpdateAttributes  // Can update NFT attributes
ESDTTransferRole     // Required for restricted transfers

Token Transfer Types

| Transfer Type | Function | Use Case |
|---------------|----------|----------|
| ESDTTransfer | Fungible token transfer | Simple token send |
| ESDTNFTTransfer | Single NFT/SFT transfer | NFT marketplace |
| MultiESDTNFTTransfer | Batch transfer | Contract calls with multiple tokens |

5. Built-in Functions

Transfer Functions

ESDTTransfer@<token_id>@<amount>
ESDTNFTTransfer@<token_id>@<nonce>@<amount>@<receiver>
MultiESDTNFTTransfer@<receiver>@<num_tokens>@<token1_id>@<nonce1>@<amount1>@...

Contract Call with Payment

MultiESDTNFTTransfer@<contract>@<num_tokens>@<token_data>...@<function>@<args>...

Direct ESDT Operations

ESDTLocalMint@<token_id>@<amount>
ESDTLocalBurn@<token_id>@<amount>
ESDTNFTCreate@<token_id>@<initial_quantity>@<name>@<royalties>@<hash>@<attributes>@<uris>

6. Sovereign Chains & Interoperability

Sovereign Chain Architecture

MultiversX Mainchain (L1)
    │
    ├── Sovereign Chain A (L2)
    │       └── Gateway Contract
    │
    └── Sovereign Chain B (L2)
            └── Gateway Contract

Cross-Chain Communication

// Mainchain → Sovereign: Deposit flow
1. User deposits tokens to Gateway Contract on Mainchain
2. Gateway emits deposit event
3. Sovereign Chain validators observe event
4. Tokens minted on Sovereign Chain

// Sovereign → Mainchain: Withdrawal flow
1. User initiates withdrawal on Sovereign Chain
2. Sovereign validators create proof
3. Proof submitted to Mainchain Gateway
4. Tokens released on Mainchain

Security Considerations

| Risk | Mitigation |
|------|------------|
| Bridge funds theft | Multi-sig validators, time locks |
| Invalid proofs | Cryptographic verification |
| Reorg attacks | Wait for finality before processing |
| Validator collusion | Slashing, stake requirements |

7. Critical Checks for Protocol Developers

Intra-shard vs Cross-shard Awareness

// WRONG: Assuming synchronous execution
#[endpoint]
fn process_and_transfer(&self) {
    let result = self.external_contract().compute_value();  // May be async!
    self.storage().set(result);  // result may be callback, not value
}

// CORRECT: Handle async explicitly
#[endpoint]
fn process_and_transfer(&self) {
    self.tx()
        .to(&self.external_contract().get())
        .typed(proxy::Proxy)
        .compute_value()
        .callback(self.callbacks().handle_result())
        .async_call_and_exit();
}

#[callback]
fn handle_result(&self, #[call_result] result: ManagedAsyncCallResult<BigUint>) {
    match result {
        ManagedAsyncCallResult::Ok(value) => {
            self.storage().set(value);
        },
        ManagedAsyncCallResult::Err(_) => {
            // Handle failure
        }
    }
}

Reorg Handling for Microservices

// WRONG: Process immediately
async function handleTransaction(tx: Transaction) {
    await processPayment(tx);  // What if block is reverted?
}

// CORRECT: Wait for finality
async function handleTransaction(tx: Transaction) {
    // Wait for finality (configurable rounds)
    await waitForFinality(tx.hash, { rounds: 3 });

    // Or subscribe to finalized blocks only
    const status = await getTransactionStatus(tx.hash);
    if (status === 'finalized') {
        await processPayment(tx);
    }
}

Gas Considerations for Cross-Shard

// Cross-shard calls consume gas on BOTH shards
// Sender: Gas for initiating call + callback execution
// Receiver: Gas for executing the called function

// Reserve enough gas for callback
const GAS_FOR_CALLBACK: u64 = 10_000_000;
const GAS_FOR_REMOTE: u64 = 20_000_000;

#[endpoint]
fn cross_shard_call(&self) {
    self.tx()
        .to(&other_contract)
        .typed(proxy::Proxy)
        .remote_function()
        .with_gas_limit(GAS_FOR_REMOTE)
        .callback(self.callbacks().on_result())
        .with_extra_gas_for_callback(GAS_FOR_CALLBACK)
        .async_call_and_exit();
}

8. MIP Standards Reference

Monitor MultiversX Improvement Proposals for standard implementations:

| MIP | Topic | Status |
|-----|-------|--------|
| MIP-2 | Fractional NFTs (SFT standard) | Implemented |
| MIP-3 | Dynamic NFTs | Implemented |
| MIP-4 | Token Royalties | Implemented |

9. Network Constants

| Constant | Value | Notes |
|----------|-------|-------|
| Max shards | 3 + Metachain | Current mainnet configuration |
| Round duration | ~6 seconds | Block time |
| Epoch duration | ~24 hours | Validator reshuffling period |
| Max TX size | 256 KB | Transaction data limit |
| Max gas limit | 600,000,000 | Per transaction |

Protocol Experts (Expert)

---
name: mvx_protocol_experts
description: Expert knowledge of the MultiversX Protocol, Consensus (SPoS), Sharding, and Standard Implementations (MIPs).
---

MultiversX Protocol Expertise

This skill encompasses deep knowledge of the core MultiversX protocol architecture, utilized for reviewing protocol-level changes, complex dApp architectures involving cross-shard logic, and sovereign chain integrations.

1. Core Architecture: Adaptive State Sharding

  • Sharding Types:
  • Network Sharding: Nodes are distributed into shards.
  • Transaction Sharding: Transactions are processed by the shard containing the sender's account.
  • State Sharding: Each shard maintains a portion of the global state (account space).
  • Metachain:
  • The coordinator shard.
  • Handles: Validator churning, Epoch/Round verification, Slashing, Header notarization.
  • Does NOT execute general smart contracts (except for system contracts like Staking, ESDT management).
  • Cross-Shard Transactions:
  • Async (Process -> Relay -> Execute): Sender Shard processes TX -> Generates internal transaction (Scratchpad) -> Relayer -> Receiver Shard executes.
  • Atomicity: Cross-shard is atomic but asynchronous.

2. Consensus: Secure Proof of Stake (SPoS)

  • Selection: Deterministic selection of validators based on stake + rating.
  • BLS Signing: Validators sign proposed blocks using BLS multi-signatures.
  • Finality: Instant finality (within seconds) due to PBFT-like consensus within the shard.

3. Token Standards (ESDT)

  • Native Implementation: Tokens are NOT smart contracts (unlike ERC-20). They are part of the protocol account state.
  • ESDT Properties:
  • CanFreeze: Protocol can freeze assets if configured.
  • CanWipe: Protocol can wipe assets if configured.
  • CanPause: Protocol can pause transfers.
  • Roles:
  • ESDTRoleLocalMint: Allows minting.
  • ESDTRoleLocalBurn: Allows burning.

4. Sovereign Chains & Interoperability

  • Sovereign Chains: Dedicated blockchains extending MultiversX.
  • Gateway Contract: Handles bridging between Mainchain and Sovereign Chain.
  • Settlement: Sovereign Chains settle proofs to the MultiversX Mainchain (acting as Layer 1).
  • Interoperability Standards:
  • MIP-X: Monitor [MIPs] for latest standard adoption.

5. Transaction Processing

  • Gas Schedule: Operations have deterministic costs.
  • Built-in Functions:
  • ESDTTransfer: Direct transfer.
  • ESDTNFTTransfer: Transfer of SFT/NFT.
  • MultiESDTNFTTransfer: Batch transfer (often used for Contract calls).

6. Critical Checks for Protocol Developers

  • Intra-shard vs Cross-shard:
  • Always assume a call might be cross-shard unless verified co-location.
  • Async: If logic depends on the result of a call to another address, it MUST be an Async Call (Callbacks).
  • Reorg Handling:
  • Microservices must handle block rollbacks (Standard: wait for 'Finalized' status, or handle re-org events).

Sharp Edges

---
name: multiversx-sharp-edges
description: Catalog of non-obvious behaviors, gotchas, and platform-specific quirks in MultiversX that often lead to bugs. Use when debugging unexpected behavior, reviewing code for subtle issues, or learning platform-specific pitfalls.
---

MultiversX Sharp Edges

A catalog of non-obvious behaviors, "gotchas," and platform-specific quirks that frequently lead to bugs in MultiversX smart contracts and dApps. Understanding these sharp edges is essential for writing correct code.

When to Use

  • Debugging unexpected contract behavior
  • Reviewing code for subtle platform-specific issues
  • Onboarding to MultiversX development
  • Checking if a bug might be caused by a known quirk
  • Preparing for security audits

1. Async Callbacks & Reverts

The Sharp Edge

When an async call fails, the #[callback] is still executed, but state changes from the original transaction are NOT automatically reverted.

The Problem

#[endpoint]
fn transfer_and_update(&self, recipient: ManagedAddress, amount: BigUint) {
    // State change happens IMMEDIATELY
    self.total_sent().update(|t| *t += &amount);

    // Async call to another contract
    self.tx()
        .to(&recipient)
        .egld(&amount)
        .callback(self.callbacks().on_transfer())
        .async_call_and_exit();
}

#[callback]
fn on_transfer(&self) {
    // If transfer FAILED, total_sent is STILL updated!
    // This is inconsistent state!
}

The Solution

#[endpoint]
fn transfer_and_update(&self, recipient: ManagedAddress, amount: BigUint) {
    // DON'T update state before async call
    self.tx()
        .to(&recipient)
        .egld(&amount)
        .callback(self.callbacks().on_transfer(amount.clone()))
        .async_call_and_exit();
}

#[callback]
fn on_transfer(&self, amount: BigUint, #[call_result] result: ManagedAsyncCallResult<()>) {
    match result {
        ManagedAsyncCallResult::Ok(_) => {
            // Only update state on SUCCESS
            self.total_sent().update(|t| *t += &amount);
        },
        ManagedAsyncCallResult::Err(_) => {
            // Handle failure explicitly
            // Funds return to contract automatically
        }
    }
}

2. Gas Limits & Out of Gas (OOG)

The Sharp Edge

OOG can leave cross-shard transactions in partial states.

Cross-Shard OOG Scenario

1. Sender shard processes transaction (state changed)
2. Receiver shard runs out of gas
3. Receiver execution fails
4. Sender state changes PERSIST
5. Callback triggered with error

The Solution

// Always reserve enough gas for callbacks
const CALLBACK_GAS: u64 = 10_000_000;

#[endpoint]
fn safe_cross_shard(&self) {
    self.tx()
        .to(&other_contract)
        .typed(proxy::Proxy)
        .function()
        .with_gas_limit(50_000_000)
        .callback(self.callbacks().handle_result())
        .with_extra_gas_for_callback(CALLBACK_GAS)
        .async_call_and_exit();
}

3. Storage Mappers vs Rust Types

The Sharp Edge

VecMapper is NOT a Vec. They have fundamentally different memory models.

The Problem

// VecMapper: Each element is a separate storage slot
// Accessing element = 1 storage read
// Iterating N elements = N storage reads
#[storage_mapper("users")]
fn users(&self) -> VecMapper<ManagedAddress>;

// If you load into a Vec, you load EVERYTHING into WASM memory
fn bad_function(&self) {
    let all_users: Vec<ManagedAddress> = self.users().iter().collect();
    // With 10,000 users = 10,000 storage reads + massive memory allocation
    // WILL run out of gas
}

The Solution

// Paginate operations
fn process_u

Related Skills

Get the best new skills
in your inbox

Weekly roundup of top Claude Code skills, MCP servers, and AI coding tips.