@armory-sh/client-web3 0.2.23-alpha.23.76 → 0.2.23-alpha.23.77

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/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Web3BaseWalletAccount, Web3BaseWallet } from 'web3-types';
2
1
  import { NetworkConfig, CustomToken, PaymentPayloadV2, PaymentRequirementsV2, SettlementResponseV2, NetworkId, TokenId, ArmoryPaymentResult, ValidationError } from '@armory-sh/base';
2
+ import { Web3BaseWalletAccount, Web3BaseWallet } from 'web3-types';
3
3
 
4
4
  type Web3Account = Web3BaseWalletAccount | Web3BaseWallet<Web3BaseWalletAccount>;
5
5
  /** Token configuration - can use pre-configured tokens from @armory-sh/tokens */
@@ -66,34 +66,6 @@ interface Web3EIP712Domain {
66
66
  [key: string]: string | number;
67
67
  }
68
68
 
69
- declare const createX402Client: (config: Web3ClientConfig) => Web3X402Client;
70
-
71
- /**
72
- * Create an x402 transport layer for handling payment-required responses
73
- */
74
- declare const createX402Transport: (options: X402TransportOptions) => X402Transport;
75
-
76
- declare const createEIP712Domain: (chainId: number | string, contractAddress: string, domainName?: string, domainVersion?: string) => Web3EIP712Domain;
77
- declare const createTransferWithAuthorization: (params: Web3TransferWithAuthorization) => Record<string, string>;
78
- declare const validateTransferWithAuthorization: (message: Web3TransferWithAuthorization) => boolean;
79
- declare const parseSignature: (signature: string) => {
80
- v: number;
81
- r: string;
82
- s: string;
83
- };
84
- declare const concatenateSignature: (v: number, r: string, s: string) => string;
85
- declare const adjustVForChainId: (v: number, chainId: number) => number;
86
- declare const signTypedData: (_account: Web3BaseWalletAccount | Web3BaseWallet<Web3BaseWalletAccount>, _domain: Web3EIP712Domain, _message: Record<string, string>) => Promise<{
87
- v: number;
88
- r: string;
89
- s: string;
90
- }>;
91
- declare const signWithPrivateKey: (_privateKey: string, _domain: Web3EIP712Domain, _message: Record<string, string>) => Promise<{
92
- v: number;
93
- r: string;
94
- s: string;
95
- }>;
96
-
97
69
  /**
98
70
  * Simple one-line payment API for Armory (Web3)
99
71
  * Focus on DX/UX - "everything just magically works"
@@ -204,4 +176,32 @@ interface ArmoryInstance {
204
176
  }
205
177
  declare const createArmory: (config: ArmoryConfig) => ArmoryInstance;
206
178
 
179
+ declare const createX402Client: (config: Web3ClientConfig) => Web3X402Client;
180
+
181
+ declare const createEIP712Domain: (chainId: number | string, contractAddress: string, domainName?: string, domainVersion?: string) => Web3EIP712Domain;
182
+ declare const createTransferWithAuthorization: (params: Web3TransferWithAuthorization) => Record<string, string>;
183
+ declare const validateTransferWithAuthorization: (message: Web3TransferWithAuthorization) => boolean;
184
+ declare const parseSignature: (signature: string) => {
185
+ v: number;
186
+ r: string;
187
+ s: string;
188
+ };
189
+ declare const concatenateSignature: (v: number, r: string, s: string) => string;
190
+ declare const adjustVForChainId: (v: number, chainId: number) => number;
191
+ declare const signTypedData: (_account: Web3BaseWalletAccount | Web3BaseWallet<Web3BaseWalletAccount>, _domain: Web3EIP712Domain, _message: Record<string, string>) => Promise<{
192
+ v: number;
193
+ r: string;
194
+ s: string;
195
+ }>;
196
+ declare const signWithPrivateKey: (_privateKey: string, _domain: Web3EIP712Domain, _message: Record<string, string>) => Promise<{
197
+ v: number;
198
+ r: string;
199
+ s: string;
200
+ }>;
201
+
202
+ /**
203
+ * Create an x402 transport layer for handling payment-required responses
204
+ */
205
+ declare const createX402Transport: (options: X402TransportOptions) => X402Transport;
206
+
207
207
  export { type ArmoryConfig, type ArmoryInstance, type HttpMethod, type NormalizedWallet, type PaymentOptions, type SimpleWalletInput, adjustVForChainId, armoryDelete, armoryGet, armoryPatch, armoryPay, armoryPost, armoryPut, concatenateSignature, createArmory, createEIP712Domain, createTransferWithAuthorization, createX402Client, createX402Transport, getNetworks, getTokens, getWalletAddress, normalizeWallet, parseSignature, signTypedData, signWithPrivateKey, validateNetwork, validateToken, validateTransferWithAuthorization };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Web3 } from 'web3';
2
1
  import { encodePaymentV2, validatePaymentConfig, isValidationError, resolveNetwork, resolveToken, V2_HEADERS, getNetworkConfig, getNetworkByChainId, networkToCaip2, combineSignatureV2, normalizeBase64Url, decodeBase64ToUtf8, isX402V2PaymentRequired } from '@armory-sh/base';
2
+ import { Web3 } from 'web3';
3
3
 
4
4
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
5
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
@@ -74,7 +74,9 @@ var validateTransferWithAuthorization = (message) => {
74
74
  var parseSignature = (signature) => {
75
75
  const hexSig = signature.startsWith("0x") ? signature.slice(2) : signature;
76
76
  if (hexSig.length !== 130) {
77
- throw new Error(`Invalid signature length: ${hexSig.length} (expected 130)`);
77
+ throw new Error(
78
+ `Invalid signature length: ${hexSig.length} (expected 130)`
79
+ );
78
80
  }
79
81
  return {
80
82
  r: `0x${hexSig.slice(0, 64)}`,
@@ -196,7 +198,8 @@ var getAddress = (account) => {
196
198
  };
197
199
  var parseSignature2 = (signature) => {
198
200
  const hexSig = signature.startsWith("0x") ? signature.slice(2) : signature;
199
- if (hexSig.length !== 130) throw new Error(`Invalid signature length: ${hexSig.length}`);
201
+ if (hexSig.length !== 130)
202
+ throw new Error(`Invalid signature length: ${hexSig.length}`);
200
203
  return {
201
204
  r: `0x${hexSig.slice(0, 64)}`,
202
205
  s: `0x${hexSig.slice(64, 128)}`,
@@ -222,7 +225,9 @@ var signTypedDataWrapper = async (account, domain, message) => {
222
225
  return parseSignature2(sig);
223
226
  }
224
227
  if ("privateKey" in account && typeof account.privateKey === "string") {
225
- throw new Error("Direct private key signing not implemented. Use wallet provider with signTypedData.");
228
+ throw new Error(
229
+ "Direct private key signing not implemented. Use wallet provider with signTypedData."
230
+ );
226
231
  }
227
232
  throw new Error("Account does not support EIP-712 signing.");
228
233
  };
@@ -237,12 +242,17 @@ var signPaymentV2 = async (state, network, params) => {
237
242
  maxTimeoutSeconds: expiry - Math.floor(Date.now() / 1e3)
238
243
  };
239
244
  const domainExtra = defaultAccepted.extra;
240
- const requirementDomainName = defaultAccepted.name ?? (domainExtra && typeof domainExtra === "object" && typeof domainExtra["name"] === "string" ? domainExtra["name"] : void 0);
241
- const requirementDomainVersion = defaultAccepted.version ?? (domainExtra && typeof domainExtra === "object" && typeof domainExtra["version"] === "string" ? domainExtra["version"] : void 0);
245
+ const requirementDomainName = defaultAccepted.name ?? (domainExtra && typeof domainExtra === "object" && typeof domainExtra.name === "string" ? domainExtra.name : void 0);
246
+ const requirementDomainVersion = defaultAccepted.version ?? (domainExtra && typeof domainExtra === "object" && typeof domainExtra.version === "string" ? domainExtra.version : void 0);
242
247
  const effectiveDomainName = state.domainName ?? requirementDomainName;
243
248
  const effectiveDomainVersion = state.domainVersion ?? requirementDomainVersion;
244
249
  const chainId = parseInt(defaultAccepted.network.split(":")[1], 10);
245
- const domain = createEIP712Domain(chainId, defaultAccepted.asset, effectiveDomainName, effectiveDomainVersion);
250
+ const domain = createEIP712Domain(
251
+ chainId,
252
+ defaultAccepted.asset,
253
+ effectiveDomainName,
254
+ effectiveDomainVersion
255
+ );
246
256
  const nowSeconds = Math.floor(Date.now() / 1e3);
247
257
  const validAfterHex = `0x${(nowSeconds - 600).toString(16)}`;
248
258
  const message = createTransferWithAuthorization({
@@ -311,7 +321,10 @@ var createX402Client = (config) => {
311
321
  accepted: req
312
322
  });
313
323
  const paymentHeaders = new Headers(init?.headers);
314
- paymentHeaders.set(V2_HEADERS.PAYMENT_SIGNATURE, encodePaymentV2(result.payload));
324
+ paymentHeaders.set(
325
+ V2_HEADERS.PAYMENT_SIGNATURE,
326
+ encodePaymentV2(result.payload)
327
+ );
315
328
  response = await fetch2(url, { ...init, headers: paymentHeaders });
316
329
  }
317
330
  return response;
@@ -323,7 +336,9 @@ var createX402Client = (config) => {
323
336
  getVersion: () => state.version,
324
337
  signPayment: async (options) => {
325
338
  const network = state.network ?? (() => {
326
- throw new Error("Network must be configured for manual payment signing");
339
+ throw new Error(
340
+ "Network must be configured for manual payment signing"
341
+ );
327
342
  })();
328
343
  const from = getAddress(state.account);
329
344
  const to = options.to;
@@ -334,14 +349,22 @@ var createX402Client = (config) => {
334
349
  },
335
350
  createPaymentHeaders: async (options) => {
336
351
  const network = state.network ?? (() => {
337
- throw new Error("Network must be configured for manual payment signing");
352
+ throw new Error(
353
+ "Network must be configured for manual payment signing"
354
+ );
338
355
  })();
339
356
  const from = getAddress(state.account);
340
357
  const to = options.to;
341
358
  const amount = options.amount.toString();
342
359
  const nonce = options.nonce ?? crypto.randomUUID();
343
360
  const expiry = options.expiry ?? Math.floor(Date.now() / 1e3) + DEFAULT_EXPIRY_SECONDS;
344
- const result = await signPaymentV2(state, network, { from, to, amount, nonce, expiry });
361
+ const result = await signPaymentV2(state, network, {
362
+ from,
363
+ to,
364
+ amount,
365
+ nonce,
366
+ expiry
367
+ });
345
368
  const headers = new Headers();
346
369
  headers.set("PAYMENT-SIGNATURE", encodePaymentV2(result.payload));
347
370
  return headers;
@@ -364,69 +387,8 @@ var createX402Client = (config) => {
364
387
  }
365
388
  };
366
389
  };
367
- var DEFAULT_MAX_RETRIES = 3;
368
- var createPaymentHeaders = (payload, _version) => {
369
- const headers = new Headers();
370
- headers.set(V2_HEADERS.PAYMENT_SIGNATURE, encodePaymentV2(payload));
371
- return headers;
372
- };
373
- var isPaymentRelatedError = (error) => error.message.includes("402") || error.message.includes("payment") || error.message.includes("signature") || error.message.includes("Payment");
374
- var backoff = (attempt) => {
375
- const baseDelay = Math.min(1e3 * Math.pow(2, attempt - 1), 1e4);
376
- const jitter = Math.random() * 100;
377
- return new Promise((resolve) => setTimeout(resolve, baseDelay + jitter));
378
- };
379
- var handlePaymentRequired = async (response, client) => {
380
- detectX402Version(response, client.getVersion());
381
- const parsed = await parsePaymentRequired(response);
382
- const selectedRequirements = parsed.requirements[0];
383
- if (!selectedRequirements) {
384
- throw new Error("No supported payment scheme found in requirements");
385
- }
386
- const req = selectedRequirements;
387
- const result = await client.handlePaymentRequired(req);
388
- return createPaymentHeaders(result.payload);
389
- };
390
- var mergePaymentHeaders = (init = {}, paymentHeaders) => {
391
- const existingHeaders = new Headers(init.headers);
392
- for (const [key, value] of paymentHeaders.entries()) {
393
- existingHeaders.set(key, value);
394
- }
395
- return { ...init, headers: existingHeaders };
396
- };
397
- var createX402Transport = (options) => {
398
- const client = options.client;
399
- const autoSign = options.autoSign ?? true;
400
- const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
401
- return {
402
- getClient: () => client,
403
- fetch: async (url, init) => {
404
- let attempt = 0;
405
- let lastError;
406
- while (attempt < maxRetries) {
407
- attempt++;
408
- try {
409
- const response = await fetch(url, init);
410
- if (isPaymentRequiredResponse(response) && autoSign) {
411
- const paymentHeaders = await handlePaymentRequired(response, client);
412
- const newInit = mergePaymentHeaders(init, paymentHeaders);
413
- return await fetch(url, newInit);
414
- }
415
- return response;
416
- } catch (error) {
417
- lastError = error instanceof Error ? error : new Error(String(error));
418
- if (!isPaymentRelatedError(lastError)) {
419
- throw lastError;
420
- }
421
- if (attempt < maxRetries) {
422
- await backoff(attempt);
423
- }
424
- }
425
- }
426
- throw lastError ?? new Error("Max retries exceeded");
427
- }
428
- };
429
- };
390
+
391
+ // src/payment-api.ts
430
392
  var normalizeWallet = (wallet) => {
431
393
  if (typeof wallet === "object" && wallet !== null && "account" in wallet) {
432
394
  return wallet.account;
@@ -495,19 +457,37 @@ var armoryPay = async (wallet, url, network, token, options) => {
495
457
  }
496
458
  };
497
459
  var armoryGet = (wallet, url, network, token, options) => {
498
- return armoryPay(wallet, url, network, token, { ...options, method: "GET" });
460
+ return armoryPay(wallet, url, network, token, {
461
+ ...options,
462
+ method: "GET"
463
+ });
499
464
  };
500
465
  var armoryPost = (wallet, url, network, token, body, options) => {
501
- return armoryPay(wallet, url, network, token, { ...options, method: "POST", body });
466
+ return armoryPay(wallet, url, network, token, {
467
+ ...options,
468
+ method: "POST",
469
+ body
470
+ });
502
471
  };
503
472
  var armoryPut = (wallet, url, network, token, body, options) => {
504
- return armoryPay(wallet, url, network, token, { ...options, method: "PUT", body });
473
+ return armoryPay(wallet, url, network, token, {
474
+ ...options,
475
+ method: "PUT",
476
+ body
477
+ });
505
478
  };
506
479
  var armoryDelete = (wallet, url, network, token, options) => {
507
- return armoryPay(wallet, url, network, token, { ...options, method: "DELETE" });
480
+ return armoryPay(wallet, url, network, token, {
481
+ ...options,
482
+ method: "DELETE"
483
+ });
508
484
  };
509
485
  var armoryPatch = (wallet, url, network, token, body, options) => {
510
- return armoryPay(wallet, url, network, token, { ...options, method: "PATCH", body });
486
+ return armoryPay(wallet, url, network, token, {
487
+ ...options,
488
+ method: "PATCH",
489
+ body
490
+ });
511
491
  };
512
492
  var getWalletAddress = (wallet) => {
513
493
  const account = normalizeWallet(wallet);
@@ -523,7 +503,7 @@ var validateNetwork = (network) => {
523
503
  return { success: true, network: resolved.config.name };
524
504
  };
525
505
  var validateToken = (token, network) => {
526
- let resolvedNetwork = void 0;
506
+ let resolvedNetwork;
527
507
  if (network) {
528
508
  const networkResult = resolveNetwork(network);
529
509
  if (isValidationError(networkResult)) {
@@ -551,7 +531,13 @@ var getTokens = () => {
551
531
  };
552
532
 
553
533
  // src/armory-api.ts
554
- var ALL_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "DELETE", "PATCH"]);
534
+ var ALL_METHODS = /* @__PURE__ */ new Set([
535
+ "GET",
536
+ "POST",
537
+ "PUT",
538
+ "DELETE",
539
+ "PATCH"
540
+ ]);
555
541
  var arrayify = (value) => {
556
542
  if (value === void 0) return void 0;
557
543
  return Array.isArray(value) ? value : [value];
@@ -607,5 +593,71 @@ var createArmory = (config) => {
607
593
  call: (url) => makeRequest(url, "GET")
608
594
  };
609
595
  };
596
+ var DEFAULT_MAX_RETRIES = 3;
597
+ var createPaymentHeaders = (payload, _version) => {
598
+ const headers = new Headers();
599
+ headers.set(V2_HEADERS.PAYMENT_SIGNATURE, encodePaymentV2(payload));
600
+ return headers;
601
+ };
602
+ var isPaymentRelatedError = (error) => error.message.includes("402") || error.message.includes("payment") || error.message.includes("signature") || error.message.includes("Payment");
603
+ var backoff = (attempt) => {
604
+ const baseDelay = Math.min(1e3 * 2 ** (attempt - 1), 1e4);
605
+ const jitter = Math.random() * 100;
606
+ return new Promise((resolve) => setTimeout(resolve, baseDelay + jitter));
607
+ };
608
+ var handlePaymentRequired = async (response, client) => {
609
+ detectX402Version(response, client.getVersion());
610
+ const parsed = await parsePaymentRequired(response);
611
+ const selectedRequirements = parsed.requirements[0];
612
+ if (!selectedRequirements) {
613
+ throw new Error("No supported payment scheme found in requirements");
614
+ }
615
+ const req = selectedRequirements;
616
+ const result = await client.handlePaymentRequired(req);
617
+ return createPaymentHeaders(result.payload);
618
+ };
619
+ var mergePaymentHeaders = (init = {}, paymentHeaders) => {
620
+ const existingHeaders = new Headers(init.headers);
621
+ for (const [key, value] of paymentHeaders.entries()) {
622
+ existingHeaders.set(key, value);
623
+ }
624
+ return { ...init, headers: existingHeaders };
625
+ };
626
+ var createX402Transport = (options) => {
627
+ const client = options.client;
628
+ const autoSign = options.autoSign ?? true;
629
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
630
+ return {
631
+ getClient: () => client,
632
+ fetch: async (url, init) => {
633
+ let attempt = 0;
634
+ let lastError;
635
+ while (attempt < maxRetries) {
636
+ attempt++;
637
+ try {
638
+ const response = await fetch(url, init);
639
+ if (isPaymentRequiredResponse(response) && autoSign) {
640
+ const paymentHeaders = await handlePaymentRequired(
641
+ response,
642
+ client
643
+ );
644
+ const newInit = mergePaymentHeaders(init, paymentHeaders);
645
+ return await fetch(url, newInit);
646
+ }
647
+ return response;
648
+ } catch (error) {
649
+ lastError = error instanceof Error ? error : new Error(String(error));
650
+ if (!isPaymentRelatedError(lastError)) {
651
+ throw lastError;
652
+ }
653
+ if (attempt < maxRetries) {
654
+ await backoff(attempt);
655
+ }
656
+ }
657
+ }
658
+ throw lastError ?? new Error("Max retries exceeded");
659
+ }
660
+ };
661
+ };
610
662
 
611
663
  export { adjustVForChainId, armoryDelete, armoryGet, armoryPatch, armoryPay, armoryPost, armoryPut, concatenateSignature, createArmory, createEIP712Domain, createTransferWithAuthorization, createX402Client, createX402Transport, getNetworks, getTokens, getWalletAddress, normalizeWallet, parseSignature, signTypedData, signWithPrivateKey, validateNetwork, validateToken, validateTransferWithAuthorization };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@armory-sh/client-web3",
3
- "version": "0.2.23-alpha.23.76",
3
+ "version": "0.2.23-alpha.23.77",
4
4
  "license": "MIT",
5
5
  "author": "Sawyer Cutler <sawyer@dirtroad.dev>",
6
6
  "keywords": [
@@ -46,7 +46,7 @@
46
46
  "directory": "packages/client-web3"
47
47
  },
48
48
  "dependencies": {
49
- "@armory-sh/base": "0.2.27-alpha.23.76",
49
+ "@armory-sh/base": "0.2.27-alpha.23.77",
50
50
  "web3": "4.16.0",
51
51
  "web3-types": "1.10.0"
52
52
  },
@@ -56,6 +56,8 @@
56
56
  },
57
57
  "scripts": {
58
58
  "build": "rm -rf dist && tsup",
59
+ "lint": "bun run build",
60
+ "format": "bun run lint",
59
61
  "test": "bun test",
60
62
  "example": "bun run examples/"
61
63
  }