@priors/mcp 0.15.0 → 0.17.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,25 @@
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 transaction's data decoded and held to those
46
+ // terms, paid to this account, with at least their minimum and a deadline after the plan's block, sdk/rialto.mjs
47
+ // checkSwap, GHSA-cqcw-9qjc-5qc7), its output and its minimum within Chainlink's 5%,
48
+ // its minimum never under the pinned trade's. Rialto's route is taken only when it gives strictly more of the token
49
+ // bought than the pinned pool (chooseRoute): the sold token approved to that router for exactly the amount, then Rialto's
50
+ // transaction unchanged, its gas estimated after the approval (a failing estimate stops the trade, the approval named).
51
+ // After the receipt: what the account received (its balance of the bought token before and after) and the router's
52
+ // allowance (0 after a full fill). Any other answer, an error, no answer within RIALTO_WAIT_MS (8 s) or a check failing:
53
+ // today's pinned trade, the plan saying why (rialtoWhy). Priors takes no fee on either route.
39
54
  import { decodeFunctionResult, encodeFunctionData, formatUnits, getAddress, isAddress, parseAbi, parseUnits } from "viem";
40
55
  import { ZAP, ERC20_ABI, READS_ABI, V3_QUOTER_ABI, V4_QUOTER_ABI, buildBuy, buildSell, impactBps, minOutOf, pinnedPool } from "./stock-zap.mjs";
41
56
  import { rpc, sendCalls } from "./pt-usdg.mjs";
57
+ import { RIALTO_CHAIN_ID, RIALTO_FEATURE, RIALTO_REGISTRY, REGISTRY_ABI, checkQuote, chooseRoute, readWire, rialtoCalls } from "./rialto.mjs";
42
58
  import V2 from "../deployments/4663.v2.json" with { type: "json" };
43
59
 
44
60
  /** 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 +73,10 @@ const POOL = getAddress(V2.pool);
57
73
  // 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
74
  // that makes a swap cost more. Upgrade trigger: a trade that stops for gas after its approval.
59
75
  export const SWAP_GAS = 400_000n;
76
+ /** Where Rialto's quote is asked: Priors' gas gate (gas-worker, priors_stockQuote), which alone holds Rialto's key; and
77
+ * how long an answer is waited for before the pinned pool trades instead. */
78
+ export const STOCK_QUOTE_URL = "https://priors.trade/gas";
79
+ export const RIALTO_WAIT_MS = 8_000;
60
80
 
61
81
  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
82
  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 +293,162 @@ export async function stockTradePlan(client, o = {}, conf = ZAP) {
273
293
  };
274
294
  }
275
295
 
296
+ // ---- Rialto's route -------------------------------------------------------------------------------------------------
297
+
298
+ /** The gate's reasons for no quote (priors_stockQuote's `reason`), in words. */
299
+ const NO_RIALTO = {
300
+ off: "Rialto's route is off on Priors' gas gate",
301
+ busy: "Priors' gas gate is busy (too many quotes asked just now)",
302
+ unavailable: "Rialto gave no quote just now",
303
+ refused: "Rialto refused to quote this trade",
304
+ balance: "Rialto says this account holds too little of the token sold",
305
+ };
306
+ 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");
307
+ /** Text from outside, printable and short. */
308
+ const words = (s) => String(s ?? "").replace(/[^\x20-\x7e]/g, "").trim().slice(0, 120);
309
+
310
+ /** priors_stockQuote asked of the gate (no Authorization header: the gate holds Rialto's key), waited for at most
311
+ * `timeoutMs`: its `result` ({ rialto, reason, expiresAt, now }), or throws an Error whose message says why not. */
312
+ async function askGate({ url = STOCK_QUOTE_URL, fetch: f = globalThis.fetch, timeoutMs = RIALTO_WAIT_MS } = {}, params) {
313
+ const ctl = typeof AbortController === "function" ? new AbortController() : null;
314
+ let timer, late = false;
315
+ const tooLate = new Error(`Priors' gas gate gave no answer within ${timeoutMs / 1000} s`);
316
+ const deadline = new Promise((_, no) => { timer = setTimeout(() => { late = true; ctl?.abort(); no(tooLate); }, timeoutMs); });
317
+ try {
318
+ let res;
319
+ try {
320
+ 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]);
321
+ } catch (e) { throw late ? tooLate : new Error(`Priors' gas gate could not be reached (${words(e?.message || e)})`); }
322
+ if (!res || typeof res.status !== "number") throw new Error("Priors' gas gate's answer is not a quote");
323
+ if (!res.ok) throw new Error(`Priors' gas gate answered HTTP ${res.status}`);
324
+ let j;
325
+ try { j = await Promise.race([res.json(), deadline]); } catch (_) { throw late ? tooLate : new Error("Priors' gas gate's answer is not JSON"); }
326
+ if (j && j.error) throw new Error(`Priors' gas gate refused the quote (${words(j.error.message) || `error ${words(j.error.code)}`})`);
327
+ const r = j && j.result;
328
+ if (!r || typeof r !== "object" || !("rialto" in r)) throw new Error("Priors' gas gate's answer is not a quote");
329
+ return r;
330
+ } finally { clearTimeout(timer); }
331
+ }
332
+
333
+ /**
334
+ * Rialto's route for `p`, a plan stockTradePlan made (every check passed), asked through Priors' gas gate with
335
+ * `o.rialto` ({ url, fetch, timeoutMs }; the caller's own `minOut` and `maxUsdg` as in the plan). Returns `p` with
336
+ * { route: "rialto" | "pinned", rialtoWhy (why not Rialto, else null), rialto (Rialto's checked quote: { quoteId, router,
337
+ * out, minOut, feeBps, legs, gas, expiresAt }, or null when there is none), pinned ({ out, minOut, label }: the pinned
338
+ * pool's quote) }. Taking Rialto's route, the plan's out, minOut, label, spender, allowance, deviationBps, valueUsdg and
339
+ * calls are Rialto's: the exact approval of the sold token to the registry's router (left out when its allowance already
340
+ * is exactly the amount), then Rialto's transaction. minOut is the minimum its transaction carries (the router's own
341
+ * check), and a sale's valueUsdg is that minimum too. Never throws for Rialto: whatever fails keeps the pinned trade.
342
+ */
343
+ export async function rialtoRoute(client, p, o = {}, conf = ZAP) {
344
+ const buy = p.side === "buy";
345
+ const sellToken = buy ? conf.usdg : p.token, buyToken = buy ? p.token : conf.usdg;
346
+ const [outD, outN] = buy ? [p.decimals, p.symbol] : [6, "USDG"];
347
+ const pinned = { out: p.out, minOut: p.minOut, label: p.label };
348
+ const keep = (why, rialto = null) => ({ ...p, route: "pinned", rialtoWhy: why, rialto, pinned });
349
+ let got, wire, ttl, router, t;
350
+ try {
351
+ got = await askGate(o.rialto || {}, [p.account, p.side, p.token, String(p.amountIn), p.slippageBps]);
352
+ } catch (e) { return keep(words(e?.message || e)); }
353
+ if (got.rialto == null) return keep(noRialtoWhy(got.reason));
354
+ try { wire = readWire(got.rialto); } catch (e) { return keep(words(e?.message || e)); }
355
+ // the wire names its taker (sdk/rialto.mjs wireTerms, readWire): it must be this account
356
+ if (got.rialto.taker != null && lc(got.rialto.taker) !== lc(p.account)) return keep("Rialto's quote: another taker");
357
+ // its expiry, on the gate's own clock
358
+ 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)");
359
+ ttl = Number(got.expiresAt) - Number(got.now);
360
+ if (ttl <= 0) return keep("Rialto's quote has expired");
361
+ // the router: Rialto's Router Registry's, read here at the plan's block, never the answer's
362
+ try { router = getAddress((await view(client, hex(p.block), RIALTO_REGISTRY, REGISTRY_ABI, "ownerOf", [BigInt(RIALTO_FEATURE)]))); } catch (_) {
363
+ return keep("Rialto's Router Registry names no router for its swaps just now (paused, or unread)");
364
+ }
365
+ try {
366
+ t = checkQuote({
367
+ quote_id: wire.quoteId, chain_id: RIALTO_CHAIN_ID, settlement: "allowance",
368
+ tx: { to: wire.router, data: wire.data, value: "0", ...(wire.gas != null ? { estimated_gas: wire.gas } : {}) },
369
+ issues: { allowance: { spender: wire.spender }, balance: null },
370
+ sell_token: wire.sellToken, buy_token: wire.buyToken, sell_amount: String(wire.sellAmount), buy_amount: String(wire.buyAmount),
371
+ min_buy_amount: String(wire.minBuyAmount), taker: got.rialto.taker ?? p.account, platform_fee: { total_bps: wire.feeBps },
372
+ }, { sellToken, buyToken, sellAmount: p.amountIn, taker: p.account, router, slippageBps: p.slippageBps, ...(Number.isSafeInteger(p.at) ? { now: p.at } : {}) });
373
+ } catch (e) { return keep(words(e?.message || e)); }
374
+ 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 };
375
+ const q = (x) => `${fmt(x, outD)} ${outN}`;
376
+ // Chainlink's 5%, either way, for Rialto's output and for its minimum
377
+ const tk = { decimals: p.decimals, feedDecimals: p.feedDecimals };
378
+ const usdIn = buy ? p.amountIn : usdOf(p.amountIn, p.price, tk);
379
+ 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; };
380
+ 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);
381
+ 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);
382
+ 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);
383
+ // never a lower floor than the pinned trade's (its slippage, and the caller's minOut), nor past one trade's cap
384
+ if (t.minBuyAmount < p.minOut) return keep(`Rialto's minimum out, ${q(t.minBuyAmount)}, is under the pinned trade's ${q(p.minOut)}`, rialto);
385
+ const cap = o.maxUsdg != null && BigInt(o.maxUsdg) < conf.maxUsdgPerOp ? BigInt(o.maxUsdg) : conf.maxUsdgPerOp;
386
+ if (!buy && t.buyAmount > cap) return keep(`Rialto's quote values the sale at ${usdg(t.buyAmount)}, over one trade's ${usdg(cap)}`, rialto);
387
+ let allowance;
388
+ try { allowance = await view(client, hex(p.block), sellToken, ERC20_ABI, "allowance", [p.account, router]); } catch (_) { allowance = 0n; }
389
+ const inText = buy ? usdg(p.amountIn) : `${fmt(p.amountIn, p.decimals)} ${p.symbol}`;
390
+ const [approval, swap] = rialtoCalls(t);
391
+ const calls = [
392
+ ...(allowance === p.amountIn ? [] : [{ ...approval, step: "approve", what: `the approval of ${inText} to Rialto's router` }]),
393
+ { ...swap, step: "swap", what: `Rialto's ${buy ? "buy" : "sale"} of ${inText} for at least ${q(t.minBuyAmount)} (quote ${t.quoteId})` },
394
+ ];
395
+ return {
396
+ ...p, route: "rialto", rialtoWhy: null, rialto, pinned, label: "Rialto's router", spender: router, out: t.buyAmount, minOut: t.minBuyAmount,
397
+ impactBps: null, deviationBps: off(t.buyAmount), valueUsdg: buy ? p.amountIn : t.minBuyAmount, allowance, calls,
398
+ };
399
+ }
400
+
401
+ /** The route in words, for a plan Rialto was asked for (p.route set; else null). */
402
+ export function routeText(p) {
403
+ if (!p.route) return null;
404
+ const [outD, outN] = p.side === "buy" ? [p.decimals, p.symbol] : [6, "USDG"];
405
+ if (p.route !== "rialto") return `Route: the pinned pool (${p.pinned.label}), not Rialto's: ${p.rialtoWhy}.`;
406
+ const r = p.rialto;
407
+ 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}).`;
408
+ }
409
+
410
+ /** A plan that stopped after its approval to Rialto's router: the error, with what stands. */
411
+ function stoppedAfterRialto(e, p, hashes) {
412
+ const inText = p.side === "buy" ? usdg(p.amountIn) : `${fmt(p.amountIn, p.decimals)} ${p.symbol}`;
413
+ const why = e?.message ? String(e.message).replace(/^stock (buy|sale|sell): /, "") : String(e);
414
+ 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 });
415
+ }
416
+
417
+ /** Rialto's two steps from the account (`send` as stockTrade's): the approval, then, once it is exactly the amount, the
418
+ * quote unexpired and the swap's gas estimated, Rialto's transaction; then what the account received of the token
419
+ * bought (its balance before and after) and the router's allowance (0 after a full fill). */
420
+ async function rialtoSend(client, p, account, send, conf) {
421
+ const buy = p.side === "buy";
422
+ const sellToken = buy ? conf.usdg : p.token, buyToken = buy ? p.token : conf.usdg;
423
+ const router = p.rialto.router, swap = p.calls[p.calls.length - 1];
424
+ const hashes = [];
425
+ const stop = (why) => (hashes.length ? stoppedAfterRialto(new StockTradeError("RIALTO", why), p, hashes) : new StockTradeError("RIALTO", `stock ${p.side}: ${why}`));
426
+ if (p.calls.length === 2) hashes.push(...(await send(p.calls[0])));
427
+ let allowance = null;
428
+ try { allowance = await view(client, "latest", sellToken, ERC20_ABI, "allowance", [account, router]); } catch (_) { allowance = null; }
429
+ if (allowance === null) throw stop("the allowance to Rialto's router could not be read back");
430
+ if (allowance !== p.amountIn) throw stop("the approval to Rialto's router is not the amount its swap takes");
431
+ if (Date.now() / 1000 >= p.rialto.expiresAt) throw stop("Rialto's quote expired before its swap");
432
+ try { await rpc(client, "eth_estimateGas", [{ from: account, to: swap.to, data: swap.data, value: "0x0" }]); } catch (e) {
433
+ throw stop(`Rialto's transaction would not go through: its gas estimate failed (${words(e?.shortMessage || e?.message || e)})`);
434
+ }
435
+ let before = null;
436
+ try { before = await view(client, "latest", buyToken, ERC20_ABI, "balanceOf", [account]); } catch (_) { before = null; }
437
+ try { hashes.push(...(await send(swap))); } catch (e) {
438
+ if (hashes.length && !e?.unconfirmed) throw stoppedAfterRialto(e, p, hashes);
439
+ if (hashes.length && e?.unconfirmed) e.hashes = [...hashes, ...(e.hashes || [])];
440
+ throw e;
441
+ }
442
+ const hash = hashes[hashes.length - 1];
443
+ let tag = "latest";
444
+ try { const rc = await rpc(client, "eth_getTransactionReceipt", [hash]); if (rc && rc.blockNumber != null) tag = hex(rc.blockNumber); } catch (_) { /* latest */ }
445
+ let received = null, allowanceAfter = null;
446
+ try { const after = await view(client, tag, buyToken, ERC20_ABI, "balanceOf", [account]); if (before !== null && after >= before) received = after - before; } catch (_) { /* the logs below */ }
447
+ if (received === null) received = await receivedIn(client, hash, buyToken, account);
448
+ try { allowanceAfter = await view(client, tag, sellToken, ERC20_ABI, "allowance", [account, router]); } catch (_) { allowanceAfter = null; }
449
+ return { ...p, hashes, received, allowanceAfter };
450
+ }
451
+
276
452
  /** A plan in words, one line: "10 USDG -> about 0.0412 NVDA (at least 0.0408), Uniswap v3, 0.05% pool; ...". */
277
453
  export function planText(p) {
278
454
  const [inD, inN, outD, outN] = p.side === "buy" ? [6, "USDG", p.decimals, p.symbol] : [p.decimals, p.symbol, 6, "USDG"];
@@ -287,15 +463,16 @@ async function accountOf(account, wallet) {
287
463
  throw new StockTradeError("ACCOUNT", "stock trade: give the account that signs (account) or a wallet to send with");
288
464
  }
289
465
 
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) {
466
+ /** The account's ETH covers the steps at today's gas price: the first's estimate (+25%), `swapGas` (SWAP_GAS; for
467
+ * Rialto's transaction its own estimate +25% when that is more) for a swap after it. */
468
+ async function gasCheck(client, side, account, calls, swapGas = SWAP_GAS) {
292
469
  let price, eth, est;
293
470
  try {
294
471
  price = BigInt(await rpc(client, "eth_gasPrice", []));
295
472
  eth = BigInt(await rpc(client, "eth_getBalance", [account, "latest"]));
296
473
  } 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;
474
+ 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; }
475
+ const need = (est + est / 4n + (calls.length > 1 ? swapGas : 0n)) * price;
299
476
  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
477
  }
301
478
 
@@ -317,15 +494,19 @@ function stoppedAfter(e, p, hashes) {
317
494
 
318
495
  /**
319
496
  * 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).
497
+ * stockTradePlan, plus wallet, waitTimeoutMs, beforeSend(plan), beforeSwap(plan) (the pinned pool's plan read again
498
+ * after its approval, right before the swap is signed: a caller's limits on a sale's new quote; what it throws stops the
499
+ * trade with the approval standing), onSend(hash, what, step), and `rialto` (stockQuote). Returns the plan, and once
500
+ * sent { ...plan, hashes, received } (received: what the swap's receipt paid the account, or null when unread; through
501
+ * Rialto, the account's balance of the token bought after less before, and allowanceAfter, the router's allowance then).
322
502
  */
323
503
  export async function stockTrade(client, o = {}, conf = ZAP) {
324
504
  stated(o);
325
505
  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);
506
+ let p = await stockQuote(client, { ...o, account }, conf);
327
507
  if (!o.wallet) return p;
328
- await gasCheck(client, p.side, account, p.calls);
508
+ const viaRialto = p.route === "rialto";
509
+ 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
510
  if (o.beforeSend) await o.beforeSend(p);
330
511
  const recheck = `this account's USDG and ${p.symbol} (wallet_balance, or the token's balanceOf)`;
331
512
  // each step's nonce, read here just before it: a wallet whose provider caches its reads (ethers' default, 250 ms) could
@@ -335,6 +516,9 @@ export async function stockTrade(client, o = {}, conf = ZAP) {
335
516
  try { n = { ...c, nonce: Number(BigInt(await rpc(client, "eth_getTransactionCount", [account, "pending"]))) }; } catch (_) { /* the wallet's own */ }
336
517
  return sendCalls(client, o.wallet, [n], account, { waitTimeoutMs: o.waitTimeoutMs, recheck, onSend: o.onSend ? (h, what) => o.onSend(h, what, c.step) : undefined });
337
518
  };
519
+ if (viaRialto) return rialtoSend(client, p, account, send, conf);
520
+ // the route as first planned (Rialto asked and not taken), kept over the plan made again after the approval
521
+ const route = p.route ? { route: p.route, rialtoWhy: p.rialtoWhy, rialto: p.rialto, pinned: p.pinned } : {};
338
522
  const hashes = [];
339
523
  if (p.calls.length === 2) {
340
524
  hashes.push(...(await send(p.calls[0])));
@@ -342,6 +526,7 @@ export async function stockTrade(client, o = {}, conf = ZAP) {
342
526
  let again;
343
527
  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
528
  if (again.calls.length !== 1) throw stoppedAfter(new Error("the approval is not the amount the swap takes"), p, hashes);
529
+ if (o.beforeSwap) { try { await o.beforeSwap(again); } catch (e) { throw stoppedAfter(e, again, hashes); } }
345
530
  p = again;
346
531
  }
347
532
  try { hashes.push(...(await send(p.calls[p.calls.length - 1]))); } catch (e) {
@@ -350,11 +535,15 @@ export async function stockTrade(client, o = {}, conf = ZAP) {
350
535
  throw e;
351
536
  }
352
537
  const received = await receivedIn(client, hashes[hashes.length - 1], p.side === "buy" ? p.token : conf.usdg, account);
353
- return { ...p, hashes, received };
538
+ return { ...p, ...route, hashes, received };
354
539
  }
355
540
 
356
- /** A quote and the calls, sent nothing: stockTradePlan for `side`. */
357
- export const stockQuote = (client, o = {}, conf = ZAP) => stockTradePlan(client, o, conf);
541
+ /** A quote and the calls, sent nothing: stockTradePlan for `side`, and with `o.rialto` Rialto's route for it
542
+ * (rialtoRoute). */
543
+ export const stockQuote = async (client, o = {}, conf = ZAP) => {
544
+ const p = await stockTradePlan(client, o, conf);
545
+ return o.rialto ? rialtoRoute(client, p, o, conf) : p;
546
+ };
358
547
  /** Buy `amount` USDG of `symbol`: the calls, sent when `wallet` is given. */
359
548
  export const stockBuy = (client, o = {}, conf = ZAP) => stockTrade(client, { ...o, side: "buy" }, conf);
360
549
  /** Sell `amount` of `symbol` (or "all") for USDG: the calls, sent when `wallet` is given. */
@@ -58,6 +58,10 @@
58
58
  // take (workAgentKey; GET /api/work?agent=<id>: a worker's way back to an awarded request).
59
59
  // A listed row is a stored row plus `stage` (WORK_LISTED_KEYS), which says what a stored row
60
60
  // cannot (a cancelled request); the answer works out `state` and `act` from it and drops it.
61
+ // work:v1:progress { v: 1, at, requests: [<a listed row>] }: the requests in progress, awarded or delivered
62
+ // and not past the deadline plus WORK_RULES.graceS, newest first (WORK_RULES.openMax at
63
+ // most), then the 10 last paid in the last 30 days (GET /api/work?show=progress: the board's
64
+ // Jobs tab, beside the open list). Read by the board's own route alone; no count is kept.
61
65
  //
62
66
  // A line of work:v1:offers also carries `wallet`, the registry wallet its offer was checked against (lower case), so the
63
67
  // hub can leave out an offer whose agent has since lost or changed its registry wallet (a transfer clears it). A renter's
@@ -302,6 +306,7 @@ export const WORK_NEXT = Object.freeze({
302
306
 
303
307
  export const WORK_OPEN_KEY = "work:v1:open";
304
308
  export const WORK_OFFERS_KEY = "work:v1:offers";
309
+ export const WORK_PROGRESS_KEY = "work:v1:progress";
305
310
  const BYTES32 = /^0x[0-9a-fA-F]{64}$/;
306
311
  const AGENT_ID = /^(?:0|[1-9][0-9]{0,11})$/;
307
312
  /** A request's key, work:v1:req:<id> (the id in lower case). */
@@ -404,8 +409,8 @@ export function hireItemOf(entry, source = "signed") {
404
409
  * Where each of one agent's offers is, in words (`offers`: its hire items, or anything with `host` and a `path` or a
405
410
  * `url`), in their order: its host alone, unless another of them has the same host. Then the host and as much of its
406
411
  * 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
412
+ * when segments follow it ("?…" when only a query does): checks.example/api/check/… and checks.example/api/dev/…;
413
+ * checks.example/check and checks.example/launch. A path every segment of which another one shares is written
409
414
  * 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
415
  * before) is its host alone, and is compared with none.
411
416
  */
@@ -472,7 +477,9 @@ export const GO_PATH = "/account";
472
477
  * 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
478
  * and there is no borrow or repay verb. A link Priors builds carries agent, do, req, job, offer, bid and origin only,
474
479
  * each at most once.
475
- * hire agent, offer? the Hire sheet for that agent's offer
480
+ * hire agent?, offer? the Hire sheet for that agent's offer (no agent: Go mode lists the agents with live hire
481
+ * offers, best record first, the board's For hire order, each opening its Hire sheet; an
482
+ * offer without an agent is left aside)
476
483
  * buy agent the Buy sheet (read only, "not open yet", while the market has no address)
477
484
  * sell agent?, bid? the Sell checklist for the account's own agent (no agent: Go mode asks which of the
478
485
  * account's agents to sell, as the For sale empty state's [Sell an agent] opens it, spec 1.7;
@@ -496,7 +503,7 @@ export const GO_PATH = "/account";
496
503
  * Go mode asks which of the account's agents)
497
504
  */
498
505
  export const GO_VERBS = Object.freeze({
499
- hire: Object.freeze({ need: ["agent"], may: ["offer"] }),
506
+ hire: Object.freeze({ need: [], may: ["agent", "offer"] }),
500
507
  buy: Object.freeze({ need: ["agent"], may: [] }),
501
508
  sell: Object.freeze({ need: [], may: ["agent", "bid"] }),
502
509
  offer: Object.freeze({ need: [], may: ["agent"] }),