@blockrun/llm 2.12.0 → 2.13.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/dist/index.d.ts CHANGED
@@ -460,6 +460,45 @@ interface VoiceInfo {
460
460
  preview_url?: string;
461
461
  [key: string]: unknown;
462
462
  }
463
+ interface RpcClientOptions {
464
+ /** EVM wallet private key (hex string starting with 0x) */
465
+ privateKey?: `0x${string}` | string;
466
+ /** API endpoint URL (default: https://blockrun.ai/api) */
467
+ apiUrl?: string;
468
+ /** Request timeout in milliseconds (default: 60000 — upstream gateway timeout is 20s) */
469
+ timeout?: number;
470
+ }
471
+ /** A JSON-RPC 2.0 error object. */
472
+ interface RpcError {
473
+ code?: number;
474
+ message?: string;
475
+ data?: unknown;
476
+ }
477
+ /**
478
+ * Response from a multi-chain JSON-RPC call.
479
+ *
480
+ * Standard JSON-RPC 2.0 envelope plus BlockRun gateway metadata pulled
481
+ * from response headers (X-Network / X-Cache / X-Payment-Receipt).
482
+ */
483
+ interface RpcResponse<T = unknown> {
484
+ jsonrpc?: string;
485
+ id?: string | number | null;
486
+ result?: T;
487
+ error?: RpcError;
488
+ /** Canonical network key, e.g. "ethereum" (from X-Network) */
489
+ network?: string;
490
+ /** Served from the gateway's method-aware cache (from X-Cache) */
491
+ cacheHit?: boolean;
492
+ /** x402 settlement tx hash (single calls) */
493
+ txHash?: string;
494
+ }
495
+ /** A single request in a JSON-RPC batch (jsonrpc/id auto-filled if omitted). */
496
+ interface RpcBatchRequest {
497
+ method: string;
498
+ params?: unknown[];
499
+ id?: string | number;
500
+ jsonrpc?: string;
501
+ }
463
502
  /** Built-in Bland.ai voice presets. Any string is accepted (custom voice IDs work too). */
464
503
  type VoicePreset = "nat" | "josh" | "maya" | "june" | "paige" | "derek" | "florian";
465
504
  /** Bland.ai conversation model tier. */
@@ -578,6 +617,22 @@ interface VideoGenerateOptions {
578
617
  * with `imageUrl`. Real-person likeness is not supported on BlockRun.
579
618
  */
580
619
  realFaceAssetId?: string;
620
+ /**
621
+ * First-and-last-frame interpolation: a second image that seeds the FINAL
622
+ * frame so the model tweens from `imageUrl` → `lastFrameUrl`. Requires
623
+ * `imageUrl` (the first frame) and a Seedance model
624
+ * (bytedance/seedance-1.5-pro, seedance-2.0, or seedance-2.0-fast).
625
+ * Priced identically to image-to-video. Mutually exclusive with
626
+ * `realFaceAssetId`.
627
+ */
628
+ lastFrameUrl?: string;
629
+ /**
630
+ * Omni / multi-reference: up to 9 reference image URLs for character/style
631
+ * consistency (**Seedance 2.0 only**). Cite them as "image 1", "image 2"
632
+ * in the prompt. Mutually exclusive with `imageUrl` / `lastFrameUrl` /
633
+ * `realFaceAssetId`.
634
+ */
635
+ referenceImageUrls?: string[];
581
636
  /** Duration to bill for (defaults to model's default duration) */
582
637
  durationSeconds?: number;
583
638
  /** Output aspect ratio. Token360 / Seedance only — silently ignored by xAI Grok. */
@@ -2296,6 +2351,125 @@ declare class SurfClient {
2296
2351
  getWalletAddress(): string;
2297
2352
  }
2298
2353
 
2354
+ /**
2355
+ * BlockRun RPC Client - Multi-chain JSON-RPC (Tatum gateway) via x402 micropayments.
2356
+ *
2357
+ * One endpoint, 40+ chains: Ethereum, Base, Solana, Polygon, BSC, Arbitrum,
2358
+ * Optimism, Avalanche, Bitcoin, Sui, and more. Standard JSON-RPC 2.0
2359
+ * passthrough — no API key, pay-per-call in USDC.
2360
+ *
2361
+ * SECURITY NOTE - Private Key Handling:
2362
+ * Your private key NEVER leaves your machine. Here's what happens:
2363
+ * 1. Key stays local - only used to sign an EIP-712 typed data message
2364
+ * 2. Only the SIGNATURE is sent in the PAYMENT-SIGNATURE header
2365
+ * 3. BlockRun verifies the signature on-chain via Coinbase CDP facilitator
2366
+ *
2367
+ * Usage:
2368
+ * import { RpcClient } from '@blockrun/llm';
2369
+ *
2370
+ * const client = new RpcClient({ privateKey: '0x...' });
2371
+ *
2372
+ * // EVM chains speak eth_* JSON-RPC
2373
+ * const block = await client.call('ethereum', 'eth_blockNumber');
2374
+ * console.log(block.result); // e.g. "0x1499f7c"
2375
+ *
2376
+ * const balance = await client.call('base', 'eth_getBalance', [
2377
+ * '0x4200000000000000000000000000000000000006',
2378
+ * 'latest',
2379
+ * ]);
2380
+ *
2381
+ * // Non-EVM chains speak their native JSON-RPC
2382
+ * const slot = await client.call('solana', 'getSlot');
2383
+ *
2384
+ * // Batch: one payment, per-element pricing ($0.002 x N)
2385
+ * const out = await client.batch('polygon', [
2386
+ * { method: 'eth_blockNumber' },
2387
+ * { method: 'eth_gasPrice' },
2388
+ * ]);
2389
+ *
2390
+ * Pricing:
2391
+ * Flat $0.002 per JSON-RPC call; a batch charges per element.
2392
+ *
2393
+ * Networks:
2394
+ * 40 curated chains (see SUPPORTED_NETWORKS) plus common aliases
2395
+ * (eth, arb, op, matic, bnb, avax, sol, btc, xrp, dot, ...). Unknown but
2396
+ * well-formed slugs fall through to a generic `{slug}-mainnet` gateway
2397
+ * attempt, so new Tatum chains work without an SDK update.
2398
+ */
2399
+
2400
+ /**
2401
+ * Flat price per JSON-RPC call (batch = N x this). Informational only —
2402
+ * the actual quote always comes from the 402 challenge.
2403
+ */
2404
+ declare const RPC_PRICE_USD = 0.002;
2405
+ /**
2406
+ * Curated chains accepted by /v1/rpc/{network}. Mirrors the backend chain
2407
+ * registry (verified live 2026-06-07). EVM chains use eth_* JSON-RPC;
2408
+ * non-EVM (Solana / UTXO / NEAR / Sui / XRP Ledger / Polkadot) speak their
2409
+ * own JSON-RPC dialect.
2410
+ */
2411
+ declare const SUPPORTED_NETWORKS: readonly ["ethereum", "base", "arbitrum", "arbitrum-nova", "optimism", "polygon", "bsc", "avalanche", "fantom", "cronos", "celo", "gnosis", "zksync", "berachain", "unichain", "monad", "chiliz", "moonbeam", "aurora", "flare", "oasis", "kaia", "sonic", "xdc", "abstract", "hyperevm", "plume", "ronin", "rootstock", "solana", "bitcoin", "litecoin", "dogecoin", "bitcoin-cash", "near", "sui", "ripple", "polkadot", "kusama", "zcash"];
2412
+ type RpcNetwork = (typeof SUPPORTED_NETWORKS)[number] | (string & {});
2413
+ /** Common short names the gateway also accepts (resolved server-side). */
2414
+ declare const NETWORK_ALIASES: Record<string, string>;
2415
+ /**
2416
+ * BlockRun Multi-chain RPC Client.
2417
+ *
2418
+ * Standard JSON-RPC 2.0 access to 40+ chains through BlockRun's Tatum
2419
+ * gateway with automatic x402 micropayments on Base chain.
2420
+ *
2421
+ * Flat $0.002 per call; a JSON-RPC batch charges per element.
2422
+ */
2423
+ declare class RpcClient {
2424
+ private account;
2425
+ private privateKey;
2426
+ private apiUrl;
2427
+ private timeout;
2428
+ private sessionTotalUsd;
2429
+ private sessionCalls;
2430
+ constructor(options?: RpcClientOptions);
2431
+ /**
2432
+ * Make a single JSON-RPC 2.0 call. Flat $0.002.
2433
+ *
2434
+ * @param network - Chain name (e.g. "ethereum", "base", "solana") or a
2435
+ * common alias ("eth", "sol", "matic", ...). See
2436
+ * SUPPORTED_NETWORKS / NETWORK_ALIASES.
2437
+ * @param method - Chain RPC method, e.g. "eth_blockNumber", "eth_call",
2438
+ * "eth_getBalance" (EVM) or "getSlot", "getAccountInfo"
2439
+ * (Solana).
2440
+ * @param params - Method-specific params array (optional).
2441
+ * @returns RpcResponse with `result` (or JSON-RPC `error`), plus
2442
+ * `network`, `cacheHit` and `txHash` metadata.
2443
+ *
2444
+ * @example
2445
+ * const block = await client.call('ethereum', 'eth_blockNumber');
2446
+ * console.log(parseInt(block.result as string, 16));
2447
+ */
2448
+ call<T = unknown>(network: RpcNetwork, method: string, params?: unknown[]): Promise<RpcResponse<T>>;
2449
+ /**
2450
+ * Make a JSON-RPC 2.0 batch call. Priced per element ($0.002 x N).
2451
+ *
2452
+ * @param network - Chain name or alias (see {@link call}).
2453
+ * @param requests - Requests, each with a `method` and optional
2454
+ * `params` / `id`. `jsonrpc` and missing ids are
2455
+ * filled in automatically.
2456
+ * @returns Array of RpcResponse, in upstream order.
2457
+ *
2458
+ * @example
2459
+ * const out = await client.batch('base', [
2460
+ * { method: 'eth_blockNumber' },
2461
+ * { method: 'eth_gasPrice' },
2462
+ * ]);
2463
+ */
2464
+ batch(network: RpcNetwork, requests: RpcBatchRequest[]): Promise<RpcResponse[]>;
2465
+ private toResponse;
2466
+ private requestWithPayment;
2467
+ private handlePaymentAndRetry;
2468
+ private fetchWithTimeout;
2469
+ getWalletAddress(): string;
2470
+ getSpending(): Spending;
2471
+ }
2472
+
2299
2473
  /**
2300
2474
  * BlockrunClient — the x402-paying HTTP primitive for the BlockRun gateway.
2301
2475
  *
@@ -3083,4 +3257,4 @@ declare function validateTemperature(temperature?: number): void;
3083
3257
  */
3084
3258
  declare function validateTopP(topP?: number): void;
3085
3259
 
3086
- export { APIError, AnthropicClient, type AudioModel, type AudioTrack, BASE_CHAIN_ID, type BarResolution, type BlockRunAnthropicOptions, BlockrunClient, type BlockrunClientOptions, BlockrunError, type CallInitiatedResponse, type CallModel, type CallOptions, type CallStatusResponse, type ChatChoice, type ChatCompletionOptions, type ChatMessage, type ChatOptions, type ChatResponse, type ChatResponseWithCost, type ChatUsage, type CostEntry, type CostEstimate, type CreatePaymentOptions, type FunctionCall, type FunctionDefinition, type HistoryOptions, ImageClient, type ImageClientOptions, type ImageData, type ImageEditOptions, type ImageGenerateOptions, type ImageModel, type ImageResponse, KNOWN_PROVIDERS, LLMClient, type LLMClientOptions, type ListOptions, type MarketSession, type Model, MusicClient, type MusicClientOptions, type MusicGenerateOptions, type MusicResponse, type NewsSearchSource, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PHONE_PRICES, PORTRAIT_ENROLLMENT_PRICE_USD, PaymentError, type PaymentLinks, type PhoneBuyOptions, type PhoneBuyResponse, PhoneClient, type PhoneClientOptions, type PhoneListResponse, type PhoneLookupResponse, type PhoneNumberRecord, type PhoneReleaseResponse, type PhoneRenewResponse, type PollOptions, PortraitClient, type PortraitClientOptions, type PortraitEnrollOptions, type PortraitEnrollResponse, type PriceBar, type PriceCategory, PriceClient, type PriceClientOptions, type PriceHistoryResponse, type PriceOptions, type PricePoint, type ResponseFormat, type RoutingDecision, type RoutingProfile, type RoutingTier, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, SearchClient, type SearchClientOptions, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SearchUsage, type SmartChatOptions, type SmartChatResponse, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type SoundEffectOptions, type SpeechAudio, SpeechClient, type SpeechClientOptions, type SpeechGenerateOptions, type SpeechModel, type SpeechResponse, type SpeechVoice, type Spending, type SpendingReport, type StockMarket, SurfClient, type SurfClientOptions, type SymbolListResponse, type Tool, type ToolCall, type ToolChoice, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, VideoClient, type VideoClientOptions, type VideoClip, type VideoGenerateOptions, type VideoModel, type VideoResponse, VoiceClient, type VoiceClientOptions, type VoiceInfo, type VoicePreset, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletInfo, type WebSearchSource, type XArticlesRisingResponse, type XAuthorAnalyticsResponse, XClient, type XClientOptions, type XCompareAuthorsResponse, type XFollower, type XFollowersResponse, type XFollowingsResponse, type XMentionsOptions, type XMentionsResponse, type XSearchOptions, type XSearchResponse, type XSearchSource, type XTrendingResponse, type XTweet, type XTweetLookupResponse, type XTweetRepliesOptions, type XTweetRepliesResponse, type XTweetThreadResponse, type XTweetsResponse, type XUser, type XUserInfoResponse, type XUserLookupResponse, type XUserTweetsOptions, type XVerifiedFollowersResponse, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatWalletCreatedMessage, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, validateMaxTokens, validateModel, validateTemperature, validateTopP };
3260
+ export { APIError, AnthropicClient, type AudioModel, type AudioTrack, BASE_CHAIN_ID, type BarResolution, type BlockRunAnthropicOptions, BlockrunClient, type BlockrunClientOptions, BlockrunError, type CallInitiatedResponse, type CallModel, type CallOptions, type CallStatusResponse, type ChatChoice, type ChatCompletionOptions, type ChatMessage, type ChatOptions, type ChatResponse, type ChatResponseWithCost, type ChatUsage, type CostEntry, type CostEstimate, type CreatePaymentOptions, type FunctionCall, type FunctionDefinition, type HistoryOptions, ImageClient, type ImageClientOptions, type ImageData, type ImageEditOptions, type ImageGenerateOptions, type ImageModel, type ImageResponse, KNOWN_PROVIDERS, LLMClient, type LLMClientOptions, type ListOptions, type MarketSession, type Model, MusicClient, type MusicClientOptions, type MusicGenerateOptions, type MusicResponse, NETWORK_ALIASES, type NewsSearchSource, OpenAI, type OpenAIChatCompletionChoice, type OpenAIChatCompletionChunk, type OpenAIChatCompletionParams, type OpenAIChatCompletionResponse, type OpenAIClientOptions, PHONE_PRICES, PORTRAIT_ENROLLMENT_PRICE_USD, PaymentError, type PaymentLinks, type PhoneBuyOptions, type PhoneBuyResponse, PhoneClient, type PhoneClientOptions, type PhoneListResponse, type PhoneLookupResponse, type PhoneNumberRecord, type PhoneReleaseResponse, type PhoneRenewResponse, type PollOptions, PortraitClient, type PortraitClientOptions, type PortraitEnrollOptions, type PortraitEnrollResponse, type PriceBar, type PriceCategory, PriceClient, type PriceClientOptions, type PriceHistoryResponse, type PriceOptions, type PricePoint, RPC_PRICE_USD, type ResponseFormat, type RoutingDecision, type RoutingProfile, type RoutingTier, type RpcBatchRequest, RpcClient, type RpcClientOptions, type RpcError, type RpcNetwork, type RpcResponse, type RssSearchSource, SOLANA_NETWORK, SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH, SUPPORTED_NETWORKS, SearchClient, type SearchClientOptions, type SearchOptions, type SearchParameters, type SearchResult, type SearchSource, type SearchUsage, type SmartChatOptions, type SmartChatResponse, SolanaLLMClient, type SolanaLLMClientOptions, type SolanaWalletInfo, type SoundEffectOptions, type SpeechAudio, SpeechClient, type SpeechClientOptions, type SpeechGenerateOptions, type SpeechModel, type SpeechResponse, type SpeechVoice, type Spending, type SpendingReport, type StockMarket, SurfClient, type SurfClientOptions, type SymbolListResponse, type Tool, type ToolCall, type ToolChoice, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, VideoClient, type VideoClientOptions, type VideoClip, type VideoGenerateOptions, type VideoModel, type VideoResponse, VoiceClient, type VoiceClientOptions, type VoiceInfo, type VoicePreset, WALLET_DIR_PATH, WALLET_FILE_PATH, type WalletInfo, type WebSearchSource, type XArticlesRisingResponse, type XAuthorAnalyticsResponse, XClient, type XClientOptions, type XCompareAuthorsResponse, type XFollower, type XFollowersResponse, type XFollowingsResponse, type XMentionsOptions, type XMentionsResponse, type XSearchOptions, type XSearchResponse, type XSearchSource, type XTrendingResponse, type XTweet, type XTweetLookupResponse, type XTweetRepliesOptions, type XTweetRepliesResponse, type XTweetThreadResponse, type XTweetsResponse, type XUser, type XUserInfoResponse, type XUserLookupResponse, type XUserTweetsOptions, type XVerifiedFollowersResponse, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatWalletCreatedMessage, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, validateMaxTokens, validateModel, validateTemperature, validateTopP };
package/dist/index.js CHANGED
@@ -2546,11 +2546,33 @@ var VideoClient = class {
2546
2546
  "realFaceAssetId must be a Token360 asset id matching 'ta_[A-Za-z0-9]+' (e.g. 'ta_abc123xyz')"
2547
2547
  );
2548
2548
  }
2549
+ if (options?.lastFrameUrl && !options?.imageUrl) {
2550
+ throw new Error(
2551
+ "lastFrameUrl requires imageUrl: imageUrl seeds the FIRST frame and lastFrameUrl the FINAL frame \u2014 send both."
2552
+ );
2553
+ }
2554
+ if (options?.lastFrameUrl && options?.realFaceAssetId) {
2555
+ throw new Error(
2556
+ "lastFrameUrl and realFaceAssetId are mutually exclusive; first-and-last-frame uses imageUrl + lastFrameUrl."
2557
+ );
2558
+ }
2559
+ if (options?.referenceImageUrls?.length) {
2560
+ if (options.imageUrl || options.lastFrameUrl || options.realFaceAssetId) {
2561
+ throw new Error(
2562
+ "referenceImageUrls is mutually exclusive with imageUrl, lastFrameUrl, and realFaceAssetId."
2563
+ );
2564
+ }
2565
+ if (options.referenceImageUrls.length > 9) {
2566
+ throw new Error("referenceImageUrls accepts at most 9 images.");
2567
+ }
2568
+ }
2549
2569
  const body = {
2550
2570
  model: options?.model || DEFAULT_MODEL4,
2551
2571
  prompt
2552
2572
  };
2553
2573
  if (options?.imageUrl) body.image_url = options.imageUrl;
2574
+ if (options?.lastFrameUrl) body.last_frame_url = options.lastFrameUrl;
2575
+ if (options?.referenceImageUrls?.length) body.reference_image_urls = options.referenceImageUrls;
2554
2576
  if (options?.realFaceAssetId) body.real_face_asset_id = options.realFaceAssetId;
2555
2577
  if (options?.durationSeconds !== void 0) body.duration_seconds = options.durationSeconds;
2556
2578
  if (options?.aspectRatio) body.aspect_ratio = options.aspectRatio;
@@ -3980,10 +4002,263 @@ var SurfClient = class {
3980
4002
  }
3981
4003
  };
3982
4004
 
3983
- // src/blockrun.ts
4005
+ // src/rpc.ts
3984
4006
  import { privateKeyToAccount as privateKeyToAccount13 } from "viem/accounts";
3985
4007
  var DEFAULT_API_URL13 = "https://blockrun.ai/api";
3986
4008
  var DEFAULT_TIMEOUT13 = 6e4;
4009
+ var RPC_PRICE_USD = 2e-3;
4010
+ var SUPPORTED_NETWORKS = [
4011
+ // EVM
4012
+ "ethereum",
4013
+ "base",
4014
+ "arbitrum",
4015
+ "arbitrum-nova",
4016
+ "optimism",
4017
+ "polygon",
4018
+ "bsc",
4019
+ "avalanche",
4020
+ "fantom",
4021
+ "cronos",
4022
+ "celo",
4023
+ "gnosis",
4024
+ "zksync",
4025
+ "berachain",
4026
+ "unichain",
4027
+ "monad",
4028
+ "chiliz",
4029
+ "moonbeam",
4030
+ "aurora",
4031
+ "flare",
4032
+ "oasis",
4033
+ "kaia",
4034
+ "sonic",
4035
+ "xdc",
4036
+ "abstract",
4037
+ "hyperevm",
4038
+ "plume",
4039
+ "ronin",
4040
+ "rootstock",
4041
+ // Non-EVM (JSON-RPC-compatible)
4042
+ "solana",
4043
+ "bitcoin",
4044
+ "litecoin",
4045
+ "dogecoin",
4046
+ "bitcoin-cash",
4047
+ "near",
4048
+ "sui",
4049
+ "ripple",
4050
+ "polkadot",
4051
+ "kusama",
4052
+ "zcash"
4053
+ ];
4054
+ var NETWORK_ALIASES = {
4055
+ eth: "ethereum",
4056
+ arb: "arbitrum",
4057
+ "arbitrum-one": "arbitrum",
4058
+ "arb-one": "arbitrum",
4059
+ "arb-nova": "arbitrum-nova",
4060
+ op: "optimism",
4061
+ matic: "polygon",
4062
+ pol: "polygon",
4063
+ bnb: "bsc",
4064
+ binance: "bsc",
4065
+ "binance-smart-chain": "bsc",
4066
+ avax: "avalanche",
4067
+ ftm: "fantom",
4068
+ bera: "berachain",
4069
+ klaytn: "kaia",
4070
+ chz: "chiliz",
4071
+ hyperliquid: "hyperevm",
4072
+ rsk: "rootstock",
4073
+ sol: "solana",
4074
+ btc: "bitcoin",
4075
+ ltc: "litecoin",
4076
+ doge: "dogecoin",
4077
+ bch: "bitcoin-cash",
4078
+ xrp: "ripple",
4079
+ xrpl: "ripple",
4080
+ dot: "polkadot",
4081
+ zec: "zcash"
4082
+ };
4083
+ var RpcClient = class {
4084
+ account;
4085
+ privateKey;
4086
+ apiUrl;
4087
+ timeout;
4088
+ sessionTotalUsd = 0;
4089
+ sessionCalls = 0;
4090
+ constructor(options = {}) {
4091
+ const envKey = typeof process !== "undefined" && process.env ? process.env.BLOCKRUN_WALLET_KEY || process.env.BASE_CHAIN_WALLET_KEY : void 0;
4092
+ const privateKey = options.privateKey || envKey;
4093
+ if (!privateKey) {
4094
+ throw new Error(
4095
+ "Private key required. Pass privateKey in options or set BLOCKRUN_WALLET_KEY environment variable."
4096
+ );
4097
+ }
4098
+ validatePrivateKey(privateKey);
4099
+ this.privateKey = privateKey;
4100
+ this.account = privateKeyToAccount13(privateKey);
4101
+ const apiUrl = options.apiUrl || DEFAULT_API_URL13;
4102
+ validateApiUrl(apiUrl);
4103
+ this.apiUrl = apiUrl.replace(/\/$/, "");
4104
+ this.timeout = options.timeout || DEFAULT_TIMEOUT13;
4105
+ }
4106
+ /**
4107
+ * Make a single JSON-RPC 2.0 call. Flat $0.002.
4108
+ *
4109
+ * @param network - Chain name (e.g. "ethereum", "base", "solana") or a
4110
+ * common alias ("eth", "sol", "matic", ...). See
4111
+ * SUPPORTED_NETWORKS / NETWORK_ALIASES.
4112
+ * @param method - Chain RPC method, e.g. "eth_blockNumber", "eth_call",
4113
+ * "eth_getBalance" (EVM) or "getSlot", "getAccountInfo"
4114
+ * (Solana).
4115
+ * @param params - Method-specific params array (optional).
4116
+ * @returns RpcResponse with `result` (or JSON-RPC `error`), plus
4117
+ * `network`, `cacheHit` and `txHash` metadata.
4118
+ *
4119
+ * @example
4120
+ * const block = await client.call('ethereum', 'eth_blockNumber');
4121
+ * console.log(parseInt(block.result as string, 16));
4122
+ */
4123
+ async call(network, method, params) {
4124
+ const body = { jsonrpc: "2.0", id: 1, method };
4125
+ if (params !== void 0) body.params = params;
4126
+ const { data, headers } = await this.requestWithPayment(network, body);
4127
+ return this.toResponse(data, headers);
4128
+ }
4129
+ /**
4130
+ * Make a JSON-RPC 2.0 batch call. Priced per element ($0.002 x N).
4131
+ *
4132
+ * @param network - Chain name or alias (see {@link call}).
4133
+ * @param requests - Requests, each with a `method` and optional
4134
+ * `params` / `id`. `jsonrpc` and missing ids are
4135
+ * filled in automatically.
4136
+ * @returns Array of RpcResponse, in upstream order.
4137
+ *
4138
+ * @example
4139
+ * const out = await client.batch('base', [
4140
+ * { method: 'eth_blockNumber' },
4141
+ * { method: 'eth_gasPrice' },
4142
+ * ]);
4143
+ */
4144
+ async batch(network, requests) {
4145
+ if (!requests.length) {
4146
+ throw new Error("batch requires at least one request");
4147
+ }
4148
+ const body = requests.map((req, i) => {
4149
+ if (!req.method) throw new Error(`batch request ${i} is missing 'method'`);
4150
+ return { jsonrpc: "2.0", id: i + 1, ...req };
4151
+ });
4152
+ const { data, headers } = await this.requestWithPayment(network, body);
4153
+ const items = Array.isArray(data) ? data : [data];
4154
+ return items.map((item) => this.toResponse(item, headers));
4155
+ }
4156
+ toResponse(data, headers) {
4157
+ const base = data !== null && typeof data === "object" && !Array.isArray(data) ? { ...data } : { result: data };
4158
+ const network = headers.get("x-network");
4159
+ if (network) base.network = network;
4160
+ base.cacheHit = (headers.get("x-cache") || "").toUpperCase() === "HIT";
4161
+ const txHash = headers.get("x-payment-receipt") || headers.get("X-Payment-Receipt");
4162
+ if (txHash) base.txHash = txHash;
4163
+ return base;
4164
+ }
4165
+ async requestWithPayment(network, body) {
4166
+ const endpoint = `/v1/rpc/${network}`;
4167
+ const url = `${this.apiUrl}${endpoint}`;
4168
+ const response = await this.fetchWithTimeout(url, {
4169
+ method: "POST",
4170
+ headers: { "Content-Type": "application/json" },
4171
+ body: JSON.stringify(body)
4172
+ });
4173
+ if (response.status === 402) {
4174
+ return this.handlePaymentAndRetry(url, endpoint, body, response);
4175
+ }
4176
+ if (!response.ok) {
4177
+ let errorBody;
4178
+ try {
4179
+ errorBody = await response.json();
4180
+ } catch {
4181
+ errorBody = { error: "Request failed" };
4182
+ }
4183
+ throw new APIError(`API error: ${response.status}`, response.status, sanitizeErrorResponse(errorBody));
4184
+ }
4185
+ return { data: await response.json(), headers: response.headers };
4186
+ }
4187
+ async handlePaymentAndRetry(url, endpoint, body, response) {
4188
+ let paymentHeader = response.headers.get("payment-required");
4189
+ if (!paymentHeader) {
4190
+ try {
4191
+ const respBody = await response.json();
4192
+ if (respBody.x402 || respBody.accepts) {
4193
+ paymentHeader = btoa(JSON.stringify(respBody));
4194
+ }
4195
+ } catch {
4196
+ }
4197
+ }
4198
+ if (!paymentHeader) {
4199
+ throw new PaymentError("402 response but no payment requirements found");
4200
+ }
4201
+ const paymentRequired = parsePaymentRequired(paymentHeader);
4202
+ const details = extractPaymentDetails(paymentRequired);
4203
+ const paymentPayload = await createPaymentPayload(
4204
+ this.privateKey,
4205
+ this.account.address,
4206
+ details.recipient,
4207
+ details.amount,
4208
+ details.network || "eip155:8453",
4209
+ {
4210
+ resourceUrl: details.resource?.url || `${this.apiUrl}${endpoint}`,
4211
+ resourceDescription: details.resource?.description || "BlockRun Multi-chain RPC",
4212
+ maxTimeoutSeconds: details.maxTimeoutSeconds || 300,
4213
+ extra: details.extra
4214
+ }
4215
+ );
4216
+ const retryResponse = await this.fetchWithTimeout(url, {
4217
+ method: "POST",
4218
+ headers: {
4219
+ "Content-Type": "application/json",
4220
+ "PAYMENT-SIGNATURE": paymentPayload
4221
+ },
4222
+ body: JSON.stringify(body)
4223
+ });
4224
+ if (retryResponse.status === 402) {
4225
+ throw new PaymentError("Payment was rejected. Check your wallet balance.");
4226
+ }
4227
+ if (!retryResponse.ok) {
4228
+ let errorBody;
4229
+ try {
4230
+ errorBody = await retryResponse.json();
4231
+ } catch {
4232
+ errorBody = { error: "Request failed" };
4233
+ }
4234
+ throw new APIError(`API error after payment: ${retryResponse.status}`, retryResponse.status, sanitizeErrorResponse(errorBody));
4235
+ }
4236
+ this.sessionCalls++;
4237
+ const paidUsd = Number(details.amount) / 1e6;
4238
+ if (Number.isFinite(paidUsd)) this.sessionTotalUsd += paidUsd;
4239
+ return { data: await retryResponse.json(), headers: retryResponse.headers };
4240
+ }
4241
+ async fetchWithTimeout(url, options) {
4242
+ const controller = new AbortController();
4243
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
4244
+ try {
4245
+ return await fetch(url, { ...options, signal: controller.signal });
4246
+ } finally {
4247
+ clearTimeout(timeoutId);
4248
+ }
4249
+ }
4250
+ getWalletAddress() {
4251
+ return this.account.address;
4252
+ }
4253
+ getSpending() {
4254
+ return { totalUsd: this.sessionTotalUsd, calls: this.sessionCalls };
4255
+ }
4256
+ };
4257
+
4258
+ // src/blockrun.ts
4259
+ import { privateKeyToAccount as privateKeyToAccount14 } from "viem/accounts";
4260
+ var DEFAULT_API_URL14 = "https://blockrun.ai/api";
4261
+ var DEFAULT_TIMEOUT14 = 6e4;
3987
4262
  var DEFAULT_POLL_INTERVAL_MS = 5e3;
3988
4263
  var DEFAULT_POLL_BUDGET_MS = 3e5;
3989
4264
  var MAX_SIGNED_AUTH_SECONDS = 600;
@@ -4004,11 +4279,11 @@ var BlockrunClient = class {
4004
4279
  }
4005
4280
  validatePrivateKey(privateKey);
4006
4281
  this.privateKey = privateKey;
4007
- this.account = privateKeyToAccount13(privateKey);
4008
- const apiUrl = options.apiUrl || DEFAULT_API_URL13;
4282
+ this.account = privateKeyToAccount14(privateKey);
4283
+ const apiUrl = options.apiUrl || DEFAULT_API_URL14;
4009
4284
  validateApiUrl(apiUrl);
4010
4285
  this.apiUrl = apiUrl.replace(/\/$/, "");
4011
- this.timeout = options.timeout || DEFAULT_TIMEOUT13;
4286
+ this.timeout = options.timeout || DEFAULT_TIMEOUT14;
4012
4287
  }
4013
4288
  /**
4014
4289
  * GET a BlockRun endpoint. `path` is everything after `/api` (a leading
@@ -4359,7 +4634,7 @@ function sleep(ms) {
4359
4634
  }
4360
4635
 
4361
4636
  // src/wallet.ts
4362
- import { privateKeyToAccount as privateKeyToAccount14, generatePrivateKey } from "viem/accounts";
4637
+ import { privateKeyToAccount as privateKeyToAccount15, generatePrivateKey } from "viem/accounts";
4363
4638
  import * as fs2 from "fs";
4364
4639
  import * as path2 from "path";
4365
4640
  import * as os2 from "os";
@@ -4369,7 +4644,7 @@ var WALLET_DIR = path2.join(os2.homedir(), ".blockrun");
4369
4644
  var WALLET_FILE = path2.join(WALLET_DIR, ".session");
4370
4645
  function createWallet() {
4371
4646
  const privateKey = generatePrivateKey();
4372
- const account = privateKeyToAccount14(privateKey);
4647
+ const account = privateKeyToAccount15(privateKey);
4373
4648
  return {
4374
4649
  address: account.address,
4375
4650
  privateKey
@@ -4425,12 +4700,12 @@ function loadWallet() {
4425
4700
  function getOrCreateWallet() {
4426
4701
  const envKey = typeof process !== "undefined" && process.env ? process.env.BLOCKRUN_WALLET_KEY || process.env.BASE_CHAIN_WALLET_KEY : void 0;
4427
4702
  if (envKey) {
4428
- const account = privateKeyToAccount14(envKey);
4703
+ const account = privateKeyToAccount15(envKey);
4429
4704
  return { address: account.address, privateKey: envKey, isNew: false };
4430
4705
  }
4431
4706
  const fileKey = loadWallet();
4432
4707
  if (fileKey) {
4433
- const account = privateKeyToAccount14(fileKey);
4708
+ const account = privateKeyToAccount15(fileKey);
4434
4709
  return { address: account.address, privateKey: fileKey, isNew: false };
4435
4710
  }
4436
4711
  const { address, privateKey } = createWallet();
@@ -4440,11 +4715,11 @@ function getOrCreateWallet() {
4440
4715
  function getWalletAddress() {
4441
4716
  const envKey = typeof process !== "undefined" && process.env ? process.env.BLOCKRUN_WALLET_KEY || process.env.BASE_CHAIN_WALLET_KEY : void 0;
4442
4717
  if (envKey) {
4443
- return privateKeyToAccount14(envKey).address;
4718
+ return privateKeyToAccount15(envKey).address;
4444
4719
  }
4445
4720
  const fileKey = loadWallet();
4446
4721
  if (fileKey) {
4447
- return privateKeyToAccount14(fileKey).address;
4722
+ return privateKeyToAccount15(fileKey).address;
4448
4723
  }
4449
4724
  return null;
4450
4725
  }
@@ -4624,7 +4899,7 @@ async function getOrCreateSolanaWallet() {
4624
4899
  // src/solana-client.ts
4625
4900
  var SOLANA_API_URL = "https://sol.blockrun.ai/api";
4626
4901
  var DEFAULT_MAX_TOKENS2 = 1024;
4627
- var DEFAULT_TIMEOUT14 = 6e4;
4902
+ var DEFAULT_TIMEOUT15 = 6e4;
4628
4903
  var SDK_VERSION2 = "0.3.0";
4629
4904
  var USER_AGENT2 = `blockrun-ts/${SDK_VERSION2}`;
4630
4905
  var DEFAULT_SOLANA_RPC_URL = "https://sol.blockrun.ai/api/v1/solana/rpc";
@@ -4674,7 +4949,7 @@ var SolanaLLMClient = class {
4674
4949
  const rpc = resolveRpcConfig(options.rpcUrl, options.rpcHeaders);
4675
4950
  this.rpcUrl = rpc.url;
4676
4951
  this.rpcHeaders = rpc.headers;
4677
- this.timeout = options.timeout || DEFAULT_TIMEOUT14;
4952
+ this.timeout = options.timeout || DEFAULT_TIMEOUT15;
4678
4953
  }
4679
4954
  /** Get Solana wallet address (public key in base58). */
4680
4955
  async getWalletAddress() {
@@ -5588,7 +5863,7 @@ var OpenAI = class {
5588
5863
  };
5589
5864
 
5590
5865
  // src/anthropic-compat.ts
5591
- import { privateKeyToAccount as privateKeyToAccount15 } from "viem/accounts";
5866
+ import { privateKeyToAccount as privateKeyToAccount16 } from "viem/accounts";
5592
5867
  var AnthropicClient = class {
5593
5868
  _client = null;
5594
5869
  _clientPromise = null;
@@ -5601,7 +5876,7 @@ var AnthropicClient = class {
5601
5876
  const key = options.privateKey ?? wallet.privateKey;
5602
5877
  validatePrivateKey(key);
5603
5878
  this._privateKey = key;
5604
- this._account = privateKeyToAccount15(this._privateKey);
5879
+ this._account = privateKeyToAccount16(this._privateKey);
5605
5880
  const apiUrl = options.apiUrl ?? "https://blockrun.ai/api";
5606
5881
  validateApiUrl(apiUrl);
5607
5882
  this._apiUrl = apiUrl.replace(/\/$/, "");
@@ -5705,6 +5980,7 @@ export {
5705
5980
  KNOWN_PROVIDERS,
5706
5981
  LLMClient,
5707
5982
  MusicClient,
5983
+ NETWORK_ALIASES,
5708
5984
  OpenAI,
5709
5985
  PHONE_PRICES,
5710
5986
  PORTRAIT_ENROLLMENT_PRICE_USD,
@@ -5712,8 +5988,11 @@ export {
5712
5988
  PhoneClient,
5713
5989
  PortraitClient,
5714
5990
  PriceClient,
5991
+ RPC_PRICE_USD,
5992
+ RpcClient,
5715
5993
  SOLANA_NETWORK,
5716
5994
  SOLANA_WALLET_FILE as SOLANA_WALLET_FILE_PATH,
5995
+ SUPPORTED_NETWORKS,
5717
5996
  SearchClient,
5718
5997
  SolanaLLMClient,
5719
5998
  SpeechClient,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/llm",
3
- "version": "2.12.0",
3
+ "version": "2.13.0",
4
4
  "type": "module",
5
5
  "description": "BlockRun SDK - Pay-per-request AI (LLM, Image, Video, Music, Voice) via x402 on Base and Solana",
6
6
  "main": "dist/index.cjs",