@priors/mcp 0.8.4 → 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 +26 -0
- package/README.md +10 -7
- package/package.json +2 -2
- package/src/daily.mjs +88 -26
- package/src/server.mjs +53 -2
- package/src/stock-line.mjs +160 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
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
|
+
|
|
15
|
+
## 0.8.5 (2026-10-12)
|
|
16
|
+
|
|
17
|
+
- **Money counts in the UTC day it lands** (GHSA-266h-jfr9-42cx). A call reserved its room in the day it started and
|
|
18
|
+
kept what it did there, so a borrow sent before 00:00 UTC that landed after was invisible to the new day's
|
|
19
|
+
`PRIORS_MAX_BORROW_DAY_USD` (and to `credit_status`'s "Today"), and a day could carry twice its limit; the same for
|
|
20
|
+
`PRIORS_MAX_SPEND_DAY_USD`. A call's money is now filed in the day it ends, and while a call is in flight every
|
|
21
|
+
process counts it in the days after the one it started, however long its transaction takes; one cut short by a
|
|
22
|
+
crash stays counted for the day it started and the two after.
|
|
23
|
+
- **`fund_base` counts against the session caps from its check** (GHSA-24qq-9p83-8798). It checked
|
|
24
|
+
`PRIORS_MAX_BORROW_TOTAL_USD` and `PRIORS_MAX_BRIDGE_TOTAL_USD`, then read the transfer record and the Base float,
|
|
25
|
+
and only then counted, so a second call made while the first waited on a late Base read could pass both caps
|
|
26
|
+
beside it. It now counts right after the check, as `borrow` and `pay_url` do (GHSA-cq9v), and gives it back when it
|
|
27
|
+
is refused.
|
|
28
|
+
|
|
3
29
|
## 0.8.4 (2026-10-11)
|
|
4
30
|
|
|
5
31
|
- **SeatVaultV5 lines work out of the box.** The bundled `deployments/4663.v2.json` names SeatVaultV5
|
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
|
|
@@ -243,7 +243,10 @@ they require: without it the server does not start) and for the wallet whose key
|
|
|
243
243
|
every process that shares `PRIORS_STATE_DIR`, kept as one file per money call under `<state dir>/daily-agent-<id>/` and
|
|
244
244
|
`<state dir>/daily-wallet-<address>/`. Every key and every client acting for the agent shares one count, and a key run
|
|
245
245
|
under another agent id still shares its wallet's. A call counts at the most it may sign or borrow (`max_price_usd`,
|
|
246
|
-
`max_borrow_usd`) while it runs, then at what it did
|
|
246
|
+
`max_borrow_usd`) while it runs, then at what it did, in the UTC day it ended (a borrow sent just before 00:00 UTC that
|
|
247
|
+
lands after counts in the new day). A call still in flight at 00:00 UTC counts in the new day too, however long its
|
|
248
|
+
transaction takes, so a call another process makes after midnight already sees it; one cut short by a crash stays
|
|
249
|
+
counted at its most for the day it started and the two days after.
|
|
247
250
|
Two processes racing for the last dollar never both get it. Only a server that sets a daily limit counts toward it, so
|
|
248
251
|
give every client that uses the agent's key the same limits. `PRIORS_MAX_BORROW_DAY_USD=0` turns borrowing off;
|
|
249
252
|
`credit_status` shows what is used today.
|
|
@@ -259,7 +262,7 @@ to approve a borrow; this package, with the key, pays for APIs. With borrowing o
|
|
|
259
262
|
approves each loan in Priors' Go mode. ElizaOS (`@elizaos/plugin-mcp`):
|
|
260
263
|
|
|
261
264
|
```ts
|
|
262
|
-
"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"],
|
|
263
266
|
env: { PRIORS_KEY_FILE: "/home/agent/.config/priors/agent-7311.key", PRIORS_AGENT_ID: "7311",
|
|
264
267
|
PRIORS_MAX_BORROW_USD: "0", PRIORS_MAX_BORROW_DAY_USD: "0", PRIORS_MAX_SPEND_DAY_USD: "1", PRIORS_MAX_PRICE_USD: "0.10",
|
|
265
268
|
PRIORS_PAY_HOSTS: "api.example.com" } }
|
|
@@ -271,7 +274,7 @@ OpenClaw (`mcp.servers`, JSON5) takes the same `command`, `args` and `env`; Herm
|
|
|
271
274
|
mcp_servers:
|
|
272
275
|
priors-wallet:
|
|
273
276
|
command: npx
|
|
274
|
-
args: ["-y", "@priors/mcp@0.
|
|
277
|
+
args: ["-y", "@priors/mcp@0.9.0"]
|
|
275
278
|
env:
|
|
276
279
|
PRIORS_KEY_FILE: /home/agent/.config/priors/agent-7311.key
|
|
277
280
|
PRIORS_AGENT_ID: "7311"
|
|
@@ -298,7 +301,7 @@ key proves it is there: it signs the ERC-8004 identity registry's `AgentWalletSe
|
|
|
298
301
|
agent's).
|
|
299
302
|
|
|
300
303
|
```sh
|
|
301
|
-
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
|
|
302
305
|
```
|
|
303
306
|
|
|
304
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/daily.mjs
CHANGED
|
@@ -19,8 +19,18 @@
|
|
|
19
19
|
// in (a count named after the wallet when the id was left out split one agent's day in two). And the wallet's,
|
|
20
20
|
// "wallet-<address>": a key run under another agent id, by mistake or for a second agent it controls, still shares
|
|
21
21
|
// one count of the money it holds. All of a call's files are created before any ledger is listed, so the argument
|
|
22
|
-
// above holds in each.
|
|
23
|
-
//
|
|
22
|
+
// above holds in each. Money counts in the UTC day it lands (GHSA-266h). A call reserves in the day it starts, and also
|
|
23
|
+
// leaves a marker in <owner>/pending/, named after that day and its amounts, which every process counts in each day
|
|
24
|
+
// after it (up to PENDING_DAYS) for as long as the call is in flight, however long its transaction takes to mine. Once
|
|
25
|
+
// it ends, its entry becomes what it did, filed in the day it ended (never in a day before the one it started: a
|
|
26
|
+
// clock set back moves nothing back), and only then does its marker go. So a borrow sent before 00:00 UTC that lands
|
|
27
|
+
// after counts in the new day, and while it is still in flight a call another process makes after midnight already
|
|
28
|
+
// sees it. A process that dies mid-call leaves its entry at its most in the day it started and its marker counted
|
|
29
|
+
// PENDING_DAYS days more, the safe direction. Days before yesterday, and markers older than that count, are deleted as
|
|
30
|
+
// new days begin. A file whose name is not a ledger entry is left alone and not counted.
|
|
31
|
+
// SHORTCUT: a call still in flight more than PENDING_DAYS days after the day it started stops counting in later days.
|
|
32
|
+
// Ceiling: none on this chain, whose sequencer includes or refuses a transaction within seconds and whose forced
|
|
33
|
+
// inclusion is bounded to 24 h. Upgrade trigger: a money call that can stay in flight longer.
|
|
24
34
|
import { closeSync, mkdirSync, openSync, readdirSync, renameSync, rmSync, unlinkSync } from "node:fs";
|
|
25
35
|
import { join } from "node:path";
|
|
26
36
|
import { randomBytes } from "node:crypto";
|
|
@@ -28,9 +38,14 @@ import { randomBytes } from "node:crypto";
|
|
|
28
38
|
const ENTRY = /^(\d{1,30})-(\d{1,30})-\d{1,10}-[0-9a-f]{16}\.r$/;
|
|
29
39
|
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
30
40
|
const OWNER = /^(agent-\d{1,78}|wallet-0x[0-9a-f]{40})$/;
|
|
41
|
+
const PENDING = "pending";
|
|
42
|
+
const MARKER = /^(\d{4}-\d{2}-\d{2})_(\d{1,30})-(\d{1,30})-\d{1,10}-[0-9a-f]{16}\.r$/;
|
|
43
|
+
/** The days after the one it started in which a call still in flight is counted. */
|
|
44
|
+
export const PENDING_DAYS = 2;
|
|
31
45
|
|
|
32
46
|
/** The UTC date of `ms` (YYYY-MM-DD). */
|
|
33
47
|
export const utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
48
|
+
const dayPlus = (day, n) => utcDay(Date.parse(`${day}T00:00:00Z`) + n * 86_400_000);
|
|
34
49
|
|
|
35
50
|
/** The agent PRIORS_AGENT_ID names, as a BigInt (leading zeros dropped: 007 and 7 are one agent), or null when it is
|
|
36
51
|
* not a decimal id. */
|
|
@@ -56,6 +71,19 @@ function sum(dir, fs) {
|
|
|
56
71
|
return { signed, borrowed };
|
|
57
72
|
}
|
|
58
73
|
|
|
74
|
+
/** What calls started in the PENDING_DAYS days before `day` and still in flight hold: their markers in `pdir`. */
|
|
75
|
+
function inFlight(pdir, day, fs) {
|
|
76
|
+
let signed = 0n, borrowed = 0n;
|
|
77
|
+
let names;
|
|
78
|
+
try { names = fs.readdirSync(pdir); } catch (e) { if (e?.code === "ENOENT") return { signed, borrowed }; throw e; }
|
|
79
|
+
const oldest = dayPlus(day, -PENDING_DAYS);
|
|
80
|
+
for (const n of names) {
|
|
81
|
+
const m = MARKER.exec(n);
|
|
82
|
+
if (m && m[1] < day && m[1] >= oldest) { signed += BigInt(m[2]); borrowed += BigInt(m[3]); }
|
|
83
|
+
}
|
|
84
|
+
return { signed, borrowed };
|
|
85
|
+
}
|
|
86
|
+
|
|
59
87
|
/**
|
|
60
88
|
* A daily ledger under `stateDir` that counts in every one of `owners` (ledgerOwners; or `owner`, one name).
|
|
61
89
|
* `caps.signed` / `caps.borrowed` are base units, or null for no limit of that kind; each holds in every owner's
|
|
@@ -66,17 +94,29 @@ export function dailyLedger({ stateDir, owners, owner, caps, now = () => Date.no
|
|
|
66
94
|
if (!list.length || !list.every((o) => OWNER.test(String(o)))) throw new Error(`not a daily ledger owner: ${list.join(", ")}`);
|
|
67
95
|
const rootOf = (o) => join(stateDir, `daily-${o}`);
|
|
68
96
|
const swept = new Map();
|
|
69
|
-
/** Days before yesterday go, once per owner and new day (best effort: a leftover
|
|
97
|
+
/** Days before yesterday, and markers no day counts any more, go, once per owner and new day (best effort: a leftover
|
|
98
|
+
* is never read again). */
|
|
70
99
|
function sweep(o, today) {
|
|
71
100
|
if (swept.get(o) === today) return;
|
|
72
101
|
swept.set(o, today);
|
|
73
|
-
const yesterday =
|
|
102
|
+
const yesterday = dayPlus(today, -1), oldest = dayPlus(today, -PENDING_DAYS);
|
|
74
103
|
try { for (const d of fs.readdirSync(rootOf(o))) if (DAY.test(d) && d < yesterday) fs.rmSync(join(rootOf(o), d), { recursive: true, force: true }); } catch (_) { /* best effort */ }
|
|
104
|
+
try {
|
|
105
|
+
for (const n of fs.readdirSync(join(rootOf(o), PENDING))) {
|
|
106
|
+
const m = MARKER.exec(n);
|
|
107
|
+
if (m && m[1] < oldest) fs.unlinkSync(join(rootOf(o), PENDING, n));
|
|
108
|
+
}
|
|
109
|
+
} catch (_) { /* best effort */ }
|
|
75
110
|
}
|
|
76
111
|
const entryName = (s, b) => `${s}-${b}-${process.pid}-${randomBytes(8).toString("hex")}.r`;
|
|
77
112
|
/** Takes a call's files back (a refusal, or a ledger that could not be written): best effort, since one left behind
|
|
78
|
-
* only counts
|
|
113
|
+
* only counts too much, the safe direction. */
|
|
79
114
|
const drop = (files) => { for (const f of files) { try { fs.unlinkSync(join(f.dir, f.name)); } catch (_) { /* counted */ } } };
|
|
115
|
+
/** What an owner's ledger holds on `day`: that day's entries, and the calls started before it still in flight. */
|
|
116
|
+
const totalOn = (o, day) => {
|
|
117
|
+
const a = sum(join(rootOf(o), day), fs), p = inFlight(join(rootOf(o), PENDING), day, fs);
|
|
118
|
+
return { signed: a.signed + p.signed, borrowed: a.borrowed + p.borrowed };
|
|
119
|
+
};
|
|
80
120
|
return {
|
|
81
121
|
caps,
|
|
82
122
|
owners: list,
|
|
@@ -85,7 +125,7 @@ export function dailyLedger({ stateDir, owners, owner, caps, now = () => Date.no
|
|
|
85
125
|
const day = utcDay(now());
|
|
86
126
|
const out = { signed: 0n, borrowed: 0n };
|
|
87
127
|
for (const o of list) {
|
|
88
|
-
const t =
|
|
128
|
+
const t = totalOn(o, day);
|
|
89
129
|
if (t.signed > out.signed) out.signed = t.signed;
|
|
90
130
|
if (t.borrowed > out.borrowed) out.borrowed = t.borrowed;
|
|
91
131
|
}
|
|
@@ -102,39 +142,61 @@ export function dailyLedger({ stateDir, owners, owner, caps, now = () => Date.no
|
|
|
102
142
|
const files = [];
|
|
103
143
|
try {
|
|
104
144
|
for (const o of list) {
|
|
105
|
-
const dir = join(rootOf(o), day);
|
|
106
|
-
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
107
145
|
sweep(o, day);
|
|
146
|
+
const dir = join(rootOf(o), day), pdir = join(rootOf(o), PENDING);
|
|
147
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
148
|
+
fs.mkdirSync(pdir, { recursive: true, mode: 0o700 });
|
|
108
149
|
const name = entryName(signed, borrowed);
|
|
109
150
|
fs.closeSync(fs.openSync(join(dir, name), "wx", 0o600));
|
|
110
|
-
files.push({ owner: o, dir, name });
|
|
151
|
+
files.push({ owner: o, day, dir, name });
|
|
152
|
+
// in flight: counted in the days after this one until it ends (GHSA-266h)
|
|
153
|
+
fs.closeSync(fs.openSync(join(pdir, `${day}_${name}`), "wx", 0o600));
|
|
154
|
+
files.push({ owner: o, day, dir: pdir, name: `${day}_${name}`, marker: true });
|
|
111
155
|
}
|
|
112
156
|
} catch (e) { drop(files); throw e; }
|
|
113
|
-
// each ledger is listed only once all of this call's files exist: a racing process sees them, or this one sees its
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
drop(files);
|
|
121
|
-
|
|
157
|
+
// each ledger is listed only once all of this call's files exist: a racing process sees them, or this one sees its.
|
|
158
|
+
// A reservation that straddled 00:00 UTC is held against the new day too (its marker counts there).
|
|
159
|
+
const after = utcDay(now());
|
|
160
|
+
const days = after > day ? [day, after] : [day];
|
|
161
|
+
for (const o of list) {
|
|
162
|
+
for (const d of days) {
|
|
163
|
+
let total;
|
|
164
|
+
try { total = totalOn(o, d); } catch (e) { drop(files); throw e; }
|
|
165
|
+
for (const [kind, want] of [["signed", signed], ["borrowed", borrowed]]) {
|
|
166
|
+
const cap = caps[kind];
|
|
167
|
+
if (cap === null || cap === undefined || want === 0n || total[kind] <= cap) continue;
|
|
168
|
+
drop(files);
|
|
169
|
+
throw Object.assign(new Error(`daily ${kind} limit`), { code: "DAY_LIMIT", kind, owner: o, used: total[kind] - want, cap, want });
|
|
170
|
+
}
|
|
122
171
|
}
|
|
123
172
|
}
|
|
124
173
|
return { files, signed, borrowed };
|
|
125
174
|
},
|
|
126
|
-
/** Once the call has ended: its
|
|
127
|
-
* includes anything that may have happened, like a payment signed before the request failed),
|
|
128
|
-
*
|
|
175
|
+
/** Once the call has ended: in each owner's ledger its entry becomes what it really did (signed, borrowed: what the
|
|
176
|
+
* server counted, which includes anything that may have happened, like a payment signed before the request failed),
|
|
177
|
+
* filed in the UTC day it ends but never in a day before the one it started (GHSA-266h), or goes when that is
|
|
178
|
+
* nothing; then its in-flight marker goes. Best effort: an entry that cannot be moved stays at its most, and its
|
|
179
|
+
* marker stays too, so the days after still count it. */
|
|
129
180
|
settle(r, signed, borrowed) {
|
|
130
181
|
if (!r) return;
|
|
131
182
|
const s = signed < 0n ? 0n : signed, b = borrowed < 0n ? 0n : borrowed;
|
|
132
|
-
|
|
133
|
-
for (const
|
|
183
|
+
const today = utcDay(now());
|
|
184
|
+
for (const o of list) {
|
|
185
|
+
const entry = r.files.find((f) => f.owner === o && !f.marker), marker = r.files.find((f) => f.owner === o && f.marker);
|
|
186
|
+
if (!entry) continue;
|
|
187
|
+
const start = entry.day ?? entry.dir.slice(-10);
|
|
188
|
+
const day = today > start ? today : start;
|
|
189
|
+
const dir = join(rootOf(o), day);
|
|
190
|
+
let done = true;
|
|
134
191
|
try {
|
|
135
|
-
if (s === 0n && b === 0n) fs.unlinkSync(join(
|
|
136
|
-
else
|
|
137
|
-
|
|
192
|
+
if (s === 0n && b === 0n) fs.unlinkSync(join(entry.dir, entry.name));
|
|
193
|
+
else if (entry.dir !== dir || s !== r.signed || b !== r.borrowed) {
|
|
194
|
+
if (entry.dir !== dir) fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
195
|
+
fs.renameSync(join(entry.dir, entry.name), join(dir, entryName(s, b)));
|
|
196
|
+
}
|
|
197
|
+
} catch (_) { done = false; /* stays counted at its most */ }
|
|
198
|
+
// the entry is final first: a crash between the two leaves the marker counted, never nothing
|
|
199
|
+
if (done && marker) drop([marker]);
|
|
138
200
|
}
|
|
139
201
|
},
|
|
140
202
|
};
|
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.
|
|
@@ -1309,12 +1358,14 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
1309
1358
|
const maxBorrow = dollars(max_borrow_usd ?? 0, "max_borrow_usd");
|
|
1310
1359
|
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).`);
|
|
1311
1360
|
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).`);
|
|
1361
|
+
reserveDay(0n, maxBorrow); // the day's borrowing limit (PRIORS_MAX_BORROW_DAY_USD), before anything is moved
|
|
1362
|
+
// the most it may move and borrow, from its check with no await between (GHSA-cq9v) until it ends: counted after
|
|
1363
|
+
// the reads below, a call made once the hold of one stalled in them had ended passed both caps beside it (GHSA-24qq)
|
|
1364
|
+
count("bridged", amount); count("borrowed", maxBorrow);
|
|
1312
1365
|
const f = await settleFlight();
|
|
1313
1366
|
if (f) throw new ToolError(blocked(f));
|
|
1314
1367
|
const float = await bridge.floatOf(wallet.address);
|
|
1315
1368
|
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.`);
|
|
1316
|
-
reserveDay(0n, maxBorrow); // the day's borrowing limit (PRIORS_MAX_BORROW_DAY_USD), before anything is moved
|
|
1317
|
-
count("bridged", amount); count("borrowed", maxBorrow); // the most it may move and borrow, until it ends (GHSA-cq9v)
|
|
1318
1369
|
// What stays on Robinhood Chain: what Autopay pulls in the next 24 h, and the USDG of payments signed there and not
|
|
1319
1370
|
// settled (the borrow-the-gap rule alone does not know either).
|
|
1320
1371
|
const nowS = Math.floor(Date.now() / 1000);
|
|
@@ -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
|
+
}
|