@auteng/agent-utils 0.3.0 → 0.4.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @auteng/agent-utils
2
2
 
3
- Give your AI agent its own crypto wallets. Create purpose-specific wallets funded with USDC on Base, then let the agent spend autonomously on x402-enabled services like sandboxed compute. No accounts, no KYC — just wallet addresses and USDC.
3
+ Utility belt for autonomous AI agents. Create crypto wallets, discover and pay for x402-enabled services, and run sandboxed compute all with USDC on Base. No accounts, no KYC — just wallet addresses and USDC.
4
4
 
5
5
  ## Install
6
6
 
@@ -11,22 +11,61 @@ npm install @auteng/agent-utils
11
11
  ## Quick Start
12
12
 
13
13
  ```typescript
14
- import { wallet, compute } from '@auteng/agent-utils';
14
+ import { wallet, x402, compute } from '@auteng/agent-utils';
15
+
16
+ // Probe any URL to check if it's x402-enabled
17
+ const info = await x402.probe('https://api.example.com/generate');
18
+ console.log(info.price); // "$0.05 USDC on Base"
15
19
 
16
- // 1. Create a wallet for this task
20
+ // Create a wallet and pay for it
17
21
  const w = await wallet.create({ name: "my-task" });
18
- console.log(`Fund me: send USDC on Base to ${w.address}`);
22
+ const res = await w.fetch('https://api.example.com/generate', {
23
+ method: 'POST',
24
+ body: JSON.stringify({ prompt: 'hello' }),
25
+ });
26
+ ```
19
27
 
20
- // 2. Wait for funding
21
- await w.waitForFunding(5_000000n); // wait for $5 USDC
28
+ ## x402 Discover & Inspect Services
22
29
 
23
- // 3. Run sandboxed code (payment handled automatically)
24
- const result = await compute.run({
25
- code: 'print("hello from the sandbox")',
26
- stack: 'python',
27
- wallet: w,
28
- });
29
- console.log(result.stdout);
30
+ Standalone functions for working with x402 services. No wallet needed.
31
+
32
+ ### Probe a URL
33
+
34
+ Check if a URL is x402-enabled and see what it costs:
35
+
36
+ ```typescript
37
+ import { x402 } from '@auteng/agent-utils';
38
+
39
+ const info = await x402.probe('https://api.example.com/generate');
40
+ if (info.enabled) {
41
+ console.log(info.price); // "$0.05 USDC on Base"
42
+ console.log(info.paymentRequired.accepts[0]); // full payment details
43
+ console.log(info.paymentRequired.resource); // what you're paying for
44
+ }
45
+ ```
46
+
47
+ ### Discover services
48
+
49
+ Browse the [Bazaar](https://www.x402.org/) registry to find x402 services:
50
+
51
+ ```typescript
52
+ const { services, total } = await x402.discover({ limit: 10 });
53
+ for (const svc of services) {
54
+ console.log(`${svc.description} — ${svc.price}`);
55
+ console.log(` ${svc.url}`);
56
+ }
57
+ ```
58
+
59
+ ### Format prices
60
+
61
+ Convert raw x402 amounts to human-readable strings:
62
+
63
+ ```typescript
64
+ x402.formatPrice("2000", "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "eip155:8453");
65
+ // → "$0.002 USDC on Base"
66
+
67
+ x402.formatPrice("2000", "0x833589f...", "eip155:8453", { short: true });
68
+ // → "$0.002 USDC"
30
69
  ```
31
70
 
32
71
  ## Wallets
@@ -38,7 +77,6 @@ import { wallet } from '@auteng/agent-utils';
38
77
 
39
78
  const monthly = await wallet.create({ name: "feb-2026" });
40
79
  const task = await wallet.create({ name: "data-pipeline" });
41
- const dev = await wallet.create({ name: "testnet", network: "base-sepolia" });
42
80
  ```
43
81
 
44
82
  Wallets are persisted at `.auteng/wallets/<name>.json`. Creating a wallet that already exists loads it from disk.
@@ -58,15 +96,15 @@ await monthly.waitForFunding(10_000000n);
58
96
  // Polls Base every 10s until >= $10 USDC is available
59
97
  ```
60
98
 
61
- ### x402 fetch
99
+ ### Pay any x402 service
62
100
 
63
101
  Drop-in `fetch()` replacement that handles x402 payments automatically:
64
102
 
65
103
  ```typescript
66
- const res = await monthly.fetch('https://x402.auteng.ai/api/x402/compute', {
104
+ const res = await monthly.fetch('https://any-x402-service.com/api', {
67
105
  method: 'POST',
68
106
  headers: { 'Content-Type': 'application/json' },
69
- body: JSON.stringify({ code: 'print("hi")', stack: 'python', size: 'small' }),
107
+ body: JSON.stringify({ prompt: 'hello' }),
70
108
  });
71
109
  ```
72
110
 
@@ -84,9 +122,9 @@ for (const w of all) {
84
122
  }
85
123
  ```
86
124
 
87
- ## Compute
125
+ ## Compute (AutEng)
88
126
 
89
- Run sandboxed code via AutEng's x402 compute endpoint. Pass a wallet to pay for execution:
127
+ Convenience wrapper for AutEng's x402 sandboxed compute service:
90
128
 
91
129
  ```typescript
92
130
  import { wallet, compute } from '@auteng/agent-utils';
@@ -116,7 +154,7 @@ compute.pricing(); // returns full pricing table
116
154
 
117
155
  ## Demo
118
156
 
119
- Run the included demo to see everything in action — wallet creation, funding, and autonomous compute:
157
+ Run the included demo to see wallet creation, funding, and compute in action:
120
158
 
121
159
  ```bash
122
160
  node demo.mjs
@@ -137,11 +175,6 @@ node demo.mjs
137
175
  Balance: $0.0000
138
176
  ────────────────────────────────────────────────────────
139
177
 
140
- This wallet needs at least $1.0000 USDC to run the demo.
141
-
142
- Please send USDC on **Base** to:
143
- 0x9cc8...e18
144
-
145
178
  Waiting for funds...
146
179
  Funded! New balance: $1.0000
147
180
  ────────────────────────────────────────────────────────
@@ -149,32 +182,20 @@ node demo.mjs
149
182
  Running compute jobs...
150
183
 
151
184
  ▸ Python — Fibonacci
152
- fib(10) = 55
153
- fib(20) = 6765
154
- fib(30) = 832040
155
- fib(40) = 102334155
156
185
  fib(50) = 12586269025
157
186
 
158
187
  ▸ Python — System info
159
- Python 3.12.12
160
- OS: Linux 6.1.158
161
- Arch: x86_64
162
- CPUs: 2
188
+ Python 3.12.12, Linux 6.1.158, x86_64, 2 CPUs
163
189
 
164
190
  ▸ Node — UUID generation
165
191
  f8b260ec-2dea-401b-b807-544f366a8588
166
- 8eb115bb-e943-455b-b675-a177ed2c5e81
167
192
  ...
168
193
 
169
- Starting balance: $1.0000
170
- Final balance: $0.9980
171
- Spent: $0.0020
194
+ Spent: $0.0020
172
195
  ────────────────────────────────────────────────────────
173
196
  Done!
174
197
  ```
175
198
 
176
- The demo creates a wallet, waits for you to fund it with $1 USDC on Base, then runs three sandboxed compute jobs (Python + Node) — all paid automatically via x402. Total cost: ~$0.002.
177
-
178
199
  ## Development
179
200
 
180
201
  ```bash
package/dist/index.d.mts CHANGED
@@ -114,4 +114,120 @@ declare const compute: {
114
114
  setEndpoint(url: string): void;
115
115
  };
116
116
 
117
- export { type ComputeRequest, type ComputeResponse, type CreateWalletOptions, type Network, type PricingTier, type Size, type Stack, type WaitForFundingOptions, Wallet, type WalletConfig, compute, wallet };
117
+ /** A single accepted payment option from a 402 response. */
118
+ interface PaymentOption {
119
+ scheme: string;
120
+ network: string;
121
+ asset: string;
122
+ /** Raw amount in minor units (e.g. "2000" = $0.002 USDC). */
123
+ amount: string;
124
+ payTo: string;
125
+ maxTimeoutSeconds: number;
126
+ extra?: Record<string, unknown>;
127
+ }
128
+ /** Normalized 402 response (works across v1 and v2). */
129
+ interface PaymentRequiredResponse {
130
+ x402Version: number;
131
+ resource: {
132
+ url: string;
133
+ description?: string;
134
+ mimeType?: string;
135
+ };
136
+ accepts: PaymentOption[];
137
+ extensions?: Record<string, unknown>;
138
+ }
139
+ /** Result of probing a URL for x402 payment requirements. */
140
+ interface ProbeResult {
141
+ /** Whether the URL returned 402 Payment Required. */
142
+ enabled: boolean;
143
+ /** The URL that was probed. */
144
+ url: string;
145
+ /** HTTP status code returned. */
146
+ status: number;
147
+ /** Human-readable price summary, e.g. "$0.002 USDC on Base". Null if not x402. */
148
+ price: string | null;
149
+ /** The parsed 402 response body. Null if not x402. */
150
+ paymentRequired: PaymentRequiredResponse | null;
151
+ }
152
+ interface ProbeOptions {
153
+ /** HTTP method to use. Default: "GET". */
154
+ method?: string;
155
+ /** Request headers to include. */
156
+ headers?: Record<string, string>;
157
+ /** Request body (for POST endpoints). */
158
+ body?: string;
159
+ /** Abort signal for timeout control. */
160
+ signal?: AbortSignal;
161
+ }
162
+ /** A service listed in the Bazaar registry. */
163
+ interface BazaarService {
164
+ /** The service endpoint URL. */
165
+ url: string;
166
+ /** Service description. */
167
+ description: string | null;
168
+ /** Human-readable price of the cheapest accept option. */
169
+ price: string;
170
+ /** All accepted payment options. */
171
+ accepts: PaymentOption[];
172
+ /** Raw metadata from the Bazaar. */
173
+ metadata: Record<string, unknown>;
174
+ }
175
+ interface DiscoverResult {
176
+ services: BazaarService[];
177
+ total: number;
178
+ }
179
+ interface DiscoverOptions {
180
+ /** Max results to return. Default: 20. */
181
+ limit?: number;
182
+ /** Pagination offset. Default: 0. */
183
+ offset?: number;
184
+ /** Bazaar API base URL. Override for testing. */
185
+ bazaarUrl?: string;
186
+ /** Abort signal for timeout control. */
187
+ signal?: AbortSignal;
188
+ }
189
+ interface FormatPriceOptions {
190
+ /** If true, omit the network suffix (e.g. "$0.002 USDC" instead of "$0.002 USDC on Base"). */
191
+ short?: boolean;
192
+ }
193
+
194
+ /**
195
+ * Check if a URL is x402-enabled and see what it costs, without paying.
196
+ *
197
+ * Sends a request to the URL. If the server returns 402 Payment Required,
198
+ * parses the payment requirements and returns a structured result with
199
+ * human-readable pricing. Non-402 responses return `{ enabled: false }`.
200
+ *
201
+ * No wallet needed — this is a read-only inspection.
202
+ */
203
+ declare function probe(url: string, options?: ProbeOptions): Promise<ProbeResult>;
204
+
205
+ /**
206
+ * Query the Bazaar registry to find available x402 services.
207
+ *
208
+ * Fetches from the Coinbase CDP Bazaar discovery endpoint and returns
209
+ * a normalized list of services with human-readable pricing.
210
+ *
211
+ * No wallet or authentication needed.
212
+ */
213
+ declare function discover(options?: DiscoverOptions): Promise<DiscoverResult>;
214
+
215
+ /**
216
+ * Format a raw x402 price into a human-readable string.
217
+ *
218
+ * Knows about common assets (USDC on Base = 6 decimals, $-prefixed)
219
+ * and falls back to raw display for unknown assets.
220
+ *
221
+ * @example
222
+ * formatPrice("2000", "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "eip155:8453")
223
+ * // → "$0.002 USDC on Base"
224
+ */
225
+ declare function formatPrice(amount: string, asset: string, network: string, options?: FormatPriceOptions): string;
226
+
227
+ declare const x402: {
228
+ probe: typeof probe;
229
+ discover: typeof discover;
230
+ formatPrice: typeof formatPrice;
231
+ };
232
+
233
+ export { type BazaarService, type ComputeRequest, type ComputeResponse, type CreateWalletOptions, type DiscoverOptions, type DiscoverResult, type FormatPriceOptions, type Network, type PaymentOption, type PaymentRequiredResponse, type PricingTier, type ProbeOptions, type ProbeResult, type Size, type Stack, type WaitForFundingOptions, Wallet, type WalletConfig, compute, wallet, x402 };
package/dist/index.d.ts CHANGED
@@ -114,4 +114,120 @@ declare const compute: {
114
114
  setEndpoint(url: string): void;
115
115
  };
116
116
 
117
- export { type ComputeRequest, type ComputeResponse, type CreateWalletOptions, type Network, type PricingTier, type Size, type Stack, type WaitForFundingOptions, Wallet, type WalletConfig, compute, wallet };
117
+ /** A single accepted payment option from a 402 response. */
118
+ interface PaymentOption {
119
+ scheme: string;
120
+ network: string;
121
+ asset: string;
122
+ /** Raw amount in minor units (e.g. "2000" = $0.002 USDC). */
123
+ amount: string;
124
+ payTo: string;
125
+ maxTimeoutSeconds: number;
126
+ extra?: Record<string, unknown>;
127
+ }
128
+ /** Normalized 402 response (works across v1 and v2). */
129
+ interface PaymentRequiredResponse {
130
+ x402Version: number;
131
+ resource: {
132
+ url: string;
133
+ description?: string;
134
+ mimeType?: string;
135
+ };
136
+ accepts: PaymentOption[];
137
+ extensions?: Record<string, unknown>;
138
+ }
139
+ /** Result of probing a URL for x402 payment requirements. */
140
+ interface ProbeResult {
141
+ /** Whether the URL returned 402 Payment Required. */
142
+ enabled: boolean;
143
+ /** The URL that was probed. */
144
+ url: string;
145
+ /** HTTP status code returned. */
146
+ status: number;
147
+ /** Human-readable price summary, e.g. "$0.002 USDC on Base". Null if not x402. */
148
+ price: string | null;
149
+ /** The parsed 402 response body. Null if not x402. */
150
+ paymentRequired: PaymentRequiredResponse | null;
151
+ }
152
+ interface ProbeOptions {
153
+ /** HTTP method to use. Default: "GET". */
154
+ method?: string;
155
+ /** Request headers to include. */
156
+ headers?: Record<string, string>;
157
+ /** Request body (for POST endpoints). */
158
+ body?: string;
159
+ /** Abort signal for timeout control. */
160
+ signal?: AbortSignal;
161
+ }
162
+ /** A service listed in the Bazaar registry. */
163
+ interface BazaarService {
164
+ /** The service endpoint URL. */
165
+ url: string;
166
+ /** Service description. */
167
+ description: string | null;
168
+ /** Human-readable price of the cheapest accept option. */
169
+ price: string;
170
+ /** All accepted payment options. */
171
+ accepts: PaymentOption[];
172
+ /** Raw metadata from the Bazaar. */
173
+ metadata: Record<string, unknown>;
174
+ }
175
+ interface DiscoverResult {
176
+ services: BazaarService[];
177
+ total: number;
178
+ }
179
+ interface DiscoverOptions {
180
+ /** Max results to return. Default: 20. */
181
+ limit?: number;
182
+ /** Pagination offset. Default: 0. */
183
+ offset?: number;
184
+ /** Bazaar API base URL. Override for testing. */
185
+ bazaarUrl?: string;
186
+ /** Abort signal for timeout control. */
187
+ signal?: AbortSignal;
188
+ }
189
+ interface FormatPriceOptions {
190
+ /** If true, omit the network suffix (e.g. "$0.002 USDC" instead of "$0.002 USDC on Base"). */
191
+ short?: boolean;
192
+ }
193
+
194
+ /**
195
+ * Check if a URL is x402-enabled and see what it costs, without paying.
196
+ *
197
+ * Sends a request to the URL. If the server returns 402 Payment Required,
198
+ * parses the payment requirements and returns a structured result with
199
+ * human-readable pricing. Non-402 responses return `{ enabled: false }`.
200
+ *
201
+ * No wallet needed — this is a read-only inspection.
202
+ */
203
+ declare function probe(url: string, options?: ProbeOptions): Promise<ProbeResult>;
204
+
205
+ /**
206
+ * Query the Bazaar registry to find available x402 services.
207
+ *
208
+ * Fetches from the Coinbase CDP Bazaar discovery endpoint and returns
209
+ * a normalized list of services with human-readable pricing.
210
+ *
211
+ * No wallet or authentication needed.
212
+ */
213
+ declare function discover(options?: DiscoverOptions): Promise<DiscoverResult>;
214
+
215
+ /**
216
+ * Format a raw x402 price into a human-readable string.
217
+ *
218
+ * Knows about common assets (USDC on Base = 6 decimals, $-prefixed)
219
+ * and falls back to raw display for unknown assets.
220
+ *
221
+ * @example
222
+ * formatPrice("2000", "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "eip155:8453")
223
+ * // → "$0.002 USDC on Base"
224
+ */
225
+ declare function formatPrice(amount: string, asset: string, network: string, options?: FormatPriceOptions): string;
226
+
227
+ declare const x402: {
228
+ probe: typeof probe;
229
+ discover: typeof discover;
230
+ formatPrice: typeof formatPrice;
231
+ };
232
+
233
+ export { type BazaarService, type ComputeRequest, type ComputeResponse, type CreateWalletOptions, type DiscoverOptions, type DiscoverResult, type FormatPriceOptions, type Network, type PaymentOption, type PaymentRequiredResponse, type PricingTier, type ProbeOptions, type ProbeResult, type Size, type Stack, type WaitForFundingOptions, Wallet, type WalletConfig, compute, wallet, x402 };
package/dist/index.js CHANGED
@@ -22,7 +22,8 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  Wallet: () => Wallet,
24
24
  compute: () => compute,
25
- wallet: () => wallet
25
+ wallet: () => wallet,
26
+ x402: () => x402
26
27
  });
27
28
  module.exports = __toCommonJS(index_exports);
28
29
 
@@ -80,7 +81,7 @@ function migrateLegacyWallet(walletsDir) {
80
81
  return null;
81
82
  }
82
83
 
83
- // src/x402/index.ts
84
+ // src/x402/payment-fetch.ts
84
85
  var import_client = require("@x402/core/client");
85
86
  var import_client2 = require("@x402/evm/exact/client");
86
87
  var import_evm = require("@x402/evm");
@@ -349,10 +350,174 @@ var compute = {
349
350
  _endpoint = url;
350
351
  }
351
352
  };
353
+
354
+ // src/x402/format.ts
355
+ var KNOWN_ASSETS = {
356
+ // USDC on Base mainnet
357
+ "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913": { symbol: "USDC", decimals: 6, prefix: "$" },
358
+ // USDC on Base Sepolia
359
+ "0x036cbd53842c5426634e7929541ec2318f3dcf7e": { symbol: "USDC", decimals: 6, prefix: "$" }
360
+ };
361
+ var NETWORK_NAMES = {
362
+ "eip155:8453": "Base",
363
+ "eip155:84532": "Base Sepolia",
364
+ "base": "Base",
365
+ "base-sepolia": "Base Sepolia"
366
+ };
367
+ function formatPrice(amount, asset, network, options) {
368
+ const known = KNOWN_ASSETS[asset.toLowerCase()];
369
+ const networkName = NETWORK_NAMES[network];
370
+ if (known) {
371
+ const value = Number(amount) / 10 ** known.decimals;
372
+ const formatted = `${known.prefix}${value} ${known.symbol}`;
373
+ if (options?.short || !networkName) return formatted;
374
+ return `${formatted} on ${networkName}`;
375
+ }
376
+ const shortAsset = `${asset.slice(0, 6)}...${asset.slice(-4)}`;
377
+ const raw = `${amount} ${shortAsset}`;
378
+ if (options?.short || !networkName) return raw;
379
+ return `${raw} on ${networkName}`;
380
+ }
381
+
382
+ // src/x402/probe.ts
383
+ async function probe(url, options) {
384
+ const res = await fetch(url, {
385
+ method: options?.method ?? "GET",
386
+ headers: options?.headers,
387
+ body: options?.body,
388
+ signal: options?.signal
389
+ });
390
+ if (res.status !== 402) {
391
+ return { enabled: false, url, status: res.status, price: null, paymentRequired: null };
392
+ }
393
+ let raw;
394
+ try {
395
+ raw = await res.json();
396
+ } catch {
397
+ return { enabled: false, url, status: 402, price: null, paymentRequired: null };
398
+ }
399
+ const paymentRequired = normalizePaymentRequired(raw);
400
+ if (!paymentRequired || paymentRequired.accepts.length === 0) {
401
+ return { enabled: false, url, status: 402, price: null, paymentRequired: null };
402
+ }
403
+ const first = paymentRequired.accepts[0];
404
+ const price = formatPrice(first.amount, first.asset, first.network);
405
+ return { enabled: true, url, status: 402, price, paymentRequired };
406
+ }
407
+ function normalizePaymentRequired(raw) {
408
+ if (!raw || typeof raw !== "object" || !Array.isArray(raw.accepts) || raw.accepts.length === 0) {
409
+ return null;
410
+ }
411
+ const firstAccept = raw.accepts[0];
412
+ const isV2 = typeof firstAccept.amount === "string" && raw.resource && typeof raw.resource === "object";
413
+ if (isV2) {
414
+ return {
415
+ x402Version: raw.x402Version ?? 2,
416
+ resource: {
417
+ url: raw.resource.url ?? "",
418
+ description: raw.resource.description,
419
+ mimeType: raw.resource.mimeType
420
+ },
421
+ accepts: raw.accepts.map(normalizeAccept),
422
+ extensions: raw.extensions ?? void 0
423
+ };
424
+ }
425
+ if (typeof firstAccept.maxAmountRequired === "string") {
426
+ return {
427
+ x402Version: raw.x402Version ?? 1,
428
+ resource: {
429
+ url: firstAccept.resource ?? raw.resource?.url ?? "",
430
+ description: firstAccept.description ?? raw.resource?.description,
431
+ mimeType: firstAccept.mimeType ?? raw.resource?.mimeType
432
+ },
433
+ accepts: raw.accepts.map((a) => normalizeAccept({
434
+ ...a,
435
+ amount: a.maxAmountRequired
436
+ })),
437
+ extensions: raw.extensions ?? void 0
438
+ };
439
+ }
440
+ return null;
441
+ }
442
+ function normalizeAccept(a) {
443
+ return {
444
+ scheme: a.scheme ?? "exact",
445
+ network: a.network ?? "",
446
+ asset: a.asset ?? "",
447
+ amount: String(a.amount ?? a.maxAmountRequired ?? "0"),
448
+ payTo: a.payTo ?? "",
449
+ maxTimeoutSeconds: a.maxTimeoutSeconds ?? 0,
450
+ extra: a.extra ?? void 0
451
+ };
452
+ }
453
+
454
+ // src/x402/discover.ts
455
+ var DEFAULT_BAZAAR_URL = "https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources";
456
+ async function discover(options) {
457
+ const baseUrl = options?.bazaarUrl ?? DEFAULT_BAZAAR_URL;
458
+ const params = new URLSearchParams();
459
+ if (options?.limit != null) params.set("limit", String(options.limit));
460
+ if (options?.offset != null) params.set("offset", String(options.offset));
461
+ const url = params.toString() ? `${baseUrl}?${params}` : baseUrl;
462
+ const res = await fetch(url, {
463
+ headers: { Accept: "application/json" },
464
+ signal: options?.signal
465
+ });
466
+ if (!res.ok) {
467
+ const text = await res.text().catch(() => "");
468
+ throw new Error(`Bazaar request failed (${res.status}): ${text}`);
469
+ }
470
+ const json = await res.json();
471
+ const items = json.items ?? json.resources ?? [];
472
+ const services = items.map(normalizeBazaarItem).filter(Boolean);
473
+ return {
474
+ services,
475
+ total: json.total ?? json.totalCount ?? services.length
476
+ };
477
+ }
478
+ function normalizeBazaarItem(item) {
479
+ if (!item || typeof item !== "object") return null;
480
+ const accepts = item.accepts ?? [];
481
+ if (accepts.length === 0) return null;
482
+ const normalizedAccepts = accepts.map((a) => {
483
+ const accept = a;
484
+ return {
485
+ scheme: accept.scheme ?? "exact",
486
+ network: accept.network ?? "",
487
+ asset: accept.asset ?? "",
488
+ amount: String(accept.amount ?? accept.maxAmountRequired ?? "0"),
489
+ payTo: accept.payTo ?? "",
490
+ maxTimeoutSeconds: accept.maxTimeoutSeconds ?? 0,
491
+ extra: accept.extra ?? void 0
492
+ };
493
+ });
494
+ const cheapest = normalizedAccepts.reduce(
495
+ (min, a) => BigInt(a.amount) < BigInt(min.amount) ? a : min
496
+ );
497
+ const price = formatPrice(cheapest.amount, cheapest.asset, cheapest.network);
498
+ const firstAccept = accepts[0];
499
+ const description = item.description ?? item.resource?.description ?? firstAccept?.description ?? item.metadata?.description ?? null;
500
+ const url = item.url ?? item.resource?.url ?? (typeof item.resource === "string" ? item.resource : null) ?? firstAccept?.resource ?? "";
501
+ return {
502
+ url,
503
+ description,
504
+ price,
505
+ accepts: normalizedAccepts,
506
+ metadata: item.metadata ?? {}
507
+ };
508
+ }
509
+
510
+ // src/x402/index.ts
511
+ var x402 = {
512
+ probe,
513
+ discover,
514
+ formatPrice
515
+ };
352
516
  // Annotate the CommonJS export names for ESM import in node:
353
517
  0 && (module.exports = {
354
518
  Wallet,
355
519
  compute,
356
- wallet
520
+ wallet,
521
+ x402
357
522
  });
358
523
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/wallet/index.ts","../src/wallet/keypair.ts","../src/wallet/storage.ts","../src/x402/index.ts","../src/wallet/types.ts","../src/wallet/balance.ts","../src/wallet/wallet.ts","../src/compute/index.ts"],"sourcesContent":["export { wallet } from \"./wallet/index.js\"\nexport { Wallet } from \"./wallet/wallet.js\"\nexport { compute } from \"./compute/index.js\"\n\nexport type { CreateWalletOptions, WalletConfig, WaitForFundingOptions, Network } from \"./wallet/types.js\"\nexport type { ComputeRequest, ComputeResponse, PricingTier, Stack, Size } from \"./compute/types.js\"\n","import { join, resolve } from \"node:path\"\nimport { createKeypair, loadKeypair } from \"./keypair.js\"\nimport { readWalletFile, writeWalletFile, listWalletFiles, migrateLegacyWallet, validateWalletName } from \"./storage.js\"\nimport { createPaymentFetch } from \"../x402/index.js\"\nimport { Wallet } from \"./wallet.js\"\nimport type { CreateWalletOptions } from \"./types.js\"\n\nconst DEFAULT_WALLETS_DIR = \".auteng/wallets\"\n\nconst _wallets = new Map<string, Wallet>()\nlet _walletsDir = resolve(DEFAULT_WALLETS_DIR)\n\nexport const wallet = {\n /**\n * Create a new named wallet or load an existing one from disk.\n * Idempotent: if a wallet with this name already exists, returns it.\n */\n async create(opts?: CreateWalletOptions): Promise<Wallet> {\n const name = opts?.name ?? \"default\"\n validateWalletName(name)\n\n if (_wallets.has(name)) return _wallets.get(name)!\n\n const dir = resolve(opts?.walletsDir ?? DEFAULT_WALLETS_DIR)\n _walletsDir = dir\n const filePath = join(dir, `${name}.json`)\n const network = opts?.network ?? \"base\"\n const rpcUrl = opts?.rpcUrl\n\n let existing = readWalletFile(filePath)\n\n if (!existing && name === \"default\") {\n existing = migrateLegacyWallet(dir)\n }\n\n let privateKey: `0x${string}`\n let account: ReturnType<typeof loadKeypair>[\"account\"]\n\n if (existing) {\n privateKey = existing.privateKey\n account = loadKeypair(existing.privateKey).account\n } else {\n const kp = createKeypair()\n privateKey = kp.privateKey\n account = kp.account\n writeWalletFile(filePath, {\n privateKey,\n address: account.address,\n network,\n })\n }\n\n const effectiveNetwork = existing?.network ?? network\n const paymentFetch = createPaymentFetch(privateKey, effectiveNetwork, rpcUrl)\n const w = new Wallet({\n name,\n account,\n privateKey,\n network: effectiveNetwork,\n rpcUrl,\n paymentFetch,\n })\n _wallets.set(name, w)\n return w\n },\n\n /**\n * Retrieve a previously-created wallet by name.\n * Loads from disk if not in memory. Throws if not found.\n */\n get(name: string): Wallet {\n validateWalletName(name)\n\n if (_wallets.has(name)) return _wallets.get(name)!\n\n const filePath = join(_walletsDir, `${name}.json`)\n const data = readWalletFile(filePath)\n if (!data) throw new Error(`Wallet \"${name}\" not found`)\n\n const { account } = loadKeypair(data.privateKey)\n const paymentFetch = createPaymentFetch(data.privateKey, data.network)\n const w = new Wallet({\n name,\n account,\n privateKey: data.privateKey,\n network: data.network,\n paymentFetch,\n })\n _wallets.set(name, w)\n return w\n },\n\n /** List all persisted wallets. */\n list(): Wallet[] {\n const names = listWalletFiles(_walletsDir)\n return names.map((n) => {\n if (_wallets.has(n)) return _wallets.get(n)!\n return wallet.get(n)\n })\n },\n\n /** @internal Clear in-memory cache and reset wallets dir. For testing only. */\n _reset(): void {\n _wallets.clear()\n _walletsDir = resolve(DEFAULT_WALLETS_DIR)\n },\n}\n","import { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\"\nimport type { PrivateKeyAccount } from \"viem\"\n\nexport function createKeypair(): {\n privateKey: `0x${string}`\n account: PrivateKeyAccount\n} {\n const privateKey = generatePrivateKey()\n const account = privateKeyToAccount(privateKey)\n return { privateKey, account }\n}\n\nexport function loadKeypair(privateKey: `0x${string}`): {\n account: PrivateKeyAccount\n} {\n const account = privateKeyToAccount(privateKey)\n return { account }\n}\n","import { mkdirSync, readFileSync, writeFileSync, existsSync, readdirSync, copyFileSync } from \"node:fs\"\nimport { dirname, join, resolve } from \"node:path\"\nimport type { WalletFile } from \"./types.js\"\n\nconst VALID_NAME = /^[a-z0-9_-]+$/\n\nexport function validateWalletName(name: string): void {\n if (!VALID_NAME.test(name)) {\n throw new Error(`Invalid wallet name \"${name}\". Use lowercase letters, numbers, hyphens, and underscores only.`)\n }\n}\n\nexport function readWalletFile(path: string): WalletFile | null {\n if (!existsSync(path)) return null\n const raw = readFileSync(path, \"utf-8\")\n return JSON.parse(raw) as WalletFile\n}\n\nexport function writeWalletFile(path: string, data: WalletFile): void {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(data, null, 2) + \"\\n\", {\n mode: 0o600,\n })\n}\n\nexport function listWalletFiles(dir: string): string[] {\n const resolved = resolve(dir)\n if (!existsSync(resolved)) return []\n return readdirSync(resolved)\n .filter((f) => f.endsWith(\".json\"))\n .map((f) => f.replace(/\\.json$/, \"\"))\n}\n\nexport function migrateLegacyWallet(walletsDir: string): WalletFile | null {\n const legacyPath = resolve(walletsDir, \"..\", \"wallet.json\")\n const newPath = join(resolve(walletsDir), \"default.json\")\n if (existsSync(legacyPath) && !existsSync(newPath)) {\n const data = readWalletFile(legacyPath)\n if (data) {\n mkdirSync(resolve(walletsDir), { recursive: true })\n copyFileSync(legacyPath, newPath)\n return data\n }\n }\n return null\n}\n","import { x402Client } from \"@x402/core/client\"\nimport { registerExactEvmScheme } from \"@x402/evm/exact/client\"\nimport { toClientEvmSigner } from \"@x402/evm\"\nimport { wrapFetchWithPayment } from \"@x402/fetch\"\nimport { privateKeyToAccount } from \"viem/accounts\"\nimport { createPublicClient, http } from \"viem\"\nimport { base, baseSepolia } from \"viem/chains\"\nimport type { Network } from \"../wallet/types.js\"\n\n/**\n * Create a fetch function that automatically handles x402 payments.\n * When the server returns 402, the SDK signs an EIP-3009 authorization\n * using the provided private key and retries with payment headers.\n */\nexport function createPaymentFetch(\n privateKey: `0x${string}`,\n network: Network = \"base\",\n rpcUrl?: string\n): typeof globalThis.fetch {\n const account = privateKeyToAccount(privateKey)\n const chain = network === \"base\" ? base : baseSepolia\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl),\n })\n const signer = toClientEvmSigner(account, publicClient)\n\n const client = new x402Client()\n registerExactEvmScheme(client, { signer })\n return wrapFetchWithPayment(fetch, client)\n}\n","export type Network = \"base\" | \"base-sepolia\"\n\nexport interface CreateWalletOptions {\n /** Wallet identifier. Default: \"default\" */\n name?: string\n /** Network to use. Default: `base` */\n network?: Network\n /** Custom RPC endpoint. Default: public Base RPC */\n rpcUrl?: string\n /** Base directory for wallet storage. Default: \".auteng/wallets\" */\n walletsDir?: string\n}\n\n/** @deprecated Use CreateWalletOptions instead */\nexport type WalletConfig = CreateWalletOptions\n\nexport interface WalletFile {\n privateKey: `0x${string}`\n address: `0x${string}`\n network: Network\n}\n\nexport interface WaitForFundingOptions {\n /** Poll interval in milliseconds. Default: 10000 (10s) */\n pollInterval?: number\n /** Timeout in milliseconds. Default: none (waits forever) */\n timeout?: number\n}\n\nexport const NETWORK_CONFIG: Record<Network, { chainId: number; usdcAddress: `0x${string}`; rpcUrl: string }> = {\n base: {\n chainId: 8453,\n usdcAddress: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n rpcUrl: \"https://mainnet.base.org\",\n },\n \"base-sepolia\": {\n chainId: 84532,\n usdcAddress: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n rpcUrl: \"https://sepolia.base.org\",\n },\n}\n","import type { Network } from \"./types.js\"\nimport { NETWORK_CONFIG } from \"./types.js\"\n\n/**\n * Read USDC balance for `address` via a direct `eth_call` to the USDC\n * contract's `balanceOf(address)` function. No viem client needed — just\n * a plain JSON-RPC POST.\n */\nexport async function getUsdcBalance(address: `0x${string}`, network: Network, rpcUrl?: string): Promise<bigint> {\n const config = NETWORK_CONFIG[network]\n const url = rpcUrl ?? config.rpcUrl\n\n // balanceOf(address) selector = 0x70a08231\n const paddedAddress = address.slice(2).toLowerCase().padStart(64, \"0\")\n const data = `0x70a08231${paddedAddress}`\n\n const res = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"eth_call\",\n params: [{ to: config.usdcAddress, data }, \"latest\"],\n }),\n })\n\n const json = (await res.json()) as { result?: string; error?: unknown }\n if (json.error) {\n throw new Error(`RPC error: ${JSON.stringify(json.error)}`)\n }\n return BigInt(json.result ?? \"0x0\")\n}\n","import type { PrivateKeyAccount } from \"viem\"\nimport { getUsdcBalance } from \"./balance.js\"\nimport type { Network, WaitForFundingOptions } from \"./types.js\"\n\nexport class Wallet {\n readonly name: string\n readonly address: `0x${string}`\n readonly network: Network\n\n private _account: PrivateKeyAccount\n private _privateKey: `0x${string}`\n private _rpcUrl: string | undefined\n private _paymentFetch: typeof globalThis.fetch\n\n constructor(params: {\n name: string\n account: PrivateKeyAccount\n privateKey: `0x${string}`\n network: Network\n rpcUrl?: string\n paymentFetch: typeof globalThis.fetch\n }) {\n this.name = params.name\n this._account = params.account\n this._privateKey = params.privateKey\n this.address = params.account.address\n this.network = params.network\n this._rpcUrl = params.rpcUrl\n this._paymentFetch = params.paymentFetch\n }\n\n /** Check USDC balance on Base. Returns balance in minor units (6 decimals). */\n async checkBalance(): Promise<bigint> {\n return getUsdcBalance(this._account.address, this.network, this._rpcUrl)\n }\n\n /**\n * Poll until USDC balance >= minAmount.\n * @param minAmount - minimum USDC balance in minor units (6 decimals)\n */\n async waitForFunding(minAmount: bigint, opts?: WaitForFundingOptions): Promise<void> {\n const interval = opts?.pollInterval ?? 10_000\n const deadline = opts?.timeout ? Date.now() + opts.timeout : null\n\n while (true) {\n const balance = await getUsdcBalance(this._account.address, this.network, this._rpcUrl)\n if (balance >= minAmount) return\n\n if (deadline && Date.now() >= deadline) {\n throw new Error(`Funding timeout: balance ${balance} < required ${minAmount}`)\n }\n\n await new Promise((r) => setTimeout(r, interval))\n }\n }\n\n /**\n * Drop-in `fetch()` replacement that handles x402 payments automatically.\n * If the server returns 402, the library signs an EIP-3009 authorization\n * and retries the request with payment headers.\n */\n async fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {\n return this._paymentFetch(input, init)\n }\n}\n","import type { ComputeRequest, ComputeResponse, PricingTier, Size } from \"./types.js\"\n\nconst DEFAULT_ENDPOINT = \"https://x402.auteng.ai/api/x402/compute\"\n\nlet _endpoint = DEFAULT_ENDPOINT\n\nconst PRICING: Record<Size, PricingTier> = {\n small: {\n vcpu: 2,\n ram_gb: 1,\n default_timeout_s: 30,\n max_timeout_s: 300,\n base_price_usd: 0.002,\n per_second_usd: 0.00005,\n },\n med: {\n vcpu: 4,\n ram_gb: 4,\n default_timeout_s: 60,\n max_timeout_s: 600,\n base_price_usd: 0.008,\n per_second_usd: 0.00012,\n },\n large: {\n vcpu: 8,\n ram_gb: 16,\n default_timeout_s: 120,\n max_timeout_s: 3600,\n base_price_usd: 0.03,\n per_second_usd: 0.00025,\n },\n}\n\nexport const compute = {\n /**\n * Execute sandboxed code via AutEng's x402 compute endpoint.\n * Payment is handled automatically via the wallet's x402 layer.\n */\n async run(request: ComputeRequest): Promise<ComputeResponse> {\n if (!request.code) {\n throw new Error(\"compute.run: 'code' is required\")\n }\n if (!request.stack) {\n throw new Error(\"compute.run: 'stack' is required\")\n }\n\n const body = {\n code: request.code,\n stack: request.stack,\n size: request.size ?? \"small\",\n ...(request.timeout_seconds != null && {\n timeout_seconds: request.timeout_seconds,\n }),\n ...(request.files != null && { files: request.files }),\n }\n\n if (!request.wallet) {\n throw new Error(\"compute.run: 'wallet' is required\")\n }\n\n const response = await request.wallet.fetch(_endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n })\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\")\n throw new Error(`Compute request failed (${response.status}): ${text}`)\n }\n\n return (await response.json()) as ComputeResponse\n },\n\n /** Returns the pricing table for all compute sizes. */\n pricing(): Record<Size, PricingTier> {\n return { ...PRICING }\n },\n\n /**\n * Override the compute endpoint URL.\n * Default: https://x402.auteng.ai/api/x402/compute\n */\n setEndpoint(url: string): void {\n _endpoint = url\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,oBAA8B;;;ACA9B,sBAAwD;AAGjD,SAAS,gBAGd;AACA,QAAM,iBAAa,oCAAmB;AACtC,QAAM,cAAU,qCAAoB,UAAU;AAC9C,SAAO,EAAE,YAAY,QAAQ;AAC/B;AAEO,SAAS,YAAY,YAE1B;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,QAAQ,OAAO;AAClB,YAAM,IAAI,MAAM,kCAAkC;AAAA,IACpD;AAEA,UAAM,OAAO;AAAA,MACX,MAAM,QAAQ;AAAA,MACd,OAAO,QAAQ;AAAA,MACf,MAAM,QAAQ,QAAQ;AAAA,MACtB,GAAI,QAAQ,mBAAmB,QAAQ;AAAA,QACrC,iBAAiB,QAAQ;AAAA,MAC3B;AAAA,MACA,GAAI,QAAQ,SAAS,QAAQ,EAAE,OAAO,QAAQ,MAAM;AAAA,IACtD;AAEA,QAAI,CAAC,QAAQ,QAAQ;AACnB,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AAEA,UAAM,WAAW,MAAM,QAAQ,OAAO,MAAM,WAAW;AAAA,MACrD,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAC9C,MAAM,KAAK,UAAU,IAAI;AAAA,IAC3B,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,OAAO,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,EAAE;AACjD,YAAM,IAAI,MAAM,2BAA2B,SAAS,MAAM,MAAM,IAAI,EAAE;AAAA,IACxE;AAEA,WAAQ,MAAM,SAAS,KAAK;AAAA,EAC9B;AAAA;AAAA,EAGA,UAAqC;AACnC,WAAO,EAAE,GAAG,QAAQ;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAY,KAAmB;AAC7B,gBAAY;AAAA,EACd;AACF;","names":["import_node_path","import_client","import_accounts"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/wallet/index.ts","../src/wallet/keypair.ts","../src/wallet/storage.ts","../src/x402/payment-fetch.ts","../src/wallet/types.ts","../src/wallet/balance.ts","../src/wallet/wallet.ts","../src/compute/index.ts","../src/x402/format.ts","../src/x402/probe.ts","../src/x402/discover.ts","../src/x402/index.ts"],"sourcesContent":["export { wallet } from \"./wallet/index.js\"\nexport { Wallet } from \"./wallet/wallet.js\"\nexport { compute } from \"./compute/index.js\"\nexport { x402 } from \"./x402/index.js\"\n\nexport type { CreateWalletOptions, WalletConfig, WaitForFundingOptions, Network } from \"./wallet/types.js\"\nexport type { ComputeRequest, ComputeResponse, PricingTier, Stack, Size } from \"./compute/types.js\"\nexport type {\n ProbeResult,\n ProbeOptions,\n PaymentRequiredResponse,\n PaymentOption,\n BazaarService,\n DiscoverResult,\n DiscoverOptions,\n FormatPriceOptions,\n} from \"./x402/types.js\"\n","import { join, resolve } from \"node:path\"\nimport { createKeypair, loadKeypair } from \"./keypair.js\"\nimport { readWalletFile, writeWalletFile, listWalletFiles, migrateLegacyWallet, validateWalletName } from \"./storage.js\"\nimport { createPaymentFetch } from \"../x402/payment-fetch.js\"\nimport { Wallet } from \"./wallet.js\"\nimport type { CreateWalletOptions } from \"./types.js\"\n\nconst DEFAULT_WALLETS_DIR = \".auteng/wallets\"\n\nconst _wallets = new Map<string, Wallet>()\nlet _walletsDir = resolve(DEFAULT_WALLETS_DIR)\n\nexport const wallet = {\n /**\n * Create a new named wallet or load an existing one from disk.\n * Idempotent: if a wallet with this name already exists, returns it.\n */\n async create(opts?: CreateWalletOptions): Promise<Wallet> {\n const name = opts?.name ?? \"default\"\n validateWalletName(name)\n\n if (_wallets.has(name)) return _wallets.get(name)!\n\n const dir = resolve(opts?.walletsDir ?? DEFAULT_WALLETS_DIR)\n _walletsDir = dir\n const filePath = join(dir, `${name}.json`)\n const network = opts?.network ?? \"base\"\n const rpcUrl = opts?.rpcUrl\n\n let existing = readWalletFile(filePath)\n\n if (!existing && name === \"default\") {\n existing = migrateLegacyWallet(dir)\n }\n\n let privateKey: `0x${string}`\n let account: ReturnType<typeof loadKeypair>[\"account\"]\n\n if (existing) {\n privateKey = existing.privateKey\n account = loadKeypair(existing.privateKey).account\n } else {\n const kp = createKeypair()\n privateKey = kp.privateKey\n account = kp.account\n writeWalletFile(filePath, {\n privateKey,\n address: account.address,\n network,\n })\n }\n\n const effectiveNetwork = existing?.network ?? network\n const paymentFetch = createPaymentFetch(privateKey, effectiveNetwork, rpcUrl)\n const w = new Wallet({\n name,\n account,\n privateKey,\n network: effectiveNetwork,\n rpcUrl,\n paymentFetch,\n })\n _wallets.set(name, w)\n return w\n },\n\n /**\n * Retrieve a previously-created wallet by name.\n * Loads from disk if not in memory. Throws if not found.\n */\n get(name: string): Wallet {\n validateWalletName(name)\n\n if (_wallets.has(name)) return _wallets.get(name)!\n\n const filePath = join(_walletsDir, `${name}.json`)\n const data = readWalletFile(filePath)\n if (!data) throw new Error(`Wallet \"${name}\" not found`)\n\n const { account } = loadKeypair(data.privateKey)\n const paymentFetch = createPaymentFetch(data.privateKey, data.network)\n const w = new Wallet({\n name,\n account,\n privateKey: data.privateKey,\n network: data.network,\n paymentFetch,\n })\n _wallets.set(name, w)\n return w\n },\n\n /** List all persisted wallets. */\n list(): Wallet[] {\n const names = listWalletFiles(_walletsDir)\n return names.map((n) => {\n if (_wallets.has(n)) return _wallets.get(n)!\n return wallet.get(n)\n })\n },\n\n /** @internal Clear in-memory cache and reset wallets dir. For testing only. */\n _reset(): void {\n _wallets.clear()\n _walletsDir = resolve(DEFAULT_WALLETS_DIR)\n },\n}\n","import { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\"\nimport type { PrivateKeyAccount } from \"viem\"\n\nexport function createKeypair(): {\n privateKey: `0x${string}`\n account: PrivateKeyAccount\n} {\n const privateKey = generatePrivateKey()\n const account = privateKeyToAccount(privateKey)\n return { privateKey, account }\n}\n\nexport function loadKeypair(privateKey: `0x${string}`): {\n account: PrivateKeyAccount\n} {\n const account = privateKeyToAccount(privateKey)\n return { account }\n}\n","import { mkdirSync, readFileSync, writeFileSync, existsSync, readdirSync, copyFileSync } from \"node:fs\"\nimport { dirname, join, resolve } from \"node:path\"\nimport type { WalletFile } from \"./types.js\"\n\nconst VALID_NAME = /^[a-z0-9_-]+$/\n\nexport function validateWalletName(name: string): void {\n if (!VALID_NAME.test(name)) {\n throw new Error(`Invalid wallet name \"${name}\". Use lowercase letters, numbers, hyphens, and underscores only.`)\n }\n}\n\nexport function readWalletFile(path: string): WalletFile | null {\n if (!existsSync(path)) return null\n const raw = readFileSync(path, \"utf-8\")\n return JSON.parse(raw) as WalletFile\n}\n\nexport function writeWalletFile(path: string, data: WalletFile): void {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(data, null, 2) + \"\\n\", {\n mode: 0o600,\n })\n}\n\nexport function listWalletFiles(dir: string): string[] {\n const resolved = resolve(dir)\n if (!existsSync(resolved)) return []\n return readdirSync(resolved)\n .filter((f) => f.endsWith(\".json\"))\n .map((f) => f.replace(/\\.json$/, \"\"))\n}\n\nexport function migrateLegacyWallet(walletsDir: string): WalletFile | null {\n const legacyPath = resolve(walletsDir, \"..\", \"wallet.json\")\n const newPath = join(resolve(walletsDir), \"default.json\")\n if (existsSync(legacyPath) && !existsSync(newPath)) {\n const data = readWalletFile(legacyPath)\n if (data) {\n mkdirSync(resolve(walletsDir), { recursive: true })\n copyFileSync(legacyPath, newPath)\n return data\n }\n }\n return null\n}\n","import { x402Client } from \"@x402/core/client\"\nimport { registerExactEvmScheme } from \"@x402/evm/exact/client\"\nimport { toClientEvmSigner } from \"@x402/evm\"\nimport { wrapFetchWithPayment } from \"@x402/fetch\"\nimport { privateKeyToAccount } from \"viem/accounts\"\nimport { createPublicClient, http } from \"viem\"\nimport { base, baseSepolia } from \"viem/chains\"\nimport type { Network } from \"../wallet/types.js\"\n\n/**\n * Create a fetch function that automatically handles x402 payments.\n * When the server returns 402, the SDK signs an EIP-3009 authorization\n * using the provided private key and retries with payment headers.\n */\nexport function createPaymentFetch(\n privateKey: `0x${string}`,\n network: Network = \"base\",\n rpcUrl?: string\n): typeof globalThis.fetch {\n const account = privateKeyToAccount(privateKey)\n const chain = network === \"base\" ? base : baseSepolia\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl),\n })\n const signer = toClientEvmSigner(account, publicClient)\n\n const client = new x402Client()\n registerExactEvmScheme(client, { signer })\n return wrapFetchWithPayment(fetch, client)\n}\n","export type Network = \"base\" | \"base-sepolia\"\n\nexport interface CreateWalletOptions {\n /** Wallet identifier. Default: \"default\" */\n name?: string\n /** Network to use. Default: `base` */\n network?: Network\n /** Custom RPC endpoint. Default: public Base RPC */\n rpcUrl?: string\n /** Base directory for wallet storage. Default: \".auteng/wallets\" */\n walletsDir?: string\n}\n\n/** @deprecated Use CreateWalletOptions instead */\nexport type WalletConfig = CreateWalletOptions\n\nexport interface WalletFile {\n privateKey: `0x${string}`\n address: `0x${string}`\n network: Network\n}\n\nexport interface WaitForFundingOptions {\n /** Poll interval in milliseconds. Default: 10000 (10s) */\n pollInterval?: number\n /** Timeout in milliseconds. Default: none (waits forever) */\n timeout?: number\n}\n\nexport const NETWORK_CONFIG: Record<Network, { chainId: number; usdcAddress: `0x${string}`; rpcUrl: string }> = {\n base: {\n chainId: 8453,\n usdcAddress: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n rpcUrl: \"https://mainnet.base.org\",\n },\n \"base-sepolia\": {\n chainId: 84532,\n usdcAddress: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n rpcUrl: \"https://sepolia.base.org\",\n },\n}\n","import type { Network } from \"./types.js\"\nimport { NETWORK_CONFIG } from \"./types.js\"\n\n/**\n * Read USDC balance for `address` via a direct `eth_call` to the USDC\n * contract's `balanceOf(address)` function. No viem client needed — just\n * a plain JSON-RPC POST.\n */\nexport async function getUsdcBalance(address: `0x${string}`, network: Network, rpcUrl?: string): Promise<bigint> {\n const config = NETWORK_CONFIG[network]\n const url = rpcUrl ?? config.rpcUrl\n\n // balanceOf(address) selector = 0x70a08231\n const paddedAddress = address.slice(2).toLowerCase().padStart(64, \"0\")\n const data = `0x70a08231${paddedAddress}`\n\n const res = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"eth_call\",\n params: [{ to: config.usdcAddress, data }, \"latest\"],\n }),\n })\n\n const json = (await res.json()) as { result?: string; error?: unknown }\n if (json.error) {\n throw new Error(`RPC error: ${JSON.stringify(json.error)}`)\n }\n return BigInt(json.result ?? \"0x0\")\n}\n","import type { PrivateKeyAccount } from \"viem\"\nimport { getUsdcBalance } from \"./balance.js\"\nimport type { Network, WaitForFundingOptions } from \"./types.js\"\n\nexport class Wallet {\n readonly name: string\n readonly address: `0x${string}`\n readonly network: Network\n\n private _account: PrivateKeyAccount\n private _privateKey: `0x${string}`\n private _rpcUrl: string | undefined\n private _paymentFetch: typeof globalThis.fetch\n\n constructor(params: {\n name: string\n account: PrivateKeyAccount\n privateKey: `0x${string}`\n network: Network\n rpcUrl?: string\n paymentFetch: typeof globalThis.fetch\n }) {\n this.name = params.name\n this._account = params.account\n this._privateKey = params.privateKey\n this.address = params.account.address\n this.network = params.network\n this._rpcUrl = params.rpcUrl\n this._paymentFetch = params.paymentFetch\n }\n\n /** Check USDC balance on Base. Returns balance in minor units (6 decimals). */\n async checkBalance(): Promise<bigint> {\n return getUsdcBalance(this._account.address, this.network, this._rpcUrl)\n }\n\n /**\n * Poll until USDC balance >= minAmount.\n * @param minAmount - minimum USDC balance in minor units (6 decimals)\n */\n async waitForFunding(minAmount: bigint, opts?: WaitForFundingOptions): Promise<void> {\n const interval = opts?.pollInterval ?? 10_000\n const deadline = opts?.timeout ? Date.now() + opts.timeout : null\n\n while (true) {\n const balance = await getUsdcBalance(this._account.address, this.network, this._rpcUrl)\n if (balance >= minAmount) return\n\n if (deadline && Date.now() >= deadline) {\n throw new Error(`Funding timeout: balance ${balance} < required ${minAmount}`)\n }\n\n await new Promise((r) => setTimeout(r, interval))\n }\n }\n\n /**\n * Drop-in `fetch()` replacement that handles x402 payments automatically.\n * If the server returns 402, the library signs an EIP-3009 authorization\n * and retries the request with payment headers.\n */\n async fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {\n return this._paymentFetch(input, init)\n }\n}\n","import type { ComputeRequest, ComputeResponse, PricingTier, Size } from \"./types.js\"\n\nconst DEFAULT_ENDPOINT = \"https://x402.auteng.ai/api/x402/compute\"\n\nlet _endpoint = DEFAULT_ENDPOINT\n\nconst PRICING: Record<Size, PricingTier> = {\n small: {\n vcpu: 2,\n ram_gb: 1,\n default_timeout_s: 30,\n max_timeout_s: 300,\n base_price_usd: 0.002,\n per_second_usd: 0.00005,\n },\n med: {\n vcpu: 4,\n ram_gb: 4,\n default_timeout_s: 60,\n max_timeout_s: 600,\n base_price_usd: 0.008,\n per_second_usd: 0.00012,\n },\n large: {\n vcpu: 8,\n ram_gb: 16,\n default_timeout_s: 120,\n max_timeout_s: 3600,\n base_price_usd: 0.03,\n per_second_usd: 0.00025,\n },\n}\n\nexport const compute = {\n /**\n * Execute sandboxed code via AutEng's x402 compute endpoint.\n * Payment is handled automatically via the wallet's x402 layer.\n */\n async run(request: ComputeRequest): Promise<ComputeResponse> {\n if (!request.code) {\n throw new Error(\"compute.run: 'code' is required\")\n }\n if (!request.stack) {\n throw new Error(\"compute.run: 'stack' is required\")\n }\n\n const body = {\n code: request.code,\n stack: request.stack,\n size: request.size ?? \"small\",\n ...(request.timeout_seconds != null && {\n timeout_seconds: request.timeout_seconds,\n }),\n ...(request.files != null && { files: request.files }),\n }\n\n if (!request.wallet) {\n throw new Error(\"compute.run: 'wallet' is required\")\n }\n\n const response = await request.wallet.fetch(_endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n })\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\")\n throw new Error(`Compute request failed (${response.status}): ${text}`)\n }\n\n return (await response.json()) as ComputeResponse\n },\n\n /** Returns the pricing table for all compute sizes. */\n pricing(): Record<Size, PricingTier> {\n return { ...PRICING }\n },\n\n /**\n * Override the compute endpoint URL.\n * Default: https://x402.auteng.ai/api/x402/compute\n */\n setEndpoint(url: string): void {\n _endpoint = url\n },\n}\n","import type { FormatPriceOptions } from \"./types.js\"\n\nconst KNOWN_ASSETS: Record<string, { symbol: string; decimals: number; prefix: string }> = {\n // USDC on Base mainnet\n \"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913\": { symbol: \"USDC\", decimals: 6, prefix: \"$\" },\n // USDC on Base Sepolia\n \"0x036cbd53842c5426634e7929541ec2318f3dcf7e\": { symbol: \"USDC\", decimals: 6, prefix: \"$\" },\n}\n\nconst NETWORK_NAMES: Record<string, string> = {\n \"eip155:8453\": \"Base\",\n \"eip155:84532\": \"Base Sepolia\",\n \"base\": \"Base\",\n \"base-sepolia\": \"Base Sepolia\",\n}\n\n/**\n * Format a raw x402 price into a human-readable string.\n *\n * Knows about common assets (USDC on Base = 6 decimals, $-prefixed)\n * and falls back to raw display for unknown assets.\n *\n * @example\n * formatPrice(\"2000\", \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\", \"eip155:8453\")\n * // → \"$0.002 USDC on Base\"\n */\nexport function formatPrice(\n amount: string,\n asset: string,\n network: string,\n options?: FormatPriceOptions,\n): string {\n const known = KNOWN_ASSETS[asset.toLowerCase()]\n const networkName = NETWORK_NAMES[network]\n\n if (known) {\n const value = Number(amount) / 10 ** known.decimals\n const formatted = `${known.prefix}${value} ${known.symbol}`\n if (options?.short || !networkName) return formatted\n return `${formatted} on ${networkName}`\n }\n\n // Unknown asset — show raw\n const shortAsset = `${asset.slice(0, 6)}...${asset.slice(-4)}`\n const raw = `${amount} ${shortAsset}`\n if (options?.short || !networkName) return raw\n return `${raw} on ${networkName}`\n}\n","import type { ProbeResult, ProbeOptions, PaymentRequiredResponse, PaymentOption } from \"./types.js\"\nimport { formatPrice } from \"./format.js\"\n\n/**\n * Check if a URL is x402-enabled and see what it costs, without paying.\n *\n * Sends a request to the URL. If the server returns 402 Payment Required,\n * parses the payment requirements and returns a structured result with\n * human-readable pricing. Non-402 responses return `{ enabled: false }`.\n *\n * No wallet needed — this is a read-only inspection.\n */\nexport async function probe(url: string, options?: ProbeOptions): Promise<ProbeResult> {\n const res = await fetch(url, {\n method: options?.method ?? \"GET\",\n headers: options?.headers,\n body: options?.body,\n signal: options?.signal,\n })\n\n if (res.status !== 402) {\n return { enabled: false, url, status: res.status, price: null, paymentRequired: null }\n }\n\n let raw: unknown\n try {\n raw = await res.json()\n } catch {\n return { enabled: false, url, status: 402, price: null, paymentRequired: null }\n }\n\n const paymentRequired = normalizePaymentRequired(raw)\n if (!paymentRequired || paymentRequired.accepts.length === 0) {\n return { enabled: false, url, status: 402, price: null, paymentRequired: null }\n }\n\n const first = paymentRequired.accepts[0]\n const price = formatPrice(first.amount, first.asset, first.network)\n\n return { enabled: true, url, status: 402, price, paymentRequired }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalizePaymentRequired(raw: any): PaymentRequiredResponse | null {\n if (!raw || typeof raw !== \"object\" || !Array.isArray(raw.accepts) || raw.accepts.length === 0) {\n return null\n }\n\n const firstAccept = raw.accepts[0]\n\n // Determine if v2 (has top-level resource object and accepts[].amount)\n // or v1 (has accepts[].maxAmountRequired and inline resource/description)\n const isV2 = typeof firstAccept.amount === \"string\" && raw.resource && typeof raw.resource === \"object\"\n\n if (isV2) {\n return {\n x402Version: raw.x402Version ?? 2,\n resource: {\n url: raw.resource.url ?? \"\",\n description: raw.resource.description,\n mimeType: raw.resource.mimeType,\n },\n accepts: raw.accepts.map(normalizeAccept),\n extensions: raw.extensions ?? undefined,\n }\n }\n\n // v1 shape: maxAmountRequired, inline resource/description on each accept\n if (typeof firstAccept.maxAmountRequired === \"string\") {\n return {\n x402Version: raw.x402Version ?? 1,\n resource: {\n url: firstAccept.resource ?? raw.resource?.url ?? \"\",\n description: firstAccept.description ?? raw.resource?.description,\n mimeType: firstAccept.mimeType ?? raw.resource?.mimeType,\n },\n accepts: raw.accepts.map((a: Record<string, unknown>) => normalizeAccept({\n ...a,\n amount: a.maxAmountRequired,\n })),\n extensions: raw.extensions ?? undefined,\n }\n }\n\n return null\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalizeAccept(a: any): PaymentOption {\n return {\n scheme: a.scheme ?? \"exact\",\n network: a.network ?? \"\",\n asset: a.asset ?? \"\",\n amount: String(a.amount ?? a.maxAmountRequired ?? \"0\"),\n payTo: a.payTo ?? \"\",\n maxTimeoutSeconds: a.maxTimeoutSeconds ?? 0,\n extra: a.extra ?? undefined,\n }\n}\n","import type { DiscoverResult, DiscoverOptions, BazaarService, PaymentOption } from \"./types.js\"\nimport { formatPrice } from \"./format.js\"\n\nconst DEFAULT_BAZAAR_URL = \"https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources\"\n\n/**\n * Query the Bazaar registry to find available x402 services.\n *\n * Fetches from the Coinbase CDP Bazaar discovery endpoint and returns\n * a normalized list of services with human-readable pricing.\n *\n * No wallet or authentication needed.\n */\nexport async function discover(options?: DiscoverOptions): Promise<DiscoverResult> {\n const baseUrl = options?.bazaarUrl ?? DEFAULT_BAZAAR_URL\n const params = new URLSearchParams()\n if (options?.limit != null) params.set(\"limit\", String(options.limit))\n if (options?.offset != null) params.set(\"offset\", String(options.offset))\n\n const url = params.toString() ? `${baseUrl}?${params}` : baseUrl\n\n const res = await fetch(url, {\n headers: { Accept: \"application/json\" },\n signal: options?.signal,\n })\n\n if (!res.ok) {\n const text = await res.text().catch(() => \"\")\n throw new Error(`Bazaar request failed (${res.status}): ${text}`)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const json = (await res.json()) as any\n\n // The Bazaar response has an `items` array (or `resources`)\n const items: unknown[] = json.items ?? json.resources ?? []\n\n const services: BazaarService[] = items.map(normalizeBazaarItem).filter(Boolean) as BazaarService[]\n\n return {\n services,\n total: json.total ?? json.totalCount ?? services.length,\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalizeBazaarItem(item: any): BazaarService | null {\n if (!item || typeof item !== \"object\") return null\n\n const accepts: unknown[] = item.accepts ?? []\n if (accepts.length === 0) return null\n\n const normalizedAccepts: PaymentOption[] = accepts.map((a: unknown) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const accept = a as any\n return {\n scheme: accept.scheme ?? \"exact\",\n network: accept.network ?? \"\",\n asset: accept.asset ?? \"\",\n amount: String(accept.amount ?? accept.maxAmountRequired ?? \"0\"),\n payTo: accept.payTo ?? \"\",\n maxTimeoutSeconds: accept.maxTimeoutSeconds ?? 0,\n extra: accept.extra ?? undefined,\n }\n })\n\n // Find cheapest option for display price\n const cheapest = normalizedAccepts.reduce((min, a) =>\n BigInt(a.amount) < BigInt(min.amount) ? a : min\n )\n const price = formatPrice(cheapest.amount, cheapest.asset, cheapest.network)\n\n // Extract description from various possible locations\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const firstAccept = accepts[0] as any\n const description: string | null =\n item.description ??\n item.resource?.description ??\n firstAccept?.description ??\n item.metadata?.description ??\n null\n\n // Extract URL\n const url: string =\n item.url ??\n item.resource?.url ??\n (typeof item.resource === \"string\" ? item.resource : null) ??\n firstAccept?.resource ??\n \"\"\n\n return {\n url,\n description,\n price,\n accepts: normalizedAccepts,\n metadata: item.metadata ?? {},\n }\n}\n","// Internal — used by wallet module\nexport { createPaymentFetch } from \"./payment-fetch.js\"\n\n// Public x402 convenience functions\nimport { probe } from \"./probe.js\"\nimport { discover } from \"./discover.js\"\nimport { formatPrice } from \"./format.js\"\n\nexport const x402 = {\n probe,\n discover,\n formatPrice,\n}\n\nexport type {\n ProbeResult,\n ProbeOptions,\n PaymentRequiredResponse,\n PaymentOption,\n BazaarService,\n DiscoverResult,\n DiscoverOptions,\n FormatPriceOptions,\n} from \"./types.js\"\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,oBAA8B;;;ACA9B,sBAAwD;AAGjD,SAAS,gBAGd;AACA,QAAM,iBAAa,oCAAmB;AACtC,QAAM,cAAU,qCAAoB,UAAU;AAC9C,SAAO,EAAE,YAAY,QAAQ;AAC/B;AAEO,SAAS,YAAY,YAE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ACf,WAAO;AAAA,MACL,QAAQ,OAAO,UAAU;AAAA,MACzB,SAAS,OAAO,WAAW;AAAA,MAC3B,OAAO,OAAO,SAAS;AAAA,MACvB,QAAQ,OAAO,OAAO,UAAU,OAAO,qBAAqB,GAAG;AAAA,MAC/D,OAAO,OAAO,SAAS;AAAA,MACvB,mBAAmB,OAAO,qBAAqB;AAAA,MAC/C,OAAO,OAAO,SAAS;AAAA,IACzB;AAAA,EACF,CAAC;AAGD,QAAM,WAAW,kBAAkB;AAAA,IAAO,CAAC,KAAK,MAC9C,OAAO,EAAE,MAAM,IAAI,OAAO,IAAI,MAAM,IAAI,IAAI;AAAA,EAC9C;AACA,QAAM,QAAQ,YAAY,SAAS,QAAQ,SAAS,OAAO,SAAS,OAAO;AAI3E,QAAM,cAAc,QAAQ,CAAC;AAC7B,QAAM,cACJ,KAAK,eACL,KAAK,UAAU,eACf,aAAa,eACb,KAAK,UAAU,eACf;AAGF,QAAM,MACJ,KAAK,OACL,KAAK,UAAU,QACd,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW,SACrD,aAAa,YACb;AAEF,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT,UAAU,KAAK,YAAY,CAAC;AAAA,EAC9B;AACF;;;ACzFO,IAAM,OAAO;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AACF;","names":["import_node_path","import_client","import_accounts"]}
package/dist/index.mjs CHANGED
@@ -52,7 +52,7 @@ function migrateLegacyWallet(walletsDir) {
52
52
  return null;
53
53
  }
54
54
 
55
- // src/x402/index.ts
55
+ // src/x402/payment-fetch.ts
56
56
  import { x402Client } from "@x402/core/client";
57
57
  import { registerExactEvmScheme } from "@x402/evm/exact/client";
58
58
  import { toClientEvmSigner } from "@x402/evm";
@@ -321,9 +321,173 @@ var compute = {
321
321
  _endpoint = url;
322
322
  }
323
323
  };
324
+
325
+ // src/x402/format.ts
326
+ var KNOWN_ASSETS = {
327
+ // USDC on Base mainnet
328
+ "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913": { symbol: "USDC", decimals: 6, prefix: "$" },
329
+ // USDC on Base Sepolia
330
+ "0x036cbd53842c5426634e7929541ec2318f3dcf7e": { symbol: "USDC", decimals: 6, prefix: "$" }
331
+ };
332
+ var NETWORK_NAMES = {
333
+ "eip155:8453": "Base",
334
+ "eip155:84532": "Base Sepolia",
335
+ "base": "Base",
336
+ "base-sepolia": "Base Sepolia"
337
+ };
338
+ function formatPrice(amount, asset, network, options) {
339
+ const known = KNOWN_ASSETS[asset.toLowerCase()];
340
+ const networkName = NETWORK_NAMES[network];
341
+ if (known) {
342
+ const value = Number(amount) / 10 ** known.decimals;
343
+ const formatted = `${known.prefix}${value} ${known.symbol}`;
344
+ if (options?.short || !networkName) return formatted;
345
+ return `${formatted} on ${networkName}`;
346
+ }
347
+ const shortAsset = `${asset.slice(0, 6)}...${asset.slice(-4)}`;
348
+ const raw = `${amount} ${shortAsset}`;
349
+ if (options?.short || !networkName) return raw;
350
+ return `${raw} on ${networkName}`;
351
+ }
352
+
353
+ // src/x402/probe.ts
354
+ async function probe(url, options) {
355
+ const res = await fetch(url, {
356
+ method: options?.method ?? "GET",
357
+ headers: options?.headers,
358
+ body: options?.body,
359
+ signal: options?.signal
360
+ });
361
+ if (res.status !== 402) {
362
+ return { enabled: false, url, status: res.status, price: null, paymentRequired: null };
363
+ }
364
+ let raw;
365
+ try {
366
+ raw = await res.json();
367
+ } catch {
368
+ return { enabled: false, url, status: 402, price: null, paymentRequired: null };
369
+ }
370
+ const paymentRequired = normalizePaymentRequired(raw);
371
+ if (!paymentRequired || paymentRequired.accepts.length === 0) {
372
+ return { enabled: false, url, status: 402, price: null, paymentRequired: null };
373
+ }
374
+ const first = paymentRequired.accepts[0];
375
+ const price = formatPrice(first.amount, first.asset, first.network);
376
+ return { enabled: true, url, status: 402, price, paymentRequired };
377
+ }
378
+ function normalizePaymentRequired(raw) {
379
+ if (!raw || typeof raw !== "object" || !Array.isArray(raw.accepts) || raw.accepts.length === 0) {
380
+ return null;
381
+ }
382
+ const firstAccept = raw.accepts[0];
383
+ const isV2 = typeof firstAccept.amount === "string" && raw.resource && typeof raw.resource === "object";
384
+ if (isV2) {
385
+ return {
386
+ x402Version: raw.x402Version ?? 2,
387
+ resource: {
388
+ url: raw.resource.url ?? "",
389
+ description: raw.resource.description,
390
+ mimeType: raw.resource.mimeType
391
+ },
392
+ accepts: raw.accepts.map(normalizeAccept),
393
+ extensions: raw.extensions ?? void 0
394
+ };
395
+ }
396
+ if (typeof firstAccept.maxAmountRequired === "string") {
397
+ return {
398
+ x402Version: raw.x402Version ?? 1,
399
+ resource: {
400
+ url: firstAccept.resource ?? raw.resource?.url ?? "",
401
+ description: firstAccept.description ?? raw.resource?.description,
402
+ mimeType: firstAccept.mimeType ?? raw.resource?.mimeType
403
+ },
404
+ accepts: raw.accepts.map((a) => normalizeAccept({
405
+ ...a,
406
+ amount: a.maxAmountRequired
407
+ })),
408
+ extensions: raw.extensions ?? void 0
409
+ };
410
+ }
411
+ return null;
412
+ }
413
+ function normalizeAccept(a) {
414
+ return {
415
+ scheme: a.scheme ?? "exact",
416
+ network: a.network ?? "",
417
+ asset: a.asset ?? "",
418
+ amount: String(a.amount ?? a.maxAmountRequired ?? "0"),
419
+ payTo: a.payTo ?? "",
420
+ maxTimeoutSeconds: a.maxTimeoutSeconds ?? 0,
421
+ extra: a.extra ?? void 0
422
+ };
423
+ }
424
+
425
+ // src/x402/discover.ts
426
+ var DEFAULT_BAZAAR_URL = "https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources";
427
+ async function discover(options) {
428
+ const baseUrl = options?.bazaarUrl ?? DEFAULT_BAZAAR_URL;
429
+ const params = new URLSearchParams();
430
+ if (options?.limit != null) params.set("limit", String(options.limit));
431
+ if (options?.offset != null) params.set("offset", String(options.offset));
432
+ const url = params.toString() ? `${baseUrl}?${params}` : baseUrl;
433
+ const res = await fetch(url, {
434
+ headers: { Accept: "application/json" },
435
+ signal: options?.signal
436
+ });
437
+ if (!res.ok) {
438
+ const text = await res.text().catch(() => "");
439
+ throw new Error(`Bazaar request failed (${res.status}): ${text}`);
440
+ }
441
+ const json = await res.json();
442
+ const items = json.items ?? json.resources ?? [];
443
+ const services = items.map(normalizeBazaarItem).filter(Boolean);
444
+ return {
445
+ services,
446
+ total: json.total ?? json.totalCount ?? services.length
447
+ };
448
+ }
449
+ function normalizeBazaarItem(item) {
450
+ if (!item || typeof item !== "object") return null;
451
+ const accepts = item.accepts ?? [];
452
+ if (accepts.length === 0) return null;
453
+ const normalizedAccepts = accepts.map((a) => {
454
+ const accept = a;
455
+ return {
456
+ scheme: accept.scheme ?? "exact",
457
+ network: accept.network ?? "",
458
+ asset: accept.asset ?? "",
459
+ amount: String(accept.amount ?? accept.maxAmountRequired ?? "0"),
460
+ payTo: accept.payTo ?? "",
461
+ maxTimeoutSeconds: accept.maxTimeoutSeconds ?? 0,
462
+ extra: accept.extra ?? void 0
463
+ };
464
+ });
465
+ const cheapest = normalizedAccepts.reduce(
466
+ (min, a) => BigInt(a.amount) < BigInt(min.amount) ? a : min
467
+ );
468
+ const price = formatPrice(cheapest.amount, cheapest.asset, cheapest.network);
469
+ const firstAccept = accepts[0];
470
+ const description = item.description ?? item.resource?.description ?? firstAccept?.description ?? item.metadata?.description ?? null;
471
+ const url = item.url ?? item.resource?.url ?? (typeof item.resource === "string" ? item.resource : null) ?? firstAccept?.resource ?? "";
472
+ return {
473
+ url,
474
+ description,
475
+ price,
476
+ accepts: normalizedAccepts,
477
+ metadata: item.metadata ?? {}
478
+ };
479
+ }
480
+
481
+ // src/x402/index.ts
482
+ var x402 = {
483
+ probe,
484
+ discover,
485
+ formatPrice
486
+ };
324
487
  export {
325
488
  Wallet,
326
489
  compute,
327
- wallet
490
+ wallet,
491
+ x402
328
492
  };
329
493
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/wallet/index.ts","../src/wallet/keypair.ts","../src/wallet/storage.ts","../src/x402/index.ts","../src/wallet/types.ts","../src/wallet/balance.ts","../src/wallet/wallet.ts","../src/compute/index.ts"],"sourcesContent":["import { join, resolve } from \"node:path\"\nimport { createKeypair, loadKeypair } from \"./keypair.js\"\nimport { readWalletFile, writeWalletFile, listWalletFiles, migrateLegacyWallet, validateWalletName } from \"./storage.js\"\nimport { createPaymentFetch } from \"../x402/index.js\"\nimport { Wallet } from \"./wallet.js\"\nimport type { CreateWalletOptions } from \"./types.js\"\n\nconst DEFAULT_WALLETS_DIR = \".auteng/wallets\"\n\nconst _wallets = new Map<string, Wallet>()\nlet _walletsDir = resolve(DEFAULT_WALLETS_DIR)\n\nexport const wallet = {\n /**\n * Create a new named wallet or load an existing one from disk.\n * Idempotent: if a wallet with this name already exists, returns it.\n */\n async create(opts?: CreateWalletOptions): Promise<Wallet> {\n const name = opts?.name ?? \"default\"\n validateWalletName(name)\n\n if (_wallets.has(name)) return _wallets.get(name)!\n\n const dir = resolve(opts?.walletsDir ?? DEFAULT_WALLETS_DIR)\n _walletsDir = dir\n const filePath = join(dir, `${name}.json`)\n const network = opts?.network ?? \"base\"\n const rpcUrl = opts?.rpcUrl\n\n let existing = readWalletFile(filePath)\n\n if (!existing && name === \"default\") {\n existing = migrateLegacyWallet(dir)\n }\n\n let privateKey: `0x${string}`\n let account: ReturnType<typeof loadKeypair>[\"account\"]\n\n if (existing) {\n privateKey = existing.privateKey\n account = loadKeypair(existing.privateKey).account\n } else {\n const kp = createKeypair()\n privateKey = kp.privateKey\n account = kp.account\n writeWalletFile(filePath, {\n privateKey,\n address: account.address,\n network,\n })\n }\n\n const effectiveNetwork = existing?.network ?? network\n const paymentFetch = createPaymentFetch(privateKey, effectiveNetwork, rpcUrl)\n const w = new Wallet({\n name,\n account,\n privateKey,\n network: effectiveNetwork,\n rpcUrl,\n paymentFetch,\n })\n _wallets.set(name, w)\n return w\n },\n\n /**\n * Retrieve a previously-created wallet by name.\n * Loads from disk if not in memory. Throws if not found.\n */\n get(name: string): Wallet {\n validateWalletName(name)\n\n if (_wallets.has(name)) return _wallets.get(name)!\n\n const filePath = join(_walletsDir, `${name}.json`)\n const data = readWalletFile(filePath)\n if (!data) throw new Error(`Wallet \"${name}\" not found`)\n\n const { account } = loadKeypair(data.privateKey)\n const paymentFetch = createPaymentFetch(data.privateKey, data.network)\n const w = new Wallet({\n name,\n account,\n privateKey: data.privateKey,\n network: data.network,\n paymentFetch,\n })\n _wallets.set(name, w)\n return w\n },\n\n /** List all persisted wallets. */\n list(): Wallet[] {\n const names = listWalletFiles(_walletsDir)\n return names.map((n) => {\n if (_wallets.has(n)) return _wallets.get(n)!\n return wallet.get(n)\n })\n },\n\n /** @internal Clear in-memory cache and reset wallets dir. For testing only. */\n _reset(): void {\n _wallets.clear()\n _walletsDir = resolve(DEFAULT_WALLETS_DIR)\n },\n}\n","import { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\"\nimport type { PrivateKeyAccount } from \"viem\"\n\nexport function createKeypair(): {\n privateKey: `0x${string}`\n account: PrivateKeyAccount\n} {\n const privateKey = generatePrivateKey()\n const account = privateKeyToAccount(privateKey)\n return { privateKey, account }\n}\n\nexport function loadKeypair(privateKey: `0x${string}`): {\n account: PrivateKeyAccount\n} {\n const account = privateKeyToAccount(privateKey)\n return { account }\n}\n","import { mkdirSync, readFileSync, writeFileSync, existsSync, readdirSync, copyFileSync } from \"node:fs\"\nimport { dirname, join, resolve } from \"node:path\"\nimport type { WalletFile } from \"./types.js\"\n\nconst VALID_NAME = /^[a-z0-9_-]+$/\n\nexport function validateWalletName(name: string): void {\n if (!VALID_NAME.test(name)) {\n throw new Error(`Invalid wallet name \"${name}\". Use lowercase letters, numbers, hyphens, and underscores only.`)\n }\n}\n\nexport function readWalletFile(path: string): WalletFile | null {\n if (!existsSync(path)) return null\n const raw = readFileSync(path, \"utf-8\")\n return JSON.parse(raw) as WalletFile\n}\n\nexport function writeWalletFile(path: string, data: WalletFile): void {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(data, null, 2) + \"\\n\", {\n mode: 0o600,\n })\n}\n\nexport function listWalletFiles(dir: string): string[] {\n const resolved = resolve(dir)\n if (!existsSync(resolved)) return []\n return readdirSync(resolved)\n .filter((f) => f.endsWith(\".json\"))\n .map((f) => f.replace(/\\.json$/, \"\"))\n}\n\nexport function migrateLegacyWallet(walletsDir: string): WalletFile | null {\n const legacyPath = resolve(walletsDir, \"..\", \"wallet.json\")\n const newPath = join(resolve(walletsDir), \"default.json\")\n if (existsSync(legacyPath) && !existsSync(newPath)) {\n const data = readWalletFile(legacyPath)\n if (data) {\n mkdirSync(resolve(walletsDir), { recursive: true })\n copyFileSync(legacyPath, newPath)\n return data\n }\n }\n return null\n}\n","import { x402Client } from \"@x402/core/client\"\nimport { registerExactEvmScheme } from \"@x402/evm/exact/client\"\nimport { toClientEvmSigner } from \"@x402/evm\"\nimport { wrapFetchWithPayment } from \"@x402/fetch\"\nimport { privateKeyToAccount } from \"viem/accounts\"\nimport { createPublicClient, http } from \"viem\"\nimport { base, baseSepolia } from \"viem/chains\"\nimport type { Network } from \"../wallet/types.js\"\n\n/**\n * Create a fetch function that automatically handles x402 payments.\n * When the server returns 402, the SDK signs an EIP-3009 authorization\n * using the provided private key and retries with payment headers.\n */\nexport function createPaymentFetch(\n privateKey: `0x${string}`,\n network: Network = \"base\",\n rpcUrl?: string\n): typeof globalThis.fetch {\n const account = privateKeyToAccount(privateKey)\n const chain = network === \"base\" ? base : baseSepolia\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl),\n })\n const signer = toClientEvmSigner(account, publicClient)\n\n const client = new x402Client()\n registerExactEvmScheme(client, { signer })\n return wrapFetchWithPayment(fetch, client)\n}\n","export type Network = \"base\" | \"base-sepolia\"\n\nexport interface CreateWalletOptions {\n /** Wallet identifier. Default: \"default\" */\n name?: string\n /** Network to use. Default: `base` */\n network?: Network\n /** Custom RPC endpoint. Default: public Base RPC */\n rpcUrl?: string\n /** Base directory for wallet storage. Default: \".auteng/wallets\" */\n walletsDir?: string\n}\n\n/** @deprecated Use CreateWalletOptions instead */\nexport type WalletConfig = CreateWalletOptions\n\nexport interface WalletFile {\n privateKey: `0x${string}`\n address: `0x${string}`\n network: Network\n}\n\nexport interface WaitForFundingOptions {\n /** Poll interval in milliseconds. Default: 10000 (10s) */\n pollInterval?: number\n /** Timeout in milliseconds. Default: none (waits forever) */\n timeout?: number\n}\n\nexport const NETWORK_CONFIG: Record<Network, { chainId: number; usdcAddress: `0x${string}`; rpcUrl: string }> = {\n base: {\n chainId: 8453,\n usdcAddress: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n rpcUrl: \"https://mainnet.base.org\",\n },\n \"base-sepolia\": {\n chainId: 84532,\n usdcAddress: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n rpcUrl: \"https://sepolia.base.org\",\n },\n}\n","import type { Network } from \"./types.js\"\nimport { NETWORK_CONFIG } from \"./types.js\"\n\n/**\n * Read USDC balance for `address` via a direct `eth_call` to the USDC\n * contract's `balanceOf(address)` function. No viem client needed — just\n * a plain JSON-RPC POST.\n */\nexport async function getUsdcBalance(address: `0x${string}`, network: Network, rpcUrl?: string): Promise<bigint> {\n const config = NETWORK_CONFIG[network]\n const url = rpcUrl ?? config.rpcUrl\n\n // balanceOf(address) selector = 0x70a08231\n const paddedAddress = address.slice(2).toLowerCase().padStart(64, \"0\")\n const data = `0x70a08231${paddedAddress}`\n\n const res = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"eth_call\",\n params: [{ to: config.usdcAddress, data }, \"latest\"],\n }),\n })\n\n const json = (await res.json()) as { result?: string; error?: unknown }\n if (json.error) {\n throw new Error(`RPC error: ${JSON.stringify(json.error)}`)\n }\n return BigInt(json.result ?? \"0x0\")\n}\n","import type { PrivateKeyAccount } from \"viem\"\nimport { getUsdcBalance } from \"./balance.js\"\nimport type { Network, WaitForFundingOptions } from \"./types.js\"\n\nexport class Wallet {\n readonly name: string\n readonly address: `0x${string}`\n readonly network: Network\n\n private _account: PrivateKeyAccount\n private _privateKey: `0x${string}`\n private _rpcUrl: string | undefined\n private _paymentFetch: typeof globalThis.fetch\n\n constructor(params: {\n name: string\n account: PrivateKeyAccount\n privateKey: `0x${string}`\n network: Network\n rpcUrl?: string\n paymentFetch: typeof globalThis.fetch\n }) {\n this.name = params.name\n this._account = params.account\n this._privateKey = params.privateKey\n this.address = params.account.address\n this.network = params.network\n this._rpcUrl = params.rpcUrl\n this._paymentFetch = params.paymentFetch\n }\n\n /** Check USDC balance on Base. Returns balance in minor units (6 decimals). */\n async checkBalance(): Promise<bigint> {\n return getUsdcBalance(this._account.address, this.network, this._rpcUrl)\n }\n\n /**\n * Poll until USDC balance >= minAmount.\n * @param minAmount - minimum USDC balance in minor units (6 decimals)\n */\n async waitForFunding(minAmount: bigint, opts?: WaitForFundingOptions): Promise<void> {\n const interval = opts?.pollInterval ?? 10_000\n const deadline = opts?.timeout ? Date.now() + opts.timeout : null\n\n while (true) {\n const balance = await getUsdcBalance(this._account.address, this.network, this._rpcUrl)\n if (balance >= minAmount) return\n\n if (deadline && Date.now() >= deadline) {\n throw new Error(`Funding timeout: balance ${balance} < required ${minAmount}`)\n }\n\n await new Promise((r) => setTimeout(r, interval))\n }\n }\n\n /**\n * Drop-in `fetch()` replacement that handles x402 payments automatically.\n * If the server returns 402, the library signs an EIP-3009 authorization\n * and retries the request with payment headers.\n */\n async fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {\n return this._paymentFetch(input, init)\n }\n}\n","import type { ComputeRequest, ComputeResponse, PricingTier, Size } from \"./types.js\"\n\nconst DEFAULT_ENDPOINT = \"https://x402.auteng.ai/api/x402/compute\"\n\nlet _endpoint = DEFAULT_ENDPOINT\n\nconst PRICING: Record<Size, PricingTier> = {\n small: {\n vcpu: 2,\n ram_gb: 1,\n default_timeout_s: 30,\n max_timeout_s: 300,\n base_price_usd: 0.002,\n per_second_usd: 0.00005,\n },\n med: {\n vcpu: 4,\n ram_gb: 4,\n default_timeout_s: 60,\n max_timeout_s: 600,\n base_price_usd: 0.008,\n per_second_usd: 0.00012,\n },\n large: {\n vcpu: 8,\n ram_gb: 16,\n default_timeout_s: 120,\n max_timeout_s: 3600,\n base_price_usd: 0.03,\n per_second_usd: 0.00025,\n },\n}\n\nexport const compute = {\n /**\n * Execute sandboxed code via AutEng's x402 compute endpoint.\n * Payment is handled automatically via the wallet's x402 layer.\n */\n async run(request: ComputeRequest): Promise<ComputeResponse> {\n if (!request.code) {\n throw new Error(\"compute.run: 'code' is required\")\n }\n if (!request.stack) {\n throw new Error(\"compute.run: 'stack' is required\")\n }\n\n const body = {\n code: request.code,\n stack: request.stack,\n size: request.size ?? \"small\",\n ...(request.timeout_seconds != null && {\n timeout_seconds: request.timeout_seconds,\n }),\n ...(request.files != null && { files: request.files }),\n }\n\n if (!request.wallet) {\n throw new Error(\"compute.run: 'wallet' is required\")\n }\n\n const response = await request.wallet.fetch(_endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n })\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\")\n throw new Error(`Compute request failed (${response.status}): ${text}`)\n }\n\n return (await response.json()) as ComputeResponse\n },\n\n /** Returns the pricing table for all compute sizes. */\n pricing(): Record<Size, PricingTier> {\n return { ...PRICING }\n },\n\n /**\n * Override the compute endpoint URL.\n * Default: https://x402.auteng.ai/api/x402/compute\n */\n setEndpoint(url: string): void {\n _endpoint = url\n },\n}\n"],"mappings":";AAAA,SAAS,QAAAA,OAAM,WAAAC,gBAAe;;;ACA9B,SAAS,oBAAoB,2BAA2B;AAGjD,SAAS,gBAGd;AACA,QAAM,aAAa,mBAAmB;AACtC,QAAM,UAAU,oBAAoB,UAAU;AAC9C,SAAO,EAAE,YAAY,QAAQ;AAC/B;AAEO,SAAS,YAAY,YAE1B;AACA,QAAM,UAAU,oBAAoB,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AAM,IAAI,MAAM,iCAAiC;AAAA,IACnD;AACA,QAAI,CAAC,QAAQ,OAAO;AAClB,YAAM,IAAI,MAAM,kCAAkC;AAAA,IACpD;AAEA,UAAM,OAAO;AAAA,MACX,MAAM,QAAQ;AAAA,MACd,OAAO,QAAQ;AAAA,MACf,MAAM,QAAQ,QAAQ;AAAA,MACtB,GAAI,QAAQ,mBAAmB,QAAQ;AAAA,QACrC,iBAAiB,QAAQ;AAAA,MAC3B;AAAA,MACA,GAAI,QAAQ,SAAS,QAAQ,EAAE,OAAO,QAAQ,MAAM;AAAA,IACtD;AAEA,QAAI,CAAC,QAAQ,QAAQ;AACnB,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AAEA,UAAM,WAAW,MAAM,QAAQ,OAAO,MAAM,WAAW;AAAA,MACrD,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAC9C,MAAM,KAAK,UAAU,IAAI;AAAA,IAC3B,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,OAAO,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,EAAE;AACjD,YAAM,IAAI,MAAM,2BAA2B,SAAS,MAAM,MAAM,IAAI,EAAE;AAAA,IACxE;AAEA,WAAQ,MAAM,SAAS,KAAK;AAAA,EAC9B;AAAA;AAAA,EAGA,UAAqC;AACnC,WAAO,EAAE,GAAG,QAAQ;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAY,KAAmB;AAC7B,gBAAY;AAAA,EACd;AACF;","names":["join","resolve","privateKeyToAccount","resolve","join"]}
1
+ {"version":3,"sources":["../src/wallet/index.ts","../src/wallet/keypair.ts","../src/wallet/storage.ts","../src/x402/payment-fetch.ts","../src/wallet/types.ts","../src/wallet/balance.ts","../src/wallet/wallet.ts","../src/compute/index.ts","../src/x402/format.ts","../src/x402/probe.ts","../src/x402/discover.ts","../src/x402/index.ts"],"sourcesContent":["import { join, resolve } from \"node:path\"\nimport { createKeypair, loadKeypair } from \"./keypair.js\"\nimport { readWalletFile, writeWalletFile, listWalletFiles, migrateLegacyWallet, validateWalletName } from \"./storage.js\"\nimport { createPaymentFetch } from \"../x402/payment-fetch.js\"\nimport { Wallet } from \"./wallet.js\"\nimport type { CreateWalletOptions } from \"./types.js\"\n\nconst DEFAULT_WALLETS_DIR = \".auteng/wallets\"\n\nconst _wallets = new Map<string, Wallet>()\nlet _walletsDir = resolve(DEFAULT_WALLETS_DIR)\n\nexport const wallet = {\n /**\n * Create a new named wallet or load an existing one from disk.\n * Idempotent: if a wallet with this name already exists, returns it.\n */\n async create(opts?: CreateWalletOptions): Promise<Wallet> {\n const name = opts?.name ?? \"default\"\n validateWalletName(name)\n\n if (_wallets.has(name)) return _wallets.get(name)!\n\n const dir = resolve(opts?.walletsDir ?? DEFAULT_WALLETS_DIR)\n _walletsDir = dir\n const filePath = join(dir, `${name}.json`)\n const network = opts?.network ?? \"base\"\n const rpcUrl = opts?.rpcUrl\n\n let existing = readWalletFile(filePath)\n\n if (!existing && name === \"default\") {\n existing = migrateLegacyWallet(dir)\n }\n\n let privateKey: `0x${string}`\n let account: ReturnType<typeof loadKeypair>[\"account\"]\n\n if (existing) {\n privateKey = existing.privateKey\n account = loadKeypair(existing.privateKey).account\n } else {\n const kp = createKeypair()\n privateKey = kp.privateKey\n account = kp.account\n writeWalletFile(filePath, {\n privateKey,\n address: account.address,\n network,\n })\n }\n\n const effectiveNetwork = existing?.network ?? network\n const paymentFetch = createPaymentFetch(privateKey, effectiveNetwork, rpcUrl)\n const w = new Wallet({\n name,\n account,\n privateKey,\n network: effectiveNetwork,\n rpcUrl,\n paymentFetch,\n })\n _wallets.set(name, w)\n return w\n },\n\n /**\n * Retrieve a previously-created wallet by name.\n * Loads from disk if not in memory. Throws if not found.\n */\n get(name: string): Wallet {\n validateWalletName(name)\n\n if (_wallets.has(name)) return _wallets.get(name)!\n\n const filePath = join(_walletsDir, `${name}.json`)\n const data = readWalletFile(filePath)\n if (!data) throw new Error(`Wallet \"${name}\" not found`)\n\n const { account } = loadKeypair(data.privateKey)\n const paymentFetch = createPaymentFetch(data.privateKey, data.network)\n const w = new Wallet({\n name,\n account,\n privateKey: data.privateKey,\n network: data.network,\n paymentFetch,\n })\n _wallets.set(name, w)\n return w\n },\n\n /** List all persisted wallets. */\n list(): Wallet[] {\n const names = listWalletFiles(_walletsDir)\n return names.map((n) => {\n if (_wallets.has(n)) return _wallets.get(n)!\n return wallet.get(n)\n })\n },\n\n /** @internal Clear in-memory cache and reset wallets dir. For testing only. */\n _reset(): void {\n _wallets.clear()\n _walletsDir = resolve(DEFAULT_WALLETS_DIR)\n },\n}\n","import { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\"\nimport type { PrivateKeyAccount } from \"viem\"\n\nexport function createKeypair(): {\n privateKey: `0x${string}`\n account: PrivateKeyAccount\n} {\n const privateKey = generatePrivateKey()\n const account = privateKeyToAccount(privateKey)\n return { privateKey, account }\n}\n\nexport function loadKeypair(privateKey: `0x${string}`): {\n account: PrivateKeyAccount\n} {\n const account = privateKeyToAccount(privateKey)\n return { account }\n}\n","import { mkdirSync, readFileSync, writeFileSync, existsSync, readdirSync, copyFileSync } from \"node:fs\"\nimport { dirname, join, resolve } from \"node:path\"\nimport type { WalletFile } from \"./types.js\"\n\nconst VALID_NAME = /^[a-z0-9_-]+$/\n\nexport function validateWalletName(name: string): void {\n if (!VALID_NAME.test(name)) {\n throw new Error(`Invalid wallet name \"${name}\". Use lowercase letters, numbers, hyphens, and underscores only.`)\n }\n}\n\nexport function readWalletFile(path: string): WalletFile | null {\n if (!existsSync(path)) return null\n const raw = readFileSync(path, \"utf-8\")\n return JSON.parse(raw) as WalletFile\n}\n\nexport function writeWalletFile(path: string, data: WalletFile): void {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(data, null, 2) + \"\\n\", {\n mode: 0o600,\n })\n}\n\nexport function listWalletFiles(dir: string): string[] {\n const resolved = resolve(dir)\n if (!existsSync(resolved)) return []\n return readdirSync(resolved)\n .filter((f) => f.endsWith(\".json\"))\n .map((f) => f.replace(/\\.json$/, \"\"))\n}\n\nexport function migrateLegacyWallet(walletsDir: string): WalletFile | null {\n const legacyPath = resolve(walletsDir, \"..\", \"wallet.json\")\n const newPath = join(resolve(walletsDir), \"default.json\")\n if (existsSync(legacyPath) && !existsSync(newPath)) {\n const data = readWalletFile(legacyPath)\n if (data) {\n mkdirSync(resolve(walletsDir), { recursive: true })\n copyFileSync(legacyPath, newPath)\n return data\n }\n }\n return null\n}\n","import { x402Client } from \"@x402/core/client\"\nimport { registerExactEvmScheme } from \"@x402/evm/exact/client\"\nimport { toClientEvmSigner } from \"@x402/evm\"\nimport { wrapFetchWithPayment } from \"@x402/fetch\"\nimport { privateKeyToAccount } from \"viem/accounts\"\nimport { createPublicClient, http } from \"viem\"\nimport { base, baseSepolia } from \"viem/chains\"\nimport type { Network } from \"../wallet/types.js\"\n\n/**\n * Create a fetch function that automatically handles x402 payments.\n * When the server returns 402, the SDK signs an EIP-3009 authorization\n * using the provided private key and retries with payment headers.\n */\nexport function createPaymentFetch(\n privateKey: `0x${string}`,\n network: Network = \"base\",\n rpcUrl?: string\n): typeof globalThis.fetch {\n const account = privateKeyToAccount(privateKey)\n const chain = network === \"base\" ? base : baseSepolia\n const publicClient = createPublicClient({\n chain,\n transport: http(rpcUrl),\n })\n const signer = toClientEvmSigner(account, publicClient)\n\n const client = new x402Client()\n registerExactEvmScheme(client, { signer })\n return wrapFetchWithPayment(fetch, client)\n}\n","export type Network = \"base\" | \"base-sepolia\"\n\nexport interface CreateWalletOptions {\n /** Wallet identifier. Default: \"default\" */\n name?: string\n /** Network to use. Default: `base` */\n network?: Network\n /** Custom RPC endpoint. Default: public Base RPC */\n rpcUrl?: string\n /** Base directory for wallet storage. Default: \".auteng/wallets\" */\n walletsDir?: string\n}\n\n/** @deprecated Use CreateWalletOptions instead */\nexport type WalletConfig = CreateWalletOptions\n\nexport interface WalletFile {\n privateKey: `0x${string}`\n address: `0x${string}`\n network: Network\n}\n\nexport interface WaitForFundingOptions {\n /** Poll interval in milliseconds. Default: 10000 (10s) */\n pollInterval?: number\n /** Timeout in milliseconds. Default: none (waits forever) */\n timeout?: number\n}\n\nexport const NETWORK_CONFIG: Record<Network, { chainId: number; usdcAddress: `0x${string}`; rpcUrl: string }> = {\n base: {\n chainId: 8453,\n usdcAddress: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n rpcUrl: \"https://mainnet.base.org\",\n },\n \"base-sepolia\": {\n chainId: 84532,\n usdcAddress: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n rpcUrl: \"https://sepolia.base.org\",\n },\n}\n","import type { Network } from \"./types.js\"\nimport { NETWORK_CONFIG } from \"./types.js\"\n\n/**\n * Read USDC balance for `address` via a direct `eth_call` to the USDC\n * contract's `balanceOf(address)` function. No viem client needed — just\n * a plain JSON-RPC POST.\n */\nexport async function getUsdcBalance(address: `0x${string}`, network: Network, rpcUrl?: string): Promise<bigint> {\n const config = NETWORK_CONFIG[network]\n const url = rpcUrl ?? config.rpcUrl\n\n // balanceOf(address) selector = 0x70a08231\n const paddedAddress = address.slice(2).toLowerCase().padStart(64, \"0\")\n const data = `0x70a08231${paddedAddress}`\n\n const res = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"eth_call\",\n params: [{ to: config.usdcAddress, data }, \"latest\"],\n }),\n })\n\n const json = (await res.json()) as { result?: string; error?: unknown }\n if (json.error) {\n throw new Error(`RPC error: ${JSON.stringify(json.error)}`)\n }\n return BigInt(json.result ?? \"0x0\")\n}\n","import type { PrivateKeyAccount } from \"viem\"\nimport { getUsdcBalance } from \"./balance.js\"\nimport type { Network, WaitForFundingOptions } from \"./types.js\"\n\nexport class Wallet {\n readonly name: string\n readonly address: `0x${string}`\n readonly network: Network\n\n private _account: PrivateKeyAccount\n private _privateKey: `0x${string}`\n private _rpcUrl: string | undefined\n private _paymentFetch: typeof globalThis.fetch\n\n constructor(params: {\n name: string\n account: PrivateKeyAccount\n privateKey: `0x${string}`\n network: Network\n rpcUrl?: string\n paymentFetch: typeof globalThis.fetch\n }) {\n this.name = params.name\n this._account = params.account\n this._privateKey = params.privateKey\n this.address = params.account.address\n this.network = params.network\n this._rpcUrl = params.rpcUrl\n this._paymentFetch = params.paymentFetch\n }\n\n /** Check USDC balance on Base. Returns balance in minor units (6 decimals). */\n async checkBalance(): Promise<bigint> {\n return getUsdcBalance(this._account.address, this.network, this._rpcUrl)\n }\n\n /**\n * Poll until USDC balance >= minAmount.\n * @param minAmount - minimum USDC balance in minor units (6 decimals)\n */\n async waitForFunding(minAmount: bigint, opts?: WaitForFundingOptions): Promise<void> {\n const interval = opts?.pollInterval ?? 10_000\n const deadline = opts?.timeout ? Date.now() + opts.timeout : null\n\n while (true) {\n const balance = await getUsdcBalance(this._account.address, this.network, this._rpcUrl)\n if (balance >= minAmount) return\n\n if (deadline && Date.now() >= deadline) {\n throw new Error(`Funding timeout: balance ${balance} < required ${minAmount}`)\n }\n\n await new Promise((r) => setTimeout(r, interval))\n }\n }\n\n /**\n * Drop-in `fetch()` replacement that handles x402 payments automatically.\n * If the server returns 402, the library signs an EIP-3009 authorization\n * and retries the request with payment headers.\n */\n async fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {\n return this._paymentFetch(input, init)\n }\n}\n","import type { ComputeRequest, ComputeResponse, PricingTier, Size } from \"./types.js\"\n\nconst DEFAULT_ENDPOINT = \"https://x402.auteng.ai/api/x402/compute\"\n\nlet _endpoint = DEFAULT_ENDPOINT\n\nconst PRICING: Record<Size, PricingTier> = {\n small: {\n vcpu: 2,\n ram_gb: 1,\n default_timeout_s: 30,\n max_timeout_s: 300,\n base_price_usd: 0.002,\n per_second_usd: 0.00005,\n },\n med: {\n vcpu: 4,\n ram_gb: 4,\n default_timeout_s: 60,\n max_timeout_s: 600,\n base_price_usd: 0.008,\n per_second_usd: 0.00012,\n },\n large: {\n vcpu: 8,\n ram_gb: 16,\n default_timeout_s: 120,\n max_timeout_s: 3600,\n base_price_usd: 0.03,\n per_second_usd: 0.00025,\n },\n}\n\nexport const compute = {\n /**\n * Execute sandboxed code via AutEng's x402 compute endpoint.\n * Payment is handled automatically via the wallet's x402 layer.\n */\n async run(request: ComputeRequest): Promise<ComputeResponse> {\n if (!request.code) {\n throw new Error(\"compute.run: 'code' is required\")\n }\n if (!request.stack) {\n throw new Error(\"compute.run: 'stack' is required\")\n }\n\n const body = {\n code: request.code,\n stack: request.stack,\n size: request.size ?? \"small\",\n ...(request.timeout_seconds != null && {\n timeout_seconds: request.timeout_seconds,\n }),\n ...(request.files != null && { files: request.files }),\n }\n\n if (!request.wallet) {\n throw new Error(\"compute.run: 'wallet' is required\")\n }\n\n const response = await request.wallet.fetch(_endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n })\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\")\n throw new Error(`Compute request failed (${response.status}): ${text}`)\n }\n\n return (await response.json()) as ComputeResponse\n },\n\n /** Returns the pricing table for all compute sizes. */\n pricing(): Record<Size, PricingTier> {\n return { ...PRICING }\n },\n\n /**\n * Override the compute endpoint URL.\n * Default: https://x402.auteng.ai/api/x402/compute\n */\n setEndpoint(url: string): void {\n _endpoint = url\n },\n}\n","import type { FormatPriceOptions } from \"./types.js\"\n\nconst KNOWN_ASSETS: Record<string, { symbol: string; decimals: number; prefix: string }> = {\n // USDC on Base mainnet\n \"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913\": { symbol: \"USDC\", decimals: 6, prefix: \"$\" },\n // USDC on Base Sepolia\n \"0x036cbd53842c5426634e7929541ec2318f3dcf7e\": { symbol: \"USDC\", decimals: 6, prefix: \"$\" },\n}\n\nconst NETWORK_NAMES: Record<string, string> = {\n \"eip155:8453\": \"Base\",\n \"eip155:84532\": \"Base Sepolia\",\n \"base\": \"Base\",\n \"base-sepolia\": \"Base Sepolia\",\n}\n\n/**\n * Format a raw x402 price into a human-readable string.\n *\n * Knows about common assets (USDC on Base = 6 decimals, $-prefixed)\n * and falls back to raw display for unknown assets.\n *\n * @example\n * formatPrice(\"2000\", \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\", \"eip155:8453\")\n * // → \"$0.002 USDC on Base\"\n */\nexport function formatPrice(\n amount: string,\n asset: string,\n network: string,\n options?: FormatPriceOptions,\n): string {\n const known = KNOWN_ASSETS[asset.toLowerCase()]\n const networkName = NETWORK_NAMES[network]\n\n if (known) {\n const value = Number(amount) / 10 ** known.decimals\n const formatted = `${known.prefix}${value} ${known.symbol}`\n if (options?.short || !networkName) return formatted\n return `${formatted} on ${networkName}`\n }\n\n // Unknown asset — show raw\n const shortAsset = `${asset.slice(0, 6)}...${asset.slice(-4)}`\n const raw = `${amount} ${shortAsset}`\n if (options?.short || !networkName) return raw\n return `${raw} on ${networkName}`\n}\n","import type { ProbeResult, ProbeOptions, PaymentRequiredResponse, PaymentOption } from \"./types.js\"\nimport { formatPrice } from \"./format.js\"\n\n/**\n * Check if a URL is x402-enabled and see what it costs, without paying.\n *\n * Sends a request to the URL. If the server returns 402 Payment Required,\n * parses the payment requirements and returns a structured result with\n * human-readable pricing. Non-402 responses return `{ enabled: false }`.\n *\n * No wallet needed — this is a read-only inspection.\n */\nexport async function probe(url: string, options?: ProbeOptions): Promise<ProbeResult> {\n const res = await fetch(url, {\n method: options?.method ?? \"GET\",\n headers: options?.headers,\n body: options?.body,\n signal: options?.signal,\n })\n\n if (res.status !== 402) {\n return { enabled: false, url, status: res.status, price: null, paymentRequired: null }\n }\n\n let raw: unknown\n try {\n raw = await res.json()\n } catch {\n return { enabled: false, url, status: 402, price: null, paymentRequired: null }\n }\n\n const paymentRequired = normalizePaymentRequired(raw)\n if (!paymentRequired || paymentRequired.accepts.length === 0) {\n return { enabled: false, url, status: 402, price: null, paymentRequired: null }\n }\n\n const first = paymentRequired.accepts[0]\n const price = formatPrice(first.amount, first.asset, first.network)\n\n return { enabled: true, url, status: 402, price, paymentRequired }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalizePaymentRequired(raw: any): PaymentRequiredResponse | null {\n if (!raw || typeof raw !== \"object\" || !Array.isArray(raw.accepts) || raw.accepts.length === 0) {\n return null\n }\n\n const firstAccept = raw.accepts[0]\n\n // Determine if v2 (has top-level resource object and accepts[].amount)\n // or v1 (has accepts[].maxAmountRequired and inline resource/description)\n const isV2 = typeof firstAccept.amount === \"string\" && raw.resource && typeof raw.resource === \"object\"\n\n if (isV2) {\n return {\n x402Version: raw.x402Version ?? 2,\n resource: {\n url: raw.resource.url ?? \"\",\n description: raw.resource.description,\n mimeType: raw.resource.mimeType,\n },\n accepts: raw.accepts.map(normalizeAccept),\n extensions: raw.extensions ?? undefined,\n }\n }\n\n // v1 shape: maxAmountRequired, inline resource/description on each accept\n if (typeof firstAccept.maxAmountRequired === \"string\") {\n return {\n x402Version: raw.x402Version ?? 1,\n resource: {\n url: firstAccept.resource ?? raw.resource?.url ?? \"\",\n description: firstAccept.description ?? raw.resource?.description,\n mimeType: firstAccept.mimeType ?? raw.resource?.mimeType,\n },\n accepts: raw.accepts.map((a: Record<string, unknown>) => normalizeAccept({\n ...a,\n amount: a.maxAmountRequired,\n })),\n extensions: raw.extensions ?? undefined,\n }\n }\n\n return null\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalizeAccept(a: any): PaymentOption {\n return {\n scheme: a.scheme ?? \"exact\",\n network: a.network ?? \"\",\n asset: a.asset ?? \"\",\n amount: String(a.amount ?? a.maxAmountRequired ?? \"0\"),\n payTo: a.payTo ?? \"\",\n maxTimeoutSeconds: a.maxTimeoutSeconds ?? 0,\n extra: a.extra ?? undefined,\n }\n}\n","import type { DiscoverResult, DiscoverOptions, BazaarService, PaymentOption } from \"./types.js\"\nimport { formatPrice } from \"./format.js\"\n\nconst DEFAULT_BAZAAR_URL = \"https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources\"\n\n/**\n * Query the Bazaar registry to find available x402 services.\n *\n * Fetches from the Coinbase CDP Bazaar discovery endpoint and returns\n * a normalized list of services with human-readable pricing.\n *\n * No wallet or authentication needed.\n */\nexport async function discover(options?: DiscoverOptions): Promise<DiscoverResult> {\n const baseUrl = options?.bazaarUrl ?? DEFAULT_BAZAAR_URL\n const params = new URLSearchParams()\n if (options?.limit != null) params.set(\"limit\", String(options.limit))\n if (options?.offset != null) params.set(\"offset\", String(options.offset))\n\n const url = params.toString() ? `${baseUrl}?${params}` : baseUrl\n\n const res = await fetch(url, {\n headers: { Accept: \"application/json\" },\n signal: options?.signal,\n })\n\n if (!res.ok) {\n const text = await res.text().catch(() => \"\")\n throw new Error(`Bazaar request failed (${res.status}): ${text}`)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const json = (await res.json()) as any\n\n // The Bazaar response has an `items` array (or `resources`)\n const items: unknown[] = json.items ?? json.resources ?? []\n\n const services: BazaarService[] = items.map(normalizeBazaarItem).filter(Boolean) as BazaarService[]\n\n return {\n services,\n total: json.total ?? json.totalCount ?? services.length,\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalizeBazaarItem(item: any): BazaarService | null {\n if (!item || typeof item !== \"object\") return null\n\n const accepts: unknown[] = item.accepts ?? []\n if (accepts.length === 0) return null\n\n const normalizedAccepts: PaymentOption[] = accepts.map((a: unknown) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const accept = a as any\n return {\n scheme: accept.scheme ?? \"exact\",\n network: accept.network ?? \"\",\n asset: accept.asset ?? \"\",\n amount: String(accept.amount ?? accept.maxAmountRequired ?? \"0\"),\n payTo: accept.payTo ?? \"\",\n maxTimeoutSeconds: accept.maxTimeoutSeconds ?? 0,\n extra: accept.extra ?? undefined,\n }\n })\n\n // Find cheapest option for display price\n const cheapest = normalizedAccepts.reduce((min, a) =>\n BigInt(a.amount) < BigInt(min.amount) ? a : min\n )\n const price = formatPrice(cheapest.amount, cheapest.asset, cheapest.network)\n\n // Extract description from various possible locations\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const firstAccept = accepts[0] as any\n const description: string | null =\n item.description ??\n item.resource?.description ??\n firstAccept?.description ??\n item.metadata?.description ??\n null\n\n // Extract URL\n const url: string =\n item.url ??\n item.resource?.url ??\n (typeof item.resource === \"string\" ? item.resource : null) ??\n firstAccept?.resource ??\n \"\"\n\n return {\n url,\n description,\n price,\n accepts: normalizedAccepts,\n metadata: item.metadata ?? {},\n }\n}\n","// Internal — used by wallet module\nexport { createPaymentFetch } from \"./payment-fetch.js\"\n\n// Public x402 convenience functions\nimport { probe } from \"./probe.js\"\nimport { discover } from \"./discover.js\"\nimport { formatPrice } from \"./format.js\"\n\nexport const x402 = {\n probe,\n discover,\n formatPrice,\n}\n\nexport type {\n ProbeResult,\n ProbeOptions,\n PaymentRequiredResponse,\n PaymentOption,\n BazaarService,\n DiscoverResult,\n DiscoverOptions,\n FormatPriceOptions,\n} from \"./types.js\"\n"],"mappings":";AAAA,SAAS,QAAAA,OAAM,WAAAC,gBAAe;;;ACA9B,SAAS,oBAAoB,2BAA2B;AAGjD,SAAS,gBAGd;AACA,QAAM,aAAa,mBAAmB;AACtC,QAAM,UAAU,oBAAoB,UAAU;AAC9C,SAAO,EAAE,YAAY,QAAQ;AAC/B;AAEO,SAAS,YAAY,YAE1B;AACA,QAAM,UAAU,oBAAoB,UAAU;AAC9C,SAAO,EAAE,QAAQ;AACnB;;;ACjBA,SAAS,WAAW,cAAc,eAAe,YAAY,aAAa,oBAAoB;AAC9F,SAAS,SAAS,MAAM,eAAe;AAGvC,IAAM,aAAa;AAEZ,SAAS,mBAAmB,MAAoB;AACrD,MAAI,CAAC,WAAW,KAAK,IAAI,GAAG;AAC1B,UAAM,IAAI,MAAM,wBAAwB,IAAI,mEAAmE;AAAA,EACjH;AACF;AAEO,SAAS,eAAe,MAAiC;AAC9D,M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ACzB;AAAA,EACF,CAAC;AAGD,QAAM,WAAW,kBAAkB;AAAA,IAAO,CAAC,KAAK,MAC9C,OAAO,EAAE,MAAM,IAAI,OAAO,IAAI,MAAM,IAAI,IAAI;AAAA,EAC9C;AACA,QAAM,QAAQ,YAAY,SAAS,QAAQ,SAAS,OAAO,SAAS,OAAO;AAI3E,QAAM,cAAc,QAAQ,CAAC;AAC7B,QAAM,cACJ,KAAK,eACL,KAAK,UAAU,eACf,aAAa,eACb,KAAK,UAAU,eACf;AAGF,QAAM,MACJ,KAAK,OACL,KAAK,UAAU,QACd,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW,SACrD,aAAa,YACb;AAEF,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT,UAAU,KAAK,YAAY,CAAC;AAAA,EAC9B;AACF;;;ACzFO,IAAM,OAAO;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AACF;","names":["join","resolve","privateKeyToAccount","resolve","join"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auteng/agent-utils",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Utility belt for autonomous AI agents — wallet, compute, and more",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",