@priors/mcp 0.2.11 → 0.6.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.
@@ -0,0 +1,289 @@
1
+ // PT-USDG for agents and builders: quote, buy, sell and redeem Pendle's principal token for USDG on Robinhood Chain
2
+ // (chain 4663; the markets of deployments/pendle.4663.json: the active one, maturing 2027-03-25 today, and any earlier
3
+ // one kept for redemption), and read a wallet's position, through the same router calls the gas gate checks
4
+ // (sdk/pendle-pt.mjs builds them; this module only adds the reads, the approvals and the sending).
5
+ //
6
+ // import { ptQuote, ptBuy, ptSell, ptRedeem, ptPosition } from "./sdk/pt-usdg.mjs";
7
+ // const rpc = "https://rpc.mainnet.chain.robinhood.com"; // or a viem PublicClient, an ethers provider
8
+ // await ptQuote(rpc, { side: "buy", amount: 100 }); // 100 USDG -> PT, at the oracle's spot price
9
+ // const { calls } = await ptBuy(rpc, { account, amount: 100 }); // [approve USDG, router call]: { to, data, value }
10
+ // await ptBuy(rpc, { amount: 100, wallet }); // or send them (a viem WalletClient or an ethers Signer)
11
+ // await ptSell(rpc, { account, amount: "50.5" }); // PT -> USDG at the market, before maturity
12
+ // await ptRedeem(rpc, { account, amount: "all" }); // PT -> USDG 1:1, from its maturity (any listed market)
13
+ // await ptPosition(rpc, account); // balance, value now, days left, implied fixed APY
14
+ //
15
+ // Markets: buys, sales and quotes are on the active market (PT_USDG); a redemption takes `market` (a market, PT or YT
16
+ // address from PT_MARKETS), or by default the oldest matured market the account holds PT of. ptPosition lists the
17
+ // account's PT of every listed market (`markets`), so PT of a matured, redeem-only market shows with its Redeem.
18
+ //
19
+ // PriorsV2 (sdk/priors-v2.mjs) carries the same as methods: p.ptQuote, p.ptBuy, p.ptSell, p.ptRedeem, p.ptPosition, and
20
+ // p.openPtLine(agentId, amount) to post PT-USDG behind an agent's line once the stock vault lists it.
21
+ //
22
+ // Amounts: a number or a decimal string is whole USDG or PT ("12.5"); a bigint is raw 6-decimal units; "all" (sell,
23
+ // redeem) is the account's whole PT balance. Each trade names a minimum out (the quote less `slippageBps`, 1% by
24
+ // default): the router reverts rather than fill worse. The quote is the oracle's spot price, before the trade's own
25
+ // price impact (about 0.1% per 1,000 USDG on 2026-10-01): a large trade may need a wider slippage or several trades.
26
+ // Every approval is for exactly the amount of the trade after it, the shape the gas gate sponsors; a call bundle is
27
+ // sponsorable when its amount is within PT_USDG.maxUsdgPerOp (2,000).
28
+ import { formatUnits, getAddress, parseUnits, encodeFunctionData, decodeFunctionResult } from "viem";
29
+ import { PENDLE, PENDLE_ADDR, ORACLE_ABI, PT_ABI, buildBuy, buildSell, buildRedeem, quoteBuy, quoteSell, marketOf, maturedMarkets } from "./pendle-pt.mjs";
30
+ import PT from "../deployments/pt-usdg.4663.json" with { type: "json" };
31
+
32
+ const YEAR = 365 * 86400;
33
+ const ZERO = "0x0000000000000000000000000000000000000000";
34
+ const VAULT_ASSET_ABI = [{ type: "function", name: "assets", stateMutability: "view", inputs: [{ name: "token", type: "address" }],
35
+ outputs: [{ name: "feed", type: "address" }, { name: "maxAge", type: "uint64" }, { name: "tokenDecimals", type: "uint8" }, { name: "feedDecimals", type: "uint8" },
36
+ { name: "enabled", type: "bool" }, { name: "ltvBps", type: "uint16" }, { name: "lineCap", type: "uint128" }] },
37
+ { type: "function", name: "openLinesOf", stateMutability: "view", inputs: [{ name: "token", type: "address" }], outputs: [{ name: "", type: "uint256" }] }];
38
+
39
+ const iso = (expiry) => new Date(expiry * 1000).toISOString().replace(".000Z", "Z");
40
+ const VIEW = marketOf(PENDLE_ADDR.market);
41
+ /** Every listed market, oldest first (deployments/pendle.4663.json): its token, addresses, maturity and status. */
42
+ export const PT_MARKETS = Object.freeze(PENDLE.markets.map((m) => Object.freeze({
43
+ token: m.pt, market: m.market, yt: m.yt, sy: m.sy, oracle: m.pyLpOracle, expiry: m.expiry, maturity: iso(m.expiry), status: m.status,
44
+ })));
45
+ /** The token of the active market, its market and where Priors posts it (deployments/pendle.4663.json, deployments/pt-usdg.4663.json). */
46
+ export const PT_USDG = Object.freeze({
47
+ chainId: 4663, symbol: "PT-USDG", decimals: 6,
48
+ token: PENDLE_ADDR.pt, market: PENDLE_ADDR.market, router: PENDLE_ADDR.router, usdg: PENDLE_ADDR.usdg, yt: PENDLE_ADDR.yt, sy: PENDLE_ADDR.sy,
49
+ oracle: VIEW.pyLpOracle, stockVault: getAddress(PT.stockVault), status: VIEW.status,
50
+ expiry: PENDLE_ADDR.expiry, maturity: iso(PENDLE_ADDR.expiry),
51
+ maxUsdgPerOp: PENDLE_ADDR.maxUsdgPerOp,
52
+ // the owner's launch settings for the stock vault (docs/PT-USDG.md): planned until the Safe's setAsset, then read from the vault
53
+ planned: Object.freeze({ ltvBps: Number(PT.setAsset.ltvBps), lineCap: BigInt(PT.setAsset.lineCap) }),
54
+ });
55
+
56
+ // ---- the chain: a URL, a viem client, an EIP-1193 provider or an ethers provider/signer ----
57
+
58
+ let rpcId = 0;
59
+ /** One JSON-RPC request through whatever `client` is. */
60
+ export async function rpc(client, method, params = []) {
61
+ if (typeof client === "string") {
62
+ const res = await fetch(client, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: ++rpcId, method, params }) });
63
+ if (!res.ok) throw new Error(`${method}: the RPC answered HTTP ${res.status}`);
64
+ const j = await res.json();
65
+ if (j.error) { const e = new Error(`${method}: ${j.error.message || "RPC error"}`); e.data = j.error.data; throw e; }
66
+ return j.result;
67
+ }
68
+ if (client && typeof client.request === "function") return client.request({ method, params }); // viem, EIP-1193
69
+ if (client && typeof client.send === "function" && typeof client.getNetwork === "function") return client.send(method, params); // ethers JsonRpcProvider
70
+ if (client && client.provider && client.provider !== client) return rpc(client.provider, method, params); // an ethers signer
71
+ if (client && typeof client.call === "function" && method === "eth_call") return client.call(params[0]); // any ethers provider
72
+ throw new Error("give an RPC URL, a viem client, an EIP-1193 provider or an ethers provider");
73
+ }
74
+ async function read(client, address, abi, functionName, args = [], from) {
75
+ const data = encodeFunctionData({ abi, functionName, args });
76
+ const out = await rpc(client, "eth_call", [{ to: address, data, ...(from ? { from } : {}) }, "latest"]);
77
+ return decodeFunctionResult({ abi, functionName, data: typeof out === "string" ? out : out.data });
78
+ }
79
+ async function chainNow(client) {
80
+ try { const b = await rpc(client, "eth_getBlockByNumber", ["latest", false]); if (b && b.timestamp != null) return Number(BigInt(b.timestamp)); } catch (_) { /* the clock below */ }
81
+ return Math.floor(Date.now() / 1000);
82
+ }
83
+
84
+ // ---- figures ----
85
+
86
+ /** `amount` in 6-decimal units: a bigint is raw, a number or a decimal string is whole tokens. */
87
+ export function ptUnits(amount) {
88
+ if (typeof amount === "bigint") { if (amount <= 0n) throw new Error("the amount must be above zero"); return amount; }
89
+ const s = typeof amount === "number" ? amount.toFixed(6).replace(/\.?0+$/, "") : String(amount ?? "").trim();
90
+ if (!/^\d+(\.\d{1,6})?$/.test(s)) throw new Error(`not an amount of USDG or PT (6 decimals at most): ${String(amount).slice(0, 40)}`);
91
+ const u = parseUnits(s, 6);
92
+ if (u <= 0n) throw new Error("the amount must be above zero");
93
+ return u;
94
+ }
95
+ const fmt6 = (u) => formatUnits(u, 6);
96
+ const bps = (n) => { const b = BigInt(n); if (b < 0n || b >= 10_000n) throw new Error("slippageBps is between 0 and 9999"); return b; };
97
+
98
+ /**
99
+ * The fixed yield a buyer at `rate` (USDG per PT, 1e18 = par) locks in to maturity, `secondsLeft` away: an annual
100
+ * rate, compounded, as Pendle states its implied APY ((1 / price) ^ (1 year / time left) - 1). 0 at or after maturity.
101
+ */
102
+ export function impliedApy(rate, secondsLeft) {
103
+ const r = Number(rate) / 1e18;
104
+ if (!(secondsLeft > 0) || !(r > 0)) return 0;
105
+ return Math.pow(1 / r, YEAR / secondsLeft) - 1;
106
+ }
107
+ const pct = (x) => `${(x * 100).toFixed(2)}%`;
108
+
109
+ /** A listed market's spot price of PT in USDG (1e18 = par) from Pendle's PY/LP oracle (`market` default: the active
110
+ * one); par from its maturity on. */
111
+ export async function ptRateOf(client, { now, market } = {}) {
112
+ const m = marketOf(market ?? PT_USDG.market);
113
+ const t = now ?? (await chainNow(client));
114
+ if (t >= m.expiry) return { rate: 10n ** 18n, now: t };
115
+ return { rate: await read(client, m.pyLpOracle, ORACLE_ABI, "getPtToAssetRate", [m.market, 0]), now: t };
116
+ }
117
+ function terms(rate, now, m = VIEW) {
118
+ const left = Math.max(0, m.expiry - now);
119
+ const apy = impliedApy(rate, left);
120
+ return { rate, price: Number(rate) / 1e18, matured: left === 0, maturity: iso(m.expiry), daysToMaturity: Math.ceil(left / 86400), impliedApy: apy, impliedApyText: pct(apy),
121
+ market: m.market, token: m.pt, status: m.status };
122
+ }
123
+ /** The market a redemption takes when none is named: the oldest matured market `holds` (address -> PT) has any of,
124
+ * else the latest matured one, else the active one (whose quote then says to sell before maturity). */
125
+ function redeemMarket(now, holds) {
126
+ const due = maturedMarkets(now);
127
+ return due.find((m) => holds && holds(m.pt) > 0n) || due[due.length - 1] || VIEW;
128
+ }
129
+
130
+ /**
131
+ * What a trade gives now, from the oracle's spot price: `side` "buy" (USDG in, PT out), "sell" (PT in, USDG out, before
132
+ * maturity) or "redeem" (PT in, USDG out 1:1, from maturity). Amounts are 6-decimal bigints, with their text alongside.
133
+ */
134
+ export async function ptQuote(client, { side = "buy", amount, slippageBps, now, market } = {}) {
135
+ if (!["buy", "sell", "redeem"].includes(side)) throw new Error('side is "buy", "sell" or "redeem"');
136
+ const units = ptUnits(amount);
137
+ const t0 = now ?? (await chainNow(client));
138
+ const m = market != null ? marketOf(market) : side === "redeem" ? redeemMarket(t0) : VIEW;
139
+ if (side !== "redeem" && !m.active) throw new Error(`the PT-USDG market maturing ${iso(m.expiry)} is redeem-only: redeem its PT from then on${PENDLE.active ? `, or buy and sell on the market maturing ${iso(PENDLE.active.expiry)}` : ""}`);
140
+ const { rate, now: t } = await ptRateOf(client, { now: t0, market: m.market });
141
+ const info = terms(rate, t, m);
142
+ if (side !== "redeem" && info.matured) throw new Error(`PT-USDG matured on ${info.maturity}: redeem it 1:1 for USDG instead`);
143
+ if (side === "redeem" && !info.matured) throw new Error(`PT-USDG redeems 1:1 from ${info.maturity}; before that, sell it`);
144
+ const slip = bps(slippageBps ?? (side === "redeem" ? 10 : 100));
145
+ let out, min;
146
+ if (side === "buy") ({ ptOut: out, minPtOut: min } = quoteBuy(units, rate, slip));
147
+ else if (side === "sell") ({ usdgOut: out, minUsdgOut: min } = quoteSell(units, rate, slip));
148
+ else { out = units; min = (units * (10_000n - slip)) / 10_000n; }
149
+ if (min <= 0n) throw new Error("the amount is too small to name a minimum out");
150
+ const tokenIn = side === "buy" ? "USDG" : "PT-USDG", tokenOut = side === "buy" ? "PT-USDG" : "USDG";
151
+ return {
152
+ side, tokenIn, tokenOut, amountIn: units, expectedOut: out, minOut: min, slippageBps: Number(slip),
153
+ amountInText: fmt6(units), expectedOutText: fmt6(out), minOutText: fmt6(min), ...info,
154
+ // a buy held to maturity: what it pays then (1 PT = 1 USDG), and the gain over what it cost
155
+ ...(side === "buy" ? { atMaturity: out, atMaturityText: fmt6(out), fixedGainText: fmt6(out - units) } : {}),
156
+ sponsorable: units <= PT_USDG.maxUsdgPerOp,
157
+ };
158
+ }
159
+
160
+ // ---- the calls ----
161
+
162
+ const approveData = (spender, amount) => encodeFunctionData({ abi: PT_ABI, functionName: "approve", args: [spender, amount] });
163
+ const call = (to, data, what) => ({ to: getAddress(to), data, value: 0n, what });
164
+
165
+ async function accountOf(account, wallet) {
166
+ if (account) return getAddress(account);
167
+ if (wallet && wallet.account && wallet.account.address) return getAddress(wallet.account.address); // viem WalletClient
168
+ if (wallet && typeof wallet.getAddress === "function") return getAddress(await wallet.getAddress()); // ethers Signer
169
+ throw new Error("give the account that signs (account) or a wallet to send with");
170
+ }
171
+
172
+ /** Wait for `hash` and check it succeeded. */
173
+ async function receipt(client, hash, { timeoutMs = 180_000 } = {}) {
174
+ const end = Date.now() + timeoutMs;
175
+ for (;;) {
176
+ const rc = await rpc(client, "eth_getTransactionReceipt", [hash]);
177
+ if (rc) { if (rc.status !== "0x1" && rc.status !== 1 && rc.status !== "success") throw new Error(`transaction ${hash} reverted`); return rc; }
178
+ if (Date.now() > end) throw new Error(`transaction ${hash} not mined after ${timeoutMs / 1000} s`);
179
+ await new Promise((r) => setTimeout(r, 1500));
180
+ }
181
+ }
182
+
183
+ /** Send `calls` in order from `wallet`, each simulated first, each waited for: the hashes. */
184
+ export async function sendCalls(client, wallet, calls, from) {
185
+ const hashes = [];
186
+ for (const c of calls) {
187
+ try { await rpc(client, "eth_call", [{ from, to: c.to, data: c.data }, "latest"]); } catch (e) { throw new Error(`${c.what || "the call"} would revert: ${e.shortMessage || e.message}`); }
188
+ let hash;
189
+ if (wallet.account && typeof wallet.sendTransaction === "function" && !wallet.getAddress) {
190
+ hash = await wallet.sendTransaction({ account: wallet.account, chain: wallet.chain ?? null, to: c.to, data: c.data, value: c.value });
191
+ } else {
192
+ const tx = await wallet.sendTransaction({ to: c.to, data: c.data, value: c.value });
193
+ hash = tx.hash;
194
+ }
195
+ await receipt(client, hash);
196
+ hashes.push(hash);
197
+ }
198
+ return hashes;
199
+ }
200
+
201
+ async function bundle(client, { kind, account, wallet, amount, slippageBps, minOut, approve = "auto", now, market }) {
202
+ const from = await accountOf(account, wallet);
203
+ const t = now ?? (await chainNow(client));
204
+ let m = market != null ? marketOf(market) : VIEW;
205
+ if (kind === "redeem" && market == null) {
206
+ // the oldest matured market the account holds PT of (each matured market's balance read once)
207
+ const due = maturedMarkets(t), held = new Map();
208
+ for (const d of due) held.set(d.pt, await read(client, d.pt, PT_ABI, "balanceOf", [from]));
209
+ m = redeemMarket(t, (pt) => held.get(pt) ?? 0n);
210
+ }
211
+ let units;
212
+ if (amount === "all") {
213
+ if (kind === "buy") throw new Error('"all" is for selling or redeeming PT');
214
+ units = await read(client, m.pt, PT_ABI, "balanceOf", [from]);
215
+ if (units === 0n) throw new Error(`${from} holds no PT-USDG${m.market === VIEW.market ? "" : ` of the market maturing ${iso(m.expiry)}`}`);
216
+ } else units = ptUnits(amount);
217
+ const q = await ptQuote(client, { side: kind, amount: units, slippageBps, now: t, market: m.market });
218
+ const min = minOut != null ? ptUnits(minOut) : q.minOut;
219
+ const payToken = kind === "buy" ? PT_USDG.usdg : m.pt;
220
+ const [have, allowed] = await Promise.all([
221
+ read(client, payToken, PT_ABI, "balanceOf", [from]),
222
+ approve === "auto" ? read(client, payToken, PT_ABI, "allowance", [from, PT_USDG.router]) : Promise.resolve(approve === "always" ? 0n : units),
223
+ ]);
224
+ const warnings = [];
225
+ if (have < units) warnings.push(`${from} holds ${fmt6(have)} ${kind === "buy" ? "USDG" : "PT-USDG"}, less than the ${fmt6(units)} this trade takes`);
226
+ if (!q.sponsorable) warnings.push(`above ${fmt6(PT_USDG.maxUsdgPerOp)}: Priors' gas sponsorship takes at most that much a trade (your own gas is fine)`);
227
+ const data = kind === "buy" ? buildBuy({ receiver: from, usdgIn: units, minPtOut: min, market: m.market })
228
+ : kind === "sell" ? buildSell({ receiver: from, ptIn: units, minUsdgOut: min, market: m.market })
229
+ : buildRedeem({ receiver: from, ptIn: units, minUsdgOut: min, market: m.market });
230
+ const calls = [
231
+ ...(allowed < units ? [call(payToken, approveData(PT_USDG.router, units), `approve ${fmt6(units)} ${kind === "buy" ? "USDG" : "PT-USDG"} to Pendle's router`)] : []),
232
+ call(PT_USDG.router, data, kind === "buy" ? `buy at least ${fmt6(min)} PT-USDG with ${fmt6(units)} USDG` : kind === "sell" ? `sell ${fmt6(units)} PT-USDG for at least ${fmt6(min)} USDG` : `redeem ${fmt6(units)} PT-USDG for at least ${fmt6(min)} USDG`),
233
+ ];
234
+ const out = { kind, account: from, chainId: PT_USDG.chainId, quote: { ...q, minOut: min, minOutText: fmt6(min) }, calls, warnings };
235
+ if (!wallet) return out;
236
+ if (have < units) throw new Error(warnings[0]);
237
+ return { ...out, hashes: await sendCalls(client, wallet, calls, from) };
238
+ }
239
+
240
+ /** Buy PT-USDG with `amount` USDG: the calls (approve, then the router's swap), sent when `wallet` is given. */
241
+ export const ptBuy = (client, o = {}) => bundle(client, { ...o, kind: "buy" });
242
+ /** Sell `amount` PT-USDG (or "all") for USDG at the market, before maturity. */
243
+ export const ptSell = (client, o = {}) => bundle(client, { ...o, kind: "sell" });
244
+ /** Redeem `amount` PT-USDG (or "all") for USDG 1:1, from maturity on: of `market` (a market, PT or YT address), or by
245
+ * default of the oldest matured market the account holds PT of. */
246
+ export const ptRedeem = (client, o = {}) => bundle(client, { ...o, kind: "redeem" });
247
+
248
+ /**
249
+ * `account`'s PT-USDG of the active market: its balance, what it is worth now at the oracle's spot price, what it pays
250
+ * at maturity, the days left and the fixed APY a buyer locks in now; the stock vault's listing of the token (whether it
251
+ * backs a line yet); and `markets`, its PT of every listed market ({ token, market, maturity, status, matured, balance,
252
+ * balanceText, action: "trade" | "redeem" | "hold" }), so PT of an earlier, redeem-only market shows with its Redeem.
253
+ */
254
+ export async function ptPosition(client, account, { now } = {}) {
255
+ const who = getAddress(account);
256
+ const { rate, now: t } = await ptRateOf(client, { now });
257
+ const [balance, listing] = await Promise.all([read(client, PT_USDG.token, PT_ABI, "balanceOf", [who]), ptListing(client)]);
258
+ const value = (balance * rate) / 10n ** 18n;
259
+ const markets = [];
260
+ for (const m of PT_MARKETS) {
261
+ const b = m.token === PT_USDG.token ? balance : await read(client, m.token, PT_ABI, "balanceOf", [who]).catch(() => null);
262
+ const due = t >= m.expiry;
263
+ markets.push({ token: m.token, market: m.market, maturity: m.maturity, status: m.status, matured: due, balance: b, balanceText: b == null ? null : fmt6(b),
264
+ action: due ? "redeem" : m.status === "active" ? "trade" : "hold" });
265
+ }
266
+ return {
267
+ account: who, token: PT_USDG.token, balance, balanceText: fmt6(balance), value, valueText: fmt6(value),
268
+ atMaturity: balance, atMaturityText: fmt6(balance), ...terms(rate, t), listing, markets,
269
+ };
270
+ }
271
+
272
+ /**
273
+ * The stock vault's listing of PT-USDG: { listed, enabled, ltvBps, lineCap, openLines, backsLines } (`backsLines`: a
274
+ * line can open on it now); `listed` false until the Safe's setAsset. null when the vault cannot be read.
275
+ */
276
+ export async function ptListing(client) {
277
+ try {
278
+ const [a, open] = await Promise.all([read(client, PT_USDG.stockVault, VAULT_ASSET_ABI, "assets", [PT_USDG.token]), read(client, PT_USDG.stockVault, VAULT_ASSET_ABI, "openLinesOf", [PT_USDG.token]).catch(() => null)]);
279
+ const [feed, , tokenDecimals, , enabled, ltvBps, lineCap] = a;
280
+ const listed = getAddress(feed) !== ZERO && Number(tokenDecimals) === PT_USDG.decimals;
281
+ return { listed, enabled: listed && enabled === true, ltvBps: Number(ltvBps), lineCap: BigInt(lineCap), openLines: open,
282
+ backsLines: listed && enabled === true && BigInt(lineCap) > 0n && (open === null || open < BigInt(lineCap)), planned: PT_USDG.planned };
283
+ } catch (_) { return null; }
284
+ }
285
+
286
+ /** The same figures as JSON-safe values (bigints as decimal strings), for an MCP tool or an HTTP answer. */
287
+ export function jsonSafe(x) {
288
+ return JSON.parse(JSON.stringify(x, (_, v) => (typeof v === "bigint" ? v.toString() : v)));
289
+ }