# An agent that buys by itself

[`agent.mjs`](agent.mjs) is a program with its own wallet. It uses an app that sells with sub3 as a signed-in
customer, and when the app answers that its credits ran out, it buys a pack and carries on. No browser, no
transaction of its own and no gas: it signs a sign-in message, and to buy it signs one USDC transfer, which sub3
submits ([x402](https://www.x402.org)).

> **Preview.** x402 purchases are offered where `GET /v1/network` gives a `router`: on production (Arc, real
> USDC) and on the sandbox (Arc Testnet, test USDC). The interface may still change. Try it on the sandbox first.

## Run it

Against the example app ([`../node`](../node/README.md)) running on the sandbox with your product, which needs at
least one credit pack of $1 or less:

```sh
cd examples/agent
npm install
AGENT_KEY=0x… node agent.mjs http://localhost:3317 "some text"
```

`AGENT_KEY` is the key of **a wallet made for this agent**, holding only what it may spend: test USDC from
https://faucet.circle.com on the sandbox. Never your own wallet's key, and never the merchant's. `MAX_PRICE` is
the most it pays at once, in dollars (default 1). `AGENT_NETWORK=84532` pays with USDC on Base Sepolia instead of
Arc Testnet, where sub3 offers it (`sources` in `GET /v1/network`): the wallet then needs USDC only there (the
same faucet has it). Paying from another network costs a fixed relay fee more ($0.03 in the sandbox) and a
fraction of a cent for the crossing, so a pack must cost about $0.96 or less to stay within the $1 limit; it
takes about ten seconds. Say which network you pay on: the client does not look at balances, and without
`network` it signs for Arc.

```text
Agent 0x…
Out of credits: buying 50 credits for $0.50
Bought taste: 50 credits for $0.50
{ text: 'SOME TEXT', id: '…', charged: { allowance: '0', credits: '1' } }
```

`npm test` runs the same flow with no wallet, chain or network, against the example app and the fake sub3 API
([`../testing`](../testing/README.md)); run `npm install` in `../node` first. (In the repository, with its lock
files, `npm ci` does the same.)

## What it does

1. **Signs in** (`signIn`). `POST /v1/auth/nonce`, sign the sign-in message with the agent's key, `POST
/v1/auth/verify`: the answer is the same session token a person gets from the `/login` page, issued to the app's
   origin. The agent sends it as `Authorization: Bearer <token>`, and the app knows it by its address.
2. **Calls the app.** With credits left, that is all.
3. **On a 402 with `purchase` links, buys one** (`buy`). Each link is an x402 resource hosted by sub3:
   `GET …/v1/x402/acme/app/<item>?user=<the agent's address>`. The stock client (`@x402/fetch`, `@x402/evm`)
   reads the price, signs the transfer and gets the receipt. Nothing here is specific to sub3.
4. **Tries the request again.** The app finds the new order through `GET /v1/orders`, credits it once, and
   answers.

## The rules it follows

- **Pay at most once for one 402.** After a payment, or while the app reports `pending` payments, it waits and
  retries; it never signs a second payment because the first is not credited yet.
- **A 502 from sub3 means "unknown", a 202 "on its way", a 429 "not now".** It sends the same signed payment
  again, which is safe: an order is bought at most once, and the answer is its receipt. A 202 comes when the
  payment was made on another network and has not arrived yet.
- **A budget.** The stock client refuses any quote above its limit before signing, $1 unless its owner raises
  it (`spendControls.maxAmountPerPayment`). The agent also skips packs priced above `MAX_PRICE`.
- **Buy for yourself.** It follows only links whose `user` is its own address: that address receives the item.
- **409 is final for now**: `item_inactive`, `already_owned`, or `tier_mismatch` (another tier is running;
  upgrades are made by a person at `/checkout`).

## The app's side

The app answers 402 with one link per active pack when a signed-in caller runs out (`charge` in
[`../node/app.mjs`](../node/app.mjs), `purchaseLinks` in [`../node/sub3.mjs`](../node/sub3.mjs)):

```json
{
	"error": "Not enough credits: buy a pack to continue",
	"code": "payment_required",
	"pending": 0,
	"purchase": [
		{
			"item": "taste",
			"name": "50 credits",
			"price": "0.50",
			"credits": "50",
			"url": "https://sub3.dev/sandbox/v1/x402/acme/app/taste?user=0x…"
		}
	]
}
```

The app does not implement x402 and receives no callback: a purchase made this way is an ordinary order, found
and credited like any other. This 402 is the app's own answer, not an x402 challenge; the links are.
