# Ampersend + Headless Oracle: Composable Pre-Trade Verification

## Why Market State Must Come Before Spend Authorization

An agent requesting spend authorization for a trade on a closed exchange
is wasting compute, authorization bandwidth, and — if approved — creating
a pending order that will fail or queue unpredictably.

The composable pattern:

1. **Headless Oracle** (Layer 1) — Is the exchange open? Signed receipt.
2. **Ampersend** (Layer 2) — Is the agent authorized to spend? Policy check.
3. **Execute** — Place the order with both proofs attached.

If Layer 1 returns anything other than `OPEN`, Layer 2 is never called.
This is fail-closed by design.

## Two-Step Verification Pattern

```typescript
import { verify } from '@headlessoracle/verify';

// Step 1: Market State Gate (Headless Oracle)
const marketRes = await fetch('https://headlessoracle.com/v5/status?mic=XNYS', {
  headers: { 'X-Oracle-Key': process.env.ORACLE_KEY }
});
const { receipt } = await marketRes.json();

const verification = await verify(receipt);
if (!verification.ok) throw new Error(verification.reason);
if (receipt.status !== 'OPEN') {
  console.log(`Market ${receipt.mic} is ${receipt.status} — halting`);
  return;
}

// Step 2: Spend Authorization (Ampersend)
// Include the HO receipt as evidence that market state was verified
const auth = await ampersendClient.requestAuthorization({
  action: 'BUY',
  asset: 'AAPL',
  amount_usd: 10000,
  exchange: 'XNYS',
  evidence: {
    market_state: {
      provider: 'headlessoracle.com',
      mic: receipt.mic,
      status: receipt.status,
      verified_at: receipt.timestamp,
      expires_at: receipt.expires_at,
      signature: receipt.signature
    }
  }
});

if (!auth.authorized) return;

// Step 3: Execute with both proofs
await executeTrade({
  asset: 'AAPL',
  side: 'BUY',
  proofs: { market_state: receipt.signature, spend_auth: auth.token }
});
```

## Batch Verification

For multi-exchange portfolios, verify all markets before requesting
batch spend authorization:

```typescript
const batch = await fetch(
  'https://headlessoracle.com/v5/batch?mics=XNYS,XNAS,XLON',
  { headers: { 'X-Oracle-Key': process.env.ORACLE_KEY } }
).then(r => r.json());

if (!batch.summary.safe_to_execute) return; // Not all markets open

const auth = await ampersend.requestAuthorization({
  action: 'REBALANCE',
  exchanges: ['XNYS', 'XNAS', 'XLON'],
  evidence: { batch_signature: batch.batch_signature }
});
```

## Links

- [Pre-Trade Stack Spec](https://headlessoracle.com/docs/specifications/pre-trade-stack) — Full 5-layer specification
- [Ampersend](https://github.com/edgeandnode/ampersend) — Agent spend control
- [Headless Oracle](https://headlessoracle.com) — Market state verification
