@warppay402/sdk 1.0.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/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # @warppay402/sdk
2
+
3
+ Official TypeScript SDK for **WarpPay402**—pay-per-use AI tools monetized via x402 USDC micropayments on Base Mainnet.
4
+
5
+ ## 📦 Installation
6
+
7
+ ```bash
8
+ npm install @warppay402/sdk
9
+ ```
10
+ ## 🚀 Quickstart
11
+ ```typescript
12
+ import { WarpPayClient } from "@warppay402/sdk";
13
+
14
+ // Initialize with your AI agent's Base wallet private key
15
+ const client = new WarpPayClient({
16
+ privateKey: process.env.CUSTOMER_PRIVATE_KEY as `0x${string}`,
17
+ });
18
+
19
+ async function main() {
20
+ // Scrapes any URL into clean Markdown ($0.01 USDC)
21
+ const page = await client.scrapeWeb("https://news.ycombinator.com");
22
+ console.log("Title:", page.title);
23
+ console.log("Markdown:", page.markdown);
24
+
25
+ // Fetch Base wallet analytics ($0.02 USDC)
26
+ const analytics = await client.getBaseAnalytics("0x556c77792642E8ff95eC930FFb8D46a76579126E");
27
+ console.log("ETH Balance:", analytics.ethBalance);
28
+
29
+ // Extract PDF text preview ($0.05 USDC)
30
+ const pdf = await client.extractPdf("https://example.com/document.pdf");
31
+ console.log("Preview:", pdf.textPreview);
32
+ }
33
+
34
+ main();
35
+ ```
36
+ ## 🛠️ LangChain Integration
37
+ ```typescript
38
+ import { WarpPayClient, createWarpPayLangChainTools } from "@warppay402/sdk";
39
+
40
+ const client = new WarpPayClient({
41
+ privateKey: process.env.CUSTOMER_PRIVATE_KEY as `0x${string}`,
42
+ });
43
+
44
+ // Pass directly into your LangChain or AutoGen agent setup
45
+ const tools = createWarpPayLangChainTools(client);
46
+ ```
47
+ ## 🌐 API Gateway & Specs
48
+
49
+ Gateway: https://api.warppay402.com
50
+
51
+ MCP Manifest: https://api.warppay402.com/.well-known/mcp.json
52
+
53
+ OpenAPI Spec: https://api.warppay402.com/openapi.json
@@ -0,0 +1,48 @@
1
+ export interface WarpPayConfig {
2
+ /** Base Mainnet private key of the agent's wallet funding the micro-payments */
3
+ privateKey: `0x${string}`;
4
+ /** Custom gateway URL (Defaults to https://api.warppay402.com) */
5
+ baseUrl?: string;
6
+ }
7
+ export interface ScrapeResponse {
8
+ success: boolean;
9
+ title: string;
10
+ markdown: string;
11
+ truncated: boolean;
12
+ }
13
+ export interface BaseAnalyticsResponse {
14
+ success: boolean;
15
+ network: string;
16
+ address: string;
17
+ ethBalance: string;
18
+ nonce: number;
19
+ timestamp: string;
20
+ }
21
+ export interface PdfExtractorResponse {
22
+ success: boolean;
23
+ pages: number;
24
+ info: Record<string, any>;
25
+ textPreview: string;
26
+ }
27
+ export declare class WarpPayClient {
28
+ private baseUrl;
29
+ private account;
30
+ constructor(config: WarpPayConfig);
31
+ /**
32
+ * Internal helper handling the initial HTTP request, 402 Payment Required challenge,
33
+ * EIP-712 signing, and automated retry with x402 payment authorization headers.
34
+ */
35
+ private executePaidRequest;
36
+ /**
37
+ * Scrapes any Web URL into clean Markdown for AI context ($0.01 USDC on Base)
38
+ */
39
+ scrapeWeb(url: string): Promise<ScrapeResponse>;
40
+ /**
41
+ * Fetches Base Mainnet balance and transaction stats for any 0x wallet ($0.02 USDC on Base)
42
+ */
43
+ getBaseAnalytics(address: string): Promise<BaseAnalyticsResponse>;
44
+ /**
45
+ * Downloads and extracts text preview from a public PDF URL ($0.05 USDC on Base)
46
+ */
47
+ extractPdf(pdfUrl: string): Promise<PdfExtractorResponse>;
48
+ }
package/dist/index.js ADDED
@@ -0,0 +1,125 @@
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.WarpPayClient = void 0;
7
+ const node_crypto_1 = __importDefault(require("node:crypto"));
8
+ const node_buffer_1 = require("node:buffer");
9
+ const accounts_1 = require("viem/accounts");
10
+ class WarpPayClient {
11
+ baseUrl;
12
+ account;
13
+ constructor(config) {
14
+ this.baseUrl = (config.baseUrl || "https://api.warppay402.com").replace(/\/$/, "");
15
+ const rawKey = config.privateKey.trim();
16
+ const formattedKey = (rawKey.startsWith("0x") ? rawKey : `0x${rawKey}`);
17
+ this.account = (0, accounts_1.privateKeyToAccount)(formattedKey);
18
+ }
19
+ /**
20
+ * Internal helper handling the initial HTTP request, 402 Payment Required challenge,
21
+ * EIP-712 signing, and automated retry with x402 payment authorization headers.
22
+ */
23
+ async executePaidRequest(endpoint, payload) {
24
+ const url = `${this.baseUrl}${endpoint}`;
25
+ // 1. Initial Request
26
+ let response = await fetch(url, {
27
+ method: "POST",
28
+ headers: { "Content-Type": "application/json" },
29
+ body: JSON.stringify(payload),
30
+ });
31
+ // 2. Handle x402 V2 Payment Challenge if HTTP 402 returned
32
+ if (response.status === 402) {
33
+ const challenge = await response.json();
34
+ const req = challenge.x402?.accepts?.[0] || challenge.accepts?.[0] || {};
35
+ const payTo = (req.payToAddress || req.payTo || "0x0000000000000000000000000000000000000000");
36
+ const assetContract = (req.asset || req.usdcAddress || "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913");
37
+ const value = BigInt(req.maxAmountRequired || req.amount || "10000");
38
+ const domain = {
39
+ name: req.extra?.name || "USD Coin",
40
+ version: req.extra?.version || "2",
41
+ chainId: 8453,
42
+ verifyingContract: assetContract,
43
+ };
44
+ const types = {
45
+ TransferWithAuthorization: [
46
+ { name: "from", type: "address" },
47
+ { name: "to", type: "address" },
48
+ { name: "value", type: "uint256" },
49
+ { name: "validAfter", type: "uint256" },
50
+ { name: "validBefore", type: "uint256" },
51
+ { name: "nonce", type: "bytes32" },
52
+ ],
53
+ };
54
+ const now = Math.floor(Date.now() / 1000);
55
+ const nonce = `0x${node_crypto_1.default.randomBytes(32).toString("hex")}`;
56
+ const message = {
57
+ from: this.account.address,
58
+ to: payTo,
59
+ value,
60
+ validAfter: BigInt(0),
61
+ validBefore: BigInt(now + 3600),
62
+ nonce,
63
+ };
64
+ // Sign typed EIP-712 USDC TransferWithAuthorization data
65
+ const signature = await this.account.signTypedData({
66
+ domain,
67
+ types,
68
+ primaryType: "TransferWithAuthorization",
69
+ message,
70
+ });
71
+ const paymentPayload = {
72
+ x402Version: 2,
73
+ scheme: req.scheme || "exact",
74
+ network: req.network || "eip155:8453",
75
+ payload: {
76
+ authorization: {
77
+ from: this.account.address,
78
+ to: payTo,
79
+ value: value.toString(),
80
+ validAfter: "0",
81
+ validBefore: (now + 3600).toString(),
82
+ nonce,
83
+ },
84
+ signature,
85
+ },
86
+ };
87
+ const encodedPayload = node_buffer_1.Buffer.from(JSON.stringify(paymentPayload)).toString("base64");
88
+ // Retry request with signed x402 headers
89
+ response = await fetch(url, {
90
+ method: "POST",
91
+ headers: {
92
+ "Content-Type": "application/json",
93
+ "X-PAYMENT": encodedPayload,
94
+ "PAYMENT-SIGNATURE": encodedPayload,
95
+ "X-PAYMENT-SIGNATURE": signature,
96
+ },
97
+ body: JSON.stringify(payload),
98
+ });
99
+ }
100
+ if (!response.ok) {
101
+ const errText = await response.text();
102
+ throw new Error(`WarpPay API Error (${response.status}): ${errText}`);
103
+ }
104
+ return (await response.json());
105
+ }
106
+ /**
107
+ * Scrapes any Web URL into clean Markdown for AI context ($0.01 USDC on Base)
108
+ */
109
+ async scrapeWeb(url) {
110
+ return this.executePaidRequest("/api/v1/tools/web-scraper", { url });
111
+ }
112
+ /**
113
+ * Fetches Base Mainnet balance and transaction stats for any 0x wallet ($0.02 USDC on Base)
114
+ */
115
+ async getBaseAnalytics(address) {
116
+ return this.executePaidRequest("/api/v1/tools/base-analytics", { address });
117
+ }
118
+ /**
119
+ * Downloads and extracts text preview from a public PDF URL ($0.05 USDC on Base)
120
+ */
121
+ async extractPdf(pdfUrl) {
122
+ return this.executePaidRequest("/api/v1/tools/pdf-extractor", { pdfUrl });
123
+ }
124
+ }
125
+ exports.WarpPayClient = WarpPayClient;
@@ -0,0 +1,23 @@
1
+ import { WarpPayClient } from "./index.js";
2
+ /**
3
+ * Generates LangChain-compatible tool definitions initialized with WarpPay402
4
+ */
5
+ export declare function createWarpPayLangChainTools(client: WarpPayClient): ({
6
+ name: string;
7
+ description: string;
8
+ func: ({ url }: {
9
+ url: string;
10
+ }) => Promise<string>;
11
+ } | {
12
+ name: string;
13
+ description: string;
14
+ func: ({ address }: {
15
+ address: string;
16
+ }) => Promise<string>;
17
+ } | {
18
+ name: string;
19
+ description: string;
20
+ func: ({ pdfUrl }: {
21
+ pdfUrl: string;
22
+ }) => Promise<string>;
23
+ })[];
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createWarpPayLangChainTools = createWarpPayLangChainTools;
4
+ /**
5
+ * Generates LangChain-compatible tool definitions initialized with WarpPay402
6
+ */
7
+ function createWarpPayLangChainTools(client) {
8
+ return [
9
+ {
10
+ name: "web_scraper",
11
+ description: "Scrapes a web page URL and returns clean markdown content. Costs $0.01 USDC on Base.",
12
+ func: async ({ url }) => {
13
+ const result = await client.scrapeWeb(url);
14
+ return result.markdown;
15
+ },
16
+ },
17
+ {
18
+ name: "base_analytics",
19
+ description: "Fetches ETH balance and nonce for a Base 0x wallet address. Costs $0.02 USDC on Base.",
20
+ func: async ({ address }) => {
21
+ const result = await client.getBaseAnalytics(address);
22
+ return JSON.stringify(result);
23
+ },
24
+ },
25
+ {
26
+ name: "pdf_extractor",
27
+ description: "Extracts text preview from a public PDF URL. Costs $0.05 USDC on Base.",
28
+ func: async ({ pdfUrl }) => {
29
+ const result = await client.extractPdf(pdfUrl);
30
+ return result.textPreview;
31
+ },
32
+ },
33
+ ];
34
+ }
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@warppay402/sdk",
3
+ "version": "1.0.0",
4
+ "description": "Official TypeScript SDK for WarpPay402 pay-per-use AI tools on Base Mainnet",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc"
9
+ },
10
+ "keywords": [
11
+ "x402",
12
+ "base",
13
+ "ai-agents",
14
+ "mcp",
15
+ "monetization",
16
+ "langchain"
17
+ ],
18
+ "dependencies": {
19
+ "@golfgolfgolf200/x402-monetize": "^1.0.2",
20
+ "viem": "^2.0.0"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^26.2.0",
24
+ "typescript": "^5.0.0"
25
+ }
26
+ }
package/src/index.ts ADDED
@@ -0,0 +1,168 @@
1
+ import crypto from "node:crypto";
2
+ import { Buffer } from "node:buffer";
3
+ import { privateKeyToAccount } from "viem/accounts";
4
+
5
+ export interface WarpPayConfig {
6
+ /** Base Mainnet private key of the agent's wallet funding the micro-payments */
7
+ privateKey: `0x${string}`;
8
+ /** Custom gateway URL (Defaults to https://api.warppay402.com) */
9
+ baseUrl?: string;
10
+ }
11
+
12
+ export interface ScrapeResponse {
13
+ success: boolean;
14
+ title: string;
15
+ markdown: string;
16
+ truncated: boolean;
17
+ }
18
+
19
+ export interface BaseAnalyticsResponse {
20
+ success: boolean;
21
+ network: string;
22
+ address: string;
23
+ ethBalance: string;
24
+ nonce: number;
25
+ timestamp: string;
26
+ }
27
+
28
+ export interface PdfExtractorResponse {
29
+ success: boolean;
30
+ pages: number;
31
+ info: Record<string, any>;
32
+ textPreview: string;
33
+ }
34
+
35
+ export class WarpPayClient {
36
+ private baseUrl: string;
37
+ private account;
38
+
39
+ constructor(config: WarpPayConfig) {
40
+ this.baseUrl = (config.baseUrl || "https://api.warppay402.com").replace(/\/$/, "");
41
+
42
+ const rawKey = config.privateKey.trim();
43
+ const formattedKey = (rawKey.startsWith("0x") ? rawKey : `0x${rawKey}`) as `0x${string}`;
44
+ this.account = privateKeyToAccount(formattedKey);
45
+ }
46
+
47
+ /**
48
+ * Internal helper handling the initial HTTP request, 402 Payment Required challenge,
49
+ * EIP-712 signing, and automated retry with x402 payment authorization headers.
50
+ */
51
+ private async executePaidRequest<T>(endpoint: string, payload: Record<string, any>): Promise<T> {
52
+ const url = `${this.baseUrl}${endpoint}`;
53
+
54
+ // 1. Initial Request
55
+ let response = await fetch(url, {
56
+ method: "POST",
57
+ headers: { "Content-Type": "application/json" },
58
+ body: JSON.stringify(payload),
59
+ });
60
+
61
+ // 2. Handle x402 V2 Payment Challenge if HTTP 402 returned
62
+ if (response.status === 402) {
63
+ const challenge = await response.json();
64
+
65
+ const req = challenge.x402?.accepts?.[0] || challenge.accepts?.[0] || {};
66
+ const payTo = (req.payToAddress || req.payTo || "0x0000000000000000000000000000000000000000") as `0x${string}`;
67
+ const assetContract = (req.asset || req.usdcAddress || "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913") as `0x${string}`;
68
+ const value = BigInt(req.maxAmountRequired || req.amount || "10000");
69
+
70
+ const domain = {
71
+ name: req.extra?.name || "USD Coin",
72
+ version: req.extra?.version || "2",
73
+ chainId: 8453,
74
+ verifyingContract: assetContract,
75
+ };
76
+
77
+ const types = {
78
+ TransferWithAuthorization: [
79
+ { name: "from", type: "address" },
80
+ { name: "to", type: "address" },
81
+ { name: "value", type: "uint256" },
82
+ { name: "validAfter", type: "uint256" },
83
+ { name: "validBefore", type: "uint256" },
84
+ { name: "nonce", type: "bytes32" },
85
+ ],
86
+ };
87
+
88
+ const now = Math.floor(Date.now() / 1000);
89
+ const nonce = `0x${crypto.randomBytes(32).toString("hex")}` as `0x${string}`;
90
+
91
+ const message = {
92
+ from: this.account.address,
93
+ to: payTo,
94
+ value,
95
+ validAfter: BigInt(0),
96
+ validBefore: BigInt(now + 3600),
97
+ nonce,
98
+ };
99
+
100
+ // Sign typed EIP-712 USDC TransferWithAuthorization data
101
+ const signature = await this.account.signTypedData({
102
+ domain,
103
+ types,
104
+ primaryType: "TransferWithAuthorization",
105
+ message,
106
+ });
107
+
108
+ const paymentPayload = {
109
+ x402Version: 2,
110
+ scheme: req.scheme || "exact",
111
+ network: req.network || "eip155:8453",
112
+ payload: {
113
+ authorization: {
114
+ from: this.account.address,
115
+ to: payTo,
116
+ value: value.toString(),
117
+ validAfter: "0",
118
+ validBefore: (now + 3600).toString(),
119
+ nonce,
120
+ },
121
+ signature,
122
+ },
123
+ };
124
+
125
+ const encodedPayload = Buffer.from(JSON.stringify(paymentPayload)).toString("base64");
126
+
127
+ // Retry request with signed x402 headers
128
+ response = await fetch(url, {
129
+ method: "POST",
130
+ headers: {
131
+ "Content-Type": "application/json",
132
+ "X-PAYMENT": encodedPayload,
133
+ "PAYMENT-SIGNATURE": encodedPayload,
134
+ "X-PAYMENT-SIGNATURE": signature,
135
+ },
136
+ body: JSON.stringify(payload),
137
+ });
138
+ }
139
+
140
+ if (!response.ok) {
141
+ const errText = await response.text();
142
+ throw new Error(`WarpPay API Error (${response.status}): ${errText}`);
143
+ }
144
+
145
+ return (await response.json()) as T;
146
+ }
147
+
148
+ /**
149
+ * Scrapes any Web URL into clean Markdown for AI context ($0.01 USDC on Base)
150
+ */
151
+ public async scrapeWeb(url: string): Promise<ScrapeResponse> {
152
+ return this.executePaidRequest<ScrapeResponse>("/api/v1/tools/web-scraper", { url });
153
+ }
154
+
155
+ /**
156
+ * Fetches Base Mainnet balance and transaction stats for any 0x wallet ($0.02 USDC on Base)
157
+ */
158
+ public async getBaseAnalytics(address: string): Promise<BaseAnalyticsResponse> {
159
+ return this.executePaidRequest<BaseAnalyticsResponse>("/api/v1/tools/base-analytics", { address });
160
+ }
161
+
162
+ /**
163
+ * Downloads and extracts text preview from a public PDF URL ($0.05 USDC on Base)
164
+ */
165
+ public async extractPdf(pdfUrl: string): Promise<PdfExtractorResponse> {
166
+ return this.executePaidRequest<PdfExtractorResponse>("/api/v1/tools/pdf-extractor", { pdfUrl });
167
+ }
168
+ }
@@ -0,0 +1,33 @@
1
+ import { WarpPayClient } from "./index.js";
2
+
3
+ /**
4
+ * Generates LangChain-compatible tool definitions initialized with WarpPay402
5
+ */
6
+ export function createWarpPayLangChainTools(client: WarpPayClient) {
7
+ return [
8
+ {
9
+ name: "web_scraper",
10
+ description: "Scrapes a web page URL and returns clean markdown content. Costs $0.01 USDC on Base.",
11
+ func: async ({ url }: { url: string }) => {
12
+ const result = await client.scrapeWeb(url);
13
+ return result.markdown;
14
+ },
15
+ },
16
+ {
17
+ name: "base_analytics",
18
+ description: "Fetches ETH balance and nonce for a Base 0x wallet address. Costs $0.02 USDC on Base.",
19
+ func: async ({ address }: { address: string }) => {
20
+ const result = await client.getBaseAnalytics(address);
21
+ return JSON.stringify(result);
22
+ },
23
+ },
24
+ {
25
+ name: "pdf_extractor",
26
+ description: "Extracts text preview from a public PDF URL. Costs $0.05 USDC on Base.",
27
+ func: async ({ pdfUrl }: { pdfUrl: string }) => {
28
+ const result = await client.extractPdf(pdfUrl);
29
+ return result.textPreview;
30
+ },
31
+ },
32
+ ];
33
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "declaration": true,
7
+ "outDir": "./dist",
8
+ "rootDir": "./src",
9
+ "strict": true,
10
+ "esModuleInterop": true,
11
+ "skipLibCheck": true
12
+ },
13
+ "include": ["src/**/*"]
14
+ }
Binary file