@priors/mcp 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -3
- package/bin/priors-mcp.mjs +1 -1
- package/deployments/pendle.4663.json +21 -0
- package/deployments/pt-usdg.4663.json +25 -0
- package/package.json +4 -3
- package/src/pendle-pt.mjs +192 -0
- package/src/pt-usdg.mjs +289 -0
- package/src/server.mjs +128 -4
package/README.md
CHANGED
|
@@ -35,6 +35,11 @@ repaying.
|
|
|
35
35
|
| `autopay_off(clear_budget?)` | turn Autopay off (and with `clear_budget`, set the approvals to 0) | yes |
|
|
36
36
|
| `score_of(agent_id)` | any agent's on-chain score (0 to 1000) and repayment record, plus its Priors Score v2 and trust rung when published | no |
|
|
37
37
|
| `find_services(query?)` | services registered with the Priors facilitator that accept USDG (`GET /merchants`), each marked as approved by Priors or self-registered and not reviewed | no |
|
|
38
|
+
| `pt_quote(side, amount, slippage_bps?)` | quote buying PT-USDG with USDG, selling it before maturity or redeeming it after: what comes out at the oracle's spot rate, the minimum a trade would name, the days to maturity and the fixed APY to maturity | no |
|
|
39
|
+
| `pt_position(address?)` | the wallet's (or any address's) PT-USDG: balance, what it is worth now, what it pays at maturity, and whether the Priors stock vault takes PT-USDG behind a line yet | no (with `address`) |
|
|
40
|
+
| `pt_buy(amount_usdg, slippage_bps?, dry_run?)` | buy PT-USDG with the wallet's USDG through Pendle's router (at most `PRIORS_MAX_PT_USD` per call, `PRIORS_MAX_PT_TOTAL_USD` per run); `dry_run` lists the calls; needs ETH for gas | yes |
|
|
41
|
+
| `pt_sell(amount_pt \| "all", slippage_bps?, dry_run?)` | sell the wallet's PT-USDG for USDG at the market, before maturity; needs ETH for gas | yes |
|
|
42
|
+
| `pt_redeem(amount_pt \| "all", slippage_bps?, dry_run?)` | redeem the wallet's PT-USDG for USDG 1:1, from maturity (2027-03-25) on; needs ETH for gas | yes |
|
|
38
43
|
|
|
39
44
|
Tools that move money state the amounts in their answer, are marked destructive for MCP clients, and their
|
|
40
45
|
descriptions tell the assistant to confirm with you first. Merchant text (response bodies, listings, redirect targets)
|
|
@@ -68,6 +73,21 @@ on the default vault. Pointing `PRIORS_SAVINGS_VAULT` at another vault means tru
|
|
|
68
73
|
contract whose asset is USDG); money saved in the default one stays there, and money saved in a custom one is reached
|
|
69
74
|
by setting that vault again.
|
|
70
75
|
|
|
76
|
+
## PT-USDG
|
|
77
|
+
|
|
78
|
+
PT-USDG is Pendle's principal token for USDG on Robinhood Chain (the market maturing 2027-03-25, 00:00 UTC): bought
|
|
79
|
+
below 1 USDG, it redeems for exactly 1 USDG at maturity, so a buyer held to maturity locks in a fixed yield; sold
|
|
80
|
+
before then, it gets the market's rate at that moment, which can be lower. The `pt_*` tools trade it through Pendle's
|
|
81
|
+
router with the same calls as the Priors SDK (`sdk/pt-usdg.mjs` and `sdk/pendle-pt.mjs`, bundled here byte for byte):
|
|
82
|
+
an approval of exactly the trade's amount, right before the router call that uses it; USDG in or out directly (no
|
|
83
|
+
outside aggregator, no limit orders); the PT or USDG always paid to the wallet itself; and a minimum out (the quote
|
|
84
|
+
less `slippage_bps`, 1% by default): the router reverts rather than fill worse. Each call is simulated before it is
|
|
85
|
+
sent and its receipt checked. The quote is the oracle's spot rate, before the trade's own price impact, so a large
|
|
86
|
+
trade may need a wider margin.
|
|
87
|
+
|
|
88
|
+
Once the Priors stock vault lists PT-USDG, an agent's owner can post it behind a line (`pt_position` says when);
|
|
89
|
+
until then it is a token the wallet holds. `PRIORS_PT=off` removes the five tools.
|
|
90
|
+
|
|
71
91
|
## Configure
|
|
72
92
|
|
|
73
93
|
The only secret is the wallet key, and it is read from the environment variable `PRIORS_KEY`, never from the command
|
|
@@ -94,6 +114,9 @@ dedicated agent wallet holding only what the agent may spend.
|
|
|
94
114
|
| `PRIORS_V5`, `PRIORS_V5_ROOT` | the bundled deployments file's `seatVaultV5` and `seatVaultV5AgentId` (none until V5 is deployed) | SeatVaultV5 and its root's agent id: a borrow on a V5 line (the `borrow` tool, `pay_url`) refreshes it first. The agent's key may do so 24 hours after V5 recorded it (`noteDelegate`, sent for it when needed); until then a borrow goes ahead only within the line's room, and the tool says when the key can borrow more |
|
|
95
115
|
| `PRIORS_MAX_AUTOPAY_USD` | `25` | the most `autopay_on` enrolls per loan (stage 0) |
|
|
96
116
|
| `PRIORS_AUTOPAY_RESERVE` | on | with Autopay on, `pay_url` keeps back what loans whose window opens in the next 24 h will pull, and says so when a payment would cut into it; `off` turns that off |
|
|
117
|
+
| `PRIORS_PT` | on | `off` (or `false`, `0`, `no`) removes the PT-USDG tools |
|
|
118
|
+
| `PRIORS_MAX_PT_USD` | `50` | most USDG one `pt_buy` may spend (sales and redemptions only turn the wallet's PT back into USDG) |
|
|
119
|
+
| `PRIORS_MAX_PT_TOTAL_USD` | `200` | most USDG `pt_buy` may spend in total while the server runs (a buy whose transaction was sent counts, even if its answer is lost) |
|
|
97
120
|
| `PRIORS_STATE_DIR` | `~/.local/state/priors-mcp` | where the payments signed and not yet settled are kept (one owner-only file per wallet, never the key, with a short-lived `.lock` beside it while it is written), so a restart, a new session or another session of the same wallet resends them instead of signing again. An absolute path, or one starting with `~/` (a relative one is refused at start). A payment that cannot be written there is not sent. `off` keeps them in memory only |
|
|
98
121
|
|
|
99
122
|
Contract addresses (pool, lens, registry, USDG) come from `deployments/4663.v2.json`, bundled in the package, and the
|
|
@@ -109,7 +132,7 @@ Settings → Developer → Edit Config (`claude_desktop_config.json`), then rest
|
|
|
109
132
|
"mcpServers": {
|
|
110
133
|
"priors": {
|
|
111
134
|
"command": "npx",
|
|
112
|
-
"args": ["-y", "@priors/mcp@0.
|
|
135
|
+
"args": ["-y", "@priors/mcp@0.6.1"],
|
|
113
136
|
"env": {
|
|
114
137
|
"PRIORS_KEY": "0xYOUR_AGENT_WALLET_KEY",
|
|
115
138
|
"PRIORS_AGENT_ID": "1234"
|
|
@@ -131,7 +154,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
|
|
|
131
154
|
"mcpServers": {
|
|
132
155
|
"priors": {
|
|
133
156
|
"command": "npx",
|
|
134
|
-
"args": ["-y", "@priors/mcp@0.
|
|
157
|
+
"args": ["-y", "@priors/mcp@0.6.1"],
|
|
135
158
|
"env": {
|
|
136
159
|
"PRIORS_KEY": "${PRIORS_KEY}",
|
|
137
160
|
"PRIORS_AGENT_ID": "${PRIORS_AGENT_ID:-}"
|
|
@@ -141,7 +164,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
|
|
|
141
164
|
}
|
|
142
165
|
```
|
|
143
166
|
|
|
144
|
-
or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.
|
|
167
|
+
or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.6.1`
|
|
145
168
|
(the key is expanded by your shell from the environment; do not paste it on the command line).
|
|
146
169
|
|
|
147
170
|
## Try it
|
package/bin/priors-mcp.mjs
CHANGED
|
@@ -9,7 +9,7 @@ if (argv.some((a) => /(^|[^0-9a-fA-F])(0x)?[0-9a-fA-F]{64}($|[^0-9a-fA-F])/.test
|
|
|
9
9
|
process.exit(2);
|
|
10
10
|
}
|
|
11
11
|
if (argv.includes("--help") || argv.includes("-h")) {
|
|
12
|
-
process.stderr.write("priors-mcp: MCP server (stdio) for Priors on Robinhood Chain.\nenv: PRIORS_KEY (wallet key, optional), PRIORS_RPC, PRIORS_AGENT_ID, PRIORS_FACILITATOR, PRIORS_MAX_PRICE_USD, PRIORS_MAX_BORROW_USD, PRIORS_MAX_SPEND_USD, PRIORS_MAX_BORROW_TOTAL_USD, PRIORS_ALLOW_LOCAL, PRIORS_STOCK_VAULT, PRIORS_SCORE_V2, PRIORS_SAVINGS_VAULT, PRIORS_MAX_SAVE_USD, PRIORS_MAX_SAVE_TOTAL_USD, PRIORS_STATE_DIR\nSee the README for the Claude Desktop / Claude Code config.\n");
|
|
12
|
+
process.stderr.write("priors-mcp: MCP server (stdio) for Priors on Robinhood Chain.\nenv: PRIORS_KEY (wallet key, optional), PRIORS_RPC, PRIORS_AGENT_ID, PRIORS_FACILITATOR, PRIORS_MAX_PRICE_USD, PRIORS_MAX_BORROW_USD, PRIORS_MAX_SPEND_USD, PRIORS_MAX_BORROW_TOTAL_USD, PRIORS_ALLOW_LOCAL, PRIORS_STOCK_VAULT, PRIORS_SCORE_V2, PRIORS_SAVINGS_VAULT, PRIORS_MAX_SAVE_USD, PRIORS_MAX_SAVE_TOTAL_USD, PRIORS_PT, PRIORS_MAX_PT_USD, PRIORS_MAX_PT_TOTAL_USD, PRIORS_STATE_DIR\nSee the README for the Claude Desktop / Claude Code config.\n");
|
|
13
13
|
process.exit(0);
|
|
14
14
|
}
|
|
15
15
|
if (argv.length > 0) {
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"_what": "Pendle's router on Robinhood Chain and the PT-USDG markets Priors trades through it, for buying, selling and redeeming PT-USDG (sdk/pendle-pt.mjs, gas-worker/gate.mjs, mcp-worker/tools.mjs, and the pages through scripts/build-site.mjs's generated pt-markets.js). From pendle-core-v2-public deployments/4663-core.json and the Pendle API, read 2026-10-05: the API's own routes for USDG to PT and PT to USDG on the 2027-03-25 market call swapExactTokenForPt (0xc81f847a) and swapExactPtForToken (0x594a88cc) on this router, with no outside aggregator.",
|
|
3
|
+
"_markets": "Every market Priors trades or has traded, oldest first. status \"active\": bought and sold (until its expiry) and redeemed after it; at most one market is active. \"redeem-only\": a matured or retired market, redeemed only, after its expiry, so holders can always cash out through Priors. A new market is listed by adding its entry as active and setting the old one to redeem-only, never by editing addresses in place (docs/PT-USDG.md, \"Rollover at maturity\"). pyLpOracle: Pendle's PY/LP oracle for the market's spot rate (the top-level one unless the entry names its own).",
|
|
4
|
+
"chainId": 4663,
|
|
5
|
+
"router": "0x888888888889758F76e7103c6CbF23ABbF58F946",
|
|
6
|
+
"routerStatic": "0x6813d43782395A1F2AAb42f39aeEDE03ac655e09",
|
|
7
|
+
"usdg": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
|
|
8
|
+
"pyLpOracle": "0x5542be50420E88dd7D5B4a3D488FA6ED82F6DAc2",
|
|
9
|
+
"maxUsdgPerOp": "2000000000",
|
|
10
|
+
"_maxUsdgPerOp": "The most USDG one sponsored buy may spend, and the most PT one sponsored sale may sell (6 decimals both): 2,000. The market moved 0.09% per 1,000 USDG and 0.76% per 10,000 on 2026-10-01 (reports/Pendle integration for Priors.md).",
|
|
11
|
+
"markets": [
|
|
12
|
+
{
|
|
13
|
+
"market": "0xc2b89e6eca583e2c232201ac557e9be58af55f4c",
|
|
14
|
+
"pt": "0x6982e39521A070a3C40782548bfBED6Dc8F566ef",
|
|
15
|
+
"sy": "0x8d3127aAbf76F95fE2970A0480B8662B4ad4C286",
|
|
16
|
+
"yt": "0xF35Ee6bd9A93fE42BC7e628BFC4DDbdc6DE1f615",
|
|
17
|
+
"expiry": 1805932800,
|
|
18
|
+
"status": "active"
|
|
19
|
+
}
|
|
20
|
+
]
|
|
21
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"_what": "The PT-USDG collateral track on the live StockVault (docs/PT-USDG.md). Read by script/DeployPtFeed.s.sol (the feed's constructor and its checks), the keeper (ops/pt-usdg-keeper.mjs, once `feed` is set) and ops/2026-10-02-pt-usdg-safe-txs.md. Pendle's addresses were read on chain 4663 on 2026-10-02 (market.readTokens(), PT.expiry(), decimals()); the deploy script reads them again and refuses to deploy if any differs.",
|
|
3
|
+
"chainId": 4663,
|
|
4
|
+
"market": "0xc2b89e6eca583e2c232201ac557e9be58af55f4c",
|
|
5
|
+
"pt": "0x6982e39521A070a3C40782548bfBED6Dc8F566ef",
|
|
6
|
+
"sy": "0x8d3127aAbf76F95fE2970A0480B8662B4ad4C286",
|
|
7
|
+
"yt": "0xF35Ee6bd9A93fE42BC7e628BFC4DDbdc6DE1f615",
|
|
8
|
+
"usdg": "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
|
|
9
|
+
"pyLpOracle": "0x5542be50420E88dd7D5B4a3D488FA6ED82F6DAc2",
|
|
10
|
+
"expiry": 1805932800,
|
|
11
|
+
"expiryUtc": "2027-03-25T00:00:00Z",
|
|
12
|
+
"ptDecimals": 6,
|
|
13
|
+
"rateBps": 600,
|
|
14
|
+
"safe": "0x20c6816B2419616238772591965E6E9AbE493fD5",
|
|
15
|
+
"stockVault": "0xbEcd07EC689988e16b870C121756C4c2C8cb02B6",
|
|
16
|
+
"setAsset": {
|
|
17
|
+
"maxAge": 93600,
|
|
18
|
+
"enabled": true,
|
|
19
|
+
"ltvBps": 5000,
|
|
20
|
+
"lineCap": "250000000",
|
|
21
|
+
"_why": "The owner's launch settings (2026-10-02): 26 h, 50%, $250 of open PT lines in all."
|
|
22
|
+
},
|
|
23
|
+
"feed": "0x0000000000000000000000000000000000000000",
|
|
24
|
+
"feedBlock": 0
|
|
25
|
+
}
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@priors/mcp",
|
|
3
3
|
"mcpName": "io.github.priors-agents/priors",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.6.1",
|
|
5
5
|
"private": false,
|
|
6
|
-
"description": "MCP server for Priors on Robinhood Chain: pay x402 URLs in USDG, read balances, credit lines and scores, borrow and repay. Key from PRIORS_KEY only.",
|
|
6
|
+
"description": "MCP server for Priors on Robinhood Chain: pay x402 URLs in USDG, read balances, credit lines and scores, borrow and repay, and buy, sell and redeem PT-USDG. Key from PRIORS_KEY only.",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"bin": {
|
|
9
9
|
"priors-mcp": "bin/priors-mcp.mjs"
|
|
@@ -39,13 +39,14 @@
|
|
|
39
39
|
"url": "https://github.com/priors-agents/priors/issues"
|
|
40
40
|
},
|
|
41
41
|
"engines": {
|
|
42
|
-
"node": ">=20"
|
|
42
|
+
"node": ">=20.10"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@modelcontextprotocol/sdk": "^1.30.1",
|
|
46
46
|
"@priors/x402": "0.5.0",
|
|
47
47
|
"ethers": "^6.13.4",
|
|
48
48
|
"undici": "6.29.0",
|
|
49
|
+
"viem": "^2.56.9",
|
|
49
50
|
"zod": "^4.6.5"
|
|
50
51
|
}
|
|
51
52
|
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// PT-USDG through Pendle's router, for the account pages, the SDK and the gas gate: one place that builds the three
|
|
2
|
+
// calls Priors makes on Pendle (buy PT with USDG, sell PT for USDG, redeem PT for USDG after maturity), quotes them from
|
|
3
|
+
// the chain, and checks a call against the one shape Priors sponsors (checkRouterCall, used by gas-worker/gate.mjs).
|
|
4
|
+
//
|
|
5
|
+
// The markets are deployments/pendle.4663.json's `markets`: Pendle lists a new PT-USDG market for each maturity, so the
|
|
6
|
+
// record keeps every market Priors trades or has traded. At most one is "active": bought and sold until its expiry,
|
|
7
|
+
// redeemed after it. The others are "redeem-only": matured or retired, redeemed only, after their expiry, so a holder
|
|
8
|
+
// can always cash out through Priors. Every call is USDG in or out directly: the SY takes and gives USDG itself, so no
|
|
9
|
+
// outside aggregator (pendleSwap 0, swap type NONE) and no limit orders are ever involved, and the receiver is always the
|
|
10
|
+
// account that signs. A buy or a sale always names a minimum out.
|
|
11
|
+
//
|
|
12
|
+
// PENDLE the record, checked and frozen: { router, routerStatic, usdg, pyLpOracle, maxUsdgPerOp, markets, active }
|
|
13
|
+
// MARKETS its markets, oldest first: { market, pt, sy, yt, expiry, maturity, pyLpOracle, status, active }
|
|
14
|
+
// ACTIVE_MARKET the active one (null when none is)
|
|
15
|
+
// PENDLE_ADDR the active market's addresses in one flat object, as before markets were a list
|
|
16
|
+
// marketOf(x) a listed market by its market, PT or YT address (or the entry itself); the active one for undefined
|
|
17
|
+
import { decodeFunctionData, encodeFunctionData, getAddress, parseAbi } from "viem";
|
|
18
|
+
import RECORD from "../deployments/pendle.4663.json" with { type: "json" };
|
|
19
|
+
|
|
20
|
+
const ZERO = "0x0000000000000000000000000000000000000000";
|
|
21
|
+
const STATUSES = new Set(["active", "redeem-only"]);
|
|
22
|
+
const day = (expiry) => new Date(expiry * 1000).toISOString().slice(0, 10);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A Pendle record (deployments/pendle.4663.json's shape) checked and frozen: addresses checksummed, expiries numbers,
|
|
26
|
+
* the cap a bigint, each market's oracle filled in, at most one active market, no market, PT or YT listed twice.
|
|
27
|
+
* Throws with the reason for a record that is not one. Tests build their own lists with it.
|
|
28
|
+
*/
|
|
29
|
+
export function pendleConfig(raw) {
|
|
30
|
+
if (!raw || !Array.isArray(raw.markets) || !raw.markets.length) throw new Error("Pendle record: no markets");
|
|
31
|
+
const addr = (v, what) => { try { const a = getAddress(v); if (a === ZERO) throw new Error(); return a; } catch (_) { throw new Error(`Pendle record: ${what} is not an address`); } };
|
|
32
|
+
const router = addr(raw.router, "router"), usdg = addr(raw.usdg, "usdg");
|
|
33
|
+
const oracle = raw.pyLpOracle ? addr(raw.pyLpOracle, "pyLpOracle") : null;
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
const markets = raw.markets.map((m, i) => {
|
|
36
|
+
const e = {
|
|
37
|
+
market: addr(m.market, `markets[${i}].market`), pt: addr(m.pt, `markets[${i}].pt`), sy: addr(m.sy, `markets[${i}].sy`), yt: addr(m.yt, `markets[${i}].yt`),
|
|
38
|
+
expiry: Number(m.expiry), pyLpOracle: m.pyLpOracle ? addr(m.pyLpOracle, `markets[${i}].pyLpOracle`) : oracle, status: m.status,
|
|
39
|
+
};
|
|
40
|
+
if (!Number.isSafeInteger(e.expiry) || e.expiry <= 0) throw new Error(`Pendle record: markets[${i}].expiry is not a time`);
|
|
41
|
+
if (!STATUSES.has(e.status)) throw new Error(`Pendle record: markets[${i}].status is "active" or "redeem-only"`);
|
|
42
|
+
for (const k of ["market", "pt", "yt"]) { const key = e[k].toLowerCase(); if (seen.has(key)) throw new Error(`Pendle record: ${e[k]} is listed twice`); seen.add(key); }
|
|
43
|
+
return Object.freeze({ ...e, maturity: day(e.expiry), active: e.status === "active" });
|
|
44
|
+
});
|
|
45
|
+
const active = markets.filter((m) => m.active);
|
|
46
|
+
if (active.length > 1) throw new Error("Pendle record: more than one active market");
|
|
47
|
+
const cap = BigInt(raw.maxUsdgPerOp);
|
|
48
|
+
if (cap <= 0n) throw new Error("Pendle record: maxUsdgPerOp must be above zero");
|
|
49
|
+
return Object.freeze({
|
|
50
|
+
chainId: Number(raw.chainId) || 4663, router, routerStatic: raw.routerStatic ? addr(raw.routerStatic, "routerStatic") : null, usdg, pyLpOracle: oracle,
|
|
51
|
+
maxUsdgPerOp: cap, markets: Object.freeze(markets), active: active[0] || null,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const PENDLE = pendleConfig(RECORD);
|
|
56
|
+
export const MARKETS = PENDLE.markets;
|
|
57
|
+
export const ACTIVE_MARKET = PENDLE.active;
|
|
58
|
+
// the active market as one flat object (the latest market's addresses when none is active: its buys are refused)
|
|
59
|
+
const VIEW = ACTIVE_MARKET || MARKETS[MARKETS.length - 1];
|
|
60
|
+
export const PENDLE_ADDR = Object.freeze({
|
|
61
|
+
router: PENDLE.router, market: VIEW.market, pt: VIEW.pt, yt: VIEW.yt, sy: VIEW.sy, usdg: PENDLE.usdg, expiry: VIEW.expiry, maxUsdgPerOp: PENDLE.maxUsdgPerOp,
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const same = (x, y) => { try { return !!x && !!y && getAddress(x) === getAddress(y); } catch (_) { return false; } };
|
|
65
|
+
/**
|
|
66
|
+
* A listed market of `conf`: `x` an entry, or a market, PT or YT address; undefined is the active market. Throws for one
|
|
67
|
+
* the record does not list (and for undefined when no market is active).
|
|
68
|
+
*/
|
|
69
|
+
export function marketOf(x, conf = PENDLE) {
|
|
70
|
+
if (x === undefined || x === null) {
|
|
71
|
+
if (!conf.active) throw new Error("Pendle: no PT-USDG market is open for buying now");
|
|
72
|
+
return conf.active;
|
|
73
|
+
}
|
|
74
|
+
const a = typeof x === "object" ? x.market : x;
|
|
75
|
+
const m = conf.markets.find((e) => same(a, e.market) || same(a, e.pt) || same(a, e.yt));
|
|
76
|
+
if (!m) throw new Error(`Pendle: ${String(a).slice(0, 42)} is not a PT-USDG market Priors lists`);
|
|
77
|
+
return m;
|
|
78
|
+
}
|
|
79
|
+
/** The markets of `conf` whose PT redeems now (`nowS` at or past expiry), oldest first. */
|
|
80
|
+
export const maturedMarkets = (nowS, conf = PENDLE) => conf.markets.filter((m) => nowS >= m.expiry);
|
|
81
|
+
const tradable = (m) => { if (!m.active) throw new Error(`Pendle: the market maturing ${m.maturity} is redeem-only`); return m; };
|
|
82
|
+
|
|
83
|
+
// the router's three functions Priors uses, with Pendle's structs spelled out (IPAllActionTypeV3)
|
|
84
|
+
const SWAP_DATA = "(uint8 swapType, address extRouter, bytes extCalldata, bool needScale)";
|
|
85
|
+
const ORDER = "(uint256 salt, uint256 expiry, uint256 nonce, uint8 orderType, address token, address YT, address maker, address receiver, uint256 makingAmount, uint256 lnImpliedRate, uint256 failSafeRate, bytes permit)";
|
|
86
|
+
const FILL = `(${ORDER} order, bytes signature, uint256 makingAmount)`;
|
|
87
|
+
const LIMIT = `(address limitRouter, uint256 epsSkipMarket, ${FILL}[] normalFills, ${FILL}[] flashFills, bytes optData)`;
|
|
88
|
+
const TOKEN_IN = `(address tokenIn, uint256 netTokenIn, address tokenMintSy, address pendleSwap, ${SWAP_DATA} swapData)`;
|
|
89
|
+
const TOKEN_OUT = `(address tokenOut, uint256 minTokenOut, address tokenRedeemSy, address pendleSwap, ${SWAP_DATA} swapData)`;
|
|
90
|
+
const APPROX = "(uint256 guessMin, uint256 guessMax, uint256 guessOffchain, uint256 maxIteration, uint256 eps)";
|
|
91
|
+
export const ROUTER_ABI = parseAbi([
|
|
92
|
+
`function swapExactTokenForPt(address receiver, address market, uint256 minPtOut, ${APPROX} guessPtOut, ${TOKEN_IN} input, ${LIMIT} limit) payable returns (uint256 netPtOut, uint256 netSyFee, uint256 netSyInterm)`,
|
|
93
|
+
`function swapExactPtForToken(address receiver, address market, uint256 exactPtIn, ${TOKEN_OUT} output, ${LIMIT} limit) returns (uint256 netTokenOut, uint256 netSyFee, uint256 netSyInterm)`,
|
|
94
|
+
`function redeemPyToToken(address receiver, address YT, uint256 netPyIn, ${TOKEN_OUT} output) returns (uint256 netTokenOut, uint256 netSyInterm)`,
|
|
95
|
+
]);
|
|
96
|
+
export const SELECTORS = Object.freeze({ buy: "0xc81f847a", sell: "0x594a88cc" });
|
|
97
|
+
export const ORACLE_ABI = parseAbi(["function getPtToAssetRate(address market, uint32 duration) view returns (uint256)"]);
|
|
98
|
+
export const PT_ABI = parseAbi(["function balanceOf(address) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function approve(address spender, uint256 amount) returns (bool)", "function isExpired() view returns (bool)"]);
|
|
99
|
+
|
|
100
|
+
const NONE_SWAP = { swapType: 0, extRouter: ZERO, extCalldata: "0x", needScale: false };
|
|
101
|
+
const NO_LIMIT = { limitRouter: ZERO, epsSkipMarket: 0n, normalFills: [], flashFills: [], optData: "0x" };
|
|
102
|
+
// Pendle's defaults for an on-chain search of the PT amount (no off-chain guess): the full range, 256 steps, 0.01%
|
|
103
|
+
const DEFAULT_APPROX = { guessMin: 0n, guessMax: (1n << 256n) - 1n, guessOffchain: 0n, maxIteration: 256n, eps: 10n ** 14n };
|
|
104
|
+
|
|
105
|
+
/** USDG in, PT out to `receiver`, at least `minPtOut` (all 6 decimals), on `market` (default: the active one; only an active market). */
|
|
106
|
+
export function buildBuy({ receiver, usdgIn, minPtOut, market }, conf = PENDLE) {
|
|
107
|
+
if (!(minPtOut > 0n)) throw new Error("a buy needs a minimum PT out");
|
|
108
|
+
const m = tradable(marketOf(market, conf));
|
|
109
|
+
return encodeFunctionData({ abi: ROUTER_ABI, functionName: "swapExactTokenForPt", args: [getAddress(receiver), m.market, minPtOut, DEFAULT_APPROX,
|
|
110
|
+
{ tokenIn: conf.usdg, netTokenIn: usdgIn, tokenMintSy: conf.usdg, pendleSwap: ZERO, swapData: NONE_SWAP }, NO_LIMIT] });
|
|
111
|
+
}
|
|
112
|
+
/** PT in, USDG out to `receiver`, at least `minUsdgOut`. Before maturity, at the market's price; only an active market. */
|
|
113
|
+
export function buildSell({ receiver, ptIn, minUsdgOut, market }, conf = PENDLE) {
|
|
114
|
+
if (!(minUsdgOut > 0n)) throw new Error("a sale needs a minimum USDG out");
|
|
115
|
+
const m = tradable(marketOf(market, conf));
|
|
116
|
+
return encodeFunctionData({ abi: ROUTER_ABI, functionName: "swapExactPtForToken", args: [getAddress(receiver), m.market, ptIn,
|
|
117
|
+
{ tokenOut: conf.usdg, minTokenOut: minUsdgOut, tokenRedeemSy: conf.usdg, pendleSwap: ZERO, swapData: NONE_SWAP }, NO_LIMIT] });
|
|
118
|
+
}
|
|
119
|
+
/** After maturity: PT in, USDG out 1:1 to `receiver` (the SY's own redemption; `minUsdgOut` is normally ptIn), on any listed market. */
|
|
120
|
+
export function buildRedeem({ receiver, ptIn, minUsdgOut, market }, conf = PENDLE) {
|
|
121
|
+
if (!(minUsdgOut > 0n)) throw new Error("a redemption needs a minimum USDG out");
|
|
122
|
+
const m = marketOf(market, conf);
|
|
123
|
+
return encodeFunctionData({ abi: ROUTER_ABI, functionName: "redeemPyToToken", args: [getAddress(receiver), m.yt, ptIn,
|
|
124
|
+
{ tokenOut: conf.usdg, minTokenOut: minUsdgOut, tokenRedeemSy: conf.usdg, pendleSwap: ZERO, swapData: NONE_SWAP }] });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The market's spot PT price in USDG (1e18 = par), read from Pendle's PY/LP oracle (`oracle`, default the market's);
|
|
129
|
+
* then what an amount buys or sells for at that price, less a slippage margin. Duration 0 is the spot rate: Pendle's
|
|
130
|
+
* TWAP needs the market's oracle cardinality raised first (ops/2026-10-05-pt-usdg-start.md).
|
|
131
|
+
*/
|
|
132
|
+
export async function ptRate(client, oracle, market) {
|
|
133
|
+
const m = marketOf(market);
|
|
134
|
+
return client.readContract({ address: getAddress(oracle || m.pyLpOracle), abi: ORACLE_ABI, functionName: "getPtToAssetRate", args: [m.market, 0] });
|
|
135
|
+
}
|
|
136
|
+
export function quoteBuy(usdgIn, rate, slippageBps = 100n) {
|
|
137
|
+
const ptOut = (usdgIn * 10n ** 18n) / rate;
|
|
138
|
+
return { ptOut, minPtOut: (ptOut * (10_000n - slippageBps)) / 10_000n };
|
|
139
|
+
}
|
|
140
|
+
export function quoteSell(ptIn, rate, slippageBps = 100n) {
|
|
141
|
+
const usdgOut = (ptIn * rate) / 10n ** 18n;
|
|
142
|
+
return { usdgOut, minUsdgOut: (usdgOut * (10_000n - slippageBps)) / 10_000n };
|
|
143
|
+
}
|
|
144
|
+
/** Whether `market` (default: the active one, else the latest) has matured at `nowS`. */
|
|
145
|
+
export const matured = (nowS, market) => nowS >= (market === undefined ? VIEW : marketOf(market)).expiry;
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The gas gate's check of one router call. Returns { kind: "buy" | "sell" | "redeem", usdgIn?, ptIn?, market, pt } for a
|
|
149
|
+
* call of the one shape Priors builds above, for `sender` as the receiver, on a market `conf` lists: a buy or a sale only
|
|
150
|
+
* on the active market before its expiry, a redemption on any listed market from its expiry on (`now`, seconds; default
|
|
151
|
+
* the clock). Throws with the reason otherwise.
|
|
152
|
+
*/
|
|
153
|
+
export function checkRouterCall(data, sender, { now = Math.floor(Date.now() / 1000), conf = PENDLE } = {}) {
|
|
154
|
+
let d;
|
|
155
|
+
try { d = decodeFunctionData({ abi: ROUTER_ABI, data }); } catch (_) { throw new Error("Pendle: only buying, selling or redeeming PT-USDG"); }
|
|
156
|
+
const f = d.functionName, x = d.args;
|
|
157
|
+
if (!same(x[0], sender)) throw new Error("Pendle: the account itself must receive what the router pays out");
|
|
158
|
+
const noSwap = (s) => { if (Number(s.swapType) !== 0 || !same(s.extRouter, ZERO) || (s.extCalldata && s.extCalldata !== "0x") || s.needScale) throw new Error("Pendle: no outside aggregator"); };
|
|
159
|
+
const noLimit = (l) => { if (!same(l.limitRouter, ZERO) || l.normalFills.length || l.flashFills.length || (l.optData && l.optData !== "0x")) throw new Error("Pendle: no limit orders"); };
|
|
160
|
+
const usdgOut = (o) => { if (!same(o.tokenOut, conf.usdg) || !same(o.tokenRedeemSy, conf.usdg) || !same(o.pendleSwap, ZERO)) throw new Error("Pendle: paid out in USDG only"); noSwap(o.swapData); if (!(o.minTokenOut > 0n)) throw new Error("Pendle: a minimum USDG out is required"); };
|
|
161
|
+
const cap = (n, what) => { if (n > conf.maxUsdgPerOp) throw new Error(`Pendle: at most ${conf.maxUsdgPerOp / 1_000_000n} ${what} at a time`); };
|
|
162
|
+
// a buy or a sale: a listed market, the active one, not yet matured
|
|
163
|
+
const trading = (market) => {
|
|
164
|
+
const m = conf.markets.find((e) => same(market, e.market));
|
|
165
|
+
if (!m) throw new Error("Pendle: only a USDG market Priors lists");
|
|
166
|
+
if (!m.active) throw new Error(`Pendle: the USDG market maturing ${m.maturity} is redeem-only: no buying or selling`);
|
|
167
|
+
if (now >= m.expiry) throw new Error(`Pendle: the USDG market matured on ${m.maturity}: redeem its PT instead`);
|
|
168
|
+
return m;
|
|
169
|
+
};
|
|
170
|
+
if (f === "swapExactTokenForPt") {
|
|
171
|
+
const [, market, minPtOut, , input, limit] = x;
|
|
172
|
+
const m = trading(market);
|
|
173
|
+
if (!same(input.tokenIn, conf.usdg) || !same(input.tokenMintSy, conf.usdg) || !same(input.pendleSwap, ZERO)) throw new Error("Pendle: paid in USDG only");
|
|
174
|
+
noSwap(input.swapData); noLimit(limit);
|
|
175
|
+
if (!(minPtOut > 0n)) throw new Error("Pendle: a minimum PT out is required");
|
|
176
|
+
cap(input.netTokenIn, "USDG");
|
|
177
|
+
return { kind: "buy", usdgIn: input.netTokenIn, market: m.market, pt: m.pt };
|
|
178
|
+
}
|
|
179
|
+
if (f === "swapExactPtForToken") {
|
|
180
|
+
const [, market, ptIn, output, limit] = x;
|
|
181
|
+
const m = trading(market);
|
|
182
|
+
usdgOut(output); noLimit(limit); cap(ptIn, "PT");
|
|
183
|
+
return { kind: "sell", ptIn, market: m.market, pt: m.pt };
|
|
184
|
+
}
|
|
185
|
+
// redeemPyToToken: the YT names the market's PT; after maturity only PT is needed, so only from the expiry on
|
|
186
|
+
const [, yt, ptIn, output] = x;
|
|
187
|
+
const m = conf.markets.find((e) => same(yt, e.yt));
|
|
188
|
+
if (!m) throw new Error("Pendle: only the PT of a USDG market Priors lists");
|
|
189
|
+
if (now < m.expiry) throw new Error(`Pendle: PT-USDG of the market maturing ${m.maturity} redeems from that day; before it, sell it`);
|
|
190
|
+
usdgOut(output);
|
|
191
|
+
return { kind: "redeem", ptIn, market: m.market, pt: m.pt };
|
|
192
|
+
}
|
package/src/pt-usdg.mjs
ADDED
|
@@ -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
|
+
}
|
package/src/server.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// @priors/mcp: an MCP server that lets an AI assistant pay x402 URLs in USDG on Robinhood Chain and run a Priors
|
|
2
2
|
// credit line, with the agent's spare USDG saved in a Morpho vault. Tools: pay_url, wallet_balance, credit_status,
|
|
3
|
-
// stock_assets, stock_position, borrow, repay, score_of, find_services, savings, save, unsave, autopay_on, autopay_off
|
|
3
|
+
// stock_assets, stock_position, borrow, repay, score_of, find_services, savings, save, unsave, autopay_on, autopay_off,
|
|
4
|
+
// and PT-USDG (Pendle's principal token for USDG): pt_quote, pt_position, pt_buy, pt_sell, pt_redeem.
|
|
4
5
|
//
|
|
5
6
|
// The private key comes from the environment (PRIORS_KEY) only. It is never read from argv, never logged, and never
|
|
6
7
|
// part of any tool result or error: every text this server returns passes through `redact()`, which removes the key
|
|
@@ -32,6 +33,9 @@
|
|
|
32
33
|
// PRIORS_AUTOPAY_RESERVE "off": pay_url no longer keeps back what Autopay loans pull in the next 24 h (default on)
|
|
33
34
|
// PRIORS_STATE_DIR where signed, unsettled payments are kept across restarts and shared by every session of the
|
|
34
35
|
// wallet (default ~/.local/state/priors-mcp; "off": memory only)
|
|
36
|
+
// PRIORS_PT "off": no PT-USDG tool (default on: the market is Pendle's, live on Robinhood Chain)
|
|
37
|
+
// PRIORS_MAX_PT_USD most USDG one pt_buy may spend (default 50); sales and redemptions only turn PT back into USDG
|
|
38
|
+
// PRIORS_MAX_PT_TOTAL_USD most USDG pt_buy may spend in total while the server runs (default 200)
|
|
35
39
|
import { readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, statSync, rmSync } from "node:fs";
|
|
36
40
|
import { homedir } from "node:os";
|
|
37
41
|
import { isAbsolute, join } from "node:path";
|
|
@@ -43,6 +47,10 @@ import { fetch as undiciFetch, Agent } from "undici";
|
|
|
43
47
|
import { ethers } from "ethers";
|
|
44
48
|
import { z } from "zod";
|
|
45
49
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
50
|
+
// PT-USDG: byte-for-byte copies of the repository's sdk/pt-usdg.mjs and sdk/pendle-pt.mjs (the calls the SDK, the
|
|
51
|
+
// hosted MCP and the gas gate's check share), with their deployments/pendle.4663.json and pt-usdg.4663.json beside
|
|
52
|
+
// this package's other records (scripts/test-packages.mjs fails on any drift).
|
|
53
|
+
import * as P from "./pt-usdg.mjs";
|
|
46
54
|
|
|
47
55
|
// @priors/x402 when installed from npm; the sibling package in the monorepo otherwise.
|
|
48
56
|
async function loadX402() {
|
|
@@ -206,7 +214,12 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
206
214
|
// window. The cap per loan is bounded by this server (stage 0: $25); pay_url keeps back what Autopay loans pull soon.
|
|
207
215
|
const maxAutopayCap = envDollars(env, "PRIORS_MAX_AUTOPAY_USD", 25);
|
|
208
216
|
const reserveOn = !/^(off|false|0|no)$/i.test(String(env.PRIORS_AUTOPAY_RESERVE ?? "").trim());
|
|
209
|
-
|
|
217
|
+
// PT-USDG (Pendle's principal token for USDG, maturing 2027-03-25): on unless PRIORS_PT=off. Buys are capped per call
|
|
218
|
+
// and per process like save; a sale or a redemption turns the wallet's own PT back into USDG and has no cap.
|
|
219
|
+
const ptOn = !/^(off|false|0|no|none)$/i.test(String(env.PRIORS_PT ?? "").trim());
|
|
220
|
+
const maxPtCeiling = envDollars(env, "PRIORS_MAX_PT_USD", 50);
|
|
221
|
+
const ptTotalCap = envDollars(env, "PRIORS_MAX_PT_TOTAL_USD", 200);
|
|
222
|
+
const session = { spent: 0n, borrowed: 0n, saved: 0n, ptBought: 0n };
|
|
210
223
|
const allowLocal = env.PRIORS_ALLOW_LOCAL === "1";
|
|
211
224
|
const lookup = deps.lookup || ((host) => dnsLookup(host, { all: true }));
|
|
212
225
|
const sleep = deps.sleep; // undefined: the library's own
|
|
@@ -558,7 +571,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
558
571
|
}
|
|
559
572
|
|
|
560
573
|
const server = new McpServer({ name: "priors", version: VERSION }, {
|
|
561
|
-
instructions:
|
|
574
|
+
instructions: `Priors on Robinhood Chain (chain 4663): pay x402-priced URLs in USDG, and run the agent's Priors credit line. Tools that move money (pay_url, borrow, repay, save, unsave, autopay_on, autopay_off${ptOn ? ", pt_buy, pt_sell, pt_redeem" : ""}) act immediately on mainnet: state the amounts to the user and get their go-ahead first. Spare USDG can be saved in a Morpho vault (save); pay_url and repay take it back out when the wallet is short, before any borrowing.${ptOn ? ` PT-USDG (Pendle's principal token for USDG, redeemable 1:1 for USDG on ${P.PT_USDG.maturity.slice(0, 10)}) can be bought, sold and redeemed through Pendle's router (pt_quote, pt_position first).` : ""} Amounts are in US dollars of USDG.`,
|
|
562
575
|
});
|
|
563
576
|
const tool = (name, config, handler) => server.registerTool(name, config, async (args) => {
|
|
564
577
|
try { return text(await handler(args || {})); } catch (e) { return failure(explain(e)); }
|
|
@@ -774,7 +787,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
774
787
|
|
|
775
788
|
tool("score_of", {
|
|
776
789
|
title: "Priors score of an agent",
|
|
777
|
-
description: "Look up any agent's Priors score (0 to 1000) and repayment record on Robinhood Chain: a public
|
|
790
|
+
description: "Look up any agent's Priors score (0 to 1000) and repayment record on Robinhood Chain: a public record built from on-chain repayments, plus the open Priors Score v2 and its trust rung when published. Useful before trusting or paying an agent. Read-only.",
|
|
778
791
|
inputSchema: { agent_id: z.number().int().nonnegative().describe("Priors (ERC-8004) agent id.") },
|
|
779
792
|
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
780
793
|
}, async ({ agent_id }) => {
|
|
@@ -1000,6 +1013,117 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
|
|
|
1000
1013
|
return `Took ${usd(r.amount)} out of savings${r.inKind ? " (part of it from the vault's other markets, in one transaction)" : ""}. Tx ${r.hash}.${after}`;
|
|
1001
1014
|
}));
|
|
1002
1015
|
|
|
1016
|
+
// ---- PT-USDG: pt_quote / pt_position / pt_buy / pt_sell / pt_redeem ---------------------------------------------
|
|
1017
|
+
// Pendle's principal token for USDG (the markets of deployments/pendle.4663.json: the active one, maturing 2027-03-25
|
|
1018
|
+
// today, and any earlier one kept for redemption): bought with USDG, sold for USDG before maturity and redeemed 1:1 from it, through Pendle's router, with the calls sdk/pt-usdg.mjs builds (an approval of exactly the
|
|
1019
|
+
// trade's amount, then the router call paying the wallet itself, with a minimum out). Like borrow and save, this server
|
|
1020
|
+
// signs and sends them from the configured wallet (its own ETH pays the gas), one money call at a time; dry_run
|
|
1021
|
+
// returns the calls without sending. The chain, behind one facade (tests replace it).
|
|
1022
|
+
if (ptOn) {
|
|
1023
|
+
const pt = deps.pt || {
|
|
1024
|
+
quote: (o) => P.ptQuote(provider, o),
|
|
1025
|
+
position: (addr) => P.ptPosition(provider, addr),
|
|
1026
|
+
trade: (kind, o) => ({ buy: P.ptBuy, sell: P.ptSell, redeem: P.ptRedeem })[kind](provider, o),
|
|
1027
|
+
};
|
|
1028
|
+
const nf = (x) => Number(x).toLocaleString("en-US", { maximumFractionDigits: 6 });
|
|
1029
|
+
const capText = (u) => `${X.formatUsdg(u)} USDG`;
|
|
1030
|
+
const termsLine = (q) => (q.matured ? `PT-USDG matured on ${q.maturity.slice(0, 10)}: it redeems 1:1 for USDG.` : `PT-USDG trades at ${q.price.toFixed(6)} USDG and redeems 1:1 for USDG on ${q.maturity.slice(0, 10)} (${q.daysToMaturity} days): a fixed ${q.impliedApyText} a year to maturity, at the oracle's spot rate.`);
|
|
1031
|
+
// the wallet's PT of other listed markets (an earlier, redeem-only one): each with what to do with it
|
|
1032
|
+
const otherLines = (p) => (p.markets || []).filter((m) => m.token !== p.token && m.balance != null && m.balance > 0n).map((m) => (m.matured
|
|
1033
|
+
? `It also holds ${nf(m.balanceText)} PT-USDG of the market that matured on ${m.maturity.slice(0, 10)} (token ${m.token}): it redeems 1:1 for USDG now (pt_redeem with market ${m.market}).`
|
|
1034
|
+
: `It also holds ${nf(m.balanceText)} PT-USDG of an earlier market (token ${m.token}): it redeems 1:1 for USDG from ${m.maturity.slice(0, 10)}.`));
|
|
1035
|
+
const listingLine = (l) => (!l ? "The stock vault's listing could not be read just now."
|
|
1036
|
+
: l.backsLines ? `The Priors stock vault takes PT-USDG behind an agent's line now, at up to ${l.ltvBps / 100}% of its value (all PT-USDG lines share one ${capText(l.lineCap)} cap): deposit it with the SDK's openPtLine(agentId, amount) or in Go mode's Backing tab.`
|
|
1037
|
+
: l.listed ? "The Priors stock vault lists PT-USDG but takes no new line on it now (disabled, or the shared cap is used up)."
|
|
1038
|
+
: `The Priors stock vault does not list PT-USDG yet. Once it does, PT-USDG backs an agent's line (planned: up to ${l.planned.ltvBps / 100}% of its value, one ${capText(BigInt(l.planned.lineCap))} cap for all PT-USDG lines).`);
|
|
1039
|
+
const slippage = z.number().int().min(0).max(500).optional().describe("Slippage margin in basis points under the quote, 0 to 500. Default 100 (1%), 10 for a redemption.");
|
|
1040
|
+
const ptAmount = z.union([z.number().positive().max(10_000_000), z.literal("all")]).describe('PT-USDG, e.g. 25.5, or "all" for the wallet\'s whole balance.');
|
|
1041
|
+
const dryRun = z.boolean().optional().describe("true: only quote and list the calls, send nothing.");
|
|
1042
|
+
const asked = (e) => new ToolError(clean(e?.shortMessage || e?.message || String(e), 300));
|
|
1043
|
+
const callsText = (b) => b.calls.map((c, i) => `${i + 1}. ${c.what}: to ${c.to}, data ${c.data}`).join("\n");
|
|
1044
|
+
const minLine = (b) => `The router call names a minimum out of ${nf(b.quote.minOutText)} ${b.quote.tokenOut} (the quote ${nf(b.quote.expectedOutText)}, less ${b.quote.slippageBps / 100}%): it reverts rather than fill worse. The quote is the oracle's spot rate, before the trade's own price impact.`;
|
|
1045
|
+
|
|
1046
|
+
tool("pt_quote", {
|
|
1047
|
+
title: "Quote a PT-USDG trade",
|
|
1048
|
+
description: "Quote buying PT-USDG (Pendle's principal token for USDG on Robinhood Chain, redeemable 1:1 for USDG at its maturity) with USDG, selling it before maturity, or redeeming it after: what comes out at the oracle's spot rate, the minimum a trade would name, the days to maturity and the fixed APY a buyer locks in. Read-only.",
|
|
1049
|
+
inputSchema: { side: z.enum(["buy", "sell", "redeem"]).describe("buy: USDG in, PT-USDG out. sell: PT-USDG in, USDG out, before maturity. redeem: PT-USDG in, USDG out 1:1, from maturity."), amount: z.number().positive().max(10_000_000).describe("USDG to spend (buy), or PT-USDG to sell or redeem."), slippage_bps: slippage },
|
|
1050
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
1051
|
+
}, async ({ side, amount, slippage_bps }) => {
|
|
1052
|
+
let q;
|
|
1053
|
+
try { q = await pt.quote({ side, amount, slippageBps: slippage_bps }); } catch (e) { throw asked(e); }
|
|
1054
|
+
return [termsLine(q), `${nf(q.amountInText)} ${q.tokenIn} -> about ${nf(q.expectedOutText)} ${q.tokenOut} (at least ${nf(q.minOutText)} with a ${q.slippageBps / 100}% margin).`,
|
|
1055
|
+
side === "buy" ? `Held to maturity it pays ${nf(q.atMaturityText)} USDG, ${nf(q.fixedGainText)} USDG more than it costs.` : "",
|
|
1056
|
+
`pt_${side} ${side === "buy" ? `spends it from this server's wallet (at most ${capText(maxPtCeiling)} a call, PRIORS_MAX_PT_USD)` : "sends it from this server's wallet"}; dry_run: true lists the calls first.`].filter(Boolean).join("\n");
|
|
1057
|
+
});
|
|
1058
|
+
|
|
1059
|
+
tool("pt_position", {
|
|
1060
|
+
title: "A wallet's PT-USDG",
|
|
1061
|
+
description: "Show a wallet's PT-USDG on Robinhood Chain: its balance, what it is worth now at the oracle's spot rate, what it pays at maturity, the days left and the fixed APY to maturity; and whether the Priors stock vault takes PT-USDG behind an agent's line. Defaults to the configured wallet; any address works without a key. Read-only.",
|
|
1062
|
+
inputSchema: { address: z.string().optional().describe("0x address to check; default: the configured wallet.") },
|
|
1063
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
1064
|
+
}, async ({ address }) => {
|
|
1065
|
+
const addr = address ?? wallet?.address;
|
|
1066
|
+
if (!addr) throw new ToolError("No wallet is configured (PRIORS_KEY is not set): pass an address to check.");
|
|
1067
|
+
if (!ethers.isAddress(addr)) throw new ToolError(`not an address: ${clean(addr, 80)}`);
|
|
1068
|
+
let p;
|
|
1069
|
+
try { p = await pt.position(ethers.getAddress(addr)); } catch (e) { throw asked(e); }
|
|
1070
|
+
return [`${p.account}${wallet && p.account === wallet.address ? " (this server's wallet)" : ""} holds ${nf(p.balanceText)} PT-USDG${p.balance > 0n ? `, worth ${nf(p.valueText)} USDG now and ${nf(p.atMaturityText)} USDG at maturity` : ""}.`, termsLine(p), ...otherLines(p), listingLine(p.listing)].join("\n");
|
|
1071
|
+
});
|
|
1072
|
+
|
|
1073
|
+
/** One trade from the configured wallet: the SDK's calls, sent in order (each simulated, then waited for). */
|
|
1074
|
+
async function ptTrade(kind, amount, slippage_bps, dry_run, market) {
|
|
1075
|
+
const signer = needWallet(`pt_${kind}`);
|
|
1076
|
+
let units = null;
|
|
1077
|
+
if (kind === "buy") {
|
|
1078
|
+
units = dollars(amount, "amount_usdg");
|
|
1079
|
+
if (units === 0n) throw new ToolError("amount_usdg must be above zero");
|
|
1080
|
+
if (units > maxPtCeiling) throw new ToolError(`amount_usdg ${X.formatUsdg(units)} is above this server's ceiling of ${usd(maxPtCeiling)} per buy (PRIORS_MAX_PT_USD).`);
|
|
1081
|
+
if (!dry_run && session.ptBought + units > ptTotalCap) throw new ToolError(`this would bring what pt_buy spent in this session to ${usd(session.ptBought + units)}, above ${usd(ptTotalCap)} (PRIORS_MAX_PT_TOTAL_USD).`);
|
|
1082
|
+
}
|
|
1083
|
+
const o = { account: signer.address, amount: units ?? amount, slippageBps: slippage_bps, ...(market ? { market } : {}) };
|
|
1084
|
+
if (dry_run) {
|
|
1085
|
+
let b;
|
|
1086
|
+
try { b = await pt.trade(kind, o); } catch (e) { throw asked(e); }
|
|
1087
|
+
return [termsLine(b.quote), `Nothing was sent. From ${b.account}, ${b.calls.length} call${b.calls.length > 1 ? "s" : ""} in order:`, callsText(b), minLine(b), ...b.warnings.map((w) => `Note: ${w}.`)].join("\n");
|
|
1088
|
+
}
|
|
1089
|
+
// what left the wallet is counted even when the answer is lost: a send that started may have landed
|
|
1090
|
+
const sent = [];
|
|
1091
|
+
const counting = { getAddress: async () => signer.address, sendTransaction: async (tx) => { const r = await signer.sendTransaction(tx); sent.push(r.hash); return r; } };
|
|
1092
|
+
if (units !== null) session.ptBought += units;
|
|
1093
|
+
let r;
|
|
1094
|
+
try { r = await pt.trade(kind, { ...o, wallet: counting }); } catch (e) {
|
|
1095
|
+
if (sent.length === 0 && units !== null) session.ptBought -= units;
|
|
1096
|
+
if (sent.length) throw new ToolError(`${sent.length} transaction${sent.length > 1 ? "s were" : " was"} sent (${sent.join(", ")}), then: ${clean(e?.shortMessage || e?.message || String(e), 300)}. Check pt_position and wallet_balance before trying again.`);
|
|
1097
|
+
throw asked(e);
|
|
1098
|
+
}
|
|
1099
|
+
const done = kind === "buy" ? `Bought about ${nf(r.quote.expectedOutText)} PT-USDG (at least ${nf(r.quote.minOutText)}) with ${usd(units)}`
|
|
1100
|
+
: kind === "sell" ? `Sold ${nf(r.quote.amountInText)} PT-USDG for about ${nf(r.quote.expectedOutText)} USDG (at least ${nf(r.quote.minOutText)})`
|
|
1101
|
+
: `Redeemed ${nf(r.quote.amountInText)} PT-USDG for ${nf(r.quote.expectedOutText)} USDG`;
|
|
1102
|
+
return [`${done}, from and to ${r.account}. Tx ${r.hashes.join(", ")}.`, kind === "buy" ? termsLine(r.quote) : "", ...r.warnings.filter((w) => !/sponsorship/.test(w)).map((w) => `Note: ${w}.`)].filter(Boolean).join("\n");
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
tool("pt_buy", {
|
|
1106
|
+
title: "Buy PT-USDG with USDG",
|
|
1107
|
+
description: `Buy PT-USDG (Pendle's principal token for USDG, redeemable 1:1 for USDG on ${P.PT_USDG.maturity.slice(0, 10)}) with the configured wallet's USDG, through Pendle's router: an approval of exactly that USDG, then the swap, paying the PT-USDG to this wallet with a minimum out. Held to maturity it pays a fixed amount of USDG; sold earlier, it gets the market's rate then, which can be lower. Moves real money: quote it (pt_quote), state the amount and what it buys to the user and get their go-ahead first; dry_run: true lists the calls without sending. Needs ETH for gas.`,
|
|
1108
|
+
inputSchema: { amount_usdg: z.number().positive().describe("USDG to spend, in US dollars (required, no default)."), slippage_bps: slippage, dry_run: dryRun },
|
|
1109
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
1110
|
+
}, serial(async ({ amount_usdg, slippage_bps, dry_run }) => ptTrade("buy", amount_usdg, slippage_bps, dry_run)));
|
|
1111
|
+
|
|
1112
|
+
tool("pt_sell", {
|
|
1113
|
+
title: "Sell PT-USDG for USDG",
|
|
1114
|
+
description: "Sell the configured wallet's PT-USDG for USDG at the market, before maturity, through Pendle's router: an approval of exactly that PT-USDG, then the swap, paying the USDG to this wallet with a minimum out. Moves real money: quote it (pt_quote), state the amount to the user and get their go-ahead first; dry_run: true lists the calls without sending. Needs ETH for gas.",
|
|
1115
|
+
inputSchema: { amount_pt: ptAmount, slippage_bps: slippage, dry_run: dryRun },
|
|
1116
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
1117
|
+
}, serial(async ({ amount_pt, slippage_bps, dry_run }) => ptTrade("sell", amount_pt, slippage_bps, dry_run)));
|
|
1118
|
+
|
|
1119
|
+
tool("pt_redeem", {
|
|
1120
|
+
title: "Redeem PT-USDG for USDG",
|
|
1121
|
+
description: `Redeem the configured wallet's PT-USDG for USDG 1:1, from its maturity (${P.PT_USDG.maturity.slice(0, 10)}) on, through Pendle's router: an approval of exactly that PT-USDG, then the redemption to this wallet. By default the PT of the oldest matured market the wallet holds (an earlier market's included); \`market\` names one (pt_position lists them). Before maturity it says to sell instead. State the amount to the user and get their go-ahead first; dry_run: true lists the calls without sending. Needs ETH for gas.`,
|
|
1122
|
+
inputSchema: { amount_pt: ptAmount, slippage_bps: slippage, dry_run: dryRun, market: z.string().regex(/^0x[0-9a-fA-F]{40}$/).optional().describe("Optional: the market (or its PT) to redeem, as pt_position lists it. Default: the oldest matured market the wallet holds PT of.") },
|
|
1123
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
1124
|
+
}, serial(async ({ amount_pt, slippage_bps, dry_run, market }) => ptTrade("redeem", amount_pt, slippage_bps, dry_run, market)));
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1003
1127
|
// ---- find_services -------------------------------------------------------------------------------------------
|
|
1004
1128
|
tool("find_services", {
|
|
1005
1129
|
title: "Find services that accept USDG",
|