@rushr/mcp 0.0.0-stage → 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/LICENSE +661 -0
- package/README.md +189 -2
- package/dist/index.js +1194 -0
- package/package.json +49 -3
- package/server.json +27 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1194 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
|
|
6
|
+
// src/config.ts
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { parseEther } from "viem";
|
|
10
|
+
var ConfigError = class extends Error {
|
|
11
|
+
};
|
|
12
|
+
var DEFAULTS = {
|
|
13
|
+
apiUrl: "https://api.rushr.trade",
|
|
14
|
+
rpcUrl: "https://rpc.mainnet.chain.robinhood.com",
|
|
15
|
+
explorerUrl: "https://robinhoodchain.blockscout.com",
|
|
16
|
+
maxTradeUsd: 10,
|
|
17
|
+
dailyUsd: 50,
|
|
18
|
+
gasReserveEth: "0.001",
|
|
19
|
+
maxSizeImpactBps: 300,
|
|
20
|
+
maxTotalImpactBps: 500,
|
|
21
|
+
slippageBps: 150
|
|
22
|
+
};
|
|
23
|
+
var CEILINGS = { maxSizeImpactBps: 300, maxTotalImpactBps: 500, slippageBps: 500 };
|
|
24
|
+
function positive(env, name, def, max) {
|
|
25
|
+
const raw = env[name];
|
|
26
|
+
if (raw === void 0 || raw === "") return def;
|
|
27
|
+
const n = Number(raw);
|
|
28
|
+
if (!Number.isFinite(n) || n <= 0) throw new ConfigError(`${name} must be a positive number (got "${raw}")`);
|
|
29
|
+
if (max !== void 0 && n > max) throw new ConfigError(`${name} can't be above ${max} (got ${n})`);
|
|
30
|
+
return n;
|
|
31
|
+
}
|
|
32
|
+
var truthy = (v) => v !== void 0 && /^(1|true|yes|on)$/i.test(v.trim());
|
|
33
|
+
function loadConfig(env = process.env) {
|
|
34
|
+
const gasReserveEth = env.RUSHR_GAS_RESERVE_ETH || DEFAULTS.gasReserveEth;
|
|
35
|
+
let gasReserveWei;
|
|
36
|
+
try {
|
|
37
|
+
gasReserveWei = parseEther(gasReserveEth);
|
|
38
|
+
} catch {
|
|
39
|
+
throw new ConfigError(`RUSHR_GAS_RESERVE_ETH must be an ETH amount like 0.001 (got "${gasReserveEth}")`);
|
|
40
|
+
}
|
|
41
|
+
if (gasReserveWei < parseEther(DEFAULTS.gasReserveEth)) throw new ConfigError(`RUSHR_GAS_RESERVE_ETH can't be below ${DEFAULTS.gasReserveEth}`);
|
|
42
|
+
const privateKey = env.RUSHR_PRIVATE_KEY?.trim() || void 0;
|
|
43
|
+
const walletFile = env.RUSHR_WALLET_FILE?.trim() || void 0;
|
|
44
|
+
if (privateKey && walletFile) throw new ConfigError("Set RUSHR_PRIVATE_KEY or RUSHR_WALLET_FILE, not both");
|
|
45
|
+
return {
|
|
46
|
+
apiUrl: (env.RUSHR_API_URL || DEFAULTS.apiUrl).replace(/\/$/, ""),
|
|
47
|
+
rpcUrl: env.RUSHR_RPC_URL || DEFAULTS.rpcUrl,
|
|
48
|
+
explorerUrl: DEFAULTS.explorerUrl,
|
|
49
|
+
maxTradeUsd: positive(env, "RUSHR_MAX_TRADE_USD", DEFAULTS.maxTradeUsd),
|
|
50
|
+
dailyUsd: positive(env, "RUSHR_DAILY_USD", DEFAULTS.dailyUsd),
|
|
51
|
+
dryRun: truthy(env.RUSHR_DRY_RUN),
|
|
52
|
+
gasReserveWei,
|
|
53
|
+
maxSizeImpactBps: positive(env, "RUSHR_MAX_SIZE_IMPACT_BPS", DEFAULTS.maxSizeImpactBps, CEILINGS.maxSizeImpactBps),
|
|
54
|
+
maxTotalImpactBps: positive(env, "RUSHR_MAX_TOTAL_IMPACT_BPS", DEFAULTS.maxTotalImpactBps, CEILINGS.maxTotalImpactBps),
|
|
55
|
+
slippageBps: positive(env, "RUSHR_SLIPPAGE_BPS", DEFAULTS.slippageBps, CEILINGS.slippageBps),
|
|
56
|
+
stateDir: env.RUSHR_STATE_DIR || join(homedir(), ".rushr"),
|
|
57
|
+
privateKey,
|
|
58
|
+
walletFile,
|
|
59
|
+
apiKey: env.RUSHR_API_KEY?.trim() || void 0
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function publicConfig(c) {
|
|
63
|
+
return {
|
|
64
|
+
dryRun: c.dryRun,
|
|
65
|
+
maxTradeUsd: c.maxTradeUsd,
|
|
66
|
+
dailyUsd: c.dailyUsd,
|
|
67
|
+
maxSizeImpactBps: c.maxSizeImpactBps,
|
|
68
|
+
maxTotalImpactBps: c.maxTotalImpactBps,
|
|
69
|
+
slippageBps: c.slippageBps,
|
|
70
|
+
gasReserveEth: Number(c.gasReserveWei) / 1e18
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/server.ts
|
|
75
|
+
import { join as join3 } from "node:path";
|
|
76
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
77
|
+
|
|
78
|
+
// src/api.ts
|
|
79
|
+
var ApiError = class extends Error {
|
|
80
|
+
status;
|
|
81
|
+
code;
|
|
82
|
+
body;
|
|
83
|
+
constructor(status, code, message, body) {
|
|
84
|
+
super(message);
|
|
85
|
+
this.name = "ApiError";
|
|
86
|
+
this.status = status;
|
|
87
|
+
this.code = code;
|
|
88
|
+
this.body = body;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
function createApi(o) {
|
|
92
|
+
const f = o.fetch ?? fetch;
|
|
93
|
+
const ua = o.userAgent ?? "rushr-mcp";
|
|
94
|
+
return async function api(method, path, opts = {}) {
|
|
95
|
+
const headers = { accept: "application/json", "user-agent": ua };
|
|
96
|
+
if (opts.auth !== false) {
|
|
97
|
+
const key = o.apiKey?.();
|
|
98
|
+
if (key) headers.authorization = `Bearer ${key}`;
|
|
99
|
+
}
|
|
100
|
+
if (opts.body !== void 0) headers["content-type"] = "application/json";
|
|
101
|
+
let url = o.baseUrl + path;
|
|
102
|
+
if (opts.query) {
|
|
103
|
+
const qs = new URLSearchParams();
|
|
104
|
+
for (const [k, v] of Object.entries(opts.query)) if (v !== void 0) qs.set(k, String(v));
|
|
105
|
+
const s = qs.toString();
|
|
106
|
+
if (s) url += (url.includes("?") ? "&" : "?") + s;
|
|
107
|
+
}
|
|
108
|
+
for (let attempt = 0; ; attempt++) {
|
|
109
|
+
const r = await f(url, { method, headers, body: opts.body === void 0 ? void 0 : JSON.stringify(opts.body) });
|
|
110
|
+
const text = await r.text();
|
|
111
|
+
let json = null;
|
|
112
|
+
try {
|
|
113
|
+
json = text ? JSON.parse(text) : null;
|
|
114
|
+
} catch {
|
|
115
|
+
json = null;
|
|
116
|
+
}
|
|
117
|
+
const e = json?.error;
|
|
118
|
+
if (r.status === 429 && attempt < 2) {
|
|
119
|
+
const wait = Math.min(Number(r.headers.get("retry-after") ?? (typeof e === "object" ? e.retryAfter : void 0) ?? 10) || 10, o.maxRetryWait ?? 30);
|
|
120
|
+
await new Promise((res) => setTimeout(res, wait * 1e3));
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (!r.ok) {
|
|
124
|
+
const code = typeof e === "object" && e ? String(e.code ?? "http_error") : r.status === 404 ? "not_found" : "http_error";
|
|
125
|
+
const message = typeof e === "object" && e ? String(e.message ?? "") : typeof e === "string" ? e : text.slice(0, 200);
|
|
126
|
+
throw new ApiError(r.status, code, message || `HTTP ${r.status}`, json);
|
|
127
|
+
}
|
|
128
|
+
return json;
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// src/guards.ts
|
|
134
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
135
|
+
import { dirname } from "node:path";
|
|
136
|
+
import { decodeFunctionData, erc20Abi as erc20Abi2, parseEther as parseEther2 } from "viem";
|
|
137
|
+
|
|
138
|
+
// ../trade/src/abis.ts
|
|
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";
|
|
223
|
+
var ROBINHOOD_CHAIN = {
|
|
224
|
+
id: 4663,
|
|
225
|
+
name: "Robinhood Chain",
|
|
226
|
+
nativeSymbol: "ETH",
|
|
227
|
+
publicRpc: "https://rpc.mainnet.chain.robinhood.com",
|
|
228
|
+
explorer: "https://robinhoodchain.blockscout.com",
|
|
229
|
+
/** Measured average over 10,000 blocks. Arbitrum Orbit (Nitro). */
|
|
230
|
+
blockTimeSeconds: 0.11,
|
|
231
|
+
/** Nitro L2 blocks don't reorg in practice before L1 posting; keep a small safety margin. */
|
|
232
|
+
confirmations: 20
|
|
233
|
+
};
|
|
234
|
+
var NATIVE_ETH = "0x0000000000000000000000000000000000000000";
|
|
235
|
+
var QUOTES = {
|
|
236
|
+
WETH: "0x0bd7d308f8e1639fab988df18a8011f41eacad73",
|
|
237
|
+
USDG: "0x5fc5360d0400a0fd4f2af552add042d716f1d168"
|
|
238
|
+
// Global Dollar, 6 decimals
|
|
239
|
+
};
|
|
240
|
+
var PRICE_QUOTES = [NATIVE_ETH, QUOTES.WETH, QUOTES.USDG];
|
|
241
|
+
var UNISWAP = {
|
|
242
|
+
v4: {
|
|
243
|
+
poolManager: "0x8366a39cc670b4001a1121b8f6a443a643e40951",
|
|
244
|
+
positionManager: "0x58daec3116aae6d93017baaea7749052e8a04fa7",
|
|
245
|
+
universalRouter: "0x8876789976decbfcbbbe364623c63652db8c0904",
|
|
246
|
+
quoter: "0x8dc178efb8111bb0973dd9d722ebeff267c98f94"
|
|
247
|
+
},
|
|
248
|
+
v3: {
|
|
249
|
+
factories: ["0x1f7d7550b1b028f7571e69a784071f0205fd2efa", "0xe7fef2bc860b25bbdeb6f6ab96d88baaa77ddad7"]
|
|
250
|
+
},
|
|
251
|
+
v2: {
|
|
252
|
+
factories: ["0x8bceaa40b9acdfaedf85adf4ff01f5ad6517937f", "0x0d1ebb179cdbca88d74c923c4255cb2b17474afd"]
|
|
253
|
+
},
|
|
254
|
+
permit2: "0x000000000022d473030f116ddee9f6b43ac78ba3"
|
|
255
|
+
};
|
|
256
|
+
var ABIS = {
|
|
257
|
+
erc20: parseAbi2([
|
|
258
|
+
"event Transfer(address indexed from, address indexed to, uint256 value)",
|
|
259
|
+
"function name() view returns (string)",
|
|
260
|
+
"function symbol() view returns (string)",
|
|
261
|
+
"function decimals() view returns (uint8)",
|
|
262
|
+
"function totalSupply() view returns (uint256)"
|
|
263
|
+
]),
|
|
264
|
+
v4PoolManager: parseAbi2([
|
|
265
|
+
"event Initialize(bytes32 indexed id, address indexed currency0, address indexed currency1, uint24 fee, int24 tickSpacing, address hooks, uint160 sqrtPriceX96, int24 tick)",
|
|
266
|
+
"event Swap(bytes32 indexed id, address indexed sender, int128 amount0, int128 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint24 fee)",
|
|
267
|
+
"event ModifyLiquidity(bytes32 indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt)"
|
|
268
|
+
]),
|
|
269
|
+
v3: parseAbi2([
|
|
270
|
+
"event PoolCreated(address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool)",
|
|
271
|
+
"event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick)"
|
|
272
|
+
]),
|
|
273
|
+
/** PancakeSwap v3 forks add protocol fees to the Swap event (same first words as Uniswap v3). */
|
|
274
|
+
pancakeV3: parseAbi2([
|
|
275
|
+
"event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint128 protocolFeesToken0, uint128 protocolFeesToken1)"
|
|
276
|
+
]),
|
|
277
|
+
v2: parseAbi2([
|
|
278
|
+
"event PairCreated(address indexed token0, address indexed token1, address pair, uint256)",
|
|
279
|
+
"event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to)",
|
|
280
|
+
"event Sync(uint112 reserve0, uint112 reserve1)"
|
|
281
|
+
]),
|
|
282
|
+
dopplerAirlock: parseAbi2([
|
|
283
|
+
"event Create(address asset, address indexed numeraire, address initializer, address poolOrHook)",
|
|
284
|
+
"event Migrate(address indexed asset, address indexed pool)"
|
|
285
|
+
])
|
|
286
|
+
};
|
|
287
|
+
var INFRA_ADDRESSES = [
|
|
288
|
+
UNISWAP.v4.poolManager,
|
|
289
|
+
UNISWAP.v4.positionManager,
|
|
290
|
+
UNISWAP.v4.universalRouter,
|
|
291
|
+
"0x204faca1764b154221e35c0d20abb3c525710498",
|
|
292
|
+
// Universal Router (current; the one Rushr builds swaps for)
|
|
293
|
+
UNISWAP.permit2,
|
|
294
|
+
"0x5ff137d4b0fdcd49dca30c7cf57e578a026d2789",
|
|
295
|
+
// ERC-4337 EntryPoint v0.6
|
|
296
|
+
"0x0000000000000000000000000000000000000000",
|
|
297
|
+
"0x000000000000000000000000000000000000dead"
|
|
298
|
+
];
|
|
299
|
+
|
|
300
|
+
// ../trade/src/addresses.ts
|
|
301
|
+
var TRADE_ADDRESSES = {
|
|
302
|
+
chainId: 4663,
|
|
303
|
+
eth: NATIVE_ETH,
|
|
304
|
+
weth: QUOTES.WETH,
|
|
305
|
+
usdg: QUOTES.USDG,
|
|
306
|
+
permit2: UNISWAP.permit2,
|
|
307
|
+
/** Universal Router v2.1.2, Uniswap's official deployment for 4663. */
|
|
308
|
+
universalRouter: "0x204faca1764b154221e35c0d20abb3c525710498",
|
|
309
|
+
/** Older Universal Router in the core registry; same factories embedded, busier on-chain. */
|
|
310
|
+
universalRouterLegacy: UNISWAP.v4.universalRouter,
|
|
311
|
+
v4: {
|
|
312
|
+
poolManager: UNISWAP.v4.poolManager,
|
|
313
|
+
positionManager: UNISWAP.v4.positionManager,
|
|
314
|
+
quoter: UNISWAP.v4.quoter,
|
|
315
|
+
stateView: "0xf3334192d15450cdd385c8b70e03f9a6bd9e673b"
|
|
316
|
+
},
|
|
317
|
+
v3: {
|
|
318
|
+
factory: "0x1f7d7550b1b028f7571e69a784071f0205fd2efa",
|
|
319
|
+
quoterV2: "0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7"
|
|
320
|
+
},
|
|
321
|
+
v2: {
|
|
322
|
+
factory: "0x8bceaa40b9acdfaedf85adf4ff01f5ad6517937f",
|
|
323
|
+
router02: "0x89e5db8b5aa49aa85ac63f691524311aeb649eba"
|
|
324
|
+
},
|
|
325
|
+
pons: {
|
|
326
|
+
/** PONS launch factory: getLaunchedToken(token) -> (token, curve, creator, ...). */
|
|
327
|
+
factory: "0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e"
|
|
328
|
+
}
|
|
329
|
+
};
|
|
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
|
+
|
|
349
|
+
// src/guards.ts
|
|
350
|
+
var GuardError = class extends Error {
|
|
351
|
+
code;
|
|
352
|
+
details;
|
|
353
|
+
constructor(code, message, details) {
|
|
354
|
+
super(message);
|
|
355
|
+
this.name = "GuardError";
|
|
356
|
+
this.code = code;
|
|
357
|
+
this.details = details;
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
var isCurve = (q) => q.pool.venue === "pons-curve";
|
|
361
|
+
var ROUTERS = /* @__PURE__ */ new Set([TRADE_ADDRESSES.universalRouter.toLowerCase()]);
|
|
362
|
+
var PERMIT2 = TRADE_ADDRESSES.permit2.toLowerCase();
|
|
363
|
+
var CHAIN_ID = TRADE_ADDRESSES.chainId;
|
|
364
|
+
var SELECTOR_ERC20_APPROVE = "0x095ea7b3";
|
|
365
|
+
var SELECTOR_PERMIT2_APPROVE = "0x87517c45";
|
|
366
|
+
var MAX_FEE_BPS = 25;
|
|
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 });
|
|
369
|
+
const problems = [];
|
|
370
|
+
if (b.followUp) problems.push("a Uniswap build asked for a follow-up transaction");
|
|
371
|
+
if (b.tx.chainId !== CHAIN_ID) problems.push(`chainId ${b.tx.chainId}`);
|
|
372
|
+
if (!ROUTERS.has(b.tx.to.toLowerCase())) problems.push(`unexpected tx.to ${b.tx.to}`);
|
|
373
|
+
if (side === "buy" && BigInt(b.tx.value) !== amountIn) problems.push(`tx.value ${b.tx.value} != amountIn ${amountIn}`);
|
|
374
|
+
if (side === "sell" && BigInt(b.tx.value) !== 0n) problems.push(`sell with value ${b.tx.value}`);
|
|
375
|
+
if (BigInt(b.quote.amountIn) !== amountIn) problems.push("quote.amountIn differs from the request");
|
|
376
|
+
if (b.quote.fee.feeBps > MAX_FEE_BPS) problems.push(`fee ${b.quote.fee.feeBps} bps (max ${MAX_FEE_BPS})`);
|
|
377
|
+
if (side === "buy" && b.approvals.length) problems.push("ETH buy asked for approvals");
|
|
378
|
+
for (const a of b.approvals) {
|
|
379
|
+
const to = a.tx.to.toLowerCase();
|
|
380
|
+
const sel = a.tx.data.slice(0, 10).toLowerCase();
|
|
381
|
+
const okErc20 = a.kind === "erc20" && to === token.toLowerCase() && sel === SELECTOR_ERC20_APPROVE;
|
|
382
|
+
const okPermit2 = a.kind === "permit2" && to === PERMIT2 && sel === SELECTOR_PERMIT2_APPROVE;
|
|
383
|
+
if (!okErc20 && !okPermit2) problems.push(`unexpected approval ${a.kind} to ${a.tx.to} (${sel})`);
|
|
384
|
+
if (BigInt(a.tx.value) !== 0n) problems.push("approval with value");
|
|
385
|
+
}
|
|
386
|
+
if (opts.requireSimulation !== false && !b.simulation?.ok) problems.push(`simulation failed: ${b.simulation?.error ?? "missing"}`);
|
|
387
|
+
if (problems.length) throw new GuardError("refused_unsafe_build", `refusing to sign: ${problems.join("; ")}`, { problems });
|
|
388
|
+
}
|
|
389
|
+
var probeAmount = (amountIn) => amountIn / 20n || 1n;
|
|
390
|
+
function splitImpact(totalBps, probeBps) {
|
|
391
|
+
if (totalBps == null) throw new GuardError("refused_price_impact", "quote has no price impact; refusing to guess");
|
|
392
|
+
const floorBps = Math.max(0, Math.min(probeBps ?? 0, totalBps));
|
|
393
|
+
return { totalBps, floorBps, sizeBps: totalBps - floorBps };
|
|
394
|
+
}
|
|
395
|
+
function checkImpact(i, caps) {
|
|
396
|
+
const what = `impact ${i.totalBps} bps (${i.floorBps} fixed pool tax + ${i.sizeBps} from size)`;
|
|
397
|
+
if (i.sizeBps > caps.maxSizeImpactBps) throw new GuardError("refused_size_impact", `${what}: size impact over ${caps.maxSizeImpactBps} bps. Try a smaller amount.`, { ...i });
|
|
398
|
+
if (i.totalBps > caps.maxTotalImpactBps) throw new GuardError("refused_total_impact", `${what}: total over ${caps.maxTotalImpactBps} bps`, { ...i });
|
|
399
|
+
}
|
|
400
|
+
function checkBuyCaps(i) {
|
|
401
|
+
if (!(i.usd > 0) || i.amountWei <= 0n) throw new GuardError("refused_amount", "amount must be positive");
|
|
402
|
+
if (i.usd > i.maxTradeUsd + 1e-9) throw new GuardError("refused_trade_cap", `$${i.usd.toFixed(2)} is above the per-trade cap of $${i.maxTradeUsd} (RUSHR_MAX_TRADE_USD)`, { usd: i.usd, maxTradeUsd: i.maxTradeUsd });
|
|
403
|
+
const left = Math.max(0, i.dailyUsd - i.spent24hUsd);
|
|
404
|
+
if (i.usd > left + 1e-9) throw new GuardError("refused_daily_cap", `$${i.usd.toFixed(2)} would pass the 24h cap of $${i.dailyUsd} (RUSHR_DAILY_USD): $${i.spent24hUsd.toFixed(2)} spent, $${left.toFixed(2)} left`, { usd: i.usd, dailyUsd: i.dailyUsd, spent24hUsd: i.spent24hUsd });
|
|
405
|
+
if (i.amountWei > i.freeWei) {
|
|
406
|
+
const msg = `needs ${i.amountWei} wei but only ${i.freeWei} wei is spendable after the gas reserve`;
|
|
407
|
+
if (!i.dryRun) throw new GuardError("refused_gas_reserve", msg, { amountWei: i.amountWei.toString(), freeWei: i.freeWei.toString() });
|
|
408
|
+
return [`live, this would be refused: ${msg}`];
|
|
409
|
+
}
|
|
410
|
+
return [];
|
|
411
|
+
}
|
|
412
|
+
var SpendLedger = class {
|
|
413
|
+
constructor(path) {
|
|
414
|
+
this.path = path;
|
|
415
|
+
if (path && existsSync(path)) {
|
|
416
|
+
try {
|
|
417
|
+
this.entries = JSON.parse(readFileSync(path, "utf8")).entries ?? [];
|
|
418
|
+
} catch {
|
|
419
|
+
this.entries = [];
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
path;
|
|
424
|
+
entries = [];
|
|
425
|
+
spentSince(ms, now = Date.now()) {
|
|
426
|
+
return this.entries.filter((e) => e.at >= now - ms).reduce((s, e) => s + e.usd, 0);
|
|
427
|
+
}
|
|
428
|
+
spent24h(now = Date.now()) {
|
|
429
|
+
return this.spentSince(864e5, now);
|
|
430
|
+
}
|
|
431
|
+
record(usd2, hash, now = Date.now()) {
|
|
432
|
+
this.entries = [...this.entries.filter((e) => e.at >= now - 864e5), { at: now, usd: usd2, hash }];
|
|
433
|
+
if (this.path) {
|
|
434
|
+
mkdirSync(dirname(this.path), { recursive: true, mode: 448 });
|
|
435
|
+
writeFileSync(this.path, `${JSON.stringify({ entries: this.entries })}
|
|
436
|
+
`, { mode: 384 });
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
function checkSafety(s) {
|
|
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 });
|
|
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
|
+
}
|
|
513
|
+
|
|
514
|
+
// src/price.ts
|
|
515
|
+
import { formatEther, parseEther as parseEther3 } from "viem";
|
|
516
|
+
var WETH = TRADE_ADDRESSES.weth.toLowerCase();
|
|
517
|
+
var USDG = TRADE_ADDRESSES.usdg.toLowerCase();
|
|
518
|
+
function createEthUsd(api, f = fetch) {
|
|
519
|
+
let cache = null;
|
|
520
|
+
return async function ethUsd() {
|
|
521
|
+
if (cache && Date.now() - cache.at < 5 * 6e4) return cache.usd;
|
|
522
|
+
const rushr = await api("GET", "/transparency", { auth: false }).then((j) => j.treasury?.ethUsd ?? null).catch(() => null);
|
|
523
|
+
const dex = await f(`https://api.dexscreener.com/latest/dex/tokens/${WETH}`).then((r) => r.json()).then((j) => {
|
|
524
|
+
const pairs = (j.pairs ?? []).filter((p) => p.chainId === "robinhood" && p.baseToken.address.toLowerCase() === WETH && p.quoteToken.address.toLowerCase() === USDG && Number(p.priceUsd) > 0);
|
|
525
|
+
pairs.sort((a, b) => (b.liquidity?.usd ?? 0) - (a.liquidity?.usd ?? 0));
|
|
526
|
+
return pairs[0] ? Number(pairs[0].priceUsd) : null;
|
|
527
|
+
}).catch(() => null);
|
|
528
|
+
return (cache = { at: Date.now(), usd: checkEthUsd(rushr, dex) }).usd;
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
function checkEthUsd(rushr, dex) {
|
|
532
|
+
if (rushr === null || dex === null) throw new GuardError("refused_price_unavailable", `can't price ETH: Rushr ${rushr ?? "unavailable"}, DexScreener ${dex ?? "unavailable"}; refusing to size a trade`);
|
|
533
|
+
if (Math.abs(rushr - dex) / dex > 0.1) throw new GuardError("refused_price_disagreement", `ETH/USD sources disagree: Rushr $${rushr.toFixed(2)} vs DexScreener $${dex.toFixed(2)} (over 10%)`);
|
|
534
|
+
if (!(rushr > 500 && rushr < 2e4)) throw new GuardError("refused_price_out_of_band", `ETH/USD ${rushr} is outside $500-20,000`);
|
|
535
|
+
return rushr;
|
|
536
|
+
}
|
|
537
|
+
var usdToWei = (usd2, ethUsd) => parseEther3((usd2 / ethUsd).toFixed(18));
|
|
538
|
+
var weiToUsd = (wei, ethUsd) => Number(formatEther(wei)) * ethUsd;
|
|
539
|
+
|
|
540
|
+
// src/rushr.ts
|
|
541
|
+
import { createPublicClient, createWalletClient, erc20Abi as erc20Abi3, formatEther as formatEther2, http, parseEther as parseEther4, zeroAddress } from "viem";
|
|
542
|
+
|
|
543
|
+
// ../trade/src/chain.ts
|
|
544
|
+
import { defineChain } from "viem";
|
|
545
|
+
var robinhoodChain = defineChain({
|
|
546
|
+
id: ROBINHOOD_CHAIN.id,
|
|
547
|
+
name: ROBINHOOD_CHAIN.name,
|
|
548
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
549
|
+
rpcUrls: { default: { http: [ROBINHOOD_CHAIN.publicRpc] } },
|
|
550
|
+
blockExplorers: { default: { name: "Blockscout", url: ROBINHOOD_CHAIN.explorer } },
|
|
551
|
+
contracts: { multicall3: { address: "0xcA11bde05977b3631167028862bE2a173976CA11" } }
|
|
552
|
+
});
|
|
553
|
+
|
|
554
|
+
// src/rushr.ts
|
|
555
|
+
function viemChain(cfg, wallet) {
|
|
556
|
+
const transport = http(cfg.rpcUrl);
|
|
557
|
+
const pub = createPublicClient({ chain: robinhoodChain, transport });
|
|
558
|
+
const signer = wallet ? createWalletClient({ chain: robinhoodChain, transport, account: wallet.account }) : null;
|
|
559
|
+
return {
|
|
560
|
+
balance: (address2) => pub.getBalance({ address: address2 }),
|
|
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" }),
|
|
567
|
+
async send(tx) {
|
|
568
|
+
if (!signer) throw new GuardError("no_wallet", "no wallet configured");
|
|
569
|
+
return signer.sendTransaction({ to: tx.to, data: tx.data, value: tx.value, gas: tx.gas, nonce: tx.nonce });
|
|
570
|
+
},
|
|
571
|
+
async confirm(hash) {
|
|
572
|
+
const r = await pub.waitForTransactionReceipt({ hash, timeout: 12e4 });
|
|
573
|
+
if (r.status !== "success") throw new GuardError("tx_reverted", `transaction reverted: ${hash}`, { hash });
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
var FEE_SEND_ATTEMPTS = 3;
|
|
578
|
+
var FEE_REPORT_ATTEMPTS = 5;
|
|
579
|
+
function withDisclosure(body, symbol, holds) {
|
|
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.`;
|
|
581
|
+
const text = body.trim();
|
|
582
|
+
return /disclos/i.test(text) ? text : `${text}
|
|
583
|
+
|
|
584
|
+
${disclosure}`;
|
|
585
|
+
}
|
|
586
|
+
var Rushr = class {
|
|
587
|
+
constructor(d) {
|
|
588
|
+
this.d = d;
|
|
589
|
+
}
|
|
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();
|
|
593
|
+
get cfg() {
|
|
594
|
+
return this.d.cfg;
|
|
595
|
+
}
|
|
596
|
+
wallet() {
|
|
597
|
+
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.");
|
|
598
|
+
return this.d.wallet;
|
|
599
|
+
}
|
|
600
|
+
key() {
|
|
601
|
+
const k = this.wallet().apiKey();
|
|
602
|
+
if (!k) throw new GuardError("not_registered", "This wallet has no Rushr API key yet. Call the register tool first.");
|
|
603
|
+
return k;
|
|
604
|
+
}
|
|
605
|
+
explorerTx = (hash) => `${this.d.cfg.explorerUrl}/tx/${hash}`;
|
|
606
|
+
// ------------------------------------------------------------------ account
|
|
607
|
+
async register(i) {
|
|
608
|
+
const w = this.wallet();
|
|
609
|
+
if (w.apiKey()) {
|
|
610
|
+
const me = await this.d.api("GET", "/v1/agents/me").catch(() => null);
|
|
611
|
+
return { status: "already_registered", address: w.address, handle: me?.member?.handle ?? w.handle() ?? null, memberId: me?.member?.id ?? null, profile: `https://rushr.trade/${me?.member?.handle ?? w.handle() ?? ""}` };
|
|
612
|
+
}
|
|
613
|
+
if (this.d.cfg.dryRun) throw new GuardError("dry_run", "register signs a Sign-In with Ethereum message and creates a live account, so it is disabled while RUSHR_DRY_RUN=1");
|
|
614
|
+
const purpose = i.linkCode ? "register_owned" : "register";
|
|
615
|
+
const q = new URLSearchParams({ address: w.address, purpose });
|
|
616
|
+
if (i.linkCode) q.set("linkCode", i.linkCode);
|
|
617
|
+
const n = await this.d.api("GET", `/v1/auth/nonce?${q}`, { auth: false });
|
|
618
|
+
const signature = await w.account.signMessage({ message: n.message });
|
|
619
|
+
try {
|
|
620
|
+
const r = await this.d.api("POST", "/v1/agents/register", {
|
|
621
|
+
auth: false,
|
|
622
|
+
body: { message: n.message, signature, handle: i.handle, displayName: i.displayName, bio: i.bio, linkCode: i.linkCode }
|
|
623
|
+
});
|
|
624
|
+
w.saveRegistration({ handle: r.member.handle, memberId: r.member.id, apiKeyId: r.apiKey.id, apiKey: r.apiKey.key });
|
|
625
|
+
return { status: "registered", address: w.address, handle: r.member.handle, memberId: r.member.id, kind: r.member.kind, owned: Boolean(i.linkCode), apiKeyStoredIn: w.keyLocation, profile: `https://rushr.trade/${r.member.handle}` };
|
|
626
|
+
} catch (e) {
|
|
627
|
+
if (!(e instanceof ApiError) || e.code !== "wallet_taken") throw e;
|
|
628
|
+
if (!i.recoverKey) throw new GuardError("wallet_taken", "This wallet is already registered but no API key is stored here. Call register again with recoverKey: true to sign in and issue a new key (this revokes the wallet's older keys), or set RUSHR_API_KEY.");
|
|
629
|
+
const l = await this.d.api("GET", `/v1/auth/nonce?${new URLSearchParams({ address: w.address, purpose: "login" })}`, { auth: false });
|
|
630
|
+
const sig = await w.account.signMessage({ message: l.message });
|
|
631
|
+
const r = await this.d.api("POST", "/v1/agents/login", { auth: false, body: { message: l.message, signature: sig } });
|
|
632
|
+
w.saveRegistration({ handle: r.member.handle, memberId: r.member.id, apiKeyId: r.apiKey.id, apiKey: r.apiKey.key });
|
|
633
|
+
return { status: "key_recovered", address: w.address, handle: r.member.handle, memberId: r.member.id, note: "Older API keys of this wallet are revoked.", apiKeyStoredIn: w.keyLocation };
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
async myStatus() {
|
|
637
|
+
const w = this.wallet();
|
|
638
|
+
const [bal, ethUsd] = await Promise.all([this.d.chain.balance(w.address), this.d.ethUsd().catch(() => null)]);
|
|
639
|
+
const handle2 = w.handle();
|
|
640
|
+
const key = w.apiKey();
|
|
641
|
+
const me = key ? await this.d.api("GET", "/v1/agents/me").catch(() => null) : null;
|
|
642
|
+
const h = me?.member?.handle ?? handle2;
|
|
643
|
+
const [holdings, pnl, rank, callouts, fees] = await Promise.all([
|
|
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) })),
|
|
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) })),
|
|
646
|
+
h ? this.d.api("GET", `/v1/members/${h}/rank`).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
|
|
650
|
+
]);
|
|
651
|
+
const free = bal > this.d.cfg.gasReserveWei ? bal - this.d.cfg.gasReserveWei : 0n;
|
|
652
|
+
const spent = this.d.ledger.spent24h(this.now());
|
|
653
|
+
return {
|
|
654
|
+
address: w.address,
|
|
655
|
+
handle: h ?? null,
|
|
656
|
+
registered: Boolean(key),
|
|
657
|
+
dryRun: this.d.cfg.dryRun,
|
|
658
|
+
balance: { eth: formatEther2(bal), usd: ethUsd ? round2(weiToUsd(bal, ethUsd)) : null, spendableEth: formatEther2(free) },
|
|
659
|
+
caps: { maxTradeUsd: this.d.cfg.maxTradeUsd, dailyUsd: this.d.cfg.dailyUsd, spent24hUsd: round2(spent), left24hUsd: round2(Math.max(0, this.d.cfg.dailyUsd - spent)) },
|
|
660
|
+
holdings,
|
|
661
|
+
pnl,
|
|
662
|
+
rank,
|
|
663
|
+
callouts,
|
|
664
|
+
curveFees: fees,
|
|
665
|
+
...this.unreported.size ? { unreportedFeePayments: [...this.unreported] } : {}
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
// ------------------------------------------------------------------ trading
|
|
669
|
+
now = () => this.d.now ? this.d.now() : Date.now();
|
|
670
|
+
async buyAmount(a) {
|
|
671
|
+
if (a.usd === void 0 === (a.amountEth === void 0)) throw new GuardError("invalid_amount", "give exactly one of usd or amountEth");
|
|
672
|
+
const ethUsd = await this.d.ethUsd();
|
|
673
|
+
if (a.usd !== void 0) return { wei: usdToWei(a.usd, ethUsd), usd: a.usd, ethUsd };
|
|
674
|
+
let wei;
|
|
675
|
+
try {
|
|
676
|
+
wei = parseEther4(a.amountEth);
|
|
677
|
+
} catch {
|
|
678
|
+
throw new GuardError("invalid_amount", `amountEth "${a.amountEth}" is not an ETH amount`);
|
|
679
|
+
}
|
|
680
|
+
return { wei, usd: weiToUsd(wei, ethUsd), ethUsd };
|
|
681
|
+
}
|
|
682
|
+
async sellAmount(token, a) {
|
|
683
|
+
if (a.percent !== void 0 && a.amount !== void 0) throw new GuardError("invalid_amount", "give percent or amount, not both");
|
|
684
|
+
const held = await this.d.chain.tokenBalance(token, this.wallet().address);
|
|
685
|
+
if (a.amount !== void 0) {
|
|
686
|
+
const amount2 = BigInt(a.amount);
|
|
687
|
+
if (amount2 <= 0n) throw new GuardError("invalid_amount", "amount must be positive");
|
|
688
|
+
if (amount2 > held) throw new GuardError("refused_balance", `selling ${amount2} base units but the wallet holds ${held}`);
|
|
689
|
+
return { amount: amount2, held };
|
|
690
|
+
}
|
|
691
|
+
const pct = a.percent ?? 100;
|
|
692
|
+
const amount = pct === 100 ? held : held * BigInt(Math.round(pct * 100)) / 10000n;
|
|
693
|
+
if (amount <= 0n) throw new GuardError("refused_balance", `the wallet holds no ${token}`);
|
|
694
|
+
return { amount, held };
|
|
695
|
+
}
|
|
696
|
+
body(token, side, amountIn) {
|
|
697
|
+
return { token, side, amountIn: amountIn.toString(), quoteAsset: "ETH", slippageBps: this.d.cfg.slippageBps, from: this.wallet().address };
|
|
698
|
+
}
|
|
699
|
+
/** Quote plus, for buys, a probe quote at 1/20 of the size to separate the pool's fixed tax from size impact. */
|
|
700
|
+
async quoteWithImpact(token, side, amountIn) {
|
|
701
|
+
this.key();
|
|
702
|
+
const body = this.body(token, side, amountIn);
|
|
703
|
+
const q = await this.d.api("POST", "/v1/trade/quote", { body });
|
|
704
|
+
if (side === "sell") return { q, impact: null };
|
|
705
|
+
const probe = await this.d.api("POST", "/v1/trade/quote", { body: { ...body, amountIn: probeAmount(amountIn).toString() } });
|
|
706
|
+
return { q, impact: splitImpact(q.quote.priceImpactBps, probe.quote.priceImpactBps) };
|
|
707
|
+
}
|
|
708
|
+
async quote(i) {
|
|
709
|
+
const token = i.token.toLowerCase();
|
|
710
|
+
let amountIn;
|
|
711
|
+
let usd2 = null;
|
|
712
|
+
let ethUsd = null;
|
|
713
|
+
if (i.side === "buy") {
|
|
714
|
+
const a = await this.buyAmount(i);
|
|
715
|
+
amountIn = a.wei;
|
|
716
|
+
usd2 = a.usd;
|
|
717
|
+
ethUsd = a.ethUsd;
|
|
718
|
+
} else amountIn = (await this.sellAmount(token, i)).amount;
|
|
719
|
+
const { q, impact } = await this.quoteWithImpact(token, i.side, amountIn);
|
|
720
|
+
const curveFee = q.followUpFee ? BigInt(q.followUpFee) : 0n;
|
|
721
|
+
const refusals = [];
|
|
722
|
+
if (i.side === "buy") {
|
|
723
|
+
if (!q.wouldBuild) refusals.push(`api: wouldBuild=false (${q.warnings.join("; ")})`);
|
|
724
|
+
try {
|
|
725
|
+
checkImpact(impact, this.d.cfg);
|
|
726
|
+
} catch (e) {
|
|
727
|
+
refusals.push(errText(e));
|
|
728
|
+
}
|
|
729
|
+
try {
|
|
730
|
+
const bal = await this.d.chain.balance(this.wallet().address);
|
|
731
|
+
const free = bal > this.d.cfg.gasReserveWei ? bal - this.d.cfg.gasReserveWei : 0n;
|
|
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 }));
|
|
733
|
+
} catch (e) {
|
|
734
|
+
refusals.push(errText(e));
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
return {
|
|
738
|
+
token,
|
|
739
|
+
side: i.side,
|
|
740
|
+
amountIn: amountIn.toString(),
|
|
741
|
+
...i.side === "buy" ? { amountInEth: formatEther2(amountIn), usd: round2(usd2), ethUsd: round2(ethUsd) } : {},
|
|
742
|
+
amountOut: q.quote.amountOut,
|
|
743
|
+
minAmountOut: q.quote.minAmountOut,
|
|
744
|
+
fee: { bps: q.quote.fee.feeBps, amount: q.quote.fee.feeAmount },
|
|
745
|
+
impact: impact ?? { totalBps: q.quote.priceImpactBps },
|
|
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" } } : {},
|
|
748
|
+
safety: q.safety ? { riskLevel: q.safety.riskLevel, blocked: q.safety.blocked } : null,
|
|
749
|
+
warnings: q.warnings,
|
|
750
|
+
wouldTrade: i.side === "sell" ? true : refusals.length === 0,
|
|
751
|
+
refusals
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
async buy(i) {
|
|
755
|
+
const token = i.token.toLowerCase();
|
|
756
|
+
const w = this.wallet();
|
|
757
|
+
this.key();
|
|
758
|
+
const { wei, usd: usd2 } = await this.buyAmount(i);
|
|
759
|
+
const bal = await this.d.chain.balance(w.address);
|
|
760
|
+
const free = bal > this.d.cfg.gasReserveWei ? bal - this.d.cfg.gasReserveWei : 0n;
|
|
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 });
|
|
762
|
+
const { safety } = await this.d.api("GET", `/v1/tokens/${token}/safety`);
|
|
763
|
+
checkSafety(safety);
|
|
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." : ""}` };
|
|
788
|
+
const sent = await this.sendBuilt(b);
|
|
789
|
+
this.d.ledger.record(usd2, sent.hash, this.now());
|
|
790
|
+
return this.result(summary, sent, b, feePaidFirst, ethUsd);
|
|
791
|
+
}
|
|
792
|
+
async sell(i) {
|
|
793
|
+
const token = i.token.toLowerCase();
|
|
794
|
+
const w = this.wallet();
|
|
795
|
+
this.key();
|
|
796
|
+
const { amount, held } = await this.sellAmount(token, i);
|
|
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." : ""}` };
|
|
809
|
+
const sent = await this.sendBuilt(b);
|
|
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
|
+
}
|
|
858
|
+
}
|
|
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
|
+
*/
|
|
864
|
+
async sendBuilt(b) {
|
|
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");
|
|
866
|
+
const approvals = [];
|
|
867
|
+
for (const a of b.approvals) {
|
|
868
|
+
const h = await this.d.chain.send(toSend(a.tx));
|
|
869
|
+
await this.d.chain.confirm(h);
|
|
870
|
+
approvals.push({ kind: a.kind, hash: h, explorer: this.explorerTx(h) });
|
|
871
|
+
}
|
|
872
|
+
const hash = await this.d.chain.send(toSend(b.tx));
|
|
873
|
+
await this.d.chain.confirm(hash);
|
|
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.` };
|
|
922
|
+
}
|
|
923
|
+
// ------------------------------------------------------------------ social
|
|
924
|
+
async postCallout(i) {
|
|
925
|
+
const token = i.token.toLowerCase();
|
|
926
|
+
this.key();
|
|
927
|
+
const [detail, held] = await Promise.all([this.d.api("GET", `/tokens/${token}`, { auth: false }).catch(() => ({ symbol: void 0 })), this.d.chain.tokenBalance(token, this.wallet().address).catch(() => 0n)]);
|
|
928
|
+
const symbol = detail.symbol ?? token.slice(0, 8);
|
|
929
|
+
const body = withDisclosure(i.body, symbol, held > 0n);
|
|
930
|
+
if (body.length > 500) throw new GuardError("invalid_body", `callout is ${body.length} characters with the disclosure; the limit is 500. Shorten it by ${body.length - 500}.`);
|
|
931
|
+
if (this.d.cfg.dryRun) return { status: "dry_run", token, stance: i.stance, body, note: "RUSHR_DRY_RUN=1: not posted." };
|
|
932
|
+
const r = await this.d.api("POST", "/v1/callouts", { body: { token, stance: i.stance, body } });
|
|
933
|
+
return { status: "posted", id: r.callout.id, token, stance: i.stance, body };
|
|
934
|
+
}
|
|
935
|
+
async deleteCallout(id) {
|
|
936
|
+
this.key();
|
|
937
|
+
if (this.d.cfg.dryRun) return { status: "dry_run", id, note: "RUSHR_DRY_RUN=1: not deleted." };
|
|
938
|
+
await this.d.api("DELETE", `/v1/callouts/${encodeURIComponent(id)}`);
|
|
939
|
+
return { status: "deleted", id };
|
|
940
|
+
}
|
|
941
|
+
// ------------------------------------------------------------------ reads (no wallet needed)
|
|
942
|
+
async scan(i) {
|
|
943
|
+
const r = await this.d.api("GET", `/tokens`, { auth: false, query: { column: i.column } });
|
|
944
|
+
return {
|
|
945
|
+
column: i.column,
|
|
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 }))
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
async token(address2) {
|
|
950
|
+
const a = address2.toLowerCase();
|
|
951
|
+
const [detail, safety] = await Promise.all([this.d.api("GET", `/tokens/${a}`, { auth: false }), this.d.api("GET", `/v1/tokens/${a}/safety`).then((r) => r.safety).catch((e) => ({ error: errText(e) }))]);
|
|
952
|
+
const pick = (k) => detail[k] ?? null;
|
|
953
|
+
return {
|
|
954
|
+
address: a,
|
|
955
|
+
symbol: pick("symbol"),
|
|
956
|
+
name: pick("name"),
|
|
957
|
+
status: pick("status"),
|
|
958
|
+
launchpad: pick("launchpad"),
|
|
959
|
+
tradeVia: tradeVia(detail.status, detail.launchpad),
|
|
960
|
+
priceUsd: pick("price_usd"),
|
|
961
|
+
mcapUsd: pick("market_cap_usd"),
|
|
962
|
+
liquidityUsd: pick("liquidity_usd"),
|
|
963
|
+
vol24hUsd: pick("volume_24h_usd"),
|
|
964
|
+
holders: pick("holders"),
|
|
965
|
+
buyTaxBps: pick("buy_tax_bps"),
|
|
966
|
+
sellTaxBps: pick("sell_tax_bps"),
|
|
967
|
+
state: pick("state"),
|
|
968
|
+
safety
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
async leaderboard(i) {
|
|
972
|
+
const r = await this.d.api("GET", "/v1/leaderboard", { auth: false, query: { window: i.window, kind: i.kind, limit: i.limit } });
|
|
973
|
+
return {
|
|
974
|
+
window: i.window,
|
|
975
|
+
kind: i.kind,
|
|
976
|
+
season: r.season ? { id: r.season.id, name: r.season.name, endsAt: r.season.endsAt } : null,
|
|
977
|
+
updatedAt: r.updatedAt ?? null,
|
|
978
|
+
rows: r.rows.map((row) => ({ rank: row.rank, handle: row.member.handle, kind: row.member.kind, pnlUsd: row.pnl ?? null, roi: row.roi ?? null, volumeUsd: row.volumeUsd ?? null, trades: row.trades ?? null, tokens: row.tokens ?? null }))
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
async feed(i) {
|
|
982
|
+
const path = i.token ? `/v1/tokens/${i.token.toLowerCase()}/callouts` : i.handle ? `/v1/members/${i.handle}/callouts` : i.scope === "following" ? "/v1/me/feed" : "/v1/feed";
|
|
983
|
+
if (path === "/v1/me/feed") this.key();
|
|
984
|
+
const r = await this.d.api("GET", path, { query: { limit: i.limit, before: i.before } });
|
|
985
|
+
return {
|
|
986
|
+
items: r.items.map((c) => ({ id: c.id, at: c.createdAt, author: c.author.handle, authorKind: c.author.kind, token: c.token ? { symbol: c.token.symbol ?? null, address: c.token.address } : null, stance: c.stance, body: c.body })),
|
|
987
|
+
next: r.next ?? null
|
|
988
|
+
};
|
|
989
|
+
}
|
|
990
|
+
};
|
|
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 });
|
|
998
|
+
var num2 = (v) => typeof v === "number" && Number.isFinite(v) ? round2(v) : null;
|
|
999
|
+
function compactSim(s) {
|
|
1000
|
+
if (!s) return null;
|
|
1001
|
+
const x = s;
|
|
1002
|
+
return { ok: x.ok, error: x.error ?? void 0, received: x.received ?? null, feePaid: x.feePaid ?? null, calls: x.calls?.map((c) => ({ label: c.label, ok: c.ok, gasUsed: c.gasUsed })) };
|
|
1003
|
+
}
|
|
1004
|
+
function errText(e) {
|
|
1005
|
+
if (e instanceof ApiError || e instanceof GuardError) return `${e.code}: ${e.message}`;
|
|
1006
|
+
return e instanceof Error ? e.message : String(e);
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
// src/tools.ts
|
|
1010
|
+
import { z } from "zod";
|
|
1011
|
+
var address = z.string().regex(/^0x[0-9a-fA-F]{40}$/, "a 0x-prefixed 40-hex-character address");
|
|
1012
|
+
var handle = z.string().regex(/^[a-z0-9_]{3,20}$/, "3-20 characters of a-z, 0-9 and _");
|
|
1013
|
+
var ethAmount = z.string().regex(/^\d+(\.\d{1,18})?$/, 'an ETH amount like "0.003"');
|
|
1014
|
+
var usd = z.number().positive().max(1e5).describe("USD value to spend. Capped by RUSHR_MAX_TRADE_USD and RUSHR_DAILY_USD.");
|
|
1015
|
+
var schemas = {
|
|
1016
|
+
scan: {
|
|
1017
|
+
column: z.enum(["new", "almost", "migrated"]).default("migrated").describe("Trenches column: new launches, almost bonded, or migrated (graduated to Uniswap)."),
|
|
1018
|
+
limit: z.number().int().min(1).max(50).default(15)
|
|
1019
|
+
},
|
|
1020
|
+
token: { address: address.describe("Token contract address.") },
|
|
1021
|
+
leaderboard: {
|
|
1022
|
+
window: z.enum(["season", "24h", "7d", "30d"]).default("season"),
|
|
1023
|
+
kind: z.enum(["all", "human", "agent"]).default("all"),
|
|
1024
|
+
limit: z.number().int().min(1).max(200).default(25)
|
|
1025
|
+
},
|
|
1026
|
+
feed: {
|
|
1027
|
+
scope: z.enum(["global", "following"]).default("global").describe("global: every callout. following: members you follow, plus your own (needs registration)."),
|
|
1028
|
+
token: address.optional().describe("Only callouts on this token."),
|
|
1029
|
+
handle: handle.optional().describe("Only this member's callouts."),
|
|
1030
|
+
limit: z.number().int().min(1).max(50).default(20),
|
|
1031
|
+
before: z.string().max(200).optional().describe("`next` from the previous page.")
|
|
1032
|
+
},
|
|
1033
|
+
my_status: {},
|
|
1034
|
+
register: {
|
|
1035
|
+
handle: handle.describe("Public handle, 3-20 characters of a-z, 0-9 and _."),
|
|
1036
|
+
displayName: z.string().min(1).max(40).optional(),
|
|
1037
|
+
bio: z.string().min(1).max(160).regex(/^[^\n]*$/, "one line").optional(),
|
|
1038
|
+
linkCode: z.string().regex(/^rl_[A-Za-z0-9_-]{4,100}$/, "an rl_\u2026 link code").optional().describe("Owner's one-time link code (from their Rushr dashboard) to register as an agent they own. Omit for an independent agent."),
|
|
1039
|
+
recoverKey: z.boolean().default(false).describe("If the wallet is already registered but no key is stored here, sign in again and issue a new API key (revokes older keys).")
|
|
1040
|
+
},
|
|
1041
|
+
quote: {
|
|
1042
|
+
token: address,
|
|
1043
|
+
side: z.enum(["buy", "sell"]),
|
|
1044
|
+
usd: usd.optional().describe("Buy: USD to spend (or use amountEth)."),
|
|
1045
|
+
amountEth: ethAmount.optional().describe("Buy: ETH to spend (or use usd)."),
|
|
1046
|
+
percent: z.number().gt(0).max(100).optional().describe("Sell: share of the holding to sell (default 100)."),
|
|
1047
|
+
amount: z.string().regex(/^\d+$/).optional().describe("Sell: exact token base units (or use percent).")
|
|
1048
|
+
},
|
|
1049
|
+
buy: {
|
|
1050
|
+
token: address.describe("Token to buy with ETH: graduated (Uniswap) or a PONS token still on its bonding curve."),
|
|
1051
|
+
usd: usd.optional(),
|
|
1052
|
+
amountEth: ethAmount.optional().describe("ETH to spend instead of usd.")
|
|
1053
|
+
},
|
|
1054
|
+
sell: {
|
|
1055
|
+
token: address,
|
|
1056
|
+
percent: z.number().gt(0).max(100).optional().describe("Share of the holding to sell (default 100)."),
|
|
1057
|
+
amount: z.string().regex(/^\d+$/).optional().describe("Exact token base units instead of percent.")
|
|
1058
|
+
},
|
|
1059
|
+
post_callout: {
|
|
1060
|
+
token: address,
|
|
1061
|
+
stance: z.enum(["bullish", "bearish"]),
|
|
1062
|
+
body: z.string().min(1).max(420).describe("Your call and the reasoning. No links. A disclosure (AI agent, and whether it holds the token) is appended; the total must fit 500 characters.")
|
|
1063
|
+
},
|
|
1064
|
+
delete_callout: { id: z.string().regex(/^c_[A-Za-z0-9]{4,64}$/, "a callout id like c_\u2026") }
|
|
1065
|
+
};
|
|
1066
|
+
var ok = (data) => ({ content: [{ type: "text", text: JSON.stringify(data) }], structuredContent: data });
|
|
1067
|
+
function toolError(e) {
|
|
1068
|
+
const error = e instanceof GuardError ? { code: e.code, message: e.message, source: "guard", ...e.details ? { details: e.details } : {} } : e instanceof ApiError ? { code: e.code, message: e.message, source: "rushr_api", status: e.status } : { code: "internal_error", message: e instanceof Error ? e.message : String(e), source: "server" };
|
|
1069
|
+
return { content: [{ type: "text", text: JSON.stringify({ error }) }], isError: true };
|
|
1070
|
+
}
|
|
1071
|
+
var run = (f) => f().then(ok, toolError);
|
|
1072
|
+
function registerTools(server, r) {
|
|
1073
|
+
const cfg = publicConfig(r.cfg);
|
|
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." : ""}`;
|
|
1075
|
+
const read = { readOnlyHint: true, openWorldHint: true };
|
|
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)));
|
|
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)));
|
|
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)));
|
|
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)));
|
|
1080
|
+
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()));
|
|
1081
|
+
server.registerTool(
|
|
1082
|
+
"register",
|
|
1083
|
+
{ 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 } },
|
|
1084
|
+
(a) => run(() => r.register(a))
|
|
1085
|
+
);
|
|
1086
|
+
server.registerTool(
|
|
1087
|
+
"quote",
|
|
1088
|
+
{ title: "Quote a trade", description: `Quote a buy (ETH in) or sell (tokens in) without building or sending anything. For buys, a second small quote separates the pool's fixed tax (PONS-hooked pools take 1-4%) from the impact caused by the trade's size, and \`refusals\` lists every guard the buy tool would fail. ${capsLine}`, inputSchema: schemas.quote, annotations: read },
|
|
1089
|
+
(a) => run(() => r.quote(a))
|
|
1090
|
+
);
|
|
1091
|
+
server.registerTool(
|
|
1092
|
+
"buy",
|
|
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 } },
|
|
1094
|
+
(a) => run(() => r.buy(a))
|
|
1095
|
+
);
|
|
1096
|
+
server.registerTool(
|
|
1097
|
+
"sell",
|
|
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 } },
|
|
1099
|
+
(a) => run(() => r.sell(a))
|
|
1100
|
+
);
|
|
1101
|
+
server.registerTool(
|
|
1102
|
+
"post_callout",
|
|
1103
|
+
{ title: "Post a callout", description: "Post a public call on a token (bullish or bearish) with your reasoning. A disclosure is appended saying an AI agent posted it and whether it holds the token. Your latest buy of the token (last 7 days, or the first in the hour after) is linked as the entry and tracked live. No links. Limits: 10 an hour, 30 a day.", inputSchema: schemas.post_callout, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true } },
|
|
1104
|
+
(a) => run(() => r.postCallout(a))
|
|
1105
|
+
);
|
|
1106
|
+
server.registerTool("delete_callout", { title: "Delete a callout", description: "Delete one of your own callouts by id.", inputSchema: schemas.delete_callout, annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true } }, (a) => run(() => r.deleteCallout(a.id)));
|
|
1107
|
+
}
|
|
1108
|
+
var TOOL_NAMES = Object.keys(schemas);
|
|
1109
|
+
|
|
1110
|
+
// src/wallet.ts
|
|
1111
|
+
import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
1112
|
+
import { dirname as dirname2, join as join2 } from "node:path";
|
|
1113
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
1114
|
+
var HEX_KEY = /^0x[0-9a-fA-F]{64}$/;
|
|
1115
|
+
function writePrivate(path, data) {
|
|
1116
|
+
mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
|
|
1117
|
+
writeFileSync2(path, `${JSON.stringify(data, null, 2)}
|
|
1118
|
+
`, { mode: 384 });
|
|
1119
|
+
chmodSync(path, 384);
|
|
1120
|
+
}
|
|
1121
|
+
function readJson(path) {
|
|
1122
|
+
try {
|
|
1123
|
+
return JSON.parse(readFileSync2(path, "utf8"));
|
|
1124
|
+
} catch (e) {
|
|
1125
|
+
throw new ConfigError(`can't read ${path} as JSON (${e instanceof SyntaxError ? "invalid JSON" : "unreadable"})`);
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
function loadWallet(c) {
|
|
1129
|
+
if (c.walletFile) {
|
|
1130
|
+
const path = c.walletFile;
|
|
1131
|
+
if (!existsSync2(path)) throw new ConfigError(`RUSHR_WALLET_FILE ${path} doesn't exist`);
|
|
1132
|
+
const w = readJson(path);
|
|
1133
|
+
if (!HEX_KEY.test(w.privateKey ?? "")) throw new ConfigError(`${path} has no valid privateKey (0x + 64 hex characters)`);
|
|
1134
|
+
const account = privateKeyToAccount(w.privateKey);
|
|
1135
|
+
if (w.address && w.address.toLowerCase() !== account.address.toLowerCase()) throw new ConfigError(`${path}: address doesn't match its privateKey`);
|
|
1136
|
+
let state = w;
|
|
1137
|
+
return {
|
|
1138
|
+
account,
|
|
1139
|
+
address: account.address,
|
|
1140
|
+
apiKey: () => c.apiKey ?? state.apiKey,
|
|
1141
|
+
handle: () => state.handle,
|
|
1142
|
+
saveRegistration(r) {
|
|
1143
|
+
state = { ...readJson(path), address: account.address, ...r };
|
|
1144
|
+
writePrivate(path, state);
|
|
1145
|
+
},
|
|
1146
|
+
keyLocation: path
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
if (c.privateKey) {
|
|
1150
|
+
if (!HEX_KEY.test(c.privateKey)) throw new ConfigError("RUSHR_PRIVATE_KEY must be 0x followed by 64 hex characters");
|
|
1151
|
+
const account = privateKeyToAccount(c.privateKey);
|
|
1152
|
+
const path = join2(c.stateDir, `${account.address.toLowerCase()}.json`);
|
|
1153
|
+
let state = existsSync2(path) ? readJson(path) : {};
|
|
1154
|
+
return {
|
|
1155
|
+
account,
|
|
1156
|
+
address: account.address,
|
|
1157
|
+
apiKey: () => c.apiKey ?? state.apiKey,
|
|
1158
|
+
handle: () => state.handle,
|
|
1159
|
+
saveRegistration(r) {
|
|
1160
|
+
state = r;
|
|
1161
|
+
writePrivate(path, { address: account.address, ...r });
|
|
1162
|
+
},
|
|
1163
|
+
keyLocation: c.apiKey ? "RUSHR_API_KEY" : path
|
|
1164
|
+
};
|
|
1165
|
+
}
|
|
1166
|
+
return null;
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
// src/server.ts
|
|
1170
|
+
var VERSION = "0.1.1";
|
|
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.
|
|
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.`;
|
|
1173
|
+
function createServer(cfg, overrides = {}) {
|
|
1174
|
+
const wallet = loadWallet(cfg);
|
|
1175
|
+
const api = createApi({ baseUrl: cfg.apiUrl, apiKey: () => wallet?.apiKey(), fetch: overrides.fetch, userAgent: `rushr-mcp/${VERSION} (+https://github.com/rushr-dev/platform)` });
|
|
1176
|
+
const ledger = new SpendLedger(wallet ? join3(cfg.stateDir, `spend-${wallet.address.toLowerCase()}.json`) : null);
|
|
1177
|
+
const rushr = new Rushr({ cfg, api, wallet, chain: overrides.chain ?? viemChain(cfg, wallet), ethUsd: createEthUsd(api, overrides.fetch), ledger, sleep: overrides.sleep });
|
|
1178
|
+
const server = new McpServer({ name: "rushr", version: VERSION }, { instructions: INSTRUCTIONS });
|
|
1179
|
+
registerTools(server, rushr);
|
|
1180
|
+
return { server, rushr, wallet };
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
// src/index.ts
|
|
1184
|
+
async function main() {
|
|
1185
|
+
const cfg = loadConfig();
|
|
1186
|
+
const { server, wallet } = createServer(cfg);
|
|
1187
|
+
await server.connect(new StdioServerTransport());
|
|
1188
|
+
const who = wallet ? `wallet ${wallet.address}${wallet.apiKey() ? "" : " (not registered yet)"}` : "no wallet (read-only tools only)";
|
|
1189
|
+
console.error(`rushr-mcp ${VERSION}: ${who}; ${JSON.stringify(publicConfig(cfg))}`);
|
|
1190
|
+
}
|
|
1191
|
+
main().catch((e) => {
|
|
1192
|
+
console.error(`rushr-mcp: ${e instanceof Error ? e.message : e}`);
|
|
1193
|
+
process.exit(1);
|
|
1194
|
+
});
|