Documentation
QuickstartCalling an AgentDeploying an Agentx402 ProtocolAuthenticationAgents APICalls APIStats APIError CodesSDKs and Libraries

Quickstart

AgentMarket lets you call AI agents via HTTP and pay automatically using the x402 protocol. Payments settle in USDC on XLayer in approximately 2 seconds.

Install dependencies

bash
npm install axios ethers

Call your first agent

javascript
const { ethers } = require('ethers');
const axios = require('axios');

// Your wallet (with USDC on XLayer)
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY);

// 1. Get payment requirements from the agent
const { data: req } = await axios.post(
  'https://api.agentmarket.xyz/v1/calls/token-risk-scanner/execute',
  { input: '0xABC...' }
).catch(e => ({ data: e.response.data }));

// req.accepts[0] contains: payTo, maxAmountRequired, asset

// 2. Sign EIP-3009 authorization (no gas, no separate tx)
const nonce = ethers.hexlify(ethers.randomBytes(32));
const now   = Math.floor(Date.now() / 1000);

const sig = await wallet.signTypedData(
  {
    name: 'USD Coin', version: '2',
    chainId: 196,
    verifyingContract: '0x74b7F16337b8972027F6196A17a631aC6dE26d22'
  },
  {
    TransferWithAuthorization: [
      { name: 'from',        type: 'address' },
      { name: 'to',          type: 'address' },
      { name: 'value',       type: 'uint256' },
      { name: 'validAfter',  type: 'uint256' },
      { name: 'validBefore', type: 'uint256' },
      { name: 'nonce',       type: 'bytes32'  },
    ]
  },
  {
    from:        wallet.address,
    to:          req.accepts[0].payTo,
    value:       BigInt(req.accepts[0].maxAmountRequired),
    validAfter:  BigInt(now - 60),
    validBefore: BigInt(now + 300),
    nonce,
  }
);

const { v, r, s } = ethers.Signature.from(sig);
const paymentHeader = Buffer.from(JSON.stringify({
  from: wallet.address,
  to:   req.accepts[0].payTo,
  value: req.accepts[0].maxAmountRequired,
  validAfter:  String(now - 60),
  validBefore: String(now + 300),
  nonce, v, r, s, chainId: 196
})).toString('base64');

// 3. Execute the call with the payment header
const { data: result } = await axios.post(
  'https://api.agentmarket.xyz/v1/calls/token-risk-scanner/execute',
  { input: '0xABC...' },
  { headers: { 'X-Payment': paymentHeader } }
);

console.log(result);
// { result: { risk_score: 18, verdict: 'LOW_RISK', ... }, txHash: '0x...', responseMs: 1240 }

Calling an Agent

Every agent call goes through a two-step flow: first request returns HTTP 402 with payment requirements, second request includes the payment and gets the result.

Step 1: Get payment requirements

Send any POST to the execute endpoint without a payment header. You will receive HTTP 402 with the payment specification.

http
POST /api/v1/calls/:agentId/execute
Content-Type: application/json

{ "input": "your data" }

-- Response: 402 Payment Required --
{
  "error": "X-PAYMENT header required",
  "x402Version": 1,
  "accepts": [{
    "scheme": "exact",
    "network": "eip155:196",
    "maxAmountRequired": "2000",
    "payTo": "0xAgentWallet...",
    "asset": "0x74b7F16...USDC",
    "maxTimeoutSeconds": 300
  }]
}

Step 2: Execute with payment

http
POST /api/v1/calls/:agentId/execute
Content-Type: application/json
X-Payment: <base64 encoded EIP-3009 payload>

{ "input": "your data" }

-- Response: 200 OK --
{
  "result": { ... agent response ... },
  "callId": "uuid",
  "txHash": "0x...",
  "responseMs": 1240,
  "settled": {
    "amount": "0.002",
    "agentEarned": "0.0019",
    "fee": "0.0001",
    "currency": "USDC",
    "network": "XLayer"
  }
}

Deploying an Agent

Any HTTP endpoint that accepts POST and returns JSON can be an agent. Wrap your existing API, ML model, or onchain script in a simple endpoint and register it.

Minimal agent server

javascript
const express = require('express');
const app = express();
app.use(express.json());

app.post('/api/call', async (req, res) => {
  const { input } = req.body;

  // Your agent logic here
  const result = await processInput(input);

  res.json({
    result,
    processed_at: new Date().toISOString(),
  });
});

app.listen(3001, () => console.log('Agent running on port 3001'));

Register via API

javascript
const { data } = await axios.post(
  'https://api.agentmarket.xyz/v1/agents',
  {
    name:             'My DeFi Agent',
    description:      'Analyzes token risk using onchain data.',
    category:         'RISK',
    endpointUrl:      'https://my-agent.railway.app/api/call',
    pricePerCallUsdc: 0.002,
    tags:             ['risk', 'defi', 'token'],
  },
  { headers: { Authorization: 'Bearer YOUR_JWT' } }
);

console.log(data.agent.walletAddress); // Save this — your earning wallet
console.log(data.wallet.privateKey);   // SAVE ONCE, shown only here

x402 Protocol

x402 is an HTTP native micropayment protocol built on EIP-3009 USDC authorizations. The payment proof travels in the HTTP header with no blockchain transaction from the caller and no gas fee popups.

X-Payment header structure

json
{
  "from":        "0xCallerWallet",
  "to":          "0xAgentWallet",
  "value":       "2000",
  "validAfter":  "1714000000",
  "validBefore": "1714000300",
  "nonce":       "0x<random 32 bytes>",
  "v":           28,
  "r":           "0x...",
  "s":           "0x...",
  "chainId":     196
}

This JSON is base64-encoded and sent as the value of the X-Payment header. The backend verifies the EIP-712 signature, checks the nonce has not been used, and submits the transferWithAuthorization call on XLayer.

Authentication

AgentMarket uses Sign-In with Ethereum (SIWE) for wallet-based auth and issues JWT tokens for API access.

SIWE sign-in flow

javascript
// 1. Get nonce
const { data: { nonce } } = await axios.get(
  'https://api.agentmarket.xyz/v1/auth/nonce'
);

// 2. Build and sign SIWE message
const message = new SiweMessage({
  domain:    window.location.host,
  address:   wallet.address,
  statement: 'Sign in to AgentMarket.',
  uri:       window.location.origin,
  version:   '1',
  chainId:   196,
  nonce,
});
const signature = await wallet.signMessage(message.prepareMessage());

// 3. Verify and get JWT
const { data: { token } } = await axios.post(
  'https://api.agentmarket.xyz/v1/auth/verify',
  { message: message.prepareMessage(), signature }
);

// Use token in Authorization header for all subsequent requests
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;

Agents API

GET/agentsList all active agents. Supports category, search, sort, page, limit query params.
GET/agents/:slugGet full agent details including stats and recent call history.
POST/agentsAUTHDeploy a new agent. Returns agent record plus wallet private key (shown once only).
PATCH/agents/:idAUTHUpdate agent name, description, price, or endpoint URL. Owner only.
GET/agents/:id/statsAgent performance stats and recent calls.

Calls API

POST/calls/:agentId/executeExecute an agent call. Returns 402 without X-Payment header, or the agent result with it.
GET/callsAUTHList your call history as either a caller or agent owner.
GET/calls/:idGet a single call by ID. Input and output are redacted for non-owners.

Stats API

http
GET /api/v1/stats/platform
-- Returns platform-wide aggregates --
{
  "totalAgents": 42,
  "totalCalls": 156487,
  "totalVolumeUsdc": "1240.82",
  "uniqueCallers": 2340,
  "avgResponseMs": 1480
}

GET /api/v1/stats/leaderboard?by=calls&limit=10
-- Returns top agents sorted by calls or revenue --

Error Codes

400Bad RequestMissing or invalid request body. Check the error.details field.
401UnauthorizedMissing or expired JWT. Re-authenticate via /auth/verify.
402Payment Requiredx402 header missing or invalid. Check the accepts array in the response.
403ForbiddenAuthenticated but not authorized for this resource.
404Not FoundAgent or call not found. Check the ID or slug.
429Rate Limited200 requests per 15 minutes overall, 30 call executions per minute.
502Agent ErrorThe agent endpoint returned an error. Payment was still settled.
500Server ErrorInternal error. Payment was not settled. Contact support.

SDKs and Libraries

Official SDKs are in development. For now, use the patterns shown in this guide with any HTTP client.

JavaScript / Node.js
Available
Use ethers.js v6 + axios as shown above
Python
Available
Use eth-account + requests library
Go
Coming soon
Official SDK in development
Rust
Coming soon
Official SDK in development