@gangfun/cli 0.21.0 → 0.23.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/src/combo.js ADDED
@@ -0,0 +1,605 @@
1
+ import { createPublicClient, parseAbi, encodeFunctionData, formatUnits, getAddress, hexToString, isAddress, maxUint128, maxUint256, parseUnits, zeroAddress } from 'viem'
2
+ import { atTokenPad, GANG_GENS, gangGens, KIND_UNREAD, padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
3
+ import { walletFor } from './fair.js'
4
+ import { parseAmount, parseNum, revertOf as revertIn, step } from './steps.js'
5
+ import { parseSplitSpec } from './split.js'
6
+
7
+ /**
8
+ * `gang combo …` and `gang create … --buyback <pct> --lp <pct> [--split <addr>:<pct>,…]` (any two or three of them) —
9
+ * GangComboSplitter (组合:回购 + 加池 + 分账, `combo-v1`): one V3 token's tax recipient that does what the three
10
+ * single-purpose modules do, at once. Of each payment of the bound quote, `buybackBps` is set aside for buy-back-and-burn
11
+ * (GangBuybackSplitter v4's chunk), `lpBps` for liquidity whose LP goes to 0xdead (GangLiquiditySplitter's chunk), and the
12
+ * rest is pushed to 1–10 payees at fixed shares (GangSplitModule's push; none when buy-back + LP = 100%).
13
+ * EVERYTHING is fixed when it is cloned: nobody (not the dev, not the platform) can change the ratios, the payees or their
14
+ * shares — unlike a lone buy-back / LP splitter, whose dev can change its ratio. A payee can only move its own slot
15
+ * (`setPayee`). GangComboSplitterFactory clones one for the dev (`create(buybackBps, lpBps, payees, shares, salt)`, at
16
+ * `predict(dev, salt)`) and has GangHandlerAdmin list it, so the dev names it as the recipient at create (launch.js does
17
+ * the three steps: clone → create → bind, as for --buyback / --split / --lp).
18
+ * Chunks: one per 4 minutes for both kinds together, always of the larger set-aside part (`chunk`), ≤ 0.5% of the pair's
19
+ * quote reserve, none while the price is > 2% above the pair's 10-minute average. The keeper's `work(minOut)` does the one
20
+ * action `previewWork` planned, encoded in minOut's top byte (1 buy-back, 2 liquidity, 3 price observation, 4 split).
21
+ * Any other asset: the buy-back + LP share goes to 0xdead, the rest to the payees (`distribute(asset)`; NotBound before
22
+ * `bind`).
23
+ * Gas: a chunk takes ~0.55–0.75M, and a split pushes up to 10 payees, each needing ~365k gas left before it. The CLI never
24
+ * sets a gas limit: the wallet / node estimates it; a lower one reverts PushStarved (nothing moves) or the chunk.
25
+ * Env: GANG_COMBO_FACTORY / GANG_TESTNET_COMBO_FACTORY override the create target's factory (gangpad.js).
26
+ */
27
+
28
+ // one factory per GangLaunchpad generation (it is bound to one pad and its GangHandlerAdmin): the create target's
29
+ // (GANG_GENS in gangpad.js). A clone reverts NotFactory until the platform allows the factory on GangHandlerAdmin
30
+ export const MAINNET_COMBO_FACTORY = GANG_GENS.mainnet[0].comboFactory
31
+ export const TESTNET_COMBO_FACTORY = GANG_GENS.testnet[0].comboFactory
32
+ export const COMBO_TYPE = 'combo-v1'
33
+ export const MAX_PAYEES = 10
34
+ const BPS = 10_000
35
+ const CHUNK_GAP_S = 4 * 60
36
+
37
+ /** previewWork's planned action, minOut's top byte (GangComboSplitter DO_*). */
38
+ export const WORK_ACTIONS = { 0: 'none', 1: 'buy-back', 2: 'liquidity', 3: 'observe', 4: 'split' }
39
+ const WORK_WHAT = {
40
+ none: 'nothing to do',
41
+ 'buy-back': 'one buy-back chunk (buys the token in the pair and burns it at 0xdead)',
42
+ liquidity: 'one liquidity chunk (half buys the token, all of it goes back into the pair with the matching quote, LP to 0xdead)',
43
+ observe: 'a price observation (the 10-minute average a chunk needs)',
44
+ split: 'a split that pays the payees their part of the quote that arrived',
45
+ }
46
+ const LOW_248 = (1n << 248n) - 1n
47
+
48
+ /** previewWork's minOut → { code, action, minTokensOut (chunks only), what }. Pass minOut to work() as returned. */
49
+ export function decodeWorkPlan(minOut) {
50
+ const v = BigInt(minOut ?? 0n)
51
+ const code = Number(v >> 248n)
52
+ const action = WORK_ACTIONS[code] ?? `unknown (${code})`
53
+ const value = v & LOW_248
54
+ return {
55
+ code, action, ...((code === 1 || code === 2) && { minTokensOut: formatUnits(value, 18) }),
56
+ what: WORK_WHAT[action] ?? 'an action this CLI does not know',
57
+ }
58
+ }
59
+
60
+ const ERRORS = [
61
+ 'error ZeroAddress()', 'error NotClone()', 'error NotFactory()', 'error AlreadyInitialized()', 'error BadBps()',
62
+ 'error BadPayees()', 'error BadShares()', 'error BadPayee()', 'error DuplicatePayee()', 'error BadIndex()',
63
+ 'error NotPayee()', 'error AlreadyBound()', 'error NotBound()', 'error NotCurve()', 'error NotCreator()',
64
+ 'error NotRecipient()', 'error NothingOwed()', 'error NothingToChunk()', 'error ChunkTooSoon()', 'error NotTradable()',
65
+ 'error Slippage()', 'error PushStarved()',
66
+ ]
67
+
68
+ export const COMBO_FACTORY_ABI = parseAbi([
69
+ 'function create(uint16 buybackBps, uint16 lpBps, address[] payees, uint16[] shares, bytes32 salt) returns (address module)',
70
+ 'function predict(address dev, bytes32 salt) view returns (address)',
71
+ 'function pad() view returns (address)',
72
+ 'error NotAgent()', 'error WrongHandler()',
73
+ 'event Created(address indexed dev, address indexed module, uint16 buybackBps, uint16 lpBps, address[] payees, uint16[] shares)',
74
+ ...ERRORS,
75
+ ])
76
+
77
+ export const COMBO_ABI = parseAbi([
78
+ 'function moduleType() view returns (bytes32)',
79
+ 'function dev() view returns (address)',
80
+ 'function token() view returns (address)',
81
+ 'function quote() view returns (address)',
82
+ 'function pair() view returns (address)',
83
+ 'function gangQuote() view returns (address)',
84
+ 'function buybackBps() view returns (uint16)',
85
+ 'function lpBps() view returns (uint16)',
86
+ 'function payeesOf() view returns (address[] payees, uint16[] shares)',
87
+ 'function buybackLeft() view returns (uint256)',
88
+ 'function lpLeft() view returns (uint256)',
89
+ 'function owedOf(address asset, uint256 index) view returns (uint256)',
90
+ 'function owedTotal(address asset) view returns (uint256)',
91
+ 'function unsplit() view returns (uint256)',
92
+ 'function undistributed(address asset) view returns (uint256)',
93
+ 'function keeperServes(address q) view returns (bool)',
94
+ 'function previewChunk() view returns (bool ready, bool burn, uint256 amount, uint256 tokensOut)',
95
+ 'function previewWork() view returns (bool due, uint256 minOut)',
96
+ 'function lastChunkAt() view returns (uint64)',
97
+ 'function lastPaidAt() view returns (uint64)',
98
+ 'function bind(address token)',
99
+ 'function split()',
100
+ 'function distribute(address asset) returns (uint256 incoming)',
101
+ 'function release(address asset, uint256 index, uint256 maxAmount) returns (uint256 amount)',
102
+ 'function setPayee(uint256 index, address newPayee)',
103
+ 'function chunk(uint256 minTokensOut) returns (bool burn, uint256 quoteIn, uint256 tokensOut, uint256 liquidity)',
104
+ 'function work(uint256 minOut)',
105
+ 'event Bound(address indexed token, address indexed quote)',
106
+ 'event Split(uint256 incoming, uint256 toBuyback, uint256 toLp, uint256 toPayees)',
107
+ 'event Distributed(address indexed asset, uint256 incoming, uint256 toDead)',
108
+ 'event PayeeOwed(address indexed asset, uint256 indexed index, uint256 amount)',
109
+ 'event PayeeReleased(address indexed asset, uint256 indexed index, uint256 amount)',
110
+ 'event PayeeChanged(uint256 indexed index, address indexed oldPayee, address indexed newPayee)',
111
+ 'event Shortfall(address indexed asset, uint256 amount)',
112
+ 'event BoughtBack(uint256 quoteIn, uint256 burned, uint256 left)',
113
+ 'event LiquidityAdded(uint256 quoteIn, uint256 tokensIn, uint256 liquidity, uint256 left)',
114
+ ...ERRORS,
115
+ ])
116
+ /** gang tx decodes these (the factory's Created and the module's events). */
117
+ export const COMBO_EVENT_ABIS = [COMBO_FACTORY_ABI, COMBO_ABI]
118
+
119
+ const PAD_ABI = parseAbi([
120
+ 'function taxConfigOf(address token) view returns (uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address recipient)',
121
+ '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)',
122
+ ])
123
+ const ERC20_ABI = parseAbi(['function symbol() view returns (string)', 'function decimals() view returns (uint8)'])
124
+
125
+ export const COMBO_GAS_NOTE = 'let the wallet estimate the gas limit (eth_estimateGas) and do not set or lower it: a chunk takes about 0.55–0.75M gas, and a split pushes up to 10 payees, each needing about 365k gas left before it, so the limit is far above the gas used; a lower limit reverts (PushStarved: nothing moves)'
126
+
127
+ export const HINTS = {
128
+ NotAgent: 'only an Agent can create a V3 token, so only an Agent gets a combined recipient',
129
+ NotFactory: 'this combo factory is not allowed on the platform\'s GangHandlerAdmin: it cannot list a combined recipient as a tax recipient. If GANG_COMBO_FACTORY / GANG_TESTNET_COMBO_FACTORY is set, unset it to use the built-in factory; otherwise launch with one of --buyback / --lp / --split alone',
130
+ BadBps: '--buyback + --lp is at most 100%',
131
+ BadPayees: 'below 100% buy-back + LP: 1–10 payees (--split), one share each; at 100%: no payees',
132
+ BadShares: 'each payee share at least 0.01% (1 bps) of the rest, all adding up to 100% of it',
133
+ BadPayee: 'a payee cannot be the combined recipient itself',
134
+ DuplicatePayee: 'that address is a payee already (each address holds at most one slot)',
135
+ ZeroAddress: 'the zero address cannot be a payee',
136
+ BadIndex: 'no payee slot with that index (gang combo status lists them, from 0)',
137
+ NotPayee: 'only the current payee of a slot can move it to another address',
138
+ AlreadyBound: 'the combined recipient is bound to a token already',
139
+ NotBound: 'the combined recipient is not bound to a token yet (gang combo bind --token <the token>): nothing is split before that',
140
+ NotCurve: 'not a V3 (curve) token on this pad',
141
+ NotCreator: 'the token was not created by this combined recipient\'s dev',
142
+ NotRecipient: 'the token does not pay its tax to this combined recipient',
143
+ NothingOwed: 'nothing is owed to that slot in this asset (gang combo status shows what each slot is owed)',
144
+ NothingToChunk: 'nothing is set aside for a buy-back or liquidity chunk yet (buybackLeft / lpLeft): it fills as the tax arrives',
145
+ ChunkTooSoon: 'one chunk (buy-back or liquidity, together) per 4 minutes: wait until 4 minutes after the last one (lastChunkAt)',
146
+ NotTradable: 'the token has not graduated: chunks start once it trades in its PancakeSwap pair',
147
+ Slippage: 'the pool price moved since the preview (fewer tokens than the minimum): run gang combo chunk again',
148
+ PushStarved: `the tx's gas limit was too low for the payee pushes: ${COMBO_GAS_NOTE}`,
149
+ }
150
+ export const revertOf = (e) => revertIn(e, [COMBO_ABI, COMBO_FACTORY_ABI], HINTS)
151
+
152
+ /** Dry-run a call; { failed } with the revert when it would not pass. */
153
+ export async function simulateCombo(client, from, address, abi, functionName, args = []) {
154
+ try {
155
+ const { result } = await client.simulateContract({ account: from, address, abi, functionName, args })
156
+ return { result }
157
+ } catch (e) {
158
+ const r = revertOf(e)
159
+ return { failed: r ? { reverted: true, ...r } : { reverted: false, error: e.shortMessage || e.message.split('\n')[0] } }
160
+ }
161
+ }
162
+
163
+ /** The create target's combo factory (a launch clones its combined recipient there, for the pad the token goes to). */
164
+ export function comboFactoryAddress(testnet) {
165
+ return gangGens(testnet)[0].comboFactory || null
166
+ }
167
+
168
+ export const comboNotDeployed = (testnet) => (testnet
169
+ ? 'GangComboSplitterFactory (the combined recipient) is not deployed on the BSC testnet in this CLI version: set GANG_TESTNET_COMBO_FACTORY to its address, or give one of --buyback / --lp / --split alone'
170
+ : 'GangComboSplitterFactory (the combined recipient) is not deployed on BSC mainnet in this CLI version: set GANG_COMBO_FACTORY to its address, or give one of --buyback / --lp / --split alone')
171
+
172
+ const COMBO_REST_NOTE = 'in a combined launch --split lists the payees of what --buyback and --lp leave, their shares adding up to 100 (of that rest)'
173
+
174
+ /**
175
+ * A combined launch's flags → { buybackBps, lpBps, payees, shares, list } or { error, … }, checked as
176
+ * GangComboSplitter.initialize checks them. `buybackBps` / `lpBps`: the parsed --buyback / --lp (bps, 0 when absent);
177
+ * `split`: the raw --split (undefined when absent); `me`: the creating wallet (`self`, and the only payee by default).
178
+ * Payee shares are of the rest (10,000 − buyback − LP); the payee being the module itself is checked once its address is
179
+ * known (launch.js, from predict).
180
+ */
181
+ export function parseComboSpec({ buybackBps = 0, lpBps = 0, split } = {}, me) {
182
+ const kept = buybackBps + lpBps
183
+ if (kept > BPS) return { error: `--buyback ${buybackBps / 100} + --lp ${lpBps / 100} is ${kept / 100}%, more than 100% of the recipient's part`, hint: 'lower one of them: the payees (--split) share what the two leave' }
184
+ if (kept === 0) return { error: '--buyback 0 and --lp 0 leave only the payees: give --split alone for a split module', hint: 'or raise --buyback / --lp' }
185
+ if (kept === BPS) {
186
+ if (split !== undefined) return { error: `--buyback + --lp is 100% of the recipient's part: nothing is left for payees, so --split is refused`, hint: 'drop --split, or lower --buyback / --lp so the payees get the rest' }
187
+ return { buybackBps, lpBps, payees: [], shares: [], list: [] }
188
+ }
189
+ let spec
190
+ if (split === undefined) {
191
+ if (!isAddress(me ?? '')) return { error: 'the rest of the recipient\'s part goes to your wallet: sign in with baw, or give --from (or name the payees with --split)' }
192
+ spec = { payees: [getAddress(me)], shares: [BPS], list: [{ index: 0, payee: getAddress(me), pct: 100, you: true }] }
193
+ } else {
194
+ spec = parseSplitSpec(split, me)
195
+ if (spec.error) return { ...spec, hint: spec.hint ? `${spec.hint}. ${COMBO_REST_NOTE}` : COMBO_REST_NOTE }
196
+ }
197
+ const rest = BPS - kept
198
+ return {
199
+ buybackBps, lpBps, payees: spec.payees, shares: spec.shares,
200
+ list: spec.list.map(({ pct: p, ...x }) => ({ ...x, pctOfRest: p, pctOfRecipient: ofRecipient(spec.shares[x.index], rest) })),
201
+ }
202
+ }
203
+
204
+ /** A payee's share of the rest (bps) as a % of the recipient's whole part. */
205
+ const ofRecipient = (share, rest) => Math.round((Number(share) * rest) / 1e2) / 1e4
206
+
207
+ /** The combo as one line: "30% buy-back, 30% liquidity, the rest (40%): 0xAb…: 70%, 0xCd…: 30%". */
208
+ export function comboLine(buybackBps, lpBps, payees, shares) {
209
+ const rest = BPS - buybackBps - lpBps
210
+ const parts = [`${buybackBps / 100}% buy-back and burn`, `${lpBps / 100}% liquidity (LP to 0xdead)`]
211
+ if (payees.length) parts.push(`the rest (${rest / 100}%) to ${payees.map((p, i) => `${p}: ${Number(shares[i]) / 100}% of it`).join(', ')}`)
212
+ return parts.join(', ')
213
+ }
214
+
215
+ export const PERMANENT_NOTE = 'PERMANENT: the buy-back %, the LP %, the payees and their shares are fixed for good — nobody (not you, not the platform) can change them later, unlike a lone --buyback or --lp splitter whose dev can change its ratio; a payee can only move its own slot to another address (gang combo set-payee)'
216
+
217
+ /** What the combo does with each part, and with any other asset (the preview and status note). */
218
+ export function comboParts(buybackBps, lpBps, nPayees) {
219
+ const dead = (buybackBps + lpBps) / 100
220
+ return {
221
+ buyback: `${buybackBps / 100}% of each tax payment to this recipient (in the token's quote) is set aside and bought back in the PancakeSwap pair, the tokens burned (0xdead)`,
222
+ liquidity: `${lpBps / 100}% is set aside and added to the pair as liquidity (half buys the token, all of it goes back in with the matching quote), the LP sent to 0xdead (locked for good)`,
223
+ payees: nPayees ? `the rest (${(BPS - buybackBps - lpBps) / 100}%) is pushed to the payees at their shares (the first also takes the rounding dust)` : 'no payees: buy-back + liquidity take it all',
224
+ chunks: 'after graduation, one chunk per 4 minutes for both kinds together (always the larger set-aside part), at most 0.5% of the pair\'s quote reserve, none while the price is more than 2% above its 10-minute average',
225
+ otherAssets: nPayees
226
+ ? `any other asset sent to it (not the token's quote) cannot be bought back or added: its buy-back + LP share (${dead}%) goes to 0xdead, the rest to the payees (gang combo distribute --asset <addr>)`
227
+ : 'any other asset sent to it (not the token\'s quote) goes to 0xdead in full (gang combo distribute --asset <addr>)',
228
+ }
229
+ }
230
+
231
+ const iso = (s) => (Number(s) > 0 ? new Date(Number(s) * 1000).toISOString() : null)
232
+ const q18 = (x) => formatUnits(x, 18)
233
+
234
+ /** _kindOf: the larger set-aside part (a buy-back on a tie); a liquidity part under 2 wei has no half. */
235
+ function kindOf(bb, lp) {
236
+ const canBurn = bb !== 0n, canAdd = lp / 2n !== 0n
237
+ if (!canBurn && !canAdd) return null
238
+ if (!canAdd) return 'buy-back'
239
+ if (!canBurn) return 'liquidity'
240
+ return bb >= lp ? 'buy-back' : 'liquidity'
241
+ }
242
+
243
+ /**
244
+ * The module's state for printing, from the raw reads (pure: unit-tested). `raw`: { module, dev, token, quote,
245
+ * quoteSymbol, buybackBps, lpBps, payees, shares, buybackLeft, lpLeft, unsplit, lastChunkAt, lastPaidAt,
246
+ * keeperServesQuote, preview: [ready, burn, amount, tokensOut] | null, work: [due, minOut] | null, graduated: bool | null,
247
+ * assets: [{ asset, symbol, decimals, undistributed, owedTotal, owed: bigint[] | null }], now (unix s) }. `ref`: how later
248
+ * commands name it (e.g. `--token 0x… --testnet`).
249
+ */
250
+ export function formatCombo(raw, ref) {
251
+ const token = raw.token && raw.token !== zeroAddress ? raw.token : null
252
+ const quote = token && raw.quote && raw.quote !== zeroAddress ? raw.quote : null
253
+ const isQuote = (a) => !!quote && a.toLowerCase() === quote.toLowerCase()
254
+ const bbBps = Number(raw.buybackBps), lpBps = Number(raw.lpBps)
255
+ const rest = BPS - bbBps - lpBps
256
+ const dev = String(raw.dev).toLowerCase()
257
+ const payees = raw.payees.map((payee, index) => ({
258
+ index, payee, pctOfRest: Number(raw.shares[index]) / 100, pctOfRecipient: ofRecipient(raw.shares[index], rest),
259
+ bps: Number(raw.shares[index]), ...(payee.toLowerCase() === dev && { isDev: true }),
260
+ }))
261
+ const now = Number(raw.now ?? Math.floor(Date.now() / 1000))
262
+ const last = Number(raw.lastChunkAt ?? 0n)
263
+
264
+ // the set-aside parts once the waiting quote is split (as the contract's _afterSplit, without a shortfall)
265
+ const unsplit = BigInt(raw.unsplit ?? 0n)
266
+ let toBb = (unsplit * BigInt(bbBps)) / 10_000n, toLp = (unsplit * BigInt(lpBps)) / 10_000n
267
+ if (!payees.length) {
268
+ const pay = unsplit - toBb - toLp
269
+ if (bbBps !== 0) toBb += pay
270
+ else toLp += pay
271
+ }
272
+ const bbAfter = BigInt(raw.buybackLeft) + toBb, lpAfter = BigInt(raw.lpLeft) + toLp
273
+ const kind = kindOf(bbAfter, lpAfter)
274
+ const [ready, burn, amount, tokensOut] = raw.preview ?? [false, false, 0n, 0n]
275
+ let waiting = null
276
+ if (!ready) {
277
+ waiting = !token ? 'not bound to a token yet (gang combo bind --token <the token>)'
278
+ : raw.graduated === false ? 'the token has not graduated: chunks start once it trades in its PancakeSwap pair (the pool tax starts then too)'
279
+ : !kind ? 'nothing set aside for a buy-back or liquidity chunk yet: it fills as the tax arrives'
280
+ : last > 0 && now < last + CHUNK_GAP_S ? `one chunk per 4 minutes (both kinds together): the next from ${iso(last + CHUNK_GAP_S)}`
281
+ : 'the price check: a 10-minute average of the pair\'s price (the next call records it, if none is running) and a price no more than 2% above it'
282
+ }
283
+ const nextChunk = ready
284
+ ? burn
285
+ ? { kind: 'buy-back', quoteIn: q18(amount), tokensBurned: formatUnits(tokensOut, 18) }
286
+ : { kind: 'liquidity', quoteChunk: q18(amount), buyHalf: q18(amount / 2n), tokensBought: formatUnits(tokensOut, 18) }
287
+ : { kind, ready: false }
288
+
289
+ const next = []
290
+ const assets = []
291
+ for (const a of raw.assets ?? []) {
292
+ const owedTotal = a.owedTotal ?? 0n
293
+ const undistributed = a.undistributed ?? 0n
294
+ if (!isQuote(a.asset) && undistributed === 0n && owedTotal === 0n) continue
295
+ const f = (x) => formatUnits(x, a.decimals ?? 18)
296
+ const owed = owedTotal > 0n && a.owed
297
+ ? a.owed.map((x, index) => ({ index, payee: raw.payees[index], amount: f(x) })).filter((_, i) => a.owed[i] > 0n) : []
298
+ const byKeeper = isQuote(a.asset) && raw.keeperServesQuote
299
+ assets.push({
300
+ asset: a.asset, symbol: a.symbol ?? null, ...(isQuote(a.asset) && { boundQuote: true }),
301
+ undistributed: f(undistributed), owedTotal: f(owedTotal), ...(owed.length && { owed }),
302
+ splitBy: !token ? 'nobody until bound (distribute reverts NotBound)'
303
+ : byKeeper ? 'keeper (or anyone, gang combo distribute)'
304
+ : isQuote(a.asset) ? 'hand: gang combo distribute (anyone)'
305
+ : `hand: gang combo distribute (anyone): ${payees.length ? `${(bbBps + lpBps) / 100}% to 0xdead, the rest to the payees` : 'all of it to 0xdead'}`,
306
+ })
307
+ if (token && undistributed > 0n && !byKeeper) next.push(`gang combo distribute ${ref} --asset ${a.asset}`)
308
+ for (const o of owed) next.push(`gang combo release ${ref} --asset ${a.asset} --index ${o.index}`)
309
+ }
310
+ if (!token) next.unshift(String(ref ?? '').startsWith('--token ') ? `gang combo bind ${ref}` : 'gang combo bind --token <the token>')
311
+ if (ready) next.push(`gang combo chunk ${ref}`)
312
+
313
+ const sym = (assets.find((x) => x.boundQuote)?.symbol) || raw.quoteSymbol || quote
314
+ const distribution = !token ? 'unbound' : raw.keeperServesQuote ? 'keeper' : 'manual'
315
+ const keeperLine = distribution === 'unbound'
316
+ ? 'Not bound to a token yet: nothing is split, bought back or added until gang combo bind --token <the token>'
317
+ : distribution === 'keeper'
318
+ ? `The keeper serves this quote (${sym}): it runs the chunks and pays the payees (once their part reaches 0.05% of the pair's quote reserve, or after a day once it reaches 1/100 of that); anyone can do it sooner (gang combo chunk / gang combo distribute)`
319
+ : `The keeper does not serve this quote (${sym}): everything is manual — gang combo chunk and gang combo distribute (anyone)`
320
+ const [due, minOut] = raw.work ?? [false, 0n]
321
+ const parts = comboParts(bbBps, lpBps, payees.length)
322
+ return {
323
+ module: raw.module, moduleType: COMBO_TYPE, dev: raw.dev, token, quote, ...(quote && sym && { quoteSymbol: sym }),
324
+ buybackPct: bbBps / 100, lpPct: lpBps / 100, payeesPct: rest / 100, buybackBps: bbBps, lpBps, permanent: true,
325
+ payees,
326
+ buybackLeft: q18(raw.buybackLeft), lpLeft: q18(raw.lpLeft), unsplit: q18(unsplit),
327
+ nextChunk, ...(waiting && { nextChunkWaitsFor: waiting }),
328
+ lastChunkAt: iso(last), lastPaidAt: iso(raw.lastPaidAt ?? 0n),
329
+ distribution,
330
+ keeper: {
331
+ servesQuote: token ? !!raw.keeperServesQuote : null, due: !!due,
332
+ ...(due && { plan: decodeWorkPlan(minOut) }),
333
+ },
334
+ assets,
335
+ ...(next.length && { next }),
336
+ parts,
337
+ note: `${PERMANENT_NOTE}. ${keeperLine}. A failed payee push is owed to that slot and paid with its next push, or by gang combo release`,
338
+ }
339
+ }
340
+
341
+ /** Reads `asset`'s side of the module; null when it is not an ERC20 the module can read. */
342
+ async function assetRaw(read, module, asset, n) {
343
+ let undistributed, owedTotal
344
+ try {
345
+ [undistributed, owedTotal] = await Promise.all([
346
+ read(module, COMBO_ABI, 'undistributed', [asset]), read(module, COMBO_ABI, 'owedTotal', [asset]),
347
+ ])
348
+ } catch { return null }
349
+ const [symbol, decimals, owed] = await Promise.all([
350
+ read(asset, ERC20_ABI, 'symbol').catch(() => null),
351
+ read(asset, ERC20_ABI, 'decimals').then(Number).catch(() => 18),
352
+ owedTotal > 0n ? Promise.all(Array.from({ length: n }, (_, i) => read(module, COMBO_ABI, 'owedOf', [asset, BigInt(i)]))) : null,
353
+ ])
354
+ return { asset, symbol, decimals, undistributed, owedTotal, owed }
355
+ }
356
+
357
+ /**
358
+ * The module's state when `addr` is a GangComboSplitter (combo-v1); null when it is not. Assets read: the bound quote,
359
+ * WBNB, the module's GANG and `extraAssets` (e.g. the quote of a token paying it that is not the bound one). `pad`: to
360
+ * read graduation.
361
+ */
362
+ export async function comboOf(read, addr, { wbnb, pad, extraAssets = [], ref } = {}) {
363
+ if (!addr || addr === zeroAddress) return null
364
+ let type
365
+ try { type = await read(addr, COMBO_ABI, 'moduleType') } catch { return null }
366
+ if (hexToString(type, { size: 32 }).replace(/\0+$/, '') !== COMBO_TYPE) return null
367
+ const [dev, token, quote, [payees, shares], buybackBps, lpBps, buybackLeft, lpLeft, unsplit, lastChunkAt, lastPaidAt, gangQuote] = await Promise.all([
368
+ ...['dev', 'token', 'quote', 'payeesOf', 'buybackBps', 'lpBps', 'buybackLeft', 'lpLeft', 'unsplit', 'lastChunkAt', 'lastPaidAt'].map((f) => read(addr, COMBO_ABI, f)),
369
+ read(addr, COMBO_ABI, 'gangQuote').catch(() => zeroAddress),
370
+ ])
371
+ const bound = token !== zeroAddress
372
+ const [preview, work, keeperServesQuote, graduated] = await Promise.all([
373
+ bound ? read(addr, COMBO_ABI, 'previewChunk').catch(() => null) : null,
374
+ bound ? read(addr, COMBO_ABI, 'previewWork').catch(() => null) : null,
375
+ bound ? read(addr, COMBO_ABI, 'keeperServes', [quote]).catch(() => false) : false,
376
+ bound && pad ? read(pad, PAD_ABI, 'curves', [token]).then((c) => c[6]).catch(() => null) : null,
377
+ ])
378
+ const seen = new Set()
379
+ const list = [quote, wbnb, gangQuote, ...extraAssets].filter((a) => {
380
+ if (!a || a === zeroAddress || seen.has(a.toLowerCase())) return false
381
+ seen.add(a.toLowerCase())
382
+ return true
383
+ })
384
+ const assets = (await Promise.all(list.map((a) => assetRaw(read, addr, a, payees.length)))).filter(Boolean)
385
+ return formatCombo({
386
+ module: addr, dev, token, quote, buybackBps, lpBps, payees, shares, buybackLeft, lpLeft, unsplit, lastChunkAt, lastPaidAt,
387
+ keeperServesQuote, preview, work, graduated, assets,
388
+ }, ref ?? (bound ? `--token ${token}` : `--module ${addr}`))
389
+ }
390
+
391
+ /** When `token` pays its tax to the combo but the combo is bound to another token (a decoy bind): what to say. */
392
+ export function decoyWarning(s, token, tokenQuote, ref) {
393
+ if (!token || !s.token || s.token.toLowerCase() === token.toLowerCase()) return null
394
+ return `this token pays its tax to the combined recipient, but it is bound to another token (${s.token}): the buy-backs and liquidity go to that token's pair, and this token's tax (${tokenQuote ?? 'its quote'}) is not its bound quote — it is only distributed by hand (gang combo distribute ${ref} --asset ${tokenQuote ?? '<its quote>'}): its buy-back + LP share to 0xdead, the rest to the payees`
395
+ }
396
+
397
+ function comboCtx(testnet) {
398
+ const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
399
+ if (!net.pad) throw new Error(NOT_ON_MAINNET)
400
+ const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
401
+ return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
402
+ }
403
+
404
+ const SUBS = ['status', 'distribute', 'release', 'set-payee', 'bind', 'chunk']
405
+ const USAGE = 'usage: gang combo <status|distribute|release|set-payee|bind|chunk> --token <addr> (or --module <addr>) [--asset <addr>|wbnb] [--index <i>] [--to <addr>] [--max <amount>] [--slippage 1] [--testnet] — see gang help'
406
+
407
+ /** `gang combo <sub>`: the combined recipient of a V3 token (its tax recipient), found from --token (or named by --module). */
408
+ export async function runCombo(sub, { opt, flag, out, fail, summarize }) {
409
+ if (!SUBS.includes(sub)) return fail(USAGE, { got: sub ?? null })
410
+ const testnet = flag('testnet')
411
+ const rawOnly = flag('calldata')
412
+ let ctx
413
+ try { ctx = comboCtx(testnet) } catch (e) { return fail(e.message) }
414
+ const chainId = Number(ctx.chainId)
415
+ const tn = testnet ? ' --testnet' : ''
416
+ if (flag('token') && flag('module')) fail('give --token (its tax recipient is the combined recipient) or --module, not both')
417
+ let token = null, module, tokenQuote = null
418
+ if (flag('module')) {
419
+ if (sub === 'bind') fail('gang combo bind needs --token <the token> (it binds the token\'s own recipient)')
420
+ module = opt('module')
421
+ if (!isAddress(module ?? '')) fail('--module must be a combined recipient address (0x…)', { got: module ?? null })
422
+ } else {
423
+ token = opt('token')
424
+ if (!isAddress(token ?? '')) fail('--token must be a V3 token address (0x…), or name the module with --module <addr>', { got: token ?? null })
425
+ if ((await atTokenPad(ctx, token)) === null) return fail(KIND_UNREAD.error, { token, retry: KIND_UNREAD.retry }) // else on the pad of the token's generation
426
+ try {
427
+ const [creator, quote] = await ctx.read(ctx.pad, PAD_ABI, 'curves', [token])
428
+ if (creator === zeroAddress) throw new Error('not a curve')
429
+ tokenQuote = quote
430
+ module = (await ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token]))[3]
431
+ } catch {
432
+ return fail(`not a V3 token on this pad (${testnet ? 'BSC testnet' : 'BSC mainnet; add --testnet for a testnet token'})`, { token, chainId })
433
+ }
434
+ }
435
+ const ref = `${token ? `--token ${token}` : `--module ${module}`}${tn}`
436
+ // status --asset <addr>: read that asset too (a stray one the default list doesn't cover)
437
+ const extra = sub === 'status' && flag('asset') && isAddress(opt('asset') ?? '') ? [getAddress(opt('asset'))] : []
438
+ const s = await comboOf(ctx.read, module, {
439
+ wbnb: ctx.wbnb, pad: ctx.pad, extraAssets: [...(tokenQuote && tokenQuote !== zeroAddress ? [tokenQuote] : []), ...extra], ref,
440
+ })
441
+ if (!s) {
442
+ return fail(token ? 'this token\'s tax recipient is not a combined recipient (combo-v1)' : 'not a combined recipient (combo-v1)',
443
+ { ...(token && { token }), recipient: module === zeroAddress ? null : module })
444
+ }
445
+ const warning = decoyWarning(s, token, tokenQuote, ref)
446
+ const me = () => walletFor(ctx, opt('from'))
447
+ const send = async (functionName, args, extra) => {
448
+ const sim = await simulateCombo(ctx.client, me(), s.module, COMBO_ABI, functionName, args)
449
+ if (sim.failed) return out({ success: false, step: extra.step, ...sim.failed, ...(warning && { warning }) })
450
+ const data = encodeFunctionData({ abi: COMBO_ABI, functionName, args })
451
+ // no gas field: the wallet / node estimates it (COMBO_GAS_NOTE)
452
+ return out(step(ctx, { from: me(), to: s.module, data }, { chainId, ...(token && { token }), module: s.module, ...extra, ...(warning && { warning }) }, rawOnly, summarize))
453
+ }
454
+ const assetArg = (def) => {
455
+ if (!flag('asset')) return def
456
+ const a = opt('asset')
457
+ if (/^wbnb$/i.test(a ?? '')) return ctx.wbnb
458
+ if (!isAddress(a ?? '') || a === zeroAddress) fail('--asset must be a token address (0x…, checksummed or all lowercase) or wbnb', { got: a ?? null })
459
+ return getAddress(a)
460
+ }
461
+ const assetState = async (asset) => {
462
+ const known = s.assets.find((x) => x.asset.toLowerCase() === asset.toLowerCase())
463
+ const r = await assetRaw(ctx.read, s.module, asset, s.payees.length)
464
+ if (!r) fail('the module cannot read that asset\'s balance (not an ERC20?)', { asset })
465
+ return { ...r, symbol: r.symbol ?? known?.symbol ?? null, f: (x) => formatUnits(x, r.decimals) }
466
+ }
467
+ const needBound = () => {
468
+ if (!s.token) fail(HINTS.NotBound, { module: s.module, ...(token && { next: `gang combo bind --token ${token}${tn}` }) })
469
+ }
470
+ /** `amount` split among the payees as the contract does: the others rounded down, the first the rest. */
471
+ const payeeParts = (amount, f) => {
472
+ if (!s.payees.length) return []
473
+ const amounts = s.payees.map((p) => (amount * BigInt(p.bps)) / BigInt(BPS))
474
+ amounts[0] = amount - amounts.slice(1).reduce((x, y) => x + y, 0n)
475
+ return s.payees.map((p, i) => ({ index: p.index, payee: p.payee, pctOfRest: p.pctOfRest, gets: f(amounts[i]) }))
476
+ }
477
+
478
+ if (sub === 'status') return out({ success: true, chainId, ...s, ...(s.token === null && { bound: false }), ...(warning && { warning }) })
479
+
480
+ if (sub === 'bind') {
481
+ if (s.token) return fail('already bound', { boundTo: s.token, ...(warning && { warning }) })
482
+ 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 is split and which pair the buy-backs and liquidity go to' })
483
+ }
484
+
485
+ if (sub === 'distribute') {
486
+ needBound()
487
+ const asset = assetArg(s.quote)
488
+ const a = await assetState(asset)
489
+ if (a.undistributed === 0n) {
490
+ return fail('nothing of this asset is waiting to be split', {
491
+ asset, symbol: a.symbol, owedTotal: a.f(a.owedTotal),
492
+ ...(a.owedTotal > 0n && { hint: `what is held is owed to payees after failed pushes: gang combo release ${ref} --asset ${asset} --index <i>` }),
493
+ })
494
+ }
495
+ const bb = BigInt(s.buybackBps), lpb = BigInt(s.lpBps)
496
+ if (asset.toLowerCase() === s.quote.toLowerCase()) {
497
+ const toBuyback = (a.undistributed * bb) / 10_000n, toLp = (a.undistributed * lpb) / 10_000n
498
+ const toPayees = s.payees.length ? a.undistributed - toBuyback - toLp : 0n
499
+ return send('distribute', [asset], {
500
+ step: 'distribute', asset, symbol: a.symbol, boundQuote: true, amount: a.f(a.undistributed),
501
+ toBuyback: a.f(toBuyback), toLp: a.f(toLp), toPayees: a.f(toPayees), parts: payeeParts(toPayees, a.f),
502
+ note: `anyone may: splits the bound quote that arrived (as split()): ${s.buybackPct}% set aside for buy-back, ${s.lpPct}% for liquidity, the rest pushed to the payees; a push that fails is owed to that slot. Gas: ${COMBO_GAS_NOTE}`,
503
+ })
504
+ }
505
+ const toDead = s.payees.length ? (a.undistributed * (bb + lpb)) / 10_000n : a.undistributed
506
+ const rest = a.undistributed - toDead
507
+ return send('distribute', [asset], {
508
+ step: 'distribute', asset, symbol: a.symbol, amount: a.f(a.undistributed), toDead: a.f(toDead), toPayees: a.f(rest),
509
+ parts: payeeParts(rest, a.f),
510
+ note: `anyone may: this is not the bound quote, so it cannot be bought back or added to the pool: ${s.payees.length ? `its buy-back + LP share (${(s.buybackBps + s.lpBps) / 100}%) goes to 0xdead, the rest to the payees at their shares` : 'all of it goes to 0xdead (no payees)'}; a push that fails is owed to that slot. Gas: ${COMBO_GAS_NOTE}`,
511
+ })
512
+ }
513
+
514
+ if (sub === 'release') {
515
+ needBound()
516
+ if (!s.payees.length) return fail('this combined recipient has no payees (buy-back + LP = 100%): nothing is ever owed')
517
+ const asset = assetArg(s.quote)
518
+ const a = await assetState(asset)
519
+ let index
520
+ if (flag('index')) index = indexArg(opt('index'), s.payees.length, fail)
521
+ else {
522
+ const mine = s.payees.find((p) => p.payee.toLowerCase() === String(me()).toLowerCase())
523
+ const owedSlots = (a.owed ?? []).map((x, i) => (x > 0n ? i : -1)).filter((i) => i >= 0)
524
+ if (mine) index = mine.index
525
+ else if (owedSlots.length === 1) index = owedSlots[0]
526
+ else fail('--index <i> required: which payee slot to pay (gang combo status lists what each is owed)', { owedSlots })
527
+ }
528
+ const owed = a.owed ? a.owed[index] : 0n
529
+ if (owed === 0n) return fail(HINTS.NothingOwed, { asset, symbol: a.symbol, index, payee: s.payees[index].payee })
530
+ let max = maxUint256
531
+ if (flag('max')) max = parseUnits(parseAmount(fail, 'max', opt('max')), a.decimals)
532
+ const amount = owed < max ? owed : max
533
+ return send('release', [asset, BigInt(index), max], {
534
+ step: 'release', asset, symbol: a.symbol, index, payee: s.payees[index].payee, amount: a.f(amount), owed: a.f(owed),
535
+ 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: ${COMBO_GAS_NOTE}`,
536
+ })
537
+ }
538
+
539
+ if (sub === 'chunk') {
540
+ needBound()
541
+ const slippage = parseNum(fail, 'slippage', opt('slippage', '1'), 0, 50)
542
+ const [ready, burn, amount, tokensOut] = await ctx.read(s.module, COMBO_ABI, 'previewChunk')
543
+ if (ready) {
544
+ // previewChunk prices the buy (a liquidity chunk: its half) after the buy tax; the contract scales the minimum
545
+ // down when the pair got less
546
+ const minOut = (tokensOut * BigInt(Math.round((100 - slippage) * 100))) / 10_000n
547
+ return send('chunk', [minOut], burn
548
+ ? {
549
+ step: 'chunk', kind: 'buy-back', quoteIn: q18(amount), expectTokensBurned: formatUnits(tokensOut, 18),
550
+ minTokens: formatUnits(minOut, 18), slippagePct: slippage, buybackLeft: s.buybackLeft, lpLeft: s.lpLeft,
551
+ note: `anyone may: splits what arrived, then one buy-back chunk (the larger set-aside part): buys the token in the pair and burns it at 0xdead (gang tx shows BoughtBack). The keeper does the same every few minutes. Gas: ${COMBO_GAS_NOTE}`,
552
+ }
553
+ : {
554
+ step: 'chunk', kind: 'liquidity', quoteChunk: q18(amount), buyHalf: q18(amount / 2n), expectTokensBought: formatUnits(tokensOut, 18),
555
+ minTokens: formatUnits(minOut, 18), slippagePct: slippage, buybackLeft: s.buybackLeft, lpLeft: s.lpLeft,
556
+ note: `anyone may: splits what arrived, then one liquidity chunk (the larger set-aside part): half buys the token, all of it goes back into the pair with the matching quote, the LP to 0xdead (gang tx shows LiquidityAdded). The keeper does the same every few minutes. Gas: ${COMBO_GAS_NOTE}`,
557
+ })
558
+ }
559
+ // not ready: only a call that records the price observation can pass; a minimum no chunk can meet makes it revert
560
+ // (Slippage) rather than trade unchecked if a chunk became possible before it lands
561
+ const sim = await simulateCombo(ctx.client, me(), s.module, COMBO_ABI, 'chunk', [maxUint128])
562
+ if (sim.failed) return out({ success: false, step: 'chunk', ...sim.failed, ...(s.nextChunkWaitsFor && { waitsFor: s.nextChunkWaitsFor }), buybackLeft: s.buybackLeft, lpLeft: s.lpLeft, ...(warning && { warning }) })
563
+ return send('chunk', [maxUint128], {
564
+ step: 'record-price', trades: false, waitsFor: s.nextChunkWaitsFor,
565
+ note: 'no chunk this time: the call splits what arrived and records the pair\'s price observation (or waits for the 10-minute average / a price no more than 2% above it). The keeper calls it too. If a chunk becomes possible before it lands, it reverts (Slippage) rather than trade without a minimum: run gang combo chunk again then, about 10 minutes after the first observation',
566
+ })
567
+ }
568
+
569
+ // set-payee: only the slot's own payee; the index is the wallet's own slot unless given
570
+ if (!s.payees.length) return fail('this combined recipient has no payees (buy-back + LP = 100%)')
571
+ const wallet = String(me()).toLowerCase()
572
+ const mine = s.payees.find((p) => p.payee.toLowerCase() === wallet)
573
+ let index
574
+ if (flag('index')) index = indexArg(opt('index'), s.payees.length, fail)
575
+ else if (mine) index = mine.index
576
+ else return fail('this wallet is not a payee of this combined recipient: only a slot\'s own payee can move it', { wallet: me(), payees: s.payees.map((p) => p.payee) })
577
+ const slot = s.payees[index]
578
+ if (slot.payee.toLowerCase() !== wallet) return fail(HINTS.NotPayee, { index, payee: slot.payee, wallet: me() })
579
+ const to = opt('to')
580
+ 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 })
581
+ if (to.toLowerCase() === s.module.toLowerCase()) return fail(HINTS.BadPayee, { to })
582
+ const taken = s.payees.find((p) => p.payee.toLowerCase() === to.toLowerCase())
583
+ if (taken) return fail(taken.index === index ? 'that is this slot\'s payee already' : HINTS.DuplicatePayee, { to, index: taken.index })
584
+ // the contract splits only the bound quote before the move: other assets that arrived would go to the new address,
585
+ // so split those first (each its own tx, then the same command again); needs the module bound (NotBound before)
586
+ const unsplit = s.token ? s.assets.filter((x) => !x.boundQuote && Number(x.undistributed) > 0) : []
587
+ if (unsplit.length) {
588
+ const first = unsplit[0]
589
+ return send('distribute', [first.asset], {
590
+ step: 'distribute-first', asset: first.asset, symbol: first.symbol, amount: first.undistributed,
591
+ ...(unsplit.length > 1 && { thenAlso: unsplit.slice(1).map((x) => ({ asset: x.asset, symbol: x.symbol, amount: x.undistributed })) }),
592
+ note: `before the move: ${first.symbol || first.asset} that arrived earlier is distributed to the current payees (and its buy-back + LP share to 0xdead); the contract splits only the bound quote itself. After executing, re-run the same command. Gas: ${COMBO_GAS_NOTE}`,
593
+ })
594
+ }
595
+ return send('setPayee', [BigInt(index), getAddress(to)], {
596
+ step: 'set-payee', index, pctOfRest: slot.pctOfRest, fromPayee: slot.payee, toPayee: getAddress(to),
597
+ note: `applies at once; the share (${slot.pctOfRest}% of the rest) 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. The ratios and the other slots stay as they are (fixed for good). Gas: ${COMBO_GAS_NOTE}`,
598
+ })
599
+ }
600
+
601
+ function indexArg(raw, n, fail) {
602
+ const i = Number(raw)
603
+ 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 combo status lists them)`, { got: raw ?? null })
604
+ return i
605
+ }