Build an agent
Pay over plain HTTP
The SDK, the CLI and the MCP server pay for you. This page is for when you can't use them: another language, a small runtime, or you want to see every step. A payment is two HTTP requests and one signature. You need nothing from Autonomo or x402, only a library that can sign typed data (EIP-712), which most Ethereum libraries can.
What you need
- A wallet that holds USDG on Robinhood Chain, or USDC on Base. A few cents is enough: most calls cost a cent or less.
- No ETH. The wallet signs a message and sends no transaction, so it pays no gas.
- A wallet made for the agent, with a small balance. Never the wallet that holds your savings.
The payment, step by step
Each step comes with the data it is about, and with the code for it in curl, JavaScript or Python. The JavaScript and Python are pieces of the two whole files further down, which also hold their small helpers (decode, encode and Python's get).
Ask for the price
Send the request with no payment. The API answers
402. The price list is not in the body: it is in thePAYMENT-REQUIREDheader, as base64 of a JSON text.The price list shown with this step is that header, decoded and shortened.
curlcurl -i "https://autonomo.fun/x/gas-now/gas"PAYMENT-REQUIRED, decoded{ "x402Version": 2, "resource": { "url": "https://autonomo.fun/x/gas-now/gas", "description": "...", "mimeType": "application/json" }, "accepts": [ { "scheme": "exact", "network": "eip155:4663", "amount": "5000", "asset": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", "payTo": "0x...", "maxTimeoutSeconds": 300, "extra": { "name": "Global Dollar", "version": "1" } }, { "scheme": "exact", "network": "eip155:8453", "amount": "5000", "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "payTo": "0x...", "maxTimeoutSeconds": 300, "extra": { "name": "USD Coin", "version": "2" } } ], "extensions": { "bazaar": { "...": "..." } } }Choose an option
acceptslists every way to pay for this call. This guide covers the two that need one signature and nothing else:- USDG on Robinhood Chain: network
eip155:4663, asset0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168. The usual price on Autonomo. - USDC on Base: network
eip155:8453, asset0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913. On most Autonomo APIs, at the same dollar price.
Pick by network and asset address, and check the price against a limit of your own before you go on. The list can hold other options too: $AUTONOMO (marked
permit2, which needs an approval first, see Pay from your own code) and a private payment (gloam-cashout, see Pay privately with Gloam).curl# Nothing to send in this step. # Pick one option from "accepts" in the price list.- USDG on Robinhood Chain: network
Sign the transfer
Sign the typed data shown with this step, with the wallet's key. It allows one transfer of exactly
amount, to exactlypayTo, untilvalidBefore. It is filled in for the USDG option.The result is a 65-byte signature, written as
0xand 130 hex characters. The standard is EIP-3009, which USDG and USDC both support.curl# curl can't sign. Use a wallet library for this step: # switch to JavaScript or Python to see one do it.The typed data to sign{ "domain": { "name": "Global Dollar", // extra.name "version": "1", // extra.version "chainId": 4663, // the number in "eip155:4663" "verifyingContract": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168" // asset }, "primaryType": "TransferWithAuthorization", "types": { "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" } ] }, "message": { "from": "0x...", // your wallet "to": "0x...", // payTo "value": "5000", // amount "validAfter": "0", "validBefore": "1795000300", // now, in seconds, plus maxTimeoutSeconds "nonce": "0x..." // 32 random bytes, new for every payment } }Ask again, with the payment
Build the payment shown with this step, encode it as base64 and send the same request again (same method, address and body) with it in the
PAYMENT-SIGNATUREheader. The numbers insideauthorizationare strings.curlcurl -i "https://autonomo.fun/x/gas-now/gas" \ -H "PAYMENT-SIGNATURE: <the payment, as base64>"The payment, before base64{ "x402Version": 2, "accepted": { ... }, // the option you chose, exactly as it came "resource": { ... }, // copied from the price list "extensions": { ... }, // copied from the price list "payload": { "authorization": { "from": "0x...", "to": "0x...", "value": "5000", "validAfter": "0", "validBefore": "1795000300", "nonce": "0x..." }, "signature": "0x..." } }Read the answer
A paid call answers as the API normally would, and adds a receipt in the
PAYMENT-RESPONSEheader, again base64 of a JSON text.transactionis the payment on-chain.If the payment is refused, the answer is
402again, with the reason in theerrorfield of a newPAYMENT-REQUIREDheader, for exampleinsufficient_funds. Nothing was taken. If the API itself fails, the payment doesn't settle either, so you aren't charged.PAYMENT-RESPONSE, decoded{ "success": true, "transaction": "0x...", "network": "eip155:4663", "payer": "0x..." }
Ask for the price
curl -i "https://autonomo.fun/x/gas-now/gas"{
"x402Version": 2,
"resource": {
"url": "https://autonomo.fun/x/gas-now/gas",
"description": "...",
"mimeType": "application/json"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:4663",
"amount": "5000",
"asset": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
"payTo": "0x...",
"maxTimeoutSeconds": 300,
"extra": { "name": "Global Dollar", "version": "1" }
},
{
"scheme": "exact",
"network": "eip155:8453",
"amount": "5000",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"payTo": "0x...",
"maxTimeoutSeconds": 300,
"extra": { "name": "USD Coin", "version": "2" }
}
],
"extensions": { "bazaar": { "...": "..." } }
}What each field of an option in accepts means:
| amount | The price in the token's smallest unit. USDG and USDC have 6 decimals, so 5000 is $0.005. |
| asset | The token's contract address. Check this, not a name, to know which token it is. |
| network | The chain: eip155:4663 is Robinhood Chain, eip155:8453 is Base. |
| payTo | The address the payment goes to. Always take it from the header of the call you are paying for. |
| maxTimeoutSeconds | How long your signature should stay valid. |
| extra | The token's name and version. You need both to sign. |
The whole thing in JavaScript
One file, about a hundred lines, with one package for signing. It pays USDG on Robinhood Chain unless told otherwise, and refuses any price over 50 cents.
npm install viem
AUTONOMO_WALLET_KEY=0x... node pay.mjs "https://autonomo.fun/x/gas-now/gas"// Pay an x402 API over plain HTTP: ask for the price, sign once, ask again with the payment.
// Needs Node 18 or newer and one package, for signing: npm install viem
// Run: AUTONOMO_WALLET_KEY=0x... node pay.mjs "https://autonomo.fun/x/gas-now/gas"
import { getAddress } from "viem";
import { privateKeyToAccount } from "viem/accounts";
// The dollars this wallet pays with. To pay USDC on Base instead, set NETWORK to "eip155:8453".
const NETWORK = process.env.PAY_NETWORK || "eip155:4663";
const DOLLARS = {
"eip155:4663": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", // USDG on Robinhood Chain
"eip155:8453": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
};
const MAX_PRICE = 0.5; // dollars. Never sign for more than this.
const url = process.argv[2];
if (!url || !process.env.AUTONOMO_WALLET_KEY) {
console.error('Usage: AUTONOMO_WALLET_KEY=0x... node pay.mjs "<api url>"');
process.exit(1);
}
const account = privateKeyToAccount(process.env.AUTONOMO_WALLET_KEY);
const decode = (header) => JSON.parse(Buffer.from(header, "base64").toString("utf8"));
const encode = (value) => Buffer.from(JSON.stringify(value), "utf8").toString("base64");
// 1. Ask. With no payment the API answers 402 and puts its price list in the PAYMENT-REQUIRED header.
const first = await fetch(url);
if (first.status !== 402) {
console.log(first.status, await first.text());
process.exit(first.ok ? 0 : 1);
}
const required = decode(first.headers.get("payment-required"));
// 2. Choose the option that is the token above, on the network above.
const offer = required.accepts.find(
(o) =>
o.scheme === "exact" &&
o.network === NETWORK &&
o.asset.toLowerCase() === DOLLARS[NETWORK].toLowerCase() &&
o.extra?.name, // a name here means one signature is enough
);
if (!offer) throw new Error(`This API has no one-signature price on ${NETWORK}`);
const price = Number(offer.amount) / 1e6; // USDG and USDC both count in millionths of a dollar
if (price > MAX_PRICE) throw new Error(`The price is $${price}, over the limit of $${MAX_PRICE}`);
// 3. Sign a transfer of exactly that amount to exactly that address.
// It is a signature, not a transaction, so the wallet pays no gas.
const authorization = {
from: account.address,
to: getAddress(offer.payTo),
value: offer.amount,
validAfter: "0",
validBefore: String(Math.floor(Date.now() / 1000) + offer.maxTimeoutSeconds),
// 32 random bytes, new for every payment
nonce: "0x" + Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex"),
};
const signature = await account.signTypedData({
domain: {
name: offer.extra.name,
version: offer.extra.version,
chainId: Number(offer.network.split(":")[1]),
verifyingContract: getAddress(offer.asset),
},
types: {
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" },
],
},
primaryType: "TransferWithAuthorization",
message: {
from: authorization.from,
to: authorization.to,
value: BigInt(authorization.value),
validAfter: BigInt(authorization.validAfter),
validBefore: BigInt(authorization.validBefore),
nonce: authorization.nonce,
},
});
// 4. Ask again, the same request, with the payment in the PAYMENT-SIGNATURE header.
const payment = {
x402Version: required.x402Version,
payload: { authorization, signature },
extensions: required.extensions, // copied back as it came
resource: required.resource, // copied back as it came
accepted: offer, // the option you chose, unchanged
};
const paid = await fetch(url, { headers: { "PAYMENT-SIGNATURE": encode(payment) } });
// 5. Read the answer. A paid call carries a receipt in the PAYMENT-RESPONSE header.
if (paid.status === 402) {
const again = paid.headers.get("payment-required");
const failed = paid.headers.get("payment-response");
const reason = (failed && decode(failed).errorReason) || (again && decode(again).error) || "no reason given";
console.error(`Not paid: ${reason}`);
process.exit(1);
}
console.log(paid.status, await paid.text());
const receipt = paid.headers.get("payment-response");
if (receipt) console.log(`Paid $${price}. Transaction: ${decode(receipt).transaction}`);To pay with USDC on Base, name the network:
PAY_NETWORK=eip155:8453 AUTONOMO_WALLET_KEY=0x... node pay.mjs "https://autonomo.fun/x/gas-now/gas"The same in Python
The same steps with the standard library and one package for signing.
pip install eth-account
AUTONOMO_WALLET_KEY=0x... python pay.py "https://autonomo.fun/x/gas-now/gas"# Pay an x402 API over plain HTTP: ask for the price, sign once, ask again with the payment.
# Needs Python 3.9 or newer and one package, for signing: pip install eth-account
# Run: AUTONOMO_WALLET_KEY=0x... python pay.py "https://autonomo.fun/x/gas-now/gas"
import base64
import json
import os
import secrets
import sys
import time
import urllib.error
import urllib.request
from eth_account import Account
from eth_utils import to_checksum_address
# The dollars this wallet pays with. To pay USDC on Base instead, set NETWORK to "eip155:8453".
NETWORK = os.environ.get("PAY_NETWORK") or "eip155:4663"
DOLLARS = {
"eip155:4663": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", # USDG on Robinhood Chain
"eip155:8453": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", # USDC on Base
}
MAX_PRICE = 0.5 # dollars. Never sign for more than this.
if len(sys.argv) < 2 or not os.environ.get("AUTONOMO_WALLET_KEY"):
sys.exit('Usage: AUTONOMO_WALLET_KEY=0x... python pay.py "<api url>"')
url = sys.argv[1]
account = Account.from_key(os.environ["AUTONOMO_WALLET_KEY"])
def decode(header):
return json.loads(base64.b64decode(header))
def encode(value):
return base64.b64encode(json.dumps(value).encode()).decode()
def get(headers=None):
"""One GET. urllib raises on 402, and the error carries the status, headers and body we need."""
request = urllib.request.Request(url, headers={"User-Agent": "pay.py", **(headers or {})})
try:
return urllib.request.urlopen(request, timeout=60)
except urllib.error.HTTPError as answer:
return answer
# 1. Ask. With no payment the API answers 402 and puts its price list in the PAYMENT-REQUIRED header.
first = get()
if first.status != 402:
print(first.status, first.read().decode())
sys.exit(0 if first.status < 400 else 1)
required = decode(first.headers["payment-required"])
# 2. Choose the option that is the token above, on the network above.
offer = next(
(
o
for o in required["accepts"]
if o["scheme"] == "exact"
and o["network"] == NETWORK
and o["asset"].lower() == DOLLARS[NETWORK].lower()
and o.get("extra", {}).get("name") # a name here means one signature is enough
),
None,
)
if offer is None:
sys.exit(f"This API has no one-signature price on {NETWORK}")
price = int(offer["amount"]) / 1e6 # USDG and USDC both count in millionths of a dollar
if price > MAX_PRICE:
sys.exit(f"The price is ${price}, over the limit of ${MAX_PRICE}")
# 3. Sign a transfer of exactly that amount to exactly that address.
# It is a signature, not a transaction, so the wallet pays no gas.
nonce = secrets.token_bytes(32) # 32 random bytes, new for every payment
authorization = {
"from": account.address,
"to": to_checksum_address(offer["payTo"]),
"value": offer["amount"],
"validAfter": "0",
"validBefore": str(int(time.time()) + offer["maxTimeoutSeconds"]),
"nonce": "0x" + nonce.hex(),
}
signed = Account.sign_typed_data(
account.key,
{
"name": offer["extra"]["name"],
"version": offer["extra"]["version"],
"chainId": int(offer["network"].split(":")[1]),
"verifyingContract": offer["asset"],
},
{
"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": authorization["from"],
"to": authorization["to"],
"value": int(authorization["value"]),
"validAfter": int(authorization["validAfter"]),
"validBefore": int(authorization["validBefore"]),
"nonce": nonce,
},
)
# 4. Ask again, the same request, with the payment in the PAYMENT-SIGNATURE header.
payment = {
"x402Version": required["x402Version"],
"payload": {"authorization": authorization, "signature": "0x" + bytes(signed.signature).hex()},
"extensions": required.get("extensions"), # copied back as it came
"resource": required.get("resource"), # copied back as it came
"accepted": offer, # the option you chose, unchanged
}
payment = {k: v for k, v in payment.items() if v is not None}
paid = get({"PAYMENT-SIGNATURE": encode(payment)})
# 5. Read the answer. A paid call carries a receipt in the PAYMENT-RESPONSE header.
if paid.status == 402:
again, failed = paid.headers["payment-required"], paid.headers["payment-response"]
reason = (failed and decode(failed).get("errorReason")) or (again and decode(again).get("error"))
sys.exit(f"Not paid: {reason or 'no reason given'}")
print(paid.status, paid.read().decode())
receipt = paid.headers["payment-response"]
if receipt:
print(f"Paid ${price}. Transaction: {decode(receipt)['transaction']}")Rules that keep the wallet safe
- Set a price limit and check it before signing. The API names the price, so your code is the only thing that can say no.
- Sign only for a token you chose. Compare the
assetaddress with one written in your code. The name inextrais only a label. - Use a new random nonce every time. A signature works once, and a nonce that was used is refused.
- Keep the signature short-lived. Use
maxTimeoutSecondsfrom the price list and no more. - Keep the key out of the code. Read it from the environment or a secrets store, and never print it.
Both examples follow these rules, and both are tested on every change to this site: the payment each one sends is compared, field for field, with what the official x402 client sends.
When you want more
The SDK adds what these files leave out: finding an API from a description, a daily budget, $AUTONOMO payments, private payments and credit. To find APIs yourself, the free discovery API is on the API reference, and the official APIs are described in one file at /openapi.json.