# Buy BTC

The whole buy with raw calls, from a price to the BTC arriving. Run these samples in order, in one shell or one file, and with a test key they run as they are.

## Get a price

Ask while the user types. It needs your key but no wallet, and it reserves nothing.

```sh
export BASE=https://whhxyutitykcsdpvdgcd.supabase.co/functions/v1/maxy-api
curl -s "$BASE/price?from=USDC%20on%20base&to=BTC&amount=10"
```

```ts
const BASE = 'https://whhxyutitykcsdpvdgcd.supabase.co/functions/v1/maxy-api';
const price = await fetch(`${BASE}/price?${new URLSearchParams({ from: 'USDC on base', to: 'BTC', amount: '10' })}`).then((r) => r.json());
console.log(price.formatted.receive); // '0.00012034 BTC'
```

```python
import requests

BASE = "https://whhxyutitykcsdpvdgcd.supabase.co/functions/v1/maxy-api"
price = requests.get(f"{BASE}/price", params={"from": "USDC on base", "to": "BTC", "amount": "10"}).json()
print(price["formatted"]["receive"])  # 0.00012034 BTC
```

`amount` is in whole coins; `fromAmount` takes the smallest unit. Name a coin as `USDC on base`, `ETH on arbitrum`, `BNB`, `AVAX` or `SOL`. Every amount in the answer is a string in the smallest unit, and `formatted` has the same amounts in words. The same question within 3 seconds is one read, so refresh as often as you like.

## Get a quote

Ask when the user moves to confirm. A quote names who pays and who receives, needs your key, and holds for 60 seconds. This sample sets up the wallet the next steps use. Put your test key in place of `mxk_test_…`. Live, the wallet and the address are your user's.

```sh
export MAXY_API_KEY=mxk_test_…
export TEST_WALLET_KEY=$(cast wallet new --json | jq -r '.[0].private_key')   # a throwaway wallet
export WALLET=$(cast wallet address --private-key "$TEST_WALLET_KEY")
export MY_BTC_ADDRESS=bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4              # where the BTC goes
curl -s -G "$BASE/quote" -H "x-maxy-key: $MAXY_API_KEY" \
  --data-urlencode "from=ETH on base" --data-urlencode "to=BTC" --data-urlencode "amount=0.004" \
  --data-urlencode "fromAddress=$WALLET" --data-urlencode "toAddress=$MY_BTC_ADDRESS" > quote.json
jq '{quoteId, toAmount, issues, steps: [.steps[]?.id]}' quote.json
```

```ts
import { createWalletClient, hashTypedData, http } from 'viem';
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
import { base } from 'viem/chains';

const KEY = process.env.MAXY_API_KEY!; // export MAXY_API_KEY=mxk_test_…
const account = privateKeyToAccount(generatePrivateKey()); // a throwaway wallet
const walletClient = createWalletClient({ account, chain: base, transport: http() });
const btcAddress = 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4'; // where the BTC goes

const q = new URLSearchParams({ from: 'ETH on base', to: 'BTC', amount: '0.004', fromAddress: account.address, toAddress: btcAddress });
const quote = await fetch(`${BASE}/quote?${q}`, { headers: { 'x-maxy-key': KEY } }).then((r) => r.json());
console.log(quote.quoteId, quote.toAmount, quote.issues);
```

```python
import os
from eth_account import Account
from eth_account.messages import encode_typed_data  # pip install eth-account

KEY = os.environ["MAXY_API_KEY"]  # export MAXY_API_KEY=mxk_test_…
account = Account.create()        # a throwaway wallet
btc_address = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"  # where the BTC goes

quote = requests.get(f"{BASE}/quote", headers={"x-maxy-key": KEY}, params={
    "from": "ETH on base", "to": "BTC", "amount": "0.004",
    "fromAddress": account.address, "toAddress": btc_address,
}).json()
print(quote["quoteId"], quote["toAmount"], quote["issues"])
```

- `quoteId` becomes the order id.
- `toAmount` is what arrives. It is executable, with every cost in. To ask for an exact BTC amount, send `receive=0.0001` in place of `amount`.
- `steps` is what the wallet does, in order. `signing` is the same in one shape on every route.
- `issues` says what is short: `balance`, `allowance`, or `orderCap`.

Check the Bitcoin address first: `GET /addresses/validate?chain=bitcoin&address=…` answers `payable` and a reason. EVM buys pay native SegWit (`bc1q…`) only. Solana buys can also pay Taproot (`bc1p…`) live, though this check reads `payable: false` for it.

> Always show the amounts and keep the button live. If a quote carries `issues.orderCap` or `liquidityAvailable: false`, show the refusal when the user clicks, and offer a smaller amount.

## Sign

The wallet signs what the quote's `steps` ask for. Each `signature` step carries the typed data exactly as the wallet shows it, and its `hash`. Check the hash, then ask the wallet to sign. It costs no gas.

```sh
INTENT_SIG=$(cast wallet sign --private-key "$TEST_WALLET_KEY" --data "$(jq -c '.steps[] | select(.id == "intent") | .typedData' quote.json)")
```

```ts
if (!quote.steps) throw new Error(quote.issues?.orderCap?.message ?? 'Not enough funds for this order.');
const signatures: Record<string, string> = {};
for (const step of quote.steps.filter((s) => s.kind === 'signature')) {
  if (hashTypedData(step.typedData) !== step.hash) throw new Error(`step ${step.id} does not hash to ${step.hash}`);
  signatures[step.id] = await walletClient.signTypedData(step.typedData);
}
```

```python
from eth_utils import keccak

if not quote["steps"]:
    raise SystemExit((quote["issues"].get("orderCap") or {}).get("message", "Not enough funds for this order."))
signatures = {}
for step in (s for s in quote["steps"] if s["kind"] == "signature"):
    message = encode_typed_data(full_message=step["typedData"])
    digest = "0x" + keccak(b"\x19" + message.version + message.header + message.body).hex()
    assert digest == step["hash"].lower()  # check what will be signed before signing it
    signatures[step["id"]] = "0x" + bytes(account.sign_message(message).signature).hex()
```

The signature binds the paying wallet, the coin, the sats, the price and its band, the solver's bond, the Bitcoin script that must receive the BTC, and the deadline. ETH, BNB and AVAX need no allowance: the escrow transaction carries the value. If the wallet declines (`4001`), nothing was signed: go back to the confirm screen.

## Place the order

Send the quote's `order` unchanged, with the signatures keyed by step id. Then the wallet sends the escrow transaction, and you tell Maxy its hash so the solver starts at once. A sandbox transaction is never sent: its `simulatedHash` stands in for the hash, as below.

```sh
curl -s -X POST "$BASE/orders" -H "x-maxy-key: $MAXY_API_KEY" -H "content-type: application/json" \
  -d "$(jq -c --arg sig "$INTENT_SIG" '{order: .order, signatures: {intent: $sig}}' quote.json)" > placed.json
jq '{orderId, simulation}' placed.json
TX_HASH=$(jq -r .transaction.simulatedHash placed.json)   # live: send .transaction from the wallet, use its hash
curl -s -X POST "$BASE/orders/submit" -H "x-maxy-key: $MAXY_API_KEY" -H "content-type: application/json" \
  -d "$(jq -c --arg tx "$TX_HASH" '.next.body + {txHash: $tx}' placed.json)"
```

```ts
const headers = { 'x-maxy-key': KEY, 'content-type': 'application/json' };
const placed = await fetch(`${BASE}/orders`, { method: 'POST', headers, body: JSON.stringify({ order: quote.order, signatures }) }).then((r) => r.json());
if (!placed.simulation.ok) throw new Error(placed.simulation.error); // do not send it

const tx = placed.transaction;
const txHash = tx.simulated ? tx.simulatedHash : await walletClient.sendTransaction({ to: tx.to, data: tx.data, value: BigInt(tx.value) });
await fetch(`${BASE}/orders/submit`, { method: 'POST', headers, body: JSON.stringify({ ...placed.next.body, txHash }) });
```

```python
headers = {"x-maxy-key": KEY}
placed = requests.post(f"{BASE}/orders", headers=headers, json={"order": quote["order"], "signatures": signatures}).json()
if not placed["simulation"]["ok"]:
    raise SystemExit(placed["simulation"]["error"])  # do not send it

tx = placed["transaction"]
tx_hash = tx["simulatedHash"] if tx.get("simulated") else your_wallet_sends(tx)
requests.post(f"{BASE}/orders/submit", headers=headers, json={**placed["next"]["body"], "txHash": tx_hash})
```

If `simulation.ok` is false, do not send the transaction. USDC orders answer `submitted: true` and send nothing: see [Pay with USDC](https://maxy.co/docs/other-coins#pay-with-usdc). Retries are safe: the same signed order returns the same `orderId`. A solver fills only at the price the user signed, within 2 hours of signing. To tag an order for your records, add `externalId` to the body.

| Code | HTTP | Cause | Fix |
| --- | --- | --- | --- |
| `quote_expired` | 409 | Over 60 seconds since the quote | New quote, sign again |
| `wallet_mismatch` | 400 | The signature is from another wallet | Sign with the paying wallet |
| `order_cap_exceeded` | 422 | Above your key's cap | Order less |
| `insufficient_liquidity` | 422 | Maxy cannot fill this size now | Less, or later |

## Track the order

Show the user where the order is. Poll every 2 seconds while they watch, and use [webhooks](https://maxy.co/docs/webhooks) for your records. No key is needed.

```sh
ORDER_ID=$(jq -r .orderId placed.json)
while :; do
  STATUS=$(curl -s "$BASE/status?orderId=$ORDER_ID&chainId=8453")
  echo "$STATUS" | jq -c '{state, btcTxId}'
  [ "$(echo "$STATUS" | jq -r '.isComplete or .state == "refundable"')" = true ] && break
  sleep 2
done
```

```ts
let status;
do {
  await new Promise((done) => setTimeout(done, 2000));
  status = await fetch(`${BASE}/status?${new URLSearchParams({ orderId: placed.orderId, chainId: '8453' })}`).then((r) => r.json());
  console.log(status.state, status.btcTxId);
} while (!status.isComplete && status.state !== 'refundable');
```

```python
import time

while True:
    status = requests.get(f"{BASE}/status", params={"orderId": placed["orderId"], "chainId": 8453}).json()
    print(status["state"], status["btcTxId"])
    if status["isComplete"] or status["state"] == "refundable":
        break
    time.sleep(2)
```

`pending` lasts one block, until the solver commits. `in_progress` lasts seconds, while the solver pays. `completed` means `btcTxId` is set: link it on any Bitcoin explorer. The user's wallet shows the BTC after its first confirmation, about 10 minutes. A receipt shows what was paid, what arrived, the receiving address, `btcTxId`, the escrow transaction and `orderId`.

`GET /orders/{id}/events/stream` sends the same changes as a stream. If the order reads `refundable`, go to [When it fails](https://maxy.co/docs/when-it-fails). A brand-new order id reads `pending`, never `404`.

---
Source: https://maxy.co/docs/buy-btc (Maxy Docs › Swaps › Routes)
