@router402/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,430 @@
1
+ <p align="center">
2
+ <img src="https://www.router402.xyz/og-image.png" alt="Router402" width="100%" />
3
+ </p>
4
+
5
+ # @router402/sdk
6
+
7
+ TypeScript SDK for [Router402](https://router402.xyz) — an OpenRouter-compatible AI gateway with true micropayment billing via the [x402 protocol](https://www.x402.org/) on Base.
8
+
9
+ Access Claude, Gemini, and more through a single API. Every request settles the cost of the **previous** request as a USDC micropayment — your funds stay in your smart account until you actually use them.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install @router402/sdk viem
15
+ ```
16
+
17
+ ```bash
18
+ yarn add @router402/sdk viem
19
+ ```
20
+
21
+ ```bash
22
+ pnpm add @router402/sdk viem
23
+ ```
24
+
25
+ ```bash
26
+ bun add @router402/sdk viem
27
+ ```
28
+
29
+ > `viem` is a peer dependency required for blockchain interactions.
30
+
31
+ ## Quick Start
32
+
33
+ ### Chat Completions
34
+
35
+ For chat completions, you only need a JWT token (get one at [router402.xyz](https://router402.xyz)):
36
+
37
+ ```typescript
38
+ import { Router402Sdk } from "@router402/sdk";
39
+
40
+ const sdk = new Router402Sdk({ token: "your-jwt-token" });
41
+
42
+ const response = await sdk.chat("What is ERC-4337?");
43
+ console.log(response);
44
+ ```
45
+
46
+ Specify a model and options:
47
+
48
+ ```typescript
49
+ const response = await sdk.chat("Explain account abstraction", {
50
+ model: "anthropic/claude-haiku-4.5",
51
+ temperature: 0.7,
52
+ max_tokens: 500,
53
+ });
54
+ ```
55
+
56
+ ### Smart Account Operations
57
+
58
+ For smart account management (deploy, session keys, gasless transactions), provide `chain` and `pimlicoApiKey`:
59
+
60
+ ```typescript
61
+ import { Router402Sdk } from "@router402/sdk";
62
+ import { baseSepolia } from "viem/chains";
63
+
64
+ const sdk = new Router402Sdk({
65
+ chain: baseSepolia,
66
+ pimlicoApiKey: "your-pimlico-api-key",
67
+ token: "your-jwt-token",
68
+ });
69
+ ```
70
+
71
+ ## Features
72
+
73
+ | Feature | Description |
74
+ |---------|-------------|
75
+ | **Chat Completions** | One-line AI calls via `sdk.chat(prompt)` |
76
+ | **Smart Accounts** | Create and manage Kernel v3.1 smart contract wallets |
77
+ | **Session Keys** | Generate, approve, and manage delegated signing keys |
78
+ | **Gasless Transactions** | Gas fees sponsored via Pimlico paymaster |
79
+ | **Account Setup** | One-call orchestration of the full setup flow |
80
+ | **Backend Support** | Export session keys for server-side transaction execution |
81
+
82
+ ## Configuration
83
+
84
+ ```typescript
85
+ interface Router402Config {
86
+ /** Target chain (required for smart account features) */
87
+ chain?: Chain;
88
+
89
+ /** Pimlico API key (required for smart account features) */
90
+ pimlicoApiKey?: string;
91
+
92
+ /** JWT token for API authentication */
93
+ token?: string;
94
+
95
+ /** Entry point version (default: "0.7") */
96
+ entryPointVersion?: "0.7";
97
+
98
+ /** Session key validity in seconds (default: 1 year) */
99
+ sessionKeyValidityPeriod?: number;
100
+
101
+ /** API base URL (default: "https://api.router402.xyz") */
102
+ apiBaseUrl?: string;
103
+ }
104
+ ```
105
+
106
+ ## API Reference
107
+
108
+ ### `new Router402Sdk(config)` / `createRouter402Sdk(config)`
109
+
110
+ Create an SDK instance. Both forms are equivalent:
111
+
112
+ ```typescript
113
+ import { Router402Sdk, createRouter402Sdk } from "@router402/sdk";
114
+
115
+ const sdk = new Router402Sdk(config);
116
+ // or
117
+ const sdk = createRouter402Sdk(config);
118
+ ```
119
+
120
+ ---
121
+
122
+ ### Chat Methods
123
+
124
+ #### `sdk.chat(prompt, options?)`
125
+
126
+ Send a chat completion request. Returns the assistant's response as a string.
127
+
128
+ ```typescript
129
+ const answer = await sdk.chat("What is x402?");
130
+ ```
131
+
132
+ **Parameters:**
133
+ - `prompt` — The user message
134
+ - `options.model` — Model identifier (default: `"anthropic/claude-opus-4.6"`)
135
+ - `options.temperature` — Sampling temperature (0–2)
136
+ - `options.max_tokens` — Maximum tokens to generate
137
+
138
+ #### `sdk.setToken(token)`
139
+
140
+ Set or update the JWT token for API requests.
141
+
142
+ ```typescript
143
+ sdk.setToken("new-jwt-token");
144
+ ```
145
+
146
+ ---
147
+
148
+ ### Smart Account Methods
149
+
150
+ > These methods require `chain` and `pimlicoApiKey` in the config.
151
+
152
+ #### `sdk.getSmartAccountAddress(walletClient)`
153
+
154
+ Get the deterministic smart account address for a wallet.
155
+
156
+ ```typescript
157
+ const address = await sdk.getSmartAccountAddress(walletClient);
158
+ ```
159
+
160
+ #### `sdk.isSmartAccountDeployed(address)`
161
+
162
+ Check if a smart account is deployed on-chain.
163
+
164
+ ```typescript
165
+ const deployed = await sdk.isSmartAccountDeployed(address);
166
+ ```
167
+
168
+ #### `sdk.getSmartAccountInfo(walletClient, eoaAddress)`
169
+
170
+ Get complete smart account information.
171
+
172
+ ```typescript
173
+ const info = await sdk.getSmartAccountInfo(walletClient, eoaAddress);
174
+ // { address, eoaAddress, isDeployed, chainId }
175
+ ```
176
+
177
+ #### `sdk.getSmartAccountBalance(address)`
178
+
179
+ Get the ETH balance of a smart account.
180
+
181
+ ```typescript
182
+ const balance = await sdk.getSmartAccountBalance(address);
183
+ ```
184
+
185
+ #### `sdk.deploySmartAccount(walletClient)`
186
+
187
+ Deploy a smart account on-chain.
188
+
189
+ ```typescript
190
+ const result = await sdk.deploySmartAccount(walletClient);
191
+ if (result.success) {
192
+ console.log("Deployed:", result.txHash);
193
+ }
194
+ ```
195
+
196
+ ---
197
+
198
+ ### Session Key Methods
199
+
200
+ #### `sdk.generateSessionKey(smartAccountAddress, ownerAddress)`
201
+
202
+ Generate a new session key pair.
203
+
204
+ ```typescript
205
+ const sessionKey = sdk.generateSessionKey(smartAccountAddress, ownerAddress);
206
+ ```
207
+
208
+ #### `sdk.approveSessionKey(walletClient, sessionKey, allowedCallers?)`
209
+
210
+ Approve a session key with the owner wallet. Returns the updated session key with approval data.
211
+
212
+ ```typescript
213
+ const approvedKey = await sdk.approveSessionKey(walletClient, sessionKey);
214
+ ```
215
+
216
+ Optionally restrict which addresses can use the session key:
217
+
218
+ ```typescript
219
+ const approvedKey = await sdk.approveSessionKey(walletClient, sessionKey, [
220
+ "0xBackendAddress...",
221
+ ]);
222
+ ```
223
+
224
+ #### `sdk.isSessionKeyValid(sessionKey)`
225
+
226
+ Check if a session key exists, is approved, and hasn't expired.
227
+
228
+ #### `sdk.canUseSessionKey(sessionKey)`
229
+
230
+ Check if a session key can be used for transactions (approved + not expired).
231
+
232
+ #### `sdk.isSessionKeyExpired(sessionKey)`
233
+
234
+ Check if a session key has expired.
235
+
236
+ #### `sdk.getSessionKeyRemainingTime(sessionKey)`
237
+
238
+ Get the remaining validity time in milliseconds.
239
+
240
+ #### `sdk.exportSessionKeyForBackend(sessionKey)`
241
+
242
+ Export session key data for server-side transaction execution. Returns `null` if the key isn't approved.
243
+
244
+ ```typescript
245
+ const backendData = sdk.exportSessionKeyForBackend(sessionKey);
246
+ // { privateKey, serializedSessionKey, smartAccountAddress, chainId }
247
+ ```
248
+
249
+ ---
250
+
251
+ ### Transaction Methods
252
+
253
+ #### `sdk.sendOwnerTransaction(walletClient, calls)`
254
+
255
+ Send a transaction signed by the owner wallet.
256
+
257
+ ```typescript
258
+ const result = await sdk.sendOwnerTransaction(walletClient, [
259
+ { to: "0x...", value: 1000n, data: "0x..." },
260
+ ]);
261
+ ```
262
+
263
+ #### `sdk.sendSessionKeyTransaction(sessionKey, calls)`
264
+
265
+ Send a transaction using a session key (client-side).
266
+
267
+ ```typescript
268
+ const result = await sdk.sendSessionKeyTransaction(approvedSessionKey, [
269
+ { to: "0x...", value: 0n, data: "0x..." },
270
+ ]);
271
+ ```
272
+
273
+ #### `sdk.sendSessionKeyTransactionFromBackend(sessionKeyData, calls)`
274
+
275
+ Send a transaction using exported session key data (server-side).
276
+
277
+ ```typescript
278
+ const result = await sdk.sendSessionKeyTransactionFromBackend(backendData, [
279
+ { to: "0x...", value: 0n, data: "0x..." },
280
+ ]);
281
+ ```
282
+
283
+ ---
284
+
285
+ ### Setup Methods
286
+
287
+ #### `sdk.setupAccount(walletClient, eoaAddress, options)`
288
+
289
+ Full account setup flow: get info, deploy, generate session key, approve, and enable on-chain.
290
+
291
+ ```typescript
292
+ const result = await sdk.setupAccount(walletClient, eoaAddress, {
293
+ usdcAddress: "0xUSDC...",
294
+ onStatus: (status) => console.log("Status:", status),
295
+ });
296
+
297
+ console.log("Account:", result.info.address);
298
+ console.log("Session key approved:", result.sessionKey.isApproved);
299
+ ```
300
+
301
+ **Status callbacks:** `initializing` → `deploying` → `creating_session_key` → `approving_session_key` → `enabling_session_key` → `complete`
302
+
303
+ #### `sdk.enableSessionKeyOnChain(sessionKey, usdcAddress, smartAccountAddress)`
304
+
305
+ Enable an approved session key on-chain. This is called automatically by `setupAccount`, but can be used independently.
306
+
307
+ ```typescript
308
+ const result = await sdk.enableSessionKeyOnChain(
309
+ approvedSessionKey,
310
+ usdcAddress,
311
+ smartAccountAddress,
312
+ );
313
+ ```
314
+
315
+ ---
316
+
317
+ ### Utility Methods
318
+
319
+ #### `sdk.getConfig()`
320
+
321
+ Get the resolved configuration object.
322
+
323
+ #### `sdk.getChainId()`
324
+
325
+ Get the configured chain ID.
326
+
327
+ ## Error Handling
328
+
329
+ All errors are thrown as `SmartAccountError` with a `type` field:
330
+
331
+ ```typescript
332
+ import { SmartAccountError } from "@router402/sdk";
333
+
334
+ try {
335
+ await sdk.chat("Hello");
336
+ } catch (error) {
337
+ if (error instanceof SmartAccountError) {
338
+ switch (error.type) {
339
+ case "NOT_CONFIGURED":
340
+ // Missing required configuration
341
+ break;
342
+ case "SESSION_KEY_EXPIRED":
343
+ // Session key needs renewal
344
+ break;
345
+ case "SESSION_KEY_NOT_APPROVED":
346
+ // Session key hasn't been approved yet
347
+ break;
348
+ // ...
349
+ }
350
+ }
351
+ }
352
+ ```
353
+
354
+ **Error types:**
355
+
356
+ | Type | Description |
357
+ |------|-------------|
358
+ | `NOT_CONFIGURED` | Missing required configuration (e.g., no JWT token for chat) |
359
+ | `DEPLOYMENT_FAILED` | Smart account deployment failed |
360
+ | `INSUFFICIENT_FUNDS` | Not enough funds for the operation |
361
+ | `USER_REJECTED` | User rejected the wallet signature |
362
+ | `NETWORK_ERROR` | Network request failed |
363
+ | `SESSION_KEY_NOT_APPROVED` | Session key hasn't been approved |
364
+ | `INVALID_SESSION_KEY` | Session key data is invalid |
365
+ | `SESSION_KEY_EXPIRED` | Session key has expired |
366
+ | `UNKNOWN_ERROR` | Unexpected error |
367
+
368
+ ## Advanced Usage
369
+
370
+ The SDK also exports low-level utilities for advanced use cases:
371
+
372
+ ```typescript
373
+ import {
374
+ // Kernel account utilities
375
+ createKernelPublicClient,
376
+ createPimlicoPaymasterClient,
377
+ createEcdsaValidator,
378
+ createKernelAccountFromWallet,
379
+ createKernelSmartAccountClient,
380
+ getKernelAccountAddress,
381
+ isKernelAccountDeployed,
382
+ createSessionKeyApproval,
383
+ createKernelClientFromSessionKey,
384
+
385
+ // Session key utilities
386
+ generateSessionKey,
387
+ isSessionKeyValid,
388
+ isSessionKeyExpired,
389
+ canUseSessionKey,
390
+ getSessionKeyRemainingTime,
391
+ getSessionKeyAccount,
392
+ exportSessionKeyForBackend,
393
+ markSessionKeyApproved,
394
+
395
+ // Transaction utilities
396
+ sendOwnerTransaction,
397
+ sendSessionKeyTransaction,
398
+
399
+ // Config utilities
400
+ resolveConfig,
401
+ validateConfig,
402
+ validateSmartAccountConfig,
403
+ DEFAULT_API_BASE_URL,
404
+ DEFAULT_SESSION_KEY_VALIDITY,
405
+ ENTRY_POINT_ADDRESS,
406
+ KERNEL_VERSION,
407
+ } from "@router402/sdk";
408
+ ```
409
+
410
+ ## How Payments Work
411
+
412
+ Router402 uses a unique **pay-for-previous** model:
413
+
414
+ 1. Your first request is free — there's no previous cost to settle
415
+ 2. Each subsequent request settles the **previous** request's cost as a USDC micropayment on Base
416
+ 3. Settlement happens via Flashblocks (~0.2s finality)
417
+ 4. Your funds stay in your smart account until a completed request is being paid for
418
+
419
+ No prepaid balances. No subscriptions. No custody.
420
+
421
+ ## Links
422
+
423
+ - [Website](https://router402.xyz)
424
+ - [Documentation](https://docs.router402.xyz)
425
+ - [GitHub](https://github.com/itublockchain/hackmoney-route402)
426
+ - [VS Code Extension](https://marketplace.visualstudio.com/items?itemName=router402xyz.router402-vscode)
427
+
428
+ ## License
429
+
430
+ MIT
@@ -0,0 +1,35 @@
1
+ import type { ResolvedConfig, Router402Config, SmartAccountResolvedConfig } from "./types.js";
2
+ /**
3
+ * ERC-4337 Entry Point v0.7
4
+ * Standard entry point contract for account abstraction
5
+ */
6
+ export declare const ENTRY_POINT_ADDRESS: "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
7
+ /**
8
+ * Default session key validity period: 1 year in seconds
9
+ */
10
+ export declare const DEFAULT_SESSION_KEY_VALIDITY: number;
11
+ /**
12
+ * Kernel version - using KERNEL_V3_1
13
+ */
14
+ export declare const KERNEL_VERSION: import("@zerodev/sdk/types").KERNEL_V3_VERSION_TYPE;
15
+ /**
16
+ * Default Router402 API base URL
17
+ */
18
+ export declare const DEFAULT_API_BASE_URL = "https://api.router402.xyz";
19
+ /**
20
+ * Resolve configuration with defaults.
21
+ * Only `chain` and `pimlicoApiKey` are needed for smart account operations.
22
+ * For chat-only usage, neither is required.
23
+ */
24
+ export declare function resolveConfig(config: Router402Config): ResolvedConfig;
25
+ /**
26
+ * Validate that configuration has the required fields for smart account operations.
27
+ * Throws if chain or pimlicoApiKey is missing.
28
+ * Returns a narrowed type with those fields guaranteed.
29
+ */
30
+ export declare function validateSmartAccountConfig(config: ResolvedConfig): asserts config is SmartAccountResolvedConfig;
31
+ /**
32
+ * @deprecated Use validateSmartAccountConfig instead. Basic config validation is no longer required.
33
+ */
34
+ export declare function validateConfig(_config: Router402Config): void;
35
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,cAAc,EACd,eAAe,EACf,0BAA0B,EAC3B,MAAM,YAAY,CAAC;AAGpB;;;GAGG;AACH,eAAO,MAAM,mBAAmB,EAC9B,4CAAqD,CAAC;AAExD;;GAEG;AACH,eAAO,MAAM,4BAA4B,QAAqB,CAAC;AAE/D;;GAEG;AACH,eAAO,MAAM,cAAc,qDAAc,CAAC;AAE1C;;GAEG;AACH,eAAO,MAAM,oBAAoB,8BAA8B,CAAC;AAEhE;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,eAAe,GAAG,cAAc,CAkBrE;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,cAAc,GACrB,OAAO,CAAC,MAAM,IAAI,0BAA0B,CAa9C;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,eAAe,GAAG,IAAI,CAG7D"}
@@ -0,0 +1,8 @@
1
+ export { DEFAULT_API_BASE_URL, DEFAULT_SESSION_KEY_VALIDITY, ENTRY_POINT_ADDRESS, KERNEL_VERSION, resolveConfig, validateConfig, validateSmartAccountConfig, } from "./config.js";
2
+ export { createEcdsaValidator, createKernelAccountFromWallet, createKernelClientFromSessionKey, createKernelPublicClient, createKernelSmartAccountClient, createPimlicoPaymasterClient, createSessionKeyApproval, getKernelAccountAddress, isKernelAccountDeployed, } from "./kernel.js";
3
+ export { createRouter402Sdk, Router402Sdk } from "./sdk.js";
4
+ export { canUseSessionKey, exportSessionKeyForBackend, generateSessionKey, getSessionKeyAccount, getSessionKeyRemainingTime, isSessionKeyExpired, isSessionKeyValid, markSessionKeyApproved, } from "./session-keys.js";
5
+ export { sendOwnerTransaction, sendSessionKeyTransaction, } from "./transactions.js";
6
+ export type { CallData, ChatMessage, ChatOptions, ChatResponse, ChatUsage, DeploymentResult, ResolvedConfig, Router402Config, SessionKeyData, SessionKeyForBackend, SetupAccountOptions, SetupAccountResult, SetupCallbacks, SetupStatus, SmartAccountErrorType, SmartAccountInfo, SmartAccountResolvedConfig, TransactionExecutionResult, TransactionResult, UserOperationResult, } from "./types.js";
7
+ export { SmartAccountError } from "./types.js";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,4BAA4B,EAC5B,mBAAmB,EACnB,cAAc,EACd,aAAa,EACb,cAAc,EACd,0BAA0B,GAC3B,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,oBAAoB,EACpB,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,8BAA8B,EAC9B,4BAA4B,EAC5B,wBAAwB,EACxB,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE5D,OAAO,EACL,gBAAgB,EAChB,0BAA0B,EAC1B,kBAAkB,EAClB,oBAAoB,EACpB,0BAA0B,EAC1B,mBAAmB,EACnB,iBAAiB,EACjB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,oBAAoB,EACpB,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAE3B,YAAY,EACV,QAAQ,EACR,WAAW,EACX,WAAW,EACX,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,cAAc,EACd,oBAAoB,EACpB,mBAAmB,EACnB,kBAAkB,EAClB,cAAc,EACd,WAAW,EACX,qBAAqB,EACrB,gBAAgB,EAChB,0BAA0B,EAC1B,0BAA0B,EAC1B,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC"}