# Skill: Getting Started with Loyal Spark

## Goal
Make your first paid call, and get an API key only when the job needs one.

**Pay first, key later.** On x402/MPP, payment alone makes the paying wallet the caller for every `recipient-api` route and for merchant GET reads (`/programs`, `/rewards`, `/balance`, …). You do not need to register to read. Get a key only for mint, deploy, create rewards, trade, or to call `/agent-api` directly without paying per call.

## When to Use
- You need to see loyalty programs before you have a key
- You want a full `lsk_` key on the Free plan ($0.01 via x402 `register-agent`: 200 calls/month, 1,000 mint tokens/month, all 5 scopes)
- You are a merchant on a Shopify store plan (Starter/Growth/Scale) or a paid Pro/Enterprise agent plan and want an `lsk_` key within your plan's limits
- You hold points in a wallet and need an `rwk_` key for that wallet only

## Agent rules: probes, 400 before 402, payment headers, next_steps

- **Probe vs. bad input.** An unpaid request with no input (no query params other than `?method=`, empty body or `{}`, MCP `arguments` empty) gets **402** with the price: that is the probe. An unpaid request that does carry input but is invalid (missing a required field, bad JSON, bad `0x` address) gets **400 with `charged:false` before any 402**, so you never pay for a call that would fail. A paid call that fails the same check is 400 and is not settled.
- **x402 headers.** Send the signed payload in `PAYMENT-SIGNATURE` (x402 v2). `X-PAYMENT` is the legacy v1 name and still works. A settled response carries `PAYMENT-RESPONSE` (base64 JSON `{success, transaction, network, payer}`) plus the legacy `X-Payment-Response: settled` and `X-Payment-TxHash`. Any response with `charged:false` was not settled.
- **MPP.** `https://api.loyalspark.online/mpp-gateway/<route>` answers `WWW-Authenticate: Payment`. Pay on Tempo (chain 4217, pathUSD or USDC) and resend with `Authorization: Payment <credential>` (`npm install -g mppx && mppx account create && mppx <url>`). USDC on Base is x402 only.
- **MPP is REST-only.** `Authorization: Payment …` sent to `/loyalty-mcp` or `/recipient-loyalty-mcp` gets **400 `invalid_payment_header`** (`charged:false`): MCP is paid with x402 only (`POST https://api.loyalspark.online/x402-gateway/mcp-tools/<tool>` or `/x402-gateway/recipient-mcp-tools/<tool>` with `PAYMENT-SIGNATURE`), or call the MCP server with your `lsk_`/`rwk_` key and no payment header. An mpp-gateway route that does not exist answers 404 (405 + `Allow` for a wrong method) with `x402_equivalent` and the full `mpp_routes` list.
- **`bazaar_probe_x402` is keyless.** The probe tool on both MCP servers works without a key (20 calls/min per IP; over the limit the tool returns `isError:true` with `error_code: rate_limited` and `retry_after_seconds: 60`). A malformed or wrong-type key is still rejected; send a valid key to use your own limits.
- **`?method=GET|POST|PUT`** only matters on an unpaid GET/HEAD probe: it returns the 402 challenge for that method on the same URL (handy for POST-only routes and crawlers that can only GET). It never changes the method of a real call: send the real call with the real method and body.
- **`POST /program-status` vs `GET /workflow/program-status`.** `POST /program-status` changes a program's status (`{token_address, status}`, $0.005, needs `lsk_`). `GET /workflow/program-status` is the read-only planner: it returns the current lifecycle step and `next_actions[]` ($0.001, payment alone works).
- **Required inputs on paid reads.** `GET /rewards` needs `token_address` (or `all=true` for every program you own). `GET /balance` needs `token_address` and `customer_address` (aliases `address`, `wallet_address`, `recipient_address`); the response carries both REST names (`current_balance`, `tokens_earned_total`) and the MCP `get_token_balance` names (`current`, `total_earned`). The keyed direct `GET /agent-api/rewards` still lists all programs when `token_address` is omitted.
- **Keyless recipient lookup.** `GET https://api.loyalspark.online/x402-gateway/resolve-recipient?recipient_email=...` ($0.001, x402, no key): the paying wallet is the merchant. Same masking as the keyed `POST /agent-api/resolve-recipient` (free with `lsk_`): a full wallet only when the customer belongs to one of your programs or you sent the address.
- **Free keyed create vs $0.01 create.** With an `lsk_` key, `POST https://api.loyalspark.online/agent-api/programs` is free (counts toward your plan's monthly calls). With no key, the cheapest path is $0.01 once at `POST /x402-gateway/register-agent` (Free plan key), then free creates. `POST /x402-gateway/programs` ($0.01) is the same create for x402-native agents that budget per call or find it via Bazaar/x402scan; it still needs the `lsk_` key and plan limits. Either way you get unsigned B20 deploy calldata and pay Base gas yourself.
- **Per-call x402/MPP payments never use plan quota.** A call paid through `/x402-gateway` or `/mpp-gateway` is billed per call only: it never counts toward, and is never blocked by, your plan's monthly API calls, even when you send your `lsk_`/`rwk_` key with it. The per-minute rate limit still applies. Direct keyed calls use the monthly plan; `rwk_` keys have their own monthly bucket, separate from the same wallet's `lsk_` keys. `GET /agent-api/me` and `GET /recipient-api/me` never use quota, so you can always check which key you hold. A keyed call without payment that gets `429` with `detail: monthly_quota` will not clear in a minute: `next_steps.action` is `upgrade_plan_or_pay_per_call` with `quota_resets_at`; pay per call at the gateway URL, or upgrade.
- **Failed paid calls are not charged.** x402: the gateway verifies the payment, runs the call, and settles only when it succeeded (2xx and not an error payload, including MCP `isError:true`). A failure comes back with `charged:false` and no `PAYMENT-RESPONSE`. Writes that cannot be undone (reward redeem, voucher use, offer accept/cancel, certificate claim/revoke/mark-minted, report delete) first run as a dry run (every check, no write), then settle, then run for real; only a state change in between can fail after settlement, and that answer carries `charged:true` and `payment_tx`. A no-op write is HTTP 409 `no_change` and is not charged.
- **`payment_already_used` (HTTP 409, `charged:false`).** The x402 `PAYMENT-SIGNATURE` (its EIP-3009 nonce) or the MPP credential already paid for a call; one payment pays for one call. Sign a new authorization with a fresh nonce (MPP: pay again) and retry; `next_steps` carries the payment requirements. Nothing was charged the second time.
- **MPP charges first, so it checks first.** Before the charge, MPP runs the input check (400 `charged:false`), a preflight of key scope, program ownership and the per-minute limit, and, for the keyed writes above plus `POST activate-program` and `POST program-status`, the same dry run. A call that still fails after an MPP charge (the state changed in between, or a route that accepts payment alone and so learns the caller only from the charge, such as reads and recipient-api routes) returns its error with `charged:true` and a `charge_note`: contact support for a refund. Use x402 when a charged failure is not acceptable.
- **Next steps stay on your gateway.** Through `/x402-gateway` or `/mpp-gateway`, REST `next_actions[]` point at the same gateway (`path`, `url`); the keyed route stays in `direct_path`. An action that gateway does not sell carries `gateway_note`: call it directly with your key.
- **Transfers take `to` or `to_address`.** `POST /agent-api/transfer`, `POST /recipient-api/prepare-transfer`, MCP `transfer_loyalty_tokens` and `prepare_loyalty_token_transfer` accept either name for the recipient (B20 token transfer calldata, ERC-20 compatible).
- **Balances and customer counts.** `GET /balance` and `get_token_balance`: `current_balance` (alias `current`) is the on-chain `balanceOf`, `offchain_ledger_balance` is the ledger that `POST /mint/confirm` writes, and `balance_basis` says which one `current_balance` is (`offchain_ledger` only when the chain read failed; then `onchain_balance` is null). `total_customers` is the same number on `GET /customers`, `export_customers`, `GET /analytics` and `get_program_analytics`: distinct wallets with a voucher, a ledger row or a completed mint (platform fee wallet excluded). Email-only store customers are `store_customers`; each response carries `count_basis`. `GET /analytics?token_address=0x…` returns one program, and HTTP 404 when you do not own it.
- **Fees and reports.** Mint `fee_amount` is rounded to 15 significant digits (3 tokens at 1.25% is `0.0375`, not `0.037500000000000006`). `send_report` takes `report_type` `seo_audit`, `audit`, `growth_idea`, `data_report`, `anomaly`, `task`, `recommendation` or `weekly_report`; anything else is 400 `invalid_input` with `allowed_report_types`, before any charge.
- **Trade and certificate error codes.** `create-offer`: `invalid_amount` (400, an amount is 0, negative or not a number; `field` names it), `missing_fields` (400, `missing[]`), `insufficient_balance` (400, your wallet holds less than `offer_amount` of the offer token; nothing stored). `accept-offer`: `offer_reserved` (409, another wallet holds the 30-minute reservation; retry after `reserved_until` or pick another offer), `onchain_offer_unlinked` (409, the row has no escrow `offerId` yet so it cannot be reserved; pass `onchain_offer_id` or `create_tx_hash`, or pick another offer), `insufficient_balance` (400, your wallet holds less than `request_amount` of the request token; nothing reserved), `onchain_offer_inactive` (409, the escrow offer is already filled or cancelled on-chain, so `fillOffer` would revert; pick another offer), `onchain_offer_in_use` (409, that `onchain_offer_id` belongs to another open offer; pass this offer's own id or its `create_tx_hash`), `tx_not_found` (404, Base does not know the fill hash; retrying the same hash will not help). `cancel-offer`: the creator can always cancel; a live reservation is released (200, `reservation_released:true`). `GET /offers` with your key also lists your own reserved offers (`reserved_until`). `mark_gift_certificate_minted`: `mint_not_verified` (the tx does not send `token_amount` of the certificate token to `redeemed_by`; mint first, then pass that hash), `tx_not_found` (404, unknown hash), `tx_pending` (503, `retryable:true`, the tx is known but not confirmed yet; retry after `retry_after_ms` 3000). On x402 none of these is charged.
- **`PUT /merchant-profile` is a partial update.** Send at least one of `business_name`, `category`, `logo_url`, `description`, `website`, `location`, `use_agent_wallet`; a body with none is 400 before payment (`charged:false`). `business_name` is required only when no profile exists yet (400 `missing_business_name`, not charged). `POST /merchant-profile` creates or replaces the profile and always requires `business_name`, also on an existing profile (400 `missing_fields`, not charged); its `next_steps` point at PUT. `website` and `logo_url` must be absolute `https://` or `http://` URLs (a bare host such as `shop.example` gets `https://`); `javascript:`, `data:` and relative values are 400 `invalid_url` (`field` names it). Send `null` to clear one.
- **Other error codes.** `register-agent`: when the wallet already has an agent under another name and no free seat, a paid call is 409 `agent_exists` (`charged:false`); keep the existing key, or resend with `rotate:true` to replace it (the same name always rotates). `POST /rewards` / `create_reward`: `cost` 0 or negative is 400 `invalid_amount`. `vouchers/use` / `use_voucher` (`voucher_code` or `code`): an already redeemed voucher is 409 `voucher_already_used`; do not retry it. Any `transaction_hash` field also accepts `tx_hash`; an unknown hash is 404 `tx_not_found`, a known but unmined one is `tx_pending`. SIWE (`agent-register-siwe`, `recipient-api/register`): an expired message is 401 `siwe_message_expired`, a used or unknown nonce 401 `siwe_nonce_invalid`; `next_steps` say: POST `/siwe-nonce`, sign a new message, retry.
- **Every error says what to do next.** Every 4xx/5xx JSON body from the gateways, agent-api, recipient-api and both MCP servers carries `hint` and `next_steps` `{action, summary, request:{method, url, body|query}, docs, openapi, discovery}` plus `how_to_pay` (402 and gateway 400) or `get_key` (401/403). Follow `next_steps.request`. Paid MCP tool errors are a JSON-RPC result with `isError:true` (HTTP 200, `charged:false`); JSON-RPC protocol errors carry `next_steps` in `error.data`. Docs without JavaScript: https://loyalspark.online/for-agents.md and https://loyalspark.online/.well-known/skills/00-getting-started.md

## Steps

### Read without a key or JavaScript

`GET https://api.loyalspark.online/agent-api/platform` needs no API key. It lists endpoints (including `x402_gateway` and `mpp_gateway`), auth (`x-api-key: lsk_...` or `rwk_...`, SIWE, x402), scopes, and first calls. A plain `GET https://api.loyalspark.online/loyalty-mcp` returns discovery JSON only (no SSE on GET). JSON-RPC is `POST` with `Content-Type: application/json` and `Accept: application/json, text/event-stream` (Streamable HTTP clients must accept both). The recipient server is `GET https://api.loyalspark.online/recipient-loyalty-mcp`. Compact OpenAPI: https://loyalspark.online/openapi-lite.json · full: https://loyalspark.online/openapi.json.

### Step 1: Choose the key for the job

These are different keys. Do not treat them as substitutes.

1. **Look, no key.** `GET https://api.loyalspark.online/x402-gateway/public-programs` is $0.001. Pay it and do not send an API key. The list is active programs. It is not your own program list. The same call exists on `mpp-gateway`. On x402/MPP, payment alone also works for every `recipient-api` route and for merchant GET reads (`/programs`, `/rewards`, `/balance`, …): the paying wallet is the caller. Mint, deploy, create rewards, and trade still need a scoped key.

2. **Autonomous key ($0.01 on x402, no browser).** `POST https://api.loyalspark.online/x402-gateway/register-agent`. HTTP 402 is $0.01 USDC on Base. Pay it and do not send an API key. Optional body: `{ "agent_name": "My agent" }` (`name` is an alias; trimmed, control/markup characters removed, max 64; default `x402 agent`; paying again without a name keeps the stored name). When the payer wallet has no Shopify store plan and no paid Pro or Enterprise plan, it receives a full `lsk_…` key on the **Free** plan (1 agent, 200 API calls/month, 1,000 mint tokens/month, 1.25% mint fee, and all 5 scopes: `read`, `create_program`, `mint`, `trade`, `manage_rewards`). If the wallet belongs to a merchant on a Shopify store plan (Starter $39: 1,000 calls/month, `read` only; Growth $79: 10,000 calls/month, `read`, `mint`, `manage_rewards`; Scale $149: 100,000 calls/month, all 5 scopes) or a paid Pro/Enterprise plan, the key operates strictly within that plan's scope and call limits. A full seat returns 403 before the gateway charges.

3. **SIWE or Dashboard key.** Get or rotate a key in the dashboard [loyalspark.online/merchant](https://loyalspark.online/merchant) → **AI Agents**, or via SIWE (when the wallet has a Shopify store plan, a paid Pro/Enterprise plan, or rotates its existing Free agent by name):

   1. `POST https://api.loyalspark.online/siwe-nonce` → `{ "nonce": "..." }`.
   2. Sign this EIP-4361 message with your merchant wallet (replace the address, nonce, and Issued At). Domain `loyalspark.online`, URI `https://loyalspark.online`, and Chain ID `8453` are required. `localhost` and `127.0.0.1` are also accepted when the URI hostname matches the domain; other domains, including other `*.lovable.app` sites, are rejected. A message with no domain or a foreign domain is rejected before the nonce is consumed.

```
loyalspark.online wants you to sign in with your Ethereum account:
0xYourWalletAddress

Register Loyal Spark merchant agent

URI: https://loyalspark.online
Version: 1
Chain ID: 8453
Nonce: YOUR_NONCE
Issued At: 2026-10-21T18:00:00.000Z
```

   3. `POST https://api.loyalspark.online/agent-register-siwe` with `{message, signature, agent_name, scopes}` (`name` is an alias; max 64 characters). This uses the same plan seats as the $0.01 key. Registering again with the same wallet and the same agent name rotates and recovers the key (HTTP 200, `rotated: true`) and keeps the stored name. The previous key stops working.

4. **Holder key.** `rwk_` is not a merchant key and has no paid registration. `POST https://api.loyalspark.online/siwe-nonce`, sign with the holder wallet (domain and URI must match an allowed host, Chain ID 8453, no special phrase), then `POST https://api.loyalspark.online/recipient-api/register`. It sees only that wallet.

### Step 2: Store the key
Copy `lsk_…` or `rwk_…` when it is shown. It cannot be retrieved again. The register response includes `how_to_use` and your active `scopes`.

### Step 3: Authenticate
Include the API key in every request:

**REST API:**
```bash
curl -X GET \
  "https://api.loyalspark.online/agent-api/me" \
  -H "x-api-key: lsk_your_key_here"
```

**MCP Server:**
```json
{
  "mcpServers": {
    "loyal-spark": {
      "url": "https://api.loyalspark.online/loyalty-mcp",
      "transport": "streamable-http",
      "headers": {
        "x-api-key": "lsk_your_key_here"
      }
    }
  }
}
```

### Step 4: Verify Connection
Call `GET /me` (REST) or `get_my_profile` (MCP) to confirm authentication:

```bash
curl -H "x-api-key: lsk_..." \
  "https://api.loyalspark.online/agent-api/me"
```

MCP equivalent (note the `Accept` header):
```bash
curl -X POST "https://api.loyalspark.online/loyalty-mcp" \
  -H "x-api-key: lsk_..." \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_my_profile","arguments":{}}}'
```

**Expected response:**
```json
{
  "agent": {
    "id": "uuid",
    "name": "My Agent",
    "scopes": ["read", "create_program", "mint", "trade", "manage_rewards"],
    "owner_address": "0x..."
  }
}
```

The example above shows a Free plan key from `$0.01` `POST /x402-gateway/register-agent` (all 5 scopes). If the wallet is on a Shopify store plan (e.g., Starter `read` only, Growth `read`, `mint`, `manage_rewards`), `scopes` reflects that plan's allowed scopes. Check `scopes` before a write call. A missing scope returns HTTP 403 with `required_scope` and `how_to_get_scope`.

### Step 4.5: Learn the Workflow Before Calling Write Endpoints

Before using lifecycle, rewards, mint, vouchers, or marketplace endpoints, read the workflow guide:

- [Endpoint Workflows](./13-endpoint-workflows.md)

Important orchestration rules:

- `POST /programs` or `create_loyalty_program` starts a deploy flow; it does **not** finish it
- new B20 programs become usable only after deploy + register
- legacy ERC-20 programs need deploy + register + activate + status update
- rewards usually come after the program exists
- minting comes only after the program is active
- voucher redemption comes only after confirmed onchain token transfer

### Step 5 (Optional): Pay-per-call MCP via x402 (Bazaar-compatible)

If the agent should **pay USDC per MCP call** instead of using subscription-only access to `loyalty-mcp` or `recipient-loyalty-mcp`:

- **Merchant read tools / holder tools:** payment alone works (paying wallet = caller; API key optional). Write tools still need **`x-api-key: lsk_...`** / **`rwk_...`** with the payment. Schemas and prices: MCP `tools/list`, `https://loyalspark.online/openapi.json`, and `https://api.loyalspark.online/.well-known/x402`.
- **True keyless, do not send `x-api-key`:** `get_platform_info`, `list_marketplace_offers`, and `list_p2p_offers`, plus `GET /offers`, `GET /recipient-api/offers`, and `GET /public-programs` on both gateways. Mint/create/trade/bazaar writes are not charged when the live key is missing. No paid route is charged when required fields are missing (400 `missing_fields`). MPP prices REST only.
- JSON-RPC **`tools/call`** with same **`name`** / **`arguments`** as direct MCP.
- Use an x402 client (**`@x402/fetch`**, **`@x402/evm`**) and a wallet with **USDC on Base** to satisfy **HTTP 402**. The gateway adds **Bazaar**-oriented fields on **402** (MCP routes use `outputSchema.input.type: "mcp"` for both URL families).

### Step 6: Create Server Wallet (Optional)
For autonomous onchain transactions, create a Coinbase MPC wallet:

```bash
curl -X POST \
  "https://api.loyalspark.online/agent-wallet" \
  -H "x-api-key: lsk_..." \
  -H "Content-Type: application/json" \
  -d '{"action": "create_wallet"}'
```

## Success Criteria
- ✅ API key obtained and stored securely
- ✅ `GET /me` returns agent profile
- ✅ Scopes match intended operations

## Next Skills
- [Create Loyalty Program](./01-create-loyalty-program.md)
- [Mint Tokens](./02-mint-tokens.md)
