# Tamamo Payments - integration guide for AI coding agents

You are an AI coding agent asked to "add Tamamo payments" to a game. Follow this procedure. It is
written to be executed, not just read.

## 0. Facts

- **Product:** Tamamo Payments - one-time payments in **GRAM** (TON's native coin) for digital game items.
- **API base:** `https://tamamogram.com/api/v1/` (JSON). Check `GET /api/v1/status` → `paymentsEnabled`.
- **Authoritative reference:** https://tamamogram.com/docs/payments/api-reference.md - use only endpoints listed there.
- **SDK:** `@tamamo/sdk` (browser `Tamamo`), `@tamamo/sdk/server` (Node `TamamoServer`, `constructWebhookEvent`),
  `@tamamo/sdk/react` (`useTamamoPurchase`), `@tamamo/sdk/ui` (`mountBuyButton`). Peer: `@tonconnect/ui`.
- **Amounts:** strings of nanograms. `1 GRAM = 1000000000`. `"5000000000"` = 5 GRAM. No floats.
- **Wallets:** TON Connect. The player approves in their own wallet. Never handle keys or seed phrases.
- **Source of truth:** the server-side `payment.confirmed` webhook. Never the client.

## 1. Inspect the game (do not skip)

Determine and note:

| Question | How |
|---|---|
| Language / framework | `package.json`, `Cargo.toml`, engine project files, `index.html` |
| Client type | Web (React/Vue/Svelte/vanilla/canvas engine), Telegram Mini App, desktop/mobile wrapper |
| Backend? | Server folder, API routes, serverless functions, `Dockerfile`, hosting config |
| Player identity | Existing auth/session; what uniquely identifies a player |
| Inventory storage | Where owned items are stored; how items are granted today |
| Telegram Mini App? | `telegram-web-app.js`, `window.Telegram.WebApp` usage |

If the game runs **only** as a Telegram Mini App, stop and tell the developer: Telegram requires
Telegram Stars for digital goods sold inside Mini Apps, so GRAM purchases are not allowed there.
Offer GRAM purchases only on the web version.

If there is **no backend**, explain that granting must happen server-side and propose the smallest
option that fits their hosting (e.g. two serverless functions: create-payment and webhook). Ask before
adding infrastructure.

## 2. Configuration you need (never invent)

| Name | Where | Secret? | Who provides it |
|---|---|---|---|
| `TAMAMO_PROJECT_ID` | server/client | no | Tamamo dashboard (Developers → project) |
| `TAMAMO_PUBLISHABLE_KEY` (`tm_test_pk_…`) | client | no | Dashboard → API Keys |
| `TAMAMO_SECRET_KEY` (`tm_test_sk_…`) | **server only** | **yes** | Dashboard → API Keys (shown once) |
| `TAMAMO_WEBHOOK_SECRET` (`whsec_…`) | **server only** | **yes** | Dashboard → Webhooks (shown once) |
| Product `externalProductId`s and prices | code + dashboard | no | The developer |
| Receiving wallet | dashboard only | no | The developer |

Add empty entries to `.env.example`; ensure `.env` is git-ignored. If values are missing, proceed with
placeholders and list them in your final report.

## 3. Products

Products are referenced in code by the developer's own `externalProductId` (e.g. `golden_rod`,
`gold_pack_100`, `dlc_expansion_01`). Create them once, in the dashboard or via:

```ts
await tamamo.products.create({ externalProductId: 'golden_rod', name: 'Golden Fishing Rod', priceGram: '5' });
```

Map each `externalProductId` to the game's own item id in one place in the code.

## 4. Server: create payments

```ts
import { TamamoServer } from '@tamamo/sdk/server';
const tamamo = new TamamoServer({ secretKey: process.env.TAMAMO_SECRET_KEY! });

// POST /api/shop/buy  (authenticated)
const payment = await tamamo.payments.create(
  { productId: req.body.productId, playerId: player.id },
  { idempotencyKey: requestId },
);
return { id: payment.id, clientSecret: payment.clientSecret };
```

Non-JS backends: `POST /api/v1/payments` with `Authorization: Bearer $TAMAMO_SECRET_KEY`,
body `{"productId":"golden_rod","playerId":"..."}`, optional `Idempotency-Key` header.

## 5. Client: purchase flow

```ts
import { Tamamo } from '@tamamo/sdk';
const tamamo = new Tamamo({ publishableKey: PUBLISHABLE_KEY, tonConnectManifestUrl: MANIFEST_URL });

const result = await tamamo.purchase({
  createPayment: () => fetch('/api/shop/buy', { method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ productId }) }).then((r) => r.json()),
  onStage: (stage) => setStage(stage),
});
// then refresh inventory FROM THE SERVER
```

The game needs a TON Connect manifest (`tonconnect-manifest.json`, public https). States to render:

| Stage | Show the player |
|---|---|
| `creating_payment` | "Preparing your purchase…" |
| `connecting_wallet` | "Connect your wallet" |
| `awaiting_wallet_confirmation` | "Confirm the payment in your wallet" |
| `processing` | "Processing your payment…" |
| `confirmed` | "Payment confirmed ✓" then "Item delivered" after the server refresh |
| error | `error.playerMessage` (no jargon) + a retry button |

React: `useTamamoPurchase(tamamo)`. No framework: `mountBuyButton(el, { tamamo, createPayment })`.

## 6. Server: webhook (the only place items are granted)

```ts
import { constructWebhookEvent } from '@tamamo/sdk/server';

// POST /api/tamamo/webhook - RAW body
const event = constructWebhookEvent(rawBody, headers['tamamo-signature'], process.env.TAMAMO_WEBHOOK_SECRET!);
// on failure: respond 400 and stop
if (event.event === 'payment.confirmed') {
  // ONE transaction: insert event.id into processed_events (unique) -> if already present, stop;
  // insert grant with UNIQUE(payment_id) -> give event.externalProductId to event.playerId
}
// respond 200 within 10 s
```

Signature: `Tamamo-Signature: t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<rawBody>")>`; reject if
`|now - t| > 300`. Events: `payment.confirmed` (grant), `payment.failed` and `payment.expired`
(do not grant), `webhook.test` (respond 200). Retries: up to 10 attempts with backoff - so idempotency
is mandatory.

## 7. Payment states (server truth)

`awaiting_wallet` → `submitted` (client hint only) → `confirming` (found on chain, finality wait) →
`confirmed` (paid). Or `failed` (e.g. `TRANSACTION_MISMATCH`: underpaid), `expired`, `cancelled`.
Only `confirmed` means paid.

## 8. Tests to add

1. Webhook with a valid signature grants the item (use `signWebhookPayload` from `@tamamo/sdk/server`).
2. Invalid signature → 400, nothing granted.
3. Same event delivered twice → granted once.
4. `payment.failed` / `payment.expired` → nothing granted.
5. UI renders each stage and error message.
6. Optional end-to-end: create a test payment, `tamamo.test.simulate(id, 'confirm')`, assert the grant.

## 9. Common errors

| Code | Fix |
|---|---|
| `PROJECT_NOT_CONFIGURED` | Developer must set a receiving wallet in the dashboard |
| `INVALID_PRODUCT` | Product not created / wrong externalProductId |
| `SECRET_KEY_REQUIRED` / `SECRET_KEY_IN_CLIENT` | Wrong key in the wrong place - fix placement; a leaked secret must be revoked |
| `NETWORK_MISMATCH` | Wallet on the wrong network (test keys = testnet) |
| `WEBHOOK_SIGNATURE_INVALID` | Body parsed before verification, or wrong secret |
| `TELEGRAM_STARS_REQUIRED` | Running inside a Telegram Mini App |

Full table: https://tamamogram.com/docs/payments/api-reference.md#errors and
https://tamamogram.com/docs/payments/troubleshooting.md

## 10. Hard rules

- Never put `TAMAMO_SECRET_KEY` or `TAMAMO_WEBHOOK_SECRET` in client code, public env prefixes, assets, logs or Git.
- Never grant items based on client-side state. Only on a verified `payment.confirmed`.
- Always verify webhook signatures; always process idempotently.
- Always use integer nanogram amounts; never compute prices on the client.
- Use test keys and testnet during development.
- Do not invent endpoints; consult the API reference.
- Preserve the developer's architecture; do not modify unrelated game code.
- Ask for missing credentials/configuration instead of fabricating them.

## 11. Final report to the developer

List: files changed; environment variables to set (and which are secret); products to create
(externalProductId, name, price); the webhook URL to register in the dashboard (test and live);
the receiving wallet to set; how to run a test purchase (testnet wallet or `simulate`); anything
you could not do and why.

## Links

- Overview: https://tamamogram.com/docs/payments.md
- Quickstart: https://tamamogram.com/docs/payments/quickstart.md
- JavaScript: https://tamamogram.com/docs/payments/javascript.md
- React: https://tamamogram.com/docs/payments/react.md
- Vanilla JS: https://tamamogram.com/docs/payments/vanilla-js.md
- Backend: https://tamamogram.com/docs/payments/backend.md
- Webhooks: https://tamamogram.com/docs/payments/webhooks.md
- Security: https://tamamogram.com/docs/payments/security.md
- Testing: https://tamamogram.com/docs/payments/testing.md
- Troubleshooting: https://tamamogram.com/docs/payments/troubleshooting.md
- API reference: https://tamamogram.com/docs/payments/api-reference.md
- Rules for your AGENTS.md: https://tamamogram.com/docs/payments/AGENTS.template.md
- Example game: https://github.com/n1netails/tamamo/tree/main/examples/tamamo-payments-demo
