@gangfun/cli 0.22.0 → 0.24.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/buyback.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createPublicClient, parseAbi, encodeFunctionData, formatUnits, hexToString, isAddress, zeroAddress } from 'viem'
2
- import { padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
2
+ import { atPad, atTokenPad, GANG_GENS, KIND_UNREAD, gangGens, listedBy, padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
3
3
  import { walletFor } from './fair.js'
4
4
  import { parseNum, revertOf as revertIn, step } from './steps.js'
5
5
 
@@ -13,17 +13,16 @@ import { parseNum, revertOf as revertIn, step } from './steps.js'
13
13
  * want it leaves --buyback out: the tax goes to their own address as before.
14
14
  * The ratio: a raise applies at once, a cut 3 days after it is asked for (then anyone applies it within 7 days, or it
15
15
  * lapses). The keeper buys back in chunks (≤ 0.5% of the pool's quote side, never > 2% above the 10-minute average).
16
- * Env: GANG_SPLITTER_FACTORY / GANG_TESTNET_SPLITTER_FACTORY override the built-in factory addresses.
16
+ * Env: GANG_SPLITTER_FACTORY / GANG_TESTNET_SPLITTER_FACTORY override the create target's factory (gangpad.js).
17
17
  */
18
18
 
19
- // BSC 56, factory v3 (one chunk per 4 minutes; docs/MAINNET-BUYBACK-SPLITTER-2026-10-28.md). v2 0x9346…8F2f and v1
20
- // 0x6bcd…8546 (2-argument create) are stopped: their clones keep working, new ones can't be made
21
- export const MAINNET_SPLITTER_FACTORY = '0xf1d5CA816d72e6F130f42662d11b238312A7F1Cd'
22
- export const TESTNET_SPLITTER_FACTORY = '0x7E63fF8A9FB9Ab1BE4e2128e9f6C8D1054292BBe'
23
- /** The factory's clones; v1 (mainnet's first factory, 0x6bcd…8546) pays the dev, v2 and v3 their payee; v3 buys at
24
- * most one chunk per 4 minutes (GangBond audit H-1). */
25
- export const BUYBACK_TYPE = 'buyback-burn-v3'
26
- const BUYBACK_TYPES = ['buyback-burn-v1', 'buyback-burn-v2', BUYBACK_TYPE]
19
+ // one factory per GangLaunchpad generation (it is bound to one pad): the create target's (GANG_GENS in gangpad.js)
20
+ export const MAINNET_SPLITTER_FACTORY = GANG_GENS.mainnet[0].splitterFactory
21
+ export const TESTNET_SPLITTER_FACTORY = GANG_GENS.testnet[0].splitterFactory
22
+ /** The factories' clones; v1 (mainnet's first factory, 0x6bcd…8546) pays the dev, v2 and later their payee; v3 buys at
23
+ * most one chunk per 4 minutes (GangBond audit H-1); v4 (GangLaunchpad 2.0's factory) prices a chunk on what the pair
24
+ * received (re-review L-1). Same calls from v2 on. */
25
+ const BUYBACK_TYPES = ['buyback-burn-v1', 'buyback-burn-v2', 'buyback-burn-v3', 'buyback-burn-v4']
27
26
 
28
27
  export const FACTORY_ABI = parseAbi([
29
28
  'function create(uint16 buybackBps, bytes32 salt, address payee) returns (address splitter)',
@@ -49,6 +48,9 @@ export const SPLITTER_ABI = parseAbi([
49
48
  'function setBuybackBps(uint16 newBps)',
50
49
  'function applyBuybackBps()',
51
50
  'function releaseDev() returns (uint256)',
51
+ 'function split()',
52
+ 'function sweep(address asset)',
53
+ 'function pad() view returns (address)',
52
54
  'function payee() view returns (address)',
53
55
  'function setPayee(address newPayee)',
54
56
  'error NotDev()',
@@ -61,6 +63,8 @@ export const SPLITTER_ABI = parseAbi([
61
63
  'error NotDue()',
62
64
  'error CutLapsed()',
63
65
  'error NothingOwed()',
66
+ 'error NotBound()',
67
+ 'error NotSweepable()',
64
68
  ])
65
69
 
66
70
  const PAD_ABI = parseAbi([
@@ -78,12 +82,13 @@ const HINTS = {
78
82
  CutLapsed: 'the cut was not applied within 7 days after its notice and has lapsed: ask for it again',
79
83
  NoProposal: 'no cut asked for',
80
84
  NothingOwed: 'nothing is owed to the dev',
85
+ NotBound: 'the splitter is not bound to a token yet',
86
+ NotSweepable: 'sweep never moves the splitter\'s own quote: gang buyback split splits it',
81
87
  }
82
88
  const revertOf = (e) => revertIn(e, [SPLITTER_ABI, FACTORY_ABI], HINTS)
83
89
 
84
90
  export function splitterFactoryAddress(testnet) {
85
- return (testnet ? process.env.GANG_TESTNET_SPLITTER_FACTORY || TESTNET_SPLITTER_FACTORY
86
- : process.env.GANG_SPLITTER_FACTORY || MAINNET_SPLITTER_FACTORY) || null
91
+ return gangGens(testnet)[0].splitterFactory || null
87
92
  }
88
93
 
89
94
  export const notDeployed = (testnet) =>
@@ -93,6 +98,61 @@ export const notDeployed = (testnet) =>
93
98
  export const buybackBpsOf = (fail, raw) => Math.round(parseNum(fail, 'buyback', raw, 0, 100) * 100)
94
99
 
95
100
  const pct = (bps) => Number(bps) / 100
101
+ const SYMBOL_ABI = parseAbi(['function symbol() view returns (string)'])
102
+ const ASSET_ABI = parseAbi(['function symbol() view returns (string)', 'function decimals() view returns (uint8)', 'function balanceOf(address) view returns (uint256)'])
103
+
104
+ /** --asset <addr>|wbnb of a sweep (required). */
105
+ export function sweepAsset(opt, fail, wbnb) {
106
+ const a = opt('asset')
107
+ if (/^wbnb$/i.test(a ?? '')) return wbnb
108
+ if (!isAddress(a ?? '') || a === zeroAddress) fail('--asset <addr>|wbnb required: the asset to send to the payee (any but the splitter\'s own quote)', { got: a ?? null })
109
+ return a
110
+ }
111
+
112
+ /**
113
+ * `sweep` of a buy-back / LP splitter, from the raw reads (pure: unit-tested): the splitter's whole balance of `asset`
114
+ * goes to the payee (the contract refuses its own quote and an unbound splitter). { error } when it can't.
115
+ */
116
+ export function sweepPlan({ asset, quote, balance, decimals = 18, symbol, payee, cmd }) {
117
+ if (!quote || /^0x0{40}$/.test(quote)) return { error: 'the splitter is not bound to a token yet: sweep works once it is bound (its launch binds it)' }
118
+ if (asset.toLowerCase() === quote.toLowerCase()) return { error: `that is the splitter's own quote: sweep never moves it; ${cmd} split splits it (the payee's part now, the rest set aside)` }
119
+ if (BigInt(balance) === 0n) return { error: `the splitter holds no ${symbol ?? asset}: nothing to sweep` }
120
+ return { asset, assetSymbol: symbol ?? null, amount: formatUnits(BigInt(balance), Number(decimals)), payee }
121
+ }
122
+
123
+ /** The reads behind sweepPlan: the splitter's quote and its balance of `asset`. */
124
+ export async function sweepReads(read, splitter, abi, asset) {
125
+ const [quote, balance, decimals, symbol] = await Promise.all([
126
+ read(splitter, abi, 'quote'), read(asset, ASSET_ABI, 'balanceOf', [splitter]),
127
+ read(asset, ASSET_ABI, 'decimals').catch(() => 18), read(asset, ASSET_ABI, 'symbol').catch(() => null),
128
+ ])
129
+ return { quote, balance, decimals, symbol }
130
+ }
131
+
132
+ /** A module named by --module that no GangLaunchpad pad of this network owns, or that its GangHandlerAdmin never listed. */
133
+ export const notListed = (what, net) =>
134
+ `not one of the platform's ${what}s: no GangLaunchpad pad${net ? ' on the BSC testnet' : ''} lists it (GangHandlerAdmin moduleOf), so the CLI will not call it`
135
+
136
+ /**
137
+ * `split` of a buy-back / LP splitter, from the raw reads (pure: unit-tested): what arrived since the last split
138
+ * (`unsplit`), the share set aside (`bps`, for `part`: the buy-back or the liquidity) and the payee's part, pushed now.
139
+ * { error } when nothing waits to be split.
140
+ */
141
+ export function splitPlan({ unsplit, bps, left, payee, part, leftField, symbol, unbound }) {
142
+ const waiting = BigInt(unsplit)
143
+ if (waiting === 0n) {
144
+ return {
145
+ error: unbound ? 'nothing to split: the splitter is not bound to a token yet, so it has no quote'
146
+ : `nothing waits to be split: no quote arrived since the last split${BigInt(left) > 0n ? ` (${leftField} ${formatUnits(BigInt(left), 18)} is already set aside)` : ''}`,
147
+ }
148
+ }
149
+ const setAside = (waiting * BigInt(bps)) / 10_000n
150
+ const toPayee = waiting - setAside
151
+ return {
152
+ quote: symbol, splitting: formatUnits(waiting, 18), toPayee: formatUnits(toPayee, 18), payee,
153
+ setAside: formatUnits(setAside, 18), setAsideFor: part, [`${leftField}After`]: formatUnits(BigInt(left) + setAside, 18),
154
+ }
155
+ }
96
156
  const iso = (s) => new Date(Number(s) * 1000).toISOString()
97
157
 
98
158
  /** The splitter's state when `addr` is a GangBuybackSplitter; null when it is not (an EOA, a partner, another module). */
@@ -137,8 +197,8 @@ export async function simulateCall(client, from, address, abi, functionName, arg
137
197
  }
138
198
  }
139
199
 
140
- const SUBS = ['status', 'set', 'set-payee', 'apply', 'bind', 'release']
141
- const USAGE = 'usage: gang buyback <status|set|set-payee|apply|bind|release> --token <addr> [--pct <0-100>] [--to <addr>] [--testnet] — see gang help'
200
+ const SUBS = ['status', 'set', 'set-payee', 'apply', 'bind', 'release', 'split', 'sweep']
201
+ const USAGE = 'usage: gang buyback <status|set|set-payee|apply|bind|release|split|sweep> --token <addr> (split / sweep: or --module <addr>) [--pct <0-100>] [--to <addr>] [--asset <addr>|wbnb] [--testnet] — see gang help'
142
202
 
143
203
  /** `gang buyback <sub>`: the splitter of a V3 token (its tax recipient), found from --token. */
144
204
  export async function runBuyback(sub, { opt, flag, out, fail, summarize }) {
@@ -147,14 +207,29 @@ export async function runBuyback(sub, { opt, flag, out, fail, summarize }) {
147
207
  const rawOnly = flag('calldata')
148
208
  let ctx
149
209
  try { ctx = buybackCtx(testnet) } catch (e) { return fail(e.message) }
150
- const token = opt('token')
151
- if (!isAddress(token ?? '')) fail('--token must be a V3 token address (0x…)', { got: token ?? null })
210
+ // split / sweep may name the splitter itself (--module), e.g. the --to of a creator-fee claim
211
+ const named = (sub === 'split' || sub === 'sweep') && flag('module')
212
+ if (named && flag('token')) fail('give --token (its tax recipient is the splitter) or --module, not both')
213
+ let token = opt('token')
152
214
  let recipient
153
- try { recipient = (await ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token]))[3] } catch {
154
- return fail('not a V3 token on this pad', { token, chainId: Number(ctx.chainId) })
215
+ if (named) {
216
+ recipient = opt('module')
217
+ if (!isAddress(recipient ?? '')) fail('--module must be a buy-back splitter address (0x…)', { got: recipient ?? null })
218
+ const pad = await ctx.read(recipient, SPLITTER_ABI, 'pad').catch(() => null)
219
+ if (!pad || !atPad(ctx, pad, testnet)) return fail(notListed('buy-back splitter', testnet), { module: recipient })
220
+ } else {
221
+ if (!isAddress(token ?? '')) fail('--token must be a V3 token address (0x…)', { got: token ?? null })
222
+ if ((await atTokenPad(ctx, token)) === null) return fail(KIND_UNREAD.error, { token: token, retry: KIND_UNREAD.retry }) // else on the pad of the token's generation
223
+ try { recipient = (await ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token]))[3] } catch {
224
+ return fail('not a V3 token on this pad', { token, chainId: Number(ctx.chainId) })
225
+ }
155
226
  }
156
227
  const s = await splitterOf(ctx.read, recipient)
157
- if (!s) return fail('this token\'s tax recipient is not a buy-back splitter', { token, recipient: recipient === zeroAddress ? null : recipient })
228
+ if (!s) {
229
+ return fail(named ? 'not a buy-back splitter (buyback-burn-v1 … v4)' : 'this token\'s tax recipient is not a buy-back splitter',
230
+ named ? { module: recipient } : { token, recipient: recipient === zeroAddress ? null : recipient })
231
+ }
232
+ if (named) token = s.token
158
233
  const chainId = Number(ctx.chainId)
159
234
  const me = () => walletFor(ctx, opt('from'))
160
235
  const send = async (functionName, args, extra) => {
@@ -201,6 +276,30 @@ export async function runBuyback(sub, { opt, flag, out, fail, summarize }) {
201
276
  return send('applyBuybackBps', [], { step: 'apply-cut', fromPct: s.buybackPct, toPct: s.pendingCut.toPct, note: 'anyone may apply a cut once its notice ran' })
202
277
  }
203
278
 
279
+ if (sub === 'split') {
280
+ if (!(await listedBy(ctx, s.splitter))) return fail(notListed('buy-back splitter', testnet), { module: s.splitter })
281
+ const [waiting, left, quote] = await Promise.all(['unsplit', 'buybackLeft', 'quote'].map((f) => ctx.read(s.splitter, SPLITTER_ABI, f)))
282
+ const symbol = quote === zeroAddress ? null : await ctx.read(quote, SYMBOL_ABI, 'symbol').catch(() => null)
283
+ const plan = splitPlan({ unsplit: waiting, bps: s.buybackBps, left, payee: s.payee, part: 'buy-back', leftField: 'buybackLeft', symbol, unbound: !s.token })
284
+ if (plan.error) return fail(plan.error, { splitter: s.splitter, buybackLeft: s.buybackLeft, devOwed: s.devOwed })
285
+ const ref = `--token ${s.token}${testnet ? ' --testnet' : ''}`
286
+ return send('split', [], {
287
+ step: 'split', ...plan,
288
+ note: `anyone may: splits what arrived since the last split. ${plan.toPayee} goes to the payee now (should that push fail, it is owed: gang buyback release ${ref}); ${plan.setAside} (${s.buybackPct}%) is set aside for the buy-back, which the keeper spends in chunks once the token trades in its pool (each chunk splits first too, so after graduation this runs by itself)`,
289
+ })
290
+ }
291
+
292
+ if (sub === 'sweep') {
293
+ if (!(await listedBy(ctx, s.splitter))) return fail(notListed('buy-back splitter', testnet), { module: s.splitter })
294
+ const asset = sweepAsset(opt, fail, ctx.wbnb)
295
+ const plan = sweepPlan({ asset, ...(await sweepReads(ctx.read, s.splitter, SPLITTER_ABI, asset)), payee: s.payee, cmd: 'gang buyback' })
296
+ if (plan.error) return fail(plan.error, { splitter: s.splitter, asset })
297
+ return send('sweep', [asset], {
298
+ step: 'sweep', ...plan,
299
+ note: 'anyone may: sends the splitter\'s whole balance of this asset (not its own quote; e.g. a creator fee or another token\'s tax in another quote) to the payee; none of it is bought back',
300
+ })
301
+ }
302
+
204
303
  // release
205
304
  if (!(Number(s.devOwed) > 0)) return fail(HINTS.NothingOwed)
206
305
  return send('releaseDev', [], { step: 'release', amount: s.devOwed, payee: s.payee, note: 'anyone may; the payee gets what a failed push left owed' })
package/src/chain.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createPublicClient, formatEther, parseEther, encodeFunctionData, decodeEventLog, isAddress, zeroAddress } from 'viem'
2
2
  import { bsc } from 'viem/chains'
3
3
  import { SOFT_ABI, V2_ABI, S_ABI, ERC20_ABI, WBNB_ABI } from './abi.js'
4
- import { kindOf, padNets, rpcTransport } from './gangpad.js'
4
+ import { genOf, padNets, rpcTransport } from './gangpad.js'
5
5
  import { mapLimit } from './limit.js'
6
6
 
7
7
  export const ADDR = {
@@ -49,7 +49,7 @@ export async function resolvePad(token) {
49
49
  } catch { /* wrong ABI shape or empty */ }
50
50
  }
51
51
  // tokens from `gang create` / `gang fair create` live on GangLaunchpad, which these commands don't trade
52
- const kind = await kindOf({ pad: padNets('v3').mainnet.pad, read }, token)
52
+ const { kind } = await genOf({ gens: padNets('v3').mainnet.gens, read }, token)
53
53
  if (GANG_POINTER[kind]) throw new Error(`${token} is ${GANG_POINTER[kind](token)}`)
54
54
  throw new Error(
55
55
  `not a Gang token on known pads (V2/Soft/U/S): ${token}. ` +
package/src/combo.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createPublicClient, parseAbi, encodeFunctionData, formatUnits, getAddress, hexToString, isAddress, maxUint128, maxUint256, parseUnits, zeroAddress } from 'viem'
2
- import { padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
2
+ import { atTokenPad, GANG_GENS, gangGens, KIND_UNREAD, padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
3
3
  import { walletFor } from './fair.js'
4
4
  import { parseAmount, parseNum, revertOf as revertIn, step } from './steps.js'
5
5
  import { parseSplitSpec } from './split.js'
@@ -22,14 +22,13 @@ import { parseSplitSpec } from './split.js'
22
22
  * `bind`).
23
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
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 built-in factory addresses.
25
+ * Env: GANG_COMBO_FACTORY / GANG_TESTNET_COMBO_FACTORY override the create target's factory (gangpad.js).
26
26
  */
27
27
 
28
- // BSC 56: deployed 2026-10-31 (pad 0x15CF…4365); a clone reverts NotFactory until the platform's Safe allows the
29
- // factory on GangHandlerAdmin
30
- export const MAINNET_COMBO_FACTORY = '0xd33C38BE3f8472b3013167830F0638C1704e1DBd'
31
- // BSC 97, set 10
32
- export const TESTNET_COMBO_FACTORY = '0x52a8f90a92E5C1828b4436a0B99C6b293f7F4CFE'
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
33
32
  export const COMBO_TYPE = 'combo-v1'
34
33
  export const MAX_PAYEES = 10
35
34
  const BPS = 10_000
@@ -161,9 +160,9 @@ export async function simulateCombo(client, from, address, abi, functionName, ar
161
160
  }
162
161
  }
163
162
 
163
+ /** The create target's combo factory (a launch clones its combined recipient there, for the pad the token goes to). */
164
164
  export function comboFactoryAddress(testnet) {
165
- return (testnet ? process.env.GANG_TESTNET_COMBO_FACTORY || TESTNET_COMBO_FACTORY
166
- : process.env.GANG_COMBO_FACTORY || MAINNET_COMBO_FACTORY) || null
165
+ return gangGens(testnet)[0].comboFactory || null
167
166
  }
168
167
 
169
168
  export const comboNotDeployed = (testnet) => (testnet
@@ -423,6 +422,7 @@ export async function runCombo(sub, { opt, flag, out, fail, summarize }) {
423
422
  } else {
424
423
  token = opt('token')
425
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
426
  try {
427
427
  const [creator, quote] = await ctx.read(ctx.pad, PAD_ABI, 'curves', [token])
428
428
  if (creator === zeroAddress) throw new Error('not a curve')
@@ -0,0 +1,261 @@
1
+ import { createPublicClient, encodeFunctionData, hexToString, isAddress, parseAbi, zeroAddress } from 'viem'
2
+ import { revertOf as revertIn, step, units } from './steps.js'
3
+ import { atTokenPad, CREATOR_FEE_ABI, creatorFeeShareOf, NOT_ON_MAINNET, padNets, rpcTransport } from './gangpad.js'
4
+ import { walletFor } from './fair.js'
5
+
6
+ /**
7
+ * `gang creator-fee` — the GangLaunchpad 2.0 creator fee (docs/SPEC-CURVE-CREATOR-FEE-2026-10-31.md): of the 1% fee on
8
+ * each V3 curve buy and sell, 70% is kept on the pad for the token's creator (`creatorFeeOf`), the rest goes to the
9
+ * platform. The creator claims it with `claimCreatorFee(token, to)`, to any address, before or after graduation, with no
10
+ * deadline. It is the creating wallet's own: it never goes to the tax recipient, a buy-back splitter, a split module or
11
+ * an LP splitter. 打新 sales and 1.0 pads have none (on 1.0 the whole curve fee is the platform's).
12
+ */
13
+
14
+ const CURVES_ABI = parseAbi([
15
+ '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)',
16
+ 'function tokenCount() view returns (uint256)',
17
+ 'function allTokens(uint256) view returns (address)',
18
+ 'function kindOf(address token) view returns (uint8)',
19
+ 'error ZeroAmount()', 'error ZeroAddress()', 'error UnknownToken()',
20
+ ])
21
+ const SYMBOL_ABI = parseAbi(['function symbol() view returns (string)'])
22
+ const MODULE_TYPE_ABI = parseAbi(['function moduleType() view returns (bytes32)'])
23
+ const QUOTE_ABI = parseAbi(['function quote() view returns (address)'])
24
+ const ABIS = [CREATOR_FEE_ABI, CURVES_ABI]
25
+ const HINTS = {
26
+ NotCreator: 'only the token\'s creator (the wallet that created it) can claim its creator fee; pass that wallet with --from',
27
+ ZeroAmount: 'nothing to claim yet: the creator fee grows with each curve buy and sell',
28
+ ZeroAddress: '--to cannot be the zero address or the pad itself',
29
+ UnknownToken: 'not a V3 curve token of this pad (打新 sales have no creator fee)',
30
+ }
31
+ const revertOf = (e) => revertIn(e, ABIS, HINTS)
32
+
33
+ // a scan reads at most this many of a pad's newest tokens, in multicall batches of BATCH
34
+ const MAX_SCAN = 5000
35
+ const BATCH = 400
36
+
37
+ export const claimCmd = (token, net = '') => `gang creator-fee --token ${token}${net} --claim`
38
+ const same = (a, b) => !!a && !!b && a.toLowerCase() === b.toLowerCase()
39
+ const pctOf = (bps) => bps / 100
40
+
41
+ /** A ctx on the create target of `testnet` / mainnet, with every generation in ctx.gens. */
42
+ export function creatorFeeCtx(testnet) {
43
+ const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
44
+ if (!net.pad) throw new Error(NOT_ON_MAINNET)
45
+ const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
46
+ return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
47
+ }
48
+
49
+ /** What a V3 create on ctx.pad says about the creator fee, or null when that pad has none (1.0). */
50
+ export async function createNote(ctx, net = '') {
51
+ let share
52
+ try { share = await creatorFeeShareOf(ctx) } catch {
53
+ return `could not read whether this pad keeps a creator fee (RPC error); gang creator-fee${net} shows it once the token is out`
54
+ }
55
+ if (share == null) return null
56
+ return `${pctOf(share)}% of the 1% curve fee on every curve buy and sell (until graduation) is kept on the pad for you, the creator. Claim it any time, before or after graduation: gang creator-fee${net} lists it, gang creator-fee --token <token>${net} --claim [--to <addr>] claims it.`
57
+ }
58
+
59
+ /**
60
+ * What pays out a fee claimed into a module, by its moduleType(): the buy-back and LP splitters pay their payee only
61
+ * when they split (the keeper's chunks do it after graduation), the split module and the combined recipient on
62
+ * distribute. null: not one of these.
63
+ */
64
+ export function payOutCmd(moduleType, at, net = '', { asset, assetSymbol } = {}) {
65
+ const t = String(moduleType ?? '')
66
+ const base = t.startsWith('buyback-burn-') ? 'gang buyback' : t === 'lp-burn-v1' ? 'gang lp'
67
+ : t === 'split-v1' ? 'gang split' : t === 'combo-v1' ? 'gang combo' : null
68
+ if (!base) return null
69
+ const splitter = base === 'gang buyback' || base === 'gang lp'
70
+ const m = `--module ${at ?? '<module>'}`
71
+ // a fee in another quote than the module's own: split / distribute of the bound quote never moves it
72
+ if (asset) {
73
+ return splitter
74
+ ? `${base} sweep ${m} --asset ${asset}${net} (anyone) sends all of it to the payee (${assetSymbol ?? 'this asset'} is not split: no ${base === 'gang lp' ? 'pool' : 'buy-back'} share)`
75
+ : `${base} distribute ${m} --asset ${asset}${net} (anyone) pays the payees their shares of it`
76
+ }
77
+ return `${base} ${splitter ? 'split' : 'distribute'} ${m}${net} (anyone) then pays ${splitter ? 'the payee its part and sets the rest aside' : 'the payees their shares'}`
78
+ + (splitter ? '; after graduation each keeper chunk splits first, so it also goes out with the next chunk' : '')
79
+ }
80
+
81
+ /**
82
+ * The claim's --to note when --to is a module (pure: unit-tested): `bound` is its quote() (zero: not bound yet),
83
+ * `quote` the token's. { payOut, warning }: a fee in another quote is not moved by split / distribute.
84
+ */
85
+ export function claimToModule({ moduleType, at, net = '', bound, quote, quoteSymbol, boundSymbol }) {
86
+ const other = !!bound && !!quote && bound.toLowerCase() !== quote.toLowerCase()
87
+ const unbound = !bound || /^0x0{40}$/.test(bound)
88
+ const payOut = payOutCmd(moduleType, at, net, other && !unbound ? { asset: quote, assetSymbol: quoteSymbol } : {})
89
+ if (!payOut) return { payOut: null, warning: null }
90
+ if (unbound) return { payOut, warning: 'the module is not bound to a token yet: it pays this out only once it is bound (its launch binds it)' }
91
+ if (!other) return { payOut, warning: null }
92
+ return {
93
+ payOut,
94
+ warning: `the module's own quote is ${boundSymbol ?? bound}, this fee is in ${quoteSymbol ?? quote}: split / distribute of the module's quote leave it where it is`,
95
+ }
96
+ }
97
+ const LAUNCH_TYPES = { buyback: 'buyback-burn-v4', lp: 'lp-burn-v1', split: 'split-v1', combo: 'combo-v1' }
98
+
99
+ /** Added to the create's note when the tax recipient is one of the dev's modules (`module`: its name; `kind`: buyback | lp | split | combo). */
100
+ export const notThroughModule = (module, { token, at, net = '', kind } = {}) =>
101
+ `This creator fee is yours, the creating wallet's: it does not go through the ${module}, which gets only the recipient's part of the pool tax after graduation.`
102
+ + (at ? ` To put it into the ${module} anyway, claim it there: gang creator-fee --token ${token ?? '<token>'}${net} --claim --to ${at}` : '')
103
+ + (at && kind && LAUNCH_TYPES[kind] ? `; ${payOutCmd(LAUNCH_TYPES[kind], at, net)}` : '')
104
+
105
+ /**
106
+ * The creator fee of a V3 curve `token` on ctx.pad (ctx already on the token's generation) for info / status:
107
+ * { padGen, creatorFee } — creatorFee null on a 1.0 pad.
108
+ */
109
+ export async function curveCreatorFee(ctx, token, { creator, quote }, net = '') {
110
+ let share, owed
111
+ try {
112
+ share = await creatorFeeShareOf(ctx)
113
+ if (share != null) owed = await ctx.read(ctx.pad, CREATOR_FEE_ABI, 'creatorFeeOf', [token])
114
+ } catch (e) {
115
+ // an RPC error leaves the field out of this answer rather than failing the whole info / status
116
+ return { padGen: ctx.gen, creatorFee: { error: `could not read the creator fee (${e.shortMessage || e.message.split('\n')[0]})`, retry: `gang creator-fee --token ${token}${net}` } }
117
+ }
118
+ const padGen = ctx.gen ?? (share == null ? '1.0' : '2.0')
119
+ if (share == null) return { padGen, creatorFee: null }
120
+ return {
121
+ padGen,
122
+ creatorFee: {
123
+ sharePct: pctOf(share), creator, claimable: await units(ctx, quote, owed), claimableRaw: owed.toString(),
124
+ ...(owed > 0n && { claim: `${claimCmd(token, net)} (the creator only)` }),
125
+ note: `${pctOf(share)}% of the 1% curve fee of each curve buy and sell is kept for the creator, apart from the pool tax and its recipient; the creator claims it any time`,
126
+ },
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Every 2.0 curve token `creator` created on this network, newest first, with what it can claim: { tokens, totals,
132
+ * scanned }. Read on chain (each 2.0 pad's allTokens, in multicall batches), so it works without gang.fun's index.
133
+ */
134
+ export async function creatorFeeList(ctx, creator) {
135
+ const tokens = []
136
+ const scanned = []
137
+ let unread = 0 // tokens whose row could not be read
138
+ for (const g of ctx.gens) {
139
+ const share = await creatorFeeShareOf(ctx, g.pad)
140
+ if (share == null) continue
141
+ const n = Number(await ctx.read(g.pad, CURVES_ABI, 'tokenCount'))
142
+ const take = Math.min(n, MAX_SCAN)
143
+ scanned.push({ padGen: g.gen ?? '2.0', pad: g.pad, tokens: n, read: take })
144
+ const call = (functionName, args) => ({ address: g.pad, abi: functionName === 'creatorFeeOf' ? CREATOR_FEE_ABI : CURVES_ABI, functionName, args })
145
+ // one eth_call per batch (viem would split it into 1 KB calls), and a row that fails is skipped, not the whole scan
146
+ const multi = (contracts, allowFailure = true) => ctx.client.multicall({ contracts, allowFailure, batchSize: 0 })
147
+ for (let from = 0; from < take; from += BATCH) {
148
+ const idx = Array.from({ length: Math.min(BATCH, take - from) }, (_, i) => BigInt(n - 1 - from - i))
149
+ const addrs = await multi(idx.map((i) => call('allTokens', [i])), false)
150
+ const curves = await multi(addrs.map((t) => call('curves', [t])))
151
+ unread += curves.filter((c) => c.status !== 'success').length
152
+ const mine = addrs.map((t, i) => ({ t, c: curves[i].result })).filter(({ c }) => c && same(c[0], creator))
153
+ if (!mine.length) continue
154
+ const owedOf = await multi(mine.map(({ t }) => call('creatorFeeOf', [t])))
155
+ const syms = await multi(mine.flatMap(({ t, c }) => [{ address: t, abi: SYMBOL_ABI, functionName: 'symbol' }, { address: c[1], abi: SYMBOL_ABI, functionName: 'symbol' }]))
156
+ for (const [i, { t, c }] of mine.entries()) {
157
+ if (owedOf[i].status !== 'success') { unread++; continue }
158
+ const owed = [owedOf[i].result]
159
+ tokens.push({
160
+ token: t, symbol: syms[2 * i].result ?? null, quote: c[1], quoteSymbol: syms[2 * i + 1].result ?? null, graduated: c[6],
161
+ padGen: g.gen ?? '2.0', claimable: await units(ctx, c[1], owed[0]), claimableRaw: owed[0],
162
+ })
163
+ }
164
+ }
165
+ }
166
+ // per quote: what all of them add up to
167
+ const sums = new Map()
168
+ for (const x of tokens) {
169
+ const k = x.quote.toLowerCase()
170
+ sums.set(k, { quote: x.quote, quoteSymbol: x.quoteSymbol, raw: (sums.get(k)?.raw ?? 0n) + x.claimableRaw })
171
+ }
172
+ const totals = await Promise.all([...sums.values()].map(async (s) => ({ quote: s.quoteSymbol ?? s.quote, claimable: await units(ctx, s.quote, s.raw) })))
173
+ return {
174
+ tokens: tokens.map((x) => ({ ...x, claimableRaw: x.claimableRaw.toString() })), totals, scanned,
175
+ ...(unread && { unreadNote: `${unread} token(s) could not be read (RPC); run it again to include them` }),
176
+ }
177
+ }
178
+
179
+ const USAGE = 'usage: gang creator-fee [--token <addr>] [--from <creator>] [--claim [--to <addr>]] [--testnet] — see gang help'
180
+
181
+ /** Entry for `gang creator-fee`. io: { opt, flag, out, fail, summarize } from index.js. */
182
+ export async function runCreatorFee({ opt, flag, out, fail, summarize }) {
183
+ const testnet = flag('testnet')
184
+ const net = testnet ? ' --testnet' : ''
185
+ const rawOnly = flag('calldata')
186
+ if (flag('to') && !flag('claim')) fail('--to goes with --claim (where the claimed fee is sent)')
187
+ if (flag('claim') && !flag('token')) fail('--claim needs --token <addr>: one token per claim (gang creator-fee lists them)')
188
+ let ctx
189
+ try { ctx = creatorFeeCtx(testnet) } catch (e) { return fail(e.message) }
190
+ const chainId = Number(ctx.chainId)
191
+
192
+ if (flag('from') && !isAddress(opt('from') ?? '')) fail('--from must be a 0x address (checksummed or all lowercase)', { got: opt('from') ?? null })
193
+ if (!flag('token')) {
194
+ const me = walletFor(ctx, opt('from'))
195
+ const r = await creatorFeeList(ctx, me)
196
+ if (!r.scanned.length) {
197
+ return out({
198
+ success: true, chainId, creator: me, tokens: [], totals: [],
199
+ note: `GangLaunchpad 2.0 is not on ${testnet ? 'the BSC testnet' : 'BSC mainnet'} in this CLI version yet: tokens created on 1.0 have no creator fee (their whole 1% curve fee is the platform's)`,
200
+ })
201
+ }
202
+ const due = r.tokens.filter((x) => x.claimableRaw !== '0')
203
+ return out({
204
+ success: true, chainId, creator: me, ...r,
205
+ ...(r.scanned.some((s) => s.read < s.tokens) && { scanNote: `only the newest ${MAX_SCAN} tokens of a pad were read` }),
206
+ note: 'GangLaunchpad 2.0 keeps 70% of the 1% curve fee of each curve buy and sell for the token\'s creator; 1.0 tokens and 打新 sales have none',
207
+ ...(due.length && { next: due.map((x) => claimCmd(x.token, net)) }),
208
+ })
209
+ }
210
+
211
+ const token = opt('token')
212
+ if (!isAddress(token ?? '')) fail('--token must be a 0x address', { got: token ?? null })
213
+ const kind = await atTokenPad(ctx, token)
214
+ if (kind === null) return fail('could not read the token\'s kind from GangLaunchpad (kindOf; RPC error)', { token, retry: 'same command again' })
215
+ if (kind === 'none') return fail(`not a GangLaunchpad token on ${testnet ? 'the BSC testnet' : 'BSC mainnet'}${testnet ? '' : ' (add --testnet for a testnet token)'}`, { token, chainId })
216
+ if (kind === 'fair') return fail('a 打新 (fair-mint) sale has no creator fee: only V3 curve trades on GangLaunchpad 2.0 pay one', { token, kind })
217
+ const c = await ctx.read(ctx.pad, CURVES_ABI, 'curves', [token])
218
+ const [creator, quote, , , , , graduated] = c
219
+ const symbol = await ctx.read(token, SYMBOL_ABI, 'symbol').catch(() => null)
220
+ const view = await curveCreatorFee(ctx, token, { creator, quote }, net)
221
+ if (!view.creatorFee) {
222
+ return fail(`this token is on GangLaunchpad ${view.padGen}, which has no creator fee: its whole 1% curve fee goes to the platform (the creator fee is on tokens created on 2.0)`,
223
+ { token, padGen: view.padGen, pad: ctx.pad })
224
+ }
225
+ const base = { chainId, token, symbol, graduated, padGen: view.padGen, pad: ctx.pad, ...view.creatorFee }
226
+
227
+ if (!flag('claim')) return out({ success: true, ...base })
228
+
229
+ const me = walletFor(ctx, opt('from'))
230
+ if (!same(me, creator)) return fail(HINTS.NotCreator, { token, wallet: me, creator })
231
+ if (BigInt(view.creatorFee.claimableRaw) === 0n) return fail(HINTS.ZeroAmount, { token, claimable: view.creatorFee.claimable })
232
+ const to = flag('to') ? opt('to') : me
233
+ if (!isAddress(to ?? '')) fail('--to must be a 0x address (checksummed or all lowercase)', { got: to ?? null })
234
+ if (to === zeroAddress) fail('--to cannot be the zero address')
235
+ if (same(to, ctx.pad)) fail('--to cannot be the pad itself: the fee would stay where it is (the pad refuses it)')
236
+ const args = [token, to]
237
+ try {
238
+ await ctx.client.simulateContract({ account: me, address: ctx.pad, abi: CREATOR_FEE_ABI, functionName: 'claimCreatorFee', args })
239
+ } catch (e) {
240
+ const r = revertOf(e)
241
+ return out({ success: false, step: 'claim-creator-fee', ...(r ? { reverted: true, ...r } : { reverted: false, error: e.shortMessage || e.message.split('\n')[0] }) })
242
+ }
243
+ const data = encodeFunctionData({ abi: CREATOR_FEE_ABI, functionName: 'claimCreatorFee', args })
244
+ // --to one of the platform's modules: say what pays it out from there (and warn when its quote is another one)
245
+ const toType = same(to, me) ? null : await ctx.read(to, MODULE_TYPE_ABI, 'moduleType').then((t) => hexToString(t, { size: 32 }).replace(/\0+$/, '')).catch(() => null)
246
+ let toModule = { payOut: null, warning: null }
247
+ if (toType && payOutCmd(toType, to)) {
248
+ const bound = await ctx.read(to, QUOTE_ABI, 'quote').catch(() => null)
249
+ const sym = (a) => (a && !/^0x0{40}$/.test(a) ? ctx.read(a, SYMBOL_ABI, 'symbol').catch(() => null) : null)
250
+ const [quoteSymbol, boundSymbol] = await Promise.all([sym(quote), sym(bound)])
251
+ toModule = claimToModule({ moduleType: toType, at: to, net, bound, quote, quoteSymbol, boundSymbol })
252
+ }
253
+ const { payOut, warning } = toModule
254
+ return out(step(ctx, { from: me, to: ctx.pad, data }, {
255
+ step: 'claim-creator-fee', chainId, token, symbol, padGen: view.padGen, amount: view.creatorFee.claimable,
256
+ to, ...(!same(to, me) && { toNote: `the fee goes to --to, not to this wallet${payOut ? `: --to is a module (${toType}); ${warning ? `${warning}. ` : ''}${payOut}` : ''}` }),
257
+ ...(warning && { warning }),
258
+ note: 'claims all of it; the fee keeps growing with later curve trades and can be claimed again',
259
+ }, rawOnly, summarize))
260
+ }
261
+
package/src/discover.js CHANGED
@@ -89,6 +89,8 @@ function gangRow(r, quoteUsdOf) {
89
89
  taxed: fair || num(r.buyTaxBps) > 0 || num(r.sellTaxBps) > 0,
90
90
  graduated, pair: r.pair || null,
91
91
  progressPct: num(r.progressPct), raised, graduationTarget: target, remaining,
92
+ // a V3 curve's target in BNB raised (2.0: the creator's pick) when gang.fun sends it; graduationTarget is it in the quote
93
+ ...(r.track === 'v3' && r.gradTargetBnb != null && { graduationTargetBnb: num(r.gradTargetBnb) }),
92
94
  remainingUsd: quoteUsd ? usd(remaining * quoteUsd) : null,
93
95
  priceUsd: r.priceUsd ?? (quoteUsd ? num(r.priceQuote) * quoteUsd : null), fdvUsd: inUsd('fdvUsd', 'fdvQuote'),
94
96
  volume24hUsd: inUsd('volume24hUsd', 'volume24hQuote'), trades24h: num(r.trades24h), trades: num(r.trades),
package/src/fair.js CHANGED
@@ -3,9 +3,9 @@ import { bawAddress } from './baw.js'
3
3
  import { defaultRefPool, dividendOf, fundingStep as fund, parseAmount, parseIntIn, parseNum, poolSellQuote, POOL_SELL_HINT, revertOf as revertIn, ROUTER_ABI, ROUTER_HINTS, routerDeadline, step, swapBackState, units, viaRouter, GAS_RESERVE } from './steps.js'
4
4
  import { API } from './discover.js'
5
5
  import { UA } from './version.js'
6
- import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets, rpcTransport } from './gangpad.js'
6
+ import { atTokenPad, KIND_UNREAD, MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets, rpcTransport } from './gangpad.js'
7
7
  import { poolPayBnb, poolTrade } from './pool.js'
8
- import { bondAddress, bondGuard } from './bond.js'
8
+ import { bondGuard } from './bond.js'
9
9
 
10
10
  /**
11
11
  * `gang fair …` — 打新 (fair mint): one fixed price per share both ways (mint buys at it, withdraw sells back at it);
@@ -259,6 +259,8 @@ export async function runFair(sub, { opt, flag, out, fail, summarize, resolveLog
259
259
 
260
260
  let ctx
261
261
  try { ctx = fairCtx(testnet) } catch (e) { return fail(e.message) }
262
+ // a token is served by the GangLaunchpad generation that has it (its pad, router, GangBond); a create goes to the newest
263
+ if (sub !== 'create' && sub !== 'tx' && (await atTokenPad(ctx, opt('token'))) === null) return fail(KIND_UNREAD.error, { token: opt('token'), retry: KIND_UNREAD.retry })
262
264
  // not a sale on this pad: on the merged pad it may be a V3 token (kindOf), so point at `gang v3`
263
265
  const notFair = async (token) => {
264
266
  const { error, kind } = await notThisKind(ctx, token, 'fair', testnet ? ' --testnet' : '')
@@ -275,7 +277,7 @@ export async function runFair(sub, { opt, flag, out, fail, summarize, resolveLog
275
277
  const swapBack = sale.launched && sale.pair
276
278
  ? await swapBackState(ctx, await ctx.read(ctx.pad, PAD_ABI, 'taxHandler'), token, (await poolReserves(ctx, token, sale.pair))[0])
277
279
  : null
278
- return out({ success: true, chainId: Number(ctx.chainId), ...pub, ...(swapBack && { swapBack }) })
280
+ return out({ success: true, chainId: Number(ctx.chainId), ...pub, ...(ctx.gen && { padGen: ctx.gen }), ...(swapBack && { swapBack }) })
279
281
  }
280
282
  const slippage = parseNum(fail, 'slippage', opt('slippage', '1'), 0, 50)
281
283
  const me = walletFor(ctx, opt('from'))
@@ -288,6 +290,7 @@ export async function runFair(sub, { opt, flag, out, fail, summarize, resolveLog
288
290
  checkMeta() // a bad --website / --twitter / --description fails here, before any wrap / approve round or upload
289
291
  const raise = parseNum(fail, 'raise', opt('raise', '15'), 5, 50)
290
292
  if (flag('hours')) fail('--hours was removed: a fair-mint sale has no deadline and stays open until it fills')
293
+ if (flag('grad')) fail('--grad is a V3 curve setting (the graduation target, 2.0): a 打新 sale fills at its --raise instead, so leave --grad out')
291
294
  const capPct = parseNum(fail, 'cap', opt('cap', '0.5'), 0.25, 1)
292
295
  const holdPct = parseNum(fail, 'hold', opt('hold', '60'), 60, 90)
293
296
  const mintFeePct = parseNum(fail, 'mint-fee', opt('mint-fee', '1'), 1, 3)
@@ -395,7 +398,7 @@ export async function runFair(sub, { opt, flag, out, fail, summarize, resolveLog
395
398
  if (!held) return fail('this wallet has no shares in this sale')
396
399
  const shares = flag('all') ? Number(held) : parseIntIn(fail, 'shares', opt('shares'), 1, Number(held))
397
400
  // a bond posted during the sale already binds: selling shares back takes their tokens out of the creator's wallet
398
- const guard = bondAddress(testnet) && await bondGuard(ctx, {
401
+ const guard = ctx.bond && await bondGuard(ctx, {
399
402
  token, me, amount: BigInt(shares) * (await ctx.read(ctx.pad, PAD_ABI, 'TOKENS_PER_SHARE')), testnet, breakBond: flag('break-bond'), settleFirst: flag('settle-first'),
400
403
  }, rawOnly, summarize)
401
404
  if (guard?.refuse) return out({ success: false, step: 'withdraw', wallet: me, ...guard.refuse })
package/src/fly.js CHANGED
@@ -192,8 +192,10 @@ export function flyCtx(testnet) {
192
192
  { address: env('FLY_PAD') || fly.v1, version: 1 },
193
193
  ].filter((p) => p.address)
194
194
  const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
195
+ // pool trades go through the GangRouter they were accepted with (1.0's), whatever generation GangLaunchpad creates on
196
+ const router = (net.gens.find((g) => g.gen === '1.0') ?? net).router
195
197
  return {
196
- ...net, pads, pad: pads[0].address, version: pads[0].version, startBlock: fly.startBlock, client,
198
+ ...net, router, pads, pad: pads[0].address, version: pads[0].version, startBlock: fly.startBlock, client,
197
199
  read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }),
198
200
  }
199
201
  }
@@ -694,6 +696,7 @@ export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo
694
696
  if (!name || !symbol) fail('--name and --symbol are required')
695
697
  checkMeta()
696
698
  if (!(await padOpen(ctx))) fail(closed(ctx, testnet), { pad: ctx.pad, padVersion: ctx.version })
699
+ if (flag('grad')) fail('--grad is a V3 curve setting (the graduation target, 2.0): a 铸币飞轮 sale fills at its --raise instead, so leave --grad out')
697
700
  const presetName = opt('preset', 'j')
698
701
  const preset = FLY_PRESETS[presetName]
699
702
  if (!preset) fail(`--preset must be ${Object.keys(FLY_PRESETS).join(' or ')}`, { got: presetName })