x402-anthropic 0.1.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.
@@ -0,0 +1,28 @@
1
+ name: node
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ node-version: ["20", "22"]
15
+
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+
19
+ - uses: actions/setup-node@v4
20
+ with:
21
+ node-version: ${{ matrix.node-version }}
22
+ cache: "npm"
23
+
24
+ - run: npm ci
25
+
26
+ - run: npm run build
27
+
28
+ - run: npm test
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kinance
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,113 @@
1
+ # x402-anthropic-typescript
2
+
3
+ [![npm](https://img.shields.io/npm/v/x402-anthropic)](https://www.npmjs.com/package/x402-anthropic)
4
+ [![TypeScript](https://img.shields.io/badge/typescript-5.0+-blue)](https://typescriptlang.org)
5
+ [![License](https://img.shields.io/badge/license-MIT-green)](https://github.com/kinance/x402-anthropic-typescript/blob/main/LICENSE)
6
+ [![CI](https://github.com/kinance/x402-anthropic-typescript/actions/workflows/node.yml/badge.svg)](https://github.com/kinance/x402-anthropic-typescript/actions)
7
+
8
+ x402 payment transport for the [Anthropic TypeScript SDK](https://github.com/anthropics/anthropic-sdk-js).
9
+
10
+ Wrap the standard `Anthropic` client with a crypto wallet. When the server responds with **HTTP 402**, the library automatically signs a USDC payment and retries — zero code changes needed. Follows the pattern introduced by [qntx/x402-openai-typescript](https://github.com/qntx/x402-openai-typescript).
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install x402-anthropic @x402/evm viem # EVM (Base, Ethereum)
16
+ npm install x402-anthropic @x402/svm @solana/kit # SVM (Solana)
17
+ npm install x402-anthropic @x402/evm @x402/svm viem @solana/kit # all chains
18
+ ```
19
+
20
+ ## Quick start
21
+
22
+ ```ts
23
+ import { X402Anthropic, EVMWallet } from "x402-anthropic";
24
+
25
+ const client = new X402Anthropic({
26
+ wallet: new EVMWallet("0x..."),
27
+ baseURL: "https://your-x402-gateway.example.com",
28
+ });
29
+
30
+ const message = await client.messages.create({
31
+ model: "claude-opus-4-5",
32
+ max_tokens: 1024,
33
+ messages: [{ role: "user", content: "Hello!" }],
34
+ });
35
+ console.log(message.content[0]);
36
+ ```
37
+
38
+ Swap `EVMWallet` for `SVMWallet` to pay on Solana — the API is identical.
39
+
40
+ ## Usage
41
+
42
+ ### Streaming
43
+
44
+ ```ts
45
+ const stream = await client.messages.stream({
46
+ model: "claude-opus-4-5",
47
+ max_tokens: 1024,
48
+ messages: [{ role: "user", content: "Tell me a story." }],
49
+ });
50
+ for await (const text of stream.textStream) {
51
+ process.stdout.write(text);
52
+ }
53
+ ```
54
+
55
+ ### Payment policies
56
+
57
+ ```ts
58
+ import { X402Anthropic, EVMWallet, preferNetwork, maxAmount } from "x402-anthropic";
59
+
60
+ const client = new X402Anthropic({
61
+ wallet: new EVMWallet("0x..."),
62
+ policies: [preferNetwork("eip155:8453"), maxAmount(1_000_000n)], // Base, max $1 USDC
63
+ baseURL: "...",
64
+ });
65
+ ```
66
+
67
+ ## API reference
68
+
69
+ ### `X402Anthropic`
70
+
71
+ Drop-in replacement for `Anthropic` from `@anthropic-ai/sdk`.
72
+
73
+ | Parameter | Type | Description |
74
+ | :-- | :-- | :-- |
75
+ | `wallet` | `Wallet` | Wallet adapter for signing payments |
76
+ | `policies` | `Policy[]` | Payment policies (chain preference, amount cap) |
77
+ | `baseURL` | `string` | Gateway URL (required — points at your x402 server) |
78
+
79
+ All standard Anthropic options (`timeout`, `maxRetries`, `apiKey`, …) are forwarded.
80
+
81
+ ### Wallet adapters
82
+
83
+ | Class | Chain | Peer deps |
84
+ | :-- | :-- | :-- |
85
+ | `EVMWallet(privateKey)` | Base, Ethereum, any EVM | `@x402/evm viem` |
86
+ | `SVMWallet(privateKey)` | Solana | `@x402/svm @solana/kit` |
87
+
88
+ Implement the `Wallet` interface to add a new chain.
89
+
90
+ ### Policy helpers
91
+
92
+ | Function | Effect |
93
+ | :-- | :-- |
94
+ | `preferNetwork(caip2)` | Prefer a specific chain (falls back to any if unavailable) |
95
+ | `preferScheme(scheme)` | Prefer a payment scheme (e.g. `"exact"`) |
96
+ | `maxAmount(units)` | Skip payment requirements above this USDC unit amount |
97
+
98
+ ## Examples
99
+
100
+ ```bash
101
+ EVM_PRIVATE_KEY="0x..." npx tsx examples/basic.ts
102
+ EVM_PRIVATE_KEY="0x..." npx tsx examples/streaming.ts
103
+ ```
104
+
105
+ ## Related
106
+
107
+ - [x402-anthropic-python](https://github.com/kinance/x402-anthropic-python) — Python version of this library
108
+ - [qntx/x402-openai-typescript](https://github.com/qntx/x402-openai-typescript) — OpenAI SDK equivalent
109
+ - [coinbase/x402](https://github.com/coinbase/x402) — x402 protocol spec and reference implementation
110
+
111
+ ## License
112
+
113
+ MIT
@@ -0,0 +1,11 @@
1
+ import Anthropic from "@anthropic-ai/sdk";
2
+ import type { Wallet } from "./wallet.js";
3
+ import type { Policy } from "./policies.js";
4
+ interface X402AnthropicOptions extends Omit<ConstructorParameters<typeof Anthropic>[0], "fetch"> {
5
+ wallet: Wallet;
6
+ policies?: Policy[];
7
+ }
8
+ export declare class X402Anthropic extends Anthropic {
9
+ constructor({ wallet, policies, ...options }: X402AnthropicOptions);
10
+ }
11
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.X402Anthropic = void 0;
7
+ const sdk_1 = __importDefault(require("@anthropic-ai/sdk"));
8
+ const fetch_1 = require("@x402/fetch");
9
+ function createLazyX402Fetch(walletFn) {
10
+ let fetchPromise = null;
11
+ return async (input, init) => {
12
+ if (!fetchPromise) {
13
+ fetchPromise = walletFn()
14
+ .then((client) => (0, fetch_1.wrapFetchWithPayment)(globalThis.fetch, client))
15
+ .catch((err) => { fetchPromise = null; throw err; });
16
+ }
17
+ const wrappedFetch = await fetchPromise;
18
+ return wrappedFetch(input, init);
19
+ };
20
+ }
21
+ class X402Anthropic extends sdk_1.default {
22
+ constructor({ wallet, policies = [], ...options }) {
23
+ const x402Fetch = createLazyX402Fetch(async () => {
24
+ const client = new fetch_1.x402Client();
25
+ await wallet.register(client);
26
+ for (const policy of policies) {
27
+ client.registerPolicy(policy);
28
+ }
29
+ return client;
30
+ });
31
+ super({
32
+ apiKey: "x402",
33
+ ...options,
34
+ fetch: x402Fetch,
35
+ });
36
+ }
37
+ }
38
+ exports.X402Anthropic = X402Anthropic;
@@ -0,0 +1,5 @@
1
+ export { X402Anthropic } from "./client.js";
2
+ export { EVMWallet, SVMWallet } from "./wallet.js";
3
+ export type { Wallet } from "./wallet.js";
4
+ export { preferNetwork, preferScheme, maxAmount } from "./policies.js";
5
+ export type { Policy } from "./policies.js";
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.maxAmount = exports.preferScheme = exports.preferNetwork = exports.SVMWallet = exports.EVMWallet = exports.X402Anthropic = void 0;
4
+ var client_js_1 = require("./client.js");
5
+ Object.defineProperty(exports, "X402Anthropic", { enumerable: true, get: function () { return client_js_1.X402Anthropic; } });
6
+ var wallet_js_1 = require("./wallet.js");
7
+ Object.defineProperty(exports, "EVMWallet", { enumerable: true, get: function () { return wallet_js_1.EVMWallet; } });
8
+ Object.defineProperty(exports, "SVMWallet", { enumerable: true, get: function () { return wallet_js_1.SVMWallet; } });
9
+ var policies_js_1 = require("./policies.js");
10
+ Object.defineProperty(exports, "preferNetwork", { enumerable: true, get: function () { return policies_js_1.preferNetwork; } });
11
+ Object.defineProperty(exports, "preferScheme", { enumerable: true, get: function () { return policies_js_1.preferScheme; } });
12
+ Object.defineProperty(exports, "maxAmount", { enumerable: true, get: function () { return policies_js_1.maxAmount; } });
@@ -0,0 +1,5 @@
1
+ import type { PaymentRequirements } from "@x402/fetch";
2
+ export type Policy = (x402Version: number, requirements: PaymentRequirements[]) => PaymentRequirements[];
3
+ export declare function preferNetwork(network: string): Policy;
4
+ export declare function preferScheme(scheme: string): Policy;
5
+ export declare function maxAmount(maxUnits: bigint | number): Policy;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.preferNetwork = preferNetwork;
4
+ exports.preferScheme = preferScheme;
5
+ exports.maxAmount = maxAmount;
6
+ function preferNetwork(network) {
7
+ return (_version, reqs) => {
8
+ const preferred = reqs.filter((r) => r.network === network);
9
+ return preferred.length > 0 ? preferred : reqs;
10
+ };
11
+ }
12
+ function preferScheme(scheme) {
13
+ return (_version, reqs) => {
14
+ const preferred = reqs.filter((r) => r.scheme === scheme);
15
+ return preferred.length > 0 ? preferred : reqs;
16
+ };
17
+ }
18
+ function maxAmount(maxUnits) {
19
+ const max = BigInt(maxUnits);
20
+ return (_version, reqs) => {
21
+ const affordable = reqs.filter((r) => {
22
+ const amount = BigInt(r.amount ??
23
+ r.maxAmountRequired ??
24
+ "0");
25
+ return amount <= max;
26
+ });
27
+ return affordable.length > 0 ? affordable : reqs;
28
+ };
29
+ }
@@ -0,0 +1,16 @@
1
+ import { x402Client } from "@x402/fetch";
2
+ export interface Wallet {
3
+ register(client: x402Client): Promise<void> | void;
4
+ }
5
+ export declare class EVMWallet implements Wallet {
6
+ #private;
7
+ constructor(privateKey: `0x${string}`);
8
+ register(client: x402Client): Promise<void>;
9
+ toString(): string;
10
+ }
11
+ export declare class SVMWallet implements Wallet {
12
+ #private;
13
+ constructor(privateKey: string, network?: `${string}:${string}`);
14
+ register(client: x402Client): Promise<void>;
15
+ toString(): string;
16
+ }
package/dist/wallet.js ADDED
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _EVMWallet_privateKey, _EVMWallet_address, _SVMWallet_privateKey, _SVMWallet_network, _SVMWallet_pubkey;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.SVMWallet = exports.EVMWallet = void 0;
16
+ class EVMWallet {
17
+ constructor(privateKey) {
18
+ _EVMWallet_privateKey.set(this, void 0);
19
+ _EVMWallet_address.set(this, void 0);
20
+ __classPrivateFieldSet(this, _EVMWallet_privateKey, privateKey, "f");
21
+ }
22
+ async register(client) {
23
+ const { privateKeyToAccount } = await import("viem/accounts");
24
+ const { ExactEvmScheme, toClientEvmSigner } = await import("@x402/evm");
25
+ const account = privateKeyToAccount(__classPrivateFieldGet(this, _EVMWallet_privateKey, "f"));
26
+ __classPrivateFieldSet(this, _EVMWallet_address, account.address, "f");
27
+ const signer = toClientEvmSigner(account);
28
+ client.register("eip155:*", new ExactEvmScheme(signer));
29
+ }
30
+ toString() {
31
+ return __classPrivateFieldGet(this, _EVMWallet_address, "f") ? `EVMWallet(${__classPrivateFieldGet(this, _EVMWallet_address, "f")})` : "EVMWallet(unregistered)";
32
+ }
33
+ }
34
+ exports.EVMWallet = EVMWallet;
35
+ _EVMWallet_privateKey = new WeakMap(), _EVMWallet_address = new WeakMap();
36
+ class SVMWallet {
37
+ constructor(privateKey, network) {
38
+ _SVMWallet_privateKey.set(this, void 0);
39
+ _SVMWallet_network.set(this, void 0);
40
+ _SVMWallet_pubkey.set(this, void 0);
41
+ __classPrivateFieldSet(this, _SVMWallet_privateKey, privateKey, "f");
42
+ __classPrivateFieldSet(this, _SVMWallet_network, network, "f");
43
+ }
44
+ async register(client) {
45
+ const { createKeyPairSignerFromBytes } = await import("@solana/kit");
46
+ const { base58 } = await import("@scure/base");
47
+ const { ExactSvmScheme, toClientSvmSigner, SOLANA_MAINNET_CAIP2 } = await import("@x402/svm");
48
+ const keyBytes = base58.decode(__classPrivateFieldGet(this, _SVMWallet_privateKey, "f"));
49
+ const signer = await createKeyPairSignerFromBytes(keyBytes);
50
+ __classPrivateFieldSet(this, _SVMWallet_pubkey, String(signer.address), "f");
51
+ client.register(__classPrivateFieldGet(this, _SVMWallet_network, "f") ?? SOLANA_MAINNET_CAIP2, new ExactSvmScheme(toClientSvmSigner(signer)));
52
+ }
53
+ toString() {
54
+ return __classPrivateFieldGet(this, _SVMWallet_pubkey, "f") ? `SVMWallet(${__classPrivateFieldGet(this, _SVMWallet_pubkey, "f")})` : "SVMWallet(unregistered)";
55
+ }
56
+ }
57
+ exports.SVMWallet = SVMWallet;
58
+ _SVMWallet_privateKey = new WeakMap(), _SVMWallet_network = new WeakMap(), _SVMWallet_pubkey = new WeakMap();
@@ -0,0 +1,15 @@
1
+ import { X402Anthropic, EVMWallet } from "@kinance/x402-anthropic";
2
+
3
+ const wallet = new EVMWallet("0x_YOUR_PRIVATE_KEY");
4
+ const client = new X402Anthropic({
5
+ wallet,
6
+ baseURL: "https://your-x402-gateway.example.com",
7
+ });
8
+
9
+ const message = await client.messages.create({
10
+ model: "claude-opus-4-5",
11
+ max_tokens: 1024,
12
+ messages: [{ role: "user", content: "Hello, Claude!" }],
13
+ });
14
+
15
+ console.log(message.content[0].type === "text" ? message.content[0].text : "");
@@ -0,0 +1,18 @@
1
+ import { X402Anthropic, EVMWallet } from "@kinance/x402-anthropic";
2
+
3
+ const wallet = new EVMWallet("0x_YOUR_PRIVATE_KEY");
4
+ const client = new X402Anthropic({
5
+ wallet,
6
+ baseURL: "https://your-x402-gateway.example.com",
7
+ });
8
+
9
+ const stream = await client.messages.stream({
10
+ model: "claude-opus-4-5",
11
+ max_tokens: 1024,
12
+ messages: [{ role: "user", content: "Tell me a short story." }],
13
+ });
14
+
15
+ for await (const text of stream.textStream) {
16
+ process.stdout.write(text);
17
+ }
18
+ console.log();
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "x402-anthropic",
3
+ "version": "0.1.0",
4
+ "description": "x402 payment transport for the Anthropic TypeScript SDK",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/index.js",
10
+ "types": "./dist/index.d.ts"
11
+ }
12
+ },
13
+ "scripts": {
14
+ "build": "tsc",
15
+ "test": "vitest run",
16
+ "typecheck": "tsc --noEmit"
17
+ },
18
+ "keywords": ["anthropic", "x402", "payments", "claude", "http402"],
19
+ "license": "MIT",
20
+ "dependencies": {
21
+ "@x402/fetch": "^2.5.0"
22
+ },
23
+ "optionalDependencies": {
24
+ "@x402/evm": "^2.3.0",
25
+ "@x402/svm": "^2.3.0"
26
+ },
27
+ "devDependencies": {
28
+ "@anthropic-ai/sdk": "^0.52.0",
29
+ "typescript": "^5.4.0",
30
+ "vitest": "^1.6.0",
31
+ "@types/node": "^20.0.0"
32
+ },
33
+ "peerDependencies": {
34
+ "@anthropic-ai/sdk": ">=0.40.0"
35
+ }
36
+ }
package/src/client.ts ADDED
@@ -0,0 +1,44 @@
1
+ import Anthropic from "@anthropic-ai/sdk";
2
+ import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
3
+ import type { Wallet } from "./wallet.js";
4
+ import type { Policy } from "./policies.js";
5
+
6
+ type FetchFn = typeof globalThis.fetch;
7
+
8
+ interface X402AnthropicOptions extends Omit<ConstructorParameters<typeof Anthropic>[0], "fetch"> {
9
+ wallet: Wallet;
10
+ policies?: Policy[];
11
+ }
12
+
13
+ function createLazyX402Fetch(walletFn: () => Promise<x402Client>): FetchFn {
14
+ let fetchPromise: Promise<FetchFn> | null = null;
15
+
16
+ return async (input, init) => {
17
+ if (!fetchPromise) {
18
+ fetchPromise = walletFn()
19
+ .then((client) => wrapFetchWithPayment(globalThis.fetch, client) as FetchFn)
20
+ .catch((err) => { fetchPromise = null; throw err; });
21
+ }
22
+ const wrappedFetch = await fetchPromise;
23
+ return wrappedFetch(input, init);
24
+ };
25
+ }
26
+
27
+ export class X402Anthropic extends Anthropic {
28
+ constructor({ wallet, policies = [], ...options }: X402AnthropicOptions) {
29
+ const x402Fetch = createLazyX402Fetch(async () => {
30
+ const client = new x402Client();
31
+ await wallet.register(client);
32
+ for (const policy of policies) {
33
+ client.registerPolicy(policy);
34
+ }
35
+ return client;
36
+ });
37
+
38
+ super({
39
+ apiKey: "x402",
40
+ ...options,
41
+ fetch: x402Fetch as FetchFn,
42
+ });
43
+ }
44
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { X402Anthropic } from "./client.js";
2
+ export { EVMWallet, SVMWallet } from "./wallet.js";
3
+ export type { Wallet } from "./wallet.js";
4
+ export { preferNetwork, preferScheme, maxAmount } from "./policies.js";
5
+ export type { Policy } from "./policies.js";
@@ -0,0 +1,32 @@
1
+ import type { PaymentRequirements } from "@x402/fetch";
2
+
3
+ export type Policy = (x402Version: number, requirements: PaymentRequirements[]) => PaymentRequirements[];
4
+
5
+ export function preferNetwork(network: string): Policy {
6
+ return (_version, reqs) => {
7
+ const preferred = reqs.filter((r) => r.network === network);
8
+ return preferred.length > 0 ? preferred : reqs;
9
+ };
10
+ }
11
+
12
+ export function preferScheme(scheme: string): Policy {
13
+ return (_version, reqs) => {
14
+ const preferred = reqs.filter((r) => r.scheme === scheme);
15
+ return preferred.length > 0 ? preferred : reqs;
16
+ };
17
+ }
18
+
19
+ export function maxAmount(maxUnits: bigint | number): Policy {
20
+ const max = BigInt(maxUnits);
21
+ return (_version, reqs) => {
22
+ const affordable = reqs.filter((r) => {
23
+ const amount = BigInt(
24
+ (r as { amount?: string }).amount ??
25
+ (r as { maxAmountRequired?: string }).maxAmountRequired ??
26
+ "0"
27
+ );
28
+ return amount <= max;
29
+ });
30
+ return affordable.length > 0 ? affordable : reqs;
31
+ };
32
+ }
package/src/wallet.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { x402Client } from "@x402/fetch";
2
+
3
+ export interface Wallet {
4
+ register(client: x402Client): Promise<void> | void;
5
+ }
6
+
7
+ export class EVMWallet implements Wallet {
8
+ readonly #privateKey: `0x${string}`;
9
+ #address: string | undefined;
10
+
11
+ constructor(privateKey: `0x${string}`) {
12
+ this.#privateKey = privateKey;
13
+ }
14
+
15
+ async register(client: x402Client): Promise<void> {
16
+ const { privateKeyToAccount } = await import("viem/accounts");
17
+ const { ExactEvmScheme, toClientEvmSigner } = await import("@x402/evm");
18
+ const account = privateKeyToAccount(this.#privateKey);
19
+ this.#address = account.address;
20
+ const signer = toClientEvmSigner(account);
21
+ client.register("eip155:*", new ExactEvmScheme(signer));
22
+ }
23
+
24
+ toString(): string {
25
+ return this.#address ? `EVMWallet(${this.#address})` : "EVMWallet(unregistered)";
26
+ }
27
+ }
28
+
29
+ export class SVMWallet implements Wallet {
30
+ readonly #privateKey: string;
31
+ readonly #network: `${string}:${string}` | undefined;
32
+ #pubkey: string | undefined;
33
+
34
+ constructor(privateKey: string, network?: `${string}:${string}`) {
35
+ this.#privateKey = privateKey;
36
+ this.#network = network;
37
+ }
38
+
39
+ async register(client: x402Client): Promise<void> {
40
+ const { createKeyPairSignerFromBytes } = await import("@solana/kit");
41
+ const { base58 } = await import("@scure/base");
42
+ const { ExactSvmScheme, toClientSvmSigner, SOLANA_MAINNET_CAIP2 } = await import("@x402/svm");
43
+ const keyBytes = base58.decode(this.#privateKey);
44
+ const signer = await createKeyPairSignerFromBytes(keyBytes);
45
+ this.#pubkey = String(signer.address);
46
+ client.register(this.#network ?? SOLANA_MAINNET_CAIP2, new ExactSvmScheme(toClientSvmSigner(signer)));
47
+ }
48
+
49
+ toString(): string {
50
+ return this.#pubkey ? `SVMWallet(${this.#pubkey})` : "SVMWallet(unregistered)";
51
+ }
52
+ }
@@ -0,0 +1,133 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import { x402Client } from "@x402/fetch";
3
+ import { X402Anthropic } from "../src/index.js";
4
+ import { preferNetwork } from "../src/policies.js";
5
+
6
+ // ---------------------------------------------------------------------------
7
+ // Constructor / config
8
+ // ---------------------------------------------------------------------------
9
+
10
+ describe("X402Anthropic constructor", () => {
11
+ it("constructs without throwing", () => {
12
+ const wallet = { register: vi.fn() };
13
+ expect(() => new X402Anthropic({ wallet, baseURL: "https://example.com" })).not.toThrow();
14
+ });
15
+
16
+ it("sets apiKey to 'x402' by default", () => {
17
+ const wallet = { register: vi.fn() };
18
+ const client = new X402Anthropic({ wallet, baseURL: "https://example.com" });
19
+ expect((client as unknown as { apiKey: string }).apiKey).toBe("x402");
20
+ });
21
+
22
+ it("allows apiKey override", () => {
23
+ const wallet = { register: vi.fn() };
24
+ const client = new X402Anthropic({ wallet, apiKey: "custom", baseURL: "https://example.com" });
25
+ expect((client as unknown as { apiKey: string }).apiKey).toBe("custom");
26
+ });
27
+ });
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // Lazy fetch singleton — wallet.register() called exactly once
31
+ // ---------------------------------------------------------------------------
32
+
33
+ describe("lazy fetch singleton", () => {
34
+ it("calls wallet.register exactly once across multiple fetches", async () => {
35
+ const register = vi.fn();
36
+ const wallet = { register };
37
+
38
+ // Intercept the fetch to avoid real network calls
39
+ const fakeFetch = vi.fn().mockResolvedValue(new Response("{}", { status: 200 }));
40
+ // Patch globalThis.fetch for this test
41
+ const originalFetch = globalThis.fetch;
42
+ globalThis.fetch = fakeFetch;
43
+
44
+ // We access the internal fetch via the _options.fetch slot
45
+ // Instead, directly test the createLazyX402Fetch behaviour by extracting the lazy fn
46
+ // from the module so we can call it multiple times without a full client.
47
+ const { default: Anthropic } = await import("@anthropic-ai/sdk");
48
+ const client = new X402Anthropic({ wallet, baseURL: "https://httpbin.org" });
49
+
50
+ // Trigger the lazy fetch twice by calling the stored fetch function directly.
51
+ // The internal fetch is stored at client._options.fetch.
52
+ const lazyFetch = (client as unknown as { _options: { fetch?: typeof globalThis.fetch } })
53
+ ._options?.fetch;
54
+
55
+ if (lazyFetch) {
56
+ await lazyFetch("https://httpbin.org/get", { method: "GET" }).catch(() => {});
57
+ await lazyFetch("https://httpbin.org/get", { method: "GET" }).catch(() => {});
58
+ }
59
+
60
+ expect(register).toHaveBeenCalledTimes(1);
61
+ globalThis.fetch = originalFetch;
62
+ });
63
+ });
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // Policy registration
67
+ // ---------------------------------------------------------------------------
68
+
69
+ describe("policy registration", () => {
70
+ it("calls registerPolicy for each supplied policy", async () => {
71
+ const registerSpy = vi.fn();
72
+ const registerPolicySpy = vi.fn();
73
+
74
+ // Mock the x402Client constructor
75
+ const mockX402Client = {
76
+ register: registerSpy,
77
+ registerPolicy: registerPolicySpy,
78
+ };
79
+
80
+ // We need to intercept x402Client instantiation inside createLazyX402Fetch.
81
+ // The simplest way: pass a wallet whose register() captures the client arg.
82
+ let capturedClient: unknown = null;
83
+ const wallet = {
84
+ register: vi.fn(async (client: unknown) => {
85
+ capturedClient = client;
86
+ }),
87
+ };
88
+
89
+ const policy = preferNetwork("eip155:8453");
90
+ const client = new X402Anthropic({
91
+ wallet,
92
+ policies: [policy],
93
+ baseURL: "https://httpbin.org",
94
+ });
95
+
96
+ const lazyFetch = (client as unknown as { _options: { fetch?: Function } })
97
+ ._options?.fetch;
98
+
99
+ if (lazyFetch) {
100
+ // Trigger initialization — the fetch will fail (no real server) but init runs.
101
+ await lazyFetch("https://httpbin.org/get").catch(() => {});
102
+ }
103
+
104
+ // wallet.register should have been called once
105
+ expect(wallet.register).toHaveBeenCalledTimes(1);
106
+ // The x402Client passed to wallet.register should be a real x402Client instance
107
+ expect(capturedClient).toBeInstanceOf(x402Client);
108
+ });
109
+ });
110
+
111
+ // ---------------------------------------------------------------------------
112
+ // Policy helpers
113
+ // ---------------------------------------------------------------------------
114
+
115
+ describe("preferNetwork policy", () => {
116
+ const base = "eip155:8453";
117
+ const eth = "eip155:1";
118
+
119
+ it("filters to preferred network when present", () => {
120
+ const policy = preferNetwork(base);
121
+ const reqs = [{ network: eth }, { network: base }] as Parameters<typeof policy>[1];
122
+ const result = policy(2, reqs);
123
+ expect(result).toHaveLength(1);
124
+ expect(result[0].network).toBe(base);
125
+ });
126
+
127
+ it("returns all when preferred network is absent (fallthrough)", () => {
128
+ const policy = preferNetwork(base);
129
+ const reqs = [{ network: eth }, { network: "eip155:137" }] as Parameters<typeof policy>[1];
130
+ const result = policy(2, reqs);
131
+ expect(result).toHaveLength(2);
132
+ });
133
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "outDir": "dist",
7
+ "declaration": true,
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true
11
+ },
12
+ "include": ["src"],
13
+ "exclude": ["node_modules", "dist", "tests", "examples"]
14
+ }