# Check a purchase against your own policy before an agent makes it

Use this when an agent is about to spend money on a tokenized stock and you want one answer it can act on: **allow**,
**deny** or **unknown**, for that exact contract and amount, under limits you set, with the evidence behind each rule.

`/verify` and `@proofofstock/guard` answer "is this the issuer's contract?"
([Check before listing](check-before-listing.md)). `check_before_buy` asks that first and then the questions a buyer
has after it: is the price of this size near the issuer's, is that price fresh, is the pool deep enough, would the swap
go through for this wallet, do the issuer's transfer rules allow it, is a share split pending, did the pool just drain.

| You have | Use |
|---|---|
| a terminal, or code without a wallet | `GET /api/check_before_buy` |
| code with the buyer's public wallet | `POST /api/check_before_buy`, a JSON body |
| an agent | the MCP tool `check_before_buy` |

All three return the same answer. Nothing is signed or sent; the swap stays yours.

## Ask once, by hand

```bash
curl -s 'https://proofofstock.com/api/check_before_buy?chain=base&token=0xb2000000000000000000001e800a7f5189430cd0&usd=500&max_premium=0.02' \
  | jq '{decision, summary, failed, unchecked}'
```

Read it in this order:

1. **`decision`.** `allow`: every enforced rule held. `deny`: at least one failed, named in `failed`. `unknown`: none
   failed, but at least one could not be checked, named in `unchecked`. **Treat `unknown` as "not now"**, never as
   allow: no evidence, no allow.
2. **`rules`.** Each one says what was measured (`value`), against what (`limit`), from which reading (`evidence`),
   and, when it did not hold, why (`reason`). A `deny` on `max_reference_age` on a Saturday is the issuer's price
   standing still while the market is closed; a `deny` on `min_liquidity` is a pool too thin for the limit you set.
3. **`use_instead`.** For a look-alike, the issuer-listed contract. The look-alike itself is never priced.

## Set your own policy

Every field has a default; send only what you change. A number set to `null` (or `off` in a URL) turns its rule off.

| Field | Default | Tighten when | Loosen when |
|---|---|---|---|
| `max_premium` | 0.03 | the agent trades size and every basis point counts | you accept a wider spread on a thin name |
| `max_reference_age_s` | 3600 | you only buy while the exchange is open | you accept the issuer's last price over a weekend |
| `min_liquidity_usd` | 50000 | you may need to sell the position back soon | you buy small amounts of a new listing |
| `max_price_impact` | 0.02 | the amount is large against the pool | the amount is tiny and fees dominate |
| `require_dry_run` | false | you never want an allow without your wallet's own dry run | (off is the default) |
| `multiplier_not_pending` | true | (on is the default) | you have read the issuer's notice of the split |
| `pool_not_drained_24h` | false | you want no pool that dropped, drained or vanished in a day | (off is the default: a pool under pool life's $10,000 floor is not tracked, and the rule then answers `unknown`) |
| `strict` | false | you want no allow that rests on a rule with nothing to read: Base's halts (`basis: not_reported`), Robinhood Chain's B20 (`not_applicable`) | (off is the default: those rules hold and the allow names them) |

The issuer's list, the look-alike check, a halt and the issuer's transfer rules are not in the table: they are always
checked, and a policy that names one is refused.

## An agent that obeys it

A minimal Node agent: it asks before each purchase, buys only on `allow`, and logs why otherwise. Node 20+, no
dependencies. The buy itself is left as a stub: wire your own swap there.

```js
// check-then-buy.mjs: node check-then-buy.mjs
const SITE = 'https://proofofstock.com'
const WALLET = process.env.WALLET // your PUBLIC address; never a private key
// strict: no allow that rests on a rule whose source publishes nothing to check (see the table above).
const POLICY = { max_premium: 0.02, min_liquidity_usd: 100000, require_dry_run: Boolean(WALLET), strict: true }

async function checkBeforeBuy (chain, token, usd) {
  const body = { chain, token, usd, policy: POLICY, ...(WALLET ? { wallet: WALLET } : {}) }
  const r = await fetch(`${SITE}/api/check_before_buy`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
  if (r.status === 503) return { decision: 'unknown', summary: `busy, retry after ${r.headers.get('retry-after') || 2} s` }
  if (!r.ok) return { decision: 'unknown', summary: `HTTP ${r.status}: ${(await r.json().catch(() => ({}))).error || 'no answer'}` }
  return r.json()
}

const PLAN = [
  { chain: 'base', token: '0xb2000000000000000000001e800a7f5189430cd0', usd: 250 },
  { chain: 'base', token: '0x35b76a8fbfbac68c449a4a4a8d1bcda0d486f703', usd: 250 },
]
for (const p of PLAN) {
  const a = await checkBeforeBuy(p.chain, p.token, p.usd)
  console.log(`${a.decision.toUpperCase().padEnd(7)} ${p.token}  ${a.summary}`)
  if (a.decision !== 'allow') {
    for (const r of (a.rules || []).filter((x) => x.enforced && x.ok !== true)) console.log(`        ${r.rule}: ${r.reason} (value ${JSON.stringify(r.value)}, limit ${JSON.stringify(r.limit)}, basis ${r.basis})`)
    if (a.use_instead) console.log(`        the issuer-listed contract is ${a.use_instead}`)
    continue
  }
  // await mySwap(p.chain, p.token, p.usd, a.quote.min_received) // your own swap, signed by your own wallet
}
```

The second address is a look-alike: it is denied on `issuer_listed` and `not_lookalike`, with the listed contract in
`use_instead`, and no quote is made for it. A contract on another issuer's list for the chain (Ondo on Robinhood Chain) comes back `unknown` with `reason: "other_issuer"`: the agent above does not buy it.

## Things to know

- **A quote lives seconds.** `quote.quoted_at` and `quote.valid_for_s` say how long; ask again right before the swap,
  rather than acting on an `allow` from minutes ago.
- **Deterministic, not frozen.** The same inputs and the same data give the same answer. A new quote, a new pool
  reading or a new issuer price are new data, and may change it.
- **The wallet** goes in a POST body only, to the aggregator and the node for this one answer, and is never echoed.
- **Cost.** 10 units of the free minute, 15 with a wallet, as `simulate_buy`. See [pay per call](pay-per-call.md) for
  more than the free minute.
- **Allow is your policy's word, not ours.** It says each rule you enforced held at the time its evidence states. It is
  not investment advice.

The rules in full: [HTTP API](../reference/http-api.md#route-check-before-buy) and
[MCP tools](../reference/tools.md#tool-check_before_buy).
