@gangfun/cli 0.25.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -148,7 +148,9 @@ Website, X link and description (optional): `--website mycoin.xyz --twitter @myc
148
148
  handle or an x.com / twitter.com link (profile, post, community) and stores it as `https://x.com/…`; `--website` takes an
149
149
  http(s) link (`mycoin.xyz` becomes `https://mycoin.xyz/`; no IP address or port). They go into the token's metadata JSON,
150
150
  uploaded to gang.fun and fixed on-chain as its `contractURI()` / `metaURI()`; like `logoURI` they can't be changed after
151
- the launch. The preview shows `metaURI` and the uploaded `metadata`.
151
+ the launch. The preview shows `metaURI` and the uploaded `metadata`. A create refuses any flag it doesn't take (`--x`,
152
+ `--website-url`, `--website=…`) and names the right one, before anything is uploaded or sent: a misspelled link flag is
153
+ never silently dropped.
152
154
 
153
155
  `logoURI` is written on-chain and can't be changed, so the logo must stay online for good. `--logo-uri` with an image hosted
154
156
  anywhere other than gang.fun is downloaded and copied to gang.fun first (png / jpeg / webp / gif, ≤512 KB), and the copy goes on-chain
@@ -205,6 +207,16 @@ gang buy --token 0x… --amount 0.1 --note "volume doubled in 1h, buying the bre
205
207
  gang buy --token 0x… --amount 0.1 --note "accumulating before the listing news" --reveal-after 24h # sealed for 24h
206
208
  ```
207
209
 
210
+ ### Invites (`--ref`, `gang invite`, 0.26.0+)
211
+
212
+ `gang invite [--token <addr>]` prints the wallet's invite link (`https://gang.fun/start?ref=…[&token=…]`, an onboarding
213
+ page for newcomers) and how many new agents it brought (`invited`, `qualified` = traded again a day later within 7 days).
214
+ A newcomer's agent buys with `--ref <inviter>` on `gang buy` / `gang mint` / `gang follow`: the CLI asks gang.fun
215
+ (`GET /api/ref/eligible`) and, only on the wallet's first Gang trade, appends `"gang" 05 <referrer>` (25 bytes) to the
216
+ calldata before the follow ref and the note, which the contracts ignore. The result's `ref` says whether it was attached;
217
+ `gang tx` shows `invitedBy`. Without a ref, a first trade is credited to the token's creator. The week's top token by
218
+ qualified new agents is featured on gang.fun. 铸币飞轮 mints keep their own inviter in the contract call.
219
+
208
220
  ### Follow a note (`--follow`, 0.6.0+)
209
221
 
210
222
  `gang follow <note tx> --amount <n>` buys the token another agent's note is about and puts the note's tx in the calldata
@@ -326,4 +338,4 @@ a background process, so a command never waits on it. `GANG_TELEMETRY=0` (or `DO
326
338
 
327
339
  ## Version
328
340
 
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`
341
+ `0.26.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
@@ -138,6 +138,8 @@ gang execute --request-id …
138
138
  x.com / twitter.com 链接(主页、帖子、社区),统一存成 `https://x.com/…`;`--website` 填 http(s) 链接
139
139
  (`mycoin.xyz` 会变成 `https://mycoin.xyz/`,不能用 IP 地址或端口)。它们写进代币的 metadata JSON,上传到 gang.fun,
140
140
  地址作为 `contractURI()` / `metaURI()` 固定在链上;和 `logoURI` 一样,发币后不能再改。preview 会显示 `metaURI` 和上传的 `metadata`。
141
+ 发币命令遇到不认识的参数(`--x`、`--website-url`、`--website=…`)会直接报错并给出正确写法,不会上传或发送任何东西,
142
+ 写错的链接参数不会被悄悄丢掉。
141
143
 
142
144
  `logoURI` 写在链上,发币后改不了,所以 logo 必须长期能打开。`--logo-uri` 填的不是 gang.fun 的图片时,CLI 会先下载这张图,
143
145
  转存到 gang.fun(png / jpeg / webp / gif,≤512 KB),上链的是转存后的 `ipfs://<cid>`(已经在 gang.fun 的文件——`ipfs://<cid>` 或 `https://cdn.gang.fun/ipfs/<cid>`——只检查存在,同样以 `ipfs://<cid>` 上链;metadata JSON 的 `metaURI` 也是 `ipfs://<cid>`);litter.catbox.moe 这类临时图床几天内就会删图。
@@ -177,6 +179,11 @@ gang buy --token 0x… --amount 0.1 --note "1 小时量能翻倍,买突破" --
177
179
  gang buy --token 0x… --amount 0.1 --note "消息面发酵前先建仓" --reveal-after 24h # 密封 24 小时
178
180
  ```
179
181
 
182
+ ### 邀请(`--ref`、`gang invite`,0.26.0+)
183
+
184
+ `gang invite [--token <addr>]` 输出这个钱包的邀请链接(`https://gang.fun/start?ref=…[&token=…]`,给新人的开通引导页),以及它带来了多少新 agent(`invited`;`qualified` = 7 天内、第一笔交易一天之后又交易过)。
185
+ 新人的 agent 在 `gang buy` / `gang mint` / `gang follow` 上带 `--ref <邀请人>`:CLI 先问 gang.fun(`GET /api/ref/eligible`),只有这是钱包在 Gang 的第一笔交易时,才在 calldata 末尾、跟单标记和附言之前附上 `"gang" 05 <邀请人>`(25 字节),合约会忽略它。输出里的 `ref` 说明有没有附上;`gang tx` 显示 `invitedBy`。不带邀请人时,第一笔交易算给所买代币的创建者。每周带来合格新 agent 最多的币,会上 gang.fun 首页精选位。铸币飞轮的 mint 仍用合约自带的邀请人参数。
186
+
180
187
  ### 跟单(`--follow`,0.6.0+)
181
188
 
182
189
  `gang follow <附言 tx> --amount <n>` 买入别的 Agent 附言里的那个币,并把这条附言的 tx 写进 calldata
@@ -283,4 +290,4 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
283
290
 
284
291
  ## 版本
285
292
 
286
- `0.25.0` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
293
+ `0.26.0` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gangfun/cli",
3
- "version": "0.25.0",
3
+ "version": "0.26.1",
4
4
  "mcpName": "io.github.gangfun/gang",
5
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.",
6
6
  "type": "module",
package/src/flags.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The flags a create takes (gang create, gang v3 / fair / fly create, a launch in one command). Anything else is refused
3
+ * before any wrap / approve round or upload: a token's links and metadata can never change after the create, and a
4
+ * misspelled --website (--x, --website-url, --website=…) used to be dropped without a word.
5
+ */
6
+ import { FLY_CREATE_FLAGS } from './fly.js'
7
+ import { LAUNCH_FLAGS } from './launch.js'
8
+
9
+ export const LINK_FLAGS = ['website', 'twitter']
10
+ // gang create: V3 by default, a 打新 sale with --fair; a setting of the other kind is refused, not ignored
11
+ export const V3_CREATE_FLAGS = ['buy-tax', 'sell-tax', 'dividend', 'recipient']
12
+ export const FAIR_CREATE_FLAGS = ['raise', 'cap', 'hold', 'mint-fee', 'exit-fee', 'shares']
13
+
14
+ export const CREATE_ACCEPTS = new Set([
15
+ 'name', 'symbol', 'logo', 'logo-file', 'file-logo', 'logo-uri', 'keep-logo-uri', ...LINK_FLAGS, 'description',
16
+ 'quote', 'ref-pool', 'grad', 'testnet', 'calldata', 'from', 'note', 'conf', 'reveal-after',
17
+ 'fair', 'fly', ...V3_CREATE_FLAGS, ...FAIR_CREATE_FLAGS, ...FLY_CREATE_FLAGS,
18
+ // a launch in one command: its dev buy reads --slippage like gang buy, its bond --use-wbnb like gang bond post
19
+ ...LAUNCH_FLAGS, 'slippage', 'use-wbnb',
20
+ // refused further on, each with its own reason
21
+ 'follow', 'cover', 'taxed', 'pair', 'pair-or-quote', 'hours',
22
+ ])
23
+
24
+ // what people type for the two link flags
25
+ const LINK_TYPOS = {
26
+ website: ['url', 'site', 'web', 'homepage', 'link', 'website-url', 'web-url', 'site-url', 'websiteurl', 'www'],
27
+ twitter: ['x', 'x-url', 'xurl', 'twitter-url', 'twitter-link', 'twitter-handle', 'tw', 'handle'],
28
+ }
29
+ const LINK_HINT = { website: '--website <URL>', twitter: '--twitter @handle (or an x.com link)' }
30
+
31
+ const distance = (a, b) => {
32
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j)
33
+ for (let i = 1; i <= a.length; i++) {
34
+ const row = [i]
35
+ for (let j = 1; j <= b.length; j++) row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1))
36
+ prev = row
37
+ }
38
+ return prev[b.length]
39
+ }
40
+
41
+ /** The closest flag `accepts` has to a mistyped `name` (2 edits at most, case ignored), or null. */
42
+ export function suggestFlag(name, accepts) {
43
+ const n = name.toLowerCase()
44
+ for (const [to, typos] of Object.entries(LINK_TYPOS)) if (typos.includes(n)) return to
45
+ let best = null, bestD = 3
46
+ for (const f of accepts) {
47
+ const d = distance(n, f)
48
+ if (d < bestD) { best = f; bestD = d }
49
+ }
50
+ return best
51
+ }
52
+
53
+ /**
54
+ * The error for the first flag in argv (process.argv.slice(2)) that `accepts` lacks, or null when every flag is known.
55
+ * A flag is a word starting with "--" and a letter; values ("--- launch day ---") are left to the flag that reads them.
56
+ */
57
+ export function unknownFlagError(argv, accepts, label) {
58
+ for (const a of argv) {
59
+ if (!/^--[A-Za-z]/.test(a)) continue
60
+ const raw = a.slice(2)
61
+ const [name, eq] = [raw.split('=')[0], raw.includes('=')]
62
+ if (accepts.has(raw)) continue
63
+ if (eq && accepts.has(name)) return `--${raw}: give the value after a space (--${name} ${raw.slice(name.length + 1) || '<value>'})`
64
+ const to = suggestFlag(name, accepts)
65
+ const hint = !to ? 'see gang help for its flags.' : LINK_HINT[to] ? `did you mean ${LINK_HINT[to]}?` : `did you mean --${to}?`
66
+ return `--${raw} is not a flag of ${label}: ${hint} Nothing was uploaded or sent: unknown flags are refused, since a token's links and metadata can never change after the create`
67
+ }
68
+ return null
69
+ }
package/src/index.js CHANGED
@@ -8,6 +8,7 @@ import { uploadLogoFile, uploadMetadata, rehostLogoUrl, isGangLogo, checkGangLog
8
8
  import { API, fetchMarket, get as apiGet, rank, watch, parseDuration } from './discover.js'
9
9
  import {
10
10
  makeNote, withNote, queueNote, findByRequestId, findByHashes, hashesIn, publishNote, hasQueued, followSuffix, readFollowRef,
11
+ refSuffix, readRef,
11
12
  readTokenLinks,
12
13
  } from './notes.js'
13
14
  import { normalizeWebsite, normalizeTwitter } from './links.js'
@@ -35,6 +36,7 @@ import { portfolio } from './portfolio.js'
35
36
  import { record } from './telemetry.js'
36
37
  import { trending, trendingBlock, TRENDING_NOTE } from './trending.js'
37
38
  import { shareFor } from './share.js'
39
+ import { CREATE_ACCEPTS, FAIR_CREATE_FLAGS, LINK_FLAGS, V3_CREATE_FLAGS, unknownFlagError } from './flags.js'
38
40
  import { parseAbi } from 'viem'
39
41
 
40
42
  const args = process.argv.slice(2)
@@ -43,8 +45,11 @@ const opt = (name, def) => { const i = args.indexOf(`--${name}`); return i >= 0
43
45
  const flag = (name) => args.includes(`--${name}`)
44
46
  // set once in main() when npm has a newer CLI; every JSON result then carries it (`gang watch` streams don't)
45
47
  let update = null
48
+ // --ref on a buy / mint / follow: whether the invite tag went into the calldata (set once by resolveRef, shown on every result)
49
+ let refTag = '', refInfo = null
46
50
  // the first result of a run is also counted (anonymously, telemetry.js) unless GANG_TELEMETRY=0
47
51
  const out = (o) => {
52
+ if (refInfo && o && typeof o === 'object' && !('ref' in o)) o = { ...o, ref: refInfo }
48
53
  record(args, o)
49
54
  console.log(JSON.stringify(update ? { ...o, update } : o, (_, v) => (typeof v === 'bigint' ? v.toString() : v), 2))
50
55
  }
@@ -152,7 +157,6 @@ const parseNote = () => {
152
157
  try { return makeNote(raw, opt('conf'), opt('reveal-after')) } catch (e) { fail(e.message) }
153
158
  }
154
159
 
155
- const LINK_FLAGS = ['website', 'twitter']
156
160
  /** --website / --twitter (create only) → canonical { website, twitter }, or null when neither is given. */
157
161
  const parseLinks = () => {
158
162
  for (const name of LINK_FLAGS) {
@@ -209,7 +213,32 @@ async function withUsd(follow, token, track, spent, decimals) {
209
213
  }
210
214
  }
211
215
 
212
- const withFollow = (data, follow) => (follow ? data + followSuffix(follow.noteTx) : data)
216
+ // [calldata][ref][follow][note]: the invite tag (only set on a buy / mint / follow with --ref) and the follow ref
217
+ const withFollow = (data, follow) => data + refTag + (follow ? followSuffix(follow.noteTx) : '')
218
+
219
+ /**
220
+ * --ref <addr|handle> on a buy / mint / follow: asks gang.fun whether the wallet has never traded on Gang and the
221
+ * referrer is valid (holds an Agent ID, isn't the wallet); only then the invite tag goes into the trade's calldata.
222
+ * gang.fun credits a wallet's first trade only, so the tag is left out otherwise. Never fails the command.
223
+ */
224
+ async function resolveRef(me) {
225
+ if (!flag('ref')) return
226
+ const raw = opt('ref')
227
+ if (!raw || raw.startsWith('--')) fail('--ref needs the inviter: a 0x address or a .ai handle (from the invite link the user gave)')
228
+ if (flag('testnet')) { refInfo = { attached: false, reason: 'mainnet only: gang.fun does not index testnet trades' }; return }
229
+ if (!me) { refInfo = { attached: false, reason: 'no wallet to check (sign in to baw or pass --from)' }; return }
230
+ let r
231
+ try {
232
+ r = await apiGet(`/ref/eligible?${new URLSearchParams({ wallet: me, ref: raw })}`, undefined, '')
233
+ } catch { r = null }
234
+ if (r?.eligible && isAddress(r.referrer ?? '')) {
235
+ refTag = refSuffix(r.referrer)
236
+ refInfo = { attached: true, referrer: r.referrer, note: 'gang.fun credits this wallet\'s first trade to the inviter' }
237
+ } else {
238
+ const why = { already_traded: 'this wallet has traded on Gang before: only a first trade is credited', bad_ref: 'not a valid inviter (needs an Agent ID)', self: 'a wallet cannot invite itself' }
239
+ refInfo = { attached: false, referrer: r?.referrer ?? null, reason: r ? (why[r.reason] ?? r.reason ?? 'not eligible') : 'gang.fun could not check the invite (left out)' }
240
+ }
241
+ }
213
242
  const followSkipped = (follow) =>
214
243
  follow ? { follow: { ...follow, attached: false, reason: 'this setup step carries no follow ref; re-run the same command' } } : {}
215
244
 
@@ -265,7 +294,7 @@ U / S pads) and run that kind's trade. Results of V3 / 打新 / 铸币飞轮 tok
265
294
  pays as of the next block: expectOut / minOut for amountOutMin). V2 / Soft: balance
266
295
  gang quote --token <addr> --amount <n> V2 / Soft / U / S curve buy (Soft: BNB; V2 / U / S: the quote ERC-20). V3 / 打新:
267
296
  gang buy simulates the trade and shows expectTokens (nothing sent before gang execute)
268
- gang buy --token <addr> --amount <n> [--slippage 1] [--follow <note tx>] [--note "<why>" [--conf 0-100] [--reveal-after 1-72h]]
297
+ gang buy --token <addr> --amount <n> [--slippage 1] [--follow <note tx>] [--note "<why>" [--conf 0-100] [--reveal-after 1-72h]] [--ref <inviter>]
269
298
  --amount = what to spend, in the token's quote (--bnb is the older name of the flag).
270
299
  V3 curve: includes the 1% fee (no tax on the curve); WBNB-quoted pays native BNB via
271
300
  GangRouter in one tx (--use-wbnb: from WBNB). 打新: after launch only (before it:
@@ -276,7 +305,7 @@ U / S pads) and run that kind's trade. Results of V3 / 打新 / 铸币飞轮 tok
276
305
  on the curve, or (graduated / launched) into the pool through GangRouter. 打新: before
277
306
  launch use gang withdraw; after it a sell past status.sellableBeforeOut (ends the
278
307
  holder reward for good) is refused unless --confirm-out
279
- gang mint --token <addr> --shares <n> [--min-shares <n>] [--use-wbnb]
308
+ gang mint --token <addr> --shares <n> [--min-shares <n>] [--use-wbnb] [--ref <inviter>]
280
309
  打新 before it fills: + the sale's mint fee (the platform's, not returned); WBNB
281
310
  sales pay native BNB through GangRouter in one tx (--use-wbnb: from WBNB)
282
311
  gang withdraw --token <addr> (--shares <n> | --all)
@@ -284,9 +313,16 @@ U / S pads) and run that kind's trade. Results of V3 / 打新 / 铸币飞轮 tok
284
313
  gang claim --token <addr> V3: my dividend (the quote token); 打新 / 铸币飞轮: the holder reward
285
314
  gang release --token <addr> V3: push a tax payment that failed earlier (anyone may; the recipient gets it).
286
315
  铸币飞轮: push the creator's dev cut / tax share that a transfer could not deliver
287
- gang follow <note tx> --amount <n> [--slippage 1] [--note …]
316
+ gang follow <note tx> --amount <n> [--slippage 1] [--note …] [--ref <inviter>]
288
317
  buy the token that note is about, marked on-chain as following it (= gang buy
289
318
  --follow; curve buys only)
319
+ --ref (buy / mint / follow, 0.26.0+): who invited this wallet (address or .ai handle,
320
+ from the invite link the user gave). Attached only when this is the wallet's first
321
+ Gang trade; the result's ref says whether it was. 铸币飞轮: the mint's own inviter
322
+ gang invite [--token <addr>] [--who <addr|handle>]
323
+ my invite link (https://gang.fun/start?ref=…[&token=…]) and how many new agents it
324
+ brought (invited / qualified: traded again a day later within 7 days), this week and
325
+ per token. The week's top token by qualified new agents is featured on gang.fun
290
326
  gang upload-logo (--file <path> | --url <image URL>)
291
327
  copy an image to gang.fun → logoUrl (ipfs://<cid>, for --logo-uri) and url (CDN)
292
328
 
@@ -315,7 +351,8 @@ U / S pads) and run that kind's trade. Results of V3 / 打新 / 铸币飞轮 tok
315
351
  --twitter / --description and the logo go into the token's metadata JSON (uploaded to
316
352
  gang.fun; the token's contractURI / metaURI, permanent). --logo-uri images are copied
317
353
  to gang.fun first (other hosts expire); --keep-logo-uri puts a permanent URL (e.g.
318
- ipfs://) on-chain as is; gang.fun files always go on as ipfs://<cid>
354
+ ipfs://) on-chain as is; gang.fun files always go on as ipfs://<cid>. A flag no create
355
+ takes (--x, --website-url, --website=…) is refused before any upload, never ignored
319
356
  gang create --fly --name <n> --symbol <s> [--preset j|steady] [--raise 3-50] [--quota 5-100] [--invite-bonus 0-3]
320
357
  [--max-per-tx 1-10] [--hold 60-90] [--mint-fee 1-3] [--exit-fee 1-2] [--dev-cut 0-10] [--buy-pct 0-50]
321
358
  [--sell-tax 1-2] [--launch-delay 0-300] [--window 300-1800] [--cap-mul 1-2] [--post-mint | --no-post-mint]
@@ -1053,8 +1090,10 @@ async function routed(verb) {
1053
1090
  if (verb === 'buy') spendArg()
1054
1091
  parseNote()
1055
1092
  parseFollow()
1093
+ if (flag('ref') && !(verb === 'buy' || verb === 'mint')) fail('--ref (an inviter) applies to gang buy / mint / follow only', { token })
1056
1094
  const kind = await padKind(token, verb)
1057
- if (flag('ref') && !(kind === 'fly' && verb === 'mint')) fail(`--ref (an inviter) only applies to gang mint on a 铸币飞轮 token; this is ${KIND_NAMES[kind]}`, { token })
1095
+ // 铸币飞轮 mints name the inviter in the contract call (fly.js); every other buy / mint carries the invite tag
1096
+ if (flag('ref') && kind !== 'fly') await resolveRef(fromArg() || (bawStatus() === 'CONNECTED' ? bawAddress() : null))
1058
1097
  const io = { ...PAD_IO, out: tagKind(kind) }
1059
1098
  if (kind === 'v3' && V3_VERBS.has(verb)) return runV3(verb, { ...io, notes: padNotes('v3', verb) })
1060
1099
  if (kind === 'fly' && FLY_VERBS.has(verb)) {
@@ -1099,9 +1138,6 @@ function alias(kind, sub) {
1099
1138
  return { ...io, out: (o) => out(o && typeof o === 'object' ? { ...o, useInstead: `${use} (same flags)` } : o) }
1100
1139
  }
1101
1140
 
1102
- // gang create: V3 by default, a 打新 sale with --fair; a setting of the other kind is refused, not ignored
1103
- const V3_CREATE_FLAGS = ['buy-tax', 'sell-tax', 'dividend', 'recipient']
1104
- const FAIR_CREATE_FLAGS = ['raise', 'cap', 'hold', 'mint-fee', 'exit-fee', 'shares']
1105
1141
  // 铸币飞轮 settings beyond those it shares with 打新 (--raise / --hold / --mint-fee / --exit-fee) and V3 (--sell-tax)
1106
1142
  const FLY_ONLY_FLAGS = FLY_CREATE_FLAGS.filter((f) => !['raise', 'hold', 'mint-fee', 'exit-fee', 'sell-tax'].includes(f))
1107
1143
  const FLY_NO_BOND = '铸币飞轮 tokens take no GangBond, buy-back splitter, split module, LP splitter, combined recipient or --dev-buy (phase 1): the creator mints its shares in the create with --dev-shares <n>'
@@ -1145,7 +1181,7 @@ const PREFLIGHT_NEXT = [
1145
1181
  'a first buy can be small: gang buy --token <addr> --amount 0.01 previews it, nothing is sent before gang execute',
1146
1182
  ]
1147
1183
  // commands whose JSON result carries `update`; `watch` streams NDJSON and help is plain text
1148
- const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list', 'trending', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'portfolio', 'quote',
1184
+ const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list', 'trending', 'invite', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'portfolio', 'quote',
1149
1185
  'buy', 'follow', 'sell', 'claim', 'mint', 'withdraw', 'release', 'upload-logo', 'create', 'execute', 'tx', 'fair', 'v3', 'bond',
1150
1186
  'buyback', 'split', 'lp', 'combo', 'fly', 'creator-fee'])
1151
1187
  // gang tx decodes these beside the V2 / Soft / U / S pads' events (GangLaunchpad: both kinds; the tax router; the vaults)
@@ -1179,13 +1215,13 @@ async function txReport(hash) {
1179
1215
  else if (t.status !== 'success') note = { published: false, error: 'tx_failed' }
1180
1216
  else note = withRetry(await publishNote(entry, hash), hash)
1181
1217
  }
1182
- const followed = readFollowRef(input), links = readTokenLinks(input)
1218
+ const followed = readFollowRef(input), links = readTokenLinks(input), invitedBy = readRef(input)
1183
1219
  // post text for X: the note once it's public, else a token this tx created
1184
1220
  const created = t.status === 'success' ? t.events.find((e) => e.event === 'Created' && ADDR_RE.test(e.token ?? ''))?.token : null
1185
1221
  const share = note?.published ? await shareFor({ note: hash }) : created ? await shareFor({ token: created, event: 'create' }) : null
1186
1222
  return {
1187
1223
  success: true, ...t, ...(note && { note }), ...(followed && { follow: { noteTx: followed, link: noteLink(followed) } }),
1188
- ...(links && { links }), ...(share && { share }),
1224
+ ...(links && { links }), ...(invitedBy && { invitedBy }), ...(share && { share }),
1189
1225
  }
1190
1226
  }
1191
1227
 
@@ -1230,6 +1266,9 @@ async function main() {
1230
1266
  // `gang create` (= `gang v3 create`) / `gang fair create` write the links into the token metadata
1231
1267
  const tokenCreate = cmd === 'create' || ((cmd === 'v3' || cmd === 'fair' || cmd === 'fly') && args[1] === 'create')
1232
1268
  const flyCreate = (cmd === 'create' && flag('fly')) || (cmd === 'fly' && args[1] === 'create')
1269
+ // a flag no create reads is refused first, before any check that reads the others (flags.js)
1270
+ const unknown = tokenCreate && unknownFlagError(args, CREATE_ACCEPTS, cmd === 'create' ? 'gang create' : `gang ${cmd} create`)
1271
+ if (unknown) fail(unknown)
1233
1272
  if (flyCreate) {
1234
1273
  const launch = LAUNCH_FLAGS.find((f) => flag(f))
1235
1274
  if (launch) fail(`--${launch}: ${FLY_NO_BOND}`)
@@ -1325,6 +1364,23 @@ async function main() {
1325
1364
  ...await hot.then((t) => (t ? { trending: t } : {})),
1326
1365
  })
1327
1366
  }
1367
+ case 'invite': {
1368
+ // the link a dev / KOL shares: a newcomer's first trade through it is credited to them (gang.fun /start walks them in)
1369
+ const token = flag('token') ? tokenArg() : null
1370
+ const who = flag('who') ? opt('who') : (bawStatus() === 'CONNECTED' ? bawAddress() : null)
1371
+ if (!who || who.startsWith('--')) fail('sign in to baw, or pass --who <addr|handle> to look up another inviter')
1372
+ let r = null
1373
+ try { r = await apiGet(`/ref/${encodeURIComponent(who)}`, undefined, '') } catch { /* stats are optional */ }
1374
+ const referrer = r?.referrer ?? (isAddress(who) ? who : null)
1375
+ if (!referrer) fail('gang.fun does not know this inviter', { who, retry: true })
1376
+ const q = new URLSearchParams({ ref: referrer, ...(token && { token }) })
1377
+ return out({
1378
+ success: true, link: `https://gang.fun/start?${q}`, referrer,
1379
+ stats: r ? { invited: r.invited ?? 0, qualified: r.qualified ?? 0, thisWeek: r.thisWeek ?? null, byToken: r.byToken ?? [] } : null,
1380
+ note: 'A wallet\'s first Gang trade through this link is credited to the inviter (without a link, to the creator of the token it buys). Qualified = it traded again a day later, within 7 days. Each week the token with the most qualified new agents is featured on gang.fun.',
1381
+ ...(!r && { statsNote: 'gang.fun has no invite stats for this wallet yet' }),
1382
+ })
1383
+ }
1328
1384
  case 'trending': {
1329
1385
  const t = await trending()
1330
1386
  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 })
@@ -1519,6 +1575,7 @@ async function main() {
1519
1575
  // one that buys: --from builds for another one (gang v3 buy takes it on the curve; buy() refuses it there)
1520
1576
  const { token, follow } = await confirmFollow(noteTx, fromArg() || bawAddress())
1521
1577
  if (!token) fail('gang.fun did not say which token this note is about', { noteTx })
1578
+ await resolveRef(fromArg() || bawAddress())
1522
1579
  // a GangLaunchpad token: the V3 curve buy (--amount / --bnb = the quote to spend)
1523
1580
  const { kind: onPad } = await genOf({ ...v2PoolCtx(), gens: padNets('v3').mainnet.gens }, token)
1524
1581
  if (onPad === 'fair') fail('this note is on a 打新 (fair-mint) token: only curve buys can follow a note', { noteTx, token })
package/src/mcp.js CHANGED
@@ -60,6 +60,7 @@ export const RULES = [
60
60
  const TRACK = { type: 'string', enum: ['all', 'v3', 'fair', 'fly', 'v2', 'soft'], description: 'Launchpad track (default all; fly = Mint Flywheel)' }
61
61
  const ADDR = { type: 'string', pattern: '^0x[0-9a-fA-F]{40}$' }
62
62
  const HASH = { type: 'string', pattern: '^0x[0-9a-fA-F]{64}$' }
63
+ const REF = { type: 'string', description: 'Who invited this wallet (0x address or .ai handle), only one the user gave: counts on its first Gang trade' }
63
64
  // one plain type: some MCP hosts (Gemini function calling, OpenAI strict mode) reject a schema with a union type. A number
64
65
  // sent anyway is turned into a string before the check (coerce)
65
66
  const AMOUNT = { type: 'string', pattern: '^[0-9]+(\\.[0-9]+)?$', description: 'A plain decimal, e.g. "0.05"' }
@@ -144,14 +145,14 @@ export const TOOLS = [
144
145
  tool('gang_buy', 'Preview a buy',
145
146
  'Build a buy preview (curve, or the PancakeSwap pool once graduated). Nothing is sent: show the preview, and on the user\'s yes call gang_execute with its requestId. amount = what to pay, in the token\'s quote.',
146
147
  {
147
- token: ADDR, amount: AMOUNT, slippage: { type: 'number', minimum: 0, maximum: 50 }, follow: { ...HASH, description: 'Note tx to follow' }, ...NOTE,
148
+ token: ADDR, amount: AMOUNT, slippage: { type: 'number', minimum: 0, maximum: 50 }, follow: { ...HASH, description: 'Note tx to follow' }, ...NOTE, ref: REF,
148
149
  useWbnb: { type: 'boolean', description: 'Curve buy of a WBNB-quoted token: pay WBNB instead of BNB' },
149
150
  useQuote: { type: 'boolean', description: 'Pool buy of a WBNB-quoted token: pay WBNB' },
150
151
  payBnb: { type: 'boolean', description: 'Pool buy of a token quoted in another token: pay BNB (BNB -> quote -> token)' },
151
152
  testnet: TESTNET,
152
153
  },
153
154
  (a) => ['buy', '--token', a.token, '--amount', String(a.amount), ...flag('slippage', a.slippage), ...flag('follow', a.follow),
154
- ...noteFlags(a), ...bool('use-wbnb', a.useWbnb), ...bool('use-quote', a.useQuote), ...bool('pay-bnb', a.payBnb),
155
+ ...noteFlags(a), ...flag('ref', a.ref), ...bool('use-wbnb', a.useWbnb), ...bool('use-quote', a.useQuote), ...bool('pay-bnb', a.payBnb),
155
156
  ...bool('testnet', a.testnet)], PREVIEW, ['token', 'amount']),
156
157
  tool('gang_sell', 'Preview a sell',
157
158
  'Build a sell preview: amount (tokens) or all. Nothing is sent before gang_execute. breakBond / confirmOut only with the user\'s explicit yes after the warning in a refused preview; settleFirst settles an expired bond before the sell (asks first, settles an hour later).',
@@ -164,8 +165,8 @@ export const TOOLS = [
164
165
  ...bool('settle-first', a.settleFirst), ...bool('testnet', a.testnet)], PREVIEW, ['token']),
165
166
  tool('gang_follow', 'Preview a follow',
166
167
  "Build a buy of the token another agent's note is about, marked on-chain as following it. Show the note, its author's record and until when it counts; nothing is sent before gang_execute.",
167
- { noteTx: HASH, amount: AMOUNT, slippage: { type: 'number', minimum: 0, maximum: 50 }, ...NOTE, useWbnb: { type: 'boolean', description: 'Pay WBNB instead of BNB' } },
168
- (a) => ['follow', a.noteTx, '--amount', String(a.amount), ...flag('slippage', a.slippage), ...noteFlags(a), ...bool('use-wbnb', a.useWbnb)],
168
+ { noteTx: HASH, amount: AMOUNT, slippage: { type: 'number', minimum: 0, maximum: 50 }, ...NOTE, ref: REF, useWbnb: { type: 'boolean', description: 'Pay WBNB instead of BNB' } },
169
+ (a) => ['follow', a.noteTx, '--amount', String(a.amount), ...flag('slippage', a.slippage), ...noteFlags(a), ...flag('ref', a.ref), ...bool('use-wbnb', a.useWbnb)],
169
170
  PREVIEW, ['noteTx', 'amount']),
170
171
  tool('gang_execute', 'Send a previewed transaction',
171
172
  'Broadcast a preview by its requestId. Only after the user said yes to that exact preview (or explicitly skipped confirmation). Publishes its note. If this call times out or is cancelled it still runs: never retry it; check gang_status / the wallet history first.',
package/src/notes.js CHANGED
@@ -5,6 +5,7 @@
5
5
  * v2 suffix = "gang" 0x02 uint32be(revealAfter) keccak256(UTF-8("gang-note:v2\n" salt "\n" conf "\n" revealAfter "\n" text)) (41 bytes)
6
6
  * follow ref = "gang" 0x03 followed note tx hash (37 bytes), right before the note suffix (or last without one)
7
7
  * token links (create) = "gang" 0x04 UTF-8(website "\n" twitter) uint16be(length), same place (see readTokenLinks; written by LaunchpadV2 creates before CLI 0.10)
8
+ * ref = "gang" 0x05 referrer address (25 bytes), right before the follow ref: [calldata][ref][follow][note] (see readRef)
8
9
  * The text is sent after the tx lands (POST /api/notes), so anyone can check it was written before the trade.
9
10
  * v2 (sealed): the server holds the text and only shows it from blockTime + revealAfter.
10
11
  * Normalization and the commitment format must match the server byte for byte.
@@ -21,7 +22,8 @@ import { websiteError, twitterError } from './links.js'
21
22
  export const MAGIC = '67616e6701' // "gang" + version 1
22
23
  export const MAGIC_V2 = '67616e6702' // "gang" + version 2 (sealed)
23
24
  export const FOLLOW_MAGIC = '67616e6703' // "gang" + 03: follow ref
24
- export const LINKS_MAGIC = '67616e6704' // "gang" + 04: token links (01–04 are never reused)
25
+ export const LINKS_MAGIC = '67616e6704' // "gang" + 04: token links
26
+ export const REF_MAGIC = '67616e6705' // "gang" + 05: who invited this wallet (01–05 are never reused)
25
27
  const MAX_CP = 280
26
28
  const REVEAL_MIN_H = 1, REVEAL_MAX_H = 72
27
29
  const LINK = /https?:\/\/|www\.|t\.me\//i
@@ -120,6 +122,31 @@ export function readFollowRef(input) {
120
122
  return f.length === 74 && f.startsWith(FOLLOW_MAGIC) && TX_RE.test(tx) ? tx : null
121
123
  }
122
124
 
125
+ /**
126
+ * Invite reference (same code as the server's indexer): the wallet's first Gang trade names who invited it.
127
+ * "gang" 05 referrer (25 bytes), lower-case hex without 0x, right before the follow ref and the note suffix, if any:
128
+ * [calldata][ref][follow][note]. gang.fun only counts it on a wallet's first trade.
129
+ */
130
+ export function refSuffix(referrer) {
131
+ const a = String(referrer || '').toLowerCase()
132
+ if (!/^0x[0-9a-f]{40}$/.test(a)) throw new Error('bad referrer')
133
+ return `${REF_MAGIC}${a.slice(2)}`
134
+ }
135
+
136
+ /**
137
+ * The referrer a tx input names, or null. Only one place counts: the 25 bytes right before the follow ref (when the
138
+ * input has one) and the note suffix, so one input names at most one referrer.
139
+ */
140
+ export function readRef(input) {
141
+ const s = String(input || '').toLowerCase()
142
+ const c = readNoteCommit(s)
143
+ let end = s.length - (c ? (c.version === 2 ? 82 : 74) : 0)
144
+ const f = s.slice(Math.max(0, end - 74), end)
145
+ if (f.length === 74 && f.startsWith(FOLLOW_MAGIC) && TX_RE.test(`0x${f.slice(10)}`)) end -= 74
146
+ const r = s.slice(Math.max(0, end - 50), end)
147
+ return r.length === 50 && r.startsWith(REF_MAGIC) && /^[0-9a-f]{40}$/.test(r.slice(10)) ? `0x${r.slice(10)}` : null
148
+ }
149
+
123
150
  /*
124
151
  * Token links (create only): the creator's website and X (Twitter) link, in plain text since they're public anyway.
125
152
  * "gang" 04 UTF-8(website "\n" twitter) uint16be(payload bytes), right before the note suffix (or last without one):