Web3 Version Control System for Smart Contracts with AI auditing, Gas optimization and monitoring.
Markov: A Web3 Version Control System for Smart Contracts Markov is an innovative open-source Hardhat plugin designed to revolutionize how developers manage and upgrade smart contracts on Ethereum and compatible blockchains. Launched in October 2025 (version 1.0.0), it functions as a Git-like version control system (VCS) tailored specifically for ERC-2535 Diamond standard contracts. At its core, Markov treats smart contract upgrades as "commits," leveraging the modular nature of Diamonds to enable fine-grained, auditable, and reversible changes without full redeployments. This addresses key challenges in Web3 development, such as contract immutability, upgrade risks, and lack of historical traceability, while integrating advanced AI and monitoring capabilities for enhanced safety and efficiency. Built by community contributors xavio2495 and charlesms1246 under the MIT license, Markov is hosted on GitHub (https://github.com/xavio2495/MARKOV) and emphasizes developer productivity through a familiar CLI interface. It supports multi-chain environments, making it ideal for building complex, upgradeable decentralized applications (dApps) in DeFi, DAOs, or other protocols. Unlike traditional tools focused on basic deployments, Markov provides a full lifecycle management system, combining versioning, AI-driven analysis, simulation, and real-time on-chain monitoring. Project Aims Markov's primary goals are rooted in making smart contract development more modular, secure, and intelligent:
Enable Git-Like Versioning for Diamonds: Use ERC-2535's facet-based modularity to track upgrades as commits, with branching for parallel experimentation and merging for integration. Integrate AI for Developer Assistance: Provide AI agents for auditing Solidity code (detecting vulnerabilities like reentrancy or overflows) and optimizing gas usage (e.g., variable packing or loop unrolling). Support Simulation and Predictive Analysis: Work with Hardhat's network simulator to forecast deployment outcomes, enhanced by AI for identifying edge cases. Offer Autonomous On-Chain Monitoring: Deploy AI agents using Model Context Protocol (MCP) to track contract activities in real-time, generating reports and alerts via CLI. Ensure Multi-Chain Compatibility and Traceability: Support chains like Ethereum, Polygon, Optimism, and Arbitrum, with bi-directional history tracing through blockchain explorers. Promote Safety and Efficiency: Incorporate simulations, hybrid history syncing, and governance proposals to minimize risks and costs.
These aims position Markov as a "Developer Tool" in the Web3 ecosystem, filling gaps in existing frameworks by blending traditional VCS concepts with blockchain-specific needs. Core Features Markov offers a rich set of features accessible via CLI commands (npx hardhat markov <subcommand>), making it extensible and user-friendly. Here's a comprehensive breakdown:
Version Control Fundamentals:
Initialization (markov init): Deploys a base Diamond contract with essential facets (e.g., DiamondCutFacet for upgrades, DiamondLoupeFacet for inspections) and initializes the history log. Deployment (markov deploy): Builds and deploys new/updated facets, executes diamondCut to add/replace/remove functions atomically, and logs the commit only after successful on-chain confirmation. Supports custom commit messages and optional initialization calldata. Reset/Revert (markov reset): Computes a reversing diamondCut from a prior commit (e.g., removing added facets), simulates it for safety, and applies it to rollback the contract state. Logging and Syncing (markov log, markov sync): Displays commit history (tx hashes, timestamps, messages, facet changes) from local JSON; syncs with on-chain DiamondCut events via viem's getLogs or Blockscout MCP for verification, ensuring no desyncs. Cloning (markov clone): Replicates a Diamond from another chain/address by querying loupe facets (e.g., facets() to get current structure) and redeploying equivalents.
Branching and Collaboration:
Branch Management (markov branch <create|switch|list>): Creates/switches/lists branches, each mapped to a separate chain (e.g., dev on Sepolia testnet, main on Ethereum). This isolates experiments without risking production. Merging (markov merge <branch>): Combines facet changes from branches, automatically resolving selector conflicts (e.g., prioritizing main branch) and simulating the merged cut.
AI-Driven Developer Tools:
Analysis (markov analyze): Scans Solidity files or facets for vulnerabilities (e.g., reentrancy, integer overflows, access control flaws) using an AI agent powered by Fetch.ai uAgents and ASI:One LLM. Provides detailed reports with code snippets and fixes. Optimization (markov optimize): Analyzes code for gas inefficiencies and suggests/applies improvements (e.g., using uint256 packing, inlining functions). Integrates with ASI:One for natural language queries like "Optimize this loop for gas." Simulation (markov simulate <scenario>): Forks the chain via Hardhat's anvil, runs tx/deploy simulations with viem, and uses AI to predict outcomes (e.g., "What if gas price spikes?"). Generates reports with gas breakdowns and visual charts.
Monitoring and Analytics:
Autonomous Agent Management (markov agent <start|stop|report>): Deploys a background AI agent using Fetch.ai uAgents for autonomy and MCP (via Blockscout server at https://mcp.blockscout.com/mcp) for data access. Monitors Diamond events/transactions in real-time (e.g., using MCP tools like get_transaction_logs or transaction_summary), detects anomalies (e.g., unusual gas usage), and generates CLI reports or summaries. Registered on Agentverse for discoverability and integration with ASI:One LLM for advanced queries. Statistics (markov stats): Aggregates analytics from history and on-chain data (e.g., gas spent per commit, upgrade frequency) using viem and MCP tools. Migration (markov migrate): Automates state migration scripts during upgrades, analyzing storage changes with AI. Visualization (markov viz): Generates ASCII graphs of facet structures and commit histories for quick overviews. Proposal (markov propose): Submits diamondCut changes to on-chain governance (e.g., DAO via Governor contracts) for community approval.
Configuration and Safety:
Setup (markov config): Configures wallet, chain, gas prices, author details, AI/MCP/Agentverse API keys in hardhat.config.ts. Status Check (markov status): Performs health checks via loupe facets (e.g., lists current facets/selectors, verifies no clashes). Safety Mechanisms: All deploys/resets include mandatory simulations (--simulate flag); hybrid syncing prevents tampering; hashes ensure commit integrity.
Architecture and Implementation Details Markov is built as a Hardhat 3 plugin, extending its config and tasks. Key components:
History Management: Uses a simple DAG structure in local .markov/history.json (arrays per branch, maps for lookups). Commits are objects with txHash as ID, linked via parentHash. Synced bi-directionally: Forward from genesis event, backward from latest via block sorting. Data Structures: Commit interface includes branch, chainId, facets array (action: add/replace/remove, selectors). FacetCut enum: 0=Add, 1=Replace, 2=Remove. Integrations:
Viem/Hardhat: For deployments (deployContract), simulations (simulateContract), and event queries (getLogs). AI Agents: Python-based Fetch.ai uAgents (deployed separately, called from TS via subprocess or API). Agents use ASI:One LLM for processing; registered on Agentverse for natural language access. MCP Monitoring: Connects to Blockscout MCP server (HTTP mode) for tools like get_address_info (balances/tags), transaction_summary (human-readable txs), and get_transaction_logs (events). uAgents orchestrate polling and analysis. Dependencies: Hardhat 3.x, viem, @langchain/openai, @modelcontextprotocol/typescript-sdk (MCP), @fetchai/uagents (via Python bridge), fs-extra, crypto, inquirer.
Workflow Example: User runs markov deploy → Simulate cut → Execute on branch chain → Log event → Sync to local → Agent monitors and reports.
Uniqueness and Advantages Markov stands out in the Developer Tool category by being the first to apply Git metaphors to Diamonds with AI enhancements—competitors like OpenZeppelin Upgrades (proxy-focused, no AI) or Foundry (testing-only) lack its depth. It's feature-rich: Only Markov offers AI auditing/simulation, MCP monitoring, and branching as chains. Pros include gas savings (10-20% via AI), reduced risks (simulations prevent exploits), and traceability (bi-directional via explorers). As of 2025, with EVM chains proliferating, its multi-chain support and autonomous agents make it essential for scalable dApp development. For more, check the GitHub repo, docs, or run npx hardhat markov --help. This project empowers developers to build upgradeable, intelligent contracts with confidence.
Markov is an open-source Hardhat plugin (built in TypeScript, version 1.0.0 as of October 2025) that reimagines version control for smart contracts using the ERC-2535 Diamond standard. We (contributors xavio2495 and charlesms1246) developed it over several months as a community project on GitHub, starting from the Hardhat 3 plugin template to ensure seamless integration with existing Ethereum dev workflows. The goal was to create a "Git for Web3" that treats contract upgrades as commits, with AI smarts for safety and real-time monitoring—addressing pain points like immutable code risks, opaque histories, and manual audits in DeFi/DAO projects.
We bootstrapped from the official Hardhat 3 template (via npx hardhat init), which provides extensible config, tasks, and hooks. This forms the backbone: Hardhat handles compilation, testing, and network management, while we extend it with custom types (src/type-extensions.ts) for Markov config (e.g., chain, wallet, AI keys) and hooks for validation/resolution (src/hooks/config.ts).
Core Versioning Logic (src/history.ts): Implements a hybrid DAG for history. Off-chain: MongoDB or JSON file stores commits as objects (txHash as ID, facets array, parent links). On-chain: Syncs via viem's getLogs for DiamondCut events (parsed with parseAbi). Pieced together: Post-deploy, tx receipts trigger event parsing and DB insert; sync queries explorers (e.g., Blockscout API) for bi-directional traceability (forward from genesis block, backward from latest via block sorting). Hacky bit: To handle branching as separate chains, we map branches to chain configs—e.g., dev on Sepolia (cheap tests), main on Ethereum—switching RPCs dynamically. This isolates risks but required custom chainId resolution in config to avoid Hardhat defaults.
Deployment/Upgrade Pipeline (src/tasks/markov-deploy.ts et al.): Uses viem (@nomicfoundation/hardhat-viem) for all chain ops—simulateContract for dry-runs (safety net against reverts/exploits), writeContract for diamondCut execution. Facet selectors computed via viem's abi utils (e.g., keccak256(signature)). Integration: Tasks hook into Hardhat's runtime env (hre), pulling artifacts from contracts/ (assumes Solidity files like Diamond.sol). For resets, we reverse-engineer cuts from history (e.g., swap add/remove actions). Pieced: Subprocess calls to Python for AI pre-checks (see below).
AI Integrations (src/ai.ts and Python agents): LangChain (@langchain/openai) for prompting OpenAI/ASI:One models (e.g., "asi1-mini" via https://api.asi1.ai/v1). Agents built in Python (Fetch.ai uAgents framework: pip install uagents) as autonomous scripts—e.g., analysis agent audits code with @agent.on_message handlers, prompting ASI:One for vulns/gas opts. Pieced: TS plugin spawns Python subprocess (child_process.spawn('python', ['agent.py'])) for agent runs, passing Solidity via stdin/stdout. Hacky: Bridged languages due to uAgents' Python focus—no native TS SDK, so we use JSON pipes for data exchange. Benefits: ASI:One (partner tech from Fetch.ai) provides cheap, fast LLM for natural queries; uAgents add autonomy (e.g., interval polling for sims).
Monitoring Agent (src/agent.ts and Python): Autonomous uAgent script monitors via Model Context Protocol (MCP) with Blockscout server (https://mcp.blockscout.com/mcp). Tools like get_transaction_logs fetch events; ASI:One summarizes anomalies. Pieced: TS starts/stops the Python agent as background process; registers on Agentverse (mailbox=True) for discoverability. Hacky: For real-time, we use uAgents' @on_interval to poll MCP every 60s (no websockets in basic setup), with fallback to viem's watchEvent. Partner benefit: Blockscout MCP (open-source, multi-chain) abstracts 1,000+ EVM chains, reducing custom RPC code; Fetch.ai uAgents enable decentralized orchestration (e.g., multi-agent for query/analysis split).
Other Features:
src/history.ts, branches are DB maps; merging traverses DAGs, resolves selector clashes by priority (hacky: custom conflict UI via inquirer prompts).hre.network.fork), runs viem sims, feeds to AI agent for predictions.Overall piecing: Hardhat as orchestrator; viem for blockchain; Python agents for AI/MCP (bridged via subprocess—hacky but effective for ecosystem leverage). Total lines: ~2,500 TS + 1,000 Python. Challenges: Language bridging added latency (mitigated by async); MCP polling vs. subscriptions (future: websockets). Partner tech (Fetch.ai/Blockscout) benefited by providing ready AI/blockchain bridges—saved weeks on custom impls, enabled multi-chain without boilerplate. Notable hack: For bi-directional traceability, we derive parent links from event timestamps/blockNumbers, querying explorers only on sync to avoid RPC spam. This makes Markov robust for production dApps.

