@waterfall-finance/sdk 0.3.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,218 @@
1
+ # Waterfall TypeScript SDK
2
+
3
+ TypeScript SDK for x402 payments with OpenRouter. This is a 1:1 port of the Python waterfall SDK.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @waterfall-finance/sdk
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { WaterfallClient, createClient } from "@waterfall-finance/sdk";
15
+
16
+ // Option 1: Use the convenience function
17
+ const client = await createClient("wf_your_api_key");
18
+
19
+ // Option 2: Manual initialization
20
+ const client = new WaterfallClient({
21
+ apiKey: "wf_your_api_key",
22
+ });
23
+ await client.configureWallet(); // Uses default wallet
24
+
25
+ // Make a chat completion request
26
+ const response = await client.chat.send({
27
+ model: "openai/gpt-3.5-turbo",
28
+ messages: [{ role: "user", content: "Hello!" }],
29
+ });
30
+
31
+ console.log(response.choices[0].message.content);
32
+ ```
33
+
34
+ ## Features
35
+
36
+ - **Automatic x402 Payment Handling**: The SDK automatically handles 402 Payment Required responses
37
+ - **OpenRouter Integration**: Full access to OpenRouter's model catalog
38
+ - **Wallet Management**: Create, list, and manage wallets
39
+ - **Streaming Support**: Stream chat completions for real-time responses
40
+ - **TypeScript First**: Full type definitions included
41
+
42
+ ## API Reference
43
+
44
+ ### WaterfallClient
45
+
46
+ The main client class for interacting with Waterfall.
47
+
48
+ ```typescript
49
+ const client = new WaterfallClient({
50
+ apiKey: "wf_...", // Your Waterfall API key
51
+ walletId: "...", // Optional: specific wallet ID
52
+ backendUrl: "...", // Optional: custom backend URL
53
+ proxyUrl: "...", // Optional: custom x402 proxy URL
54
+ });
55
+ ```
56
+
57
+ ### Client Methods
58
+
59
+ #### `configureWallet(options?)`
60
+
61
+ Configure which wallet to use for payments.
62
+
63
+ ```typescript
64
+ // Use default wallet
65
+ await client.configureWallet();
66
+
67
+ // Use wallet by name
68
+ await client.configureWallet({ walletName: "My Wallet" });
69
+
70
+ // Use wallet by ID
71
+ await client.configureWallet({ walletId: "wallet_123" });
72
+ ```
73
+
74
+ #### `listWallets()`
75
+
76
+ List all wallets associated with your API key.
77
+
78
+ ```typescript
79
+ const wallets = await client.listWallets();
80
+ console.log(wallets);
81
+ // [{ id: "...", name: "...", address: "0x...", network: "base-mainnet" }, ...]
82
+ ```
83
+
84
+ #### `createWallet(options)`
85
+
86
+ Create a new wallet.
87
+
88
+ ```typescript
89
+ const wallet = await client.createWallet({
90
+ name: "My New Wallet",
91
+ useTestnet: false, // Optional: use Base Sepolia testnet
92
+ teamId: "...", // Optional: team ID
93
+ });
94
+ ```
95
+
96
+ ### Chat API
97
+
98
+ #### `chat.send(options)`
99
+
100
+ Send a chat completion request.
101
+
102
+ ```typescript
103
+ const response = await client.chat.send({
104
+ model: "openai/gpt-4",
105
+ messages: [
106
+ { role: "system", content: "You are a helpful assistant." },
107
+ { role: "user", content: "What is the capital of France?" },
108
+ ],
109
+ temperature: 0.7,
110
+ maxTokens: 1000,
111
+ });
112
+ ```
113
+
114
+ #### `chat.stream(options)`
115
+
116
+ Stream a chat completion response.
117
+
118
+ ```typescript
119
+ const stream = await client.chat.stream({
120
+ model: "openai/gpt-3.5-turbo",
121
+ messages: [{ role: "user", content: "Tell me a story" }],
122
+ });
123
+
124
+ for await (const chunk of stream) {
125
+ process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
126
+ }
127
+ ```
128
+
129
+ ### Supported Models
130
+
131
+ Any model available on OpenRouter can be used:
132
+
133
+ - `openai/gpt-4`
134
+ - `openai/gpt-3.5-turbo`
135
+ - `anthropic/claude-3-opus`
136
+ - `anthropic/claude-3-sonnet`
137
+ - `google/gemini-pro`
138
+ - `meta-llama/llama-3-70b-instruct`
139
+ - And many more...
140
+
141
+ ## How It Works
142
+
143
+ 1. **Initial Request**: Client sends request to the x402 proxy
144
+ 2. **402 Response**: Proxy returns `402 Payment Required` with payment details
145
+ 3. **Payment Signing**: SDK automatically signs the payment via Coinbase CDP wallet
146
+ 4. **Retry**: SDK retries the request with the payment signature
147
+ 5. **Success**: Proxy verifies signature and forwards to OpenRouter
148
+
149
+ ```
150
+ Your Code
151
+
152
+ WaterfallClient.chat.send()
153
+
154
+ x402 Proxy
155
+
156
+ [402 Payment Required]
157
+
158
+ Waterfall Backend (signs payment)
159
+
160
+ [Payment Signature]
161
+
162
+ Retry with signature
163
+
164
+ OpenRouter API
165
+
166
+ AI Model Response
167
+ ```
168
+
169
+ ## Configuration
170
+
171
+ ### Environment Variables
172
+
173
+ You can also set the API key via environment variable:
174
+
175
+ ```bash
176
+ export WATERFALL_API_KEY=wf_your_api_key
177
+ ```
178
+
179
+ ```typescript
180
+ const client = new WaterfallClient({
181
+ apiKey: process.env.WATERFALL_API_KEY,
182
+ });
183
+ ```
184
+
185
+ ### Custom URLs
186
+
187
+ Override default URLs if needed:
188
+
189
+ ```typescript
190
+ const client = new WaterfallClient({
191
+ apiKey: "wf_...",
192
+ backendUrl: "https://your-custom-backend.convex.site",
193
+ proxyUrl: "https://your-custom-proxy.com",
194
+ });
195
+ ```
196
+
197
+ ## Error Handling
198
+
199
+ ```typescript
200
+ try {
201
+ const response = await client.chat.send({
202
+ model: "openai/gpt-4",
203
+ messages: [{ role: "user", content: "Hello!" }],
204
+ });
205
+ } catch (error) {
206
+ if (error.message.includes("Invalid or missing Waterfall API key")) {
207
+ console.error("Check your API key");
208
+ } else if (error.message.includes("Payment failed")) {
209
+ console.error("Payment signing failed - check wallet balance");
210
+ } else {
211
+ console.error("Unexpected error:", error);
212
+ }
213
+ }
214
+ ```
215
+
216
+ ## License
217
+
218
+ MIT
@@ -0,0 +1,395 @@
1
+ /**
2
+ * Waterfall SDK Types
3
+ */
4
+ /**
5
+ * Configuration for wallet selection and usage.
6
+ */
7
+ interface WalletConfig {
8
+ /** Optional wallet ID to use. If undefined, uses default wallet. */
9
+ walletId?: string;
10
+ }
11
+ /**
12
+ * Wallet details returned from the API.
13
+ */
14
+ interface Wallet {
15
+ /** Wallet ID (Convex ID) */
16
+ id: string;
17
+ /** Wallet name */
18
+ name: string;
19
+ /** Ethereum address */
20
+ address: string;
21
+ /** Network (e.g., "base-mainnet", "base-sepolia") */
22
+ network: string;
23
+ /** Chain identifier */
24
+ chain: string;
25
+ /** Whether this is the default wallet */
26
+ isDefault?: boolean;
27
+ }
28
+ /**
29
+ * Payment required response from x402 proxy.
30
+ */
31
+ interface PaymentRequired {
32
+ [key: string]: unknown;
33
+ }
34
+ /**
35
+ * Payment signature response from backend.
36
+ */
37
+ interface PaymentSignatureResponse {
38
+ success: boolean;
39
+ signature?: string;
40
+ payment_signature?: string;
41
+ error?: string;
42
+ }
43
+ /**
44
+ * Options for creating a WaterfallClient.
45
+ */
46
+ interface WaterfallClientOptions {
47
+ /** Waterfall API key (wf_...) for authentication */
48
+ apiKey?: string;
49
+ /** Optional wallet ID to use for payments */
50
+ walletId?: string;
51
+ /** Waterfall backend URL (defaults to Convex deployment) */
52
+ backendUrl?: string;
53
+ /** x402 proxy URL (defaults to X402_PROXY_URL) */
54
+ proxyUrl?: string;
55
+ /** Legacy parameter name (use apiKey instead) */
56
+ x402ApiKey?: string;
57
+ }
58
+ /**
59
+ * Options for creating a wallet.
60
+ */
61
+ interface CreateWalletOptions {
62
+ /** Name for the wallet */
63
+ name: string;
64
+ /** Optional team ID to create wallet under */
65
+ teamId?: string;
66
+ /** If true, creates on Base Sepolia testnet */
67
+ useTestnet?: boolean;
68
+ }
69
+ /**
70
+ * Chat message format (OpenAI compatible).
71
+ */
72
+ interface ChatMessage {
73
+ role: "system" | "user" | "assistant" | "function" | "tool";
74
+ content: string | null;
75
+ name?: string;
76
+ function_call?: {
77
+ name: string;
78
+ arguments: string;
79
+ };
80
+ tool_calls?: Array<{
81
+ id: string;
82
+ type: "function";
83
+ function: {
84
+ name: string;
85
+ arguments: string;
86
+ };
87
+ }>;
88
+ }
89
+ /**
90
+ * Chat completion request options.
91
+ */
92
+ interface ChatCompletionOptions {
93
+ /** Model to use (e.g., "openai/gpt-4", "anthropic/claude-3-opus") */
94
+ model: string;
95
+ /** Messages for the conversation */
96
+ messages: ChatMessage[];
97
+ /** Maximum tokens to generate */
98
+ maxTokens?: number;
99
+ /** Temperature for sampling */
100
+ temperature?: number;
101
+ /** Top-p sampling */
102
+ topP?: number;
103
+ /** Stop sequences */
104
+ stop?: string | string[];
105
+ /** Whether to stream the response */
106
+ stream?: boolean;
107
+ /** Frequency penalty */
108
+ frequencyPenalty?: number;
109
+ /** Presence penalty */
110
+ presencePenalty?: number;
111
+ /** Number of completions to generate */
112
+ n?: number;
113
+ /** User identifier */
114
+ user?: string;
115
+ }
116
+ /**
117
+ * Chat completion response choice.
118
+ */
119
+ interface ChatCompletionChoice {
120
+ index: number;
121
+ message: {
122
+ role: "assistant";
123
+ content: string | null;
124
+ function_call?: {
125
+ name: string;
126
+ arguments: string;
127
+ };
128
+ tool_calls?: Array<{
129
+ id: string;
130
+ type: "function";
131
+ function: {
132
+ name: string;
133
+ arguments: string;
134
+ };
135
+ }>;
136
+ };
137
+ finish_reason: string | null;
138
+ }
139
+ /**
140
+ * Chat completion response.
141
+ */
142
+ interface ChatCompletionResponse {
143
+ id: string;
144
+ object: "chat.completion";
145
+ created: number;
146
+ model: string;
147
+ choices: ChatCompletionChoice[];
148
+ usage?: {
149
+ prompt_tokens: number;
150
+ completion_tokens: number;
151
+ total_tokens: number;
152
+ };
153
+ }
154
+
155
+ /**
156
+ * Wallet configuration and management for Waterfall client.
157
+ */
158
+
159
+ /**
160
+ * Manages wallet operations and communication with Waterfall/Convex backend.
161
+ */
162
+ declare class WalletManager {
163
+ private backendUrl?;
164
+ private apiKey?;
165
+ /**
166
+ * Initialize wallet manager.
167
+ *
168
+ * @param backendUrl - URL of the Waterfall Convex backend (e.g., https://xxx.convex.site)
169
+ * @param apiKey - Waterfall API key (wf_...) for authentication
170
+ */
171
+ constructor(backendUrl?: string, apiKey?: string);
172
+ /**
173
+ * Get authorization headers for Waterfall API requests.
174
+ */
175
+ private getAuthHeaders;
176
+ /**
177
+ * Construct full API URL.
178
+ */
179
+ private apiUrl;
180
+ /**
181
+ * List all wallets for the authenticated user.
182
+ *
183
+ * @param chain - Optional chain/network filter (e.g., "base-sepolia", "base-mainnet")
184
+ * @returns List of wallet objects
185
+ */
186
+ listWallets(chain?: string): Promise<Wallet[]>;
187
+ /**
188
+ * Get the default wallet ID.
189
+ *
190
+ * @param chain - Optional chain/network filter to get default for specific chain
191
+ * @returns Default wallet ID or undefined if not available
192
+ */
193
+ getDefaultWallet(chain?: string): Promise<string | undefined>;
194
+ /**
195
+ * Get wallet ID by name.
196
+ *
197
+ * @param name - Name of the wallet
198
+ * @returns Wallet ID or undefined if not found
199
+ */
200
+ getWalletByName(name: string): Promise<string | undefined>;
201
+ /**
202
+ * Get wallet details by ID.
203
+ *
204
+ * @param walletId - Wallet ID (Convex ID, Coinbase ID, or address)
205
+ * @returns Wallet object or undefined if not found
206
+ */
207
+ getWallet(walletId: string): Promise<Wallet | undefined>;
208
+ /**
209
+ * Create a new wallet on the Base network.
210
+ *
211
+ * @param options - Wallet creation options
212
+ * @returns Created wallet details including id and address
213
+ * @throws Error if creation fails
214
+ */
215
+ createWallet(options: CreateWalletOptions): Promise<Wallet>;
216
+ /**
217
+ * Sign data using the specified wallet.
218
+ *
219
+ * @param _data - Data to sign
220
+ * @param _walletId - Optional wallet ID. If undefined, uses default wallet.
221
+ * @returns Signature string
222
+ *
223
+ * Note: For x402 payments, the SDK handles signing automatically via
224
+ * the wallet-pay endpoint. This method is for custom signing needs.
225
+ */
226
+ signData(_data: Uint8Array, _walletId?: string): Promise<string>;
227
+ /**
228
+ * Close the manager (no-op in TypeScript, included for API compatibility).
229
+ */
230
+ close(): void;
231
+ }
232
+
233
+ /**
234
+ * Waterfall client - OpenRouter with x402 payment integration.
235
+ */
236
+
237
+ /** Default Waterfall Convex backend URL */
238
+ declare const DEFAULT_BACKEND_URL = "https://marvelous-wolf-471.convex.site";
239
+ /** Default x402 proxy URL for OpenRouter */
240
+ declare const X402_PROXY_URL = "https://rishabhspro.x402instant.com";
241
+ /**
242
+ * Chat interface with x402 payment handling.
243
+ * Uses native Node.js https module to preserve header casing.
244
+ */
245
+ declare class X402Chat {
246
+ private client;
247
+ constructor(client: WaterfallClient);
248
+ /**
249
+ * Make a request to the x402 proxy with automatic payment handling.
250
+ */
251
+ private makeRequest;
252
+ /**
253
+ * Send a chat completion request.
254
+ *
255
+ * @param options - Chat completion options
256
+ * @returns Chat completion response
257
+ *
258
+ * @example
259
+ * ```typescript
260
+ * const response = await client.chat.send({
261
+ * model: "openai/gpt-3.5-turbo",
262
+ * messages: [{ role: "user", content: "Hello!" }],
263
+ * });
264
+ * ```
265
+ */
266
+ send(options: ChatCompletionOptions): Promise<ChatCompletionResponse>;
267
+ /**
268
+ * Send a streaming chat completion request.
269
+ * Note: Streaming is not yet fully implemented with native https.
270
+ *
271
+ * @param options - Chat completion options
272
+ * @returns Chat completion response (non-streaming for now)
273
+ */
274
+ stream(options: Omit<ChatCompletionOptions, "stream">): Promise<ChatCompletionResponse>;
275
+ }
276
+ /**
277
+ * Waterfall client for x402 payments with OpenRouter.
278
+ *
279
+ * Provides direct access to OpenRouter's chat API with automatic
280
+ * payment signature handling via the x402 proxy.
281
+ *
282
+ * @example
283
+ * ```typescript
284
+ * // Initialize with your Waterfall API key
285
+ * const client = new WaterfallClient({ apiKey: "wf_xxxxxxxx_..." });
286
+ *
287
+ * // Configure wallet (optional - uses default if not specified)
288
+ * await client.configureWallet({ walletName: "My Wallet" });
289
+ *
290
+ * // Use OpenRouter with automatic payment handling
291
+ * const response = await client.chat.send({
292
+ * model: "openai/gpt-3.5-turbo",
293
+ * messages: [{ role: "user", content: "Hello!" }],
294
+ * });
295
+ * ```
296
+ */
297
+ declare class WaterfallClient {
298
+ /** Waterfall API key */
299
+ readonly apiKey?: string;
300
+ /** Legacy alias for apiKey */
301
+ readonly x402ApiKey?: string;
302
+ /** Waterfall backend URL */
303
+ readonly backendUrl: string;
304
+ /** x402 proxy URL */
305
+ readonly proxyUrl: string;
306
+ /** Wallet configuration */
307
+ walletConfig: WalletConfig;
308
+ /** Wallet manager instance */
309
+ readonly walletManager: WalletManager;
310
+ /** Lazy-initialized chat interface */
311
+ private _chat?;
312
+ /**
313
+ * Initialize Waterfall client.
314
+ *
315
+ * @param options - Client configuration options
316
+ */
317
+ constructor(options?: WaterfallClientOptions);
318
+ /**
319
+ * Configure the wallet to use for signing.
320
+ *
321
+ * @param options - Wallet configuration options
322
+ * @returns This client instance for method chaining
323
+ *
324
+ * If neither walletId nor walletName provided, fetches the default wallet.
325
+ */
326
+ configureWallet(options?: {
327
+ walletId?: string;
328
+ walletName?: string;
329
+ }): Promise<WaterfallClient>;
330
+ /**
331
+ * List all wallets associated with your API key.
332
+ *
333
+ * @returns List of wallet objects
334
+ */
335
+ listWallets(): Promise<Wallet[]>;
336
+ /**
337
+ * Create a new wallet on the Base network.
338
+ *
339
+ * @param options - Wallet creation options
340
+ * @returns Created wallet details including id and address
341
+ */
342
+ createWallet(options: CreateWalletOptions): Promise<Wallet>;
343
+ /**
344
+ * Sign a payment via Waterfall wallet-pay endpoint.
345
+ *
346
+ * @internal
347
+ * @param paymentRequired - Payment required data from 402 response
348
+ * @returns Payment signature
349
+ */
350
+ signPayment(paymentRequired: PaymentRequired): Promise<string>;
351
+ /**
352
+ * Access OpenRouter chat API with automatic x402 payment handling.
353
+ *
354
+ * @returns Chat interface with send() and stream() methods
355
+ *
356
+ * @example
357
+ * ```typescript
358
+ * const response = await client.chat.send({
359
+ * model: "openai/gpt-3.5-turbo",
360
+ * messages: [{ role: "user", content: "Hello!" }],
361
+ * });
362
+ * ```
363
+ */
364
+ get chat(): X402Chat;
365
+ /**
366
+ * Close the client and clean up resources.
367
+ */
368
+ close(): void;
369
+ }
370
+ /**
371
+ * Create a configured Waterfall client.
372
+ *
373
+ * @param apiKey - Your Waterfall API key (wf_...)
374
+ * @param walletName - Optional wallet name to use (uses default if not specified)
375
+ * @param backendUrl - Optional custom backend URL
376
+ * @returns Configured WaterfallClient ready for use
377
+ *
378
+ * @example
379
+ * ```typescript
380
+ * const client = await createClient("wf_abc123_xyz789");
381
+ * const response = await client.chat.send({
382
+ * model: "openai/gpt-3.5-turbo",
383
+ * messages: [{ role: "user", content: "Hello!" }],
384
+ * });
385
+ * ```
386
+ */
387
+ declare function createClient(apiKey: string, walletName?: string, backendUrl?: string): Promise<WaterfallClient>;
388
+
389
+ /**
390
+ * Waterfall - TypeScript SDK for x402 payments with OpenRouter.
391
+ */
392
+
393
+ declare const VERSION = "0.3.0";
394
+
395
+ export { type ChatCompletionChoice, type ChatCompletionOptions, type ChatCompletionResponse, type ChatMessage, type CreateWalletOptions, DEFAULT_BACKEND_URL, type PaymentRequired, type PaymentSignatureResponse, VERSION, type Wallet, type WalletConfig, WalletManager, WaterfallClient, type WaterfallClientOptions, X402_PROXY_URL, createClient };