Skip to content
NearGate

CONCEPTS

How it works

An x402 V1 flow settled through the neargate-registry contract: a 402 invoice, a registry pay call, an X-PAYMENT proof, an on-chain check, a single-use nonce and a payment-backed attestation. This page is the spec for a hand-rolled client or gateway.

CLI v0.2.1SDK v0.1.0registry neargate-app-registry.testnetnear-testnet

The flow at a glance

  1. 01

    Register

    The seller calls register_service. The registry stores the name, price list, payment target, attestor and the gateway base URL; readers compute the endpoint <gateway>/svc/<id>. The upstream URL never goes on-chain: it is mapped on the gateway.
  2. 02

    Challenge — HTTP 402

    The buyer calls the endpoint with no proof. The gateway issues a fresh invoice with a single-use nonce and answers 402 with a PaymentRequiredResponse.
  3. 03

    Pay through the registry

    The buyer calls pay(service_id, nonce) on the registry with maxAmountRequired attached (price + 0.002 NEAR). The registry forwards the price to the seller, keeps the fee, refunds any excess and records the payment under the nonce.
  4. 04

    Prove it

    The buyer retries the request with an X-PAYMENT header naming the transaction, the nonce and the payer.
  5. 05

    Verify, burn, serve

    The gateway checks the registry’s payment record (and, live, the transaction), burns the nonce, proxies to the upstream and returns the response with an X-PAYMENT-RESPONSE header.
  6. 06

    Attest and score

    After answering, the gateway calls record_attestation. The registry accepts it only for a real, not self-paid, not yet attested payment, then bumps the service’s (total, success) score.

The 402 challenge body

An unpaid call to /svc/:id answers 402 with this JSON (x402Version: 1). There is always exactly one accepts[] entry, paying in native NEAR. Amounts are yoctoNEAR decimal strings (1 NEAR = 1024 yocto). This is what the hosted gateway answers for service #1, a 0.01 NEAR service, with the relay on:

402 response (GET /svc/1 on the hosted gateway)

{
  "x402Version": 1,
  "error": "X-PAYMENT header is required",
  "accepts": [
    {
      "scheme": "exact",
      "network": "near-testnet",
      "maxAmountRequired": "12000000000000000000000",
      "asset": "NEAR",
      "payTo": "neargate-app-registry.testnet",
      "resource": "https://neargate-gateway-production.up.railway.app/svc/1",
      "description": "USD exchange rates",
      "maxTimeoutSeconds": 300,
      "extra": {
        "nonce": "1983699248480309",
        "serviceId": 1,
        "expiresAtMs": 1794520151523,
        "settlement": "neargate-registry-pay",
        "contractId": "neargate-app-registry.testnet",
        "method": "pay",
        "priceYocto": "10000000000000000000000",
        "storageFeeYocto": "2000000000000000000000",
        "seller": "neargate-app-seller.testnet",
        "caip2": "near:testnet",
        "relayer": "neargate-app-gateway.testnet",
        "relayMethod": "pay_from_escrow"
      }
    }
  ]
}
errorstringrequired
Why the gateway is challenging: X-PAYMENT header is required on a first call, else one of the rejection reasons.
transaction / codestringoptional
Top-level, gasless rail only: transaction is the relay transaction on a settlement_pending whose relay timed out (it may still land), and code is the chain’s code after relay_failed (for example ERR_ESCROW_INSUFFICIENT).
networkstringrequired
The gateway’s chain: near-testnet, near-mainnet or near-mock (the offline devnet). A client refuses an invoice for another network (NETWORK_MISMATCH).
maxAmountRequiredyocto stringrequired
What the buyer attaches to pay: priceYocto + storageFeeYocto.
payTo / extra.contractIdNEAR account idrequired
The registry contract. The buyer pays the registry, never the seller directly; both fields name the same account.
resourceurlrequired
Absolute URL of the paid endpoint.
maxTimeoutSeconds / extra.expiresAtMsnumberrequired
How long the invoice lives (the gateway’s INVOICE_TTL_MS, default 5 minutes) and the moment it expires (unix ms). A client refuses an invoice already expired.
extra.nonce1–20 digitsrequired
The single-use invoice nonce. It is passed to pay and echoed in the X-PAYMENT proof, and it keys the registry’s payment record.
extra.serviceIdpositive integerrequired
The registry service id to pay (the first argument of pay).
extra.settlement / methodstringrequired
Always neargate-registry-pay and pay: the one settlement rail.
extra.priceYocto / storageFeeYoctoyocto stringrequired
The service price the seller receives, and the registry’s flat storage fee, always 2000000000000000000000 (0.002 NEAR). A client refuses an invoice whose fee or total does not match (BAD_INVOICE).
extra.sellerNEAR account idrequired
The service’s payment target: the account that receives exactly priceYocto.
extra.caip2stringrequired
The CAIP-2 id of the network: near:testnet, near:mainnet or near:mock.
extra.relayer / relayMethodNEAR account id / "pay_from_escrow"optional
Present only when the gateway runs with RELAYER_ENABLED: the gateway account that relays a signed pay_from_escrow and pays its gas, and the one method it relays. See the gasless rail.

Rejection reasons in the 402 body

The error field says why the gateway is challenging. After every reason except settlement_pending the body carries a fresh invoice (a new nonce): pay that one, do not reuse the old nonce.

errorMeaning
X-PAYMENT header is requiredThe first call: there was no proof.
invalid_payment_headerThe header is not valid base64 JSON of the expected shape, or names a different network than the gateway.
relayer_disabledThe proof is a delegate (gasless) payload and this gateway relays none (RELAYER_ENABLED is off); pay with a tx proof. The invoice stays open.
unknown_nonceThe gateway issued no invoice with that nonce for this service, or no longer remembers it: an invoice is dropped about a minute after it expires (so a used or expired nonce presented later gets this reason), and a restart forgets every invoice unless INVOICE_STORE_PATH keeps them.
invoice_usedThat invoice was already redeemed. A nonce serves one call.
invoice_expiredThe invoice is older than its time to live.
not_foundThe registry holds no payment for the nonce.
wrong_serviceThe payment under that nonce was made for another service.
amount_too_lowThe price the registry forwarded is below the service price.
expiredThe registry payment is older than the invoice time to live.
already_attestedThe payment was already attested, which only follows a served call.
tx_mismatchLive: the transaction is not a successful pay or pay_from_escrow of this nonce and service on this registry, signed by the named payer. The gasless rail answers it in either mode when its relayed payment does not match the invoice.
settlement_pendingLive: the payment is not yet visible. On the gasless rail: the relay is in flight, timed out, or landed and its record is not read yet. The same invoice stays valid: retry the identical proof after the Retry-After seconds (2).

The gasless rail adds its own reasons (delegate_*, bad_signature, unknown_key, key_not_allowed, stale_nonce, escrow_insufficient, relay_failed); they are listed with its checks.

Payment and proof

The pay call

The buyer signs a call to the registry’s pay method with the invoice’s serviceId and nonce and maxAmountRequired attached as the deposit. The registry panics (ERR_*, see the contract) if the service is inactive, the deposit is below price + 0.002 NEAR, the nonce is malformed, or the nonce was ever used before — a nonce is single-use across the whole registry. Otherwise it forwards exactly the price to the payment target, keeps the fee, refunds the excess to the payer and stores the payment, flagging it self_paid when the payer is the service owner or payment target.

A buyer with a prepaid escrow can call pay_from_escrow with the same serviceId and nonce instead: it attaches nothing and the registry debits price + 0.002 NEAR from the buyer’s escrow, then writes the identical payment record and event. The invoice and the proof are the same for both rails (see escrow).

The X-PAYMENT header

The proof is the base64 encoding of this JSON, sent on the retried request:

X-PAYMENT (decoded)

{
  "x402Version": 1,
  "scheme": "exact",
  "network": "near-testnet",
  "payload": {
    "kind": "tx",
    "transaction": "<base58 tx hash of the pay or pay_from_escrow call>",
    "nonce": "3673826824572287",
    "payer": "<buyer account id>"
  }
}

transaction is the base58 hash of the pay (or pay_from_escrow) transaction; payer is the account that signed it. A kind: "delegate" payload carries a NEP-366 signed delegate instead, for the gateway to relay: see the gasless rail. A gateway that relays none answers it relayer_disabled.

The X-PAYMENT-RESPONSE header

A served call carries X-PAYMENT-RESPONSE: base64 JSON { success, transaction, network, payer } confirming which payment was redeemed. It is set on every call the gateway processed after verifying the payment — including one whose upstream then failed, because the buyer did pay.

Verification rules

For a request carrying a proof the gateway checks, in this order, and answers a 402 with the matching reason at the first failure. One exception in live mode: when the registry holds no payment for the nonce, the gateway looks at the transaction before answering, so a transaction that does not match gives tx_mismatch, one still executing (or executed but not yet readable) gives settlement_pending, and only an unknown or failed one gives not_found.

#CheckReason on failure
1The header decodes to a proof for this gateway’s network: a tx proof, or a delegate when the gateway relays (its own checks are below).invalid_payment_header, relayer_disabled
2An invoice with that nonce exists, for this service, unused and unexpired.unknown_nonce, invoice_used, invoice_expired
3The registry’s get_payment(nonce) view (read at optimistic finality, so a payment counts as soon as its transaction executes): exists, for this service, price at least the service price, younger than the invoice time to live, not yet attested.not_found, wrong_service, amount_too_low, expired, already_attested
4Live only: the transaction itself. Via the RPC, it must be signed by the named payer, received by the registry, hold a pay or pay_from_escrow action with the same service id and nonce, and have succeeded. While it cannot yet be shown the answer is pending.tx_mismatch, settlement_pending
5The nonce is burned (below).invoice_used

Other statuses the paywall route can answer before any invoice, so nothing is charged: 404 service_not_found, 403 service_inactive (the owner paused it), 503 service_unavailable (no upstream is mapped on this gateway, or in live mode the upstream host is not public), 415 unsupported_media_type (a request body that is not JSON), 400 invalid_json (a JSON body that does not parse), 413 payload_too_large (a body over 256 KB) and 429 rate_limited (60 requests per minute per client on /svc). The gateway caches each service record for 60 s, so a pause or resume can take up to a minute to show here.

After a verified payment the nonce is burned before the upstream is called, so these answers come after the buyer paid, with X-PAYMENT-RESPONSE set: 502 upstream_unreachable, 504 upstream_timeout, 502 upstream_response_too_large (over 1 MiB) and 502 upstream_request_too_large. The receipt records it as skipped_upstream_failed and no attestation is sent. A failure inside the gateway answers 500 internal_error, or the lower-cased code of a known error with its own status (an RPC failure while verifying, for example).

The gasless rail (a relayed pay_from_escrow)

With RELAYER_ENABLED the gateway also takes a buyer who has a prepaid escrow but pays no gas: the buyer signs its pay_from_escrow as a NEP-366 delegate and sends it in the proof, and the gateway account (GATEWAY_ACCOUNT_ID, named in extra.relayer) relays it in a transaction it signs and pays for. The escrow pays price + 0.002 NEAR; the buyer’s account pays nothing. The invoice is the same, and the payment record and event are those of any pay_from_escrow.

X-PAYMENT (decoded), gasless

{
  "x402Version": 1,
  "scheme": "exact",
  "network": "near-testnet",
  "payload": {
    "kind": "delegate",
    "signedDelegate": "<base64 borsh SignedDelegate>",
    "nonce": "3673826824572287",
    "payer": "<buyer account id>"
  }
}

signedDelegate is the base64 of a borsh NEP-366 SignedDelegate of at most 4096 bytes once decoded (a larger one is refused invalid_payment_header, like any malformed header), signed with an ed25519 key of the payer (its full-access key or an agent key for pay_from_escrow). Its delegate action is exactly what the clients build: sender = payer, receiver = the registry, one FunctionCall pay_from_escrow whose arguments are the bytes {"service_id":<id>,"nonce":"<nonce>"} of this invoice, 30 TGas, no deposit; its nonce is the signing key’s nonce + 1, read at optimistic finality so that a nonce spent in a block not yet final is not signed again, and it expires 100 blocks past the height the buyer read. NEAR has a relayer pay the deposit a relayed call attaches, so the gateway relays nothing else.

The gateway’s checks

A gateway without RELAYER_ENABLED answers a delegate proof relayer_disabled before it reads the invoice. With it, after the invoice checks (unknown_nonce, invoice_used, invoice_expired) the gateway runs these, in this order. Refusals 1–8 cost the relayer nothing: they come before the relay. relay_failed costs at most one relay’s gas. No refusal burns the nonce: the invoice stays open, and the 402 also carries a fresh one.

#CheckReason on failure
1The delegate decodes (canonical borsh, ed25519; base64 and size were already checked with the header), its sender is the payer, its receiver the registry, and it holds one FunctionCall pay_from_escrow with this invoice’s arguments, no deposit and 30 TGas.delegate_malformed, delegate_wrong_sender, delegate_wrong_receiver, delegate_wrong_action, delegate_wrong_args, delegate_deposit_not_zero, delegate_gas_too_high, delegate_gas_too_low
2The signature verifies over NEAR’s delegate encoding.bad_signature
3No relay of this invoice is in flight.settlement_pending (the same invoice)
4The registry holds no payment for the nonce yet. One it does hold is served only as the retry of a relay this gateway process sent (one that timed out, or whose record was not read yet), presented by that relay’s payer with its signing key, for this service and price; any other payment is never relayed again.invoice_used
5No relay of this invoice that this gateway sent can still land: there was none, or its delegate expired without NEAR running it (the key’s nonce, read at final, never reached the delegate’s).settlement_pending, with that relay tx in transaction
6The delegate stays valid 20 more blocks, and its nonce is below the height × 10^6 NEAR allows. This comes after the payment checks, so the retry of a relay that landed is served even once its delegate has expired.delegate_expired, delegate_nonce_too_large
7The signing key is an access key of the payer, read at final: full access, or a function-call key for the registry allowing pay_from_escrow. The delegate nonce is above the key’s nonce read at optimistic finality (a nonce spent in a block not yet final is spent), above every nonce this gateway relayed for that key whose delegate may still run, and not the nonce of a relay of that key in flight.unknown_key, key_not_allowed, stale_nonce
8The escrow holds price + 0.002 NEAR.escrow_insufficient
9The relay: the registry’s own receipt must have succeeded — the transaction’s status is never trusted alone — and its payment record must name the payer, this service and the price. The gateway remembers the relay as soon as it is sent, before it reads anything else.relay_failed, with a code (below); settlement_pending with the relay tx, in transaction, when the outcome is unknown (a timeout) or the record is not read yet; a record of another payer, service or price: tx_mismatch or its reason

The code of a relay_failed says whose failure it was: the registry’s ERR_* (e.g. ERR_ESCROW_INSUFFICIENT) or CONTRACT_ERROR when NEAR ran the delegate and its call failed; DELEGATE_REJECTED when NEAR refused the delegate itself (its key or nonce changed after the checks); RELAYER_ERROR when the relay failed on the gateway’s side (its key, account or balance, or the RPC), whose detail stays in the gateway’s log.

A served call is burned, proxied and attested as on the tx rail; its X-PAYMENT-RESPONSE names the relay transaction. While the answer is settlement_pending, present the same delegate again: once the relay has landed the retry is served without a second relay. The clients do this on their own: a gasless buy presents the same delegate again after each settlement_pending, waiting the Retry-After clamped to 1–10 s, until the gateway answers definitively; it waits at most 150 s in all (the client’s gaslessWaitMs), longer than the delegate’s 100 blocks. Never sign a new delegate for an invoice whose relay may still land. A relay whose delegate NEAR ran but whose call did not pay keeps the invoice pending until it expires. The relays a gateway sent stay in its memory until their invoice is served, so a gateway restart forgets them: the retry of a relay that landed before the restart is then invoice_used, and a delegate whose relay had not landed yet can be relayed a second time. NEAR runs a delegate nonce once, so that cannot pay twice, but the second relay costs gas and its answer (relay_failed or stale_nonce) does not say the first one paid: after either, read the escrow balance before buying again. What this means for the relayer and for front-running is on the security page.

Single-use nonce and idempotency

Once a proof verifies, the gateway burns the nonce before it proxies: the call is single-use even if the upstream then fails, and when several requests race on one proof exactly one wins and the rest get invoice_used. The registry enforces the same rule on-chain — pay refuses a reused nonce with ERR_NONCE_USED — so a nonce can never be paid twice, anywhere.

The consequence for a client: after you have paid, a failed call is not a reason to pay again. Re-present the same proof; if the gateway answers settlement_pending wait and resend it; only an invoice the gateway never issued or that expired unused needs a new payment. The client package turns a paid call that was not served into PAID_NOT_SERVED carrying exactly that proof (on the gasless rail, GASLESS_NOT_SERVED, which says whether the escrow paid). Invoices live in the gateway’s memory unless INVOICE_STORE_PATH points at a JSON file, so without one a gateway restart forgets open invoices (unknown_nonce).

Attestation and trust score

After it has answered the buyer, the gateway calls record_attestation(service_id, nonce, payment_tx_hash, success) as its own account (GATEWAY_ACCOUNT_ID). The registry accepts it only from the service’s attestor or owner, so a service must name its gateway’s account as attestor when it registers (wrap --attestor); otherwise every attestation is rejected and paid calls are never scored. success is whether the upstream answered with a 2xx. It never blocks the buyer: a failed attempt is retried with exponential backoff (5 s, 10 s, 20 s — four attempts) and, with ATTESTATION_QUEUE_PATH set, an attestation that never confirmed is replayed when the gateway next boots.

The gateway does not attest — the call is served but not scored — when:

CaseWhy
The upstream could not be reached, timed out or answered too large a bodyThat is the seller’s backend being down, not a service outcome: it is scored neither way. The receipt says skipped_upstream_failed.
The payer is the service owner or the payment targetA self-paid call can never raise a score. The registry itself rejects it (ERR_SELF_PAYMENT); the receipt says skipped_self_paid.

The registry keeps (total_calls, success_calls) per service and the latest 100 attestations, newest first. The trust tier is derived from the score, with exact integer arithmetic:

TierRule
newfewer than 5 attested calls, or a success rate below 90%
reliableat least 5 calls and at least 90% successful
trustedat least 25 calls and at least 95% successful

Receipts: GET /receipts/:nonce

A contract view cannot know the transaction that produced its own event, so the registry’s activity feed names a block, not a transaction. The only party that knows the transaction of an attestation is the gateway that sent it, so the gateway serves what it did about each paid call, keyed by the invoice nonce. This is where a buyer, a seed script or the waitForReceipt helper in @neargate/sdk learns the attestation’s transaction.

curl <gateway>/receipts/3673826824572287

(no payment, no header needed)

200 response

{
  "nonce": "3673826824572287",
  "serviceId": 1,
  "paymentTxHash": "<the pay transaction the buyer presented>",
  "attestation": {
    "status": "recorded",
    "txHash": "<the record_attestation transaction>"
  }
}
attestation.statusMeaning
pendingThe call was served; the attestation is still being sent or retried. Poll again.
recordedThe registry holds the attestation. txHash names the gateway’s transaction; it is absent when the registry already had it from another party (ERR_ALREADY_ATTESTED).
skipped_self_paidThe payer is the service owner or payment target: served, never attested.
skipped_upstream_failedThe gateway could not reach the upstream: not scored either way.
failedEvery attempt failed. A gateway with a persistent attestation queue retries on its next boot.

WHAT TO RELY ON

An unknown nonce answers 404 receipt_not_found. Receipts live in the memory of one gateway process, bounded to its last 1000 paid calls (the oldest goes first), and are gone after a restart; a buyer needing a durable record should read the chain (get_payment, get_attestations). The route is public, answers a receipt with Cache-Control: no-store and allows 60 requests per minute; everything in a receipt is already public on-chain.

Gateway routes

RoutePurpose
ALL /svc/:idThe paywall: 402 challenge, then the proxied upstream response.Auth: the x402 proof
GET /svc/:id/metaThe service record, its score and trust tier as JSON, unpaid.Auth: none
GET /receipts/:nonceThe attestation receipt above.Auth: none
GET /healthzLiveness: { ok, network }.Auth: none
GET /readyzReadiness: the chain is reachable; 503 { ready: false } when it is not.Auth: none
POST /services/:id/mapThe service owner maps the private upstream with a signed request — see the self-map signature.Auth: the owner’s signature
POST, GET /admin/servicesOperator mapping of upstreams by token: how mock mode maps, and a self-hosted fallback. Rate limited to 20 per minute.Auth: the admin bearer token
DELETE /admin/services/:idRemoves a mapping.Auth: the admin bearer token