anthropos-mcp 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,11 +4,16 @@ import { createHmac, randomBytes } from 'node:crypto';
4
4
  import * as fs from 'node:fs';
5
5
  import * as os from 'node:os';
6
6
  import * as path from 'node:path';
7
+ import { spawnSync } from 'node:child_process';
8
+ import * as dns from 'node:dns/promises';
9
+ import * as http from 'node:http';
10
+ import * as https from 'node:https';
11
+ import { spawn } from 'node:child_process';
7
12
  import * as readline from 'node:readline/promises';
8
13
  const __m_core = (() => {
9
14
  // ANTHROPOS core: read-only BNB Chain / Flap / PancakeSwap reads.
10
15
  // No keys, no signing, no funds. Runs in Node >= 18 and in the browser (same file).
11
- const VERSION = '0.2.0';
16
+ const VERSION = '0.3.0';
12
17
  const CHAIN = { id: 56, name: 'BNB Smart Chain' };
13
18
  const DEFAULT_RPCS = ['https://bsc-rpc.publicnode.com', 'https://bsc-dataseed.binance.org', 'https://bsc-dataseed1.defibit.io'];
14
19
  /** Only some public nodes allow eth_getLogs. Used first for log queries when the caller did not pick URLs. */
@@ -813,12 +818,21 @@ return { keccak256, parsePrivateKey, randomHex, randomPrivateKey, publicKey, add
813
818
  const __m_relay = (() => {
814
819
  // Relay API (api.relay.link): chains, tokens, quotes (cross-chain and same-chain swaps) and step execution.
815
820
  // Quotes need no key. Nothing here signs or sends unless the caller passes a user-approved quote to `runSteps`.
816
- const API = 'https://api.relay.link';
821
+ // Quotes work without a key; a key (env RELAY_API_KEY in the MCP server, a Pages secret behind /relay in the web app) only raises the rate limit.
822
+ // The key is never part of this file or of any bundle.
817
823
  const NATIVE = '0x0000000000000000000000000000000000000000';
818
824
  const cache = {};
825
+ let base = 'https://api.relay.link', apiKey = '';
819
826
 
820
- async function api(path, init) {
821
- const res = await fetch(API + path, init);
827
+ /** Point the client at another base URL (the same-origin /relay proxy in the browser) and/or give it an API key. */
828
+ function configure({ baseUrl, key } = {}) {
829
+ if (baseUrl) { base = String(baseUrl).replace(/\/$/, ''); for (const k of Object.keys(cache)) delete cache[k]; }
830
+ if (key !== undefined) apiKey = String(key || '');
831
+ }
832
+
833
+ async function api(path, init = {}) {
834
+ const headers = { ...(init.headers || {}), ...(apiKey ? { 'x-api-key': apiKey } : {}) };
835
+ const res = await fetch(base + path, { ...init, headers });
822
836
  const body = await res.json().catch(() => ({}));
823
837
  if (!res.ok) throw new Error(body.message || body.error || `Relay HTTP ${res.status}`);
824
838
  return body;
@@ -890,7 +904,7 @@ function summarize(q) {
890
904
  };
891
905
  }
892
906
 
893
- return { NATIVE, api, chainsOnce, tokensOnce, toUnits, quote, transactionItems, runSteps, summarize };
907
+ return { NATIVE, configure, api, chainsOnce, tokensOnce, toUnits, quote, transactionItems, runSteps, summarize };
894
908
  })();
895
909
 
896
910
  const __m_wallet = (() => {
@@ -932,6 +946,282 @@ function initWallet(env = process.env) {
932
946
  return { homeDir, keyPath, loadWallet, initWallet };
933
947
  })();
934
948
 
949
+ const __m_vanity = (() => {
950
+ // Vanity wallet search: find a fresh private key whose address starts and/or ends with the hex you want (e.g. suffix "7777").
951
+ // Speed comes from stepping through consecutive keys k, k+1, ... with batched affine point additions (one modular inversion per
952
+ // batch) and a 32-bit-lane Keccak specialised for a 64-byte input. Every hit is re-derived with the reference implementation in
953
+ // crypto.js before it is returned, so a bug here can only cost time, never produce a wrong address.
954
+ //
955
+ // Keys never leave this machine: a found key is written to a private file and only the address is returned. Switching the active
956
+ // wallet to it is a human step (`anthropos-mcp wallet use <address>` in a terminal); the agent cannot do it.
957
+ const { addressOf, publicKey, randomPrivateKey } = __m_crypto;
958
+ const { homeDir, keyPath } = __m_wallet;
959
+
960
+ const P = 2n ** 256n - 2n ** 32n - 977n;
961
+ const N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
962
+ const G = { x: 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n, y: 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n };
963
+ const mod = (a) => { const r = a % P; return r < 0n ? r + P : r; };
964
+ function inv(a) { let [r0, r1, s0, s1] = [mod(a), P, 1n, 0n]; while (r1) { const q = r0 / r1; [r0, r1] = [r1, r0 - q * r1]; [s0, s1] = [s1, s0 - q * s1]; } return mod(s0); }
965
+ function add(p, q) { // affine addition, p != +-q
966
+ const l = mod((q.y - p.y) * inv(q.x - p.x)), x = mod(l * l - p.x - q.x);
967
+ return { x, y: mod(l * (p.x - x) - p.y) };
968
+ }
969
+ function dbl(p) { const l = mod(3n * p.x * p.x * inv(2n * p.y)), x = mod(l * l - 2n * p.x); return { x, y: mod(l * (p.x - x) - p.y) }; }
970
+
971
+ // ------------------------------------------------------------------ keccak-256 of exactly 64 bytes (an uncompressed public key)
972
+ const RC = [[1, 0], [0x8082, 0], [0x808a, 0x80000000], [0x80008000, 0x80000000], [0x808b, 0], [0x80000001, 0], [0x80008081, 0x80000000], [0x8009, 0x80000000], [0x8a, 0], [0x88, 0], [0x80008009, 0], [0x8000000a, 0],
973
+ [0x8000808b, 0], [0x8b, 0x80000000], [0x8089, 0x80000000], [0x8003, 0x80000000], [0x8002, 0x80000000], [0x80, 0x80000000], [0x800a, 0], [0x8000000a, 0x80000000], [0x80008081, 0x80000000], [0x8080, 0x80000000], [0x80000001, 0], [0x80008008, 0x80000000]];
974
+ const ROT = [0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14]; // lane x + 5y
975
+ const PI = ROT.map((_, i) => { const x = i % 5, y = (i - x) / 5; return y + 5 * ((2 * x + 3 * y) % 5); });
976
+ const S = new Uint32Array(50), B = new Uint32Array(50), C = new Uint32Array(10), Dd = new Uint32Array(10);
977
+
978
+ function permute() {
979
+ for (let round = 0; round < 24; round++) {
980
+ for (let x = 0; x < 5; x++) { C[2 * x] = S[2 * x] ^ S[2 * (x + 5)] ^ S[2 * (x + 10)] ^ S[2 * (x + 15)] ^ S[2 * (x + 20)]; C[2 * x + 1] = S[2 * x + 1] ^ S[2 * (x + 5) + 1] ^ S[2 * (x + 10) + 1] ^ S[2 * (x + 15) + 1] ^ S[2 * (x + 20) + 1]; }
981
+ for (let x = 0; x < 5; x++) {
982
+ const a = (x + 4) % 5, b = (x + 1) % 5, lo = C[2 * b], hi = C[2 * b + 1];
983
+ Dd[2 * x] = C[2 * a] ^ ((lo << 1) | (hi >>> 31)); Dd[2 * x + 1] = C[2 * a + 1] ^ ((hi << 1) | (lo >>> 31));
984
+ }
985
+ for (let i = 0; i < 25; i++) {
986
+ const lo = S[2 * i] ^ Dd[2 * (i % 5)], hi = S[2 * i + 1] ^ Dd[2 * (i % 5) + 1], r = ROT[i], j = 2 * PI[i];
987
+ if (r === 0) { B[j] = lo; B[j + 1] = hi; }
988
+ else if (r < 32) { B[j] = (lo << r) | (hi >>> (32 - r)); B[j + 1] = (hi << r) | (lo >>> (32 - r)); }
989
+ else if (r === 32) { B[j] = hi; B[j + 1] = lo; }
990
+ else { const k = r - 32; B[j] = (hi << k) | (lo >>> (32 - k)); B[j + 1] = (lo << k) | (hi >>> (32 - k)); }
991
+ }
992
+ for (let y = 0; y < 25; y += 5) for (let x = 0; x < 5; x++) {
993
+ const i = 2 * (y + x), n1 = 2 * (y + ((x + 1) % 5)), n2 = 2 * (y + ((x + 2) % 5));
994
+ S[i] = B[i] ^ (~B[n1] & B[n2]); S[i + 1] = B[i + 1] ^ (~B[n1 + 1] & B[n2 + 1]);
995
+ }
996
+ S[0] ^= RC[round][0]; S[1] ^= RC[round][1];
997
+ }
998
+ }
999
+
1000
+ const HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
1001
+ const be32 = (v) => v.toString(16).padStart(64, '0');
1002
+ const words = (n) => { const out = new Array(8); for (let i = 0; i < 8; i++) out[i] = Number((n >> BigInt(32 * i)) & 0xffffffffn); return out; }; // little-endian 32-bit words
1003
+
1004
+ /** Lower-case 40-hex address of the public key (x, y), no 0x prefix. Same as keccak256(x||y)[12..]. */
1005
+ function addressHex(x, y) {
1006
+ const xw = words(x), yw = words(y); // key bytes are big-endian: byte 0 is the top byte of x
1007
+ S.fill(0);
1008
+ const bswap = (w) => (((w & 0xff) << 24) | ((w & 0xff00) << 8) | ((w >>> 8) & 0xff00) | (w >>> 24)) >>> 0;
1009
+ for (let i = 0; i < 8; i++) S[i] = bswap(xw[7 - i]); // bytes 0..31 -> lanes 0..3
1010
+ for (let i = 0; i < 8; i++) S[8 + i] = bswap(yw[7 - i]); // bytes 32..63 -> lanes 4..7
1011
+ S[16] = 1; S[33] = 0x80000000; // padding: byte 64 = 0x01, byte 135 |= 0x80
1012
+ permute();
1013
+ // digest bytes 12..31 = lane1.hi, lane2, lane3 (little-endian)
1014
+ const w = [S[3], S[4], S[5], S[6], S[7]];
1015
+ let out = '';
1016
+ for (const v of w) out += HEX[v & 0xff] + HEX[(v >>> 8) & 0xff] + HEX[(v >>> 16) & 0xff] + HEX[v >>> 24];
1017
+ return out;
1018
+ }
1019
+
1020
+ const validHex = (s) => /^[0-9a-f]*$/i.test(s);
1021
+
1022
+ /** Expected number of keys to try for a pattern of this many hex characters. */
1023
+ const expectedAttempts = (prefix = '', suffix = '') => 16 ** (prefix.length + suffix.length);
1024
+
1025
+ /** Check and normalise a pattern. Throws a plain-language error. */
1026
+ function checkPattern(prefix, suffix) {
1027
+ prefix = String(prefix || '').toLowerCase().replace(/^0x/, ''); suffix = String(suffix || '').toLowerCase();
1028
+ if (!validHex(prefix) || !validHex(suffix)) throw new Error('prefix and suffix must be hex characters (0-9, a-f).');
1029
+ if (prefix.length + suffix.length === 0) throw new Error('give a prefix, a suffix, or both.');
1030
+ if (prefix.length + suffix.length > 12) throw new Error('more than 12 hex characters would take years. Use a shorter pattern.');
1031
+ return { prefix, suffix };
1032
+ }
1033
+
1034
+ /** A resumable search: call `step(ms)` repeatedly; it returns a result object once a key is found, otherwise null. */
1035
+ function makeSearcher(prefix, suffix, batch = 256) {
1036
+ const table = [null, G, dbl(G)]; // table[i] = i*G
1037
+ for (let i = 3; i <= batch; i++) table.push(add(table[i - 1], G));
1038
+ const step = table[batch];
1039
+ let k = randomPrivateKey(), pt = publicKey(k), attempts = 0;
1040
+ const dens = new Array(batch + 1), pre = new Array(batch + 1);
1041
+ return function run(sliceMs, now) {
1042
+ const end = now() + sliceMs;
1043
+ do {
1044
+ // denominators d_i = T_i.x - P.x, inverted together (Montgomery's trick)
1045
+ let acc = 1n;
1046
+ for (let i = 1; i <= batch; i++) { const d = mod(table[i].x - pt.x); dens[i] = d; pre[i] = acc; acc = mod(acc * (d === 0n ? 1n : d)); }
1047
+ let invAcc = inv(acc);
1048
+ for (let i = batch; i >= 1; i--) {
1049
+ const d = dens[i];
1050
+ if (d === 0n) continue;
1051
+ const invD = mod(invAcc * pre[i]); invAcc = mod(invAcc * d);
1052
+ const tp = table[i], l = mod((tp.y - pt.y) * invD), x = mod(l * l - pt.x - tp.x), y = mod(l * (pt.x - x) - pt.y);
1053
+ const a = addressHex(x, y);
1054
+ if ((prefix === '' || a.startsWith(prefix)) && (suffix === '' || a.endsWith(suffix))) {
1055
+ const priv = (k + BigInt(i)) % N;
1056
+ if (addressOf(priv).toLowerCase() !== '0x' + a) throw new Error('internal check failed: derived address does not match the key (vanity search aborted).');
1057
+ return { priv, address: '0x' + a, attempts: attempts + (batch - i + 1) };
1058
+ }
1059
+ }
1060
+ attempts += batch;
1061
+ k = (k + BigInt(batch)) % N; pt = add(pt, step);
1062
+ } while (now() < end);
1063
+ return { priv: null, address: null, attempts };
1064
+ };
1065
+ }
1066
+
1067
+ const timeBudget = (maxMs) => { const v = Number(maxMs); if (!Number.isFinite(v) || v <= 0) throw new Error('the time limit must be a positive number.'); return v; };
1068
+
1069
+ /**
1070
+ * Search for a key whose address starts with `prefix` and/or ends with `suffix` (hex, case-insensitive), for at most `maxMs`.
1071
+ * Returns { priv (bigint), address, attempts, ms } or { priv: null, attempts, ms } when the time ran out. Blocks the thread: use findVanityAsync in a server.
1072
+ */
1073
+ function findVanity({ prefix = '', suffix = '', maxMs = 20000, batch = 256, now = () => Date.now() } = {}) {
1074
+ ({ prefix, suffix } = checkPattern(prefix, suffix)); maxMs = timeBudget(maxMs);
1075
+ const start = now(), run = makeSearcher(prefix, suffix, batch);
1076
+ for (;;) {
1077
+ const r = run(Math.min(250, maxMs), now);
1078
+ if (r.priv || now() - start >= maxMs) return { ...r, ms: now() - start };
1079
+ }
1080
+ }
1081
+
1082
+ /** Same search, but hands the event loop back every ~100 ms so the MCP server keeps answering pings and other requests. */
1083
+ async function findVanityAsync({ prefix = '', suffix = '', maxMs = 20000, batch = 256, now = () => Date.now(), yieldNow = () => new Promise((r) => setImmediate(r)) } = {}) {
1084
+ ({ prefix, suffix } = checkPattern(prefix, suffix)); maxMs = timeBudget(maxMs);
1085
+ const start = now(), run = makeSearcher(prefix, suffix, batch);
1086
+ for (;;) {
1087
+ const r = run(100, now);
1088
+ if (r.priv || now() - start >= maxMs) return { ...r, ms: now() - start };
1089
+ await yieldNow();
1090
+ }
1091
+ }
1092
+
1093
+ // ------------------------------------------------------------------ candidates on disk
1094
+ const MAX_CANDIDATES = 50;
1095
+ const candDir = (env = process.env) => path.join(homeDir(env), 'vanity');
1096
+
1097
+ function saveCandidate(priv, env = process.env) {
1098
+ const dir = candDir(env); fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
1099
+ const address = addressOf(priv).toLowerCase(), file = path.join(dir, `${address}.key`);
1100
+ if (!fs.existsSync(file) && listCandidates(env).length >= MAX_CANDIDATES) throw new Error(`There are already ${MAX_CANDIDATES} saved vanity wallets in ${dir}. Nothing is deleted automatically (a funded one may still need its key). Remove the ones you do not need, then try again.`);
1101
+ fs.writeFileSync(file, be32(priv) + '\n', { mode: 0o600 });
1102
+ return { address, file };
1103
+ }
1104
+
1105
+ const listCandidates = (env = process.env) => { try { return fs.readdirSync(candDir(env)).filter((f) => f.endsWith('.key')).map((f) => f.slice(0, -4)); } catch { return []; } };
1106
+
1107
+ /** Make a saved candidate the active wallet. An existing wallet is kept as wallet.key.bak-<time>; call this only after a person confirmed. */
1108
+ function useCandidate(address, env = process.env) {
1109
+ const addr = String(address).toLowerCase(), src = path.join(candDir(env), `${addr}.key`);
1110
+ if (!/^0x[0-9a-f]{40}$/.test(addr) || !fs.existsSync(src)) throw new Error(`No saved candidate ${address}. List them with: npx -y anthropos-mcp wallet list`);
1111
+ const dest = keyPath(env); let backup = null;
1112
+ fs.mkdirSync(path.dirname(dest), { recursive: true, mode: 0o700 });
1113
+ if (fs.existsSync(dest)) { backup = `${dest}.bak-${Date.now()}`; fs.renameSync(dest, backup); fs.chmodSync(backup, 0o600); }
1114
+ fs.renameSync(src, dest); fs.chmodSync(dest, 0o600); // moved, so the key does not live in two places
1115
+ return { address: addr, file: dest, backup };
1116
+ }
1117
+
1118
+ // ------------------------------------------------------------------ MCP tool
1119
+ function createVanity({ env = process.env } = {}) {
1120
+ return [{
1121
+ name: 'wallet_vanity',
1122
+ description: 'Generate a new burner wallet whose address starts and/or ends with hex characters the user picks (e.g. suffix "7777" or prefix "dead"). Searches locally for up to `seconds`. The key is saved in a private file and never returned; only the address is. The user switches to it with `npx -y anthropos-mcp wallet use <address>` in their own terminal. Longer patterns take much longer: each extra character is 16x more work.',
1123
+ inputSchema: { type: 'object', properties: {
1124
+ prefix: { type: 'string', description: 'Hex characters the address should start with, after 0x (e.g. "dead")' },
1125
+ suffix: { type: 'string', description: 'Hex characters the address should end with (e.g. "7777")' },
1126
+ seconds: { type: 'integer', minimum: 1, maximum: 45, description: 'How long to search (default 20, max 45)' } } },
1127
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
1128
+ run: async ({ prefix = '', suffix = '', seconds = 20 }) => {
1129
+ const expected = expectedAttempts(String(prefix).replace(/^0x/, ''), suffix);
1130
+ const r = await findVanityAsync({ prefix, suffix, maxMs: Math.min(Math.max(Number(seconds) || 20, 1), 45) * 1000 });
1131
+ const rate = Math.round(r.attempts / Math.max(r.ms / 1000, 0.001));
1132
+ if (!r.priv) return { found: false, tried: r.attempts, keysPerSecond: rate, expectedKeysNeeded: expected, estimatedMinutesOneCore: Number((expected / Math.max(rate, 1) / 60).toFixed(1)),
1133
+ tip: 'Not found in time. For a long search the user can run `npx -y anthropos-mcp vanity --suffix <hex> --minutes 30`, which uses every CPU core.' };
1134
+ const saved = saveCandidate(r.priv, env);
1135
+ return { found: true, address: r.address, tried: r.attempts, seconds: Number((r.ms / 1000).toFixed(1)), keysPerSecond: rate, savedIn: 'the private vanity folder in your ANTHROPOS home',
1136
+ next: `The key is stored privately and was not shown. To use this wallet the user must run in their own terminal: npx -y anthropos-mcp wallet use ${r.address} (the current wallet, if any, is kept as a backup). Fund it with a small amount of BNB only.`,
1137
+ note: 'A vanity address is only cosmetic. It is not more or less secure than a random one as long as the key stays private.' };
1138
+ },
1139
+ }];
1140
+ }
1141
+
1142
+ return { validHex, expectedAttempts, checkPattern, findVanity, findVanityAsync, saveCandidate, listCandidates, useCandidate, createVanity };
1143
+ })();
1144
+
1145
+ const __m_install = (() => {
1146
+ // `anthropos-mcp install`: add ANTHROPOS to every MCP client found on this machine, with one command.
1147
+ // Claude Code -> `claude mcp add --scope user anthropos -- npx -y anthropos-mcp`
1148
+ // Claude Desktop -> merges mcpServers.anthropos into claude_desktop_config.json (a .bak copy is kept)
1149
+ // Cursor -> merges mcpServers.anthropos into ~/.cursor/mcp.json
1150
+ // Nothing is sent anywhere. `--dry` prints what would change; `--uninstall` removes the entries again.
1151
+
1152
+ const NAME = 'anthropos';
1153
+ const ENTRY = { command: 'npx', args: ['-y', 'anthropos-mcp'] };
1154
+
1155
+ function clientPaths(env = process.env, platform = process.platform, home = os.homedir()) {
1156
+ const desktop = platform === 'win32' ? path.join(env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Claude', 'claude_desktop_config.json')
1157
+ : platform === 'darwin' ? path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')
1158
+ : path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'Claude', 'claude_desktop_config.json');
1159
+ return { desktop, cursor: path.join(home, '.cursor', 'mcp.json') };
1160
+ }
1161
+
1162
+ /** Return the JSON config with our entry added (or removed). Keeps every other key and server untouched. */
1163
+ function mergeConfig(text, { remove = false } = {}) {
1164
+ let cfg = {};
1165
+ if (text && text.trim()) { try { cfg = JSON.parse(text); } catch { throw new Error('the file is not valid JSON; fix or remove it first'); } }
1166
+ if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg)) throw new Error('unexpected JSON shape');
1167
+ if (cfg.mcpServers !== undefined && (cfg.mcpServers === null || typeof cfg.mcpServers !== 'object' || Array.isArray(cfg.mcpServers))) throw new Error('"mcpServers" is not an object; fix the file first');
1168
+ cfg.mcpServers = cfg.mcpServers || {};
1169
+ if (remove) delete cfg.mcpServers[NAME];
1170
+ else cfg.mcpServers[NAME] = { ...(cfg.mcpServers[NAME] && typeof cfg.mcpServers[NAME] === 'object' ? cfg.mcpServers[NAME] : {}), ...ENTRY }; // keep the user's own env and other settings
1171
+ return JSON.stringify(cfg, null, 2) + '\n';
1172
+ }
1173
+
1174
+ function editJson(file, { dry, remove, requireDir }) {
1175
+ const dir = path.dirname(file);
1176
+ if (requireDir && !fs.existsSync(dir)) return { status: 'not found', file };
1177
+ const before = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
1178
+ if (!before && remove) return { status: 'nothing to remove', file };
1179
+ const after = mergeConfig(before, { remove });
1180
+ const same = (() => { try { return JSON.stringify(JSON.parse(before)) === JSON.stringify(JSON.parse(after)); } catch { return false; } })();
1181
+ if (after === before || same) return { status: remove ? 'nothing to remove' : 'already installed', file };
1182
+ if (dry) return { status: remove ? 'would remove' : 'would add', file };
1183
+ fs.mkdirSync(dir, { recursive: true });
1184
+ const mode = before ? fs.statSync(file).mode & 0o777 : 0o600;
1185
+ let backup;
1186
+ if (before) { backup = fs.existsSync(`${file}.bak`) ? `${file}.${Date.now()}.bak` : `${file}.bak`; fs.writeFileSync(backup, before, { mode }); } // never overwrite an older backup
1187
+ const tmp = `${file}.tmp-${process.pid}`;
1188
+ fs.writeFileSync(tmp, after, { mode }); fs.renameSync(tmp, file); // atomic: a crash cannot leave half a config
1189
+ return { status: remove ? 'removed' : 'added', file, backup };
1190
+ }
1191
+
1192
+ function claudeCode({ dry, remove }, platform) {
1193
+ const probe = spawnSync('claude', ['--version'], { encoding: 'utf8', shell: platform === 'win32', cwd: os.homedir() });
1194
+ if (probe.error || probe.status !== 0) return { status: 'not found' };
1195
+ const args = remove ? ['mcp', 'remove', '--scope', 'user', NAME]
1196
+ : ['mcp', 'add', '--scope', 'user', NAME, '--', ...(platform === 'win32' ? ['cmd', '/c', 'npx'] : ['npx']), '-y', 'anthropos-mcp'];
1197
+ if (dry) return { status: remove ? 'would remove' : 'would add', command: `claude ${args.join(' ')}` };
1198
+ const r = spawnSync('claude', args, { encoding: 'utf8', shell: platform === 'win32', cwd: os.homedir() });
1199
+ const out = `${r.stdout || ''}${r.stderr || ''}`.trim();
1200
+ if (r.status === 0) return { status: remove ? 'removed' : 'added' };
1201
+ if (/already exists/i.test(out)) return { status: 'already installed' };
1202
+ if (remove && /no mcp server found|not found/i.test(out)) return { status: 'nothing to remove' };
1203
+ return { status: 'failed', detail: out.split('\n')[0] };
1204
+ }
1205
+
1206
+ function runInstall(argv = [], { env = process.env, platform = process.platform, log = console.log } = {}) {
1207
+ const dry = argv.includes('--dry'), remove = argv.includes('--uninstall');
1208
+ const only = (argv.find((a) => a.startsWith('--client=')) || '').slice(9);
1209
+ const want = (c) => !only || only === c;
1210
+ const paths = clientPaths(env, platform);
1211
+ const results = [];
1212
+ if (want('claude-code')) results.push(['Claude Code', claudeCode({ dry, remove }, platform)]);
1213
+ if (want('claude-desktop')) results.push(['Claude Desktop', editJson(paths.desktop, { dry, remove, requireDir: true })]);
1214
+ if (want('cursor')) results.push(['Cursor', editJson(paths.cursor, { dry, remove, requireDir: true })]);
1215
+ for (const [label, r] of results) log(`${label.padEnd(15)} ${r.status}${r.file ? ` (${r.file})` : ''}${r.command ? ` ${r.command}` : ''}${r.detail ? ` ${r.detail}` : ''}`);
1216
+ const done = results.filter(([, r]) => ['added', 'already installed', 'would add'].includes(r.status)).length;
1217
+ if (!remove && !done) log('\nNo supported client found. Add this to your MCP client settings by hand:\n' + JSON.stringify({ mcpServers: { [NAME]: ENTRY } }, null, 2));
1218
+ else if (!remove && !dry) log('\nRestart your client, then ask: "Use anthropos to list the newest Flap launches."');
1219
+ return results;
1220
+ }
1221
+
1222
+ return { clientPaths, mergeConfig, runInstall };
1223
+ })();
1224
+
935
1225
  const __m_guard = (() => {
936
1226
  // Guard: the rules every action must pass before anything is signed. Policy file, daily ledger, approvals and the audit log.
937
1227
  // Nothing in here talks to the network. The action layer feeds it facts (USD value, targets, slippage) and it answers allow / block / ask.
@@ -947,6 +1237,9 @@ const DEFAULT_POLICY = {
947
1237
  sendEnabled: true, // allow send_bnb / send_token (always needs approval and an allowlisted recipient)
948
1238
  bridgeEnabled: true,
949
1239
  swapEnabled: true,
1240
+ launchEnabled: true, // allow flap_launch (a token launch always needs your approval, whatever its value)
1241
+ allowPublicUploads: false, // let flap_prepare_launch publish a token image + details to Flap's public IPFS without asking you first (otherwise it asks through your client, or you pass a metaCid)
1242
+ allowLocalImages: false, // let flap_prepare_launch read an image from a file path on this machine (otherwise https URLs or a metaCid only)
950
1243
  allowedRecipients: [], // addresses transfers may go to. Empty means no transfers at all.
951
1244
  extraAllowedTargets: [], // contract addresses beyond the built-in list that transactions may call
952
1245
  };
@@ -973,7 +1266,7 @@ function normalizePolicy(raw = {}) {
973
1266
  p.maxSlippageBps = num(p.maxSlippageBps, DEFAULT_POLICY.maxSlippageBps, 1, 2000);
974
1267
  p.maxGasUsd = num(p.maxGasUsd, DEFAULT_POLICY.maxGasUsd);
975
1268
  p.maxLossPct = num(p.maxLossPct, DEFAULT_POLICY.maxLossPct, 0, 50);
976
- for (const k of ['blockDangerousTokens', 'sendEnabled', 'bridgeEnabled', 'swapEnabled']) p[k] = raw[k] === undefined ? DEFAULT_POLICY[k] : Boolean(raw[k]);
1269
+ for (const k of ['blockDangerousTokens', 'sendEnabled', 'bridgeEnabled', 'swapEnabled', 'launchEnabled', 'allowPublicUploads', 'allowLocalImages']) p[k] = raw[k] === undefined ? DEFAULT_POLICY[k] : Boolean(raw[k]);
977
1270
  p.allowedRecipients = (Array.isArray(raw.allowedRecipients) ? raw.allowedRecipients : []).filter(isAddr).map((a) => a.toLowerCase());
978
1271
  p.extraAllowedTargets = (Array.isArray(raw.extraAllowedTargets) ? raw.extraAllowedTargets : []).filter(isAddr).map((a) => a.toLowerCase());
979
1272
  return p;
@@ -998,12 +1291,24 @@ class Ledger {
998
1291
  constructor(home, now = () => Date.now()) { this.home = home; this.now = now; fs.mkdirSync(path.join(home, 'pending'), { recursive: true }); }
999
1292
  _state() { try { const s = JSON.parse(fs.readFileSync(path.join(this.home, 'state.json'), 'utf8')); return s.day === dayOf(this.now()) ? s : { day: dayOf(this.now()), spentUsd: 0 }; } catch (_) { return { day: dayOf(this.now()), spentUsd: 0 }; } }
1000
1293
  spentToday() { return this._state().spentUsd; }
1001
- addSpend(usd) { const s = this._state(); s.spentUsd = Number((s.spentUsd + usd).toFixed(4)); fs.writeFileSync(path.join(this.home, 'state.json'), JSON.stringify(s)); return s.spentUsd; }
1294
+ addSpend(usd) { const s = this._state(); s.spentUsd = Math.max(0, Number((s.spentUsd + usd).toFixed(4))); fs.writeFileSync(path.join(this.home, 'state.json'), JSON.stringify(s)); return s.spentUsd; }
1002
1295
  audit(entry) { fs.appendFileSync(path.join(this.home, 'audit.log'), JSON.stringify({ at: new Date(this.now()).toISOString(), ...entry }, jsonSafe) + '\n'); }
1003
1296
  // approvals: the plan is stored on disk; a human approves it with `anthropos-mcp approve <id>` in their own terminal
1004
1297
  savePending(id, plan) { fs.writeFileSync(path.join(this.home, 'pending', `${id}.json`), JSON.stringify({ ...plan, approved: false }, jsonSafe), { mode: 0o600 }); }
1005
1298
  loadPending(id) { if (!/^[a-f0-9]{8}$/.test(id)) return null; try { return JSON.parse(fs.readFileSync(path.join(this.home, 'pending', `${id}.json`), 'utf8')); } catch (_) { return null; } }
1006
1299
  deletePending(id) { try { fs.unlinkSync(path.join(this.home, 'pending', `${id}.json`)); } catch (_) { /* already gone */ } }
1300
+ // Taking an approved action to run it: the rename is atomic, so of any number of concurrent callers exactly one gets the record.
1301
+ // The record stays as <id>.running until finishPending() (it was sent, or may have been: it is never runnable again) or releasePending() (provably not sent).
1302
+ claimPending(id) {
1303
+ if (!/^[a-f0-9]{8}$/.test(id)) return null;
1304
+ const from = path.join(this.home, 'pending', `${id}.json`), to = path.join(this.home, 'pending', `${id}.running`);
1305
+ try { fs.renameSync(from, to); } catch (_) { return null; }
1306
+ let p = null; try { p = JSON.parse(fs.readFileSync(to, 'utf8')); } catch (_) { /* unreadable: give it back */ }
1307
+ if (!p || p.approved !== true || p.expiresAt < this.now()) { try { fs.renameSync(to, from); } catch (_) { /* gone */ } return null; }
1308
+ return p;
1309
+ }
1310
+ releasePending(id) { try { fs.renameSync(path.join(this.home, 'pending', `${id}.running`), path.join(this.home, 'pending', `${id}.json`)); } catch (_) { /* gone */ } }
1311
+ finishPending(id) { try { fs.unlinkSync(path.join(this.home, 'pending', `${id}.running`)); } catch (_) { /* gone */ } }
1007
1312
  approve(id) {
1008
1313
  const p = this.loadPending(id);
1009
1314
  if (!p) throw new Error(`No pending action ${id}.`);
@@ -1016,13 +1321,13 @@ class Ledger {
1016
1321
  /**
1017
1322
  * @param {object} policy normalized policy
1018
1323
  * @param {number} spentToday USD already spent today
1019
- * @param {{ action: 'swap'|'bridge'|'send', usd: number|null, slippageBps?: number, gasUsd?: number|null, lossPct?: number|null,
1324
+ * @param {{ action: 'swap'|'bridge'|'send'|'launch', usd: number|null, slippageBps?: number, gasUsd?: number|null, lossPct?: number|null,
1020
1325
  * targets?: string[], recipient?: string, dangerFlags?: string[] }} intent
1021
1326
  * @returns {{ blocks: string[], needsApproval: boolean, why: string }}
1022
1327
  */
1023
1328
  function checkIntent(policy, spentToday, intent) {
1024
1329
  const blocks = [];
1025
- const enabled = { swap: policy.swapEnabled, bridge: policy.bridgeEnabled, send: policy.sendEnabled }[intent.action];
1330
+ const enabled = { swap: policy.swapEnabled, bridge: policy.bridgeEnabled, send: policy.sendEnabled, launch: policy.launchEnabled }[intent.action];
1026
1331
  if (enabled === false) blocks.push(`${intent.action} is switched off in policy.json.`);
1027
1332
  if (intent.usd === null || intent.usd === undefined || !Number.isFinite(intent.usd)) blocks.push('The USD value of this action could not be determined, so the spending limits cannot be applied.');
1028
1333
  else {
@@ -1036,8 +1341,9 @@ function checkIntent(policy, spentToday, intent) {
1036
1341
  for (const t of intent.targets || []) if (!allowed.has(String(t).toLowerCase())) blocks.push(`Contract ${t} is not on the allowed list. Add it to extraAllowedTargets in policy.json only if you trust it.`);
1037
1342
  if (intent.recipient !== undefined && !policy.allowedRecipients.includes(String(intent.recipient).toLowerCase())) blocks.push(`Recipient ${intent.recipient} is not in allowedRecipients in policy.json.`);
1038
1343
  if (policy.blockDangerousTokens && intent.dangerFlags?.length) blocks.push(`The token scan found dangerous flags: ${intent.dangerFlags.join('; ')}`);
1039
- const needsApproval = intent.action === 'send' || (intent.usd ?? Infinity) > policy.autoApproveUsd;
1040
- return { blocks, needsApproval, why: intent.action === 'send' ? 'Transfers always need approval.' : `Value is above the auto-approve limit of $${policy.autoApproveUsd}.` };
1344
+ const always = intent.action === 'send' || intent.action === 'launch'; // these never run on the agent's say-so alone, whatever they are worth
1345
+ const needsApproval = always || (intent.usd ?? Infinity) > policy.autoApproveUsd;
1346
+ return { blocks, needsApproval, why: intent.action === 'send' ? 'Transfers always need approval.' : intent.action === 'launch' ? 'A token launch always needs approval.' : `Value is above the auto-approve limit of $${policy.autoApproveUsd}.` };
1041
1347
  }
1042
1348
 
1043
1349
  return { DEFAULT_POLICY, PINNED_TARGETS, normalizePolicy, loadPolicy, writeDefaultPolicy, Ledger, checkIntent };
@@ -1078,6 +1384,19 @@ function decodeApprove(data) {
1078
1384
  return { spender: '0x' + data.slice(10 + 24, 10 + 64), amount: BigInt('0x' + data.slice(10 + 64)) };
1079
1385
  }
1080
1386
 
1387
+ /**
1388
+ * Text from outside (on-chain names and symbols, quote labels, API fields) made safe to print in a plan or an approval prompt:
1389
+ * control characters, ESC sequences, line breaks, zero-width and bidi-override characters are removed, whitespace is collapsed, length is capped.
1390
+ */
1391
+ function clean(value, max = 80) {
1392
+ const s = String(value ?? '').replace(/\u001b\[[0-?]*[ -\/]*[@-~]/g, '').replace(/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u180e\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff\ufff9-\ufffb]/g, ' ').replace(/\s+/g, ' ').trim();
1393
+ return [...s].slice(0, max).join('');
1394
+ }
1395
+
1396
+ // One action runs at a time: the daily-spend check and the spend it records must not interleave (tools/call can arrive concurrently).
1397
+ let lock = Promise.resolve();
1398
+ const exclusive = (fn) => { const run = lock.then(fn, fn); lock = run.then(() => {}, () => {}); return run; };
1399
+
1081
1400
  function createActions({ rpc, relay = { quote: relayQuote }, env = process.env, elicit = null, now = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), getBnbUsd = bnbUsd, scan = tokenScan }) {
1082
1401
  const home = homeDir(env);
1083
1402
  let priceCache = null;
@@ -1088,7 +1407,7 @@ function createActions({ rpc, relay = { quote: relayQuote }, env = process.env,
1088
1407
  const policy = loadPolicy(home), ledger = new Ledger(home, now);
1089
1408
  return { wallet, policy, ledger };
1090
1409
  }
1091
- const needWallet = (wallet) => { if (!wallet) throw new Error('No wallet is set up. On the machine running this server, run: anthropos-mcp init (it creates a burner wallet and prints only its address). Then fund that address with a small amount of BNB.'); };
1410
+ const needWallet = (wallet) => { if (!wallet) throw new Error('No wallet is set up. On the machine running this server, run: npx -y anthropos-mcp init (it creates a burner wallet and prints only its address). Then fund that address with a small amount of BNB.'); };
1092
1411
 
1093
1412
  async function resolveToken(text) {
1094
1413
  if (isNative(text)) return { native: true, address: ZERO_ADDRESS, symbol: 'BNB', decimals: 18 };
@@ -1096,16 +1415,17 @@ function createActions({ rpc, relay = { quote: relayQuote }, env = process.env,
1096
1415
  const info = await tokenInfo(rpc, text);
1097
1416
  if (!info.is_contract) throw new Error(`${text} is not a contract on BNB Chain.`);
1098
1417
  if (info.decimals === null || info.decimals === undefined) throw new Error(`${text} does not look like an ERC-20 token (no decimals).`);
1099
- return { native: false, address: text, symbol: info.symbol || 'TOKEN', decimals: info.decimals };
1418
+ return { native: false, address: text, symbol: clean(info.symbol, 24) || 'TOKEN', decimals: info.decimals };
1100
1419
  }
1101
1420
  const amountUnits = (amount, decimals) => { const u = toUnits(String(amount), decimals); if (!u || BigInt(u) <= 0n) throw new Error(`"${amount}" is not a valid positive amount.`); return BigInt(u); };
1102
1421
  const call = (to, data, from) => rpc('eth_call', [{ to, data, ...(from ? { from } : {}) }, 'latest']);
1103
1422
  const balanceOf = async (token, owner) => (token.native ? BigInt(await rpc('eth_getBalance', [owner, 'latest'])) : BigInt(await call(token.address, SEL.balanceOf + a32(owner))));
1104
1423
  const allowanceOf = async (token, owner, spender) => BigInt(await call(token.address, SEL.allowance + a32(owner) + a32(spender)));
1105
1424
 
1425
+ /** Danger flags of the token being bought. A scan that fails is reported as `unavailable`, never as "no flags". */
1106
1426
  async function dangerFlags(token) {
1107
- if (token.native || STABLES.has(lc(token.address)) || lc(token.address) === lc(ADDR.WBNB)) return [];
1108
- try { return (await scan(rpc, token.address)).flags.filter((f) => f.level === 'danger').map((f) => f.text); } catch (_) { return []; }
1427
+ if (token.native || STABLES.has(lc(token.address)) || lc(token.address) === lc(ADDR.WBNB)) return { flags: [], unavailable: null };
1428
+ try { return { flags: (await scan(rpc, token.address)).flags.filter((f) => f.level === 'danger').map((f) => clean(f.text, 200)), unavailable: null }; } catch (e) { return { flags: [], unavailable: clean(e.message || e, 120) || 'error' }; }
1109
1429
  }
1110
1430
 
1111
1431
  // ------------------------------------------------------------------ planning
@@ -1221,14 +1541,16 @@ function createActions({ rpc, relay = { quote: relayQuote }, env = process.env,
1221
1541
  }
1222
1542
  const gasUsd = Number(plain(gas * gasPrice, 18)) * price;
1223
1543
  const outToken = plan.tokens.out;
1224
- const dangerFlagsList = outToken ? await dangerFlags(outToken) : [];
1544
+ const scanned = plan.tokens.out ? await dangerFlags(plan.tokens.out) : { flags: [], unavailable: null };
1545
+ const dangerFlagsList = scanned.flags;
1546
+ if (scanned.unavailable && policy.blockDangerousTokens) extra.push(`Token scan unavailable (${scanned.unavailable}), so ${plan.tokens.out.symbol} could not be checked for danger flags. Nothing was sent.`);
1225
1547
  // balance check
1226
1548
  const need = plan.tokens.in.native ? plan.units + gasEstimateWei(gas, gasPrice) : plan.units;
1227
1549
  const have = await balanceOf(plan.tokens.in, from);
1228
1550
  if (have < (plan.tokens.in.native ? need : plan.units)) extra.push(`Wallet balance is too low: it holds ${plain(have, plan.tokens.in.decimals)} ${plan.tokens.in.symbol}${plan.tokens.in.native ? ' (including gas)' : ''}.`);
1229
1551
  if (!plan.tokens.in.native) { const bnbHave = BigInt(await rpc('eth_getBalance', [from, 'latest'])); if (bnbHave < gasEstimateWei(gas, gasPrice)) extra.push('The wallet has too little BNB to pay for gas.'); }
1230
1552
  const verdict = checkIntent(policy, ledger.spentToday(), { action: plan.action, usd: plan.usd, slippageBps: plan.slippageBps, gasUsd, lossPct: plan.lossPct, targets, recipient: plan.recipient, dangerFlags: dangerFlagsList });
1231
- return { blocks: [...extra, ...verdict.blocks], needsApproval: verdict.needsApproval, why: verdict.why, gasUsd, simulated };
1553
+ return { blocks: [...extra, ...verdict.blocks], needsApproval: verdict.needsApproval || Boolean(scanned.unavailable), why: scanned.unavailable && !verdict.needsApproval ? 'The token scan was unavailable, so a human must look at this.' : verdict.why, gasUsd, simulated, scanUnavailable: scanned.unavailable };
1232
1554
  }
1233
1555
  const gasEstimateWei = (gas, gasPrice) => (gas * gasPrice * 125n) / 100n;
1234
1556
 
@@ -1237,8 +1559,8 @@ function createActions({ rpc, relay = { quote: relayQuote }, env = process.env,
1237
1559
  for (let i = 0; i < tries; i++) { const r = await rpc('eth_getTransactionReceipt', [hash]).catch(() => null); if (r) return r; await sleep(2000); }
1238
1560
  throw new Error(`Timed out waiting for ${hash}. It may still confirm: ${explorer(hash)}`);
1239
1561
  }
1240
- async function send(plan, wallet) {
1241
- const hashes = [];
1562
+ /** Sends the steps in order. `state` is filled as it goes so the caller knows afterwards whether anything may have reached the network. */
1563
+ async function send(plan, wallet, state) {
1242
1564
  for (let i = 0; i < plan.steps.length; i++) {
1243
1565
  const s = plan.steps[i], value = BigInt(s.value || 0);
1244
1566
  const tx = { from: wallet.address, to: s.to, data: s.data, value: hexv(value) };
@@ -1247,22 +1569,37 @@ function createActions({ rpc, relay = { quote: relayQuote }, env = process.env,
1247
1569
  const nonce = BigInt(await rpc('eth_getTransactionCount', [wallet.address, 'pending']));
1248
1570
  const gasPrice = BigInt(await rpc('eth_gasPrice', []));
1249
1571
  const signed = wallet.signTx({ nonce, gasPrice, gasLimit: (est * 125n) / 100n, to: s.to, value, data: s.data, chainId: CHAIN_ID });
1572
+ state.attempted = true; // from here on the transaction may be on its way, whatever happens next
1250
1573
  const hash = await rpc('eth_sendRawTransaction', [signed.raw]);
1251
- hashes.push(hash);
1574
+ state.hashes.push(hash);
1252
1575
  const receipt = await waitReceipt(hash);
1253
- if (receipt.status !== '0x1') throw Object.assign(new Error(`Step ${i + 1} (${s.label}) failed on chain: ${explorer(hash)}`), { hashes });
1576
+ if (receipt.status !== '0x1') throw new Error(`Step ${i + 1} (${s.label}) failed on chain: ${explorer(hash)}`);
1254
1577
  }
1255
- return hashes;
1578
+ return state.hashes;
1256
1579
  }
1257
1580
 
1258
- async function finish(plan, ctx, { id = null } = {}) {
1581
+ /** Make a plan safe to print: outside text cleaned, every step has a value. */
1582
+ function tidy(plan) {
1583
+ plan.summary = clean(plan.summary, 700);
1584
+ if (plan.route) plan.route = clean(plan.route, 200);
1585
+ plan.steps = plan.steps.map((s) => ({ ...s, label: clean(s.label, 300), value: BigInt(s.value || 0) }));
1586
+ return plan;
1587
+ }
1588
+ const stepLine = (s, i) => `${i + 1}. ${s.label} -> ${s.to}${s.value > 0n ? ` (sends ${plain(s.value, 18)} BNB)` : ''}`;
1589
+
1590
+ const finish = (plan, ctx, opts) => exclusive(() => finishNow(plan, ctx, opts));
1591
+ async function finishNow(plan, ctx, { id = null } = {}) {
1259
1592
  const { wallet, policy, ledger } = ctx;
1593
+ tidy(plan);
1260
1594
  const report = await inspect(plan, wallet, policy, ledger);
1261
- const base = { summary: plan.summary, valueUsd: plan.usd === null ? null : Number(plan.usd.toFixed(2)), gasUsd: Number(report.gasUsd.toFixed(3)), steps: plan.steps.map((s) => s.label) };
1595
+ const base = { summary: plan.summary, valueUsd: plan.usd === null ? null : Number(plan.usd.toFixed(2)), gasUsd: Number(report.gasUsd.toFixed(3)), steps: plan.steps.map((s) => s.label), ...(report.scanUnavailable ? { scan: `unavailable (${report.scanUnavailable})` } : {}) };
1262
1596
  if (report.blocks.length) { ledger.audit({ action: plan.action, status: 'blocked', summary: plan.summary, usd: plan.usd, reasons: report.blocks }); return { status: 'blocked', ...base, reasons: report.blocks }; }
1263
- const approved = id ? ledger.loadPending(id)?.approved === true : false;
1264
- if (report.needsApproval && !approved) {
1265
- const text = `${plan.summary}\nValue about $${(plan.usd ?? 0).toFixed(2)}, gas about $${report.gasUsd.toFixed(3)}.\nTransactions:\n${plan.steps.map((s, i) => `${i + 1}. ${s.label} -> ${s.to}`).join('\n')}`;
1597
+ let claimed = false;
1598
+ if (id) { // an approved action: take it, so nobody else can run it
1599
+ if (!ledger.claimPending(id)) return { status: 'not_found', ...base, note: 'That pending action is gone, was not approved, expired, or is already running. Nothing was sent.' };
1600
+ claimed = true;
1601
+ } else if (report.needsApproval) {
1602
+ const text = `${plan.summary}\nValue about $${(plan.usd ?? 0).toFixed(2)}, gas about $${report.gasUsd.toFixed(3)}.${report.scanUnavailable ? '\nThe token scan was unavailable.' : ''}\nTransactions:\n${plan.steps.map(stepLine).join('\n')}`;
1266
1603
  // null from elicit() means the client cannot show a prompt; true / false is the person's answer
1267
1604
  const answer = elicit ? await elicit(text).catch(() => false) : null;
1268
1605
  if (answer === false) { ledger.audit({ action: plan.action, status: 'declined', summary: plan.summary }); return { status: 'declined', ...base, note: 'The approval was declined or timed out. Nothing was sent.' }; }
@@ -1270,18 +1607,23 @@ function createActions({ rpc, relay = { quote: relayQuote }, env = process.env,
1270
1607
  const pid = randomHex(4);
1271
1608
  ledger.savePending(pid, { id: pid, plan: serializePlan(plan), createdAt: now(), expiresAt: now() + PLAN_TTL_MS });
1272
1609
  ledger.audit({ action: plan.action, status: 'approval_required', id: pid, summary: plan.summary, usd: plan.usd });
1273
- return { status: 'approval_required', id: pid, ...base, why: report.why, how_to_approve: `A human must run this on the machine that holds the wallet: anthropos-mcp approve ${pid} then call confirm_action with id "${pid}". Expires in 10 minutes.` };
1610
+ return { status: 'approval_required', id: pid, ...base, why: report.why, how_to_approve: `A human must run this on the machine that holds the wallet: npx -y anthropos-mcp approve ${pid} then call confirm_action with id "${pid}". Expires in 10 minutes.` };
1274
1611
  }
1275
1612
  }
1613
+ // The spend is booked before anything is sent and given back only if nothing can have reached the network.
1614
+ const reserved = plan.usd === null ? 0 : plan.usd;
1615
+ if (reserved) ledger.addSpend(reserved);
1616
+ const state = { attempted: false, hashes: [] };
1276
1617
  try {
1277
- const hashes = await send(plan, wallet);
1278
- const spent = plan.usd === null ? 0 : ledger.addSpend(plan.usd);
1279
- if (id) ledger.deletePending(id);
1618
+ const hashes = await send(plan, wallet, state);
1619
+ if (claimed) ledger.finishPending(id);
1280
1620
  ledger.audit({ action: plan.action, status: 'sent', summary: plan.summary, usd: plan.usd, hashes });
1281
- return { status: 'sent', ...base, transactions: hashes.map((h) => ({ hash: h, url: explorer(h) })), spentTodayUsd: spent };
1621
+ return { status: 'sent', ...base, transactions: hashes.map((h) => ({ hash: h, url: explorer(h) })), spentTodayUsd: ledger.spentToday(), ...(plan.sentInfo || {}) };
1282
1622
  } catch (e) {
1283
- ledger.audit({ action: plan.action, status: 'failed', summary: plan.summary, error: String(e.message || e).slice(0, 300), hashes: e.hashes });
1284
- return { status: 'failed', ...base, error: String(e.message || e), transactions: (e.hashes || []).map((h) => ({ hash: h, url: explorer(h) })) };
1623
+ if (!state.attempted) { if (reserved) ledger.addSpend(-reserved); if (claimed) ledger.releasePending(id); } // provably not sent: nothing is booked and the approval still stands
1624
+ else if (claimed) ledger.finishPending(id); // may be on chain (even after a receipt timeout): this approval is used up
1625
+ ledger.audit({ action: plan.action, status: 'failed', summary: plan.summary, error: String(e.message || e).slice(0, 300), hashes: state.hashes, maybeSent: state.attempted });
1626
+ return { status: 'failed', ...base, error: String(e.message || e), transactions: state.hashes.map((h) => ({ hash: h, url: explorer(h) })), ...(state.attempted ? { note: 'A transaction may have been broadcast. Check the explorer before trying again; this approval cannot be used a second time.' } : { note: 'Nothing was sent.' }) };
1285
1627
  }
1286
1628
  }
1287
1629
  const serializePlan = (plan) => JSON.parse(JSON.stringify(plan, (_, v) => (typeof v === 'bigint' ? { __bigint: v.toString() } : v)));
@@ -1293,14 +1635,15 @@ function createActions({ rpc, relay = { quote: relayQuote }, env = process.env,
1293
1635
  const exec = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true };
1294
1636
  const quoteHint = { readOnlyHint: true, openWorldHint: true };
1295
1637
  const wrapQuote = async (plan, ctx) => {
1638
+ tidy(plan);
1296
1639
  let report = null;
1297
1640
  if (ctx.wallet) { try { report = await inspect(plan, ctx.wallet, ctx.policy, ctx.ledger); } catch (e) { report = { blocks: [String(e.message || e)], needsApproval: false, gasUsd: 0 }; } }
1298
- return { summary: plan.summary, route: plan.route, valueUsd: plan.usd === null ? null : Number(plan.usd.toFixed(2)), steps: plan.steps.map((s) => ({ what: s.label, to: s.to })), guard: report ? { wouldBlock: report.blocks, needsApproval: report.needsApproval, gasUsd: Number(report.gasUsd.toFixed(3)) } : 'No wallet yet, so Guard checks were not run.', note: 'Quote only: nothing was signed or sent.' };
1641
+ return { summary: plan.summary, route: plan.route, valueUsd: plan.usd === null ? null : Number(plan.usd.toFixed(2)), steps: plan.steps.map((s) => ({ what: s.label, to: s.to, value_bnb: plain(s.value, 18) })), guard: report ? { wouldBlock: report.blocks, needsApproval: report.needsApproval, gasUsd: Number(report.gasUsd.toFixed(3)), ...(report.scanUnavailable ? { scan: `unavailable (${report.scanUnavailable})` } : {}) } : 'No wallet yet, so Guard checks were not run.', note: 'Quote only: nothing was signed or sent.' };
1299
1642
  };
1300
1643
 
1301
- return [
1644
+ const tools = [
1302
1645
  { name: 'wallet_info', description: 'The local ANTHROPOS wallet: address, BNB balance, spending limits and how much of today\'s limit is used. Never reveals the key.', inputSchema: { type: 'object', properties: {} }, annotations: quoteHint,
1303
- run: async () => { const { wallet, policy, ledger } = context(); if (!wallet) return { wallet: null, setup: 'Run `anthropos-mcp init` on this machine to create a burner wallet, then fund it with a small amount of BNB.' };
1646
+ run: async () => { const { wallet, policy, ledger } = context(); if (!wallet) return { wallet: null, setup: 'Run `npx -y anthropos-mcp init` on this machine to create a burner wallet, then fund it with a small amount of BNB.' };
1304
1647
  const bal = BigInt(await rpc('eth_getBalance', [wallet.address, 'latest'])), price = await bnbPrice();
1305
1648
  return { address: wallet.address, chain: 'BNB Smart Chain (56)', balanceBnb: plain(bal, 18), balanceUsd: Number((Number(plain(bal, 18)) * price).toFixed(2)), limits: { perActionUsd: policy.perTxUsd, dailyUsd: policy.dailyUsd, spentTodayUsd: ledger.spentToday(), autoApproveUsd: policy.autoApproveUsd, maxSlippagePct: policy.maxSlippageBps / 100, allowedRecipients: policy.allowedRecipients.length }, pendingApprovals: ledger.listPending().map((p) => ({ id: p.id, summary: p.plan.summary, approved: p.approved })) }; } },
1306
1649
  { name: 'swap_quote', description: 'Quote a swap on BNB Chain without sending anything. Uses the Flap Portal for tokens still on their bonding curve and Relay for everything else. Also runs the Guard checks and says what would be blocked.', inputSchema: { type: 'object', properties: { tokenIn: { type: 'string', description: '"BNB" or a token address' }, tokenOut: { type: 'string', description: '"BNB" or a token address' }, amount: schemaAmount, slippageBps: { type: 'integer', description: 'Max slippage in basis points (default 100 = 1%)' } }, required: ['tokenIn', 'tokenOut', 'amount'] }, annotations: quoteHint,
@@ -1316,37 +1659,1412 @@ function createActions({ rpc, relay = { quote: relayQuote }, env = process.env,
1316
1659
  { name: 'send_token', description: 'Send a stablecoin or WBNB from the local wallet. Only to allowlisted recipients, always needs human approval. Other tokens cannot be valued, so they are refused.', inputSchema: { type: 'object', properties: { token: { type: 'string' }, to: { type: 'string' }, amount: schemaAmount }, required: ['token', 'to', 'amount'] }, annotations: exec,
1317
1660
  run: async (a) => { const ctx = context(); needWallet(ctx.wallet); const plan = await planSendToken(a, ctx.wallet); if (plan.usd === null) return { status: 'blocked', summary: plan.summary, reasons: [plan.note] }; return finish(plan, ctx); } },
1318
1661
  { name: 'confirm_action', description: 'Run an action that was prepared and then approved by a human with `anthropos-mcp approve <id>`. Does nothing if it was not approved.', inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'The id returned by an execute tool' } }, required: ['id'] }, annotations: exec,
1319
- run: async ({ id }) => { const ctx = context(); needWallet(ctx.wallet); const p = ctx.ledger.loadPending(String(id));
1662
+ run: ({ id }) => exclusive(async () => { const ctx = context(); needWallet(ctx.wallet); const p = ctx.ledger.loadPending(String(id));
1320
1663
  if (!p) return { status: 'not_found', note: 'No such pending action (it may have expired or already run).' };
1321
1664
  if (p.expiresAt < now()) { ctx.ledger.deletePending(p.id); return { status: 'expired', note: 'Prepare the action again.' }; }
1322
- if (!p.approved) return { status: 'waiting_for_human', note: `Not approved yet. The wallet owner must run: anthropos-mcp approve ${p.id}` };
1323
- return finish(revivePlan(p.plan), ctx, { id: p.id }); } },
1665
+ if (!p.approved) return { status: 'waiting_for_human', note: `Not approved yet. The wallet owner must run: npx -y anthropos-mcp approve ${p.id}` };
1666
+ return finishNow(revivePlan(p.plan), ctx, { id: p.id }); }) },
1324
1667
  { name: 'policy_show', description: 'The active spending policy and the built-in list of contracts that transactions may call.', inputSchema: { type: 'object', properties: {} }, annotations: quoteHint,
1325
1668
  run: async () => { const { policy } = context(); return { policy, editFile: `${home}/policy.json`, note: 'Only the wallet owner can change limits, by editing this file. The agent cannot.' }; } },
1326
1669
  ];
1670
+ // The pieces other tool sets (launch.js) build on, so they go through the same Guard, approval and signing path as swaps. Not an MCP tool.
1671
+ Object.defineProperty(tools, 'engine', { value: { context, needWallet, inspect, finish, tidy, bnbPrice, serializePlan, revivePlan }, enumerable: false });
1672
+ return tools;
1673
+ }
1674
+
1675
+ return { plain, decodeApprove, clean, createActions };
1676
+ })();
1677
+
1678
+ const __m_perps = (() => {
1679
+ // Perpetual futures tools (Aster). READ-ONLY: public market data only, no key, no signing.
1680
+ // Aster trading needs the user's own Aster API wallet (agent) signing EIP-712 messages and a deposit. None of that exists here,
1681
+ // so there is deliberately no order placement, cancel or account tool, and every description says so.
1682
+ // The pure maths (step rounding, notional, funding per hour, liquidation estimate, book walking) is exported and unit-tested.
1683
+
1684
+ const DEFAULT_API = 'https://fapi.asterdex.com';
1685
+ const TIMEOUT_MS = 12000;
1686
+ const INFO_TTL = 10 * 60 * 1000; // exchangeInfo (~900 KB) and fundingInfo change rarely
1687
+ const TICKER_TTL = 8000;
1688
+ const NO_TRADING = 'Trading is not available yet: ANTHROPOS cannot place, cancel or sign Aster orders. It would need your own Aster API wallet and a deposit.';
1689
+ const INTERVALS = ['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h', '1d', '3d', '1w', '1M'];
1690
+ const DEPTHS = [5, 10, 20, 50, 100];
1691
+ const CATEGORIES = ['all', 'crypto', 'stocks', 'etf', 'commodities'];
1692
+ const SORTS = ['volume', 'gainers', 'losers', 'funding_high', 'funding_low'];
1693
+ const QUOTES = ['USDT', 'USD1', 'USDC', 'U'];
1694
+ const READ = { readOnlyHint: true, openWorldHint: true };
1695
+
1696
+ const num = (v) => { if (v === null || v === undefined || v === '') return null; const n = Number(v); return Number.isFinite(n) ? n : null; };
1697
+ const iso = (ms) => (Number.isFinite(Number(ms)) && ms ? new Date(Number(ms)).toISOString() : null);
1698
+ const round = (v, digits) => (v === null || !Number.isFinite(v) ? null : Number(v.toFixed(digits)));
1699
+ const sig = (v, digits = 8) => (v === null || !Number.isFinite(v) ? null : Number(v.toPrecision(digits)));
1700
+
1701
+ // ---------------------------------------------------------------------------------------------------- pure maths
1702
+ /** Number of decimals in a step such as "0.001" or 1e-8. */
1703
+ function decimalsOf(step) {
1704
+ const s = String(Number(step));
1705
+ const exp = /e-(\d+)$/.exec(s);
1706
+ if (exp) { const mant = (s.split('e')[0].split('.')[1] || '').length; return Number(exp[1]) + mant; }
1707
+ return (s.split('.')[1] || '').length;
1708
+ }
1709
+
1710
+ /** Round a quantity DOWN to the market step. Never rounds up beyond float noise, so an order never exceeds the size asked for. */
1711
+ function floorToStep(value, step) {
1712
+ const v = Number(value), st = Number(step);
1713
+ if (!(v > 0) || !(st > 0)) return 0;
1714
+ const decimals = decimalsOf(st);
1715
+ const steps = Math.floor((v / st) * (1 + 1e-12));
1716
+ return Number((steps * st).toFixed(decimals));
1717
+ }
1718
+
1719
+ /** Funding rate per hour from a settled rate and the funding interval in hours. */
1720
+ const fundingPerHour = (rate, intervalHours) => (rate === null || rate === undefined || !(intervalHours > 0) ? null : rate / intervalHours);
1721
+
1722
+ /** Approximate liquidation price of an isolated linear (USDT-margined) position. Ignores fees, funding and tiered maintenance margin. */
1723
+ function liquidationPrice({ side, entry, leverage, maintenanceRate }) {
1724
+ const inv = 1 / leverage;
1725
+ const p = side === 'long' ? (entry * (1 - inv)) / (1 - maintenanceRate) : (entry * (1 + inv)) / (1 + maintenanceRate);
1726
+ return Math.max(0, p);
1727
+ }
1728
+
1729
+ /** Order maths. `meta` carries the market's filters. Nothing is sent anywhere. */
1730
+ function previewOrder({ meta, side, sizeUsd, leverage, price, priceGiven = false, ratePerHour = null }) {
1731
+ const qtyNum = floorToStep(sizeUsd / price, meta.stepSize || 0);
1732
+ const qty = meta.stepSize ? qtyNum.toFixed(decimalsOf(meta.stepSize)) : String(qtyNum);
1733
+ const notional = Number((qtyNum * price).toFixed(8));
1734
+ const problems = [], warnings = [];
1735
+ const maxQty = (priceGiven ? meta.maxQty : meta.marketMaxQty ?? meta.maxQty) ?? null;
1736
+ const checks = {
1737
+ minQty: { ok: qtyNum >= (meta.minQty || 0) && qtyNum > 0, required: meta.minQty },
1738
+ minNotional: { ok: meta.minNotional === null || notional >= meta.minNotional, required: meta.minNotional },
1739
+ maxQty: { ok: maxQty === null || qtyNum <= maxQty, allowed: maxQty },
1740
+ };
1741
+ if (qtyNum <= 0) problems.push(`Size is below one step (${meta.stepSize}) of ${meta.base}: the order would round down to zero.`);
1742
+ else if (!checks.minQty.ok) problems.push(`Quantity ${qty} is below the minimum ${meta.minQty} ${meta.base}.`);
1743
+ if (qtyNum > 0 && !checks.minNotional.ok) problems.push(`Notional ${round(notional, 4)} ${meta.quote} is below the minimum ${meta.minNotional} ${meta.quote}.`);
1744
+ if (!checks.maxQty.ok) problems.push(`Quantity ${qty} is above the maximum ${maxQty} ${meta.base} per order.`);
1745
+ if (priceGiven && meta.tickSize && Math.abs(price / meta.tickSize - Math.round(price / meta.tickSize)) > 1e-6) problems.push(`Price ${price} is not a multiple of the tick size ${meta.tickSize}.`);
1746
+ if (meta.status !== 'TRADING') problems.push(`Market status is ${meta.status}, not TRADING.`);
1747
+
1748
+ const mmr = meta.maintMarginPercent === null ? null : meta.maintMarginPercent / 100;
1749
+ const impliedMax = meta.requiredMarginPercent ? Math.floor(100 / meta.requiredMarginPercent) : null;
1750
+ if (impliedMax !== null && leverage > impliedMax) warnings.push(`${leverage}x is above the ${impliedMax}x implied by the exchange-published required margin (${meta.requiredMarginPercent}%). The exchange may reject it; the real per-account cap needs a signed call that was not made.`);
1751
+
1752
+ let liquidation = null;
1753
+ if (mmr !== null) {
1754
+ const immediate = 1 / leverage <= mmr;
1755
+ if (immediate) warnings.push(`At ${leverage}x the margin (${round(100 / leverage, 3)}%) does not exceed the maintenance margin (${meta.maintMarginPercent}%): the position would be liquidated at once.`);
1756
+ const raw = liquidationPrice({ side, entry: price, leverage, maintenanceRate: mmr });
1757
+ liquidation = {
1758
+ approximate: true,
1759
+ price: meta.pricePrecision === null ? sig(raw) : round(raw, meta.pricePrecision),
1760
+ distanceFromEntryPct: round((Math.abs(raw - price) / price) * 100, 3),
1761
+ maintenanceMarginPct: meta.maintMarginPercent,
1762
+ method: side === 'long' ? 'entry x (1 - 1/leverage) / (1 - maintenance rate)' : 'entry x (1 + 1/leverage) / (1 + maintenance rate)',
1763
+ assumes: 'isolated margin, one position, price held at the entry price until liquidation',
1764
+ ignores: ['trading fees', 'funding payments', 'cross-margin balance', 'tiered maintenance margin for larger sizes (needs the signed leverage-bracket endpoint)', 'the exchange liquidation fee'],
1765
+ };
1766
+ }
1767
+ const funding = ratePerHour === null ? null : {
1768
+ lastRatePerHourPct: sig(ratePerHour * 100, 6),
1769
+ youPayPerHourUsd: round((side === 'long' ? 1 : -1) * notional * ratePerHour, 6),
1770
+ note: 'Positive = you pay, negative = you receive. Uses the last settled rate; the next one can differ.',
1771
+ };
1772
+ return {
1773
+ quantity: qty, quantityNumber: qtyNum, notional, roundedDownByUsd: round(sizeUsd - notional, 6), checks, problems, warnings,
1774
+ valid: problems.length === 0,
1775
+ margin: { initialMarginUsd: round(notional / leverage, 6), leverage, basis: 'notional / leverage, isolated margin, before fees' },
1776
+ liquidation, funding,
1777
+ };
1778
+ }
1779
+
1780
+ /** Book levels as rows with cumulative size and notional. */
1781
+ function bookLevels(levels, limit = levels.length) {
1782
+ let size = 0, notional = 0;
1783
+ return levels.slice(0, limit).map(([p, q]) => {
1784
+ const price = Number(p), qty = Number(q);
1785
+ size += qty; notional += price * qty;
1786
+ return { price, size: qty, notional: sig(price * qty, 10), cumulativeSize: sig(size, 10), cumulativeNotional: sig(notional, 10) };
1787
+ });
1788
+ }
1789
+
1790
+ /** Walk one side of the book for a USD amount: average price and slippage versus the best level. */
1791
+ function walkBook(levels, usd) {
1792
+ let left = usd, qty = 0, spent = 0;
1793
+ for (const [p, q] of levels) {
1794
+ const price = Number(p), size = Number(q);
1795
+ const take = Math.min(size, left / price);
1796
+ qty += take; spent += take * price; left -= take * price;
1797
+ if (left <= 1e-9) break;
1798
+ }
1799
+ const best = Number(levels[0]?.[0]);
1800
+ const avg = qty > 0 ? spent / qty : null;
1801
+ return { requestedUsd: usd, filledUsd: round(spent, 4), fullyFilled: left <= 1e-6, averagePrice: sig(avg), slippagePctVsBest: avg === null || !best ? null : round((Math.abs(avg - best) / best) * 100, 4) };
1802
+ }
1803
+
1804
+ /** crypto / stocks / etf / commodities from the exchange's underlying sub-type tags. */
1805
+ function categoryOf(subType = []) {
1806
+ if (subType.includes('STOCK')) return 'stocks';
1807
+ if (subType.includes('ETF')) return 'etf';
1808
+ if (subType.includes('Commodities')) return 'commodities';
1809
+ return 'crypto';
1810
+ }
1811
+
1812
+ function parseMeta(s, fundingBySymbol) {
1813
+ const f = Object.fromEntries((s.filters || []).map((x) => [x.filterType, x]));
1814
+ const fi = fundingBySymbol.get(s.symbol);
1815
+ const subType = s.underlyingSubType || [];
1816
+ return {
1817
+ symbol: s.symbol, base: s.baseAsset, quote: s.quoteAsset, status: s.status, contractType: s.contractType, subType, category: categoryOf(subType),
1818
+ tickSize: num(f.PRICE_FILTER?.tickSize), stepSize: num(f.LOT_SIZE?.stepSize), minQty: num(f.LOT_SIZE?.minQty), maxQty: num(f.LOT_SIZE?.maxQty),
1819
+ marketMaxQty: num(f.MARKET_LOT_SIZE?.maxQty), minNotional: num(f.MIN_NOTIONAL?.notional),
1820
+ pricePrecision: Number.isInteger(s.pricePrecision) ? s.pricePrecision : null, quantityPrecision: Number.isInteger(s.quantityPrecision) ? s.quantityPrecision : null,
1821
+ requiredMarginPercent: num(s.requiredMarginPercent), maintMarginPercent: num(s.maintMarginPercent),
1822
+ intervalHours: fi?.fundingIntervalHours > 0 ? fi.fundingIntervalHours : 8, fundingCap: num(fi?.fundingFeeCap), fundingFloor: num(fi?.fundingFeeFloor),
1823
+ onboardDate: iso(s.onboardDate), tags: s.tags || [],
1824
+ };
1825
+ }
1826
+
1827
+ // ---------------------------------------------------------------------------------------------------- tools
1828
+ function createPerps({ env = process.env, fetchImpl = globalThis.fetch, now = () => Date.now() } = {}) {
1829
+ const cache = new Map();
1830
+ let blockedUntil = 0, blockedStatus = 0;
1831
+
1832
+ const baseUrl = () => {
1833
+ const raw = (env.ANTHROPOS_PERPS_API || DEFAULT_API).trim().replace(/\/+$/, '');
1834
+ let u; try { u = new URL(raw); } catch (_) { throw new Error(`ANTHROPOS_PERPS_API is not a valid URL: ${raw}`); }
1835
+ if (u.protocol !== 'https:' && u.protocol !== 'http:') throw new Error(`ANTHROPOS_PERPS_API must be an http(s) URL: ${raw}`);
1836
+ return raw;
1837
+ };
1838
+ const rateError = () => {
1839
+ const err = new Error(`Aster rate limit reached (HTTP ${blockedStatus}). Backing off: no further requests will be sent for about ${Math.max(1, Math.ceil((blockedUntil - now()) / 1000))} s. Try again after that${blockedStatus === 418 ? ' (418 means the IP was temporarily banned for ignoring earlier limits)' : ''}.`);
1840
+ err.rateLimited = true;
1841
+ return err;
1842
+ };
1843
+
1844
+ async function fetchJson(path) {
1845
+ let res;
1846
+ try { res = await fetchImpl(baseUrl() + path, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) }); }
1847
+ catch (e) {
1848
+ if (/ANTHROPOS_PERPS_API/.test(e.message)) throw e;
1849
+ throw new Error(`Cannot reach the Aster API: ${e.name === 'TimeoutError' ? 'timed out' : e.message}`);
1850
+ }
1851
+ if (res.status === 429 || res.status === 418) {
1852
+ const ra = num(res.headers?.get?.('retry-after'));
1853
+ const wait = ra !== null && ra > 0 ? ra : res.status === 418 ? 300 : 60;
1854
+ blockedUntil = now() + wait * 1000; blockedStatus = res.status;
1855
+ throw rateError();
1856
+ }
1857
+ const text = await res.text();
1858
+ let body = null; try { body = JSON.parse(text); } catch (_) { /* reported below */ }
1859
+ if (!res.ok) {
1860
+ const msg = body && typeof body === 'object' && body.msg ? `: ${body.msg}` : '';
1861
+ throw new Error(`Aster API HTTP ${res.status}${msg} (${path.split('?')[0]})`);
1862
+ }
1863
+ if (body === null) throw new Error(`Aster API returned a non-JSON response (${path.split('?')[0]})`);
1864
+ return body;
1865
+ }
1866
+
1867
+ /** GET with a per-path cache and one shared in-flight request; fails fast while backing off after a 429/418. */
1868
+ function get(path, ttl = TICKER_TTL) {
1869
+ const hit = cache.get(path);
1870
+ if (hit && now() - hit.at < ttl) return hit.promise;
1871
+ if (blockedUntil > now()) return Promise.reject(rateError());
1872
+ if (cache.size > 400) cache.clear();
1873
+ const promise = fetchJson(path);
1874
+ cache.set(path, { at: now(), promise });
1875
+ promise.catch(() => { if (cache.get(path)?.promise === promise) cache.delete(path); });
1876
+ return promise;
1877
+ }
1878
+ /** A request whose failure should not sink the whole answer. Rate limits still propagate. */
1879
+ const optional = (promise) => promise.catch((e) => { if (e.rateLimited) throw e; return null; });
1880
+
1881
+ async function marketInfo() {
1882
+ const [ex, fi] = await Promise.all([get('/fapi/v1/exchangeInfo', INFO_TTL), get('/fapi/v1/fundingInfo', INFO_TTL)]);
1883
+ const fundingBySymbol = new Map((Array.isArray(fi) ? fi : []).map((x) => [x.symbol, x]));
1884
+ const out = new Map();
1885
+ for (const s of ex.symbols || []) if (s.contractType === 'PERPETUAL') out.set(s.symbol, parseMeta(s, fundingBySymbol));
1886
+ return out;
1887
+ }
1888
+ function resolve(input, info) {
1889
+ if (typeof input !== 'string' || !input.trim()) throw new Error('symbol is required, e.g. "BTCUSDT" or "BTC".');
1890
+ const clean = input.trim().toUpperCase().replace(/[\s/_-]+/g, '');
1891
+ const candidates = [clean, clean.replace(/PERP$/, '')];
1892
+ for (const c of candidates) {
1893
+ if (info.has(c)) return info.get(c);
1894
+ for (const q of QUOTES) if (info.has(c + q)) return info.get(c + q);
1895
+ }
1896
+ const near = [...info.values()].filter((m) => m.status === 'TRADING' && (m.base.includes(clean) || m.symbol.includes(clean))).slice(0, 5).map((m) => m.symbol);
1897
+ throw new Error(`Unknown Aster perpetual "${input}".${near.length ? ` Did you mean: ${near.join(', ')}?` : ' Use perps_markets to search.'}`);
1898
+ }
1899
+ const need = async (symbol) => resolve(symbol, await marketInfo());
1900
+ const q = encodeURIComponent;
1901
+ const intArg = (v, def, lo, hi, name) => {
1902
+ if (v === undefined || v === null) return def;
1903
+ const n = Number(v);
1904
+ if (!Number.isInteger(n) || n < lo || n > hi) throw new Error(`${name} must be an integer from ${lo} to ${hi}.`);
1905
+ return n;
1906
+ };
1907
+ const oneOf = (v, list, def, name) => {
1908
+ if (v === undefined || v === null) return def;
1909
+ if (!list.includes(v)) throw new Error(`${name} must be one of: ${list.join(', ')}.`);
1910
+ return v;
1911
+ };
1912
+ const source = () => `Aster public API (${baseUrl()}), no key`;
1913
+
1914
+ // ---- perps_markets
1915
+ async function markets(args = {}) {
1916
+ const category = oneOf(args.category, CATEGORIES, 'all', 'category');
1917
+ const sort = oneOf(args.sort, SORTS, 'volume', 'sort');
1918
+ const limit = intArg(args.limit, 20, 1, 100, 'limit');
1919
+ const quote = args.quote === undefined ? null : String(args.quote).toUpperCase();
1920
+ const query = args.query ? String(args.query).trim().toUpperCase() : '';
1921
+ const minVol = args.minVolumeUsd === undefined ? 0 : num(args.minVolumeUsd);
1922
+ if (minVol === null || minVol < 0) throw new Error('minVolumeUsd must be a number >= 0.');
1923
+ const [info, tickers, premium] = await Promise.all([marketInfo(), get('/fapi/v1/ticker/24hr'), get('/fapi/v1/premiumIndex')]);
1924
+ const prem = new Map(premium.map((p) => [p.symbol, p]));
1925
+ const all = [];
1926
+ for (const t of tickers) {
1927
+ const m = info.get(t.symbol);
1928
+ if (!m || m.status !== 'TRADING') continue;
1929
+ const last = num(t.lastPrice); if (last === null) continue;
1930
+ const p = prem.get(t.symbol), rate = p ? num(p.lastFundingRate) : null, perHour = fundingPerHour(rate, m.intervalHours);
1931
+ all.push({
1932
+ symbol: m.symbol, base: m.base, quote: m.quote, category: m.category, price: last, markPrice: p ? num(p.markPrice) : null, indexPrice: p ? num(p.indexPrice) : null,
1933
+ change24hPct: num(t.priceChangePercent), volume24hQuote: num(t.quoteVolume), fundingRatePct: rate === null ? null : sig(rate * 100, 6), fundingIntervalHours: m.intervalHours,
1934
+ fundingPerHourPct: perHour === null ? null : sig(perHour * 100, 6), nextFundingTime: p ? iso(p.nextFundingTime) : null, _perHour: perHour,
1935
+ });
1936
+ }
1937
+ const hit = all.filter((m) => (category === 'all' || m.category === category) && (!quote || m.quote === quote) && (!query || m.base.includes(query) || m.symbol.includes(query)) && (m.volume24hQuote || 0) >= minVol);
1938
+ const key = { volume: (m) => -(m.volume24hQuote || 0), gainers: (m) => -(m.change24hPct ?? -Infinity), losers: (m) => m.change24hPct ?? Infinity, funding_high: (m) => -(m._perHour ?? -Infinity), funding_low: (m) => m._perHour ?? Infinity }[sort];
1939
+ const rows = hit.sort((a, b) => key(a) - key(b)).slice(0, limit).map(({ _perHour, ...r }) => r);
1940
+ const notes = ['volume24hQuote is in the quote asset (USDT, USD1 and USDC are about one dollar; check `quote`).', 'Funding: positive means longs pay shorts. fundingRatePct is the last settled rate per fundingIntervalHours.'];
1941
+ if (args.includeOpenInterest) {
1942
+ const part = rows.slice(0, 25);
1943
+ const oi = await Promise.all(part.map((r) => optional(get(`/fapi/v1/openInterest?symbol=${q(r.symbol)}`, TICKER_TTL))));
1944
+ part.forEach((r, i) => { const v = oi[i] ? num(oi[i].openInterest) : null; r.openInterest = v; r.openInterestQuote = v !== null && r.markPrice ? sig(v * r.markPrice, 10) : null; });
1945
+ notes.push(rows.length > 25 ? 'Open interest was fetched for the first 25 rows only (the exchange has one request per symbol).' : 'openInterest is in base-asset units; openInterestQuote = openInterest x mark price.');
1946
+ } else notes.push('Open interest is a per-symbol request: pass includeOpenInterest: true (first 25 rows) or call perps_market.');
1947
+ return { source: source(), fetchedAt: new Date(now()).toISOString(), tradable: all.length, matched: hit.length, returned: rows.length, sort, markets: rows, notes, trading: NO_TRADING };
1948
+ }
1949
+
1950
+ // ---- perps_market
1951
+ async function market(args = {}) {
1952
+ const history = intArg(args.fundingHistory, 12, 0, 100, 'fundingHistory');
1953
+ const m = await need(args.symbol);
1954
+ const [t, p, fr, oi] = await Promise.all([
1955
+ get(`/fapi/v1/ticker/24hr?symbol=${q(m.symbol)}`), get(`/fapi/v1/premiumIndex?symbol=${q(m.symbol)}`),
1956
+ history ? get(`/fapi/v1/fundingRate?symbol=${q(m.symbol)}&limit=${history}`, 30000) : Promise.resolve([]),
1957
+ optional(get(`/fapi/v1/openInterest?symbol=${q(m.symbol)}`)),
1958
+ ]);
1959
+ const mark = num(p.markPrice), index = num(p.indexPrice), rate = num(p.lastFundingRate), perHour = fundingPerHour(rate, m.intervalHours);
1960
+ const rates = (Array.isArray(fr) ? fr : []).map((x) => ({ time: iso(x.fundingTime), ratePct: sig(num(x.fundingRate) * 100, 6) }));
1961
+ const avg = rates.length ? rates.reduce((s, x) => s + x.ratePct, 0) / rates.length : null;
1962
+ const oiBase = oi ? num(oi.openInterest) : null;
1963
+ return {
1964
+ symbol: m.symbol, base: m.base, quote: m.quote, category: m.category, subType: m.subType, status: m.status, listedSince: m.onboardDate,
1965
+ price: { last: num(t.lastPrice), mark, index, markVsIndexPct: mark !== null && index ? round(((mark - index) / index) * 100, 4) : null, estimatedSettle: num(p.estimatedSettlePrice) },
1966
+ change24h: { pct: num(t.priceChangePercent), high: num(t.highPrice), low: num(t.lowPrice), open: num(t.openPrice), volumeBase: num(t.volume), volumeQuote: num(t.quoteVolume), trades: num(t.count) },
1967
+ funding: {
1968
+ lastRatePct: rate === null ? null : sig(rate * 100, 6), intervalHours: m.intervalHours, perHourPct: perHour === null ? null : sig(perHour * 100, 6),
1969
+ annualisedPctSimple: perHour === null ? null : round(perHour * 24 * 365 * 100, 2), nextFundingTime: iso(p.nextFundingTime), capPct: m.fundingCap === null ? null : m.fundingCap * 100, floorPct: m.fundingFloor === null ? null : m.fundingFloor * 100,
1970
+ history: rates, historyAveragePct: avg === null ? null : sig(avg, 6),
1971
+ note: 'Positive: longs pay shorts. annualisedPctSimple = last hourly rate x 24 x 365, not compounded and not a forecast.',
1972
+ },
1973
+ openInterest: oiBase === null ? null : { base: oiBase, quoteAtMark: mark ? sig(oiBase * mark, 10) : null, asOf: iso(oi.time) },
1974
+ limits: {
1975
+ tickSize: m.tickSize, stepSize: m.stepSize, minQty: m.minQty, maxQty: m.maxQty, marketOrderMaxQty: m.marketMaxQty, minNotional: m.minNotional, pricePrecision: m.pricePrecision, quantityPrecision: m.quantityPrecision,
1976
+ requiredMarginPercent: m.requiredMarginPercent, maintenanceMarginPercent: m.maintMarginPercent,
1977
+ impliedMaxLeverage: m.requiredMarginPercent ? Math.floor(100 / m.requiredMarginPercent) : null,
1978
+ leverageNote: 'impliedMaxLeverage = 100 / requiredMarginPercent from the exchange info. The real cap is per account and per size tier and needs a signed call that was not made.',
1979
+ },
1980
+ notChecked: ['per-account leverage cap and tiered maintenance margin (signed endpoint)', 'trading fees (account-specific)', 'anything about your own Aster account'],
1981
+ source: source(), fetchedAt: new Date(now()).toISOString(), trading: NO_TRADING,
1982
+ };
1983
+ }
1984
+
1985
+ // ---- perps_orderbook
1986
+ async function orderbook(args = {}) {
1987
+ const depth = args.depth === undefined ? 20 : Number(args.depth);
1988
+ if (!DEPTHS.includes(depth)) throw new Error(`depth must be one of: ${DEPTHS.join(', ')}.`);
1989
+ const sizeUsd = args.sizeUsd === undefined ? null : num(args.sizeUsd);
1990
+ if (args.sizeUsd !== undefined && !(sizeUsd > 0)) throw new Error('sizeUsd must be a number > 0.');
1991
+ const m = await need(args.symbol);
1992
+ const d = await get(`/fapi/v1/depth?symbol=${q(m.symbol)}&limit=${depth}`, 1500);
1993
+ if (!Array.isArray(d.bids) || !Array.isArray(d.asks)) throw new Error('Aster returned an unexpected order book shape.');
1994
+ const bids = bookLevels(d.bids), asks = bookLevels(d.asks);
1995
+ const bestBid = bids[0]?.price ?? null, bestAsk = asks[0]?.price ?? null;
1996
+ const mid = bestBid !== null && bestAsk !== null ? (bestBid + bestAsk) / 2 : null;
1997
+ const abs = mid === null ? null : bestAsk - bestBid;
1998
+ const bidN = bids.at(-1)?.cumulativeNotional || 0, askN = asks.at(-1)?.cumulativeNotional || 0;
1999
+ return {
2000
+ symbol: m.symbol, quote: m.quote, bestBid, bestAsk, mid: sig(mid),
2001
+ spread: abs === null ? null : { absolute: sig(abs), pct: round((abs / mid) * 100, 5), bps: round((abs / mid) * 10000, 3), ticks: m.tickSize ? round(abs / m.tickSize, 2) : null },
2002
+ depthNotional: { bids: bidN, asks: askN, bidShare: bidN + askN ? round(bidN / (bidN + askN), 4) : null },
2003
+ bids, asks,
2004
+ ...(sizeUsd ? { marketImpact: { buy: walkBook(d.asks, sizeUsd), sell: walkBook(d.bids, sizeUsd), note: `Walks the ${depth} levels fetched; fullyFilled false means the amount is deeper than those levels. Slippage is versus the best level, before fees.` } } : {}),
2005
+ snapshotTime: iso(d.T || d.E), source: source(), fetchedAt: new Date(now()).toISOString(), trading: NO_TRADING,
2006
+ };
2007
+ }
2008
+
2009
+ // ---- perps_klines
2010
+ async function klines(args = {}) {
2011
+ const interval = oneOf(args.interval, INTERVALS, '1h', 'interval');
2012
+ const limit = intArg(args.limit, 100, 1, 500, 'limit');
2013
+ const time = (v, name) => {
2014
+ if (v === undefined || v === null) return null;
2015
+ const n = typeof v === 'number' ? v : Number.isFinite(Number(v)) ? Number(v) : Date.parse(v);
2016
+ if (!Number.isFinite(n) || n <= 0) throw new Error(`${name} must be a millisecond timestamp or an ISO date.`);
2017
+ return Math.floor(n);
2018
+ };
2019
+ const start = time(args.startTime, 'startTime'), end = time(args.endTime, 'endTime');
2020
+ const m = await need(args.symbol);
2021
+ const rows = await get(`/fapi/v1/klines?symbol=${q(m.symbol)}&interval=${interval}&limit=${limit}${start ? `&startTime=${start}` : ''}${end ? `&endTime=${end}` : ''}`, 10000);
2022
+ if (!Array.isArray(rows)) throw new Error('Aster returned an unexpected klines shape.');
2023
+ const candles = rows.map((k) => ({ time: iso(k[0]), open: num(k[1]), high: num(k[2]), low: num(k[3]), close: num(k[4]), volumeBase: num(k[5]), volumeQuote: num(k[7]), trades: num(k[8]) }));
2024
+ const first = candles[0], last = candles.at(-1);
2025
+ return {
2026
+ symbol: m.symbol, interval, count: candles.length,
2027
+ summary: candles.length ? {
2028
+ from: first.time, to: last.time, open: first.open, close: last.close, changePct: first.open ? round(((last.close - first.open) / first.open) * 100, 3) : null,
2029
+ high: Math.max(...candles.map((c) => c.high)), low: Math.min(...candles.map((c) => c.low)), volumeQuote: sig(candles.reduce((s, c) => s + (c.volumeQuote || 0), 0), 10),
2030
+ lastCandleIsOpen: rows.at(-1)[6] > now(),
2031
+ } : null,
2032
+ candles, source: source(), trading: NO_TRADING,
2033
+ };
2034
+ }
2035
+
2036
+ // ---- perps_order_preview
2037
+ async function orderPreview(args = {}) {
2038
+ const side = { long: 'long', buy: 'long', short: 'short', sell: 'short' }[String(args.side || '').toLowerCase()];
2039
+ if (!side) throw new Error('side must be "long" or "short".');
2040
+ const sizeUsd = num(args.sizeUsd);
2041
+ if (!(sizeUsd > 0)) throw new Error('sizeUsd must be a number > 0 (position size in quote-asset terms, e.g. USDT).');
2042
+ const leverage = num(args.leverage);
2043
+ if (!(leverage >= 1) || leverage > 1001) throw new Error('leverage must be a number from 1 to 1001.');
2044
+ const given = args.price === undefined ? null : num(args.price);
2045
+ if (args.price !== undefined && !(given > 0)) throw new Error('price must be a number > 0 (omit it to use the mark price).');
2046
+ const m = await need(args.symbol);
2047
+ const p = await get(`/fapi/v1/premiumIndex?symbol=${q(m.symbol)}`);
2048
+ const mark = num(p.markPrice);
2049
+ const entry = given ?? mark;
2050
+ if (!(entry > 0)) throw new Error('No usable price for this market right now.');
2051
+ const out = previewOrder({ meta: m, side, sizeUsd, leverage, price: entry, priceGiven: given !== null, ratePerHour: fundingPerHour(num(p.lastFundingRate), m.intervalHours) });
2052
+ return {
2053
+ preview: true, sent: false, symbol: m.symbol, side, quote: m.quote,
2054
+ request: { sizeUsd, leverage },
2055
+ entry: { price: entry, source: given !== null ? 'price you gave (treated as a limit price)' : 'current mark price (a market order would fill near the book, see perps_orderbook marketImpact)', markPrice: mark },
2056
+ order: { quantity: out.quantity, base: m.base, stepSize: m.stepSize, notional: round(out.notional, 6), roundedDownByUsd: out.roundedDownByUsd },
2057
+ valid: out.valid, problems: out.problems, warnings: out.warnings, checks: out.checks,
2058
+ margin: out.margin, liquidation: out.liquidation, funding: out.funding,
2059
+ disclaimer: `Pure arithmetic on public market filters. Nothing was sent or signed. Liquidation is an APPROXIMATION and the exchange's own number will differ. ${NO_TRADING}`,
2060
+ fetchedAt: new Date(now()).toISOString(),
2061
+ };
2062
+ }
2063
+
2064
+ const symbolArg = { type: 'string', description: 'Aster perpetual symbol such as "BTCUSDT", or just the base asset ("BTC", "ETH", "AAPL")' };
2065
+ return [
2066
+ {
2067
+ name: 'perps_markets', annotations: READ, run: markets,
2068
+ description: `List Aster perpetual futures markets (read-only, public data): price, mark/index, 24h change and volume, funding rate and per-hour funding, with filter and sort. ${NO_TRADING}`,
2069
+ inputSchema: { type: 'object', properties: {
2070
+ query: { type: 'string', description: 'Substring of the symbol or base asset, e.g. "ETH"' },
2071
+ category: { type: 'string', enum: CATEGORIES, description: 'Default all' },
2072
+ quote: { type: 'string', description: 'Quote asset filter, e.g. USDT' },
2073
+ sort: { type: 'string', enum: SORTS, description: 'Default volume (24h quote volume, highest first)' },
2074
+ limit: { type: 'integer', description: '1-100, default 20' },
2075
+ minVolumeUsd: { type: 'number', description: 'Only markets with at least this 24h quote volume' },
2076
+ includeOpenInterest: { type: 'boolean', description: 'Also fetch open interest for the first 25 rows (one request each)' },
2077
+ } },
2078
+ },
2079
+ {
2080
+ name: 'perps_market', annotations: READ, run: market,
2081
+ description: `One Aster perpetual in detail (read-only): 24h ticker, mark vs index, funding now with per-hour rate and recent history, open interest, and the tick/step/min-notional limits. Lists what was not checked. ${NO_TRADING}`,
2082
+ inputSchema: { type: 'object', properties: { symbol: symbolArg, fundingHistory: { type: 'integer', description: 'Past funding settlements to return, 0-100, default 12' } }, required: ['symbol'] },
2083
+ },
2084
+ {
2085
+ name: 'perps_orderbook', annotations: READ, run: orderbook,
2086
+ description: `Aster order book for one perpetual (read-only): levels with cumulative size and notional, spread, bid/ask depth share, and optionally the average fill and slippage for a USD amount. ${NO_TRADING}`,
2087
+ inputSchema: { type: 'object', properties: { symbol: symbolArg, depth: { type: 'integer', enum: DEPTHS, description: 'Levels per side, default 20' }, sizeUsd: { type: 'number', description: 'Optional: estimate the average fill and slippage for buying or selling this many USD' } }, required: ['symbol'] },
2088
+ },
2089
+ {
2090
+ name: 'perps_klines', annotations: READ, run: klines,
2091
+ description: `Candles for an Aster perpetual (read-only): open/high/low/close, base and quote volume, trades, plus a summary. ${NO_TRADING}`,
2092
+ inputSchema: { type: 'object', properties: { symbol: symbolArg, interval: { type: 'string', enum: INTERVALS, description: 'Default 1h' }, limit: { type: 'integer', description: '1-500, default 100' }, startTime: { type: ['number', 'string'], description: 'Optional start, ms timestamp or ISO date' }, endTime: { type: ['number', 'string'], description: 'Optional end, ms timestamp or ISO date' } }, required: ['symbol'] },
2093
+ },
2094
+ {
2095
+ name: 'perps_order_preview', annotations: READ, run: orderPreview,
2096
+ description: `Preview the maths of an Aster perpetual order WITHOUT sending anything: quantity rounded DOWN to the market step, notional, minimum-notional and size checks, estimated initial margin and an APPROXIMATE liquidation price, and hourly funding cost. Nothing is placed or signed. ${NO_TRADING}`,
2097
+ inputSchema: { type: 'object', properties: { symbol: symbolArg, side: { type: 'string', enum: ['long', 'short'] }, sizeUsd: { type: 'number', description: 'Position size (notional) in quote-asset terms, e.g. 250 for about 250 USDT' }, leverage: { type: 'number', description: 'Leverage, 1 or more' }, price: { type: 'number', description: 'Optional entry/limit price; default is the current mark price' } }, required: ['symbol', 'side', 'sizeUsd', 'leverage'] },
2098
+ },
2099
+ ];
1327
2100
  }
1328
2101
 
1329
- return { plain, decodeApprove, createActions };
2102
+ return { decimalsOf, floorToStep, fundingPerHour, liquidationPrice, previewOrder, bookLevels, walkBook, categoryOf, createPerps };
2103
+ })();
2104
+
2105
+ const __m_launch = (() => {
2106
+ // Flap token launch: build the exact Portal transaction for a new token, run it through the same Guard / approval / signing path as swaps.
2107
+ // Source of truth: the Flap docs "Launch Tokens" (bonding curve protocol), "Flap IPFS Gateway" and "Deployed Contract Addresses" (research/flap-docs).
2108
+ // tax token Portal.newTokenV6, TOKEN_TAXED_V3 (6), migrates to a V2 pool, salt must give an address ending 7777
2109
+ // non-tax token Portal.newTokenV7, TOKEN_V3_PERMIT (7), migrates to PancakeSwap Infinity CL, salt must give an address ending 8888
2110
+ // Not supported on purpose: vault launches (VaultPortal, factory-specific vaultData), Agent ID gate, ERC-20 quote tokens, commission receiver.
2111
+ // Nothing here signs or sends. flap_prepare_launch plans and checks; flap_launch hands the plan to the Guard, which always asks a human.
2112
+ const { ADDR, ZERO_ADDRESS, isAddress } = __m_core;
2113
+ const { keccak256, randomHex } = __m_crypto;
2114
+ const { checkIntent } = __m_guard;
2115
+ const { homeDir, keyPath } = __m_wallet;
2116
+ const { clean, createActions, plain } = __m_actions;
2117
+ const { toUnits } = __m_relay;
2118
+
2119
+ // ------------------------------------------------------------------ constants (docs: Deployed Contract Addresses, Launch Tokens)
2120
+ const FLAP = {
2121
+ portal: ADDR.FLAP_PORTAL, // bonding-curve Portal, BNB Chain
2122
+ taxImpl: '0x024f18294970B5c76c0691b87f138A0317156422', // "Tax Token V3 Impl", vanity suffix 7777
2123
+ standardImpl: '0x88881b6f03090462a969eC7f48385744Eeb63333', // "Standard Token V3 Impl", vanity suffix 8888
2124
+ uploadUrl: 'https://funcs.flap.sh/api/upload',
2125
+ gateway: 'https://flap.mypinata.cloud/ipfs/',
2126
+ pinUrl: 'https://funcs.flap.sh/api/v1/ipfs/pins',
2127
+ tokenUrl: 'https://flap.sh/bnb/',
2128
+ TOKEN_TAXED_V3: 6, TOKEN_V3_PERMIT: 7,
2129
+ DEX_FOUR_FIFTHS: 1, MIGRATOR_V2: 1, MIGRATOR_PCS_INFINITY_CL: 3, FEE_DIVIDEND: 2,
2130
+ MAGIC_DIVIDEND_SELF: '0xfEEDFEEDfeEDFEedFEEdFEEDFeEdfEEdFeEdFEEd',
2131
+ MIN_SHARE_TOKENS: 10000n, // dividends need minimumShareBalance >= 10,000 tokens
2132
+ };
2133
+ const E18 = 10n ** 18n;
2134
+ const BNB_TOKEN = { native: true, address: ZERO_ADDRESS, symbol: 'BNB', decimals: 18 };
2135
+ const ZERO_HASH = '0x' + '0'.repeat(64);
2136
+ const DEAD = ADDR.DEAD.toLowerCase();
2137
+ const lc = (a) => String(a).toLowerCase();
2138
+ const MAX_IMAGE_BYTES = 5 * 1024 * 1024; // our own cap: Flap documents no size limit
2139
+ const PLAN_TTL_MS = 15 * 60 * 1000;
2140
+
2141
+ // ------------------------------------------------------------------ ABI encoding (just what the launch calls need)
2142
+ // A field list is [[name, type]]; type is 'string' | 'bytes' | 'bytes32' | 'address' | 'uintN' | { tuple: fields } | { fixed: n, of: type }.
2143
+ const isDynamic = (t) => t === 'string' || t === 'bytes' || (typeof t === 'object' && (t.tuple ? t.tuple.some(([, x]) => isDynamic(x)) : isDynamic(t.of)));
2144
+ const sigType = (t) => (typeof t === 'string' ? t : t.tuple ? `(${t.tuple.map(([, x]) => sigType(x)).join(',')})` : `${sigType(t.of)}[${t.fixed}]`);
2145
+ const word = (v) => BigInt(v).toString(16).padStart(64, '0');
2146
+ const bytesBody = (hex) => word(hex.length / 2) + hex.padEnd(Math.ceil(hex.length / 64) * 64, '0');
2147
+
2148
+ function encodeValue(t, v, label) {
2149
+ if (t === 'string') { if (typeof v !== 'string') throw new Error(`${label} must be a string`); return bytesBody(Buffer.from(v, 'utf8').toString('hex')); }
2150
+ if (t === 'bytes') { if (typeof v !== 'string' || !/^0x([0-9a-fA-F]{2})*$/.test(v)) throw new Error(`${label} must be 0x hex bytes`); return bytesBody(v.slice(2).toLowerCase()); }
2151
+ if (t === 'bytes32') { if (typeof v !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(v)) throw new Error(`${label} must be 32 bytes of hex`); return v.slice(2).toLowerCase(); }
2152
+ if (t === 'address') { if (!isAddress(v)) throw new Error(`${label} must be an address`); return v.slice(2).toLowerCase().padStart(64, '0'); }
2153
+ if (typeof t === 'string' && /^uint\d+$/.test(t)) {
2154
+ const n = typeof v === 'bigint' ? v : typeof v === 'number' && Number.isInteger(v) ? BigInt(v) : typeof v === 'string' && /^\d+$/.test(v) ? BigInt(v) : null;
2155
+ if (n === null || n < 0n || n >= 1n << BigInt(t.slice(4))) throw new Error(`${label} does not fit ${t}`);
2156
+ return word(n);
2157
+ }
2158
+ if (t.tuple) return encodeTuple(t.tuple, v, label);
2159
+ if (t.fixed) { if (!Array.isArray(v) || v.length !== t.fixed) throw new Error(`${label} needs exactly ${t.fixed} items`); if (isDynamic(t.of)) throw new Error('dynamic fixed arrays are not needed here'); return v.map((x, i) => encodeValue(t.of, x, `${label}[${i}]`)).join(''); }
2160
+ throw new Error(`unsupported ABI type ${JSON.stringify(t)}`);
2161
+ }
2162
+ function encodeTuple(fields, obj, label = 'args') {
2163
+ const parts = fields.map(([k, t]) => ({ dyn: isDynamic(t), enc: encodeValue(t, obj[k], `${label}.${k}`) }));
2164
+ const headBytes = parts.reduce((n, p) => n + (p.dyn ? 32 : p.enc.length / 2), 0);
2165
+ let head = '', tail = '';
2166
+ for (const p of parts) { if (p.dyn) { head += word(headBytes + tail.length / 2); tail += p.enc; } else head += p.enc; }
2167
+ return head + tail;
2168
+ }
2169
+ const selectorOf = (name, fields) => '0x' + keccak256(`${name}(${fields.map(([, t]) => sigType(t)).join(',')})`).subarray(0, 4).toString('hex');
2170
+
2171
+ /** IPortalTypes.NewTokenV6Params, field order from the Flap docs. */
2172
+ const V6_FIELDS = [['name', 'string'], ['symbol', 'string'], ['meta', 'string'], ['dexThresh', 'uint8'], ['salt', 'bytes32'], ['migratorType', 'uint8'], ['quoteToken', 'address'], ['quoteAmt', 'uint256'], ['beneficiary', 'address'], ['permitData', 'bytes'], ['extensionID', 'bytes32'], ['extensionData', 'bytes'], ['dexId', 'uint8'], ['lpFeeProfile', 'uint8'], ['buyTaxRate', 'uint16'], ['sellTaxRate', 'uint16'], ['taxDuration', 'uint64'], ['antiFarmerDuration', 'uint64'], ['mktBps', 'uint16'], ['deflationBps', 'uint16'], ['dividendBps', 'uint16'], ['lpBps', 'uint16'], ['minimumShareBalance', 'uint256'], ['dividendToken', 'address'], ['commissionReceiver', 'address'], ['tokenVersion', 'uint8']];
2173
+ const FEE_CONFIG = { tuple: [['feeType', 'uint8'], ['bps', 'uint16'], ['marketingAddress', 'address'], ['dividendToken', 'address'], ['minimumShareBalance', 'uint256']] };
2174
+ /** IPortalTypes.NewTokenV7Params. */
2175
+ const V7_FIELDS = [['name', 'string'], ['symbol', 'string'], ['meta', 'string'], ['dexThresh', 'uint8'], ['salt', 'bytes32'], ['migratorType', 'uint8'], ['quoteToken', 'address'], ['quoteAmt', 'uint256'], ['permitData', 'bytes'], ['extensionID', 'bytes32'], ['extensionData', 'bytes'], ['dexId', 'uint8'], ['buyTaxRate', 'uint16'], ['sellTaxRate', 'uint16'], ['taxDuration', 'uint64'], ['antiFarmerDuration', 'uint64'], ['commissionReceiver', 'address'], ['tokenVersion', 'uint8'], ['feeConfigs', { fixed: 4, of: FEE_CONFIG }]];
2176
+ const LOCK_FIELDS = [['salt', 'bytes32'], ['tokenVersion', 'uint8']];
2177
+
2178
+ const SELECTORS = {
2179
+ newTokenV6: selectorOf('newTokenV6', [['params', { tuple: V6_FIELDS }]]), // 0x8cb5772c, seen in live Portal transactions
2180
+ newTokenV7: selectorOf('newTokenV7', [['params', { tuple: V7_FIELDS }]]),
2181
+ lockSalt: selectorOf('lockSalt', LOCK_FIELDS),
2182
+ SALT_LOCK_FEE: selectorOf('SALT_LOCK_FEE', []),
2183
+ };
2184
+ const encodeNewTokenV6 = (p) => SELECTORS.newTokenV6 + encodeTuple([['params', { tuple: V6_FIELDS }]], { params: p });
2185
+ const encodeNewTokenV7 = (p) => SELECTORS.newTokenV7 + encodeTuple([['params', { tuple: V7_FIELDS }]], { params: p });
2186
+ const encodeLockSalt = (salt, tokenVersion) => SELECTORS.lockSalt + encodeTuple(LOCK_FIELDS, { salt, tokenVersion });
2187
+
2188
+ // ------------------------------------------------------------------ vanity salt (CREATE2 prediction, docs "Find the salt")
2189
+ const proxyInitCode = (impl) => Buffer.from('3d602d80600a3d3981f3363d3d373d3d3d363d73' + impl.slice(2).toLowerCase() + '5af43d82803e903d91602b57fd5bf3', 'hex'); // EIP-1167 minimal proxy
2190
+ const addrBytes = (a) => Buffer.from(a.slice(2), 'hex');
2191
+
2192
+ /** EIP-55 checksum form of an address. */
2193
+ function checksumAddress(address) {
2194
+ const a = address.slice(2).toLowerCase(), h = keccak256(a).toString('hex');
2195
+ return '0x' + [...a].map((c, i) => (parseInt(h[i], 16) >= 8 ? c.toUpperCase() : c)).join('');
2196
+ }
2197
+ /** The address the Portal's CREATE2 will give a token clone of `impl` for `salt`. Reference implementation (slow path). */
2198
+ function predictTokenAddress(portal, impl, salt) {
2199
+ const hash = keccak256(Buffer.concat([Buffer.from([0xff]), addrBytes(portal), Buffer.from(salt.slice(2), 'hex'), keccak256(proxyInitCode(impl))]));
2200
+ return checksumAddress('0x' + hash.subarray(12).toString('hex'));
2201
+ }
2202
+
2203
+ // A keccak-f[1600] for single-block inputs on 32-bit halves: the mining loop needs ~10^5 hashes, which the generic BigInt keccak in crypto.js would make slow.
2204
+ const RC = [0x0000000000000001n, 0x0000000000008082n, 0x800000000000808An, 0x8000000080008000n, 0x000000000000808Bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n, 0x000000000000008An, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000An, 0x000000008000808Bn, 0x800000000000008Bn, 0x8000000000008089n, 0x8000000000008003n, 0x8000000000008002n, 0x8000000000000080n, 0x000000000000800An, 0x800000008000000An, 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n];
2205
+ const RCL = Int32Array.from(RC, (v) => Number(v & 0xffffffffn) | 0), RCH = Int32Array.from(RC, (v) => Number(v >> 32n) | 0);
2206
+ const ROT_XY = [[0, 36, 3, 41, 18], [1, 44, 10, 45, 2], [62, 6, 43, 15, 61], [28, 55, 25, 21, 56], [27, 20, 39, 8, 14]]; // rotation offset of lane (x, y)
2207
+ const LANE_ROT = new Uint8Array(25), LANE_DEST = new Uint8Array(25);
2208
+ for (let x = 0; x < 5; x++) for (let y = 0; y < 5; y++) { LANE_ROT[x + 5 * y] = ROT_XY[x][y]; LANE_DEST[x + 5 * y] = y + 5 * ((2 * x + 3 * y) % 5); }
2209
+ const aL = new Int32Array(25), aH = new Int32Array(25), bL = new Int32Array(25), bH = new Int32Array(25), cL = new Int32Array(5), cH = new Int32Array(5);
2210
+ function keccakF() {
2211
+ for (let r = 0; r < 24; r++) {
2212
+ for (let x = 0; x < 5; x++) { cL[x] = aL[x] ^ aL[x + 5] ^ aL[x + 10] ^ aL[x + 15] ^ aL[x + 20]; cH[x] = aH[x] ^ aH[x + 5] ^ aH[x + 10] ^ aH[x + 15] ^ aH[x + 20]; }
2213
+ for (let x = 0; x < 5; x++) {
2214
+ const l = cL[(x + 1) % 5], h = cH[(x + 1) % 5], dL = cL[(x + 4) % 5] ^ ((l << 1) | (h >>> 31)), dH = cH[(x + 4) % 5] ^ ((h << 1) | (l >>> 31));
2215
+ for (let y = 0; y < 25; y += 5) { aL[x + y] ^= dL; aH[x + y] ^= dH; }
2216
+ }
2217
+ for (let i = 0; i < 25; i++) {
2218
+ const n = LANE_ROT[i], l = aL[i], h = aH[i], d = LANE_DEST[i];
2219
+ if (n === 0) { bL[d] = l; bH[d] = h; }
2220
+ else if (n < 32) { bL[d] = (l << n) | (h >>> (32 - n)); bH[d] = (h << n) | (l >>> (32 - n)); }
2221
+ else if (n === 32) { bL[d] = h; bH[d] = l; }
2222
+ else { const m = n - 32; bL[d] = (h << m) | (l >>> (32 - m)); bH[d] = (l << m) | (h >>> (32 - m)); }
2223
+ }
2224
+ for (let y = 0; y < 25; y += 5) for (let x = 0; x < 5; x++) { const i = y + x, j = y + ((x + 1) % 5), k = y + ((x + 2) % 5); aL[i] = bL[i] ^ (~bL[j] & bL[k]); aH[i] = bH[i] ^ (~bH[j] & bH[k]); }
2225
+ aL[0] ^= RCL[r]; aH[0] ^= RCH[r];
2226
+ }
2227
+ }
2228
+ /** Absorb one padded 136-byte block (already in `dv`) and permute. Leaves the digest in aL / aH. */
2229
+ function absorbOneBlock(dv) {
2230
+ for (let i = 0; i < 17; i++) { aL[i] = dv.getInt32(8 * i, true); aH[i] = dv.getInt32(8 * i + 4, true); }
2231
+ aL.fill(0, 17); aH.fill(0, 17);
2232
+ keccakF();
2233
+ }
2234
+ function paddedBlock(message) {
2235
+ if (message.length > 135) throw new Error('single-block keccak takes at most 135 bytes');
2236
+ const blk = new Uint8Array(136); blk.set(message); blk[message.length] ^= 0x01; blk[135] ^= 0x80;
2237
+ return blk;
2238
+ }
2239
+ /** keccak-256 of up to 135 bytes, fast path. Same result as crypto.js keccak256 (checked in the tests). */
2240
+ function keccak256Short(message) {
2241
+ const blk = paddedBlock(message), dv = new DataView(blk.buffer);
2242
+ absorbOneBlock(dv);
2243
+ const out = Buffer.alloc(32), o = new DataView(out.buffer, out.byteOffset, 32);
2244
+ for (let i = 0; i < 4; i++) { o.setInt32(8 * i, aL[i], true); o.setInt32(8 * i + 4, aH[i], true); }
2245
+ return out;
2246
+ }
2247
+
2248
+ /**
2249
+ * Mine a salt whose CREATE2 address ends with `suffix` (4 hex characters). Expected work is 16^4 = 65,536 hashes.
2250
+ * Gives up after `maxMs` and says so; the caller may retry (every attempt starts from fresh random bytes).
2251
+ */
2252
+ async function findVanitySalt({ portal, impl, suffix, maxMs = 30000, now = () => Date.now(), random = () => randomHex(24) }) {
2253
+ if (!/^[0-9a-f]{4}$/.test(suffix)) throw new Error('suffix must be 4 lowercase hex characters');
2254
+ const message = Buffer.concat([Buffer.from([0xff]), addrBytes(portal), Buffer.from(random(), 'hex'), Buffer.alloc(8), keccak256(proxyInitCode(impl))]); // 1 + 20 + 32 + 32
2255
+ const blk = paddedBlock(message), dv = new DataView(blk.buffer);
2256
+ const saltAt = 21, counterAt = saltAt + 24;
2257
+ const want = parseInt(suffix.slice(0, 2), 16) | (parseInt(suffix.slice(2), 16) << 8); // address bytes 18, 19 sit at the top of lane 3's high word
2258
+ const start = now();
2259
+ for (let counter = 0; ; ) {
2260
+ for (let i = 0; i < 4096; i++, counter++) {
2261
+ dv.setUint32(counterAt, Math.floor(counter / 4294967296)); dv.setUint32(counterAt + 4, counter >>> 0);
2262
+ absorbOneBlock(dv);
2263
+ if (((aH[3] >>> 16) & 0xffff) === want) {
2264
+ const salt = '0x' + Buffer.from(blk.subarray(saltAt, saltAt + 32)).toString('hex');
2265
+ const token = predictTokenAddress(portal, impl, salt); // never trust the fast path alone
2266
+ if (!token.toLowerCase().endsWith(suffix)) throw new Error('internal error: mined salt does not give the wanted suffix');
2267
+ return { salt, token, tries: counter + 1, ms: now() - start };
2268
+ }
2269
+ }
2270
+ if (now() - start > maxMs) throw new Error(`No salt with the ${suffix} suffix was found in ${Math.round(maxMs / 1000)} s (${counter} tries; about 65,000 are needed on average). Call again, or raise saltSearchSeconds.`);
2271
+ await new Promise((r) => setImmediate(r));
2272
+ }
2273
+ }
2274
+
2275
+ // ------------------------------------------------------------------ input checks
2276
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/; // would let a name rewrite the approval prompt
2277
+ const CONTROL_MULTILINE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/;
2278
+ function text(v, label, { min = 0, max, multiline = false, optional = false } = {}) {
2279
+ if (v === undefined || v === null || v === '') { if (optional) return null; throw new Error(`${label} is required.`); }
2280
+ if (typeof v !== 'string') throw new Error(`${label} must be text.`);
2281
+ const s = v.trim();
2282
+ if (s.length < min || (!s && !optional)) throw new Error(`${label} is required.`);
2283
+ if ([...s].length > max) throw new Error(`${label} is too long (at most ${max} characters).`);
2284
+ if ((multiline ? CONTROL_MULTILINE : CONTROL).test(s)) throw new Error(`${label} contains control characters.`);
2285
+ return s || null;
2286
+ }
2287
+ function int(v, label, { min, max, fallback }) {
2288
+ if (v === undefined || v === null || v === '') return fallback;
2289
+ const n = typeof v === 'string' && /^\d+$/.test(v.trim()) ? Number(v) : v;
2290
+ if (!Number.isInteger(n) || n < min || n > max) throw new Error(`${label} must be a whole number from ${min} to ${max}.`);
2291
+ return n;
2292
+ }
2293
+ function url(v, label) {
2294
+ const s = text(v, label, { max: 200, optional: true });
2295
+ if (s === null) return null;
2296
+ let u; try { u = new URL(s); } catch (_) { throw new Error(`${label} must be an http(s) URL.`); }
2297
+ if (u.protocol !== 'https:' && u.protocol !== 'http:') throw new Error(`${label} must be an http(s) URL.`);
2298
+ return u.href;
2299
+ }
2300
+ const CID_ONLY = /^(baf[a-z0-9]{40,}|Qm[1-9A-HJ-NP-Za-km-z]{44})$/;
2301
+ /** Decimal text to integer units; "0" is allowed. */
2302
+ function decimalUnits(v, decimals, label) {
2303
+ const s = String(v ?? '0').trim(), u = toUnits(s, decimals);
2304
+ if (u === null || !/^\d+(\.\d+)?$/.test(s)) throw new Error(`${label} must be a plain decimal number, for example "0.1".`);
2305
+ return BigInt(u);
2306
+ }
2307
+
2308
+ /**
2309
+ * Turn the tool input into one validated, fully explicit configuration. `walletAddress` may be null (no wallet set up).
2310
+ * Rules come from the Flap docs: tax rates are 0 or 100 to 1000 bps, tax shares sum to 10000, dividends need a minimum share of 10,000 tokens.
2311
+ */
2312
+ function normalizeLaunchInput(a, walletAddress) {
2313
+ a = Object.fromEntries(Object.entries(a || {}).filter(([, v]) => v !== null && v !== undefined && !(typeof v === 'string' && v.trim() === ''))); // null and '' mean "not given", for every optional field
2314
+ const cfg = {
2315
+ name: text(a.name, 'name', { max: 64 }), symbol: text(a.symbol, 'symbol', { max: 16 }),
2316
+ description: text(a.description, 'description', { max: 1000, multiline: true, optional: true }) || '',
2317
+ website: url(a.website, 'website'), twitter: text(a.twitter, 'twitter', { max: 200, optional: true }), telegram: text(a.telegram, 'telegram', { max: 200, optional: true }),
2318
+ };
2319
+ if (/\s/.test(cfg.symbol)) throw new Error('symbol must not contain spaces.');
2320
+ if (a.image && a.metaCid) throw new Error('Give either image (it is uploaded to Flap) or metaCid (already uploaded), not both.');
2321
+ if (!a.image && !a.metaCid) throw new Error('Give an image (https URL or path of a PNG, JPEG, GIF or WebP file) or a metaCid you already uploaded to Flap.');
2322
+ if (a.metaCid) { const c = String(a.metaCid).trim().replace(/^ipfs:\/\//, ''); if (!CID_ONLY.test(c)) throw new Error('metaCid must be a bare IPFS CID (bafy... / bafkrei... / Qm...), not a URL or a path.'); cfg.metaCid = c; }
2323
+ else cfg.image = text(a.image, 'image', { max: 1000 });
2324
+
2325
+ cfg.devBuyUnits = decimalUnits(a.devBuyBnb ?? '0', 18, 'devBuyBnb');
2326
+ const buy = int(a.buyTaxBps, 'buyTaxBps', { min: 0, max: 1000, fallback: 0 }), sell = int(a.sellTaxBps, 'sellTaxBps', { min: 0, max: 1000, fallback: 0 });
2327
+ for (const [k, r] of [['buyTaxBps', buy], ['sellTaxBps', sell]]) if (r !== 0 && r < 100) throw new Error(`${k} must be 0 or between 100 and 1000 (1% to 10%).`);
2328
+ cfg.tax = buy > 0 || sell > 0;
2329
+ const taxOnly = ['taxDurationDays', 'antiFarmerSeconds', 'beneficiary', 'mktBps', 'deflationBps', 'lpBps', 'dividendToken'].filter((k) => a[k] !== undefined && a[k] !== null && a[k] !== '');
2330
+ cfg.lockSalt = a.lockSalt === true;
2331
+ cfg.minShareUnits = a.minimumShareBalance === undefined ? null : decimalUnits(a.minimumShareBalance, 18, 'minimumShareBalance');
2332
+
2333
+ if (!cfg.tax) { // newTokenV7: one DIVIDEND slot, 100% of the pool's LP-fee revenue to holders in BNB
2334
+ if (taxOnly.length) throw new Error(`${taxOnly.join(', ')} only apply to tax tokens. Set buyTaxBps or sellTaxBps (100 to 1000) to launch a tax token.`);
2335
+ if (a.dividendBps !== undefined) throw new Error('dividendBps only applies to tax tokens.');
2336
+ cfg.kind = 'standard'; cfg.tokenVersion = FLAP.TOKEN_V3_PERMIT; cfg.impl = FLAP.standardImpl; cfg.suffix = '8888';
2337
+ cfg.minShareUnits = cfg.minShareUnits ?? FLAP.MIN_SHARE_TOKENS * E18;
2338
+ if (cfg.minShareUnits < FLAP.MIN_SHARE_TOKENS * E18) throw new Error('minimumShareBalance must be at least 10000 tokens (Flap rule for dividends).');
2339
+ return cfg;
2340
+ }
2341
+ cfg.kind = 'tax'; cfg.tokenVersion = FLAP.TOKEN_TAXED_V3; cfg.impl = FLAP.taxImpl; cfg.suffix = '7777';
2342
+ cfg.buyTaxBps = buy; cfg.sellTaxBps = sell;
2343
+ cfg.taxDurationDays = int(a.taxDurationDays, 'taxDurationDays', { min: 1, max: 36500, fallback: 365 });
2344
+ cfg.antiFarmerSeconds = int(a.antiFarmerSeconds, 'antiFarmerSeconds', { min: 0, max: 365 * 86400, fallback: 3600 });
2345
+ const split = { mktBps: a.mktBps, deflationBps: a.deflationBps, dividendBps: a.dividendBps, lpBps: a.lpBps };
2346
+ const given = Object.values(split).some((v) => v !== undefined && v !== null && v !== '');
2347
+ const s = given ? Object.fromEntries(Object.entries(split).map(([k, v]) => [k, int(v, k, { min: 0, max: 10000, fallback: 0 })])) : { mktBps: 10000, deflationBps: 0, dividendBps: 0, lpBps: 0 };
2348
+ if (s.mktBps + s.deflationBps + s.dividendBps + s.lpBps !== 10000) throw new Error('mktBps + deflationBps + dividendBps + lpBps must add up to 10000 (they split the tax after the protocol fee).');
2349
+ Object.assign(cfg, s);
2350
+ const dt = a.dividendToken === undefined || a.dividendToken === null || a.dividendToken === '' ? 'bnb' : String(a.dividendToken).toLowerCase();
2351
+ if (dt !== 'bnb' && dt !== 'self') throw new Error('dividendToken must be "bnb" (holders are paid in BNB, the default) or "self" (holders are paid in the token itself). Other tokens need a SwapRegistry check this tool does not do.');
2352
+ cfg.dividendToken = dt === 'self' ? FLAP.MAGIC_DIVIDEND_SELF : ZERO_ADDRESS; cfg.dividendMode = dt;
2353
+ if (s.dividendBps > 0) {
2354
+ cfg.minShareUnits = cfg.minShareUnits ?? FLAP.MIN_SHARE_TOKENS * E18;
2355
+ if (cfg.minShareUnits < FLAP.MIN_SHARE_TOKENS * E18) throw new Error('minimumShareBalance must be at least 10000 tokens when dividendBps is above 0 (Flap rule).');
2356
+ } else { if (cfg.minShareUnits) throw new Error('minimumShareBalance only applies when dividendBps is above 0.'); cfg.minShareUnits = 0n; }
2357
+ if (a.beneficiary !== undefined && a.beneficiary !== null && a.beneficiary !== '') { if (!isAddress(a.beneficiary)) throw new Error('beneficiary must be a 0x address.'); cfg.beneficiary = a.beneficiary; }
2358
+ else if (walletAddress) cfg.beneficiary = walletAddress;
2359
+ else throw new Error('A tax token needs a beneficiary (the address that receives the marketing share of the tax). Pass beneficiary, or run `npx -y anthropos-mcp init` so the wallet address can be used.');
2360
+ if ([ZERO_ADDRESS, DEAD].includes(lc(cfg.beneficiary))) throw new Error('beneficiary must not be the zero or dead address.');
2361
+ return cfg;
2362
+ }
2363
+
2364
+ // ------------------------------------------------------------------ image + metadata upload (docs: Flap IPFS Gateway)
2365
+ function sniffImage(b) {
2366
+ const at = (i, s) => s.every((x, j) => b[i + j] === x);
2367
+ if (b.length > 12 && at(0, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return { mime: 'image/png', ext: 'png' };
2368
+ if (b.length > 3 && at(0, [0xff, 0xd8, 0xff])) return { mime: 'image/jpeg', ext: 'jpg' };
2369
+ if (b.length > 6 && (at(0, [0x47, 0x49, 0x46, 0x38, 0x37, 0x61]) || at(0, [0x47, 0x49, 0x46, 0x38, 0x39, 0x61]))) return { mime: 'image/gif', ext: 'gif' };
2370
+ if (b.length > 12 && at(0, [0x52, 0x49, 0x46, 0x46]) && at(8, [0x57, 0x45, 0x42, 0x50])) return { mime: 'image/webp', ext: 'webp' };
2371
+ return null;
2372
+ }
2373
+ // ---- is this address globally routable? Parsed numerically, so every spelling of an address (hex, mapped, NAT64, 6to4, odd zero runs) is judged by the IPv4 it really is.
2374
+ const BAD_NAME = /(^|\.)(localhost|local|internal|localdomain|home|lan|corp|intranet)$/;
2375
+ function parseIPv4(s) {
2376
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(s);
2377
+ if (!m) return null;
2378
+ const b = m.slice(1).map(Number);
2379
+ return b.every((x) => x <= 255) ? b : null;
2380
+ }
2381
+ function parseIPv6(input) {
2382
+ let s = input.split('%')[0].toLowerCase();
2383
+ const m = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(s);
2384
+ if (m) { const v4 = parseIPv4(m[2]); if (!v4) return null; s = m[1] + ((v4[0] << 8) | v4[1]).toString(16) + ':' + ((v4[2] << 8) | v4[3]).toString(16); }
2385
+ const halves = s.split('::');
2386
+ if (halves.length > 2) return null;
2387
+ const head = halves[0] ? halves[0].split(':') : [], tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
2388
+ if (halves.length === 1 ? head.length !== 8 : head.length + tail.length > 7) return null;
2389
+ const groups = halves.length === 1 ? head : [...head, ...new Array(8 - head.length - tail.length).fill('0'), ...tail];
2390
+ if (!groups.every((g) => /^[0-9a-f]{1,4}$/.test(g))) return null;
2391
+ return groups.flatMap((g) => { const n = parseInt(g, 16); return [n >> 8, n & 255]; });
2392
+ }
2393
+ function publicV4([a, b, c]) {
2394
+ if (a === 0 || a === 10 || a === 127 || a >= 224) return false; // this network, private, loopback, multicast and reserved
2395
+ if (a === 100 && b >= 64 && b <= 127) return false; // carrier-grade NAT
2396
+ if (a === 169 && b === 254) return false; // link local (cloud metadata lives here)
2397
+ if (a === 172 && b >= 16 && b <= 31) return false;
2398
+ if (a === 192 && ((b === 0 && (c === 0 || c === 2)) || b === 168 || (b === 88 && c === 99))) return false;
2399
+ if (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) return false;
2400
+ if (a === 203 && b === 0 && c === 113) return false;
2401
+ return true;
2402
+ }
2403
+ function publicV6(g) {
2404
+ if (g.slice(0, 10).every((x) => x === 0) && g[10] === 0xff && g[11] === 0xff) return publicV4(g.slice(12)); // ::ffff:a.b.c.d
2405
+ if (g.slice(0, 12).every((x) => x === 0)) return false; // ::, ::1 and the deprecated IPv4-compatible form
2406
+ if (g[0] === 0 && g[1] === 0x64 && g[2] === 0xff && g[3] === 0x9b && g.slice(4, 12).every((x) => x === 0)) return publicV4(g.slice(12)); // NAT64 64:ff9b::/96
2407
+ if (g[0] === 0x20 && g[1] === 0x02) return publicV4(g.slice(2, 6)); // 6to4 2002::/16
2408
+ if ((g[0] & 0xe0) !== 0x20) return false; // only 2000::/3 is global unicast: not fc00::/7, fe80::/10, ff00::/8, ::/8, 64:ff9b:1::/48 ...
2409
+ if (g[0] === 0x20 && g[1] === 0x01 && (g[2] < 0x02 || (g[2] === 0x0d && g[3] === 0xb8))) return false; // 2001::/23 (Teredo, benchmarking...), 2001:db8::/32
2410
+ if (g[0] === 0x3f && g[1] === 0xff) return false; // 3fff::/20 documentation
2411
+ return true;
2412
+ }
2413
+ /** True only for a globally routable unicast address. */
2414
+ function isPublicAddress(ip) {
2415
+ const text = String(ip).replace(/^\[|\]$/g, '').toLowerCase();
2416
+ const v4 = parseIPv4(text); if (v4) return publicV4(v4);
2417
+ const v6 = text.includes(':') ? parseIPv6(text) : null; return v6 ? publicV6(v6) : false;
2418
+ }
2419
+ async function readLimited(res, limit) {
2420
+ const declared = Number(res.headers?.get?.('content-length') || 0);
2421
+ if (declared > limit) throw new Error(`The image is larger than ${limit / 1048576} MB.`);
2422
+ if (!res.body?.getReader) { const b = Buffer.from(await res.arrayBuffer()); if (b.length > limit) throw new Error(`The image is larger than ${limit / 1048576} MB.`); return b; }
2423
+ const reader = res.body.getReader(), chunks = []; let n = 0;
2424
+ for (;;) { const { done, value } = await reader.read(); if (done) break; n += value.length; if (n > limit) { await reader.cancel(); throw new Error(`The image is larger than ${limit / 1048576} MB.`); } chunks.push(value); }
2425
+ return Buffer.concat(chunks);
2426
+ }
2427
+ const PRIVATE_URL = 'The image URL points at this machine or a private network. Only public image URLs are fetched.';
2428
+ /** Resolve the host once and return the address to connect to; every address it resolves to must be public. */
2429
+ async function publicAddress(urlText, resolveHost) {
2430
+ const host = new URL(urlText).hostname.replace(/^\[|\]$/g, '').toLowerCase().replace(/\.$/, '');
2431
+ if (BAD_NAME.test(host)) throw new Error(PRIVATE_URL);
2432
+ const addresses = parseIPv4(host) || host.includes(':') ? [host] : (await resolveHost(host)).map((x) => x.address);
2433
+ if (!addresses.length || !addresses.every(isPublicAddress)) throw new Error(PRIVATE_URL);
2434
+ return addresses[0];
2435
+ }
2436
+
2437
+ /**
2438
+ * GET with the connection pinned to an address that was already checked: the name is never resolved a second time, so DNS rebinding between
2439
+ * the check and the connection cannot redirect it. The Host header and TLS server name are still the URL's. Does not follow redirects.
2440
+ * Returns a Response with the body read (at most `limit` bytes).
2441
+ */
2442
+ function pinnedFetch(urlText, { ip, limit, timeoutMs = 20000 }) {
2443
+ const u = new URL(urlText), tls = u.protocol === 'https:';
2444
+ if (!tls && u.protocol !== 'http:') return Promise.reject(new Error('Only http(s) URLs are fetched.'));
2445
+ const family = ip.includes(':') ? 6 : 4;
2446
+ return new Promise((resolve, reject) => {
2447
+ const req = (tls ? https : http).request({
2448
+ protocol: u.protocol, hostname: u.hostname.replace(/^\[|\]$/g, ''), port: u.port || undefined, path: u.pathname + u.search, method: 'GET', timeout: timeoutMs,
2449
+ headers: { 'user-agent': 'anthropos-mcp', accept: 'image/*' },
2450
+ lookup: (_host, options, cb) => (options && options.all ? cb(null, [{ address: ip, family }]) : cb(null, ip, family)),
2451
+ }, (res) => {
2452
+ const chunks = []; let n = 0, tooBig = false;
2453
+ res.on('data', (c) => { n += c.length; if (n > limit) tooBig = true; else chunks.push(c); });
2454
+ res.on('end', () => {
2455
+ if (tooBig) { reject(new Error(`The image is larger than ${limit / 1048576} MB.`)); return; }
2456
+ const headers = new Headers(); for (const [k, v] of Object.entries(res.headers)) { try { headers.set(k, Array.isArray(v) ? v.join(', ') : String(v)); } catch (_) { /* skip odd header */ } }
2457
+ const empty = [204, 205, 304].includes(res.statusCode) || res.statusCode < 200;
2458
+ resolve(new Response(empty ? null : Buffer.concat(chunks), { status: res.statusCode, headers }));
2459
+ });
2460
+ res.on('error', reject);
2461
+ });
2462
+ req.on('timeout', () => req.destroy(new Error('The image server took too long to answer.')));
2463
+ req.on('error', reject);
2464
+ req.end();
2465
+ });
2466
+ }
2467
+
2468
+ /** A local image path must be absolute and local: no network shares, no device paths, no relative paths that depend on the server's working directory. */
2469
+ function localPath(source) {
2470
+ if (source.includes('\u0000')) throw new Error('The image path is not valid.');
2471
+ if (/^[\\/]{2}/.test(source)) throw new Error('Network paths (\\\\server\\share, //server/share, device paths) are not allowed as image paths.');
2472
+ const expanded = source.replace(/^~(?=$|[\\/])/, os.homedir());
2473
+ const win = process.platform === 'win32';
2474
+ if (!path.isAbsolute(expanded) || (win && !/^[a-zA-Z]:[\\/]/.test(expanded))) throw new Error('Give the image as an absolute path (or one starting with ~/), or as an https URL.');
2475
+ if (win && expanded.slice(2).includes(':')) throw new Error('The image path is not valid.');
2476
+ const full = path.resolve(expanded);
2477
+ if (/^[\\/]{2}/.test(full)) throw new Error('Network paths are not allowed as image paths.');
2478
+ return full;
2479
+ }
2480
+ /**
2481
+ * Image bytes from an https URL, or from a local file when the owner allows it (policy allowLocalImages). Only real PNG / JPEG / GIF / WebP content is accepted
2482
+ * (by its first bytes), so this cannot be used to publish other files.
2483
+ */
2484
+ async function loadImage(source, { fetchImage = pinnedFetch, env, resolveHost = (h) => dns.lookup(h, { all: true }), allowLocal = false }) {
2485
+ let bytes;
2486
+ if (/^https?:\/\//i.test(source)) {
2487
+ let current = source;
2488
+ for (let hop = 0; ; hop++) {
2489
+ const ip = await publicAddress(current, resolveHost);
2490
+ const res = await fetchImage(current, { ip, limit: MAX_IMAGE_BYTES });
2491
+ if (res.status >= 300 && res.status < 400 && res.headers.get('location')) { if (hop >= 3) throw new Error('Too many redirects while fetching the image.'); current = new URL(res.headers.get('location'), current).href; if (!/^https?:/i.test(current)) throw new Error(PRIVATE_URL); continue; }
2492
+ if (!res.ok) throw new Error(`Could not fetch the image: HTTP ${res.status}.`);
2493
+ bytes = await readLimited(res, MAX_IMAGE_BYTES); break;
2494
+ }
2495
+ } else {
2496
+ if (!allowLocal) throw new Error('Reading an image from a file on this machine is switched off. Give an https URL or a metaCid, or the wallet owner can set allowLocalImages to true in policy.json.');
2497
+ const file = localPath(source);
2498
+ let real; try { real = fs.realpathSync(file); } catch (_) { throw new Error(`Image file not found: ${file}`); }
2499
+ const homePath = homeDir(env), home = fs.existsSync(homePath) ? fs.realpathSync(homePath) : null;
2500
+ const protectedPaths = [keyPath(env)].filter((p) => fs.existsSync(p)).map((p) => fs.realpathSync(p));
2501
+ if (protectedPaths.includes(real) || (home && (real === home || real.startsWith(home + path.sep)))) throw new Error('That file is inside the ANTHROPOS data folder. Refusing to read it.');
2502
+ const st = fs.statSync(real);
2503
+ if (!st.isFile()) throw new Error('The image path is not a file.');
2504
+ if (st.size > MAX_IMAGE_BYTES) throw new Error(`The image is larger than ${MAX_IMAGE_BYTES / 1048576} MB.`);
2505
+ bytes = fs.readFileSync(real);
2506
+ }
2507
+ const kind = sniffImage(bytes);
2508
+ if (!kind) throw new Error('The image is not a PNG, JPEG, GIF or WebP file (checked by content, not by name).');
2509
+ return { bytes, ...kind };
2510
+ }
2511
+
2512
+ const UPLOAD_MUTATION = 'mutation Create($file: Upload!, $meta: MetadataInput!) { create(file: $file, meta: $meta) }';
2513
+ /** POST the image and details to Flap's upload API (GraphQL multipart). Returns the metadata CID. */
2514
+ async function uploadMetadata({ image, description, website, twitter, telegram }, { fetchImpl }) {
2515
+ const form = new FormData();
2516
+ form.append('operations', JSON.stringify({ query: UPLOAD_MUTATION, variables: { file: null, meta: { description, website, twitter, telegram, creator: ZERO_ADDRESS } } }));
2517
+ form.append('map', JSON.stringify({ 0: ['variables.file'] }));
2518
+ form.append('0', new Blob([image.bytes], { type: image.mime }), `image.${image.ext}`);
2519
+ let res, body;
2520
+ try { res = await fetchImpl(FLAP.uploadUrl, { method: 'POST', body: form, signal: AbortSignal.timeout(45000) }); body = await res.text(); }
2521
+ catch (e) { throw new Error(`Flap's upload API could not be reached (${String(e.message || e).slice(0, 120)}). Upload the image yourself and pass metaCid.`); }
2522
+ let json = null; try { json = JSON.parse(body); } catch (_) { /* not JSON */ }
2523
+ const cid = json?.data?.create;
2524
+ if (!res.ok || typeof cid !== 'string' || !CID_ONLY.test(cid)) throw new Error(`Flap's upload API refused the upload (HTTP ${res.status}: ${(json?.errors?.[0]?.message || body || '').slice(0, 200)}). Upload through Flap yourself and pass metaCid.`);
2525
+ return cid;
2526
+ }
2527
+ /** Is the metadata served by the Flap gateway? Flap's indexer and most terminals read only that gateway. null = could not tell. */
2528
+ async function gatewayServes(cid, fetchImpl) {
2529
+ try { const res = await fetchImpl(FLAP.gateway + cid, { signal: AbortSignal.timeout(10000) }); return res.ok; } catch (_) { return null; }
2530
+ }
2531
+
2532
+ // ------------------------------------------------------------------ the tools
2533
+ const pct = (bps) => bps / 100;
2534
+
2535
+ function createLaunch({ rpc, env = process.env, elicit = null, fetchImpl = globalThis.fetch, fetchImage = pinnedFetch, resolveHost = (h) => dns.lookup(h, { all: true }), saltSearch = findVanitySalt, ...rest }) {
2536
+ const engine = createActions({ rpc, env, elicit, ...rest }).engine;
2537
+ const { now = () => Date.now() } = rest;
2538
+ const prepared = new Map(); // plan_id -> { plan, expires }; in memory only, the approval record is the ledger's pending file
2539
+
2540
+ async function saltFor(cfg, opts) {
2541
+ if (opts.salt) {
2542
+ if (!/^0x[0-9a-fA-F]{64}$/.test(opts.salt)) throw new Error('salt must be 32 bytes of hex.');
2543
+ const token = predictTokenAddress(FLAP.portal, cfg.impl, opts.salt);
2544
+ if (!token.toLowerCase().endsWith(cfg.suffix)) throw new Error(`That salt gives ${token}, which does not end in ${cfg.suffix}. The Portal would revert with VanityAddressRequirementNotMet.`);
2545
+ return { salt: opts.salt.toLowerCase(), token, tries: null, ms: 0, source: 'provided' };
2546
+ }
2547
+ const r = await saltSearch({ portal: FLAP.portal, impl: cfg.impl, suffix: cfg.suffix, maxMs: opts.maxMs, now });
2548
+ return { ...r, source: 'mined' };
2549
+ }
2550
+
2551
+ async function lockFee() {
2552
+ let raw;
2553
+ try { raw = await rpc('eth_call', [{ to: FLAP.portal, data: SELECTORS.SALT_LOCK_FEE }, 'latest']); } catch (e) { throw new Error(`Could not read SALT_LOCK_FEE() from the Portal (${String(e.message || e).slice(0, 100)}), so the salt cannot be locked.`); }
2554
+ const fee = BigInt(raw && raw !== '0x' ? raw : 0);
2555
+ if (fee === 0n || fee > E18 / 10n) throw new Error(`The Portal reports a salt lock fee of ${plain(fee, 18)} BNB, which looks wrong. Not locking.`);
2556
+ return fee;
2557
+ }
2558
+
2559
+ /** Everything except the Guard: validate, upload, mine, encode. Returns { plan, view }. Signs and sends nothing. */
2560
+ async function build(args, ctx) {
2561
+ const wallet = ctx.wallet, cfg = normalizeLaunchInput(args, wallet?.address || null);
2562
+ const dryRun = args.dryRun === true;
2563
+ const notes = [];
2564
+ const salt = await saltFor(cfg, { salt: args.salt, maxMs: int(args.saltSearchSeconds, 'saltSearchSeconds', { min: 1, max: 120, fallback: 30 }) * 1000 }); // before the upload: a failed search must not leave a pinned file behind
2565
+ const lockUnits = cfg.lockSalt ? await lockFee() : 0n;
2566
+ const self = wallet && cfg.beneficiary && lc(cfg.beneficiary) === lc(wallet.address);
2567
+ const recipient = cfg.kind === 'tax' && cfg.mktBps > 0 && !self ? cfg.beneficiary : undefined; // revenue to somebody else is treated like a transfer: the address must be allowlisted
2568
+ const total = cfg.devBuyUnits + lockUnits, price = await engine.bnbPrice();
2569
+ let metaCid = cfg.metaCid || null, uploaded = false, served = null, upload = metaCid ? 'not needed: metaCid was given' : 'preview: nothing uploaded';
2570
+ if (dryRun) metaCid = metaCid || 'bafkrei' + 'a'.repeat(52); // stand-in with a real CID's length, only for the simulation
2571
+ else if (!metaCid) {
2572
+ // The upload is public and cannot be undone. The Guard looks first, then the owner has to have said yes (policy, or a prompt in their client).
2573
+ const early = checkIntent(ctx.policy, ctx.ledger.spentToday(), { action: 'launch', usd: Number(plain(total, 18)) * price, targets: [FLAP.portal], recipient });
2574
+ if (early.blocks.length) throw new Error(`Nothing was uploaded: the Guard would block this launch. ${early.blocks.join(' ')}`);
2575
+ const image = await loadImage(cfg.image, { fetchImage, env, resolveHost, allowLocal: ctx.policy.allowLocalImages });
2576
+ if (!ctx.policy.allowPublicUploads) {
2577
+ const answer = elicit ? await elicit(`Publish to Flap's public IPFS gateway? This cannot be undone.\nToken: "${clean(cfg.name, 64)}" ($${clean(cfg.symbol, 16)})\nImage: ${image.ext}, ${image.bytes.length} bytes\nDescription: ${clean(cfg.description, 300) || '(none)'}\nWebsite: ${cfg.website || '(none)'} X: ${clean(cfg.twitter, 100) || '(none)'} Telegram: ${clean(cfg.telegram, 100) || '(none)'}`).catch(() => false) : null;
2578
+ if (answer !== true) throw new Error(`Nothing was uploaded. ${answer === false ? 'The wallet owner declined (or the prompt timed out).' : 'The client cannot ask the wallet owner, and policy.json does not set "allowPublicUploads": true.'} Uploading publishes the image and details on Flap's public IPFS gateway permanently. Either upload them through Flap yourself and pass metaCid, or the wallet owner can set "allowPublicUploads": true in ${homeDir(env)}/policy.json.`);
2579
+ }
2580
+ metaCid = await uploadMetadata({ image, description: cfg.description, website: cfg.website, twitter: cfg.twitter, telegram: cfg.telegram }, { fetchImpl });
2581
+ uploaded = true; upload = 'done: published to Flap\'s IPFS gateway with the owner\'s consent'; served = await gatewayServes(metaCid, fetchImpl);
2582
+ } else served = await gatewayServes(metaCid, fetchImpl);
2583
+ if (!dryRun && served === false) notes.push(`The Flap gateway does not serve ${metaCid} yet. Flap's indexer and most terminals read only that gateway, so pin it first (POST ${FLAP.pinUrl} with {"cid": "..."}) or the token may show without image and details.`);
2584
+ if (!dryRun && served === null) notes.push('Could not check whether the Flap gateway serves the metadata.');
2585
+
2586
+ const steps = [];
2587
+ if (cfg.lockSalt) steps.push({ label: `Lock salt for token ${salt.token} on the Flap Portal (fee ${plain(lockUnits, 18)} BNB)`, to: FLAP.portal, data: encodeLockSalt(salt.salt, cfg.tokenVersion), value: lockUnits });
2588
+ const common = { name: cfg.name, symbol: cfg.symbol, meta: metaCid, dexThresh: FLAP.DEX_FOUR_FIFTHS, salt: salt.salt, quoteToken: ZERO_ADDRESS, quoteAmt: cfg.devBuyUnits, permitData: '0x', extensionID: ZERO_HASH, extensionData: '0x', dexId: 0, commissionReceiver: ZERO_ADDRESS, tokenVersion: cfg.tokenVersion };
2589
+ let data;
2590
+ if (cfg.kind === 'tax') {
2591
+ data = encodeNewTokenV6({ ...common, migratorType: FLAP.MIGRATOR_V2, beneficiary: cfg.beneficiary, lpFeeProfile: 0, buyTaxRate: cfg.buyTaxBps, sellTaxRate: cfg.sellTaxBps, taxDuration: BigInt(cfg.taxDurationDays) * 86400n, antiFarmerDuration: BigInt(cfg.antiFarmerSeconds), mktBps: cfg.mktBps, deflationBps: cfg.deflationBps, dividendBps: cfg.dividendBps, lpBps: cfg.lpBps, minimumShareBalance: cfg.minShareUnits, dividendToken: cfg.dividendToken });
2592
+ } else {
2593
+ const none = { feeType: 0, bps: 0, marketingAddress: ZERO_ADDRESS, dividendToken: ZERO_ADDRESS, minimumShareBalance: 0n };
2594
+ data = encodeNewTokenV7({ ...common, migratorType: FLAP.MIGRATOR_PCS_INFINITY_CL, buyTaxRate: 0, sellTaxRate: 0, taxDuration: 0n, antiFarmerDuration: 0n, feeConfigs: [{ feeType: FLAP.FEE_DIVIDEND, bps: 10000, marketingAddress: ZERO_ADDRESS, dividendToken: ZERO_ADDRESS, minimumShareBalance: cfg.minShareUnits }, none, none, none] });
2595
+ }
2596
+ const fn = cfg.kind === 'tax' ? 'newTokenV6' : 'newTokenV7';
2597
+ const buyText = cfg.devBuyUnits > 0n ? `dev buy ${plain(cfg.devBuyUnits, 18)} BNB` : 'no dev buy';
2598
+ steps.push({ label: `Launch ${cfg.name} ($${cfg.symbol}) with Portal.${fn}, ${buyText}, token address ${salt.token}`, to: FLAP.portal, data, value: cfg.devBuyUnits });
2599
+
2600
+ const realCid = cfg.metaCid || (dryRun ? null : metaCid);
2601
+ const taxText = cfg.kind === 'tax' ? `tax ${pct(cfg.buyTaxBps)}% buy / ${pct(cfg.sellTaxBps)}% sell for ${cfg.taxDurationDays} days, split ${cfg.mktBps / 100}% to ${cfg.beneficiary}, ${cfg.dividendBps / 100}% to holders (${cfg.dividendMode === 'self' ? 'paid in the token' : 'paid in BNB'}), ${cfg.deflationBps / 100}% burn, ${cfg.lpBps / 100}% liquidity` : 'no tax; 100% of the pool LP-fee revenue goes to holders as BNB dividends';
2602
+ const summary = `Launch Flap token "${cfg.name}" ($${cfg.symbol}) on BNB Chain at ${salt.token}: ${taxText}; ${buyText}${lockUnits ? `; salt lock fee ${plain(lockUnits, 18)} BNB` : ''}; metadata ${realCid || '(not uploaded: preview)'}`;
2603
+
2604
+ const plan = {
2605
+ action: 'launch', summary, usd: Number(plain(total, 18)) * price, route: 'Flap Portal (bonding curve launch)', steps, tokens: { in: BNB_TOKEN }, units: total, recipient,
2606
+ sentInfo: { token: { name: cfg.name, symbol: cfg.symbol, address: salt.token, flap_url: FLAP.tokenUrl + salt.token.toLowerCase() }, verify: 'The address is predicted from the salt (CREATE2). After the transaction confirms, check it with flap_token.' },
2607
+ launch: { name: cfg.name, symbol: cfg.symbol, token: salt.token, kind: cfg.kind, wallet: wallet?.address || null },
2608
+ };
2609
+ const view = {
2610
+ token: { name: cfg.name, symbol: cfg.symbol, type: cfg.kind === 'tax' ? 'Tax token (Flap Tax Token V3)' : 'Standard token, no tax (Flap Standard Token V3)', predicted_address: salt.token, address_rule: `must end in ${cfg.suffix} (Flap vanity rule for this token type)`, salt: salt.salt, salt_source: salt.source, salt_tries: salt.tries, salt_ms: salt.ms, flap_url: FLAP.tokenUrl + salt.token.toLowerCase(), migrates_to: cfg.kind === 'tax' ? 'PancakeSwap V2 pool at 80% of supply sold' : 'PancakeSwap Infinity CL pool at 80% of supply sold' },
2611
+ metadata: { cid: realCid, upload, uploaded_now: uploaded, served_by_flap_gateway: dryRun ? null : served, gateway_url: realCid ? FLAP.gateway + realCid : null, description: cfg.description || null, website: cfg.website, twitter: cfg.twitter, telegram: cfg.telegram },
2612
+ tax: cfg.kind === 'tax' ? { buy_pct: pct(cfg.buyTaxBps), sell_pct: pct(cfg.sellTaxBps), duration_days: cfg.taxDurationDays, anti_farmer_seconds: cfg.antiFarmerSeconds, beneficiary: cfg.beneficiary, split_pct: { beneficiary: cfg.mktBps / 100, holders_dividend: cfg.dividendBps / 100, burn: cfg.deflationBps / 100, liquidity: cfg.lpBps / 100 }, dividend_paid_in: cfg.dividendMode === 'self' ? 'the token itself' : 'BNB', minimum_share_tokens: plain(cfg.minShareUnits, 18) } : null,
2613
+ cost: { dev_buy_bnb: plain(cfg.devBuyUnits, 18), salt_lock_fee_bnb: plain(lockUnits, 18), total_bnb: plain(total, 18), total_usd: Number((Number(plain(total, 18)) * price).toFixed(2)), note: 'Gas is paid on top. The dev buy is an ordinary bonding-curve buy: Flap takes its 1% curve fee from it (and, on a tax token, the token\'s own tax is added while it is still on the curve), and you receive the tokens it buys.' },
2614
+ transactions: steps.map((s) => ({ what: s.label, to: s.to, contract: 'Flap Portal', value_bnb: plain(s.value, 18), ...(dryRun ? {} : { calldata: s.data }) })),
2615
+ };
2616
+ return { plan, view, dryRun, notes, cfg };
2617
+ }
2618
+
2619
+ async function guardReport(plan, ctx) {
2620
+ engine.tidy(plan);
2621
+ if (ctx.wallet) {
2622
+ let r; try { r = await engine.inspect(plan, ctx.wallet, ctx.policy, ctx.ledger); } catch (e) { r = { blocks: [String(e.message || e)], needsApproval: true, gasUsd: 0, simulated: 0, why: '' }; }
2623
+ return { checks: 'full: policy, allowed contracts, simulation (eth_call + estimateGas), balance', wouldBlock: r.blocks, needsApproval: r.needsApproval, why: r.why, gasUsd: Number(r.gasUsd.toFixed(3)), simulatedSteps: r.simulated };
2624
+ }
2625
+ const v = checkIntent(ctx.policy, ctx.ledger.spentToday(), { action: 'launch', usd: plan.usd, targets: plan.steps.map((s) => s.to), recipient: plan.recipient });
2626
+ return { checks: 'policy only (no wallet): limits and allowed contracts. Simulation, gas and balance were NOT checked.', wouldBlock: v.blocks, needsApproval: v.needsApproval, why: v.why };
2627
+ }
2628
+
2629
+ const prune = () => { for (const [k, v] of prepared) if (v.expires < now()) prepared.delete(k); };
2630
+ const prepareTool = {
2631
+ name: 'flap_prepare_launch',
2632
+ description: 'Plan a Flap token launch on BNB Chain (bonding curve) and check it against the Guard. Validates the inputs, mines the vanity salt (tax tokens end in 7777, no-tax tokens in 8888), builds the exact Portal transaction, simulates it and says what the Guard would do. Returns the predicted token address and total cost. The metadata CID is part of the transaction, so give a metaCid you already uploaded through Flap, or an image: then the Guard is checked first and the image and details are published on Flap\'s public IPFS gateway (permanent, cannot be undone) only if the wallet owner allows it (policy allowPublicUploads, or a yes in their client). Local image files are read only if the owner set allowLocalImages. Nothing is signed or sent. Run flap_launch with the returned plan_id to execute (a human always approves).',
2633
+ inputSchema: { type: 'object', properties: {
2634
+ name: { type: 'string', description: 'Token name' }, symbol: { type: 'string', description: 'Token symbol, no spaces' }, description: { type: 'string' },
2635
+ image: { type: 'string', description: 'https URL of a PNG, JPEG, GIF or WebP (max 5 MB; a local absolute path works only if the owner enabled allowLocalImages). Uploaded to Flap with the owner\'s consent. Omit when metaCid is given.' },
2636
+ metaCid: { type: 'string', description: 'Metadata CID you already uploaded through Flap (bare CID). Skips the upload.' },
2637
+ website: { type: 'string' }, twitter: { type: 'string', description: 'Passed to the metadata unchanged' }, telegram: { type: 'string', description: 'Passed to the metadata unchanged' },
2638
+ devBuyBnb: { type: 'string', description: 'BNB for the creator\'s first buy at launch, e.g. "0.05". Default "0" (none).' },
2639
+ buyTaxBps: { type: 'integer', description: 'Buy tax in bps, 0 or 100 to 1000. Set buyTaxBps and/or sellTaxBps to launch a TAX token; omit both for a no-tax token.' },
2640
+ sellTaxBps: { type: 'integer', description: 'Sell tax in bps, 0 or 100 to 1000' },
2641
+ taxDurationDays: { type: 'integer', description: 'Tax tokens: how long the tax applies (default 365)' }, antiFarmerSeconds: { type: 'integer', description: 'Tax tokens: dividend farming blocked this long after launch (default 3600, max 365 days)' },
2642
+ beneficiary: { type: 'string', description: 'Tax tokens: address that receives the marketing share. Default: the local wallet. Any other address must be in allowedRecipients.' },
2643
+ mktBps: { type: 'integer', description: 'Tax tokens: share of the tax to the beneficiary, bps' }, dividendBps: { type: 'integer', description: 'Tax tokens: share paid to holders, bps' }, deflationBps: { type: 'integer', description: 'Tax tokens: share burned, bps' }, lpBps: { type: 'integer', description: 'Tax tokens: share added to liquidity, bps. The four shares must add up to 10000; default is 10000 to the beneficiary.' },
2644
+ dividendToken: { type: 'string', description: 'Tax tokens: "bnb" (default) or "self"' },
2645
+ minimumShareBalance: { type: 'string', description: 'Tokens a holder needs to earn dividends (at least 10000, the default)' },
2646
+ lockSalt: { type: 'boolean', description: 'Reserve the salt first (extra transaction, 0.01 BNB fee read from the Portal) so nobody can launch another token at your address first. Default false.' },
2647
+ salt: { type: 'string', description: 'A salt you mined yourself (bytes32); it is checked against the suffix rule' }, saltSearchSeconds: { type: 'integer', description: 'Give up mining after this long (default 30)' },
2648
+ dryRun: { type: 'boolean', description: 'Check everything without uploading anything. The result cannot be executed.' },
2649
+ }, required: ['name', 'symbol'] },
2650
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
2651
+ run: async (a) => {
2652
+ const ctx = engine.context();
2653
+ const { plan, view, dryRun, notes } = await build(a || {}, ctx);
2654
+ const guard = await guardReport(plan, ctx);
2655
+ const out = { status: dryRun ? 'preview' : 'prepared', summary: plan.summary, ...view, guard };
2656
+ if (!dryRun) { prune(); const id = randomHex(4); prepared.set(id, { plan, expires: now() + PLAN_TTL_MS }); out.plan_id = id; }
2657
+ out.wallet = ctx.wallet ? ctx.wallet.address : 'No wallet is set up, so this is an unsigned plan only. Run `npx -y anthropos-mcp init` on this machine and fund the wallet before flap_launch.';
2658
+ out.next_step = dryRun ? 'Preview only: nothing was uploaded. Call again without dryRun to upload and get a plan_id.' : guard.wouldBlock.length ? 'The Guard would block this as it stands. Report the reasons to the user; do not try to work around them.' : 'Show this plan to the user. If they want it, call flap_launch with plan_id. It will not send anything until the wallet owner approves.';
2659
+ out.notes = [...notes, 'Nothing was signed or sent. The token address is predicted from the salt and only exists once the transaction confirms.', 'A launch always needs the wallet owner\'s approval, whatever its value.'];
2660
+ out.unchecked = ['That the Flap Portal contract still accepts these parameters (only a simulation from a funded wallet tests that; without a wallet it was not simulated)', 'Whether the name, symbol or image infringe anyone\'s rights or break Flap\'s terms', 'Whether the beneficiary address is controlled by who you think it is', 'Vault, Agent ID gate and ERC-20 quote launches (not supported by this tool)'];
2661
+ return out;
2662
+ },
2663
+ };
2664
+ const launchTool = {
2665
+ name: 'flap_launch',
2666
+ description: 'Launch the token prepared by flap_prepare_launch. The Guard re-checks everything (limits, allowed contracts, simulation, balance) and a launch ALWAYS needs the wallet owner\'s approval: you get an id back, the owner runs `npx -y anthropos-mcp approve <id>` in their own terminal, then call confirm_action with that id. Never sent without that.',
2667
+ inputSchema: { type: 'object', properties: { plan_id: { type: 'string', description: 'plan_id from flap_prepare_launch' } }, required: ['plan_id'] },
2668
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
2669
+ run: async ({ plan_id } = {}) => {
2670
+ const ctx = engine.context(); engine.needWallet(ctx.wallet); prune();
2671
+ const hit = prepared.get(String(plan_id));
2672
+ if (!hit) throw new Error('Unknown or expired plan_id. Call flap_prepare_launch again (plans are kept for 15 minutes in memory).');
2673
+ const { plan } = hit;
2674
+ if (plan.launch.wallet && lc(plan.launch.wallet) !== lc(ctx.wallet.address)) throw new Error('The wallet changed since this plan was prepared. Prepare it again.');
2675
+ const result = await engine.finish(plan, ctx);
2676
+ if (result.status === 'approval_required' || result.status === 'sent') prepared.delete(String(plan_id));
2677
+ return { ...result, token: { name: plan.launch.name, symbol: plan.launch.symbol, predicted_address: plan.launch.token } };
2678
+ },
2679
+ };
2680
+ return [prepareTool, launchTool];
2681
+ }
2682
+
2683
+ return { FLAP, V6_FIELDS, V7_FIELDS, SELECTORS, encodeNewTokenV6, encodeNewTokenV7, encodeLockSalt, checksumAddress, predictTokenAddress, keccak256Short, findVanitySalt, normalizeLaunchInput, isPublicAddress, pinnedFetch, loadImage, uploadMetadata, createLaunch };
2684
+ })();
2685
+
2686
+ const __m_prompts = (() => {
2687
+ // MCP prompts: ready-made slash commands (Claude Code shows them as /mcp__anthropos__<name>). Each one returns a single user message that tells
2688
+ // the model which ANTHROPOS tools to call, in what order, and keeps the project's honesty rules. A prompt never calls a tool itself.
2689
+ const { isAddress } = __m_core;
2690
+
2691
+ /** A JSON-RPC error with a code, so main.mjs can answer exactly (-32602 for bad names and arguments). */
2692
+ class RpcError extends Error {
2693
+ constructor(code, message) { super(message); this.code = code; }
2694
+ }
2695
+ const bad = (message) => new RpcError(-32602, message);
2696
+
2697
+ const RULES = [
2698
+ 'Rules that always apply:',
2699
+ '- Show the user every flag and the full "unchecked" list a tool returns. "No flags" never means safe, and you must not call anything safe, risk-free or a good buy.',
2700
+ '- Quote before you execute. Never call an execute tool (swap_execute, bridge_execute, send_bnb, send_token, flap_launch) unless the user has seen the quote or plan and said yes in this chat.',
2701
+ '- The Guard decides. If it blocks something or asks for approval, report the reasons as they are. Do not retry with different numbers to get past it, do not try to change policy.json, and never ask for or reveal a private key.',
2702
+ '- Say what you did not run. Do not give financial advice or predict prices.',
2703
+ ].join('\n');
2704
+
2705
+ const ZERO_TO_DECIMAL = /^(?:0+(?:\.0*)?|\.0+)$/;
2706
+ const text = (value, label) => {
2707
+ if (value === undefined || value === null) return undefined;
2708
+ if (typeof value !== 'string' && typeof value !== 'number') throw bad(`${label} must be a string.`);
2709
+ const s = String(value).trim();
2710
+ return s === '' ? undefined : s;
2711
+ };
2712
+ const address = (value, label) => {
2713
+ const s = text(value, label);
2714
+ if (s === undefined) throw bad(`${label} is required.`);
2715
+ if (!isAddress(s)) throw bad(`${label} must be a 0x-prefixed BNB Chain address (0x followed by 40 hex characters).`);
2716
+ return s;
2717
+ };
2718
+ const bnbOrAddress = (value, label) => {
2719
+ const s = text(value, label);
2720
+ if (s === undefined) throw bad(`${label} is required ("BNB" or a token address).`);
2721
+ if (s.toUpperCase() === 'BNB') return 'BNB';
2722
+ if (!isAddress(s)) throw bad(`${label} must be "BNB" or a 0x-prefixed token address.`);
2723
+ return s;
2724
+ };
2725
+
2726
+ const PROMPTS = [
2727
+ {
2728
+ name: 'scan_token',
2729
+ title: 'Scan a token for risks',
2730
+ description: 'Read-only risk scan of a BNB Chain token: ownership, pause, Flap curve and tax, PancakeSwap pool and LP burn. Always ends with what was not checked.',
2731
+ arguments: [{ name: 'address', description: 'Token contract address (0x...)', required: true }],
2732
+ build: (a) => {
2733
+ const token = address(a.address, 'address');
2734
+ return [
2735
+ `Scan the BNB Chain token ${token} with ANTHROPOS and tell me the risks.`,
2736
+ '',
2737
+ '1. Call token_scan with this address. If it reports a Flap token (a "flap" object), also call flap_token for the curve state.',
2738
+ '2. Report: name, symbol, whether it is a contract. Then EVERY entry of "flags" with its level (danger / warn / info) in plain words, and the pool and LP-burn numbers if there are any.',
2739
+ '3. Finish with the complete "unchecked" list from the tool result, word for word, plus anything you did not run (holders, honeypot simulation, source verification, liquidity locks).',
2740
+ '4. Do not give a verdict such as safe or scam. Say which findings would worry you and why, and which you could not judge.',
2741
+ '5. Do not buy anything. If I want to, I will ask, and you will use swap_quote first.',
2742
+ '',
2743
+ RULES,
2744
+ ].join('\n');
2745
+ },
2746
+ },
2747
+ {
2748
+ name: 'new_flap_launches',
2749
+ title: 'Newest Flap launches',
2750
+ description: 'List the newest Flap bonding-curve launches with their taxes, curve progress and a short risk note each.',
2751
+ arguments: [
2752
+ { name: 'hours', description: 'How far back to look, in hours (0.1 to 24). The tool scans at most 5000 blocks, about 37 minutes. Default: the last ~1000 blocks', required: false },
2753
+ { name: 'limit', description: 'Maximum launches to list, 1 to 25 (default 10)', required: false },
2754
+ ],
2755
+ build: (a) => {
2756
+ const h = text(a.hours, 'hours'), l = text(a.limit, 'limit');
2757
+ let hours = null, limit = 10;
2758
+ if (h !== undefined) { hours = Number(h); if (!/^\d+(\.\d+)?$/.test(h) || !(hours >= 0.1 && hours <= 24)) throw bad('hours must be a number from 0.1 to 24.'); }
2759
+ if (l !== undefined) { limit = Number(l); if (!/^\d+$/.test(l) || limit < 1 || limit > 25) throw bad('limit must be a whole number from 1 to 25.'); }
2760
+ const wanted = hours === null ? 1000 : Math.round(hours * 8000); // BNB Chain makes a block about every 0.45 s
2761
+ const blocks = Math.min(wanted, 5000);
2762
+ const window = hours === null
2763
+ ? `Call flap_recent_launches with blocks: ${blocks} and limit: ${limit}.`
2764
+ : `I asked for the last ${hours} hour(s), which is about ${wanted} blocks. Call flap_recent_launches with blocks: ${blocks} and limit: ${limit}.${wanted > blocks ? ` The tool is capped at 5000 blocks (about 37 minutes), so tell me plainly that the window is shorter than I asked for.` : ''}`;
2765
+ return [
2766
+ 'List the newest Flap token launches on BNB Chain with ANTHROPOS.',
2767
+ '',
2768
+ `1. ${window}`,
2769
+ '2. Show a table: symbol, name, token address, age, status, buy / sell tax, progress to DEX migration and curve reserve in BNB.',
2770
+ '3. Mark every launch with a tax above 5% (buy or sell) or whose state could not be read ("state_error"). Say how many launches the window held and how many you are showing ("launches_in_window" vs "returned").',
2771
+ '4. For at most the 3 launches that look most worth a look, call token_scan and give the flags and the unchecked list for each. Do not scan the rest, and say you did not.',
2772
+ '5. Do not recommend buying. A new launch is a bet with a high chance of losing everything.',
2773
+ '',
2774
+ RULES,
2775
+ ].join('\n');
2776
+ },
2777
+ },
2778
+ {
2779
+ name: 'safe_swap',
2780
+ title: 'Swap with checks first',
2781
+ description: 'Scan, quote and only then swap, under the Guard. Shows the quote and every flag and asks you before anything is sent.',
2782
+ arguments: [
2783
+ { name: 'from', description: 'Token to sell: "BNB" or a token address', required: true },
2784
+ { name: 'to', description: 'Token to buy: "BNB" or a token address', required: true },
2785
+ { name: 'amount', description: 'Amount of the "from" token, e.g. 0.05', required: true },
2786
+ ],
2787
+ build: (a) => {
2788
+ const from = bnbOrAddress(a.from, 'from'), to = bnbOrAddress(a.to, 'to'), amount = text(a.amount, 'amount');
2789
+ if (amount === undefined) throw bad('amount is required, e.g. 0.05.');
2790
+ if (!/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(amount) || ZERO_TO_DECIMAL.test(amount)) throw bad('amount must be a positive decimal number such as 0.05 (no exponents, no commas).');
2791
+ if (from.toLowerCase() === to.toLowerCase()) throw bad('from and to must be different tokens.');
2792
+ const scans = [from, to].filter((t) => t !== 'BNB');
2793
+ return [
2794
+ `Swap ${amount} ${from} for ${to} on BNB Chain with ANTHROPOS, carefully and in this order.`,
2795
+ '',
2796
+ `1. Call token_scan for ${scans.join(' and ')}. Show me every flag and the full "unchecked" list of ${scans.length > 1 ? 'each' : 'it'}. If a scan reports a "danger" flag, stop here and ask me whether to go on.`,
2797
+ '2. Call wallet_info to check the wallet exists, has enough balance, and what limits apply (per action, per day, auto-approve). If there is no wallet, tell me how to create one (`npx -y anthropos-mcp init`) and stop.',
2798
+ `3. Call swap_quote with tokenIn "${from}", tokenOut "${to}", amount "${amount}". Show me: the route, the expected output, the USD value, the gas, and everything under "guard" (wouldBlock, needsApproval). Nothing has been sent at this point.`,
2799
+ '4. If the Guard would block it, report the reasons and stop. Do not change the amount, the slippage or the tokens to get around it.',
2800
+ '5. Ask me to confirm the exact quote. Only after I say yes, call swap_execute with the same tokenIn, tokenOut and amount. Do not execute on your own.',
2801
+ '6. If the result is "approval_required", tell me to run `npx -y anthropos-mcp approve <id>` in my own terminal. After I tell you I did, call confirm_action with that id. Report the final status and the transaction link.',
2802
+ '',
2803
+ RULES,
2804
+ ].join('\n');
2805
+ },
2806
+ },
2807
+ {
2808
+ name: 'perps_snapshot',
2809
+ title: 'Aster perps snapshot',
2810
+ description: 'Read-only snapshot of Aster perpetual futures: funding, open interest and order-book depth. Nothing is traded.',
2811
+ arguments: [{ name: 'symbol', description: 'Optional market such as BTCUSDT or just BTC. Without it: the busiest markets', required: false }],
2812
+ build: (a) => {
2813
+ const symbol = text(a.symbol, 'symbol');
2814
+ if (symbol !== undefined && !/^[A-Za-z0-9]{1,24}$/.test(symbol)) throw bad('symbol must be letters and digits only, e.g. BTCUSDT or BTC.');
2815
+ const steps = symbol === undefined
2816
+ ? [
2817
+ '1. Call perps_markets with sort left at its default (24h volume), limit 10 and includeOpenInterest true.',
2818
+ '2. Show a table: symbol, price, 24h change, 24h volume, funding rate and per-hour funding, open interest.',
2819
+ '3. Point out the most extreme funding rates (positive means longs pay shorts) and say what that implies, in one line each.',
2820
+ ]
2821
+ : [
2822
+ `1. Call perps_market with symbol "${symbol}" (fundingHistory 12) for the ticker, mark vs index, funding now and recent funding, open interest and the exchange limits.`,
2823
+ `2. Call perps_orderbook with symbol "${symbol}" to see depth and the spread.`,
2824
+ '3. Summarise: price and 24h move, mark vs index gap, current funding and its recent trend (positive means longs pay shorts), open interest, and how thin or deep the book is.',
2825
+ ];
2826
+ return [
2827
+ `Give me a read-only snapshot of Aster perpetual futures${symbol === undefined ? '' : ` for ${symbol}`} with ANTHROPOS.`,
2828
+ '',
2829
+ ...steps,
2830
+ '4. State that this is public exchange data only: there is no account, so nothing can be traded from here, and you must not offer to place orders. Say what you did not look at (liquidations, other venues, news).',
2831
+ '5. No predictions and no trade suggestions.',
2832
+ '',
2833
+ RULES,
2834
+ ].join('\n');
2835
+ },
2836
+ },
2837
+ {
2838
+ name: 'launch_checklist',
2839
+ title: 'Flap token launch checklist',
2840
+ description: 'Walk through launching a token on Flap: collect the inputs, dry-run the plan, show the cost and the Guard result. Nothing is uploaded or sent until you say so.',
2841
+ arguments: [
2842
+ { name: 'name', description: 'Token name (max 50 characters)', required: true },
2843
+ { name: 'symbol', description: 'Token symbol (letters and digits, max 12)', required: true },
2844
+ ],
2845
+ build: (a) => {
2846
+ const name = text(a.name, 'name'), symbol = text(a.symbol, 'symbol');
2847
+ if (name === undefined) throw bad('name is required.');
2848
+ if (symbol === undefined) throw bad('symbol is required.');
2849
+ if ([...name].length > 50 || !/^[\p{L}\p{N} ._'&-]+$/u.test(name)) throw bad('name must be 1 to 50 characters: letters, digits, spaces and . _ \' & - only.');
2850
+ if (!/^[A-Za-z0-9]{1,12}$/.test(symbol)) throw bad('symbol must be 1 to 12 letters or digits, no spaces.');
2851
+ return [
2852
+ `Help me launch a token on Flap (BNB Chain bonding curve) with ANTHROPOS. Name: ${JSON.stringify(name)}, symbol: ${JSON.stringify(symbol)}. Go step by step and stop at every question.`,
2853
+ '',
2854
+ '1. Call wallet_info. A launch needs a funded local wallet. If there is none, tell me how to create one (`npx -y anthropos-mcp init`) and stop.',
2855
+ '2. Ask me what is still missing: description, an image (https URL) or an already uploaded metaCid, website / socials, the creator\'s first buy in BNB (devBuyBnb), and whether this is a no-tax token or a tax token (buyTaxBps / sellTaxBps, 100 to 1000 bps, and how the tax is split). Do not invent values and do not pick taxes for me.',
2856
+ '3. Explain what I am committing to before anything runs: the launch costs real BNB (plus gas), is permanent, and a launch ALWAYS needs my approval. Uploading an image and details to Flap\'s public IPFS is permanent too and happens only if my policy allows it or I say yes.',
2857
+ '4. Call flap_prepare_launch with dryRun true first. Nothing is uploaded or signed. Show me the predicted token address (tax tokens end in 7777, no-tax tokens in 8888), total cost, the parameters, and everything under "guard" and "unchecked".',
2858
+ '5. If the Guard would block it, report the reasons and stop. Do not change settings to get around it.',
2859
+ '6. Only after I confirm the dry run, call flap_prepare_launch again without dryRun to get a plan_id, and show me that plan.',
2860
+ '7. Only after I say yes to that plan, call flap_launch with the plan_id. It returns an id: tell me to run `npx -y anthropos-mcp approve <id>` in my own terminal, and after I confirm I did, call confirm_action with that id. Report the result and the transaction link.',
2861
+ '8. Remind me at the end that a token launch is not a profit plan: most tokens lose their value, and you checked nothing about trademark, legal or platform-rule issues.',
2862
+ '',
2863
+ RULES,
2864
+ ].join('\n');
2865
+ },
2866
+ },
2867
+ {
2868
+ name: 'wallet_health',
2869
+ title: 'Wallet health check',
2870
+ description: 'Show the local wallet, its limits and today\'s spend, pending approvals and what it holds. Read-only.',
2871
+ arguments: [],
2872
+ build: () => [
2873
+ 'Check the health of my ANTHROPOS wallet. Read-only: do not send, swap or approve anything.',
2874
+ '',
2875
+ '1. Call wallet_info: address, BNB balance, limits, how much of today\'s limit is used. If there is no wallet, say so, tell me `npx -y anthropos-mcp init` creates one, and stop.',
2876
+ '2. Call policy_show: summarise the limits (per action, per day, auto-approve, slippage, gas, which actions are enabled) and the number of allowed recipients. Point out anything unusually loose, such as high caps or a long extra-contract list. Only the owner can edit policy.json; you cannot.',
2877
+ '3. List the pending approvals from wallet_info (id, summary, approved or waiting). For each one waiting, remind me that I approve it with `npx -y anthropos-mcp approve <id>` in my own terminal, and that I should read it first. Do not call confirm_action unless I ask.',
2878
+ '4. Call wallet_portfolio (no address: it uses the local wallet) and show the holdings, the USD values with their price source, the tokens it could not price, and the "unchecked" list.',
2879
+ '5. Close with any concerns: a nearly exhausted daily limit, a very low BNB balance for gas, or a balance far above what a burner wallet should hold.',
2880
+ '',
2881
+ RULES,
2882
+ ].join('\n'),
2883
+ },
2884
+ ];
2885
+
2886
+ const byName = new Map(PROMPTS.map((p) => [p.name, p]));
2887
+
2888
+ /** `prompts/list` payload: everything but the builder. */
2889
+ const listPrompts = () => PROMPTS.map(({ build, ...p }) => p);
2890
+
2891
+ /** `prompts/get` payload. Throws RpcError(-32602) for an unknown prompt, a missing or invalid argument, or an argument the prompt does not take. */
2892
+ function getPrompt(name, args) {
2893
+ const p = typeof name === 'string' ? byName.get(name) : undefined;
2894
+ if (!p) throw bad(`Unknown prompt: ${typeof name === 'string' ? name : ''}`.trim());
2895
+ if (args !== undefined && args !== null && (typeof args !== 'object' || Array.isArray(args))) throw bad('arguments must be an object of strings.');
2896
+ const given = args || {};
2897
+ const known = new Set(p.arguments.map((x) => x.name));
2898
+ for (const k of Object.keys(given)) if (!known.has(k)) throw bad(`Unknown argument "${k}" for prompt ${p.name}.`);
2899
+ return { description: p.description, messages: [{ role: 'user', content: { type: 'text', text: p.build(given) } }] };
2900
+ }
2901
+
2902
+ return { RpcError, PROMPTS, listPrompts, getPrompt };
2903
+ })();
2904
+
2905
+ const __m_portfolio = (() => {
2906
+ // wallet_portfolio: BNB and well-known token balances of one address in a single Multicall3 request, valued only where a price source exists.
2907
+ // Read-only. Anything outside the built-in list, and everything that is not a plain ERC-20 balance, is named in `unchecked`.
2908
+ const { ADDR, CHAIN, MULTICALL3, bnbUsd, formatUnits, isAddress, multicall, pairPricesBnb } = __m_core;
2909
+ const { loadWallet } = __m_wallet;
2910
+
2911
+ /** Major BNB Chain tokens. Address, symbol and decimals were each read back from the chain (symbol(), decimals()); see portfolio.test.mjs. */
2912
+ const PORTFOLIO_TOKENS = [
2913
+ { symbol: 'WBNB', address: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c', decimals: 18 },
2914
+ { symbol: 'USDT', address: '0x55d398326f99059fF775485246999027B3197955', decimals: 18, stable: true },
2915
+ { symbol: 'USDC', address: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d', decimals: 18, stable: true },
2916
+ { symbol: 'BUSD', address: '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56', decimals: 18, stable: true },
2917
+ { symbol: 'FDUSD', address: '0xc5f0f7b66764F6ec8C8Dff7BA683102295E16409', decimals: 18, stable: true },
2918
+ { symbol: 'USD1', address: '0x8d0D000Ee44948FC98c9B98A4FA4921476f08B0d', decimals: 18, stable: true },
2919
+ { symbol: 'DAI', address: '0x1AF3F329e8BE154074D8769D1FFa4eE058B1DBc3', decimals: 18, stable: true },
2920
+ { symbol: 'CAKE', address: '0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82', decimals: 18 },
2921
+ { symbol: 'ETH', address: '0x2170Ed0880ac9A755fd29B2688956BD959F933F8', decimals: 18 },
2922
+ { symbol: 'BTCB', address: '0x7130d2A12B9BCbFAe4f2634d864A1Ee1Ce3Ead9c', decimals: 18 },
2923
+ { symbol: 'XRP', address: '0x1D2F0da169ceB9fC7B3144628dB156f3F6c60dBE', decimals: 18 },
2924
+ { symbol: 'ADA', address: '0x3EE2200Efb3400fAbB9AacF31297cBdD1d435D47', decimals: 18 },
2925
+ { symbol: 'DOGE', address: '0xbA2aE424d960c26247Dd6c32edC70B295c744C43', decimals: 8 },
2926
+ { symbol: 'DOT', address: '0x7083609fCE4d1d8Dc0C979AAb8c869Ea2C873402', decimals: 18 },
2927
+ { symbol: 'LINK', address: '0xF8A0BF9cF54Bb92F17374d9e9A321E6a111a51bD', decimals: 18 },
2928
+ { symbol: 'UNI', address: '0xBf5140A22578168FD562DCcF235E5D43A02ce9B1', decimals: 18 },
2929
+ { symbol: 'LTC', address: '0x4338665CBB7B2485A8855A139b75D5e34AB0DB94', decimals: 18 },
2930
+ { symbol: 'TRX', address: '0xCE7de646e7208a4Ef112cb6ed5038FA6cC6b12e3', decimals: 6 },
2931
+ { symbol: 'AVAX', address: '0x1CE0c2827e2eF14D5C4f29a091d735A204794041', decimals: 18 },
2932
+ { symbol: 'MATIC', address: '0xCC42724C6683B7E57334c4E856f4c9965ED682bD', decimals: 18 },
2933
+ { symbol: 'ATOM', address: '0x0Eb3a705fc54725037CC9e008bDede697f62F335', decimals: 18 },
2934
+ { symbol: 'SHIB', address: '0x2859e4544C4bB03966803b044A93563Bd2D0DD4D', decimals: 18 },
2935
+ { symbol: 'TWT', address: '0x4B0F1812e5Df2A09796481Ff14017e6005508003', decimals: 18 },
2936
+ { symbol: 'XVS', address: '0xcF6BB5389c92Bdda8a3747Ddb454cB7a64626C63', decimals: 18 },
2937
+ { symbol: 'AAVE', address: '0xfb6115445Bff7b52FeB98650C87f44907E58f802', decimals: 18 },
2938
+ { symbol: '1INCH', address: '0x111111111117dC0aa78b770fA6A738034120C302', decimals: 18 },
2939
+ { symbol: 'FLOKI', address: '0xfb5B838b6cfEEdC2873aB27866079AC55363D37E', decimals: 9 },
2940
+ { symbol: 'LISTA', address: '0xFceB31A79F71AC9CBDCF853519c1b12D379EdC46', decimals: 18 },
2941
+ { symbol: 'BabyDoge', address: '0xc748673057861a797275CD8A068AbB95A902e8de', decimals: 9 },
2942
+ { symbol: 'slisBNB', address: '0xB0b84D294e0C75A6abe60171b70edEb2EFd14A1B', decimals: 18 },
2943
+ ];
2944
+
2945
+ /** A Pancake V2 pool must hold at least this much (both sides, in USD) before its price is trusted. Same bar as the web portfolio. */
2946
+ const MIN_POOL_USD = 20000;
2947
+ const SEL_BALANCE_OF = '0x70a08231', SEL_ETH_BALANCE = '0x4d2301cc'; // balanceOf(address); Multicall3.getEthBalance(address)
2948
+ const pad = (a) => a.slice(2).toLowerCase().padStart(64, '0');
2949
+ const word0 = (r) => (r.success && r.data.length >= 66 ? BigInt(r.data.slice(0, 66)) : null);
2950
+
2951
+ const UNCHECKED = [
2952
+ 'Tokens that are not in the built-in list (every other BEP-20, including Flap launches and memecoins)',
2953
+ 'NFTs',
2954
+ 'PancakeSwap LP positions (V2 LP tokens and V3 position NFTs)',
2955
+ 'Staked, farmed, lent, vested or locked balances in other contracts (Venus, staking pools, Flap dividends, ...)',
2956
+ 'Native balances on other chains',
2957
+ 'Pending rewards and unclaimed airdrops',
2958
+ ];
2959
+
2960
+ /**
2961
+ * BNB and listed-token balances for `address`, one aggregate3 call; prices only for the tokens actually held.
2962
+ * Price sources: stablecoins counted at $1 (peg not checked), WBNB and BNB from the WBNB/USDT Pancake V2 pool, other tokens from a
2963
+ * Pancake V2 pool against WBNB with at least MIN_POOL_USD of liquidity. Everything else is listed as unpriced and left out of the total.
2964
+ */
2965
+ async function walletPortfolio(rpc, address, { tokens = PORTFOLIO_TOKENS, getBnbUsd = bnbUsd, minPoolUsd = MIN_POOL_USD } = {}) {
2966
+ if (!isAddress(address)) throw new Error('Invalid address. Expected 0x followed by 40 hex characters.');
2967
+ const results = await multicall(rpc, [{ to: MULTICALL3, data: SEL_ETH_BALANCE + pad(address) }, ...tokens.map((t) => ({ to: t.address, data: SEL_BALANCE_OF + pad(address) }))]);
2968
+ const wei = word0(results[0]);
2969
+ if (wei === null) throw new Error('Multicall3 did not return the BNB balance.');
2970
+ let failed = 0;
2971
+ const held = [];
2972
+ tokens.forEach((t, i) => {
2973
+ const r = results[i + 1], raw = r ? word0(r) : null;
2974
+ if (raw === null) { failed++; return; }
2975
+ if (raw > 0n) held.push({ ...t, raw });
2976
+ });
2977
+
2978
+ let bnb = null, priceNote = null;
2979
+ try { bnb = await getBnbUsd(rpc); } catch (e) { priceNote = `BNB price unavailable (${e.message}), so nothing could be valued in USD`; }
2980
+ const wbnb = ADDR.WBNB.toLowerCase();
2981
+ const needPool = held.filter((h) => !h.stable && h.address.toLowerCase() !== wbnb);
2982
+ let pools = new Map();
2983
+ if (bnb && needPool.length) { try { pools = await pairPricesBnb(rpc, needPool.map((h) => h.address)); } catch (e) { priceNote = `token pools could not be read (${e.message})`; } }
2984
+
2985
+ const rows = held.map((h) => {
2986
+ const amount = Number(h.raw) / 10 ** h.decimals;
2987
+ const row = { symbol: h.symbol, address: h.address, balance: formatUnits(h.raw, h.decimals, 8), raw: h.raw.toString(), decimals: h.decimals, priceUsd: null, valueUsd: null, priceSource: null };
2988
+ if (h.stable) { row.priceUsd = 1; row.priceSource = 'assumed $1 (stablecoin; peg not checked)'; }
2989
+ else if (h.address.toLowerCase() === wbnb) { if (bnb) { row.priceUsd = bnb; row.priceSource = 'PancakeSwap V2 WBNB/USDT pool'; } else row.note = 'unpriced: BNB price unavailable'; }
2990
+ else if (!bnb) row.note = 'unpriced: BNB price unavailable';
2991
+ else {
2992
+ const p = pools.get(h.address.toLowerCase());
2993
+ if (!p) row.note = 'unpriced: no PancakeSwap V2 pool against WBNB (a V3 pool or another route may exist; it was not checked)';
2994
+ else if (p.tokenReserveRaw === 0n || p.bnbReserve * bnb * 2 < minPoolUsd) row.note = `unpriced: the PancakeSwap V2 pool is too small to trust (under $${minPoolUsd.toLocaleString('en-US')} of liquidity)`;
2995
+ else { row.priceUsd = Number(((p.bnbReserve / (Number(p.tokenReserveRaw) / 10 ** h.decimals)) * bnb).toPrecision(6)); row.priceSource = 'PancakeSwap V2 pool against WBNB'; }
2996
+ }
2997
+ if (row.priceUsd !== null) row.valueUsd = Number((amount * row.priceUsd).toFixed(2));
2998
+ return row;
2999
+ });
3000
+ rows.sort((a, b) => (b.valueUsd ?? -1) - (a.valueUsd ?? -1) || a.symbol.localeCompare(b.symbol));
3001
+
3002
+ const bnbAmount = Number(wei) / 1e18;
3003
+ const bnbValue = bnb ? Number((bnbAmount * bnb).toFixed(2)) : null;
3004
+ const priced = rows.filter((r) => r.valueUsd !== null), unpriced = rows.filter((r) => r.valueUsd === null).map((r) => r.symbol);
3005
+ return {
3006
+ address, chain: `${CHAIN.name} (${CHAIN.id})`,
3007
+ bnb: { balance: formatUnits(wei, 18, 8), balanceWei: wei.toString(), priceUsd: bnb === null ? null : Number(bnb.toFixed(2)), valueUsd: bnbValue },
3008
+ tokens: rows,
3009
+ totalPricedUsd: bnb ? Number(((bnbValue || 0) + priced.reduce((s, r) => s + r.valueUsd, 0)).toFixed(2)) : null,
3010
+ totalNote: bnb ? (unpriced.length ? `Covers BNB and the priced tokens only. Held but not valued: ${unpriced.join(', ')}.` : 'Covers BNB and the listed tokens held.') : 'No total: ' + priceNote,
3011
+ unpriced,
3012
+ checked: { tokens: tokens.map((t) => t.symbol), count: tokens.length + 1, requests: 'one Multicall3 aggregate3 call for BNB and every listed balance', failedReads: failed },
3013
+ unchecked: UNCHECKED,
3014
+ ...(priceNote && bnb ? { priceWarning: priceNote } : {}),
3015
+ note: 'Public on-chain reads. Prices come from single PancakeSwap V2 pools and are not an audit or a quote you can trade at. Not financial advice.',
3016
+ };
3017
+ }
3018
+
3019
+ /** The `wallet_portfolio` tool. The address defaults to the local wallet when one is set up. */
3020
+ function createPortfolio({ rpc, env = process.env, getBnbUsd = bnbUsd, tokens = PORTFOLIO_TOKENS } = {}) {
3021
+ return [{
3022
+ name: 'wallet_portfolio',
3023
+ description: `BNB and about ${tokens.length} well-known BEP-20 token balances of an address (default: the local ANTHROPOS wallet) read in one Multicall3 request, with USD values only where a price source exists (stablecoins at $1, PancakeSwap V2 pools with enough liquidity). Unpriced tokens are marked, never guessed. Returns an explicit list of what was NOT checked: other tokens, NFTs, LP positions, staking.`,
3024
+ inputSchema: { type: 'object', properties: { address: { type: 'string', description: '0x-prefixed BNB Chain address. Omit to use the local wallet.' } } },
3025
+ annotations: { readOnlyHint: true, openWorldHint: true },
3026
+ run: async (a) => {
3027
+ let address = a?.address, source = 'argument';
3028
+ if (address === undefined || address === null || address === '') { const w = loadWallet(env); if (!w) throw new Error('No address given and no local wallet is set up. Pass an address, or run `npx -y anthropos-mcp init` to create a burner wallet.'); address = w.address; source = 'local wallet'; }
3029
+ return { addressSource: source, ...(await walletPortfolio(rpc, address, { tokens, getBnbUsd })) };
3030
+ },
3031
+ }];
3032
+ }
3033
+
3034
+ return { PORTFOLIO_TOKENS, MIN_POOL_USD, walletPortfolio, createPortfolio };
1330
3035
  })();
1331
3036
 
1332
3037
  const { VERSION, DEFAULT_RPCS, makeRpc, isAddress, bnbBalance, tokenInfo, tokenScan, flapToken, flapRecent } = __m_core;
1333
3038
  const { createActions } = __m_actions;
3039
+ const { configure: configureRelay } = __m_relay;
3040
+ const { createPerps } = __m_perps;
3041
+ const { createLaunch } = __m_launch;
3042
+ const { PROMPTS, RpcError, getPrompt, listPrompts } = __m_prompts;
3043
+ const { createPortfolio } = __m_portfolio;
1334
3044
  const { homeDir, initWallet, loadWallet } = __m_wallet;
1335
- const { Ledger, writeDefaultPolicy } = __m_guard;
3045
+ const { checkPattern, createVanity, expectedAttempts, findVanity, listCandidates, saveCandidate, useCandidate } = __m_vanity;
3046
+ const { runInstall } = __m_install;
3047
+ const { Ledger, loadPolicy, writeDefaultPolicy } = __m_guard;
1336
3048
 
1337
3049
  const rpcUrls = process.env.BSC_RPC_URL ? process.env.BSC_RPC_URL.split(',').map((s) => s.trim()).filter(Boolean) : DEFAULT_RPCS;
1338
3050
  const rpc = makeRpc({ urls: rpcUrls });
3051
+ /** Hosted node URLs carry the provider key in the path or query; the model must only ever see the host. */
3052
+ const redact = (u) => { try { return new URL(u).origin; } catch { return 'rpc'; } };
3053
+ const rpcHosts = rpcUrls.map(redact);
3054
+ configureRelay({ baseUrl: process.env.RELAY_API_URL, key: process.env.RELAY_API_KEY }); // optional: a Relay API key raises the rate limit; none is bundled
1339
3055
  const addrSchema = { type: 'string', description: '0x-prefixed BNB Chain address (42 chars)' };
1340
3056
 
1341
3057
  const TOOLS = [
1342
3058
  { name: 'anthropos_status', description: 'What ANTHROPOS can do right now and what is still planned. Call this first if unsure.', inputSchema: { type: 'object', properties: {} }, annotations: { readOnlyHint: true }, run: async () => {
1343
3059
  const w = (() => { try { return loadWallet(); } catch (e) { return { error: e.message }; } })();
1344
- return { name: 'ANTHROPOS MCP', version: VERSION, chain: 'BNB Smart Chain (56), mainnet only', rpc: rpcUrls,
1345
- wallet: w ? (w.error ? { problem: w.error } : { address: w.address }) : 'not set up: run `anthropos-mcp init` on this machine',
1346
- read: ['bnb_balance', 'token_info', 'token_scan', 'flap_token', 'flap_recent_launches'],
1347
- act: ['wallet_info', 'swap_quote', 'swap_execute', 'bridge_quote', 'bridge_execute', 'send_bnb', 'send_token', 'confirm_action', 'policy_show'],
3060
+ return { name: 'ANTHROPOS MCP', version: VERSION, chain: 'BNB Smart Chain (56), mainnet only', rpc: rpcHosts,
3061
+ wallet: w ? (w.error ? { problem: w.error } : { address: w.address }) : 'not set up: run `npx -y anthropos-mcp init` on this machine',
3062
+ read: TOOLS.filter((t) => t.annotations?.readOnlyHint && t.name !== 'anthropos_status').map((t) => t.name),
3063
+ act: TOOLS.filter((t) => !t.annotations?.readOnlyHint).map((t) => t.name),
1348
3064
  guard: 'Every action is checked against spending limits, an allowed-contract list and a simulation before anything is signed. Larger actions need a human to approve them.',
1349
- planned: ['Flap token launch', 'perpetual futures', 'multi-chain wallets'],
3065
+ planned: ['placing perp orders from the agent (needs your own Aster API wallet)', 'multi-chain wallets'],
3066
+ prompts: PROMPTS.map((p) => p.name), promptsNote: 'MCP prompts: clients list them as slash commands (Claude Code: /mcp__anthropos__<name>).',
3067
+ resources: RESOURCES.map((r) => r.uri),
1350
3068
  note: 'Heuristic reads of public data. Not an audit, not financial advice. Not affiliated with Anthropic, Flap, PancakeSwap or Relay.' }; } },
1351
3069
  { name: 'bnb_balance', description: 'BNB balance of an address on BNB Chain mainnet, and whether it is a contract.', inputSchema: { type: 'object', properties: { address: addrSchema }, required: ['address'] }, run: (a) => bnbBalance(rpc, a.address) },
1352
3070
  { name: 'token_info', description: 'ERC-20 basics for a token: name, symbol, decimals, supply, bytecode size, EIP-1167 clone detection.', inputSchema: { type: 'object', properties: { address: addrSchema }, required: ['address'] }, run: (a) => tokenInfo(rpc, a.address) },
@@ -1354,6 +3072,7 @@ const TOOLS = [
1354
3072
  { name: 'flap_token', description: 'Flap bonding-curve state for a token: status, price, supply, progress to DEX migration, buy/sell tax, vault risk level.', inputSchema: { type: 'object', properties: { address: addrSchema }, required: ['address'] }, run: (a) => flapToken(rpc, a.address) },
1355
3073
  { name: 'flap_recent_launches', description: 'Most recent token launches on the Flap bonding-curve Portal (BNB Chain) with live curve state for each.', inputSchema: { type: 'object', properties: { blocks: { type: 'integer', description: 'How many recent blocks to scan (1-5000, default 1000, about 0.45 s per block)' }, limit: { type: 'integer', description: 'Max launches to return (1-25, default 15)' } } }, run: (a) => flapRecent(rpc, a || {}) },
1356
3074
  ];
3075
+ for (const t of TOOLS) t.annotations ??= { readOnlyHint: true, openWorldHint: true }; // the built-in reads never write anything
1357
3076
 
1358
3077
  const send = (m) => process.stdout.write(JSON.stringify(m) + '\n');
1359
3078
  let clientCaps = {};
@@ -1370,6 +3089,43 @@ function elicitApproval(text) {
1370
3089
  }
1371
3090
  const actions = createActions({ rpc, elicit: (text) => (clientCaps.elicitation ? elicitApproval(text) : Promise.resolve(null)) });
1372
3091
  TOOLS.push(...actions);
3092
+ TOOLS.push(...createPortfolio({ rpc, env: process.env }));
3093
+ TOOLS.push(...createVanity({ env: process.env }));
3094
+ TOOLS.push(...createPerps({ rpc, env: process.env }));
3095
+ TOOLS.push(...createLaunch({ rpc, env: process.env, elicit: (text) => (clientCaps.elicitation ? elicitApproval(text) : Promise.resolve(null)) }));
3096
+
3097
+ /** Read-only MCP resources. Small, and never key material: the policy is read from policy.json only, the rest is static or already public through a tool. */
3098
+ const GUIDE = [
3099
+ '# ANTHROPOS usage guide',
3100
+ '',
3101
+ 'ANTHROPOS reads BNB Chain and Flap data and can act from a local burner wallet under hard limits (the Guard). Mainnet only, independent project, not financial advice.',
3102
+ '',
3103
+ '## Reading (no wallet needed)',
3104
+ '- token_scan: risk flags AND what was not checked. Show both. "No flags" never means safe.',
3105
+ '- flap_token, flap_recent_launches: Flap bonding-curve state and the newest launches.',
3106
+ '- bnb_balance, wallet_portfolio: balances; the portfolio values only tokens with a price source and names what it did not check.',
3107
+ '- perps_markets, perps_market, perps_orderbook, perps_klines, perps_order_preview: Aster perpetual data. Nothing is traded.',
3108
+ '',
3109
+ '## Acting (needs `npx -y anthropos-mcp init`)',
3110
+ '- Quote first (swap_quote, bridge_quote), then execute (swap_execute, bridge_execute, send_bnb, send_token, flap_launch).',
3111
+ '- Nothing is signed before the Guard says yes: per-action and daily USD caps, slippage and gas caps, allowed contracts, a simulation.',
3112
+ '- Above the auto-approve amount, and for every transfer and launch, the wallet owner approves outside the chat (`npx -y anthropos-mcp approve <id>`), then confirm_action runs it.',
3113
+ '- Never try to raise limits or get around a block. Report the reasons.',
3114
+ '',
3115
+ '## Prompts and resources',
3116
+ `- Prompts (slash commands): ${PROMPTS.map((p) => p.name).join(', ')}.`,
3117
+ '- Resources: anthropos://policy (active limits), anthropos://status (capabilities), anthropos://guide (this text).',
3118
+ '',
3119
+ 'Keys never leave the owner\'s machine and no tool returns one.',
3120
+ ].join('\n');
3121
+ const jsonText = (v) => JSON.stringify(v, (_, x) => (typeof x === 'bigint' ? x.toString() : x), 2);
3122
+ const RESOURCES = [
3123
+ { uri: 'anthropos://policy', name: 'policy', title: 'Active spending policy', description: 'The Guard limits from policy.json (same data as the policy_show tool). Only the wallet owner can change them.', mimeType: 'application/json',
3124
+ read: () => { const home = homeDir(process.env); return jsonText({ policy: loadPolicy(home), editFile: `${home}/policy.json`, note: 'Only the wallet owner can change limits, by editing this file. The agent cannot.' }); } },
3125
+ { uri: 'anthropos://status', name: 'status', title: 'ANTHROPOS status', description: 'What this server can do right now (same data as the anthropos_status tool).', mimeType: 'application/json',
3126
+ read: async () => jsonText(await TOOLS[0].run({})) },
3127
+ { uri: 'anthropos://guide', name: 'guide', title: 'Usage guide', description: 'Short guide to the tools, the Guard and the honesty rules.', mimeType: 'text/markdown', read: () => GUIDE },
3128
+ ];
1373
3129
  const reply = (id, result) => send({ jsonrpc: '2.0', id, result });
1374
3130
  const fail = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
1375
3131
 
@@ -1378,50 +3134,110 @@ async function handle(line) {
1378
3134
  if (m.method === undefined && m.id !== undefined && waiting.has(m.id)) { const done = waiting.get(m.id); waiting.delete(m.id); return done(m); }
1379
3135
  const { id, method, params } = m;
1380
3136
  if (method === 'initialize') clientCaps = params?.capabilities || {};
1381
- if (method === 'initialize') return reply(id, { protocolVersion: params?.protocolVersion || '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'anthropos', version: VERSION },
1382
- instructions: 'ANTHROPOS reads BNB Chain and Flap data and can act with a local burner wallet under hard spending limits (Guard). Mainnet only. Always show the user the flags and the unchecked list from token_scan before buying anything. Quote first, then execute. Never try to raise limits or work around a block: report the reasons to the user. Actions above the auto-approve amount need the wallet owner to approve them outside the chat.' });
3137
+ if (method === 'initialize') return reply(id, { protocolVersion: params?.protocolVersion || '2024-11-05', capabilities: { tools: {}, prompts: { listChanged: false }, resources: { subscribe: false, listChanged: false } }, serverInfo: { name: 'anthropos', version: VERSION },
3138
+ instructions: 'ANTHROPOS reads BNB Chain and Flap data and can act with a local burner wallet under hard spending limits (Guard). Mainnet only. Always show the user the flags and the unchecked list from token_scan before buying anything. Quote first, then execute. Never try to raise limits or work around a block: report the reasons to the user. Actions above the auto-approve amount need the wallet owner to approve them outside the chat. Ready-made prompts (slash commands) cover the common jobs: ' + PROMPTS.map((p) => p.name).join(', ') + '. Read-only resources: ' + RESOURCES.map((r) => r.uri).join(', ') + '.' });
1383
3139
  if (method?.startsWith('notifications/')) return;
1384
3140
  if (method === 'ping') return reply(id, {});
1385
3141
  if (method === 'tools/list') return reply(id, { tools: TOOLS.map(({ run, ...t }) => t) });
3142
+ if (method === 'prompts/list') return reply(id, { prompts: listPrompts() });
3143
+ if (method === 'prompts/get') {
3144
+ try { return reply(id, getPrompt(params?.name, params?.arguments)); }
3145
+ catch (e) { return e instanceof RpcError ? fail(id, e.code, e.message) : fail(id, -32603, 'internal error: ' + (e.message || e)); }
3146
+ }
3147
+ if (method === 'resources/list') return reply(id, { resources: RESOURCES.map(({ read, ...r }) => r) });
3148
+ if (method === 'resources/templates/list') return reply(id, { resourceTemplates: [] });
3149
+ if (method === 'resources/read') {
3150
+ const r = RESOURCES.find((x) => x.uri === params?.uri);
3151
+ if (!r) return fail(id, -32002, 'resource not found: ' + params?.uri);
3152
+ try { return reply(id, { contents: [{ uri: r.uri, mimeType: r.mimeType, text: await r.read() }] }); }
3153
+ catch (e) { return fail(id, -32603, 'could not read ' + r.uri + ': ' + (e.message || e)); }
3154
+ }
1386
3155
  if (method === 'tools/call') {
1387
3156
  const t = TOOLS.find((x) => x.name === params?.name);
1388
3157
  if (!t) return fail(id, -32602, 'unknown tool: ' + params?.name);
1389
3158
  const args = params.arguments || {};
1390
3159
  if (t.inputSchema.required?.includes('address') && !isAddress(args.address)) return reply(id, { isError: true, content: [{ type: 'text', text: 'Invalid address. Expected 0x followed by 40 hex characters.' }] });
1391
3160
  try { return reply(id, { content: [{ type: 'text', text: JSON.stringify(await t.run(args), (_, v) => (typeof v === 'bigint' ? v.toString() : v), 2) }] }); }
1392
- catch (e) { return reply(id, { isError: true, content: [{ type: 'text', text: 'Error: ' + (e.message || e) + ' (RPC: ' + rpcUrls.join(', ') + ')' }] }); }
3161
+ catch (e) { return reply(id, { isError: true, content: [{ type: 'text', text: 'Error: ' + (e.message || e) + ' (RPC: ' + rpcHosts.join(', ') + ')' }] }); }
1393
3162
  }
1394
3163
  if (id !== undefined && id !== null) fail(id, -32601, 'method not found: ' + method);
1395
3164
  }
1396
3165
 
1397
3166
  const arg = process.argv[2];
1398
3167
  if (arg === '--version') { console.log(VERSION); process.exit(0); }
1399
- if (arg === '--help' || arg === 'help') {
3168
+ if (arg === '--help' || arg === '-h' || arg === 'help') {
1400
3169
  console.log(`ANTHROPOS MCP ${VERSION}
1401
3170
  Stdio MCP server for BNB Chain: read tools, plus actions from a local burner wallet under hard limits.
1402
3171
 
1403
3172
  anthropos-mcp start the MCP server (this is what your MCP client runs)
3173
+ anthropos-mcp install add ANTHROPOS to Claude Code, Claude Desktop and Cursor (--dry to preview, --uninstall to remove)
1404
3174
  anthropos-mcp init create a burner wallet and a default policy; prints only the public address
3175
+ anthropos-mcp vanity find a wallet address you like: --prefix dead --suffix 7777 --minutes 10 (uses all CPU cores)
3176
+ anthropos-mcp wallet list saved vanity candidates; wallet use <address> make one the active wallet (asks you to confirm)
1405
3177
  anthropos-mcp address print the wallet address
1406
3178
  anthropos-mcp pending list actions waiting for your approval
1407
3179
  anthropos-mcp approve <id> review and approve a pending action (needs an interactive terminal)
1408
3180
  anthropos-mcp --selftest check that the RPC is reachable
1409
3181
 
1410
- Files live in ${homeDir()} (override with ANTHROPOS_HOME). Env: BSC_RPC_URL=comma,separated,urls`);
3182
+ install options: --dry --uninstall --client=claude-code|claude-desktop|cursor
3183
+
3184
+ Files live in ${homeDir()} (override with ANTHROPOS_HOME).
3185
+ Env: BSC_RPC_URL=comma,separated,urls RELAY_API_KEY RELAY_API_URL ANTHROPOS_PERPS_API ANTHROPOS_KEY_FILE ANTHROPOS_PRIVATE_KEY`);
1411
3186
  process.exit(0);
1412
3187
  }
1413
3188
  if (arg === 'init') {
1414
3189
  try { const w = initWallet(); const policy = writeDefaultPolicy(w.dir); console.log(`Wallet created.\n Address: ${w.address}\n Key file: ${w.file} (keep it private; it is never printed or sent anywhere)\n Policy: ${policy}\n\nFund the address with a small amount of BNB. This is a burner wallet: do not keep more in it than you can afford to lose.`); process.exit(0); }
1415
3190
  catch (e) { console.error('init failed: ' + e.message); process.exit(1); }
1416
3191
  }
1417
- if (arg === 'address') { try { const w = loadWallet(); if (!w) { console.error('No wallet. Run: anthropos-mcp init'); process.exit(1); } console.log(w.address); process.exit(0); } catch (e) { console.error(e.message); process.exit(1); } }
3192
+ if (arg === 'install') { runInstall(process.argv.slice(3)); process.exit(0); }
3193
+ if (arg === 'vanity-worker') { // internal: one search process of `vanity`
3194
+ const [, , , prefix, suffix, ms] = process.argv; const r = findVanity({ prefix, suffix, maxMs: Number(ms) });
3195
+ process.stdout.write(JSON.stringify({ priv: r.priv === null ? null : r.priv.toString(16).padStart(64, '0'), attempts: r.attempts }) + '\n'); process.exit(0);
3196
+ }
3197
+ if (arg === 'vanity') {
3198
+ const opt = (name) => { const i = process.argv.indexOf('--' + name); return i > 0 ? String(process.argv[i + 1] || '') : ''; };
3199
+ const prefix = opt('prefix').toLowerCase().replace(/^0x/, ''), suffix = opt('suffix').toLowerCase(), minutes = Number(opt('minutes') || 5);
3200
+ const usage = 'Usage: anthropos-mcp vanity --prefix dead --suffix 7777 [--minutes 10]\nEach extra hex character is 16x more work: 4 characters takes seconds, 6 takes minutes, 8 takes hours.';
3201
+ try { if (!(Number.isFinite(minutes) && minutes > 0)) throw new Error('--minutes must be a positive number'); checkPattern(prefix, suffix); } catch (e) { console.error(`${e.message}\n${usage}`); process.exit(1); }
3202
+ const workers = Math.max(1, os.cpus().length - 1), ms = Math.round(minutes * 60000);
3203
+ console.log(`Searching with ${workers} process(es) for up to ${minutes} minute(s). About ${expectedAttempts(prefix, suffix).toLocaleString('en-US')} keys are needed on average.`);
3204
+ let finished = 0, won = false; const kids = [];
3205
+ const finish = (attempts) => { if (!won) { console.log(`Not found in time (${attempts.toLocaleString('en-US')} keys tried here). Try more minutes or a shorter pattern.`); process.exit(1); } };
3206
+ for (let i = 0; i < workers; i++) {
3207
+ const c = spawn(process.execPath, [process.argv[1], 'vanity-worker', prefix, suffix, String(ms)], { stdio: ['ignore', 'pipe', 'inherit'] }); kids.push(c);
3208
+ let out = ''; c.stdout.on('data', (d) => { out += d; });
3209
+ c.on('close', () => { finished++; if (won) return; let r = null; try { r = JSON.parse(out.trim().split('\n').pop()); } catch { /* worker failed */ }
3210
+ if (r?.priv) { won = true; kids.forEach((k) => k.kill()); const saved = saveCandidate(BigInt('0x' + r.priv));
3211
+ console.log(`Found: ${saved.address}\nKey stored privately at ${saved.file} (never printed).\nTo use it as your wallet: npx -y anthropos-mcp wallet use ${saved.address}`); process.exit(0); }
3212
+ if (finished === workers) finish(0); });
3213
+ }
3214
+ await new Promise(() => {}); // stay alive until a worker reports (process.exit above); never fall through to the stdio server
3215
+ }
3216
+ if (arg === 'wallet') {
3217
+ const sub = process.argv[3];
3218
+ if (sub === 'list') { const l = listCandidates(); console.log(l.length ? l.join('\n') : 'No saved vanity candidates. Create one with: npx -y anthropos-mcp vanity --suffix 7777'); process.exit(0); }
3219
+ if (sub === 'use') {
3220
+ const addr = process.argv[4];
3221
+ if (!/^0x[0-9a-fA-F]{40}$/.test(addr || '')) { console.error('Usage: anthropos-mcp wallet use <address> (see: anthropos-mcp wallet list)'); process.exit(1); }
3222
+ if (!process.stdin.isTTY || !process.stdout.isTTY) { console.error('Switching wallets needs an interactive terminal, so that a person confirms it. Run this command yourself.'); process.exit(1); }
3223
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
3224
+ const current = (() => { try { return loadWallet()?.address; } catch { return null; } })();
3225
+ console.log(`Switch the ANTHROPOS wallet to ${addr}?${current ? `\n Current wallet ${current} is kept as a backup file next to the new key.` : ''}`);
3226
+ const answer = (await rl.question('Type "use" to confirm: ')).trim(); rl.close();
3227
+ if (answer !== 'use') { console.log('Not changed.'); process.exit(1); }
3228
+ try { const r = useCandidate(addr); console.log(`Active wallet is now ${r.address}${r.backup ? `\nOld key saved as ${r.backup}` : ''}${process.env.ANTHROPOS_PRIVATE_KEY ? '\nWARNING: ANTHROPOS_PRIVATE_KEY is set in this environment and overrides the key file. Unset it to use the new wallet.' : ''}\nFund it with a small amount of BNB. Restart your MCP client.`); process.exit(0); }
3229
+ catch (e) { console.error(e.message); process.exit(1); }
3230
+ }
3231
+ console.error('Usage: anthropos-mcp wallet list | wallet use <address>'); process.exit(1);
3232
+ }
3233
+ if (arg === 'address') { try { const w = loadWallet(); if (!w) { console.error('No wallet. Run: npx -y anthropos-mcp init'); process.exit(1); } console.log(w.address); process.exit(0); } catch (e) { console.error(e.message); process.exit(1); } }
1418
3234
  if (arg === 'pending' || arg === 'approve') {
1419
3235
  const ledger = new Ledger(homeDir());
1420
3236
  if (arg === 'pending') { const list = ledger.listPending(); console.log(list.length ? list.map((p) => `${p.id} ${p.approved ? '[approved]' : '[waiting]'} ${p.plan.summary}`).join('\n') : 'Nothing is waiting.'); process.exit(0); }
1421
3237
  const id = process.argv[3]; const p = id && ledger.loadPending(id);
1422
3238
  if (!p) { console.error('No pending action with that id.'); process.exit(1); }
1423
3239
  if (!process.stdin.isTTY || !process.stdout.isTTY) { console.error('Approving needs an interactive terminal, so that a person reads and confirms it. Run this command yourself in a terminal.'); process.exit(1); }
1424
- console.log(`\nAction ${p.id}\n ${p.plan.summary}\n Value about $${Number(p.plan.usd ?? 0).toFixed(2)}\n Transactions:\n${p.plan.steps.map((s, i) => ` ${i + 1}. ${s.label}\n to ${s.to}`).join('\n')}\n`);
3240
+ console.log(`\nAction ${p.id}\n ${p.plan.summary}\n Value about $${Number(p.plan.usd ?? 0).toFixed(2)}\n Transactions:\n${p.plan.steps.map((s, i) => ` ${i + 1}. ${s.label}\n to ${s.to}${(() => { const v = s.value && typeof s.value === 'object' ? s.value.__bigint : s.value; return v && BigInt(v) > 0n ? `\n sends ${(Number(BigInt(v) / 10n ** 10n) / 1e8).toFixed(8)} BNB` : ''; })()}`).join('\n')}\n`);
1425
3241
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1426
3242
  const answer = (await rl.question('Type "approve" to allow this: ')).trim(); rl.close();
1427
3243
  if (answer !== 'approve') { console.log('Not approved.'); process.exit(1); }
@@ -1431,6 +3247,7 @@ if (arg === '--selftest') {
1431
3247
  try { const b = await bnbBalance(rpc, '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c'); console.log('OK rpc reachable; WBNB contract holds ' + b.balance_bnb + ' BNB'); process.exit(0); }
1432
3248
  catch (e) { console.error('FAIL ' + (e.message || e)); process.exit(1); }
1433
3249
  }
3250
+ if (arg) { console.error(`Unknown command "${arg}". Run: anthropos-mcp --help`); process.exit(1); } // never start the stdio server by accident from a typo
1434
3251
  let buf = ''; process.stdin.setEncoding('utf8');
1435
3252
  process.stdin.on('data', (c) => { buf += c; let i; while ((i = buf.indexOf('\n')) >= 0) { const l = buf.slice(0, i).trim(); buf = buf.slice(i + 1); if (l) handle(l).catch((e) => console.error(e)); } });
1436
3253
  process.stdin.on('end', () => setTimeout(() => process.exit(0), 50));