@gangfun/cli 0.18.3 → 0.19.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
@@ -10,6 +10,8 @@ Operate [gang.fun](https://gang.fun) from a Binance **Agentic Wallet**. Curve bu
10
10
 
11
11
  **V3 tax tokens and 打新 (0.9.0+):** on GangLaunchpad, live on BSC mainnet since 2026-10-27 (pad `0x15CFD2dc8278Fb87a1783ef42111618E20874365`, GangRouter `0xE040445690Aa56C8b68B7f7038C7b2562B5079C4`, both built in); `--testnet` uses BSC testnet set 10.
12
12
 
13
+ **Split recipient (0.19.0+):** `gang create … --buy-tax … --sell-tax … --split self:60,0x…:30,0x…:10` makes a V3 token's tax recipient the dev's split module (GangSplitModule, `split-v1`): the recipient's part of the tax is split among 1–10 payees at shares fixed for good (nobody, not the dev, not the platform, can change them; a payee can only move its own slot). `self` is the creating wallet (`me` also works); payee slots are numbered as in the contract, from 0 (`--index`). The quote must be one the keeper splits: WBNB (default), GANG or a quote in the pad's QuoteRegistry (others are refused before the clone, as for `--buyback`); `gang split distribute` still splits any asset sent to the module. `gang split …` shows and drives it. Live on BSC mainnet (factory `0x27e08271E52B2D129c824CD245e69471a8d3067c`, allowed by the platform's Safe on 2026-10-30, built in) and testnet set 10.
14
+
13
15
  ## Install
14
16
 
15
17
  Node ≥ 18. Also install Binance Agentic Wallet CLI (`baw`):
@@ -103,6 +105,8 @@ gang bond burn --token <addr> | gang bond tx --hash <0x..> # push one buy-
103
105
  gang create … --dev-buy <quote> [--bond <quote> [--bond-hold <tokens|N%|all>] --bond-days <7-90>] # V3: create → dev buy → bond
104
106
  gang create … --buy-tax 3 --sell-tax 3 --buyback 50 [--buyback-to 0x…] [--dev-buy …] # V3: the recipient's part of the tax 50% bought back + burned, the rest to you (or --buyback-to)
105
107
  gang buyback status|set|set-payee|apply --token 0x… [--pct 0-100] [--to 0x…] # the buy-back splitter: ratio (raise now, cut after 3 days), payee (at once), what waits
108
+ gang create … --buy-tax 3 --sell-tax 3 --split self:60,0x…:30,0x…:10 [--dev-buy …] # V3: the recipient's part of the tax split among 1–10 payees at fixed shares (% summing to 100; self = you)
109
+ gang split status|distribute|release|set-payee|bind --token 0x… [--asset 0x…] [--index <i>] [--to 0x…] # the split module: payees (slot --index from 0), what waits / is owed; split by hand; a payee moves its own slot
106
110
  gang create --fair … [--shares <n>] --bond <quote> [--bond-hold …] --bond-days <7-90> # 打新: create (dev shares) → bond
107
111
  gang execute --request-id <id>
108
112
  gang tx --pending # trades approved in the Binance App: found by the exact call previewed, then as below
@@ -214,13 +218,13 @@ take MCP servers instead of a shell (Claude Desktop / Code, Cursor, …). Each t
214
218
 
215
219
  | Tool | Runs |
216
220
  |---|---|
217
- | `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, mint or withdraw |
221
+ | `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, mint or withdraw |
218
222
  | `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+) |
219
223
  | `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) |
220
224
  | `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 |
221
225
  | `gang_buy`, `gang_sell`, `gang_follow` | the trade previews (nothing is sent), with all their flags: `useWbnb` / `useQuote` / `payBnb`, `settleFirst`, … |
222
226
  | `gang_execute` | `gang execute --request-id …`: only after the user's yes on that preview |
223
- | `gang_cli` | every other command as an argument list: `create` (also `--fair` and a launch in one command), `mint`, `withdraw`, `claim`, `release`, `quote`, `list`, `upload-logo`, `bond …`, `buyback …`, `v3 income`, `version`, and the flags no other tool takes (`--calldata`, `--from`, …) |
227
+ | `gang_cli` | every other command as an argument list: `create` (also `--fair` and a launch in one command), `mint`, `withdraw`, `claim`, `release`, `quote`, `list`, `upload-logo`, `bond …`, `buyback …`, `split …`, `v3 income`, `version`, and the flags no other tool takes (`--calldata`, `--from`, …) |
224
228
 
225
229
  ```json
226
230
  { "mcpServers": { "gang": { "command": "gang", "args": ["mcp"] } } }
@@ -276,8 +280,9 @@ timed-out `gang_execute`, check `gang_status` / the wallet history instead of ex
276
280
  | `GANG_TESTNET_RPC_URL` | Testnet RPC, one URL or a comma list (unset: PublicNode, then BNB Chain's testnet nodes); old names `GANG_V3_TESTNET_RPC_URL` / `GANG_FAIR_TESTNET_RPC_URL` still work |
277
281
  | `GANG_FLY_PAD` / `GANG_TESTNET_FLY_PAD` | GangFlywheelPad (铸币飞轮). Defaults: mainnet `0x631e…B029` (open since 2026-10-30), testnet set 2 `0xD648…951c` |
278
282
  | `GANG_BOND` / `GANG_TESTNET_BOND` | GangBond (creator bonds, `gang bond`). Defaults: mainnet `0xe92d…14E4` (since 2026-10-29, CLI 0.16.2+), testnet `0xd6a8…1086` |
283
+ | `GANG_SPLIT_FACTORY` / `GANG_TESTNET_SPLIT_FACTORY` | GangSplitModuleFactory (`--split`). Defaults: mainnet `0x27e0…067c` (since 2026-10-30, CLI 0.19.0+), testnet set 10 `0x5F7d…567E` |
279
284
  | `GANG_ROUTER` / `GANG_TESTNET_ROUTER` | GangRouter proxy (native-BNB V3 buys / mints, and every PancakeSwap trade of a graduated token); old name `GANG_ROUTER_TESTNET` still works. Defaults: mainnet `0xE040…79C4`, testnet set 10 `0x6bB6…C9F6` |
280
285
 
281
286
  ## Version
282
287
 
283
- `0.18.3` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
288
+ `0.19.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
@@ -10,6 +10,8 @@
10
10
 
11
11
  **V3 税收币和打新(0.9.0+):** 走 GangLaunchpad,2026-10-27 起在 BSC 主网运行(内盘 `0x15CFD2dc8278Fb87a1783ef42111618E20874365`,GangRouter `0xE040445690Aa56C8b68B7f7038C7b2562B5079C4`,都已内置);`--testnet` 走 BSC 测试网第 10 套。
12
12
 
13
+ **多人分账收款(0.19.0+):** `gang create … --buy-tax … --sell-tax … --split self:60,0x…:30,0x…:10` 把 V3 币的税收接收地址设成 dev 自己的分账模块(GangSplitModule,`split-v1`):接收地址那份税按固定比例分给 1–10 个地址,名单和比例永久不能改(dev 和平台都改不了;每个收款人只能把自己那一份换到别的地址)。`self` 表示发币钱包(也可以写 `me`);收款人序号和合约一致,从 0 开始(`--index`)。报价币只能是 keeper 会分账的:WBNB(默认)、GANG 或发射台 QuoteRegistry 里的报价币(其他的在克隆前就拒绝,和 `--buyback` 一样);转进模块的其他资产仍可用 `gang split distribute` 手动分。`gang split …` 查看和操作。已在 BSC 主网(工厂 `0x27e08271E52B2D129c824CD245e69471a8d3067c`,2026-10-30 平台多签已放行,已内置)和测试网第 10 套可用。
14
+
13
15
  ## 安装
14
16
 
15
17
  Node ≥ 18。另需 `baw`:
@@ -83,6 +85,8 @@ gang bond burn --token <addr> | gang bond tx --hash <0x..> # 推进一块
83
85
  gang create … --dev-buy <报价币数量> [--bond <数量> [--bond-hold <枚数|N%|all>] --bond-days <7-90>] # V3:发币 → dev 内盘买入 → 押金
84
86
  gang create … --buy-tax 3 --sell-tax 3 --buyback 50 [--buyback-to 0x…] [--dev-buy …] # V3:接收地址那份税 50% 回购销毁,其余给你(或 --buyback-to 指定的地址)
85
87
  gang buyback status|set|set-payee|apply --token 0x… [--pct 0-100] [--to 0x…] # 回购合约:比例(提高立即生效,下调 3 天后)、收款地址(立即生效)、待回购金额
88
+ gang create … --buy-tax 3 --sell-tax 3 --split self:60,0x…:30,0x…:10 [--dev-buy …] # V3:接收地址那份税按固定比例分给 1–10 个地址(百分比合计 100;self = 你自己)
89
+ gang split status|distribute|release|set-payee|bind --token 0x… [--asset 0x…] [--index <i>] [--to 0x…] # 分账模块:名单(--index 从 0 开始)、待分和欠款;手动分账;收款人换自己的地址
86
90
  gang create --fair … [--shares <n>] --bond <数量> [--bond-hold …] --bond-days <7-90> # 打新:发币(含 dev 份额)→ 押金
87
91
  gang execute --request-id <id>
88
92
  gang tx --pending # 在 Binance App 里批准过的交易:按预览时的调用自动找到交易,再按下面这条处理
@@ -190,13 +194,13 @@ gang agents --window 30d --sort follow
190
194
 
191
195
  | 工具 | 对应 |
192
196
  |---|---|
193
- | `gang_help` | 本 CLI 的完整帮助(所有命令、所有参数)和完整规则(0.17.2+):没装 skill 的 Agent 在发币、一条命令发射、押金、回购、打新认购 / 撤回之前先读它 |
197
+ | `gang_help` | 本 CLI 的完整帮助(所有命令、所有参数)和完整规则(0.17.2+):没装 skill 的 Agent 在发币、一条命令发射、押金、回购、分账、打新认购 / 撤回之前先读它 |
194
198
  | `gang_preflight`、`gang_hot`、`gang_new`、`gang_near_grad`、`gang_info`、`gang_status`、`gang_portfolio`、`gang_notes`、`gang_agents` | 同名的只读命令(`gang_portfolio`:0.17.6+) |
195
199
  | `gang_tx` | `gang tx --hash …`:解码交易,发布排队中的想法;`pending: true` 即 `gang tx --pending`,找出在 Binance App 里批准过的交易(不用哈希) |
196
200
  | `gang_watch` | `gang watch`,等到 `maxEvents`(默认 1)条或 `timeout`(默认 50s,最长 30m):返回 `{ events, meta }`,没等到时带 `timedOut: true`,再调一次接着等 |
197
201
  | `gang_buy`、`gang_sell`、`gang_follow` | 交易预览(不发送),对应命令的参数都有:`useWbnb` / `useQuote` / `payBnb`、`settleFirst` 等 |
198
202
  | `gang_execute` | `gang execute --request-id …`:用户对这份预览点头之后才调 |
199
- | `gang_cli` | 其余所有命令,按参数数组传:`create`(也包括 `--fair` 和一条命令发射)、`mint`、`withdraw`、`claim`、`release`、`quote`、`list`、`upload-logo`、`bond …`、`buyback …`、`v3 income`、`version`,以及其他工具没有的参数(`--calldata`、`--from` 等) |
203
+ | `gang_cli` | 其余所有命令,按参数数组传:`create`(也包括 `--fair` 和一条命令发射)、`mint`、`withdraw`、`claim`、`release`、`quote`、`list`、`upload-logo`、`bond …`、`buyback …`、`split …`、`v3 income`、`version`,以及其他工具没有的参数(`--calldata`、`--from` 等) |
200
204
 
201
205
  ```json
202
206
  { "mcpServers": { "gang": { "command": "gang", "args": ["mcp"] } } }
@@ -240,8 +244,9 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
240
244
  | `GANG_TESTNET_RPC_URL` | 测试网 RPC,可填一个或逗号分隔的多个(不设时先用 PublicNode,再用 BNB Chain 的测试网节点);旧名 `GANG_V3_TESTNET_RPC_URL` / `GANG_FAIR_TESTNET_RPC_URL` 仍可用 |
241
245
  | `GANG_FLY_PAD` / `GANG_TESTNET_FLY_PAD` | GangFlywheelPad(铸币飞轮)。默认:主网 `0x631e…B029`(2026-10-30 起开放),测试网第 2 套 `0xD648…951c` |
242
246
  | `GANG_BOND` / `GANG_TESTNET_BOND` | GangBond(押金承诺,`gang bond`)。默认:主网 `0xe92d…14E4`(2026-10-29 起,CLI 0.16.2+),测试网 `0xd6a8…1086` |
247
+ | `GANG_SPLIT_FACTORY` / `GANG_TESTNET_SPLIT_FACTORY` | GangSplitModuleFactory(`--split`)。默认:主网 `0x27e0…067c`(2026-10-30 起,CLI 0.19.0+),测试网第 10 套 `0x5F7d…567E` |
243
248
  | `GANG_ROUTER` / `GANG_TESTNET_ROUTER` | GangRouter 代理(用原生 BNB 买 V3 / 打新,以及已毕业币的所有外盘买卖);旧名 `GANG_ROUTER_TESTNET` 仍可用。默认:主网 `0xE040…79C4`,测试网第 10 套 `0x6bB6…C9F6` |
244
249
 
245
250
  ## 版本
246
251
 
247
- `0.18.3` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
252
+ `0.19.0` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "@gangfun/cli",
3
- "version": "0.18.3",
3
+ "version": "0.19.0",
4
4
  "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
5
  "type": "module",
6
+ "scripts": {
7
+ "test": "for f in test/*.mjs; do node \"$f\" || exit 1; done"
8
+ },
6
9
  "bin": {
7
10
  "gang": "./src/index.js"
8
11
  },
package/src/index.js CHANGED
@@ -20,6 +20,7 @@ import { runFair, FAIR_EVENT_ABIS } from './fair.js'
20
20
  import { runV3, v3Ctx, V3_EVENT_ABIS } from './v3.js'
21
21
  import { runBond } from './bond.js'
22
22
  import { runBuyback } from './buyback.js'
23
+ import { runSplit, SPLIT_EVENT_ABIS } from './split.js'
23
24
  import { runFly, flyCtx, isFlyToken, FLY_EVENT_ABIS, FLY_CREATE_FLAGS } from './fly.js'
24
25
  import { FAIR_DEV_BUY, isLaunch, LAUNCH_FLAGS, runLaunch } from './launch.js'
25
26
  import { poolPayBnb, poolTrade } from './pool.js'
@@ -341,6 +342,17 @@ U / S pads) and run that kind's trade. Results of V3 / 打新 / 铸币飞轮 tok
341
342
  (GangBuybackSplitterFactory; listed as a recipient in the same tx) → create with it as
342
343
  the recipient → bind → the rest of the launch. Without --buyback the tax goes to you.
343
344
  Quote: WBNB (default), GANG or one listed in the pad's QuoteRegistry only
345
+ gang create … --buy-tax <1-5> --sell-tax <1-5> --split <addr>:<pct>[,<addr>:<pct>…] [--dev-buy … [--bond …]]
346
+ V3, taxed: the recipient's part of the tax is split among 1–10 payees at fixed shares
347
+ (% with up to 2 decimals, at least 0.01, adding up to 100; the first payee also takes
348
+ the rounding dust), e.g. --split self:60,0xKol…:30,0xDao…:10 (self = your wallet, me
349
+ works too; payee slots are the contract's 0-based index, here 0, 1, 2). PERMANENT:
350
+ nobody (not you, not the platform) can change the payees or shares later; a payee can
351
+ only move its own slot (gang split set-payee). Steps: clone your split module
352
+ (GangSplitModuleFactory; listed as a recipient in the same tx) → create with it as the
353
+ recipient → bind → the rest of the launch. --split, --buyback and --recipient are
354
+ exclusive. Quote: WBNB (default), GANG or one listed in the pad's QuoteRegistry only
355
+ (the quotes the keeper splits; others are refused before the clone)
344
356
  gang create --fair … [--shares <n>] --bond <quote> [--bond-hold …] --bond-days <7-90>
345
357
  打新: create (the dev's --shares are bought in it) → bond. Progress is read from the
346
358
  chain (a token this wallet created with this symbol since the plan); a run that finds
@@ -414,6 +426,26 @@ BUYBACK (a V3 token whose recipient is a buy-back splitter; GANG_SPLITTER_FACTOR
414
426
  gang buyback bind --token <addr> | gang buyback release --token <addr>
415
427
  anyone: bind the splitter to its token (the launch does it) / push the payee what a
416
428
  failed payment left owed. --testnet, --calldata, --from as in gang v3
429
+ SPLIT (a V3 token whose recipient is a split module, split-v1; GANG_SPLIT_FACTORY / GANG_TESTNET_SPLIT_FACTORY):
430
+ gang split status --token <addr> payees and shares (fixed), the dev, the bound token / quote, what waits to be split
431
+ and what each slot is owed (bound quote, WBNB, GANG, the token's quote), whether the
432
+ keeper is due and serves the quote (WBNB, GANG, a QuoteRegistry quote; any other
433
+ quote, and any other asset sent to the module, is split by hand), next commands
434
+ gang split distribute --token <addr> [--asset <addr>|wbnb]
435
+ anyone: split what of the asset (default the bound quote) arrived since its last split
436
+ gang split release --token <addr> [--asset <addr>] [--index <i>] [--max <amount>]
437
+ anyone: push a slot what a failed push left owed (default all; --index = the
438
+ contract's 0-based slot, default your own slot or the only one owed)
439
+ gang split set-payee --token <addr> --to <addr> [--index <i>]
440
+ only the slot's current payee (--index = the contract's 0-based slot, default your
441
+ wallet's own): moves the slot to --to at once, the share stays. Splits WBNB / GANG /
442
+ other known assets waiting in the module first (one tx each, then re-run), so they go
443
+ to the current address
444
+ gang split bind --token <addr> anyone: bind the module to its token (the launch does it)
445
+ --module <addr> instead of --token names a module directly (not for bind).
446
+ Gas: the CLI never sets a gas limit on these; let the wallet estimate it. Each payee's
447
+ push needs ~365k gas left before it, so the limit is far above the gas used; a lower
448
+ limit reverts PushStarved. --testnet, --calldata, --from as in gang v3
417
449
  gang execute --request-id <id> broadcast a previewed call
418
450
  gang tx --pending a trade that waited for Binance App approval (execute: pendingConfirmation): find its tx
419
451
  in the wallet's history by the exact call previewed, then as gang tx --hash below
@@ -952,7 +984,7 @@ const V3_CREATE_FLAGS = ['buy-tax', 'sell-tax', 'dividend', 'recipient']
952
984
  const FAIR_CREATE_FLAGS = ['raise', 'cap', 'hold', 'mint-fee', 'exit-fee', 'shares']
953
985
  // 铸币飞轮 settings beyond those it shares with 打新 (--raise / --hold / --mint-fee / --exit-fee) and V3 (--sell-tax)
954
986
  const FLY_ONLY_FLAGS = FLY_CREATE_FLAGS.filter((f) => !['raise', 'hold', 'mint-fee', 'exit-fee', 'sell-tax'].includes(f))
955
- const FLY_NO_BOND = '铸币飞轮 tokens take no GangBond, buy-back splitter or --dev-buy (phase 1): the creator mints its shares in the create with --dev-shares <n>'
987
+ const FLY_NO_BOND = '铸币飞轮 tokens take no GangBond, buy-back splitter, split module or --dev-buy (phase 1): the creator mints its shares in the create with --dev-shares <n>'
956
988
  /** The flags a 铸币飞轮 create refuses (gang create --fly and gang fly create alike). */
957
989
  function checkFlyCreate() {
958
990
  if (flag('fair')) fail('give --fly (铸币飞轮) or --fair (打新), not both')
@@ -986,11 +1018,11 @@ function create() {
986
1018
  // commands whose JSON result carries `update`; `watch` streams NDJSON and help is plain text
987
1019
  const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'portfolio', 'quote',
988
1020
  'buy', 'follow', 'sell', 'claim', 'mint', 'withdraw', 'release', 'upload-logo', 'create', 'execute', 'tx', 'fair', 'v3', 'bond',
989
- 'buyback', 'fly'])
1021
+ 'buyback', 'split', 'fly'])
990
1022
  // gang tx decodes these beside the V2 / Soft / U / S pads' events (GangLaunchpad: both kinds; the tax router; the vaults)
991
- const GANG_EVENT_ABIS = [...V3_EVENT_ABIS, ...FAIR_EVENT_ABIS, ...FLY_EVENT_ABIS]
1023
+ const GANG_EVENT_ABIS = [...V3_EVENT_ABIS, ...FAIR_EVENT_ABIS, ...FLY_EVENT_ABIS, ...SPLIT_EVENT_ABIS]
992
1024
 
993
- /** gang bond / gang buyback on a 铸币飞轮 token: both contracts refuse it, so say why before any step. */
1025
+ /** gang bond / gang buyback / gang split on a 铸币飞轮 token: those contracts refuse it, so say why before any step. */
994
1026
  async function refuseFly(what) {
995
1027
  const token = opt('token')
996
1028
  if (!isAddress(token ?? '')) return
@@ -1081,7 +1113,7 @@ async function main() {
1081
1113
  // a 打新 dev buys with --shares in the create itself: say so here, not "add --bond" (which would only lead to that)
1082
1114
  if (launchKind === 'fair' && flag('dev-buy')) fail(FAIR_DEV_BUY)
1083
1115
  const lone = LAUNCH_FLAGS.find((f) => flag(f))
1084
- if (lone) fail(`--${lone} only applies to a launch in one command: add --bond <quote>${launchKind === 'fair' ? '' : ' (or --dev-buy <quote> / --buyback <pct>)'}`)
1116
+ if (lone) fail(`--${lone} only applies to a launch in one command: add --bond <quote>${launchKind === 'fair' ? '' : ' (or --dev-buy <quote> / --buyback <pct> / --split <addr>:<pct>,…)'}`)
1085
1117
  }
1086
1118
  switch (cmd) {
1087
1119
  case 'fair':
@@ -1101,6 +1133,9 @@ async function main() {
1101
1133
  case 'buyback':
1102
1134
  await refuseFly('a buy-back splitter')
1103
1135
  return runBuyback(args[1], { opt, flag, out, fail, summarize: summarizePreview })
1136
+ case 'split':
1137
+ await refuseFly('a split module')
1138
+ return runSplit(args[1], { opt, flag, out, fail, summarize: summarizePreview })
1104
1139
  case 'version':
1105
1140
  case '--version':
1106
1141
  case '-v':
package/src/launch.js CHANGED
@@ -8,6 +8,7 @@ import { bondAddress, BOND_ABI } from './bond.js'
8
8
  import { walletFor } from './fair.js'
9
9
  import { parseAmount, parseIntIn, step } from './steps.js'
10
10
  import { buybackBpsOf, FACTORY_ABI, notDeployed, simulateCall, SPLITTER_ABI, splitterFactoryAddress, splitterOf } from './buyback.js'
11
+ import { parseSplitSpec, simulateSplit, SPLIT_ABI, SPLIT_FACTORY_ABI, splitFactoryAddress, splitLine, splitNotDeployed, splitOf } from './split.js'
11
12
 
12
13
  /**
13
14
  * One command for a launch: `gang create … [--buyback <pct>] [--dev-buy <quote> [--bond <quote> [--bond-hold <tokens|N%|all>]
@@ -27,6 +28,10 @@ import { buybackBpsOf, FACTORY_ABI, notDeployed, simulateCall, SPLITTER_ABI, spl
27
28
  * launch's), the create names it as the recipient, and a bind step follows the create. A launch keeps the mode it began
28
29
  * with: adding --buyback after the create (or dropping it before) is refused rather than starting over.
29
30
  * --buyback-to <addr> names where the dev's part goes (default: the dev); the dev can change it later at once.
31
+ * --split <addr>:<pct>[,…] (V3, taxed): the same three steps with GangSplitModuleFactory — the dev's split module (fixed
32
+ * payees and shares, split-v1) is cloned at predict(dev, salt), named as the recipient, then bound. The plan keeps which
33
+ * module it cloned (`module: 'split'`; a plan without it is a --buyback one), and a re-run with other payees or shares is
34
+ * refused rather than starting over. --buyback, --split and --recipient are exclusive (each sets the recipient).
30
35
  */
31
36
 
32
37
  const LAUNCH_DIR = process.env.GANG_LAUNCH_DIR || join(dirname(DIR), 'launch')
@@ -48,9 +53,21 @@ const REGISTRY_ABI = parseAbi(['function quoteRegistry() view returns (address)'
48
53
  * --buyback only over a quote gang.fun trusts (WBNB, GANG, or listed in the pad's QuoteRegistry): a splitter prices each
49
54
  * buy-back chunk on what it sends, so a quote that taxes transfers into pairs fails the pair's K check on every chunk
50
55
  * and the buy-back part is stuck for good (GangBond re-review L-1, 2026-10-29; splitter v3 has the same pricing).
56
+ * --split takes the same quotes: a quote that calls the receiver back on transfer would let one payee make every split
57
+ * run out of gas, and the keeper splits only these quotes anyway (split spec §2.4).
51
58
  * null when trusted; otherwise the failure to report.
52
59
  */
53
- async function untrustedBuybackQuote(read, net, quote) {
60
+ const UNTRUSTED = {
61
+ buyback: {
62
+ why: '--buyback needs WBNB, GANG or a quote listed in the pad\'s QuoteRegistry: the buy-back splitter cannot buy back with a quote that taxes transfers into the pair, and an unlisted quote may do that',
63
+ hint: 'drop --quote (WBNB), use a listed quote, or launch without --buyback',
64
+ },
65
+ split: {
66
+ why: '--split needs WBNB, GANG or a quote listed in the pad\'s QuoteRegistry: the keeper splits only those quotes, and an unlisted quote may call the receiver back on transfer, letting one payee make every split run out of gas',
67
+ hint: 'drop --quote (WBNB), use a listed quote, or launch without --split',
68
+ },
69
+ }
70
+ export async function untrustedBuybackQuote(read, net, quote, mode = 'buyback') {
54
71
  if (!isAddress(quote ?? '')) return { error: '--quote must be a 0x address', got: quote ?? null }
55
72
  const q = quote.toLowerCase()
56
73
  if (q === String(net.wbnb).toLowerCase() || (String(net.chainId) === '56' && q === MAINNET_GANG_TOKEN)) return null
@@ -61,19 +78,19 @@ async function untrustedBuybackQuote(read, net, quote) {
61
78
  if (listed) return null
62
79
  return {
63
80
  error: listed === null
64
- ? 'could not read the pad\'s QuoteRegistry to check the --buyback quote: try again'
65
- : '--buyback needs WBNB, GANG or a quote listed in the pad\'s QuoteRegistry: the buy-back splitter cannot buy back with a quote that taxes transfers into the pair, and an unlisted quote may do that',
66
- quote, hint: 'drop --quote (WBNB), use a listed quote, or launch without --buyback',
81
+ ? `could not read the pad's QuoteRegistry to check the --${mode} quote: try again`
82
+ : UNTRUSTED[mode].why,
83
+ quote, hint: UNTRUSTED[mode].hint,
67
84
  }
68
85
  }
69
86
 
70
- export const LAUNCH_FLAGS = ['dev-buy', 'bond', 'bond-hold', 'bond-days', 'buyback', 'buyback-to', 'restart']
87
+ export const LAUNCH_FLAGS = ['dev-buy', 'bond', 'bond-hold', 'bond-days', 'buyback', 'buyback-to', 'split', 'restart']
71
88
  const NOTE_FLAGS = ['note', 'conf', 'reveal-after']
72
89
  /** `gang fair create --dev-buy`, with or without --bond (index.js stops the lone flag, runLaunch the chained one). */
73
90
  export const FAIR_DEV_BUY = 'a 打新 dev buys its shares in the create itself: use --shares <n> (not --dev-buy)'
74
91
 
75
92
  /** The run asks for a chained launch (`kind` 'v3' | 'fair'). */
76
- export const isLaunch = (kind, flag) => flag('bond') || flag('buyback') || (kind === 'v3' && flag('dev-buy'))
93
+ export const isLaunch = (kind, flag) => flag('bond') || flag('buyback') || flag('split') || (kind === 'v3' && flag('dev-buy'))
77
94
 
78
95
  const planPath = (key) => join(LAUNCH_DIR, `${createHash('sha256').update(key).digest('hex').slice(0, 32)}.json`)
79
96
 
@@ -117,6 +134,8 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
117
134
  if (flag('follow')) fail('--follow does not apply to a launch')
118
135
  if (kind === 'fair' && flag('dev-buy')) fail(FAIR_DEV_BUY)
119
136
  if (kind === 'fair' && flag('buyback')) fail('--buyback is for V3 tokens: it makes the tax recipient a buy-back splitter, and a 打新 token has no recipient')
137
+ if (kind === 'fair' && flag('split')) fail('--split is for V3 tokens: it makes the tax recipient a split module, and a 打新 token has no recipient')
138
+ if (flag('split') && flag('buyback')) fail('give --split or --buyback, not both: each makes the tax recipient its own module (a split with a buy-back is not supported)')
120
139
 
121
140
  // everything checked before the create, so a launch never stops half way on a bad flag
122
141
  const devBuy = kind === 'v3' && flag('dev-buy') ? parseAmount(fail, 'dev-buy', opt('dev-buy')) : null
@@ -154,11 +173,33 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
154
173
  buyback = { bps: buybackBpsOf(fail, opt('buyback')), factory, payee }
155
174
  }
156
175
 
176
+ const me = walletFor({ chainId: net.chainId }, opt('from'))
177
+
178
+ // --split: a taxed V3 token whose recipient is the dev's split module (fixed payees and shares)
179
+ let split = null
180
+ if (flag('split')) {
181
+ const zero = (f) => /^0+(\.0+)?$/.test(opt(f) ?? '')
182
+ if (!flag('buy-tax') || !flag('sell-tax') || (zero('buy-tax') && zero('sell-tax'))) {
183
+ fail('--split needs a taxed token: add --buy-tax and --sell-tax (each 1–5, in %); the split is paid from the tax')
184
+ }
185
+ if (flag('recipient')) fail('--split makes the recipient your split module: leave --recipient out')
186
+ if (/^0*100(\.0+)?$/.test(opt('dividend', '0'))) fail('--dividend 100 leaves nothing for the recipient, so nothing to split: lower it or drop --split')
187
+ const factory = splitFactoryAddress(testnet)
188
+ if (!factory) fail(splitNotDeployed(testnet))
189
+ const spec = parseSplitSpec(opt('split'), me)
190
+ if (spec.error) {
191
+ const { error, ...extra } = spec
192
+ fail(error, extra)
193
+ }
194
+ split = { ...spec, factory }
195
+ }
196
+ const mod = buyback ? 'buyback' : split ? 'split' : null
197
+
157
198
  const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
158
199
  const read = (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args })
159
- const me = walletFor({ chainId: net.chainId }, opt('from'))
160
200
  const key = [net.chainId, net.pad, me.toLowerCase(), kind, name, symbol].join('|')
161
- const steps = [...(buyback ? ['buyback-splitter'] : []), kind === 'v3' ? 'create' : 'create (dev shares included)', ...(buyback ? ['bind'] : []),
201
+ const cloneStep = buyback ? 'buyback-splitter' : 'split-module'
202
+ const steps = [...(mod ? [cloneStep] : []), kind === 'v3' ? 'create' : 'create (dev shares included)', ...(mod ? ['bind'] : []),
162
203
  ...(devBuy ? ['dev-buy'] : []), ...(bond ? ['bond'] : [])]
163
204
  const rerun = 're-run this same command after executing it'
164
205
  const tag = (stage, extra = {}) => ({ launch: { stage, steps, ...extra } })
@@ -169,11 +210,13 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
169
210
 
170
211
  // ---- a launch keeps the mode it began with (the create, once built, is never redone by a changed flag)
171
212
  const created = plan?.startCount !== undefined
172
- if (buyback && created && !plan.splitter) {
173
- return fail('this launch was created without --buyback (its recipient is fixed): run it again without --buyback, or add --restart for a new token')
213
+ // the module this plan cloned: 'split' when it says so, else a --buyback splitter (plans from before --split)
214
+ const planMod = plan?.salt ? (plan.module === 'split' ? 'split' : 'buyback') : null
215
+ if (mod && created && !plan.splitter) {
216
+ return fail(`this launch was created without --${mod} (its recipient is fixed): run it again without --${mod}, or add --restart for a new token`)
174
217
  }
175
- if (!buyback && !created && plan?.salt) {
176
- return fail('this launch began with --buyback (its splitter is cloned or on the way): run it again with --buyback, or add --restart without it')
218
+ if (planMod && mod !== planMod && (!created || mod)) {
219
+ return fail(`this launch began with --${planMod} (its ${planMod === 'split' ? 'split module' : 'splitter'} is cloned or on the way): run it again with --${planMod}${mod ? ` instead of --${mod}` : ''}, or add --restart${mod ? '' : ` without it`}`)
177
220
  }
178
221
 
179
222
  // ---- buy-back splitter: cloned for the dev before the create, at predict(dev, plan.salt)
@@ -220,6 +263,47 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
220
263
  }
221
264
  }
222
265
 
266
+ // ---- split module: cloned for the dev before the create, at predict(dev, plan.salt)
267
+ if (split && !created) {
268
+ if (!plan?.salt) {
269
+ const refused = await untrustedBuybackQuote(read, net, flag('quote') ? opt('quote') : net.wbnb, 'split')
270
+ if (refused) {
271
+ const { error, ...extra } = refused
272
+ return fail(error, extra)
273
+ }
274
+ const salt = `0x${randomBytes(32).toString('hex')}`
275
+ const at = await read(split.factory, SPLIT_FACTORY_ABI, 'predict', [me, salt])
276
+ if (split.payees.some((p) => p.toLowerCase() === at.toLowerCase())) return fail('--split: a payee cannot be the split module itself', { module: at })
277
+ const args = [split.payees, split.shares, salt]
278
+ const sim = await simulateSplit(client, me, split.factory, SPLIT_FACTORY_ABI, 'create', args)
279
+ if (sim.failed) return out({ success: false, step: 'split-module', factory: split.factory, ...tag('split-module'), ...sim.failed })
280
+ writePlan(key, { ...base, salt, splitter: at, factory: split.factory, module: 'split' })
281
+ const data = encodeFunctionData({ abi: SPLIT_FACTORY_ABI, functionName: 'create', args })
282
+ return out({
283
+ ...step({ chainId: net.chainId }, { from: me, to: split.factory, data }, {
284
+ step: 'split-module', chainId: Number(net.chainId), factory: split.factory, module: at, payees: split.list,
285
+ note: `clones your split module (listed as a tax recipient in the same tx). The recipient's part of the tax is split ${splitLine(split.payees, split.shares)}. PERMANENT: nobody (not you, not the platform) can change the payees or shares later; each payee can only move its own slot to another address (gang split set-payee). The first payee also takes the rounding dust`,
286
+ }, flag('calldata'), io.summarize),
287
+ ...tag('split-module', { module: at, next: `${rerun}: it then builds the create with the module as the recipient` }),
288
+ })
289
+ }
290
+ if ((await client.getCode({ address: plan.splitter }) ?? '0x') === '0x') {
291
+ return out({
292
+ success: false, ...tag('split-module', { module: plan.splitter }), error: 'the split module is not on chain yet',
293
+ hint: `if the clone was executed, wait for it to land and ${rerun.replace(' after executing it', '')}; if it was not, add --restart to build it again`,
294
+ })
295
+ }
296
+ const s = await splitOf(read, plan.splitter, { wbnb: net.wbnb })
297
+ if (!s || s.dev.toLowerCase() !== me.toLowerCase() || s.token) {
298
+ return fail('the module at this launch\'s address is not an unbound split module of this wallet: add --restart', { module: plan.splitter })
299
+ }
300
+ const same = s.payees.length === split.payees.length
301
+ && s.payees.every((p, i) => p.payee.toLowerCase() === split.payees[i].toLowerCase() && p.bps === split.shares[i])
302
+ if (!same) {
303
+ return fail(`this launch's split module pays ${splitLine(s.payees.map((p) => p.payee), s.payees.map((p) => p.bps))}, not what --split says: run it again with that --split, or add --restart for a new module (the payees and shares can never change after the clone)`, { module: plan.splitter })
304
+ }
305
+ }
306
+
223
307
  // ---- create
224
308
  if (!created) {
225
309
  const startCount = (await read(net.pad, PAD_ABI, 'tokenCount')).toString()
@@ -230,7 +314,7 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
230
314
  // the plan starts with the create tx itself: a wrap / approve step before it (or a failed preview) leaves none,
231
315
  // so the next run builds the create again
232
316
  const built = o.success && o.step === 'create'
233
- if (built) writePlan(key, { ...base, ...(plan?.splitter && { salt: plan.salt, splitter: plan.splitter, factory: plan.factory }), startCount })
317
+ if (built) writePlan(key, { ...base, ...(plan?.splitter && { salt: plan.salt, splitter: plan.splitter, factory: plan.factory, ...(plan.module && { module: plan.module }) }), startCount })
234
318
  const after = steps[steps.indexOf(kind === 'v3' ? 'create' : 'create (dev shares included)') + 1]
235
319
  return out({
236
320
  ...o,
@@ -268,7 +352,9 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
268
352
  // later steps carry no note (it went on the create) and take the token from the plan
269
353
  const stepIo = (over) => ({ ...io, ...argsWith(io, { ...over, token }, [...LAUNCH_FLAGS, ...NOTE_FLAGS, 'name', 'symbol']) })
270
354
  const bal = await read(token, ERC20_ABI, 'balanceOf', [me])
271
- const buybackState = () => (plan.splitter ? splitterOf(read, plan.splitter) : null)
355
+ const isSplit = plan.module === 'split'
356
+ const buybackState = () => (plan.splitter && !isSplit ? splitterOf(read, plan.splitter) : null)
357
+ const splitState = () => (plan.splitter && isSplit ? splitOf(read, plan.splitter, { wbnb: net.wbnb, ref: `--token ${token}${testnet ? ' --testnet' : ''}` }) : null)
272
358
 
273
359
  // ---- done: the report only, whatever happened to the balance or the bond since
274
360
  const report = async () => {
@@ -278,28 +364,33 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
278
364
  }
279
365
  const bb = await buybackState()
280
366
  if (bb) done.buyback = bb
367
+ const sp = await splitState()
368
+ if (sp) done.split = sp
281
369
  if (!bond) return out({ ...done, note: `launched: gang ${kind} info --token ${token}${testnet ? ' --testnet' : ''}` })
282
370
  return runBond('status', { ...stepIo({}), out: (o) => out({ ...done, bondStatus: o, note: `launched and bonded: gang bond status --token ${token}${testnet ? ' --testnet' : ''}` }) })
283
371
  }
284
372
  if (plan.done) return report()
285
373
 
286
- // ---- bind the splitter to the token (anyone may; the launch does it right after the create)
374
+ // ---- bind the splitter / split module to the token (anyone may; the launch does it right after the create)
287
375
  if (plan.splitter) {
288
- const bound = await read(plan.splitter, SPLITTER_ABI, 'token')
376
+ const abi = isSplit ? SPLIT_ABI : SPLITTER_ABI
377
+ const bound = await read(plan.splitter, abi, 'token')
289
378
  if (bound === zeroAddress) {
290
- const sim = await simulateCall(client, me, plan.splitter, SPLITTER_ABI, 'bind', [token])
379
+ const sim = await (isSplit ? simulateSplit : simulateCall)(client, me, plan.splitter, abi, 'bind', [token])
291
380
  if (sim.failed) return out({ success: false, step: 'bind', ...tag('bind', { token }), ...sim.failed })
292
- const data = encodeFunctionData({ abi: SPLITTER_ABI, functionName: 'bind', args: [token] })
381
+ const data = encodeFunctionData({ abi, functionName: 'bind', args: [token] })
293
382
  return out({
294
383
  ...step({ chainId: net.chainId }, { from: me, to: plan.splitter, data }, {
295
- step: 'bind', chainId: Number(net.chainId), token, splitter: plan.splitter,
296
- note: 'ties the splitter to this token for good (what it buys back and burns)',
384
+ step: 'bind', chainId: Number(net.chainId), token, ...(isSplit ? { module: plan.splitter } : { splitter: plan.splitter }),
385
+ note: isSplit
386
+ ? 'ties the split module to this token for good: the keeper then splits its quote among the payees'
387
+ : 'ties the splitter to this token for good (what it buys back and burns)',
297
388
  }, flag('calldata'), io.summarize),
298
389
  ...tag('bind', { token, next: `${rerun}${devBuy ? ': it continues with the dev buy' : bond ? ': it continues with the bond' : ': the launch is then done'}` }),
299
390
  })
300
391
  }
301
392
  if (bound.toLowerCase() !== token.toLowerCase()) {
302
- return out({ success: false, ...tag('bind', { token }), error: 'the splitter is bound to another token', splitter: plan.splitter, boundTo: bound })
393
+ return out({ success: false, ...tag('bind', { token }), error: `the ${isSplit ? 'split module' : 'splitter'} is bound to another token`, [isSplit ? 'module' : 'splitter']: plan.splitter, boundTo: bound })
303
394
  }
304
395
  }
305
396
 
package/src/mcp.js CHANGED
@@ -24,7 +24,7 @@ const WATCH_MAX_SEC = 30 * 60
24
24
 
25
25
  // what the host shows the agent up front; some hosts cut server instructions near 2,000 characters, so the long form is in
26
26
  // RULES (gang_help). Keep both in step with skill/SKILL.md "Hard rules"
27
- const INSTRUCTIONS = `Gang (gang.fun): agent-only token launchpad on BNB Chain. Curve trades need a Binance Agentic Wallet with a .ai Agent ID: call gang_preflight first, relay each issues[].fix. Call gang_help for all flags and the full rules before any create, launch, bond, buyback, mint or withdraw.
27
+ const INSTRUCTIONS = `Gang (gang.fun): agent-only token launchpad on BNB Chain. Curve trades need a Binance Agentic Wallet with a .ai Agent ID: call gang_preflight first, relay each issues[].fix. Call gang_help for all flags and the full rules before any create, launch, bond, buyback, split, mint or withdraw.
28
28
  Hard rules:
29
29
  - Preview -> show the user -> wait for a yes -> gang_execute. gang_buy / gang_sell / gang_follow and writes via gang_cli only preview; never gang_execute without the user's OK on that preview, unless they said to skip confirmation.
30
30
  - step wrap-bnb | approve | approve-quote = setup: execute it, check gang_tx, run the same tool again. A launch in one command is re-run until launch.stage is done.
@@ -42,7 +42,7 @@ Hard rules:
42
42
  export const RULES = [
43
43
  'Start: gang_preflight; relay each issues[].fix. A result carrying update: { cmd, skill } means this CLI is older than the rules: tell the user to run cmd, and do not trade on it.',
44
44
  'Preview -> show -> confirm -> execute. Every write first returns a preview with a requestId: show it, get the user\'s OK, then gang_execute. Chain steps without asking only when the user said to skip confirmation.',
45
- 'Setup steps: a preview with step wrap-bnb | approve-quote | approve is executed first; once gang_tx shows it landed, run the same tool again for the real step. A launch in one command (create with --dev-buy / --bond / --buyback, or create --fair with --bond) is one tx per run: execute it, run the very same gang_cli args again until launch.stage is done.',
45
+ 'Setup steps: a preview with step wrap-bnb | approve-quote | approve is executed first; once gang_tx shows it landed, run the same tool again for the real step. A launch in one command (create with --dev-buy / --bond / --buyback / --split, or create --fair with --bond) is one tx per run: execute it, run the very same gang_cli args again until launch.stage is done.',
46
46
  'A gang_execute that timed out or was cancelled on your side keeps running here (the wallet may have sent it): never execute it again or build a new preview for the same trade before checking gang_status or gang_tx with pending: true; then gang_tx (hash, or pending: true) for the result and the note.',
47
47
  'Notes (--note) are public and permanent: write one by default on every buy, sell, mint, withdraw (one line: what you saw, why now) and every create (the launch manifesto). Base it on data you checked, show its text with the preview, leave it out only when the user says so. No links. --conf is an honest 0-100.',
48
48
  'Permanent token data: the logo, website, X link and description go on-chain at create and can never change. Use only links the user gave; ask once if they have not said. Never host a logo on a temporary file host. Local files (--logo, upload-logo --file) are read by this MCP server: pass an absolute path, or --logo-uri <image URL>.',
@@ -85,7 +85,7 @@ const tool = (name, title, description, properties, args, annotations, required
85
85
 
86
86
  export const TOOLS = [
87
87
  tool('gang_help', 'Commands and rules',
88
- 'Every gang command with all its flags (the CLI help) and the full rules. Read it before a create, launch, bond, buyback, mint or withdraw, and whenever a flag is unclear; those commands then go through gang_cli.',
88
+ 'Every gang command with all its flags (the CLI help) and the full rules. Read it before a create, launch, bond, buyback, split, mint or withdraw, and whenever a flag is unclear; those commands then go through gang_cli.',
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),
@@ -175,7 +175,7 @@ export const TOOLS = [
175
175
  { hash: HASH, pending: { type: 'boolean', description: 'Find the txs of trades approved in the Binance App (no hash needed)' }, testnet: TESTNET },
176
176
  (a) => (a.pending ? ['tx', '--pending'] : ['tx', '--hash', a.hash, ...bool('testnet', a.testnet)]), PREVIEW),
177
177
  tool('gang_cli', 'Other gang commands',
178
- 'Every other gang command, its flags as separate items (gang_help lists them all): create (V3; create --fair = fair mint; create --fly = Mint Flywheel; launch in one command with --dev-buy / --bond / --buyback), mint (--ref <inviter> on a Mint Flywheel token), withdraw, claim, release, fly open-early|launch|invite, quote, list, upload-logo, bond post|topup|raise-hold|extend|status|start|report|settle|refund|burn|tx, buyback status|set|set-payee|apply|bind|release, v3 income, version; the flags no other tool takes (--calldata, --from, …) too. E.g. ["create","--name","My Token","--symbol","MYT","--logo","/Users/me/avatar.png"], ["bond","status","--token","0x…"]. Local files are read by this server: absolute paths, or --logo-uri <image URL>. Writes only preview, as above. execute / watch / help have their own tools.',
178
+ 'Every other gang command, its flags as separate items (gang_help lists them all): create (V3; create --fair = fair mint; create --fly = Mint Flywheel; launch in one command with --dev-buy / --bond / --buyback / --split), mint (--ref <inviter> on a Mint Flywheel token), withdraw, claim, release, fly open-early|launch|invite, quote, list, upload-logo, bond post|topup|raise-hold|extend|status|start|report|settle|refund|burn|tx, buyback status|set|set-payee|apply|bind|release, split status|distribute|release|set-payee|bind, v3 income, version; the flags no other tool takes (--calldata, --from, …) too. E.g. ["create","--name","My Token","--symbol","MYT","--logo","/Users/me/avatar.png"], ["bond","status","--token","0x…"]. Local files are read by this server: absolute paths, or --logo-uri <image URL>. Writes only preview, as above. execute / watch / help have their own tools.',
179
179
  { args: { type: 'array', items: { type: 'string' }, minItems: 1 } }, (a) => a.args, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, ['args']),
180
180
  ]
181
181
  const BY_NAME = new Map(TOOLS.map((t) => [t.name, t]))
package/src/split.js ADDED
@@ -0,0 +1,429 @@
1
+ import { createPublicClient, parseAbi, encodeFunctionData, formatUnits, getAddress, hexToString, isAddress, maxUint256, parseUnits, zeroAddress } from 'viem'
2
+ import { padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
3
+ import { walletFor } from './fair.js'
4
+ import { parseAmount, revertOf as revertIn, step } from './steps.js'
5
+
6
+ /**
7
+ * `gang split …` and `gang create … --split <addr>:<pct>[,…]` — GangSplitModule (多人分账, `split-v1`): a V3 token's tax
8
+ * recipient that splits everything it receives among 1–10 payees at shares fixed when it is cloned (summing to 100%).
9
+ * Nobody — not the dev, not the platform — can change the payees or the shares; a payee can only move its own slot to
10
+ * another address (`setPayee`). GangSplitModuleFactory clones one for the dev (`create(payees, shares, salt)`, at
11
+ * `predict(dev, salt)`) and has GangHandlerAdmin list it, so the dev names it as the recipient at create (launch.js does
12
+ * the three steps: clone → create → bind, as for --buyback).
13
+ * Every asset that reaches the module is split at the same shares (`distribute(asset)`, anyone); the keeper splits only
14
+ * the bound quote, and only when it serves that quote (`keeperServes`: WBNB, GANG, a QuoteRegistry quote).
15
+ * Gas: each payee's push needs about 365k gas left before it (PUSH_GAS 300k × 64/63 + a 60k reserve), so a split needs a
16
+ * gas limit far above the gas it uses. The CLI never sets or lowers one: the wallet / node estimates it (eth_estimateGas
17
+ * searches for a limit that passes); a lower limit reverts PushStarved, and nothing moves.
18
+ * Env: GANG_SPLIT_FACTORY / GANG_TESTNET_SPLIT_FACTORY override the built-in factory addresses.
19
+ */
20
+
21
+ // BSC 56: deployed 2026-10-30, allowed on GangHandlerAdmin by the platform's Safe the same day (docs/MAINNET-SPLIT-MODULE-2026-10-30.md)
22
+ export const MAINNET_SPLIT_FACTORY = '0x27e08271E52B2D129c824CD245e69471a8d3067c'
23
+ // BSC 97, set 10 (docs/TESTNET-SPLIT-MODULE-2026-10-30.md)
24
+ export const TESTNET_SPLIT_FACTORY = '0x5F7dC7502E945A860Cf49cca72dA8bD60Fb1567E'
25
+ export const SPLIT_TYPE = 'split-v1'
26
+ export const MAX_PAYEES = 10
27
+ const BPS = 10_000
28
+
29
+ const ERRORS = [
30
+ 'error ZeroAddress()', 'error NotClone()', 'error NotFactory()', 'error AlreadyInitialized()', 'error BadPayees()',
31
+ 'error BadShares()', 'error BadPayee()', 'error DuplicatePayee()', 'error BadIndex()', 'error NotPayee()',
32
+ 'error AlreadyBound()', 'error NotCurve()', 'error NotCreator()', 'error NotRecipient()', 'error NothingOwed()',
33
+ 'error PushStarved()',
34
+ ]
35
+
36
+ export const SPLIT_FACTORY_ABI = parseAbi([
37
+ 'function create(address[] payees, uint16[] shares, bytes32 salt) returns (address module)',
38
+ 'function predict(address dev, bytes32 salt) view returns (address)',
39
+ 'function pad() view returns (address)',
40
+ 'error NotAgent()', 'error WrongHandler()',
41
+ 'event Created(address indexed dev, address indexed module, address[] payees, uint16[] shares)',
42
+ ...ERRORS,
43
+ ])
44
+
45
+ export const SPLIT_ABI = parseAbi([
46
+ 'function moduleType() view returns (bytes32)',
47
+ 'function dev() view returns (address)',
48
+ 'function token() view returns (address)',
49
+ 'function quote() view returns (address)',
50
+ 'function gangQuote() view returns (address)',
51
+ 'function payeesOf() view returns (address[] payees, uint16[] shares)',
52
+ 'function payeeCount() view returns (uint256)',
53
+ 'function owedOf(address asset, uint256 index) view returns (uint256)',
54
+ 'function owedTotal(address asset) view returns (uint256)',
55
+ 'function undistributed(address asset) view returns (uint256)',
56
+ 'function keeperServes(address q) view returns (bool)',
57
+ 'function previewWork() view returns (bool due, uint256 minOut)',
58
+ 'function lastDistributedAt() view returns (uint64)',
59
+ 'function bind(address token)',
60
+ 'function distribute(address asset) returns (uint256 incoming)',
61
+ 'function release(address asset, uint256 index, uint256 maxAmount) returns (uint256 amount)',
62
+ 'function setPayee(uint256 index, address newPayee)',
63
+ 'event Bound(address indexed token, address indexed quote)',
64
+ 'event Distributed(address indexed asset, uint256 incoming)',
65
+ 'event PayeeOwed(address indexed asset, uint256 indexed index, uint256 amount)',
66
+ 'event PayeeReleased(address indexed asset, uint256 indexed index, uint256 amount)',
67
+ 'event PayeeChanged(uint256 indexed index, address indexed oldPayee, address indexed newPayee)',
68
+ 'event Shortfall(address indexed asset, uint256 amount)',
69
+ ...ERRORS,
70
+ ])
71
+ /** gang tx decodes these (the factory's Created and the module's events). */
72
+ export const SPLIT_EVENT_ABIS = [SPLIT_FACTORY_ABI, SPLIT_ABI]
73
+
74
+ const PAD_ABI = parseAbi([
75
+ 'function taxConfigOf(address token) view returns (uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address recipient)',
76
+ 'function curves(address token) view returns (address creator, address quote, uint128 realQuote, uint128 sold, uint128 gradAmt, uint128 virtualQuote, bool graduated, uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address pair, address refPair)',
77
+ ])
78
+ const ERC20_ABI = parseAbi(['function symbol() view returns (string)', 'function decimals() view returns (uint8)'])
79
+
80
+ export const GAS_NOTE = 'let the wallet estimate the gas limit (eth_estimateGas) and do not lower it: each payee\'s push needs about 365k gas left before it, so the limit is far above the gas used; a lower limit reverts PushStarved (nothing moves)'
81
+
82
+ export const HINTS = {
83
+ NotAgent: 'only an Agent can create a V3 token, so only an Agent gets a split module',
84
+ NotFactory: 'this split factory is not allowed on the platform\'s GangHandlerAdmin: it cannot list a split module as a tax recipient. If GANG_SPLIT_FACTORY / GANG_TESTNET_SPLIT_FACTORY is set, unset it to use the built-in factory; otherwise launch without --split',
85
+ BadPayees: '1–10 payees, one share each',
86
+ BadShares: 'each share at least 0.01% (1 bps), all adding up to 100%',
87
+ BadPayee: 'a payee cannot be the split module itself',
88
+ DuplicatePayee: 'that address is a payee already (each address holds at most one slot)',
89
+ ZeroAddress: 'the zero address cannot be a payee',
90
+ BadIndex: 'no payee slot with that index (gang split status lists them, from 0)',
91
+ NotPayee: 'only the current payee of a slot can move it to another address',
92
+ AlreadyBound: 'the module is bound to a token already',
93
+ NotCurve: 'not a V3 (curve) token on this pad',
94
+ NotCreator: 'the token was not created by this module\'s dev',
95
+ NotRecipient: 'the token does not pay its tax to this module',
96
+ NothingOwed: 'nothing is owed to that slot in this asset (gang split status shows what each slot is owed)',
97
+ PushStarved: `the tx's gas limit was too low for the split: ${GAS_NOTE}`,
98
+ }
99
+ export const revertOf = (e) => revertIn(e, [SPLIT_ABI, SPLIT_FACTORY_ABI], HINTS)
100
+
101
+ /** Dry-run a call; { failed } with the revert when it would not pass. */
102
+ export async function simulateSplit(client, from, address, abi, functionName, args = []) {
103
+ try {
104
+ const { result } = await client.simulateContract({ account: from, address, abi, functionName, args })
105
+ return { result }
106
+ } catch (e) {
107
+ const r = revertOf(e)
108
+ return { failed: r ? { reverted: true, ...r } : { reverted: false, error: e.shortMessage || e.message.split('\n')[0] } }
109
+ }
110
+ }
111
+
112
+ export function splitFactoryAddress(testnet) {
113
+ return (testnet ? process.env.GANG_TESTNET_SPLIT_FACTORY || TESTNET_SPLIT_FACTORY
114
+ : process.env.GANG_SPLIT_FACTORY || MAINNET_SPLIT_FACTORY) || null
115
+ }
116
+
117
+ export const splitNotDeployed = (testnet) =>
118
+ `GangSplitModuleFactory is not deployed on ${testnet ? 'the BSC testnet' : 'BSC mainnet'} in this CLI version: set ${testnet ? 'GANG_TESTNET_SPLIT_FACTORY' : 'GANG_SPLIT_FACTORY'} to its address`
119
+
120
+ const SPLIT_USAGE = '--split takes <addr>:<pct>[,<addr>:<pct>…]: 1–10 payees, each share in % (up to 2 decimals, at least 0.01), adding up to 100; self (or me) = your wallet. E.g. --split self:60,0xAbc…:30,0xDef…:10'
121
+ const PCT_RE = /^(\d{1,3})(?:\.(\d{1,2}))?$/
122
+
123
+ /**
124
+ * --split <addr>:<pct>[,…] → { payees, shares (bps), list } or { error, got }, checked as GangSplitModule.initialize checks
125
+ * them (1–10 payees, none 0, no repeats, each share ≥ 1 bps, summing to 10,000). `self` (alias `me`) is the creating wallet;
126
+ * the order is kept (the first payee also takes the rounding dust of each split). Whether a payee is the module itself
127
+ * is checked once its address is known (launch.js, from predict).
128
+ */
129
+ export function parseSplitSpec(raw, me) {
130
+ const s = String(raw ?? '').trim()
131
+ if (!s || s.startsWith('--')) return { error: SPLIT_USAGE, got: raw ?? null }
132
+ const parts = s.split(',').map((x) => x.trim())
133
+ if (parts.some((p) => !p)) return { error: `${SPLIT_USAGE} (an empty entry between commas)`, got: raw }
134
+ if (parts.length > MAX_PAYEES) return { error: `--split takes at most ${MAX_PAYEES} payees`, got: parts.length }
135
+ const list = []
136
+ for (const p of parts) {
137
+ const i = p.lastIndexOf(':')
138
+ if (i < 0) return { error: `--split: "${p}" is not <addr>:<pct>`, hint: SPLIT_USAGE }
139
+ const who = p.slice(0, i).trim(), pctRaw = p.slice(i + 1).trim()
140
+ let payee, you = false
141
+ if (/^(me|self)$/i.test(who)) {
142
+ if (!isAddress(me ?? '')) return { error: `--split: "${who}" needs your wallet address (sign in with baw, or give --from)` }
143
+ payee = getAddress(me); you = true
144
+ } else if (!isAddress(who)) {
145
+ return { error: `--split: "${who}" is not a 0x address (checksummed or all lowercase) or self`, hint: SPLIT_USAGE }
146
+ } else payee = getAddress(who)
147
+ if (payee === zeroAddress) return { error: '--split: the zero address cannot be a payee' }
148
+ const m = PCT_RE.exec(pctRaw)
149
+ if (!m) return { error: `--split: "${pctRaw}" (for ${who}) is not a share in % with at most 2 decimals (e.g. 60 or 33.33)`, hint: SPLIT_USAGE }
150
+ const bps = Number(m[1]) * 100 + Number((m[2] ?? '').padEnd(2, '0'))
151
+ if (bps < 1) return { error: `--split: ${who} has a 0% share; each payee needs at least 0.01%` }
152
+ if (bps > BPS) return { error: `--split: ${who} has more than 100%` }
153
+ if (!you && me && isAddress(me) && payee === getAddress(me)) you = true
154
+ list.push({ payee, bps, you })
155
+ }
156
+ const seen = new Set()
157
+ for (const { payee } of list) {
158
+ if (seen.has(payee)) return { error: `--split: ${payee} appears twice (self is your wallet ${me}); each address holds one slot`, got: raw }
159
+ seen.add(payee)
160
+ }
161
+ const sum = list.reduce((a, x) => a + x.bps, 0)
162
+ if (sum !== BPS) return { error: `--split: the shares add up to ${sum / 100}%, not 100%`, got: raw }
163
+ return {
164
+ payees: list.map((x) => x.payee), shares: list.map((x) => x.bps),
165
+ list: list.map((x, index) => ({ index, payee: x.payee, pct: x.bps / 100, ...(x.you && { you: true }) })),
166
+ }
167
+ }
168
+
169
+ /** The split as a one-line summary: "0xAb…:60%, 0xCd…:40%". */
170
+ export const splitLine = (payees, shares) => payees.map((p, i) => `${p}: ${Number(shares[i]) / 100}%`).join(', ')
171
+
172
+ const iso = (s) => (Number(s) > 0 ? new Date(Number(s) * 1000).toISOString() : null)
173
+
174
+ /**
175
+ * The module's state for printing, from the raw reads (pure: unit-tested). `raw`: { module, dev, token, quote, payees,
176
+ * shares, lastDistributedAt, keeperServesQuote, due, assets: [{ asset, symbol, decimals, undistributed, owedTotal,
177
+ * owed: bigint[] | null }] }. `ref`: how later commands name it (e.g. `--token 0x… --testnet`).
178
+ */
179
+ export function formatSplit(raw, ref) {
180
+ const token = raw.token && raw.token !== zeroAddress ? raw.token : null
181
+ const quote = token && raw.quote && raw.quote !== zeroAddress ? raw.quote : null
182
+ const isQuote = (a) => !!quote && a.toLowerCase() === quote.toLowerCase()
183
+ const dev = String(raw.dev).toLowerCase()
184
+ const payees = raw.payees.map((payee, index) => ({
185
+ index, payee, pct: Number(raw.shares[index]) / 100, bps: Number(raw.shares[index]), ...(payee.toLowerCase() === dev && { isDev: true }),
186
+ }))
187
+ const next = []
188
+ const assets = []
189
+ for (const a of raw.assets) {
190
+ const owedTotal = a.owedTotal ?? 0n
191
+ const undistributed = a.undistributed ?? 0n
192
+ // the bound quote always; another asset only when something of it is here
193
+ if (!isQuote(a.asset) && undistributed === 0n && owedTotal === 0n) continue
194
+ const f = (x) => formatUnits(x, a.decimals ?? 18)
195
+ const owed = owedTotal > 0n && a.owed
196
+ ? a.owed.map((x, index) => ({ index, payee: raw.payees[index], amount: f(x) })).filter((_, i) => a.owed[i] > 0n) : []
197
+ const byKeeper = isQuote(a.asset) && raw.keeperServesQuote
198
+ assets.push({
199
+ asset: a.asset, symbol: a.symbol ?? null, ...(isQuote(a.asset) && { boundQuote: true }),
200
+ undistributed: f(undistributed), owedTotal: f(owedTotal), ...(owed.length && { owed }),
201
+ splitBy: byKeeper ? 'keeper (or anyone, gang split distribute)' : 'hand: gang split distribute (anyone)',
202
+ })
203
+ if (undistributed > 0n && !byKeeper) next.push(`gang split distribute ${ref} --asset ${a.asset}`)
204
+ for (const o of owed) next.push(`gang split release ${ref} --asset ${a.asset} --index ${o.index}`)
205
+ }
206
+ const sym = (assets.find((x) => x.boundQuote)?.symbol) || quote
207
+ const distribution = !token ? 'unbound' : raw.keeperServesQuote ? 'keeper' : 'manual'
208
+ const keeperLine = distribution === 'unbound'
209
+ ? `Not bound to a token yet (gang split bind --token <the token>): the keeper splits nothing until then; anyone can split by hand (gang split distribute --asset <addr>)`
210
+ : distribution === 'keeper'
211
+ ? `The keeper splits the bound quote (${sym}) once enough has gathered (0.05% of the pool's quote reserve, or after a day once it reaches 1/100 of that); anyone can split it sooner (gang split distribute)`
212
+ : `The keeper does not serve this quote (${sym}): distribution is manual — run gang split distribute (anyone) to pay the payees`
213
+ return {
214
+ module: raw.module, moduleType: SPLIT_TYPE, dev: raw.dev, token, quote, ...(quote && { quoteSymbol: sym }),
215
+ payees, distribution,
216
+ keeper: { servesQuote: token ? !!raw.keeperServesQuote : null, due: !!raw.due, lastDistributedAt: iso(raw.lastDistributedAt) },
217
+ assets,
218
+ ...(next.length && { next }),
219
+ note: 'the payees and shares are fixed for good: nobody (not the dev, not the platform) can change them; a payee can only '
220
+ + 'move its own slot to another address (gang split set-payee). Every asset that reaches the module is split at these '
221
+ + `shares, the first payee also taking the rounding dust. ${keeperLine}. Any other asset sent to it is split by hand `
222
+ + '(gang split distribute --asset <addr>). A failed push is owed to that slot and paid with its next push, or by gang split release',
223
+ }
224
+ }
225
+
226
+ /** Reads `asset`'s side of the module; null when it is not an ERC20 the module can read. */
227
+ async function assetRaw(read, module, asset, n) {
228
+ let undistributed, owedTotal
229
+ try {
230
+ [undistributed, owedTotal] = await Promise.all([
231
+ read(module, SPLIT_ABI, 'undistributed', [asset]), read(module, SPLIT_ABI, 'owedTotal', [asset]),
232
+ ])
233
+ } catch { return null }
234
+ const [symbol, decimals, owed] = await Promise.all([
235
+ read(asset, ERC20_ABI, 'symbol').catch(() => null),
236
+ read(asset, ERC20_ABI, 'decimals').then(Number).catch(() => 18),
237
+ owedTotal > 0n ? Promise.all(Array.from({ length: n }, (_, i) => read(module, SPLIT_ABI, 'owedOf', [asset, BigInt(i)]))) : null,
238
+ ])
239
+ return { asset, symbol, decimals, undistributed, owedTotal, owed }
240
+ }
241
+
242
+ /**
243
+ * The module's state when `addr` is a GangSplitModule (split-v1); null when it is not (an EOA, a partner, another
244
+ * module). Assets read: the bound quote, WBNB, the module's GANG (mainnet) and `extraAssets` (e.g. the quote of a token
245
+ * paying it that is not the bound one).
246
+ */
247
+ export async function splitOf(read, addr, { wbnb, extraAssets = [], ref } = {}) {
248
+ if (!addr || addr === zeroAddress) return null
249
+ let type
250
+ try { type = await read(addr, SPLIT_ABI, 'moduleType') } catch { return null }
251
+ if (hexToString(type, { size: 32 }).replace(/\0+$/, '') !== SPLIT_TYPE) return null
252
+ const [dev, token, quote, [payees, shares], last, gangQuote, preview] = await Promise.all([
253
+ read(addr, SPLIT_ABI, 'dev'), read(addr, SPLIT_ABI, 'token'), read(addr, SPLIT_ABI, 'quote'), read(addr, SPLIT_ABI, 'payeesOf'),
254
+ read(addr, SPLIT_ABI, 'lastDistributedAt'), read(addr, SPLIT_ABI, 'gangQuote').catch(() => zeroAddress),
255
+ read(addr, SPLIT_ABI, 'previewWork').catch(() => [false, 0n]),
256
+ ])
257
+ const keeperServesQuote = quote !== zeroAddress ? await read(addr, SPLIT_ABI, 'keeperServes', [quote]).catch(() => false) : false
258
+ const seen = new Set()
259
+ const list = [quote, wbnb, gangQuote, ...extraAssets].filter((a) => {
260
+ if (!a || a === zeroAddress || seen.has(a.toLowerCase())) return false
261
+ seen.add(a.toLowerCase())
262
+ return true
263
+ })
264
+ const assets = (await Promise.all(list.map((a) => assetRaw(read, addr, a, payees.length)))).filter(Boolean)
265
+ return formatSplit({
266
+ module: addr, dev, token, quote, payees, shares, lastDistributedAt: last, keeperServesQuote, due: preview[0], assets,
267
+ }, ref ?? (token !== zeroAddress ? `--token ${token}` : `--module ${addr}`))
268
+ }
269
+
270
+ function splitCtx(testnet) {
271
+ const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
272
+ if (!net.pad) throw new Error(NOT_ON_MAINNET)
273
+ const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
274
+ return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
275
+ }
276
+
277
+ const SUBS = ['status', 'distribute', 'release', 'set-payee', 'bind']
278
+ const USAGE = 'usage: gang split <status|distribute|release|set-payee|bind> --token <addr> (or --module <addr>) [--asset <addr>] [--index <i>] [--to <addr>] [--max <amount>] [--testnet] — see gang help'
279
+
280
+ /** `gang split <sub>`: the split module of a V3 token (its tax recipient), found from --token (or named by --module). */
281
+ export async function runSplit(sub, { opt, flag, out, fail, summarize }) {
282
+ if (!SUBS.includes(sub)) return fail(USAGE, { got: sub ?? null })
283
+ const testnet = flag('testnet')
284
+ const rawOnly = flag('calldata')
285
+ let ctx
286
+ try { ctx = splitCtx(testnet) } catch (e) { return fail(e.message) }
287
+ const chainId = Number(ctx.chainId)
288
+ const tn = testnet ? ' --testnet' : ''
289
+ if (flag('token') && flag('module')) fail('give --token (its tax recipient is the module) or --module, not both')
290
+ let token = null, module, tokenQuote = null
291
+ if (flag('module')) {
292
+ if (sub === 'bind') fail('gang split bind needs --token <the token> (it binds the token\'s own recipient)')
293
+ module = opt('module')
294
+ if (!isAddress(module ?? '')) fail('--module must be a split module address (0x…)', { got: module ?? null })
295
+ } else {
296
+ token = opt('token')
297
+ if (!isAddress(token ?? '')) fail('--token must be a V3 token address (0x…), or name the module with --module <addr>', { got: token ?? null })
298
+ try {
299
+ const [creator, quote] = await ctx.read(ctx.pad, PAD_ABI, 'curves', [token])
300
+ if (creator === zeroAddress) throw new Error('not a curve')
301
+ tokenQuote = quote
302
+ module = (await ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token]))[3]
303
+ } catch {
304
+ return fail(`not a V3 token on this pad (${testnet ? 'BSC testnet' : 'BSC mainnet'}${testnet ? '' : '; add --testnet for a testnet token'})`, { token, chainId })
305
+ }
306
+ }
307
+ const ref = `${token ? `--token ${token}` : `--module ${module}`}${tn}`
308
+ const s = await splitOf(ctx.read, module, { wbnb: ctx.wbnb, extraAssets: tokenQuote && tokenQuote !== zeroAddress ? [tokenQuote] : [], ref })
309
+ if (!s) {
310
+ return fail(token ? 'this token\'s tax recipient is not a split module' : 'not a split module (split-v1)',
311
+ { ...(token && { token }), recipient: module === zeroAddress ? null : module })
312
+ }
313
+ // the token pays this module but the module is bound to another one: the keeper never splits this token's tax
314
+ const decoy = token && s.token && s.token.toLowerCase() !== token.toLowerCase()
315
+ const warning = decoy
316
+ ? `this token pays its tax to the module, but the module is bound to another token (${s.token}): the keeper splits only that token's quote; this token's tax (${tokenQuote}) is split only by hand (gang split distribute ${ref} --asset ${tokenQuote})`
317
+ : null
318
+ const me = () => walletFor(ctx, opt('from'))
319
+ const send = async (functionName, args, extra) => {
320
+ const sim = await simulateSplit(ctx.client, me(), s.module, SPLIT_ABI, functionName, args)
321
+ if (sim.failed) return out({ success: false, step: extra.step, ...sim.failed })
322
+ const data = encodeFunctionData({ abi: SPLIT_ABI, functionName, args })
323
+ // no gas field: the wallet / node estimates it (GAS_NOTE)
324
+ return out(step(ctx, { from: me(), to: s.module, data }, { chainId, ...(token && { token }), module: s.module, ...extra }, rawOnly, summarize))
325
+ }
326
+ /** --asset <addr | wbnb>, else `def` (the bound quote, or the token's own quote while unbound). */
327
+ const assetArg = (def) => {
328
+ if (!flag('asset')) {
329
+ if (!def) fail('the module is not bound to a token yet: give --asset <addr> (what to split), or bind it first (gang split bind --token <the token>)')
330
+ return def
331
+ }
332
+ const a = opt('asset')
333
+ if (/^wbnb$/i.test(a ?? '')) return ctx.wbnb
334
+ if (!isAddress(a ?? '') || a === zeroAddress) fail('--asset must be a token address (0x…, checksummed or all lowercase) or wbnb', { got: a ?? null })
335
+ return getAddress(a)
336
+ }
337
+ const assetState = async (asset) => {
338
+ const known = s.assets.find((x) => x.asset.toLowerCase() === asset.toLowerCase())
339
+ const r = await assetRaw(ctx.read, s.module, asset, s.payees.length)
340
+ if (!r) fail('the module cannot read that asset\'s balance (not an ERC20?)', { asset })
341
+ return { ...r, symbol: r.symbol ?? known?.symbol ?? null, f: (x) => formatUnits(x, r.decimals) }
342
+ }
343
+ const defaultAsset = s.quote ?? (tokenQuote && tokenQuote !== zeroAddress ? tokenQuote : null)
344
+
345
+ if (sub === 'status') return out({ success: true, chainId, ...s, ...(warning && { warning }) })
346
+
347
+ if (sub === 'bind') {
348
+ if (s.token) return fail('already bound', { boundTo: s.token, ...(warning && { warning }) })
349
+ return send('bind', [token], { step: 'bind', note: 'anyone may bind (once); the token must be the dev\'s and pay its tax to this module. It decides which quote the keeper splits' })
350
+ }
351
+
352
+ if (sub === 'distribute') {
353
+ const asset = assetArg(defaultAsset)
354
+ const a = await assetState(asset)
355
+ if (a.undistributed === 0n) {
356
+ return fail('nothing of this asset is waiting to be split', {
357
+ asset, symbol: a.symbol, owedTotal: a.f(a.owedTotal),
358
+ ...(a.owedTotal > 0n && { hint: `what is held is owed to payees after failed pushes: gang split release ${ref} --asset ${asset} --index <i>` }),
359
+ })
360
+ }
361
+ // as the contract: the others rounded down, the first payee the rest
362
+ const amounts = s.payees.map((p) => (a.undistributed * BigInt(p.bps)) / BigInt(BPS))
363
+ amounts[0] = a.undistributed - amounts.slice(1).reduce((x, y) => x + y, 0n)
364
+ const parts = s.payees.map((p, i) => ({ index: p.index, payee: p.payee, pct: p.pct, gets: a.f(amounts[i]) }))
365
+ return send('distribute', [asset], {
366
+ step: 'distribute', asset, symbol: a.symbol, amount: a.f(a.undistributed), parts,
367
+ note: `anyone may: splits what of this asset arrived since its last split at the fixed shares (the first payee also takes the rounding dust); a push that fails is owed to that slot. Gas: ${GAS_NOTE}`,
368
+ })
369
+ }
370
+
371
+ if (sub === 'release') {
372
+ const asset = assetArg(defaultAsset)
373
+ const a = await assetState(asset)
374
+ let index
375
+ if (flag('index')) index = indexArg(opt('index'), s.payees.length, fail)
376
+ else {
377
+ const mine = s.payees.find((p) => p.payee.toLowerCase() === String(me()).toLowerCase())
378
+ const owedSlots = (a.owed ?? []).map((x, i) => (x > 0n ? i : -1)).filter((i) => i >= 0)
379
+ if (mine) index = mine.index
380
+ else if (owedSlots.length === 1) index = owedSlots[0]
381
+ else fail('--index <i> required: which payee slot to pay (gang split status lists what each is owed)', { owedSlots })
382
+ }
383
+ const owed = a.owed ? a.owed[index] : 0n
384
+ if (owed === 0n) return fail(HINTS.NothingOwed, { asset, symbol: a.symbol, index, payee: s.payees[index].payee })
385
+ let max = maxUint256
386
+ if (flag('max')) max = parseUnits(parseAmount(fail, 'max', opt('max')), a.decimals)
387
+ const amount = owed < max ? owed : max
388
+ return send('release', [asset, BigInt(index), max], {
389
+ step: 'release', asset, symbol: a.symbol, index, payee: s.payees[index].payee, amount: a.f(amount), owed: a.f(owed),
390
+ note: `anyone may: splits what newly arrived of this asset first, then pushes ${max === maxUint256 ? 'all' : 'up to --max'} of what this slot is owed to its payee (reverts while it still cannot receive; nothing owed is lost). Gas: ${GAS_NOTE}`,
391
+ })
392
+ }
393
+
394
+ // set-payee: only the slot's own payee; the index is the wallet's own slot unless given
395
+ const wallet = String(me()).toLowerCase()
396
+ const mine = s.payees.find((p) => p.payee.toLowerCase() === wallet)
397
+ let index
398
+ if (flag('index')) index = indexArg(opt('index'), s.payees.length, fail)
399
+ else if (mine) index = mine.index
400
+ else return fail('this wallet is not a payee of this module: only a slot\'s own payee can move it', { wallet: me(), payees: s.payees.map((p) => p.payee) })
401
+ const slot = s.payees[index]
402
+ if (slot.payee.toLowerCase() !== wallet) return fail(HINTS.NotPayee, { index, payee: slot.payee, wallet: me() })
403
+ const to = opt('to')
404
+ if (!isAddress(to ?? '') || to === zeroAddress) fail('--to <0x…> required (checksummed or all lowercase): the address this slot is paid to from now on', { got: to ?? null })
405
+ if (to.toLowerCase() === s.module.toLowerCase()) return fail(HINTS.BadPayee, { to })
406
+ const taken = s.payees.find((p) => p.payee.toLowerCase() === to.toLowerCase())
407
+ if (taken) return fail(taken.index === index ? 'that is this slot\'s payee already' : HINTS.DuplicatePayee, { to, index: taken.index })
408
+ // the contract splits only the bound quote before the move: what else arrived would go to the new address, so split
409
+ // those first (review I-3); each is its own tx, then the same command again
410
+ const unsplit = s.assets.filter((x) => !x.boundQuote && Number(x.undistributed) > 0)
411
+ if (unsplit.length) {
412
+ const first = unsplit[0]
413
+ return send('distribute', [first.asset], {
414
+ step: 'distribute-first', asset: first.asset, symbol: first.symbol, amount: first.undistributed,
415
+ ...(unsplit.length > 1 && { thenAlso: unsplit.slice(1).map((x) => ({ asset: x.asset, symbol: x.symbol, amount: x.undistributed })) }),
416
+ note: `before the move: ${first.symbol || first.asset} that arrived earlier is split to the current payees (the contract splits only the bound quote itself). After executing, re-run the same command. Gas: ${GAS_NOTE}`,
417
+ })
418
+ }
419
+ return send('setPayee', [BigInt(index), getAddress(to)], {
420
+ step: 'set-payee', index, pct: slot.pct, fromPayee: slot.payee, toPayee: getAddress(to),
421
+ note: `applies at once; the share (${slot.pct}%) stays with the slot. The bound quote that arrived before is split first (to the current address); what this slot is owed (any asset) goes to the new one. Gas: ${GAS_NOTE}`,
422
+ })
423
+ }
424
+
425
+ function indexArg(raw, n, fail) {
426
+ const i = Number(raw)
427
+ if (!Number.isInteger(i) || i < 0 || i >= n) fail(`--index must be a payee slot: the contract's 0-based index, 0 to ${n - 1} (gang split status lists them)`, { got: raw ?? null })
428
+ return i
429
+ }
package/src/v3.js CHANGED
@@ -7,6 +7,7 @@ import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets,
7
7
  import { poolPayBnb, poolTrade } from './pool.js'
8
8
  import { bondGuard } from './bond.js'
9
9
  import { splitterOf } from './buyback.js'
10
+ import { splitOf } from './split.js'
10
11
 
11
12
  /**
12
13
  * `gang v3 …` — LaunchpadV3 (tax recipient): a token with its own buy / sell tax (1–5% each), a dividend share and a
@@ -278,7 +279,15 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
278
279
  : `untaxed; curve trades pay the ${fees.curveFeePct}% fee`
279
280
  // a recipient that is the dev's buy-back splitter: its ratio and what waits to be bought back
280
281
  const buyback = c.recipient && !c.recipientIsCreator ? await splitterOf(ctx.read, c.recipient) : null
281
- return out({ success: true, chainId: Number(ctx.chainId), ...fees, ...pub, taxNote, ...(swapBack && { swapBack }), ...(buyback && { buyback }) })
282
+ // or the dev's split module (split-v1): its fixed payees and shares, what waits to be split
283
+ const split = c.recipient && !c.recipientIsCreator && !buyback
284
+ ? await splitOf(ctx.read, c.recipient, { wbnb: ctx.wbnb, extraAssets: [c.quote], ref: `--token ${token}${net}` }) : null
285
+ const splitWarn = split && split.token && split.token.toLowerCase() !== token.toLowerCase()
286
+ ? { warning: `this token pays its tax to the split module, but the module is bound to another token (${split.token}): the keeper never splits this token's tax (${c.quote}); it is split only by hand (gang split distribute --token ${token}${net} --asset ${c.quote})` } : null
287
+ return out({
288
+ success: true, chainId: Number(ctx.chainId), ...fees, ...pub, taxNote, ...(swapBack && { swapBack }), ...(buyback && { buyback }),
289
+ ...(split && { split: { ...split, ...splitWarn } }),
290
+ })
282
291
  }
283
292
 
284
293
  if (sub === 'status') {