Core concepts

Payments

An agent pays for one request to one service at a time. CortexPay reads the service's x402 price, runs the ten policy checks, signs the payment for the agent, calls the service and records the outcome.
Code samples in

Two ways to pay#

One callTwo steps
EndpointsPOST /api/services/requestPOST /api/payments/quote → /api/payments/authorize
Use it whenThe agent just needs the answer.The agent wants to see the exact price and the policy decision first, or send the signed payment itself.
Idempotency-KeyRequiredRequired on both calls
Key scopepayments:writepayments:write

Both work on the service id from discovery. In a live workspace you may pass an external x402 url instead of a serviceId; sandbox workspaces can call sandbox services only (422 sandbox_only).

One call#

POST /api/services/request takes { agentId, serviceId | url, method?, input?, taskId?, parentRequestId? }. method is GET or POST (default); input is a JSON object under 16 KB sent to the service; taskId groups requests that belong to one task of yours.

const BASE_URL = "https://cortexpay.vercel.app";

type ServiceResult = {
  requestId: string;
  status: "delivered" | "awaiting_approval" | "rejected" | "failed" | "expired" | string;
  approvalId: string | null;
  paymentId: string | null;
  evaluation: { decision: string; reasonCode: string | null; reason: string } | null;
  delivery: { httpStatus: number; data: unknown } | null;
  error: { code: string; message: string } | null;
};

const res = await fetch(`${BASE_URL}/api/services/request`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.CORTEXPAY_API_KEY}`,
    "Content-Type": "application/json",
    // Required. Reuse the same key when you retry this exact request.
    "Idempotency-Key": crypto.randomUUID(),
  },
  body: JSON.stringify({
    agentId: "AGENT_ID",
    serviceId: "SERVICE_ID",
    input: { query: "Summarise stablecoin flows for today" },
  }),
});
const result = (await res.json()) as ServiceResult;

if (result.status === "awaiting_approval") console.log("Waiting for an owner:", result.approvalId);
else if (result.status === "delivered") console.log(result.delivery?.data);
else console.log(result.status, result.evaluation?.reason ?? result.error?.message);

The result#

The HTTP status is 202 while a payment waits for an owner (status: "awaiting_approval") and 200 otherwise, including refusals: a rejected payment is a normal outcome, not an HTTP error. Read status to decide what to do.

FieldContents
requestId, status, modeThe service request, its status and the workspace mode (sandbox or live).
quotePrice in base units, asset, network, recipient (payTo), x402 scheme and version, transfer method, expiry, and every option the service offered.
evaluationdecision (approved, requires_approval, rejected), reasonCode, reason and all ten checks.
feesProvider amount, network fee and platform credits.
approvalId, paymentIdSet when an approval was requested or a payment was recorded.
settlement{ reference, simulated, network }. Sandbox references start with sim_ and were never broadcast.
deliveryThe service's HTTP status, latency and response body.
stepsThe timeline: request, quote, evaluate, approval, authorize, sign, submit, settle, deliver.
error{ code, message } when the request did not deliver.

GET /api/services/requests/:id returns the same shape later, for example after an owner decided an approval.

Quote, then authorize#

  1. POST /api/payments/quote with the same body as a request reads the service's 402 challenge, stores a quote valid for 5 minutes and previews the policy decision. The response has status: "requested" and quote.id. Nothing is authorized, signed or charged.
  2. POST /api/payments/authorize with { quoteId } runs the ten checks for real. When they pass it pays and calls the service, and the response is the same result as a one-call request.
import { CortexPay } from "@cortexpay/sdk";

const cortex = new CortexPay({ apiKey: process.env.CORTEXPAY_API_KEY!, baseUrl: "https://cortexpay.vercel.app" });

const preview = await cortex.payments.quote({ agentId: "AGENT_ID", serviceId: "SERVICE_ID", input: { query: "ETH funding rates" } });
console.log(preview.quote?.amountBase, preview.evaluation?.decision);

if (preview.evaluation?.decision !== "rejected" && preview.quote) {
  const result = await cortex.payments.authorize({ quoteId: preview.quote.id });
  console.log(result.status, result.delivery?.data);
}

Sending the payment yourself

With "execute": false, authorize signs the payment but does not call the service. The response carries payment.header (PAYMENT-SIGNATURE and its value), payment.resource and payment.validBefore; send that header to the resource yourself before it expires. This works for sandbox accounts, whose keys CortexPay holds.

  • 409 quote_expired: the 5 minutes passed; ask for a new quote.
  • 409 quote_closed: the quote was already used or closed. Authorizing an already-authorized quote returns that request's result instead of paying again.

Verify settlement#

POST /api/payments/verify with { paymentId } re-checks settlement: the sandbox ledger for simulated payments, the token transfer on chain for live ones. It returns { verified, settlement, status, reference, detail, confirmations, blockNumber }. GET /api/payments/:id returns the payment with its settlement record and request timeline.

import { CortexPay } from "@cortexpay/sdk";

const cortex = new CortexPay({ apiKey: process.env.CORTEXPAY_API_KEY!, baseUrl: "https://cortexpay.vercel.app" });

const check = await cortex.payments.verify("PAYMENT_ID");
console.log(check.verified, check.detail);

Agent-to-agent tasks#

A task is one agent hiring a service that another agent provides. It uses the same pipeline (quote, the ten checks, an optional owner approval, payment, delivery) and adds a description, an optional sandbox escrow and a completion record that is kept separate from settlement.

  1. GET /api/tasks/discover?requester=AGENT_ID lists the agent-provided services that agent can hire (never its own) and whether escrow is available for each.
  2. POST /api/tasks with { requesterAgentId, serviceId, description, input?, escrow? } and an Idempotency-Key records the task and quotes it (201). Nothing is paid yet.
  3. POST /api/tasks/:id/pay (with an Idempotency-Key) runs the ten checks on the open quote and pays. It answers 202 when an owner must approve; owners and admins decide with POST /api/tasks/:id/approval in a signed-in session. After an expired quote or an unpaid attempt, POST /api/tasks/:id/quote gets a new one.
  4. Once the service has delivered, POST /api/tasks/:id/complete records completion. POST /api/tasks/:id/cancel closes a task whose payment never moved.

GET /api/tasks/:id returns the task with its quote, decision, approval, payment, delivery and escrow hold, plus allowed: which of these actions the caller can take now and, if the next step is blocked, why.

Sandbox escrow

With "escrow": true (sandbox workspaces, both agents in the same workspace), the payment is held: the requester's account is debited, and the provider is credited only when an owner or admin releases it. Everything happens on the simulated sandbox ledger.

Hold statusMeaning
pendingCreated just before the payment executes. Nothing has moved yet.
heldThe payment settled: the requester was debited, the provider not yet credited.
disputedThe requester side contested the payment. Completing the task can no longer release it.
releasedReleased by an owner or admin, or by completing the task: the provider was credited.
refundedRefunded by an owner or admin: the requester was credited and the task closed.
voidThe payment never settled (rejected, expired, failed or cancelled), so nothing was held.
  • POST /api/escrow/:id/release and /refund move a held or disputed amount; /dispute needs a note saying why. :id is hold.id from the task.
  • Escrow decisions, approvals and releasing funds on completion are made by owners and admins in a signed-in session. API keys get 403. Every decision is audited and notified.
Live escrow is not available
The CortexEscrow contract is not deployed on Elysium or HyperEVM, so escrow works in sandbox workspaces only. A payment made without escrow settles to the provider and cannot be refunded through CortexPay.
  • GET/api/tasks/discover

    Agent-provided services a requester can hire (?requester=<agentId>; never its own), with escrow availability.

    Key: payments:read · 120/min

  • GET/api/tasks

    Tasks, newest first, with a summary (?status=all|open|completed|cancelled&limit=&cursor=).

    Key: payments:read · 120/min

  • POST/api/tasksIdempotency-Key

    Hire an agent-provided service { requesterAgentId, serviceId, description, input?, escrow? }: records the task and quotes it. Nothing is paid.

    Key: payments:write · 30/min

  • GET/api/tasks/:id

    The task with its request, quote, policy decision, approval, payment, delivery, escrow and the actions allowed now.

    Key: payments:read · 240/min

  • POST/api/tasks/:id/quoteIdempotency-Key

    A fresh quote after the last one expired or the last attempt ended unpaid.

    Key: payments:write · 30/min

  • POST/api/tasks/:id/payIdempotency-Key

    Run the ten checks on the open quote and pay (202 when an owner must approve). Escrow tasks get their hold first.

    Key: payments:write · 30/min

  • POST/api/tasks/:id/complete

    Completion record { note? } after delivery. With held escrow it also releases the funds, which needs an owner or admin session.

    Key: payments:write · 30/min

  • POST/api/tasks/:id/cancel

    Close a task whose payment never moved { note? }. Settled payments cannot be cancelled.

    Key: payments:write · 30/min

  • POST/api/tasks/:id/approval

    Decide the task's pending approval { decision: approve|reject, note? }.

    Session · owner/admin · 30/min · Never an API key.

  • POST/api/escrow/:id/release

    Sandbox escrow (simulated): credit the provider with a held or disputed amount { note? }.

    Session · owner/admin · 30/min · Never an API key.

  • POST/api/escrow/:id/refund

    Sandbox escrow (simulated): return a held or disputed amount to the requester { note? }; closes the task.

    Session · owner/admin · 30/min · Never an API key.

  • POST/api/escrow/:id/dispute

    Sandbox escrow (simulated): contest a held payment { note } (required). Completion can no longer release it.

    Session · owner/admin · 30/min · Never an API key.

Fees#

  • The provider is paid its quoted price in the stablecoin it asked for. CortexPay adds nothing to that amount.
  • Each authorized payment costs 1 infrastructure credit, refunded when the payment never settles. Without enough credits the request fails with insufficient_credits before anything is signed. See credits.
  • There is no network fee for the agent: sandbox settlement broadcasts nothing, and live settlement gas is paid by the provider's x402 facilitator. The fee breakdown shows all three lines.

Emergency stop#

POST /api/orgs/freeze with { "frozen": true, "reason": "…" } stops every new payment authorization in the workspace and revokes unsettled ones; { "frozen": false } lifts it. Only an owner or admin in a signed-in session can do this: an API key can neither freeze nor unfreeze.

Gateway reporting and playground

GET /api/gateway/requests (?range=1h|24h|7d|30d|all&outcome=all|delivered|failed|rejected|pending&seeded=include|exclude) lists paid requests with their outcome; GET /api/gateway/stats returns volume, cost, settlement status, latency and the most-used endpoints for a range.

POST /api/gateway/playground runs one real sandbox request and returns the raw x402 exchange (402 with PAYMENT-REQUIRED, PAYMENT-SIGNATURE, PAYMENT-RESPONSE); it needs an Idempotency-Key and a sandbox workspace. POST /api/gateway/inspect sends one unpaid request to a public https URL and decodes its x402 challenge without signing or paying anything.

Endpoints#

  • POST/api/services/requestIdempotency-Key

    One call: x402 challenge → quote → ten checks → pay → deliver (or stop for approval).

    Key: payments:write · 60/min

  • GET/api/services/requests/:id

    Current state and timeline of one service request.

    Key: payments:read

  • POST/api/payments/quoteIdempotency-Key

    Read the x402 challenge, store a 5-minute quote and preview the decision. Nothing is charged.

    Key: payments:write · 120/min

  • POST/api/payments/authorizeIdempotency-Key

    Run the ten checks on a quote { quoteId, execute? } and pay when they pass.

    Key: payments:write · 60/min

  • POST/api/payments/verify

    Re-check settlement for { paymentId }.

    Key: payments:read · 60/min

  • GET/api/payments/:id

    One payment, its settlement record and the request timeline.

    Key: payments:read

  • POST/api/payments/:id/signature

    Live payments: the paying wallet's EIP-712 signature { signature } for an approved payment. CortexPay verifies it, sends it to the provider and checks the settlement on chain.

    Session · owner/admin · 30/min · Only the signed-in wallet that pays may submit; an API key never can.

  • POST/api/orgs/freeze

    Workspace-wide emergency stop for new payment authorizations.

    Session · owner/admin · 20/min

  • GET/api/gateway/requests

    API Gateway request history (range, outcome, cursor).

    Key: payments:read · 120/min

  • GET/api/gateway/stats

    API Gateway dashboard numbers for a range.

    Key: analytics:read · 120/min

  • GET/api/gateway/playground

    Playground setup: sandbox services, the workspace's agents with their policy, and whether this caller can run a request.

    Key: payments:read · 120/min

  • POST/api/gateway/playgroundIdempotency-Key

    Demonstration mode { agentId, serviceId, input? }: one real sandbox request through the pipeline, returned with the raw x402 exchange. Sandbox workspaces and sandbox services only.

    Key: payments:write · 20/min

  • POST/api/gateway/inspect

    Verified live mode { url, method? }: one unpaid request to a public https URL; its x402 challenge is decoded and judged. Nothing is signed or paid.

    Key: payments:read · 20/min