@blockrun/clawrouter 0.3.2 → 0.3.4

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/dist/index.d.ts CHANGED
@@ -237,6 +237,103 @@ type RouterOptions = {
237
237
  */
238
238
  declare function route(prompt: string, systemPrompt: string | undefined, maxOutputTokens: number, options: RouterOptions): RoutingDecision;
239
239
 
240
+ /**
241
+ * Balance Monitor for ClawRouter
242
+ *
243
+ * Monitors USDC balance on Base network with intelligent caching.
244
+ * Provides pre-request balance checks to prevent failed payments.
245
+ *
246
+ * Caching Strategy:
247
+ * - TTL: 30 seconds (balance is cached to avoid excessive RPC calls)
248
+ * - Optimistic deduction: after successful payment, subtract estimated cost from cache
249
+ * - Invalidation: on payment failure, immediately refresh from RPC
250
+ */
251
+ /** Balance thresholds in USDC smallest unit (6 decimals) */
252
+ declare const BALANCE_THRESHOLDS: {
253
+ /** Low balance warning threshold: $1.00 */
254
+ readonly LOW_BALANCE_MICROS: 1000000n;
255
+ /** Effectively zero threshold: $0.0001 (covers dust/rounding) */
256
+ readonly ZERO_THRESHOLD: 100n;
257
+ };
258
+ /** Balance information returned by checkBalance() */
259
+ type BalanceInfo = {
260
+ /** Raw balance in USDC smallest unit (6 decimals) */
261
+ balance: bigint;
262
+ /** Formatted balance as "$X.XX" */
263
+ balanceUSD: string;
264
+ /** True if balance < $1.00 */
265
+ isLow: boolean;
266
+ /** True if balance < $0.0001 (effectively zero) */
267
+ isEmpty: boolean;
268
+ /** Wallet address for funding instructions */
269
+ walletAddress: string;
270
+ };
271
+ /** Result from checkSufficient() */
272
+ type SufficiencyResult = {
273
+ /** True if balance >= estimated cost */
274
+ sufficient: boolean;
275
+ /** Current balance info */
276
+ info: BalanceInfo;
277
+ /** If insufficient, the shortfall as "$X.XX" */
278
+ shortfall?: string;
279
+ };
280
+ /**
281
+ * Monitors USDC balance on Base network.
282
+ *
283
+ * Usage:
284
+ * const monitor = new BalanceMonitor("0x...");
285
+ * const info = await monitor.checkBalance();
286
+ * if (info.isLow) console.warn("Low balance!");
287
+ */
288
+ declare class BalanceMonitor {
289
+ private readonly client;
290
+ private readonly walletAddress;
291
+ /** Cached balance (null = not yet fetched) */
292
+ private cachedBalance;
293
+ /** Timestamp when cache was last updated */
294
+ private cachedAt;
295
+ constructor(walletAddress: string);
296
+ /**
297
+ * Check current USDC balance.
298
+ * Uses cache if valid, otherwise fetches from RPC.
299
+ */
300
+ checkBalance(): Promise<BalanceInfo>;
301
+ /**
302
+ * Check if balance is sufficient for an estimated cost.
303
+ *
304
+ * @param estimatedCostMicros - Estimated cost in USDC smallest unit (6 decimals)
305
+ */
306
+ checkSufficient(estimatedCostMicros: bigint): Promise<SufficiencyResult>;
307
+ /**
308
+ * Optimistically deduct estimated cost from cached balance.
309
+ * Call this after a successful payment to keep cache accurate.
310
+ *
311
+ * @param amountMicros - Amount to deduct in USDC smallest unit
312
+ */
313
+ deductEstimated(amountMicros: bigint): void;
314
+ /**
315
+ * Invalidate cache, forcing next checkBalance() to fetch from RPC.
316
+ * Call this after a payment failure to get accurate balance.
317
+ */
318
+ invalidate(): void;
319
+ /**
320
+ * Force refresh balance from RPC (ignores cache).
321
+ */
322
+ refresh(): Promise<BalanceInfo>;
323
+ /**
324
+ * Format USDC amount (in micros) as "$X.XX".
325
+ */
326
+ formatUSDC(amountMicros: bigint): string;
327
+ /**
328
+ * Get the wallet address being monitored.
329
+ */
330
+ getWalletAddress(): string;
331
+ /** Fetch balance from RPC */
332
+ private fetchBalance;
333
+ /** Build BalanceInfo from raw balance */
334
+ private buildInfo;
335
+ }
336
+
240
337
  /**
241
338
  * Local x402 Proxy Server
242
339
  *
@@ -260,11 +357,25 @@ declare function route(prompt: string, systemPrompt: string | undefined, maxOutp
260
357
  * - Usage logging: log every request as JSON line to ~/.openclaw/blockrun/logs/
261
358
  */
262
359
 
360
+ /** Callback info for low balance warning */
361
+ type LowBalanceInfo = {
362
+ balanceUSD: string;
363
+ walletAddress: string;
364
+ };
365
+ /** Callback info for insufficient funds error */
366
+ type InsufficientFundsInfo = {
367
+ balanceUSD: string;
368
+ requiredUSD: string;
369
+ walletAddress: string;
370
+ };
263
371
  type ProxyOptions = {
264
372
  walletKey: string;
265
373
  apiBase?: string;
374
+ /** Port to listen on (default: 8402) */
266
375
  port?: number;
267
376
  routingConfig?: Partial<RoutingConfig>;
377
+ /** Request timeout in ms (default: 180000 = 3 minutes). Covers on-chain tx + LLM response. */
378
+ requestTimeoutMs?: number;
268
379
  onReady?: (port: number) => void;
269
380
  onError?: (error: Error) => void;
270
381
  onPayment?: (info: {
@@ -273,10 +384,16 @@ type ProxyOptions = {
273
384
  network: string;
274
385
  }) => void;
275
386
  onRouted?: (decision: RoutingDecision) => void;
387
+ /** Called when balance drops below $1.00 (warning, request still proceeds) */
388
+ onLowBalance?: (info: LowBalanceInfo) => void;
389
+ /** Called when balance is insufficient for a request (request fails) */
390
+ onInsufficientFunds?: (info: InsufficientFundsInfo) => void;
276
391
  };
277
392
  type ProxyHandle = {
278
393
  port: number;
279
394
  baseUrl: string;
395
+ walletAddress: string;
396
+ balanceMonitor: BalanceMonitor;
280
397
  close: () => Promise<void>;
281
398
  };
282
399
  /**
@@ -446,6 +563,102 @@ type PaymentFetchResult = {
446
563
  */
447
564
  declare function createPaymentFetch(privateKey: `0x${string}`): PaymentFetchResult;
448
565
 
566
+ /**
567
+ * Typed Error Classes for ClawRouter
568
+ *
569
+ * Provides structured errors for balance-related failures with
570
+ * all necessary information for user-friendly error messages.
571
+ */
572
+ /**
573
+ * Thrown when wallet has insufficient USDC balance for a request.
574
+ */
575
+ declare class InsufficientFundsError extends Error {
576
+ readonly code: "INSUFFICIENT_FUNDS";
577
+ readonly currentBalanceUSD: string;
578
+ readonly requiredUSD: string;
579
+ readonly walletAddress: string;
580
+ constructor(opts: {
581
+ currentBalanceUSD: string;
582
+ requiredUSD: string;
583
+ walletAddress: string;
584
+ });
585
+ }
586
+ /**
587
+ * Thrown when wallet has no USDC balance (or effectively zero).
588
+ */
589
+ declare class EmptyWalletError extends Error {
590
+ readonly code: "EMPTY_WALLET";
591
+ readonly walletAddress: string;
592
+ constructor(walletAddress: string);
593
+ }
594
+ /**
595
+ * Type guard to check if an error is InsufficientFundsError.
596
+ */
597
+ declare function isInsufficientFundsError(error: unknown): error is InsufficientFundsError;
598
+ /**
599
+ * Type guard to check if an error is EmptyWalletError.
600
+ */
601
+ declare function isEmptyWalletError(error: unknown): error is EmptyWalletError;
602
+ /**
603
+ * Type guard to check if an error is a balance-related error.
604
+ */
605
+ declare function isBalanceError(error: unknown): error is InsufficientFundsError | EmptyWalletError;
606
+ /**
607
+ * Thrown when RPC call fails (network error, node down, etc).
608
+ * Distinguishes infrastructure failures from actual empty wallets.
609
+ */
610
+ declare class RpcError extends Error {
611
+ readonly code: "RPC_ERROR";
612
+ readonly originalError: unknown;
613
+ constructor(message: string, originalError?: unknown);
614
+ }
615
+ /**
616
+ * Type guard to check if an error is RpcError.
617
+ */
618
+ declare function isRpcError(error: unknown): error is RpcError;
619
+
620
+ /**
621
+ * Retry Logic for ClawRouter
622
+ *
623
+ * Provides fetch wrapper with exponential backoff for transient errors.
624
+ * Retries on 429 (rate limit), 502, 503, 504 (server errors).
625
+ */
626
+ /** Configuration for retry behavior */
627
+ type RetryConfig = {
628
+ /** Maximum number of retries (default: 2) */
629
+ maxRetries: number;
630
+ /** Base delay in ms for exponential backoff (default: 500) */
631
+ baseDelayMs: number;
632
+ /** HTTP status codes that trigger a retry (default: [429, 502, 503, 504]) */
633
+ retryableCodes: number[];
634
+ };
635
+ /** Default retry configuration */
636
+ declare const DEFAULT_RETRY_CONFIG: RetryConfig;
637
+ /**
638
+ * Wrap a fetch-like function with retry logic and exponential backoff.
639
+ *
640
+ * @param fetchFn - The fetch function to wrap (can be standard fetch or x402 payFetch)
641
+ * @param url - URL to fetch
642
+ * @param init - Fetch init options
643
+ * @param config - Retry configuration (optional, uses defaults)
644
+ * @returns Response from successful fetch or last failed attempt
645
+ *
646
+ * @example
647
+ * ```typescript
648
+ * const response = await fetchWithRetry(
649
+ * fetch,
650
+ * "https://api.example.com/endpoint",
651
+ * { method: "POST", body: JSON.stringify(data) },
652
+ * { maxRetries: 3 }
653
+ * );
654
+ * ```
655
+ */
656
+ declare function fetchWithRetry(fetchFn: (url: string, init?: RequestInit) => Promise<Response>, url: string, init?: RequestInit, config?: Partial<RetryConfig>): Promise<Response>;
657
+ /**
658
+ * Check if an error or response indicates a retryable condition.
659
+ */
660
+ declare function isRetryable(errorOrResponse: Error | Response, config?: Partial<RetryConfig>): boolean;
661
+
449
662
  /**
450
663
  * @blockrun/clawrouter
451
664
  *
@@ -459,12 +672,12 @@ declare function createPaymentFetch(privateKey: `0x${string}`): PaymentFetchResu
459
672
  * # Fund your wallet with USDC on Base (address printed on install)
460
673
  *
461
674
  * # Use smart routing (auto-picks cheapest model)
462
- * openclaw config set model blockrun/auto
675
+ * openclaw models set blockrun/auto
463
676
  *
464
677
  * # Or use any specific BlockRun model
465
- * openclaw config set model openai/gpt-5.2
678
+ * openclaw models set openai/gpt-5.2
466
679
  */
467
680
 
468
681
  declare const plugin: OpenClawPluginDefinition;
469
682
 
470
- export { BLOCKRUN_MODELS, type CachedPaymentParams, type CachedResponse, DEFAULT_ROUTING_CONFIG, OPENCLAW_MODELS, PaymentCache, type PaymentFetchResult, type PreAuthParams, RequestDeduplicator, type RoutingConfig, type RoutingDecision, type Tier, type UsageEntry, blockrunProvider, buildProviderModels, createPaymentFetch, plugin as default, logUsage, route, startProxy };
683
+ export { BALANCE_THRESHOLDS, BLOCKRUN_MODELS, type BalanceInfo, BalanceMonitor, type CachedPaymentParams, type CachedResponse, DEFAULT_RETRY_CONFIG, DEFAULT_ROUTING_CONFIG, EmptyWalletError, InsufficientFundsError, type InsufficientFundsInfo, type LowBalanceInfo, OPENCLAW_MODELS, PaymentCache, type PaymentFetchResult, type PreAuthParams, type ProxyHandle, type ProxyOptions, RequestDeduplicator, type RetryConfig, type RoutingConfig, type RoutingDecision, RpcError, type SufficiencyResult, type Tier, type UsageEntry, blockrunProvider, buildProviderModels, createPaymentFetch, plugin as default, fetchWithRetry, isBalanceError, isEmptyWalletError, isInsufficientFundsError, isRetryable, isRpcError, logUsage, route, startProxy };