@armory-sh/client-web3 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sawyer Cutler
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # @armory-sh/client-web3
2
+
3
+ Web3.js client for creating and signing Armory payments.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ bun add @armory-sh/client-web3
9
+ ```
10
+
11
+ ## Use
12
+
13
+ ```typescript
14
+ import { Web3 } from 'web3'
15
+ import { createArmoryPayment } from '@armory-sh/client-web3'
16
+
17
+ const web3 = new Web3('https://mainnet.base.org')
18
+
19
+ const payment = await createArmoryPayment(web3, {
20
+ to: '0x...',
21
+ amount: 1000000n,
22
+ chainId: 'eip155:8453',
23
+ assetId: 'eip155:8453/erc20:0x...'
24
+ })
25
+ ```
26
+
27
+ ---
28
+
29
+ MIT License | Sawyer Cutler 2026 | Provided "AS IS" without warranty
@@ -0,0 +1,147 @@
1
+ import { Web3BaseWalletAccount, Web3BaseWallet } from 'web3-types';
2
+ import { PaymentPayloadV1, PaymentPayloadV2, CustomToken, NetworkConfig, PaymentRequirementsV1, PaymentRequirementsV2, SettlementResponseV1, SettlementResponseV2 } from '@armory-sh/base';
3
+ export { EIP712_TYPES as CORE_EIP712_TYPES, USDC_DOMAIN as CORE_USDC_DOMAIN, NETWORKS, NetworkConfig, PaymentPayload, PaymentPayloadV1, PaymentPayloadV2, PaymentRequirements, PaymentRequirementsV1, PaymentRequirementsV2, SettlementResponse, SettlementResponseV1, SettlementResponseV2, V1_HEADERS, V2_HEADERS, createEIP712Domain as createCoreEIP712Domain, createTransferWithAuthorization as createCoreTransferWithAuthorization, decodePaymentV1, decodePaymentV2, decodeSettlementV1, decodeSettlementV2, encodePaymentV1, encodePaymentV2, encodeSettlementV1, encodeSettlementV2, getMainnets, getNetworkByChainId, getNetworkConfig, getPaymentHeaderName, getPaymentRequiredHeaderName, getPaymentResponseHeaderName, getPaymentVersionFromPayload, getRequirementsVersion, getSettlementVersion, getTestnets, getTxHash, isAddress, isCAIP2ChainId, isCAIPAssetId, isSettlementSuccessful, isV1, isV2, validateTransferWithAuthorization as validateCoreTransferWithAuthorization } from '@armory-sh/base';
4
+
5
+ type Web3Account = Web3BaseWalletAccount | Web3BaseWallet<Web3BaseWalletAccount>;
6
+ /** Token configuration - can use pre-configured tokens from @armory-sh/tokens */
7
+ type Token = CustomToken;
8
+ interface Web3ClientConfig {
9
+ account: Web3Account;
10
+ network: NetworkConfig | string;
11
+ version?: 1 | 2;
12
+ rpcUrl?: string;
13
+ /** Pre-configured token object (overrides individual fields below) */
14
+ token?: Token;
15
+ /** Override EIP-712 domain name for custom tokens */
16
+ domainName?: string;
17
+ /** Override EIP-712 domain version for custom tokens */
18
+ domainVersion?: string;
19
+ }
20
+ interface PaymentSignatureResult {
21
+ v?: number;
22
+ r?: string;
23
+ s?: string;
24
+ signature?: {
25
+ v: number;
26
+ r: string;
27
+ s: string;
28
+ };
29
+ payload: PaymentPayloadV1 | PaymentPayloadV2;
30
+ }
31
+ interface PaymentSignOptions {
32
+ amount: string | bigint;
33
+ to: string;
34
+ nonce?: string;
35
+ expiry?: number;
36
+ validAfter?: number;
37
+ }
38
+ interface X402RequestContext {
39
+ url: string;
40
+ method: string;
41
+ headers: Record<string, string> | Headers;
42
+ body?: string | Record<string, unknown> | null;
43
+ version: 1 | 2;
44
+ }
45
+ interface X402TransportOptions {
46
+ client: Web3X402Client;
47
+ autoSign?: boolean;
48
+ maxRetries?: number;
49
+ }
50
+ interface Web3X402Client {
51
+ getAccount(): Web3Account;
52
+ getNetwork(): NetworkConfig;
53
+ getVersion(): 1 | 2;
54
+ signPayment(options: PaymentSignOptions): Promise<PaymentSignatureResult>;
55
+ createPaymentHeaders(options: PaymentSignOptions): Promise<Headers>;
56
+ handlePaymentRequired(requirements: PaymentRequirementsV1 | PaymentRequirementsV2): Promise<PaymentSignatureResult>;
57
+ verifySettlement(response: SettlementResponseV1 | SettlementResponseV2): boolean;
58
+ }
59
+ interface X402Transport {
60
+ fetch(url: string | Request, init?: RequestInit): Promise<Response>;
61
+ getClient(): Web3X402Client;
62
+ }
63
+ interface Web3TransferWithAuthorization {
64
+ from: string;
65
+ to: string;
66
+ value: string | bigint;
67
+ validAfter: string | bigint;
68
+ validBefore: string | bigint;
69
+ nonce: string | bigint;
70
+ }
71
+ interface Web3EIP712Domain {
72
+ name: string;
73
+ version: string;
74
+ chainId: string | number;
75
+ verifyingContract: string;
76
+ [key: string]: string | number;
77
+ }
78
+ declare const isV1Requirements: (requirements: PaymentRequirementsV1 | PaymentRequirementsV2) => requirements is PaymentRequirementsV1;
79
+ declare const isV2Requirements: (requirements: PaymentRequirementsV1 | PaymentRequirementsV2) => requirements is PaymentRequirementsV2;
80
+ declare const isV1Settlement: (response: SettlementResponseV1 | SettlementResponseV2) => response is SettlementResponseV1;
81
+ declare const isV2Settlement: (response: SettlementResponseV1 | SettlementResponseV2) => response is SettlementResponseV2;
82
+
83
+ declare const createX402Client: (config: Web3ClientConfig) => Web3X402Client;
84
+
85
+ declare const createX402Transport: (options: X402TransportOptions) => X402Transport;
86
+ declare const createFetchWithX402: (transport: X402Transport) => (url: string | Request, init?: RequestInit) => Promise<Response>;
87
+
88
+ declare const EIP712_TYPES: {
89
+ readonly EIP712Domain: readonly [{
90
+ readonly name: "name";
91
+ readonly type: "string";
92
+ }, {
93
+ readonly name: "version";
94
+ readonly type: "string";
95
+ }, {
96
+ readonly name: "chainId";
97
+ readonly type: "uint256";
98
+ }, {
99
+ readonly name: "verifyingContract";
100
+ readonly type: "address";
101
+ }];
102
+ readonly TransferWithAuthorization: readonly [{
103
+ readonly name: "from";
104
+ readonly type: "address";
105
+ }, {
106
+ readonly name: "to";
107
+ readonly type: "address";
108
+ }, {
109
+ readonly name: "value";
110
+ readonly type: "uint256";
111
+ }, {
112
+ readonly name: "validAfter";
113
+ readonly type: "uint256";
114
+ }, {
115
+ readonly name: "validBefore";
116
+ readonly type: "uint256";
117
+ }, {
118
+ readonly name: "nonce";
119
+ readonly type: "uint256";
120
+ }];
121
+ };
122
+ declare const USDC_DOMAIN: {
123
+ readonly NAME: "USD Coin";
124
+ readonly VERSION: "2";
125
+ };
126
+ declare const createEIP712Domain: (chainId: number | string, contractAddress: string, domainName?: string, domainVersion?: string) => Web3EIP712Domain;
127
+ declare const createTransferWithAuthorization: (params: Web3TransferWithAuthorization) => Record<string, string>;
128
+ declare const validateTransferWithAuthorization: (message: Web3TransferWithAuthorization) => boolean;
129
+ declare const parseSignature: (signature: string) => {
130
+ v: number;
131
+ r: string;
132
+ s: string;
133
+ };
134
+ declare const concatenateSignature: (v: number, r: string, s: string) => string;
135
+ declare const adjustVForChainId: (v: number, chainId: number) => number;
136
+ declare const signTypedData: (_account: Web3BaseWalletAccount | Web3BaseWallet<Web3BaseWalletAccount>, _domain: Web3EIP712Domain, _message: Record<string, string>) => Promise<{
137
+ v: number;
138
+ r: string;
139
+ s: string;
140
+ }>;
141
+ declare const signWithPrivateKey: (_privateKey: string, _domain: Web3EIP712Domain, _message: Record<string, string>) => Promise<{
142
+ v: number;
143
+ r: string;
144
+ s: string;
145
+ }>;
146
+
147
+ export { EIP712_TYPES, type PaymentSignOptions, type PaymentSignatureResult, type Token, USDC_DOMAIN, type Web3Account, type Web3ClientConfig, type Web3EIP712Domain, type Web3TransferWithAuthorization, type Web3X402Client, type X402RequestContext, type X402Transport, type X402TransportOptions, adjustVForChainId, concatenateSignature, createEIP712Domain, createFetchWithX402, createTransferWithAuthorization, createX402Client, createX402Transport, isV1Requirements, isV1Settlement, isV2Requirements, isV2Settlement, parseSignature, signTypedData, signWithPrivateKey, validateTransferWithAuthorization };
package/dist/index.js ADDED
@@ -0,0 +1,504 @@
1
+ // src/client.ts
2
+ import { Web3 } from "web3";
3
+ import {
4
+ getNetworkConfig,
5
+ encodePaymentV1,
6
+ encodePaymentV2
7
+ } from "@armory-sh/base";
8
+
9
+ // src/eip3009.ts
10
+ var EIP712_TYPES = {
11
+ EIP712Domain: [
12
+ { name: "name", type: "string" },
13
+ { name: "version", type: "string" },
14
+ { name: "chainId", type: "uint256" },
15
+ { name: "verifyingContract", type: "address" }
16
+ ],
17
+ TransferWithAuthorization: [
18
+ { name: "from", type: "address" },
19
+ { name: "to", type: "address" },
20
+ { name: "value", type: "uint256" },
21
+ { name: "validAfter", type: "uint256" },
22
+ { name: "validBefore", type: "uint256" },
23
+ { name: "nonce", type: "uint256" }
24
+ ]
25
+ };
26
+ var USDC_DOMAIN = {
27
+ NAME: "USD Coin",
28
+ VERSION: "2"
29
+ };
30
+ var toQuantity = (value) => {
31
+ if (typeof value === "bigint") return value.toString();
32
+ if (typeof value === "number") return `0x${value.toString(16)}`;
33
+ return value;
34
+ };
35
+ var toBigInt = (value) => {
36
+ if (typeof value === "bigint") return value;
37
+ if (typeof value === "number") return BigInt(Math.floor(value));
38
+ if (typeof value === "string") {
39
+ return value.startsWith("0x") ? BigInt(value) : BigInt(value);
40
+ }
41
+ throw new Error(`Invalid value type: ${typeof value}`);
42
+ };
43
+ var createEIP712Domain = (chainId, contractAddress, domainName, domainVersion) => ({
44
+ name: domainName ?? USDC_DOMAIN.NAME,
45
+ version: domainVersion ?? USDC_DOMAIN.VERSION,
46
+ chainId: toQuantity(chainId),
47
+ verifyingContract: contractAddress.toLowerCase()
48
+ });
49
+ var createTransferWithAuthorization = (params) => ({
50
+ from: params.from.toLowerCase(),
51
+ to: params.to.toLowerCase(),
52
+ value: toQuantity(params.value),
53
+ validAfter: toQuantity(params.validAfter),
54
+ validBefore: toQuantity(params.validBefore),
55
+ nonce: toQuantity(params.nonce)
56
+ });
57
+ var validateTransferWithAuthorization = (message) => {
58
+ const addressRegex = /^0x[a-fA-F0-9]{40}$/;
59
+ if (!addressRegex.test(message.from)) {
60
+ throw new Error(`Invalid "from" address: ${message.from}`);
61
+ }
62
+ if (!addressRegex.test(message.to)) {
63
+ throw new Error(`Invalid "to" address: ${message.to}`);
64
+ }
65
+ const value = toBigInt(message.value);
66
+ if (value < 0n) {
67
+ throw new Error(`"value" must be non-negative: ${value}`);
68
+ }
69
+ const validAfter = toBigInt(message.validAfter);
70
+ const validBefore = toBigInt(message.validBefore);
71
+ if (validAfter < 0n) {
72
+ throw new Error(`"validAfter" must be non-negative: ${validAfter}`);
73
+ }
74
+ if (validBefore < 0n) {
75
+ throw new Error(`"validBefore" must be non-negative: ${validBefore}`);
76
+ }
77
+ if (validAfter >= validBefore) {
78
+ throw new Error(
79
+ `"validAfter" (${validAfter}) must be before "validBefore" (${validBefore})`
80
+ );
81
+ }
82
+ const nonce = toBigInt(message.nonce);
83
+ if (nonce < 0n) {
84
+ throw new Error(`"nonce" must be non-negative: ${nonce}`);
85
+ }
86
+ return true;
87
+ };
88
+ var parseSignature = (signature) => {
89
+ const hexSig = signature.startsWith("0x") ? signature.slice(2) : signature;
90
+ if (hexSig.length !== 130) {
91
+ throw new Error(`Invalid signature length: ${hexSig.length} (expected 130)`);
92
+ }
93
+ return {
94
+ r: `0x${hexSig.slice(0, 64)}`,
95
+ s: `0x${hexSig.slice(64, 128)}`,
96
+ v: parseInt(hexSig.slice(128, 130), 16)
97
+ };
98
+ };
99
+ var concatenateSignature = (v, r, s) => {
100
+ const rHex = r.startsWith("0x") ? r.slice(2) : r;
101
+ const sHex = s.startsWith("0x") ? s.slice(2) : s;
102
+ const vHex = v.toString(16).padStart(2, "0");
103
+ return `0x${rHex}${sHex}${vHex}`;
104
+ };
105
+ var adjustVForChainId = (v, chainId) => {
106
+ if (v === 27 || v === 28) return v;
107
+ const chainIdBit = chainId * 2 + 35;
108
+ return v - chainIdBit + 27;
109
+ };
110
+ var signTypedData = async (_account, _domain, _message) => {
111
+ throw new Error(
112
+ "EIP-712 signing requires web3-eth-personal or wallet provider."
113
+ );
114
+ };
115
+ var signWithPrivateKey = async (_privateKey, _domain, _message) => {
116
+ throw new Error(
117
+ "Direct private key signing not implemented. Use wallet provider's signTypedData method instead."
118
+ );
119
+ };
120
+
121
+ // src/client.ts
122
+ var DEFAULT_EXPIRY_SECONDS = 3600;
123
+ var DEFAULT_VALID_AFTER = 0;
124
+ var extractDomainConfig = (config) => {
125
+ if (config.token) {
126
+ return {
127
+ domainName: config.token.name,
128
+ domainVersion: config.token.version
129
+ };
130
+ }
131
+ return {
132
+ domainName: config.domainName,
133
+ domainVersion: config.domainVersion
134
+ };
135
+ };
136
+ var createClientState = (config) => {
137
+ const network = typeof config.network === "string" ? getNetworkConfig(config.network) ?? (() => {
138
+ throw new Error(`Unknown network: ${config.network}`);
139
+ })() : config.network;
140
+ const { domainName, domainVersion } = extractDomainConfig(config);
141
+ return {
142
+ account: config.account,
143
+ version: config.version ?? 2,
144
+ network,
145
+ web3: new Web3(config.rpcUrl ?? network.rpcUrl),
146
+ domainName,
147
+ domainVersion
148
+ };
149
+ };
150
+ var getAddress = (account) => {
151
+ if ("address" in account) return account.address;
152
+ if (Array.isArray(account) && account[0]) return account[0].address;
153
+ throw new Error("Unable to get address from account");
154
+ };
155
+ var parseSignature2 = (signature) => {
156
+ const hexSig = signature.startsWith("0x") ? signature.slice(2) : signature;
157
+ if (hexSig.length !== 130) throw new Error(`Invalid signature length: ${hexSig.length}`);
158
+ return {
159
+ r: `0x${hexSig.slice(0, 64)}`,
160
+ s: `0x${hexSig.slice(64, 128)}`,
161
+ v: parseInt(hexSig.slice(128, 130), 16)
162
+ };
163
+ };
164
+ var signTypedDataWrapper = async (account, domain, message) => {
165
+ const acc = account;
166
+ if (typeof acc.signTypedData === "function") {
167
+ const sig = await acc.signTypedData(domain, message);
168
+ return parseSignature2(sig);
169
+ }
170
+ const getAddress2 = () => {
171
+ if ("address" in account) return account.address;
172
+ if (Array.isArray(account) && account[0]) return account[0].address;
173
+ throw new Error("Unable to get address from account");
174
+ };
175
+ if (typeof acc.request === "function") {
176
+ const sig = await acc.request({
177
+ method: "eth_signTypedData_v4",
178
+ params: [getAddress2(), JSON.stringify({ domain, message })]
179
+ });
180
+ return parseSignature2(sig);
181
+ }
182
+ if ("privateKey" in account && typeof account.privateKey === "string") {
183
+ throw new Error("Direct private key signing not implemented. Use wallet provider with signTypedData.");
184
+ }
185
+ throw new Error("Account does not support EIP-712 signing.");
186
+ };
187
+ var signPaymentV1 = async (state, params) => {
188
+ const { from, to, amount, nonce, expiry, validAfter } = params;
189
+ const { network, domainName, domainVersion } = state;
190
+ const domain = createEIP712Domain(network.chainId, network.usdcAddress, domainName, domainVersion);
191
+ const message = createTransferWithAuthorization({
192
+ from,
193
+ to,
194
+ value: amount,
195
+ validAfter: `0x${validAfter.toString(16)}`,
196
+ validBefore: `0x${expiry.toString(16)}`,
197
+ nonce: `0x${nonce}`
198
+ });
199
+ const signature = await signTypedDataWrapper(state.account, domain, message);
200
+ const payload = {
201
+ from,
202
+ to,
203
+ amount,
204
+ nonce,
205
+ expiry,
206
+ v: signature.v,
207
+ r: signature.r,
208
+ s: signature.s,
209
+ chainId: network.chainId,
210
+ contractAddress: network.usdcAddress,
211
+ network: network.name.toLowerCase().replace(" ", "-")
212
+ };
213
+ return { v: signature.v, r: signature.r, s: signature.s, payload };
214
+ };
215
+ var signPaymentV2 = async (state, params) => {
216
+ const { from, to, amount, nonce, expiry } = params;
217
+ const { network, domainName, domainVersion } = state;
218
+ const domain = createEIP712Domain(network.chainId, network.usdcAddress, domainName, domainVersion);
219
+ const message = createTransferWithAuthorization({
220
+ from,
221
+ to,
222
+ value: amount,
223
+ validAfter: "0x0",
224
+ validBefore: `0x${expiry.toString(16)}`,
225
+ nonce: `0x${nonce}`
226
+ });
227
+ const signature = await signTypedDataWrapper(state.account, domain, message);
228
+ const payload = {
229
+ from,
230
+ to,
231
+ amount,
232
+ nonce,
233
+ expiry,
234
+ signature: {
235
+ v: signature.v,
236
+ r: signature.r,
237
+ s: signature.s
238
+ },
239
+ chainId: network.caip2Id,
240
+ assetId: network.caipAssetId
241
+ };
242
+ return { signature: payload.signature, payload };
243
+ };
244
+ var createX402Client = (config) => {
245
+ const state = createClientState(config);
246
+ return {
247
+ getAccount: () => state.account,
248
+ getNetwork: () => state.network,
249
+ getVersion: () => state.version,
250
+ signPayment: async (options) => {
251
+ const from = getAddress(state.account);
252
+ const to = options.to;
253
+ const amount = options.amount.toString();
254
+ const nonce = options.nonce ?? crypto.randomUUID();
255
+ const expiry = options.expiry ?? Math.floor(Date.now() / 1e3) + DEFAULT_EXPIRY_SECONDS;
256
+ if (state.version === 1) {
257
+ return signPaymentV1(state, {
258
+ from,
259
+ to,
260
+ amount,
261
+ nonce,
262
+ expiry,
263
+ validAfter: options.validAfter ?? DEFAULT_VALID_AFTER
264
+ });
265
+ }
266
+ return signPaymentV2(state, { from, to, amount, nonce, expiry });
267
+ },
268
+ createPaymentHeaders: async (options) => {
269
+ const result = await signPayment(options, state);
270
+ const headers = new Headers();
271
+ if (state.version === 1) {
272
+ headers.set("X-PAYMENT", encodePaymentV1(result.payload));
273
+ } else {
274
+ headers.set("PAYMENT-SIGNATURE", encodePaymentV2(result.payload));
275
+ }
276
+ return headers;
277
+ },
278
+ handlePaymentRequired: async (requirements) => {
279
+ if ("contractAddress" in requirements) {
280
+ const req2 = requirements;
281
+ return signPayment({
282
+ amount: req2.amount,
283
+ to: req2.payTo,
284
+ expiry: req2.expiry
285
+ }, state);
286
+ }
287
+ const req = requirements;
288
+ const to = typeof req.to === "string" ? req.to : "0x0000000000000000000000000000000000000000";
289
+ return signPayment({
290
+ amount: req.amount,
291
+ to,
292
+ nonce: req.nonce,
293
+ expiry: req.expiry
294
+ }, state);
295
+ },
296
+ verifySettlement: (response) => {
297
+ return "success" in response ? response.success : response.status === "success";
298
+ }
299
+ };
300
+ };
301
+ var signPayment = async (options, state) => {
302
+ const from = getAddress(state.account);
303
+ if (state.version === 1) {
304
+ return signPaymentV1(state, {
305
+ from,
306
+ to: options.to,
307
+ amount: options.amount.toString(),
308
+ nonce: options.nonce ?? crypto.randomUUID(),
309
+ expiry: options.expiry ?? Math.floor(Date.now() / 1e3) + DEFAULT_EXPIRY_SECONDS,
310
+ validAfter: options.validAfter ?? DEFAULT_VALID_AFTER
311
+ });
312
+ }
313
+ return signPaymentV2(state, {
314
+ from,
315
+ to: options.to,
316
+ amount: options.amount.toString(),
317
+ nonce: options.nonce ?? crypto.randomUUID(),
318
+ expiry: options.expiry ?? Math.floor(Date.now() / 1e3) + DEFAULT_EXPIRY_SECONDS
319
+ });
320
+ };
321
+
322
+ // src/transport.ts
323
+ import { V1_HEADERS, V2_HEADERS, encodePaymentV1 as encodePaymentV12, encodePaymentV2 as encodePaymentV22 } from "@armory-sh/base";
324
+ var DEFAULT_MAX_RETRIES = 3;
325
+ var detectProtocolVersion = (response, client) => {
326
+ if (response.headers.has(V2_HEADERS.PAYMENT_REQUIRED) || response.headers.has("PAYMENT-REQUIRED")) {
327
+ return 2;
328
+ }
329
+ if (response.headers.has("X-PAYMENT-REQUIRED")) {
330
+ return 1;
331
+ }
332
+ return client.getVersion();
333
+ };
334
+ var parsePaymentRequirements = async (response, version) => {
335
+ if (version === 2) {
336
+ const header = response.headers.get(V2_HEADERS.PAYMENT_REQUIRED);
337
+ if (header) return JSON.parse(header);
338
+ } else {
339
+ const header = response.headers.get("X-PAYMENT-REQUIRED");
340
+ if (header) {
341
+ const json = Buffer.from(header, "base64").toString("utf-8");
342
+ return JSON.parse(json);
343
+ }
344
+ }
345
+ return JSON.parse(await response.clone().text());
346
+ };
347
+ var createPaymentHeaders = (payload, version) => {
348
+ const headers = new Headers();
349
+ if (version === 1) {
350
+ headers.set(V1_HEADERS.PAYMENT, encodePaymentV12(payload));
351
+ } else {
352
+ headers.set(V2_HEADERS.PAYMENT_SIGNATURE, encodePaymentV22(payload));
353
+ }
354
+ return headers;
355
+ };
356
+ var isPaymentRelatedError = (error) => error.message.includes("402") || error.message.includes("payment") || error.message.includes("signature");
357
+ var backoff = (attempt) => {
358
+ const delay = Math.min(1e3 * Math.pow(2, attempt - 1), 1e4);
359
+ return new Promise((resolve) => setTimeout(resolve, delay));
360
+ };
361
+ var handlePaymentRequired = async (response, client) => {
362
+ const version = detectProtocolVersion(response, client);
363
+ const requirements = await parsePaymentRequirements(response, version);
364
+ const result = await client.handlePaymentRequired(
365
+ requirements
366
+ );
367
+ return createPaymentHeaders(result.payload, version);
368
+ };
369
+ var mergePaymentHeaders = (init = {}, paymentHeaders) => {
370
+ const existingHeaders = new Headers(init.headers);
371
+ for (const [key, value] of paymentHeaders.entries()) {
372
+ existingHeaders.set(key, value);
373
+ }
374
+ return { ...init, headers: existingHeaders };
375
+ };
376
+ var createX402Transport = (options) => {
377
+ const client = options.client;
378
+ const autoSign = options.autoSign ?? true;
379
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
380
+ return {
381
+ getClient: () => client,
382
+ fetch: async (url, init) => {
383
+ let attempt = 0;
384
+ let lastError;
385
+ while (attempt < maxRetries) {
386
+ attempt++;
387
+ try {
388
+ const response = await fetch(url, init);
389
+ if (response.status === 402 && autoSign) {
390
+ const paymentHeaders = await handlePaymentRequired(response, client);
391
+ const newInit = mergePaymentHeaders(init, paymentHeaders);
392
+ return await fetch(url, newInit);
393
+ }
394
+ return response;
395
+ } catch (error) {
396
+ lastError = error instanceof Error ? error : new Error(String(error));
397
+ if (!isPaymentRelatedError(lastError)) {
398
+ throw lastError;
399
+ }
400
+ if (attempt < maxRetries) {
401
+ await backoff(attempt);
402
+ }
403
+ }
404
+ }
405
+ throw lastError ?? new Error("Max retries exceeded");
406
+ }
407
+ };
408
+ };
409
+ var createFetchWithX402 = (transport) => (url, init) => transport.fetch(url, init);
410
+
411
+ // src/types.ts
412
+ var isV1Requirements = (requirements) => "contractAddress" in requirements;
413
+ var isV2Requirements = (requirements) => "chainId" in requirements && "assetId" in requirements;
414
+ var isV1Settlement = (response) => "success" in response;
415
+ var isV2Settlement = (response) => "status" in response;
416
+
417
+ // src/index.ts
418
+ import {
419
+ V1_HEADERS as V1_HEADERS2,
420
+ encodePaymentV1 as encodePaymentV13,
421
+ decodePaymentV1,
422
+ encodeSettlementV1,
423
+ decodeSettlementV1,
424
+ V2_HEADERS as V2_HEADERS2,
425
+ isCAIP2ChainId,
426
+ isCAIPAssetId,
427
+ isAddress,
428
+ encodePaymentV2 as encodePaymentV23,
429
+ decodePaymentV2,
430
+ encodeSettlementV2,
431
+ decodeSettlementV2,
432
+ isV1,
433
+ isV2,
434
+ getPaymentVersionFromPayload,
435
+ getRequirementsVersion,
436
+ getSettlementVersion,
437
+ getPaymentHeaderName,
438
+ getPaymentResponseHeaderName,
439
+ getPaymentRequiredHeaderName,
440
+ isSettlementSuccessful,
441
+ getTxHash,
442
+ NETWORKS,
443
+ getNetworkConfig as getNetworkConfig2,
444
+ getNetworkByChainId,
445
+ getMainnets,
446
+ getTestnets,
447
+ EIP712_TYPES as EIP712_TYPES2,
448
+ USDC_DOMAIN as USDC_DOMAIN2,
449
+ createEIP712Domain as createEIP712Domain2,
450
+ createTransferWithAuthorization as createTransferWithAuthorization2,
451
+ validateTransferWithAuthorization as validateTransferWithAuthorization2
452
+ } from "@armory-sh/base";
453
+ export {
454
+ EIP712_TYPES2 as CORE_EIP712_TYPES,
455
+ USDC_DOMAIN2 as CORE_USDC_DOMAIN,
456
+ EIP712_TYPES,
457
+ NETWORKS,
458
+ USDC_DOMAIN,
459
+ V1_HEADERS2 as V1_HEADERS,
460
+ V2_HEADERS2 as V2_HEADERS,
461
+ adjustVForChainId,
462
+ concatenateSignature,
463
+ createEIP712Domain2 as createCoreEIP712Domain,
464
+ createTransferWithAuthorization2 as createCoreTransferWithAuthorization,
465
+ createEIP712Domain,
466
+ createFetchWithX402,
467
+ createTransferWithAuthorization,
468
+ createX402Client,
469
+ createX402Transport,
470
+ decodePaymentV1,
471
+ decodePaymentV2,
472
+ decodeSettlementV1,
473
+ decodeSettlementV2,
474
+ encodePaymentV13 as encodePaymentV1,
475
+ encodePaymentV23 as encodePaymentV2,
476
+ encodeSettlementV1,
477
+ encodeSettlementV2,
478
+ getMainnets,
479
+ getNetworkByChainId,
480
+ getNetworkConfig2 as getNetworkConfig,
481
+ getPaymentHeaderName,
482
+ getPaymentRequiredHeaderName,
483
+ getPaymentResponseHeaderName,
484
+ getPaymentVersionFromPayload,
485
+ getRequirementsVersion,
486
+ getSettlementVersion,
487
+ getTestnets,
488
+ getTxHash,
489
+ isAddress,
490
+ isCAIP2ChainId,
491
+ isCAIPAssetId,
492
+ isSettlementSuccessful,
493
+ isV1,
494
+ isV1Requirements,
495
+ isV1Settlement,
496
+ isV2,
497
+ isV2Requirements,
498
+ isV2Settlement,
499
+ parseSignature,
500
+ signTypedData,
501
+ signWithPrivateKey,
502
+ validateTransferWithAuthorization2 as validateCoreTransferWithAuthorization,
503
+ validateTransferWithAuthorization
504
+ };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@armory-sh/client-web3",
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "author": "Sawyer Cutler <sawyer@dirtroad.dev>",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "bun": "./src/index.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./dist/*": "./dist/*.js"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "README.md"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/thegreataxios/armory.git",
27
+ "directory": "packages/client-web3"
28
+ },
29
+ "dependencies": {
30
+ "@armory-sh/base": "workspace:*",
31
+ "web3": "4.16.0",
32
+ "web3-types": "1.10.0"
33
+ },
34
+ "devDependencies": {
35
+ "typescript": "5.9.3",
36
+ "bun-types": "latest"
37
+ },
38
+ "scripts": {
39
+ "build": "tsup",
40
+ "test": "bun test",
41
+ "example": "bun run examples/"
42
+ }
43
+ }