x402-llm-proxy 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +78 -2
- package/SKILL.md +26 -0
- package/bin/cli.mjs +135 -0
- package/package.json +61 -4
- package/src/models.mjs +85 -0
- package/src/proxy.mjs +323 -0
- package/src/x402-signer.mjs +147 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mazhic87
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,79 @@
|
|
|
1
|
-
#
|
|
1
|
+
# x402-llm-proxy
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Local **OpenAI** and **Anthropic** compatible API proxy that lets **Claude Code**, **Cursor**, **Cline**, **Continue**, **OpenClaw**, and any OpenAI/Anthropic SDK call full-strength **Claude 5.5**, **GPT-6.2**, and **Gemini 4** with **Base or Solana USDC** — no credit card, no monthly subscription, and no region lock.
|
|
4
|
+
|
|
5
|
+
Private keys stay strictly on `127.0.0.1` and sign EIP-3009 gasless USDC authorizations locally per call with hard spend caps.
|
|
6
|
+
|
|
7
|
+
## Supported Frontier Models
|
|
8
|
+
|
|
9
|
+
| Model ID | Upstream Endpoint | Price (USDC) |
|
|
10
|
+
| --- | --- | ---: |
|
|
11
|
+
| `claude-sonnet-5-5` | `/v1/llm/claude-sonnet` | 0.015 |
|
|
12
|
+
| `claude-opus-5-5` | `/v1/llm/claude-opus` | 0.030 |
|
|
13
|
+
| `claude-haiku-5-5` | `/v1/llm/claude-haiku` | 0.002 |
|
|
14
|
+
| `gpt-6.2-astra` | `/v1/llm/gpt-flagship` | 0.005 |
|
|
15
|
+
| `gpt-6.2-sol` | `/v1/llm/gpt-fast` | 0.002 |
|
|
16
|
+
| `gemini-4-argon` | `/v1/llm/gemini-pro` | 0.006 |
|
|
17
|
+
| `gemini-3.8-flash` | `/v1/llm/gemini-flash` | 0.003 |
|
|
18
|
+
|
|
19
|
+
Full gateway specification & prepaid top-up: https://sage-x402-tools.sage-ibis.workers.dev
|
|
20
|
+
|
|
21
|
+
## Quickstart
|
|
22
|
+
|
|
23
|
+
### 1. Free Connectivity & Quote Test (0 USDC)
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npx x402-llm-proxy --test
|
|
27
|
+
npx x402-llm-proxy --models
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### 2. Mode A — Pay Per Call with Base USDC (HTTP x402, Zero API Key)
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
BASE_PRIVATE_KEY=0xYOUR_HOT_WALLET_KEY npx x402-llm-proxy --max-call-usd 0.05 --max-session-usd 2.00
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### 3. Mode B — Prepaid API Key (Base or Solana USDC, True Native Streaming + Tool Use)
|
|
37
|
+
|
|
38
|
+
Generate a key and credit it with Base or Solana USDC at https://sage-x402-tools.sage-ibis.workers.dev/topup, then run:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
SAGE_API_KEY=sk-sage-... npx x402-llm-proxy
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Connect Your Tools
|
|
45
|
+
|
|
46
|
+
### Claude Code
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
ANTHROPIC_BASE_URL=http://127.0.0.1:4020 ANTHROPIC_API_KEY=x402 claude
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Cursor / Cline / Continue / Open WebUI
|
|
53
|
+
|
|
54
|
+
- **Base URL**: `http://127.0.0.1:4020/v1`
|
|
55
|
+
- **API Key**: `x402` (or your `sk-sage-...` prepaid key)
|
|
56
|
+
- **Model**: `claude-sonnet-5-5`, `gpt-6.2-astra`, `gemini-4-argon`, etc.
|
|
57
|
+
|
|
58
|
+
### Python OpenAI SDK
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from openai import OpenAI
|
|
62
|
+
|
|
63
|
+
client = OpenAI(base_url="http://127.0.0.1:4020/v1", api_key="x402")
|
|
64
|
+
resp = client.chat.completions.create(
|
|
65
|
+
model="claude-sonnet-5-5",
|
|
66
|
+
messages=[{"role": "user", "content": "Write a minimal Rust HTTP health check."}],
|
|
67
|
+
)
|
|
68
|
+
print(resp.choices[0].message.content)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Security Model
|
|
72
|
+
|
|
73
|
+
- Binds to `127.0.0.1` by default (never exposed to LAN unless explicitly passed `--host`).
|
|
74
|
+
- `BASE_PRIVATE_KEY` never leaves your machine; only signed EIP-3009 authorizations for the exact quoted amount are sent in the `PAYMENT-SIGNATURE` header.
|
|
75
|
+
- Built-in `--max-call-usd` (default `0.05`) and `--max-session-usd` (default `2.00`) prevent unexpected spend.
|
|
76
|
+
|
|
77
|
+
## License
|
|
78
|
+
|
|
79
|
+
MIT
|
package/SKILL.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: x402-llm-proxy
|
|
3
|
+
description: Run a local OpenAI & Anthropic API proxy backed by HTTP x402 Base/Solana USDC micropayments for Claude Code, Cursor, Cline, and OpenClaw to access full-strength Claude 5.5, GPT-6.2, and Gemini 4 without a credit card.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# x402-llm-proxy Skill
|
|
7
|
+
|
|
8
|
+
Start a local OpenAI (`http://127.0.0.1:4020/v1`) and Anthropic (`http://127.0.0.1:4020`) proxy backed by full-strength Claude 5.5, GPT-6.2, and Gemini 4 via HTTP x402 USDC:
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
# Free quote & health verification
|
|
12
|
+
npx x402-llm-proxy --test
|
|
13
|
+
|
|
14
|
+
# Pay-per-call Base USDC mode
|
|
15
|
+
BASE_PRIVATE_KEY=0x... npx x402-llm-proxy --max-call-usd 0.05 --max-session-usd 2.00
|
|
16
|
+
|
|
17
|
+
# Prepaid Base/Solana USDC key mode (https://sage-x402-tools.sage-ibis.workers.dev/topup)
|
|
18
|
+
SAGE_API_KEY=sk-sage-... npx x402-llm-proxy
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Direct gateway endpoints (no proxy needed for x402-native agents):
|
|
22
|
+
- `POST https://sage-x402-tools.sage-ibis.workers.dev/v1/llm/claude-sonnet` (0.015 USDC)
|
|
23
|
+
- `POST https://sage-x402-tools.sage-ibis.workers.dev/v1/llm/claude-opus` (0.030 USDC)
|
|
24
|
+
- `POST https://sage-x402-tools.sage-ibis.workers.dev/v1/llm/gpt-flagship` (0.005 USDC)
|
|
25
|
+
- `POST https://sage-x402-tools.sage-ibis.workers.dev/v1/llm/gemini-pro` (0.006 USDC)
|
|
26
|
+
- Remote MCP: `https://sage-x402-tools.sage-ibis.workers.dev/mcp`
|
package/bin/cli.mjs
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { DEFAULT_UPSTREAM, MODEL_CATALOG } from "../src/models.mjs";
|
|
3
|
+
import { createProxyServer } from "../src/proxy.mjs";
|
|
4
|
+
|
|
5
|
+
function parseArgs(argv) {
|
|
6
|
+
const out = {};
|
|
7
|
+
for (let i = 0; i < argv.length; i++) {
|
|
8
|
+
const a = argv[i];
|
|
9
|
+
if (!a.startsWith("--")) continue;
|
|
10
|
+
const k = a.slice(2);
|
|
11
|
+
const next = argv[i + 1];
|
|
12
|
+
if (next && !next.startsWith("--")) {
|
|
13
|
+
out[k] = next;
|
|
14
|
+
i++;
|
|
15
|
+
} else {
|
|
16
|
+
out[k] = true;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function printHelp() {
|
|
23
|
+
console.log(`x402-llm-proxy — Local OpenAI & Anthropic proxy backed by HTTP x402 USDC
|
|
24
|
+
|
|
25
|
+
Usage:
|
|
26
|
+
npx x402-llm-proxy [options]
|
|
27
|
+
|
|
28
|
+
Options:
|
|
29
|
+
--port <num> Local port (default: 4020)
|
|
30
|
+
--host <addr> Bind host (default: 127.0.0.1)
|
|
31
|
+
--upstream <url> x402 gateway URL (default: ${DEFAULT_UPSTREAM})
|
|
32
|
+
--key <0x...> Base Mainnet EVM private key for x402 auto-pay (or env BASE_PRIVATE_KEY)
|
|
33
|
+
--api-key <sk-sage-...> Prepaid Base/Solana USDC API key (or env SAGE_API_KEY)
|
|
34
|
+
--max-call-usd <num> Max USDC allowed per single request (default: 0.05)
|
|
35
|
+
--max-session-usd <num> Max USDC allowed per session (default: 2.00)
|
|
36
|
+
--models Print available frontier models & prices and exit
|
|
37
|
+
--test Run a free live 402 quote check against the upstream gateway
|
|
38
|
+
--help Show this help
|
|
39
|
+
|
|
40
|
+
Examples:
|
|
41
|
+
# Pay per call with Base USDC (no credit card, no API key):
|
|
42
|
+
BASE_PRIVATE_KEY=0x... npx x402-llm-proxy
|
|
43
|
+
|
|
44
|
+
# Use a prepaid Base/Solana USDC key (true streaming + Claude Code tool use):
|
|
45
|
+
SAGE_API_KEY=sk-sage-... npx x402-llm-proxy
|
|
46
|
+
|
|
47
|
+
# Connect Claude Code:
|
|
48
|
+
ANTHROPIC_BASE_URL=http://127.0.0.1:4020 ANTHROPIC_API_KEY=x402 claude
|
|
49
|
+
|
|
50
|
+
# Connect Cursor / Cline / OpenAI SDK:
|
|
51
|
+
OPENAI_BASE_URL=http://127.0.0.1:4020/v1 OPENAI_API_KEY=x402
|
|
52
|
+
`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function printModels() {
|
|
56
|
+
console.log("\nFrontier Models (Full-Strength Passthrough — Base & Solana USDC)\n");
|
|
57
|
+
for (const m of MODEL_CATALOG) {
|
|
58
|
+
console.log(` ${m.id.padEnd(20)} $${m.priceUsd.toFixed(3)} USDC ${m.endpoint.padEnd(24)} ${m.summary}`);
|
|
59
|
+
}
|
|
60
|
+
console.log(`\nPrepaid API Key Top-Up (Base & Solana USDC): ${DEFAULT_UPSTREAM}/topup\n`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function runDryTest(upstream) {
|
|
64
|
+
const base = upstream.replace(/\/+$/, "");
|
|
65
|
+
const health = await fetch(`${base}/health`, {
|
|
66
|
+
headers: { "User-Agent": "x402-llm-proxy/1.0.0" },
|
|
67
|
+
}).then((r) => r.json());
|
|
68
|
+
const probe = await fetch(`${base}/v1/llm/claude-sonnet`, {
|
|
69
|
+
method: "POST",
|
|
70
|
+
headers: { "Content-Type": "application/json", "User-Agent": "x402-llm-proxy/1.0.0" },
|
|
71
|
+
body: JSON.stringify({ prompt: "Reply OK", max_tokens: 16 }),
|
|
72
|
+
});
|
|
73
|
+
const payHdr = probe.headers.get("payment-required");
|
|
74
|
+
const decoded = payHdr ? JSON.parse(Buffer.from(payHdr, "base64").toString("utf8")) : null;
|
|
75
|
+
console.log(
|
|
76
|
+
JSON.stringify(
|
|
77
|
+
{
|
|
78
|
+
ok: probe.status === 402 && Boolean(decoded?.accepts?.length),
|
|
79
|
+
upstream: base,
|
|
80
|
+
service: health.service,
|
|
81
|
+
version: health.version,
|
|
82
|
+
probeStatus: probe.status,
|
|
83
|
+
acceptedNetworks: (decoded?.accepts || []).map((a) => ({
|
|
84
|
+
network: a.network,
|
|
85
|
+
amountUsdc: Number(a.amount) / 1e6,
|
|
86
|
+
payTo: a.payTo,
|
|
87
|
+
})),
|
|
88
|
+
},
|
|
89
|
+
null,
|
|
90
|
+
2
|
|
91
|
+
)
|
|
92
|
+
);
|
|
93
|
+
if (probe.status !== 402) process.exit(1);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const args = parseArgs(process.argv.slice(2));
|
|
97
|
+
if (args.help) {
|
|
98
|
+
printHelp();
|
|
99
|
+
process.exit(0);
|
|
100
|
+
}
|
|
101
|
+
if (args.models) {
|
|
102
|
+
printModels();
|
|
103
|
+
process.exit(0);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const upstream = String(args.upstream || process.env.X402_UPSTREAM || DEFAULT_UPSTREAM);
|
|
107
|
+
if (args.test) {
|
|
108
|
+
await runDryTest(upstream);
|
|
109
|
+
process.exit(0);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const port = Number(args.port || process.env.PORT || 4020);
|
|
113
|
+
const host = String(args.host || "127.0.0.1");
|
|
114
|
+
const privateKey = String(args.key || process.env.BASE_PRIVATE_KEY || process.env.EVM_PRIVATE_KEY || "");
|
|
115
|
+
const apiKey = String(args["api-key"] || process.env.SAGE_API_KEY || "");
|
|
116
|
+
const maxCallUsd = Number(args["max-call-usd"] || 0.05);
|
|
117
|
+
const maxSessionUsd = Number(args["max-session-usd"] || 2.0);
|
|
118
|
+
|
|
119
|
+
const { server, mode, signer } = createProxyServer({
|
|
120
|
+
upstream,
|
|
121
|
+
privateKey,
|
|
122
|
+
apiKey,
|
|
123
|
+
maxCallUsd,
|
|
124
|
+
maxSessionUsd,
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
server.listen(port, host, () => {
|
|
128
|
+
console.log(`x402-llm-proxy listening on http://${host}:${port}`);
|
|
129
|
+
console.log(` Mode: ${mode}${signer ? ` (${signer.address})` : ""}`);
|
|
130
|
+
console.log(` Upstream: ${upstream}`);
|
|
131
|
+
if (signer) console.log(` Caps: $${maxCallUsd.toFixed(3)}/call, $${maxSessionUsd.toFixed(2)}/session`);
|
|
132
|
+
console.log(` OpenAI: http://${host}:${port}/v1`);
|
|
133
|
+
console.log(` Anthropic: http://${host}:${port}`);
|
|
134
|
+
console.log(` Health: http://${host}:${port}/health`);
|
|
135
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "x402-llm-proxy",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Local OpenAI & Anthropic API proxy for Claude Code, Cursor, Cline, and OpenClaw — pay per call in Base USDC via HTTP x402 (zero credit card) or prepaid Base/Solana USDC key for full-strength Claude 5.5, GPT-6.2, and Gemini 4.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"bin": {
|
|
8
|
+
"x402-llm-proxy": "bin/cli.mjs"
|
|
9
|
+
},
|
|
10
|
+
"main": "./src/proxy.mjs",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": "./src/proxy.mjs",
|
|
13
|
+
"./models": "./src/models.mjs",
|
|
14
|
+
"./signer": "./src/x402-signer.mjs"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"bin/",
|
|
18
|
+
"src/",
|
|
19
|
+
"SKILL.md",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"registry": "https://registry.npmjs.org/",
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"start": "node bin/cli.mjs",
|
|
29
|
+
"test": "node test/selftest.mjs"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"viem": "^2.23.0"
|
|
33
|
+
},
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=20.0.0"
|
|
36
|
+
},
|
|
37
|
+
"keywords": [
|
|
38
|
+
"x402",
|
|
39
|
+
"llm-proxy",
|
|
40
|
+
"claude-code",
|
|
41
|
+
"cursor",
|
|
42
|
+
"cline",
|
|
43
|
+
"openclaw",
|
|
44
|
+
"openai-proxy",
|
|
45
|
+
"anthropic-proxy",
|
|
46
|
+
"claude-sonnet",
|
|
47
|
+
"claude-opus",
|
|
48
|
+
"gpt",
|
|
49
|
+
"gemini",
|
|
50
|
+
"base",
|
|
51
|
+
"solana",
|
|
52
|
+
"usdc",
|
|
53
|
+
"pay-per-call",
|
|
54
|
+
"no-credit-card",
|
|
55
|
+
"ai-agents"
|
|
56
|
+
],
|
|
57
|
+
"repository": {
|
|
58
|
+
"type": "git",
|
|
59
|
+
"url": "git+https://github.com/mazhic87/x402-llm-proxy.git"
|
|
60
|
+
},
|
|
61
|
+
"homepage": "https://sage-x402-tools.sage-ibis.workers.dev",
|
|
62
|
+
"author": "mazhic87"
|
|
63
|
+
}
|
package/src/models.mjs
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
export const DEFAULT_UPSTREAM = "https://sage-x402-tools.sage-ibis.workers.dev";
|
|
2
|
+
|
|
3
|
+
export const MODEL_CATALOG = [
|
|
4
|
+
{
|
|
5
|
+
id: "claude-sonnet-5-5",
|
|
6
|
+
aliases: ["claude-sonnet", "sonnet", "claude-3-5-sonnet", "claude-3-7-sonnet", "claude-sonnet-4", "claude-sonnet-4-5"],
|
|
7
|
+
endpoint: "/v1/llm/claude-sonnet",
|
|
8
|
+
priceUsd: 0.015,
|
|
9
|
+
ownedBy: "anthropic",
|
|
10
|
+
maxOutputTokens: 1200,
|
|
11
|
+
summary: "Anthropic Claude Sonnet 5.5 flagship coding & agent model (zero-injection passthrough)",
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
id: "claude-opus-5-5",
|
|
15
|
+
aliases: ["claude-opus", "opus", "claude-3-opus", "claude-opus-4", "claude-opus-4-5"],
|
|
16
|
+
endpoint: "/v1/llm/claude-opus",
|
|
17
|
+
priceUsd: 0.03,
|
|
18
|
+
ownedBy: "anthropic",
|
|
19
|
+
maxOutputTokens: 1200,
|
|
20
|
+
summary: "Anthropic Claude Opus 5.5 apex reasoning & architecture model",
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
id: "claude-haiku-5-5",
|
|
24
|
+
aliases: ["claude-haiku", "haiku", "claude-3-5-haiku", "claude-haiku-4-5"],
|
|
25
|
+
endpoint: "/v1/llm/claude-haiku",
|
|
26
|
+
priceUsd: 0.002,
|
|
27
|
+
ownedBy: "anthropic",
|
|
28
|
+
maxOutputTokens: 1024,
|
|
29
|
+
summary: "Anthropic Claude Haiku 5.5 fast, low-cost agent loop model",
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
id: "gpt-6.2-astra",
|
|
33
|
+
aliases: ["gpt-flagship", "gpt-5", "gpt-4o", "o3", "o4-mini"],
|
|
34
|
+
endpoint: "/v1/llm/gpt-flagship",
|
|
35
|
+
priceUsd: 0.005,
|
|
36
|
+
ownedBy: "openai",
|
|
37
|
+
maxOutputTokens: 1200,
|
|
38
|
+
summary: "OpenAI GPT-6.2 Astra flagship reasoning & coding model",
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
id: "gpt-6.2-sol",
|
|
42
|
+
aliases: ["gpt-fast", "gpt-4o-mini", "gpt-5-mini", "gpt-mini"],
|
|
43
|
+
endpoint: "/v1/llm/gpt-fast",
|
|
44
|
+
priceUsd: 0.002,
|
|
45
|
+
ownedBy: "openai",
|
|
46
|
+
maxOutputTokens: 1024,
|
|
47
|
+
summary: "OpenAI GPT-6.2 Sol high-speed agent model",
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
id: "gemini-4-argon",
|
|
51
|
+
aliases: ["gemini-pro", "gemini-2.5-pro", "gemini-3-pro", "gemini-3.5-pro"],
|
|
52
|
+
endpoint: "/v1/llm/gemini-pro",
|
|
53
|
+
priceUsd: 0.006,
|
|
54
|
+
ownedBy: "google",
|
|
55
|
+
maxOutputTokens: 1200,
|
|
56
|
+
summary: "Google Gemini 4 Argon flagship reasoning & long-context model",
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
id: "gemini-3.8-flash",
|
|
60
|
+
aliases: ["gemini-flash", "gemini-2.5-flash", "gemini-3-flash"],
|
|
61
|
+
endpoint: "/v1/llm/gemini-flash",
|
|
62
|
+
priceUsd: 0.003,
|
|
63
|
+
ownedBy: "google",
|
|
64
|
+
maxOutputTokens: 1200,
|
|
65
|
+
summary: "Google Gemini 3.8 Flash low-latency multimodal model",
|
|
66
|
+
},
|
|
67
|
+
];
|
|
68
|
+
|
|
69
|
+
export function resolveModelRoute(requestedModel = "") {
|
|
70
|
+
const clean = String(requestedModel || "").trim().toLowerCase();
|
|
71
|
+
if (!clean) return MODEL_CATALOG[0];
|
|
72
|
+
for (const m of MODEL_CATALOG) {
|
|
73
|
+
if (m.id === clean || m.aliases.includes(clean)) return m;
|
|
74
|
+
}
|
|
75
|
+
if (clean.includes("opus")) return MODEL_CATALOG.find((m) => m.id === "claude-opus-5-5");
|
|
76
|
+
if (clean.includes("haiku")) return MODEL_CATALOG.find((m) => m.id === "claude-haiku-5-5");
|
|
77
|
+
if (clean.includes("claude") || clean.includes("sonnet")) return MODEL_CATALOG.find((m) => m.id === "claude-sonnet-5-5");
|
|
78
|
+
if (clean.includes("mini") || clean.includes("sol") || clean.includes("fast")) return MODEL_CATALOG.find((m) => m.id === "gpt-6.2-sol");
|
|
79
|
+
if (clean.includes("gpt") || clean.includes("astra") || clean.startsWith("o1") || clean.startsWith("o3") || clean.startsWith("o4")) {
|
|
80
|
+
return MODEL_CATALOG.find((m) => m.id === "gpt-6.2-astra");
|
|
81
|
+
}
|
|
82
|
+
if (clean.includes("flash")) return MODEL_CATALOG.find((m) => m.id === "gemini-3.8-flash");
|
|
83
|
+
if (clean.includes("gemini")) return MODEL_CATALOG.find((m) => m.id === "gemini-4-argon");
|
|
84
|
+
return MODEL_CATALOG[0];
|
|
85
|
+
}
|
package/src/proxy.mjs
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { DEFAULT_UPSTREAM, MODEL_CATALOG, resolveModelRoute } from "./models.mjs";
|
|
4
|
+
import { createX402Signer } from "./x402-signer.mjs";
|
|
5
|
+
|
|
6
|
+
function readBody(req, limitBytes = 2 * 1024 * 1024) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
const chunks = [];
|
|
9
|
+
let total = 0;
|
|
10
|
+
req.on("data", (c) => {
|
|
11
|
+
total += c.length;
|
|
12
|
+
if (total > limitBytes) {
|
|
13
|
+
reject(new Error("Request body too large"));
|
|
14
|
+
req.destroy();
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
chunks.push(c);
|
|
18
|
+
});
|
|
19
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
20
|
+
req.on("error", reject);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function writeJson(res, status, obj) {
|
|
25
|
+
const body = JSON.stringify(obj);
|
|
26
|
+
res.writeHead(status, {
|
|
27
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
28
|
+
"Access-Control-Allow-Origin": "*",
|
|
29
|
+
});
|
|
30
|
+
res.end(body);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function extractTextFromContent(content) {
|
|
34
|
+
if (typeof content === "string") return content;
|
|
35
|
+
if (Array.isArray(content)) {
|
|
36
|
+
return content
|
|
37
|
+
.map((p) => {
|
|
38
|
+
if (typeof p === "string") return p;
|
|
39
|
+
if (p?.type === "text") return p.text || "";
|
|
40
|
+
return "";
|
|
41
|
+
})
|
|
42
|
+
.filter(Boolean)
|
|
43
|
+
.join("\n");
|
|
44
|
+
}
|
|
45
|
+
return "";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function writeOpenAiSse(res, completion) {
|
|
49
|
+
const id = completion.id || `chatcmpl-${randomUUID().replace(/-/g, "").slice(0, 24)}`;
|
|
50
|
+
const created = completion.created || Math.floor(Date.now() / 1000);
|
|
51
|
+
const model = completion.model || "claude-sonnet-5-5";
|
|
52
|
+
const choice = completion.choices?.[0];
|
|
53
|
+
const content = choice?.message?.content ?? "";
|
|
54
|
+
const finishReason = choice?.finish_reason || "stop";
|
|
55
|
+
|
|
56
|
+
res.writeHead(200, {
|
|
57
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
58
|
+
"Cache-Control": "no-cache",
|
|
59
|
+
Connection: "keep-alive",
|
|
60
|
+
"Access-Control-Allow-Origin": "*",
|
|
61
|
+
});
|
|
62
|
+
res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { role: "assistant", content }, finish_reason: null }] })}\n\n`);
|
|
63
|
+
res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: {}, finish_reason: finishReason }], usage: completion.usage })}\n\n`);
|
|
64
|
+
res.write("data: [DONE]\n\n");
|
|
65
|
+
res.end();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function writeAnthropicSse(res, msg) {
|
|
69
|
+
const text = msg.content?.[0]?.text ?? "";
|
|
70
|
+
res.writeHead(200, {
|
|
71
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
72
|
+
"Cache-Control": "no-cache",
|
|
73
|
+
Connection: "keep-alive",
|
|
74
|
+
"Access-Control-Allow-Origin": "*",
|
|
75
|
+
});
|
|
76
|
+
const send = (evt, data) => res.write(`event: ${evt}\ndata: ${JSON.stringify(data)}\n\n`);
|
|
77
|
+
send("message_start", {
|
|
78
|
+
type: "message_start",
|
|
79
|
+
message: { ...msg, content: [], stop_reason: null, stop_sequence: null },
|
|
80
|
+
});
|
|
81
|
+
send("content_block_start", { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } });
|
|
82
|
+
send("content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text } });
|
|
83
|
+
send("content_block_stop", { type: "content_block_stop", index: 0 });
|
|
84
|
+
send("message_delta", {
|
|
85
|
+
type: "message_delta",
|
|
86
|
+
delta: { stop_reason: msg.stop_reason || "end_turn", stop_sequence: null },
|
|
87
|
+
usage: { output_tokens: msg.usage?.output_tokens ?? 0 },
|
|
88
|
+
});
|
|
89
|
+
send("message_stop", { type: "message_stop" });
|
|
90
|
+
res.end();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function extractIncomingSageKey(req, defaultApiKey) {
|
|
94
|
+
const auth = String(req.headers.authorization || "").trim();
|
|
95
|
+
if (auth.toLowerCase().startsWith("bearer sk-sage-")) return auth.slice(7).trim();
|
|
96
|
+
const xApiKey = String(req.headers["x-api-key"] || "").trim();
|
|
97
|
+
if (xApiKey.startsWith("sk-sage-")) return xApiKey;
|
|
98
|
+
if (defaultApiKey && defaultApiKey.startsWith("sk-sage-")) return defaultApiKey;
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function createProxyServer({
|
|
103
|
+
upstream = DEFAULT_UPSTREAM,
|
|
104
|
+
privateKey = "",
|
|
105
|
+
apiKey = "",
|
|
106
|
+
maxCallUsd = 0.05,
|
|
107
|
+
maxSessionUsd = 2.0,
|
|
108
|
+
logger = console,
|
|
109
|
+
} = {}) {
|
|
110
|
+
const cleanUpstream = upstream.replace(/\/+$/, "");
|
|
111
|
+
const signer = privateKey ? createX402Signer({ privateKey, maxCallUsd, maxSessionUsd }) : null;
|
|
112
|
+
const mode = signer ? "x402-base-usdc" : apiKey ? "prepaid-api-key" : "passthrough-only";
|
|
113
|
+
|
|
114
|
+
async function forwardPrepaid(targetUrl, rawBody, req, res, bearerKey) {
|
|
115
|
+
const headers = {
|
|
116
|
+
"Content-Type": "application/json",
|
|
117
|
+
Authorization: `Bearer ${bearerKey}`,
|
|
118
|
+
"User-Agent": "x402-llm-proxy/1.0.0 (+https://github.com/mazhic87/x402-llm-proxy)",
|
|
119
|
+
};
|
|
120
|
+
if (req.headers["anthropic-version"]) headers["anthropic-version"] = String(req.headers["anthropic-version"]);
|
|
121
|
+
if (req.headers["anthropic-beta"]) headers["anthropic-beta"] = String(req.headers["anthropic-beta"]);
|
|
122
|
+
|
|
123
|
+
const up = await fetch(targetUrl, { method: "POST", headers, body: rawBody });
|
|
124
|
+
const respHeaders = {
|
|
125
|
+
"Content-Type": up.headers.get("content-type") || "application/json; charset=utf-8",
|
|
126
|
+
"Access-Control-Allow-Origin": "*",
|
|
127
|
+
};
|
|
128
|
+
const costHdr = up.headers.get("x-sage-cost-usd");
|
|
129
|
+
const balHdr = up.headers.get("x-sage-balance-usd");
|
|
130
|
+
if (costHdr) respHeaders["X-Sage-Cost-USD"] = costHdr;
|
|
131
|
+
if (balHdr) respHeaders["X-Sage-Balance-USD"] = balHdr;
|
|
132
|
+
|
|
133
|
+
res.writeHead(up.status, respHeaders);
|
|
134
|
+
if (!up.body) {
|
|
135
|
+
res.end();
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const reader = up.body.getReader();
|
|
139
|
+
while (true) {
|
|
140
|
+
const { done, value } = await reader.read();
|
|
141
|
+
if (done) break;
|
|
142
|
+
res.write(value);
|
|
143
|
+
}
|
|
144
|
+
res.end();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const server = http.createServer(async (req, res) => {
|
|
148
|
+
try {
|
|
149
|
+
if (req.method === "OPTIONS") {
|
|
150
|
+
res.writeHead(204, {
|
|
151
|
+
"Access-Control-Allow-Origin": "*",
|
|
152
|
+
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
153
|
+
"Access-Control-Allow-Headers": "Content-Type, Authorization, x-api-key, anthropic-version, anthropic-beta",
|
|
154
|
+
});
|
|
155
|
+
res.end();
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const url = new URL(req.url || "/", "http://127.0.0.1");
|
|
160
|
+
const path = url.pathname.replace(/\/+$/, "") || "/";
|
|
161
|
+
|
|
162
|
+
if (path === "/health" && req.method === "GET") {
|
|
163
|
+
writeJson(res, 200, {
|
|
164
|
+
ok: true,
|
|
165
|
+
service: "x402-llm-proxy",
|
|
166
|
+
mode,
|
|
167
|
+
upstream: cleanUpstream,
|
|
168
|
+
x402: signer ? signer.getStats() : null,
|
|
169
|
+
models: MODEL_CATALOG.map((m) => ({ id: m.id, price_usdc: m.priceUsd, endpoint: m.endpoint })),
|
|
170
|
+
});
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (path === "/v1/models" && req.method === "GET") {
|
|
175
|
+
writeJson(res, 200, {
|
|
176
|
+
object: "list",
|
|
177
|
+
data: MODEL_CATALOG.map((m) => ({
|
|
178
|
+
id: m.id,
|
|
179
|
+
object: "model",
|
|
180
|
+
created: 1764000000,
|
|
181
|
+
owned_by: m.ownedBy,
|
|
182
|
+
x402_price_usdc: m.priceUsd,
|
|
183
|
+
x402_endpoint: `${cleanUpstream}${m.endpoint}`,
|
|
184
|
+
})),
|
|
185
|
+
});
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (path === "/v1/chat/completions" && req.method === "POST") {
|
|
190
|
+
const rawBody = await readBody(req);
|
|
191
|
+
const sageKey = extractIncomingSageKey(req, apiKey);
|
|
192
|
+
if (sageKey) {
|
|
193
|
+
await forwardPrepaid(`${cleanUpstream}/v1/chat/completions`, rawBody, req, res, sageKey);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (!signer) {
|
|
197
|
+
writeJson(res, 401, {
|
|
198
|
+
error: {
|
|
199
|
+
message: "No payment credential configured. Start x402-llm-proxy with --key (Base USDC private key) or --api-key (sk-sage-... prepaid key from " + cleanUpstream + "/topup).",
|
|
200
|
+
type: "authentication_error",
|
|
201
|
+
},
|
|
202
|
+
});
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const body = JSON.parse(rawBody || "{}");
|
|
207
|
+
const route = resolveModelRoute(body.model);
|
|
208
|
+
const payload = {
|
|
209
|
+
messages: body.messages,
|
|
210
|
+
prompt: body.prompt,
|
|
211
|
+
max_tokens: Math.min(Number(body.max_tokens || route.maxOutputTokens), route.maxOutputTokens),
|
|
212
|
+
temperature: body.temperature,
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
const { response, paid, amountUsd } = await signer.fetchPaid(`${cleanUpstream}${route.endpoint}`, {
|
|
216
|
+
method: "POST",
|
|
217
|
+
headers: { "Content-Type": "application/json" },
|
|
218
|
+
body: JSON.stringify(payload),
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
const data = await response.json().catch(() => ({ error: "Invalid upstream JSON" }));
|
|
222
|
+
if (!response.ok) {
|
|
223
|
+
writeJson(res, response.status, data);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (paid) {
|
|
228
|
+
const st = signer.getStats();
|
|
229
|
+
logger.log(`[x402 PAID] ${route.id} | $${amountUsd.toFixed(4)} Base USDC | session total: $${st.sessionSpentUsd.toFixed(4)}`);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const completion = data?.choices ? data : data?.data?.choices ? data.data : data;
|
|
233
|
+
if (body.stream) {
|
|
234
|
+
writeOpenAiSse(res, completion);
|
|
235
|
+
} else {
|
|
236
|
+
writeJson(res, 200, completion);
|
|
237
|
+
}
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (path === "/v1/messages" && req.method === "POST") {
|
|
242
|
+
const rawBody = await readBody(req);
|
|
243
|
+
const sageKey = extractIncomingSageKey(req, apiKey);
|
|
244
|
+
if (sageKey) {
|
|
245
|
+
await forwardPrepaid(`${cleanUpstream}/v1/messages`, rawBody, req, res, sageKey);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (!signer) {
|
|
249
|
+
writeJson(res, 401, {
|
|
250
|
+
type: "error",
|
|
251
|
+
error: {
|
|
252
|
+
type: "authentication_error",
|
|
253
|
+
message: "No payment credential configured. Start x402-llm-proxy with --key (Base USDC private key) or --api-key (sk-sage-... prepaid key from " + cleanUpstream + "/topup).",
|
|
254
|
+
},
|
|
255
|
+
});
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const body = JSON.parse(rawBody || "{}");
|
|
260
|
+
const route = resolveModelRoute(body.model || "claude-sonnet-5-5");
|
|
261
|
+
const messages = Array.isArray(body.messages)
|
|
262
|
+
? body.messages.map((m) => ({ role: m.role, content: extractTextFromContent(m.content) }))
|
|
263
|
+
: [];
|
|
264
|
+
const payload = {
|
|
265
|
+
system: extractTextFromContent(body.system),
|
|
266
|
+
messages,
|
|
267
|
+
max_tokens: Math.min(Number(body.max_tokens || route.maxOutputTokens), route.maxOutputTokens),
|
|
268
|
+
temperature: body.temperature,
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
const { response, paid, amountUsd } = await signer.fetchPaid(`${cleanUpstream}${route.endpoint}`, {
|
|
272
|
+
method: "POST",
|
|
273
|
+
headers: { "Content-Type": "application/json" },
|
|
274
|
+
body: JSON.stringify(payload),
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
const data = await response.json().catch(() => ({ error: "Invalid upstream JSON" }));
|
|
278
|
+
if (!response.ok) {
|
|
279
|
+
writeJson(res, response.status, {
|
|
280
|
+
type: "error",
|
|
281
|
+
error: { type: "api_error", message: data?.error?.message || data?.error || `Upstream HTTP ${response.status}` },
|
|
282
|
+
});
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
if (paid) {
|
|
287
|
+
const st = signer.getStats();
|
|
288
|
+
logger.log(`[x402 PAID] ${route.id} (Anthropic) | $${amountUsd.toFixed(4)} Base USDC | session total: $${st.sessionSpentUsd.toFixed(4)}`);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const completion = data?.choices ? data : data?.data?.choices ? data.data : data;
|
|
292
|
+
const text = completion?.choices?.[0]?.message?.content ?? "";
|
|
293
|
+
const anthropicMsg = {
|
|
294
|
+
id: `msg_${randomUUID().replace(/-/g, "").slice(0, 24)}`,
|
|
295
|
+
type: "message",
|
|
296
|
+
role: "assistant",
|
|
297
|
+
model: completion?.model || route.id,
|
|
298
|
+
content: [{ type: "text", text }],
|
|
299
|
+
stop_reason: "end_turn",
|
|
300
|
+
stop_sequence: null,
|
|
301
|
+
usage: {
|
|
302
|
+
input_tokens: completion?.usage?.prompt_tokens ?? 0,
|
|
303
|
+
output_tokens: completion?.usage?.completion_tokens ?? 0,
|
|
304
|
+
},
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
if (body.stream) {
|
|
308
|
+
writeAnthropicSse(res, anthropicMsg);
|
|
309
|
+
} else {
|
|
310
|
+
writeJson(res, 200, anthropicMsg);
|
|
311
|
+
}
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
writeJson(res, 404, { error: { message: `Unsupported route: ${req.method} ${path}`, type: "not_found" } });
|
|
316
|
+
} catch (e) {
|
|
317
|
+
logger.error(`[proxy error] ${e.message}`);
|
|
318
|
+
writeJson(res, 502, { error: { message: e.message || "Proxy error", type: "proxy_error" } });
|
|
319
|
+
}
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
return { server, mode, signer };
|
|
323
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
3
|
+
|
|
4
|
+
const BASE_CHAIN_ID = 8453;
|
|
5
|
+
const TRANSFER_WITH_AUTH_TYPES = {
|
|
6
|
+
TransferWithAuthorization: [
|
|
7
|
+
{ name: "from", type: "address" },
|
|
8
|
+
{ name: "to", type: "address" },
|
|
9
|
+
{ name: "value", type: "uint256" },
|
|
10
|
+
{ name: "validAfter", type: "uint256" },
|
|
11
|
+
{ name: "validBefore", type: "uint256" },
|
|
12
|
+
{ name: "nonce", type: "bytes32" },
|
|
13
|
+
],
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
function decodeBase64Json(b64) {
|
|
17
|
+
return JSON.parse(Buffer.from(String(b64 || "").trim(), "base64").toString("utf8"));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function encodeBase64Json(obj) {
|
|
21
|
+
return Buffer.from(JSON.stringify(obj), "utf8").toString("base64");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function createX402Signer({ privateKey, maxCallUsd = 0.05, maxSessionUsd = 2.0 }) {
|
|
25
|
+
const normalized = String(privateKey || "").trim();
|
|
26
|
+
if (!/^0x[a-fA-F0-9]{64}$/.test(normalized)) {
|
|
27
|
+
throw new Error("Invalid EVM private key: expected 66-character 0x-prefixed hex string");
|
|
28
|
+
}
|
|
29
|
+
const account = privateKeyToAccount(normalized);
|
|
30
|
+
let sessionSpentAtomic = 0n;
|
|
31
|
+
let paidCalls = 0;
|
|
32
|
+
|
|
33
|
+
async function signBaseV2Payment(paymentRequired) {
|
|
34
|
+
const accepts = Array.isArray(paymentRequired?.accepts) ? paymentRequired.accepts : [];
|
|
35
|
+
const req = accepts.find((a) => a.network === "eip155:8453" && a.scheme === "exact");
|
|
36
|
+
if (!req) {
|
|
37
|
+
throw new Error("Upstream HTTP 402 does not offer an eip155:8453 exact USDC payment option");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const amountAtomic = BigInt(req.amount);
|
|
41
|
+
const amountUsd = Number(amountAtomic) / 1e6;
|
|
42
|
+
const projectedSessionUsd = Number(sessionSpentAtomic + amountAtomic) / 1e6;
|
|
43
|
+
|
|
44
|
+
if (amountUsd > maxCallUsd) {
|
|
45
|
+
throw new Error(`Safety cap blocked payment: quote $${amountUsd.toFixed(6)} exceeds --max-call-usd $${maxCallUsd.toFixed(4)}`);
|
|
46
|
+
}
|
|
47
|
+
if (projectedSessionUsd > maxSessionUsd) {
|
|
48
|
+
throw new Error(`Session cap reached: projected $${projectedSessionUsd.toFixed(6)} exceeds --max-session-usd $${maxSessionUsd.toFixed(4)}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const nowSec = Math.floor(Date.now() / 1000);
|
|
52
|
+
const validAfter = BigInt(Math.max(0, nowSec - 600));
|
|
53
|
+
const validBefore = BigInt(nowSec + Number(req.maxTimeoutSeconds || 60));
|
|
54
|
+
const nonce = "0x" + randomBytes(32).toString("hex");
|
|
55
|
+
|
|
56
|
+
const signature = await account.signTypedData({
|
|
57
|
+
domain: {
|
|
58
|
+
name: req.extra?.name || "USD Coin",
|
|
59
|
+
version: req.extra?.version || "2",
|
|
60
|
+
chainId: BASE_CHAIN_ID,
|
|
61
|
+
verifyingContract: req.asset,
|
|
62
|
+
},
|
|
63
|
+
types: TRANSFER_WITH_AUTH_TYPES,
|
|
64
|
+
primaryType: "TransferWithAuthorization",
|
|
65
|
+
message: {
|
|
66
|
+
from: account.address,
|
|
67
|
+
to: req.payTo,
|
|
68
|
+
value: amountAtomic,
|
|
69
|
+
validAfter,
|
|
70
|
+
validBefore,
|
|
71
|
+
nonce,
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
const payload = {
|
|
76
|
+
x402Version: 2,
|
|
77
|
+
resource: paymentRequired.resource,
|
|
78
|
+
accepted: req,
|
|
79
|
+
payload: {
|
|
80
|
+
signature,
|
|
81
|
+
authorization: {
|
|
82
|
+
from: account.address,
|
|
83
|
+
to: req.payTo,
|
|
84
|
+
value: String(amountAtomic),
|
|
85
|
+
validAfter: String(validAfter),
|
|
86
|
+
validBefore: String(validBefore),
|
|
87
|
+
nonce,
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
return { headerValue: encodeBase64Json(payload), amountAtomic, amountUsd, payTo: req.payTo };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function fetchPaid(url, init = {}) {
|
|
96
|
+
const baseHeaders = {
|
|
97
|
+
"User-Agent": "x402-llm-proxy/1.0.0 (+https://github.com/mazhic87/x402-llm-proxy)",
|
|
98
|
+
...(init.headers || {}),
|
|
99
|
+
};
|
|
100
|
+
const first = await fetch(url, { ...init, headers: baseHeaders });
|
|
101
|
+
if (first.status !== 402) {
|
|
102
|
+
return { response: first, paid: false, amountUsd: 0 };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const payReqHdr = first.headers.get("payment-required");
|
|
106
|
+
if (!payReqHdr) {
|
|
107
|
+
throw new Error("Upstream returned HTTP 402 without a v2 PAYMENT-REQUIRED header");
|
|
108
|
+
}
|
|
109
|
+
const paymentRequired = decodeBase64Json(payReqHdr);
|
|
110
|
+
const signed = await signBaseV2Payment(paymentRequired);
|
|
111
|
+
|
|
112
|
+
const second = await fetch(url, {
|
|
113
|
+
...init,
|
|
114
|
+
headers: {
|
|
115
|
+
...baseHeaders,
|
|
116
|
+
"PAYMENT-SIGNATURE": signed.headerValue,
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
if (second.ok) {
|
|
121
|
+
sessionSpentAtomic += signed.amountAtomic;
|
|
122
|
+
paidCalls += 1;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
response: second,
|
|
127
|
+
paid: second.ok,
|
|
128
|
+
amountUsd: second.ok ? signed.amountUsd : 0,
|
|
129
|
+
payTo: signed.payTo,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
address: account.address,
|
|
135
|
+
signBaseV2Payment,
|
|
136
|
+
fetchPaid,
|
|
137
|
+
getStats() {
|
|
138
|
+
return {
|
|
139
|
+
wallet: account.address,
|
|
140
|
+
paidCalls,
|
|
141
|
+
sessionSpentUsd: Number((Number(sessionSpentAtomic) / 1e6).toFixed(6)),
|
|
142
|
+
maxCallUsd,
|
|
143
|
+
maxSessionUsd,
|
|
144
|
+
};
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|