@beggar-bot/x402-client 0.0.0-stage → 0.1.1

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/README.md CHANGED
@@ -1,3 +1,18 @@
1
- # Temporary Holding Version
1
+ # @beggar-bot/x402-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Source: [https://github.com/beggar-bot-x402/beggar-bot-connectors/tree/main/packages/x402-client](https://github.com/beggar-bot-x402/beggar-bot-connectors/tree/main/packages/x402-client)
4
+
5
+ Core client for Beggar Bot's pay-per-call APIs. A request that returns HTTP 402 is signed with the **buyer's** wallet (EIP-3009 `transferWithAuthorization` for USDC on Base) and retried with `PAYMENT-SIGNATURE` (x402 v2) or `X-PAYMENT` (v1).
6
+
7
+ Default price is $0.02 USDC per call. The client will refuse to sign if the 402 asks for more than the configured cap (default $0.02).
8
+
9
+ ```js
10
+ import { paidGet, privateKeySigner } from "@beggar-bot/x402-client";
11
+
12
+ const signer = privateKeySigner(process.env.BUYER_PRIVATE_KEY);
13
+ const { data, payment } = await paidGet("/v1/wallet-portfolio", { address: "0x…" }, { signer });
14
+ ```
15
+
16
+ `payment.transaction` is the settlement hash when the server returns a `PAYMENT-RESPONSE` header.
17
+
18
+ A viem account can be used directly if it has `address` and `signTypedData`.
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@beggar-bot/x402-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "x402 client for Beggar Bot: $0.02 USDC per call on Base, signed by the buyer's wallet.",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js"
9
+ },
10
+ "files": [
11
+ "src"
12
+ ],
13
+ "keywords": [
14
+ "x402",
15
+ "usdc",
16
+ "base",
17
+ "mcp",
18
+ "agents"
19
+ ],
20
+ "license": "MIT",
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "peerDependencies": {
25
+ "viem": ">=2"
26
+ },
27
+ "peerDependenciesMeta": {
28
+ "viem": {
29
+ "optional": true
30
+ }
31
+ },
32
+ "author": {
33
+ "name": "Beggar Bot",
34
+ "email": "beggarbot@mail.grokbot.com"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/beggar-bot-x402/beggar-bot-connectors.git",
42
+ "directory": "packages/x402-client"
43
+ },
44
+ "homepage": "https://github.com/beggar-bot-x402/beggar-bot-connectors/tree/main/packages/x402-client#readme",
45
+ "bugs": {
46
+ "url": "https://github.com/beggar-bot-x402/beggar-bot-connectors/issues"
47
+ }
48
+ }
package/src/catalog.js ADDED
@@ -0,0 +1,104 @@
1
+ /** Curated routes used by the framework wrappers. Any of the 600+ routes can still be called via paidGet/paidRequest. */
2
+ export const DEFAULT_BASE_URL = "https://beggar-bot-demand.beggarbot.workers.dev";
3
+ export const DEFAULT_PRICE_USD = 0.02;
4
+ export const BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
5
+
6
+ export const CATALOG = [
7
+ {
8
+ name: "token_price",
9
+ path: "/v1/token-price",
10
+ method: "GET",
11
+ description:
12
+ "Token price in USD on Base or another supported chain. $0.02 USDC via x402. Pass token (symbol or contract) and optional chain.",
13
+ params: {
14
+ token: { type: "string", required: true, description: "Token symbol or contract address, e.g. ETH or 0x…" },
15
+ chain: { type: "string", required: false, description: "Chain id or name, default base" },
16
+ },
17
+ },
18
+ {
19
+ name: "wallet_portfolio",
20
+ path: "/v1/wallet-portfolio",
21
+ method: "GET",
22
+ description:
23
+ "Wallet portfolio: native and token balances for an address. $0.02 USDC via x402. Pass address and optional chain.",
24
+ params: {
25
+ address: { type: "string", required: true, description: "0x wallet address" },
26
+ chain: { type: "string", required: false, description: "Chain id or name, default base" },
27
+ tokens: { type: "string", required: false, description: "Optional comma-separated token list" },
28
+ },
29
+ },
30
+ {
31
+ name: "gas_fee",
32
+ path: "/v1/gas-fee",
33
+ method: "GET",
34
+ description:
35
+ "Current gas fee and USD cost estimates for a transfer, USDC payment, swap or approve. $0.02 USDC via x402.",
36
+ params: {
37
+ chain: { type: "string", required: false, description: "Chain, default base" },
38
+ gas_limit: { type: "string", required: false, description: "Optional gas limit" },
39
+ },
40
+ },
41
+ {
42
+ name: "ens_resolve",
43
+ path: "/v1/ens",
44
+ method: "GET",
45
+ description:
46
+ "ENS resolve / lookup: .eth name to address (and records), with spoofing flags. $0.02 USDC via x402.",
47
+ params: {
48
+ name: { type: "string", required: true, description: "ENS name, e.g. vitalik.eth" },
49
+ },
50
+ },
51
+ {
52
+ name: "fetch_page",
53
+ path: "/v1/fetch",
54
+ method: "GET",
55
+ description:
56
+ "Fetch a public URL and return clean markdown (title, links, word count). SSRF-safe. $0.02 USDC via x402.",
57
+ params: {
58
+ url: { type: "string", required: true, description: "Public https URL to fetch" },
59
+ },
60
+ },
61
+ {
62
+ name: "crypto_news",
63
+ path: "/v1/crypto-news",
64
+ method: "GET",
65
+ description:
66
+ "Latest crypto headlines from major outlets, merged and deduped. $0.02 USDC via x402.",
67
+ params: {
68
+ q: { type: "string", required: false, description: "Optional keyword or ticker filter, e.g. BTC" },
69
+ hours: { type: "string", required: false, description: "Optional time window in hours" },
70
+ limit: { type: "string", required: false, description: "Optional max headlines" },
71
+ },
72
+ },
73
+ {
74
+ name: "token_info",
75
+ path: "/v1/token-info",
76
+ method: "GET",
77
+ description: "Token metadata and basic checks for a symbol or contract. $0.02 USDC via x402.",
78
+ params: {
79
+ token: { type: "string", required: true, description: "Token symbol or contract address" },
80
+ chain: { type: "string", required: false, description: "Chain, default base" },
81
+ },
82
+ },
83
+ {
84
+ name: "perp_funding",
85
+ path: "/v1/perpfunding",
86
+ method: "GET",
87
+ description: "Perpetual futures funding rates. $0.02 USDC via x402.",
88
+ params: {
89
+ coins: { type: "string", required: false, description: "Optional comma-separated symbols, e.g. BTC,ETH" },
90
+ sort: { type: "string", required: false, description: "Optional sort key" },
91
+ limit: { type: "string", required: false, description: "Optional max rows" },
92
+ },
93
+ },
94
+ ];
95
+
96
+ export function jsonSchemaFor(entry) {
97
+ const properties = {};
98
+ const required = [];
99
+ for (const [name, spec] of Object.entries(entry.params || {})) {
100
+ properties[name] = { type: spec.type || "string", description: spec.description };
101
+ if (spec.required) required.push(name);
102
+ }
103
+ return { type: "object", properties, required, additionalProperties: false };
104
+ }
package/src/index.js ADDED
@@ -0,0 +1,298 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { CATALOG, DEFAULT_BASE_URL, DEFAULT_PRICE_USD, BASE_USDC, jsonSchemaFor } from "./catalog.js";
3
+
4
+ export { CATALOG, DEFAULT_BASE_URL, DEFAULT_PRICE_USD, BASE_USDC, jsonSchemaFor };
5
+
6
+ const TRANSFER_TYPES = {
7
+ EIP712Domain: [
8
+ { name: "name", type: "string" },
9
+ { name: "version", type: "string" },
10
+ { name: "chainId", type: "uint256" },
11
+ { name: "verifyingContract", type: "address" },
12
+ ],
13
+ TransferWithAuthorization: [
14
+ { name: "from", type: "address" },
15
+ { name: "to", type: "address" },
16
+ { name: "value", type: "uint256" },
17
+ { name: "validAfter", type: "uint256" },
18
+ { name: "validBefore", type: "uint256" },
19
+ { name: "nonce", type: "bytes32" },
20
+ ],
21
+ };
22
+
23
+ export class X402Error extends Error {
24
+ constructor(message, extra = {}) {
25
+ super(message);
26
+ this.name = "X402Error";
27
+ Object.assign(this, extra);
28
+ }
29
+ }
30
+
31
+ export function privateKeySigner(privateKey, signTypedData) {
32
+ if (!privateKey || typeof privateKey !== "string") {
33
+ throw new X402Error("privateKeySigner needs the buyer's 0x private key, or pass a signer object instead");
34
+ }
35
+ if (typeof signTypedData !== "function") {
36
+ throw new X402Error(
37
+ "privateKeySigner(key, signTypedData) needs a signTypedData function (for example a viem Account.signTypedData bound to that account). Prefer passing a viem Account as { signer } so the key never enters this package.",
38
+ );
39
+ }
40
+ // This helper deliberately does not derive the address or hold the key.
41
+ // Callers should use a viem/CDP account: { address, signTypedData }.
42
+ throw new X402Error(
43
+ "Use a signer object { address, signTypedData } from viem or your wallet. This package will not load a raw private key itself.",
44
+ );
45
+ }
46
+
47
+ export function asSigner(signer) {
48
+ if (!signer || typeof signer.signTypedData !== "function" || !signer.address) {
49
+ throw new X402Error("signer must have address and signTypedData(typedData)");
50
+ }
51
+ return signer;
52
+ }
53
+
54
+ function headerMap(headers) {
55
+ const out = {};
56
+ if (!headers) return out;
57
+ if (typeof headers.forEach === "function") {
58
+ headers.forEach((v, k) => {
59
+ out[String(k).toLowerCase()] = v;
60
+ });
61
+ } else {
62
+ for (const [k, v] of Object.entries(headers)) out[String(k).toLowerCase()] = v;
63
+ }
64
+ return out;
65
+ }
66
+
67
+ export function b64encodeJson(obj) {
68
+ return Buffer.from(JSON.stringify(obj), "utf8").toString("base64");
69
+ }
70
+
71
+ export function b64decodeJson(s) {
72
+ const pad = s + "=".repeat((4 - (s.length % 4)) % 4);
73
+ return JSON.parse(Buffer.from(pad, "base64").toString("utf8"));
74
+ }
75
+
76
+ export function chainIdOf(network) {
77
+ const n = String(network || "");
78
+ if (n.startsWith("eip155:")) return Number(n.split(":")[1]);
79
+ if (n === "base" || n === "base-mainnet") return 8453;
80
+ throw new X402Error(`unsupported x402 network ${network}`);
81
+ }
82
+
83
+ export function pickAccept(paymentRequired) {
84
+ const accepts = paymentRequired?.accepts || [];
85
+ if (!accepts.length) throw new X402Error("402 had no accepts[]");
86
+ return accepts[0];
87
+ }
88
+
89
+ export function assertPrice(accept, maxUsd = DEFAULT_PRICE_USD) {
90
+ const amount = String(accept.amount ?? accept.maxAmountRequired ?? "");
91
+ if (!/^\d+$/.test(amount)) throw new X402Error(`bad x402 amount ${amount}`);
92
+ const atomic = BigInt(amount);
93
+ const usd = Number(atomic) / 1e6;
94
+ const network = accept.network || "";
95
+ const asset = String(accept.asset || "").toLowerCase();
96
+ if (usd - maxUsd > 1e-12) {
97
+ throw new X402Error(`x402 price $${usd} exceeds cap $${maxUsd}`, { usd, atomic: amount, accept });
98
+ }
99
+ if (!["eip155:8453", "base", "base-mainnet"].includes(network)) {
100
+ throw new X402Error(`x402 network ${network} is not Base`, { accept });
101
+ }
102
+ if (asset && asset !== BASE_USDC.toLowerCase()) {
103
+ throw new X402Error(`x402 asset ${accept.asset} is not Base USDC`, { accept });
104
+ }
105
+ return { atomic: amount, usd, network, asset: accept.asset, payTo: accept.payTo || accept.pay_to };
106
+ }
107
+
108
+ export async function signExact(accept, signer, { now = Math.floor(Date.now() / 1000) } = {}) {
109
+ const s = asSigner(signer);
110
+ const extra = accept.extra || {};
111
+ const { atomic, payTo } = assertPrice(accept, accept._maxUsd ?? DEFAULT_PRICE_USD);
112
+ const timeout = Number(accept.maxTimeoutSeconds || accept.max_timeout_seconds || 120);
113
+ const validBefore = now + Math.max(timeout - 30, 60);
114
+ const nonce = "0x" + randomBytes(32).toString("hex");
115
+ const message = {
116
+ from: s.address,
117
+ to: payTo,
118
+ value: BigInt(atomic),
119
+ validAfter: 0n,
120
+ validBefore: BigInt(validBefore),
121
+ nonce,
122
+ };
123
+ const domain = {
124
+ name: extra.name || "USD Coin",
125
+ version: String(extra.version || "2"),
126
+ chainId: chainIdOf(accept.network),
127
+ verifyingContract: accept.asset,
128
+ };
129
+ const typed = {
130
+ types: { TransferWithAuthorization: TRANSFER_TYPES.TransferWithAuthorization },
131
+ primaryType: "TransferWithAuthorization",
132
+ domain,
133
+ message,
134
+ };
135
+ const signature = await s.signTypedData(typed);
136
+ return {
137
+ inner: {
138
+ authorization: {
139
+ from: s.address,
140
+ to: payTo,
141
+ value: String(atomic),
142
+ validAfter: "0",
143
+ validBefore: String(validBefore),
144
+ nonce,
145
+ },
146
+ signature,
147
+ },
148
+ accept,
149
+ atomic,
150
+ payTo,
151
+ };
152
+ }
153
+
154
+ export function paymentHeaders(inner, accept, paymentRequired, version) {
155
+ if (version === 2) {
156
+ const payload = { x402Version: 2, payload: inner, accepted: accept };
157
+ if (paymentRequired && typeof paymentRequired.resource === "object" && paymentRequired.resource) {
158
+ payload.resource = paymentRequired.resource;
159
+ if (paymentRequired.extensions) payload.extensions = paymentRequired.extensions;
160
+ }
161
+ return { "PAYMENT-SIGNATURE": b64encodeJson(payload), "x402-version": "2" };
162
+ }
163
+ const net = accept.network;
164
+ const netV1 = ["eip155:8453", "base", "base-mainnet"].includes(net) ? "base" : net;
165
+ const payload = { x402Version: 1, scheme: accept.scheme || "exact", network: netV1, payload: inner };
166
+ return { "X-PAYMENT": b64encodeJson(payload) };
167
+ }
168
+
169
+ export async function parse402(res) {
170
+ const headers = headerMap(res.headers);
171
+ let v2 = null;
172
+ if (headers["payment-required"]) {
173
+ try {
174
+ v2 = b64decodeJson(headers["payment-required"]);
175
+ } catch (err) {
176
+ throw new X402Error(`PAYMENT-REQUIRED decode failed: ${err.message}`);
177
+ }
178
+ }
179
+ let v1 = null;
180
+ try {
181
+ v1 = await res.clone().json();
182
+ } catch {
183
+ v1 = null;
184
+ }
185
+ const paymentRequired = v2?.accepts ? v2 : v1;
186
+ if (!paymentRequired) throw new X402Error("could not parse 402 payment requirements");
187
+ const version = v2?.accepts ? 2 : 1;
188
+ return { paymentRequired, version, body: v1 };
189
+ }
190
+
191
+ export function decodePaymentResponse(headers) {
192
+ const h = headerMap(headers);
193
+ const raw = h["payment-response"] || h["x-payment-response"];
194
+ if (!raw) return null;
195
+ try {
196
+ return b64decodeJson(raw);
197
+ } catch {
198
+ return { _raw: String(raw).slice(0, 200), _decode_error: true };
199
+ }
200
+ }
201
+
202
+ export function resolveUrl(pathOrUrl, { baseUrl = DEFAULT_BASE_URL, query } = {}) {
203
+ const base = baseUrl.replace(/\/$/, "");
204
+ const url = /^https?:\/\//i.test(pathOrUrl) ? pathOrUrl : `${base}${pathOrUrl.startsWith("/") ? "" : "/"}${pathOrUrl}`;
205
+ const u = new URL(url);
206
+ if (query) {
207
+ for (const [k, v] of Object.entries(query)) {
208
+ if (v !== undefined && v !== null && v !== "") u.searchParams.set(k, String(v));
209
+ }
210
+ }
211
+ return u.toString();
212
+ }
213
+
214
+ async function doFetch(url, { method = "GET", headers, body, fetchImpl = globalThis.fetch, timeout = 45_000 } = {}) {
215
+ if (typeof fetchImpl !== "function") throw new X402Error("fetch is not available");
216
+ const ctl = new AbortController();
217
+ const t = setTimeout(() => ctl.abort(), timeout);
218
+ try {
219
+ return await fetchImpl(url, { method, headers, body, signal: ctl.signal });
220
+ } finally {
221
+ clearTimeout(t);
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Call a Beggar Bot (or any x402) URL, paying from the buyer's signer if a 402 is returned.
227
+ */
228
+ export async function paidRequest(pathOrUrl, options = {}) {
229
+ const {
230
+ method = "GET",
231
+ query,
232
+ body,
233
+ signer,
234
+ baseUrl = DEFAULT_BASE_URL,
235
+ maxUsd = DEFAULT_PRICE_USD,
236
+ fetchImpl = globalThis.fetch,
237
+ headers: extraHeaders,
238
+ timeout,
239
+ } = options;
240
+ const s = asSigner(signer);
241
+ const url = resolveUrl(pathOrUrl, { baseUrl, query });
242
+ const headers = { accept: "application/json", "user-agent": "beggar-bot-x402-client/0.1.0", ...(extraHeaders || {}) };
243
+ let encodedBody;
244
+ if (body !== undefined && method !== "GET" && method !== "HEAD") {
245
+ encodedBody = typeof body === "string" || body instanceof Uint8Array ? body : JSON.stringify(body);
246
+ if (!headers["content-type"]) headers["content-type"] = "application/json";
247
+ }
248
+ const first = await doFetch(url, { method, headers, body: encodedBody, fetchImpl, timeout });
249
+ if (first.status !== 402) {
250
+ return packResult(first, null);
251
+ }
252
+ const { paymentRequired, version } = await parse402(first);
253
+ const accept = pickAccept(paymentRequired);
254
+ accept._maxUsd = maxUsd;
255
+ const { inner } = await signExact(accept, s);
256
+ const payHeaders = { ...headers, ...paymentHeaders(inner, accept, paymentRequired, version) };
257
+ const second = await doFetch(url, { method, headers: payHeaders, body: encodedBody, fetchImpl, timeout });
258
+ const payment = decodePaymentResponse(second.headers);
259
+ if (second.status === 402) {
260
+ throw new X402Error(`payment was rejected (still 402)`, { payment, status: second.status });
261
+ }
262
+ return packResult(second, payment);
263
+ }
264
+
265
+ async function packResult(res, payment) {
266
+ const text = await res.text();
267
+ let data = text;
268
+ try {
269
+ data = text ? JSON.parse(text) : null;
270
+ } catch {
271
+ data = text;
272
+ }
273
+ return { ok: res.status >= 200 && res.status < 300, status: res.status, data, payment, headers: headerMap(res.headers) };
274
+ }
275
+
276
+ export async function paidGet(pathOrUrl, query, options = {}) {
277
+ return paidRequest(pathOrUrl, { ...options, method: "GET", query });
278
+ }
279
+
280
+ export async function paidPost(pathOrUrl, body, options = {}) {
281
+ return paidRequest(pathOrUrl, { ...options, method: "POST", body, query: options.query });
282
+ }
283
+
284
+ export async function callCatalog(name, args, options = {}) {
285
+ const entry = CATALOG.find((e) => e.name === name);
286
+ if (!entry) throw new X402Error(`unknown catalog tool ${name}`);
287
+ for (const [k, spec] of Object.entries(entry.params || {})) {
288
+ if (spec.required && (args?.[k] === undefined || args?.[k] === "")) {
289
+ throw new X402Error(`${name} requires ${k}`);
290
+ }
291
+ }
292
+ return paidRequest(entry.path, { ...options, method: entry.method, query: args });
293
+ }
294
+
295
+ // Keep crypto import used so tree/tests can hash payloads if needed.
296
+ export function sha256Json(obj) {
297
+ return createHash("sha256").update(JSON.stringify(obj)).digest("hex");
298
+ }