Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
2da50b8
feat: x402 payment protocol POC for Hathor Network
andreabadesso Apr 2, 2026
e990b56
feat: multi-token support and asset field alignment with x402 spec
andreabadesso Apr 2, 2026
9ebb1c7
feat: add x402 payment client dApp
andreabadesso Apr 2, 2026
085ea0b
docs: rewrite README with detailed escrow model explanation
andreabadesso Apr 2, 2026
c13559b
feat: add payment channels (pre-funded, instant after setup)
andreabadesso Apr 2, 2026
0341ff0
fix: settle before serving resource (no optimistic verify)
andreabadesso Apr 2, 2026
da57309
feat: add docker-compose for production deployment
andreabadesso Apr 2, 2026
17f25d2
fix: use latest tag for wallet-headless Docker image
andreabadesso Apr 2, 2026
4c9aa49
fix: remove host port conflicts, add FACILITATOR_URL for Docker netwo…
andreabadesso Apr 2, 2026
fe23c58
fix: use ports 4020/4021 to avoid conflicts on deploy server
andreabadesso Apr 2, 2026
a03666e
fix: add healthchecks and ordered startup for Traefik
andreabadesso Apr 2, 2026
72938f6
fix: use curl for dApp healthcheck (already installed in image)
andreabadesso Apr 2, 2026
5d266f4
fix: expose facilitator port for Traefik routing
andreabadesso Apr 2, 2026
3e91a76
fix: add tx-mining service URL for wallet-headless
andreabadesso Apr 2, 2026
367dd5b
fix: use public URLs for deployed services
andreabadesso Apr 2, 2026
e4799f5
feat: auto-initialize wallets on deploy
andreabadesso Apr 2, 2026
a6222d7
fix: use HTTPS for fullnode URLs (mixed content blocked by browser)
andreabadesso Apr 2, 2026
02a4a3e
fix: upgrade wallet-headless to v0.39.0-rc.1
andreabadesso Apr 3, 2026
3e7e7ec
revert: back to wallet-headless:latest
andreabadesso Apr 3, 2026
361beb4
fix: remove debug plugin from wallet-headless
andreabadesso Apr 6, 2026
821b459
fix: force Docker to always pull latest wallet-headless image
andreabadesso Apr 6, 2026
8b16334
fix: settle async to avoid Traefik timeout on deployment
andreabadesso Apr 6, 2026
33cee78
fix: don't wait for block confirmation on settlement
andreabadesso Apr 6, 2026
461da83
feat: align with x402 V2 spec and add production stability
andreabadesso Apr 7, 2026
b8cb857
fix: add detailed RPC error logging for balance fetch debugging
andreabadesso Apr 7, 2026
2a9ea64
fix: log raw error keys and JSON on RPC failure
andreabadesso Apr 7, 2026
ef1beea
fix: fallback to fullnode API for balance when wallet RPC fails
andreabadesso Apr 7, 2026
b4f5c16
fix: JSON.stringify crash on BigInt response was causing RPC "failure"
andreabadesso Apr 7, 2026
875cbd7
fix: remove idempotency cache for channel settlements
andreabadesso Apr 7, 2026
8f1e4ea
feat: add x402 "upto" scheme for usage-based billing
andreabadesso Apr 9, 2026
3d6aa6f
feat(dapp): demonstrate the upto scheme in X402Fetch
andreabadesso Apr 9, 2026
749b66b
feat: hathor-direct PoC — drop nano contracts, add UTXO-payment + sig…
pedroferreira1 May 28, 2026
43e1956
ci(dokploy): use named volume x402_data for SQLite persistence
pedroferreira1 May 28, 2026
5b5d04c
fix(verifier): align mint/verify SERVER_SECRET fallback
pedroferreira1 May 28, 2026
3348b2a
fix(dapp): pin changeAddress to address-0 + stop auto-refresh balance
pedroferreira1 May 28, 2026
48e0a21
feat(verifier): switch PAYMENT-SIGNATURE to multi-signature payload
pedroferreira1 May 29, 2026
1bd4088
feat(skill): add x402-pay Claude Code skill
pedroferreira1 Jun 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# --- Hathor fullnode (read-only) --------------------------------------------
FULLNODE_URL=https://node1.testnet.hathor.network
HATHOR_NETWORK=testnet

# --- Resource server --------------------------------------------------------
RESOURCE_SERVER_PORT=3000
RESOURCE_SERVER_PUBLIC_URL=http://localhost:3000

# Seller's static receiving address. The resource server emits this in 402's
# `payTo`. The seller controls this address (in any wallet of their choosing).
SELLER_ADDRESS=

# --- Server secret (HMACs the requestId) ------------------------------------
# Must be at least 32 bytes of entropy in prod. Local dev: any non-empty string.
SERVER_SECRET=change-me-32-bytes-min
REQUEST_ID_TTL_SECONDS=120

# --- Dedup + blocklist store ------------------------------------------------
DEDUP_DB_PATH=./data/payments.sqlite

# Above this amount, the verifier refuses zero-conf (requires meta.first_block).
# Default: never require a block (zero-conf for everything — fine for POC).
ZERO_CONF_MAX_AMOUNT=9007199254740991

# --- Pricing (atomic units; 1 HTR = 100) ------------------------------------
HTR_PAYMENT_AMOUNT=100
GENERATE_MAX_PRICE=500

# --- Verify path: 'self' or 'facilitator' -----------------------------------
VERIFY_MODE=self
FACILITATOR_PORT=8402
FACILITATOR_URL=http://localhost:8402

# --- Seller's wallet-headless (only needed for the upto refund) ------------
SELLER_WALLET_URL=http://wallet-headless:8000
SELLER_WALLET_ID=seller
SELLER_SEED=

# --- Optional: only needed if you want to run the CLI client.js -------------
BUYER_SEED=
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/
*.log
.env
.deploy
.DS_Store
26 changes: 26 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
FROM node:22-alpine

# `curl` for the init script + container healthchecks; build deps installed
# transiently for the `better-sqlite3` native compile.
RUN apk add --no-cache curl

WORKDIR /app

COPY package.json package-lock.json* ./

# Install with build deps, then drop them to keep the image small.
RUN apk add --no-cache --virtual .build python3 make g++ \
&& npm install --omit=dev \
&& apk del .build

COPY *.js ./
COPY *.sh ./

# Persistent dedup + blocklist SQLite file lives here.
RUN mkdir -p /app/data
VOLUME ["/app/data"]

EXPOSE 8402 3000

# Default: run the resource server. Override CMD for the facilitator service.
CMD ["node", "resource-server.js"]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Hathor Network

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
168 changes: 165 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,167 @@
# x402 Payment Protocol POC for Hathor Network
# x402 Payment Protocol PoC for Hathor Network

> Machines paying machines. HTTP 402 meets nano contract escrow.
> Machines paying machines, settled on Hathor with regular UTXO payments.
> No nano contracts, no escrow blueprint, no facilitator hot wallet.

See the [x402 RFC](https://github.com/HathorNetwork/rfcs/blob/feat/x402-support/projects/x402/0001-x402-support.md) for the full protocol design.
This is a proof-of-concept implementation of the [x402 protocol](https://www.x402.org/)
on [Hathor Network](https://hathor.network/) using the **`hathor-direct`** scheme: the
client makes an ordinary "send tokens" transaction to the seller, signs a server-issued
challenge with its payer key, and the server verifies the on-chain payment + signature
read-only.

See the full design rationale (with the rejected nano-contract design and the
fair-exchange / trust analysis) in
[`../x402-hathor-no-nc-proposal.md`](../x402-hathor-no-nc-proposal.md).

## What is x402?

[x402](https://www.x402.org/) repurposes the HTTP `402 Payment Required` status code
for machine-to-machine payments: a client requests a paid resource, the server returns
a 402 with payment requirements, the client pays, retries the request with proof, and
gets the resource. The client is always code — an AI agent, a script, a backend
service. Never a human clicking buttons.

## How Hathor does it (this PoC)

```
┌──────────────┐ ┌──────────────────────────┐ ┌─────────────────┐
│ dApp / │──fetch──▶│ resource-server │──read───▶│ Hathor fullnode │
│ agent │ │ verifier.js + │ │ (testnet/etc.) │
│ │ │ dedupStore + │ └─────────────────┘
│ htr_sendTx │ │ voidWatcher + │ ▲
│ htr_signWith │ │ (refundIssuer for │ │
│ Address │ │ the upto scheme) │ │
└──────┬───────┘ └──────────┬───────────────┘ │
│ │ POST /wallet/send-tx (refund only)
▼ ▼
Hathor wallet wallet-headless (seller refund wallet)
(desktop / mobile /
MetaMask snap)
```

Two on-chain transactions in the worst case:

1. **Client → seller**: a plain `sendTransaction` paying `amount` to `payTo`.
This is the *only* tx for `hathor-direct` (exact).
2. **Seller → client** (upto only): a refund tx for `amount - chargedAmount`,
issued by the seller's wallet-headless after the route handler reports
actual usage.

The server (or an optional facilitator wrapper) is purely read-only against the
fullnode:

- Verify the on-chain payment (correct `payTo`, `amount`, asset, not voided).
- Verify the payer signature over the server-issued `requestId`.
- Atomically dedup against the SQLite ledger so the same payment can't be replayed.
- Kick off a void-watcher for zero-conf payments; double-spending payers get
blocklisted.

## Schemes

| Scheme | Semantics | Settlement |
|---|---|---|
| `hathor-direct` | Pay exact amount up front. | No-op — payment is final on-chain. |
| `hathor-direct-upto` | Authorize a max. Server charges actual usage. | Server issues a refund tx for `max - charged` from its own wallet. |

Both use the same wire protocol and verifier code path; `upto` adds the optional
refund step.

## Wire protocol

402 body returned by the resource server:

```jsonc
{
"x402Version": 2,
"accepts": [{
"scheme": "hathor-direct" | "hathor-direct-upto",
"network": "hathor:testnet",
"amount": "100", // atomic units; 1 HTR = 100. For upto, this is MAX.
"asset": "00", // "00" = HTR
"payTo": "WXf4x…",
"resource": "https://host/route",
"maxTimeoutSeconds": 120,
"description": "Pay 1.00 HTR",
"extra": {
"requestId": "<base64url(claims)>.<base64url(mac)>",
"facilitatorUrl": "https://…" // optional
}
}]
}
```

The client retries with a `PAYMENT-SIGNATURE` header (base64-encoded JSON):

```jsonc
{
"x402Version": 2,
"scheme": "hathor-direct",
"network": "hathor:testnet",
"payload": {
"txId": "000abc…",
"payerAddress": "WPo2…",
"signature": "BASE64…",
"requestId": "<base64url(claims)>.<base64url(mac)>"
}
}
```

## Components

| Component | File | Port | What it does |
|---|---|---|---|
| **Resource server** | `resource-server.js` | 3000 | Paid `/weather` (direct) + `/generate` (upto). Self-verifies via `verifier.js`. |
| **Facilitator** (optional) | `facilitator.js` | 8402 | Thin HTTP wrapper around the verifier. No wallet, no seeds, no nano contracts. |
| **Verifier** | `verifier.js` | — | Single source of truth for "is this payment claim valid?" |
| **Dedup store** | `dedupStore.js` + SQLite | — | Atomic `(txId, outputIndex)` ledger + payer blocklist. |
| **requestId** | `requestId.js` | — | Stateless HMAC challenge token (binds payment ↔ request). |
| **Void watcher** | `voidWatcher.js` | — | Background detection of double-spent payments → blocklist. |
| **Refund issuer** | `refundIssuer.js` | — | Calls the seller's wallet-headless to issue upto refunds. |
| **CLI client** | `client.js` | — | Buyer-side smoke test using `@hathor/wallet-lib`. |
| **dApp** | `dapp/` | 3000 | Browser client (Next.js + WalletConnect/Reown + MetaMask Snap). |
| **MCP example** | `examples/mcp-server/` | stdio | Paid MCP tool gated by `hathor-direct`. |

## Quick start

```bash
# 0. Fund a Hathor address on testnet (faucet) — that's the seller address.
# Generate a seed for the seller wallet (only needed for the upto scheme).

cp .env.example .env
$EDITOR .env # set SELLER_ADDRESS, SELLER_SEED, SERVER_SECRET

docker compose up --build
# -> wallet-headless on :8000 (seller wallet)
# -> resource-server on :3000 (paid /weather, /generate)
# -> dapp on :4020

# Browser: http://localhost:4020 — connect WalletConnect, fetch the paid URL.
# CLI: BUYER_SEED='...' node client.js --route weather
```

## What this PoC is NOT

- **Not production-ready.** Idempotent retry response caching, blocklist
sharing, structured logging, metrics, key rotation for `SERVER_SECRET`
are all deferred.
- **Not confidential-transaction-enabled.** Hathor's shielded outputs are
alpha and out of mainnet — the design is *compatible* with future CT but
this PoC doesn't exercise it.
- **No protocol-level refund** beyond the upto remainder. If the server takes
the payment and doesn't deliver, there is no on-chain recovery — same trust
model as EVM `exact`. Reputation + small amounts + amount caps is the
bounding mechanism.

## References

- Design proposal: [`../x402-hathor-no-nc-proposal.md`](../x402-hathor-no-nc-proposal.md)
- x402 specification: <https://www.x402.org/>
- x402 v1 → v2 migration: <https://docs.x402.org/guides/migration-v1-to-v2>
- Hathor wallet-lib `signMessage`/`verifyMessage`:
`hathor-wallet-lib/src/utils/crypto.ts`
- Hathor RPC methods (`htr_sendTransaction`, `htr_signWithAddress`):
`hathor-rpc-lib/packages/hathor-rpc-handler/src/types/rpcRequest.ts`

## License

MIT
Loading