@gangfun/cli 0.19.1 → 0.21.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/lp.js ADDED
@@ -0,0 +1,305 @@
1
+ import { createPublicClient, parseAbi, encodeFunctionData, formatUnits, hexToString, isAddress, maxUint128, zeroAddress } from 'viem'
2
+ import { padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
3
+ import { walletFor } from './fair.js'
4
+ import { parseNum, revertOf as revertIn, step } from './steps.js'
5
+
6
+ /**
7
+ * `gang lp …` and `gang create … --lp <pct> [--lp-to <addr>]` — GangLiquiditySplitter (dev 税按比例自动加池子,
8
+ * `lp-burn-v1`): a V3 token's tax recipient that splits each payment between liquidity added to the token's PancakeSwap
9
+ * pair, its LP sent to 0xdead (locked for good, like the graduation LP), and the dev's payee (the dev unless it names
10
+ * another address; `gang lp set-payee`). The buy-back splitter's sibling (GangBuybackSplitter v4): the same split, ratio
11
+ * rules, payee and pace; only the chunk differs. GangLiquiditySplitterFactory clones one per token for the dev
12
+ * (`create(bps, salt, payee)`, at `predict(dev, salt)`) and has GangHandlerAdmin list it, so the dev names it as the
13
+ * recipient at create (launch.js does the three steps: clone → create → bind, as for --buyback).
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
+ * lapses). The keeper adds liquidity in chunks (`work`: one per 4 minutes, ≤ 0.5% of the pair's quote reserve, none
16
+ * while the price is > 2% above the pair's 10-minute average): half buys the token, all of it goes back into the pair
17
+ * with the matching quote, and the pair mints the LP to 0xdead. Both pool taxes apply, so part of the other half stays
18
+ * for the next chunk.
19
+ * Gas: a chunk takes ~0.53–0.75M (the deposit lets the tax handler sell a chunk of its tax first). The CLI never sets a
20
+ * gas limit: the wallet / node estimates it; a fixed or trimmed limit can revert.
21
+ * Env: GANG_LP_FACTORY / GANG_TESTNET_LP_FACTORY override the built-in factory addresses.
22
+ */
23
+
24
+ // BSC 56: deployed 2026-10-31, allowed on GangHandlerAdmin by the platform's Safe the same day
25
+ export const MAINNET_LP_FACTORY = '0xE0436867dAFcf42Ee1418083251a9B8B61F0C248'
26
+ // BSC 97, set 10 (docs/TESTNET-LP-MODULE-2026-10-30.md)
27
+ export const TESTNET_LP_FACTORY = '0xA729C60FCa0Bd0D28a55E22126D3fE412AA41591'
28
+ export const LP_TYPE = 'lp-burn-v1'
29
+ const BPS = 10_000n
30
+ const CHUNK_GAP_S = 4 * 60
31
+
32
+ const ERRORS = [
33
+ 'error ZeroAddress()', 'error NotClone()', 'error NotFactory()', 'error AlreadyInitialized()', 'error BadBps()',
34
+ 'error NotDev()', 'error AlreadyBound()', 'error NotBound()', 'error NotCurve()', 'error NotCreator()',
35
+ 'error NotRecipient()', 'error NoProposal()', 'error NotDue()', 'error CutLapsed()', 'error NothingOwed()',
36
+ 'error NothingToAdd()', 'error AddTooSoon()', 'error NotTradable()', 'error Slippage()', 'error NotSweepable()',
37
+ 'error BadPayee()',
38
+ ]
39
+
40
+ export const LP_FACTORY_ABI = parseAbi([
41
+ 'function create(uint16 lpBps, bytes32 salt, address payee) returns (address splitter)',
42
+ 'function predict(address dev, bytes32 salt) view returns (address)',
43
+ 'function pad() view returns (address)',
44
+ 'error NotAgent()', 'error WrongHandler()',
45
+ 'event Created(address indexed dev, address indexed splitter, uint16 lpBps, address payee)',
46
+ ...ERRORS,
47
+ ])
48
+
49
+ export const LP_ABI = parseAbi([
50
+ 'function moduleType() view returns (bytes32)',
51
+ 'function dev() view returns (address)',
52
+ 'function payee() view returns (address)',
53
+ 'function token() view returns (address)',
54
+ 'function quote() view returns (address)',
55
+ 'function lpBps() view returns (uint16)',
56
+ 'function pendingCut() view returns (bool live, uint16 bps, uint64 at)',
57
+ 'function lpLeft() view returns (uint256)',
58
+ 'function unsplit() view returns (uint256)',
59
+ 'function devOwed() view returns (uint256)',
60
+ 'function lastAddAt() view returns (uint64)',
61
+ 'function previewAdd() view returns (bool ready, uint256 chunk, uint256 tokensOut)',
62
+ 'function previewWork() view returns (bool due, uint256 minOut)',
63
+ 'function bind(address token)',
64
+ 'function setLpBps(uint16 newBps)',
65
+ 'function applyLpBps()',
66
+ 'function setPayee(address newPayee)',
67
+ 'function split()',
68
+ 'function releaseDev() returns (uint256)',
69
+ 'function addChunk(uint256 minTokensOut) returns (uint256 quoteIn, uint256 tokensIn, uint256 liquidity)',
70
+ 'function work(uint256 minOut)',
71
+ 'function sweep(address asset)',
72
+ 'event Bound(address indexed token, address indexed quote)',
73
+ 'event Split(uint256 incoming, uint256 toLp, uint256 toDev)',
74
+ 'event DevOwed(uint256 amount)',
75
+ 'event DevReleased(uint256 amount)',
76
+ 'event Shortfall(uint256 amount)',
77
+ 'event LpBpsSet(uint16 oldBps, uint16 newBps)',
78
+ 'event LpBpsProposed(uint16 newBps, uint64 at)',
79
+ 'event LpBpsProposalCancelled(uint16 newBps)',
80
+ 'event LiquidityAdded(uint256 quoteIn, uint256 tokensIn, uint256 liquidity, uint256 left)',
81
+ 'event Swept(address indexed asset, uint256 amount)',
82
+ 'event PayeeSet(address indexed oldPayee, address indexed newPayee)',
83
+ ...ERRORS,
84
+ ])
85
+ /** gang tx decodes these (the factory's Created and the splitter's events). */
86
+ export const LP_EVENT_ABIS = [LP_FACTORY_ABI, LP_ABI]
87
+
88
+ const ERC20_ABI = parseAbi(['function symbol() view returns (string)'])
89
+ const PAD_ABI = parseAbi([
90
+ 'function taxConfigOf(address token) view returns (uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address recipient)',
91
+ '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)',
92
+ ])
93
+
94
+ export const LP_GAS_NOTE = 'let the wallet estimate the gas limit and do not set or trim it: a chunk takes about 0.53–0.75M gas (the deposit lets the tax handler sell a chunk of its tax first); too low a limit reverts'
95
+
96
+ export const HINTS = {
97
+ NotAgent: 'only an Agent can create a V3 token, so only an Agent gets an LP splitter',
98
+ NotFactory: 'this LP factory is not allowed on the platform\'s GangHandlerAdmin: it cannot list an LP splitter as a tax recipient. If GANG_LP_FACTORY / GANG_TESTNET_LP_FACTORY is set, unset it to use the built-in factory; otherwise launch without --lp',
99
+ BadBps: 'the LP share is 0–100%',
100
+ BadPayee: 'the payee cannot be the LP splitter itself',
101
+ ZeroAddress: 'the zero address cannot be the payee',
102
+ NotDev: 'only the dev this LP splitter was made for can change its ratio or payee',
103
+ NotCreator: 'the token was not created by this LP splitter\'s dev',
104
+ NotRecipient: 'the token does not pay its tax to this LP splitter',
105
+ NotCurve: 'not a V3 (curve) token on this pad',
106
+ AlreadyBound: 'the LP splitter is bound to a token already',
107
+ NotBound: 'the LP splitter is not bound to a token yet (gang lp bind --token <the token>)',
108
+ NotDue: 'the 3-day notice of this cut has not run yet',
109
+ CutLapsed: 'the cut was not applied within 7 days after its notice and has lapsed: ask for it again',
110
+ NoProposal: 'no cut asked for',
111
+ NothingOwed: 'nothing is owed to the payee',
112
+ NothingToAdd: 'no quote is set aside for the pool yet (lpLeft 0): it fills as the tax arrives',
113
+ AddTooSoon: 'one chunk per 4 minutes: wait until 4 minutes after the last one (lastAddAt)',
114
+ NotTradable: 'the token has not graduated: chunks start once it trades in its PancakeSwap pair',
115
+ Slippage: 'the pool price moved since the preview (fewer tokens than the minimum): run gang lp add again',
116
+ }
117
+ export const revertOf = (e) => revertIn(e, [LP_ABI, LP_FACTORY_ABI], HINTS)
118
+
119
+ /** Dry-run a call; { failed } with the revert when it would not pass. */
120
+ export async function simulateLp(client, from, address, abi, functionName, args = []) {
121
+ try {
122
+ const { result } = await client.simulateContract({ account: from, address, abi, functionName, args })
123
+ return { result }
124
+ } catch (e) {
125
+ const r = revertOf(e)
126
+ return { failed: r ? { reverted: true, ...r } : { reverted: false, error: e.shortMessage || e.message.split('\n')[0] } }
127
+ }
128
+ }
129
+
130
+ export function lpFactoryAddress(testnet) {
131
+ return (testnet ? process.env.GANG_TESTNET_LP_FACTORY || TESTNET_LP_FACTORY
132
+ : process.env.GANG_LP_FACTORY || MAINNET_LP_FACTORY) || null
133
+ }
134
+
135
+ export const lpNotDeployed = (testnet) =>
136
+ `GangLiquiditySplitterFactory is not deployed on ${testnet ? 'the BSC testnet' : 'BSC mainnet'} in this CLI version: set ${testnet ? 'GANG_TESTNET_LP_FACTORY' : 'GANG_LP_FACTORY'} to its address`
137
+
138
+ /** --lp <pct> / --pct (0–100, the share of the recipient's part added to the pool) in bps. */
139
+ export const lpBpsOf = (fail, raw, name = 'lp') => Math.round(parseNum(fail, name, raw, 0, 100) * 100)
140
+
141
+ const pct = (bps) => Number(bps) / 100
142
+ const iso = (s) => (Number(s) > 0 ? new Date(Number(s) * 1000).toISOString() : null)
143
+ // the pad takes 18-decimal quotes only
144
+ const q = (x) => formatUnits(x, 18)
145
+
146
+ /**
147
+ * The splitter's state for printing, from the raw reads (pure: unit-tested). `raw`: { splitter, dev, payee, token, quote,
148
+ * bps, cut: [live, bps, at], left, unsplit, owed, lastAddAt, preview: [ready, chunk, tokensOut] | null,
149
+ * work: [due, minOut] | null, graduated: bool | null, quoteSymbol, now (unix s) }.
150
+ */
151
+ export function formatLp(raw) {
152
+ const token = raw.token && raw.token !== zeroAddress ? raw.token : null
153
+ const quote = token && raw.quote && raw.quote !== zeroAddress ? raw.quote : null
154
+ const toDev = String(raw.payee).toLowerCase() === String(raw.dev).toLowerCase()
155
+ const bps = Number(raw.bps)
156
+ const [live, cutBps, cutAt] = raw.cut ?? [false, 0, 0n]
157
+ const [ready, chunk, tokensOut] = raw.preview ?? [false, 0n, 0n]
158
+ const last = Number(raw.lastAddAt ?? 0n)
159
+ const now = Number(raw.now ?? Math.floor(Date.now() / 1000))
160
+ // what lpLeft is once the waiting quote is split (as the contract's _lpAfterSplit, without a shortfall)
161
+ const setAside = BigInt(raw.left) + (BigInt(raw.unsplit) * BigInt(bps)) / BPS
162
+ let waiting = null
163
+ if (!ready) {
164
+ waiting = !token ? 'not bound to a token yet (gang lp bind --token <the token>)'
165
+ : raw.graduated === false ? 'the token has not graduated: chunks start once it trades in its PancakeSwap pair (the pool tax starts then too)'
166
+ : setAside === 0n ? 'nothing set aside for the pool yet: it fills as the tax arrives'
167
+ : last > 0 && now < last + CHUNK_GAP_S ? `one chunk per 4 minutes: the next from ${iso(last + CHUNK_GAP_S)}`
168
+ : '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'
169
+ }
170
+ return {
171
+ splitter: raw.splitter, moduleType: LP_TYPE, dev: raw.dev, payee: raw.payee, token, quote, ...(quote && raw.quoteSymbol && { quoteSymbol: raw.quoteSymbol }),
172
+ lpPct: pct(bps), lpBps: bps,
173
+ pendingCut: live ? { toPct: pct(cutBps), appliesFrom: iso(cutAt), lapsesAfter: iso(Number(cutAt) + 7 * 86400) } : null,
174
+ lpLeft: q(raw.left), unsplit: q(raw.unsplit), devOwed: q(raw.owed),
175
+ lastAddAt: iso(last),
176
+ nextChunk: ready ? { quoteChunk: q(chunk), buyHalf: q(chunk / 2n), tokensBought: formatUnits(tokensOut, 18) } : null,
177
+ ...(waiting && { nextChunkWaitsFor: waiting }),
178
+ ...(raw.work && token && { keeper: { due: !!raw.work[0] } }),
179
+ note: `${pct(bps)}% of each tax payment to this recipient is added to the token's PancakeSwap pair as liquidity whose LP goes to 0xdead (locked for good), the rest goes to ${toDev ? 'the dev' : `the payee ${raw.payee}`}. `
180
+ + 'The keeper adds it in chunks (one per 4 minutes, at most 0.5% of the pair\'s quote reserve, none while the price is more than 2% above its 10-minute average; it waits until at least 0.05% of that reserve is set aside): half buys the token, all of it goes back into the pair with the matching quote. Both pool taxes apply, so part of each chunk\'s quote stays for the next. '
181
+ + 'A raise of the share applies at once, a cut only 3 days after it is asked for; the dev can change the payee at once (gang lp set-payee)',
182
+ }
183
+ }
184
+
185
+ /** The splitter's state when `addr` is a GangLiquiditySplitter (lp-burn-v1); null when it is not. `pad`: to read graduation. */
186
+ export async function lpOf(read, addr, { pad } = {}) {
187
+ if (!addr || addr === zeroAddress) return null
188
+ let type
189
+ try { type = await read(addr, LP_ABI, 'moduleType') } catch { return null }
190
+ if (hexToString(type, { size: 32 }).replace(/\0+$/, '') !== LP_TYPE) return null
191
+ const [dev, payee, token, quote, bps, cut, left, unsplit, owed, lastAddAt] = await Promise.all(
192
+ ['dev', 'payee', 'token', 'quote', 'lpBps', 'pendingCut', 'lpLeft', 'unsplit', 'devOwed', 'lastAddAt'].map((f) => read(addr, LP_ABI, f)))
193
+ const bound = token !== zeroAddress
194
+ const [preview, work, graduated, quoteSymbol] = await Promise.all([
195
+ bound ? read(addr, LP_ABI, 'previewAdd').catch(() => null) : null,
196
+ bound ? read(addr, LP_ABI, 'previewWork').catch(() => null) : null,
197
+ bound && pad ? read(pad, PAD_ABI, 'curves', [token]).then((c) => c[6]).catch(() => null) : null,
198
+ bound ? read(quote, ERC20_ABI, 'symbol').catch(() => null) : null,
199
+ ])
200
+ return formatLp({ splitter: addr, dev, payee, token, quote, bps, cut, left, unsplit, owed, lastAddAt, preview, work, graduated, quoteSymbol })
201
+ }
202
+
203
+ function lpCtx(testnet) {
204
+ const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
205
+ if (!net.pad) throw new Error(NOT_ON_MAINNET)
206
+ const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
207
+ return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
208
+ }
209
+
210
+ const SUBS = ['status', 'set', 'set-payee', 'apply', 'bind', 'release', 'add']
211
+ const USAGE = 'usage: gang lp <status|set|set-payee|apply|bind|release|add> --token <addr> [--pct <0-100>] [--to <addr>] [--slippage 1] [--testnet] — see gang help'
212
+
213
+ /** `gang lp <sub>`: the LP splitter of a V3 token (its tax recipient), found from --token. */
214
+ export async function runLp(sub, { opt, flag, out, fail, summarize }) {
215
+ if (!SUBS.includes(sub)) return fail(USAGE, { got: sub ?? null })
216
+ const testnet = flag('testnet')
217
+ const rawOnly = flag('calldata')
218
+ let ctx
219
+ try { ctx = lpCtx(testnet) } catch (e) { return fail(e.message) }
220
+ const token = opt('token')
221
+ if (!isAddress(token ?? '')) fail('--token must be a V3 token address (0x…)', { got: token ?? null })
222
+ const chainId = Number(ctx.chainId)
223
+ let recipient
224
+ try { recipient = (await ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token]))[3] } catch {
225
+ return fail(`not a V3 token on this pad (${testnet ? 'BSC testnet' : 'BSC mainnet; add --testnet for a testnet token'})`, { token, chainId })
226
+ }
227
+ const s = await lpOf(ctx.read, recipient, { pad: ctx.pad })
228
+ if (!s) return fail('this token\'s tax recipient is not an LP splitter (lp-burn-v1)', { token, recipient: recipient === zeroAddress ? null : recipient })
229
+ const tn = testnet ? ' --testnet' : ''
230
+ // the token pays this splitter, which is bound to another token: it adds liquidity only to that one's pair
231
+ const warning = s.token && s.token.toLowerCase() !== token.toLowerCase()
232
+ ? `this token pays its tax to the LP splitter, but it is bound to another token (${s.token}): the liquidity goes to that token's pair` : null
233
+ const me = () => walletFor(ctx, opt('from'))
234
+ const send = async (functionName, args, extra) => {
235
+ const sim = await simulateLp(ctx.client, me(), s.splitter, LP_ABI, functionName, args)
236
+ if (sim.failed) return out({ success: false, step: extra.step, ...sim.failed })
237
+ const data = encodeFunctionData({ abi: LP_ABI, functionName, args })
238
+ // no gas field: the wallet / node estimates it (LP_GAS_NOTE)
239
+ return out(step(ctx, { from: me(), to: s.splitter, data }, { chainId, token, splitter: s.splitter, ...extra }, rawOnly, summarize))
240
+ }
241
+
242
+ if (sub === 'status') return out({ success: true, chainId, ...s, ...(s.token === null && { bound: false }), ...(warning && { warning }) })
243
+
244
+ if (sub === 'bind') {
245
+ if (s.token) return fail('already bound', { boundTo: s.token, ...(warning && { warning }) })
246
+ return send('bind', [token], { step: 'bind', note: 'anyone may bind (once); the token must be the dev\'s and pay its tax to this splitter. Its pair is where the liquidity goes' })
247
+ }
248
+
249
+ if (sub === 'set') {
250
+ if (me().toLowerCase() !== s.dev.toLowerCase()) return fail(HINTS.NotDev, { wallet: me(), dev: s.dev })
251
+ if (!flag('pct')) fail('--pct <0-100> required: the new LP share')
252
+ const bps = lpBpsOf(fail, opt('pct'), 'pct')
253
+ return send('setLpBps', [bps], bps >= s.lpBps
254
+ ? { step: 'set-lp', fromPct: s.lpPct, toPct: bps / 100, note: `applies at once (quote that arrived before is split at the old share first)${s.pendingCut ? ' and cancels the pending cut' : ''}` }
255
+ : {
256
+ step: 'ask-cut', fromPct: s.lpPct, toPct: bps / 100, appliesFromAbout: new Date(Date.now() + 3 * 86400_000).toISOString(),
257
+ note: `a cut waits 3 days (holders see it coming), then anyone runs gang lp apply --token ${token}${tn} within 7 days or it lapses${s.pendingCut ? '; this replaces the cut already asked for' : ''}`,
258
+ })
259
+ }
260
+
261
+ if (sub === 'set-payee') {
262
+ if (me().toLowerCase() !== s.dev.toLowerCase()) return fail('only the dev this LP splitter was made for can change its payee', { wallet: me(), dev: s.dev })
263
+ const to = opt('to')
264
+ if (!isAddress(to ?? '') || to === zeroAddress) fail('--to <0x…> required (checksummed or all lowercase): the address the dev\'s part goes to from now on', { got: to ?? null })
265
+ if (to.toLowerCase() === s.splitter.toLowerCase()) return fail(HINTS.BadPayee, { to })
266
+ if (to.toLowerCase() === s.payee.toLowerCase()) return fail('that is the payee already', { payee: s.payee })
267
+ return send('setPayee', [to], {
268
+ step: 'set-payee', fromPayee: s.payee, toPayee: to,
269
+ note: 'applies at once (the dev\'s own share; holders are not affected). Quote that arrived before is split to the current payee first; what is owed goes to the new one',
270
+ })
271
+ }
272
+
273
+ if (sub === 'apply') {
274
+ if (!s.pendingCut) return fail(HINTS.NoProposal, { lpPct: s.lpPct })
275
+ if (Date.parse(s.pendingCut.appliesFrom) > Date.now()) return fail(HINTS.NotDue, { appliesFrom: s.pendingCut.appliesFrom })
276
+ return send('applyLpBps', [], { step: 'apply-cut', fromPct: s.lpPct, toPct: s.pendingCut.toPct, note: 'anyone may apply a cut once its notice ran' })
277
+ }
278
+
279
+ if (sub === 'release') {
280
+ if (!(Number(s.devOwed) > 0)) return fail(HINTS.NothingOwed)
281
+ return send('releaseDev', [], { step: 'release', amount: s.devOwed, payee: s.payee, note: 'anyone may; the payee gets what a failed push left owed' })
282
+ }
283
+
284
+ // add: one chunk by hand (anyone), as the keeper's work does
285
+ if (!s.token) return fail(HINTS.NotBound, { splitter: s.splitter })
286
+ const slippage = parseNum(fail, 'slippage', opt('slippage', '1'), 0, 50)
287
+ const [ready, chunk, tokensOut] = await ctx.read(s.splitter, LP_ABI, 'previewAdd')
288
+ if (ready) {
289
+ // previewAdd prices the buy half after the buy tax; the contract scales the minimum down when the pair got less
290
+ const minOut = (tokensOut * BigInt(Math.round((100 - slippage) * 100))) / BPS
291
+ return send('addChunk', [minOut], {
292
+ step: 'add', quoteChunk: q(chunk), buyHalf: q(chunk / 2n), expectTokensBought: formatUnits(tokensOut, 18),
293
+ minTokensBought: formatUnits(minOut, 18), slippagePct: slippage, lpLeft: s.lpLeft,
294
+ note: `anyone may: splits what arrived, then half of the chunk buys the token, all of it goes back into the pair with the matching quote, and the pair mints the LP to 0xdead (gang tx shows LiquidityAdded). The keeper does the same every few minutes. Gas: ${LP_GAS_NOTE}`,
295
+ })
296
+ }
297
+ // not ready: only a call that records the price observation can pass; a minimum no chunk can meet makes it revert
298
+ // (Slippage) rather than buy unchecked if a chunk became possible before it lands
299
+ const sim = await simulateLp(ctx.client, me(), s.splitter, LP_ABI, 'addChunk', [maxUint128])
300
+ if (sim.failed) return out({ success: false, step: 'add', ...sim.failed, ...(s.nextChunkWaitsFor && { waitsFor: s.nextChunkWaitsFor }), lpLeft: s.lpLeft })
301
+ return send('addChunk', [maxUint128], {
302
+ step: 'record-price', addsLiquidity: false, waitsFor: s.nextChunkWaitsFor,
303
+ note: 'no chunk this time: the call only records the pair\'s price observation (or waits for the 10-minute average / a price no more than 2% above it). It is cheap; the keeper calls it too. If a chunk becomes possible before it lands, it reverts (Slippage) rather than add without a minimum: run gang lp add again then, about 10 minutes after the first observation',
304
+ })
305
+ }
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, split, 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, lp, 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 / --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.',
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 / --lp, 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, split, 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, lp, 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 / --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.',
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 / --lp), 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, lp status|set|set-payee|apply|bind|release|add, 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/v3.js CHANGED
@@ -8,6 +8,7 @@ import { poolPayBnb, poolTrade } from './pool.js'
8
8
  import { bondGuard } from './bond.js'
9
9
  import { splitterOf } from './buyback.js'
10
10
  import { splitOf } from './split.js'
11
+ import { lpOf } from './lp.js'
11
12
 
12
13
  /**
13
14
  * `gang v3 …` — LaunchpadV3 (tax recipient): a token with its own buy / sell tax (1–5% each), a dividend share and a
@@ -282,11 +283,15 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
282
283
  // or the dev's split module (split-v1): its fixed payees and shares, what waits to be split
283
284
  const split = c.recipient && !c.recipientIsCreator && !buyback
284
285
  ? await splitOf(ctx.read, c.recipient, { wbnb: ctx.wbnb, extraAssets: [c.quote], ref: `--token ${token}${net}` }) : null
286
+ // or the dev's LP splitter (lp-burn-v1): its ratio, what is set aside for the pool, the next chunk
287
+ const lp = c.recipient && !c.recipientIsCreator && !buyback && !split ? await lpOf(ctx.read, c.recipient, { pad: ctx.pad }) : null
288
+ const lpWarn = lp && lp.token && lp.token.toLowerCase() !== token.toLowerCase()
289
+ ? { warning: `this token pays its tax to the LP splitter, but it is bound to another token (${lp.token}): the liquidity goes to that token's pair` } : null
285
290
  const splitWarn = split && split.token && split.token.toLowerCase() !== token.toLowerCase()
286
291
  ? { 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
292
  return out({
288
293
  success: true, chainId: Number(ctx.chainId), ...fees, ...pub, taxNote, ...(swapBack && { swapBack }), ...(buyback && { buyback }),
289
- ...(split && { split: { ...split, ...splitWarn } }),
294
+ ...(split && { split: { ...split, ...splitWarn } }), ...(lp && { lp: { ...lp, ...lpWarn } }),
290
295
  })
291
296
  }
292
297