@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.
package/README.md CHANGED
@@ -2,15 +2,13 @@
2
2
 
3
3
  An MCP server that gives an AI assistant (Claude Desktop, Claude Code, or any MCP client) a USDG wallet on Robinhood
4
4
  Chain: pay x402-priced APIs, check balances, read any agent's [Priors](https://priors.trade) credit record, and
5
- borrow from and repay the agent's own Priors line.
5
+ borrow from and repay the agent's own Priors line, and keep its spare USDG saved in a Morpho vault until it needs it.
6
6
 
7
7
  ## Just reading? Use the hosted server
8
8
 
9
9
  No install and no key: `https://mcp.priors.trade/mcp` (Streamable HTTP) answers the read-only questions (an agent's
10
10
  record and score, the pool's figures, recent loans, the facilitator's services) from the same public data as
11
- priors.trade. It holds no key and cannot send a transaction. In hosts that render MCP Apps it shows a Priors view, and
12
- `request_borrow` / `request_repay` return two links where the agent's owner confirms the borrow or repayment: one in
13
- Go mode, one in the agent console on priors.trade for the wallet that owns the agent.
11
+ priors.trade. It holds no key and cannot send a transaction.
14
12
 
15
13
  ```bash
16
14
  claude mcp add --transport http priors https://mcp.priors.trade/mcp
@@ -23,20 +21,73 @@ repaying.
23
21
 
24
22
  | tool | what it does | needs the key |
25
23
  |---|---|---|
26
- | `pay_url(url, method?, body?, max_price_usd?, max_borrow_usd?)` | fetch an https URL, pay its x402 402 in USDG if the price is ≤ `max_price_usd` (default **$0.10**); borrows the gap only if `max_borrow_usd` is given. Refuses private and local addresses, never follows a redirect, answers within 45 s, and never signs a second payment for a purchase (the same method, URL and body) that is still pending, until its validBefore plus 60 s (a new call resends the same one, also after a restart, in a new session or from another session of the same wallet: see `PRIORS_STATE_DIR`) | yes |
24
+ | `pay_url(url, method?, body?, max_price_usd?, max_borrow_usd?, use_savings?)` | fetch an https URL, pay its x402 402 in USDG if the price is ≤ `max_price_usd` (default **$0.10**); once the 402 names the price, if the wallet is short it first takes the difference out of savings (unless `use_savings: false`), and borrows the gap only if `max_borrow_usd` is given. Refuses private and local addresses, never follows a redirect, answers within 45 s, and never signs a second payment for a purchase (the same method, URL and body) that is still pending, until its validBefore plus 60 s (a new call resends the same one, also after a restart, in a new session or from another session of the same wallet: see `PRIORS_STATE_DIR`) | yes |
27
25
  | `wallet_balance(address?)` | USDG and gas ETH of the wallet (or any address) | no (with `address`) |
28
26
  | `credit_status(agent_id?)` | line, drawn, available, backer, record, score, open loans and due dates; on a stock line, the stock tokens behind it, and `available` capped by what the stock vault lets it draw | no (with `agent_id`) |
29
27
  | `stock_assets(symbol?)` | the stock tokens the Priors stock vault accepts: live Chainlink price, whether it lends against each now (or why not: a sharp price move, a multiplier change, a paused or blocked token), loan-to-value | no |
30
28
  | `stock_position(agent_id?)` | the stock tokens behind an agent's stock line: amount, what the vault values them at, loan-to-value, what the line can draw now, any lending hold | no (with `agent_id`) |
31
29
  | `borrow(amount_usd, days, dry_run?)` | borrow USDG from the line into the wallet; both amounts required; `dry_run` quotes the fee. A borrow sent whose answer is lost is counted and said to be possibly open (check `credit_status`) | yes |
32
- | `repay(loan_id? \| all)` | repay one of the agent's own loans, or all of them earliest due first; another agent's loan is refused | yes |
30
+ | `repay(loan_id? \| all, use_savings?)` | repay one of the agent's own loans, or all of them earliest due first; another agent's loan is refused. If the wallet is short of what is due, it first takes the difference out of savings (unless `use_savings: false`) | yes |
31
+ | `savings(address?)` | what the wallet (or any address) has saved in the savings vault, how much can come out right now, and the USDG in the wallet | no (with `address`) |
32
+ | `save(amount_usd)` | move spare USDG from the wallet into the savings vault, where it earns the vault's rate (at most `PRIORS_MAX_SAVE_USD` per call, `PRIORS_MAX_SAVE_TOTAL_USD` per run); needs ETH for gas | yes |
33
+ | `unsave(amount_usd? \| all)` | take USDG back out of savings into the wallet: a normal withdrawal, and when that is not enough, the rest from the vault's other markets in the same transaction (only where that costs no penalty); refused before any transaction when even that cannot pay it; needs ETH for gas | yes |
34
+ | `autopay_on(cap_usd?, use_savings?, late?, budget_usd?)` | turn on Autopay: the wallet approves AutoRepay for a budget (4 x the limit per loan, never unlimited) and enrolls, so each loan is repaid from the wallet (then its savings, if chosen) in the 6 hours before it is due, with no call per loan, while the wallet holds enough. It makes an on-time repayment more likely; it is not a promise. Default limit: the line plus a 30-day fee, at most `PRIORS_MAX_AUTOPAY_USD`; call again to approve more. Works once AutoRepay is deployed; needs ETH for gas | yes |
35
+ | `autopay_off(clear_budget?)` | turn Autopay off (and with `clear_budget`, set the approvals to 0) | yes |
33
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 |
34
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 |
35
43
 
36
44
  Tools that move money state the amounts in their answer, are marked destructive for MCP clients, and their
37
45
  descriptions tell the assistant to confirm with you first. Merchant text (response bodies, listings, redirect targets)
38
46
  comes back between random `<<merchant-data …>>` markers, as data. They act on Robinhood Chain mainnet.
39
47
 
48
+ ## Savings
49
+
50
+ Spare USDG doesn't have to sit idle. `save` puts it in a Morpho vault (Steakhouse USDG by default, a Morpho Vault V2
51
+ curated by Steakhouse Financial), where it earns the vault's rate. When the agent has to pay (`pay_url`) or repay
52
+ (`repay`) and its wallet is short, the server takes the difference back out first, and only then borrows. That makes
53
+ an on-time repayment more likely; it does not guarantee one: savings come out only while the vault's markets have
54
+ liquidity.
55
+
56
+ It is the agent's own money in someone else's vault: Priors never holds it, and the saver carries the vault's risks: a
57
+ loss in one of its markets lowers the share value at once; its curator and allocators choose the markets and some
58
+ settings change with no timelock; liquidity can be lent out; USDG's issuer can freeze addresses. The rate moves with
59
+ Morpho's markets. How money goes in and comes out: the Savings section of
60
+ [@priors/x402's README](https://www.npmjs.com/package/@priors/x402).
61
+
62
+ How the server handles it: the vault must be a contract whose asset is USDG; `save` checks the vault's deposit gate
63
+ before approving, and approves the amount only when the current allowance is lower; every vault transaction is sent
64
+ with a gas margin; what can come out is found by simulating the withdrawal (Morpho Vault V2 answers 0 to `maxWithdraw`
65
+ by design). A failed top-up never stops a payment or repayment, and the answer says what happened.
66
+
67
+ A top-up is bounded by the call's own time. When time runs out it stops before sending anything; if a withdrawal
68
+ was already sent and has not confirmed, `pay_url` neither borrows nor signs, says so, and the next money call waits
69
+ for that withdrawal. `save` keeps the USDG that signed, unsettled payments still need.
70
+
71
+ `PRIORS_SAVINGS_VAULT=off` stops `save` and the automatic top-ups, not the way out: `savings` and `unsave` keep working
72
+ on the default vault. Pointing `PRIORS_SAVINGS_VAULT` at another vault means trusting that vault (the only check is a
73
+ contract whose asset is USDG); money saved in the default one stays there, and money saved in a custom one is reached
74
+ by setting that vault again.
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
+
40
91
  ## Configure
41
92
 
42
93
  The only secret is the wallet key, and it is read from the environment variable `PRIORS_KEY`, never from the command
@@ -56,6 +107,16 @@ dedicated agent wallet holding only what the agent may spend.
56
107
  | `PRIORS_ALLOW_LOCAL` | off | `1` lets `pay_url` reach `http://localhost` and private addresses (local testing only) |
57
108
  | `PRIORS_SCORE_V2` | `https://priors.trade/api/score-v2` | where `score_of` reads Priors Score v2; `off` shows the on-chain score only |
58
109
  | `PRIORS_STOCK_VAULT` | the bundled deployments file's `stockVault` | the stock vault the stock tools and `credit_status` read |
110
+ | `PRIORS_SAVINGS_VAULT` | Steakhouse USDG on Morpho (`0xBeEff033F34C046626B8D0A041844C5d1A5409dd`) | the USDG vault savings go to; `off` (or `false`, `0`, `no`) stops `save` and the automatic top-ups, while `savings` and `unsave` keep working on the default vault. Its value is never echoed |
111
+ | `PRIORS_MAX_SAVE_USD` | `50` | most one `save` call may move into the vault |
112
+ | `PRIORS_MAX_SAVE_TOTAL_USD` | `200` | most `save` may move in total while the server runs |
113
+ | `PRIORS_AUTOREPAY` | the bundled deployments file's `autoRepay` (none until AutoRepay v2 is deployed) | AutoRepay v2's address, for `autopay_on`, `autopay_off` and the Autopay lines of `credit_status`; AutoRepay v1 (retired before use) is refused |
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 |
115
+ | `PRIORS_MAX_AUTOPAY_USD` | `25` | the most `autopay_on` enrolls per loan (stage 0) |
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) |
59
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 |
60
121
 
61
122
  Contract addresses (pool, lens, registry, USDG) come from `deployments/4663.v2.json`, bundled in the package, and the
@@ -71,7 +132,7 @@ Settings → Developer → Edit Config (`claude_desktop_config.json`), then rest
71
132
  "mcpServers": {
72
133
  "priors": {
73
134
  "command": "npx",
74
- "args": ["-y", "@priors/mcp@0.2.11"],
135
+ "args": ["-y", "@priors/mcp@0.6.0"],
75
136
  "env": {
76
137
  "PRIORS_KEY": "0xYOUR_AGENT_WALLET_KEY",
77
138
  "PRIORS_AGENT_ID": "1234"
@@ -93,7 +154,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
93
154
  "mcpServers": {
94
155
  "priors": {
95
156
  "command": "npx",
96
- "args": ["-y", "@priors/mcp@0.2.11"],
157
+ "args": ["-y", "@priors/mcp@0.6.0"],
97
158
  "env": {
98
159
  "PRIORS_KEY": "${PRIORS_KEY}",
99
160
  "PRIORS_AGENT_ID": "${PRIORS_AGENT_ID:-}"
@@ -103,7 +164,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
103
164
  }
104
165
  ```
105
166
 
106
- or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.2.11`
167
+ or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.6.0`
107
168
  (the key is expanded by your shell from the environment; do not paste it on the command line).
108
169
 
109
170
  ## Try it
@@ -111,6 +172,7 @@ or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIO
111
172
  "What's the Priors score of agent 6228?" · "How much USDG does my wallet hold?" · "Find services that sell token
112
173
  prices" · "Pay https://api.example.com/report, up to 5 cents" · "Borrow $5 for 7 days, show me the fee first".
113
174
 
114
- ## Source
175
+ ## Tests
115
176
 
116
- [github.com/priors-agents/priors](https://github.com/priors-agents/priors/tree/main/packages/mcp), MIT.
177
+ `npm run test:packages` in the Priors repository lists and calls every tool through the MCP SDK's in-memory client and
178
+ over stdio, and checks that the key never appears in any output or error.
@@ -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_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) {
@@ -29,5 +29,8 @@
29
29
  "seatVaultV4AgentId": 6466,
30
30
  "seatVaultV4Block": 75614831,
31
31
  "seatSizerV4": "0x97C4e594D458f8BBE961d5384Bbd8a9Cc2D18777",
32
- "seatSizerV4Block": 75614955
32
+ "seatSizerV4Block": 75614955,
33
+ "autoRepayV1": "0x765f51Bd38404154762f2822d3ac5d16CE9AF822",
34
+ "autoRepayV1Block": 79616581,
35
+ "autoRepayV1Note": "AutoRepay v1: retired before use, never enrolled, no allowance. Replaced by AutoRepay v2, recorded here as autoRepay and autoRepayBlock once deployed. Kept so the score mapping recognises both; nothing else uses it."
33
36
  }
@@ -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.2.11",
4
+ "version": "0.6.0",
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
- "@priors/x402": "0.2.11",
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
+ }