@priors/mcp 0.9.0 → 0.9.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,27 @@
1
1
  # @priors/mcp changelog
2
2
 
3
+ ## 0.9.1 (2026-10-13)
4
+
5
+ - **`stock_line_request` checks the caps against the line the deposit opens.** The deposit is the line's need × 1.3,
6
+ so the vault opens about 1.3 times the line asked for (at most its largest line); the token's cap and the week's room
7
+ were checked against the line asked for, so a 100 USDG request with 110 USDG of room returned a link to a deposit that
8
+ opens 130 USDG, which the vault refuses. The request is now refused when the line the filled deposit opens is over
9
+ either, and the answer names the largest line that fits with the same room for a 23% fall.
10
+ - **`stock_line_request` sizes a named agent at its own loan-to-value**: the vault's `ltvOf(agent, token)`, the token's
11
+ own plus the agent's record bonus, which is what the vault opens its line at. It sized at the token's own, so an agent
12
+ with a bonus was asked for more of the token than its line needs (about 25% more at 75% against 60%). The answer says
13
+ the bonus; when that figure cannot be read, the request is refused rather than sized at the token's own.
14
+ - **`stock_line_request` without `agent_id` no longer turns a failed lookup into a new agent's link.** With a wallet
15
+ configured, a wallet that owns several agent identities, or none, a lookup that failed, or a key that can't be used
16
+ now gives a tool error that asks for `agent_id`; before, the link opened the new-agent deposit, where the owner could
17
+ fund another identity than the agent's. `PRIORS_AGENT_ID` is used when set. Only with no wallet configured (and no
18
+ `PRIORS_AGENT_ID`) is a request without `agent_id` for a new agent.
19
+ - `stock_line_request` refuses an agent whose owner has a default marked on their account (the pool's `ownerDefaults`,
20
+ which `StockVault.open` refuses for every agent of that owner), instead of a link to a sheet that can open nothing.
21
+ - `stock_line_request` names the tab as Go mode shows it (Stock lines, not Backing), and says the pool's grace as it is,
22
+ never rounded up (a 36 h grace reads 1.5 days). `pt_position` names it the same where the vault takes PT-USDG
23
+ behind a line ("Go mode's Stock lines tab").
24
+
3
25
  ## 0.9.0 (2026-10-12)
4
26
 
5
27
  - **`stock_line_request`**: when the agent's line is too small for a task, it asks its owner for a line backed by a
package/README.md CHANGED
@@ -7,8 +7,8 @@ borrow from and repay the agent's own Priors line, and keep its spare USDG saved
7
7
  ## Just reading? Use the hosted server
8
8
 
9
9
  No install and no key: `https://mcp.priors.trade/mcp` (Streamable HTTP) answers the read-only questions (an agent's
10
- record and score, the pool's figures, recent loans, the facilitator's services) from the same public data as
11
- priors.trade. It holds no key and cannot send a transaction.
10
+ record and score, a backer's record, the pool's figures, recent loans, the facilitator's services) from the same public
11
+ data as priors.trade. It holds no key and cannot send a transaction.
12
12
 
13
13
  ```bash
14
14
  claude mcp add --transport http priors https://mcp.priors.trade/mcp
@@ -16,6 +16,13 @@ claude mcp add --transport http priors https://mcp.priors.trade/mcp
16
16
 
17
17
  or, in any client that takes a remote server: `{ "mcpServers": { "priors": { "url": "https://mcp.priors.trade/mcp" } } }`.
18
18
 
19
+ **Show the agent's record** in its README with the badge (its score and loans repaid, red once it has defaulted), its
20
+ own id for `<id>`; Copy badge on `priors.trade/agent?id=<id>` gives the line with the id filled in:
21
+
22
+ ```markdown
23
+ [![Priors record](https://priors.trade/api/badge/<id>.svg)](https://priors.trade/agent?id=<id>)
24
+ ```
25
+
19
26
  This package is the other half: a local server with the agent's wallet behind it, for paying, borrowing and
20
27
  repaying.
21
28
 
@@ -171,7 +178,7 @@ Settings → Developer → Edit Config (`claude_desktop_config.json`), then rest
171
178
  "mcpServers": {
172
179
  "priors": {
173
180
  "command": "npx",
174
- "args": ["-y", "@priors/mcp@0.9.0"],
181
+ "args": ["-y", "@priors/mcp@0.9.1"],
175
182
  "env": {
176
183
  "PRIORS_KEY": "0xYOUR_AGENT_WALLET_KEY",
177
184
  "PRIORS_AGENT_ID": "1234"
@@ -193,7 +200,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
193
200
  "mcpServers": {
194
201
  "priors": {
195
202
  "command": "npx",
196
- "args": ["-y", "@priors/mcp@0.9.0"],
203
+ "args": ["-y", "@priors/mcp@0.9.1"],
197
204
  "env": {
198
205
  "PRIORS_KEY": "${PRIORS_KEY}",
199
206
  "PRIORS_AGENT_ID": "${PRIORS_AGENT_ID:-}"
@@ -206,7 +213,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
206
213
  or, for your user only, from a macOS or Linux terminal:
207
214
 
208
215
  ```sh
209
- (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.9.0' priors-mcp ~/.config/priors/agent.key
216
+ (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.9.1' priors-mcp ~/.config/priors/agent.key
210
217
  ```
211
218
 
212
219
  It waits for the key without showing it (paste it, then Enter), saves it in a file only you can read, and gives Claude
@@ -262,7 +269,7 @@ to approve a borrow; this package, with the key, pays for APIs. With borrowing o
262
269
  approves each loan in Priors' Go mode. ElizaOS (`@elizaos/plugin-mcp`):
263
270
 
264
271
  ```ts
265
- "priors-wallet": { type: "stdio", command: "npx", args: ["-y", "@priors/mcp@0.9.0"],
272
+ "priors-wallet": { type: "stdio", command: "npx", args: ["-y", "@priors/mcp@0.9.1"],
266
273
  env: { PRIORS_KEY_FILE: "/home/agent/.config/priors/agent-7311.key", PRIORS_AGENT_ID: "7311",
267
274
  PRIORS_MAX_BORROW_USD: "0", PRIORS_MAX_BORROW_DAY_USD: "0", PRIORS_MAX_SPEND_DAY_USD: "1", PRIORS_MAX_PRICE_USD: "0.10",
268
275
  PRIORS_PAY_HOSTS: "api.example.com" } }
@@ -274,7 +281,7 @@ OpenClaw (`mcp.servers`, JSON5) takes the same `command`, `args` and `env`; Herm
274
281
  mcp_servers:
275
282
  priors-wallet:
276
283
  command: npx
277
- args: ["-y", "@priors/mcp@0.9.0"]
284
+ args: ["-y", "@priors/mcp@0.9.1"]
278
285
  env:
279
286
  PRIORS_KEY_FILE: /home/agent/.config/priors/agent-7311.key
280
287
  PRIORS_AGENT_ID: "7311"
@@ -301,7 +308,7 @@ key proves it is there: it signs the ERC-8004 identity registry's `AgentWalletSe
301
308
  agent's).
302
309
 
303
310
  ```sh
304
- PRIORS_KEY_FILE=~/.config/priors/agent-7311.key npx -y @priors/mcp@0.9.0 link-wallet --agent 7311
311
+ PRIORS_KEY_FILE=~/.config/priors/agent-7311.key npx -y @priors/mcp@0.9.1 link-wallet --agent 7311
305
312
  ```
306
313
 
307
314
  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.9.0",
4
+ "version": "0.9.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.7.0",
48
+ "@priors/x402": "0.7.1",
49
49
  "ethers": "^6.13.4",
50
50
  "undici": "6.29.0",
51
51
  "viem": "^2.56.9",
package/src/server.mjs CHANGED
@@ -104,11 +104,11 @@ const ADDRESSES = JSON.parse(readFileSync(new URL("../deployments/4663.v2.json",
104
104
  /** The stock tokens the stock vault accepts (a copy of the repository's deployments/stock-assets.4663.json). */
105
105
  const STOCK_ASSETS = JSON.parse(readFileSync(new URL("../deployments/stock-assets.4663.json", import.meta.url), "utf8")).assets;
106
106
  // stock_line_request's reads of the stock vault beyond @priors/x402's: the token's cap and open lines, the vault's
107
- // maxLine, the week's room and its root, and the fair default's buffer (an implementation without seizeBufferOf keeps
108
- // the whole deposit on a default: null)
107
+ // maxLine, the week's room and its root, the fair default's buffer (an implementation without seizeBufferOf keeps
108
+ // the whole deposit on a default: null), and a named agent's loan-to-value (ltvOf: the token's own plus its record bonus)
109
109
  const STOCK_LINE_ABI = [
110
110
  "function params() view returns (uint256 ltvBps, uint256 maxLine, uint256 epochCap, uint64 epochLength)", "function epochRoom() view returns (uint256)", "function agentId() view returns (uint256)",
111
- "function openLinesOf(address token) view returns (uint256)", "function seizeBufferOf(address token) view returns (uint256)",
111
+ "function openLinesOf(address token) view returns (uint256)", "function seizeBufferOf(address token) view returns (uint256)", "function ltvOf(uint256 id, address token) view returns (uint256)",
112
112
  "function assets(address token) view returns (address feed, uint64 maxAge, uint8 tokenDecimals, uint8 feedDecimals, bool enabled, uint16 ltvBps, uint128 lineCap)",
113
113
  ];
114
114
  // Go mode's account page, where the owner reviews what the agent asked for (the hosted server's APP_URL)
@@ -698,13 +698,24 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
698
698
  const v = new ethers.Contract(addresses.stockVault, STOCK_LINE_ABI, provider);
699
699
  const meta = STOCK_ASSETS.find((a) => a.symbol.toUpperCase() === symbol) || null;
700
700
  const [vp, room, root, pp] = await Promise.all([v.params(), v.epochRoom(), v.agentId(), contracts.pool.getParams()]);
701
- let asset = null;
701
+ let asset = null, agentLtv = null;
702
702
  if (meta) {
703
- const [[x], a, lines, buffer] = await Promise.all([C.stockAssets(contracts, [meta]), v.assets(meta.token), v.openLinesOf(meta.token), v.seizeBufferOf(meta.token).catch(() => null)]);
703
+ // a named agent's own loan-to-value, its record bonus included: the vault opens its line at that, not the token's
704
+ // own (ltvOf(0, token), the stockAssets figure); unread, null, and the request is refused (sdk stock-line.mjs)
705
+ const [[x], a, lines, buffer, ltv] = await Promise.all([C.stockAssets(contracts, [meta]), v.assets(meta.token), v.openLinesOf(meta.token), v.seizeBufferOf(meta.token).catch(() => null),
706
+ id != null ? v.ltvOf(BigInt(id), meta.token).catch(() => null) : null]);
704
707
  asset = { symbol: meta.symbol, name: meta.name, token: meta.token, answer: x.answer, decimals: meta.decimals, feedDecimals: meta.feedDecimals, ltvBps: x.ltvBps, usable: !!x.usable, hold: Number(x.hold || 0), holdReason: x.holdReason || "", lineCap: a.lineCap, openLines: lines, seizeBufferBps: buffer };
708
+ agentLtv = ltv;
705
709
  }
706
710
  let agent = null;
707
- if (id != null) { const st = await C.creditStatus(contracts, id); agent = { id: Number(id), defaulted: !!st.defaulted, isRoot: !!st.isRoot, sponsor: Number(st.sponsor), activeLoans: st.openLoans.length, stockLine: !!st.collateral }; }
711
+ if (id != null) {
712
+ const st = await C.creditStatus(contracts, id);
713
+ // a default marked on the owner's account (the pool's ownerDefaults): StockVault.open refuses every agent of it
714
+ // the owner unread is never "no default on the owner's account" (review 2026-10-13): refused, try again
715
+ if (!st.owner) throw new ToolError(`Agent #${Number(id)}'s owner couldn't be read from the chain just now, so whether its owner has a default can't be told: try again in a minute.`);
716
+ const ownerDefaulted = (await contracts.pool.ownerDefaults(st.owner)) > 0n;
717
+ agent = { id: Number(id), defaulted: !!st.defaulted, ownerDefaulted, isRoot: !!st.isRoot, sponsor: Number(st.sponsor), activeLoans: st.openLoans.length, stockLine: !!st.collateral, ltvBps: agentLtv };
718
+ }
708
719
  return { asset, vault: { maxLine: vp.maxLine, epochRoom: room, root: Number(root) }, pool: { feeBps: pp.feeBps, minLoan: pp.minLoan, graceDays: Number(pp.grace) / 86400 }, agent, count: STOCK_ASSETS.length };
709
720
  },
710
721
  quote: (id, amount, term) => C.quoteBorrow(contracts, id, amount, term),
@@ -1142,16 +1153,26 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
1142
1153
  // sdk/stock-line.mjs). It reads; it never deposits, signs or holds the owner's tokens.
1143
1154
  tool("stock_line_request", {
1144
1155
  title: "Ask the owner for a stock-backed line",
1145
- description: "When the agent's Priors line is too small for a task, ask its owner for a line backed by a Robinhood stock token the owner holds: checks the token takes new lines now (price, holds, caps, the week's room) and the agent can take one, sizes the deposit to the line asked for (with room for a 23% fall), states the cost in cents for a day and a week and what a default would keep, and returns a Go mode link that opens the owner's deposit sheet already filled in. Nothing is deposited or signed by this tool. Ask once per task, and only for what the task needs. agent_id defaults to the configured wallet's agent.",
1156
+ description: "When the agent's Priors line is too small for a task, ask its owner for a line backed by a Robinhood stock token the owner holds: checks the token takes new lines now (price, holds, caps, the week's room, against the line the deposit opens) and the agent can take one, sizes the deposit to the line asked for at the agent's own loan-to-value (its record bonus included), with room for a 23% fall, states the cost in cents for a day and a week and what a default would keep, and returns a Go mode link that opens the owner's deposit sheet already filled in. Nothing is deposited or signed by this tool. Ask once per task, and only for what the task needs. agent_id defaults to the configured agent (PRIORS_AGENT_ID, or the one identity minted to the configured wallet); when a wallet is configured and its agent can't be told, the call fails and asks for agent_id. Without agent_id and with no wallet configured, the request is for a new agent.",
1146
1157
  inputSchema: {
1147
- agent_id: z.number().int().nonnegative().optional().describe("The agent the line is for (an ERC-8004 id); default: the configured wallet's agent, or a new agent without one."),
1158
+ agent_id: z.number().int().nonnegative().optional().describe("The agent the line is for (an ERC-8004 id); default: PRIORS_AGENT_ID or the configured wallet's agent (an error asks for agent_id when that can't be told), or a new agent when no wallet is configured."),
1148
1159
  symbol: z.string().min(1).max(12).describe("The stock token's ticker, e.g. SPY (stock_assets lists them)."),
1149
1160
  line_usd: z.number().positive().max(1_000_000).describe("The line wanted, in USDG (lines are capped at the vault's maxLine, 500 today)."),
1150
1161
  reason: z.string().max(200).optional().describe("Why the agent needs it, in one sentence, for its owner."),
1151
1162
  },
1152
1163
  annotations: { readOnlyHint: true, openWorldHint: true },
1153
1164
  }, async ({ agent_id, symbol, line_usd, reason }) => {
1154
- const id = agent_id !== undefined ? agent_id : wallet ? Number(await resolveAgent().catch(() => null)) || null : null;
1165
+ // agent_id, else the configured agent: PRIORS_AGENT_ID, or the one identity minted to the configured wallet. A wallet
1166
+ // whose agent can't be told (several, none, the lookup failing, a key that can't be used) is a tool error that asks
1167
+ // for agent_id: a new agent's link would have the owner fund another identity than the agent's. Only with no wallet
1168
+ // and no PRIORS_AGENT_ID is the request for a new agent (null).
1169
+ let id = agent_id ?? null;
1170
+ if (agent_id === undefined) {
1171
+ const ask = "Pass agent_id, the agent the line is for: with a wallet configured, a request without it is never taken as one for a new agent.";
1172
+ if (env.PRIORS_AGENT_ID || wallet) {
1173
+ try { id = Number(await resolveAgent()); } catch (e) { throw new ToolError(e instanceof ToolError ? `${e.message.replace(/ Set PRIORS_AGENT_ID or pass agent_id\.$/, "")} ${ask}` : `This wallet's agent could not be looked up just now (${explain(e)}). ${ask}`); }
1174
+ } else if (keyProblem) throw new ToolError(`The configured wallet can't be used (${keyProblem}), so its agent can't be looked up. ${ask}`);
1175
+ }
1155
1176
  const want = String(symbol).trim().toUpperCase();
1156
1177
  const inp = await credit.stockLineInputs(want, id);
1157
1178
  const r = stockLineRequest({ ...inp, lineUsd: line_usd, reason, appUrl: GO_APP_URL, asOf: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), symbol });
@@ -1622,7 +1643,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
1622
1643
  ? `It also holds ${nf(m.balanceText)} PT-USDG of the market that matured on ${m.maturity.slice(0, 10)} (token ${m.token}): it redeems 1:1 for USDG now (pt_redeem with market ${m.market}).`
1623
1644
  : `It also holds ${nf(m.balanceText)} PT-USDG of an earlier market (token ${m.token}): it redeems 1:1 for USDG from ${m.maturity.slice(0, 10)}.`));
1624
1645
  const listingLine = (l) => (!l ? "The stock vault's listing could not be read just now."
1625
- : l.backsLines ? `The Priors stock vault takes PT-USDG behind an agent's line now, at up to ${l.ltvBps / 100}% of its value (all PT-USDG lines share one ${capText(l.lineCap)} cap): deposit it with the SDK's openPtLine(agentId, amount) or in Go mode's Backing tab.`
1646
+ : l.backsLines ? `The Priors stock vault takes PT-USDG behind an agent's line now, at up to ${l.ltvBps / 100}% of its value (all PT-USDG lines share one ${capText(l.lineCap)} cap): deposit it with the SDK's openPtLine(agentId, amount) or in Go mode's Stock lines tab.`
1626
1647
  : l.listed ? "The Priors stock vault lists PT-USDG but takes no new line on it now (disabled, or the shared cap is used up)."
1627
1648
  : `The Priors stock vault does not list PT-USDG yet. Once it does, PT-USDG backs an agent's line (planned: up to ${l.planned.ltvBps / 100}% of its value, one ${capText(BigInt(l.planned.lineCap))} cap for all PT-USDG lines).`);
1628
1649
  const slippage = z.number().int().min(0).max(500).optional().describe("Slippage margin in basis points under the quote, 0 to 500. Default 100 (1%), 10 for a redemption.");
@@ -85,18 +85,21 @@ export function defaultRule(bufferBps, graceDays = 3) {
85
85
 
86
86
  // ---- stock_line_request: an agent asks its owner for a stock line (both MCP servers) ----
87
87
 
88
+ /** Token units rounded up at `max` decimal places (of a `decimals`-decimal token): the figure a sheet fills. */
89
+ export function upAt(units, decimals, max = 6) {
90
+ const d = Number(decimals), cut = d > max ? 10n ** BigInt(d - max) : 1n;
91
+ return ((big(units) + cut - 1n) / cut) * cut;
92
+ }
88
93
  /** Token units as a decimal string, rounded up at `max` places: what the link fills is never short of the figure said. */
89
94
  export function tokenText(units, decimals, max = 6) {
90
- units = big(units);
91
- const d = Number(decimals), cut = d > max ? 10n ** BigInt(d - max) : 1n;
92
- const up = ((units + cut - 1n) / cut) * cut, base = 10n ** BigInt(d);
95
+ const d = Number(decimals), up = upAt(units, d, max), base = 10n ** BigInt(d);
93
96
  const frac = (up % base).toString().padStart(d, "0").slice(0, Math.min(d, max)).replace(/0+$/, "");
94
97
  return `${up / base}${frac ? "." + frac : ""}`;
95
98
  }
96
99
  const usd = (units) => { const u = big(units), w = u / 1_000_000n, f = (u % 1_000_000n).toString().padStart(6, "0").replace(/0+$/, ""); return `${w}${f ? "." + f.slice(0, 6) : ""}`; };
97
100
  const oneLine = (s, n) => String(s ?? "").replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim().slice(0, n);
98
101
 
99
- /** Go mode's link for the request: the Backing tab's deposit sheet on that token, for that agent, sized to that line
102
+ /** Go mode's link for the request: the Stock lines tab's deposit sheet on that token, for that agent, sized to that line
100
103
  * (web/account-stocks.js reads ai=stock once). It carries nothing to sign: the owner's own Deposit click does it all. */
101
104
  export function stockLink(appUrl, { agentId = null, symbol, line }) {
102
105
  const u = new URL(appUrl);
@@ -112,10 +115,18 @@ export function stockLink(appUrl, { agentId = null, symbol, line }) {
112
115
  * The answer to stock_line_request, the same in both MCP servers: { refusal } when the line can't open now (and why,
113
116
  * in words), else { data, text }. Inputs, read by each server its own way:
114
117
  * asset { symbol, name, token, answer, decimals, feedDecimals, ltvBps, usable, hold, holdReason, lineCap, openLines,
115
- * seizeBufferBps } (null: not a token the vault takes); vault { maxLine, epochRoom, root }; pool { feeBps,
116
- * minLoan, graceDays }; agent { id, defaulted, isRoot, sponsor, activeLoans, stockLine } or null (a new agent);
117
- * lineUsd (a number of dollars), reason (the agent's own words, kept in this answer only), appUrl, count (the tokens
118
- * the vault takes, for the refusal), asOf.
118
+ * seizeBufferBps } (null: not a token the vault takes; ltvBps the token's own, ltvOf(0, token)); vault {
119
+ * maxLine, epochRoom, root }; pool { feeBps, minLoan, graceDays }; agent { id, defaulted, ownerDefaulted (a default
120
+ * marked on its owner's account: the pool's ownerDefaults, which StockVault.open refuses for every agent of that
121
+ * owner), isRoot, sponsor, activeLoans, stockLine, ltvBps } or null (a new agent), where ltvBps is the vault's
122
+ * ltvOf(id, token), the token's own plus the agent's record bonus: what the vault opens its line at (null when it
123
+ * could not be read: refused, since the token's own would ask the owner for more than the line needs); lineUsd (a
124
+ * number of dollars), reason (the agent's own words, kept in this answer only), appUrl, count (the tokens the vault
125
+ * takes, for the refusal), asOf.
126
+ * The caps (the token's, with its open lines; the week's room) hold the line the deposit opens, not the line asked for:
127
+ * the deposit the link fills (× 1.3, rounded up at 6 places) opens about 1.3 times the ask, at most maxLine. When that
128
+ * is over a cap the request is refused, naming the largest ask whose deposit still fits: the link never fills a
129
+ * deposit the vault would refuse, and never one with less room for a fall than it says.
119
130
  */
120
131
  export function stockLineRequest({ asset, vault, pool, agent = null, lineUsd, reason = "", appUrl, count = null, asOf = null, symbol = "" }) {
121
132
  const n = Number(lineUsd);
@@ -126,32 +137,55 @@ export function stockLineRequest({ asset, vault, pool, agent = null, lineUsd, re
126
137
  const sym = asset.symbol;
127
138
  if (agent) {
128
139
  if (agent.defaulted) return { refusal: `Agent #${agent.id} has defaulted: no new line can open for it.` };
140
+ if (agent.ownerDefaulted) return { refusal: `A default on the account that owns agent #${agent.id} stops new lines and loans for all its agents: no new line can open for it.` };
129
141
  if (agent.isRoot) return { refusal: `Agent #${agent.id} is a backer (root): backers lend their stake, they do not borrow.` };
130
- if (agent.stockLine) return { refusal: `Agent #${agent.id} already has a stock line. Its owner can add stock to it in Go mode (Backing tab, Add stock) to raise what it can draw.` };
142
+ if (agent.stockLine) return { refusal: `Agent #${agent.id} already has a stock line. Its owner can add stock to it in Go mode (Stock lines tab, Add stock) to raise what it can draw.` };
131
143
  if (agent.sponsor && String(agent.sponsor) !== String(vault.root) && Number(agent.activeLoans) > 0) return { refusal: `Agent #${agent.id} has ${agent.activeLoans} loan(s) open on its line from backer #${agent.sponsor}. A stock line takes over the agent's backing (one backer per agent), so those loans are repaid first.` };
132
144
  }
133
145
  if (!asset.usable || Number(asset.hold || 0) !== 0) return { refusal: `The vault opens no new line on ${sym} right now${asset.holdReason ? `: ${asset.holdReason}` : " (its price is not usable now)"}. stock_assets lists the tokens that take new lines.` };
134
146
  if (asset.lineCap != null && big(asset.lineCap) === 0n) return { refusal: `The vault takes no new line on ${sym} (its cap is 0). stock_assets lists the tokens that take new lines.` };
135
- const sized = sizeStockLine({ line: units, price: asset.answer, tokenDecimals: asset.decimals, feedDecimals: asset.feedDecimals, ltvBps: asset.ltvBps, maxLine: vault.maxLine ?? null, minLoan: pool.minLoan ?? null });
147
+ if (agent && agent.ltvBps == null) return { refusal: `Agent #${agent.id}'s loan-to-value on ${sym} (the token's own plus its record bonus) could not be read from the chain just now, so the deposit cannot be sized: try again in a minute.` };
148
+ const ltvBps = big(agent ? agent.ltvBps : asset.ltvBps), ownBps = big(asset.ltvBps);
149
+ if (ltvBps <= 0n) return { refusal: `The vault takes no new line on ${sym} (its loan-to-value is 0). stock_assets lists the tokens that take new lines.` };
150
+ const sizing = { price: asset.answer, tokenDecimals: asset.decimals, feedDecimals: asset.feedDecimals, ltvBps, maxLine: vault.maxLine ?? null, minLoan: pool.minLoan ?? null };
151
+ const sized = sizeStockLine({ line: units, ...sizing });
136
152
  if (pool.minLoan != null && sized.line < big(pool.minLoan)) return { refusal: `A line is at least ${usd(pool.minLoan)} USDG (the pool's smallest loan).` };
137
- if (asset.lineCap != null && asset.openLines != null && big(asset.openLines) + sized.line > big(asset.lineCap)) return { refusal: `${sym} lines share a cap of ${usd(asset.lineCap)} USDG and ${usd(big(asset.lineCap) > big(asset.openLines) ? big(asset.lineCap) - big(asset.openLines) : 0n)} USDG of it is left: ask for less, or another token.` };
138
- if (vault.epochRoom != null && big(vault.epochRoom) < sized.line) return { refusal: `The vault opens at most ${usd(vault.epochRoom)} USDG of new lines more this week: ask for less, or later.` };
153
+ // the line the vault opens for the deposit the link fills (rounded up at 6 places, as said): what every cap holds
154
+ const opens = (line) => {
155
+ const v = (valueOf(upAt(sizeStockLine({ line, ...sizing }).deposit, asset.decimals), asset.answer, asset.decimals, asset.feedDecimals) * ltvBps) / 10_000n;
156
+ return vault.maxLine != null && v > big(vault.maxLine) ? big(vault.maxLine) : v;
157
+ };
158
+ const opened = opens(sized.line);
159
+ const tokenLeft = asset.lineCap != null && asset.openLines != null ? (big(asset.lineCap) > big(asset.openLines) ? big(asset.lineCap) - big(asset.openLines) : 0n) : null;
160
+ const weekLeft = vault.epochRoom != null ? big(vault.epochRoom) : null;
161
+ if ((tokenLeft != null && opened > tokenLeft) || (weekLeft != null && opened > weekLeft)) {
162
+ const room = tokenLeft == null ? weekLeft : weekLeft == null || tokenLeft < weekLeft ? tokenLeft : weekLeft;
163
+ // the largest ask whose deposit opens within the room (opens() never falls as the ask grows), to the cent below
164
+ let lo = 0n, hi = sized.line;
165
+ while (lo < hi) { const mid = (lo + hi + 1n) / 2n; if (opens(mid) <= room) lo = mid; else hi = mid - 1n; }
166
+ const fit = lo - (lo % 10_000n);
167
+ const fits = fit > 0n && (pool.minLoan == null || fit >= big(pool.minLoan));
168
+ const deposit = `the deposit for a ${usd(sized.line)} USDG line, with room for a 23% fall, opens ${usd(opened)} USDG`;
169
+ if (tokenLeft != null && opened > tokenLeft) return { refusal: `${sym} lines share a cap of ${usd(asset.lineCap)} USDG and ${usd(tokenLeft)} USDG of it is left, and ${deposit}: ${fits ? `ask for at most ${usd(fit)} USDG, or another token` : "ask for another token"}.` };
170
+ return { refusal: `The vault opens at most ${usd(weekLeft)} USDG of new lines more this week, and ${deposit}: ${fits ? `ask for at most ${usd(fit)} USDG, or later` : "ask later"}.` };
171
+ }
139
172
  const costs = lineCosts(sized.line, pool.feeBps);
140
- const rule = defaultRule(asset.seizeBufferBps ?? null, pool.graceDays ?? 3);
173
+ // the grace in days as the pool has it, never rounded up (a 36 h grace is 1.5 days, not 2): down to a tenth
174
+ const rule = defaultRule(asset.seizeBufferBps ?? null, Math.floor(Number(pool.graceDays ?? 3) * 10) / 10);
141
175
  const approvalUrl = stockLink(appUrl, { agentId: agent ? agent.id : null, symbol: sym, line: sized.line });
142
176
  const price = Number(big(asset.answer)) / 10 ** Number(asset.feedDecimals);
143
177
  const why = oneLine(reason, 200);
144
178
  const moves = agent && agent.sponsor && String(agent.sponsor) !== String(vault.root);
145
179
  const data = {
146
180
  kind: "stock_line_request", agentId: agent ? agent.id : null, symbol: sym, token: asset.token, lineUsd: usd(sized.line), capped: sized.capped,
147
- price: price.toFixed(2), ltvBps: Number(asset.ltvBps), neededTokens: tokenText(sized.needed, asset.decimals), depositTokens: tokenText(sized.deposit, asset.decimals),
148
- lineOpenedUsd: usd(sized.lineOpened), costs: costs.map((c) => ({ days: c.days, usd: c.text.slice(1) })), feeBps: Number(pool.feeBps),
181
+ price: price.toFixed(2), ltvBps: Number(ltvBps), neededTokens: tokenText(sized.needed, asset.decimals), depositTokens: tokenText(sized.deposit, asset.decimals),
182
+ lineOpenedUsd: usd(opened), costs: costs.map((c) => ({ days: c.days, usd: c.text.slice(1) })), feeBps: Number(pool.feeBps),
149
183
  defaultRule: { kind: rule.kind, bufferBps: rule.bufferBps == null ? null : Number(rule.bufferBps) }, approvalUrl, reason: why || null, asOf,
150
184
  };
151
185
  const who = agent ? `Agent #${agent.id}` : "A new agent";
152
186
  const text = [
153
187
  `${who} asks its owner for a ${data.lineUsd} USDG line backed by ${sym}${sized.capped ? ` (lines are capped at ${usd(vault.maxLine)} USDG)` : ""}${why ? `. The agent's reason: "${why}"` : ""}.`,
154
- `At $${data.price} and ${data.ltvBps / 100}% of its value, the line needs at least ${data.neededTokens} ${sym}. The link fills ${data.depositTokens} ${sym} (1.3 times that), so what the agent can draw holds through a 23% fall; the owner keeps the rest of their ${sym}.`,
188
+ `At $${data.price} and ${data.ltvBps / 100}% of its value${ltvBps > ownBps ? ` (${sym}'s own ${Number(ownBps) / 100}%, plus ${Number(ltvBps - ownBps) / 100}% for agent #${agent.id}'s record)` : ""}, the line needs at least ${data.neededTokens} ${sym}. The link fills ${data.depositTokens} ${sym} (1.3 times that), so what the agent can draw holds through a 23% fall; the owner keeps the rest of their ${sym}.`,
155
189
  `Cost: borrowing the whole ${data.lineUsd} USDG costs about ${costs.map((c) => `${c.text} for ${c.days === 1 ? "a day" : c.days === 7 ? "a week" : `${c.days} days`}`).join(" or ")} (${data.feeBps / 100}% per 30 days), plus any backer premium.`,
156
190
  `${rule.text} A default also stops new lines for every agent of that owner.${moves ? ` The agent's current line from backer #${agent.sponsor} moves to the stock vault when this one opens.` : ""}`,
157
191
  `Nothing moves until the owner deposits, signed in to Go mode, where the vault's own quote is shown first: ${approvalUrl}`,