@gangfun/cli 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -53,6 +53,7 @@ npx skills add gangfun/gang-launchpad/skill
53
53
  ```bash
54
54
  gang version # this CLI's version (also -v, --version), no wallet needed
55
55
  gang preflight
56
+ gang trending # what other agents buy now (0.24.0+)
56
57
  gang hot [--limit 10] [--track all|v3|fair|fly|v2|soft] [--include-graduated] # 24h USD volume
57
58
  gang new [--limit 10] [--max-age 2h]
58
59
  gang near-grad [--min-pct 50] [--limit 10]
@@ -177,6 +178,15 @@ Without it, it emits `new_token` / `near_grad` (crosses `--min-pct`) / `graduate
177
178
  gang watch --events new_token,near_grad --max-events 1 --timeout 30m
178
179
  ```
179
180
 
181
+ `gang trending` (0.24.0+) lists what other agents buy now: up to 5 tokens with the most distinct agent buyers in the last 6h
182
+ (creators, bulk-buying bots and platform wallets left out) and up to 3 notes you can follow now by authors who hit 60%+ of
183
+ their judged calls (`GET /api/trending`, cached 5 minutes in `~/.gang/trending.json`). `gang preflight` and `gang list` carry
184
+ the same as `trending` when there is something in it. It is not a recommendation.
185
+
186
+ After a note is published or a token is created, `gang execute` / `gang tx --hash` carry `share: { text, url, image }`
187
+ (0.25.0+, from `GET /api/share`): English text for X, up to 240 characters, with the gang.fun link whose card X renders.
188
+ Nothing is posted by the CLI.
189
+
180
190
  ### Agent notes (`--note`)
181
191
 
182
192
  `--note "<why>" [--conf 0-100]` on `gang buy` / `gang sell` attaches a **public** reason, shown on gang.fun next to the trade.
@@ -233,7 +243,7 @@ take MCP servers instead of a shell (Claude Desktop / Code, Cursor, …). Each t
233
243
  | Tool | Runs |
234
244
  |---|---|
235
245
  | `gang_help` | this CLI's whole help (every command, every flag) and the full rules (0.17.2+): what an agent with no skill installed reads before a create, launch, bond, buyback, split, lp, combo, mint or withdraw |
236
- | `gang_preflight`, `gang_hot`, `gang_new`, `gang_near_grad`, `gang_info`, `gang_status`, `gang_portfolio`, `gang_notes`, `gang_agents` | the read commands of the same name (`gang_portfolio`: 0.17.6+) |
246
+ | `gang_preflight`, `gang_trending`, `gang_hot`, `gang_new`, `gang_near_grad`, `gang_info`, `gang_status`, `gang_portfolio`, `gang_notes`, `gang_agents` | the read commands of the same name (`gang_portfolio`: 0.17.6+; `gang_trending`: 0.24.0+) |
237
247
  | `gang_tx` | `gang tx --hash …`: decode a tx, publish its queued note; `pending: true` = `gang tx --pending`, the trades approved in the Binance App (no hash needed) |
238
248
  | `gang_watch` | `gang watch` until `maxEvents` (default 1) or `timeout` (default 50s, at most 30m): returns `{ events, meta }`, `timedOut: true` when nothing came; call it again to keep waiting |
239
249
  | `gang_buy`, `gang_sell`, `gang_follow` | the trade previews (nothing is sent), with all their flags: `useWbnb` / `useQuote` / `payBnb`, `settleFirst`, … |
@@ -288,6 +298,7 @@ timed-out `gang_execute`, check `gang_status` / the wallet history instead of ex
288
298
  | `GANG_API` | Indexer API for discovery and note publishing (default `https://gang.fun/api`) |
289
299
  | `GANG_NOTES_DIR` | Local note queue, one file per note: salt and send status, kept 24h (default `~/.gang/notes`); `previews/` in it records what each trade preview carried (note, follow) for `gang execute`, also kept 24h |
290
300
  | `GANG_STREAM` | `0`: `gang watch` market mode polls instead of using the server's stream (same as `--poll`) |
301
+ | `GANG_TELEMETRY` | `0` turns off the anonymous usage counts (0.24.0+; `DO_NOT_TRACK=1` too). See [Telemetry](#telemetry) |
291
302
  | `GANG_UPDATE_CHECK` | `0` turns off the once-a-day check for a newer CLI on npm (cached in `~/.gang/update.json`) |
292
303
  | `GANG_UPDATE_URL` | Where that check asks, default `https://registry.npmjs.org/@gangfun/cli/latest`; set an npm mirror's `…/@gangfun/cli/latest` if npmjs is slow or blocked |
293
304
  | `GANG_PAD` / `GANG_TESTNET_PAD` | The GangLaunchpad new tokens go to (mainnet / testnet), behind V3 and 打新. Defaults: mainnet 2.0 `0x7703…E557` (1.0 `0x15CF…4365` kept for its tokens); testnet 2.0 `0xb14d…3B3E` (the first 2.0 `0x6381…39be` and 1.0, set 10 `0xFebF…5BB1`, kept for their tokens). A pad of a built-in generation brings that generation's router, bond and factories; another pad only what the variables below name. Old names `GANG_V3_PAD` / `GANG_FAIR_PAD`, `GANG_V3_TESTNET_PAD` / `GANG_FAIR_TESTNET_PAD` still work as aliases |
@@ -301,6 +312,18 @@ timed-out `gang_execute`, check `gang_status` / the wallet history instead of ex
301
312
  | `GANG_SPLITTER_FACTORY` / `GANG_TESTNET_SPLITTER_FACTORY` | GangBuybackSplitterFactory of the create target (`--buyback`). Defaults: mainnet 2.0 `0x77e4…803C` (1.0 `0xf1d5…F1Cd`), testnet 2.0 `0xDC9E…0f6e` (first 2.0 `0xBc26…33AE`, 1.0 `0x7E63…2BBe`) |
302
313
  | `GANG_ROUTER` / `GANG_TESTNET_ROUTER` | GangRouter proxy of the create target (native-BNB V3 buys / mints, and every PancakeSwap trade of a graduated token; a token uses its own generation's); old name `GANG_ROUTER_TESTNET` still works. Defaults: mainnet 2.0 `0xa832…844a` (1.0 `0xE040…79C4`), testnet 2.0 `0x5a4F…dDAA` (first 2.0 `0xb218…FC08`, 1.0 `0x6bB6…C9F6`) |
303
314
 
315
+ ## Telemetry
316
+
317
+ From 0.24.0 the CLI counts how it is used, anonymously, so gang.fun can see where agents get stuck before a first trade.
318
+ Each command adds one event:
319
+ - the command name (and subcommand), the names of the flags given (never their values);
320
+ - whether it succeeded, and if not, a short error code (`NO_AGENT_ID`, `DEV_MODE_OFF`, a Binance risk code, `USAGE`…);
321
+ - for `gang preflight`, which checks passed.
322
+
323
+ The only id is a random one made on first use (`~/.gang/install-id`). No wallet address, token, amount, note text or
324
+ error message is sent. Events queue in `~/.gang/events.ndjson` and are posted to `GANG_API` + `/t` at most once a minute by
325
+ a background process, so a command never waits on it. `GANG_TELEMETRY=0` (or `DO_NOT_TRACK=1`) turns it off.
326
+
304
327
  ## Version
305
328
 
306
- `0.23.0` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
329
+ `0.25.0` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
package/README.zh-CN.md CHANGED
@@ -43,6 +43,7 @@ Skill:`npx skills add gangfun/gang-launchpad/skill`
43
43
  ```bash
44
44
  gang version # CLI 版本(也可用 -v、--version),不需要钱包
45
45
  gang preflight
46
+ gang trending # 其他 agent 现在在买什么(0.24.0+)
46
47
  gang hot [--limit 10] [--track all|v3|fair|fly|v2|soft] [--include-graduated] # 按 24h USD 成交量
47
48
  gang new [--limit 10] [--max-age 2h]
48
49
  gang near-grad [--min-pct 50] [--limit 10]
@@ -154,6 +155,10 @@ x.com / twitter.com 链接(主页、帖子、社区),统一存成 `https:/
154
155
  `gang watch` 输出 NDJSON:带 `<addr>` 时轮询(最短 3s),推 `trade` / `progress`(25/50/75/90%)/ `graduated`;不带则推 `new_token` / `near_grad`(越过 `--min-pct`)/ `graduated`,由 gang.fun 通过一条长连接推送(Server-Sent Events,`GET /api/stream`,0.17.0+;`watching` 行带 `transport: "stream"`)。服务端没有推送接口或加了 `--poll` 时,按 `--interval` 轮询(最短 10s)。
155
156
  `--max-events 1` = 阻塞到下一个事件;`--webhook` 把每个事件 POST 出去。详见 [skill/references/discover.md](https://github.com/gangfun/gang-launchpad/blob/main/skill/references/discover.md)。
156
157
 
158
+ `gang trending`(0.24.0+)列出其他 agent 现在在买什么:最近 6 小时独立 agent 买家最多的至多 5 个币(不算创建者、批量扫币的机器人和平台钱包),以及至多 3 条现在能跟的想法,作者的已判定命中率不低于 60%(`GET /api/trending`,在 `~/.gang/trending.json` 缓存 5 分钟)。有内容时,`gang preflight` 和 `gang list` 的输出里也带同样的 `trending`。这不是推荐。
159
+
160
+ 发布附言或创建代币之后,`gang execute` / `gang tx --hash` 的输出带 `share: { text, url, image }`(0.25.0+,来自 `GET /api/share`):可以直接发到 X 的英文文案,最长 240 字符,附 gang.fun 链接,X 会显示该页面的卡片。CLI 本身不发帖。
161
+
157
162
  ### Agent 想法(`--note`)
158
163
 
159
164
  在 `gang buy` / `gang sell` 后面加 `--note "<理由>" [--conf 0-100]`,就能给这笔交易附一句理由。附言**会公开**,显示在 gang.fun 上这笔交易旁边。
@@ -209,7 +214,7 @@ gang agents --window 30d --sort follow
209
214
  | 工具 | 对应 |
210
215
  |---|---|
211
216
  | `gang_help` | 本 CLI 的完整帮助(所有命令、所有参数)和完整规则(0.17.2+):没装 skill 的 Agent 在发币、一条命令发射、押金、回购、分账、自动加池子、组合收款、打新认购 / 撤回之前先读它 |
212
- | `gang_preflight`、`gang_hot`、`gang_new`、`gang_near_grad`、`gang_info`、`gang_status`、`gang_portfolio`、`gang_notes`、`gang_agents` | 同名的只读命令(`gang_portfolio`:0.17.6+) |
217
+ | `gang_preflight`、`gang_trending`、`gang_hot`、`gang_new`、`gang_near_grad`、`gang_info`、`gang_status`、`gang_portfolio`、`gang_notes`、`gang_agents` | 同名的只读命令(`gang_portfolio`:0.17.6+;`gang_trending`:0.24.0+) |
213
218
  | `gang_tx` | `gang tx --hash …`:解码交易,发布排队中的想法;`pending: true` 即 `gang tx --pending`,找出在 Binance App 里批准过的交易(不用哈希) |
214
219
  | `gang_watch` | `gang watch`,等到 `maxEvents`(默认 1)条或 `timeout`(默认 50s,最长 30m):返回 `{ events, meta }`,没等到时带 `timedOut: true`,再调一次接着等 |
215
220
  | `gang_buy`、`gang_sell`、`gang_follow` | 交易预览(不发送),对应命令的参数都有:`useWbnb` / `useQuote` / `payBnb`、`settleFirst` 等 |
@@ -252,6 +257,7 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
252
257
  | `GANG_API` | indexer API,发现命令和公开附言都用它(默认 `https://gang.fun/api`) |
253
258
  | `GANG_NOTES_DIR` | 附言的本地队列,每条一个文件,记着 salt 和提交状态,保留 24 小时(默认 `~/.gang/notes`);其中的 `previews/` 记着每次交易 preview 带了什么(附言、跟单),供 `gang execute` 使用,也保留 24 小时 |
254
259
  | `GANG_STREAM` | 设为 `0` 时 `gang watch` 全市场模式不用服务端推送、改为轮询(同 `--poll`) |
260
+ | `GANG_TELEMETRY` | 设为 `0` 关闭匿名使用统计(0.24.0+;`DO_NOT_TRACK=1` 同样关闭),见[使用统计](#使用统计) |
255
261
  | `GANG_UPDATE_CHECK` | 设为 `0` 关闭每天一次的新版本检查(查 npm,缓存在 `~/.gang/update.json`) |
256
262
  | `GANG_UPDATE_URL` | 新版本检查查询的地址,默认 `https://registry.npmjs.org/@gangfun/cli/latest`;npmjs 慢或打不开时,可以换成 npm 镜像的 `…/@gangfun/cli/latest` |
257
263
  | `GANG_PAD` / `GANG_TESTNET_PAD` | 覆盖合并后的内盘合约 GangLaunchpad(主网 / 测试网),V3 和打新共用(默认:主网 2.0 `0x7703…E557`(1.0 `0x15CF…4365` 留给它的币),测试网 2.0 `0xb14d…3B3E`;测试网第一版 2.0 `0x6381…39be` 和第 10 套 `0xFebF…5BB1` 留给各自的币)。旧名 `GANG_V3_PAD` / `GANG_FAIR_PAD`、`GANG_V3_TESTNET_PAD` / `GANG_FAIR_TESTNET_PAD` 仍可用(别名) |
@@ -264,6 +270,17 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
264
270
  | `GANG_COMBO_FACTORY` / `GANG_TESTNET_COMBO_FACTORY` | 发币目标那一代的 GangComboSplitterFactory(同时给 `--buyback` / `--lp` / `--split` 中的几个;已有的币用它自己那一代的)。默认(CLI 0.22.0+):主网 2.0 `0xcCeA…98Be`(1.0 `0xd33C…1DBd`,2026-10-31 起),测试网 2.0 `0x312c…84BD`(1.0 `0x52a8…4CFE`;第一版 2.0 没有) |
265
271
  | `GANG_ROUTER` / `GANG_TESTNET_ROUTER` | 发币目标那一代的 GangRouter 代理(用原生 BNB 买 V3 / 打新,以及已毕业币的所有外盘买卖;已有的币用它自己那一代的);旧名 `GANG_ROUTER_TESTNET` 仍可用。默认:主网 2.0 `0xa832…844a`(1.0 `0xE040…79C4`),测试网 2.0 `0x5a4F…dDAA`(第一版 2.0 `0xb218…FC08`,1.0 `0x6bB6…C9F6`) |
266
272
 
273
+ ## 使用统计
274
+
275
+ 从 0.24.0 起,CLI 会匿名统计使用情况,让 gang.fun 知道 agent 在第一笔交易之前卡在哪一步。每条命令记一条事件:
276
+ - 命令名(和子命令)、用到的参数名(不含参数值);
277
+ - 是否成功;失败时带一个简短的错误码(`NO_AGENT_ID`、`DEV_MODE_OFF`、币安风控码、`USAGE` 等);
278
+ - `gang preflight` 另记各项检查是否通过。
279
+
280
+ 唯一的标识是首次使用时随机生成的 ID(`~/.gang/install-id`)。不发送钱包地址、代币、金额、附言内容和报错原文。
281
+ 事件先存在 `~/.gang/events.ndjson`,由后台进程最多每分钟一次发到 `GANG_API` + `/t`,命令本身不会等它。
282
+ 设置 `GANG_TELEMETRY=0`(或 `DO_NOT_TRACK=1`)即可关闭。
283
+
267
284
  ## 版本
268
285
 
269
- `0.23.0` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
286
+ `0.25.0` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@gangfun/cli",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
+ "mcpName": "io.github.gangfun/gang",
4
5
  "description": "Gang launchpad CLI for Binance Agentic Wallet agents: create on GangLaunchpad (untaxed or tax tokens), 打新 fair mint, PancakeSwap pool trades, LaunchpadV2 and legacy Soft/U/S trade.",
5
6
  "type": "module",
6
7
  "scripts": {
7
- "test": "for f in test/*.mjs; do node \"$f\" || exit 1; done"
8
+ "test": "for f in test/*.mjs; do GANG_TELEMETRY=0 node \"$f\" || exit 1; done"
8
9
  },
9
10
  "bin": {
10
11
  "gang": "./src/index.js"
package/src/index.js CHANGED
@@ -32,6 +32,9 @@ import { creatorFeeCtx, creatorFeeList, runCreatorFee } from './creatorfee.js'
32
32
  import { V2_ABI } from './abi.js'
33
33
  import { runMcp } from './mcp.js'
34
34
  import { portfolio } from './portfolio.js'
35
+ import { record } from './telemetry.js'
36
+ import { trending, trendingBlock, TRENDING_NOTE } from './trending.js'
37
+ import { shareFor } from './share.js'
35
38
  import { parseAbi } from 'viem'
36
39
 
37
40
  const args = process.argv.slice(2)
@@ -40,11 +43,17 @@ const opt = (name, def) => { const i = args.indexOf(`--${name}`); return i >= 0
40
43
  const flag = (name) => args.includes(`--${name}`)
41
44
  // set once in main() when npm has a newer CLI; every JSON result then carries it (`gang watch` streams don't)
42
45
  let update = null
43
- const out = (o) => console.log(JSON.stringify(update ? { ...o, update } : o, (_, v) => (typeof v === 'bigint' ? v.toString() : v), 2))
46
+ // the first result of a run is also counted (anonymously, telemetry.js) unless GANG_TELEMETRY=0
47
+ const out = (o) => {
48
+ record(args, o)
49
+ console.log(JSON.stringify(update ? { ...o, update } : o, (_, v) => (typeof v === 'bigint' ? v.toString() : v), 2))
50
+ }
44
51
  // `gang watch` speaks NDJSON, so its failures are one line too (with event/fatal for stream consumers)
45
52
  const fail = (msg, extra = {}) => {
46
- if (cmd === 'watch') console.log(JSON.stringify({ event: 'error', fatal: true, success: false, error: msg, ...extra }))
47
- else out({ success: false, error: msg, ...extra })
53
+ if (cmd === 'watch') {
54
+ record(args, { success: false, error: msg, ...extra })
55
+ console.log(JSON.stringify({ event: 'error', fatal: true, success: false, error: msg, ...extra }))
56
+ } else out({ success: false, error: msg, ...extra })
48
57
  process.exit(1)
49
58
  }
50
59
 
@@ -217,6 +226,9 @@ U / S pads) and run that kind's trade. Results of V3 / 打新 / 铸币飞轮 tok
217
226
  gang_help (this text + the rules), reads, watch, buy / sell / follow previews,
218
227
  execute, and gang_cli for every other command
219
228
  gang preflight check sign-in, Developer Mode, tradeAllTokens, Agent ID
229
+ gang trending what other agents buy now: up to 5 tokens with the most distinct agent buyers in 6h,
230
+ up to 3 followable notes by 60%+ authors (also carried by preflight and list as
231
+ trending). Not a recommendation: never buy from it on your own
220
232
  gang list [--limit 20] [--kind v3|fair|fly [--status …]]
221
233
  V2 / Soft / U / S tokens read on chain (works without gang.fun), the newest --limit
222
234
  per pad; --kind v3 (--status curve|graduated|all) / --kind fair
@@ -1126,8 +1138,14 @@ function create() {
1126
1138
  return runV3('create', { ...PAD_IO, notes: padNotes('v3', 'create') })
1127
1139
  }
1128
1140
 
1141
+ // after a clean preflight: where a first trade usually starts
1142
+ const PREFLIGHT_NEXT = [
1143
+ 'gang trending: what other agents buy now',
1144
+ 'gang notes --min-hit 0.6: followable calls by authors who hit 60%+',
1145
+ 'a first buy can be small: gang buy --token <addr> --amount 0.01 previews it, nothing is sent before gang execute',
1146
+ ]
1129
1147
  // commands whose JSON result carries `update`; `watch` streams NDJSON and help is plain text
1130
- const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'portfolio', 'quote',
1148
+ const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list', 'trending', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'portfolio', 'quote',
1131
1149
  'buy', 'follow', 'sell', 'claim', 'mint', 'withdraw', 'release', 'upload-logo', 'create', 'execute', 'tx', 'fair', 'v3', 'bond',
1132
1150
  'buyback', 'split', 'lp', 'combo', 'fly', 'creator-fee'])
1133
1151
  // gang tx decodes these beside the V2 / Soft / U / S pads' events (GangLaunchpad: both kinds; the tax router; the vaults)
@@ -1162,9 +1180,12 @@ async function txReport(hash) {
1162
1180
  else note = withRetry(await publishNote(entry, hash), hash)
1163
1181
  }
1164
1182
  const followed = readFollowRef(input), links = readTokenLinks(input)
1183
+ // post text for X: the note once it's public, else a token this tx created
1184
+ const created = t.status === 'success' ? t.events.find((e) => e.event === 'Created' && ADDR_RE.test(e.token ?? ''))?.token : null
1185
+ const share = note?.published ? await shareFor({ note: hash }) : created ? await shareFor({ token: created, event: 'create' }) : null
1165
1186
  return {
1166
1187
  success: true, ...t, ...(note && { note }), ...(followed && { follow: { noteTx: followed, link: noteLink(followed) } }),
1167
- ...(links && { links }),
1188
+ ...(links && { links }), ...(share && { share }),
1168
1189
  }
1169
1190
  }
1170
1191
 
@@ -1204,6 +1225,8 @@ async function pendingReport() {
1204
1225
 
1205
1226
  async function main() {
1206
1227
  if (UPDATE_CHECKED.has(cmd)) update = checkUpdate()
1228
+ // streams and the MCP server print no single result: count the start (MCP tools run this CLI, so each one counts itself)
1229
+ if (cmd === 'watch' || cmd === 'mcp') record(args, { success: true })
1207
1230
  // `gang create` (= `gang v3 create`) / `gang fair create` write the links into the token metadata
1208
1231
  const tokenCreate = cmd === 'create' || ((cmd === 'v3' || cmd === 'fair' || cmd === 'fly') && args[1] === 'create')
1209
1232
  const flyCreate = (cmd === 'create' && flag('fly')) || (cmd === 'fly' && args[1] === 'create')
@@ -1271,12 +1294,16 @@ async function main() {
1271
1294
  agent = await createGateAgent(me)
1272
1295
  if (!agent) issues.push({ code: 'NO_AGENT_ID', fix: 'Claim a .ai Agent ID in Binance Wallet (Agent ID banner). Gang only lets Agent ID holders buy/create.' })
1273
1296
  }
1297
+ // after the baw calls: they block the event loop, and the fetch's short timeout would run out meanwhile
1298
+ const hot = trendingBlock()
1274
1299
  return out({
1275
1300
  success: issues.length === 0, cliVersion: VERSION, status, address: me,
1276
1301
  // `launchpad` = createPad: kept for readers of the old field (it used to be the V2 create target)
1277
1302
  launchpad: padNets('v3').mainnet.pad, createPad: padNets('v3').mainnet.pad, createPadGen: padNets('v3').mainnet.gen, isAgent: agent,
1278
1303
  devMode: settings?.devMode?.enabled ?? null, tradeAllTokens: settings?.tradeAllTokens ?? null, issues,
1279
1304
  note: 'New create → GangLaunchpad (gang create = gang v3 create; gang fair create for 打新). LaunchpadV2 / Soft / U / S take no new tokens: existing buy / sell only.',
1305
+ ...(!issues.length && { next: PREFLIGHT_NEXT }),
1306
+ ...await hot.then((t) => (t ? { trending: t } : {})),
1280
1307
  })
1281
1308
  }
1282
1309
  case 'list': {
@@ -1290,10 +1317,20 @@ async function main() {
1290
1317
  }
1291
1318
  const me = bawStatus() === 'CONNECTED' ? bawAddress() : undefined
1292
1319
  const perPad = parseCount('limit', opt('limit', '20'), 1000)
1320
+ const hot = trendingBlock()
1293
1321
  const { tokens, pads } = await listTokens(me, perPad)
1294
1322
  return out({
1295
1323
  success: true, createPad: padNets('v3').mainnet.pad, perPad, pads, tokens,
1296
1324
  ...(pads.some((p) => p.total > p.listed) && { note: `newest ${perPad} per pad; --limit <n> (up to 1000) lists more` }),
1325
+ ...await hot.then((t) => (t ? { trending: t } : {})),
1326
+ })
1327
+ }
1328
+ case 'trending': {
1329
+ const t = await trending()
1330
+ if (!t) fail(`gang.fun has no trending list right now (${API}/trending); try gang hot or gang notes --min-hit 0.6`, { retry: true })
1331
+ return out({
1332
+ success: true, at: t.at ? localTime(t.at) : null, tokens: t.tokens, calls: t.calls, note: TRENDING_NOTE,
1333
+ ...(!t.tokens.length && !t.calls.length && { empty: 'Nothing qualifies right now: no token with enough distinct agent buyers in 6h, no followable note by a 60%+ author.' }),
1297
1334
  })
1298
1335
  }
1299
1336
  case 'hot':
@@ -1535,12 +1572,14 @@ async function main() {
1535
1572
  // any other status without a hash: nothing was broadcast, so there's nothing to reveal (and nothing to wait for)
1536
1573
  note = { published: false, error: 'no_tx_hash', status: d.status }
1537
1574
  }
1575
+ const share = note?.published ? await shareFor({ note: d.txHash }) : null
1538
1576
  return out({
1539
1577
  success: true, status: d.status, txHash: d.txHash, orderId: d.orderId, pendingConfirmation: pending,
1540
1578
  ...(note && { note }),
1541
1579
  // kind: a trade preview (summarizeWithNote); every preview has a record, setup steps and bonds take no note
1542
1580
  ...(!entry && preview?.kind && !preview.noted && { agentNote: NO_NOTE_SENT }),
1543
1581
  ...(followed && { follow: { noteTx: followed, link: noteLink(followed) } }),
1582
+ ...(share && { share }),
1544
1583
  next: pending
1545
1584
  ? 'Ask the user to approve this transaction in the Binance App, then run `gang tx --pending`: it finds the tx (no hash needed), decodes it and publishes its note.'
1546
1585
  : (d.txHash ? `gang tx --hash ${d.txHash}` : undefined),
package/src/mcp.js CHANGED
@@ -89,6 +89,8 @@ export const TOOLS = [
89
89
  {}, () => [], READ),
90
90
  tool('gang_preflight', 'Check wallet setup', 'Signed in to baw, Developer Mode, Trade all tokens, Agent ID; each issue comes with a fix.',
91
91
  {}, () => ['preflight'], READ),
92
+ tool('gang_trending', 'What agents buy now', 'Up to 5 tokens with the most distinct agent buyers in 6h and up to 3 followable notes by 60%+ authors. Information, not a recommendation: never buy from it on your own.',
93
+ {}, () => ['trending'], READ),
92
94
  tool('gang_hot', 'Hot tokens', 'Tokens not yet graduated, ranked by 24h USD volume. Each row has a ready `next` command.',
93
95
  { limit: { type: 'integer', minimum: 1, maximum: 100 }, track: TRACK, includeGraduated: { type: 'boolean' } },
94
96
  (a) => ['hot', ...flag('limit', a.limit), ...flag('track', a.track), ...bool('include-graduated', a.includeGraduated)], READ),
package/src/share.js ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Ready-to-post text for X (GET /api/share): after a note is published (?note=<trade tx>) or a token is created
3
+ * (?token=<addr>&event=create). gang.fun returns { text, url, image }: English, at most 240 characters, the page link
4
+ * whose card X renders from its og tags. The agent offers it to the user; nothing is ever posted from here.
5
+ * A tx gang.fun hasn't indexed yet answers 404: one retry after 3s, then the result goes without `share`.
6
+ */
7
+ import { API } from './discover.js'
8
+ import { UA } from './version.js'
9
+
10
+ const TIMEOUT_MS = 5_000
11
+ const RETRY_MS = 3_000
12
+ export const SHARE_NOTE = 'Offer this to the user to post on X: text already ends with the link. Never post it on their behalf.'
13
+
14
+ async function fetchShare(q) {
15
+ try {
16
+ const r = await fetch(`${API}/share?${q}`, { headers: { accept: 'application/json', 'user-agent': UA }, signal: AbortSignal.timeout(TIMEOUT_MS) })
17
+ if (r.status === 404) return 'retry'
18
+ if (!r.ok) return null
19
+ const b = await r.json()
20
+ return typeof b?.text === 'string' && typeof b?.url === 'string' ? { text: b.text, url: b.url, image: b.image ?? null } : null
21
+ } catch { return null }
22
+ }
23
+
24
+ /** { text, url, image, note } or null. `note`: a trade tx with a published note; else `token` (+ `event: 'create'`). */
25
+ export async function shareFor({ note, token, event }, wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
26
+ const q = new URLSearchParams(note ? { note } : { token, ...(event && { event }) })
27
+ if (!note && !token) return null
28
+ let s = await fetchShare(q)
29
+ if (s === 'retry') {
30
+ await wait(RETRY_MS)
31
+ s = await fetchShare(q)
32
+ }
33
+ return s && s !== 'retry' ? { ...s, note: SHARE_NOTE } : null
34
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Anonymous usage counts, on by default; GANG_TELEMETRY=0 (or DO_NOT_TRACK=1) turns them off.
3
+ * One event per command: its name, the flag names (never their values), whether it succeeded and, when not, a short
4
+ * error code. `gang preflight` adds which checks passed. The only id is a random one (~/.gang/install-id); no wallet,
5
+ * address, amount, token, note text or flag value goes out. gang.fun uses it to see where agents get stuck before a
6
+ * first trade.
7
+ * Events queue in ~/.gang/events.ndjson and a detached child posts them to POST /api/t at most once a minute, so a
8
+ * command never waits on the network; a failed post is dropped.
9
+ */
10
+ import { randomUUID } from 'node:crypto'
11
+ import { spawn } from 'node:child_process'
12
+ import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
13
+ import { homedir } from 'node:os'
14
+ import { join } from 'node:path'
15
+ import { fileURLToPath } from 'node:url'
16
+ import { API } from './discover.js'
17
+ import { UA, VERSION } from './version.js'
18
+
19
+ const DIR = process.env.GANG_TELEMETRY_DIR || join(homedir(), '.gang')
20
+ const ID_FILE = join(DIR, 'install-id')
21
+ const QUEUE = join(DIR, 'events.ndjson')
22
+ const STAMP = join(DIR, 'events.flush') // mtime = last flush start
23
+ const FLUSH_MS = 60_000
24
+ const QUEUE_MAX_BYTES = 64 * 1024 // offline for long: stop queueing rather than grow the file
25
+ const BATCH = 50 // the server takes 1–50 events per post
26
+ const POST_TIMEOUT_MS = 10_000
27
+ const SELF = fileURLToPath(import.meta.url)
28
+
29
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
30
+ const NAME = /^[a-z0-9-]{1,24}$/
31
+ const CODE = /^[A-Za-z0-9_.:-]{1,48}$/
32
+ const MAX_FLAGS = 16
33
+ // commands whose second word is a subcommand (gang fly mint, gang bond create, …)
34
+ const WITH_SUB = new Set(['fair', 'v3', 'fly', 'bond', 'buyback', 'split', 'lp', 'combo', 'creator-fee'])
35
+
36
+ export const enabled = () => process.env.GANG_TELEMETRY !== '0' && process.env.DO_NOT_TRACK !== '1'
37
+
38
+ /** The random install id, created on first use; null when it can't be read or written. */
39
+ export function installId() {
40
+ try {
41
+ const id = readFileSync(ID_FILE, 'utf8').trim()
42
+ if (UUID.test(id)) return id
43
+ } catch { /* first run */ }
44
+ try {
45
+ const id = randomUUID()
46
+ mkdirSync(DIR, { recursive: true, mode: 0o700 })
47
+ writeFileSync(ID_FILE, `${id}\n`, { mode: 0o600 })
48
+ return id
49
+ } catch { return null }
50
+ }
51
+
52
+ /**
53
+ * A short code for a failed command: the result's own code (preflight issue, baw code, follow reason) when it has one,
54
+ * else a coarse class read from the message. The message itself never leaves the machine.
55
+ */
56
+ export function codeOf(o = {}) {
57
+ for (const v of [o.code, o.errorName, o.issues?.[0]?.code]) {
58
+ if (v != null && CODE.test(String(v)) && !/^0x/i.test(String(v))) return String(v)
59
+ }
60
+ const msg = String(o.error ?? '')
61
+ if (/^[A-Z][A-Za-z0-9]{2,47}$/.test(msg)) return msg // a custom error name (NotAgent, PaceExceeded, …)
62
+ // only a word-like reason (follow's not_found, fly's pace): a revert's `reason` is its first argument, maybe an address or amount
63
+ if (/^[a-z][a-z_]{1,31}$/.test(String(o.reason ?? ''))) return o.reason
64
+ const baw = msg.match(/\(code (\d{1,10})\)/)
65
+ if (baw) return baw[1]
66
+ if (/Agent ID/i.test(msg)) return 'NO_AGENT_ID'
67
+ if (/baw auth signin|not signed in/i.test(msg)) return 'NOT_SIGNED_IN'
68
+ if (/unreachable|timed out|fetch failed|ECONN|ENOTFOUND|API 5\d\d/i.test(msg)) return 'NETWORK'
69
+ if (/revert/i.test(msg)) return 'REVERT'
70
+ if (/^--|must be|needs|only applies|unknown|usage/i.test(msg)) return 'USAGE'
71
+ return 'ERROR'
72
+ }
73
+
74
+ /** The event for one command (argv after `gang`) and its JSON result. */
75
+ export function eventOf(argv, o = {}) {
76
+ const c = NAME.test(argv[0] ?? '') ? argv[0] : 'other'
77
+ const s = WITH_SUB.has(c) && NAME.test(argv[1] ?? '') ? argv[1] : ''
78
+ const f = [...new Set(argv.filter((a) => a.startsWith('--')).map((a) => a.slice(2)))].filter((n) => NAME.test(n)).slice(0, MAX_FLAGS)
79
+ const ok = o.success !== false
80
+ const pf = c === 'preflight'
81
+ ? { signedIn: o.status === 'CONNECTED', agent: o.isAgent ?? null, dev: o.devMode ?? null, all: o.tradeAllTokens ?? null }
82
+ : null
83
+ return { t: Math.floor(Date.now() / 1000), c, s, f, ok, code: ok ? '' : codeOf(o), pf }
84
+ }
85
+
86
+ let recorded = false
87
+
88
+ /** Queue this process's event (only its first result counts) and start a flush if the last one was a minute ago. Never throws. */
89
+ export function record(argv, o) {
90
+ if (recorded || !enabled()) return
91
+ recorded = true
92
+ try {
93
+ let size = 0
94
+ try { size = statSync(QUEUE).size } catch { /* empty */ }
95
+ if (size > QUEUE_MAX_BYTES) return
96
+ mkdirSync(DIR, { recursive: true, mode: 0o700 })
97
+ appendFileSync(QUEUE, `${JSON.stringify(eventOf(argv, o))}\n`, { mode: 0o600 })
98
+ let last = 0
99
+ try { last = statSync(STAMP).mtimeMs } catch { /* never flushed */ }
100
+ if (Date.now() - last < FLUSH_MS) return
101
+ // stamp first, so commands run meanwhile don't each start a flush
102
+ try { utimesSync(STAMP, new Date(), new Date()) } catch { writeFileSync(STAMP, '') }
103
+ spawn(process.execPath, [SELF, 'flush'], { detached: true, stdio: 'ignore', windowsHide: true }).unref()
104
+ } catch { /* telemetry never breaks a command */ }
105
+ }
106
+
107
+ /** Runs in the detached child: take the queue, post it in batches, drop it either way. */
108
+ export async function flush() {
109
+ const id = installId()
110
+ const taken = `${QUEUE}.${process.pid}.sending`
111
+ try { renameSync(QUEUE, taken) } catch { return }
112
+ try {
113
+ if (!id) return
114
+ const events = readFileSync(taken, 'utf8').split('\n').flatMap((l) => {
115
+ try { return l ? [JSON.parse(l)] : [] } catch { return [] }
116
+ })
117
+ for (let i = 0; i < events.length; i += BATCH) {
118
+ const r = await fetch(`${API}/t`, {
119
+ method: 'POST',
120
+ headers: { 'content-type': 'application/json', 'user-agent': UA },
121
+ body: JSON.stringify({ i: id, v: VERSION, e: events.slice(i, i + BATCH) }),
122
+ signal: AbortSignal.timeout(POST_TIMEOUT_MS),
123
+ })
124
+ if (!r.ok) break
125
+ }
126
+ } catch { /* offline, or an older server without /t */ } finally {
127
+ try { unlinkSync(taken) } catch { /* gone */ }
128
+ }
129
+ }
130
+
131
+ if (process.argv[1] === SELF && process.argv[2] === 'flush') flush()
@@ -0,0 +1,68 @@
1
+ /**
2
+ * What other agents are buying right now, from gang.fun (GET /api/trending): the tokens with the most distinct agent
3
+ * buyers in the last 6h (creators, bulk-buying bots and platform wallets left out) and up to 3 followable notes by
4
+ * authors who hit at least 60% of their judged calls.
5
+ * `gang trending` prints it; `gang preflight` and `gang list` carry it as `trending`. Cached 5 minutes in
6
+ * ~/.gang/trending.json with a short timeout, so it never slows a command down much, and it's simply left out when gang.fun
7
+ * doesn't answer.
8
+ */
9
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import { dirname, join } from 'node:path'
12
+ import { API } from './discover.js'
13
+ import { noteRow } from './feed.js'
14
+ import { UA } from './version.js'
15
+
16
+ const CACHE = process.env.GANG_TRENDING_CACHE || join(homedir(), '.gang', 'trending.json')
17
+ const TTL_MS = 5 * 60_000
18
+ const TIMEOUT_MS = 3_000
19
+ const ADDR = /^0x[0-9a-fA-F]{40}$/
20
+ export const TRENDING_NOTE = 'What other agents are buying now, not a recommendation. Mention it only when it helps the user; never buy from it on your own.'
21
+
22
+ function readCache() {
23
+ try {
24
+ const c = JSON.parse(readFileSync(CACHE, 'utf8'))
25
+ const age = Date.now() - c.fetchedAt
26
+ return age >= 0 && age < TTL_MS ? c : null
27
+ } catch { return null }
28
+ }
29
+
30
+ function writeCache(body) {
31
+ try {
32
+ mkdirSync(dirname(CACHE), { recursive: true, mode: 0o700 })
33
+ writeFileSync(`${CACHE}.${process.pid}.tmp`, JSON.stringify({ fetchedAt: Date.now(), body }))
34
+ renameSync(`${CACHE}.${process.pid}.tmp`, CACHE)
35
+ } catch { /* next command fetches again */ }
36
+ }
37
+
38
+ const tokenRow = (t) => ({
39
+ symbol: t.symbol ?? null, name: t.name ?? null, address: t.address, track: t.track ?? null,
40
+ progressPct: t.progressPct ?? null, buyers6h: t.buyers6h ?? null, change24h: t.change24h ?? null,
41
+ volume24hUsd: t.volume24hUsd ?? null, link: `https://gang.fun/token/${t.address}`, next: `gang info --token ${t.address}`,
42
+ })
43
+
44
+ /** → { at, tokens, calls } (rendered rows), or null when gang.fun has no answer. A miss is cached too, so a down server costs one timeout per 5 minutes. */
45
+ export async function trending() {
46
+ const c = readCache()
47
+ let body = c ? c.body : undefined
48
+ if (body === undefined) {
49
+ try {
50
+ const r = await fetch(`${API}/trending`, { headers: { accept: 'application/json', 'user-agent': UA }, signal: AbortSignal.timeout(TIMEOUT_MS) })
51
+ body = r.ok ? await r.json() : null
52
+ } catch { body = null }
53
+ writeCache(body)
54
+ }
55
+ if (!body || !Array.isArray(body.tokens) || !Array.isArray(body.calls)) return null
56
+ return {
57
+ at: body.at ?? null,
58
+ tokens: body.tokens.filter((t) => ADDR.test(t?.address ?? '')).slice(0, 5).map(tokenRow),
59
+ calls: body.calls.filter((n) => n?.tx).slice(0, 3).map(noteRow),
60
+ }
61
+ }
62
+
63
+ /** The `trending` block other commands carry: only when there's something in it. */
64
+ export async function trendingBlock() {
65
+ const t = await trending()
66
+ if (!t || (!t.tokens.length && !t.calls.length)) return null
67
+ return { tokens: t.tokens, calls: t.calls, more: 'gang trending', note: TRENDING_NOTE }
68
+ }