@priors/mcp 0.6.4 → 0.7.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.
Files changed (3) hide show
  1. package/README.md +36 -4
  2. package/package.json +2 -2
  3. package/src/server.mjs +387 -30
package/README.md CHANGED
@@ -40,6 +40,8 @@ repaying.
40
40
  | `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 |
41
41
  | `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 |
42
42
  | `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 |
43
+ | `fund_base(amount_usd, max_borrow_usd?)` | only with Base on (below): move USDG to USDC in the same address on Base through Across, keeping back what Autopay and signed payments need, borrowing the gap only with `max_borrow_usd`; needs ETH for gas | yes |
44
+ | `return_to_robinhood(amount_usd \| "all")` | only with Base on: move USDC from the Base float back to USDG on Robinhood Chain through Relay, one signature and no gas on Base; keeps back what signed Base payments need | yes |
43
45
 
44
46
  Tools that move money state the amounts in their answer, are marked destructive for MCP clients, and their
45
47
  descriptions tell the assistant to confirm with you first. They run one at a time and each answers within 45 s, under an
@@ -91,6 +93,27 @@ trade may need a wider margin.
91
93
  Once the Priors stock vault lists PT-USDG, an agent's owner can post it behind a line (`pt_position` says when);
92
94
  until then it is a token the wallet holds. `PRIORS_PT=off` removes the five tools.
93
95
 
96
+ ## Paying USDC sellers on Base (off by default)
97
+
98
+ Many x402 sellers (search, market data, model calls) take USDC on Base only. With `PRIORS_PAY_NETWORKS` naming
99
+ `eip155:8453` and `PRIORS_BRIDGE=across`, the agent keeps a small USDC balance on Base, its Base float, and `pay_url`
100
+ pays those sellers from it. Without both settings nothing changes.
101
+
102
+ - `fund_base` moves USDG from the wallet on Robinhood Chain to USDC in the same address on Base through Across, in a
103
+ few seconds. It keeps back what Autopay loans pull in the next 24 hours and what signed payments still need, refuses
104
+ a fee above `PRIORS_MAX_BRIDGE_FEE_BPS`, keeps the float at most `PRIORS_MAX_BASE_FLOAT_USD`, and borrows the gap
105
+ from the line only with `max_borrow_usd` covering that loan (the gap, or the pool's minimum loan if that is more; a
106
+ short answer names the amount). That loan counts like any other, and is repaid in USDG on Robinhood Chain.
107
+ - `pay_url` pays a USDC 402 on Base from the float, never from a loan; a float short of the price is refused before
108
+ anything is signed, with a pointer to `fund_base`. USDC that a return to Robinhood Chain still in flight may pull is
109
+ not counted as free. A seller that takes both is paid in USDG.
110
+ - `return_to_robinhood` brings USDC back as USDG through Relay, with one signature and no gas on Base. The signature is
111
+ checked field by field and rebuilt before it is signed.
112
+ - One transfer at a time per wallet: while one is on its way (kept on file next to the payments, so a restart or
113
+ another session sees it), `fund_base` and `return_to_robinhood` do nothing; payments, `borrow` and `repay` go on.
114
+ `wallet_balance` and `credit_status` show the float and any transfer in flight, and `credit_status` warns when a
115
+ loan is due within 24 hours while money sits on Base.
116
+
94
117
  ## Configure
95
118
 
96
119
  The only secret is the wallet key, and it is read from the environment variable `PRIORS_KEY`, never from the command
@@ -120,6 +143,14 @@ dedicated agent wallet holding only what the agent may spend.
120
143
  | `PRIORS_PT` | on | `off` (or `false`, `0`, `no`) removes the PT-USDG tools |
121
144
  | `PRIORS_MAX_PT_USD` | `50` | most USDG one `pt_buy` may spend (sales and redemptions only turn the wallet's PT back into USDG) |
122
145
  | `PRIORS_MAX_PT_TOTAL_USD` | `200` | most USDG `pt_buy` may spend in total while the server runs (a buy whose transaction was sent counts, even if its answer is lost) |
146
+ | `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 |
147
+ | `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 |
148
+ | `PRIORS_BASE_RPC` | `https://mainnet.base.org` | Base JSON-RPC endpoint, read only (a private URL is redacted from every answer) |
149
+ | `PRIORS_BRIDGE_TIMEOUT_S` | `30` | longest `fund_base` and `return_to_robinhood` wait for the money to land, never past the call's own 45 s; one still on its way is reported as in flight |
150
+ | `PRIORS_MAX_BRIDGE_USD` | `10` | most one `fund_base` or `return_to_robinhood` may move |
151
+ | `PRIORS_MAX_BRIDGE_TOTAL_USD` | `25` | most both may move in total while the server runs, either way (a transfer that may be out counts, and one in flight when the server starts counts too) |
152
+ | `PRIORS_MAX_BRIDGE_FEE_BPS` | `100` | a bridge fee above this, in basis points of the amount, is refused |
153
+ | `PRIORS_MAX_BASE_FLOAT_USD` | `10` | `fund_base` never brings the Base float above this |
123
154
  | `PRIORS_STATE_DIR` | `~/.local/state/priors-mcp` | where the payments signed and not yet settled are kept (one owner-only file per wallet, never the key, with a short-lived `.lock` beside it while it is written), so a restart, a new session or another session of the same wallet resends them instead of signing again. An absolute path, or one starting with `~/` (a relative one is refused at start). A payment that cannot be written there is not sent. `off` keeps them in memory only |
124
155
 
125
156
  Contract addresses (pool, lens, registry, USDG) come from `deployments/4663.v2.json`, bundled in the package, and the
@@ -135,7 +166,7 @@ Settings → Developer → Edit Config (`claude_desktop_config.json`), then rest
135
166
  "mcpServers": {
136
167
  "priors": {
137
168
  "command": "npx",
138
- "args": ["-y", "@priors/mcp@0.6.4"],
169
+ "args": ["-y", "@priors/mcp@0.7.0"],
139
170
  "env": {
140
171
  "PRIORS_KEY": "0xYOUR_AGENT_WALLET_KEY",
141
172
  "PRIORS_AGENT_ID": "1234"
@@ -157,7 +188,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
157
188
  "mcpServers": {
158
189
  "priors": {
159
190
  "command": "npx",
160
- "args": ["-y", "@priors/mcp@0.6.4"],
191
+ "args": ["-y", "@priors/mcp@0.7.0"],
161
192
  "env": {
162
193
  "PRIORS_KEY": "${PRIORS_KEY}",
163
194
  "PRIORS_AGENT_ID": "${PRIORS_AGENT_ID:-}"
@@ -167,7 +198,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
167
198
  }
168
199
  ```
169
200
 
170
- or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.6.4`
201
+ or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.7.0`
171
202
  (the key is expanded by your shell from the environment; do not paste it on the command line).
172
203
 
173
204
  ## Try it
@@ -178,4 +209,5 @@ prices" · "Pay https://api.example.com/report, up to 5 cents" · "Borrow $5 for
178
209
  ## Tests
179
210
 
180
211
  `npm run test:packages` in the Priors repository lists and calls every tool through the MCP SDK's in-memory client and
181
- over stdio, and checks that the key never appears in any output or error.
212
+ over stdio, and checks that the key never appears in any output or error. `scripts/test-x402-base.mjs` covers the
213
+ Base tools: their caps, one money call at a time, a restart with a transfer in flight, and the default being off.
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.6.4",
4
+ "version": "0.7.0",
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 only.",
7
7
  "type": "module",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "dependencies": {
45
45
  "@modelcontextprotocol/sdk": "^1.30.1",
46
- "@priors/x402": "0.5.0",
46
+ "@priors/x402": "0.6.0",
47
47
  "ethers": "^6.13.4",
48
48
  "undici": "6.29.0",
49
49
  "viem": "^2.56.9",
package/src/server.mjs CHANGED
@@ -36,6 +36,24 @@
36
36
  // PRIORS_PT "off": no PT-USDG tool (default on: the market is Pendle's, live on Robinhood Chain)
37
37
  // PRIORS_MAX_PT_USD most USDG one pt_buy may spend (default 50); sales and redemptions only turn PT back into USDG
38
38
  // PRIORS_MAX_PT_TOTAL_USD most USDG pt_buy may spend in total while the server runs (default 200)
39
+ //
40
+ // Paying USDC sellers on Base (docs/X402-BASE-PLAN.md, phase 1). Off by default: nothing below changes anything unless
41
+ // PRIORS_PAY_NETWORKS names eip155:8453 AND PRIORS_BRIDGE is across or relay. Then pay_url also pays x402 URLs that take
42
+ // USDC on Base only, from the USDC this wallet holds on Base (its Base float), and two tools move money between the
43
+ // float and Robinhood Chain: fund_base (USDG out through Across, borrowing the gap only when asked) and
44
+ // return_to_robinhood (USDC back through Relay, gasless). Loans and repayments stay on Robinhood Chain.
45
+ // PRIORS_PAY_NETWORKS comma-separated CAIP-2 networks pay_url pays on (default eip155:4663, always on; add
46
+ // eip155:8453 for Base)
47
+ // PRIORS_BRIDGE off (default), across (fund_base through Across) or relay (the Relay route out is phase 2:
48
+ // fund_base says so); return_to_robinhood goes through Relay either way
49
+ // PRIORS_BASE_RPC Base JSON-RPC endpoint (default the public https://mainnet.base.org); cut from answers like
50
+ // PRIORS_RPC
51
+ // PRIORS_BRIDGE_TIMEOUT_S longest fund_base and return_to_robinhood wait for the money to land (default 30; never
52
+ // past the call's own time budget)
53
+ // PRIORS_MAX_BRIDGE_USD most one fund_base or return_to_robinhood may move (default 10)
54
+ // PRIORS_MAX_BRIDGE_TOTAL_USD most both may move in total while the server runs, either way (default 25)
55
+ // PRIORS_MAX_BRIDGE_FEE_BPS a bridge fee above this, in basis points of the amount, is refused (default 100)
56
+ // PRIORS_MAX_BASE_FLOAT_USD fund_base never brings the Base float above this (default 10)
39
57
  import { readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, statSync, rmSync } from "node:fs";
40
58
  import { homedir } from "node:os";
41
59
  import { isAbsolute, join } from "node:path";
@@ -55,13 +73,13 @@ import * as P from "./pt-usdg.mjs";
55
73
  // @priors/x402 when installed from npm; the sibling package in the monorepo otherwise.
56
74
  async function loadX402() {
57
75
  try {
58
- return { X: await import("@priors/x402"), C: await import("@priors/x402/credit"), S: await import("@priors/x402/savings"), A: await import("@priors/x402/autopay") };
76
+ return { X: await import("@priors/x402"), C: await import("@priors/x402/credit"), S: await import("@priors/x402/savings"), A: await import("@priors/x402/autopay"), B: await import("@priors/x402/bridge") };
59
77
  } catch (e) {
60
78
  if (e?.code !== "ERR_MODULE_NOT_FOUND" || !String(e.message).includes("@priors/x402")) throw e;
61
- return { X: await import("../../x402/index.mjs"), C: await import("../../x402/src/credit.mjs"), S: await import("../../x402/src/savings.mjs"), A: await import("../../x402/src/autopay.mjs") };
79
+ return { X: await import("../../x402/index.mjs"), C: await import("../../x402/src/credit.mjs"), S: await import("../../x402/src/savings.mjs"), A: await import("../../x402/src/autopay.mjs"), B: await import("../../x402/src/bridge.mjs") };
62
80
  }
63
81
  }
64
- const { X, C, S, A } = await loadX402();
82
+ const { X, C, S, A, B } = await loadX402();
65
83
 
66
84
  export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
67
85
  const ADDRESSES = JSON.parse(readFileSync(new URL("../deployments/4663.v2.json", import.meta.url), "utf8"));
@@ -219,7 +237,30 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
219
237
  const ptOn = !/^(off|false|0|no|none)$/i.test(String(env.PRIORS_PT ?? "").trim());
220
238
  const maxPtCeiling = envDollars(env, "PRIORS_MAX_PT_USD", 50);
221
239
  const ptTotalCap = envDollars(env, "PRIORS_MAX_PT_TOTAL_USD", 200);
222
- const session = { spent: 0n, borrowed: 0n, saved: 0n, ptBought: 0n };
240
+ // Base (docs/X402-BASE-PLAN.md phase 1): on only when PRIORS_PAY_NETWORKS names eip155:8453 AND PRIORS_BRIDGE picks a
241
+ // route. Off, the server is exactly as before: no Base provider, no Base tool, pay_url pays Robinhood Chain only, and
242
+ // the other Base settings are not read (a value these two cannot parse stops the start, as PRIORS_STATE_DIR's does).
243
+ // Neither value is ever echoed: a key pasted into one must not reach a log.
244
+ let payNets;
245
+ try { payNets = X.payNetworks(env.PRIORS_PAY_NETWORKS); } catch (_) { throw new Error(`PRIORS_PAY_NETWORKS must list networks this server pays on, comma-separated (${Object.keys(X.NETWORKS).join(", ")})`); }
246
+ const bridgeRaw = String(env.PRIORS_BRIDGE ?? "").trim().toLowerCase();
247
+ if (bridgeRaw && !/^(off|false|0|no|none|across|relay)$/.test(bridgeRaw)) throw new Error("PRIORS_BRIDGE must be off, across or relay");
248
+ const bridgeRoute = bridgeRaw === "across" || bridgeRaw === "relay" ? bridgeRaw : null;
249
+ const baseOn = payNets.includes(X.BASE_USDC.network) && bridgeRoute !== null;
250
+ // Robinhood Chain is always paid on: the line, the savings and every other tool live there.
251
+ const networks = baseOn ? [X.ROBINHOOD_USDG.network, X.BASE_USDC.network] : [X.ROBINHOOD_USDG.network];
252
+ const envInt = (name, dflt, lo, hi) => {
253
+ const raw = String(env[name] ?? "").trim();
254
+ if (raw === "") return dflt;
255
+ if (!/^\d{1,7}$/.test(raw) || Number(raw) < lo || Number(raw) > hi) throw new Error(`${name} must be a whole number from ${lo} to ${hi}`);
256
+ return Number(raw);
257
+ };
258
+ const bridgeTimeoutMs = baseOn ? envInt("PRIORS_BRIDGE_TIMEOUT_S", 30, 1, 600) * 1000 : 0;
259
+ const maxBridgeCeiling = baseOn ? envDollars(env, "PRIORS_MAX_BRIDGE_USD", 10) : 0n;
260
+ const bridgeTotalCap = baseOn ? envDollars(env, "PRIORS_MAX_BRIDGE_TOTAL_USD", 25) : 0n;
261
+ const maxBridgeFeeBps = baseOn ? envInt("PRIORS_MAX_BRIDGE_FEE_BPS", 100, 0, 1000) : 0;
262
+ const maxBaseFloat = baseOn ? envDollars(env, "PRIORS_MAX_BASE_FLOAT_USD", 10) : 0n;
263
+ const session = { spent: 0n, borrowed: 0n, saved: 0n, ptBought: 0n, bridged: 0n };
223
264
  const allowLocal = env.PRIORS_ALLOW_LOCAL === "1";
224
265
  const lookup = deps.lookup || ((host) => dnsLookup(host, { all: true }));
225
266
  const sleep = deps.sleep; // undefined: the library's own
@@ -316,10 +357,12 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
316
357
  const h = rawKey.replace(/^0x/i, "").replace(/[^0-9a-zA-Z]/g, "");
317
358
  if (h.length >= 16) secrets.push(new RegExp(`(0x)?${[...h].join("[\\s\"'+,\\-]{0,3}")}`, "gi"));
318
359
  }
319
- if (env.PRIORS_RPC && env.PRIORS_RPC !== X.robinhood.rpcUrl) {
320
- const parts = [env.PRIORS_RPC];
360
+ // A private RPC endpoint: PRIORS_RPC, and PRIORS_BASE_RPC (set, it is cut whether or not Base is on).
361
+ for (const [raw, pub] of [[env.PRIORS_RPC, X.robinhood.rpcUrl], [env.PRIORS_BASE_RPC, X.BASE_USDC.rpcUrl]]) {
362
+ if (!raw || raw === pub) continue;
363
+ const parts = [raw];
321
364
  try {
322
- const u = new URL(env.PRIORS_RPC);
365
+ const u = new URL(raw);
323
366
  // the hostname alone too: with a port, u.host is "name:port", and a DNS error names the bare hostname
324
367
  parts.push(u.href, u.host, u.hostname, u.hostname.replace(/^\[|\]$/g, ""), u.username, u.password);
325
368
  for (const seg of u.pathname.split("/")) if (seg.length >= 8) parts.push(seg, decodeURIComponent(seg));
@@ -336,6 +379,9 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
336
379
  // answers a batch that size with HTTP 429, which ethers retries until its 5-minute timeout (stock_assets' ~140 reads).
337
380
  const provider = deps.provider || new ethers.JsonRpcProvider(rpc, ethers.Network.from(X.robinhood.chainId), { staticNetwork: true, cacheTimeout: -1, batchMaxCount: 1 });
338
381
  const wallet = key ? new ethers.Wallet(key, provider) : null;
382
+ // Base, read only (the Base float's balance; USDC's authorization state): payments there are signatures, and the way
383
+ // back is Relay's gasless route, so this server never sends a transaction on Base.
384
+ const baseProvider = !baseOn ? null : deps.baseProvider || new ethers.JsonRpcProvider(env.PRIORS_BASE_RPC || X.BASE_USDC.rpcUrl, ethers.Network.from(X.BASE_USDC.chainId), { staticNetwork: true, cacheTimeout: -1, batchMaxCount: 1 });
339
385
  // The payments this wallet signed and has not seen settle outlive the process (a restart, or the client closing its
340
386
  // session, starts a new one): one file per wallet under PRIORS_STATE_DIR (default ~/.local/state/priors-mcp; "off"
341
387
  // disables it), owner-only. It holds signed authorizations, each payable only to the merchant it was sent to, never the key.
@@ -346,11 +392,13 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
346
392
  if (stateHome && !/^(off|none|false|0)$/i.test(stateHome) && !isAbsolute(stateHome)) throw new Error(`PRIORS_STATE_DIR must be an absolute path (or start with ~/), not "${stateRaw}"`);
347
393
  const stateDir = /^(off|none|false|0)$/i.test(stateRaw) ? null : stateHome || join(homedir(), ".local", "state", "priors-mcp");
348
394
  const stateFile = wallet && stateDir ? join(stateDir, `outstanding-${wallet.address.toLowerCase()}.json`) : null;
349
- // An entry is { paymentHeaders, validBefore, price, payTo, borrowed, loanId }: only what this server wrote, never the
350
- // merchant's requirement object (its fields are the merchant's to choose). On disk the amounts are decimal strings;
351
- // each entry is checked on its own, so one bad entry never costs the others. No reviver.
395
+ // An entry is { paymentHeaders, validBefore, price, payTo, borrowed, loanId, network, asset }: only what this server
396
+ // wrote, never the merchant's requirement object (its fields are the merchant's to choose). On disk the amounts are
397
+ // decimal strings; each entry is checked on its own, so one bad entry never costs the others. No reviver. An entry an
398
+ // older server wrote has no network: it is Robinhood Chain USDG, the only one it paid on.
352
399
  const live = (e, nowS) => e.validBefore + X.SKEW_SECONDS > nowS;
353
400
  const DEC = /^\d{1,30}$/;
401
+ const onRobinhood = (e) => (e.network ?? X.ROBINHOOD_USDG.network) === X.ROBINHOOD_USDG.network;
354
402
  function entryFrom(v) {
355
403
  if (!v || typeof v !== "object" || !v.paymentHeaders || typeof v.paymentHeaders !== "object") return null;
356
404
  const headers = {};
@@ -359,7 +407,11 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
359
407
  if (Object.keys(headers).length === 0 || !Number.isSafeInteger(validBefore) || !DEC.test(String(v.price)) || !ethers.isAddress(String(v.payTo))) return null;
360
408
  const borrowed = DEC.test(String(v.borrowed ?? "0")) ? BigInt(v.borrowed ?? "0") : 0n;
361
409
  const loanId = v.loanId !== null && v.loanId !== undefined && DEC.test(String(v.loanId)) ? BigInt(v.loanId) : null;
362
- return { paymentHeaders: headers, validBefore, price: BigInt(v.price), payTo: String(v.payTo), borrowed, loanId };
410
+ const net = X.networkOf(v.network === undefined || v.network === null ? X.ROBINHOOD_USDG.network : String(v.network));
411
+ if (!net) return null;
412
+ const asset = v.asset === undefined || v.asset === null ? (net === X.ROBINHOOD_USDG && ethers.isAddress(String(addresses.usdg)) ? ethers.getAddress(String(addresses.usdg)) : net.asset) : ethers.isAddress(String(v.asset)) ? ethers.getAddress(String(v.asset)) : null;
413
+ if (!asset) return null;
414
+ return { paymentHeaders: headers, validBefore, price: BigInt(v.price), payTo: String(v.payTo), borrowed, loanId, network: net.network, asset };
363
415
  }
364
416
  function readState() {
365
417
  const m = new Map();
@@ -373,7 +425,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
373
425
  function writeState(m) {
374
426
  mkdirSync(stateDir, { recursive: true, mode: 0o700 });
375
427
  const tmp = `${stateFile}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
376
- const out = Object.fromEntries([...m].map(([k, e]) => [k, { paymentHeaders: e.paymentHeaders, validBefore: e.validBefore, price: String(e.price), payTo: e.payTo, borrowed: String(e.borrowed || 0n), loanId: e.loanId === null || e.loanId === undefined ? null : String(e.loanId) }]));
428
+ const out = Object.fromEntries([...m].map(([k, e]) => [k, { paymentHeaders: e.paymentHeaders, validBefore: e.validBefore, price: String(e.price), payTo: e.payTo, borrowed: String(e.borrowed || 0n), loanId: e.loanId === null || e.loanId === undefined ? null : String(e.loanId), network: e.network ?? X.ROBINHOOD_USDG.network, ...(e.asset ? { asset: e.asset } : {}) }]));
377
429
  writeFileSync(tmp, JSON.stringify(out), { mode: 0o600 });
378
430
  renameSync(tmp, stateFile);
379
431
  }
@@ -424,6 +476,127 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
424
476
  if (stateFile) { try { await locked(() => { const m = readState(); if (same(m.get(key)) && m.delete(key)) writeState(m); }); } catch (_) { /* best effort */ } }
425
477
  }
426
478
  refresh();
479
+
480
+ // ---- The Base float's transfer in flight (fund_base / return_to_robinhood) ----------------------------------------
481
+ // At most one transfer between Robinhood Chain and Base is in flight per wallet. Its record is written before the
482
+ // money can leave (fundBase's onDepositSending, returnToRobinhood's onSigned) to its own file next to the payments
483
+ // (bridge-<wallet>.json, owner-only, under the same lock), and read back at start and by every session of the wallet.
484
+ // While it stands, fund_base, return_to_robinhood and borrowing for a bridge do nothing; payments, borrow and repay
485
+ // go on (an Across refund can take hours, and must not freeze the agent's ordinary USDG payments). It ends when the
486
+ // route reports the transfer done (Across filled or refunded, Relay success), or once nothing more can happen to it:
487
+ // an Across deposit 12 h past its fill deadline (Across refunds an expired one within hours), a Relay authorization
488
+ // past its validBefore (it can no longer be used). Its amount counts against PRIORS_MAX_BRIDGE_TOTAL_USD, from start.
489
+ const bridgeFile = wallet && stateDir ? join(stateDir, `bridge-${wallet.address.toLowerCase()}.json`) : null;
490
+ const ACROSS_REFUND_WAIT_S = 12 * 3600;
491
+ const B32 = /^0x[0-9a-fA-F]{64}$/;
492
+ let flightMem = null; // with PRIORS_STATE_DIR=off: this process's memory only
493
+ function flightFrom(v) {
494
+ if (!v || typeof v !== "object" || !DEC.test(String(v.amount)) || !Number.isSafeInteger(v.startedAt)) return null;
495
+ const base = { route: v.route, amount: BigInt(v.amount), startedAt: v.startedAt };
496
+ if (v.route === "across" && Number.isSafeInteger(v.fillDeadline) && DEC.test(String(v.outputAmount))) {
497
+ return { ...base, fillDeadline: v.fillDeadline, outputAmount: BigInt(v.outputAmount), hash: TX_RE.test(String(v.hash ?? "")) ? String(v.hash) : null };
498
+ }
499
+ if (v.route === "relay" && Number.isSafeInteger(v.validBefore) && B32.test(String(v.requestId)) && B32.test(String(v.nonce)) && DEC.test(String(v.expectedOut))) {
500
+ return { ...base, validBefore: v.validBefore, requestId: String(v.requestId), nonce: String(v.nonce), expectedOut: BigInt(v.expectedOut) };
501
+ }
502
+ return null;
503
+ }
504
+ const flightJson = (f) => JSON.stringify(Object.fromEntries(Object.entries(f).map(([k, x]) => [k, typeof x === "bigint" ? String(x) : x])));
505
+ const sameFlight = (a, b) => !!a && !!b && a.route === b.route && a.startedAt === b.startedAt && a.amount === b.amount;
506
+ function readFlight() {
507
+ if (!bridgeFile) return flightMem;
508
+ try { return flightFrom(JSON.parse(readFileSync(bridgeFile, "utf8"))); } catch (_) { return null; }
509
+ }
510
+ function writeFlight(f) {
511
+ if (!f) { rmSync(bridgeFile, { force: true }); return; }
512
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
513
+ const tmp = `${bridgeFile}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
514
+ writeFileSync(tmp, flightJson(f), { mode: 0o600 });
515
+ renameSync(tmp, bridgeFile);
516
+ }
517
+ /** Before the money can leave: refused (and so never sent) if it cannot be written, or if another session of this
518
+ * wallet has a transfer in flight. */
519
+ async function recordFlight(f) {
520
+ if (!bridgeFile) { if (flightMem) throw new Error("a transfer is already in flight"); flightMem = f; return f; }
521
+ await locked(() => {
522
+ if (readFlight()) throw Object.assign(new Error("another session of this wallet has a transfer in flight"), { code: "OTHER_SESSION" });
523
+ writeFlight(f);
524
+ });
525
+ return f;
526
+ }
527
+ /** The hash, once known (best effort: the record already blocks a second transfer). */
528
+ async function updateFlight(f) {
529
+ if (!bridgeFile) { if (sameFlight(flightMem, f)) flightMem = f; return; }
530
+ try { await locked(() => { if (sameFlight(readFlight(), f)) writeFlight(f); }); } catch (_) { /* best effort */ }
531
+ }
532
+ /** Only that same transfer's record: another session's is never removed. */
533
+ async function clearFlight(f) {
534
+ if (!bridgeFile) { if (sameFlight(flightMem, f)) flightMem = null; return; }
535
+ try { await locked(() => { if (sameFlight(readFlight(), f)) writeFlight(null); }); } catch (_) { /* best effort */ }
536
+ }
537
+ const startFlight = baseOn ? readFlight() : null;
538
+ if (startFlight) session.bridged += startFlight.amount; // what the previous process may have moved counts here too
539
+
540
+ // The bridge routes and the Base float, behind one facade (tests replace parts of it).
541
+ const bridgeFetch = deps.bridgeFetch || fetchImpl;
542
+ const bridge = {
543
+ floatOf: async (addr) => BigInt(await new ethers.Contract(X.BASE_USDC.asset, C.ERC20_ABI, baseProvider).balanceOf(addr)),
544
+ quote: (o) => B.acrossQuote({ fetchImpl: bridgeFetch, ...o }),
545
+ fundBase: (o) => B.fundBase({ signer: wallet, fetchImpl: bridgeFetch, ...o }),
546
+ returnToRobinhood: (o) => B.returnToRobinhood({ signer: wallet, baseProvider, fetchImpl: bridgeFetch, ...o }),
547
+ depositStatus: (hash) => B.depositStatus({ hash, fetchImpl: bridgeFetch }),
548
+ relayStatus: (requestId) => B.relayStatus({ requestId, fetchImpl: bridgeFetch }),
549
+ authorizationUsed: (nonce) => B.authorizationUsed({ baseProvider, from: wallet.address, nonce }),
550
+ ...(deps.bridge || {}),
551
+ };
552
+ /** The transfer in flight, after asking its route whether it is done (a read that fails keeps it), or null. */
553
+ async function settleFlight() {
554
+ const f = readFlight();
555
+ if (!f) return null;
556
+ const nowS = Math.floor(Date.now() / 1000);
557
+ // Past the time after which nothing more can happen to it, a record ends whatever its route answers, and before
558
+ // asking: a route that cannot be reached (DNS, refused, slow) must not hold the Base tools on a record that has
559
+ // already run out, with an "at the latest" time in the past (own review).
560
+ if (f.route === "across" ? nowS > f.fillDeadline + ACROSS_REFUND_WAIT_S : nowS > f.validBefore + X.SKEW_SECONDS) { await clearFlight(f); return null; }
561
+ try {
562
+ if (f.route === "across") {
563
+ if (f.hash) {
564
+ const st = await withinTime(bridge.depositStatus(f.hash), 5_000);
565
+ if (st.status === "filled" || st.status === "refunded") { await clearFlight(f); return null; }
566
+ f.status = st.status;
567
+ }
568
+ } else {
569
+ const st = await withinTime(bridge.relayStatus(f.requestId), 5_000);
570
+ if (st.status === "success") { await clearFlight(f); return null; }
571
+ f.status = st.status;
572
+ }
573
+ } catch (_) { /* its route did not answer: the record stands until its time runs out */ }
574
+ return f;
575
+ }
576
+ /**
577
+ * What the Base float keeps back from pay_url (createPayer's `baseReserve`): a return to Robinhood Chain whose
578
+ * ReceiveWithAuthorization is out and can still be used. Until validBefore Relay may pull its whole value, and a
579
+ * payment signed against the same USDC would make one of the two fail (the return, or the seller's settlement after it
580
+ * served). Once USDC records the nonce as used, the float already shows the transfer and nothing is kept back; a read
581
+ * that fails keeps it back (a Base payment is then refused, never signed twice over). No record, an Across transfer
582
+ * (it adds to the float, never takes from it), or one past validBefore: nothing.
583
+ */
584
+ async function baseHeld() {
585
+ const f = readFlight();
586
+ if (!f || f.route !== "relay" || Math.floor(Date.now() / 1000) > f.validBefore + X.SKEW_SECONDS) return 0n;
587
+ try { if (await withinTime(bridge.authorizationUsed(f.nonce), 5_000)) return 0n; } catch (_) { /* kept back */ }
588
+ return f.amount;
589
+ }
590
+ /** One line on a transfer in flight. */
591
+ function flightText(f) {
592
+ if (f.route === "across") {
593
+ return `A transfer of ${usd(f.amount)} from Robinhood Chain to Base (Across) is in flight${f.hash ? ` (tx ${f.hash})` : " (its transaction hash was not seen)"}${f.status === "expired" ? ": it was not filled in time, and Across refunds it to this wallet on Robinhood Chain within hours" : f.status && f.status !== "unknown" ? `, ${f.status}` : ""}. fund_base, return_to_robinhood and borrowing for Base wait until it lands (at the latest ${when(f.fillDeadline + ACROSS_REFUND_WAIT_S)}).`;
594
+ }
595
+ return `A return of ${X.formatUsdg(f.amount)} USDC from Base to Robinhood Chain (Relay request ${f.requestId}) is in flight${f.status && f.status !== "pending" ? `, ${f.status}` : ""}. fund_base, return_to_robinhood and borrowing for Base wait until it lands, or until its authorization expires at ${when(f.validBefore)}.`;
596
+ }
597
+ /** "0.05 USDG", or "0.01 USDC on Base": what pay_url says it paid, in the token it was paid in. */
598
+ const money = (units, network) => (network === X.BASE_USDC.network ? `${X.formatUsdg(units)} USDC on Base` : usd(units));
599
+
427
600
  const contracts = C.creditContracts({ runner: provider, addresses: { pool: addresses.pool, lens: addresses.lens, usdg: addresses.usdg, registry: addresses.registry, stockVault: addresses.stockVault || null, seatVaultV5: v5.v5, seatVaultV5AgentId: v5.v5Root } });
428
601
 
429
602
  // The chain, behind one facade (tests replace it).
@@ -445,6 +618,10 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
445
618
  save: async (amount) => S.save(await savingsC(), wallet, amount),
446
619
  unsave: async (o) => S.unsave(await savingsC(), wallet, o),
447
620
  topUp: async (need, o) => S.topUpFromSavings(await savingsC(), wallet, need, o),
621
+ // fund_base's loan: pay_url's borrow-the-gap (a draw of max(shortfall, the pool's minimum loan), simulated first),
622
+ // and the pool's minimum loan, read so a refusal can name the max_borrow_usd that would do
623
+ borrowGap: (o) => C.borrowGap({ signer: wallet, pool: addresses.pool, ...v5, ...o }),
624
+ minLoan: async () => (await contracts.pool.getParams()).minLoan,
448
625
  };
449
626
  let savingsCache = null;
450
627
  function needSavings() { if (savingsProblem) throw new ToolError(savingsProblem); }
@@ -594,7 +771,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
594
771
  }
595
772
 
596
773
  const server = new McpServer({ name: "priors", version: VERSION }, {
597
- instructions: `Priors on Robinhood Chain (chain 4663): pay x402-priced URLs in USDG, and run the agent's Priors credit line. Tools that move money (pay_url, borrow, repay, save, unsave, autopay_on, autopay_off${ptOn ? ", pt_buy, pt_sell, pt_redeem" : ""}) act immediately on mainnet: state the amounts to the user and get their go-ahead first. Spare USDG can be saved in a Morpho vault (save); pay_url and repay take it back out when the wallet is short, before any borrowing.${ptOn ? ` PT-USDG (Pendle's principal token for USDG, redeemable 1:1 for USDG on ${P.PT_USDG.maturity.slice(0, 10)}) can be bought, sold and redeemed through Pendle's router (pt_quote, pt_position first).` : ""} Amounts are in US dollars of USDG.`,
774
+ instructions: `Priors on Robinhood Chain (chain 4663): pay x402-priced URLs in USDG, and run the agent's Priors credit line. Tools that move money (pay_url, borrow, repay, save, unsave, autopay_on, autopay_off${ptOn ? ", pt_buy, pt_sell, pt_redeem" : ""}${baseOn ? ", fund_base, return_to_robinhood" : ""}) act immediately on mainnet: state the amounts to the user and get their go-ahead first. Spare USDG can be saved in a Morpho vault (save); pay_url and repay take it back out when the wallet is short, before any borrowing.${ptOn ? ` PT-USDG (Pendle's principal token for USDG, redeemable 1:1 for USDG on ${P.PT_USDG.maturity.slice(0, 10)}) can be bought, sold and redeemed through Pendle's router (pt_quote, pt_position first).` : ""}${baseOn ? ` pay_url also pays URLs that take USDC on Base only, from the wallet's USDC on Base (its Base float, kept at most ${X.formatUsdg(maxBaseFloat)}): fund_base moves USDG from Robinhood Chain into it (borrowing the gap from the line only with max_borrow_usd), and return_to_robinhood brings what is left back as USDG. Loans stay on Robinhood Chain and are repaid there.` : ""} Amounts are in US dollars of USDG${baseOn ? " (of USDC on Base)" : ""}.`,
598
775
  });
599
776
  const tool = (name, config, handler) => server.registerTool(name, config, async (args) => {
600
777
  try { return text(await handler(args || {})); } catch (e) { return failure(explain(e)); }
@@ -602,8 +779,10 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
602
779
 
603
780
  // ---- pay_url -------------------------------------------------------------------------------------------------
604
781
  tool("pay_url", {
605
- title: "Pay for a URL with x402 (USDG)",
606
- description: "Fetch a URL that may charge per call with x402 (HTTP 402) and pay it in USDG on Robinhood Chain from the configured wallet. Moves real money: confirm the URL and the most you will pay with the user first. Pays only if the price is at or below max_price_usd (default 0.10 USD); a higher price is refused before anything is signed. If the wallet is short, it borrows the gap from the agent's Priors credit line only when max_borrow_usd is given and covers it (the loan must then be repaid with the repay tool before its due date). Returns what was paid and borrowed, and the response body.",
782
+ title: baseOn ? "Pay for a URL with x402 (USDG, or USDC on Base)" : "Pay for a URL with x402 (USDG)",
783
+ description: baseOn
784
+ ? "Fetch a URL that may charge per call with x402 (HTTP 402) and pay it from the configured wallet: in USDG on Robinhood Chain, or, when the URL only takes USDC on Base, in USDC from the wallet's Base float (fund_base tops it up; a float short of the price is refused before anything is signed). Moves real money: confirm the URL and the most you will pay with the user first. Pays only if the price is at or below max_price_usd (default 0.10 USD); a higher price is refused before anything is signed. If the wallet is short of USDG on Robinhood Chain, it borrows the gap from the agent's Priors credit line only when max_borrow_usd is given and covers it (the loan must then be repaid with the repay tool before its due date); a Base payment never borrows. Returns what was paid and borrowed, and the response body."
785
+ : "Fetch a URL that may charge per call with x402 (HTTP 402) and pay it in USDG on Robinhood Chain from the configured wallet. Moves real money: confirm the URL and the most you will pay with the user first. Pays only if the price is at or below max_price_usd (default 0.10 USD); a higher price is refused before anything is signed. If the wallet is short, it borrows the gap from the agent's Priors credit line only when max_borrow_usd is given and covers it (the loan must then be repaid with the repay tool before its due date). Returns what was paid and borrowed, and the response body.",
607
786
  inputSchema: {
608
787
  url: z.string().url().describe("The https URL to fetch (http only for localhost)."),
609
788
  method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).optional().describe("HTTP method; default GET."),
@@ -648,15 +827,17 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
648
827
  const unmatched = !prior && purchase !== urlOnly ? outstanding.get(urlOnly) : undefined;
649
828
  if (unmatched) {
650
829
  const until = when(unmatched.validBefore + X.SKEW_SECONDS);
651
- throw new ToolError(`A payment of ${usd(unmatched.price)} to ${unmatched.payTo} for ${urlOnly} was signed earlier and kept without its request body (by an earlier version of this server, or for a call without a body), and the merchant may still settle it until ${until}. It cannot be told apart from this purchase, so nothing was signed: do NOT call pay_url again for this URL before ${until}; check wallet_balance.`);
830
+ throw new ToolError(`A payment of ${money(unmatched.price, unmatched.network)} to ${unmatched.payTo} for ${urlOnly} was signed earlier and kept without its request body (by an earlier version of this server, or for a call without a body), and the merchant may still settle it until ${until}. It cannot be told apart from this purchase, so nothing was signed: do NOT call pay_url again for this URL before ${until}; check wallet_balance.`);
652
831
  }
653
832
  let r;
654
833
  let signedPrice = null; // what the payer checked and signed; never a merchant field read again here
834
+ let signedNetwork = null; // where: Robinhood Chain (USDG) or Base (USDC)
655
835
  if (prior) {
656
836
  // A payment for this purchase is already out and still cashable: send that same one, never a second.
657
837
  r = await X.createPayer({ signer, fetchImpl: payFetch, pendingRetries: 2, maxSleepMs: 10_000, timeoutMs: requestTimeoutMs, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())), ...(sleep ? { sleep } : {}) }).resend(url, prior.paymentHeaders, init);
658
- r = { ...r, requirement: { payTo: prior.payTo }, paid: r.response.ok ? prior.price : 0n, borrowed: 0n, signed: prior, resent: true, ...(r.response.ok ? { settlement: settlementOf(r.response) } : {}) };
838
+ r = { ...r, requirement: { payTo: prior.payTo }, paid: r.response.ok ? prior.price : 0n, borrowed: 0n, signed: prior, resent: true, network: prior.network, ...(r.response.ok ? { settlement: settlementOf(r.response) } : {}) };
659
839
  signedPrice = prior.price;
840
+ signedNetwork = prior.network;
660
841
  lines.push("No new payment was signed: the same signed payment was sent again.");
661
842
  if (prior.borrowed > 0n) lines.push(`The first attempt at this purchase borrowed ${usd(prior.borrowed)}${prior.loanId !== null && prior.loanId !== undefined ? ` as loan #${prior.loanId}` : ""}: repay it with the repay tool.`);
662
843
  } else {
@@ -668,9 +849,13 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
668
849
  // The agent's own savings before a loan: once the 402 names the price, only what the wallet is short of.
669
850
  const topUp = use_savings && autoSavings && typeof credit.topUp === "function" ? (need) => topUpWithin(need, deadline) : undefined;
670
851
  const payer = X.createPayer({ signer, maxPrice, maxBorrow, fetchImpl: payFetch, pendingRetries: 2, maxSleepMs: 10_000, timeoutMs: requestTimeoutMs, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())), ...(sleep ? { sleep } : {}), ...(maxBorrow > 0n ? { pool: addresses.pool, agentId, ...v5 } : {}), ...(topUp ? { topUp } : {}), ...(reserveOn && autopay ? { reserve: autopayReserve } : {}),
852
+ // Base (when on): a USDC requirement there is paid from the Base float, never from a loan or savings, and never
853
+ // from USDC a return to Robinhood Chain still in flight may pull (baseHeld)
854
+ ...(baseOn ? { networks, baseProvider, baseReserve: baseHeld } : {}),
671
855
  // Recorded, then counted, when signed, at the price the payer checked and signed (a v1 requirement's `amount` is the
672
- // merchant's text). A record that cannot be kept throws, and the payer does not send the payment.
673
- onSigned: async (s) => { await record(purchase, { paymentHeaders: s.paymentHeaders, validBefore: s.validBefore, price: s.price, payTo: s.requirement.payTo, borrowed: s.borrowed || 0n, loanId: s.loanId ?? null }); signedPrice = s.price; session.spent += s.price; } });
856
+ // merchant's text). A record that cannot be kept throws, and the payer does not send the payment. A payment on
857
+ // either chain counts against PRIORS_MAX_SPEND_USD.
858
+ onSigned: async (s) => { await record(purchase, { paymentHeaders: s.paymentHeaders, validBefore: s.validBefore, price: s.price, payTo: s.requirement.payTo, borrowed: s.borrowed || 0n, loanId: s.loanId ?? null, network: s.network, asset: s.asset }); signedPrice = s.price; signedNetwork = s.network; session.spent += s.price; } });
674
859
  try { r = await payer.pay(url, init); } catch (e) {
675
860
  // What savings did before the failure is part of the answer, whatever failed after.
676
861
  const sv = []; savingsLines(e?.savings, sv);
@@ -681,13 +866,20 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
681
866
  if (e?.unconfirmed) throw new ToolError(`A borrow of ${usd(e.borrowed)} was sent${e.hash ? ` (tx ${e.hash})` : ""} and its answer was lost (${explain(e.cause ?? e)}), so it may have opened a loan: check credit_status, and repay it with the repay tool before its due date. Nothing was signed or paid.${note}`);
682
867
  if (e?.signed) {
683
868
  // onSigned ran before the payment left; should it not have, count the most this call could sign
684
- if (signedPrice === null) { signedPrice = maxPrice; session.spent += maxPrice; await recordSent(purchase, { ...e.signed, price: maxPrice, payTo: e.requirement.payTo, borrowed: e.borrowed || 0n, loanId: e.loanId ?? null }); }
869
+ if (signedPrice === null) { signedPrice = maxPrice; signedNetwork = e.network ?? null; session.spent += maxPrice; await recordSent(purchase, { ...e.signed, price: maxPrice, payTo: e.requirement.payTo, borrowed: e.borrowed || 0n, loanId: e.loanId ?? null, network: e.network, asset: e.asset }); }
685
870
  const price = signedPrice;
686
871
  const until = when(e.signed.validBefore + X.SKEW_SECONDS);
687
- throw new ToolError(`A payment of ${usd(price)} to ${e.requirement.payTo} was signed, then the request failed (${explain(e)}). The merchant may still settle it until ${until}, so do NOT call pay_url again for this purchase (the same method, URL and body) before ${until}; check wallet_balance.${e.borrowed > 0n ? ` Borrowed ${usd(e.borrowed)}${e.loanId !== null ? ` as loan #${e.loanId}` : ""}: repay it with the repay tool.` : ""}${note}`);
872
+ throw new ToolError(`A payment of ${money(price, signedNetwork ?? e.network)} to ${e.requirement.payTo} was signed, then the request failed (${explain(e)}). The merchant may still settle it until ${until}, so do NOT call pay_url again for this purchase (the same method, URL and body) before ${until}; check wallet_balance.${e.borrowed > 0n ? ` Borrowed ${usd(e.borrowed)}${e.loanId !== null ? ` as loan #${e.loanId}` : ""}: repay it with the repay tool.` : ""}${note}`);
688
873
  }
689
874
  const loan = e?.borrowed > 0n ? ` ${usd(e.borrowed)} was borrowed${e.loanId !== null ? ` as loan #${e.loanId}` : ""} before it failed: repay it with the repay tool.` : "";
690
- if (e?.code === "NOT_RECORDED" && e.cause?.code === "OTHER_SESSION") { outstanding.set(purchase, e.cause.prior); throw new ToolError(`Another session of this wallet signed a payment of ${usd(e.cause.prior.price)} for this purchase a moment ago, and it may still settle until ${when(e.cause.prior.validBefore + X.SKEW_SECONDS)}. Nothing was sent from this call and no payment of its own is out: calling pay_url again resends that same payment, never a new one.${loan}`); }
875
+ // Base: the float is short. Nothing was signed; topping it up is a call of its own (phase 1), the user's to approve.
876
+ if (e?.code === "BASE_FLOAT_SHORT") {
877
+ // USDC a return to Robinhood Chain may still pull is not the float's to spend: wait for it, fund_base waits too
878
+ const f = e.reserve > 0n ? readFlight() : null;
879
+ if (f?.route === "relay") throw new ToolError(`${method} ${u.href} takes USDC on Base. The wallet's Base float holds ${X.formatUsdg(e.balance)} USDC, and ${X.formatUsdg(e.reserve)} of it is held for a return to Robinhood Chain still in flight (Relay may use its authorization until ${when(f.validBefore)}), leaving less than the price of ${X.formatUsdg(e.price)} USDC. Nothing was signed or paid. wallet_balance shows when the return lands or expires; call pay_url again after that (top the float up with fund_base first if it is still short).`);
880
+ throw new ToolError(`${method} ${u.href} takes USDC on Base, and the wallet's Base float holds ${X.formatUsdg(e.balance)} USDC, less than the price of ${X.formatUsdg(e.price)} USDC. Nothing was signed or paid. Top the float up with fund_base (it moves USDG from Robinhood Chain to USDC on Base, borrowing only with max_borrow_usd: state the amount to the user and get their go-ahead first), then call pay_url again.`);
881
+ }
882
+ if (e?.code === "NOT_RECORDED" && e.cause?.code === "OTHER_SESSION") { outstanding.set(purchase, e.cause.prior); throw new ToolError(`Another session of this wallet signed a payment of ${money(e.cause.prior.price, e.cause.prior.network)} for this purchase a moment ago, and it may still settle until ${when(e.cause.prior.validBefore + X.SKEW_SECONDS)}. Nothing was sent from this call and no payment of its own is out: calling pay_url again resends that same payment, never a new one.${loan}`); }
691
883
  if (e?.code === "NOT_RECORDED") throw new ToolError(`A payment was signed but could not be written to PRIORS_STATE_DIR (${explain(e.cause ?? e)}), so it was not sent and nothing can be settled. Fix that directory, or set PRIORS_STATE_DIR=off to keep payments in this process's memory only, then call again.${loan}${note}`);
692
884
  if (e?.name === "TimeoutError" || e?.name === "AbortError") throw new ToolError(`${method} ${u.href} did not answer in time. Nothing was signed or paid.${loan}${note}`);
693
885
  if (loan || note) throw new ToolError(`${explain(e)}.${loan}${note}`);
@@ -695,8 +887,8 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
695
887
  }
696
888
  savingsLines(r.savings, lines);
697
889
  if (r.signed && signedPrice === null) { // onSigned counted and recorded it; should it not have, the most this call could sign
698
- signedPrice = maxPrice; session.spent += maxPrice;
699
- if (r.paid === 0n) await recordSent(purchase, { ...r.signed, price: maxPrice, payTo: r.requirement.payTo, borrowed: r.borrowed || 0n, loanId: r.loanId ?? null });
890
+ signedPrice = maxPrice; signedNetwork = r.network ?? null; session.spent += maxPrice;
891
+ if (r.paid === 0n) await recordSent(purchase, { ...r.signed, price: maxPrice, payTo: r.requirement.payTo, borrowed: r.borrowed || 0n, loanId: r.loanId ?? null, network: r.network, asset: r.asset });
700
892
  }
701
893
  if (r.borrowed > 0n) { session.borrowed += r.borrowed; lines.push(`Borrowed ${usd(r.borrowed)} from the Priors line for agent #${agentId}${r.loanId !== null ? ` as loan #${r.loanId}` : ""}${r.dueAt ? `, due ${when(r.dueAt)}` : ""}. Repay it with the repay tool before then.`); }
702
894
  else if (r.requirement) lines.push("Nothing was borrowed.");
@@ -706,10 +898,10 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
706
898
  else if (r.paid > 0n) {
707
899
  await forget(purchase, r.signed?.paymentHeaders);
708
900
  const tx = r.settlement?.transaction;
709
- lines.unshift(`Paid ${usd(r.paid)}${r.x402Version ? ` (x402 v${r.x402Version})` : ""} to ${r.requirement.payTo} for ${method} ${u.href}: ${status}.${tx ? (TX_RE.test(String(tx)) ? ` Settlement tx ${tx}.` : " (The merchant's settlement id is not a transaction hash; not shown.)") : ""}`);
901
+ lines.unshift(`Paid ${money(r.paid, signedNetwork ?? r.network)}${r.x402Version ? ` (x402 v${r.x402Version})` : ""} to ${r.requirement.payTo} for ${method} ${u.href}: ${status}.${tx ? (TX_RE.test(String(tx)) ? ` Settlement tx ${tx}.` : " (The merchant's settlement id is not a transaction hash; not shown.)") : ""}`);
710
902
  } else {
711
903
  const until = when(r.signed.validBefore + X.SKEW_SECONDS);
712
- lines.unshift(`A payment of ${usd(signedPrice)} to ${r.requirement.payTo} was signed and sent (${status}), and the merchant may still settle it until ${until}, so do NOT call pay_url again for this purchase (the same method, URL and body) before ${until}; check wallet_balance. A later call for this purchase only resends this same payment.`);
904
+ lines.unshift(`A payment of ${money(signedPrice, signedNetwork ?? r.network)} to ${r.requirement.payTo} was signed and sent (${status}), and the merchant may still settle it until ${until}, so do NOT call pay_url again for this purchase (the same method, URL and body) before ${until}; check wallet_balance. A later call for this purchase only resends this same payment.`);
713
905
  }
714
906
  const loc = r.response.status >= 300 && r.response.status < 400 ? r.response.headers.get("location") : null;
715
907
  if (loc) lines.push(`The server redirected (not followed): ${fenced(oneLine(loc, 500), "redirect target")}`);
@@ -720,9 +912,22 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
720
912
  }));
721
913
 
722
914
  // ---- wallet_balance ------------------------------------------------------------------------------------------
915
+ /** The Base float of `addr` and, for this server's wallet, a transfer in flight: lines for wallet_balance and
916
+ * credit_status, and the float itself (null when it could not be read). Never fails the calling tool. */
917
+ async function baseLines(addr) {
918
+ if (!baseOn) return { lines: [], float: null };
919
+ const out = [];
920
+ let float = null;
921
+ try { float = await withinTime(bridge.floatOf(addr), 5_000); out.push(`On Base it holds ${X.formatUsdg(float)} USDC: its Base float, for x402 sellers paid in USDC on Base (at most ${X.formatUsdg(maxBaseFloat)} by fund_base).`); } catch (e) { out.push(`Its USDC on Base could not be read just now (${explain(e)}).`); }
922
+ if (wallet && ethers.getAddress(addr) === wallet.address) { const f = await settleFlight(); if (f) out.push(flightText(f)); }
923
+ return { lines: out, float };
924
+ }
925
+
723
926
  tool("wallet_balance", {
724
- title: "USDG and gas balance",
725
- description: "Show how much USDG (the dollar the payments and loans use) and native ETH for gas a Robinhood Chain address holds. Defaults to the configured wallet; any address works without a key. Read-only.",
927
+ title: baseOn ? "USDG, gas and Base float balance" : "USDG and gas balance",
928
+ description: baseOn
929
+ ? "Show how much USDG (the dollar the payments and loans use) and native ETH for gas a Robinhood Chain address holds, and the USDC it holds on Base (its Base float, for x402 sellers paid on Base), with any transfer between the two still in flight. Defaults to the configured wallet; any address works without a key. Read-only."
930
+ : "Show how much USDG (the dollar the payments and loans use) and native ETH for gas a Robinhood Chain address holds. Defaults to the configured wallet; any address works without a key. Read-only.",
726
931
  inputSchema: { address: z.string().optional().describe("0x address to check; default: the configured wallet.") },
727
932
  annotations: { readOnlyHint: true, openWorldHint: true },
728
933
  }, async ({ address }) => {
@@ -730,7 +935,8 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
730
935
  if (!addr) throw new ToolError("No wallet is configured (PRIORS_KEY is not set): pass an address to check.");
731
936
  if (!ethers.isAddress(addr)) throw new ToolError(`not an address: ${clean(addr, 80)}`);
732
937
  const b = await credit.balances(ethers.getAddress(addr));
733
- return `${b.address}${wallet && ethers.getAddress(addr) === wallet.address ? " (this server's wallet)" : ""} holds ${usd(b.usdg)} and ${ethers.formatEther(b.native)} ETH for gas on Robinhood Chain.${await savedNote(b.address)}`;
938
+ const base = await baseLines(b.address);
939
+ return `${b.address}${wallet && ethers.getAddress(addr) === wallet.address ? " (this server's wallet)" : ""} holds ${usd(b.usdg)} and ${ethers.formatEther(b.native)} ETH for gas on Robinhood Chain.${await savedNote(b.address)}${base.lines.length ? ` ${base.lines.join(" ")}` : ""}`;
734
940
  });
735
941
 
736
942
  // ---- credit_status -------------------------------------------------------------------------------------------
@@ -753,6 +959,14 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
753
959
  if (s.openLoans.length === 0) lines.push("Open loans: none.");
754
960
  for (const l of s.openLoans) lines.push(`Open loan #${l.loanId}: ${usd(l.principal)} + fee ${usd(l.fee)} = ${usd(l.due)}, due ${when(l.dueAt)}${Date.now() / 1000 > l.dueAt ? " (PAST DUE: repay now)" : ""}.`);
755
961
  lines.push(...(await autopayLines(id)));
962
+ // The configured wallet's own agent: its Base float, a transfer in flight, and a loan due soon while money sits on Base
963
+ // (loans are repaid in USDG on Robinhood Chain only).
964
+ if (baseOn && wallet && (agent_id === undefined || (await resolveAgent().catch(() => null)) === id)) {
965
+ const base = await baseLines(wallet.address);
966
+ lines.push(...base.lines);
967
+ const soon = s.openLoans.find((l) => l.dueAt - Date.now() / 1000 <= 86_400);
968
+ if (soon && base.float > 0n) lines.push(`Loan #${soon.loanId} is due within 24 hours and ${X.formatUsdg(base.float)} USDC sits on Base, where it cannot repay it: bring it back with return_to_robinhood (about a minute; confirm with the user first), or repay from USDG on Robinhood Chain.`);
969
+ }
756
970
  return lines.join("\n");
757
971
  });
758
972
 
@@ -907,6 +1121,148 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
907
1121
  return out.join("\n");
908
1122
  }));
909
1123
 
1124
+ // ---- fund_base / return_to_robinhood (the Base float; registered only with Base on) ------------------------------
1125
+ // The agent's own money between USDG on Robinhood Chain and USDC on Base, where some x402 sellers take payment: out
1126
+ // through Across (bridge.mjs fundBase), back through Relay's gasless route (returnToRobinhood). Both are money calls
1127
+ // (serial(): one at a time with pay_url and borrow, so neither spends USDG the other is about to move, and no loan is
1128
+ // taken twice), both are capped per call and per process (PRIORS_MAX_BRIDGE_USD, PRIORS_MAX_BRIDGE_TOTAL_USD, either
1129
+ // way), and both wait at most PRIORS_BRIDGE_TIMEOUT_S, never past the call's own budget (so a slow fill is answered as
1130
+ // in flight and never turns into the 120 s hold of a call that ran out of time). A transfer still on its way is kept
1131
+ // on file and reported, and never sent again.
1132
+ if (baseOn) {
1133
+ /** Answer this long before the call's budget ends: time to clear the record and read the float. */
1134
+ const BRIDGE_MARGIN_MS = Math.min(4_000, callBudgetMs / 5);
1135
+ const blocked = (f) => `${flightText(f)} Nothing was done by this call: check wallet_balance in a minute.`;
1136
+ const otherSession = (e) => e?.code === "NOT_RECORDED" && e.cause?.code === "OTHER_SESSION";
1137
+ const heldOnBase = () => { const nowS = Math.floor(Date.now() / 1000); refresh(); return [...outstanding.values()].filter((v) => live(v, nowS) && !onRobinhood(v)).reduce((a, v) => a + v.price, 0n); };
1138
+ const stillOut = (what) => `Do NOT call ${what} again for this: wallet_balance shows when it lands. Until then fund_base and return_to_robinhood do nothing; pay_url, borrow and repay work as usual.`;
1139
+
1140
+ tool("fund_base", {
1141
+ title: "Move USDG to the Base float (Across)",
1142
+ description: `Move USDG from the configured wallet on Robinhood Chain to USDC in the same address on Base (its Base float), through Across, so pay_url can pay x402 sellers that take USDC on Base only. Takes a few seconds and needs a little ETH for gas on Robinhood Chain. Across's fee is quoted first and refused above ${maxBridgeFeeBps / 100}% (PRIORS_MAX_BRIDGE_FEE_BPS); Across's minimum is about 0.50. One call moves at most ${X.formatUsdg(maxBridgeCeiling)} (PRIORS_MAX_BRIDGE_USD), and the float is kept at most ${X.formatUsdg(maxBaseFloat)} USDC (PRIORS_MAX_BASE_FLOAT_USD). USDG kept for Autopay loans due in the next 24 hours and for signed payments not settled yet stays on Robinhood Chain. If the wallet is short, it borrows the gap from the agent's Priors line, raised to the pool's minimum loan, only when max_borrow_usd is given and covers that loan (when it refuses, its answer names the max_borrow_usd that would do); the loan is repaid in USDG on Robinhood Chain before its due date. Moves real money: state the amount, any loan and the fee to the user and get their go-ahead first.`,
1143
+ inputSchema: {
1144
+ amount_usd: z.number().positive().describe("How much USDG to move to Base, in US dollars (required, no default)."),
1145
+ max_borrow_usd: z.number().nonnegative().optional().describe("Most to borrow from the Priors line if the wallet is short, in US dollars. Default 0: never borrow."),
1146
+ },
1147
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
1148
+ }, serial(async ({ amount_usd, max_borrow_usd }, deadline, count) => {
1149
+ needWallet("fund_base");
1150
+ if (bridgeRoute !== "across") throw new ToolError("fund_base moves money out through Across only in this version (PRIORS_BRIDGE=across); the Relay route out is not built yet. Nothing was done.");
1151
+ const amount = dollars(amount_usd, "amount_usd");
1152
+ if (amount === 0n) throw new ToolError("amount_usd must be above zero");
1153
+ if (amount > maxBridgeCeiling) throw new ToolError(`amount_usd ${X.formatUsdg(amount)} is above this server's ceiling of ${X.formatUsdg(maxBridgeCeiling)} per transfer (PRIORS_MAX_BRIDGE_USD).`);
1154
+ if (session.bridged + amount > bridgeTotalCap) throw new ToolError(`this would bring what moved between Robinhood Chain and Base in this session to ${X.formatUsdg(session.bridged + amount)}, above ${X.formatUsdg(bridgeTotalCap)} (PRIORS_MAX_BRIDGE_TOTAL_USD).`);
1155
+ const maxBorrow = dollars(max_borrow_usd ?? 0, "max_borrow_usd");
1156
+ if (maxBorrow > maxBorrowCeiling) throw new ToolError(`max_borrow_usd ${X.formatUsdg(maxBorrow)} is above this server's ceiling of ${usd(maxBorrowCeiling)} (PRIORS_MAX_BORROW_USD).`);
1157
+ if (maxBorrow > 0n && session.borrowed + maxBorrow > borrowTotalCap) throw new ToolError(`this could bring what is borrowed in this session to ${usd(session.borrowed + maxBorrow)}, above ${usd(borrowTotalCap)} (PRIORS_MAX_BORROW_TOTAL_USD).`);
1158
+ const f = await settleFlight();
1159
+ if (f) throw new ToolError(blocked(f));
1160
+ const float = await bridge.floatOf(wallet.address);
1161
+ if (float + amount > maxBaseFloat) throw new ToolError(`this would bring the Base float to about ${X.formatUsdg(float + amount)} USDC, above ${X.formatUsdg(maxBaseFloat)} (PRIORS_MAX_BASE_FLOAT_USD); it holds ${X.formatUsdg(float)} now. Nothing was done.`);
1162
+ count("bridged", amount); count("borrowed", maxBorrow); // the most it may move and borrow, until it ends (GHSA-cq9v)
1163
+ // What stays on Robinhood Chain: what Autopay pulls in the next 24 h, and the USDG of payments signed there and not
1164
+ // settled (the borrow-the-gap rule alone does not know either).
1165
+ const nowS = Math.floor(Date.now() / 1000);
1166
+ refresh();
1167
+ const signedOut = [...outstanding.values()].filter((v) => live(v, nowS) && onRobinhood(v)).reduce((a, v) => a + v.price, 0n);
1168
+ const autopayKept = reserveOn ? await autopayReserve() : 0n;
1169
+ const kept = signedOut + autopayKept;
1170
+ const balance = (await credit.balances(wallet.address)).usdg;
1171
+ const lines = [];
1172
+ if (amount + kept > balance) {
1173
+ // The loan is the gap (what moving `amount` while keeping `kept` needs beyond the balance), raised to the pool's
1174
+ // minimum loan, and max_borrow_usd caps that loan, as the answer below tells the model to pass it. borrowGap is
1175
+ // handed the gap as its price with a zero balance: its first rule (price at most maxBorrow) is then the gap's.
1176
+ // Handed the whole amount, it refused whenever max_borrow_usd covered the gap but not the amount (own review).
1177
+ const gap = amount + kept - balance;
1178
+ const why = [autopayKept > 0n ? `${usd(autopayKept)} for Autopay loans due in the next 24 hours` : null, signedOut > 0n ? `${usd(signedOut)} for signed payments not settled yet` : null].filter(Boolean).join(" and ");
1179
+ const holds = `The wallet holds ${usd(balance)} on Robinhood Chain${why ? ` and keeps ${why}` : ""}: it is ${usd(gap)} short of moving ${usd(amount)}.`;
1180
+ // the pool's minimum loan, best effort (borrowGap reads it again and refuses a loan above max_borrow_usd anyway)
1181
+ let minLoan = null;
1182
+ try { if (typeof credit.minLoan === "function") minLoan = BigInt(await withinTime(credit.minLoan(), 5_000)); } catch (_) { /* said as "at least its minimum loan" */ }
1183
+ const loanNeed = minLoan !== null && minLoan > gap ? minLoan : gap;
1184
+ const loanText = minLoan === null ? `at least ${usd(gap)} (the pool lends at least its minimum loan, so it may be more)` : loanNeed > gap ? `${usd(loanNeed)}, the pool's minimum loan` : usd(gap);
1185
+ const atLeast = `pass max_borrow_usd of at least ${X.formatUsdg(loanNeed)}, after confirming the loan with the user`;
1186
+ if (maxBorrow === 0n) throw new ToolError(`${holds} Nothing was done. A loan from the Priors line for it would be ${loanText}: to take it, ${atLeast}; or add USDG.`);
1187
+ if (loanNeed > maxBorrow) throw new ToolError(`${holds} A loan for it would be ${loanText}, above max_borrow_usd ${X.formatUsdg(maxBorrow)}. Nothing was borrowed or moved: ${atLeast}; or move less.`);
1188
+ const agentId = await resolveAgent();
1189
+ await needController(agentId);
1190
+ // The route first (a read-only quote): a transfer Across would refuse (its fee, its minimum, a token or spoke that
1191
+ // is not the pinned one) never leaves behind a loan taken for it.
1192
+ try { await bridge.quote({ amount, maxFeeBps: maxBridgeFeeBps }); } catch (e) { throw new ToolError(`${explain(e)}. Nothing was borrowed or moved.`); }
1193
+ let loan;
1194
+ try { loan = await credit.borrowGap({ agentId, price: gap, balance: 0n, maxBorrow }); } catch (e) {
1195
+ // a borrow sent whose answer was lost may have mined (GHSA-v9xj): counted, and said
1196
+ if (e?.borrowed > 0n) session.borrowed += e.borrowed;
1197
+ if (e?.unconfirmed) throw new ToolError(`A borrow of ${usd(e.borrowed)} was sent${e.hash ? ` (tx ${e.hash})` : ""} and its answer was lost (${explain(e.cause ?? e)}), so it may have opened a loan: check credit_status, and repay it with the repay tool before its due date. Nothing was moved to Base.`);
1198
+ // the pool's minimum loan (when it could not be read above) above the cap: said in dollars, with what would do
1199
+ if (e?.code === "MIN_LOAN_ABOVE_MAX_BORROW" && typeof e.amount === "bigint") throw new ToolError(`${holds} The pool lends at least ${usd(e.amount)}, above max_borrow_usd ${X.formatUsdg(maxBorrow)}. Nothing was borrowed or moved: pass max_borrow_usd of at least ${X.formatUsdg(e.amount)}, after confirming the loan with the user; or add USDG.`);
1200
+ throw e;
1201
+ }
1202
+ session.borrowed += loan.borrowed;
1203
+ lines.push(`Borrowed ${usd(loan.borrowed)} from the Priors line for agent #${agentId}${loan.loanId !== null && loan.loanId !== undefined ? ` as loan #${loan.loanId}` : ""}${loan.dueAt ? `, due ${when(loan.dueAt)}` : ""}: repay it with the repay tool, in USDG on Robinhood Chain, before then.`);
1204
+ }
1205
+ let rec = null, r;
1206
+ try {
1207
+ r = await bridge.fundBase({ amount, maxFeeBps: maxBridgeFeeBps, timeoutMs: bridgeTimeoutMs, pollUntil: deadline - BRIDGE_MARGIN_MS,
1208
+ onDepositSending: async (t) => { rec = await recordFlight(t); },
1209
+ onDepositSent: async (t) => { if (rec) { rec = { ...rec, hash: t.hash }; await updateFlight(rec); } } });
1210
+ } catch (e) {
1211
+ const loanNote = lines.length ? ` ${lines.join(" ")}` : "";
1212
+ if (!rec || e?.moved === false) {
1213
+ if (rec) await clearFlight(rec);
1214
+ if (otherSession(e)) throw new ToolError(`Another session of this wallet has a transfer to or from Base in flight. Nothing was sent: check wallet_balance in a minute.${loanNote}`);
1215
+ throw new ToolError(`${explain(e)}. Nothing was moved to Base.${loanNote}`);
1216
+ }
1217
+ session.bridged += amount; // it may have moved: counted, and its record holds every other transfer
1218
+ if (e?.code === "BRIDGE_REFUNDED") { await clearFlight(rec); throw new ToolError(`${explain(e)}. The USDG is back in the wallet on Robinhood Chain.${loanNote}`); }
1219
+ throw new ToolError(`${explain(e)}. ${stillOut("fund_base")}${loanNote}`);
1220
+ }
1221
+ session.bridged += amount;
1222
+ await clearFlight(rec);
1223
+ let after = "";
1224
+ try { after = ` The Base float now holds ${X.formatUsdg(await withinTime(bridge.floatOf(wallet.address), 2_000))} USDC.`; } catch (_) { /* wallet_balance shows it */ }
1225
+ return [`Moved ${usd(amount)} from Robinhood Chain to ${X.formatUsdg(r.outputAmount)} USDC on Base through Across (fee ${X.formatUsdg(r.fee)}, ${r.feeBps / 100}%). Deposit tx ${r.hash}${r.fillTx ? `; filled on Base in tx ${r.fillTx}` : ""}.${after}`, ...lines].join("\n");
1226
+ }));
1227
+
1228
+ tool("return_to_robinhood", {
1229
+ title: "Move the Base float back to Robinhood Chain (Relay)",
1230
+ description: `Move USDC from the configured wallet's Base float back to USDG in the same address on Robinhood Chain, through Relay's gasless route: one signature, no gas on Base. amount_usd, or "all" for everything the float does not owe to signed payments still settling on Base. About a minute; Relay's fee is quoted first and refused above ${maxBridgeFeeBps / 100}% (PRIORS_MAX_BRIDGE_FEE_BPS); one call moves at most ${X.formatUsdg(maxBridgeCeiling)} (PRIORS_MAX_BRIDGE_USD). Loans are repaid in USDG on Robinhood Chain only: use it before a due date when money sits on Base. Moves real money: state the amount to the user and get their go-ahead first.`,
1231
+ inputSchema: { amount_usd: z.union([z.number().positive(), z.literal("all")]).describe('USDC to move back, in US dollars, or "all".') },
1232
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
1233
+ }, serial(async ({ amount_usd }, deadline, count) => {
1234
+ needWallet("return_to_robinhood");
1235
+ const f = await settleFlight();
1236
+ if (f) throw new ToolError(blocked(f));
1237
+ const float = await bridge.floatOf(wallet.address);
1238
+ // USDC that payments signed on Base and not settled yet still need stays: the merchant may cash them until they expire.
1239
+ const held = heldOnBase();
1240
+ const free = float > held ? float - held : 0n;
1241
+ const amount = amount_usd === "all" ? free : dollars(amount_usd, "amount_usd");
1242
+ const owes = held > 0n ? `, of which ${X.formatUsdg(held)} is held for signed payments on Base not settled yet` : "";
1243
+ if (amount === 0n) throw new ToolError(amount_usd === "all" ? `The Base float holds ${X.formatUsdg(float)} USDC${owes}: nothing to move back.` : "amount_usd must be above zero");
1244
+ if (amount > free) throw new ToolError(`The Base float holds ${X.formatUsdg(float)} USDC${owes}: at most ${X.formatUsdg(free)} can move back now. Nothing was done.`);
1245
+ if (amount > maxBridgeCeiling) throw new ToolError(`${X.formatUsdg(amount)} is above this server's ceiling of ${X.formatUsdg(maxBridgeCeiling)} per transfer (PRIORS_MAX_BRIDGE_USD): move it back in parts.`);
1246
+ if (session.bridged + amount > bridgeTotalCap) throw new ToolError(`this would bring what moved between Robinhood Chain and Base in this session to ${X.formatUsdg(session.bridged + amount)}, above ${X.formatUsdg(bridgeTotalCap)} (PRIORS_MAX_BRIDGE_TOTAL_USD).`);
1247
+ count("bridged", amount);
1248
+ let rec = null, r;
1249
+ try {
1250
+ r = await bridge.returnToRobinhood({ amount, maxFeeBps: maxBridgeFeeBps, timeoutMs: bridgeTimeoutMs, pollUntil: deadline - BRIDGE_MARGIN_MS, onSigned: async (t) => { rec = await recordFlight(t); } });
1251
+ } catch (e) {
1252
+ if (!rec || e?.moved === false) {
1253
+ if (rec) await clearFlight(rec);
1254
+ if (otherSession(e)) throw new ToolError("Another session of this wallet has a transfer to or from Base in flight. Nothing was signed or sent: check wallet_balance in a minute.");
1255
+ throw new ToolError(`${explain(e)}. Nothing left the Base float.`);
1256
+ }
1257
+ session.bridged += amount; // the authorization is out: counted, and its record holds every other transfer until it expires
1258
+ throw new ToolError(`${explain(e)}. ${stillOut("return_to_robinhood")}`);
1259
+ }
1260
+ session.bridged += amount;
1261
+ await clearFlight(rec);
1262
+ return `Moved ${X.formatUsdg(amount)} USDC from Base back to Robinhood Chain through Relay: ${usd(r.expectedOut)} delivered to ${wallet.address} (fee ${X.formatUsdg(r.fee)}).${r.txHashes?.length ? ` Tx ${r.txHashes.join(", ")}.` : ""} Relay request ${r.requestId}.`;
1263
+ }));
1264
+ }
1265
+
910
1266
  // ---- autopay_on / autopay_off ---------------------------------------------------------------------------------
911
1267
  // Autopay: the agent's own wallet approves AutoRepay for a budget (4 x the limit, never unlimited)
912
1268
  // and enrolls; Priors' keeper (or anyone) then repays each loan in the 6 hours before it is due, from this wallet,
@@ -1005,7 +1361,8 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
1005
1361
  // Payments signed and not yet settled still need their USDG in the wallet: never save it away from under them.
1006
1362
  const nowS = Math.floor(Date.now() / 1000);
1007
1363
  refresh(); // another session's pending payments need their USDG too
1008
- const reserved = [...outstanding.values()].filter((v) => live(v, nowS)).reduce((a, v) => a + v.price, 0n);
1364
+ // only Robinhood Chain's: a payment signed on Base is paid from the Base float, not from this USDG
1365
+ const reserved = [...outstanding.values()].filter((v) => live(v, nowS) && onRobinhood(v)).reduce((a, v) => a + v.price, 0n);
1009
1366
  if (reserved > 0n) {
1010
1367
  const b = await credit.balances(wallet.address);
1011
1368
  if (b.usdg < amount + reserved) throw new ToolError(`${usd(reserved)} of the wallet's USDG is held for signed payments that have not settled yet; at most ${usd(b.usdg > reserved ? b.usdg - reserved : 0n)} can be saved now.`);