@blockrun/clawrouter 0.3.2 → 0.3.3

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,24 @@ 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;
266
374
  port?: number;
267
375
  routingConfig?: Partial<RoutingConfig>;
376
+ /** Request timeout in ms (default: 180000 = 3 minutes). Covers on-chain tx + LLM response. */
377
+ requestTimeoutMs?: number;
268
378
  onReady?: (port: number) => void;
269
379
  onError?: (error: Error) => void;
270
380
  onPayment?: (info: {
@@ -273,10 +383,16 @@ type ProxyOptions = {
273
383
  network: string;
274
384
  }) => void;
275
385
  onRouted?: (decision: RoutingDecision) => void;
386
+ /** Called when balance drops below $1.00 (warning, request still proceeds) */
387
+ onLowBalance?: (info: LowBalanceInfo) => void;
388
+ /** Called when balance is insufficient for a request (request fails) */
389
+ onInsufficientFunds?: (info: InsufficientFundsInfo) => void;
276
390
  };
277
391
  type ProxyHandle = {
278
392
  port: number;
279
393
  baseUrl: string;
394
+ walletAddress: string;
395
+ balanceMonitor: BalanceMonitor;
280
396
  close: () => Promise<void>;
281
397
  };
282
398
  /**
@@ -446,6 +562,102 @@ type PaymentFetchResult = {
446
562
  */
447
563
  declare function createPaymentFetch(privateKey: `0x${string}`): PaymentFetchResult;
448
564
 
565
+ /**
566
+ * Typed Error Classes for ClawRouter
567
+ *
568
+ * Provides structured errors for balance-related failures with
569
+ * all necessary information for user-friendly error messages.
570
+ */
571
+ /**
572
+ * Thrown when wallet has insufficient USDC balance for a request.
573
+ */
574
+ declare class InsufficientFundsError extends Error {
575
+ readonly code: "INSUFFICIENT_FUNDS";
576
+ readonly currentBalanceUSD: string;
577
+ readonly requiredUSD: string;
578
+ readonly walletAddress: string;
579
+ constructor(opts: {
580
+ currentBalanceUSD: string;
581
+ requiredUSD: string;
582
+ walletAddress: string;
583
+ });
584
+ }
585
+ /**
586
+ * Thrown when wallet has no USDC balance (or effectively zero).
587
+ */
588
+ declare class EmptyWalletError extends Error {
589
+ readonly code: "EMPTY_WALLET";
590
+ readonly walletAddress: string;
591
+ constructor(walletAddress: string);
592
+ }
593
+ /**
594
+ * Type guard to check if an error is InsufficientFundsError.
595
+ */
596
+ declare function isInsufficientFundsError(error: unknown): error is InsufficientFundsError;
597
+ /**
598
+ * Type guard to check if an error is EmptyWalletError.
599
+ */
600
+ declare function isEmptyWalletError(error: unknown): error is EmptyWalletError;
601
+ /**
602
+ * Type guard to check if an error is a balance-related error.
603
+ */
604
+ declare function isBalanceError(error: unknown): error is InsufficientFundsError | EmptyWalletError;
605
+ /**
606
+ * Thrown when RPC call fails (network error, node down, etc).
607
+ * Distinguishes infrastructure failures from actual empty wallets.
608
+ */
609
+ declare class RpcError extends Error {
610
+ readonly code: "RPC_ERROR";
611
+ readonly originalError: unknown;
612
+ constructor(message: string, originalError?: unknown);
613
+ }
614
+ /**
615
+ * Type guard to check if an error is RpcError.
616
+ */
617
+ declare function isRpcError(error: unknown): error is RpcError;
618
+
619
+ /**
620
+ * Retry Logic for ClawRouter
621
+ *
622
+ * Provides fetch wrapper with exponential backoff for transient errors.
623
+ * Retries on 429 (rate limit), 502, 503, 504 (server errors).
624
+ */
625
+ /** Configuration for retry behavior */
626
+ type RetryConfig = {
627
+ /** Maximum number of retries (default: 2) */
628
+ maxRetries: number;
629
+ /** Base delay in ms for exponential backoff (default: 500) */
630
+ baseDelayMs: number;
631
+ /** HTTP status codes that trigger a retry (default: [429, 502, 503, 504]) */
632
+ retryableCodes: number[];
633
+ };
634
+ /** Default retry configuration */
635
+ declare const DEFAULT_RETRY_CONFIG: RetryConfig;
636
+ /**
637
+ * Wrap a fetch-like function with retry logic and exponential backoff.
638
+ *
639
+ * @param fetchFn - The fetch function to wrap (can be standard fetch or x402 payFetch)
640
+ * @param url - URL to fetch
641
+ * @param init - Fetch init options
642
+ * @param config - Retry configuration (optional, uses defaults)
643
+ * @returns Response from successful fetch or last failed attempt
644
+ *
645
+ * @example
646
+ * ```typescript
647
+ * const response = await fetchWithRetry(
648
+ * fetch,
649
+ * "https://api.example.com/endpoint",
650
+ * { method: "POST", body: JSON.stringify(data) },
651
+ * { maxRetries: 3 }
652
+ * );
653
+ * ```
654
+ */
655
+ declare function fetchWithRetry(fetchFn: (url: string, init?: RequestInit) => Promise<Response>, url: string, init?: RequestInit, config?: Partial<RetryConfig>): Promise<Response>;
656
+ /**
657
+ * Check if an error or response indicates a retryable condition.
658
+ */
659
+ declare function isRetryable(errorOrResponse: Error | Response, config?: Partial<RetryConfig>): boolean;
660
+
449
661
  /**
450
662
  * @blockrun/clawrouter
451
663
  *
@@ -459,12 +671,12 @@ declare function createPaymentFetch(privateKey: `0x${string}`): PaymentFetchResu
459
671
  * # Fund your wallet with USDC on Base (address printed on install)
460
672
  *
461
673
  * # Use smart routing (auto-picks cheapest model)
462
- * openclaw config set model blockrun/auto
674
+ * openclaw models set blockrun/auto
463
675
  *
464
676
  * # Or use any specific BlockRun model
465
- * openclaw config set model openai/gpt-5.2
677
+ * openclaw models set openai/gpt-5.2
466
678
  */
467
679
 
468
680
  declare const plugin: OpenClawPluginDefinition;
469
681
 
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 };
682
+ 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 };