@priors/mcp 0.8.5 → 0.9.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.
- package/CHANGELOG.md +12 -0
- package/README.md +6 -6
- package/package.json +2 -2
- package/src/server.mjs +49 -0
- package/src/stock-line.mjs +160 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @priors/mcp changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.0 (2026-10-12)
|
|
4
|
+
|
|
5
|
+
- **`stock_line_request`**: when the agent's line is too small for a task, it asks its owner for a line backed by a
|
|
6
|
+
Robinhood stock token the owner holds. It checks the token takes new lines now (its price, holds, the token's cap, the
|
|
7
|
+
vault's room this week) and that the agent can take one, sizes the deposit to the line asked for (line ÷ LTV × 1.3,
|
|
8
|
+
so what the agent can draw holds through a 23% fall), states the cost in cents for a day and a week, says what a
|
|
9
|
+
default would keep as the live vault does it (its fair-default buffer, or the whole deposit), and returns a Go mode
|
|
10
|
+
link that opens the owner's deposit sheet already filled in. It reads; it never deposits, signs or holds the owner's
|
|
11
|
+
tokens. The same answer as the hosted server's tool (both from `src/stock-line.mjs`).
|
|
12
|
+
- `credit_status` names `stock_line_request` as the way to a bigger line, for an agent without a stock line.
|
|
13
|
+
- On `@priors/x402` 0.7.0.
|
|
14
|
+
|
|
3
15
|
## 0.8.5 (2026-10-12)
|
|
4
16
|
|
|
5
17
|
- **Money counts in the UTC day it lands** (GHSA-266h-jfr9-42cx). A call reserved its room in the day it started and
|
package/README.md
CHANGED
|
@@ -171,7 +171,7 @@ Settings → Developer → Edit Config (`claude_desktop_config.json`), then rest
|
|
|
171
171
|
"mcpServers": {
|
|
172
172
|
"priors": {
|
|
173
173
|
"command": "npx",
|
|
174
|
-
"args": ["-y", "@priors/mcp@0.
|
|
174
|
+
"args": ["-y", "@priors/mcp@0.9.0"],
|
|
175
175
|
"env": {
|
|
176
176
|
"PRIORS_KEY": "0xYOUR_AGENT_WALLET_KEY",
|
|
177
177
|
"PRIORS_AGENT_ID": "1234"
|
|
@@ -193,7 +193,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
|
|
|
193
193
|
"mcpServers": {
|
|
194
194
|
"priors": {
|
|
195
195
|
"command": "npx",
|
|
196
|
-
"args": ["-y", "@priors/mcp@0.
|
|
196
|
+
"args": ["-y", "@priors/mcp@0.9.0"],
|
|
197
197
|
"env": {
|
|
198
198
|
"PRIORS_KEY": "${PRIORS_KEY}",
|
|
199
199
|
"PRIORS_AGENT_ID": "${PRIORS_AGENT_ID:-}"
|
|
@@ -206,7 +206,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
|
|
|
206
206
|
or, for your user only, from a macOS or Linux terminal:
|
|
207
207
|
|
|
208
208
|
```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.
|
|
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
|
|
210
210
|
```
|
|
211
211
|
|
|
212
212
|
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 +262,7 @@ to approve a borrow; this package, with the key, pays for APIs. With borrowing o
|
|
|
262
262
|
approves each loan in Priors' Go mode. ElizaOS (`@elizaos/plugin-mcp`):
|
|
263
263
|
|
|
264
264
|
```ts
|
|
265
|
-
"priors-wallet": { type: "stdio", command: "npx", args: ["-y", "@priors/mcp@0.
|
|
265
|
+
"priors-wallet": { type: "stdio", command: "npx", args: ["-y", "@priors/mcp@0.9.0"],
|
|
266
266
|
env: { PRIORS_KEY_FILE: "/home/agent/.config/priors/agent-7311.key", PRIORS_AGENT_ID: "7311",
|
|
267
267
|
PRIORS_MAX_BORROW_USD: "0", PRIORS_MAX_BORROW_DAY_USD: "0", PRIORS_MAX_SPEND_DAY_USD: "1", PRIORS_MAX_PRICE_USD: "0.10",
|
|
268
268
|
PRIORS_PAY_HOSTS: "api.example.com" } }
|
|
@@ -274,7 +274,7 @@ OpenClaw (`mcp.servers`, JSON5) takes the same `command`, `args` and `env`; Herm
|
|
|
274
274
|
mcp_servers:
|
|
275
275
|
priors-wallet:
|
|
276
276
|
command: npx
|
|
277
|
-
args: ["-y", "@priors/mcp@0.
|
|
277
|
+
args: ["-y", "@priors/mcp@0.9.0"]
|
|
278
278
|
env:
|
|
279
279
|
PRIORS_KEY_FILE: /home/agent/.config/priors/agent-7311.key
|
|
280
280
|
PRIORS_AGENT_ID: "7311"
|
|
@@ -301,7 +301,7 @@ key proves it is there: it signs the ERC-8004 identity registry's `AgentWalletSe
|
|
|
301
301
|
agent's).
|
|
302
302
|
|
|
303
303
|
```sh
|
|
304
|
-
PRIORS_KEY_FILE=~/.config/priors/agent-7311.key npx -y @priors/mcp@0.
|
|
304
|
+
PRIORS_KEY_FILE=~/.config/priors/agent-7311.key npx -y @priors/mcp@0.9.0 link-wallet --agent 7311
|
|
305
305
|
```
|
|
306
306
|
|
|
307
307
|
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.
|
|
4
|
+
"version": "0.9.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_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.
|
|
48
|
+
"@priors/x402": "0.7.0",
|
|
49
49
|
"ethers": "^6.13.4",
|
|
50
50
|
"undici": "6.29.0",
|
|
51
51
|
"viem": "^2.56.9",
|
package/src/server.mjs
CHANGED
|
@@ -86,6 +86,7 @@ import { keyFromEnv, stateDirProblem } from "./key-file.mjs";
|
|
|
86
86
|
import { parsePayHosts, hostAllowed, hostKey, guardFetch } from "./pay-hosts.mjs";
|
|
87
87
|
import { agentOf, dailyLedger, ledgerOwners } from "./daily.mjs";
|
|
88
88
|
import { shareFacts, factsLine, repaidPost } from "./share.mjs";
|
|
89
|
+
import { stockLineRequest } from "./stock-line.mjs";
|
|
89
90
|
|
|
90
91
|
// @priors/x402 when installed from npm; the sibling package in the monorepo otherwise.
|
|
91
92
|
async function loadX402() {
|
|
@@ -102,6 +103,16 @@ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import
|
|
|
102
103
|
const ADDRESSES = JSON.parse(readFileSync(new URL("../deployments/4663.v2.json", import.meta.url), "utf8"));
|
|
103
104
|
/** The stock tokens the stock vault accepts (a copy of the repository's deployments/stock-assets.4663.json). */
|
|
104
105
|
const STOCK_ASSETS = JSON.parse(readFileSync(new URL("../deployments/stock-assets.4663.json", import.meta.url), "utf8")).assets;
|
|
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)
|
|
109
|
+
const STOCK_LINE_ABI = [
|
|
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)",
|
|
112
|
+
"function assets(address token) view returns (address feed, uint64 maxAge, uint8 tokenDecimals, uint8 feedDecimals, bool enabled, uint16 ltvBps, uint128 lineCap)",
|
|
113
|
+
];
|
|
114
|
+
// Go mode's account page, where the owner reviews what the agent asked for (the hosted server's APP_URL)
|
|
115
|
+
const GO_APP_URL = "https://go.priors.trade/account";
|
|
105
116
|
const DEFAULT_PAY_MAX_USD = 0.1;
|
|
106
117
|
|
|
107
118
|
/** A private key (64 hex, optional 0x) anywhere in a string: refused on the command line. */
|
|
@@ -681,6 +692,21 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
681
692
|
status: (id) => C.creditStatus(contracts, id),
|
|
682
693
|
stockAssets: () => C.stockAssets(contracts, STOCK_ASSETS),
|
|
683
694
|
stockPosition: (id) => C.stockPosition(contracts, id, STOCK_ASSETS),
|
|
695
|
+
// stock_line_request's inputs, shaped as the hosted server reads them from /api/stocks (sdk/stock-line.mjs)
|
|
696
|
+
stockLineInputs: async (symbol, id) => {
|
|
697
|
+
if (!addresses.stockVault) throw new ToolError("Priors has no stock vault configured: stock lines are not open.");
|
|
698
|
+
const v = new ethers.Contract(addresses.stockVault, STOCK_LINE_ABI, provider);
|
|
699
|
+
const meta = STOCK_ASSETS.find((a) => a.symbol.toUpperCase() === symbol) || null;
|
|
700
|
+
const [vp, room, root, pp] = await Promise.all([v.params(), v.epochRoom(), v.agentId(), contracts.pool.getParams()]);
|
|
701
|
+
let asset = null;
|
|
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)]);
|
|
704
|
+
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 };
|
|
705
|
+
}
|
|
706
|
+
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 }; }
|
|
708
|
+
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
|
+
},
|
|
684
710
|
quote: (id, amount, term) => C.quoteBorrow(contracts, id, amount, term),
|
|
685
711
|
borrow: (id, amount, term) => C.borrowLine(contracts, wallet, id, amount, term),
|
|
686
712
|
repay: (loanId) => C.repayLoan(contracts, wallet, loanId),
|
|
@@ -1063,6 +1089,8 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
1063
1089
|
];
|
|
1064
1090
|
if (s.openLoans.length === 0) lines.push("Open loans: none.");
|
|
1065
1091
|
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)" : ""}.`);
|
|
1092
|
+
// the way to a bigger line when a task needs one (once per task: the tool's own rule)
|
|
1093
|
+
if (!s.defaulted && !s.isRoot && !s.collateral && contracts.stockVault) lines.push("A task that needs more than this line: stock_line_request asks the agent's owner for a line backed by a Robinhood stock token they hold.");
|
|
1066
1094
|
lines.push(...(await autopayLines(id)));
|
|
1067
1095
|
// The day's limits (0.8.0) for the agent this server acts for: what is used today, across restarts and sessions.
|
|
1068
1096
|
if (ledger && (agent_id === undefined || BigInt(agent_id) === dayAgent)) {
|
|
@@ -1110,6 +1138,27 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
1110
1138
|
return [`Agent #${id}: stock line of ${usd(p.line)}, ${p.status}.`, collateralText(p)].join("\n");
|
|
1111
1139
|
});
|
|
1112
1140
|
|
|
1141
|
+
// ---- stock_line_request: the agent asks its owner for a stock-backed line (the hosted server's tool, the same answer:
|
|
1142
|
+
// sdk/stock-line.mjs). It reads; it never deposits, signs or holds the owner's tokens.
|
|
1143
|
+
tool("stock_line_request", {
|
|
1144
|
+
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.",
|
|
1146
|
+
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."),
|
|
1148
|
+
symbol: z.string().min(1).max(12).describe("The stock token's ticker, e.g. SPY (stock_assets lists them)."),
|
|
1149
|
+
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
|
+
reason: z.string().max(200).optional().describe("Why the agent needs it, in one sentence, for its owner."),
|
|
1151
|
+
},
|
|
1152
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
1153
|
+
}, async ({ agent_id, symbol, line_usd, reason }) => {
|
|
1154
|
+
const id = agent_id !== undefined ? agent_id : wallet ? Number(await resolveAgent().catch(() => null)) || null : null;
|
|
1155
|
+
const want = String(symbol).trim().toUpperCase();
|
|
1156
|
+
const inp = await credit.stockLineInputs(want, id);
|
|
1157
|
+
const r = stockLineRequest({ ...inp, lineUsd: line_usd, reason, appUrl: GO_APP_URL, asOf: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), symbol });
|
|
1158
|
+
if (r.refusal) throw new ToolError(r.refusal);
|
|
1159
|
+
return r.text;
|
|
1160
|
+
});
|
|
1161
|
+
|
|
1113
1162
|
// ---- score_of ------------------------------------------------------------------------------------------------
|
|
1114
1163
|
// Priors Score v2 (open weights, published at /api/score-v2) next to the on-chain v1: optional. Not published
|
|
1115
1164
|
// (404/503), slow or unreachable means v1 only, never a tool error; a defaulted agent never shows a positive v2.
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// A stock line sized from the line it needs (docs/research/2026-10-12-scale-rwa/PLAN.md W1-W2): how much of a token to
|
|
2
|
+
// deposit for a line of L USDG, what that line costs in cents, and the default rule in words. Pure: no chain, no
|
|
3
|
+
// network; every figure in the units the contracts use (USDG 6 decimals, the token's own, the feed's own).
|
|
4
|
+
// One file for every place that says it:
|
|
5
|
+
// - the hosted MCP's stock_line_request (mcp-worker/tools.mjs);
|
|
6
|
+
// - the local MCP's (packages/mcp/src/stock-line.mjs, a copy that scripts/test-packages.mjs checks is identical);
|
|
7
|
+
// - Go mode's deposit sheet (web-src/priors-app.mjs: PriorsApp.stockLine).
|
|
8
|
+
// The vault (src/StockVault.sol open, _valueOf) values `amount` tokens at floor(amount × price ÷ 10^(token + feed − 6))
|
|
9
|
+
// and opens a line of floor(value × ltv ÷ 10,000), at most maxLine; the quote it runs at Deposit is the last word.
|
|
10
|
+
|
|
11
|
+
/** The deposit is the line's need × 1.3: the borrow room stays whole through a 23% fall (1 − 1 ÷ 1.3). */
|
|
12
|
+
export const HEADROOM_BPS = 13_000n;
|
|
13
|
+
/** The two costs a sheet shows: a day and a week. */
|
|
14
|
+
export const COST_DAYS = [1, 7];
|
|
15
|
+
|
|
16
|
+
const big = (x) => (typeof x === "bigint" ? x : BigInt(x));
|
|
17
|
+
const ceilDiv = (a, b) => (a + b - 1n) / b;
|
|
18
|
+
|
|
19
|
+
/** The smallest amount of the token the vault values at `usdg` (6 decimals) or more at `price`. */
|
|
20
|
+
export function tokensFor(usdg, price, tokenDecimals, feedDecimals) {
|
|
21
|
+
usdg = big(usdg); price = big(price);
|
|
22
|
+
if (price <= 0n) throw new RangeError("tokensFor: a price above zero");
|
|
23
|
+
const scale = Number(tokenDecimals) + Number(feedDecimals);
|
|
24
|
+
return scale >= 6 ? ceilDiv(usdg * 10n ** BigInt(scale - 6), price) : ceilDiv(usdg, price * 10n ** BigInt(6 - scale));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** What the vault values `amount` of the token at (USDG, 6 decimals): its own rounding, down. */
|
|
28
|
+
export function valueOf(amount, price, tokenDecimals, feedDecimals) {
|
|
29
|
+
const scale = Number(tokenDecimals) + Number(feedDecimals);
|
|
30
|
+
return scale >= 6 ? (big(amount) * big(price)) / 10n ** BigInt(scale - 6) : big(amount) * big(price) * 10n ** BigInt(6 - scale);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The deposit for a line of `line` USDG on a token at `price` and `ltvBps` (the token's own, or the agent's with its
|
|
35
|
+
* record bonus): { line (capped at maxLine), needed (the least that opens it), deposit (needed's value × 1.3),
|
|
36
|
+
* capped, keep (the balance left after the deposit, when `balance` is given), short (the balance is under `needed`),
|
|
37
|
+
* tooSmall (under minLoan) }. `deposit` is never above the balance when one is given and covers `needed`; under
|
|
38
|
+
* `needed` the deposit is the whole balance and `short` says the line will be smaller.
|
|
39
|
+
*/
|
|
40
|
+
export function sizeStockLine({ line, price, tokenDecimals, feedDecimals, ltvBps, maxLine = null, minLoan = null, balance = null }) {
|
|
41
|
+
let want = big(line);
|
|
42
|
+
const ltv = big(ltvBps);
|
|
43
|
+
if (want <= 0n) throw new RangeError("sizeStockLine: a line above zero");
|
|
44
|
+
if (ltv <= 0n || ltv > 10_000n) throw new RangeError("sizeStockLine: an LTV between 1 and 10,000 bps");
|
|
45
|
+
const capped = maxLine != null && want > big(maxLine);
|
|
46
|
+
if (capped) want = big(maxLine);
|
|
47
|
+
const neededValue = ceilDiv(want * 10_000n, ltv);
|
|
48
|
+
const needed = tokensFor(neededValue, price, tokenDecimals, feedDecimals);
|
|
49
|
+
let deposit = tokensFor(ceilDiv(neededValue * HEADROOM_BPS, 10_000n), price, tokenDecimals, feedDecimals);
|
|
50
|
+
let keep = null, short = false;
|
|
51
|
+
if (balance != null) {
|
|
52
|
+
const bal = big(balance);
|
|
53
|
+
short = bal < needed;
|
|
54
|
+
if (deposit > bal) deposit = bal;
|
|
55
|
+
keep = bal - deposit;
|
|
56
|
+
}
|
|
57
|
+
const opens = (valueOf(deposit, price, tokenDecimals, feedDecimals) * ltv) / 10_000n;
|
|
58
|
+
const lineOpened = maxLine != null && opens > big(maxLine) ? big(maxLine) : opens;
|
|
59
|
+
return { line: want, needed, deposit, capped, keep, short, lineOpened, tooSmall: minLoan != null && lineOpened < big(minLoan) };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The pool's fee on `line` USDG held `days` days: line × feeBps × days ÷ (30 × 10,000), rounded up (USDG units). */
|
|
63
|
+
export function lineFee(line, feeBps, days) {
|
|
64
|
+
return ceilDiv(big(line) * big(feeBps) * BigInt(days), 30n * 10_000n);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** USDG units in dollars and cents: the nearest cent, half up; "$0.01" for anything above zero that rounds to 0. */
|
|
68
|
+
export function cents(units) {
|
|
69
|
+
units = big(units);
|
|
70
|
+
let c = (units + 5_000n) / 10_000n;
|
|
71
|
+
if (c === 0n && units > 0n) c = 1n;
|
|
72
|
+
return `$${(c / 100n).toLocaleString("en-US")}.${String(c % 100n).padStart(2, "0")}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The line's cost for each of COST_DAYS: [{ days, fee (USDG units), text ("$0.03") }]. */
|
|
76
|
+
export const lineCosts = (line, feeBps, days = COST_DAYS) => days.map((d) => { const fee = lineFee(line, feeBps, d); return { days: d, fee, text: cents(fee) }; });
|
|
77
|
+
|
|
78
|
+
/** The vault's default rule, from its buffer (bps) for the token: null when the vault has no buffer (an implementation
|
|
79
|
+
* from before the fair default, whose default keeps the whole deposit). */
|
|
80
|
+
export function defaultRule(bufferBps, graceDays = 3) {
|
|
81
|
+
if (bufferBps == null) return { kind: "all", bufferBps: null, text: `If a loan is still unpaid ${graceDays} days after it was due, the vault keeps the whole deposit. A falling price never sells it.` };
|
|
82
|
+
const pct = Number(big(bufferBps)) / 100;
|
|
83
|
+
return { kind: "fair", bufferBps: big(bufferBps), text: `If a loan is still unpaid ${graceDays} days after it was due, the vault keeps tokens worth what is owed plus ${pct}% and gives the rest back (it keeps them all if the stock's price can't be used that day). A falling price never sells it.` };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ---- stock_line_request: an agent asks its owner for a stock line (both MCP servers) ----
|
|
87
|
+
|
|
88
|
+
/** Token units as a decimal string, rounded up at `max` places: what the link fills is never short of the figure said. */
|
|
89
|
+
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);
|
|
93
|
+
const frac = (up % base).toString().padStart(d, "0").slice(0, Math.min(d, max)).replace(/0+$/, "");
|
|
94
|
+
return `${up / base}${frac ? "." + frac : ""}`;
|
|
95
|
+
}
|
|
96
|
+
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
|
+
const oneLine = (s, n) => String(s ?? "").replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim().slice(0, n);
|
|
98
|
+
|
|
99
|
+
/** Go mode's link for the request: the Backing tab's deposit sheet on that token, for that agent, sized to that line
|
|
100
|
+
* (web/account-stocks.js reads ai=stock once). It carries nothing to sign: the owner's own Deposit click does it all. */
|
|
101
|
+
export function stockLink(appUrl, { agentId = null, symbol, line }) {
|
|
102
|
+
const u = new URL(appUrl);
|
|
103
|
+
u.searchParams.set("ai", "stock");
|
|
104
|
+
if (agentId != null) u.searchParams.set("ai_agent", String(agentId));
|
|
105
|
+
u.searchParams.set("ai_token", symbol);
|
|
106
|
+
u.searchParams.set("ai_usd", usd(line));
|
|
107
|
+
u.hash = "ac-stocks";
|
|
108
|
+
return u.href;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The answer to stock_line_request, the same in both MCP servers: { refusal } when the line can't open now (and why,
|
|
113
|
+
* in words), else { data, text }. Inputs, read by each server its own way:
|
|
114
|
+
* 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.
|
|
119
|
+
*/
|
|
120
|
+
export function stockLineRequest({ asset, vault, pool, agent = null, lineUsd, reason = "", appUrl, count = null, asOf = null, symbol = "" }) {
|
|
121
|
+
const n = Number(lineUsd);
|
|
122
|
+
if (!(n > 0) || n > 1_000_000) return { refusal: "line_usd must be above 0 and at most 1,000,000." };
|
|
123
|
+
const units = BigInt(Math.round(n * 1e6));
|
|
124
|
+
if (Math.abs(Number(units) / 1e6 - n) > 1e-9) return { refusal: "line_usd has more than 6 decimals (USDG has 6)." };
|
|
125
|
+
if (!asset) return { refusal: `${oneLine(symbol, 12) || "That token"} is not among the ${count ?? "listed"} tokens the Priors stock vault takes.` };
|
|
126
|
+
const sym = asset.symbol;
|
|
127
|
+
if (agent) {
|
|
128
|
+
if (agent.defaulted) return { refusal: `Agent #${agent.id} has defaulted: no new line can open for it.` };
|
|
129
|
+
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.` };
|
|
131
|
+
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
|
+
}
|
|
133
|
+
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
|
+
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 });
|
|
136
|
+
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.` };
|
|
139
|
+
const costs = lineCosts(sized.line, pool.feeBps);
|
|
140
|
+
const rule = defaultRule(asset.seizeBufferBps ?? null, pool.graceDays ?? 3);
|
|
141
|
+
const approvalUrl = stockLink(appUrl, { agentId: agent ? agent.id : null, symbol: sym, line: sized.line });
|
|
142
|
+
const price = Number(big(asset.answer)) / 10 ** Number(asset.feedDecimals);
|
|
143
|
+
const why = oneLine(reason, 200);
|
|
144
|
+
const moves = agent && agent.sponsor && String(agent.sponsor) !== String(vault.root);
|
|
145
|
+
const data = {
|
|
146
|
+
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),
|
|
149
|
+
defaultRule: { kind: rule.kind, bufferBps: rule.bufferBps == null ? null : Number(rule.bufferBps) }, approvalUrl, reason: why || null, asOf,
|
|
150
|
+
};
|
|
151
|
+
const who = agent ? `Agent #${agent.id}` : "A new agent";
|
|
152
|
+
const text = [
|
|
153
|
+
`${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}.`,
|
|
155
|
+
`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
|
+
`${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
|
+
`Nothing moves until the owner deposits, signed in to Go mode, where the vault's own quote is shown first: ${approvalUrl}`,
|
|
158
|
+
].join("\n");
|
|
159
|
+
return { data, text };
|
|
160
|
+
}
|