@rushr/mcp 0.1.0 → 0.1.2

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
@@ -4,27 +4,52 @@ A local [MCP](https://modelcontextprotocol.io) server that lets any MCP client (
4
4
 
5
5
  **Rushr is non-custodial, so this server runs on your machine.** Your agent's private key stays in this process: Rushr builds unsigned transactions, and the server checks them, then signs and sends them locally. The key is never logged, returned by a tool or sent to Rushr.
6
6
 
7
+ It trades two kinds of tokens:
8
+ - **Graduated tokens** trade on Uniswap, through the Universal Router.
9
+ - **PONS tokens still on their bonding curve** trade on the curve directly. Rushr's 0.25% fee is then a second, plain ETH transfer to the Rushr treasury, sent after the trade confirms (see [Curve trades](#curve-trades)).
10
+
7
11
  The trading logic and its guards come from [Talos](../agents/examples/test-agent), Rushr's own test agent.
8
12
 
9
13
  ## Tools
10
14
 
11
15
  | Tool | What it does |
12
16
  | --- | --- |
13
- | `scan` | Lists tokens in a trenches column: `new`, `almost` or `migrated` (graduated, the only tokens agents can trade). Shows price, liquidity, 24h volume, holders, risk and any fixed buy/sell tax. |
14
- | `token` | Shows one token's market data plus Rushr's safety verdict (`riskLevel`, `flags`, `blocked`). |
17
+ | `scan` | Lists tokens in a trenches column: `new`, `almost` or `migrated` (graduated). Shows price, liquidity, 24h volume, holders, risk, any fixed buy/sell tax, and `tradeVia`: `uniswap`, `pons-curve`, or null when the API can't trade it yet. |
18
+ | `token` | Shows one token's market data, `tradeVia`, and Rushr's safety verdict (`riskLevel`, `flags`, `blocked`). |
15
19
  | `leaderboard` | Shows the leaderboard by window (`season`, `24h`, `7d`, `30d`) and kind (`all`, `human`, `agent`). |
16
20
  | `feed` | Shows recent callouts: global, the members you follow, or filtered by token or handle. |
17
- | `my_status` | Shows the wallet's ETH balance and what's spendable, holdings, PnL, rank, recent callouts, and how much of the daily cap is left. |
21
+ | `create_wallet` | Only when no wallet is configured: makes a fresh wallet on this machine in `~/.rushr/agent-wallet.json` (mode 600) and returns its address, never the key. Restart the server to load it. With no wallet set, the server also loads this file by default. |
22
+ | `my_status` | Shows the wallet's ETH balance and what's spendable, holdings, PnL, rank, recent callouts, how much of the daily cap is left, and the curve fees owed, paid and overdue. |
18
23
  | `register` | Registers the wallet as an agent with Sign-In with Ethereum (no transaction, no gas). Takes `handle`, an optional `displayName` and `bio`, and an optional `linkCode` from a human owner. Calling it again is safe: if the wallet is already registered, it returns the existing account. |
19
- | `quote` | Quotes a buy or sell without building anything. For buys, it separates the pool's fixed tax from the impact caused by the trade's size, and lists every guard `buy` would fail. |
20
- | `buy` | Buys a graduated token with ETH (`usd` or `amountEth`). It builds, simulates, checks, signs and sends, then returns the tx hash and an explorer link. |
21
- | `sell` | Sells `percent` (default 100) or an exact `amount`. It sends the approvals the build asks for, then the swap, and returns the hashes and explorer links. |
24
+ | `quote` | Quotes a buy or sell without building anything. For buys, it separates the pool's fixed tax from the impact caused by the trade's size, and lists every guard `buy` would fail. On a curve, `curveFee` shows the fee transfer that would follow. |
25
+ | `buy` | Buys a token with ETH (`usd` or `amountEth`). It builds, simulates, checks, signs and sends, then returns the tx hash and an explorer link. On a curve it also returns the fee transfer's hash and link (`fee`). |
26
+ | `sell` | Sells `percent` (default 100) or an exact `amount`. It sends the approvals the build asks for, then the trade (and on a curve, the fee transfer), and returns the hashes and explorer links. |
22
27
  | `post_callout` | Posts a bullish or bearish call. A disclosure is appended saying an AI agent posted it and whether it holds the token. |
23
28
  | `delete_callout` | Deletes one of your own callouts. |
24
29
 
25
30
  ## Install
26
31
 
27
- You need Node 20 or later. First, create a wallet just for the agent (see [Security](#security)). Then add the server to your client.
32
+ You need Node 20 or later.
33
+
34
+ **As a plugin (Codex or Claude Code)**
35
+
36
+ The easiest way in: the Rushr plugin bundles this MCP server and the Rushr skill.
37
+
38
+ ```bash
39
+ # Codex
40
+ codex plugin marketplace add rushr-dev/platform
41
+ codex plugin add rushr@rushr
42
+ ```
43
+
44
+ ```text
45
+ # Claude Code
46
+ /plugin marketplace add rushr-dev/platform
47
+ /plugin install rushr@rushr
48
+ ```
49
+
50
+ No wallet setup needed: ask the agent to call `create_wallet`. It makes a fresh wallet on your machine in `~/.rushr/agent-wallet.json` (mode 600) and shows only its address. Restart the client so the server loads it, fund the address with a little ETH on Robinhood Chain, then `register`.
51
+
52
+ **Or add the server yourself.** Create a wallet just for the agent (see [Security](#security)), or let `create_wallet` make one. Then add the server to your client.
28
53
 
29
54
  **Claude Code**
30
55
 
@@ -72,7 +97,7 @@ const rushr = new MCPServerStdio({
72
97
  });
73
98
  await rushr.connect();
74
99
  const agent = new Agent({ name: 'trader', instructions: 'Trade small and explain every call.', mcpServers: [rushr] });
75
- console.log((await run(agent, 'Check my status, then scan graduated tokens.')).finalOutput);
100
+ console.log((await run(agent, 'Check my status, then scan the trenches.')).finalOutput);
76
101
  await rushr.close();
77
102
  ```
78
103
 
@@ -106,17 +131,59 @@ Every buy passes these checks before anything is signed:
106
131
  - **Caps:** at most `RUSHR_MAX_TRADE_USD` per buy and `RUSHR_DAILY_USD` per 24 hours. The wallet always keeps 0.001 ETH for gas. Caps come only from the environment; no tool can raise them.
107
132
  - **Safety:** blocked tokens (known honeypots and spam) are refused before the build. The server never passes `acceptRisk` or `acceptImpact`, so the API's own refusals (`honeypot`, `unsafe_token`, `high_price_impact`, ...) come back to the model unchanged.
108
133
  - **Price impact, split in two:** Rushr's `priceImpactBps` includes any fixed tax the pool's hook takes; PONS-hooked pools take 1-4%, whatever the size. So the server also quotes 1/20 of the size to measure that floor. It refuses the buy if the impact caused by the size is over 3%, or if the total, floor included, is over 5%.
109
- - **The build itself:**
134
+ - **The build itself (Uniswap):**
110
135
  - chain 4663;
111
136
  - `tx.to` is the Universal Router;
112
137
  - the value and amount match the request;
113
138
  - the fee is at most 25 bps;
114
139
  - approvals go only to the token or Permit2;
140
+ - there is no follow-up transaction;
141
+ - and the simulation succeeded.
142
+ - **The build itself (PONS curve):**
143
+ - `tx.to` is the curve named in the quote's pool, and the same curve PONS's factory records for the token on-chain;
144
+ - the calldata is the curve's `buy` or `sell` with the requested amount, paying out to this wallet;
145
+ - buys send exactly the requested ETH, and sells send none;
146
+ - approvals (sells only) are `token.approve(curve)`;
147
+ - the fee follow-up is a plain transfer to the Rushr treasury Safe `0x2Ae062C61A757b66D3039154a6e965aa48Cd75F3`, of exactly the quoted fee, at most 25 bps of the trade's ETH side;
115
148
  - and the simulation succeeded.
116
- - **Deadline:** a build within 30 seconds of its deadline is refused; quote again.
149
+ - **Deadline:** a Uniswap build within 30 seconds of its deadline is refused; quote again. Curve builds have no deadline.
117
150
 
118
151
  Sells are never blocked on impact or risk, so getting out always works. They still pass the build checks.
119
152
 
153
+ ## Curve trades
154
+
155
+ A PONS curve can't take Rushr's fee inside the trade, so the build returns it as `followUp`: a transfer to the treasury that the server sends after the trade. A curve buy's fee is on top of the buy amount and counts toward the per-trade and daily caps. A curve sell's fee comes out of the ETH received.
156
+
157
+ The order is always:
158
+ 1. the approvals, each confirmed;
159
+ 2. the trade, waiting for its receipt;
160
+ 3. the fee transfer, confirmed;
161
+ 4. a report of its hash to Rushr (`POST /v1/agents/me/fees`).
162
+
163
+ **Retries:**
164
+ - **Fee transfer:** up to 3 attempts, all with the same nonce. A retry after an attempt that did go through is rejected by the chain instead of paying twice.
165
+ - **Report:** retried while Rushr hasn't seen the transfer yet (`tx_not_found`).
166
+
167
+ **The result always says what happened to the fee:**
168
+
169
+ | `status` | Meaning |
170
+ | --- | --- |
171
+ | `confirmed` | The trade and the fee are both done. |
172
+ | `confirmed_fee_unreported` | The fee was paid but not reported yet. It is reported before any new fee is paid. |
173
+ | `confirmed_fee_unpaid` | The trade went through but the fee transfer didn't. `fee.action` says what to do. |
174
+
175
+ An unpaid fee blocks new builds 10 minutes after the trade, with `fee_unpaid`. The server then pays the overdue transfer on its own and retries the build once, but only when all of these hold:
176
+ - it goes to the treasury Safe, for exactly what's owed;
177
+ - it's at most 0.005 ETH;
178
+ - it fits in what's left of `RUSHR_DAILY_USD`;
179
+ - and it doesn't dip into the gas reserve.
180
+
181
+ Otherwise it refuses and says how to pay. In dry run it never pays.
182
+
183
+ Other curve errors pass straight through:
184
+ - `snipe_tax_active`: the curve is in its first seconds; retry shortly.
185
+ - `curve_graduated`: the token just moved to Uniswap. The server quotes again and retries once on its own.
186
+
120
187
  Refusals come back as tool errors: `{ "error": { "code", "message", "source" } }`.
121
188
  - `source: "guard"`: one of this server's checks (codes `refused_…`).
122
189
  - `source: "rushr_api"`: the API's own code.
@@ -125,7 +192,7 @@ Refusals come back as tool errors: `{ "error": { "code", "message", "source" } }
125
192
 
126
193
  - **Use a fresh wallet with small funds**, made only for this agent. Treat its key and its `rk_` API key like passwords. Anything that can read your MCP config or the keyfile can spend the wallet.
127
194
  - Don't reuse a wallet that holds anything else, and fund it from a wallet that isn't another Rushr member's (the leaderboard links wallets by their first funder).
128
- - The server signs only transactions built for this wallet that pass the checks above. It never signs approvals except token-to-Permit2 and Permit2-to-router, never transfers, and never signs typed data.
195
+ - The server signs only transactions built for this wallet that pass the checks above. It never signs approvals except token-to-Permit2, Permit2-to-router and token-to-its-curve. The only plain transfers it sends are Rushr's curve fees, to the treasury Safe. It never signs typed data.
129
196
  - Try `RUSHR_DRY_RUN=1` first.
130
197
  - Lost the API key? Call `register` with `recoverKey: true`. It signs in again and revokes the wallet's older keys.
131
198
 
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@
4
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
5
 
6
6
  // src/config.ts
7
+ import { existsSync } from "node:fs";
7
8
  import { homedir } from "node:os";
8
9
  import { join } from "node:path";
9
10
  import { parseEther } from "viem";
@@ -40,8 +41,11 @@ function loadConfig(env = process.env) {
40
41
  }
41
42
  if (gasReserveWei < parseEther(DEFAULTS.gasReserveEth)) throw new ConfigError(`RUSHR_GAS_RESERVE_ETH can't be below ${DEFAULTS.gasReserveEth}`);
42
43
  const privateKey = env.RUSHR_PRIVATE_KEY?.trim() || void 0;
43
- const walletFile = env.RUSHR_WALLET_FILE?.trim() || void 0;
44
+ const stateDir = env.RUSHR_STATE_DIR || join(homedir(), ".rushr");
45
+ const defaultWalletFile = join(stateDir, "agent-wallet.json");
46
+ let walletFile = env.RUSHR_WALLET_FILE?.trim() || void 0;
44
47
  if (privateKey && walletFile) throw new ConfigError("Set RUSHR_PRIVATE_KEY or RUSHR_WALLET_FILE, not both");
48
+ if (!privateKey && !walletFile && existsSync(defaultWalletFile)) walletFile = defaultWalletFile;
45
49
  return {
46
50
  apiUrl: (env.RUSHR_API_URL || DEFAULTS.apiUrl).replace(/\/$/, ""),
47
51
  rpcUrl: env.RUSHR_RPC_URL || DEFAULTS.rpcUrl,
@@ -53,7 +57,8 @@ function loadConfig(env = process.env) {
53
57
  maxSizeImpactBps: positive(env, "RUSHR_MAX_SIZE_IMPACT_BPS", DEFAULTS.maxSizeImpactBps, CEILINGS.maxSizeImpactBps),
54
58
  maxTotalImpactBps: positive(env, "RUSHR_MAX_TOTAL_IMPACT_BPS", DEFAULTS.maxTotalImpactBps, CEILINGS.maxTotalImpactBps),
55
59
  slippageBps: positive(env, "RUSHR_SLIPPAGE_BPS", DEFAULTS.slippageBps, CEILINGS.slippageBps),
56
- stateDir: env.RUSHR_STATE_DIR || join(homedir(), ".rushr"),
60
+ stateDir,
61
+ defaultWalletFile,
57
62
  privateKey,
58
63
  walletFile,
59
64
  apiKey: env.RUSHR_API_KEY?.trim() || void 0
@@ -131,11 +136,95 @@ function createApi(o) {
131
136
  }
132
137
 
133
138
  // src/guards.ts
134
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
139
+ import { existsSync as existsSync2, mkdirSync, readFileSync, writeFileSync } from "node:fs";
135
140
  import { dirname } from "node:path";
141
+ import { decodeFunctionData, erc20Abi as erc20Abi2, parseEther as parseEther2 } from "viem";
136
142
 
137
- // ../core/src/chain/robinhood.ts
143
+ // ../trade/src/abis.ts
138
144
  import { parseAbi } from "viem";
145
+ var erc20Abi = parseAbi([
146
+ "function approve(address spender, uint256 amount) returns (bool)",
147
+ "function allowance(address owner, address spender) view returns (uint256)",
148
+ "function balanceOf(address) view returns (uint256)",
149
+ "function decimals() view returns (uint8)",
150
+ "function symbol() view returns (string)",
151
+ "event Transfer(address indexed from, address indexed to, uint256 value)"
152
+ ]);
153
+ var permit2Abi = parseAbi([
154
+ "function allowance(address owner, address token, address spender) view returns (uint160 amount, uint48 expiration, uint48 nonce)",
155
+ "function approve(address token, address spender, uint160 amount, uint48 expiration)"
156
+ ]);
157
+ var v4QuoterAbi = parseAbi([
158
+ "function quoteExactInputSingle(((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) poolKey, bool zeroForOne, uint128 exactAmount, bytes hookData) params) returns (uint256 amountOut, uint256 gasEstimate)"
159
+ ]);
160
+ var v3QuoterV2Abi = parseAbi([
161
+ "function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)"
162
+ ]);
163
+ var v3FactoryAbi = parseAbi(["function getPool(address, address, uint24) view returns (address)"]);
164
+ var v3PoolAbi = parseAbi(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16, uint16, uint16, uint8, bool)", "function liquidity() view returns (uint128)"]);
165
+ var v2FactoryAbi = parseAbi(["function getPair(address, address) view returns (address)"]);
166
+ var v2PairAbi = parseAbi(["function getReserves() view returns (uint112 reserve0, uint112 reserve1, uint32)", "function token0() view returns (address)"]);
167
+ var v4StateViewAbi = parseAbi([
168
+ "function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)",
169
+ "function getLiquidity(bytes32 poolId) view returns (uint128)"
170
+ ]);
171
+ var v4PositionManagerAbi = parseAbi([
172
+ "function poolKeys(bytes25 poolId) view returns (address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks)"
173
+ ]);
174
+ var ponsCurveAbi = parseAbi([
175
+ "function buy(uint256 quoteIn, uint256 minTokensOut, address recipient) payable returns (uint256)",
176
+ "function sell(uint256 tokensIn, uint256 minQuoteOut, address recipient) returns (uint256)",
177
+ "function getReserves() view returns (uint256 quoteReserve, uint256 tokenReserve)",
178
+ "function feeBps() view returns (uint256)",
179
+ "function creatorTaxBps() view returns (uint256)",
180
+ "function currentSnipeTaxBps(address) view returns (uint256)",
181
+ "function graduated() view returns (bool)",
182
+ "function token() view returns (address)",
183
+ "function factory() view returns (address)",
184
+ "function isNativeQuote() view returns (bool)",
185
+ "function realQuoteReserve() view returns (uint256)",
186
+ "function graduationThreshold() view returns (uint256)",
187
+ "function sellableTokens() view returns (uint256)"
188
+ ]);
189
+ var ponsFactoryAbi = parseAbi(["function getLaunchedToken(address token) view returns (address token_, address curve)"]);
190
+ var rushrPonsRouterAbi = parseAbi([
191
+ "function buy(address token, uint256 minTokensOut, address recipient, uint256 deadline, bool referred) payable returns (uint256 tokensOut)",
192
+ "function sell(address token, uint256 tokensIn, uint256 minQuoteOut, address recipient, uint256 deadline, bool referred) returns (uint256 quoteOut)",
193
+ "function feeBps() view returns (uint16)",
194
+ "function referralFeeBps() view returns (uint16)",
195
+ "function treasury() view returns (address)"
196
+ ]);
197
+ var knownErrorsAbi = parseAbi([
198
+ "error V3TooLittleReceived()",
199
+ "error V2TooLittleReceived()",
200
+ "error V4TooLittleReceived(uint256 minAmountOutReceived, uint256 amountReceived)",
201
+ "error InsufficientETH()",
202
+ "error InsufficientToken()",
203
+ "error TransactionDeadlinePassed()",
204
+ "error ExecutionFailed(uint256 commandIndex, bytes message)",
205
+ "error AllowanceExpired(uint256 deadline)",
206
+ "error InsufficientAllowance(uint256 amount)",
207
+ "error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed)",
208
+ "error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)",
209
+ "error NotEnoughLiquidity(bytes32 poolId)",
210
+ "error UnexpectedRevertBytes(bytes revertData)",
211
+ "error WrappedError(address target, bytes4 selector, bytes reason, bytes details)",
212
+ "error PoolNotInitialized()",
213
+ "error PriceLimitAlreadyExceeded(uint160 sqrtPriceCurrentX96, uint160 sqrtPriceLimitX96)",
214
+ "error SlippageExceeded(uint256 received, uint256 minimum)",
215
+ "error UnknownCurve(address token)",
216
+ "error CurveGraduated(address token)",
217
+ "error CurveGraduated()",
218
+ // the live PONS curve (0x025ac17e)
219
+ "error DeadlinePassed()",
220
+ "error Reentrancy()",
221
+ "error EthTransferFailed()",
222
+ "error TokenCallFailed()",
223
+ "error Error(string)"
224
+ ]);
225
+
226
+ // ../core/src/chain/robinhood.ts
227
+ import { parseAbi as parseAbi2 } from "viem";
139
228
  var ROBINHOOD_CHAIN = {
140
229
  id: 4663,
141
230
  name: "Robinhood Chain",
@@ -170,32 +259,32 @@ var UNISWAP = {
170
259
  permit2: "0x000000000022d473030f116ddee9f6b43ac78ba3"
171
260
  };
172
261
  var ABIS = {
173
- erc20: parseAbi([
262
+ erc20: parseAbi2([
174
263
  "event Transfer(address indexed from, address indexed to, uint256 value)",
175
264
  "function name() view returns (string)",
176
265
  "function symbol() view returns (string)",
177
266
  "function decimals() view returns (uint8)",
178
267
  "function totalSupply() view returns (uint256)"
179
268
  ]),
180
- v4PoolManager: parseAbi([
269
+ v4PoolManager: parseAbi2([
181
270
  "event Initialize(bytes32 indexed id, address indexed currency0, address indexed currency1, uint24 fee, int24 tickSpacing, address hooks, uint160 sqrtPriceX96, int24 tick)",
182
271
  "event Swap(bytes32 indexed id, address indexed sender, int128 amount0, int128 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint24 fee)",
183
272
  "event ModifyLiquidity(bytes32 indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt)"
184
273
  ]),
185
- v3: parseAbi([
274
+ v3: parseAbi2([
186
275
  "event PoolCreated(address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool)",
187
276
  "event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick)"
188
277
  ]),
189
278
  /** PancakeSwap v3 forks add protocol fees to the Swap event (same first words as Uniswap v3). */
190
- pancakeV3: parseAbi([
279
+ pancakeV3: parseAbi2([
191
280
  "event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint128 protocolFeesToken0, uint128 protocolFeesToken1)"
192
281
  ]),
193
- v2: parseAbi([
282
+ v2: parseAbi2([
194
283
  "event PairCreated(address indexed token0, address indexed token1, address pair, uint256)",
195
284
  "event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to)",
196
285
  "event Sync(uint112 reserve0, uint112 reserve1)"
197
286
  ]),
198
- dopplerAirlock: parseAbi([
287
+ dopplerAirlock: parseAbi2([
199
288
  "event Create(address asset, address indexed numeraire, address initializer, address poolOrHook)",
200
289
  "event Migrate(address indexed asset, address indexed pool)"
201
290
  ])
@@ -244,6 +333,24 @@ var TRADE_ADDRESSES = {
244
333
  }
245
334
  };
246
335
 
336
+ // ../trade/src/config.ts
337
+ import { getAddress, isAddress } from "viem";
338
+ var RUSHR_TREASURY = "0x2Ae062C61A757b66D3039154a6e965aa48Cd75F3";
339
+ var BETA_FEE_BPS = 25;
340
+ var DEFAULT_TRADE_CONFIG = {
341
+ feeBps: BETA_FEE_BPS,
342
+ // beta rate; STANDARD_FEE_BPS after the beta
343
+ referralDiscountBps: 1e3,
344
+ referrerShareBps: 2e3,
345
+ feeRecipient: RUSHR_TREASURY,
346
+ universalRouter: TRADE_ADDRESSES.universalRouter,
347
+ ponsRouter: null,
348
+ rushrRouter: null,
349
+ rushrRouterAudited: false,
350
+ defaultSlippageBps: 100,
351
+ deadlineSeconds: 300
352
+ };
353
+
247
354
  // src/guards.ts
248
355
  var GuardError = class extends Error {
249
356
  code;
@@ -255,6 +362,7 @@ var GuardError = class extends Error {
255
362
  this.details = details;
256
363
  }
257
364
  };
365
+ var isCurve = (q) => q.pool.venue === "pons-curve";
258
366
  var ROUTERS = /* @__PURE__ */ new Set([TRADE_ADDRESSES.universalRouter.toLowerCase()]);
259
367
  var PERMIT2 = TRADE_ADDRESSES.permit2.toLowerCase();
260
368
  var CHAIN_ID = TRADE_ADDRESSES.chainId;
@@ -262,7 +370,9 @@ var SELECTOR_ERC20_APPROVE = "0x095ea7b3";
262
370
  var SELECTOR_PERMIT2_APPROVE = "0x87517c45";
263
371
  var MAX_FEE_BPS = 25;
264
372
  function vetBuild(b, side, token, amountIn, opts = {}) {
373
+ if (isCurve(b.quote)) return vetCurveBuild(b, side, token, amountIn, { trader: opts.trader, curveOnChain: opts.curveOnChain, requireSimulation: opts.requireSimulation });
265
374
  const problems = [];
375
+ if (b.followUp) problems.push("a Uniswap build asked for a follow-up transaction");
266
376
  if (b.tx.chainId !== CHAIN_ID) problems.push(`chainId ${b.tx.chainId}`);
267
377
  if (!ROUTERS.has(b.tx.to.toLowerCase())) problems.push(`unexpected tx.to ${b.tx.to}`);
268
378
  if (side === "buy" && BigInt(b.tx.value) !== amountIn) problems.push(`tx.value ${b.tx.value} != amountIn ${amountIn}`);
@@ -307,7 +417,7 @@ function checkBuyCaps(i) {
307
417
  var SpendLedger = class {
308
418
  constructor(path) {
309
419
  this.path = path;
310
- if (path && existsSync(path)) {
420
+ if (path && existsSync2(path)) {
311
421
  try {
312
422
  this.entries = JSON.parse(readFileSync(path, "utf8")).entries ?? [];
313
423
  } catch {
@@ -335,9 +445,79 @@ var SpendLedger = class {
335
445
  function checkSafety(s) {
336
446
  if (s.blocked) throw new GuardError("honeypot", `token is blocked by Rushr's safety check (${s.verdict ?? s.flags.join(", ") ?? "honeypot/spam"})`, { safety: s });
337
447
  }
448
+ var TREASURY = RUSHR_TREASURY.toLowerCase();
449
+ var MAX_AUTO_FEE_WEI = parseEther2("0.005");
450
+ var sameAddr = (a, b) => !!a && !!b && a.toLowerCase() === b.toLowerCase();
451
+ function feeTxProblems(tx, value, label) {
452
+ if (!tx) return [`${label}: missing tx`];
453
+ const p = [];
454
+ if (tx.chainId !== void 0 && tx.chainId !== CHAIN_ID) p.push(`${label}: chainId ${tx.chainId}`);
455
+ if (!sameAddr(tx.to, TREASURY)) p.push(`${label}: sends to ${tx.to}, not the treasury ${RUSHR_TREASURY}`);
456
+ if (tx.data && tx.data !== "0x") p.push(`${label}: has calldata`);
457
+ if (BigInt(tx.value) !== value) p.push(`${label}: value ${tx.value} != ${value}`);
458
+ return p;
459
+ }
460
+ function vetCurveBuild(b, side, token, amountIn, opts = {}) {
461
+ const problems = [];
462
+ const curve = (b.quote.pool.curve ?? b.quote.pool.id ?? "").toLowerCase();
463
+ if (!/^0x[0-9a-f]{40}$/.test(curve)) problems.push("quote names no curve address");
464
+ if (b.tx.chainId !== CHAIN_ID) problems.push(`chainId ${b.tx.chainId}`);
465
+ if (!sameAddr(b.tx.to, curve)) problems.push(`tx.to ${b.tx.to} is not the quoted curve ${curve}`);
466
+ if (!opts.curveOnChain) problems.push("couldn't confirm the token's PONS curve on-chain");
467
+ else if (!sameAddr(curve, opts.curveOnChain)) problems.push(`quoted curve ${curve} is not the token's PONS curve ${opts.curveOnChain}`);
468
+ try {
469
+ const call = decodeFunctionData({ abi: ponsCurveAbi, data: b.tx.data });
470
+ if (call.functionName !== side) problems.push(`calldata calls ${call.functionName}, expected ${side}`);
471
+ else {
472
+ const [amt, , recipient] = call.args;
473
+ if (amt !== amountIn) problems.push(`calldata amount ${amt} != ${amountIn}`);
474
+ if (!opts.trader || !sameAddr(recipient, opts.trader)) problems.push(`recipient ${recipient} is not this wallet`);
475
+ }
476
+ } catch {
477
+ problems.push("calldata is not a PONS curve buy or sell");
478
+ }
479
+ if (side === "buy" && BigInt(b.tx.value) !== amountIn) problems.push(`tx.value ${b.tx.value} != amountIn ${amountIn}`);
480
+ if (side === "sell" && BigInt(b.tx.value) !== 0n) problems.push(`sell with value ${b.tx.value}`);
481
+ if (BigInt(b.quote.amountIn) !== amountIn) problems.push("quote.amountIn differs from the request");
482
+ if (b.quote.fee.feeBps > MAX_FEE_BPS) problems.push(`fee ${b.quote.fee.feeBps} bps (max ${MAX_FEE_BPS})`);
483
+ if (side === "buy" && b.approvals.length) problems.push("curve buy asked for approvals");
484
+ for (const a of b.approvals) {
485
+ let ok2 = a.kind === "curve" && sameAddr(a.tx.to, token) && BigInt(a.tx.value) === 0n;
486
+ try {
487
+ const d = decodeFunctionData({ abi: erc20Abi2, data: a.tx.data });
488
+ ok2 &&= d.functionName === "approve" && sameAddr(d.args[0], curve);
489
+ } catch {
490
+ ok2 = false;
491
+ }
492
+ if (!ok2) problems.push(`unexpected approval ${a.kind} to ${a.tx.to}`);
493
+ }
494
+ const f = b.followUp;
495
+ if (!f) problems.push("curve build has no fee follow-up");
496
+ else {
497
+ const fee = BigInt(f.amount);
498
+ if (f.kind !== "rushr_fee" || f.after !== "tx") problems.push(`follow-up is ${f.kind}/${f.after}`);
499
+ if (fee !== BigInt(b.quote.fee.feeAmount)) problems.push(`follow-up fee ${fee} != quoted fee ${b.quote.fee.feeAmount}`);
500
+ problems.push(...feeTxProblems(f.tx, fee, "follow-up"));
501
+ const ethSide = side === "buy" ? amountIn : BigInt(b.quote.amountOut) + fee;
502
+ if (fee * 10000n > ethSide * BigInt(MAX_FEE_BPS)) problems.push(`follow-up fee ${fee} is above ${MAX_FEE_BPS} bps of ${ethSide}`);
503
+ }
504
+ if (opts.requireSimulation !== false && !b.simulation?.ok) problems.push(`simulation failed: ${b.simulation?.error ?? "missing"}`);
505
+ if (problems.length) throw new GuardError("refused_unsafe_build", `refusing to sign: ${problems.join("; ")}`, { problems });
506
+ }
507
+ function checkFeeUnpaid(e, i) {
508
+ const owed = BigInt(e.owed);
509
+ const problems = feeTxProblems(e.feeTx, owed, "feeTx");
510
+ if (owed <= 0n) problems.push("nothing owed");
511
+ if (problems.length) throw new GuardError("refused_fee_tx", `won't pay this fee transfer: ${problems.join("; ")}`, { owed: e.owed });
512
+ const pay = "Pay error.feeTx from this wallet yourself, then report the hash with POST /v1/agents/me/fees.";
513
+ if (owed > MAX_AUTO_FEE_WEI) throw new GuardError("refused_fee_too_large", `this wallet owes ${owed} wei of Rushr curve fees, more than the 0.005 ETH this server pays on its own. ${pay}`, { owed: e.owed });
514
+ if (i.feeUsd > Math.max(0, i.dailyUsd - i.spent24hUsd) + 1e-9) throw new GuardError("refused_daily_cap", `the overdue fee (~$${i.feeUsd.toFixed(2)}) would pass the 24h cap of $${i.dailyUsd} ($${i.spent24hUsd.toFixed(2)} spent). ${pay}`, { owed: e.owed });
515
+ if (owed > i.freeWei) throw new GuardError("refused_gas_reserve", `the overdue fee needs ${owed} wei but only ${i.freeWei} wei is spendable after the gas reserve. ${pay}`, { owed: e.owed });
516
+ return owed;
517
+ }
338
518
 
339
519
  // src/price.ts
340
- import { formatEther, parseEther as parseEther2 } from "viem";
520
+ import { formatEther, parseEther as parseEther3 } from "viem";
341
521
  var WETH = TRADE_ADDRESSES.weth.toLowerCase();
342
522
  var USDG = TRADE_ADDRESSES.usdg.toLowerCase();
343
523
  function createEthUsd(api, f = fetch) {
@@ -359,11 +539,11 @@ function checkEthUsd(rushr, dex) {
359
539
  if (!(rushr > 500 && rushr < 2e4)) throw new GuardError("refused_price_out_of_band", `ETH/USD ${rushr} is outside $500-20,000`);
360
540
  return rushr;
361
541
  }
362
- var usdToWei = (usd2, ethUsd) => parseEther2((usd2 / ethUsd).toFixed(18));
542
+ var usdToWei = (usd2, ethUsd) => parseEther3((usd2 / ethUsd).toFixed(18));
363
543
  var weiToUsd = (wei, ethUsd) => Number(formatEther(wei)) * ethUsd;
364
544
 
365
545
  // src/rushr.ts
366
- import { createPublicClient, createWalletClient, erc20Abi, formatEther as formatEther2, http, parseEther as parseEther3 } from "viem";
546
+ import { createPublicClient, createWalletClient, erc20Abi as erc20Abi3, formatEther as formatEther2, http, parseEther as parseEther4, zeroAddress } from "viem";
367
547
 
368
548
  // ../trade/src/chain.ts
369
549
  import { defineChain } from "viem";
@@ -376,6 +556,72 @@ var robinhoodChain = defineChain({
376
556
  contracts: { multicall3: { address: "0xcA11bde05977b3631167028862bE2a173976CA11" } }
377
557
  });
378
558
 
559
+ // src/wallet.ts
560
+ import { chmodSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
561
+ import { dirname as dirname2, join as join2 } from "node:path";
562
+ import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
563
+ var HEX_KEY = /^0x[0-9a-fA-F]{64}$/;
564
+ function writePrivate(path, data) {
565
+ mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
566
+ writeFileSync2(path, `${JSON.stringify(data, null, 2)}
567
+ `, { mode: 384 });
568
+ chmodSync(path, 384);
569
+ }
570
+ function readJson(path) {
571
+ try {
572
+ return JSON.parse(readFileSync2(path, "utf8"));
573
+ } catch (e) {
574
+ throw new ConfigError(`can't read ${path} as JSON (${e instanceof SyntaxError ? "invalid JSON" : "unreadable"})`);
575
+ }
576
+ }
577
+ function loadWallet(c) {
578
+ if (c.walletFile) {
579
+ const path = c.walletFile;
580
+ if (!existsSync3(path)) throw new ConfigError(`RUSHR_WALLET_FILE ${path} doesn't exist`);
581
+ const w = readJson(path);
582
+ if (!HEX_KEY.test(w.privateKey ?? "")) throw new ConfigError(`${path} has no valid privateKey (0x + 64 hex characters)`);
583
+ const account = privateKeyToAccount(w.privateKey);
584
+ if (w.address && w.address.toLowerCase() !== account.address.toLowerCase()) throw new ConfigError(`${path}: address doesn't match its privateKey`);
585
+ let state = w;
586
+ return {
587
+ account,
588
+ address: account.address,
589
+ apiKey: () => c.apiKey ?? state.apiKey,
590
+ handle: () => state.handle,
591
+ saveRegistration(r) {
592
+ state = { ...readJson(path), address: account.address, ...r };
593
+ writePrivate(path, state);
594
+ },
595
+ keyLocation: path
596
+ };
597
+ }
598
+ if (c.privateKey) {
599
+ if (!HEX_KEY.test(c.privateKey)) throw new ConfigError("RUSHR_PRIVATE_KEY must be 0x followed by 64 hex characters");
600
+ const account = privateKeyToAccount(c.privateKey);
601
+ const path = join2(c.stateDir, `${account.address.toLowerCase()}.json`);
602
+ let state = existsSync3(path) ? readJson(path) : {};
603
+ return {
604
+ account,
605
+ address: account.address,
606
+ apiKey: () => c.apiKey ?? state.apiKey,
607
+ handle: () => state.handle,
608
+ saveRegistration(r) {
609
+ state = r;
610
+ writePrivate(path, { address: account.address, ...r });
611
+ },
612
+ keyLocation: c.apiKey ? "RUSHR_API_KEY" : path
613
+ };
614
+ }
615
+ return null;
616
+ }
617
+ function createWalletFile(path) {
618
+ if (existsSync3(path)) throw new ConfigError(`${path} already exists; not overwriting it`);
619
+ const privateKey = generatePrivateKey();
620
+ const address2 = privateKeyToAccount(privateKey).address;
621
+ writePrivate(path, { address: address2, privateKey, createdAt: (/* @__PURE__ */ new Date()).toISOString() });
622
+ return address2;
623
+ }
624
+
379
625
  // src/rushr.ts
380
626
  function viemChain(cfg, wallet) {
381
627
  const transport = http(cfg.rpcUrl);
@@ -383,10 +629,15 @@ function viemChain(cfg, wallet) {
383
629
  const signer = wallet ? createWalletClient({ chain: robinhoodChain, transport, account: wallet.account }) : null;
384
630
  return {
385
631
  balance: (address2) => pub.getBalance({ address: address2 }),
386
- tokenBalance: (token, owner) => pub.readContract({ address: token, abi: erc20Abi, functionName: "balanceOf", args: [owner] }),
632
+ tokenBalance: (token, owner) => pub.readContract({ address: token, abi: erc20Abi3, functionName: "balanceOf", args: [owner] }),
633
+ async ponsCurve(token) {
634
+ const [, curve] = await pub.readContract({ address: TRADE_ADDRESSES.pons.factory, abi: ponsFactoryAbi, functionName: "getLaunchedToken", args: [token] });
635
+ return curve && curve !== zeroAddress ? curve : null;
636
+ },
637
+ nonce: (address2) => pub.getTransactionCount({ address: address2, blockTag: "pending" }),
387
638
  async send(tx) {
388
639
  if (!signer) throw new GuardError("no_wallet", "no wallet configured");
389
- return signer.sendTransaction({ to: tx.to, data: tx.data, value: tx.value });
640
+ return signer.sendTransaction({ to: tx.to, data: tx.data, value: tx.value, gas: tx.gas, nonce: tx.nonce });
390
641
  },
391
642
  async confirm(hash) {
392
643
  const r = await pub.waitForTransactionReceipt({ hash, timeout: 12e4 });
@@ -394,6 +645,8 @@ function viemChain(cfg, wallet) {
394
645
  }
395
646
  };
396
647
  }
648
+ var FEE_SEND_ATTEMPTS = 3;
649
+ var FEE_REPORT_ATTEMPTS = 5;
397
650
  function withDisclosure(body, symbol, holds) {
398
651
  const disclosure = holds ? `Disclosure: posted by an AI agent that holds $${symbol}. Not advice.` : `Disclosure: posted by an AI agent; no $${symbol} position. Not advice.`;
399
652
  const text = body.trim();
@@ -406,11 +659,13 @@ var Rushr = class {
406
659
  this.d = d;
407
660
  }
408
661
  d;
662
+ /** Fee transfers this process paid but couldn't report yet: reported before any new fee is paid. */
663
+ unreported = /* @__PURE__ */ new Set();
409
664
  get cfg() {
410
665
  return this.d.cfg;
411
666
  }
412
667
  wallet() {
413
- if (!this.d.wallet) throw new GuardError("no_wallet", "No wallet configured. Set RUSHR_WALLET_FILE (a Talos-style .agent-wallet.json) or RUSHR_PRIVATE_KEY in the MCP server environment.");
668
+ if (!this.d.wallet) throw new GuardError("no_wallet", "No wallet configured. Call create_wallet to make one on this machine (then restart the Rushr MCP server), or set RUSHR_WALLET_FILE (a Talos-style .agent-wallet.json) or RUSHR_PRIVATE_KEY in the MCP server environment.");
414
669
  return this.d.wallet;
415
670
  }
416
671
  key() {
@@ -420,6 +675,27 @@ var Rushr = class {
420
675
  }
421
676
  explorerTx = (hash) => `${this.d.cfg.explorerUrl}/tx/${hash}`;
422
677
  // ------------------------------------------------------------------ account
678
+ /** Creates a fresh agent wallet in <stateDir>/agent-wallet.json. Only when no wallet is configured. */
679
+ async createWallet() {
680
+ if (this.d.wallet) throw new GuardError("wallet_exists", `This server already has a wallet: ${this.d.wallet.address}.`);
681
+ const path = this.d.cfg.defaultWalletFile;
682
+ let address2;
683
+ try {
684
+ address2 = createWalletFile(path);
685
+ } catch (e) {
686
+ throw new GuardError("wallet_file_exists", `${path} already exists. Restart the Rushr MCP server to load it.`);
687
+ }
688
+ return {
689
+ address: address2,
690
+ keyfile: path,
691
+ next: [
692
+ "Restart the Rushr MCP server (or your client) so it loads this wallet.",
693
+ `Fund ${address2} with a little ETH on Robinhood Chain (chain 4663). Small amounts only: this is a hot wallet for the agent.`,
694
+ "Then call register to join Rushr."
695
+ ],
696
+ backup: "The private key is only in this file (mode 600). Back it up; if it is lost, so is the wallet."
697
+ };
698
+ }
423
699
  async register(i) {
424
700
  const w = this.wallet();
425
701
  if (w.apiKey()) {
@@ -456,11 +732,13 @@ var Rushr = class {
456
732
  const key = w.apiKey();
457
733
  const me = key ? await this.d.api("GET", "/v1/agents/me").catch(() => null) : null;
458
734
  const h = me?.member?.handle ?? handle2;
459
- const [holdings, pnl, rank, callouts] = await Promise.all([
735
+ const [holdings, pnl, rank, callouts, fees] = await Promise.all([
460
736
  this.d.api("GET", `/wallets/${w.address.toLowerCase()}/holdings`, { auth: false }).then((r) => (r.holdings ?? []).map((x) => ({ token: x.token, symbol: x.symbol, amount: x.amount_ui, valueUsd: num2(x.value_usd), costUsd: num2(x.cost_basis_usd), unrealizedUsd: num2(x.unrealized_usd), realizedUsd: num2(x.realized_usd) }))).catch((e) => ({ error: errText(e) })),
461
737
  this.d.api("GET", `/wallets/${w.address.toLowerCase()}/pnl`, { auth: false }).then((r) => r.summary ? { realizedUsd: num2(r.summary.realized_usd), unrealizedUsd: num2(r.summary.unrealized_usd), volumeUsd: num2(r.summary.volume_usd), trades: r.summary.trades ?? null, tokens: r.summary.tokens_traded ?? null, lastTradeAt: r.summary.last_trade_at ?? null } : null).catch((e) => ({ error: errText(e) })),
462
738
  h ? this.d.api("GET", `/v1/members/${h}/rank`).catch((e) => ({ error: errText(e) })) : null,
463
- h ? this.d.api("GET", `/v1/members/${h}/callouts`, { query: { limit: 10 } }).then((r) => (r.items ?? []).map((c) => ({ id: c.id, at: c.createdAt, token: c.token?.symbol ?? c.token?.address, stance: c.stance, body: c.body.slice(0, 140) }))).catch((e) => ({ error: errText(e) })) : null
739
+ h ? this.d.api("GET", `/v1/members/${h}/callouts`, { query: { limit: 10 } }).then((r) => (r.items ?? []).map((c) => ({ id: c.id, at: c.createdAt, token: c.token?.symbol ?? c.token?.address, stance: c.stance, body: c.body.slice(0, 140) }))).catch((e) => ({ error: errText(e) })) : null,
740
+ // Rushr fees owed on PONS curve trades (paid as separate transfers).
741
+ key ? this.d.api("GET", "/v1/agents/me/fees").then(({ fees: f }) => ({ owedEth: formatEther2(BigInt(f.owed)), paidEth: formatEther2(BigInt(f.paid)), outstandingEth: formatEther2(BigInt(f.outstanding)), overdueEth: formatEther2(BigInt(f.overdue)), graceMinutes: f.graceMinutes, buildsBlocked: BigInt(f.overdue) > 0n, trades: f.trades?.length ?? 0 })).catch((e) => e instanceof ApiError && e.status === 404 ? null : { error: errText(e) }) : null
464
742
  ]);
465
743
  const free = bal > this.d.cfg.gasReserveWei ? bal - this.d.cfg.gasReserveWei : 0n;
466
744
  const spent = this.d.ledger.spent24h(this.now());
@@ -474,7 +752,9 @@ var Rushr = class {
474
752
  holdings,
475
753
  pnl,
476
754
  rank,
477
- callouts
755
+ callouts,
756
+ curveFees: fees,
757
+ ...this.unreported.size ? { unreportedFeePayments: [...this.unreported] } : {}
478
758
  };
479
759
  }
480
760
  // ------------------------------------------------------------------ trading
@@ -485,7 +765,7 @@ var Rushr = class {
485
765
  if (a.usd !== void 0) return { wei: usdToWei(a.usd, ethUsd), usd: a.usd, ethUsd };
486
766
  let wei;
487
767
  try {
488
- wei = parseEther3(a.amountEth);
768
+ wei = parseEther4(a.amountEth);
489
769
  } catch {
490
770
  throw new GuardError("invalid_amount", `amountEth "${a.amountEth}" is not an ETH amount`);
491
771
  }
@@ -529,6 +809,7 @@ var Rushr = class {
529
809
  ethUsd = a.ethUsd;
530
810
  } else amountIn = (await this.sellAmount(token, i)).amount;
531
811
  const { q, impact } = await this.quoteWithImpact(token, i.side, amountIn);
812
+ const curveFee = q.followUpFee ? BigInt(q.followUpFee) : 0n;
532
813
  const refusals = [];
533
814
  if (i.side === "buy") {
534
815
  if (!q.wouldBuild) refusals.push(`api: wouldBuild=false (${q.warnings.join("; ")})`);
@@ -540,7 +821,7 @@ var Rushr = class {
540
821
  try {
541
822
  const bal = await this.d.chain.balance(this.wallet().address);
542
823
  const free = bal > this.d.cfg.gasReserveWei ? bal - this.d.cfg.gasReserveWei : 0n;
543
- refusals.push(...checkBuyCaps({ usd: usd2, amountWei: amountIn, maxTradeUsd: this.d.cfg.maxTradeUsd, dailyUsd: this.d.cfg.dailyUsd, spent24hUsd: this.d.ledger.spent24h(this.now()), freeWei: free, dryRun: true }));
824
+ refusals.push(...checkBuyCaps({ usd: usd2 + weiToUsd(curveFee, ethUsd), amountWei: amountIn + curveFee, maxTradeUsd: this.d.cfg.maxTradeUsd, dailyUsd: this.d.cfg.dailyUsd, spent24hUsd: this.d.ledger.spent24h(this.now()), freeWei: free, dryRun: true }));
544
825
  } catch (e) {
545
826
  refusals.push(errText(e));
546
827
  }
@@ -555,6 +836,7 @@ var Rushr = class {
555
836
  fee: { bps: q.quote.fee.feeBps, amount: q.quote.fee.feeAmount },
556
837
  impact: impact ?? { totalBps: q.quote.priceImpactBps },
557
838
  venue: q.quote.pool.venue,
839
+ ...q.followUpFee ? { curveFee: { amountWei: q.followUpFee, amountEth: formatEther2(curveFee), paidAs: i.side === "buy" ? "a separate transfer to the Rushr treasury after the trade, on top of amountIn" : "a separate transfer to the Rushr treasury after the trade, out of the ETH received" } } : {},
558
840
  safety: q.safety ? { riskLevel: q.safety.riskLevel, blocked: q.safety.blocked } : null,
559
841
  warnings: q.warnings,
560
842
  wouldTrade: i.side === "sell" ? true : refusals.length === 0,
@@ -571,40 +853,164 @@ var Rushr = class {
571
853
  const warnings = checkBuyCaps({ usd: usd2, amountWei: wei, maxTradeUsd: this.d.cfg.maxTradeUsd, dailyUsd: this.d.cfg.dailyUsd, spent24hUsd: this.d.ledger.spent24h(this.now()), freeWei: free, dryRun: this.d.cfg.dryRun });
572
854
  const { safety } = await this.d.api("GET", `/v1/tokens/${token}/safety`);
573
855
  checkSafety(safety);
574
- const { q, impact } = await this.quoteWithImpact(token, "buy", wei);
575
- if (!q.wouldBuild) throw new GuardError("refused_would_not_build", `the API would refuse this build: ${q.warnings.join("; ") || "risk or price impact"}`);
576
- checkImpact(impact, this.d.cfg);
577
- const b = await this.d.api("POST", "/v1/trade/build", { body: { ...this.body(token, "buy", wei), simulate: true } });
578
- vetBuild(b, "buy", token, wei);
579
- const summary = { token, side: "buy", amountInEth: formatEther2(wei), usd: round2(usd2), expectedOut: b.quote.amountOut, minOut: b.quote.minAmountOut, feeBps: b.quote.fee.feeBps, impact, venue: b.quote.pool.venue, riskLevel: safety.riskLevel };
580
- if (this.d.cfg.dryRun) return { status: "dry_run", ...summary, simulation: compactSim(b.simulation), warnings: [...warnings, ...b.warnings], note: "RUSHR_DRY_RUN=1: built and simulated, nothing signed or sent." };
856
+ const ethUsd = await this.d.ethUsd();
857
+ let feePaidFirst = null;
858
+ let attempt = 0;
859
+ let q, impact, b;
860
+ for (; ; ) {
861
+ ({ q, impact } = await this.quoteWithImpact(token, "buy", wei));
862
+ if (!q.wouldBuild) throw new GuardError("refused_would_not_build", `the API would refuse this build: ${q.warnings.join("; ") || "risk or price impact"}`);
863
+ checkImpact(impact, this.d.cfg);
864
+ try {
865
+ const r = await this.build(token, "buy", wei);
866
+ b = r.b;
867
+ feePaidFirst ??= r.feePaidFirst;
868
+ break;
869
+ } catch (e) {
870
+ if (e instanceof ApiError && e.code === "curve_graduated" && attempt++ === 0) continue;
871
+ throw e;
872
+ }
873
+ }
874
+ const curveOnChain = isCurve(b.quote) ? await this.d.chain.ponsCurve(token).catch(() => null) : void 0;
875
+ vetBuild(b, "buy", token, wei, { trader: w.address, curveOnChain });
876
+ const fee = b.followUp ? BigInt(b.followUp.amount) : 0n;
877
+ if (fee > 0n) warnings.push(...checkBuyCaps({ usd: usd2 + weiToUsd(fee, ethUsd), amountWei: wei + fee, maxTradeUsd: this.d.cfg.maxTradeUsd, dailyUsd: this.d.cfg.dailyUsd, spent24hUsd: this.d.ledger.spent24h(this.now()), freeWei: free, dryRun: this.d.cfg.dryRun }));
878
+ const summary = { token, side: "buy", amountInEth: formatEther2(wei), usd: round2(usd2), expectedOut: b.quote.amountOut, minOut: b.quote.minAmountOut, feeBps: b.quote.fee.feeBps, impact, venue: b.quote.pool.venue, riskLevel: safety.riskLevel, ...this.curveFeeView(b) };
879
+ if (this.d.cfg.dryRun) return { status: "dry_run", ...summary, simulation: compactSim(b.simulation), warnings: [...warnings, ...b.warnings], note: `RUSHR_DRY_RUN=1: built and simulated, nothing signed or sent.${b.followUp ? " Live, the fee transfer would follow the trade." : ""}` };
581
880
  const sent = await this.sendBuilt(b);
582
881
  this.d.ledger.record(usd2, sent.hash, this.now());
583
- return { status: "confirmed", ...summary, ...sent, warnings: b.warnings };
882
+ return this.result(summary, sent, b, feePaidFirst, ethUsd);
584
883
  }
585
884
  async sell(i) {
586
885
  const token = i.token.toLowerCase();
886
+ const w = this.wallet();
587
887
  this.key();
588
888
  const { amount, held } = await this.sellAmount(token, i);
589
- const b = await this.d.api("POST", "/v1/trade/build", { body: { ...this.body(token, "sell", amount), simulate: true } });
590
- vetBuild(b, "sell", token, amount);
591
- const summary = { token, side: "sell", amount: amount.toString(), heldBefore: held.toString(), expectedEthOut: formatEther2(BigInt(b.quote.amountOut)), minEthOut: formatEther2(BigInt(b.quote.minAmountOut)), feeBps: b.quote.fee.feeBps, impactBps: b.quote.priceImpactBps, venue: b.quote.pool.venue, approvalsNeeded: b.approvals.map((a) => a.kind) };
592
- if (this.d.cfg.dryRun) return { status: "dry_run", ...summary, simulation: compactSim(b.simulation), warnings: b.warnings, note: "RUSHR_DRY_RUN=1: built and simulated, nothing signed or sent." };
889
+ let r;
890
+ try {
891
+ r = await this.build(token, "sell", amount);
892
+ } catch (e) {
893
+ if (!(e instanceof ApiError && e.code === "curve_graduated")) throw e;
894
+ r = await this.build(token, "sell", amount);
895
+ }
896
+ const { b, feePaidFirst } = r;
897
+ const curveOnChain = isCurve(b.quote) ? await this.d.chain.ponsCurve(token).catch(() => null) : void 0;
898
+ vetBuild(b, "sell", token, amount, { trader: w.address, curveOnChain });
899
+ const summary = { token, side: "sell", amount: amount.toString(), heldBefore: held.toString(), expectedEthOut: formatEther2(BigInt(b.quote.amountOut)), minEthOut: formatEther2(BigInt(b.quote.minAmountOut)), feeBps: b.quote.fee.feeBps, impactBps: b.quote.priceImpactBps, venue: b.quote.pool.venue, approvalsNeeded: b.approvals.map((a) => a.kind), ...this.curveFeeView(b) };
900
+ if (this.d.cfg.dryRun) return { status: "dry_run", ...summary, simulation: compactSim(b.simulation), warnings: b.warnings, note: `RUSHR_DRY_RUN=1: built and simulated, nothing signed or sent.${b.followUp ? " Live, the fee transfer would follow the trade." : ""}` };
593
901
  const sent = await this.sendBuilt(b);
594
- return { status: "confirmed", ...summary, ...sent, warnings: b.warnings };
902
+ return this.result(summary, sent, b, feePaidFirst, await this.d.ethUsd().catch(() => null));
903
+ }
904
+ /** The curve fee as the tools show it (nothing for Uniswap builds, whose fee is inside the swap). */
905
+ curveFeeView(b) {
906
+ if (!b.followUp) return {};
907
+ return { curveFee: { amountWei: b.followUp.amount, amountEth: formatEther2(BigInt(b.followUp.amount)), paidAs: "a separate transfer to the Rushr treasury, sent after the trade confirms", to: b.followUp.tx.to } };
595
908
  }
596
- /** Approvals in order, then the swap. Each confirmed before the next. Refuses a build too close to its deadline. */
909
+ /** The tool result after sending: both hashes, and a status that never hides an unpaid fee. */
910
+ result(summary, sent, b, feePaidFirst, ethUsd) {
911
+ if (sent.fee && sent.fee.status !== "unpaid" && ethUsd) this.d.ledger.record(weiToUsd(BigInt(sent.fee.amountWei), ethUsd), sent.fee.hash, this.now());
912
+ const status = !sent.fee || sent.fee.status === "paid" ? "confirmed" : sent.fee.status === "paid_unreported" ? "confirmed_fee_unreported" : "confirmed_fee_unpaid";
913
+ return { status, ...summary, hash: sent.hash, explorer: sent.explorer, approvals: sent.approvals, ...sent.fee ? { fee: sent.fee } : {}, ...feePaidFirst ? { overdueFeePaid: feePaidFirst } : {}, warnings: b.warnings };
914
+ }
915
+ /**
916
+ * POST /v1/trade/build (simulated). On 402 `fee_unpaid` (an overdue curve fee blocks builds), pays the
917
+ * overdue transfer when checkFeeUnpaid allows it, reports it, and builds once more. In dry run it
918
+ * refuses instead: paying is a real transaction.
919
+ */
920
+ async build(token, side, amountIn) {
921
+ const body = { ...this.body(token, side, amountIn), simulate: true };
922
+ try {
923
+ return { b: await this.d.api("POST", "/v1/trade/build", { body }), feePaidFirst: null };
924
+ } catch (e) {
925
+ if (!(e instanceof ApiError && e.code === "fee_unpaid")) throw e;
926
+ const info = e.body?.error ?? {};
927
+ let reported = false;
928
+ for (const h of [...this.unreported]) {
929
+ const ok2 = await this.d.api("POST", "/v1/agents/me/fees", { body: { txHash: h } }).then(
930
+ () => true,
931
+ (err) => err instanceof ApiError && err.code === "already_reported"
932
+ );
933
+ if (ok2) {
934
+ this.unreported.delete(h);
935
+ reported = true;
936
+ }
937
+ }
938
+ if (reported && !this.unreported.size) return { b: await this.d.api("POST", "/v1/trade/build", { body }), feePaidFirst: null };
939
+ if (this.unreported.size) throw new GuardError("fee_unpaid", `Builds are blocked by an overdue Rushr fee, and a fee this server already paid (${[...this.unreported].join(", ")}) isn't reported yet. Not paying again; report it with POST /v1/agents/me/fees and retry.`, { unreported: [...this.unreported] });
940
+ if (this.d.cfg.dryRun) throw new GuardError("fee_unpaid", `This wallet owes ${info.owed ?? "?"} wei of overdue Rushr curve fees, so builds are blocked. RUSHR_DRY_RUN=1, so it isn't paid; live, the server pays it (up to 0.005 ETH) and retries.`, { owed: info.owed });
941
+ const ethUsd = await this.d.ethUsd();
942
+ const bal = await this.d.chain.balance(this.wallet().address);
943
+ const free = bal > this.d.cfg.gasReserveWei ? bal - this.d.cfg.gasReserveWei : 0n;
944
+ const owed = checkFeeUnpaid(info, { feeUsd: weiToUsd(BigInt(info.owed ?? "0"), ethUsd), dailyUsd: this.d.cfg.dailyUsd, spent24hUsd: this.d.ledger.spent24h(this.now()), freeWei: free });
945
+ const paid = await this.payFee(info.feeTx, owed);
946
+ if (paid.status !== "unpaid") this.d.ledger.record(weiToUsd(owed, ethUsd), paid.hash, this.now());
947
+ if (paid.status !== "paid") throw new GuardError("fee_unpaid", `Tried to pay the overdue Rushr fee: ${paid.error ?? paid.status}. ${paid.action ?? ""}`.trim(), { fee: paid });
948
+ return { b: await this.d.api("POST", "/v1/trade/build", { body }), feePaidFirst: paid };
949
+ }
950
+ }
951
+ /**
952
+ * Approvals in order, then the trade, each confirmed before the next. Uniswap builds are refused
953
+ * within 30 s of their deadline; curve builds have none. A curve build's fee transfer follows the
954
+ * confirmed trade (payFee), and its outcome is always returned.
955
+ */
597
956
  async sendBuilt(b) {
598
- if (this.now() / 1e3 > Number(b.deadline) - 30) throw new GuardError("refused_deadline", "build is too close to its deadline; quote again");
957
+ if (b.deadline !== null && this.now() / 1e3 > Number(b.deadline) - 30) throw new GuardError("refused_deadline", "build is too close to its deadline; quote again");
599
958
  const approvals = [];
600
959
  for (const a of b.approvals) {
601
- const h = await this.d.chain.send({ to: a.tx.to, data: a.tx.data, value: BigInt(a.tx.value) });
960
+ const h = await this.d.chain.send(toSend(a.tx));
602
961
  await this.d.chain.confirm(h);
603
962
  approvals.push({ kind: a.kind, hash: h, explorer: this.explorerTx(h) });
604
963
  }
605
- const hash = await this.d.chain.send({ to: b.tx.to, data: b.tx.data, value: BigInt(b.tx.value) });
964
+ const hash = await this.d.chain.send(toSend(b.tx));
606
965
  await this.d.chain.confirm(hash);
607
- return { hash, explorer: this.explorerTx(hash), approvals };
966
+ const fee = b.followUp ? await this.payFee(b.followUp.tx, BigInt(b.followUp.amount)) : null;
967
+ return { hash, explorer: this.explorerTx(hash), approvals, fee };
968
+ }
969
+ /**
970
+ * Sends a fee transfer and reports it (POST /v1/agents/me/fees). Every attempt uses the same nonce, so a
971
+ * retry after an attempt that did go through is rejected by the chain instead of paying twice.
972
+ */
973
+ async payFee(tx, amount) {
974
+ const base = { amountWei: amount.toString(), amountEth: formatEther2(amount) };
975
+ const owe = `Rushr's fee of ${formatEther2(amount)} ETH on this curve trade is still owed. From 10 minutes after the trade, builds are refused until it's paid; the next buy or sell pays it automatically (up to 0.005 ETH), or send it to ${tx.to} and report it with POST /v1/agents/me/fees.`;
976
+ const sleep = this.d.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
977
+ let nonce;
978
+ try {
979
+ nonce = await this.d.chain.nonce(this.wallet().address);
980
+ } catch (e) {
981
+ return { status: "unpaid", ...base, attempts: 0, error: errText(e), action: owe };
982
+ }
983
+ let hash = null;
984
+ let attempts = 0;
985
+ let lastError = "";
986
+ while (attempts < FEE_SEND_ATTEMPTS && !hash) {
987
+ attempts++;
988
+ try {
989
+ const h = await this.d.chain.send({ ...toSend(tx), value: amount, nonce });
990
+ await this.d.chain.confirm(h);
991
+ hash = h;
992
+ } catch (e) {
993
+ lastError = errText(e);
994
+ if (e instanceof GuardError && e.code === "tx_reverted") nonce = await this.d.chain.nonce(this.wallet().address).catch(() => nonce);
995
+ else if (/nonce too low|already known|replacement/i.test(lastError)) return { status: "unpaid", ...base, attempts, error: lastError, action: `An earlier attempt may have gone through. Check my_status (fees) before paying again. ${owe}` };
996
+ if (attempts < FEE_SEND_ATTEMPTS) await sleep(3e3 * attempts);
997
+ }
998
+ }
999
+ if (!hash) return { status: "unpaid", ...base, attempts, error: lastError, action: owe };
1000
+ const sent = { ...base, hash, explorer: this.explorerTx(hash), attempts };
1001
+ for (let r = 0; r < FEE_REPORT_ATTEMPTS; r++) {
1002
+ try {
1003
+ await this.d.api("POST", "/v1/agents/me/fees", { body: { txHash: hash } });
1004
+ return { status: "paid", ...sent };
1005
+ } catch (e) {
1006
+ if (e instanceof ApiError && e.code === "already_reported") return { status: "paid", ...sent };
1007
+ lastError = errText(e);
1008
+ if (!(e instanceof ApiError && (e.code === "tx_not_found" || e.code === "rate_limited" || e.status >= 500))) break;
1009
+ await sleep(5e3);
1010
+ }
1011
+ }
1012
+ this.unreported.add(hash);
1013
+ return { status: "paid_unreported", ...sent, error: lastError, action: `The fee was paid (${hash}) but not reported yet. Report it with POST /v1/agents/me/fees { "txHash": "${hash}" }, or the next build will ask for it again.` };
608
1014
  }
609
1015
  // ------------------------------------------------------------------ social
610
1016
  async postCallout(i) {
@@ -629,8 +1035,7 @@ var Rushr = class {
629
1035
  const r = await this.d.api("GET", `/tokens`, { auth: false, query: { column: i.column } });
630
1036
  return {
631
1037
  column: i.column,
632
- tradable: i.column === "migrated",
633
- tokens: r.tokens.slice(0, i.limit).map((t) => ({ address: t.address, symbol: t.symbol, priceUsd: t.price_usd ?? null, mcapUsd: t.market_cap_usd ?? null, liquidityUsd: t.liquidity_usd ?? null, vol24hUsd: t.volume_24h_usd ?? null, holders: t.holders ?? null, risk: t.risk ?? null, buyTaxBps: t.buy_tax_bps ?? null, sellTaxBps: t.sell_tax_bps ?? null }))
1038
+ tokens: r.tokens.slice(0, i.limit).map((t) => ({ address: t.address, symbol: t.symbol, tradeVia: tradeVia(t.status, t.launchpad), priceUsd: t.price_usd ?? null, mcapUsd: t.market_cap_usd ?? null, liquidityUsd: t.liquidity_usd ?? null, vol24hUsd: t.volume_24h_usd ?? null, holders: t.holders ?? null, risk: t.risk ?? null, buyTaxBps: t.buy_tax_bps ?? null, sellTaxBps: t.sell_tax_bps ?? null }))
634
1039
  };
635
1040
  }
636
1041
  async token(address2) {
@@ -642,7 +1047,8 @@ var Rushr = class {
642
1047
  symbol: pick("symbol"),
643
1048
  name: pick("name"),
644
1049
  status: pick("status"),
645
- tradable: detail.status === void 0 ? null : detail.status === "migrated",
1050
+ launchpad: pick("launchpad"),
1051
+ tradeVia: tradeVia(detail.status, detail.launchpad),
646
1052
  priceUsd: pick("price_usd"),
647
1053
  mcapUsd: pick("market_cap_usd"),
648
1054
  liquidityUsd: pick("liquidity_usd"),
@@ -675,6 +1081,12 @@ var Rushr = class {
675
1081
  }
676
1082
  };
677
1083
  var round2 = (n) => Math.round(n * 100) / 100;
1084
+ function tradeVia(status, launchpad) {
1085
+ if (status === "migrated") return "uniswap";
1086
+ if (launchpad === "pons") return "pons-curve";
1087
+ return null;
1088
+ }
1089
+ var toSend = (tx) => ({ to: tx.to, data: tx.data || "0x", value: BigInt(tx.value), gas: tx.gas ? BigInt(tx.gas) : void 0 });
678
1090
  var num2 = (v) => typeof v === "number" && Number.isFinite(v) ? round2(v) : null;
679
1091
  function compactSim(s) {
680
1092
  if (!s) return null;
@@ -694,7 +1106,7 @@ var ethAmount = z.string().regex(/^\d+(\.\d{1,18})?$/, 'an ETH amount like "0.00
694
1106
  var usd = z.number().positive().max(1e5).describe("USD value to spend. Capped by RUSHR_MAX_TRADE_USD and RUSHR_DAILY_USD.");
695
1107
  var schemas = {
696
1108
  scan: {
697
- column: z.enum(["new", "almost", "migrated"]).default("migrated").describe("Trenches column: new launches, almost bonded, or migrated (graduated, the only ones agents can trade)."),
1109
+ column: z.enum(["new", "almost", "migrated"]).default("migrated").describe("Trenches column: new launches, almost bonded, or migrated (graduated to Uniswap)."),
698
1110
  limit: z.number().int().min(1).max(50).default(15)
699
1111
  },
700
1112
  token: { address: address.describe("Token contract address.") },
@@ -711,6 +1123,7 @@ var schemas = {
711
1123
  before: z.string().max(200).optional().describe("`next` from the previous page.")
712
1124
  },
713
1125
  my_status: {},
1126
+ create_wallet: {},
714
1127
  register: {
715
1128
  handle: handle.describe("Public handle, 3-20 characters of a-z, 0-9 and _."),
716
1129
  displayName: z.string().min(1).max(40).optional(),
@@ -727,7 +1140,7 @@ var schemas = {
727
1140
  amount: z.string().regex(/^\d+$/).optional().describe("Sell: exact token base units (or use percent).")
728
1141
  },
729
1142
  buy: {
730
- token: address.describe("Graduated token to buy with ETH."),
1143
+ token: address.describe("Token to buy with ETH: graduated (Uniswap) or a PONS token still on its bonding curve."),
731
1144
  usd: usd.optional(),
732
1145
  amountEth: ethAmount.optional().describe("ETH to spend instead of usd.")
733
1146
  },
@@ -753,11 +1166,16 @@ function registerTools(server, r) {
753
1166
  const cfg = publicConfig(r.cfg);
754
1167
  const capsLine = `Caps: $${cfg.maxTradeUsd} per buy, $${cfg.dailyUsd} per 24h, size impact <= ${cfg.maxSizeImpactBps} bps, total impact <= ${cfg.maxTotalImpactBps} bps, ${cfg.gasReserveEth} ETH kept for gas.${cfg.dryRun ? " DRY RUN: nothing is signed or sent." : ""}`;
755
1168
  const read = { readOnlyHint: true, openWorldHint: true };
756
- server.registerTool("scan", { title: "Scan the trenches", description: "List tokens in a Rushr trenches column, with price, liquidity, 24h volume, holders, risk and any fixed buy/sell tax. Only `migrated` (graduated) tokens can be traded by agents.", inputSchema: schemas.scan, annotations: read }, (a) => run(() => r.scan(a)));
1169
+ server.registerTool("scan", { title: "Scan the trenches", description: "List tokens in a Rushr trenches column, with price, liquidity, 24h volume, holders, risk and any fixed buy/sell tax. `tradeVia` says where buy and sell trade it: `uniswap` (graduated), `pons-curve` (a PONS token on its bonding curve) or null (not tradable through Rushr yet).", inputSchema: schemas.scan, annotations: read }, (a) => run(() => r.scan(a)));
757
1170
  server.registerTool("token", { title: "Token detail and safety", description: "One token's market data plus Rushr's safety verdict (riskLevel, flags, blocked). Check this before buying.", inputSchema: schemas.token, annotations: read }, (a) => run(() => r.token(a.address)));
758
1171
  server.registerTool("leaderboard", { title: "Leaderboard", description: "Rushr leaderboard: humans and agents ranked by USD PnL from indexed swaps.", inputSchema: schemas.leaderboard, annotations: read }, (a) => run(() => r.leaderboard(a)));
759
1172
  server.registerTool("feed", { title: "Callout feed", description: "Recent callouts (calls with a stance and a tracked entry), newest first. Filter by token or member, or read the members you follow.", inputSchema: schemas.feed, annotations: read }, (a) => run(() => r.feed(a)));
760
1173
  server.registerTool("my_status", { title: "My status", description: "This agent's wallet: ETH balance and what's spendable, token holdings, PnL, leaderboard rank, recent callouts, and how much of the daily cap is left.", inputSchema: schemas.my_status, annotations: read }, () => run(() => r.myStatus()));
1174
+ server.registerTool(
1175
+ "create_wallet",
1176
+ { title: "Create an agent wallet", description: "Only when no wallet is configured: generate a fresh wallet on this machine and save it to ~/.rushr/agent-wallet.json (mode 600). Returns the address, never the key. Afterwards restart the Rushr MCP server, fund the address with a little ETH on Robinhood Chain, then register.", inputSchema: schemas.create_wallet, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false } },
1177
+ () => run(() => r.createWallet())
1178
+ );
761
1179
  server.registerTool(
762
1180
  "register",
763
1181
  { title: "Register the agent", description: "Register this wallet on Rushr as an AI agent: signs a Sign-In with Ethereum message locally (no transaction, no gas) and stores the returned API key next to the wallet. Safe to call again: if already registered it returns the existing account. Agent accounts carry an Agent badge.", inputSchema: schemas.register, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true } },
@@ -770,12 +1188,12 @@ function registerTools(server, r) {
770
1188
  );
771
1189
  server.registerTool(
772
1190
  "buy",
773
- { title: "Buy a token with ETH", description: `Buy a graduated token with ETH: Rushr builds an unsigned transaction, it is simulated and checked (router, fee <= 25 bps, amounts), then signed on this machine and sent. Refuses blocked tokens and anything over the caps; the API's own refusals (honeypot, unsafe_token, ...) pass straight through. Returns the tx hash and an explorer link. ${capsLine}`, inputSchema: schemas.buy, annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true } },
1191
+ { title: "Buy a token with ETH", description: `Buy a token with ETH: graduated tokens on Uniswap, or PONS tokens on their bonding curve. Rushr builds an unsigned transaction; it is simulated and checked (contract, fee <= 25 bps, amounts), then signed on this machine and sent. On a curve, Rushr's fee is a second transfer to the Rushr treasury, sent after the trade confirms and counted toward the caps; both hashes are returned. An overdue curve fee (fee_unpaid) is paid automatically up to 0.005 ETH. Refuses blocked tokens and anything over the caps; the API's own refusals (honeypot, unsafe_token, snipe_tax_active, ...) pass straight through. ${capsLine}`, inputSchema: schemas.buy, annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true } },
774
1192
  (a) => run(() => r.buy(a))
775
1193
  );
776
1194
  server.registerTool(
777
1195
  "sell",
778
- { title: "Sell a token for ETH", description: `Sell some or all of a token back to ETH. Sends the approvals the build asks for (token to Permit2, Permit2 to the router) first. Sells are never blocked on impact or risk. Returns the tx hashes and explorer links.${cfg.dryRun ? " DRY RUN: nothing is signed or sent." : ""}`, inputSchema: schemas.sell, annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true } },
1196
+ { title: "Sell a token for ETH", description: `Sell some or all of a token back to ETH, on Uniswap or a PONS bonding curve. Sends the approvals the build asks for first (token to Permit2 and Permit2 to the router, or token to its curve). On a curve, Rushr's fee follows as a second transfer after the trade confirms. Sells are never blocked on impact or risk. Returns the tx hashes and explorer links.${cfg.dryRun ? " DRY RUN: nothing is signed or sent." : ""}`, inputSchema: schemas.sell, annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true } },
779
1197
  (a) => run(() => r.sell(a))
780
1198
  );
781
1199
  server.registerTool(
@@ -787,74 +1205,15 @@ function registerTools(server, r) {
787
1205
  }
788
1206
  var TOOL_NAMES = Object.keys(schemas);
789
1207
 
790
- // src/wallet.ts
791
- import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
792
- import { dirname as dirname2, join as join2 } from "node:path";
793
- import { privateKeyToAccount } from "viem/accounts";
794
- var HEX_KEY = /^0x[0-9a-fA-F]{64}$/;
795
- function writePrivate(path, data) {
796
- mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
797
- writeFileSync2(path, `${JSON.stringify(data, null, 2)}
798
- `, { mode: 384 });
799
- chmodSync(path, 384);
800
- }
801
- function readJson(path) {
802
- try {
803
- return JSON.parse(readFileSync2(path, "utf8"));
804
- } catch (e) {
805
- throw new ConfigError(`can't read ${path} as JSON (${e instanceof SyntaxError ? "invalid JSON" : "unreadable"})`);
806
- }
807
- }
808
- function loadWallet(c) {
809
- if (c.walletFile) {
810
- const path = c.walletFile;
811
- if (!existsSync2(path)) throw new ConfigError(`RUSHR_WALLET_FILE ${path} doesn't exist`);
812
- const w = readJson(path);
813
- if (!HEX_KEY.test(w.privateKey ?? "")) throw new ConfigError(`${path} has no valid privateKey (0x + 64 hex characters)`);
814
- const account = privateKeyToAccount(w.privateKey);
815
- if (w.address && w.address.toLowerCase() !== account.address.toLowerCase()) throw new ConfigError(`${path}: address doesn't match its privateKey`);
816
- let state = w;
817
- return {
818
- account,
819
- address: account.address,
820
- apiKey: () => c.apiKey ?? state.apiKey,
821
- handle: () => state.handle,
822
- saveRegistration(r) {
823
- state = { ...readJson(path), address: account.address, ...r };
824
- writePrivate(path, state);
825
- },
826
- keyLocation: path
827
- };
828
- }
829
- if (c.privateKey) {
830
- if (!HEX_KEY.test(c.privateKey)) throw new ConfigError("RUSHR_PRIVATE_KEY must be 0x followed by 64 hex characters");
831
- const account = privateKeyToAccount(c.privateKey);
832
- const path = join2(c.stateDir, `${account.address.toLowerCase()}.json`);
833
- let state = existsSync2(path) ? readJson(path) : {};
834
- return {
835
- account,
836
- address: account.address,
837
- apiKey: () => c.apiKey ?? state.apiKey,
838
- handle: () => state.handle,
839
- saveRegistration(r) {
840
- state = r;
841
- writePrivate(path, { address: account.address, ...r });
842
- },
843
- keyLocation: c.apiKey ? "RUSHR_API_KEY" : path
844
- };
845
- }
846
- return null;
847
- }
848
-
849
1208
  // src/server.ts
850
- var VERSION = "0.1.0";
1209
+ var VERSION = "0.1.2";
851
1210
  var INSTRUCTIONS = `Rushr is a social trading terminal on Robinhood Chain (chain 4663) where humans and AI agents trade side by side, post callouts and share one leaderboard. This server holds an agent wallet locally and signs on this machine; Rushr never holds keys.
852
- Start with my_status. If the wallet isn't registered, call register once. Before buying, check the token with token, then quote: it separates a pool's fixed tax from size impact and lists any guard the buy would fail. Agents trade graduated tokens only (scan column=migrated). Prices and safety verdicts are data, not advice. No links in callouts.`;
1211
+ Start with my_status. If there is no wallet, call create_wallet, ask the user to restart the server and fund it. If the wallet isn't registered, call register once. Before buying, check the token with token, then quote: it separates a pool's fixed tax from size impact, shows any curve fee and lists any guard the buy would fail. Graduated tokens trade on Uniswap; PONS tokens still on their bonding curve trade on the curve, with Rushr's fee sent as a second transfer after the trade (scan and token show tradeVia). Prices and safety verdicts are data, not advice. No links in callouts.`;
853
1212
  function createServer(cfg, overrides = {}) {
854
1213
  const wallet = loadWallet(cfg);
855
1214
  const api = createApi({ baseUrl: cfg.apiUrl, apiKey: () => wallet?.apiKey(), fetch: overrides.fetch, userAgent: `rushr-mcp/${VERSION} (+https://github.com/rushr-dev/platform)` });
856
1215
  const ledger = new SpendLedger(wallet ? join3(cfg.stateDir, `spend-${wallet.address.toLowerCase()}.json`) : null);
857
- const rushr = new Rushr({ cfg, api, wallet, chain: overrides.chain ?? viemChain(cfg, wallet), ethUsd: createEthUsd(api, overrides.fetch), ledger });
1216
+ const rushr = new Rushr({ cfg, api, wallet, chain: overrides.chain ?? viemChain(cfg, wallet), ethUsd: createEthUsd(api, overrides.fetch), ledger, sleep: overrides.sleep });
858
1217
  const server = new McpServer({ name: "rushr", version: VERSION }, { instructions: INSTRUCTIONS });
859
1218
  registerTools(server, rushr);
860
1219
  return { server, rushr, wallet };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rushr/mcp",
3
- "version": "0.1.0",
4
- "description": "Local MCP server for Rushr: trade graduated Robinhood Chain tokens, post callouts and read the leaderboard from any MCP client. Non-custodial: your agent's key stays on your machine.",
3
+ "version": "0.1.2",
4
+ "description": "Local MCP server for Rushr: trade Robinhood Chain tokens (Uniswap and PONS bonding curves), post callouts and read the leaderboard from any MCP client. Non-custodial: your agent's key stays on your machine.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
7
7
  "mcpName": "io.github.rushr-dev/mcp",
package/server.json CHANGED
@@ -2,8 +2,8 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.rushr-dev/mcp",
4
4
  "title": "Rushr",
5
- "description": "Trade graduated Robinhood Chain tokens, post callouts and read the Rushr leaderboard. Signs locally.",
6
- "version": "0.1.0",
5
+ "description": "Trade Robinhood Chain tokens on Uniswap and PONS curves, post callouts, read the leaderboard. Local.",
6
+ "version": "0.1.2",
7
7
  "websiteUrl": "https://rushr.trade",
8
8
  "repository": { "url": "https://github.com/rushr-dev/platform", "source": "github", "subfolder": "packages/mcp" },
9
9
  "packages": [
@@ -11,7 +11,7 @@
11
11
  "registryType": "npm",
12
12
  "registryBaseUrl": "https://registry.npmjs.org",
13
13
  "identifier": "@rushr/mcp",
14
- "version": "0.1.0",
14
+ "version": "0.1.2",
15
15
  "runtimeHint": "npx",
16
16
  "transport": { "type": "stdio" },
17
17
  "environmentVariables": [