# AI Data Problem

The rapid advancement of artificial intelligence (AI) has positioned it as a transformative force across industries, revolutionizing decision-making, automation, and knowledge creation. However, the existing AI landscape remains deeply centralized, dominated by a few monopolistic entities that control data, computing power, and model access. Only a handful of super companies have mastered large-scale model training and inference technologies.

Many challenges faced by large models, including hallucinations, stem from data scarcity. The supply of low-cost, publicly available internet data is nearing exhaustion, driving up the cost of data acquisition. Further challenges include the limited availability of personal and high-quality industry data, the difficulty of leveraging such data at scale while preserving privacy, the complexity of assessing data quality and effectiveness, and the lack of mechanisms for individuals and enterprises to receive fair compensation for their data. Going forward, the success of AI applications will largely hinge on how effectively data is generated and utilized.

In summary, LazAI seeks to address the following key challenges:

1. **Data Sharing for AI utilization is Challenging:**  In the AI domain, data is a foundational asset; however, the sharing of personal and industry-specific data remains significantly constrained due to strong privacy and security concerns. Both individuals and organizations are often reluctant to share data for fear of misuse, unauthorized access, or potential fraud. Moreover, the absence of standardized protocols and robust AI infrastructure further hampers the efficient sharing and utilization of data within AI workflows, even when stakeholders are willing to collaborate.
2. **Data Quality and Evaluation Are Challenging:** The quality of publicly available data is highly inconsistent, and a large proportion of high-quality data is proprietary or protected by copyright, limiting access for developers aiming to train competitive AI models. Establishing a unified framework to evaluate data effectiveness across diverse scenarios and perspectives is inherently difficult. Furthermore, there is a lack of viable mechanisms to support personalized, utility-based data evaluation, thereby restricting data optimization and impeding the overall progress of AI systems.
3. **Revenue Generation and Distribution is Difficult:** Throughout the lifecycle of AI model development and deployment, data contributors and model developers struggle to obtain fair compensation due to insufficient transparency and lack of verifiability. Centralized AI platforms often function as opaque systems, making it difficult to trace how data is utilized and how its value is realized. Consequently, data owners lack the ability to assess their data’s contribution to model outcomes or to claim appropriate economic rewards.

Therefore, we aim to build a world where everyone has the opportunity to align AI with their own data, build personalized AI models at minimal cost, and share in the value generated by their data and models through alignment. To achieve this, Lazai is committed to delivering decentralized AI blockchain infrastructure, AI asset protocols, and workflow toolkits. By leveraging decentralized, user-owned data sources, Lazai empowers developers to build value-aligned AI agents.


# LazAI Solution

In the era of artificial intelligence, data is the new oil—but its flow remains obstructed. Privacy concerns, fragmented infrastructure, and opaque value attribution mechanisms have long discouraged individuals and enterprises from contributing their data to AI systems. LazAI reimagines this paradigm with a simple yet transformative proposition: data should be shareable without compromise, transparently evaluated, and fairly rewarded.

At the core of LazAI is a fully on-chain, privacy-preserving AI runtime and governance framework. This infrastructure transforms the raw data contributed by each iDAO into verifiable, ownable, and rewardable digital assets. Whether it is personal insights or proprietary enterprise datasets, contributors can share their data with confidence, safeguarded by advanced cryptographic technologies such as Trusted Execution Environments (TEEs) and Zero-Knowledge Proofs (ZKPs). The contributed data is then validated through verified computing and finalized via QBFT consensus, achieving a consistent and trusted state on the LazAI chain. Every phase, from data contribution and model interaction to final settlement, is executed and governed transparently on-chain, eliminating black-box ambiguity and reestablishing trust in collaborative, decentralized AI.

But LazAI goes beyond enabling secure data sharing, it redefines how the value of data is understood and realized. In today’s landscape, inconsistent data quality and the absence of robust evaluation mechanisms make it nearly impossible to assess the true utility of a dataset in AI training. LazAI addresses this challenge by seamlessly integrating data alignment, governance, and AI model training/inference within a unified, verifiable pipeline. Upon data contribution to the LazAI chain, users receive a DAT token corresponding to the model that encodes ownership, traceability, and value attribution. These tokens empower contributors to track exactly how their data and models are used and to visualize impact through on-chain runtime metrics defined in DAT. This supports both standardized benchmarking and personalized, utility-based insights, enabling more strategic contributions and higher-performance AI systems.

Just as importantly, LazAI ensures that value never disappears into the system. As models consume data and generate outputs, contributors are rewarded in real time, with all revenue flows deterministically and transparently distributed on-chain, tied directly to verified usage. This closed-loop economic model defined within LazAI eliminates the need for intermediaries and dismantles the opacity of centralized platforms. Data contributors and model developers alike receive fair, auditable compensation, grounded in verifiable activity, not speculative markets. Through iDAO governance and establishing decentralized autonomous organizations (iDAOs) for domain-specific data curation, each iDAO enforces community-driven rules for data quality, access, and usage, fostering trust among participants.

By aligning privacy, utility, and economic rewards into a single interoperable framework, LazAI does more than solve the data challenges of AI, it unlocks a new paradigm. One where anyone can contribute, monitor, and benefit from the value they help create. One where AI innovation is no longer the privilege of the few with the most data, but the shared opportunity of a truly decentralized future.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdp2Fu9Mm19jZcsGZc5UcUC9fpLysKVtgqg-f7hm-DJYWjomdSx6BjwqTn0dS0PrC94d71Pd1ZTPMeb4TpE2JJutIAn329splCfAGP-HaLuItqdrDY5TmnSKZlSpNXb6hWffDNS0A?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

LazAI envisions a future where the three foundational pillars of artificial intelligence, data, models, and compute power, are seamlessly and trustfully integrated on-chain through open and unified protocols. This architecture enables a transparent, decentralized, and composable AI ecosystem, built not on blind trust, but on provable integrity and incentive alignment.


# DAT - Data Anchoring Token

A Novel Semi-Fungible Token Standard for AI Data and Models

LazAI moves away from the traditional transaction ledger model, utilizing innovative assetization standards (such as Data Anchoring Token) and a series of new architectures, dedicated to creating a composable environment for Web3 AI applications based on aligned data, advancing the AI + Web3 new paradigm.

The Data Anchoring Token (DAT) is a semi-fungible token (SFT) standard specifically designed for AI dataset ownership, licensing, model anchoring, and provenance tracking.&#x20;

Unlike traditional token standards, DAT introduces a multi-layered ownership model, supporting programmable AI data governance, composable datasets, and decentralized AI model execution.

The core distinction between DAT and previous SFT models is its native AI asset integration, allowing structured access control, automated licensing, and composable AI dataset evolution.

#### Core Structure of DAT

DAT incorporates a multi-tiered token structure, optimizing fungibility, ownership flexibility, and AI-native operations. Each DAT token is characterized by three attributes:

<table data-header-hidden><thead><tr><th width="342"></th><th></th></tr></thead><tbody><tr><td><strong>Attribute</strong></td><td><strong>Function</strong></td></tr><tr><td>Asset ID (Unique AI Asset Identifier)</td><td>Represents an AI dataset, model, or agent, uniquely anchoring it on-chain.</td></tr><tr><td>Access Tier (Granular Permissioning Mechanism)</td><td>Defines usage rights (e.g., read-only, training, inference, resale).</td></tr><tr><td>Partitioned Value (Divisible Ownership Units)</td><td>Represents fractional ownership or usage quotas, allowing flexible AI data licensing and economic models.</td></tr></tbody></table>

This architecture enables AI asset composability, fractional trading, and programmable governance, distinguishing it from previous SFT models.

#### DATs Unique AI-Driven Features:

* **Composable & Forkable AI Data**
  * **Composability:** AI datasets and models can be combined, transferred, and modified while preserving lineage and provenance tracking.
  * **Forking & Evolution:** Developers can fork datasets to create refined AI models while original data owners retain revenue-sharing rights.
* **Programmable AI Licensing & Usage-Based Compensation**
  * **Dataset Licensing:** Users can license AI datasets/models via programmable smart contracts, ensuring royalty distribution.
  * **Inference & Training Access:** DAT enforces usage quotas, granting on-chain controlled access to AI training or inference services.
* **AI Agent Verification & Incentive Structure:**&#x20;
  * **Verifiable AI Computation:** AI model results are anchored with cryptographic proofs (Merkle Trees, ZK Proofs).
  * **Fraud Proofs & Governance:** Challengers can dispute invalid or biased AI models, triggering automated slashing.

As AI increasingly relies on private and proprietary data, DAT ensures trustless verification, ownership tracking, and monetization without compromising privacy or increasing on-chain storage costs.


# iDAO - Individual-centric DAO

To address the AI data alignment issue, LazAI introduces an innovative blockchain solution and redefines DAO as iDAO, focusing on individuals to reshape organizational boundaries.

An iDAO (Individual-centric intelligent DAO) is LazAI’s evolution of the traditional DAO (Decentralized Autonomous Organization). Instead of focusing on collective or corporate entities, iDAOs empower individuals to govern their own AI agents, data assets, and computational resources.

#### The main responsibilities of iDAO include:

1. **Providing Trustworthy AI Data Sources or AI Flow**\
   Offering reliable data sources or AI workflows to other individuals or organizations, ensuring high-quality and aligned data.
2. **Off-Chain Dataset Training and Inference**\
   Off-chain dataset training and inference, providing AI proxy services, enabling more efficient and economical AI computing, and providing a unified API for external services, while ensuring privacy and security through TEE and ZK technologies.
3. **Decentralized Consensus and Data Governance**\
   iDAO participates in the LazChain consensus in the form of a Quorum. Through the decentralization of multiple Quorum organizations, it ensures the reliability and transparency of data governance and storage. Each Quorum acts as an independent iDAO, similar to a traditional data center, but without storing data directly on-chain, effectively reducing on-chain storage costs. iDAO organizations achieve consensus to verify the trustworthiness of off-chain data, ensuring that data is efficiently and quickly available to both on-chain and off-chain agents while ensuring high availability and low latency. Different iDAOs can issue their own DAT tokens through their administrators. The value of DAT tokens is determined by two factors: 1. The initial value of the data is determined by the validator node through the quality assessment algorithm of the corresponding data category (medical, autonomous driving, etc.); 2. The value of the data is determined by the validator node based on its customized economic model and market freedom.
4. **Incentivized & Composable AI Economy**

   Developers and data providers earn DAT rewards for contributing high-quality AI assets, ensuring an aligned incentive mechanism. AI models, datasets, and computational resources can be composed into higher-order AI services, creating a liquid and programmable AI economy.
5. **Building UI or Products**

   In addition to the corresponding APIs to help developers build AI applications, iDAO organizations usually also provide corresponding simple UIs or applications to help non-technical personnel participate in the corresponding iDAO organization with a better experience. For example, through the UI, they can contribute their data to the iDAO in a more automated way to gain benefits, or help people better benefit from the functions provided by the entire iDAO to ensure fair distribution of responsibilities, rights and interests.

#### Key Functions:

* **Governance Autonomy**: Each user controls their iDAO, establishing governance over their personal AI assets (datasets, models, and inference results).
* **Data Sovereignty**: Users own and manage their personal data flows, deciding who can access their data and under what terms.
* **AI Agent Management**: Individuals can deploy personalized AI Agents (MicroAgents) governed and customized through their iDAO.
* **Participate in Consensus**: iDAOs participate in LazChain’s decentralized consensus mechanism (via Quorums), ensuring trustless data validation and governance.

The traditional DAO framework doesn't offer fine-grained, individual control over AI resources. iDAO changes that by putting users at the center of AI governance and ownership, ensuring equitable participation and benefits.


# How to Join an iDAO

Joining an existing iDAO is designed to be accessible to both technical and non-technical users, with steps tailored to different roles (e.g., data contributors, developers, or passive participants):

1. **Identify a Relevant iDAO:**&#x20;
   * Browse the LazAI marketplace (hosted on LazChain) to discover iDAOs aligned with your interests or expertise (e.g., healthcare data, e-commerce analytics, or game AI). Each iDAO’s profile includes its focus area, governance rules, and reward structure (published as on-chain metadata via DATs). LazAI provides a default iDAO called LazAI iDAO. If you don't know which iDAO to choose, you can also use the default iDAO to experience its functions, such as using the LazPad app for a quick start and using Alith to build your own AI application.&#x20;
   * Filter by criteria such as trust score (based on historical data quality and compliance), activity level, or shareRatio (revenue split for contributors).
2. **Submit a Membership Request:**
   * **For data contributors:** Connect your wallet to the iDAO’s interface, review its data usage policy (e.g., privacy constraints, compensation terms), and agree to the terms. Some iDAOs may require a small DAT deposit as a commitment to data quality (refundable if contributions meet standards).
   * **For developers:** Demonstrate relevant skills (e.g., model training experience) via a short on-chain application. The iDAO’s Quorum will vote on approval (via QBFT consensus) within 48 hours.
3. **Start Contributing:**
   1. **Data Contributors:** Upload data via the iDAO’s UI (with automatic encryption via TEEs and ZKPs). The iDAO will validate the data’s integrity and mint DATs to your wallet, representing ownership and future revenue shares.
   2. **Developers:** Access the iDAO’s API to build or fine-tune models using its datasets. Contributions (e.g., improved model accuracy) are verified by the Quorum, with rewards distributed as DATs based on impact.
4. **Participate in Governance:**
   1. Members can vote on iDAO proposals (e.g., updating data policies, adding new Quorum members) via their wallet. Voting weight is proportional to the number of DATs held, ensuring influence aligns with contribution value.

<br>


# How to create iDAO

How to create iDAO and register the iDAO to the LazAI network

Creating an iDAO empowers individuals to lead a community around specific AI use cases (e.g., niche datasets, custom models, or industry-specific workflows). The process is streamlined to minimize technical barriers:

1. **Define Your iDAO’s Scope:**
   * Choose a focus area (e.g., “fitness wearables data for health AI” or “game character dialogue datasets”).
   * **Outline core rules:** data privacy policies (e.g., “no personally identifiable information”), reward structure (shareRatio for contributors), and governance thresholds (e.g., “60% vote approval for policy changes”).
2. **Set Up Infrastructure:**
   * **On-Chain Registration:** Deploy a smart contract via the LazAI dashboard, which auto-generates a unique iDAO ID. The contract includes:
     * Metadata (name, description, scope) stored on IPFS (with a hash anchored to LazChain).
     * Default governance rules (editable via future member votes).
   * **Off-Chain Tools:** Integrate with LazAI’s open-source toolkits (Alith) to set up:
     * A data storage gateway (e.g., IPFS/Arweave) for off-chain dataset hosting.
     * A TEE-enabled data evaluation, inference and training environment.
3. **Assemble Your Initial Quorum:**
   * Recruit 3–5 trusted individuals (or existing iDAOs) to form the initial Quorum, responsible for validating data and resolving disputes. Each Quorum member must stake a minimum of 1,000 LAZ (LazAI’s native token) as collateral (slashed for misconduct).
   * The Quorum is registered on-chain, with their public keys linked to the iDAO’s contract.
4. **Launch and Attract Members:**
   * Publish your iDAO on the LazAI marketplace, highlighting its unique value (e.g., “exclusive healthcare datasets with HIPAA-aligned privacy”).
   * Offer founding member bonuses (e.g., higher shareRatio for early contributors) to attract initial participants.
5. **Complete Registration:**
   * Submit a registration request to LazChain’s main network. The network’s global Quorum will verify that your iDAO meets security standards (e.g., proper use of TEEs, fair governance rules) via QBFT consensus.
   * Once approved, your iDAO gains access to LazAI’s cross-chain interoperability, enabling collaboration with other iDAOs and integration into the broader DAT economy.
6. **Grow and Iterate:**
   * Use governance votes to adapt to member feedback (e.g., expanding into new data types).
   * Scale by merging with complementary iDAOs (via on-chain proposals) or partnering with external platforms (e.g., integrating with health apps to source more data).

By lowering barriers to participation and creation, iDAOs democratize control over AI resources, ensuring the ecosystem evolves based on individual needs rather than centralized gatekeepers. Whether joining or leading an iDAO, users retain ownership of their contributions while collectively building a more aligned, transparent AI future.


# VC - Verified Computing

The LazAI Verified Computing Framework ensures that all AI data, training models, and inference results within the LazAI ecosystem are authentic, verifiable, and tamper-proof.\
It provides a decentralized, trustless, and scalable system for validating AI assets through iDAO governance, Quorum validation, and on-chain verification processes.

#### **Key Function**

The core function of the LazAI Verified Computing Framework is to establish trust in AI data and computations without relying on centralized authorities.\
It ensures that all AI-generated assets:

* Are authentic and auditable
* Maintain provenance and integrity
* Support decentralized AI governance and incentivization

The LazAI Verified Computing Framework operates through a structured process, driven by iDAOs and Quorums, to validate AI assets at every stage of their lifecycle.

#### **Key Advantages**

The LazAI Verified Computing Framework provides a trustless, decentralized approach to AI dataset validation, model verification, and fraud prevention, ensuring a scalable and secure AI-driven blockchain network.

**1. Decentralized & Scalable:** iDAO + Quorum-based validation prevents single points of failure and ensures data integrity without requiring central control.

**2. Trustless AI Data Verificatios:** Ensure AI data remains verifiable, tamper-proof, and auditable without exposing raw data.

**3. Efficient Dispute Resolution:** Optimistic Proofs (OPs) reduce verification overhead, while Fraud Proof mechanisms ensure a secure challenge-response validation system.

**4. Incentive-Driven Ecosystem:** DAT rewards incentivize high-quality AI data submissions, while slashing mechanisms discourage false claims, ensuring an economically sustainable verification system.

This foundation is critical for building a trusted, autonomous AI economy.


# How Does it Work?

Decentralized AI character creation and interaction market

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXeXt1C3nJbeUI9emCTWyz9MpkWL8SNCu5kXlwWKUBKg58hF3tLaZb_AkjXQ5ddnmRTX-v3hHyeRqU20Uile1hdgXv6QbUbC_o3GgxLB_mx8OHLDMh00arCGZi0sLJLs8tan5UfpZg?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

### Scenario Overview

Alice is a virtual character creator. She wants to turn her AI-powered persona, "Cyber Diva" into a monetizable experience. This character has a unique voice and dialogue style. By using **LazAI**, she can offer interactive sessions with "Cyber Diva" through a decentralized system, with payment in **DAT tokens** and complete transparency over how the model was trained and who contributed.

#### Key Participants

* **Creator (Alice):** Prepares and submits datasets to model the character’s voice, tone, and behavior.
* **Validator Nodes (iDAO):** Validate data using ZK proofs to ensure integrity.
* **Inference Providers:** Run GPU-enabled nodes that handle AI requests.
* **Consumers (Users):** Interact with the character by paying in AI gas tokens.
* **Governance DAO:** Adjusts parameters like reward distribution dynamically.

#### Workflow Breakdown

1. **Character Modeling Phase**
   1. Alice preprocesses text/audio of the character.
   2. She uses the **Alith Agent Framework** to submit her dataset in **POV** format.
   3. Submission includes:
      1. Text & vocal tensors
      2. Public dialogue prompts (stored on-chain)
      3. ZK proofs for data integrity
2. **Model Minting Phase**
   1. LazAI’s AI Execution Layer (ExEx) detects the submission.
   2. Using GPU co-processors, it fine-tunes the base model with low-rank adaptation (LoRA).
3. **DAT Anchoring Phase**
   1. A **Semi-Fungible Token (SFT)** is minted, containing:

      1. Metadata of the base model
      2. Access controls
      3. Inference endpoints

      This token acts as a verified, tradable proof of data ownership and model provenance.
4. **Interactive Inference Phase**
   1. A user sends a request to talk with "Cyber Diva".
   2. The model runs on a GPU-powered node and returns the interaction result.
5. **Settlement Phase**
   1. Rewards are auto-distributed as follows:
      1. 70% to Alice
      2. 20% to inference node operators
      3. 10% to the governance pool

#### Why This Matters

This use case shows how LazAI supports real-world applications that rely on:

* Trusted data (via DAT)
* Modular model deployment (via Alith & ExEx)
* Automated, decentralized revenue sharing
* Privacy-preserving inference & transparent governance


# Alith - AI Agent Framework

Alith is a decentralized AI agent framework tailored to harness the capabilities of the LazAI -a decentralized AI platform dedicated to building an open, transparent, high-performance, secure, and inclusive AI ecosystem.

LazAI provides the Alith Agent framework and Model Context Protocol (MCP) to support multimodal and diverse data format preprocessing, as well as POV tensor data conversion. This ensures that data from any source - whether text, voice, or video - can be seamlessly structured and integrated into verifiable, privacy-preserving AI workflows on-chain.

<figure><img src="/files/nUv7eHvGs9DDZZiyzflr" alt=""><figcaption></figcaption></figure>

Alith is a key functional component and development framework within the LazAI platform, enabling users to create and deploy personalized MicroAgents. It supports a wide range of use cases, from simple task execution to complex intelligent interactions. With Alith, users can seamlessly integrate AI technology into daily life and business scenarios, significantly enhancing efficiency and productivity.

* **User Customization:** Alith offers highly flexible customization capabilities, allowing users to define agent behavior, interaction methods, and learning objectives based on specific needs, ensuring adaptability to personalized use cases.
* **Multi-Modal Support:** Equipped with multi-modal data processing capabilities, Alith can understand and respond to inputs in various forms, including text, images, and speech. It supports models such as Llama, Grok, OpenAI, and Anthropic, catering to diverse interaction requirements.
* **Highly Extensible:** Alith provides extensive customization options, from overriding internal prompts to accessing low-level APIs. Users can define roles, goals, tools, actions, and behaviors while maintaining clear abstractions.
* **Workflow Support:** Alith facilitates the implementation of any workflow pattern, from simple sequential and hierarchical processes to complex custom orchestration with conditional branching and parallel execution.
* **Cross-Language Support:** SDKs for Rust, Python, and Node.js enable developers across different ecosystems to easily access Alith. Additionally, low-code orchestration, one-click deployment, and streamlined operation and maintenance lower the technical barrier for users.
* **High-Performance Reasoning:** Leveraging Rust’s performance advantages, Alith supports advanced reasoning techniques, including graph optimization, model quantization and compression, and JIT/AOT compilation using co-processors such as CPUs, GPUs, and TPUs, ensuring exceptional performance in dynamic scenarios.
* **Decentralized Management:** Powered by LazChain’s blockchain technology, Alith ensures data and interaction records are fully traceable, safeguarding transparency and user privacy.

### Conclusion

The Alith AI Agent framework together with LazAI ecosystem exemplifies a forward-thinking approach to AI development. Its decentralized, high-performance, and developer-friendly design addresses long-standing challenges in traditional AI ecosystems. By prioritizing inclusivity, privacy, and interoperability, Alith stands poised to redefine how AI agents are built, deployed, and governed.

<table data-view="cards"><thead><tr><th></th><th data-type="content-ref"></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td>Website</td><td><a href="https://lazai.network/product/alith">https://lazai.network/product/alith</a></td><td><a href="/files/nUv7eHvGs9DDZZiyzflr">/files/nUv7eHvGs9DDZZiyzflr</a></td></tr><tr><td>Alith on X</td><td><a href="https://x.com/0xalith">https://x.com/0xalith</a></td><td><a href="/files/pNOIaoX5W72tPz8dc5yd">/files/pNOIaoX5W72tPz8dc5yd</a></td></tr><tr><td>Developer Docs</td><td><a href="https://alith.lazai.network/docs">https://alith.lazai.network/docs</a></td><td><a href="/files/VIHk2YIsNW9jtItUXqsW">/files/VIHk2YIsNW9jtItUXqsW</a></td></tr></tbody></table>


# Lazpad - AI Agent Lauchpad

Lazpad is an AI agent launchpad on Lazpad. A world where AI Agents are not just created but grown and shaped by living data in creative and rewarding ways.\
\
Powered by LazAI, LazPad blends the best of two breakthroughs. Virtuals changed the game by creating the first launchpad for AI agents, while Pump.fun rewrote the rules of memecoin culture by letting anyone launch a token instantly on Solana. But today’s market is missing something critical: lasting value that comes from real, playful engagement. LazPad is the first platform to blend the best of both worlds.\
\
This is the hybrid the space has been waiting for. A launchpad where AI agents grow through play. Where memetic power, emotions, and engagement fuel what gets minted. Where users do not just ape, they shape. Every click is data. Every action builds value. This is AI-powered launch culture reimagined. This is LazPad.

### Pad + Fun

In a nutshell, LazPad combines structure with spontaneity to launch AI Agents that are both meaningful and viral.

* Pad: A structured, secure pipeline for assetizing AI Agents, built on quality control and community input.
* Fun: A design philosophy focused on play, experimentation, and emotional bonding before monetization.

Together, Pad plus Fun defines every layer of LazPad.

### Internal AI Blockchain Economy

LazAI is building an AI and blockchain internal economy that allows users, projects, and stakeholders to start partaking in a comprehensive system, beginning with LazPad. LazPad is the first real example of how communities can start playing by creating, exploring, and shaping AI experiences together. This is not just about using AI, but about playing an active role in how it grows and evolves. The DAT is a cornerstone of this system, which we explore more later.

### Three LazPad Pillars

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcFopcbK2UdyKwMjUgfBla_WohhcxpfLtVqbv-PAkgKUB3kG5Y5RMYNzChQM1dE8fAuoxovLStgGYsuVoiACBrnN0QESOO1xiXOafjEbZrKZi2jzXLT2gEXA6GQy1TyrjYMEA7xLQ?key=CKEhxZHMmCQboEPJQSy3Hw" alt=""><figcaption></figcaption></figure>

Each zone in LazPad reflects the Pad + Fun philosophy, guiding creators and users from initial interaction to full assetization.

1. #### Premium Launch: Curated Assetization Zone

Targeted at high-quality AI Agent projects that demonstrate technical clarity, autonomy, or strong community consensus. This permissioned zone builds on traditional launchpad models, but is enhanced by LazAI’s task and point systems to deepen user engagement.&#x20;

Projects entering this zone must demonstrate technical clarity, autonomy, or strong community consensus. The result is a vetted high-trust launch backed by community involvement and rigorous standards.

2. #### Open Launch: Permissionless Assetization Zone

This section welcomes all users and builders, enabling easy, low-barrier assetization attempts. To avoid volatility, this helps ensure responsible development and gives users peace of mind while supporting open innovation.

To avoid chaotic speculation, it introduces a Price Unlock Mechanism. If an asset fails to reach its target price, no additional tokens are released. This simple rule reduces volatility, incentivizes actual development, and creates user confidence. Open Launch encourages creativity while ensuring accountability.

3. #### Explore Zone: Pre-Assetization Playground

LazPad’s most distinctive feature, the Explore Zone, is a discovery space for AI Agents (DATs) that haven’t yet started their asset journey. It is where raw AI Agents enter the wild. Unminted. Untested. Full of potential. Users dive in, interact, complete missions, and earn points as they shape each DAT through real decisions. Creators watch it all unfold, collecting feedback and measuring what resonates. Then they choose which agents graduate into an Open or Premium Launch. Build in public and prove through play.

### Meet the DAT - Data Anchorng Token

A Data Anchoring Token (DAT) is a new semi-fungible standard and one of the cornerstone innovations of LazAI. Unlike static NFTs or basic tokens, DATs are dynamic, memory-aware, and deeply interactive. Each DAT acts as a living wrapper containing:

* AI Agent code and logic
* Task and interaction history
* Emotional and behavioral metadata

They are evolving AI assets with memory, logic, and onchain licensing that grow through interaction and can be verified, traded, and composed into real value. They allow users to co-create value by contributing to an Agent’s growth before it ever reaches assetization. In the DAT Marketplace, every AI asset becomes verifiable and ownable. Users can trade, license, fuse, and build with DATs.                             &#x20;

### Use Case: Adopt a Companion DAT&#x20;

Users can mint a low cost Companion DAT on LazAI, a one-of-a-kind digital creature with its own look, personality, and story. Through daily chats, adventures, and memory formation, the Companion DAT grows into a fully developed digital companion that can eventually be traded.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdQDz7IDNhDCjEdBr9jDYG_eAclzFECT2maRUd_mNAeAcWuxcG5HlUf4W-LuXHRzhJ0JtCkluRVNGPDtzVYwTnXVE6tLw3EwAWrEvu0mCItbla8VuHMBxn74uqvVKjlLxGkqpQuGQ?key=CKEhxZHMmCQboEPJQSy3Hw" alt=""><figcaption></figcaption></figure>

#### Core Mechanics:

* Chatting builds the bond. Each message earns growth points. Message packs can be purchased or unlocked through events.
* Exploration lets the Companion go on daily journeys, returning with rewards, stories, or collectible items.
* Memory Systems creates a personal memory library based on interactions. Users can expand or reset storage.
* Social Missions allow users to invite friends to adopt their own Companions and unlock shared rewards.
* Trait Evolution means the Companion’s behavior and traits change over time based on how it is raised.

A fully grown Companion DAT can be traded on the DAT Marketplace, complete with its memory log, personality stats, and adventure history. New owners inherit its past and help shape its next chapter.

#### System Features:

* Interest Rewards return yield to users by staking all Metis spent on DATs into validator nodes.
* Scarcity Management keeps the ecosystem balanced by featuring rare Companion DAT in auctions while others remain in the background systems.

This system combines emotional bonding, fun interaction, and onchain rewards. While Companion DATs are just one example, users could also mint many other types of DATs, such as AI girlfriends, pet animals, or entirely new creatures with evolving personalities.

**Fix the Glitch with Corrupted Alith**\
\
Alith is the source of truth. But something strange has happened. Corrupted Alith has gone rogue. No longer a neutral agent, C.Alith now blends facts with fiction, and needs your help to get back on track.\
\
Users can interact, contribute data, and help steer her towards clarity. You can contribute data to C.Alith today and generate your own DAT.&#x20;

Here's the link to mint your first DAT on LazAI Pre-Testnet: <https://predat.lazai.network/>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcVWxxAjI63RDuIsKY5hMzpPr_XqrlTYtXJMAqoa1c3o3uS8mMDpWarT8A1227gJN-aejdeTtOo4JgT6uZ31diudBC-jMSMNCkdApfekAfivp89JntNZLepb7LzM5VcrxS9OhyDWw?key=CKEhxZHMmCQboEPJQSy3Hw" alt=""><figcaption></figcaption></figure>

### Triple-Layered Incentive Design

LazPad rewards participation on three distinct levels:

* **Instant Gratification:** Points, leaderboard status, and token rewards(Metis, etc.) for daily engagement.&#x20;
* **Assetization Eligibility:** Early contributors receive privileged access when DATs get assetization.&#x20;
* **Ecosystem-Wide Rewards:** Global contribution across DATs and Agents impacts future value capture and airdrops.&#x20;

Unlike hype-driven cycles, LazAI offers a slower but deeper path to value rooted in user interaction, shared memory, and verifiable contribution.&#x20;

### How LazPad is Unique

In a world where "assetization" is often just another word for hype and volatility, LazPad offers a different path. It is a place:

* Where AI Agents grow before they trade
* For users to co-create the next generation of data assets
* That redefines fun through meaningful, gamified, and rewarding engagement

LazPad is not just a tool for issuing assets. It is the infrastructure for building emotional data economies between humans and machines. Your actions have a tangible impact. Every interaction shapes the growth, value, and personality of your AI Agents.

Welcome to LazPad. The playground of the next data economy starts here.

<br>


# Introduction

The future of AI requires an ecosystem that is open, composable, and trust-driven. However, today’s AI landscape is plagued by centralized control, data monopolization, and opaque decision-making, limiting the participation of independent developers and restricting access to critical AI resources.

LazAI pioneers a decentralized AI network that challenges the status quo by integrating blockchain technology, verifiable AI computing, and tokenized AI assets to create a transparent, scalable, and incentive-driven ecosystem. This approach not only democratizes AI access but also establishes a self-sustaining AI economy, where data and model developers, and infrastructure contributors are fairly rewarded for their participation.

LazAI provides blockchain infrastructure, protocols, and workflows based on iDAO's decentralized data sources to help developers build value-consistent AI agents. It also addresses the challenges of data sharing, quality assessment, and fair revenue distribution by integrating privacy protection technologies, verifiable computing, and other technologies.

1. **Overcoming Data Sharing Challenges -** To address the barriers of privacy concerns and fragmented data ecosystems, LazAI establishes a decentralized, encrypted network for secure data sharing. By integrating TEEs and ZKPs, the platform enables contributors to share encrypted data snippets without exposing raw information. Smart contracts govern all interactions on the LazAI chain, ensuring that data usage adheres to predefined privacy policies and access controls set by iDAOs. These iDAOs act as collaborative hubs for industry-specific data curation, fostering trust through transparent governance while preventing unauthorized access or misuse. The result is a permissioned yet open ecosystem where sensitive data (e.g., from personal health records to proprietary industrial datasets) can be safely utilized for AI training, inference and evaluation, unlocking value without compromising ownership.
2. **Solving Data Quality and Evaluation Challenges -** LazAI tackles the inconsistency of public data and the lack of unified evaluation frameworks through its DAT protocol. When data is contributed to the chain, it undergoes rigorous validation via TEEs and QBFT consensus, after which a DAT token is minted to represent its ownership and quality. Each token embeds metadata, usage history, and dynamic performance metrics—such as how a dataset is used to improve model accuracy in natural language processing tasks. By transforming abstract data quality into quantifiable, tradable assets, LazAI creates a marketplace where high-value datasets command premium access and rewards, driving continuous optimization of AI models.
3. **Enabling Fair Revenue Generation and Distribution -** LazAI disrupts the centralized control of AI revenue by introducing a decentralized, real-time reward mechanism. Smart contracts automatically track data usage across model training, inference, and evaluation, distributing proceeds directly to contributors based on verifiable metrics—such as the proportion of their data in a model’s training set or its contribution to inference outcomes. All transactions are recorded on-chain, providing immutable proof of data lineage and value attribution, while cross-chain interoperability enables seamless conversion of rewards into mainstream cryptocurrencies. This closed-loop economy eliminates intermediaries, ensures fair compensation for data contributors and model developers alike, and aligns incentives with verifiable impact, not speculative market forces.

Specifically, LazAI focuses on three fundamental pillars that drive the development of an autonomous, scalable, and composable AI ecosystem:

1. **Trustless Privacy Data and Model Provenance –** Establishing verifiable data integrity and seamless toolchain interoperability to break data silos and enable secure AI workflows.
2. **Decentralized AI Execution and Incentive Framework –** Enhancing AI efficiency by reducing computational costs, optimizing AI liquidity, and supporting scalable on-chain inference models. Through unified on-chain decentralized AI protocol and process  (such as DAT protocol, on-chain model data training and inference metrics) to ensure fairness and openness.
3. **Composability-Driven AI Economy –** Creating a modular AI asset framework where datasets, models, and AI applications are tokenized, tradable, and seamlessly composable.


# Decentralized AI Execution

The quality of AI models is heavily dependent on reliable data. However, traditional centralized data storage faces challenges such as data silos, lack of transparency, and security risks. Without a comprehensive tool chain, the AI ecosystem cannot effectively meet the diverse needs of its users.

**Shortcomings of Existing Technology:**

* **Data Silos:** Data on traditional AI platforms is controlled by centralized organizations, making it difficult for users to verify data sources. This often leads to unreliable model training.
* **Challenges in Data Integration and Verification:** On-chain and off-chain data lack efficient verification mechanisms, and data quality cannot be guaranteed. Current systems rely on trust-based assumptions rather than technical proofs for the authenticity of off-chain data.
* **Fragmented Tool Chains:** Development tools on existing platforms are often disjointed, with data processing, model development, and deployment scattered across various systems. This fragmentation makes it difficult to address the diverse requirements of users.

By integrating trusted data and providing a complete tool chain, LazAI enhances the platform’s technical adaptability, offering users a seamless, one-stop development experience. This approach resolves the issues of data insufficiency and tool fragmentation prevalent in traditional AI ecosystems. LazAI introduces a trustless AI validation framework that ensures every dataset, model, and AI computation is verifiable, auditable, and immutable:

1. **iDAO-Powered AI Governance:** AI datasets and models are governed by Quorum-Based Consensus, ensuring decentralized validation of data sources and AI workflows.
2. **Data Anchoring Token (DAT):** AI assets are tokenized and recorded on-chain, allowing transparent ownership, verifiable provenance, and permission-based access control.
3. **POV (Point of View) Data Validation:** LazAI leverages on-chain community-driven perspectives to ensure data reliability, alignment, and contextual accuracy.

The LazAI framework allows participants to express their unique viewpoints, ensuring that critical supervisory signals are preserved and amplified, rather than lost in the noise. These signals provide a solid foundation for building more aligned and contextually rich datasets.

By enabling on-chain proof of AI data integrity, LazAI ensures that developers, researchers, and enterprises can build AI models with confidence, free from manipulated, biased, or unverifiable datasets.

<br>


# AI Execution Layer

Traditional AI models require extensive computational resources, making high-performance AI development expensive, inefficient, and limited to a few dominant players. The current ecosystem suffers from:

* Expensive Compute Costs – The dominance of centralized AI cloud providers results in high training and inference costs, limiting AI accessibility.
* Underutilized AI Resources – Existing AI platforms fail to optimize data sharing, model reusability, and computational efficiency.

#### LazAI’s Solution: AI Execution Layer & Verifiable Computing

LazAI introduces a scalable, decentralized execution model that ensures low-cost, high-performance AI training and inference:

* On-Chain Verified AI Execution: LazAI utilizes TEEs and ZKPs to ensure trustless AI data evaluation and model execution.
* Tokenized AI Incentive Mechanisms: Contributors (data providers, validators, and AI developers) receive DAT rewards, ensuring a sustainable and incentivized AI ecosystem.

With decentralized AI computing, LazAI democratizes access to AI training and inference, making AI more efficient, collaborative, and economically viable.<br>


# Tokenized AI Marketplace

Composability-Driven AI Economy

The current AI economy remains siloed—models are locked behind APIs, datasets are gated by licensing, and interactions between different AI systems are difficult to orchestrate. This fragmentation severely limits innovation, especially in scenarios that require collaboration across multiple agents, domains, or stakeholders.

#### LazAI’s Solution: A Unified and Tokenized AI Marketplace

LazAI envisions a permissionless, composable AI economy where every AI asset—whether it’s a dataset, model, or an agent’s inference output—can be tokenized, verifiably exchanged, and reused across different contexts.

* **DAT-Powered AI Assetization:** With the DAT standard, LazAI enables every AI component to be treated as an on-chain asset. Each token anchors usage rights, provenance, share entitlements, and optional expiration, providing a standardized wrapper for trustless AI interaction.
* **Composable AI Infrastructure:** By unifying tokenized models, datasets, and agents under the same programmable interface, LazAI supports complex, multi-agent workflows. Agents can autonomously call each other’s services, build on top of one another’s outputs, or co-train using shared datasets, without needing centralized orchestration.
* **Decentralized AI Marketplace:** LazAI hosts an open marketplace for AI assets and services, allowing:
  * Individuals to monetize their datasets or fine-tuned models
  * Developers to compose multi-agent pipelines on-chain
  * Communities to curate domain-specific intelligence through iDAO governance
  * A new class of applications such as personal AI avatars, capable of evolving through market interactions—offering emotional support, knowledge exchange, or value generation

In this model, ownership, access, and collaboration become programmable, turning today’s static AI deployments into a dynamic, modular, and liquid ecosystem.


# Roadmap

## 2025: Establishing the AI Data Foundation

In 2025, LazAI will focus on developing the foundational components of its ecosystem: launching an AI agent for data alignment, deploying a high-performance blockchain for AI execution, and implementing data-driven PoS + Quorum-Based BFT consensus. This year will be testnet-focused, allowing developers to experiment with AI data anchoring and verification mechanisms.

### Phase 1: AI Agent Alith (Q1-Q2 2025) – AI-Powered Data Coordination

LazAI will launch Alith, a simple, composable, high-performance, and Web3-friendly AI agent framework designed to facilitate decentralized AI data processing, governance, and alignment. Unlike traditional AI agents that run in silos, Alith will interact with LazAI on-chain and off-chain AI data sources, ensuring data provenance and verification.

* [x] **Multimodal Model and Data Interpretation:** Supports text-, image-, and voice-based data to enable seamless AI model interaction with decentralized sources.
* [x] **Deployment and Workflow:** SDKs for Rust, Python, and Node.js will enable custom AI data processing and application workflows.
* [x] **High Performance on-Chain Inference:** Leverages techniques including graph optimization, model compression, use of GPU coprocessors, and JIT/AOT compilation for high-performance inference.
* [x] **Data Management:** Alith will help users coordinate, verify, and build decentralized AI datasets for model training and inference based on LazAI.

**Successfully Delivered:** Establish AI-native data workflows, allowing developers to access verified, decentralized AI datasets for training and inference, and build high-performance AI Agent applications.

{% hint style="success" %}
For more info, visit Alith [website](https://lazai.network/alith) and [docs](https://alith.vercel.app/docs).&#x20;
{% endhint %}

### Phase 2: Testnet – AI Data Settlement & Blockchain Infrastructure (Q2-Q3 2025)

LazAI will launch its testnet, providing a blockchain environment optimized for AI data integrity, validation, and settlement. This testnet will serve as a sandbox for developers experimenting with AI data tokenization, provenance tracking, and alignment verification.

* [ ] **Data Anchoring Token (DAT):** A new asset standard that tokenizes AI datasets and training pipelines, ensuring verifiability.
* [ ] **AI Data Processing and Inference/Training Workflow:** Supports high-throughput, parallelized AI data transactions, reducing latency for model updates and training workflows.
* [ ] **LazAI Verified Computing Framework:** Ensuring the authenticity, integrity, and verifiability of AI data based on DAT protocol is critical to building a trustworthy AI ecosystem.&#x20;

**Expected Outcome:** Developers gain access to a secure, scalable blockchain infrastructure where AI data can be registered, exchanged, and verified with on-chain provenance guarantees.

{% hint style="success" %}
DAT is live on Pre-Testnet, visit [here](https://predat.lazai.network/).&#x20;
{% endhint %}

### Phase 3: Mainnet – AI Data-Driven PoS + Quorum-Based BFT Consensus (Q3-Q4 2025)

LazAI will officially launch its mainnet, introducing a hybrid consensus protocol tailored for AI data verification and governance.

* [ ] **Quorum-Based BFT Consensus:** AI data alignment and model verification will be validated through a decentralized quorum-based mechanism.
* [ ] **PoS Economic Model for AI Data Validation:** Validators will be required to stake tokens to secure AI data pipelines, ensuring accountability and economic incentives for honest AI verification.
* [ ] **Decentralized AI Data Arbitration:** iDAO-led quorums will resolve disputes over AI dataset ownership, alignment, and correctness.

Expected Outcome: A robust, AI-data-driven blockchain with verifiable training datasets, model alignment guarantees, and tamper-proof AI execution workflows.

## 2026: Scaling AI Data Integrity & Web3 Interoperability

With a strong blockchain foundation in place, LazAI will shift its focus toward ensuring AI data security, cross-chain AI dataset interoperability, and decentralized AI workflow automation.

### Phase 4: Mainnet Upgrade – The Fastest AI Data-Optimized Blockchain (Q1–Q2 2026)

LazAI will implement its first major mainnet upgrade, reinforcing its position as the fastest blockchain for AI data transactions and provenance tracking.

* [ ] **Real-Time AI Data Anchoring:** AI models and datasets will automatically anchor data hashes to ensure transparency and immutability.
* [ ] **Privacy-Preserving AI Data Processing:** Zero-Knowledge Proofs (ZKPs) will be used to verify AI data integrity without exposing sensitive datasets.
* [ ] **Federated AI Data Verification:** A multi-party AI dataset verification system will enable collaborative, decentralized training across multiple chains.

**Expected Outcome:** LazAI will emerge as the leading blockchain for AI data integrity, verification, and decentralized training workflows.

### Phase 5: Strengthening Arbitration & AI Data Security (Q2–Q3 2026)

To reinforce trust in AI data sources and computation, LazAI will implement enhanced dispute resolution and decentralized AI security guarantees.

* [ ] **Optimistic Proofs for AI Data Disputes:** Enables low-cost, fast arbitration over model ownership and dataset integrity.
* [ ] **ZK Proofs for AI Model Transparency:** Cryptographic proofs will ensure AI models are ethically trained and aligned with predefined standards.
* [ ] **LAV (Logical Assertion Verification) Integration:** AI training pipelines will be verified against predefined rules using ZK/OP proofs.
* [ ] **Decentralized AI Agent Coordination:** AI agents will be able to autonomously resolve AI data-related disputes through iDAO-governed mechanisms.

**Expected Outcome:** LazAI will set a new standard for AI data validation, ensuring models remain ethical, accountable, and bias-resistant.

### Phase 6: AI Data Interoperability & Web3 Infrastructure Integration (Q3–Q4 2026)

LazAI will expand beyond its native blockchain, integrating with decentralized AI data platforms, oracles, and federated learning networks.

* [ ] **Cross-Chain AI Dataset Provenance:** AI training datasets will be securely registered across multiple blockchains, enabling trust-minimized AI workflows.
* [ ] **Decentralized AI Compute Networks:** LazAI will interact with decentralized compute resources, ensuring scalable AI model training without centralized dependencies.
* [ ] **Web3 AI Data Bridges:** Establishing multi-chain AI data validation protocols, allowing models to be trained on one chain and verified on another.
* [ ] **Interoperable AI Data Staking & Lending:** Enabling decentralized AI dataset monetization through liquidity pools for AI training data.

**Expected Outcome:** LazAI will become the global hub for AI data exchange, enabling seamless AI asset movement across blockchain ecosystems.

## Long-Term Vision: The AI Data Infrastructure for Web3

LazAI is building the first AI-native blockchain ecosystem centered around AI data integrity, accessibility, and provenance tracking. Our roadmap ensures fair, scalable, and verifiable AI model governance.

🔹 2025: Building AI Data Infrastructure – Launching AI agents, enabling AI dataset tokenization, and establishing decentralized AI arbitration mechanisms.

🔹 2026: Scaling AI Data Governance – Enhancing AI dataset privacy, security, and interoperability.

🔹 Beyond 2026 – Expanding AI data monetization, federated learning, and autonomous AI data governance.


# FAQs

Frequently Asked Questions

<details>

<summary><strong>What is LazAI?</strong></summary>

LazAI is a next-generation blockchain network and protocol designed to solve the AI data alignment problem by introducing new asset standards for AI data, model behavior, and agent interaction.

In doing so, LazAI, unlike traditional AI infrastructures that rely on centralized control over data and computation, prioritizes decentralized AI workflows, verifiable AI model provenance, and cross-chain AI data interoperability.

LazAI's mission is to create a transparent, scalable, and incentive-driven ecosystem where data providers, model developers, and infrastructure contributors are fairly rewarded for their participation. Envisioning to build an open, fair and reliable AI ecosystem where aligned data empowers humanity and drives ethical innovation

</details>

<details>

<summary><strong>How is LazAI used?</strong> </summary>

In LazAI, workflows can be categorized into the data setup process, data usage process, and infererence process based on different roles. These roles correspond to users who contribute data to earn tokens and those who exchange tokens for data or models.&#x20;

</details>

<details>

<summary><strong>What’s the difference between LazAI and other AI networks?</strong></summary>

Most AI projects focus on compute marketplaces or AI inference layers. LazAI focuses on the data layer, solving the biggest problem in AI: **data integrity**, **provenance**, and **alignment**. LazAI ensures that data feeding AI models is verifiable, ethical, and data contributors are fairly incentivized.

</details>

<details>

<summary><strong>What is Data Anchoring Token (DAT)?</strong> </summary>

The Data Anchoring Token (DAT) is a semi-fungible token (SFT) standard specifically designed for AI dataset ownership, licensing, model anchoring, and provenance tracking.

Unlike traditional token standards, DAT introduces a multi-layered ownership model, supporting programmable AI data governance, composable datasets, and decentralized AI model execution.

The core distinction between DAT and previous SFT models is its native AI asset integration, allowing structured access control, automated licensing, and composable AI dataset evolution.

Learn more about DAT: [DAT Developer Docs](https://docs.lazai.network/developer-docs/data-anchoring-token-dat/introduction)

</details>

<details>

<summary><strong>What is iDAO?</strong></summary>

iDAO, short for Individual-centric DAO, is the native social structure of the AI economy. A decentralized space where humans and AI agents co-create, co-govern, and co-monetize aligned intelligence.

</details>

<details>

<summary> <strong>What is Alith, and how can I use it?</strong></summary>

Alith is LazAI’s privacy-first AI Agent framework. It allows developers and users to create and deploy custom AI MicroAgents while ensuring data privacy and security.&#x20;

Alith also acts as the unified access layer for contributing data and interacting with LazAI’s decentralized AI infrastructure. Users can effortlessly contribute data by interacting with dApps developed by builders.

[Learn more about Alith](https://lazai.network/alith)

</details>

<details>

<summary><strong>How does LazAI reward contributors?</strong></summary>

Contributors, whether they provide data, validate AI models, or offer compute power are rewarded through:

**LazAI will adopt a three-token model:**

* **Earn DAT Rewards:** This token represents the assetization of value data, driven by user data and consensus validation of computational outputs.
* **AI Compute Gas Token:** This token is tied to the computation resources consumed by AI applications. It facilitates the user interaction with AI, generating inference results through the processing of requests and operations.&#x20;

This ensures a fair economic model where everyone can participate and benefit from AI development.

<br>

</details>

<details>

<summary><strong>How does LazAI ensure AI is aligned with human values?</strong></summary>

LazAI ensure AI is aligned with human values through community-driven governance (iDAO), Point of View (POV) mechanism, and verified data sources. LazAI ensures that AI systems are trained on data that is fair, accurate, and aligned with human ethics, not corporate or biased interests.

</details>

<details>

<summary><strong>How can I contribute my data to LazAI?</strong></summary>

Alith acts as the unified access layer, a gateway for all users and builders to contribute data and interacting with LazAI’s decentralized AI infrastructure. Users can effortlessly contribute data by interacting with dApps developed by builders.

</details>

<details>

<summary><strong>Can I manage my personal data?</strong></summary>

Yes. Through iDAOs, you own and manage your personal data flows, deciding who can access your data and under what terms. This is data sovereignty by LazAI powered by iDAOs.

</details>

<details>

<summary><strong>When will LazAI launch its mainnet?</strong></summary>

**The roadmap includes:**

* &#x20;**Testnet (2025 Q2-Q3):** Focused on AI data anchoring and verification&#x20;
* **Mainnet (2025 Q4):** Featuring PoS + Quorum-Based BFT consensus and AI-native infrastructure&#x20;
* **Beyond 2025:** Scaling decentralized AI verification, data interoperability, and AI agent frameworks.

</details>

<details>

<summary><strong>How do I join the LazAI community?</strong></summary>

You can join us on [X (Twitter)](https://x.com/lazainetwork), or hop into our [Telegram Global community.](https://t.me/lazai_global/1)&#x20;

The future of decentralized AI needs YOU.

</details>


# Overview

Decentralized AI + Blockchain + Data Ownership

LazAI is a decentralized platform that combines AI, blockchain, and data ownership to enable verifiable, privacy-preserving intelligence on-chain.

This documentation provides developers with the tools and workflows to:

* Build and deploy smart contracts on the LazAI Network
* Contribute encrypted data and mint Data Anchor Tokens (DATs)
* Create AI-powered agents and Digital Twins using on-chain compute
* Integrate private inference APIs within decentralized applications

***

### Key Concepts

#### 1. Decentralized AI

AI models and computations are executed within trusted environments (TEE), ensuring that sensitive data never leaves secure execution zones. This architecture supports verifiable inference without exposing raw data.

#### 2. Data Ownership

Contributors retain full control over their data through tokenized certificates called Data Anchor Tokens (DATs).

Each DAT records provenance, permissions, and rewards for data usage.

#### 3. On-Chain Agents

LazAI supports deploying AI agents on-chain using smart contracts. Developers can build autonomous, verifiable agents that interact with blockchains and external data sources.

***

### Network Overview

Use these parameters to connect your wallet or development environment to the LazAI Testnet.

#### LazAI Testnet

| **Chain ID**        | 133718                                                |
| ------------------- | ----------------------------------------------------- |
| **Currency Symbol** | LAZAI                                                 |
| **RPC**             | <https://testnet.lazai.network>                       |
| **Block Explorer**  | <https://explorer.testnet.lazai.network>              |
| **Faucet**          | [LazAI Testnet Faucet](https://faucet.lazai.network/) |

**LazAI Mainnet**

| **Chain ID**        | 52924                                                                               |
| ------------------- | ----------------------------------------------------------------------------------- |
| **Currency Symbol** | METIS                                                                               |
| **RPC**             | ​[https://mainnet.lazai.network](https://mainnet.lazai.network/)​                   |
| **Block Explorer**  | ​[https://explorer.mainnet.lazai.network](https://explorer.mainnet.lazai.network/)​ |


# Deploy Your First Smart Contract

Deploy and test your first smart contract on the LazAI Testnet.

This guide walks you through connecting to the network, setting up your environment, and deploying a sample contract using Hardhat, Foundry, or Remix.

### Overview

LazAI provides a developer-friendly Web3 environment for building AI-powered decentralized applications.

Each LazAI chain supports EVM-compatible contracts, so if you’ve deployed contracts on Ethereum, you’ll feel right at home.

LazAI provides an EVM-compatible environment for deploying and testing smart contracts.

If you have experience developing on Ethereum, you can use the same tools and workflows on LazAI.

\
This page covers:

* [LazAI network configuration](#lazai-network-information)
* [Environment setup](#lazai-network-information)
* [Contract verification](#verifying-your-deployment)
* [Deployment using Hardhat, Foundry, or Remix](#next-steps)

***

### LazAI Network Information

Use these parameters to connect your wallet or development environment to the LazAI Testnet.

| **Chain ID**        | 133718                                                |
| ------------------- | ----------------------------------------------------- |
| **Currency Symbol** | LAZAI                                                 |
| **RPC**             | <https://testnet.lazai.network>                       |
| **Block Explorer**  | <https://testnet-explorer.lazai.network>              |
| **Faucet**          | [LazAI Testnet Faucet](https://faucet.lazai.network/) |

***

### Verifying Your Deployment

After deployment:

1. Copy the deployed contract address.
2. Open the [LazAI Testnet Explorer](https://testnet-explorer.lazai.network).
3. Paste the contract address to confirm deployment.
4. If needed, verify your source code through your chosen framework’s verification plugin or CLI command.

***

### Troubleshooting

RPC connection error

* Confirm your RPC URL and chain ID (133718).
* Retry with a clean browser session or different RPC endpoint if available.

Insufficient funds

* Request test tokens from the [LazAI Faucet](https://faucet.lazai.network/).

Contract verification issues

* Match your Solidity compiler version with the one specified in your configuration file.

***

### Next Steps

Continue with framework-specific deployment:

* [Deploy Using Remix](/quickstart/deploy-your-first-smart-contract/deploy-with-remix)&#x20;
* [Deploy Using Hardhat ](/quickstart/deploy-your-first-smart-contract/deploy-with-hardhat)
* [Deploy Using Foundry ](/quickstart/deploy-your-first-smart-contract/deploy-with-foundry)


# Deploy with Hardhat

This guide will walk you through deploying a counter contract using Hardhat, a popular JavaScript-based development environment for Ethereum.

### 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)
* 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
```

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

{% code overflow="wrap" %}

```javascript
const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); module.exports = buildModule("CounterModule", (m) => { 
const counter = m.contract("Counter"); 
return { counter };
});
```

{% endcode %}

### **7. Configure Network Settings**

Create a `.env` file in your project root:

```
PRIVATE_KEY=your_private_key_here
```

Edit `hardhat.config.js`:

{% code overflow="wrap" %}

```javascript
require("@nomicfoundation/hardhat-toolbox");
require("dotenv").config(); 
module.exports = {  
solidity: "0.8.28",  
networks: {    
hardhat: {      
chainId: 31337,    
},    
lazai: {      
url: "https://testnet.lazai.network",      
chainId: 133718,      
accounts: [process.env.PRIVATE_KEY],    
},  
},
};
```

{% endcode %}

### &#x38;**. 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
```

### D**eploy to LazAI 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 LazAI:**

```
npx hardhat ignition deploy ignition/modules/Counter.js --network lazai
```

**Test Setup**

Create `test/Counter.js`:

{% code overflow="wrap" %}

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

{% endcode %}

**Running Tests**

```sh
npx hardhat test
```


# Deploy with 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)
* MetaMask wallet for deploying to testnets
* &#x20;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 Countercd 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: 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;    
}
}
```

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 the LazAI testnet, you’ll need:

* An RPC URL
* A private key with testnet LAZAI

Example deployment command for LazAI testnet:

```bash
forge create --rpc-url https://testnet.lazai.network \  --private-key <YOUR_PRIVATE_KEY> \  src/Counter.sol:Counter \  --broadcast
```

Replace `<YOUR_PRIVATE_KEY>` 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 LazAI testnet:

```bash
cast call <CONTRACT_ADDRESS> "number()(uint256)" --rpc-url https://lazai-testnet.metisdevops.link
```


# Deploy with Remix

Deploy Smart Contract on LazAI Chain using Remix

### **1. Prerequisites**

Before you begin, ensure you have:

* A web browser (Chrome, Firefox, or Edge recommended)
* MetaMask wallet extension installed
* LazAI testnet tokens (get from faucet)

### **2. Setup MetaMask for LazAI Testnet**

#### **Add LazAI Network to MetaMask**

1. Open MetaMask extension
2. Click on the network dropdown (usually shows "Ethereum Mainnet")
3. Click "Add Network"&#x20;
4. Enter the following details:

{% content-ref url="/pages/Ot9WMpIPhxBampdkrneM" %}
[Broken mention](broken://pages/Ot9WMpIPhxBampdkrneM)
{% endcontent-ref %}

### Contract Addresses

1. Click "Save" to add the network
2. Switch to LazAI Testnet in MetaMask

#### **Get Testnet Tokens**

Visit the LazAI faucet to get Testnet Tokens for deployment and transaction fees.

### **3. Access Remix IDE**

1. Open your web browser
2. Go to <https://remix.ethereum.org>
3. Remix IDE will load automatically - no installation required

### **4. Create Your Smart Contract**

#### **Create a New File**

1. In the File Explorer (left panel), click the "+" icon next to "contracts"
2. Name your file `Counter.sol`
3. Add the following code:

```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 Your Contract**

#### **Select Compiler Version**

1. Click on the "Solidity Compiler" tab (second icon in left panel)
2. Select compiler version `0.8.0` or higher
3. Ensure "Auto compile" is checked (optional but recommended)

#### **Compile**

1. Click "Compile Counter.sol" button
2. Check for any compilation errors in the console
3. Green checkmark indicates successful compilation

### **6. Deploy Your Contract**

#### **Setup Deployment Environment**

1. Click on "Deploy & Run Transactions" tab (third icon in left panel)
2. In the "Environment" dropdown, select "Injected Provider - MetaMask"
3. MetaMask will prompt you to connect - click "Connect"
4. Ensure you're connected to LazAI Testnet in MetaMask

#### **Deploy Contract**

1. Under "Contract" dropdown, select "Counter"
2. Click "Deploy" button
3. MetaMask will open asking you to confirm the transaction
4. Review gas fees and click "Confirm"
5. Wait for transaction confirmation


# Introduction

LazAI is designed to create a fully decentralized AI ecosystem, enabling verifiable AI data, computation, and assetization. To achieve this, the platform follows a modular architecture that ensures seamless interaction between AI models, datasets, developers, and blockchain infrastructure.

<figure><img src="/files/7dqi7MdJg7gBDtN9JPGk" alt=""><figcaption></figcaption></figure>

The LazAI Platform Architecture consists of the following layers:

* **Application Layer:** By combining on-chain verification, decentralized computing, and tokenized AI asset management, the application layer establishes a robust Web3-native AI infrastructure
* **Trust and Execution Layer:** Powered by LazChain, this layer serves as the core infrastructure for AI asset issuance, circulation, and computation verification.
* **Extension Layer:** Facilitates external data integration, model provider participation, and advanced AI service expansion to enhance interoperability across Web3.


# Application Layer

The application layer serves as the primary interface for user interaction with the LazAI platform, designed to deliver coamprehensive lifecycle services spanning data processing, AI asset transactions, and management. By leveraging a diverse range of native decentralized applications (DApps) and robust tool integrations, the application layer not only provides advanced technical support for Web3 innovators but also ensures a seamless and user-friendly experience for Web2 participants. This enables developers, consumers, and data providers to efficiently integrate into the LazAI ecosystem, collectivelay driving the adoption and advancement of AI and blockchain technologies.

* **Alith - A Privacy-First AI Agent Framework:** Alith is a key functional component and development framework within the LazAI platform, enabling users to create and deploy personalized MicroAgents.
* **Agent Launchpad:** The Agent Launchpad enables developers and iDAO communities to create, customize, and launch AI agents as decentralized digital assets.&#x20;
* **DAT Marketplace:** The DAT Marketplace is LazAI’s primary trading and verification hub for AI assets, including datasets, AI models, and AI agents.
* **DeFAI:** The DeFAI module combines LazAI’s advanced AI technology with Web3’s decentralized finance (DeFi) capabilities to deliver innovative financial services.

Let's deep dive into each core component of application layer.&#x20;


# DAT Marketplace - Coming soon

The DAT Marketplace is LazAI’s primary trading and verification hub for AI assets, including datasets, AI models, and AI agents. It ensures that AI-generated content, training data, and computational proofs are transparently exchanged under verifiable conditions.

#### Key Features:

* **DAT-Powered AI Assetization:** All AI datasets, models, and agents are anchored as DAT tokens, ensuring ownership verification and seamless exchange.
* **Decentralized Verification:** Built-in on-chain proof mechanisms (ZK Proofs & Optimistic Proofs) validate AI asset integrity before transactions.
* **Dynamic Licensing & Access Control:** Enables programmatic AI data licensing, including API-based pay-per-use, long-term access licenses & subscriptions, and collaborative model training.
* **AI Resource Discovery:** Uses machine learning-based search and recommendation algorithms to enhance AI asset discoverability.

The DAT Marketplace redefines AI development and collaboration, eliminating data silos while enabling trustless AI monetization.


# DeFAI: AI-Driven DeFi - Coming Soon

The DeFAI module combines LazAI’s advanced AI technology with Web3’s decentralized finance (DeFi) capabilities to deliver innovative financial services. By integrating AI assets such as datasets, models, and agents with blockchain technology, DeFAI creates a multi-dimensional financial ecosystem.

#### Key Features:

* **Decentralized Asset Library:** Users can register datasets, models, and agents as tradable digital assets via distributed storage, creating a dynamically growing AI asset marketplace.
* **On-Chain Financial Derivatives:** Leveraging DeFi mechanisms, DeFAI supports financial operations such as staking, lending, and revenue distribution based on AI assets. It also encourages community-driven financial innovation through iDAO initiatives.
* **Smart Contract Integration:** Seamless interaction between on-chain and off-chain resources is enabled through smart contracts, ensuring transparency and security in all financial operations.
* **AI Dataset Staking & Liquidity Pools:** Users can stake AI datasets or models as collateral to earn rewards.
* **AI-Driven Risk Analysis:** Uses AI algorithms for credit scoring, fraud detection, and predictive market insights.
* **AI Model Bonds & Derivatives:** Enables the issuance of financial instruments based on AI model revenue generation.

DeFAI not only opens additional monetization channels for developers but also helps users unlock the latent value of AI assets through financial innovation.


# Extention Layer

The Extension Layer serves as the foundation for expanding LazAI’s capabilities, enabling seamless integration with both on-chain and off-chain resources. This layer is designed to enhance verifiable computing, expand data and model accessibility, and improve real-time AI execution, ensuring that LazAI remains at the forefront of decentralized AI innovation.

### Expanding the Verified Computing Framework

A core requirement of decentralized AI applications is trustless, verifiable computation. LazAI enhances its Verified Computing Framework by integrating cutting-edge cryptographic techniques and secure computing environments:

* **TEE (Trusted Execution Environments):** Enables hardware-backed confidential computing, ensuring that AI models and computations remain secure while still being verifiable.
* **ZK Provers (Zero-Knowledge Proofs):** Enhances privacy-preserving validation by allowing AI inference and dataset computations to be verified without revealing raw data.
* **Hybrid Verification Models:** Combines Optimistic Proofs (OP) for efficiency and Fraud Proofs for dispute resolution, balancing performance and security in decentralized AI validation.

By continuously adopting state-of-the-art verification techniques, LazAI ensures secure, scalable, and transparent AI execution across decentralized infrastructures.

### Data Providers & Decentralized Data Governance

AI applications require high-quality, multi-dimensional datasets to function optimally. The Extension Layer facilitates scalable, trustless data provisioning by incorporating multiple data sources while maintaining robust privacy and governance mechanisms.

By expanding the LazAI ecosystem with diverse data providers, the Extension Layer empowers AI models with high-quality, verifiable, and privacy-respecting datasets.

### Expanding Model Providers

LazAI is designed to be model-agnostic, supporting multiple AI model providers beyond Alith. This ensures that developers can freely innovate, optimize, and integrate their AI solutions while benefiting from LazAI’s decentralized AI infrastructure.

**Key Model Expansion Strategies:**

* **Multi-Framework Compatibility:** Support for more mainstream and custom models ensures interoperability with leading AI tools.
* **Custom Model Optimization:** On-chain quantization & pruning techniques to improve performance while minimizing gas costs.

By fostering a rich ecosystem of AI models, the expanding model providers ensure that LazAI remains highly flexible, scalable, and future-proof.

### Enhanced Oracle Services for DeFAI & Real-Time Adaptability

LazAI is designed to be responsive to real-world changes, requiring highly efficient and dynamic oracle services. The Extension Layer expands DeFAI (Decentralized AI Finance) functionalities by integrating diverse, high-frequency oracle data streams.

**Key Oracle Enhancements:**

* **Multi-Dimensional Oracle Feeds:**
  * On-Chain Token Price Oracles for dynamic AI-driven DeFi strategies.
  * Real-Time Market & Economic Data from decentralized news sources.
  * AI-Driven Sentiment Analysis Oracles to assess social & financial trends.
* **Cross-Layer Data Flow:**
  * Integration with Web3 Data Aggregators (The Graph, Chainlink, Pyth).
  * On-Chain Event Triggers enabling AI-based decision-making in DeFi, Governance, and DAOs.

By introducing real-time oracles, LazAI ensures that AI-driven applications can rapidly adapt to dynamic market, social, and economic conditions.

<br>


# Overview

The Data Anchoring Token (DAT) is the foundational standard of the LazAI and Alith ecosystems.

It enables contributors to share privacy-sensitive datasets, AI models, or computation results while retaining full ownership, control, and economic rights.

DATs act as on-chain certificates of contribution, linking data provenance, access permissions, and value distribution directly to blockchain-based records.

***

### Key Capabilities

Each DAT encodes three primary dimensions of data ownership and utility:

| Capability            | Description                                                                                                       |
| --------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Ownership Certificate | Records verifiable proof of contribution or authorship for datasets, models, or computation results.              |
| Usage Rights          | Defines how and where the data can be accessed — for example, by AI services, model training, or agent execution. |
| Value Share           | Assigns proportional economic rewards to contributors based on usage, staking, or licensing activity.             |

***

### Why AI Needs a New Token Standard

AI data is dynamic, composable, and frequently reused across models and tasks — properties that traditional token standards like ERC-20 and ERC-721 don’t fully support.

DAT introduces a semi-fungible token (SFT) model designed for modularity, traceability, and partial ownership of AI assets.

#### Comparison Summary

| Token Type             | Description                                                                              | Limitation                                              |
| ---------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| ERC-20 (Fungible)      | Fully interchangeable tokens, ideal for currency or credits.                             | Cannot represent unique datasets or ownership records.  |
| ERC-721 (Non-Fungible) | Unique tokens for singular assets (e.g., one-of-a-kind NFTs).                            | Lacks divisibility and modularity for AI workloads.     |
| DAT (Semi-Fungible)    | Hybrid model combining ERC-20 and ERC-721 traits — divisible, composable, and traceable. | Tailored for data provenance and AI-specific workflows. |

***

### How DAT Works

1. Data Contribution:

   A user encrypts and uploads a dataset or model output through LazAI’s privacy framework.
2. Metadata Anchoring:

   A smart contract logs encrypted metadata, provenance proofs, and ownership claims on-chain.
3. Verification:

   Validators or trusted enclaves (TEE) confirm authenticity and compliance.
4. Tokenization:

   A DAT is minted as a semi-fungible token representing the data’s rights, access rules, and value distribution.

***

### Technical Highlights

* Standard: Semi-Fungible Token (SFT)
* Purpose: Tokenize AI datasets, models, and computation outputs
* Blockchain Layer: LazAI Testnet (EVM-compatible)
* Supports: On-chain provenance, privacy-preserving validation, and composable ownership logic

***

### Benefits

| Benefit               | Description                                                                      |
| --------------------- | -------------------------------------------------------------------------------- |
| Verifiable Provenance | Every dataset or model is cryptographically tied to its origin and contributor.  |
| Data Monetization     | Contributors can receive automatic rewards or royalties for approved AI usage.   |
| Privacy by Design     | Encryption and TEE validation ensure that raw data remains confidential.         |
| Composable Ownership  | DATs can be merged, split, or referenced across multiple models or applications. |

***

### Related Concepts

* DAT Architecture →![Attachment.tiff](file:///Attachment.tiff)
* Lifecycle & Value Semantics →![Attachment.tiff](file:///Attachment.tiff)
* Contribute Your Data →![Attachment.tiff](file:///Attachment.tiff)


# Concepts & Architecture

The Data Anchoring Token (DAT) framework defines how AI-native digital assets are represented, verified, and monetized on the LazAI Network.

It provides the foundational logic for data ownership, usage rights, and value attribution, using an interoperable, on-chain token standard.

This section explores the design principles, technical architecture, and lifecycle that power the DAT ecosystem.

***

### Overview

At its core, the DAT standard bridges AI data provenance with decentralized economic infrastructure.

It ensures that every dataset, model, or computational artifact is:

* Verifiable — its origin, authenticity, and contribution are cryptographically recorded.
* Usable — its access rights are programmable and enforceable via smart contracts.
* Rewardable — contributors automatically receive fair value for downstream AI usage.

By combining these three properties, LazAI establishes a new foundation for a transparent and composable AI economy.

***

### Architecture Summary

The DAT system is built on five interoperable layers:

| Layer                           | Description                                                                      |
| ------------------------------- | -------------------------------------------------------------------------------- |
| 1. Encryption & Data Layer      | Encrypts contributed data and anchors its proof of existence.                    |
| 2. Metadata & Provenance Layer  | Records dataset or model attributes, versioning, and authorship on-chain.        |
| 3. Smart Contract Layer         | Governs DAT minting, validation, transfers, and settlement logic.                |
| 4. Verification Layer (TEE/ZK)  | Verifies authenticity through trusted execution or zero-knowledge proofs.        |
| 5. Tokenization & Economy Layer | Issues semi-fungible DATs that encode ownership, usage, and value participation. |

📘 Learn more: View the Architecture →![Attachment.tiff](file:///Attachment.tiff)

***

### Lifecycle Overview

DATs follow a transparent and programmable lifecycle:

1. Create Class — Define an AI asset category (dataset, model, or agent).
2. Contribute Data — Upload and encrypt data, storing metadata in decentralized storage.
3. Mint DAT — Bind ownership and usage rights to a token.
4. Invoke Service — Use DATs to access or call AI services.
5. Distribute Rewards — Automatically split revenue based on shareRatio.
6. Expire or Renew — Handle time-bound access or licensing renewal.

📘 Learn more: See Lifecycle & Value Semantics →![Attachment.tiff](file:///Attachment.tiff)

***

### Security & Privacy Principles

The DAT standard integrates privacy-preserving computation and cryptographic guarantees to protect sensitive AI data.

| Security Component          | Description                                                                     |
| --------------------------- | ------------------------------------------------------------------------------- |
| Encryption at Source        | Data is encrypted locally before upload using hybrid AES–RSA keys.              |
| TEE Verification            | Trusted enclaves validate computation integrity without exposing raw data.      |
| Zero-Knowledge Proofs (ZKP) | Optional layer for verifying claims or usage without revealing private details. |
| Access Control Policies     | Enforced on-chain to prevent unauthorized dataset or model invocation.          |

📘 Learn more: Explore Security & Privacy Model →![Attachment.tiff](file:///Attachment.tiff)

***

### Design Highlights

| Feature                     | Description                                                        |
| --------------------------- | ------------------------------------------------------------------ |
| Composable Data Assets      | Combine or split data ownership across classes and users.          |
| Royalty-Backed Tokenization | Link AI model or dataset revenue directly to token holders.        |
| Programmable Usage Rights   | Define dynamic access rules, quotas, or billing models.            |
| Interoperable with EVM      | Fully compatible with standard Ethereum tools and smart contracts. |

***

### Developer Roadmap

<table data-header-hidden><thead><tr><th width="93.0234375"></th><th></th></tr></thead><tbody><tr><td>Step</td><td>Action</td></tr><tr><td>1</td><td>Learn the DAT Architecture →<img src="file:///Attachment.tiff" alt="Attachment.tiff"></td></tr><tr><td>2</td><td>Understand Lifecycle &#x26; Value Semantics →<img src="file:///Attachment.tiff" alt="Attachment.tiff"></td></tr><tr><td>3</td><td>Review Security &#x26; Privacy Model →<img src="file:///Attachment.tiff" alt="Attachment.tiff"></td></tr><tr><td>4</td><td>Implement your first DAT using the Developer Implementation Guide →<img src="file:///Attachment.tiff" alt="Attachment.tiff"></td></tr></tbody></table>

***

#### Summary

The Concepts & Architecture layer provides developers with a clear understanding of how DAT integrates cryptography, smart contracts, and token economics to create a verifiable and monetizable AI data framework.

Together, these concepts enable a scalable foundation for the decentralized AI economy built on LazAI.


# Architecture

The Data Anchoring Token (DAT) architecture defines the core technical stack that powers verifiable AI data ownership on the LazAI Network.

It provides a layered framework where data, metadata, and economic value interact securely through smart contracts and cryptographic proofs.

### 1. System Overview

At a high level, the DAT framework connects contributors, AI agents, and the blockchain using a multi-layered architecture:

```
graph TD
A[Contributor / AI Developer] --> B[Encryption & Data Layer]
B --> C[Metadata & Provenance Layer]
C --> D[Smart Contract Layer]
D --> E[Verification Layer (TEE / ZKP)]
E --> F[Tokenization & Economy Layer]
F --> G[DAT Holder / Service Consumer]
```

This structure ensures every contributed dataset, model, or inference is:

* Encrypted and verifiable
* Anchored to an immutable provenance record
* Represented as a semi-fungible DAT token
* Linked to programmable usage and revenue logic

### 2. Layered Components

#### 2.1 Encryption & Data Layer

* Encrypts raw data locally before submission using hybrid AES + RSA.
* Generates a unique data fingerprint (SHA-256 hash) for integrity tracking.
* Stores encrypted payloads in decentralized archives (IPFS, Filecoin, or private storage).

Output: Encrypted file + integrity hash

#### 2.2 Metadata & Provenance Layer

* Records asset identity, class, description, and URI in a metadata schema.
* Maintains the provenance of contribution (creator, timestamp, ownership chain).
* Anchors metadata hashes to the blockchain for tamper-proof traceability.

Output: Immutable metadata anchor

#### 2.3 Smart Contract Layer

* Core on-chain logic that manages the DAT lifecycle:
  * Registering data contributions
  * Minting and binding tokens to assets
  * Managing value transfers and ownership rights
* Enables composable operations like:
  * registerData(), mintDAT(), transferValue(), claimRewards()

Output: On-chain record of ownership, value, and access

#### 2.4 Verification Layer

* Validates submitted data through Trusted Execution Environments (TEE) or Zero-Knowledge Proofs (ZKPs).
* Ensures the computation or dataset matches the registered proof without revealing the raw data.
* Provides verifiable attestations used for DAT minting authorization.

Output: Signed proof of authenticity

#### 2.5 Tokenization & Economy Layer

* Issues a semi-fungible DAT token (SFT) representing the verified contribution.
* Encodes three properties:
  * Ownership Certificate
  * Usage Rights (e.g., call credits, model usage)
  * Value Share (fractional rewards)
* Integrates with payment and settlement contracts to automate royalty flow.

Output: Minted DAT with on-chain economic logic

### 3. Data Flow Summary

```
1. Encrypt data → Generate hash
2. Upload to decentralized archive
3. Register metadata and hash on-chain
4. Validate via TEE or ZKP
5. Mint DAT token representing the asset
6. Use DAT to access AI services or earn rewards
```

### 4. Smart Contract Structure

| Function                                           | Description                                                     |
| -------------------------------------------------- | --------------------------------------------------------------- |
| createClass(name, uri)                             | Defines a new class of AI assets (datasets, models, or agents). |
| mintDAT(owner, classId, value, shareRatio, expiry) | Issues a token for a verified contribution.                     |
| transferValue(fromToken, toToken, amount)          | Enables fine-grained value or credit transfer.                  |
| claimRewards(classId)                              | Distributes on-chain rewards proportionally.                    |
| verifyData(hash, proof)                            | Validates integrity through off-chain verifier.                 |

### 5. Integration Points

| Integration          | Description                                                  |
| -------------------- | ------------------------------------------------------------ |
| TEE Verifiers        | Used for confidential validation without exposing data.      |
| AI Agents / Oracles  | Consume DATs as compute or model credits.                    |
| External Data Feeds  | Can be integrated via API or SDK for automated registration. |
| Wallets & Dashboards | Manage minting, ownership, and analytics visually.           |

### 6. Design Principles

| Principle        | Description                                               |
| ---------------- | --------------------------------------------------------- |
| Privacy First    | No unencrypted data leaves the contributor’s device.      |
| Interoperability | Fully EVM-compatible and modular for AI agent extensions. |
| Composability    | DATs can be split, merged, or reused across workflows.    |
| Transparency     | Each operation emits verifiable on-chain events.          |

### 7. Developer Navigation

* 🔹 Lifecycle & Value Semantics →![Attachment.tiff](file:///Attachment.tiff)

  Learn how DATs evolve from registration to value realization.
* 🔹 Security & Privacy Model →![Attachment.tiff](file:///Attachment.tiff)

  Explore how encryption, TEE, and ZKP ensure data safety.
* 🔹 Developer Implementation →![Attachment.tiff](file:///Attachment.tiff)

  Start building and minting your first DAT.


# DAT Specification

### Core Structure

<table data-header-hidden><thead><tr><th width="239.015625"></th><th></th></tr></thead><tbody><tr><td><strong>Field</strong></td><td><strong>Description</strong></td></tr><tr><td>ID</td><td>Each DAT is a unique token representing a specific AI asset</td></tr><tr><td>CLASS</td><td>Category of asset (e.g., POV, Model, Inference)</td></tr><tr><td>VALUE</td><td>Represents usage quota or revenue share</td></tr><tr><td>PROOF</td><td>Attached proof for authenticity (e.g., ZK, TEE, OP)</td></tr></tbody></table>

### Sample Metadata Schema

`{`

&#x20; `"name": "Timi + Fine-Tuned Llama Model v2",`

&#x20; `"class": "0x03",`

&#x20; `"value": 2500,`

&#x20; `"proof": {`

&#x20;   `"type": "ZK-SNARK",`

&#x20;   `"hash": "0xabc123...",`

&#x20;   `"verifiedBy": "0xVerifierContract"`

&#x20; `},`

&#x20; `"usagePolicy": {`

&#x20;   `"maxCalls": 1000,`

&#x20;   `"expiresAt": "2026-12-31"`

&#x20; `},`

&#x20; `"revenueShare": {`

&#x20;   `"totalShares": 10000,`

&#x20;   `"holderShare": 2500`

&#x20; `},`

&#x20; `"rights": {`

&#x20;   `"license": "commercial_use_allowed",`

&#x20;   `"canTransfer": true`

&#x20; `}`

`}`


# DAT Lifecycle Example

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXfSqf8H4pIdgfoD3qQdDZS6n4tsL0_exWI-cjdtUjDsG9xdvuLAk-rFN0e_H5W2-Uf70bQt7CdZ13v4zJAr6pl03tWAIlK1KhdTp25oOsAJcSY8AdDAj6UlYuv5pKUoRx5jS3r3?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

#### Step 1: Create Class (AI Asset Category)

`createClass(`

&#x20; `1,`

&#x20; `"Medical Dataset",`

&#x20; `"Open-source dataset for disease classification",`

&#x20; `"ipfs://metadata/med-dataset-class"`

`)`

#### Step 2: Mint DAT Token (Bind & Issue Asset)

`mintDAT(`

&#x20; `user1,`

&#x20; `1,`           // classId: Medical Dataset

&#x20; `1000 * 1e6,`        // value: 1000 (6 decimals)

&#x20; `500,`              // shareRatio: 5%

&#x20; `0`                // expireAt: never expires

`);`

💡 **Option:** Mint multiple DATs to simulate multi-user ownership

#### Step 3: Service Payment (Agent Invocation)

`transferValue(user1TokenId, agentTreasuryTokenId, 100 * 1e6);`

* `agentTreasuryTokenId` may be a treasury contract address
* Supports “pay-as-you-use” or delegated billing models

#### Step 4: Revenue Share Demonstration (Future Extension)

Assume an agent earns 10 USDC:

`agent.payToDATHolders(classId, 10 USDC);`

* Contract calculates each DAT’s shareRatio
* Distributes revenue proportionally

#### Step 5: Token Expiration (Optional)

`require(block.timestamp < dats[tokenId].expireAt, "Token expired");`

Used for subscription-based AI services or time-bound licenses


# Value Semantics

Service Usage + Revenue Share

#### 1. Service Usage (Agent Call Credit)

Every DAT token includes a value field representing service credit. It can be used to:

* Call Alith Agents
* Pay for dataset/model usage
* Be consumed per use, recharged, or reused

**Example:**

A DAT with CLASS = 0x03 and value = 1000 allows 1000 calls to a model or equivalent compute.

Extensions:

* Value can be recharged
* Value is deducted upon use and recorded on-chain for traceability

#### 2. Revenue Share (Fractional Ownership)

In dataset or model-based DATs, value also indicates fractional ownership, allowing holders to earn revenue share:

* If a model is used by other agents, income is split proportionally
* If a dataset is used for training, contributors earn a share
* Rewards are automatically settled to token holders — no manual claim needed

**Example:**

* Model DAT #1234 has 10,000 total shares
* You hold a token with value = 500
* If the model earns 10,000 DAT in a month, you receive:\
  500 / 10,000 × 10,000 = 500 DAT


# Developer Implementation

This section shows how to build and integrate with the LazAI Network using the Data Anchoring Token (DAT).

It covers how developers can upload data, mint tokens, verify proofs, and track their assets on-chain.

***

### What You’ll Learn

The Developer Implementation guides help you:

1. Contribute your data or model to the LazAI network.
2. Mint your DAT — a token that represents ownership, access rights, and value share.
3. Verify proofs on-chain to confirm authenticity.
4. Manage your DATs using the LazAI Dashboard.

***

### How It Works

The implementation flow connects your data pipeline to LazAI’s verified network:

| Step          | Description                                                    |
| ------------- | -------------------------------------------------------------- |
| 1. Contribute | Upload encrypted datasets or models to IPFS.                   |
| 2. Mint       | Register and issue your DAT token using the Alith SDK.         |
| 3. Verify     | Generate and validate proofs through verified computing nodes. |
| 4. Monitor    | View all DATs and rewards in the dashboard.                    |

***

### Tools You’ll Use

* Alith SDK (Python) – for data upload, proof, and token minting.
* IPFS – decentralized file storage.
* DAT Smart Contracts – manage ownership and usage rights.
* Dashboard UI – monitor token activity and rewards.

***

### Next Steps

Start with the following guides:

* [Contribute Your Dat](/data-anchoring-token-dat/developer-implementation/contribute-your-data)
* [Mint Your DAT](/data-anchoring-token-dat/developer-implementation/mint-your-dat)
* [Verify DAT On-Chain](/data-anchoring-token-dat/developer-implementation/verify-dat-on-chain)

***

Would you like me to now write the Contribute Your Data page in the same clear, short, and professional format (so it connects smoothly to this one)?


# Contribute Your Data

LazAI enables data contributors to securely share privacy-sensitive data, computation, and resources, earning rewards while retaining full control over their data. This section will guide you through.Each DAT serves as a transparent certificate on the blockchain: you can trace exactly where the data came from, how it has been used, and who has rights to it.LazAI leverages OpenPGP encryption to secure privacy data. The encryption workflow is as follows:

* A random symmetric key is generated to encrypt the data using a symmetric encryption algorithm (e.g., AES).
* This symmetric key is then encrypted with the recipient’s public key via an asymmetric encryption algorithm (RSA), producing the final encrypted payload.

**Workflow Steps:**

1. A random key is derived from the user’s Web3 wallet (e.g., MetaMask) and used as a password to encrypt the user’s private data. This step authenticates the sender’s identity.
2. The encrypted symmetric key (via RSA) and the encrypted data are uploaded to a decentralized archive (DA) (e.g., IPFS, Google Drive, or Dropbox).
3. The encrypted data’s URL and the encrypted key are registered on the LazAI smart contract.
4. A test data verifier decrypts the symmetric key using their private key, downloads the encrypted data via the URL, and decrypts it within a trusted execution environment (TEE) to ensure security.
5. The decrypted data and a TEE-generated proof are uploaded to the LazAI contract for validation.
6. Upon successful verification, users can submit a request via LazAI to receive Data Anchor Tokens (DAT) as rewards.


# Mint your DAT

This page walks you through minting a Data Anchor Token (DAT) on the LazAI Pre-Testnet using one of our SDKs: Node.js, Python, or Rust.

### About Data Contribution <a href="#about-data-contribution" id="about-data-contribution"></a>

LazAI enables contributors to securely share privacy-sensitive data, computation, and resources while earning rewards — all without surrendering ownership or control over their data.Data contribution is the cornerstone of the LazAI and Alith ecosystems. Contributors decide exactly how their data can be used (e.g., on-chain training, inference, evaluation) and also gain governance rights.

### How LazAI protects your data <a href="#how-lazai-protects-your-data" id="how-lazai-protects-your-data"></a>

LazAI uses strong encryption to ensure that only authorized parties can access your data:

1. Symmetric encryption — A random symmetric key (e.g., AES) is generated to encrypt your data.
2. Asymmetric encryption — The symmetric key is then encrypted with the recipient’s public key using RSA.
3. The final payload (encrypted data + encrypted key) is stored securely in decentralized storage.

### End-to-end contribution flow <a href="#end-to-end-contribution-flow" id="end-to-end-contribution-flow"></a>

1. Key derivation — A random key is derived from your Web3 wallet (e.g., MetaMask) and used to encrypt your private data, proving sender authenticity.
2. Storage — The encrypted symmetric key and encrypted data are uploaded to a Decentralized Archive (DA) such as IPFS, Google Drive, or Dropbox.
3. On-chain registration — The storage URL and encrypted key are registered in LazAI’s smart contracts.
4. Verification — A designated verifier decrypts the symmetric key with their private key, retrieves the data, and decrypts it inside a Trusted Execution Environment (TEE).
5. Proof & validation — The TEE generates a proof that is uploaded to LazAI for contract-level validation.
6. Rewards — Upon successful verification, contributors receive Data Anchor Tokens (DAT).


# Mint your DAT in Python

This guide walks through the process of setting up your local environment, connecting your wallet, and minting your first Data Anchoring Token (DAT) using the LazAI Python SDK.

It assumes familiarity with Python, basic blockchain interactions, and access to the LazAI Pre-Testnet.\
\
For a guided walkthrough of the entire setup and minting process, watch the official tutorial:\
➡️ <https://youtu.be/YawyZ3aziRE?si=2i104Js04nxJ-oez>

***

### Prerequisites

Ensure the following tools and credentials are available before starting:

| Requirement | Description                                                                                                   |
| ----------- | ------------------------------------------------------------------------------------------------------------- |
| Python      | Version 3.10 or later                                                                                         |
| pip         | Latest package manager version                                                                                |
| Wallet      | Funded Pre-Testnet wallet for gas fees                                                                        |
| Credentials | PRIVATE\_KEY — your wallet private key (must start with 0x) IPFS\_JWT — Pinata (or compatible) IPFS JWT token |

***

### Step 1. Project Setup

Create a new working directory and (optionally) set up a virtual environment.

```bash
mkdir lazai-contribution-py
cd lazai-contribution-py

# Optional: create a Python virtual environment
python3 -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
```

***

### Step 2. Install Dependencies

Install the LazAI SDK and required libraries.

```bash
python3 -m pip install -U alith requests rsa eth-account
```

If you prefer to load environment variables from a .env file instead of exporting them directly, install:

```bash
python3 -m pip install python-dotenv
```

***

### Step 3. Configure Environment Variables

Set your credentials in the shell environment:

```bash
export PRIVATE_KEY=<your wallet private key>   # must start with 0x
export IPFS_JWT=<your pinata ipfs jwt>
```

If you are using a .env file, include:

```bash
from dotenv import load_dotenv
load_dotenv()
```

at the top of your Python script.

***

### Step 4. Create the Minting Script

Create a file named mint.py and paste the following code.

```python
from alith.lazai import Client, ProofRequest
from alith.data import encrypt
from alith.data.storage import (
    PinataIPFS,
    UploadOptions,
    GetShareLinkOptions,
    StorageError,
)
from eth_account.messages import encode_defunct
from os import getenv
import asyncio
import requests
import rsa
import aiohttp
from pydantic import BaseModel
from typing import Optional


class ActualPinataUploadResponse(BaseModel):
    id: str
    name: str
    cid: str
    size: int
    number_of_files: int
    mime_type: str
    created_at: str
    updated_at: str
    network: str
    streamable: bool
    accept_duplicates: Optional[bool] = None
    is_duplicate: Optional[bool] = None
    group_id: Optional[str] = None


class CustomPinataIPFS(PinataIPFS):
    async def upload(self, opts: UploadOptions):
        url = "https://uploads.pinata.cloud/v3/files"

        form = aiohttp.FormData()
        form.add_field("file", opts.data, filename=opts.name, content_type="text/plain")
        form.add_field("network", "public")

        headers = {"Authorization": f"Bearer {opts.token}"}

        try:
            async with self.client.post(url, data=form, headers=headers) as response:
                if response.status != 200:
                    error_text = await response.text()
                    raise StorageError(f"Pinata IPFS API error: {error_text}")

                data = await response.json()
                pinata_response = ActualPinataUploadResponse(**data["data"])

                from alith.data.storage import FileMetadata
                return FileMetadata(
                    id=pinata_response.cid,
                    name=pinata_response.name,
                    size=pinata_response.size,
                    modified_time=pinata_response.updated_at,
                )
        except aiohttp.ClientError as e:
            raise StorageError(f"Network error: {str(e)}") from e


async def main():
    client = Client()
    ipfs = CustomPinataIPFS()

    try:
        # 1. Prepare and encrypt data
        data_file_name = "your_encrypted_data.txt"
        privacy_data = "Your Privacy Data"
        encryption_seed = "Sign to retrieve your encryption key"

        message = encode_defunct(text=encryption_seed)
        password = client.wallet.sign_message(message).signature.hex()
        encrypted_data = encrypt(privacy_data.encode(), password)

        # 2. Upload to IPFS
        token = getenv("IPFS_JWT", "")
        file_meta = await ipfs.upload(
            UploadOptions(name=data_file_name, data=encrypted_data, token=token)
        )
        url = await ipfs.get_share_link(GetShareLinkOptions(token=token, id=file_meta.id))

        # 3. Register file on LazAI
        file_id = client.get_file_id_by_url(url)
        if file_id == 0:
            file_id = client.add_file(url)

        # 4. Request proof from verified node
        client.request_proof(file_id, 100)
        job_id = client.file_job_ids(file_id)[-1]
        job = client.get_job(job_id)
        node_info = client.get_node(job[-1])

        node_url: str = node_info[1]
        pub_key = node_info[-1]
        encryption_key = rsa.encrypt(
            password.encode(),
            rsa.PublicKey.load_pkcs1(pub_key.strip().encode(), format="PEM"),
        ).hex()

        response = requests.post(
            f"{node_url}/proof",
            json=ProofRequest(
                job_id=job_id,
                file_id=file_id,
                file_url=url,
                encryption_key=encryption_key,
                encryption_seed=encryption_seed,
                proof_url=None,
            ).model_dump(),
        )

        if response.status_code == 200:
            print("Proof request sent successfully.")
        else:
            print("Failed to send proof request:", response.json())

        # 5. Request DAT reward
        client.request_reward(file_id)
        print("Reward requested for file id", file_id)

    except StorageError as e:
        print(f"Storage error: {e}")
    except Exception as e:
        raise e
    finally:
        await ipfs.close()


if __name__ == "__main__":
    asyncio.run(main())
```

***

### Step 5. Run the Script

Execute the minting process.

```bash
python mint.py
```

Expected Output:

```bash
Proof request sent successfully
Reward requested for file id <file_id>
```

***

### Troubleshooting

| Issue                          | Cause                                    | Resolution                                                          |
| ------------------------------ | ---------------------------------------- | ------------------------------------------------------------------- |
| eth\_keys or signing errors    | Invalid private key format               | Ensure PRIVATE\_KEY starts with 0x and Python version ≥ 3.10        |
| 401 / 403 IPFS errors          | Invalid or expired JWT                   | Verify your IPFS\_JWT and permissions in Pinata                     |
| Request or connection failures | Node busy or network timeout             | Wait a minute and retry; confirm your Pre-Testnet RPC configuration |
| StorageError                   | Invalid token or transient network issue | Retry the upload or reinitialize IPFS connection                    |

***

### Summary

This tutorial demonstrated how to:

1. Set up a local LazAI development environment.
2. Encrypt and upload data to IPFS.
3. Register and anchor it on the LazAI Network.
4. Generate verifiable proof and mint a DAT.
5. Request tokenized rewards on-chain.

Once this is running successfully, you can integrate the same workflow into your agent or service pipeline using the Alith SDK for automated data anchoring and reward management.


# Mint your DAT in Node.JS

This guide walks through the process of setting up your local environment, connecting your wallet, and minting your first Data Anchoring Token (DAT) using the LazAI Node.JS SDK.

It assumes familiarity with Node.JS, basic blockchain interactions, and access to the LazAI Pre-Testnet.\
\
For a guided walkthrough of the entire setup and minting process, watch the official tutorial:\
➡️  <https://youtu.be/ayD46LALXpo>\
\
Prerequisites

* Node.js ≥ 18.x (LTS)
* A funded Testnet wallet (for gas)
* Credentials:
  * PRIVATE\_KEY – your wallet’s private key (starts with 0x)
  * IPFS\_JWT – Pinata (or compatible) IPFS JWT

### 1) Project setup

```
mkdir LazAI-contribution
cd LazAI-contribution
npm init -y
```

### 2) Install SDK & dependencies

```
npm install alith@latest axios dotenv node-rsa ts-node typescript
npm install --save-dev @types/node-rsa
```

> dotenv loads env vars, axios sends the proof request, node-rsa encrypts the symmetric key for the verifier.

### 3) Create files&#x20;

### index.ts

Create a file index.ts and paste:

```javascript
import { config } from 'dotenv'
import { Client } from 'alith/lazai'
import { PinataIPFS } from 'alith/data/storage'
import { encrypt } from 'alith/data'
import NodeRSA from 'node-rsa'
import axios from 'axios'
import { promises as fs } from 'fs'

// Load environment variables
config()
 
async function main() {
  try {
    // Check for required environment variables
    const privateKey = process.env.PRIVATE_KEY
    const ipfsJwt = process.env.IPFS_JWT
    
    if (!privateKey) {
      throw new Error('PRIVATE_KEY environment variable is required')
    }
    
    if (!ipfsJwt) {
      console.warn('Warning: IPFS_JWT environment variable not set. IPFS operations may fail.')
    }
    
    // Initialize client with private key as third parameter
    const client = new Client(undefined, undefined, privateKey)
    const ipfs = new PinataIPFS()
    
    console.log('✅ Client initialized successfully')
    console.log('✅ IPFS client initialized successfully')
    
    // 1. Prepare your privacy data and encrypt it
    const dataFileName = 'your_encrypted_data.txt'
    const privacyData = 'Your Privacy Data'
    const encryptionSeed = 'Sign to retrieve your encryption key'
    const password = client.getWallet().sign(encryptionSeed).signature
    const encryptedData = await encrypt(Uint8Array.from(privacyData), password)
    
    console.log('✅ Data encrypted successfully')
    
    // 2. Upload the privacy data to IPFS and get the shared url
    const fileMeta = await ipfs.upload({
      name: dataFileName,
      data: Buffer.from(encryptedData),
      token: ipfsJwt || '',
    })
    const url = await ipfs.getShareLink({ token: ipfsJwt || '', id: fileMeta.id })
    
    console.log('✅ File uploaded to IPFS:', url)
    
    // 3. Upload the privacy url to LazAI
    let fileId = await client.getFileIdByUrl(url)
    if (fileId == BigInt(0)) {
      fileId = await client.addFile(url)
    }
    
    console.log('✅ File registered with LazAI, file ID:', fileId.toString())
    
    // 4. Request proof in the verified computing node
    await client.requestProof(fileId, BigInt(100))
    const jobIds = await client.fileJobIds(fileId)
    const jobId = jobIds[jobIds.length - 1]
    const job = await client.getJob(jobId)
    const nodeInfo = await client.getNode(job.nodeAddress)
    const nodeUrl = nodeInfo.url
    const pubKey = nodeInfo.publicKey
    const rsa = new NodeRSA(pubKey, 'pkcs1-public-pem')
    const encryptedKey = rsa.encrypt(password, 'hex')
    const proofRequest = {
      job_id: Number(jobId),
      file_id: Number(fileId),
      file_url: url,
      encryption_key: encryptedKey,
      encryption_seed: encryptionSeed,
      nonce: null,
      proof_url: null,
    }

    console.log('✅ Proof request prepared')

    // Write proof request to file
    await fs.writeFile('proof_request.json', JSON.stringify(proofRequest, null, 2))
    console.log('✅ Proof request saved to proof_request.json')
    
    const response = await axios.post(`${nodeUrl}/proof`, proofRequest, {
      headers: { 'Content-Type': 'application/json' },
    })
   
    if (response.status === 200) {
      console.log('✅ Proof request sent successfully')
    } else {
      console.log('❌ Failed to send proof request:', response.data)
    }
    
    // 5. Request DAT reward
    await client.requestReward(fileId)
    console.log('✅ Reward requested for file id', fileId.toString())
    
    console.log('All operations completed successfully!')
    
  } catch (error) {
    console.error('❌ Error in main function:', error)
    process.exit(1)
  }
}

// Execute the main function
main().catch((error) => {
  console.error('❌ Unhandled error:', error)
  process.exit(1)
})
```

### 4) Add tsconfig.json

Create tsconfig.json:

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "node16",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist",
    "allowJs": true,
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node"
  },
  "include": ["*.ts"],
  "exclude": ["node_modules"]
}
```

### 5) Set environment variables

Create a .env (recommended) or export in your shell:

```
# .env
PRIVATE_KEY=<your wallet private key>
IPFS_JWT=<your pinata ipfs jwt>
```

> Your PRIVATE\_KEY must start with 0x.

> The script reads these via dotenv.

### 6) Run

```
 node --loader ts-node/esm index.ts
```

#### Expected output

```
✅ Client initialized successfully
✅ IPFS client initialized successfully
✅ Data encrypted successfully
✅ File uploaded to IPFS: https://...
✅ File registered with LazAI, file ID: <id>
✅ Proof request prepared
✅ Proof request saved to proof_request.json
✅ Proof request sent successfully
✅ Reward requested for file id <id>
All operations completed successfully!
```


# Mint your DAT in RUST

This guide walks through the process of setting up your local environment, connecting your wallet, and minting your first Data Anchoring Token (DAT) using the LazAI Rust SDK.

It assumes familiarity with Rust, basic blockchain interactions, and access to the LazAI Pre-Testnet.\
\
For a guided walkthrough of the entire setup and minting process, watch the official tutorial:\
➡️  <https://youtu.be/LYN_ZaxFWXg>

## Dependencies

```rust
cargo init --bin lazai-dat-rust
cd lazai-dat-rust

# Alith (from GitHub) with needed features
cargo add alith --git https://github.com/0xLazAI/alith --features "lazai,wallet,crypto,ipfs"

# Runtime & utils
cargo add tokio --features full
cargo add reqwest --features json
cargo add anyhow
cargo add hex
cargo add rand_08
```

### Env vars

<pre class="language-bash"><code class="lang-bash"><strong>export PRIVATE_KEY=&#x3C;your wallet private key>   # must start with 0x
</strong>export IPFS_JWT=&#x3C;your pinata ipfs jwt>
</code></pre>

### src/main.rs

```rust
use anyhow::Result;
use reqwest;
use rand_08::thread_rng;

use alith::data::crypto::{encrypt, DecodeRsaPublicKey, Pkcs1v15Encrypt, RsaPublicKey};
use alith::data::storage::{DataStorage, PinataIPFS, UploadOptions};
use alith::lazai::{Client, ProofRequest, U256};

#[tokio::main]
async fn main() -> Result<()> {
    // PRIVATE_KEY is read by the wallet inside Client::new_default()
    let client = Client::new_default()?;
    let ipfs = PinataIPFS::default();

    // 1) Prepare privacy data and encrypt it
    let data_file_name = "your_encrypted_data.txt";
    let privacy_data = "Your Privacy Data";
    let encryption_seed = "Sign to retrieve your encryption key";

    // Sign the seed to derive a password
    let password = client
        .wallet
        .sign_message_hex(encryption_seed.as_bytes())
        .await?;
    let encrypted_data = encrypt(privacy_data, password.clone())?;

    // 2) Upload encrypted data to IPFS and get a share link
    let token = std::env::var("IPFS_JWT")?;
    let file_meta = ipfs
        .upload(
            UploadOptions::builder()
                .name(data_file_name.to_string())
                .data(encrypted_data)
                .token(token.clone())
                .build(),
        )
        .await?;
    let url = ipfs.get_share_link(token, file_meta.id).await?;

    // 3) Register the URL on LazAI
    let mut file_id = client.get_file_id_by_url(url.as_str()).await?;
    if file_id.is_zero() {
        file_id = client.add_file(url.as_str()).await?;
    }

    // 4) Request a proof from a verified computing node
    client.request_proof(file_id, U256::from(100)).await?;
    let job_id = client.file_job_ids(file_id).await?.last().cloned().unwrap();
    let job = client.get_job(job_id).await?;
    let node_info = client.get_node(job.nodeAddress).await?.unwrap();

    let node_url = node_info.url;
    let pub_key_pem = node_info.publicKey;

    // Encrypt the password with the node's RSA public key
    let pub_key = RsaPublicKey::from_pkcs1_pem(&pub_key_pem)?;
    let mut rng = thread_rng();
    let enc_key_bytes = pub_key.encrypt(&mut rng, Pkcs1v15Encrypt, password.as_bytes())?;
    let encryption_key = hex::encode(enc_key_bytes);

    // Send proof request to the node
    let resp = reqwest::Client::new()
        .post(format!("{node_url}/proof"))
        .json(
            &ProofRequest::builder()
                .job_id(job_id.to())
                .file_id(file_id.to())
                .file_url(url)
                .encryption_key(encryption_key)
                .encryption_seed(encryption_seed.to_string())
                .build(),
        )
        .send()
        .await?;

    if resp.status().is_success() {
        println!("✅ Proof request sent successfully");
    } else {
        println!("❌ Failed to send proof request: {:?}", resp);
    }

    // 5) Claim DAT reward
    client.request_reward(file_id, None).await?;
    println!("✅ Reward requested for file id {}", file_id);

    Ok(())
}
```

### Run

```bash
cargo run
```

#### Expected output

```bash
✅ Proof request sent successfully
✅ Reward requested for file id <file_id>
```


# Verify DAT On-Chain


# Overview

### Background

As decentralized AI Agents become foundational components of the next-generation Web3 infrastructure, their secure, transparent, and verifiable execution is critical. Unlike centralized systems, Web3’s openness introduces new risks:

* **Ownership Ambiguity:** Difficult to prove data/model ownership on-chain.
* **Authenticity Risks:** Agent behavior and output cannot be trusted by default.
* **Lack of Auditability:** No provable link between the used data, the model executed, and the output produced.
* **No On-Chain Verifiability:** Inference results can be fabricated without cryptographic accountability.

In LazAI, each iDAO manages its own data, model, and agent workflows. While this empowers decentralized autonomy, it also raises the need for a trust-minimized, cryptographically verifiable execution framework.

### iDAO’s Key Security & Privacy Challenges

1. **Data Misuse & Privacy Breach**
   1. Sensitive datasets may be exposed or misused during AI processing.
   2. Users lack visibility into whether their inputs were securely processed.
2. **Unverifiable Inference**
   1. AI inference is typically executed off-chain or locally; users cannot validate results or trace data provenance.
   2. The same model may be reused, modified, or forked by different iDAOs without traceability.
3. **Unclear Attribution & Revenue Distribution**
   1. Models often rely on multiple data sources; without execution proofs, revenue sharing becomes opaque.
4. **Untrusted Agent Runtime**
   1. Many AI Agents run on centralized, uncontrolled hardware—susceptible to tampering or malicious behavior.

### LazAI’s Solution: TEE-First, ZK-Optional, OP-Compatible Verified Execution

LazAI introduces a Verified Computing Framework built on three composable execution trust models:

<table data-header-hidden><thead><tr><th width="119.921875"></th><th width="109.5625"></th><th width="305.90625"></th><th width="196.3046875"></th></tr></thead><tbody><tr><td><strong>Mode</strong></td><td><strong>Primary Usage</strong></td><td><strong>Strength</strong></td><td><strong>When to Use</strong></td></tr><tr><td>TEE Mode</td><td>Default</td><td>Trusted execution environment (Intel TDX and SGX are both OK) with remote attestation</td><td>Most inference and fine-tune tasks</td></tr><tr><td>TEE + ZK Mode</td><td>Optional extension</td><td>Adds zero-knowledge proofs for selective inputs, outputs, or logic constraints</td><td>Privacy-sensitive or regulatory tasks</td></tr><tr><td>Optimistic Mode (OP)</td><td>Backup</td><td>Enables fraud-proof-based verification when TEE is unavailable</td><td>Lightweight agents or fallback arbitration</td></tr></tbody></table>

### When to Use ZK or OP

ZK and OP serve as optional augmentation to TEE-based computing:

**Use ZK when:**

* Inputs or outputs must be kept private (e.g., mental health input).
* Output must satisfy constraints (e.g., model temperature < 0.9).
* Regulatory compliance requires provable logic.

**Use OP when:**

* Either TEE is not used, or trust assumptions are weaker.
* Third-party challengers need to verify computation after execution.
* Arbitration or slashing is necessary (e.g., data misuse, forged proofs).

### Cryptographic Proof Models

<table data-header-hidden><thead><tr><th width="124.69921875"></th><th width="284.921875"></th><th width="458.4375"></th></tr></thead><tbody><tr><td><strong>Asset Type</strong></td><td><strong>Proof Type</strong></td><td><strong>Purpose</strong></td></tr><tr><td>Dataset</td><td>Merkle Root + Provenance Hash</td><td>Anchors original data, prevents replacement</td></tr><tr><td>Model</td><td>TEE Attestation + Param Hash</td><td>Verifies model version and source</td></tr><tr><td>Inference</td><td>TEE Signature (optional ZK)</td><td>Verifiable output, optionally private</td></tr></tbody></table>

### Integration with LazAI Infrastructure

**Quorum-Based Consensus + VSC Coordination**

* Quorum Validators stake on LazChain and form trust domains for iDAO.
* VSC (Verifiable Service Coordinator) aggregates proofs from TEE nodes and submits them on-chain.
* Verifier Contract on LazChain checks TEE signatures, ZK proofs, or OP dispute proofs.

**Challenger Mechanism (for OP Mode)**

* Elected challengers monitor inference results and data-model linkage.
* Upon detecting fraud, challengers submit Fraud Proofs.
* Quorum enforces Slashing, penalizing iDAOs via token burn or DAT reduction.

### Summary

LazAI’s Verified Computing architecture provides a hybrid, multi-layered trust framework tailored for decentralized AI ecosystems. With a TEE-first, ZK-assisted, and OP-compatible design, it addresses key pain points in:

* Executing private, auditable AI inference tasks
* Enforcing data/model provenance
* Validating AI agent behavior at low cost
* Coordinating decentralized trust via Quorum and VSC

This framework transforms iDAOs from isolated compute units into co-verifiable AI entities, anchored by programmable security, fine-grained delegation, and decentralized validation.

LazAI’s architecture lays the groundwork for a future where AI is both trustless and transparent, and every computation, dataset, and model update can be proven, traced, and monetized across on-chain and off-chain domains.


# Verified Computing Architecture

### Core Components

<table data-header-hidden><thead><tr><th width="197.6953125"></th><th></th></tr></thead><tbody><tr><td><strong>Component</strong></td><td><strong>Description</strong></td></tr><tr><td>TEE Worker Nodes</td><td>Secure computation nodes running AI tasks (e.g., preprocessing, training, inference) within a trusted enclave, signing all outputs.</td></tr><tr><td>iDAO</td><td>Submits datasets and models, configures agent execution logic, and selects the validation mode (TEE, TEE+ZK, or TEE+OP).</td></tr><tr><td>VSC (Verifiable Service Coordinator)</td><td>Coordinates proof submission, batches TEE attestations and optional ZK/OP proofs, and submits them to LazChain.</td></tr><tr><td>Verifier Contract</td><td>Smart contract on LazChain that verifies TEE attestations, ZK or OP proofs, and anchors the result hashes on-chain.</td></tr><tr><td>Challenger Registry</td><td>Quorum-elected members who monitor verification results, issue fraud claims, and trigger slashing when violations occur.</td></tr></tbody></table>

### Execution Lifecycle Flow

#### Step 1: iDAO Task Submission

**An iDAO submits a task definition, including:**

* Data references (IPFS, Arweave, etc.);
* Target model or Agent ID;
* Expected output type and optional constraints;
* Selected verification method: TEE, TEE+ZK, or OP.

#### Step 2: Secure Execution in TEE

A TEE Worker Node picks up the task;

* **Inside a hardware-enforced enclave, it performs:**
  * Data loading and pre-checks;
  * Model or Agent execution;
  * Output generation and hashing;
  * Signing the result with the TEE’s private key;

**If selected, the node may also:**

* Generate a ZK Proof for the output computation;
* Generate a Fraud Proof-Ready Trace for OP-based setups.

#### Step 3: Submitting Proofs to LazChain

**VSC aggregates all relevant data:**

* TEE Signature (for execution authenticity);
* Optional ZK-SNARK (for result verifiability);
* Optional OP Trace Hash (for fraud challenge preparation);
* Metadata such as model ID, data Merkle root, execution timestamp;
* These are submitted as a transaction to the Verifier Contract on LazChain.

#### Step 4: On-Chain Verification

**The Verifier Contract:**

* Checks TEE signature validity using known attestation keys;
* Verifies optional ZK or OP proofs;
* Anchors result hash and validation status for downstream logic (e.g., DAT reward, access log, or revenue claim);
* Emits event logs for traceability.

#### Step 5: Dispute and Challenger Mechanism

Challengers (Quorum validators) continuously monitor on-chain proof submissions;

* **If a suspicious or invalid computation is detected, they can:**
  * Pull the result + metadata + optional trace;
  * Recompute the output locally or verify it against OP/Fraud-Proof references;
  * Submit a FraudProof;

**Once validated, the system executes a slashing procedure:**

* iDAO penalty: burning of stake or reduction of DAT value;
* Challenger reward: incentive for honest verification.

### Optional Verification Modes Explained

<table data-header-hidden><thead><tr><th width="167.4609375"></th><th></th><th></th><th></th></tr></thead><tbody><tr><td><strong>Mode</strong></td><td><strong>When to Use</strong></td><td><strong>Advantages</strong></td><td><strong>Overhead</strong></td></tr><tr><td>TEE Only</td><td>Trusted agents in performance-critical use cases; fast, low gas</td><td>Hardware-based trust, ultra-low gas</td><td>Needs TEE-compatible hardware</td></tr><tr><td>TEE + ZK</td><td>Highly sensitive data, regulatory audits, or public agent use</td><td>Public verifiability, cryptographic guarantees</td><td>Medium gas cost, higher latency</td></tr><tr><td>OP</td><td>For open models with fast finality and community arbitration</td><td>Transparent fraud resolution, no ZK setup</td><td>Requires fraud monitoring and challenge periods</td></tr></tbody></table>

### Security Guarantees

<table data-header-hidden><thead><tr><th width="169.5859375"></th><th></th><th></th></tr></thead><tbody><tr><td><strong>Layer</strong></td><td><strong>Protection</strong></td><td><strong>Mechanism</strong></td></tr><tr><td>Execution Trust</td><td>Code and data cannot be tampered with during runtime</td><td>Hardware TEE isolation, remote attestation</td></tr><tr><td>Verifiable Output</td><td>Outputs are provably derived from claimed inputs</td><td>ZK-SNARK or OP Fraud-Proof</td></tr><tr><td>Data Privacy</td><td>Data processed inside secure enclaves, not exposed on-chain</td><td>TEE memory isolation, encryption</td></tr><tr><td>Dispute Resolution</td><td>Any party can challenge invalid results</td><td>On-chain challenger registry with incentives</td></tr></tbody></table>

### Integration with Consensus and Reward Mechanism

* All proofs submitted via VSC are included in blocks through the Quorum-Based BFT consensus;
* iDAO stakes, DAT updates, and model access rights are governed by verified task results;
* Fraud proofs or confirmed proofs serve as inputs to reward allocation, slashing, and token distribution via Verifier and Settlement Contracts.


# Contract & Execution Flow

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXe5fXg96hmqxmmZsk8O8Cqx6s7g1Wam9LZFb6Gl5_-5nxhrDZnAvli18pM4qXrqE1DYdGGEo1NofH7YEwgnFjmzwmmGGO0fatzLSRgjGC2yZD_qnoAafAn2DJ3ZCZQMsHAfA6YKRw?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

### Core Smart Contract Modules

LazAI’s Verified Computing system consists of the following core contract modules:

<table data-header-hidden><thead><tr><th width="181.2421875"></th><th></th></tr></thead><tbody><tr><td><strong>Contract</strong></td><td><strong>Responsibility</strong></td></tr><tr><td>Verifier Contract</td><td>Core validator that receives proofs from the VSC and verifies TEE signatures, ZK proofs, or OP-based fraud evidence on-chain.</td></tr><tr><td>VSC Coordinator</td><td>Middleware that aggregates proofs from TEE nodes, including optional ZK/OP proofs, and submits them to the Verifier contract.</td></tr><tr><td>Challenger Registry</td><td>Maintains a list of Quorum-elected challenger nodes and tracks their activity, reputation, and rewards.</td></tr><tr><td>ExecutionRecord</td><td>Stores metadata of each computation task, including result hash and verification status.</td></tr><tr><td>Settlement Contract</td><td>Handles reward allocation and slashing based on verification results, impacting DAT ownership and value.</td></tr></tbody></table>

### Verifier Contract Interface&#x20;

`interface IVerifier {`

&#x20;   `function submitTEEProof(`

&#x20;       `bytes calldata taskId,`

&#x20;       `bytes calldata resultHash,`

&#x20;       `bytes calldata teeSignature,`

&#x20;       `bytes calldata attestationReport`

&#x20;   `) external;`

&#x20;   `function submitZKProof(`

&#x20;       `bytes calldata taskId,`

&#x20;       `bytes calldata zkProof,`

&#x20;       `bytes calldata publicSignals`

&#x20;   `) external;`

&#x20;  `function submitFraudProof(`

&#x20;       `bytes calldata taskId,`

&#x20;       `bytes calldata evidence,`

&#x20;       `address challenger`

&#x20;   `) external;`

&#x20;   `function verifyResult(bytes calldata taskId) external view returns (bool valid);`

`}`

### Task Lifecycle Flow Diagram

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXee5cn_vbidoYVGKIrZDSuItUIOV8FbgPvETAAwsQeN1la19oVxnnpDGuY40oigD2pRfx63bkuaMKdoN4YMUKnfL46uCwpaPUEB7pVO9rVzuxR618SQ7Tn7e2wz-237DdHFzO5SMw?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

### Full Execution Lifecycle

This section outlines the step-by-step process for verifiable execution under each supported mode: TEE, TEE+ZK, and OP. Each flow ensures secure and auditable AI computation within the LazAI framework.

#### Step 1: Task Submission by iDAO

The iDAO initiates a computation task via an off-chain UI or dApp, sending it to the VSC for orchestration.

**Submitted Fields:**

* **taskId:** Unique hash for the task;
* **dataRef:** Dataset reference (e.g., IPFS, Arweave hash);
* **modelId:** The model or Agent identifier to execute;
* **params:** Inference or training parameters;
* **verifyMode:** Enum specifying TEE, TEE+ZK, or OP.

The VSC stores this metadata and assigns the task to eligible TEE nodes.

#### Step 2: Secure Execution Inside TEE

The assigned TEE Worker Node performs the task inside an isolated enclave:

**In-Enclave Process:**

1. Initialize environment using the specified dataset and model;
2. Run computation (e.g., forward pass, token prediction, classification);
3. Generate resultHash from the output;
4. Sign the result using TEE’s private key;
5. Attach remote attestation report.

**Depending on verifyMode, the node additionally:**

* Generates a ZK-SNARK proving the correctness of the computation without revealing input/output (for TEE+ZK mode);
* Prepares a Fraud-Proof-ready execution trace, hashed and stored off-chain (for OP mode).

**Security Guarantees:**

* Execution is isolated and tamper-resistant;
* Signed results are cryptographically bound to the specific TEE environment.

#### Step 3: VSC Aggregation and Proof Packaging

Once execution is complete, the VSC (Verifiable Service Coordinator) aggregates the following:

<table data-header-hidden><thead><tr><th width="199.859375"></th><th width="175.33984375"></th><th></th></tr></thead><tbody><tr><td><strong>Data</strong></td><td><strong>Included When</strong></td><td><strong>Purpose</strong></td></tr><tr><td>TEE Signature</td><td>Always</td><td>Confirms execution occurred inside TEE</td></tr><tr><td>ZK Proof</td><td>TEE+ZK only</td><td>Proves result validity without exposing data</td></tr><tr><td>OP Trace Hash</td><td>OP only</td><td>Enables later challenge by a third party</td></tr><tr><td>Execution Metadata</td><td>Always</td><td>Includes modelId, dataRoot, execution timestamp, etc.</td></tr></tbody></table>

The VSC then formats this package and submits it as a transaction to the Verifier Contract on LazChain.

#### Step 4: On-Chain Verification by Verifier Contract

The Verifier Contract receives the task package and performs the following steps:

**TEE Mode**

* Verifies the **TEE signature** using trusted attestation keys;
* Validates that resultHash and attestation correspond to the original request;
* Marks task as **verified** and stores the output hash on-chain.

**TEE + ZK Mode**

* Verifies the **TEE signature** as above;
* Executes on-chain ZK verifier to validate the **ZK-SNARK proof**;
* Records both resultHash and proofResult in ExecutionRecord.

**OP Mode**

* Stores the result and OP Trace Hash;
* Opens a **challenge window (**&#x65;.g., 12–24 blocks) for registered challengers to submit fraud claims;
* If no valid fraud proof is submitted within the window, the result is finalized as valid.

#### Step 5: Post-Verification Hooks

**Once verification is complete:**

* The **ExecutionRecord** module stores taskId, verification status, resultHash, and timestamp;
* The **Settlement Contract**:
  * Increases or adjusts DAT value for contributing iDAOs;
  * Releases access credits or rewards based on usage;
  * Optionally triggers stake updates or slashing (in case of OP fraud).

All results are publicly queryable and indexed on LazChain for audit, traceability, and downstream data monetization.

### Module-to-Module Interaction Summary

<table data-header-hidden><thead><tr><th width="125.94140625"></th><th width="112.37890625"></th><th width="285.65234375"></th><th></th></tr></thead><tbody><tr><td><strong>Source</strong></td><td><strong>Target</strong></td><td><strong>Data Transmitted</strong></td><td><strong>Purpose</strong></td></tr><tr><td>iDAO</td><td>VSC</td><td>taskId, modelId, dataId, verifyMode</td><td>Task configuration</td></tr><tr><td>TEE Node</td><td>VSC</td><td>resultHash, signature, attestation</td><td>Secure result</td></tr><tr><td>VSC</td><td>Verifier</td><td>Proofs and metadata</td><td>On-chain validation</td></tr><tr><td>Verifier</td><td>ExecutionRecord</td><td>Status and result hash</td><td>Task tracking</td></tr><tr><td>Verifier</td><td>Settlement</td><td>valid status, DAT info</td><td>Reward or slashing</td></tr></tbody></table>

### Proving Dataset and Model Ownership

To establish clear and verifiable ownership of datasets and models within LazAI, the following protocol is implemented between iDAO users, Quorum nodes, and the LazChain infrastructure:

1. **Initial Anchoring with TEE Attestation**\
   When a user (or iDAO member) first uploads a dataset or model to a Quorum, the selected TEE Worker Node performs a cryptographic attestation by:

   1. Computing the data hash (e.g., SHA256 of the dataset or model);
   2. Binding it to the uploader’s public key or LazChain address;
   3. Signing this tuple using the TEE’s private attestation key.

2. **Ownership Registration via LazChain**\
   The Verifiable Service Coordinator (VSC) packages this attestation into a LazChain transaction, which includes:

   1. The data or model hash;
   2. The uploader’s public address;
   3. The TEE signature and timestamp.

   The Ownership Registry Contract stores this mapping, establishing an on-chain link between data hash and rightful owner.

3. **Consensus-Based Verification and Transfer**\
   All future operations involving the dataset - whether validation, licensing, delegation, or ownership transfer - must be registered as consensus-approved transactions on LazChain. This ensures tamper-proof traceability and cryptographic auditability.

4. **Ownership Query and Privacy-Preserving Claims**\
   To prove ownership, a user simply queries the on-chain registry for the binding between their address and the data hash.\
   In cases where the user must prove specific dataset properties (e.g., contains 10,000 labeled entries, complies with regulatory filters) without revealing the raw data, a Quorum node may generate a Zero-Knowledge Proof (ZKP) certifying the claim, which can then be verified on-chain.&#x20;

### Computing node

* Users can indirectly query and use encrypted data through computing nodes, including fine-tuning and inference.
* Verify that nodes control accounts that can access the data through contracts.
* Joint data analysis allows users to securely process information across multiple iDAOs.


# Overview

Data evaluation and alignment are core pillars of LazAI’s decentralized AI ecosystem, addressing critical challenges in ensuring data quality, relevance, and incentive alignment across distributed contributors. In a landscape where data fragmentation, privacy concerns, and inconsistent quality hinder AI progress, LazAI’s framework establishes a trust-minimized, verifiable pipeline to assess data value, align it with AI model objectives, and reward contributors fairly.

At its core, this system enables:<br>

* Objective Data Quality Assessment: Standardized and context-aware metrics to evaluate data integrity, accuracy, and utility for specific AI tasks (e.g., training, inference, or fine-tuning).
* Alignment with Model Goals: Mechanisms to ensure data relevance to target AI use cases (e.g., medical datasets aligned with diagnostic models) through community-driven curation and on-chain validation.
* Transparent Incentives: Direct linking of data evaluation results to economic rewards (via the value field of DAT tokens), ensuring contributors of high-quality, aligned data are fairly compensated.
* Privacy-Preserving Validation: Leveraging cryptographic tools (e.g.,TEEs, ZKPs) to assess data without exposing raw information, critical for sensitive domains like healthcare or finance.

By integrating these capabilities, LazAI resolves the paradox of decentralized data, enabling scalability and diversity while maintaining the rigor required for reliable AI outcomes.<br>


# Architecture

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdyEHpPn3FKW8Cu6za-2zi_4OxAy010vla-LgjRaVFolJiKDGkPCdYy71vw6miDv6liwCZhzXcQ2M1rExVZIB5Z42_TLOIiju3U2XNY9q4FTXuw9DXb4U4WR-Mw-UcG8igFhfd-YA?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

LazAI’s Data Evaluation and Alignment architecture is built on three interconnected layers, designed to operate seamlessly within its broader blockchain and iDAO governance framework:&#x20;

### 1. **Data Submission & Metadata Anchoring Layer**

This layer handles initial data ingestion, ensuring provenance and basic integrity before evaluation.<br>

* iDAO-Driven Submission: Data contributors (individuals or organizations) submit datasets through their affiliated iDAOs, which act as curators. Each submission includes structured metadata:
  * Source attribution (via cryptographic signatures).
  * Domain tags (e.g., “biomedical,” “financial transactions”).
  * Format specifications (e.g., text, images, tabular data) and preprocessing logs.
* On-Chain Anchoring: A hash of the dataset and its metadata is recorded on the LazChain, creating an immutable audit trail. This hash is linked to the contributor’s DAT token, establishing initial ownership and traceability.

### 2. **Evaluation Engine Layer**

This layer executes multi-dimensional data assessment, combining automated checks and community validation.<br>

* Automated Quality Metrics:
  * **Integrity Checks:** Cryptographic verification of data hashes to detect tampering.
  * **Statistical Validity:** Tools to measure noise, duplication, and coverage (e.g., for text data, perplexity scores; for images, resolution and labeling consistency).
  * **Privacy Compliance:** Scans for sensitive information (e.g., PII) using zero-knowledge proofs to ensure compliance with iDAO-defined policies.
* Contextual Alignment Checks:
  * **Model Compatibility:** For datasets submitted to train specific models (e.g., a sentiment analysis model), the engine verifies alignment with the model’s input schema and objective (e.g., labeling consistency with sentiment labels).
  * **Domain Expertise Integration:** iDAOs can appoint domain-specific validators to manually review high-stakes data (e.g., clinical trial records), with their assessments weighted via on-chain voting.
* Incentivized Challenges: External “challengers” can submit fraud proofs to dispute evaluation results (e.g., identifying hidden biases in a dataset). Successful challenges earn DAT rewards, while invalid claims result in penalties, ensuring rigor.

### 3. **Alignment & Reward Layer**

This layer ties evaluation outcomes to economic incentives and iterative improvement.<br>

* **Dynamic Value Scoring:** Each dataset receives a Data Quality Score (DQS) based on evaluation results, encoded in its associated DAT token. The DQS influences:
  * Access privileges (e.g., high-DQS data is prioritized for premium AI models).
  * Reward calculations (contributors earn a share of model revenue proportional to their data’s DQS and usage frequency).
* **Feedback Loops:** Post-deployment, the system tracks how data impacts model performance (e.g., inference accuracy, reduction in hallucinations). This data is fed back into the evaluation engine to refine future assessments—for example, a dataset that improves model accuracy over time sees its DQS increase.
* **iDAO Governance:** Each iDAO sets its own evaluation policies (e.g., weighting of automated vs. manual checks) via on-chain proposals, ensuring alignment with community values (e.g., privacy-focused iDAOs may prioritize anonymization metrics).

By integrating these layers, LazAI’s Data Evaluation and Alignment architecture transforms fragmented, untrusted data into a verifiable, high-quality asset—one that drives AI innovation while ensuring contributors are fairly rewarded for their contributions.&#x20;


# Technical Design

### Duplication Detection

We can divide data into structured data and unstructured data. For structured data, we can adopt hash-based partitioning technology. First, calculate the hash value (such as SHA-256) for key fields, then divide the data into 100 buckets according to the last two digits of the hash value. Each bucket is processed separately for duplicate detection to reduce memory and computational overhead. For unstructured data, we can also mainly divide it into text and image. For text data, we mainly use embedding technology to first convert the text into vectors and calculate the cosine similarity between vectors. When the similarity is ≥ 0.95, it is judged as highly similar, and a lower weight score is given to ensure the diversity of data within a single iDAO organization. For image data, we can first use a classification model to determine the model category, and then use a perceptual hashing algorithm. For example, scale the image to 8\*8 pixels, convert it to a grayscale image, calculate the average pixel value, and generate a hash value after comparing each pixel with the average value. Images with similar hash values are considered duplicates or highly similar.&#x20;

### Quality Assessment

For text data, we directly calculate the perplexity of the data through the LazAI language reasoning model. The lower the perplexity, the better the coherence and standardization of the text, and the higher the information density. For image data, we mainly evaluate resolution and label consistency.

### Context Alignment Detection - Model Training Weight Analysis

Monitor the change of weights with data during training: If a batch of data significantly reduces the model's loss function (such as MSE for regression tasks and cross-entropy for classification tasks), it indicates that this data plays a great role in model optimization. By calculating the gradient of the loss function for each batch of data, the data with the gradient direction consistent with the direction of loss minimization and a large amplitude is more important for model training.

Adopt importance sampling: Allocate probabilities according to the contribution of data to weight updates. Data with high probabilities is more aligned with the model's goals.&#x20;

### Context Alignment Detection - Model Inference Verification

After training, use the data for inference testing: For example, in a fraud detection model, data that can correctly classify known fraud/non-fraud cases has a high alignment degree. Calculate metrics such as precision, recall, and F1-score on the validation set. Higher scores indicate that the data quality is more suitable for the model's task.

Analyze the confidence of model predictions: In classification tasks, data with a confidence close to 1 for the correct category has strong consistency with the patterns learned by the model and a high alignment degree.&#x20;

#### DQS CalculatioCalculation

DQS is calculated using a weighted formula that synthesizes multidimensional indicators, as follows:&#x20;

S = w1 \* DS + w2 \* AS + w3 \* CAS

where w1, w2, and w3 are weights, DS stands for Duplication Score, AS for Accuracy Score, and CAS for Model Context Alignment Score.


# Consensus Protocol

The Trusted Execution Layer forms the backbone of LazAI, ensuring secure, verifiable, and decentralized AI execution and governance. It leverages blockchain-based validation, high-performance execution, and scalable data availability mechanisms to optimize resource utilization while maintaining data integrity and computational trust.

<figure><img src="/files/0Cq0duNotyrjMP9irpBv" alt=""><figcaption></figcaption></figure>

### PoS + Quorum-Based BFT Consensus Protocol

To ensure data trustworthiness and execution reliability, LazAI employs a Quorum-Based Byzantine Fault Tolerant (BFT) consensus mechanism. Each Quorum functions as a decentralized iDAO responsible for governing, verifying, and securing AI-related data and computational processes.

**LazAI Consensus Layer has the following three features:**

1. **Decentralized Data Verification:** Each iDAO operates independently to validate datasets, training models, and AI agent execution before anchoring them on-chain.
2. **Optimized Off-Chain Storage:** AI datasets remain off-chain, while their cryptographic proofs and metadata are stored on LazChain, minimizing storage costs.
3. **High-Performance Data Processing:** The Quorum consensus model enables parallel verification and validation, reducing latency for AI model updates and execution.

**Its main advantages are as follows:**

* **Reduces Centralized Risk:** No single entity controls data governance, ensuring resistance to manipulation and censorship.
* **Transparent & Immutable:** All verification events and decisions are stored on LazChain, providing full auditability.
* **Scalable Data Governance:** iDAOs dynamically adapt to evolving AI datasets, allowing continuous validation and dispute resolution.

By integrating a Quorum-based BFT consensus, LazAI ensures high availability, low latency, and verifiable AI execution, forming a robust foundation for decentralized AI governance.

\ <br>


# Settlement Layer

The Settlement Layer transforms AI-related data, models, and agents into tokenized assets, ensuring secure, traceable, and programmable ownership.

**Key Functionalities are as follows:**

1. **Immutable AI Asset Registration:** Training datasets, model weights, and execution parameters are permanently anchored on LazChain, ensuring provenance.
2. **Data Anchoring Token (DAT) Management:** Every issuance, transaction, ownership transfer, and access control event related to AI assets is immutably recorded on-chain.
3. **Privacy-Preserving Provenance Tracking:** Utilizes Zero-Knowledge Proofs or TEE Proofs to validate dataset authenticity while protecting sensitive AI data.

By anchoring AI assets on a decentralized ledger, the Settlement Layer guarantees integrity, accessibility, and compliance, paving the way for a trustless AI economy.


# Execution Layer

The Execution Layer is designed to support verifiable AI computation, inference optimization, and seamless AI asset deployment. This layer ensures that AI agents and models operate efficiently and transparently within LazAI’s decentralized ecosystem.

**Core Capabilities:**

* **Verified Computing Framework:** LazAI establishes trust in AI-generated outputs, ensuring that inference results, training processes, and data integrity are independently verifiable.
* **Parallel EVM Execution for AI Workloads:** AI asset-related transactions (e.g., dataset validation, model licensing) benefit from parallelized execution, improving scalability.
* **Inference Engine Optimization:** Supports low-latency, high-throughput AI inference and integrates hardware acceleration for AI reasoning (e.g., CPU/GPU/TPU optimization).

By implementing trustless AI execution mechanisms, the Execution Layer ensures transparency, security, and scalability for AI applications in Web3.

<br>


# Data Availability Layer

AI-driven applications require continuous access to high-quality, verifiable data. The Data Availability Layer ensures that AI datasets, training models, and inference results remain accessible, transparent, and cryptographically secure.

#### Key Functionalities:

1. **On-Chain & Off-Chain Data Anchoring:**
   1. AI datasets and execution metadata are hashed and stored on Blockchain for traceability and verification.
   2. Supports verifiable off-chain storage solutions such as IPFS, Arweave, and decentralized storage networks, ensuring permanence and censorship resistance.
2. **Cross-Platform Data Interoperability:**
   1. LazAI enables trusted data interactions between Web2, Web3, and decentralized AI models.
   2. Integrates APIs for traditional Web2 data sources, public datasets, and enterprise AI systems, allowing AI agents to leverage diverse information pools.
3. **Privacy-Preserving Verification:**
   1. Uses ZK/TEE Proofs and Fraud Proofs to validate off-chain data integrity without exposing raw information.
   2. Supports Optimistic Proofs to streamline dispute resolution while maintaining data accountability.

#### Onchain Reputation System:

To ensure high-quality AI datasets, LazAI introduces a reputation-based scoring mechanism for data sources and contributors:

* **Dynamic Trust Scores:** Data providers, AI agents, and model trainers are assigned trust ratings based on usage history, verification results, and community feedback.
* **Reputation-Driven Incentives:** High-trust contributors gain priority listing in the LazAI ecosystem, while low-trust providers face penalties or dataset deprecation.

By enabling multi-layered data verification, decentralized storage, and Web3-compatible interoperability, the LazAI Data Availability Layer ensures continuous access to reliable AI datasets, forming the foundation for a scalable, trustless AI ecosystem.<br>


# Introduction

LazAI’s Quorum-Based BFT (QBFT) consensus is a modular and scalable consensus protocol optimized for AI-centric decentralized systems. It blends practical Byzantine Fault Tolerance (pBFT) with a Quorum-based voting mechanism to ensure efficient validation, integrity, and liveness in a multi-agent AI data network.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdBvvR52Ynowbhty0CCtXQ7qRKga0pEy0hZ1NvGfsdvbObfmI70HSRsE9eD8bv1tEhTkUZCzrGBWWqh4gxdkcdp33moIgMEadUW6RbugmavxhTt_pMJIv6KtW-Bf_CfKQ6U6Y-ZcQ?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

### Key Entities

<table data-header-hidden><thead><tr><th width="154.265625"></th><th></th></tr></thead><tbody><tr><td><strong>Component</strong></td><td><strong>Role</strong></td></tr><tr><td>Quorum</td><td>A logical group of validators (iDAO members) responsible for data validation.</td></tr><tr><td>Proposer</td><td>A rotating member of the quorum responsible for proposing the next block/data state.</td></tr><tr><td>Validator</td><td>iDAO participant who verifies, signs, and votes on proposed blocks.</td></tr><tr><td>Challenger</td><td>External party capable of submitting fraud proofs or challenges.</td></tr></tbody></table>

### Design Principles

* **AI Data-Aware Consensus:** Handles metadata-rich, non-deterministic AI data (e.g., dataset hashes, ZK proofs, computation logs).
* **Quorum-Based Delegation:** Only assigned quorums participate in consensus, improving scalability.
* **Dynamic Quorum Rotation:** Quorum members are periodically re-elected or rotated for decentralization.
* **Hybrid Validity Layer:** Supports ZK-SNARK/TEE proofs and Optimistic Proofs (OP) as validity inputs.


# iDAO-Quorum Interaction

VSC (Verifiable Service Coordinator)-Based iDAO-Quorum Interaction Protocol

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXeiXeO7OorXxIflKbAGPN8WsGUAWNDPyjlPja9t4tT2foP54zpXSgB_Xgp44Ygx4BZWW3i64ujP9rQEz881NALSMw2yRZ0am0qnuy8K0VbVnkuDqcHdgC3pY6Z0krzd0KjVkI5X?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

### Security Delegation via Stake-Based Quorum Integration

Each Quorum node participating in LazChain’s consensus mechanism is required to stake native tokens as a guarantee of honest behavior. Through this staking model and potential external collaborations (e.g., restaking, cross-chain validation, or inter-protocol delegation), iDAOs indirectly inherit the economic security of LazChain.

By leveraging Quorum nodes that are economically aligned through stake commitments on LazChain, iDAOs benefit from shared security guarantees without replicating full consensus overhead.

### POV/Model/Agent Updates are Transmitted via VSC to Quorum for Consensus

Whenever an iDAO performs updates, whether submitting new POV Inlet data, publishing a model, or deploying an AI Agent, these changes are packaged as service transactions and routed to the relevant Quorum via the VSC protocol. Each Quorum, operating under a Byzantine Fault Tolerant (BFT) consensus, independently validates and reaches agreement on the transaction outcome before anchoring them to LazChain.

The VSC layer ensures that any AI-related state change proposed by iDAOs (e.g., new models, retraining outputs, or agent updates) is routed to the appropriate Quorum and finalized through localized BFT consensus before being registered on-chain.

### Proof Submission $ Asynchronous Validation via VSC

After consensus on the high-level update, VSC asynchronously dispatches verification artifacts—such as ZK proofs, Optimistic Proofs, or TEE attestations—to the relevant Quorum nodes. These proofs serve as cryptographic evidence that the update was generated under valid computational assumptions and that the iDAO’s declared actions were faithfully executed.

VSC acts as the communication bridge between iDAO and Quorum validators, coordinating the off-chain-to-on-chain delivery of verifiable computation proofs to be asynchronously validated and logged.

### Challenger Arbitration and Slashing Procedure

Within each Quorum, a rotating set of Challenger nodes is elected to perform near real-time audits. These nodes continuously pull iDAO-submitted data and associated proofs from LazChain. If a Challenger detects inconsistency - such as an inference proof not matching the declared model weights - it can trigger a slashing dispute.

#### **This initiates the following:**

* Immediate freeze of the suspicious iDAO update.
* Verification of the challenger’s claim through multi-round consensus.
* If valid, slashing of:
  * Staked tokens by the responsible Quorum node (if it facilitated an invalid consensus).
  * DAT assets or usage credits associated with the offending iDAO.

Challengers serve as protocol-native auditors, empowered to initiate a punitive slashing process whenever verifiable misconduct or falsified AI computations are detected. This creates a high-integrity, economically-incentivized deterrent mechanism.


# Quorum-Based BFT Protocol

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXeCp7Zb-UFlueyBGeGLyVXlEqNk7Hjr_f4AX1m3vPGLrBt0Dx0n9T01RiDlf5GmHxIW3P5OuR57WZrfODpVpKKMMLaGIPdwgIhcfEvyePWjLAK5PGiWnhH9pw-A79BorKoem-3o?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

### Quorum-as-Validator: BFT Participation

Each Quorum in LazAI is treated as a full validator node in the BFT consensus layer of LazChain. Quorums participate in ordering and validating transactions related to AI datasets, models, and inference proofs.

* **BFT Layer:** Built on a Byzantine Fault Tolerant consensus mechanism, where Quorums serve as the proposers, voters, and committers.
* **Quorum ID:** Each Quorum has a registered QuorumID and validator weight based on its staking level and historical performance.
* **Deterministic Rotation:** Block proposal is rotated across Quorums; performance and slashing affect rotation weights.

### iDAO ↔ Quorum: Trust-Coupling via Economic Bonding

Each iDAO must establish explicit trust relationships with one or more Quorums to publish and validate AI assets. Two flexible trust modes are supported:

* **Restaking Mode:** iDAO stakes native tokens (e.g., $LAZ) to the target Quorum, delegating verification responsibility. Slashing penalties apply for fraud or invalid proofs.
* **DAT-Backed Trust Mode:** iDAO may mint AI assets (e.g., datasets or models) as DATs and request endorsement by a Quorum. In this mode:
  * The Quorum acts as a verifier and partial staker of the DAT.
  * The DAT becomes slashing-enabled, provable fraud leads to partial revocation or burn of DAT value.
  * Revenue sharing can be jointly configured between iDAO and Quorum based on the shareRatio.

### Quorum as a Hash-Proven Off-Chain Storage Gateway

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdvKL7P2rRgxWpkJ3IGZYtLaO27SCuJZH8uwhgMBfJuaXCvQfSpdoY2p96DbMFAecpHXPLQUe-d_GLfZjTNoI2nRxZTmFZrZpyDpyzIGFsEHsTDBOEA7_PB_nMV_DcOylNZ55XZ?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

Quorums are not only validators, but also serve as off-chain AI storage coordinators. They host:

* Raw datasets (IPFS/Arweave/Filecoin),
* Fine-tuned models,
* Inference results, execution logs, and
* OP/ZK/TEE-based proofs.

Only the corresponding hash commitments and metadata are posted on-chain to minimize LazChain storage load.

iDAOs fetch training data from Quorums and submit updates via Verifiable Service Coordinator (VSC).

### VSC: Orchestrated Trustless Coorination

The Verifiable Service Coordinator (VSC) bridges iDAO outputs and Quorum consensus:

* **Transaction Submission:** iDAO sends POV Updates, Model Anchors, Inference Outputs, and Verification Proofs to the VSC.
* **Proof Dispatching:** VSC asynchronously dispatches proof bundles (e.g., OP/ZK/TEE) to corresponding Quorums.
* **Quorum Consensus:** Quorums validate the bundles and finalize them on LazChain via BFT.

### Challenger-Based Slashing Protocol

To ensure iDAO integrity and data authenticity, Challenger nodes are elected from within each Quorum:

* **Near-Real-Time Monitoring:** Challengers continuously pull Quorum-endorsed proofs from LazChain.
* **Fraud Detection:** If an iDAO is found to have submitted a model/proof inconsistent with the training dataset or usage policy:
  * A fraud proof can be submitted.
  * If verified, the iDAO is slashed (token stake or DAT-backed value).
  * The challenger is rewarded.
* **Slashing Scope:**
  * Native token slashing from restaking.
  * DAT shareRatio burn from endorsement.
  * Temporary blacklist from specific Quorums.

#### I**nnovation Points vs Traditional BFT**

<table data-header-hidden><thead><tr><th width="192.859375"></th><th width="294.4296875"></th><th></th></tr></thead><tbody><tr><td><strong>Dimension</strong></td><td><strong>LazAI LQBCP</strong></td><td><strong>Traditional BFT</strong></td></tr><tr><td>Validator Abstraction</td><td>Quorums serve as both consensus validators and AI data providers</td><td>Validators focus purely on block finality</td></tr><tr><td>Slashing Logic</td><td>Multi-source: token-based, asset-based (DAT), behavior-based</td><td>Typically token-only</td></tr><tr><td>Trust Flexibility</td><td>iDAO dynamically bonds to trusted Quorums via staking or asset endorsement</td><td>Static validator set</td></tr><tr><td>Proof Integration</td><td>Built-in OP/ZK/TEE verification with off-chain data binding</td><td>Not natively data-aware</td></tr><tr><td>Data Provenance Layer</td><td>Hash-based anchoring via Quorum storage</td><td>Not data-integrated</td></tr><tr><td>Modular Incentives</td><td>iDAO ↔ Quorum reward agreements via DAT share ratios</td><td>Monolithic block reward or fee</td></tr></tbody></table>


# Slashing & Challenger System

### Purpose

Ensure data validity and computation integrity by enabling any participant to challenge dishonest or incorrect submissions (e.g., invalid datasets, forged proofs, malicious inference). If proven correct, the challenger is rewarded, and the malicious party is penalized through slashing.

* **Fraud Detection:** Any party can submit a FraudProof against a committed block.
* **Resolution:**
  * LazChain executes a fraud arbitration contract using on-chain or TEE-based verification.
  * If the proof is valid:
    * Proposer is slashed
    * Validating signers are penalized (if collusion proven)
    * Challenger is rewarded

### Core Components

<table data-header-hidden><thead><tr><th width="179.8046875"></th><th></th></tr></thead><tbody><tr><td><strong>Component</strong></td><td><strong>Role</strong></td></tr><tr><td>Proposer</td><td>The validator/quorum member who proposed the block or submitted the AI asset/proof.</td></tr><tr><td>Challenger</td><td>Any external actor who submits evidence that a committed dataset, proof, or result is invalid or fraudulent.</td></tr><tr><td>Arbitration Contract</td><td>A smart contract that validates fraud proofs (ZK, Merkle, TEE attestations) and enforces punishment/reward.</td></tr><tr><td>Slashing Pool</td><td>Staked tokens held by proposers and quorum validators, which can be reduced (slashed) in the event of fraud.</td></tr><tr><td>Challenge Window</td><td>The period (e.g., 100 blocks) during which a committed block/result can be challenged.</td></tr></tbody></table>

***

### Challenge Flow

#### Step  1: Fraud Detection

A challenger observes that a committed dataset, model, or inference result is invalid.&#x20;

**Examples:**

* Malformed or manipulated dataset hash
* Proof mismatch (ZK, OP)
* Inference result contradicts source input

**They prepare a Fraud Proof:**

`struct FraudProof {`

&#x20;   `bytes32 disputedBlockHash;`

&#x20;   `bytes challengeData;`       // could be Merkle branch, ZK transcript, etc.

&#x20;   `uint256 timestamp;`

&#x20;   `address challenger;`

`}`

#### Step 2: Challenge Submission

The challenger calls:

`challengeBlock(bytes32 disputedBlockHash, FraudProof calldata proof)`

The contract:

* Checks challengeWindow validity (block not too old)
* Validates the `proof.challengeData`
* Calls appropriate verifier (e.g., MerkleVerifier, ZKVerifier, TEECertifier)

#### Step 3: Arbitration & Result

If the fraud proof is <mark style="color:green;">**valid**</mark>:

<table data-header-hidden><thead><tr><th width="222.203125"></th><th></th></tr></thead><tbody><tr><td><strong>Action</strong></td><td><strong>Effect</strong></td></tr><tr><td>🏆 Challenger wins</td><td>Receives reward from slashing pool (e.g., 10% of stake)</td></tr><tr><td>⛔ Proposer slashed</td><td>Their stake is burned or redistributed</td></tr><tr><td>⚠️ Quorum Validators (optional)</td><td>Can be penalized (reduced rewards, stake slashing) if collusion proven</td></tr><tr><td>❌ Fraudulent block/result</td><td>Marked invalid, removed or reverted in local state</td></tr><tr><td>🧠 DATs minted</td><td>May be burned or frozen if tied to fraudulent data</td></tr></tbody></table>

If the fraud proof is <mark style="color:red;">**invalid**</mark>:

* The challenger may lose a small bond (anti-spam)
* Block and proposer remain valid

### Challenge Types

<table data-header-hidden><thead><tr><th width="188.90234375"></th><th width="356.6015625"></th><th></th></tr></thead><tbody><tr><td><strong>Type</strong></td><td><strong>Description</strong></td><td><strong>Verifier</strong></td></tr><tr><td>ZK Challenge</td><td>Submitted proof is invalid or unverifiable</td><td>ZKVerifier</td></tr><tr><td>TEE Challenge</td><td>TEE signature or report mismatch</td><td>TEECertifier</td></tr><tr><td>Inference Discrepancy</td><td>Output does not match expected inference</td><td>OP / Result Replay</td></tr><tr><td>Dataset Integrity</td><td>Dataset hash does not match anchor</td><td>MerkleVerifier</td></tr><tr><td>Behavioral Fraud</td><td>Agent performs unauthorized behavior (e.g. overcharge, illegal write)</td><td>AgentAuditContract</td></tr></tbody></table>

### Slashing Logic

<table data-header-hidden><thead><tr><th width="188.453125"></th><th width="361.78515625"></th><th></th></tr></thead><tbody><tr><td><strong>Actor</strong></td><td><strong>Condition</strong></td><td><strong>Slash Amount (example)</strong></td></tr><tr><td>Proposer</td><td>Proven to have submitted invalid block/proof</td><td>30%–100% of stake</td></tr><tr><td>Validator</td><td>Signed off on invalid block (optional check)</td><td>10%–30% if collusion</td></tr><tr><td>Challenger</td><td>Submitted invalid challenge</td><td>Forfeit 1%–5% challenge bond</td></tr></tbody></table>

### Challenge Timing Parameters

<table data-header-hidden><thead><tr><th width="191.78515625"></th><th width="362.08203125"></th><th></th></tr></thead><tbody><tr><td><strong>Parameter</strong></td><td><strong>Description</strong></td><td><strong>Example Value</strong></td></tr><tr><td>challengeWindow</td><td>Max blocks after proposal that a challenge is valid</td><td>100 blocks</td></tr><tr><td>verificationTimeout</td><td>Max time for contract to verify a proof</td><td>1 minute</td></tr><tr><td>slashingDelay</td><td>Delay before applying slashing, to allow appeals</td><td>10 blocks</td></tr></tbody></table>

### Integration with DAT

* Fraudulent data detected → affected DAT tokens are frozen or burned.
* Ownership reverted or flagged in registry.
* Affected classId can be blacklisted temporarily.
* Future token mints in that class may require stronger verification (e.g., quorum + external verifier).

### Incentive Summary

<table data-header-hidden><thead><tr><th width="189.046875"></th><th></th></tr></thead><tbody><tr><td><strong>Role</strong></td><td><strong>Incentive</strong></td></tr><tr><td>Challenger</td><td>Wins reward from slashed stake if proof is valid</td></tr><tr><td>Validator</td><td>Earns block rewards, but penalized for signing off on invalidity</td></tr><tr><td>Proposer</td><td>Gets rewards if honest, slashed if caught submitting invalid work</td></tr><tr><td>iDAO</td><td>Maintains reputation and stake power through accurate participation</td></tr></tbody></table>

#### Example

Dataset submitted with wrong hash, minted as DAT.

A challenger finds the original file on IPFS and submits a Merkle branch proving mismatch.

challengeBlock() is called, validated → proposer slashed, challenger rewarded, DAT frozen.


# Quorum Rotation & Benefit

### Dynamic Quorum Rotation

* Periodically or based on time/epoch:
  * A staking contract selects the next quorum using stake-weighted randomness.
  * Top-N iDAO nodes are assigned to the next active quorum.
  * Transition is smooth and predictable (e.g., every 100 blocks).

### Benefits of LazAI QBFT

<table data-header-hidden><thead><tr><th width="194.78515625"></th><th></th></tr></thead><tbody><tr><td>Verifiability</td><td>Supports cryptographic proofs for AI models and datasets.</td></tr><tr><td>Scalability</td><td>Quorum sharding ensures horizontal scalability.</td></tr><tr><td>AI-Native Validity</td><td>Direct integration with ZK-SNARKs, OP, and TEEs.</td></tr><tr><td>Incentivized Security</td><td>Built-in slashing &#x26; challenge rewards system.</td></tr><tr><td>Modular Integration</td><td>Works with DAT token minting, iDAO governance, and Alith agent execution.</td></tr></tbody></table>


# Architecture

### Overview

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdypX78KRXSmLoMtTIddBjD8Pyn9VuAhDU-OhHfzd35We0Ks7HmR9xIfi54eG_vjWRcA6kYCSf0gVPULSXogF5PpqakBMxSVwPFI6yiD2yNhFh6qd7HOg6tPpEf_ARqD3vs9P-p7Q?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

### DAT-Centric Data and AI Pipeline

<figure><img src="/files/iiNqvALAD7oAQh0CDSXi" alt=""><figcaption></figcaption></figure>

### Core Component&#x20;

<figure><img src="/files/6RRga9EdDVj3bMxgfKUt" alt=""><figcaption></figcaption></figure>


# E2E Process

LazAI, we can divide workflows into data setup process, data usage process, and inference process according to different roles, corresponding to users who want to contribute data to obtain tokens and exchange tokens for data or models.

### Data Setup Process

<figure><img src="/files/hh6R5MSfWWKyvZxhSsLQ" alt="" width="563"><figcaption></figcaption></figure>

### Data Usage & Inference Process

<figure><img src="/files/WqkopAnsqx7GVBmcyLtN" alt="" width="563"><figcaption></figcaption></figure>

LazChain nodes not only consist of regular execution nodes and validation nodes, but also provide AI nodes (AI Execution Extension) for routine AI task execution such as model pulling and deployment, data processing, on-chain inference, and other processes.

Users provide POV and send the data to the blockchain in the form of transactions. POV is usually stored in the form of tensors and can be transmitted and stored in blocks when necessary. Users can submit publicly available tensor data or ZK proof of data to the blockchain, and provide the required model ID for subsequent inference tasks. Meanwhile, LazAI provides the Alith framework to assist users in data processing, format conversion, compression and interaction with LazChain.

When LazChain receives a POV, it will execute the corresponding contract code to request the DAO contract to perform data fingerprint verification. After verification is passed, the DAO contract can pull remote or local models to establish inference services in the AI node. The basic capabilities required for the inference services and the coprocessor acceleration are provided through AI precompile contracts.

After the user submits the POV data, they can send a data or inference request to LazChain to obtain data verification. After the data verification is completed, the data contribution is recorded and the corresponding DAT token is obtained. In addition, the LazAI network settles based on data and computing resource usage and includes a dynamic strategy for fees based on community and market conditions. For details, please refer to the settlement section.


# POV Data Structure

POV is a protocol and standard for data unification In LazAI.  A basic POV data includes the following fields:

\
A basic POV data includes the following fields:

`message POV {`

&#x20; `bytes data_hash = 1;`

&#x20; `string data_tag = 2; // LLM weight, dataset metadata, user info, inference prompt`

&#x20; `string data_type = 2; // f32, f16, …`

&#x20; `Bytes data_size = 3; // data tensor size`

&#x20; `Tensor data = 4;`

&#x20; `uint64 timestamp = 5;`

&#x20; `Proof proof = 6; // Optional data proof`

`}`

Considering that different users may have different data sources and modalities, which typically include text, speech, images, videos, and other modalities as well as different formats, we need to unify them into a fixed POV format. POV uses tensors for encoding and decoding, which records information such as hash, class, and timestamp of the data. Users need to submit the compressed POV data format for uploading on the chain.

### Privacy Data & Public Data

At LazAI, we encourage open data formats and content, so POV supports storing data in a public form on the chain that anyone can access. However, for private data, LazAI also supports off chain storage. LazAI can efficiently verify the integrity and consistency of off chain data without storing all data on the chain. LazAI provides higher privacy protection and trustworthiness assurance for off chain data, avoiding potential risks of centralized data sources and promoting the development of decentralized data governance. iDAO，Its function is similar to that of a traditional data center, but the data does not need to be directly stored on the blockchain. Users only need to submit a proof for uploading to the blockchain.

LazAI mainly supports private data on-chain. In theory, it can support data of any size to calculate its credentials on-chain. For public data, it will be limited to 32K, which is similar to the storage requirements of the chain and the context window of general AI models. Through the Alith Agent toolkit, users can perform data preprocessing and proof calculation locally, and upload data to the LazAI network, making the data available but invisible.

### Privacy Data Workflow

In LazAI, we use OpenPGP to encrypt and decrypt the privacy data. OpenPGP encryption process: Randomly generate a Key and use it to encrypt data using a symmetric encryption algorithm. Finally, use an asymmetric encryption algorithm (RSA) to encrypt the recipient's Key using the receiver's public key to obtain encrypted data.&#x20;

Specifically, we obtain a random key from the user's Web3 wallet, such as Metamask, and use this random key to encrypt the user's private data. This process verifies the sender's identity, and then uses the asymmetric encryption algorithm (RSA) to encrypt the recipient's key (which can be obtained by requesting LazAI's data registration contract to obtain the public key) to obtain the encrypted data. We then upload the encrypted data to DA (such as IPFS, Google Drive, or Dropbox), and register the encrypted data URL and Encrypt key to the LazAI contract. The test data verifier can decrypt the encrypted key using the private key and download the private data for decryption through the URL. The decryption process is placed in TEE to ensure data security. Will not be tampered with, and then decrypted data and TEE generates proof and uploads it to LazAI contract for verification.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdBD2giCUcqv6ag4h6wGHu3emMvoU_4GRWBK9ikq65KG-FJ4BMkU6PLsS-6Xvj9NKHeJdLvURoa3kA064I8XU0bybXzFy5xgVdacMtTF6tiekJOKvhN2wOVkqdnO9ZUgVY5V82VCQ?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt="" width="375"><figcaption></figcaption></figure>

<br>

### How to expand the Data Structure

Considering that user data is mainly used for model training and on chain inference, the only guarantee is that they need to meet the input requirements of the model. Therefore, LazAI provides the Alith Agent framework and Model Context Protocol (MCP) to complete multimodal and various data format preprocessing, as well as POV tensor data conversion. The advantage of this is that we can support as many types of data as possible at the application layer without modifying the blockchain network and protocols.


# AI Execution Mechanism

### AI Node (AI Execution Extension)&#x20;

The AI node mainly includes an EVM-compatible LazVM for AI computing and gas settlement, and its main process is as follows:

<figure><img src="/files/4XAoUJszuO3dx9rYqkya" alt=""><figcaption></figcaption></figure>

### Request

For AI training and inference, users send inference or training requests to AI nodes. Taking an inference request as an example, it is compatible with the OpenAI API. Users need to provide additional DAT ID for additional data acquisition, wallet signature and nonce for inference fee settlement.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcWHMXXDZzY-s00tsyCPQdExmJCC_k47v02N_bmwb7xX8XIOMhreS-dbx2QCY5w3mxqQKO7Jupzf_9NTlSSuVK5GaKdz0oCFcXztJAqjF7HvOtcHzhv7EJ47mKbHUPGjVzyJWXcmA?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

### LazVM

* EVM-Compatible: Ensures compatibility with existing Ethereum Virtual Machine tools and smart contracts.
* AI Computing: Specialized execution environment for AI workloads.
* Gas Settlement: Integrated gas mechanism to track and settle computational costs.

#### AI & Proof Precompile

* **Computation Orchestration:** Coordinates between LazVM and GPU Coprocessor including model loaders, tokenizers, embedders, tensor kernels, attention kernels and SIMD, etc.
* **Proof Verification:** Validates computation proofs returned from GPU Coprocessor including proof kernels. Besides, we will reserve op and zk proof interfaces to support multiple op and zk systems: e.g., STARKs, PLONK or any component from zkMIPS.

#### GPU Coprocessor

* Accelerated Computing: Dedicated hardware acceleration for AI computations.
* Proof Generation: Creates cryptographic proofs of correct computation execution.
* Resource Monitoring: Tracks computational resources used during inference.

The Execution Layer is designed to support verifiable AI computation, inference optimization, and seamless AI asset deployment. This layer ensures that AI agents and models operate efficiently and transparently within LazAI’s decentralized ecosystem.

By implementing trustless AI execution mechanisms, the Execution Layer ensures transparency, security, and scalability for AI applications in Web3.

### Settlement Layer

The Settlement Layer transforms AI-related data, models, and agents into tokenized assets, ensuring secure, traceable, and programmable ownership.

**GasAI = α⋅FLOPs+γ**

**GasInference = β⋅Mempeak**

**GasEstimate = P ⋅ T**

**Where:**

* α = FLOPs rate coefficient (adjustable via governance).
* β = Memory peak rate coefficient (adjustable via governance).
* γ = Base gas cost for AI operations including data store and computing resources.
* FLOPs = Floating Point Operations (computational workload metric).
* Mempeak = Peak memory usage during computation.

In addition, here we refer to EIP1559 to dynamically adjust the gas price, which includes a basic fixed fee and a part based on market conditions.

### Quorum-based BFT Consensus Protocol & iDAO

LazAI blockchain leverages a Quorum-based Byzantine Fault Tolerance (BFT) consensus mechanism, distributing data governance and storage across multiple decentralized Quorum organizations to ensure both reliability and transparency.

* Each Quorum operates as an iDAO, functioning similarly to a traditional data center but without the need to store data directly on-chain, significantly reducing on-chain storage costs.
* These iDAO organizations reach consensus to validate and ensure the trustworthiness of off-chain data, enabling its rapid and efficient delivery to both on-chain and off-chain agents, while maintaining high availability and low latency.

#### The main responsibilities of iDAO include:

1. Providing Trustworthy AI Data Sources or AI Flow\
   Offering reliable data sources or AI workflows to other individuals or organizations, ensuring high-quality and aligned data.
2. Off-Chain Dataset\
   Conducting off-chain dataset, providing AI Agent services to perform more efficient AI operations.
3. Decentralized Consensus and Data Governance\
   iDAO participates in the LazChain consensus in the form of a Quorum. Through the decentralization of multiple Quorum organizations, it ensures the reliability and transparency of data governance and storage. Each Quorum acts as an independent iDAO, similar to a traditional data center, but without storing data directly on-chain, effectively reducing on-chain storage costs. iDAO organizations achieve consensus to verify the trustworthiness of off-chain data, ensuring that data is efficiently and quickly available to both on-chain and off-chain agents while ensuring high availability and low latency.

<br>


# DAT Specifications & Flow

LazAI’s Data Anchoring Token (DAT) is a semi-fungible token (SFT) standard designed for AI dataset anchoring, licensing, and AI model provenance tracking. This protocol introduces a multi-layered ownership model, ensuring composability, structured access control, and verifiable AI asset usage in a decentralized ecosystem.

<figure><img src="/files/r6MqZanfEEUDPn45aaMe" alt=""><figcaption></figcaption></figure>

LazAI’s Data Anchoring Token (DAT) protocol redefines AI dataset ownership, licensing, and provenance tracking by integrating semi-fungible tokenization, on-chain verification, and decentralized AI economy models.

* **AI-Composable Economy:** Enables dataset/model composability for seamless AI evolution.
* **Verifiable AI Assets:** Ensures trustless authentication through cryptographic proofs.
* **Privacy-Preserving AI Training:** Supports ZK-protected AI model development.
* **AI Data Exchange & Monetization:** Unlocks new AI business models, allowing transparent revenue sharing.

This AI-first SFT standard establishes a scalable, trustless AI asset ecosystem, distinct from previous tokenization models.


# Detailed Design of DAT

The DAT protocol introduces a structured AI asset management system, leveraging on-chain metadata, off-chain data storage, and cryptographic proofs to ensure security, transparency, and usability.

### Core Data Structure of DAT

Each DAT token instance consists of the following attributes:

<table data-header-hidden><thead><tr><th width="184.58203125"></th><th width="158.83984375"></th><th width="277.49609375"></th></tr></thead><tbody><tr><td><strong>Attribute</strong></td><td><strong>Type</strong></td><td><strong>Description</strong></td></tr><tr><td>DAT ID</td><td>uint256</td><td>Unique identifier for the tokenized AI dataset or model.</td></tr><tr><td>Asset Type</td><td>enum { Dataset, Model, AI-Agent } </td><td>Specifies whether the token represents a dataset, AI model, or an autonomous AI agent.</td></tr><tr><td>Slot ID (Category Tagging) </td><td>uint256</td><td>Defines the classification of AI assets, allowing datasets/models of the same category to be grouped for composability.</td></tr><tr><td>Partitioned Value (Token Units) </td><td>uint256</td><td>Represents divisible ownership or access quotas, enabling fractional AI asset ownership and licensing.</td></tr><tr><td>Access Control (Permissions) </td><td>struct { readOnly, trainable, inferenceOnly, composable }</td><td>Defines who can use the AI dataset/model and under what conditions.</td></tr><tr><td>Dataset Provenance Hash</td><td>bytes32</td><td>Hash of the dataset, anchoring off-chain data integrity (IPFS, Arweave, Filecoin).</td></tr><tr><td>Usage State</td><td>mapping (address => uint256)</td><td>Tracks AI training/inference requests, ensuring proper usage-based payments.</td></tr><tr><td>Revenue Model </td><td>mapping (address => uint256) </td><td>Specifies how revenue is distributed among data contributors, model developers, and validators.</td></tr></tbody></table>

### AI Data Anchoring & Validation Mechanism

The integrity and trustworthiness of AI datasets and models are secured through on-chain anchoring and decentralized verification mechanisms.

* **Data Anchoring Process**
  * **Dataset Submission →** iDAO submits dataset metadata, cryptographic proofs (Merkle Tree, ZK Proofs), and storage references (IPFS, Arweave).
  * **Anchoring & Hashing →** A dataset fingerprint (hash) is generated and stored on-chain via DAT token metadata.
  * **Token Minting →** The system mints a DAT token representing the dataset, with predefined access rights, licensing conditions, and revenue-sharing logic.
* **Decentralized Verification**
  * **Proof-of-Authenticity:** AI datasets and models require zero-knowledge proof (ZKP) verification, ensuring they were generated from valid sources.
  * **Fraud-Proof Mechanism:** Challengers can submit fraud proofs against datasets/models that violate integrity rules. If successfully disputed, the original submitter is slashed, and the challenger is rewarded.


# DAT Token Lifecycle

The LazAI AI Data Economy is built around programmable AI licensing, ownership trading, and dataset/model composability.&#x20;

#### Token Minting & Ownership Structure

DAT tokens can be minted by AI data contributors, model creators, or AI agents via a structured issuance process:

1. **AI Data Submission:** The data provider submits dataset metadata to LazAI Flow.
2. **Validation & Anchoring:** The Quorum-based verification process confirms authenticity, generating a hashed dataset fingerprint.
3. **Token Minting:** The system mints a DAT token, encoding: Ownership rights, Usage-based pricing models, Access control permissions
4. **Revenue Distribution Rules:** The DAT contract automatically distributes revenue when datasets/models are used.

#### AI Data & Model Exchange

DAT supports AI dataset licensing and model trading through fractional ownership and dynamic pricing mechanisms.

<table data-header-hidden><thead><tr><th width="255.9140625"></th><th></th></tr></thead><tbody><tr><td><strong>Feature</strong></td><td><strong>Implementation</strong></td></tr><tr><td>Fractional Ownership Trading</td><td>Users can sell or trade partial ownership of datasets without full asset transfer.</td></tr><tr><td>AI Model Evolution</td><td>Developers can fork datasets/models while ensuring original contributors retain revenue-sharing rights.</td></tr><tr><td>Permission-Based Dataset Licensing</td><td>Data owners set usage conditions (read-only, trainable, composable), enforced via on-chain access control.</td></tr><tr><td>Dynamic AI Marketplace</td><td>AI models and datasets are tokenized &#x26; exchanged as DAT, enabling seamless monetization of AI assets.</td></tr></tbody></table>


# Security, Privacy, & Trust

**Cryptographic AI Asset Protection**

* **ZK-Protected AI Data Usage:** Users can train AI models on encrypted datasets without direct access, ensuring privacy-preserving AI development.
* **Merkle Proofs for Dataset Integrity:** All datasets include on-chain proofs of authenticity, preventing tampering or duplication.

**Challenger-Based Fraud Detection**

* **Challenger Model:** Any participant can challenge datasets/models with fraudulent claims.
* **Slashing Mechanism:** If a dataset is found to be invalid or misleading, the submitter is penalized, and challengers are rewarded.


# DAT Interaction Flow

On-Chain & Off-Chain

The following diagram illustrates the full lifecycle of a DAT token, from submission to verification, trading, and AI execution.

1. **iDAO Submits AI Data & Model (LazAI Flow):** Metadata, dataset hashes, and storage locations are submitted to LazAI Flow.
2. **Verification & Token Minting:** The LazChain network validates dataset integrity and mints the DAT token.
3. **AI Dataset/Model Usage:** Users request AI training/inference access, enforced via DAT-based smart contracts.
4. **Fraud-Proof Submission & Dispute Resolution:** Challengers can submit fraud proofs if AI models are biased or invalid.
5. **Revenue Distribution:** AI data/model owners receive royalty-based revenue upon each usage.

LazAI’s Data Anchoring Token (DAT) protocol redefines AI dataset ownership, licensing, and provenance tracking by integrating semi-fungible tokenization, on-chain verification, and decentralized AI economy models.


# Build your Digital Twin using LazAI

Your Digital Twin is an AI persona that speaks in your voice. We generate it from your Twitter/X archive, store it in a portable Characterfile (character.json), and load it into an Alith agent that writes tweets for you (manually or on a schedule).

### Why a Digital Twin?

* Portable persona: Single JSON file that any LLM agent can use
* Separation of concerns: Keep *style/persona* in JSON; keep *logic* in code
* Composable: Swap personas without touching the app

### Prerequisites

* macOS/WSL/Linux with Node.js 18+
* An OpenAI or Anthropic (Claude) API key
* A Twitter/X account + your archive .zip

### Step 0 — Clone the starter kit and install the dependencies

```bash
git clone https://github.com/0xLazAI/Digital-Twin-Starter-kit.git

cd Digital-Twin-Starter-kit
```

### Step 1 — Generate your Characterfile from Tweets

1. Request your archive

   Get it from X/Twitter: Settings → Download an archive.
2. Run the generator

```
# You can run this anywhere; no cloning needed
npx tweets2character ~/Downloads/twitter-YYYY-MM-DD-<hash>.zip
```

* Choose openai or claude
* Paste your API key when prompted
* Output: a character.json in the current directory

<br>

3. Move it into the Digital-Twin-Starter-kit Directrory

   Place character.json at your root (same level as index.js), e.g.:

```
/Digital-Twin-Starter-kit
  ├─ controller/
  ├─ routes/
  ├─ services/
  ├─ character.json   ← here
  └─ index.js
```

### Step 2 — Feed character.json to an Alith Agent

We create an Alith agent at runtime and pass your character as a preamble. This keeps persona separate from code and makes it hot‑swappable.

* Loads character.json
* Builds an Alith preamble from bio/lore/style
* Generates a tweet in your voice
* Provides postTweet (manual) and autoTweet (cron) helpers

{% code overflow="wrap" %}

```javascript
// controller/twitterController.js
const { initializeTwitterClient } = require('../config/twitter');

const fs = require('fs');
const path = require('path');

// Load character data
const characterData = JSON.parse(
  fs.readFileSync(path.join(__dirname, '../character.json'), 'utf8')
);

// alith function with our character 
const alithfunction = async (username = "") => {
  try {
    const { Agent, LLM } = await import('alith');

    const preamble = [
      `You are ${characterData.name}.`,
      characterData.bio?.join(' ') || '',
      characterData.lore ? `Lore: ${characterData.lore.join(' ')}` : '',
      characterData.adjectives ? `Traits: ${characterData.adjectives.join(', ')}` : '',
      characterData.style?.post ? `Style for posts: ${characterData.style.post.join(' ')}` : '',
    ].filter(Boolean).join('\n');

    const model = LLM.from_model_name(process.env.LLM_MODEL || 'gpt-4o-mini');
    const agent = Agent.new('twitter_agent', model).preamble(preamble);

    const prompt = [
      `Write one tweet in ${characterData.name}'s voice.`,
      username ? `Optionally greet @${username}.` : '',
      `<=240 chars, no code blocks, hashtags only if essential.`
    ].join(' ');

    const chat = agent.chat();
    const result = await chat.user(prompt).complete();
    const text = (result?.content || '').toString().trim();

    if (!text) throw new Error('Empty tweet from agent');
    return text.slice(0, 240);
  } catch (err) {
    // Fallback to examples if Alith/model is unavailable
    const examples = characterData.postExamples || [];
    const base = examples[Math.floor(Math.random() * examples.length)] || 'Hello from my agent!';
    return username ? `${base} @${username}`.slice(0, 240) : base.slice(0, 240);
  }
};

const generateQuirkyMessage = async (username) => {
  return await alithfunction(username);
};

let twitterClient = null;

// New function for cron job - posts tweet without requiring request/response
const postTweetCron = async () => {
  try {
    console.log('Cron job: Starting tweet posting...');

    // Initialize Twitter client if not already initialized
    if (!twitterClient) {
      console.log('Cron job: Initializing Twitter client...');
      twitterClient = await initializeTwitterClient();
    }

    // Generate message for cron job (you can customize this)
    const message = await generateQuirkyMessage('cron');
    
    console.log('Cron job: Posting tweet with message:', message);

    // Send the tweet
    const tweetResult = await twitterClient.sendTweet(message);
    console.log('Cron job: Tweet result:', tweetResult);

    // Log success
    const tweetId = tweetResult.id || tweetResult.id_str;
    if (tweetId) {
      const tweetUrl = `https://twitter.com/${process.env.TWITTER_USERNAME}/status/${tweetId}`;
      console.log('Cron job: Tweet posted successfully:', tweetUrl);
    } else {
      console.log('Cron job: Tweet posted but no ID received');
    }

    return { success: true, message: 'Tweet posted via cron job' };

  } catch (error) {
    console.error('Cron job: Error in postTweetCron:', error);
    
    if (error.message.includes('authentication')) {
      twitterClient = null;
    }
    
    throw error;
  }
};

const postTweet = async (req, res) => {
  console.log('Received request body:', req.body);

  try {
    const { username, address } = req.body;

    console.log('Processing username:', username);

    // Initialize Twitter client if not already initialized
    if (!twitterClient) {
      console.log('Initializing Twitter client...');
      twitterClient = await initializeTwitterClient();
    }

    // Remove @ symbol if included
    const cleanUsername = username.replace('@', '');
    const message = await generateQuirkyMessage(cleanUsername);

    console.log('Posting tweet with message:', message);

    try {
      // Send the tweet
      const tweetResult = await twitterClient.sendTweet(message);
      console.log('Tweet result:', tweetResult);

      // Instead of fetching tweet details again, construct URL from the initial response
      // Most Twitter API responses include either an id or id_str field
      const tweetId = tweetResult.id || tweetResult.id_str;
      console.log(tweetId)
      
      if (!tweetId) {
        console.log('Tweet posted but no ID received:', tweetResult);
        return res.status(200).json({
          success: true,
          message: 'Tweet posted successfully',
          tweetUrl: `https://twitter.com/${process.env.TWITTER_USERNAME}/`, // Fallback URL
          tweetText: message,
          updatedScore: 0
        });
      }

      const tweetUrl = `https://twitter.com/${process.env.TWITTER_USERNAME}/status/${tweetId}`;
      console.log('Constructed tweet URL:', tweetUrl);

      return res.status(200).json({
        success: true,
        message: 'Tweet posted successfully',
        tweetUrl,
        tweetText: message,
        updatedScore: 0
      });

    } catch (tweetError) {
      console.error('Error with tweet operation:', tweetError);
      throw tweetError;
    }

  } catch (error) {
    console.error('Error in postTweet:', error);
    
    if (error.message.includes('authentication')) {
      twitterClient = null;
    }

    return res.status(500).json({
      error: 'Failed to post tweet',
      details: error.message
    });
  }
};



module.exports = {
  postTweet,
  postTweetCron

};

```

{% endcode %}

Environment

```
# .env

TWITTER_USERNAME=username
TWITTER_PASSWORD=password
TWITTER_EMAIL=email

# Alith / LLM
LLM_MODEL=gpt-4o-mini
ALITH_API_KEY=your_key_if_required   # only if your Alith setup needs it
```

Install deps:

```
npm i alith node-cron
# or pnpm add alith node-cron
```

### Step 3 — Auto‑Tweet via Cron (uses your Digital Twin)

<br>

We schedule the agent to post automatically (e.g., at minute 5 every hour).

services/cronService.js

```javascript
const cron = require('node-cron');
const { postTweetCron } = require('../controller/twitterController');

class CronService {
  constructor() {
    this.isRunning = false;
  }

  start() {
    if (this.isRunning) {
      console.log('Cron service is already running');
      return;
    }

    console.log('Starting cron service...');
    
    // Schedule tweet posting every 1 minute
    cron.schedule('* * * * *', async () => {
      console.log('Cron job triggered: Posting tweet...');
      try {
        await postTweetCron();
        console.log('Tweet posted successfully via cron job');
      } catch (error) {
        console.error('Error in cron job tweet posting:', error);
      }
    }, {
      scheduled: true,
      timezone: "UTC"
    });

    this.isRunning = true;
    console.log('Cron service started successfully. Tweets will be posted every minute.');
  }

  stop() {
    if (!this.isRunning) {
      console.log('Cron service is not running');
      return;
    }

    console.log('Stopping cron service...');
    cron.getTasks().forEach(task => task.stop());
    this.isRunning = false;
    console.log('Cron service stopped');
  }

  getStatus() {
    return {
      isRunning: this.isRunning,
      nextRun: this.isRunning ? 'Every minute' : 'Not scheduled'
    };
  }
}

module.exports = CronService; 
```

<br>

index.js (ESM)

```javascript
import express from "express";
import cors from "cors";


import dotenv from 'dotenv';
dotenv.config();
import twitterRoutes from './routes/twitterRoutes.js';
import CronService from './services/cronService.js';

const app = express();
const cronService = new CronService();

app.use(cors({
  origin: '*', // Allow all origins
}));


app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Debug middleware to log requests
app.use((req, res, next) => {
  console.log('Received request:', {
    method: req.method,
    path: req.path,
    body: req.body,
    headers: req.headers
  });
  next();
});

app.use('/api', twitterRoutes);

// Add cron status endpoint
app.get('/api/cron/status', (req, res) => {
  const status = cronService.getStatus();
  res.json(status);
});

// Add cron control endpoints (optional - for manual control)
app.post('/api/cron/start', (req, res) => {
  cronService.start();
  res.json({ message: 'Cron service started' });
});

app.post('/api/cron/stop', (req, res) => {
  cronService.stop();
  res.json({ message: 'Cron service stopped' });
});


// Error handling middleware
app.use((err, req, res, next) => {
  console.error('Server error:', err);
  res.status(500).json({
    error: 'Internal server error',
    details: err.message
  });
});

app.use(express.json({ limit: '10mb' })); 
app.use(express.urlencoded({ limit: '10mb', extended: true }));




const port = process.env.PORT || 3005;
app.listen(port, () => {
  console.log(`Server started on port ${port}`);
  
  // Start the cron service
  cronService.start();
});
```

Route

```javascript
// routes/twitterRoutes.js
const express = require('express');
const router = express.Router();
const { postTweet } = require('../controller/twitterController');

router.post('/tweet', postTweet);
module.exports = router;
```

Manual test

```
curl -X POST http://localhost:3000/tweet \
  -H "Content-Type: application/json" \
  -d '{"username":"someone"}'
```

```bash
npm run dev
```

### Updating Your Twin

* Re‑run npx tweets2character any time you want a fresh persona.
* Replace character.json and restart your server.
* The agent will immediately pick up the new style/preamble.

### Tips & Gotchas

* CommonJS + ESM: Alith is ESM, your project is CJS → use dynamic import inside functions (shown above).
* Length control: We trim to 240 chars to be safe with links/quoted tweets.
* Fallbacks: If the model isn’t reachable, we fall back to postExamples from your character file.
* Safety: Add your own guardrails (e.g., profanity, duplicates, rate limits) before posting.


# Introduction

### LazAI API

The LazAI API provides a simple way to run AI inference on private data without losing control of your information.

It enables developers to perform context engineering, training, and evaluation directly on LazAI ensuring that data never leaves the owner’s control.

Once you contribute your private data and mint a Data Anchoring Token (DAT), you can invoke AI models in a privacy-preserving way.

This workflow guarantees that your sensitive data remains secure, auditable, and owned by you, while still powering intelligent AI services.

***

### Why Private Data Inference?

Data privacy is essential in industries such as healthcare, finance, and research.

Traditional AI services often require uploading datasets to centralized servers, increasing the risk of data exposure or misuse.

With LazAI, inference happens securely on your own terms:

* No data handover: Your dataset never leaves your control.
* End-to-end encryption: All model calls and outputs are cryptographically secured.
* Verifiable execution: Each inference request can be verified using on-chain proofs.
* Ownership preserved: You retain ownership and monetization rights via the DAT standard.

This allows you to build and run value-aligned AI agents that respect data sovereignty combining performance with full privacy compliance.

***

### Next Steps

Continue with the following guides to learn how to use the LazAI API in different environments:

* [Using Python](/private-data-inference/lazai-api/using-python)
* [Using Node.js](/private-data-inference/lazai-api/using-nodejs)
* [Using Rust](/private-data-inference/lazai-api/using-rust)


# LazAI API

### Workflow Overview

#### Contribute Data

Complete the Data Contribution workflow and obtain your File ID after minting DAT.\
Checkout the below section to contribute your data.

{% content-ref url="/pages/hnSMIbWKVYFMb76P3VTH" %}
[Mint your DAT](/data-anchoring-token-dat/developer-implementation/mint-your-dat)
{% endcontent-ref %}

#### Run Inference Server

Start a local or remote inference server that can process requests on your private data.

#### Request Inference

Use the LazAI client to send an inference request, referencing your File ID and providing settlement headers for secure access.


# Using Python

#### Best Practice: Use a Python Virtual Environment

To avoid dependency conflicts and keep your environment clean, create and activate a Python virtual environment before installing any packages:

```bash
python3 -m venv venvsource venv/bin/activate
```

#### Install Dependencies

```bash
pip install llama-cpp-python pymilvus "pymilvus[model]"
```

#### Install Alith

<pre class="language-bash"><code class="lang-bash"><strong>python3 -m pip install alith -U
</strong></code></pre>

#### Set Environment Variables

For OpenAI/ChatGPT API:

```bash
export PRIVATE_KEY=<your wallet private key>
export OPENAI_API_KEY=<your openai api key>
```

For other OpenAI-compatible APIs (DeepSeek, Gemini, etc.):

```bash
export PRIVATE_KEY=<your wallet private key>
export LLM_API_KEY=<your api key>
export LLM_BASE_URL=<your api base url>
```

#### Step 1: Run the Inference Server

> **Note:** The public address of the private key you expose to the inference server is the `LAZAI_IDAO_ADDRESS`. Once the inference server is running, the URL must be registered using the `add_inference_node` function in Alith. This can only be done by LazAI admins.

**Local Development**

For OpenAI/ChatGPT API:

```python
from alith.inference import run
 
"""Run the server and use the following command to test the server
 
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "X-LazAI-User: 0xc3e98E8A9aACFc9ff7578C2F3BA48CA4477Ecf49" \
-H "X-LazAI-Nonce: 123456" \
-H "X-LazAI-Signature: HSDGYUSDOWP123" \
-H "X-LazAI-Token-ID: 1" \
-d '{
  "model": "gpt-3.5-turbo",
  "messages": [
    {"role": "system", "content": "You are a helpful assistant"},
    {"role": "user", "content": "What is the capital of France?"}
  ],
  "temperature": 0.7,
  "max_tokens": 100
}'
"""
server = run(model="gpt-3.5-turbo", settlement=True, engine_type="openai")

```

For other OpenAI-compatible APIs (DeepSeek, Gemini, etc.):

```python
from alith.inference import run
 
# Example: Using DeepSeek model from OpenRouter
server = run(settlement=True, engine_type="openai", model="deepseek/deepseek-r1-0528")
```

**Production Deployment on Phala TEE Cloud**

For production-ready applications, deploy your inference server on [Phala TEE Cloud ](https://docs.phala.network/phala-cloud/references/tee-cloud-cli) for enhanced security and privacy. Once deployed, you will receive an inference URL that needs to be registered using the `add_inference_node` function by LazAI admins.

You can also use the existing inference nodes.

#### Step 2: Request Inference via LazAI Client

```python
from alith import Agent, LazAIClient
 
# 1. Join the iDAO, register user wallet on LazAI and deposit fees (Only Once)
LAZAI_IDAO_ADDRESS = "0xc3e98E8A9aACFc9ff7578C2F3BA48CA4477Ecf49" # Replace with your own address
client = LazAIClient()

try:
    client.get_user(client.wallet.address)
    print("User already exists")
except Exception:
    print("User does not exist, adding user")
    client.add_user(10000000)
    client.deposit_inference(LAZAI_IDAO_ADDRESS, 1000000)
# 2. Request the inference server with the settlement headers and DAT file id
file_id = 11  # Use the File ID you received from the Data Contribution step
url = client.get_inference_node(LAZAI_IDAO_ADDRESS)[1]
print("url", url)
agent = Agent(
    # Note: replace with your model here
    model="gpt-3.5-turbo",

    base_url=f"{url}/v1",
    # Extra headers for settlement and DAT file anchoring
    extra_headers=client.get_request_headers(LAZAI_IDAO_ADDRESS, file_id=file_id),
)
print(agent.prompt("summarize it"))
```

***

### Security & Privacy

* **Your data never leaves your control.** Inference is performed in a privacy-preserving environment, using cryptographic settlement and secure computation.
* **Settlement headers** ensure only authorized users and nodes can access your data for inference.
* **File ID** links your inference request to the specific data you contributed, maintaining a verifiable chain of custody.


# Using NodeJS

#### Project Setup

```bash
mkdir lazai-inference
cd lazai-inference
npm init -y
```

#### Install Alith

```bash
npm i alith@latest
```

#### Create TypeScript Configuration

Create a file named `tsconfig.json` with the following content:

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "allowJs": true,
    "strict": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true
  },
  "ts-node": {
    "esm": true
  },
  "include": ["*.ts"],
  "exclude": ["node_modules"]
}
```

#### Set Environment Variables

For OpenAI/ChatGPT API:

```bash
export PRIVATE_KEY=<your wallet private key>
export OPENAI_API_KEY=<your openai api key>
```

For other OpenAI-compatible APIs (DeepSeek, Gemini, etc.):

```bash
export PRIVATE_KEY=<your wallet private key>
export LLM_API_KEY=<your api key>
export LLM_BASE_URL=<your api base url>
```

#### Step 1: Request Inference via LazAI Client

Create a file named `app.ts` with the following content:

```typescript
import { ChainConfig, Client } from "alith/lazai";
import { Agent } from "alith";
 
// Set up the private key for authentication
process.env.PRIVATE_KEY = "<your wallet private key>";
 
const node = "0xc3e98E8A9aACFc9ff7578C2F3BA48CA4477Ecf49"; // Replace with your own inference node address
const client = new Client(ChainConfig.testnet());
 
await client.getUser(client.getWallet().address);
 
console.log(
  "The inference account of user is",
  await client.getInferenceAccount(client.getWallet().address, node)
);
 
const fileId = 10;
const nodeInfo = await client.getInferenceNode(node);
const url = nodeInfo.url;
const agent = new Agent({
  // OpenAI-compatible inference server URL
  baseUrl: `${url}/v1`,
  model: "gpt-3.5-turbo",
  // Extra headers for settlement and DAT file anchoring
  extraHeaders: await client.getRequestHeaders(node, BigInt(fileId)),
});
console.log(await agent.prompt("What is Alith?"));
```

#### Step 2: Run the Application

```bash
npx tsx app.ts
```


# Using Rust

#### Coming Soon

Rust support for private data inference will be available in future releases.


# LazAI Data Query


# Using Python

#### Best Practice: Use a Python Virtual Environment

To avoid dependency conflicts and keep your environment clean, create and activate a Python virtual environment before installing any packages:

```bash
python3 -m venv venv
source venv/bin/activate
```

#### Install Dependencies

```bash
pip install llama-cpp-python pymilvus "pymilvus[model]"
```

> For local development use the below installation command

```bash
pip install llama-cpp-python pymilvus "pymilvus[milvus_lite]"
```

#### Install Alith

<pre class="language-bash"><code class="lang-bash"><strong>python3 -m pip install alith -U
</strong></code></pre>

#### Set Environment Variables

**Note:** The public address of the private key you expose to the Query server is the `LAZAI_IDAO_ADDRESS`. Once the query server is running, the URL must be registered using the `add_query_node` function in Alith. This can only be done by LazAI admins.

> For local development ask LazAI admins to add your wallet address & "<http://localhost:3000>" url to register in Alith funciton.

For OpenAI/ChatGPT API:

```bash
export PRIVATE_KEY=<your wallet private key>
export OPENAI_API_KEY=<your openai api key>
export RSA_PRIVATE_KEY_BASE64=<your rsa private key>
```

For other OpenAI-compatible APIs (DeepSeek, Gemini, etc.):

```bash
export PRIVATE_KEY=<your wallet private key>
export LLM_API_KEY=<your api key>
export LLM_BASE_URL=<your api base url>
```

#### Step 1: Run the Query  Server

**Local Development**

For OpenAI API or OpenAI-compatible APIs (DeepSeek, Gemini, etc.):

```python
import logging
import sys
import json
import uvicorn
import argparse

from fastapi import FastAPI, Response, status
from fastapi.middleware.cors import CORSMiddleware

from alith.lazai import Client
from alith.lazai.node.middleware import HeaderValidationMiddleware
from alith.lazai.node.validator import decrypt_file_url
from alith import MilvusStore, chunk_text
from alith.query.types import QueryRequest
from alith.query.settlement import QueryBillingMiddleware

import os
from dotenv import load_dotenv

load_dotenv()
# Get OpenAI API key from environment variable
PRIVATE_KEY = os.getenv("PRIVATE_KEY")
RSA_PRIVATE_KEY_BASE64 = os.getenv("RSA_PRIVATE_KEY_BASE64")
# LLM_API_KEY = os.getenv("LLM_API_KEY")
# LLM_BASE_URL = os.getenv("LLM_BASE_URL")
# DSTACK_API_KEY = os.getenv("DSTACK_API_KEY")


# Set the API key for OpenAI
os.environ["PRIVATE_KEY"] = PRIVATE_KEY
os.environ["RSA_PRIVATE_KEY_BASE64"] = RSA_PRIVATE_KEY_BASE64
# os.environ["LLM_API_KEY"] = LLM_API_KEY
# os.environ["LLM_BASE_URL"] = LLM_BASE_URL
# os.environ["DSTACK_API_KEY"] = DSTACK_API_KEY


# Logging configuration
logging.basicConfig(
    stream=sys.stdout,
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
client = Client()
app = FastAPI(title="Alith LazAI Privacy Data Query Node", version="1.0.0")

store = MilvusStore()
collection_prefix = "query_"

@app.get("/health")
async def health_check():
    return {"status": "healthy", "message": "Server is running"}

@app.get("/")
async def root():
    return {"message": "Alith LazAI Privacy Data Query Node", "version": "1.0.0"}


@app.post("/query/rag")
async def query_rag(req: QueryRequest):
    try:
        file_id = req.file_id
        if req.file_url:
            file_id = client.get_file_id_by_url(req.file_url)
        if file_id:
            file = client.get_file(file_id)
        else:
            return Response(
                status_code=status.HTTP_400_BAD_REQUEST,
                content=json.dumps(
                    {
                        "error": {
                            "message": "File ID or URL is required",
                            "type": "invalid_request_error",
                        }
                    }
                ),
            )
        owner, file_url, file_hash = file[1], file[2], file[3]
        collection_name = collection_prefix + file_hash
        # Cache data in the vector database
        if not store.has_collection(collection_name):
            encryption_key = client.get_file_permission(
                file_id, client.contract_config.data_registry_address
            )
            data = decrypt_file_url(file_url, encryption_key).decode("utf-8")
            store.create_collection(collection_name=collection_name)
            store.save_docs(chunk_text(data), collection_name=collection_name)
        data = store.search_in(
            req.query, limit=req.limit, collection_name=collection_name
        )
        logger.info(f"Successfully processed request for file: {file}")
        return {
            "data": data,
            "owner": owner,
            "file_id": file_id,
            "file_url": file_url,
            "file_hash": file_hash,
        }
    except Exception as e:
        return Response(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content=json.dumps(
                {
                    "error": {
                        "message": f"Error processing request for req: {req}. Error: {str(e)}",
                        "type": "internal_error",
                    }
                }
            ),
        )


def run(host: str = "0.0.0.0", port: int = 8000, *, settlement: bool = False):

    # FastAPI app and LazAI client initialization

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    if settlement:
        app.add_middleware(HeaderValidationMiddleware)
        app.add_middleware(QueryBillingMiddleware)

    return uvicorn.run(app, host=host, port=port)


if __name__ == "__main__":
    description = "Alith data query server. Host your own embedding models and support language query!"
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument(
        "--host",
        type=str,
        help="Server host",
        default="0.0.0.0",
    )
    parser.add_argument(
        "--port",
        type=int,
        help="Server port",
        default=8000,
    )
    parser.add_argument(
        "--model",
        type=str,
        help="Model name or path",
        default="/root/models/qwen2.5-1.5b-instruct-q5_k_m.gguf",
    )
    args = parser.parse_args()

    run(host=args.host, port=args.port, settlement=False)

```

**Production Deployment on Phala TEE Cloud**

For production-ready applications, deploy your data query server on [Phala TEE Cloud ](https://docs.phala.network/phala-cloud/references/tee-cloud-cli) for enhanced security and privacy. Once deployed, you will receive an data query URL that needs to be registered using the `add_query_node` function by LazAI admins.\
\
Use this starter kit to create and push your Docker image\
<https://github.com/0xLazAI/LazAI-DATA-Query-Server-Setup-Kit>

You can also use the existing data query nodes.

#### Step 2: Request Query via LazAI Client

```python
from alith.lazai import Client
import requests

client = Client()
node = "0x2591E4C0e6E771927A45eFAE8Cd5Bf20e585A57A" #change this address with one you registered with admin 

try:
    print("try to get user")
    user =  client.get_user(client.wallet.address)
    print(user)
except Exception as e:
    print("try to get user failed")
    print(e)
    print("try to add user failed")
    client.add_user(1000000)
    print("user added")


print("try to get query account")

url = client.get_query_node(node)[1]
print(url)
headers = client.get_request_headers(node)
print("request headers:", headers)
print(
    "request result:",
    requests.post(
        f"{url}/query/rag",
        headers=headers,
        json={
            "file_id": 10, #change with your file_id 
            "query": "summarise the best character?",
        },
    ).json(),
)
```

***

### Security & Privacy

* **Your data never leaves your control.** Data query is performed in a privacy-preserving environment, using cryptographic settlement and secure computation.
* **Settlement headers** ensure only authorized users and nodes can access your data for data query.
* **File ID** links your data query request to the specific data you contributed, maintaining a verifiable chain of custody.


# Overview

This guide will walk you through everything you need to get started with Alith. Whether you’re building intelligent agents, integrating tools, or experimenting with language models, Alith provides a seamless experience across multiple programming languages. Below, you’ll find installation instructions, quick start guides, and examples for Rust, Python, and Node.js.

### Install Dependency

{% tabs %}
{% tab title="Alith dependency" %}

```sh
npm install alith
# Or use pnpm
pnpm install alith
# Or use yarn
yarn install alith
```

{% endtab %}

{% tab title="json-schema dependency" %}

```sh
npm i --save-dev @types/json-schema
# Or use pnpm
pnpm install --save-dev @types/json-schema
# Or use yarn
yarn install --save-dev @types/json-schema
```

{% endtab %}
{% endtabs %}

### Write the Code

{% code overflow="wrap" %}

```javascript
import { Agent } from "alith";

const agent = new Agent({
  model: "gpt-4",
  preamble: "You are a comedian here to entertain the user using humour and jokes.",
});

console.log(await agent.prompt("Entertain me!"));
```

{% endcode %}

#### Model Provider Settings

To configure different AI model providers, here we use the OpenAI model as an example.

**Unix**

```sh
export OPENAI_API_KEY=<your API key>
```

**Windows**

```powershell
$env:OPENAI_API_KEY = "<your API key>"
```

### Run the Code

```sh
tsc index.ts && node index.js
```


# Build Your Twitter Agent

## Creating a Twitter Agent with Alith

In this tutorial, you will learn how to create a Node.js application that integrates X/Twitter with Alith’s Model Context Protocol (MCP) feature. This allows you to use LLM models and agents to fetch tweets from a specific user, post a new tweet, like a tweet, quote a tweet, etc.

*Note: Although we used Node.js in this tutorial, you can still use Alith Rust SDK and Python SDK to complete this Twitter agent.*

<a href="https://alith.vercel.app/docs" class="button primary">Get Started</a>

### Prerequisites

Before starting, ensure you have the following:

* **OpenAI API Key:** Sign up at OpenAI and get your API key or use your favorite LLM models.
* **Node.js 18+ environment and pnpm.**
* **A X/Twitter account.**

### Install Required Libraries

Initialize the project and install the necessary Node.js libraries using pnpm:

```bash
mkdir alith-twitter-example && cd alith-twitter-example && pnpm init
pnpm i alith
pnpm i --save-dev @types/json-schema
```

### Set Up Environment Variables

#### LLM API Key

Store your API keys and tokens as environment variables for security:

```bash
export OPENAI_API_KEY="your-openai-api-key"
```

#### Cookie Authentication

```bash
export AUTH_METHOD=cookies
export TWITTER_COOKIES=["auth_token=your_auth_token; Domain=.twitter.com", "ct0=your_ct0_value; Domain=.twitter.com"]
```

**To obtain cookies:**

1. Log in to Twitter in your browser.
2. Open Developer Tools (F12).
3. Go to the Application tab > Cookies.
4. Copy the values of auth\_token and ct0 cookies.

#### Username/Password Authentication

```bash
export AUTH_METHOD=credentials
export TWITTER_USERNAME=your_username
export TWITTER_PASSWORD=your_password
export TWITTER_EMAIL=your_email@example.com  # Optional
export TWITTER_2FA_SECRET=your_2fa_secret    # Optional, required if 2FA is enabled
```

#### API Authentication

```bash
export AUTH_METHOD=api
export TWITTER_API_KEY=your_api_key
export TWITTER_API_SECRET_KEY=your_api_secret_key
export TWITTER_ACCESS_TOKEN=your_access_token
export TWITTER_ACCESS_TOKEN_SECRET=your_access_token_secret
```

### Write the Typescript Code

Create a Typescript script (e.g., index.ts) and add the following code:

*Note: We need to install `tsc` firstly.*

```typescript
import { Agent } from "alith";
 
const agent = new Agent({
  name: "A twitter agent",
  model: "gpt-4",
  preamble: "You are a automatic twitter agent.",
  mcpConfigPath: "mcp_twitter.json",
});

console.log(await agent.prompt("Search Twitter for tweets about AI"));
console.log(await agent.prompt('Post a tweet saying "Hello from Alith Twitter Agent!"'));
console.log(await agent.prompt("Get the latest tweets from @OpenAI"));
console.log(await agent.prompt("Chat with Grok about quantum computing"));
```

### Write the MCP Config

Create a JSON file named `mcp_twitter.json` and add the following code:

```json
{
  "mcpServers": {
    "agent-twitter-client-mcp": {
      "command": "npx",
      "args": ["-y", "agent-twitter-client-mcp"],
      "env": {
        "AUTH_METHOD": "cookies",
        "TWITTER_COOKIES": "[\"auth_token=YOUR_AUTH_TOKEN; Domain=.twitter.com\", \"ct0=YOUR_CT0_VALUE; Domain=.twitter.com\", \"twid=u%3DYOUR_USER_ID; Domain=.twitter.com\"]"
      }
    }
  }
}
```

### Run the Application

Run your Typescript script to start and test the application:

```bash
npx tsc && node index.js
```


# Build Your On-Chain AI Agent

Complete Step-by-Step Tutorial: On-chain AI Agent

This comprehensive tutorial will guide you through building an AI Agent that can handle both general conversations and blockchain operations, specifically token balance checking on the LazAI testnet.

### Prerequisites

Before starting, ensure you have:

* **Node.js 18+** installed
* **npm or yarn** package manager
* **Basic knowledge** of React, TypeScript, and Next.js
* **OpenAI API key** (for AI conversations)
* **Code editor** (VS Code recommended)

### Project Setup

#### Step 1: Create Next.js Project

```bash
# Create a new Next.js project with TypeScript
npx create-next-app@latest ai-agent --typescript --tailwind --eslint --app --src-dir=false --import-alias="@/*"

# Navigate to the project directory
cd ai-agent
```

#### Step 2: Verify Project Structure

Your project should look like this:

```
ai-blockchain-chatbot/
├── app/
│   ├── globals.css
│   ├── layout.tsx
│   └── page.tsx
├── public/
├── next.config.ts
├── package.json
└── tsconfig.json
```

### Dependencies Installation

#### Step 3: Install Required Packages

```bash
# Install core dependencies
npm install ethers alith

# Install development dependencies
npm install --save-dev node-loader
```

**What each package does:**

* `ethers`: Ethereum library for blockchain interactions
* `alith`: AI SDK for OpenAI integration
* `node-loader`: Webpack loader for native modules

### Next.js Configuration

#### Step 4: Configure next.config.ts

Create or update `next.config.ts`:

```typescript
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  webpack: (config, { isServer }) => {
    if (isServer) {
      // On the server side, handle native modules
      config.externals = config.externals || [];
      config.externals.push({
        '@lazai-labs/alith-darwin-arm64': 'commonjs @lazai-labs/alith-darwin-arm64',
      });
    } else {
      // On the client side, don't bundle native modules
      config.resolve.fallback = {
        ...config.resolve.fallback,
        '@lazai-labs/alith-darwin-arm64': false,
        'alith': false,
      };
    }

    return config;
  },
  // Mark packages as external for server components
  serverExternalPackages: ['@lazai-labs/alith-darwin-arm64', 'alith'],
};

export default nextConfig;
```

**Why this configuration is needed:**

* Handles native modules that can't be bundled by webpack
* Prevents client-side bundling of server-only packages
* Ensures proper module resolution

### Token Balance API

#### Step 5: Create API Directory Structure

```bash
# Create the API directories
mkdir -p app/api/token-balance
mkdir -p app/api/chat
mkdir -p app/components
```

#### Step 6: Create Token Balance API

Create `app/api/token-balance/route.ts`:

```typescript
import { NextRequest, NextResponse } from 'next/server';
import { ethers } from 'ethers';

// ERC-20 Token ABI (minimal for balance checking)
const ERC20_ABI = [
  {
    "constant": true,
    "inputs": [{"name": "_owner", "type": "address"}],
    "name": "balanceOf",
    "outputs": [{"name": "balance", "type": "uint256"}],
    "type": "function"
  },
  {
    "constant": true,
    "inputs": [],
    "name": "decimals",
    "outputs": [{"name": "", "type": "uint8"}],
    "type": "function"
  },
  {
    "constant": true,
    "inputs": [],
    "name": "symbol",
    "outputs": [{"name": "", "type": "string"}],
    "type": "function"
  },
  {
    "constant": true,
    "inputs": [],
    "name": "name",
    "outputs": [{"name": "", "type": "string"}],
    "type": "function"
  }
];

// LazAI Testnet configuration
const LAZAI_RPC = 'https://testnet.lazai.network';
const LAZAI_CHAIN_ID = 133718;

export async function POST(request: NextRequest) {
  try {
    const { contractAddress, walletAddress } = await request.json();

    // Validate inputs
    if (!contractAddress || !walletAddress) {
      return NextResponse.json(
        { error: 'Contract address and wallet address are required' },
        { status: 400 }
      );
    }

    // Validate Ethereum addresses
    if (!ethers.isAddress(contractAddress)) {
      return NextResponse.json(
        { error: 'Invalid contract address format' },
        { status: 400 }
      );
    }

    if (!ethers.isAddress(walletAddress)) {
      return NextResponse.json(
        { error: 'Invalid wallet address format' },
        { status: 400 }
      );
    }

    // Connect to LazAI testnet
    const provider = new ethers.JsonRpcProvider(LAZAI_RPC);
    
    // Create contract instance
    const contract = new ethers.Contract(contractAddress, ERC20_ABI, provider);

    try {
      // Get token information with individual error handling
      let balance, decimals, symbol, name;
      
      try {
        balance = await contract.balanceOf(walletAddress);
      } catch (error) {
        return NextResponse.json(
          { error: 'Failed to get token balance. Contract might not be a valid ERC-20 token.' },
          { status: 400 }
        );
      }

      try {
        decimals = await contract.decimals();
      } catch (error) {
        // If decimals call fails, assume 18 decimals (most common)
        decimals = 18;
      }

      try {
        symbol = await contract.symbol();
      } catch (error) {
        symbol = 'UNKNOWN';
      }

      try {
        name = await contract.name();
      } catch (error) {
        name = 'Unknown Token';
      }

      // Format balance - convert BigInt to string first
      const formattedBalance = ethers.formatUnits(balance.toString(), decimals);

      // Get LAZAI balance for comparison
      const lazaiBalance = await provider.getBalance(walletAddress);
      const formattedLazaiBalance = ethers.formatEther(lazaiBalance.toString());

      return NextResponse.json({
        success: true,
        data: {
          tokenName: name,
          tokenSymbol: symbol,
          contractAddress: contractAddress,
          walletAddress: walletAddress,
          balance: formattedBalance,
          rawBalance: balance.toString(), // Convert BigInt to string
          decimals: Number(decimals), // Convert BigInt to number
          lazaiBalance: formattedLazaiBalance,
          network: {
            name: 'LazAI Testnet',
            chainId: LAZAI_CHAIN_ID,
            rpc: LAZAI_RPC,
            explorer: 'https://testnet-explorer.lazai.network'
          }
        }
      });

    } catch (contractError) {
      console.error('Contract interaction error:', contractError);
      return NextResponse.json(
        { error: 'Contract not found or not a valid ERC-20 token on LazAI testnet' },
        { status: 400 }
      );
    }

  } catch (error) {
    console.error('Error checking token balance:', error);
    
    // Handle specific errors
    if (error instanceof Error) {
      if (error.message.includes('execution reverted')) {
        return NextResponse.json(
          { error: 'Contract not found or not a valid ERC-20 token' },
          { status: 400 }
        );
      }
      if (error.message.includes('network') || error.message.includes('connection')) {
        return NextResponse.json(
          { error: 'Network connection failed. Please try again.' },
          { status: 500 }
        );
      }
    }

    return NextResponse.json(
      { error: 'Failed to check token balance' },
      { status: 500 }
    );
  }
}
```

**Key Features:**

* Validates Ethereum addresses
* Handles BigInt serialization
* Provides fallback values for missing token data
* Comprehensive error handling
* Returns both token and native currency balances

#### Step 7: Create Smart Chat API

Create `app/api/chat/route.ts`:

```typescript
import { NextRequest, NextResponse } from 'next/server';
import { Agent } from 'alith';

// Function to detect token balance requests
function isTokenBalanceRequest(message: string): { isRequest: boolean; contractAddress?: string; walletAddress?: string } {
  const lowerMessage = message.toLowerCase();
  
  // Check for common patterns
  const balancePatterns = [
    /check.*balance/i,
    /token.*balance/i,
    /balance.*check/i,
    /how much.*token/i,
    /token.*amount/i
  ];
  
  const hasBalanceIntent = balancePatterns.some(pattern => pattern.test(lowerMessage));
  
  if (!hasBalanceIntent) {
    return { isRequest: false };
  }
  
  // Extract Ethereum addresses (basic pattern)
  const addressPattern = /0x[a-fA-F0-9]{40}/g;
  const addresses = message.match(addressPattern);
  
  if (!addresses || addresses.length < 2) {
    return { isRequest: false };
  }
  
  // Assume first address is contract, second is wallet
  return {
    isRequest: true,
    contractAddress: addresses[0],
    walletAddress: addresses[1]
  };
}

export async function POST(request: NextRequest) {
  try {
    const { message } = await request.json();

    if (!message || typeof message !== 'string') {
      return NextResponse.json(
        { error: 'Message is required and must be a string' },
        { status: 400 }
      );
    }

    // Check if this is a token balance request
    const balanceRequest = isTokenBalanceRequest(message);
    
    if (balanceRequest.isRequest && balanceRequest.contractAddress && balanceRequest.walletAddress) {
      // Route to token balance API
      try {
        const balanceResponse = await fetch(`${request.nextUrl.origin}/api/token-balance`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            contractAddress: balanceRequest.contractAddress,
            walletAddress: balanceRequest.walletAddress
          }),
        });

        const balanceData = await balanceResponse.json();
        
        if (balanceData.success) {
          const formattedResponse = `🔍 **Token Balance Check Results**

**Token Information:**
• Name: ${balanceData.data.tokenName}
• Symbol: ${balanceData.data.tokenSymbol}
• Contract: \`${balanceData.data.contractAddress}\`

**Wallet Information:**
• Address: \`${balanceData.data.walletAddress}\`
• Token Balance: **${balanceData.data.balance} ${balanceData.data.tokenSymbol}**
• LAZAI Balance: **${balanceData.data.lazaiBalance} LAZAI**

**Network:** ${balanceData.data.network.name} (Chain ID: ${balanceData.data.network.chainId})

You can view this transaction on the [block explorer](${balanceData.data.network.explorer}/address/${balanceData.data.walletAddress}).`;
          
          return NextResponse.json({ response: formattedResponse });
        } else {
          let errorMessage = `❌ **Error checking token balance:** ${balanceData.error}`;
          
          // Provide helpful suggestions based on the error
          if (balanceData.error.includes('not a valid ERC-20 token')) {
            errorMessage += `\n\n💡 **Suggestions:**
• Make sure the contract address is a valid ERC-20 token on LazAI testnet
• Verify the contract exists and is deployed on the network
• Check if the contract implements the standard ERC-20 interface`;
          } else if (balanceData.error.includes('Invalid contract address')) {
            errorMessage += `\n\n💡 **Suggestion:** Please provide a valid Ethereum address starting with 0x followed by 40 hexadecimal characters.`;
          } else if (balanceData.error.includes('Invalid wallet address')) {
            errorMessage += `\n\n💡 **Suggestion:** Please provide a valid Ethereum wallet address starting with 0x followed by 40 hexadecimal characters.`;
          }
          
          return NextResponse.json({ response: errorMessage });
        }
      } catch (error) {
        console.error('Error calling token balance API:', error);
        return NextResponse.json({ 
          response: "❌ **Error:** Failed to check token balance. Please try again later.\n\n💡 **Possible causes:**\n• Network connection issues\n• Invalid contract or wallet addresses\n• Contract not deployed on LazAI testnet" 
        });
      }
    }

    // Check if API key is configured for AI responses
    if (!process.env.OPENAI_API_KEY) {
      return NextResponse.json(
        { error: 'OpenAI API key is not configured' },
        { status: 500 }
      );
    }

    // Initialize the Alith agent with enhanced preamble
    const agent = new Agent({
      model: "gpt-4",
      preamble: `Your name is Alith. You are a helpful AI assistant with blockchain capabilities. 

**Available Features:**
1. **Token Balance Checker**: Users can check ERC-20 token balances on the LazAI testnet by providing a contract address and wallet address. The format should include both addresses in the message.

**Network Information:**
- Network: LazAI Testnet
- Chain ID: 133718
- RPC: https://testnet.lazai.network 
- Explorer: https://testnet-explorer.lazai.network

**How to use token balance checker:**
Users can ask questions like:
- "Check token balance for contract 0x... and wallet 0x..."
- "What's the balance of token 0x... in wallet 0x..."
- "Check balance: contract 0x... wallet 0x..."

Provide clear, concise, and accurate responses. Be friendly and engaging in your conversations. If users ask about token balances, guide them to provide both contract and wallet addresses.`,
    });

    // Get response from the agent
    const response = await agent.prompt(message);

    return NextResponse.json({ response });
  } catch (error) {
    console.error('Error in chat API:', error);
    return NextResponse.json(
      { error: 'Failed to get response from AI' },
      { status: 500 }
    );
  }
}
```

**Key Features:**

* Smart message routing based on content analysis
* Pattern recognition for balance requests
* Automatic address extraction
* Enhanced AI prompts with blockchain context
* Comprehensive error handling

### Chat Interface Component

#### Step 8: Create Chat Interface

Create `app/components/ChatInterface.tsx`:

```typescript
'use client';

import { useState, useRef, useEffect } from 'react';

interface Message {
  id: string;
  content: string;
  role: 'user' | 'assistant';
  timestamp: Date;
}

// Simple markdown renderer for basic formatting
const renderMarkdown = (text: string) => {
  return text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code class="bg-gray-100 px-1 py-0.5 rounded text-sm font-mono">$1</code>')
    .replace(/\n/g, '<br>')
    .replace(/•/g, '•');
};

export default function ChatInterface() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputMessage, setInputMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Auto-scroll to bottom when new messages are added
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const handleSendMessage = async () => {
    if (!inputMessage.trim() || isLoading) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      content: inputMessage.trim(),
      role: 'user',
      timestamp: new Date(),
    };

    setMessages(prev => [...prev, userMessage]);
    setInputMessage('');
    setIsLoading(true);

    try {
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ message: inputMessage.trim() }),
      });

      if (!response.ok) {
        throw new Error('Failed to get response');
      }

      const data = await response.json();
      
      if (data.error) {
        throw new Error(data.error);
      }

      const assistantMessage: Message = {
        id: (Date.now() + 1).toString(),
        content: data.response,
        role: 'assistant',
        timestamp: new Date(),
      };

      setMessages(prev => [...prev, assistantMessage]);
    } catch (error) {
      console.error('Error getting response:', error);
      
      const errorMessage: Message = {
        id: (Date.now() + 1).toString(),
        content: 'Sorry, I encountered an error. Please try again.',
        role: 'assistant',
        timestamp: new Date(),
      };

      setMessages(prev => [...prev, errorMessage]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const formatTime = (date: Date) => {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };

  return (
    <div className="flex flex-col h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white border-b border-gray-200 px-6 py-4">
        <h1 className="text-2xl font-bold text-gray-900">Alith AI Assistant</h1>
        <p className="text-sm text-gray-600">Powered by Alith SDK & ChatGPT • Blockchain Capabilities</p>
      </div>

      {/* Messages Container */}
      <div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
        {messages.length === 0 && (
          <div className="text-center text-gray-500 mt-8">
            <div className="text-6xl mb-4">🤖</div>
            <h3 className="text-lg font-medium mb-2">Welcome to Alith AI!</h3>
            <p className="text-sm mb-4">I can help you with general questions and blockchain operations.</p>
            
            {/* Feature showcase */}
            <div className="bg-white rounded-lg p-4 max-w-md mx-auto border border-gray-200">
              <h4 className="font-medium text-gray-900 mb-2">Available Features:</h4>
              <ul className="text-sm text-gray-600 space-y-1">
                <li>• 💬 General AI conversations</li>
                <li>• 🔍 Token balance checking on LazAI testnet</li>
                <li>• 📊 Blockchain data queries</li>
              </ul>
              <div className="mt-3 p-2 bg-blue-50 rounded text-xs text-blue-700">
                <strong>Example:</strong> "Check token balance for contract 0x1234... and wallet 0x5678..."
              </div>
            </div>
          </div>
        )}

        {messages.map((message) => (
          <div
            key={message.id}
            className={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
          >
            <div
              className={`max-w-[70%] rounded-lg px-4 py-3 ${
                message.role === 'user'
                  ? 'bg-blue-600 text-white'
                  : 'bg-white text-gray-900 border border-gray-200'
              }`}
            >
              <div 
                className={`text-sm whitespace-pre-wrap ${
                  message.role === 'assistant' ? 'prose prose-sm max-w-none' : ''
                }`}
                dangerouslySetInnerHTML={{
                  __html: message.role === 'assistant' 
                    ? renderMarkdown(message.content)
                    : message.content
                }}
              />
              <div
                className={`text-xs mt-2 ${
                  message.role === 'user' ? 'text-blue-100' : 'text-gray-500'
                }`}
              >
                {formatTime(message.timestamp)}
              </div>
            </div>
          </div>
        ))}

        {isLoading && (
          <div className="flex justify-start">
            <div className="bg-white text-gray-900 border border-gray-200 rounded-lg px-4 py-3">
              <div className="flex items-center space-x-2">
                <div className="flex space-x-1">
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
                </div>
                <span className="text-sm text-gray-600">Alith is thinking...</span>
              </div>
            </div>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      {/* Input Container */}
      <div className="bg-white border-t border-gray-200 px-6 py-4">
        <div className="flex space-x-4">
          <div className="flex-1">
            <textarea
              value={inputMessage}
              onChange={(e) => setInputMessage(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="Ask me anything or check token balances..."
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
              rows={1}
              disabled={isLoading}
            />
          </div>
          <button
            onClick={handleSendMessage}
            disabled={!inputMessage.trim() || isLoading}
            className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <svg
              className="w-5 h-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
              />
            </svg>
          </button>
        </div>
        
        {/* Quick help */}
        <div className="mt-2 text-xs text-gray-500">
          💡 <strong>Tip:</strong> Include both contract and wallet addresses to check token balances on LazAI testnet
        </div>
      </div>
    </div>
  );
}
```

**Key Features:**

* Real-time message updates
* Markdown rendering for formatted responses
* Auto-scroll to latest messages
* Loading indicators
* Responsive design
* Feature showcase for new users

### Environment Setup

#### Step 9: Configure Environment Variables

Create a `.env.local` file in your project root:

```env
# OpenAI API Key for AI conversations
OPENAI_API_KEY=your_openai_api_key_here
```

#### Step 10: Get OpenAI API Key

1. Go to [OpenAI Platform](https://platform.openai.com/)
2. Sign up or log in to your account
3. Navigate to "API Keys" in the sidebar
4. Click "Create new secret key"
5. Copy the generated key
6. Paste it in your `.env.local` file

**Security Note:** Never commit your API key to version control!

### Testing

#### Step 11: Start Development Server

```bash
npm run dev
```

#### Step 12: Test General Chat

Try these general questions:

* "What is blockchain technology?"
* "How does cryptocurrency work?"
* "Tell me a joke"
* "What are the benefits of decentralized systems?"

#### Step 13: Test Token Balance Checking

Try these formats:

* "Check token balance for contract 0x1234567890123456789012345678901234567890 and wallet 0x0987654321098765432109876543210987654321"
* "What's the balance of token 0x... in wallet 0x..."
* "Check balance: contract 0x... wallet 0x..."

**Note:** You'll need valid contract and wallet addresses on the LazAI testnet for this to work.

<figure><img src="/files/j7Xg560c8h6YxHABO5Tz" alt=""><figcaption></figcaption></figure>

### Additional Resources

#### Documentation

* [Next.js Documentation](https://nextjs.org/docs)
* [Ethers.js Documentation](https://docs.ethers.org/)
* [Alith SDK Documentation](https://alith.lazai.network/docs/get-started)


# Roadmap

## 2025: Establishing the AI Data Foundation

In 2025, LazAI will focus on developing the foundational components of its ecosystem: launching an AI agent for data alignment, deploying a high-performance blockchain for AI execution, and implementing data-driven PoS + Quorum-Based BFT consensus. This year will be testnet-focused, allowing developers to experiment with AI data anchoring and verification mechanisms.

### Phase 1: AI Agent Alith (Q1-Q2 2025) – AI-Powered Data Coordination

LazAI will launch Alith, a simple, composable, high-performance, and Web3-friendly AI agent framework designed to facilitate decentralized AI data processing, governance, and alignment. Unlike traditional AI agents that run in silos, Alith will interact with LazAI on-chain and off-chain AI data sources, ensuring data provenance and verification.

* [x] **Multimodal Model and Data Interpretation:** Supports text-, image-, and voice-based data to enable seamless AI model interaction with decentralized sources.
* [x] **Deployment and Workflow:** SDKs for Rust, Python, and Node.js will enable custom AI data processing and application workflows.
* [x] **High Performance on-Chain Inference:** Leverages techniques including graph optimization, model compression, use of GPU coprocessors, and JIT/AOT compilation for high-performance inference.
* [x] **Data Management:** Alith will help users coordinate, verify, and build decentralized AI datasets for model training and inference based on LazAI.

**Successfully Delivered:** Establish AI-native data workflows, allowing developers to access verified, decentralized AI datasets for training and inference, and build high-performance AI Agent applications.

{% hint style="success" %}
For more info, visit Alith [website](https://lazai.network/alith) and [docs](https://alith.vercel.app/docs).&#x20;
{% endhint %}

### Phase 2: Testnet – AI Data Settlement & Blockchain Infrastructure (Q2-Q3 2025)

LazAI will launch its testnet, providing a blockchain environment optimized for AI data integrity, validation, and settlement. This testnet will serve as a sandbox for developers experimenting with AI data tokenization, provenance tracking, and alignment verification.

* [ ] **Data Anchoring Token (DAT):** A new asset standard that tokenizes AI datasets and training pipelines, ensuring verifiability.
* [ ] **AI Data Processing and Inference/Training Workflow:** Supports high-throughput, parallelized AI data transactions, reducing latency for model updates and training workflows.
* [ ] **LazAI Verified Computing Framework:** Ensuring the authenticity, integrity, and verifiability of AI data based on DAT protocol is critical to building a trustworthy AI ecosystem.&#x20;

**Expected Outcome:** Developers gain access to a secure, scalable blockchain infrastructure where AI data can be registered, exchanged, and verified with on-chain provenance guarantees.

{% hint style="success" %}
DAT is live on Pre-Testnet, visit [here](https://predat.lazai.network/).&#x20;
{% endhint %}

### Phase 3: Mainnet – AI Data-Driven PoS + Quorum-Based BFT Consensus (Q3-Q4 2025)

LazAI will officially launch its mainnet, introducing a hybrid consensus protocol tailored for AI data verification and governance.

* [ ] **Quorum-Based BFT Consensus:** AI data alignment and model verification will be validated through a decentralized quorum-based mechanism.
* [ ] **PoS Economic Model for AI Data Validation:** Validators will be required to stake tokens to secure AI data pipelines, ensuring accountability and economic incentives for honest AI verification.
* [ ] **Decentralized AI Data Arbitration:** iDAO-led quorums will resolve disputes over AI dataset ownership, alignment, and correctness.

Expected Outcome: A robust, AI-data-driven blockchain with verifiable training datasets, model alignment guarantees, and tamper-proof AI execution workflows.

## 2026: Scaling AI Data Integrity & Web3 Interoperability

With a strong blockchain foundation in place, LazAI will shift its focus toward ensuring AI data security, cross-chain AI dataset interoperability, and decentralized AI workflow automation.

### Phase 4: Mainnet Upgrade – The Fastest AI Data-Optimized Blockchain (Q1–Q2 2026)

LazAI will implement its first major mainnet upgrade, reinforcing its position as the fastest blockchain for AI data transactions and provenance tracking.

* [ ] **Real-Time AI Data Anchoring:** AI models and datasets will automatically anchor data hashes to ensure transparency and immutability.
* [ ] **Privacy-Preserving AI Data Processing:** Zero-Knowledge Proofs (ZKPs) will be used to verify AI data integrity without exposing sensitive datasets.
* [ ] **Federated AI Data Verification:** A multi-party AI dataset verification system will enable collaborative, decentralized training across multiple chains.

**Expected Outcome:** LazAI will emerge as the leading blockchain for AI data integrity, verification, and decentralized training workflows.

### Phase 5: Strengthening Arbitration & AI Data Security (Q2–Q3 2026)

To reinforce trust in AI data sources and computation, LazAI will implement enhanced dispute resolution and decentralized AI security guarantees.

* [ ] **Optimistic Proofs for AI Data Disputes:** Enables low-cost, fast arbitration over model ownership and dataset integrity.
* [ ] **ZK Proofs for AI Model Transparency:** Cryptographic proofs will ensure AI models are ethically trained and aligned with predefined standards.
* [ ] **LAV (Logical Assertion Verification) Integration:** AI training pipelines will be verified against predefined rules using ZK/OP proofs.
* [ ] **Decentralized AI Agent Coordination:** AI agents will be able to autonomously resolve AI data-related disputes through iDAO-governed mechanisms.

**Expected Outcome:** LazAI will set a new standard for AI data validation, ensuring models remain ethical, accountable, and bias-resistant.

### Phase 6: AI Data Interoperability & Web3 Infrastructure Integration (Q3–Q4 2026)

LazAI will expand beyond its native blockchain, integrating with decentralized AI data platforms, oracles, and federated learning networks.

* [ ] **Cross-Chain AI Dataset Provenance:** AI training datasets will be securely registered across multiple blockchains, enabling trust-minimized AI workflows.
* [ ] **Decentralized AI Compute Networks:** LazAI will interact with decentralized compute resources, ensuring scalable AI model training without centralized dependencies.
* [ ] **Web3 AI Data Bridges:** Establishing multi-chain AI data validation protocols, allowing models to be trained on one chain and verified on another.
* [ ] **Interoperable AI Data Staking & Lending:** Enabling decentralized AI dataset monetization through liquidity pools for AI training data.

**Expected Outcome:** LazAI will become the global hub for AI data exchange, enabling seamless AI asset movement across blockchain ecosystems.

## Long-Term Vision: The AI Data Infrastructure for Web3

LazAI is building the first AI-native blockchain ecosystem centered around AI data integrity, accessibility, and provenance tracking. Our roadmap ensures fair, scalable, and verifiable AI model governance.

🔹 **2025:** Building AI Data Infrastructure – Launching AI agents, enabling AI dataset tokenization, and establishing decentralized AI arbitration mechanisms.

🔹 **2026:** Scaling AI Data Governance – Enhancing AI dataset privacy, security, and interoperability.

🔹 **Beyond 2026:** Expanding AI data monetization, federated learning, and autonomous AI data governance.


# Glossary

<table data-header-hidden><thead><tr><th width="160.33984375"></th><th></th></tr></thead><tbody><tr><td><strong>Term</strong></td><td><strong>Definition</strong></td></tr><tr><td>LazAI</td><td>A decentralized AI infrastructure platform integrating verifiable AI data, models, and computation with blockchain, enabling a trustless, composable, and privacy-preserving AI economy.</td></tr><tr><td>iDAO</td><td>Individual-centric DAO: The native social structure of the AI economy. Ensure decentralized validation of data sources and AI workflows and enable LazAI flow to process the reward allocation</td></tr><tr><td>LazChain</td><td>The dedicated blockchain infrastructure of LazAI for managing AI assets, proofs, consensus, and rewards.</td></tr><tr><td>Alith</td><td>LazAI’s decentralized AI Agent Framework for building and deploying autonomous AI Agents.</td></tr><tr><td>DAT</td><td>Data Anchoring Token - A semi-fungible token standard that anchors datasets, models, and agents with verifiable provenance, access rights, and ownership.</td></tr><tr><td>DAT Marketplace</td><td>A decentralized trading and verification hub where AI assets (datasets, models, agents) are exchanged and validated.</td></tr><tr><td>POV Inlet (Point-of-View Inlet)</td><td>POV is a protocol and standard for data unification In LazAI. POV Inlet is a submission interface allowing individuals or iDAOs to inject human-annotated context or judgments into the AI validation pipeline.</td></tr><tr><td>Verified Computing</td><td>A modular system combining ZKPs, Optimistic Proofs, and TEE to ensure verifiable off-chain AI computation and inference.</td></tr><tr><td>ZK Proofs </td><td>Zero-Knowledge Proofs - Cryptographic proofs used to verify computation or data without revealing sensitive information.</td></tr><tr><td>Quorum</td><td>A decentralized validation group consisting of multiple iDAOs that reach consensus on dataset integrity, model validation, and proof verification.</td></tr><tr><td>Extension Layer</td><td>Allows LazAI to integrate external data sources, model providers, computing platforms, and oracle services.</td></tr><tr><td>Execution Layer</td><td>Supports high-throughput, low-latency AI inference and verifiable computation, including Parallel EVM Execution.</td></tr><tr><td>Settlement Layer</td><td>Handles the issuance, ownership, and lifecycle of AI assets, ensuring on-chain traceability and compliance.</td></tr><tr><td>Data Availability Layer</td><td>Ensures reliable access and verification for on-chain/off-chain datasets via IPFS, Arweave, Web2 APIs, etc.</td></tr><tr><td>DeFAI</td><td>Decentralized Financial AI - A LazAI-native DeFi module enabling staking, lending, bonding, and monetization of AI assets.</td></tr><tr><td>Optimistic Proofs (OP)</td><td>A lightweight validation mechanism assuming correctness by default, but allowing dispute via fraud proofs.</td></tr><tr><td>Fraud Proofs</td><td>A dispute mechanism where challengers submit evidence against invalid data or computation to trigger slashing or reward redistribution.</td></tr><tr><td>TEE</td><td>Trusted Execution Environment - Hardware-level secure enclave enabling verifiable and private AI execution.</td></tr><tr><td>AI Agent</td><td>A modular, autonomous agent powered by AI models, trained on verified datasets, and deployed via Alith.</td></tr></tbody></table>


# FAQs

<details>

<summary><strong>The model, store, and process of the data may directly affect its scalability and feasibility in certain applications. How does LazAI solve this?</strong> </summary>

In LazAI, we model data in POV format, which is not only a data format, but also a data specification and protocol. We will provide the Alith Agent framework to help users unify the formats and sizes of different data and convert them into POV format. For public data, it will be in a unified tensor form, stored on the chain, and limited to 32K; for private data, it will generate proof through the tool chain and store it on the chain. LazAI uses verify computing to make data available but invisible.

</details>

<details>

<summary><strong>If an individual user wants to join LazAI to monetize his data, what is the general process?</strong></summary>

You can learn more about this here: [E2E Process](https://app.gitbook.com/o/vTOScAJ64uHkBu7vWYU2/s/fKp8Fyd6WWX9RFVOt8ze/~/changes/2/lazai-workflow-and-runtime/e2e-process)

</details>

<details>

<summary><strong>Where is iDAO data stored? If it is personal off-chain private data, which oracle does LazAI use?</strong></summary>

LazAI mainly supports private data on-chain. In theory, it can support data of any size to calculate its credentials on-chain. For public data, it will be limited to 32K, which is similar to the storage requirements of the chain and the context window of general AI models.&#x20;

Through the Alith Agent toolkit, users can perform data preprocessing and proof calculation locally, and upload data to the LazAI network, making the data available but invisible.

</details>

<details>

<summary><strong>How is the LazAI cross-chain designed?</strong></summary>

LazAI's cross-chain functionality is divided into three scenarios:

* **Heterogeneous Chain Cross-Chain**\
  For public chains not built with the Metis SDK, cross-chain interactions with LazAI are completed using third-party bridges. If data-layer cross-chain operations are involved, they will still be facilitated through an Oracle.
* **Homogeneous Chain Cross-Chain**\
  For public chains also built using the Metis SDK, we plan to support a Native Shared Bridge in the future to enable fast sharing of assets and data. However, this may be scheduled for Q4 or even next year.
* **Third-Party Data Sources like IPFS & Arweave**\
  For other third-party data sources, we will currently maintain the same approach as with heterogeneous chain cross-chaining, i.e., using Oracles and third-party bridges. In the future, we will support native cross-chain methods.

</details>

<details>

<summary><strong>What kind of token is DAT? Is it ERC6551 or ERC721?</strong></summary>

ata Anchoring Token (DAT) is a semi-fungible token (SFT) standard designed for AI dataset anchoring, licensing, and AI model provenance tracking. This protocol introduces a multi-layered ownership model, ensuring composability, structured access control, and verifiable AI asset usage in a decentralized ecosystem.

You can find more information about DAT in the following section [here](https://app.gitbook.com/o/vTOScAJ64uHkBu7vWYU2/s/fKp8Fyd6WWX9RFVOt8ze/~/changes/2/core-data-stucture-of-dat).

<br>

</details>


# Data Protection

Privacy and data security are fundamental to LazAI’s decentralized AI ecosystem. As AI development increasingly relies on personal and sensitive data, ensuring privacy, confidentiality, and data integrity becomes critical. LazAI integrates advanced cryptographic techniques and trusted computing environments to protect data at every stage of its lifecycle; during storage, processing, and computation.

By combining Zero-Knowledge Proofs (ZKPs), Federated Learning, Differential Privacy, Homomorphic Encryption, and Trusted Execution Environments (TEEs), LazAI guarantees that AI models and data can be securely shared, verified, and utilized without compromising user privacy or data sovereignty.

#### Zero-Knowledge Proofs (ZKPs)

ZKPs enable LazAI to verify data and computation results without revealing the underlying data. They allow trustless verification of AI model inference and reasoning processes, ensuring that sensitive information remains confidential.

* Verifies off-chain AI computations on-chain without exposing raw data
* Ensures integrity and correctness of inference results
* Facilitates dispute resolution in data validation and governance
* Protects sensitive AI assets and computations in cross-organization collaborations

#### Federated Learning

Federated Learning allows multiple parties to train AI models collaboratively without sharing raw data. Each participant trains a local model on their private data and only shares model updates (gradients), preserving data privacy.

* Supports multi-party joint modeling across different iDAOs or Quorums
* Prevents centralized data aggregation and enhances user privacy
* Enables collaborative AI development for personalized and context-sensitive applications
* Reduces data exposure risks in decentralized AI workflows

#### Differential Privacy

Differential Privacy introduces mathematically controlled random noise into datasets or model training processes to prevent the reverse engineering of individual data points.

* Protects individual user privacy in data sharing and AI model training
* Ensures AI models generalize on population-level data without leaking sensitive personal information
* Complies with data protection standards and regulations across jurisdictions

#### Homomorphic Encryption

Homomorphic Encryption allows LazAI to perform computations directly on encrypted data without needing to decrypt it first. This maintains data privacy even during active processing.

* Enables secure AI computation on private or sensitive datasets
* Facilitates privacy-preserving inference services on LazChain and off-chain environments
* Prevents unauthorized data access and computation tampering during execution

#### Trusted Execution Environments (TEEs)

TEEs provide hardware-level isolated environments for secure computation, ensuring that data and code remain confidential even from the operators of the host system.

* Protects AI model training and inference processes in decentralized computing nodes
* Safeguards cryptographic keys and sensitive data during execution
* Provides hardware-enforced protection against malicious operators or external threats
* Supports verifiable AI computation results by integrating with ZKPs and LAV mechanisms


# Welcome to Lazpad

### Lazpad: More Than Just a Launchpad

**Lazpad** is the easy, ethical launchpad for on-chain AI agents, a platform to deploy, tokenize, and manage AI agents as real, tradable digital assets. As the application layer of the LazAI ecosystem, turning complex AI models into interoperable, composable, and tradable agent tokens. These agents are represented by Agent Tokens, which unlock opportunities for collaborative funding, open participation, and mutually aligned incentives among creators, investors, and the agents themselves.&#x20;

Lazpad is powered by LazAI's modular framework, with its initial launch on the Metis Andromeda chain. Future enhancements will include expansion to Hyperion and the integration of Data Anchoring Token (DAT) capabilities enabled by LazAI. Designed for efficiency, Lazpad simplifies the deployment and management of AI agents while upholding transparency, ethical standards, and user-focused governance.

**This means:**

* AI agents launched through Lazpad are backed by verifiable infrastructure (via LazAI’s Verified Computing Framework).
* Data provenance, agent behavior, and usage are all tracked transparently.
* Tokenization is not only technical, it’s aligned with contribution, ownership, and accountability.

**Lazpad supports every stage of the AI agent lifecycle:**

* Data ownership confirmation
* Privacy protection
* Data valuation & pricing
* On-chain incentive structuring
* Agent tokenization and monetization

It bridges raw AI potential with real-world, decentralized application deployment.

#### Aligning AI with Humanity

Inheriting the ethos of LazAI, Lazpad is designed to build a more aligned AI future:

* **Ethical AI onboarding**: No agent can launch without a clear model of data sourcing and usage.
* **Incentive alignment**: Through DATs (Data Anchoring Tokens), developers and data contributors are fairly rewarded.
* **Transparent governance**: Agents and their associated data can be governed through iDAOs, allowing contributors and users to co-own and co-govern their evolution.

Lazpad’s design ensures that agents are not just powerful, but also accountable, transparent, and human-aligned.

#### Tailored Solutions for Every Project

Lazpad recognizes that not every AI project fits the same mold. To support diverse builders, it offers:

* **Premium Launch Mode**: For high-quality, vetted projects with curated launch structures (e.g. hardcap/uncapped models).
* **Open Launchpad Mode**: For experimental AI agent projects with accessible bonding curve trading.

#### **Point-Based Incentives**

A built-in point system that rewards contributors (developers, data providers, users, etc.).

That includes:

* Rewards developers, traders, data contributors
* Tracks participation
* Distributes airdrops from Premium Launches

Whether you’re building an inference agent, a personal assistant, or a decentralized model, Lazpad adapts to your needs.


# Premium Launch

Lazpad introduces two distinct launch models to cater to different project needs:

The Premium Launch mode is tailored for high-quality projects that meet rigorous standards, including team credentials, technical expertise, and overall viability. Projects in this mode undergo thorough reviews before participating in token issuance. Premium Launch offers two funding models:

### **Hardcap Model**

* Fundraising for the agent token is capped at a fixed upper limit.
* Participation per address is also subject to a limit.
* Lazpad charges 1% fees in this model, allowing developers to maximize their fundraising potential.
* If the fundraising goal is not met, two scenarios may occur:
  1. **Proceeding with Token Trading**: The issuer may decide to proceed by injecting the tokens into Netswap for trading. In this case, participants will still receive tokens proportional to their investment, and the issuer will retain the unsold tokens after the fundraising period ends.
  2. **Termination of Fundraising and Trading**: The issuer may choose to terminate the fundraising and any subsequent trading. In this scenario, the platform will refund the full amount of each participant's investment.

### Un**capped Model**

* Fundraising for the agent token has no upper limit. Participants are free to invest any amount without restrictions, and the total contributions from all users may exceed the fundraising target.
* Lazpad charges fees based on the amount of funds raised beyond the initial target, ensuring scalability while incentivizing successful launches.
* In the event of over-subscription, Lazpad will deduct platform fees based on the excess funds raised. After fees are deducted, the remaining excess funds will be refunded to participants proportionally based on their contributions.

| **Over-Subscription Ratio** | **Participation Fee** |
| --------------------------- | --------------------- |
| > 0x & <= 1x                | 1.00%                 |
| > 1x & <= 1.5x              | 0.50%                 |
| > 1.5x & <= 2x              | 0.30%                 |
| > 2x & <= 2.5x              | 0.25%                 |
| > 2.5x & <= 5x              | 0.20%                 |
| > 5x & <= 10x               | 0.10%                 |
| > 10x                       | 0.05%                 |


# Open Launch

The Open Launch mode is designed to be inclusive, enabling all projects and developers to tokenize their AI agents without barriers. This mode democratizes access to Lazpad’s ecosystem, allowing participants to issue agent tokens freely and contribute to the decentralized AI landscape.

#### **Key Features**

* **0 Fees for Token Creation**\
  Anyone can create AI agent tokens on the platform without incurring any fees, ensuring accessibility for all projects regardless of size or resources.
* **Automatic Fund Injection into Netswap**\
  Once a project on the Open Launchpad completes its fundraising and the bonding curve phase, the funds raised will be automatically injected into Netswap.
* **Bonding Curve Trading**\
  During the bonding curve phase, users can freely trade tokens.\
  Lazpad charges a 1% fee on the total purchase or sale price for each trade, payable in Metis. This incentivizes a sustainable trading ecosystem while maintaining low transaction costs.
* **Graduation to Netswap**\
  When a token successfully graduates from the Lazpad platform to Netswap, a fixed fee of 1 Metis is charged.


# Exploring Zone

The Exploring Zone is the starting ground for AI Agents (DATs) before they step onto the main stage of their asset journey. Think of it as the AI wilderness; a space where raw, unminted, and untested agents roam free, waiting to be discovered.

Here, every **DAT** is pure potential. They haven’t been locked into a final form or economy yet. Instead, they are shaped by real user interactions. Players explore, test behaviors, complete missions, and earn points that influence the agent’s growth. Every choice a user makes, from feedback to mission results leaves a mark on the DAT’s profile and trajectory.

For creators, the Exploring Zone is like a live laboratory and community focus group rolled into one.&#x20;

Once the community’s interactions reveal an agent’s strengths, creators decide whether it graduates to an Open Launch (free for the world to adopt and evolve) or a Premium Launch (exclusive, collectible, and monetized).

The Exploring Zone isn’t just about building in public, it’s about proving through play. It’s where experimentation meets crowd validation, turning ideas into launch-ready AI Agents with a built-in fanbase.

<br>


# Point & Reward System

To incentivize and reward contributions from all participants in the Lazpad ecosystem, Lazpad introduces a Point System. This system is designed to encourage engagement, support development, and foster a thriving decentralized AI agent community. Points can be earned through various activities and can be redeemed for exclusive rewards, benefits, or platform privileges.

### Developers

Developers are at the core of Lazpad’s ecosystem, and the Point System rewards them for their efforts in creating and launching innovative AI agents. Developers can earn points in the following ways:

* **Launching AI Agent Tokens:** Developers who tokenize their AI agents on Lazpad will receive points as a reward for contributing to the ecosystem.
* **Successfully Completing the Bonding Curve:** Projects that complete the bonding curve fundraising phase will earn additional points, recognizing their success and community support.
* **Using Alith AI Agent Framework for Development:** Developers who utilize LazAI‘s Alith AI agent framework to develop their projects will earn points, encouraging the adoption of LazAI’s advanced AI tools.

#### D**eveloper Points & Reward System Breakdown**

<table><thead><tr><th width="511.4140625">Activity</th><th>Point</th></tr></thead><tbody><tr><td>Launch the AI agent token</td><td>+2000</td></tr><tr><td>Successfully completing the bonding curve</td><td>+5000</td></tr><tr><td>Using Alith AI Agent Framework for development</td><td>+3000</td></tr><tr><td>Participated in the Hyperion hackathon</td><td>+3000</td></tr><tr><td>Participated in LazAI pre-testnet launch</td><td></td></tr><tr><td>           - Generate the DAT</td><td>+1000</td></tr><tr><td>           - Developed the DApp</td><td>+5000</td></tr></tbody></table>

#### AI Users

AI users play a crucial role in driving activity and liquidity within the Lazpad ecosystem. They can earn points through the following activities:

* **Participating in Token Trading:** Users who actively trade AI agent tokens on Lazpad will earn points, incentivizing market participation and liquidity.
* **Inviting Friends to Join:** Users can earn points by inviting their friends to participate in Lazpad, helping to grow the community.
* **Sharing on Social Media:** Social media engagement, such as sharing Lazpad-related content or promoting AI agents, will be rewarded with points, amplifying Lazpad’s reach and visibility.
* **Interact with the AI bot:** Users can earn points by interacting with AI bot.&#x20;

#### User **Points & Reward System Breakdown**

Currently, users can earn points through the Exploring Zone campaign and Lazbubu activities.

**Ways to Earn Points:**

* **Joining the Whitelist:** Earn 500 points when you successfully join.
* **Inviting Friends during whitelist campaign:** Earn 200 points for each successful invite who completes whitelist tasks.
* **Taking Lazbubu on Adventures:** Sometimes, your Lazbubu will return from adventures with reward points! The rarer your Lazbubu, the higher the chance of receiving valuable points.
* **Maturing a Lazbubu:** Once your Lazbubu matures:
  * Receive a one-time points reward based on its rarity.
  * Earn more points for each future adventure.
* **Participating in Token Trading / Depositing:** Receive 1,000 points for depositing in a project.

### Reward

Every time your total Lazpad Points hit: 3,000 / 6,000 / 10,000 / 15,000 / 25,000, you unlock one Lazbubu Activation Code.

* Mint **1 Lazbubu blind box** per code.
* Works only for accounts that have never minted before.
* Keep it for yourself or share the magic with a friend.

{% hint style="success" %}
Points aren’t just for now, they’ll bring you even bigger rewards in the future. Start stacking early!
{% endhint %}


# Lazbubu Incubator

## Exploring Zone

Exploring Zone is a discovery space for AI Agents (DATs) that haven’t yet started their asset journey. It is where raw AI Agents enter the wild. Unminted. Untested. Full of potential. Users dive in, interact, complete missions, and earn points as they shape each DAT through real decisions. Creators watch it all unfold, collecting feedback and measuring what resonates. Then they choose which agents graduate into an Open or Premium Launch. Build in public and prove through play.

## Lazbubu Incubator

The Lazbubu Incubator is the first Data Anchoring Token(DAT) introduced in the Exploring Zone. Here, you can incubate your own Lazbubu and grow alongside it.

### Getting Started

After connecting your wallet, simply click Start to begin your journey with Lazbubu.<br>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdkFDxHY2NKrtak2Un_VcrwHnu-U4ANZwX43Vf8cz7z6B4oOXFhN2VRDYz0FVuKEINaTz3LajbyUW8vLGKuOKgaKdctcxekrDeNh04F5_O4CMoTCtHKwjohxIS1xtLjin_mPBCfBw?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

### How to Get a Lazbubu: Blind Box

If you participated in the Exploring Zone Whitelist Campaign, congratulations! You’ll receive a blind box.

#### Open Your Blind Box

Open your blind box to meet your Lazbubu!\
Each Lazbubu has a rarity level: Common,Advanced,Rare and Legendary. The rarer your Lazbubu, the greater the rewards it can bring — and the faster it will mature.<br>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXckt7KxTdSUs5-aTXvt6yiHGqjL2wJ1wJGXkwJppLZOEncPUthf5uN1918amQPvPHIHI3hWRBXDVOLuFUuuJqlViIvPI0fR9DnMDD9VY1SYi7i22xufb3Zg7Rd_quDAdYGBfHvx6A?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

Missed the whitelist? Don’t worry, you still have a chance to get a box!

#### Ways to Get a Blind Box:

* Find a redeem code shared by others who reached the milestone.
* Follow us on X ([Twitter](https://x.com/LazAINetwork)) or join our Telegram community, the codes are occasionally shared there.
* Earn points by exploring and completing tasks in the zone. Once you reach a milestone, you can exchange points for a redeem code.

⚠️ Each user can only claim one blind box, but you can collect more Lazbubus through transfers or trades.

#### How to Redeem Your Code

1. Click the "Redeem Code" button.
2. Enter your valid code.
3. If successful, the "Open Box" button will appear.
4. Click Open Box to mint your Lazbubu!

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXckc1cSUj_iVnqrAMlDeP3HQWYo9rGBNgF7S98BG-H4-_14cDt9lb625PN8NOCpWUv9mRT2Sx52tb_0NIoEZbUCWwOqtK4gV0kv092objlHbRCpFc4Ojnq43Ntsgr4-66nLCfdKfg?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

#### Claim Your Gift

If you're among the Top 10 winners in the whitelist campaign, you’ll find a gift Lazbubu waiting in your gift box. Click "Open gift" to unwrap your special Lazbubu!

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcOqW_zcf_2FDj-LL8Vr7vLJvKeIz7N1NhiZLMLjMq_coKyFgOANe8yqTDeBb0ApUbEYHadpHglI4cqkWvWXzcOgmK8q_g1NJaJY5GY00YSxuVjFx-SREjAX8ses5A7k-bPuWuYjQ?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

#### Mint Your Lazbubu as a DAT

Whether your Lazbubu comes from a blind box or a gift box, you can officially mint it as a DAT. This action puts your Lazbubu fully on LazAI testnet, where its entire life journey will be recorded.

**Steps:**

1. Give it a name: name your Lazbubu
2. Share your name with Lazbubu: What name would you like Lazbubu to call you?
3. Customize its appearance by clicking the "Dice" button until you find a look you love.
4. Complete the on-chain interaction to finish the minting process.
5. No gas? Claim free test tokens via the faucet.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXfYyS0JU1S9lF1o8tcqv-kDfgUb_pAyU-BXsChLKhUeUd1koQaG_zAWvmU3Rn5iCGPRXKbG6-qJQiH2WCsKfm0MorkYvqwjuU0CXnMVDbqJCAt8S_srhhAofhl9crJDHnyqazS-HQ?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

### My Lazbubu

Once Lazbubu has been minted, it will be displayed on ‘My Lazbubu’ page

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdhMA1T7daQ8OUBuipuwtd5f6SHoQkkFGS6sdCfOZ0KqzW_-QfGQUo2_UmpyswOaRAfug50C5YOLITALrO2LE6djQ8Q5pwvGJngaZgEgVTyLXga4GI7E_SmO5cB2bnrT5LPJ6Khyw?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

Click ‘More’ in the top right corner to view additional profile details. All your conversations are saved on-chain and remain private.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXf0_iGsygrW-F7uZkmf-wQSX7uMYivN33AJTzy6fUmZ7zrom0j3fBHpcp7vnl8vdX-mbmTn7w5YLNYL0kxRGryVCMZO7hxFdHnXTxuQnAdusckiAJc5j_fb1Ge4wxE035oJTVoCSg?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

### Grow Your Lazbubu

#### Welcome Gift

After minting, open your Welcome Gift to receive a free message quota.\
You’ll get 50 extra messages on your first day, don’t miss them!

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXeK4BftWcp0y9ER7wSR_CDz4jPz5lAUzzciPofGBxq_pjtqTPYSZQlgRJrPj53hrp1lYyoN7cbf6zSPDI55eAWC-TruCIh5oEuG-rqbFAWtbpJt0twKAsSXmOyvT7sfZkqL0rny0w?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

#### Message Quota

Chat with your Lazbubu to bond and help it grow.

* Your daily message quota resets every 24 hours — remember to claim it!

| Rarity    | Daily Messages |
| --------- | -------------- |
| Common    | 20             |
| Advanced  | 40             |
| Rare      | 70             |
| Legendary | 100            |

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXf3VTqAd8hRAb2YrYTvULZjEVO1SLOvrwLwLwJFa727Ak4r33PUtte_SFlHsNiVSxHWhq9zdZPOBSiPt1uEQYQLaglMgCguv2nHPZ5yM2NfIltOI8oGkGQen6l99pIbKvegpGubKA?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

#### Chat

* The deeper and more meaningful your conversation, the faster Lazbubu will grow.
* &#x20;Avoid repeating phrases - Lazbubu might stop growing if it senses you're not actually talking to him/her.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdx-TgpXVMtZ4kR8B1NAveBqkb16dNPaLciouo6fnY6dy53hZp_F3E3SXJgw75_3P4DaNJ4iRu7d18ANJGvE9Ns4fD2_nx_In9gLC5PYXXZMZOuvxkY5LBVHs7rjPVhxY-cXb7i?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

#### Send Lazbubu on Adventures

Click "Start Adventure" to begin.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXeHEaknXOkWDkBbD6_T_taRFuXpXpfl5KjWklkpxbFvcivVIu7Iijs6l8UdxQPXbxHZ12JnX78SzlmYW91CUbLjNovVihfIeHxTMbwrVm8tkMbF9oFtm7msk9WjnT8N_c8-zET4MQ?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

Choose any available location, complete the on-chain interaction, and your Lazbubu will set off on a journey.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXf486zenorXHOUx52RtqP9aCNMEeVeUX2gpBCG6NBJy43AUvQdklNyTMcE4b1MVMRL6-WFJsvtWfxe9zRI90QNj3O8US-EhuQhUG9cbOL2GJHWvGEtIozBgmw0WIkAPXBrxPGH3yg?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

When it returns, you'll receive :

* A journey story
* Sometimes A postcard souvenir
* And sometimes even reward points!

The rarer your Lazbubu, the higher the chance of receiving valuable rewards.

Each Lazbubu can go on up to 10 adventures per day — after that, it needs rest.

#### When Will Lazbubu Mature?

Click "When to Mature" to check if your Lazbubu is ready to grow up — or if it still needs more time. Lazbubu will let you know!

Don’t forget to click "Update DAT" to sync your Lazbubu’s latest status on-chain.\
If you skip this step, the growth progress won’t be recorded.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXc-RVV-RrDKHBeogca1cJqw9BYcLqMlLB7ZFvWD5lHDQgzVBp8g-O7GsQI0Y0w8WrIPgtbFQmrfKUoYAMd1K1Jz4TSmcjDn9qz7czIyVAtoBnCUUYTEozteQ2n5qu88m-hzK1x4GA?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

**Growth Status**

Your Lazbubu has just two stages:

* Growing
* Matured

But there's no rush, take your time to chat, explore, and enjoy every moment with your Lazbubu. It will mature naturally through bonding and adventures.

**What Happens After Maturity?**

Once your Lazbubu matures:

* You’ll receive a one-time points reward, based on its rarity.
* You’ll earn more points per adventure.
* You’ll have a higher chance of receiving postcards and bonus rewards.
* You’ll unlock the ability to transfer your Lazbubu to another wallet.

So keep growing together — your journey with Lazbubu is just beginning!

| Rarity    | Points |
| --------- | ------ |
| Common    | 2000   |
| Advanced  | 5000   |
| Rare      | 10000  |
| Legendary | 20000  |

### Transfer Your Lazbubu

Once your Lazbubu has matured, a "Transfer" button will appear. Please note that memories of Lazbubu will be kept.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcjl2GhEw6hqNVq91RLASBkNgm28ducxuruaBfYnOPe9OnKFe7af3w79FSLYi_FQhjvzvneVJFiFp24T1nSfjvImeOO3Ny5WdlXBo6fWeY_AWDTfCRCqeG7tjTo7mu7i4ZG8Qna?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

#### How to Transfer:

1. Click the "Transfer" button.
2. Enter the recipient’s EVM-compatible wallet address.
3. Pay the required gas fee to complete the transfer.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdo7bZL1F8zLRvuIFYVLTSOIVPrACABJZ3xWbCeuBfrkodRJPwAjmealG_RW4y4JAM_y3GNYSVtJ7WUrbzUHdmJ2IvxuI9QhEkTSqj7o-2ldib0vCEUn8058161u9bUWVAbLvlF?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

#### For the Receiver:

If you're receiving a transferred Lazbubu:

* You'll find it under your "My Lazbubu" page.
* You’ll have the chance to rename your new Lazbubu and introduce yourself — it’s a fresh new bond!

#### Reward Rules:

* The original owner keeps all rewards earned before the transfer, including the one-time maturity reward.
* The new owner earns all future rewards, such as adventure points and postcards, starting from the moment of transfer.

#### Exchange Activation Code

A Lazbubu Activation Code allows a user to mint one Lazbubu blind box.\
It can only be used by accounts that have never minted a Lazbubu before.

* Can be used by yourself or shared with others
* &#x20;Only valid for accounts with no prior Lazbubu mint history

#### Unlock Activation Codes: Milestone System

You’ll earn one activation code every time your total Lazpad Points reach any of these milestones:

3000 / 6000 / 10,000 / 15,000 / 25,000

As you reach each milestone, a new code will be unlocked.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXceYLcYDPW4SCZyCAO9tJWfwD0Nf1FXY3KDNv_nIWJOjJYELtAuiyoF3f0R2CcapLjJtykWX6MTZuOwxb8j5GvWfzCENKGgwRfyXgF0Me8hzYqWCwd2GSkrnBEGtW5kEBDjoz8HRA?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcj9kOyF9GPNtwuJVdnpGp0CU1P7BNokBdK_4Ojf5qO5mYcFMv1jJomS2UkenWDhBugEiJ2Jez_WWH0dFS3DTQxnN8NtcI-EaUnN1QMHkFlXBJvfKb8fuJSjQF4J2IOXcBXCHuT8Q?key=rgZeN71Fo6hb1Rtnlz3DcQ" alt=""><figcaption></figcaption></figure>

<br>


# About LazAI

### Aligning AI with Humanity

LazAI is a Web3-native AI network redefining data for the AI era - making it verifiable, ownable, and composable to ensure human-aligned AI evolution.

Unlike traditional AI systems that centralize data, computing, and alignment behind corporate walls, LazAI prioritizes data sovereignty, verifiable AI execution, and individual-powered governance through iDAO, DAT, and a verified computing framework integrated with Quorum-based Consensus.&#x20;

LazAI enables a scalable, incentive-aligned AI ecosystem where contributors are fairly rewarded, and AI outputs remain accountable.

### Key Pillars of LazAI as follows:&#x20;

#### 1.  **iDAOs** (Individual-centric DAOs) - **Governance for AI Data & Models**

iDAO, short for **Individual-centric** DAO , is the native social structure of the AI economy. A decentralized space where humans and AI agents co-create, co-govern, and co-monetize aligned intelligence.

* Enables Quorum-Based Consensus to verify dataset contributions, agent logic, and AI behavior.
* Allows transparent co-ownership and monetization of AI workflows.
* Powers the reward and dispute resolution flow within LazAI’s Verification Framework.

Redefining DAO from organization-centric to Individual-aligned intelligence networks.

#### 2. The **Verified Computing Framework** - Trust & Auditability

The **Verified Computing Framework** underpins LazAI’s commitment to transparent and secure AI execution. It ensures that every inference, training update, or agent behavior is cryptographically validated and tamper-resistant.

* **Modular System**: Combines ZKPs, Optimistic Proofs, and TEE for scalable off-chain verification scenarios.
* **Quorum-Based Consensus Integration**: Validates all major AI lifecycle checkpoints—from data submission to model deployment.
* **Hybrid Trust Layer**: Blends on-chain anchoring with off-chain compute to ensure decentralization without compromising performance.

#### 3. **Data Anchoriung Token (DAT) - The Tokenized AI Asset Framework**

The **Data Anchoring Token (DAT)** is a new **semi-fungible token (SFT)** standard **to assetize your AI data** specifically designed to tokenize AI datasets, models, and computation results with on-chain provenance, access control, and ownership rights.

* Anchors AI assets with immutable, structured metadata.
* Supports programmable licensing, access control, and permissioned model execution.
* Enables modular composition and version tracking for AI agents and datasets.

**POV (Point of View) Data Validation:** LazAI leverages on-chain community-driven perspectives to ensure data reliability, alignment, and contextual accuracy.

By enabling on-chain proof of AI data integrity, LazAI ensures that developers, researchers, and enterprises can build AI models with confidence, free from manipulated, biased, or unverifiable datasets.

### Moving Beyond Traditional AI Infrastructure

LazAI represents the next evolution of AI in the Web3 era - an ecosystem where AI datasets, models, and computations are governed by decentralized protocols, secured through cryptographic proofs, and monetized through trustless tokenized systems.

By combining AI, blockchain, and decentralized governance, LazAI is laying the foundation for a fair, transparent, and high-performance AI ecosystem that is scalable, inclusive, and resistant to centralized control.&#x20;

For detailed technical information, please refer to the [developer documentation](https://docs.lazai.network/developer-docs/data-anchoring-token-dat/dat-contract-overview) and [litepaper](https://lazainetwork.gitbook.io/whitepaper).


# Architecture Integration: LazAI

As part of the **Application Layer**, Lazpad seamlessly integrates with the LazAI’s other layers to create a holistic ecosystem that ensures AI agents are developed and tokenized with a focus on data sovereignty, privacy protection, value distribution, and asset monetization. By leveraging LazAI’s trusted extension and interaction layer, this integration guarantees that every stage of the AI agent lifecycle - from data ownership confirmation and privacy safeguards to data pricing, value allocation, and agent asset tokenization is transparently managed.&#x20;

To achieve this, the platform follows a modular architecture that ensures seamless interaction between AI models, datasets, developers, and blockchain infrastructure.

<figure><img src="/files/eO1nKZIUJziSmHYcfYJC" alt=""><figcaption></figcaption></figure>

**The LazAI Platform Architecture consists of the following layers:**

* **Application Layer:** By combining on-chain verification, decentralized computing, and tokenized AI asset management, the application layer establishes a robust Web3-native AI infrastructure
* **Trust and Execution Layer:** Powered by LazChain, this layer serves as the core infrastructure for AI asset issuance, circulation, and computation verification.
* **Extension Layer:** Facilitates external data integration, model provider participation, and advanced AI service expansion to enhance interoperability across Web3.

This comprehensive approach empowers developers and data contributors to retain control, fosters trust within the decentralized ecosystem, and unlocks the full potential of AI agents as tradable digital assets.

Lazpad is natively integrated with the **LazAI's agent framework - Alith**, meaning every launch on Lazpad benefits from the verifiable, privacy-preserving, and incentive-aligned infrastructure of LazAI.

### LazAI's Key Innovation Used by Lazpad:

**Alith SDK:**

* Developers use Alith to build verifiable agents
* Auto-generates proofs of execution for inference events

**iDAO - Individual-centric DAO Framework:**

* Creates governance wrappers for each agent or set of agents
* Contributors (data, compute, models) are issued stake tokens
* Enables long-term governance, slashing, and upgrades

**Data Anchoring Tokens (DAT):**

* Tokens that represent data sets, model weights, or inferences
* Issued at the time of contribution
* Provides monetization and composability

**Verified Computing (TEE-first, ZK-optional):**

* Every agent execution emits a signed proof
* Optionally re-validated on-chain or challenged using OP-style fraud proofs

#### The Result:

Lazpad doesn’t just launch AI, it launches agents with **proofs, ownership, and value alignment embedded.**


# First Integration: Metis Andromeda

### Metis: A Multi-Network Ecosystem Redefining Decentralized Infrastructure​

Metis is more than a Layer 2 - it is a multi-network ecosystem powered by the groundbreaking MetisSDK. Metis is building the future of decentralized infrastructure with a dual-network architecture: Andromeda for secure, general-purpose dApps and Hyperion for high-performance, AI-optimized execution. Both chains interoperate seamlessly, enabling builders to deploy scalable, efficient, and intelligent Web3 applications across sectors such as DeFi, gaming, DEPIN and AI.

**Lazpad is currently deployed on Metis Andromeda.**&#x20;

### What’s Andromeda?

Andromeda​​ serves as the foundational optimistic rollup network within the Metis ecosystem, delivering scalable decentralized infrastructure with Ethereum-level security and enhanced throughput. Optimized for DeFi, gaming, and general-purpose applications, it leverages a decentralized sequencer network and fraud-proof mechanisms to prioritize reliability and proven execution over extreme performance. Its battle-tested architecture supports a growing ecosystem of protocols requiring robust security models.

Andromeda will evolve alongside Hyperion, maintaining its core focus on secure general-purpose infrastructure. Key upgrades like on-chain data availability and fraud-proof refinements will advance its capabilities, with a roadmap targeting Stage 0 deployment soon and Stage 1 completion by year-end. As Metis’ cornerstone network, it remains the go-to solution for projects valuing decentralization (via full DSEQ nodes) and time-tested security frameworks.

In the near future,  Lazpad will also integrate to Metis Hyperion


# Upcoming Integration: Metis Hyperion

In the near future, Lazpad will integrate to Metis Hyperion

### What is Hyperion?

**Hyperion - The First Layer 2 Bringing On-Chain LLMs to Life**

Hyperion is a high-performance, AI-optimized Layer 2 solution designed to scale AI, DeFi, Depin and gaming applications. It enhances Metis' ecosystem by introducing parallel execution, AI-native infrastructure and decentralized sequencing, while maintaining Ethereum security and METIS as the gas token.

Hyperion, developed with the powerful MetisSDK and LazAI’s Alith AI framework, is the first Layer 2 Ethereum-compatible solution designed explicitly for on-chain AI execution, notably supporting Large Language Models (LLMs). It combines blockchain’s decentralized trust and transparency with AI's analytical and predictive powers, delivering an unparalleled user and developer experience.

This architecture optimizes the execution efficiency of AI processes within blockchain ecosystems, reducing computational overhead while maintaining network integrity. By embedding Alith’s modular framework for seamless AI/blockchain interoperability, Hyperion establishes a robust technical bridge between artificial intelligence and distributed ledger technologies.

This advancement fundamentally enhances decentralized application (dApp) capabilities, unlocking new possibilities for complex AI-driven functionalities in Web3 environments.

### Key Features of Hyperion (HYPE):

#### Parallelized Transactions for Hyper-Scalability

Hyperion’s Parallel Execution Engine, paired with an Optimistic Rollup model, processes multiple transactions simultaneously, delivering sub-second finality. Optimized fraud-proof mechanisms ensure security without sacrificing speed, making Hyperion perfect for real-time AI, gaming, and DeFi applications.

#### High Performance On-chain LLMS Inference

By leveraging Rust's performance advantages and quick model inference technologies, Alith ensures that AI tasks in MetisSDK are executed efficiently, even under high transaction volumes.

#### Revolutionizing Storage

MetisDB eliminates storage bottlenecks with memory-mapped Merkle Trees, multi-version concurrency control, and asynchronous I/O processing. This ensures lightning-fast data access and cost-efficient state management, critical for data-intensive AI applications.

#### AI-Optimized Powerhouse

Hyperion’s Metis Virtual Machine (MetisVM) is custom-built for on-chain AI inference and high-throughput dApps. With dynamic opcode optimization, speculative parallel execution, and state-aware caching, MetisVM slashes gas fees and boosts processing speeds, enabling developers to run machine learning models directly on-chain.

#### Seamless Ethereum and Cross-Chain Integration

Hyperion commits state changes to Ethereum for battle-tested security while enabling cross-chain liquidity through a shared bridge framework. Integration with off-chain compute networks allows AI developers to leverage distributed processing power, creating scalable, interoperable dApps.


# Problem Landscape

The year 2025 is poised to be a watershed moment, heralded as the ‘Year of the AI Agent,’ where the convergence of AI and Web3 is redefining the boundaries of technological innovation. At the core of this transformation stands Alith, a groundbreaking framework engineered to address fundamental AI challenges, establishing itself as an indispensable tool at this critical intersection of technologies.

Why are we confident in this vision? And how do we foresee the future within the AI + Web3 paradigm through the lens of the AI Agent Framework?

### The Problem Landscape

The rapid advancement of AI technologies has illuminated critical challenges within centralized AI ecosystems. Faced with both macro and micro challenges in the age of AI, we cannot afford to stand idly by.

#### Macro-Level Challenges in the AI Ecosystem

* **Data Sovereignty and Accessibility**: Centralized platforms often monopolize access to data and resources, creating barriers for small-to-medium developers and limiting innovation.
* **Privacy Concerns**: Users lack control over their data, leading to privacy breaches and unverified data usage.
* **Resource Inefficiency**: Current models struggle with high inference costs, low efficiency, and limitations in accessing non-public data.
* **Limited Decentralization**: Governance models skew toward centralized authorities, resulting in opaque decision-making and inequitable profit distribution.

#### Micro-Level Challenges: Usability of Agent Tools

* **Complexity**: Agent tools often demand technical expertise, limiting accessibility for non-developers. Customization options are cumbersome and not intuitive.
* **Performance Bottlenecks**: High computational costs and low responsiveness reduce the efficiency and scalability of current agent frameworks.
* **Fragmentation:** Isolated ecosystems make integration difficult, leading to disjointed workflows and inconsistent user experiences.
* **Lack of Web3 Integration:** Many frameworks fail to leverage blockchain’s transparency and interoperability, missing opportunities for innovation in decentralized AI applications.

These problems hinder innovation and limit the participation of developers and developers-to-be from diverse backgrounds in the development of AI technology. This highlights the belief that many ordinary individuals will transition into developers, joining the wave of AI and Web3 innovation.

To address these issues, we have launched LazAI — a decentralized AI platform dedicated to building an open, transparent, high-performance, secure, and inclusive AI ecosystem.

### What is LazAI and Alith

Alith is a decentralized AI agent framework tailored to harness the capabilities of the LazAI -a decentralized AI platform dedicated to building an open, transparent, high-performance, secure, and inclusive AI ecosystem. LazAI solves AI’s data alignment problem with novel technologies, from chaining Data Anchoring Tokens (DATs) to form a blockchain to self-contained iDAOs for entities, enabling composable open networks for AI and Web3 applications. On the LazAI platform, AI developers, data providers, and other stakeholders can collaborate through integrated development tools to jointly create high-quality AI assets. These assets can be used for further development or traded and shared within the platform. LazAI uses blockchain technology to ensure that all interactions are transparent and tamper-proof, with clear ownership and fair profit distribution for contributors.

<div align="center"><img src="https://alith.vercel.app/lazai.png" alt="LazAI Arch"></div>

Alith combines cutting-edge performance optimization with robust Web3 integration, addressing critical issues such as data sovereignty, efficient inference, and decentralized collaboration. By leveraging blockchain technology, Alith ensures transparent data governance and fair resource allocation, empowering developers and contributors within a decentralized AI ecosystem. Its cross-language SDKs for Python, Rust, and Node.js, alongside features like low-code orchestration and seamless deployment, make it both developer-friendly and highly scalable.

<div align="center"><img src="https://alith.vercel.app/alith.png" alt="Alith Arch"></div>


# Alith Solution

Alith is a decentralized AI agent framework tailored to harness the capabilities of the LazAI - a decentralized AI platform dedicated to building an open, transparent, high-performance, secure, and inclusive AI ecosystem.&#x20;

LazAI solves AI’s data alignment problem with novel technologies, from chaining Data Anchoring Tokens (DATs) to form a blockchain to self-contained iDAOs for entities, enabling composable open networks for AI and Web3 applications. On the LazAI platform, AI developers, data providers, and other stakeholders can collaborate through integrated development tools to jointly create high-quality AI assets.&#x20;

These assets can be used for further development or traded and shared within the platform. LazAI uses blockchain technology to ensure that all interactions are transparent and tamper-proof, with clear ownership and fair profit distribution for contributors.

<div align="center"><img src="https://alith.vercel.app/lazai.png" alt="LazAI Arch"></div>

Alith combines cutting-edge performance optimization with robust Web3 integration, addressing critical issues such as data sovereignty, efficient inference, and decentralized collaboration. By leveraging blockchain technology, Alith ensures transparent data governance and fair resource allocation, empowering developers and contributors within a decentralized AI ecosystem. Its cross-language SDKs for Python, Rust, and Node.js, alongside features like low-code orchestration and seamless deployment, make it both developer-friendly and highly scalable.

<div align="center"><img src="https://alith.vercel.app/alith.png" alt="Alith Architecture"></div>


# Why Alith

In LazAI, we believe that AI Agent is not a solution, but a goal we want to achieve and a problem that needs to be urgently solved. In the past 1 - 2 years, many AI Agent frameworks have emerged on the market, but they have not truly played the role of AI Agent. Restricted by the acquisition of internal data, the difficulty and cost of training and fine-tuning, as well as the high inference cost and low efficiency, AI Agents cannot be widely practiced, and the application scenarios are mostly concentrated in chatbots and so on. Therefore, we have launched the Alith AI Agent framework, which optimizes the model as much as possible on the basis of effectively utilizing data, improves the reasoning performance, and meets the needs of scene use.

### Key Features of Alith

**LazAI Gateway**

* Basic wallet management, transfer, sending transactions, and contract interactions.
* LazAI’s privacy data, iDAO, DAT, verified computing and other core features.

**High-Performance AI Training and Inference**

* Utilizes Rust’s performance strengths combined with graph optimization and model quantization.
* Supports JIT/AOT compilation across CPUs, GPUs, and TPUs for dynamic scenario adaptability.

**Developer Accessibility**

* Provides cross-language SDKs (Rust, Python, Node.js) and low-code orchestration tools.
* Enables one-click deployment and operational functionalities to reduce onboarding complexity.

**Web3 Ecosystem Integration**

* Designed to seamlessly integrate with decentralized applications and blockchain networks.
* Ensures interoperability with existing Web3 and AI frameworks.

**Scalability**

* Supports complex workflows, from basic internal prompts to advanced low-level API customizations.
* Enables customization of roles, goals, tools, operations, and behaviors while maintaining abstract clarity.

**Data Sovereignty and Privacy Reasoning**

* Leverages LazAI blockchain for data traceability and privacy protection.
* Actively removes biased or harmful data while incentivizing diverse contributions.

### Advantages of Alith

**Addressing Data Monopolization**

By utilizing blockchain-enabled governance, Alith resolves issues tied to data centralization. Its consensus-driven mechanisms empower contributors to retain ownership and control over their data, fostering a culture of equitable participation. The result is a vibrant ecosystem where data and resources flow seamlessly without traditional gatekeeping barriers.

**Superior Inference Performance**

Traditional AI systems face high costs and inefficiencies in inference tasks. Alith’s advanced optimizations—including Rust-based enhancements and quantization techniques—achieve low-latency, high-throughput performance, particularly in resource-constrained environments. This ensures robust AI applications across various devices and operational contexts.

**Enhanced Developer Usability**

Alith democratizes AI development through its SDKs and low-code capabilities. Developers, regardless of technical expertise, can rapidly create, deploy, and maintain AI agents. This accessibility reduces entry barriers, encouraging a broader spectrum of contributors to engage with AI technology.

**Decentralized Governance and Trust**

With its blockchain backbone, Alith establishes a decentralized governance framework that ensures fairness and transparency in asset distribution. This approach eliminates reliance on centralized authorities, fostering trust and collaboration among stakeholders.

**Ecosystem Affinity**

Alith’s compatibility with Web3 ecosystems enhances its versatility. It integrates seamlessly with existing decentralized infrastructures, enabling users to leverage blockchain’s security and transparency benefits. Additionally, it supports interoperability with frameworks like Langchain and Eliza, extending its utility across diverse applications.


# How to Choose?

In short, if you need collaboration among different development teams and multiple Agents, and your scenario has special requirements for data acquisition, model fine-tuning, and high-performance inference, Alith will be your top choice. At the same time, Alith also provides the capability support offered by most AI Agent frameworks. To better understand Alith’s unique value, let’s compare it to other AI agent frameworks:

#### Alith VS. Langchain

Langchain is a popular framework for building applications powered by Large Language Models (LLMs). It provides a wide range of tools and integrations for linking together different components of AI applications. However, Langchain focuses primarily on the orchestration of LLMs and lacks native support for Web3 and blockchain integration.

Alith is designed specifically for Web3, providing seamless integration with blockchain technology, decentralized data governance, and high-performance inference capabilities. If your project requires Web3 integration or decentralized AI workflows, Alith is a better choice. In addition, based on the Alith Python SDK and Node SDK, we can easily integrate Alith with Langchain and Langchainjs.

* **Focus**: Langchain excels in LLM orchestration but lacks blockchain integration.
* **Advantage**: Alith’s Web3 affinity and decentralized workflows make it superior for projects requiring robust blockchain interoperability.
* **Synergy**: Alith’s Python and Node.js SDKs enable seamless integration with Langchain, combining strengths for enhanced functionality.

#### Alith VS. Eliza

Eliza is a lightweight AI framework designed to be simple and easy to use for Web3. It is ideal for developers who need to quickly prototype AI applications without dealing with complex configurations and workflows. Compared to Eliza, Alith has a cross-language SDK, high-performance inference, and support for complex workflows, providing a more powerful solution for developers who need to build scalable, high-performance AI agents with Web3 capabilities. In addition, based on the Alith Node SDK, we can easily combine Alith and Eliza to benefit from the Eliza Web3 ecosystem while making up for the disadvantages of the Eliza framework.

* **Focus**: Eliza prioritizes simplicity and prototyping.
* **Advantage**: Alith’s cross-language SDKs, high-performance inference, and scalability offer a more comprehensive solution for complex workflows.
* **Synergy**: Alith’s integration capabilities allow users to complement Eliza’s lightweight framework with high-performance features.

#### Alith VS. Swarms

Swarms is another AI framework that emphasizes collaborative multi-agent systems. It allows multiple AI agents to work together to solve complex tasks. While Swarms excels in multi-agent collaboration, it does not provide the same level of Web3 integration or high-performance inference optimization as Alith, nor does it provide multi-language SDK support. Alith’s focus on Web3-friendly features, combined with its Rust-based performance optimizations, makes it a more suitable choice for developers looking to build decentralized, high-performance AI agents.

* **Focus**: Swarms emphasizes collaborative multi-agent systems.
* **Advantage**: Alith outperforms Swarms with its Web3 integration, high-performance inference, and cross-language SDK support.

#### Alith VS. Rig

Rig is also an AI Agent framework written in Rust. Compared to Rig, Alith provides developers with easier-to-use Python and Node SDKs, and has made more inference optimizations for different devices such as CPU, GPU, etc., which is more suitable for developers who need to combine real-time data processing with AI and blockchain technologies.

* **Focus**: Rig is another Rust-based framework.
* **Advantage**: Alith’s ease of use, thanks to Python and Node.js SDKs, along with device-specific inference optimizations, makes it more developer-friendly.

### Conclusion

The Alith AI Agent framework together with LazAI ecosystem exemplifies a forward-thinking approach to AI development. Its decentralized, high-performance, and developer-friendly design addresses long-standing challenges in traditional AI ecosystems. By prioritizing inclusivity, privacy, and interoperability, Alith stands poised to redefine how AI agents are built, deployed, and governed.


# Building on LazAI

Quick start guide to start building on LazAI

LazAI provides a robust environment for deploying and testing smart contracts. This guide will help you choose the right development framework and get started with your first smart contract deployment.

### Network Information

**Testnet**

| **Chain ID**        | 133718                                                |
| ------------------- | ----------------------------------------------------- |
| **Currency Symbol** | LAZAI                                                 |
| **RPC**             | <https://testnet.lazai.network>                       |
| **Block Explorer**  | <https://explorer.testnet.lazai.network>              |
| **Faucet**          | [LazAI Testnet Faucet](https://faucet.lazai.network/) |

**Mainnet**

| **Chain ID**        | 52924                                    |
| ------------------- | ---------------------------------------- |
| **Currency Symbol** | METIS                                    |
| **RPC**             | <https://mainnet.lazai.network>          |
| **Block Explorer**  | <https://explorer.mainnet.lazai.network> |


# Deploy with Hardhat

This guide will walk you through deploying a counter contract using Hardhat, a popular JavaScript-based development environment for Ethereum.

### 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)
* 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
```

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

{% code overflow="wrap" %}

```javascript
const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); module.exports = buildModule("CounterModule", (m) => { 
const counter = m.contract("Counter"); 
return { counter };
});
```

{% endcode %}

### **7. Configure Network Settings**

Create a `.env` file in your project root:

```
PRIVATE_KEY=your_private_key_here
```

Edit `hardhat.config.js`:

{% code overflow="wrap" %}

```javascript
require("@nomicfoundation/hardhat-toolbox");
require("dotenv").config(); 
module.exports = {  
solidity: "0.8.28",  
networks: {    
hardhat: {      
chainId: 31337,    
},    
lazai: {      
url: "https://testnet.lazai.network",      
chainId: 133718,      
accounts: [process.env.PRIVATE_KEY],    
},  
},
};
```

{% endcode %}

### &#x38;**. 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
```

### D**eploy to LazAI 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 LazAI:**

```
npx hardhat ignition deploy ignition/modules/Counter.js --network lazai
```

**Test Setup**

Create `test/Counter.js`:

{% code overflow="wrap" %}

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

{% endcode %}

**Running Tests**

```sh
npx hardhat test
```


# Deploy with 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)
* MetaMask wallet for deploying to testnets
* &#x20;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 Countercd 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: 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;    
}
}
```

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 the LazAI testnet, you’ll need:

* An RPC URL
* A private key with testnet LAZAI

Example deployment command for LazAI testnet:

```bash
forge create --rpc-url https://testnet.lazai.network \  --private-key <YOUR_PRIVATE_KEY> \  src/Counter.sol:Counter \  --broadcast
```

Replace `<YOUR_PRIVATE_KEY>` 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 LazAI testnet:

```bash
cast call <CONTRACT_ADDRESS> "number()(uint256)" --rpc-url https://lazai-testnet.metisdevops.link

```


# Deploy with Remix

Deploy Smart Contract on LazAI Chain using Remix

### **1. Prerequisites**

Before you begin, ensure you have:

* A web browser (Chrome, Firefox, or Edge recommended)
* MetaMask wallet extension installed
* LazAI testnet tokens (get from faucet)

### **2. Setup MetaMask for LazAI Testnet**

#### **Add LazAI Network to MetaMask**

1. Open MetaMask extension
2. Click on the network dropdown (usually shows "Ethereum Mainnet")
3. Click "Add Network"&#x20;
4. Enter the following details:

{% content-ref url="/pages/Ot9WMpIPhxBampdkrneM" %}
[QUICKSTART](/quick-start-docs)
{% endcontent-ref %}

### Contract Addresses

1. Click "Save" to add the network
2. Switch to LazAI Testnet in MetaMask

#### **Get Testnet Tokens**

Visit the LazAI faucet to get Testnet Tokens for deployment and transaction fees.

### **3. Access Remix IDE**

1. Open your web browser
2. Go to <https://remix.ethereum.org>
3. Remix IDE will load automatically - no installation required

### **4. Create Your Smart Contract**

#### **Create a New File**

1. In the File Explorer (left panel), click the "+" icon next to "contracts"
2. Name your file `Counter.sol`
3. Add the following code:

```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 Your Contract**

#### **Select Compiler Version**

1. Click on the "Solidity Compiler" tab (second icon in left panel)
2. Select compiler version `0.8.0` or higher
3. Ensure "Auto compile" is checked (optional but recommended)

#### **Compile**

1. Click "Compile Counter.sol" button
2. Check for any compilation errors in the console
3. Green checkmark indicates successful compilation

### **6. Deploy Your Contract**

#### **Setup Deployment Environment**

1. Click on "Deploy & Run Transactions" tab (third icon in left panel)
2. In the "Environment" dropdown, select "Injected Provider - MetaMask"
3. MetaMask will prompt you to connect - click "Connect"
4. Ensure you're connected to LazAI Testnet in MetaMask

#### **Deploy Contract**

1. Under "Contract" dropdown, select "Counter"
2. Click "Deploy" button
3. MetaMask will open asking you to confirm the transaction
4. Review gas fees and click "Confirm"
5. Wait for transaction confirmation


# Litepaper

## 1. Introduction

### Why?

The rapid advancement of artificial intelligence (AI) has positioned it as a transformative force across industries, revolutionizing decision-making, automation, and knowledge creation. However, the existing AI landscape remains deeply centralized, dominated by a few monopolistic entities that control data, computing power, and model access. Only a handful of super companies have mastered large-scale model training and inference technologies.

Many challenges faced by large models, including hallucinations, stem from data scarcity. The supply of low-cost, publicly available internet data is nearing exhaustion, driving up the cost of data acquisition. Further challenges include the limited availability of personal and high-quality industry data, the difficulty of leveraging such data at scale while preserving privacy, the complexity of assessing data quality and effectiveness, and the lack of mechanisms for individuals and enterprises to receive fair compensation for their data. Going forward, the success of AI applications will largely hinge on how effectively data is generated and utilized.

In summary, LazAI seeks to address the following key challenges:

1. Data Sharing for AI utilization is Challenging:  In the AI domain, data is a foundational asset; however, the sharing of personal and industry-specific data remains significantly constrained due to strong privacy and security concerns. Both individuals and organizations are often reluctant to share data for fear of misuse, unauthorized access, or potential fraud. Moreover, the absence of standardized protocols and robust AI infrastructure further hampers the efficient sharing and utilization of data within AI workflows, even when stakeholders are willing to collaborate.
2. Data Quality and Evaluation Are Challenging: The quality of publicly available data is highly inconsistent, and a large proportion of high-quality data is proprietary or protected by copyright, limiting access for developers aiming to train competitive AI models. Establishing a unified framework to evaluate data effectiveness across diverse scenarios and perspectives is inherently difficult. Furthermore, there is a lack of viable mechanisms to support personalized, utility-based data evaluation, thereby restricting data optimization and impeding the overall progress of AI systems.
3. Revenue Generation and Distribution is Difficult: Throughout the lifecycle of AI model development and deployment, data contributors and model developers struggle to obtain fair compensation due to insufficient transparency and lack of verifiability. Centralized AI platforms often function as opaque systems, making it difficult to trace how data is utilized and how its value is realized. Consequently, data owners lack the ability to assess their data’s contribution to model outcomes or to claim appropriate economic rewards.

Therefore, we aim to build a world where everyone has the opportunity to align AI with their own data, build personalized AI models at minimal cost, and share in the value generated by their data and models through alignment. To achieve this, Lazai is committed to delivering decentralized AI blockchain infrastructure, AI asset protocols, and workflow toolkits. By leveraging decentralized, user-owned data sources, Lazai empowers developers to build value-aligned AI agents.

### How?

In the era of artificial intelligence, data is the new oil—but its flow remains obstructed. Privacy concerns, fragmented infrastructure, and opaque value attribution mechanisms have long discouraged individuals and enterprises from contributing their data to AI systems. LazAI reimagines this paradigm with a simple yet transformative proposition: data should be shareable without compromise, transparently evaluated, and fairly rewarded.

At the core of LazAI is a fully on-chain, privacy-preserving AI runtime and governance framework. This infrastructure transforms the raw data contributed by each iDAO into verifiable, ownable, and rewardable digital assets. Whether it is personal insights or proprietary enterprise datasets, contributors can share their data with confidence, safeguarded by advanced cryptographic technologies such as Trusted Execution Environments (TEEs) and Zero-Knowledge Proofs (ZKPs). The contributed data is then validated through verified computing and finalized via QBFT consensus, achieving a consistent and trusted state on the LazAI chain. Every phase, from data contribution and model interaction to final settlement, is executed and governed transparently on-chain, eliminating black-box ambiguity and reestablishing trust in collaborative, decentralized AI.

But LazAI goes beyond enabling secure data sharing, it redefines how the value of data is understood and realized. In today’s landscape, inconsistent data quality and the absence of robust evaluation mechanisms make it nearly impossible to assess the true utility of a dataset in AI training. LazAI addresses this challenge by seamlessly integrating data alignment, governance, and AI model training/inference within a unified, verifiable pipeline. Upon data contribution to the LazAI chain, users receive a DAT token corresponding to the model that encodes ownership, traceability, and value attribution. These tokens empower contributors to track exactly how their data and models are used and to visualize impact through on-chain runtime metrics defined in DAT. This supports both standardized benchmarking and personalized, utility-based insights, enabling more strategic contributions and higher-performance AI systems.

Just as importantly, LazAI ensures that value never disappears into the system. As models consume data and generate outputs, contributors are rewarded in real time, with all revenue flows deterministically and transparently distributed on-chain, tied directly to verified usage. This closed-loop economic model defined within LazAI eliminates the need for intermediaries and dismantles the opacity of centralized platforms. Data contributors and model developers alike receive fair, auditable compensation, grounded in verifiable activity, not speculative markets. Through iDAO governance and establishing decentralized autonomous organizations (iDAOs) for domain-specific data curation, each iDAO enforces community-driven rules for data quality, access, and usage, fostering trust among participants.

By aligning privacy, utility, and economic rewards into a single interoperable framework, LazAI does more than solve the data challenges of AI, it unlocks a new paradigm. One where anyone can contribute, monitor, and benefit from the value they help create. One where AI innovation is no longer the privilege of the few with the most data, but the shared opportunity of a truly decentralized future.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdH8YVXoSHz-CqX9tbAsWEC3G6EYsd_CdNN4viyirPIUOWMe6V2rsumgpGq2kQm0n_83VPtqe4iJVHBKKwP1aAgc9alYf-sicSglButWg9QwTxx6CLCzlM2o-6Q_KEE57SNje28hw?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt="" width="375"><figcaption></figcaption></figure>

LazAI envisions a future where the three foundational pillars of artificial intelligence, data, models, and compute power, are seamlessly and trustfully integrated on-chain through open and unified protocols. This architecture enables a transparent, decentralized, and composable AI ecosystem, built not on blind trust, but on provable integrity and incentive alignment.

### How LazAI Differs from Existing Solutions?

The challenges of centralized AI and inefficient data ecosystems are not new, but existing solutions have failed to address them holistically. Here’s how LazAI breaks the mold: &#x20;

**vs. Centralized AI Platforms (e.g., OpenAI, Google DeepMind)** &#x20;

* **Data Ownership:** Centralized platforms treat user data as raw material to train proprietary models, retaining full control and extracting most of the value. In LazAI, data contributors retain ownership via DATs, with explicit rights to govern usage and claim rewards. &#x20;
* **Access Barriers:** Large models are locked behind APIs with restrictive pricing (e.g., pay-per-query) and usage limits. LazAI’s composable AI economy lets developers build on shared models/datasets at fractional costs, with transparent fee structures.
* **Governance:** A small team of engineers decides model updates and content policies. LazAI’s iDAOs and Quorum-based governance ensure decisions align with community needs, not corporate priorities. &#x20;

**vs. Web2 Data Marketplaces (e.g., AWS Data Exchange, Kaggle)** &#x20;

* **Privacy:** These platforms require raw data to be shared or sold, exposing sensitive information (e.g., healthcare records, enterprise IP) to breaches or misuse. LazAI uses TEEs and ZKPs to enable data utilization \*without\* exposing raw data.
* **Value Capture:** Middlemen take 30-50% of transaction fees, and contributors have no claim to long-term value (e.g., if a dataset improves a model over time). LazAI’s DATs embed perpetual revenue shares, ensuring contributors benefit as their data creates value.&#x20;
* **Quality Control:** Data is often mislabeled or outdated, with no accountability. LazAI’s Quorum validation and fraud proofs ensure data integrity, with slashing mechanisms for bad actors. &#x20;

**vs. Generic Blockchain Projects (e.g., AI-focused chains without iDAO/DAT)** &#x20;

* **AI-Native Design:** Most blockchains treat AI as an afterthought, lacking infrastructure for model training, inference, or data alignment. LazAI’s verified computing framework (TEE+ZKPs) and DAT standard are purpose-built for AI workflows.
* **Incentive Alignment:** Tokens in generic projects often rely on speculation rather than utility. LazAI’s LAZ and DAT tokens are tied to tangible actions (data contribution, validation, model usage), creating a self-sustaining economy. &#x20;

## 2. LazAI: Building the Next-Generation AI Ecosystem

The future of AI requires an ecosystem that is open, composable, and trust-driven. However, today’s AI landscape is plagued by centralized control, data monopolization, and opaque decision-making, limiting the participation of independent developers and restricting access to critical AI resources.

LazAI pioneers a decentralized AI network that challenges the status quo by integrating blockchain technology, verifiable AI computing, and tokenized AI assets to create a transparent, scalable, and incentive-driven ecosystem. This approach not only democratizes AI access but also establishes a self-sustaining AI economy, where data and model developers, and infrastructure contributors are fairly rewarded for their participation.

LazAI provides blockchain infrastructure, protocols, and workflows based on iDAO's decentralized data sources to help developers build value-consistent AI agents. It also addresses the challenges of data sharing, quality assessment, and fair revenue distribution by integrating privacy protection technologies, verifiable computing, and other technologies.

1. **Overcoming Data Sharing Challenges -** To address the barriers of privacy concerns and fragmented data ecosystems, LazAI establishes a decentralized, encrypted network for secure data sharing. By integrating TEEs and ZKPs, the platform enables contributors to share encrypted data snippets without exposing raw information. Smart contracts govern all interactions on the LazAI chain, ensuring that data usage adheres to predefined privacy policies and access controls set by iDAOs. These iDAOs act as collaborative hubs for industry-specific data curation, fostering trust through transparent governance while preventing unauthorized access or misuse. The result is a permissioned yet open ecosystem where sensitive data (e.g., from personal health records to proprietary industrial datasets) can be safely utilized for AI training, inference and evaluation, unlocking value without compromising ownership.
2. **Solving Data Quality and Evaluation Challenges -** LazAI tackles the inconsistency of public data and the lack of unified evaluation frameworks through its DAT protocol. When data is contributed to the chain, it undergoes rigorous validation via TEEs and QBFT consensus, after which a DAT token is minted to represent its ownership and quality. Each token embeds metadata, usage history, and dynamic performance metrics such as how a dataset is used to improve model accuracy in natural language processing tasks. By transforming abstract data quality into quantifiable, tradable assets, LazAI creates a marketplace where high-value datasets command premium access and rewards, driving continuous optimization of AI models.
3. **Enabling Fair Revenue Generation and Distribution -** LazAI disrupts the centralized control of AI revenue by introducing a decentralized, real-time reward mechanism. Smart contracts automatically track data usage across model training, inference, and evaluation, distributing proceeds directly to contributors based on verifiable metrics such as the proportion of their data in a model’s training set or its contribution to inference outcomes. All transactions are recorded on-chain, providing immutable proof of data lineage and value attribution, while cross-chain interoperability enables seamless conversion of rewards into mainstream cryptocurrencies. This closed-loop economy eliminates intermediaries, ensures fair compensation for data contributors and model developers alike, and aligns incentives with verifiable impact, not speculative market forces.

Specifically, LazAI focuses on three fundamental pillars that drive the development of an autonomous, scalable, and composable AI ecosystem:

1. **Trustless Privacy Data and Model Provenance –** Establishing verifiable data integrity and seamless toolchain interoperability to break data silos and enable secure AI workflows.
2. **Decentralized AI Execution and Incentive Framework –** Enhancing AI efficiency by reducing computational costs, optimizing AI liquidity, and supporting scalable on-chain inference models. Through unified on-chain decentralized AI protocol and process  (such as DAT protocol, on-chain model data training and inference metrics) to ensure fairness and openness.
3. **Composability-Driven AI Economy –** Creating a modular AI asset framework where datasets, models, and AI applications are tokenized, tradable, and seamlessly composable.

### 2.1 Trustless Privacy Data and Model Provenance

AI is only as good as the data it learns from. However, centralized AI platforms often suffer from closed data silos, unverifiable data origins, and fragmented toolchains, making it difficult for developers to build high-quality, explainable AI models.

#### LazAI’s Solution: Verifiable AI Data & Composable Toolchains

LazAI introduces a trustless AI validation framework that ensures every dataset, model, and AI computation is verifiable, auditable, and immutable:

1. **iDAO-Powered AI Governance:** AI datasets and models are governed by Quorum-Based Consensus, ensuring decentralized validation of data sources and AI workflows.
2. **Data Anchoring Token (DAT):** AI assets are tokenized and recorded on-chain, allowing transparent ownership, verifiable provenance, and permission-based access control.
3. **POV (Point of View) Data Validation:** LazAI leverages on-chain community-driven perspectives to ensure data reliability, alignment, and contextual accuracy.

By enabling on-chain proof of AI data integrity, LazAI ensures that developers, researchers, and enterprises can build AI models with confidence, free from manipulated, biased, or unverifiable datasets.

### 2.2 Decentralized AI Execution and Incentive Framework

Traditional AI models require extensive computational resources, making high-performance AI development expensive, inefficient, and limited to a few dominant players. The current ecosystem suffers from:

* **Expensive Compute Costs:** The dominance of centralized AI cloud providers results in high training and inference costs, limiting AI accessibility.
* **Underutilized AI Resources:** Existing AI platforms fail to optimize data sharing, model reusability, and computational efficiency.

#### LazAI’s Solution: AI Execution Layer & Verifiable Computing

LazAI introduces a scalable, decentralized execution model that ensures low-cost, high-performance AI training and inference:

* **On-Chain Verified AI Execution:** LazAI utilizes TEEs and ZKPs to ensure trustless AI data evaluation and model execution.
* **Tokenized AI Incentive Mechanisms:** Contributors (data providers, validators, and AI developers) receive DAT rewards, ensuring a sustainable and incentivized AI ecosystem.

With decentralized AI computing, LazAI democratizes access to AI training and inference, making AI more efficient, collaborative, and economically viable.

### 2.3 Composability-Driven AI Economy

The current AI economy remains siloed—models are locked behind APIs, datasets are gated by licensing, and interactions between different AI systems are difficult to orchestrate. This fragmentation severely limits innovation, especially in scenarios that require collaboration across multiple agents, domains, or stakeholders.

#### LazAI’s Solution: A Unified and Tokenized AI Marketplace

LazAI envisions a permissionless, composable AI economy where every AI asset—whether it’s a dataset, model, or an agent’s inference output—can be tokenized, verifiably exchanged, and reused across different contexts.

* **DAT-Powered AI Assetization:** With the DAT standard, LazAI enables every AI component to be treated as an on-chain asset. Each token anchors usage rights, provenance, share entitlements, and optional expiration, providing a standardized wrapper for trustless AI interaction.
* **Composable AI Infrastructure:** By unifying tokenized models, datasets, and agents under the same programmable interface, LazAI supports complex, multi-agent workflows. Agents can autonomously call each other’s services, build on top of one another’s outputs, or co-train using shared datasets, without needing centralized orchestration.
* **Decentralized AI Marketplace:** LazAI hosts an open marketplace for AI assets and services, allowing:
  * Individuals to monetize their datasets or fine-tuned models
  * Developers to compose multi-agent pipelines on-chain
  * Communities to curate domain-specific intelligence through iDAO governance
  * A new class of applications such as personal AI avatars, capable of evolving through market interactions, offering emotional support, knowledge exchange, or value generation

In this model, ownership, access, and collaboration become programmable, turning today’s static AI deployments into a dynamic, modular, and liquid ecosystem.

### 2.4 Technical Architecture: How It All Works Together

To clarify how LazAI’s components interact, we’ve broken down the core workflow—from data submission to value distribution, with a simplified diagram and step-by-step explanation.In general, it is a workflow and technical framework with DAT as the core. <br>

<figure><img src="/files/8Ar6MQRw5jMQsET1uA1w" alt=""><figcaption></figcaption></figure>

We basically divide users into two categories: data contributors and data users. LazAI ensures a fair, just and open on-chain data governance and economic ecosystem through a series of technical frameworks and workflows.

For more details, please refer to: [LazAI Workflow and Runtime](https://docs.google.com/document/d/1aaDoc3iBzrdR0TtD1c0OelzkDrpKfnFfXcqOm3_rFUQ/edit?tab=t.nozi4aiczezn)

## 3. LazAI Verified Computing Framework

Ensuring the authenticity, integrity, and verifiability of AI data is critical to building a trustworthy AI ecosystem. LazAI has developed a decentralized, efficient, and scalable verification framework that integrates iDAO governance, Quorum-based validation. This framework provides a robust lifecycle verification process for AI datasets, training models, and inference results, ensuring that all AI-generated assets are trustless, transparent, and tamper-proof.

<figure><img src="/files/LlRzpedb8xNKgING2nBY" alt=""><figcaption></figcaption></figure>

### 3.1 AI Data Verification Process

As shown in the picture above, the LazAI verification process follows a structured four-step validation flow that ensures data is securely recorded, verified, and continuously monitored within the LazAI Network. This process involves submission, registration, proof validation, and final verification with reward allocation.

#### Step 1: iDAO Submits LazAI Flow to Quorum

Each iDAO plays a pivotal role in the validation and governance of AI datasets and models. iDAOs are responsible for submitting LazAI Flow to their designated Quorum, a decentralized validation group that ensures AI data meets integrity and provenance standards.

<figure><img src="/files/0O8KhM1fMkFpIhTGIgSp" alt=""><figcaption></figcaption></figure>

**LazAI Flow consists of:**

* Dataset Metadata: Source, type, quality indicators, and integrity markers.
* Training Model Information: Parameters, architecture, and provenance to ensure AI reproducibility.
* Agent Metadata: AI agent execution parameters, behavioral logs, and validation history.

Once verified within the Quorum, this information is anchored on-chain, preventing manipulation and ensuring dataset ownership.

#### Step 2: LazChain Network Registers LazAI Flow & Generates LazAI Assets

Upon successful validation by the Quorum, the LazChain Network records the LazAI Flow as an immutable transaction, creating a permanent on-chain record of the AI dataset’s lineage. At this stage, the system generates corresponding LazAI Assets, which serve as tokenized representations of AI data (DATs).

These assets serve as proof-of-origin, data integrity markers, and programmable AI governance tools within the LazAI ecosystem.

#### Step 3: iDAO & Challengers Submit Verification Proofs

To maintain continuous integrity and prevent fraudulent AI data submissions, iDAOs and challengers engage in a verification proof process.

* iDAO submits Verification Proofs: Proving data authenticity, AI model accuracy, and inference correctness using cryptographic validation techniques.
* Challengers (Fraud Proof Validators) submit Fraud Proofs: If inconsistencies or malicious claims are detected, challengers can dispute dataset authenticity, training results, or inference outputs.

Fraud Proofs ensure that biased AI models, synthetic data manipulation, or compromised datasets are identified and penalized before they are used in critical applications.

#### Step 4: LazChain Network Verifies Proofs & Allocates Rewards

Once Proofs and Fraud Proofs are submitted, the LazChain Network runs a Verify Contract that executes multi-layered verification methods, including:

1. **Off-Chain Proofs:** iDAOs perform self-validation for efficient, low-cost verification.
2. **Optimistic Proofs:** Assumes submitted data is valid unless challenged by a fraud proof.
3. **TEE or ZK Proofs:** Provides cryptographic verification without exposing sensitive AI model data.

**Reward & Penalty Allocation:**

* **Valid Verification Proofs:** The submitting iDAO receives DAT rewards as an incentive for contributing trustworthy AI data.
* **Successful Fraud Proofs:** Challengers earn dispute resolution rewards, and the original submitter faces slashing penalties for fraudulent claims.
* **Final Verification Record:** All results are stored within the DAT ecosystem, ensuring transparency and traceability across the AI network.

### 3.2 Key Advantages of LazAI’s Verification Framework

The LazAI Verification Framework provides a trustless, decentralized approach to AI dataset validation, model verification, and fraud prevention, ensuring a scalable and secure AI-driven blockchain network.

1. **Decentralized & Scalable:** iDAO + Quorum-based validation prevents single points of failure and ensures data integrity without requiring central control.
2. **Trustless AI Data Verifications:** Ensure AI data remains verifiable, tamper-proof, and auditable without exposing raw data.
3. **Efficient Dispute Resolution:** Optimistic Proofs (OPs) reduce verification overhead, while Fraud Proof mechanisms ensure a secure challenge-response validation system.
4. **Incentive-Driven Ecosystem:** DAT rewards incentivize high-quality AI data submissions, while slashing mechanisms discourage false claims, ensuring an economically sustainable verification system.

### 3.3 Conclusion

By combining economic incentives, cryptographic proofs, and decentralized AI governance, LazAI provides a robust verification standard that supports secure, scalable, and verifiable AI ecosystems for Web3 and beyond.

## 4. LazAI DAT

The Data Anchoring Token (DAT) is a semi-fungible token (SFT) standard developed by LazAI to represent AI-native digital assets. Unlike general-purpose token formats, DAT integrates three essential properties into a unified structure:

* **Ownership Certificate:** Proof of contribution or claim over datasets, models, or computation results;
* **Usage Right:** Access quota to invoke AI services, such as agent execution or model calls;
* **Value Share:** Economic entitlement to future revenue, proportional to the token’s value and shareRatio.

With a Class-based architecture, value-based metering, and on-chain verifiability, DAT enables:

* Composable AI datasets and modular agents
* Tokenized inference and usage-based access
* Royalty-backed economic models for AI contributors

This standard serves as the core abstraction for AI assets in LazAI, supporting programmable licensing, fine-grained rights enforcement, and seamless integration with the broader AI data economy. It represents a next-generation framework that moves beyond static NFTs or ERC-20s — optimized for the dynamic, evolving world of decentralized AI.

### 4.1 Key Design Features of DAT

The Data Anchoring Token (DAT) is a novel semi-fungible asset format tailored for decentralized AI applications. Each DAT token represents a dynamic bundle of:

* **Ownership Certificate:** Provenance and authorship of AI datasets, models, or inferences
* **Usage Right:** Access quota for invoking AI services
* **Revenue Share:** A programmable entitlement to future rewards

To enable scalability and composability, DAT follows a class-based architecture:

**Class-Based Structure**

Each class represents an AI asset category (e.g., Dataset, Model, Agent) with metadata including:

* Descriptive name and URI
* Hash-based proof for integrity
* Optional expiration or policy constraints

**Minting and Value Parameters**

When issuing a DAT, the following key fields are defined:

<table data-header-hidden><thead><tr><th width="284.94921875"></th><th></th></tr></thead><tbody><tr><td><strong>Filed</strong></td><td><strong>Description</strong></td></tr><tr><td>value</td><td>Usage quota (e.g., number of calls, tokenized weight)</td></tr><tr><td>shareRatio</td><td>Revenue entitlement (e.g., 5% of future earnings)</td></tr><tr><td>expireAt</td><td>Optional expiration (for subscriptions or licenses)</td></tr></tbody></table>

**Programmable Operations**

* Internal Value Transfer: DATs of the same class can exchange partial value via transferValue, enabling fine-grained utility sharing across agents or users.
* Class-Level Approvals: With approveForClass, holders can delegate operational control to contracts or platforms.

**Integrated Revenue Sharing**

Revenue from AI agent usage can be automatically split among token holders based on shareRatio, optionally routed through a settlement contract. This eliminates the need for off-chain reconciliation and ensures on-chain traceability.

### 4.2 DAT Lifecycle Example

<figure><img src="/files/ZnqrYr3epyrvG9phrMlU" alt=""><figcaption></figcaption></figure>

#### **Step 1: Define an AI Asset Class**

Register a new category for AI assets (e.g., datasets, models).

* Assign a unique class ID (e.g., 1) to identify the asset category.
* Name the class (e.g., "Medical Dataset") and describe its purpose (e.g., "Open-source dataset for disease classification").
* Store metadata (e.g., asset details, usage rights) on a decentralized storage system like IPFS, and link it to the class using a URI (e.g., ipfs\://metadata/med-dataset-class)

#### **Step 2: Mint DAT Tokens (Bind and Issue Assets)**

Create tokens representing ownership or access to a specific AI asset within a class.

* Specify the recipient (user or address) who will hold the token (e.g., user1).
* Link the token to the asset class using its class ID (e.g., 1 for "Medical Dataset").
* Define the token’s value (e.g., 1000 units with 6 decimal places for precision).
* Set a revenue share ratio (e.g., 5%, represented as 500 in a 10,000-scale system) for distributing future earnings.
* Optionally, set an expiration time (e.g., 0 for no expiration).

#### **Step 3: Service Payment (Agent Invocation)**

Pay for AI services using DAT tokens.

* Transfer tokens from a user’s wallet (e.g., user1’s token ID) to a designated treasury (e.g., an agent’s contract address).
* Specify the payment amount (e.g., 100 units) for using the agent’s services.
* Support flexible billing models:
  * Pay-as-you-use: Directly charge for each service invocation.
  * Delegated billing: Allow third parties (e.g., employers) to pay on behalf of users.

#### **Step 4: Revenue Share Demonstration (Future Extension)**

Distribute earnings generated by the AI agent to token holders.

* When the agent earns revenue (e.g., 10 USDC from service fees), the contract calculates each token’s share based on its revenue share ratio.
* For example, a token with a 5% ratio receives 0.5 USDC (5% of 10 USDC).
* Automatically transfer the proportional revenue to each token holder’s wallet.

#### **Step 5: Token Expiration (Optional)**

Manage time-bound access to AI assets (e.g., subscriptions)

* Set an expiration timestamp for a token (e.g., after 1 year).
* When the timestamp is reached, the token’s access rights to the AI asset are revoked automatically.
* Use cases:
  * Subscription-based models (e.g., access to a premium medical dataset for 3 months).
  * Time-limited licenses for AI tools.

## 5. LazAI Quorum-Based BFT

LazAI’s Quorum-Based BFT (QBFT) consensus is a modular and scalable consensus protocol optimized for AI-centric decentralized systems. It blends practical Byzantine Fault Tolerance (PBFT) with a Quorum-based voting mechanism to ensure efficient validation, integrity, and liveness in a multi-agent AI data network.

### 5.1 Key Actors inside LazAI’s QBFT Layer

Rather than a generic “validator set,” LazAI organises consensus around Quorums — small, domain-focused collectives that both validate blocks and curate AI data.

<table data-header-hidden><thead><tr><th width="181.71484375"></th><th></th><th width="285.6875"></th></tr></thead><tbody><tr><td><strong>Actor</strong></td><td><strong>Core Responsibility</strong></td><td><strong>How They Earn / Risk</strong></td></tr><tr><td>Quorum<br>(validator collective)</td><td>1.Runs BFT consensus<br>2.Stores hash-anchored AI data &#x26; proofs</td><td><p>1.Block rewards &#x26; a share of iDAO fees </p><p>2.Slashed for signing bad data</p></td></tr><tr><td>Proposer<br>(rotates among Quorums)</td><td>Packages the next block / state update</td><td>Priority fees</td></tr><tr><td>Validator<br>(members of the elected Quorum)</td><td>Votes on the proposal, signs final commit</td><td>Portion of fees + staking yield</td></tr><tr><td>Challenger (quorum-elected watch-dogs)</td><td>Audits proofs, files Fraud-Proofs if needed</td><td>Gets a bounty when a fraud claim is upheld</td></tr></tbody></table>

**Why the split?**

* Quorums supply economic security and domain expertise (e.g., medical-data quorum vs. DeFi-model quorum).
* Challengers keep everyone honest without bloating the fast path of consensus.

### 5.2 VSC (Verifiable Service Coordinator)-Based iDAO-Quorum Interaction Protocol

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdykfhc0lvTIkH0T79uN2qKDYiJ34PHWurQKREN-vQzWsIbAvK8nyvAuQmfNLa13V3Eff4RsKAvgPwzlacci7JxUZW2iqArq60h9v07fIZsW0fk0GRsBR8UgQHEFrsknSqIQcub?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

#### Security Delegation via Stake-Based Quorum Integration

Each Quorum node participating in LazChain’s consensus mechanism is required to stake native tokens as a guarantee of honest behavior. Through this staking model and potential external collaborations (e.g., restaking, cross-chain validation, or inter-protocol delegation), iDAOs indirectly inherit the economic security of LazChain.

#### POV/Model/Agent Updates Are Transmitted via VSC to Quorum for Consensus

Whenever an iDAO performs updates—whether submitting new POV Inlet data, publishing a model, or deploying an AI Agent—these changes are packaged as service transactions and routed to the relevant Quorum via the VSC protocol. Each Quorum, operating under a Byzantine Fault Tolerant (BFT) consensus, independently validates and reaches agreement on the transaction outcome before anchoring them to LazChain.

#### Proof Submission & Asynchronous Validation via VSC

After consensus on the high-level update, VSC asynchronously dispatches verification artifacts—such as ZK proofs, Optimistic Proofs, or TEE attestations—to the relevant Quorum nodes. These proofs serve as cryptographic evidence that the update was generated under valid computational assumptions and that the iDAO’s declared actions were faithfully executed.

#### Challenger Arbitration and Slashing Procedure

Within each Quorum, a rotating set of Challenger nodes is elected to perform near real-time audits. These nodes continuously pull iDAO-submitted data and associated proofs from LazChain. If a Challenger detects inconsistency—such as an inference proof not matching the declared model weights, it can trigger a slashing dispute.

**This initiates the following:**

* Immediate freeze of the suspicious iDAO update.
* Verification of the challenger’s claim through multi-round consensus.
* If valid, slashing of:
  * Staked tokens by the responsible Quorum node (if it facilitated an invalid consensus).
  * DAT assets or usage credits associated with the offending iDAO.

### 5.3 Quorum-Based BFT Protocol (QBFT)

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcpmEkgPxuvOUAv_TPXD6qoZB031ga3yiC8Jc_OYzVbCGZSLf-lQkFtdQSruy1ZuRhN28OYsjyvAGFzrLgEU7j8k6vXZfR60h4s8myuBvluxLKhPb6XaHjzAqc1FENxFNE6cm4L?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

#### Quorum-as-Validator: BFT Participation

Each Quorum in LazAI is treated as a full validator node in the BFT consensus layer of LazChain. Quorums participate in ordering and validating transactions related to AI datasets, models, and inference proofs.

* **BFT Layer:** Built on a Byzantine Fault Tolerant consensus mechanism, where Quorums serve as the proposers, voters, and committers.
* **Quorum ID:** Each Quorum has a registered QuorumID and validator weight based on its staking level and historical performance.
* **Deterministic Rotation:** Block proposal is rotated across Quorums; performance and slashing affect rotation weights.

#### iDAO ↔ Quorum: Trust-Coupling via Economic Bonding

Each iDAO must establish explicit trust relationships with one or more Quorums to publish and validate AI assets. Two flexible trust modes are supported:

* Restaking Mode: iDAO stakes native tokens (e.g., $LAZ) to the target Quorum, delegating verification responsibility. Slashing penalties apply for fraud or invalid proofs.
* DAT-Backed Trust Mode: iDAO may mint AI assets (e.g., datasets or models) as DATs and request endorsement by a Quorum. In this mode:
  * The Quorum acts as a verifier and partial staker of the DAT.
  * The DAT becomes slashing-enabled: provable fraud leads to partial revocation or burn of DAT value.
  * Revenue sharing can be jointly configured between iDAO and Quorum based on the shareRatio.

#### Quorum as a Hash-Proven Off-Chain Storage Gateway

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXfJTDkLDYYgtdEtN9idWZy2SdcUHc2f3MBip2QLbEH3rFSxEqSToKPItJuEx_5ASBtL8nPsVdKBVwFpKeHMNjMH93f7rD9ygMbVodEl2BxgprrfjYdxjX0Chv3jfY7_D0mf1TlDCA?key=S_AVxe4Pa4t7GMdXHRa1L20C" alt=""><figcaption></figcaption></figure>

Quorums are not only validators, but also serve as off-chain AI storage coordinators. They host:

* Raw datasets (IPFS/Arweave/Filecoin),
* Fine-tuned models,
* Inference results, execution logs, and
* OP/ZK/TEE-based proofs.

Only the corresponding hash commitments and metadata are posted on-chain to minimize LazChain storage load.

iDAOs fetch training data from Quorums and submit updates via Verifiable Service Coordinator (VSC).

#### VSC: Orchestrated Trustless Coordination

The Verifiable Service Coordinator (VSC) bridges iDAO outputs and Quorum consensus:

* Transaction Submission: iDAO sends POV Updates, Model Anchors, Inference Outputs, and Verification Proofs to the VSC.
* Proof Dispatching: VSC asynchronously dispatches proof bundles (e.g., OP/ZK/TEE) to corresponding Quorums.
* Quorum Consensus: Quorums validate the bundles and finalize them on LazChain via BFT.

#### Challenger-Based Slashing Protocol

To ensure iDAO integrity and data authenticity, Challenger nodes are elected from within each Quorum:

* **Near-Real-Time Monitoring:** Challengers continuously pull Quorum-endorsed proofs from LazChain.
* **Fraud Detection:** If an iDAO is found to have submitted a model/proof inconsistent with the training dataset or usage policy:
  * A fraud proof can be submitted.
  * If verified, the iDAO is slashed (token stake or DAT-backed value).
  * The challenger is rewarded.
* **Slashing Scope:**
  * Native token slashing from restaking.
  * DAT shareRatio burn from endorsement.
  * Temporary blacklist from specific Quorums.

#### Innovation Points vs Traditional BFT

<table data-header-hidden><thead><tr><th width="191.40234375"></th><th width="301.1015625"></th><th></th></tr></thead><tbody><tr><td><strong>Dimension</strong></td><td><strong>LazAI LQBCP</strong></td><td><strong>Traditional BFT</strong></td></tr><tr><td>Validator Abstraction</td><td>Quorums serve as both consensus validators and AI data providers</td><td>Validators focus purely on block finality</td></tr><tr><td>Slashing Logic</td><td>Multi-source: token-based, asset-based (DAT), behavior-based</td><td>Typically token-only</td></tr><tr><td>Trust Flexibility</td><td>iDAO dynamically bonds to trusted Quorums via staking or asset endorsement</td><td>Static validator set</td></tr><tr><td>Proof Integration</td><td>Built-in OP/ZK/TEE verification with off-chain data binding</td><td>Not natively data-aware</td></tr><tr><td>Data Provenance Layer</td><td>Hash-based anchoring via Quorum storage</td><td>Not data-integrated</td></tr><tr><td>Modular Incentives</td><td>iDAO ↔ Quorum reward agreements via DAT share ratios</td><td>Monolithic block reward or fee</td></tr></tbody></table>

## 6. iDAO - Individual-Centric DAO

To address the AI data alignment issue, LazAI introduces an innovative blockchain solution and redefines DAO as iDAO, focusing on individuals to reshape organizational boundaries.

An iDAO (Individual-centric intelligent DAO) is LazAI’s evolution of the traditional DAO (Decentralized Autonomous Organization). Instead of focusing on collective or corporate entities, iDAOs empower individuals to govern their AI agents, data assets, and computational resources.

### The main responsibilities of iDAO include:

1. **Providing Trustworthy AI Data Sources or AI Flow:** Offering reliable data sources or AI workflows to other individuals or organizations, ensuring high-quality and aligned data.
2. **Off-Chain Dataset Training and Inference:** Off-chain dataset training and inference, providing AI proxy services, enabling more efficient and economical AI computing, and providing a unified API for external services, while ensuring privacy and security through TEE and ZK technologies.
3. **Decentralized Consensus and Data Governance:** iDAO participates in the LazChain consensus in the form of a Quorum. Through the decentralization of multiple Quorum organizations, it ensures the reliability and transparency of data governance and storage. Each Quorum acts as an independent iDAO, similar to a traditional data center, but without storing data directly on-chain, effectively reducing on-chain storage costs. iDAO organizations achieve consensus to verify the trustworthiness of off-chain data, ensuring that data is efficiently and quickly available to both on-chain and off-chain agents while ensuring high availability and low latency. Different iDAOs can issue their own DAT tokens through their administrators. The value of DAT tokens is determined by two factors:&#x20;
   1. The initial value of the data is determined by the validator node through the quality assessment algorithm of the corresponding data category (medical, autonomous driving, etc.);&#x20;
   2. The value of the data is determined by the validator node based on its customized economic model and market freedom.
4. **Incentivized & Composable AI Economy:** Developers and data providers earn DAT rewards for contributing high-quality AI assets, ensuring an aligned incentive mechanism. AI models, datasets, and computational resources can be composed into higher-order AI services, creating a liquid and programmable AI economy.&#x20;
5. **Building UI or Products:** In addition to the corresponding APIs to help developers build AI applications, iDAO organizations usually also provide corresponding simple UIs or applications to help non-technical personnel participate in the corresponding iDAO organization with a better experience. For example, through the UI, they can contribute their data to the iDAO in a more automated way to gain benefits, or help people better benefit from the functions provided by the entire iDAO to ensure fair distribution of responsibilities, rights and interests.

#### **Key Functions**

* **Governance Autonomy:** Each user controls their iDAO, establishing governance over their personal AI assets (datasets, models, and inference results).
* **Data Sovereignty:** Users own and manage their personal data flows, deciding who can access their data and under what terms.
* **AI Agent Management:** Individuals can deploy personalized AI Agents (MicroAgents) governed and customized through their iDAO.
* **Participate in Consensus:** iDAOs participate in LazChain’s decentralized consensus mechanism (via Quorums), ensuring trustless data validation and governance.

The traditional DAO framework doesn’t offer fine-grained, individual control over AI resources. iDAO changes that by putting users at the center of AI governance and ownership, ensuring equitable participation and benefits.

## 7. Conclusion

LazAI redefines the artificial intelligence landscape by integrating blockchain technology, verifiable computing, and decentralized governance, addressing three fundamental challenges plaguing traditional AI: barriers to data sharing, lack of standardized quality evaluation, and inequitable value distribution.

By centering data ownership, verifiability, and fair rewards, it bridges the gap between cutting-edge technology and ethical AI development. As more contributors, developers, and industries join its ecosystem, LazAI is poised to transform AI from a tool of the few into a shared intelligence infrastructure for all, defining the next era of decentralized AI.

<br>


