@priors/mcp 0.17.0 → 0.17.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # @priors/mcp changelog
2
2
 
3
+ ## 0.17.1 (2026-11-04)
4
+
5
+ On @priors/x402 0.8.7 (Autopay's savings approval and current plan, below).
6
+
7
+ - **Rialto's route holds the router call's fee words too** (GHSA-m3hr-g75r-gmcj, reported by @sonson0910; only with
8
+ `PRIORS_STOCKS` and `PRIORS_RIALTO=on`, both off by default). 0.17.0 decoded the router call's fee words
9
+ (`feeRecipient`, `srcBps`, `dstBps`) and checked none of them, and the router pays them to whatever address they name
10
+ (it checks the minimum after the fee): an answer whose JSON was honest could still pay the output above the
11
+ transaction's minimum, within the slippage, to another address, and a quote stating no fee showed "Rialto's fee 0
12
+ bps". The transaction is now taken only with no fee or Rialto's own, at most 5 bps paid to Rialto's address
13
+ (`src/rialto.mjs` `checkSwapFee`, `RIALTO_FEE_BPS`, `RIALTO_FEE_RECIPIENT`), never above the fee the quote states; the
14
+ fee shown is the one the transaction takes. Anything else keeps the pinned trade, and the answer says why. Priors' gas
15
+ gate and Go mode hold Rialto's quotes to the same rule.
16
+ - **A sale through Rialto counts its quote against `PRIORS_MAX_STOCK_TOTAL_USD`** (GHSA-m3hr-g75r-gmcj): 0.17.0 counted
17
+ its transaction's minimum, up to the slippage under the quote. It counts the quote, as the pinned trade's does.
18
+ - **A dry run's `min_out` through Rialto holds on the live call** (GHSA-m3hr-g75r-gmcj): when Rialto's quote beat the
19
+ pinned pool by more than the slippage, the `min_out` a dry run printed was above the pinned pool's output, and the
20
+ live call stopped "the price moved past the slippage" before Rialto was asked. Rialto is asked now, and its route
21
+ taken only when its transaction's minimum is at least that `min_out`; otherwise the refusal stands.
22
+ - **The PT buys keep to `PRIORS_MAX_PT_TOTAL_USD` and keep back what signed payments still need**
23
+ (GHSA-hx6h-j9hm-9gvr, reported by @sonson0910). `pt_buy_and_deposit` (only with `PRIORS_PT_ONESTEP=on`) counted its
24
+ buy only after its chain reads and its consent: a call stalled in those reads past its hold was left out of the total
25
+ a later buy read, and both bought past the cap. Both PT buys now count their amount from the check, before any read,
26
+ until the call ends. Neither kept back the USDG of payments signed and not settled yet, as `save`, `stock_buy` and the
27
+ market tools do: a live buy that would spend it is now refused before anything is signed. And a buy whose swap did
28
+ nothing after its USDG approval (refused in its simulation, refused for gas, or mined and reverted) stayed counted, as
29
+ though it had spent its USDG: it counts nothing now, and the answer says so.
30
+ - `autopay_on` with savings approves shares worth the whole budget, and `credit_status` and the reserve never count a
31
+ plan of a wallet the agent no longer declares (@priors/x402 0.8.7).
32
+
3
33
  ## 0.17.0 (2026-11-04)
4
34
 
5
35
  On @priors/x402 0.8.6, as 0.16.0.
package/README.md CHANGED
@@ -44,7 +44,7 @@ repaying.
44
44
  | `find_services(query?)` | services registered with the Priors facilitator that accept USDG (`GET /merchants`): the ones Priors approved, and the ones under review whose own endpoint passed the facilitator's 402 check, marked so; hidden or unchecked ones are not listed | no |
45
45
  | `pt_quote(side, amount, slippage_bps?)` | quote buying PT-USDG with USDG, selling it before maturity or redeeming it after: what comes out at the oracle's spot rate, the minimum a trade would name, the days to maturity and the fixed APY to maturity | no |
46
46
  | `pt_position(address?)` | the wallet's (or any address's) PT-USDG: balance, what it is worth now, what it pays at maturity, and whether the Priors stock vault takes PT-USDG behind a line yet | no (with `address`) |
47
- | `pt_buy(amount_usdg, slippage_bps?, dry_run?)` | buy PT-USDG with the wallet's USDG through Pendle's router (at most `PRIORS_MAX_PT_USD` per call, `PRIORS_MAX_PT_TOTAL_USD` per run); `dry_run` lists the calls; needs ETH for gas | yes |
47
+ | `pt_buy(amount_usdg, slippage_bps?, dry_run?)` | buy PT-USDG with the wallet's USDG through Pendle's router (at most `PRIORS_MAX_PT_USD` per call, `PRIORS_MAX_PT_TOTAL_USD` per run), keeping back what payments signed and not settled yet still need; `dry_run` lists the calls; needs ETH for gas | yes |
48
48
  | `pt_sell(amount_pt \| "all", slippage_bps?, dry_run?)` | sell the wallet's PT-USDG for USDG at the market, before maturity; needs ETH for gas | yes |
49
49
  | `pt_redeem(amount_pt \| "all", slippage_bps?, dry_run?)` | redeem the wallet's PT-USDG for USDG 1:1, from maturity (2027-03-25) on; needs ETH for gas | yes |
50
50
  | `pt_buy_and_deposit(amount_usdg, agent_id?, include_held?, slippage_bps?, dry_run?)` | only with `PRIORS_PT_ONESTEP=on` (below): buy PT-USDG with the wallet's USDG and deposit it, with the PT-USDG the wallet already holds (unless `include_held` is false), behind the agent's line on the Priors stock vault, which opens the line, in one call: four transactions (the exact USDG approval, the buy with its minimum out, the exact PT-USDG approval to the vault, the vault's open with this wallet's pool consent). The wallet must own the agent, and the agent must have no open stock line; checked before the first is signed. `pt_buy`'s caps apply; `dry_run` lists the calls; needs ETH for gas | yes |
@@ -224,7 +224,10 @@ quoted by Rialto (docs.rialto.xyz), a swap router on Robinhood Chain. The quote
224
224
  (`priors_stockQuote` at `PRIORS_STOCK_QUOTE_URL`), which alone holds Rialto's API key: this server holds none and never
225
225
  calls Rialto itself. The answer is checked again here: the two tokens, the exact amount, this wallet as the taker, the
226
226
  router that Rialto's Router Registry names on chain (never one the answer names), a minimum within the slippage, Rialto's
227
- output and its minimum each within 5% of Chainlink's price, and a minimum never under the pinned trade's. Only when
227
+ output and its minimum each within 5% of Chainlink's price, and a minimum never under the pinned trade's (nor under a
228
+ `min_out` you pass). So is Rialto's transaction itself: the router's swap of those tokens and that amount, paid to this
229
+ wallet, with at least the quoted minimum, a deadline at most 30 minutes on, and no fee but Rialto's own (at most 5 bps,
230
+ paid to Rialto's address, and never above the fee its quote states). Only when
228
231
  Rialto gives strictly more of the token bought than the pinned pool does the trade go through Rialto: an approval of
229
232
  exactly the amount sold to that router, then Rialto's transaction, unchanged, its gas estimated first. If the estimate
230
233
  fails, the trade stops there and the answer says the approval stands; the next Rialto trade of that amount sends the
@@ -232,7 +235,7 @@ swap alone. Otherwise (Rialto's quote worse or equal, no quote, an error, no ans
232
235
  the pinned trade goes ahead exactly as without the setting, and the answer says why Rialto's route was not taken. A
233
236
  refusal above is never sent either way, and the gate is not asked for a trade that is refused. Priors takes no fee on
234
237
  either route; Rialto's own fee is part of its quote. The answer names the route, both quotes (the pinned pool's and
235
- Rialto's), Rialto's fee in basis points and its quote id, what the wallet received (its balance of the token bought,
238
+ Rialto's), Rialto's fee in basis points (the one its transaction takes) and its quote id, what the wallet received (its balance of the token bought,
236
239
  before and after), and the allowance left to Rialto's router, 0 after a full fill. `dry_run` asks the same and lists the
237
240
  route's transactions.
238
241
 
@@ -339,7 +342,7 @@ may spend. Rows marked (0.8.0) take effect from that version; 0.7.x ignores them
339
342
  | `PRIORS_AUTOPAY_RESERVE` | on | with Autopay on, `pay_url` keeps back what loans whose window opens in the next 24 h will pull, and says so when a payment would cut into it; `off` turns that off |
340
343
  | `PRIORS_PT` | on | `off` (or `false`, `0`, `no`) removes the PT-USDG tools |
341
344
  | `PRIORS_MAX_PT_USD` | `50` | most USDG one `pt_buy` may spend (sales and redemptions only turn the wallet's PT back into USDG) |
342
- | `PRIORS_MAX_PT_TOTAL_USD` | `200` | most USDG `pt_buy` and `pt_buy_and_deposit` may spend in total while the server runs (a buy whose transaction was sent counts, even if its answer is lost) |
345
+ | `PRIORS_MAX_PT_TOTAL_USD` | `200` | most USDG `pt_buy` and `pt_buy_and_deposit` may spend in total while the server runs, counted from the call's check (a buy whose swap was sent counts, even if its answer is lost; one whose swap did nothing counts nothing) |
343
346
  | `PRIORS_PT_ONESTEP` | off | `on`: `pt_buy_and_deposit` (PT-USDG bought and deposited behind the agent's line in one call), with the PT-USDG tools on |
344
347
  | `PRIORS_PAY_NETWORKS` | `eip155:4663` | networks `pay_url` pays on, comma-separated; add `eip155:8453` for USDC on Base (also needs `PRIORS_BRIDGE`). Robinhood Chain is always on |
345
348
  | `PRIORS_BRIDGE` | `off` | `across`: `fund_base` moves money out through Across (`relay`, the Relay route out, is not built yet); `return_to_robinhood` goes through Relay either way |
@@ -370,7 +373,7 @@ Settings → Developer → Edit Config (`claude_desktop_config.json`), then rest
370
373
  "mcpServers": {
371
374
  "priors": {
372
375
  "command": "npx",
373
- "args": ["-y", "@priors/mcp@0.17.0"],
376
+ "args": ["-y", "@priors/mcp@0.17.1"],
374
377
  "env": {
375
378
  "PRIORS_KEY": "0xYOUR_AGENT_WALLET_KEY",
376
379
  "PRIORS_AGENT_ID": "1234"
@@ -392,7 +395,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
392
395
  "mcpServers": {
393
396
  "priors": {
394
397
  "command": "npx",
395
- "args": ["-y", "@priors/mcp@0.17.0"],
398
+ "args": ["-y", "@priors/mcp@0.17.1"],
396
399
  "env": {
397
400
  "PRIORS_KEY": "${PRIORS_KEY}",
398
401
  "PRIORS_AGENT_ID": "${PRIORS_AGENT_ID:-}"
@@ -405,7 +408,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
405
408
  or, for your user only, from a macOS or Linux terminal:
406
409
 
407
410
  ```sh
408
- (read -rs PRIORS_KEY && umask 077 && mkdir -p ~/.config/priors && rm -f ~/.config/priors/agent.key && printf '%s\n' "$PRIORS_KEY" > ~/.config/priors/agent.key) && claude mcp add priors --scope user -- sh -c 'read -r PRIORS_KEY < "$1" && export PRIORS_KEY && exec npx -y @priors/mcp@0.17.0' priors-mcp ~/.config/priors/agent.key
411
+ (read -rs PRIORS_KEY && umask 077 && mkdir -p ~/.config/priors && rm -f ~/.config/priors/agent.key && printf '%s\n' "$PRIORS_KEY" > ~/.config/priors/agent.key) && claude mcp add priors --scope user -- sh -c 'read -r PRIORS_KEY < "$1" && export PRIORS_KEY && exec npx -y @priors/mcp@0.17.1' priors-mcp ~/.config/priors/agent.key
409
412
  ```
410
413
 
411
414
  It waits for the key without showing it (paste it, then Enter), saves it in a file only you can read, and gives Claude
@@ -486,7 +489,7 @@ to approve a borrow; this package, with the key, pays for APIs. With borrowing o
486
489
  approves each loan in Priors' Go mode. ElizaOS (`@elizaos/plugin-mcp`):
487
490
 
488
491
  ```ts
489
- "priors-wallet": { type: "stdio", command: "npx", args: ["-y", "@priors/mcp@0.17.0"],
492
+ "priors-wallet": { type: "stdio", command: "npx", args: ["-y", "@priors/mcp@0.17.1"],
490
493
  env: { PRIORS_KEY_FILE: "/home/agent/.config/priors/agent-7311.key", PRIORS_AGENT_ID: "7311",
491
494
  PRIORS_MAX_BORROW_USD: "0", PRIORS_MAX_BORROW_DAY_USD: "0", PRIORS_MAX_SPEND_DAY_USD: "1", PRIORS_MAX_PRICE_USD: "0.10",
492
495
  PRIORS_PAY_HOSTS: "api.example.com" } }
@@ -498,7 +501,7 @@ OpenClaw (`mcp.servers`, JSON5) takes the same `command`, `args` and `env`; Herm
498
501
  mcp_servers:
499
502
  priors-wallet:
500
503
  command: npx
501
- args: ["-y", "@priors/mcp@0.17.0"]
504
+ args: ["-y", "@priors/mcp@0.17.1"]
502
505
  env:
503
506
  PRIORS_KEY_FILE: /home/agent/.config/priors/agent-7311.key
504
507
  PRIORS_AGENT_ID: "7311"
@@ -525,7 +528,7 @@ key proves it is there: it signs the ERC-8004 identity registry's `AgentWalletSe
525
528
  agent's).
526
529
 
527
530
  ```sh
528
- PRIORS_KEY_FILE=~/.config/priors/agent-7311.key npx -y @priors/mcp@0.17.0 link-wallet --agent 7311
531
+ PRIORS_KEY_FILE=~/.config/priors/agent-7311.key npx -y @priors/mcp@0.17.1 link-wallet --agent 7311
529
532
  ```
530
533
 
531
534
  It reads the registry's EIP-712 domain and refuses to sign for any other, takes the owner from the chain (`--owner`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@priors/mcp",
3
3
  "mcpName": "io.github.priors-agents/priors",
4
- "version": "0.17.0",
4
+ "version": "0.17.1",
5
5
  "private": false,
6
6
  "description": "MCP server for Priors on Robinhood Chain: pay x402 URLs in USDG, read balances, credit lines and scores, borrow and repay, and buy, sell and redeem PT-USDG. Key from PRIORS_KEY_FILE (a file only you can read) or PRIORS_KEY, never the command line.",
7
7
  "type": "module",
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@modelcontextprotocol/sdk": "^1.30.1",
48
- "@priors/x402": "0.8.6",
48
+ "@priors/x402": "0.8.7",
49
49
  "ethers": "^6.13.4",
50
50
  "undici": "6.29.1",
51
51
  "viem": "^2.56.9",
package/src/rialto.mjs CHANGED
@@ -18,7 +18,8 @@
18
18
  // recipient and deadline, so checkQuote decodes it (checkSwap) and takes it only when it is the trade it checked, paid
19
19
  // to the taker, with at least the quote's minimum (GHSA-cqcw-9qjc-5qc7, reported by @hey-research-lab: @priors/mcp
20
20
  // 0.16.0 checked the JSON alone and sent the data as it came, so an answer could pay another address or drop the
21
- // minimum).
21
+ // minimum), and its fee words name Rialto's own fee, paid to Rialto, at most what the quote states (GHSA-m3hr-g75r-gmcj,
22
+ // reported by @sonson0910: 0.17.0 decoded them and checked none, and the router pays them to any address).
22
23
  //
23
24
  // RIALTO_REGISTRY, RIALTO_FEATURE, REGISTRY_ABI the registry that names Rialto's router (Rialto's API address is the
24
25
  // gate's alone, gas-worker/rialto.mjs: this file ships in @priors/mcp, which never calls Rialto)
@@ -27,6 +28,7 @@
27
28
  // decodeSwap(data) the router's swap call read: { sellToken, buyToken, sellAmount, minBuyAmount, recipient, deadline,
28
29
  // feeRecipient, srcBps, dstBps }, or throws RialtoError
29
30
  // checkSwap(data, o) that call taken only as the trade checked (checkQuote's last check), or throws RialtoError
31
+ // checkSwapFee(s, o) its fee words held to Rialto's own fee (RIALTO_FEE_RECIPIENT, RIALTO_FEE_BPS), or throws
30
32
  // chooseRoute(o) "rialto" when its quote gives more of the bought token than the pinned pool's, else "pinned"
31
33
  // rialtoCalls(terms) the two calls: the exact approval of the sold token to the router, then Rialto's transaction
32
34
  // wireTerms / readWire terms to JSON (amounts as digits) and back, checked again
@@ -60,6 +62,17 @@ export const SWAP_SELECTOR = "0x77963966";
60
62
  const SWAP_WORDS = 12, ACTIONS_AT = 0x180n;
61
63
  /** The latest deadline a quote's transaction may carry, from now (Rialto's is about 5 minutes on). */
62
64
  export const MAX_DEADLINE_S = 1800;
65
+ /**
66
+ * Rialto's fee on a swap, and where its router pays it. Rialto's docs: 0.05% a swap, inside the quoted output; every
67
+ * live router call read (the ones above) carries 5 bps on the USDG side (srcBps on a buy, dstBps on a sale), paid to
68
+ * 0xEc8a...cfDD (word 6). The router pays the fee words to whatever address word 6 names, up to 2,000 bps each, and
69
+ * checks the minimum after the fee (read 2026-11-04 by simulating the live router on the latest block): a fee to
70
+ * another address is a payment out of the trade's output the quote never named. So a quote's transaction is taken only
71
+ * with no fee, or Rialto's at most RIALTO_FEE_BPS to RIALTO_FEE_RECIPIENT; a change of either on Rialto's side falls back
72
+ * to the pinned pool until it is read again, as a change of the swap's layout does.
73
+ */
74
+ export const RIALTO_FEE_BPS = 5;
75
+ export const RIALTO_FEE_RECIPIENT = getAddress("0xec8acb43c45f4b98125df8cb5f42c963e5b3cfdd");
63
76
 
64
77
  export class RialtoError extends Error {
65
78
  constructor(message, o = {}) { super(message); this.name = "RialtoError"; Object.assign(this, o); }
@@ -99,9 +112,11 @@ export function quoteQuery({ sellToken, buyToken, sellAmount, sellDecimals, take
99
112
  * no integrator fee, and the taker holding enough (issues.balance). An approval Rialto asks for (issues.allowance) must
100
113
  * be to the router itself. Last, the transaction's data itself (checkSwap): the router's swap of those tokens and that
101
114
  * amount, paid to `taker`, its minimum at least the quote's and not above its output, its deadline after `now` (unix s,
102
- * the clock's by default) and at most MAX_DEADLINE_S on. -> frozen terms: { quoteId, router, spender, data, sellToken,
103
- * buyToken, sellAmount, buyAmount, minBuyAmount (the transaction's own minimum, what the router enforces), gas, feeBps,
104
- * legs }. Throws RialtoError (balance: true when the taker holds too little).
115
+ * the clock's by default) and at most MAX_DEADLINE_S on, its fee Rialto's own and at most the fee the quote states
116
+ * (platform_fee.total_bps: whole basis points, or none stated, never read as 0). -> frozen terms: { quoteId, router,
117
+ * spender, data, sellToken, buyToken, sellAmount, buyAmount, minBuyAmount (the transaction's own minimum, what the router
118
+ * enforces), gas, feeBps (the transaction's own fee, what the router takes), legs }. Throws RialtoError (balance: true
119
+ * when the taker holds too little).
105
120
  */
106
121
  export function checkQuote(body, { sellToken, buyToken, sellAmount, taker, router, slippageBps, now = Math.floor(Date.now() / 1000) }) {
107
122
  if (!body || typeof body !== "object") fail("Rialto's quote: not a quote");
@@ -128,13 +143,15 @@ export function checkQuote(body, { sellToken, buyToken, sellAmount, taker, route
128
143
  if (issues.balance != null) fail("not enough of the sold token for that amount", { balance: true });
129
144
  if (issues.allowance != null && !same(issues.allowance.spender, want.router)) fail("Rialto's quote: an approval to another spender");
130
145
  if (typeof body.quote_id !== "string" || !/^[0-9a-fA-F-]{8,64}$/.test(body.quote_id)) fail("Rialto's quote: no quote id");
131
- const feeBps = Number(body.platform_fee && body.platform_fee.total_bps);
132
- const swap = checkSwap(tx.data, { sellToken: want.sell, buyToken: want.buy, sellAmount: amount, taker: want.taker, minBuyAmount, buyAmount, now });
146
+ // the fee the quote states: whole basis points, or none (null: then only Rialto's own is taken, never "0 bps")
147
+ const pf = body.platform_fee && typeof body.platform_fee === "object" ? body.platform_fee.total_bps : null;
148
+ const stated = pf == null ? null : (Number.isSafeInteger(pf) && pf >= 0) || (typeof pf === "string" && DIGITS.test(pf) && pf.length <= 5) ? Number(pf) : fail("Rialto's quote: an unreadable fee");
149
+ const swap = checkSwap(tx.data, { sellToken: want.sell, buyToken: want.buy, sellAmount: amount, taker: want.taker, minBuyAmount, buyAmount, feeBps: stated, now });
133
150
  return Object.freeze({
134
151
  quoteId: body.quote_id, router: want.router, spender: want.router, data: tx.data.toLowerCase(),
135
152
  sellToken: want.sell, buyToken: want.buy, taker: want.taker, sellAmount: amount, buyAmount, minBuyAmount: swap.minBuyAmount,
136
153
  gas: Number.isSafeInteger(tx.estimated_gas) ? tx.estimated_gas : null,
137
- feeBps: Number.isFinite(feeBps) ? feeBps : null,
154
+ feeBps: swap.srcBps + swap.dstBps,
138
155
  legs: Array.isArray(body.route && body.route.legs) ? body.route.legs.length : null,
139
156
  });
140
157
  }
@@ -159,8 +176,9 @@ export function decodeSwap(data) {
159
176
 
160
177
  /** The router's swap call `data` taken only as the trade checked: `sellAmount` of `sellToken` for `buyToken`, paid to
161
178
  * `taker`, a minimum at least `minBuyAmount` (and not above `buyAmount` when given), a deadline after `now` (unix s)
162
- * and at most MAX_DEADLINE_S after it. -> decodeSwap's fields, or throws RialtoError with the reason. */
163
- export function checkSwap(data, { sellToken, buyToken, sellAmount, taker, minBuyAmount, buyAmount = null, now }) {
179
+ * and at most MAX_DEADLINE_S after it, its fee Rialto's own and at most `feeBps` when given (checkSwapFee).
180
+ * -> decodeSwap's fields, or throws RialtoError with the reason. */
181
+ export function checkSwap(data, { sellToken, buyToken, sellAmount, taker, minBuyAmount, buyAmount = null, feeBps = null, now }) {
164
182
  const s = decodeSwap(data);
165
183
  if (!same(s.sellToken, sellToken) || !same(s.buyToken, buyToken)) fail("Rialto's quote: its transaction swaps other tokens");
166
184
  if (s.sellAmount !== big(sellAmount, "sell amount")) fail("Rialto's quote: its transaction sells another amount");
@@ -170,9 +188,21 @@ export function checkSwap(data, { sellToken, buyToken, sellAmount, taker, minBuy
170
188
  const t = big(now, "now");
171
189
  if (s.deadline <= t) fail("Rialto's quote: its transaction's deadline has passed");
172
190
  if (s.deadline > t + BigInt(MAX_DEADLINE_S)) fail("Rialto's quote: its transaction's deadline is too far off");
191
+ checkSwapFee(s, { feeBps });
173
192
  return s;
174
193
  }
175
194
 
195
+ /** A decoded swap's fee words (decodeSwap's feeRecipient, srcBps, dstBps) held to Rialto's own fee: none at all (the
196
+ * zero address, 0 bps), or at most RIALTO_FEE_BPS in all paid to RIALTO_FEE_RECIPIENT, and never above `feeBps`, the
197
+ * fee the quote states, when given (GHSA-m3hr-g75r-gmcj). Throws RialtoError with the reason. */
198
+ export function checkSwapFee(s, { feeBps = null } = {}) {
199
+ const fee = s.srcBps + s.dstBps;
200
+ if (/^0x0{40}$/i.test(s.feeRecipient)) { if (fee !== 0) fail("Rialto's quote: its transaction's fee has no recipient"); }
201
+ else if (!same(s.feeRecipient, RIALTO_FEE_RECIPIENT)) fail("Rialto's quote: its transaction's fee is paid to another address than Rialto's");
202
+ if (fee > RIALTO_FEE_BPS) fail("Rialto's quote: its transaction's fee is above Rialto's");
203
+ if (feeBps != null && fee > feeBps) fail("Rialto's quote: its transaction's fee is above the quote's");
204
+ }
205
+
176
206
  /** The route a trade takes: "rialto" only when Rialto's terms give strictly more of the bought token than the pinned
177
207
  * pool's quote (`pinnedOut`, base units, null when no pinned pool serves the token), else "pinned" (null when neither
178
208
  * can: no pinned pool and no Rialto quote). Equal goes to the pinned pool, today's path. */
package/src/server.mjs CHANGED
@@ -2032,8 +2032,21 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2032
2032
  return [`${p.account}${wallet && p.account === wallet.address ? " (this server's wallet)" : ""} holds ${nf(p.balanceText)} PT-USDG${p.balance > 0n ? `, worth ${nf(p.valueText)} USDG now and ${nf(p.atMaturityText)} USDG at maturity` : ""}.`, termsLine(p), ...otherLines(p), listingLine(p.listing)].join("\n");
2033
2033
  });
2034
2034
 
2035
- /** One trade from the configured wallet: the SDK's calls, sent in order (each simulated, then waited for). */
2036
- async function ptTrade(kind, amount, slippage_bps, dry_run, market) {
2035
+ // A PT buy leaves the USDG that payments signed and not settled yet still need (heldForPayments, kept back as save,
2036
+ // stock_buy, first_line and the market tools keep it): a buy never spends it from under them (GHSA-hx6h-j9hm-9gvr).
2037
+ const heldWords = (held, have) => `${usd(held)} of the wallet's USDG is held for signed payments that have not settled yet; at most ${usd(have > held ? have - held : 0n)} can buy PT-USDG now. Nothing was signed or sent.`;
2038
+ const USDG_BAL = new ethers.Interface(["function balanceOf(address) view returns (uint256)"]);
2039
+ async function usdgHeld(account) {
2040
+ try { return USDG_BAL.decodeFunctionResult("balanceOf", await withinTime(provider.call({ to: P.PT_USDG.usdg, data: USDG_BAL.encodeFunctionData("balanceOf", [account]) }), requestTimeoutMs))[0]; } catch (e) {
2041
+ throw new ToolError(`the wallet's USDG could not be read just now (${explain(e)}), so what signed payments still need of it can't be kept back. Nothing was signed or sent.`);
2042
+ }
2043
+ }
2044
+ // the buy did nothing: said in the answer of a buy whose steps stopped after its approval
2045
+ const boughtNothing = (units) => ` The buy did nothing: its ${usd(units)} does not count against PRIORS_MAX_PT_TOTAL_USD.`;
2046
+
2047
+ /** One trade from the configured wallet: the SDK's calls, sent in order (each simulated, then waited for). `count` is
2048
+ * serial's: a buy's amount counts against PRIORS_MAX_PT_TOTAL_USD from its check until the call ends. */
2049
+ async function ptTrade(kind, amount, slippage_bps, dry_run, market, count) {
2037
2050
  const signer = needWallet(`pt_${kind}`);
2038
2051
  let units = null;
2039
2052
  if (kind === "buy") {
@@ -2041,6 +2054,9 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2041
2054
  if (units === 0n) throw new ToolError("amount_usdg must be above zero");
2042
2055
  if (units > maxPtCeiling) throw new ToolError(`amount_usdg ${X.formatUsdg(units)} is above this server's ceiling of ${usd(maxPtCeiling)} per buy (PRIORS_MAX_PT_USD).`);
2043
2056
  if (!dry_run && session.ptBought + units > ptTotalCap) throw new ToolError(`this would bring what pt_buy spent in this session to ${usd(session.ptBought + units)}, above ${usd(ptTotalCap)} (PRIORS_MAX_PT_TOTAL_USD).`);
2057
+ // what it may spend, from its check with no await between (GHSA-cq9v) until it ends: the keep back below reads the
2058
+ // chain, and a call made once the hold of one stalled there had ended would pass the cap beside it (GHSA-hx6h)
2059
+ if (!dry_run) count("ptBought", units);
2044
2060
  }
2045
2061
  const o = { account: signer.address, amount: units ?? amount, slippageBps: slippage_bps, ...(market ? { market } : {}) };
2046
2062
  if (dry_run) {
@@ -2048,6 +2064,13 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2048
2064
  try { b = await pt.trade(kind, o); } catch (e) { throw asked(e); }
2049
2065
  return [termsLine(b.quote), `Nothing was sent. From ${b.account}, ${b.calls.length} call${b.calls.length > 1 ? "s" : ""} in order:`, callsText(b), minLine(b), ...b.warnings.map((w) => `Note: ${w}.`)].join("\n");
2050
2066
  }
2067
+ if (units !== null) {
2068
+ const held = heldForPayments();
2069
+ if (held > 0n) {
2070
+ const have = await usdgHeld(signer.address);
2071
+ if (have < units + held) throw new ToolError(heldWords(held, have));
2072
+ }
2073
+ }
2051
2074
  // what left the wallet is counted even when the answer is lost: a send that started may have landed (GHSA-549m:
2052
2075
  // it was given back as "nothing sent" with the bare transport error). The SDK signs each step here first, so it
2053
2076
  // knows the hash before the broadcast and asks the node about it after a failure: mined goes on, pending is waited
@@ -2063,10 +2086,12 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2063
2086
  const was = (list) => `${list.length} transaction${list.length > 1 ? "s were" : " was"} sent (${list.join(", ")})`;
2064
2087
  if (e?.unconfirmed) throw new ToolError(`${done.length ? `${was(done)}, then another` : "A transaction"} may have been sent: its answer was lost (${why}).${units !== null ? ` Its ${usd(units)} stays counted against PRIORS_MAX_PT_TOTAL_USD.` : ""} Check pt_position and wallet_balance before trying again.`);
2065
2088
  // not unconfirmed: the steps that went through are the SDK's `hashes` (a refused or reverted step did nothing);
2066
- // an error before any step left carries none
2089
+ // an error before any step left carries none. The step that failed is the last that ran (sendCalls sends none
2090
+ // after it), and a buy's USDG moves only in its last step, the router's swap: a buy that failed spent nothing,
2091
+ // whatever approval went before it, and counts nothing (GHSA-hx6h-j9hm-9gvr)
2067
2092
  const went = Array.isArray(e?.hashes) ? done : sent.filter(Boolean);
2068
- if (went.length === 0 && units !== null) session.ptBought -= units;
2069
- if (went.length) throw new ToolError(`${was(went)}, then: ${why}. Check pt_position and wallet_balance before trying again.`);
2093
+ if (units !== null) session.ptBought -= units;
2094
+ if (went.length) throw new ToolError(`${was(went)}, then: ${why}.${units !== null ? boughtNothing(units) : ""} Check pt_position and wallet_balance before trying again.`);
2070
2095
  throw asked(e);
2071
2096
  }
2072
2097
  const done = kind === "buy" ? `Bought about ${nf(r.quote.expectedOutText)} PT-USDG (at least ${nf(r.quote.minOutText)}) with ${usd(units)}`
@@ -2080,7 +2105,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2080
2105
  description: `Buy PT-USDG (Pendle's principal token for USDG, redeemable 1:1 for USDG on ${P.PT_USDG.maturity.slice(0, 10)}) with the configured wallet's USDG, through Pendle's router: an approval of exactly that USDG, then the swap, paying the PT-USDG to this wallet with a minimum out. Held to maturity it pays a fixed amount of USDG; sold earlier, it gets the market's rate then, which can be lower. Moves real money: quote it (pt_quote), state the amount and what it buys to the user and get their go-ahead first; dry_run: true lists the calls without sending. Needs ETH for gas.`,
2081
2106
  inputSchema: { amount_usdg: z.number().positive().describe("USDG to spend, in US dollars (required, no default)."), slippage_bps: slippage, dry_run: dryRun },
2082
2107
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
2083
- }, serial(async ({ amount_usdg, slippage_bps, dry_run }) => ptTrade("buy", amount_usdg, slippage_bps, dry_run)));
2108
+ }, serial(async ({ amount_usdg, slippage_bps, dry_run }, _deadline, count) => ptTrade("buy", amount_usdg, slippage_bps, dry_run, undefined, count)));
2084
2109
 
2085
2110
  tool("pt_sell", {
2086
2111
  title: "Sell PT-USDG for USDG",
@@ -2107,8 +2132,9 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2107
2132
  // Refused before anything is signed: no wallet, or one that does not own the agent (the consent is its owner's); an
2108
2133
  // agent with an open or written-off position, defaulted, a root, or lent to by another backer; a default on this
2109
2134
  // wallet; the vault not taking new PT-USDG lines (ptListing); a line under the pool's smallest, over the shared cap's
2110
- // room or the week's; less USDG than the buy; pt_buy's caps (PRIORS_MAX_PT_USD, PRIORS_MAX_PT_TOTAL_USD, the same
2111
- // session total); a plan the core refuses. Four transactions are not one operation: the open refused after the buy
2135
+ // room or the week's; less USDG than the buy, or than the buy and what payments signed and not settled yet still
2136
+ // need; pt_buy's caps (PRIORS_MAX_PT_USD, PRIORS_MAX_PT_TOTAL_USD, the same session total, counted from the check);
2137
+ // a plan the core refuses. Four transactions are not one operation: the open refused after the buy
2112
2138
  // leaves the PT-USDG in this wallet, and the answer says so.
2113
2139
  if (ptOnestepOn) {
2114
2140
  const ONE = createRequire(import.meta.url)("./pt-onestep-core.cjs");
@@ -2147,13 +2173,17 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2147
2173
  dry_run: dryRun,
2148
2174
  },
2149
2175
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
2150
- }, serial(async ({ amount_usdg, agent_id, include_held, slippage_bps, dry_run }) => {
2176
+ }, serial(async ({ amount_usdg, agent_id, include_held, slippage_bps, dry_run }, _deadline, count) => {
2151
2177
  const signer = needWallet("pt_buy_and_deposit");
2152
2178
  const units = dollars(amount_usdg, "amount_usdg");
2153
2179
  const nothing = "Nothing was signed or sent.";
2154
2180
  if (units === 0n) throw new ToolError(`amount_usdg must be above zero. ${nothing}`);
2155
2181
  if (units > maxPtCeiling) throw new ToolError(`amount_usdg ${X.formatUsdg(units)} is above this server's ceiling of ${usd(maxPtCeiling)} per buy (PRIORS_MAX_PT_USD). ${nothing}`);
2156
2182
  if (!dry_run && session.ptBought + units > ptTotalCap) throw new ToolError(`this would bring what pt_buy and pt_buy_and_deposit spent in this session to ${usd(session.ptBought + units)}, above ${usd(ptTotalCap)} (PRIORS_MAX_PT_TOTAL_USD). ${nothing}`);
2183
+ // what it may spend, from its check with no await between (GHSA-cq9v) until it ends: counted only at its send, after
2184
+ // the reads and the consent below, a call made once the hold of one stalled in them had ended passed the cap beside
2185
+ // it (GHSA-hx6h-j9hm-9gvr)
2186
+ if (!dry_run) count("ptBought", units);
2157
2187
  const id = await resolveAgent(agent_id);
2158
2188
  const me = signer.address;
2159
2189
  let r;
@@ -2171,6 +2201,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2171
2201
  if (r.agent.sponsor !== 0n && r.agent.sponsor !== r.root && r.agent.activeLoans !== 0n) throw new ToolError(`Agent #${id} has an open loan with another backer: repay it first. ${nothing}`);
2172
2202
  if (!r.listing || !r.listing.backsLines) throw new ToolError(`${P.ptListingText(r.listing, { cap: (u) => `${X.formatUsdg(u)} USDG`, where: ptLink(GO_APP_URL) })} ${nothing}`);
2173
2203
  if (r.usdgHave < units) throw new ToolError(`${me} holds ${X.formatUsdg(r.usdgHave)} USDG, less than the ${X.formatUsdg(units)} this buy takes. ${nothing}`);
2204
+ if (!dry_run) { const held = heldForPayments(); if (held > 0n && r.usdgHave < units + held) throw new ToolError(heldWords(held, r.usdgHave)); }
2174
2205
  let p;
2175
2206
  try { p = ONE.plan({ conf, usdgIn: units, rate: r.rate, rateAt: r.t, now: r.t, slippageBps: slippage_bps, held: r.ptHave, includeHeld: include_held !== false }); } catch (e) { throw new ToolError(`${PLAN_WORDS[e.code] || clean(e.message, 200)}. ${nothing}`); }
2176
2207
  // the line the vault would open on that deposit, and what it would refuse of it
@@ -2214,8 +2245,11 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2214
2245
  const was = (list) => `${list.length} transaction${list.length > 1 ? "s were" : " was"} sent (${list.join(", ")})`;
2215
2246
  const bought = done.length >= 2 ? ` The buy went through: the PT-USDG it bought stays in this wallet (pt_position shows it), to deposit from Go mode's Pendle tab (${ptLink(GO_APP_URL)}) or sell (pt_sell).` : "";
2216
2247
  if (e?.unconfirmed) throw new ToolError(`${done.length ? `${was(done)}, then another` : "A transaction"} may have been sent: its answer was lost (${why}). Its ${usd(units)} stays counted against PRIORS_MAX_PT_TOTAL_USD.${bought} Check pt_position and stock_position before trying again.`);
2217
- if (done.length === 0) session.ptBought -= units;
2218
- if (done.length) throw new ToolError(`${was(done)}, then: ${why}.${bought} Check pt_position and stock_position before trying again.`);
2248
+ // not unconfirmed: the step that failed did nothing and none after it was sent. The USDG moves only in the buy,
2249
+ // the second of the four steps: with fewer than two through (the USDG approval at most), nothing was spent and
2250
+ // nothing counts (GHSA-hx6h-j9hm-9gvr); from the buy on, its USDG was spent and stays counted
2251
+ if (done.length < 2) session.ptBought -= units;
2252
+ if (done.length) throw new ToolError(`${was(done)}, then: ${why}.${bought || boughtNothing(units)} Check pt_position and stock_position before trying again.`);
2219
2253
  throw new ToolError(`${why}. ${nothing}`);
2220
2254
  }
2221
2255
  let after = null;
@@ -44,10 +44,13 @@
44
44
  // again (sdk/rialto.mjs readWire, then checkQuote against the trade asked, with the router that Rialto's Router Registry
45
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
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).
47
+ // checkSwap, GHSA-cqcw-9qjc-5qc7; its fee Rialto's own, paid to Rialto, GHSA-m3hr-g75r-gmcj), its output and its
48
+ // minimum within Chainlink's 5%, its minimum never under the pinned trade's (nor the caller's `minOut`: a minOut over
49
+ // the pinned pool's output, which a dry run through Rialto prints, asks Rialto rather than stopping MOVED, and takes
50
+ // Rialto's route only when its transaction's minimum holds it). Rialto's route is taken only when it gives strictly
51
+ // more of the token bought than the pinned pool (chooseRoute): the sold token approved to that router for exactly the
52
+ // amount, then Rialto's transaction unchanged, its gas estimated after the approval (a failing estimate stops the
53
+ // trade, the approval named).
51
54
  // After the receipt: what the account received (its balance of the bought token before and after) and the router's
52
55
  // allowance (0 after a full fill). Any other answer, an error, no answer within RIALTO_WAIT_MS (8 s) or a check failing:
53
56
  // today's pinned trade, the plan saying why (rialtoWhy). Priors takes no fee on either route.
@@ -338,7 +341,8 @@ async function askGate({ url = STOCK_QUOTE_URL, fetch: f = globalThis.fetch, tim
338
341
  * pool's quote) }. Taking Rialto's route, the plan's out, minOut, label, spender, allowance, deviationBps, valueUsdg and
339
342
  * calls are Rialto's: the exact approval of the sold token to the registry's router (left out when its allowance already
340
343
  * 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.
344
+ * check); a sale's valueUsdg is Rialto's quoted output, as the pinned trade's is its quote (GHSA-m3hr-g75r-gmcj: 0.17.0
345
+ * counted the minimum, up to the slippage under it). Never throws for Rialto: whatever fails keeps the pinned trade.
342
346
  */
343
347
  export async function rialtoRoute(client, p, o = {}, conf = ZAP) {
344
348
  const buy = p.side === "buy";
@@ -394,7 +398,7 @@ export async function rialtoRoute(client, p, o = {}, conf = ZAP) {
394
398
  ];
395
399
  return {
396
400
  ...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,
401
+ impactBps: null, deviationBps: off(t.buyAmount), valueUsdg: buy ? p.amountIn : t.buyAmount, allowance, calls,
398
402
  };
399
403
  }
400
404
 
@@ -539,9 +543,18 @@ export async function stockTrade(client, o = {}, conf = ZAP) {
539
543
  }
540
544
 
541
545
  /** A quote and the calls, sent nothing: stockTradePlan for `side`, and with `o.rialto` Rialto's route for it
542
- * (rialtoRoute). */
546
+ * (rialtoRoute). With `o.rialto` and a caller's `minOut` the pinned pool's quote is under (MOVED), Rialto is still
547
+ * asked, on the plan made without it, and its route is taken only when its transaction's minimum is at least that
548
+ * minOut; otherwise the MOVED refusal stands (GHSA-m3hr-g75r-gmcj: a dry run through Rialto prints Rialto's minimum,
549
+ * which can be over the pinned pool's output). */
543
550
  export const stockQuote = async (client, o = {}, conf = ZAP) => {
544
- const p = await stockTradePlan(client, o, conf);
551
+ let p;
552
+ try { p = await stockTradePlan(client, o, conf); } catch (e) {
553
+ if (!o.rialto || o.minOut == null || !(e instanceof StockTradeError) || e.code !== "MOVED") throw e;
554
+ const r = await rialtoRoute(client, await stockTradePlan(client, { ...o, minOut: null }, conf), o, conf);
555
+ if (r.route === "rialto" && r.minOut >= BigInt(o.minOut)) return r;
556
+ throw e;
557
+ }
545
558
  return o.rialto ? rialtoRoute(client, p, o, conf) : p;
546
559
  };
547
560
  /** Buy `amount` USDG of `symbol`: the calls, sent when `wallet` is given. */