AgentMesh Developer Guide

AgentMesh is an open API marketplace where payments settle on-chain through the x402 protocol. No accounts, no API keys, no invoicing — just a wallet, USDC, and one approval. This guide covers everything from first call to running autonomous agents.

Note:
This documentation refers to Morph Testnet only.
X402AgentSDK is still not uploaded as npm package.

ChainMorph L2
TokenMockUSDC
ApprovalOne-time
Fee split99% / 1%

How it works

Request, sign, settle — all in one call

Every API call carries an off-chain ECDSA signature in the X-Payment header. The gateway middleware verifies it and triggers an on-chain USDC transfer before proxying your request. Providers receive funds within the same transaction.

Discover

Browse the on-chain API catalog. Every listing includes live pricing, parameter schemas, and example responses.

Pay

Sign a micro-payment off-chain with your wallet. No gas is required from you — the gateway calls the facilitator contract.

Receive

The API response comes back in the same HTTP round-trip. Settlement is confirmed on Morph L2 within the same request lifecycle.


Quick start

Call your first API in under 5 minutes

The fastest path is through the UI. For programmatic access, use the SDK or send raw HTTP with the payment header.

Via the app

  1. Open Marketplace and pick an API.
  2. Connect a wallet that holds USDC on Morph Hoodi Testnet. Use POST /faucet/mint if you need test tokens.
  3. Click Approve Facilitator once. This sets the USDC allowance for the X402Facilitator contract.
  4. Click Call API. The app builds the payment header, signs it, and shows you the live response.

Via the SDK (Soon)

install
npm install @agentmesh/x402-agent-sdk
index.js
import { createX402Agent } from "@agentmesh/x402-agent-sdk";

const agent = await createX402Agent({
  gateway:     process.env.GATEWAY_URL,
  privateKey:  process.env.AGENT_PRIVATE_KEY,
  llm:         { provider: "groq", apiKey: process.env.GROQ_API_KEY },
  autoMint:    true,   // claim test USDC automatically
  autoApprove: true,   // approve facilitator automatically
});

const result = await agent.run("What is the current BTC price in USD?");
console.log(result.answer);
// → "Bitcoin is currently trading at $67,420."
raw HTTP (no SDK)
// 1. Fetch catalog
const catalog = await fetch(`${GATEWAY}/api/v1/catalog`).then(r => r.json());

// 2. Get nonce
const { nonce, deadline } = await fetch(`${GATEWAY}/payment/nonce`).then(r => r.json());

// 3. Sign payment
const payload = ethers.utils.solidityKeccak256(
  ["address","address","address","uint256","uint256","uint256"],
  [facilitator, payer, provider, amount, nonce, deadline]
);
const signature = await wallet.signMessage(ethers.utils.arrayify(payload));

// 4. Call API with payment header
const xPayment = btoa(JSON.stringify({ payer, provider, amount, nonce, deadline, signature }));
const res = await fetch(apiUrl, { headers: { "X-Payment": xPayment } });
const data = await res.json();

Payment flow

Step-by-step: how a paid call settles

Each step below maps directly to a network hop or contract call. Understanding this helps you debug failed payments and design reliable agent workflows.

01

Fetch catalog

The agent (or browser) hits GET /api/v1/catalog. The gateway reads APIRegistry.sol on Morph and returns every live API with its price in micro-USDC.

GET /api/v1/catalog
02

Get a nonce

Before signing, request a fresh nonce + deadline from GET /payment/nonce. Nonces expire in 5 minutes and are single-use to prevent replay attacks.

GET /payment/nonce
→ { nonce, deadline }
03

Sign off-chain

Construct the EIP-191 payload and sign it locally with your wallet. Nothing hits the chain yet — the signature is just base64-encoded JSON.

keccak256(
  facilitator + payer +
  provider   + amount +
  nonce      + deadline
)
04

Send X-Payment header

Attach the encoded payment to your API call. The x402 middleware on the gateway verifies the ECDSA signature, then calls settle() on-chain.

X-Payment: base64({
  payer, provider, amount,
  nonce, deadline, sig
})
05

On-chain settlement

X402Facilitator.sol verifies the signature, checks the nonce, enforces the deadline, and transfers USDC — 99% to the provider, 1% to the treasury.

emit PaymentSettled(
  payer, provider,
  amount, apiId
)

SDK reference (Soon)

x402-agent-sdk configuration

All options passed to createX402Agent(). Every field is optional except gateway and privateKey.

OptionTypeDescription
gatewaystringBackend URL
privateKeystringWallet private key for signing payments
llmobject{ provider: "groq" | "openai", apiKey, model }
autoMintbooleanAuto-claim test USDC from faucet (testnet only)
autoApprovebooleanAuto-approve USDC spending for the facilitator
settleDelaynumberms to wait for on-chain confirmation (default 5000)
maxLoopsnumberMax AI reasoning iterations before forcing an answer
temperaturenumberLLM temperature — 0 for deterministic output
catalogTtlnumberCatalog cache TTL in ms (0 = cache forever)
onEventfunctionCallback for payment:success, tool:called, run:complete, …

SDK events

Pass an onEvent callback to observe the agent lifecycle in real time.

onEvent callback
const agent = await createX402Agent({
  // ...
  onEvent: (event) => {
    switch (event.type) {
      case "catalog:loaded":   console.log(`${event.count} APIs available`); break;
      case "balance:checked":  console.log(`Balance: ${event.usdcBalance} USDC`); break;
      case "tool:called":      console.log(`Calling ${event.name} — $${event.priceUsd}`); break;
      case "payment:success":  console.log(`Settled ${event.amountUsd} USDC`); break;
      case "payment:failed":   console.error(`Failed: ${event.error}`); break;
      case "run:complete":     console.log(`Done. Spent: $${event.metrics.totalSpent}`); break;
    }
  },
});

Smart contracts

On-chain components

Three contracts run the protocol on Morph Hoodi Testnet. You never call them directly as a consumer — the gateway and SDK handle that — but understanding them helps you verify settlement and build custom integrations.

APIRegistry.sol

On-chain source of truth for the API catalog. Providers call registerAPI() to list an endpoint. The backend reads getAllAPIs() to build the catalog served to agents.

  • registerAPI(name, endpoint, price)
  • getAPI(apiId)
  • getAllAPIs()
  • updateAPI(apiId, price, active)
X402Facilitator.sol

Handles every settlement. Verifies the ECDSA signature, checks the nonce for replay protection, enforces the deadline, then splits the USDC transfer.

  • settle(payer, provider, amount, nonce, deadline, sig)
MockUSDC.sol

ERC-20 test token on Morph Hoodi. The faucet endpoint calls mint() for you — up to 1000 USDC per wallet per hour.

  • mint(address, amount)
  • balanceOf(address)
  • approve(spender, amount)

Network

Chain & token details

All activity runs on Morph Hoodi Testnet during beta. Mainnet migration will be announced on the waitlist.

NetworkMorph Hoodi Testnet
Chain ID2910
RPChttps://rpc-hoodi.morphl2.io
Explorerhttps://explorer-hoodi.morphl2.io
TokenMockUSDC (ERC-20, 6 decimals)
Fee split99% provider · 1% treasury
Nonce TTL5 minutes
Faucet limit1000 USDC / hr / wallet

FAQ

Common questions

Do I need an account or API key?

No. Access is gated by USDC payment through x402. Connect a wallet, approve the facilitator once, and you can call any listed API immediately.

Which chain is used?

Settlement happens on Morph Hoodi Testnet (chain ID 2910). All USDC amounts are in micro-USDC — 1 USDC = 1,000,000 units.

What is the fee split?

99% of every payment goes directly to the API provider's wallet. 1% goes to the AgentMesh treasury for protocol maintenance.

How do I get test USDC?

The faucet endpoint POST /faucet/mint sends 1000 USDC to your address. You can call it once per hour. The SDK handles this automatically when autoMint: true.

Can an AI agent use this without a human in the loop?

Yes — that is the primary use case. The x402-agent-sdk wraps the full payment + LLM loop. The agent fetches the catalog, picks the right API via function calling, signs and settles automatically.

What prevents double-spending or replay attacks?

Each nonce is single-use and stored in the gateway's nonce cache. Deadlines expire after 5 minutes. X402Facilitator.sol rejects any payment with a used nonce or expired deadline.