@blockrun/llm 3.18.0 → 3.19.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 +59 -1
- package/dist/index.cjs +475 -90
- package/dist/index.d.cts +47 -1
- package/dist/index.d.ts +47 -1
- package/dist/index.js +478 -93
- package/package.json +19 -4
package/dist/index.js
CHANGED
|
@@ -163,7 +163,7 @@ var TRANSIENT_RETRIES = 2;
|
|
|
163
163
|
var TRANSIENT_BACKOFF_MS = 1e3;
|
|
164
164
|
function retryDelay(ms, signal) {
|
|
165
165
|
signal?.throwIfAborted();
|
|
166
|
-
return new Promise((
|
|
166
|
+
return new Promise((resolve2, reject) => {
|
|
167
167
|
const onAbort = () => {
|
|
168
168
|
clearTimeout(timer);
|
|
169
169
|
signal?.removeEventListener("abort", onAbort);
|
|
@@ -171,7 +171,7 @@ function retryDelay(ms, signal) {
|
|
|
171
171
|
};
|
|
172
172
|
const timer = setTimeout(() => {
|
|
173
173
|
signal?.removeEventListener("abort", onAbort);
|
|
174
|
-
|
|
174
|
+
resolve2();
|
|
175
175
|
}, ms);
|
|
176
176
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
177
177
|
});
|
|
@@ -207,8 +207,8 @@ var ApiKeyAuth = class {
|
|
|
207
207
|
this.#key = key;
|
|
208
208
|
}
|
|
209
209
|
/** Resolve gateway poll paths without forwarding credentials to another origin. */
|
|
210
|
-
resolveUrl(
|
|
211
|
-
const url = new URL(
|
|
210
|
+
resolveUrl(path7) {
|
|
211
|
+
const url = new URL(path7, this.apiUrl + "/");
|
|
212
212
|
if (url.origin !== new URL(this.apiUrl).origin || url.username || url.password) {
|
|
213
213
|
throw new Error("Refusing to send a BlockRun API key to a different origin.");
|
|
214
214
|
}
|
|
@@ -274,7 +274,7 @@ var ApiKeyAuth = class {
|
|
|
274
274
|
if (["failed", "cancelled", "canceled"].includes(String(data.status))) {
|
|
275
275
|
throw new APIError("Account API job failed or was cancelled", 502, sanitizeErrorResponse(data));
|
|
276
276
|
}
|
|
277
|
-
await new Promise((
|
|
277
|
+
await new Promise((resolve2) => setTimeout(resolve2, Math.min(interval, Math.max(0, deadline - Date.now()))));
|
|
278
278
|
const remaining = deadline - Date.now();
|
|
279
279
|
if (remaining <= 0) break;
|
|
280
280
|
try {
|
|
@@ -4539,7 +4539,7 @@ function getCostSummary() {
|
|
|
4539
4539
|
}
|
|
4540
4540
|
|
|
4541
4541
|
// src/version.ts
|
|
4542
|
-
var SDK_VERSION = "3.
|
|
4542
|
+
var SDK_VERSION = "3.19.0";
|
|
4543
4543
|
var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
|
|
4544
4544
|
|
|
4545
4545
|
// src/client.ts
|
|
@@ -5648,8 +5648,8 @@ var LLMClient = class _LLMClient {
|
|
|
5648
5648
|
* @example
|
|
5649
5649
|
* const results = await client.exa("search", { query: "latest AI research", numResults: 5 });
|
|
5650
5650
|
*/
|
|
5651
|
-
async exa(
|
|
5652
|
-
return this.requestWithPaymentRaw(`/v1/exa/${
|
|
5651
|
+
async exa(path7, body) {
|
|
5652
|
+
return this.requestWithPaymentRaw(`/v1/exa/${path7}`, body);
|
|
5653
5653
|
}
|
|
5654
5654
|
/**
|
|
5655
5655
|
* Neural web search via Exa. Returns semantically relevant URLs and metadata.
|
|
@@ -5797,8 +5797,8 @@ var LLMClient = class _LLMClient {
|
|
|
5797
5797
|
* const market = await client.pm("kalshi/markets/KXBTC-25MAR14");
|
|
5798
5798
|
* const results = await client.pm("polymarket/search", { q: "bitcoin" });
|
|
5799
5799
|
*/
|
|
5800
|
-
async pm(
|
|
5801
|
-
return this.getWithPaymentRaw(`/v1/pm/${
|
|
5800
|
+
async pm(path7, params) {
|
|
5801
|
+
return this.getWithPaymentRaw(`/v1/pm/${path7}`, params);
|
|
5802
5802
|
}
|
|
5803
5803
|
/**
|
|
5804
5804
|
* Structured query for Predexon prediction market data (POST endpoints).
|
|
@@ -5814,8 +5814,8 @@ var LLMClient = class _LLMClient {
|
|
|
5814
5814
|
* addresses: ["0xabc...", "0xdef..."],
|
|
5815
5815
|
* });
|
|
5816
5816
|
*/
|
|
5817
|
-
async pmQuery(
|
|
5818
|
-
return this.requestWithPaymentRaw(`/v1/pm/${
|
|
5817
|
+
async pmQuery(path7, query) {
|
|
5818
|
+
return this.requestWithPaymentRaw(`/v1/pm/${path7}`, query);
|
|
5819
5819
|
}
|
|
5820
5820
|
// ── PM convenience helpers (Predexon v2) ─────────────────────────────────
|
|
5821
5821
|
// Thin wrappers over pm() / pmQuery() for the most common v2 endpoints.
|
|
@@ -5903,8 +5903,8 @@ var LLMClient = class _LLMClient {
|
|
|
5903
5903
|
* "prices/coingecko:bitcoin,base:0x..."
|
|
5904
5904
|
* @param params - Query parameters passed through to DefiLlama
|
|
5905
5905
|
*/
|
|
5906
|
-
async defi(
|
|
5907
|
-
return this.getWithPaymentRaw(`/v1/defillama/${
|
|
5906
|
+
async defi(path7, params) {
|
|
5907
|
+
return this.getWithPaymentRaw(`/v1/defillama/${path7}`, params);
|
|
5908
5908
|
}
|
|
5909
5909
|
/** All DeFi protocols with TVL. */
|
|
5910
5910
|
async defiProtocols() {
|
|
@@ -5940,9 +5940,9 @@ var LLMClient = class _LLMClient {
|
|
|
5940
5940
|
* @param params - Query params (chainId, sellToken, buyToken, sellAmount, taker, ...)
|
|
5941
5941
|
* @param body - JSON body — pass to switch to POST (gasless/submit only)
|
|
5942
5942
|
*/
|
|
5943
|
-
async dex(
|
|
5944
|
-
if (body) return this.requestWithPaymentRaw(`/v1/zerox/${
|
|
5945
|
-
return this.getWithPaymentRaw(`/v1/zerox/${
|
|
5943
|
+
async dex(path7, params, body) {
|
|
5944
|
+
if (body) return this.requestWithPaymentRaw(`/v1/zerox/${path7}`, body);
|
|
5945
|
+
return this.getWithPaymentRaw(`/v1/zerox/${path7}`, params);
|
|
5946
5946
|
}
|
|
5947
5947
|
/** Indicative Permit2 swap price — no commitment (free). */
|
|
5948
5948
|
async dexPrice(params) {
|
|
@@ -5986,8 +5986,8 @@ var LLMClient = class _LLMClient {
|
|
|
5986
5986
|
* "sandbox/status", "sandbox/terminate"
|
|
5987
5987
|
* @param body - JSON body for the endpoint
|
|
5988
5988
|
*/
|
|
5989
|
-
async modal(
|
|
5990
|
-
return this.requestWithPaymentRaw(`/v1/modal/${
|
|
5989
|
+
async modal(path7, body) {
|
|
5990
|
+
return this.requestWithPaymentRaw(`/v1/modal/${path7}`, body ?? {});
|
|
5991
5991
|
}
|
|
5992
5992
|
/** Create a sandboxed compute environment (CPU / GPU tiers). */
|
|
5993
5993
|
async modalSandboxCreate(body) {
|
|
@@ -6295,7 +6295,7 @@ var ImageClient = class {
|
|
|
6295
6295
|
const pollUrl = pollPath.startsWith("/api/") ? `${this.apiUrl.replace(/\/api$/, "")}${pollPath}` : `${this.apiUrl}${pollPath.startsWith("/") ? "" : "/"}${pollPath}`;
|
|
6296
6296
|
const startedAt = Date.now();
|
|
6297
6297
|
while (Date.now() - startedAt < POLL_MAX_DURATION_MS) {
|
|
6298
|
-
await new Promise((
|
|
6298
|
+
await new Promise((resolve2) => setTimeout(resolve2, POLL_INTERVAL_MS));
|
|
6299
6299
|
const pollResp = await this.fetchWithTimeout(pollUrl, {
|
|
6300
6300
|
method: "GET",
|
|
6301
6301
|
headers: {
|
|
@@ -7493,8 +7493,8 @@ var PhoneClient = class {
|
|
|
7493
7493
|
return data;
|
|
7494
7494
|
}
|
|
7495
7495
|
// ─── Internals ─────────────────────────────────────────────────────────
|
|
7496
|
-
async request(
|
|
7497
|
-
const url = `${this.apiUrl}/v1/phone/${
|
|
7496
|
+
async request(path7, body) {
|
|
7497
|
+
const url = `${this.apiUrl}/v1/phone/${path7}`;
|
|
7498
7498
|
const response = await this.fetchWithTimeout(url, {
|
|
7499
7499
|
method: "POST",
|
|
7500
7500
|
headers: { "Content-Type": "application/json" },
|
|
@@ -7935,10 +7935,10 @@ var PriceClient = class {
|
|
|
7935
7935
|
}
|
|
7936
7936
|
async price(category, symbol, options) {
|
|
7937
7937
|
if (!symbol) throw new Error("symbol is required");
|
|
7938
|
-
const
|
|
7938
|
+
const path7 = categoryPath(category, options?.market, "price", symbol);
|
|
7939
7939
|
const query = {};
|
|
7940
7940
|
if (options?.session) query.session = options.session;
|
|
7941
|
-
const data = await this.getWithPayment(
|
|
7941
|
+
const data = await this.getWithPayment(path7, query);
|
|
7942
7942
|
return {
|
|
7943
7943
|
symbol: data.symbol ?? symbol.toUpperCase(),
|
|
7944
7944
|
price: data.price,
|
|
@@ -7957,14 +7957,14 @@ var PriceClient = class {
|
|
|
7957
7957
|
if (!options.from || options.from <= 0) {
|
|
7958
7958
|
throw new Error("history requires options.from (unix seconds)");
|
|
7959
7959
|
}
|
|
7960
|
-
const
|
|
7960
|
+
const path7 = categoryPath(category, options.market, "history", symbol);
|
|
7961
7961
|
const query = {
|
|
7962
7962
|
resolution: options.resolution ?? "D",
|
|
7963
7963
|
from: String(options.from)
|
|
7964
7964
|
};
|
|
7965
7965
|
if (options.to) query.to = String(options.to);
|
|
7966
7966
|
if (options.session) query.session = options.session;
|
|
7967
|
-
const data = await this.getWithPayment(
|
|
7967
|
+
const data = await this.getWithPayment(path7, query);
|
|
7968
7968
|
return {
|
|
7969
7969
|
symbol: data.symbol ?? symbol.toUpperCase(),
|
|
7970
7970
|
resolution: data.resolution ?? (options.resolution ?? "D"),
|
|
@@ -7976,12 +7976,12 @@ var PriceClient = class {
|
|
|
7976
7976
|
};
|
|
7977
7977
|
}
|
|
7978
7978
|
async listSymbols(category, options) {
|
|
7979
|
-
const
|
|
7979
|
+
const path7 = categoryPath(category, options?.market, "list");
|
|
7980
7980
|
const query = {
|
|
7981
7981
|
limit: String(options?.limit && options.limit > 0 ? options.limit : 100)
|
|
7982
7982
|
};
|
|
7983
7983
|
if (options?.query) query.q = options.query;
|
|
7984
|
-
const data = await this.getWithPayment(
|
|
7984
|
+
const data = await this.getWithPayment(path7, query);
|
|
7985
7985
|
if (Array.isArray(data)) {
|
|
7986
7986
|
return { symbols: data, count: data.length };
|
|
7987
7987
|
}
|
|
@@ -8154,19 +8154,19 @@ var SurfClient = class {
|
|
|
8154
8154
|
* `/v1/surf` is tolerated and stripped). Query params are URL-encoded;
|
|
8155
8155
|
* arrays become repeated keys (`?a=1&a=2`).
|
|
8156
8156
|
*/
|
|
8157
|
-
async get(
|
|
8158
|
-
const url = this.buildUrl(
|
|
8157
|
+
async get(path7, params) {
|
|
8158
|
+
const url = this.buildUrl(path7, params);
|
|
8159
8159
|
return this.requestWithPayment(url, "GET");
|
|
8160
8160
|
}
|
|
8161
8161
|
/**
|
|
8162
8162
|
* POST a Surf endpoint with a JSON body. Same path normalization as `get`.
|
|
8163
8163
|
*/
|
|
8164
|
-
async post(
|
|
8165
|
-
const url = this.buildUrl(
|
|
8164
|
+
async post(path7, body) {
|
|
8165
|
+
const url = this.buildUrl(path7);
|
|
8166
8166
|
return this.requestWithPayment(url, "POST", body);
|
|
8167
8167
|
}
|
|
8168
|
-
buildUrl(
|
|
8169
|
-
let normalized =
|
|
8168
|
+
buildUrl(path7, params) {
|
|
8169
|
+
let normalized = path7.startsWith("/") ? path7 : `/${path7}`;
|
|
8170
8170
|
if (!normalized.startsWith(SURF_PREFIX)) {
|
|
8171
8171
|
normalized = `${SURF_PREFIX}${normalized}`;
|
|
8172
8172
|
}
|
|
@@ -8624,15 +8624,15 @@ var BlockrunClient = class {
|
|
|
8624
8624
|
* `/api` is tolerated and stripped). Query params are URL-encoded; arrays
|
|
8625
8625
|
* become repeated keys (`?a=1&a=2`); undefined/null are dropped.
|
|
8626
8626
|
*/
|
|
8627
|
-
async get(
|
|
8628
|
-
const url = this.buildUrl(
|
|
8627
|
+
async get(path7, params) {
|
|
8628
|
+
const url = this.buildUrl(path7, params);
|
|
8629
8629
|
return this.requestWithPayment(url, "GET");
|
|
8630
8630
|
}
|
|
8631
8631
|
/**
|
|
8632
8632
|
* POST a BlockRun endpoint with a JSON body.
|
|
8633
8633
|
*/
|
|
8634
|
-
async post(
|
|
8635
|
-
const url = this.buildUrl(
|
|
8634
|
+
async post(path7, body) {
|
|
8635
|
+
const url = this.buildUrl(path7);
|
|
8636
8636
|
return this.requestWithPayment(url, "POST", body);
|
|
8637
8637
|
}
|
|
8638
8638
|
/**
|
|
@@ -8656,8 +8656,8 @@ var BlockrunClient = class {
|
|
|
8656
8656
|
* short-circuits and returns the body. Most long-running endpoints (image,
|
|
8657
8657
|
* video, music, voice) return 202 with a poll_url.
|
|
8658
8658
|
*/
|
|
8659
|
-
async poll(
|
|
8660
|
-
const submitUrl = this.buildUrl(
|
|
8659
|
+
async poll(path7, body, options) {
|
|
8660
|
+
const submitUrl = this.buildUrl(path7);
|
|
8661
8661
|
const budgetMs = options?.budgetMs ?? DEFAULT_POLL_BUDGET_MS;
|
|
8662
8662
|
const intervalMs = options?.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
8663
8663
|
const resp402 = await this.fetchWithTimeout(submitUrl, {
|
|
@@ -8757,8 +8757,8 @@ var BlockrunClient = class {
|
|
|
8757
8757
|
* process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
|
|
8758
8758
|
* }
|
|
8759
8759
|
*/
|
|
8760
|
-
async *stream(
|
|
8761
|
-
const url = this.buildUrl(
|
|
8760
|
+
async *stream(path7, body) {
|
|
8761
|
+
const url = this.buildUrl(path7);
|
|
8762
8762
|
const requestBody = JSON.stringify(body ?? {});
|
|
8763
8763
|
const resp402 = await this.fetchWithTimeout(url, {
|
|
8764
8764
|
method: "POST",
|
|
@@ -8801,8 +8801,8 @@ var BlockrunClient = class {
|
|
|
8801
8801
|
// --------------------------------------------------------------------
|
|
8802
8802
|
// Internal: shared infrastructure
|
|
8803
8803
|
// --------------------------------------------------------------------
|
|
8804
|
-
buildUrl(
|
|
8805
|
-
let normalized =
|
|
8804
|
+
buildUrl(path7, params) {
|
|
8805
|
+
let normalized = path7.startsWith("/") ? path7 : `/${path7}`;
|
|
8806
8806
|
if (normalized.startsWith("/api/")) {
|
|
8807
8807
|
normalized = normalized.slice(4);
|
|
8808
8808
|
}
|
|
@@ -9448,6 +9448,332 @@ async function getOrCreateSolanaWallet() {
|
|
|
9448
9448
|
return { address, privateKey, isNew: true };
|
|
9449
9449
|
}
|
|
9450
9450
|
|
|
9451
|
+
// src/solana-batch.ts
|
|
9452
|
+
import * as fs6 from "fs";
|
|
9453
|
+
import * as path5 from "path";
|
|
9454
|
+
var BATCH_SCHEME = "batch-settlement";
|
|
9455
|
+
var INSTALL_HINT2 = "npm install @x402/core@~2.28.0 @x402/svm@~2.28.0 @solana/kit";
|
|
9456
|
+
async function load(pkg, importer) {
|
|
9457
|
+
try {
|
|
9458
|
+
return await importer();
|
|
9459
|
+
} catch (err) {
|
|
9460
|
+
throw new Error(
|
|
9461
|
+
`@blockrun/llm: Solana batch-settlement requires the optional peer dependency "${pkg}", which is not installed.
|
|
9462
|
+
|
|
9463
|
+
${INSTALL_HINT2}
|
|
9464
|
+
|
|
9465
|
+
Original error: ${err instanceof Error ? err.message : String(err)}`,
|
|
9466
|
+
{ cause: err }
|
|
9467
|
+
);
|
|
9468
|
+
}
|
|
9469
|
+
}
|
|
9470
|
+
var FileChannelStorage = class {
|
|
9471
|
+
constructor(file) {
|
|
9472
|
+
this.file = file;
|
|
9473
|
+
}
|
|
9474
|
+
file;
|
|
9475
|
+
read() {
|
|
9476
|
+
try {
|
|
9477
|
+
const parsed = JSON.parse(fs6.readFileSync(this.file, "utf8"));
|
|
9478
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
9479
|
+
} catch (err) {
|
|
9480
|
+
if (err.code === "ENOENT") return {};
|
|
9481
|
+
throw err;
|
|
9482
|
+
}
|
|
9483
|
+
}
|
|
9484
|
+
write(all) {
|
|
9485
|
+
fs6.mkdirSync(path5.dirname(this.file), { recursive: true, mode: 448 });
|
|
9486
|
+
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
9487
|
+
fs6.writeFileSync(tmp, JSON.stringify(all, null, 2), { mode: 384 });
|
|
9488
|
+
fs6.renameSync(tmp, this.file);
|
|
9489
|
+
}
|
|
9490
|
+
async get(key) {
|
|
9491
|
+
return this.read()[key];
|
|
9492
|
+
}
|
|
9493
|
+
async set(key, record) {
|
|
9494
|
+
const all = this.read();
|
|
9495
|
+
all[key] = record;
|
|
9496
|
+
this.write(all);
|
|
9497
|
+
}
|
|
9498
|
+
async delete(key) {
|
|
9499
|
+
const all = this.read();
|
|
9500
|
+
if (!(key in all)) return;
|
|
9501
|
+
delete all[key];
|
|
9502
|
+
this.write(all);
|
|
9503
|
+
}
|
|
9504
|
+
/** Forget every channel in this file. */
|
|
9505
|
+
clear() {
|
|
9506
|
+
try {
|
|
9507
|
+
fs6.unlinkSync(this.file);
|
|
9508
|
+
} catch (err) {
|
|
9509
|
+
if (err.code !== "ENOENT") throw err;
|
|
9510
|
+
}
|
|
9511
|
+
}
|
|
9512
|
+
};
|
|
9513
|
+
function processAlive(pid) {
|
|
9514
|
+
try {
|
|
9515
|
+
process.kill(pid, 0);
|
|
9516
|
+
return true;
|
|
9517
|
+
} catch (err) {
|
|
9518
|
+
return err.code === "EPERM";
|
|
9519
|
+
}
|
|
9520
|
+
}
|
|
9521
|
+
var heldLocks = /* @__PURE__ */ new Set();
|
|
9522
|
+
var exitHookInstalled = false;
|
|
9523
|
+
function lockChannelFile(file) {
|
|
9524
|
+
if (heldLocks.has(file)) return void 0;
|
|
9525
|
+
const lock = `${file}.lock`;
|
|
9526
|
+
fs6.mkdirSync(path5.dirname(lock), { recursive: true, mode: 448 });
|
|
9527
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
9528
|
+
try {
|
|
9529
|
+
fs6.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
|
|
9530
|
+
heldLocks.add(file);
|
|
9531
|
+
if (!exitHookInstalled) {
|
|
9532
|
+
exitHookInstalled = true;
|
|
9533
|
+
process.once("exit", () => {
|
|
9534
|
+
for (const held of heldLocks) {
|
|
9535
|
+
try {
|
|
9536
|
+
fs6.unlinkSync(`${held}.lock`);
|
|
9537
|
+
} catch {
|
|
9538
|
+
}
|
|
9539
|
+
}
|
|
9540
|
+
});
|
|
9541
|
+
}
|
|
9542
|
+
return void 0;
|
|
9543
|
+
} catch (err) {
|
|
9544
|
+
if (err.code !== "EEXIST") throw err;
|
|
9545
|
+
}
|
|
9546
|
+
const owner = Number(fs6.readFileSync(lock, "utf8").trim());
|
|
9547
|
+
if (Number.isInteger(owner) && owner > 0 && owner !== process.pid && processAlive(owner)) return owner;
|
|
9548
|
+
try {
|
|
9549
|
+
fs6.unlinkSync(lock);
|
|
9550
|
+
} catch {
|
|
9551
|
+
}
|
|
9552
|
+
}
|
|
9553
|
+
return -1;
|
|
9554
|
+
}
|
|
9555
|
+
function pendingDeposit(pending) {
|
|
9556
|
+
const entries = Array.isArray(pending) ? pending : [pending];
|
|
9557
|
+
return entries.some(
|
|
9558
|
+
(entry) => entry?.payment?.payload?.type === "deposit"
|
|
9559
|
+
);
|
|
9560
|
+
}
|
|
9561
|
+
function dropOrphanedPending(storage) {
|
|
9562
|
+
return {
|
|
9563
|
+
get: async (key) => {
|
|
9564
|
+
const record = await storage.get(key);
|
|
9565
|
+
if (!record?.pending || record.channelConfig?.voucherSigner !== "server") return record;
|
|
9566
|
+
if (!record.hasConfirmedState || pendingDeposit(record.pending)) {
|
|
9567
|
+
await storage.delete(key);
|
|
9568
|
+
return void 0;
|
|
9569
|
+
}
|
|
9570
|
+
const { pending: _pending, hasConfirmedState: _confirmed, ...confirmed } = record;
|
|
9571
|
+
await storage.set(key, confirmed);
|
|
9572
|
+
return confirmed;
|
|
9573
|
+
},
|
|
9574
|
+
set: (key, record) => storage.set(key, record),
|
|
9575
|
+
delete: (key) => storage.delete(key)
|
|
9576
|
+
};
|
|
9577
|
+
}
|
|
9578
|
+
function offersBatch(paymentRequired) {
|
|
9579
|
+
return (paymentRequired.accepts ?? []).some((accept) => accept.scheme === BATCH_SCHEME);
|
|
9580
|
+
}
|
|
9581
|
+
function atomicToUsd(amount) {
|
|
9582
|
+
return amount !== void 0 && /^\d+$/.test(amount) ? Number(amount) / 1e6 : void 0;
|
|
9583
|
+
}
|
|
9584
|
+
async function isBatchRefusal(response) {
|
|
9585
|
+
if (response.status === 402) return "payment_required";
|
|
9586
|
+
if (![400, 403, 409, 503].includes(response.status)) return void 0;
|
|
9587
|
+
let body;
|
|
9588
|
+
try {
|
|
9589
|
+
body = await response.clone().json();
|
|
9590
|
+
} catch {
|
|
9591
|
+
return void 0;
|
|
9592
|
+
}
|
|
9593
|
+
const { error, code } = body ?? {};
|
|
9594
|
+
if (code === "PAYMENT_VERIFICATION_UNAVAILABLE") return code;
|
|
9595
|
+
return typeof error === "string" && error.startsWith("batch_") ? error : void 0;
|
|
9596
|
+
}
|
|
9597
|
+
var wallets = /* @__PURE__ */ new Map();
|
|
9598
|
+
var SolanaBatchPayer = class {
|
|
9599
|
+
constructor(init) {
|
|
9600
|
+
this.init = init;
|
|
9601
|
+
const { operators } = init.options;
|
|
9602
|
+
if (!Array.isArray(operators) || operators.length === 0 || operators.some((o) => typeof o !== "string" || !o)) {
|
|
9603
|
+
throw new Error("batch.operators must list at least one base58 operator public key");
|
|
9604
|
+
}
|
|
9605
|
+
}
|
|
9606
|
+
init;
|
|
9607
|
+
state;
|
|
9608
|
+
async storeFile() {
|
|
9609
|
+
const { channelStore } = this.init.options;
|
|
9610
|
+
if (channelStore === false) return void 0;
|
|
9611
|
+
return path5.resolve(channelStore ?? path5.join(paths().dir, "solana-batch", `${await this.init.address()}.json`));
|
|
9612
|
+
}
|
|
9613
|
+
/**
|
|
9614
|
+
* This wallet's shared batch state, or why this client cannot use batch:
|
|
9615
|
+
* another client in this process holds the wallet with a different trust
|
|
9616
|
+
* configuration, or another live process owns its channel file.
|
|
9617
|
+
*/
|
|
9618
|
+
wallet() {
|
|
9619
|
+
this.state ??= (async () => {
|
|
9620
|
+
const address = await this.init.address();
|
|
9621
|
+
const file = await this.storeFile();
|
|
9622
|
+
const { operators, maxDeposit } = this.init.options;
|
|
9623
|
+
const config = JSON.stringify([[...operators].sort(), String(maxDeposit ?? ""), file ?? null, this.init.rpcUrl]);
|
|
9624
|
+
const existing = wallets.get(address);
|
|
9625
|
+
if (existing) {
|
|
9626
|
+
return existing.config === config ? existing : "another client in this process uses this wallet with different batch options";
|
|
9627
|
+
}
|
|
9628
|
+
if (file) {
|
|
9629
|
+
const owner = lockChannelFile(file);
|
|
9630
|
+
if (owner !== void 0) return `channel store ${file} is in use by process ${owner}`;
|
|
9631
|
+
}
|
|
9632
|
+
const created = { config, busy: false, warned: /* @__PURE__ */ new Set() };
|
|
9633
|
+
wallets.set(address, created);
|
|
9634
|
+
return created;
|
|
9635
|
+
})();
|
|
9636
|
+
return this.state;
|
|
9637
|
+
}
|
|
9638
|
+
build(wallet) {
|
|
9639
|
+
wallet.client ??= (async () => {
|
|
9640
|
+
const [core, svm, kit] = await Promise.all([
|
|
9641
|
+
load("@x402/core", () => import("@x402/core/client")),
|
|
9642
|
+
load("@x402/svm", () => import("@x402/svm/batch-settlement/client")),
|
|
9643
|
+
load("@solana/kit", () => import("@solana/kit"))
|
|
9644
|
+
]);
|
|
9645
|
+
const signer = await kit.createKeyPairSignerFromBytes(await this.init.secretKey());
|
|
9646
|
+
const file = await this.storeFile();
|
|
9647
|
+
const storage = file ? dropOrphanedPending(new FileChannelStorage(file)) : void 0;
|
|
9648
|
+
const scheme = new svm.BatchSvmScheme(signer, {
|
|
9649
|
+
rpcUrl: this.init.rpcUrl,
|
|
9650
|
+
serverSignedChannelsPolicy: {
|
|
9651
|
+
allowedOperators: this.init.options.operators,
|
|
9652
|
+
maxDeposit: this.init.options.maxDeposit ?? svm.DEFAULT_SERVER_SIGNED_MAX_DEPOSIT
|
|
9653
|
+
},
|
|
9654
|
+
...storage ? { channelStorage: storage } : {}
|
|
9655
|
+
});
|
|
9656
|
+
const client = new core.x402Client().register("solana:*", scheme).registerPolicy(scheme.paymentPolicy);
|
|
9657
|
+
client.setSpendControls({ maxAmountPerPayment: false });
|
|
9658
|
+
return {
|
|
9659
|
+
http: new core.x402HTTPClient(client),
|
|
9660
|
+
refund: (url) => scheme.refund(url)
|
|
9661
|
+
};
|
|
9662
|
+
})();
|
|
9663
|
+
wallet.client.catch(() => {
|
|
9664
|
+
wallet.client = void 0;
|
|
9665
|
+
});
|
|
9666
|
+
return wallet.client;
|
|
9667
|
+
}
|
|
9668
|
+
/**
|
|
9669
|
+
* Drop everything this wallet knows about its channel, on disk and in
|
|
9670
|
+
* memory. The next call rebuilds the scheme, which reads the channel's real
|
|
9671
|
+
* state (deposit, open or closed) from the chain.
|
|
9672
|
+
*/
|
|
9673
|
+
async forget(wallet) {
|
|
9674
|
+
wallet.client = void 0;
|
|
9675
|
+
const file = await this.storeFile();
|
|
9676
|
+
if (file) new FileChannelStorage(file).clear();
|
|
9677
|
+
}
|
|
9678
|
+
warn(wallet, reason) {
|
|
9679
|
+
if (wallet?.warned.has(reason)) return;
|
|
9680
|
+
wallet?.warned.add(reason);
|
|
9681
|
+
console.error(`[@blockrun/llm] batch-settlement unavailable (${reason}); paying with exact`);
|
|
9682
|
+
}
|
|
9683
|
+
/**
|
|
9684
|
+
* Pay one 402 with batch-settlement, or say why the caller should use exact.
|
|
9685
|
+
*
|
|
9686
|
+
* `send` replays the original request with the payment headers. The
|
|
9687
|
+
* returned response is 2xx; any other answer either becomes a fallback (the
|
|
9688
|
+
* gateway charged nothing) or is returned to the caller's own error path.
|
|
9689
|
+
*/
|
|
9690
|
+
async pay(paymentRequired, send) {
|
|
9691
|
+
if (!offersBatch(paymentRequired)) return { kind: "fallback", reason: "not_offered" };
|
|
9692
|
+
const wallet = await this.wallet();
|
|
9693
|
+
if (typeof wallet === "string") {
|
|
9694
|
+
this.warn(void 0, wallet);
|
|
9695
|
+
return { kind: "fallback", reason: wallet };
|
|
9696
|
+
}
|
|
9697
|
+
if (wallet.busy) return { kind: "fallback", reason: "channel_busy" };
|
|
9698
|
+
wallet.busy = true;
|
|
9699
|
+
try {
|
|
9700
|
+
let http;
|
|
9701
|
+
let payload;
|
|
9702
|
+
try {
|
|
9703
|
+
http = (await this.build(wallet)).http;
|
|
9704
|
+
payload = await http.createPaymentPayload(paymentRequired);
|
|
9705
|
+
} catch (err) {
|
|
9706
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
9707
|
+
this.warn(wallet, reason);
|
|
9708
|
+
return { kind: "fallback", reason };
|
|
9709
|
+
}
|
|
9710
|
+
const deposit = payload.payload?.type === "deposit";
|
|
9711
|
+
let response;
|
|
9712
|
+
try {
|
|
9713
|
+
response = await send(http.encodePaymentSignatureHeader(payload));
|
|
9714
|
+
} catch (err) {
|
|
9715
|
+
if (deposit) await this.forget(wallet);
|
|
9716
|
+
else await this.settle(http, payload, () => null, 0);
|
|
9717
|
+
throw err;
|
|
9718
|
+
}
|
|
9719
|
+
const getHeader = (name) => response.headers.get(name);
|
|
9720
|
+
const settled = await this.settle(http, payload, getHeader, response.status);
|
|
9721
|
+
if (deposit && !(response.ok && settled?.success === true)) await this.forget(wallet);
|
|
9722
|
+
if (response.ok) {
|
|
9723
|
+
const charged = atomicToUsd(settled?.amount) ?? atomicToUsd(payload.accepted?.amount) ?? 0;
|
|
9724
|
+
return { kind: "paid", response, chargedUsd: charged };
|
|
9725
|
+
}
|
|
9726
|
+
const refusal = await isBatchRefusal(response);
|
|
9727
|
+
if (refusal) {
|
|
9728
|
+
this.warn(wallet, refusal);
|
|
9729
|
+
return { kind: "fallback", reason: refusal };
|
|
9730
|
+
}
|
|
9731
|
+
return { kind: "failed", response };
|
|
9732
|
+
} finally {
|
|
9733
|
+
wallet.busy = false;
|
|
9734
|
+
}
|
|
9735
|
+
}
|
|
9736
|
+
/**
|
|
9737
|
+
* Hand the gateway's answer to the scheme, which verifies the operator's
|
|
9738
|
+
* voucher and advances (or rolls back) the channel's local state.
|
|
9739
|
+
*
|
|
9740
|
+
* A malformed receipt must not lose a response the caller has been served,
|
|
9741
|
+
* so a scheme error is logged rather than thrown.
|
|
9742
|
+
*/
|
|
9743
|
+
async settle(http, payload, getHeader, status2) {
|
|
9744
|
+
try {
|
|
9745
|
+
return (await http.processPaymentResult(payload, getHeader, status2)).settleResponse;
|
|
9746
|
+
} catch (err) {
|
|
9747
|
+
console.error(
|
|
9748
|
+
`[@blockrun/llm] batch-settlement receipt not reconciled: ${err instanceof Error ? err.message : String(err)}`
|
|
9749
|
+
);
|
|
9750
|
+
return void 0;
|
|
9751
|
+
}
|
|
9752
|
+
}
|
|
9753
|
+
/**
|
|
9754
|
+
* Close the channel and return its unused escrow to the wallet.
|
|
9755
|
+
*
|
|
9756
|
+
* The scheme keeps a closed channel in its records, and would go on paying
|
|
9757
|
+
* into it, so a successful close forgets the channel. The next batch call
|
|
9758
|
+
* finds no open channel on-chain and opens a new one.
|
|
9759
|
+
*
|
|
9760
|
+
* @param url - any batch-enabled route on the gateway the channel was opened with.
|
|
9761
|
+
*/
|
|
9762
|
+
async close(url) {
|
|
9763
|
+
const wallet = await this.wallet();
|
|
9764
|
+
if (typeof wallet === "string") throw new Error(`batch-settlement unavailable: ${wallet}`);
|
|
9765
|
+
if (wallet.busy) throw new Error("batch-settlement channel has a request in flight; close it when the call returns");
|
|
9766
|
+
wallet.busy = true;
|
|
9767
|
+
try {
|
|
9768
|
+
const result = await (await this.build(wallet)).refund(url);
|
|
9769
|
+
await this.forget(wallet);
|
|
9770
|
+
return result;
|
|
9771
|
+
} finally {
|
|
9772
|
+
wallet.busy = false;
|
|
9773
|
+
}
|
|
9774
|
+
}
|
|
9775
|
+
};
|
|
9776
|
+
|
|
9451
9777
|
// src/solana-client.ts
|
|
9452
9778
|
var SOLANA_API_URL = "https://sol.blockrun.ai/api";
|
|
9453
9779
|
var DEFAULT_MAX_TOKENS2 = 1024;
|
|
@@ -9511,7 +9837,7 @@ async function isSafeStaleBlockhashResponse(response) {
|
|
|
9511
9837
|
}
|
|
9512
9838
|
async function waitForStaleRetry(attempt) {
|
|
9513
9839
|
await new Promise(
|
|
9514
|
-
(
|
|
9840
|
+
(resolve2) => setTimeout(resolve2, STALE_BLOCKHASH_RETRY_BACKOFFS_MS[attempt])
|
|
9515
9841
|
);
|
|
9516
9842
|
}
|
|
9517
9843
|
var DEFAULT_SOLANA_RPC_URL = "https://sol.blockrun.ai/api/v1/solana/rpc";
|
|
@@ -9555,6 +9881,7 @@ var SolanaLLMClient = class {
|
|
|
9555
9881
|
addressCache = null;
|
|
9556
9882
|
modelPricingCache = null;
|
|
9557
9883
|
modelPricingPromise = null;
|
|
9884
|
+
batchPayer;
|
|
9558
9885
|
constructor(options = {}) {
|
|
9559
9886
|
this.apiAuth = resolveApiKeyAuth(options);
|
|
9560
9887
|
if (!this.apiAuth) {
|
|
@@ -9574,6 +9901,25 @@ var SolanaLLMClient = class {
|
|
|
9574
9901
|
this.rpcUrl = rpc.url;
|
|
9575
9902
|
this.rpcHeaders = rpc.headers;
|
|
9576
9903
|
this.timeout = options.timeout || DEFAULT_TIMEOUT14;
|
|
9904
|
+
if (options.batch && !this.apiAuth) {
|
|
9905
|
+
this.batchPayer = new SolanaBatchPayer({
|
|
9906
|
+
options: options.batch,
|
|
9907
|
+
secretKey: () => solanaKeyToBytes(this.privateKey),
|
|
9908
|
+
address: () => this.getWalletAddress(),
|
|
9909
|
+
rpcUrl: this.rpcUrl
|
|
9910
|
+
});
|
|
9911
|
+
}
|
|
9912
|
+
}
|
|
9913
|
+
/**
|
|
9914
|
+
* Close this wallet's batch-settlement channel and return its unused escrow.
|
|
9915
|
+
*
|
|
9916
|
+
* The gateway closes it cooperatively when it can; otherwise this starts a
|
|
9917
|
+
* payer-forced close and the escrow comes back after the channel's grace
|
|
9918
|
+
* period. Only meaningful with the `batch` option.
|
|
9919
|
+
*/
|
|
9920
|
+
async closeBatchChannel() {
|
|
9921
|
+
if (!this.batchPayer) throw new Error("closeBatchChannel() requires the `batch` option in wallet mode");
|
|
9922
|
+
return this.batchPayer.close(`${this.apiUrl}/v1/chat/completions`);
|
|
9577
9923
|
}
|
|
9578
9924
|
/** Get Solana wallet address (public key in base58). */
|
|
9579
9925
|
async getWalletAddress() {
|
|
@@ -9767,8 +10113,8 @@ var SolanaLLMClient = class {
|
|
|
9767
10113
|
* how you end up debugging a request you did not send.
|
|
9768
10114
|
* @returns each decoded SSE frame, in order.
|
|
9769
10115
|
*/
|
|
9770
|
-
async *stream(
|
|
9771
|
-
const url = this.buildUrl(
|
|
10116
|
+
async *stream(path7, body) {
|
|
10117
|
+
const url = this.buildUrl(path7);
|
|
9772
10118
|
const response = await this.openPaidStream(url, JSON.stringify(body ?? {}));
|
|
9773
10119
|
yield* readSseFrames(
|
|
9774
10120
|
response,
|
|
@@ -9840,8 +10186,8 @@ var SolanaLLMClient = class {
|
|
|
9840
10186
|
* @param path - endpoint path, with or without a leading slash.
|
|
9841
10187
|
* @returns the absolute URL to call.
|
|
9842
10188
|
*/
|
|
9843
|
-
buildUrl(
|
|
9844
|
-
let normalized =
|
|
10189
|
+
buildUrl(path7) {
|
|
10190
|
+
let normalized = path7.startsWith("/") ? path7 : `/${path7}`;
|
|
9845
10191
|
if (normalized.startsWith("/api/")) normalized = normalized.slice(4);
|
|
9846
10192
|
return `${this.apiUrl}${normalized}`;
|
|
9847
10193
|
}
|
|
@@ -9920,11 +10266,11 @@ var SolanaLLMClient = class {
|
|
|
9920
10266
|
return data;
|
|
9921
10267
|
}
|
|
9922
10268
|
// ── Prediction Markets (Powered by Predexon) ────────────────────────────
|
|
9923
|
-
async pm(
|
|
9924
|
-
return this.getWithPaymentRaw(`/v1/pm/${
|
|
10269
|
+
async pm(path7, params) {
|
|
10270
|
+
return this.getWithPaymentRaw(`/v1/pm/${path7}`, params);
|
|
9925
10271
|
}
|
|
9926
|
-
async pmQuery(
|
|
9927
|
-
return this.requestWithPaymentRaw(`/v1/pm/${
|
|
10272
|
+
async pmQuery(path7, query) {
|
|
10273
|
+
return this.requestWithPaymentRaw(`/v1/pm/${path7}`, query);
|
|
9928
10274
|
}
|
|
9929
10275
|
// ── Exa Web Search (Powered by Exa) ──────────────────────────────────────
|
|
9930
10276
|
/**
|
|
@@ -9936,8 +10282,8 @@ var SolanaLLMClient = class {
|
|
|
9936
10282
|
* @example
|
|
9937
10283
|
* const results = await client.exa("search", { query: "latest AI research", numResults: 5 });
|
|
9938
10284
|
*/
|
|
9939
|
-
async exa(
|
|
9940
|
-
return this.requestWithPaymentRaw(`/v1/exa/${
|
|
10285
|
+
async exa(path7, body) {
|
|
10286
|
+
return this.requestWithPaymentRaw(`/v1/exa/${path7}`, body);
|
|
9941
10287
|
}
|
|
9942
10288
|
/**
|
|
9943
10289
|
* Neural and keyword web search via Exa (Solana payment).
|
|
@@ -9987,8 +10333,8 @@ var SolanaLLMClient = class {
|
|
|
9987
10333
|
* "prices/coingecko:bitcoin,base:0x..."
|
|
9988
10334
|
* @param params - Query parameters passed through to DefiLlama
|
|
9989
10335
|
*/
|
|
9990
|
-
async defi(
|
|
9991
|
-
return this.getWithPaymentRaw(`/v1/defillama/${
|
|
10336
|
+
async defi(path7, params) {
|
|
10337
|
+
return this.getWithPaymentRaw(`/v1/defillama/${path7}`, params);
|
|
9992
10338
|
}
|
|
9993
10339
|
/** All DeFi protocols with TVL. */
|
|
9994
10340
|
async defiProtocols() {
|
|
@@ -10024,9 +10370,9 @@ var SolanaLLMClient = class {
|
|
|
10024
10370
|
* @param params - Query params (chainId, sellToken, buyToken, sellAmount, taker, ...)
|
|
10025
10371
|
* @param body - JSON body — pass to switch to POST (gasless/submit only)
|
|
10026
10372
|
*/
|
|
10027
|
-
async dex(
|
|
10028
|
-
if (body) return this.requestWithPaymentRaw(`/v1/zerox/${
|
|
10029
|
-
return this.getWithPaymentRaw(`/v1/zerox/${
|
|
10373
|
+
async dex(path7, params, body) {
|
|
10374
|
+
if (body) return this.requestWithPaymentRaw(`/v1/zerox/${path7}`, body);
|
|
10375
|
+
return this.getWithPaymentRaw(`/v1/zerox/${path7}`, params);
|
|
10030
10376
|
}
|
|
10031
10377
|
/** Indicative Permit2 swap price — no commitment (free). */
|
|
10032
10378
|
async dexPrice(params) {
|
|
@@ -10070,8 +10416,8 @@ var SolanaLLMClient = class {
|
|
|
10070
10416
|
* "sandbox/status", "sandbox/terminate"
|
|
10071
10417
|
* @param body - JSON body for the endpoint
|
|
10072
10418
|
*/
|
|
10073
|
-
async modal(
|
|
10074
|
-
return this.requestWithPaymentRaw(`/v1/modal/${
|
|
10419
|
+
async modal(path7, body) {
|
|
10420
|
+
return this.requestWithPaymentRaw(`/v1/modal/${path7}`, body ?? {});
|
|
10075
10421
|
}
|
|
10076
10422
|
/** Create a sandboxed compute environment (CPU / GPU tiers). */
|
|
10077
10423
|
async modalSandboxCreate(body) {
|
|
@@ -10108,7 +10454,31 @@ var SolanaLLMClient = class {
|
|
|
10108
10454
|
});
|
|
10109
10455
|
if (response.status === 402) {
|
|
10110
10456
|
try {
|
|
10111
|
-
|
|
10457
|
+
const paymentRequired = await this.readPaymentRequired(response);
|
|
10458
|
+
if (this.batchPayer && staleRetries === 0) {
|
|
10459
|
+
const batch = await this.batchPayer.pay(
|
|
10460
|
+
paymentRequired,
|
|
10461
|
+
(paymentHeaders) => this.fetchWithTimeout(url, {
|
|
10462
|
+
method: "POST",
|
|
10463
|
+
headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT, ...paymentHeaders },
|
|
10464
|
+
body: JSON.stringify(body)
|
|
10465
|
+
})
|
|
10466
|
+
);
|
|
10467
|
+
if (batch.kind === "paid") {
|
|
10468
|
+
this.recordSettlement(batch.chargedUsd);
|
|
10469
|
+
return batch.response.json();
|
|
10470
|
+
}
|
|
10471
|
+
if (batch.kind === "failed") {
|
|
10472
|
+
let errorBody;
|
|
10473
|
+
try {
|
|
10474
|
+
errorBody = await batch.response.json();
|
|
10475
|
+
} catch {
|
|
10476
|
+
errorBody = { error: "Request failed" };
|
|
10477
|
+
}
|
|
10478
|
+
throw new APIError(`API error after payment: ${batch.response.status}`, batch.response.status, sanitizeErrorResponse(errorBody));
|
|
10479
|
+
}
|
|
10480
|
+
}
|
|
10481
|
+
return await this.handlePaymentAndRetry(url, body, paymentRequired, staleRetries > 0);
|
|
10112
10482
|
} catch (error) {
|
|
10113
10483
|
if (!(error instanceof SafeStaleBlockhashError) || staleRetries >= STALE_BLOCKHASH_RETRY_BACKOFFS_MS.length) throw error;
|
|
10114
10484
|
await waitForStaleRetry(staleRetries++);
|
|
@@ -10229,6 +10599,15 @@ var SolanaLLMClient = class {
|
|
|
10229
10599
|
);
|
|
10230
10600
|
}
|
|
10231
10601
|
async signPaymentFrom402(url, response, forceFreshBlockhash, resourceFallback = url) {
|
|
10602
|
+
return this.signExactPayment(
|
|
10603
|
+
url,
|
|
10604
|
+
await this.readPaymentRequired(response),
|
|
10605
|
+
forceFreshBlockhash,
|
|
10606
|
+
resourceFallback
|
|
10607
|
+
);
|
|
10608
|
+
}
|
|
10609
|
+
/** Read a `402`'s payment requirements from its header, or its JSON body. */
|
|
10610
|
+
async readPaymentRequired(response) {
|
|
10232
10611
|
let paymentHeader = response.headers.get("payment-required");
|
|
10233
10612
|
if (!paymentHeader) {
|
|
10234
10613
|
try {
|
|
@@ -10242,8 +10621,14 @@ var SolanaLLMClient = class {
|
|
|
10242
10621
|
if (!paymentHeader) {
|
|
10243
10622
|
throw new PaymentError("402 response but no payment requirements found");
|
|
10244
10623
|
}
|
|
10245
|
-
|
|
10246
|
-
|
|
10624
|
+
return parsePaymentRequired(paymentHeader);
|
|
10625
|
+
}
|
|
10626
|
+
/** Sign the `exact` accept of a 402 as an SPL TransferChecked payment. */
|
|
10627
|
+
async signExactPayment(url, paymentRequired, forceFreshBlockhash, resourceFallback = url) {
|
|
10628
|
+
const details = extractPaymentDetails(
|
|
10629
|
+
{ ...paymentRequired, accepts: paymentRequired.accepts.filter((accept) => accept.scheme !== BATCH_SCHEME) },
|
|
10630
|
+
SOLANA_NETWORK
|
|
10631
|
+
);
|
|
10247
10632
|
if (!details.network?.startsWith("solana:")) {
|
|
10248
10633
|
throw new PaymentError(
|
|
10249
10634
|
`Expected Solana payment network, got: ${details.network}. Use LLMClient for Base payments.`
|
|
@@ -10276,10 +10661,10 @@ var SolanaLLMClient = class {
|
|
|
10276
10661
|
);
|
|
10277
10662
|
return { paymentPayload, costUsd: parseFloat(details.amount) / 1e6 };
|
|
10278
10663
|
}
|
|
10279
|
-
async handlePaymentAndRetry(url, body,
|
|
10280
|
-
const { paymentPayload, costUsd } = await this.
|
|
10664
|
+
async handlePaymentAndRetry(url, body, paymentRequired, forceFreshBlockhash = false) {
|
|
10665
|
+
const { paymentPayload, costUsd } = await this.signExactPayment(
|
|
10281
10666
|
url,
|
|
10282
|
-
|
|
10667
|
+
paymentRequired,
|
|
10283
10668
|
forceFreshBlockhash,
|
|
10284
10669
|
`${this.apiUrl}/v1/chat/completions`
|
|
10285
10670
|
);
|
|
@@ -10440,13 +10825,13 @@ function solanaClient(options = {}) {
|
|
|
10440
10825
|
}
|
|
10441
10826
|
|
|
10442
10827
|
// src/cache.ts
|
|
10443
|
-
import * as
|
|
10444
|
-
import * as
|
|
10828
|
+
import * as fs7 from "fs";
|
|
10829
|
+
import * as path6 from "path";
|
|
10445
10830
|
import * as os4 from "os";
|
|
10446
10831
|
import * as crypto2 from "crypto";
|
|
10447
|
-
var CACHE_DIR =
|
|
10448
|
-
var DATA_DIR =
|
|
10449
|
-
var COST_LOG_FILE2 =
|
|
10832
|
+
var CACHE_DIR = path6.join(os4.homedir(), ".blockrun", "cache");
|
|
10833
|
+
var DATA_DIR = path6.join(os4.homedir(), ".blockrun", "data");
|
|
10834
|
+
var COST_LOG_FILE2 = path6.join(os4.homedir(), ".blockrun", "cost_log.jsonl");
|
|
10450
10835
|
var DEFAULT_TTL = {
|
|
10451
10836
|
"/v1/partner/": 3600 * 1e3,
|
|
10452
10837
|
"/v1/pm/": 1800 * 1e3,
|
|
@@ -10466,19 +10851,19 @@ function cacheKey(endpoint, body) {
|
|
|
10466
10851
|
return crypto2.createHash("sha256").update(keyData).digest("hex").slice(0, 16);
|
|
10467
10852
|
}
|
|
10468
10853
|
function cachePath(key) {
|
|
10469
|
-
return
|
|
10854
|
+
return path6.join(CACHE_DIR, `${key}.json`);
|
|
10470
10855
|
}
|
|
10471
10856
|
function getCached(key) {
|
|
10472
10857
|
const filePath = cachePath(key);
|
|
10473
|
-
if (!
|
|
10858
|
+
if (!fs7.existsSync(filePath)) return null;
|
|
10474
10859
|
try {
|
|
10475
|
-
const raw =
|
|
10860
|
+
const raw = fs7.readFileSync(filePath, "utf-8");
|
|
10476
10861
|
const entry = JSON.parse(raw);
|
|
10477
10862
|
const ttl = entry.ttlMs ?? getTtl(entry.endpoint ?? "");
|
|
10478
10863
|
if (ttl <= 0) return null;
|
|
10479
10864
|
if (Date.now() - entry.cachedAt > ttl) {
|
|
10480
10865
|
try {
|
|
10481
|
-
|
|
10866
|
+
fs7.unlinkSync(filePath);
|
|
10482
10867
|
} catch {
|
|
10483
10868
|
}
|
|
10484
10869
|
return null;
|
|
@@ -10497,7 +10882,7 @@ function getCachedByRequest(endpoint, body) {
|
|
|
10497
10882
|
function setCache(key, data, ttlMs) {
|
|
10498
10883
|
if (ttlMs <= 0) return;
|
|
10499
10884
|
try {
|
|
10500
|
-
|
|
10885
|
+
fs7.mkdirSync(CACHE_DIR, { recursive: true });
|
|
10501
10886
|
} catch {
|
|
10502
10887
|
}
|
|
10503
10888
|
const entry = {
|
|
@@ -10506,7 +10891,7 @@ function setCache(key, data, ttlMs) {
|
|
|
10506
10891
|
ttlMs
|
|
10507
10892
|
};
|
|
10508
10893
|
try {
|
|
10509
|
-
|
|
10894
|
+
fs7.writeFileSync(cachePath(key), JSON.stringify(entry));
|
|
10510
10895
|
} catch {
|
|
10511
10896
|
}
|
|
10512
10897
|
}
|
|
@@ -10527,7 +10912,7 @@ function readableFilename(endpoint, body) {
|
|
|
10527
10912
|
}
|
|
10528
10913
|
function saveReadable(endpoint, body, response, costUsd) {
|
|
10529
10914
|
try {
|
|
10530
|
-
|
|
10915
|
+
fs7.mkdirSync(DATA_DIR, { recursive: true });
|
|
10531
10916
|
} catch {
|
|
10532
10917
|
}
|
|
10533
10918
|
const filename = readableFilename(endpoint, body);
|
|
@@ -10539,14 +10924,14 @@ function saveReadable(endpoint, body, response, costUsd) {
|
|
|
10539
10924
|
response
|
|
10540
10925
|
};
|
|
10541
10926
|
try {
|
|
10542
|
-
|
|
10927
|
+
fs7.writeFileSync(path6.join(DATA_DIR, filename), JSON.stringify(entry, null, 2));
|
|
10543
10928
|
} catch {
|
|
10544
10929
|
}
|
|
10545
10930
|
}
|
|
10546
10931
|
function appendCostLog(endpoint, costUsd) {
|
|
10547
10932
|
if (costUsd <= 0) return;
|
|
10548
10933
|
try {
|
|
10549
|
-
|
|
10934
|
+
fs7.mkdirSync(path6.dirname(COST_LOG_FILE2), { recursive: true });
|
|
10550
10935
|
} catch {
|
|
10551
10936
|
}
|
|
10552
10937
|
const entry = {
|
|
@@ -10555,7 +10940,7 @@ function appendCostLog(endpoint, costUsd) {
|
|
|
10555
10940
|
cost_usd: costUsd
|
|
10556
10941
|
};
|
|
10557
10942
|
try {
|
|
10558
|
-
|
|
10943
|
+
fs7.appendFileSync(COST_LOG_FILE2, JSON.stringify(entry) + "\n");
|
|
10559
10944
|
} catch {
|
|
10560
10945
|
}
|
|
10561
10946
|
}
|
|
@@ -10563,7 +10948,7 @@ function saveToCache(endpoint, body, response, costUsd = 0) {
|
|
|
10563
10948
|
const ttl = getTtl(endpoint);
|
|
10564
10949
|
if (ttl > 0) {
|
|
10565
10950
|
try {
|
|
10566
|
-
|
|
10951
|
+
fs7.mkdirSync(CACHE_DIR, { recursive: true });
|
|
10567
10952
|
} catch {
|
|
10568
10953
|
}
|
|
10569
10954
|
const key = cacheKey(endpoint, body);
|
|
@@ -10575,7 +10960,7 @@ function saveToCache(endpoint, body, response, costUsd = 0) {
|
|
|
10575
10960
|
costUsd
|
|
10576
10961
|
};
|
|
10577
10962
|
try {
|
|
10578
|
-
|
|
10963
|
+
fs7.writeFileSync(cachePath(key), JSON.stringify(entry));
|
|
10579
10964
|
} catch {
|
|
10580
10965
|
}
|
|
10581
10966
|
}
|
|
@@ -10583,14 +10968,14 @@ function saveToCache(endpoint, body, response, costUsd = 0) {
|
|
|
10583
10968
|
appendCostLog(endpoint, costUsd);
|
|
10584
10969
|
}
|
|
10585
10970
|
function clearCache() {
|
|
10586
|
-
if (!
|
|
10971
|
+
if (!fs7.existsSync(CACHE_DIR)) return 0;
|
|
10587
10972
|
let count = 0;
|
|
10588
10973
|
try {
|
|
10589
|
-
const files =
|
|
10974
|
+
const files = fs7.readdirSync(CACHE_DIR);
|
|
10590
10975
|
for (const file of files) {
|
|
10591
10976
|
if (file.endsWith(".json")) {
|
|
10592
10977
|
try {
|
|
10593
|
-
|
|
10978
|
+
fs7.unlinkSync(path6.join(CACHE_DIR, file));
|
|
10594
10979
|
count++;
|
|
10595
10980
|
} catch {
|
|
10596
10981
|
}
|
|
@@ -10601,14 +10986,14 @@ function clearCache() {
|
|
|
10601
10986
|
return count;
|
|
10602
10987
|
}
|
|
10603
10988
|
function getCostLogSummary() {
|
|
10604
|
-
if (!
|
|
10989
|
+
if (!fs7.existsSync(COST_LOG_FILE2)) {
|
|
10605
10990
|
return { totalUsd: 0, calls: 0, byEndpoint: {} };
|
|
10606
10991
|
}
|
|
10607
10992
|
let totalUsd = 0;
|
|
10608
10993
|
let calls = 0;
|
|
10609
10994
|
const byEndpoint = {};
|
|
10610
10995
|
try {
|
|
10611
|
-
const content =
|
|
10996
|
+
const content = fs7.readFileSync(COST_LOG_FILE2, "utf-8").trim();
|
|
10612
10997
|
if (!content) return { totalUsd: 0, calls: 0, byEndpoint: {} };
|
|
10613
10998
|
for (const line of content.split("\n")) {
|
|
10614
10999
|
if (!line) continue;
|
|
@@ -10628,9 +11013,9 @@ function getCostLogSummary() {
|
|
|
10628
11013
|
}
|
|
10629
11014
|
|
|
10630
11015
|
// src/setup.ts
|
|
10631
|
-
import { readFileSync as
|
|
11016
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
10632
11017
|
import { homedir as homedir5 } from "os";
|
|
10633
|
-
import { join as
|
|
11018
|
+
import { join as join7 } from "path";
|
|
10634
11019
|
function setupAgentWallet(options) {
|
|
10635
11020
|
const { address, privateKey, isNew } = getOrCreateWallet();
|
|
10636
11021
|
if (isNew) {
|
|
@@ -10679,7 +11064,7 @@ async function setupAgentClient(options = {}) {
|
|
|
10679
11064
|
if (!chain) {
|
|
10680
11065
|
for (const file of ["payment-chain", ".chain"]) {
|
|
10681
11066
|
try {
|
|
10682
|
-
const saved =
|
|
11067
|
+
const saved = readFileSync7(join7(homedir5(), ".blockrun", file), "utf8").trim();
|
|
10683
11068
|
if (saved === "solana" || saved === "base") {
|
|
10684
11069
|
chain = saved;
|
|
10685
11070
|
break;
|