@rushr/mcp 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,21 +4,25 @@ 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
+ | `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
22
  | `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. |
23
+ | `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. |
24
+ | `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`). |
25
+ | `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
26
  | `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
27
  | `delete_callout` | Deletes one of your own callouts. |
24
28
 
@@ -72,7 +76,7 @@ const rushr = new MCPServerStdio({
72
76
  });
73
77
  await rushr.connect();
74
78
  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);
79
+ console.log((await run(agent, 'Check my status, then scan the trenches.')).finalOutput);
76
80
  await rushr.close();
77
81
  ```
78
82
 
@@ -106,17 +110,59 @@ Every buy passes these checks before anything is signed:
106
110
  - **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
111
  - **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
112
  - **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:**
113
+ - **The build itself (Uniswap):**
110
114
  - chain 4663;
111
115
  - `tx.to` is the Universal Router;
112
116
  - the value and amount match the request;
113
117
  - the fee is at most 25 bps;
114
118
  - approvals go only to the token or Permit2;
119
+ - there is no follow-up transaction;
120
+ - and the simulation succeeded.
121
+ - **The build itself (PONS curve):**
122
+ - `tx.to` is the curve named in the quote's pool, and the same curve PONS's factory records for the token on-chain;
123
+ - the calldata is the curve's `buy` or `sell` with the requested amount, paying out to this wallet;
124
+ - buys send exactly the requested ETH, and sells send none;
125
+ - approvals (sells only) are `token.approve(curve)`;
126
+ - 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
127
  - and the simulation succeeded.
116
- - **Deadline:** a build within 30 seconds of its deadline is refused; quote again.
128
+ - **Deadline:** a Uniswap build within 30 seconds of its deadline is refused; quote again. Curve builds have no deadline.
117
129
 
118
130
  Sells are never blocked on impact or risk, so getting out always works. They still pass the build checks.
119
131
 
132
+ ## Curve trades
133
+
134
+ 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.
135
+
136
+ The order is always:
137
+ 1. the approvals, each confirmed;
138
+ 2. the trade, waiting for its receipt;
139
+ 3. the fee transfer, confirmed;
140
+ 4. a report of its hash to Rushr (`POST /v1/agents/me/fees`).
141
+
142
+ **Retries:**
143
+ - **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.
144
+ - **Report:** retried while Rushr hasn't seen the transfer yet (`tx_not_found`).
145
+
146
+ **The result always says what happened to the fee:**
147
+
148
+ | `status` | Meaning |
149
+ | --- | --- |
150
+ | `confirmed` | The trade and the fee are both done. |
151
+ | `confirmed_fee_unreported` | The fee was paid but not reported yet. It is reported before any new fee is paid. |
152
+ | `confirmed_fee_unpaid` | The trade went through but the fee transfer didn't. `fee.action` says what to do. |
153
+
154
+ 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:
155
+ - it goes to the treasury Safe, for exactly what's owed;
156
+ - it's at most 0.005 ETH;
157
+ - it fits in what's left of `RUSHR_DAILY_USD`;
158
+ - and it doesn't dip into the gas reserve.
159
+
160
+ Otherwise it refuses and says how to pay. In dry run it never pays.
161
+
162
+ Other curve errors pass straight through:
163
+ - `snipe_tax_active`: the curve is in its first seconds; retry shortly.
164
+ - `curve_graduated`: the token just moved to Uniswap. The server quotes again and retries once on its own.
165
+
120
166
  Refusals come back as tool errors: `{ "error": { "code", "message", "source" } }`.
121
167
  - `source: "guard"`: one of this server's checks (codes `refused_…`).
122
168
  - `source: "rushr_api"`: the API's own code.
@@ -125,7 +171,7 @@ Refusals come back as tool errors: `{ "error": { "code", "message", "source" } }
125
171
 
126
172
  - **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
173
  - 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.
174
+ - 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
175
  - Try `RUSHR_DRY_RUN=1` first.
130
176
  - Lost the API key? Call `register` with `recoverKey: true`. It signs in again and revokes the wallet's older keys.
131
177
 
package/dist/index.js CHANGED
@@ -133,9 +133,93 @@ function createApi(o) {
133
133
  // src/guards.ts
134
134
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
135
135
  import { dirname } from "node:path";
136
+ import { decodeFunctionData, erc20Abi as erc20Abi2, parseEther as parseEther2 } from "viem";
136
137
 
137
- // ../core/src/chain/robinhood.ts
138
+ // ../trade/src/abis.ts
138
139
  import { parseAbi } from "viem";
140
+ var erc20Abi = parseAbi([
141
+ "function approve(address spender, uint256 amount) returns (bool)",
142
+ "function allowance(address owner, address spender) view returns (uint256)",
143
+ "function balanceOf(address) view returns (uint256)",
144
+ "function decimals() view returns (uint8)",
145
+ "function symbol() view returns (string)",
146
+ "event Transfer(address indexed from, address indexed to, uint256 value)"
147
+ ]);
148
+ var permit2Abi = parseAbi([
149
+ "function allowance(address owner, address token, address spender) view returns (uint160 amount, uint48 expiration, uint48 nonce)",
150
+ "function approve(address token, address spender, uint160 amount, uint48 expiration)"
151
+ ]);
152
+ var v4QuoterAbi = parseAbi([
153
+ "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)"
154
+ ]);
155
+ var v3QuoterV2Abi = parseAbi([
156
+ "function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)"
157
+ ]);
158
+ var v3FactoryAbi = parseAbi(["function getPool(address, address, uint24) view returns (address)"]);
159
+ var v3PoolAbi = parseAbi(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16, uint16, uint16, uint8, bool)", "function liquidity() view returns (uint128)"]);
160
+ var v2FactoryAbi = parseAbi(["function getPair(address, address) view returns (address)"]);
161
+ var v2PairAbi = parseAbi(["function getReserves() view returns (uint112 reserve0, uint112 reserve1, uint32)", "function token0() view returns (address)"]);
162
+ var v4StateViewAbi = parseAbi([
163
+ "function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)",
164
+ "function getLiquidity(bytes32 poolId) view returns (uint128)"
165
+ ]);
166
+ var v4PositionManagerAbi = parseAbi([
167
+ "function poolKeys(bytes25 poolId) view returns (address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks)"
168
+ ]);
169
+ var ponsCurveAbi = parseAbi([
170
+ "function buy(uint256 quoteIn, uint256 minTokensOut, address recipient) payable returns (uint256)",
171
+ "function sell(uint256 tokensIn, uint256 minQuoteOut, address recipient) returns (uint256)",
172
+ "function getReserves() view returns (uint256 quoteReserve, uint256 tokenReserve)",
173
+ "function feeBps() view returns (uint256)",
174
+ "function creatorTaxBps() view returns (uint256)",
175
+ "function currentSnipeTaxBps(address) view returns (uint256)",
176
+ "function graduated() view returns (bool)",
177
+ "function token() view returns (address)",
178
+ "function factory() view returns (address)",
179
+ "function isNativeQuote() view returns (bool)",
180
+ "function realQuoteReserve() view returns (uint256)",
181
+ "function graduationThreshold() view returns (uint256)",
182
+ "function sellableTokens() view returns (uint256)"
183
+ ]);
184
+ var ponsFactoryAbi = parseAbi(["function getLaunchedToken(address token) view returns (address token_, address curve)"]);
185
+ var rushrPonsRouterAbi = parseAbi([
186
+ "function buy(address token, uint256 minTokensOut, address recipient, uint256 deadline, bool referred) payable returns (uint256 tokensOut)",
187
+ "function sell(address token, uint256 tokensIn, uint256 minQuoteOut, address recipient, uint256 deadline, bool referred) returns (uint256 quoteOut)",
188
+ "function feeBps() view returns (uint16)",
189
+ "function referralFeeBps() view returns (uint16)",
190
+ "function treasury() view returns (address)"
191
+ ]);
192
+ var knownErrorsAbi = parseAbi([
193
+ "error V3TooLittleReceived()",
194
+ "error V2TooLittleReceived()",
195
+ "error V4TooLittleReceived(uint256 minAmountOutReceived, uint256 amountReceived)",
196
+ "error InsufficientETH()",
197
+ "error InsufficientToken()",
198
+ "error TransactionDeadlinePassed()",
199
+ "error ExecutionFailed(uint256 commandIndex, bytes message)",
200
+ "error AllowanceExpired(uint256 deadline)",
201
+ "error InsufficientAllowance(uint256 amount)",
202
+ "error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed)",
203
+ "error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)",
204
+ "error NotEnoughLiquidity(bytes32 poolId)",
205
+ "error UnexpectedRevertBytes(bytes revertData)",
206
+ "error WrappedError(address target, bytes4 selector, bytes reason, bytes details)",
207
+ "error PoolNotInitialized()",
208
+ "error PriceLimitAlreadyExceeded(uint160 sqrtPriceCurrentX96, uint160 sqrtPriceLimitX96)",
209
+ "error SlippageExceeded(uint256 received, uint256 minimum)",
210
+ "error UnknownCurve(address token)",
211
+ "error CurveGraduated(address token)",
212
+ "error CurveGraduated()",
213
+ // the live PONS curve (0x025ac17e)
214
+ "error DeadlinePassed()",
215
+ "error Reentrancy()",
216
+ "error EthTransferFailed()",
217
+ "error TokenCallFailed()",
218
+ "error Error(string)"
219
+ ]);
220
+
221
+ // ../core/src/chain/robinhood.ts
222
+ import { parseAbi as parseAbi2 } from "viem";
139
223
  var ROBINHOOD_CHAIN = {
140
224
  id: 4663,
141
225
  name: "Robinhood Chain",
@@ -170,32 +254,32 @@ var UNISWAP = {
170
254
  permit2: "0x000000000022d473030f116ddee9f6b43ac78ba3"
171
255
  };
172
256
  var ABIS = {
173
- erc20: parseAbi([
257
+ erc20: parseAbi2([
174
258
  "event Transfer(address indexed from, address indexed to, uint256 value)",
175
259
  "function name() view returns (string)",
176
260
  "function symbol() view returns (string)",
177
261
  "function decimals() view returns (uint8)",
178
262
  "function totalSupply() view returns (uint256)"
179
263
  ]),
180
- v4PoolManager: parseAbi([
264
+ v4PoolManager: parseAbi2([
181
265
  "event Initialize(bytes32 indexed id, address indexed currency0, address indexed currency1, uint24 fee, int24 tickSpacing, address hooks, uint160 sqrtPriceX96, int24 tick)",
182
266
  "event Swap(bytes32 indexed id, address indexed sender, int128 amount0, int128 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint24 fee)",
183
267
  "event ModifyLiquidity(bytes32 indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt)"
184
268
  ]),
185
- v3: parseAbi([
269
+ v3: parseAbi2([
186
270
  "event PoolCreated(address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool)",
187
271
  "event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick)"
188
272
  ]),
189
273
  /** PancakeSwap v3 forks add protocol fees to the Swap event (same first words as Uniswap v3). */
190
- pancakeV3: parseAbi([
274
+ pancakeV3: parseAbi2([
191
275
  "event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint128 protocolFeesToken0, uint128 protocolFeesToken1)"
192
276
  ]),
193
- v2: parseAbi([
277
+ v2: parseAbi2([
194
278
  "event PairCreated(address indexed token0, address indexed token1, address pair, uint256)",
195
279
  "event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to)",
196
280
  "event Sync(uint112 reserve0, uint112 reserve1)"
197
281
  ]),
198
- dopplerAirlock: parseAbi([
282
+ dopplerAirlock: parseAbi2([
199
283
  "event Create(address asset, address indexed numeraire, address initializer, address poolOrHook)",
200
284
  "event Migrate(address indexed asset, address indexed pool)"
201
285
  ])
@@ -244,6 +328,24 @@ var TRADE_ADDRESSES = {
244
328
  }
245
329
  };
246
330
 
331
+ // ../trade/src/config.ts
332
+ import { getAddress, isAddress } from "viem";
333
+ var RUSHR_TREASURY = "0x2Ae062C61A757b66D3039154a6e965aa48Cd75F3";
334
+ var BETA_FEE_BPS = 25;
335
+ var DEFAULT_TRADE_CONFIG = {
336
+ feeBps: BETA_FEE_BPS,
337
+ // beta rate; STANDARD_FEE_BPS after the beta
338
+ referralDiscountBps: 1e3,
339
+ referrerShareBps: 2e3,
340
+ feeRecipient: RUSHR_TREASURY,
341
+ universalRouter: TRADE_ADDRESSES.universalRouter,
342
+ ponsRouter: null,
343
+ rushrRouter: null,
344
+ rushrRouterAudited: false,
345
+ defaultSlippageBps: 100,
346
+ deadlineSeconds: 300
347
+ };
348
+
247
349
  // src/guards.ts
248
350
  var GuardError = class extends Error {
249
351
  code;
@@ -255,6 +357,7 @@ var GuardError = class extends Error {
255
357
  this.details = details;
256
358
  }
257
359
  };
360
+ var isCurve = (q) => q.pool.venue === "pons-curve";
258
361
  var ROUTERS = /* @__PURE__ */ new Set([TRADE_ADDRESSES.universalRouter.toLowerCase()]);
259
362
  var PERMIT2 = TRADE_ADDRESSES.permit2.toLowerCase();
260
363
  var CHAIN_ID = TRADE_ADDRESSES.chainId;
@@ -262,7 +365,9 @@ var SELECTOR_ERC20_APPROVE = "0x095ea7b3";
262
365
  var SELECTOR_PERMIT2_APPROVE = "0x87517c45";
263
366
  var MAX_FEE_BPS = 25;
264
367
  function vetBuild(b, side, token, amountIn, opts = {}) {
368
+ if (isCurve(b.quote)) return vetCurveBuild(b, side, token, amountIn, { trader: opts.trader, curveOnChain: opts.curveOnChain, requireSimulation: opts.requireSimulation });
265
369
  const problems = [];
370
+ if (b.followUp) problems.push("a Uniswap build asked for a follow-up transaction");
266
371
  if (b.tx.chainId !== CHAIN_ID) problems.push(`chainId ${b.tx.chainId}`);
267
372
  if (!ROUTERS.has(b.tx.to.toLowerCase())) problems.push(`unexpected tx.to ${b.tx.to}`);
268
373
  if (side === "buy" && BigInt(b.tx.value) !== amountIn) problems.push(`tx.value ${b.tx.value} != amountIn ${amountIn}`);
@@ -335,9 +440,79 @@ var SpendLedger = class {
335
440
  function checkSafety(s) {
336
441
  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
442
  }
443
+ var TREASURY = RUSHR_TREASURY.toLowerCase();
444
+ var MAX_AUTO_FEE_WEI = parseEther2("0.005");
445
+ var sameAddr = (a, b) => !!a && !!b && a.toLowerCase() === b.toLowerCase();
446
+ function feeTxProblems(tx, value, label) {
447
+ if (!tx) return [`${label}: missing tx`];
448
+ const p = [];
449
+ if (tx.chainId !== void 0 && tx.chainId !== CHAIN_ID) p.push(`${label}: chainId ${tx.chainId}`);
450
+ if (!sameAddr(tx.to, TREASURY)) p.push(`${label}: sends to ${tx.to}, not the treasury ${RUSHR_TREASURY}`);
451
+ if (tx.data && tx.data !== "0x") p.push(`${label}: has calldata`);
452
+ if (BigInt(tx.value) !== value) p.push(`${label}: value ${tx.value} != ${value}`);
453
+ return p;
454
+ }
455
+ function vetCurveBuild(b, side, token, amountIn, opts = {}) {
456
+ const problems = [];
457
+ const curve = (b.quote.pool.curve ?? b.quote.pool.id ?? "").toLowerCase();
458
+ if (!/^0x[0-9a-f]{40}$/.test(curve)) problems.push("quote names no curve address");
459
+ if (b.tx.chainId !== CHAIN_ID) problems.push(`chainId ${b.tx.chainId}`);
460
+ if (!sameAddr(b.tx.to, curve)) problems.push(`tx.to ${b.tx.to} is not the quoted curve ${curve}`);
461
+ if (!opts.curveOnChain) problems.push("couldn't confirm the token's PONS curve on-chain");
462
+ else if (!sameAddr(curve, opts.curveOnChain)) problems.push(`quoted curve ${curve} is not the token's PONS curve ${opts.curveOnChain}`);
463
+ try {
464
+ const call = decodeFunctionData({ abi: ponsCurveAbi, data: b.tx.data });
465
+ if (call.functionName !== side) problems.push(`calldata calls ${call.functionName}, expected ${side}`);
466
+ else {
467
+ const [amt, , recipient] = call.args;
468
+ if (amt !== amountIn) problems.push(`calldata amount ${amt} != ${amountIn}`);
469
+ if (!opts.trader || !sameAddr(recipient, opts.trader)) problems.push(`recipient ${recipient} is not this wallet`);
470
+ }
471
+ } catch {
472
+ problems.push("calldata is not a PONS curve buy or sell");
473
+ }
474
+ if (side === "buy" && BigInt(b.tx.value) !== amountIn) problems.push(`tx.value ${b.tx.value} != amountIn ${amountIn}`);
475
+ if (side === "sell" && BigInt(b.tx.value) !== 0n) problems.push(`sell with value ${b.tx.value}`);
476
+ if (BigInt(b.quote.amountIn) !== amountIn) problems.push("quote.amountIn differs from the request");
477
+ if (b.quote.fee.feeBps > MAX_FEE_BPS) problems.push(`fee ${b.quote.fee.feeBps} bps (max ${MAX_FEE_BPS})`);
478
+ if (side === "buy" && b.approvals.length) problems.push("curve buy asked for approvals");
479
+ for (const a of b.approvals) {
480
+ let ok2 = a.kind === "curve" && sameAddr(a.tx.to, token) && BigInt(a.tx.value) === 0n;
481
+ try {
482
+ const d = decodeFunctionData({ abi: erc20Abi2, data: a.tx.data });
483
+ ok2 &&= d.functionName === "approve" && sameAddr(d.args[0], curve);
484
+ } catch {
485
+ ok2 = false;
486
+ }
487
+ if (!ok2) problems.push(`unexpected approval ${a.kind} to ${a.tx.to}`);
488
+ }
489
+ const f = b.followUp;
490
+ if (!f) problems.push("curve build has no fee follow-up");
491
+ else {
492
+ const fee = BigInt(f.amount);
493
+ if (f.kind !== "rushr_fee" || f.after !== "tx") problems.push(`follow-up is ${f.kind}/${f.after}`);
494
+ if (fee !== BigInt(b.quote.fee.feeAmount)) problems.push(`follow-up fee ${fee} != quoted fee ${b.quote.fee.feeAmount}`);
495
+ problems.push(...feeTxProblems(f.tx, fee, "follow-up"));
496
+ const ethSide = side === "buy" ? amountIn : BigInt(b.quote.amountOut) + fee;
497
+ if (fee * 10000n > ethSide * BigInt(MAX_FEE_BPS)) problems.push(`follow-up fee ${fee} is above ${MAX_FEE_BPS} bps of ${ethSide}`);
498
+ }
499
+ if (opts.requireSimulation !== false && !b.simulation?.ok) problems.push(`simulation failed: ${b.simulation?.error ?? "missing"}`);
500
+ if (problems.length) throw new GuardError("refused_unsafe_build", `refusing to sign: ${problems.join("; ")}`, { problems });
501
+ }
502
+ function checkFeeUnpaid(e, i) {
503
+ const owed = BigInt(e.owed);
504
+ const problems = feeTxProblems(e.feeTx, owed, "feeTx");
505
+ if (owed <= 0n) problems.push("nothing owed");
506
+ if (problems.length) throw new GuardError("refused_fee_tx", `won't pay this fee transfer: ${problems.join("; ")}`, { owed: e.owed });
507
+ const pay = "Pay error.feeTx from this wallet yourself, then report the hash with POST /v1/agents/me/fees.";
508
+ 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 });
509
+ 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 });
510
+ 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 });
511
+ return owed;
512
+ }
338
513
 
339
514
  // src/price.ts
340
- import { formatEther, parseEther as parseEther2 } from "viem";
515
+ import { formatEther, parseEther as parseEther3 } from "viem";
341
516
  var WETH = TRADE_ADDRESSES.weth.toLowerCase();
342
517
  var USDG = TRADE_ADDRESSES.usdg.toLowerCase();
343
518
  function createEthUsd(api, f = fetch) {
@@ -359,11 +534,11 @@ function checkEthUsd(rushr, dex) {
359
534
  if (!(rushr > 500 && rushr < 2e4)) throw new GuardError("refused_price_out_of_band", `ETH/USD ${rushr} is outside $500-20,000`);
360
535
  return rushr;
361
536
  }
362
- var usdToWei = (usd2, ethUsd) => parseEther2((usd2 / ethUsd).toFixed(18));
537
+ var usdToWei = (usd2, ethUsd) => parseEther3((usd2 / ethUsd).toFixed(18));
363
538
  var weiToUsd = (wei, ethUsd) => Number(formatEther(wei)) * ethUsd;
364
539
 
365
540
  // src/rushr.ts
366
- import { createPublicClient, createWalletClient, erc20Abi, formatEther as formatEther2, http, parseEther as parseEther3 } from "viem";
541
+ import { createPublicClient, createWalletClient, erc20Abi as erc20Abi3, formatEther as formatEther2, http, parseEther as parseEther4, zeroAddress } from "viem";
367
542
 
368
543
  // ../trade/src/chain.ts
369
544
  import { defineChain } from "viem";
@@ -383,10 +558,15 @@ function viemChain(cfg, wallet) {
383
558
  const signer = wallet ? createWalletClient({ chain: robinhoodChain, transport, account: wallet.account }) : null;
384
559
  return {
385
560
  balance: (address2) => pub.getBalance({ address: address2 }),
386
- tokenBalance: (token, owner) => pub.readContract({ address: token, abi: erc20Abi, functionName: "balanceOf", args: [owner] }),
561
+ tokenBalance: (token, owner) => pub.readContract({ address: token, abi: erc20Abi3, functionName: "balanceOf", args: [owner] }),
562
+ async ponsCurve(token) {
563
+ const [, curve] = await pub.readContract({ address: TRADE_ADDRESSES.pons.factory, abi: ponsFactoryAbi, functionName: "getLaunchedToken", args: [token] });
564
+ return curve && curve !== zeroAddress ? curve : null;
565
+ },
566
+ nonce: (address2) => pub.getTransactionCount({ address: address2, blockTag: "pending" }),
387
567
  async send(tx) {
388
568
  if (!signer) throw new GuardError("no_wallet", "no wallet configured");
389
- return signer.sendTransaction({ to: tx.to, data: tx.data, value: tx.value });
569
+ return signer.sendTransaction({ to: tx.to, data: tx.data, value: tx.value, gas: tx.gas, nonce: tx.nonce });
390
570
  },
391
571
  async confirm(hash) {
392
572
  const r = await pub.waitForTransactionReceipt({ hash, timeout: 12e4 });
@@ -394,6 +574,8 @@ function viemChain(cfg, wallet) {
394
574
  }
395
575
  };
396
576
  }
577
+ var FEE_SEND_ATTEMPTS = 3;
578
+ var FEE_REPORT_ATTEMPTS = 5;
397
579
  function withDisclosure(body, symbol, holds) {
398
580
  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
581
  const text = body.trim();
@@ -406,6 +588,8 @@ var Rushr = class {
406
588
  this.d = d;
407
589
  }
408
590
  d;
591
+ /** Fee transfers this process paid but couldn't report yet: reported before any new fee is paid. */
592
+ unreported = /* @__PURE__ */ new Set();
409
593
  get cfg() {
410
594
  return this.d.cfg;
411
595
  }
@@ -456,11 +640,13 @@ var Rushr = class {
456
640
  const key = w.apiKey();
457
641
  const me = key ? await this.d.api("GET", "/v1/agents/me").catch(() => null) : null;
458
642
  const h = me?.member?.handle ?? handle2;
459
- const [holdings, pnl, rank, callouts] = await Promise.all([
643
+ const [holdings, pnl, rank, callouts, fees] = await Promise.all([
460
644
  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
645
  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
646
  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
647
+ 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,
648
+ // Rushr fees owed on PONS curve trades (paid as separate transfers).
649
+ 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
650
  ]);
465
651
  const free = bal > this.d.cfg.gasReserveWei ? bal - this.d.cfg.gasReserveWei : 0n;
466
652
  const spent = this.d.ledger.spent24h(this.now());
@@ -474,7 +660,9 @@ var Rushr = class {
474
660
  holdings,
475
661
  pnl,
476
662
  rank,
477
- callouts
663
+ callouts,
664
+ curveFees: fees,
665
+ ...this.unreported.size ? { unreportedFeePayments: [...this.unreported] } : {}
478
666
  };
479
667
  }
480
668
  // ------------------------------------------------------------------ trading
@@ -485,7 +673,7 @@ var Rushr = class {
485
673
  if (a.usd !== void 0) return { wei: usdToWei(a.usd, ethUsd), usd: a.usd, ethUsd };
486
674
  let wei;
487
675
  try {
488
- wei = parseEther3(a.amountEth);
676
+ wei = parseEther4(a.amountEth);
489
677
  } catch {
490
678
  throw new GuardError("invalid_amount", `amountEth "${a.amountEth}" is not an ETH amount`);
491
679
  }
@@ -529,6 +717,7 @@ var Rushr = class {
529
717
  ethUsd = a.ethUsd;
530
718
  } else amountIn = (await this.sellAmount(token, i)).amount;
531
719
  const { q, impact } = await this.quoteWithImpact(token, i.side, amountIn);
720
+ const curveFee = q.followUpFee ? BigInt(q.followUpFee) : 0n;
532
721
  const refusals = [];
533
722
  if (i.side === "buy") {
534
723
  if (!q.wouldBuild) refusals.push(`api: wouldBuild=false (${q.warnings.join("; ")})`);
@@ -540,7 +729,7 @@ var Rushr = class {
540
729
  try {
541
730
  const bal = await this.d.chain.balance(this.wallet().address);
542
731
  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 }));
732
+ 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
733
  } catch (e) {
545
734
  refusals.push(errText(e));
546
735
  }
@@ -555,6 +744,7 @@ var Rushr = class {
555
744
  fee: { bps: q.quote.fee.feeBps, amount: q.quote.fee.feeAmount },
556
745
  impact: impact ?? { totalBps: q.quote.priceImpactBps },
557
746
  venue: q.quote.pool.venue,
747
+ ...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
748
  safety: q.safety ? { riskLevel: q.safety.riskLevel, blocked: q.safety.blocked } : null,
559
749
  warnings: q.warnings,
560
750
  wouldTrade: i.side === "sell" ? true : refusals.length === 0,
@@ -571,40 +761,164 @@ var Rushr = class {
571
761
  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
762
  const { safety } = await this.d.api("GET", `/v1/tokens/${token}/safety`);
573
763
  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." };
764
+ const ethUsd = await this.d.ethUsd();
765
+ let feePaidFirst = null;
766
+ let attempt = 0;
767
+ let q, impact, b;
768
+ for (; ; ) {
769
+ ({ q, impact } = await this.quoteWithImpact(token, "buy", wei));
770
+ if (!q.wouldBuild) throw new GuardError("refused_would_not_build", `the API would refuse this build: ${q.warnings.join("; ") || "risk or price impact"}`);
771
+ checkImpact(impact, this.d.cfg);
772
+ try {
773
+ const r = await this.build(token, "buy", wei);
774
+ b = r.b;
775
+ feePaidFirst ??= r.feePaidFirst;
776
+ break;
777
+ } catch (e) {
778
+ if (e instanceof ApiError && e.code === "curve_graduated" && attempt++ === 0) continue;
779
+ throw e;
780
+ }
781
+ }
782
+ const curveOnChain = isCurve(b.quote) ? await this.d.chain.ponsCurve(token).catch(() => null) : void 0;
783
+ vetBuild(b, "buy", token, wei, { trader: w.address, curveOnChain });
784
+ const fee = b.followUp ? BigInt(b.followUp.amount) : 0n;
785
+ 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 }));
786
+ 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) };
787
+ 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
788
  const sent = await this.sendBuilt(b);
582
789
  this.d.ledger.record(usd2, sent.hash, this.now());
583
- return { status: "confirmed", ...summary, ...sent, warnings: b.warnings };
790
+ return this.result(summary, sent, b, feePaidFirst, ethUsd);
584
791
  }
585
792
  async sell(i) {
586
793
  const token = i.token.toLowerCase();
794
+ const w = this.wallet();
587
795
  this.key();
588
796
  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." };
797
+ let r;
798
+ try {
799
+ r = await this.build(token, "sell", amount);
800
+ } catch (e) {
801
+ if (!(e instanceof ApiError && e.code === "curve_graduated")) throw e;
802
+ r = await this.build(token, "sell", amount);
803
+ }
804
+ const { b, feePaidFirst } = r;
805
+ const curveOnChain = isCurve(b.quote) ? await this.d.chain.ponsCurve(token).catch(() => null) : void 0;
806
+ vetBuild(b, "sell", token, amount, { trader: w.address, curveOnChain });
807
+ 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) };
808
+ 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
809
  const sent = await this.sendBuilt(b);
594
- return { status: "confirmed", ...summary, ...sent, warnings: b.warnings };
810
+ return this.result(summary, sent, b, feePaidFirst, await this.d.ethUsd().catch(() => null));
811
+ }
812
+ /** The curve fee as the tools show it (nothing for Uniswap builds, whose fee is inside the swap). */
813
+ curveFeeView(b) {
814
+ if (!b.followUp) return {};
815
+ 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 } };
816
+ }
817
+ /** The tool result after sending: both hashes, and a status that never hides an unpaid fee. */
818
+ result(summary, sent, b, feePaidFirst, ethUsd) {
819
+ if (sent.fee && sent.fee.status !== "unpaid" && ethUsd) this.d.ledger.record(weiToUsd(BigInt(sent.fee.amountWei), ethUsd), sent.fee.hash, this.now());
820
+ const status = !sent.fee || sent.fee.status === "paid" ? "confirmed" : sent.fee.status === "paid_unreported" ? "confirmed_fee_unreported" : "confirmed_fee_unpaid";
821
+ return { status, ...summary, hash: sent.hash, explorer: sent.explorer, approvals: sent.approvals, ...sent.fee ? { fee: sent.fee } : {}, ...feePaidFirst ? { overdueFeePaid: feePaidFirst } : {}, warnings: b.warnings };
822
+ }
823
+ /**
824
+ * POST /v1/trade/build (simulated). On 402 `fee_unpaid` (an overdue curve fee blocks builds), pays the
825
+ * overdue transfer when checkFeeUnpaid allows it, reports it, and builds once more. In dry run it
826
+ * refuses instead: paying is a real transaction.
827
+ */
828
+ async build(token, side, amountIn) {
829
+ const body = { ...this.body(token, side, amountIn), simulate: true };
830
+ try {
831
+ return { b: await this.d.api("POST", "/v1/trade/build", { body }), feePaidFirst: null };
832
+ } catch (e) {
833
+ if (!(e instanceof ApiError && e.code === "fee_unpaid")) throw e;
834
+ const info = e.body?.error ?? {};
835
+ let reported = false;
836
+ for (const h of [...this.unreported]) {
837
+ const ok2 = await this.d.api("POST", "/v1/agents/me/fees", { body: { txHash: h } }).then(
838
+ () => true,
839
+ (err) => err instanceof ApiError && err.code === "already_reported"
840
+ );
841
+ if (ok2) {
842
+ this.unreported.delete(h);
843
+ reported = true;
844
+ }
845
+ }
846
+ if (reported && !this.unreported.size) return { b: await this.d.api("POST", "/v1/trade/build", { body }), feePaidFirst: null };
847
+ 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] });
848
+ 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 });
849
+ const ethUsd = await this.d.ethUsd();
850
+ const bal = await this.d.chain.balance(this.wallet().address);
851
+ const free = bal > this.d.cfg.gasReserveWei ? bal - this.d.cfg.gasReserveWei : 0n;
852
+ 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 });
853
+ const paid = await this.payFee(info.feeTx, owed);
854
+ if (paid.status !== "unpaid") this.d.ledger.record(weiToUsd(owed, ethUsd), paid.hash, this.now());
855
+ 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 });
856
+ return { b: await this.d.api("POST", "/v1/trade/build", { body }), feePaidFirst: paid };
857
+ }
595
858
  }
596
- /** Approvals in order, then the swap. Each confirmed before the next. Refuses a build too close to its deadline. */
859
+ /**
860
+ * Approvals in order, then the trade, each confirmed before the next. Uniswap builds are refused
861
+ * within 30 s of their deadline; curve builds have none. A curve build's fee transfer follows the
862
+ * confirmed trade (payFee), and its outcome is always returned.
863
+ */
597
864
  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");
865
+ 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
866
  const approvals = [];
600
867
  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) });
868
+ const h = await this.d.chain.send(toSend(a.tx));
602
869
  await this.d.chain.confirm(h);
603
870
  approvals.push({ kind: a.kind, hash: h, explorer: this.explorerTx(h) });
604
871
  }
605
- const hash = await this.d.chain.send({ to: b.tx.to, data: b.tx.data, value: BigInt(b.tx.value) });
872
+ const hash = await this.d.chain.send(toSend(b.tx));
606
873
  await this.d.chain.confirm(hash);
607
- return { hash, explorer: this.explorerTx(hash), approvals };
874
+ const fee = b.followUp ? await this.payFee(b.followUp.tx, BigInt(b.followUp.amount)) : null;
875
+ return { hash, explorer: this.explorerTx(hash), approvals, fee };
876
+ }
877
+ /**
878
+ * Sends a fee transfer and reports it (POST /v1/agents/me/fees). Every attempt uses the same nonce, so a
879
+ * retry after an attempt that did go through is rejected by the chain instead of paying twice.
880
+ */
881
+ async payFee(tx, amount) {
882
+ const base = { amountWei: amount.toString(), amountEth: formatEther2(amount) };
883
+ 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.`;
884
+ const sleep = this.d.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
885
+ let nonce;
886
+ try {
887
+ nonce = await this.d.chain.nonce(this.wallet().address);
888
+ } catch (e) {
889
+ return { status: "unpaid", ...base, attempts: 0, error: errText(e), action: owe };
890
+ }
891
+ let hash = null;
892
+ let attempts = 0;
893
+ let lastError = "";
894
+ while (attempts < FEE_SEND_ATTEMPTS && !hash) {
895
+ attempts++;
896
+ try {
897
+ const h = await this.d.chain.send({ ...toSend(tx), value: amount, nonce });
898
+ await this.d.chain.confirm(h);
899
+ hash = h;
900
+ } catch (e) {
901
+ lastError = errText(e);
902
+ if (e instanceof GuardError && e.code === "tx_reverted") nonce = await this.d.chain.nonce(this.wallet().address).catch(() => nonce);
903
+ 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}` };
904
+ if (attempts < FEE_SEND_ATTEMPTS) await sleep(3e3 * attempts);
905
+ }
906
+ }
907
+ if (!hash) return { status: "unpaid", ...base, attempts, error: lastError, action: owe };
908
+ const sent = { ...base, hash, explorer: this.explorerTx(hash), attempts };
909
+ for (let r = 0; r < FEE_REPORT_ATTEMPTS; r++) {
910
+ try {
911
+ await this.d.api("POST", "/v1/agents/me/fees", { body: { txHash: hash } });
912
+ return { status: "paid", ...sent };
913
+ } catch (e) {
914
+ if (e instanceof ApiError && e.code === "already_reported") return { status: "paid", ...sent };
915
+ lastError = errText(e);
916
+ if (!(e instanceof ApiError && (e.code === "tx_not_found" || e.code === "rate_limited" || e.status >= 500))) break;
917
+ await sleep(5e3);
918
+ }
919
+ }
920
+ this.unreported.add(hash);
921
+ 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
922
  }
609
923
  // ------------------------------------------------------------------ social
610
924
  async postCallout(i) {
@@ -629,8 +943,7 @@ var Rushr = class {
629
943
  const r = await this.d.api("GET", `/tokens`, { auth: false, query: { column: i.column } });
630
944
  return {
631
945
  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 }))
946
+ 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
947
  };
635
948
  }
636
949
  async token(address2) {
@@ -642,7 +955,8 @@ var Rushr = class {
642
955
  symbol: pick("symbol"),
643
956
  name: pick("name"),
644
957
  status: pick("status"),
645
- tradable: detail.status === void 0 ? null : detail.status === "migrated",
958
+ launchpad: pick("launchpad"),
959
+ tradeVia: tradeVia(detail.status, detail.launchpad),
646
960
  priceUsd: pick("price_usd"),
647
961
  mcapUsd: pick("market_cap_usd"),
648
962
  liquidityUsd: pick("liquidity_usd"),
@@ -675,6 +989,12 @@ var Rushr = class {
675
989
  }
676
990
  };
677
991
  var round2 = (n) => Math.round(n * 100) / 100;
992
+ function tradeVia(status, launchpad) {
993
+ if (status === "migrated") return "uniswap";
994
+ if (launchpad === "pons") return "pons-curve";
995
+ return null;
996
+ }
997
+ var toSend = (tx) => ({ to: tx.to, data: tx.data || "0x", value: BigInt(tx.value), gas: tx.gas ? BigInt(tx.gas) : void 0 });
678
998
  var num2 = (v) => typeof v === "number" && Number.isFinite(v) ? round2(v) : null;
679
999
  function compactSim(s) {
680
1000
  if (!s) return null;
@@ -694,7 +1014,7 @@ var ethAmount = z.string().regex(/^\d+(\.\d{1,18})?$/, 'an ETH amount like "0.00
694
1014
  var usd = z.number().positive().max(1e5).describe("USD value to spend. Capped by RUSHR_MAX_TRADE_USD and RUSHR_DAILY_USD.");
695
1015
  var schemas = {
696
1016
  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)."),
1017
+ column: z.enum(["new", "almost", "migrated"]).default("migrated").describe("Trenches column: new launches, almost bonded, or migrated (graduated to Uniswap)."),
698
1018
  limit: z.number().int().min(1).max(50).default(15)
699
1019
  },
700
1020
  token: { address: address.describe("Token contract address.") },
@@ -727,7 +1047,7 @@ var schemas = {
727
1047
  amount: z.string().regex(/^\d+$/).optional().describe("Sell: exact token base units (or use percent).")
728
1048
  },
729
1049
  buy: {
730
- token: address.describe("Graduated token to buy with ETH."),
1050
+ token: address.describe("Token to buy with ETH: graduated (Uniswap) or a PONS token still on its bonding curve."),
731
1051
  usd: usd.optional(),
732
1052
  amountEth: ethAmount.optional().describe("ETH to spend instead of usd.")
733
1053
  },
@@ -753,7 +1073,7 @@ function registerTools(server, r) {
753
1073
  const cfg = publicConfig(r.cfg);
754
1074
  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
1075
  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)));
1076
+ 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
1077
  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
1078
  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
1079
  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)));
@@ -770,12 +1090,12 @@ function registerTools(server, r) {
770
1090
  );
771
1091
  server.registerTool(
772
1092
  "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 } },
1093
+ { 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
1094
  (a) => run(() => r.buy(a))
775
1095
  );
776
1096
  server.registerTool(
777
1097
  "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 } },
1098
+ { 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
1099
  (a) => run(() => r.sell(a))
780
1100
  );
781
1101
  server.registerTool(
@@ -847,14 +1167,14 @@ function loadWallet(c) {
847
1167
  }
848
1168
 
849
1169
  // src/server.ts
850
- var VERSION = "0.1.0";
1170
+ var VERSION = "0.1.1";
851
1171
  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.`;
1172
+ 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, 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
1173
  function createServer(cfg, overrides = {}) {
854
1174
  const wallet = loadWallet(cfg);
855
1175
  const api = createApi({ baseUrl: cfg.apiUrl, apiKey: () => wallet?.apiKey(), fetch: overrides.fetch, userAgent: `rushr-mcp/${VERSION} (+https://github.com/rushr-dev/platform)` });
856
1176
  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 });
1177
+ const rushr = new Rushr({ cfg, api, wallet, chain: overrides.chain ?? viemChain(cfg, wallet), ethUsd: createEthUsd(api, overrides.fetch), ledger, sleep: overrides.sleep });
858
1178
  const server = new McpServer({ name: "rushr", version: VERSION }, { instructions: INSTRUCTIONS });
859
1179
  registerTools(server, rushr);
860
1180
  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.1",
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.1",
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.1",
15
15
  "runtimeHint": "npx",
16
16
  "transport": { "type": "stdio" },
17
17
  "environmentVariables": [