kculture-x402
by k-agentpay
README.md
# kaia-x402
**x402 payments on Kaia.** AI agents pay per request in **JPYC or USDT on Kaia**: no account, no API key, and no KAIA needed by the buyer.
- **x402 v2**, network `eip155:8217`, headers `PAYMENT-REQUIRED` / `PAYMENT-SIGNATURE` / `PAYMENT-RESPONSE` (v1 `X-PAYMENT` still accepted).
- **Standard-compatible for JPYC**: the official x402 v2 client (`@x402/fetch` + `@x402/evm`) pays this server unmodified — see [`examples/official_client.mjs`](examples/official_client.mjs).
The official client only allows its default assets (e.g. USDC) unless told otherwise, so allow JPYC on Kaia in its config:
```js
spendControls: { allowedAssets: [{ network: "eip155:8217", asset: "0xe7c3d8c9a439fede00d2600032d5db0be71c3c29", maxAmountPerPayment: "100000000000000000000" }] } // ¥100 cap
```
- **Live service** built on this repo: **https://api.k-agentpay.com** (catalog at `/v1`). Every endpoint takes `lang=ja` (default) `| en | ko`; the MCP tools pass the user's language.
## Buying data (people and their AI agents)
The steps to buy from the live service. The *Quick start* further down (`keys.mjs`, `facilitator.mjs`, `server.mjs`) is for sellers running their own API; buyers do not need it.
1. Install: `npm install`
2. Find the concert id (free, no payment):
`node client.mjs "https://api.k-agentpay.com/v1/kpop/search?q=EVNNE"`
3. Buy the trip pack (¥50, paid in JPYC on Kaia):
`node client.mjs "https://api.k-agentpay.com/v1/seoul/trip-pack?id=<id>"`
Add `&lang=en` or `&lang=ko` for English or Korean (default Japanese).
4. `client.mjs` prints `wallet: 0x…` first. If that wallet has no balance, it says so; the wallet owner decides whether to fund it with **JPYC on Kaia** (a few hundred yen covers several purchases). **No KAIA is needed for gas.** After funding, step 3 can be run again.
Safety notes:
- The wallet key is created at `~/.kaia-x402/buyer.key` (or `$KAIA_X402_HOME/buyer.key`). Run this on your own computer. In temporary cloud environments (e.g. Claude Code on the web) the key disappears when the session ends, together with any funds sent to it.
- Spending limits: ¥100 per payment and ¥300 per day by default (`MAX_CALL_YEN`, `MAX_DAY_YEN`). They are computed from the amount actually signed (USDT is converted at our own ECB-based rate; a server's own price label can only raise it), each signed payment counts toward the day as soon as it is sent, and every signature expires within 2 minutes.
- Only send a small amount: this wallet is for small per-request payments.
This repo contains:
- a **Kaia x402 facilitator** (`/verify`, `/settle`, `/supported`) for the `exact` scheme, which pays the gas itself (logic in `facilitator_core.mjs`):
- **JPYC** via EIP-3009 `transferWithAuthorization` (one tx) — the standard x402 `exact` EVM method;
- **USDT** via EIP-2612 `permit` + `transferFrom` (two txs; spender = the facilitator, allowance = the price). **Non-standard extension**: Kaia USDT has no EIP-3009, and the x402 Permit2 proxy (`0x402085c2…20001`) is not deployed on Kaia yet (Permit2 itself is). Official clients will pick the JPYC option;
- an **example paid API** (`server.mjs`, sample data in `examples/`): a free search and a ¥50 *ソウル遠征パック* (Seoul concert trip pack for Japanese fans);
- a **buyer library** with wallet guardrails, and **MCP tools** so any MCP-capable agent (Claude, Cursor, …) pays automatically.
```
agent ──GET /v1/seoul/trip-pack?id=…──▶ API ◀── 402 Payment Required (accepts: JPYC ¥50 | USDT $0.32, payTo)
agent signs a JPYC authorization (EIP-3009) or a USDT permit (EIP-2612), gasless for the agent
agent ──GET + X-PAYMENT──▶ API ──verify / settle──▶ facilitator ──▶ funds move on Kaia
agent ◀── 200 + data + X-PAYMENT-RESPONSE (tx hash)
```
Data is returned only after the payment has settled. If the upstream data fails, or the request is invalid (e.g. unknown id), the buyer is not charged. A payment payload is served at most once.
Settlement edge cases: a transfer that was broadcast but has no receipt within 45 s is treated as settled (the signature and balance were verified), the data is returned, and the final outcome is confirmed in the background. Every attempt is written to `data/settlements.jsonl` (`settled`, `reverted`, `pending` → `pending_settled` / `pending_reverted`). `refund.mjs` sends a manual refund from the seller, gasless for the seller (dry run by default, `--live` to send).
## Live on Kaia mainnet
Payments on 2026-10-14 (the buyer held 0 KAIA for the JPYC payments):
| What was bought | Paid | Tx |
|---|---|---|
| Seoul concert trip pack (Japanese) | ¥50 JPYC | [0x004de750…](https://kaiascan.io/tx/0x004de750742b9ffb44377cc003f511c4bc6526d70d4572de5f08d2ac66b3fda5) |
| Seoul concert trip pack (Japanese) | $0.32 USDT | [0xb0d30aad…](https://kaiascan.io/tx/0xb0d30aad8624601fe8e014c54983b3e176b97e54a4e384161bf09cb075659f21) |
| Seoul pop concerts | ¥3 JPYC | [0x6adc96bd…](https://kaiascan.io/tx/0x6adc96bdc5faa249ef76e837f1ffc45c8f2a97177a330035e2930dc73052b4f8) |
| Korea festivals (Japanese) | ¥3 JPYC | [0xe40c3fe7…](https://kaiascan.io/tx/0xe40c3fe7322417f469701a9224abafff1dfafdcc17c8148005d1f3cb08f39db8) |
Settlement gas, paid by the facilitator: JPYC ≈ 81k gas (≈ 0.002 KAIA); USDT ≈ 71k + 49–66k gas (≈ 0.003 KAIA).
## Token facts (verified on Kaia mainnet)
| Token | Address | Gasless method | EIP-712 domain |
|---|---|---|---|
| JPYC | `0xe7c3d8c9a439fede00d2600032d5db0be71c3c29` (18 dp) | EIP-3009 `transferWithAuthorization` | name `JPY Coin`, version `1`, chainId `8217` |
| USDT | `0xd077a400968890eacc75cdc901f0356c943e4fdb` (6 dp) | EIP-2612 `permit` (no EIP-3009) | name `Tether USD`, version `1`, chainId `8217` (matches `DOMAIN_SEPARATOR()`) |
USDT payment payload (our extension of `exact` for permit-only tokens): `payload = { signature, permit: { owner, spender, value, nonce, deadline } }`, where `spender` is `extra.spender` from the 402 response. The facilitator moves exactly `value` to `payTo`.
## Example API
| Endpoint | Price | Returns |
|---|---|---|
| `GET /v1/kpop/search?q=` | free | concerts matching an artist or title, with ids (the discovery step) |
| `GET /v1/seoul/trip-pack?id=` | ¥50 | Japanese trip pack: schedule, seat prices in yen, ticket sellers, venue + map link, nearby hotels/food/spots |
| `GET /v1`, `GET /.well-known/x402` | free | machine-readable catalog |
The example serves one sample concert (`examples/trip_pack_sample.json`); replace the handlers with your own data. `paid(describe, handler, priceYen)` is the reusable part: it returns 402 with both payment options, verifies, runs the handler, settles, and only then returns the data.
Prices are set in yen. The USDT price is the yen price converted at the ECB euro reference rates (daily), rounded up to the cent.
## Quick start (sellers: run your own paid API)
```bash
npm install
node keys.mjs # creates facilitator / seller / buyer keys in secrets/ (prints addresses only)
# fund the buyer with a little JPYC or USDT on Kaia, the facilitator with a little KAIA (gas)
node facilitator.mjs & # 127.0.0.1:8402
node server.mjs & # 127.0.0.1:8403
node client.mjs # pays the example trip pack
```
Environment: `KAIA_RPC_URL` (default `https://public-en.node.kaia.io`), `PRICE_YEN` (3), `PACK_YEN` (50), `PUBLIC_BASE` (public URL used in the 402 `resource`), `PAY_TO` (payTo address; the seller key is then not needed on the server).
## Use it from an agent (MCP)
**One-click (Claude Desktop):** download `kaia-x402-mcp.mcpb` from the [latest release](https://github.com/k-agentpay/kaia-x402/releases/latest) and open it.
- MCP Registry name: `mcp-name: com.k-agentpay/kaia-x402`
The MCP server runs next to the agent, with the agent's own wallet:
```json
{
"mcpServers": {
"kculture-x402": { "command": "node", "args": ["/path/to/kaia-x402/mcp.mjs"], "env": { "API_BASE": "https://api.k-agentpay.com" } }
}
}
```
- Wallet: `KAIA_X402_KEY_FILE`, else `secrets/buyer.key` in this checkout, else `~/.kaia-x402/buyer.key` (created on first use, mode 0600). Call `wallet_info` to see the address and balances, then send it JPYC or USDT on Kaia.
- `PAY_ASSET`: `auto` (default: JPYC when the balance covers the price, else USDT), `JPYC` or `USDT`.
- Limits: `MAX_CALL_YEN` (100) and `MAX_DAY_YEN` (300). The daily budget is reserved before each payment, so parallel tool calls cannot overshoot it.
`API_BASE` defaults to the live service https://api.k-agentpay.com.
Tools: `wallet_info` (free), `kpop_search(q)` (free), `seoul_places()` (free), `request_korea_data(want)` (free: ask for Korea data we don't have yet), `seoul_trip_pack(id)`, `kpop_new_concerts(q?, since?)`, `seoul_now(place)`, `seoul_subway_now(station)`, `incheon_airport_wait()`, `kpop_concerts(from?, to?)`, `korea_festivals(lang, from?)`. Each paid call returns the data with the payment tx. (The example server implements `kpop_search` and `seoul_trip_pack`; the hosted K-culture service implements all of them.)
## Missing some Korea data?
Open a [data request](https://github.com/k-agentpay/kaia-x402/issues/new?template=data-request.yml), or let your agent call `GET https://api.k-agentpay.com/v1/request?want=...` (free) / the MCP tool `request_korea_data`. The most requested data is built first.
## Deploy
`deploy/push.sh` copies the app to a fresh Amazon Linux 2023 host and runs `deploy/setup_server.sh`: Node, systemd units for the facilitator (private, 127.0.0.1) and the API, and Caddy for HTTPS. Only the facilitator gas key (plus any files in `DEPLOY_SECRETS`) goes to the host; payTo is an address.
```bash
HOST=<ip> DOMAIN=<api host> SSH_KEY=~/.ssh/<key> bash deploy/push.sh
```
## Tests
- `npm test` — offline facilitator tests (stubbed chain): valid v1/v2 payloads; rejects wrong recipient, low amount, expired / not-yet-valid authorization, forged signature, used nonce, insufficient balance, wrong network, unsupported asset, replay; USDT permit spender / nonce / deadline; pending settlement.
- `node examples/official_client.mjs <url>` — pays a running server with the official x402 v2 client (real funds).
- `test/` also runs the full flow on a local Hardhat fork of Kaia mainnet against the real JPYC contract (`test/fund_fork.mjs` funds the demo wallets on the fork only).
## License
MIT
This server cannot be deployed
Maintenance
ActivitySlowing
ResponsivenessLimited data