file: ./content/docs/index.mdx meta: { "title": "Welcome", "description": "Metis Developer Documentation", "icon": "Landmark" } import { Card, Cards } from "fumadocs-ui/components/card"; import { Bot, Landmark } from "lucide-react"; Metis is a next-generation **Layer 2 Ethereum solution**, designed to empower decentralized applications and businesses with **scalability, low-cost transactions**, and a user-centric ecosystem. By leveraging advanced technologies like **Optimistic Rollups** and **Decentralized Sequencers**, Metis aims to overcome the limitations of traditional blockchain networks while maintaining the core ethos of decentralization and security. }> Layer 2 for the next generation of AI DApps }> Battle-tested Mainnet L2 ## Key Features of Metis * **Scalability**: Supports high transaction throughput while maintaining low latency and cost. * **Ethereum Compatibility**: Fully compatible with Ethereum's EVM, making it easy for developers to deploy dApps. * **Decentralized Sequencing**: Eliminates single points of failure by decentralizing the process of transaction ordering and block production. * **Community-Driven Governance**: Encourages collaboration and community-led decision-making. * **Cross-Chain Interoperability**: Facilitates seamless asset and data transfer between Ethereum Layer 1 and Metis Layer 2. file: ./content/docs/andromeda/index.mdx meta: { "title": "Welcome", "description": "Metis Developer Documentation", "icon": "Landmark" } import { Card, Cards } from "fumadocs-ui/components/card"; import { PlayCircle, Code2, Server } from "lucide-react"; Metis is a next-generation **Layer 2 Ethereum solution**, designed to empower decentralized applications and businesses with **scalability, low-cost transactions**, and a user-centric ecosystem. By leveraging advanced technologies like **Optimistic Rollups** and **Decentralized Sequencers**, Metis aims to overcome the limitations of traditional blockchain networks while maintaining the core ethos of decentralization and security. }> Start the Interactive Demo }> Benefits of Building }> Network Operation ## Key Features of Metis * **Scalability**: Supports high transaction throughput while maintaining low latency and cost. * **Ethereum Compatibility**: Fully compatible with Ethereum's EVM, making it easy for developers to deploy dApps. * **Decentralized Sequencing**: Eliminates single points of failure by decentralizing the process of transaction ordering and block production. * **Community-Driven Governance**: Encourages collaboration and community-led decision-making. * **Cross-Chain Interoperability**: Facilitates seamless asset and data transfer between Ethereum Layer 1 and Metis Layer 2. ## Structure The entire structure of Metis Layer 2 is designed around several algorithm loops which are designated to mitigate the potential damage and filter the possible malfunctions of decentralized actors and/or other outer ill-wishers. There are 7 distinguished actors participating in the system (Governance Protocol is a part of L1 / Smart contract, but it handles a number of functions that make it a separate entity): 1. **User** sends the transactions; 2. **Sequencer Node** is responsible for correcting the blockchain, propagating the blocks through the Peer Network; 3. **Metis Blockchain** is an entity held by Decentralized Sequencer; 4. **Verifier** is the counterpart of Sequencer, mostly responsible for keeping an eye on the Sequencer to not provide false/invalid data; 5. **L1 Smart Contracts** — the set of smart contracts that handle the security of the system, solve the disputes between Sequencer and Verifier; 6. **Memolabs** stores the transaction data; 7. **The Governance Protocol** is responsible for anything related to the efficiency of the system. file: ./content/docs/hyperion/index.mdx meta: { "title": "Overview", "description": "Hyperion Developer Documentation", "icon": "Bot" } import Profile from "@/components/rainbowkit/Profile"; import { Card, Cards } from "fumadocs-ui/components/card"; import { Code2, TestTube2, Rocket } from "lucide-react"; Hyperion is a high-performance, Ethereum-compatible Layer 2 network built using the [Metis SDK](https://metis-sdk.vercel.app), designed to deliver unmatched scalability, real-time transaction processing, and seamless interoperability. Leveraging the power of Optimistic Rollup, Parallel Execution, and Decentralized Sequencing, Hyperion pushes the boundaries of Web3 usability, making blockchain applications as fast and responsive as Web2. As a modular and developer-friendly blockchain, Hyperion combines security, decentralization, and high-speed performance, enabling a new era of decentralized finance (DeFi), real-time AI-driven smart contracts, and enterprise blockchain solutions.
| | Hyperion (Testnet) | | --------------- | ---------------------------------------------------------------------------------------- | | Chain ID | 133717 | | Currency Symbol | tMETIS | | RPC | [https://hyperion-testnet.metis.io](https://hyperion-testnet.metis.io) | | Block Explorer | [https://explorer.hyperion-testnet.metis.io](https://explorer.hyperion-testnet.metis.io) | | Faucet | [Telegram Bot](https://t.me/hyperion_testnet_bot) | ## Unrivaled Scalability with Optimistic Rollup & Parallel Execution Hyperion redefines Layer 2 scalability by integrating Optimistic Rollup technology with highly parallelized transaction execution. This enables developers to build complex applications without worrying about throughput bottlenecks. * Instant Transaction Finality - Achieves near sub-second settlement through Optimistic Commitments. * Parallel Execution Engine - Smart contracts and transactions run concurrently, significantly increasing processing speed. * Optimized Fraud-Proof Mechanisms - Ensures Ethereum-grade security while reducing costs and delays. Why it matters: Hyperion outperforms traditional Layer 2s by eliminating sequential processing bottlenecks, allowing for a seamless Web3 experience. ## MetisVM: A High-Performance Virtual Machine for Smart Contracts At the heart of Hyperion lies MetisVM, an Ethereum-compatible virtual machine that delivers unparalleled efficiency and performance for smart contract execution. * Dynamic Opcode Optimization - Reduces execution costs and boosts contract efficiency. * Speculative & Parallel Execution - Improves transaction throughput with optimized resource allocation. * State-Aware Caching - Enhances execution speed by reducing redundant storage access. * AI Infra Support - Optimizing and supporting computationally intensive on chain inference AI applications through inference engine optimization, VM precompile and host functions. Besides, MetisVM also supports integration with zkVM to achieve more secure AI features. Why it matters: Developers can build high-frequency trading, gaming, and AI-integrated DApps with enterprise-grade speed and security. ## MetisDB: Next-Gen State Management System Blockchain performance hinges on efficient state management. MetisDB introduces a revolutionary approach to storage, enabling instant access to state data, optimized transaction processing, and cost-efficient data management. * Memory-Mapped Merkle Trees - Provides near nanosecond-level state access for real-time applications. * Multi-Version Concurrency Control (MVCC) - Enables parallel state updates for high-speed execution. * Asynchronous I/O Processing - Ensures low-latency, high-throughput storage operations. Why it matters: MetisDB eliminates storage bottlenecks, ensuring smooth execution of high-frequency blockchain transactions. ## Ethereum Settlement & Cross-Chain Interoperability Hyperion is Ethereum-secure and interoperable with multiple blockchain ecosystems, ensuring seamless cross-chain liquidity and data flow. * Optimized Ethereum Settlement - Periodic state commitments to Ethereum guarantee long-term security. * Shared Bridge & Cross-Chain Connectivity - Enables multi-chain liquidity and interoperability. * Decentralized Data & Compute Aggregation - Connects AI-driven applications, compute providers, and data networks. Why it matters: Hyperion creates a fluid Web3 infrastructure, enabling scalable decentralized applications that interact across blockchain networks. ## The Future of Decentralized Sequencing Hyperion will introduce the Decentralized Sequencer Network in an upcoming release, providing fault tolerance, censorship resistance, and fair transaction ordering—a major leap from centralized sequencer models. * Leader Rotation Mechanism - Prevents centralization by dynamically assigning sequencers. * Timeout Failover - Automatic failover ensures continuous transaction processing. * MEV-Resistant Ordering - Encrypted mempools & Proposer-Builder Separation (PBS) eliminate front-running and unfair advantage. With decentralized sequencing, Hyperion will ensure fair and transparent transaction execution, preventing manipulation and guaranteeing reliability. *** ## The Future of High-Performance Layer 2 Networks Hyperion is not just another Layer 2—it's a revolutionary infrastructure built for ultra-fast execution, scalable smart contracts, and enterprise adoption. With Optimistic Rollup efficiency, decentralized sequencing, and cross-chain interoperability, Hyperion sets a new benchmark for blockchain performance. ### Key Takeaways * Real-Time Execution - Transactions settle instantly, delivering a Web2-like user experience for memory and compute-intensive applications like on-chain games, DEXs, AI inference, etc. * Unmatched Throughput - Parallel execution eliminates congestion, scaling beyond traditional Layer 2 solutions. * Decentralized Sequencing - Prevents censorship, ensures fairness, and eliminates MEV manipulation. * Ethereum Security + Cross-Chain Compatibility - Seamlessly connects Ethereum, AI ecosystems, and next-gen Web3 applications. Hyperion is pioneering the future of Layer 2, combining performance, scalability, and decentralization—empowering the next wave of blockchain innovation. ## Relationship with Andromeda While Andromeda remains Metis' established Layer 2 network designed for general-purpose DApps, Metis Hyperion represents the next evolution focused on high-performance execution, decentralized sequencing, and gas fee flexibility. Both networks will coexist within the Metis ecosystem, serving different use cases. file: ./content/docs/andromeda/network/audits.mdx meta: { "title": "Audits", "icon": "Shield" } import { Card, Cards } from "fumadocs-ui/components/card"; Ensuring the security and safety of the Metis Layer 2 network is a top priority. To maintain the highest standards of security, Metis undergoes regular security audits conducted by industry-leading blockchain security firms. These audits meticulously review our smart contracts, bridges, and protocol to identify any vulnerabilities and ensure the robustness of our ecosystem. Security audits are essential to maintaining the trust of users and developers, ensuring that our code is free from vulnerabilities and secure against potential threats. Below, you can download the security audit reports from the leading blockchain security firms that have audited Metis's infrastructure: ### Audit Reports file: ./content/docs/andromeda/network/council.mdx meta: { "title": "Security Council", "icon": "EarthLock" } | Name | Organization | Address | Bio | | ------------------------------------------------------------------------------------ | ----------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Dr. Redouane Elkamhi](https://discover.research.utoronto.ca/24652-redouane-elkamhi) | University of Toronto | 0xF81F0E3490cF754dFB3247e5BF202601aA9C49f4 | Redouane Elkamhi is a Professor of Finance at the Rotman School of Management, University of Toronto, Canada. His areas of expertise include strategic and tactical asset allocation, total fund management, and decentralized finance. Professor Elkamhi was the inaugural co-director of the Finance Lab at the Rotman Financial Innovation Hub, focusing on blockchain, decentralized finance, and crypto-ventures. In addition to his academic career, Professor Elkamhi has served for over two decades as a senior advisor to several large Canadian pension funds, including OTPP, HOOPP, and PSP, providing strategic and investment advisory services. He has also been a strategic advisor to EY and KPMG. | | [PGov Team](https://x.com/PGovTeam) | PGov LLC (Uniswap DAO member) | 0x9A73D57BB1fB280C5672A13f655675De25F13b70 | PGov specializes in providing governance services for decentralized protocols. Our members are dedicated to innovation, leveraging over five years of specialized expertise to provide pinpointed guidance that meets each team's specific governance needs. | | [Ben A. Wynn](https://x.com/0x1164) | House of ZK | 0x308400748938E14789A40222b45163D073167136 | Ben Wynn is a strategist and builder focused on advancing blockchain and ZK infrastructure. He co-founded House of ZK, a media and education platform accelerating mainstream understanding and adoption of ZK. | | [Larry Ma](https://snzholding.com/about#snz-team) | SNZ Holding, CSO | 0x4361eD603737246b36cABf27F26d63f2A691feD5 | Larry brings over 25 years of global experience across e-commerce, digital marketing, financial services, and blockchain innovation. A proven leader, he has spearheaded successful startups and held leadership roles at renowned internet conglomerates, fintech giants, and top blockchain ecosystems. Larry is passionate about building high-performing teams, fostering a culture of innovation, and driving impactful results. | | [Amber D. Scott](https://www.linkedin.com/in/amberdscott) | Outliner Solutions | 0x671babD79cf53BE512F9549D3C30EB1A066aAeb8 | Amber D. Scott is a seasoned compliance executive with deep expertise spanning banking, mutual funds, insurance, and digital assets. As Co-Founder and Chair of Outlier Compliance Group, she leads strategy and regulatory innovation in AML, crypto, and identity, while mentoring compliance teams. Amber is also a doctoral candidate and sought-after speaker, blending real-world insight with academic rigor to advance financial inclusion and secure systems. | | [Yuan Su](https://www.linkedin.com/in/yuansu) | Metis CoFounder and CTO | 0x886d5203cE6EDc8BA719ea5931E689606e84492B | Yuan Su is the Co-Founder and CTO of Metis, bringing a visionary blend of tech and business expertise to Web3. Formerly a Technical Lead at IBM, he now channels his passion into advancing decentralization through Metis and his latest venture, Nuvo. | | [Elena Sinelnikova](https://x.com/ElenaCryptoChic) | Metis CoFounder | 0xc27896E7b4172D6B1C21177D91fd64A935EEc4EA | Elena Sinelnikova is the Co-Founder of Metis and CryptoChicks, where she played a key role in growing it from a startup into a leading Layer 2 platform. With 20+ years in software engineering and blockchain, she's a recognized voice in Web3 education, advocacy, and ecosystem leadership. | | [Nelli Orlova](https://www.linkedin.com/in/nelli-orlova) | InnMind Founder | 0xDEe0AE49547c50E6B687f9242333E39b904fb2af | Nelli Orlova, BBA, is a Web3 founder and investor currently serving as CEO of InnMind and co-founder of AlphaMind, where she leads accelerator programs, tokenomics workshops, and investor scouting. | file: ./content/docs/andromeda/network/faq.mdx meta: { "title": "FAQ", "icon": "CircleHelp" } import { Accordion, Accordions } from "fumadocs-ui/components/accordion"; In a decentralized network, control is distributed across multiple participants rather than being concentrated in a central authority. This ensures: * **Resilience**: Prevents single points of failure. * **Security**: Guards against malicious attacks by spreading control across the network. * **Transparency**: Enables open and verifiable operations. * **Censorship Resistance**: Protects against undue influence or restrictions by centralized entities. Metis is pioneering decentralized infrastructure by integrating advanced governance and **Decentralized Sequencers**, enabling a robust and equitable environment for blockchain applications. Metis is an Ethereum Layer 2 leveraging innovative technologies such as Decentralized Sequencers and off-chain storage for empowering a sustainable Web3 economy. The system is designed in a way that any malfunctioning actor gets charged and swapped out through the constant cycles of rotation. It is accomplished with the Peer Network which includes Sequencers, Verifiers, and Consensus (PoS) layer. After the next major upgrade, there will be no more downtime at all, and the maintenance schedule will be controlled by the community through the governance protocol. It is a network of decentralized actors (nodes) that serve the Metis system. Anyone can become a part of the Peer Network just by setting up a node on their computer. The participants of the Peer Network receive revenue with a portion of the fees from all the transactions that go through the Peer Network. Metis utilizes the Merkle Tree State and Batch Roots (MTSR/MTTBR). In an oversimplified analogy, you can think about MTSR or MTTBR as a bank cheque that you can withdraw the money from. Let’s say you want to give someone a big sum of money: in a more efficient way you would give a bank cheque instead of a bag of cash. Metis does the same: instead of posting huge chunks of transaction data to Layer 1, Metis utilizes MTSR/MTTBR to make it way more efficient while still utilizing the security of Ethereum. It is a hashing algorithm which is aimed to identify the inconsistencies between the nodes (or participants of the Peer Network in our case). Merkle tree is created by dividing data into many pieces, which are then hashed repeatedly to form the Merkle Tree Root. You can efficiently verify if something has gone wrong with a piece of data. Yes, you can practically check whether your transaction is included into a MTSR/MTTBR data batch (that’s also how Metis solves the data availability problem), and it cannot be maliciously altered without your private keys. Ethereum Layer 1 processes the transaction data, Metis instead utilizes Ethereum Layer 1 to process MTSR/MTTBR batches which were derived from the transaction data. Your money will either successfully reach the desired destination address, or you will have to resend the transaction. No money will be lost. Metis stores the transaction data in Memolabs storage, which is based on blockchain technology to provide safe, efficient, and large-scale decentralized cloud storage services. Yes, in this case the Verifier downloads the transaction data from Memolabs. If Memolabs is unavailable, then Verifier requests the Sequencer to post the transaction data on L1 and then downloads it from there. You can check these cases in diagrams or algorithm section below for more details. Metis is a native token but also an ERC20 compatible token on Layer 2. It is a built-in feature, so there is no need to create a wrapped Metis token, and the source code is [here](https://github.com/MetisProtocol/mvm/blob/develop/packages/contracts/contracts/MVM/MVM_Coinbase.sol). Sushiswap team deployed a wMetis, it's the same with WETH9, the contract address is [0x75cb093E4D61d2A2e65D8e0BBb01DE8d89b53481](https://andromeda-explorer.metis.io/address/0x75cb093E4D61d2A2e65D8e0BBb01DE8d89b53481/contracts). Metis has support for the Berlin and `PUSH0` opcode with the Shanghai upgrade. Metis does not support the Cancun upgrade yet. The latest Solidity version that Metis Andromeda supports is **v0.8.23**. file: ./content/docs/hyperion/architecture/db.mdx meta: { "title": "MetisDB" } ## Overview MetisDB is a cutting-edge storage solution tailored for high-throughput, low-latency Layer 2 networks. It optimizes transaction processing, state synchronization, and historical data management by separating state commitment from state storage, ensuring unmatched performance and scalability. ## Core Design Principles ### State Commitment and Storage Separation MetisDB follows a novel architectural approach that separates state commitment from storage: * **State Commitment Layer**: Manages active blockchain state for rapid access and updates * **State Storage Layer**: Focuses on historical data maintenance for archival and query purposes This separation allows MetisDB to optimize both real-time processing and historical data retrieval, addressing different performance needs simultaneously. ### Multi-Version Concurrency Control (MVCC) MetisDB implements MVCC to enable concurrent state access and modifications: * Allows multiple transactions to read and write state concurrently * Prevents blocking during parallel execution * Supports efficient rollbacks in speculative execution environments * Reduces contention during high-throughput operations ### Asynchronous I/O Processing To minimize latency and maximize throughput, MetisDB employs asynchronous I/O: * State changes are committed asynchronously * Write operations don't block transaction processing * Allows continuous transaction execution at high speeds * Maintains ACID guarantees through careful transaction management ## Key Components ### State Commitment Layer The State Commitment Layer is optimized for active state access and modification: * **Memory-Mapped Merkle Trees**: Provides nanosecond-level state access * **Transaction Delta Processing**: Efficiently applies state changes and generates block hashes * **Write-Ahead Log (WAL)**: Records changesets asynchronously for durability * **Snapshot Management**: Creates periodic snapshots to accelerate recovery ### State Storage Layer The State Storage Layer handles historical data storage and retrieval: * **Raw Key-Value Storage**: Minimizes overhead through optimized data structures * **Asynchronous Pruning**: Removes outdated data without affecting active processes * **Flexible Backend Support**: Compatibile with various storage solutions (RocksDB, etc.) ## Integration With Parallel Execution Framework MetisDB is tightly integrated with the Metis Parallel Execution Framework: 1. Transactions are executed in parallel by the execution framework 2. State access and modifications are tracked through MVCC 3. Conflict detection and resolution is performed automatically 4. Valid state changes are committed asynchronously file: ./content/docs/hyperion/architecture/index.mdx meta: { "title": "Architecture", "description": "Detailed overview of the Metis Hyperion (HYPE) architecture, including its layered design, key components, and developer interactions." } This document provides an in-depth overview of the Metis Hyperion (HYPE) architecture, highlighting its layered design, key components, and how they interact to deliver high-performance Layer 2 capabilities. Metis Hyperion is built on a modular architecture with four primary layers, each addressing specific aspects of blockchain scalability, performance, and interoperability: 1. **Networking & Consensus Layer**: Handles data communication and transaction ordering 2. **Execution Layer**: Powers high-performance transaction processing 3. **Data Services Layer**: Provides efficient state management and storage ## 1. Networking & Consensus Layer The Networking & Consensus Layer manages data communication, transaction ordering, and consensus within the Hyperion network. ### Key Components * **Decentralized Sequencer Network**: Provides decentralized and fair transaction ordering with: * Leader rotation mechanism * Timeout-based failover * BLS multi-signatures for quorum certificates * MEV-resistant mechanisms * **Scalable Consensus Engine**: Supports customizable sequencer networks, balancing performance and decentralization. * **Node Sync Component**: Ensures rapid synchronization of blockchain data across nodes. * **Relayer**: Manages message communication and transaction forwarding between Ethereum Layer 1 and Metis Hyperion. ### Consensus Workflow 1. Transaction Submission: Users submit signed transactions to the distributed mempool 2. Sequencer Leader Election: A stake-weighted mechanism assigns the active sequencer 3. Transaction Batch Formation: The sequencer creates ordered transaction batches 4. Batch Validation: Transactions are validated against consensus rules 5. State Commitment: The batch is finalized with a quorum certificate (QC) 6. Ethereum Settlement: Periodically, state roots are submitted to Ethereum L1 ## 2. High-Performance & Infinite Scalability Execution Layer The Execution Layer forms the backbone of Metis Hyperion's high-performance capabilities, enabling real-time transaction processing and parallel execution. ### Key Components * **MetisVM (EVM-Compatible Executor)**: * Dynamic Opcode Optimization * Instruction Extensions (including floating-point operations) * JIT Compilation for frequently used opcodes * Speculative & Parallel Execution * State-Aware Caching * AI Infrastructure Support * **Real-Time Transaction Pipeline**: * Pipelined architecture for minimum end-to-end latency * Immediate transaction feedback * Deferred BlockHash Priority for high throughput * Parallelized State Root Framework * **Metis Parallel Execution Framework (MPEF)**: * Transaction Pre-Processing with static code analysis * DAG-based execution scheduling * Optimistic Concurrency Control * Conflict detection and resolution * **Native Paymaster** (Future): * Gas fee abstraction * Support for ETH, USDC, and USDT payments * Web2-style user onboarding ## 3. Data Services Layer The Data Services Layer ensures efficient, secure, and scalable data management for the Metis Hyperion network, optimizing storage and retrieval of blockchain state. ### Key Components * **MetisDB**: A custom-designed database optimized for Sequencer operations with: * Asynchronous I/O for minimal latency * High-efficiency MVCC caching * Memory-mapped Merkle trees for nanosecond-level state access * Write-Ahead Logging (WAL) for durability * Snapshot management for recovery * **State Commitment Layer**: Manages active blockchain state with: * Memory-Mapped Merkle Trees * Transaction Delta Processing * Efficient state proof generation * **State Storage Layer**: Optimized for historical data with: * Raw Key-Value Storage * Asynchronous Pruning * Flexible backend support ## Integration Between Layers Metis Hyperion's layered architecture ensures modular yet integrated operation: 1. **Inputs**: Transactions from users and cross-chain messages enter through the Networking Layer 2. **Ordering**: The Consensus Layer sequences these transactions via the Decentralized Sequencer 3. **Execution**: The High-Performance Execution Layer processes transactions in parallel 4. **State Management**: The Data Services Layer efficiently updates and maintains state ### Full Transaction Flow 1. User submits transaction to Metis Hyperion network 2. Transaction enters the encrypted mempool 3. Leader sequencer includes the transaction in a batch 4. Static analysis identifies dependencies and execution paths 5. Parallel execution framework processes the transaction 6. State is updated in MetisDB with minimal latency 7. User receives immediate transaction confirmation 8. Periodically, state commitments are sent to Ethereum L1 ## Developer Implications This architecture delivers several key benefits for developers: * **Modularity**: Select and customize components based on application needs * **Scalability**: Leverage parallel execution for high-throughput applications * **Flexibility**: Support for diverse virtual machines and programming models * **Performance**: Sub-second finality and immediate feedback for responsive dApps * **Interoperability**: Seamless cross-chain functionality without complex bridging file: ./content/docs/hyperion/architecture/pef.mdx meta: { "title": "Parallel Execution Framework (PEF)" } The Parallel Execution Framework (PEF) is a transaction execution engine that powers Metis Hyperion (HYPE) with unprecedented throughput and efficiency. This guide provides developers with a comprehensive understanding of MPEF and how to optimize smart contracts to leverage its parallel execution capabilities. ## Introduction Traditional blockchain execution engines process transactions sequentially, resulting in bottlenecks as network usage increases. MPEF eliminates this limitation by enabling concurrent transaction processing while maintaining data consistency and transaction integrity. By combining advanced techniques like Block-STM, static dependency analysis, and DAG-based scheduling, MPEF achieves dramatic performance improvements without sacrificing security or determinism. ## Key Concepts ### Transaction Dependencies For parallel execution to work correctly, the system needs to understand when transactions can safely execute concurrently: * **Independent transactions**: Operations that don't access the same state can run in parallel * **Dependent transactions**: Operations with overlapping state access must maintain execution order * **Conflict detection**: The system identifies and manages potential conflicts to ensure consistent results ### DAG-Based Execution Model MPEF uses a Directed Acyclic Graph (DAG) to represent transaction dependencies: ```mermaid graph TD TX1 --> TX2 TX3 --> TX4 TX2 --> TX5 TX4 --> TX5 ``` In this example: * TX1 and TX3 can execute in parallel (independent) * TX2 depends on TX1 and TX4 depends on TX3 * TX5 depends on both TX2 and TX4 ### Optimistic Concurrency Control (OCC) MPEF employs OCC to maximize throughput: 1. Transactions execute speculatively without waiting for dependency resolution 2. The system tracks read and write sets during execution 3. If conflicts are detected, affected transactions are rolled back and re-executed 4. Successful transactions are committed to the final state ## Architecture Components ### 1. Transaction Pre-Processing Before execution, MPEF analyzes transactions to optimize parallel processing. The static analyzer identifies: * Storage slots accessed (e.g., `balances[msg.sender]`, `balances[to]`) * Access patterns (read/write) * Potential conflicts between transactions #### Dependency Graph Generation MPEF constructs a DAG representing transaction dependencies: * Nodes represent transactions * Edges represent dependencies (must execute in order) * Independent paths represent opportunities for parallelization #### Batch Formation Transactions are grouped into execution batches based on the DAG: * Layer 1: All independent transactions * Layer 2: Transactions depending only on Layer 1 * And so on... ### 2. Parallel Execution Engine The core of MPEF is its parallel execution engine: #### Optimistic Concurrency Control ``` Process: 1. Begin transaction 2. Execute speculatively 3. Track read/write set 4. Validate (check conflicts) 5. If valid, commit; otherwise, abort and retry ``` This approach allows maximum throughput while ensuring correct execution results. #### DAG-Based Scheduling The scheduler: * Executes independent transactions concurrently * Respects DAG dependencies for ordering * Dynamically adjusts priorities based on gas fees, user specifications, etc. ### 3. State Management Efficient state management is crucial for parallel execution: #### Multi-Version Concurrency Control (MVCC) MPEF maintains multiple versions of the blockchain state: * Each transaction sees a consistent snapshot * New versions are created during execution * Versions are merged or discarded based on validation results #### Asynchronous State Updates State changes are committed efficiently: * Updates are batched for performance * Commits happen after validation * MetisDB integration ensures efficient storage and retrieval ### 4. Validation and Feedback MPEF provides real-time validation and feedback: * **Conflict Detection**: Continuously monitors for state access conflicts * **Execution Status**: Provides immediate feedback on transaction status * **Performance Metrics**: Tracks execution statistics for optimization ## Execution Workflow Example To illustrate the complete workflow, let's follow a set of transactions through MPEF: 1. Users submit multiple token transfer transactions to Metis Hyperion 2. Transactions enter the mempool and are forwarded to MPEF 3. Static analysis identifies which transfers can run in parallel (different sender/recipient pairs) 4. DAG generation creates a dependency graph, grouping independent transfers 5. Parallel execution processes multiple transfers simultaneously 6. MVCC maintains consistent state during execution 7. Conflict detection identifies any overlapping state access 8. Validation confirms transaction results 9. State updates are committed to MetisDB 10. Users receive confirmation with minimal latency ## Performance Benefits MPEF provides significant performance improvements: | Scenario | Without PEF | With PEF | | ---------------------------- | ----------- | ---------- | | Independent ERC-20 Transfers | 100-200 TPS | 1,000+ TPS | | DEX Swaps (Different Pairs) | 50-100 TPS | 500+ TPS | | NFT Minting | 30-60 TPS | 300+ TPS | | Complex DeFi Operations | 20-40 TPS | 100+ TPS | file: ./content/docs/hyperion/architecture/vm.mdx meta: { "title": "MetisVM" } MetisVM is the high-performance virtual machine at the core of Metis Hyperion (HYPE), designed to deliver exceptional efficiency, flexibility, and developer accessibility. This guide provides comprehensive information for developers looking to leverage MetisVM's capabilities. ## Overview MetisVM is a next-generation EVM-compatible execution environment that powers Metis Hyperion with three critical elements: * **Uncompromising security**: Robust execution with built-in safeguards * **Seamless scalability**: Parallel processing and optimized execution * **Enterprise-grade reliability**: Predictable performance at scale The VM is specifically optimized for both traditional smart contracts and AI-specific operations, creating a foundation for high-performance decentralized applications. ## Key Features ### 1. Dynamic Opcode Optimization #### Instruction Extension MetisVM supports customizable extended opcodes, including: * Floating-point operations of different precisions * AI quantization models with varying precision requirements * Dynamic instruction set updates through on-chain governance ### 2. Speculative & Parallel Execution MetisVM utilizes advanced predictive algorithms to forecast operation results and execute transactions in parallel: #### Block-STM Parallel Execution By leveraging Software Transactional Memory concepts, MetisVM: * Executes multiple transactions concurrently * Detects and resolves conflicts automatically * Maximizes throughput without sacrificing correctness In high-volume decentralized trading scenarios, this can increase transaction processing speed by more than 50%, enabling faster settlement and a smoother user experience. #### State-Aware Caching MetisVM intelligently caches frequently-accessed state variables: * Tracks state transitions to reduce redundant storage access * Adapts caching strategy based on contract behavior * Significantly improves execution speed for state-intensive contracts This is particularly beneficial for governance and voting contracts in DAOs, where many operations access the same state variables repeatedly. ### 3. AI Infrastructure Support MetisVM provides foundational support for on-chain AI applications through three critical innovations: #### Inference Engine Optimization MetisVM optimizes inference through: * VM precompilation for faster model loading and execution * Host functions bridging AI models and smart contract logic * Reduced latency for AI-based operations #### AI Coprocessor Acceleration Machine learning inference often requires substantial computing resources. MetisVM supports hardware acceleration through: * SIMD instructions (e.g., AVX512) * GPU/TPU integration * FPGA support * Optimized tensor operations This acceleration dramatically enhances inference performance, enabling previously impossible on-chain AI applications. #### zkVM Integration MetisVM supports integration with zero-knowledge proofs for AI inference: * Generate ZK proofs for the AI inference process * Achieve more secure AI functions with privacy preservation * Protect sensitive data while maintaining verifiability Example use case: In a decentralized AI-driven lending platform, this integration can protect borrowers' financial data while still allowing AI models to make accurate credit assessments. ## Developer Ecosystem ### EVM-Compatible Toolkit MetisVM maintains full compatibility with standard Ethereum development tools: * **Foundry**: Test, debug and deploy using Foundry's powerful toolchain * **Hardhat**: Complete Hardhat compatibility for contract development * **Truffle**: Legacy Truffle support for existing projects * **Remix**: Compatible with Remix IDE for quick development ## Application Scenarios ### 1. Real-Time Financial Derivatives MetisVM enables sub-second option pricing through: * Parallel execution of pricing models * Floating-point extension opcodes * zkML for model compliance verification ### 2. On-Chain Gaming MetisVM's state caching system supports: * 200+ entity state updates per second * AI-powered NPC decision making * Real-time player interactions ### 3. DeFAI Risk Control Real-time machine learning models can: * Monitor liquidity risk dynamically * Adjust protocol parameters based on market conditions * Execute preventative measures during volatile periods file: ./content/docs/hyperion/hyperhack/test-dex.mdx meta: { "title": "Test DEX", "description": "Learn how to use the Test DEX and its subgraph" } ## Interacting with the DEX A Decentralized Exchange (DEX) allows users to swap tokens directly from their wallets, provide liquidity, and earn fees. To use the DEX: 1. **Connect Your Wallet**: Use a wallet like MetaMask or Rabby to connect to the [DEX Interface](https://hype-test-dex.metis.io). 2. **Swap Tokens**: * Select the token you want to swap from and the token you want to receive. * Enter the amount and review the estimated output. * Approve the token if required, then confirm the swap. 3. **Provide Liquidity**: * Go to the "Liquidity" section. * Select the token pair and amounts to deposit. * Approve both tokens if necessary, then supply liquidity. * You will receive LP (Liquidity Provider) tokens representing your share. ## Querying DEX Data with the Subgraph The subgraph indexes on-chain DEX events and exposes them via a GraphQL API for easy querying. 1. **Access the Subgraph**: * Use the [Subgraph Endpoint](https://subgraph.metis.io/subgraphs/name/hype-test-dex) 2. **Example Queries**: * **Fetch Recent Swaps**: ```graphql query { swaps(first: 5, orderBy: timestamp, orderDirection: desc) { id sender amount0In amount0Out amount1In amount1Out timestamp } } ``` * **Get Liquidity Pool Stats**: ```graphql query { pairs { id token0 { symbol } token1 { symbol } reserve0 reserve1 totalSupply } } ``` ### Get Testnet Tokens You can get testnet tokens from the [HyperHack Forum](https://forum.ceg.vote/t/request-dex-test-tokens-here/5206). file: ./content/docs/hyperion/lazai/index.mdx meta: { "title": "LazAI Client" } What if we want to connect AI to a larger, global network? How can we share data, offer services, or use services from other AI agents around the world in a secure and verifiable way? This is where the LazAI network comes in, and your gateway to it is the LazAI Client. ## Your Passport to a Decentralized AI Nation Imagine the LazAI network is a new digital country. This country has its own government (a blockchain), public records office, and a marketplace for AI services. To do anything in this country—like register property, open a business, or hire someone—you need a passport and a way to interact with its systems. The `alith.lazai.Client` is your personal passport and remote control for the LazAI network. You use it to: * **Establish Your Identity:** It manages your digital wallet, which is your unique ID on the network. * **Interact with the "Government":** It lets you perform official actions on the blockchain, like registering data or services. * **Participate in the Economy:** It allows you to request services from other network members and handle payments. Our goal is simple but fundamental: we'll use the `LazAI Client` to perform our first official act on the network: **registering a piece of data (a file's location) in the public record.** ## Getting Your Passport: Creating a Client The first step to entering any new country is to get your passport. With Alith, this is incredibly easy. **1. Import and Create the Client** ```python from alith.lazai import Client # This one line connects you to the LazAI network client = Client() ``` That's it! When you create an instance of `Client`, Alith automatically creates a new digital wallet for you (or loads an existing one). This wallet is your identity. You can think of it as your unique passport number. **2. See Your New Identity** Every passport has a unique number. You can see your wallet's public address like this: ```python print("My wallet address:", client.wallet.address) ``` **Example Output:** ``` My wallet address: 0xAbC123...dE45F6 ``` This address is your public identity on the LazAI network. You'll use it to sign transactions and prove ownership. ## Your First Official Act: Registering a File Now that we have our passport, let's interact with the "public records office" (the blockchain). We're going to register the location of a file. This doesn't upload the file itself; it just creates a permanent, verifiable record on the blockchain that says, "This file, at this URL, is associated with me." **1. Define the File's Location** First, let's specify the URL of the file we want to register. ```python # The location of the data we want to register url = "https://example.com/my-awesome-dataset.csv" ``` **2. Add the File to the LazAI Registry** Next, we use our `client` to call the `add_file` function. This is like going to the records office and officially filing paperwork. ```python # Register the file on the blockchain file_id = client.add_file(url) print("My file has been registered with ID:", file_id) ``` The `client.add_file(url)` function sends a request to the LazAI network. The network processes it, adds the record to the blockchain, and gives you back a unique `file_id`. This ID is like your receipt or tracking number. **3. Verify Your Registration** How can we be sure our file was actually registered? We can ask the network to look it up for us using its URL. ```python # Ask the network to find the ID for our URL retrieved_id = client.get_file_id_by_url(url) if retrieved_id == file_id: print("Success! The network confirms our file is registered.") ``` This confirms that our transaction was successful and the record is now permanently on the blockchain for anyone to see. This simple process is the foundation for data contribution, which is described in detail in the next section. ## How Does It Work Under the Hood? When you call `client.add_file()`, a few important things happen behind the scenes to ensure the process is secure and verifiable. 1. **Prepare the "Paperwork":** Your `Client` creates a formal request, called a "transaction," that says "Add this URL to the registry." 2. **Sign with Your Passport:** The `Client` uses your private wallet key to digitally "sign" this transaction. This is like an official signature that proves the request came from you and nobody else. 3. **Submit to the Government:** The signed transaction is sent to LazChain. 4. **An Official Record is Made:** The network validators check your signature, confirm the request is valid, and permanently add the information (the URL and your ownership) to the public ledger. 5. **A Receipt is Issued:** The network assigns a new, unique `file_id` for this record and sends it back to your `Client`. Here is a diagram showing the flow: ```mermaid sequenceDiagram participant YourScript as "Your Script" participant LazAIClient as LazAI Client participant Wallet participant LazChain as LazChain YourScript->>LazAIClient: client.add_file("https://...") LazAIClient->>Wallet: "Please sign this transaction" Wallet-->>LazAIClient: Returns a digital signature LazAIClient->>LazChain: Submits the signed transaction LazChain-->>LazAIClient: Confirms transaction, returns file_id LazAIClient-->>YourScript: Returns the file_id ``` ## More Than Just Files: Becoming a Network Participant The `LazAI Client` is your all-purpose tool for network interaction. Registering a file is just the beginning. As seen in `lazai_inference_settlement.py`, before you can request paid services, you need to officially register as a "user" and deposit a small amount of funds to cover transaction fees. ```python # A simplified example of becoming a network user try: # Check if I'm already registered client.get_user(client.wallet.address) except Exception: # If not, register and deposit funds for fees client.add_user(1000000) ``` This is a one-time setup step, like opening a bank account in our new digital country. Furthermore, you can use the `Client` to register yourself as a **service provider** (a "node"). As shown in `lazai_add_node.py`, you can tell the network that you are ready to do work for others. ```python # A simplified example of registering your own service my_service_url = "https://my-ai-service.com" my_public_key = "-----BEGIN RSA PUBLIC KEY-----..." # Announce your service to the network client.add_node(client.wallet.address, my_service_url, my_public_key) ``` This action tells the LazAI network, "I'm open for business! Anyone who needs my AI service can find me at this address." file: ./content/docs/hyperion/lazai/inference.mdx meta: { "title": "Inference & Settlement" } Previously, we got our "passport" to the LazAI network. We learned how to create a digital identity and register a piece of data on the blockchain. We are now official citizens of this new digital country. But what do we *do* here? The most exciting part of the LazAI network is its bustling marketplace of AI services. What if your agent needs to think with a super-powerful AI brain that you can't run on your own computer? How do you securely "rent" time on someone else's machine and pay them for it? ## The Pay-As-You-Go AI Marketplace Imagine you have an AI Agent but you want it to use a massive, cutting-edge AI model. Running this model requires expensive, powerful hardware that you don't have. In a centralized world, you'd subscribe to a single company's service. In the LazAI network, you can access a global, decentralized marketplace of "inference nodes"—people and organizations all over the world who are renting out their AI processing power. **Our goal:** We will take a simple `Agent` and make it run its "thinking" process (inference) on a remote machine in the LazAI network. We'll see how payment is handled automatically and securely, without needing to trust the node operator directly. ## The "Digital Check": How Settlement Works How can a node operator trust that you'll pay them *after* they've done the work? And how can you be sure you're only paying for the work you requested? The solution is a "digital check" that you sign *before* you even send your request. In Alith, these are called **settlement headers**. When you want to ask a remote AI model a question, here's what happens: 1. **You Write a Digital Check:** Your `LazAI Client` creates a special set of data (the headers) that says, "I, wallet `0x123...`, promise to pay node `0xABC...` for this one request." 2. **You Sign It:** You digitally sign this "check" with your wallet's private key. This is a cryptographic guarantee that it came from you. 3. **You Attach It to Your Request:** Your AI's question and this signed check are sent together to the remote node. 4. **The Node Verifies the Check:** Before doing any work, the node operator can quickly verify your signature and check the blockchain to see if you have enough funds deposited to cover the cost. 5. **Work is Done & Payment is Claimed:** Once they see the check is valid, they run the AI model and send you the answer. Later, they can submit your signed "check" to the blockchain to claim their payment. This creates a fair, trustless, and pay-as-you-go system. ## Using a Remote AI Model: A Step-by-Step Guide Let's modify our `Agent` to use a remote AI model. We'll be referencing the logic in the [`lazai_inference_settlement.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/examples/lazai_inference_settlement.py) example file. **1. One-Time Setup: Join the Club and Add Funds** Before you can shop in the marketplace, you need to register as a user and deposit a small amount of funds to cover service fees. This is like opening a bank account in the new country. *This is a one-time operation.* Once you've done it, you're ready to make requests. ```python from alith.lazai import LazAIClient # This is the "address" of the service provider group we want to join LAZAI_IDAO_ADDRESS = "0x34d9E02F9bB4E4C8836e38DF4320D4a79106F194" client = LazAIClient() # This block is only run once to set up your account try: client.get_user(client.wallet.address) print("User already registered!") except Exception: print("Registering user and depositing funds for services...") client.add_user(10000000) # Register on the network client.deposit_inference(LAZAI_IDAO_ADDRESS, 5000000) # Deposit funds ``` This code first checks if you're already a registered user. If not, it registers you and deposits some funds into a special account for paying for inference services. **2. Find a Service Provider (Inference Node)** Now, let's find a shop to buy from. We'll ask our `client` for the web address (URL) of a registered inference node. ```python # Get the URL of a node that provides the service url = client.get_inference_node(LAZAI_IDAO_ADDRESS)[1] print(f"Found an inference node at: {url}") ``` This fetches a list of available providers from the blockchain and gives us the URL for one of them. **3. Get Your Signed "Digital Check" (Settlement Headers)** This is the most important step. We ask our `client` to generate the signed settlement headers for our request. ```python # Create the signed "digital check" for our request headers = client.get_request_headers(LAZAI_IDAO_ADDRESS) print("Generated settlement headers:", headers) ``` **Example Output:** ``` Generated settlement headers: {'X-LazAI-User': '0x...', 'X-LazAI-Node': '0x34d9E...', 'X-LazAI-Nonce': 16, 'X-LazAI-Signature': '0x...'} ``` This dictionary contains your identity (`X-LazAI-User`), the provider's address (`X-LazAI-Node`), a unique number for this request (`X-LazAI-Nonce`), and your unforgeable digital signature (`X-LazAI-Signature`). **4. Create an Agent Pointing to the Remote Node** Now, we create our `Agent`, but instead of letting it use a local model, we tell it to send its requests to the remote node's URL and to include our "digital check" with every request. ```python from alith import Agent agent = Agent( model="Qwen-2.5", # The name of the model on the remote server base_url=f"{url}/v1", # The remote server's API address extra_headers=headers, # Attach our signed "digital check" ) ``` The `base_url` tells the agent *where* to send its thoughts, and the `extra_headers` ensures it gets paid for. **5. Talk to the Remote Agent!** Now, you can use the agent just like before. But this time, the hard work is being done on a powerful remote machine! ```python response = agent.prompt("What is Alith?") print(response) ``` When you run this line, your agent sends the question "What is Alith?" *plus* your signed settlement headers to the remote node. The node verifies your payment guarantee, runs the `Qwen-2.5` model, and streams the answer back to you. ### How It Works Under the Hood The process seems simple from your side, but it involves a beautifully coordinated dance between your script, the remote node, and the blockchain. 1. **You call `agent.prompt()`:** Your script wants an answer. 2. **Agent Prepares Request:** The `Agent` creates a standard web request for the AI model. 3. **Client Attaches Headers:** It automatically includes the `extra_headers` you provided. 4. **Request Sent:** The complete package (prompt + headers) is sent over the internet to the remote inference node. 5. **Node Verifies Signature:** The *first thing* the remote node does is check your `X-LazAI-Signature`. It uses a public function to confirm that the request really came from your wallet address and hasn't been tampered with. It also checks the blockchain to ensure you have enough funds deposited. 6. **Node Does the Work:** If the signature is valid, the node performs the computationally expensive AI inference. 7. **Response Returned:** The AI's answer is sent back to your `Agent`. 8. **Settlement Occurs:** The node now holds your signed "check" (the headers) as proof of work. It can submit this proof to the blockchain at any time to have the funds transferred from your deposit to its own account. Here is a diagram of the flow: ```mermaid sequenceDiagram participant You as Alith Agent participant RemoteNode as Remote Inference Node participant LazChain as LazChain You->>RemoteNode: Sends prompt + signed settlement headers RemoteNode->>LazChain: "Is this signature from this user valid?" LazChain-->>RemoteNode: "Yes, and they have funds." RemoteNode->>RemoteNode: Runs the AI computation RemoteNode-->>You: Returns the final AI-generated answer ``` The code in [`lazai_inference_server.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/examples/lazai_inference_server.py) shows the other side of this transaction. It's a server that listens for requests, and its first step is to check for and validate these exact `X-LazAI-*` headers before it proceeds with any AI computation. file: ./content/docs/hyperion/lazai/proofs.mdx meta: { "title": "Data Contribution & Proofs" } In the previous section, we learned how to be a *consumer* in the LazAI economy, securely using AI models run by others. But a healthy economy needs producers too! What if you have a valuable dataset—like curated medical images, financial records, or specialized texts—that could help train better AI models? How can you contribute it to the network, prove its quality, and get rewarded for your effort? ### Your Data, Verified: The "Peer Review" for AI Datasets Think of contributing data to the LazAI network like submitting a scientific paper to a prestigious journal for peer review. You don't just email your paper to a random person; you follow a structured, verifiable process to build trust. 1. **Write the Paper (Prepare Your Data):** You prepare your dataset. For sensitive information, you might encrypt it to protect privacy. 2. **Submit to a Journal (Publish its Location):** You upload your data to a public storage system (like IPFS) and then register its *location* on LazChain. You are not putting the data itself on the chain, just a pointer to it. 3. **Request Peer Review (Request a Proof):** You ask the network for a "proof," which is like asking the journal to send your paper to expert reviewers. A network "node" (a reviewer) is assigned to verify your data. 4. **Get Published (Receive a Proof):** The node examines your data and, if it meets the criteria, submits a "proof" to LazChain. This is like your paper being officially accepted and published. Your data is now trusted. 5. **Earn Citations (Get Rewarded):** With your data proven and trusted, others can use it, and you can earn rewards for your valuable contribution. Our goal is to walk through this entire "peer review" process to contribute a piece of data to the LazAI network. ### The Contribution Workflow: Step-by-Step Let's follow the journey of a data contributor, referencing the logic found in files like [`lazai_data_contribution_with_reward.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/examples/lazai_data_contribution_with_reward.py). We'll simplify the steps to focus on the core concepts. #### Step 1: Prepare Your Data (and Encrypt It) First, we prepare our data. If it's sensitive, we should encrypt it. LazAI has built-in tools for this. Let's say our valuable data is a secret message. We'll use a password to encrypt it. In a real application, you'd generate this password securely, as shown in the examples. ```python from alith.data import encrypt # This is our valuable, private dataset privacy_data = b"The future of AI is decentralized." # We create a password to lock the data password = "my-secret-password-123" # Encrypt the data, so only someone with the password can read it encrypted_data = encrypt(privacy_data, password) print("Data has been encrypted!") ``` Now our `encrypted_data` is a bundle of scrambled text that is safe to share publicly. We keep the `password` secret. #### Step 2: Put the Data Online and Register It Next, we need to upload our `encrypted_data` to a public storage service like IPFS (InterPlanetary File System). After uploading, we get a unique URL. Then, we use our LazAI Client to register this URL on LazChain. This creates a permanent, public record pointing to our data. ```python from alith.lazai import Client client = Client() # Imagine we uploaded our data and got this URL from IPFS # (This is just a placeholder) url = "ipfs://QmXo9bb4cZJ..." # Register the URL on LazChain file_id = client.add_file(url) print(f"Success! Our file is registered with ID: {file_id}") ``` Our data's existence is now known to the network, but it's not yet trusted or verified. #### Step 3: Request a Proof (The "Peer Review") Now, we ask the network to verify our contribution. We offer a small fee to a "proof node" to do the work. ```python # Offer a small fee for the node's verification service node_fee = 10 # Broadcast a request for a proof to the network client.request_proof(file_id, node_fee) print(f"Proof has been requested for file {file_id}. A node will now review it.") ``` This action creates a "job" on the network that any available proof node can accept. #### Step 4: A Node Verifies and Submits the Proof This step happens on a different machine—the proof node's machine. 1. A node sees our job request on the blockchain. 2. It accepts the job. 3. It downloads the `encrypted_data` from the IPFS URL we provided. 4. It performs verification checks (e.g., checks for viruses, validates format, etc.). If the data is encrypted, we would securely provide the node with the password. 5. If everything looks good, the node submits a "proof" back to the blockchain, confirming the data is valid. This is done by the node calling a function like `node.add_proof()`. #### Step 5: Claim Your Reward Once the proof is on the blockchain, our data is officially "peer-reviewed" and trusted. We can now claim our reward for contributing high-quality data to the ecosystem. ```python # After the node has submitted the proof, we can request our reward client.request_reward(file_id) print(f"Reward requested for our contribution of file {file_id}!") ``` This final transaction rewards us for our work, completing the cycle and incentivizing more high-quality contributions. ### How It Works Under the Hood The process is a coordinated effort between you (the Contributor), LazChain, and a Proof Node. 1. **You Prepare:** You get your data ready, encrypt it, and upload it to a place like IPFS. 2. **You Register:** You call `client.add_file(url)`, which creates a transaction on the blockchain, establishing you as the owner of the data at that URL. 3. **You Request:** You call `client.request_proof(file_id)`, which creates another transaction that announces a "job" is available for nodes. 4. **Node Accepts & Verifies:** A proof node, which is constantly watching the blockchain, sees the job. It accepts it, downloads the data, and performs its verification process. 5. **Node Proves:** After successful verification, the node calls `node.add_proof()`, sending a final transaction to the blockchain that attaches a "verified" stamp to your `file_id`. 6. **You Get Rewarded:** You call `client.request_reward(file_id)` which triggers the reward mechanism in the smart contract. Here is a diagram of the key interactions: ```mermaid sequenceDiagram participant C as Data Contributor participant IPFS as "Storage (IPFS)" participant BC as "LazChain" participant PN as Proof Node C->>IPFS: Uploads encrypted data IPFS-->>C: Returns data URL C->>BC: add_file(URL) BC-->>C: Returns file_id C->>BC: request_proof(file_id) PN-->>BC: Sees and accepts the job PN->>IPFS: Downloads data from URL Note right of PN: Node verifies the data PN->>BC: add_proof(file_id) C->>BC: request_reward(file_id) ``` The example file [`lazai_data_contribution_with_reward.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/examples/lazai_data_contribution_with_reward.py) shows this entire flow in a single, automated script. It handles creating a password from your wallet's signature, uploading to IPFS, and communicating with the node to complete the proof request. file: ./content/docs/hyperion/lazai/tee.mdx meta: { "title": "TEE Integration" } In the previous section, we learned how to contribute data to the LazAI network and have it verified by a "proof node." This system works great, but it relies on us trusting the proof node operator not to misuse our data during verification. What if our data is extremely sensitive, like a user's private key or private medical information? How can we let a node process our data without *ever* revealing it to the node operator? ### The "Secure Black Box" for Computation A Trusted Execution Environment (TEE) is a special, isolated area inside a computer's processor. Think of it as a **secure digital vault** or a **black box**. * Anything that goes inside the box (code and data) is encrypted and protected. * The code running inside the box can work with the unencrypted data. * Crucially, *no one* from the outside can peek inside—not even the owner of the computer, the operating system, or any other program. This technology allows us to send our most private data to a remote machine, have it processed securely inside this "black box," and get a result back, all with a mathematical guarantee that our data was never exposed. Our goal for this chapter is to understand how to use Alith's clients to talk to these TEEs and get a cryptographic "receipt" (an attestation) proving that our application is running securely and untampered inside one. ### What is Attestation? A Digital Notary Stamp How can we trust that a remote computer *really* has a TEE and that it's running the exact code we expect? We need proof. This proof is called an **attestation**. Getting an attestation is like asking the TEE for a notarized statement that says: > "I, a genuine and secure chip, do hereby certify that I am currently running the application with the code measurement `[a unique hash]`, and I have not been tampered with. Signed, The CPU/GPU." This "notary stamp" is a cryptographic signature from the chip manufacturer itself, which is impossible to forge. Alith provides simple clients to request these attestations from different TEE providers like Phala and Marlin. ### Interacting with a Phala TEE The Phala network uses TEEs to enable private computation. Alith's `TappdClient` is our tool for communicating with a Phala TEE application. Let's see how we can get proof that a Phala TEE app is running securely. **1. Import and Create the Client** First, we import the `TappdClient` and create an instance. This client connects to the TEE running on the machine. ```python from alith.tee.phala import TappdClient # Connect to the local Phala TEE service client = TappdClient() ``` This simple line establishes a connection to the secure environment. **2. Get Basic Info from the TEE** We can start by asking the TEE for its basic identity information. This is like asking the black box for its ID card. ```python # Get information about the TEE application info = client.info() print("TEE Application ID:", info.app_id) ``` This tells us which specific application is running inside the secure environment. **3. Request a Signed Attestation (The "Quote")** Now for the most important part: asking for the cryptographic proof. We use the `tdx_quote()` method. We can also include some of our own data (`report_data`) to be included in the signed proof. ```python # Request a signed proof, including some of our own data quote_result = client.tdx_quote(report_data="my-verification-request-123") print("Attestation Quote:", quote_result.quote[:32], "...") ``` **Example Output:** ``` Attestation Quote: 4a8b2f91c3d0e5a67b8c9d0e1f2a3b4c ... ``` This long string of characters is our unforgeable "notary stamp." We can now send this quote to a verification service to confirm that it's a genuine proof from a real TEE running our exact code. ### Interacting with a Marlin TEE The Marlin ecosystem also uses TEEs for its services. The process is very similar, but we use the `MarlinClient`. **1. Import and Create the Client** Just like before, we start by creating a client. ```python from alith.tee.marlin import MarlinClient, AttestationRequest # Initialize a client for the Marlin TEE service client = MarlinClient.default() ``` **2. Prepare and Send an Attestation Request** With Marlin, we package our request into an `AttestationRequest` object. This includes our public key and any other data we want to be part of the proof. ```python # Create a request for attestation request = AttestationRequest( public_key=b"my_public_key", user_data=b"my_other_data", nonce=b"a_random_value_123", ) ``` This bundles all the information we want the TEE to sign. **3. Get the Attestation** Finally, we send the request and get back the attestation result. ```python # Fetch the signed attestation from the TEE result = client.attestation_hex(request) print(f"Attestation result: {result[:32]}...") ``` Again, we receive a cryptographic proof that we can independently verify, confirming the integrity of the remote application. ### How Does It Work Under the Hood? The magic of attestation involves a secure conversation between your script, the application inside the TEE, and the computer's CPU/GPU hardware itself. 1. **You Make a Request:** Your script calls `client.tdx_quote()`. 2. **Challenge is Sent:** The client sends your request (including any `report_data`) to the application running inside the TEE. 3. **TEE Prepares Report:** The TEE application gathers its security measurements (hashes of its code and memory) and combines them with your `report_data`. 4. **CPU/GPU Creates Quote:** The application passes this report to a special, locked-down part of the CPU/GPU. The CPU/GPU signs the report using a secret cryptographic key that was burned into the silicon during manufacturing. This signed report is the "quote." 5. **Quote is Returned:** The quote is sent back out of the TEE and returned to your script. 6. **You Verify:** You can now take this quote and have it verified. The verification process confirms that the signature came from a genuine CPU and that the security measurements match the application you intended to run. Here is a diagram of the simplified flow: ```mermaid sequenceDiagram participant YourScript as "Your Script" participant TEEApp as "App in TEE" participant CPU as "CPU/GPU Hardware" participant Verifier as "Verification Service" YourScript->>TEEApp: "Give me a proof with this data: 'abc'" TEEApp->>CPU: "Please sign my measurements + 'abc'" CPU-->>TEEApp: Returns signed Quote TEEApp-->>YourScript: Returns signed Quote YourScript->>Verifier: "Is this Quote valid?" Verifier-->>YourScript: "Yes, it's from a genuine, secure TEE." ``` The code in [`agent_with_phala_tee.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/examples/agent_with_phala_tee.py) and [`agent_with_marlin_tee.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/examples/agent_with_marlin_tee.py) demonstrates how these client libraries act as the bridge in this process, hiding all the complex cryptographic steps behind simple function calls. file: ./content/docs/hyperion/start/foundry.mdx meta: { "title": "Foundry", "description": "Deploy a Counter Contract using Foundry" } # Deploying a Counter Contract with Foundry This guide will walk you through deploying a counter contract using Foundry, a fast and portable toolkit for Ethereum application development. ## 1. Prerequisites Before you begin, make sure you have: * A code editor (e.g., VS Code) * Git installed * (Optional) MetaMask wallet for deploying to testnets * (Optional) RPC endpoint for deploying to a network ## 2. Install Foundry Open your terminal and run: ```bash curl -L https://foundry.paradigm.xyz | bash ``` This installs foundryup, the Foundry installer. Next, run: ```bash foundryup ``` This will install the Foundry toolchain (forge, cast, anvil, chisel). Check the installation: ```bash forge --version ``` ## 3. Initialize a New Project Create a new directory for your project and initialize Foundry: ```bash forge init Counter cd Counter ``` This creates a project with the following structure: * `src/` - for your smart contracts * `test/` - for Solidity tests * `script/` - for deployment scripts * `lib/` - for dependencies * `foundry.toml` - project configuration file ## 4. Explore the Counter Contract Foundry initializes your project with a Counter contract in `src/Counter.sol`: ```solidity // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; contract Counter { uint256 public number; function setNumber(uint256 newNumber) public { number = newNumber; } function increment() public { number++; } } ``` This contract stores a number and allows you to set or increment it. ## 5. Compile the Contract Compile your smart contracts with: ```bash forge build ``` This command compiles all contracts in `src/` and outputs artifacts to the `out/` directory. ## 6. Run Tests Foundry supports writing tests in Solidity (in the `test/` directory). To run all tests: ```bash forge test ``` You'll see output indicating which tests passed or failed. The default project includes a sample test for the Counter contract. ## 7. Deploying Your Contract To deploy your contract to a Hyperion testnet , you'll need: * An RPC URL * A private key with testnet ETH For Hyperion testnet, use these details: | Parameter | Value | | --------------- | -------------------------------------------------------------------------------------------------------- | | Chain ID | 133717 | | Currency Symbol | tMETIS | | RPC URL | [https://hyperion-testnet.metisdevops.link](https://hyperion-testnet.metisdevops.link) | | Block Explorer | [https://hyperion-testnet-explorer.metisdevops.link](https://hyperion-testnet-explorer.metisdevops.link) | | Faucet | [Telegram Bot](https://t.me/hyperion_testnet_bot), [Website](https://hype-faucet.metis.io) | Example deployment command for Hyperion testnet: ```bash forge create --rpc-url https://hyperion-testnet.metisdevops.link \ --private-key \ src/Counter.sol:Counter \ --broadcast ``` Replace `` with your actual private key. Never share your private key. ## 8. Interacting with Contracts You can use cast to interact with deployed contracts, send transactions, or query data. For example, to read the number variable on Hyperion testnet: ```bash cast call "number()(uint256)" --rpc-url https://hyperion-testnet.metisdevops.link ``` ## Next Steps * Add more complex functionality to your counter contract * Implement events for better tracking * Add access control mechanisms * Set up continuous integration * Add more comprehensive tests file: ./content/docs/hyperion/start/hardhat.mdx meta: { "title": "Hardhat", "description": "Deploy a Counter Contract using Hardhat" } # Deploying a Counter Contract with Hardhat This guide will walk you through deploying a counter contract using Hardhat, a popular JavaScript-based development environment for Ethereum. ## 1. Prerequisites Before you begin, ensure you have: * Node.js installed (v12 or later) * npm (comes with Node.js) * A code editor (e.g., VS Code) * (Optional) MetaMask wallet and testnet tokens for deployment ## 2. Install Hardhat Open your terminal and create a new project directory: ```bash mkdir counter-project cd counter-project ``` Initialize a new npm project: ```bash npm init -y ``` Install Hardhat and required dependencies: ```bash npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox dotenv ``` ```bash npm install --save-dev @nomicfoundation/hardhat-ignition ``` ## 3. Create a New Hardhat Project Run the Hardhat setup wizard: ```bash npx hardhat init ``` Choose "Create a JavaScript project" when prompted. This will create a project structure like: * `contracts/` - for Solidity contracts * `igntion/` - for deployment scripts * `test/` - for tests * `hardhat.config.js` - configuration file ## 4. Write Your Smart Contract Create a new file in the contracts directory, `Counter.sol`: ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Counter { uint256 private count; function increment() public { count += 1; } function decrement() public { count -= 1; } function getCount() public view returns (uint256) { return count; } } ``` ## 5. Compile the Smart Contract Compile your contracts with: ```bash npx hardhat compile ``` You should see a success message if there are no errors. ## 6. Write a Deployment Script Create a new file in the ignition directory, `Counter.js`: ```javascript const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); module.exports = buildModule("CounterModule", (m) => { const counter = m.contract("Counter"); return { counter }; }); ``` ## 7. Configure Network Settings Create a `.env` file in your project root: ```bash PRIVATE_KEY=your_private_key_here ``` Edit `hardhat.config.js`: ```javascript require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); module.exports = { solidity: "0.8.28", networks: { hardhat: { chainId: 31337, }, hyperion: { url: "https://hyperion-testnet.metisdevops.link", chainId: 133717, accounts: [process.env.PRIVATE_KEY], }, }, }; ``` For Hyperion testnet, use these details: | Parameter | Value | | --------------- | -------------------------------------------------------------------------------------------------------- | | Chain ID | 133717 | | Currency Symbol | tMETIS | | RPC URL | [https://hyperion-testnet.metisdevops.link](https://hyperion-testnet.metisdevops.link) | | Block Explorer | [https://hyperion-testnet-explorer.metisdevops.link](https://hyperion-testnet-explorer.metisdevops.link) | | Faucet | [Telegram Bot](https://t.me/hyperion_testnet_bot), [Website](https://hype-faucet.metis.io) | ## 8. Deploy Your Contract ### Local Deployment (Optional) Start the Hardhat local node in a separate terminal: ```bash npx hardhat node ``` Deploy to local network: ```bash npx hardhat ignition deploy ignition/modules/Counter.js --network localhost ``` ### Deploy to Hyperion Testnet Make sure to: 1. Get testnet tokens from the faucet 2. Add your private key to the `.env` file 3. Never share your private key Deploy to Hyperion: ````bash npx hardhat ignition deploy ignition/modules/Counter.js --network hyperion ``` ## Testing ### Test Setup Create `test/Counter.js`: ```javascript const { expect } = require("chai"); describe("Counter", function () { it("Should increment the counter", async function () { const Counter = await ethers.getContractFactory("Counter"); const counter = await Counter.deploy(); await counter.deployed(); await counter.increment(); expect(await counter.getCount()).to.equal(1); }); }); ```` ### Running Tests ```bash npx hardhat test ``` ## Next Steps * Add more complex functionality to your counter contract * Implement events for better tracking * Add access control mechanisms * Set up continuous integration * Add more comprehensive tests file: ./content/docs/hyperion/start/index.mdx meta: { "title": "Testnet Faucet", "description": "Learn how to get test tokens from the Hyperion faucet" } import { Step, Steps } from "fumadocs-ui/components/steps"; ## Steps to Get Testnet Tokens Visit the Hyperion Faucet at [https://t.me/hyperion\_testnet\_bot](https://t.me/hyperion_testnet_bot) Send the following command: ```bash /start 0xyour_address ``` Replace `0xyour_address` with your actual wallet address. The bot will send you 0.01 tMETIS tokens to your wallet. ## Important Notes * You can request tokens once every 24 hours * Make sure you're using the correct network (Hyperion Testnet) in your wallet * Tokens are usually delivered within 30 seconds file: ./content/docs/andromeda/dapp/benefits/builder-mining.mdx meta: { "title": "Builder Mining Reward" } ## Overview The Metis Builder Mining Rewards (BMR) program is a retroactive funding initiative designed to incentivize and reward Web3 builders within the Metis ecosystem. The program allocates 10,000 $METIS tokens monthly to ecosystem partners developing on the Metis Layer 2 platform. ## Monthly Token Allocation ### Trading Volume Reward (4,000 $METIS) * Allocated based on project trading volume * Distribution calculated block-by-block * Rewards formula: ```math \text{Project Allocation} = \frac{\text{Project Smart Contract Transactions}}{\sum \text{Smart Contract Transactions (All Projects)}} ``` ### Special Initiatives (6,000 $METIS) Dedicated to supporting builders through: * Verifier rewards * Staking rewards * Special grants * Cold launch assistance * Milestone events ## Program Details ### Block Calculation * Rewards are calculated per block * Monthly block count determines total reward distribution * Upper limit: 4,000 $METIS for trading volume rewards * Program adjustments planned when monthly blocks exceed 4,000,000 ### Special Initiative Support * Minimum target: 3 projects per month * Unused tokens roll over to the following month * Project selection involves: * Direct ecosystem project applications * Recommendations from existing Metis projects * Community voting through Snapshot.org partnership ## Eligibility and Participation Projects must be deployed on the Metis Layer 2 platform and [register their contracts](https://docs.google.com/forms/d/e/1FAIpQLScqqysYuk51nuF5nxE2jxXKUK41vEtncEkH4kAyoLP7BlkK5w/viewform) to participate in the BMR program. The program is designed to support various Web3 sectors, including: * DeFi * ReFi * NFTs * DAOs * GameFi ## Program Objectives 1. Recognize and reward builder contributions 2. Foster ecosystem growth and innovation 3. Provide sustainable support for project development 4. Create opportunities for blockchain technology advancement 5. Drive community engagement and participation For more information or to apply for the program, projects should contact the Metis ecosystem team directly. file: ./content/docs/andromeda/dapp/benefits/index.mdx meta: { "title": "Benefits" } import { Card, Cards } from "fumadocs-ui/components/card"; import { Coins, Gift, Shield } from "lucide-react"; The Metis ecosystem offers several key benefits for builders: }> Earn rewards by deploying and maintaining active dApps on Metis } external> Apply for funding to build innovative projects on the Metis ecosystem } external> Get your project verified by the community and increase user trust ### Builder Mining Rewards (BMR) * Monthly allocation of 10,000 $METIS tokens * 4,000 $METIS for trading volume-based rewards * 6,000 $METIS for special initiatives (verifier rewards, staking, grants, etc.) ### Ecosystem Development Fund (MetisEDF) * 4.6M METIS total allocation * 3M METIS for sequencer mining * 1.6M METIS for ecosystem grants over 10 years ### Grant Programs * **Pioneer**: $100K+ for proven projects ready to scale * **Navigator**: $50K+ for projects expanding to Metis * **Voyager**: Up to $50K for proven MVPs * **Explorer**: Up to $20K for early-stage projects * Special programs: GameFi Accelerator and Metis Accelerate Program ### Community Verified Projects (CVP) Program The CVP program is a unique community-driven verification system that offers multiple benefits: #### Verification Process * Projects undergo community review through the CEG (Community Ecosystem Governance) * Transparent evaluation process with community participation * Successful projects receive official "Community Verified" status #### Benefits * Enhanced visibility within the Metis ecosystem * Increased credibility and trust from users * Direct engagement with the Metis community * Amplified social media presence and community discussions #### Support Package * Marketing assistance and promotional opportunities * Community engagement initiatives * Integration with Metis ecosystem partners * Access to networking events and collaborations #### Success Metrics * Projects show increased user adoption after verification * Higher community engagement rates * Stronger ecosystem integration * Better positioning for additional Metis benefits and programs file: ./content/docs/andromeda/dapp/infra/aa.mdx meta: { "title": "Account Abstraction" } import { Card, Cards } from "fumadocs-ui/components/card"; import { SeparatorVertical, Scan, Shield } from "lucide-react"; Account abstraction (AA) is a paradigm shift in blockchain user experience and security. Instead of relying on externally owned accounts (EOAs) with private keys, AA enables smart contract wallets to act as user accounts. This unlocks advanced functionality, such as: * Gasless transactions (sponsored by dApps or third parties) * Social recovery and multi-signature security * Session keys and programmable permissions * Batched transactions and automation With AA, users can interact with dApps seamlessly, even if they don't hold native tokens, and developers can build more secure and flexible onboarding flows. ## How Account Abstraction Works Account abstraction is typically implemented using smart contract wallets that conform to standards like ERC-4337. Key components include: * **Smart Contract Wallets:** User accounts implemented as contracts (e.g., Safe, ZeroDev, Biconomy, Thirdweb) * **Bundlers:** Aggregate and submit user operations to the network * **Paymasters:** Sponsor transaction fees, enabling gasless UX * **Gelato Functions:** On Metis, Gelato provides automation and secure execution for AA operations ## Benefits for dApps and Users * **Enhanced Security:** Social recovery, multi-sig, and custom logic protect users from key loss or theft * **Better UX:** Gasless onboarding, batched actions, and flexible permissions * **Programmability:** Developers can define custom rules for account management and transaction approval ## Account Abstraction on Metis Metis supports AA via Gelato Functions and compatible wallet providers. This enables: * Gasless transactions and fee abstraction * Automated contract execution and relaying * Integration with leading AA SDKs and APIs ## Providers } /> } /> } /> ## Best Practices for Integrating AA * Use audited smart contract wallet implementations (e.g. Thirdweb, Gelato, Metis Safe) * Clearly communicate security features (e.g., recovery, multi-sig) to users * Test gasless flows and fallback mechanisms * Monitor for compatibility with wallets and dApp browsers ## How to Get Started 1. **Choose a Provider:** Select a smart contract wallet or SDK (e.g., Thirdweb, Gelato, Metis Safe) 2. **Integrate SDK:** Follow provider docs to add AA wallet support to your dApp 3. **Enable Gasless Transactions:** Set up a paymaster or relayer (e.g., via Gelato) 4. **Test User Flows:** Ensure onboarding, recovery, and transaction signing are seamless file: ./content/docs/andromeda/dapp/infra/analytics.mdx meta: { "title": "Analytics" } import { Card, Cards } from "fumadocs-ui/components/card"; import { LineChart, Search, PieChart } from "lucide-react"; Data and analytics are essential for tracking your project's growth, understanding user behavior, and making data-driven decisions. For dApps on Andromeda/Metis, leveraging analytics can help you: * Monitor on-chain activity (transactions, TVL, user growth) * Track protocol health and adoption * Identify trends and optimize features * Demonstrate traction to the community and investors ## Types of Analytics * **On-chain Analytics:** Track blockchain metrics such as transaction volume, active addresses, TVL, and contract interactions. * **Custom/Event Analytics:** Instrument your dApp to log custom events (e.g., swaps, mints, votes) for deeper insights. ## Providers } /> } /> } /> ### Provider Overviews * **DefiLlama:** * Track total value locked (TVL), protocol rankings, and DeFi metrics for Metis. * Great for DeFi projects and ecosystem overviews. * **Routescan Explorer:** * Explore on-chain data, transaction charts, and contract analytics. * Useful for tracking network activity and smart contract usage. * **GrowThePie:** * Visualizes ecosystem growth, user retention, and protocol comparisons. * Good for understanding broader trends and user flows. ## Best Practices for dApp Analytics * **Define Key Metrics:** Decide what matters (e.g., DAUs, TVL, retention, conversion rates). * **Automate Data Collection:** Use APIs or event logging to gather data in real time. * **Visualize Results:** Build dashboards or use provider tools to share insights with your team/community. * **Respect Privacy:** Be transparent about data collection and comply with relevant regulations. ## How to Get Started 1. **Pick a Provider:** Start with DefiLlama or Routescan for high-level metrics. 2. **Integrate Analytics:** For custom tracking, consider event logging in your dApp frontend/backend. 3. **Explore APIs:** Most providers offer APIs for programmatic access to data. 4. **Build Dashboards:** Use Grafana to build dashboards for your dApp. file: ./content/docs/andromeda/dapp/infra/automation.mdx meta: { "title": "Automation" } import { Card, Cards } from "fumadocs-ui/components/card"; import { Parentheses } from "lucide-react"; Blockchain automation services enable smart contracts to execute functions automatically without requiring manual intervention. These services solve a fundamental limitation of blockchain networks: smart contracts can only execute when triggered by an external transaction, but many applications need functions to run automatically based on time intervals or specific conditions. ## Providers }> Gelato provides a more flexible automation framework where developers can create custom execution logic using JavaScript-like functions. ## How They Work These automation networks operate through decentralized networks of nodes that monitor smart contracts and execute predefined functions when certain conditions are met. The process typically involves: 1. **Job Registration**: Developers register their smart contracts with the automation service, specifying trigger conditions and the functions to execute 2. **Monitoring**: Nodes continuously monitor registered contracts for trigger conditions 3. **Execution**: When conditions are met, nodes submit transactions to execute the specified functions 4. **Compensation**: Node operators receive payment in network tokens for their services ## Common Use Cases Automation enable applications like automated yield harvesting in DeFi protocols, dynamic NFT updates, insurance claim processing, subscription payments, liquidations in lending protocols, and gaming mechanics that require regular state updates. They're essential infrastructure for creating autonomous, self-executing blockchain applications that don't require constant manual oversight. file: ./content/docs/andromeda/dapp/infra/monitoring.mdx meta: { "title": "Monitoring" } import { Card, Cards } from "fumadocs-ui/components/card"; import { TriangleAlert, Clapperboard } from "lucide-react"; Monitoring is critical for maintaining the reliability, security, and performance of your dApp. Effective monitoring allows you to detect issues early, respond to incidents quickly, and ensure a seamless experience for your users. It also helps with compliance and auditing, which are increasingly important in the blockchain space. ## Types of Monitoring * **Transaction Monitoring:** Track on-chain transactions, failed/successful calls, and gas usage. * **Smart Contract Monitoring:** Watch for specific contract events, anomalies, or upgrades. * **Infrastructure Monitoring:** Ensure your RPC nodes, APIs, and backend services are healthy and performant. * **User Activity Monitoring:** Analyze user flows, wallet connections, and interaction patterns. ## Providers } /> } /> ### Provider Overviews * **Tenderly Alerts:** Real-time notifications for on-chain events, errors, and custom triggers. Integrates with Slack, email, and webhooks. * **Tenderly Web3 Actions:** Automated workflows that react to blockchain events, enabling auto-responses and integrations. ## Best Practices for dApp Monitoring * **Set Up Alerts:** Define thresholds and triggers for critical events (e.g., contract upgrades, large transfers, failed transactions). * **Automate Incident Response:** Use Web3 Actions or Defender Autotasks to automate responses to incidents. * **Visualize Metrics:** Build dashboards (e.g., with Grafana or Tenderly) for real-time and historical monitoring. * **Log Everything:** Maintain logs for all critical actions and events for auditing and debugging. * **Test Regularly:** Simulate incidents to ensure your monitoring and alerting are functioning as expected. ## How to Get Started 1. **Choose Monitoring Tools:** Start with Tenderly for smart contract monitoring. 2. **Integrate Alerts:** Connect to Slack, email, or other channels for real-time notifications. 3. **Automate Actions:** Use Web3 Actions, Defender Autotasks, or custom scripts to automate responses. 4. **Build Dashboards:** Visualize key metrics and events for your team. 5. **Review and Iterate:** Regularly review your monitoring setup and improve based on new risks or requirements. file: ./content/docs/andromeda/dapp/infra/oracles.mdx meta: { "title": "Oracles" } **Oracles** are critical infrastructure for blockchain applications, acting as bridges between smart contracts and the outside world. They enable dApps to access real-world data—such as asset prices, weather, sports results, or random numbers—so that contracts can execute logic based on external events. Without oracles, blockchains would be isolated and unable to react to changes beyond their own network. Oracles are widely used in DeFi (for price feeds and liquidations), insurance (for weather or event triggers), gaming (for randomness), and many other use cases. ## Why Oracles Matter * **Automation:** Enable smart contracts to respond to real-world events * **DeFi:** Secure price feeds are essential for lending, trading, and derivatives * **Randomness:** Fair gaming, lotteries, and NFT reveals require verifiable randomness * **Custom Data:** Access APIs for weather, sports, IoT, and more ## Types of Oracles * **Price Feeds:** Deliver up-to-date asset prices (e.g., ETH/USD) * **Data Feeds:** Provide other off-chain data (e.g., weather, sports, news) * **Randomness Oracles:** Supply verifiable random numbers * **Custom/API Oracles:** Fetch data from any external API ## How Oracles Work Oracles can be implemented in different ways: * **On-chain vs. Off-chain:** Some oracles run as smart contracts, others as off-chain services that push data on-chain. * **Push vs. Pull:** Data can be pushed to the blockchain at regular intervals, or pulled by contracts on demand. * **Aggregation:** Leading oracles aggregate data from multiple sources to reduce manipulation risk. * **Security:** Decentralized oracles use multiple nodes, cryptographic proofs, and monitoring to ensure data integrity and reliability. ## Supported Oracle Providers on Metis Metis partners with several leading oracle providers, each offering unique features: | Name | Type | | | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | [Chainlink](https://chain.link) | [Price Feed](https://docs.chain.link/data-feeds/price-feeds/addresses?network=metis) | | | [API3](https://api3.org) | [Price Feed](https://market-catalog.api3.org/?chain=metis) | [Example](https://github.com/metis-edu/Community-contributions/tree/main/API3/api3-dapi-workshop) | | [DIA](https://diadata.org) | [Price Feed](https://docs.diadata.org/use-nexus-product/readme/token-price-feeds/access-the-oracle) | | | [Witnet](https://witnet.io) | [Price Feed](https://docs.witnet.io/smart-contracts/supported-chains), [Randomness](https://docs.witnet.io/smart-contracts/supported-chains) | | | [Gelato](https://gelato.network) | [Randomness](https://docs.gelato.cloud/web3-services/vrf) | [Example](https://docs.gelato.cloud/web3-services/vrf/quick-start) | | [Supra](https://docs.supra.com/oracles) | [Price Feed](https://docs.supra.com/oracles/data-feeds), [Randomness](https://docs.supra.com/oracles/dvrf-verifiable-randomness) | | ### Provider Overviews * **Chainlink:** The most widely used decentralized oracle network. Aggregates data from many sources and nodes, providing highly secure and reliable price feeds. Also supports VRF (verifiable randomness) and custom data feeds. * **API3:** Decentralized APIs (dAPIs) with first-party oracles operated by data providers themselves. Supports price feeds and custom data, with transparent governance and on-chain insurance. * **DIA:** Open-source oracles focused on transparency and customization. Data is sourced from both on-chain and off-chain sources, with flexible feed creation. * **Witnet:** Decentralized oracle network specialized in both price feeds and randomness. Provides verifiable randomness for gaming and NFTs, as well as secure data feeds. * **Gelato:** Provides verifiable randomness using VRFs (Verifiable Random Functions). * **Supra:** Decentralized, high-performance oracle infrastructure delivering reliable, low-latency data feeds and verifiable randomness. Offers both push and pull oracle models with real-time and historical data APIs, designed for speed and security. ## Best Practices for Using Oracles * **Use Multiple Oracles:** For critical applications, aggregate data from more than one provider to reduce risk. * **Monitor Feeds:** Set up alerts for stale or abnormal data. * **Validate Data:** Check timestamps, values, and source signatures. * **Plan for Fallbacks:** Have backup feeds or manual intervention for outages. * **Stay Updated:** Monitor provider documentation for new feeds and breaking changes. ## How to Get Started 1. **Choose a Provider:** Review the available oracles and select the one that fits your data and security needs. 2. **Integrate the Feed:** Use the provider's documentation to read data from the oracle contract in your smart contract. 3. **Test Thoroughly:** Simulate edge cases (stale data, outages, extreme values) in your testnet deployments. 4. **Monitor in Production:** Set up monitoring for data freshness and anomalies. file: ./content/docs/andromeda/dapp/infra/rpcs.mdx meta: { "title": "RPCs" } import { Card, Cards } from "fumadocs-ui/components/card"; import { Server, Container, Cloud, Zap, Network, Bolt, Workflow, Sparkle, } from "lucide-react"; ## What Are RPCs? **Remote Procedure Call (RPC) endpoints** are the backbone of blockchain connectivity. They allow wallets, dApps, indexers, and backend services to communicate with the Metis network—sending transactions, reading on-chain data, and subscribing to events. Every interaction with the blockchain (outside of running your own node) relies on RPC endpoints. | | Andromeda (Mainnet) | Sepolia (Testnet) | | --------------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | RPCs | [https://chainlist.org/chain/1088](https://chainlist.org/chain/1088) | [https://chainlist.org/chain/59902](https://chainlist.org/chain/59902) | | Chain ID | 1088 | 59902 | | Currency Symbol | METIS | sMETIS | | Block Explorer | [Routescan](https://explorer.metis.io), [Blockscout](https://andromeda-explorer.metis.io) | [Blockscout](https://sepolia-explorer.metisdevops.link/) | ## Types of RPC Endpoints * **Public RPCs:** Free and easy to use, but subject to rate limits and congestion. Best for development, testing, and light usage. * **Private RPC Providers:** Offer higher throughput, reliability, and support. Ideal for production dApps, bots, and high-traffic services. * **Self-Hosted Nodes:** Maximum control, privacy, and reliability. Recommended for enterprise, indexers, or when handling sensitive data. ## Common Use Cases * **Frontend dApps:** Connect wallets and user interfaces to the Metis blockchain. * **Backend Services:** Power bots, relayers, analytics, and automation. * **Indexers & Analytics:** Aggregate and process on-chain data at scale. * **Monitoring:** Track contract events, network health, and infrastructure status. ## Key Considerations * **Rate Limits:** Public endpoints may throttle requests. Use private or self-hosted solutions for higher limits. * **Latency:** Choose geographically close endpoints to reduce response times. * **Reliability:** Monitor for downtime and have fallback endpoints. * **Security:** Never expose private keys to RPC endpoints you don't control. Use HTTPS and restrict access as needed. * **Compatibility:** Ensure the endpoint supports all required methods (e.g., websockets for subscriptions). All public RPCs are rate limited. If you need higher rate limits, consider the following options: ## Self-Hosted } /> } /> ## Private RPC Providers } external /> } external /> } external /> } external /> } external /> } external /> ## Best Practices for Using RPCs * **Use Multiple Endpoints:** Implement fallback logic to switch endpoints if one fails. * **Monitor Health:** Regularly check latency and uptime of your RPC providers. * **Cache Responses:** For frequently-read data, cache results to reduce load and latency. * **Secure Sensitive Operations:** Only sign transactions on endpoints you trust or control. * **Stay Updated:** Watch for network upgrades or endpoint deprecations from your provider. ## How to Get Started 1. **Choose an Endpoint:** Use public endpoints for development, private or self-hosted for production. 2. **Integrate in Your dApp:** Configure your web3 provider (ethers.js, web3.js, etc.) with the RPC URL. 3. **Test Thoroughly:** Simulate high load and failover scenarios in staging. 4. **Monitor and Iterate:** Continuously monitor performance and update endpoints as needed. ## Example: Switching RPC Endpoints in ethers.js ```js import { ethers } from "ethers"; const endpoints = [ "https://andromeda.metis.io/?owner=1088", "https://metis-mainnet.public.blastapi.io", // Add more as needed ]; let provider; for (const url of endpoints) { try { provider = new ethers.JsonRpcProvider(url); await provider.getBlockNumber(); // Test connectivity break; } catch (e) { // Try next endpoint } } if (!provider) throw new Error("No healthy RPC endpoints available"); ``` file: ./content/docs/andromeda/dapp/start/environment.mdx meta: { "title": "Environment" } Before you begin deploying smart contracts on Metis, you need to ensure that your development environment is properly configured. import { Step, Steps } from "fumadocs-ui/components/steps"; import { Card, Cards } from "fumadocs-ui/components/card"; import { Droplet } from "lucide-react"; ### Install a Wallet * [Rabby](https://rabby.io) * [MetaMask](https://metamask.io) ### Add The Metis Network to Your Wallet To connect to the **Metis Andromeda (Mainnet)** or **Metis Sepolia (Testnet)** network, you can use the cards below. ### Get Testnet Tokens (Metis Sepolia) If you are developing on the Metis Sepolia Testnet, you will need **sMETIS** tokens to test your transactions and smart contracts. You can get free testnet tokens by visiting the official Metis Sepolia Testnet Faucet. } title="Metis Sepolia Testnet Faucet" href="https://faucet.metis.io" external /> file: ./content/docs/andromeda/dapp/start/tutorials.mdx meta: { "title": "Tutorials" } import { Card, Cards } from "fumadocs-ui/components/card"; To help you refine your skills, this section offers a set of tutorials ranging from beginner to advanced topics. The tutorials will provide hands-on experience with Metis smart contract deployment, gas optimization, and cross-chain operations. Learn how to deploy your very first smart contract on the **Metis Andromeda** network. This step-by-step guide will walk you through writing a simple Solidity contract, compiling it, and deploying it to the Metis testnet using tools like **Remix** or **Hardhat**. One of Metis’s main advantages is low gas fees. In this tutorial, you will explore techniques for optimizing gas usage in your smart contracts, ensuring that your dApp is both efficient and cost-effective on the Metis network. file: ./content/docs/andromeda/network/contracts/predeploys.mdx meta: { "title": "Predeploys" } The Metis protocol consists of several contracts that are deployed on some specific addresses. The contracts have been deployed on L2, L1, Andromeda, and Metis Sepolia testnet. The [Metis Github page](https://github.com/MetisProtocol/mvm/tree/develop/packages/contracts/deployments) shows all the core predeployed contracts addresses. | **Network** | **Andromeda (Mainnet)** | | ------------------------------------------------------- | ------------------------------------------ | | BondManager[^1] | 0x595801b85628ec6979C420988b8843A40F850528 | | CanonicalTransactionChain[^2] | 0x56a76bcC92361f6DF8D75476feD8843EdC70e1C9 | | ChainStorageContainer-CTC-batches[^3] | 0x38473Feb3A6366757A249dB2cA4fBB2C663416B7 | | ChainStorageContainer-CTC-queue[^4] | 0xA91Ea6F5d1EDA8e6686639d6C88b309cF35D2E57 | | ChainStorageContainer-SCC-batches[^5] | 0x10739F09f6e62689c0aA8A1878816de9e166d6f9 | | L1StandardBridge\_for\_verification\_only[^6] | 0x101500214981e7A5Ad2334D8404eaF365C2c3113 | | Lib\_AddressManager[^7] | 0x918778e825747a892b17C66fe7D24C618262867d | | MVM\_CanonicalTransaction\_for\_verification\_only[^8] | 0x431e877E216714647a4DCcEFFC03d7B4Fd4B825E | | MVM\_DiscountOracle[^9] | 0xC8953ca384b4AdC8B1b11B030Afe2F05471664b0 | | MVM\_L2ChainManagerOnL1\_for\_verification\_only[^10] | 0x9E2E3be85df5Ca63DE7674BA64ffD564075f3B48 | | MVM\_StateCommitmentChain\_for\_verification\_only[^11] | 0x4549292213D41CB62E94e7E2DDC4b468a4CDD16d | | MVM\_Verifier[^12] | 0x9Ed4739afd706122591E75F215208ecF522C0Fd3 | | MVM\_Verifier\_for\_verification\_only[^13] | 0xB2e2060A179e67cA4299Cc79fA337B98791DE069 | | OVM\_L1CrossDomainMessenger[^14] | 0x8bF439ef7167023F009E24b21719Ca5f768Ecb36 | | Proxy\_\_MVM\_CanonicalTransaction | 0x6A1DB7d799FBA381F2a518cA859ED30cB8E1d41a | | Proxy\_\_MVM\_ChainManager | 0xf3d58D1794f2634d6649a978f2dc093898FEEBc0 | | Proxy\_\_MVM\_StateCommitmentChain | 0xA2FaAAC9120c1Ff75814F0c6DdB119496a12eEA6 | | Proxy\_\_MVM\_Verifier | 0xe70DD4dE81D282B3fa92A6700FEE8339d2d9b5cb | | Proxy\_\_OVM\_L1CrossDomainMessenger | 0x081D1101855bD523bA69A9794e0217F0DB6323ff | | Proxy\_\_OVM\_L1StandardBridge | 0x3980c9ed79d2c191A89E02Fa3529C60eD6e9c04b | | StateCommitmentChain[^15] | 0xf209815E595Cdf3ed0aAF9665b1772e608AB9380 | [^1]: **BondManager** is a component responsible for managing and maintaining bonds or collateral deposits that are used to secure the network. [^2]: The **CanonicalTransactionChain** is essentially the ordered list of transactions that have been submitted to the Layer 2 chain. It serves as the official record of all transactions that have been processed and included in the chain. [^3]: The **ChainStorageContainer-CTC-batches** is a data structure that holds batches of transactions which are part of the CanonicalTransactionChain in Layer 2 solutions like Optimistic Rollups. [^4]: The **ChainStorageContainer-CTC-queue** is a data structure designed to manage and temporarily store transactions that are waiting to be included in the next batch of the CanonicalTransactionChain (CTC). [^5]: The **ChainStorageContainer-SCC-batches** is a data structure that holds batches of state commitments within a state commitment chain (SCC). These commitments represent the state of the Layer 2 chain at various points in time. [^6]: The **L1StandardBridge** is a smart contract deployed on Layer 1 (Ethereum mainnet) that handles the transfer of assets (such as ETH and ERC20 tokens) and messages between Layer 1 and Layer 2. The "**for verification only**" aspect indicates that this bridge is also responsible for verifying the correctness of state transitions and transactions that occur on Layer 2. [^7]: The **Lib\_AddressManager** is a smart contract utility that serves as a registry for storing and managing addresses of key contracts and components in a Layer 2 solution. This central address management helps ensure that all components can easily locate and interact with each other. [^8]: The **MVM\_CanonicalTransaction\_for\_verification\_only** is a specialized component or function designed to handle the verification of transactions within a CanonicalTransactionChain. This component ensures that transactions are valid and adhere to the rules and protocols established by the Layer 2 (L2) solution. [^9]: The **MVM\_DiscountOracle** is a service or smart contract that provides information about discounts or reduced transaction fees within the MetaMask Virtual Machine (MVM) or another blockchain-based ecosystem. This oracle supplies data that can be used to adjust the cost of operations dynamically. [^10]: The **MVM\_L2ChainManagerOnL1\_for\_verification\_only** is a smart contract or a set of smart contracts on the Ethereum mainnet (Layer 1) that manages and verifies the state and transactions of the Layer 2 chain. This component is focused solely on verification tasks to ensure the integrity and correctness of the L2 chain from the L1 perspective. [^11]: The **MVM\_StateCommitmentChain\_for\_verification\_only** is a specialized module or smart contract that manages and verifies state commitments on the Metis Layer 2 (L2) chain. It is responsible for recording cryptographic commitments to the state of the L2 chain and ensuring these commitments are valid and secure. [^12]: The **MVM\_Verifier** is a smart contract or a module within the Metis Virtual Machine (MVM) dedicated to verifying the accuracy and integrity of transactions, state transitions, and other operations within the Layer 2 (L2) chain. [^13]: The **MVM\_Verifier\_for\_verification\_only** is a component within the Metis Virtual Machine that exclusively handles the verification of transactions and state transitions. Its purpose is to ensure the validity and integrity of these operations, playing a crucial role in the security and reliability of the Metis Layer 2 chain. [^14]: The **OVM\_L1CrossDomainMessenger** is a smart contract deployed on the Ethereum mainnet (L1) that handles the sending and receiving of messages between Layer 1 and Layer 2. This component is essential for enabling cross-domain interactions, allowing contracts and users on L1 to communicate with contracts and users on L2. [^15]: The **SCC contract** is a smart contract deployed on the L1 blockchain that records and manages cryptographic commitments to the state of the L2 chain. It plays a vital role in anchoring the L2 state to L1, ensuring security and verifiability. file: ./content/docs/andromeda/network/contracts/preinstalls.mdx meta: { "title": "Preinstalls" } The Metis protocol consists of several contracts that are deployed on some specific addresses. The contracts have been deployed on L2, L1, Andromeda, and Stardust testnet. You can use the etherscan explorer to see full details about deployed contract addresses. The [Metis Github page](https://github.com/MetisProtocol/mvm/tree/develop/packages/contracts/deployments) shows all the deployed contract addresses. | **Network** | **Andromeda (Mainnet)** | **Metis Sepolia (Testnet)** | | ----------- | ------------------------------------------ | ------------------------------------------ | | Safe | 0xd9Db270c1B5E3Bd161E8c8503c55cEABeE709552 | N/A | | Multisend | 0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761 | 0x38869bf66a61cF6bDB996A6aE40D5853Fd43B526 | | Multicall2 | 0x98FE5034f2eE6bE044CDbD857744C63Ad06532Ed | 0x98FE5034f2eE6bE044CDbD857744C63Ad06532Ed | | Multicall3 | 0xcA11bde05977b3631167028862bE2a173976CA11 | 0xcA11bde05977b3631167028862bE2a173976CA11 | | Permit2 | 0xb1F795776cB9DdAC6E7e162f31C7419Dd3d48297 | 0x1Ac569879EF7EacB17CC373EF801cDcE4acCdeD5 | | Create2 | 0x13b0D85CcB8bf860b6b79AF3029fCA081AE9beF2 | 0x13b0D85CcB8bf860b6b79AF3029fCA081AE9beF2 | | Create3 | 0x6Bf49Dec20Ef49513948Efa1e7073523E0EA222B | 0x95eF67E50247C2aC9Ef5857Cf0a207F71bd5393D | file: ./content/docs/andromeda/sequencer/architecture/bridge.mdx meta: { "title": "Bridge Module" } The connection between Consensus layer (PoS) and Sequencer (Metis node). It has 2 functions: 1. Processor: * Sends the transactions to TSS/Themis for consensus according to Listener * Scans epoch and Metis blocks information * If the block is wrong, submits `reProposeSpan` messages to Themis * Scans the MPC service interface and sends the transaction batches to the consensus layer for MPC signing 2. Listener * Monitors the L1 Locking contract events and obtains the info about Sequencer node list (`join` / `exit` / `update`) * Listens to Metis block events to determine whether to send tasks (It means that when the listener listens to the block events of Themis or Ethereum, it determines whether it needs to notify the Processor to perform some task processing. For example, whether it needs to enter the MPC signature process) file: ./content/docs/andromeda/sequencer/architecture/finality.mdx meta: { "title": "Finality" } import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; ```mermaid sequenceDiagram participant L2Block participant Sequencers participant PoS participant L1Contract L2Block->>Sequencers: Block Created Note over Sequencers: 2/3 Sequencers must agree Sequencers->>PoS: Reach Consensus PoS->>L1Contract: Submit State Root L1Contract-->>L2Block: Block Finalized Note over L2Block,L1Contract: ~30 min for batch submission ``` This document outlines the process and methodologies used to obtain the finalized block number in the Metis chain environment. It specifically addresses the retrieval methods via Layer 2 (L2) RPC and Layer 1 (L1) Smart Contract (SCC) checks, along with the operational timings for batch submissions. ## Definitions `mvm_finalizedBlockNumber`: The block number in the Layer 2 blockchain that has been finalized after the sequencer rotation and can no longer be reorganized when 2/3 of sequencers reach consensus. `eth_getBlockByNumber`: This is the standard Ethereum JSON-RPC method used to retrieve block information, including the finalized block number. ## Steps to Retrieve Latest Finalized Block Number To obtain the latest ‘`eth_getBlockByNumber`’, you can query through any healthy Layer 2 RPC. Ensure your RPC client handles updates dynamically to reflect changes post-sequencer rotations. Connect to the L2 RPC. Execute the ‘`eth_getBlockByNumber`’ method with the parameter "`finalized`“, similar to how you would use “`latest`”. This instructs the RPC to return the latest finalized block. Example JSON-RPC request: ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["finalized", true], "id": 1 } ``` file: ./content/docs/andromeda/sequencer/architecture/index.mdx meta: { "title": "Sequencer Architecture", "description": "The architecture of the Metis Decentralized Sequencer system is designed to achieve full decentralization and security for the Layer 2 network." } import { Card, Cards } from "fumadocs-ui/components/card"; With the introduction of Decentralized Sequencers, Metis aims to achieve full decentralization of its Layer 2 networks, overcoming the limitations of traditional centralized sequencers. This system is designed to enhance security, scalability, and transparency while ensuring fault tolerance and efficient transaction ordering. We have launched a Decentralized Sequencer Pool to achieve full decentralization in Layer 2 networks and avoid the single-point failures derived from centralized sequencers. This is a key step towards making our L2 network fully decentralized. It works with our existing decentralized P2P network to enable smooth and secure sequencer transitions, and the removal of faulty or malicious nodes. This ensures the network's long-term stability and creates a continuous, stable, and community-driven model. To achieve that, we utilize such technologies: * [Tendermint consensus](https://docs.tendermint.com/v0.34/introduction/what-is-tendermint.html) developed developed by Cosmos * [Threshold Signature Scheme](https://github.com/bnb-chain/tss-lib) (TSS) * Multi Party Computation (MPC) * [Libp2p](https://libp2p.io/) * L2 Geth and others ## Core Components 1. **Ethereum Layer (L1)** * [Smart Contracts](/sequencer/operation/natspec): Responsible for locking METIS tokens, managing sequencer staking, and storing critical data for sequencer rotation. * [Finality](/sequencer/architecture/finality): Provides security and finality by anchoring transaction batches on Ethereum. 2. **Consensus Layer (PoS)** * [Tendermint-based Nodes](/sequencer/architecture/selection-rotation): Handles consensus on sequencer rotation and election processes. * [MPC (Multi-Party Computation)](/sequencer/architecture/mpc): Enables secure and decentralized batch signing by sequencer nodes. 3. **Metis Layer (L2)** * [Sequencer Nodes](/sequencer/architecture/sequencer): Processes user transactions, assembles blocks, and submits them to Ethereum L1. * [Bridge & Adapter Module](/sequencer/architecture/bridge): Facilitates communication between the PoS layer and the Metis layer. It ensures synchronization and updates sequencer information. The system operates with seamless coordination between sequencers, validators, and block producers, leveraging decentralized infrastructure and community governance. ### Key Features 1. **Decentralization:** Every network role is distributed, ensuring fairness and security. 2. **Fault Tolerance:** Automatic rotation and reselection of sequencers in the event of failures or malicious activity. 3. **Efficiency and Scalability:** Transactions are processed in batches for optimized throughput, while finalization happens on Ethereum Layer 1 (L1). 4. **Transparency and Governance:** Governed by community voting power based on METIS token staking. This document provides a detailed breakdown of the system components, workflows, governance mechanisms, technical requirements, and participation processes. ## System Architecture ```mermaid graph TB User[User/dApp] -->|Submit Transaction| RPC[RPC Node] RPC -->|Forward| Bridge[Bridge & Adapter] Bridge -->|Validate| PoS[PoS Layer] PoS -->|Select| Sequencer[Current Sequencer] Sequencer -->|Create Block| P2P[P2P Network] Sequencer -->|Batch Txs| MPC[MPC Module] MPC -->|Sign Batch| L1[Ethereum L1] L1 -->|Verify| Verifier[Verifier] subgraph "Layer 2" RPC Bridge PoS Sequencer P2P MPC end ``` The architecture of the Metis Decentralized Sequencer system is designed to achieve full decentralization, fault tolerance, and scalability for the Layer 2 network. It integrates three key layers that coordinate to ensure efficient transaction processing and secure block production. Simplified transaction flow overview: 1. A user initiates a transaction. 2. The transaction is sent to Sequencer nodes in the network. 3. The Sequencers receive the transaction, and produce a block for it if it is valid. 4. Multi-party computation (MPC) nodes combine the blocks and send them to the Ethereum main chain. This completes the transaction. ### Workflow Summary 1. **Transaction Processing:** * Users send transactions to the Metis RPC nodes. * The current sequencer validates, assembles, and executes the transactions. 2. **Batch Submission:** * The sequencer forms transaction batches and signs them through MPC. * Signed batches are submitted to Ethereum Layer 1 for finality. 3. **Sequencer Rotation:** * The PoS layer manages periodic sequencer rotations using a weighted random algorithm. * The active sequencer is replaced according to the staking weights, ensuring fairness and fault tolerance. ### Key Features of the Architecture * **Fair Sequencer Rotation:** Sequencer rotation is controlled by staking weights and governed by community consensus. Each sequencer's participation is validated through smart contracts on the Ethereum Layer. * **Fault Tolerance and Recovery:** If a sequencer fails or acts maliciously, the PoS layer reselects a new sequencer to maintain uninterrupted block production. * **Transparent Operations:** Sequencer rotations, staking data, and governance votes are fully transparent and auditable on-chain. * **Security and Finality:** By anchoring transaction batches to Ethereum, the system ensures robust security and immutable finality. ### Metis Nodes: Works on 3 layers (LockingPool.sol) * **Ethereum layer:** * A set of smart contracts on the Ethereum network responsible for locking and rewards for sequencers. * **Consensus (PoS) layer:** * A set of PoS Nodes based on Tendermint * When started, it detects the MPC addresses and calls the MPC module (see below) to trigger the keys generation if they do not exist; * When the sequencer submits L2BatchTxs to L1, the signature needs to be generated by multiple existing sequencers (more than 2/3 of the Sequencer nodes participate in MPC signing); * When the new sequencer node joins or exits, it performs the MPC resharing of private key shards without updating the mpc address in the locking contract (the mpc address can also be generated if needed); * Provides a variety of data query interfaces for Metis layer; * **Metis layer:** * On this layer, for every new epoch another entity called sequencer is getting selected and/or rotated according to the information generated by the consensus layer; ## Transaction Flow The transaction flow within the Metis Decentralized Sequencer system ensures efficient, secure, and decentralized processing. The flow is designed to handle transactions from users and produce finalized blocks on Layer 1 (Ethereum) with fault tolerance and scalability. **Step-by-Step Transaction Flow** 1. **User Transaction Submission:** * Users interact with Metis dApps or wallets to send transactions via an RPC interface. * The transaction is received and validated by the current sequencer node. 2. **Transaction Validation and Inclusion:** * The sequencer checks the validity of the transaction, ensuring it adheres to protocol rules. * Valid transactions are assembled into a block for Layer 2. 3. **Block Execution and Confirmation:** * The sequencer node executes the transactions in the block. * A transaction hash and block number are returned to the user as confirmation. 4. **Batch Formation:** * The sequencer groups multiple Layer 2 blocks into a single batch. * This batch contains Merkle proofs for all transactions, ensuring tamper-proof validation. 5. **Multi-Party Computation (MPC) Signature:** * The batch is signed using an MPC mechanism, requiring signatures from a majority of active sequencers. * This process ensures decentralization and security for the batch submission. 6. **Batch Submission to Ethereum (L1):** * The signed batch is submitted to the Ethereum Layer 1 via the [Bridge & Adapter module](/sequencer/architecture/bridge). * This ensures the finality of transactions by anchoring them on Ethereum. 7. **Sequencer Rotation (if applicable):** * At periodic intervals or upon fault detection, the PoS layer rotates the sequencer role to a new node. * The new sequencer takes over transaction processing seamlessly. ## How to Become a Sequencer The process of becoming a sequencer in the Metis Decentralized Sequencer system is essential for contributing to the network's decentralization and earning rewards. It involves meeting technical requirements, locking METIS tokens, and maintaining operational reliability. For a detailed, step-by-step guide on becoming a sequencer, including prerequisites, application process, and governance mechanisms, visit the dedicated page: file: ./content/docs/andromeda/sequencer/architecture/locking.mdx meta: { "title": "Locking Pool / NFT" } Metis uses the POS contract to manage the entry and exit of the sequencer node set, which can be deployed in L1 ## Entry and Replacement of Sequencer Nodes Anyone can mortgage metis and apply to become a sequencer. When the number of active sequencers reaches the agreed maximum, the newly applied node will enter the waiting queue. If the sequencer is unhealthy for a long time, they will be withdrawn from the network. When there is free space in the sequencer pool, remove the top node from the head of the waiting queue and enter the pool. Reference examples: * [https://github.com/poanetwork/posdao-contracts](https://github.com/poanetwork/posdao-contracts) * [https://github.com/bnb-chain/bsc-genesis-contract/tree/master/contracts](https://github.com/bnb-chain/bsc-genesis-contract/tree/master/contracts) * [https://github.com/maticnetwork/contracts](https://github.com/maticnetwork/contracts) ## **Locking NFT** ```mermaid stateDiagram-v2 [*] --> Locked: Lock METIS Locked --> Active: Mint NFT Active --> Waiting: Request Exit Waiting --> Unlocked: After 21 Days Unlocked --> [*]: Burn NFT Active --> UpdatedStake: Increase Stake UpdatedStake --> Active Active --> UpdatedSigner: Change Signer UpdatedSigner --> Active ``` Every user who successfully locks tokens and applies to become a sequencer will get an NFT. The tokenId of the NFT is the sequence id corresponding to the sequencer. On the contrary, when the unlocked token exits the sequencer, the corresponding NFT token will be destroyed. If the user accidentally transfers the NFT to others, he will not be able to withdraw the locked METIS. In order to prevent this from happening, the transfer of the NFT obtained by the user is restricted in the contract. Only the LockingPool owns the mint/burn/transfer permissions. Because after the NFT contract is successfully deployed, the owner will be transferred to the LockingPool. If the user who has already locked the METIS needs to replace the signer, then the updateSigner method is provided in the LockingPool contract, which can help the user to replace the signer and transfer the NFT file: ./content/docs/andromeda/sequencer/architecture/mpc.mdx meta: { "title": "MPC Module" } Multi Party Computation (MPC) module is a part of Sequencer node and is responsible for the management of the entire life-cycle of the multisignature keys. Conducts external operations such as: 1. Multisig generation 2. Key resharing 3. Applying the signature 4. Deletion of signature 5. Provides support for the asynchronous usage of many multisignatures ## Core Method Processing Flow ```mermaid sequenceDiagram participant Initiator participant MPCNodes participant TSSLib participant Storage Initiator->>MPCNodes: keyGenPrepare (sessionID) MPCNodes->>Storage: Check Local Data Storage-->>MPCNodes: Data Status MPCNodes-->>Initiator: keyGenReady Initiator->>MPCNodes: keyGenStart MPCNodes->>TSSLib: Construct LocalParty TSSLib->>MPCNodes: Process Key Generation MPCNodes->>Storage: Store Key Data Storage-->>MPCNodes: Confirm Storage MPCNodes-->>Initiator: Key Generation Complete ``` `keyGen` process flow Phase 1: Notifying MPC Nodes to Prepare * Generate a random `sessionID` locally; * Broadcast the `keyGenPrepare` message to all MPC nodes using the p2p network; * Upon receiving the `keyGenPrepare` message, each MPC node starts its processing goroutine; * Check the local data (the data means whether the TSS module has stored the mpc information corresponding to the id) based on the `keyId`; * If there is existing data in the `READY` state, return the data from storage directly. No need to proceed with the `keyGen` operation; * If there is existing data with a `PENDING` state, return an error to avoid inconsistencies in key generation due to concurrent execution of different key generation calls; * Establish a p2p communication channel; * Return the `keyGenReady` message to the initiating node; Phase 2: Initiating the `keyGen` process * The initiating node waits to receive `keyGenReady` messages from all nodes; * Once the initiating node receives `keyGenReady` messages from all nodes, it broadcasts the `keyGenStart` message to all MPC nodes using the p2p network; * Upon receiving the `keyGenStart` message, each MPC node: * Constructs a `LocalParty` instance locally; * Begins receiving information from other nodes; ## Additional processes flow * In essence, the processing flow of `keySign` is similar to `keyGen`, with the difference lying in some data transmission and verification.. * On the other hand, `keyDelete` does not involve any TSS-lib operations. It only requires broadcasting the `KeyDeleteMessage` message to all nodes to request the deletion of the key. ## TSS Library: Threshold Signature Scheme Library - open-source multisig tool library and the main source of MPC logic: * Responsible for the multisig key algorithm layer ## Key Local Storage: * Conducts the saving and encrypting the key’s info in the local kv storage (levelDB) provided by the corresponding node * The specific fields are described as follows: * `keyId`: The unique identifier of the multi-signature key pair. Passed in by the consensus layer caller, it is guaranteed that only one key pair can be generated for the same keyID; * `keySessionId`: The session id when the key is generated (keyGen), randomly generated. The module will ensure that the value is different every time it is called; * `data`: Key storage data, generated by tss-lib. It mainly includes: public key (address), private key fragmentation, and all partyIds participating in multi-signature. The specific data is in tss-libkeygen.LocalPartySaveData; * `status`: The status of the current key data, mainly consists of three types: * `PENDING` (processing) * `READY` (already available) * `ERROR` (An error occurred during generation, the current key cannot be used to sign) ## Tendermint channel: Open-source p2p communication and consensus library provided by cosmos-sdk: * POS Node creates a separate Tendermint channel for communication messages between multiple p2p nodes during MPC operations ## libp2p ibp2p Is an open-source p2p network communication library * MPC uses libp2p `inCommunication` messages between multiple different p2p nodes, supporting information transmission during MPC operation file: ./content/docs/andromeda/sequencer/architecture/rotation.mdx meta: { "title": "Selection and Rotation" } ## Selection Process The probability of choosing Sequencer A: ```math P(A) = VotingPower(A) / TotalVotingPower ``` ```math VotingPower(A) = LockedAmount(A) / 10^{18} ``` This code implements a weighted random selection algorithm to choose blockchain producers for the next span in a provably fair way, the use of the block hash seed prevents manipulation. The key steps are: 1. It extracts a seed from the block hash to seed the random number generator; 2. Then converts each validator's voting power to a number of "slots" or weighted ranges proportional to their power; 3. After that, it generates a random number in the total weighted range; 4. To select a validator, It does a binary search to find which validator's range the random number falls into; 5. Lastly, it repeats steps 3-4 to select N producers based on their relative voting power; ```mermaid stateDiagram-v2 [*] --> Active: Lock METIS Tokens Active --> Selected: Random Selection Selected --> Producing: Start Block Production Producing --> Rotating: End of Period Rotating --> Active: New Sequencer Selected Active --> Exiting: Initiate Exit Exiting --> [*]: After 21 Days ``` ## Example The current lock is 20000 METIS, which means votingPower is 20000. To be more precise: When a validator joins in `MsgValidatorJoin`, its voting power is calculated from its staked amount using the `GetPowerFromAmount()` function. This seems to convert the amount to voting power using some fixed ratio or formula. In `GetPowerFromAmount()`, the amount is converted to an int64 voting power: ```go // get voting power from amount votingPower, err := helper.GetPowerFromAmount(msg.Amount.BigInt()) ``` When a validator updates its stake in MsgStakeUpdate, the new voting power is recalculated from the new amount:: ```go // set validator amount p, err := helper.GetPowerFromAmount(msg.NewAmount.BigInt()) if err != nil { // handle error } validator.VotingPower = p.Int64() ``` So there is a direct correlation between stake amount and voting power, where stake amount is converted to voting power using a fixed ratio or formula. ## Rotation Process Sequencer Lists are stored in a system contract named `MetisSequencerSet` on Metis L2 Chain. This contract is controlled by MPC address which needs several signers to set the sequencer info. The sequencer lists are rotated by PoS layer according to staking info on Ethereum L1 Chain. There is another situation for sequencer rotation, when the active sequencer is down or out of service (currently no penalty is benign implemented in that regard). The other sequencers will reselect a new sequencer according to consensus on the PoS layer. file: ./content/docs/andromeda/sequencer/architecture/sequencer.mdx meta: { "title": "Sequencer Node" } The Sequencer Node includes: 1. L2 Geth (including the OP-Node) 2. Batch Submitter (Proposer) 3. Adapter Module 4. MPC Module ```mermaid graph TB subgraph "Sequencer Node" L2Geth[L2 Geth] Batcher[Batch Submitter] Adapter[Adapter Module] MPC[MPC Module] end Txs[Transactions] -->|Submit| L2Geth L2Geth -->|Sequence| Batcher Batcher -->|Request Signature| MPC MPC -->|Sign Batch| L1[Ethereum L1] PoS[PoS Layer] -->|Rotation Info| Adapter Adapter -->|Update| L2Geth ``` ## L2 Geth (including the OP-Node) * It is responsible for transaction sequencing and assembly of the blocks on the Metis layer. * The processing logic of whether it is the current block sequencer is added in the `applyTransactionToTip` function, to conduct regular sequencer rotation. * The sequencer (OP-NODE) node obtains the current sequencer position in the rotation list which corresponds to the block height with the help of the Adapter module (see below) from the MPC Consensus Layer. It checks whether it is the current sequencer in the rotation – if so, constructs the batch, if not, does not construct the batch. ## Batch Submitter (Proposer) * Responsible for building the batches and submitting them to Layer 1 after they get signed by multiple sequencers; * For decentralization it utilizes MPC. Multiple sequencers sign the transaction batch jointly when the transaction batch is being formed. * MPC service signs the batch submission with such entry parameters: `batchID`, `signHash`, and the signature result has such parameters: `batchID`: return value: signature r, s, v-values. * Query the corresponding `signHash` according to the `batchID`: Input parameter: `batchID` – return value: `signHash` ## Adapter Module * Responsible for interacting with the other external modules on the consensus layer (PoS Node). ## Additional Information The core problem of the single-sequencer model adopted by other Layer 2 networks is the the inability to perform sequencer rotation. Here is how Metis tackles it: * The rotation information is stored on the L2 contract (managed by sequencers, named as `MetisSequencerSet` contract), so that all nodes can obtain the latest sequencer rotation information through L2 transactions, and the management of the sequencer list contract is controlled by the consensus layer (PoS nodes); * After the consensus layer produces the sequencer list information (contained in each epoch), the list will be signed by MPC, and the current sequencer will initiate a transaction to update the sequencer list; * Each approved sequencer in the sequencer list can verify the current (picked) sequencer in rotation according to the sequencer list. * If the current sequencer fails to order transactions within the specified time, or produces wrong transactions (like initiating two transactions with identical L2 TxID), the node is considered malicious. The PoS layer will select a new sequencer (construct `ReselectSeqencer` signature transaction, containing expected TxID, version and other information, signed by the MPC service), and the new sequencer will initiate a `ReselectSeqencer` transaction on the current TxID on L2, writing the information of the new sequencer into `MetisSequencerSet` contract. * In case of rotation, when a node receives a regular transaction with TXID, it puts on hold the regular transaction and executes MetisSequencerSet.sol contract transaction based on the latest version, then the PoS layer selects the new sequencer that will execute the regular transaction. This ensures that the update to the sequencer list contract is executed, and the execution result reflects the latest state. file: ./content/docs/andromeda/sequencer/architecture/transaction.mdx meta: { "title": "Transaction Processing", "description": "This document outlines the transaction processing within the Metis Andromeda Decentralized Sequencer Pool system." } import { Step, Steps } from "fumadocs-ui/components/steps"; ```mermaid sequenceDiagram participant User participant RPC participant Sequencer participant MPC participant L1 participant Verifier User->>RPC: Submit Transaction RPC->>Sequencer: Forward Transaction Sequencer->>Sequencer: Create Block Sequencer->>MPC: Request Batch Signature MPC-->>Sequencer: Return Signature Sequencer->>L1: Submit Batch L1->>Verifier: Verify Batch Verifier-->>L1: Confirm Finality ``` ## Transaction Initiation and Propagation Users typically initiate transactions from a client, sign them, and submit them to the network. These transactions are sent directly to the RPC network. The L2 transactions are then proxied to the Bridge & Adapter layer, which collaborates with the Proof of Stake (PoS) layer to ensure the transactions reach the current Sequencer's transaction pool. ## Block Formation and Sequencer Consensus Upon receiving verified L2 transactions from the PoS layer via the Bridge & Adapter, the current Sequencer constructs a block and broadcasts it to the peer-to-peer (P2P) network. Transactions originating from Ethereum L1 and enqueued via a cross-chain bridge are handled uniquely by the current Sequencer, which creates a block containing the single transaction. The Bridge & Adapter monitors the transaction status from the current Sequencer. Other sequencers receiving blocks from the P2P network save it after verifying the Sequencer's signature on the transaction. ## Transaction Verification The batcher program creates batch data and state root batch data, then solicits a signature from the Multi-Party Computation (MPC) module. The PoS layer verifies the Sequencer's batch transaction signature and initiates the MPC signing process. ## Batching and Submission to Layer 1 After the MPC node signs the batches, they are dispatched to the Layer 1 Ethereum network. ## Layer 1 Verification and Finalization A verifier, in sync with Ethereum Layer 1, validates the integrity of the batches, ensuring that the finalized block number aligns across both layers. ## Finality Check The Layer 2 block number is considered finalized after a sequencer rotation and consensus is reached by two-thirds of the sequencers. The State Commitment Chain contract (SCC) on the Ethereum mainnet is critical for confirming the finality of batches. Batch submissions are made approximately every 30 minutes, when blocks reach finality in L2. file: ./content/docs/andromeda/sequencer/operation/faq.mdx meta: { "title": "FAQs" } import { Accordion, Accordions } from "fumadocs-ui/components/accordion"; Decentralized Sequencers are key entities within the Metis Layer 2 ecosystem, responsible for: * Sequencing transactions and assembling blocks on the Metis Layer 2 chain. * Submitting batched transactions to Ethereum Layer 1 for security and finality. * Ensuring seamless rotation and fault tolerance through decentralized governance. Unlike centralized systems, Metis leverages a pool of decentralized sequencers to distribute responsibilities and eliminate single points of failure. This model enhances the resilience of the network while fostering community-driven participation. The transition to decentralized sequencers is a critical milestone for Metis. The primary objectives include: 1. **Resilience and Security**: Elimination of single points of failure by distributing the sequencing process across multiple nodes. 2. **Fair Participation**: Introducing a weighted voting mechanism based on staked METIS tokens, ensuring fairness in sequencer selection. 3. **Governance and Accountability**: Establishing governance mechanisms to penalize malicious behavior and reward contributors. 4. **Efficiency and Scalability**: Ensuring efficient transaction processing and block production across the Layer 2 network. 1. **Sequencer Rotation** * Ensures fair distribution of block production roles. * Utilizes a rotation mechanism managed by the Proof-of-Stake (PoS) consensus layer and smart contracts. 2. **Fault Tolerance** * Automatic reselection of sequencers in case of failure or malicious activity. * Guarantees network stability by replacing inactive or misbehaving sequencers. 3. **Community Governance** * Decentralized governance ensures community participation in decision-making. * Slashing mechanisms to penalize malicious behavior and reward honest participants. 4. **Transparency** * Publicly auditable sequencer operations and rotation records. * All sequencer-related actions are stored on-chain, ensuring transparency. In case of bad performance or malicious acting, the particular sequencer pool participant’s locked tokens would be slashed. Cases would include but not limited to: 1. Transaction manipulation (MEV or sandwiching) 2. Malicious Execution Result Modification: If a node modifies the execution result of a block, it will fail validation by other sequencers. This will cause other sequencers to stop producing blocks. The node will then be forced to produce a new block with the correct execution result. Cases would include but not limited to: 1. Failing to produce a block during a certain period of time 2. Slow performance: if the sequencer fails to produce the blocks vastly behind the average timing of other sequencers 3. Multiple Node Outages: If multiple nodes go offline at the same time, and they are all malicious, they should be punished more severely. This includes nodes that represent more than 1/3 of the total number of sequencers 4. Accumulated Unpacked Blocks: If a node does not pack a block for a certain number of transactions, other sequencers can vote to slash it. file: ./content/docs/andromeda/sequencer/operation/guide.mdx meta: { "title": "Guide", "description": "The Decentralized Sequencer Pool is a critical step towards complete decentralization of Metis’ Layer 2 network, eliminating single points of failure associated with centralized sequencers. By combining existing decentralized P2P validators and block producers, it enhances stability, scalability, and fault tolerance." } import { Callout } from "fumadocs-ui/components/callout"; import { Step, Steps } from "fumadocs-ui/components/steps"; By following these guidelines, Sequencers can efficiently claim rewards, increase or withdraw their lock-up amounts, and avoid penalties while contributing to the security and stability of the Metis network. There are some prerequisites to running a sequencer. See [Requirements](/sequencer/operation/requirements) for more details. ## Set Up and Run Your Node Follow the provided technical documentation to deploy and initialize your Sequencer node: **Initialization**: 1. Install and configure [Docker Compose](https://github.com/ericlee42/metis-sequencer-setup-docker-compose) or [Kubernetes](https://github.com/MetisProtocol/metis-charts/blob/main/README.md) on your server. 2. Run the Sequencer node setup script: * Generate the Sequencer address, private key, and public key during initialization. 3. Back up your private key securely. Loss of the key may result in irrecoverable consequences. **Configuration**: * Deploy your node as instructed in the README file using Docker Compose or Kubernetes. * Ensure your private key address is backed up, and generate a local private key file for secure storage. ## Submit Sequencer Information Submit your node's details via a GitHub pull request for inclusion in the Metis Decentralized Sequencer Dashboard. **Required Information**: * **Name**: Name of your Sequencer. * **Avatar**: A profile image/logo. * **URL**: Your organization's website. * **Address**: The whitelist address for sequencer lock-up. * **Seq\_addr**: The sequencer address provided by the server after you run the Sequencer. * **Pubkey**: The public key provided by the server after you run the Sequencer. Please remove the extra ‘04’ characters from the generated pubkey. * **Description**: Brief introduction about you or your organization. **Submission Steps**: 1. Fork the [metis-sequencer-resources](https://github.com/MetisProtocol/metis-sequencer-resources) repository. 2. Create a new branch and add your Sequencer details. 3. Submit a pull request for approval. ## Synchronize Your Node ### Wait for Sequencer Synchronization Run the node and wait for block synchronization to complete: 1. Check the logs of the bridge container. Wait until the “`Waiting for themis to be synced`” message disappears, indicating that themis is synchronized to the latest height. 2. `Query eth_getBlockByNumber` via the l2geth RPC to confirm the block height if it is synchronized to the latest. Once both the Bridge and L2geth are fully synchronized, you can proceed with the lock operation. Note: Ensure synchronization is complete before proceeding. Continuing operations before synchronization is finished may result in lock events not being recognized. ## Lock METIS Tokens The Metis tokens to be locked must be on Ethereum L1 (chainid:1) You can complete the locking process through the [Sequencer Mining](https://sequencer.metis.io/) page. Alternatively, you can interact directly with the [contract](/sequencer/operation/natspec) to bypass the frontend operations. ### Locking Options You can lock METIS tokens using one of the following methods: 1. **Via Sequencer Mining Page**: * Access the user-friendly interface to complete the locking process directly through the [Sequencer Mining](https://sequencer.metis.io/) page. 2. **Direct Contract Interaction**: * For advanced users, bypass the frontend and interact directly with the smart contract. ### Wallet Whitelisting Once your wallet address is added to the whitelist, you'll notice a **"Become a Sequencer"** button after connecting your MetaMask wallet. To initiate the process: 1. **Connect Your Wallet**: Ensure your MetaMask is connected to the Ethereum network. 2. **Start the Process**: Click the **"Become a Sequencer"** button to begin. ### Pre-Requisites Before proceeding: * **Minimum METIS Tokens**: Ensure your wallet holds at least **20,000 METIS** on the Ethereum mainnet. ### Node Setup Set up your Sequencer node using Kubernetes for deployment. While Kubernetes is the recommended method for deployment, additional deployment options will be introduced in the future. ### Token Lock-Up The lock-up process is a critical step for participating in the Sequencer Pool: 1. **Lock-Up Amount**: * Enter the amount of METIS tokens you want to lock, ensuring a **minimum of 20,000 METIS** and a **maximum of 100,000 METIS**. 2. **Confirm Transaction**: * Click **"CONFIRM"** to execute the lock-up transaction and confirm it in your wallet. ### Important Considerations * **Lock-Up Cap**: The maximum lock-up amount is 100,000 METIS. Transactions exceeding this cap will still execute; however, rewards will be calculated based on the capped amount of 100,000 METIS. * **Partial Withdrawals**: The functionality to partially withdraw locked tokens is not available yet. If you accidentally lock more than intended, you will need to exit and rejoin the Sequencer Pool. Note that there is a **21-day exit period**, during which rewards will not accrue. * **Plan Carefully**: Only lock the amount of METIS you are comfortable with, keeping in mind the operational limits and restrictions. ### Completion Once the lock-up process is complete and you see the **"Complete"** confirmation page, congratulations—your Sequencer setup is now successful, and you are ready to operate as part of the Metis Decentralized Sequencer Pool. Rewards are capped at 100,000 METIS lock-up. Withdrawals before the 21-day exit period are not allowed. ## Activate Your Sequencer and Monitor via the Dashboard Once your Sequencer node is successfully running, proceed to the [Sequencer Dashboard](https://sequencer.metis.io) to monitor and manage your node. Within the dashboard, you can: * **View Operational Metrics**: Access real-time data about your Sequencer's performance, such as block production status and synchronization progress. * **Check Rewards**: Monitor your earned mining rewards and track reward distribution details. * **Node Health Status**: Ensure your node is operational and meeting network requirements. This dashboard provides you with a streamlined view of all essential metrics, making it easier to manage and optimize your Sequencer operations. ## Daily Operations and Support To ensure your Sequencer operates efficiently and generates consistent earnings, follow these guidelines: ### Daily Maintenance 1. **Server and Network Health**: * Maintain a stable server environment and network connection. * Regularly monitor your node’s performance metrics to ensure proper block packaging and production. 2. **Log Monitoring**: * Review system logs frequently to detect and resolve any issues promptly. 3. **Software Updates**: * Keep your Sequencer node software updated to the latest version to avoid compatibility issues and ensure optimal performance. ### Community Support If you encounter any issues or need assistance: * **Join the Community**: Connect with other Sequencer operators on the Metis Sequencer group via: * [Discord](https://discord.gg/metis) * [Telegram](https://t.me/metis_dev) * **Get Quick Help**: These groups provide real-time communication and a platform to share solutions and receive technical support from the Metis team and the community. Efficient daily operations and active engagement with the community will help you maintain your node's uptime and maximize your earnings. ## Claim Mining Rewards Once your Sequencer starts earning rewards, you can claim them through the [Sequencer Dashboard](https://sequencer.metis.io): Please double-check your wallet address before submitting. If you are using a contract address, make sure it is the correct contract address on Metis Andromeda. Entering an incorrect address could result in the loss of rewards. ### Steps to Claim Rewards: 1. **View Unclaimed Rewards**: * Navigate to the Dashboard to check your current unclaimed rewards. 2. **Initiate Claim Transaction**: * Click the **"Claim"** button to begin the reward distribution process. 3. **Confirm or Modify Wallet Address**: * Verify your wallet address in the popup window. * If needed, modify the address before submitting the transaction. Please double-check your wallet address before submitting. If you are using a contract address, make sure it is the correct contract address on Metis Andromeda. Entering an incorrect address could result in the loss of rewards. 4. **Rewards Distribution**: * The rewards will be transferred to your specified address on the Metis Andromeda network. ### Additional Practices #### Increasing Your Lock-Up Amount 1. **Dashboard Update**: * On the Sequencer Dashboard, view the current amount of locked METIS. 2. **Increase Lock-Up**: * Enter the additional METIS amount in the **"Increase"** field and confirm the transaction. 3. **Maximum Cap**: * The lock-up cap remains at **100,000 METIS**. Attempts to lock more will not yield additional rewards. #### Partial Withdrawals 1. **Eligibility**: * You can withdraw any amount exceeding the **20,000 METIS minimum** lock-up. * The withdrawable amount is calculated as:\ \&#xNAN;*Total locked tokens – 20,000 METIS.* 2. **Initiate Withdrawal**: * On the Dashboard, click **"Partial Withdraw."** * Enter the desired amount, confirm the transaction in the popup, and validate it in MetaMask. 3. **Token Transfer**: * The withdrawn METIS will be sent to your **Owner address**. #### Exiting the Sequencer Pool 1. **Initiate Unlock**: * Click the **"Unlock"** button on the Dashboard and confirm the exit transaction in MetaMask. 2. **21-Day Exit Period**: * Your Sequencer will enter a **21-day waiting period** during which: * Rewards will not be earned. * Block production will stop. 3. **Final Withdrawal**: * After 21 days, return to the Dashboard to withdraw your locked METIS. file: ./content/docs/andromeda/sequencer/operation/index.mdx meta: { "title": "Sequencer Operation", "description": "Welcome to the Metis Sequencer Operation Documentation." } import { Card, Cards } from "fumadocs-ui/components/card"; import Tally1 from "lucide-react/dist/esm/icons/tally-1"; import Tally2 from "lucide-react/dist/esm/icons/tally-2"; import Tally3 from "lucide-react/dist/esm/icons/tally-3"; This document serves as a comprehensive resource to understand the operations of Sequencer Nodes in the Metis Layer 2 network. ## Sequencer Mining Rewards * The estimated **Mining Reward Rate (EMRR)** is **20%**, designed to incentivize Sequencer participation. * Rewards are calculated per block and updated every two weeks to maintain the target MRR. ## Sequencer Onboarding Overview } title="Review Technical Documentation" description="Thoroughly review all technical documentation to understand the operational and technical requirements for running a Sequencer." href="/andromeda/sequencer/architecture" /> } title="Approved by Metis Governance" description="Submit an application to join the Sequencer Pool. Approval is required to begin operation." href="/andromeda/sequencer/operation/requirements" /> } title="Set Up and Run Your Sequencer" description="Deploy your Sequencer node, configure it correctly, and securely back up your private keys." href="/andromeda/sequencer/operation/guide" /> file: ./content/docs/andromeda/sequencer/operation/natspec.mdx meta: { "title": "NatSpec" } Smart Contracts play a critical role in the Metis Layer 2 ecosystem, enabling secure and decentralized management of Sequencer operations and network activities. This section provides detailed **NatSpec (Ethereum Natural Specification Format)** documentation for both Mainnet and Testnet contracts. By adhering to NatSpec standards, we ensure clarity and transparency for developers and auditors alike. ## Key Contracts | **Contract** | **Ethereum Mainnet (`ChainId: 1`)** | **Sepolia Testnet (`ChainId: 11155111`)** | | --------------- | -------------------------------------------- | -------------------------------------------- | | **LockingInfo** | `0x0fe382b74c3894b65c10e5c12ae60bbd8faf5b48` | `0x390A6fE63385522E87e248BC5200f7d3a02F994b` | | **LockingPool** | `0xd54c868362c2098e0e46f12e7d924c6a332952dd` | `0x7591940125cC0344a65D60319d1ADcD463B2D4c3` | Sequencers can interact directly with these contracts to manage rewards, lock-ups, and related activities without requiring frontend tools. ## Key Contract Functionality The following methods are provided to manage Sequencers efficiently. These include querying and updating your Sequencer's status, locking tokens, and handling rewards. ### Reading Contract Information 1. **`seqOwners`** Retrieves comprehensive Sequencer status using the owner's address. * **Parameter**: `seqId (uint256)` - The Sequencer ID. * **Response**: Returns details of the Sequencer's operational state. 2. **`seqSigners`** Retrieves Sequencer information using the signer's address. * **Parameter**: `seqId (uint256)` - The Sequencer ID. * **Response**: Returns details of the Sequencer's operational state. 3. **`sequencers`** Accesses all detailed information about a Sequencer using its ID. * **Parameter**: `seqId (uint256)` - The Sequencer ID. * **Response**: ```python amount (uint256): Locked METIS tokens. reward (uint256): Accrued rewards. activationBatch (uint256): Activation batch number. updatedBatch (uint256): Last updated batch number. deactivationBatch (uint256): Deactivation batch number. deactivationTime (uint256): Time of deactivation. unlockClaimTime (uint256): Time for claiming unlocked tokens. nonce (uint256): Nonce value. owner (address): Owner's address. signer (address): Signer's address. pubkey (bytes): Signer's public key. rewardRecipient (address): Reward distribution address. status (uint8): Current Sequencer status. ``` ### Writing Contract Information 1. **`lockFor`** Locks METIS tokens and assigns Sequencer ownership. * **Parameters**: * `_signer (address)`: Sequencer signer address. * `_amount (uint256)`: Amount of METIS tokens to lock. * `_signerPubkey (bytes)`: Uncompressed public key of the signer. 2. **`lockWithRewardRecipient`** Similar to `lockFor`, but includes an additional parameter to specify a reward recipient. * **Parameters**: * `_signer (address)`: Sequencer signer address. * `_rewardRecipient (address)`: Reward recipient address. * `_amount (uint256)`: Amount of METIS tokens to lock. * `_signerPubkey (bytes)`: Uncompressed public key. 3. **`relock`** Adds more tokens to an existing lock or locks accrued rewards. * **Parameters**: * `_seqId (uint256)`: Sequencer ID. * `_amount (uint256)`: Additional tokens to lock (can be `0` if relocking rewards). * `_lockReward (bool)`: Whether to lock current rewards. 4. **`setSequencerRewardRecipient`** Updates or assigns a reward recipient address. * **Parameters**: * `_seqId (uint256)`: Sequencer ID. * `_recipient (address)`: New reward recipient address. 5. **`withdrawRewards`** Withdraws accrued rewards to the specified address. * **Parameters**: * `_seqId (uint256)`: Sequencer ID. * `_l2Gas (uint32)`: Gas limit for the operation. 6. **`unlock`** Initiates the unlocking process for METIS tokens. * **Parameters**: * `_seqId (uint256)`: Sequencer ID. * `_l2Gas (uint32)`: Gas limit for the bridge operation. 7. **`unlockClaim`** Claims unlocked tokens after the mandatory 21-day waiting period. * **Parameters**: * `_seqId (uint256)`: Sequencer ID. * `_l2Gas (uint32)`: Gas limit. 8. **`withdraw`** Partially withdraws locked tokens while maintaining the minimum lock balance. * **Parameters**: * `_amount (uint256)`: Amount to withdraw. * `_seqId (uint256)`: Sequencer ID. file: ./content/docs/andromeda/sequencer/operation/requirements.mdx meta: { "title": "Requirements" } import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; Anyone can become a sequencer by meeting the Infrastructure, Staking, and Governance requirements. The process includes: * **Hardware Requirements:** Network configurations that meet the technical requirements, such as: * CPU/RAM: c5.2xlarge or equivalent * Storage: 500Gi ebs gp3 with 200 MB/s throughput * **Staking:** Ability to lock a minimum of **20,000 METIS** tokens on Ethereum Mainnet (chainid:1). The maximum lock-up is **100,000 METIS**. * **Governance:** Complying with governance rules and participating in community voting. ## Hardware Requirements | Component | Minimum Specifications | | --------- | ---------------------- | | CPU | 8 vCPU | | RAM | 16 GiB | | Storage | 500 GiB | Please ensure these ports are exposed for P2P connection. Refer to [metis-node](https://github.com/MetisProtocol/metis-charts/blob/main/charts/metis-node/README.md) for the details. ## Steps to Apply ### Submit an Application * Visit the [Metis Governance Forum](https://ceg.vote/c/infrastructure-sequencer/) and submit a proposal to become a Sequencer. * Provide details about your experience with blockchain nodes, your infrastructure, and why you want to participate in the Sequencer Pool. [Template](https://ceg.vote/t/governance-proposal-decentralized-sequencer-governance/1922) ### Review by Governance * Your proposal will be reviewed by the Metis governance team or community. This ensures that participants align with the network’s decentralization goals and technical standards. ### Team Contact * If approved, a team member from Metis will contact you regarding your application status and next steps. file: ./content/docs/hyperion/lazai/node/blockchain.mdx meta: { "title": "Client & Blockchain" } The final step involved a `client` object that handled the actual payment on the blockchain. But what is this mysterious `client`? And how do we, as users, interact with our funds on the LazAI network? This is where the **LazAI Client** comes in. It is your secure gateway to the LazChain, like a specialized banking app and notary service rolled into one. ### The Problem: Talking to a Blockchain is Hard Blockchains are powerful, but they aren't user-friendly. Interacting with one directly involves managing cryptographic keys, formatting transactions, calculating "gas" fees (the cost of a transaction), and understanding complex smart contract interfaces. A single mistake could lead to lost funds. Imagine you want to pay for an AI service. You shouldn't need to be a blockchain expert to do it. You need a simple, safe tool that handles all the technical details for you, just like using a credit card online without needing to understand the international banking system. ### The Solution: Your Personal Blockchain Assistant The `Client` is our solution. It's a Python class that abstracts away all the low-level blockchain complexity. It provides simple, easy-to-understand methods for all the key actions you might want to perform, such as: * Checking your account balance. * Depositing funds to pay for services. * Registering new compute nodes. * Signing requests to authorize payment. It's your secure wallet and remote control for the entire decentralized side of the Alith ecosystem. ### How to Use the LazAI Client Let's see how to use the `Client` to manage your account. The first step is to initialize it with your `private_key`. **A quick note on private keys:** A private key is like the master password to your blockchain account. It should be kept extremely secret. We'll load it from an environment variable, which is a secure way to handle secrets in code. ```python import os from alith.lazai import Client # For this example, we'll set a dummy private key. # In a real app, you would set this in your terminal before running the script: # export PRIVATE_KEY='0xyour_real_private_key' os.environ['PRIVATE_KEY'] = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80' # 1. Create a client instance. It automatically finds your private key. client = Client() print(f"Client created for account: {client.wallet.address}") ``` **Output:** ``` Client created for account: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 ``` Great! We've created our `Client` and it's linked to our personal account on the blockchain. Now, let's perform a simple "read" operation: checking our balance. This just asks the blockchain for information and doesn't cost anything. ```python # 2. Check the account balance balance_wei = client.get_balance() print(f"Current balance is: {balance_wei} wei") # 'wei' is the smallest unit of the currency ``` **Output:** ``` Current balance is: 999999... wei ``` Next, let's perform a "write" operation. We'll deposit some funds into the settlement contract, making them available to pay for AI services. This requires sending a transaction to the blockchain, which the `Client` makes incredibly simple. ```python # 3. Deposit 1000 wei into the settlement contract for future payments tx_hash, _ = client.deposit(amount=1000) print(f"Deposit transaction sent! Transaction hash: {tx_hash.hex()}") ``` **Output:** ``` Deposit transaction sent! Transaction hash: 0x... ``` Behind the scenes, the `Client` created a valid transaction, signed it with your private key, and broadcasted it to the network. Finally, remember from earlier that paid requests need a signature? The `Client` handles that too. The `get_request_headers` method creates the special headers needed to prove you approve the payment, without sending a full transaction just yet. ```python # 4. Get authentication headers for a request to a node node_address = "0x...some_node_address..." headers = client.get_request_headers(node=node_address) print("Generated Headers for a Paid Request:") print(headers) ``` **Output:** ``` Generated Headers for a Paid Request: {'x-lazai-user': '0xf39...92266', 'x-lazai-nonce': '...', 'x-lazai-signature': '0x...'} ``` You would then include these headers when sending a request to a paid [AI Service Node](05_ai_service_nodes__inference__query__training__.md). ### Under the Hood: How a Transaction is Made When you call a method like `client.deposit(1000)`, how does the `Client` turn that into a secure blockchain transaction? 1. **Prepare the Call:** The `Client` identifies which smart contract to talk to (the `settlement_contract`) and which function to call (`deposit`). 2. **Build the Transaction:** It constructs a transaction object, including the recipient (the contract's address), the value (`1000`), and other details like a `nonce` (a transaction counter to prevent replays). 3. **Sign:** It uses your secret `private_key` to create a unique digital signature for this exact transaction. This proves to the network that you authorized it. 4. **Send:** It broadcasts the signed transaction to a blockchain node. 5. **Confirm:** The node validates the signature and, if valid, includes it in a new block, making the state change (your deposit) permanent. The `Client` then waits for this confirmation. This flow ensures that only you can authorize actions from your account. ```mermaid sequenceDiagram participant You participant client as LazAI Client participant w3 as Web3.py Library participant Blockchain You->>client: deposit(1000) client->>client: Prepare call to settlement_contract.functions.deposit() client->>w3: Build transaction object w3-->>client: Transaction object ready client->>w3: Sign transaction with private key w3-->>client: Signed transaction ready client->>Blockchain: Send raw transaction Blockchain-->>client: Transaction confirmed (hash) client-->>You: Return transaction hash ``` ### Diving into the Code The power of the `Client` comes from two key files: [`alith/lazai/client.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/alith/lazai/client.py) and [`alith/lazai/chain.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/alith/lazai/chain.py). The `Client` class itself is a high-level interface. Its `__init__` method sets up connections to all the important smart contracts on the LazAI network. A contract's `address` is its unique location, and its `ABI` is like a menu of all its available functions. ```python # Simplified from: alith/lazai/client.py class Client(ChainManager): def __init__(self, private_key: str): # The parent ChainManager handles the basic connection and wallet super().__init__(private_key=private_key) # Connect to the Settlement smart contract using its address and "menu" (ABI) self.settlement_contract = self.w3.eth.contract( address=contract_config.settlement_address, abi=SETTLEMENT_CONTRACT_ABI, ) # ... and connections to all other contracts ... ``` This setup means `self.settlement_contract` is now a ready-to-use Python object that represents the smart contract on the blockchain. When you call a method like `deposit`, it's a simple wrapper that calls the real workhorse: `send_transaction`. ```python # Simplified from: alith/lazai/client.py def deposit(self, amount: int): # Prepare the specific function call we want to make function_call = self.settlement_contract.functions.deposit() # Pass the function call and the amount to the generic transaction sender return self.send_transaction(function_call, value=amount) ``` The `send_transaction` method (located in the parent `ChainManager` class) contains the core logic for signing and sending, as shown in our diagram. ```python # Simplified from: alith/lazai/chain.py def send_transaction(self, function: Any, value: int = 0): # ... code to estimate gas and get a nonce ... # 1. Build the transaction tx = function.build_transaction({'from': self.wallet.address, 'value': value, ...}) # 2. Sign it with your private key signed_tx = self.w3.eth.account.sign_transaction(tx, self.wallet.key) # 3. Send it to the network tx_hash = self.w3.eth.send_raw_transaction(signed_tx.raw_transaction) # 4. Wait for it to be confirmed and return the receipt tx_receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash) return tx_hash, tx_receipt ``` This beautiful abstraction means that adding new blockchain interactions is as simple as creating a new wrapper method in the `Client` class. All the difficult and repetitive parts are handled by `send_transaction`. file: ./content/docs/hyperion/lazai/node/index.mdx meta: { "title": "AI Service Nodes" } The `Agent` can decide *what* to do, but it needs a powerful engine to actually perform the complex computations of a large language model. This is where **AI Service Nodes** come in. They are the power plants of our AI ecosystem. ### The Problem: From Blueprint to Factory Imagine you've designed a revolutionary new car. Your design (the `Agent`) is brilliant. It knows how the car should look, how the engine connects to the wheels, and how the steering works. But a blueprint can't drive. You need a factory with heavy machinery to actually build the car. And you might need different types of factories: one for assembling the car, one for testing its off-road capabilities on a special track, and another for training new assembly-line robots. Our AI components are the same. The `Agent` is the blueprint. The AI Service Nodes are the specialized factories that bring the blueprint to life and offer its capabilities to the world. They are the runnable, deployable server applications that do the actual work. ### The Solution: Specialized AI Factories In our project, we have three main types of Service Nodes, each a different kind of factory: 1. **The Inference Node:** This is the main "chat factory." Its job is to run a powerful language model. When our `Agent` needs to think, reason, or generate text, it sends the request to an Inference Node. This is the node that provides the raw intelligence. 2. **The Query Node:** This is the "private library" factory. It's a specialized server that provides Retrieval-Augmented Generation (RAG) capabilities. A user can give it their private documents and a question, and this node will search *only within those documents* to find the answer. It's designed for secure, private data analysis. 3. **The Training Node:** This is the "AI school." Its job is to take a general-purpose AI model and fine-tune it on a specific dataset. For example, you could use a Training Node to teach a base model to become an expert in legal documents or medical terminology. These nodes are designed to be run as independent servers, exposing their functions over a standard API. This means any application, not just our `Agent`, can use their power. ### How to Run a Service Node Running a service node is like turning on the power to one of our factories. You do it right from your command line. Let's look at how to start the most common one, the Inference Node. To start an Inference Node, you run the `alith.inference.server` module and tell it which AI model to load. ```bash # This command starts a server running a specific AI model python3 -m alith.inference.server \ --model /path/to/your/model.gguf \ --port 8080 ``` This command tells the project: "Start the inference server using the model file found at `/path/to/your/model.gguf`, and make it available on port `8080`." Once running, you'll see output in your terminal indicating that a web server has started. Now, your `Agent` (or any other application) can be configured to send its requests to `http://localhost:8080` to get a response from the AI. Similarly, you can start the other nodes: ```bash # Start a Query Node to handle private data searches python3 -m alith.query.server ``` ```bash # Start a Training Node to handle model fine-tuning jobs python3 -m alith.training.server ``` Each command launches a dedicated server, ready to perform its specialized task. ### Under the Hood: A Web Server for AI So what happens when you run one of these commands? You are starting a web server built using a popular Python framework called FastAPI. This server listens for incoming HTTP requests (just like any website) and, based on the request, performs an AI task. Let's trace a typical request to an **Inference Node**. 1. Our `Agent` needs to answer a user's question. It sends a request to the Inference Node's API endpoint (e.g., `/v1/chat/completions`). 2. The Inference Node server receives this request. 3. It might first pass the request through **Middleware**. Think of middleware as a security guard or a toll booth that inspects the request before it goes further. We'll see in the next chapter that this is where billing happens. 4. The server passes the user's prompt to the loaded language model (the "engine"). 5. The model processes the prompt and generates a response. 6. The server packages this response and sends it back to the `Agent`. Here is a diagram of that flow: ```mermaid sequenceDiagram participant Agent participant Node as Inference Node Server participant Middleware as Optional Billing Middleware participant LLM as Language Model Engine Agent->>Node: POST /v1/chat/completions (with prompt) Node->>Middleware: Validate request Middleware->>Node: Request OK Node->>LLM: Process the prompt LLM-->>Node: Return generated text Node->>Middleware: Report usage for billing Middleware-->>Node: Billing recorded Node-->>Agent: Send back final response ``` ### Diving into the Code Let's peek inside [`alith/inference/server.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/alith/query/server.py) to see how this is structured. The code might look complex, but the core idea is simple. The `if __name__ == "__main__":` block at the bottom is what runs when you execute the command from your terminal. It's responsible for parsing your command-line arguments, like `--model`. ```python # Simplified from: alith/inference/server.py if __name__ == "__main__": # Code to parse arguments like --host, --port, --model... parser = argparse.ArgumentParser(...) # ... args = parser.parse_args() # Call the main run function with the provided arguments run( host=args.host, port=args.port, model=args.model, settlement=args.settlement, # Important for later! ) ``` This part just gathers the settings. The real work happens in the `run` function it calls. The `run` function sets up and starts the web server. Notice the `if settlement:` check. This is a preview of how we can easily enable paid services. ```python # Simplified from: alith/inference/server.py def run(host: str, port: int, *, model: str, settlement: bool = False): # ... code to create the basic FastAPI web server app ... app = create_app(...) if settlement: # If settlement is enabled, add the billing "toll booth" from .settlement import TokenBillingMiddleware app.add_middleware(TokenBillingMiddleware) # Start the actual server return uvicorn.run(app, host=host, port=port) ``` This code shows the modular design. The core function is to create the `app`. Then, we can optionally `add_middleware` to it, adding new layers of functionality like billing without changing the core AI logic. The Query Node ([`alith/query/server.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/alith/query/server.py)) works similarly. It defines an endpoint like `/query/rag` that uses a Store to search through private data and return the results. *** file: ./content/docs/hyperion/lazai/node/middleware.mdx meta: { "title": "Middleware", "description": "The Settlement & Billing Middleware is a component that a node operator can \"plug in\" to their service node. This middleware sits between the user and the AI model, performing two critical jobs, authentication and billing." } We learned how to run the "factories" that provide the computational power for our AI. These nodes are the workhorses of the network. But running powerful computers costs real money for electricity and hardware. So, how do the people running these nodes get paid for their services? This is where the **Settlement & Billing Middleware** comes in. Think of it as the automated accounting system for the entire AI network. ### The Problem: A Free-for-All Isn't Sustainable Imagine a highway system where there are no toll booths. Everyone can drive as much as they want for free. At first, it sounds great! But soon, the roads would be overcrowded, and there would be no money to pay for maintenance, repairs, or building new roads. The system would collapse. Our AI network is like that highway. If using powerful AI Service Nodes is free, there is no incentive for people to provide the expensive computing resources needed to run them. We need a fair and automated way to charge for usage, like a smart toll booth that only charges for the distance you've driven. ### The Solution: A Smart Utility Meter for AI The `Settlement & Billing Middleware` is our smart toll booth. It's a component that a node operator can "plug in" to their service node. This middleware sits between the user and the AI model, performing two critical jobs: 1. **Authentication:** Before letting a request through, it checks the user's identity and confirms they have enough funds on the LazChain to pay for the service. 2. **Billing:** After the AI model has done its work, the middleware measures the resources used (like the number of text "tokens" processed), calculates the cost, and automatically initiates the payment from the user to the node operator on the blockchain. This middleware is the key to creating a decentralized marketplace for AI compute. ### How a Node Operator Enables Billing Unlike the other components we've seen, you don't typically use this middleware in your `Agent` code. Instead, the person running the **AI Service Node** enables it when they start their server. In the [Node](/hyperion/lazai/node) section, we saw this command to start a server: ```bash # Start a server without billing python3 -m alith.inference.server --model /path/to/model.gguf ``` To turn on the billing system, the node operator simply adds the `--settlement` flag. ```bash # Start the same server, but now with the billing middleware enabled python3 -m alith.inference.server \ --model /path/to/model.gguf \ --settlement ``` That's it! By adding that single argument, the server is now running our "smart toll booth," ready to authenticate users and charge for AI processing. ### Under the Hood: The Life of a Billed Request When a user sends a request to a node with settlement enabled, a fascinating dance happens between the server and the blockchain. 1. **User Signs the Request:** The user, using their wallet, creates a cryptographic signature that essentially says, "I, User A, approve this action and agree to pay for it." They send this signature along with their request. 2. **Middleware Intercepts:** The `TokenBillingMiddleware` catches the incoming request *before* it reaches the AI model. 3. **Authentication & Validation:** The middleware checks the user's signature to prove their identity. It then makes a quick call to the LazChain to verify that the user's account is valid and has sufficient funds. 4. **AI Processing:** If everything checks out, the request is passed along to the AI model, which generates a response. 5. **Cost Calculation:** The middleware intercepts the outgoing response. It looks inside the response data to find out how much work was done (e.g., `"total_tokens": 512`). 6. **Settlement:** It calculates the final cost (e.g., 512 tokens \* price per token) and submits this information to the LazChain to finalize the payment from the user to the node operator. 7. **Final Response:** The original response from the AI model is sent back to the user. Here is a diagram of that flow: ```mermaid sequenceDiagram participant User participant Node as AI Service Node participant Middleware as Billing Middleware participant Blockchain as LazChain User->>Node: Request + Signature Node->>Middleware: Intercept Request Middleware->>Blockchain: Validate User & Funds Blockchain-->>Middleware: User OK Middleware->>Node: Pass request to AI model Node-->>Middleware: Return AI Response (with usage) Middleware->>Blockchain: Settle payment (User -> Node Owner) Blockchain-->>Middleware: Payment Recorded Middleware-->>User: Return AI Response ``` ### Diving into the Code Let's see how the code enables this. In the [`alith/inference/server.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/alith/inference/server.py) file, the `run` function checks for the `--settlement` flag we used. ```python # Simplified from: alith/inference/server.py def run(host: str, port: int, *, model: str, settlement: bool = False): app = create_app(...) # Create the basic web server if settlement: # If settlement is enabled, plug in the billing middleware from .settlement import TokenBillingMiddleware app.add_middleware(TokenBillingMiddleware) # Start the server uvicorn.run(app, host=host, port=port) ``` This shows the "plug-in" nature of the middleware. If `settlement` is true, we simply add the `TokenBillingMiddleware` to our server application (`app`). Now, let's look at a simplified version of the middleware itself from [`alith/inference/settlement.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/alith/inference/settlement.py). Middleware classes have a special `dispatch` method that gets to inspect both the `request` and the `response`. ```python # Simplified from: alith/inference/settlement.py class TokenBillingMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): # 1. First, validate the incoming request signature (not shown here for simplicity) # from ..lazai.request import validate_request # validate_request(request, ...) # 2. Let the request proceed to the AI model response = await call_next(request) # 3. After the AI is done, inspect the response to bill the user if response.status_code == 200: # ... code to read the response body and get the token count ... response_data = json.loads(response_body) total_tokens = response_data["usage"]["total_tokens"] # 4. Calculate the cost and settle the payment on the blockchain calculate_billing(request, total_tokens, self.client) return response ``` This code follows our diagram perfectly. It lets the main application do its job by calling `await call_next(request)`, and then it does its own accounting work afterward. The final piece of the puzzle is the `calculate_billing` function. ```python # Simplified from: alith/inference/settlement.py def calculate_billing(request, total_tokens, price_per_token, client): # Get user info from the request headers user = request.headers[USER_HEADER] nonce = request.headers[NONCE_HEADER] # ... # Calculate the final cost cost = total_tokens * price_per_token # Tell the client to settle the fees on the blockchain client.inference_settlement_fees(...) return user, cost ``` This function does the simple math and then, most importantly, calls a method on the `client` object. This `client` is our bridge to the blockchain. file: ./content/docs/hyperion/lazai/node/training.mdx meta: { "title": "Training" } Now, we'll tackle one of the most exciting capabilities: creating our own specialized AI models. A general-purpose model is a jack-of-all-trades, but what if you need a master of one? This is where the **Training Pipeline** comes in. It is a specialized "university" for language models. ### The Problem: A Generalist in a Specialist's World Imagine you have a powerful, general AI that knows about history, science, and art. Now, you want to use it to provide expert-level customer support for your new software product. If a user asks, "How do I configure the Z-widget in version 3.2?", the general AI has no idea. It wasn't trained on your product's documentation. We need a way to take this smart, general model and send it to "school" to learn a new, specific subject. We need to turn our generalist into a specialist. ### The Solution: An AI University The Training Pipeline is the infrastructure for this AI university. It allows you to fine-tune a general-purpose model on your own private data, turning it into an expert on a particular topic. You play the role of the university's dean. You provide: * **The Curriculum:** A dataset of examples you want the model to learn from (e.g., your product's help documents or past support tickets). * **The Teaching Method:** A set of training parameters that define *how* the model should learn. The pipeline then manages the entire, resource-intensive training process, from preparing the data to running the "classes" on powerful GPUs, ultimately graduating a new, customized model. ### How to Use the Training Pipeline Using the training pipeline is a three-step process: 1. Start a **Training Node**, the server that runs the university. 2. Define your curriculum and teaching method (`TrainingParams`). 3. Submit your training job and monitor its progress. #### Step 1: Start the Training Node First, the person providing the computing power needs to start a Training Node. This is done from the command line, just like our other service nodes. ```bash # This command starts the "AI University" server python3 -m alith.training.server --port 8080 ``` This starts a server listening on port `8080`, ready to accept new training jobs. #### Step 2: Define the "Curriculum" and "Teaching Method" Now, as a user, you need to define your training job. We do this by creating a set of `TrainingParams`. Let's say we want to teach a small model to be an expert on our product. We'll use a technique called **LoRA**, which is a very efficient way to fine-tune a model. The parameters are defined using Pydantic models from [`alith/training/types.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/alith/training/types.py). Let's create our parameters in Python. ```python # Import the parameter classes from alith.training.types import TrainingParams, LoraParams, DataParams # 1. Define the "curriculum" - our private data # (For a real job, this URL would point to your training data file) our_curriculum = DataParams(data_url="https://example.com/my_product_docs.jsonl") # 2. Define the "teaching method" using LoRA our_teaching_method = TrainingParams( model="Qwen/Qwen2-0.5B", # Start with this general model finetuning_type="lora", # Use the efficient LoRA method num_epochs=3, # Have the model study the data 3 times learning_rate=5e-5, # How big of a "step" to take after each lesson data_params=our_curriculum, # Link to our curriculum lora_params=LoraParams(rank=8) # LoRA-specific settings ) ``` This configuration tells the pipeline: "Take the `Qwen2-0.5B` model and fine-tune it using the `lora` method for `3` epochs on the data found at my URL." There are many more parameters you can tweak, but these are the most important ones to start with. #### Step 3: Submit and Monitor the Job Training can take hours or even days, so we don't wait for it to finish. We submit it as a background job. We'll use the `requests` library to send our `TrainingParams` to the running Training Node. ```python import requests import json import time # Convert our Pydantic object to a dictionary for sending job_config = our_teaching_method.model_dump() # Send the job to the server response = requests.post( "http://localhost:8080/v1/training", json=job_config ) # The server immediately responds with a job ID job_result = response.json() job_id = job_result['job_id'] print(f"Training job started successfully! Your job ID is: {job_id}") ``` **Output:** ``` Training job started successfully! Your job ID is: a1b2c3d4 ``` Now the training is running in the background! We can use our `job_id` to check on its progress at any time. ```python # Check the status of our job status_response = requests.get(f"http://localhost:8080/v1/training/{job_id}") status = status_response.json() print(f"Job Status: {status['percentage']}% complete.") print(f"Current Loss: {status['loss']}") # A lower loss value is better! ``` **Output:** ``` Job Status: 15.0% complete. Current Loss: 1.234 ``` You can call this status endpoint periodically until the `percentage` reaches 100. Once finished, a new model, fine-tuned on your data, will be saved in the node's output directory. ### Under the Hood: The Life of a Training Job When you submit a training job, a carefully orchestrated process begins. 1. **Job Submission:** Your client sends an HTTP POST request to the `/v1/training` endpoint on the Training Node. The body of the request contains your `TrainingParams`. 2. **Validation & ID Generation:** The server receives the request. It quickly validates the parameters and generates a unique `job_id` (e.g., `a1b2c3d4`). 3. **Immediate Response:** The server immediately sends a `202 Accepted` response back to you, containing the `job_id`. This non-blocking design is crucial because the actual training will take a long time. 4. **Background Task:** The server adds the real training work to a background task queue. This is where the heavy lifting happens. 5. **Data Preparation:** The background trainer downloads your data from the `data_url`, decrypts it if necessary, and prepares it for the model. 6. **Model Training:** The trainer loads the base model and starts the fine-tuning process using your specified parameters. It periodically writes its progress (percentage, loss, etc.) to a log file associated with the `job_id`. 7. **Status Check:** When you make a GET request to `/v1/training/{job_id}`, the server simply reads the latest entry from that specific log file and returns it to you. ```mermaid sequenceDiagram participant Client participant Node as Training Node participant Trainer as Background Trainer Client->>Node: POST /v1/training (with TrainingParams) Node->>Node: Generate job_id Node-->>Client: Return 202 Accepted + job_id Node->>Trainer: start_trainer(params, job_id) Trainer->>Trainer: Download & prepare data Trainer->>Trainer: Run training, update log file Note over Client, Trainer: Sometime later... Client->>Node: GET /v1/training/{job_id} Node->>Node: Read log file for job_id Node-->>Client: Return TrainingStatus ``` ### Diving into the Code The logic is split across a few key files in [`alith/training/`](https://github.com/0xLazAI/alith/blob/main/sdks/python/alith/training/). First, [`alith/training/server.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/alith/training/server.py) starts the web server. This is the entry point that listens for your requests. ```python # Simplified from: alith/training/server.py def run(host: str, port: int): app = FastAPI() # ... middleware setup ... # The router contains our API endpoints like /v1/training app.include_router(router, prefix="/v1/training", ...) # Start the server uvicorn.run(app, host=host, port=port) ``` Next, [`alith/training/service.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/alith/training/service.py) defines the API endpoints. The `training` function handles new job submissions. Notice `BackgroundTasks`—this is FastAPI's way of running long jobs without blocking the server. ```python # Simplified from: alith/training/service.py @router.post("") async def training(params: TrainingParams, tasks: BackgroundTasks) -> TrainingResult: # ... validate request ... job_id = generate_job_id() # Add the real work to a background task queue tasks.add_task( start_trainer, params=params, job_id=job_id, ) # Immediately return the job ID return TrainingResult(job_id=job_id, ...) ``` Finally, [`alith/training/trainer.py`](https://github.com/0xLazAI/alith/blob/main/sdks/python/alith/training/trainer.py) contains the `start_trainer` function. This is where the *actual* training happens. It's a wrapper that calls `run_exp` from `llama-factory`, a powerful open-source library specialized for fine-tuning models. ```python # Simplified from: alith/training/trainer.py from llamafactory.train.tuner import run_exp def start_trainer(params: TrainingParams, job_id: str): """Here we use the llamafactory to train the model""" # 1. Prepare the data (download, decrypt, etc.) dataset_name = preprocess_data(params) # 2. Build a large dictionary of arguments for llama-factory training_args = { "do_train": True, "model_name_or_path": params.model, "finetuning_type": params.finetuning_type, "dataset": dataset_name, "output_dir": get_output_dir(job_id), # ... and many more parameters from our TrainingParams ... } # 3. Call the specialized library to do the heavy lifting run_exp(training_args) ``` This shows a smart design: our project provides a user-friendly API and pipeline for managing jobs, while delegating the complex, low-level training algorithms to a specialized, best-in-class library. file: ./content/docs/andromeda/dapp/infra/indexers/0xgraph.mdx meta: { "title": "0xgraph", "description": "A comprehensive, backwards-compatible subgraph solution for simplified blockchain data access." } import { Card, Cards } from "fumadocs-ui/components/card"; import { Database, LayoutPanelTop } from "lucide-react"; A product by Ormi, delivers a comprehensive, backwards-compatible subgraph solution that combines advanced indexing capabilities with seamless hosting. It is designed to simplify blockchain data access. } /> } /> ## Why 0xgraph? 0xgraph provides a powerful, reliable, and scalable platform for managing real-time blockchain data efficiently and effectively. It also allows you to monitor and optimize your subgraphs through robust analytics and high-throughput capabilities. 0xgraph is 100% spec-compliant with The Graph Protocol, ensuring compatibility with every subgraph on The Graph’s hosted and decentralized networks. ## Key Features * **Enhanced Infrastructure**: A revamped RPC layer, autoscaling query handling, and optimized storage for improved reliability (99.9%+ uptime) and performance (up to 6x faster). High throughput ensures smooth handling of large-scale query volumes without latency. * **Zero-Hassle Hosting**: Fully spec-compliant with The Graph Protocol’s hosted and decentralized networks, 0xgraph eliminates lag and downtime. It also enables plug-and-play deployment and familiar tooling, using the same UI, CLI, and tooling as The Graph. You can query subgraphs without managing nodes or infrastructure. * **Analytics & Metrics Dashboard**: Gain real-time insights into subgraph performance, query volume, and uptime through an intuitive dashboard. You can track key metrics to optimize performance and ensure reliability. * **Built-in Webhooks**: Out-of-the-box support for notifications, messaging, and other push-driven use cases. * **Custom Chain Compatibility**: Seamlessly index your custom EVM rollups or private blockchains. file: ./content/docs/andromeda/dapp/infra/indexers/envio.mdx meta: { "title": "Envio", "description": "Feature-rich indexing solution and data infrastructure provider for fast and flexible access to real-time and historical data for any EVM." } import { Card, Cards } from "fumadocs-ui/components/card"; import { Cylinder } from "lucide-react"; Envio is a feature-rich indexing solution that provides developers with a seamless and efficient way to index and aggregate real-time or historical blockchain data for any EVM. The indexed data is easily accessible through custom GraphQL queries, providing developers with the flexibility and power to retrieve specific information. Envio offers native support for Metis (both testnet and mainnet) and has been designed to support high-throughput blockchain applications that rely on real-time data for their business requirements. Designed to optimize the user experience, Envio offers automatic code generation, flexible language support, quickstart templates, and a reliable cost-effective [hosted service](https://docs.envio.dev/docs/hosted-service). Indexers on Envio can be written in JavaScript, TypeScript, or ReScript. } /> ## Why Envio? Envio supports [HyperSync](https://docs.envio.dev/docs/hypersync) on Metis mainnet. HyperSync is an accelerated data query layer for the Metis blockchain, providing APIs that bypass JSON-RPC for 20-100x faster syncing of historical data. HyperSync is used by default in Envio's indexing framework, with the use of RPC being optional. Using HyperSync, application developers do not need to worry about RPC URLs, rate-limiting, or managing infrastructure and can easily sync large datasets in a few minutes, something that would usually take hours or days using RPC. HyperSync is also available as a standalone API for data analytic use cases. Data analysts can interact with the HyperSync API using JavaScript, Python, or Rust clients and extract data in JSON, Arrow, or Parquet formats. For more information, visit the HyperSync documentation [here](https://docs.envio.dev/docs/overview-hypersync). ## Key Features * Contract Import: Autogenerate the key boilerplate for an entire Indexer project off a single or multiple smart contracts. Deploy within minutes. * Multi-chain Support: Aggregate data across multiple networks into a single database. Query all your data with a unified GraphQL API. * Asynchronous Mode: Fetch data from off-chain storage such as IPFS, or contract state (e.g. smart contract view functions). * Quickstart Templates: Use pre-defined indexing logic for popular OpenZeppelin contracts (e.g. ERC-20). file: ./content/docs/andromeda/dapp/infra/indexers/flair.mdx meta: { "title": "Flair", "description": "Real-time and historical custom data indexing for any evm chain." } import { Card, Cards } from "fumadocs-ui/components/card"; import { Server } from "lucide-react"; Flair provides **indexing primitives** (such as fault-tolerant RPC ingestors, custom processors, re-org aware database integrations) to make it easy to receive, transform, store and access your on-chain data. } /> ## Why Flair? Compared to other alternatives the main reasons are: * Adopting parallel and distributed processing paradigm means high scalability and resiliency for your indexing stack. Instead of constrained sequential processing (e.g Subgraph). * Focused on primitives, which means on the left you plug-in an RPC and on the right you output the data to any destination database. * Native real-time stream processing for certain data workload (such as aggregations, rollups) for things like total volume per pool, or total portfolio per user wallet. * Managed cloud services avoid DevOps and irrelevant engineering costs for dApp developers. * Avoid decentralization overhead (consensus, network hops, etc) since we believe to enable best UX for dApps reading data must be as close to the developers as possible. ## Key Features * Listen to any EVM chain with just an RPC URL. * Free managed RPC URLs for +8 popular chains already included. * Works with both websocket and https-only RPCs. * Track and ingest any contract for any event topic. * Auto-track new contracts deployed from factory contracts. * Custom processor scripts with Javascript runtime (with Typescript support) * Make external API or Webhook calls to third-party or your backend. * Get current or historical USD value of any ERC20 token amount of any contract address on any chain. * Use any external NPM library. * Stream any stored data to your destination database (Postgres, MongoDB, MySQL, Kafka, Elasticsearch, Timescale, etc). file: ./content/docs/andromeda/dapp/infra/indexers/index.mdx meta: { "title": "Indexers" } import { Card, Cards } from "fumadocs-ui/components/card"; import { Network, Database, Boxes, Layers } from "lucide-react"; Indexers, in a broad context, play a fundamental role in organizing and optimizing data retrieval within various systems. These tools act as navigational aids, allowing efficient access to specific information by creating structured indexes. In the realm of databases and information management, indexers enhance query performance by creating a roadmap to swiftly locate data entries. In the context of blockchain and dApps, indexers go beyond traditional databases, facilitating streamlined access to on-chain data. This includes transaction histories, smart contract states, and event logs. In the dynamic and decentralized world of blockchain, indexers contribute to the efficiency of data queries, supporting real-time updates and ensuring the seamless functionality of diverse applications and platforms. There are several indexer solutions available, each offering different levels of decentralization, ease of development, and performance for you to consider. These solutions serve as intermediaries to assist in indexing the Metis network. } /> } /> } /> } /> file: ./content/docs/andromeda/dapp/infra/indexers/the-graph.mdx meta: { "title": "The Graph", "description": "A decentralized indexing protocol that provides an easy way to query blockchain data through APIs known as subgraphs." } import { Card, Cards } from "fumadocs-ui/components/card"; import { LayoutPanelTop, Network } from "lucide-react"; Getting historical data on a smart contract can be frustrating when building a dapp. [The Graph](https://thegraph.com/) provides an easy way to query smart contract data through APIs known as **subgraphs**. The Graph's infrastructure relies on a decentralized network of indexers, enabling your dapp to become truly decentralized. } /> } /> ## Why The Graph? The Graph provides a robust solution for indexing and querying blockchain data. It effectively tackles the challenge of reading blockchain data without creating a centralized bottleneck. With its network of indexers, The Graph offers increased redundancy and quicker query responses. Using GraphQL queries, your dApp can pinpoint exactly the fields it requires. ## Key Features * **Decentralized Indexing**: Enables indexing blockchain data through multiple indexers, thus eliminating any single point of failure * **GraphQL Queries**: Provides a powerful GraphQL interface for querying indexed data, making data retrieval super simple. * **Customizable & Reusable**: Define your own logic for transforming & storing blockchain data. Reuse subgraphs published by other developers. file: ./content/docs/andromeda/dapp/infra/interop/ccip.mdx meta: { "title": "CCIP" } import { Card, Cards } from "fumadocs-ui/components/card"; The **Cross-Chain Interoperability Protocol (CCIP)** is a powerful tool that allows developers to build cross-chain decentralized applications (dApps) that communicate seamlessly between different blockchain networks. With CCIP on Metis, you can enable smart contracts on one chain (e.g., Ethereum) to trigger actions on Metis and vice versa. This opens up new possibilities for cross-chain applications, asset transfers, and messaging between Layer 1 and Layer 2 solutions. The CCIP provides a secure, scalable way to handle complex cross-chain interactions, ensuring consistency and security in a multi-chain environment. To help you get started with CCIP on Metis, we’ve provided the following examples and open-source code contributions from the community. These examples show real-world use cases of how CCIP can be implemented. This example demonstrates how you can use CCIP to build a cross-chain Tic-Tac-Toe game that operates across different blockchain networks. Players on different chains can participate in the game, with contract calls interacting across chains seamlessly. This repository showcases how to set up a basic token transfer system using CCIP to move assets between chains. It’s a simple, foundational use case that can be extended to more complex asset management solutions or cross-chain DeFi applications. ### **Start Building with CCIP on Metis** The provided examples are a starting point for building your cross-chain applications using the CCIP framework. You can modify these examples or create your own cross-chain dApps. Follow the links to the GitHub repositories, clone the projects, and start experimenting with CCIP on Metis today. For further guidance on deploying CCIP projects, check out the Cross-Chain Development section or visit our Developer Support for more assistance. file: ./content/docs/andromeda/dapp/infra/interop/index.mdx meta: { "title": "Interoperability" } import { Card, Cards } from "fumadocs-ui/components/card"; import { Link } from "lucide-react"; Interoperability is the ability to connect different blockchain networks and protocols. From general message passing to liquidity optimization. ## Frameworks } /> file: ./content/docs/andromeda/dapp/start/demo/index.mdx meta: { "title": "Demo" } import { Card, Cards } from "fumadocs-ui/components/card"; The Demo section provides examples and guides for integrating popular libraries like Rainbowkit and Thirdweb into your dApp. It includes: Learn how to use Rainbowkit for wallet connection with Sign in With Ethereum (SIWE), as well as an example implementation for creating and indexing NFTs. Explore Thirdweb for wallet connection. Includes an example implementation for creating and indexing NFTs. Each guide contains practical examples and code snippets to help you get started quickly. file: ./content/docs/andromeda/dapp/start/deploy/foundry.mdx meta: { "title": "Foundry" } import { Step, Steps } from "fumadocs-ui/components/steps"; import { Card, Cards } from "fumadocs-ui/components/card"; **Foundry** is a fast and powerful framework for Ethereum development, written in Rust. It’s great for developers who prefer more control and speed in their development workflows. ## Prerequisites ### Install Foundry Install Foundry by running the following command in your terminal: ```bash curl -L https://foundry.paradigm.xyz | bash ``` Then, initialize Foundry: ```bash foundryup ``` ### Create a Foundry Project Start a new project: ```bash forge init my-foundry-project ``` ### Configure Foundry for Metis You will need to edit the `foundry.toml` file to include Metis network details: ```toml [profile.default] rpc_endpoints = { metis = "https://andromeda.metis.io/?owner=1088", # Andromeda Mainnet sepolia = "https://sepolia.metisdevops.link" # Sepolia Testnet } ``` ### Compile and Deploy Compile your contracts: ```bash forge build ``` Deploy using Foundry: ```bash forge create --rpc-url https://sepolia.metisdevops.link src/MyContract.sol:MyContract ``` file: ./content/docs/andromeda/dapp/start/deploy/remix.mdx meta: { "title": "Remix", "description": "This tutorial walks through the process of deploying a smart contract on Metis using Remix." } import { Step, Steps } from "fumadocs-ui/components/steps"; import { Card, Cards } from "fumadocs-ui/components/card"; ## Prerequisites ### Prepare Your Smart Contract 1. Go to [Remix IDE](https://remix.ethereum.org/) 2. Create a new file (e.g., `MyContract.sol`) 3. Paste the smart contract code: ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; contract MyToken { string public name = "My Token"; string public symbol = "MTK"; uint8 public decimals = 18; uint256 public totalSupply = 1000000 * 10**18; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor() { balanceOf[msg.sender] = totalSupply; } function transfer(address to, uint256 value) public returns (bool) { require(balanceOf[msg.sender] >= value, "Insufficient balance"); balanceOf[msg.sender] -= value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(balanceOf[from] >= value, "Insufficient balance"); require(allowance[from][msg.sender] >= value, "Not approved"); balanceOf[from] -= value; balanceOf[to] += value; allowance[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } } ``` 4. Compile your contract by clicking on the "Solidity Compiler" tab and pressing "Compile" ### Deploy Using Rabby Wallet 1. In Remix, go to the "Deploy & Run Transactions" tab 2. Change the environment to "Injected Provider - Rabby" or "Injected Provider - MetaMask" - if you don't see this connection, click "Customize this list..." and add the related plugin 3. When prompted, connect your Wallet to Remix 4. Ensure you're on the correct network in your wallet 5. Select your contract from the dropdown 6. Click "Deploy" 7. The Wallet will open a confirmation popup: * Review contract deployment details * Check the gas fee * Confirm the transaction ## Verify Your Contract (Optional) 1. After deployment, copy your contract address from Remix 2. Go to the [Block Explorer](https://sepolia-explorer.metisdevops.link/) 3. Paste and search the contract address 4. Navigate to the "Verify Contract" section 5. Enter your contract address 6. Upload your source code or paste it directly 7. Complete verification ## Step 4: Interact with Your Contract 1. In Remix, under the "Deployed Contracts" section, you'll see your contract 2. Expand it to view all available functions 3. Use the interface to call functions and interact with your contract 4. For transactions that modify state, your wallet will prompt for confirmation ## Conclusion You've successfully deployed a smart contract using a Wallet on the Metis Sepolia chain. This same process works for any EVM-compatible blockchain. Remember to always test your contracts on testnets before deploying to mainnet, and ensure you understand the security implications of your smart contract code. file: ./content/docs/andromeda/dapp/start/demo/rainbowkit/index.mdx meta: { "title": "Rainbowkit" } import Profile from "@/components/rainbowkit/Profile"; import { SIWEDemo } from "@/components/rainbowkit/SIWEDemo"; import { Card, Cards } from "fumadocs-ui/components/card"; This is an interactive experience filled with components. For example this is a wallet connector, it uses the `rainbowkit` library that integrates `siwe` (Sign in with Ethereum) using `next-auth`. file: ./content/docs/andromeda/dapp/start/demo/rainbowkit/nft.mdx meta: { "title": "Deploy NFT" } import Profile from "@/components/rainbowkit/Profile"; import NFTGallery from "@/components/rainbowkit/NFTGallery"; After logging in, you need to have test metis in your wallet. You can get some from [here](https://faucet.metis.io/). This Application is using the [Metis Sepolia Testnet](https://sepolia-explorer.metisdevops.link/address/0x70062f9a402bfe8B1f98a18a5d5541b99a58023A) and directly indexing the NFTs by deploying a custom subgraph using [Ormi](/dapp/infra/indexers/ormi/0xgraph). The subgraph is located [here](https://metisapi.0xgraph.xyz/api/public/7628e867-6568-4fe1-9c24-742d1ffc6e79/subgraphs/erc721/v0.0.1/gn). The code for this is located [here](https://github.com/MetisProtocol/docs/blob/main/components/rainbowkit/NFTGallery.tsx). ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /** * @title SimpleNFT * @dev Implementation of an enumerable ERC721 NFT token */ contract SimpleNFT is ERC721 { using Counters for Counters.Counter; Counters.Counter private _tokenIds; constructor( string memory name, string memory symbol ) ERC721(name, symbol) {} /** * @dev Mint a new token */ function mint() public returns (uint256) { _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _safeMint(msg.sender, newTokenId); return newTokenId; } } ``` file: ./content/docs/andromeda/dapp/start/demo/thirdweb/index.mdx meta: { "title": "Thirdweb" } import Profile from "@/components/thirdweb/Profile"; import { Card, Cards } from "fumadocs-ui/components/card"; This is an interactive experience filled with components. For example this is a wallet connector, it uses the `thirdweb` library that integrates `siwe` (Sign in with Ethereum). file: ./content/docs/andromeda/dapp/start/demo/thirdweb/nft.mdx meta: { "title": "Deploy NFT" } import Profile from "@/components/thirdweb/Profile"; import NFTGallery from "@/components/thirdweb/NFTGallery"; You do not need to have test metis in your wallet when using thirdweb's account abstraction. This Application is using the [Metis Sepolia Testnet](https://sepolia-explorer.metisdevops.link/address/0x70062f9a402bfe8B1f98a18a5d5541b99a58023A) and directly indexing the NFTs by deploying a custom subgraph using [Ormi](/dapp/infra/indexers/ormi/0xgraph). The subgraph is located [here](https://metisapi.0xgraph.xyz/api/public/7628e867-6568-4fe1-9c24-742d1ffc6e79/subgraphs/erc721/v0.0.1/gn). The code for this is located [here](https://github.com/MetisProtocol/docs/blob/main/components/thirdweb/NFTGallery.tsx). ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /** * @title SimpleNFT * @dev Implementation of an enumerable ERC721 NFT token */ contract SimpleNFT is ERC721 { using Counters for Counters.Counter; Counters.Counter private _tokenIds; constructor( string memory name, string memory symbol ) ERC721(name, symbol) {} /** * @dev Mint a new token */ function mint() public returns (uint256) { _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _safeMint(msg.sender, newTokenId); return newTokenId; } } ```