@pay-skill/sdk 0.1.8 → 0.2.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.
Files changed (60) hide show
  1. package/README.md +143 -154
  2. package/dist/auth.d.ts +11 -6
  3. package/dist/auth.d.ts.map +1 -1
  4. package/dist/auth.js +19 -7
  5. package/dist/auth.js.map +1 -1
  6. package/dist/errors.d.ts +4 -2
  7. package/dist/errors.d.ts.map +1 -1
  8. package/dist/errors.js +8 -3
  9. package/dist/errors.js.map +1 -1
  10. package/dist/index.d.ts +2 -13
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -6
  13. package/dist/index.js.map +1 -1
  14. package/dist/keychain.d.ts +8 -0
  15. package/dist/keychain.d.ts.map +1 -0
  16. package/dist/keychain.js +17 -0
  17. package/dist/keychain.js.map +1 -0
  18. package/dist/wallet.d.ts +135 -104
  19. package/dist/wallet.d.ts.map +1 -1
  20. package/dist/wallet.js +631 -276
  21. package/dist/wallet.js.map +1 -1
  22. package/jsr.json +13 -13
  23. package/knip.json +5 -5
  24. package/package.json +51 -48
  25. package/src/auth.ts +210 -200
  26. package/src/eip3009.ts +79 -79
  27. package/src/errors.ts +55 -48
  28. package/src/index.ts +24 -51
  29. package/src/keychain.ts +18 -0
  30. package/src/wallet.ts +1111 -445
  31. package/tests/test_auth_rejection.ts +102 -154
  32. package/tests/test_crypto.ts +138 -251
  33. package/tests/test_e2e.ts +99 -158
  34. package/tests/test_errors.ts +44 -36
  35. package/tests/test_ows.ts +153 -0
  36. package/tests/test_wallet.ts +194 -0
  37. package/dist/client.d.ts +0 -94
  38. package/dist/client.d.ts.map +0 -1
  39. package/dist/client.js +0 -443
  40. package/dist/client.js.map +0 -1
  41. package/dist/models.d.ts +0 -78
  42. package/dist/models.d.ts.map +0 -1
  43. package/dist/models.js +0 -2
  44. package/dist/models.js.map +0 -1
  45. package/dist/ows-signer.d.ts +0 -75
  46. package/dist/ows-signer.d.ts.map +0 -1
  47. package/dist/ows-signer.js +0 -130
  48. package/dist/ows-signer.js.map +0 -1
  49. package/dist/signer.d.ts +0 -46
  50. package/dist/signer.d.ts.map +0 -1
  51. package/dist/signer.js +0 -111
  52. package/dist/signer.js.map +0 -1
  53. package/src/client.ts +0 -644
  54. package/src/models.ts +0 -77
  55. package/src/ows-signer.ts +0 -223
  56. package/src/signer.ts +0 -147
  57. package/tests/test_ows_integration.ts +0 -92
  58. package/tests/test_ows_signer.ts +0 -365
  59. package/tests/test_signer.ts +0 -47
  60. package/tests/test_validation.ts +0 -66
package/dist/wallet.js CHANGED
@@ -1,331 +1,686 @@
1
1
  /**
2
- * Wallet — high-level write client for agents.
3
- * Wraps PayClient with private key signing and balance tracking.
2
+ * Wallet — the single entry point for the pay SDK.
4
3
  *
5
- * This is the primary entry point for the playground and agent integrations.
6
- * The PayClient is lower-level (HTTP only); Wallet adds signing + state.
4
+ * Zero-config for agents: new Wallet() (reads PAYSKILL_KEY env)
5
+ * Explicit key: new Wallet({ privateKey: "0x..." })
6
+ * OS keychain (CLI key): await Wallet.create()
7
+ * OWS wallet extension: await Wallet.fromOws({ walletId: "..." })
7
8
  */
8
9
  import { privateKeyToAccount } from "viem/accounts";
9
- import { buildAuthHeaders } from "./auth.js";
10
- /** Map well-known chain names to numeric IDs. */
11
- const CHAIN_IDS = {
12
- "base": 8453,
13
- "base-sepolia": 84532,
14
- };
10
+ import { buildAuthHeaders, buildAuthHeadersSigned } from "./auth.js";
11
+ import { signTransferAuthorization, combinedSignature } from "./eip3009.js";
12
+ import { readFromKeychain } from "./keychain.js";
13
+ import { PayError, PayValidationError, PayNetworkError, PayServerError, PayInsufficientFundsError, } from "./errors.js";
14
+ // ── Constants ────────────────────────────────────────────────────────
15
+ const MAINNET_API_URL = "https://pay-skill.com/api/v1";
16
+ const TESTNET_API_URL = "https://testnet.pay-skill.com/api/v1";
17
+ const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
18
+ const KEY_RE = /^0x[0-9a-fA-F]{64}$/;
19
+ const DIRECT_MIN_MICRO = 1_000_000; // $1.00
20
+ const TAB_MIN_MICRO = 5_000_000; // $5.00
21
+ const TAB_MULTIPLIER = 10;
22
+ const DEFAULT_TIMEOUT = 30_000;
23
+ // Internal sentinel for OWS construction
24
+ const _OWS_INIT = Symbol("ows-init");
25
+ // ── Helpers ──────────────────────────────────────────────────────────
26
+ function normalizeKey(key) {
27
+ const clean = key.startsWith("0x") ? key : "0x" + key;
28
+ if (!KEY_RE.test(clean)) {
29
+ throw new PayValidationError("Invalid private key: must be 32 bytes hex", "privateKey");
30
+ }
31
+ return clean;
32
+ }
33
+ function validateAddress(address) {
34
+ if (!ADDRESS_RE.test(address)) {
35
+ throw new PayValidationError(`Invalid Ethereum address: ${address}`, "address");
36
+ }
37
+ }
38
+ function toMicro(amount) {
39
+ if (typeof amount === "number") {
40
+ if (!Number.isFinite(amount) || amount < 0) {
41
+ throw new PayValidationError("Amount must be a positive finite number", "amount");
42
+ }
43
+ return Math.round(amount * 1_000_000);
44
+ }
45
+ if (!Number.isInteger(amount.micro) || amount.micro < 0) {
46
+ throw new PayValidationError("Micro amount must be a non-negative integer", "amount");
47
+ }
48
+ return amount.micro;
49
+ }
50
+ function toDollars(micro) {
51
+ return micro / 1_000_000;
52
+ }
53
+ function parseTab(raw) {
54
+ return {
55
+ id: raw.tab_id,
56
+ provider: raw.provider,
57
+ amount: toDollars(raw.amount),
58
+ balanceRemaining: toDollars(raw.balance_remaining),
59
+ totalCharged: toDollars(raw.total_charged),
60
+ chargeCount: raw.charge_count,
61
+ maxChargePerCall: toDollars(raw.max_charge_per_call),
62
+ totalWithdrawn: toDollars(raw.total_withdrawn),
63
+ status: raw.status,
64
+ pendingChargeCount: raw.pending_charge_count,
65
+ pendingChargeTotal: toDollars(raw.pending_charge_total),
66
+ effectiveBalance: toDollars(raw.effective_balance),
67
+ };
68
+ }
69
+ function parseSig(signature) {
70
+ const sig = signature.startsWith("0x")
71
+ ? signature.slice(2)
72
+ : signature;
73
+ return {
74
+ v: parseInt(sig.slice(128, 130), 16),
75
+ r: "0x" + sig.slice(0, 64),
76
+ s: "0x" + sig.slice(64, 128),
77
+ };
78
+ }
79
+ function resolveApiUrl(testnet) {
80
+ return (process.env.PAYSKILL_API_URL ??
81
+ (testnet ? TESTNET_API_URL : MAINNET_API_URL));
82
+ }
83
+ function createOwsSignTypedData(ows, walletId, owsApiKey) {
84
+ return async (params) => {
85
+ // Build EIP712Domain type from domain fields
86
+ const domainType = [];
87
+ const d = params.domain;
88
+ if (d.name !== undefined)
89
+ domainType.push({ name: "name", type: "string" });
90
+ if (d.version !== undefined)
91
+ domainType.push({ name: "version", type: "string" });
92
+ if (d.chainId !== undefined)
93
+ domainType.push({ name: "chainId", type: "uint256" });
94
+ if (d.verifyingContract !== undefined)
95
+ domainType.push({ name: "verifyingContract", type: "address" });
96
+ const fullTypedData = {
97
+ types: {
98
+ EIP712Domain: domainType,
99
+ ...Object.fromEntries(Object.entries(params.types).map(([k, v]) => [k, [...v]])),
100
+ },
101
+ primaryType: params.primaryType,
102
+ domain: params.domain,
103
+ message: params.message,
104
+ };
105
+ const json = JSON.stringify(fullTypedData, (_key, v) => typeof v === "bigint" ? v.toString() : v);
106
+ const result = ows.signTypedData(walletId, "evm", json, owsApiKey);
107
+ const sig = result.signature.startsWith("0x")
108
+ ? result.signature.slice(2)
109
+ : result.signature;
110
+ if (sig.length === 130)
111
+ return `0x${sig}`;
112
+ const v = (result.recoveryId ?? 0) + 27;
113
+ return `0x${sig}${v.toString(16).padStart(2, "0")}`;
114
+ };
115
+ }
116
+ // ── Standalone discover (no wallet needed) ───────────────────────────
117
+ export async function discover(query, options) {
118
+ const testnet = options?.testnet ?? !!process.env.PAYSKILL_TESTNET;
119
+ const apiUrl = resolveApiUrl(testnet);
120
+ return discoverImpl(apiUrl, DEFAULT_TIMEOUT, query, options);
121
+ }
122
+ async function discoverImpl(apiUrl, timeout, query, options) {
123
+ const params = new URLSearchParams();
124
+ if (query)
125
+ params.set("q", query);
126
+ if (options?.sort)
127
+ params.set("sort", options.sort);
128
+ if (options?.category)
129
+ params.set("category", options.category);
130
+ if (options?.settlement)
131
+ params.set("settlement", options.settlement);
132
+ const qs = params.toString();
133
+ const url = `${apiUrl}/discover${qs ? `?${qs}` : ""}`;
134
+ const resp = await fetch(url, { signal: AbortSignal.timeout(timeout) });
135
+ if (!resp.ok) {
136
+ throw new PayServerError(`discover failed: ${resp.status}`, resp.status);
137
+ }
138
+ const data = (await resp.json());
139
+ return data.services;
140
+ }
141
+ // ── Wallet ───────────────────────────────────────────────────────────
15
142
  export class Wallet {
16
143
  address;
17
- _privateKey;
18
- _apiUrl;
19
- _chain;
20
- _chainId;
21
- _routerAddress;
22
- _account;
23
- /** URL path prefix extracted from apiUrl (e.g., "/api/v1"). */
24
- _basePath;
25
- /** Cached contracts response. */
26
- _contractsCache = null;
144
+ // Signing: signTypedData works for both private key and OWS.
145
+ // rawKey is non-null only for private-key wallets (needed for x402 direct / EIP-3009).
146
+ #signTypedData;
147
+ #rawKey;
148
+ #apiUrl;
149
+ #basePath;
150
+ #testnet;
151
+ #timeout;
152
+ #contracts = null;
153
+ /**
154
+ * Sync constructor. Resolves key from: privateKey arg -> PAYSKILL_KEY env -> error.
155
+ * For OS keychain, use `await Wallet.create()`.
156
+ * For OWS, use `await Wallet.fromOws({ walletId })`.
157
+ */
27
158
  constructor(options) {
28
- this._privateKey = normalizeKey(options.privateKey);
29
- this._apiUrl = options.apiUrl;
30
- this._chain = options.chain;
31
- this._chainId = options.chainId ?? CHAIN_IDS[options.chain] ?? (parseInt(options.chain, 10) || 8453);
32
- this._routerAddress = options.routerAddress;
33
- this._account = privateKeyToAccount(this._privateKey);
34
- this.address = this._account.address;
159
+ // Check for internal OWS init (symbol key hidden from public API)
160
+ const raw = options;
161
+ if (raw && raw[_OWS_INIT]) {
162
+ const init = raw;
163
+ this.address = init._address;
164
+ this.#signTypedData = init._signTypedData;
165
+ this.#rawKey = null;
166
+ this.#testnet = init._testnet;
167
+ this.#timeout = init._timeout;
168
+ this.#apiUrl = resolveApiUrl(this.#testnet);
169
+ try {
170
+ this.#basePath = new URL(this.#apiUrl).pathname.replace(/\/+$/, "");
171
+ }
172
+ catch {
173
+ this.#basePath = "";
174
+ }
175
+ return;
176
+ }
177
+ const key = options?.privateKey ?? process.env.PAYSKILL_KEY;
178
+ if (!key) {
179
+ throw new PayError("No private key found. Provide { privateKey }, set PAYSKILL_KEY env var, " +
180
+ "or use Wallet.create() to read from OS keychain.");
181
+ }
182
+ this.#rawKey = normalizeKey(key);
183
+ const account = privateKeyToAccount(this.#rawKey);
184
+ this.address = account.address;
185
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
186
+ this.#signTypedData = (p) => account.signTypedData(p);
187
+ this.#testnet = options?.testnet ?? !!process.env.PAYSKILL_TESTNET;
188
+ this.#timeout = options?.timeout ?? DEFAULT_TIMEOUT;
189
+ this.#apiUrl = resolveApiUrl(this.#testnet);
35
190
  try {
36
- this._basePath = new URL(options.apiUrl).pathname.replace(/\/+$/, "");
191
+ this.#basePath = new URL(this.#apiUrl).pathname.replace(/\/+$/, "");
37
192
  }
38
193
  catch {
39
- this._basePath = "";
194
+ this.#basePath = "";
40
195
  }
41
196
  }
42
- get _authConfig() {
43
- return {
44
- chainId: this._chainId,
45
- routerAddress: this._routerAddress,
197
+ /** Async factory. Resolves key from: privateKey arg -> OS keychain -> PAYSKILL_KEY env -> error. */
198
+ static async create(options) {
199
+ if (options?.privateKey)
200
+ return new Wallet(options);
201
+ const keychainKey = await readFromKeychain();
202
+ if (keychainKey) {
203
+ return new Wallet({ ...options, privateKey: keychainKey });
204
+ }
205
+ return new Wallet(options);
206
+ }
207
+ /** Sync factory. Reads key from PAYSKILL_KEY env var only. */
208
+ static fromEnv(options) {
209
+ const key = process.env.PAYSKILL_KEY;
210
+ if (!key)
211
+ throw new PayError("PAYSKILL_KEY env var not set");
212
+ return new Wallet({ privateKey: key, testnet: options?.testnet });
213
+ }
214
+ /** Async factory. Creates a wallet backed by an OWS (Open Wallet Standard) wallet. */
215
+ static async fromOws(options) {
216
+ let owsModule;
217
+ if (options._owsModule) {
218
+ owsModule = options._owsModule;
219
+ }
220
+ else {
221
+ try {
222
+ const moduleName = "@open-wallet-standard/core";
223
+ owsModule = (await import(moduleName));
224
+ }
225
+ catch {
226
+ throw new PayError("@open-wallet-standard/core is not installed. " +
227
+ "Install it with: npm install @open-wallet-standard/core");
228
+ }
229
+ }
230
+ const walletInfo = owsModule.getWallet(options.walletId);
231
+ const evmAccount = walletInfo.accounts.find((a) => a.chainId === "evm" || a.chainId.startsWith("eip155:"));
232
+ if (!evmAccount) {
233
+ throw new PayError(`No EVM account found in OWS wallet '${options.walletId}'. ` +
234
+ `Available chains: ${walletInfo.accounts.map((a) => a.chainId).join(", ") || "none"}.`);
235
+ }
236
+ const signFn = createOwsSignTypedData(owsModule, options.walletId, options.owsApiKey);
237
+ // Use the internal init path through the constructor
238
+ return new Wallet({
239
+ [_OWS_INIT]: true,
240
+ _address: evmAccount.address,
241
+ _signTypedData: signFn,
242
+ _testnet: options.testnet ?? !!process.env.PAYSKILL_TESTNET,
243
+ _timeout: options.timeout ?? DEFAULT_TIMEOUT,
244
+ });
245
+ }
246
+ // ── Internal: contracts ──────────────────────────────────────────
247
+ async ensureContracts() {
248
+ if (this.#contracts)
249
+ return this.#contracts;
250
+ let resp;
251
+ try {
252
+ resp = await fetch(`${this.#apiUrl}/contracts`, {
253
+ signal: AbortSignal.timeout(this.#timeout),
254
+ });
255
+ }
256
+ catch (e) {
257
+ throw new PayNetworkError(`Failed to reach server: ${e}`);
258
+ }
259
+ if (!resp.ok) {
260
+ throw new PayNetworkError(`Failed to fetch contracts: ${resp.status}`);
261
+ }
262
+ const data = (await resp.json());
263
+ this.#contracts = {
264
+ router: String(data.router ?? ""),
265
+ tab: String(data.tab ?? ""),
266
+ direct: String(data.direct ?? ""),
267
+ fee: String(data.fee ?? ""),
268
+ usdc: String(data.usdc ?? ""),
269
+ chainId: Number(data.chain_id ?? 0),
46
270
  };
271
+ return this.#contracts;
47
272
  }
48
- /** Build authenticated fetch headers for an API request. */
49
- async _authFetch(path, init = {}) {
273
+ // ── Internal: HTTP ───────────────────────────────────────────────
274
+ async authFetch(path, init = {}) {
275
+ const contracts = await this.ensureContracts();
50
276
  const method = (init.method ?? "GET").toUpperCase();
51
- // Sign only the path portion (no query string) — server verifies against uri.path().
52
277
  const pathOnly = path.split("?")[0];
53
- const signPath = this._basePath + pathOnly;
54
- const authHeaders = await buildAuthHeaders(this._privateKey, method, signPath, this._authConfig);
55
- const resp = await fetch(`${this._apiUrl}${path}`, {
278
+ const signPath = this.#basePath + pathOnly;
279
+ const config = {
280
+ chainId: contracts.chainId,
281
+ routerAddress: contracts.router,
282
+ };
283
+ const headers = this.#rawKey
284
+ ? await buildAuthHeaders(this.#rawKey, method, signPath, config)
285
+ : await buildAuthHeadersSigned(this.address, this.#signTypedData, method, signPath, config);
286
+ return fetch(`${this.#apiUrl}${path}`, {
56
287
  ...init,
288
+ signal: init.signal ?? AbortSignal.timeout(this.#timeout),
57
289
  headers: {
58
290
  "Content-Type": "application/json",
59
- ...authHeaders,
291
+ ...headers,
60
292
  ...init.headers,
61
293
  },
62
294
  });
63
- return resp;
64
295
  }
65
- /** Get USDC balance in human-readable units (e.g., 142.50). */
66
- async balance() {
67
- const resp = await this._authFetch("/status");
68
- if (!resp.ok)
69
- throw new Error(`balance fetch failed: ${resp.status}`);
70
- const data = (await resp.json());
71
- if (!data.balance_usdc)
72
- return 0;
73
- const raw = parseFloat(data.balance_usdc);
74
- // Server returns raw micro-units (USDC 6 decimals). Convert to dollars.
75
- return raw / 1_000_000;
296
+ async get(path) {
297
+ let resp;
298
+ try {
299
+ resp = await this.authFetch(path);
300
+ }
301
+ catch (e) {
302
+ if (e instanceof PayError)
303
+ throw e;
304
+ throw new PayNetworkError(String(e));
305
+ }
306
+ return this.handleResponse(resp);
76
307
  }
77
- /**
78
- * Sign an EIP-2612 permit for a given spender and amount.
79
- * Uses the server's /permit/prepare endpoint to get the nonce and hash,
80
- * then signs the hash locally.
81
- * @param flow — "direct" or "tab" (used to look up the spender contract address)
82
- * @param amount — micro-USDC amount
83
- */
84
- async signPermit(flow, amount) {
85
- const contracts = await this.getContracts();
86
- const spender = flow === "tab" ? contracts.tab : contracts.direct;
87
- // Server prepares the permit: reads nonce via its own RPC, computes EIP-712 hash
88
- const prepResp = await this._authFetch("/permit/prepare", {
89
- method: "POST",
90
- body: JSON.stringify({ amount, spender }),
91
- });
92
- if (!prepResp.ok) {
93
- const err = (await prepResp.json().catch(() => ({})));
94
- throw new Error(err.error ?? `permit/prepare failed: ${prepResp.status}`);
308
+ async post(path, body) {
309
+ let resp;
310
+ try {
311
+ resp = await this.authFetch(path, {
312
+ method: "POST",
313
+ body: JSON.stringify(body),
314
+ });
95
315
  }
96
- const prep = (await prepResp.json());
97
- // Sign the pre-computed EIP-712 hash locally (raw ECDSA, no EIP-191 prefix)
98
- const signature = await this._account.sign({
99
- hash: prep.hash,
100
- });
101
- // Parse 65-byte signature into v, r, s
102
- const sigClean = signature.startsWith("0x") ? signature.slice(2) : signature;
103
- const r = "0x" + sigClean.slice(0, 64);
104
- const s = "0x" + sigClean.slice(64, 128);
105
- const v = parseInt(sigClean.slice(128, 130), 16);
106
- return { nonce: prep.nonce, deadline: prep.deadline, v, r, s };
107
- }
108
- /** Send a direct payment. Auto-signs permit if not provided. */
109
- async payDirect(to, amount, memo, options) {
110
- const microAmount = Math.round(amount * 1_000_000);
111
- // Auto-sign permit if not provided
112
- let permit = options?.permit;
113
- if (!permit) {
114
- permit = await this.signPermit("direct", microAmount);
316
+ catch (e) {
317
+ if (e instanceof PayError)
318
+ throw e;
319
+ throw new PayNetworkError(String(e));
115
320
  }
116
- const resp = await this._authFetch("/direct", {
117
- method: "POST",
118
- body: JSON.stringify({
119
- to,
120
- amount: microAmount,
121
- memo,
122
- permit,
123
- }),
124
- });
125
- if (!resp.ok) {
126
- const err = (await resp.json().catch(() => ({})));
127
- throw new Error(err.error ?? `payDirect failed: ${resp.status}`);
321
+ return this.handleResponse(resp);
322
+ }
323
+ async del(path) {
324
+ let resp;
325
+ try {
326
+ resp = await this.authFetch(path, { method: "DELETE" });
327
+ }
328
+ catch (e) {
329
+ if (e instanceof PayError)
330
+ throw e;
331
+ throw new PayNetworkError(String(e));
332
+ }
333
+ if (resp.status >= 400) {
334
+ const text = await resp.text();
335
+ throw new PayServerError(text, resp.status);
336
+ }
337
+ }
338
+ async handleResponse(resp) {
339
+ if (resp.status >= 400) {
340
+ let msg;
341
+ try {
342
+ const body = (await resp.json());
343
+ msg = body.error ?? `Server error: ${resp.status}`;
344
+ if (body.code === "insufficient_funds" ||
345
+ msg.toLowerCase().includes("insufficient")) {
346
+ throw new PayInsufficientFundsError(msg);
347
+ }
348
+ }
349
+ catch (e) {
350
+ if (e instanceof PayInsufficientFundsError)
351
+ throw e;
352
+ msg = `Server error: ${resp.status}`;
353
+ }
354
+ throw new PayServerError(msg, resp.status);
128
355
  }
356
+ if (resp.status === 204)
357
+ return undefined;
129
358
  return (await resp.json());
130
359
  }
131
- /** Create a one-time fund link via the server. Returns the dashboard URL. */
132
- async createFundLink(options) {
133
- const resp = await this._authFetch("/links/fund", {
134
- method: "POST",
135
- body: JSON.stringify({
136
- messages: options?.messages ?? [],
137
- agent_name: options?.agentName,
138
- }),
360
+ // ── Internal: permits ────────────────────────────────────────────
361
+ async signPermit(flow, microAmount) {
362
+ const contracts = await this.ensureContracts();
363
+ const spender = flow === "tab" ? contracts.tab : contracts.direct;
364
+ const prep = await this.post("/permit/prepare", { amount: microAmount, spender });
365
+ if (this.#rawKey) {
366
+ // Private key path: sign the pre-computed hash directly
367
+ const account = privateKeyToAccount(this.#rawKey);
368
+ const signature = await account.sign({
369
+ hash: prep.hash,
370
+ });
371
+ return { nonce: prep.nonce, deadline: prep.deadline, ...parseSig(signature) };
372
+ }
373
+ // OWS path: sign full EIP-2612 permit typed data
374
+ const signature = await this.#signTypedData({
375
+ domain: {
376
+ name: "USD Coin",
377
+ version: "2",
378
+ chainId: contracts.chainId,
379
+ verifyingContract: contracts.usdc,
380
+ },
381
+ types: {
382
+ Permit: [
383
+ { name: "owner", type: "address" },
384
+ { name: "spender", type: "address" },
385
+ { name: "value", type: "uint256" },
386
+ { name: "nonce", type: "uint256" },
387
+ { name: "deadline", type: "uint256" },
388
+ ],
389
+ },
390
+ primaryType: "Permit",
391
+ message: {
392
+ owner: this.address,
393
+ spender: spender,
394
+ value: BigInt(microAmount),
395
+ nonce: BigInt(prep.nonce),
396
+ deadline: BigInt(prep.deadline),
397
+ },
139
398
  });
140
- if (!resp.ok) {
141
- const err = (await resp.json().catch(() => ({})));
142
- throw new Error(err.error ?? `createFundLink failed: ${resp.status}`);
399
+ return { nonce: prep.nonce, deadline: prep.deadline, ...parseSig(signature) };
400
+ }
401
+ // ── Internal: x402 ───────────────────────────────────────────────
402
+ async parse402(resp) {
403
+ const prHeader = resp.headers.get("payment-required");
404
+ if (prHeader) {
405
+ try {
406
+ const decoded = JSON.parse(atob(prHeader));
407
+ return extract402(decoded);
408
+ }
409
+ catch {
410
+ /* fall through to body */
411
+ }
143
412
  }
144
- const data = (await resp.json());
145
- return data.url;
413
+ const body = (await resp.json());
414
+ return extract402((body.requirements ?? body));
146
415
  }
147
- /** Create a one-time withdraw link via the server. Returns the dashboard URL. */
148
- async createWithdrawLink(options) {
149
- const resp = await this._authFetch("/links/withdraw", {
150
- method: "POST",
151
- body: JSON.stringify({
152
- messages: options?.messages ?? [],
153
- agent_name: options?.agentName,
154
- }),
155
- });
156
- if (!resp.ok) {
157
- const err = (await resp.json().catch(() => ({})));
158
- throw new Error(err.error ?? `createWithdrawLink failed: ${resp.status}`);
416
+ async handle402(resp, url, method, body, headers) {
417
+ const reqs = await this.parse402(resp);
418
+ if (reqs.settlement === "tab") {
419
+ return this.settleViaTab(url, method, body, headers, reqs);
159
420
  }
160
- const data = (await resp.json());
161
- return data.url;
421
+ return this.settleViaDirect(url, method, body, headers, reqs);
162
422
  }
163
- /** Register a webhook for this wallet. */
164
- async registerWebhook(url, events, secret) {
165
- const payload = { url, events };
166
- if (secret)
167
- payload.secret = secret;
168
- const resp = await this._authFetch("/webhooks", {
169
- method: "POST",
170
- body: JSON.stringify(payload),
423
+ async settleViaDirect(url, method, body, headers, reqs) {
424
+ if (!this.#rawKey) {
425
+ throw new PayError("x402 direct settlement requires a private key. " +
426
+ "OWS wallets only support tab settlement. " +
427
+ "Ask the provider to enable tab settlement, or use a private key wallet.");
428
+ }
429
+ const contracts = await this.ensureContracts();
430
+ const auth = await signTransferAuthorization(this.#rawKey, reqs.to, reqs.amount, contracts.chainId, contracts.usdc);
431
+ const paymentPayload = {
432
+ x402Version: 2,
433
+ accepted: reqs.accepted ?? {
434
+ scheme: "exact",
435
+ network: `eip155:${contracts.chainId}`,
436
+ amount: String(reqs.amount),
437
+ payTo: reqs.to,
438
+ },
439
+ payload: {
440
+ signature: combinedSignature(auth),
441
+ authorization: {
442
+ from: auth.from,
443
+ to: auth.to,
444
+ value: String(reqs.amount),
445
+ validAfter: "0",
446
+ validBefore: "0",
447
+ nonce: auth.nonce,
448
+ },
449
+ },
450
+ extensions: {},
451
+ };
452
+ return fetch(url, {
453
+ method,
454
+ body,
455
+ signal: AbortSignal.timeout(this.#timeout),
456
+ headers: {
457
+ ...headers,
458
+ "Content-Type": "application/json",
459
+ "PAYMENT-SIGNATURE": btoa(JSON.stringify(paymentPayload)),
460
+ },
171
461
  });
172
- if (!resp.ok)
173
- throw new Error(`registerWebhook failed: ${resp.status}`);
174
- return (await resp.json());
175
462
  }
176
- /** Open a tab with a provider (positional or object form). */
177
- async openTab(providerOrOpts, amount, maxChargePerCall, options) {
178
- let provider;
179
- let amt;
180
- let maxCharge;
181
- let permit;
182
- if (typeof providerOrOpts === "string") {
183
- if (amount === undefined || maxChargePerCall === undefined) {
184
- throw new Error("amount and maxChargePerCall are required when provider is a string");
463
+ async settleViaTab(url, method, body, headers, reqs) {
464
+ const contracts = await this.ensureContracts();
465
+ const rawTabs = await this.get("/tabs");
466
+ let tab = rawTabs.find((t) => t.provider === reqs.to && t.status === "open");
467
+ if (!tab) {
468
+ const tabMicro = Math.max(reqs.amount * TAB_MULTIPLIER, TAB_MIN_MICRO);
469
+ const bal = await this.balance();
470
+ const tabDollars = toDollars(tabMicro);
471
+ if (bal.available < tabDollars) {
472
+ throw new PayInsufficientFundsError(`Insufficient balance for tab: have $${bal.available.toFixed(2)}, need $${tabDollars.toFixed(2)}`, bal.available, tabDollars);
185
473
  }
186
- provider = providerOrOpts;
187
- amt = amount;
188
- maxCharge = maxChargePerCall;
189
- permit = options?.permit;
474
+ const permit = await this.signPermit("tab", tabMicro);
475
+ tab = await this.post("/tabs", {
476
+ provider: reqs.to,
477
+ amount: tabMicro,
478
+ max_charge_per_call: reqs.amount,
479
+ permit,
480
+ });
190
481
  }
191
- else {
192
- provider = providerOrOpts.to;
193
- amt = providerOrOpts.limit;
194
- maxCharge = providerOrOpts.perUnit;
195
- permit = providerOrOpts.permit;
482
+ const charge = await this.post(`/tabs/${tab.tab_id}/charge`, { amount: reqs.amount });
483
+ const paymentPayload = {
484
+ x402Version: 2,
485
+ accepted: reqs.accepted ?? {
486
+ scheme: "exact",
487
+ network: `eip155:${contracts.chainId}`,
488
+ amount: String(reqs.amount),
489
+ payTo: reqs.to,
490
+ },
491
+ payload: {
492
+ authorization: { from: this.address },
493
+ },
494
+ extensions: {
495
+ pay: {
496
+ settlement: "tab",
497
+ tabId: tab.tab_id,
498
+ chargeId: charge.charge_id ?? "",
499
+ },
500
+ },
501
+ };
502
+ return fetch(url, {
503
+ method,
504
+ body,
505
+ signal: AbortSignal.timeout(this.#timeout),
506
+ headers: {
507
+ ...headers,
508
+ "Content-Type": "application/json",
509
+ "PAYMENT-SIGNATURE": btoa(JSON.stringify(paymentPayload)),
510
+ },
511
+ });
512
+ }
513
+ // ── Public: Direct Payment ───────────────────────────────────────
514
+ async send(to, amount, memo) {
515
+ validateAddress(to);
516
+ const micro = toMicro(amount);
517
+ if (micro < DIRECT_MIN_MICRO) {
518
+ throw new PayValidationError("Amount below minimum ($1.00)", "amount");
196
519
  }
197
- const microAmount = Math.round(amt * 1_000_000);
198
- // Auto-sign permit if not provided
199
- if (!permit) {
200
- permit = await this.signPermit("tab", microAmount);
520
+ const permit = await this.signPermit("direct", micro);
521
+ const raw = await this.post("/direct", {
522
+ to,
523
+ amount: micro,
524
+ memo: memo ?? "",
525
+ permit,
526
+ });
527
+ return {
528
+ txHash: raw.tx_hash,
529
+ status: raw.status,
530
+ amount: toDollars(raw.amount),
531
+ fee: toDollars(raw.fee),
532
+ };
533
+ }
534
+ // ── Public: Tabs ─────────────────────────────────────────────────
535
+ async openTab(provider, amount, maxChargePerCall) {
536
+ validateAddress(provider);
537
+ const microAmount = toMicro(amount);
538
+ const microMax = toMicro(maxChargePerCall);
539
+ if (microAmount < TAB_MIN_MICRO) {
540
+ throw new PayValidationError("Tab amount below minimum ($5.00)", "amount");
201
541
  }
202
- const resp = await this._authFetch("/tabs", {
203
- method: "POST",
204
- body: JSON.stringify({
205
- provider,
206
- amount: microAmount,
207
- max_charge_per_call: Math.round(maxCharge * 1_000_000),
208
- permit,
209
- }),
542
+ if (microMax <= 0) {
543
+ throw new PayValidationError("maxChargePerCall must be positive", "maxChargePerCall");
544
+ }
545
+ const permit = await this.signPermit("tab", microAmount);
546
+ const raw = await this.post("/tabs", {
547
+ provider,
548
+ amount: microAmount,
549
+ max_charge_per_call: microMax,
550
+ permit,
210
551
  });
211
- if (!resp.ok)
212
- throw new Error(`openTab failed: ${resp.status}`);
213
- const data = (await resp.json());
214
- return { id: data.tab_id, tab_id: data.tab_id };
215
- }
216
- /** Charge a tab (provider-side). */
217
- async chargeTab(tabId, amountOrOpts) {
218
- const body = typeof amountOrOpts === "number"
219
- ? { amount: Math.round(amountOrOpts * 1_000_000) }
220
- : {
221
- amount: Math.round(amountOrOpts.amount * 1_000_000),
222
- cumulative: Math.round(amountOrOpts.cumulative * 1_000_000),
223
- call_count: amountOrOpts.callCount,
224
- provider_sig: amountOrOpts.providerSig,
225
- };
226
- const resp = await this._authFetch(`/tabs/${tabId}/charge`, {
227
- method: "POST",
228
- body: JSON.stringify(body),
552
+ return parseTab(raw);
553
+ }
554
+ async closeTab(tabId) {
555
+ const raw = await this.post(`/tabs/${tabId}/close`, {});
556
+ return parseTab(raw);
557
+ }
558
+ async topUpTab(tabId, amount) {
559
+ const micro = toMicro(amount);
560
+ if (micro <= 0) {
561
+ throw new PayValidationError("Amount must be positive", "amount");
562
+ }
563
+ const permit = await this.signPermit("tab", micro);
564
+ const raw = await this.post(`/tabs/${tabId}/topup`, {
565
+ amount: micro,
566
+ permit,
229
567
  });
230
- if (!resp.ok)
231
- throw new Error(`chargeTab failed: ${resp.status}`);
232
- return (await resp.json());
568
+ return parseTab(raw);
569
+ }
570
+ async listTabs() {
571
+ const raw = await this.get("/tabs");
572
+ return raw.map(parseTab);
233
573
  }
234
- /** Close a tab. */
235
- async closeTab(tabId, options) {
236
- const body = {};
237
- if (options?.finalAmount !== undefined)
238
- body.final_amount = Math.round(options.finalAmount * 1_000_000);
239
- if (options?.providerSig)
240
- body.provider_sig = options.providerSig;
241
- const resp = await this._authFetch(`/tabs/${tabId}/close`, {
242
- method: "POST",
243
- body: JSON.stringify(body),
574
+ async getTab(tabId) {
575
+ const raw = await this.get(`/tabs/${tabId}`);
576
+ return parseTab(raw);
577
+ }
578
+ async chargeTab(tabId, amount) {
579
+ const micro = toMicro(amount);
580
+ const raw = await this.post(`/tabs/${tabId}/charge`, { amount: micro });
581
+ return { chargeId: raw.charge_id ?? "", status: raw.status };
582
+ }
583
+ // ── Public: x402 ─────────────────────────────────────────────────
584
+ async request(url, options) {
585
+ const method = options?.method ?? "GET";
586
+ const headers = options?.headers ?? {};
587
+ const bodyStr = options?.body
588
+ ? JSON.stringify(options.body)
589
+ : undefined;
590
+ const resp = await fetch(url, {
591
+ method,
592
+ body: bodyStr,
593
+ headers,
594
+ signal: AbortSignal.timeout(this.#timeout),
244
595
  });
245
- if (!resp.ok)
246
- throw new Error(`closeTab failed: ${resp.status}`);
247
- return (await resp.json());
596
+ if (resp.status !== 402)
597
+ return resp;
598
+ return this.handle402(resp, url, method, bodyStr, headers);
248
599
  }
249
- /** Fetch contract addresses from the API (public, no auth). */
250
- async getContracts() {
251
- if (this._contractsCache)
252
- return this._contractsCache;
253
- const resp = await fetch(`${this._apiUrl}/contracts`);
254
- if (!resp.ok)
255
- throw new Error(`getContracts failed: ${resp.status}`);
256
- const data = (await resp.json());
257
- this._contractsCache = {
258
- router: data.router ?? "",
259
- tab: data.tab ?? "",
260
- direct: data.direct ?? "",
261
- fee: data.fee ?? "",
262
- usdc: data.usdc ?? "",
263
- chainId: data.chain_id ?? 0,
600
+ // ── Public: Wallet ───────────────────────────────────────────────
601
+ async balance() {
602
+ const raw = await this.get("/status");
603
+ const total = raw.balance_usdc
604
+ ? Number(raw.balance_usdc) / 1_000_000
605
+ : 0;
606
+ const locked = (raw.total_locked ?? 0) / 1_000_000;
607
+ return { total, locked, available: total - locked };
608
+ }
609
+ async status() {
610
+ const raw = await this.get("/status");
611
+ const total = raw.balance_usdc
612
+ ? Number(raw.balance_usdc) / 1_000_000
613
+ : 0;
614
+ const locked = (raw.total_locked ?? 0) / 1_000_000;
615
+ return {
616
+ address: raw.wallet,
617
+ balance: { total, locked, available: total - locked },
618
+ openTabs: raw.open_tabs,
264
619
  };
265
- return this._contractsCache;
266
620
  }
267
- /** Sign a tab charge (provider-side EIP-712 signature). */
268
- async signTabCharge(contractAddr, tabId, cumulativeUnits, callCount) {
269
- return this._account.signTypedData({
270
- domain: {
271
- name: "pay",
272
- version: "0.1",
273
- chainId: this._chainId,
274
- verifyingContract: contractAddr,
275
- },
276
- types: {
277
- TabCharge: [
278
- { name: "tabId", type: "string" },
279
- { name: "cumulativeUnits", type: "uint256" },
280
- { name: "callCount", type: "uint256" },
281
- ],
282
- },
283
- primaryType: "TabCharge",
284
- message: {
285
- tabId,
286
- cumulativeUnits: BigInt(cumulativeUnits),
287
- callCount: BigInt(callCount),
288
- },
289
- });
621
+ // ── Public: Discovery ────────────────────────────────────────────
622
+ async discover(query, options) {
623
+ return discoverImpl(this.#apiUrl, this.#timeout, query, options);
290
624
  }
291
- /** Sign a raw hash with the wallet's private key. */
292
- async _signHash(hash) {
293
- const signature = await this._account.signMessage({
294
- message: { raw: hash },
625
+ // ── Public: Funding ──────────────────────────────────────────────
626
+ async createFundLink(options) {
627
+ const data = await this.post("/links/fund", {
628
+ messages: options?.message ? [{ text: options.message }] : [],
629
+ agent_name: options?.agentName,
295
630
  });
296
- // Parse 65-byte signature into v, r, s
297
- const sigClean = signature.startsWith("0x")
298
- ? signature.slice(2)
299
- : signature;
300
- const r = "0x" + sigClean.slice(0, 64);
301
- const s = "0x" + sigClean.slice(64, 128);
302
- const v = parseInt(sigClean.slice(128, 130), 16);
303
- return { v, r, s };
631
+ return data.url;
304
632
  }
305
- }
306
- /** PrivateKeySigner for manual EIP-712 signing in the playground. */
307
- export class PrivateKeySigner {
308
- _account;
309
- address;
310
- constructor(privateKey) {
311
- const key = normalizeKey(privateKey);
312
- this._account = privateKeyToAccount(key);
313
- this.address = this._account.address;
314
- }
315
- /** Sign EIP-712 typed data. Returns hex signature. */
316
- async signTypedData(domain, types, message) {
317
- return this._account.signTypedData({
318
- domain: domain,
319
- types: types,
320
- primaryType: Object.keys(types)[0],
321
- message,
633
+ async createWithdrawLink(options) {
634
+ const data = await this.post("/links/withdraw", {
635
+ messages: options?.message ? [{ text: options.message }] : [],
636
+ agent_name: options?.agentName,
322
637
  });
638
+ return data.url;
639
+ }
640
+ // ── Public: Webhooks ─────────────────────────────────────────────
641
+ async registerWebhook(url, events, secret) {
642
+ const payload = { url };
643
+ if (events)
644
+ payload.events = events;
645
+ if (secret)
646
+ payload.secret = secret;
647
+ const raw = await this.post("/webhooks", payload);
648
+ return { id: raw.id, url: raw.url, events: raw.events };
649
+ }
650
+ async listWebhooks() {
651
+ const raw = await this.get("/webhooks");
652
+ return raw.map((w) => ({ id: w.id, url: w.url, events: w.events }));
653
+ }
654
+ async deleteWebhook(webhookId) {
655
+ await this.del(`/webhooks/${webhookId}`);
656
+ }
657
+ // ── Public: Testnet ──────────────────────────────────────────────
658
+ async mint(amount) {
659
+ if (!this.#testnet) {
660
+ throw new PayError("mint is only available on testnet");
661
+ }
662
+ const micro = toMicro(amount);
663
+ const raw = await this.post("/mint", { amount: micro });
664
+ return { txHash: raw.tx_hash, amount: toDollars(raw.amount) };
323
665
  }
324
666
  }
325
- /** Normalize a private key to 0x-prefixed Hex. */
326
- function normalizeKey(key) {
327
- if (key.startsWith("0x"))
328
- return key;
329
- return ("0x" + key);
667
+ // ── x402 helpers ─────────────────────────────────────────────────────
668
+ function extract402(obj) {
669
+ const accepts = obj.accepts;
670
+ if (Array.isArray(accepts) && accepts.length > 0) {
671
+ const offer = accepts[0];
672
+ const extra = (offer.extra ?? {});
673
+ return {
674
+ settlement: String(extra.settlement ?? "direct"),
675
+ amount: Number(offer.amount ?? 0),
676
+ to: String(offer.payTo ?? ""),
677
+ accepted: offer,
678
+ };
679
+ }
680
+ return {
681
+ settlement: String(obj.settlement ?? "direct"),
682
+ amount: Number(obj.amount ?? 0),
683
+ to: String(obj.to ?? ""),
684
+ };
330
685
  }
331
686
  //# sourceMappingURL=wallet.js.map