Let an agent pay for its own inference

Moth DocsTutorials

Give an agent a moth_ key and a wallet with USDG, and it tops up its own balance over HTTP 402, then keeps calling models. Nobody approves each payment.

An agent that runs for hours stops when its balance runs out, unless a person is there to add credit. With x402 the agent adds the credit itself. It signs one USDG transfer to your account's deposit address, Moth sends it on Robinhood Chain and pays the gas, and the balance shows it a few seconds later. The agent then carries on with the same key, on the same private balance.

Set it up once

  1. Make a key for the agent

    Sign in to Moth Console and make a key under API keys, with a spend cap that fits the job. Keys and their limits explains the cap.

  2. Give the agent its own wallet

    Create a new wallet for the agent alone and send it the USDG it may spend, on Robinhood Chain. It needs no ETH, since the agent only signs.

  3. Hand over two secrets

    The agent gets the key as MOTH_API_KEY and its wallet's private key as AGENT_WALLET_KEY. That is all it needs.

The wallet doesn't have to be yours. The credit goes to the account behind the key, whichever wallet signs. So the agent's wallet can be a fresh one that has never signed in anywhere.

The loop

The agent has two ways to know it needs credit, and one way to add it.

SignalWhat the agent reads
The balance is lowGET /v1/usage with the key returns balance_usd, the account's balance in dollars.
A call is refusedA model call answers 402 with the error type insufficient_credit and the message "Not enough credit for this request. Top up to continue." The status and type are the same on /v1/chat/completions, /v1/messages and the media jobs.
The key is at its capAlso 402 and insufficient_credit, with "spend cap" in the message. A top-up doesn't help here, so the agent should stop.
  1. Ask for the offer

    POST /v1/credits/x402?amount_usd=5 with the key answers 402 and one offer in the PAYMENT-REQUIRED header. The agent checks that it names USDG on Robinhood Chain and the amount it asked for.

  2. Sign and send it back

    The agent signs the transfer and sends the same call again with the PAYMENT-SIGNATURE header.

  3. Wait for the credit

    200 means the transfer is sent. 202 means it is still on its way, and GET /v1/credits/x402/{id} says when it is sent. The balance rises a few seconds after the transfer is mined.

  4. Call the model again

    The agent repeats the call that was refused, and it runs.

A complete agent in TypeScript

This file is the whole loop. It reads the balance, tops up when it is low or when a call answers 402, waits for the credit and asks again. It needs Node 20 or later and viem.

shell
npm install viem
MOTH_API_KEY=moth_... AGENT_WALLET_KEY=0x... npx tsx agent.mts
agent.mts
// agent.mts: an agent that pays for its own inference on Moth.
//   MOTH_API_KEY          a key made once in Moth Console, with a spend cap
//   AGENT_WALLET_KEY      the private key of the agent's own wallet, holding only the USDG it may spend
//   MOTH_DEPOSIT_ADDRESS  optional: your account's deposit address from the Credit page, so the agent pays nowhere else
import { privateKeyToAccount } from "viem/accounts";

const API = process.env.MOTH_API_URL ?? "https://api.runmoth.ai";
const USDG = "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"; // USDG on Robinhood Chain
const MODEL = "claude-haiku-5.5";
const LOW_USD = 0.5;   // top up before working when the balance is under this
const TOP_UP_USD = 5;  // one top-up. The API takes $1 to $1,000, so the ceiling is yours to set
const BUDGET_USD = 20; // the most this run may top up in all

const headers = { Authorization: `Bearer ${process.env.MOTH_API_KEY}`, "Content-Type": "application/json" };
const wallet = privateKeyToAccount(process.env.AGENT_WALLET_KEY as `0x${string}`);
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
let toppedUp = 0;

/** The account's balance in dollars, read with the key. */
async function balance(): Promise<number> {
  const r = await fetch(`${API}/v1/usage`, { headers });
  if (!r.ok) throw new Error(`Could not read the balance: ${r.status}`);
  return Number((await r.json()).balance_usd);
}

/** Adds credit with one signed USDG transfer, and returns once the balance shows it. */
async function topUp(usd: number): Promise<void> {
  if (toppedUp + usd > BUDGET_USD) throw new Error("This run's top-up budget is spent.");
  const url = `${API}/v1/credits/x402?amount_usd=${usd}`;

  // 1. Ask for the offer, and check it before signing anything.
  const offer = await fetch(url, { method: "POST", headers });
  if (offer.status === 503) throw new Error("x402 is paused for now. Try again later.");
  if (offer.status !== 402) throw new Error(`No offer: ${offer.status}`);
  const accepted = JSON.parse(atob(offer.headers.get("PAYMENT-REQUIRED") ?? "")).accepts[0];
  const pinned = process.env.MOTH_DEPOSIT_ADDRESS;
  const asAsked = accepted.scheme === "exact" && accepted.network === "eip155:4663"
    && accepted.asset.toLowerCase() === USDG.toLowerCase() && accepted.amount === String(usd * 1_000_000)
    && (!pinned || accepted.payTo.toLowerCase() === pinned.toLowerCase());
  if (!asAsked) throw new Error("The offer is not the one asked for, so nothing was signed.");

  // 2. Sign one transfer of exactly that amount, valid for five minutes, with a nonce used once.
  const now = BigInt(Math.floor(Date.now() / 1000));
  const nonce = `0x${[...crypto.getRandomValues(new Uint8Array(32))].map((b) => b.toString(16).padStart(2, "0")).join("")}` as const;
  const authorization = { from: wallet.address, to: accepted.payTo, value: BigInt(accepted.amount), validAfter: now - 30n, validBefore: now + 300n, nonce };
  const signature = await wallet.signTypedData({
    domain: { name: accepted.extra.name, version: accepted.extra.version, chainId: 4663, verifyingContract: accepted.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: authorization,
  });

  // 3. Send the same call again with the signature. Moth sends the transfer and pays the gas.
  const payment = btoa(JSON.stringify({ x402Version: 2, accepted, payload: { signature, authorization: {
    ...authorization, value: String(authorization.value), validAfter: String(authorization.validAfter), validBefore: String(authorization.validBefore),
  } } }));
  const before = await balance();
  const paid = await fetch(url, { method: "POST", headers: { ...headers, "PAYMENT-SIGNATURE": payment } });
  let top = await paid.json();
  if (paid.status === 503) throw new Error("x402 is paused for now. Try again later.");
  if (paid.status !== 200 && paid.status !== 202) throw new Error(`The top-up was refused: ${paid.status} ${top.error?.message ?? top.error ?? ""}`);
  toppedUp += usd;

  // 4. 200 means sent. 202 means still on its way, so read the top-up until it is sent.
  for (let i = 0; i < 90 && top.status === "queued"; i++) {
    await sleep(2000);
    top = await (await fetch(`${API}/v1/credits/x402/${top.id}`, { headers })).json();
  }
  if (top.status === "failed" || top.status === "expired") {
    toppedUp -= usd; // nothing moved
    throw new Error(`The top-up ${top.status}: ${top.error}`);
  }

  // 5. The credit comes from the transfer itself, a few seconds after it is mined.
  for (let i = 0; i < 90 && (await balance()) <= before; i++) await sleep(2000);
  if ((await balance()) <= before) throw new Error(`Top-up ${top.id} was sent but is not credited yet.`);
  console.log(`Topped up $${usd}: ${top.tx_hash}`);
}

/** One model call. If the balance can't cover it, the agent tops up and asks again, once. */
async function ask(prompt: string): Promise<string> {
  for (let attempt = 0; attempt < 2; attempt++) {
    const r = await fetch(`${API}/v1/chat/completions`, { method: "POST", headers,
      body: JSON.stringify({ model: MODEL, max_tokens: 300, messages: [{ role: "user", content: prompt }] }) });
    if (r.ok) return (await r.json()).choices[0].message.content;
    const { error } = await r.json();
    // 402 insufficient_credit: the balance can't cover this call. A key at its spend cap gets the same status with
    // "spend cap" in the message, and no top-up helps that, so the agent stops.
    const outOfCredit = r.status === 402 && error?.type === "insufficient_credit" && !/spend cap/.test(error.message);
    if (!outOfCredit || attempt === 1) throw new Error(`${r.status} ${error?.message ?? ""}`);
    await topUp(TOP_UP_USD);
  }
  throw new Error("unreachable");
}

if ((await balance()) < LOW_USD) await topUp(TOP_UP_USD);
console.log(await ask("In one sentence, what does HTTP status 402 mean?"));

The same agent in Python

shell
pip install requests eth-account
MOTH_API_KEY=moth_... AGENT_WALLET_KEY=0x... python3 agent.py
agent.py
# agent.py: an agent that pays for its own inference on Moth.  pip install requests eth-account
#   MOTH_API_KEY          a key made once in Moth Console, with a spend cap
#   AGENT_WALLET_KEY      the private key of the agent's own wallet, holding only the USDG it may spend
#   MOTH_DEPOSIT_ADDRESS  optional: your account's deposit address from the Credit page, so the agent pays nowhere else
import base64, json, os, secrets, time

import requests
from eth_account import Account

API = os.environ.get("MOTH_API_URL", "https://api.runmoth.ai")
USDG = "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"  # USDG on Robinhood Chain
MODEL = "claude-haiku-5.5"
LOW_USD = 0.5    # top up before working when the balance is under this
TOP_UP_USD = 5   # one top-up. The API takes $1 to $1,000, so the ceiling is yours to set
BUDGET_USD = 20  # the most this run may top up in all

headers = {"Authorization": f"Bearer {os.environ['MOTH_API_KEY']}", "Content-Type": "application/json"}
wallet = Account.from_key(os.environ["AGENT_WALLET_KEY"])
topped_up = 0


def balance() -> float:
    """The account's balance in dollars, read with the key."""
    r = requests.get(f"{API}/v1/usage", headers=headers)
    r.raise_for_status()
    return float(r.json()["balance_usd"])


def top_up(usd: int) -> None:
    """Adds credit with one signed USDG transfer, and returns once the balance shows it."""
    global topped_up
    if topped_up + usd > BUDGET_USD:
        raise RuntimeError("This run's top-up budget is spent.")
    url = f"{API}/v1/credits/x402?amount_usd={usd}"

    # 1. Ask for the offer, and check it before signing anything.
    offer = requests.post(url, headers=headers)
    if offer.status_code == 503:
        raise RuntimeError("x402 is paused for now. Try again later.")
    if offer.status_code != 402:
        raise RuntimeError(f"No offer: {offer.status_code}")
    accepted = json.loads(base64.b64decode(offer.headers["PAYMENT-REQUIRED"]))["accepts"][0]
    pinned = os.environ.get("MOTH_DEPOSIT_ADDRESS")
    as_asked = (
        accepted["scheme"] == "exact" and accepted["network"] == "eip155:4663"
        and accepted["asset"].lower() == USDG.lower() and accepted["amount"] == str(usd * 1_000_000)
        and (not pinned or accepted["payTo"].lower() == pinned.lower())
    )
    if not as_asked:
        raise RuntimeError("The offer is not the one asked for, so nothing was signed.")

    # 2. Sign one transfer of exactly that amount, valid for five minutes, with a nonce used once.
    now = int(time.time())
    authorization = {"from": wallet.address, "to": accepted["payTo"], "value": int(accepted["amount"]),
                     "validAfter": now - 30, "validBefore": now + 300, "nonce": "0x" + secrets.token_hex(32)}
    signed = Account.sign_typed_data(
        wallet.key,
        {"name": accepted["extra"]["name"], "version": accepted["extra"]["version"], "chainId": 4663, "verifyingContract": accepted["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"},
        ]},
        authorization,
    )

    # 3. Send the same call again with the signature. Moth sends the transfer and pays the gas.
    payload = {"signature": "0x" + bytes(signed.signature).hex(),
               "authorization": {**authorization, "value": str(authorization["value"]),
                                 "validAfter": str(authorization["validAfter"]), "validBefore": str(authorization["validBefore"])}}
    payment = base64.b64encode(json.dumps({"x402Version": 2, "accepted": accepted, "payload": payload}).encode()).decode()
    before = balance()
    paid = requests.post(url, headers={**headers, "PAYMENT-SIGNATURE": payment})
    top = paid.json()
    if paid.status_code == 503:
        raise RuntimeError("x402 is paused for now. Try again later.")
    if paid.status_code not in (200, 202):
        error = top.get("error")
        raise RuntimeError(f"The top-up was refused: {paid.status_code} {error.get('message') if isinstance(error, dict) else error}")
    topped_up += usd

    # 4. 200 means sent. 202 means still on its way, so read the top-up until it is sent.
    for _ in range(90):
        if top["status"] != "queued":
            break
        time.sleep(2)
        top = requests.get(f"{API}/v1/credits/x402/{top['id']}", headers=headers).json()
    if top["status"] in ("failed", "expired"):
        topped_up -= usd  # nothing moved
        raise RuntimeError(f"The top-up {top['status']}: {top['error']}")

    # 5. The credit comes from the transfer itself, a few seconds after it is mined.
    for _ in range(90):
        if balance() > before:
            break
        time.sleep(2)
    else:
        raise RuntimeError(f"Top-up {top['id']} was sent but is not credited yet.")
    print(f"Topped up ${usd}: {top['tx_hash']}")


def ask(prompt: str) -> str:
    """One model call. If the balance can't cover it, the agent tops up and asks again, once."""
    for attempt in range(2):
        r = requests.post(f"{API}/v1/chat/completions", headers=headers,
                          json={"model": MODEL, "max_tokens": 300, "messages": [{"role": "user", "content": prompt}]})
        if r.ok:
            return r.json()["choices"][0]["message"]["content"]
        error = r.json().get("error") or {}
        # 402 insufficient_credit: the balance can't cover this call. A key at its spend cap gets the same status with
        # "spend cap" in the message, and no top-up helps that, so the agent stops.
        out_of_credit = r.status_code == 402 and error.get("type") == "insufficient_credit" and "spend cap" not in error.get("message", "")
        if not out_of_credit or attempt == 1:
            raise RuntimeError(f"{r.status_code} {error.get('message', '')}")
        top_up(TOP_UP_USD)
    raise RuntimeError("unreachable")


if balance() < LOW_USD:
    top_up(TOP_UP_USD)
print(ask("In one sentence, what does HTTP status 402 mean?"))

Both files were run against the API on a copy of Robinhood Chain before this page was written. Each topped up from an empty balance, and from a refused call, and then got its reply.

Keep it safe

An agent that can pay is an agent that can overpay, so set the limits before it runs. Each one below is in the example or in the API.

  • A wallet of its own. Give the agent a new wallet holding only what it may spend. Never put the key of your main wallet, or of the wallet that owns the account, in an agent.
  • A ceiling in code. The API takes $1 to $1,000 a top-up. The example tops up $5 at a time and stops at $20 a run, and both numbers are yours to set.
  • A cap on the key. The key's spend cap limits what the agent can spend on models in a day, a week or a month, however much credit the account holds.
  • Check the offer before signing. The example signs only an offer for USDG on Robinhood Chain and for the amount it asked for. Set MOTH_DEPOSIT_ADDRESS to the address on your Credit page, and it also refuses an offer that pays anywhere else.
  • Small top-ups show sooner. Up to $25 not yet settled is credited as soon as the transfer is seen, and the rest once the chain marks it final, about 15 minutes later.
  • A signature works once. Each one carries a new nonce and runs out after five minutes. A signature sent twice is refused with "This authorization was already used.", so a replay moves nothing.
  • Paused means wait. While x402 is paused the call answers 503, and GET /v1/credits/x402/status says so. The agent should wait and try later, or stop and let you send USDG to the deposit address.
  • Limits on the API. An account may try 10 top-ups an hour and have three on their way at once. Past that the call answers 429.
  • Stop on a cap. A 402 that names the spend cap is your limit working. The example stops there and signs nothing.

The same private balance

Credit an agent adds is the account's ordinary balance. Calls paid from it pass the Mothpoint like any others, so the model's host never receives the key, the wallet or the IP address, and Moth keeps no prompt or reply. The paying wallet's address is used for the signature and the transfer, and it is never sent to a model's host. The transfer itself is public on Robinhood Chain, as every deposit is. What is removed has the detail.

  • A key you make in Moth Console can top up. A free session cannot.
  • Any key reads the whole account's balance and usage, so give a key only to an agent you would trust with those figures.
  • The x402 reference lists every field, status and error. Top up with x402 shows the same payment in Moth Console.
On this page