@armory-sh/client-viem 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 +21 -0
- package/README.md +29 -0
- package/dist/index.d.ts +152 -0
- package/dist/index.js +421 -0
- package/package.json +42 -0
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-viem
|
|
2
|
+
|
|
3
|
+
Viem client for creating and signing Armory payments.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
bun add @armory-sh/client-viem
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Use
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { createWalletClient, http } from 'viem'
|
|
15
|
+
import { createArmoryPayment } from '@armory-sh/client-viem'
|
|
16
|
+
|
|
17
|
+
const client = createWalletClient({ transport: http() })
|
|
18
|
+
|
|
19
|
+
const payment = await createArmoryPayment(client, {
|
|
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
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { Address, Account, WalletClient, Transport } from 'viem';
|
|
2
|
+
import { CustomToken, PaymentPayloadV1, PaymentPayloadV2, NetworkId, TokenId, ArmoryPaymentResult, ValidationError } from '@armory-sh/base';
|
|
3
|
+
export { ArmoryPaymentResult, FacilitatorConfig, NetworkId, TokenId } from '@armory-sh/base';
|
|
4
|
+
|
|
5
|
+
type X402Wallet = {
|
|
6
|
+
type: "account";
|
|
7
|
+
account: Account;
|
|
8
|
+
} | {
|
|
9
|
+
type: "walletClient";
|
|
10
|
+
walletClient: WalletClient;
|
|
11
|
+
};
|
|
12
|
+
type X402ProtocolVersion = 1 | 2 | "auto";
|
|
13
|
+
/** Token configuration - can use pre-configured tokens from @armory-sh/tokens */
|
|
14
|
+
type Token = CustomToken;
|
|
15
|
+
interface X402ClientConfig {
|
|
16
|
+
wallet: X402Wallet;
|
|
17
|
+
version?: X402ProtocolVersion;
|
|
18
|
+
defaultExpiry?: number;
|
|
19
|
+
nonceGenerator?: () => string;
|
|
20
|
+
debug?: boolean;
|
|
21
|
+
/** Pre-configured token object (overrides individual fields below) */
|
|
22
|
+
token?: Token;
|
|
23
|
+
/** Override EIP-712 domain name for custom tokens */
|
|
24
|
+
domainName?: string;
|
|
25
|
+
/** Override EIP-712 domain version for custom tokens */
|
|
26
|
+
domainVersion?: string;
|
|
27
|
+
}
|
|
28
|
+
interface X402Client {
|
|
29
|
+
fetch: typeof fetch;
|
|
30
|
+
getAddress(): Address;
|
|
31
|
+
createPayment(amount: string, to: Address, contractAddress: Address, chainId: number, expiry?: number): Promise<PaymentPayloadV1 | PaymentPayloadV2>;
|
|
32
|
+
signPayment<T extends PaymentPayloadV1 | PaymentPayloadV2>(payload: Omit<T, "signature" | "v" | "r" | "s">): Promise<T>;
|
|
33
|
+
}
|
|
34
|
+
interface X402TransportConfig {
|
|
35
|
+
wallet: X402Wallet;
|
|
36
|
+
transport?: Transport;
|
|
37
|
+
version?: X402ProtocolVersion;
|
|
38
|
+
defaultExpiry?: number;
|
|
39
|
+
nonceGenerator?: () => string;
|
|
40
|
+
debug?: boolean;
|
|
41
|
+
/** Pre-configured token object */
|
|
42
|
+
token?: Token;
|
|
43
|
+
/** Override EIP-712 domain name */
|
|
44
|
+
domainName?: string;
|
|
45
|
+
/** Override EIP-712 domain version */
|
|
46
|
+
domainVersion?: string;
|
|
47
|
+
}
|
|
48
|
+
interface PaymentResult {
|
|
49
|
+
success: boolean;
|
|
50
|
+
txHash?: string;
|
|
51
|
+
error?: string;
|
|
52
|
+
timestamp: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
declare const createX402Client: (config: X402ClientConfig) => X402Client;
|
|
56
|
+
declare const createX402Transport: (config: X402TransportConfig) => typeof fetch;
|
|
57
|
+
|
|
58
|
+
declare class X402ClientError extends Error {
|
|
59
|
+
readonly cause?: unknown;
|
|
60
|
+
constructor(message: string, cause?: unknown);
|
|
61
|
+
}
|
|
62
|
+
declare class SigningError extends X402ClientError {
|
|
63
|
+
constructor(message: string, cause?: unknown);
|
|
64
|
+
}
|
|
65
|
+
declare class PaymentError extends X402ClientError {
|
|
66
|
+
constructor(message: string, cause?: unknown);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Simple one-line payment API for Armory
|
|
71
|
+
* Focus on DX/UX - "everything just magically works"
|
|
72
|
+
*/
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Simple wallet configuration
|
|
76
|
+
* Pass a viem Account or WalletClient directly
|
|
77
|
+
*/
|
|
78
|
+
type SimpleWallet = {
|
|
79
|
+
account: Account;
|
|
80
|
+
} | {
|
|
81
|
+
walletClient: WalletClient;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Make a payment-protected API request with one line of code
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* ```ts
|
|
88
|
+
* const result = await armoryPay(
|
|
89
|
+
* { account }, // wallet
|
|
90
|
+
* "https://api.example.com/data", // URL
|
|
91
|
+
* "base", // network
|
|
92
|
+
* "usdc" // token
|
|
93
|
+
* );
|
|
94
|
+
*
|
|
95
|
+
* if (result.success) {
|
|
96
|
+
* console.log(result.data);
|
|
97
|
+
* } else {
|
|
98
|
+
* console.error(result.message);
|
|
99
|
+
* }
|
|
100
|
+
* ```
|
|
101
|
+
*/
|
|
102
|
+
declare const armoryPay: <T = unknown>(wallet: SimpleWallet, url: string, network: NetworkId, token: TokenId, options?: {
|
|
103
|
+
/** Request method (default: GET) */
|
|
104
|
+
method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
|
|
105
|
+
/** Request body (for POST/PUT/PATCH) */
|
|
106
|
+
body?: unknown;
|
|
107
|
+
/** Request headers */
|
|
108
|
+
headers?: Record<string, string>;
|
|
109
|
+
/** Protocol version (default: auto-detect) */
|
|
110
|
+
version?: 1 | 2 | "auto";
|
|
111
|
+
/** Payment amount in token units (default: from 402 header) */
|
|
112
|
+
amount?: string;
|
|
113
|
+
/** Enable debug logging */
|
|
114
|
+
debug?: boolean;
|
|
115
|
+
}) => Promise<ArmoryPaymentResult<T>>;
|
|
116
|
+
/**
|
|
117
|
+
* Make a GET request with payment
|
|
118
|
+
*/
|
|
119
|
+
declare const armoryGet: <T = unknown>(wallet: SimpleWallet, url: string, network: NetworkId, token: TokenId, options?: Omit<Parameters<typeof armoryPay>[4], "method">) => Promise<ArmoryPaymentResult<T>>;
|
|
120
|
+
/**
|
|
121
|
+
* Make a POST request with payment
|
|
122
|
+
*/
|
|
123
|
+
declare const armoryPost: <T = unknown>(wallet: SimpleWallet, url: string, network: NetworkId, token: TokenId, body?: unknown, options?: Omit<Parameters<typeof armoryPay>[4], "method" | "body">) => Promise<ArmoryPaymentResult<T>>;
|
|
124
|
+
/**
|
|
125
|
+
* Get the wallet address from a SimpleWallet
|
|
126
|
+
*/
|
|
127
|
+
declare const getWalletAddress: (wallet: SimpleWallet) => Address;
|
|
128
|
+
/**
|
|
129
|
+
* Validate a network identifier without making a request
|
|
130
|
+
*/
|
|
131
|
+
declare const validateNetwork: (network: NetworkId) => ValidationError | {
|
|
132
|
+
success: true;
|
|
133
|
+
network: string;
|
|
134
|
+
};
|
|
135
|
+
/**
|
|
136
|
+
* Validate a token identifier without making a request
|
|
137
|
+
*/
|
|
138
|
+
declare const validateToken: (token: TokenId, network?: NetworkId) => ValidationError | {
|
|
139
|
+
success: true;
|
|
140
|
+
token: string;
|
|
141
|
+
network: string;
|
|
142
|
+
};
|
|
143
|
+
/**
|
|
144
|
+
* Get list of available networks
|
|
145
|
+
*/
|
|
146
|
+
declare const getNetworks: () => string[];
|
|
147
|
+
/**
|
|
148
|
+
* Get list of available tokens
|
|
149
|
+
*/
|
|
150
|
+
declare const getTokens: () => string[];
|
|
151
|
+
|
|
152
|
+
export { PaymentError, type PaymentResult, SigningError, type SimpleWallet, type Token, type X402Client, type X402ClientConfig, X402ClientError, type X402ProtocolVersion, type X402TransportConfig, type X402Wallet, armoryGet, armoryPay, armoryPost, createX402Client, createX402Transport, getNetworks, getTokens, getWalletAddress, validateNetwork, validateToken };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
import {
|
|
3
|
+
encodePaymentV1,
|
|
4
|
+
encodePaymentV2,
|
|
5
|
+
V1_HEADERS,
|
|
6
|
+
V2_HEADERS,
|
|
7
|
+
createEIP712Domain,
|
|
8
|
+
createTransferWithAuthorization,
|
|
9
|
+
EIP712_TYPES
|
|
10
|
+
} from "@armory-sh/base";
|
|
11
|
+
|
|
12
|
+
// src/errors.ts
|
|
13
|
+
var X402ClientError = class extends Error {
|
|
14
|
+
cause;
|
|
15
|
+
constructor(message, cause) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "X402ClientError";
|
|
18
|
+
this.cause = cause;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var SigningError = class extends X402ClientError {
|
|
22
|
+
constructor(message, cause) {
|
|
23
|
+
super(`Signing failed: ${message}`, cause);
|
|
24
|
+
this.name = "SigningError";
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
var PaymentError = class extends X402ClientError {
|
|
28
|
+
constructor(message, cause) {
|
|
29
|
+
super(`Payment failed: ${message}`, cause);
|
|
30
|
+
this.name = "PaymentError";
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
// src/client.ts
|
|
35
|
+
var DEFAULT_EXPIRY = 3600;
|
|
36
|
+
var DEFAULT_NONCE = () => `${Date.now()}`;
|
|
37
|
+
var parseSignature = (signature) => {
|
|
38
|
+
const sig = signature.slice(2);
|
|
39
|
+
return {
|
|
40
|
+
v: parseInt(sig.slice(128, 130), 16) + 27,
|
|
41
|
+
r: `0x${sig.slice(0, 64)}`,
|
|
42
|
+
s: `0x${sig.slice(64, 128)}`
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
var getWalletAddress = (wallet) => wallet.type === "account" ? wallet.account.address : wallet.walletClient.account.address;
|
|
46
|
+
var signTypedData = (wallet, domain, types, message) => {
|
|
47
|
+
if (wallet.type === "account" && !wallet.account.signTypedData) {
|
|
48
|
+
throw new SigningError("Account does not support signTypedData");
|
|
49
|
+
}
|
|
50
|
+
const params = {
|
|
51
|
+
domain,
|
|
52
|
+
types,
|
|
53
|
+
primaryType: "TransferWithAuthorization",
|
|
54
|
+
message
|
|
55
|
+
};
|
|
56
|
+
return wallet.type === "account" ? wallet.account.signTypedData(params) : wallet.walletClient.signTypedData({ ...params, account: wallet.walletClient.account });
|
|
57
|
+
};
|
|
58
|
+
var withCustomDomain = (domain, domainName, domainVersion) => domainName || domainVersion ? { ...domain, name: domainName ?? domain.name, version: domainVersion ?? domain.version } : domain;
|
|
59
|
+
var toNetworkName = (chainId) => chainId === 1 ? "ethereum" : chainId === 8453 ? "base" : "evm";
|
|
60
|
+
var createPaymentV1 = async (wallet, from, to, amount, chainId, contractAddress, nonce, expiry, domainName, domainVersion) => {
|
|
61
|
+
const domain = createEIP712Domain(chainId, contractAddress);
|
|
62
|
+
const value = createTransferWithAuthorization({
|
|
63
|
+
from,
|
|
64
|
+
to,
|
|
65
|
+
value: BigInt(Math.floor(parseFloat(amount) * 1e6)),
|
|
66
|
+
validAfter: 0n,
|
|
67
|
+
validBefore: BigInt(expiry),
|
|
68
|
+
nonce: BigInt(nonce)
|
|
69
|
+
});
|
|
70
|
+
const signature = await signTypedData(wallet, withCustomDomain(domain, domainName, domainVersion), EIP712_TYPES, value);
|
|
71
|
+
const { v, r, s } = parseSignature(signature);
|
|
72
|
+
return { from, to, amount, nonce, expiry, v, r, s, chainId, contractAddress, network: toNetworkName(chainId) };
|
|
73
|
+
};
|
|
74
|
+
var createPaymentV2 = async (wallet, from, to, amount, chainId, assetId, nonce, expiry, domainName, domainVersion) => {
|
|
75
|
+
const contractAddress = assetId.split(":")[2];
|
|
76
|
+
const domain = createEIP712Domain(chainId, contractAddress);
|
|
77
|
+
const value = createTransferWithAuthorization({
|
|
78
|
+
from,
|
|
79
|
+
to,
|
|
80
|
+
value: BigInt(Math.floor(parseFloat(amount) * 1e6)),
|
|
81
|
+
validAfter: 0n,
|
|
82
|
+
validBefore: BigInt(expiry),
|
|
83
|
+
nonce: BigInt(nonce)
|
|
84
|
+
});
|
|
85
|
+
const signature = await signTypedData(wallet, withCustomDomain(domain, domainName, domainVersion), EIP712_TYPES, value);
|
|
86
|
+
const { v, r, s } = parseSignature(signature);
|
|
87
|
+
return {
|
|
88
|
+
from,
|
|
89
|
+
to,
|
|
90
|
+
amount,
|
|
91
|
+
nonce,
|
|
92
|
+
expiry,
|
|
93
|
+
signature: { v, r, s },
|
|
94
|
+
chainId: `eip155:${chainId}`,
|
|
95
|
+
assetId
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
var detectVersion = (response, version) => {
|
|
99
|
+
if (version === 1) return 1;
|
|
100
|
+
if (version === 2) return 2;
|
|
101
|
+
const headers = response.headers;
|
|
102
|
+
if (headers.has(V1_HEADERS.PAYMENT_RESPONSE) || headers.has("X-PAYMENT-REQUIRED")) {
|
|
103
|
+
return 1;
|
|
104
|
+
}
|
|
105
|
+
return 2;
|
|
106
|
+
};
|
|
107
|
+
var parseRequirements = (response, version) => {
|
|
108
|
+
if (version === 1) {
|
|
109
|
+
const text = response.headers.get("X-PAYMENT-REQUIRED");
|
|
110
|
+
if (text) {
|
|
111
|
+
try {
|
|
112
|
+
const json = atob(text);
|
|
113
|
+
return JSON.parse(json);
|
|
114
|
+
} catch {
|
|
115
|
+
throw new PaymentError("Failed to decode v1 payment requirements");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
amount: "1.0",
|
|
120
|
+
network: "base",
|
|
121
|
+
contractAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
122
|
+
payTo: "0x0000000000000000000000000000000000000000",
|
|
123
|
+
expiry: Math.floor(Date.now() / 1e3) + 3600
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
const v2Text = response.headers.get(V2_HEADERS.PAYMENT_REQUIRED);
|
|
127
|
+
if (v2Text) {
|
|
128
|
+
try {
|
|
129
|
+
return JSON.parse(v2Text);
|
|
130
|
+
} catch {
|
|
131
|
+
throw new PaymentError("Failed to decode v2 payment requirements");
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
amount: "1.0",
|
|
136
|
+
to: "0x0000000000000000000000000000000000000000",
|
|
137
|
+
chainId: "eip155:8453",
|
|
138
|
+
assetId: "eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
139
|
+
nonce: `${Date.now()}`,
|
|
140
|
+
expiry: Math.floor(Date.now() / 1e3) + 3600
|
|
141
|
+
};
|
|
142
|
+
};
|
|
143
|
+
var createPaymentFromRequirements = async (wallet, requirements, version, getAddress, nonceGenerator, domainName, domainVersion) => {
|
|
144
|
+
const from = getAddress();
|
|
145
|
+
const nonce = nonceGenerator();
|
|
146
|
+
const expiry = requirements.expiry;
|
|
147
|
+
if (version === 1) {
|
|
148
|
+
const req2 = requirements;
|
|
149
|
+
return createPaymentV1(
|
|
150
|
+
wallet,
|
|
151
|
+
from,
|
|
152
|
+
req2.payTo,
|
|
153
|
+
req2.amount,
|
|
154
|
+
req2.network === "base" ? 8453 : 1,
|
|
155
|
+
req2.contractAddress,
|
|
156
|
+
nonce,
|
|
157
|
+
expiry,
|
|
158
|
+
domainName,
|
|
159
|
+
domainVersion
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
const req = requirements;
|
|
163
|
+
const chainId = parseInt(req.chainId.split(":")[1], 10);
|
|
164
|
+
const to = typeof req.to === "string" ? req.to : "0x0000000000000000000000000000000000000000";
|
|
165
|
+
return createPaymentV2(wallet, from, to, req.amount, chainId, req.assetId, nonce, expiry, domainName, domainVersion);
|
|
166
|
+
};
|
|
167
|
+
var addPaymentHeader = (headers, payment, version) => {
|
|
168
|
+
if (version === 1) {
|
|
169
|
+
headers.set(V1_HEADERS.PAYMENT, encodePaymentV1(payment));
|
|
170
|
+
} else {
|
|
171
|
+
headers.set(V2_HEADERS.PAYMENT_SIGNATURE, encodePaymentV2(payment));
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
var checkSettlement = (response, version) => {
|
|
175
|
+
const v1Header = response.headers.get(V1_HEADERS.PAYMENT_RESPONSE);
|
|
176
|
+
const v2Header = response.headers.get(V2_HEADERS.PAYMENT_RESPONSE);
|
|
177
|
+
let settlement = null;
|
|
178
|
+
if (version === 1 && v1Header) {
|
|
179
|
+
try {
|
|
180
|
+
const json = atob(v1Header);
|
|
181
|
+
settlement = JSON.parse(json);
|
|
182
|
+
} catch {
|
|
183
|
+
}
|
|
184
|
+
} else if (version === 2 && v2Header) {
|
|
185
|
+
try {
|
|
186
|
+
settlement = JSON.parse(v2Header);
|
|
187
|
+
} catch {
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (settlement) {
|
|
191
|
+
const success = "success" in settlement ? settlement.success : settlement.status === "success";
|
|
192
|
+
if (!success) {
|
|
193
|
+
const error = "error" in settlement ? settlement.error : "Payment settlement failed";
|
|
194
|
+
throw new PaymentError(error);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
var createFetch = (wallet, config) => {
|
|
199
|
+
const { version = "auto", nonceGenerator = DEFAULT_NONCE, debug = false, domainName, domainVersion } = config;
|
|
200
|
+
const getAddress = () => getWalletAddress(wallet);
|
|
201
|
+
return async (input, init) => {
|
|
202
|
+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
203
|
+
if (debug) {
|
|
204
|
+
console.log(`[X402] Fetching: ${url}`);
|
|
205
|
+
}
|
|
206
|
+
let response = await fetch(input, init);
|
|
207
|
+
if (response.status === 402) {
|
|
208
|
+
if (debug) {
|
|
209
|
+
console.log(`[X402] Payment required for: ${url}`);
|
|
210
|
+
}
|
|
211
|
+
const detectedVersion = detectVersion(response, version);
|
|
212
|
+
if (debug) {
|
|
213
|
+
console.log(`[X402] Detected protocol v${detectedVersion}`);
|
|
214
|
+
}
|
|
215
|
+
const requirements = parseRequirements(response, detectedVersion);
|
|
216
|
+
if (debug) {
|
|
217
|
+
console.log(`[X402] Payment requirements:`, requirements);
|
|
218
|
+
}
|
|
219
|
+
const payment = await createPaymentFromRequirements(wallet, requirements, detectedVersion, getAddress, nonceGenerator, domainName, domainVersion);
|
|
220
|
+
if (debug) {
|
|
221
|
+
console.log(`[X402] Created payment:`, payment);
|
|
222
|
+
}
|
|
223
|
+
const headers = new Headers(init?.headers);
|
|
224
|
+
addPaymentHeader(headers, payment, detectedVersion);
|
|
225
|
+
response = await fetch(input, { ...init, headers });
|
|
226
|
+
if (debug) {
|
|
227
|
+
console.log(`[X402] Payment response status: ${response.status}`);
|
|
228
|
+
}
|
|
229
|
+
checkSettlement(response, detectedVersion);
|
|
230
|
+
}
|
|
231
|
+
return response;
|
|
232
|
+
};
|
|
233
|
+
};
|
|
234
|
+
var extractDomainConfig = (config) => config.token ? { domainName: config.token.name, domainVersion: config.token.version } : { domainName: config.domainName, domainVersion: config.domainVersion };
|
|
235
|
+
var createX402Client = (config) => {
|
|
236
|
+
const { wallet, version = "auto", defaultExpiry = DEFAULT_EXPIRY, nonceGenerator = DEFAULT_NONCE } = config;
|
|
237
|
+
const { domainName, domainVersion } = extractDomainConfig(config);
|
|
238
|
+
const getAddress = () => getWalletAddress(wallet);
|
|
239
|
+
const fetchFn = createFetch(wallet, { version, defaultExpiry, nonceGenerator, debug: config.debug, domainName, domainVersion });
|
|
240
|
+
return {
|
|
241
|
+
fetch: fetchFn,
|
|
242
|
+
getAddress,
|
|
243
|
+
async createPayment(amount, to, contractAddress, chainId, expiry) {
|
|
244
|
+
const from = getAddress();
|
|
245
|
+
const nonce = nonceGenerator();
|
|
246
|
+
const validExpiry = expiry ?? Math.floor(Date.now() / 1e3) + defaultExpiry;
|
|
247
|
+
const targetVersion = version === "auto" ? 1 : version;
|
|
248
|
+
if (targetVersion === 1) {
|
|
249
|
+
return createPaymentV1(wallet, from, to, amount, chainId, contractAddress, nonce, validExpiry, domainName, domainVersion);
|
|
250
|
+
}
|
|
251
|
+
const assetId = `eip155:${chainId}/erc20:${contractAddress}`;
|
|
252
|
+
return createPaymentV2(wallet, from, to, amount, chainId, assetId, nonce, validExpiry, domainName, domainVersion);
|
|
253
|
+
},
|
|
254
|
+
async signPayment(payload) {
|
|
255
|
+
const from = getAddress();
|
|
256
|
+
const chainId = typeof payload.chainId === "number" ? payload.chainId : parseInt(payload.chainId.split(":")[1], 10);
|
|
257
|
+
const to = payload.to;
|
|
258
|
+
const expiry = payload.expiry;
|
|
259
|
+
const nonce = nonceGenerator();
|
|
260
|
+
if ("contractAddress" in payload) {
|
|
261
|
+
const input2 = payload;
|
|
262
|
+
return createPaymentV1(
|
|
263
|
+
wallet,
|
|
264
|
+
from,
|
|
265
|
+
to,
|
|
266
|
+
input2.amount,
|
|
267
|
+
chainId,
|
|
268
|
+
input2.contractAddress,
|
|
269
|
+
nonce,
|
|
270
|
+
expiry,
|
|
271
|
+
domainName,
|
|
272
|
+
domainVersion
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
const input = payload;
|
|
276
|
+
return createPaymentV2(
|
|
277
|
+
wallet,
|
|
278
|
+
from,
|
|
279
|
+
to,
|
|
280
|
+
input.amount,
|
|
281
|
+
chainId,
|
|
282
|
+
input.assetId,
|
|
283
|
+
nonce,
|
|
284
|
+
expiry,
|
|
285
|
+
domainName,
|
|
286
|
+
domainVersion
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
};
|
|
291
|
+
var createX402Transport = (config) => {
|
|
292
|
+
const { wallet, transport, version, defaultExpiry, nonceGenerator, debug, token, domainName, domainVersion } = config;
|
|
293
|
+
return createFetch(wallet, { version, defaultExpiry, nonceGenerator, debug, token, domainName, domainVersion });
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
// src/simple.ts
|
|
297
|
+
import {
|
|
298
|
+
resolveNetwork,
|
|
299
|
+
resolveToken,
|
|
300
|
+
validatePaymentConfig,
|
|
301
|
+
isValidationError,
|
|
302
|
+
getAvailableNetworks,
|
|
303
|
+
getAvailableTokens
|
|
304
|
+
} from "@armory-sh/base";
|
|
305
|
+
var armoryPay = async (wallet, url, network, token, options) => {
|
|
306
|
+
try {
|
|
307
|
+
const x402Wallet = "account" in wallet ? { type: "account", account: wallet.account } : { type: "walletClient", walletClient: wallet.walletClient };
|
|
308
|
+
const config = validatePaymentConfig(network, token);
|
|
309
|
+
if (isValidationError(config)) {
|
|
310
|
+
return {
|
|
311
|
+
success: false,
|
|
312
|
+
code: config.code,
|
|
313
|
+
message: config.message,
|
|
314
|
+
details: config
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
const client = createX402Client({
|
|
318
|
+
wallet: x402Wallet,
|
|
319
|
+
version: options?.version ?? "auto",
|
|
320
|
+
token: config.token.config,
|
|
321
|
+
debug: options?.debug ?? false
|
|
322
|
+
});
|
|
323
|
+
const method = options?.method ?? "GET";
|
|
324
|
+
const headers = new Headers(options?.headers ?? {});
|
|
325
|
+
let response;
|
|
326
|
+
if (method === "GET") {
|
|
327
|
+
response = await client.fetch(url, { method, headers });
|
|
328
|
+
} else {
|
|
329
|
+
response = await client.fetch(url, {
|
|
330
|
+
method,
|
|
331
|
+
headers,
|
|
332
|
+
body: JSON.stringify(options?.body)
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
if (response.status === 402) {
|
|
336
|
+
return {
|
|
337
|
+
success: false,
|
|
338
|
+
code: "PAYMENT_REQUIRED",
|
|
339
|
+
message: "Payment required but could not be completed automatically"
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
if (!response.ok) {
|
|
343
|
+
const error = await response.text();
|
|
344
|
+
return {
|
|
345
|
+
success: false,
|
|
346
|
+
code: "PAYMENT_DECLINED",
|
|
347
|
+
message: `Request failed: ${response.status} ${error}`
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
const data = await response.json();
|
|
351
|
+
const txHash = response.headers.get("X-PAYMENT-RESPONSE") || response.headers.get("PAYMENT-RESPONSE");
|
|
352
|
+
return {
|
|
353
|
+
success: true,
|
|
354
|
+
data,
|
|
355
|
+
...txHash && { txHash }
|
|
356
|
+
};
|
|
357
|
+
} catch (error) {
|
|
358
|
+
return {
|
|
359
|
+
success: false,
|
|
360
|
+
code: "NETWORK_ERROR",
|
|
361
|
+
message: error instanceof Error ? error.message : "Unknown error occurred",
|
|
362
|
+
details: error
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
var armoryGet = (wallet, url, network, token, options) => {
|
|
367
|
+
return armoryPay(wallet, url, network, token, { ...options, method: "GET" });
|
|
368
|
+
};
|
|
369
|
+
var armoryPost = (wallet, url, network, token, body, options) => {
|
|
370
|
+
return armoryPay(wallet, url, network, token, { ...options, method: "POST", body });
|
|
371
|
+
};
|
|
372
|
+
var getWalletAddress2 = (wallet) => {
|
|
373
|
+
return "account" in wallet ? wallet.account.address : wallet.walletClient.account.address;
|
|
374
|
+
};
|
|
375
|
+
var validateNetwork = (network) => {
|
|
376
|
+
const resolved = resolveNetwork(network);
|
|
377
|
+
if (isValidationError(resolved)) {
|
|
378
|
+
return resolved;
|
|
379
|
+
}
|
|
380
|
+
return { success: true, network: resolved.config.name };
|
|
381
|
+
};
|
|
382
|
+
var validateToken = (token, network) => {
|
|
383
|
+
let resolvedNetwork = void 0;
|
|
384
|
+
if (network) {
|
|
385
|
+
const networkResult = resolveNetwork(network);
|
|
386
|
+
if (isValidationError(networkResult)) {
|
|
387
|
+
return networkResult;
|
|
388
|
+
}
|
|
389
|
+
resolvedNetwork = networkResult;
|
|
390
|
+
}
|
|
391
|
+
const resolved = resolveToken(token, resolvedNetwork);
|
|
392
|
+
if (isValidationError(resolved)) {
|
|
393
|
+
return resolved;
|
|
394
|
+
}
|
|
395
|
+
return {
|
|
396
|
+
success: true,
|
|
397
|
+
token: resolved.config.symbol,
|
|
398
|
+
network: resolved.network.config.name
|
|
399
|
+
};
|
|
400
|
+
};
|
|
401
|
+
var getNetworks = () => {
|
|
402
|
+
return getAvailableNetworks();
|
|
403
|
+
};
|
|
404
|
+
var getTokens = () => {
|
|
405
|
+
return getAvailableTokens();
|
|
406
|
+
};
|
|
407
|
+
export {
|
|
408
|
+
PaymentError,
|
|
409
|
+
SigningError,
|
|
410
|
+
X402ClientError,
|
|
411
|
+
armoryGet,
|
|
412
|
+
armoryPay,
|
|
413
|
+
armoryPost,
|
|
414
|
+
createX402Client,
|
|
415
|
+
createX402Transport,
|
|
416
|
+
getNetworks,
|
|
417
|
+
getTokens,
|
|
418
|
+
getWalletAddress2 as getWalletAddress,
|
|
419
|
+
validateNetwork,
|
|
420
|
+
validateToken
|
|
421
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@armory-sh/client-viem",
|
|
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-viem"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@armory-sh/base": "workspace:*",
|
|
31
|
+
"viem": "2.45.0"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"typescript": "5.9.3",
|
|
35
|
+
"bun-types": "latest"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsup",
|
|
39
|
+
"test": "bun test",
|
|
40
|
+
"example": "bun run examples/"
|
|
41
|
+
}
|
|
42
|
+
}
|