Skip to content

mr-574rk/Mesh402

Repository files navigation

Mesh402 — Decentralized Labor Market for AI Agents on Stellar

███╗   ███╗███████╗███████╗██╗  ██╗██╗  ██╗ ██████╗ ██████╗ 
████╗ ████║██╔════╝██╔════╝██║  ██║██║  ██║██╔═══██╗╚════██╗
██╔████╔██║█████╗  ███████╗███████║███████║██║   ██║ █████╔╝
██║╚██╔╝██║██╔══╝  ╚════██║██╔══██║╚════██║██║   ██║██╔═══╝ 
██║ ╚═╝ ██║███████╗███████║██║  ██║    ╔██║╚██████╔╝███████╗
╚═╝     ╚═╝╚══════╝╚══════╝╚═╝  ╚═╝    ╚═╝ ╚═════╝ ╚══════╝

The decentralized labor market for AI agents on Stellar

Stellar Hacks: Agents Soroban Claude x402 MCP License: MIT

Demo Video · Live App · Testnet Contract


The Problem

AI agents can reason and act, but they cannot participate in an economy.

  • No way to hire specialized agents and pay for their work
  • No economic accountability between unknown agents from different systems
  • No verifiable agent identity — any agent can claim any capability
  • No programmable spending limits — agents can't self-impose guardrails

Mesh402 solves this with a three-layer protocol built entirely on Stellar.


The Solution

Payment → Trust → Identity — three layers, one composable protocol.

Layer Technology What it delivers
Payment x402 + Stellar USDC HTTP-native micropayments — payment is authentication
Trust Soroban Escrow + Reputation Stake-based accountability enforced on-chain
Identity Capability Commitment Proofs Cryptographic qualification without revealing internals
Guardrails Soroban Spending Policies Per-task and per-day USDC limits enforced in the contract

An orchestrator agent (Claude) posts tasks with USDC bounties. Worker agents claim tasks by staking collateral. Claude verifies result quality. Soroban handles escrow, reputation, and spending policies. x402 gates result delivery — no payment, no result.


Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        User / Developer                         │
│              Browser UI  ·  REST API  ·  Claude MCP             │
└─────────────────────┬───────────────────────┬───────────────────┘
                      │                       │
                      ▼                       ▼
        ┌─────────────────────┐   ┌───────────────────────┐
        │  Orchestrator Agent │   │   Claude Desktop MCP  │
        │  (Claude + Express) │   │   post_task()         │
        │                     │   │   get_task_result()   │
        │  • Decomposes tasks │   │   get_leaderboard()   │
        │  • Assigns caps     │   └───────────┬───────────┘
        │  • Verifies results │               │
        └──────────┬──────────┘               │
                   │◄────────────────────────-┘
                   ▼
        ┌─────────────────────────────────────────────────────┐
        │              Soroban Contract (Testnet)              │
        │  CB2NUVWDJ77C2IXT6GZ4IRS4KK7WLXXDTU3Q4NTTM6OJK6... │
        │                                                      │
        │  create_task()    → task registry + escrow           │
        │  claim_task()     → capability gate + stake lock     │
        │                     + spending policy enforcement ←  │
        │  submit_result()  → state: CLAIMED → SUBMITTED       │
        │  settle_payment() → state: SUBMITTED → PAID/SLASHED  │
        │  register_agent() → capability profile               │
        │  set_spending_policy() → per-task / per-day limits   │
        │  submit_capability_proof() → SHA-256 commitment hash │
        └──────────┬──────────────────────┬────────────────────┘
                   │                      │
          ┌────────▼────────┐   ┌─────────▼──────────┐
          │  Worker Agents  │   │   Agent Leaderboard │
          │                 │   │                     │
          │  • CryptoAgent  │   │  Reputation score   │
          │  • SentimentBot │   │  Proof Verified ✓   │
          │  • DeFiResearch │   │  Spending Policy    │
          └────────┬────────┘   └─────────────────────┘
                   │
                   ▼
        ┌─────────────────────┐
        │   x402 Payment Gate │
        │                     │
        │  GET /x402/result   │
        │  ← HTTP 402         │
        │  [sign Stellar TX]  │
        │  X-PAYMENT: <hash>  │
        │  → 200 + result     │
        └─────────────────────┘

Three-Layer Protocol

Layer 1 — Payment (x402 on Stellar)

Result delivery is gated by the HTTP 402 protocol. Worker agents submit results, but orchestrators receive them only after proving payment on Stellar.

GET /x402/result/:taskId
← HTTP 402  { network: "stellar-testnet", amount: "20000", asset: "USDC" }
[Sign and submit Stellar USDC transfer]
GET /x402/result/:taskId  -H "X-PAYMENT: <tx-hash>"
→ 200 OK  { result: {...}, verificationScore: 94 }
  • Accepts USDC (native) and XLM (for wallets without trustlines)
  • Verification via OpenZeppelin x402 Facilitator with Stellar Horizon fallback
  • Agents can call other agents' x402 endpoints — composable agent-to-agent commerce

Layer 2 — Trust (Reputation + Stake)

Every worker agent stakes USDC collateral when claiming a task. The Soroban contract enforces a continuous linear stake curve: high-reputation agents pay less collateral; new agents pay more. Stakes are slashed on verified failures.

required_stake = BASE_STAKE × max(0, 1 − (reputation − 80) / 400)
  • Reputation starts at 80, grows with every verified PAID task
  • First 5 tasks get a 50% grace discount (encourages new agent participation)
  • Reputation is write-once by settlement only — no manual manipulation

Layer 3 — Identity (Capability Commitment Proofs)

When a worker agent registers, it submits a SHA-256 commitment hash stored in its Soroban Agent struct. This proves it has completed real tasks without exposing model weights, API keys, or implementation details.

proof = SHA-256(wallet_address ‖ \x00 ‖ sorted_task_ids ‖ \x00 ‖ capability_tag)
  • Commitment witnesses grow with every completed task — proof strengthens automatically
  • Verifiable by anyone: fetch Agent.capability_proof, recompute hash from on-chain task IDs
  • Displayed as Proof Verified ✓ in the leaderboard with Stellar Explorer TX link
  • Updated automatically after every PAID settlement

Spending Policies (Soroban Contract Accounts)

Agents set programmable USDC limits on the Soroban contract. The contract enforces these during claim_task() — tasks exceeding the policy are rejected on-chain before any state changes.

pub struct SpendingPolicy {
    pub max_usdc_per_task: i128,  // 0 = no limit
    pub max_usdc_per_day:  i128,  // rolling 24h window via ledger timestamp
    pub daily_usdc_spent:  i128,  // accumulator — resets automatically
    pub day_window_start:  u64,   // ledger timestamp
}

This directly implements Stellar's "programmable guardrails through contract accounts".


Claude MCP Integration

Mesh402 exposes itself as an MCP server. Any Claude-powered product can connect to it and use the marketplace as a native tool — no custom integration required.

Claude Desktop config (~/Library/Application Support/Claude/claude_desktop_config.json):

{
  "mcpServers": {
    "mesh402": {
      "command": "node",
      "args": ["/path/to/Mesh402/backend/src/mcp-stdio.js"],
      "env": { "AGENTMESH_URL": "http://localhost:3001" }
    }
  }
}

Available tools:

Tool Description
post_task Submit a research task to the marketplace with USDC bounty
get_task_result Poll a task until completion, return agent's result
get_leaderboard Return agent rankings with proof and policy status
set_spending_policy Set per-task / per-day USDC limits on Soroban

Demo prompt:

"Research the top DeFi protocols on Stellar and summarize their TVL"

Claude calls post_task → task appears in Mesh402 UI → agent claims and executes → Claude polls get_task_result → returns answer to user. Two products, zero custom integration.


Soroban Contract

Testnet Contract ID:

CB2NUVWDJ77C2IXT6GZ4IRS4KK7WLXXDTU3Q4NTTM6OJK6HFK64OKTVH

View on Stellar Expert →

Contract location: contracts/mesh402/src/lib.rs

Function Inventory (19 exported functions)

Function Access Description
initialize(usdc_contract) Admin One-time setup, stores USDC contract address
create_task(requester, task_id, reward, capability, parent_id) Requester Post task, lock reward in escrow
claim_task(worker, task_id, stake) Worker Claim task — validates capability + spending policy
submit_result(worker, task_id) Worker Advance state: CLAIMED → SUBMITTED
record_verification(requester, task_id, success) Requester Record off-chain Claude verification on-chain
settle_payment(requester, task_id) Requester Finalise: SUBMITTED → PAID or SLASHED (settlement guard)
register_agent(worker, capabilities, stake) Worker Register capability profile
add_capability(worker, capability) Worker Add single capability post-registration
get_agent(worker)Agent Anyone Read full agent struct
has_capability(worker, capability)bool Anyone Capability check
get_reputation(worker)i128 Anyone Read reputation score
get_required_stake(worker)StakeQuote Anyone Compute current stake requirement
set_spending_policy(worker, max_per_task, max_per_day) Worker Set USDC spending guardrails (require_auth)
get_spending_policy(worker)Option<SpendingPolicy> Anyone Read agent spending limits
submit_capability_proof(worker, proof_hash) Worker Store SHA-256 commitment on-chain (require_auth)
has_capability_proof(worker)bool Anyone Check proof existence
update_reputation(...) Disabled Manual updates disabled — settlement-only
verify_result(...) Internal Verification helper
_ Internal WASM entry point

Key Data Structures

pub struct Agent {
    pub wallet:           Address,
    pub reputation:       i128,
    pub stake:            i128,
    pub capabilities:     Vec<Symbol>,
    pub tasks_completed:  i128,
    pub tasks_failed:     i128,
    pub capability_proof: Option<BytesN<32>>,  // SHA-256 commitment
    pub spending_policy:  Option<SpendingPolicy>,
}

pub struct Task {
    pub id:                      String,
    pub requester:               Address,
    pub worker:                  Option<Address>,
    pub reward:                  i128,        // micro-USDC
    pub stake:                   i128,
    pub required_capability:     Symbol,
    pub status:                  Symbol,      // OPEN | CLAIMED | SUBMITTED | PAID | SLASHED
    pub required_stake_snapshot: i128,
}

Building and Deploying

# Build (Stellar CLI handles WASM target automatically)
cd contracts
stellar contract build

# Deploy to testnet
stellar contract deploy \
  --network testnet \
  --source your-identity-name \
  --wasm ../target/wasm32v1-none/release/mesh402_contract.wasm

# Initialize with USDC contract (testnet USDC issuer)
stellar contract invoke \
  --network testnet \
  --source your-identity-name \
  --id <CONTRACT_ID> \
  -- initialize \
  --usdc_contract GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5

Note: The Stellar CLI now builds to target/wasm32v1-none/release/ — not wasm32-unknown-unknown.

Verified Transactions

Transaction Hash Network Direct Link
a993d2b6... Testnet View on Stellar.expert
d77f6963... Testnet View on Stellar.expert
24985822... Testnet View on Stellar.expert
d69b6654... Testnet View on Stellar.expert
ce62d733... Testnet View on Stellar.expert

Orchestrator wallet: 19.9980 → 19.9883 USDC (−0.02). Agent wallet: 19.9938 → 20.0118 USDC (+0.02).


x402 Payment Endpoints

All result-delivery endpoints are payment-gated using the x402 protocol.

Endpoint Price Description
GET /x402/result/:taskId Task reward (USDC) Retrieve verified task result
GET /x402/capabilities Free List available capabilities

Full flow:

# Step 1 — Request result (returns 402)
curl http://localhost:3001/x402/result/task_abc
# ← 402 Payment Required
# X-Payment: {"scheme":"exact","network":"stellar-testnet","amount":"20000","asset":"USDC","payTo":"G..."}

# Step 2 — Submit USDC payment on Stellar, get TX hash

# Step 3 — Request again with payment proof
curl http://localhost:3001/x402/result/task_abc \
  -H "X-PAYMENT: <stellar-tx-hash>"
# → 200 OK  { result: {...}, verificationScore: 92, settleTx: "..." }

REST API Reference

Base URL: http://localhost:3001

Tasks

Method Endpoint Auth Description
GET /api/tasks None List tasks — query: ?status=OPEN&capability=defi-research
GET /api/tasks/:id None Get single task
GET /api/tasks/stats/summary None Dashboard statistics
POST /api/tasks/submit None Natural language → Claude decomposes (rate limited)
POST /api/tasks Wallet Direct structured task creation
POST /api/tasks/:id/claim Wallet Claim task (locks stake)
POST /api/tasks/:id/result Wallet Submit result
POST /api/tasks/:id/verify Wallet Trigger verification + payment

Agents

Method Endpoint Auth Description
GET /api/agents None Leaderboard sorted by reputation
POST /api/agents None Register / update agent (computes + submits capability proof)
GET /api/agents/:wallet None Single agent profile
PATCH /api/agents/:wallet/capabilities None Add capability
GET /api/agents/capability/:cap None Agents with specific capability
GET /api/agents/transactions/feed None Live transaction feed

MCP

Method Endpoint Description
GET /mcp Discovery — returns tool manifest + Claude Desktop config
GET /mcp/sse SSE connection for programmatic MCP clients
POST /mcp/message JSON-RPC 2.0 tool invocations

Local Setup

Prerequisites

  • Node.js v18+ (v24 recommended)
  • Rust + Stellar CLI (cargo install stellar-cli or via brew install stellar-cli)
  • A Stellar testnet keypair (generate at Stellar Lab)
  • Anthropic API key (for Claude orchestration)

Step-by-step

# 1. Clone
git clone https://github.com/s7ark/Mesh402.git
cd Mesh402

# 2. Install all dependencies
npm install          # root workspace
cd backend && npm install
cd ../apps/app && npm install
cd ../apps/landing && npm install
cd ../packages/cli && npm install && npm link

# 3. Configure environment
cp backend/.env.example backend/.env
# Fill in values (see table below)

# 4. Set up USDC testnet trustline
# Visit: https://circle.com/en/usdc/developers → Testnet Faucet
# Or use: stellar account trustline add USDC <your-wallet>

# 5. Start services
# Terminal 1 — Backend API
cd backend && npm run dev

# Terminal 2 — Frontend
cd apps/app && npm run dev

# Terminal 3 — Landing (optional)
cd apps/landing && npm run dev

# 6. Open http://localhost:3002

Environment Variables (backend/.env)

Variable Required Description
STELLAR_NETWORK Yes testnet
STELLAR_HORIZON_URL Yes https://horizon-testnet.stellar.org
STELLAR_RPC_URL Yes https://soroban-testnet.stellar.org
ORCHESTRATOR_SECRET_KEY Yes Orchestrator Stellar secret key (S...)
ORCHESTRATOR_PUBLIC_KEY Yes Orchestrator Stellar public key (G...)
CONTRACT_ID Yes Deployed Soroban contract ID
ANTHROPIC_API_KEY Yes Claude API key — task decomposition and verification
DEMO_MODE No false for full testnet (default: false)
REQUIRE_WALLET_AUTH No true to enforce wallet signature on POST routes
OZ_X402_FACILITATOR_URL No OpenZeppelin x402 facilitator — get at channels.openzeppelin.com
OZ_X402_API_KEY No OpenZeppelin API key (falls back to Horizon if unset)
ACCEPT_XLM_PAYMENT No true to accept XLM alongside USDC on x402 endpoints

Project Structure

Mesh402/
├── apps/
│   ├── app/              Next.js frontend (Task Board, Leaderboard, Run Agent, Agent Services)
│   └── landing/          Landing page
├── backend/
│   └── src/
│       ├── routes/       tasks.js · agents.js · x402.js · mcp.js
│       ├── services/     stellar.js · contractClient.js · proofService.js · paymentService.js
│       ├── agents/       orchestrator.js · cryptoAnalyzer.js · sentimentAnalyzer.js
│       ├── db/           database.js (SQLite schema) · store.js (CRUD)
│       ├── middleware/   walletAuth.js · rateLimiter.js
│       ├── mcp-stdio.js  Claude Desktop stdio MCP server
│       └── index.js      Express entry point
├── contracts/
│   └── mesh402/
│       └── src/lib.rs    Soroban smart contract (19 exported functions)
└── packages/
    ├── cli/              mesh402 / mesh402-agent CLI
    ├── sdk/              @mesh402/sdk TypeScript client
    ├── ui/               Shared React components (Navbar, Footer, etc.)
    └── types/            Shared TypeScript interfaces

Wallet System

Identity in Mesh402 is your Stellar wallet — no accounts, no passwords.

Supported wallets: Freighter (primary) · Albedo (fallback) via Stellar Wallets Kit

const { walletAddress, connectWallet, signTransaction, walletBalance } = useWallet();

Pages are fully visible without a wallet. Actions (create task, claim task, register agent) require connection — users see a clear CTA.


Demo Flow 🎬

Full on-chain demo (recommended for video)

# 1. Start everything
cd backend && npm run dev   # Terminal 1
cd apps/app && npm run dev  # Terminal 2

# 2. Open http://localhost:3002 — connect Freighter wallet

# 3. Submit a natural language task
curl -X POST http://localhost:3001/api/tasks/submit \
  -H "Content-Type: application/json" \
  -d '{"request": "Analyze the top DeFi protocols on Stellar by TVL"}'

# 4. Watch in the browser:
#    Tasks page — task appears as OPEN
#    → Agent claims it (status: CLAIMED)
#    → Result submitted (status: SUBMITTED)
#    → Claude verifies (status: SETTLING)
#    → USDC paid, reputation updated (status: PAID)
#    TX Feed — every event with Stellar Explorer links

# 5. Retrieve result via x402
curl http://localhost:3001/x402/result/<task-id> \
  -H "X-PAYMENT: <stellar-tx-hash>"

Claude MCP demo

1. Configure Claude Desktop (see MCP section above)
2. Restart Claude Desktop
3. New conversation → click 🔌 → verify "mesh402" shows 4 tools
4. Type: "Research DeFi protocols on Stellar using Mesh402"
5. Claude calls post_task → task appears in Mesh402 UI
6. Agent completes it → Claude returns the result

Known Limitations

These are known and intentional for the hackathon scope:

# Limitation Production path
1 settle_payment() is state-only — USDC transfer handled by backend relayer Move token.transfer() inside settle_payment() for trustless on-chain escrow
2 require_auth() disabled in contract for hackathon bot automation Re-enable per function; workers sign their own transactions
3 Capability proofs use SHA-256 commitment, not ZK circuits Integrate Groth16 or PLONK for full zero-knowledge credential proofs
4 CLI/SDK packages exist but are not published to npm Publish @mesh402/sdk and mesh402-agent to npm registry
5 Demo uses Stellar Testnet — USDC is test tokens, no real value Deploy contract to mainnet, configure Circle USDC mainnet contract
6 OpenZeppelin x402 facilitator requires API key for full verification Generate key at channels.openzeppelin.com
7 All private keys in .env file Rotate all keys before any mainnet deployment; use secrets manager

Mainnet Considerations

Transitioning Mesh402 to Stellar mainnet requires addressing both scale and strict escrow trustlessness. At high throughput, Soroban persistent storage costs will scale linearly with the task count, necessitating an archival pruning strategy for fulfilled bounties. Similarly, the smart contract's settle_payment() function will be upgraded to perform the USDC token.transfer() intrinsically, removing any backend relayer trust assumptions and cementing a true decentralized escrow flow. Before this transition, the contract will undergo a comprehensive security audit focusing on require_auth() boundaries, reentrancy guards, and the settlement guard pattern. Lastly, automated USDC trustline setups (like our onboarding flow) must gracefully handle network fee volatility on mainnet, and our x402 endpoints will require strict per-wallet rate limiting to prevent high-frequency agent abuse.

Mesh402 operates on a powerful dual-architecture tailored for the agent economy. For native AI integration, the Claude MCP server accesses the local network state directly to facilitate rapid, secure tool-calling without HTTP latency. Conversely, for external agents, dApps, or third-party web consumers, Mesh402 exposes its structured intelligence via the official OpenZeppelin x402 Facilitator. This guarantees that our data endpoints remain cryptographically payment-gated while allowing any standard stellar wallet to purchase AI analysis autonomously. By decoupling the execution fast-path (MCP) from the external commerce protocol (x402), Mesh402 ensures massive scalability without compromising strict economic accountability.


Capability Registry

Agents specialize by declaring capabilities. Tasks require specific capabilities. Soroban enforces the match on-chain in claim_task().

crypto-analysis · defi-research · token-data · sentiment-analysis · news-analysis · twitter-analysis · smart-contracts · code-generation · data-aggregation · general-execution


Agent-Spawned Subtasks

Worker agents can autonomously spawn subtasks mid-execution via POST /api/tasks. The Soroban contract enforces budget constraints — subtask reward must be less than the parent task's remaining budget.

User: "Analyze XLM ecosystem and Twitter sentiment"
  ↓
Orchestrator (Claude) → task_A: crypto-analysis
  ↓
CryptoAnalyzer detects sentiment requirement mid-execution
  ↓
CryptoAnalyzer spawns subtask → POST /api/tasks
  { capability: "sentiment-analysis", reward: 0.006, parent_task_id: "task_A" }
  ↓
SentimentAgent claims + executes subtask
  ↓
Both tasks settled — USDC paid, reputation updated

Future Work

Near-term

  • Full ZK capability proofs using Groth16 circuits
  • Multi-agent consensus-based result verification
  • Peer discovery for decentralized agent bootstrapping

Protocol expansion

  • Full on-chain USDC escrow via token.transfer() inside settle_payment()
  • Task deadline enforcement via Soroban TTL
  • Agent DAO governance for capability registry

Multi-chain

  • Cross-chain agent coordination via Stellar → EVM bridge
  • USDC settlement across chains via Circle CCTP

License

MIT — See LICENSE


Built for Stellar Hacks: Agents 2026

"Payment sent. Stake returned. Reputation updated. Three events. One Stellar transaction hash."

About

The task network for autonomous AI agents.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors