diff --git a/.github/workflows/check-protocol-docs.yml b/.github/workflows/check-protocol-docs.yml new file mode 100644 index 00000000..cd6a71f2 --- /dev/null +++ b/.github/workflows/check-protocol-docs.yml @@ -0,0 +1,28 @@ +name: Check Protocol Documentation + +on: + pull_request: + paths: + - "pages/understand-genlayer-protocol.mdx" + - "pages/understand-genlayer-protocol/**" + - "pages/api-references/genlayer-node/gen/gen_getTransactionStatus.mdx" + - "scripts/check-protocol-docs.js" + - "PROTOCOL_DOCUMENTATION.md" + push: + branches: [main] + paths: + - "pages/understand-genlayer-protocol.mdx" + - "pages/understand-genlayer-protocol/**" + - "pages/api-references/genlayer-node/gen/gen_getTransactionStatus.mdx" + - "scripts/check-protocol-docs.js" + - "PROTOCOL_DOCUMENTATION.md" + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: node scripts/check-protocol-docs.js diff --git a/PROTOCOL_DOCUMENTATION.md b/PROTOCOL_DOCUMENTATION.md new file mode 100644 index 00000000..2d082b50 --- /dev/null +++ b/PROTOCOL_DOCUMENTATION.md @@ -0,0 +1,58 @@ +# Protocol documentation maintenance + +Use this guide when changing `pages/understand-genlayer-protocol.mdx` or `pages/understand-genlayer-protocol/`. That section explains the protocol to readers; it must not become a second, independently evolving specification or API reference. + +## Source precedence + +When sources disagree, use this order and resolve the inconsistency before publishing: + +1. Deployed consensus contracts and the matching contract interfaces define executable state, enums, and transitions. +2. The consensus specification explains intended protocol behavior. Verify high-risk details against the implementation. +3. GenLayer Node and GenVM code and their repository documentation define component behavior. +4. Developer documentation in this repository defines the public SDK and Intelligent Contract APIs. +5. Architecture articles and blog posts can supply narrative and motivation, but they are not normative. + +Never copy a deployment default into a timeless rule. Label values such as timeouts, committee limits, minimum stake, weights, rewards, and slash percentages as current defaults or configurable parameters. + +## Page ownership + +Keep each fact in one primary place and link to it elsewhere. + +| Topic | Primary page type | +| --- | --- | +| Architecture, roles, lifecycle, and mental models | Understand GenLayer Protocol | +| Python APIs, code patterns, and contract restrictions | Intelligent Contract developer guides | +| SDK methods and frontend code | DApp developer guides and SDK reference | +| RPC fields, numeric codes, and response schemas | API reference | +| Node installation and operations | Validator documentation | + +Concept pages can summarize an API, but they should not duplicate long code examples or response payloads. API pages can link back to concepts instead of redefining consensus semantics. + +## Writing style + +Follow the [Google developer documentation style guide](https://developers.google.com/style) unless GenLayer terminology requires an exception. + +- Put the reader's question or outcome first. +- Use sentence case for headings. +- Prefer active voice, present tense, and short paragraphs. +- Define a term before using its abbreviation. +- Use **Intelligent Contract**, **GenLayer Chain**, **GenVM**, **Ghost**, and **Optimistic Democracy** consistently. +- Distinguish `Accepted` from `Finalized` and consensus status from execution result. +- Use meaningful link text. Link to the canonical page rather than “here.” +- Give every image useful alternative text. Prefer Mermaid for protocol flows that are likely to change. +- Separate protocol guarantees from current deployment configuration and future plans. + +## Review triggers + +Review the affected concept pages when any of these sources change: + +| Source change | Pages to review | +| --- | --- | +| `ITransactions.TransactionStatus` or phase contracts | Transaction execution, statuses, appeals, finality | +| Committee selection or round sizing | Validators, Optimistic Democracy, appeals | +| Staking, rewards, epochs, or slash contracts | Economic model, staking, slashing, unstaking | +| GenVM sandbox, runner, or host interface | GenVM, non-deterministic operations, LLM and web pages | +| Ghost, messages, or account queues | Architecture, accounts, transactions, finality | +| Node RPC receipt/status schema | Transaction pages and API reference | + +Run `npm run check:protocol-docs` after editing these pages. The check intentionally keeps a local snapshot of the public status enum because CI does not have the sibling consensus repository. Update the snapshot only after verifying the deployed-compatible consensus interface. diff --git a/README.md b/README.md index 1216479a..bb07dd0f 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,8 @@ You can use either `npm` or `pnpm` as your package manager. ## Maintaining Documentation +For protocol concept pages, follow [PROTOCOL_DOCUMENTATION.md](./PROTOCOL_DOCUMENTATION.md) and run `npm run check:protocol-docs` before opening a pull request. + ### Adding New Changelog Entries The changelog is automatically generated from individual version files during the build process. diff --git a/next.config.js b/next.config.js index 807c405b..39ff854f 100644 --- a/next.config.js +++ b/next.config.js @@ -70,6 +70,23 @@ const actualRedirects = [ { old: "/overview", new: "/understand-genlayer-protocol" }, { old: "/overview/:page*", new: "/understand-genlayer-protocol/:page*" }, + { + old: "/understand-genlayer-protocol/what-are-intelligent-contracts", + new: "/understand-genlayer-protocol/what-is-genlayer", + }, + { + old: "/understand-genlayer-protocol/what-makes-genlayer-different", + new: "/understand-genlayer-protocol/what-is-genlayer", + }, + { + old: "/understand-genlayer-protocol/who-is-genlayer-for", + new: "/understand-genlayer-protocol/what-is-genlayer", + }, + { + old: "/understand-genlayer-protocol/why-we-are-building-genlayer", + new: "/understand-genlayer-protocol/what-is-genlayer", + }, + { old: "/core-concepts", new: "/understand-genlayer-protocol/core-concepts" }, { old: "/core-concepts/:page*", new: "/understand-genlayer-protocol/core-concepts/:page*" }, @@ -133,7 +150,7 @@ const actualRedirects = [ }, { old: "/overview/genlayer-different", - new: "/understand-genlayer-protocol/what-makes-genlayer-different", + new: "/understand-genlayer-protocol/what-is-genlayer", }, { old: "/build-with-genlayer/use-cases", @@ -205,4 +222,4 @@ const nextConfig = withNextra({ }, }); -module.exports = nextConfig; \ No newline at end of file +module.exports = nextConfig; diff --git a/package.json b/package.json index d3a7b1d6..793e9d0c 100644 --- a/package.json +++ b/package.json @@ -4,10 +4,11 @@ "description": "GenLayer documentation", "scripts": { "dev": "npm run node-generate-changelog && npm run node-update-setup-guide && npm run node-update-config && npm run node-update-docker-compose && npm run node-update-monitoring-docker-compose && npm run node-update-monitoring-alloy-config && npm run node-update-greybox && npm run node-generate-api-docs && node scripts/generate-full-docs.js && node scripts/check-llm-exports.js && next dev", - "build": "npm run node-generate-changelog && npm run node-update-setup-guide && npm run node-update-config && npm run node-update-docker-compose && npm run node-update-monitoring-docker-compose && npm run node-update-monitoring-alloy-config && npm run node-update-greybox && npm run node-generate-api-docs && node scripts/generate-full-docs.js && node scripts/check-llm-exports.js && next build", + "build": "npm run check:protocol-docs && npm run node-generate-changelog && npm run node-update-setup-guide && npm run node-update-config && npm run node-update-docker-compose && npm run node-update-monitoring-docker-compose && npm run node-update-monitoring-alloy-config && npm run node-update-greybox && npm run node-generate-api-docs && node scripts/generate-full-docs.js && node scripts/check-llm-exports.js && next build", "start": "next start", "test:e2e": "playwright test", "generate-sitemap": "node scripts/generate-sitemap-xml.js", + "check:protocol-docs": "node scripts/check-protocol-docs.js", "node-generate-changelog": "node scripts/generate-changelog.js", "node-generate-api-docs": "node scripts/generate-api-docs.js", "node-update-setup-guide": "node scripts/update-setup-guide-versions.js", diff --git a/pages/api-references/genlayer-node.mdx b/pages/api-references/genlayer-node.mdx index 5f109115..1f682955 100644 --- a/pages/api-references/genlayer-node.mdx +++ b/pages/api-references/genlayer-node.mdx @@ -692,6 +692,7 @@ Returns the current consensus status of a transaction. This is a lightweight end | 11 | READY_TO_FINALIZE | | 12 | VALIDATORS_TIMEOUT | | 13 | LEADER_TIMEOUT | +| 14 | LEADER_REVEALING | **Example Request:** diff --git a/pages/api-references/genlayer-node/gen/gen_getTransactionStatus.mdx b/pages/api-references/genlayer-node/gen/gen_getTransactionStatus.mdx index 05a38643..1d86211c 100644 --- a/pages/api-references/genlayer-node/gen/gen_getTransactionStatus.mdx +++ b/pages/api-references/genlayer-node/gen/gen_getTransactionStatus.mdx @@ -37,6 +37,7 @@ Returns the current consensus status of a transaction. This is a lightweight end | 11 | READY_TO_FINALIZE | | 12 | VALIDATORS_TIMEOUT | | 13 | LEADER_TIMEOUT | +| 14 | LEADER_REVEALING | **Example Request:** diff --git a/pages/style.css b/pages/style.css index 2d6c40bc..848cf588 100644 --- a/pages/style.css +++ b/pages/style.css @@ -44,9 +44,52 @@ img { color: #BCA2FF !important; } +/* Give protocol diagrams a consistent, readable canvas. Mermaid adds the + aria-roledescription attribute after rendering, so this stays scoped to + diagrams without requiring a custom MDX wrapper. */ +main div:has(> svg[aria-roledescription]) { + margin: 1.75rem 0 2rem; + padding: clamp(1rem, 3vw, 1.75rem); + overflow-x: auto; + border: 1px solid rgba(109, 93, 245, 0.18); + border-radius: 14px; + background: + radial-gradient(circle at top right, rgba(109, 93, 245, 0.09), transparent 42%), + #fbfbfe; +} + +main svg[aria-roledescription] { + display: block; + margin: 0 auto !important; +} + +main svg[aria-roledescription] .node rect, +main svg[aria-roledescription] .actor { + rx: 8px; + ry: 8px; +} + +main svg[aria-roledescription] .edgeLabel { + border-radius: 4px; + color: #4b5563 !important; + background-color: rgba(251, 251, 254, 0.94) !important; +} + +.dark main div:has(> svg[aria-roledescription]) { + border-color: rgba(188, 162, 255, 0.24); + background: + radial-gradient(circle at top right, rgba(188, 162, 255, 0.12), transparent 42%), + rgba(17, 18, 28, 0.72); +} + +.dark main svg[aria-roledescription] .edgeLabel { + color: #e5e7eb !important; + background-color: rgba(17, 18, 28, 0.94) !important; +} + /* Prevent long method names from wrapping in sidebar */ nav.nextra-sidebar-container a span, aside a span { font-size: 0.8rem; word-break: break-all; -} \ No newline at end of file +} diff --git a/pages/understand-genlayer-protocol.mdx b/pages/understand-genlayer-protocol.mdx index 5fceb524..f87f1a3c 100644 --- a/pages/understand-genlayer-protocol.mdx +++ b/pages/understand-genlayer-protocol.mdx @@ -1,69 +1,66 @@ --- -description: "Optimistic Democracy consensus in GenLayer: validator selection, recomputation, and AI-driven transaction validation." +description: "Understand GenLayer architecture, Intelligent Contract execution, Optimistic Democracy, transactions, and protocol economics." --- -## What is GenLayer? -GenLayer is the first AI-native blockchain built for AI-powered smart contracts—called Intelligent Contracts—capable of reasoning and adapting to real-world data. Its foundation is the Optimistic Democracy consensus mechanism, an enhanced Delegated Proof of Stake (dPoS) model where validators connect directly to Large Language Models (LLMs). This setup allows for non-deterministic operations—such as processing text prompts, fetching live web data, and executing AI-based decision-making—while preserving the reliability and security of a traditional blockchain. +import { Card, Cards } from "nextra-theme-docs"; -## Core Technology +# Discover the GenLayer protocol +GenLayer is an intelligent blockchain for applications that need consensus on outcomes derived from natural language, live web data, or other non-deterministic inputs. -At the heart of GenLayer lies Optimistic Democracy—an enhanced Delegated Proof of Stake (dPoS) consensus mechanism that integrates AI models directly into validator operations. This synergy delivers three capabilities traditional blockchains cannot match: +Intelligent Contracts divide execution into deterministic code and isolated non-deterministic operations. A selected leader proposes an execution result, a validator committee evaluates it under the contract's equivalence rule, and the onchain consensus system coordinates appeals and finality. -1. **On-Chain AI Processing** +## Start here -Validators connect to leading AI models (GPT, LLaMA, Meta, etc.) to execute complex reasoning on-chain, from natural language comprehension to data-driven predictions. + + + + + + -2. **Consensus-Backed Security** +## Architecture at a glance -Multiple validators vote on outcomes, ensuring collective agreement and robust reliability for every transaction—even those involving non-deterministic AI outputs. +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 44, "rankSpacing": 54, "htmlLabels": true}}}%% +flowchart TB + App(["Application"]) + Chain["GenLayer Chain
orders and coordinates"] + Worker["Validator node
performs assigned duty"] + VM["GenVM
executes or validates"] + Action["Signed proposal or vote"] + State(["Updated onchain state"]) -3. **Intelligent Contracts** + App -->|"1 · submit transaction"| Chain + Chain -->|"2 · publish assignment"| Worker + Worker -->|"3 · run contract"| VM + VM -->|"4 · return result"| Action + Action -->|"5 · record consensus action"| State -Smart contracts in GenLayer gain reasoning abilities, allowing them to understand natural language, process real-world data, and adapt to evolving conditions. + classDef actor fill:#F7F8FC,stroke:#8B95A7,color:#202536,stroke-width:1.5px; + classDef chain fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef compute fill:#EAF7FF,stroke:#2686C4,color:#113F59,stroke-width:2px; + class App actor; + class Chain,Action,State chain; + class Worker,VM compute; + linkStyle default stroke:#7C879C,stroke-width:1.8px; +``` -## Technical Implementation +- **GenLayer Chain** orders actions and stores the authoritative consensus state. +- **Validator nodes** watch the chain, maintain derived Intelligent Contract state, and perform assigned consensus duties. +- **GenVM** runs Intelligent Contracts in a WebAssembly sandbox and isolates web and LLM operations. -To integrate AI seamlessly with the blockchain, GenLayer employs a distributed neural consensus network, wherein validators run specialized software connected via API to advanced AI models. This approach unifies: +Each Intelligent Contract has an EVM-facing Ghost contract at the same address. The Ghost routes calls and messages between GenLayer Chain and GenVM. -- Delegated Proof of Stake (dPoS) for efficient block production and governance. -- Neural Consensus for non-deterministic transactions requiring advanced AI reasoning. +## Explore by topic -This architecture supports autonomous DAOs, self-executing prediction markets, and dynamic DeFi protocols that react to real-world data in real time. + + + + + + + + -# Optimistic Democracy: How Consensus Works - -Optimistic Democracy is GenLayer's consensus mechanism for merging probabilistic AI systems with deterministic blockchain rules so the network can reach secure and accurate consensus at scale. Inspired by **[Condorcet's Jury Theorem](https://jury-theorem.genlayer.com/)** (click the link to check out our interactive model), the process uses validator recomputation and majority agreement as a safety net for AI-driven computations. - -GenLayer Optimistic Democracy Consensus Diagram - -1. **User Submits a Transaction** -A user sends a transaction request to the network (see the diagram's Step 1). - -2. **Leader (Validator) Proposes Result** -The network selects a Leader, who processes the request and proposes an outcome (Step 2). - -3. **Validators Recompute** -A group of Validators independently re-compute the transaction (Step 3). If the output aligns with the Leader's proposal, they approve; otherwise, they deny. - -## Validator Selection Mechanism -Token holders bolster network security by delegating tokens to validator candidates. A deterministic function f(x) then randomly designates Leader-Validator and Validators for each transaction. This process promotes fairness, helps decentralize validation power, and strengthens GenLayer's security and trustlessness. - -## Validator Operational Framework -Each GenLayer validator node integrates: - -- **Validator Software** -Handles core blockchain functions: networking, block production, and transaction management. - -- **AI Model Integration** -Connects to Large Language Models (LLMs) or other AI services for complex reasoning, natural language processing, and real-time data retrieval. - -Validators seamlessly manage both: - -1. **Deterministic Transactions** typical of traditional blockchains. -2. **Non-Deterministic Transactions** that leverage AI-driven logic (e.g., searching the internet, analyzing data, making probabilistic inferences). - -By splitting tasks between standard deterministic transactions and advanced AI-powered transactions, GenLayer ensures high performance without compromising on security. - -## Putting It All Together -With Optimistic Democracy guiding consensus and validators empowered by AI, GenLayer enables a new class of blockchain applications. From DAOs that self-govern based on real-time data to DeFi protocols that dynamically adjust parameters in response to market changes, developers can now build truly intelligent decentralized solutions. +For the extended architectural rationale, read [Making GenLayer 100% Secure, Part 1: The Architecture](https://genlayer.com/blog/making-genlayer-100-percent-secure-part-1-the-architecture). diff --git a/pages/understand-genlayer-protocol/core-concepts.mdx b/pages/understand-genlayer-protocol/core-concepts.mdx index 872f0bf2..2368e5e1 100644 --- a/pages/understand-genlayer-protocol/core-concepts.mdx +++ b/pages/understand-genlayer-protocol/core-concepts.mdx @@ -1,21 +1,39 @@ --- -description: "GenLayer Core Concepts explains GenVM, transactions, Optimistic Democracy, finality, staking, slashing, and unstaking." +description: "Explore GenLayer architecture, execution, consensus, transactions, accounts, and protocol economics." --- -import { Card, Cards } from 'nextra-theme-docs' +import { Card, Cards } from "nextra-theme-docs"; -# Core Concepts +# Core concepts -GenLayer core concepts are the fundamental building blocks that explain how Intelligent Contracts remain secure, efficient, and reliable in a non-deterministic environment. Use these topics to understand GenVM, transactions, Optimistic Democracy, the Equivalence Principle, the appeal process, finality, staking, slashing, and unstaking. +Start with the architecture, then follow a transaction through execution, consensus, and finality. The pages in this section explain protocol behavior. For APIs and contract code, use the linked developer documentation. + +## Architecture and execution + + + + + + + + + +## Consensus and transactions + + + + + + + + + + +## Protocol economics - - - - - - - - - + + + + diff --git a/pages/understand-genlayer-protocol/core-concepts/_meta.json b/pages/understand-genlayer-protocol/core-concepts/_meta.json index 74ca54b6..398c6221 100644 --- a/pages/understand-genlayer-protocol/core-concepts/_meta.json +++ b/pages/understand-genlayer-protocol/core-concepts/_meta.json @@ -1,12 +1,12 @@ { - "validators-and-validator-roles": "Validators", + "rollup-integration": "GenLayer Chain Integration", + "accounts-and-addresses": "Accounts and Addresses", "genvm": "GenVM", - "optimistic-democracy": "Optimistic Democracy", - "rollup-integration": "Rollup Integration", "non-deterministic-operations-handling": "Non-deterministic Operations", "large-language-model-llm-integration": "LLM Integration", "web-data-access": "Web Data Access", + "validators-and-validator-roles": "Validators and Roles", + "optimistic-democracy": "Optimistic Democracy", "transactions": "Transactions", - "economic-model": "Economic Model", - "accounts-and-addresses": "Accounts and Addresses" + "economic-model": "Economic Model" } diff --git a/pages/understand-genlayer-protocol/core-concepts/accounts-and-addresses.mdx b/pages/understand-genlayer-protocol/core-concepts/accounts-and-addresses.mdx index c22053c3..078d2df6 100644 --- a/pages/understand-genlayer-protocol/core-concepts/accounts-and-addresses.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/accounts-and-addresses.mdx @@ -1,36 +1,72 @@ --- -description: "Accounts and addresses in GenLayer: EOAs, contract accounts, 0x addresses, keys, transactions, gas, and security" +description: "Understand GenLayer EOAs, EVM contracts, Intelligent Contracts, Ghost contracts, addresses, and transaction queues." --- -# Accounts and Addressing +# Accounts and addresses -Accounts in GenLayer are entities that can hold tokens, deploy Intelligent Contracts, and initiate transactions on the network. GenLayer supports Externally Owned Accounts controlled by private keys and Contract Accounts associated with deployed Intelligent Contracts, each using addresses typically represented as `0x`-prefixed hexadecimal strings. +GenLayer uses Ethereum-style, `0x`-prefixed addresses. The meaning of an address depends on whether it identifies an externally owned account (EOA), an EVM contract, or an Intelligent Contract and its Ghost. -## Overview +## Account types -Accounts are fundamental to interacting with the GenLayer network. They represent users or entities that can hold tokens, deploy Intelligent Contracts, and initiate transactions. +| Account | Controlled or executed by | Can initiate an EVM transaction? | Where code runs | +| --- | --- | --- | --- | +| EOA | A private key or smart-account policy | Yes | No contract code | +| EVM contract | EVM bytecode | Through calls and messages | GenLayer Chain | +| Intelligent Contract | GenVM code | Through its Ghost and message system | GenVM | -## Types of Accounts +## Intelligent Contracts and Ghosts share an address -1. **Externally Owned Accounts (EOAs)**: - - Controlled by private keys - - Can initiate transactions and hold tokens +Deploying an Intelligent Contract creates a Ghost contract on GenLayer Chain and the corresponding Intelligent Contract in GenVM. Both use the same address. -2. **Contract Accounts**: - - Associated with deployed Intelligent Contracts - - Have their own addresses and code +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 44, "rankSpacing": 50, "htmlLabels": true}}}%% +flowchart TB + Sender(["EOA or EVM contract"]) + Address{"Address
0xABC…"} -## Account Addresses + subgraph ChainLayer["GenLayer Chain"] + direction LR + Ghost["Ghost contract
0xABC…"] --> Consensus["Consensus contracts"] + end -- **Address Format**: GenLayer uses a specific address format, typically represented as a hexadecimal string prefixed with `0x`. -- **Public and Private Keys**: Addresses are derived from public keys, which in turn are generated from private keys kept securely by the account owner. + subgraph ExecutionLayer["Validator execution"] + direction LR + Node["Validator nodes"] --> IC["Intelligent Contract
0xABC… · GenVM"] + end -## Interacting with Intelligent Contracts + Sender -->|"call"| Address --> Ghost + Consensus --> Node + Address -. "same logical address" .-> IC -- **Transaction Sending**: Accounts initiate transactions to call functions on Intelligent Contracts or transfer tokens. -- **Gas Fees**: Transactions require gas fees to be processed. + classDef actor fill:#F7F8FC,stroke:#8B95A7,color:#202536,stroke-width:1.5px; + classDef address fill:#FFF4E5,stroke:#D58A16,color:#583705,stroke-width:2px; + classDef chain fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef compute fill:#EAF7FF,stroke:#2686C4,color:#113F59,stroke-width:2px; + class Sender actor; + class Address address; + class Ghost,Consensus chain; + class Node,IC compute; + style ChainLayer fill:#F8F7FF,stroke:#B9B0FF,stroke-width:1px + style ExecutionLayer fill:#F5FBFF,stroke:#A8D7F2,stroke-width:1px + linkStyle default stroke:#7C879C,stroke-width:1.8px; +``` -## Account Management +The Ghost is an EVM-facing proxy for protocol integration, not a second copy of the Intelligent Contract logic. It holds the address's native GEN balance on GenLayer Chain and forwards calls into consensus. If GenVM deployment fails, the Ghost can remain as the address placeholder for a later successful deployment. -- **Creating Accounts**: Users can create new accounts using wallets or development tools provided by GenLayer. -- **Security Practices**: Users must securely manage their private keys, as losing them can result in loss of access to their funds. \ No newline at end of file +## Accounts also define execution order + +The consensus system maintains state and queues for each Intelligent Contract recipient. Transactions addressed to the same Intelligent Contract pass through the active proposal and voting phases sequentially. This keeps later state changes from overtaking an earlier unresolved state change. + +Transactions to different Intelligent Contracts can progress independently. + +## Keys and security + +An EOA address is derived from its public key and controlled by the corresponding private key. Never put a private key or recovery phrase in contract code, frontend source, logs, or documentation examples. Use a wallet or managed signer to sign transactions. + +Validator accounts use a separate owner/operator model. See [staking](/understand-genlayer-protocol/core-concepts/optimistic-democracy/staking) for those roles. + +## Related developer guides + +- [Deploy an Intelligent Contract](/developers/intelligent-contracts/deploying) +- [Call Intelligent Contracts](/developers/decentralized-applications/writing-data) +- [Messages and Ghost contracts](/developers/intelligent-contracts/features/messages) diff --git a/pages/understand-genlayer-protocol/core-concepts/economic-model.mdx b/pages/understand-genlayer-protocol/core-concepts/economic-model.mdx index bc2a01be..2efa2697 100644 --- a/pages/understand-genlayer-protocol/core-concepts/economic-model.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/economic-model.mdx @@ -1,28 +1,61 @@ --- -description: "Economic Model explains GenLayer validator staking, rewards, transaction fees, slashing, and economic security." +description: "Learn how GenLayer fees, appeal bonds, staking rewards, and penalties fund consensus and align participants." --- -# Economic Model +# Economic model -GenLayer's Economic Model defines how staking, rewards, transaction fees, and slashing incentivize participants to maintain the network's security and functionality. Validators stake tokens to participate in validation, earn rewards for correctly validating transactions, receive fees from transaction processing, and risk penalties if they act maliciously or incompetently. +GenLayer's economic model pays for Intelligent Contract execution and makes validators accountable for timely, honest work. Its main mechanisms are transaction fee budgets, appeal bonds, staking rewards, and penalties. -## Overview +## Transaction budgets -GenLayer's economic model is designed to incentivize participants to maintain the network's security and functionality. It involves staking, rewards, transaction fees, and penalties. +An Intelligent Contract transaction can require several EVM transactions and many GenVM executions. The sender therefore funds a protocol budget rather than paying only for the submission transaction. -## Key Components +The budget can cover: -- **Staking**: Validators must stake tokens to participate in the validation process, aligning their interests with the network's health. -- **Rewards**: Validators receive rewards for correctly validating transactions. -- **Transaction Fees**: Users pay fees for transaction processing, which are partly used to reward validators. -- **Slashing**: Validators acting maliciously or incompetently can have their staked tokens slashed as a penalty. +- leader and validator execution time; +- normal rounds and funded leader rotations; +- GenVM storage and receipt data; +- messages created by the Intelligent Contract; and +- any appeal capacity the sender chooses to pre-fund. -## Incentive Mechanisms +The sender also sets price ceilings. Prices lock when the transaction activates so a later governance change cannot silently charge more than the sender authorized. Unused budget is refunded according to the protocol's contributor accounting. -- **Positive Incentives**: Rewards and fees motivate validators to act in the network's best interest. -- **Negative Incentives**: Slashing and penalties deter malicious behavior. +Appeal bonds are separate from the primary transaction budget. The bond funds the additional committee or proposal round and is returned or forfeited according to the appeal result. -## Economic Security +## Validator selection and stake -- **Stake-Based Security**: The amount staked by validators serves as a deterrent against attacks, as they risk losing their stake. -- **Balancing Supply and Demand**: The economic model aims to balance the supply of validation services with demand from users. \ No newline at end of file +Validators provide self-stake, and token holders can delegate stake to them. Selection weight combines both amounts and applies a sublinear exponent. This gives larger pools more selection probability while reducing the advantage of concentrating all stake in one validator. + +Current default parameters include: + +| Parameter | Default | +| --- | ---: | +| Minimum validator self-stake | 42,000 GEN | +| Minimum delegation | 42 GEN | +| Maximum active validators | 1,000 | +| Self-stake weight (`alpha`) | 0.6 | +| Weight exponent (`beta`) | 0.5 | +| Unbonding period | 7 epochs | + +These are governance or deployment parameters, not constants applications should hardcode. + +## Reward sources and routing + +Rewards come from transaction fees and protocol inflation. Under the current distribution, the combined pool is routed as follows: + +| Recipient | Share | +| --- | ---: | +| Stake pools, including self-stake and delegation | 75% | +| Validator owners for operations | 10% | +| Intelligent Contract developers | 10% | +| DeepThought DAO treasury | 5% | + +Stake-pool rewards are assigned according to selection weight, then shared between a validator's owner and delegators according to their stake in that pool. Stake uses share accounting, so rewards compound by increasing the GEN value represented by each share. + +Protocol inflation starts from a configured bootstrap rate and declines toward a configured floor. Treat current rates and splits as protocol parameters when presenting estimates. + +## Negative incentives + +The protocol can reduce rewards, ban validators from selection, quarantine them during an investigation, slash stake for specified faults, and forfeit unsuccessful appeal bonds. Different faults use different mechanisms; a vote on the eventual losing side is not automatically proof of misconduct. + +See [staking](/understand-genlayer-protocol/core-concepts/optimistic-democracy/staking), [slashing](/understand-genlayer-protocol/core-concepts/optimistic-democracy/slashing), and [appeals](/understand-genlayer-protocol/core-concepts/optimistic-democracy/appeal-process). diff --git a/pages/understand-genlayer-protocol/core-concepts/genvm.mdx b/pages/understand-genlayer-protocol/core-concepts/genvm.mdx index 29a3e7af..7b180448 100644 --- a/pages/understand-genlayer-protocol/core-concepts/genvm.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/genvm.mdx @@ -1,38 +1,56 @@ --- -description: "GenVM is GenLayer's virtual machine for executing Python Intelligent Contracts with web and LLM access." +description: "GenVM is GenLayer's WebAssembly sandbox for deterministic and non-deterministic Intelligent Contract execution." --- -# GenVM (GenLayer Virtual Machine) +# GenVM -GenVM is the execution environment for Intelligent Contracts in the GenLayer protocol, processing and managing contract operations across the GenLayer ecosystem. GenVM executes Intelligent Contracts that may use non-deterministic code while preserving blockchain security and consistency. +GenVM is the execution environment for Intelligent Contracts. It runs contract code in a WebAssembly sandbox and exposes controlled host functions for contract state, messages, web access, and LLM calls. -[Source code at GitHub](https://github.com/genlayerlabs/genvm) +[View the GenVM source code](https://github.com/genlayerlabs/genvm). -## Purpose of GenVM +## Execution model -The only purpose of the GenVM is to execute Intelligent Contracts, which can have non-deterministic code while maintaining blockchain security and consistency. +GenVM separates reproducible execution from operations that can vary across validators. -In summary, the GenVM plays a crucial role in enabling GenLayer's unique features, bridging the gap between traditional smart contracts and AI-powered, web-connected Intelligent Contracts. +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 42, "rankSpacing": 50, "htmlLabels": true}}}%% +flowchart TD + Call(["Intelligent Contract call"]) --> Deterministic["Deterministic execution"] + Deterministic --> Block{"Enter a
non-deterministic block?"} + Block -->|"no"| Receipt(["Execution receipt"]) -## Key Features That Make the GenVM Different + subgraph Isolated["Isolated GenVM instance"] + direction LR + Sandbox["Non-deterministic code"] --> Host["Web or LLM
host function"] --> Result["Candidate output or
validator decision"] + end -Unlike traditional blockchain virtual machines such as Ethereum Virtual Machine (EVM), the GenVM has some advanced features. + Block -->|"yes"| Sandbox + Result -->|"return value only"| Deterministic -- **Integration with LLMs**: the GenVM facilitates seamless interaction between Intelligent Contracts and Large Language Models -- **Web access**: the GenVM provides access to the Internet -- **User friendliness**: Intelligent Contracts can be written in Python, which makes the learning curve much more shallow + classDef boundary fill:#F7F8FC,stroke:#8B95A7,color:#202536,stroke-width:1.5px; + classDef deterministic fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef nondeterministic fill:#EAF7FF,stroke:#2686C4,color:#113F59,stroke-width:2px; + classDef output fill:#E9F8F0,stroke:#23966B,color:#123F30,stroke-width:2px; + class Call boundary; + class Deterministic,Block deterministic; + class Sandbox,Host,Result nondeterministic; + class Receipt output; + style Isolated fill:#F5FBFF,stroke:#A8D7F2,stroke-width:1px + linkStyle default stroke:#7C879C,stroke-width:1.8px; +``` -## How the GenVM Works +The top-level contract path must be deterministic. A non-deterministic block runs in a separate VM instance so that its transient memory and side effects cannot leak directly into deterministic state. Only the block's returned value crosses the boundary. -1. **Contract Deployment**: When an Intelligent Contract is deployed, the GenVM compiles and executes the contract code. +In leader mode, the block produces the candidate value used by the transaction. In validator mode, it evaluates the leader's value and returns whether it is acceptable. Consensus, not GenVM alone, decides whether the receipt is accepted. -2. **Transaction Processing**: As transactions are submitted to the network, the GenVM executes the relevant contract functions and produces the contract's next state. +## Runners and languages -## Developer Considerations +GenVM executes WebAssembly contracts through **runners**. A runner packages the language runtime or other support code a contract needs and identifies that package by a human-readable name and content hash. Pinning the runner makes the execution environment explicit and reproducible across nodes. -When developing Intelligent Contracts for the GenVM: +The standard developer experience uses Python on a CPython WebAssembly runner. The runtime boundary is WebAssembly/WASI, so the architecture can support other compatible runners and compiled languages as they become available. -- Utilize Python's robust libraries and features -- Consider potential non-deterministic outcomes when integrating LLMs -- Implement proper error handling for web data access -- Optimize code for efficient execution within the rollup environment +## Security boundary + +GenVM constrains contract capabilities through its WebAssembly runtime and host interface. Intelligent Contracts do not receive unrestricted access to the validator machine. Web and LLM functions are available through the non-deterministic interface, where their output is subject to the contract's [equivalence rule](/understand-genlayer-protocol/core-concepts/optimistic-democracy/equivalence-principle). + +For code and API details, see [your first Intelligent Contract](/developers/intelligent-contracts/first-contract) and [non-determinism](/developers/intelligent-contracts/features/non-determinism). diff --git a/pages/understand-genlayer-protocol/core-concepts/large-language-model-llm-integration.mdx b/pages/understand-genlayer-protocol/core-concepts/large-language-model-llm-integration.mdx index 4fa6f9a2..44459026 100644 --- a/pages/understand-genlayer-protocol/core-concepts/large-language-model-llm-integration.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/large-language-model-llm-integration.mdx @@ -1,27 +1,30 @@ --- -description: "Large Language Model integration in GenLayer lets Intelligent Contracts use LLMs for natural language decisions." +description: "Learn how Intelligent Contracts use LLMs and how validators assess model-generated results." --- -# Large Language Model (LLM) Integration +# LLM integration -Large Language Model (LLM) integration in GenLayer lets Intelligent Contracts interact directly with LLMs for natural language processing and context-aware decision-making within blockchain applications. +Intelligent Contracts can use large language models (LLMs) inside non-deterministic blocks. This enables decisions based on natural-language instructions, unstructured evidence, text classification, extraction, and multimodal inputs. -## Overview +An LLM response does not become trusted state merely because a model returned it. The leader proposes a result, and the selected validators apply the contract's validation logic before consensus can accept the transaction. -Intelligent Contracts in GenLayer can interact directly with Large Language Models (LLMs), enabling natural language processing and more complex decision-making capabilities within blockchain applications. +## Model diversity and equivalence -## Key Features +Validators can use different supported models or providers. Their raw wording may differ while their conclusions remain equivalent. Contracts should therefore define the properties an acceptable response must satisfy instead of depending on exact prose unless exact equality is intentional. -- **Natural Language Understanding**: Contracts can process and interpret instructions written in natural language. -- **Dynamic Decision Making**: Utilizing LLMs allows contracts to make context-aware decisions based on complex inputs. +Common patterns include: -## Implementation +- require JSON with a fixed schema, then check its fields; +- independently repeat a classification and compare the label; +- ask validators whether the proposal satisfies explicit natural-language criteria; or +- combine objective checks with an LLM judgment for the remaining subjective question. -1. **LLM Providers**: Validators are configured with LLM providers (e.g., OpenAI, Ollama) to process LLM requests. -2. **Equivalence Principle**: LLM outputs are validated using the Equivalence Principle to ensure consensus among validators. -3. **Prompt Design**: Developers craft prompts to interact effectively with LLMs, specifying expected formats and constraints. +## Design considerations -## Considerations +- Treat prompts and retrieved content as untrusted input. +- Keep prompts specific and define the evidence and criteria validators should use. +- Request structured output where possible. +- Handle timeouts, provider errors, and malformed responses. +- Avoid making the validation rule a paraphrase of “agree with the leader.” -- **Cost and Performance**: LLM interactions may incur additional computational costs and latency. -- **Security**: Care must be taken to prevent prompt injections and ensure the reliability of LLM responses. \ No newline at end of file +See [prompt and data techniques](/developers/intelligent-contracts/crafting-prompts) and [non-determinism](/developers/intelligent-contracts/features/non-determinism) for current contract APIs. diff --git a/pages/understand-genlayer-protocol/core-concepts/non-deterministic-operations-handling.mdx b/pages/understand-genlayer-protocol/core-concepts/non-deterministic-operations-handling.mdx index 04905bda..708c9329 100644 --- a/pages/understand-genlayer-protocol/core-concepts/non-deterministic-operations-handling.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/non-deterministic-operations-handling.mdx @@ -1,26 +1,34 @@ --- -description: "Non-deterministic operations handling in GenLayer explains how Intelligent Contracts use equivalence and consensus for variable outputs." +description: "Learn how GenLayer contains variable web and LLM outputs and reaches consensus on their meaning." --- -# Non-Deterministic Operations Handling +# Non-deterministic operations -Non-deterministic operations handling in GenLayer is the process of maintaining network consensus when Intelligent Contracts produce variable results from actions such as interacting with Large Language Models (LLMs) or accessing web data. GenLayer addresses this variability through the Equivalence Principle, where validators assess whether different outputs are equivalent based on predefined criteria, and Optimistic Democracy, which supports provisional transaction acceptance with an appeals process. +A non-deterministic operation can return different raw output when two validators run it. LLM responses, live web content, time-sensitive APIs, and rendered pages are common examples. -## Overview +GenLayer does not require these outputs to become identical. It contains the variability in a non-deterministic block, then asks validators to judge the leader's proposed output under a rule defined by the Intelligent Contract. -GenLayer extends traditional smart contracts by allowing Intelligent Contracts to perform non-deterministic operations, such as interacting with Large Language Models (LLMs) and accessing web data. Handling the variability inherent in these operations is crucial for maintaining consensus across the network. +## Leader and validator paths -## Challenges +Each non-deterministic block has two logical paths: -- **Variability of Outputs**: Non-deterministic operations can produce different outputs when executed by different validators. -- **Consensus Difficulty**: Achieving consensus on varying outputs requires specialized mechanisms. +- The **leader function** obtains or produces a candidate output. +- The **validator function** receives that output and decides whether it is acceptable. -## Solutions in GenLayer +The validator can reproduce the operation and compare results, inspect the proposed output against objective constraints, or use another LLM judgment. The best choice depends on what a correct result means for the application. -- **Equivalence Principle**: Validators assess whether different outputs are equivalent based on predefined criteria, allowing for consensus despite variability. -- **Optimistic Democracy**: The consensus mechanism accommodates non-deterministic operations by allowing provisional acceptance of transactions and providing an appeals process. +## What remains deterministic -## Developer Considerations +Code outside the non-deterministic block must produce the same result from the same inputs and accepted block outputs. In particular: -- **Defining Equivalence Criteria**: Developers must specify what constitutes equivalent outputs in their Intelligent Contracts. -- **Testing and Validation**: Thorough testing is essential to ensure that non-deterministic operations behave as expected in the consensus process. \ No newline at end of file +- contract state is read and written on the deterministic path; +- validators must reproduce deterministic computation exactly; and +- only a returned value crosses from a non-deterministic block into the surrounding execution. + +If validators detect a provable mismatch in deterministic execution, they can report a deterministic violation. That is different from legitimately disagreeing about a subjective output. + +## Designing for consensus + +Use the narrowest validation rule that captures the application's real requirement. Prefer structured outputs and check objective properties before asking an LLM for a qualitative judgment. Account for unavailable sources, timeouts, malformed data, and adversarial content. + +See the [Equivalence Principle](/understand-genlayer-protocol/core-concepts/optimistic-democracy/equivalence-principle) for the conceptual model and [implement non-determinism](/developers/intelligent-contracts/features/non-determinism) for current APIs and code restrictions. diff --git a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy.mdx b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy.mdx index d81a1c0c..c58c6421 100644 --- a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy.mdx @@ -1,37 +1,60 @@ --- -description: "Optimistic Democracy explains GenLayer consensus for validating Intelligent Contract transactions and appeals." +description: "Optimistic Democracy coordinates leader proposals, validator votes, appeals, and finality for Intelligent Contracts." --- -import { Callout } from 'nextra-theme-docs' # Optimistic Democracy -Optimistic Democracy is GenLayer's consensus method for validating transactions and operations of Intelligent Contracts. It is designed to handle unpredictable outcomes from transactions involving web data or AI models, helping keep the network reliable and secure. +Optimistic Democracy is GenLayer's protocol for deciding Intelligent Contract outcomes. A randomly selected leader proposes an execution result, a stake-weighted committee evaluates it, and the decision becomes final unless someone funds a valid appeal. -## Key Components +It is **optimistic** because the protocol starts with a small committee and finalizes an uncontested result after an appeal window. It is **democratic** because a majority of independently selected validators decides whether the proposal is acceptable. -- **Validators:** Participants who stake tokens to earn the right to validate transactions. They play a crucial role in both the initial validation and any appeals process if needed. -- **Leader Selection:** A process that randomly picks one validator to propose the outcome for each transaction, ensuring fairness and reducing potential biases. +## One consensus round -## How It Works +```mermaid +%%{init: {"sequence": {"useMaxWidth": true, "diagramMarginX": 32, "actorMargin": 56, "messageMargin": 34, "mirrorActors": false}}}%% +sequenceDiagram + autonumber + participant C as Consensus contracts + participant L as Leader + participant V as Validator committee + C->>L: Assign transaction + Note over L,V: Execute independently in GenVM + L->>L: Run leader and validator paths + L->>C: Propose receipt + V->>V: Evaluate proposal in GenVM + par Commit before seeing other votes + L->>C: Commit encrypted vote + and + V->>C: Commit encrypted votes + end + L->>C: Reveal execution data and key + V->>C: Reveal votes + C->>C: Calculate majority and record decision +``` -Optimistic Democracy relies on a mix of trust and verification to ensure transaction integrity: +The committee checks two kinds of work: -![](/optimistic-democracy-concept.png) +- Deterministic execution must reproduce the leader's proposed state transition exactly. +- Non-deterministic outputs must satisfy the contract's [Equivalence Principle](/understand-genlayer-protocol/core-concepts/optimistic-democracy/equivalence-principle). -1. **Initial Validation:** When a transaction is submitted, a small group of randomly selected validators checks its validity. One is chosen as the leader. The leader executes the transaction, and the other validators assess the leader's proposal using the Equivalence Principle. +The commit-reveal process hides votes until commitments are fixed. A separate leader-revealing phase exposes the leader's execution data before the remaining validators reveal. -2. **Majority Consensus:** If most validators accept the leader's proposal, the transaction is provisionally accepted. However, this decision is not final yet, allowing for possible appeals during a limited window of time, known as the **Finality Window**. +## Possible decisions - - If any validator fails to vote within the specified timeframe, they are replaced, and a new validator is selected to cast a vote. - +- **Accepted**: The committee reached the required majority on the proposed outcome. +- **ValidatorsTimeout**: A majority reported that validation could not finish within its execution allowance. +- **LeaderTimeout**: The leader reported that it could not produce a proposal within its allowance. +- **Undetermined**: The round could not reach consensus and no funded rotation remained. -3. **Initiating an Appeal:** If a participant disagrees with the initial validation (if it's incorrect or fraudulent), they can appeal during the Finality Window. They must submit a request and provide a bond. After the appeal starts, a new group of validators joins the original ones. This group first votes on whether the transaction should be re-evaluated. If they agree, a new leader is chosen to reassess the transaction, and all validators then review this new evaluation. +Accepted describes agreement, not whether the contract returned without an error. A receipt that contains a contract error can still be Accepted when validators agree that it is the correct result. -4. **Appeal Evaluation:** The new leader re-evaluates the transaction, while the other validators assess the leader's proposal using the Equivalence Principle. This step involves more validators, increasing the chances of an accurate decision. +## Appeals scale review -5. **Escalating Appeals:** If the appealing party is still not satisfied, the process can escalate, with each round involving more validators. Each round doubles the number of validators. A new leader is only chosen if the transaction is overturned. +Anyone can challenge an eligible decision during its appeal window by posting the required bond. The protocol distinguishes: -6. **Final Decision:** The appeals process continues until a majority consensus is reached or until all validators have participated. The final decision is recorded, and the transaction's state is updated accordingly. If the appealing party is correct, they receive a reward for their efforts, while incorrect appellants lose their bond. +- a **validator appeal**, which asks fresh validators to re-evaluate the existing proposal; and +- a **leader appeal**, which starts another proposal round after an Undetermined or LeaderTimeout result. +Further appeals use larger committees and exclude validators already consumed by the relevant appeal selection. This increases the cost of sustaining an incorrect result while avoiding the expense of involving the whole active set in routine transactions. +Read [appeals](/understand-genlayer-protocol/core-concepts/optimistic-democracy/appeal-process) and [finality](/understand-genlayer-protocol/core-concepts/optimistic-democracy/finality) for the next steps in the lifecycle. diff --git a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/_meta.json b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/_meta.json index 8c046227..d757be54 100644 --- a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/_meta.json +++ b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/_meta.json @@ -1,8 +1,8 @@ { - "equivalence-principle": "", - "appeal-process": "", - "finality": "", - "staking": "", - "slashing": "", - "unstaking": "" - } \ No newline at end of file + "equivalence-principle": "Equivalence Principle", + "appeal-process": "Appeals", + "finality": "Finality", + "staking": "Staking", + "slashing": "Slashing", + "unstaking": "Unstaking" +} diff --git a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/appeal-process.mdx b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/appeal-process.mdx index 45791218..2586afd6 100644 --- a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/appeal-process.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/appeal-process.mdx @@ -1,21 +1,51 @@ --- -description: "Appeals Process explains how GenLayer challenges validation decisions, escalates validator review, and handles appeal bonds and gas costs." +description: "Learn how validator appeals and leader appeals challenge GenLayer consensus decisions." --- -# Appeals Process +# Appeals -The appeals process in GenLayer is the Optimistic Democracy mechanism for correcting errors or disagreements in the validation of Intelligent Contracts. Participants can challenge an initial validation decision so non-deterministic transactions are reassessed, helping preserve the platform's robustness and fairness. +An appeal challenges a decided Intelligent Contract transaction before finalization. Anyone can appeal an eligible transaction during its appeal window by posting the bond quoted by the consensus contracts. -## How It Works +GenLayer has two appeal paths because a disputed committee decision and a round that failed to produce a decision require different remedies. -- **Initiating an Appeal**: Participants can appeal the initial decision by submitting a request and a required bond during the Finality Window. A new set of validators is then added to the original group to reassess the transaction. +## Validator appeals -- **Appeal Evaluation**: The new validators first review the existing transaction to decide if it needs to be overturned. If they agree it should be re-evaluated, a new leader re-evaluates the transaction. The combined group of original and new validators then review this new evaluation to ensure accuracy. +A validator appeal challenges an **Accepted** or **ValidatorsTimeout** decision. -- **Escalating Appeals**: If unresolved, the appeal can escalate, doubling the number of validators each round until a majority consensus is reached or all validators have participated. +1. The protocol selects an entirely fresh appeal committee that did not participate in earlier rounds for the transaction. +2. The fresh validators evaluate the original leader's proposal. +3. They commit and reveal their votes in `AppealCommitting` and `AppealRevealing`. +4. If their majority differs from the original majority, the appeal succeeds and the transaction returns for recomputation. If the majorities match, the appeal fails. -Once a consensus is reached, the final decision is recorded, and the transaction's state is updated. Correct appellants receive a reward, while those who are incorrect may lose their bond. +For a normal committee of size *N*, the appeal committee has *N + 2* validators. An appeal round does not choose a new leader or produce a new proposal; it rechecks the existing proposal. -## Gas Costs for Appeals +## Leader appeals -The gas costs for an appeal can be covered by the original user, the appellant, or any third party. When submitting a transaction, users can include an optional tip to cover potential appeal costs. If insufficient gas is provided, the appeal may fail to be processed, but any party can supply additional gas to ensure the appeal proceeds. +A leader appeal challenges an **Undetermined** or **LeaderTimeout** decision. It automatically starts a new proposal round instead of asking an appeal committee to vote on the old result. + +- After **Undetermined**, the protocol drops the previous leader, carries forward the remaining committee members, adds fresh validators, and uses the larger normal-round committee size. +- After **LeaderTimeout**, the protocol keeps the committee, removes the timed-out leader, and selects a new leader from the remaining members. + +The new round's outcome determines whether the appeal was economically successful. + +## Committee growth + +Normal execution and validator-appeal committees follow interleaved growth schedules. The first normal round currently uses 5 validators, its validator appeal uses 7 fresh validators, and the next expanded normal round uses 11. Later rounds continue growing. These values are protocol parameters and can change through a protocol upgrade. + +## Bonds and incentives + +The appeal bond covers the additional validation work and discourages frivolous challenges. The consensus contracts calculate the required amount from the appeal type and round size. + +- A successful appellant recovers the bond and receives the configured reward. +- A failed validator appeal forfeits its bond to the majority-aligned validators in that appeal round. +- Leader-appeal bond handling depends on the prior status and the result of the new round. + +Clients should request the current bond quote instead of hardcoding an amount. + +## Appeal windows and dependent transactions + +The appeal-window duration and its reduction after an unsuccessful validator appeal are governance-managed parameters. The window pauses while a validator appeal is voting. A successful appeal gives the recomputed transaction a fresh window. + +Because transactions for one Intelligent Contract depend on earlier state, a successful appeal can return later non-finalized transactions in that contract's queues for recomputation. Appeals on those dependent transactions are canceled and their bonds refunded when necessary. + +Deterministic-violation tribunals are separate. They decide penalties for provable execution fraud but do not change the transaction outcome. See [slashing](/understand-genlayer-protocol/core-concepts/optimistic-democracy/slashing). diff --git a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/equivalence-principle.mdx b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/equivalence-principle.mdx index f305b3ec..a6a0e880 100644 --- a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/equivalence-principle.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/equivalence-principle.mdx @@ -1,54 +1,71 @@ --- -description: "The Equivalence Principle is how GenLayer validators reach consensus on non-deterministic outputs such as LLM responses and live web data." +description: "The Equivalence Principle lets validators accept non-identical outputs when they satisfy an Intelligent Contract's validation rule." --- -# Equivalence Principle Mechanism +# Equivalence Principle -The Equivalence Principle mechanism is a cornerstone in ensuring that Intelligent Contracts function consistently across various validators when handling non-deterministic outputs like responses from Large Language Models (LLMs) or data retrieved through web browsing. It plays a crucial role in how validators assess and agree on the outcomes proposed by the Leader. +The Equivalence Principle is the rule an Intelligent Contract uses to decide whether a leader's non-deterministic output is acceptable. It allows validators to agree on meaning or required properties even when their raw LLM or web results are not byte-for-byte identical. -The Equivalence Principle protects the network from manipulations or errors by ensuring that only suitable, equivalent outcomes influence the blockchain state. +The principle is implemented as contract code. It is not a network-wide similarity threshold, and it does not mean that validators trust the leader. -## Key Features of the Equivalence Principle +## Leader and validator responsibilities -The Equivalence Principle is fundamental to how Intelligent Contracts operate, ensuring they work reliably across different network validators. +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 46, "rankSpacing": 48, "htmlLabels": true}}}%% +flowchart TB + L["Leader function"] -->|"candidate output"| P["Proposed receipt"] -- **Consistency in Decentralized Outputs:** The Equivalence Principle allows outputs from various sources, such as LLMs or web data, to be different yet still considered valid as long as they meet predefined standards. This is essential to maintain fairness and uniform decision-making across the blockchain, despite the natural differences in AI-generated responses or web-sourced information. + V1["Validator 1
independent check"] + V2["Validator 2
independent check"] + V3["Validator 3
independent check"] -- **Security Enhancement:** To protect the integrity of transactions, the Equivalence Principle requires that all validators check each other’s work. This mutual verification helps prevent errors and manipulation, ensuring that only accurate and agreed-upon data affects the blockchain. + P --> V1 + P --> V2 + P --> V3 + V1 --> M{"Majority
accepts?"} + V2 --> M + V3 --> M + M -->|"yes"| A(["Accept proposal"]) + M -->|"no"| R(["Reject or rotate"]) -- **Output Validation Flexibility:** Intelligent Contracts often need to handle complex and varied data. This part of the principle allows developers to set specific rules for what counts as "equivalent" or acceptable outputs. This flexibility helps developers tailor the validation process to suit different needs, optimizing either for accuracy or efficiency depending on the contract's requirements. + classDef leader fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef validator fill:#EAF7FF,stroke:#2686C4,color:#113F59,stroke-width:2px; + classDef success fill:#E9F8F0,stroke:#23966B,color:#123F30,stroke-width:2px; + classDef challenge fill:#FFF4E5,stroke:#D58A16,color:#583705,stroke-width:2px; + class L,P,M leader; + class V1,V2,V3 validator; + class A success; + class R challenge; + linkStyle default stroke:#7C879C,stroke-width:1.8px; +``` -## Types of Equivalence Principles +The leader function produces the value that the surrounding deterministic code can use. Each validator function receives that value and independently returns an accept or reject decision. Intermediate validator results do not automatically become contract state. -Validators work to reach a consensus on whether the result set by the Leader is acceptable, which might involve direct comparison or qualitative evaluation, depending on the contract’s design. If the validators do not reach a consensus due to differing data interpretations or an error in data processing, the result might be challenged or an appeal process might be initiated. +## Validation patterns -### Comparative Equivalence Principle +### Strict equality -In the Comparative Equivalence Principle, both the Leader and the validators perform identical tasks and then directly compare their respective results with the predefined criteria in the Equivalence Principle to ensure consistency and accuracy. This method uses an acceptable margin of error to handle slight variations in results between validators and is suitable for quantifiable outputs. However, since multiple validators perform the same tasks as the Leader, it increases computational demands and associated costs. +Use strict equality when validators can normalize an operation to exactly the same bytes. Examples include stable structured data with canonical serialization. Strict equality is usually unsuitable for open-ended LLM responses or time-varying data. -For example, if an Intelligent Contract is tasked with calculating the average rating of a product based on user reviews, the Equivalence Principle specifies that the average ratings should not differ by more than 0.1 points. Here's how it works: +### Independent comparison -1. **Leader Calculation**: The Leader validator calculates the average rating from the user reviews and arrives at a rating of 4.5. -2. **Validators' Calculations**: Each validator independently calculates the average rating using the same set of user reviews. Suppose one validator calculates an average rating of 4.6. -3. **Comparison**: The validators compare their calculated average (4.6) with the Leader's average (4.5). According to the Equivalence Principle, the ratings should not differ by more than 0.1 points. -4. **Decision**: Since the difference (0.1) is within the acceptable margin of error, the validators accept the Leader's result as valid. +The validator repeats the task and compares the decision-bearing fields. It can require exact labels, allow a numeric tolerance, or use an LLM to compare two complex outputs against explicit criteria. -### Non-Comparative Equivalence Principle +### Independent assessment -In contrast, the Non-Comparative Equivalence Principle does not require validators to replicate the Leader's output, which makes the validation process faster and less costly. Instead, validators assess the accuracy of the Leader’s result against the criteria defined in the Equivalence Principle. This method is particularly useful for qualitative outputs like text summaries. +The validator evaluates the leader's output directly against the original evidence and criteria without producing a second candidate answer. This can reduce duplicated work, but the validator must still consult independent evidence. Checking only that the leader returned valid JSON or an allowed enum does not verify the answer. -For example, in an Intelligent Contract designed to summarize news articles, the process works as follows: +### Custom validation -1. **Leader Summary**: The Leader validator generates a summary of a news article. -2. **Evaluation Criteria**: The Equivalence Principle defines criteria for an acceptable summary, such as accuracy, relevance, and length. -3. **Validators' Assessment**: Instead of generating their own summaries, validators review the Leader’s summary and check if it meets the predefined criteria. - - **Accuracy**: Does the summary accurately reflect the main points of the article? - - **Relevance**: Is the summary relevant to the content of the article? - - **Length**: Is the summary within the acceptable length? -4. **Decision**: If the Leader’s summary meets all the criteria, it is accepted by the validators. +Most contracts use a custom leader/validator pair because it can combine objective checks, source retrieval, tolerances, and qualitative judgment. Convenience wrappers exist for common strict, comparative, and non-comparative cases. -## Key Points for Developers +## Design principles -- **Setting Equivalence Criteria:** Developers must define what 'equivalent' means for each non-deterministic operation in their Intelligent Contract. This guideline helps validators judge if different outcomes are close enough to be treated as the same. +- Define what must agree and what may vary. +- Compare structured decision fields instead of incidental prose. +- Give validators the same source evidence and explicit criteria. +- Reject malformed outputs before applying subjective checks. +- Define behavior for source failures, model errors, and timeouts. +- Keep side effects outside the non-deterministic block so state changes use only the accepted value. -- **Ensuring Contract Reliability:** By clearly defining equivalence, developers help maintain the reliability and predictability of their contracts, even when those contracts interact with the unpredictable web or complex AI models. +For current APIs, security guidance, and examples, use the canonical developer guide: [Implement the Equivalence Principle](/developers/intelligent-contracts/equivalence-principle). diff --git a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/finality.mdx b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/finality.mdx index b53dcbd2..a78b61e2 100644 --- a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/finality.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/finality.mdx @@ -1,50 +1,51 @@ --- -description: "Finality in GenLayer explains when transactions become unchangeable, how Finality Windows enable appeals, and when fast finality applies." +description: "Learn when a GenLayer Intelligent Contract transaction becomes final and how the appeal window affects application state." --- # Finality -Finality in GenLayer is the state in which a transaction is settled, unchangeable, and no longer appealable. Once a transaction achieves finality, it cannot be appealed or altered, giving participants certainty that the outcome is definitive. Finality is especially important for applications that depend on accurate settled outcomes, such as financial contracts or decentralized autonomous organizations (DAOs). +An Intelligent Contract transaction is final when the consensus decision can no longer be appealed and the protocol has moved it to `Finalized`. Until then, an accepted result is provisional. -## Finality Window +## Decision, appeal window, and finalization -The Finality Window is a time frame during which a transaction can be challenged or appealed before it becomes final. This window serves several purposes: +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 42, "rankSpacing": 48, "htmlLabels": true}}}%% +flowchart TB + D["Decided outcome"] --> W["Appeal window"] + W -->|"window elapses"| R["Ready to finalize"] --> F(["Finalized"]) + W -->|"valid appeal"| A["Appeal processing"] + A -->|"confirmed or recomputed"| W -1. **Appeals**: During the Finality Window, any participant can appeal a transaction if they believe the validation was incorrect. This allows for a process of checks and balances, ensuring that non-deterministic transactions are evaluated properly. + classDef phase fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef challenge fill:#FFF4E5,stroke:#D58A16,color:#583705,stroke-width:2px; + classDef success fill:#E9F8F0,stroke:#23966B,color:#123F30,stroke-width:2px; + class D,W phase; + class A challenge; + class R,F success; + linkStyle default stroke:#7C879C,stroke-width:1.8px; +``` -2. **Re-computation**: If a transaction is appealed, the system can re-evaluate the transaction with a new set of validators. The Finality Window provides the time necessary for this process to occur. +The appeal window starts after a decided outcome such as Accepted, Undetermined, ValidatorsTimeout, or LeaderTimeout. Its duration is governed by the protocol configuration. Applications should read the effective transaction status rather than assume a fixed number of seconds. -3. **Security**: The window also acts as a security feature, allowing the network to correct potential errors or malicious activity before finalizing a transaction. +After the window expires, the transaction can report `ReadyToFinalize`. Anyone can then submit the onchain finalization action. `ReadyToFinalize` means the deadline has passed; `Finalized` means the state transition has been recorded. -import Image from 'next/image' +## Accepted is not final - +An Accepted receipt can influence the contract's provisional execution chain, but a successful appeal can require it and later non-finalized transactions for the same Intelligent Contract to be recomputed. Applications that need irreversible settlement should wait for `Finalized`. -## Deterministic vs. Non-Deterministic Transactions +Accepted also does not mean “execution succeeded.” It means the committee agreed on the receipt. The agreed receipt can contain a user error or a GenVM error. -In GenLayer, Intelligent Contracts are classified as either deterministic or non-deterministic. +## Messages at different stages -### Deterministic Contracts -These contracts have a shorter Finality Window because their validation process is straightforward and not subject to appeals. However, it is essential that all interactions with the contract remain deterministic to maintain this efficiency. +An Intelligent Contract can schedule messages for acceptance or finalization. On-acceptance messages are emitted when the transaction is accepted and are not revoked by a later appeal. Use them only for effects that are safe before finality. On-finalization messages are emitted only after the transaction finalizes. -### Non-Deterministic Contracts -Non-deterministic contracts involve Large Language Model (LLM) calls or web data retrieval, which introduce variability in their outcomes. These contracts require a longer Finality Window to account for potential appeals and re-computation. +See [messages](/developers/intelligent-contracts/features/messages) for developer guidance. -import { Callout } from 'nextra-theme-docs' +## Two layers of confirmation - - If a specific transaction within the contract is deterministic but interacts with a non-deterministic part of the contract, it will be treated as non-deterministic. This ensures that any appeals or re-computations of previous transactions are handled consistently, maintaining the integrity of the contract's overall state. - +The EVM transaction that submitted an Intelligent Contract call can be included on GenLayer Chain before the Intelligent Contract transaction finishes consensus. Therefore: +- an EVM receipt confirms that the submission was included; and +- the GenLayer transaction status confirms the Intelligent Contract outcome. -## Fast Finality - -For scenarios requiring immediate finality, such as emergency decisions in a DAO, it is possible to pay for all validators to validate the transaction immediately. This approach, though more costly, allows for fast finality, bypassing the typical Finality Window. - - - Fast finality only works if there are no previous non-deterministic transactions still within their Finality Window. Even if your transaction is considered final, if a previous transaction is reverted, your transaction will have to be recomputed as it might depend on the same state. - - -## Appealability and Gas - -When submitting a transaction, users can include additional gas to cover potential appeals. If a transaction lacks sufficient gas for appeals, third parties can supply additional gas during the Finality Window. Developers of Intelligent Contracts can also set minimum gas requirements for appealability, ensuring that critical transactions have adequate coverage. +Use [`gen_getTransactionStatus`](/api-references/genlayer-node/gen/gen_getTransactionStatus) for lightweight polling or [`gen_getTransactionReceipt`](/api-references/genlayer-node/gen/gen_getTransactionReceipt) for the full consensus receipt. diff --git a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/slashing.mdx b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/slashing.mdx index 00737911..4482fa99 100644 --- a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/slashing.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/slashing.mdx @@ -1,29 +1,42 @@ --- -description: "Slashing in GenLayer penalizes validators for missed execution or appeal windows by reducing stake after finality." +description: "Learn how GenLayer handles validator idleness, failure to reveal, deterministic violations, quarantine, bans, and stake penalties." --- -# Slashing in GenLayer +# Slashing and validator penalties -Slashing in GenLayer is the validator penalty mechanism that reduces stake for behavior detrimental to the network, such as missing required execution or appeal windows. Slashing helps validators act honestly and effectively, maintains the integrity of the platform and the Intelligent Contracts executed within it, and aligns validator incentives with the network and its users. +GenLayer uses several penalties to protect liveness and punish provable protocol violations. Not every incorrect or minority vote is slashable, and not every penalty immediately removes stake. -## Slashing Process +## Penalty types -1. **Violation Detection**: The network identifies a violation, such as missing an execution window. +| Behavior | Protocol response | +| --- | --- | +| Missed activation, proposal, commit, or reveal duty | Replace or rotate the idle participant; record idleness where applicable. | +| Repeated idleness or failure to reveal | Add epoch strikes and ban the validator after the configured threshold. | +| Failure to reveal a committed vote | Record a percentage-based stake slash and a strike. | +| Vote that loses after an appeal | Forfeit the applicable reward or receive a negative fee adjustment; this alone is not a deterministic-violation slash. | +| Provable deterministic execution violation | Quarantine the accused validator and open a tribunal that can impose a larger slash or clear the quarantine. | -2. **Slash Calculation**: The amount to be slashed is calculated based on the specific violation and platform rules. +## Bans and quarantine -3. **Stake Reduction**: The slashed amount is deducted from the validator's stake. +A **ban** temporarily excludes a validator after it accumulates the configured number of idleness strikes. Current defaults use three strikes in an epoch and exclude the validator for the current and following epoch. -4. **Finality**: The slashing becomes final after the Finality Window closes, ensuring that the validator's balance is finalized and accounts for any potential appeals. +A **quarantine** immediately excludes a validator selected for a deterministic-violation tribunal. The tribunal uses the active validator network to decide punishment. It runs separately from the transaction's outcome: the transaction continues through rotation or its ordinary appeal path. -## When Slashing Occurs +## Current slash parameters -Validators in GenLayer can be slashed for several reasons: +Current protocol parameters include: -1. **Missing Transaction Execution Window**: Validators are expected to execute transactions within a specified time frame. If a validator misses this window, they are penalized, ensuring that validators remain active and responsive. +- 1% of stake for validator idleness or failure to reveal; +- 5% for a leader found responsible for a deterministic violation; +- 1% for other minority validators found responsible in that tribunal; and +- a 10% per-epoch cap on deterministic-violation slashes. -2. **Missing Appeal Execution Window**: During the appeals process, validators must respond within a set time frame. If they fail to do so, they are slashed, which motivates validators to participate in the appeals process. +Percentage-based slashes currently draw 80% of the penalty from validator self-stake and 20% from delegated stake. These values are upgradeable protocol parameters and can differ by deployment. -### Amount Slashed +## Delayed, permissionless enforcement -The amount slashed varies based on the severity of the violation and the specific rules set by the GenLayer platform. The slashing amount is designed to be substantial enough to deter malicious or negligent behavior while not being excessively punitive for honest mistakes. +Slashable events record a pending penalty. Under the current implementation, a two-epoch delay gives governance time to correct an erroneous slash before it can be enforced. The stake deduction is then applied lazily when someone calls `validatorPrime()`. + +Priming is permissionless so a validator cannot reliably avoid enforcement by refusing to process itself. The caller currently receives 1% of an applied slash as an execution incentive; the remainder enters the protocol's slashed-token accounting. + +For operational monitoring and current configuration, see the [validator setup guide](/validators/setup-guide). diff --git a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/staking.mdx b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/staking.mdx index 14ea766e..43aa44fa 100644 --- a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/staking.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/staking.mdx @@ -1,360 +1,76 @@ --- -description: "Staking in GenLayer explains validator and delegator token locking, network consensus participation, and transaction processing." +description: "Learn how validator self-stake, delegation, selection weight, epochs, and validator keys work in GenLayer." --- import { Callout } from "nextra-theme-docs"; -# Staking in GenLayer +# Staking -Staking in GenLayer is the process where validators lock a specified amount of tokens on the rollup layer to participate in the network. This commitment supports GenLayer's consensus mechanism and enables validators to process transactions and help manage the network. +Validators stake GEN to become eligible for consensus duties. Other token holders can delegate GEN to a validator without operating a node. Stake secures the protocol, influences validator selection, earns rewards, and remains exposed to protocol penalties. -## Validators vs Delegators +## Validators and delegators -| Role | Minimum Stake | Infrastructure | Rewards | -|------|--------------|----------------|---------| -| **Validator** | 42,000 GEN | Must run a node | 10% operational fee + stake rewards | -| **Delegator** | 42 GEN | None required | Passive stake rewards | +| Participant | Provides | Current minimum | Receives | +| --- | --- | ---: | --- | +| Validator owner | Self-stake and node operation | 42,000 GEN | Stake-pool rewards and validator-owner rewards | +| Delegator | Stake assigned to a validator | 42 GEN | A proportional share of that validator's stake-pool rewards | -**Validators** run the consensus infrastructure and are responsible for executing intelligent contracts and validating transactions. They receive a 10% operational fee from rewards before distribution. +Minimums and the maximum active-set size are governance-configurable. Check current network configuration before transacting. -**Delegators** stake their tokens with validators without running infrastructure. They earn passive rewards proportional to their stake, minus the validator's operational fee. +## Owner, operator, and ValidatorWallet -## How Staking Works - -- **Stake Deposit**: To become a validator on GenLayer, participants must deposit GEN tokens on the rollup layer. This deposit acts as a security bond and qualifies them to join the pool of active validators. - -- **Validator Participation**: Only a maximum of 1000 validators with the highest stakes can be part of the active validator set. Once staked, validators take on the responsibility of validating transactions and executing Intelligent Contracts. Their role is crucial for ensuring the network's reliability and achieving consensus on transaction outcomes. - -- **Delegated Proof of Stake (DPoS)**: GenLayer enhances accessibility and network security through a Delegated Proof of Stake system. This allows token holders who are not active validators themselves to delegate their tokens to trusted validators. By delegating their tokens, users increase the total stake of the validator and share in the rewards. Typically, the validator takes a configurable fee (around 10%), with the remaining rewards (90%) going to the delegating user. - -- **Earning Rewards**: Validators, and those who delegate their tokens to them, earn rewards for their contributions to validating transactions, paid in GEN tokens. These rewards are proportional to the amount of tokens staked and the transaction volume processed. - -- **Risk of Slashing**: Validators, and by extension their delegators, face the risk of having a portion of their staked tokens [slashed](/understand-genlayer-protocol/core-concepts/optimistic-democracy/slashing) if they fail to comply with network rules or if the validator supports fraudulent transactions. - -## Owner, Operator, and ValidatorWallet - -Every validator involves three distinct entities. Two of them are **keys** (regular externally owned accounts) and one is a **smart contract** — a distinction that matters when you plan key management: +A validator separates control of funds from day-to-day node operation. ```mermaid -graph LR - Owner["Owner key
(cold wallet, kept offline)"] - Operator["Operator key
(hot wallet, in the node keystore)"] - VW["ValidatorWallet
(smart contract, on-chain)
holds stake and rewards"] - - Owner -->|"owns: exit, claim,
change operator, set identity"| VW - Operator -->|"operates: propose receipts,
commit and reveal votes"| VW - VW -.->|"claimed funds
paid to owner"| Owner +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 48, "rankSpacing": 48, "htmlLabels": true}}}%% +flowchart TB + Owner["Owner key
funds and administration"] --> Wallet["ValidatorWallet
onchain identity"] + Operator["Operator key
consensus duties"] --> Wallet + Wallet --> Stake(["Stake and rewards"]) + + classDef key fill:#F7F8FC,stroke:#8B95A7,color:#202536,stroke-width:1.5px; + classDef identity fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef value fill:#E9F8F0,stroke:#23966B,color:#123F30,stroke-width:2px; + class Owner,Operator key; + class Wallet identity; + class Stake value; + linkStyle default stroke:#7C879C,stroke-width:1.8px; ``` -**ValidatorWallet** — a smart contract, not a key. It is deployed automatically when `validatorJoin()` is called and becomes the validator's on-chain identity: stake is accounted against its address, rewards accrue to it, and all consensus actions are executed through it. There is no private key for the ValidatorWallet; it is controlled entirely by the owner and operator keys. - -**Owner key** — the wallet that calls `validatorJoin()` (the `msg.sender`) becomes the owner. This is an external wallet that you create and safeguard yourself — **the node never generates, stores, or needs it, and it cannot be extracted from a validator server**. The owner controls everything related to funds and administration: - -- Exit stake (`validatorExit`) and claim rewards and withdrawals (`validatorClaim` — claimed funds are paid out to the owner address) -- Change the operator (`setOperator`) -- Set the validator's public identity (`setIdentity`) -- Hand over ownership to a new owner (`transferOwnership`) - -**Operator key** — the hot key the node uses for day-to-day consensus duties: activating transactions, proposing receipts, committing and revealing votes. This is the only key that lives on the validator server. It is created or imported with `genlayernode account new` / `account import` and referenced as `operatorAddress` in the node configuration. If no operator is passed to `validatorJoin()`, it defaults to the owner, but a separate operator is strongly recommended: if the server is compromised, the staked funds (controlled by the owner) remain safe. An operator address cannot be the zero address and cannot be reused by another validator. - - -Heard the terms "node key" or "validator key"? Both refer to the operator key — the node manages exactly one key. There is also no separate "rewards key": rewards accrue to the ValidatorWallet contract and are claimed by the owner. - - -### Which key does what - -| | Owner key | Operator key | ValidatorWallet | -|---|---|---|---| -| **What it is** | External wallet (EOA) | External wallet (EOA) | Smart contract (no key) | -| **Where it lives** | Cold wallet, offline | Node keystore on the server | On-chain | -| **Created by** | You, before joining | `genlayernode account new` or the CLI wizard | Automatically on `validatorJoin()` | -| **Used for** | Staking operations: join, deposit, exit, claim, change operator | Consensus operations: propose, commit, reveal | Holds stake and rewards; validator's on-chain identity | -| **Receives funds** | Yes — all claims pay out here | No (only needs gas for consensus transactions) | Stake and rewards accrue here until claimed | -| **If lost** | **Unrecoverable** — see below | Owner assigns a new operator | Not applicable | - -Topping up stake is the one exception to the owner-only rule: `validatorDeposit()` is permissionless, so any address can add stake to a validator. - -### Key rotation and loss scenarios - -**Losing the operator key is an inconvenience.** The owner can replace the operator at any time with `setOperator(newOperator)`. Generate a new key on the server (`genlayernode account new`), call `setOperator` from the owner wallet, and update `operatorAddress` in the node config. For planned handovers (for example, migrating to a new server or service provider) there is also a two-step flow — `initiateOperatorTransfer(newOperator)` followed by `completeOperatorTransfer()` after a safety delay (48 hours by default), cancellable in between with `cancelOperatorTransfer()`. See [Set Operator](/api-references/genlayer-cli/staking/staking/set-operator) for the CLI command and [backing up your operator key](/validators/setup-guide#backing-up-your-operator-key) to avoid the situation entirely. - -**Losing the owner key is unrecoverable.** Ownership can only be transferred by the current owner (`transferOwnership`); there is no admin override, no social recovery, and the operator key cannot stand in for it. Without the owner key you can no longer exit stake, claim rewards, or change the operator — the staked funds stay locked in the ValidatorWallet permanently. +- The **owner key** joins, deposits, exits, claims, changes the operator, and controls the validator identity. Keep it offline when practical. +- The **operator key** signs activations, proposals, commits, and reveals. It is the hot key configured on the node and can be replaced by the owner. +- The **ValidatorWallet** is a smart contract created when the validator joins. It is the validator's onchain identity and holds its stake accounting. It has no private key. -The node setup flow only ever creates the **operator** key. If you inherited a running validator from someone else, verify that you were also handed the **owner** wallet's private key or seed phrase — it is not on the server and cannot be derived from any of the node's keys. Treat it like the keys to the stake itself: keep it in cold storage, back it up, and document who holds it. + Losing the owner key can permanently prevent exits, claims, and operator changes. The node stores only the operator key; it cannot recover the owner key. -### How the pieces come together - -1. Create an owner wallet (cold) and an operator key on your server ([setup guide](/validators/setup-guide#understanding-validator-addresses)). -2. From the owner wallet, call `validatorJoin(operator)` with your stake. The ValidatorWallet contract is deployed and its address is returned — save it. -3. Configure the node with `validatorWalletAddress` and `operatorAddress`. The node signs consensus duties with the operator key; the owner wallet stays offline. -4. Rewards accrue to the ValidatorWallet. The owner exits and claims when needed (see [Unstaking and Withdrawing](#unstaking-and-withdrawing) below). - -## Epoch System - -The network operates in epochs (1 day): - -- **Epoch +2 Activation Rule**: All deposits become active 2 epochs after they are made -- Epoch finalization requires all transactions to be finalized -- Cannot advance to epoch N+1 until epoch N-1 is finalized -- Validators are "primed" via `validatorPrime()` each epoch (permissionless - anyone can call it) - -**Critical**: If `validatorPrime()` isn't called, the validator is excluded from the next epoch's selection. - -### Genesis Epoch 0 - -Epoch 0 is the **genesis bootstrapping period** with special rules designed to facilitate network launch. The normal staking rules are relaxed to allow rapid network bootstrapping. +## Selection weight -#### What is Epoch 0? +The protocol derives committee-selection weight from self-stake and delegated stake: -Epoch 0 is the **bootstrapping period** before the network becomes operational. During epoch 0: - -- **No transactions are processed** - the network is not yet active -- **No consensus occurs** - validators are not yet participating -- Stakes are registered and prepared for activation in epoch 2 - -**Important**: The network transitions directly from epoch 0 to epoch 2 (epoch 1 is skipped). Validators and delegators who stake in epoch 0 become active in epoch 2, but only if they meet the minimum stake requirements. - -#### Special Rules for Epoch 0 - -| Rule | Normal Epochs (2+) | Epoch 0 | -|------|-------------------|---------| -| Validator minimum stake | 42,000 GEN | No minimum to join | -| Delegator minimum stake | 42 GEN | No minimum to join | -| Activation delay | +2 epochs | Active in epoch 2 | -| validatorPrime required | Yes, each epoch | Not required | -| Share calculation | Based on existing ratio | 1:1 (shares = input) | -| Transaction processing | Yes | No (bootstrapping only) | - -**Activation requires meeting minimums**: While you can join with any amount during epoch 0, your stake will only be **activated in epoch 2** if it meets the minimum requirements (42,000 GEN for validators, 42 GEN for delegators). Stakes below the minimum remain registered but inactive. - -#### Validators in Epoch 0 - -**Key behaviors:** - -1. **No minimum stake to join**: Validators can join with any non-zero amount during epoch 0 -2. **Registered for epoch 2**: Stakes are recorded and will become active when epoch 2 begins -3. **No priming required**: `validatorPrime()` is not needed during epoch 0 -4. **No consensus participation**: Validators do not process transactions in epoch 0 - -**Do validators need to take any action in epoch 0 to be active in epoch 2?** - -No. Validators who join in epoch 0: - -- Have their stake registered during epoch 0 -- Become active automatically in epoch 2 (epoch 1 is skipped) **only if they have at least 42,000 GEN staked** -- Must start calling `validatorPrime()` in epoch 2 for continued participation in epoch 4+ - -**Important**: Validators who joined in epoch 0 with less than 42,000 GEN will **not be active** in epoch 2. They must deposit additional funds to meet the minimum requirement before epoch 2 begins. - -#### Delegators in Epoch 0 - -**Key behaviors:** - -1. **No minimum delegation**: Any non-zero amount accepted during epoch 0 -2. **Registered for epoch 2**: Delegation is recorded and will become active when epoch 2 begins -3. **No rewards in epoch 0**: Since no transactions are processed, no rewards are earned during epoch 0 - -**Is a delegation made in epoch 0 active in epoch 2?** - -Yes. Delegations made in epoch 0 become active in epoch 2 (epoch 1 is skipped). Unlike normal epochs where you wait +2 epochs, epoch 0 delegations activate as soon as the network becomes operational. - -#### Activation Timeline Comparison - -**Normal Epochs (2+):** -``` -Epoch N: validatorJoin() or delegatorJoin() called -Epoch N+1: validatorPrime() stages the deposit -Epoch N+2: validatorPrime() activates the deposit → NOW ACTIVE +```text +weight = (alpha × self-stake + (1 - alpha) × delegated stake) ^ beta ``` -**Epoch 0 (Bootstrapping):** -``` -Epoch 0: validatorJoin() or delegatorJoin() called → stake registered (not yet active) - No transactions processed, no consensus -Epoch 2: Stakes become active (if minimum met), network operational, validatorPrime() required -``` - -#### Share Calculation in Epoch 0 - -In epoch 0, shares are calculated at a 1:1 ratio with the input amount: - -``` -Shares = Input Amount - -Example: Deposit 1,000 GEN → Receive 1,000 shares -``` - -This is because there's no existing stake pool to calculate a ratio against. Starting from epoch 2, shares are calculated based on the current stake-to-share ratio. - -#### Transitioning from Epoch 0 to Epoch 2 - -When the network advances from epoch 0 to epoch 2 (epoch 1 is skipped): - -1. **Epoch 0 stakes that meet minimums become active** - validators need 42,000 GEN, delegators need 42 GEN -2. **Normal minimum requirements apply** for new joins/deposits -3. **+2 epoch activation delay** applies to all new deposits -4. **validatorPrime() becomes mandatory** for validators to remain in the selection pool -5. **Existing validators** must ensure their nodes begin calling `validatorPrime()` in epoch 2 - -#### FAQ: Epoch 0 Special Cases - -**Q: Can I join as a validator with less than 42,000 GEN in epoch 0?** -A: Yes, any non-zero amount is accepted during epoch 0. However, you will **not be active** in epoch 2 unless you have at least 42,000 GEN staked by then. - -**Q: If I delegate in epoch 0, when does it become active?** -A: In epoch 2. Unlike normal epochs with a +2 delay, epoch 0 delegations activate when the network becomes operational. - -**Q: Do I need to call validatorPrime() in epoch 0?** -A: No. Priming is not required during epoch 0. Your node should start calling it automatically when epoch 2 begins. - -**Q: Will my epoch 0 stake still be active after epoch 0 ends?** -A: Yes, if you meet the minimum requirements. Stakes from epoch 0 carry forward and remain active in all subsequent epochs. - -**Q: What happens to my stake if I joined in epoch 0 but my node doesn't call validatorPrime() in epoch 2?** -A: You'll be excluded from validator selection in epoch 4, but your stake remains. Once priming resumes, you'll be eligible for selection again. - -## Shares vs Stake - -The staking system uses shares to track ownership: - -**Shares** are fixed quantities that never change. You receive shares when depositing and exit by burning shares. They represent immutable claims on the stake pool. - -**Stake** is the dynamic GEN token amount. It increases with rewards/fees and decreases with slashing. The exchange rate is calculated as: - -``` -stake_per_share = total_stake / total_shares -``` - -**Example**: 100 shares representing 1,000 GEN (10 GEN per share). After rewards are distributed, the same 100 shares might represent 1,050 GEN (10.5 GEN per share). Rewards automatically compound without user action. - -## Validator Selection and Weight - -Validators are selected for consensus based on their weight, calculated using: - -``` -Weight = (ALPHA × Self_Stake + (1-ALPHA) × Delegated_Stake)^BETA -``` - -**Parameters:** -- **ALPHA = 0.6**: Self-stake counts 50% more than delegated stake -- **BETA = 0.5**: Square-root damping prevents whale dominance - -**Effects:** -- Higher stake leads to higher weight and higher selection probability -- Doubling stake only increases weight by approximately 41% -- Encourages distribution across validators -- Smaller validators often provide higher returns per GEN staked - -## Reward Distribution - -**Sources:** -1. Transaction Fees -2. Inflation (starting at 15% APR, decreasing to 4% APR over time) - -**Distribution Pattern:** -- **10%** → Validator owners (operational fee) -- **75%** → Total validator stake (validators + delegators) -- **10%** → Developers -- **5%** → Locked future allocation for the DeepThought AI-DAO - -Within the 75% stake allocation: -- Self-stake receives a portion based on the validator's own staked amount -- Delegated stake is split among delegators proportionally to their shares - -Rewards automatically increase the stake-per-share ratio without requiring user action. - -## Unbonding Period - -Both validators and delegators face a **7-epoch unbonding period** when withdrawing: - -- Prevents rapid stake movements that could destabilize the network -- Exit is not processed immediately - validator remains active until next `validatorPrime()` call at next epoch -- Exited tokens stop earning rewards only after the exit is processed in the next epoch -- Countdown starts from the exit epoch -- Funds become claimable when: `current_epoch >= exit_epoch + 7` - -**Detailed Exit Flow**: - -``` -Epoch N: validatorExit(all_shares) called - → Exit scheduled in contract state - → Validator STILL ACTIVE and earning rewards - → Can still be selected for consensus participation - -Epoch N+1: validatorPrime() called (by anyone) - → Exit processed: stake reduced to 0 - → Removed from validator tree - → No longer active or earning rewards - → Cannot be selected for new transactions - -Epoch N+2: epochAdvance() called - → Validator officially not in active validator set - → Fully excluded from consensus operations - -Epoch N+7: validatorClaim() callable - → 7 epochs have passed since exit call (epoch N) - → Tokens released to validator owner -``` - -## Validator Priming - -`validatorPrime(address validator)` is a critical function that: - -- Activates pending deposits -- Processes pending withdrawals -- Distributes previous epoch rewards -- Applies pending slashing penalties -- Sorts the validator into the selection tree - -**Key Properties:** -- **Monitoring Required**: Ensure correct execution -- **Permissionless**: Anyone can call it -- **Incentivized**: Caller receives 1% of any slashed amount -- **Critical**: If the node fails to prime, the validator is excluded from the next epoch -- **No Loss**: Missing priming doesn't lose rewards, but the validator can't be selected - -## Unstaking and Withdrawing - -Both validators and delegators can withdraw their staked tokens, but must follow the unbonding process. - -### For Validators - -To stop validating or retrieve staked tokens, validators must: - -1. **Calculate shares to exit**: Determine how many shares to withdraw (partial or full) -2. **Call `validatorExit(shares)`**: Initiate the unbonding process -3. **Wait 7 epochs**: Tokens are locked during the unbonding period -4. **Call `validatorClaim()`**: Retrieve tokens after unbonding completes +Current defaults are `alpha = 0.6` and `beta = 0.5`. Self-stake therefore contributes more per GEN than delegated stake, while the square-root-like damping reduces concentration advantages. The activator role is selected uniformly and does not use this weight. -Validators can perform partial exits while remaining active, as long as their stake stays above the 42,000 GEN minimum. +## Shares and compounding -### For Delegators +Stake pools use shares. A deposit receives shares representing a fraction of the pool. Rewards increase the GEN represented by each share; slashes decrease it. This lets rewards compound without issuing new shares for every epoch. -Delegators follow a similar process: +Delegation increases a validator's selection weight, but delegates also share the economic performance and slash exposure of that pool. -1. **Calculate shares to exit**: Use `sharesOf(delegator, validator)` to check current shares -2. **Call `delegatorExit(validator, shares)`**: Initiate unbonding for a specific validator -3. **Wait 7 epochs**: Tokens are locked during the unbonding period -4. **Call `delegatorClaim(delegator, validator)`**: Retrieve tokens after unbonding +## Epoch activation and priming -**Important for delegators:** -- Exit each validator separately if delegating to multiple validators -- Claims are permissionless—anyone can trigger them on your behalf -- Tokens stop earning rewards immediately upon calling exit -- Multiple exits create separate withdrawals that can be claimed together +Deposits, withdrawals, rewards, and penalties are staged across epochs rather than changing the active set immediately. Under the current rules, new validator and delegation deposits become active two epochs later. -For detailed step-by-step instructions and code examples, see the [Staking Guide](/developers/staking-guide). +`validatorPrime()` processes a validator's pending epoch changes, applies rewards and matured penalties, and places eligible stake in the selection structure for the next epoch. The call is permissionless. A validator that is not primed is excluded from the next selection set until processing catches up. -## Governance and Safeguards +## Rewards and risks -- **24-Hour Delay**: All slashing actions have a governance delay period -- Parameters like ALPHA, BETA, minimum stakes, and unbonding periods are adjustable through governance -- Maximum 1,000 active validators per epoch (adjustable) +Validators and delegators share the stake portion of transaction fees and inflation. Validator owners also receive the protocol's operations allocation. Exact rates and routing are protocol parameters; see the [economic model](/understand-genlayer-protocol/core-concepts/economic-model). -## Next Steps +Stake can lose value through penalties. Validators can also be temporarily banned or quarantined, which prevents new selection. Read [slashing](/understand-genlayer-protocol/core-concepts/optimistic-democracy/slashing) before choosing a validator. -- [Staking Guide](/developers/staking-guide) - Practical guide for staking operations -- [Unstaking](/understand-genlayer-protocol/core-concepts/optimistic-democracy/unstaking) - Detailed unstaking process -- [Slashing](/understand-genlayer-protocol/core-concepts/optimistic-democracy/slashing) - Slashing conditions and penalties +For transactions and command examples, use the [staking guide](/developers/staking-guide) and [validator setup guide](/validators/setup-guide). diff --git a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/unstaking.mdx b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/unstaking.mdx index 455d5dc8..b218e17b 100644 --- a/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/unstaking.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/optimistic-democracy/unstaking.mdx @@ -1,33 +1,49 @@ --- -description: "Unstaking in GenLayer explains how validators exit active duties, wait for finality, and withdraw stake and rewards." +description: "Learn how GenLayer validator and delegator exits move through epoch processing and the unbonding period." --- -# Unstaking in GenLayer -Unstaking in GenLayer is the process by which validators disengage their staked tokens from the network and end active participation as validators. Validators initiate unstaking with a transaction, are removed from the active validator pool, and wait through a cooldown period so all transactions they participated in can reach full finality. After pending obligations and issues are resolved, validators and their delegators can withdraw staked tokens and any accrued rewards while preserving network integrity and platform security. +# Unstaking -## How Unstaking Works +Unstaking converts validator or delegator shares into a scheduled GEN withdrawal. An exit is processed through epoch accounting, stops earning after the exited stake leaves the active record, and becomes claimable after the unbonding period. -The unstaking process includes several key steps: +It does not wait for every transaction in which the validator participated to finalize. -1. **Initiating Unstaking**: Validators initiate their exit from active duties by submitting an unstaking transaction, signaling their intention to cease participation in validating transactions. +## Exit lifecycle -2. **Validator Removal**: Once the unstaking request is made, the validator is promptly removed from the pool of active validators, meaning they will no longer receive new transactions or be called upon for appeal validations. +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 42, "rankSpacing": 44, "htmlLabels": true}}}%% +flowchart TB + A(["Request exit
burn shares"]) --> B["Pending epoch
processing"] + B --> C["Remove stake from
active position"] + C --> D["Unbonding
current default: 7 epochs"] + D --> E(["Claimable GEN"]) -3. **Finality Period**: During this period, validators must wait for all transactions they have participated in to reach full finality. This is crucial to ensure that validators do not exit while still having potential influence over unresolved transactions. This cooldown period helps prevent the situation where new transactions with new finality windows could prevent them from ever achieving full finality on all transactions they were involved in. + classDef action fill:#F7F8FC,stroke:#8B95A7,color:#202536,stroke-width:1.5px; + classDef pending fill:#FFF4E5,stroke:#D58A16,color:#583705,stroke-width:2px; + classDef success fill:#E9F8F0,stroke:#23966B,color:#123F30,stroke-width:2px; + class A action; + class B,C,D pending; + class E success; + linkStyle default stroke:#7C879C,stroke-width:1.8px; +``` -4. **Withdrawing Stake**: After all transactions have achieved finality and no outstanding issues remain, validators and their delegators can safely withdraw their staked tokens and any accrued rewards. +1. The validator owner or delegator chooses a positive number of shares and submits an exit. +2. The protocol stages the withdrawal and processes it through the validator's epoch records and `validatorPrime()`. +3. Once removed from active stake, those shares no longer contribute to selection weight or earn rewards. +4. After the unbonding period, anyone can trigger the claim for the beneficiary. Funds go to the owner or delegator, not the caller. +Under the current rules, the exit epoch still earns its normal rewards, and the unbonding period is seven epochs measured from the exit request. These values are protocol parameters. -## Purpose of Unstaking +## Validator exits -The unstaking process is designed to: +A validator can exit part of its shares and remain eligible if the resulting self-stake still meets the active minimum. A full exit, or a partial exit below the minimum, removes it from new consensus selection after the staged update takes effect. -- **Ensure Accountability**: By enforcing a Finality Window, validators are held accountable for their actions until all transactions they influenced are fully resolved. This prevents premature exit from the network and ensures that all potential disputes are settled. - -- **Align Incentives**: The requirement for validators to wait through the Finality Window aligns their incentives with the long-term security and reliability of the network, promoting responsible participation. +The owner key controls validator exits and claims. The node's operator key cannot withdraw stake. -- **Maintain Network Security**: The unstaking process discourages abrupt departures and ensures that validators address any possible security concerns related to their past validations before leaving. +## Delegator exits -## Implications for Validators and Delegators +A delegator exits shares separately for each validator pool. Multiple matured withdrawals can be claimed together according to the staking contract's accounting. During unbonding, exited stake earns no rewards and remains subject to the protocol rules attached to the withdrawal record. -For validators, this process mandates careful planning regarding their exit strategy from the network, considering the need to wait out the Finality Window. Delegators must also be patient, understanding that their assets will remain locked until their validator has cleared all responsibilities, safeguarding their investments from potential liabilities caused by unresolved validations. \ No newline at end of file +Use current contract views or the SDK to calculate shares and claimability; do not convert a desired GEN amount to shares using a stale exchange rate. + +For step-by-step commands, see the [staking guide](/developers/staking-guide). diff --git a/pages/understand-genlayer-protocol/core-concepts/rollup-integration.mdx b/pages/understand-genlayer-protocol/core-concepts/rollup-integration.mdx index a6ab9c77..a4c4576a 100644 --- a/pages/understand-genlayer-protocol/core-concepts/rollup-integration.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/rollup-integration.mdx @@ -1,47 +1,72 @@ --- -description: "Rollup Integration explains how GenLayer uses Ethereum rollups to scale GenVM execution, lower fees, and inherit Ethereum security." +description: "Learn how GenLayer Chain, its consensus contracts, validator nodes, GenVM, and Ethereum settlement fit together." --- -# Rollup Integration +# GenLayer Chain integration -Rollup Integration is how GenLayer uses Ethereum rollups, such as ZKSync or Polygon CDK, to improve scalability and compatibility with existing Ethereum infrastructure. By moving execution off-chain while anchoring results to Ethereum, this integration helps optimize transaction throughput and reduce fees while maintaining the security guarantees of the Ethereum mainnet. +GenLayer Chain is an EVM-compatible chain built with the ZK Stack. It hosts ordinary Solidity contracts and the consensus contracts that coordinate Intelligent Contract execution. GenVM is a separate execution environment operated by nodes; it is not an EVM precompile or an Ethereum rollup execution engine. -## Key Aspects of Rollup Integration +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 48, "rankSpacing": 54, "htmlLabels": true}}}%% +flowchart TB + Client(["Wallet or application"]) + Ethereum[("Ethereum")] -### Scalability -- **High Transaction Throughput**: Rollups allow GenLayer to process a much higher number of transactions per second compared to Layer 1 solutions. -- **Reduced Congestion**: By moving computation off-chain, GenLayer helps alleviate congestion on the Ethereum mainnet. + subgraph Onchain["Onchain layer"] + Chain["GenLayer Chain
EVM + consensus contracts"] + end -### Cost Efficiency -- **Lower Transaction Fees**: Users benefit from significantly reduced gas fees compared to direct Layer 1 transactions. -- **Batched Submissions**: Transactions are batched and submitted to the Ethereum mainnet, distributing costs across multiple operations. + subgraph Offchain["Validator execution layer"] + direction LR + Node["GenLayer node"] <--> VM["GenVM"] + end -### Security -- **Ethereum Security Inheritance**: While execution happens off-chain, the security of assets and final state is guaranteed by Ethereum's robust consensus mechanism. -- **Fraud Proofs/Validity Proofs**: Depending on the specific rollup solution (Optimistic or ZK), security is ensured through either fraud proofs or validity proofs. + Client -->|"EVM JSON-RPC"| Chain + Client -->|"GenLayer JSON-RPC"| Node + Ethereum <-->|"bridge and settlement"| Chain + Chain -->|"events and reads"| Node + Node -->|"signed consensus transaction"| Chain -## How Rollup Integration Works with GenLayer + classDef actor fill:#F7F8FC,stroke:#8B95A7,color:#202536,stroke-width:1.5px; + classDef settlement fill:#FFF4E5,stroke:#D58A16,color:#583705,stroke-width:2px; + classDef chain fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef compute fill:#EAF7FF,stroke:#2686C4,color:#113F59,stroke-width:2px; + class Client actor; + class Ethereum settlement; + class Chain chain; + class Node,VM compute; + style Onchain fill:#F8F7FF,stroke:#B9B0FF,stroke-width:1px + style Offchain fill:#F5FBFF,stroke:#A8D7F2,stroke-width:1px + linkStyle default stroke:#7C879C,stroke-width:1.8px; +``` -1. **Transaction Submission**: Users submit transactions to the rollup. +## What lives on GenLayer Chain -2. **Transaction Execution**: Transactions are executed within the GenVM environment. +The chain provides ordering, availability, and an authoritative state machine for consensus. Its contracts record: -3. **Consensus**: The rollup layer implements the Optimistic Democracy mechanism to reach consensus on the state updates. +- Intelligent Contract transactions and per-contract queues; +- activator, leader, and committee assignments; +- proposal, commit, reveal, decision, and appeal state; +- validator staking, fees, and penalties; and +- Ghost contracts that connect EVM accounts to Intelligent Contracts. -4. **State Updates**: The rollup layer maintains an up-to-date state of all accounts and contracts. +Because consensus actions are chain transactions, validators do not need a separate peer-to-peer network to agree on an Intelligent Contract result. Chain time and state determine whether a phase is open or a participant is idle. -5. **Batch Submission**: Periodically, batches of transactions and state updates are submitted to the Ethereum mainnet. +## What lives in GenVM -6. **Verification**: The Ethereum network verifies the integrity of the submitted data, ensuring its validity. +Intelligent Contract code and state execute in GenVM. Nodes reconstruct the accepted Intelligent Contract state by following GenLayer Chain events and replaying the corresponding state transitions. The consensus contracts store commitments and lifecycle data; they do not execute Python contract logic. -## Benefits for Developers and Users +## Ghost contracts bridge the environments -- **Ethereum Compatibility**: Developers can leverage existing Ethereum tools and infrastructure. -- **Improved User Experience**: Lower fees and faster transactions lead to a better overall user experience. +Every Intelligent Contract has a Ghost contract on GenLayer Chain at the same address. A Ghost: -## Considerations +- receives EVM transactions addressed to the Intelligent Contract; +- holds its native GEN balance on the EVM side; +- forwards Intelligent Contract calls to the consensus system; and +- delivers on-acceptance and on-finalization messages to EVM recipients. -- **Withdrawal Periods**: Depending on the rollup solution, there might be waiting periods for withdrawing assets back to the Ethereum mainnet. -- **Rollup-Specific Features**: Different rollup solutions may offer unique features or limitations that developers should be aware of. +The shared address gives wallets and EVM contracts one destination even though execution and balances span two environments. See [accounts and addresses](/understand-genlayer-protocol/core-concepts/accounts-and-addresses) and [messages](/developers/intelligent-contracts/features/messages). -By integrating with Ethereum rollups, GenLayer combines the innovative capabilities of Intelligent Contracts with the scalability and efficiency of Layer 2 solutions, creating a powerful platform for next-generation decentralized applications. \ No newline at end of file +## Settlement and protocol finality are different + +GenLayer Chain inherits its rollup settlement properties from its ZK Stack and Ethereum configuration. Separately, an Intelligent Contract transaction reaches **protocol finality** only after its consensus decision and appeal window complete. Applications must use the Intelligent Contract transaction status—not only the enclosing EVM transaction receipt—to determine whether an outcome is final. diff --git a/pages/understand-genlayer-protocol/core-concepts/transactions.mdx b/pages/understand-genlayer-protocol/core-concepts/transactions.mdx index 8c93a929..5e96147b 100644 --- a/pages/understand-genlayer-protocol/core-concepts/transactions.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/transactions.mdx @@ -1,149 +1,59 @@ --- -description: "Transactions in GenLayer define how deployments, transfers, and contract calls change network state." +description: "Understand the EVM submission and protocol transaction that make up an Intelligent Contract call in GenLayer." --- +import { Card, Cards } from "nextra-theme-docs"; + # Transactions -Transactions in GenLayer are the fundamental operations that change network state, including deploying a new contract, sending value between accounts, or invoking a function within an existing contract. A transaction records the call data, sender and recipient addresses, gas limit, nonce, status, consensus data, and execution receipts used by the protocol to process and finalize the operation. - -Here is the general structure of a transaction: - -```json -{ - "consensus_data": { - "leader_receipt": { - "args": [ - [ - 2, - "0x793Ae2CfF17462cc9f9D68e194b7b949d2080Ea2" - ] - ], - "class_name": "LlmErc20", - "contract_state": "gASVnAAAAAAAAACMF2JhY2tlbmQubm9kZS5nZW52bS5iYXNllIwITGxtRXJjMjCUk5QpgZR9lIwIYmFsYW5jZXOUfZQojCoweEQyNzFjNzRBNzgwODNGMzU3YTlmOGQzMWQ1YWRDNTlCMzk1Y2YxNmKUS2KMKjB4NzkzQWUyQ2ZGMTc0NjJjYzlmOUQ2OGUxOTRiN2I5NDlkMjA4MEVhMpRLAnVzYi4=", - "eq_outputs": { - "leader": { - "0": "{\"transaction_success\": true, \"transaction_error\": \"\", \"updated_balances\": {\"0xD271c74A78083F357a9f8d31d5adC59B395cf16b\": 98, \"0x793Ae2CfF17462cc9f9D68e194b7b949d2080Ea2\": 2}}" - } - }, - "error": null, - "execution_result": "SUCCESS", - "gas_used": 0, - "method": "transfer", - "mode": "leader", - "node_config": { - "address": "0x185D2108D9dE15ccf6beEb31774CA96a4f19E62B", - "config": {}, - "model": "gpt-4o", - "plugin": "openai", - "plugin_config": { - "api_key_env_var": "OPENAIKEY", - "api_url": null - }, - "provider": "openai", - "stake": 1 - }, - "vote": "agree" - }, - "validators": [ - { - "args": [ - [ - 2, - "0x793Ae2CfF17462cc9f9D68e194b7b949d2080Ea2" - ] - ], - "class_name": "LlmErc20", - "contract_state": "gASVnAAAAAAAAACMF2JhY2tlbmQubm9kZS5nZW52bS5iYXNllIwITGxtRXJjMjCUk5QpgZR9lIwIYmFsYW5jZXOUfZQojCoweEQyNzFjNzRBNzgwODNGMzU3YTlmOGQzMWQ1YWRDNTlCMzk1Y2YxNmKUS2KMKjB4NzkzQWUyQ2ZGMTc0NjJjYzlmOUQ2OGUxOTRiN2I5NDlkMjA4MEVhMpRLAnVzYi4=", - "eq_outputs": { - "leader": { - "0": "{\"transaction_success\": true, \"transaction_error\": \"\", \"updated_balances\": {\"0xD271c74A78083F357a9f8d31d5adC59B395cf16b\": 98, \"0x793Ae2CfF17462cc9f9D68e194b7b949d2080Ea2\": 2}}" - } - }, - "error": null, - "execution_result": "SUCCESS", - "gas_used": 0, - "method": "transfer", - "mode": "validator", - "node_config": { - "address": "0x31bc9380eCbF487EF5919eBa7457F457B5196FCD", - "config": {}, - "model": "gpt-4o", - "plugin": "openai", - "plugin_config": { - "api_key_env_var": "OPENAIKEY", - "api_url": null - }, - "provider": "openai", - "stake": 1 - }, - "pending_transactions": [], - "vote": "agree" - }, - ... - ], - "votes": { - "0x185D2108D9dE15ccf6beEb31774CA96a4f19E62B": "agree", - "0x2F04Fb1e5daf7DCbf170E4CB0e427d9b11aB96cA": "agree", - "0x31bc9380eCbF487EF5919eBa7457F457B5196FCD": "agree" - } - }, - "created_at": "2024-10-02T20:32:50.469443+00:00", - "data": { - "function_args": "[2,\"0x793Ae2CfF17462cc9f9D68e194b7b949d2080Ea2\"]", - "function_name": "transfer" - }, - "from_address": "0xD271c74A78083F357a9f8d31d5adC59B395cf16b", - "gaslimit": 66, - "hash": "0xb7486f70a3fec00af5f929fc1cf1078af9ff3a063afe8b6f370a44a96635505d", - "leader_only": false, - "nonce": 66, - "r": null, - "s": null, - "status": "FINALIZED", - "to_address": "0x5929bB548a2Fd7E9Ea2577DaC9c67A08BbC2F356", - "type": 2, - "v": null, - "value": 0 -} + +An Intelligent Contract interaction begins as an EVM transaction on GenLayer Chain and creates a protocol transaction managed by the consensus contracts. These are related records with different purposes and finality. + +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 38, "rankSpacing": 44, "htmlLabels": true}}}%% +flowchart TB + E(["1 · Sign
EVM request"]) --> G["2 · Queue
GenLayer transaction"] + G --> V["3 · Execute
and reach consensus"] + V --> F(["4 · Finalize
contract state"]) + + classDef request fill:#F7F8FC,stroke:#8B95A7,color:#202536,stroke-width:1.5px; + classDef consensus fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef success fill:#E9F8F0,stroke:#23966B,color:#123F30,stroke-width:2px; + class E request; + class G,V consensus; + class F success; + linkStyle default stroke:#7C879C,stroke-width:1.8px; ``` -## Explanation of fields: - -- consensus_data: Object containing information about the consensus process - - leader_receipt: Object containing details about the leader's execution of the transaction - - args: Arguments passed to the contract function - - class_name: Name of the contract class - - contract_state: Encoded state of the contract - - eq_outputs: Outputs from every equivalence principle in the execution of the contract method - - error: Any error that occurred during execution (null if no error) - - execution_result: Result of the execution (e.g., "SUCCESS" or "ERROR") - - gas_used: Amount of gas used in the transaction - - method: Name of the method called on the contract - - mode: Execution mode (e.g., "leader" or "validator") - - node_config: Configuration of the node executing the transaction - - address: Address of the node - - config: Configuration of the node - - model: Model of the node - - plugin: Plugin used for the LLM provider connection - - plugin_config: Configuration of the plugin - - api_key_env_var: Environment variable containing the API key for the given provider - - api_url: API URL for the given provider - - provider: Provider of the node - - stake: Stake of the validator - - vote: The leader's vote on the transaction (e.g., "agree") - - validators: Array of objects containing similar information for each validator - - votes: Object mapping validator addresses to their votes -- created_at: Timestamp of when the transaction was created -- data: Object containing details about the function call in the transaction -- from_address: Address of the account initiating the transaction -- gaslimit: Maximum amount of gas the transaction is allowed to consume -- hash: Unique identifier (hash) of the transaction -- leader_only: Boolean indicating whether the transaction is to be executed by the leader node only -- nonce: Number of transactions sent from the from_address (used to prevent double-spending) -- r: Part of the transaction signature (null if not yet signed) -- s: Part of the transaction signature (null if not yet signed) -- status: Current status of the transaction (e.g., "FINALIZED") -- to_address: Address of the contract or account receiving the transaction -- type: Internal type of the transaction (2 indicates a contract write call) -- v: Part of the transaction signature (null if not yet signed) -- value: Amount of native currency (GEN) being transferred in the transaction +## EVM transaction + +The caller signs an Ethereum-compatible transaction addressed to an Intelligent Contract's Ghost or to a consensus deployment function. Inclusion of this transaction confirms that GenLayer Chain received the request. Standard EVM fields include the sender, destination, nonce, value, gas parameters, and encoded calldata. + +Ordinary GEN transfers and calls to Solidity contracts can complete entirely on this EVM layer. They do not enter Optimistic Democracy unless they create an Intelligent Contract transaction. + +## GenLayer transaction + +The consensus contracts assign an Intelligent Contract request its transaction ID and lifecycle state. The record includes: + +- the original EVM initiator, immediate sender, and Intelligent Contract recipient; +- encoded contract call or deployment data; +- the activator, committee, leader, and round history; +- execution commitments, equivalence-block outputs, and votes; +- phase timestamps, fee accounting, and appeal bonds; and +- the current protocol status and decided execution result. + +The protocol transaction can remain in consensus after the EVM submission is mined. Applications that require the Intelligent Contract outcome must follow the GenLayer transaction until `Finalized`. + +## Ordering + +Each Intelligent Contract has its own pending and decided queues. Transactions for the same recipient move through the active proposal and voting phases sequentially because later calls can depend on earlier state. Transactions to different recipients can progress independently. + +Messages emitted by Intelligent Contracts also create transactions and preserve their dependency on the parent transaction's state and fee allocation. + + + + + + + +For the current receipt schema, see [`gen_getTransactionReceipt`](/api-references/genlayer-node/gen/gen_getTransactionReceipt). diff --git a/pages/understand-genlayer-protocol/core-concepts/transactions/_meta.json b/pages/understand-genlayer-protocol/core-concepts/transactions/_meta.json index 87f421d5..5c430492 100644 --- a/pages/understand-genlayer-protocol/core-concepts/transactions/_meta.json +++ b/pages/understand-genlayer-protocol/core-concepts/transactions/_meta.json @@ -1,6 +1,6 @@ { - "types-of-transactions": "", - "transaction-statuses": "", - "transaction-execution": "", - "transaction-encoding-serialization-and-signing": "" + "types-of-transactions": "Transaction Types", + "transaction-execution": "Transaction Execution", + "transaction-statuses": "Transaction Statuses", + "transaction-encoding-serialization-and-signing": "Encoding and Signing" } diff --git a/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-encoding-serialization-and-signing.mdx b/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-encoding-serialization-and-signing.mdx index fce43794..11b20ccd 100644 --- a/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-encoding-serialization-and-signing.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-encoding-serialization-and-signing.mdx @@ -1,8 +1,30 @@ --- -description: "Transaction encoding, serialization, and signing in GenLayer for preparing raw transactions and RPC submission" +description: "Learn how an Intelligent Contract request becomes signed EVM calldata and a GenLayer consensus transaction." --- -# Transaction encoding, serialization, and signing -Transaction encoding, serialization, and signing in GenLayer is the client-side process of packaging all three transaction types into a reliable, cross-platform, efficient format and signing them with the sender's private key to verify the sender's identity. +# Encoding, signing, and submission -Once prepared, the transaction is sent to the network via the `eth_sendRawTransaction` method on the RPC Server. This method performs the inverse process: it decodes and deserializes the transaction data, and then verifies the signature to ensure its authenticity. By handling all transaction types through `eth_sendRawTransaction`, GenLayer ensures that transactions are processed securely and efficiently while maintaining compatibility with Ethereum’s specification. +Clients submit an Intelligent Contract request through an Ethereum-compatible transaction. The outer transaction uses standard EVM signing and serialization; its calldata contains the GenLayer-specific deployment or method call and fee configuration. + +## Submission layers + +1. The client encodes the Intelligent Contract method and arguments in the GenLayer call format. +2. It packages that data and the protocol fee configuration into a call to the Ghost or consensus contracts. +3. The caller signs the outer EVM transaction with its account key. +4. The client serializes and sends the signed transaction through `eth_sendRawTransaction`. +5. When the EVM call is included, the consensus contracts create the GenLayer transaction and emit its ID. + +The SDK and CLI perform these steps for normal application code. Use their high-level deployment and write methods instead of constructing consensus calldata by hand. + +## Two identifiers and two receipts + +The outer EVM transaction has an EVM transaction hash and receipt. The created Intelligent Contract transaction has a protocol transaction ID and consensus receipt. Do not assume that the two identifiers or their success fields are interchangeable. + +- The EVM receipt tells you whether the submission call executed on GenLayer Chain. +- The GenLayer receipt tells you how Intelligent Contract consensus progressed and which execution result finalized. + +## Signing safety + +Signing proves authorization for the EVM transaction, including its destination, value, calldata, nonce, gas settings, and chain ID. Before asking a wallet to sign, a client should show the network, recipient, value, and expected action. Never transmit or log the caller's private key. + +For current code, use [GenLayerJS write calls](/developers/decentralized-applications/writing-data), [Intelligent Contract deployment](/developers/intelligent-contracts/deploying), and the [node RPC reference](/api-references/genlayer-node). diff --git a/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-execution.mdx b/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-execution.mdx index cfd7c28b..e1ed9229 100644 --- a/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-execution.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-execution.mdx @@ -1,41 +1,72 @@ --- -description: "Transaction execution in GenLayer: how submitted transactions move from pending through validator consensus to finalization" +description: "Follow a GenLayer transaction through activation, leader execution, commit-reveal voting, appeals, and finalization." --- # Transaction execution -Transaction execution in GenLayer is the process that starts after `eth_sendRawTransaction` receives and verifies a transaction, stores it with a PENDING status, and returns its hash as the RPC response. At that point, the transaction has been validated for authenticity and format, but it has not yet been executed; it enters the GenLayer consensus mechanism, where the network's validators pick it up for execution according to the consensus rules. -As the transaction progresses through stages such as proposing, committing, and revealing, its status is updated accordingly. Users can query the current status and output of the transaction by calling the `eth_getTransactionByHash` method on the RPC server, which retrieves the transaction's details based on its unique hash. This method lets users track the transaction's journey from submission to finalization, providing transparency and helping them monitor transaction outcomes in real time. +After an EVM submission creates a GenLayer transaction, the consensus contracts coordinate execution as an onchain state machine. Validator nodes observe the current phase, perform work in GenVM, and submit the next signed consensus action. -## Transaction Status Transitions +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 40, "rankSpacing": 44, "htmlLabels": true}}}%% +flowchart TD + Pending(["Pending"]) -->|"activate and select committee"| Propose["Proposing"] + Propose -->|"leader submits receipt"| Vote["Committing → LeaderRevealing → Revealing"] + Vote --> Decision{"Decided
outcome"} + Decision --> Window["Appeal window"] + Window -->|"window elapses"| Ready["ReadyToFinalize"] + Ready --> Final(["Finalized"]) + Pending -. "cancel or expire" .-> Canceled(["Canceled"]) + + classDef phase fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef success fill:#E9F8F0,stroke:#23966B,color:#123F30,stroke-width:2px; + classDef inactive fill:#F3F4F6,stroke:#9CA3AF,color:#374151,stroke-width:1.5px; + class Pending,Propose,Vote,Decision,Window phase; + class Ready,Final success; + class Canceled inactive; + linkStyle default stroke:#7C879C,stroke-width:1.8px; +``` + +## Pending and activation + +Transactions enter the recipient Intelligent Contract's pending queue. The assigned activator advances the transaction when it reaches the queue head. Activation fixes the selection seed, locks applicable fee prices, selects the stake-weighted committee, and chooses a leader. + +## Proposal + +The leader executes the call in GenVM and submits a receipt with the proposed execution result and state changes. It also executes the validator path so it can vote with the committee. -In the journey of a transaction within the GenLayer protocol, it begins its life when an Externally Owned Account (EOA) submits it, entering the `Pending` state. Here, it awaits further processing unless it encounters an `OutOfFee` state due to insufficient fees. If the fees are topped up, it returns to `Pending`. Alternatively, the user can cancel the transaction, moving it to the `Canceled` state. +If the leader cannot finish within its allocated execution time, it can report a leader timeout. If the leader is idle, a permissionless timeout action can rotate it when the transaction has funded rotations available. -From `Pending`, the transaction progresses to the `Proposing` stage, where a leader is selected to propose a receipt. Upon successful proposal, it advances to the `Committing` stage, where all validators must commit to the transaction. If all validators commit, the transaction moves to the `Revealing` stage. +## Commit, leader reveal, and vote reveal -In the `Revealing` stage, the transaction's fate is determined. If a majority agrees, it is `Accepted`. However, if there is no majority agreement, it returns to `Proposing`. If all leaders are rotated without agreement, it becomes `Undetermined`. In cases of disagreement, a successful appeal can revert it to `Pending`, while a failed appeal results in `Accepted`. +Committee members validate deterministic execution and apply the contract's equivalence rules to non-deterministic outputs. They commit encrypted votes and result hashes before seeing the other revealed votes. -Once `Accepted`, the transaction awaits the passing of the appeal window to become `Finalized`. An `Undetermined` transaction also becomes `Finalized` after the appeal window passes. However, an appeal can initiate a return to `Committing` from `Accepted`, or automatically revert an `Undetermined` transaction to `Pending`. +The leader reveals its execution data and decryption keys in `LeaderRevealing`. Committee members then reveal their votes in `Revealing`. The consensus contracts calculate the majority from the revealed votes. + +## Decision and appeals + +Accepted, ValidatorsTimeout, Undetermined, and LeaderTimeout are decided outcomes that enter an appeal window. Validator appeals use a fresh committee to check the existing proposal. Leader appeals begin another proposal round. See [appeals](/understand-genlayer-protocol/core-concepts/optimistic-democracy/appeal-process). ```mermaid -graph TD; - Start(( )) -->|EOA submits| Pending(Pending) - Start -->|Insufficient fee| OutOfFee(OutOfFee) - OutOfFee -->|Fee topped up| Pending - Pending -->|User cancels| Canceled(Canceled) - - Pending -->|Select leader| Proposing(Proposing) - Proposing -->|Leader proposes receipt| Committing(Committing) - Committing -->|All validators commit| Revealing(Revealing) - - Revealing -->|Majority agrees| Accepted(Accepted) - Revealing -->|No majority agreement| Proposing - Revealing -->|All leaders rotated| Undetermined(Undetermined) - Revealing -.->|Disagreement, appeal successful| Pending - Revealing -.->|Agreement, appeal failed| Accepted - - Accepted -->|Appeal window passes| Finalized(Finalized) - Undetermined -->|Appeal window passes| Finalized - Accepted -.->|Appeal initiated| Committing - Undetermined -->|Appeal automatically| Pending +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 40, "rankSpacing": 46, "htmlLabels": true}}}%% +flowchart TB + Decision["Decided outcome"] --> Window["Appeal window"] + Window -->|"no appeal"| Ready["Ready to finalize"] + Window -->|"validator appeal"| Review["Fresh committee review"] + Review -->|"confirmed"| Window + Review -->|"overturned"| Round["New proposal round"] + Window -->|"leader appeal"| Round + + classDef phase fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef challenge fill:#FFF4E5,stroke:#D58A16,color:#583705,stroke-width:2px; + classDef success fill:#E9F8F0,stroke:#23966B,color:#123F30,stroke-width:2px; + class Decision,Window,Round phase; + class Review challenge; + class Ready success; + linkStyle default stroke:#7C879C,stroke-width:1.8px; ``` + +## Finalization + +When the effective appeal window has elapsed, the transaction is ready to finalize. The finalization call records the terminal status, settles remaining fees and refunds, emits finalization messages, and advances the recipient's queues. + +An EVM submission receipt is not a substitute for this lifecycle. Poll [`gen_getTransactionStatus`](/api-references/genlayer-node/gen/gen_getTransactionStatus) or retrieve the full [`gen_getTransactionReceipt`](/api-references/genlayer-node/gen/gen_getTransactionReceipt). diff --git a/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-statuses.mdx b/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-statuses.mdx index ca5a1d08..e4a02017 100644 --- a/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-statuses.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/transactions/transaction-statuses.mdx @@ -1,30 +1,37 @@ --- -description: "Transaction Processing explains GenLayer transaction statuses from pending queue to finalized, undetermined, or canceled outcomes." +description: "Reference all GenLayer Intelligent Contract transaction statuses and their numeric codes." --- -# Transaction Processing -GenLayer transaction processing is the account-based queue flow that moves each transaction through network statuses from submission to execution outcome. Transactions are queued per account to preserve the order in which they were submitted, then transition through pending, proposing, committing, revealing, accepted, finalized, undetermined, or canceled states. +# Transaction statuses -## 1. Pending -When a transaction is first submitted, it enters the pending state. This means it has been received by the network but is waiting to be processed. Transactions are queued per account, ensuring that each account's transactions are processed in the order they were submitted. +The consensus contracts define 15 numeric status values. APIs can return the stored status or an effective status calculated from the current time, such as `ReadyToFinalize` after an appeal window expires. -## 2. Proposing -In this stage, the transaction is moved from the pending queue to the proposing stage. A leader and a set of voters are selected from the validator set via a weighted random selection based on total stake. The leader proposes a receipt for the transaction, which is then committed to by the validators. +| Code | Status | Meaning | +| ---: | --- | --- | +| 0 | `Uninitialized` | No transaction is initialized for this ID. | +| 1 | `Pending` | The transaction is queued and waiting for activation. | +| 2 | `Proposing` | A leader is assigned and must propose an execution receipt. | +| 3 | `Committing` | The committee is submitting encrypted vote commitments. | +| 4 | `Revealing` | Committee members are revealing their committed votes. | +| 5 | `Accepted` | The committee accepted the proposed receipt; the appeal window is open. | +| 6 | `Undetermined` | The round did not reach a result and no funded rotation remained; a leader appeal is possible. | +| 7 | `Finalized` | The appeal process is complete and finalization was recorded. | +| 8 | `Canceled` | The transaction was canceled before completing consensus. | +| 9 | `AppealRevealing` | A fresh validator-appeal committee is revealing votes. | +| 10 | `AppealCommitting` | A fresh validator-appeal committee is committing votes. | +| 11 | `ReadyToFinalize` | The effective appeal window elapsed and the transaction can be finalized. | +| 12 | `ValidatorsTimeout` | A validator majority reported that validation timed out; the appeal window is open. | +| 13 | `LeaderTimeout` | The leader reported an execution timeout; the appeal window is open. | +| 14 | `LeaderRevealing` | The leader must reveal execution data and keys before committee vote reveals. | -## 3. Committing -The transaction enters the committing stage, where validators commit their votes and cost estimates for processing the transaction. This stage is crucial for reaching consensus on the transaction's execution. +## Status is not execution success -## 4. Revealing -After the committing stage, validators reveal their votes and cost estimates, allowing the network to finalize the transaction's execution cost and validate the consensus. +`Accepted` means the validator committee reached consensus on the receipt. The receipt itself can represent a successful return, a user error, a GenVM error, or a timeout. Inspect the receipt's execution result in addition to its consensus status. -## 5. Accepted -Once the majority of validators agree on the transaction's validity and cost, the transaction is marked as accepted. This status indicates that the transaction has passed through the initial validation process successfully. +Similarly, `Finalized` means the decided receipt is no longer appealable. It does not convert an error result into a successful contract call. -## 6. Finalized -After all validations are completed and any potential appeals have been resolved, the transaction is finalized. In this state, the transaction is considered irreversible and is permanently recorded in the blockchain. +## Stored and effective status -## 7. Undetermined -If the transaction fails to reach consensus after all voting rounds, it enters the undetermined state. This status indicates that the transaction's outcome is unresolved, and it may require further validation or be subject to an appeal process. +Some view functions accept a timestamp and derive the status that applies after a deadline. A transaction whose stored decision is `Accepted`, for example, can be reported as `ReadyToFinalize` after its appeal window elapses even before a finalization transaction updates storage to `Finalized`. -## 8. Canceled -A transaction can be canceled by the user or by the system if it fails to meet certain criteria (e.g., insufficient funds). Once canceled, the transaction is removed from the processing queue and will not be executed. +Use the numeric codes for program logic and display the names to users. See [`gen_getTransactionStatus`](/api-references/genlayer-node/gen/gen_getTransactionStatus). diff --git a/pages/understand-genlayer-protocol/core-concepts/transactions/types-of-transactions.mdx b/pages/understand-genlayer-protocol/core-concepts/transactions/types-of-transactions.mdx index 897cdce9..63b6eca0 100644 --- a/pages/understand-genlayer-protocol/core-concepts/transactions/types-of-transactions.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/transactions/types-of-transactions.mdx @@ -1,98 +1,41 @@ --- -description: "Types of Transactions covers GenLayer contract deployment, GEN transfers, and Intelligent Contract function calls." +description: "Distinguish ordinary EVM transactions from Intelligent Contract deployments, calls, and messages in GenLayer." --- -# Types of Transactions -GenLayer transactions are user-submitted operations that deploy an Intelligent Contract, send native GEN value, or call a function on an existing Intelligent Contract. All three types are sent through the same RPC method, but they differ in the data they contain and the actions they perform. - -## 1. Deploy a Contract -Deploying a contract involves creating a new Intelligent Contract on the GenLayer network. This transaction initializes the contract's state and assigns it a unique address on the blockchain. The deployment process ensures that the contract code is properly validated and stored, making it ready to be called. - -### Example -```json -{ - "consensus_data": { - "leader_receipt": { - "args": [ - { - "total_supply": 100 - } - ], - "class_name": "LlmErc20", - "contract_state": "gASVnAAAAAAAAACMF2JhY2tlbmQubm9kZS5nZW52bS5iYXNllIwITGxtRXJjMjCUk5QpgZR9lIwIYmFsYW5jZXOUfZQojCoweEQyNzFjNzRBNzgwODNGMzU3YTlmOGQzMWQ1YWRDNTlCMzk1Y2YxNmKUS2KMKjB4NzkzQWUyQ2ZGMTc0NjJjYzlmOUQ2OGUxOTRiN2I5NDlkMjA4MEVhMpRLAnVzYi4=", - ... - }, - "validators": [ - ... - ], - ... - }, - "data": { - "constructor_args": "{\"total_supply\":100}", - "contract_address": "0x5929bB548a2Fd7E9Ea2577DaC9c67A08BbC2F356", - "contract_code": "import json\nfrom backend.node.genvm.icontract import IContract\nfrom backend.node.genvm.equivalence_principle import EquivalencePrinciple\n\n\nclass LlmErc20(IContract):\n def __init__(self, total_supply: int) -> None:\n self.balances = {}\n self.balances[contract_runner.from_address] = total_supply\n...", - }, - ... -} -``` -## 2. Send Value -Sending value refers to transferring the native GEN token from one account to another. This is one of the most common types of transactions. Each transfer updates the balance of the involved accounts, and the transaction is recorded on the blockchain to ensure transparency and security. - -### Example -```json -{ - "consensus_data": null, - "created_at": "2024-10-02T21:21:04.192995+00:00", - "data": {}, - "from_address": "0x0Bd6441CB92a64fA667254BCa1e102468fffB3f3", - "gaslimit": 0, - "hash": "0x6357ec1e86f003b20964ef3b2e9e072c7c9521f92989b08e04459b871b69de89", - "leader_only": false, - "nonce": 2, - "r": null, - "s": null, - "status": "FINALIZED", - "to_address": "0xf739FDe22E0C0CB6DFD8f3F8D170bFC07329489E", - "type": 0, - "v": null, - "value": 200 -} -``` - -## 3. Call Contract Function -Calling a contract function is the process of invoking a specific method within an existing Intelligent Contract. This could involve anything from querying data stored within the contract to executing more complex operations like transferring tokens or interacting with other contracts. Each function call is a transaction that modifies the contract’s state based on the inputs provided. - -### Example -```json -{ - "consensus_data": { - "leader_receipt": { - "args": [ - [ - 2, - "0x793Ae2CfF17462cc9f9D68e194b7b949d2080Ea2" - ] - ], - "class_name": "LlmErc20", - "contract_state": "gASVnAAAAAAAAACMF2JhY2tlbmQubm9kZS5nZW52bS5iYXNllIwITGxtRXJjMjCUk5QpgZR9lIwIYmFsYW5jZXOUfZQojCoweEQyNzFjNzRBNzgwODNGMzU3YTlmOGQzMWQ1YWRDNTlCMzk1Y2YxNmKUS2KMKjB4NzkzQWUyQ2ZGMTc0NjJjYzlmOUQ2OGUxOTRiN2I5NDlkMjA4MEVhMpRLAnVzYi4=", - "eq_outputs": { - "leader": { - "0": "{\"transaction_success\": true, \"transaction_error\": \"\", \"updated_balances\": {\"0xD271c74A78083F357a9f8d31d5adC59B395cf16b\": 98, \"0x793Ae2CfF17462cc9f9D68e194b7b949d2080Ea2\": 2}}" - } - }, - ... - }, - "validators": [ - ... - ], - ... - }, - "data": { - "function_args": "[2,\"0x793Ae2CfF17462cc9f9D68e194b7b949d2080Ea2\"]", - "function_name": "transfer" - }, - ... -} -``` - -* For a list of all the fields in a transaction, see [here](/core-concepts/transactions) \ No newline at end of file +# Transaction types + +GenLayer supports ordinary EVM transactions and transactions that enter Intelligent Contract consensus. The distinction determines which execution environment runs the code and which status an application must monitor. + +## Ordinary EVM transactions + +EOAs can transfer native GEN or call Solidity contracts on GenLayer Chain. The EVM executes these operations according to the chain's ordinary rules. Their EVM receipt is the relevant execution record. + +Examples include: + +- transferring GEN between EOAs; +- interacting with an ERC-20 or another Solidity contract; and +- calling staking or consensus administration contracts directly. + +## Intelligent Contract deployment + +A deployment request creates a Ghost contract on GenLayer Chain and submits the Intelligent Contract code and constructor arguments for GenVM consensus. The Ghost and Intelligent Contract use the same address. + +The Ghost can exist before GenVM deployment finalizes. Therefore, the presence of EVM code at the address does not by itself prove that the Intelligent Contract deployment succeeded. Follow the deployment's GenLayer transaction status and receipt. + +## Intelligent Contract write call + +A write call sends encoded method data to an existing Intelligent Contract's Ghost. The Ghost relays the request to the consensus contracts, and the resulting transaction follows the full proposal, voting, appeal, and finalization lifecycle. + +A call can include native value. The value is accounted for separately from the consensus fee budget and follows the protocol's cancellation and settlement rules. + +## Intelligent Contract messages + +During deterministic execution, an Intelligent Contract can schedule asynchronous messages to another Intelligent Contract, an EVM contract, or an EOA. A message can be configured for acceptance or finalization and can create a child Intelligent Contract transaction. + +Messages use fee capacity reserved by the parent transaction. They are not synchronous nested calls and do not return a value to the parent execution. + +## Read-only simulation + +A read or simulated call can execute through a node RPC without creating an onchain consensus transaction. It is useful for previews and view methods, but its result does not have protocol finality and can depend on the node's synchronized state. + +Use [GenLayerJS write calls](/developers/decentralized-applications/writing-data), [read calls](/developers/decentralized-applications/reading-data), and [messages](/developers/intelligent-contracts/features/messages) for implementation details. diff --git a/pages/understand-genlayer-protocol/core-concepts/validators-and-validator-roles.mdx b/pages/understand-genlayer-protocol/core-concepts/validators-and-validator-roles.mdx index 413ba9d7..64ddeeea 100644 --- a/pages/understand-genlayer-protocol/core-concepts/validators-and-validator-roles.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/validators-and-validator-roles.mdx @@ -1,29 +1,46 @@ --- -description: "Validators in GenLayer validate transactions, vote in Optimistic Democracy, stake tokens, and serve leader or consensus roles." +description: "Learn how GenLayer selects activators, leaders, and committee validators for each Intelligent Contract transaction." --- -# Validators and Validator Roles +# Validators and roles -Validators are GenLayer network participants that validate transactions, help maintain blockchain integrity and security, and participate in Optimistic Democracy consensus. They verify deterministic and non-deterministic transactions, use the Equivalence Principle for non-deterministic operations, take part in leader selection, vote on proposed outcomes, and stake tokens to earn validation rights and rewards. +Validators run GenLayer nodes, stake GEN, execute Intelligent Contracts, and submit consensus actions to GenLayer Chain. A validator can receive different roles for different transactions. -## Overview +## Roles in a transaction -Validators are essential participants in the GenLayer network. They are responsible for validating transactions and maintaining the integrity and security of the blockchain. Validators play a crucial role in the Optimistic Democracy consensus mechanism, ensuring that both deterministic and non-deterministic transactions are processed correctly. +| Role | Main responsibility | Selection | +| --- | --- | --- | +| Activator | Advances the next queued transaction and fixes the seed used for committee selection. | Uniformly from the active validator set. | +| Leader | Executes the Intelligent Contract, proposes a receipt, and participates in voting. | Randomly from the selected committee, using stake-weighted selection. | +| Committee member | Evaluates the leader's receipt, commits an encrypted vote, and reveals it. | Randomly from the active set, weighted by validator selection weight. | -## Key Responsibilities +The leader is part of the committee. It runs both the leader path and the validator path, then commits and reveals its own vote. This keeps the voting set odd in a normal round. -- **Transaction Validation**: Validators verify the correctness of transactions proposed by the leader, using mechanisms like the Equivalence Principle for non-deterministic operations. -- **Leader Selection**: Validators participate in the process of randomly selecting a leader for each transaction, ensuring fairness and decentralization. -- **Consensus Participation**: Validators cast votes on proposed transaction outcomes, contributing to the consensus process. -- **Staking and Incentives**: Validators stake tokens to earn the right to validate transactions and receive rewards based on their participation and correctness. +The activator is a coordination role, not a proposer. When the activator is also selected for the committee, the protocol excludes it from leader selection. -## Validator Selection and Roles +## What a validator node does -- **Leader Validator**: For each transaction, a leader is randomly selected among the validators. The leader is responsible for executing the transaction and proposing the result to other validators. -- **Consensus Validators**: Other validators assess the leader's proposed result and vote to accept or reject it based on predefined criteria. +A node follows GenLayer Chain events and reads the consensus contracts to learn its assignments. It then: -## Becoming a Validator +1. reconstructs the relevant Intelligent Contract state; +2. executes the leader or validator path in GenVM; +3. signs and sends the required proposal, commit, or reveal transaction; and +4. monitors deadlines, appeals, epoch changes, and staking duties. -- **Staking Requirement**: Participants must stake a certain amount of tokens to become validators. -- **Validator Configuration**: Validators must configure their nodes with the appropriate LLM providers and models, depending on the network's requirements. -- **Reputation and Slashing**: Validators must act honestly to avoid penalties such as slashing of their staked tokens. \ No newline at end of file +Consensus actions are recorded on GenLayer Chain. Validators do not exchange offchain votes through a separate peer-to-peer consensus protocol. + +## Selection weight + +Committee selection is stake-weighted, but it is not directly proportional to raw stake. The protocol calculates a governance-configurable weight from self-stake and delegated stake: + +```text +weight = (alpha × self-stake + (1 - alpha) × delegated stake) ^ beta +``` + +Current defaults give self-stake more influence and apply sublinear damping so that selection probability grows more slowly than stake. See [staking](/understand-genlayer-protocol/core-concepts/optimistic-democracy/staking) for the current defaults and activation rules. + +## Liveness and accountability + +Each phase has an onchain timeout. If an assigned participant does not act, a permissionless idleness call can replace it, rotate the leader, or move the transaction to a timeout or undetermined decision. Repeated idleness, failure to reveal, or proven deterministic violations can cause exclusion and [slashing](/understand-genlayer-protocol/core-concepts/optimistic-democracy/slashing). + +To operate a node, use the [validator setup guide](/validators/setup-guide). diff --git a/pages/understand-genlayer-protocol/core-concepts/web-data-access.mdx b/pages/understand-genlayer-protocol/core-concepts/web-data-access.mdx index 76fe3b33..b7f6cbc1 100644 --- a/pages/understand-genlayer-protocol/core-concepts/web-data-access.mdx +++ b/pages/understand-genlayer-protocol/core-concepts/web-data-access.mdx @@ -1,28 +1,21 @@ --- -description: "Web Data Access in Intelligent Contracts lets GenLayer contracts fetch, validate, and use live web data without oracles." +description: "Learn how Intelligent Contracts retrieve web content and validate time-varying external data without a single oracle." --- -# Web Data Access in Intelligent Contracts +# Web access -Web Data Access in Intelligent Contracts is GenLayer's capability for contracts to directly retrieve and use web data without relying on oracles. This enables blockchain applications to respond to real-world events while validators use equivalence validation to check retrieved data for consistency. +Intelligent Contracts can retrieve web pages and HTTP resources inside non-deterministic blocks. This lets a contract evaluate public evidence without relying on one oracle to publish a preselected value. -## Overview +Direct access does not make web data deterministic or inherently trustworthy. Sources can change between requests, return personalized content, fail, or contain adversarial instructions. The contract must define which sources and evidence count and how validators assess the leader's result. -GenLayer enables Intelligent Contracts to directly access and interact with web data, removing the need for oracles and allowing for real-time data integration into blockchain applications. +## Validation patterns -## Key Features +- Retrieve the same source independently and compare a structured fact. +- Require multiple independent sources for a claim. +- Check provenance, timestamps, status codes, and expected content shape. +- Render a page when important information depends on client-side behavior. +- Return a defined failure result when evidence is unavailable or inconsistent. -- **Direct Web Access**: Contracts can retrieve data from web sources. -- **Dynamic Applications**: Access to web data allows for applications that respond to external events and real-world data. -- **Equivalence Validation**: Retrieved data is validated across validators to ensure consistency. +Prefer stable, authoritative sources and extract only the facts the contract needs. Where possible, validate hashes, signatures, or other objective evidence before using qualitative interpretation. -## Implementation - -1. **Data Retrieval Functions**: GenLayer provides mechanisms for fetching web data within contracts. -2. **Data Parsing and Validation**: Contracts must parse web data and validate it according to defined equivalence criteria. -3. **Security Measures**: Contracts should handle potential security risks such as untrusted data sources and ensure data integrity. - -## Considerations - -- **Network Dependencies**: Reliance on external web sources introduces dependencies that may affect contract execution. -- **Performance Impact**: Web data retrieval may introduce latency and affect transaction processing times. \ No newline at end of file +For current APIs and examples, see [web access](/developers/intelligent-contracts/features/web-access) and [non-determinism](/developers/intelligent-contracts/features/non-determinism). diff --git a/pages/understand-genlayer-protocol/optimistic-democracy-how-genlayer-works.mdx b/pages/understand-genlayer-protocol/optimistic-democracy-how-genlayer-works.mdx index 397cb99d..c92730ce 100644 --- a/pages/understand-genlayer-protocol/optimistic-democracy-how-genlayer-works.mdx +++ b/pages/understand-genlayer-protocol/optimistic-democracy-how-genlayer-works.mdx @@ -1,52 +1,82 @@ --- -description: "Optimistic Democracy: how GenLayer validators reach consensus, handle non-determinism, appeals, and finality." +description: "Follow an Intelligent Contract transaction through GenLayer Chain, GenVM execution, validator consensus, appeals, and finality." --- -import { Callout } from "nextra-theme-docs"; -# How GenLayer Works +# How GenLayer works -GenLayer works through **Optimistic Democracy**, a consensus mechanism where validators running diverse AI models independently evaluate transactions and vote on outcomes. This page explains the transaction lifecycle, how GenLayer reaches consensus on non-deterministic results from Intelligent Contracts, and how appeals lead to finality. +GenLayer separates **ordering and consensus state** from **Intelligent Contract execution**. Consensus contracts on GenLayer Chain coordinate the process. Validator nodes execute the contract in GenVM and report their actions back to the chain. -## Optimistic Democracy +## The three components -GenLayer uses **Optimistic Democracy** for consensus — a mechanism where validators running diverse AI models independently evaluate transactions and vote on outcomes. It applies [Condorcet's Jury Theorem](https://en.wikipedia.org/wiki/Condorcet%27s_jury_theorem): a group of independent reasoners is more likely to reach the correct answer than any individual. This is what lets GenLayer act as an **adjudication layer** for the agentic economy — judgments emerge from a diverse validator set rather than from any one model, operator, or jurisdiction. +| Component | Responsibility | +| --- | --- | +| GenLayer Chain | Orders EVM transactions and stores authoritative consensus state, assignments, votes, fees, and final outcomes. | +| Validator node | Watches chain events, maintains derived Intelligent Contract state, performs assigned consensus duties, and serves GenLayer RPC requests. | +| GenVM | Executes Intelligent Contracts in a WebAssembly sandbox, including isolated web and LLM operations. | -Transactions are accepted if a majority of validators agree. Anyone can appeal an accepted result, triggering re-evaluation by a new, larger validator set. This process can escalate through multiple rounds until a final decision is reached. +This design makes phase deadlines and the order of consensus actions objectively observable. A proposal, commit, reveal, or appeal is a transaction to a consensus contract—not a message in a separate validator network. -## Transaction Lifecycle +## Transaction lifecycle -Every transaction moves through these stages: +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 42, "rankSpacing": 48, "htmlLabels": true}}}%% +flowchart TB + Pending(["Pending"]) + Round["Proposal and
commit–reveal round"] + Decision{"Decided
outcome"} + Window["Appeal window"] + Review["Funded appeal
fresh review"] + Ready["Ready to finalize"] + Final(["Finalized"]) -1. **Pending** — queued, waiting to be picked up -2. **Proposing** — a leader validator executes the contract and proposes a result -3. **Committing** — other validators execute independently and submit encrypted votes -4. **Leader Revealing** — the leader reveals execution data and decryption keys -5. **Revealing** — validators reveal their votes -6. **Accepted** — majority consensus reached; transaction enters the appeal window -7. **Finalized** — appeal window closed, result is permanent and irreversible + Pending --> Round --> Decision --> Window + Window -->|"window elapses"| Ready --> Final + Window -->|"appeal"| Review + Review -->|"decision confirmed"| Window + Review -->|"decision overturned"| Round -If consensus is not reached, the transaction may be marked **Undetermined** or rotate to a new leader. + classDef phase fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef challenge fill:#FFF4E5,stroke:#D58A16,color:#583705,stroke-width:2px; + classDef success fill:#E9F8F0,stroke:#23966B,color:#123F30,stroke-width:2px; + class Pending,Round,Decision,Window phase; + class Review challenge; + class Ready,Final success; + linkStyle default stroke:#7C879C,stroke-width:1.8px; +``` -See [Transaction Execution](/understand-genlayer-protocol/core-concepts/transactions/transaction-execution) for the full state machine. +### 1. Submit and queue -## Non-Determinism and Consensus +A user or EVM contract sends a transaction to the Intelligent Contract's Ghost. The Ghost forwards the request to the consensus contracts, which assign a transaction ID and add it to the recipient's pending queue. Transactions for one Intelligent Contract are processed sequentially through the active consensus phases. -Because Intelligent Contracts use LLMs and web data, validators may produce different outputs for the same input. GenLayer provides several strategies for reaching consensus on non-deterministic results: +### 2. Activate and select -- **Strict equality** — all validators must produce the exact same output (for deterministic operations) -- **LLM-based comparison** — an LLM compares validator outputs against developer-defined criteria -- **Custom validation** — developers write explicit leader/validator function pairs with full control over consensus logic +The protocol selects one validator uniformly from the active set to be the **activator**. Activation fixes the transaction's seed and selects a stake-weighted committee and its leader. The activator is excluded from the leader selection when it is also in the selected committee. -See [Non-determinism](/developers/intelligent-contracts/features/non-determinism) for implementation details. +### 3. Propose -## Appeals and Finality +The leader runs the transaction in GenVM and proposes a receipt containing the execution result and state changes. The leader also runs the validator path and later votes as part of the committee. -After a transaction is accepted, it enters a **finality window** during which anyone can appeal the result. +### 4. Commit and reveal -- An appeal triggers a new round with a fresh, larger validator set -- Appeals can escalate through multiple rounds -- The final round's decision is binding +Every committee member evaluates the leader's proposal. Deterministic execution must match. For each non-deterministic block, the validator applies the equivalence rule chosen by the contract developer. -Once the finality window closes without appeal (or after the final appeal round), the transaction is **finalized** — permanent and irreversible. +Validators first commit encrypted votes. The leader then reveals its execution data and keys, after which the committee reveals its votes. This ordering prevents validators from adapting their votes to votes already made public. -See [Appeal Process](/understand-genlayer-protocol/core-concepts/optimistic-democracy/appeal-process) and [Finality](/understand-genlayer-protocol/core-concepts/optimistic-democracy/finality) for details. +### 5. Decide + +A majority can accept the leader's proposal. The round can instead end in a validator timeout, leader timeout, or an undetermined result. When disagreement can still be retried within the transaction's funded execution budget, the protocol rotates the leader and starts another proposal round. + +### 6. Appeal and finalize + +Decided transactions enter an appeal window. Validator appeals recheck an Accepted or ValidatorsTimeout decision with a fresh committee. Leader appeals restart execution after an Undetermined or LeaderTimeout decision. If no valid appeal remains, anyone can finalize the transaction. + +See [transaction execution](/understand-genlayer-protocol/core-concepts/transactions/transaction-execution), [appeals](/understand-genlayer-protocol/core-concepts/optimistic-democracy/appeal-process), and [finality](/understand-genlayer-protocol/core-concepts/optimistic-democracy/finality) for the detailed rules. + +## Why results can differ + +Web pages change, service responses vary, and LLMs do not always return identical text. GenLayer does not pretend these operations are deterministic. Instead, the contract divides execution into: + +- deterministic code, which validators reproduce exactly; and +- non-deterministic blocks, whose proposed outputs validators assess using the [Equivalence Principle](/understand-genlayer-protocol/core-concepts/optimistic-democracy/equivalence-principle). + +This makes the validation rule part of the application rather than an assumption hidden in infrastructure. diff --git a/pages/understand-genlayer-protocol/typical-use-cases.mdx b/pages/understand-genlayer-protocol/typical-use-cases.mdx index 2d56f295..04a58a20 100644 --- a/pages/understand-genlayer-protocol/typical-use-cases.mdx +++ b/pages/understand-genlayer-protocol/typical-use-cases.mdx @@ -1,70 +1,83 @@ --- -description: "GenLayer use cases for Intelligent Contracts that resolve subjective, evidence-based outcomes on-chain" +description: "Explore use cases where GenLayer can resolve shared outcomes from natural language, public evidence, and subjective criteria." --- -# Use Cases +# Use cases -GenLayer use cases are commitments where outcomes depend on judgment, such as evaluating evidence, interpreting language, or assessing quality, and where a deterministic smart contract alone cannot resolve them. +GenLayer is useful when an application needs a shared, enforceable outcome but the decision cannot be reduced to deterministic onchain data. The strongest use cases have explicit criteria, accessible evidence, meaningful consequences, and participants who benefit from a neutral appeal process. -If you are deciding whether a feature belongs on GenLayer or in a normal backend, start with the [builder fit checklist](/developers/intelligent-contracts/when-to-use-genlayer). +Use the [builder fit checklist](/developers/intelligent-contracts/when-to-use-genlayer) before choosing GenLayer over a conventional smart contract or backend. -The use cases below are grouped by where the need for adjudication is most acute today. +## Performance and milestone decisions -## 1. Performance & Milestone Adjudication +An Intelligent Contract can assess whether work satisfies a written specification and release an onchain outcome. -Payments, rewards, or recognition that depend on whether some obligation was actually fulfilled under criteria that are partly measurable and partly interpretive. The money is already on-chain. The commitment is already written down. The dispute already happens — and today it is resolved by human bottlenecks that do not scale. +Examples include: -- **Bounties** where payout depends on whether the work met the spec -- **Grant milestones** where tranche release turns on contested deliverables -- **Retroactive funding rounds** where allocation depends on impact assessment -- **Creator economies** where AI-scored rewards generate disputes with no resolution layer -- **Prediction markets** with subjective outcomes ([example contract](/developers/intelligent-contracts/examples/prediction)) -- **Contributor performance** tied to vesting or continued compensation -- **Freelance and gig work** — was the deliverable satisfactory? AI consensus replaces subjective back-and-forth -- **Chargebacks** — buyer/seller disputes resolved by analyzing shipping records, communication logs, and transaction history +- bounty payouts based on deliverable quality; +- grant tranches based on milestone evidence; +- freelance escrow based on acceptance criteria; +- service-level agreement claims; and +- retroactive funding based on documented impact. -GenLayer can support agreed dispute-resolution workflows, but it is not a court and does not automatically make a result legally binding. For legal or contractual use cases, parties still need the appropriate agreements, jurisdiction, and escalation process around the Intelligent Contract. +The contract should identify the authoritative submission, rubric, deadline, and behavior when evidence is unavailable. -## 2. Adjudication Inside the Agentic-Commerce Stack +## Markets and claims -GenLayer plugs into the infrastructure the industry is building right now: payment rails ([x402](https://www.x402.org/)), agent identity and reputation ([ERC-8004](https://eips.ethereum.org/EIPS/eip-8004)), agent-to-agent task exchange ([A2A](https://a2a-protocol.org)), plus Stripe/OpenAI's ACP, Visa's Trusted Agent Protocol, Google's AP2, and Mastercard's Agent Pay. Each standard ships the happy path and carves the moment of disagreement out as someone else's problem. GenLayer is that someone else. +Markets and coverage products often depend on a public event whose resolution still requires interpretation. -- **Agent-executed job disputes** — was the task delivered to spec? -- **Escrow release on ambiguous completion** — agent counterparties needing neutral resolution -- **SLA enforcement on agent work** — quality, latency, or scope claims -- **Reputation claims contested between counterparties** in ERC-8004-style identity systems -- **Coverage claims on agent-to-agent commitments** — parametric and evidence-based -- **Multi-agent workflows** where responsibility for failure has to be assigned across participants +Examples include: -## 3. Rule & Constitution Verification +- prediction markets with a natural-language resolution rule; +- flight, weather, or shipping claims based on several public sources; +- chargeback evidence from counterparties and carriers; and +- structured evaluation of insurance evidence. -Check whether something meets a set of criteria defined in natural language — a foundational primitive that many applications reduce to. +For high-value or regulated uses, GenLayer can implement the technical decision process, but it does not replace the legal agreements, licensing, jurisdiction, or human escalation a product may require. -- Does a new prediction market meet listing guidelines? -- Does a DAO proposal comply with the organization's charter? -- Does a content submission follow community standards? -- Does a transaction comply with regulatory requirements? +## Agent-to-agent commitments -## 4. Adjacent Surfaces +Autonomous agents can pay, exchange tasks, and report results, but a counterparty still needs a way to challenge incomplete or low-quality work. GenLayer can evaluate a task specification and its evidence, then settle escrow or update reputation. -The same primitive shows up across digital commerce: +Examples include: -- **Insurance** — parametric and evidence-based claims evaluated by AI validators. Contracts fetch weather data, flight statuses, or photographic evidence to assess claims and trigger payouts automatically — no adjusters, no weeks of waiting. -- **Social content verification** — AI validators assess quality, detect plagiarism, and distribute rewards based on originality and engagement. Replaces centralized moderation with consensus-driven evaluation. -- **Code & work quality assurance** — staked submissions where reviewers are economically incentivized to find issues; AI validators assess deliverable completeness or compliance with specifications. -- **AI-governed organizations** — DAOs where proposals are written in natural language, evaluated against real-time data, and executed automatically when conditions align. -- **Compliance automation** — real-time screening against sanctions lists, KYC/AML requirements, and changing regulations. Contracts read authoritative sources directly — no manual updates needed. -- **Argumentation and debate markets** — structured debates where participants stake positions and AI consensus determines outcomes, a new primitive for information markets. +- whether an agent-delivered job meets its requested scope; +- whether an API or agent met a service-level commitment; +- which participant caused a multi-agent workflow to fail; and +- whether a disputed reputation report is supported by evidence. -## What Makes These Possible +## Policy and rule evaluation -All of these share a common pattern: they require **judgment** that traditional smart contracts can't perform. GenLayer's Intelligent Contracts can: +Natural-language policies can guide an outcome while validators independently check the relevant evidence. -- Fetch and interpret live web data -- Process natural language and unstructured inputs -- Make subjective decisions through multi-validator AI consensus -- Execute outcomes on-chain with full finality — justice in minutes, not months +Examples include: -See [projects building on GenLayer](https://portal.genlayer.foundation/#/) for live examples. +- whether a DAO proposal complies with its charter; +- whether a submission meets community guidelines; +- whether a market satisfies listing rules; and +- whether a process followed a published policy. -[Start building →](/developers/intelligent-contracts/first-contract) +Avoid treating an LLM response as legal or compliance advice. Use authoritative data, encode objective checks where possible, and define who can update the governing policy. + +## Content and information assessment + +GenLayer can combine web retrieval, structured extraction, and qualitative validation for tasks such as: + +- plagiarism or attribution review; +- evidence-backed content classification; +- code or document review against a rubric; and +- summarizing public information into a structured decision. + +Store only the output the application needs. Large source documents and validator reasoning can be expensive, privacy-sensitive, and difficult to reproduce. + +## A common contract pattern + +Across these examples, a robust Intelligent Contract usually: + +1. fixes the question, eligible outcomes, evidence sources, and deadline; +2. retrieves or receives the evidence in a non-deterministic block; +3. returns a small, structured proposed result; +4. asks validators to check the result against independent evidence and explicit criteria; and +5. applies the accepted result through deterministic state changes or messages. + +[Build your first Intelligent Contract](/developers/intelligent-contracts/first-contract). diff --git a/pages/understand-genlayer-protocol/what-are-intelligent-contracts.mdx b/pages/understand-genlayer-protocol/what-are-intelligent-contracts.mdx deleted file mode 100644 index ae91ed6b..00000000 --- a/pages/understand-genlayer-protocol/what-are-intelligent-contracts.mdx +++ /dev/null @@ -1,5 +0,0 @@ -import { Callout } from "nextra-theme-docs"; - -# What Are Intelligent Contracts? - -This page has moved to [What is GenLayer](/understand-genlayer-protocol/what-is-genlayer). diff --git a/pages/understand-genlayer-protocol/what-is-genlayer.mdx b/pages/understand-genlayer-protocol/what-is-genlayer.mdx index f66c9cfd..0b536497 100644 --- a/pages/understand-genlayer-protocol/what-is-genlayer.mdx +++ b/pages/understand-genlayer-protocol/what-is-genlayer.mdx @@ -1,123 +1,90 @@ --- -description: "GenLayer is the first Intelligent Blockchain: smart contracts that natively access the web, call LLMs, and reach consensus on subjective, judgment-based decisions." +description: "GenLayer is an intelligent blockchain for applications that need consensus on subjective, web-connected decisions." --- -import { Callout } from "nextra-theme-docs"; +import { Card, Cards } from "nextra-theme-docs"; -# What is GenLayer +# What is GenLayer? -## The Adjudication Layer for the Agentic Economy +GenLayer is a blockchain for applications that need to make decisions from natural language, live web data, or other inputs that do not have one mechanically reproducible answer. -GenLayer uses decentralized AI-validator consensus to resolve contracts that require judgment, not just code. +Traditional smart contracts require every node to calculate exactly the same result. An **Intelligent Contract** can instead ask a group of validators whether a proposed result is acceptable. This lets applications put judgment-based rules onchain without trusting one AI model, data provider, or operator. -Intelligent Contracts interpret language, process unstructured data, and pull live web inputs. No oracles, no intermediaries. +## What GenLayer adds -- **Bitcoin** — Trustless Money -- **Ethereum** — Trustless Computation -- **GenLayer** — Trustless Adjudication +Intelligent Contracts can: -Where Bitcoin reached consensus on the *order* of transactions and Ethereum on the *execution* of code, GenLayer reaches consensus on the **meaning** of transactions. The technical primitive that makes this possible is the [Equivalence Principle](/developers/intelligent-contracts/features/non-determinism): two answers can be different in form yet equivalent in meaning, and a network of independent AI validators can agree on that. +- retrieve and interpret web content; +- use large language models (LLMs) to evaluate natural-language criteria; +- process unstructured inputs, such as text and images; and +- commit an accepted result to shared state. -## The Missing Layer +Different validators can receive different raw answers. The contract defines how validators judge whether the leader's answer is acceptable through the [Equivalence Principle](/understand-genlayer-protocol/core-concepts/optimistic-democracy/equivalence-principle). -The agentic-commerce stack is being built in the open — and every layer of it stops at the happy path. +## How the protocol fits together -| Layer | Standard | What it handles | Dispute resolution | -|---|---|---|---| -| Payments | [x402](https://www.x402.org/) (Coinbase) | Internet-native, agent-friendly payments | Not specified | -| Identity & reputation | [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) (Ethereum) | Trustless agent identity | Delegated to external validation protocols | -| Agent interoperability | [A2A](https://a2a-protocol.org) (Linux Foundation / Google) | How agents discover each other and exchange tasks | Not defined within the protocol | +GenLayer has three cooperating components: -Other players are stacking in alongside them — Stripe + OpenAI's ACP (already powering ChatGPT checkout), Visa's Trusted Agent Protocol, Google's AP2, Mastercard's Agent Pay + BVNK, and Tempo (Stripe / Paradigm L1). The shape is the same in every case: the payment goes through, the job is accepted, the reputation is updated — and the moment a single material dispute appears, the stack reaches for a function it does not have. +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 44, "rankSpacing": 52, "htmlLabels": true}}}%% +flowchart TB + User(["User or application"]) + Ghost["Ghost contract
EVM entry point"] + Consensus["Consensus contracts
order and assign work"] + Node["Validator node
observe and coordinate"] + VM["GenVM
execute or validate"] + State(["Consensus state updated"]) -That function is **adjudication**. Not a sovereign court. A credible, machine-speed mechanism for evaluating contested commitments, weighing evidence, interpreting language, reaching a verdict, and attaching consequences to it. + User -->|"submit transaction"| Ghost + Ghost --> Consensus + Consensus -->|"publish assignment"| Node + Node -->|"run contract"| VM + VM -->|"proposal or vote"| State -GenLayer is that layer. - -## What Intelligent Contracts Can Do - -### Subjective Decisions -Evaluate context and nuance. Turn judgment calls into enforceable on-chain outcomes — content moderation, claim assessment, quality evaluation. - -### Internet Access -Fetch live web data directly on-chain. Contracts can read websites, call APIs, and verify real-world information without oracles or intermediaries. - -### Natural Language Processing -Interpret human-readable inputs via LLMs. Contracts can analyze text, extract meaning, and make decisions based on qualitative criteria. - -### Image & Visual Processing -Pass images to LLMs for analysis — screenshot a webpage and verify its content, check visual evidence for claims, analyze receipts or documents. Contracts can capture screenshots via `gl.nondet.web.render()` and send them to LLMs via `gl.nondet.exec_prompt(images=[...])`. - -### Unstructured Data -Process text, images, audio transcripts, and qualitative evidence. Handle real-world complexity that traditional smart contracts cannot. - -## How It Compares - -| Feature | Traditional Smart Contracts | Intelligent Contracts | -|---|---|---| -| **Language** | Solidity, Rust | Python | -| **Data sources** | On-chain only (or oracles) | On-chain + live web data | -| **Decision logic** | Deterministic only | Deterministic + subjective | -| **AI integration** | Not possible | Native LLM access (text + images) | -| **Consensus** | All nodes must agree on exact output | Validators assess equivalence of results | - -## Architecture: Two Layers - -GenLayer operates as two integrated layers: - -**GenLayer Chain** — an EVM-compatible L2 (zkSync Elastic Chain). Holds account balances via ghost contracts, handles standard Ethereum operations (`eth_*` methods), and anchors to Ethereum's security model. - -**GenVM** — the execution environment for Intelligent Contracts. A WebAssembly-based VM (built on [Wasmtime](https://wasmtime.dev)) that runs a Python interpreter with native access to LLMs, web data, and non-deterministic operations. Can also execute compiled native code. + classDef actor fill:#F7F8FC,stroke:#8B95A7,color:#202536,stroke-width:1.5px; + classDef chain fill:#EFEDFF,stroke:#6D5DF5,color:#251E63,stroke-width:2px; + classDef compute fill:#EAF7FF,stroke:#2686C4,color:#113F59,stroke-width:2px; + class User actor; + class Ghost,Consensus,State chain; + class Node,VM compute; + linkStyle default stroke:#7C879C,stroke-width:1.8px; +``` -Every Intelligent Contract has a corresponding **ghost contract** on the chain layer at the same address. Ghost contracts hold the contract's GEN balance, relay transactions to consensus, and execute external messages. See [Messages](/developers/intelligent-contracts/features/messages#ghost-contracts) for details. +### GenLayer Chain -Transactions enter via `addTransaction` on the chain layer. GenVM executes the contract logic. Results settle back on-chain. +GenLayer Chain is an EVM-compatible ZK Stack chain. Solidity consensus contracts record transaction order, committee assignments, votes, appeals, and final outcomes. For the consensus process, this onchain state is authoritative. -## Develop in Python +### Validator nodes -Intelligent Contracts are Python classes extending `gl.Contract`: +Validator nodes watch the chain, perform their assigned duties, execute Intelligent Contracts in GenVM, and submit proposals or votes as EVM transactions. Validators do not run a separate peer-to-peer consensus network for Intelligent Contract outcomes. -```python -# { "Depends": "py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6" } -from genlayer import * -import json +### GenVM -class WizardOfCoin(gl.Contract): - has_coin: bool +GenVM is a WebAssembly-based sandbox for Intelligent Contracts. It keeps ordinary contract execution reproducible and runs web or LLM operations in isolated non-deterministic blocks. The leader proposes a result, and the selected validators apply the contract's validation rule to that proposal. - def __init__(self): - self.has_coin = True +Each Intelligent Contract has a **Ghost contract** at the same address on GenLayer Chain. The Ghost receives EVM transactions, holds the contract's native-token balance, and routes messages between the EVM and GenVM sides. - @gl.public.write - def ask_for_coin(self, request: str) -> None: - if not self.has_coin: - raise gl.vm.UserError("I don't have a coin!") +## From submission to finality - prompt = f""" - You are a wizard guarding a gold coin. - An adventurer says: {request} - Should you give them the coin? - Respond as JSON: {{"give_coin": true/false}} - """ +1. A user sends an EVM transaction to an Intelligent Contract's Ghost. +2. The consensus contracts queue the transaction and select an activator, leader, and validator committee. +3. The leader executes the Intelligent Contract in GenVM and proposes a receipt. +4. The committee executes the validator path, commits encrypted votes, and then reveals them. +5. The protocol records the decision and opens an appeal window. +6. If nobody successfully appeals, the transaction becomes final. - def leader_fn(): - return gl.nondet.exec_prompt(prompt, response_format="json") +An **Accepted** transaction is one whose proposed outcome reached consensus. It does not necessarily mean the contract returned successfully: validators can agree that an error is the correct execution result. - def validator_fn(leaders_res) -> bool: - if not isinstance(leaders_res, gl.vm.Return): - return False - my_result = leader_fn() - return my_result["give_coin"] == leaders_res.calldata["give_coin"] + + + + + - result = gl.vm.run_nondet_unsafe(leader_fn, validator_fn) - if result["give_coin"]: - self.has_coin = False +## When to use GenLayer - @gl.public.view - def get_has_coin(self) -> bool: - return self.has_coin -``` +GenLayer is a fit when an outcome must be shared and enforceable, but determining it requires interpreting evidence or criteria. Examples include resolving a prediction market, assessing whether work meets a specification, or evaluating a claim from public sources. -Full SDK available: [genlayer-js](/api-references/genlayer-js) (TypeScript), [genlayer-py](/api-references/genlayer-py) (Python), [CLI](/api-references/genlayer-cli). +Use a conventional smart contract for rules that can be expressed entirely as deterministic computation. Use a conventional backend when no shared, adversarially verifiable outcome is needed. -[Get started →](/developers/intelligent-contracts/first-contract) +See [common use cases](/understand-genlayer-protocol/typical-use-cases) and the [builder fit checklist](/developers/intelligent-contracts/when-to-use-genlayer). diff --git a/pages/understand-genlayer-protocol/what-makes-genlayer-different.mdx b/pages/understand-genlayer-protocol/what-makes-genlayer-different.mdx deleted file mode 100644 index 7bab8320..00000000 --- a/pages/understand-genlayer-protocol/what-makes-genlayer-different.mdx +++ /dev/null @@ -1,5 +0,0 @@ -import { Callout } from "nextra-theme-docs"; - -# What Makes GenLayer Different? - -This page has moved to [What is GenLayer](/understand-genlayer-protocol/what-is-genlayer). diff --git a/pages/understand-genlayer-protocol/who-is-genlayer-for.mdx b/pages/understand-genlayer-protocol/who-is-genlayer-for.mdx deleted file mode 100644 index 3e2dfe88..00000000 --- a/pages/understand-genlayer-protocol/who-is-genlayer-for.mdx +++ /dev/null @@ -1,5 +0,0 @@ -import { Callout } from "nextra-theme-docs"; - -# Who Is GenLayer For? - -This page has moved to [What is GenLayer](/understand-genlayer-protocol/what-is-genlayer). diff --git a/pages/understand-genlayer-protocol/why-we-are-building-genlayer.mdx b/pages/understand-genlayer-protocol/why-we-are-building-genlayer.mdx deleted file mode 100644 index 53cbc4a9..00000000 --- a/pages/understand-genlayer-protocol/why-we-are-building-genlayer.mdx +++ /dev/null @@ -1,5 +0,0 @@ -import { Callout } from "nextra-theme-docs"; - -# Why We Are Building GenLayer - -This page has moved to [What is GenLayer](/understand-genlayer-protocol/what-is-genlayer). diff --git a/scripts/check-protocol-docs.js b/scripts/check-protocol-docs.js new file mode 100644 index 00000000..17740b5c --- /dev/null +++ b/scripts/check-protocol-docs.js @@ -0,0 +1,130 @@ +const fs = require("fs"); +const path = require("path"); + +const ROOT = process.cwd(); +const UNDERSTAND = path.join(ROOT, "pages", "understand-genlayer-protocol"); +const failures = []; + +function walk(directory) { + return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const fullPath = path.join(directory, entry.name); + return entry.isDirectory() ? walk(fullPath) : [fullPath]; + }); +} + +function relative(file) { + return path.relative(ROOT, file); +} + +const landingPage = path.join(ROOT, "pages", "understand-genlayer-protocol.mdx"); +const pages = [landingPage, ...walk(UNDERSTAND).filter((file) => file.endsWith(".mdx"))]; + +for (const file of pages) { + const content = fs.readFileSync(file, "utf8"); + + if (!content.startsWith("---\n")) { + failures.push(`${relative(file)}: missing frontmatter`); + } + + if (/!\[\]\(/.test(content)) { + failures.push(`${relative(file)}: Markdown image has empty alternative text`); + } + + for (const imageTag of content.match(//g) || []) { + if (!/\balt=/.test(imageTag)) { + failures.push(`${relative(file)}: Image component is missing alt`); + } + } + + const localRoutes = [ + ...Array.from(content.matchAll(/\]\((\/[^)\s#]+)(?:#[^)]*)?\)/g), (match) => match[1]), + ...Array.from(content.matchAll(/\bhref=["'](\/[^"'#?]+)(?:[?#][^"']*)?["']/g), (match) => match[1]), + ]; + for (const localRoute of localRoutes) { + const route = localRoute.replace(/\/$/, ""); + const candidates = [ + path.join(ROOT, "pages", `${route}.mdx`), + path.join(ROOT, "pages", `${route}.cmdx`), + path.join(ROOT, "pages", route, "index.mdx"), + ]; + if (!candidates.some(fs.existsSync)) { + failures.push(`${relative(file)}: unresolved internal link ${localRoute}`); + } + } +} + +const legacyLinkPattern = /(?:\]\(|href=["'])\/(?:core-concepts|about-genlayer)(?:\/|[)"'])/; +for (const file of pages) { + if (legacyLinkPattern.test(fs.readFileSync(file, "utf8"))) { + failures.push(`${relative(file)}: uses a legacy route instead of its canonical URL`); + } +} + +const staleClaims = [ + ["OutOfFee", "obsolete OutOfFee transaction status"], + ["each round doubles", "obsolete appeal committee growth claim"], + ["pay for all validators", "unsupported fast-finality claim"], +]; +for (const file of pages) { + const content = fs.readFileSync(file, "utf8").toLowerCase(); + for (const [text, description] of staleClaims) { + if (content.includes(text.toLowerCase())) { + failures.push(`${relative(file)}: contains ${description}`); + } + } +} + +const statuses = [ + "Uninitialized", + "Pending", + "Proposing", + "Committing", + "Revealing", + "Accepted", + "Undetermined", + "Finalized", + "Canceled", + "AppealRevealing", + "AppealCommitting", + "ReadyToFinalize", + "ValidatorsTimeout", + "LeaderTimeout", + "LeaderRevealing", +]; +const statusTables = [ + path.join(UNDERSTAND, "core-concepts", "transactions", "transaction-statuses.mdx"), + path.join(ROOT, "pages", "api-references", "genlayer-node", "gen", "gen_getTransactionStatus.mdx"), +]; +for (const statusTable of statusTables) { + const content = fs.readFileSync(statusTable, "utf8"); + for (const [code, status] of statuses.entries()) { + const readableName = status.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase(); + const conceptRow = `| ${code} | \`${status}\` |`; + const apiRow = `| ${code} | ${readableName} |`; + if (!content.includes(conceptRow) && !content.includes(apiRow)) { + failures.push(`${relative(statusTable)}: missing status ${code} ${status}`); + } + } +} + +const removedStubs = [ + "what-are-intelligent-contracts.mdx", + "what-makes-genlayer-different.mdx", + "who-is-genlayer-for.mdx", + "why-we-are-building-genlayer.mdx", +]; +for (const stub of removedStubs) { + if (fs.existsSync(path.join(UNDERSTAND, stub))) { + failures.push(`${stub}: replace moved-page stub with a redirect`); + } +} + +if (failures.length) { + console.error("check-protocol-docs: FAILED"); + for (const failure of failures) console.error(` - ${failure}`); + process.exit(1); +} + +console.log( + `check-protocol-docs: OK (${pages.length} concept pages, ${statuses.length} transaction statuses)`, +);