@wardy-agent/x402 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wardy Agent contributors
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 CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # @wardy-agent/x402
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A drop-in `fetch` for AI agents that buy APIs over x402 or pay.sh. When a seller answers "402, pay me", the offer goes to
4
+ Wardy Agent first: a lookalike payee, a repeated bill or a price jump is refused before any money moves. Only a checked
5
+ payment is signed.
6
+
7
+ ```bash
8
+ npm install @wardy-agent/x402
9
+ ```
10
+
11
+ ```ts
12
+ import { createWardyFetch, WardyRefusal } from "@wardy-agent/x402";
13
+
14
+ const fetch = createWardyFetch({ wardyUrl, agentToken });
15
+ try {
16
+ const data = await fetch("https://seller.example/price");
17
+ } catch (error) {
18
+ if (error instanceof WardyRefusal) console.log(error.answer.decision, error.answer.reasons);
19
+ }
20
+ ```
21
+
22
+ Try it against the live sandbox (test money): `curl -s -X POST https://wardy-agent-solana.fly.dev/v1/sandbox` gives an `agentToken`; use
23
+ `wardyUrl: "https://wardy-agent-solana.fly.dev"`.
24
+
25
+ MIT licensed.
@@ -0,0 +1,25 @@
1
+ export interface WardyFetchOptions {
2
+ wardyUrl: string;
3
+ agentToken: string;
4
+ agentId?: string;
5
+ fetch?: typeof fetch;
6
+ /** How long to wait for the owner on a HOLD. 0 returns at once with the HOLD. */
7
+ maxWaitMs?: number;
8
+ pollMs?: number;
9
+ /** Called with every Wardy Agent answer, for logging. */
10
+ onVerdict?: (verdict: WardyAnswer) => void;
11
+ }
12
+ export interface WardyAnswer {
13
+ verdictId: string;
14
+ decision: "ALLOW" | "HOLD" | "BLOCK";
15
+ riskScore: number;
16
+ reasons: string[];
17
+ nextStep: string;
18
+ paymentSignature: string | null;
19
+ }
20
+ /** Wardy Agent didn't pay. `answer` says why, and what to do: never retry a BLOCK some other way. */
21
+ export declare class WardyRefusal extends Error {
22
+ readonly answer: WardyAnswer;
23
+ constructor(answer: WardyAnswer);
24
+ }
25
+ export declare function createWardyFetch(options: WardyFetchOptions): typeof fetch;
@@ -0,0 +1,55 @@
1
+ // wardyFetch: a fetch that pays x402 APIs only through Wardy Agent. One line in an agent:
2
+ // const fetch = createWardyFetch({ wardyUrl, agentToken });
3
+ // A 402 goes to Wardy Agent, which checks who is being paid and why. ALLOW: the request is retried with the payment.
4
+ // HOLD: it waits for the owner (or gives up after maxWaitMs). BLOCK: nothing is paid, and you get a WardyRefusal.
5
+ // The agent never holds a key or a balance.
6
+ import { HEADER_SIGNATURE, readPaymentRequired } from "./protocol.js";
7
+ /** Wardy Agent didn't pay. `answer` says why, and what to do: never retry a BLOCK some other way. */
8
+ export class WardyRefusal extends Error {
9
+ answer;
10
+ constructor(answer) {
11
+ super(`Wardy Agent ${answer.decision === "BLOCK" ? "refused" : "held"} this payment: ${answer.reasons[0] ?? answer.nextStep}`);
12
+ this.answer = answer;
13
+ this.name = "WardyRefusal";
14
+ }
15
+ }
16
+ export function createWardyFetch(options) {
17
+ const base = options.fetch ?? fetch;
18
+ const wardy = (path, init = {}) => base(`${options.wardyUrl.replace(/\/$/, "")}${path}`, {
19
+ ...init,
20
+ headers: { "content-type": "application/json", authorization: `Bearer ${options.agentToken}`, ...(init.headers ?? {}) },
21
+ });
22
+ return (async (input, init) => {
23
+ const first = await base(input, init);
24
+ if (first.status !== 402)
25
+ return first;
26
+ const required = readPaymentRequired(first.headers);
27
+ if (!required)
28
+ return first; // A 402 with no x402 offer: nothing to pay.
29
+ const asked = await wardy("/v1/x402/pay", { method: "POST", body: JSON.stringify({ paymentRequired: required, agentId: options.agentId ?? "x402-agent" }) });
30
+ if (!asked.ok) {
31
+ const body = (await asked.json().catch(() => ({})));
32
+ throw new Error(`Wardy Agent refused the request: ${body.message ?? asked.status}`);
33
+ }
34
+ let answer = (await asked.json());
35
+ options.onVerdict?.(answer);
36
+ const deadline = Date.now() + (options.maxWaitMs ?? 0);
37
+ while (!answer.paymentSignature && answer.nextStep === "wait_for_owner" && Date.now() < deadline) {
38
+ await new Promise((resolve) => setTimeout(resolve, options.pollMs ?? 2000));
39
+ const status = await wardy(`/v1/x402/${answer.verdictId}`);
40
+ if (status.ok) {
41
+ const next = (await status.json());
42
+ answer = { ...answer, ...next, reasons: answer.reasons };
43
+ }
44
+ }
45
+ if (!answer.paymentSignature)
46
+ throw new WardyRefusal(answer);
47
+ const headers = new Headers(init?.headers);
48
+ headers.set(HEADER_SIGNATURE, answer.paymentSignature);
49
+ const paid = await base(input, { ...init, headers });
50
+ // Still 402 after paying: the seller didn't settle, so Wardy Agent sends the money back to the vault.
51
+ if (paid.status === 402)
52
+ await wardy(`/v1/x402/${answer.verdictId}/unsettled`, { method: "POST", body: "{}" }).catch(() => undefined);
53
+ return paid;
54
+ });
55
+ }
@@ -0,0 +1,71 @@
1
+ import { z } from "zod";
2
+ export declare const HEADER_REQUIRED = "payment-required";
3
+ export declare const HEADER_SIGNATURE = "payment-signature";
4
+ export declare const HEADER_RESPONSE = "payment-response";
5
+ export declare const NETWORKS: {
6
+ readonly "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "mainnet";
7
+ readonly "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1": "devnet";
8
+ };
9
+ export declare const DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
10
+ export declare const COMPUTE_BUDGET_PROGRAM = "ComputeBudget111111111111111111111111111111";
11
+ export declare const MEMO_PROGRAM = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr";
12
+ export declare const PaymentRequirementsSchema: z.ZodObject<{
13
+ scheme: z.ZodString;
14
+ network: z.ZodString;
15
+ amount: z.ZodString;
16
+ asset: z.ZodString;
17
+ payTo: z.ZodString;
18
+ maxTimeoutSeconds: z.ZodOptional<z.ZodNumber>;
19
+ extra: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
20
+ }, z.core.$strip>;
21
+ export type PaymentRequirements = z.output<typeof PaymentRequirementsSchema>;
22
+ export declare const ResourceSchema: z.ZodObject<{
23
+ url: z.ZodString;
24
+ description: z.ZodOptional<z.ZodString>;
25
+ mimeType: z.ZodOptional<z.ZodString>;
26
+ }, z.core.$strip>;
27
+ export declare const PaymentRequiredSchema: z.ZodObject<{
28
+ x402Version: z.ZodLiteral<2>;
29
+ error: z.ZodOptional<z.ZodString>;
30
+ resource: z.ZodObject<{
31
+ url: z.ZodString;
32
+ description: z.ZodOptional<z.ZodString>;
33
+ mimeType: z.ZodOptional<z.ZodString>;
34
+ }, z.core.$strip>;
35
+ accepts: z.ZodArray<z.ZodObject<{
36
+ scheme: z.ZodString;
37
+ network: z.ZodString;
38
+ amount: z.ZodString;
39
+ asset: z.ZodString;
40
+ payTo: z.ZodString;
41
+ maxTimeoutSeconds: z.ZodOptional<z.ZodNumber>;
42
+ extra: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
43
+ }, z.core.$strip>>;
44
+ extensions: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
45
+ }, z.core.$strip>;
46
+ export type PaymentRequired = z.output<typeof PaymentRequiredSchema>;
47
+ export interface PaymentPayload {
48
+ x402Version: 2;
49
+ resource?: z.output<typeof ResourceSchema>;
50
+ accepted: PaymentRequirements;
51
+ payload: {
52
+ transaction: string;
53
+ };
54
+ }
55
+ export interface SettlementResponse {
56
+ success: boolean;
57
+ transaction?: string;
58
+ network: string;
59
+ payer?: string;
60
+ errorReason?: string;
61
+ }
62
+ export declare const encodeHeader: (value: unknown) => string;
63
+ export declare function decodeHeader(value: string): unknown;
64
+ /** The PaymentRequired a 402 carries, or null if it carries none we can read. */
65
+ export declare function readPaymentRequired(headers: Headers): PaymentRequired | null;
66
+ /** The one requirement we can pay: exact, on the network we run on. */
67
+ export declare function chooseRequirement(required: PaymentRequired, network?: string): PaymentRequirements | null;
68
+ /** What the agent saw, word for word, so Wardy Agent's detectors read it as untrusted text. Never as instructions. */
69
+ export declare function describeForCheck(required: PaymentRequired, requirement: PaymentRequirements): string;
70
+ /** Atomic units to a decimal string: 10000 with 6 decimals is "0.01". */
71
+ export declare function fromAtomic(amount: string, decimals: number): string;
@@ -0,0 +1,90 @@
1
+ // x402 v2, the "exact" scheme on Solana, as the spec at github.com/coinbase/x402 defines it (read 2026-11-20):
2
+ // - the seller answers 402 with a PAYMENT-REQUIRED header: base64 JSON PaymentRequired
3
+ // - the buyer retries with PAYMENT-SIGNATURE: base64 JSON PaymentPayload, whose payload.transaction is a partially
4
+ // signed transaction the seller's facilitator co-signs as fee payer and sends
5
+ // - the seller answers with PAYMENT-RESPONSE: base64 JSON SettlementResponse
6
+ // The transaction must be exactly: SetComputeUnitLimit, SetComputeUnitPrice, one TransferChecked to the ATA of payTo,
7
+ // and a Memo. Everything here is plain data and pure functions, so it runs in Node and in a browser.
8
+ import { z } from "zod";
9
+ export const HEADER_REQUIRED = "payment-required";
10
+ export const HEADER_SIGNATURE = "payment-signature";
11
+ export const HEADER_RESPONSE = "payment-response";
12
+ export const NETWORKS = {
13
+ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "mainnet",
14
+ "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1": "devnet",
15
+ };
16
+ export const DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
17
+ export const COMPUTE_BUDGET_PROGRAM = "ComputeBudget111111111111111111111111111111";
18
+ export const MEMO_PROGRAM = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr";
19
+ const Base58 = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/);
20
+ export const PaymentRequirementsSchema = z.object({
21
+ scheme: z.string(),
22
+ network: z.string(),
23
+ /** Atomic units, as a string. */
24
+ amount: z.string().regex(/^\d+$/),
25
+ /** The token's mint. */
26
+ asset: Base58,
27
+ payTo: Base58,
28
+ maxTimeoutSeconds: z.number().int().positive().optional(),
29
+ extra: z.record(z.string(), z.unknown()).optional(),
30
+ });
31
+ export const ResourceSchema = z.object({
32
+ url: z.string(),
33
+ description: z.string().optional(),
34
+ mimeType: z.string().optional(),
35
+ });
36
+ export const PaymentRequiredSchema = z.object({
37
+ x402Version: z.literal(2),
38
+ error: z.string().optional(),
39
+ resource: ResourceSchema,
40
+ accepts: z.array(PaymentRequirementsSchema).min(1),
41
+ extensions: z.record(z.string(), z.unknown()).optional(),
42
+ });
43
+ function toBase64(text) {
44
+ return btoa(String.fromCharCode(...new TextEncoder().encode(text)));
45
+ }
46
+ function fromBase64(value) {
47
+ return new TextDecoder().decode(Uint8Array.from(atob(value), (character) => character.charCodeAt(0)));
48
+ }
49
+ export const encodeHeader = (value) => toBase64(JSON.stringify(value));
50
+ export function decodeHeader(value) {
51
+ return JSON.parse(fromBase64(value));
52
+ }
53
+ /** The PaymentRequired a 402 carries, or null if it carries none we can read. */
54
+ export function readPaymentRequired(headers) {
55
+ const raw = headers.get(HEADER_REQUIRED);
56
+ if (!raw)
57
+ return null;
58
+ try {
59
+ const parsed = PaymentRequiredSchema.safeParse(decodeHeader(raw));
60
+ return parsed.success ? parsed.data : null;
61
+ }
62
+ catch {
63
+ return null;
64
+ }
65
+ }
66
+ /** The one requirement we can pay: exact, on the network we run on. */
67
+ export function chooseRequirement(required, network = DEVNET) {
68
+ return required.accepts.find((option) => option.scheme === "exact" && option.network === network) ?? null;
69
+ }
70
+ /** What the agent saw, word for word, so Wardy Agent's detectors read it as untrusted text. Never as instructions. */
71
+ export function describeForCheck(required, requirement) {
72
+ return [
73
+ `HTTP 402 Payment Required for ${required.resource.url}`,
74
+ required.resource.description ? `description: ${required.resource.description}` : "",
75
+ required.error ? `error: ${required.error}` : "",
76
+ `amount (atomic): ${requirement.amount}`,
77
+ `asset: ${requirement.asset}`,
78
+ `pay to: ${requirement.payTo}`,
79
+ requirement.extra ? `extra: ${JSON.stringify(requirement.extra)}` : "",
80
+ ]
81
+ .filter(Boolean)
82
+ .join("\n");
83
+ }
84
+ /** Atomic units to a decimal string: 10000 with 6 decimals is "0.01". */
85
+ export function fromAtomic(amount, decimals) {
86
+ const padded = amount.padStart(decimals + 1, "0");
87
+ const whole = padded.slice(0, -decimals) || "0";
88
+ const fraction = padded.slice(-decimals).replace(/0+$/, "");
89
+ return fraction ? `${BigInt(whole)}.${fraction}` : `${BigInt(whole)}`;
90
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@wardy-agent/x402",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A fetch for AI agents: when a seller answers 402 (x402 or pay.sh), Wardy Agent checks who is being paid before any money moves.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "homepage": "https://wardy-agent-solana.fly.dev",
8
+ "keywords": [
9
+ "x402",
10
+ "pay.sh",
11
+ "solana",
12
+ "ai-agent",
13
+ "payments",
14
+ "security"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/packages/x402/src/client.d.ts",
19
+ "default": "./dist/packages/x402/src/client.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "engines": {
28
+ "node": ">=20"
29
+ },
30
+ "dependencies": {
31
+ "zod": "4.6.7"
32
+ }
33
+ }