@blockrun/llm 3.26.5 → 4.1.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 CHANGED
@@ -703,7 +703,7 @@ operator to sign vouchers against the channel, up to `maxDeposit`.
703
703
  Batch mode needs three more optional peers on top of the Solana ones:
704
704
 
705
705
  ```bash
706
- npm install @x402/core@~2.28.0 @x402/svm@~2.28.0 @solana/kit
706
+ npm install @x402/core@~2.30.0 @x402/svm@~2.30.0 @solana/kit@^8
707
707
  ```
708
708
 
709
709
  ```typescript
@@ -1216,7 +1216,7 @@ const seedance = await client.generate('aerial drone shot over a snowy mountain'
1216
1216
  model: 'bytedance/seedance-2.0',
1217
1217
  aspectRatio: '21:9',
1218
1218
  resolution: '1080p',
1219
- generateAudio: true, // omit to use the model's default
1219
+ generateAudio: true, // Seedance default for every input; false = silent clip
1220
1220
  seed: 42,
1221
1221
  returnLastFrame: true, // useful for clip chaining
1222
1222
  });
package/dist/index.cjs CHANGED
@@ -51,10 +51,12 @@ __export(index_exports, {
51
51
  MusicClient: () => MusicClient,
52
52
  NETWORK_ALIASES: () => NETWORK_ALIASES,
53
53
  OpenAI: () => OpenAI,
54
+ PAYMENT_REPLAY: () => PAYMENT_REPLAY,
54
55
  PHONE_PRICES: () => PHONE_PRICES,
55
56
  PORTAL_URL: () => PORTAL_URL,
56
57
  PORTRAIT_ENROLLMENT_PRICE_USD: () => PORTRAIT_ENROLLMENT_PRICE_USD,
57
58
  PaymentError: () => PaymentError,
59
+ PaymentReplayError: () => PaymentReplayError,
58
60
  PhoneClient: () => PhoneClient,
59
61
  PortraitClient: () => PortraitClient,
60
62
  PriceClient: () => PriceClient,
@@ -77,6 +79,7 @@ __export(index_exports, {
77
79
  VoiceClient: () => VoiceClient,
78
80
  WALLET_DIR_PATH: () => WALLET_DIR_PATH,
79
81
  WALLET_FILE_PATH: () => WALLET_FILE_PATH,
82
+ buildPaymentRejectedError: () => buildPaymentRejectedError,
80
83
  clearCache: () => clearCache,
81
84
  createPaymentPayload: () => createPaymentPayload,
82
85
  createSolanaPaymentPayload: () => createSolanaPaymentPayload,
@@ -101,12 +104,14 @@ __export(index_exports, {
101
104
  getWalletAddress: () => getWalletAddress,
102
105
  importSolanaWallet: () => importSolanaWallet,
103
106
  importWallet: () => importWallet,
107
+ isPaymentReplay: () => isPaymentReplay,
104
108
  listDiscoveredSolanaWallets: () => listDiscoveredSolanaWallets,
105
109
  listDiscoveredWallets: () => listDiscoveredWallets2,
106
110
  loadSolanaWallet: () => loadSolanaWallet,
107
111
  loadWallet: () => loadWallet,
108
112
  logCost: () => logCost,
109
113
  parsePaymentRequired: () => parsePaymentRequired,
114
+ paymentRejectedErrorFromBody: () => paymentRejectedErrorFromBody,
110
115
  readSettlement: () => readSettlement,
111
116
  retryDisposition: () => retryDisposition,
112
117
  saveSolanaWallet: () => saveSolanaWallet,
@@ -160,9 +165,42 @@ var RetiredEndpointError = class extends BlockrunError {
160
165
  }
161
166
  };
162
167
  var PaymentError = class extends BlockrunError {
163
- constructor(message) {
168
+ /** HTTP status of the refusal, when it came from the gateway. */
169
+ statusCode;
170
+ /** The gateway's refusal body, sanitized; recovery fields kept verbatim. */
171
+ response;
172
+ constructor(message, options) {
164
173
  super(message);
165
174
  this.name = "PaymentError";
175
+ if (options?.statusCode !== void 0) this.statusCode = options.statusCode;
176
+ if (options?.response !== void 0) this.response = options.response;
177
+ }
178
+ };
179
+ var PAYMENT_REPLAY = "PAYMENT_REPLAY";
180
+ var PaymentReplayError = class extends PaymentError {
181
+ code = PAYMENT_REPLAY;
182
+ serverMessage;
183
+ details;
184
+ pollUrl;
185
+ jobId;
186
+ recoverable;
187
+ walletAuth;
188
+ payer;
189
+ constructor(message, options) {
190
+ super(message, options);
191
+ this.name = "PaymentReplayError";
192
+ const body = options?.response ?? {};
193
+ const str = (v) => typeof v === "string" && v ? v : void 0;
194
+ this.serverMessage = str(body.message);
195
+ this.details = str(body.details);
196
+ this.pollUrl = str(body.poll_url);
197
+ this.jobId = str(body.job_id) ?? str(body.id);
198
+ if (typeof body.recoverable === "boolean") this.recoverable = body.recoverable;
199
+ const walletAuth = body.wallet_auth;
200
+ if (walletAuth && typeof walletAuth === "object" && !Array.isArray(walletAuth)) {
201
+ this.walletAuth = walletAuth;
202
+ }
203
+ this.payer = str(body.payer);
166
204
  }
167
205
  };
168
206
  var APIError = class extends BlockrunError {
@@ -319,6 +357,83 @@ function validateResourceUrl(url, baseUrl) {
319
357
  return `${baseUrl}/v1/chat/completions`;
320
358
  }
321
359
  }
360
+ var REPLAY_FIELDS = [
361
+ "error",
362
+ "message",
363
+ "details",
364
+ "code",
365
+ "payer",
366
+ "id",
367
+ "job_id",
368
+ "poll_url",
369
+ "recoverable",
370
+ "wallet_auth",
371
+ "status"
372
+ ];
373
+ function asRecord(body) {
374
+ return body && typeof body === "object" && !Array.isArray(body) ? body : {};
375
+ }
376
+ function bodyCode(body) {
377
+ if (typeof body.code === "string") return body.code;
378
+ const nested = asRecord(body.error);
379
+ return typeof nested.code === "string" ? nested.code : void 0;
380
+ }
381
+ function isPaymentReplay(body) {
382
+ return bodyCode(asRecord(body))?.toUpperCase() === PAYMENT_REPLAY;
383
+ }
384
+ function namesEarlierResult(body) {
385
+ const record = asRecord(body);
386
+ return ["recoverable", "poll_url", "job_id", "wallet_auth"].some((key) => Boolean(record[key]));
387
+ }
388
+ function boundedString(value, max) {
389
+ return typeof value === "string" && value.length > 0 && value.length < max ? value : void 0;
390
+ }
391
+ function replayError(body, statusCode) {
392
+ const detail = {};
393
+ for (const key of REPLAY_FIELDS) if (body[key] !== void 0 && body[key] !== null) detail[key] = body[key];
394
+ detail.code = PAYMENT_REPLAY;
395
+ for (const field of PAYMENT_FACT_FIELDS) if (typeof body[field] === "string") detail[field] = body[field];
396
+ const serverMessage = typeof body.message === "string" ? body.message : "";
397
+ const pollUrl = typeof body.poll_url === "string" ? body.poll_url : "";
398
+ const details = typeof body.details === "string" ? body.details : "";
399
+ let text = "Payment authorization already used (PAYMENT_REPLAY): an earlier request with this authorization was accepted and may already have been charged. Nothing new was signed; a fresh payment for the same request can charge twice.";
400
+ if (pollUrl) text += ` Its result can be collected at ${pollUrl}.`;
401
+ if (serverMessage) text += ` Gateway: ${serverMessage}`;
402
+ if (details && details !== serverMessage) text += ` (${details})`;
403
+ return new PaymentReplayError(text, { statusCode, response: detail });
404
+ }
405
+ function paymentRejectedErrorFromBody(body, statusCode = 402, options = {}) {
406
+ const record = asRecord(body);
407
+ if (options.replay ?? isPaymentReplay(record)) return replayError(record, statusCode);
408
+ const sanitized = { ...sanitizeErrorResponse(record) };
409
+ const details = boundedString(record.details, 256);
410
+ if (details) sanitized.details = details;
411
+ const invalidMessage = boundedString(record.invalidMessage, 256);
412
+ if (invalidMessage) sanitized.invalidMessage = invalidMessage;
413
+ const reason = boundedString(record.reason, 128);
414
+ if (reason) sanitized.reason = reason;
415
+ const nested = asRecord(record.error);
416
+ const title = typeof record.error === "string" ? record.error : typeof nested.message === "string" ? nested.message : "";
417
+ const serverMessage = typeof record.message === "string" ? record.message : "";
418
+ let detailPart = details || title;
419
+ if (!details && serverMessage && serverMessage !== detailPart) {
420
+ detailPart = detailPart ? `${detailPart}: ${serverMessage}` : serverMessage;
421
+ }
422
+ if (invalidMessage) detailPart = detailPart ? `${detailPart} (${invalidMessage})` : invalidMessage;
423
+ const message = detailPart ? `Payment rejected by gateway: ${detailPart}` : `Payment rejected by gateway (HTTP ${statusCode}); it gave no reason`;
424
+ return new PaymentError(message, { statusCode, response: sanitized });
425
+ }
426
+ async function buildPaymentRejectedError(response, options = {}) {
427
+ let body;
428
+ try {
429
+ const text = await response.text();
430
+ body = text ? JSON.parse(text) : {};
431
+ } catch {
432
+ body = {};
433
+ }
434
+ const replay = options.replay ? options.replay(body) || void 0 : void 0;
435
+ return paymentRejectedErrorFromBody(body, response.status, { replay });
436
+ }
322
437
 
323
438
  // src/api-key.ts
324
439
  var TRANSIENT_STATUS = /* @__PURE__ */ new Set([502, 503, 504, 522, 524]);
@@ -5202,7 +5317,7 @@ function getCostSummary() {
5202
5317
  }
5203
5318
 
5204
5319
  // src/version.ts
5205
- var SDK_VERSION = "3.26.5";
5320
+ var SDK_VERSION = "4.1.0";
5206
5321
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
5207
5322
 
5208
5323
  // src/client.ts
@@ -5770,7 +5885,7 @@ var LLMClient = class _LLMClient {
5770
5885
  body: JSON.stringify(body)
5771
5886
  }, timeoutMs);
5772
5887
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
5773
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
5888
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
5774
5889
  if (!retryResp2.ok) {
5775
5890
  let errorBody;
5776
5891
  try {
@@ -5784,7 +5899,7 @@ var LLMClient = class _LLMClient {
5784
5899
  }
5785
5900
  }
5786
5901
  if (retryResponse.status === 402) {
5787
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
5902
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
5788
5903
  }
5789
5904
  if (!retryResponse.ok) {
5790
5905
  let errorBody;
@@ -5990,7 +6105,7 @@ var LLMClient = class _LLMClient {
5990
6105
  },
5991
6106
  body: JSON.stringify(body)
5992
6107
  });
5993
- if (streamResp.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
6108
+ if (streamResp.status === 402) throw await buildPaymentRejectedError(streamResp, { replay: namesEarlierResult });
5994
6109
  if (!streamResp.ok) {
5995
6110
  let errorBody;
5996
6111
  try {
@@ -6117,7 +6232,7 @@ var LLMClient = class _LLMClient {
6117
6232
  body: JSON.stringify(body)
6118
6233
  });
6119
6234
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
6120
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
6235
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
6121
6236
  if (!retryResp2.ok) {
6122
6237
  let errorBody;
6123
6238
  try {
@@ -6132,7 +6247,7 @@ var LLMClient = class _LLMClient {
6132
6247
  }
6133
6248
  }
6134
6249
  if (retryResponse.status === 402) {
6135
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
6250
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
6136
6251
  }
6137
6252
  if (!retryResponse.ok) {
6138
6253
  let errorBody;
@@ -6257,7 +6372,7 @@ var LLMClient = class _LLMClient {
6257
6372
  }
6258
6373
  });
6259
6374
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
6260
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
6375
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
6261
6376
  if (!retryResp2.ok) {
6262
6377
  let errorBody;
6263
6378
  try {
@@ -6272,7 +6387,7 @@ var LLMClient = class _LLMClient {
6272
6387
  }
6273
6388
  }
6274
6389
  if (retryResponse.status === 402) {
6275
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
6390
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
6276
6391
  }
6277
6392
  if (!retryResponse.ok) {
6278
6393
  let errorBody;
@@ -7037,9 +7152,7 @@ var ImageClient = class {
7037
7152
  body: JSON.stringify(body)
7038
7153
  });
7039
7154
  if (retryResponse.status === 402) {
7040
- throw new PaymentError(
7041
- "Payment was rejected. Check your wallet balance."
7042
- );
7155
+ throw await buildPaymentRejectedError(retryResponse);
7043
7156
  }
7044
7157
  if (!retryResponse.ok) {
7045
7158
  let errorBody;
@@ -7092,6 +7205,7 @@ var ImageClient = class {
7092
7205
  continue;
7093
7206
  }
7094
7207
  const pollBody = await pollResp.json().catch(() => ({}));
7208
+ if (pollResp.status === 402) throw paymentRejectedErrorFromBody(pollBody, 402);
7095
7209
  if (!pollResp.ok) {
7096
7210
  throw new APIError(
7097
7211
  `API error during poll: ${pollResp.status}`,
@@ -7291,7 +7405,7 @@ var MusicClient = class {
7291
7405
  body: JSON.stringify(body)
7292
7406
  });
7293
7407
  if (retryResponse.status === 402) {
7294
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7408
+ throw await buildPaymentRejectedError(retryResponse);
7295
7409
  }
7296
7410
  if (!retryResponse.ok) {
7297
7411
  let errorBody;
@@ -7350,6 +7464,7 @@ var MusicClient = class {
7350
7464
  }
7351
7465
  if (pollResp.status === 202 || TRANSIENT_POLL_STATUSES.has(pollResp.status)) continue;
7352
7466
  const pollBody = await pollResp.json().catch(() => ({}));
7467
+ if (pollResp.status === 402) throw paymentRejectedErrorFromBody(pollBody, 402);
7353
7468
  if (!pollResp.ok) {
7354
7469
  throw new APIError(
7355
7470
  `API error during poll of ${pollPath}: ${pollResp.status}`,
@@ -7570,7 +7685,7 @@ var SpeechClient = class {
7570
7685
  body: JSON.stringify(body)
7571
7686
  });
7572
7687
  if (retryResponse.status === 402) {
7573
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7688
+ throw await buildPaymentRejectedError(retryResponse);
7574
7689
  }
7575
7690
  if (!retryResponse.ok) {
7576
7691
  let errorBody;
@@ -7842,7 +7957,7 @@ var VideoClient = class {
7842
7957
  body: JSON.stringify(body)
7843
7958
  });
7844
7959
  if (submitResp.status === 402) {
7845
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7960
+ throw await buildPaymentRejectedError(submitResp);
7846
7961
  }
7847
7962
  if (submitResp.status !== 200 && submitResp.status !== 202) {
7848
7963
  await this.throwApiError(submitResp, "Submit failed");
@@ -7892,6 +8007,9 @@ var VideoClient = class {
7892
8007
  return data;
7893
8008
  }
7894
8009
  if (pollResp.status === 402) {
8010
+ if (isPaymentReplay(pollData)) {
8011
+ throw paymentRejectedErrorFromBody(pollData, pollResp.status, { replay: true });
8012
+ }
7895
8013
  if (resignsLeft > 0) {
7896
8014
  resignsLeft--;
7897
8015
  const challenge = await this.fetchWithTimeout(pollUrl, { method: "GET" });
@@ -7903,9 +8021,7 @@ var VideoClient = class {
7903
8021
  continue;
7904
8022
  }
7905
8023
  }
7906
- throw new PaymentError(
7907
- "Payment verification failed mid-poll (not a signature-expiry). Check the wallet balance and that you poll from the wallet that submitted the job."
7908
- );
8024
+ throw paymentRejectedErrorFromBody(pollData, pollResp.status);
7909
8025
  }
7910
8026
  if (pollResp.status !== 200 && pollResp.status !== 202 && pollResp.status !== 504) {
7911
8027
  await this.throwApiError(pollResp, "Poll failed");
@@ -8169,7 +8285,7 @@ var VoiceClient = class {
8169
8285
  body: JSON.stringify(body)
8170
8286
  });
8171
8287
  if (retryResponse.status === 402) {
8172
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8288
+ throw await buildPaymentRejectedError(retryResponse);
8173
8289
  }
8174
8290
  if (!retryResponse.ok) {
8175
8291
  let errorBody;
@@ -8401,7 +8517,7 @@ var PhoneClient = class {
8401
8517
  body: JSON.stringify(body)
8402
8518
  });
8403
8519
  if (retry.status === 402) {
8404
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8520
+ throw await buildPaymentRejectedError(retry);
8405
8521
  }
8406
8522
  const data = await this.unwrap(retry, true);
8407
8523
  if (!settlementSkipped(retry)) {
@@ -8569,7 +8685,7 @@ var PortraitClient = class {
8569
8685
  body: JSON.stringify(body)
8570
8686
  });
8571
8687
  if (retry.status === 402) {
8572
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8688
+ throw await buildPaymentRejectedError(retry);
8573
8689
  }
8574
8690
  const data = await this.unwrap(retry, true);
8575
8691
  if (!settlementSkipped(retry)) {
@@ -8731,7 +8847,7 @@ var SearchClient = class {
8731
8847
  body: JSON.stringify(body)
8732
8848
  });
8733
8849
  if (retry.status === 402) {
8734
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8850
+ throw await buildPaymentRejectedError(retry);
8735
8851
  }
8736
8852
  if (!retry.ok) {
8737
8853
  let errorBody;
@@ -8922,7 +9038,7 @@ var PriceClient = class {
8922
9038
  headers: { "PAYMENT-SIGNATURE": paymentPayload }
8923
9039
  });
8924
9040
  if (retry.status === 402) {
8925
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9041
+ throw await buildPaymentRejectedError(retry);
8926
9042
  }
8927
9043
  if (!retry.ok) {
8928
9044
  let errorBody;
@@ -9113,7 +9229,7 @@ var SurfClient = class {
9113
9229
  }
9114
9230
  const retry = await this.fetchWithTimeout(url, retryInit);
9115
9231
  if (retry.status === 402) {
9116
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9232
+ throw await buildPaymentRejectedError(retry);
9117
9233
  }
9118
9234
  if (!retry.ok) {
9119
9235
  await this.throwApiError(retry, `Surf request failed after payment (${method} ${url})`);
@@ -9381,7 +9497,7 @@ var RpcClient = class {
9381
9497
  body: JSON.stringify(body)
9382
9498
  });
9383
9499
  if (retryResponse.status === 402) {
9384
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9500
+ throw await buildPaymentRejectedError(retryResponse);
9385
9501
  }
9386
9502
  if (!retryResponse.ok) {
9387
9503
  let errorBody;
@@ -9556,7 +9672,7 @@ var BlockrunClient = class {
9556
9672
  body: JSON.stringify(body ?? {})
9557
9673
  });
9558
9674
  if (submitResp.status === 402) {
9559
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9675
+ throw await buildPaymentRejectedError(submitResp);
9560
9676
  }
9561
9677
  if (submitResp.status !== 200 && submitResp.status !== 202) {
9562
9678
  await this.throwApiError(submitResp, `poll submit failed (${submitUrl})`);
@@ -9652,9 +9768,7 @@ var BlockrunClient = class {
9652
9768
  body: requestBody
9653
9769
  });
9654
9770
  if (streamResp.status === 402) {
9655
- throw new PaymentError(
9656
- "Payment was rejected. Check your wallet balance."
9657
- );
9771
+ throw await buildPaymentRejectedError(streamResp);
9658
9772
  }
9659
9773
  if (!streamResp.ok) {
9660
9774
  await this.throwApiError(streamResp, `stream failed after payment (${url})`);
@@ -9731,9 +9845,7 @@ var BlockrunClient = class {
9731
9845
  }
9732
9846
  const retry = await this.fetchWithTimeout(url, retryInit);
9733
9847
  if (retry.status === 402) {
9734
- throw new PaymentError(
9735
- "Payment was rejected. Check your wallet balance."
9736
- );
9848
+ throw await buildPaymentRejectedError(retry);
9737
9849
  }
9738
9850
  if (!retry.ok) {
9739
9851
  await this.throwApiError(retry, `${method} ${url} failed after payment`);
@@ -9837,7 +9949,7 @@ function sleep(ms) {
9837
9949
  // src/wallet.ts
9838
9950
  var import_accounts16 = require("viem/accounts");
9839
9951
 
9840
- // node_modules/.pnpm/@blockrun+core@0.1.1_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@6.0.6_zod@3.25.76/node_modules/@blockrun/core/dist/config.js
9952
+ // node_modules/.pnpm/@blockrun+core@0.1.1_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@6.0.6_zod@4.6.7/node_modules/@blockrun/core/dist/config.js
9841
9953
  var fs2 = __toESM(require("fs"), 1);
9842
9954
  var os2 = __toESM(require("os"), 1);
9843
9955
  var path2 = __toESM(require("path"), 1);
@@ -9859,7 +9971,7 @@ function paths() {
9859
9971
  };
9860
9972
  }
9861
9973
 
9862
- // node_modules/.pnpm/@blockrun+core@0.1.1_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@6.0.6_zod@3.25.76/node_modules/@blockrun/core/dist/wallet.js
9974
+ // node_modules/.pnpm/@blockrun+core@0.1.1_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@6.0.6_zod@4.6.7/node_modules/@blockrun/core/dist/wallet.js
9863
9975
  var fs3 = __toESM(require("fs"), 1);
9864
9976
  var path3 = __toESM(require("path"), 1);
9865
9977
  var import_accounts15 = require("viem/accounts");
@@ -10437,7 +10549,7 @@ var BatchChannelLockedError = class extends BlockrunError {
10437
10549
  withDisposition(this, "unpaid");
10438
10550
  }
10439
10551
  };
10440
- var INSTALL_HINT2 = "npm install @x402/core@~2.28.0 @x402/svm@~2.28.0 @solana/kit";
10552
+ var INSTALL_HINT2 = "npm install @x402/core@~2.30.0 @x402/svm@~2.30.0 @solana/kit@^8";
10441
10553
  async function load(pkg, importer) {
10442
10554
  try {
10443
10555
  return await importer();
@@ -13056,18 +13168,23 @@ async function readPaymentFailureBody(response) {
13056
13168
  }
13057
13169
  }
13058
13170
  async function isSafeStaleBlockhashResponse(response) {
13171
+ const body = await readPaymentFailure(response);
13172
+ return body !== null && isSafeStaleBlockhashBody(body);
13173
+ }
13174
+ async function readPaymentFailure(response) {
13059
13175
  const length = Number(response.headers.get("content-length") || "0");
13060
- if (Number.isFinite(length) && length > MAX_PAYMENT_FAILURE_BYTES) return false;
13176
+ if (Number.isFinite(length) && length > MAX_PAYMENT_FAILURE_BYTES) return null;
13061
13177
  const text = await readPaymentFailureBody(response);
13062
- if (text === null) return false;
13063
- let body;
13178
+ if (text === null) return null;
13064
13179
  try {
13065
13180
  const parsed = JSON.parse(text);
13066
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
13067
- body = parsed;
13181
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
13182
+ return parsed;
13068
13183
  } catch {
13069
- return false;
13184
+ return null;
13070
13185
  }
13186
+ }
13187
+ function isSafeStaleBlockhashBody(body) {
13071
13188
  const nested = body.error && typeof body.error === "object" && !Array.isArray(body.error) ? body.error : void 0;
13072
13189
  const errorLabel = typeof body.error === "string" ? body.error : "";
13073
13190
  const code = normalizePaymentSignal(body.code ?? nested?.code);
@@ -14060,6 +14177,9 @@ var SolanaLLMClient = class {
14060
14177
  lastStatus = data.status || lastStatus;
14061
14178
  failIfFailed(data, paid.status);
14062
14179
  if (paid.status === 200 && lastStatus === "completed") return deliver(data, paid);
14180
+ if (paid.status === 402 && isPaymentReplay(data)) {
14181
+ throw withDisposition(paymentRejectedErrorFromBody(data, 402, { replay: true }), "paid-or-in-doubt");
14182
+ }
14063
14183
  if (paid.status === 402 && kind === "video") {
14064
14184
  if (data.error === "Payment verification failed" && !await isSafeStaleBlockhashResponse(new Response(JSON.stringify(data), { status: 402 }))) {
14065
14185
  throw new PaymentError(
@@ -14334,10 +14454,11 @@ var SolanaLLMClient = class {
14334
14454
  */
14335
14455
  async assertPaid(response) {
14336
14456
  if (response.status === 402) {
14337
- if (await isSafeStaleBlockhashResponse(response)) {
14457
+ const body = await readPaymentFailure(response);
14458
+ if (body !== null && isSafeStaleBlockhashBody(body)) {
14338
14459
  throw withDisposition(new SafeStaleBlockhashError(), "unpaid");
14339
14460
  }
14340
- throw withDisposition(new PaymentError("Payment was rejected. Check your Solana USDC balance."), "paid-or-in-doubt");
14461
+ throw withDisposition(paymentRejectedErrorFromBody(body ?? {}, 402), "paid-or-in-doubt");
14341
14462
  }
14342
14463
  if (!response.ok) {
14343
14464
  let errorBody;
@@ -14897,9 +15018,7 @@ var AnthropicClient = class {
14897
15018
  signal: controller.signal
14898
15019
  });
14899
15020
  if (response.status === 402) {
14900
- throw new Error(
14901
- "Payment was rejected. Check your wallet balance."
14902
- );
15021
+ throw await buildPaymentRejectedError(response);
14903
15022
  }
14904
15023
  }
14905
15024
  return response;
@@ -14947,10 +15066,12 @@ var AnthropicClient = class {
14947
15066
  MusicClient,
14948
15067
  NETWORK_ALIASES,
14949
15068
  OpenAI,
15069
+ PAYMENT_REPLAY,
14950
15070
  PHONE_PRICES,
14951
15071
  PORTAL_URL,
14952
15072
  PORTRAIT_ENROLLMENT_PRICE_USD,
14953
15073
  PaymentError,
15074
+ PaymentReplayError,
14954
15075
  PhoneClient,
14955
15076
  PortraitClient,
14956
15077
  PriceClient,
@@ -14973,6 +15094,7 @@ var AnthropicClient = class {
14973
15094
  VoiceClient,
14974
15095
  WALLET_DIR_PATH,
14975
15096
  WALLET_FILE_PATH,
15097
+ buildPaymentRejectedError,
14976
15098
  clearCache,
14977
15099
  createPaymentPayload,
14978
15100
  createSolanaPaymentPayload,
@@ -14996,12 +15118,14 @@ var AnthropicClient = class {
14996
15118
  getWalletAddress,
14997
15119
  importSolanaWallet,
14998
15120
  importWallet,
15121
+ isPaymentReplay,
14999
15122
  listDiscoveredSolanaWallets,
15000
15123
  listDiscoveredWallets,
15001
15124
  loadSolanaWallet,
15002
15125
  loadWallet,
15003
15126
  logCost,
15004
15127
  parsePaymentRequired,
15128
+ paymentRejectedErrorFromBody,
15005
15129
  readSettlement,
15006
15130
  retryDisposition,
15007
15131
  saveSolanaWallet,
package/dist/index.d.cts CHANGED
@@ -985,10 +985,9 @@ interface VideoGenerateOptions {
985
985
  /**
986
986
  * Whether the model should produce a synced audio track. Token360 / Seedance
987
987
  * only — silently ignored by xAI Grok. When omitted, the gateway defaults to
988
- * `true` for text-to-video and `false` for image- or face-conditioned
989
- * generation (the t2v / i2v split that matches Token360's quality profile).
990
- * Pass an explicit boolean to override. Audio generation may be a paid
991
- * surcharge upstream, so callers should expose this as a visible toggle.
988
+ * `true` for every input: text, image-to-video, first/last frame, reference
989
+ * images/video/audio and RealFace. Pass `false` for a silent clip. The price
990
+ * is the same either way.
992
991
  */
993
992
  generateAudio?: boolean;
994
993
  /** Reproducibility seed when supported by the model. */
@@ -1335,7 +1334,60 @@ declare class RetiredEndpointError extends BlockrunError {
1335
1334
  constructor(message: string);
1336
1335
  }
1337
1336
  declare class PaymentError extends BlockrunError {
1338
- constructor(message: string);
1337
+ /** HTTP status of the refusal, when it came from the gateway. */
1338
+ statusCode?: number;
1339
+ /** The gateway's refusal body, sanitized; recovery fields kept verbatim. */
1340
+ response?: Record<string, unknown>;
1341
+ constructor(message: string, options?: {
1342
+ statusCode?: number;
1343
+ response?: Record<string, unknown>;
1344
+ });
1345
+ }
1346
+ /** The gateway's `code` for a payment authorization it has already seen. */
1347
+ declare const PAYMENT_REPLAY: "PAYMENT_REPLAY";
1348
+ /**
1349
+ * The EIP-191 challenge the gateway issues for a settled authorization:
1350
+ * sign `message` with the paying wallet and resend the same request with the
1351
+ * headers named in `headers` (`X-Wallet-Address`, `X-Wallet-Timestamp`,
1352
+ * `X-Wallet-Signature`) to get the earlier request's `poll_url`.
1353
+ */
1354
+ interface WalletAuthChallenge {
1355
+ timestamp: string;
1356
+ message: string;
1357
+ headers: string[];
1358
+ expires_in: number;
1359
+ [key: string]: unknown;
1360
+ }
1361
+ /**
1362
+ * The gateway refused the payment as already used (`code: "PAYMENT_REPLAY"`).
1363
+ *
1364
+ * Not a balance problem. The same signed authorization was already submitted
1365
+ * once (usually a retry or a proxy re-sent it), and that earlier request may
1366
+ * already have been served and charged. The SDK throws this without signing
1367
+ * anything new: a fresh authorization for the same request can be a second
1368
+ * charge.
1369
+ *
1370
+ * Every field the gateway sent is kept verbatim: `serverMessage` / `details`
1371
+ * (its `message` and `details`), `pollUrl` / `jobId` (where the earlier
1372
+ * result can be collected), `walletAuth` (the EIP-191 challenge for a settled
1373
+ * authorization; the SDK does not answer it for you yet) and `payer`.
1374
+ * `response` carries the same fields under the gateway's own key names.
1375
+ * Extends {@link PaymentError}, so existing `instanceof PaymentError` checks
1376
+ * keep working.
1377
+ */
1378
+ declare class PaymentReplayError extends PaymentError {
1379
+ readonly code: "PAYMENT_REPLAY";
1380
+ serverMessage?: string;
1381
+ details?: string;
1382
+ pollUrl?: string;
1383
+ jobId?: string;
1384
+ recoverable?: boolean;
1385
+ walletAuth?: WalletAuthChallenge;
1386
+ payer?: string;
1387
+ constructor(message: string, options?: {
1388
+ statusCode?: number;
1389
+ response?: Record<string, unknown>;
1390
+ });
1339
1391
  }
1340
1392
  declare class APIError extends BlockrunError {
1341
1393
  statusCode: number;
@@ -4544,6 +4596,37 @@ declare function validateTemperature(temperature?: number): void;
4544
4596
  * validateTopP(0.9);
4545
4597
  */
4546
4598
  declare function validateTopP(topP?: number): void;
4599
+ /**
4600
+ * Does this response body say `code: "PAYMENT_REPLAY"`? The gateway sends it
4601
+ * when the signed authorization was already submitted once. The earlier
4602
+ * request may have been served and charged, so the answer is never "sign a new
4603
+ * payment and try again".
4604
+ */
4605
+ declare function isPaymentReplay(body: unknown): boolean;
4606
+ /**
4607
+ * Turn a refused payment's body into the error to throw.
4608
+ *
4609
+ * - `code: "PAYMENT_REPLAY"` (or `replay: true`, for a caller with its own
4610
+ * evidence) gives a {@link PaymentReplayError} carrying the gateway's
4611
+ * `message`, `details`, `poll_url`, `job_id`, `wallet_auth` and `payer`
4612
+ * verbatim. Callers must not answer it by signing again.
4613
+ * - Anything else gives a {@link PaymentError} whose message is the gateway's
4614
+ * reason. Clients used to throw "Payment was rejected. Check your wallet
4615
+ * balance." for every 402, which hid `PAYMENT_MALFORMED`, facilitator
4616
+ * reasons and already-used authorizations behind a balance guess.
4617
+ *
4618
+ * Mirrors the Python SDK's `validation.build_payment_rejected_error`.
4619
+ */
4620
+ declare function paymentRejectedErrorFromBody(body: unknown, statusCode?: number, options?: {
4621
+ replay?: boolean;
4622
+ }): PaymentError;
4623
+ /**
4624
+ * Read a refused payment's response and turn it into the error to throw. See
4625
+ * {@link paymentRejectedErrorFromBody}. Consumes the body.
4626
+ */
4627
+ declare function buildPaymentRejectedError(response: Response, options?: {
4628
+ replay?: (body: unknown) => boolean;
4629
+ }): Promise<PaymentError>;
4547
4630
 
4548
4631
  /**
4549
4632
  * Wire format for xAI search on the BlockRun gateways.
@@ -4591,4 +4674,4 @@ declare function readSettlement(response: Response, quotedUsd: number, scheme: S
4591
4674
  settlement: Settlement;
4592
4675
  };
4593
4676
 
4594
- export { APIError, API_KEY_URL, ARC_CHAIN_ID, AnthropicClient, type AnyTool, type ApiKeyOptions, type AudioModel, type AudioTrack, BASE_CHAIN_ID, BLOCKRUN_SOL_OPERATOR, type BarResolution, type BatchAttempt, BatchChannelLockedError, BatchCloseDeferredError, type BatchPayloadKind, BatchPaymentUnresolvedError, type BatchUnresolvedReason, 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, DEFAULT_BATCH_IN_DOUBT, DEFAULT_BATCH_LOCK_WAIT_MS, DEFAULT_BATCH_RATE_LIMIT, EVM_NETWORKS, type EvmNetwork, 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, PORTAL_URL, 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 ReasoningEffort, type Rechallenge, type ResponseFormat, RetiredEndpointError, type RetryDisposition, type RoutingDecision, type RoutingProfile, type RoutingTaskType, type RoutingTier, type RoutingTierConfig, 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 Settlement, type SmartChatCompletionOptions, type SmartChatCompletionResponse, type SmartChatOptions, type SmartChatResponse, type SolanaBatchEvent, type SolanaBatchOptions, SolanaBatchPayer, type SolanaBatchPayerInit, type SolanaBatchStats, 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_ARC, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, type UrlCitation, 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 WebSearchTool, type X402ClientLike, type X402HookContext, type XSearchSource, type XSearchTool, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, evmNetwork, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatSolanaWalletMigrationNotice, formatWalletCreatedMessage, formatWalletMigrationNotice, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, importSolanaWallet, importWallet, listDiscoveredSolanaWallets, listDiscoveredWallets, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, readSettlement, retryDisposition, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentClient, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, toWireSearchParameters, toWireTools, validateMaxTokens, validateModel, validateTemperature, validateTopP };
4677
+ export { APIError, API_KEY_URL, ARC_CHAIN_ID, AnthropicClient, type AnyTool, type ApiKeyOptions, type AudioModel, type AudioTrack, BASE_CHAIN_ID, BLOCKRUN_SOL_OPERATOR, type BarResolution, type BatchAttempt, BatchChannelLockedError, BatchCloseDeferredError, type BatchPayloadKind, BatchPaymentUnresolvedError, type BatchUnresolvedReason, 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, DEFAULT_BATCH_IN_DOUBT, DEFAULT_BATCH_LOCK_WAIT_MS, DEFAULT_BATCH_RATE_LIMIT, EVM_NETWORKS, type EvmNetwork, 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, PAYMENT_REPLAY, PHONE_PRICES, PORTAL_URL, PORTRAIT_ENROLLMENT_PRICE_USD, PaymentError, type PaymentLinks, PaymentReplayError, 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 ReasoningEffort, type Rechallenge, type ResponseFormat, RetiredEndpointError, type RetryDisposition, type RoutingDecision, type RoutingProfile, type RoutingTaskType, type RoutingTier, type RoutingTierConfig, 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 Settlement, type SmartChatCompletionOptions, type SmartChatCompletionResponse, type SmartChatOptions, type SmartChatResponse, type SolanaBatchEvent, type SolanaBatchOptions, SolanaBatchPayer, type SolanaBatchPayerInit, type SolanaBatchStats, 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_ARC, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, type UrlCitation, 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 WalletAuthChallenge, type WalletInfo, type WebSearchSource, type WebSearchTool, type X402ClientLike, type X402HookContext, type XSearchSource, type XSearchTool, buildPaymentRejectedError, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, evmNetwork, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatSolanaWalletMigrationNotice, formatWalletCreatedMessage, formatWalletMigrationNotice, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, importSolanaWallet, importWallet, isPaymentReplay, listDiscoveredSolanaWallets, listDiscoveredWallets, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, paymentRejectedErrorFromBody, readSettlement, retryDisposition, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentClient, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, toWireSearchParameters, toWireTools, validateMaxTokens, validateModel, validateTemperature, validateTopP };
package/dist/index.d.ts CHANGED
@@ -985,10 +985,9 @@ interface VideoGenerateOptions {
985
985
  /**
986
986
  * Whether the model should produce a synced audio track. Token360 / Seedance
987
987
  * only — silently ignored by xAI Grok. When omitted, the gateway defaults to
988
- * `true` for text-to-video and `false` for image- or face-conditioned
989
- * generation (the t2v / i2v split that matches Token360's quality profile).
990
- * Pass an explicit boolean to override. Audio generation may be a paid
991
- * surcharge upstream, so callers should expose this as a visible toggle.
988
+ * `true` for every input: text, image-to-video, first/last frame, reference
989
+ * images/video/audio and RealFace. Pass `false` for a silent clip. The price
990
+ * is the same either way.
992
991
  */
993
992
  generateAudio?: boolean;
994
993
  /** Reproducibility seed when supported by the model. */
@@ -1335,7 +1334,60 @@ declare class RetiredEndpointError extends BlockrunError {
1335
1334
  constructor(message: string);
1336
1335
  }
1337
1336
  declare class PaymentError extends BlockrunError {
1338
- constructor(message: string);
1337
+ /** HTTP status of the refusal, when it came from the gateway. */
1338
+ statusCode?: number;
1339
+ /** The gateway's refusal body, sanitized; recovery fields kept verbatim. */
1340
+ response?: Record<string, unknown>;
1341
+ constructor(message: string, options?: {
1342
+ statusCode?: number;
1343
+ response?: Record<string, unknown>;
1344
+ });
1345
+ }
1346
+ /** The gateway's `code` for a payment authorization it has already seen. */
1347
+ declare const PAYMENT_REPLAY: "PAYMENT_REPLAY";
1348
+ /**
1349
+ * The EIP-191 challenge the gateway issues for a settled authorization:
1350
+ * sign `message` with the paying wallet and resend the same request with the
1351
+ * headers named in `headers` (`X-Wallet-Address`, `X-Wallet-Timestamp`,
1352
+ * `X-Wallet-Signature`) to get the earlier request's `poll_url`.
1353
+ */
1354
+ interface WalletAuthChallenge {
1355
+ timestamp: string;
1356
+ message: string;
1357
+ headers: string[];
1358
+ expires_in: number;
1359
+ [key: string]: unknown;
1360
+ }
1361
+ /**
1362
+ * The gateway refused the payment as already used (`code: "PAYMENT_REPLAY"`).
1363
+ *
1364
+ * Not a balance problem. The same signed authorization was already submitted
1365
+ * once (usually a retry or a proxy re-sent it), and that earlier request may
1366
+ * already have been served and charged. The SDK throws this without signing
1367
+ * anything new: a fresh authorization for the same request can be a second
1368
+ * charge.
1369
+ *
1370
+ * Every field the gateway sent is kept verbatim: `serverMessage` / `details`
1371
+ * (its `message` and `details`), `pollUrl` / `jobId` (where the earlier
1372
+ * result can be collected), `walletAuth` (the EIP-191 challenge for a settled
1373
+ * authorization; the SDK does not answer it for you yet) and `payer`.
1374
+ * `response` carries the same fields under the gateway's own key names.
1375
+ * Extends {@link PaymentError}, so existing `instanceof PaymentError` checks
1376
+ * keep working.
1377
+ */
1378
+ declare class PaymentReplayError extends PaymentError {
1379
+ readonly code: "PAYMENT_REPLAY";
1380
+ serverMessage?: string;
1381
+ details?: string;
1382
+ pollUrl?: string;
1383
+ jobId?: string;
1384
+ recoverable?: boolean;
1385
+ walletAuth?: WalletAuthChallenge;
1386
+ payer?: string;
1387
+ constructor(message: string, options?: {
1388
+ statusCode?: number;
1389
+ response?: Record<string, unknown>;
1390
+ });
1339
1391
  }
1340
1392
  declare class APIError extends BlockrunError {
1341
1393
  statusCode: number;
@@ -4544,6 +4596,37 @@ declare function validateTemperature(temperature?: number): void;
4544
4596
  * validateTopP(0.9);
4545
4597
  */
4546
4598
  declare function validateTopP(topP?: number): void;
4599
+ /**
4600
+ * Does this response body say `code: "PAYMENT_REPLAY"`? The gateway sends it
4601
+ * when the signed authorization was already submitted once. The earlier
4602
+ * request may have been served and charged, so the answer is never "sign a new
4603
+ * payment and try again".
4604
+ */
4605
+ declare function isPaymentReplay(body: unknown): boolean;
4606
+ /**
4607
+ * Turn a refused payment's body into the error to throw.
4608
+ *
4609
+ * - `code: "PAYMENT_REPLAY"` (or `replay: true`, for a caller with its own
4610
+ * evidence) gives a {@link PaymentReplayError} carrying the gateway's
4611
+ * `message`, `details`, `poll_url`, `job_id`, `wallet_auth` and `payer`
4612
+ * verbatim. Callers must not answer it by signing again.
4613
+ * - Anything else gives a {@link PaymentError} whose message is the gateway's
4614
+ * reason. Clients used to throw "Payment was rejected. Check your wallet
4615
+ * balance." for every 402, which hid `PAYMENT_MALFORMED`, facilitator
4616
+ * reasons and already-used authorizations behind a balance guess.
4617
+ *
4618
+ * Mirrors the Python SDK's `validation.build_payment_rejected_error`.
4619
+ */
4620
+ declare function paymentRejectedErrorFromBody(body: unknown, statusCode?: number, options?: {
4621
+ replay?: boolean;
4622
+ }): PaymentError;
4623
+ /**
4624
+ * Read a refused payment's response and turn it into the error to throw. See
4625
+ * {@link paymentRejectedErrorFromBody}. Consumes the body.
4626
+ */
4627
+ declare function buildPaymentRejectedError(response: Response, options?: {
4628
+ replay?: (body: unknown) => boolean;
4629
+ }): Promise<PaymentError>;
4547
4630
 
4548
4631
  /**
4549
4632
  * Wire format for xAI search on the BlockRun gateways.
@@ -4591,4 +4674,4 @@ declare function readSettlement(response: Response, quotedUsd: number, scheme: S
4591
4674
  settlement: Settlement;
4592
4675
  };
4593
4676
 
4594
- export { APIError, API_KEY_URL, ARC_CHAIN_ID, AnthropicClient, type AnyTool, type ApiKeyOptions, type AudioModel, type AudioTrack, BASE_CHAIN_ID, BLOCKRUN_SOL_OPERATOR, type BarResolution, type BatchAttempt, BatchChannelLockedError, BatchCloseDeferredError, type BatchPayloadKind, BatchPaymentUnresolvedError, type BatchUnresolvedReason, 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, DEFAULT_BATCH_IN_DOUBT, DEFAULT_BATCH_LOCK_WAIT_MS, DEFAULT_BATCH_RATE_LIMIT, EVM_NETWORKS, type EvmNetwork, 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, PORTAL_URL, 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 ReasoningEffort, type Rechallenge, type ResponseFormat, RetiredEndpointError, type RetryDisposition, type RoutingDecision, type RoutingProfile, type RoutingTaskType, type RoutingTier, type RoutingTierConfig, 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 Settlement, type SmartChatCompletionOptions, type SmartChatCompletionResponse, type SmartChatOptions, type SmartChatResponse, type SolanaBatchEvent, type SolanaBatchOptions, SolanaBatchPayer, type SolanaBatchPayerInit, type SolanaBatchStats, 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_ARC, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, type UrlCitation, 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 WebSearchTool, type X402ClientLike, type X402HookContext, type XSearchSource, type XSearchTool, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, evmNetwork, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatSolanaWalletMigrationNotice, formatWalletCreatedMessage, formatWalletMigrationNotice, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, importSolanaWallet, importWallet, listDiscoveredSolanaWallets, listDiscoveredWallets, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, readSettlement, retryDisposition, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentClient, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, toWireSearchParameters, toWireTools, validateMaxTokens, validateModel, validateTemperature, validateTopP };
4677
+ export { APIError, API_KEY_URL, ARC_CHAIN_ID, AnthropicClient, type AnyTool, type ApiKeyOptions, type AudioModel, type AudioTrack, BASE_CHAIN_ID, BLOCKRUN_SOL_OPERATOR, type BarResolution, type BatchAttempt, BatchChannelLockedError, BatchCloseDeferredError, type BatchPayloadKind, BatchPaymentUnresolvedError, type BatchUnresolvedReason, 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, DEFAULT_BATCH_IN_DOUBT, DEFAULT_BATCH_LOCK_WAIT_MS, DEFAULT_BATCH_RATE_LIMIT, EVM_NETWORKS, type EvmNetwork, 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, PAYMENT_REPLAY, PHONE_PRICES, PORTAL_URL, PORTRAIT_ENROLLMENT_PRICE_USD, PaymentError, type PaymentLinks, PaymentReplayError, 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 ReasoningEffort, type Rechallenge, type ResponseFormat, RetiredEndpointError, type RetryDisposition, type RoutingDecision, type RoutingProfile, type RoutingTaskType, type RoutingTier, type RoutingTierConfig, 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 Settlement, type SmartChatCompletionOptions, type SmartChatCompletionResponse, type SmartChatOptions, type SmartChatResponse, type SolanaBatchEvent, type SolanaBatchOptions, SolanaBatchPayer, type SolanaBatchPayerInit, type SolanaBatchStats, 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_ARC, USDC_BASE, USDC_BASE_CONTRACT, USDC_SOLANA, type UrlCitation, 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 WalletAuthChallenge, type WalletInfo, type WebSearchSource, type WebSearchTool, type X402ClientLike, type X402HookContext, type XSearchSource, type XSearchTool, buildPaymentRejectedError, clearCache, createPaymentPayload, createSolanaPaymentPayload, createSolanaWallet, createWallet, LLMClient as default, evmNetwork, extractPaymentDetails, formatFundingMessageCompact, formatNeedsFundingMessage, formatSolanaWalletMigrationNotice, formatWalletCreatedMessage, formatWalletMigrationNotice, getCached, getCachedByRequest, getCostLogSummary, getCostSummary, getEip681Uri, getOrCreateSolanaWallet, getOrCreateWallet, getPaymentLinks, getWalletAddress, importSolanaWallet, importWallet, isPaymentReplay, listDiscoveredSolanaWallets, listDiscoveredWallets, loadSolanaWallet, loadWallet, logCost, parsePaymentRequired, paymentRejectedErrorFromBody, readSettlement, retryDisposition, saveSolanaWallet, saveToCache, saveWallet, scanSolanaWallets, scanWallets, setCache, setupAgentClient, setupAgentSolanaWallet, setupAgentWallet, solanaClient, solanaKeyToBytes, solanaPublicKey, status, toWireSearchParameters, toWireTools, validateMaxTokens, validateModel, validateTemperature, validateTopP };
package/dist/index.js CHANGED
@@ -27,9 +27,42 @@ var RetiredEndpointError = class extends BlockrunError {
27
27
  }
28
28
  };
29
29
  var PaymentError = class extends BlockrunError {
30
- constructor(message) {
30
+ /** HTTP status of the refusal, when it came from the gateway. */
31
+ statusCode;
32
+ /** The gateway's refusal body, sanitized; recovery fields kept verbatim. */
33
+ response;
34
+ constructor(message, options) {
31
35
  super(message);
32
36
  this.name = "PaymentError";
37
+ if (options?.statusCode !== void 0) this.statusCode = options.statusCode;
38
+ if (options?.response !== void 0) this.response = options.response;
39
+ }
40
+ };
41
+ var PAYMENT_REPLAY = "PAYMENT_REPLAY";
42
+ var PaymentReplayError = class extends PaymentError {
43
+ code = PAYMENT_REPLAY;
44
+ serverMessage;
45
+ details;
46
+ pollUrl;
47
+ jobId;
48
+ recoverable;
49
+ walletAuth;
50
+ payer;
51
+ constructor(message, options) {
52
+ super(message, options);
53
+ this.name = "PaymentReplayError";
54
+ const body = options?.response ?? {};
55
+ const str = (v) => typeof v === "string" && v ? v : void 0;
56
+ this.serverMessage = str(body.message);
57
+ this.details = str(body.details);
58
+ this.pollUrl = str(body.poll_url);
59
+ this.jobId = str(body.job_id) ?? str(body.id);
60
+ if (typeof body.recoverable === "boolean") this.recoverable = body.recoverable;
61
+ const walletAuth = body.wallet_auth;
62
+ if (walletAuth && typeof walletAuth === "object" && !Array.isArray(walletAuth)) {
63
+ this.walletAuth = walletAuth;
64
+ }
65
+ this.payer = str(body.payer);
33
66
  }
34
67
  };
35
68
  var APIError = class extends BlockrunError {
@@ -186,6 +219,83 @@ function validateResourceUrl(url, baseUrl) {
186
219
  return `${baseUrl}/v1/chat/completions`;
187
220
  }
188
221
  }
222
+ var REPLAY_FIELDS = [
223
+ "error",
224
+ "message",
225
+ "details",
226
+ "code",
227
+ "payer",
228
+ "id",
229
+ "job_id",
230
+ "poll_url",
231
+ "recoverable",
232
+ "wallet_auth",
233
+ "status"
234
+ ];
235
+ function asRecord(body) {
236
+ return body && typeof body === "object" && !Array.isArray(body) ? body : {};
237
+ }
238
+ function bodyCode(body) {
239
+ if (typeof body.code === "string") return body.code;
240
+ const nested = asRecord(body.error);
241
+ return typeof nested.code === "string" ? nested.code : void 0;
242
+ }
243
+ function isPaymentReplay(body) {
244
+ return bodyCode(asRecord(body))?.toUpperCase() === PAYMENT_REPLAY;
245
+ }
246
+ function namesEarlierResult(body) {
247
+ const record = asRecord(body);
248
+ return ["recoverable", "poll_url", "job_id", "wallet_auth"].some((key) => Boolean(record[key]));
249
+ }
250
+ function boundedString(value, max) {
251
+ return typeof value === "string" && value.length > 0 && value.length < max ? value : void 0;
252
+ }
253
+ function replayError(body, statusCode) {
254
+ const detail = {};
255
+ for (const key of REPLAY_FIELDS) if (body[key] !== void 0 && body[key] !== null) detail[key] = body[key];
256
+ detail.code = PAYMENT_REPLAY;
257
+ for (const field of PAYMENT_FACT_FIELDS) if (typeof body[field] === "string") detail[field] = body[field];
258
+ const serverMessage = typeof body.message === "string" ? body.message : "";
259
+ const pollUrl = typeof body.poll_url === "string" ? body.poll_url : "";
260
+ const details = typeof body.details === "string" ? body.details : "";
261
+ let text = "Payment authorization already used (PAYMENT_REPLAY): an earlier request with this authorization was accepted and may already have been charged. Nothing new was signed; a fresh payment for the same request can charge twice.";
262
+ if (pollUrl) text += ` Its result can be collected at ${pollUrl}.`;
263
+ if (serverMessage) text += ` Gateway: ${serverMessage}`;
264
+ if (details && details !== serverMessage) text += ` (${details})`;
265
+ return new PaymentReplayError(text, { statusCode, response: detail });
266
+ }
267
+ function paymentRejectedErrorFromBody(body, statusCode = 402, options = {}) {
268
+ const record = asRecord(body);
269
+ if (options.replay ?? isPaymentReplay(record)) return replayError(record, statusCode);
270
+ const sanitized = { ...sanitizeErrorResponse(record) };
271
+ const details = boundedString(record.details, 256);
272
+ if (details) sanitized.details = details;
273
+ const invalidMessage = boundedString(record.invalidMessage, 256);
274
+ if (invalidMessage) sanitized.invalidMessage = invalidMessage;
275
+ const reason = boundedString(record.reason, 128);
276
+ if (reason) sanitized.reason = reason;
277
+ const nested = asRecord(record.error);
278
+ const title = typeof record.error === "string" ? record.error : typeof nested.message === "string" ? nested.message : "";
279
+ const serverMessage = typeof record.message === "string" ? record.message : "";
280
+ let detailPart = details || title;
281
+ if (!details && serverMessage && serverMessage !== detailPart) {
282
+ detailPart = detailPart ? `${detailPart}: ${serverMessage}` : serverMessage;
283
+ }
284
+ if (invalidMessage) detailPart = detailPart ? `${detailPart} (${invalidMessage})` : invalidMessage;
285
+ const message = detailPart ? `Payment rejected by gateway: ${detailPart}` : `Payment rejected by gateway (HTTP ${statusCode}); it gave no reason`;
286
+ return new PaymentError(message, { statusCode, response: sanitized });
287
+ }
288
+ async function buildPaymentRejectedError(response, options = {}) {
289
+ let body;
290
+ try {
291
+ const text = await response.text();
292
+ body = text ? JSON.parse(text) : {};
293
+ } catch {
294
+ body = {};
295
+ }
296
+ const replay = options.replay ? options.replay(body) || void 0 : void 0;
297
+ return paymentRejectedErrorFromBody(body, response.status, { replay });
298
+ }
189
299
 
190
300
  // src/api-key.ts
191
301
  var TRANSIENT_STATUS = /* @__PURE__ */ new Set([502, 503, 504, 522, 524]);
@@ -5069,7 +5179,7 @@ function getCostSummary() {
5069
5179
  }
5070
5180
 
5071
5181
  // src/version.ts
5072
- var SDK_VERSION = "3.26.5";
5182
+ var SDK_VERSION = "4.1.0";
5073
5183
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
5074
5184
 
5075
5185
  // src/client.ts
@@ -5637,7 +5747,7 @@ var LLMClient = class _LLMClient {
5637
5747
  body: JSON.stringify(body)
5638
5748
  }, timeoutMs);
5639
5749
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
5640
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
5750
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
5641
5751
  if (!retryResp2.ok) {
5642
5752
  let errorBody;
5643
5753
  try {
@@ -5651,7 +5761,7 @@ var LLMClient = class _LLMClient {
5651
5761
  }
5652
5762
  }
5653
5763
  if (retryResponse.status === 402) {
5654
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
5764
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
5655
5765
  }
5656
5766
  if (!retryResponse.ok) {
5657
5767
  let errorBody;
@@ -5857,7 +5967,7 @@ var LLMClient = class _LLMClient {
5857
5967
  },
5858
5968
  body: JSON.stringify(body)
5859
5969
  });
5860
- if (streamResp.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
5970
+ if (streamResp.status === 402) throw await buildPaymentRejectedError(streamResp, { replay: namesEarlierResult });
5861
5971
  if (!streamResp.ok) {
5862
5972
  let errorBody;
5863
5973
  try {
@@ -5984,7 +6094,7 @@ var LLMClient = class _LLMClient {
5984
6094
  body: JSON.stringify(body)
5985
6095
  });
5986
6096
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
5987
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
6097
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
5988
6098
  if (!retryResp2.ok) {
5989
6099
  let errorBody;
5990
6100
  try {
@@ -5999,7 +6109,7 @@ var LLMClient = class _LLMClient {
5999
6109
  }
6000
6110
  }
6001
6111
  if (retryResponse.status === 402) {
6002
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
6112
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
6003
6113
  }
6004
6114
  if (!retryResponse.ok) {
6005
6115
  let errorBody;
@@ -6124,7 +6234,7 @@ var LLMClient = class _LLMClient {
6124
6234
  }
6125
6235
  });
6126
6236
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
6127
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
6237
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
6128
6238
  if (!retryResp2.ok) {
6129
6239
  let errorBody;
6130
6240
  try {
@@ -6139,7 +6249,7 @@ var LLMClient = class _LLMClient {
6139
6249
  }
6140
6250
  }
6141
6251
  if (retryResponse.status === 402) {
6142
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
6252
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
6143
6253
  }
6144
6254
  if (!retryResponse.ok) {
6145
6255
  let errorBody;
@@ -6904,9 +7014,7 @@ var ImageClient = class {
6904
7014
  body: JSON.stringify(body)
6905
7015
  });
6906
7016
  if (retryResponse.status === 402) {
6907
- throw new PaymentError(
6908
- "Payment was rejected. Check your wallet balance."
6909
- );
7017
+ throw await buildPaymentRejectedError(retryResponse);
6910
7018
  }
6911
7019
  if (!retryResponse.ok) {
6912
7020
  let errorBody;
@@ -6959,6 +7067,7 @@ var ImageClient = class {
6959
7067
  continue;
6960
7068
  }
6961
7069
  const pollBody = await pollResp.json().catch(() => ({}));
7070
+ if (pollResp.status === 402) throw paymentRejectedErrorFromBody(pollBody, 402);
6962
7071
  if (!pollResp.ok) {
6963
7072
  throw new APIError(
6964
7073
  `API error during poll: ${pollResp.status}`,
@@ -7158,7 +7267,7 @@ var MusicClient = class {
7158
7267
  body: JSON.stringify(body)
7159
7268
  });
7160
7269
  if (retryResponse.status === 402) {
7161
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7270
+ throw await buildPaymentRejectedError(retryResponse);
7162
7271
  }
7163
7272
  if (!retryResponse.ok) {
7164
7273
  let errorBody;
@@ -7217,6 +7326,7 @@ var MusicClient = class {
7217
7326
  }
7218
7327
  if (pollResp.status === 202 || TRANSIENT_POLL_STATUSES.has(pollResp.status)) continue;
7219
7328
  const pollBody = await pollResp.json().catch(() => ({}));
7329
+ if (pollResp.status === 402) throw paymentRejectedErrorFromBody(pollBody, 402);
7220
7330
  if (!pollResp.ok) {
7221
7331
  throw new APIError(
7222
7332
  `API error during poll of ${pollPath}: ${pollResp.status}`,
@@ -7437,7 +7547,7 @@ var SpeechClient = class {
7437
7547
  body: JSON.stringify(body)
7438
7548
  });
7439
7549
  if (retryResponse.status === 402) {
7440
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7550
+ throw await buildPaymentRejectedError(retryResponse);
7441
7551
  }
7442
7552
  if (!retryResponse.ok) {
7443
7553
  let errorBody;
@@ -7709,7 +7819,7 @@ var VideoClient = class {
7709
7819
  body: JSON.stringify(body)
7710
7820
  });
7711
7821
  if (submitResp.status === 402) {
7712
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7822
+ throw await buildPaymentRejectedError(submitResp);
7713
7823
  }
7714
7824
  if (submitResp.status !== 200 && submitResp.status !== 202) {
7715
7825
  await this.throwApiError(submitResp, "Submit failed");
@@ -7759,6 +7869,9 @@ var VideoClient = class {
7759
7869
  return data;
7760
7870
  }
7761
7871
  if (pollResp.status === 402) {
7872
+ if (isPaymentReplay(pollData)) {
7873
+ throw paymentRejectedErrorFromBody(pollData, pollResp.status, { replay: true });
7874
+ }
7762
7875
  if (resignsLeft > 0) {
7763
7876
  resignsLeft--;
7764
7877
  const challenge = await this.fetchWithTimeout(pollUrl, { method: "GET" });
@@ -7770,9 +7883,7 @@ var VideoClient = class {
7770
7883
  continue;
7771
7884
  }
7772
7885
  }
7773
- throw new PaymentError(
7774
- "Payment verification failed mid-poll (not a signature-expiry). Check the wallet balance and that you poll from the wallet that submitted the job."
7775
- );
7886
+ throw paymentRejectedErrorFromBody(pollData, pollResp.status);
7776
7887
  }
7777
7888
  if (pollResp.status !== 200 && pollResp.status !== 202 && pollResp.status !== 504) {
7778
7889
  await this.throwApiError(pollResp, "Poll failed");
@@ -8036,7 +8147,7 @@ var VoiceClient = class {
8036
8147
  body: JSON.stringify(body)
8037
8148
  });
8038
8149
  if (retryResponse.status === 402) {
8039
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8150
+ throw await buildPaymentRejectedError(retryResponse);
8040
8151
  }
8041
8152
  if (!retryResponse.ok) {
8042
8153
  let errorBody;
@@ -8268,7 +8379,7 @@ var PhoneClient = class {
8268
8379
  body: JSON.stringify(body)
8269
8380
  });
8270
8381
  if (retry.status === 402) {
8271
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8382
+ throw await buildPaymentRejectedError(retry);
8272
8383
  }
8273
8384
  const data = await this.unwrap(retry, true);
8274
8385
  if (!settlementSkipped(retry)) {
@@ -8436,7 +8547,7 @@ var PortraitClient = class {
8436
8547
  body: JSON.stringify(body)
8437
8548
  });
8438
8549
  if (retry.status === 402) {
8439
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8550
+ throw await buildPaymentRejectedError(retry);
8440
8551
  }
8441
8552
  const data = await this.unwrap(retry, true);
8442
8553
  if (!settlementSkipped(retry)) {
@@ -8598,7 +8709,7 @@ var SearchClient = class {
8598
8709
  body: JSON.stringify(body)
8599
8710
  });
8600
8711
  if (retry.status === 402) {
8601
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8712
+ throw await buildPaymentRejectedError(retry);
8602
8713
  }
8603
8714
  if (!retry.ok) {
8604
8715
  let errorBody;
@@ -8789,7 +8900,7 @@ var PriceClient = class {
8789
8900
  headers: { "PAYMENT-SIGNATURE": paymentPayload }
8790
8901
  });
8791
8902
  if (retry.status === 402) {
8792
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8903
+ throw await buildPaymentRejectedError(retry);
8793
8904
  }
8794
8905
  if (!retry.ok) {
8795
8906
  let errorBody;
@@ -8980,7 +9091,7 @@ var SurfClient = class {
8980
9091
  }
8981
9092
  const retry = await this.fetchWithTimeout(url, retryInit);
8982
9093
  if (retry.status === 402) {
8983
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9094
+ throw await buildPaymentRejectedError(retry);
8984
9095
  }
8985
9096
  if (!retry.ok) {
8986
9097
  await this.throwApiError(retry, `Surf request failed after payment (${method} ${url})`);
@@ -9248,7 +9359,7 @@ var RpcClient = class {
9248
9359
  body: JSON.stringify(body)
9249
9360
  });
9250
9361
  if (retryResponse.status === 402) {
9251
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9362
+ throw await buildPaymentRejectedError(retryResponse);
9252
9363
  }
9253
9364
  if (!retryResponse.ok) {
9254
9365
  let errorBody;
@@ -9423,7 +9534,7 @@ var BlockrunClient = class {
9423
9534
  body: JSON.stringify(body ?? {})
9424
9535
  });
9425
9536
  if (submitResp.status === 402) {
9426
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9537
+ throw await buildPaymentRejectedError(submitResp);
9427
9538
  }
9428
9539
  if (submitResp.status !== 200 && submitResp.status !== 202) {
9429
9540
  await this.throwApiError(submitResp, `poll submit failed (${submitUrl})`);
@@ -9519,9 +9630,7 @@ var BlockrunClient = class {
9519
9630
  body: requestBody
9520
9631
  });
9521
9632
  if (streamResp.status === 402) {
9522
- throw new PaymentError(
9523
- "Payment was rejected. Check your wallet balance."
9524
- );
9633
+ throw await buildPaymentRejectedError(streamResp);
9525
9634
  }
9526
9635
  if (!streamResp.ok) {
9527
9636
  await this.throwApiError(streamResp, `stream failed after payment (${url})`);
@@ -9598,9 +9707,7 @@ var BlockrunClient = class {
9598
9707
  }
9599
9708
  const retry = await this.fetchWithTimeout(url, retryInit);
9600
9709
  if (retry.status === 402) {
9601
- throw new PaymentError(
9602
- "Payment was rejected. Check your wallet balance."
9603
- );
9710
+ throw await buildPaymentRejectedError(retry);
9604
9711
  }
9605
9712
  if (!retry.ok) {
9606
9713
  await this.throwApiError(retry, `${method} ${url} failed after payment`);
@@ -9704,7 +9811,7 @@ function sleep(ms) {
9704
9811
  // src/wallet.ts
9705
9812
  import { privateKeyToAccount as privateKeyToAccount15, generatePrivateKey as generatePrivateKey2 } from "viem/accounts";
9706
9813
 
9707
- // node_modules/.pnpm/@blockrun+core@0.1.1_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@6.0.6_zod@3.25.76/node_modules/@blockrun/core/dist/config.js
9814
+ // node_modules/.pnpm/@blockrun+core@0.1.1_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@6.0.6_zod@4.6.7/node_modules/@blockrun/core/dist/config.js
9708
9815
  import * as fs2 from "fs";
9709
9816
  import * as os2 from "os";
9710
9817
  import * as path2 from "path";
@@ -9726,7 +9833,7 @@ function paths() {
9726
9833
  };
9727
9834
  }
9728
9835
 
9729
- // node_modules/.pnpm/@blockrun+core@0.1.1_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@6.0.6_zod@3.25.76/node_modules/@blockrun/core/dist/wallet.js
9836
+ // node_modules/.pnpm/@blockrun+core@0.1.1_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@6.0.6_zod@4.6.7/node_modules/@blockrun/core/dist/wallet.js
9730
9837
  import * as fs3 from "fs";
9731
9838
  import * as path3 from "path";
9732
9839
  import { privateKeyToAccount as privateKeyToAccount14, generatePrivateKey } from "viem/accounts";
@@ -10304,7 +10411,7 @@ var BatchChannelLockedError = class extends BlockrunError {
10304
10411
  withDisposition(this, "unpaid");
10305
10412
  }
10306
10413
  };
10307
- var INSTALL_HINT2 = "npm install @x402/core@~2.28.0 @x402/svm@~2.28.0 @solana/kit";
10414
+ var INSTALL_HINT2 = "npm install @x402/core@~2.30.0 @x402/svm@~2.30.0 @solana/kit@^8";
10308
10415
  async function load(pkg, importer) {
10309
10416
  try {
10310
10417
  return await importer();
@@ -12923,18 +13030,23 @@ async function readPaymentFailureBody(response) {
12923
13030
  }
12924
13031
  }
12925
13032
  async function isSafeStaleBlockhashResponse(response) {
13033
+ const body = await readPaymentFailure(response);
13034
+ return body !== null && isSafeStaleBlockhashBody(body);
13035
+ }
13036
+ async function readPaymentFailure(response) {
12926
13037
  const length = Number(response.headers.get("content-length") || "0");
12927
- if (Number.isFinite(length) && length > MAX_PAYMENT_FAILURE_BYTES) return false;
13038
+ if (Number.isFinite(length) && length > MAX_PAYMENT_FAILURE_BYTES) return null;
12928
13039
  const text = await readPaymentFailureBody(response);
12929
- if (text === null) return false;
12930
- let body;
13040
+ if (text === null) return null;
12931
13041
  try {
12932
13042
  const parsed = JSON.parse(text);
12933
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
12934
- body = parsed;
13043
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
13044
+ return parsed;
12935
13045
  } catch {
12936
- return false;
13046
+ return null;
12937
13047
  }
13048
+ }
13049
+ function isSafeStaleBlockhashBody(body) {
12938
13050
  const nested = body.error && typeof body.error === "object" && !Array.isArray(body.error) ? body.error : void 0;
12939
13051
  const errorLabel = typeof body.error === "string" ? body.error : "";
12940
13052
  const code = normalizePaymentSignal(body.code ?? nested?.code);
@@ -13927,6 +14039,9 @@ var SolanaLLMClient = class {
13927
14039
  lastStatus = data.status || lastStatus;
13928
14040
  failIfFailed(data, paid.status);
13929
14041
  if (paid.status === 200 && lastStatus === "completed") return deliver(data, paid);
14042
+ if (paid.status === 402 && isPaymentReplay(data)) {
14043
+ throw withDisposition(paymentRejectedErrorFromBody(data, 402, { replay: true }), "paid-or-in-doubt");
14044
+ }
13930
14045
  if (paid.status === 402 && kind === "video") {
13931
14046
  if (data.error === "Payment verification failed" && !await isSafeStaleBlockhashResponse(new Response(JSON.stringify(data), { status: 402 }))) {
13932
14047
  throw new PaymentError(
@@ -14201,10 +14316,11 @@ var SolanaLLMClient = class {
14201
14316
  */
14202
14317
  async assertPaid(response) {
14203
14318
  if (response.status === 402) {
14204
- if (await isSafeStaleBlockhashResponse(response)) {
14319
+ const body = await readPaymentFailure(response);
14320
+ if (body !== null && isSafeStaleBlockhashBody(body)) {
14205
14321
  throw withDisposition(new SafeStaleBlockhashError(), "unpaid");
14206
14322
  }
14207
- throw withDisposition(new PaymentError("Payment was rejected. Check your Solana USDC balance."), "paid-or-in-doubt");
14323
+ throw withDisposition(paymentRejectedErrorFromBody(body ?? {}, 402), "paid-or-in-doubt");
14208
14324
  }
14209
14325
  if (!response.ok) {
14210
14326
  let errorBody;
@@ -14764,9 +14880,7 @@ var AnthropicClient = class {
14764
14880
  signal: controller.signal
14765
14881
  });
14766
14882
  if (response.status === 402) {
14767
- throw new Error(
14768
- "Payment was rejected. Check your wallet balance."
14769
- );
14883
+ throw await buildPaymentRejectedError(response);
14770
14884
  }
14771
14885
  }
14772
14886
  return response;
@@ -14813,10 +14927,12 @@ export {
14813
14927
  MusicClient,
14814
14928
  NETWORK_ALIASES,
14815
14929
  OpenAI,
14930
+ PAYMENT_REPLAY,
14816
14931
  PHONE_PRICES,
14817
14932
  PORTAL_URL,
14818
14933
  PORTRAIT_ENROLLMENT_PRICE_USD,
14819
14934
  PaymentError,
14935
+ PaymentReplayError,
14820
14936
  PhoneClient,
14821
14937
  PortraitClient,
14822
14938
  PriceClient,
@@ -14839,6 +14955,7 @@ export {
14839
14955
  VoiceClient,
14840
14956
  WALLET_DIR_PATH,
14841
14957
  WALLET_FILE_PATH,
14958
+ buildPaymentRejectedError,
14842
14959
  clearCache,
14843
14960
  createPaymentPayload,
14844
14961
  createSolanaPaymentPayload,
@@ -14863,12 +14980,14 @@ export {
14863
14980
  getWalletAddress,
14864
14981
  importSolanaWallet,
14865
14982
  importWallet,
14983
+ isPaymentReplay,
14866
14984
  listDiscoveredSolanaWallets,
14867
14985
  listDiscoveredWallets2 as listDiscoveredWallets,
14868
14986
  loadSolanaWallet,
14869
14987
  loadWallet,
14870
14988
  logCost,
14871
14989
  parsePaymentRequired,
14990
+ paymentRejectedErrorFromBody,
14872
14991
  readSettlement,
14873
14992
  retryDisposition,
14874
14993
  saveSolanaWallet,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/llm",
3
- "version": "3.26.5",
3
+ "version": "4.1.0",
4
4
  "type": "module",
5
5
  "description": "TypeScript SDK for BlockRun - every frontier model behind one OpenAI-compatible client. Pay with a BlockRun API key or per-call in USDC. Smart routing picks the cheapest capable model. No rate limits.",
6
6
  "main": "dist/index.cjs",
@@ -60,10 +60,10 @@
60
60
  "@blockrun/core": "^0.1.0",
61
61
  "@blockrun/router-core": "https://codeload.github.com/BlockRunAI/router-core/tar.gz/273c2af0a9abe70212efbad7117b72eb3038cffc",
62
62
  "@eslint/js": "^10.0.1",
63
- "@solana/kit": "^5.5.1",
63
+ "@solana/kit": "^8.4.0",
64
64
  "@types/node": "^26.4.1",
65
- "@x402/core": "2.28.0",
66
- "@x402/svm": "2.28.0",
65
+ "@x402/core": "2.30.0",
66
+ "@x402/svm": "2.30.0",
67
67
  "eslint": "^10.9.1",
68
68
  "tsup": "^8.5.1",
69
69
  "typescript": "^6.0.3",
@@ -84,11 +84,11 @@
84
84
  },
85
85
  "packageManager": "pnpm@9.15.4",
86
86
  "peerDependencies": {
87
- "@solana/kit": ">=5.1.0",
87
+ "@solana/kit": ">=8.0.0",
88
88
  "@solana/spl-token": "^0.4.15",
89
89
  "@solana/web3.js": "^1.98.4",
90
- "@x402/core": "~2.28.0",
91
- "@x402/svm": "~2.28.0"
90
+ "@x402/core": "~2.30.0",
91
+ "@x402/svm": "~2.30.0"
92
92
  },
93
93
  "peerDependenciesMeta": {
94
94
  "@solana/kit": {