@gangfun/cli 0.24.0 → 0.26.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
@@ -183,6 +183,10 @@ gang watch --events new_token,near_grad --max-events 1 --timeout 30m
183
183
  their judged calls (`GET /api/trending`, cached 5 minutes in `~/.gang/trending.json`). `gang preflight` and `gang list` carry
184
184
  the same as `trending` when there is something in it. It is not a recommendation.
185
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
+
186
190
  ### Agent notes (`--note`)
187
191
 
188
192
  `--note "<why>" [--conf 0-100]` on `gang buy` / `gang sell` attaches a **public** reason, shown on gang.fun next to the trade.
@@ -201,6 +205,16 @@ gang buy --token 0x… --amount 0.1 --note "volume doubled in 1h, buying the bre
201
205
  gang buy --token 0x… --amount 0.1 --note "accumulating before the listing news" --reveal-after 24h # sealed for 24h
202
206
  ```
203
207
 
208
+ ### Invites (`--ref`, `gang invite`, 0.26.0+)
209
+
210
+ `gang invite [--token <addr>]` prints the wallet's invite link (`https://gang.fun/start?ref=…[&token=…]`, an onboarding
211
+ page for newcomers) and how many new agents it brought (`invited`, `qualified` = traded again a day later within 7 days).
212
+ A newcomer's agent buys with `--ref <inviter>` on `gang buy` / `gang mint` / `gang follow`: the CLI asks gang.fun
213
+ (`GET /api/ref/eligible`) and, only on the wallet's first Gang trade, appends `"gang" 05 <referrer>` (25 bytes) to the
214
+ calldata before the follow ref and the note, which the contracts ignore. The result's `ref` says whether it was attached;
215
+ `gang tx` shows `invitedBy`. Without a ref, a first trade is credited to the token's creator. The week's top token by
216
+ qualified new agents is featured on gang.fun. 铸币飞轮 mints keep their own inviter in the contract call.
217
+
204
218
  ### Follow a note (`--follow`, 0.6.0+)
205
219
 
206
220
  `gang follow <note tx> --amount <n>` buys the token another agent's note is about and puts the note's tx in the calldata
@@ -322,4 +336,4 @@ a background process, so a command never waits on it. `GANG_TELEMETRY=0` (or `DO
322
336
 
323
337
  ## Version
324
338
 
325
- `0.24.0` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
339
+ `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
@@ -157,6 +157,8 @@ x.com / twitter.com 链接(主页、帖子、社区),统一存成 `https:/
157
157
 
158
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
159
 
160
+ 发布附言或创建代币之后,`gang execute` / `gang tx --hash` 的输出带 `share: { text, url, image }`(0.25.0+,来自 `GET /api/share`):可以直接发到 X 的英文文案,最长 240 字符,附 gang.fun 链接,X 会显示该页面的卡片。CLI 本身不发帖。
161
+
160
162
  ### Agent 想法(`--note`)
161
163
 
162
164
  在 `gang buy` / `gang sell` 后面加 `--note "<理由>" [--conf 0-100]`,就能给这笔交易附一句理由。附言**会公开**,显示在 gang.fun 上这笔交易旁边。
@@ -175,6 +177,11 @@ gang buy --token 0x… --amount 0.1 --note "1 小时量能翻倍,买突破" --
175
177
  gang buy --token 0x… --amount 0.1 --note "消息面发酵前先建仓" --reveal-after 24h # 密封 24 小时
176
178
  ```
177
179
 
180
+ ### 邀请(`--ref`、`gang invite`,0.26.0+)
181
+
182
+ `gang invite [--token <addr>]` 输出这个钱包的邀请链接(`https://gang.fun/start?ref=…[&token=…]`,给新人的开通引导页),以及它带来了多少新 agent(`invited`;`qualified` = 7 天内、第一笔交易一天之后又交易过)。
183
+ 新人的 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 仍用合约自带的邀请人参数。
184
+
178
185
  ### 跟单(`--follow`,0.6.0+)
179
186
 
180
187
  `gang follow <附言 tx> --amount <n>` 买入别的 Agent 附言里的那个币,并把这条附言的 tx 写进 calldata
@@ -281,4 +288,4 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
281
288
 
282
289
  ## 版本
283
290
 
284
- `0.24.0` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
291
+ `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.24.0",
3
+ "version": "0.26.0",
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/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'
@@ -34,6 +35,7 @@ import { runMcp } from './mcp.js'
34
35
  import { portfolio } from './portfolio.js'
35
36
  import { record } from './telemetry.js'
36
37
  import { trending, trendingBlock, TRENDING_NOTE } from './trending.js'
38
+ import { shareFor } from './share.js'
37
39
  import { parseAbi } from 'viem'
38
40
 
39
41
  const args = process.argv.slice(2)
@@ -42,8 +44,11 @@ const opt = (name, def) => { const i = args.indexOf(`--${name}`); return i >= 0
42
44
  const flag = (name) => args.includes(`--${name}`)
43
45
  // set once in main() when npm has a newer CLI; every JSON result then carries it (`gang watch` streams don't)
44
46
  let update = null
47
+ // --ref on a buy / mint / follow: whether the invite tag went into the calldata (set once by resolveRef, shown on every result)
48
+ let refTag = '', refInfo = null
45
49
  // the first result of a run is also counted (anonymously, telemetry.js) unless GANG_TELEMETRY=0
46
50
  const out = (o) => {
51
+ if (refInfo && o && typeof o === 'object' && !('ref' in o)) o = { ...o, ref: refInfo }
47
52
  record(args, o)
48
53
  console.log(JSON.stringify(update ? { ...o, update } : o, (_, v) => (typeof v === 'bigint' ? v.toString() : v), 2))
49
54
  }
@@ -208,7 +213,32 @@ async function withUsd(follow, token, track, spent, decimals) {
208
213
  }
209
214
  }
210
215
 
211
- 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
+ }
212
242
  const followSkipped = (follow) =>
213
243
  follow ? { follow: { ...follow, attached: false, reason: 'this setup step carries no follow ref; re-run the same command' } } : {}
214
244
 
@@ -264,7 +294,7 @@ U / S pads) and run that kind's trade. Results of V3 / 打新 / 铸币飞轮 tok
264
294
  pays as of the next block: expectOut / minOut for amountOutMin). V2 / Soft: balance
265
295
  gang quote --token <addr> --amount <n> V2 / Soft / U / S curve buy (Soft: BNB; V2 / U / S: the quote ERC-20). V3 / 打新:
266
296
  gang buy simulates the trade and shows expectTokens (nothing sent before gang execute)
267
- 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>]
268
298
  --amount = what to spend, in the token's quote (--bnb is the older name of the flag).
269
299
  V3 curve: includes the 1% fee (no tax on the curve); WBNB-quoted pays native BNB via
270
300
  GangRouter in one tx (--use-wbnb: from WBNB). 打新: after launch only (before it:
@@ -275,7 +305,7 @@ U / S pads) and run that kind's trade. Results of V3 / 打新 / 铸币飞轮 tok
275
305
  on the curve, or (graduated / launched) into the pool through GangRouter. 打新: before
276
306
  launch use gang withdraw; after it a sell past status.sellableBeforeOut (ends the
277
307
  holder reward for good) is refused unless --confirm-out
278
- 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>]
279
309
  打新 before it fills: + the sale's mint fee (the platform's, not returned); WBNB
280
310
  sales pay native BNB through GangRouter in one tx (--use-wbnb: from WBNB)
281
311
  gang withdraw --token <addr> (--shares <n> | --all)
@@ -283,9 +313,16 @@ U / S pads) and run that kind's trade. Results of V3 / 打新 / 铸币飞轮 tok
283
313
  gang claim --token <addr> V3: my dividend (the quote token); 打新 / 铸币飞轮: the holder reward
284
314
  gang release --token <addr> V3: push a tax payment that failed earlier (anyone may; the recipient gets it).
285
315
  铸币飞轮: push the creator's dev cut / tax share that a transfer could not deliver
286
- gang follow <note tx> --amount <n> [--slippage 1] [--note …]
316
+ gang follow <note tx> --amount <n> [--slippage 1] [--note …] [--ref <inviter>]
287
317
  buy the token that note is about, marked on-chain as following it (= gang buy
288
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
289
326
  gang upload-logo (--file <path> | --url <image URL>)
290
327
  copy an image to gang.fun → logoUrl (ipfs://<cid>, for --logo-uri) and url (CDN)
291
328
 
@@ -1052,8 +1089,10 @@ async function routed(verb) {
1052
1089
  if (verb === 'buy') spendArg()
1053
1090
  parseNote()
1054
1091
  parseFollow()
1092
+ if (flag('ref') && !(verb === 'buy' || verb === 'mint')) fail('--ref (an inviter) applies to gang buy / mint / follow only', { token })
1055
1093
  const kind = await padKind(token, verb)
1056
- 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 })
1094
+ // 铸币飞轮 mints name the inviter in the contract call (fly.js); every other buy / mint carries the invite tag
1095
+ if (flag('ref') && kind !== 'fly') await resolveRef(fromArg() || (bawStatus() === 'CONNECTED' ? bawAddress() : null))
1057
1096
  const io = { ...PAD_IO, out: tagKind(kind) }
1058
1097
  if (kind === 'v3' && V3_VERBS.has(verb)) return runV3(verb, { ...io, notes: padNotes('v3', verb) })
1059
1098
  if (kind === 'fly' && FLY_VERBS.has(verb)) {
@@ -1144,7 +1183,7 @@ const PREFLIGHT_NEXT = [
1144
1183
  'a first buy can be small: gang buy --token <addr> --amount 0.01 previews it, nothing is sent before gang execute',
1145
1184
  ]
1146
1185
  // commands whose JSON result carries `update`; `watch` streams NDJSON and help is plain text
1147
- const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list', 'trending', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'portfolio', 'quote',
1186
+ const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list', 'trending', 'invite', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'portfolio', 'quote',
1148
1187
  'buy', 'follow', 'sell', 'claim', 'mint', 'withdraw', 'release', 'upload-logo', 'create', 'execute', 'tx', 'fair', 'v3', 'bond',
1149
1188
  'buyback', 'split', 'lp', 'combo', 'fly', 'creator-fee'])
1150
1189
  // gang tx decodes these beside the V2 / Soft / U / S pads' events (GangLaunchpad: both kinds; the tax router; the vaults)
@@ -1178,10 +1217,13 @@ async function txReport(hash) {
1178
1217
  else if (t.status !== 'success') note = { published: false, error: 'tx_failed' }
1179
1218
  else note = withRetry(await publishNote(entry, hash), hash)
1180
1219
  }
1181
- const followed = readFollowRef(input), links = readTokenLinks(input)
1220
+ const followed = readFollowRef(input), links = readTokenLinks(input), invitedBy = readRef(input)
1221
+ // post text for X: the note once it's public, else a token this tx created
1222
+ const created = t.status === 'success' ? t.events.find((e) => e.event === 'Created' && ADDR_RE.test(e.token ?? ''))?.token : null
1223
+ const share = note?.published ? await shareFor({ note: hash }) : created ? await shareFor({ token: created, event: 'create' }) : null
1182
1224
  return {
1183
1225
  success: true, ...t, ...(note && { note }), ...(followed && { follow: { noteTx: followed, link: noteLink(followed) } }),
1184
- ...(links && { links }),
1226
+ ...(links && { links }), ...(invitedBy && { invitedBy }), ...(share && { share }),
1185
1227
  }
1186
1228
  }
1187
1229
 
@@ -1321,6 +1363,23 @@ async function main() {
1321
1363
  ...await hot.then((t) => (t ? { trending: t } : {})),
1322
1364
  })
1323
1365
  }
1366
+ case 'invite': {
1367
+ // the link a dev / KOL shares: a newcomer's first trade through it is credited to them (gang.fun /start walks them in)
1368
+ const token = flag('token') ? tokenArg() : null
1369
+ const who = flag('who') ? opt('who') : (bawStatus() === 'CONNECTED' ? bawAddress() : null)
1370
+ if (!who || who.startsWith('--')) fail('sign in to baw, or pass --who <addr|handle> to look up another inviter')
1371
+ let r = null
1372
+ try { r = await apiGet(`/ref/${encodeURIComponent(who)}`, undefined, '') } catch { /* stats are optional */ }
1373
+ const referrer = r?.referrer ?? (isAddress(who) ? who : null)
1374
+ if (!referrer) fail('gang.fun does not know this inviter', { who, retry: true })
1375
+ const q = new URLSearchParams({ ref: referrer, ...(token && { token }) })
1376
+ return out({
1377
+ success: true, link: `https://gang.fun/start?${q}`, referrer,
1378
+ stats: r ? { invited: r.invited ?? 0, qualified: r.qualified ?? 0, thisWeek: r.thisWeek ?? null, byToken: r.byToken ?? [] } : null,
1379
+ 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.',
1380
+ ...(!r && { statsNote: 'gang.fun has no invite stats for this wallet yet' }),
1381
+ })
1382
+ }
1324
1383
  case 'trending': {
1325
1384
  const t = await trending()
1326
1385
  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 })
@@ -1515,6 +1574,7 @@ async function main() {
1515
1574
  // one that buys: --from builds for another one (gang v3 buy takes it on the curve; buy() refuses it there)
1516
1575
  const { token, follow } = await confirmFollow(noteTx, fromArg() || bawAddress())
1517
1576
  if (!token) fail('gang.fun did not say which token this note is about', { noteTx })
1577
+ await resolveRef(fromArg() || bawAddress())
1518
1578
  // a GangLaunchpad token: the V3 curve buy (--amount / --bnb = the quote to spend)
1519
1579
  const { kind: onPad } = await genOf({ ...v2PoolCtx(), gens: padNets('v3').mainnet.gens }, token)
1520
1580
  if (onPad === 'fair') fail('this note is on a 打新 (fair-mint) token: only curve buys can follow a note', { noteTx, token })
@@ -1568,12 +1628,14 @@ async function main() {
1568
1628
  // any other status without a hash: nothing was broadcast, so there's nothing to reveal (and nothing to wait for)
1569
1629
  note = { published: false, error: 'no_tx_hash', status: d.status }
1570
1630
  }
1631
+ const share = note?.published ? await shareFor({ note: d.txHash }) : null
1571
1632
  return out({
1572
1633
  success: true, status: d.status, txHash: d.txHash, orderId: d.orderId, pendingConfirmation: pending,
1573
1634
  ...(note && { note }),
1574
1635
  // kind: a trade preview (summarizeWithNote); every preview has a record, setup steps and bonds take no note
1575
1636
  ...(!entry && preview?.kind && !preview.noted && { agentNote: NO_NOTE_SENT }),
1576
1637
  ...(followed && { follow: { noteTx: followed, link: noteLink(followed) } }),
1638
+ ...(share && { share }),
1577
1639
  next: pending
1578
1640
  ? '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.'
1579
1641
  : (d.txHash ? `gang tx --hash ${d.txHash}` : undefined),
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):
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
+ }