@priors/mcp 0.15.0 → 0.16.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.
@@ -36,9 +36,23 @@
36
36
  // the approval stands (its spender pulls only from its caller, so only this account's own swap can use it).
37
37
  // `beforeSend(plan)` is called once a plan has passed every check, before anything is signed (a throw stops the trade
38
38
  // with nothing sent); `onSend(hash, what, step)` as each step leaves ("approve" or "swap").
39
+ //
40
+ // Rialto's route (docs/STOCK-ZAP-SPEC.md 18, "Rialto's route"; only with `rialto: { url?, fetch?, timeoutMs? }`, which
41
+ // @priors/mcp passes with PRIORS_RIALTO=on; without it nothing here changes and nothing is asked). Once today's plan has
42
+ // passed every check above, the same trade is quoted by Rialto (docs.rialto.xyz) through Priors' gas gate
43
+ // (priors_stockQuote at STOCK_QUOTE_URL, no key: Rialto's key never leaves the gate), and its answer is checked here
44
+ // again (sdk/rialto.mjs readWire, then checkQuote against the trade asked, with the router that Rialto's Router Registry
45
+ // names on chain at the plan's block, never the one the answer names), its output and its minimum within Chainlink's 5%,
46
+ // its minimum never under the pinned trade's. Rialto's route is taken only when it gives strictly more of the token
47
+ // bought than the pinned pool (chooseRoute): the sold token approved to that router for exactly the amount, then Rialto's
48
+ // transaction unchanged, its gas estimated after the approval (a failing estimate stops the trade, the approval named).
49
+ // After the receipt: what the account received (its balance of the bought token before and after) and the router's
50
+ // allowance (0 after a full fill). Any other answer, an error, no answer within RIALTO_WAIT_MS (8 s) or a check failing:
51
+ // today's pinned trade, the plan saying why (rialtoWhy). Priors takes no fee on either route.
39
52
  import { decodeFunctionResult, encodeFunctionData, formatUnits, getAddress, isAddress, parseAbi, parseUnits } from "viem";
40
53
  import { ZAP, ERC20_ABI, READS_ABI, V3_QUOTER_ABI, V4_QUOTER_ABI, buildBuy, buildSell, impactBps, minOutOf, pinnedPool } from "./stock-zap.mjs";
41
54
  import { rpc, sendCalls } from "./pt-usdg.mjs";
55
+ import { RIALTO_CHAIN_ID, RIALTO_FEATURE, RIALTO_REGISTRY, REGISTRY_ABI, checkQuote, chooseRoute, readWire, rialtoCalls } from "./rialto.mjs";
42
56
  import V2 from "../deployments/4663.v2.json" with { type: "json" };
43
57
 
44
58
  /** The web zap's eligibility tick, word for word (web/account.html's #as-ok, the deposit sheet's and the buy drawer's),
@@ -57,6 +71,10 @@ const POOL = getAddress(V2.pool);
57
71
  // twice what a pinned pool's swap used on an anvil fork of chain 4663 (2026-10-29). Ceiling: a pool or chain change
58
72
  // that makes a swap cost more. Upgrade trigger: a trade that stops for gas after its approval.
59
73
  export const SWAP_GAS = 400_000n;
74
+ /** Where Rialto's quote is asked: Priors' gas gate (gas-worker, priors_stockQuote), which alone holds Rialto's key; and
75
+ * how long an answer is waited for before the pinned pool trades instead. */
76
+ export const STOCK_QUOTE_URL = "https://priors.trade/gas";
77
+ export const RIALTO_WAIT_MS = 8_000;
60
78
 
61
79
  const LOAN_T = "(uint256 agentId, uint256 sponsorId, uint256 principal, uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium, address owner, uint64 issuedAt, uint64 dueAt, uint64 defaultableAt, uint64 minScoreTerm, uint64 closedAt, uint8 status)";
62
80
  const AGENT_T = "(bool enrolled, bool isRoot, bool defaulted, bool frozen, bool importedFromV1, uint64 enrolledAt, uint64 lastBorrowAt, uint64 lastRepayAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 principalOut, uint256 activeLoans, uint256 premiumBps, uint256 premiumCap, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 recourseHonored, uint256 childrenDefaulted, uint256 qualifiedRepaid, uint256 dollarSecondsRepaid)";
@@ -273,6 +291,161 @@ export async function stockTradePlan(client, o = {}, conf = ZAP) {
273
291
  };
274
292
  }
275
293
 
294
+ // ---- Rialto's route -------------------------------------------------------------------------------------------------
295
+
296
+ /** The gate's reasons for no quote (priors_stockQuote's `reason`), in words. */
297
+ const NO_RIALTO = {
298
+ off: "Rialto's route is off on Priors' gas gate",
299
+ busy: "Priors' gas gate is busy (too many quotes asked just now)",
300
+ unavailable: "Rialto gave no quote just now",
301
+ refused: "Rialto refused to quote this trade",
302
+ balance: "Rialto says this account holds too little of the token sold",
303
+ };
304
+ const noRialtoWhy = (reason) => NO_RIALTO[reason] || (typeof reason === "string" && /^[a-z_]{1,32}$/.test(reason) ? `Priors' gas gate gave no quote (${reason})` : "Priors' gas gate gave no quote");
305
+ /** Text from outside, printable and short. */
306
+ const words = (s) => String(s ?? "").replace(/[^\x20-\x7e]/g, "").trim().slice(0, 120);
307
+
308
+ /** priors_stockQuote asked of the gate (no Authorization header: the gate holds Rialto's key), waited for at most
309
+ * `timeoutMs`: its `result` ({ rialto, reason, expiresAt, now }), or throws an Error whose message says why not. */
310
+ async function askGate({ url = STOCK_QUOTE_URL, fetch: f = globalThis.fetch, timeoutMs = RIALTO_WAIT_MS } = {}, params) {
311
+ const ctl = typeof AbortController === "function" ? new AbortController() : null;
312
+ let timer, late = false;
313
+ const tooLate = new Error(`Priors' gas gate gave no answer within ${timeoutMs / 1000} s`);
314
+ const deadline = new Promise((_, no) => { timer = setTimeout(() => { late = true; ctl?.abort(); no(tooLate); }, timeoutMs); });
315
+ try {
316
+ let res;
317
+ try {
318
+ res = await Promise.race([f(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "priors_stockQuote", params }), ...(ctl ? { signal: ctl.signal } : {}) }), deadline]);
319
+ } catch (e) { throw late ? tooLate : new Error(`Priors' gas gate could not be reached (${words(e?.message || e)})`); }
320
+ if (!res || typeof res.status !== "number") throw new Error("Priors' gas gate's answer is not a quote");
321
+ if (!res.ok) throw new Error(`Priors' gas gate answered HTTP ${res.status}`);
322
+ let j;
323
+ try { j = await Promise.race([res.json(), deadline]); } catch (_) { throw late ? tooLate : new Error("Priors' gas gate's answer is not JSON"); }
324
+ if (j && j.error) throw new Error(`Priors' gas gate refused the quote (${words(j.error.message) || `error ${words(j.error.code)}`})`);
325
+ const r = j && j.result;
326
+ if (!r || typeof r !== "object" || !("rialto" in r)) throw new Error("Priors' gas gate's answer is not a quote");
327
+ return r;
328
+ } finally { clearTimeout(timer); }
329
+ }
330
+
331
+ /**
332
+ * Rialto's route for `p`, a plan stockTradePlan made (every check passed), asked through Priors' gas gate with
333
+ * `o.rialto` ({ url, fetch, timeoutMs }; the caller's own `minOut` and `maxUsdg` as in the plan). Returns `p` with
334
+ * { route: "rialto" | "pinned", rialtoWhy (why not Rialto, else null), rialto (Rialto's checked quote: { quoteId, router,
335
+ * out, minOut, feeBps, legs, gas, expiresAt }, or null when there is none), pinned ({ out, minOut, label }: the pinned
336
+ * pool's quote) }. Taking Rialto's route, the plan's out, minOut, label, spender, allowance, deviationBps, valueUsdg and
337
+ * calls are Rialto's: the exact approval of the sold token to the registry's router (left out when its allowance already
338
+ * is exactly the amount), then Rialto's transaction. Never throws for Rialto: whatever fails keeps the pinned trade.
339
+ */
340
+ export async function rialtoRoute(client, p, o = {}, conf = ZAP) {
341
+ const buy = p.side === "buy";
342
+ const sellToken = buy ? conf.usdg : p.token, buyToken = buy ? p.token : conf.usdg;
343
+ const [outD, outN] = buy ? [p.decimals, p.symbol] : [6, "USDG"];
344
+ const pinned = { out: p.out, minOut: p.minOut, label: p.label };
345
+ const keep = (why, rialto = null) => ({ ...p, route: "pinned", rialtoWhy: why, rialto, pinned });
346
+ let got, wire, ttl, router, t;
347
+ try {
348
+ got = await askGate(o.rialto || {}, [p.account, p.side, p.token, String(p.amountIn), p.slippageBps]);
349
+ } catch (e) { return keep(words(e?.message || e)); }
350
+ if (got.rialto == null) return keep(noRialtoWhy(got.reason));
351
+ try { wire = readWire(got.rialto); } catch (e) { return keep(words(e?.message || e)); }
352
+ // the wire names its taker (sdk/rialto.mjs wireTerms, readWire): it must be this account
353
+ if (got.rialto.taker != null && lc(got.rialto.taker) !== lc(p.account)) return keep("Rialto's quote: another taker");
354
+ // its expiry, on the gate's own clock
355
+ if (got.expiresAt == null || got.now == null || !Number.isFinite(Number(got.expiresAt)) || !Number.isFinite(Number(got.now))) return keep("Priors' gas gate's answer is not a quote (no expiry)");
356
+ ttl = Number(got.expiresAt) - Number(got.now);
357
+ if (ttl <= 0) return keep("Rialto's quote has expired");
358
+ // the router: Rialto's Router Registry's, read here at the plan's block, never the answer's
359
+ try { router = getAddress((await view(client, hex(p.block), RIALTO_REGISTRY, REGISTRY_ABI, "ownerOf", [BigInt(RIALTO_FEATURE)]))); } catch (_) {
360
+ return keep("Rialto's Router Registry names no router for its swaps just now (paused, or unread)");
361
+ }
362
+ try {
363
+ t = checkQuote({
364
+ quote_id: wire.quoteId, chain_id: RIALTO_CHAIN_ID, settlement: "allowance",
365
+ tx: { to: wire.router, data: wire.data, value: "0", ...(wire.gas != null ? { estimated_gas: wire.gas } : {}) },
366
+ issues: { allowance: { spender: wire.spender }, balance: null },
367
+ sell_token: wire.sellToken, buy_token: wire.buyToken, sell_amount: String(wire.sellAmount), buy_amount: String(wire.buyAmount),
368
+ min_buy_amount: String(wire.minBuyAmount), taker: got.rialto.taker ?? p.account, platform_fee: { total_bps: wire.feeBps },
369
+ }, { sellToken, buyToken, sellAmount: p.amountIn, taker: p.account, router, slippageBps: p.slippageBps });
370
+ } catch (e) { return keep(words(e?.message || e)); }
371
+ const rialto = { quoteId: t.quoteId, router, out: t.buyAmount, minOut: t.minBuyAmount, feeBps: t.feeBps, legs: wire.legs, gas: t.gas, expiresAt: Math.floor(Date.now() / 1000) + ttl };
372
+ const q = (x) => `${fmt(x, outD)} ${outN}`;
373
+ // Chainlink's 5%, either way, for Rialto's output and for its minimum
374
+ const tk = { decimals: p.decimals, feedDecimals: p.feedDecimals };
375
+ const usdIn = buy ? p.amountIn : usdOf(p.amountIn, p.price, tk);
376
+ const off = (x) => { const usdOut = buy ? usdOf(x, p.price, tk) : x; return usdIn > 0n ? Number(((usdIn > usdOut ? usdIn - usdOut : usdOut - usdIn) * 10_000n) / usdIn) : 0; };
377
+ if (off(t.buyAmount) > MAX_DEVIATION_BPS) return keep(`Rialto's quote, ${q(t.buyAmount)}, is ${(off(t.buyAmount) / 100).toFixed(2)}% from Chainlink's price, over ${MAX_DEVIATION_BPS / 100}%`, rialto);
378
+ if (off(t.minBuyAmount) > MAX_DEVIATION_BPS) return keep(`Rialto's minimum out, ${q(t.minBuyAmount)}, is ${(off(t.minBuyAmount) / 100).toFixed(2)}% from Chainlink's price, over ${MAX_DEVIATION_BPS / 100}%`, rialto);
379
+ if (chooseRoute({ pinnedOut: p.out, rialto: t }).route !== "rialto") return keep(`Rialto's quote gives ${q(t.buyAmount)}, not more than the pinned pool's ${q(p.out)}`, rialto);
380
+ // never a lower floor than the pinned trade's (its slippage, and the caller's minOut), nor past one trade's cap
381
+ if (t.minBuyAmount < p.minOut) return keep(`Rialto's minimum out, ${q(t.minBuyAmount)}, is under the pinned trade's ${q(p.minOut)}`, rialto);
382
+ const cap = o.maxUsdg != null && BigInt(o.maxUsdg) < conf.maxUsdgPerOp ? BigInt(o.maxUsdg) : conf.maxUsdgPerOp;
383
+ if (!buy && t.buyAmount > cap) return keep(`Rialto's quote values the sale at ${usdg(t.buyAmount)}, over one trade's ${usdg(cap)}`, rialto);
384
+ let allowance;
385
+ try { allowance = await view(client, hex(p.block), sellToken, ERC20_ABI, "allowance", [p.account, router]); } catch (_) { allowance = 0n; }
386
+ const inText = buy ? usdg(p.amountIn) : `${fmt(p.amountIn, p.decimals)} ${p.symbol}`;
387
+ const [approval, swap] = rialtoCalls(t);
388
+ const calls = [
389
+ ...(allowance === p.amountIn ? [] : [{ ...approval, step: "approve", what: `the approval of ${inText} to Rialto's router` }]),
390
+ { ...swap, step: "swap", what: `Rialto's ${buy ? "buy" : "sale"} of ${inText} for at least ${q(t.minBuyAmount)} (quote ${t.quoteId})` },
391
+ ];
392
+ return {
393
+ ...p, route: "rialto", rialtoWhy: null, rialto, pinned, label: "Rialto's router", spender: router, out: t.buyAmount, minOut: t.minBuyAmount,
394
+ impactBps: null, deviationBps: off(t.buyAmount), valueUsdg: buy ? p.amountIn : t.buyAmount, allowance, calls,
395
+ };
396
+ }
397
+
398
+ /** The route in words, for a plan Rialto was asked for (p.route set; else null). */
399
+ export function routeText(p) {
400
+ if (!p.route) return null;
401
+ const [outD, outN] = p.side === "buy" ? [p.decimals, p.symbol] : [6, "USDG"];
402
+ if (p.route !== "rialto") return `Route: the pinned pool (${p.pinned.label}), not Rialto's: ${p.rialtoWhy}.`;
403
+ const r = p.rialto;
404
+ return `Route: Rialto, through the router its Router Registry names (${r.router}), quote ${r.quoteId}, Rialto's fee ${r.feeBps ?? "unstated"} bps, no Priors fee: about ${fmt(r.out, outD)} ${outN}, at least ${fmt(r.minOut, outD)}, against the pinned pool's ${fmt(p.pinned.out, outD)} ${outN} (${p.pinned.label}).`;
405
+ }
406
+
407
+ /** A plan that stopped after its approval to Rialto's router: the error, with what stands. */
408
+ function stoppedAfterRialto(e, p, hashes) {
409
+ const inText = p.side === "buy" ? usdg(p.amountIn) : `${fmt(p.amountIn, p.decimals)} ${p.symbol}`;
410
+ const why = e?.message ? String(e.message).replace(/^stock (buy|sale|sell): /, "") : String(e);
411
+ return new StockTradeError(e?.code || "STOPPED", `stock ${p.side}: the approval was sent (tx ${hashes.join(", ")}), then the trade stopped: ${why}. Nothing more was sent. The approval of exactly ${inText} to Rialto's router ${p.rialto.router} stands: this account's next Rialto trade of that amount sends its swap alone`, { hashes: [...hashes], stoppedAfterApproval: true, cause: e });
412
+ }
413
+
414
+ /** Rialto's two steps from the account (`send` as stockTrade's): the approval, then, once it is exactly the amount, the
415
+ * quote unexpired and the swap's gas estimated, Rialto's transaction; then what the account received of the token
416
+ * bought (its balance before and after) and the router's allowance (0 after a full fill). */
417
+ async function rialtoSend(client, p, account, send, conf) {
418
+ const buy = p.side === "buy";
419
+ const sellToken = buy ? conf.usdg : p.token, buyToken = buy ? p.token : conf.usdg;
420
+ const router = p.rialto.router, swap = p.calls[p.calls.length - 1];
421
+ const hashes = [];
422
+ const stop = (why) => (hashes.length ? stoppedAfterRialto(new StockTradeError("RIALTO", why), p, hashes) : new StockTradeError("RIALTO", `stock ${p.side}: ${why}`));
423
+ if (p.calls.length === 2) hashes.push(...(await send(p.calls[0])));
424
+ let allowance = null;
425
+ try { allowance = await view(client, "latest", sellToken, ERC20_ABI, "allowance", [account, router]); } catch (_) { allowance = null; }
426
+ if (allowance === null) throw stop("the allowance to Rialto's router could not be read back");
427
+ if (allowance !== p.amountIn) throw stop("the approval to Rialto's router is not the amount its swap takes");
428
+ if (Date.now() / 1000 >= p.rialto.expiresAt) throw stop("Rialto's quote expired before its swap");
429
+ try { await rpc(client, "eth_estimateGas", [{ from: account, to: swap.to, data: swap.data, value: "0x0" }]); } catch (e) {
430
+ throw stop(`Rialto's transaction would not go through: its gas estimate failed (${words(e?.shortMessage || e?.message || e)})`);
431
+ }
432
+ let before = null;
433
+ try { before = await view(client, "latest", buyToken, ERC20_ABI, "balanceOf", [account]); } catch (_) { before = null; }
434
+ try { hashes.push(...(await send(swap))); } catch (e) {
435
+ if (hashes.length && !e?.unconfirmed) throw stoppedAfterRialto(e, p, hashes);
436
+ if (hashes.length && e?.unconfirmed) e.hashes = [...hashes, ...(e.hashes || [])];
437
+ throw e;
438
+ }
439
+ const hash = hashes[hashes.length - 1];
440
+ let tag = "latest";
441
+ try { const rc = await rpc(client, "eth_getTransactionReceipt", [hash]); if (rc && rc.blockNumber != null) tag = hex(rc.blockNumber); } catch (_) { /* latest */ }
442
+ let received = null, allowanceAfter = null;
443
+ try { const after = await view(client, tag, buyToken, ERC20_ABI, "balanceOf", [account]); if (before !== null && after >= before) received = after - before; } catch (_) { /* the logs below */ }
444
+ if (received === null) received = await receivedIn(client, hash, buyToken, account);
445
+ try { allowanceAfter = await view(client, tag, sellToken, ERC20_ABI, "allowance", [account, router]); } catch (_) { allowanceAfter = null; }
446
+ return { ...p, hashes, received, allowanceAfter };
447
+ }
448
+
276
449
  /** A plan in words, one line: "10 USDG -> about 0.0412 NVDA (at least 0.0408), Uniswap v3, 0.05% pool; ...". */
277
450
  export function planText(p) {
278
451
  const [inD, inN, outD, outN] = p.side === "buy" ? [6, "USDG", p.decimals, p.symbol] : [p.decimals, p.symbol, 6, "USDG"];
@@ -287,15 +460,16 @@ async function accountOf(account, wallet) {
287
460
  throw new StockTradeError("ACCOUNT", "stock trade: give the account that signs (account) or a wallet to send with");
288
461
  }
289
462
 
290
- /** The account's ETH covers the steps at today's gas price: the first's estimate (+25%), SWAP_GAS for a swap after it. */
291
- async function gasCheck(client, side, account, calls) {
463
+ /** The account's ETH covers the steps at today's gas price: the first's estimate (+25%), `swapGas` (SWAP_GAS; for
464
+ * Rialto's transaction its own estimate +25% when that is more) for a swap after it. */
465
+ async function gasCheck(client, side, account, calls, swapGas = SWAP_GAS) {
292
466
  let price, eth, est;
293
467
  try {
294
468
  price = BigInt(await rpc(client, "eth_gasPrice", []));
295
469
  eth = BigInt(await rpc(client, "eth_getBalance", [account, "latest"]));
296
470
  } catch (e) { throw new StockTradeError("UNREAD", `stock ${side}: the gas price or the account's ETH could not be read just now`); }
297
- try { est = BigInt(await rpc(client, "eth_estimateGas", [{ from: account, to: calls[0].to, data: calls[0].data }])); } catch (_) { est = calls[0].step === "swap" ? SWAP_GAS : 75_000n; }
298
- const need = (est + est / 4n + (calls.length > 1 ? SWAP_GAS : 0n)) * price;
471
+ try { est = BigInt(await rpc(client, "eth_estimateGas", [{ from: account, to: calls[0].to, data: calls[0].data }])); } catch (_) { est = calls[0].step === "swap" ? swapGas : 75_000n; }
472
+ const need = (est + est / 4n + (calls.length > 1 ? swapGas : 0n)) * price;
299
473
  if (eth < need) no(side, "NO_GAS", `${account} has ${formatUnits(eth, 18)} ETH, under the ${formatUnits(need, 18)} ETH its ${calls.length > 1 ? "two transactions" : "transaction"} may cost in gas`);
300
474
  }
301
475
 
@@ -317,15 +491,19 @@ function stoppedAfter(e, p, hashes) {
317
491
 
318
492
  /**
319
493
  * One trade: the plan, and with `wallet` (an ethers Wallet or Signer, a viem WalletClient) its steps sent. o: as
320
- * stockTradePlan, plus wallet, waitTimeoutMs, beforeSend(plan), onSend(hash, what, step). Returns the plan, and once sent
321
- * { ...plan, hashes, received } (received: what the swap's receipt paid the account, or null when unread).
494
+ * stockTradePlan, plus wallet, waitTimeoutMs, beforeSend(plan), beforeSwap(plan) (the pinned pool's plan read again
495
+ * after its approval, right before the swap is signed: a caller's limits on a sale's new quote; what it throws stops the
496
+ * trade with the approval standing), onSend(hash, what, step), and `rialto` (stockQuote). Returns the plan, and once
497
+ * sent { ...plan, hashes, received } (received: what the swap's receipt paid the account, or null when unread; through
498
+ * Rialto, the account's balance of the token bought after less before, and allowanceAfter, the router's allowance then).
322
499
  */
323
500
  export async function stockTrade(client, o = {}, conf = ZAP) {
324
501
  stated(o);
325
502
  const account = await accountOf(o.account, o.wallet).catch((e) => { throw e instanceof StockTradeError ? e : new StockTradeError("ACCOUNT", String(e?.message || e)); });
326
- let p = await stockTradePlan(client, { ...o, account }, conf);
503
+ let p = await stockQuote(client, { ...o, account }, conf);
327
504
  if (!o.wallet) return p;
328
- await gasCheck(client, p.side, account, p.calls);
505
+ const viaRialto = p.route === "rialto";
506
+ await gasCheck(client, p.side, account, p.calls, viaRialto && p.rialto.gas && BigInt(p.rialto.gas) * 5n / 4n > SWAP_GAS ? BigInt(p.rialto.gas) * 5n / 4n : SWAP_GAS);
329
507
  if (o.beforeSend) await o.beforeSend(p);
330
508
  const recheck = `this account's USDG and ${p.symbol} (wallet_balance, or the token's balanceOf)`;
331
509
  // each step's nonce, read here just before it: a wallet whose provider caches its reads (ethers' default, 250 ms) could
@@ -335,6 +513,9 @@ export async function stockTrade(client, o = {}, conf = ZAP) {
335
513
  try { n = { ...c, nonce: Number(BigInt(await rpc(client, "eth_getTransactionCount", [account, "pending"]))) }; } catch (_) { /* the wallet's own */ }
336
514
  return sendCalls(client, o.wallet, [n], account, { waitTimeoutMs: o.waitTimeoutMs, recheck, onSend: o.onSend ? (h, what) => o.onSend(h, what, c.step) : undefined });
337
515
  };
516
+ if (viaRialto) return rialtoSend(client, p, account, send, conf);
517
+ // the route as first planned (Rialto asked and not taken), kept over the plan made again after the approval
518
+ const route = p.route ? { route: p.route, rialtoWhy: p.rialtoWhy, rialto: p.rialto, pinned: p.pinned } : {};
338
519
  const hashes = [];
339
520
  if (p.calls.length === 2) {
340
521
  hashes.push(...(await send(p.calls[0])));
@@ -342,6 +523,7 @@ export async function stockTrade(client, o = {}, conf = ZAP) {
342
523
  let again;
343
524
  try { again = await stockTradePlan(client, { ...o, account, amount: p.amountIn, pool: p.pool, minOut: p.minOut, slippageBps: p.slippageBps }, conf); } catch (e) { throw stoppedAfter(e, p, hashes); }
344
525
  if (again.calls.length !== 1) throw stoppedAfter(new Error("the approval is not the amount the swap takes"), p, hashes);
526
+ if (o.beforeSwap) { try { await o.beforeSwap(again); } catch (e) { throw stoppedAfter(e, again, hashes); } }
345
527
  p = again;
346
528
  }
347
529
  try { hashes.push(...(await send(p.calls[p.calls.length - 1]))); } catch (e) {
@@ -350,11 +532,15 @@ export async function stockTrade(client, o = {}, conf = ZAP) {
350
532
  throw e;
351
533
  }
352
534
  const received = await receivedIn(client, hashes[hashes.length - 1], p.side === "buy" ? p.token : conf.usdg, account);
353
- return { ...p, hashes, received };
535
+ return { ...p, ...route, hashes, received };
354
536
  }
355
537
 
356
- /** A quote and the calls, sent nothing: stockTradePlan for `side`. */
357
- export const stockQuote = (client, o = {}, conf = ZAP) => stockTradePlan(client, o, conf);
538
+ /** A quote and the calls, sent nothing: stockTradePlan for `side`, and with `o.rialto` Rialto's route for it
539
+ * (rialtoRoute). */
540
+ export const stockQuote = async (client, o = {}, conf = ZAP) => {
541
+ const p = await stockTradePlan(client, o, conf);
542
+ return o.rialto ? rialtoRoute(client, p, o, conf) : p;
543
+ };
358
544
  /** Buy `amount` USDG of `symbol`: the calls, sent when `wallet` is given. */
359
545
  export const stockBuy = (client, o = {}, conf = ZAP) => stockTrade(client, { ...o, side: "buy" }, conf);
360
546
  /** Sell `amount` of `symbol` (or "all") for USDG: the calls, sent when `wallet` is given. */
@@ -404,8 +404,8 @@ export function hireItemOf(entry, source = "signed") {
404
404
  * Where each of one agent's offers is, in words (`offers`: its hire items, or anything with `host` and a `path` or a
405
405
  * `url`), in their order: its host alone, unless another of them has the same host. Then the host and as much of its
406
406
  * path as tells it from those others: its segments up to the first one no other offer on that host has there, and "/…"
407
- * when segments follow it ("?…" when only a query does): t0ll.xyz/api/x402/check/… and t0ll.xyz/api/x402/dev/…;
408
- * check.blockpin.dev/check and check.blockpin.dev/launch. A path every segment of which another one shares is written
407
+ * when segments follow it ("?…" when only a query does): checks.example/api/check/… and checks.example/api/dev/…;
408
+ * checks.example/check and checks.example/launch. A path every segment of which another one shares is written
409
409
  * whole, with its query when another has that same path. An offer with neither a path nor a url (from a data Worker of
410
410
  * before) is its host alone, and is compared with none.
411
411
  */
@@ -472,7 +472,9 @@ export const GO_PATH = "/account";
472
472
  * Each verb, what it needs and what it may carry. No amount ever travels in a link (prices are read again in Go mode),
473
473
  * and there is no borrow or repay verb. A link Priors builds carries agent, do, req, job, offer, bid and origin only,
474
474
  * each at most once.
475
- * hire agent, offer? the Hire sheet for that agent's offer
475
+ * hire agent?, offer? the Hire sheet for that agent's offer (no agent: Go mode lists the agents with live hire
476
+ * offers, best record first, the board's For hire order, each opening its Hire sheet; an
477
+ * offer without an agent is left aside)
476
478
  * buy agent the Buy sheet (read only, "not open yet", while the market has no address)
477
479
  * sell agent?, bid? the Sell checklist for the account's own agent (no agent: Go mode asks which of the
478
480
  * account's agents to sell, as the For sale empty state's [Sell an agent] opens it, spec 1.7;
@@ -496,7 +498,7 @@ export const GO_PATH = "/account";
496
498
  * Go mode asks which of the account's agents)
497
499
  */
498
500
  export const GO_VERBS = Object.freeze({
499
- hire: Object.freeze({ need: ["agent"], may: ["offer"] }),
501
+ hire: Object.freeze({ need: [], may: ["agent", "offer"] }),
500
502
  buy: Object.freeze({ need: ["agent"], may: [] }),
501
503
  sell: Object.freeze({ need: [], may: ["agent", "bid"] }),
502
504
  offer: Object.freeze({ need: [], may: ["agent"] }),