# Build prompt: a gift card shop on the plusmore RaaS API (v2)

Paste everything below this line into an AI coding agent working in an empty folder.

---

## Goal

Build an unbranded Next.js gift card shop on the plusmore RaaS API, with four settings that make it the owner's own brand
(section 10). Buyers pay USDC directly to the shop's own wallet; the shop verifies the payment on chain, then orders the
gift card through the plusmore RaaS API and shows the voucher to the buyer. One API instead of a deal with every gift card
brand.

Build it in this order: first in DEMO mode (no key, the two demo brands, selling off), then against the plusmore RaaS
sandbox (a free test key, demo gift cards, test USDC on Base Sepolia, nothing of value), and only then go live through the
partner portal at https://partners.plusmore.xyz.

What to tell the shop owner, in these words where they apply:

- plusmore adds 0% to every gift card rate: each rate is the rate our gift card supplier gives us, passed on in full.
  Rates vary by gift card and some are zero. The full list is public at https://plusmore.xyz/pool-n-earn/rates.
- Going live on the plusmore RaaS API is a one off 999 USDC setup and API activation fee per product (gift cards now),
  which is non refundable and guarantees no uptime, supply, margin or continued service. The sandbox is free.
- Float top ups can take up to 3 days to arrive.

Never type a catalogue size, a brand count or an average rate into anything you build: read the counts live from
`GET /v1/summary` (section 1) and state no average at all. Never name plusmore's own gift card supplier, and do not claim
the shop buys from the brands themselves: it buys through the plusmore RaaS API.

If you have the open source starter (plusmore.xyz/raas/giftcards, `plusmore-giftcard-shop-starter.zip`), vendor its
`sdk/plusmore.ts` and `sdk/vectors/` as they are: it is this whole client in one file and already passes the vectors.
Otherwise write the client from section 1 and prove it against the vectors quoted there.

## 1. The plusmore RaaS API, v1

Docs: https://plusmore.xyz/pool-n-earn/developers/docs (read them if you can reach them; everything you need is also
here).

### Hosts, keys and environments

- `PLUSMORE_ENV=sandbox` calls `https://raas-sandbox.plusmore.xyz/v1`; `PLUSMORE_ENV=live` calls
  `https://raas.plusmore.xyz/v1`.
- A key has three parts, each shown once: the API key `pmr_test_<16 a to z or 0 to 9>_<43 base62>` (sandbox) or
  `pmr_live_...` (production), the signing secret `pmrsig_test_...` or `pmrsig_live_...` (43 base62 after the prefix),
  and the webhook secret `pmrwh_test_...` or `pmrwh_live_...`. Sandbox keys come from the docs page, live keys from the
  partner portal. A test key on the production host, or the reverse, answers `403 wrong_environment`: refuse the mix in
  your own code before sending anything.
- Scopes: `catalogue:read`, `quotes:write`, `orders:write`, `orders:read`, `balance:read`, `funding:read`,
  `statements:read`, `events:read`.

### Request signing v1 (every request)

Headers: `Authorization: Bearer <api key>`, `x-plusmore-timestamp: <unix seconds>` (within 300 seconds of the server's
clock), `x-plusmore-nonce: <a new UUID for every request>` (a nonce is never accepted twice),
`x-plusmore-signature: v1=<lower case hex HMAC-SHA256>`, and on `POST /v1/orders` also `Idempotency-Key: <client_ref>`
equal to the body's `client_ref`.

The HMAC key is the UTF-8 bytes of the WHOLE signing secret, prefix included. The message is seven lines joined by `\n`
with no trailing newline:

```
v1
<METHOD, upper case>
<path exactly as sent, without the query>
<canonical query: an empty line when there is none>
<the timestamp header value>
<the nonce header value>
<lower case hex sha256 of the raw body bytes; of zero bytes for a GET>
```

The canonical query: split the raw query on `&` only (never `;`), drop empty parts, split each part at its first `=`
(no `=` means an empty value), percent decode both halves as UTF-8, encode each again with RFC 3986 (only `A` to `Z`,
`a` to `z`, `0` to `9` and `- . _ ~` stay as they are, hex digits upper case), sort by name then by value (byte order),
join as `name=value` with `&`. Never send a raw `+`, a raw space or a `#` in a request target: write a space as `%20`
and a plus sign as `%2B`. Sign the exact target you send.

Prove your signer with these two vectors (test values only; they open nothing):

```
signing secret  pmrsig_test_ofgAuPEFw9Y9xZ0nlsVdI2ELfyLwz4pdxAlQbwyxJMo

GET /v1/catalogue?limit=2&country=GB&q=demo%20books
timestamp 1760000001   nonce 0d6e5c1b-8a3f-4f2e-b1c4-7e9a2d6f0b33
canonical query  country=GB&limit=2&q=demo%20books
signature        v1=fb97cc74b8f35b70399c4e1bff03f3a55aeeef80f7a63a70e2bc2f869e25836a

POST /v1/quotes   body {"slug":"demo-books","currency":"GBP","face_minor":2500}
timestamp 1760000005   nonce 22222222-3333-4444-8555-666666666666
body sha256      ce5ee58c7597c64fde3b7bd0ec56a355a302eb2ab199c87bd960fb813d239daa
signature        v1=cc321c78ca1b46c901471fda914d7a03965fd6d7c4f0ec41e4166e8e7388e0da
```

Use only `fetch` and WebCrypto (`crypto.subtle` for SHA-256 and HMAC, `crypto.randomUUID` for the nonce), so the client
runs on Node.js 20 or later and on edge runtimes. Compare signatures in constant time.

### The envelope and the units

Success: `{"data": ..., "request_id": "req_..."}`. Failure: `{"error": {"code", "message", "request_id",
"retry_after_sec"?, "details"?}}`; throw it as a typed error carrying the HTTP status, the code, the request id, the retry
time and the details. `*_minor` are integer minor units of the gift card's currency (2500 is 25.00), `*_usd6` are US
dollars with six decimals (the USDC unit: 12.63 is 12630000), `*_bps` are basis points (500 is 5%). Times are RFC 3339 in
UTC.

### Endpoints

| Method and path | Scope | Answer |
|---|---|---|
| `GET /v1/ping` | any | `{partner_id, environment, key_id, scopes, expires_at, server_time}` |
| `GET /v1/catalogue?country=&currency=&q=&category=&cursor=&limit=` | catalogue:read | `{items:[item], total, next_cursor}` (limit 1 to 100; pass `next_cursor` back as `cursor`) |
| `GET /v1/catalogue/{slug}` | catalogue:read | one item, or `404 not_found` |
| `GET /v1/fx` | catalogue:read | `{base:"USD", usd6_per_unit:{"GBP":1250000,...}, fixed, as_of, source:"supplier"}` |
| `GET /v1/summary` | catalogue:read | `{brands, gift_cards, countries, currencies, as_of}`: counts only |
| `POST /v1/quotes` `{slug, currency, face_minor}` | quotes:write | `{quote_id, slug, currency, face_minor, rate_bps, cost_minor, cost_usd6, sellable, code, expires_at}`; `code` is `ok`, `insufficient_balance`, `restocking` or `limit_exceeded` (sent by the sandbox only, for its test allowances); books nothing |
| `POST /v1/orders` `{client_ref, slug, currency, face_minor, quote_id?, end_customer:{ref, country}}` | orders:write | 201 issued with the voucher, 202 pending, 200 a replay (`replay: true`), or an error |
| `GET /v1/orders/{client_ref}` | orders:read | the order, with the voucher once issued, or `404 not_found` |
| `GET /v1/orders?status=&from=&to=&cursor=&limit=` | orders:read | `{orders, next_cursor}` newest first, never a voucher |
| `GET /v1/balance` | balance:read | `{balance_usd6, held_usd6, available_usd6, low_balance_usd6, limits, as_of, environment}` |
| `GET /v1/funding` | funding:read | how to fund the float (below) |
| `GET /v1/deposits?cursor=&limit=`, `GET /v1/deposits/{id}` | funding:read | each deposit and its state |
| `GET /v1/statements?month=YYYY-MM` | statements:read | the monthly statement, signed with Ed25519 over its canonical JSON, with the key id |
| `GET /v1/events?after=&limit=` | events:read | `{events, next_after, has_more}`: the same events as the webhooks |
| Sandbox only: `POST /v1/sandbox/deposits/simulate`, `POST /v1/sandbox/webhooks/test {type?}`, `GET /v1/sandbox/events` | test keys | a test top up, a test event, and every event as the signed delivery a webhook endpoint would get |

A catalogue item: `{slug, brand, name, category, category_label, country, currency, rate_bps, denominations (fixed
amounts in minor units, or null), range ({min_minor, max_minor, step_minor}, or null), prices:[{face_minor, cost_minor,
cost_usd6}], availability:{state: "available" | "limited" | "unavailable", max_face_minor_today}, cash_equivalent,
logo_url, terms, source: "supplier", demo}`. Slugs are lower case letters, digits and single dashes.

An order: `{id, client_ref, status: "pending" | "issued" | "failed", slug, brand, currency, face_minor, rate_bps,
cost_minor, cost_usd6, quote_id, end_customer:{ref_sha256, country}, voucher, created_at, issued_at, replay,
environment}`. A voucher: `{code, pin, redeem_url, expires_at, demo, notice}`.

`client_ref` (`[A-Za-z0-9_.:-]`, 1 to 128 characters) is the idempotency key: the same client_ref with the same body
returns the same order and voucher and is never charged twice; a different body is `409 idempotency_mismatch`. The body
counts `quote_id` too, so send `quote_id: null` and the same `end_customer` on every attempt of one purchase.
`end_customer.ref` is your reference for the buyer (printable text, stored only as its SHA-256) and
`end_customer.country` the ISO 3166 two letter country where the gift card will be used: both required.

Counts for page copy come from `GET /v1/summary`, read live, never typed in. Show one count only, in LIVE mode only:
`gift_cards`, labelled "gift card brands" (for example "N gift card brands in M countries"). The sandbox holds demo gift
cards only: state no count there.

### Errors (one code, one HTTP status, one retry advice)

| HTTP | Code | Retry |
|---|---|---|
| 400 | `invalid_request`, `field_not_allowed`, `idempotency_key_required` | no |
| 401 | `unauthorized`, `signature_invalid`, `timestamp_out_of_window`, `nonce_reused` | after fixing the request |
| 402 | `insufficient_balance` (nothing was booked) | after funding the float |
| 403 | `scope_missing`, `ip_not_allowed`, `wrong_environment`, `partner_not_live`, `partner_suspended`, `origin` | no |
| 404 | `not_found`, `not_sold` | no |
| 409 | `denomination_unavailable`, `price_changed` (the new cost in `details`), `order_in_progress` | as stated |
| 409 | `idempotency_mismatch` | no |
| 422 | `cash_equivalent_excluded` | no |
| 429 | `rate_limited`; `limit_exceeded` (sent by the sandbox only, for its test allowances) | after `retry_after_sec` |
| 451 | `region_blocked` (a sanctioned place: the caller's or the end customer's country) | no |
| 502 | `upstream_failed` (the gift card could not be issued, nothing was charged) | yes, with the same client_ref |
| 503 | `restocking` (`retry_after_sec` 3600) | after `retry_after_sec` |
| 503 | `capacity_unavailable`, `fx_unavailable`, `maintenance` | yes, shortly |

Treat any code you do not know by its HTTP status. Production never explains an authentication failure; the sandbox adds
an `x-plusmore-signature-debug` header to help you.

### Float and rate limits

There are no order limits on your account. Your credited float pays for each order. An order the available float cannot cover answers
`402 insufficient_balance`, with nothing booked. The api keeps rate limits per key: reads 20 a second (burst 60), quotes 10 a
second, orders 5 a second (burst 10); above them it answers `429 rate_limited` with `retry_after_sec`. The sandbox has
its own test allowances, shown in `GET /v1/balance` `limits`.

### Places

plusmore refuses only sanctioned places (`451 region_blocked`, for the caller's place or the end customer's country);
every other place is open, and each partner runs its own compliance. Every order still names
`end_customer.country`, because the api screens it.

### Webhooks

Events: `order.issued`, `order.failed`, `order.pending`, `deposit.detected`, `deposit.credited`, `deposit.held`,
`balance.low`, `key.created`, `key.revoked`, `statement.ready` (and `limits.changed`, a test event the sandbox can send;
acknowledge any type you do not handle). Each delivery is a POST with
`plusmore-signature: t=<unix seconds>,v1=<hex HMAC-SHA256(webhook secret, "<t>.<raw body>")>`, `plusmore-event-id` and
`plusmore-event-type`. The HMAC key is the UTF-8 bytes of the whole webhook secret. Check the signature over the RAW body
bytes BEFORE parsing them, refuse a `t` more than 300 seconds from your clock, accept a header that carries several `v1`
entries when one matches (secret rotation), compare in constant time, handle each event id once, answer 200 fast.
Vector: secret `pmrwh_test_iRuDTPc69sk1PMVw6AUhj0xaohRinG2qLFWX7QUh5TF`, `t` 1760000100, raw body
`{"id":"evt_01J9ZQ3M4N5P6Q7R8S9T0V1W2X","type":"order.issued","created_at":"2026-10-09T08:00:00.000Z","environment":"sandbox","test":false,"data":{"client_ref":"order-0001","status":"issued","slug":"demo-coffee","face_minor":2500,"cost_usd6":23750000}}`
gives `t=1760000100,v1=caee53c007947760e9c99355dc1401f9388961e43309ed958483d6039716ad2b`.

### Funding the float

The float is a prepaid USDC balance that pays the wholesale cost of each gift card you order. In production `GET /v1/funding` answers
`{asset:"USDC", chain_id:8453, token_address:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", deposit_address:<the
account's own float address>, notice:"Float top ups can take up to 3 days to arrive."}`: the operator sends USDC on Base
only, to that address. A deposit's `state` is `detected` (received), `credited` (available to spend) or `held` (with a
`hold_reason`). Orders spend only the available float. Show the notice line wherever the operator reads about funding,
exactly as it is, and never a cap, a "you can add up to" line or any other timing claim. In the sandbox the float is a
test balance: each key starts with one, and `POST /v1/sandbox/deposits/simulate` adds more (see the sandbox docs).

## 2. DEMO mode

With no key the shop runs on a built in demo catalogue: the sandbox's own two demo brands, in exactly the item shape
above, so the same pages work unchanged once a key is set. Save them as `lib/demo-catalogue.ts`:

- `demo-books`: brand "Demo Books", name "Demo Books gift card", GB, GBP, `rate_bps` 300, range 1000 to 10000 step 1,
  category `books-and-education` ("Books and education"), available.
- `demo-coffee`: brand "Demo Coffee", name "Demo Coffee gift card", US, USD, `rate_bps` 500, denominations 1000, 2500 and
  5000, category `food-and-drink` ("Food and drink"), available.
- `demo-limited`: like `demo-books`, name "Demo Books gift card, limited", availability `limited` with
  `max_face_minor_today` 5000.

Every item: `cash_equivalent` false, `source` "supplier", `demo` true, `terms` "Demo gift card for the plusmore RaaS
sandbox. It has no value and cannot be redeemed anywhere.", `prices` for each fixed amount (or the two ends of the range,
the top capped by today's limit) with `cost_minor = face_minor - floor(face_minor * rate_bps / 10000)` and `cost_usd6` at
the fixed rates USD 1 and GBP 1.25, rounded to whole cents, half up. Fixed demo fx `{USD: 1000000, GBP: 1250000}`. Serve
the art yourself (a plain coffee and a plain book or gift box SVG in `public/demo-art/`), sorted by slug. Selling stays
off in DEMO mode and no catalogue count is shown.

## 3. Stack, configuration and modes

Next.js 14 App Router, React 18, TypeScript (strict), plain CSS, Vitest. Pin: `next` 14.2.x, `react` and `react-dom`
18.3.x, `typescript` ~5.9, `vitest` ^3.2, `@types/node` 20, `@types/react` and `@types/react-dom` 18, `viem` ^2.21 (the
ONE dependency beyond Next and React: it verifies a buyer's claim signature against a smart contract wallet, section 6;
the API client itself is plain `fetch` and WebCrypto). A standalone folder with its own package.json and lockfile;
`npm install && npm run build && npm test` must work with nothing else, offline.

`.env.example`, every line commented in plain English:

```
PLUSMORE_ENV=sandbox
PLUSMORE_API_KEY=
PLUSMORE_SIGNING_SECRET=
PLUSMORE_WEBHOOK_SECRET=
PLUSMORE_API_BASE_URL=
SHOP_WALLET=
NEXT_PUBLIC_SHOP_WALLET=
BASE_RPC_URL=https://sepolia.base.org
NEXT_PUBLIC_SHOP_DOMAIN=
NEXT_PUBLIC_SHOP_NAME=
NEXT_PUBLIC_SHOP_LOGO_URL=
ADMIN_PASSWORD=
```

Modes: DEMO with no key and no signing secret; sandbox with `PLUSMORE_ENV=sandbox` and a test key; live with
`PLUSMORE_ENV=live` and a live key. An empty `PLUSMORE_ENV` follows the key's prefix. Half the credentials, a test key
with a live secret, a key that does not match `PLUSMORE_ENV`, or a malformed value: stay in DEMO mode and say why in a
plain configuration problem that never contains the value. `PLUSMORE_API_BASE_URL` points the sandbox at a local test
double (your tests set it) and is ignored in live mode: live keys only ever go to the production host. Read every
variable in one module (`lib/env.ts`) at request time, never at build time (read names through a variable,
`process.env[name]`), put no host defaults in code beyond the two API hosts, and mark every page and route
`export const dynamic = "force-dynamic"`. Checkout is enabled only when connected (sandbox or live) with a valid
`SHOP_WALLET` and `BASE_RPC_URL`, and only when `NEXT_PUBLIC_SHOP_WALLET` is empty or equal to `SHOP_WALLET`.

The chain follows the mode: the sandbox takes test USDC on Base Sepolia, live takes USDC on Base (section 5).

## 4. Money safety rules (non negotiable)

1. The credentials are read on the server only. They never reach a browser, a response body or a log line.
2. The quote (`POST /v1/quotes`) runs before the buyer is shown how to pay. If it is not sellable, the buyer is never
   asked to pay.
3. `client_ref` is derived from the payment's transaction hash: `clientRefFromTxHash(txHash)` trims, lowercases, strips
   a leading `0x` and prefixes `tx-` (it throws unless 64 hex characters remain). One payment is one order forever, and
   every retry MUST send the same client_ref AND the same order body (`quote_id` null, the same `end_customer`).
4. A transaction hash alone is NEVER proof of who paid: hashes are public the instant they are broadcast, so anyone
   watching `SHOP_WALLET` could otherwise submit a hash before the real buyer does. Every claim (first time or a replay)
   must also carry a signature proving the caller controls the wallet that actually sent the USDC, verified BEFORE
   looking up or returning any order (section 6).
5. Before ordering, `GET /v1/orders/{client_ref}`. If it is issued, return that order as a replay and stop, but only
   after rule 4's signature check passes. If it is pending, say it is being issued. Never order twice.
6. A voucher travels only in the answer to a payment claim, once the claim signature verifies. The order page shows it
   once and keeps no copy; status routes never return it; it is NEVER written to a server log. Log only allowlisted
   fields (client_ref, status, error code, request id).
7. Only buyer safe fields leave the server: never the cost, the float balance or the end customer reference.

## 5. Verifying the payment (`lib/rpc.ts`)

`getUsdcTransferToShop(txHash, minUsdc)`, using two plain JSON RPC POSTs to `BASE_RPC_URL`:

- `eth_chainId` must answer `"0x14a34"` (Base Sepolia) in the sandbox and `"0x2105"` (Base) live, else `wrong_chain`.
- `eth_getTransactionReceipt` with `[hash]`: `null` is `not_found_yet`; a `status` other than `"0x1"` is `reverted`.
- Add up every log whose `address` (lower case) is the chain's USDC (`0x036cbd53842c5426634e7929541ec2318f3dcf7e`, test
  USDC on Base Sepolia, or `0x833589fcd6edb6e08f4c7c32d4f71b54bda02913` on Base), whose `topics[0]` is
  `0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef` (ERC20 Transfer) and whose `topics[2]` (the
  recipient: the last 40 hex characters of the 32 byte topic) equals `SHOP_WALLET` (lower case). Each amount is
  `BigInt(log.data)` with six decimals; `topics[1]` is `from`, the ONLY wallet allowed to claim this payment.
- Nothing to the shop is `no_usdc_to_shop`; a total below the price is `amount_too_small`. Compare integers.
- A receipt with a success status counts as paid; say in a comment that a production shop should wait for more
  confirmations.

## 6. Proving who paid: the claim signature (`lib/claim.ts`)

- `buildClaimMessage({domain, txHash, brandSlug, currency, faceMinor})` returns one deterministic, human readable string:
  ```
  plusmore gift card shop: claim a gift card

  Shop: my-shop.example.com
  Payment transaction: 0xabc...
  Gift card: demo-coffee
  Amount: 25.00 USD

  Signing proves you control the wallet that sent this payment. It does not send any funds and costs no gas.
  ```
  Plain text only, never an EIP-712 typed message. `domain` is `NEXT_PUBLIC_SHOP_DOMAIN` when set, else the incoming
  request's own host, built identically wherever it is needed.
- `POST /api/claim-message` `{slug, currency, faceMinor, txHash}` returns `{message}`: pure string building, no chain or
  API call.
- `verifyClaimSignature({address, message, signature, rpcUrl})` uses viem
  `createPublicClient({transport: http(rpcUrl)}).verifyMessage(...)` (a plain wallet, ERC-1271 and ERC-6492); false,
  never a throw, on a malformed signature (`/^0x[0-9a-fA-F]{130,8192}$/`) or an RPC failure.
- `POST /api/verify-payment` `{slug, currency, faceMinor, txHash, signature, buyerRef?, country?}`: the price now, the
  on chain payment (gives `from`), then the signature over `buildClaimMessage(...)` by `from`. Not verified:
  `401 {"error":"...","code":"signature_mismatch","paid":true,"retryable":true}` before any order lookup.
- Checkout UI: once the buyer has pasted a transaction hash, fetch the claim message, then try an injected wallet
  (`window.ethereum`: `eth_requestAccounts`, then `personal_sign` with `[message, account]`). Without one, or when it
  fails, show the message with a copy button and a field to paste a signature made another way. The submit button stays
  off until a signature is attached.

## 7. The purchase flow

- Price: `faceMinor / 100 * (usd6_per_unit[currency] / 1000000)` from `GET /v1/fx`, rounded to the cent, half up: the
  USDC amount the buyer sends, shown as a plain decimal such as `25.00`. No rate means not sellable now.
- Brand page `/brand/[slug]`: every fixed amount as a button (orderable ones link to
  `/checkout/{slug}?amount={faceMinor}&currency={CUR}`, the rest disabled), a free amount input for range gift cards
  (on the step, capped by `max_face_minor_today`). In DEMO mode every buy button is disabled with the text "Selling is
  switched off in DEMO mode. Selling starts with a sandbox key." In DEMO and the sandbox show the partner rate.
- `POST /api/check` `{slug, currency, faceMinor}` runs the quote and answers `{ok, code, message, retryAfterSec,
  priceUsd}`, never the cost.
- Checkout `/checkout/[slug]`: calls `POST /api/check`; if ok, shows "send exactly {priceUsd} USDC on {Base or Base
  Sepolia}", the shop wallet with a copy button, a warning that the wrong amount, token or network is not refunded
  automatically (and, in the sandbox, that test USDC and the demo gift card have no value), a country field (two letters,
  prefilled from `x-vercel-ip-country` or `cf-ipcountry` when the host sets one), a field for the transaction hash, and
  the sign step of section 6.
- `POST /api/verify-payment` (section 6), then: rule 5 of section 4; the end customer's country (a trusted edge header
  first, else the buyer's choice; none answers `400 country_required`); the quote again (not sellable: tell the buyer
  the payment is safe and to retry later with the same hash); `POST /v1/orders` with the fixed body of rule 3 and
  `end_customer.ref` = buyerRef or the payer address in lower case (on `price_changed`, retry once with the same body).
  Answer `201 {ok:true, replay:false, order}`, `200` with `replay:true`, or `202` for a pending order; `order` is
  `{clientRef, status, issued, slug, brand, currency, faceMinor, createdAt, voucher}`. Errors are
  `{error, code, paid, retryable, clientRef}` with plain English messages for every code of section 1.
- Order page `/order/[clientRef]`: shows the voucher handed over from checkout (sessionStorage), then deletes it from
  storage. Otherwise it shows the status from `GET /api/orders/[clientRef]` (never the voucher; an admin session also
  sees the cost, the rate and the country), polls while pending, and offers a link back to checkout with the same
  transaction hash to claim again (a fresh signature every time).
- Webhooks: `POST /api/webhooks/plusmore` verifies and handles each event once (section 1), logging ids only.
- Admin `/admin`: `ADMIN_PASSWORD` (empty switches the page off), compared in constant time; an HttpOnly, SameSite=Strict,
  HMAC signed cookie that expires. Shows the mode, configuration problems, the connection (`GET /v1/ping`), the balance
  and the available float (two figures), the newest deposits (received, available or held; the notice line beside a
  received one), how to fund it (`GET /v1/funding`: the deposit address, USDC on Base only, the notice line), the way to
  go live (https://partners.plusmore.xyz) when not live, and an order lookup by client_ref (status only).
- Routes: `GET /api/brands?q=&country=&currency=&cursor=` (`{mode, brands, total, nextCursor, paged}`),
  `GET /api/brands/[slug]`, `POST /api/check`, `POST /api/claim-message`, `POST /api/verify-payment`,
  `GET /api/orders/[clientRef]`, `POST /api/webhooks/plusmore`, `POST /api/admin/login`, `POST /api/admin/logout`,
  `GET /api/admin/float` (`{balance, funding, deposits}`; 401 without the session). In DEMO mode the selling routes
  answer `400 {"code":"DEMO_MODE",...}` and the webhook route `503`.
- The home page shows a DEMO, SANDBOX or LIVE banner in plain English, search, a country filter (a select from the demo
  catalogue in DEMO mode; a two letter input when connected), a currency filter (from `/v1/fx`), an availability badge
  per gift card and cursor paging. The one count of section 1, in LIVE mode only.
- In DEMO mode only, a small "Make it your brand" panel lists the five steps of section 10.

## 8. One Brand type for every mode (`lib/types.ts`)

```ts
type Availability = { state: "available" | "limited" | "unavailable"; maxFaceToday: number | null };
type Brand = {
  slug: string; brand: string; name: string; currency: string; countries: string[]; category: string | null;
  logoUrl: string | null; denominations: number[]; range: { min: number; max: number; increment: number } | null; // minor units
  rateBps: number; cashEquivalent: boolean; availability: Availability; usdPerUnit: number | null; terms: string | null;
  demo: boolean; source: "demo" | "sandbox" | "live";
};
```

One mapping from a catalogue item to a Brand serves DEMO and connected modes.

## 9. Tests

- Vitest unit tests: the signer against the vectors of section 1 (every line of the canonical string, the signature, a
  refused raw `+`), the webhook verifier against its vector (in and out of the 300 second window, a changed body, a
  rotation header), the pricing helpers, client_ref, the Brand mapping, the fixed order body, the payment check against
  a JSON RPC stub on both chains (good, too small, wrong wallet, reverted, unknown, wrong chain, RPC down), and the claim
  signature (deterministic message; the right signer verifies and another wallet does not; a smart contract wallet
  verifies, or is refused, against a stubbed `eth_call`).
- End to end tests that start the app (`next dev` in its own build folder, every variable set explicitly) with no key,
  and in sandbox mode against a local test double of the sandbox (`PLUSMORE_API_BASE_URL`) that checks every request's
  signature with your own verifier, serves the demo catalogue, follows the order rules above (idempotency, the magic
  values: Demo Books at 13.37 restocking, at 66.60 `upstream_failed`, at 99.99 `price_changed` once; country `XX`
  `region_blocked`) and a Base Sepolia RPC stub. Walk every item of the checklist below, including: a wallet that never
  sent the payment cannot claim it, before or after the real payer does; the webhook route refuses a wrong or stale
  signature and handles an event id once; and no voucher value or credential appears in the server output.
- Stop every server a test starts by its own PID (and its child processes, each by PID), never by a name or a group.
- `README.md`: DEMO quick start, the sandbox, the three calls (catalogue, quote, order) with the client, webhooks, going
  live in the portal with the fee line, the float line, the rates rule, and the known limitations (every USDC transfer
  into `SHOP_WALLET` can be claimed once by the wallet that sent it, no extra confirmations, manual refunds). MIT licence.

## 10. Copy and style

Call the API "the plusmore RaaS API", always lowercase plusmore. No em dashes, en dashes or hyphens inside words in
visible text, and no emoji. Say "gift card", never a bare "card". No "up to" before a rate, no promised margin, uptime or
approval. Unbranded by default, plain neutral styling; the shop's identity comes only from the settings below. Plain
English everywhere, including error messages.

Make it your brand. Put the colours in CSS variables at the top of `app/globals.css`: `--accent` (the brand colour on
buttons and links) and `--accent-text` (the text on it), once in `:root` for light mode and once in a
`prefers-color-scheme: dark` block. The README carries these steps, and so does the DEMO panel:

1. Name: set `NEXT_PUBLIC_SHOP_NAME`. It shows in the header and in every page title.
2. Logo: set `NEXT_PUBLIC_SHOP_LOGO_URL` to an https image, or to a file in `public/` such as `/logo.svg`. Without one,
   the header shows the name.
3. Colours: change `--accent` and `--accent-text` in `app/globals.css`, in `:root` for light mode and in the dark mode
   block.
4. Domain: point your domain at the shop and set `NEXT_PUBLIC_SHOP_DOMAIN` to it.
5. Restart or redeploy: the shop reads these settings from its environment when it serves a page.

## 11. Acceptance checklist

1. With no `PLUSMORE_API_KEY` set, the home page loads and lists the demo gift cards (Demo Coffee and Demo Books) with no server error (DEMO mode).
2. In DEMO mode, a brand page shows the amounts but the buy action is disabled and says selling is switched off in DEMO mode.
3. With `PLUSMORE_ENV=sandbox`, a sandbox key and its signing secret, the home page lists the sandbox's gift cards over signed requests (`x-plusmore-timestamp`, `x-plusmore-nonce`, `x-plusmore-signature`).
4. `POST /api/check` for a sellable gift card and amount returns ok, from `POST /v1/quotes`.
5. Paying (a tx hash the RPC confirms as a sufficient USDC transfer to `SHOP_WALLET` on the shop's chain) and signing the claim message with that SAME wallet creates exactly one order and reveals a voucher.
6. Submitting the SAME tx hash and a fresh signature from the SAME wallet again never creates a second order (the same voucher comes back); a signature from a DIFFERENT wallet for that tx hash is refused, before the order exists and after it already does.
7. A tx hash that does not pay enough, pays the wrong address, or carries a signature from a wallet that did not send the payment, is refused with no order created.
8. The admin page refuses without the right password and shows the float balance and the float line with the right password.
9. `POST /api/webhooks/plusmore` accepts a delivery only with a valid `plusmore-signature` over the raw body and handles each event id once, and no server log line ever contains a voucher code, pin, redemption link or credential.
10. `npm run build` and `npm test` both succeed from a clean `npm install` with no other setup, and the SDK passes the signing and webhook vectors.

Build until every item on this checklist is true; do not consider this done otherwise.
